Compare commits

...

327 Commits
rm ... patch-1

Author SHA1 Message Date
glzjin 87f91d3e62 refine redirect, forbidden list will not work when redirect rule work 10 years ago
glzjin 938a3246ba Support redirect rule
Syntax:

match_hostname_regex:port(* means match all port)#redirect_dist_host:redirect_port

and in the config.json(user-config.json) redirect param should be a list,

for example

```
"redirect": ["*:8080#zhaoj.in:80","zhaojin97.cn:80#127.0.0.1:80","*#pku.edu.cn:80"]
```

This example means abnormal connection which connect to port 8080 will be redirected to zhaoj.in:80,and if there a http request with hostname zhaojin97.cn(you can set hosts file to test it) will be redirected to 127.0.0.1:80,and the rest of abnormal connection will be redirect to pku.edu.cn:80
10 years ago
shoaly bdee67b856 create a Dockerfile for ssr (#143)
by this dockerfile, make it easy to run ssr-server on docker server
10 years ago
破娃酱 e048e224d0 Do not return empty list if raise exception 10 years ago
破娃酱 d45ba8de03 OpenSSL 1.1.0 compatible 10 years ago
破娃酱 c3a9612919 bump 2.9.7
manage client with LRUCache
10 years ago
破娃酱 ce25bbf650 catch bind error 10 years ago
破娃酱 0b94af0b7d Merge pull request #130 from V-E-O/patch-1
fix import error of resource on windows
10 years ago
V.E.O 2a6fbc87d4 fix import error of resource on windows 10 years ago
破娃酱 ac58020595 print RLIMIT_NOFILE
always close cymysql objects
10 years ago
破娃酱 9533044bd8 update init script 10 years ago
破娃酱 c7fb9bcb5e init script & update README.md 10 years ago
破娃酱 e5824be145 fix none encrypt key size 10 years ago
破娃酱 13ffdac2b7 tls1.2 split pack data 10 years ago
破娃酱 2eaca2faea fix typo 10 years ago
破娃酱 cfb8944003 tls1.2_ticket_auth random packet size 10 years ago
破娃酱 685b62532e 2.9.5.1
UDP bind address (set out_bind and out_bindv6)
UDP over TCP auto bind
return a long enough err string
10 years ago
破娃酱 a0ee80a5ad new default config 10 years ago
破娃酱 b8afd216d6 bump 2.9.5
update auth_aes128_md5 & auth_aes128_sha1
10 years ago
破娃酱 5345c66abe add License 10 years ago
破娃酱 249b7fd73f fix path 10 years ago
破娃酱 45e27f9142 display version 10 years ago
破娃酱 c48190fe7a sort key, refine log 10 years ago
破娃酱 d1f64de6b4 -P => -O 10 years ago
破娃酱 1183d567c9 server can limit the host setting 10 years ago
破娃酱 293a937501 wait extra data 10 years ago
破娃酱 e8f6d87bb1 add user key, add HMAC-MD5 10 years ago
破娃酱 574a10a743 fix bugs in auth_aes128 when run as a client
add auth_aes128_sha1
10 years ago
破娃酱 ada4eab628 sendback an empty packet if auth success 10 years ago
破娃酱 e7db6d4248 fix typo 10 years ago
破娃酱 a407bcc568 add auth_aes128 10 years ago
破娃酱 52041387f9 fix push_db_all_user 10 years ago
破娃酱 933e75b9a7 add auth_sha1_v4 10 years ago
夏侯 a02e995a8a fix bug at KqueueLoop close (#117) 10 years ago
破娃酱 2637c8d1c7 fix chacha20-ietf 10 years ago
破娃酱 88017d9643 fix ssl connection 10 years ago
破娃酱 e81f8db0b8 add auth_sha1_v3, remove tls1.0_session_auth 10 years ago
破娃酱 1fe6e89c07 fix log RLIMIT_NOFILE 10 years ago
破娃酱 1221a1f3f6 log RLIMIT_NOFILE
let http_simple the same as http_post when server_decode
10 years ago
破娃酱 3d4356e8b4 fix verify_sha1 redirect 10 years ago
破娃酱 6c34c4116f fix verify_sha1 response 10 years ago
破娃酱 6ee4eb3184 set default node id to 0 and default db to "sspanel" 10 years ago
破娃酱 5e485eb2be warn if incorrect node id 10 years ago
破娃酱 b3fcee662a fix unit_len in auth_sha1 10 years ago
破娃酱 e1aa68029d log if no user 10 years ago
破娃酱 1e2445061f remove keep alive 10 years ago
破娃酱 efea3e08cc fix error return 10 years ago
破娃酱 f989fd4d37 fix error return 10 years ago
破娃酱 a26019f9e6 fix online users 10 years ago
破娃酱 816d2f6298 remove tls_simple, fix tls1.2_ticket_auth 10 years ago
破娃酱 3ce6e6f714 fix transfer update 10 years ago
BreakWa11 b1aade8640 remove custom obfs_param & protocol_param 10 years ago
BreakWa11 d47905f01d fix name 10 years ago
BreakWa11 f3808a306f random choice a host name (http_simple/http_post/tls1.2_ticket_auth) 10 years ago
BreakWa11 e15030cc6e set KEEPIDLE on windows/mac osx 10 years ago
BreakWa11 292865f625 Linux only 10 years ago
BreakWa11 f14461ea64 replace("=", "") 10 years ago
BreakWa11 8da3bdc511 set KEEPALIVE except windows 10 years ago
BreakWa11 25e9c131d4 change err return 10 years ago
BreakWa11 9b314af84b Merge branch 'manyuser' of git@breakwa11:breakwa11/shadowsocks.git into manyuser 10 years ago
BreakWa11 4a291ff335 add keep alive setting 10 years ago
破娃酱 ca41f18f42 Merge pull request #103 from ufbycd/manyuser
add shadowsocks.obfsplugin to setup.py for distribution
10 years ago
BreakWa11 82df4524d1 fix host_list type 10 years ago
chenss 1121434a5f add shadowsocks.obfsplugin to setup.py for distribution 10 years ago
BreakWa11 f0d6a5b41e log listening port over UDP 10 years ago
BreakWa11 0213e78847 log listening port, remove `auth_simple`, redirect the same port 10 years ago
BreakWa11 a440a726f6 fix get node_id 10 years ago
BreakWa11 3525d3d86a fix get node_id 10 years ago
BreakWa11 2c4600cf0e fix get node_id 10 years ago
BreakWa11 b922d70a87 set pull flag 10 years ago
BreakWa11 0ed10c73c9 remove dup close 10 years ago
BreakWa11 a6162496ad read traffic_rate from ss_node 10 years ago
BreakWa11 0a7d71a393 using mysql.json to config mysql 10 years ago
BreakWa11 c3484b3375 fix uptime 10 years ago
BreakWa11 9c80dee9da fix traffic & uptime 10 years ago
BreakWa11 7bfafa7f3d fix cfg 10 years ago
BreakWa11 794121f111 show port details 10 years ago
BreakWa11 32957158b9 check decode remote_addr 10 years ago
BreakWa11 9538afebff check decode remote_addr 10 years ago
BreakWa11 3f6f16e4d6 change the counter of the online users 10 years ago
BreakWa11 e2bae5874c catch decode error 10 years ago
BreakWa11 3fd0fbf1d0 mysql SSL connect
mujson_mgr add obfs & protocol mapping
10 years ago
BreakWa11 8e73f50ff5 fix http_post & http_simple redirect 10 years ago
BreakWa11 6db1445d2a auto get ip, ignore 'enable' 10 years ago
BreakWa11 5709f7d901 fix a bug 10 years ago
BreakWa11 68d0c8e260 auto get ip in mujson_mgr.py 10 years ago
BreakWa11 1dbc5e780d fix column name 10 years ago
BreakWa11 4fdd9ea0ab fix transfer update 10 years ago
BreakWa11 d8dda5042f change online user counter & note traffic 10 years ago
BreakWa11 6255a1d321 fix mudbjson mode 10 years ago
BreakWa11 783267dba0 support sspanelv3 node info & logs 10 years ago
BreakWa11 b812ab10bf fix reload module 11 years ago
BreakWa11 e45d5d308e custom tls time diff. not check time diff by default 11 years ago
BreakWa11 cd6dab188c avoid making mudb.json empty
test more encryptor
add rc4-md5-6
11 years ago
BreakWa11 45584dc4f5 display ssr link 11 years ago
BreakWa11 50b11fff02 wait longer to keep safe 11 years ago
BreakWa11 2621e5e564 fix mgr under py3 11 years ago
BreakWa11 050270a725 fix send back str type 11 years ago
BreakWa11 f5434bdbd0 process empty str 11 years ago
BreakWa11 187f0de25a generate random password
remove default users in mudb.json
11 years ago
BreakWa11 bd43069bcf sendback param of server_post_decrypt
details of errors
11 years ago
BreakWa11 f58d76da47 fix spell 11 years ago
BreakWa11 4b2adda440 print_server_help by default 11 years ago
BreakWa11 b344bc236b fix bytes 11 years ago
BreakWa11 9b14c019bb obfs http_simple broken in some cases 11 years ago
BreakWa11 ad625cd899 custom dns ip & port with 'dns.conf' 11 years ago
BreakWa11 7259b211c6 fix auth, refine log 11 years ago
BreakWa11 3912ecba8e accept older connection id 11 years ago
BreakWa11 d2b6c34bdf accept older connection id 11 years ago
BreakWa11 3d1d38aa0f fix connections stat
mgr help info
11 years ago
BreakWa11 3d56b040cf accept older connection id 11 years ago
BreakWa11 acb3eb2910 compatible python3 11 years ago
BreakWa11 44598a070d compatible python3 11 years ago
BreakWa11 8031337d65 compatible python3 11 years ago
BreakWa11 044e1539e9 fix clear command 11 years ago
BreakWa11 268f6e23b4 fix mujson_mgr & add -f 11 years ago
BreakWa11 9e64d1837c add mudbjson mgr 11 years ago
BreakWa11 97785aae2e fix recv data bug 11 years ago
BreakWa11 8556fd3c18 fix UDPRelay _forbidden_portset 11 years ago
BreakWa11 2f8517190c ignore empty 11 years ago
BreakWa11 5c1b90b774 custom 'forbidden_ip' for each user
fix cmp for IPNetwork & PortRange
11 years ago
BreakWa11 8cbca008c6 custom 'forbidden_port' for each user 11 years ago
BreakWa11 72aab7701f fix a tiny bug 11 years ago
BreakWa11 d653c9bdb3 add forbidden_port 11 years ago
BreakWa11 9e288c9ac0 supper local json database for mu 11 years ago
BreakWa11 8dac9faa28 'obfs', 'protocol', 'method' leave blank that use the config of config.json 11 years ago
BreakWa11 825aece219 fix char set 11 years ago
BreakWa11 4af9472986 detect cfg modification 11 years ago
BreakWa11 7f26f43f88 allow custom obfs & protocol 11 years ago
BreakWa11 c7864acc37 add sspanelv3 interface, read the 'method' row 11 years ago
BreakWa11 51bd3fcea0 fix config.json 11 years ago
BreakWa11 569aaa5248 hot load config
support userapiconfig
11 years ago
BreakWa11 4d43e12139 rename API_HOST 11 years ago
BreakWa11 6932548d8e ulimit -n 512000 11 years ago
BreakWa11 91576d1e08 detect thread status
add API params
11 years ago
BreakWa11 82ffa15a56 add connection stat log 11 years ago
BreakWa11 9eefd27152 add file name and line number in log 11 years ago
BreakWa11 7ccee594d5 catch sys exception & close port 11 years ago
BreakWa11 ce189ecd85 remove useless log
add openssl rand_bytes
11 years ago
BreakWa11 3c64e849b0 log client address 11 years ago
BreakWa11 b3ab5d7c4c show exception peer name 11 years ago
BreakWa11 8b35508b6f show exception peer name 11 years ago
BreakWa11 2e65becc44 fix data size 11 years ago
BreakWa11 c5ca6bd80a optimize DNS query 11 years ago
BreakWa11 979a51318c add http_post 11 years ago
BreakWa11 5dbeac99de more error info about peers 11 years ago
BreakWa11 4e10ff9063 better way to stop a server 11 years ago
BreakWa11 760a5308dd add "udp_timeout" in config.json 11 years ago
BreakWa11 cb866dc8fe set udp_timeout default value 11 years ago
BreakWa11 be922ba7c2 add ignore_bind list 11 years ago
BreakWa11 6906c7db04 rename bind -> out_bind 11 years ago
BreakWa11 f91e04b0bd TCP: bind the IP which connecting in, or set the IP by config file
allow setting method/bind/bindv6 for each port
11 years ago
BreakWa11 7e8472332a xrange -> range 11 years ago
BreakWa11 4a02d19597 add udp_cache 11 years ago
BreakWa11 b71af8f4df log connection info as debug level by default 11 years ago
BreakWa11 b8cf491212 remove mgr 11 years ago
BreakWa11 d47b0d47ea add config "udp_timeout"
drop TCP over UDP query
11 years ago
BreakWa11 4e43a4932d limit active UDP client to 256 11 years ago
BreakWa11 bb916eb705 LRUCache add 'clear' method
refine close
11 years ago
BreakWa11 691aa0970a UDP use only 1 lru cache (_client_fd_to_server_addr set to dict type) 11 years ago
BreakWa11 0e26f9b513 remove useless code 11 years ago
BreakWa11 6486f02fbe remove a log info 11 years ago
BreakWa11 b8feaacbbb fix mysql update BUG
hot update mysql connection info
more tls1.2 info for debugging
11 years ago
BreakWa11 9f4f42eefd catch exit exception 11 years ago
BreakWa11 d6640b2e81 add udp data transfer 11 years ago
BreakWa11 95bc6e4a2f tcp resend data bug fix
add tls1.2_ticket_auth
11 years ago
BreakWa11 962a05f137 fix loading obfs plugin on py3 11 years ago
BreakWa11 14edb58281 DNS VALID_HOSTNAME add underline 11 years ago
BreakWa11 cb86c34c3b UDP recv size 11 years ago
BreakWa11 77abc7d1bc support big UDP data 11 years ago
BreakWa11 41e92e277e fix iter.next ? 11 years ago
BreakWa11 16eb3e3448 optimize sql update 11 years ago
BreakWa11 b9aefc144b better speed 11 years ago
BreakWa11 27d2214337 "auth_sha1_v2" add salt 11 years ago
BreakWa11 397990534a add plugin "auth_sha1_v2" 11 years ago
BreakWa11 187e266b26 refine "http_simple" in py3.4 11 years ago
BreakWa11 f5cc946796 fix "http_simple" in py2/py3 11 years ago
BreakWa11 8b7db6d996 fix host name type 11 years ago
BreakWa11 a49b21ee2c fix "bytes" in "encode_head" 2 11 years ago
BreakWa11 81b0597591 fix "bytes" in "encode_head" 11 years ago
BreakWa11 e76939981a fix "chr" 11 years ago
BreakWa11 6576359c1c fix "ord" 11 years ago
BreakWa11 90ae1fdc40 refine manyuser thread start & stop 11 years ago
BreakWa11 876bbbe5d8 allow default settings 11 years ago
BreakWa11 e56c5e4b90 fix index 11 years ago
BreakWa11 519c84719f add "protocol_param" 11 years ago
BreakWa11 42a05d22d6 support UDP protocol plugin 11 years ago
BreakWa11 b151bf815f fix "chacha20-ietf" 11 years ago
BreakWa11 ddcf7f796f ignore error if not support "chacha20-ietf" 11 years ago
BreakWa11 3dec2377bb add "chacha20-ietf", libsodium version must be higher than 1.0.4, see https://github.com/jedisct1/libsodium/releases/ 11 years ago
BreakWa11 202f0f6142 disconnect if wrong handshake package 11 years ago
BreakWa11 80604a9421 fix auth_sha1
fix tls1.0_session_auth
11 years ago
BreakWa11 68a77ddc70 load 'user-config.json' first
set default obfs plugin 'tls1.0_session_auth_compatible'
11 years ago
BreakWa11 459b0c7004 add "redirect" in config.json 11 years ago
BreakWa11 0c4b00a8af fix LRUCache 11 years ago
BreakWa11 8fb3cc3394 fix tls1.0 protocol 11 years ago
BreakWa11 e889f953ff UDP server_transfer_dl += len(post_data) 11 years ago
BreakWa11 430b98c982 fix "tls1.0_session_auth_compatible" 11 years ago
BreakWa11 7300205add not check tls version 11 years ago
BreakWa11 443c4f35c2 fix IPv6 detect 11 years ago
BreakWa11 13579f1ca4 return after destory
fix "tls1.0_session_auth"
11 years ago
BreakWa11 aff97d4ce8 improve LRUCache
add "tls1.0_session_auth"
fix "auth_sha1" in local mode
refine log
11 years ago
BreakWa11 aa92a59405 improve tls_simple 11 years ago
BreakWa11 e61ab27e59 tls_simple bug fixed 11 years ago
BreakWa11 c83341da9b add protocol_param 11 years ago
BreakWa11 7f480248f8 Merge pull request #27 from falseen/manyuser-travis
fix travis
11 years ago
BreakWa11 96495e7dd9 add auth_sha1 11 years ago
BreakWa11 b5da4bc86a add MYSQL_TRANSFER_MUL
add protocol_param (for auth_simple)
11 years ago
BreakWa11 4894925cac add demo code in switchrule.py 11 years ago
BreakWa11 409f3b053d fix ipv6 check 11 years ago
BreakWa11 4b97412569 only correct request add into transfer size 11 years ago
BreakWa11 57433bccb9 fix transfer upload size calculation. avoid flow attack 11 years ago
BreakWa11 0504fb43cf fix a ipv6 bug in mysql mode 11 years ago
BreakWa11 3930cfc726 fix a bug 11 years ago
BreakWa11 84275b6815 UDP over TCP use 0x8 as flag 11 years ago
BreakWa11 19c84cac17 avoid conflict with OTA 11 years ago
BreakWa11 e513faae64 rename verify.py 11 years ago
BreakWa11 737b7d9890 add verify_sha1 (libev OTA) 11 years ago
BreakWa11 8826629741 fix http_simple calc 'head_size'
add 'iv', 'key', 'head_len' in server_info
11 years ago
BreakWa11 125c3e88fd random size from 0 11 years ago
BreakWa11 2a03747e76 pack header in uri 11 years ago
BreakWa11 b778a60502 detect wrong http request
disconnect wrong request by default
11 years ago
BreakWa11 f45d57950b default buffer setting 11 years ago
BreakWa11 b4d1d6b5f4 nginx http response 11 years ago
BreakWa11 877f0470c5 http_simple: fix no response in some case
verify_simple: check package size minimum 7 bytes
11 years ago
BreakWa11 04133d806c set default timeout 120 for many connections 11 years ago
BreakWa11 24a3769809 fix http_simple a bug of urlencode length 11 years ago
BreakWa11 5e46aa0b47 check encryptor object 11 years ago
BreakWa11 b606e19c0b fix default protocol setting 11 years ago
BreakWa11 bc419c4dc2 bump 2.6.13 11 years ago
BreakWa11 b713690521 multiple-port setting 11 years ago
BreakWa11 cb17c7b3b5 let setting & code simple
add "protocol" in config.json
11 years ago
Falseen 032027c3ff fix test_command
由于ssr在根目录中添加了config.json文件,导致相关的测试代码失效。所以暂时先移除。
11 years ago
Falseen 0f7a0c5628 fix chmod 11 years ago
Falseen a96e2cbb63 fix READEME and travis url 11 years ago
Falseen 52391b9214 add test_udp_src 11 years ago
Falseen 60e86c27c4 add setup.py and remove __init__.py
根目录下的__init__.py会导致测试代码无法找到引用的包。
11 years ago
Falseen 208f1462c3 fix manger test again 11 years ago
Falseen 7d2b66766c add cymysql 11 years ago
Falseen fcc7a4cf9b remove os.chdir(file_path)
os.chdir(file_path) 会导致测试代码无法找到引用的包,暂时先移除。
11 years ago
Falseen 72001556b5 remove m2.py 11 years ago
Falseen 82b5980422 fix test files 11 years ago
Falseen fe4b35fb0a remove coverage run -a
最新版coverage的-a和-p参数不能同时用
11 years ago
BreakWa11 c02fcbf746 refine
time diff set to 5 min
11 years ago
BreakWa11 d9dc3ae0b5 rename to "dns_ipv6"
log wrong UDP header package
11 years ago
BreakWa11 c0d1d666a4 add ipv6 config 11 years ago
BreakWa11 e6d7a12afe fix bugs
dns working in both v4 & v6
connecting problem in windows
11 years ago
BreakWa11 011415f710 auth package size not less than head size 11 years ago
BreakWa11 8ee4cd513a a stupid bug 11 years ago
BreakWa11 5137377580 bump 2.6.12 11 years ago
BreakWa11 f5fbf579e2 fix 'http2_simple' & 'tls_simple' 11 years ago
BreakWa11 33d907cc08 fix 'http_simple' & 'random_head' 11 years ago
BreakWa11 b31a8ea3f3 auto get realpath 11 years ago
BreakWa11 c8423e360d DNS request ipv6 first 11 years ago
BreakWa11 6ee8035735 merge pr from mengskysama 11 years ago
BreakWa11 59105f6e64 support auth_simple 11 years ago
BreakWa11 83c8b50ea2 add startup time in auth_simple 11 years ago
BreakWa11 39dffa220f optimize code
add logs
add timestamp
11 years ago
BreakWa11 0ba76b666d not redirect host to chn web
add auth_simple
11 years ago
BreakWa11 126afea524 delete buffer 11 years ago
BreakWa11 3f66ec443f remove FORCE_NEW_PROTOCOL 11 years ago
BreakWa11 041a5c1046 optimize decrypt
first recv size < iv_len will cause decrypt error
11 years ago
BreakWa11 79260ff4ab check duplicate port 11 years ago
breakwa11 eec312cc4c bump 2.6.11 11 years ago
breakwa11 6be40dbf1e Merge branch 'manyuser' of git@breakwa11:breakwa11/shadowsocks.git into manyuser 11 years ago
breakwa11 4551d5c268 shorter code 11 years ago
breakwa11 612c1e2ab3 add obfs_param
catch TCP&UDP exceptions
verify_simple&verify_deflate support sub obfs
11 years ago
BreakWa11 8988926ec7 Merge pull request #20 from falseen/manyuser
添加混淆插件参数"-o"
11 years ago
falseen 6d963cea44 添加混淆插件参数"-o" 11 years ago
breakwa11 c73127d858 insert a reload step
main thread run 'thread_db' directly
insert a 'ulimit' command before run the server
11 years ago
breakwa11 36dc8f9463 add verify_deflate 11 years ago
breakwa11 a597e61093 obfs plugins compatible version 11 years ago
breakwa11 463ce07426 add verify_simple module 11 years ago
BreakWa11 e9f005c926 Merge pull request #17 from falseen/path-1
多端口模式下支持每个端口定义不同的混淆协议
11 years ago
falseen 96a9a25eaa 多端口模式下支持每个端口定义不同的混淆协议
增加:多端口模式下支持每个端口定义不同的混淆协议
11 years ago
breakwa11 74972875ff tiny fix 11 years ago
breakwa11 f9cdf2090f add crc verify 11 years ago
breakwa11 e060fd5b4d tiny bug 11 years ago
breakwa11 93c94fbe3c Merge branch 'manyuser' of git@breakwa11:breakwa11/shadowsocks.git into manyuser 11 years ago
breakwa11 f9e8af6358 add random_head obfs 11 years ago
BreakWa11 bbbb9995d8 Merge pull request #15 from falseen/path-1
优化细节。
11 years ago
falseen 680c128c72 优化细节。
修复:搜索完所有路径之后再判断是否抛出错误,而不是遇到错误就抛出。主要是考虑到系统中同时存在32位和64位dll的情况,原来的代码如果第一个找到的dll文件跟系统不符的话会直接报错。
11 years ago
breakwa11 6f8fc5b77f remove thread module 11 years ago
breakwa11 3e5cbb955e add obfs: 'tls_simple' 11 years ago
breakwa11 71338a7385 fix on python3
http2 obfs
11 years ago
breakwa11 2e3114f40f fix 'ord' bug
replace 'xrange'
support new protocol when run as a client
11 years ago
breakwa11 9df46398d6 Merge branch 'manyuser' of git@breakwa11:breakwa11/shadowsocks.git into manyuser 11 years ago
breakwa11 a723c2f05e add obfs plugin 11 years ago
BreakWa11 ac19b91719 Merge pull request #11 from falseen/manyuser
兼容py3,修正语法错误,加载libcrypto模块失败时显示详细错误。
11 years ago
falseen b6961974ba 兼容py3,修正语法错误,加载libcrypto模块失败时显示详细错误。
修正语法错误:` except Exception, e: ` 是旧版本的语法,py2.6之后的版本已不再使用此语法。
加载libcrypto模块失败时显示详细错误。
11 years ago
falseen 5a5b897578 兼容py3,显示详细错误。
兼容py3,显示详细错误。
11 years ago
Falseen 401da7815f Merge pull request #2 from breakwa11/manyuser
fork Manyuser
11 years ago
breakwa11 55d10ace01 simple reverse proxy 11 years ago
breakwa11 56af51b43c log TCP header if parse error 11 years ago
breakwa11 5249fd528c add FORCE_NEW_PROTOCOL switch 11 years ago
breakwa11 61959945c3 revert encrypt.py
new obfs header
11 years ago
breakwa11 928c26e4f2 fix some exceptions 11 years ago
breakwa11 9defba2d36 merge master 20150810 11 years ago
breakwa11 da46866828 restart server quickly when change password 11 years ago
breakwa11 b32cc8f703 fix closing relays 11 years ago
breakwa11 661fbbfb8b fix handle_event 11 years ago
breakwa11 a3344d9f1c rename handle_event 11 years ago
breakwa11 e5e3102591 remove debug code
add AddressMap for udp
11 years ago
breakwa11 6e5744829c fix asyncmgr.py 11 years ago
breakwa11 a9ea55c396 new UDP over TCP protocol, merge master 11 years ago
breakwa11 469d9f7bfa merge master 12 years ago
breakwa11 69d369268a update run.sh, set working dir 12 years ago
breakwa11 f78f5b56e3 client_key change 12 years ago
breakwa11 298e8a06c9 add getKeys in switchrule.py 12 years ago
breakwa11 a142b957a7 remove 'plan' & 'switch' 12 years ago
breakwa11 3af426b13b remove tail 12 years ago
breakwa11 543a5903a1 encrypt speed test 12 years ago
breakwa11 ad588af75f single user script 12 years ago
breakwa11 d4ca0d281c always UDP on
random length TCP/UDP packet
12 years ago
breakwa11 28318b5c1a double UDP sockets for IPv4 and IPv6 12 years ago
breakwa11 1f530ff8f1 fix udp ipv6 12 years ago
breakwa11 17122c299c fix udp ipv6 12 years ago
breakwa11 4b52f83376 udp ipv6 12 years ago
breakwa11 07dc98f60d udp fix sendto argv 12 years ago
breakwa11 99db626225 run script
fix server restart
12 years ago
breakwa11 9b7dab692b skip bind ipv4 addr if bind ipv6 success
fix close server
12 years ago
breakwa11 565812ae15 elaborate reasons of header parsing failure 12 years ago
breakwa11 616a0c74bd rename destroy to close 12 years ago
breakwa11 1e71fba852 drop UDP message if frag != 0 12 years ago
breakwa11 7c2fe9fd56 use db key 12 years ago
breakwa11 c27f6283a2 UDP remote DNS resolve 12 years ago
breakwa11 f2efed9608 add manyuser branch
support udp over tcp
support chacha20 & salsa20 (base on libsodium)
12 years ago

@ -13,7 +13,7 @@ before_install:
- sudo dd if=/dev/urandom of=/usr/share/nginx/www/file bs=1M count=10
- sudo sh -c "echo '127.0.0.1 localhost' > /etc/hosts"
- sudo service nginx restart
- pip install pep8 pyflakes nose coverage
- pip install pep8 pyflakes nose coverage PySocks cymysql
- sudo tests/socksify/install.sh
- sudo tests/libsodium/install.sh
- sudo tests/setup_tc.sh

@ -1,3 +1,41 @@
2.9.7 2016-11-22
- manage client with LRUCache
- catch bind error
- fix import error of resource on windows
- print RLIMIT_NOFILE
- always close cymysql objects
- add init script
2.9.6 2016-10-17
- tls1.2_ticket_auth random packet size
2.9.5.1 2016-10-16
- UDP bind address
2.9.5 2016-10-13
- add auth_aes128_md5 and auth_aes128_sha1
2.9.4 2016-10-11
- sync client version
2.6.13 2015-11-02
- add protocol setting
2.6.12 2015-10-27
- IPv6 first
- Fix mem leaks
- auth_simple plugin
- remove FORCE_NEW_PROTOCOL
- optimize code
2.6.11 2015-10-20
- Obfs plugin
- Obfs parameters
- UDP over TCP
- TCP over UDP (experimental)
- Fix socket leaks
- Catch abnormal UDP package
2.6.10 2015-06-08
- Optimize LRU cache
- Refine logging

@ -0,0 +1,32 @@
FROM alpine
ENV SERVER_ADDR 0.0.0.0
ENV SERVER_PORT 51348
ENV PASSWORD=
ENV METHOD aes-256-cfb
ENV PROTOCOL origin
ENV OBFS http_simple
ENV TIMEOUT 300
ENV DNS_ADDR 8.8.8.8
ENV DNS_ADDR_2 8.8.4.4
RUN apk update \
&& apk add python \
libsodium \
unzip \
wget \
&& rm -rf /var/cache/apk/*
RUN wget --no-check-certificate https://github.com/breakwa11/shadowsocks/archive/manyuser.zip -O /tmp/manyuser.zip \
&& unzip -d /tmp /tmp/manyuser.zip \
&& mv /tmp/shadowsocks-manyuser/shadowsocks ~/shadowsocks \
&& rm -rf /tmp/*
WORKDIR ~/shadowsocks
CMD python ~/shadowsocks/server.py -p $SERVER_PORT -k $PASSWORD -m $METHOD -O $PROTOCOL -o $OBFS

@ -1,9 +1,7 @@
shadowsocks
ShadowsocksR
===========
[![PyPI version]][PyPI]
[![Build Status]][Travis CI]
[![Coverage Status]][Coverage]
A fast tunnel proxy that helps you bypass firewalls.
@ -14,36 +12,47 @@ Server
Debian / Ubuntu:
apt-get install python-pip
pip install shadowsocks
apt-get install git
git clone https://github.com/breakwa11/shadowsocks.git
CentOS:
yum install python-setuptools && easy_install pip
pip install shadowsocks
yum install git
git clone https://github.com/breakwa11/shadowsocks.git
Windows:
See [Install Server on Windows]
git clone https://github.com/breakwa11/shadowsocks.git
### Usage
### Usage for single user on linux platform
ssserver -p 443 -k password -m aes-256-cfb
If you clone it into "~/shadowsocks"
move to "~/shadowsocks", then run:
bash initcfg.sh
move to "~/shadowsocks/shadowsocks", then run:
python server.py -p 443 -k password -m aes-128-cfb -O auth_aes128_md5_compatible -o tls1.2_ticket_auth_compatible
Check all the options via `-h`.
You can also use a configuration file instead (recommand), move to "~/shadowsocks" and edit the file "user-config.json", then move to "~/shadowsocks/shadowsocks" again, just run:
python server.py
To run in the background:
sudo ssserver -p 443 -k password -m aes-256-cfb --user nobody -d start
./logrun.sh
To stop:
sudo ssserver -d stop
./stop.sh
To check the log:
To monitor the log:
sudo less /var/log/shadowsocks.log
./tail.sh
Check all the options via `-h`. You can also use a [Configuration] file
instead.
Client
------
@ -80,27 +89,17 @@ under the License.
Bugs and Issues
----------------
* [Troubleshooting]
* [Issue Tracker]
* [Mailing list]
[Android]: https://github.com/shadowsocks/shadowsocks-android
[Build Status]: https://img.shields.io/travis/shadowsocks/shadowsocks/master.svg?style=flat
[Configuration]: https://github.com/shadowsocks/shadowsocks/wiki/Configuration-via-Config-File
[Coverage Status]: https://jenkins.shadowvpn.org/result/shadowsocks
[Coverage]: https://jenkins.shadowvpn.org/job/Shadowsocks/ws/PYENV/py34/label/linux/htmlcov/index.html
[Build Status]: https://travis-ci.org/falseen/shadowsocks.svg?branch=manyuser-travis
[Debian sid]: https://packages.debian.org/unstable/python/shadowsocks
[iOS]: https://github.com/shadowsocks/shadowsocks-iOS/wiki/Help
[Issue Tracker]: https://github.com/shadowsocks/shadowsocks/issues?state=open
[Install Server on Windows]: https://github.com/shadowsocks/shadowsocks/wiki/Install-Shadowsocks-Server-on-Windows
[Mailing list]: https://groups.google.com/group/shadowsocks
[Issue Tracker]: https://github.com/breakwa11/shadowsocks/issues?state=open
[OpenWRT]: https://github.com/shadowsocks/openwrt-shadowsocks
[OS X]: https://github.com/shadowsocks/shadowsocks-iOS/wiki/Shadowsocks-for-OSX-Help
[PyPI]: https://pypi.python.org/pypi/shadowsocks
[PyPI version]: https://img.shields.io/pypi/v/shadowsocks.svg?style=flat
[Travis CI]: https://travis-ci.org/shadowsocks/shadowsocks
[Troubleshooting]: https://github.com/shadowsocks/shadowsocks/wiki/Troubleshooting
[Wiki]: https://github.com/shadowsocks/shadowsocks/wiki
[Windows]: https://github.com/shadowsocks/shadowsocks-csharp
[Travis CI]: https://travis-ci.org/falseen/shadowsocks
[Windows]: https://github.com/breakwa11/shadowsocks-csharp
[Wiki]: https://github.com/breakwa11/shadowsocks-rss/wiki

@ -0,0 +1,15 @@
# Config
API_INTERFACE = 'sspanelv2' #mudbjson, sspanelv2, sspanelv3, sspanelv3ssr, muapiv2(not support)
UPDATE_TIME = 60
SERVER_PUB_ADDR = '127.0.0.1' # mujson_mgr need this to generate ssr link
#mudb
MUDB_FILE = 'mudb.json'
# Mysql
MYSQL_CONFIG = 'usermysql.json'
# API
MUAPI_CONFIG = 'usermuapi.json'

@ -0,0 +1,99 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014 clowwindy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import time
import os
import socket
import struct
import re
import logging
from shadowsocks import common
from shadowsocks import lru_cache
from shadowsocks import eventloop
import server_pool
import Config
class ServerMgr(object):
def __init__(self):
self._loop = None
self._request_id = 1
self._hosts = {}
self._hostname_status = {}
self._hostname_to_cb = {}
self._cb_to_hostname = {}
self._last_time = time.time()
self._sock = None
self._servers = None
def add_to_loop(self, loop):
if self._loop:
raise Exception('already add to loop')
self._loop = loop
# TODO when dns server is IPv6
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
socket.SOL_UDP)
self._sock.bind((Config.MANAGE_BIND_IP, Config.MANAGE_PORT))
self._sock.setblocking(False)
loop.add(self._sock, eventloop.POLL_IN, self)
def _handle_data(self, sock):
data, addr = sock.recvfrom(128)
#manage pwd:port:passwd:action
args = data.split(':')
if len(args) < 4:
return
if args[0] == Config.MANAGE_PASS:
if args[3] == '0':
server_pool.ServerPool.get_instance().cb_del_server(args[1])
elif args[3] == '1':
server_pool.ServerPool.get_instance().new_server(args[1], args[2])
def handle_event(self, sock, fd, event):
if sock != self._sock:
return
if event & eventloop.POLL_ERR:
logging.error('mgr socket err')
self._loop.remove(self._sock)
self._sock.close()
# TODO when dns server is IPv6
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
socket.SOL_UDP)
self._sock.setblocking(False)
self._loop.add(self._sock, eventloop.POLL_IN, self)
else:
self._handle_data(sock)
def close(self):
if self._sock:
if self._loop:
self._loop.remove(self._sock)
self._sock.close()
self._sock = None
def test():
pass
if __name__ == '__main__':
test()

@ -0,0 +1,19 @@
{
"server": "0.0.0.0",
"server_ipv6": "::",
"server_port": 8388,
"local_address": "127.0.0.1",
"local_port": 1080,
"password": "m",
"timeout": 120,
"udp_timeout": 60,
"method": "aes-256-cfb",
"protocol": "auth_sha1_v4_compatible",
"protocol_param": "",
"obfs": "tls1.2_ticket_auth_compatible",
"obfs_param": "",
"dns_ipv6": false,
"connect_verbose_info": 0,
"redirect": "",
"fast_open": false
}

@ -0,0 +1,15 @@
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import importloader
g_config = None
def load_config():
global g_config
g_config = importloader.loads(['userapiconfig', 'apiconfig'])
def get_config():
return g_config
load_config()

@ -0,0 +1,568 @@
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import logging
import time
import sys
from server_pool import ServerPool
import traceback
from shadowsocks import common, shell, lru_cache
from configloader import load_config, get_config
import importloader
switchrule = None
db_instance = None
class TransferBase(object):
def __init__(self):
import threading
self.event = threading.Event()
self.key_list = ['port', 'u', 'd', 'transfer_enable', 'passwd', 'enable']
self.last_get_transfer = {} #上一次的实际流量
self.last_update_transfer = {} #上一次更新到的流量(小于等于实际流量)
self.force_update_transfer = set() #强制推入数据库的ID
self.port_uid_table = {} #端口到uid的映射(仅v3以上有用)
self.onlineuser_cache = lru_cache.LRUCache(timeout=60*30) #用户在线状态记录
self.pull_ok = False #记录是否已经拉出过数据
def load_cfg(self):
pass
def push_db_all_user(self):
if self.pull_ok is False:
return
#更新用户流量到数据库
last_transfer = self.last_update_transfer
curr_transfer = ServerPool.get_instance().get_servers_transfer()
#上次和本次的增量
dt_transfer = {}
for id in self.force_update_transfer: #此表中的用户统计上次未计入的流量
if id in self.last_get_transfer and id in last_transfer:
dt_transfer[id] = [self.last_get_transfer[id][0] - last_transfer[id][0], self.last_get_transfer[id][1] - last_transfer[id][1]]
for id in curr_transfer.keys():
if id in self.force_update_transfer:
continue
#算出与上次记录的流量差值,保存于dt_transfer表
if id in last_transfer:
if curr_transfer[id][0] + curr_transfer[id][1] - last_transfer[id][0] - last_transfer[id][1] <= 0:
continue
dt_transfer[id] = [curr_transfer[id][0] - last_transfer[id][0],
curr_transfer[id][1] - last_transfer[id][1]]
else:
if curr_transfer[id][0] + curr_transfer[id][1] <= 0:
continue
dt_transfer[id] = [curr_transfer[id][0], curr_transfer[id][1]]
#有流量的,先记录在线状态
if id in self.last_get_transfer:
if curr_transfer[id][0] + curr_transfer[id][1] > self.last_get_transfer[id][0] + self.last_get_transfer[id][1]:
self.onlineuser_cache[id] = curr_transfer[id][0] + curr_transfer[id][1]
else:
self.onlineuser_cache[id] = curr_transfer[id][0] + curr_transfer[id][1]
self.onlineuser_cache.sweep()
update_transfer = self.update_all_user(dt_transfer) #返回有更新的表
for id in update_transfer.keys(): #其增量加在此表
if id not in self.force_update_transfer: #但排除在force_update_transfer内的
last = self.last_update_transfer.get(id, [0,0])
self.last_update_transfer[id] = [last[0] + update_transfer[id][0], last[1] + update_transfer[id][1]]
self.last_get_transfer = curr_transfer
for id in self.force_update_transfer:
if id in self.last_update_transfer:
del self.last_update_transfer[id]
if id in self.last_get_transfer:
del self.last_get_transfer[id]
self.force_update_transfer = set()
def del_server_out_of_bound_safe(self, last_rows, rows):
#停止超流量的服务
#启动没超流量的服务
try:
switchrule = importloader.load('switchrule')
except Exception as e:
logging.error('load switchrule.py fail')
cur_servers = {}
new_servers = {}
for row in rows:
try:
allow = switchrule.isTurnOn(row) and row['enable'] == 1 and row['u'] + row['d'] < row['transfer_enable']
except Exception as e:
allow = False
port = row['port']
passwd = common.to_bytes(row['passwd'])
cfg = {'password': passwd}
if 'id' in row:
self.port_uid_table[row['port']] = row['id']
read_config_keys = ['method', 'obfs', 'obfs_param', 'protocol', 'protocol_param', 'forbidden_ip', 'forbidden_port']
for name in read_config_keys:
if name in row and row[name]:
cfg[name] = row[name]
merge_config_keys = ['password'] + read_config_keys
for name in cfg.keys():
if hasattr(cfg[name], 'encode'):
cfg[name] = cfg[name].encode('utf-8')
if port not in cur_servers:
cur_servers[port] = passwd
else:
logging.error('more than one user use the same port [%s]' % (port,))
continue
if ServerPool.get_instance().server_is_run(port) > 0:
if not allow:
logging.info('db stop server at port [%s]' % (port,))
ServerPool.get_instance().cb_del_server(port)
self.force_update_transfer.add(port)
else:
cfgchange = False
if port in ServerPool.get_instance().tcp_servers_pool:
relay = ServerPool.get_instance().tcp_servers_pool[port]
for name in merge_config_keys:
if name in cfg and not self.cmp(cfg[name], relay._config[name]):
cfgchange = True
break;
if not cfgchange and port in ServerPool.get_instance().tcp_ipv6_servers_pool:
relay = ServerPool.get_instance().tcp_ipv6_servers_pool[port]
for name in merge_config_keys:
if name in cfg and not self.cmp(cfg[name], relay._config[name]):
cfgchange = True
break;
#config changed
if cfgchange:
logging.info('db stop server at port [%s] reason: config changed: %s' % (port, cfg))
ServerPool.get_instance().cb_del_server(port)
self.force_update_transfer.add(port)
new_servers[port] = (passwd, cfg)
elif allow and ServerPool.get_instance().server_run_status(port) is False:
self.new_server(port, passwd, cfg)
for row in last_rows:
if row['port'] in cur_servers:
pass
else:
logging.info('db stop server at port [%s] reason: port not exist' % (row['port']))
ServerPool.get_instance().cb_del_server(row['port'])
self.clear_cache(row['port'])
if row['port'] in self.port_uid_table:
del self.port_uid_table[row['port']]
if len(new_servers) > 0:
from shadowsocks import eventloop
self.event.wait(eventloop.TIMEOUT_PRECISION + eventloop.TIMEOUT_PRECISION / 2)
for port in new_servers.keys():
passwd, cfg = new_servers[port]
self.new_server(port, passwd, cfg)
def clear_cache(self, port):
if port in self.force_update_transfer: del self.force_update_transfer[port]
if port in self.last_get_transfer: del self.last_get_transfer[port]
if port in self.last_update_transfer: del self.last_update_transfer[port]
def new_server(self, port, passwd, cfg):
protocol = cfg.get('protocol', ServerPool.get_instance().config.get('protocol', 'origin'))
method = cfg.get('method', ServerPool.get_instance().config.get('method', 'None'))
obfs = cfg.get('obfs', ServerPool.get_instance().config.get('obfs', 'plain'))
logging.info('db start server at port [%s] pass [%s] protocol [%s] method [%s] obfs [%s]' % (port, passwd, protocol, method, obfs))
ServerPool.get_instance().new_server(port, cfg)
def cmp(self, val1, val2):
if type(val1) is bytes:
val1 = common.to_str(val1)
if type(val2) is bytes:
val2 = common.to_str(val2)
return val1 == val2
@staticmethod
def del_servers():
for port in [v for v in ServerPool.get_instance().tcp_servers_pool.keys()]:
if ServerPool.get_instance().server_is_run(port) > 0:
ServerPool.get_instance().cb_del_server(port)
for port in [v for v in ServerPool.get_instance().tcp_ipv6_servers_pool.keys()]:
if ServerPool.get_instance().server_is_run(port) > 0:
ServerPool.get_instance().cb_del_server(port)
@staticmethod
def thread_db(obj):
import socket
import time
global db_instance
timeout = 60
socket.setdefaulttimeout(timeout)
last_rows = []
db_instance = obj()
ServerPool.get_instance()
shell.log_shadowsocks_version()
import resource
logging.info('current process RLIMIT_NOFILE resource: soft %d hard %d' % resource.getrlimit(resource.RLIMIT_NOFILE))
try:
while True:
load_config()
db_instance.load_cfg()
try:
db_instance.push_db_all_user()
rows = db_instance.pull_db_all_user()
if rows:
db_instance.pull_ok = True
db_instance.del_server_out_of_bound_safe(last_rows, rows)
last_rows = rows
except Exception as e:
trace = traceback.format_exc()
logging.error(trace)
#logging.warn('db thread except:%s' % e)
if db_instance.event.wait(get_config().UPDATE_TIME) or not ServerPool.get_instance().thread.is_alive():
break
except KeyboardInterrupt as e:
pass
db_instance.del_servers()
ServerPool.get_instance().stop()
db_instance = None
@staticmethod
def thread_db_stop():
global db_instance
db_instance.event.set()
class DbTransfer(TransferBase):
def __init__(self):
super(DbTransfer, self).__init__()
self.user_pass = {} #记录更新此用户流量时被跳过多少次
self.cfg = {
"host": "127.0.0.1",
"port": 3306,
"user": "ss",
"password": "pass",
"db": "shadowsocks",
"node_id": 0,
"transfer_mul": 1.0,
"ssl_enable": 0,
"ssl_ca": "",
"ssl_cert": "",
"ssl_key": ""}
self.load_cfg()
def load_cfg(self):
import json
config_path = get_config().MYSQL_CONFIG
cfg = None
with open(config_path, 'r+') as f:
cfg = json.loads(f.read().decode('utf8'))
if cfg:
self.cfg.update(cfg)
def update_all_user(self, dt_transfer):
import cymysql
update_transfer = {}
query_head = 'UPDATE user'
query_sub_when = ''
query_sub_when2 = ''
query_sub_in = None
last_time = time.time()
for id in dt_transfer.keys():
transfer = dt_transfer[id]
#小于最低更新流量的先不更新
update_trs = 1024 * (2048 - self.user_pass.get(id, 0) * 64)
if transfer[0] + transfer[1] < update_trs and id not in self.force_update_transfer:
self.user_pass[id] = self.user_pass.get(id, 0) + 1
continue
if id in self.user_pass:
del self.user_pass[id]
query_sub_when += ' WHEN %s THEN u+%s' % (id, int(transfer[0] * self.cfg["transfer_mul"]))
query_sub_when2 += ' WHEN %s THEN d+%s' % (id, int(transfer[1] * self.cfg["transfer_mul"]))
update_transfer[id] = transfer
if query_sub_in is not None:
query_sub_in += ',%s' % id
else:
query_sub_in = '%s' % id
if query_sub_when == '':
return update_transfer
query_sql = query_head + ' SET u = CASE port' + query_sub_when + \
' END, d = CASE port' + query_sub_when2 + \
' END, t = ' + str(int(last_time)) + \
' WHERE port IN (%s)' % query_sub_in
if self.cfg["ssl_enable"] == 1:
conn = cymysql.connect(host=self.cfg["host"], port=self.cfg["port"],
user=self.cfg["user"], passwd=self.cfg["password"],
db=self.cfg["db"], charset='utf8',
ssl={'ca':self.cfg["ssl_ca"],'cert':self.cfg["ssl_cert"],'key':self.cfg["ssl_key"]})
else:
conn = cymysql.connect(host=self.cfg["host"], port=self.cfg["port"],
user=self.cfg["user"], passwd=self.cfg["password"],
db=self.cfg["db"], charset='utf8')
try:
cur = conn.cursor()
try:
cur.execute(query_sql)
except Exception as e:
logging.error(e)
update_transfer = {}
cur.close()
conn.commit()
except Exception as e:
logging.error(e)
update_transfer = {}
finally:
conn.close()
return update_transfer
def pull_db_all_user(self):
import cymysql
#数据库所有用户信息
if self.cfg["ssl_enable"] == 1:
conn = cymysql.connect(host=self.cfg["host"], port=self.cfg["port"],
user=self.cfg["user"], passwd=self.cfg["password"],
db=self.cfg["db"], charset='utf8',
ssl={'ca':self.cfg["ssl_ca"],'cert':self.cfg["ssl_cert"],'key':self.cfg["ssl_key"]})
else:
conn = cymysql.connect(host=self.cfg["host"], port=self.cfg["port"],
user=self.cfg["user"], passwd=self.cfg["password"],
db=self.cfg["db"], charset='utf8')
try:
rows = self.pull_db_users(conn)
finally:
conn.close()
if not rows:
logging.warn('no user in db')
return rows
def pull_db_users(self, conn):
try:
switchrule = importloader.load('switchrule')
keys = switchrule.getKeys(self.key_list)
except Exception as e:
keys = self.key_list
cur = conn.cursor()
cur.execute("SELECT " + ','.join(keys) + " FROM user")
rows = []
for r in cur.fetchall():
d = {}
for column in range(len(keys)):
d[keys[column]] = r[column]
rows.append(d)
cur.close()
return rows
class Dbv3Transfer(DbTransfer):
def __init__(self):
super(Dbv3Transfer, self).__init__()
self.key_list += ['id', 'method']
if get_config().API_INTERFACE == 'sspanelv3ssr':
self.key_list += ['obfs', 'protocol']
self.start_time = time.time()
def update_all_user(self, dt_transfer):
import cymysql
update_transfer = {}
query_head = 'UPDATE user'
query_sub_when = ''
query_sub_when2 = ''
query_sub_in = None
last_time = time.time()
alive_user_count = len(self.onlineuser_cache)
bandwidth_thistime = 0
if self.cfg["ssl_enable"] == 1:
conn = cymysql.connect(host=self.cfg["host"], port=self.cfg["port"],
user=self.cfg["user"], passwd=self.cfg["password"],
db=self.cfg["db"], charset='utf8',
ssl={'ca':self.cfg["ssl_ca"],'cert':self.cfg["ssl_cert"],'key':self.cfg["ssl_key"]})
else:
conn = cymysql.connect(host=self.cfg["host"], port=self.cfg["port"],
user=self.cfg["user"], passwd=self.cfg["password"],
db=self.cfg["db"], charset='utf8')
conn.autocommit(True)
for id in dt_transfer.keys():
transfer = dt_transfer[id]
bandwidth_thistime = bandwidth_thistime + transfer[0] + transfer[1]
update_trs = 1024 * (2048 - self.user_pass.get(id, 0) * 64)
if transfer[0] + transfer[1] < update_trs:
self.user_pass[id] = self.user_pass.get(id, 0) + 1
continue
if id in self.user_pass:
del self.user_pass[id]
query_sub_when += ' WHEN %s THEN u+%s' % (id, int(transfer[0] * self.cfg["transfer_mul"]))
query_sub_when2 += ' WHEN %s THEN d+%s' % (id, int(transfer[1] * self.cfg["transfer_mul"]))
update_transfer[id] = transfer
cur = conn.cursor()
try:
if id in self.port_uid_table:
cur.execute("INSERT INTO `user_traffic_log` (`id`, `user_id`, `u`, `d`, `node_id`, `rate`, `traffic`, `log_time`) VALUES (NULL, '" + \
str(self.port_uid_table[id]) + "', '" + str(transfer[0]) + "', '" + str(transfer[1]) + "', '" + \
str(self.cfg["node_id"]) + "', '" + str(self.cfg["transfer_mul"]) + "', '" + \
self.traffic_format((transfer[0] + transfer[1]) * self.cfg["transfer_mul"]) + "', unix_timestamp()); ")
except:
logging.warn('no `user_traffic_log` in db')
cur.close()
if query_sub_in is not None:
query_sub_in += ',%s' % id
else:
query_sub_in = '%s' % id
if query_sub_when != '':
query_sql = query_head + ' SET u = CASE port' + query_sub_when + \
' END, d = CASE port' + query_sub_when2 + \
' END, t = ' + str(int(last_time)) + \
' WHERE port IN (%s)' % query_sub_in
cur = conn.cursor()
try:
cur.execute(query_sql)
except Exception as e:
logging.error(e)
cur.close()
try:
cur = conn.cursor()
try:
cur.execute("INSERT INTO `ss_node_online_log` (`id`, `node_id`, `online_user`, `log_time`) VALUES (NULL, '" + \
str(self.cfg["node_id"]) + "', '" + str(alive_user_count) + "', unix_timestamp()); ")
except Exception as e:
logging.error(e)
cur.close()
cur = conn.cursor()
try:
cur.execute("INSERT INTO `ss_node_info_log` (`id`, `node_id`, `uptime`, `load`, `log_time`) VALUES (NULL, '" + \
str(self.cfg["node_id"]) + "', '" + str(self.uptime()) + "', '" + \
str(self.load()) + "', unix_timestamp()); ")
except Exception as e:
logging.error(e)
cur.close()
except:
logging.warn('no `ss_node_online_log` or `ss_node_info_log` in db')
conn.close()
return update_transfer
def pull_db_users(self, conn):
try:
switchrule = importloader.load('switchrule')
keys = switchrule.getKeys(self.key_list)
except Exception as e:
keys = self.key_list
cur = conn.cursor()
node_info_keys = ['traffic_rate']
try:
cur.execute("SELECT " + ','.join(node_info_keys) +" FROM ss_node where `id`='" + str(self.cfg["node_id"]) + "'")
nodeinfo = cur.fetchone()
except Exception as e:
logging.error(e)
nodeinfo = None
if nodeinfo == None:
rows = []
cur.close()
conn.commit()
logging.warn('None result when select node info from ss_node in db, maybe you set the incorrect node id')
return rows
cur.close()
node_info_dict = {}
for column in range(len(nodeinfo)):
node_info_dict[node_info_keys[column]] = nodeinfo[column]
self.cfg['transfer_mul'] = float(node_info_dict['traffic_rate'])
cur = conn.cursor()
try:
cur.execute("SELECT " + ','.join(keys) + " FROM user")
rows = []
for r in cur.fetchall():
d = {}
for column in range(len(keys)):
d[keys[column]] = r[column]
rows.append(d)
except Exception as e:
logging.error(e)
cur.close()
return rows
def load(self):
import os
return os.popen("cat /proc/loadavg | awk '{ print $1\" \"$2\" \"$3 }'").readlines()[0]
def uptime(self):
return time.time() - self.start_time
def traffic_format(self, traffic):
if traffic < 1024 * 8:
return str(int(traffic)) + "B";
if traffic < 1024 * 1024 * 2:
return str(round((traffic / 1024.0), 2)) + "KB";
return str(round((traffic / 1048576.0), 2)) + "MB";
class MuJsonTransfer(TransferBase):
def __init__(self):
super(MuJsonTransfer, self).__init__()
def update_all_user(self, dt_transfer):
import json
rows = None
config_path = get_config().MUDB_FILE
with open(config_path, 'rb+') as f:
rows = json.loads(f.read().decode('utf8'))
for row in rows:
if "port" in row:
port = row["port"]
if port in dt_transfer:
row["u"] += dt_transfer[port][0]
row["d"] += dt_transfer[port][1]
if rows:
output = json.dumps(rows, sort_keys=True, indent=4, separators=(',', ': '))
with open(config_path, 'r+') as f:
f.write(output)
f.truncate()
return dt_transfer
def pull_db_all_user(self):
import json
rows = None
config_path = get_config().MUDB_FILE
with open(config_path, 'rb+') as f:
rows = json.loads(f.read().decode('utf8'))
for row in rows:
try:
if 'forbidden_ip' in row:
row['forbidden_ip'] = common.IPNetwork(row['forbidden_ip'])
except Exception as e:
logging.error(e)
try:
if 'forbidden_port' in row:
row['forbidden_port'] = common.PortRange(row['forbidden_port'])
except Exception as e:
logging.error(e)
if not rows:
logging.warn('no user in json file')
return rows

@ -0,0 +1,24 @@
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def load(name):
try:
obj = __import__(name)
reload(obj)
return obj
except:
pass
try:
import importlib
obj = importlib.__import__(name)
importlib.reload(obj)
return obj
except:
pass
def loads(namelist):
for name in namelist:
obj = load(name)
if obj is not None:
return obj

@ -0,0 +1,8 @@
#!/bin/bash
chmod +x *.sh
chmod +x shadowsocks/*.sh
cp -n apiconfig.py userapiconfig.py
cp -n config.json user-config.json
cp -n mysql.json usermysql.json

@ -0,0 +1,6 @@
#!/bin/bash
cd `dirname $0`
eval $(ps -ef | grep "[0-9] python server\\.py m" | awk '{print "kill "$2}')
ulimit -n 512000
nohup python server.py m>> ssserver.log 2>&1 &

@ -0,0 +1,2 @@
[
]

@ -0,0 +1,317 @@
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import traceback
from shadowsocks import shell, common
from configloader import load_config, get_config
import random
import getopt
import sys
import json
import base64
class MuJsonLoader(object):
def __init__(self):
self.json = None
def load(self, path):
with open(path, 'rb+') as f:
self.json = json.loads(f.read().decode('utf8'))
def save(self, path):
if self.json:
output = json.dumps(self.json, sort_keys=True, indent=4, separators=(',', ': '))
with open(path, 'r+') as f:
f.write(output)
f.truncate()
class MuMgr(object):
def __init__(self):
self.config_path = get_config().MUDB_FILE
try:
self.server_addr = get_config().SERVER_PUB_ADDR
except:
self.server_addr = '127.0.0.1'
self.data = MuJsonLoader()
if self.server_addr == '127.0.0.1':
self.server_addr = self.getipaddr()
def getipaddr(self, ifname = 'eth0'):
import socket
import struct
import fcntl
ret = '127.0.0.1'
try:
ret = socket.gethostbyname(socket.getfqdn(socket.gethostname()))
except:
pass
if ret == '127.0.0.1':
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ret = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])
except:
pass
return ret
def ssrlink(self, user, encode):
protocol = user.get('protocol', '')
obfs = user.get('obfs', '')
protocol = protocol.replace("_compatible", "")
obfs = obfs.replace("_compatible", "")
link = "%s:%s:%s:%s:%s:%s" % (self.server_addr, user['port'], protocol, user['method'], obfs, common.to_str(base64.urlsafe_b64encode(common.to_bytes(user['passwd']))).replace("=", ""))
return "ssr://" + ( encode and common.to_str(base64.urlsafe_b64encode(common.to_bytes(link))).replace("=", "") or link)
def userinfo(self, user):
ret = ""
for key in sorted(user):
if key in ['enable']:
continue
ret += '\n'
if key in ['transfer_enable', 'u', 'd'] :
val = user[key]
if val / 1024 < 4:
ret += " %s : %s" % (key, val)
elif val / 1024**2 < 4:
val /= float(1024)
ret += " %s : %s K Bytes" % (key, val)
elif val / 1024**3 < 4:
val /= float(1024**2)
ret += " %s : %s M Bytes" % (key, val)
else:
val /= float(1024**3)
ret += " %s : %s G Bytes" % (key, val)
else:
ret += " %s : %s" % (key, user[key])
ret += "\n " + self.ssrlink(user, False)
ret += "\n " + self.ssrlink(user, True)
return ret
def rand_pass(self):
return ''.join([random.choice('''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~-_=+(){}[]^&%$@''') for i in range(8)])
def add(self, user):
up = {'enable': True, 'u': 0, 'd': 0, 'method': "aes-128-cfb",
'protocol': "auth_sha1_v4_compatible",
'obfs': "tls1.2_ticket_auth_compatible",
'transfer_enable': 1125899906842624}
up['passwd'] = self.rand_pass()
up.update(user)
self.data.load(self.config_path)
for row in self.data.json:
match = False
if 'user' in user and row['user'] == user['user']:
match = True
if 'port' in user and row['port'] == user['port']:
match = True
if match:
print("user [%s] port [%s] already exist" % (row['user'], row['port']))
return
self.data.json.append(up)
print("### add user info %s" % self.userinfo(up))
self.data.save(self.config_path)
def edit(self, user):
self.data.load(self.config_path)
for row in self.data.json:
match = True
if 'user' in user and row['user'] != user['user']:
match = False
if 'port' in user and row['port'] != user['port']:
match = False
if match:
print("edit user [%s]" % (row['user'],))
row.update(user)
print("### new user info %s" % self.userinfo(row))
break
self.data.save(self.config_path)
def delete(self, user):
self.data.load(self.config_path)
index = 0
for row in self.data.json:
match = True
if 'user' in user and row['user'] != user['user']:
match = False
if 'port' in user and row['port'] != user['port']:
match = False
if match:
print("delete user [%s]" % row['user'])
del self.data.json[index]
break
index += 1
self.data.save(self.config_path)
def clear_ud(self, user):
up = {'u': 0, 'd': 0}
self.data.load(self.config_path)
for row in self.data.json:
match = True
if 'user' in user and row['user'] != user['user']:
match = False
if 'port' in user and row['port'] != user['port']:
match = False
if match:
row.update(up)
print("clear user [%s]" % row['user'])
self.data.save(self.config_path)
def list_user(self, user):
self.data.load(self.config_path)
if not user:
for row in self.data.json:
print("user [%s] port %s" % (row['user'], row['port']))
return
for row in self.data.json:
match = True
if 'user' in user and row['user'] != user['user']:
match = False
if 'port' in user and row['port'] != user['port']:
match = False
if match:
print("### user [%s] info %s" % (row['user'], self.userinfo(row)))
def print_server_help():
print('''usage: python mujson_manage.py -a|-d|-e|-c|-l [OPTION]...
Actions:
-a ADD add/edit a user
-d DELETE delete a user
-e EDIT edit a user
-c CLEAR set u/d to zero
-l LIST display a user infomation or all users infomation
Options:
-u USER the user name
-p PORT server port
-k PASSWORD password
-m METHOD encryption method, default: aes-128-cfb
-O PROTOCOL protocol plugin, default: auth_sha1_v2_compatible
-o OBFS obfs plugin, default: tls1.2_ticket_auth_compatible
-G PROTOCOL_PARAM protocol plugin param
-g OBFS_PARAM obfs plugin param
-t TRANSFER max transfer for G bytes, default: 1048576, can be float point number
-f FORBID set forbidden ports. Example (ban 1~79 and 81~100): -f "1-79,81-100"
General options:
-h, --help show this help message and exit
''')
def main():
shortopts = 'adeclu:p:k:O:o:G:g:m:t:f:h'
longopts = ['help']
action = None
user = {}
fast_set_obfs = {'0': 'plain',
'+1': 'http_simple_compatible',
'1': 'http_simple',
'+2': 'tls1.2_ticket_auth_compatible',
'2': 'tls1.2_ticket_auth'}
fast_set_protocol = {'0': 'origin',
'+1': 'verify_sha1_compatible',
'1': 'verify_sha1',
'+2': 'auth_sha1_compatible',
'2': 'auth_sha1',
'+3': 'auth_sha1_v2_compatible',
'3': 'auth_sha1_v2',
'+4': 'auth_sha1_v4_compatible',
'4': 'auth_sha1_v4',
'a1': 'auth_aes128'}
fast_set_method = {'a0': 'aes-128-cfb',
'a1': 'aes-192-cfb',
'a2': 'aes-256-cfb',
'r': 'rc4-md5',
'r6': 'rc4-md5-6',
'c': 'chacha20',
'ci': 'chacha20-ietf',
's': 'salsa20',
'b': 'bf-cfb',
'm0': 'camellia-128-cfb',
'm1': 'camellia-192-cfb',
'm2': 'camellia-256-cfb',
'a0t': 'aes-128-ctr',
'a1t': 'aes-192-ctr',
'a2t': 'aes-256-ctr'}
try:
optlist, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
for key, value in optlist:
if key == '-a':
action = 1
elif key == '-d':
action = 2
elif key == '-e':
action = 3
elif key == '-l':
action = 4
elif key == '-c':
action = 0
elif key == '-u':
user['user'] = value
elif key == '-p':
user['port'] = int(value)
elif key == '-k':
user['passwd'] = value
elif key == '-o':
if value in fast_set_obfs:
user['obfs'] = fast_set_obfs[value]
else:
user['obfs'] = value
elif key == '-O':
if value in fast_set_protocol:
user['protocol'] = fast_set_protocol[value]
else:
user['protocol'] = value
elif key == '-g':
user['obfs_param'] = value
elif key == '-G':
user['protocol_param'] = value
elif key == '-m':
if value in fast_set_method:
user['method'] = fast_set_method[value]
else:
user['method'] = value
elif key == '-f':
user['forbidden_port'] = value
elif key == '-t':
val = float(value)
try:
val = int(value)
except:
pass
user['transfer_enable'] = val * (1024 ** 3)
elif key in ('-h', '--help'):
print_server_help()
sys.exit(0)
except getopt.GetoptError as e:
print(e)
sys.exit(2)
manage = MuMgr()
if action == 0:
manage.clear_ud(user)
elif action == 1:
if 'user' not in user and 'port' in user:
user['user'] = str(user['port'])
if 'user' in user and 'port' in user:
manage.add(user)
else:
print("You have to set the port with -p")
elif action == 2:
if 'user' in user or 'port' in user:
manage.delete(user)
else:
print("You have to set the user name or port with -u/-p")
elif action == 3:
if 'user' in user or 'port' in user:
manage.edit(user)
else:
print("You have to set the user name or port with -u/-p")
elif action == 4:
manage.list_user(user)
elif action is None:
print_server_help()
if __name__ == '__main__':
main()

@ -0,0 +1,13 @@
{
"host": "127.0.0.1",
"port": 3306,
"user": "ss",
"password": "pass",
"db": "sspanel",
"node_id": 0,
"transfer_mul": 1.0,
"ssl_enable": 0,
"ssl_ca": "",
"ssl_cert": "",
"ssl_key": ""
}

@ -0,0 +1,6 @@
#!/bin/bash
cd `dirname $0`
eval $(ps -ef | grep "[0-9] python server\\.py m" | awk '{print "kill "$2}')
ulimit -n 512000
nohup python server.py m>> /dev/null 2>&1 &

@ -0,0 +1,65 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2015 breakwall
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import time
import sys
import threading
import os
if __name__ == '__main__':
import inspect
os.chdir(os.path.dirname(os.path.realpath(inspect.getfile(inspect.currentframe()))))
import server_pool
import db_transfer
from shadowsocks import shell
from configloader import load_config, get_config
class MainThread(threading.Thread):
def __init__(self, obj):
threading.Thread.__init__(self)
self.obj = obj
def run(self):
self.obj.thread_db(self.obj)
def stop(self):
self.obj.thread_db_stop()
def main():
shell.check_python()
if False:
db_transfer.DbTransfer.thread_db()
else:
if get_config().API_INTERFACE == 'mudbjson':
thread = MainThread(db_transfer.MuJsonTransfer)
elif get_config().API_INTERFACE == 'sspanelv2':
thread = MainThread(db_transfer.DbTransfer)
else:
thread = MainThread(db_transfer.Dbv3Transfer)
thread.start()
try:
while thread.is_alive():
time.sleep(10)
except (KeyboardInterrupt, IOError, OSError) as e:
import traceback
traceback.print_exc()
thread.stop()
if __name__ == '__main__':
main()

@ -0,0 +1,242 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014 clowwindy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
import logging
import time
from shadowsocks import shell, eventloop, tcprelay, udprelay, asyncdns, common
import threading
import sys
from socket import *
from configloader import load_config, get_config
class MainThread(threading.Thread):
def __init__(self, params):
threading.Thread.__init__(self)
self.params = params
def run(self):
ServerPool._loop(*self.params)
class ServerPool(object):
instance = None
def __init__(self):
shell.check_python()
self.config = shell.get_config(False)
self.dns_resolver = asyncdns.DNSResolver()
if not self.config.get('dns_ipv6', False):
asyncdns.IPV6_CONNECTION_SUPPORT = False
self.mgr = None #asyncmgr.ServerMgr()
self.tcp_servers_pool = {}
self.tcp_ipv6_servers_pool = {}
self.udp_servers_pool = {}
self.udp_ipv6_servers_pool = {}
self.stat_counter = {}
self.loop = eventloop.EventLoop()
self.thread = MainThread( (self.loop, self.dns_resolver, self.mgr) )
self.thread.start()
@staticmethod
def get_instance():
if ServerPool.instance is None:
ServerPool.instance = ServerPool()
return ServerPool.instance
def stop(self):
self.loop.stop()
@staticmethod
def _loop(loop, dns_resolver, mgr):
try:
if mgr is not None:
mgr.add_to_loop(loop)
dns_resolver.add_to_loop(loop)
loop.run()
except (KeyboardInterrupt, IOError, OSError) as e:
logging.error(e)
import traceback
traceback.print_exc()
os.exit(0)
except Exception as e:
logging.error(e)
import traceback
traceback.print_exc()
def server_is_run(self, port):
port = int(port)
ret = 0
if port in self.tcp_servers_pool:
ret = 1
if port in self.tcp_ipv6_servers_pool:
ret |= 2
return ret
def server_run_status(self, port):
if 'server' in self.config:
if port not in self.tcp_servers_pool:
return False
if 'server_ipv6' in self.config:
if port not in self.tcp_ipv6_servers_pool:
return False
return True
def new_server(self, port, user_config):
ret = True
port = int(port)
ipv6_ok = False
if 'server_ipv6' in self.config:
if port in self.tcp_ipv6_servers_pool:
logging.info("server already at %s:%d" % (self.config['server_ipv6'], port))
return 'this port server is already running'
else:
a_config = self.config.copy()
a_config.update(user_config)
if len(a_config['server_ipv6']) > 2 and a_config['server_ipv6'][0] == "[" and a_config['server_ipv6'][-1] == "]":
a_config['server_ipv6'] = a_config['server_ipv6'][1:-1]
a_config['server'] = a_config['server_ipv6']
a_config['server_port'] = port
a_config['max_connect'] = 128
a_config['method'] = common.to_str(a_config['method'])
try:
logging.info("starting server at [%s]:%d" % (common.to_str(a_config['server']), port))
tcp_server = tcprelay.TCPRelay(a_config, self.dns_resolver, False, stat_counter=self.stat_counter)
tcp_server.add_to_loop(self.loop)
self.tcp_ipv6_servers_pool.update({port: tcp_server})
udp_server = udprelay.UDPRelay(a_config, self.dns_resolver, False, stat_counter=self.stat_counter)
udp_server.add_to_loop(self.loop)
self.udp_ipv6_servers_pool.update({port: udp_server})
if common.to_str(a_config['server_ipv6']) == "::":
ipv6_ok = True
except Exception as e:
logging.warn("IPV6 %s " % (e,))
if 'server' in self.config:
if port in self.tcp_servers_pool:
logging.info("server already at %s:%d" % (common.to_str(self.config['server']), port))
return 'this port server is already running'
else:
a_config = self.config.copy()
a_config.update(user_config)
a_config['server_port'] = port
a_config['max_connect'] = 128
a_config['method'] = common.to_str(a_config['method'])
try:
logging.info("starting server at %s:%d" % (common.to_str(a_config['server']), port))
tcp_server = tcprelay.TCPRelay(a_config, self.dns_resolver, False)
tcp_server.add_to_loop(self.loop)
self.tcp_servers_pool.update({port: tcp_server})
udp_server = udprelay.UDPRelay(a_config, self.dns_resolver, False)
udp_server.add_to_loop(self.loop)
self.udp_servers_pool.update({port: udp_server})
except Exception as e:
if not ipv6_ok:
logging.warn("IPV4 %s " % (e,))
return True
def del_server(self, port):
port = int(port)
logging.info("del server at %d" % port)
try:
udpsock = socket(AF_INET, SOCK_DGRAM)
udpsock.sendto('%s:%s:0:0' % (get_config().MANAGE_PASS, port), (get_config().MANAGE_BIND_IP, get_config().MANAGE_PORT))
udpsock.close()
except Exception as e:
logging.warn(e)
return True
def cb_del_server(self, port):
port = int(port)
if port not in self.tcp_servers_pool:
logging.info("stopped server at %s:%d already stop" % (self.config['server'], port))
else:
logging.info("stopped server at %s:%d" % (self.config['server'], port))
try:
self.tcp_servers_pool[port].close(True)
del self.tcp_servers_pool[port]
except Exception as e:
logging.warn(e)
try:
self.udp_servers_pool[port].close(True)
del self.udp_servers_pool[port]
except Exception as e:
logging.warn(e)
if 'server_ipv6' in self.config:
if port not in self.tcp_ipv6_servers_pool:
logging.info("stopped server at [%s]:%d already stop" % (self.config['server_ipv6'], port))
else:
logging.info("stopped server at [%s]:%d" % (self.config['server_ipv6'], port))
try:
self.tcp_ipv6_servers_pool[port].close(True)
del self.tcp_ipv6_servers_pool[port]
except Exception as e:
logging.warn(e)
try:
self.udp_ipv6_servers_pool[port].close(True)
del self.udp_ipv6_servers_pool[port]
except Exception as e:
logging.warn(e)
return True
def get_server_transfer(self, port):
port = int(port)
ret = [0, 0]
if port in self.tcp_servers_pool:
ret[0] = self.tcp_servers_pool[port].server_transfer_ul
ret[1] = self.tcp_servers_pool[port].server_transfer_dl
if port in self.udp_servers_pool:
ret[0] += self.udp_servers_pool[port].server_transfer_ul
ret[1] += self.udp_servers_pool[port].server_transfer_dl
if port in self.tcp_ipv6_servers_pool:
ret[0] += self.tcp_ipv6_servers_pool[port].server_transfer_ul
ret[1] += self.tcp_ipv6_servers_pool[port].server_transfer_dl
if port in self.udp_ipv6_servers_pool:
ret[0] += self.udp_ipv6_servers_pool[port].server_transfer_ul
ret[1] += self.udp_ipv6_servers_pool[port].server_transfer_dl
return ret
def get_servers_transfer(self):
servers = self.tcp_servers_pool.copy()
servers.update(self.tcp_ipv6_servers_pool)
servers.update(self.udp_servers_pool)
servers.update(self.udp_ipv6_servers_pool)
ret = {}
for port in servers.keys():
ret[port] = self.get_server_transfer(port)
return ret

@ -7,13 +7,13 @@ with codecs.open('README.rst', encoding='utf-8') as f:
setup(
name="shadowsocks",
version="2.6.11",
version="2.6.12",
license='http://www.apache.org/licenses/LICENSE-2.0',
description="A fast tunnel proxy that help you get through firewalls",
author='clowwindy',
author_email='clowwindy42@gmail.com',
url='https://github.com/shadowsocks/shadowsocks',
packages=['shadowsocks', 'shadowsocks.crypto'],
packages=['shadowsocks', 'shadowsocks.crypto', 'shadowsocks.obfsplugin'],
package_data={
'shadowsocks': ['README.rst', 'LICENSE']
},

@ -18,19 +18,24 @@
from __future__ import absolute_import, division, print_function, \
with_statement
import time
import os
import socket
import struct
import re
import logging
if __name__ == '__main__':
import sys
import inspect
file_path = os.path.dirname(os.path.realpath(inspect.getfile(inspect.currentframe())))
sys.path.insert(0, os.path.join(file_path, '../'))
from shadowsocks import common, lru_cache, eventloop, shell
CACHE_SWEEP_INTERVAL = 30
VALID_HOSTNAME = re.compile(br"(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
VALID_HOSTNAME = re.compile(br"(?!-)[A-Z\d_-]{1,63}(?<!-)$", re.IGNORECASE)
common.patch_socket()
@ -72,6 +77,19 @@ QTYPE_CNAME = 5
QTYPE_NS = 2
QCLASS_IN = 1
def detect_ipv6_supprot():
if 'has_ipv6' in dir(socket):
try:
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
s.connect(('::1', 0))
print('IPv6 support')
return True
except:
pass
print('IPv6 not support')
return False
IPV6_CONNECTION_SUPPORT = detect_ipv6_supprot()
def build_address(address):
address = address.strip(b'.')
@ -256,7 +274,6 @@ class DNSResolver(object):
self._hostname_to_cb = {}
self._cb_to_hostname = {}
self._cache = lru_cache.LRUCache(timeout=300)
self._last_time = time.time()
self._sock = None
self._servers = None
self._parse_resolv()
@ -267,23 +284,44 @@ class DNSResolver(object):
def _parse_resolv(self):
self._servers = []
try:
with open('/etc/resolv.conf', 'rb') as f:
with open('dns.conf', 'rb') as f:
content = f.readlines()
for line in content:
line = line.strip()
if line:
if line.startswith(b'nameserver'):
parts = line.split()
if len(parts) >= 2:
server = parts[1]
if common.is_ip(server) == socket.AF_INET:
if type(server) != str:
server = server.decode('utf8')
self._servers.append(server)
parts = line.split(b' ', 1)
if len(parts) >= 2:
server = parts[0]
port = int(parts[1])
else:
server = parts[0]
port = 53
if common.is_ip(server) == socket.AF_INET:
if type(server) != str:
server = server.decode('utf8')
self._servers.append((server, port))
except IOError:
pass
if not self._servers:
self._servers = ['8.8.4.4', '8.8.8.8']
try:
with open('/etc/resolv.conf', 'rb') as f:
content = f.readlines()
for line in content:
line = line.strip()
if line:
if line.startswith(b'nameserver'):
parts = line.split()
if len(parts) >= 2:
server = parts[1]
if common.is_ip(server) == socket.AF_INET:
if type(server) != str:
server = server.decode('utf8')
self._servers.append((server, 53))
except IOError:
pass
if not self._servers:
self._servers = [('8.8.4.4', 53), ('8.8.8.8', 53)]
logging.info('dns server: %s' % (self._servers,))
def _parse_hosts(self):
etc_path = '/etc/hosts'
@ -304,7 +342,7 @@ class DNSResolver(object):
except IOError:
self._hosts['localhost'] = '127.0.0.1'
def add_to_loop(self, loop, ref=False):
def add_to_loop(self, loop):
if self._loop:
raise Exception('already add to loop')
self._loop = loop
@ -312,8 +350,8 @@ class DNSResolver(object):
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
socket.SOL_UDP)
self._sock.setblocking(False)
loop.add(self._sock, eventloop.POLL_IN)
loop.add_handler(self.handle_events, ref=ref)
loop.add(self._sock, eventloop.POLL_IN, self)
loop.add_periodic(self.handle_periodic)
def _call_callback(self, hostname, ip, error=None):
callbacks = self._hostname_to_cb.get(hostname, [])
@ -340,44 +378,56 @@ class DNSResolver(object):
answer[2] == QCLASS_IN:
ip = answer[0]
break
if not ip and self._hostname_status.get(hostname, STATUS_IPV6) \
== STATUS_IPV4:
self._hostname_status[hostname] = STATUS_IPV6
self._send_req(hostname, QTYPE_AAAA)
else:
if ip:
self._cache[hostname] = ip
self._call_callback(hostname, ip)
elif self._hostname_status.get(hostname, None) == STATUS_IPV6:
for question in response.questions:
if question[1] == QTYPE_AAAA:
self._call_callback(hostname, None)
break
def handle_events(self, events):
for sock, fd, event in events:
if sock != self._sock:
continue
if event & eventloop.POLL_ERR:
logging.error('dns socket err')
self._loop.remove(self._sock)
self._sock.close()
# TODO when dns server is IPv6
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
socket.SOL_UDP)
self._sock.setblocking(False)
self._loop.add(self._sock, eventloop.POLL_IN)
if IPV6_CONNECTION_SUPPORT:
if not ip and self._hostname_status.get(hostname, STATUS_IPV4) \
== STATUS_IPV6:
self._hostname_status[hostname] = STATUS_IPV4
self._send_req(hostname, QTYPE_A)
else:
if ip:
self._cache[hostname] = ip
self._call_callback(hostname, ip)
elif self._hostname_status.get(hostname, None) == STATUS_IPV4:
for question in response.questions:
if question[1] == QTYPE_A:
self._call_callback(hostname, None)
break
else:
data, addr = sock.recvfrom(1024)
if addr[0] not in self._servers:
logging.warn('received a packet other than our dns')
break
self._handle_data(data)
break
now = time.time()
if now - self._last_time > CACHE_SWEEP_INTERVAL:
self._cache.sweep()
self._last_time = now
if not ip and self._hostname_status.get(hostname, STATUS_IPV6) \
== STATUS_IPV4:
self._hostname_status[hostname] = STATUS_IPV6
self._send_req(hostname, QTYPE_AAAA)
else:
if ip:
self._cache[hostname] = ip
self._call_callback(hostname, ip)
elif self._hostname_status.get(hostname, None) == STATUS_IPV6:
for question in response.questions:
if question[1] == QTYPE_AAAA:
self._call_callback(hostname, None)
break
def handle_event(self, sock, fd, event):
if sock != self._sock:
return
if event & eventloop.POLL_ERR:
logging.error('dns socket err')
self._loop.remove(self._sock)
self._sock.close()
# TODO when dns server is IPv6
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
socket.SOL_UDP)
self._sock.setblocking(False)
self._loop.add(self._sock, eventloop.POLL_IN, self)
else:
data, addr = sock.recvfrom(1024)
if addr not in self._servers:
logging.warn('received a packet other than our dns')
return
self._handle_data(data)
def handle_periodic(self):
self._cache.sweep()
def remove_callback(self, callback):
hostname = self._cb_to_hostname.get(callback)
@ -396,7 +446,7 @@ class DNSResolver(object):
for server in self._servers:
logging.debug('resolving %s with type %d using server %s',
hostname, qtype, server)
self._sock.sendto(req, (server, 53))
self._sock.sendto(req, server)
def resolve(self, hostname, callback):
if type(hostname) != bytes:
@ -417,19 +467,38 @@ class DNSResolver(object):
if not is_valid_hostname(hostname):
callback(None, Exception('invalid hostname: %s' % hostname))
return
if False:
addrs = socket.getaddrinfo(hostname, 0, 0,
socket.SOCK_DGRAM, socket.SOL_UDP)
if addrs:
af, socktype, proto, canonname, sa = addrs[0]
logging.debug('DNS resolve %s %s' % (hostname, sa[0]) )
self._cache[hostname] = sa[0]
callback((hostname, sa[0]), None)
return
arr = self._hostname_to_cb.get(hostname, None)
if not arr:
self._hostname_status[hostname] = STATUS_IPV4
self._send_req(hostname, QTYPE_A)
if IPV6_CONNECTION_SUPPORT:
self._hostname_status[hostname] = STATUS_IPV6
self._send_req(hostname, QTYPE_AAAA)
else:
self._hostname_status[hostname] = STATUS_IPV4
self._send_req(hostname, QTYPE_A)
self._hostname_to_cb[hostname] = [callback]
self._cb_to_hostname[callback] = hostname
else:
arr.append(callback)
# TODO send again only if waited too long
self._send_req(hostname, QTYPE_A)
if IPV6_CONNECTION_SUPPORT:
self._send_req(hostname, QTYPE_AAAA)
else:
self._send_req(hostname, QTYPE_A)
def close(self):
if self._sock:
if self._loop:
self._loop.remove_periodic(self.handle_periodic)
self._loop.remove(self._sock)
self._sock.close()
self._sock = None
@ -437,7 +506,7 @@ class DNSResolver(object):
def test():
dns_resolver = DNSResolver()
loop = eventloop.EventLoop()
dns_resolver.add_to_loop(loop, ref=True)
dns_resolver.add_to_loop(loop)
global counter
counter = 0
@ -451,8 +520,8 @@ def test():
print(result, error)
counter += 1
if counter == 9:
loop.remove_handler(dns_resolver.handle_events)
dns_resolver.close()
loop.stop()
a_callback = callback
return a_callback
@ -481,3 +550,4 @@ def test():
if __name__ == '__main__':
test()

@ -21,7 +21,8 @@ from __future__ import absolute_import, division, print_function, \
import socket
import struct
import logging
import binascii
import re
def compat_ord(s):
if type(s) == int:
@ -40,6 +41,7 @@ _chr = chr
ord = compat_ord
chr = compat_chr
connect_log = logging.debug
def to_bytes(s):
if bytes != str:
@ -54,6 +56,16 @@ def to_str(s):
return s.decode('utf-8')
return s
def int32(x):
if x > 0xFFFFFFFF or x < 0:
x &= 0xFFFFFFFF
if x > 0x7FFFFFFF:
x = int(0x100000000 - x)
if x < 0x80000000:
return -x
else:
return -2147483648
return x
def inet_ntop(family, ipstr):
if family == socket.AF_INET:
@ -74,7 +86,7 @@ def inet_pton(family, addr):
if '.' in addr: # a v4 addr
v4addr = addr[addr.rindex(':') + 1:]
v4addr = socket.inet_aton(v4addr)
v4addr = map(lambda x: ('%02X' % ord(x)), v4addr)
v4addr = ['%02X' % ord(x) for x in v4addr]
v4addr.insert(2, ':')
newaddr = addr[:addr.rindex(':') + 1] + ''.join(v4addr)
return inet_pton(family, newaddr)
@ -107,6 +119,13 @@ def is_ip(address):
return False
def match_regex(regex, text):
regex = re.compile(regex)
for item in regex.findall(text):
return True
return False
def patch_socket():
if not hasattr(socket, 'inet_pton'):
socket.inet_pton = inet_pton
@ -138,12 +157,54 @@ def pack_addr(address):
address = address[:255] # TODO
return b'\x03' + chr(len(address)) + address
def pre_parse_header(data):
if not data:
return None
datatype = ord(data[0])
if datatype == 0x80:
if len(data) <= 2:
return None
rand_data_size = ord(data[1])
if rand_data_size + 2 >= len(data):
logging.warn('header too short, maybe wrong password or '
'encryption method')
return None
data = data[rand_data_size + 2:]
elif datatype == 0x81:
data = data[1:]
elif datatype == 0x82:
if len(data) <= 3:
return None
rand_data_size = struct.unpack('>H', data[1:3])[0]
if rand_data_size + 3 >= len(data):
logging.warn('header too short, maybe wrong password or '
'encryption method')
return None
data = data[rand_data_size + 3:]
elif datatype == 0x88 or (~datatype & 0xff) == 0x88:
if len(data) <= 7 + 7:
return None
data_size = struct.unpack('>H', data[1:3])[0]
ogn_data = data
data = data[:data_size]
crc = binascii.crc32(data) & 0xffffffff
if crc != 0xffffffff:
logging.warn('uncorrect CRC32, maybe wrong password or '
'encryption method')
return None
start_pos = 3 + ord(data[3])
data = data[start_pos:-4]
if data_size < len(ogn_data):
data += ogn_data[data_size:]
return data
def parse_header(data):
addrtype = ord(data[0])
dest_addr = None
dest_port = None
header_length = 0
connecttype = (addrtype & 0x8) and 1 or 0
addrtype &= ~0x8
if addrtype == ADDRTYPE_IPV4:
if len(data) >= 7:
dest_addr = socket.inet_ntoa(data[1:5])
@ -154,10 +215,10 @@ def parse_header(data):
elif addrtype == ADDRTYPE_HOST:
if len(data) > 2:
addrlen = ord(data[1])
if len(data) >= 2 + addrlen:
if len(data) >= 4 + addrlen:
dest_addr = data[2:2 + addrlen]
dest_port = struct.unpack('>H', data[2 + addrlen:4 +
addrlen])[0]
addrlen])[0]
header_length = 4 + addrlen
else:
logging.warn('header is too short')
@ -175,13 +236,14 @@ def parse_header(data):
'encryption method' % addrtype)
if dest_addr is None:
return None
return addrtype, to_bytes(dest_addr), dest_port, header_length
return connecttype, to_bytes(dest_addr), dest_port, header_length
class IPNetwork(object):
ADDRLENGTH = {socket.AF_INET: 32, socket.AF_INET6: 128, False: 0}
def __init__(self, addrs):
self.addrs_str = addrs
self._network_list_v4 = []
self._network_list_v6 = []
if type(addrs) == str:
@ -232,6 +294,39 @@ class IPNetwork(object):
else:
return False
def __cmp__(self, other):
return cmp(self.addrs_str, other.addrs_str)
class PortRange(object):
def __init__(self, range_str):
self.range_str = to_str(range_str)
self.range = set()
range_str = to_str(range_str).split(',')
for item in range_str:
try:
int_range = item.split('-')
if len(int_range) == 1:
if item:
self.range.add(int(item))
elif len(int_range) == 2:
int_range[0] = int(int_range[0])
int_range[1] = int(int_range[1])
if int_range[0] < 0:
int_range[0] = 0
if int_range[1] > 65535:
int_range[1] = 65535
i = int_range[0]
while i <= int_range[1]:
self.range.add(i)
i += 1
except Exception as e:
logging.error(e)
def __contains__(self, val):
return val in self.range
def __cmp__(self, other):
return cmp(self.range_str, other.range_str)
def test_inet_conv():
ipv4 = b'8.8.4.4'
@ -244,12 +339,12 @@ def test_inet_conv():
def test_parse_header():
assert parse_header(b'\x03\x0ewww.google.com\x00\x50') == \
(3, b'www.google.com', 80, 18)
(0, b'www.google.com', 80, 18)
assert parse_header(b'\x01\x08\x08\x08\x08\x00\x35') == \
(1, b'8.8.8.8', 53, 7)
(0, b'8.8.8.8', 53, 7)
assert parse_header((b'\x04$\x04h\x00@\x05\x08\x05\x00\x00\x00\x00\x00'
b'\x00\x10\x11\x00\x50')) == \
(4, b'2404:6800:4005:805::1011', 80, 19)
(0, b'2404:6800:4005:805::1011', 80, 19)
def test_pack_header():

@ -0,0 +1,135 @@
#!/usr/bin/env python
# Copyright (c) 2014 clowwindy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import absolute_import, division, print_function, \
with_statement
import logging
from ctypes import CDLL, c_char_p, c_int, c_ulonglong, byref, \
create_string_buffer, c_void_p
__all__ = ['ciphers']
libsodium = None
loaded = False
buf_size = 2048
# for salsa20 and chacha20
BLOCK_SIZE = 64
def load_libsodium():
global loaded, libsodium, buf
from ctypes.util import find_library
for p in ('sodium',):
libsodium_path = find_library(p)
if libsodium_path:
break
else:
raise Exception('libsodium not found')
logging.info('loading libsodium from %s', libsodium_path)
libsodium = CDLL(libsodium_path)
libsodium.sodium_init.restype = c_int
libsodium.crypto_stream_salsa20_xor_ic.restype = c_int
libsodium.crypto_stream_salsa20_xor_ic.argtypes = (c_void_p, c_char_p,
c_ulonglong,
c_char_p, c_ulonglong,
c_char_p)
libsodium.crypto_stream_chacha20_xor_ic.restype = c_int
libsodium.crypto_stream_chacha20_xor_ic.argtypes = (c_void_p, c_char_p,
c_ulonglong,
c_char_p, c_ulonglong,
c_char_p)
libsodium.sodium_init()
buf = create_string_buffer(buf_size)
loaded = True
class Salsa20Crypto(object):
def __init__(self, cipher_name, key, iv, op):
if not loaded:
load_libsodium()
self.key = key
self.iv = iv
self.key_ptr = c_char_p(key)
self.iv_ptr = c_char_p(iv)
if cipher_name == b'salsa20':
self.cipher = libsodium.crypto_stream_salsa20_xor_ic
elif cipher_name == b'chacha20':
self.cipher = libsodium.crypto_stream_chacha20_xor_ic
else:
raise Exception('Unknown cipher')
# byte counter, not block counter
self.counter = 0
def update(self, data):
global buf_size, buf
l = len(data)
# we can only prepend some padding to make the encryption align to
# blocks
padding = self.counter % BLOCK_SIZE
if buf_size < padding + l:
buf_size = (padding + l) * 2
buf = create_string_buffer(buf_size)
if padding:
data = (b'\0' * padding) + data
self.cipher(byref(buf), c_char_p(data), padding + l,
self.iv_ptr, int(self.counter / BLOCK_SIZE), self.key_ptr)
self.counter += l
# buf is copied to a str object when we access buf.raw
# strip off the padding
return buf.raw[padding:padding + l]
ciphers = {
b'salsa20': (32, 8, Salsa20Crypto),
b'chacha20': (32, 8, Salsa20Crypto),
}
def test_salsa20():
from shadowsocks.crypto import util
cipher = Salsa20Crypto(b'salsa20', b'k' * 32, b'i' * 16, 1)
decipher = Salsa20Crypto(b'salsa20', b'k' * 32, b'i' * 16, 0)
util.run_cipher(cipher, decipher)
def test_chacha20():
from shadowsocks.crypto import util
cipher = Salsa20Crypto(b'chacha20', b'k' * 32, b'i' * 16, 1)
decipher = Salsa20Crypto(b'chacha20', b'k' * 32, b'i' * 16, 0)
util.run_cipher(cipher, decipher)
if __name__ == '__main__':
test_chacha20()
test_salsa20()

@ -0,0 +1,188 @@
#!/usr/bin/env python
# Copyright (c) 2014 clowwindy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import absolute_import, division, print_function, \
with_statement
import logging
from ctypes import CDLL, c_char_p, c_int, c_long, byref,\
create_string_buffer, c_void_p
__all__ = ['ciphers']
libcrypto = None
loaded = False
buf_size = 2048
def load_openssl():
global loaded, libcrypto, buf
from ctypes.util import find_library
for p in ('crypto', 'eay32', 'libeay32'):
libcrypto_path = find_library(p)
if libcrypto_path:
break
else:
raise Exception('libcrypto(OpenSSL) not found')
logging.info('loading libcrypto from %s', libcrypto_path)
libcrypto = CDLL(libcrypto_path)
libcrypto.EVP_get_cipherbyname.restype = c_void_p
libcrypto.EVP_CIPHER_CTX_new.restype = c_void_p
libcrypto.EVP_CipherInit_ex.argtypes = (c_void_p, c_void_p, c_char_p,
c_char_p, c_char_p, c_int)
libcrypto.EVP_CipherUpdate.argtypes = (c_void_p, c_void_p, c_void_p,
c_char_p, c_int)
libcrypto.EVP_CIPHER_CTX_cleanup.argtypes = (c_void_p,)
libcrypto.EVP_CIPHER_CTX_free.argtypes = (c_void_p,)
if hasattr(libcrypto, 'OpenSSL_add_all_ciphers'):
libcrypto.OpenSSL_add_all_ciphers()
buf = create_string_buffer(buf_size)
loaded = True
def load_cipher(cipher_name):
func_name = b'EVP_' + cipher_name.replace(b'-', b'_')
if bytes != str:
func_name = str(func_name, 'utf-8')
cipher = getattr(libcrypto, func_name, None)
if cipher:
cipher.restype = c_void_p
return cipher()
return None
class CtypesCrypto(object):
def __init__(self, cipher_name, key, iv, op):
if not loaded:
load_openssl()
self._ctx = None
cipher = libcrypto.EVP_get_cipherbyname(cipher_name)
if not cipher:
cipher = load_cipher(cipher_name)
if not cipher:
raise Exception('cipher %s not found in libcrypto' % cipher_name)
key_ptr = c_char_p(key)
iv_ptr = c_char_p(iv)
self._ctx = libcrypto.EVP_CIPHER_CTX_new()
if not self._ctx:
raise Exception('can not create cipher context')
r = libcrypto.EVP_CipherInit_ex(self._ctx, cipher, None,
key_ptr, iv_ptr, c_int(op))
if not r:
self.clean()
raise Exception('can not initialize cipher context')
def update(self, data):
global buf_size, buf
cipher_out_len = c_long(0)
l = len(data)
if buf_size < l:
buf_size = l * 2
buf = create_string_buffer(buf_size)
libcrypto.EVP_CipherUpdate(self._ctx, byref(buf),
byref(cipher_out_len), c_char_p(data), l)
# buf is copied to a str object when we access buf.raw
return buf.raw[:cipher_out_len.value]
def __del__(self):
self.clean()
def clean(self):
if self._ctx:
libcrypto.EVP_CIPHER_CTX_cleanup(self._ctx)
libcrypto.EVP_CIPHER_CTX_free(self._ctx)
ciphers = {
b'aes-128-cfb': (16, 16, CtypesCrypto),
b'aes-192-cfb': (24, 16, CtypesCrypto),
b'aes-256-cfb': (32, 16, CtypesCrypto),
b'aes-128-ofb': (16, 16, CtypesCrypto),
b'aes-192-ofb': (24, 16, CtypesCrypto),
b'aes-256-ofb': (32, 16, CtypesCrypto),
b'aes-128-ctr': (16, 16, CtypesCrypto),
b'aes-192-ctr': (24, 16, CtypesCrypto),
b'aes-256-ctr': (32, 16, CtypesCrypto),
b'aes-128-cfb8': (16, 16, CtypesCrypto),
b'aes-192-cfb8': (24, 16, CtypesCrypto),
b'aes-256-cfb8': (32, 16, CtypesCrypto),
b'aes-128-cfb1': (16, 16, CtypesCrypto),
b'aes-192-cfb1': (24, 16, CtypesCrypto),
b'aes-256-cfb1': (32, 16, CtypesCrypto),
b'bf-cfb': (16, 8, CtypesCrypto),
b'camellia-128-cfb': (16, 16, CtypesCrypto),
b'camellia-192-cfb': (24, 16, CtypesCrypto),
b'camellia-256-cfb': (32, 16, CtypesCrypto),
b'cast5-cfb': (16, 8, CtypesCrypto),
b'des-cfb': (8, 8, CtypesCrypto),
b'idea-cfb': (16, 8, CtypesCrypto),
b'rc2-cfb': (16, 8, CtypesCrypto),
b'rc4': (16, 0, CtypesCrypto),
b'seed-cfb': (16, 16, CtypesCrypto),
}
def run_method(method):
from shadowsocks.crypto import util
cipher = CtypesCrypto(method, b'k' * 32, b'i' * 16, 1)
decipher = CtypesCrypto(method, b'k' * 32, b'i' * 16, 0)
util.run_cipher(cipher, decipher)
def test_aes_128_cfb():
run_method(b'aes-128-cfb')
def test_aes_256_cfb():
run_method(b'aes-256-cfb')
def test_aes_128_cfb8():
run_method(b'aes-128-cfb8')
def test_aes_256_ofb():
run_method(b'aes-256-ofb')
def test_aes_256_ctr():
run_method(b'aes-256-ctr')
def test_bf_cfb():
run_method(b'bf-cfb')
def test_rc4():
run_method(b'rc4')
if __name__ == '__main__':
test_aes_128_cfb()

@ -49,8 +49,15 @@ def load_openssl():
libcrypto.EVP_CipherUpdate.argtypes = (c_void_p, c_void_p, c_void_p,
c_char_p, c_int)
libcrypto.EVP_CIPHER_CTX_cleanup.argtypes = (c_void_p,)
if hasattr(libcrypto, "EVP_CIPHER_CTX_cleanup"):
libcrypto.EVP_CIPHER_CTX_cleanup.argtypes = (c_void_p,)
else:
libcrypto.EVP_CIPHER_CTX_reset.argtypes = (c_void_p,)
libcrypto.EVP_CIPHER_CTX_free.argtypes = (c_void_p,)
libcrypto.RAND_bytes.restype = c_int
libcrypto.RAND_bytes.argtypes = (c_void_p, c_int)
if hasattr(libcrypto, 'OpenSSL_add_all_ciphers'):
libcrypto.OpenSSL_add_all_ciphers()
@ -68,6 +75,14 @@ def load_cipher(cipher_name):
return cipher()
return None
def rand_bytes(length):
if not loaded:
load_openssl()
buf = create_string_buffer(length)
r = libcrypto.RAND_bytes(buf, length)
if r <= 0:
raise Exception('RAND_bytes return error')
return buf.raw
class OpenSSLCrypto(object):
def __init__(self, cipher_name, key, iv, op):
@ -108,11 +123,17 @@ class OpenSSLCrypto(object):
def clean(self):
if self._ctx:
libcrypto.EVP_CIPHER_CTX_cleanup(self._ctx)
if hasattr(libcrypto, "EVP_CIPHER_CTX_cleanup"):
libcrypto.EVP_CIPHER_CTX_cleanup(self._ctx)
else:
libcrypto.EVP_CIPHER_CTX_reset(self._ctx)
libcrypto.EVP_CIPHER_CTX_free(self._ctx)
ciphers = {
'aes-128-cbc': (16, 16, OpenSSLCrypto),
'aes-192-cbc': (24, 16, OpenSSLCrypto),
'aes-256-cbc': (32, 16, OpenSSLCrypto),
'aes-128-cfb': (16, 16, OpenSSLCrypto),
'aes-192-cfb': (24, 16, OpenSSLCrypto),
'aes-256-cfb': (32, 16, OpenSSLCrypto),

@ -35,6 +35,7 @@ def create_cipher(alg, key, iv, op, key_as_bytes=0, d=None, salt=None,
ciphers = {
'rc4-md5': (16, 16, create_cipher),
'rc4-md5-6': (16, 6, create_cipher),
}

@ -17,7 +17,7 @@
from __future__ import absolute_import, division, print_function, \
with_statement
from ctypes import c_char_p, c_int, c_ulonglong, byref, \
from ctypes import c_char_p, c_int, c_ulong, c_ulonglong, byref, \
create_string_buffer, c_void_p
from shadowsocks.crypto import util
@ -29,7 +29,7 @@ loaded = False
buf_size = 2048
# for salsa20 and chacha20
# for salsa20 and chacha20 and chacha20-ietf
BLOCK_SIZE = 64
@ -52,6 +52,15 @@ def load_libsodium():
c_char_p, c_ulonglong,
c_char_p)
try:
libsodium.crypto_stream_chacha20_ietf_xor_ic.restype = c_int
libsodium.crypto_stream_chacha20_ietf_xor_ic.argtypes = (c_void_p, c_char_p,
c_ulonglong,
c_char_p, c_ulong,
c_char_p)
except:
pass
buf = create_string_buffer(buf_size)
loaded = True
@ -68,6 +77,8 @@ class SodiumCrypto(object):
self.cipher = libsodium.crypto_stream_salsa20_xor_ic
elif cipher_name == 'chacha20':
self.cipher = libsodium.crypto_stream_chacha20_xor_ic
elif cipher_name == 'chacha20-ietf':
self.cipher = libsodium.crypto_stream_chacha20_ietf_xor_ic
else:
raise Exception('Unknown cipher')
# byte counter, not block counter
@ -97,6 +108,7 @@ class SodiumCrypto(object):
ciphers = {
'salsa20': (32, 8, SodiumCrypto),
'chacha20': (32, 8, SodiumCrypto),
'chacha20-ietf': (32, 12, SodiumCrypto),
}
@ -115,6 +127,14 @@ def test_chacha20():
util.run_cipher(cipher, decipher)
def test_chacha20_ietf():
cipher = SodiumCrypto('chacha20-ietf', b'k' * 32, b'i' * 16, 1)
decipher = SodiumCrypto('chacha20-ietf', b'k' * 32, b'i' * 16, 0)
util.run_cipher(cipher, decipher)
if __name__ == '__main__':
test_chacha20_ietf()
test_chacha20()
test_salsa20()

@ -65,8 +65,15 @@ class TableCipher(object):
else:
return translate(data, self._decrypt_table)
class NoneCipher(object):
def __init__(self, cipher_name, key, iv, op):
pass
def update(self, data):
return data
ciphers = {
'none': (16, 0, NoneCipher),
'table': (0, 0, TableCipher)
}

@ -88,7 +88,8 @@ def find_library(possible_lib_names, search_symbol, library_name):
logging.warn('can\'t find symbol %s in %s', search_symbol,
path)
except Exception:
pass
if path == paths[-1]:
raise
return None

@ -34,8 +34,10 @@ method_supported.update(table.ciphers)
def random_string(length):
return os.urandom(length)
try:
return os.urandom(length)
except NotImplementedError as e:
return openssl.rand_bytes(length)
cached_keys = {}
@ -47,6 +49,8 @@ def try_cipher(key, method=None):
def EVP_BytesToKey(password, key_len, iv_len):
# equivalent to OpenSSL's EVP_BytesToKey() with count 1
# so that we make the same key and iv as nodejs version
if hasattr(password, 'encode'):
password = password.encode('utf-8')
cached_key = '%s-%d-%d' % (password, key_len, iv_len)
r = cached_keys.get(cached_key, None)
if r:
@ -69,18 +73,23 @@ def EVP_BytesToKey(password, key_len, iv_len):
class Encryptor(object):
def __init__(self, key, method):
def __init__(self, key, method, iv = None):
self.key = key
self.method = method
self.iv = None
self.iv_sent = False
self.cipher_iv = b''
self.iv_buf = b''
self.cipher_key = b''
self.decipher = None
method = method.lower()
self._method_info = self.get_method_info(method)
if self._method_info:
self.cipher = self.get_cipher(key, method, 1,
if iv is None or len(iv) != self._method_info[1]:
self.cipher = self.get_cipher(key, method, 1,
random_string(self._method_info[1]))
else:
self.cipher = self.get_cipher(key, method, 1, iv)
else:
logging.error('method %s not supported' % method)
sys.exit(1)
@ -106,6 +115,7 @@ class Encryptor(object):
if op == 1:
# this iv is for cipher not decipher
self.cipher_iv = iv[:m[1]]
self.cipher_key = key
return m[2](method, key, iv, op)
def encrypt(self, buf):
@ -120,16 +130,21 @@ class Encryptor(object):
def decrypt(self, buf):
if len(buf) == 0:
return buf
if self.decipher is None:
decipher_iv_len = self._method_info[1]
decipher_iv = buf[:decipher_iv_len]
if self.decipher is not None: #optimize
return self.decipher.update(buf)
decipher_iv_len = self._method_info[1]
if len(self.iv_buf) <= decipher_iv_len:
self.iv_buf += buf
if len(self.iv_buf) > decipher_iv_len:
decipher_iv = self.iv_buf[:decipher_iv_len]
self.decipher = self.get_cipher(self.key, self.method, 0,
iv=decipher_iv)
buf = buf[decipher_iv_len:]
if len(buf) == 0:
return buf
return self.decipher.update(buf)
buf = self.iv_buf[decipher_iv_len:]
del self.iv_buf
return self.decipher.update(buf)
else:
return b''
def encrypt_all(password, method, op, data):
result = []
@ -149,6 +164,40 @@ def encrypt_all(password, method, op, data):
result.append(cipher.update(data))
return b''.join(result)
def encrypt_key(password, method):
method = method.lower()
(key_len, iv_len, m) = method_supported[method]
if key_len > 0:
key, _ = EVP_BytesToKey(password, key_len, iv_len)
else:
key = password
return key
def encrypt_iv_len(method):
method = method.lower()
(key_len, iv_len, m) = method_supported[method]
return iv_len
def encrypt_new_iv(method):
method = method.lower()
(key_len, iv_len, m) = method_supported[method]
return random_string(iv_len)
def encrypt_all_iv(key, method, op, data, ref_iv):
result = []
method = method.lower()
(key_len, iv_len, m) = method_supported[method]
if op:
iv = ref_iv[0]
result.append(iv)
else:
iv = data[:iv_len]
data = data[iv_len:]
ref_iv[0] = iv
cipher = m(method, key, iv, op)
result.append(cipher.update(data))
return b''.join(result)
CIPHERS_TO_TEST = [
'aes-128-cfb',

@ -0,0 +1,51 @@
from __future__ import absolute_import, division, print_function, \
with_statement
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))
from shadowsocks.crypto import rc4_md5
from shadowsocks.crypto import openssl
from shadowsocks.crypto import sodium
from shadowsocks.crypto import table
def run(func):
try:
func()
except:
pass
def run_n(func, name):
try:
func(name)
except:
pass
def main():
print("\n""rc4_md5")
rc4_md5.test()
print("\n""aes-256-cfb")
openssl.test_aes_256_cfb()
print("\n""aes-128-cfb")
openssl.test_aes_128_cfb()
print("\n""bf-cfb")
run(openssl.test_bf_cfb)
print("\n""camellia-128-cfb")
run_n(openssl.run_method, "camellia-128-cfb")
print("\n""cast5-cfb")
run_n(openssl.run_method, "cast5-cfb")
print("\n""idea-cfb")
run_n(openssl.run_method, "idea-cfb")
print("\n""seed-cfb")
run_n(openssl.run_method, "seed-cfb")
print("\n""salsa20")
run(sodium.test_salsa20)
print("\n""chacha20")
run(sodium.test_chacha20)
if __name__ == '__main__':
main()

@ -22,6 +22,7 @@ from __future__ import absolute_import, division, print_function, \
with_statement
import os
import time
import socket
import select
import errno
@ -51,23 +52,8 @@ EVENT_NAMES = {
POLL_NVAL: 'POLL_NVAL',
}
class EpollLoop(object):
def __init__(self):
self._epoll = select.epoll()
def poll(self, timeout):
return self._epoll.poll(timeout)
def add_fd(self, fd, mode):
self._epoll.register(fd, mode)
def remove_fd(self, fd):
self._epoll.unregister(fd)
def modify_fd(self, fd, mode):
self._epoll.modify(fd, mode)
# we check timeouts every TIMEOUT_PRECISION seconds
TIMEOUT_PRECISION = 5
class KqueueLoop(object):
@ -100,17 +86,20 @@ class KqueueLoop(object):
results[fd] |= POLL_OUT
return results.items()
def add_fd(self, fd, mode):
def register(self, fd, mode):
self._fds[fd] = mode
self._control(fd, mode, select.KQ_EV_ADD)
def remove_fd(self, fd):
def unregister(self, fd):
self._control(fd, self._fds[fd], select.KQ_EV_DELETE)
del self._fds[fd]
def modify_fd(self, fd, mode):
self.remove_fd(fd)
self.add_fd(fd, mode)
def modify(self, fd, mode):
self.unregister(fd)
self.register(fd, mode)
def close(self):
self._kqueue.close()
class SelectLoop(object):
@ -129,7 +118,7 @@ class SelectLoop(object):
results[fd] |= p[1]
return results.items()
def add_fd(self, fd, mode):
def register(self, fd, mode):
if mode & POLL_IN:
self._r_list.add(fd)
if mode & POLL_OUT:
@ -137,7 +126,7 @@ class SelectLoop(object):
if mode & POLL_ERR:
self._x_list.add(fd)
def remove_fd(self, fd):
def unregister(self, fd):
if fd in self._r_list:
self._r_list.remove(fd)
if fd in self._w_list:
@ -145,16 +134,18 @@ class SelectLoop(object):
if fd in self._x_list:
self._x_list.remove(fd)
def modify_fd(self, fd, mode):
self.remove_fd(fd)
self.add_fd(fd, mode)
def modify(self, fd, mode):
self.unregister(fd)
self.register(fd, mode)
def close(self):
pass
class EventLoop(object):
def __init__(self):
self._iterating = False
if hasattr(select, 'epoll'):
self._impl = EpollLoop()
self._impl = select.epoll()
model = 'epoll'
elif hasattr(select, 'kqueue'):
self._impl = KqueueLoop()
@ -165,72 +156,74 @@ class EventLoop(object):
else:
raise Exception('can not find any available functions in select '
'package')
self._fd_to_f = {}
self._handlers = []
self._ref_handlers = []
self._handlers_to_remove = []
self._fdmap = {} # (f, handler)
self._last_time = time.time()
self._periodic_callbacks = []
self._stopping = False
logging.debug('using event model: %s', model)
def poll(self, timeout=None):
events = self._impl.poll(timeout)
return [(self._fd_to_f[fd], fd, event) for fd, event in events]
return [(self._fdmap[fd][0], fd, event) for fd, event in events]
def add(self, f, mode):
def add(self, f, mode, handler):
fd = f.fileno()
self._fd_to_f[fd] = f
self._impl.add_fd(fd, mode)
self._fdmap[fd] = (f, handler)
self._impl.register(fd, mode)
def remove(self, f):
fd = f.fileno()
del self._fd_to_f[fd]
self._impl.remove_fd(fd)
del self._fdmap[fd]
self._impl.unregister(fd)
def add_periodic(self, callback):
self._periodic_callbacks.append(callback)
def remove_periodic(self, callback):
self._periodic_callbacks.remove(callback)
def modify(self, f, mode):
fd = f.fileno()
self._impl.modify_fd(fd, mode)
def add_handler(self, handler, ref=True):
self._handlers.append(handler)
if ref:
# when all ref handlers are removed, loop stops
self._ref_handlers.append(handler)
def remove_handler(self, handler):
if handler in self._ref_handlers:
self._ref_handlers.remove(handler)
if self._iterating:
self._handlers_to_remove.append(handler)
else:
self._handlers.remove(handler)
self._impl.modify(fd, mode)
def stop(self):
self._stopping = True
def run(self):
events = []
while self._ref_handlers:
while not self._stopping:
asap = False
try:
events = self.poll(1)
events = self.poll(TIMEOUT_PRECISION)
except (OSError, IOError) as e:
if errno_from_exception(e) in (errno.EPIPE, errno.EINTR):
# EPIPE: Happens when the client closes the connection
# EINTR: Happens when received a signal
# handles them as soon as possible
asap = True
logging.debug('poll:%s', e)
else:
logging.error('poll:%s', e)
import traceback
traceback.print_exc()
continue
self._iterating = True
for handler in self._handlers:
# TODO when there are a lot of handlers
try:
handler(events)
except (OSError, IOError) as e:
shell.print_exception(e)
if self._handlers_to_remove:
for handler in self._handlers_to_remove:
self._handlers.remove(handler)
self._handlers_to_remove = []
self._iterating = False
for sock, fd, event in events:
handler = self._fdmap.get(fd, None)
if handler is not None:
handler = handler[1]
try:
handler.handle_event(sock, fd, event)
except (OSError, IOError) as e:
shell.print_exception(e)
now = time.time()
if asap or now - self._last_time >= TIMEOUT_PRECISION:
for callback in self._periodic_callbacks:
callback()
self._last_time = now
def __del__(self):
self._impl.close()
# from tornado

@ -23,7 +23,11 @@ import os
import logging
import signal
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))
if __name__ == '__main__':
import inspect
file_path = os.path.dirname(os.path.realpath(inspect.getfile(inspect.currentframe())))
sys.path.insert(0, os.path.join(file_path, '../'))
from shadowsocks import shell, daemon, eventloop, tcprelay, udprelay, asyncdns
@ -38,7 +42,12 @@ def main():
config = shell.get_config(True)
if not config.get('dns_ipv6', False):
asyncdns.IPV6_CONNECTION_SUPPORT = False
daemon.daemon_exec(config)
logging.info("local start with protocol[%s] password [%s] method [%s] obfs [%s] obfs_param [%s]" %
(config['protocol'], config['password'], config['method'], config['obfs'], config['obfs_param']))
try:
logging.info("starting local at %s:%d" %

@ -0,0 +1,6 @@
#!/bin/bash
cd `dirname $0`
eval $(ps -ef | grep "[0-9] python server\\.py a" | awk '{print "kill "$2}')
ulimit -n 4096
nohup python server.py a >> ssserver.log 2>&1 &

@ -22,14 +22,25 @@ import collections
import logging
import time
if __name__ == '__main__':
import os, sys, inspect
file_path = os.path.dirname(os.path.realpath(inspect.getfile(inspect.currentframe())))
sys.path.insert(0, os.path.join(file_path, '../'))
try:
from collections import OrderedDict
print("loaded collections.OrderedDict")
except:
from shadowsocks.ordereddict import OrderedDict
# this LRUCache is optimized for concurrency, not QPS
# n: concurrency, keys stored in the cache
# m: visits not timed out, proportional to QPS * timeout
# get & set is O(1), not O(n). thus we can support very large n
# TODO: if timeout or QPS is too large, then this cache is not very efficient,
# as sweep() causes long pause
# sweep is O((n - m)) or O(1024) at most,
# no metter how large the cache or timeout value is
SWEEP_MAX_ITEMS = 1024
class LRUCache(collections.MutableMapping):
"""This class is not thread safe"""
@ -38,73 +49,92 @@ class LRUCache(collections.MutableMapping):
self.timeout = timeout
self.close_callback = close_callback
self._store = {}
self._time_to_keys = collections.defaultdict(list)
self._keys_to_last_time = {}
self._last_visits = collections.deque()
self._closed_values = set()
self._keys_to_last_time = OrderedDict()
self.update(dict(*args, **kwargs)) # use the free update to set keys
def __getitem__(self, key):
# O(1)
t = time.time()
last_t = self._keys_to_last_time[key]
del self._keys_to_last_time[key]
self._keys_to_last_time[key] = t
self._time_to_keys[t].append(key)
self._last_visits.append(t)
return self._store[key]
def __setitem__(self, key, value):
# O(1)
t = time.time()
if key in self._keys_to_last_time:
del self._keys_to_last_time[key]
self._keys_to_last_time[key] = t
self._store[key] = value
self._time_to_keys[t].append(key)
self._last_visits.append(t)
def __delitem__(self, key):
# O(1)
last_t = self._keys_to_last_time[key]
del self._store[key]
del self._keys_to_last_time[key]
def __contains__(self, key):
return key in self._store
def __iter__(self):
return iter(self._store)
def __len__(self):
return len(self._store)
def first(self):
if len(self._keys_to_last_time) > 0:
for key in self._keys_to_last_time:
return key
def sweep(self):
# O(m)
# O(n - m)
now = time.time()
c = 0
while len(self._last_visits) > 0:
least = self._last_visits[0]
if now - least <= self.timeout:
while c < SWEEP_MAX_ITEMS:
if len(self._keys_to_last_time) == 0:
break
for key in self._keys_to_last_time:
break
last_t = self._keys_to_last_time[key]
if now - last_t <= self.timeout:
break
value = self._store[key]
del self._store[key]
del self._keys_to_last_time[key]
if self.close_callback is not None:
for key in self._time_to_keys[least]:
if key in self._store:
if now - self._keys_to_last_time[key] > self.timeout:
value = self._store[key]
if value not in self._closed_values:
self.close_callback(value)
self._closed_values.add(value)
for key in self._time_to_keys[least]:
self._last_visits.popleft()
if key in self._store:
if now - self._keys_to_last_time[key] > self.timeout:
del self._store[key]
del self._keys_to_last_time[key]
c += 1
del self._time_to_keys[least]
self.close_callback(value)
c += 1
if c:
self._closed_values.clear()
logging.debug('%d keys swept' % c)
return c < SWEEP_MAX_ITEMS
def clear(self, keep):
now = time.time()
c = 0
while len(self._keys_to_last_time) > keep:
if len(self._keys_to_last_time) == 0:
break
for key in self._keys_to_last_time:
break
last_t = self._keys_to_last_time[key]
value = self._store[key]
if self.close_callback is not None:
self.close_callback(value)
del self._store[key]
del self._keys_to_last_time[key]
c += 1
if c:
logging.debug('%d keys swept' % c)
return c < SWEEP_MAX_ITEMS
def test():
c = LRUCache(timeout=0.3)
c['a'] = 1
assert c['a'] == 1
c['a'] = 1
time.sleep(0.5)
c.sweep()

@ -0,0 +1,291 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2015 clowwindy
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import, division, print_function, \
with_statement
import errno
import traceback
import socket
import logging
import json
import collections
from shadowsocks import common, eventloop, tcprelay, udprelay, asyncdns, shell
BUF_SIZE = 1506
STAT_SEND_LIMIT = 50
class Manager(object):
def __init__(self, config):
self._config = config
self._relays = {} # (tcprelay, udprelay)
self._loop = eventloop.EventLoop()
self._dns_resolver = asyncdns.DNSResolver()
self._dns_resolver.add_to_loop(self._loop)
self._statistics = collections.defaultdict(int)
self._control_client_addr = None
try:
manager_address = common.to_str(config['manager_address'])
if ':' in manager_address:
addr = manager_address.rsplit(':', 1)
addr = addr[0], int(addr[1])
addrs = socket.getaddrinfo(addr[0], addr[1])
if addrs:
family = addrs[0][0]
else:
logging.error('invalid address: %s', manager_address)
exit(1)
else:
addr = manager_address
family = socket.AF_UNIX
self._control_socket = socket.socket(family,
socket.SOCK_DGRAM)
self._control_socket.bind(addr)
self._control_socket.setblocking(False)
except (OSError, IOError) as e:
logging.error(e)
logging.error('can not bind to manager address')
exit(1)
self._loop.add(self._control_socket,
eventloop.POLL_IN, self)
self._loop.add_periodic(self.handle_periodic)
port_password = config['port_password']
del config['port_password']
for port, password in port_password.items():
a_config = config.copy()
a_config['server_port'] = int(port)
a_config['password'] = password
self.add_port(a_config)
def add_port(self, config):
port = int(config['server_port'])
servers = self._relays.get(port, None)
if servers:
logging.error("server already exists at %s:%d" % (config['server'],
port))
return
logging.info("adding server at %s:%d" % (config['server'], port))
t = tcprelay.TCPRelay(config, self._dns_resolver, False,
stat_callback=self.stat_callback)
u = udprelay.UDPRelay(config, self._dns_resolver, False,
stat_callback=self.stat_callback)
t.add_to_loop(self._loop)
u.add_to_loop(self._loop)
self._relays[port] = (t, u)
def remove_port(self, config):
port = int(config['server_port'])
servers = self._relays.get(port, None)
if servers:
logging.info("removing server at %s:%d" % (config['server'], port))
t, u = servers
t.close(next_tick=False)
u.close(next_tick=False)
del self._relays[port]
else:
logging.error("server not exist at %s:%d" % (config['server'],
port))
def handle_event(self, sock, fd, event):
if sock == self._control_socket and event == eventloop.POLL_IN:
data, self._control_client_addr = sock.recvfrom(BUF_SIZE)
parsed = self._parse_command(data)
if parsed:
command, config = parsed
a_config = self._config.copy()
if config:
# let the command override the configuration file
a_config.update(config)
if 'server_port' not in a_config:
logging.error('can not find server_port in config')
else:
if command == 'add':
self.add_port(a_config)
self._send_control_data(b'ok')
elif command == 'remove':
self.remove_port(a_config)
self._send_control_data(b'ok')
elif command == 'ping':
self._send_control_data(b'pong')
else:
logging.error('unknown command %s', command)
def _parse_command(self, data):
# commands:
# add: {"server_port": 8000, "password": "foobar"}
# remove: {"server_port": 8000"}
data = common.to_str(data)
parts = data.split(':', 1)
if len(parts) < 2:
return data, None
command, config_json = parts
try:
config = shell.parse_json_in_str(config_json)
return command, config
except Exception as e:
logging.error(e)
return None
def stat_callback(self, port, data_len):
self._statistics[port] += data_len
def handle_periodic(self):
r = {}
i = 0
def send_data(data_dict):
if data_dict:
# use compact JSON format (without space)
data = common.to_bytes(json.dumps(data_dict,
separators=(',', ':')))
self._send_control_data(b'stat: ' + data)
for k, v in self._statistics.items():
r[k] = v
i += 1
# split the data into segments that fit in UDP packets
if i >= STAT_SEND_LIMIT:
send_data(r)
r.clear()
i = 0
if len(r) > 0 :
send_data(r)
self._statistics.clear()
def _send_control_data(self, data):
if self._control_client_addr:
try:
self._control_socket.sendto(data, self._control_client_addr)
except (socket.error, OSError, IOError) as e:
error_no = eventloop.errno_from_exception(e)
if error_no in (errno.EAGAIN, errno.EINPROGRESS,
errno.EWOULDBLOCK):
return
else:
shell.print_exception(e)
if self._config['verbose']:
traceback.print_exc()
def run(self):
self._loop.run()
def run(config):
Manager(config).run()
def test():
import time
import threading
import struct
from shadowsocks import encrypt
logging.basicConfig(level=5,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
enc = []
eventloop.TIMEOUT_PRECISION = 1
def run_server():
config = shell.get_config(True)
config = config.copy()
a_config = {
'server': '127.0.0.1',
'local_port': 1081,
'port_password': {
'8381': 'foobar1',
'8382': 'foobar2'
},
'method': 'aes-256-cfb',
'manager_address': '127.0.0.1:6001',
'timeout': 60,
'fast_open': False,
'verbose': 2
}
config.update(a_config)
manager = Manager(config)
enc.append(manager)
manager.run()
t = threading.Thread(target=run_server)
t.start()
time.sleep(1)
manager = enc[0]
cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
cli.connect(('127.0.0.1', 6001))
# test add and remove
time.sleep(1)
cli.send(b'add: {"server_port":7001, "password":"asdfadsfasdf"}')
time.sleep(1)
assert 7001 in manager._relays
data, addr = cli.recvfrom(1506)
assert b'ok' in data
cli.send(b'remove: {"server_port":8381}')
time.sleep(1)
assert 8381 not in manager._relays
data, addr = cli.recvfrom(1506)
assert b'ok' in data
logging.info('add and remove test passed')
# test statistics for TCP
header = common.pack_addr(b'google.com') + struct.pack('>H', 80)
data = encrypt.encrypt_all(b'asdfadsfasdf', 'aes-256-cfb', 1,
header + b'GET /\r\n\r\n')
tcp_cli = socket.socket()
tcp_cli.connect(('127.0.0.1', 7001))
tcp_cli.send(data)
tcp_cli.recv(4096)
tcp_cli.close()
data, addr = cli.recvfrom(1506)
data = common.to_str(data)
assert data.startswith('stat: ')
data = data.split('stat:')[1]
stats = shell.parse_json_in_str(data)
assert '7001' in stats
logging.info('TCP statistics test passed')
# test statistics for UDP
header = common.pack_addr(b'127.0.0.1') + struct.pack('>H', 80)
data = encrypt.encrypt_all(b'foobar2', 'aes-256-cfb', 1,
header + b'test')
udp_cli = socket.socket(type=socket.SOCK_DGRAM)
udp_cli.sendto(data, ('127.0.0.1', 8382))
tcp_cli.close()
data, addr = cli.recvfrom(1506)
data = common.to_str(data)
assert data.startswith('stat: ')
data = data.split('stat:')[1]
stats = json.loads(data)
assert '8382' in stats
logging.info('UDP statistics test passed')
manager._loop.stop()
t.join()
if __name__ == '__main__':
test()

@ -0,0 +1,104 @@
#!/usr/bin/env python
#
# Copyright 2015-2015 breakwa11
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import, division, print_function, \
with_statement
import os
import sys
import hashlib
import logging
from shadowsocks import common
from shadowsocks.obfsplugin import plain, http_simple, obfs_tls, verify, auth
method_supported = {}
method_supported.update(plain.obfs_map)
method_supported.update(http_simple.obfs_map)
method_supported.update(obfs_tls.obfs_map)
method_supported.update(verify.obfs_map)
method_supported.update(auth.obfs_map)
class server_info(object):
def __init__(self, data):
self.data = data
class obfs(object):
def __init__(self, method):
method = common.to_str(method)
self.method = method
self._method_info = self.get_method_info(method)
if self._method_info:
self.obfs = self.get_obfs(method)
else:
raise Exception('obfs plugin [%s] not supported' % method)
def init_data(self):
return self.obfs.init_data()
def set_server_info(self, server_info):
return self.obfs.set_server_info(server_info)
def get_method_info(self, method):
method = method.lower()
m = method_supported.get(method)
return m
def get_obfs(self, method):
m = self._method_info
return m[0](method)
def client_pre_encrypt(self, buf):
return self.obfs.client_pre_encrypt(buf)
def client_encode(self, buf):
return self.obfs.client_encode(buf)
def client_decode(self, buf):
return self.obfs.client_decode(buf)
def client_post_decrypt(self, buf):
return self.obfs.client_post_decrypt(buf)
def server_pre_encrypt(self, buf):
return self.obfs.server_pre_encrypt(buf)
def server_encode(self, buf):
return self.obfs.server_encode(buf)
def server_decode(self, buf):
return self.obfs.server_decode(buf)
def server_post_decrypt(self, buf):
return self.obfs.server_post_decrypt(buf)
def client_udp_pre_encrypt(self, buf):
return self.obfs.client_udp_pre_encrypt(buf)
def client_udp_post_decrypt(self, buf):
return self.obfs.client_udp_post_decrypt(buf)
def server_udp_pre_encrypt(self, buf):
return self.obfs.server_udp_pre_encrypt(buf)
def server_udp_post_decrypt(self, buf):
return self.obfs.server_udp_post_decrypt(buf)
def dispose(self):
self.obfs.dispose()
del self.obfs

@ -0,0 +1,18 @@
#!/usr/bin/env python
#
# Copyright 2015 clowwindy
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import, division, print_function, \
with_statement

File diff suppressed because it is too large Load Diff

@ -0,0 +1,307 @@
#!/usr/bin/env python
#
# Copyright 2015-2015 breakwa11
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import, division, print_function, \
with_statement
import os
import sys
import hashlib
import logging
import binascii
import struct
import base64
import datetime
import random
from shadowsocks import common
from shadowsocks.obfsplugin import plain
from shadowsocks.common import to_bytes, to_str, ord, chr
def create_http_simple_obfs(method):
return http_simple(method)
def create_http_post_obfs(method):
return http_post(method)
def create_random_head_obfs(method):
return random_head(method)
obfs_map = {
'http_simple': (create_http_simple_obfs,),
'http_simple_compatible': (create_http_simple_obfs,),
'http_post': (create_http_post_obfs,),
'http_post_compatible': (create_http_post_obfs,),
'random_head': (create_random_head_obfs,),
'random_head_compatible': (create_random_head_obfs,),
}
def match_begin(str1, str2):
if len(str1) >= len(str2):
if str1[:len(str2)] == str2:
return True
return False
class http_simple(plain.plain):
def __init__(self, method):
self.method = method
self.has_sent_header = False
self.has_recv_header = False
self.host = None
self.port = 0
self.recv_buffer = b''
self.user_agent = [b"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0",
b"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/44.0",
b"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
b"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Ubuntu/11.10 Chromium/27.0.1453.93 Chrome/27.0.1453.93 Safari/537.36",
b"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0",
b"Mozilla/5.0 (compatible; WOW64; MSIE 10.0; Windows NT 6.2)",
b"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27",
b"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; Trident/7.0; .NET4.0E; .NET4.0C)",
b"Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko",
b"Mozilla/5.0 (Linux; Android 4.4; Nexus 5 Build/BuildID) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36",
b"Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3",
b"Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3"]
def encode_head(self, buf):
hexstr = binascii.hexlify(buf)
chs = []
for i in range(0, len(hexstr), 2):
chs.append(b"%" + hexstr[i:i+2])
return b''.join(chs)
def client_encode(self, buf):
if self.has_sent_header:
return buf
head_size = len(self.server_info.iv) + self.server_info.head_len
if len(buf) - head_size > 64:
headlen = head_size + random.randint(0, 64)
else:
headlen = len(buf)
headdata = buf[:headlen]
buf = buf[headlen:]
port = b''
if self.server_info.port != 80:
port = b':' + to_bytes(str(self.server_info.port))
body = None
hosts = (self.server_info.obfs_param or self.server_info.host)
pos = hosts.find("#")
if pos >= 0:
body = hosts[pos + 1:].replace("\n", "\r\n")
body = body.replace("\\n", "\r\n")
hosts = hosts[:pos]
hosts = hosts.split(',')
host = random.choice(hosts)
http_head = b"GET /" + self.encode_head(headdata) + b" HTTP/1.1\r\n"
http_head += b"Host: " + to_bytes(host) + port + b"\r\n"
if body:
http_head += body + "\r\n\r\n"
else:
http_head += b"User-Agent: " + random.choice(self.user_agent) + b"\r\n"
http_head += b"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.8\r\nAccept-Encoding: gzip, deflate\r\nDNT: 1\r\nConnection: keep-alive\r\n\r\n"
self.has_sent_header = True
return http_head + buf
def client_decode(self, buf):
if self.has_recv_header:
return (buf, False)
pos = buf.find(b'\r\n\r\n')
if pos >= 0:
self.has_recv_header = True
return (buf[pos + 4:], False)
else:
return (b'', False)
def server_encode(self, buf):
if self.has_sent_header:
return buf
header = b'HTTP/1.1 200 OK\r\nConnection: keep-alive\r\nContent-Encoding: gzip\r\nContent-Type: text/html\r\nDate: '
header += to_bytes(datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S GMT'))
header += b'\r\nServer: nginx\r\nVary: Accept-Encoding\r\n\r\n'
self.has_sent_header = True
return header + buf
def get_data_from_http_header(self, buf):
ret_buf = b''
lines = buf.split(b'\r\n')
if lines and len(lines) > 4:
hex_items = lines[0].split(b'%')
if hex_items and len(hex_items) > 1:
for index in range(1, len(hex_items)):
if len(hex_items[index]) < 2:
ret_buf += binascii.unhexlify('0' + hex_items[index])
break
elif len(hex_items[index]) > 2:
ret_buf += binascii.unhexlify(hex_items[index][:2])
break
else:
ret_buf += binascii.unhexlify(hex_items[index])
return ret_buf
return b''
def get_host_from_http_header(self, buf):
ret_buf = b''
lines = buf.split(b'\r\n')
if lines and len(lines) > 4:
for line in lines:
if match_begin(line, b"Host: "):
return line[6:]
def not_match_return(self, buf):
self.has_sent_header = True
self.has_recv_header = True
if self.method == 'http_simple':
return (b'E'*2048, False, False)
return (buf, True, False)
def server_decode(self, buf):
if self.has_recv_header:
return (buf, True, False)
self.recv_buffer += buf
buf = self.recv_buffer
if len(buf) > 10:
if match_begin(buf, b'GET ') or match_begin(buf, b'POST '):
if len(buf) > 65536:
self.recv_buffer = None
logging.warn('http_simple: over size')
return self.not_match_return(buf)
else: #not http header, run on original protocol
self.recv_buffer = None
logging.debug('http_simple: not match begin')
return self.not_match_return(buf)
else:
return (b'', True, False)
if b'\r\n\r\n' in buf:
datas = buf.split(b'\r\n\r\n', 1)
ret_buf = self.get_data_from_http_header(buf)
host = self.get_host_from_http_header(buf)
if host and self.server_info.obfs_param:
pos = host.find(":")
if pos >= 0:
host = host[:pos]
hosts = self.server_info.obfs_param.split(',')
if host not in hosts:
return self.not_match_return(buf)
if len(datas) > 1:
ret_buf += datas[1]
if len(ret_buf) >= 7:
self.has_recv_header = True
return (ret_buf, True, False)
return self.not_match_return(buf)
else:
return (b'', True, False)
class http_post(http_simple):
def __init__(self, method):
super(http_post, self).__init__(method)
def boundary(self):
return b''.join([random.choice(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") for i in range(32)])
def client_encode(self, buf):
if self.has_sent_header:
return buf
head_size = len(self.server_info.iv) + self.server_info.head_len
if len(buf) - head_size > 64:
headlen = head_size + random.randint(0, 64)
else:
headlen = len(buf)
headdata = buf[:headlen]
buf = buf[headlen:]
port = b''
if self.server_info.port != 80:
port = b':' + to_bytes(str(self.server_info.port))
body = None
hosts = (self.server_info.obfs_param or self.server_info.host)
pos = hosts.find("#")
if pos >= 0:
body = hosts[pos + 1:].replace("\\n", "\r\n")
hosts = hosts[:pos]
hosts = hosts.split(',')
host = random.choice(hosts)
http_head = b"POST /" + self.encode_head(headdata) + b" HTTP/1.1\r\n"
http_head += b"Host: " + to_bytes(host) + port + b"\r\n"
if body:
http_head += body + "\r\n\r\n"
else:
http_head += b"User-Agent: " + random.choice(self.user_agent) + b"\r\n"
http_head += b"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.8\r\nAccept-Encoding: gzip, deflate\r\n"
http_head += b"Content-Type: multipart/form-data; boundary=" + self.boundary() + b"\r\nDNT: 1\r\n"
http_head += "Connection: keep-alive\r\n\r\n"
self.has_sent_header = True
return http_head + buf
def not_match_return(self, buf):
self.has_sent_header = True
self.has_recv_header = True
if self.method == 'http_post':
return (b'E'*2048, False, False)
return (buf, True, False)
class random_head(plain.plain):
def __init__(self, method):
self.method = method
self.has_sent_header = False
self.has_recv_header = False
self.raw_trans_sent = False
self.raw_trans_recv = False
self.send_buffer = b''
def client_encode(self, buf):
if self.raw_trans_sent:
return buf
self.send_buffer += buf
if not self.has_sent_header:
self.has_sent_header = True
data = os.urandom(common.ord(os.urandom(1)[0]) % 96 + 4)
crc = (0xffffffff - binascii.crc32(data)) & 0xffffffff
return data + struct.pack('<I', crc)
if self.raw_trans_recv:
ret = self.send_buffer
self.send_buffer = b''
self.raw_trans_sent = True
return ret
return b''
def client_decode(self, buf):
if self.raw_trans_recv:
return (buf, False)
self.raw_trans_recv = True
return (b'', True)
def server_encode(self, buf):
if self.has_sent_header:
return buf
self.has_sent_header = True
return os.urandom(common.ord(os.urandom(1)[0]) % 96 + 4)
def server_decode(self, buf):
if self.has_recv_header:
return (buf, True, False)
self.has_recv_header = True
crc = binascii.crc32(buf) & 0xffffffff
if crc != 0xffffffff:
self.has_sent_header = True
if self.method == 'random_head':
return (b'E'*2048, False, False)
return (buf, True, False)
# (buffer_to_recv, is_need_decrypt, is_need_to_encode_and_send_back)
return (b'', False, True)

@ -0,0 +1,270 @@
#!/usr/bin/env python
#
# Copyright 2015-2015 breakwa11
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import, division, print_function, \
with_statement
import os
import sys
import hashlib
import logging
import binascii
import struct
import base64
import time
import random
import hmac
import hashlib
import string
from shadowsocks import common
from shadowsocks.obfsplugin import plain
from shadowsocks.common import to_bytes, to_str, ord
from shadowsocks import lru_cache
def create_tls_ticket_auth_obfs(method):
return tls_ticket_auth(method)
obfs_map = {
'tls1.2_ticket_auth': (create_tls_ticket_auth_obfs,),
'tls1.2_ticket_auth_compatible': (create_tls_ticket_auth_obfs,),
}
def match_begin(str1, str2):
if len(str1) >= len(str2):
if str1[:len(str2)] == str2:
return True
return False
class obfs_auth_data(object):
def __init__(self):
self.client_data = lru_cache.LRUCache(60 * 5)
self.client_id = os.urandom(32)
self.startup_time = int(time.time() - 60 * 30) & 0xFFFFFFFF
class tls_ticket_auth(plain.plain):
def __init__(self, method):
self.method = method
self.handshake_status = 0
self.send_buffer = b''
self.recv_buffer = b''
self.client_id = b''
self.max_time_dif = 0 # time dif (second) setting
self.tls_version = b'\x03\x03'
def init_data(self):
return obfs_auth_data()
def sni(self, url):
url = common.to_bytes(url)
data = b"\x00" + struct.pack('>H', len(url)) + url
data = b"\x00\x00" + struct.pack('>H', len(data) + 2) + struct.pack('>H', len(data)) + data
return data
def pack_auth_data(self, client_id):
utc_time = int(time.time()) & 0xFFFFFFFF
data = struct.pack('>I', utc_time) + os.urandom(18)
data += hmac.new(self.server_info.key + client_id, data, hashlib.sha1).digest()[:10]
return data
def client_encode(self, buf):
if self.handshake_status == -1:
return buf
if self.handshake_status == 8:
ret = b''
while len(buf) > 2048:
size = min(struct.unpack('>H', os.urandom(2))[0] % 4096 + 100, len(buf))
ret += b"\x17" + self.tls_version + struct.pack('>H', size) + buf[:size]
buf = buf[size:]
if len(buf) > 0:
ret += b"\x17" + self.tls_version + struct.pack('>H', len(buf)) + buf
return ret
self.send_buffer += b"\x17" + self.tls_version + struct.pack('>H', len(buf)) + buf
if self.handshake_status == 0:
self.handshake_status = 1
data = self.tls_version + self.pack_auth_data(self.server_info.data.client_id) + b"\x20" + self.server_info.data.client_id + binascii.unhexlify(b"001cc02bc02fcca9cca8cc14cc13c00ac014c009c013009c0035002f000a" + b"0100")
ext = binascii.unhexlify(b"ff01000100")
host = self.server_info.obfs_param or self.server_info.host
if host and host[-1] in string.digits:
host = ''
hosts = host.split(',')
host = random.choice(hosts)
ext += self.sni(host)
ext += b"\x00\x17\x00\x00"
ext += b"\x00\x23\x00\xd0" + os.urandom(208) # ticket
ext += binascii.unhexlify(b"000d001600140601060305010503040104030301030302010203")
ext += binascii.unhexlify(b"000500050100000000")
ext += binascii.unhexlify(b"00120000")
ext += binascii.unhexlify(b"75500000")
ext += binascii.unhexlify(b"000b00020100")
ext += binascii.unhexlify(b"000a0006000400170018")
data += struct.pack('>H', len(ext)) + ext
data = b"\x01\x00" + struct.pack('>H', len(data)) + data
data = b"\x16\x03\x01" + struct.pack('>H', len(data)) + data
return data
elif self.handshake_status == 1 and len(buf) == 0:
data = b"\x14" + self.tls_version + b"\x00\x01\x01" #ChangeCipherSpec
data += b"\x16" + self.tls_version + b"\x00\x20" + os.urandom(22) #Finished
data += hmac.new(self.server_info.key + self.server_info.data.client_id, data, hashlib.sha1).digest()[:10]
ret = data + self.send_buffer
self.send_buffer = b''
self.handshake_status = 8
return ret
return b''
def client_decode(self, buf):
if self.handshake_status == -1:
return (buf, False)
if self.handshake_status == 8:
ret = b''
self.recv_buffer += buf
while len(self.recv_buffer) > 5:
if ord(self.recv_buffer[0]) != 0x17:
logging.info("data = %s" % (binascii.hexlify(self.recv_buffer)))
raise Exception('server_decode appdata error')
size = struct.unpack('>H', self.recv_buffer[3:5])[0]
if len(self.recv_buffer) < size + 5:
break
buf = self.recv_buffer[5:size+5]
ret += buf
self.recv_buffer = self.recv_buffer[size+5:]
return (ret, False)
if len(buf) < 11 + 32 + 1 + 32:
raise Exception('client_decode data error')
verify = buf[11:33]
if hmac.new(self.server_info.key + self.server_info.data.client_id, verify, hashlib.sha1).digest()[:10] != buf[33:43]:
raise Exception('client_decode data error')
return (b'', True)
def server_encode(self, buf):
if self.handshake_status == -1:
return buf
if self.handshake_status == 8:
ret = b''
while len(buf) > 2048:
size = min(struct.unpack('>H', os.urandom(2))[0] % 4096 + 100, len(buf))
ret += b"\x17" + self.tls_version + struct.pack('>H', size) + buf[:size]
buf = buf[size:]
if len(buf) > 0:
ret += b"\x17" + self.tls_version + struct.pack('>H', len(buf)) + buf
return ret
self.handshake_status = 3
data = self.tls_version + self.pack_auth_data(self.client_id) + b"\x20" + self.client_id + binascii.unhexlify(b"c02f000005ff01000100")
data = b"\x02\x00" + struct.pack('>H', len(data)) + data #server hello
data = b"\x16\x03\x03" + struct.pack('>H', len(data)) + data
data += b"\x14" + self.tls_version + b"\x00\x01\x01" #ChangeCipherSpec
data += b"\x16" + self.tls_version + b"\x00\x20" + os.urandom(22) #Finished
data += hmac.new(self.server_info.key + self.client_id, data, hashlib.sha1).digest()[:10]
return data
def decode_error_return(self, buf):
self.handshake_status = -1
if self.method == 'tls1.2_ticket_auth':
return (b'E'*2048, False, False)
return (buf, True, False)
def server_decode(self, buf):
if self.handshake_status == -1:
return (buf, True, False)
if self.handshake_status == 8:
ret = b''
self.recv_buffer += buf
while len(self.recv_buffer) > 5:
if ord(self.recv_buffer[0]) != 0x17 or ord(self.recv_buffer[1]) != 0x3 or ord(self.recv_buffer[2]) != 0x3:
logging.info("data = %s" % (binascii.hexlify(self.recv_buffer)))
raise Exception('server_decode appdata error')
size = struct.unpack('>H', self.recv_buffer[3:5])[0]
if len(self.recv_buffer) < size + 5:
break
ret += self.recv_buffer[5:size+5]
self.recv_buffer = self.recv_buffer[size+5:]
return (ret, True, False)
if self.handshake_status == 3:
verify = buf
verify_len = 43 - 10
if len(buf) < 43:
raise Exception('server_decode data error')
if not match_begin(buf, b"\x14" + self.tls_version + b"\x00\x01\x01"): #ChangeCipherSpec
raise Exception('server_decode data error')
buf = buf[6:]
if not match_begin(buf, b"\x16" + self.tls_version + b"\x00\x20"): #Finished
raise Exception('server_decode data error')
if hmac.new(self.server_info.key + self.client_id, verify[:verify_len], hashlib.sha1).digest()[:10] != verify[verify_len:verify_len+10]:
raise Exception('server_decode data error')
if len(buf) < 37:
raise Exception('server_decode data error')
self.recv_buffer = buf[37:]
self.handshake_status = 8
return self.server_decode(b'')
#raise Exception("handshake data = %s" % (binascii.hexlify(buf)))
self.handshake_status = 2
ogn_buf = buf
if not match_begin(buf, b'\x16\x03\x01'):
return self.decode_error_return(ogn_buf)
buf = buf[3:]
if struct.unpack('>H', buf[:2])[0] != len(buf) - 2:
logging.info("tls_auth wrong tls head size")
return self.decode_error_return(ogn_buf)
buf = buf[2:]
if not match_begin(buf, b'\x01\x00'): #client hello
logging.info("tls_auth not client hello message")
return self.decode_error_return(ogn_buf)
buf = buf[2:]
if struct.unpack('>H', buf[:2])[0] != len(buf) - 2:
logging.info("tls_auth wrong message size")
return self.decode_error_return(ogn_buf)
buf = buf[2:]
if not match_begin(buf, self.tls_version):
logging.info("tls_auth wrong tls version")
return self.decode_error_return(ogn_buf)
buf = buf[2:]
verifyid = buf[:32]
buf = buf[32:]
sessionid_len = ord(buf[0])
if sessionid_len < 32:
logging.info("tls_auth wrong sessionid_len")
return self.decode_error_return(ogn_buf)
sessionid = buf[1:sessionid_len + 1]
buf = buf[sessionid_len+1:]
self.client_id = sessionid
sha1 = hmac.new(self.server_info.key + sessionid, verifyid[:22], hashlib.sha1).digest()[:10]
utc_time = struct.unpack('>I', verifyid[:4])[0]
time_dif = common.int32((int(time.time()) & 0xffffffff) - utc_time)
if self.server_info.obfs_param:
try:
self.max_time_dif = int(self.server_info.obfs_param)
except:
pass
if self.max_time_dif > 0 and (time_dif < -self.max_time_dif or time_dif > self.max_time_dif \
or common.int32(utc_time - self.server_info.data.startup_time) < -self.max_time_dif / 2):
logging.info("tls_auth wrong time")
return self.decode_error_return(ogn_buf)
if sha1 != verifyid[22:]:
logging.info("tls_auth wrong sha1")
return self.decode_error_return(ogn_buf)
if self.server_info.data.client_data.get(verifyid[:22]):
logging.info("replay attack detect, id = %s" % (binascii.hexlify(verifyid)))
return self.decode_error_return(ogn_buf)
self.server_info.data.client_data.sweep()
self.server_info.data.client_data[verifyid[:22]] = sessionid
# (buffer_to_recv, is_need_decrypt, is_need_to_encode_and_send_back)
return (b'', False, True)

@ -0,0 +1,98 @@
#!/usr/bin/env python
#
# Copyright 2015-2015 breakwa11
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import, division, print_function, \
with_statement
import os
import sys
import hashlib
import logging
from shadowsocks.common import ord
def create_obfs(method):
return plain(method)
obfs_map = {
'plain': (create_obfs,),
'origin': (create_obfs,),
}
class plain(object):
def __init__(self, method):
self.method = method
self.server_info = None
def init_data(self):
return b''
def set_server_info(self, server_info):
self.server_info = server_info
def client_pre_encrypt(self, buf):
return buf
def client_encode(self, buf):
return buf
def client_decode(self, buf):
# (buffer_to_recv, is_need_to_encode_and_send_back)
return (buf, False)
def client_post_decrypt(self, buf):
return buf
def server_pre_encrypt(self, buf):
return buf
def server_encode(self, buf):
return buf
def server_decode(self, buf):
# (buffer_to_recv, is_need_decrypt, is_need_to_encode_and_send_back)
return (buf, True, False)
def server_post_decrypt(self, buf):
return (buf, False)
def client_udp_pre_encrypt(self, buf):
return buf
def client_udp_post_decrypt(self, buf):
return buf
def server_udp_pre_encrypt(self, buf):
return buf
def server_udp_post_decrypt(self, buf):
return buf
def dispose(self):
pass
def get_head_size(self, buf, def_value):
if len(buf) < 2:
return def_value
head_type = ord(buf[0]) & 0x7
if head_type == 1:
return 7
if head_type == 4:
return 19
if head_type == 3:
return 4 + ord(buf[1])
return def_value

@ -0,0 +1,360 @@
#!/usr/bin/env python
#
# Copyright 2015-2015 breakwa11
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import, division, print_function, \
with_statement
import os
import sys
import hashlib
import logging
import binascii
import base64
import time
import datetime
import random
import struct
import zlib
import hmac
import hashlib
import shadowsocks
from shadowsocks import common
from shadowsocks.obfsplugin import plain
from shadowsocks.common import to_bytes, to_str, ord, chr
def create_verify_obfs(method):
return verify_simple(method)
def create_verify_deflate(method):
return verify_deflate(method)
def create_verify_sha1(method):
return verify_sha1(method)
def create_auth_obfs(method):
return auth_simple(method)
obfs_map = {
'verify_simple': (create_verify_obfs,),
'verify_deflate': (create_verify_deflate,),
'verify_sha1': (create_verify_sha1,),
'verify_sha1_compatible': (create_verify_sha1,),
}
def match_begin(str1, str2):
if len(str1) >= len(str2):
if str1[:len(str2)] == str2:
return True
return False
class obfs_verify_data(object):
def __init__(self):
pass
class verify_base(plain.plain):
def __init__(self, method):
super(verify_base, self).__init__(method)
self.method = method
def init_data(self):
return obfs_verify_data()
def set_server_info(self, server_info):
self.server_info = server_info
def client_encode(self, buf):
return buf
def client_decode(self, buf):
return (buf, False)
def server_encode(self, buf):
return buf
def server_decode(self, buf):
return (buf, True, False)
class verify_simple(verify_base):
def __init__(self, method):
super(verify_simple, self).__init__(method)
self.recv_buf = b''
self.unit_len = 8100
self.decrypt_packet_num = 0
self.raw_trans = False
def pack_data(self, buf):
if len(buf) == 0:
return b''
rnd_data = os.urandom(common.ord(os.urandom(1)[0]) % 16)
data = common.chr(len(rnd_data) + 1) + rnd_data + buf
data = struct.pack('>H', len(data) + 6) + data
crc = (0xffffffff - binascii.crc32(data)) & 0xffffffff
data += struct.pack('<I', crc)
return data
def client_pre_encrypt(self, buf):
ret = b''
while len(buf) > self.unit_len:
ret += self.pack_data(buf[:self.unit_len])
buf = buf[self.unit_len:]
ret += self.pack_data(buf)
return ret
def client_post_decrypt(self, buf):
if self.raw_trans:
return buf
self.recv_buf += buf
out_buf = b''
while len(self.recv_buf) > 2:
length = struct.unpack('>H', self.recv_buf[:2])[0]
if length >= 8192 or length < 7:
self.raw_trans = True
self.recv_buf = b''
raise Exception('client_post_decrypt data error')
if length > len(self.recv_buf):
break
if (binascii.crc32(self.recv_buf[:length]) & 0xffffffff) != 0xffffffff:
self.raw_trans = True
self.recv_buf = b''
raise Exception('client_post_decrypt data uncorrect CRC32')
pos = common.ord(self.recv_buf[2]) + 2
out_buf += self.recv_buf[pos:length - 4]
self.recv_buf = self.recv_buf[length:]
if out_buf:
self.decrypt_packet_num += 1
return out_buf
def server_pre_encrypt(self, buf):
ret = b''
while len(buf) > self.unit_len:
ret += self.pack_data(buf[:self.unit_len])
buf = buf[self.unit_len:]
ret += self.pack_data(buf)
return ret
def server_post_decrypt(self, buf):
if self.raw_trans:
return (buf, False)
self.recv_buf += buf
out_buf = b''
while len(self.recv_buf) > 2:
length = struct.unpack('>H', self.recv_buf[:2])[0]
if length >= 8192 or length < 7:
self.raw_trans = True
self.recv_buf = b''
if self.decrypt_packet_num == 0:
return (b'E'*2048, False)
else:
raise Exception('server_post_decrype data error')
if length > len(self.recv_buf):
break
if (binascii.crc32(self.recv_buf[:length]) & 0xffffffff) != 0xffffffff:
self.raw_trans = True
self.recv_buf = b''
if self.decrypt_packet_num == 0:
return (b'E'*2048, False)
else:
raise Exception('server_post_decrype data uncorrect CRC32')
pos = common.ord(self.recv_buf[2]) + 2
out_buf += self.recv_buf[pos:length - 4]
self.recv_buf = self.recv_buf[length:]
if out_buf:
self.decrypt_packet_num += 1
return (out_buf, False)
class verify_deflate(verify_base):
def __init__(self, method):
super(verify_deflate, self).__init__(method)
self.recv_buf = b''
self.unit_len = 32700
self.decrypt_packet_num = 0
self.raw_trans = False
def pack_data(self, buf):
if len(buf) == 0:
return b''
data = zlib.compress(buf)
data = struct.pack('>H', len(data)) + data[2:]
return data
def client_pre_encrypt(self, buf):
ret = b''
while len(buf) > self.unit_len:
ret += self.pack_data(buf[:self.unit_len])
buf = buf[self.unit_len:]
ret += self.pack_data(buf)
return ret
def client_post_decrypt(self, buf):
if self.raw_trans:
return buf
self.recv_buf += buf
out_buf = b''
while len(self.recv_buf) > 2:
length = struct.unpack('>H', self.recv_buf[:2])[0]
if length >= 32768 or length < 6:
self.raw_trans = True
self.recv_buf = b''
raise Exception('client_post_decrypt data error')
if length > len(self.recv_buf):
break
out_buf += zlib.decompress(b'x\x9c' + self.recv_buf[2:length])
self.recv_buf = self.recv_buf[length:]
if out_buf:
self.decrypt_packet_num += 1
return out_buf
def server_pre_encrypt(self, buf):
ret = b''
while len(buf) > self.unit_len:
ret += self.pack_data(buf[:self.unit_len])
buf = buf[self.unit_len:]
ret += self.pack_data(buf)
return ret
def server_post_decrypt(self, buf):
if self.raw_trans:
return (buf, False)
self.recv_buf += buf
out_buf = b''
while len(self.recv_buf) > 2:
length = struct.unpack('>H', self.recv_buf[:2])[0]
if length >= 32768 or length < 6:
self.raw_trans = True
self.recv_buf = b''
if self.decrypt_packet_num == 0:
return (b'E'*2048, False)
else:
raise Exception('server_post_decrype data error')
if length > len(self.recv_buf):
break
out_buf += zlib.decompress(b'\x78\x9c' + self.recv_buf[2:length])
self.recv_buf = self.recv_buf[length:]
if out_buf:
self.decrypt_packet_num += 1
return (out_buf, False)
class verify_sha1(verify_base):
def __init__(self, method):
super(verify_sha1, self).__init__(method)
self.recv_buf = b''
self.unit_len = 8100
self.raw_trans = False
self.pack_id = 0
self.recv_id = 0
self.has_sent_header = False
self.has_recv_header = False
def pack_data(self, buf):
if len(buf) == 0:
return b''
sha1data = hmac.new(self.server_info.iv + struct.pack('>I', self.pack_id), buf, hashlib.sha1).digest()
data = struct.pack('>H', len(buf)) + sha1data[:10] + buf
self.pack_id += 1
return data
def pack_auth_data(self, buf):
data = chr(ord(buf[0]) | 0x10) + buf[1:]
data += hmac.new(self.server_info.iv + self.server_info.key, data, hashlib.sha1).digest()[:10]
return data
def client_pre_encrypt(self, buf):
ret = b''
if not self.has_sent_header:
datalen = self.get_head_size(buf, 30)
ret += self.pack_auth_data(buf[:datalen])
buf = buf[datalen:]
self.has_sent_header = True
while len(buf) > self.unit_len:
ret += self.pack_data(buf[:self.unit_len])
buf = buf[self.unit_len:]
ret += self.pack_data(buf)
return ret
def client_post_decrypt(self, buf):
return buf
def server_pre_encrypt(self, buf):
return buf
def not_match_return(self, buf):
self.raw_trans = True
if self.method == 'verify_sha1':
return (b'E'*2048, False)
return (buf, False)
def server_post_decrypt(self, buf):
if self.raw_trans:
return (buf, False)
self.recv_buf += buf
out_buf = b''
if not self.has_recv_header:
if len(self.recv_buf) < 2:
return (b'', False)
if (ord(self.recv_buf[0]) & 0x10) != 0x10:
return self.not_match_return(self.recv_buf)
head_size = self.get_head_size(self.recv_buf, 65536)
if len(self.recv_buf) < head_size + 10:
return self.not_match_return(self.recv_buf)
sha1data = hmac.new(self.server_info.recv_iv + self.server_info.key, self.recv_buf[:head_size], hashlib.sha1).digest()[:10]
if sha1data != self.recv_buf[head_size:head_size + 10]:
logging.error('server_post_decrype data uncorrect auth HMAC-SHA1')
return self.not_match_return(self.recv_buf)
out_buf = to_bytes(chr(ord(self.recv_buf[0]) & 0xEF)) + self.recv_buf[1:head_size]
self.recv_buf = self.recv_buf[head_size + 10:]
self.has_recv_header = True
while len(self.recv_buf) > 2:
length = struct.unpack('>H', self.recv_buf[:2])[0] + 12
if length > len(self.recv_buf):
break
data = self.recv_buf[12:length]
sha1data = hmac.new(self.server_info.recv_iv + struct.pack('>I', self.recv_id), data, hashlib.sha1).digest()[:10]
if sha1data != self.recv_buf[2:12]:
raise Exception('server_post_decrype data uncorrect chunk HMAC-SHA1')
self.recv_id = (self.recv_id + 1) & 0xFFFFFFFF
out_buf += data
self.recv_buf = self.recv_buf[length:]
return (out_buf, False)
def client_udp_pre_encrypt(self, buf):
ret = self.pack_auth_data(buf)
return chr(ord(buf[0]) | 0x10) + buf[1:]
def server_udp_post_decrypt(self, buf):
if buf and ((ord(buf[0]) & 0x10) == 0x10):
if len(buf) <= 11:
return b''
sha1data = hmac.new(self.server_info.recv_iv + self.server_info.key, buf[:-10], hashlib.sha1).digest()[:10]
if sha1data != buf[-10:]:
return b''
return to_bytes(chr(ord(buf[0]) & 0xEF)) + buf[1:-10]
else:
return buf

@ -0,0 +1,214 @@
import collections
################################################################################
### OrderedDict
################################################################################
class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as regular dictionaries.
# The internal self.__map dict maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# Each link is stored as a list of length three: [PREV, NEXT, KEY].
def __init__(*args, **kwds):
'''Initialize an ordered dictionary. The signature is the same as
regular dictionaries, but keyword arguments are not recommended because
their insertion order is arbitrary.
'''
if not args:
raise TypeError("descriptor '__init__' of 'OrderedDict' object "
"needs an argument")
self = args[0]
args = args[1:]
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__root
except AttributeError:
self.__root = root = [] # sentinel node
root[:] = [root, root, None]
self.__map = {}
self.__update(*args, **kwds)
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link at the end of the linked list,
# and the inherited dictionary is updated with the new key/value pair.
if key not in self:
root = self.__root
last = root[0]
last[1] = root[0] = self.__map[key] = [last, root, key]
return dict_setitem(self, key, value)
def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which gets
# removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link_prev, link_next, _ = self.__map.pop(key)
link_prev[1] = link_next # update link_prev[NEXT]
link_next[0] = link_prev # update link_next[PREV]
def __iter__(self):
'od.__iter__() <==> iter(od)'
# Traverse the linked list in order.
root = self.__root
curr = root[1] # start at the first node
while curr is not root:
yield curr[2] # yield the curr[KEY]
curr = curr[1] # move to next node
def __reversed__(self):
'od.__reversed__() <==> reversed(od)'
# Traverse the linked list in reverse order.
root = self.__root
curr = root[0] # start at the last node
while curr is not root:
yield curr[2] # yield the curr[KEY]
curr = curr[0] # move to previous node
def clear(self):
'od.clear() -> None. Remove all items from od.'
root = self.__root
root[:] = [root, root, None]
self.__map.clear()
dict.clear(self)
# -- the following methods do not depend on the internal structure --
def keys(self):
'od.keys() -> list of keys in od'
return list(self)
def values(self):
'od.values() -> list of values in od'
return [self[key] for key in self]
def items(self):
'od.items() -> list of (key, value) pairs in od'
return [(key, self[key]) for key in self]
def iterkeys(self):
'od.iterkeys() -> an iterator over the keys in od'
return iter(self)
def itervalues(self):
'od.itervalues -> an iterator over the values in od'
for k in self:
yield self[k]
def iteritems(self):
'od.iteritems -> an iterator over the (key, value) pairs in od'
for k in self:
yield (k, self[k])
update = collections.MutableMapping.update
__update = update # let subclasses override update without breaking __init__
__marker = object()
def pop(self, key, default=__marker):
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding
value. If key is not found, d is returned if given, otherwise KeyError
is raised.
'''
if key in self:
result = self[key]
del self[key]
return result
if default is self.__marker:
raise KeyError(key)
return default
def setdefault(self, key, default=None):
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
if key in self:
return self[key]
self[key] = default
return default
def popitem(self, last=True):
'''od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.
'''
if not self:
raise KeyError('dictionary is empty')
key = next(reversed(self) if last else iter(self))
value = self.pop(key)
return key, value
def __repr__(self, _repr_running={}):
'od.__repr__() <==> repr(od)'
call_key = id(self), _get_ident()
if call_key in _repr_running:
return '...'
_repr_running[call_key] = 1
try:
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.items())
finally:
del _repr_running[call_key]
def __reduce__(self):
'Return state information for pickling'
items = [[k, self[k]] for k in self]
inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
if inst_dict:
return (self.__class__, (items,), inst_dict)
return self.__class__, (items,)
def copy(self):
'od.copy() -> a shallow copy of od'
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
If not specified, the value defaults to None.
'''
self = cls()
for key in iterable:
self[key] = value
return self
def __eq__(self, other):
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive.
'''
if isinstance(other, OrderedDict):
return dict.__eq__(self, other) and all(_imap(_eq, self, other))
return dict.__eq__(self, other)
def __ne__(self, other):
'od.__ne__(y) <==> od!=y'
return not self == other
# -- the following methods support python 3.x style dictionary views --
def viewkeys(self):
"od.viewkeys() -> a set-like object providing a view on od's keys"
return KeysView(self)
def viewvalues(self):
"od.viewvalues() -> an object providing a view on od's values"
return ValuesView(self)
def viewitems(self):
"od.viewitems() -> a set-like object providing a view on od's items"
return ItemsView(self)

@ -0,0 +1,6 @@
#!/bin/bash
cd `dirname $0`
eval $(ps -ef | grep "[0-9] python server\\.py a" | awk '{print "kill "$2}')
ulimit -n 4096
nohup python server.py a >> /dev/null 2>&1 &

@ -23,8 +23,13 @@ import os
import logging
import signal
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))
from shadowsocks import shell, daemon, eventloop, tcprelay, udprelay, asyncdns
if __name__ == '__main__':
import inspect
file_path = os.path.dirname(os.path.realpath(inspect.getfile(inspect.currentframe())))
sys.path.insert(0, os.path.join(file_path, '../'))
from shadowsocks import shell, daemon, eventloop, tcprelay, udprelay, \
asyncdns, manager
def main():
@ -32,13 +37,18 @@ def main():
config = shell.get_config(False)
shell.log_shadowsocks_version()
daemon.daemon_exec(config)
try:
import resource
logging.info('current process RLIMIT_NOFILE resource: soft %d hard %d' % resource.getrlimit(resource.RLIMIT_NOFILE))
except ImportError:
pass
if config['port_password']:
if config['password']:
logging.warn('warning: port_password should not be used with '
'server_port and password. server_port and password '
'will be ignored')
pass
else:
config['port_password'] = {}
server_port = config['server_port']
@ -48,17 +58,93 @@ def main():
else:
config['port_password'][str(server_port)] = config['password']
if not config.get('dns_ipv6', False):
asyncdns.IPV6_CONNECTION_SUPPORT = False
if config.get('manager_address', 0):
logging.info('entering manager mode')
manager.run(config)
return
tcp_servers = []
udp_servers = []
dns_resolver = asyncdns.DNSResolver()
for port, password in config['port_password'].items():
if int(config['workers']) > 1:
stat_counter_dict = None
else:
stat_counter_dict = {}
port_password = config['port_password']
config_password = config.get('password', 'm')
del config['port_password']
for port, password_obfs in port_password.items():
method = config["method"]
protocol = config.get("protocol", 'origin')
protocol_param = config.get("protocol_param", '')
obfs = config.get("obfs", 'plain')
obfs_param = config.get("obfs_param", '')
bind = config.get("out_bind", '')
bindv6 = config.get("out_bindv6", '')
if type(password_obfs) == list:
password = password_obfs[0]
obfs = password_obfs[1]
if len(password_obfs) > 2:
protocol = password_obfs[2]
elif type(password_obfs) == dict:
password = password_obfs.get('password', config_password)
method = password_obfs.get('method', method)
protocol = password_obfs.get('protocol', protocol)
protocol_param = password_obfs.get('protocol_param', protocol_param)
obfs = password_obfs.get('obfs', obfs)
obfs_param = password_obfs.get('obfs_param', obfs_param)
bind = password_obfs.get('bind', bind)
bindv6 = password_obfs.get('bindv6', bindv6)
else:
password = password_obfs
a_config = config.copy()
a_config['server_port'] = int(port)
a_config['password'] = password
logging.info("starting server at %s:%d" %
(a_config['server'], int(port)))
tcp_servers.append(tcprelay.TCPRelay(a_config, dns_resolver, False))
udp_servers.append(udprelay.UDPRelay(a_config, dns_resolver, False))
ipv6_ok = False
logging.info("server start with protocol[%s] password [%s] method [%s] obfs [%s] obfs_param [%s]" %
(protocol, password, a_config['method'], obfs, obfs_param))
if 'server_ipv6' in a_config:
try:
if len(a_config['server_ipv6']) > 2 and a_config['server_ipv6'][0] == "[" and a_config['server_ipv6'][-1] == "]":
a_config['server_ipv6'] = a_config['server_ipv6'][1:-1]
a_config['server_port'] = int(port)
a_config['password'] = password
a_config['method'] = method
a_config['protocol'] = protocol
a_config['protocol_param'] = protocol_param
a_config['obfs'] = obfs
a_config['obfs_param'] = obfs_param
a_config['out_bind'] = bind
a_config['out_bindv6'] = bindv6
a_config['server'] = a_config['server_ipv6']
logging.info("starting server at [%s]:%d" %
(a_config['server'], int(port)))
tcp_servers.append(tcprelay.TCPRelay(a_config, dns_resolver, False, stat_counter=stat_counter_dict))
udp_servers.append(udprelay.UDPRelay(a_config, dns_resolver, False, stat_counter=stat_counter_dict))
if a_config['server_ipv6'] == b"::":
ipv6_ok = True
except Exception as e:
shell.print_exception(e)
try:
a_config = config.copy()
a_config['server_port'] = int(port)
a_config['password'] = password
a_config['method'] = method
a_config['protocol'] = protocol
a_config['protocol_param'] = protocol_param
a_config['obfs'] = obfs
a_config['obfs_param'] = obfs_param
a_config['out_bind'] = bind
a_config['out_bindv6'] = bindv6
logging.info("starting server at %s:%d" %
(a_config['server'], int(port)))
tcp_servers.append(tcprelay.TCPRelay(a_config, dns_resolver, False, stat_counter=stat_counter_dict))
udp_servers.append(udprelay.UDPRelay(a_config, dns_resolver, False, stat_counter=stat_counter_dict))
except Exception as e:
if not ipv6_ok:
shell.print_exception(e)
def run_server():
def child_handler(signum, _):

@ -23,7 +23,7 @@ import json
import sys
import getopt
import logging
from shadowsocks.common import to_bytes, to_str, IPNetwork
from shadowsocks.common import to_bytes, to_str, IPNetwork, PortRange
from shadowsocks import encrypt
@ -54,16 +54,39 @@ def print_exception(e):
def print_shadowsocks():
version = ''
version_str = ''
try:
import pkg_resources
version = pkg_resources.get_distribution('shadowsocks').version
version_str = pkg_resources.get_distribution('shadowsocks').version
except Exception:
pass
print('Shadowsocks %s' % version)
try:
from shadowsocks import version
version_str = version.version()
except Exception:
pass
print('ShadowsocksR %s' % version_str)
def log_shadowsocks_version():
version_str = ''
try:
import pkg_resources
version_str = pkg_resources.get_distribution('shadowsocks').version
except Exception:
try:
from shadowsocks import version
version_str = version.version()
except Exception:
pass
logging.info('ShadowsocksR %s' % version_str)
def find_config():
config_path = 'user-config.json'
if os.path.exists(config_path):
return config_path
config_path = os.path.join(os.path.dirname(__file__), '../', 'user-config.json')
if os.path.exists(config_path):
return config_path
config_path = 'config.json'
if os.path.exists(config_path):
return config_path
@ -130,13 +153,13 @@ def get_config(is_local):
logging.basicConfig(level=logging.INFO,
format='%(levelname)-s: %(message)s')
if is_local:
shortopts = 'hd:s:b:p:k:l:m:c:t:vq'
shortopts = 'hd:s:b:p:k:l:m:O:o:G:g:c:t:vq'
longopts = ['help', 'fast-open', 'pid-file=', 'log-file=', 'user=',
'version']
else:
shortopts = 'hd:s:p:k:m:c:t:vq'
shortopts = 'hd:s:p:k:m:O:o:G:g:c:t:vq'
longopts = ['help', 'fast-open', 'pid-file=', 'log-file=', 'workers=',
'forbidden-ip=', 'user=', 'version']
'forbidden-ip=', 'user=', 'manager-address=', 'version']
try:
config_path = find_config()
optlist, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
@ -148,8 +171,7 @@ def get_config(is_local):
logging.info('loading config from %s' % config_path)
with open(config_path, 'rb') as f:
try:
config = json.loads(f.read().decode('utf8'),
object_hook=_decode_dict)
config = parse_json_in_str(f.read().decode('utf8'))
except ValueError as e:
logging.error('found an error in config.json: %s',
e.message)
@ -169,6 +191,14 @@ def get_config(is_local):
config['server'] = to_str(value)
elif key == '-m':
config['method'] = to_str(value)
elif key == '-O':
config['protocol'] = to_str(value)
elif key == '-o':
config['obfs'] = to_str(value)
elif key == '-G':
config['protocol_param'] = to_str(value)
elif key == '-g':
config['obfs_param'] = to_str(value)
elif key == '-b':
config['local_address'] = to_str(value)
elif key == '-v':
@ -181,10 +211,12 @@ def get_config(is_local):
config['fast_open'] = True
elif key == '--workers':
config['workers'] = int(value)
elif key == '--manager-address':
config['manager_address'] = value
elif key == '--user':
config['user'] = to_str(value)
elif key == '--forbidden-ip':
config['forbidden_ip'] = to_str(value).split(',')
config['forbidden_ip'] = to_str(value)
elif key in ('-h', '--help'):
if is_local:
print_local_help()
@ -215,13 +247,20 @@ def get_config(is_local):
config['password'] = to_bytes(config.get('password', b''))
config['method'] = to_str(config.get('method', 'aes-256-cfb'))
config['protocol'] = to_str(config.get('protocol', 'origin'))
config['protocol_param'] = to_str(config.get('protocol_param', ''))
config['obfs'] = to_str(config.get('obfs', 'plain'))
config['obfs_param'] = to_str(config.get('obfs_param', ''))
config['port_password'] = config.get('port_password', None)
config['timeout'] = int(config.get('timeout', 300))
config['udp_timeout'] = int(config.get('udp_timeout', 120))
config['udp_cache'] = int(config.get('udp_cache', 64))
config['fast_open'] = config.get('fast_open', False)
config['workers'] = config.get('workers', 1)
config['pid-file'] = config.get('pid-file', '/var/run/shadowsocks.pid')
config['log-file'] = config.get('log-file', '/var/log/shadowsocks.log')
config['verbose'] = config.get('verbose', False)
config['connect_verbose_info'] = config.get('connect_verbose_info', 0)
config['local_address'] = to_str(config.get('local_address', '127.0.0.1'))
config['local_port'] = config.get('local_port', 1080)
if is_local:
@ -239,6 +278,17 @@ def get_config(is_local):
except Exception as e:
logging.error(e)
sys.exit(2)
try:
config['forbidden_port'] = PortRange(config.get('forbidden_port', ''))
except Exception as e:
logging.error(e)
sys.exit(2)
try:
config['ignore_bind'] = \
IPNetwork(config.get('ignore_bind', '127.0.0.0/8,::1/128'))
except Exception as e:
logging.error(e)
sys.exit(2)
config['server_port'] = config.get('server_port', 8388)
logging.getLogger('').handlers = []
@ -255,7 +305,7 @@ def get_config(is_local):
level = logging.INFO
verbose = config['verbose']
logging.basicConfig(level=level,
format='%(asctime)s %(levelname)-8s %(message)s',
format='%(asctime)s %(levelname)-8s %(filename)s:%(lineno)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
check_config(config, is_local)
@ -284,6 +334,7 @@ Proxy options:
-l LOCAL_PORT local port, default: 1080
-k PASSWORD password
-m METHOD encryption method, default: aes-256-cfb
-o OBFS obfsplugin, default: http_simple
-t TIMEOUT timeout in seconds, default: 300
--fast-open use TCP_FASTOPEN, requires Linux 3.7+
@ -313,10 +364,12 @@ Proxy options:
-p SERVER_PORT server port, default: 8388
-k PASSWORD password
-m METHOD encryption method, default: aes-256-cfb
-o OBFS obfsplugin, default: http_simple
-t TIMEOUT timeout in seconds, default: 300
--fast-open use TCP_FASTOPEN, requires Linux 3.7+
--workers WORKERS number of workers, available on Unix/Linux
--forbidden-ip IPLIST comma seperated IP list forbidden to connect
--manager-address ADDR optional server manager UDP address, see wiki
General options:
-h, --help show this help message and exit
@ -356,3 +409,8 @@ def _decode_dict(data):
value = _decode_dict(value)
rv[key] = value
return rv
def parse_json_in_str(data):
# parse json and convert everything from unicode to str
return json.loads(data, object_hook=_decode_dict)

@ -0,0 +1,3 @@
#!/bin/bash
eval $(ps -ef | grep "[0-9] python server\\.py a" | awk '{print "kill "$2}')

@ -0,0 +1,3 @@
#!/bin/bash
tail -f ssserver.log

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,20 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2016 breakwa11
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
def version():
return '2.9.7 2016-11-22'

@ -0,0 +1,3 @@
#!/bin/bash
eval $(ps -ef | grep "[0-9] python server\\.py m" | awk '{print "kill "$2}')

@ -0,0 +1,8 @@
def getKeys(key_list):
return key_list
#return key_list + ['plan'] # append the column name 'plan'
def isTurnOn(row):
return True
#return row['plan'] == 'B' # then judge here

@ -0,0 +1,3 @@
#!/bin/bash
cd `dirname $0`
tail -f ssserver.log

@ -69,7 +69,7 @@ if [ -f /proc/sys/net/ipv4/tcp_fastopen ] ; then
fi
run_test tests/test_large_file.sh
run_test tests/test_udp_src.sh
run_test tests/test_command.sh
coverage combine && coverage report --include=shadowsocks/*

@ -44,7 +44,7 @@ parser.add_argument('--dns', type=str, default='8.8.8.8')
config = parser.parse_args()
if config.with_coverage:
python = ['coverage', 'run', '-p', '-a']
python = ['coverage', 'run', '-p']
client_args = python + ['shadowsocks/local.py', '-v']
server_args = python + ['shadowsocks/server.py', '-v']

@ -2,18 +2,13 @@
. tests/assert.sh
PYTHON="coverage run -a -p"
PYTHON="coverage run -p"
LOCAL="$PYTHON shadowsocks/local.py"
SERVER="$PYTHON shadowsocks/server.py"
assert "$LOCAL --version 2>&1 | grep Shadowsocks | awk -F\" \" '{print \$1}'" "Shadowsocks"
assert "$SERVER --version 2>&1 | grep Shadowsocks | awk -F\" \" '{print \$1}'" "Shadowsocks"
assert "$LOCAL 2>&1 | grep ERROR" "ERROR: config not specified"
assert "$LOCAL 2>&1 | grep usage | cut -d: -f1" "usage"
assert "$SERVER 2>&1 | grep ERROR" "ERROR: config not specified"
assert "$SERVER 2>&1 | grep usage | cut -d: -f1" "usage"
assert "$LOCAL 2>&1 -m rc4-md5 -k testrc4 -s 127.0.0.1 -p 8388 -d start | grep WARNING | awk -F\"WARNING\" '{print \$2}'" " warning: server set to listen on 127.0.0.1:8388, are you sure?"
$LOCAL 2>/dev/null 1>/dev/null -m rc4-md5 -k testrc4 -s 127.0.0.1 -p 8388 -d stop
@ -30,14 +25,6 @@ $LOCAL 2>/dev/null 1>/dev/null -m rc4-md5 -k testrc4 -s 127.0.0.1 -p 8388 -d sto
assert "$LOCAL 2>&1 -m rc4-md5 -k mypassword -s 0.0.0.0 -p 8388 -d start | grep ERROR | awk -F\"ERROR\" '{print \$2}'" " DON'T USE DEFAULT PASSWORD! Please change it in your config.json!"
$LOCAL 2>/dev/null 1>/dev/null -m rc4-md5 -k testrc4 -s 127.0.0.1 -p 8388 -d stop
assert "$LOCAL 2>&1 -m rc4-md5 -p 8388 -k testrc4 -d start | grep ERROR | awk -F\"ERROR\" '{print \$2}'" ": server addr not specified"
$LOCAL 2>/dev/null 1>/dev/null -m rc4-md5 -k testrc4 -s 127.0.0.1 -p 8388 -d stop
assert "$LOCAL 2>&1 -m rc4-md5 -p 8388 -s 0.0.0.0 -d start | grep ERROR | awk -F\"ERROR\" '{print \$2}'" " password not specified"
$LOCAL 2>/dev/null 1>/dev/null -m rc4-md5 -k testrc4 -s 127.0.0.1 -p 8388 -d stop
assert "$SERVER 2>&1 -m rc4-md5 -p 8388 -s 0.0.0.0 -d start | grep ERROR | awk -F\"ERROR\" '{print \$2}'" " password or port_password not specified"
$LOCAL 2>/dev/null 1>/dev/null -m rc4-md5 -k testrc4 -s 127.0.0.1 -p 8388 -d stop
assert "$SERVER 2>&1 --forbidden-ip 127.0.0.1/4a -m rc4-md5 -k 12345 -p 8388 -s 0.0.0.0 -d start | grep ERROR | awk -F\"ERROR\" '{print \$2}'" ": Not a valid CIDR notation: 127.0.0.1/4a"
$LOCAL 2>/dev/null 1>/dev/null -m rc4-md5 -k testrc4 -s 127.0.0.1 -p 8388 -d stop

@ -18,7 +18,7 @@ function run_test {
for module in local server
do
command="coverage run -p -a shadowsocks/$module.py"
command="coverage run -p shadowsocks/$module.py"
mkdir -p tmp

@ -1,6 +1,6 @@
#!/bin/bash
PYTHON="coverage run -p -a"
PYTHON="coverage run -p"
URL=http://127.0.0.1/file
mkdir -p tmp

@ -0,0 +1,83 @@
#!/usr/bin/python
import socket
import socks
SERVER_IP = '127.0.0.1'
SERVER_PORT = 1081
if __name__ == '__main__':
# Test 1: same source port IPv4
sock_out = socks.socksocket(socket.AF_INET, socket.SOCK_DGRAM,
socket.SOL_UDP)
sock_out.set_proxy(socks.SOCKS5, SERVER_IP, SERVER_PORT)
sock_out.bind(('127.0.0.1', 9000))
sock_in1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
socket.SOL_UDP)
sock_in2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
socket.SOL_UDP)
sock_in1.bind(('127.0.0.1', 9001))
sock_in2.bind(('127.0.0.1', 9002))
sock_out.sendto(b'data', ('127.0.0.1', 9001))
result1 = sock_in1.recvfrom(8)
sock_out.sendto(b'data', ('127.0.0.1', 9002))
result2 = sock_in2.recvfrom(8)
sock_out.close()
sock_in1.close()
sock_in2.close()
# make sure they're from the same source port
assert result1 == result2
# Test 2: same source port IPv6
# try again from the same port but IPv6
sock_out = socks.socksocket(socket.AF_INET, socket.SOCK_DGRAM,
socket.SOL_UDP)
sock_out.set_proxy(socks.SOCKS5, SERVER_IP, SERVER_PORT)
sock_out.bind(('127.0.0.1', 9000))
sock_in1 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM,
socket.SOL_UDP)
sock_in2 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM,
socket.SOL_UDP)
sock_in1.bind(('::1', 9001))
sock_in2.bind(('::1', 9002))
sock_out.sendto(b'data', ('::1', 9001))
result1 = sock_in1.recvfrom(8)
sock_out.sendto(b'data', ('::1', 9002))
result2 = sock_in2.recvfrom(8)
sock_out.close()
sock_in1.close()
sock_in2.close()
# make sure they're from the same source port
assert result1 == result2
# Test 3: different source ports IPv6
sock_out = socks.socksocket(socket.AF_INET, socket.SOCK_DGRAM,
socket.SOL_UDP)
sock_out.set_proxy(socks.SOCKS5, SERVER_IP, SERVER_PORT)
sock_out.bind(('127.0.0.1', 9003))
sock_in1 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM,
socket.SOL_UDP)
sock_in1.bind(('::1', 9001))
sock_out.sendto(b'data', ('::1', 9001))
result3 = sock_in1.recvfrom(8)
# make sure they're from different source ports
assert result1 != result3
sock_out.close()
sock_in1.close()

@ -0,0 +1,23 @@
#!/bin/bash
PYTHON="coverage run -p"
mkdir -p tmp
$PYTHON shadowsocks/local.py -c tests/aes.json -v &
LOCAL=$!
$PYTHON shadowsocks/server.py -c tests/aes.json --forbidden-ip "" -v &
SERVER=$!
sleep 3
python tests/test_udp_src.py
r=$?
kill -s SIGINT $LOCAL
kill -s SIGINT $SERVER
sleep 2
exit $r

@ -0,0 +1,5 @@
[Definition]
_daemon = shadowsocks
failregex = ^\s+ERROR\s+can not parse header when handling connection from <HOST>:\d+$
Loading…
Cancel
Save