You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1043 lines
41 KiB

  1. #!/bin/sh /etc/rc.common
  2. # Copyright 2017-2020 Stan Grishin (stangri@melmac.net)
  3. # shellcheck disable=SC2039,SC1091,SC2018,SC2019
  4. PKG_VERSION='dev-test'
  5. export START=94
  6. export USE_PROCD=1
  7. readonly _OK_='\033[0;32m\xe2\x9c\x93\033[0m'
  8. readonly _FAIL_='\033[0;31m\xe2\x9c\x97\033[0m'
  9. readonly __OK__='\033[0;32m[\xe2\x9c\x93]\033[0m'
  10. readonly __FAIL__='\033[0;31m[\xe2\x9c\x97]\033[0m'
  11. readonly __PASS__='\033[0;33m[-]\033[0m'
  12. readonly _ERROR_='\033[0;31mERROR\033[0m'
  13. readonly _WARNING_='\033[0;33mWARNING\033[0m'
  14. readonly readmeURL="https://github.com/openwrt/packages/tree/master/net/vpn-policy-routing/files/README.md"
  15. extra_command "support" "Generates output required to troubleshoot routing issues
  16. Use '-d' option for more detailed output
  17. Use '-p' option to automatically upload data under VPR paste.ee account
  18. WARNING: while paste.ee uploads are unlisted, they are still publicly available
  19. List domain names after options to include their lookup in report"
  20. readonly packageName='vpn-policy-routing'
  21. readonly serviceName="$packageName $PKG_VERSION"
  22. readonly PID="/var/run/${packageName}.pid"
  23. readonly dnsmasqFile="/var/dnsmasq.d/${packageName}"
  24. readonly userFile="/etc/${packageName}.user"
  25. readonly sharedMemoryOutput="/dev/shm/$packageName-output"
  26. create_lock() { [ -e "$PID" ] && return 1; touch "$PID"; }
  27. remove_lock() { [ -e "$PID" ] && rm -f "$PID"; }
  28. trap remove_lock EXIT
  29. output_ok() { output 1 "$_OK_"; output 2 "$__OK__\\n"; }
  30. output_okn() { output 1 "$_OK_\\n"; output 2 "$__OK__\\n"; }
  31. output_fail() { s=1; output 1 "$_FAIL_"; output 2 "$__FAIL__\\n"; }
  32. output_failn() { output 1 "$_FAIL_\\n"; output 2 "$__FAIL__\\n"; }
  33. # str_replace() { printf "%b" "$1" | sed -e "s/$(printf "%b" "$2")/$(printf "%b" "$3")/g"; }
  34. # str_contains() { [ "$1" != "$(str_replace "$1" "$2" "")" ]; }
  35. # shellcheck disable=SC2018,SC2019
  36. str_to_lower() { echo "$1" | tr 'A-Z' 'a-z'; }
  37. str_extras_to_underscore() { echo "$1" | tr '[\. ~`!@#$%^&*()\+/,<>?//;:]' '_'; }
  38. str_extras_to_space() { echo "$1" | tr ';{}' ' '; }
  39. output() {
  40. # Can take a single parameter (text) to be output at any verbosity
  41. # Or target verbosity level and text to be output at specifc verbosity
  42. local msg memmsg logmsg
  43. if [ $# -ne 1 ]; then
  44. if [ $((verbosity & $1)) -gt 0 ] || [ "$verbosity" = "$1" ]; then shift; else return 0; fi
  45. fi
  46. [ -t 1 ] && printf "%b" "$1"
  47. msg="${1//$serviceName /service }";
  48. if [ "$(printf "%b" "$msg" | wc -l)" -gt 0 ]; then
  49. [ -s "$sharedMemoryOutput" ] && memmsg="$(cat "$sharedMemoryOutput")"
  50. logmsg="$(printf "%b" "${memmsg}${msg}" | sed 's/\x1b\[[0-9;]*m//g')"
  51. logger -t "${packageName:-service} [$$]" "$(printf "%b" "$logmsg")"
  52. rm -f "$sharedMemoryOutput"
  53. else
  54. printf "%b" "$msg" >> "$sharedMemoryOutput"
  55. fi
  56. }
  57. is_installed() { [ -s "/usr/lib/opkg/info/${1}.control" ]; }
  58. export serviceEnabled verbosity strictMode wanTableID wanMark fwMask
  59. export ipv6Enabled localIpset remoteIpset ipruleEnabled icmpIface
  60. export ignoredIfaces="" supportedIfaces=""
  61. export appendLocalPolicy="" appendRemotePolicy=""
  62. export wanIface4 wanIface6 ifaceMark ifaceTableID ifAll ifSupported wanGW4 wanGW6
  63. export bootTimeout insertOption
  64. list_iface() { ifAll="${ifAll}${1} "; }
  65. list_supported_iface() { is_supported_interface "$1" && ifSupported="${ifSupported}${1} "; }
  66. vpr_find_true() {
  67. local iface i param="$2"
  68. [ "$param" = 'wan6' ] || param='wan'
  69. "network_find_${param}" iface
  70. is_tunnel "$iface" && unset iface
  71. if [ -z "$iface" ]; then
  72. unset ifAll; config_load 'network';
  73. config_foreach list_iface 'interface'
  74. for i in $ifAll; do
  75. if "is_${param}" "$i"; then break; else unset i; fi
  76. done
  77. fi
  78. export "$1=${iface:-$i}"
  79. }
  80. vpr_get_gateway() {
  81. local iface="$2" dev="$3" gw
  82. network_get_gateway gw "$iface"
  83. if [ -z "$gw" ] || [ "$gw" = '0.0.0.0' ]; then
  84. gw="$(ip -4 a list dev "$dev" 2>/dev/null | grep inet | awk '{print $2}' | awk -F "/" '{print $1}')"
  85. fi
  86. export "$1=$gw"
  87. }
  88. vpr_get_gateway6() {
  89. local iface="$2" dev="$3" gw
  90. network_get_gateway6 gw "$iface"
  91. if [ -z "$gw" ] || [ "$gw" = '::/0' ] || [ "$gw" = '::0/0' ] || [ "$gw" = '::' ]; then
  92. gw="$(ip -6 a list dev "$dev" 2>/dev/null | grep inet6 | awk '{print $2}')"
  93. fi
  94. export "$1=$gw"
  95. }
  96. is_l2tp() { local proto; proto=$(uci -q get network."$1".proto); [ "${proto:0:4}" = "l2tp" ]; }
  97. is_oc() { local proto; proto=$(uci -q get network."$1".proto); [ "${proto:0:11}" = "openconnect" ]; }
  98. is_ovpn() { local dev; dev=$(uci -q get network."$1".ifname); [ "${dev:0:3}" = "tun" ] || [ "${dev:0:3}" = "tap" ] || [ -f "/sys/devices/virtual/net/${dev}/tun_flags" ]; }
  99. is_pptp() { local proto; proto=$(uci -q get network."$1".proto); [ "${proto:0:4}" = "pptp" ]; }
  100. is_tor() { local dev; dev=$(uci -q get network."$1".ifname); [ "${dev:0:3}" = "tor" ]; }
  101. is_wg() { local proto; proto=$(uci -q get network."$1".proto); [ "${proto:0:9}" = "wireguard" ]; }
  102. is_tunnel() { is_l2tp "$1" || is_oc "$1" || is_ovpn "$1" || is_pptp "$1" || is_tor "$1" || is_wg "$1"; }
  103. is_wan() { [ "$1" = "$wanIface4" ] || { [ "${1##wan}" != "$1" ] && [ "${1##wan6}" = "$1" ]; } || [ "${1%%wan}" != "$1" ]; }
  104. is_wan6() { [ -n "$wanIface6" ] && [ "$1" = "$wanIface6" ] || [ "${1/#wan6}" != "$1" ] || [ "${1/%wan6}" != "$1" ]; }
  105. string_match_word() { echo "$1" | grep -q -w "$2"; }
  106. is_ignored_interface() { string_match_word "$ignoredIfaces" "$1"; }
  107. is_supported_interface() { string_match_word "$supportedIfaces" "$1" || { ! is_ignored_interface "$1" && { is_wan "$1" || is_wan6 "$1" || is_tunnel "$1"; }; }; }
  108. is_mac_address() { expr "$1" : '[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]$' >/dev/null; }
  109. is_ipv4() { expr "$1" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null; }
  110. is_ipv6() { ! is_mac_address "$1" && [ "${1//:}" != "$1" ]; }
  111. is_ipv6_link_local() { [ "${1:0:4}" = "fe80" ]; }
  112. is_ipv6_unique_local() { [ "${1:0:2}" = "fc" ] || [ "${1:0:2}" = "fd" ]; }
  113. is_ipv6_global() { [ "${1:0:4}" = "2001" ]; }
  114. # is_ipv6_global() { is_ipv6 "$1" && ! is_ipv6_link_local "$1" && ! is_ipv6_link_local "$1"; }
  115. is_netmask() { local ip="${1%/*}"; [ "$ip" != "$1" ] && is_ipv4 "$ip"; }
  116. is_domain() { [ "${1//[a-zA-Z-]}" != "$1" ]; }
  117. is_phys_dev() { [ "${1:0:1}" = "@" ] && ip l show | grep -E -q "^\\d+\\W+${1:1}"; }
  118. is_turris() { /bin/ubus -S call system board | /bin/grep 'Turris' | /bin/grep -q '15.05'; }
  119. is_chaos_calmer() { ubus -S call system board | grep -q 'Chaos Calmer'; }
  120. dnsmasq_kill() { killall -q -HUP dnsmasq; }
  121. dnsmasq_restart() { output 1 'Restarting DNSMASQ '; if /etc/init.d/dnsmasq restart >/dev/null 2>&1; then output_okn; else output_failn; fi; }
  122. is_default_dev() { [ "$1" = "$(ip -4 r | grep -m1 'dev' | grep -Eso 'dev [^ ]*' | awk '{print $2}')" ]; }
  123. is_supported_iface_dev() {
  124. for n in $ifSupported; do
  125. if [ "$1" = "$(uci -q get "network.${n}.ifname" || echo "$n")" ] || [ "$1" = "$(uci -q get "network.${n}.proto")-${n}" ] ; then return 0; fi
  126. done
  127. return 1
  128. }
  129. is_supported_protocol () { grep -o '^[^#]*' /etc/protocols | grep -w -v '0' | grep . | awk '{print $1}' | grep -q "$1"; }
  130. load_package_config() {
  131. config_load "$packageName"
  132. config_get_bool serviceEnabled 'config' 'enabled' 0
  133. config_get_bool strictMode 'config' 'strict_enforcement' 1
  134. config_get_bool ipv6Enabled 'config' 'ipv6_enabled' 0
  135. config_get_bool localIpset 'config' 'src_ipset' 0
  136. config_get_bool ipruleEnabled 'config' 'iprule_enabled' 0
  137. config_get remoteIpset 'config' 'dest_ipset'
  138. config_get appendLocalPolicy 'config' 'append_src_rules'
  139. config_get appendRemotePolicy 'config' 'append_dest_rules'
  140. config_get verbosity 'config' 'verbosity' '2'
  141. config_get wanTableID 'config' 'wan_tid' '201'
  142. config_get wanMark 'config' 'wan_mark' '0x010000'
  143. config_get fwMask 'config' 'fw_mask' '0xff0000'
  144. config_get icmpIface 'config' 'icmp_interface'
  145. config_get ignoredIfaces 'config' 'ignored_interface'
  146. config_get supportedIfaces 'config' 'supported_interface'
  147. config_get bootTimeout 'config' 'boot_timeout' '30'
  148. config_get insertOption 'config' 'iptables_rule_option' 'append'
  149. if [ -z "${verbosity##*[!0-9]*}" ] || [ "$verbosity" -lt 0 ] || [ "$verbosity" -gt 2 ]; then
  150. verbosity=1
  151. fi
  152. . /lib/functions/network.sh
  153. . /usr/share/libubox/jshn.sh
  154. vpr_find_true wanIface4 'wan'
  155. [ "$ipv6Enabled" -ne 0 ] && vpr_find_true wanIface6 'wan6'
  156. [ -n "$wanIface4" ] && network_get_gateway wanGW4 "$wanIface4"
  157. [ -n "$wanIface6" ] && network_get_gateway6 wanGW6 "$wanIface6"
  158. wanGW="${wanGW4:-$wanGW6}"
  159. }
  160. is_enabled() {
  161. load_package_config
  162. if [ "$serviceEnabled" -eq 0 ]; then
  163. if [ "$1" = 'on_start' ]; then
  164. output "$packageName is currently disabled.\\n"
  165. output "Run the following commands before starting service again:\\n"
  166. output "uci set $packageName.config.enabled='1'; uci commit;\\n"
  167. fi
  168. return 1
  169. fi
  170. case $insertOption in
  171. insert|-i|-I) insertOption='-I';;
  172. append|-a|-A|*) insertOption='-A';;
  173. esac
  174. case $remoteIpset in
  175. ipset)
  176. if ! ipset help hash:net >/dev/null 2>&1; then
  177. output "$_ERROR_: ipset support is enabled in $packageName, but ipset is either not installed or installed ipset does not support 'hash:net' type!\\n"
  178. unset remoteIpset
  179. fi
  180. ;;
  181. dnsmasq.ipset)
  182. if dnsmasq -v 2>/dev/null | grep -q 'no-ipset' || ! dnsmasq -v 2>/dev/null | grep -q -w 'ipset'; then
  183. output "$_ERROR_: DNSMASQ ipset support is enabled in $packageName, but DNSMASQ is either not installed or installed DNSMASQ does not support ipsets!\\n"
  184. unset remoteIpset
  185. fi
  186. if ! ipset help hash:net >/dev/null 2>&1; then
  187. output "$_ERROR_: DNSMASQ ipset support is enabled in $packageName, but ipset is either not installed or installed ipset does not support 'hash:net' type!\\n"
  188. unset remoteIpset
  189. fi
  190. ;;
  191. *) unset remoteIpset;;
  192. esac
  193. if [ "$localIpset" -ne 0 ]; then
  194. if ! ipset help hash:net >/dev/null 2>&1; then
  195. output "$_ERROR_: Local ipset support is enabled in $packageName, but ipset is either not installed or installed ipset does not support 'hash:net' type!\\n"
  196. unset localIpset
  197. fi
  198. if ! ipset help hash:mac >/dev/null 2>&1; then
  199. output "$_ERROR_: Local ipset support is enabled in $packageName, but ipset is either not installed or installed ipset does not support 'hash:mac' type!\\n"
  200. unset localIpset
  201. fi
  202. fi
  203. }
  204. is_wan_up() {
  205. local sleepCount=1
  206. while [ -z "$wanGW" ] ; do
  207. vpr_find_true wanIface4 'wan'
  208. [ "$ipv6Enabled" -ne 0 ] && vpr_find_true wanIface6 'wan6'
  209. [ -n "$wanIface4" ] && network_get_gateway wanGW4 "$wanIface4"
  210. [ -n "$wanIface6" ] && network_get_gateway6 wanGW6 "$wanIface6"
  211. wanGW="${wanGW4:-$wanGW6}"
  212. if [ $((sleepCount)) -gt $((bootTimeout)) ] || [ -n "$wanGW" ]; then break; fi
  213. output "$serviceName waiting for wan gateway...\\n"; sleep 1; network_flush_cache; sleepCount=$((sleepCount+1));
  214. done
  215. mkdir -p "${PID%/*}"; mkdir -p "${dnsmasqFile%/*}";
  216. unset ifSupported
  217. config_load 'network'
  218. config_foreach list_supported_iface 'interface'
  219. if [ -n "$wanGW" ]; then
  220. return 0
  221. else
  222. output "$_ERROR_: $serviceName failed to discover WAN gateway!\\n"
  223. return 1
  224. fi
  225. }
  226. ipt_cleanup() {
  227. local i
  228. for i in PREROUTING FORWARD INPUT OUTPUT; do
  229. while iptables -t mangle -D $i -m mark --mark 0x0/0xff0000 -j VPR_${i} >/dev/null 2>&1; do : ; done
  230. done
  231. for i in PREROUTING FORWARD INPUT OUTPUT; do
  232. while iptables -t mangle -D $i -j VPR_${i} >/dev/null 2>&1; do : ; done
  233. done
  234. }
  235. # shellcheck disable=SC2086
  236. ipt() {
  237. local d failFlagIpv4=1 failFlagIpv6=1
  238. for d in "${*//-A/-D}" "${*//-I/-D}" "${*//-N/-F}" "${*//-N/-X}"; do
  239. [ "$d" != "$*" ] && { iptables $d >/dev/null 2>&1; ip6tables $d >/dev/null 2>&1; }
  240. done
  241. d="$*"; iptables $d >/dev/null 2>&1 && failFlagIpv4=0;
  242. if [ "$ipv6Enabled" -gt 0 ]; then ip6tables $d >/dev/null 2>&1 && failFlagIpv6=0; fi
  243. [ "$failFlagIpv4" -eq 0 ] || [ "$failFlagIpv6" -eq 0 ]
  244. }
  245. # shellcheck disable=SC2086
  246. ips() {
  247. local command="$1" ipset="${2//-/_}" param="$3" comment="$4" appendix failFlag=0
  248. if [ "${ipset//_ip}" != "${ipset}" ]; then
  249. ipset="${ipset//_ip}"; appendix='_ip';
  250. elif [ "${ipset//_mac}" != "${ipset}" ]; then
  251. ipset="${ipset//_mac}"; appendix='_mac';
  252. fi
  253. if [ "$command" = "add_dnsmasq" ]; then
  254. [ "$remoteIpset" != 'dnsmasq.ipset' ] && return 1
  255. # elif [ "$command" = "add_unbound" ]; then
  256. # [ "$remoteIpset" != 'unbound.ipset' ] && return 1
  257. else
  258. if [[ -z "$appendix" && -z "$remoteIpset" ]] || \
  259. [[ -n "$appendix" && "$localIpset" -eq 0 ]]; then
  260. return 1
  261. fi
  262. fi
  263. case "$command" in
  264. add_dnsmasq)
  265. echo "ipset=/${param}/${ipset} # $comment" >> "$dnsmasqFile" || failFlag=1
  266. ;;
  267. add)
  268. ipset -q -! $command "${ipset}${appendix}" $param comment "$comment" || failFlag=1
  269. ;;
  270. create)
  271. ipset -q -! "$command" "${ipset}${appendix}" $param || failFlag=1
  272. ;;
  273. destroy|flush)
  274. ipset -q -! "$command" "${ipset}${appendix}" 2>/dev/null || failFlag=1
  275. return 0
  276. ;;
  277. esac
  278. return $failFlag
  279. }
  280. ipr()
  281. {
  282. [ "$ipruleEnabled" -ne 0 ] || return 1
  283. local comment="$1" tid=$(eval echo "\$tid_${2//-/_}") laddr="$3" failFlagIpv4=0 failFlagIpv6=1
  284. ip -4 rule del from "$laddr" table "$tid" >/dev/null 2>&1
  285. ip -4 rule add from "$laddr" table "$tid" >/dev/null 2>&1 || failFlagIpv4=1
  286. if [ "$ipv6Enabled" -ne 0 ]; then
  287. ip -6 rule del from "$laddr" table "$tid" >/dev/null 2>&1
  288. ip -6 rule add from "$laddr" table "$tid" >/dev/null 2>&1 && failFlagIpv6=0
  289. fi
  290. if [ "$failFlagIpv4" -eq 0 ] || [ "$failFlagIpv6" -eq 0 ]; then return 0; else return 1; fi
  291. }
  292. insert_tor_policy() {
  293. local comment="$1" iface="$2" laddr="$3" lport="$4" raddr="$5" rport="$6" proto="$7" chain="${8:-PREROUTING}"
  294. local mark=$(eval echo "\$mark_${iface//-/_}")
  295. [ -z "$mark" ] && processPolicyError="${processPolicyError}${_ERROR_}: Unknown fw_mark for ${iface}##"
  296. param="-t mangle $insertOption VPR_${chain} -j MARK --set-xmark ${mark}/${fwMask}"
  297. [ -n "$laddr" ] && param="$param -s $laddr"
  298. [ -n "$lport" ] && param="$param -p tcp -m multiport --sport ${lport//-/:}"
  299. [ -n "$raddr" ] && param="$param -d $raddr"
  300. [ -n "$rport" ] && param="$param -p $proto -m multiport --dport ${rport//-/:}"
  301. [ -n "$comment" ] && param="$param -m comment --comment $(str_extras_to_underscore "$comment")"
  302. # Here be dragons
  303. return 0
  304. }
  305. insert_policy() {
  306. local comment="$1" iface="$2" laddr="$3" lport="$4" raddr="$5" rport="$6" proto="$(str_to_lower "$7")" chain="${8:-PREROUTING}"
  307. local mark=$(eval echo "\$mark_${iface//-/_}") param i valueNeg value
  308. if [ "$ipv6Enabled" -eq 0 ]; then
  309. is_ipv6 "$laddr" && return 0
  310. is_ipv6 "$raddr" && return 0
  311. fi
  312. if is_ipv4 "$laddr" && is_ipv6 "$raddr"; then return 0; fi
  313. if is_ipv6 "$laddr" && is_ipv4 "$raddr"; then return 0; fi
  314. if [ -z "$mark" ]; then
  315. processPolicyError="${processPolicyError}${_ERROR_}: Unknown fw_mark for ${iface}##"
  316. return 0
  317. fi
  318. if [ -z "$proto" ]; then
  319. if [ -n "$lport" ] || [ -n "$rport" ]; then
  320. proto='tcp udp'
  321. else
  322. proto='all'
  323. fi
  324. fi
  325. for i in $proto; do
  326. if [ "$i" = 'all' ]; then
  327. param="-t mangle -I VPR_${chain} -j MARK --set-xmark ${mark}/${fwMask}"
  328. elif ! is_supported_protocol "$i"; then
  329. processPolicyError="${processPolicyError}${_ERROR_}: Unknown protocol '$i' in policy '$comment'##"
  330. return 0
  331. else
  332. param="-t mangle -I VPR_${chain} -j MARK --set-xmark ${mark}/${fwMask} -p $i"
  333. fi
  334. if [ -n "$laddr" ]; then
  335. if [ "${laddr:0:1}" = "!" ]; then
  336. valueNeg='!'; value="${laddr:1}"
  337. else
  338. unset valueNeg; value="$laddr";
  339. fi
  340. if is_phys_dev "$value"; then
  341. param="$param $valueNeg -m physdev --physdev-in ${value:1}"
  342. elif is_mac_address "$value"; then
  343. param="$param -m mac $valueNeg --mac-source $value"
  344. elif [ "${appendLocalPolicy//-d}" != "$appendLocalPolicy" ] && [ -n "$raddr" ]; then
  345. param="$param $valueNeg -s $value"
  346. processPolicyError="${processPolicyError}${_ERROR_}: Cannot append '$comment' policy with '$appendLocalPolicy' as destination is already set to '$raddr'##"
  347. else
  348. param="$param $valueNeg -s $value $appendLocalPolicy"
  349. fi
  350. fi
  351. if [ -n "$lport" ]; then
  352. if [ "${lport:0:1}" = "!" ]; then
  353. valueNeg='!'; value="${lport:1}"
  354. else
  355. unset valueNeg; value="$lport";
  356. fi
  357. param="$param -m multiport $valueNeg --sport ${value//-/:}"
  358. fi
  359. if [ -n "$raddr" ]; then
  360. if [ "${raddr:0:1}" = "!" ]; then
  361. valueNeg='!'; value="${raddr:1}"
  362. else
  363. unset valueNeg; value="$raddr";
  364. fi
  365. if [ "${appendRemotePolicy//-s}" != "$appendRemotePolicy" ] && [ -n "$laddr" ]; then
  366. param="$param $valueNeg -d $value"
  367. processPolicyError="${processPolicyError}${_ERROR_}: Cannot append '$comment' policy with '$appendRemotePolicy' as source is already set to '$laddr'\\n"
  368. else
  369. param="$param $valueNeg -d $value $appendRemotePolicy"
  370. fi
  371. fi
  372. if [ -n "$rport" ]; then
  373. if [ "${rport:0:1}" = "!" ]; then
  374. valueNeg='!'; value="${rport:1}"
  375. else
  376. unset valueNeg; value="$rport";
  377. fi
  378. param="$param -m multiport $valueNeg --dport ${value//-/:}"
  379. fi
  380. [ -n "$comment" ] && param="$param -m comment --comment $(str_extras_to_underscore "$comment")"
  381. ipt "$param" || processPolicyError="${processPolicyError}${_ERROR_}: iptables $param\\n"
  382. done
  383. return 0
  384. }
  385. r_process_policy(){
  386. local comment="$1" iface="$2" laddr="$3" lport="$4" raddr="$5" rport="$6" proto="$7" chain="$8" resolved_laddr resolved_raddr i ipsFailFlag
  387. if [ "${laddr//[ ;\{\}]/}" != "$laddr" ]; then
  388. for i in $(str_extras_to_space "$laddr"); do [ -n "$i" ] && r_process_policy "$comment" "$iface" "$i" "$lport" "$raddr" "$rport" "$proto" "$chain"; done
  389. return 0
  390. elif [ "${lport//[ ;\{\}]/}" != "$lport" ]; then
  391. for i in $(str_extras_to_space "$lport"); do [ -n "$i" ] && r_process_policy "$comment" "$iface" "$laddr" "$i" "$raddr" "$rport" "$proto" "$chain"; done
  392. return 0
  393. elif [ "${raddr//[ ;\{\}]/}" != "$raddr" ]; then
  394. for i in $(str_extras_to_space "$raddr"); do [ -n "$i" ] && r_process_policy "$comment" "$iface" "$laddr" "$lport" "$i" "$rport" "$proto" "$chain"; done
  395. return 0
  396. elif [ "${rport//[ ;\{\}]/}" != "$rport" ]; then
  397. for i in $(str_extras_to_space "$rport"); do [ -n "$i" ] && r_process_policy "$comment" "$iface" "$laddr" "$lport" "$raddr" "$i" "$proto" "$chain"; done
  398. return 0
  399. fi
  400. # start non-recursive processing
  401. # process TOR, netmask, physical device and mac-address separately, so we don't send them to resolveip
  402. if is_tor "$iface"; then
  403. insert_tor_policy "$comment" "$iface" "$laddr" "$lport" "$raddr" "$rport" "$proto" "$chain"
  404. elif is_phys_dev "$laddr"; then
  405. insert_policy "$comment" "$iface" "$laddr" "$lport" "$raddr" "$rport" "$proto" "$chain"
  406. elif [ -n "$laddr" ] && [ -z "${lport}${raddr}${rport}" ] && [ "$chain" = 'PREROUTING' ]; then
  407. if is_mac_address "$laddr"; then
  408. if [ -n "$proto" ] && [ "$proto" != 'all' ] && [ "$localIpset" -ne 0 ]; then
  409. processPolicyWarning="${processPolicyWarning}${_WARNING_}: Please unset 'proto' or set 'proto' to 'all' for policy '$comment', mac-address '$laddr'\\n"
  410. fi
  411. ips 'add' "${iface}_mac" "$laddr" "${comment}: $laddr" || ipsFailFlag=1
  412. else
  413. if [ -n "$proto" ] && [ "$proto" != "all" ] && [ "$localIpset" -ne 0 ]; then
  414. processPolicyWarning="${processPolicyWarning}${_WARNING_}: Please unset 'proto' or set 'proto' to 'all' for policy '$comment', address '$laddr'\\n"
  415. fi
  416. if ! ips 'add' "${iface}_ip" "$laddr" "${comment}: $laddr"; then
  417. ipr "$comment" "$iface" "$i" || ipsFailFlag=1
  418. fi
  419. fi
  420. elif [ -n "$raddr" ] && [ -z "${laddr}${lport}${rport}" ] && [ "$chain" = 'PREROUTING' ] && [ -n "$remoteIpset" ]; then
  421. if [ -n "$proto" ] && [ "$proto" != 'all' ]; then
  422. processPolicyWarning="${processPolicyWarning}${_WARNING_}: Please unset 'proto' or set 'proto' to 'all' for policy '$comment', domain '$raddr'\\n"
  423. fi
  424. case "$remoteIpset" in
  425. ipset)
  426. ips 'add' "${iface}" "$raddr" "${comment}: $raddr" || ipsFailFlag=1;;
  427. dnsmasq.ipset)
  428. if is_domain "$raddr"; then ips 'add_dnsmasq' "${iface}" "$raddr" "${comment}" || ipsFailFlag=1
  429. else ips 'add' "${iface}" "$raddr" "${comment}: $raddr" || ipsFailFlag=1; fi;;
  430. esac
  431. else
  432. ipsFailFlag=1
  433. fi
  434. if [ -n "$ipsFailFlag" ]; then
  435. if is_mac_address "$laddr"; then
  436. insert_policy "$comment" "$iface" "$laddr" "$lport" "$raddr" "$rport" "$proto" "$chain"
  437. elif is_netmask "$laddr" || is_netmask "$raddr"; then
  438. insert_policy "$comment" "$iface" "$laddr" "$lport" "$raddr" "$rport" "$proto" "$chain"
  439. else
  440. [ -n "$laddr" ] && resolved_laddr="$(resolveip "$laddr")"
  441. [ -n "$raddr" ] && resolved_raddr="$(resolveip "$raddr")"
  442. if [ -n "$resolved_laddr" ] && [ "$resolved_laddr" != "$laddr" ]; then
  443. for i in $resolved_laddr; do [ -n "$i" ] && r_process_policy "$comment $laddr" "$iface" "$i" "$lport" "$raddr" "$rport" "$proto" "$chain"; done
  444. elif [ -n "$resolved_raddr" ] && [ "$resolved_raddr" != "$raddr" ]; then
  445. for i in $resolved_raddr; do [ -n "$i" ] && r_process_policy "$comment $raddr" "$iface" "$laddr" "$lport" "$i" "$rport" "$proto" "$chain"; done
  446. else
  447. insert_policy "$comment" "$iface" "$laddr" "$lport" "$raddr" "$rport" "$proto" "$chain"
  448. fi
  449. fi
  450. fi
  451. }
  452. process_policy(){
  453. local name comment iface laddr lport raddr rport param mark processPolicyError processPolicyWarning proto chain enabled
  454. config_get comment "$1" 'comment'
  455. config_get name "$1" 'name' 'blank'
  456. config_get iface "$1" 'interface'
  457. config_get laddr "$1" 'src_addr'
  458. config_get lport "$1" 'src_port'
  459. config_get raddr "$1" 'dest_addr'
  460. config_get rport "$1" 'dest_port'
  461. config_get proto "$1" 'proto'
  462. config_get chain "$1" 'chain' 'PREROUTING'
  463. config_get_bool enabled "$1" 'enabled' 1
  464. [ "$enabled" -gt 0 ] || return 0
  465. proto="$(str_to_lower "$proto")"
  466. [ "$proto" = 'auto' ] && unset proto
  467. comment="${comment:-$name}"
  468. output 2 "Routing '$comment' via $iface "
  469. if [ -z "$comment" ]; then
  470. errorSummary="${errorSummary}${_ERROR_}: Policy name is empty\\n"
  471. output_fail; return 1;
  472. fi
  473. if [ -z "${laddr}${lport}${raddr}${rport}" ]; then
  474. errorSummary="${errorSummary}${_ERROR_}: Policy '$comment' missing all IPs/ports\\n"
  475. output_fail; return 1;
  476. fi
  477. if [ -z "$iface" ]; then
  478. errorSummary="${errorSummary}${_ERROR_}: Policy '$comment' has no assigned interface\\n"
  479. output_fail; return 1;
  480. fi
  481. if ! is_supported_interface "$iface"; then
  482. errorSummary="${errorSummary}${_ERROR_}: Policy '$comment' has unknown interface: '${iface}'\\n"
  483. output_fail; return 1;
  484. fi
  485. lport="${lport// / }"; lport="${lport// /,}"; lport="${lport//,\!/ !}";
  486. rport="${rport// / }"; rport="${rport// /,}"; rport="${rport//,\!/ !}";
  487. r_process_policy "$comment" "$iface" "$laddr" "$lport" "$raddr" "$rport" "$proto" "$chain"
  488. if [ -n "$processPolicyWarning" ]; then
  489. warningSummary="${warningSummary}${processPolicyWarning}\\n"
  490. fi
  491. if [ -n "$processPolicyError" ]; then
  492. output_fail
  493. errorSummary="${errorSummary}${processPolicyError}\\n"
  494. else
  495. output_ok
  496. fi
  497. }
  498. table_destroy(){
  499. local tid="$1" iface="$2" mark="$3"
  500. if [ -n "$tid" ] && [ -n "$iface" ] && [ -n "$mark" ]; then
  501. ip -4 rule del fwmark "$mark" table "$tid" >/dev/null 2>&1
  502. ip -6 rule del fwmark "$mark" table "$tid" >/dev/null 2>&1
  503. ip -4 rule del table "$tid" >/dev/null 2>&1
  504. ip -6 rule del table "$tid" >/dev/null 2>&1
  505. ip -4 route flush table "$tid";
  506. ip -6 route flush table "$tid";
  507. ips 'flush' "${iface}"; ips 'destroy' "${iface}";
  508. ips 'flush' "${iface}_ip"; ips 'destroy' "${iface}_ip";
  509. ips 'flush' "${iface}_mac"; ips 'destroy' "${iface}_mac";
  510. ip -4 route flush cache
  511. ip -6 route flush cache
  512. return 0
  513. else
  514. return 1
  515. fi
  516. }
  517. # shellcheck disable=SC2086
  518. table_create(){
  519. local tid="$1" mark="$2" iface="$3" gw4="$4" dev="$5" gw6="$6" dev6="$7" dscp s=0 i ipv4_error=0 ipv6_error=0
  520. if [ -z "$tid" ] || [ -z "$mark" ] || [ -z "$iface" ]; then
  521. return 1
  522. fi
  523. table_destroy "$tid" "$iface" "$mark"
  524. if [ -n "$gw4" ] || [ "$strictMode" -ne 0 ]; then
  525. if [ -z "$gw4" ]; then
  526. ip -4 route add unreachable default table "$tid" >/dev/null 2>&1 || ipv4_error=1
  527. else
  528. ip -4 route add default via "$gw4" dev "$dev" table "$tid" >/dev/null 2>&1 || ipv4_error=1
  529. fi
  530. ip -4 route ls table main | grep -v 'br-lan' | while read -r i; do
  531. idev="$(echo "$i" | grep -Eso 'dev [^ ]*' | awk '{print $2}')"
  532. if ! is_supported_iface_dev "$idev"; then
  533. ip -4 route add $i table "$tid" >/dev/null 2>&1 || ipv4_error=1
  534. fi
  535. done
  536. ip -4 route flush cache || ipv4_error=1
  537. ip -4 rule add fwmark "${mark}/${fwMask}" table "$tid" || ipv4_error=1
  538. fi
  539. if [ "$ipv6Enabled" -ne 0 ]; then
  540. if { [ -n "$gw6" ] && [ "$gw6" != "::/0" ]; } || [ "$strictMode" -ne 0 ]; then
  541. if [ -z "$gw6" ] || [ "$gw6" = "::/0" ]; then
  542. ip -6 route add unreachable default table "$tid" || ipv6_error=1
  543. else
  544. ip -6 route ls table main | grep " dev $dev6 " | while read -r i; do
  545. ip -6 route add $i table "$tid" >/dev/null 2>&1 || ipv6_error=1
  546. done
  547. fi
  548. ip -6 route flush cache || ipv6_error=1
  549. ip -6 rule add fwmark "${mark}/${fwMask}" table "$tid" || ipv6_error=1
  550. fi
  551. fi
  552. if [ $ipv4_error -eq 0 ] || [ $ipv6_error -eq 0 ]; then
  553. dscp="$(uci -q get "${packageName}".config."${iface}"_dscp)"
  554. if [ "${dscp:-0}" -ge 1 ] && [ "${dscp:-0}" -le 63 ]; then
  555. ipt -t mangle -I VPR_PREROUTING -m dscp --dscp "${dscp}" -j MARK --set-xmark "${mark}/${fwMask}" || s=1
  556. fi
  557. if [ -n "$remoteIpset" ]; then
  558. if ips 'create' "${iface}" 'hash:net comment' && ips 'flush' "${iface}"; then
  559. for i in PREROUTING FORWARD INPUT OUTPUT; do
  560. ipt -t mangle -I VPR_${i} -m set --match-set "${iface}" dst -j MARK --set-xmark "${mark}/${fwMask}" || s=1
  561. done
  562. else
  563. s=1
  564. fi
  565. fi
  566. if [ "$localIpset" -ne 0 ]; then
  567. if ips 'create' "${iface}_ip" 'hash:net comment' && ips 'flush' "${iface}_ip"; then
  568. ipt -t mangle -I VPR_PREROUTING -m set --match-set "${iface}_ip" src -j MARK --set-mark "${mark}/${fwMask}" || s=1
  569. else
  570. s=1
  571. fi
  572. if ips 'create' "${iface}_mac" 'hash:mac comment' && ips 'flush' "${iface}_mac"; then
  573. ipt -t mangle -I VPR_PREROUTING -m set --match-set "${iface}_mac" src -j MARK --set-mark "${mark}/${fwMask}" || s=1
  574. else
  575. s=1
  576. fi
  577. fi
  578. if [ "$iface" = "$icmpIface" ]; then
  579. ipt -t mangle -I VPR_OUTPUT -p icmp -j MARK --set-xmark "${mark}/${fwMask}" || s=1
  580. fi
  581. else
  582. s=1
  583. fi
  584. return $s
  585. }
  586. process_interface(){
  587. local gw4 gw6 dev dev6 s=0 dscp iface="$1" action="$2" displayText
  588. is_supported_interface "$iface" || return 0
  589. is_wan6 "$iface" && return 0
  590. [ $((ifaceMark)) -gt $((fwMask)) ] && return 1
  591. network_get_device dev "$iface"
  592. [ -z "$dev" ] && config_get dev "$iface" 'ifname'
  593. if is_wan "$iface" && [ -n "$wanIface6" ]; then
  594. network_get_device dev6 "$wanIface6"
  595. [ -z "$dev6" ] && config_get dev6 "$wanIface6" 'ifname'
  596. fi
  597. [ -z "$dev6" ] && dev6="$dev"
  598. [ -z "$ifaceTableID" ] && ifaceTableID="$wanTableID"; [ -z "$ifaceMark" ] && ifaceMark="$wanMark";
  599. case "$action" in
  600. destroy)
  601. table_destroy "${ifaceTableID}" "${iface}" "${ifaceMark}"
  602. ifaceTableID="$((ifaceTableID + 1))"; ifaceMark="$(printf '0x%06x' $((ifaceMark + wanMark)))";
  603. ;;
  604. create)
  605. export "mark_${iface//-/_}=$ifaceMark"; export "tid_${iface//-/_}=$ifaceTableID";
  606. table_destroy "${ifaceTableID}" "${iface}"
  607. vpr_get_gateway gw4 "$iface" "$dev"
  608. vpr_get_gateway6 gw6 "$iface" "$dev6"
  609. if [ "$iface" = "$dev" ]; then
  610. displayText="${iface}/${gw4:-0.0.0.0}"
  611. else
  612. displayText="${iface}/${dev}/${gw4:-0.0.0.0}"
  613. fi
  614. [ "$ipv6Enabled" -ne 0 ] && displayText="${displayText}/${gw6:-::/0}"
  615. output 2 "Creating table '$displayText' "
  616. is_default_dev "$dev" && displayText="${displayText} ${__OK__}"
  617. if table_create "$ifaceTableID" "$ifaceMark" "$iface" "$gw4" "$dev" "$gw6" "$dev6"; then
  618. gatewaySummary="${gatewaySummary}${displayText}\\n"
  619. output_ok
  620. else
  621. errorSummary="${errorSummary}${_ERROR_}: Failed to set up '$displayText'\\n"
  622. output_fail
  623. fi
  624. ifaceTableID="$((ifaceTableID + 1))"; ifaceMark="$(printf '0x%06x' $((ifaceMark + wanMark)))";
  625. ;;
  626. esac
  627. return $s
  628. }
  629. convert_config(){
  630. local i
  631. [ -s "/etc/config/${packageName}" ] || return 0
  632. sed -i 's/ignored_interfaces/ignored_interface/g' "/etc/config/${packageName}"
  633. sed -i 's/supported_interfaces/supported_interface/g' "/etc/config/${packageName}"
  634. sed -i 's/local_addresses/local_address/g' "/etc/config/${packageName}"
  635. sed -i 's/local_ports/local_port/g' "/etc/config/${packageName}"
  636. sed -i 's/remote_addresses/remote_address/g' "/etc/config/${packageName}"
  637. sed -i 's/remote_ports/remote_port/g' "/etc/config/${packageName}"
  638. sed -i 's/ipset_enabled/remote_ipset/g' "/etc/config/${packageName}"
  639. sed -i 's/dnsmasq_enabled/dnsmasq_ipset/g' "/etc/config/${packageName}"
  640. sed -i 's/enable_control/webui_enable_column/g' "/etc/config/${packageName}"
  641. sed -i 's/proto_control/webui_protocol_column/g' "/etc/config/${packageName}"
  642. sed -i 's/chain_control/webui_chain_column/g' "/etc/config/${packageName}"
  643. sed -i 's/sort_control/webui_sorting/g' "/etc/config/${packageName}"
  644. sed -i 's/local_address/src_addr/g' "/etc/config/${packageName}"
  645. sed -i 's/local_port/src_port/g' "/etc/config/${packageName}"
  646. sed -i 's/remote_address/dest_addr/g' "/etc/config/${packageName}"
  647. sed -i 's/remote_port/dest_port/g' "/etc/config/${packageName}"
  648. sed -i 's/append_local_rules/append_src_rules/g' "/etc/config/${packageName}"
  649. sed -i 's/append_remote_rules/append_dest_rules/g' "/etc/config/${packageName}"
  650. sync
  651. config_load "$packageName"
  652. config_get_bool dnsmasqIpset 'config' 'dnsmasq_ipset' 0
  653. config_get remoteIpset 'config' 'remote_ipset'
  654. config_get webuiProtocol 'config' 'webui_supported_protocol'
  655. # shellcheck disable=SC2154
  656. if [ "$dnsmasqIpset" = "1" ]; then
  657. remoteIpset="dnsmasq.ipset";
  658. elif [ "$remoteIpset" = "1" ]; then
  659. remoteIpset="ipset";
  660. elif [ "$remoteIpset" = "0" ]; then
  661. remoteIpset=""
  662. fi
  663. uci -q del "$packageName.config.dnsmasq_ipset"
  664. uci -q set "$packageName".config.remote_ipset="$remoteIpset"
  665. # shellcheck disable=SC2154
  666. if [ -z "$webuiProtocol" ]; then
  667. uci add_list "$packageName".config.webui_supported_protocol='tcp'
  668. uci add_list "$packageName".config.webui_supported_protocol='udp'
  669. uci add_list "$packageName".config.webui_supported_protocol='tcp udp'
  670. uci add_list "$packageName".config.webui_supported_protocol='icmp'
  671. uci add_list "$packageName".config.webui_supported_protocol='all'
  672. fi
  673. uci commit "$packageName"
  674. sed -i 's/local_ipset/src_ipset/g' "/etc/config/${packageName}"
  675. sed -i 's/remote_ipset/dest_ipset/g' "/etc/config/${packageName}"
  676. for i in udp_proto_enabled forward_chain_enabled input_chain_enabled output_chain_enabled; do
  677. grep -q "$i" "/etc/config/${packageName}" && output "${_WARNING_}: $i setting is not supported in ${serviceName}.\\n"
  678. done
  679. }
  680. check_config(){ local en; config_get_bool en "$1" 'enabled' 1; [ "$en" -gt 0 ] && _cfg_enabled=0; }
  681. is_config_enabled(){
  682. local cfg="$1" _cfg_enabled=1
  683. [ -n "$1" ] || return 1
  684. config_load "$packageName"
  685. config_foreach check_config "$cfg"
  686. return "$_cfg_enabled"
  687. }
  688. process_user_file(){
  689. local path enabled shellBin="${SHELL:-/bin/ash}"
  690. config_get_bool enabled "$1" 'enabled' 1
  691. config_get path "$1" 'path'
  692. [ "$enabled" -gt 0 ] || return 0
  693. if [ ! -s "$path" ]; then
  694. errorSummary="${errorSummary}${_ERROR_}: Custom user file '$path' not found or empty\\n"
  695. output_fail
  696. return 1
  697. fi
  698. if ! $shellBin -n "$path"; then
  699. errorSummary="${errorSummary}${_ERROR_}: Syntax error in custom user file '$path'\\n"
  700. output_fail
  701. return 1
  702. fi
  703. # shellcheck disable=SC1090
  704. if ! . "$path"; then
  705. errorSummary="${errorSummary}${_ERROR_}: Error running custom user file '$path'\\n"
  706. output_fail
  707. return 1
  708. else
  709. output 2 "Running $path "
  710. output_ok
  711. return 0
  712. fi
  713. }
  714. start_service() {
  715. local gatewaySummary errorSummary warningSummary dnsmasqStoredHash dnsmasqNewHash i modprobeStatus=0
  716. convert_config
  717. is_enabled 'on_start' || return 1
  718. is_wan_up || return 0
  719. if create_lock; then
  720. if [ -s "$dnsmasqFile" ]; then
  721. dnsmasqStoredHash="$(md5sum $dnsmasqFile | awk '{ print $1; }')"
  722. rm -f "$dnsmasqFile"
  723. fi
  724. for i in xt_set ip_set ip_set_hash_ip; do
  725. modprobe "$i" >/dev/null 2>/dev/null || modprobeStatus=$((modprobeStatus + 1))
  726. done
  727. if [ "$modprobeStatus" -gt 0 ] && ! is_chaos_calmer; then
  728. errorSummary="${errorSummary}${_ERROR_}: Failed to load kernel modules\\n"
  729. fi
  730. for i in PREROUTING FORWARD INPUT OUTPUT; do
  731. ipt -t mangle -N "VPR_${i}"
  732. ipt -t mangle "$insertOption" "$i" -m mark --mark "0x0/${fwMask}" -j "VPR_${i}"
  733. done
  734. output 1 'Processing Interfaces '
  735. config_load 'network'; config_foreach process_interface 'interface' 'create';
  736. output 1 '\n'
  737. if is_config_enabled 'policy'; then
  738. output 1 'Processing Policies '
  739. config_load "$packageName"; config_foreach process_policy 'policy';
  740. output 1 '\n'
  741. fi
  742. if is_config_enabled 'include'; then
  743. output 1 'Processing User File(s) '
  744. config_load "$packageName"; config_foreach process_user_file 'include';
  745. output 1 '\n'
  746. fi
  747. if [ -s "$dnsmasqFile" ]; then
  748. dnsmasqNewHash="$(md5sum $dnsmasqFile | awk '{ print $1; }')"
  749. fi
  750. [ "$dnsmasqNewHash" != "$dnsmasqStoredHash" ] && dnsmasq_restart
  751. if [ -z "$gatewaySummary" ]; then
  752. errorSummary="${errorSummary}${_ERROR_}: failed to set up any gateway\\n"
  753. else
  754. output "$serviceName started with gateways:\\n${gatewaySummary}"
  755. [ -n "$errorSummary" ] && output "${errorSummary}"
  756. [ -n "$warningSummary" ] && output "${warningSummary}"
  757. fi
  758. procd_open_instance "main"
  759. procd_set_param command /bin/true
  760. procd_set_param stdout 1
  761. procd_set_param stderr 1
  762. procd_open_data
  763. json_add_array 'status'
  764. json_add_object ''
  765. [ -n "$gatewaySummary" ] && json_add_string gateway "$gatewaySummary"
  766. [ -n "$errorSummary" ] && json_add_string error "$errorSummary"
  767. [ -n "$warningSummary" ] && json_add_string warning "$warningSummary"
  768. if [ "$strictMode" -ne 0 ] && [ "${gatewaySummary//0.0.0.0}" != "${gatewaySummary}" ]; then
  769. json_add_string mode "strict"
  770. fi
  771. json_close_object
  772. json_close_array
  773. procd_close_data
  774. procd_close_instance
  775. remove_lock
  776. else
  777. output "$serviceName: another instance of ${packageName} is currently running "
  778. output_failn
  779. return 1
  780. fi
  781. }
  782. restart() { reload; }
  783. restart_service() { reload; }
  784. stop_service() {
  785. local i
  786. iptables -t mangle -L | grep -q VPR_PREROUTING || return 0
  787. if create_lock; then
  788. load_package_config
  789. for i in PREROUTING FORWARD INPUT OUTPUT; do
  790. ipt -t mangle -D "${i}" -m mark --mark "0x0/${fwMask}" -j "VPR_${i}"
  791. ipt -t mangle -F "VPR_${i}"; ipt -t mangle -X "VPR_${i}";
  792. done
  793. config_load 'network'; config_foreach process_interface 'interface' 'destroy'
  794. unset ifaceTableID; unset ifaceMark;
  795. if [ -s "$dnsmasqFile" ]; then
  796. rm -f "$dnsmasqFile"
  797. dnsmasq_restart
  798. fi
  799. if [ "$serviceEnabled" -ne 0 ]; then
  800. output "$serviceName stopped "; output_okn;
  801. fi
  802. remove_lock
  803. else
  804. output "$serviceName: another instance of ${packageName} is currently running "; output_failn;
  805. return 1
  806. fi
  807. }
  808. # shellcheck disable=SC2119
  809. service_triggers() {
  810. local n
  811. is_enabled || return 1
  812. procd_open_validate
  813. validate_config
  814. validate_policy
  815. validate_include
  816. procd_close_validate
  817. procd_add_reload_trigger 'firewall' 'openvpn' 'vpn-policy-routing'
  818. procd_open_trigger
  819. for n in $ifSupported; do procd_add_reload_interface_trigger "$n"; procd_add_interface_trigger "interface.*" "$n" /etc/init.d/${packageName} reload; done;
  820. procd_close_trigger
  821. if [ "$verbosity" -eq 2 ]; then
  822. output "$serviceName monitoring interfaces: $ifSupported.\\n"
  823. fi
  824. }
  825. input() { local data; while read -r data; do echo "$data" | tee -a /var/${packageName}-support; done; }
  826. status_service() { support "$@"; }
  827. support() {
  828. local dist vers out id s param status set_d set_p tableCount i=0 dev dev6
  829. is_enabled
  830. json_load "$(ubus call system board)"; json_select release; json_get_var dist distribution; json_get_var vers version
  831. if [ -n "$wanIface4" ]; then
  832. network_get_gateway wanGW4 "$wanIface4"
  833. dev="$(uci -q get network."${wanIface4}".ifname)"
  834. fi
  835. if [ -n "$wanIface6" ]; then
  836. dev6="$(uci -q get network."${wanIface6}".ifname)"
  837. wanGW6=$(ip -6 route show | grep -m1 " dev $dev6 " | awk '{print $1}')
  838. [ "$wanGW6" = "default" ] && wanGW6=$(ip -6 route show | grep -m1 " dev $dev6 " | awk '{print $3}')
  839. fi
  840. while [ "${1:0:1}" = "-" ]; do param="${1//-/}"; export "set_$param=1"; shift; done
  841. [ -e "/var/${packageName}-support" ] && rm -f "/var/${packageName}-support"
  842. status="$serviceName running on $dist $vers."
  843. [ -n "$wanIface4" ] && status="$status WAN (IPv4): $wanIface4/dev/${wanGW4:-0.0.0.0}."
  844. [ -n "$wanIface6" ] && status="$status WAN (IPv6): $wanIface6/dev6/${wanGW6:-::/0}."
  845. {
  846. echo "$status"
  847. echo "============================================================"
  848. dnsmasq --version 2>/dev/null | sed '/^$/,$d'
  849. [ -n "$1" ] && {
  850. echo "============================================================"
  851. echo "Resolving domains"
  852. while [ -n "$1" ]; do echo "$1: $(resolveip "$1" | tr '\n' ' ')"; shift; done; }
  853. echo "============================================================"
  854. echo "Routes/IP Rules"
  855. tableCount=$(ip rule list | grep -c 'fwmark') || tableCount=0
  856. if [ -n "$set_d" ]; then route; else route | grep '^default'; fi
  857. if [ -n "$set_d" ]; then ip rule list; fi # || ip rule list | grep 'fwmark'
  858. i=0; while [ $i -lt $tableCount ]; do echo "IPv4 Table $((wanTableID + i)): $(ip route show table $((wanTableID + i)))"; echo "IPv4 Table $((wanTableID + i)) Rules:"; ip rule list | grep $((wanTableID + i)); i=$((i + 1)); done
  859. [ "$ipv6Enabled" -ne 0 ] && {
  860. i=0; while [ $i -lt $tableCount ]; do
  861. ip -6 route show table $((wanTableID + i)) | while read -r param; do echo "IPv6 Table $((wanTableID + i)): $param"; done
  862. i=$((i + 1))
  863. done; }
  864. echo "============================================================"
  865. if [ -z "$set_d" ]; then echo "IP Tables PREROUTING"; else echo "IP Tables"; fi
  866. if [ -z "$set_d" ]; then iptables -v -t mangle -S VPR_PREROUTING; else iptables -L -t mangle; fi
  867. [ "$ipv6Enabled" -ne 0 ] && {
  868. echo "============================================================"
  869. if [ -z "$set_d" ]; then echo "IP6 Tables PREROUTING"; else echo "IP6 Tables"; fi
  870. if [ -z "$set_d" ]; then ip6tables -v -t mangle -S VPR_PREROUTING; else ip6tables -L -t mangle; fi
  871. }
  872. [ -z "$set_d" ] && { echo "============================================================"
  873. echo "IP Tables FORWARD"
  874. iptables -v -t mangle -S VPR_FORWARD
  875. [ "$ipv6Enabled" -ne 0 ] && {
  876. echo "============================================================"
  877. echo "IPv6 Tables FORWARD"
  878. ip6tables -v -t mangle -S VPR_FORWARD
  879. };}
  880. [ -z "$set_d" ] && { echo "============================================================"
  881. echo "IP Tables INPUT"
  882. iptables -v -t mangle -S VPR_INPUT
  883. [ "$ipv6Enabled" -ne 0 ] && {
  884. echo "============================================================"
  885. echo "IPv6 Tables INPUT"
  886. ip6tables -v -t mangle -S VPR_INPUT
  887. };}
  888. [ -z "$set_d" ] && { echo "============================================================"
  889. echo "IP Tables OUTPUT"
  890. iptables -v -t mangle -S VPR_OUTPUT
  891. [ "$ipv6Enabled" -ne 0 ] && {
  892. echo "============================================================"
  893. echo "IPv6 Tables OUTPUT"
  894. ip6tables -v -t mangle -S VPR_OUTPUT
  895. };}
  896. echo "============================================================"
  897. echo "Current ipsets"
  898. ipset save
  899. if [ -s "$dnsmasqFile" ]; then
  900. echo "============================================================"
  901. echo "DNSMASQ ipsets"
  902. cat "$dnsmasqFile"
  903. fi
  904. echo "============================================================"
  905. } | input
  906. if [ -n "$set_p" ]; then
  907. printf "%b" "Pasting to paste.ee... "
  908. if is_installed 'curl' && is_installed 'libopenssl' && is_installed 'ca-bundle'; then
  909. json_init; json_add_string "description" "${packageName}-support"
  910. json_add_array "sections"; json_add_object '0'
  911. json_add_string "name" "$(uci -q get system.@system[0].hostname)"
  912. json_add_string "contents" "$(cat /var/${packageName}-support)"
  913. json_close_object; json_close_array; payload=$(json_dump)
  914. out=$(curl -s -k "https://api.paste.ee/v1/pastes" -X "POST" -H "Content-Type: application/json" -H "X-Auth-Token:uVOJt6pNqjcEWu7qiuUuuxWQafpHhwMvNEBviRV2B" -d "$payload")
  915. json_load "$out"; json_get_var id id; json_get_var s success
  916. [ "$s" = "1" ] && printf "%b" "https://paste.ee/p/$id $__OK__" || printf "%b" "$__FAIL__"
  917. [ -e "/var/${packageName}-support" ] && rm -f "/var/${packageName}-support"
  918. else
  919. printf "%b" "$__FAIL__\\n"
  920. printf "%b" "$_ERROR_: curl, libopenssl or ca-bundle were not found!\\nRun 'opkg update; opkg install curl libopenssl ca-bundle' to install them.\\n"
  921. fi
  922. else
  923. printf "%b" "Your support details have been logged to '/var/${packageName}-support'. $__OK__\\n"
  924. fi
  925. }
  926. # shellcheck disable=SC2120
  927. validate_config() {
  928. uci_validate_section "${packageName}" config "${1}" \
  929. 'enabled:bool:0' \
  930. 'verbosity:range(0,2):1' \
  931. 'strict_enforcement:bool:1' \
  932. 'src_ipset:bool:0' \
  933. 'dest_ipset:string' \
  934. 'ipv6_enabled:bool:0' \
  935. 'supported_interface:list(string)' \
  936. 'ignored_interface:list(string)' \
  937. 'boot_timeout:integer:30' \
  938. 'iptables_rule_option:or("", "append", "insert")' \
  939. 'iprule_enabled:bool:0' \
  940. 'webui_enable_column:bool:0' \
  941. 'webui_protocol_column:bool:0' \
  942. 'webui_supported_protocol:list(string)' \
  943. 'webui_chain_column:bool:0' \
  944. 'webui_sorting:bool:1' \
  945. 'icmp_interface:string' \
  946. 'wan_tid:integer:201' \
  947. 'wan_fw_mark:hex(8)' \
  948. 'fw_mask:hex(8)'
  949. }
  950. # shellcheck disable=SC2120
  951. validate_policy() {
  952. uci_validate_section "${packageName}" policy "${1}" \
  953. 'name:string' \
  954. 'enabled:bool:0' \
  955. 'interface:network' \
  956. 'proto:or(string)' \
  957. 'chain:or("", "PREROUTING", "FORWARD", "INPUT", "OUTPUT")' \
  958. 'src_addr:list(neg(or(host,network,macaddr)))' \
  959. 'src_port:list(neg(or(portrange, string)))' \
  960. 'dest_addr:list(neg(host))' \
  961. 'dest_port:list(neg(or(portrange, string)))'
  962. }
  963. # shellcheck disable=SC2120
  964. validate_include() {
  965. uci_validate_section "${packageName}" include "${1}" \
  966. 'path:string' \
  967. 'enabled:bool:0'
  968. }