#!/bin/bash

main_cfg='/etc/tproxy/ss-tproxy.conf'
if [ -f $main_cfg ]; then
    source $main_cfg
else
    echo "No such file or directory: '$main_cfg'" 1>&2
    exit 1
fi

function check_depend {
case "$mode" in
    tproxy_global)
        { command -v ss-redir &>/dev/null || command -v ssr-redir &>/dev/null; } || { echo "Error: ss-redir/ssr-redir is not installed." 1>&2; exit 1; }
        { command -v ss-tunnel &>/dev/null || command -v ssr-tunnel &>/dev/null; } || { echo "Error: ss-tunnel/ssr-tunnel is not installed." 1>&2; exit 1; }
        command -v haveged &>/dev/null || { echo "Warning: haveged is not installed." 1>&2; }
        modprobe xt_TPROXY &>/dev/null || { echo "Error: xt_TPROXY module is not installed." 1>&2; exit 1; }
        command -v ip &>/dev/null || { echo "Error: iproute2 is not installed." 1>&2; exit 1; }
        command -v dnsmasq &>/dev/null || { echo "Error: dnsmasq is not installed." 1>&2; exit 1; }
        ;;
    tproxy_global_tcp)
        { command -v ss-redir &>/dev/null || command -v ssr-redir &>/dev/null; } || { echo "Error: ss-redir/ssr-redir is not installed." 1>&2; exit 1; }
        command -v haveged &>/dev/null || { echo "Warning: haveged is not installed." 1>&2; }
        command -v dnsforwarder &>/dev/null || { echo "Error: dnsforwarder is not installed." 1>&2; exit 1; }
        ;;
    tproxy_gfwlist)
        { command -v ss-redir &>/dev/null || command -v ssr-redir &>/dev/null; } || { echo "Error: ss-redir/ssr-redir is not installed." 1>&2; exit 1; }
        { command -v ss-tunnel &>/dev/null || command -v ssr-tunnel &>/dev/null; } || { echo "Error: ss-tunnel/ssr-tunnel is not installed." 1>&2; exit 1; }
        command -v haveged &>/dev/null || { echo "Warning: haveged is not installed." 1>&2; }
        modprobe xt_TPROXY &>/dev/null || { echo "Error: xt_TPROXY module is not installed." 1>&2; exit 1; }
        command -v ip &>/dev/null || { echo "Error: iproute2 is not installed." 1>&2; exit 1; }
        command -v dnsmasq &>/dev/null || { echo "Error: dnsmasq is not installed." 1>&2; exit 1; }
        command -v ipset &>/dev/null || { echo "Error: ipset is not installed." 1>&2; exit 1; }
        command -v perl &>/dev/null || { echo "Error: perl is not installed." 1>&2; exit 1; }
        command -v curl &>/dev/null || { echo "Warning: curl is not installed." 1>&2; }
        command -v base64 &>/dev/null || { echo "Warning: base64 is not installed." 1>&2; }
        ;;
    tproxy_gfwlist_tcp)
        { command -v ss-redir &>/dev/null || command -v ssr-redir &>/dev/null; } || { echo "Error: ss-redir/ssr-redir is not installed." 1>&2; exit 1; }
        command -v haveged &>/dev/null || { echo "Warning: haveged is not installed." 1>&2; }
        command -v dnsforwarder &>/dev/null || { echo "Error: dnsforwarder is not installed." 1>&2; exit 1; }
        command -v dnsmasq &>/dev/null || { echo "Error: dnsmasq is not installed." 1>&2; exit 1; }
        command -v ipset &>/dev/null || { echo "Error: ipset is not installed." 1>&2; exit 1; }
        command -v perl &>/dev/null || { echo "Error: perl is not installed." 1>&2; exit 1; }
        command -v curl &>/dev/null || { echo "Warning: curl is not installed." 1>&2; }
        command -v base64 &>/dev/null || { echo "Warning: base64 is not installed." 1>&2; }
        ;;
    tproxy_chnroute)
        { command -v ss-redir &>/dev/null || command -v ssr-redir &>/dev/null; } || { echo "Error: ss-redir/ssr-redir is not installed." 1>&2; exit 1; }
        { command -v ss-tunnel &>/dev/null || command -v ssr-tunnel &>/dev/null; } || { echo "Error: ss-tunnel/ssr-tunnel is not installed." 1>&2; exit 1; }
        command -v haveged &>/dev/null || { echo "Warning: haveged is not installed." 1>&2; }
        modprobe xt_TPROXY &>/dev/null || { echo "Error: xt_TPROXY module is not installed." 1>&2; exit 1; }
        command -v ip &>/dev/null || { echo "Error: iproute2 is not installed." 1>&2; exit 1; }
        command -v ipset &>/dev/null || { echo "Error: ipset is not installed." 1>&2; exit 1; }
        command -v chinadns &>/dev/null || { echo "Error: chinadns is not installed." 1>&2; exit 1; }
        command -v dnsmasq &>/dev/null || { echo "Error: dnsmasq is not installed." 1>&2; exit 1; }
        command -v curl &>/dev/null || { echo "Warning: curl is not installed." 1>&2; }
        ;;
    tproxy_chnroute_tcp)
        { command -v ss-redir &>/dev/null || command -v ssr-redir &>/dev/null; } || { echo "Error: ss-redir/ssr-redir is not installed." 1>&2; exit 1; }
        command -v haveged &>/dev/null || { echo "Warning: haveged is not installed." 1>&2; }
        command -v ipset &>/dev/null || { echo "Error: ipset is not installed." 1>&2; exit 1; }
        command -v chinadns &>/dev/null || { echo "Error: chinadns is not installed." 1>&2; exit 1; }
        command -v dnsforwarder &>/dev/null || { echo "Error: dnsforwarder is not installed." 1>&2; exit 1; }
        command -v curl &>/dev/null || { echo "Warning: curl is not installed." 1>&2; }
        ;;
    tun2socks_global)
        command -v tun2socks &>/dev/null || { echo "Error: tun2socks is not installed." 1>&2; exit 1; }
        command -v ip &>/dev/null || { echo "Error: iproute2 is not installed." 1>&2; exit 1; }
        command -v dnsmasq &>/dev/null || { echo "Error: dnsmasq is not installed." 1>&2; exit 1; }
        ;;
    tun2socks_global_tcp)
        command -v tun2socks &>/dev/null || { echo "Error: tun2socks is not installed." 1>&2; exit 1; }
        command -v ip &>/dev/null || { echo "Error: iproute2 is not installed." 1>&2; exit 1; }
        command -v dnsforwarder &>/dev/null || { echo "Error: dnsforwarder is not installed." 1>&2; exit 1; }
        ;;
    tun2socks_gfwlist)
        command -v tun2socks &>/dev/null || { echo "Error: tun2socks is not installed." 1>&2; exit 1; }
        command -v ip &>/dev/null || { echo "Error: iproute2 is not installed." 1>&2; exit 1; }
        command -v dnsmasq &>/dev/null || { echo "Error: dnsmasq is not installed." 1>&2; exit 1; }
        command -v ipset &>/dev/null || { echo "Error: ipset is not installed." 1>&2; exit 1; }
        command -v perl &>/dev/null || { echo "Error: perl is not installed." 1>&2; exit 1; }
        command -v curl &>/dev/null || { echo "Warning: curl is not installed." 1>&2; }
        command -v base64 &>/dev/null || { echo "Warning: base64 is not installed." 1>&2; }
        ;;
    tun2socks_gfwlist_tcp)
        command -v tun2socks &>/dev/null || { echo "Error: tun2socks is not installed." 1>&2; exit 1; }
        command -v ip &>/dev/null || { echo "Error: iproute2 is not installed." 1>&2; exit 1; }
        command -v dnsforwarder &>/dev/null || { echo "Error: dnsforwarder is not installed." 1>&2; exit 1; }
        command -v dnsmasq &>/dev/null || { echo "Error: dnsmasq is not installed." 1>&2; exit 1; }
        command -v ipset &>/dev/null || { echo "Error: ipset is not installed." 1>&2; exit 1; }
        command -v perl &>/dev/null || { echo "Error: perl is not installed." 1>&2; exit 1; }
        command -v curl &>/dev/null || { echo "Warning: curl is not installed." 1>&2; }
        command -v base64 &>/dev/null || { echo "Warning: base64 is not installed." 1>&2; }
        ;;
    tun2socks_chnroute)
        command -v tun2socks &>/dev/null || { echo "Error: tun2socks is not installed." 1>&2; exit 1; }
        command -v ip &>/dev/null || { echo "Error: iproute2 is not installed." 1>&2; exit 1; }
        command -v ipset &>/dev/null || { echo "Error: ipset is not installed." 1>&2; exit 1; }
        command -v chinadns &>/dev/null || { echo "Error: chinadns is not installed." 1>&2; exit 1; }
        command -v dnsmasq &>/dev/null || { echo "Error: dnsmasq is not installed." 1>&2; exit 1; }
        command -v curl &>/dev/null || { echo "Warning: curl is not installed." 1>&2; }
        ;;
    tun2socks_chnroute_tcp)
        command -v tun2socks &>/dev/null || { echo "Error: tun2socks is not installed." 1>&2; exit 1; }
        command -v ip &>/dev/null || { echo "Error: iproute2 is not installed." 1>&2; exit 1; }
        command -v ipset &>/dev/null || { echo "Error: ipset is not installed." 1>&2; exit 1; }
        command -v chinadns &>/dev/null || { echo "Error: chinadns is not installed." 1>&2; exit 1; }
        command -v dnsforwarder &>/dev/null || { echo "Error: dnsforwarder is not installed." 1>&2; exit 1; }
        command -v curl &>/dev/null || { echo "Warning: curl is not installed." 1>&2; }
        ;;
esac
}

function update_gfwlist {
    curl -4sSkL https://raw.github.com/gfwlist/gfwlist/master/gfwlist.txt | base64 -d | { perl -pe '
    if (/URL Keywords/i) { $null = <> until $null =~ /^!/ }
    s#^\s*+$|^!.*+$|^@@.*+$|^\[AutoProxy.*+$|^/.*/$##i;
    s@^\|\|?|\|$@@;
    s@^https?:/?/?@@i;
    s@(?:/|%).*+$@@;
    s@\*[^.*]++$@\n@;
    s@^.*?\*[^.]*+(?=[^*]+$)@@;
    s@^\*?\.|^.*\.\*?$@@;
    s@(?=[^0-9a-zA-Z.-]).*+$@@;
    s@^\d+\.\d+\.\d+\.\d+(?::\d+)?$@@;
    s@^\s*+$@@'
    echo 'twimg.edgesuite.net'
    echo -e 'blogspot.ae\nblogspot.al\nblogspot.am\nblogspot.ba\nblogspot.be\nblogspot.bg\nblogspot.bj\nblogspot.ca\nblogspot.cat\nblogspot.cf\nblogspot.ch\nblogspot.cl\nblogspot.co.at\nblogspot.co.id\nblogspot.co.il\nblogspot.co.ke\nblogspot.com\nblogspot.com.ar\nblogspot.com.au\nblogspot.com.br\nblogspot.com.by\nblogspot.com.co\nblogspot.com.cy\nblogspot.com.ee\nblogspot.com.eg\nblogspot.com.es\nblogspot.com.mt\nblogspot.com.ng\nblogspot.com.tr\nblogspot.com.uy\nblogspot.co.nz\nblogspot.co.uk\nblogspot.co.za\nblogspot.cv\nblogspot.cz\nblogspot.de\nblogspot.dk\nblogspot.fi\nblogspot.fr\nblogspot.gr\nblogspot.hk\nblogspot.hr\nblogspot.hu\nblogspot.ie\nblogspot.in\nblogspot.is\nblogspot.it\nblogspot.jp\nblogspot.kr\nblogspot.li\nblogspot.lt\nblogspot.lu\nblogspot.md\nblogspot.mk\nblogspot.mr\nblogspot.mx\nblogspot.my\nblogspot.nl\nblogspot.no\nblogspot.pe\nblogspot.pt\nblogspot.qa\nblogspot.re\nblogspot.ro\nblogspot.rs\nblogspot.ru\nblogspot.se\nblogspot.sg\nblogspot.si\nblogspot.sk\nblogspot.sn\nblogspot.td\nblogspot.tw\nblogspot.ug\nblogspot.vn'
    echo -e 'google.ac\ngoogle.ad\ngoogle.ae\ngoogle.al\ngoogle.am\ngoogle.as\ngoogle.at\ngoogle.az\ngoogle.ba\ngoogle.be\ngoogle.bf\ngoogle.bg\ngoogle.bi\ngoogle.bj\ngoogle.bs\ngoogle.bt\ngoogle.by\ngoogle.ca\ngoogle.cat\ngoogle.cc\ngoogle.cd\ngoogle.cf\ngoogle.cg\ngoogle.ch\ngoogle.ci\ngoogle.cl\ngoogle.cm\ngoogle.cn\ngoogle.co.ao\ngoogle.co.bw\ngoogle.co.ck\ngoogle.co.cr\ngoogle.co.id\ngoogle.co.il\ngoogle.co.in\ngoogle.co.jp\ngoogle.co.ke\ngoogle.co.kr\ngoogle.co.ls\ngoogle.com\ngoogle.co.ma\ngoogle.com.af\ngoogle.com.ag\ngoogle.com.ai\ngoogle.com.ar\ngoogle.com.au\ngoogle.com.bd\ngoogle.com.bh\ngoogle.com.bn\ngoogle.com.bo\ngoogle.com.br\ngoogle.com.bz\ngoogle.com.co\ngoogle.com.cu\ngoogle.com.cy\ngoogle.com.do\ngoogle.com.ec\ngoogle.com.eg\ngoogle.com.et\ngoogle.com.fj\ngoogle.com.gh\ngoogle.com.gi\ngoogle.com.gt\ngoogle.com.hk\ngoogle.com.jm\ngoogle.com.kh\ngoogle.com.kw\ngoogle.com.lb\ngoogle.com.lc\ngoogle.com.ly\ngoogle.com.mm\ngoogle.com.mt\ngoogle.com.mx\ngoogle.com.my\ngoogle.com.na\ngoogle.com.nf\ngoogle.com.ng\ngoogle.com.ni\ngoogle.com.np\ngoogle.com.om\ngoogle.com.pa\ngoogle.com.pe\ngoogle.com.pg\ngoogle.com.ph\ngoogle.com.pk\ngoogle.com.pr\ngoogle.com.py\ngoogle.com.qa\ngoogle.com.sa\ngoogle.com.sb\ngoogle.com.sg\ngoogle.com.sl\ngoogle.com.sv\ngoogle.com.tj\ngoogle.com.tr\ngoogle.com.tw\ngoogle.com.ua\ngoogle.com.uy\ngoogle.com.vc\ngoogle.com.vn\ngoogle.co.mz\ngoogle.co.nz\ngoogle.co.th\ngoogle.co.tz\ngoogle.co.ug\ngoogle.co.uk\ngoogle.co.uz\ngoogle.co.ve\ngoogle.co.vi\ngoogle.co.za\ngoogle.co.zm\ngoogle.co.zw\ngoogle.cv\ngoogle.cz\ngoogle.de\ngoogle.dj\ngoogle.dk\ngoogle.dm\ngoogle.dz\ngoogle.ee\ngoogle.es\ngoogle.fi\ngoogle.fm\ngoogle.fr\ngoogle.ga\ngoogle.ge\ngoogle.gf\ngoogle.gg\ngoogle.gl\ngoogle.gm\ngoogle.gp\ngoogle.gr\ngoogle.gy\ngoogle.hn\ngoogle.hr\ngoogle.ht\ngoogle.hu\ngoogle.ie\ngoogle.im\ngoogle.io\ngoogle.iq\ngoogle.is\ngoogle.it\ngoogle.je\ngoogle.jo\ngoogle.kg\ngoogle.ki\ngoogle.kz\ngoogle.la\ngoogle.li\ngoogle.lk\ngoogle.lt\ngoogle.lu\ngoogle.lv\ngoogle.md\ngoogle.me\ngoogle.mg\ngoogle.mk\ngoogle.ml\ngoogle.mn\ngoogle.ms\ngoogle.mu\ngoogle.mv\ngoogle.mw\ngoogle.ne\ngoogle.net\ngoogle.nl\ngoogle.no\ngoogle.nr\ngoogle.nu\ngoogle.org\ngoogle.pl\ngoogle.pn\ngoogle.ps\ngoogle.pt\ngoogle.ro\ngoogle.rs\ngoogle.ru\ngoogle.rw\ngoogle.sc\ngoogle.se\ngoogle.sh\ngoogle.si\ngoogle.sk\ngoogle.sm\ngoogle.sn\ngoogle.so\ngoogle.sr\ngoogle.st\ngoogle.td\ngoogle.tg\ngoogle.tk\ngoogle.tl\ngoogle.tm\ngoogle.tn\ngoogle.to\ngoogle.tt\ngoogle.vg\ngoogle.vu\ngoogle.ws'; } | sort | uniq -i >$dnsmasq_gfwlist
}

function update_chnroute {
    #chnroute_url="http://f.ip.cn/rt/chnroutes.txt"
    chnroute_url="https://github.com/17mon/china_ip_list/raw/master/china_ip_list.txt"
    { curl -4sSkL "$chnroute_url"; echo; } | grep -Ev '^\s*$|^\s*#' >$chinadns_chnroute
    echo '-N chnroute hash:net' >$iptables_ipset_file; sed -r 's/^.+$/-A chnroute &/' $chinadns_chnroute >>$iptables_ipset_file
}

function flush_cache {
case "$mode" in
*global|*gfwlist*|*chnroute) pgrep '^dnsmasq$' | xargs kill -HUP;;
tproxy_global_tcp)
if [ $(pgrep -c '^dnsforwarder$') -ne 0 ]; then
pkill '^dnsforwarder$' &>/dev/null
sleep 2
dnsforwarder -q -d -f <(cat <<EOF
LogOn $dnsfwd_log_on
LogFileThresholdLength 5242880
LogFileFolder $dnsfwd_log_dir

UDPLocal 0.0.0.0:53
TCPGroup $dns_remote * no
BlockNegativeResponse true

Hosts file:///etc/hosts
HostsUpdateInterval 3600

UseCache $dnsfwd_cache_on
MemoryCache $dnsfwd_cache_mem
CacheSize $dnsfwd_cache_size
IgnoreTTL $dnsfwd_ignore_ttl
EOF
) &>/dev/null
fi;;
tproxy_chnroute_tcp)
if [ $(pgrep -c '^dnsforwarder$') -ne 0 ]; then
pkill '^dnsforwarder$' &>/dev/null
sleep 2
dnsforwarder -q -d -f <(cat <<EOF
LogOn false
UseCache false
UDPLocal 0.0.0.0:60053
TCPGroup $dns_remote * no
BlockNegativeResponse true
EOF
) &>/dev/null
dnsforwarder -q -d -f <(cat <<EOF
LogOn $dnsfwd_log_on
LogFileThresholdLength 5242880
LogFileFolder $dnsfwd_log_dir

UDPLocal 0.0.0.0:53
UDPGroup 127.0.0.1:65353 * on
BlockNegativeResponse true

Hosts file:///etc/hosts
HostsUpdateInterval 3600

UseCache $dnsfwd_cache_on
MemoryCache $dnsfwd_cache_mem
CacheSize $dnsfwd_cache_size
IgnoreTTL $dnsfwd_ignore_ttl
EOF
) &>/dev/null
fi;;
tun2socks_global_tcp)
if [ $(pgrep -c '^dnsforwarder$') -ne 0 ]; then
pkill '^dnsforwarder$' &>/dev/null
sleep 2
dnsforwarder -q -d -f <(cat <<EOF
LogOn $dnsfwd_log_on
LogFileThresholdLength 5242880
LogFileFolder $dnsfwd_log_dir

UDPLocal 0.0.0.0:53
TCPGroup $dns_remote * $socks5_listen
BlockNegativeResponse true

Hosts file:///etc/hosts
HostsUpdateInterval 3600

UseCache $dnsfwd_cache_on
MemoryCache $dnsfwd_cache_mem
CacheSize $dnsfwd_cache_size
IgnoreTTL $dnsfwd_ignore_ttl
EOF
) &>/dev/null
fi;;
tun2socks_chnroute_tcp)
if [ $(pgrep -c '^dnsforwarder$') -ne 0 ]; then
pkill '^dnsforwarder$' &>/dev/null
sleep 2
dnsforwarder -q -d -f <(cat <<EOF
LogOn false
UseCache false
UDPLocal 0.0.0.0:60053
TCPGroup $dns_remote * $socks5_listen
BlockNegativeResponse true
EOF
) &>/dev/null
dnsforwarder -q -d -f <(cat <<EOF
LogOn $dnsfwd_log_on
LogFileThresholdLength 5242880
LogFileFolder $dnsfwd_log_dir

UDPLocal 0.0.0.0:53
UDPGroup 127.0.0.1:65353 * on
BlockNegativeResponse true

Hosts file:///etc/hosts
HostsUpdateInterval 3600

UseCache $dnsfwd_cache_on
MemoryCache $dnsfwd_cache_mem
CacheSize $dnsfwd_cache_size
IgnoreTTL $dnsfwd_ignore_ttl
EOF
) &>/dev/null
fi;;
esac
}

function start_socks {
case "$mode" in
tproxy*)
    if [ "$server_use_ssr" = 'false' ]; then
        redir_params="-s'$server_addr' -p'$server_port' -m'$server_method' -k'$server_passwd' -b0.0.0.0 -l60080 --no-delay --reuse-port"
        [[ "$mode" != *tcp ]] && redir_params+=' -u'
        [ "$redir_verbose" = 'true' ] && redir_params+=' -v'
        [ "$redir_fast_open" = 'true' ] && redir_params+=' --fast-open'
        eval "nohup ss-redir $redir_params </dev/null &>>'$redir_log' &"

        if [[ "$mode" != *tcp ]]; then
            tunnel_params="-s'$server_addr' -p'$server_port' -m'$server_method' -k'$server_passwd' -b0.0.0.0 -l60053 -L'$dns_remote' -U --no-delay --reuse-port"
            [ "$tunnel_verbose" = 'true' ] && tunnel_params+=' -v'
            eval "nohup ss-tunnel $tunnel_params </dev/null &>>'$tunnel_log' &";
        fi
    else
        redir_params="-s'$server_addr' -p'$server_port' -m'$server_method' -k'$server_passwd' -O'$server_protocol' -o'$server_obfs' -b0.0.0.0 -l60080"
        [ -n "$server_protocol_param" ] && redir_params+=" -G'$server_protocol_param'"
        [ -n "$server_obfs_param" ] && redir_params+=" -g'$server_obfs_param'"
        [[ "$mode" != *tcp ]] && redir_params+=' -u'
        [ "$redir_verbose" = 'true' ] && redir_params+=' -v'
        eval "nohup ssr-redir $redir_params </dev/null &>>'$redir_log' &"

        if [[ "$mode" != *tcp ]]; then
            tunnel_params="-s'$server_addr' -p'$server_port' -m'$server_method' -k'$server_passwd' -O'$server_protocol' -o'$server_obfs' -b0.0.0.0 -l60053 -L'$dns_remote' -U"
            [ -n "$server_protocol_param" ] && tunnel_params+=" -G'$server_protocol_param'"
            [ -n "$server_obfs_param" ] && tunnel_params+=" -g'$server_obfs_param'"
            [ "$tunnel_verbose" = 'true' ] && tunnel_params+=' -v'
            eval "nohup ssr-tunnel $tunnel_params </dev/null &>>'$tunnel_log' &"
        fi
    fi
    ;;
tun2socks*)
    eval "$socks5_runcmd"
    nohup tun2socks -tun-device $tun2socks_tundev -tun-address $tun2socks_address -tun-mask $tun2socks_netmask -tun-gw $tun2socks_gateway -local-socks-addr $socks5_listen -public-only </dev/null &>>"$tun2socks_log" &
    ;;
esac
}

function start_dns {
case "$mode" in
tproxy_global)
    dnsmasq -C <(cat <<EOF
$([ "$dnsmasq_log_on" = 'true' ] && echo 'log-queries')
log-async = 20
log-facility = $dnsmasq_log_file
domain-needed
cache-size = $dnsmasq_cache_size
min-cache-ttl = $dnsmasq_cache_time
no-negcache
no-resolv
port = 53
server = 127.0.0.1#60053
EOF
);;
tproxy_gfwlist)
    dnsmasq -C <(cat <<EOF
$([ "$dnsmasq_log_on" = 'true' ] && echo 'log-queries')
log-async = 20
log-facility = $dnsmasq_log_file
domain-needed
cache-size = $dnsmasq_cache_size
min-cache-ttl = $dnsmasq_cache_time
no-negcache
no-resolv
port = 53
$(for dns in "${dns_direct[@]}"; do echo "server = $dns"; done)
$(perl -pe 's@^.*+$@server=/$&/127.0.0.1#60053\nipset=/$&/gfwlist@' $dnsmasq_gfwlist <(
perl -ne 'print unless m@^\s|\s\n$|^#|^\d++\.\d++\.\d++\.\d++(?:/\d++)?$@' $dnsmasq_gfwlist_ext
))
EOF
);;
tproxy_chnroute)
    chinadns_chnroute_temp=$(mktemp)
    cat $chinadns_chnroute >$chinadns_chnroute_temp
    for dns in "${dns_direct[@]}"; do echo "$dns/32" >>$chinadns_chnroute_temp; done
    chinadns_upstream=$(for dns in "${dns_direct[@]}"; do echo -n "$dns,"; done)
    chinadns_params="-b 0.0.0.0 -p 65353 -s ${chinadns_upstream}127.0.0.1:60053 -c $chinadns_chnroute_temp"
    [ "$chinadns_mutation" = 'true' ] && chinadns_params+=' -m'
    [ "$chinadns_verbose" = 'true' ] && chinadns_params+=' -v'
    nohup chinadns $chinadns_params </dev/null &>>"$chinadns_log" &

    dnsmasq -C <(cat <<EOF
$([ "$dnsmasq_log_on" = 'true' ] && echo 'log-queries')
log-async = 20
log-facility = $dnsmasq_log_file
domain-needed
cache-size = $dnsmasq_cache_size
min-cache-ttl = $dnsmasq_cache_time
no-negcache
no-resolv
port = 53
server = 127.0.0.1#65353
EOF
);;
tproxy_global_tcp)
    mkdir -p /root/.dnsforwarder
    dnsforwarder -q -d -f <(cat <<EOF
LogOn $dnsfwd_log_on
LogFileThresholdLength 5242880
LogFileFolder $dnsfwd_log_dir

UDPLocal 0.0.0.0:53
TCPGroup $dns_remote * no
BlockNegativeResponse true

Hosts file:///etc/hosts
HostsUpdateInterval 3600

UseCache $dnsfwd_cache_on
MemoryCache $dnsfwd_cache_mem
CacheSize $dnsfwd_cache_size
IgnoreTTL $dnsfwd_ignore_ttl
EOF
) &>/dev/null;;
tproxy_gfwlist_tcp)
    dnsforwarder -q -d -f <(cat <<EOF
LogOn false
UseCache false
UDPLocal 0.0.0.0:60053
TCPGroup $dns_remote * no
BlockNegativeResponse true
EOF
) &>/dev/null
    dnsmasq -C <(cat <<EOF
$([ "$dnsmasq_log_on" = 'true' ] && echo 'log-queries')
log-async = 20
log-facility = $dnsmasq_log_file
domain-needed
cache-size = $dnsmasq_cache_size
min-cache-ttl = $dnsmasq_cache_time
no-negcache
no-resolv
port = 53
$(for dns in "${dns_direct[@]}"; do echo "server = $dns"; done)
$(perl -pe 's@^.*+$@server=/$&/127.0.0.1#60053\nipset=/$&/gfwlist@' $dnsmasq_gfwlist <(
perl -ne 'print unless m@^\s|\s\n$|^#|^\d++\.\d++\.\d++\.\d++(?:/\d++)?$@' $dnsmasq_gfwlist_ext
))
EOF
);;
tproxy_chnroute_tcp)
    dnsforwarder -q -d -f <(cat <<EOF
LogOn false
UseCache false
UDPLocal 0.0.0.0:60053
TCPGroup $dns_remote * no
BlockNegativeResponse true
EOF
) &>/dev/null

    chinadns_chnroute_temp=$(mktemp)
    cat $chinadns_chnroute >$chinadns_chnroute_temp
    for dns in "${dns_direct[@]}"; do echo "$dns/32" >>$chinadns_chnroute_temp; done
    chinadns_upstream=$(for dns in "${dns_direct[@]}"; do echo -n "$dns,"; done)
    chinadns_params="-b 0.0.0.0 -p 65353 -s ${chinadns_upstream}127.0.0.1:60053 -c $chinadns_chnroute_temp"
    [ "$chinadns_mutation" = 'true' ] && chinadns_params+=' -m'
    [ "$chinadns_verbose" = 'true' ] && chinadns_params+=' -v'
    nohup chinadns $chinadns_params </dev/null &>>"$chinadns_log" &

    mkdir -p /root/.dnsforwarder
    dnsforwarder -q -d -f <(cat <<EOF
LogOn $dnsfwd_log_on
LogFileThresholdLength 5242880
LogFileFolder $dnsfwd_log_dir

UDPLocal 0.0.0.0:53
UDPGroup 127.0.0.1:65353 * on
BlockNegativeResponse true

Hosts file:///etc/hosts
HostsUpdateInterval 3600

UseCache $dnsfwd_cache_on
MemoryCache $dnsfwd_cache_mem
CacheSize $dnsfwd_cache_size
IgnoreTTL $dnsfwd_ignore_ttl
EOF
) &>/dev/null;;
tun2socks_global)
    dnsmasq -C <(cat <<EOF
$([ "$dnsmasq_log_on" = 'true' ] && echo 'log-queries')
log-async = 20
log-facility = $dnsmasq_log_file
domain-needed
cache-size = $dnsmasq_cache_size
min-cache-ttl = $dnsmasq_cache_time
no-negcache
no-resolv
port = 53
server = ${dns_remote/:/#}
EOF
);;
tun2socks_gfwlist)
    dnsmasq -C <(cat <<EOF
$([ "$dnsmasq_log_on" = 'true' ] && echo 'log-queries')
log-async = 20
log-facility = $dnsmasq_log_file
domain-needed
cache-size = $dnsmasq_cache_size
min-cache-ttl = $dnsmasq_cache_time
no-negcache
no-resolv
port = 53
$(for dns in "${dns_direct[@]}"; do echo "server = $dns"; done)
$(perl -pe "s@^.*+\$@server=/$&/${dns_remote/:/#}\nipset=/$&/gfwlist@" $dnsmasq_gfwlist <(
perl -ne 'print unless m@^\s|\s\n$|^#|^\d++\.\d++\.\d++\.\d++(?:/\d++)?$@' $dnsmasq_gfwlist_ext
))
EOF
);;
tun2socks_chnroute)
    chinadns_chnroute_temp=$(mktemp)
    cat $chinadns_chnroute >$chinadns_chnroute_temp
    for dns in "${dns_direct[@]}"; do echo "$dns/32" >>$chinadns_chnroute_temp; done
    chinadns_upstream=$(for dns in "${dns_direct[@]}"; do echo -n "$dns,"; done)
    chinadns_params="-b 0.0.0.0 -p 60053 -s ${chinadns_upstream}${dns_remote} -c $chinadns_chnroute_temp"
    [ "$chinadns_mutation" = 'true' ] && chinadns_params+=' -m'
    [ "$chinadns_verbose" = 'true' ] && chinadns_params+=' -v'
    nohup chinadns $chinadns_params </dev/null &>>"$chinadns_log" &

    dnsmasq -C <(cat <<EOF
$([ "$dnsmasq_log_on" = 'true' ] && echo 'log-queries')
log-async = 20
log-facility = $dnsmasq_log_file
domain-needed
cache-size = $dnsmasq_cache_size
min-cache-ttl = $dnsmasq_cache_time
no-negcache
no-resolv
port = 53
server = 127.0.0.1#60053
EOF
);;
tun2socks_global_tcp)
    mkdir -p /root/.dnsforwarder
    dnsforwarder -q -d -f <(cat <<EOF
LogOn $dnsfwd_log_on
LogFileThresholdLength 5242880
LogFileFolder $dnsfwd_log_dir

UDPLocal 0.0.0.0:53
TCPGroup $dns_remote * $socks5_listen
BlockNegativeResponse true

Hosts file:///etc/hosts
HostsUpdateInterval 3600

UseCache $dnsfwd_cache_on
MemoryCache $dnsfwd_cache_mem
CacheSize $dnsfwd_cache_size
IgnoreTTL $dnsfwd_ignore_ttl
EOF
) &>/dev/null;;
tun2socks_gfwlist_tcp)
    dnsforwarder -q -d -f <(cat <<EOF
LogOn false
UseCache false
UDPLocal 0.0.0.0:60053
TCPGroup $dns_remote * $socks5_listen
BlockNegativeResponse true
EOF
) &>/dev/null
    dnsmasq -C <(cat <<EOF
$([ "$dnsmasq_log_on" = 'true' ] && echo 'log-queries')
log-async = 20
log-facility = $dnsmasq_log_file
domain-needed
cache-size = $dnsmasq_cache_size
min-cache-ttl = $dnsmasq_cache_time
no-negcache
no-resolv
port = 53
$(for dns in "${dns_direct[@]}"; do echo "server = $dns"; done)
$(perl -pe 's@^.*+$@server=/$&/127.0.0.1#60053\nipset=/$&/gfwlist@' $dnsmasq_gfwlist <(
perl -ne 'print unless m@^\s|\s\n$|^#|^\d++\.\d++\.\d++\.\d++(?:/\d++)?$@' $dnsmasq_gfwlist_ext
))
EOF
);;
tun2socks_chnroute_tcp)
    dnsforwarder -q -d -f <(cat <<EOF
LogOn false
UseCache false
UDPLocal 0.0.0.0:60053
TCPGroup $dns_remote * $socks5_listen
BlockNegativeResponse true
EOF
) &>/dev/null

    chinadns_chnroute_temp=$(mktemp)
    cat $chinadns_chnroute >$chinadns_chnroute_temp
    for dns in "${dns_direct[@]}"; do echo "$dns/32" >>$chinadns_chnroute_temp; done
    chinadns_upstream=$(for dns in "${dns_direct[@]}"; do echo -n "$dns,"; done)
    chinadns_params="-b 0.0.0.0 -p 65353 -s ${chinadns_upstream}127.0.0.1:60053 -c $chinadns_chnroute_temp"
    [ "$chinadns_mutation" = 'true' ] && chinadns_params+=' -m'
    [ "$chinadns_verbose" = 'true' ] && chinadns_params+=' -v'
    nohup chinadns $chinadns_params </dev/null &>>"$chinadns_log" &

    mkdir -p /root/.dnsforwarder
    dnsforwarder -q -d -f <(cat <<EOF
LogOn $dnsfwd_log_on
LogFileThresholdLength 5242880
LogFileFolder $dnsfwd_log_dir

UDPLocal 0.0.0.0:53
UDPGroup 127.0.0.1:65353 * on
BlockNegativeResponse true

Hosts file:///etc/hosts
HostsUpdateInterval 3600

UseCache $dnsfwd_cache_on
MemoryCache $dnsfwd_cache_mem
CacheSize $dnsfwd_cache_size
IgnoreTTL $dnsfwd_ignore_ttl
EOF
) &>/dev/null;;
esac
}

function start_rule {
case "$mode" in
tproxy_global*|tproxy_chnroute*)
    iptables -t nat -F OUTPUT
    iptables -t nat -F PREROUTING
    iptables -t nat -F POSTROUTING
    iptables -t nat -F SS-TCP &>/dev/null
    iptables -t nat -X SS-TCP &>/dev/null

    iptables -t nat -N SS-TCP
    iptables -t nat -A SS-TCP -d 0/8 -j RETURN
    iptables -t nat -A SS-TCP -d 10/8 -j RETURN
    iptables -t nat -A SS-TCP -d 127/8 -j RETURN
    iptables -t nat -A SS-TCP -d 169.254/16 -j RETURN
    iptables -t nat -A SS-TCP -d 172.16/12 -j RETURN
    iptables -t nat -A SS-TCP -d 192.168/16 -j RETURN
    for cidr in "${iptables_intranet_nonstd[@]}"; do
        iptables -t nat -A SS-TCP -d $cidr -j RETURN
    done
    iptables -t nat -A SS-TCP -d 224/4 -j RETURN
    iptables -t nat -A SS-TCP -d 240/4 -j RETURN
    iptables -t nat -A SS-TCP -d $server_addr -j RETURN
    if [[ "$mode" == *chnroute* ]]; then
        ipset -X chnroute &>/dev/null
        ipset -R <$iptables_ipset_file
        iptables -t nat -A SS-TCP -m set --match-set chnroute dst -j RETURN
    fi
    iptables -t nat -A SS-TCP -p tcp -j REDIRECT --to-ports 60080

    if [[ "$mode" != *tcp ]]; then
        iptables -t mangle -F PREROUTING
    	iptables -t mangle -F SS-UDP &>/dev/null
    	iptables -t mangle -X SS-UDP &>/dev/null

        iptables -t mangle -N SS-UDP
        iptables -t mangle -A SS-UDP -d 0/8 -j RETURN
        iptables -t mangle -A SS-UDP -d 10/8 -j RETURN
        iptables -t mangle -A SS-UDP -d 127/8 -j RETURN
        iptables -t mangle -A SS-UDP -d 169.254/16 -j RETURN
        iptables -t mangle -A SS-UDP -d 172.16/12 -j RETURN
        iptables -t mangle -A SS-UDP -d 192.168/16 -j RETURN
        for cidr in "${iptables_intranet_nonstd[@]}"; do
            iptables -t mangle -A SS-UDP -d $cidr -j RETURN
        done
        iptables -t mangle -A SS-UDP -d 224/4 -j RETURN
        iptables -t mangle -A SS-UDP -d 240/4 -j RETURN
        iptables -t mangle -A SS-UDP -d $server_addr -j RETURN
        [[ "$mode" == *chnroute* ]] && iptables -t mangle -A SS-UDP -m set --match-set chnroute dst -j RETURN
        iptables -t mangle -A SS-UDP -p udp -j TPROXY --tproxy-mark $iptables_pbr_fwmark --on-ip 127.0.0.1 --on-port 60080

        ip route add local 0/0 dev lo table $iptables_pbr_number
        ip rule add fwmark $iptables_pbr_fwmark table $iptables_pbr_number
    fi

    iptables -t nat -A OUTPUT -p tcp -j SS-TCP
    for intranet in "${iptables_intranet[@]}"; do
        if [[ "$mode" == *tcp ]]; then
            iptables -t nat -A PREROUTING -p tcp -s $intranet -j SS-TCP
            iptables -t nat -A PREROUTING -p udp -s $intranet ! -d $intranet --dport 53 -j REDIRECT --to-ports 53
        else
            iptables -t mangle -A PREROUTING -p udp -s $intranet ! -d $intranet --dport 53 -j ACCEPT
            iptables -t nat -A PREROUTING -p udp -s $intranet ! -d $intranet --dport 53 -j REDIRECT --to-ports 53
            iptables -t mangle -A PREROUTING -p udp -s $intranet -j SS-UDP
            iptables -t nat -A PREROUTING -p tcp -s $intranet -j SS-TCP
        fi
        iptables -t nat -A POSTROUTING -s $intranet ! -d $intranet -j MASQUERADE
    done
    ;;
tproxy_gfwlist*)
    iptables -t nat -F OUTPUT
    iptables -t nat -F PREROUTING
    iptables -t nat -F POSTROUTING
    iptables -t nat -F SS-TCP &>/dev/null
    iptables -t nat -X SS-TCP &>/dev/null

    iptables -t nat -N SS-TCP
    ipset -N gfwlist hash:net &>/dev/null
    perl -ne 'print if m@^\d++\.\d++\.\d++\.\d++(?:/\d++)?$@' $dnsmasq_gfwlist_ext | xargs -n1 ipset -A gfwlist &>/dev/null
    [[ "$mode" == *tcp ]] && iptables -t nat -A SS-TCP -p tcp -d ${dns_remote%%:*} -j REDIRECT --to-ports 60080
    iptables -t nat -A SS-TCP -p tcp -m set --match-set gfwlist dst -j REDIRECT --to-ports 60080

    if [[ "$mode" != *tcp ]]; then
        iptables -t mangle -F PREROUTING
    	iptables -t mangle -F SS-UDP &>/dev/null
    	iptables -t mangle -X SS-UDP &>/dev/null

        iptables -t mangle -N SS-UDP
        iptables -t mangle -A SS-UDP -p udp -m set --match-set gfwlist dst -j TPROXY --tproxy-mark $iptables_pbr_fwmark --on-ip 127.0.0.1 --on-port 60080

        ip route add local 0/0 dev lo table $iptables_pbr_number
        ip rule add fwmark $iptables_pbr_fwmark table $iptables_pbr_number
    fi

    iptables -t nat -A OUTPUT -p tcp -j SS-TCP
    for intranet in "${iptables_intranet[@]}"; do
        if [[ "$mode" == *tcp ]]; then
            iptables -t nat -A PREROUTING -p tcp -s $intranet -j SS-TCP
            iptables -t nat -A PREROUTING -p udp -s $intranet ! -d $intranet --dport 53 -j REDIRECT --to-ports 53
        else
            iptables -t mangle -A PREROUTING -p udp -s $intranet ! -d $intranet --dport 53 -j ACCEPT
            iptables -t nat -A PREROUTING -p udp -s $intranet ! -d $intranet --dport 53 -j REDIRECT --to-ports 53
            iptables -t mangle -A PREROUTING -p udp -s $intranet -j SS-UDP
            iptables -t nat -A PREROUTING -p tcp -s $intranet -j SS-TCP
        fi
        iptables -t nat -A POSTROUTING -s $intranet ! -d $intranet -j MASQUERADE
    done
    ;;
tun2socks_global*|tun2socks_chnroute*)
    iptables -t mangle -F OUTPUT
    iptables -t mangle -F PREROUTING
    iptables -t mangle -F TUN2SOCKS &>/dev/null
    iptables -t mangle -X TUN2SOCKS &>/dev/null
    iptables -t nat -F PREROUTING
    iptables -t nat -F POSTROUTING

    iptables -t mangle -N TUN2SOCKS
    iptables -t mangle -A TUN2SOCKS -d 0/8 -j RETURN
    iptables -t mangle -A TUN2SOCKS -d 10/8 -j RETURN
    iptables -t mangle -A TUN2SOCKS -d 127/8 -j RETURN
    iptables -t mangle -A TUN2SOCKS -d 169.254/16 -j RETURN
    iptables -t mangle -A TUN2SOCKS -d 172.16/12 -j RETURN
    iptables -t mangle -A TUN2SOCKS -d 192.168/16 -j RETURN
    for cidr in "${iptables_intranet_nonstd[@]}"; do
        iptables -t mangle -A TUN2SOCKS -d $cidr -j RETURN
    done
    iptables -t mangle -A TUN2SOCKS -d 224/4 -j RETURN
    iptables -t mangle -A TUN2SOCKS -d 240/4 -j RETURN
    iptables -t mangle -A TUN2SOCKS -d $socks5_remote -j RETURN
    if [[ "$mode" == *chnroute* ]]; then
        ipset -X chnroute &>/dev/null
        ipset -R <$iptables_ipset_file
        iptables -t mangle -A TUN2SOCKS -m set --match-set chnroute dst -j RETURN
    fi
    iptables -t mangle -A TUN2SOCKS -j MARK --set-mark $iptables_pbr_fwmark

    ip route add 0/0 via $tun2socks_gateway dev $tun2socks_tundev table $iptables_pbr_number
    ip rule add fwmark $iptables_pbr_fwmark table $iptables_pbr_number

    iptables -t mangle -A OUTPUT -p tcp -j TUN2SOCKS
    [[ "$mode" != *tcp ]] && iptables -t mangle -A OUTPUT -p udp -j TUN2SOCKS

    for intranet in "${iptables_intranet[@]}"; do
        if [[ "$mode" == *tcp ]]; then
            iptables -t mangle -A PREROUTING -p tcp -s $intranet -j TUN2SOCKS
            iptables -t nat -A PREROUTING -p udp -s $intranet ! -d $intranet --dport 53 -j REDIRECT --to-ports 53
        else
            iptables -t mangle -A PREROUTING -p udp -s $intranet ! -d $intranet --dport 53 -j ACCEPT
            iptables -t nat -A PREROUTING -p udp -s $intranet ! -d $intranet --dport 53 -j REDIRECT --to-ports 53
            iptables -t mangle -A PREROUTING -p tcp -s $intranet -j TUN2SOCKS
            iptables -t mangle -A PREROUTING -p udp -s $intranet -j TUN2SOCKS
        fi
        iptables -t nat -A POSTROUTING -s $intranet ! -d $intranet -j MASQUERADE
    done
    ;;
tun2socks_gfwlist*)
    iptables -t mangle -F OUTPUT
    iptables -t mangle -F PREROUTING
    iptables -t mangle -F TUN2SOCKS &>/dev/null
    iptables -t mangle -X TUN2SOCKS &>/dev/null
    iptables -t nat -F PREROUTING
    iptables -t nat -F POSTROUTING

    iptables -t mangle -N TUN2SOCKS
    ipset -N gfwlist hash:net &>/dev/null
    perl -ne 'print if m@^\d++\.\d++\.\d++\.\d++(?:/\d++)?$@' $dnsmasq_gfwlist_ext | xargs -n1 ipset -A gfwlist &>/dev/null
    [[ "$mode" != *tcp ]] && iptables -t mangle -A TUN2SOCKS -p udp -d ${dns_remote%%:*} -j MARK --set-mark $iptables_pbr_fwmark
    iptables -t mangle -A TUN2SOCKS -m set --match-set gfwlist dst -j MARK --set-mark $iptables_pbr_fwmark

    ip route add 0/0 via $tun2socks_gateway dev $tun2socks_tundev table $iptables_pbr_number
    ip rule add fwmark $iptables_pbr_fwmark table $iptables_pbr_number

    iptables -t mangle -A OUTPUT -p tcp -j TUN2SOCKS
    [[ "$mode" != *tcp ]] && iptables -t mangle -A OUTPUT -p udp -j TUN2SOCKS

    for intranet in "${iptables_intranet[@]}"; do
        if [[ "$mode" == *tcp ]]; then
            iptables -t mangle -A PREROUTING -p tcp -s $intranet -j TUN2SOCKS
            iptables -t nat -A PREROUTING -p udp -s $intranet ! -d $intranet --dport 53 -j REDIRECT --to-ports 53
        else
            iptables -t mangle -A PREROUTING -p udp -s $intranet ! -d $intranet --dport 53 -j ACCEPT
            iptables -t nat -A PREROUTING -p udp -s $intranet ! -d $intranet --dport 53 -j REDIRECT --to-ports 53
            iptables -t mangle -A PREROUTING -p tcp -s $intranet -j TUN2SOCKS
            iptables -t mangle -A PREROUTING -p udp -s $intranet -j TUN2SOCKS
        fi
        iptables -t nat -A POSTROUTING -s $intranet ! -d $intranet -j MASQUERADE
    done
    ;;
esac
}

function start_kopts {
    [ $(sysctl net.ipv4.ip_forward | awk '{print $3}') -ne 1 ] && sysctl -w net.ipv4.ip_forward=1
    [[ "$mode" == tun2socks* ]] && {
        [ $(sysctl net.ipv4.conf.$tun2socks_tundev.rp_filter | awk '{print $3}') -ne 2 ] &&
            sysctl -w net.ipv4.conf.$tun2socks_tundev.rp_filter=2
    }
}

function dns_proxy {
cat <<EOF >/etc/resolv.conf
# Generated by ss-tproxy at $(date '+%F %T')
nameserver 127.0.0.1
EOF
}

function dns_normal {
cat <<EOF >/etc/resolv.conf
# Generated by ss-tproxy at $(date '+%F %T')
$(for dns in "${dns_direct[@]}"; do echo "nameserver $dns"; done)
EOF
}

function start {
    check_depend
    dns_normal
    start_socks
    start_dns
    start_rule
    start_kopts
    dns_proxy
    rm -f $chinadns_chnroute_temp &>/dev/null
}

function stop {
    check_depend
    dns_normal

    iptables -t nat -F OUTPUT            
    iptables -t nat -F PREROUTING
    iptables -t nat -F POSTROUTING
    iptables -t nat -F SS-TCP &>/dev/null
    iptables -t nat -X SS-TCP &>/dev/null

    iptables -t mangle -F OUTPUT
    iptables -t mangle -F PREROUTING
    iptables -t mangle -F SS-UDP &>/dev/null
    iptables -t mangle -X SS-UDP &>/dev/null
    iptables -t mangle -F TUN2SOCKS &>/dev/null
    iptables -t mangle -X TUN2SOCKS &>/dev/null

    for intranet in "${iptables_intranet[@]}"; do
        iptables -t nat -A PREROUTING -p udp -s $intranet -d $intranet --dport 53 -j DNAT --to-destination ${dns_direct[0]}
        iptables -t nat -A POSTROUTING -s $intranet ! -d $intranet -j MASQUERADE
    done

    ipset -X chnroute &>/dev/null

    ip rule show | grep "fwmark $iptables_pbr_fwmark" | awk -F':' '{print $1}' | xargs -n1 ip rule del pref &>/dev/null
    ip route flush table $iptables_pbr_number

    pkill -9 '^dnsmasq$'
    pkill -9 '^chinadns$'
    pkill -9 '^dnsforwarder$'

    pkill -9 '^ss-redir$'
    pkill -9 '^ss-tunnel$'
    pkill -9 '^ssr-redir$'
    pkill -9 '^ssr-tunnel$'
    pkill -9 '^tun2socks$'

    port=$(echo $socks5_listen | awk -F: '{print $2}')
    ss -lnptu | grep ":$port\s" | grep -Eo 'pid=[0-9]+' | awk -F= '{print $2}' | sort -n | uniq | xargs kill -9 &>/dev/null
}

function status {
case "$mode" in
    tproxy_global)
        echo "mode:          tproxy_global"
        if [ "$server_use_ssr" != 'true' ]; then
            [ $(pgrep -c '^ss-redir$') -ne 0 ] && echo -e "ss-redir:          \e[32m[running]\e[0m" || echo -e "ss-redir:          \e[35m[stopped]\e[0m"
            [ $(pgrep -c '^ss-tunnel$') -ne 0 ] && echo -e "ss-tunnel:         \e[32m[running]\e[0m" || echo -e "ss-tunnel:         \e[35m[stopped]\e[0m"
        else
            [ $(pgrep -c '^ssr-redir$') -ne 0 ] && echo -e "ssr-redir:         \e[32m[running]\e[0m" || echo -e "ssr-redir:         \e[35m[stopped]\e[0m"
            [ $(pgrep -c '^ssr-tunnel$') -ne 0 ] && echo -e "ssr-tunnel:        \e[32m[running]\e[0m" || echo -e "ssr-tunnel:        \e[35m[stopped]\e[0m"
        fi
        [ $(pgrep -c '^dnsmasq$') -ne 0 ] && echo -e "dnsmasq:           \e[32m[running]\e[0m" || echo -e "dnsmasq:           \e[35m[stopped]\e[0m"
        ;;
    tproxy_global_tcp)
        echo "mode:      tproxy_global_tcp"
        if [ "$server_use_ssr" != 'true' ]; then
            [ $(pgrep -c '^ss-redir$') -ne 0 ] && echo -e "ss-redir:          \e[32m[running]\e[0m" || echo -e "ss-redir:          \e[35m[stopped]\e[0m"
        else
            [ $(pgrep -c '^ssr-redir$') -ne 0 ] && echo -e "ssr-redir:         \e[32m[running]\e[0m" || echo -e "ssr-redir:         \e[35m[stopped]\e[0m"
        fi
        [ $(pgrep -c '^dnsforwarder$') -ne 0 ] && echo -e "dnsforwarder:      \e[32m[running]\e[0m" || echo -e "dnsforwarder:      \e[35m[stopped]\e[0m"
        ;;
    tproxy_gfwlist)
        echo "mode:         tproxy_gfwlist"
        if [ "$server_use_ssr" != 'true' ]; then
            [ $(pgrep -c '^ss-redir$') -ne 0 ] && echo -e "ss-redir:          \e[32m[running]\e[0m" || echo -e "ss-redir:          \e[35m[stopped]\e[0m"
            [ $(pgrep -c '^ss-tunnel$') -ne 0 ] && echo -e "ss-tunnel:         \e[32m[running]\e[0m" || echo -e "ss-tunnel:         \e[35m[stopped]\e[0m"
        else
            [ $(pgrep -c '^ssr-redir$') -ne 0 ] && echo -e "ssr-redir:         \e[32m[running]\e[0m" || echo -e "ssr-redir:         \e[35m[stopped]\e[0m"
            [ $(pgrep -c '^ssr-tunnel$') -ne 0 ] && echo -e "ssr-tunnel:        \e[32m[running]\e[0m" || echo -e "ssr-tunnel:        \e[35m[stopped]\e[0m"
        fi
        [ $(pgrep -c '^dnsmasq$') -ne 0 ] && echo -e "dnsmasq:           \e[32m[running]\e[0m" || echo -e "dnsmasq:           \e[35m[stopped]\e[0m"
        ;;
    tproxy_gfwlist_tcp)
        echo "mode:     tproxy_gfwlist_tcp"
        if [ "$server_use_ssr" != 'true' ]; then
            [ $(pgrep -c '^ss-redir$') -ne 0 ] && echo -e "ss-redir:          \e[32m[running]\e[0m" || echo -e "ss-redir:          \e[35m[stopped]\e[0m"
        else
            [ $(pgrep -c '^ssr-redir$') -ne 0 ] && echo -e "ssr-redir:         \e[32m[running]\e[0m" || echo -e "ssr-redir:         \e[35m[stopped]\e[0m"
        fi
        [ $(pgrep -c '^dnsforwarder$') -ne 0 ] && echo -e "dnsforwarder:      \e[32m[running]\e[0m" || echo -e "dnsforwarder:      \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^dnsmasq$') -ne 0 ] && echo -e "dnsmasq:           \e[32m[running]\e[0m" || echo -e "dnsmasq:           \e[35m[stopped]\e[0m"
        ;;
    tproxy_chnroute)
        echo "mode:        tproxy_chnroute"
        if [ "$server_use_ssr" != 'true' ]; then
            [ $(pgrep -c '^ss-redir$') -ne 0 ] && echo -e "ss-redir:          \e[32m[running]\e[0m" || echo -e "ss-redir:          \e[35m[stopped]\e[0m"
            [ $(pgrep -c '^ss-tunnel$') -ne 0 ] && echo -e "ss-tunnel:         \e[32m[running]\e[0m" || echo -e "ss-tunnel:         \e[35m[stopped]\e[0m"
        else
            [ $(pgrep -c '^ssr-redir$') -ne 0 ] && echo -e "ssr-redir:         \e[32m[running]\e[0m" || echo -e "ssr-redir:         \e[35m[stopped]\e[0m"
            [ $(pgrep -c '^ssr-tunnel$') -ne 0 ] && echo -e "ssr-tunnel:        \e[32m[running]\e[0m" || echo -e "ssr-tunnel:        \e[35m[stopped]\e[0m"
        fi
        [ $(pgrep -c '^chinadns$') -ne 0 ] && echo -e "chinadns:          \e[32m[running]\e[0m" || echo -e "chinadns:          \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^dnsmasq$') -ne 0 ] && echo -e "dnsmasq:           \e[32m[running]\e[0m" || echo -e "dnsmasq:           \e[35m[stopped]\e[0m"
        ;;
    tproxy_chnroute_tcp)
        echo "mode:    tproxy_chnroute_tcp"
        if [ "$server_use_ssr" != 'true' ]; then
            [ $(pgrep -c '^ss-redir$') -ne 0 ] && echo -e "ss-redir:          \e[32m[running]\e[0m" || echo -e "ss-redir:          \e[35m[stopped]\e[0m"
        else
            [ $(pgrep -c '^ssr-redir$') -ne 0 ] && echo -e "ssr-redir:         \e[32m[running]\e[0m" || echo -e "ssr-redir:         \e[35m[stopped]\e[0m"
        fi
        [ $(ss -lnpu | grep ':60053\s' | wc -l) -ne 0 ] && echo -e "dnsforwarder0:     \e[32m[running]\e[0m" || echo -e "dnsforwarder0:     \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^chinadns$') -ne 0 ] && echo -e "chinadns:          \e[32m[running]\e[0m" || echo -e "chinadns:          \e[35m[stopped]\e[0m"
        [ $(ss -lnpu | grep ':53\s' | wc -l) -ne 0 ] && echo -e "dnsforwarder1:     \e[32m[running]\e[0m" || echo -e "dnsforwarder1:     \e[35m[stopped]\e[0m"
        ;;
    tun2socks_global)
        echo "mode:       tun2socks_global"
        port=$(echo $socks5_listen | awk -F: '{print $2}')
        [ $(ss -lnpt | grep ":$port\s" | wc -l) -ne 0 ] && echo -e "socks5/tcp:        \e[32m[running]\e[0m" || echo -e "socks5/tcp:        \e[35m[stopped]\e[0m"
        [ $(ss -lnpu | grep ":$port\s" | wc -l) -ne 0 ] && echo -e "socks5/udp:        \e[32m[running]\e[0m" || echo -e "socks5/udp:        \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^tun2socks$') -ne 0 ] && echo -e "tun2socks:         \e[32m[running]\e[0m" || echo -e "tun2socks:         \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^dnsmasq$') -ne 0 ] && echo -e "dnsmasq:           \e[32m[running]\e[0m" || echo -e "dnsmasq:           \e[35m[stopped]\e[0m"
        ;;
    tun2socks_global_tcp)
        echo "mode:   tun2socks_global_tcp"
        port=$(echo $socks5_listen | awk -F: '{print $2}')
        [ $(ss -lnpt | grep ":$port\s" | wc -l) -ne 0 ] && echo -e "socks5/tcp:        \e[32m[running]\e[0m" || echo -e "socks5/tcp:        \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^tun2socks$') -ne 0 ] && echo -e "tun2socks:         \e[32m[running]\e[0m" || echo -e "tun2socks:         \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^dnsforwarder$') -ne 0 ] && echo -e "dnsforwarder:      \e[32m[running]\e[0m" || echo -e "dnsforwarder:      \e[35m[stopped]\e[0m"
        ;;
    tun2socks_gfwlist)
        echo "mode:      tun2socks_gfwlist"
        port=$(echo $socks5_listen | awk -F: '{print $2}')
        [ $(ss -lnpt | grep ":$port\s" | wc -l) -ne 0 ] && echo -e "socks5/tcp:        \e[32m[running]\e[0m" || echo -e "socks5/tcp:        \e[35m[stopped]\e[0m"
        [ $(ss -lnpu | grep ":$port\s" | wc -l) -ne 0 ] && echo -e "socks5/udp:        \e[32m[running]\e[0m" || echo -e "socks5/udp:        \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^tun2socks$') -ne 0 ] && echo -e "tun2socks:         \e[32m[running]\e[0m" || echo -e "tun2socks:         \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^dnsmasq$') -ne 0 ] && echo -e "dnsmasq:           \e[32m[running]\e[0m" || echo -e "dnsmasq:           \e[35m[stopped]\e[0m"
        ;;
    tun2socks_gfwlist_tcp)
        echo "mode:  tun2socks_gfwlist_tcp"
        port=$(echo $socks5_listen | awk -F: '{print $2}')
        [ $(ss -lnpt | grep ":$port\s" | wc -l) -ne 0 ] && echo -e "socks5/tcp:        \e[32m[running]\e[0m" || echo -e "socks5/tcp:        \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^tun2socks$') -ne 0 ] && echo -e "tun2socks:         \e[32m[running]\e[0m" || echo -e "tun2socks:         \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^dnsforwarder$') -ne 0 ] && echo -e "dnsforwarder:      \e[32m[running]\e[0m" || echo -e "dnsforwarder:      \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^dnsmasq$') -ne 0 ] && echo -e "dnsmasq:           \e[32m[running]\e[0m" || echo -e "dnsmasq:           \e[35m[stopped]\e[0m"
        ;;
    tun2socks_chnroute)
        echo "mode:     tun2socks_chnroute"
        port=$(echo $socks5_listen | awk -F: '{print $2}')
        [ $(ss -lnpt | grep ":$port\s" | wc -l) -ne 0 ] && echo -e "socks5/tcp:        \e[32m[running]\e[0m" || echo -e "socks5/tcp:        \e[35m[stopped]\e[0m"
        [ $(ss -lnpu | grep ":$port\s" | wc -l) -ne 0 ] && echo -e "socks5/udp:        \e[32m[running]\e[0m" || echo -e "socks5/udp:        \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^tun2socks$') -ne 0 ] && echo -e "tun2socks:         \e[32m[running]\e[0m" || echo -e "tun2socks:         \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^chinadns$') -ne 0 ] && echo -e "chinadns:          \e[32m[running]\e[0m" || echo -e "chinadns:          \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^dnsmasq$') -ne 0 ] && echo -e "dnsmasq:           \e[32m[running]\e[0m" || echo -e "dnsmasq:           \e[35m[stopped]\e[0m"
        ;;
    tun2socks_chnroute_tcp)
        echo "mode: tun2socks_chnroute_tcp"
        port=$(echo $socks5_listen | awk -F: '{print $2}')
        [ $(ss -lnpt | grep ":$port\s" | wc -l) -ne 0 ] && echo -e "socks5/tcp:        \e[32m[running]\e[0m" || echo -e "socks5/tcp:        \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^tun2socks$') -ne 0 ] && echo -e "tun2socks:         \e[32m[running]\e[0m" || echo -e "tun2socks:         \e[35m[stopped]\e[0m"
        [ $(ss -lnpu | grep ':60053\s' | wc -l) -ne 0 ] && echo -e "dnsforwarder0:     \e[32m[running]\e[0m" || echo -e "dnsforwarder0:     \e[35m[stopped]\e[0m"
        [ $(pgrep -c '^chinadns$') -ne 0 ] && echo -e "chinadns:          \e[32m[running]\e[0m" || echo -e "chinadns:          \e[35m[stopped]\e[0m"
        [ $(ss -lnpu | grep ':53\s' | wc -l) -ne 0 ] && echo -e "dnsforwarder1:     \e[32m[running]\e[0m" || echo -e "dnsforwarder1:     \e[35m[stopped]\e[0m"
        ;;
esac
}

function usage {
cat <<EOF
Usage: ss-tproxy <COMMAND>
COMMAND := {
    start               start ss-tproxy
    stop                stop ss-tproxy
    restart             restart ss-tproxy
    status              status of ss-tproxy
    flush-cache         flush dns cache
    update-gfwlist      update gfwlist
    update-chnroute     update chnroute
    check-depend        check dependency
    help                show this help and exit
}
Issues/Bug report: zfl9.com@gmail.com (Otokaze)
See also https://www.zfl9.com/ss-redir.html for more details.
EOF
}

case $1 in
    start)      start; status;;
    stop)       stop; status;;
    status)     status;;
    r*)         stop; status; echo; start; status;;
    f*)         flush_cache;;
    update-g*)  update_gfwlist;;
    update-c*)  update_chnroute;;
    c*)         check_depend;;
    h*)         usage;;
    *)          usage; exit 1;;
esac
