Created
October 8, 2014 01:31
-
-
Save aa65535/19bb817a9a21169e4aa1 to your computer and use it in GitHub Desktop.
blacklist mode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# Get argument | |
getopts :c: opt && CONFIG=$OPTARG | |
getopts :i: opt && IGNORE=$OPTARG | |
# Check argument | |
[ -z $CONFIG ] || [ -z $IGNORE ] && { | |
echo "Missing argument" | |
exit 128 | |
} | |
# Check configuration files | |
for C in $CONFIG $IGNORE; do | |
[ ! -f $C ] && echo "$C not found." && exit 1 | |
done | |
# Get variable | |
eval $(awk -F'[,:]' '{ | |
for (i=1; i<=NF; i++) { | |
if ($i ~ /server\042/) { | |
printf("server=%s;", $(i+1)) | |
} | |
if ($i ~ /local_port\042/) { | |
printf("local_port=%s;", $(i+1)) | |
} | |
} | |
}' $CONFIG | tr -d '" ') | |
# Check variable | |
[ -z $server ] || [ -z $local_port ] && { | |
echo "Invalid $CONFIG." | |
exit 128 | |
} | |
# Use iptables | |
iptab_r() { | |
HEAD="*nat\n\ | |
:SHADOWSOCKS - [0:0]\n\ | |
-A PREROUTING -p tcp -j SHADOWSOCKS\n" | |
TAIL="\n\ | |
-A SHADOWSOCKS -p tcp -j RETURN\n\ | |
COMMIT" | |
# Read the ignore list | |
BODY=$(awk -v port="$local_port" '$1 ~ /^([0-9]{1,3}\.){3}[0-9]{1,3}/ { | |
printf("-A SHADOWSOCKS -d %s -j REDIRECT --to-ports %s\n", $1,port) | |
}' $IGNORE) | |
# Apply the rules | |
/etc/init.d/firewall restart>/dev/null 2>&1 | |
echo -e "$HEAD$BODY$TAIL" | iptables-restore -n | |
exit $? | |
} | |
# Use ipset | |
ipset_r() { | |
HEAD="create shadowsocks hash:net\n" | |
# Read the ignore list | |
BODY=$(awk '$1 ~ /^([0-9]{1,3}\.){3}[0-9]{1,3}/ { | |
printf("add shadowsocks %s\n", $1) | |
}' $IGNORE) | |
# Apply the rules | |
echo -e "$HEAD$BODY" | ipset -R && \ | |
iptables -t nat -A PREROUTING -p tcp \ | |
-m set --match-set shadowsocks dst \ | |
-j REDIRECT --to-ports $local_port | |
return $? | |
} | |
# Catch error codes | |
ipset -X shadowsocks>/dev/null 2>&1 | |
# Select rules mode | |
[ "$?" = 127 ] && iptab_r | |
ipset_r || iptab_r | |
exit $? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment