Compare commits
311 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a3eb0bfde9 | ||
|
|
33e665631d | ||
|
|
375eb9aa66 | ||
|
|
889ce76676 | ||
|
|
abdcae31c9 | ||
|
|
c9f8f6c6fb | ||
|
|
aab899397e | ||
|
|
a933322ef7 | ||
|
|
b9f054c495 | ||
|
|
5c2e6fd109 | ||
|
|
e427263ccf | ||
|
|
a1a2c3f985 | ||
|
|
84458a10e4 | ||
|
|
9dd7bf80c5 | ||
|
|
317d0113fb | ||
|
|
53153da2e6 | ||
|
|
747a94a1c8 | ||
|
|
df94ca5601 | ||
|
|
3cf7788f34 | ||
|
|
af91921070 | ||
|
|
7fc5c30f60 | ||
|
|
c4a7f0fbb0 | ||
|
|
f656773858 | ||
|
|
e208ccee18 | ||
|
|
5980fee788 | ||
|
|
61f791e77d | ||
|
|
907dec42e0 | ||
|
|
8dce99fec6 | ||
|
|
db13b83f44 | ||
|
|
dd8d7dd0d4 | ||
|
|
dd355b5d98 | ||
|
|
1e1999dede | ||
|
|
bb933cfb6e | ||
|
|
2603802dd9 | ||
|
|
68ad904772 | ||
|
|
af19e5d25b | ||
|
|
62907efe0c | ||
|
|
29e4cdf4e2 | ||
|
|
3a4a9a3a27 | ||
|
|
04ef338807 | ||
|
|
3c070a7da3 | ||
|
|
c34f7db239 | ||
|
|
1f655808c6 | ||
|
|
0226d2cde3 | ||
|
|
61bb2d8ca0 | ||
|
|
f5d09b878b | ||
|
|
6b4ee97f05 | ||
|
|
12dd591c58 | ||
|
|
3b49f17e01 | ||
|
|
cb8d0c0b42 | ||
|
|
e92375f6a9 | ||
|
|
c20e19d74f | ||
|
|
50886bd69a | ||
|
|
eaf836eff3 | ||
|
|
bf72325fc0 | ||
|
|
846956a9fe | ||
|
|
20c31b0c68 | ||
|
|
d84a4bec86 | ||
|
|
05d2f16777 | ||
|
|
9fa1c4932b | ||
|
|
0932aecff3 | ||
|
|
a9f8acd98d | ||
|
|
2336e77ac4 | ||
|
|
1ef8d7c82a | ||
|
|
24d54725df | ||
|
|
9b430b5ba4 | ||
|
|
0ee7abbd6a | ||
|
|
361215fb6f | ||
|
|
7c0daad40a | ||
|
|
726240e669 | ||
|
|
1449b94dd4 | ||
|
|
ee9cd7b181 | ||
|
|
ec0492b4b6 | ||
|
|
7b4cb4df04 | ||
|
|
7a31291c4c | ||
|
|
16f1d80588 | ||
|
|
7101530b22 | ||
|
|
7f0bea952d | ||
|
|
380c203222 | ||
|
|
c4ac760603 | ||
|
|
09158ebaa2 | ||
|
|
4709ccfca4 | ||
|
|
bea9ca25cf | ||
|
|
8ca1bfe09c | ||
|
|
878b5e8c8a | ||
|
|
1e9cfccd5a | ||
|
|
995aa73bf2 | ||
|
|
97012a0a19 | ||
|
|
006f2f9510 | ||
|
|
e849cbfcd8 | ||
|
|
dff1a6daaf | ||
|
|
250dc26514 | ||
|
|
1b327d6abf | ||
|
|
fa11146246 | ||
|
|
da7bfcf3be | ||
|
|
4214ec4239 | ||
|
|
504de47999 | ||
|
|
e185d734d0 | ||
|
|
9b1ef52649 | ||
|
|
5c9fc850d8 | ||
|
|
ff96e52a33 | ||
|
|
78004bcd39 | ||
|
|
b16decf976 | ||
|
|
828636553d | ||
|
|
bfcc27e70f | ||
|
|
7cb7d34d42 | ||
|
|
5276154401 | ||
|
|
dad091441e | ||
|
|
81ff3dadd5 | ||
|
|
f559fb1cae | ||
|
|
8649bbc191 | ||
|
|
d775339948 | ||
|
|
69a5b906e0 | ||
|
|
2d66cc6215 | ||
|
|
8d74baf48c | ||
|
|
d7641c4483 | ||
|
|
ffe54c3af7 | ||
|
|
53df3b5578 | ||
|
|
54c22f1410 | ||
|
|
366b7e04f3 | ||
|
|
a33a4d2bd3 | ||
|
|
eb00d570a8 | ||
|
|
500142f4c8 | ||
|
|
bffd5891cc | ||
|
|
cf2e6f9ff0 | ||
|
|
ed4b8d11e3 | ||
|
|
905c1eac63 | ||
|
|
61872133b1 | ||
|
|
e18f53a5bb | ||
|
|
947fb51963 | ||
|
|
7aeef3f8ba | ||
|
|
b42f6a6364 | ||
|
|
92f4d31dfc | ||
|
|
4f11593f26 | ||
|
|
795d63879f | ||
|
|
1c46eeaf43 | ||
|
|
6f47d12498 | ||
|
|
e6c56675ca | ||
|
|
ff92c96d8d | ||
|
|
fed2afb964 | ||
|
|
b3feff7843 | ||
|
|
edb2fb3458 | ||
|
|
dc51a0bd9d | ||
|
|
34b30ac8c9 | ||
|
|
8122af9096 | ||
|
|
2b267fe4bb | ||
|
|
90bf483976 | ||
|
|
b109f273a5 | ||
|
|
482977a4ac | ||
|
|
515dcdbf1f | ||
|
|
0e033c1d85 | ||
|
|
ad2441de3b | ||
|
|
7a881b3625 | ||
|
|
faf61fdd60 | ||
|
|
2b3d23f77c | ||
|
|
06e1247706 | ||
|
|
6b5fdef8c7 | ||
|
|
48b1621ee4 | ||
|
|
c2ce973f61 | ||
|
|
cac648cc32 | ||
|
|
b9bffcdf4b | ||
|
|
7a1e5c5de7 | ||
|
|
e24dfc856a | ||
|
|
66a115c764 | ||
|
|
a6e80a30dc | ||
|
|
52a2771382 | ||
|
|
6b2b75bc50 | ||
|
|
893baff6c6 | ||
|
|
de62d956dd | ||
|
|
b59cf1f144 | ||
|
|
8b5cc3fb89 | ||
|
|
fbd8c67649 | ||
|
|
c6f6266592 | ||
|
|
ab72640ffd | ||
|
|
905bfff92b | ||
|
|
4ef33d0ffd | ||
|
|
1597363dd1 | ||
|
|
27896a0563 | ||
|
|
bef385cfd1 | ||
|
|
98e0154baa | ||
|
|
01961a798a | ||
|
|
d5a460bd09 | ||
|
|
e94605644f | ||
|
|
8dc206e2d6 | ||
|
|
e8acbbfabf | ||
|
|
17335eb92b | ||
|
|
d2051e6e37 | ||
|
|
0aa0e7c550 | ||
|
|
57935c2296 | ||
|
|
9d4930b29d | ||
|
|
66206e63b3 | ||
|
|
19baccb91a | ||
|
|
98bbd68448 | ||
|
|
45dee58203 | ||
|
|
e2557c44c4 | ||
|
|
f0ed6d73e4 | ||
|
|
47790d1d58 | ||
|
|
9aff5eda38 | ||
|
|
eb2f055e07 | ||
|
|
0998c06195 | ||
|
|
cf22866b2a | ||
|
|
16bb452640 | ||
|
|
6f1d826ef5 | ||
|
|
5a68fb3c3d | ||
|
|
350eb5b6ed | ||
|
|
d48f3b3323 | ||
|
|
7a1491c7b3 | ||
|
|
68deae6bf8 | ||
|
|
2086966a89 | ||
|
|
3aba428b76 | ||
|
|
a11ce38747 | ||
|
|
f7b363ec73 | ||
|
|
4c33a1e9b2 | ||
|
|
c4d9382ac7 | ||
|
|
7df2d990e7 | ||
|
|
900b75ddcd | ||
|
|
a5d199fb1c | ||
|
|
2d8190873f | ||
|
|
3eff793ac2 | ||
|
|
27ce6e1bd2 | ||
|
|
b11c7e632b | ||
|
|
d911be7d80 | ||
|
|
bd056d74cc | ||
|
|
69b65a37ca | ||
|
|
dd52ad8a8a | ||
|
|
59b5ef2df4 | ||
|
|
4a34566f08 | ||
|
|
d81d5ffe06 | ||
|
|
59c9148875 | ||
|
|
40bce3e736 | ||
|
|
d4c0775b4a | ||
|
|
7f983152b7 | ||
|
|
bab4325414 | ||
|
|
0d85c7dd7d | ||
|
|
f756d62b19 | ||
|
|
2d1c1449aa | ||
|
|
f348298acd | ||
|
|
ad47104fc7 | ||
|
|
4d4fb64b59 | ||
|
|
9ce3a6e468 | ||
|
|
34e9e362b9 | ||
|
|
f87cbf73e8 | ||
|
|
362ada2ebb | ||
|
|
b4b7221dab | ||
|
|
2d8dc56f4e | ||
|
|
1cf4313d12 | ||
|
|
7bb8f19b90 | ||
|
|
1263a4e751 | ||
|
|
1a432a9b79 | ||
|
|
8951fdbd59 | ||
|
|
77129367fe | ||
|
|
ae2e1e0933 | ||
|
|
4143f14fbd | ||
|
|
8e3e262c2f | ||
|
|
6f11deab96 | ||
|
|
a17acd7351 | ||
|
|
1cbb4195e4 | ||
|
|
c471dd8297 | ||
|
|
25deffb7d6 | ||
|
|
7eb0e0040e | ||
|
|
15994988be | ||
|
|
ae293a6102 | ||
|
|
5ed4702b62 | ||
|
|
287ddc3424 | ||
|
|
57a4227007 | ||
|
|
c9eacd1bf2 | ||
|
|
5f38162fbb | ||
|
|
c755f75a11 | ||
|
|
ac9eb64501 | ||
|
|
3dd013c13c | ||
|
|
ab0205587a | ||
|
|
70955878c9 | ||
|
|
86f017d92f | ||
|
|
446cc3f9a7 | ||
|
|
6529921d71 | ||
|
|
52e441c111 | ||
|
|
a6b169d336 | ||
|
|
5514cfee6c | ||
|
|
b1de184bda | ||
|
|
af2405ba48 | ||
|
|
bee80330b0 | ||
|
|
f1de8659b7 | ||
|
|
bfc5835d82 | ||
|
|
82bc3e27d6 | ||
|
|
5436a95430 | ||
|
|
2c675f2cbe | ||
|
|
8e9427b0c0 | ||
|
|
edcf78f77c | ||
|
|
8f88d14c07 | ||
|
|
1372801b6f | ||
|
|
2af904f442 | ||
|
|
885b27e0d1 | ||
|
|
0207e4731f | ||
|
|
038b6749a3 | ||
|
|
ead577cbfb | ||
|
|
26e9231e48 | ||
|
|
938ddd1141 | ||
|
|
68080539f7 | ||
|
|
5583b303be | ||
|
|
9301c9b49b | ||
|
|
8d2e210522 | ||
|
|
32661552ff | ||
|
|
9a111a59bf | ||
|
|
f5e472ea9f | ||
|
|
7599e2c793 | ||
|
|
3726f5b9c3 | ||
|
|
dee517217e | ||
|
|
983912e44e | ||
|
|
982390f4b2 | ||
|
|
5e3f51a8b0 | ||
|
|
bd594684ce |
9
.gitignore
vendored
@ -1,7 +1,10 @@
|
||||
proxy
|
||||
/proxy
|
||||
/goproxy
|
||||
*.exe
|
||||
*.exe~
|
||||
.*
|
||||
*.prof
|
||||
!.gitignore
|
||||
release-*
|
||||
proxy.crt
|
||||
proxy.key
|
||||
/proxy.crt
|
||||
/proxy.key
|
||||
|
||||
101
CHANGELOG
@ -1,4 +1,105 @@
|
||||
proxy更新日志
|
||||
v5.4
|
||||
1.优化了获取本地IP信息导致CPU过高的问题.
|
||||
2.所有服务都增加了--nolog参数,可以关闭日志输出,节省CPU.
|
||||
3.优化sdk,支持并发启动/关闭操作.
|
||||
4.修复了多连接版本的内网穿透,tserver连接不能正确释放的bug.
|
||||
5.内网穿透增加了client/tclient和server/tserver使用代理连接bridge/tbridge的功能,详细内容参考手册.
|
||||
6.TCP端口映射(TCP代理)增加了使用代理连接上级的功能,详细内容参考手册.
|
||||
|
||||
v5.3
|
||||
1.优化了socks_client握手端口判断,避免了sstap测试UDP失败的问题.
|
||||
|
||||
v5.2
|
||||
1.修复了HTTP(S)\SPS反向代理无法正常工作的问题.
|
||||
2.优化了智能判断,减少不必要的DNS解析.
|
||||
3.重构了SOCKS和SPS的UDP功能,基于UDP的游戏加速嗖嗖的.
|
||||
|
||||
v5.1
|
||||
1.优化了kcp默认mtu配置,调整为450.
|
||||
2.优化了HTTP(S)\SOCKS5代理智能判断,更加精确。
|
||||
3.fix #97 , 修复了RemoveProxyHeaders方法忽略了第一行的bug。
|
||||
4.修复了-g参数长格式没有连接符号的bug.
|
||||
5.重构了证书生成功能,不再有任何外部依赖,任何平台都可以独立生成证书.
|
||||
|
||||
v5.0
|
||||
1.修复了SPS多端口无效的bug.
|
||||
2.增加了DNS代理功能,提供安全无污染的DNS解析.
|
||||
|
||||
v4.9
|
||||
1.修复了HTTP Basic代理返回不合适的头部,导致浏览器不会弹框,个别代理插件无法认证的问题.
|
||||
2.内网穿透切换smux到yamux.
|
||||
3.优化了HTTP(S)\SOCKS5代理--always的处理逻辑.
|
||||
|
||||
v4.8
|
||||
1.优化了SPS连接HTTP上级的指令,避免了某些代理不响应的问题.
|
||||
2.SPS功能增加了参数:
|
||||
--disable-http:禁用http(s)代理
|
||||
--disable-socks:禁用socks代理
|
||||
默认都是false(开启).
|
||||
3.重构了部分代码的日志部分,保证了日志按着预期输出.
|
||||
4.修复了sps\http代理初始化服务的时机不正确,导致nil异常的bug.
|
||||
5.优化了sps日志输出.
|
||||
6.--debug参数增加了Profiling功能,可以保存cpu,内存等多种调试数据到文件.
|
||||
7.优化了服务注册,避免了不必要的内存开销.
|
||||
8.增加了Dockerfile和docker安装手册.
|
||||
9.优化了ioCopy避免了内存泄漏,大大提升了内存占用的稳定性.
|
||||
|
||||
|
||||
v4.7
|
||||
1.增加了基于gomobile的sdk,对android/ios/windows/linux/mac提供SDK支持.
|
||||
2.优化了bridge的日志,增加了client和server的掉线日志.
|
||||
3.优化了sps读取http(s)代理响应的缓冲大小,同时优化了CONNECT请求,
|
||||
避免了某些代理服务器返回过多数据导致不能正常通讯的问题.
|
||||
4.去除了鸡肋连接池功能.
|
||||
5.优化了所有服务代码,方便对sdk提供支持.
|
||||
6.增加了SDK手册.
|
||||
7.增加了GUI客户端(windows/web/android/ios)介绍主页.
|
||||
8.SPS\HTTP(s)\Socks代理增加了自定义加密传输,只需要通过参数-z和-Z设置一个密码即可.
|
||||
9.SPS\HTTP(s)\Socks代理增加了压缩传输,只需要通过参数-m和-M设置即可.
|
||||
10.手册增加了SPS\HTTP(s)\Socks自定义加密的使用示例.
|
||||
11.手册增加了SPS\HTTP(s)\Socks压缩传输的使用示例.
|
||||
12.优化了多链接版本的内网穿透,融合了多链接和smux的优点,即能够拥有大的吞吐量,
|
||||
同时又具备mux的心跳机制保证了链接的稳定性.
|
||||
13.手册增加了大量配图.
|
||||
14.优化了socks代理udp上级的设置逻辑,智能判断parent上级填充udp parent.
|
||||
15.优化了项目文件夹结构,使用源码可以直接go get.
|
||||
|
||||
v4.6
|
||||
1.sps,http(s),socks5,内网穿透都做了大量的超时优化处理,更加稳定.
|
||||
2.sps增加了强大的树形级联认证支持,可以轻松构建你的认证代理网络.
|
||||
3.手册增加了6.6对sps认证功能的介绍.
|
||||
|
||||
|
||||
v4.5
|
||||
1.优化了mux内网穿透连接管理逻辑,增强了稳定性.
|
||||
2.mux内网穿透增加了tcp和kcp协议支持,之前是tls,现在支持三种协议tcp,tls,kcp.
|
||||
3.keygen参数增加了用法: proxy keygen usage.
|
||||
4.http(s)/socks5代理,tls增加了自签名证书支持.
|
||||
5.建议升级.
|
||||
v4.4
|
||||
1.增加了协议转换sps功能,代理协议转换使用的是sps子命令(socks+https的缩写),
|
||||
sps本身不提供代理功能,只是接受代理请求"转换并转发"给已经存在的http(s)代理
|
||||
或者socks5代理;sps可以把已经存在的http(s)代理或者socks5代理转换为一个端口
|
||||
同时支持http(s)和socks5代理,而且http(s)代理支持正向代理和反向代理(SNI),转
|
||||
换后的SOCKS5代理不支持UDP功能;另外对于已经存在的http(s)代理或者socks5代理,
|
||||
支持tls、tcp、kcp三种模式,支持链式连接,也就是可以多个sps结点层级连接构建
|
||||
加密通道。
|
||||
2.增加了对KCP传输参数的配置,多达17个参数可以自由的配置对kcp传输效率调优。
|
||||
3.内网穿透功能,server和client增加了--session-count参数,可以设置server每个
|
||||
监听端口到bridge打开的session数量,可以设置client到bridge打开的session数量,
|
||||
之前都是1个,现在性能提升N倍,N就是你自己设置的--session-count,这个参数很大
|
||||
程度上解决了多路复用的拥塞问题,v4.4开始默认10个。
|
||||
|
||||
v4.3
|
||||
1.优化了参数keygen生成证书逻辑,避免证书出现特征。
|
||||
2.http(s)和socks代理增加了--dns-address和--dns-ttl参数。
|
||||
用于自己指定proxy访问域名的时候使用的dns(--dns-address)以及解析结果缓存时间(--dns-ttl)秒数,
|
||||
避免系统dns对proxy的干扰,另外缓存功能还能减少dns解析时间提高访问速度。
|
||||
3.优化了http代理的basic认证逻辑。
|
||||
提示:
|
||||
v4.3生成的证书不适用于v4.2及以下版本。
|
||||
|
||||
v4.2
|
||||
1.优化了内网穿透,避免了client意外下线,导致链接信息残留的问题.
|
||||
2.http代理增加了SNI支持,现在http(s)代理模式支持反向代理,支持http(s)透明代理.
|
||||
|
||||
82
Dockerfile
Normal file
@ -0,0 +1,82 @@
|
||||
FROM alpine:3.7 AS builder
|
||||
|
||||
RUN apk add --no-cache \
|
||||
ca-certificates
|
||||
|
||||
# set up nsswitch.conf for Go's "netgo" implementation
|
||||
# - https://github.com/golang/go/blob/go1.9.1/src/net/conf.go#L194-L275
|
||||
# - docker run --rm debian:stretch grep '^hosts:' /etc/nsswitch.conf
|
||||
RUN [ ! -e /etc/nsswitch.conf ] && echo 'hosts: files dns' > /etc/nsswitch.conf
|
||||
|
||||
ENV GOLANG_VERSION 1.10.3
|
||||
|
||||
# make-sure-R0-is-zero-before-main-on-ppc64le.patch: https://github.com/golang/go/commit/9aea0e89b6df032c29d0add8d69ba2c95f1106d9 (Go 1.9)
|
||||
#COPY *.patch /go-alpine-patches/
|
||||
|
||||
RUN set -eux; \
|
||||
apk add --no-cache --virtual .build-deps \
|
||||
bash \
|
||||
gcc \
|
||||
musl-dev \
|
||||
openssl \
|
||||
go \
|
||||
; \
|
||||
export \
|
||||
# set GOROOT_BOOTSTRAP such that we can actually build Go
|
||||
GOROOT_BOOTSTRAP="$(go env GOROOT)" \
|
||||
# ... and set "cross-building" related vars to the installed system's values so that we create a build targeting the proper arch
|
||||
# (for example, if our build host is GOARCH=amd64, but our build env/image is GOARCH=386, our build needs GOARCH=386)
|
||||
GOOS="$(go env GOOS)" \
|
||||
GOARCH="$(go env GOARCH)" \
|
||||
GOHOSTOS="$(go env GOHOSTOS)" \
|
||||
GOHOSTARCH="$(go env GOHOSTARCH)" \
|
||||
; \
|
||||
# also explicitly set GO386 and GOARM if appropriate
|
||||
# https://github.com/docker-library/golang/issues/184
|
||||
apkArch="$(apk --print-arch)"; \
|
||||
case "$apkArch" in \
|
||||
armhf) export GOARM='6' ;; \
|
||||
x86) export GO386='387' ;; \
|
||||
esac; \
|
||||
\
|
||||
wget -O go.tgz "https://golang.org/dl/go$GOLANG_VERSION.src.tar.gz"; \
|
||||
echo '567b1cc66c9704d1c019c50bef946272e911ec6baf244310f87f4e678be155f2 *go.tgz' | sha256sum -c -; \
|
||||
tar -C /usr/local -xzf go.tgz; \
|
||||
rm go.tgz; \
|
||||
\
|
||||
cd /usr/local/go/src; \
|
||||
for p in /go-alpine-patches/*.patch; do \
|
||||
[ -f "$p" ] || continue; \
|
||||
patch -p2 -i "$p"; \
|
||||
done; \
|
||||
./make.bash; \
|
||||
\
|
||||
rm -rf /go-alpine-patches; \
|
||||
apk del .build-deps; \
|
||||
\
|
||||
export PATH="/usr/local/go/bin:$PATH"; \
|
||||
go version
|
||||
|
||||
ENV GOPATH /go
|
||||
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH
|
||||
|
||||
RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH"
|
||||
WORKDIR $GOPATH
|
||||
|
||||
ARG GOPROXY_VERSION=master
|
||||
RUN apk update; apk upgrade; \
|
||||
apk add --no-cache git; \
|
||||
cd /go/src/; \
|
||||
mkdir github.com; \
|
||||
mkdir github.com/snail007; \
|
||||
cd github.com/snail007; \
|
||||
git clone https://github.com/snail007/goproxy.git; \
|
||||
cd goproxy; \
|
||||
git checkout ${GOPROXY_VERSION}; \
|
||||
CGO_ENABLED=0 GOOS=linux go build -ldflags "-s -w" -a -installsuffix cgo -o proxy; \
|
||||
chmod 0777 proxy
|
||||
|
||||
FROM 1.10.3-stretch
|
||||
RUN mkdir /proxy && chmod 0777 /proxy
|
||||
COPY --from=builder builder /go/src/github.com/snail007/goproxy/proxy /proxy/
|
||||
CMD cd /proxy && /proxy ${OPTS}
|
||||
133
Godeps/Godeps.json
generated
@ -1,133 +0,0 @@
|
||||
{
|
||||
"ImportPath": "proxy",
|
||||
"GoVersion": "go1.8",
|
||||
"GodepVersion": "v79",
|
||||
"Packages": [
|
||||
"./..."
|
||||
],
|
||||
"Deps": [
|
||||
{
|
||||
"ImportPath": "github.com/alecthomas/template",
|
||||
"Rev": "a0175ee3bccc567396460bf5acd36800cb10c49c"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/alecthomas/template/parse",
|
||||
"Rev": "a0175ee3bccc567396460bf5acd36800cb10c49c"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/alecthomas/units",
|
||||
"Rev": "2efee857e7cfd4f3d0138cc3cbb1b4966962b93a"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/golang/snappy",
|
||||
"Rev": "553a641470496b2327abcac10b36396bd98e45c9"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/pkg/errors",
|
||||
"Comment": "v0.8.0-6-g602255c",
|
||||
"Rev": "602255cdb6deaf1523ea53ac30eae5554ba7bee9"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/templexxx/cpufeat",
|
||||
"Rev": "3794dfbfb04749f896b521032f69383f24c3687e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/templexxx/reedsolomon",
|
||||
"Comment": "0.1.1-4-g7092926",
|
||||
"Rev": "7092926d7d05c415fabb892b1464a03f8228ab80"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/templexxx/xor",
|
||||
"Comment": "0.1.2",
|
||||
"Rev": "0af8e873c554da75f37f2049cdffda804533d44c"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/tjfoc/gmsm/sm4",
|
||||
"Comment": "v1.0.1-3-g9d99fac",
|
||||
"Rev": "9d99face20b0dd300b7db50b3f69758de41c096a"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/xtaci/kcp-go",
|
||||
"Comment": "v3.19-6-g21da33a",
|
||||
"Rev": "21da33a6696d67c1bffb3c954366499d613097a6"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/xtaci/smux",
|
||||
"Comment": "v1.0.6",
|
||||
"Rev": "ebec7ef2574b42a7088cd7751176483e0a27d458"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/crypto/blowfish",
|
||||
"Rev": "f899cbd3df85058aa20d1cf129473b18f2a2b49f"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/crypto/cast5",
|
||||
"Rev": "86e16787bfd59cb4db9e278c51a95488c141a5d6"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/crypto/curve25519",
|
||||
"Rev": "1843fabd21d7180cf65e36759986d00c13dbb0fd"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/crypto/ed25519",
|
||||
"Rev": "1843fabd21d7180cf65e36759986d00c13dbb0fd"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/crypto/ed25519/internal/edwards25519",
|
||||
"Rev": "1843fabd21d7180cf65e36759986d00c13dbb0fd"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/crypto/pbkdf2",
|
||||
"Rev": "1843fabd21d7180cf65e36759986d00c13dbb0fd"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/crypto/salsa20",
|
||||
"Rev": "1843fabd21d7180cf65e36759986d00c13dbb0fd"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/crypto/salsa20/salsa",
|
||||
"Rev": "1843fabd21d7180cf65e36759986d00c13dbb0fd"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/crypto/ssh",
|
||||
"Rev": "1843fabd21d7180cf65e36759986d00c13dbb0fd"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/crypto/tea",
|
||||
"Rev": "1843fabd21d7180cf65e36759986d00c13dbb0fd"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/crypto/twofish",
|
||||
"Rev": "1843fabd21d7180cf65e36759986d00c13dbb0fd"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/crypto/xtea",
|
||||
"Rev": "1843fabd21d7180cf65e36759986d00c13dbb0fd"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/net/bpf",
|
||||
"Rev": "114479435b31b5077a087cc5303a45cb5d355dc4"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/net/internal/iana",
|
||||
"Rev": "114479435b31b5077a087cc5303a45cb5d355dc4"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/net/internal/socket",
|
||||
"Rev": "114479435b31b5077a087cc5303a45cb5d355dc4"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/net/ipv4",
|
||||
"Rev": "114479435b31b5077a087cc5303a45cb5d355dc4"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/time/rate",
|
||||
"Rev": "8be79e1e0910c292df4e79c241bb7e8f7e725959"
|
||||
},
|
||||
{
|
||||
"ImportPath": "gopkg.in/alecthomas/kingpin.v2",
|
||||
"Comment": "v2.2.5",
|
||||
"Rev": "1087e65c9441605df944fb12c33f0fe7072d18ca"
|
||||
}
|
||||
]
|
||||
}
|
||||
5
Godeps/Readme
generated
@ -1,5 +0,0 @@
|
||||
This directory tree is generated automatically by godep.
|
||||
|
||||
Please do not edit.
|
||||
|
||||
See https://github.com/tools/godep for more information.
|
||||
139
Gopkg.lock
generated
Normal file
@ -0,0 +1,139 @@
|
||||
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
|
||||
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/alecthomas/template"
|
||||
packages = [
|
||||
".",
|
||||
"parse"
|
||||
]
|
||||
revision = "a0175ee3bccc567396460bf5acd36800cb10c49c"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/alecthomas/units"
|
||||
packages = ["."]
|
||||
revision = "2efee857e7cfd4f3d0138cc3cbb1b4966962b93a"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/golang/snappy"
|
||||
packages = ["."]
|
||||
revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/hashicorp/yamux"
|
||||
packages = ["."]
|
||||
revision = "3520598351bb3500a49ae9563f5539666ae0a27c"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/klauspost/cpuid"
|
||||
packages = ["."]
|
||||
revision = "ae7887de9fa5d2db4eaa8174a7eff2c1ac00f2da"
|
||||
version = "v1.1"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/klauspost/reedsolomon"
|
||||
packages = ["."]
|
||||
revision = "6bb6130ff6a76a904c1841707d65603aec9cc288"
|
||||
version = "v1.6"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/miekg/dns"
|
||||
packages = ["."]
|
||||
revision = "5a2b9fab83ff0f8bfc99684bd5f43a37abe560f1"
|
||||
version = "v1.0.8"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/pkg/errors"
|
||||
packages = ["."]
|
||||
revision = "645ef00459ed84a119197bfb8d8205042c6df63d"
|
||||
version = "v0.8.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/pmylund/go-cache"
|
||||
packages = ["."]
|
||||
revision = "a3647f8e31d79543b2d0f0ae2fe5c379d72cedc0"
|
||||
version = "v2.1.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/templexxx/cpufeat"
|
||||
packages = ["."]
|
||||
revision = "3794dfbfb04749f896b521032f69383f24c3687e"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/templexxx/xor"
|
||||
packages = ["."]
|
||||
revision = "0af8e873c554da75f37f2049cdffda804533d44c"
|
||||
version = "0.1.2"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/tjfoc/gmsm"
|
||||
packages = ["sm4"]
|
||||
revision = "98aa888b79d8de04afe0fccf45ed10594efc858b"
|
||||
version = "v1.1"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/xtaci/kcp-go"
|
||||
packages = ["."]
|
||||
revision = "42bc1dfefff592fdb3affa793980c4f6ab4213e5"
|
||||
version = "v3.25"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/crypto"
|
||||
packages = [
|
||||
"blowfish",
|
||||
"cast5",
|
||||
"curve25519",
|
||||
"ed25519",
|
||||
"ed25519/internal/edwards25519",
|
||||
"internal/chacha20",
|
||||
"internal/subtle",
|
||||
"pbkdf2",
|
||||
"poly1305",
|
||||
"salsa20",
|
||||
"salsa20/salsa",
|
||||
"ssh",
|
||||
"tea",
|
||||
"twofish",
|
||||
"xtea"
|
||||
]
|
||||
revision = "a8fb68e7206f8c78be19b432c58eb52a6aa34462"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/net"
|
||||
packages = [
|
||||
"bpf",
|
||||
"context",
|
||||
"internal/iana",
|
||||
"internal/socket",
|
||||
"internal/socks",
|
||||
"ipv4",
|
||||
"ipv6",
|
||||
"proxy"
|
||||
]
|
||||
revision = "db08ff08e8622530d9ed3a0e8ac279f6d4c02196"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/time"
|
||||
packages = ["rate"]
|
||||
revision = "fbb02b2291d28baffd63558aa44b4b56f178d650"
|
||||
|
||||
[[projects]]
|
||||
name = "gopkg.in/alecthomas/kingpin.v2"
|
||||
packages = ["."]
|
||||
revision = "947dcec5ba9c011838740e680966fd7087a71d0d"
|
||||
version = "v2.2.6"
|
||||
|
||||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
inputs-digest = "eab0ef29432489696d8bfd524757dcb03a83f91c329f2d05c36da70df850360d"
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
||||
66
Gopkg.toml
Normal file
@ -0,0 +1,66 @@
|
||||
# Gopkg.toml example
|
||||
#
|
||||
# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html
|
||||
# for detailed Gopkg.toml documentation.
|
||||
#
|
||||
# required = ["github.com/user/thing/cmd/thing"]
|
||||
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
|
||||
#
|
||||
# [[constraint]]
|
||||
# name = "github.com/user/project"
|
||||
# version = "1.0.0"
|
||||
#
|
||||
# [[constraint]]
|
||||
# name = "github.com/user/project2"
|
||||
# branch = "dev"
|
||||
# source = "github.com/myfork/project2"
|
||||
#
|
||||
# [[override]]
|
||||
# name = "github.com/x/y"
|
||||
# version = "2.4.0"
|
||||
#
|
||||
# [prune]
|
||||
# non-go = false
|
||||
# go-tests = true
|
||||
# unused-packages = true
|
||||
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/golang/snappy"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/hashicorp/yamux"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/miekg/dns"
|
||||
version = "1.0.8"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/pmylund/go-cache"
|
||||
version = "2.1.0"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/xtaci/kcp-go"
|
||||
version = "3.25.0"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/crypto"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/net"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/time"
|
||||
|
||||
[[constraint]]
|
||||
name = "gopkg.in/alecthomas/kingpin.v2"
|
||||
version = "2.2.6"
|
||||
|
||||
[prune]
|
||||
go-tests = true
|
||||
unused-packages = true
|
||||
517
README.md
@ -1,11 +1,23 @@
|
||||
<img src="https://github.com/snail007/goproxy/blob/master/docs/images/logo.jpg?raw=true" width="200"/>
|
||||
Proxy is a high performance HTTP(S), websocket, TCP, UDP, Socks5 proxy server implemented by golang. It supports parent proxy,nat forward,TCP/UDP port forwarding, SSH transfer. you can expose a local server behind a NAT or firewall to the internet.
|
||||
<img src="https://github.com/snail007/goproxy/blob/master/docs/images/logo.jpg?raw=true" width="200"/>
|
||||
Proxy is a high performance HTTP, HTTPS, HTTPS, websocket, TCP, UDP, Socks5 proxy server implemented by golang. It supports parent proxy,nat forward,TCP/UDP port forwarding, SSH transfer, TLS encrypted transmission, protocol conversion. you can expose a local server behind a NAT or firewall to the internet, secure DNS proxy.
|
||||
|
||||
|
||||
---
|
||||
|
||||
[](https://github.com/snail007/goproxy/) []() [](https://github.com/snail007/goproxy/releases) [](https://github.com/snail007/goproxy/releases)
|
||||
|
||||
[中文手册](/README_ZH.md)
|
||||
**[中文手册](/README_ZH.md)**
|
||||
|
||||
**[全平台图形界面版本](/gui/README.md)**
|
||||
|
||||
**[全平台SDK](/sdk/README.md)**
|
||||
|
||||
### How to contribute to the code (Pull Request)?
|
||||
|
||||
Pull Request is welcomed.
|
||||
First, you need to clone the project to your account, and then modify the code on the dev branch.
|
||||
Finally, Pull Request to dev branch of goproxy project, and contribute code for efficiency.
|
||||
PR needs to explain what changes have been made and why you change them.
|
||||
|
||||
### Features
|
||||
- chain-style proxy: the program itself can be a primary proxy, and if a parent proxy is set, it can be used as a second level proxy or even a N level proxy.
|
||||
@ -21,6 +33,10 @@ Proxy is a high performance HTTP(S), websocket, TCP, UDP, Socks5 proxy server im
|
||||
- The integrated external API, HTTP (S): SOCKS5 proxy authentication can be integrated with the external HTTP API, which can easily control the user's access through the external system.
|
||||
- Reverse proxy: goproxy supports directly parsing the domain to proxy monitor IP, and then proxy will help you to access the HTTP (S) site that you need to access.
|
||||
- Transparent proxy: with the iptables, goproxy can directly forward the 80 and 443 port's traffic to proxy in the gateway, and can realize the unaware intelligent router proxy.
|
||||
- Protocol conversion: The existing HTTP (S) or SOCKS5 proxy can be converted to a proxy which support both HTTP (S) and SOCKS5 by one port, but the converted SOCKS5 proxy does not support the UDP function.Also support powerful cascading authentication.
|
||||
- Custom underlying encrypted transmission, HTTP(s)\sps\socks proxy can encrypt TCP data through TLS standard encryption and KCP protocol encryption. In addition, it also supports custom encryption after TLS and KCP. That is to say, custom encryption and tls|kcp can be used together. The internal uses AES256 encryption, and it only needs to define one password by yourself when is used.
|
||||
- Low level compression and efficient transmission,The HTTP(s)\sps\socks proxy can encrypt TCP data through a custom encryption and TLS standard encryption and KCP protocol encryption, and can also compress the data after encryption. That is to say, the compression and custom encryption and tls|kcp can be used together.
|
||||
- The secure DNS proxy, Through the DNS proxy provided by the local proxy, you can encrypted communicate with the father proxy to realize the DNS query of security and pollution prevention.
|
||||
|
||||
### Why need these?
|
||||
- Because for some reason, we cannot access our services elsewhere. We can build a secure tunnel to access our services through multiple connected proxy nodes.
|
||||
@ -32,26 +48,17 @@ Proxy is a high performance HTTP(S), websocket, TCP, UDP, Socks5 proxy server im
|
||||
- ...
|
||||
|
||||
|
||||
This page is the v4.2 manual, and the other version of the manual can be checked by the following link.
|
||||
- [v4.0-4.1 manual](https://github.com/snail007/goproxy/tree/v4.1)
|
||||
- [v3.9 manual](https://github.com/snail007/goproxy/tree/v3.9)
|
||||
- [v3.8 manual](https://github.com/snail007/goproxy/tree/v3.8)
|
||||
- [v3.6-v3.7 manual](https://github.com/snail007/goproxy/tree/v3.6)
|
||||
- [v3.5 manual](https://github.com/snail007/goproxy/tree/v3.5)
|
||||
- [v3.4 manual](https://github.com/snail007/goproxy/tree/v3.4)
|
||||
- [v3.3 manual](https://github.com/snail007/goproxy/tree/v3.3)
|
||||
- [v3.2 manual](https://github.com/snail007/goproxy/tree/v3.2)
|
||||
- [v3.1 manual](https://github.com/snail007/goproxy/tree/v3.1)
|
||||
- [v3.0 manual](https://github.com/snail007/goproxy/tree/v3.0)
|
||||
- [v2.x manual](https://github.com/snail007/goproxy/tree/v2.2)
|
||||
This page is the v5.3 manual, and the other version of the manual can be checked by the following [link](docs/old-release.md).
|
||||
|
||||
### How to find the organization?
|
||||
[Click to join the proxy group of gitter](https://gitter.im/go-proxy/Lobby?utm_source=share-link&utm_medium=link&utm_campaign=share-link)
|
||||
[Click to join the proxy group of gitter](https://gitter.im/go-proxy/Lobby?utm_source=share-link&utm_medium=link&utm_campaign=share-link)
|
||||
[Click to join the proxy group of telegram](https://t.me/joinchat/GYHXghCDSBmkKZrvu4wIdQ)
|
||||
|
||||
|
||||
### Installation
|
||||
- [Quick installation](#quick-installation)
|
||||
- [Manual installation](#manual-installation)
|
||||
- [Docker installation](#docker-installation)
|
||||
|
||||
### First use must read
|
||||
- [Environmental Science](#environmental-science)
|
||||
@ -77,7 +84,10 @@ This page is the v4.2 manual, and the other version of the manual can be checked
|
||||
- [1.8 KCP protocol transmission](#18kcp-protocol-transmission)
|
||||
- [1.9 HTTP(S) reverse proxy](#19http-reverse-proxy)
|
||||
- [1.10 HTTP(S) transparent proxy](#110http-transparent-proxy)
|
||||
- [1.11 View help](#111view-help)
|
||||
- [1.11 Custom DNS](#111custom-dns)
|
||||
- [1.12 Custom encryption](#112-custom-encryption)
|
||||
- [1.13 Compressed transmission](#113-compressed-transmission)
|
||||
- [1.14 View help](#114view-help)
|
||||
- [2.TCP proxy](#2tcp-proxy)
|
||||
- [2.1 Common TCP first level proxy](#21common-tcp-first-level-proxy)
|
||||
- [2.2 Common TCP second level proxy](#22common-tcp-second-level-proxy)
|
||||
@ -112,7 +122,28 @@ This page is the v4.2 manual, and the other version of the manual can be checked
|
||||
- [5.6.2 The way of username and key](#562the-way-of-username-and-key)
|
||||
- [5.7 Authentication](#57authentication)
|
||||
- [5.8 KCP protocol transmission](#58kcp-protocol-transmission)
|
||||
- [5.9 View help](#59view-help)
|
||||
- [5.9 Custom DNS](#59custom-dns)
|
||||
- [5.10 Custom encryption](#510custom-encryption)
|
||||
- [5.11 Compressed transmission](#511compressed-transmission)
|
||||
- [5.12 View help](#512view-help)
|
||||
- [6.Proxy protocol conversion](#6proxy-protocol-conversion)
|
||||
- [6.1 Functional introduction](#61functional-introduction)
|
||||
- [6.2 HTTP(S) to HTTP(S) + SOCKS5](#62http-to-http-socks5)
|
||||
- [6.3 SOCKS5 to HTTP(S) + SOCKS5](#63socks5-to-http-socks5)
|
||||
- [6.4 Chain style connection](#64chain-style-connection)
|
||||
- [6.5 Listening on multiple ports](#65listening-on-multiple-ports)
|
||||
- [6.6 Authentication](#66authentication)
|
||||
- [6.7 Custom encryption](#67-custom-encryption)
|
||||
- [6.8 Compressed transmission](#68-compressed-transmission)
|
||||
- [6.9 View Help](#69view-help)
|
||||
- [7.KCP Configuration](#7kcp-configuration)
|
||||
- [7.1 Configuration introduction](#71configuration-introduction)
|
||||
- [7.2 Configuration details](#72configuration-details)
|
||||
- [8.DNS anti pollution server](#8dns-anti-pollution-server)
|
||||
- [8.1 Introduction](#81introduction)
|
||||
- [8.2 Use examples](#82use-examples)
|
||||
|
||||
|
||||
|
||||
### Fast Start
|
||||
tips:all operations require root permissions.
|
||||
@ -130,7 +161,7 @@ If the installation fails or your VPS is not a linux64 system, please follow the
|
||||
Download address: https://github.com/snail007/goproxy/releases
|
||||
```shell
|
||||
cd /root/proxy/
|
||||
wget https://github.com/snail007/goproxy/releases/download/v4.0/proxy-linux-amd64.tar.gz
|
||||
wget https://github.com/snail007/goproxy/releases/download/v5.3/proxy-linux-amd64.tar.gz
|
||||
```
|
||||
#### **2.Download the automatic installation script**
|
||||
```shell
|
||||
@ -139,6 +170,36 @@ wget https://raw.githubusercontent.com/snail007/goproxy/master/install.sh
|
||||
chmod +x install.sh
|
||||
./install.sh
|
||||
```
|
||||
|
||||
#### Docker installation
|
||||
|
||||
Dockerfile root of project uses multistage build and alpine project to comply with best practices. Uses golang 1.10.3 for building as noted in the project README.md and will be pretty small image. total extracted size will be 17.3MB for goproxy latest version.
|
||||
|
||||
The default build process builds the master branch (latest commits/ cutting edge), and it can be configured to build specific version, just edit Dockerfile before build, following builds release version 5.3:
|
||||
|
||||
```
|
||||
ARG GOPROXY_VERSION=v5.3
|
||||
```
|
||||
|
||||
To Run:
|
||||
1. Clone the repository and cd into it.
|
||||
```
|
||||
sudo docker build .
|
||||
```
|
||||
2. Tag the image:
|
||||
```
|
||||
sudo docker tag <id from previous step> snail007/goproxy:latest
|
||||
```
|
||||
3. Run!
|
||||
Just put your arguments to proxy binary in the OPTS environmental variable (this is just a sample http proxy):
|
||||
```
|
||||
sudo docker run -d --restart=always --name goproxy -e OPTS="http -p :33080" -p 33080:33080 snail007/goproxy:latest
|
||||
```
|
||||
4. View logs:
|
||||
```
|
||||
sudo docker logs -f goproxy
|
||||
```
|
||||
|
||||
|
||||
## **First use must be read**
|
||||
|
||||
@ -166,9 +227,18 @@ for example, --log proxy.log, The log will be exported to proxy.log file which i
|
||||
|
||||
### **Generating a communication certificate file**
|
||||
HTTP, TCP, UDP proxy process will communicate with parent proxy. In order to secure, we use encrypted communication. Of course, we can choose not to encrypted communication. All communication with parent proxy in this tutorial is encrypted, requiring certificate files.
|
||||
The OpenSSL command is installed on the Linux and encrypted certificate can be generated directly through the following command.
|
||||
`./proxy keygen`
|
||||
By default, the certificate file proxy.crt and the key file proxy.key are generated under the current program directory.
|
||||
|
||||
1.Generate signed certificates and key files through the following commands.
|
||||
`./proxy keygen -C proxy`
|
||||
The certificate file proxy.crt and key file proxy.key will be generated under the current directory.
|
||||
|
||||
2.Through the following commands, use the signed certificate proxy.crt and key file proxy.key to issue new certificates: goproxy.crt and goproxy.key.
|
||||
`./proxy keygen -s -C proxy -c goproxy`
|
||||
The certificate file goproxy.crt and key file goproxy.key will be generated under the current program directory.
|
||||
|
||||
3.By default, the domain name in the certificate is a random domain and can be specified using the `-n test.com` parameter.
|
||||
|
||||
4.More usage:`proxy keygen --help`。
|
||||
|
||||
### **Daemon mode**
|
||||
After the default execution of proxy, if you want to keep proxy running, you can't close the command line.
|
||||
@ -189,10 +259,11 @@ Assuming that your VPS outer external network IP is 23.23.23.23, the following c
|
||||
|
||||
### **1.HTTP proxy**
|
||||
#### **1.1.common HTTP proxy**
|
||||

|
||||

|
||||
`./proxy http -t tcp -p "0.0.0.0:38080"`
|
||||
|
||||
#### **1.2.Common HTTP second level proxy**
|
||||

|
||||
Using local port 8090, assume the parent HTTP proxy is: `22.22.22.22:8080`
|
||||
`./proxy http -t tcp -p "0.0.0.0:8090" -T tcp -P "22.22.22.22:8080" `
|
||||
The connection pool is closed by default. If you want to speed up access speed, -L can open the connection pool, the 10 is the size of the connection pool, and the 0 is closed.
|
||||
@ -202,6 +273,7 @@ We can also specify the black and white list files of the domain name, one line
|
||||
`./proxy http -p "0.0.0.0:8090" -T tcp -P "22.22.22.22:8080" -b blocked.txt -d direct.txt`
|
||||
|
||||
#### **1.3.HTTP second level encrypted proxy**
|
||||

|
||||
HTTP first level proxy(VPS,IP:22.22.22.22)
|
||||
`./proxy http -t tls -p ":38080" -C proxy.crt -K proxy.key`
|
||||
|
||||
@ -214,6 +286,7 @@ HTTP second level proxy(local windows)
|
||||
In your windos system, the mode of the program that needs to surf the Internet by proxy is setted up as HTTP mode, the address is 127.0.0.1, the port is: 8080, the program can go through the encrypted channel through VPS to surf on the internet.
|
||||
|
||||
#### **1.4.HTTP third level encrypted proxy**
|
||||

|
||||
HTTP first level proxy VPS_01,IP:22.22.22.22
|
||||
`./proxy http -t tls -p ":38080" -C proxy.crt -K proxy.key`
|
||||
HTTP second level proxy VPS_02,IP:33.33.33.33
|
||||
@ -250,6 +323,7 @@ Through --always, all HTTP proxy traffic can be coercion to the parent HTTP prox
|
||||
`./proxy http --always -t tls -p ":28080" -T tls -P "22.22.22.22:38080" -C proxy.crt -K proxy.key`
|
||||
|
||||
#### **1.7.Transfer through SSH**
|
||||

|
||||
Explanation: the principle of SSH transfer is to take advantage of SSH's forwarding function, which is, after you connect to SSH, you can access to the target address through the SSH proxy.
|
||||
Suppose there is a vps
|
||||
- IP is 2.2.2.2, ssh port is 22, ssh username is user, ssh password is demo
|
||||
@ -263,15 +337,17 @@ Local HTTP (S) proxy use 28080 port,excute:
|
||||
`./proxy http -T ssh -P "2.2.2.2:22" -u user -S user.key -t tcp -p ":28080"`
|
||||
|
||||
#### **1.8.KCP protocol transmission**
|
||||
The KCP protocol requires a -B parameter to set a password which can encrypt and decrypt data.
|
||||

|
||||
The KCP protocol requires a --kcp-key parameter to set a password which can encrypt and decrypt data.
|
||||
|
||||
Http first level proxy(VPS,IP:22.22.22.22)
|
||||
`./proxy http -t kcp -p ":38080" -B mypassword`
|
||||
`./proxy http -t kcp -p ":38080" --kcp-key mypassword`
|
||||
|
||||
Http second level proxy(os is Linux)
|
||||
`./proxy http -t tcp -p ":8080" -T kcp -P "22.22.22.22:38080" -B mypassword`
|
||||
`./proxy http -t tcp -p ":8080" -T kcp -P "22.22.22.22:38080" --kcp-key mypassword`
|
||||
Then access to the local 8080 port is access to the proxy's port 38080 on the VPS, and the data is transmitted through the KCP protocol.
|
||||
#### **1.9.HTTP reverse proxy**
|
||||

|
||||
Proxy supports not only set up a proxy through in other software, to provide services for other software, but support the request directly to the website domain to proxy monitor IP when proxy monitors 80 and 443 ports, then proxy will automatically access to the HTTP proxy access website for you.
|
||||
|
||||
How to use:
|
||||
@ -331,19 +407,67 @@ iptables -t nat -A OUTPUT -p tcp -j PROXY
|
||||
- Deleting the specified chain that user defined command is iptables -X chain name, such as iptables -t NAT -X PROXY
|
||||
- Deleting the rules of the chain command is iptables -D chain name from the selected chain, such as iptables -t nat -D PROXY -d 223.223.192.0/255.255.240.0 -j RETURN
|
||||
|
||||
#### **1.11.view help**
|
||||
#### **1.11.Custom DNS**
|
||||
--dns-address and --dns-ttl parameters can be used to specify DNS(--dns-address) when you use proxy to access to a domain.
|
||||
they also can specify dns result cache time (--dns-ttl) which unit is second. they can avoid the interference of system DNS to proxy. cache can reduce DNS resolution time and increase access speed.
|
||||
for example:
|
||||
`./proxy http -p ":33080" --dns-address "8.8.8.8:53" --dns-ttl 300`
|
||||
|
||||
#### **1.12 Custom encryption**
|
||||
HTTP(s) proxy can encrypt TCP data by TLS standard encryption and KCP protocol encryption, in addition to supporting custom encryption after TLS and KCP, That is to say, custom encryption and tls|kcp can be combined to use. The internal AES256 encryption is used, and it only needs to define one password by yourself. Encryption is divided into two parts, the one is whether the local (-z) is encrypted and decrypted, the other is whether the parents (-Z) is encrypted and decrypted.
|
||||
Custom encryption requires both ends are proxy. Next, we use two level example and three level example as examples:
|
||||
|
||||
**two level example**
|
||||
First level VPS (ip:2.2.2.2) execution:
|
||||
`proxy http -t tcp -z demo_password -p :7777`
|
||||
Local second level execution:
|
||||
`proxy http -T tcp -P 2.2.2.2:777 -Z demo_password -t tcp -p :8080`
|
||||
through this way, When you visits the website by local proxy 8080, it visits the target website by encryption transmission with the parents proxy.
|
||||
|
||||
**three level example**
|
||||
First level VPS (ip:2.2.2.2) execution:
|
||||
`proxy http -t tcp -z demo_password -p :7777`
|
||||
Second level VPS (ip:2.2.2.2) execution:
|
||||
`proxy http -T tcp -P 2.2.2.2:7777 -Z demo_password -t tcp -z other_password -p :8888`
|
||||
Local third level execution:
|
||||
`proxy http -T tcp -P 3.3.3.3:8888 -Z other_password -t tcp -p :8080`
|
||||
through this way, When you visits the website by local proxy 8080, it visits the target website by encryption transmission with the parents proxy.
|
||||
|
||||
#### **1.13 Compressed transmission**
|
||||
HTTP(s) proxy can encrypt TCP data through TCP standard encryption and KCP protocol encryption, and can also compress data before custom encryption.
|
||||
That is to say, compression and custom encryption and tls|kcp can be used together, compression is divided into two parts, the one is whether the local (-z) is compressed transmission, the other is whether the parents (-Z) is compressed transmission.
|
||||
The compression requires both ends are proxy. Compression also protects the (encryption) data in certain extent. we use two level example and three level example as examples:
|
||||
|
||||
**two level example**
|
||||
First level VPS (ip:2.2.2.2) execution:
|
||||
`proxy http -t tcp -m -p :7777`
|
||||
Local second level execution:
|
||||
`proxy http -T tcp -P 2.2.2.2:777 -M -t tcp -p :8080`
|
||||
through this way, When you visits the website by local proxy 8080, it visits the target website by compressed transmission with the parents proxy.
|
||||
|
||||
|
||||
**three level example**
|
||||
First level VPS (ip:2.2.2.2) execution:
|
||||
`proxy http -t tcp -m -p :7777`
|
||||
Second level VPS (ip:3.3.3.3) execution:
|
||||
`proxy http -T tcp -P 2.2.2.2:7777 -M -t tcp -m -p :8888`
|
||||
Local third level execution:
|
||||
`proxy http -T tcp -P 3.3.3.3:8888 -M -t tcp -p :8080`
|
||||
through this way, When you visits the website by local proxy 8080, it visits the target website by compressed transmission with the parents proxy.
|
||||
|
||||
#### **1.14.view help**
|
||||
`./proxy help http`
|
||||
|
||||
### **2.TCP proxy**
|
||||
|
||||
#### **2.1.Common TCP first level proxy**
|
||||

|
||||

|
||||
Local execution:
|
||||
`./proxy tcp -p ":33080" -T tcp -P "192.168.22.33:22" -L 0`
|
||||
Then access to the local 33080 port is the 22 port of access to 192.168.22.33.
|
||||
|
||||
#### **2.2.Common TCP second level proxy**
|
||||

|
||||

|
||||
VPS(IP:22.22.22.33) execute:
|
||||
`./proxy tcp -p ":33080" -T tcp -P "127.0.0.1:8080" -L 0`
|
||||
local execution:
|
||||
@ -351,6 +475,7 @@ local execution:
|
||||
Then access to the local 23080 port is the 8080 port of access to 22.22.22.33.
|
||||
|
||||
#### **2.3.Common TCP third level proxy**
|
||||

|
||||
TCP first level proxy VPS_01,IP:22.22.22.22
|
||||
`./proxy tcp -p ":38080" -T tcp -P "66.66.66.66:8080" -L 0`
|
||||
TCP second level proxy VPS_02,IP:33.33.33.33
|
||||
@ -360,6 +485,7 @@ TCP third level proxy (local)
|
||||
Then access to the local 8080 port is to access the 8080 port of the 66.66.66.66 by encrypting the TCP tunnel.
|
||||
|
||||
#### **2.4.TCP second level encrypted proxy**
|
||||

|
||||
VPS(IP:22.22.22.33) execute:
|
||||
`./proxy tcp --tls -p ":33080" -T tcp -P "127.0.0.1:8080" -L 0 -C proxy.crt -K proxy.key`
|
||||
local execution:
|
||||
@ -367,6 +493,7 @@ local execution:
|
||||
Then access to the local 23080 port is to access the 8080 port of the 22.22.22.33 by encrypting the TCP tunnel.
|
||||
|
||||
#### **2.5.TCP third level encrypted proxy**
|
||||

|
||||
TCP first level proxy VPS_01,IP:22.22.22.22
|
||||
`./proxy tcp --tls -p ":38080" -T tcp -P "66.66.66.66:8080" -C proxy.crt -K proxy.key`
|
||||
TCP second level proxy VPS_02,IP:33.33.33.33
|
||||
@ -381,11 +508,13 @@ Then access to the local 8080 port is to access the 8080 port of the 66.66.66.66
|
||||
### **3.UDP proxy**
|
||||
|
||||
#### **3.1.Common UDP first level proxy**
|
||||

|
||||
local execution:
|
||||
`./proxy udp -p ":5353" -T udp -P "8.8.8.8:53"`
|
||||
Then access to the local UDP:5353 port is access to the UDP:53 port of the 8.8.8.8.
|
||||
|
||||
#### **3.2.Common UDP second level proxy**
|
||||

|
||||
VPS(IP:22.22.22.33) execute:
|
||||
`./proxy tcp -p ":33080" -T udp -P "8.8.8.8:53"`
|
||||
local execution:
|
||||
@ -393,6 +522,7 @@ local execution:
|
||||
Then access to the local UDP:5353 port is access to the UDP:53 port of the 8.8.8.8 through the TCP tunnel.
|
||||
|
||||
#### **3.3.Common UDP third level proxy**
|
||||

|
||||
TCP first level proxy VPS_01,IP:22.22.22.22
|
||||
`./proxy tcp -p ":38080" -T udp -P "8.8.8.8:53"`
|
||||
TCP second level proxy VPS_02,IP:33.33.33.33
|
||||
@ -402,6 +532,7 @@ TCP third level proxy (local)
|
||||
Then access to the local 5353 port is access to the 53 port of the 8.8.8.8 through the TCP tunnel.
|
||||
|
||||
#### **3.4.UDP second level encrypted proxy**
|
||||

|
||||
VPS(IP:22.22.22.33) execute:
|
||||
`./proxy tcp --tls -p ":33080" -T udp -P "8.8.8.8:53" -C proxy.crt -K proxy.key`
|
||||
local execution:
|
||||
@ -409,6 +540,7 @@ local execution:
|
||||
Then access to the local UDP:5353 port is access to the UDP:53 port of the 8.8.8.8 by the encrypting TCP tunnel.
|
||||
|
||||
#### **3.5.UDP third level encrypted proxy**
|
||||

|
||||
TCP first level proxy VPS_01,IP:22.22.22.22
|
||||
`./proxy tcp --tls -p ":38080" -T udp -P "8.8.8.8:53" -C proxy.crt -K proxy.key`
|
||||
TCP second level proxy VPS_02,IP:33.33.33.33
|
||||
@ -557,7 +689,7 @@ Procedure:
|
||||
#### **4.8.view help**
|
||||
`./proxy help bridge`
|
||||
`./proxy help server`
|
||||
`./proxy help server`
|
||||
`./proxy help client`
|
||||
|
||||
### **5.SOCKS5 proxy**
|
||||
Tips: SOCKS5 proxy, support CONNECT, UDP protocol and don't support BIND and support username password authentication.
|
||||
@ -565,6 +697,7 @@ Tips: SOCKS5 proxy, support CONNECT, UDP protocol and don't support BIND and sup
|
||||
`./proxy socks -t tcp -p "0.0.0.0:38080"`
|
||||
|
||||
#### **5.2.Common SOCKS5 second level proxy**
|
||||

|
||||

|
||||
Using local port 8090, assume that the parent SOCKS5 proxy is `22.22.22.22:8080`
|
||||
`./proxy socks -t tcp -p "0.0.0.0:8090" -T tcp -P "22.22.22.22:8080" `
|
||||
@ -572,6 +705,7 @@ We can also specify the black and white list files of the domain name, one line
|
||||
`./proxy socks -p "0.0.0.0:8090" -T tcp -P "22.22.22.22:8080" -b blocked.txt -d direct.txt`
|
||||
|
||||
#### **5.3.SOCKS second level encrypted proxy**
|
||||

|
||||
SOCKS5 first level proxy(VPS,IP:22.22.22.22)
|
||||
`./proxy socks -t tls -p ":38080" -C proxy.crt -K proxy.key`
|
||||
|
||||
@ -584,6 +718,7 @@ SOCKS5 second level proxy(local windows)
|
||||
Then set up your windows system, the proxy that needs to surf the Internet by proxy is Socks5 mode, the address is: 127.0.0.1, the port is: 8080. the program can surf the Internet through the encrypted channel which is running on VPS.
|
||||
|
||||
#### **5.4.SOCKS third level encrypted proxy**
|
||||

|
||||
SOCKS5 first level proxy VPS_01,IP:22.22.22.22
|
||||
`./proxy socks -t tls -p ":38080" -C proxy.crt -K proxy.key`
|
||||
SOCKS5 second level proxy VPS_02,IP:33.33.33.33
|
||||
@ -597,6 +732,7 @@ By default, proxy will intelligently judge whether a domain name can be accessed
|
||||
`./proxy socks --always -t tls -p ":28080" -T tls -P "22.22.22.22:38080" -C proxy.crt -K proxy.key`
|
||||
|
||||
#### **5.6.Transfer through SSH**
|
||||

|
||||
Explanation: the principle of SSH transfer is to take advantage of SSH's forwarding function, which is, after you connect to SSH, you can access the target address by the SSH.
|
||||
Suppose there is a vps
|
||||
- IP is 2.2.2.2, SSH port is 22, SSH username is user, SSH password is Demo
|
||||
@ -619,7 +755,7 @@ You can also be placed in a file, which is a line, a ‘username: password’, a
|
||||
`./proxy socks -t tcp -p ":33080" -F auth-file.txt`
|
||||
|
||||
In addition, socks5 proxy also integrates external HTTP API authentication, we can specify a http url interface address through the --auth-url parameter,
|
||||
Then when the user is connected, the proxy request this url by get way, with the following four parameters, if the return HTTP status code 204, on behalf of the authentication is successful.
|
||||
Then when the user is connected, the proxy request this url by get way, with the following three parameters, if the return HTTP status code 204, on behalf of the authentication is successful.
|
||||
In other cases, the authentication fails.
|
||||
for example:
|
||||
`./proxy socks -t tcp -p ":33080" --auth-url "http://test.com/auth.php"`
|
||||
@ -633,27 +769,320 @@ ip: user's IP, for example: 192.168.1.200
|
||||
If there is no -a or -F or --auth-url parameters, it means to turn off the authentication.
|
||||
|
||||
#### **5.8.KCP protocol transmission**
|
||||
The KCP protocol requires a -B parameter which can set a password to encrypt and decrypt data.
|
||||
The KCP protocol requires a --kcp-key parameter which can set a password to encrypt and decrypt data.
|
||||
|
||||
HTTP first level proxy(VPS,IP:22.22.22.22)
|
||||
`./proxy socks -t kcp -p ":38080" -B mypassword`
|
||||
`./proxy socks -t kcp -p ":38080" --kcp-key mypassword`
|
||||
|
||||
HTTP two level proxy(local os is Linux)
|
||||
`./proxy socks -t tcp -p ":8080" -T kcp -P "22.22.22.22:38080" -B mypassword`
|
||||
Then access to the local 8080 port is access to the proxy port 38080 on the VPS, and the data is transmitted through the KCP protocol.
|
||||
`./proxy socks -t tcp -p ":8080" -T kcp -P "22.22.22.22:38080" --kcp-key mypassword`
|
||||
Then access to the local 8080 port is access to the proxy port 38080 on the VPS, and the data is transmitted through the KCP protocol.
|
||||
|
||||
#### **5.9.view help**
|
||||
#### **5.9.Custom DNS**
|
||||
--dns-address and --dns-ttl parameters can be used to specify DNS(--dns-address) when you use proxy to access to a domain.
|
||||
they also can specify dns result cache time (--dns-ttl) which unit is second. they can avoid the interference of system DNS to proxy. cache can reduce DNS resolution time and increase access speed.
|
||||
for example:
|
||||
`./proxy socks -p ":33080" --dns-address "8.8.8.8:53" --dns-ttl 300`
|
||||
|
||||
#### **5.10.Custom encryption**
|
||||
HTTP(s) proxy can encrypt TCP data by TLS standard encryption and KCP protocol encryption, in addition to supporting custom encryption after TLS and KCP, That is to say, custom encryption and tls|kcp can be combined to use. The internal AES256 encryption is used, and it only needs to define one password by yourself. Encryption is divided into two parts, the one is whether the local (-z) is encrypted and decrypted, the other is whether the parents (-Z) is encrypted and decrypted.
|
||||
Custom encryption requires both ends are proxy. Next, we use two level example and three level example as examples:
|
||||
|
||||
**two level example**
|
||||
First level VPS (ip:2.2.2.2) execution:
|
||||
`proxy socks -t tcp -z demo_password -p :7777`
|
||||
Local second level execution:
|
||||
`proxy socks -T tcp -P 2.2.2.2:777 -Z demo_password -t tcp -p :8080`
|
||||
through this way, When you visits the website by local proxy 8080, it visits the target website by encryption transmission with the parents proxy.
|
||||
|
||||
**three level example**
|
||||
First level VPS (ip:2.2.2.2) execution:
|
||||
`proxy socks -t tcp -z demo_password -p :7777`
|
||||
Second level VPS (ip:2.2.2.2) execution:
|
||||
`proxy socks -T tcp -P 2.2.2.2:7777 -Z demo_password -t tcp -z other_password -p :8888`
|
||||
Local third level execution:
|
||||
`proxy socks -T tcp -P 3.3.3.3:8888 -Z other_password -t tcp -p :8080`
|
||||
through this way, When you visits the website by local proxy 8080, it visits the target website by encryption transmission with the parents proxy.
|
||||
|
||||
#### **5.11.Compressed transmission**
|
||||
HTTP(s) proxy can encrypt TCP data through TCP standard encryption and KCP protocol encryption, and can also compress data before custom encryption.
|
||||
That is to say, compression and custom encryption and tls|kcp can be used together, compression is divided into two parts, the one is whether the local (-z) is compressed transmission, the other is whether the parents (-Z) is compressed transmission.
|
||||
The compression requires both ends are proxy. Compression also protects the (encryption) data in certain extent. we use two level example and three level example as examples:
|
||||
|
||||
**two level example**
|
||||
First level VPS (ip:2.2.2.2) execution:
|
||||
`proxy socks -t tcp -m -p :7777`
|
||||
Local second level execution:
|
||||
`proxy socks -T tcp -P 2.2.2.2:777 -M -t tcp -p :8080`
|
||||
through this way, When you visits the website by local proxy 8080, it visits the target website by compressed transmission with the parents proxy.
|
||||
|
||||
|
||||
**three level example**
|
||||
First level VPS (ip:2.2.2.2) execution:
|
||||
`proxy socks -t tcp -m -p :7777`
|
||||
Second level VPS (ip:3.3.3.3) execution:
|
||||
`proxy socks -T tcp -P 2.2.2.2:7777 -M -t tcp -m -p :8888`
|
||||
Local third level execution:
|
||||
`proxy socks -T tcp -P 3.3.3.3:8888 -M -t tcp -p :8080`
|
||||
through this way, When you visits the website by local proxy 8080, it visits the target website by compressed transmission with the parents proxy.
|
||||
|
||||
#### **5.12.view help**
|
||||
`./proxy help socks`
|
||||
|
||||
### TODO
|
||||
- Welcome joining group feedback...
|
||||
### **6.Proxy protocol conversion**
|
||||
|
||||
### How to use the source code?
|
||||
use command cd to enter your go SRC directory and then
|
||||
execute `git clone https://github.com/snail007/goproxy.git ./proxy`
|
||||
Direct compilation: `go build`
|
||||
execution: `go run *.go`
|
||||
`utils` is a toolkit, and `service` is a specific service class.
|
||||
#### **6.1.Functional introduction**
|
||||
The proxy protocol conversion use the SPS subcommand (abbreviation of socks+https), SPS itself does not provide the proxy function, just accept the proxy request and then converse protocol and forwarded to the existing HTTP (s) or Socks5 proxy. SPS can use existing HTTP (s) or Socks5 proxy converse to support HTTP (s) and Socks5 HTTP (s) proxy at the same time by one port, and proxy supports forward and reverse proxy (SNI), SOCKS5 proxy which is also does support UDP when parent is Socks5. in addition to the existing HTTP or Socks5 proxy, which supports TLS, TCP, KCP three modes and chain-style connection. That is more than one SPS node connection can build encryption channel.
|
||||
|
||||
#### **6.2.HTTP(S) to HTTP(S) + SOCKS5**
|
||||
Suppose there is a common HTTP (s) proxy: 127.0.0.1:8080. Now we turn it into a common proxy that supports HTTP (s) and Socks5 at the same time. The local port after transformation is 18080.
|
||||
command:
|
||||
`./proxy sps -S http -T tcp -P 127.0.0.1:8080 -t tcp -p :18080`
|
||||
|
||||
Suppose that there is a TLS HTTP (s) proxy: 127.0.0.1:8080. Now we turn it into a common proxy that supports HTTP (s) and Socks5 at the same time. The local port after transformation is 18080, TLS needs certificate file.
|
||||
command:
|
||||
`./proxy sps -S http -T tls -P 127.0.0.1:8080 -t tcp -p :18080 -C proxy.crt -K proxy.key`
|
||||
|
||||
Suppose there is a KCP HTTP (s) proxy (password: demo123): 127.0.0.1:8080. Now we turn it into a common proxy that supports HTTP (s) and Socks5 at the same time. The local port after transformation is 18080.
|
||||
command:
|
||||
`./proxy sps -S http -T kcp -P 127.0.0.1:8080 -t tcp -p :18080 --kcp-key demo123`
|
||||
|
||||
#### **6.3.SOCKS5 to HTTP(S) + SOCKS5**
|
||||
Suppose there is a common Socks5 proxy: 127.0.0.1:8080, now we turn it into a common proxy that supports HTTP (s) and Socks5 at the same time, and the local port after transformation is 18080.
|
||||
command:
|
||||
`./proxy sps -S socks -T tcp -P 127.0.0.1:8080 -t tcp -p :18080`
|
||||
|
||||
Suppose there is a TLS Socks5 proxy: 127.0.0.1:8080. Now we turn it into a common proxy that support HTTP (s) and Socks5 at the same time. The local port after transformation is 18080, TLS needs certificate file.
|
||||
command:
|
||||
`./proxy sps -S socks -T tls -P 127.0.0.1:8080 -t tcp -p :18080 -C proxy.crt -K proxy.key`
|
||||
|
||||
Suppose there is a KCP Socks5 proxy (password: demo123): 127.0.0.1:8080, now we turn it into a common proxy that support HTTP (s) and Socks5 at the same time, and the local port after transformation is 18080.
|
||||
command:
|
||||
`./proxy sps -S socks -T kcp -P 127.0.0.1:8080 -t tcp -p :18080 --kcp-key demo123`
|
||||
|
||||
#### **6.4.Chain style connection**
|
||||

|
||||
It is mentioned above that multiple SPS nodes can be connected to build encrypted channels, assuming you have the following VPS and a PC.
|
||||
vps01:2.2.2.2
|
||||
vps02:3.3.3.3
|
||||
Now we want to use PC and vps01 and vps02 to build an encrypted channel. In this example, TLS is used. KCP also supports encryption in addition to TLS. and accessing to local 18080 port on PC is accessing to the local 8080 ports of vps01.
|
||||
First, on vps01 (2.2.2.2), we run a HTTP (s) proxy that only can be accessed locally,excute:
|
||||
`./proxy -t tcp -p 127.0.0.1:8080`
|
||||
|
||||
Then run a SPS node on vps01 (2.2.2.2),excute:
|
||||
`./proxy -S http -T tcp -P 127.0.0.1:8080 -t tls -p :8081 -C proxy.crt -K proxy.key`
|
||||
|
||||
Then run a SPS node on vps02 (3.3.3.3),excute:
|
||||
`./proxy -S http -T tls -P 2.2.2.2:8081 -t tls -p :8082 -C proxy.crt -K proxy.key`
|
||||
|
||||
Then run a SPS node on the PC,excute:
|
||||
`./proxy -S http -T tls -P 3.3.3.3:8082 -t tcp -p :18080 -C proxy.crt -K proxy.key`
|
||||
|
||||
finish。
|
||||
|
||||
#### **6.5.Listening on multiple ports**
|
||||
In general, listening one port is enough, but if you need to monitor 80 and 443 ports at the same time as a reverse proxy, the -p parameter can support it.
|
||||
The format is:`-p 0.0.0.0:80,0.0.0.0:443`, Multiple bindings are separated by a comma.
|
||||
|
||||
#### **6.6.Authentication**
|
||||
SPS supports HTTP(s)\socks5 proxy authentication, which can concatenate authentication, there are four important information:
|
||||
1:Users send authentication information`user-auth`。
|
||||
2:Local authentication information set up`local-auth`。
|
||||
3:Set the authentication information accessing to the father proxy`parent-auth`。
|
||||
4:The final authentication information sent to the father proxy`auth-info-to-parent`。
|
||||
The relationship between them is as follows:
|
||||
|
||||
| user-auth | local-auth | parent-auth | auth-info-to-paren
|
||||
| ------ | ------ | ------ | ------
|
||||
| yes/no | yes | yes | come from parent-auth
|
||||
| yes/no | no | yes | come from parent-auth
|
||||
| yes/no | yes | no | no
|
||||
| no | no | no | no
|
||||
| yes | no | no | come from user-auth
|
||||
|
||||
For SPS proxy we can have username and password to authenticate, and the authentication username and password can be specified on the command line
|
||||
`./proxy sps -S http -T tcp -P 127.0.0.1:8080 -t tcp -p ":33080" -a "user1:pass1" -a "user2:pass2"`
|
||||
if there are multiple users, repeat the -a parameters.
|
||||
It can also be placed in a file, which is a line to a username: password, and then specified in -F parameter.
|
||||
`./proxy sps -S http -T tcp -P 127.0.0.1:8080 -t tcp -p ":33080" -F auth-file.txt`
|
||||
|
||||
If the father proxy is authenticated, the lower level can set the authentication information through the -A parameters, such as:
|
||||
father proxy:`./proxy sps -S http -T tcp -P 127.0.0.1:8080 -t tcp -p ":33080" -a "user1:pass1" -a "user2:pass2"`
|
||||
local proxy:`./proxy sps -S http -T tcp -P 127.0.0.1:8080 -A "user1:pass1" -t tcp -p ":33080" `
|
||||
|
||||
In addition, SPS proxy, local authentication is integrated with external HTTP API authentication, and we can specify a HTTP URL interface address through the --auth-url parameter,
|
||||
Then, when there is a user connection, proxy will request this URL by GET way, with the following four parameters, and if the HTTP state code 204 is returned, the authentication is successful.
|
||||
Other cases consider authentication failure.
|
||||
for example:
|
||||
`./proxy sps -S http -T tcp -P 127.0.0.1:8080 -t tcp -p ":33080" --auth-url "http://test.com/auth.php"`
|
||||
When the user is connected, proxy will request this URL by GET way("http://test.com/auth.php"),
|
||||
Four parameters with user, pass, IP, and target:
|
||||
http://test.com/auth.php?user={USER}&pass={PASS}&ip={IP}&target={TARGET}
|
||||
user:username
|
||||
pass:password
|
||||
ip:user's ip,for example:192.168.1.200
|
||||
target: if the client is the HTTP (s) proxy request, this represents the complete URL of the request, and the other cases are empty.
|
||||
|
||||
If there is no -a or -F or --auth-url parameters, local authentication is closed.
|
||||
If there is no -A parameter, the connection to the father proxy does not use authentication.
|
||||
|
||||
#### **6.7 Custom encryption**
|
||||
HTTP(s) proxy can encrypt TCP data by TLS standard encryption and KCP protocol encryption, in addition to supporting custom encryption after TLS and KCP, That is to say, custom encryption and tls|kcp can be combined to use. The internal AES256 encryption is used, and it only needs to define one password by yourself. Encryption is divided into two parts, the one is whether the local (-z) is encrypted and decrypted, the other is whether the parents (-Z) is encrypted and decrypted.
|
||||
Custom encryption requires both ends are proxy. Next, we use two level example and three level example as examples:
|
||||
Suppose there is already a HTTP (s) proxy:`6.6.6.6:6666`
|
||||
|
||||
**two level example**
|
||||
First level VPS (ip:2.2.2.2) execution:
|
||||
`proxy sps -S http -T tcp -P 6.6.6.6:6666 -t tcp -z demo_password -p :7777`
|
||||
Local second level execution:
|
||||
`proxy sps -T tcp -P 2.2.2.2:777 -Z demo_password -t tcp -p :8080`
|
||||
through this way, When you visits the website by local proxy 8080, it visits the target website by encryption transmission with the parents proxy.
|
||||
|
||||
**three level example**
|
||||
First level VPS (ip:2.2.2.2) execution:
|
||||
`proxy sps -S http -T tcp -P 6.6.6.6:6666 -t tcp -z demo_password -p :7777`
|
||||
Second level VPS (ip:2.2.2.2) execution:
|
||||
`proxy sps -T tcp -P 2.2.2.2:7777 -Z demo_password -t tcp -z other_password -p :8888`
|
||||
Local third level execution:
|
||||
`proxy sps -T tcp -P 3.3.3.3:8888 -Z other_password -t tcp -p :8080`
|
||||
through this way, When you visits the website by local proxy 8080, it visits the target website by encryption transmission with the parents proxy.
|
||||
|
||||
#### **6.8 Compressed transmission**
|
||||
HTTP(s) proxy can encrypt TCP data through TCP standard encryption and KCP protocol encryption, and can also compress data before custom encryption.
|
||||
That is to say, compression and custom encryption and tls|kcp can be used together, compression is divided into two parts, the one is whether the local (-z) is compressed transmission, the other is whether the parents (-Z) is compressed transmission.
|
||||
The compression requires both ends are proxy. Compression also protects the (encryption) data in certain extent. we use two level example and three level example as examples:
|
||||
|
||||
**two level example**
|
||||
First level VPS (ip:2.2.2.2) execution:
|
||||
`proxy sps -t tcp -m -p :7777`
|
||||
Local second level execution:
|
||||
`proxy sps -T tcp -P 2.2.2.2:777 -M -t tcp -p :8080`
|
||||
through this way, When you visits the website by local proxy 8080, it visits the target website by compressed transmission with the parents proxy.
|
||||
|
||||
**three level example**
|
||||
First level VPS (ip:2.2.2.2) execution:
|
||||
`proxy sps -t tcp -m -p :7777`
|
||||
Second level VPS (ip:3.3.3.3) execution::
|
||||
`proxy sps -T tcp -P 2.2.2.2:7777 -M -t tcp -m -p :8888`
|
||||
Local third level execution:
|
||||
`proxy sps -T tcp -P 3.3.3.3:8888 -M -t tcp -p :8080`
|
||||
through this way, When you visits the website by local proxy 8080, it visits the target website by compressed transmission with the parents proxy.
|
||||
|
||||
#### **6.9.view help**
|
||||
`./proxy help sps`
|
||||
|
||||
### **7.KCP Configuration**
|
||||
|
||||
#### **7.1.Configuration introduction**
|
||||
Many functions of the proxy support the KCP protocol, and all the functions that can use the KCP protocol support the configuration parameters introduced here.
|
||||
So here is a unified introduction to the KCP configuration parameters.
|
||||
|
||||
#### **7.2.Configuration details**
|
||||
The number of KCP configuration parameters is 17, you don't have to set up them. they all have the default value, if for the best effect,
|
||||
You need to configure the parameters according to your own network conditions. Due to the complexity of KCP configuration, a certain network basic knowledge is required,
|
||||
If you want to get a more detailed configuration and explanation of the KCP parameters, search for yourself. The command line name for each parameter, as well as the default and simple functions, are described as follows:
|
||||
```
|
||||
--kcp-key="secrect" pre-shared secret between client and server
|
||||
--kcp-method="aes" encrypt/decrypt method, can be: aes, aes-128, aes-192, salsa20, blowfish,
|
||||
twofish, cast5, 3des, tea, xtea, xor, sm4, none
|
||||
--kcp-mode="secrect" profiles: fast3, fast2, fast, normal, manual
|
||||
--kcp-mtu=1350 set maximum transmission unit for UDP packets
|
||||
--kcp-sndwnd=1024 set send window size(num of packets)
|
||||
--kcp-rcvwnd=1024 set receive window size(num of packets)
|
||||
--kcp-ds=10 set reed-solomon erasure coding - datashard
|
||||
--kcp-ps=3 set reed-solomon erasure coding - parityshard
|
||||
--kcp-dscp=0 set DSCP(6bit)
|
||||
--kcp-nocomp disable compression
|
||||
--kcp-acknodelay be carefull! flush ack immediately when a packet is received
|
||||
--kcp-nodelay=0 be carefull!
|
||||
--kcp-interval=50 be carefull!
|
||||
--kcp-resend=0 be carefull!
|
||||
--kcp-nc=0 be carefull! no congestion
|
||||
--kcp-sockbuf=4194304 be carefull!
|
||||
--kcp-keepalive=10 be carefull!
|
||||
```
|
||||
|
||||
### **8.DNS anti pollution server**
|
||||
|
||||
#### **8.1.Introduction**
|
||||
It is well known that DNS is a service which use UDP protocol and 53 port,But with the development of network, some well-known DNS servers also support TCP protocol's DNS query,such as google's 8.8.8.8,Proxy's DNS anti pollution server theory is starting a local DNS proxy server,It uses TCP to conduct DNS queries through father proxy. If it encrypted communicate with father proxy,Then you can make a safe and pollution-free DNS analysis.
|
||||
|
||||
#### **8.2.Use examples**
|
||||
|
||||
***8.2.1 common HTTP(S) father proxy***
|
||||
Suppose there is a father proxy:2.2.2.2:33080
|
||||
local execution:
|
||||
`proxy dns -S http -T tcp -P 2.2.2.2:33080 -p :53`
|
||||
Then the local UDP port 53 provides the DNS analysis.
|
||||
|
||||
***8.2.2 common SOCKS5 father proxy***
|
||||
Suppose there is a father proxy:2.2.2.2:33080
|
||||
local execution:
|
||||
`proxy dns -S socks -T tcp -P 2.2.2.2:33080 -p :53`
|
||||
Then the local UDP port 53 provides the DNS analysis.
|
||||
|
||||
***8.2.3 TLS encrypted HTTP(S) father proxy***
|
||||
Suppose there is a father proxy:2.2.2.2:33080
|
||||
The orders executed by father proxy:
|
||||
`proxy http -t tls -C proxy.crt -K proxy.key -p :33080`
|
||||
local execution:
|
||||
`proxy dns -S http -T tls -P 2.2.2.2:33080 -C proxy.crt -K proxy.key -p :53`
|
||||
Then the local UDP port 53 provides a security and anti pollution DNS analysis.
|
||||
|
||||
***8.2.4 TLS encrypted SOCKS5 father proxy***
|
||||
Suppose there is a father proxy:2.2.2.2:33080
|
||||
The orders executed by father proxy:
|
||||
`proxy socks -t tls -C proxy.crt -K proxy.key -p :33080`
|
||||
local execution:
|
||||
`proxy dns -S socks -T tls -P 2.2.2.2:33080 -C proxy.crt -K proxy.key -p :53`
|
||||
Then the local UDP port 53 provides a security and anti pollution DNS analysis.
|
||||
|
||||
***8.2.5 KCP encrypted HTTP(S) father proxy***
|
||||
Suppose there is a father proxy:2.2.2.2:33080
|
||||
The orders executed by father proxy:
|
||||
`proxy http -t kcp -p :33080`
|
||||
local execution:
|
||||
`proxy dns -S http -T kcp -P 2.2.2.2:33080 -p :53`
|
||||
Then the local UDP port 53 provides a security and anti pollution DNS analysis.
|
||||
|
||||
***8.2.6 KCP encrypted SOCKS5 father proxy***
|
||||
Suppose there is a father proxy:2.2.2.2:33080
|
||||
The orders executed by father proxy:
|
||||
`proxy socks -t kcp -p :33080`
|
||||
local execution:
|
||||
`proxy dns -S socks -T kcp -P 2.2.2.2:33080 -p :53`
|
||||
Then the local UDP port 53 provides a security and anti pollution DNS analysis.
|
||||
|
||||
***8.2.7 Custom encrypted HTTP(S) father proxy***
|
||||
Suppose there is a father proxy:2.2.2.2:33080
|
||||
The orders executed by father proxy:
|
||||
`proxy http -t tcp -p :33080 -z password`
|
||||
local execution:
|
||||
`proxy dns -S http -T tcp -Z password -P 2.2.2.2:33080 -p :53`
|
||||
Then the local UDP port 53 provides a security and anti pollution DNS analysis.
|
||||
|
||||
***8.2.8 Custom encrypted SOCKS5 father proxy***
|
||||
Suppose there is a father proxy:2.2.2.2:33080
|
||||
The orders executed by father proxy:
|
||||
`proxy socks -t kcp -p :33080 -z password`
|
||||
local execution:
|
||||
`proxy dns -S socks -T tcp -Z password -P 2.2.2.2:33080 -p :53`
|
||||
Then the local UDP port 53 provides a security and anti pollution DNS analysis.
|
||||
|
||||
### TODO
|
||||
- HTTP, socks proxy which has multi parents proxy load balancing?
|
||||
- HTTP (s) proxy support PAC?
|
||||
- Welcome joining group feedback...
|
||||
|
||||
### How to use the source code?
|
||||
|
||||
Recommend go1.10.1.
|
||||
`go get github.com/snail007/goproxy`
|
||||
use command cd to enter your go SRC directory
|
||||
then cd to enter `github.com/snail007/goproxy`.
|
||||
Direct compilation:`go build -o proxy`
|
||||
execution: `go run *.go`
|
||||
`utils` is a toolkit, and `service` is a specific service class.
|
||||
|
||||
### License
|
||||
Proxy is licensed under GPLv3 license.
|
||||
|
||||
643
README_ZH.md
@ -1,5 +1,5 @@
|
||||
<img src="https://github.com/snail007/goproxy/blob/master/docs/images/logo.jpg?raw=true" width="200"/>
|
||||
Proxy是golang实现的高性能http,https,websocket,tcp,udp,socks5代理服务器,支持正向代理、反向代理、透明代理、内网穿透、TCP/UDP端口映射、SSH中转,TLS加密传输。
|
||||
Proxy是golang实现的高性能http,https,websocket,tcp,udp,socks5代理服务器,支持正向代理、反向代理、透明代理、内网穿透、TCP/UDP端口映射、SSH中转、TLS加密传输、协议转换、防污染DNS代理。
|
||||
|
||||
[点击下载](https://github.com/snail007/goproxy/releases) 官方QQ交流群:189618940
|
||||
|
||||
@ -7,7 +7,17 @@ Proxy是golang实现的高性能http,https,websocket,tcp,udp,socks5代理服务
|
||||
|
||||
[](https://github.com/snail007/goproxy/) []() [](https://github.com/snail007/goproxy/releases) [](https://github.com/snail007/goproxy/releases)
|
||||
|
||||
[English Manual](/README.md)
|
||||
**[English Manual](/README.md)**
|
||||
|
||||
**[全平台图形界面版本](/gui/README.md)**
|
||||
|
||||
**[全平台SDK](/sdk/README.md)**
|
||||
|
||||
### 如何贡献代码(Pull Request)?
|
||||
|
||||
欢迎加入一起发展壮大proxy.首先需要clone本项目到自己的帐号下面,
|
||||
然后在dev分支上面修改代码,最后发Pull Request到goproxy项目的dev分支即可,
|
||||
为了高效贡献代码,pr的时候需要说明做了什么变更,原因是什么.
|
||||
|
||||
### Features
|
||||
- 链式代理,程序本身可以作为一级代理,如果设置了上级代理那么可以作为二级代理,乃至N级代理.
|
||||
@ -23,6 +33,10 @@ Proxy是golang实现的高性能http,https,websocket,tcp,udp,socks5代理服务
|
||||
- 集成外部API,HTTP(S),SOCKS5代理认证功能可以与外部HTTP API集成,可以方便的通过外部系统控制代理用户.
|
||||
- 反向代理,支持直接把域名解析到proxy监听的ip,然后proxy就会帮你代理访问需要访问的HTTP(S)网站.
|
||||
- 透明HTTP(S)代理,配合iptables,在网关直接把出去的80,443方向的流量转发到proxy,就能实现无感知的智能路由器代理.
|
||||
- 协议转换,可以把已经存在的HTTP(S)或SOCKS5代理转换为一个端口同时支持HTTP(S)和SOCKS5代理,转换后的SOCKS5代理不支持UDP功能,同时支持强大的级联认证功能。
|
||||
- 自定义底层加密传输,http(s)\sps\socks代理在tcp之上可以通过tls标准加密以及kcp协议加密tcp数据,除此之外还支持在tls和kcp之后进行自定义加密,也就是说自定义加密和tls|kcp是可以联合使用的,内部采用AES256加密,使用的时候只需要自己定义一个密码即可。
|
||||
- 底层压缩高效传输,http(s)\sps\socks代理在tcp之上可以通过自定义加密和tls标准加密以及kcp协议加密tcp数据,在加密之后还可以对数据进行压缩,也就是说压缩功能和自定义加密和tls|kcp是可以联合使用的。
|
||||
- 安全的DNS代理,可以通过本地的proxy提供的DNS代理服务器与上级代理加密通讯实现安全防污染的DNS查询。
|
||||
|
||||
### Why need these?
|
||||
- 当由于某某原因,我们不能访问我们在其它地方的服务,我们可以通过多个相连的proxy节点建立起一个安全的隧道访问我们的服务.
|
||||
@ -34,18 +48,8 @@ Proxy是golang实现的高性能http,https,websocket,tcp,udp,socks5代理服务
|
||||
- ...
|
||||
|
||||
|
||||
本页是v4.2手册,其他版本手册请点击下面链接查看.
|
||||
- [v4.0-v4.1手册](https://github.com/snail007/goproxy/tree/v4.1)
|
||||
- [v3.9手册](https://github.com/snail007/goproxy/tree/v3.9)
|
||||
- [v3.8手册](https://github.com/snail007/goproxy/tree/v3.8)
|
||||
- [v3.6-v3.7手册](https://github.com/snail007/goproxy/tree/v3.6)
|
||||
- [v3.5手册](https://github.com/snail007/goproxy/tree/v3.5)
|
||||
- [v3.4手册](https://github.com/snail007/goproxy/tree/v3.4)
|
||||
- [v3.3手册](https://github.com/snail007/goproxy/tree/v3.3)
|
||||
- [v3.2手册](https://github.com/snail007/goproxy/tree/v3.2)
|
||||
- [v3.1手册](https://github.com/snail007/goproxy/tree/v3.1)
|
||||
- [v3.0手册](https://github.com/snail007/goproxy/tree/v3.0)
|
||||
- [v2.x手册](https://github.com/snail007/goproxy/tree/v2.2)
|
||||
本页是v5.4手册,其他版本手册请点击[这里](docs/old-release.md)查看.
|
||||
|
||||
|
||||
### 怎么找到组织?
|
||||
[点击加入交流组织gitter](https://gitter.im/go-proxy/Lobby?utm_source=share-link&utm_medium=link&utm_campaign=share-link)
|
||||
@ -53,6 +57,7 @@ Proxy是golang实现的高性能http,https,websocket,tcp,udp,socks5代理服务
|
||||
### 安装
|
||||
1. [快速安装](#自动安装)
|
||||
1. [手动安装](#手动安装)
|
||||
1. [Docker安装](#docker安装)
|
||||
|
||||
### 首次使用必看
|
||||
- [环境](#首次使用必看-1)
|
||||
@ -78,15 +83,19 @@ Proxy是golang实现的高性能http,https,websocket,tcp,udp,socks5代理服务
|
||||
- [1.8 KCP协议传输](#18kcp协议传输)
|
||||
- [1.9 HTTP(S)反向代理](#19-https反向代理)
|
||||
- [1.10 HTTP(S)透明代理](#110-https透明代理)
|
||||
- [1.11 查看帮助](#111查看帮助)
|
||||
- [2. TCP代理](#2tcp代理)
|
||||
- [1.11 自定义DNS](#111-自定义dns)
|
||||
- [1.12 自定义加密](#112-自定义加密)
|
||||
- [1.13 压缩传输](#113-压缩传输)
|
||||
- [1.14 查看帮助](#114-查看帮助)
|
||||
- [2. TCP代理(端口映射)](#2tcp代理)
|
||||
- [2.1 普通一级TCP代理](#21普通一级tcp代理)
|
||||
- [2.2 普通二级TCP代理](#22普通二级tcp代理)
|
||||
- [2.3 普通三级TCP代理](#23普通三级tcp代理)
|
||||
- [2.4 加密二级TCP代理](#24加密二级tcp代理)
|
||||
- [2.5 加密三级TCP代理](#25加密三级tcp代理)
|
||||
- [2.6 查看帮助](#26查看帮助)
|
||||
- [3. UDP代理](#3udp代理)
|
||||
- [2.6 通过代理连接上级](#26通过代理连接上级)
|
||||
- [2.7 查看帮助](#27查看帮助)
|
||||
- [3. UDP代理(端口映射)](#3udp代理)
|
||||
- [3.1 普通一级UDP代理](#31普通一级udp代理)
|
||||
- [3.2 普通二级UDP代理](#32普通二级udp代理)
|
||||
- [3.3 普通三级UDP代理](#33普通三级udp代理)
|
||||
@ -101,7 +110,8 @@ Proxy是golang实现的高性能http,https,websocket,tcp,udp,socks5代理服务
|
||||
- [4.5 高级用法一](#45高级用法一)
|
||||
- [4.6 高级用法一](#46高级用法二)
|
||||
- [4.7 server的-r参数](#47server的-r参数)
|
||||
- [4.8 查看帮助](#48查看帮助)
|
||||
- [4.8 server和client通过代理连接bridge](#48server和client通过代理连接bridge)
|
||||
- [4.9 查看帮助](#49查看帮助)
|
||||
- [5. SOCKS5代理](#5socks5代理)
|
||||
- [5.1 普通SOCKS5代理](#51普通socks5代理)
|
||||
- [5.2 普通二级SOCKS5代理](#52普通二级socks5代理)
|
||||
@ -113,7 +123,27 @@ Proxy是golang实现的高性能http,https,websocket,tcp,udp,socks5代理服务
|
||||
- [5.6.2 用户名和密钥的方式](#562-ssh用户名和密钥的方式)
|
||||
- [5.7 认证](#57认证)
|
||||
- [5.8 KCP协议传输](#58kcp协议传输)
|
||||
- [5.9 查看帮助](#59查看帮助)
|
||||
- [5.9 自定义DNS](#59自定义dns)
|
||||
- [5.10 自定义加密](#510-自定义加密)
|
||||
- [5.11 压缩传输](#511-压缩传输)
|
||||
- [5.12 查看帮助](#512查看帮助)
|
||||
- [6. 代理协议转换](#6代理协议转换)
|
||||
- [6.1 功能介绍](#61-功能介绍)
|
||||
- [6.2 HTTP(S)转HTTP(S)+SOCKS5](#62-https转httpssocks5)
|
||||
- [6.3 SOCKS5转HTTP(S)+SOCKS5](#63-socks5转httpssocks5)
|
||||
- [6.4 链式连接](#64-链式连接)
|
||||
- [6.5 监听多个端口](#65-监听多个端口)
|
||||
- [6.6 认证功能](#66-认证功能)
|
||||
- [6.7 自定义加密](#67-自定义加密)
|
||||
- [6.8 压缩传输](#68-压缩传输)
|
||||
- [6.9 禁用协议](#69-禁用协议)
|
||||
- [6.10 查看帮助](#610-查看帮助)
|
||||
- [7. KCP配置](#7kcp配置)
|
||||
- [7.1 配置介绍](#71-配置介绍)
|
||||
- [7.2 详细配置](#72-详细配置)
|
||||
- [8. DNS防污染服务器](#8dns防污染服务器)
|
||||
- [8.1 介绍](#81-介绍)
|
||||
- [8.2 使用示例](#82-使用示例)
|
||||
|
||||
### Fast Start
|
||||
提示:所有操作需要root权限.
|
||||
@ -131,7 +161,7 @@ curl -L https://raw.githubusercontent.com/snail007/goproxy/master/install_auto.s
|
||||
下载地址:https://github.com/snail007/goproxy/releases
|
||||
```shell
|
||||
cd /root/proxy/
|
||||
wget https://github.com/snail007/goproxy/releases/download/v4.2/proxy-linux-amd64.tar.gz
|
||||
wget https://github.com/snail007/goproxy/releases/download/v5.4/proxy-linux-amd64.tar.gz
|
||||
```
|
||||
#### **2.下载自动安装脚本**
|
||||
```shell
|
||||
@ -140,7 +170,37 @@ wget https://raw.githubusercontent.com/snail007/goproxy/master/install.sh
|
||||
chmod +x install.sh
|
||||
./install.sh
|
||||
```
|
||||
|
||||
|
||||
#### Docker安装
|
||||
项目根目录的Dockerfile文件用来构建,使用golang 1.10.3,构建基于goproxy的master分支最新版本,
|
||||
全部大小17.3MB,默认情况下使用master分支,不过可以通过修改配置文件Dockerfile
|
||||
或者使用参数GOPROXY_VERSION指定构建的goproxy版本.
|
||||
|
||||
```
|
||||
ARG GOPROXY_VERSION=v5.3
|
||||
```
|
||||
|
||||
步骤:
|
||||
1. 克隆仓库,然后cd进入仓库文件夹,执行:
|
||||
```
|
||||
sudo docker build .
|
||||
```
|
||||
2. 镜像打标签:
|
||||
```
|
||||
sudo docker tag <上一步的结果ID> snail007/goproxy:latest
|
||||
```
|
||||
3. 运行
|
||||
参数OPTS的值就是传递给proxy的所有参数
|
||||
比如下面的例子启动了一个http服务:
|
||||
|
||||
```
|
||||
sudo docker run -d --restart=always --name goproxy -e OPTS="http -p :33080" -p 33080:33080 snail007/goproxy:latest
|
||||
```
|
||||
4. 查看日志:
|
||||
```
|
||||
sudo docker logs -f goproxy
|
||||
```
|
||||
|
||||
## **首次使用必看**
|
||||
|
||||
### **环境**
|
||||
@ -169,10 +229,19 @@ http
|
||||
|
||||
### **生成加密通讯需要的证书文件**
|
||||
http,tcp,udp代理过程会和上级通讯,为了安全我们采用加密通讯,当然可以选择不加密通信通讯,本教程所有和上级通讯都采用加密,需要证书文件.
|
||||
在linux上并安装了openssl命令,可以直接通过下面的命令生成证书和key文件.
|
||||
`./proxy keygen`
|
||||
默认会在当前程序目录下面生成证书文件proxy.crt和key文件proxy.key。
|
||||
|
||||
|
||||
1.通过下面的命令生成自签名的证书和key文件.
|
||||
`./proxy keygen -C proxy`
|
||||
会在当前程序目录下面生成证书文件proxy.crt和key文件proxy.key。
|
||||
|
||||
2.通过下面的命令生,使用自签名证书proxy.crt和key文件proxy.key签发新证书:goproxy.crt和goproxy.key.
|
||||
`./proxy keygen -s -C proxy -c goproxy`
|
||||
会在当前程序目录下面生成证书文件goproxy.crt和key文件goproxy.key。
|
||||
|
||||
3.默认情况下证书的里面的域名是随机的,可以使用`-n test.com`参数指定.
|
||||
|
||||
4.更多用法:`proxy keygen --help`。
|
||||
|
||||
### **后台运行**
|
||||
默认执行proxy之后,如果要保持proxy运行,不能关闭命令行.
|
||||
如果想在后台运行proxy,命令行可以关闭,只需要在命令最后加上--daemon参数即可.
|
||||
@ -192,20 +261,21 @@ proxy会fork子进程,然后监控子进程,如果子进程异常退出,5秒后
|
||||
`./proxy http -g "23.23.23.23"`
|
||||
|
||||
### **1.HTTP代理**
|
||||
#### **1.1.普通HTTP代理**
|
||||

|
||||
#### **1.1.普通一级HTTP代理**
|
||||

|
||||
`./proxy http -t tcp -p "0.0.0.0:38080"`
|
||||
|
||||
#### **1.2.普通二级HTTP代理**
|
||||

|
||||
使用本地端口8090,假设上级HTTP代理是`22.22.22.22:8080`
|
||||
`./proxy http -t tcp -p "0.0.0.0:8090" -T tcp -P "22.22.22.22:8080" `
|
||||
默认关闭了连接池,如果要加快访问速度,-L可以开启连接池,10就是连接池大小,0为关闭,
|
||||
开启连接池在网络不好的情况下,稳定不是很好.
|
||||
`./proxy http -t tcp -p "0.0.0.0:8090" -T tcp -P "22.22.22.22:8080" -L 10`
|
||||
我们还可以指定网站域名的黑白名单文件,一行一个域名,匹配规则是最右匹配,比如:baidu.com,匹配的是*.*.baidu.com,黑名单的域名域名直接走上级代理,白名单的域名不走上级代理.
|
||||
我们还可以指定网站域名的黑白名单文件,一行一个域名,匹配规则是最右匹配,比如:baidu.com,匹配的是*.*.baidu.com,黑名单的域名直接走上级代理,白名单的域名不走上级代理.
|
||||
`./proxy http -p "0.0.0.0:8090" -T tcp -P "22.22.22.22:8080" -b blocked.txt -d direct.txt`
|
||||
|
||||
#### **1.3.HTTP二级代理(加密)**
|
||||
> 注意: 后面二级代理使用的`proxy.crt`和`proxy.key`应与一级代理一致
|
||||
|
||||

|
||||
一级HTTP代理(VPS,IP:22.22.22.22)
|
||||
`./proxy http -t tls -p ":38080" -C proxy.crt -K proxy.key`
|
||||
|
||||
@ -218,6 +288,7 @@ proxy会fork子进程,然后监控子进程,如果子进程异常退出,5秒后
|
||||
然后设置你的windos系统中,需要通过代理上网的程序的代理为http模式,地址为:127.0.0.1,端口为:8080,程序即可通过加密通道通过vps上网。
|
||||
|
||||
#### **1.4.HTTP三级代理(加密)**
|
||||

|
||||
一级HTTP代理VPS_01,IP:22.22.22.22
|
||||
`./proxy http -t tls -p ":38080" -C proxy.crt -K proxy.key`
|
||||
二级HTTP代理VPS_02,IP:33.33.33.33
|
||||
@ -253,6 +324,7 @@ target:用户访问的URL,比如:http://demo.com:80/1.html或https://www.baidu.c
|
||||
`./proxy http --always -t tls -p ":28080" -T tls -P "22.22.22.22:38080" -C proxy.crt -K proxy.key`
|
||||
|
||||
#### **1.7.HTTP(S)通过SSH中转**
|
||||

|
||||
说明:ssh中转的原理是利用了ssh的转发功能,就是你连接上ssh之后,可以通过ssh代理访问目标地址.
|
||||
假设有:vps
|
||||
- IP是2.2.2.2, ssh端口是22, ssh用户名是:user, ssh用户密码是:demo
|
||||
@ -266,16 +338,18 @@ target:用户访问的URL,比如:http://demo.com:80/1.html或https://www.baidu.c
|
||||
`./proxy http -T ssh -P "2.2.2.2:22" -u user -S user.key -t tcp -p ":28080"`
|
||||
|
||||
#### **1.8.KCP协议传输**
|
||||
KCP协议需要-B参数设置一个密码用于加密解密数据
|
||||

|
||||
KCP协议需要--kcp-key参数设置一个密码用于加密解密数据
|
||||
|
||||
一级HTTP代理(VPS,IP:22.22.22.22)
|
||||
`./proxy http -t kcp -p ":38080" -B mypassword`
|
||||
`./proxy http -t kcp -p ":38080" --kcp-key mypassword`
|
||||
|
||||
二级HTTP代理(本地Linux)
|
||||
`./proxy http -t tcp -p ":8080" -T kcp -P "22.22.22.22:38080" -B mypassword`
|
||||
那么访问本地的8080端口就是访问VPS上面的代理端口38080,数据通过kcp协议传输.
|
||||
`./proxy http -t tcp -p ":8080" -T kcp -P "22.22.22.22:38080" --kcp-key mypassword`
|
||||
那么访问本地的8080端口就是访问VPS上面的代理端口38080,数据通过kcp协议传输,注意kcp走的是udp协议协议,所以防火墙需放开38080的udp协议.
|
||||
|
||||
#### **1.9 HTTP(S)反向代理**
|
||||
#### **1.9 HTTP(S)反向代理**
|
||||

|
||||
proxy不仅支持在其他软件里面通过设置代理的方式,为其他软件提供代理服务,而且支持直接把请求的网站域名解析到proxy监听的ip上,然后proxy监听80和443端口,那么proxy就会自动为你代理访问需要访问的HTTP(S)网站.
|
||||
|
||||
使用方式:
|
||||
@ -288,7 +362,7 @@ proxy不仅支持在其他软件里面通过设置代理的方式,为其他软
|
||||
`./proxy http -t tcp -p :80,:443 -T tls -P "2.2.2.2:33080" -C proxy.crt -K proxy.key`
|
||||
|
||||
注意:
|
||||
proxy所在的服务器的DNS解析结果不能受到自定义的解析影响,不然就死循环了.
|
||||
proxy所在的服务器的DNS解析结果不能受到自定义的解析影响,不然就死循环了,proxy代理最好指定`--dns 8.8.8.8`参数.
|
||||
|
||||
#### **1.10 HTTP(S)透明代理**
|
||||
该模式需要具有一定的网络基础,相关概念不懂的请自行搜索解决.
|
||||
@ -335,19 +409,71 @@ iptables -t nat -A OUTPUT -p tcp -j PROXY
|
||||
- 删除指定的用户自定义链 iptables -X 链名 比如 iptables -t nat -X PROXY
|
||||
- 从所选链中删除规则 iptables -D 链名 规则详情 比如 iptables -t nat -D PROXY -d 223.223.192.0/255.255.240.0 -j RETURN
|
||||
|
||||
#### **1.9.查看帮助**
|
||||
#### **1.11 自定义DNS**
|
||||
--dns-address和--dns-ttl参数,用于自己指定proxy访问域名的时候使用的dns(--dns-address)
|
||||
以及解析结果缓存时间(--dns-ttl)秒数,避免系统dns对proxy的干扰,另外缓存功能还能减少dns解析时间提高访问速度.
|
||||
比如:
|
||||
`./proxy http -p ":33080" --dns-address "8.8.8.8:53" --dns-ttl 300`
|
||||
|
||||
#### **1.12 自定义加密**
|
||||
proxy的http(s)代理在tcp之上可以通过tls标准加密以及kcp协议加密tcp数据,除此之外还支持在tls和kcp之后进行自定义
|
||||
加密,也就是说自定义加密和tls|kcp是可以联合使用的,内部采用AES256加密,使用的时候只需要自己定义一个密码即可,
|
||||
加密分为两个部分,一部分是本地(-z)是否加密解密,一部分是与上级(-Z)传输是否加密解密.
|
||||
自定义加密要求两端都是proxy才可以,下面分别用二级,三级为例:
|
||||
|
||||
**二级实例**
|
||||
一级vps(ip:2.2.2.2)上执行:
|
||||
`proxy http -t tcp -z demo_password -p :7777`
|
||||
本地二级执行:
|
||||
`proxy http -T tcp -P 2.2.2.2:777 -Z demo_password -t tcp -p :8080`
|
||||
这样通过本地代理8080访问网站的时候就是通过与上级加密传输访问目标网站.
|
||||
|
||||
|
||||
**三级实例**
|
||||
一级vps(ip:2.2.2.2)上执行:
|
||||
`proxy http -t tcp -z demo_password -p :7777`
|
||||
二级vps(ip:3.3.3.3)上执行:
|
||||
`proxy http -T tcp -P 2.2.2.2:7777 -Z demo_password -t tcp -z other_password -p :8888`
|
||||
本地三级执行:
|
||||
`proxy http -T tcp -P 3.3.3.3:8888 -Z other_password -t tcp -p :8080`
|
||||
这样通过本地代理8080访问网站的时候就是通过与上级加密传输访问目标网站.
|
||||
|
||||
#### **1.13 压缩传输**
|
||||
proxy的http(s)代理在tcp之上可以通过tls标准加密以及kcp协议加密tcp数据,在自定义加密之前还可以对数据进行压缩,
|
||||
也就是说压缩功能和自定义加密和tls|kcp是可以联合使用的,压缩分为两个部分,一部分是本地(-m)是否压缩传输,
|
||||
一部分是与上级(-M)传输是否压缩.
|
||||
压缩要求两端都是proxy才可以,压缩也在一定程度上保护了(加密)数据,下面分别用二级,三级为例:
|
||||
|
||||
**二级实例**
|
||||
一级vps(ip:2.2.2.2)上执行:
|
||||
`proxy http -t tcp -m -p :7777`
|
||||
本地二级执行:
|
||||
`proxy http -T tcp -P 2.2.2.2:777 -M -t tcp -p :8080`
|
||||
这样通过本地代理8080访问网站的时候就是通过与上级压缩传输访问目标网站.
|
||||
|
||||
|
||||
**三级实例**
|
||||
一级vps(ip:2.2.2.2)上执行:
|
||||
`proxy http -t tcp -m -p :7777`
|
||||
二级vps(ip:3.3.3.3)上执行:
|
||||
`proxy http -T tcp -P 2.2.2.2:7777 -M -t tcp -m -p :8888`
|
||||
本地三级执行:
|
||||
`proxy http -T tcp -P 3.3.3.3:8888 -M -t tcp -p :8080`
|
||||
这样通过本地代理8080访问网站的时候就是通过与上级压缩传输访问目标网站.
|
||||
|
||||
#### **1.14 查看帮助**
|
||||
`./proxy help http`
|
||||
|
||||
### **2.TCP代理**
|
||||
|
||||
#### **2.1.普通一级TCP代理**
|
||||

|
||||

|
||||
本地执行:
|
||||
`./proxy tcp -p ":33080" -T tcp -P "192.168.22.33:22"`
|
||||
那么访问本地33080端口就是访问192.168.22.33的22端口.
|
||||
|
||||
#### **2.2.普通二级TCP代理**
|
||||

|
||||

|
||||
VPS(IP:22.22.22.33)执行:
|
||||
`./proxy tcp -p ":33080" -T tcp -P "127.0.0.1:8080"`
|
||||
本地执行:
|
||||
@ -355,6 +481,7 @@ VPS(IP:22.22.22.33)执行:
|
||||
那么访问本地23080端口就是访问22.22.22.33的8080端口.
|
||||
|
||||
#### **2.3.普通三级TCP代理**
|
||||

|
||||
一级TCP代理VPS_01,IP:22.22.22.22
|
||||
`./proxy tcp -p ":38080" -T tcp -P "66.66.66.66:8080"`
|
||||
二级TCP代理VPS_02,IP:33.33.33.33
|
||||
@ -364,32 +491,56 @@ VPS(IP:22.22.22.33)执行:
|
||||
那么访问本地8080端口就是通过加密TCP隧道访问66.66.66.66的8080端口.
|
||||
|
||||
#### **2.4.加密二级TCP代理**
|
||||

|
||||
VPS(IP:22.22.22.33)执行:
|
||||
`./proxy tcp -t tcp -p ":33080" -T tcp -P "127.0.0.1:8080" -C proxy.crt -K proxy.key`
|
||||
`./proxy tcp -t tls -p ":33080" -T tcp -P "127.0.0.1:8080" -C proxy.crt -K proxy.key`
|
||||
本地执行:
|
||||
`./proxy tcp -p ":23080" -T tls -P "22.22.22.33:33080" -C proxy.crt -K proxy.key`
|
||||
那么访问本地23080端口就是通过加密TCP隧道访问22.22.22.33的8080端口.
|
||||
|
||||
#### **2.5.加密三级TCP代理**
|
||||

|
||||
一级TCP代理VPS_01,IP:22.22.22.22
|
||||
`./proxy tcp -t tcp -p ":38080" -T tcp -P "66.66.66.66:8080" -C proxy.crt -K proxy.key`
|
||||
`./proxy tcp -t tls -p ":38080" -T tcp -P "66.66.66.66:8080" -C proxy.crt -K proxy.key`
|
||||
二级TCP代理VPS_02,IP:33.33.33.33
|
||||
`./proxy tcp -t tcp -p ":28080" -T tls -P "22.22.22.22:38080" -C proxy.crt -K proxy.key`
|
||||
`./proxy tcp -t tls -p ":28080" -T tls -P "22.22.22.22:38080" -C proxy.crt -K proxy.key`
|
||||
三级TCP代理(本地)
|
||||
`./proxy tcp -p ":8080" -T tls -P "33.33.33.33:28080" -C proxy.crt -K proxy.key`
|
||||
那么访问本地8080端口就是通过加密TCP隧道访问66.66.66.66的8080端口.
|
||||
|
||||
#### **2.6.查看帮助**
|
||||
#### **2.6.通过代理连接上级**
|
||||
有时候proxy所在的网络不能直接访问外网,需要通过一个https或者socks5代理才能上网,那么这个时候
|
||||
-J参数就可以帮助你让proxy的tcp端口映射的时候通过https或者socks5代理去连接上级-P,将外部端口映射到本地.
|
||||
-J参数格式如下:
|
||||
|
||||
https代理写法:
|
||||
代理需要认证,用户名:username 密码:password
|
||||
https://username:password@host:port
|
||||
代理不需要认证
|
||||
https://host:port
|
||||
|
||||
socks5代理写法:
|
||||
代理需要认证,用户名:username 密码:password
|
||||
socks5://username:password@host:port
|
||||
代理不需要认证
|
||||
socks5://host:port
|
||||
|
||||
host:代理的IP或者域名
|
||||
port:代理的端口
|
||||
|
||||
#### **2.7.查看帮助**
|
||||
`./proxy help tcp`
|
||||
|
||||
### **3.UDP代理**
|
||||
|
||||
#### **3.1.普通一级UDP代理**
|
||||

|
||||
本地执行:
|
||||
`./proxy udp -p ":5353" -T udp -P "8.8.8.8:53"`
|
||||
那么访问本地UDP:5353端口就是访问8.8.8.8的UDP:53端口.
|
||||
|
||||
#### **3.2.普通二级UDP代理**
|
||||

|
||||
VPS(IP:22.22.22.33)执行:
|
||||
`./proxy tcp -p ":33080" -T udp -P "8.8.8.8:53"`
|
||||
本地执行:
|
||||
@ -397,6 +548,7 @@ VPS(IP:22.22.22.33)执行:
|
||||
那么访问本地UDP:5353端口就是通过TCP隧道,通过VPS访问8.8.8.8的UDP:53端口.
|
||||
|
||||
#### **3.3.普通三级UDP代理**
|
||||

|
||||
一级TCP代理VPS_01,IP:22.22.22.22
|
||||
`./proxy tcp -p ":38080" -T udp -P "8.8.8.8:53"`
|
||||
二级TCP代理VPS_02,IP:33.33.33.33
|
||||
@ -406,17 +558,19 @@ VPS(IP:22.22.22.33)执行:
|
||||
那么访问本地5353端口就是通过TCP隧道,通过VPS访问8.8.8.8的53端口.
|
||||
|
||||
#### **3.4.加密二级UDP代理**
|
||||

|
||||
VPS(IP:22.22.22.33)执行:
|
||||
`./proxy tcp -t tcp -p ":33080" -T udp -P "8.8.8.8:53" -C proxy.crt -K proxy.key`
|
||||
`./proxy tcp -t tls -p ":33080" -T udp -P "8.8.8.8:53" -C proxy.crt -K proxy.key`
|
||||
本地执行:
|
||||
`./proxy udp -p ":5353" -T tls -P "22.22.22.33:33080" -C proxy.crt -K proxy.key`
|
||||
那么访问本地UDP:5353端口就是通过加密TCP隧道,通过VPS访问8.8.8.8的UDP:53端口.
|
||||
|
||||
#### **3.5.加密三级UDP代理**
|
||||

|
||||
一级TCP代理VPS_01,IP:22.22.22.22
|
||||
`./proxy tcp -t tcp -p ":38080" -T udp -P "8.8.8.8:53" -C proxy.crt -K proxy.key`
|
||||
`./proxy tcp -t tls -p ":38080" -T udp -P "8.8.8.8:53" -C proxy.crt -K proxy.key`
|
||||
二级TCP代理VPS_02,IP:33.33.33.33
|
||||
`./proxy tcp -t tcp -p ":28080" -T tls -P "22.22.22.22:38080" -C proxy.crt -K proxy.key`
|
||||
`./proxy tcp -t tls -p ":28080" -T tls -P "22.22.22.22:38080" -C proxy.crt -K proxy.key`
|
||||
三级TCP代理(本地)
|
||||
`./proxy udp -p ":5353" -T tls -P "33.33.33.33:28080" -C proxy.crt -K proxy.key`
|
||||
那么访问本地5353端口就是通过加密TCP隧道,通过VPS_01访问8.8.8.8的53端口.
|
||||
@ -561,24 +715,52 @@ server连接到bridge的时候,如果同时有多个client连接到同一个brid
|
||||
|
||||
4.7.3.LOCAL_IP为空默认是:`0.0.0.0`,CLIENT_LOCAL_HOST为空默认是:`127.0.0.1`;
|
||||
|
||||
#### **4.8.查看帮助**
|
||||
#### **4.8.server和client通过代理连接bridge**
|
||||
有时候server或者client所在的网络不能直接访问外网,需要通过一个https或者socks5代理才能上网,那么这个时候
|
||||
-J参数就可以帮助你让server或者client通过https或者socks5代理去连接bridge.
|
||||
-J参数格式如下:
|
||||
|
||||
https代理写法:
|
||||
代理需要认证,用户名:username 密码:password
|
||||
https://username:password@host:port
|
||||
代理不需要认证
|
||||
https://host:port
|
||||
|
||||
socks5代理写法:
|
||||
代理需要认证,用户名:username 密码:password
|
||||
socks5://username:password@host:port
|
||||
代理不需要认证
|
||||
socks5://host:port
|
||||
|
||||
host:代理的IP或者域名
|
||||
port:代理的端口
|
||||
|
||||
#### **4.9.查看帮助**
|
||||
`./proxy help bridge`
|
||||
`./proxy help server`
|
||||
`./proxy help server`
|
||||
`./proxy help client`
|
||||
|
||||
### **5.SOCKS5代理**
|
||||
提示:SOCKS5代理,支持CONNECT,UDP协议,不支持BIND,支持用户名密码认证.
|
||||
提示:
|
||||
|
||||
SOCKS5代理,支持CONNECT,UDP协议,不支持BIND,支持用户名密码认证.
|
||||
|
||||
***如果你的VPS是阿里云,腾讯云这种VPS,就是ifconfig看不见你的公网IP,只能看见内网IP,***
|
||||
|
||||
***那么需要加上`-g VPS公网IP`参数,SOCKS5代理的UDP功能才能正常工作。***
|
||||
|
||||
#### **5.1.普通SOCKS5代理**
|
||||
`./proxy socks -t tcp -p "0.0.0.0:38080"`
|
||||
|
||||
#### **5.2.普通二级SOCKS5代理**
|
||||

|
||||

|
||||
使用本地端口8090,假设上级SOCKS5代理是`22.22.22.22:8080`
|
||||
`./proxy socks -t tcp -p "0.0.0.0:8090" -T tcp -P "22.22.22.22:8080" `
|
||||
我们还可以指定网站域名的黑白名单文件,一行一个域名,匹配规则是最右匹配,比如:baidu.com,匹配的是*.*.baidu.com,黑名单的域名域名直接走上级代理,白名单的域名不走上级代理.
|
||||
我们还可以指定网站域名的黑白名单文件,一行一个域名,匹配规则是最右匹配,比如:baidu.com,匹配的是*.*.baidu.com,黑名单的域名域名直接走上级代理,白名单的域名不走上级代理;如果域名即在黑名单又在白名单中,那么黑名单起作用.
|
||||
`./proxy socks -p "0.0.0.0:8090" -T tcp -P "22.22.22.22:8080" -b blocked.txt -d direct.txt`
|
||||
|
||||
#### **5.3.SOCKS二级代理(加密)**
|
||||

|
||||
一级SOCKS代理(VPS,IP:22.22.22.22)
|
||||
`./proxy socks -t tls -p ":38080" -C proxy.crt -K proxy.key`
|
||||
|
||||
@ -591,6 +773,7 @@ server连接到bridge的时候,如果同时有多个client连接到同一个brid
|
||||
然后设置你的windos系统中,需要通过代理上网的程序的代理为socks5模式,地址为:127.0.0.1,端口为:8080,程序即可通过加密通道通过vps上网。
|
||||
|
||||
#### **5.4.SOCKS三级代理(加密)**
|
||||

|
||||
一级SOCKS代理VPS_01,IP:22.22.22.22
|
||||
`./proxy socks -t tls -p ":38080" -C proxy.crt -K proxy.key`
|
||||
二级SOCKS代理VPS_02,IP:33.33.33.33
|
||||
@ -604,6 +787,7 @@ server连接到bridge的时候,如果同时有多个client连接到同一个brid
|
||||
`./proxy socks --always -t tls -p ":28080" -T tls -P "22.22.22.22:38080" -C proxy.crt -K proxy.key`
|
||||
|
||||
#### **5.6.SOCKS通过SSH中转**
|
||||

|
||||
说明:ssh中转的原理是利用了ssh的转发功能,就是你连接上ssh之后,可以通过ssh代理访问目标地址.
|
||||
假设有:vps
|
||||
- IP是2.2.2.2, ssh端口是22, ssh用户名是:user, ssh用户密码是:demo
|
||||
@ -626,7 +810,7 @@ server连接到bridge的时候,如果同时有多个client连接到同一个brid
|
||||
`./proxy socks -t tcp -p ":33080" -F auth-file.txt`
|
||||
|
||||
另外,socks5代理还集成了外部HTTP API认证,我们可以通过--auth-url参数指定一个http url接口地址,
|
||||
然后有用户连接的时候,proxy会GET方式请求这url,带上下面四个参数,如果返回HTTP状态码204,代表认证成功
|
||||
然后有用户连接的时候,proxy会GET方式请求这url,带上下面三个参数,如果返回HTTP状态码204,代表认证成功
|
||||
其它情况认为认证失败.
|
||||
比如:
|
||||
`./proxy socks -t tcp -p ":33080" --auth-url "http://test.com/auth.php"`
|
||||
@ -640,29 +824,358 @@ ip:用户的IP,比如:192.168.1.200
|
||||
如果没有-a或-F或--auth-url参数,就是关闭认证.
|
||||
|
||||
#### **5.8.KCP协议传输**
|
||||
KCP协议需要-B参数设置一个密码用于加密解密数据
|
||||
KCP协议需要--kcp-key参数设置一个密码用于加密解密数据
|
||||
|
||||
一级HTTP代理(VPS,IP:22.22.22.22)
|
||||
`./proxy socks -t kcp -p ":38080" -B mypassword`
|
||||
`./proxy socks -t kcp -p ":38080" --kcp-key mypassword`
|
||||
|
||||
二级HTTP代理(本地Linux)
|
||||
`./proxy socks -t tcp -p ":8080" -T kcp -P "22.22.22.22:38080" -B mypassword`
|
||||
`./proxy socks -t tcp -p ":8080" -T kcp -P "22.22.22.22:38080" --kcp-key mypassword`
|
||||
那么访问本地的8080端口就是访问VPS上面的代理端口38080,数据通过kcp协议传输.
|
||||
|
||||
#### **5.9.查看帮助**
|
||||
#### **5.9.自定义DNS**
|
||||
--dns-address和--dns-ttl参数,用于自己指定proxy访问域名的时候使用的dns(--dns-address)
|
||||
以及解析结果缓存时间(--dns-ttl)秒数,避免系统dns对proxy的干扰,另外缓存功能还能减少dns解析时间提高访问速度.
|
||||
比如:
|
||||
`./proxy socks -p ":33080" --dns-address "8.8.8.8:53" --dns-ttl 300`
|
||||
|
||||
#### **5.10 自定义加密**
|
||||
proxy的socks代理在tcp之上可以通过tls标准加密以及kcp协议加密tcp数据,除此之外还支持在tls和kcp之后进行自定义加密,也就是说自定义加密和tls|kcp是可以联合使用的,内部采用AES256加密,使用的时候只需要自己定义一个密码即可,
|
||||
加密分为两个部分,一部分是本地(-z)是否加密解密,一部分是与上级(-Z)传输是否加密解密.
|
||||
|
||||
自定义加密要求两端都是proxy才可以.
|
||||
|
||||
下面分别用二级,三级为例:
|
||||
|
||||
**二级实例**
|
||||
一级vps(ip:2.2.2.2)上执行:
|
||||
`proxy socks -t tcp -z demo_password -p :7777`
|
||||
本地二级执行:
|
||||
`proxy socks -T tcp -P 2.2.2.2:777 -Z demo_password -t tcp -p :8080`
|
||||
这样通过本地代理8080访问网站的时候就是通过与上级加密传输访问目标网站.
|
||||
|
||||
|
||||
**三级实例**
|
||||
一级vps(ip:2.2.2.2)上执行:
|
||||
`proxy socks -t tcp -z demo_password -p :7777`
|
||||
二级vps(ip:3.3.3.3)上执行:
|
||||
`proxy socks -T tcp -P 2.2.2.2:7777 -Z demo_password -t tcp -z other_password -p :8888`
|
||||
本地三级执行:
|
||||
`proxy socks -T tcp -P 3.3.3.3:8888 -Z other_password -t tcp -p :8080`
|
||||
这样通过本地代理8080访问网站的时候就是通过与上级加密传输访问目标网站.
|
||||
|
||||
#### **5.11 压缩传输**
|
||||
proxy的socks代理在tcp之上可以通过自定义加密和tls标准加密以及kcp协议加密tcp数据,在自定义加密之前还可以
|
||||
对数据进行压缩,也就是说压缩功能和自定义加密和tls|kcp是可以联合使用的,压缩分为两个部分,
|
||||
一部分是本地(-m)是否压缩传输,一部分是与上级(-M)传输是否压缩.
|
||||
|
||||
压缩要求两端都是proxy才可以,压缩也在一定程度上保护了(加密)数据.
|
||||
|
||||
下面分别用二级,三级为例:
|
||||
|
||||
**二级实例**
|
||||
一级vps(ip:2.2.2.2)上执行:
|
||||
`proxy socks -t tcp -m -p :7777`
|
||||
本地二级执行:
|
||||
`proxy socks -T tcp -P 2.2.2.2:777 -M -t tcp -p :8080`
|
||||
这样通过本地代理8080访问网站的时候就是通过与上级压缩传输访问目标网站.
|
||||
|
||||
|
||||
**三级实例**
|
||||
一级vps(ip:2.2.2.2)上执行:
|
||||
`proxy socks -t tcp -m -p :7777`
|
||||
二级vps(ip:3.3.3.3)上执行:
|
||||
`proxy socks -T tcp -P 2.2.2.2:7777 -M -t tcp -m -p :8888`
|
||||
本地三级执行:
|
||||
`proxy socks -T tcp -P 3.3.3.3:8888 -M -t tcp -p :8080`
|
||||
这样通过本地代理8080访问网站的时候就是通过与上级压缩传输访问目标网站.
|
||||
|
||||
#### **5.12.查看帮助**
|
||||
`./proxy help socks`
|
||||
|
||||
### **6.代理协议转换**
|
||||
|
||||
#### **6.1 功能介绍**
|
||||
代理协议转换使用的是sps子命令(socks+https的缩写),sps本身不提供代理功能,只是接受代理请求"转换并转发"给已经存在的http(s)代理或者socks5代理;sps可以把已经存在的http(s)代理或者socks5代理转换为一个端口同时支持http(s)和socks5代理,而且http(s)代理支持正向代理和反向代理(SNI),转换后的SOCKS5代理,当上级是SOCKS5时仍然支持UDP功能;另外对于已经存在的http(s)代理或者socks5代理,支持tls、tcp、kcp三种模式,支持链式连接,也就是可以多个sps结点层级连接构建加密通道。
|
||||
|
||||
#### **6.2 HTTP(S)转HTTP(S)+SOCKS5**
|
||||
假设已经存在一个普通的http(s)代理:127.0.0.1:8080,现在我们把它转为同时支持http(s)和socks5的普通代理,转换后的本地端口为18080。
|
||||
命令如下:
|
||||
`./proxy sps -S http -T tcp -P 127.0.0.1:8080 -t tcp -p :18080`
|
||||
|
||||
假设已经存在一个tls的http(s)代理:127.0.0.1:8080,现在我们把它转为同时支持http(s)和socks5的普通代理,转换后的本地端口为18080,tls需要证书文件。
|
||||
命令如下:
|
||||
`./proxy sps -S http -T tls -P 127.0.0.1:8080 -t tcp -p :18080 -C proxy.crt -K proxy.key`
|
||||
|
||||
假设已经存在一个kcp的http(s)代理(密码是:demo123):127.0.0.1:8080,现在我们把它转为同时支持http(s)和socks5的普通代理,转换后的本地端口为18080。
|
||||
命令如下:
|
||||
`./proxy sps -S http -T kcp -P 127.0.0.1:8080 -t tcp -p :18080 --kcp-key demo123`
|
||||
|
||||
#### **6.3 SOCKS5转HTTP(S)+SOCKS5**
|
||||
假设已经存在一个普通的socks5代理:127.0.0.1:8080,现在我们把它转为同时支持http(s)和socks5的普通代理,转换后的本地端口为18080。
|
||||
命令如下:
|
||||
`./proxy sps -S socks -T tcp -P 127.0.0.1:8080 -t tcp -p :18080`
|
||||
|
||||
假设已经存在一个tls的socks5代理:127.0.0.1:8080,现在我们把它转为同时支持http(s)和socks5的普通代理,转换后的本地端口为18080,tls需要证书文件。
|
||||
命令如下:
|
||||
`./proxy sps -S socks -T tls -P 127.0.0.1:8080 -t tcp -p :18080 -C proxy.crt -K proxy.key`
|
||||
|
||||
假设已经存在一个kcp的socks5代理(密码是:demo123):127.0.0.1:8080,现在我们把它转为同时支持http(s)和socks5的普通代理,转换后的本地端口为18080。
|
||||
命令如下:
|
||||
`./proxy sps -S socks -T kcp -P 127.0.0.1:8080 -t tcp -p :18080 --kcp-key demo123`
|
||||
|
||||
#### **6.4 链式连接**
|
||||

|
||||
上面提过多个sps结点可以层级连接构建加密通道,假设有如下vps和家里的pc电脑。
|
||||
vps01:2.2.2.2
|
||||
vps02:3.3.3.3
|
||||
现在我们想利用pc和vps01和vps02构建一个加密通道,本例子用tls加密也可以用kcp,在pc上访问本地18080端口就是访问vps01的本地8080端口。
|
||||
首先在vps01(2.2.2.2)上我们运行一个只有本地可以访问的http(s)代理,执行:
|
||||
`./proxy http -t tcp -p 127.0.0.1:8080`
|
||||
|
||||
然后在vps01(2.2.2.2)上运行一个sps结点,执行:
|
||||
`./proxy sps -S http -T tcp -P 127.0.0.1:8080 -t tls -p :8081 -C proxy.crt -K proxy.key`
|
||||
|
||||
然后在vps02(3.3.3.3)上运行一个sps结点,执行:
|
||||
`./proxy sps -S http -T tls -P 2.2.2.2:8081 -t tls -p :8082 -C proxy.crt -K proxy.key`
|
||||
|
||||
然后在pc上运行一个sps结点,执行:
|
||||
`./proxy sps -S http -T tls -P 3.3.3.3:8082 -t tcp -p :18080 -C proxy.crt -K proxy.key`
|
||||
|
||||
完成。
|
||||
|
||||
#### **6.5 监听多个端口**
|
||||
一般情况下监听一个端口就可以,不过如果作为反向代理需要同时监听80和443两个端口,那么-p参数是支持的,
|
||||
格式是:`-p 0.0.0.0:80,0.0.0.0:443`,多个绑定用逗号分隔即可。
|
||||
|
||||
#### **6.6 认证功能**
|
||||
sps支持http(s)\socks5代理认证,可以级联认证,有四个重要的信息:
|
||||
1:用户发送认证信息`user-auth`。
|
||||
2:设置的本地认证信息`local-auth`。
|
||||
3:设置的连接上级使用的认证信息`parent-auth`。
|
||||
4:最终发送给上级的认证信息`auth-info-to-parent`。
|
||||
他们的情况关系如下:
|
||||
|
||||
| user-auth | local-auth | parent-auth | auth-info-to-paren
|
||||
| ------ | ------ | ------ | ------
|
||||
| 有/没有 | 有 | 有 | 来自parent-auth
|
||||
| 有/没有 | 没有 | 有 | 来自parent-auth
|
||||
| 有/没有 | 有 | 没有 | 无
|
||||
| 没有 | 没有 | 没有 | 无
|
||||
| 有 | 没有 | 没有 | 来自user-auth
|
||||
|
||||
对于sps代理我们可以进行用户名密码认证,认证的用户名和密码可以在命令行指定
|
||||
`./proxy sps -S http -T tcp -P 127.0.0.1:8080 -t tcp -p ":33080" -a "user1:pass1" -a "user2:pass2"`
|
||||
多个用户,重复-a参数即可.
|
||||
也可以放在文件中,格式是一行一个"用户名:密码",然后用-F指定.
|
||||
`./proxy sps -S http -T tcp -P 127.0.0.1:8080 -t tcp -p ":33080" -F auth-file.txt`
|
||||
|
||||
如果上级有认证,下级可以通过-A参数设置认证信息,比如:
|
||||
上级:`./proxy sps -S http -T tcp -P 127.0.0.1:8080 -t tcp -p ":33080" -a "user1:pass1" -a "user2:pass2"`
|
||||
下级:`./proxy sps -S http -T tcp -P 127.0.0.1:8080 -A "user1:pass1" -t tcp -p ":33080" `
|
||||
|
||||
另外,sps代理,本地认证集成了外部HTTP API认证,我们可以通过--auth-url参数指定一个http url接口地址,
|
||||
然后有用户连接的时候,proxy会GET方式请求这url,带上下面四个参数,如果返回HTTP状态码204,代表认证成功
|
||||
其它情况认为认证失败.
|
||||
比如:
|
||||
`./proxy sps -S http -T tcp -P 127.0.0.1:8080 -t tcp -p ":33080" --auth-url "http://test.com/auth.php"`
|
||||
用户连接的时候,proxy会GET方式请求这url("http://test.com/auth.php"),
|
||||
带上user,pass,ip,target四个参数:
|
||||
http://test.com/auth.php?user={USER}&pass={PASS}&ip={IP}&target={TARGET}
|
||||
user:用户名
|
||||
pass:密码
|
||||
ip:用户的IP,比如:192.168.1.200
|
||||
target:如果客户端是http(s)代理请求,这里代表的是请求的完整url,其它情况为空.
|
||||
|
||||
如果没有-a或-F或--auth-url参数,就是关闭本地认证.
|
||||
如果没有-A参数,连接上级不使用认证.
|
||||
|
||||
|
||||
#### **6.7 自定义加密**
|
||||
proxy的sps代理在tcp之上可以通过tls标准加密以及kcp协议加密tcp数据,除此之外还支持在tls和kcp之后进行
|
||||
自定义加密,也就是说自定义加密和tls|kcp是可以联合使用的,内部采用AES256加密,使用的时候只需要自己定义
|
||||
一个密码即可,加密分为两个部分,一部分是本地(-z)是否加密解密,一部分是与上级(-Z)传输是否加密解密.
|
||||
|
||||
自定义加密要求两端都是proxy才可以.
|
||||
|
||||
下面分别用二级,三级为例:
|
||||
|
||||
假设已经存在一个http(s)代理:`6.6.6.6:6666`
|
||||
|
||||
**二级实例**
|
||||
一级vps(ip:2.2.2.2)上执行:
|
||||
`proxy sps -S http -T tcp -P 6.6.6.6:6666 -t tcp -z demo_password -p :7777`
|
||||
本地二级执行:
|
||||
`proxy sps -T tcp -P 2.2.2.2:777 -Z demo_password -t tcp -p :8080`
|
||||
这样通过本地代理8080访问网站的时候就是通过与上级加密传输访问目标网站.
|
||||
|
||||
|
||||
**三级实例**
|
||||
一级vps(ip:2.2.2.2)上执行:
|
||||
`proxy sps -S http -T tcp -P 6.6.6.6:6666 -t tcp -z demo_password -p :7777`
|
||||
二级vps(ip:3.3.3.3)上执行:
|
||||
`proxy sps -T tcp -P 2.2.2.2:7777 -Z demo_password -t tcp -z other_password -p :8888`
|
||||
本地三级执行:
|
||||
`proxy sps -T tcp -P 3.3.3.3:8888 -Z other_password -t tcp -p :8080`
|
||||
这样通过本地代理8080访问网站的时候就是通过与上级加密传输访问目标网站.
|
||||
|
||||
#### **6.8 压缩传输**
|
||||
proxy的sps代理在tcp之上可以通过自定义加密和tls标准加密以及kcp协议加密tcp数据,在自定义加密之前还可以
|
||||
对数据进行压缩,也就是说压缩功能和自定义加密和tls|kcp是可以联合使用的,压缩分为两个部分,
|
||||
一部分是本地(-m)是否压缩传输,一部分是与上级(-M)传输是否压缩.
|
||||
|
||||
压缩要求两端都是proxy才可以,压缩也在一定程度上保护了(加密)数据.
|
||||
|
||||
下面分别用二级,三级为例:
|
||||
|
||||
**二级实例**
|
||||
一级vps(ip:2.2.2.2)上执行:
|
||||
`proxy sps -t tcp -m -p :7777`
|
||||
本地二级执行:
|
||||
`proxy sps -T tcp -P 2.2.2.2:777 -M -t tcp -p :8080`
|
||||
这样通过本地代理8080访问网站的时候就是通过与上级压缩传输访问目标网站.
|
||||
|
||||
|
||||
**三级实例**
|
||||
一级vps(ip:2.2.2.2)上执行:
|
||||
`proxy sps -t tcp -m -p :7777`
|
||||
二级vps(ip:3.3.3.3)上执行:
|
||||
`proxy sps -T tcp -P 2.2.2.2:7777 -M -t tcp -m -p :8888`
|
||||
本地三级执行:
|
||||
`proxy sps -T tcp -P 3.3.3.3:8888 -M -t tcp -p :8080`
|
||||
这样通过本地代理8080访问网站的时候就是通过与上级压缩传输访问目标网站.
|
||||
|
||||
|
||||
#### **6.9 禁用协议**
|
||||
SPS默认情况下一个端口支持http(s)和socks5两种代理协议,我们可以通过参数禁用某个协议
|
||||
比如:
|
||||
1.禁用HTTP(S)代理功能只保留SOCKS5代理功能,参数:`--disable-http`.
|
||||
`proxy sps -T tcp -P 3.3.3.3:8888 -M -t tcp -p :8080 --disable-http`
|
||||
|
||||
1.禁用SOCKS5代理功能只保留HTTP(S)代理功能,参数:`--disable-socks`.
|
||||
`proxy sps -T tcp -P 3.3.3.3:8888 -M -t tcp -p :8080 --disable-http`
|
||||
|
||||
#### **6.10 查看帮助**
|
||||
`./proxy help sps`
|
||||
|
||||
### **7.KCP配置**
|
||||
|
||||
#### **7.1 配置介绍**
|
||||
proxy的很多功能都支持kcp协议,凡是使用了kcp协议的功能都支持这里介绍的配置参数。
|
||||
所以这里统一对KCP配置参数进行介绍。
|
||||
|
||||
#### **7.2 详细配置**
|
||||
所有的KCP配置参数共有17个,你可以都不用设置,他们都有默认值,如果为了或者最好的效果,
|
||||
就需要自己根据自己根据网络情况对参数进行配置。由于kcp配置很复杂需要一定的网络基础知识,
|
||||
如果想获得kcp参数更详细的配置和解说,请自行搜索。每个参数的命令行名称以及默认值和简单的功能说明如下:
|
||||
```
|
||||
--kcp-key="secrect" pre-shared secret between client and server
|
||||
--kcp-method="aes" encrypt/decrypt method, can be: aes, aes-128, aes-192, salsa20, blowfish,
|
||||
twofish, cast5, 3des, tea, xtea, xor, sm4, none
|
||||
--kcp-mode="fast" profiles: fast3, fast2, fast, normal, manual
|
||||
--kcp-mtu=1350 set maximum transmission unit for UDP packets
|
||||
--kcp-sndwnd=1024 set send window size(num of packets)
|
||||
--kcp-rcvwnd=1024 set receive window size(num of packets)
|
||||
--kcp-ds=10 set reed-solomon erasure coding - datashard
|
||||
--kcp-ps=3 set reed-solomon erasure coding - parityshard
|
||||
--kcp-dscp=0 set DSCP(6bit)
|
||||
--kcp-nocomp disable compression
|
||||
--kcp-acknodelay be carefull! flush ack immediately when a packet is received
|
||||
--kcp-nodelay=0 be carefull!
|
||||
--kcp-interval=50 be carefull!
|
||||
--kcp-resend=0 be carefull!
|
||||
--kcp-nc=0 be carefull! no congestion
|
||||
--kcp-sockbuf=4194304 be carefull!
|
||||
--kcp-keepalive=10 be carefull!
|
||||
```
|
||||
提示:
|
||||
参数:--kcp-mode中的四种fast3, fast2, fast, normal模式,
|
||||
相当于设置了下面四个参数:
|
||||
normal:`--nodelay=0 --interval=40 --resend=2 --nc=1`
|
||||
fast :`--nodelay=0 --interval=30 --resend=2 --nc=1`
|
||||
fast2:`--nodelay=1 --interval=20 --resend=2 --nc=1`
|
||||
fast3:`--nodelay=1 --interval=10 --resend=2 --nc=1`
|
||||
|
||||
### **8.DNS防污染服务器**
|
||||
|
||||
#### **8.1 介绍**
|
||||
众所周知DNS是UDP端口53提供的服务,但是随着网络的发展一些知名DNS服务器也支持TCP方式dns查询,比如谷歌的8.8.8.8,proxy的DNS防污染服务器原理就是在本地启动一个proxy的DNS代理服务器,它用TCP的方式通过上级代理进行dns查询。如果它和上级代理通讯采用加密的方式,那么就可以进行安全无污染的DNS解析。
|
||||
|
||||
#### **8.2 使用示例**
|
||||
|
||||
***8.2.1 普通HTTP(S)上级代理***
|
||||
假设有一个上级代理:2.2.2.2:33080
|
||||
本地执行:
|
||||
`proxy dns -S http -T tcp -P 2.2.2.2:33080 -p :53`
|
||||
那么本地的UDP端口53就提供了DNS解析功能。
|
||||
|
||||
***8.2.2 普通SOCKS5上级代理***
|
||||
假设有一个上级代理:2.2.2.2:33080
|
||||
本地执行:
|
||||
`proxy dns -S socks -T tcp -P 2.2.2.2:33080 -p :53`
|
||||
那么本地的UDP端口53就提供了DNS解析功能。
|
||||
|
||||
***8.2.3 TLS加密的HTTP(S)上级代理***
|
||||
假设有一个上级代理:2.2.2.2:33080
|
||||
上级代理执行的命令是:
|
||||
`proxy http -t tls -C proxy.crt -K proxy.key -p :33080`
|
||||
本地执行:
|
||||
`proxy dns -S http -T tls -P 2.2.2.2:33080 -C proxy.crt -K proxy.key -p :53`
|
||||
那么本地的UDP端口53就提供了安全防污染DNS解析功能。
|
||||
|
||||
***8.2.4 TLS加密的SOCKS5上级代理***
|
||||
假设有一个上级代理:2.2.2.2:33080
|
||||
上级代理执行的命令是:
|
||||
`proxy socks -t tls -C proxy.crt -K proxy.key -p :33080`
|
||||
本地执行:
|
||||
`proxy dns -S socks -T tls -P 2.2.2.2:33080 -C proxy.crt -K proxy.key -p :53`
|
||||
那么本地的UDP端口53就提供了安全防污染DNS解析功能。
|
||||
|
||||
***8.2.5 KCP加密的HTTP(S)上级代理***
|
||||
假设有一个上级代理:2.2.2.2:33080
|
||||
上级代理执行的命令是:
|
||||
`proxy http -t kcp -p :33080`
|
||||
本地执行:
|
||||
`proxy dns -S http -T kcp -P 2.2.2.2:33080 -p :53`
|
||||
那么本地的UDP端口53就提供了安全防污染DNS解析功能。
|
||||
|
||||
***8.2.6 KCP加密的SOCKS5上级代理***
|
||||
假设有一个上级代理:2.2.2.2:33080
|
||||
上级代理执行的命令是:
|
||||
`proxy socks -t kcp -p :33080`
|
||||
本地执行:
|
||||
`proxy dns -S socks -T kcp -P 2.2.2.2:33080 -p :53`
|
||||
那么本地的UDP端口53就提供了安全防污染DNS解析功能。
|
||||
|
||||
***8.2.7 自定义加密的HTTP(S)上级代理***
|
||||
假设有一个上级代理:2.2.2.2:33080
|
||||
上级代理执行的命令是:
|
||||
`proxy http -t tcp -p :33080 -z password`
|
||||
本地执行:
|
||||
`proxy dns -S http -T tcp -Z password -P 2.2.2.2:33080 -p :53`
|
||||
那么本地的UDP端口53就提供了安全防污染DNS解析功能。
|
||||
|
||||
***8.2.8 自定义加密的SOCKS5上级代理***
|
||||
假设有一个上级代理:2.2.2.2:33080
|
||||
上级代理执行的命令是:
|
||||
`proxy socks -t kcp -p :33080 -z password`
|
||||
本地执行:
|
||||
`proxy dns -S socks -T tcp -Z password -P 2.2.2.2:33080 -p :53`
|
||||
那么本地的UDP端口53就提供了安全防污染DNS解析功能。
|
||||
|
||||
### TODO
|
||||
- http,socks代理多个上级负载均衡?
|
||||
- http(s)代理增加pac支持?
|
||||
- 欢迎加群反馈...
|
||||
|
||||
### 如何使用源码?
|
||||
建议go1.8,不保证>=1.9能用.
|
||||
cd进入你的go src目录,然后git clone https://github.com/snail007/goproxy.git ./proxy 即可.
|
||||
编译直接:go build
|
||||
运行: go run *.go
|
||||
utils是工具包,service是具体的每个服务类.
|
||||
### 如何使用源码?
|
||||
建议go1.10.1.
|
||||
`go get github.com/snail007/goproxy`
|
||||
cd进入你的go src目录
|
||||
cd进入`github.com/snail007/goproxy`即可.
|
||||
编译直接:`go build -o proxy`
|
||||
运行: `go run *.go`
|
||||
utils是工具包,service是具体的每个服务类.
|
||||
|
||||
### License
|
||||
Proxy is licensed under GPLv3 license.
|
||||
@ -674,5 +1187,3 @@ QQ交流群:189618940
|
||||
如果proxy帮助你解决了很多问题,你可以通过下面的捐赠更好的支持proxy.
|
||||
<img src="https://github.com/snail007/goproxy/blob/master/docs/images/alipay.jpg?raw=true" width="200"/>
|
||||
<img src="https://github.com/snail007/goproxy/blob/master/docs/images/wxpay.jpg?raw=true" width="200"/>
|
||||
|
||||
|
||||
|
||||
323
config.go
@ -2,43 +2,60 @@ package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/sha1"
|
||||
"fmt"
|
||||
"log"
|
||||
"io/ioutil"
|
||||
logger "log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"proxy/services"
|
||||
"proxy/utils"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"runtime/pprof"
|
||||
"time"
|
||||
|
||||
sdk "github.com/snail007/goproxy/sdk/android-ios"
|
||||
"github.com/snail007/goproxy/services"
|
||||
"github.com/snail007/goproxy/services/kcpcfg"
|
||||
|
||||
httpx "github.com/snail007/goproxy/services/http"
|
||||
keygenx "github.com/snail007/goproxy/services/keygen"
|
||||
mux "github.com/snail007/goproxy/services/mux"
|
||||
socksx "github.com/snail007/goproxy/services/socks"
|
||||
spsx "github.com/snail007/goproxy/services/sps"
|
||||
tcpx "github.com/snail007/goproxy/services/tcp"
|
||||
tunnel "github.com/snail007/goproxy/services/tunnel"
|
||||
udpx "github.com/snail007/goproxy/services/udp"
|
||||
|
||||
kcp "github.com/xtaci/kcp-go"
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
kingpin "gopkg.in/alecthomas/kingpin.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
app *kingpin.Application
|
||||
service *services.ServiceItem
|
||||
cmd *exec.Cmd
|
||||
app *kingpin.Application
|
||||
service *services.ServiceItem
|
||||
cmd *exec.Cmd
|
||||
cpuProfilingFile, memProfilingFile, blockProfilingFile, goroutineProfilingFile, threadcreateProfilingFile *os.File
|
||||
isDebug bool
|
||||
)
|
||||
|
||||
func initConfig() (err error) {
|
||||
//keygen
|
||||
if len(os.Args) > 1 {
|
||||
if os.Args[1] == "keygen" {
|
||||
utils.Keygen()
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
//define args
|
||||
tcpArgs := services.TCPArgs{}
|
||||
httpArgs := services.HTTPArgs{}
|
||||
tunnelServerArgs := services.TunnelServerArgs{}
|
||||
tunnelClientArgs := services.TunnelClientArgs{}
|
||||
tunnelBridgeArgs := services.TunnelBridgeArgs{}
|
||||
muxServerArgs := services.MuxServerArgs{}
|
||||
muxClientArgs := services.MuxClientArgs{}
|
||||
muxBridgeArgs := services.MuxBridgeArgs{}
|
||||
udpArgs := services.UDPArgs{}
|
||||
socksArgs := services.SocksArgs{}
|
||||
tcpArgs := tcpx.TCPArgs{}
|
||||
httpArgs := httpx.HTTPArgs{}
|
||||
tunnelServerArgs := tunnel.TunnelServerArgs{}
|
||||
tunnelClientArgs := tunnel.TunnelClientArgs{}
|
||||
tunnelBridgeArgs := tunnel.TunnelBridgeArgs{}
|
||||
muxServerArgs := mux.MuxServerArgs{}
|
||||
muxClientArgs := mux.MuxClientArgs{}
|
||||
muxBridgeArgs := mux.MuxBridgeArgs{}
|
||||
udpArgs := udpx.UDPArgs{}
|
||||
socksArgs := socksx.SocksArgs{}
|
||||
spsArgs := spsx.SPSArgs{}
|
||||
dnsArgs := sdk.DNSArgs{}
|
||||
keygenArgs := keygenx.KeygenArgs{}
|
||||
kcpArgs := kcpcfg.KCPConfigArgs{}
|
||||
|
||||
//build srvice args
|
||||
app = kingpin.New("proxy", "happy with proxy")
|
||||
app.Author("snail").Version(APP_VERSION)
|
||||
@ -46,10 +63,29 @@ func initConfig() (err error) {
|
||||
daemon := app.Flag("daemon", "run proxy in background").Default("false").Bool()
|
||||
forever := app.Flag("forever", "run proxy in forever,fail and retry").Default("false").Bool()
|
||||
logfile := app.Flag("log", "log file path").Default("").String()
|
||||
nolog := app.Flag("nolog", "turn off logging").Default("false").Bool()
|
||||
kcpArgs.Key = app.Flag("kcp-key", "pre-shared secret between client and server").Default("secrect").String()
|
||||
kcpArgs.Crypt = app.Flag("kcp-method", "encrypt/decrypt method, can be: aes, aes-128, aes-192, salsa20, blowfish, twofish, cast5, 3des, tea, xtea, xor, sm4, none").Default("aes").Enum("aes", "aes-128", "aes-192", "salsa20", "blowfish", "twofish", "cast5", "3des", "tea", "xtea", "xor", "sm4", "none")
|
||||
kcpArgs.Mode = app.Flag("kcp-mode", "profiles: fast3, fast2, fast, normal, manual").Default("fast").Enum("fast3", "fast2", "fast", "normal", "manual")
|
||||
kcpArgs.MTU = app.Flag("kcp-mtu", "set maximum transmission unit for UDP packets").Default("450").Int()
|
||||
kcpArgs.SndWnd = app.Flag("kcp-sndwnd", "set send window size(num of packets)").Default("1024").Int()
|
||||
kcpArgs.RcvWnd = app.Flag("kcp-rcvwnd", "set receive window size(num of packets)").Default("1024").Int()
|
||||
kcpArgs.DataShard = app.Flag("kcp-ds", "set reed-solomon erasure coding - datashard").Default("10").Int()
|
||||
kcpArgs.ParityShard = app.Flag("kcp-ps", "set reed-solomon erasure coding - parityshard").Default("3").Int()
|
||||
kcpArgs.DSCP = app.Flag("kcp-dscp", "set DSCP(6bit)").Default("0").Int()
|
||||
kcpArgs.NoComp = app.Flag("kcp-nocomp", "disable compression").Default("false").Bool()
|
||||
kcpArgs.AckNodelay = app.Flag("kcp-acknodelay", "be carefull! flush ack immediately when a packet is received").Default("true").Bool()
|
||||
kcpArgs.NoDelay = app.Flag("kcp-nodelay", "be carefull!").Default("0").Int()
|
||||
kcpArgs.Interval = app.Flag("kcp-interval", "be carefull!").Default("50").Int()
|
||||
kcpArgs.Resend = app.Flag("kcp-resend", "be carefull!").Default("0").Int()
|
||||
kcpArgs.NoCongestion = app.Flag("kcp-nc", "be carefull! no congestion").Default("0").Int()
|
||||
kcpArgs.SockBuf = app.Flag("kcp-sockbuf", "be carefull!").Default("4194304").Int()
|
||||
kcpArgs.KeepAlive = app.Flag("kcp-keepalive", "be carefull!").Default("10").Int()
|
||||
|
||||
//########http#########
|
||||
http := app.Command("http", "proxy on http mode")
|
||||
httpArgs.Parent = http.Flag("parent", "parent address, such as: \"23.32.32.19:28008\"").Default("").Short('P').String()
|
||||
httpArgs.CaCertFile = http.Flag("ca", "ca cert file for tls").Default("").String()
|
||||
httpArgs.CertFile = http.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
httpArgs.KeyFile = http.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
httpArgs.LocalType = http.Flag("local-type", "local protocol type <tls|tcp|kcp>").Default("tcp").Short('t').Enum("tls", "tcp", "kcp")
|
||||
@ -62,20 +98,23 @@ func initConfig() (err error) {
|
||||
httpArgs.Direct = http.Flag("direct", "direct domain file , one domain each line").Default("direct").Short('d').String()
|
||||
httpArgs.AuthFile = http.Flag("auth-file", "http basic auth file,\"username:password\" each line in file").Short('F').String()
|
||||
httpArgs.Auth = http.Flag("auth", "http basic auth username and password, mutiple user repeat -a ,such as: -a user1:pass1 -a user2:pass2").Short('a').Strings()
|
||||
httpArgs.PoolSize = http.Flag("pool-size", "conn pool size , which connect to parent proxy, zero: means turn off pool").Short('L').Default("0").Int()
|
||||
httpArgs.CheckParentInterval = http.Flag("check-parent-interval", "check if proxy is okay every interval seconds,zero: means no check").Short('I').Default("3").Int()
|
||||
httpArgs.Local = http.Flag("local", "local ip:port to listen,multiple address use comma split,such as: 0.0.0.0:80,0.0.0.0:443").Short('p').Default(":33080").String()
|
||||
httpArgs.SSHUser = http.Flag("ssh-user", "user for ssh").Short('u').Default("").String()
|
||||
httpArgs.SSHKeyFile = http.Flag("ssh-key", "private key file for ssh").Short('S').Default("").String()
|
||||
httpArgs.SSHKeyFileSalt = http.Flag("ssh-keysalt", "salt of ssh private key").Short('s').Default("").String()
|
||||
httpArgs.SSHPassword = http.Flag("ssh-password", "password for ssh").Short('A').Default("").String()
|
||||
httpArgs.KCPKey = http.Flag("kcp-key", "key for kcp encrypt/decrypt data").Short('B').Default("encrypt").String()
|
||||
httpArgs.KCPMethod = http.Flag("kcp-method", "kcp encrypt/decrypt method").Short('M').Default("3des").String()
|
||||
httpArgs.LocalIPS = http.Flag("local bind ips", "if your host behind a nat,set your public ip here avoid dead loop").Short('g').Strings()
|
||||
httpArgs.LocalIPS = http.Flag("local-bind-ips", "if your host behind a nat,set your public ip here avoid dead loop").Short('g').Strings()
|
||||
httpArgs.AuthURL = http.Flag("auth-url", "http basic auth username and password will send to this url,response http code equal to 'auth-code' means ok,others means fail.").Default("").String()
|
||||
httpArgs.AuthURLTimeout = http.Flag("auth-timeout", "access 'auth-url' timeout milliseconds").Default("3000").Int()
|
||||
httpArgs.AuthURLOkCode = http.Flag("auth-code", "access 'auth-url' success http code").Default("204").Int()
|
||||
httpArgs.AuthURLRetry = http.Flag("auth-retry", "access 'auth-url' fail and retry count").Default("1").Int()
|
||||
httpArgs.DNSAddress = http.Flag("dns-address", "if set this, proxy will use this dns for resolve doamin").Short('q').Default("").String()
|
||||
httpArgs.DNSTTL = http.Flag("dns-ttl", "caching seconds of dns query result").Short('e').Default("300").Int()
|
||||
httpArgs.LocalKey = http.Flag("local-key", "the password for auto encrypt/decrypt local connection data").Short('z').Default("").String()
|
||||
httpArgs.ParentKey = http.Flag("parent-key", "the password for auto encrypt/decrypt parent connection data").Short('Z').Default("").String()
|
||||
httpArgs.LocalCompress = http.Flag("local-compress", "auto compress/decompress data on local connection").Short('m').Default("false").Bool()
|
||||
httpArgs.ParentCompress = http.Flag("parent-compress", "auto compress/decompress data on parent connection").Short('M').Default("false").Bool()
|
||||
|
||||
//########tcp#########
|
||||
tcp := app.Command("tcp", "proxy on tcp mode")
|
||||
@ -85,11 +124,8 @@ func initConfig() (err error) {
|
||||
tcpArgs.Timeout = tcp.Flag("timeout", "tcp timeout milliseconds when connect to real server or parent proxy").Short('e').Default("2000").Int()
|
||||
tcpArgs.ParentType = tcp.Flag("parent-type", "parent protocol type <tls|tcp|kcp|udp>").Short('T').Enum("tls", "tcp", "udp", "kcp")
|
||||
tcpArgs.LocalType = tcp.Flag("local-type", "local protocol type <tls|tcp|kcp>").Default("tcp").Short('t').Enum("tls", "tcp", "kcp")
|
||||
tcpArgs.PoolSize = tcp.Flag("pool-size", "conn pool size , which connect to parent proxy, zero: means turn off pool").Short('L').Default("0").Int()
|
||||
tcpArgs.CheckParentInterval = tcp.Flag("check-parent-interval", "check if proxy is okay every interval seconds,zero: means no check").Short('I').Default("3").Int()
|
||||
tcpArgs.Local = tcp.Flag("local", "local ip:port to listen").Short('p').Default(":33080").String()
|
||||
tcpArgs.KCPKey = tcp.Flag("kcp-key", "key for kcp encrypt/decrypt data").Short('B').Default("encrypt").String()
|
||||
tcpArgs.KCPMethod = tcp.Flag("kcp-method", "kcp encrypt/decrypt method").Short('M').Default("3des").String()
|
||||
tcpArgs.Jumper = tcp.Flag("jumper", "https or socks5 proxies used when connecting to parent, only worked of -T is tls or tcp, format is https://username:password@host:port https://host:port or socks5://username:password@host:port socks5://host:port").Short('J').Default("").String()
|
||||
|
||||
//########udp#########
|
||||
udp := app.Command("udp", "proxy on udp mode")
|
||||
@ -98,36 +134,42 @@ func initConfig() (err error) {
|
||||
udpArgs.KeyFile = udp.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
udpArgs.Timeout = udp.Flag("timeout", "tcp timeout milliseconds when connect to parent proxy").Short('t').Default("2000").Int()
|
||||
udpArgs.ParentType = udp.Flag("parent-type", "parent protocol type <tls|tcp|udp>").Short('T').Enum("tls", "tcp", "udp")
|
||||
udpArgs.PoolSize = udp.Flag("pool-size", "conn pool size , which connect to parent proxy, zero: means turn off pool").Short('L').Default("0").Int()
|
||||
udpArgs.CheckParentInterval = udp.Flag("check-parent-interval", "check if proxy is okay every interval seconds,zero: means no check").Short('I').Default("3").Int()
|
||||
udpArgs.Local = udp.Flag("local", "local ip:port to listen").Short('p').Default(":33080").String()
|
||||
|
||||
//########mux-server#########
|
||||
muxServer := app.Command("server", "proxy on mux server mode")
|
||||
muxServerArgs.Parent = muxServer.Flag("parent", "parent address, such as: \"23.32.32.19:28008\"").Default("").Short('P').String()
|
||||
muxServerArgs.ParentType = muxServer.Flag("parent-type", "parent protocol type <tls|tcp|kcp>").Default("tls").Short('T').Enum("tls", "tcp", "kcp")
|
||||
muxServerArgs.CertFile = muxServer.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
muxServerArgs.KeyFile = muxServer.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
muxServerArgs.Timeout = muxServer.Flag("timeout", "tcp timeout with milliseconds").Short('t').Default("2000").Int()
|
||||
muxServerArgs.Timeout = muxServer.Flag("timeout", "tcp timeout with milliseconds").Short('i').Default("2000").Int()
|
||||
muxServerArgs.IsUDP = muxServer.Flag("udp", "proxy on udp mux server mode").Default("false").Bool()
|
||||
muxServerArgs.Key = muxServer.Flag("k", "client key").Default("default").String()
|
||||
muxServerArgs.Route = muxServer.Flag("route", "local route to client's network, such as: PROTOCOL://LOCAL_IP:LOCAL_PORT@[CLIENT_KEY]CLIENT_LOCAL_HOST:CLIENT_LOCAL_PORT").Short('r').Default("").Strings()
|
||||
muxServerArgs.IsCompress = muxServer.Flag("c", "compress data when tcp mode").Default("false").Bool()
|
||||
muxServerArgs.IsCompress = muxServer.Flag("c", "compress data when tcp|tls mode").Default("false").Bool()
|
||||
muxServerArgs.SessionCount = muxServer.Flag("session-count", "session count which connect to bridge").Short('n').Default("10").Int()
|
||||
muxServerArgs.Jumper = muxServer.Flag("jumper", "https or socks5 proxies used when connecting to parent, only worked of -T is tls or tcp, format is https://username:password@host:port https://host:port or socks5://username:password@host:port socks5://host:port").Short('J').Default("").String()
|
||||
|
||||
//########mux-client#########
|
||||
muxClient := app.Command("client", "proxy on mux client mode")
|
||||
muxClientArgs.Parent = muxClient.Flag("parent", "parent address, such as: \"23.32.32.19:28008\"").Default("").Short('P').String()
|
||||
muxClientArgs.ParentType = muxClient.Flag("parent-type", "parent protocol type <tls|tcp|kcp>").Default("tls").Short('T').Enum("tls", "tcp", "kcp")
|
||||
muxClientArgs.CertFile = muxClient.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
muxClientArgs.KeyFile = muxClient.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
muxClientArgs.Timeout = muxClient.Flag("timeout", "tcp timeout with milliseconds").Short('t').Default("2000").Int()
|
||||
muxClientArgs.Timeout = muxClient.Flag("timeout", "tcp timeout with milliseconds").Short('i').Default("2000").Int()
|
||||
muxClientArgs.Key = muxClient.Flag("k", "key same with server").Default("default").String()
|
||||
muxClientArgs.IsCompress = muxClient.Flag("c", "compress data when tcp mode").Default("false").Bool()
|
||||
muxClientArgs.IsCompress = muxClient.Flag("c", "compress data when tcp|tls mode").Default("false").Bool()
|
||||
muxClientArgs.SessionCount = muxClient.Flag("session-count", "session count which connect to bridge").Short('n').Default("10").Int()
|
||||
muxClientArgs.Jumper = muxClient.Flag("jumper", "https or socks5 proxies used when connecting to parent, only worked of -T is tls or tcp, format is https://username:password@host:port https://host:port or socks5://username:password@host:port socks5://host:port").Short('J').Default("").String()
|
||||
|
||||
//########mux-bridge#########
|
||||
muxBridge := app.Command("bridge", "proxy on mux bridge mode")
|
||||
muxBridgeArgs.CertFile = muxBridge.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
muxBridgeArgs.KeyFile = muxBridge.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
muxBridgeArgs.Timeout = muxBridge.Flag("timeout", "tcp timeout with milliseconds").Short('t').Default("2000").Int()
|
||||
muxBridgeArgs.Timeout = muxBridge.Flag("timeout", "tcp timeout with milliseconds").Short('i').Default("2000").Int()
|
||||
muxBridgeArgs.Local = muxBridge.Flag("local", "local ip:port to listen").Short('p').Default(":33080").String()
|
||||
muxBridgeArgs.LocalType = muxBridge.Flag("local-type", "local protocol type <tls|tcp|kcp>").Default("tls").Short('t').Enum("tls", "tcp", "kcp")
|
||||
|
||||
//########tunnel-server#########
|
||||
tunnelServer := app.Command("tserver", "proxy on tunnel server mode")
|
||||
@ -138,6 +180,7 @@ func initConfig() (err error) {
|
||||
tunnelServerArgs.IsUDP = tunnelServer.Flag("udp", "proxy on udp tunnel server mode").Default("false").Bool()
|
||||
tunnelServerArgs.Key = tunnelServer.Flag("k", "client key").Default("default").String()
|
||||
tunnelServerArgs.Route = tunnelServer.Flag("route", "local route to client's network, such as: PROTOCOL://LOCAL_IP:LOCAL_PORT@[CLIENT_KEY]CLIENT_LOCAL_HOST:CLIENT_LOCAL_PORT").Short('r').Default("").Strings()
|
||||
tunnelServerArgs.Jumper = tunnelServer.Flag("jumper", "https or socks5 proxies used when connecting to parent, only worked of -T is tls or tcp, format is https://username:password@host:port https://host:port or socks5://username:password@host:port socks5://host:port").Short('J').Default("").String()
|
||||
|
||||
//########tunnel-client#########
|
||||
tunnelClient := app.Command("tclient", "proxy on tunnel client mode")
|
||||
@ -146,6 +189,7 @@ func initConfig() (err error) {
|
||||
tunnelClientArgs.KeyFile = tunnelClient.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
tunnelClientArgs.Timeout = tunnelClient.Flag("timeout", "tcp timeout with milliseconds").Short('t').Default("2000").Int()
|
||||
tunnelClientArgs.Key = tunnelClient.Flag("k", "key same with server").Default("default").String()
|
||||
tunnelClientArgs.Jumper = tunnelClient.Flag("jumper", "https or socks5 proxies used when connecting to parent, only worked of -T is tls or tcp, format is https://username:password@host:port https://host:port or socks5://username:password@host:port socks5://host:port").Short('J').Default("").String()
|
||||
|
||||
//########tunnel-bridge#########
|
||||
tunnelBridge := app.Command("tbridge", "proxy on tunnel bridge mode")
|
||||
@ -160,9 +204,8 @@ func initConfig() (err error) {
|
||||
socksArgs.ParentType = socks.Flag("parent-type", "parent protocol type <tls|tcp|kcp|ssh>").Default("tcp").Short('T').Enum("tls", "tcp", "kcp", "ssh")
|
||||
socksArgs.LocalType = socks.Flag("local-type", "local protocol type <tls|tcp|kcp>").Default("tcp").Short('t').Enum("tls", "tcp", "kcp")
|
||||
socksArgs.Local = socks.Flag("local", "local ip:port to listen").Short('p').Default(":33080").String()
|
||||
socksArgs.UDPParent = socks.Flag("udp-parent", "udp parent address, such as: \"23.32.32.19:33090\"").Default("").Short('X').String()
|
||||
socksArgs.UDPLocal = socks.Flag("udp-local", "udp local ip:port to listen").Short('x').Default(":33090").String()
|
||||
socksArgs.CertFile = socks.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
socksArgs.CaCertFile = socks.Flag("ca", "ca cert file for tls").Default("").String()
|
||||
socksArgs.KeyFile = socks.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
socksArgs.SSHUser = socks.Flag("ssh-user", "user for ssh").Short('u').Default("").String()
|
||||
socksArgs.SSHKeyFile = socks.Flag("ssh-key", "private key file for ssh").Short('S').Default("").String()
|
||||
@ -175,25 +218,149 @@ func initConfig() (err error) {
|
||||
socksArgs.Direct = socks.Flag("direct", "direct domain file , one domain each line").Default("direct").Short('d').String()
|
||||
socksArgs.AuthFile = socks.Flag("auth-file", "http basic auth file,\"username:password\" each line in file").Short('F').String()
|
||||
socksArgs.Auth = socks.Flag("auth", "socks auth username and password, mutiple user repeat -a ,such as: -a user1:pass1 -a user2:pass2").Short('a').Strings()
|
||||
socksArgs.KCPKey = socks.Flag("kcp-key", "key for kcp encrypt/decrypt data").Short('B').Default("encrypt").String()
|
||||
socksArgs.KCPMethod = socks.Flag("kcp-method", "kcp encrypt/decrypt method").Short('M').Default("3des").String()
|
||||
socksArgs.LocalIPS = socks.Flag("local bind ips", "if your host behind a nat,set your public ip here avoid dead loop").Short('g').Strings()
|
||||
socksArgs.LocalIPS = socks.Flag("local-bind-ips", "if your host behind a nat,set your public ip here avoid dead loop").Short('g').Strings()
|
||||
socksArgs.AuthURL = socks.Flag("auth-url", "auth username and password will send to this url,response http code equal to 'auth-code' means ok,others means fail.").Default("").String()
|
||||
socksArgs.AuthURLTimeout = socks.Flag("auth-timeout", "access 'auth-url' timeout milliseconds").Default("3000").Int()
|
||||
socksArgs.AuthURLOkCode = socks.Flag("auth-code", "access 'auth-url' success http code").Default("204").Int()
|
||||
socksArgs.AuthURLRetry = socks.Flag("auth-retry", "access 'auth-url' fail and retry count").Default("0").Int()
|
||||
socksArgs.DNSAddress = socks.Flag("dns-address", "if set this, proxy will use this dns for resolve doamin").Short('q').Default("").String()
|
||||
socksArgs.DNSTTL = socks.Flag("dns-ttl", "caching seconds of dns query result").Short('e').Default("300").Int()
|
||||
socksArgs.LocalKey = socks.Flag("local-key", "the password for auto encrypt/decrypt local connection data").Short('z').Default("").String()
|
||||
socksArgs.ParentKey = socks.Flag("parent-key", "the password for auto encrypt/decrypt parent connection data").Short('Z').Default("").String()
|
||||
socksArgs.LocalCompress = socks.Flag("local-compress", "auto compress/decompress data on local connection").Short('m').Default("false").Bool()
|
||||
socksArgs.ParentCompress = socks.Flag("parent-compress", "auto compress/decompress data on parent connection").Short('M').Default("false").Bool()
|
||||
|
||||
//########socks+http(s)#########
|
||||
sps := app.Command("sps", "proxy on socks+http(s) mode")
|
||||
spsArgs.Parent = sps.Flag("parent", "parent address, such as: \"23.32.32.19:28008\"").Default("").Short('P').String()
|
||||
spsArgs.CertFile = sps.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
spsArgs.KeyFile = sps.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
spsArgs.CaCertFile = sps.Flag("ca", "ca cert file for tls").Default("").String()
|
||||
spsArgs.Timeout = sps.Flag("timeout", "tcp timeout milliseconds when connect to real server or parent proxy").Short('i').Default("2000").Int()
|
||||
spsArgs.ParentType = sps.Flag("parent-type", "parent protocol type <tls|tcp|kcp>").Short('T').Enum("tls", "tcp", "kcp")
|
||||
spsArgs.LocalType = sps.Flag("local-type", "local protocol type <tls|tcp|kcp>").Default("tcp").Short('t').Enum("tls", "tcp", "kcp")
|
||||
spsArgs.Local = sps.Flag("local", "local ip:port to listen,multiple address use comma split,such as: 0.0.0.0:80,0.0.0.0:443").Short('p').Default(":33080").String()
|
||||
spsArgs.ParentServiceType = sps.Flag("parent-service-type", "parent service type <http|socks>").Short('S').Enum("http", "socks")
|
||||
spsArgs.DNSAddress = sps.Flag("dns-address", "if set this, proxy will use this dns for resolve doamin").Short('q').Default("").String()
|
||||
spsArgs.DNSTTL = sps.Flag("dns-ttl", "caching seconds of dns query result").Short('e').Default("300").Int()
|
||||
spsArgs.AuthFile = sps.Flag("auth-file", "http basic auth file,\"username:password\" each line in file").Short('F').String()
|
||||
spsArgs.Auth = sps.Flag("auth", "socks auth username and password, mutiple user repeat -a ,such as: -a user1:pass1 -a user2:pass2").Short('a').Strings()
|
||||
spsArgs.LocalIPS = sps.Flag("local-bind-ips", "if your host behind a nat,set your public ip here avoid dead loop").Short('g').Strings()
|
||||
spsArgs.AuthURL = sps.Flag("auth-url", "auth username and password will send to this url,response http code equal to 'auth-code' means ok,others means fail.").Default("").String()
|
||||
spsArgs.AuthURLTimeout = sps.Flag("auth-timeout", "access 'auth-url' timeout milliseconds").Default("3000").Int()
|
||||
spsArgs.AuthURLOkCode = sps.Flag("auth-code", "access 'auth-url' success http code").Default("204").Int()
|
||||
spsArgs.AuthURLRetry = sps.Flag("auth-retry", "access 'auth-url' fail and retry count").Default("0").Int()
|
||||
spsArgs.ParentAuth = sps.Flag("parent-auth", "parent socks auth username and password, such as: -A user1:pass1").Short('A').String()
|
||||
spsArgs.LocalKey = sps.Flag("local-key", "the password for auto encrypt/decrypt local connection data").Short('z').Default("").String()
|
||||
spsArgs.ParentKey = sps.Flag("parent-key", "the password for auto encrypt/decrypt parent connection data").Short('Z').Default("").String()
|
||||
spsArgs.LocalCompress = sps.Flag("local-compress", "auto compress/decompress data on local connection").Short('m').Default("false").Bool()
|
||||
spsArgs.ParentCompress = sps.Flag("parent-compress", "auto compress/decompress data on parent connection").Short('M').Default("false").Bool()
|
||||
spsArgs.DisableHTTP = sps.Flag("disable-http", "disable http(s) proxy").Default("false").Bool()
|
||||
spsArgs.DisableSocks5 = sps.Flag("disable-socks", "disable socks proxy").Default("false").Bool()
|
||||
|
||||
//########dns#########
|
||||
dns := app.Command("dns", "proxy on dns server mode")
|
||||
dnsArgs.Parent = dns.Flag("parent", "parent address, such as: \"23.32.32.19:28008\"").Default("").Short('P').String()
|
||||
dnsArgs.CertFile = dns.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
dnsArgs.KeyFile = dns.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
dnsArgs.CaCertFile = dns.Flag("ca", "ca cert file for tls").Default("").String()
|
||||
dnsArgs.Timeout = dns.Flag("timeout", "tcp timeout milliseconds when connect to real server or parent proxy").Short('i').Default("2000").Int()
|
||||
dnsArgs.ParentType = dns.Flag("parent-type", "parent protocol type <tls|tcp|kcp>").Short('T').Enum("tls", "tcp", "kcp")
|
||||
dnsArgs.Local = dns.Flag("local", "local ip:port to listen,multiple address use comma split,such as: 0.0.0.0:80,0.0.0.0:443").Short('p').Default(":53").String()
|
||||
dnsArgs.ParentServiceType = dns.Flag("parent-service-type", "parent service type <http|socks>").Short('S').Enum("http", "socks")
|
||||
dnsArgs.RemoteDNSAddress = dns.Flag("dns-address", "remote dns for resolve doamin").Short('q').Default("8.8.8.8:53").String()
|
||||
dnsArgs.DNSTTL = dns.Flag("dns-ttl", "caching seconds of dns query result").Short('e').Default("300").Int()
|
||||
dnsArgs.ParentAuth = dns.Flag("parent-auth", "parent socks auth username and password, such as: -A user1:pass1").Short('A').String()
|
||||
dnsArgs.ParentKey = dns.Flag("parent-key", "the password for auto encrypt/decrypt parent connection data").Short('Z').Default("").String()
|
||||
dnsArgs.ParentCompress = dns.Flag("parent-compress", "auto compress/decompress data on parent connection").Short('M').Default("false").Bool()
|
||||
dnsArgs.CacheFile = dns.Flag("cache-file", "dns result cached file").Short('f').Default(filepath.Join(path.Dir(os.Args[0]), "cache.dat")).String()
|
||||
dnsArgs.LocalSocks5Port = dns.Flag("socks-port", "local socks5 port").Short('s').Default("65501").String()
|
||||
|
||||
//########keygen#########
|
||||
keygen := app.Command("keygen", "create certificate for proxy")
|
||||
keygenArgs.CommonName = keygen.Flag("cn", "common name").Short('n').Default("").String()
|
||||
keygenArgs.CaName = keygen.Flag("ca", "ca name").Short('C').Default("").String()
|
||||
keygenArgs.CertName = keygen.Flag("cert", "cert name of sign to create").Short('c').Default("").String()
|
||||
keygenArgs.SignDays = keygen.Flag("days", "days of sign").Short('d').Default("365").Int()
|
||||
keygenArgs.Sign = keygen.Flag("sign", "cert is to signin").Short('s').Default("false").Bool()
|
||||
|
||||
//parse args
|
||||
serviceName := kingpin.MustParse(app.Parse(os.Args[1:]))
|
||||
flags := log.Ldate
|
||||
|
||||
isDebug = *debug
|
||||
|
||||
//set kcp config
|
||||
|
||||
switch *kcpArgs.Mode {
|
||||
case "normal":
|
||||
*kcpArgs.NoDelay, *kcpArgs.Interval, *kcpArgs.Resend, *kcpArgs.NoCongestion = 0, 40, 2, 1
|
||||
case "fast":
|
||||
*kcpArgs.NoDelay, *kcpArgs.Interval, *kcpArgs.Resend, *kcpArgs.NoCongestion = 0, 30, 2, 1
|
||||
case "fast2":
|
||||
*kcpArgs.NoDelay, *kcpArgs.Interval, *kcpArgs.Resend, *kcpArgs.NoCongestion = 1, 20, 2, 1
|
||||
case "fast3":
|
||||
*kcpArgs.NoDelay, *kcpArgs.Interval, *kcpArgs.Resend, *kcpArgs.NoCongestion = 1, 10, 2, 1
|
||||
}
|
||||
pass := pbkdf2.Key([]byte(*kcpArgs.Key), []byte("snail007-goproxy"), 4096, 32, sha1.New)
|
||||
|
||||
switch *kcpArgs.Crypt {
|
||||
case "sm4":
|
||||
kcpArgs.Block, _ = kcp.NewSM4BlockCrypt(pass[:16])
|
||||
case "tea":
|
||||
kcpArgs.Block, _ = kcp.NewTEABlockCrypt(pass[:16])
|
||||
case "xor":
|
||||
kcpArgs.Block, _ = kcp.NewSimpleXORBlockCrypt(pass)
|
||||
case "none":
|
||||
kcpArgs.Block, _ = kcp.NewNoneBlockCrypt(pass)
|
||||
case "aes-128":
|
||||
kcpArgs.Block, _ = kcp.NewAESBlockCrypt(pass[:16])
|
||||
case "aes-192":
|
||||
kcpArgs.Block, _ = kcp.NewAESBlockCrypt(pass[:24])
|
||||
case "blowfish":
|
||||
kcpArgs.Block, _ = kcp.NewBlowfishBlockCrypt(pass)
|
||||
case "twofish":
|
||||
kcpArgs.Block, _ = kcp.NewTwofishBlockCrypt(pass)
|
||||
case "cast5":
|
||||
kcpArgs.Block, _ = kcp.NewCast5BlockCrypt(pass[:16])
|
||||
case "3des":
|
||||
kcpArgs.Block, _ = kcp.NewTripleDESBlockCrypt(pass[:24])
|
||||
case "xtea":
|
||||
kcpArgs.Block, _ = kcp.NewXTEABlockCrypt(pass[:16])
|
||||
case "salsa20":
|
||||
kcpArgs.Block, _ = kcp.NewSalsa20BlockCrypt(pass)
|
||||
default:
|
||||
*kcpArgs.Crypt = "aes"
|
||||
kcpArgs.Block, _ = kcp.NewAESBlockCrypt(pass)
|
||||
}
|
||||
//attach kcp config
|
||||
tcpArgs.KCP = kcpArgs
|
||||
httpArgs.KCP = kcpArgs
|
||||
socksArgs.KCP = kcpArgs
|
||||
spsArgs.KCP = kcpArgs
|
||||
muxBridgeArgs.KCP = kcpArgs
|
||||
muxServerArgs.KCP = kcpArgs
|
||||
muxClientArgs.KCP = kcpArgs
|
||||
dnsArgs.KCP = kcpArgs
|
||||
|
||||
log := logger.New(os.Stderr, "", logger.Ldate|logger.Ltime)
|
||||
|
||||
flags := logger.Ldate
|
||||
if *debug {
|
||||
flags |= log.Lshortfile | log.Lmicroseconds
|
||||
flags |= logger.Lshortfile | logger.Lmicroseconds
|
||||
cpuProfilingFile, _ = os.Create("cpu.prof")
|
||||
memProfilingFile, _ = os.Create("memory.prof")
|
||||
blockProfilingFile, _ = os.Create("block.prof")
|
||||
goroutineProfilingFile, _ = os.Create("goroutine.prof")
|
||||
threadcreateProfilingFile, _ = os.Create("threadcreate.prof")
|
||||
pprof.StartCPUProfile(cpuProfilingFile)
|
||||
} else {
|
||||
flags |= log.Ltime
|
||||
flags |= logger.Ltime
|
||||
}
|
||||
log.SetFlags(flags)
|
||||
|
||||
if *logfile != "" {
|
||||
if *nolog {
|
||||
log.SetOutput(ioutil.Discard)
|
||||
} else if *logfile != "" {
|
||||
f, e := os.OpenFile(*logfile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
|
||||
if e != nil {
|
||||
log.Fatal(e)
|
||||
@ -227,6 +394,7 @@ func initConfig() (err error) {
|
||||
for {
|
||||
if cmd != nil {
|
||||
cmd.Process.Kill()
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
cmd = exec.Command(os.Args[0], args...)
|
||||
cmdReaderStderr, err := cmd.StderrPipe()
|
||||
@ -262,26 +430,52 @@ func initConfig() (err error) {
|
||||
continue
|
||||
}
|
||||
log.Printf("worker %s [PID] %d unexpected exited, restarting...\n", os.Args[0], pid)
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}()
|
||||
return
|
||||
}
|
||||
if *logfile == "" {
|
||||
poster()
|
||||
if *debug {
|
||||
log.Println("[profiling] cpu profiling save to file : cpu.prof")
|
||||
log.Println("[profiling] memory profiling save to file : memory.prof")
|
||||
log.Println("[profiling] block profiling save to file : block.prof")
|
||||
log.Println("[profiling] goroutine profiling save to file : goroutine.prof")
|
||||
log.Println("[profiling] threadcreate profiling save to file : threadcreate.prof")
|
||||
}
|
||||
}
|
||||
//regist services and run service
|
||||
services.Regist("http", services.NewHTTP(), httpArgs)
|
||||
services.Regist("tcp", services.NewTCP(), tcpArgs)
|
||||
services.Regist("udp", services.NewUDP(), udpArgs)
|
||||
services.Regist("tserver", services.NewTunnelServerManager(), tunnelServerArgs)
|
||||
services.Regist("tclient", services.NewTunnelClient(), tunnelClientArgs)
|
||||
services.Regist("tbridge", services.NewTunnelBridge(), tunnelBridgeArgs)
|
||||
services.Regist("server", services.NewMuxServerManager(), muxServerArgs)
|
||||
services.Regist("client", services.NewMuxClient(), muxClientArgs)
|
||||
services.Regist("bridge", services.NewMuxBridge(), muxBridgeArgs)
|
||||
services.Regist("socks", services.NewSocks(), socksArgs)
|
||||
service, err = services.Run(serviceName)
|
||||
//regist services and run service
|
||||
switch serviceName {
|
||||
case "http":
|
||||
services.Regist(serviceName, httpx.NewHTTP(), httpArgs, log)
|
||||
case "tcp":
|
||||
services.Regist(serviceName, tcpx.NewTCP(), tcpArgs, log)
|
||||
case "udp":
|
||||
services.Regist(serviceName, udpx.NewUDP(), udpArgs, log)
|
||||
case "tserver":
|
||||
services.Regist(serviceName, tunnel.NewTunnelServerManager(), tunnelServerArgs, log)
|
||||
case "tclient":
|
||||
services.Regist(serviceName, tunnel.NewTunnelClient(), tunnelClientArgs, log)
|
||||
case "tbridge":
|
||||
services.Regist(serviceName, tunnel.NewTunnelBridge(), tunnelBridgeArgs, log)
|
||||
case "server":
|
||||
services.Regist(serviceName, mux.NewMuxServerManager(), muxServerArgs, log)
|
||||
case "client":
|
||||
services.Regist(serviceName, mux.NewMuxClient(), muxClientArgs, log)
|
||||
case "bridge":
|
||||
services.Regist(serviceName, mux.NewMuxBridge(), muxBridgeArgs, log)
|
||||
case "socks":
|
||||
services.Regist(serviceName, socksx.NewSocks(), socksArgs, log)
|
||||
case "sps":
|
||||
services.Regist(serviceName, spsx.NewSPS(), spsArgs, log)
|
||||
case "dns":
|
||||
services.Regist(serviceName, sdk.NewDNS(), dnsArgs, log)
|
||||
case "keygen":
|
||||
services.Regist(serviceName, keygenx.NewKeygen(), keygenArgs, log)
|
||||
}
|
||||
|
||||
service, err = services.Run(serviceName, nil)
|
||||
if err != nil {
|
||||
log.Fatalf("run service [%s] fail, ERR:%s", serviceName, err)
|
||||
}
|
||||
@ -300,3 +494,14 @@ func poster() {
|
||||
|
||||
v%s`+" by snail , blog : http://www.host900.com/\n\n", APP_VERSION)
|
||||
}
|
||||
func saveProfiling() {
|
||||
goroutine := pprof.Lookup("goroutine")
|
||||
goroutine.WriteTo(goroutineProfilingFile, 1)
|
||||
heap := pprof.Lookup("heap")
|
||||
heap.WriteTo(memProfilingFile, 1)
|
||||
block := pprof.Lookup("block")
|
||||
block.WriteTo(blockProfilingFile, 1)
|
||||
threadcreate := pprof.Lookup("threadcreate")
|
||||
threadcreate.WriteTo(threadcreateProfilingFile, 1)
|
||||
pprof.StopCPUProfile()
|
||||
}
|
||||
|
||||
BIN
docs/images/fxdl.png
Normal file
|
After Width: | Height: | Size: 34 KiB |
BIN
docs/images/http-1.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
docs/images/http-2.png
Normal file
|
After Width: | Height: | Size: 22 KiB |
BIN
docs/images/http-kcp.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
docs/images/http-ssh-1.png
Normal file
|
After Width: | Height: | Size: 29 KiB |
BIN
docs/images/http-tls-2.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
docs/images/http-tls-3.png
Normal file
|
After Width: | Height: | Size: 30 KiB |
BIN
docs/images/socks-2.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
docs/images/socks-ssh.png
Normal file
|
After Width: | Height: | Size: 24 KiB |
BIN
docs/images/socks-tls-2.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
docs/images/socks-tls-3.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
docs/images/sps-tls.png
Normal file
|
After Width: | Height: | Size: 24 KiB |
BIN
docs/images/tcp-1.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
docs/images/tcp-2.png
Normal file
|
After Width: | Height: | Size: 17 KiB |
BIN
docs/images/tcp-3.png
Normal file
|
After Width: | Height: | Size: 22 KiB |
BIN
docs/images/tcp-tls-2.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
docs/images/tcp-tls-3.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
docs/images/udp-1.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
docs/images/udp-2.png
Normal file
|
After Width: | Height: | Size: 20 KiB |
BIN
docs/images/udp-3.png
Normal file
|
After Width: | Height: | Size: 23 KiB |
BIN
docs/images/udp-tls-2.png
Normal file
|
After Width: | Height: | Size: 22 KiB |
BIN
docs/images/udp-tls-3.png
Normal file
|
After Width: | Height: | Size: 26 KiB |
25
docs/old-release.md
Normal file
@ -0,0 +1,25 @@
|
||||
# Old Versions of Proxy
|
||||
|
||||
- [v5.3手册](https://github.com/snail007/goproxy/tree/v5.3)
|
||||
- [v5.2手册](https://github.com/snail007/goproxy/tree/v5.2)
|
||||
- [v5.1手册](https://github.com/snail007/goproxy/tree/v5.1)
|
||||
- [v5.0手册](https://github.com/snail007/goproxy/tree/v5.0)
|
||||
- [v4.9手册](https://github.com/snail007/goproxy/tree/v4.9)
|
||||
- [v4.8手册](https://github.com/snail007/goproxy/tree/v4.8)
|
||||
- [v4.7手册](https://github.com/snail007/goproxy/tree/v4.7)
|
||||
- [v4.6手册](https://github.com/snail007/goproxy/tree/v4.6)
|
||||
- [v4.5手册](https://github.com/snail007/goproxy/tree/v4.5)
|
||||
- [v4.4手册](https://github.com/snail007/goproxy/tree/v4.4)
|
||||
- [v4.3手册](https://github.com/snail007/goproxy/tree/v4.3)
|
||||
- [v4.2手册](https://github.com/snail007/goproxy/tree/v4.2)
|
||||
- [v4.0-v4.1手册](https://github.com/snail007/goproxy/tree/v4.1)
|
||||
- [v3.9手册](https://github.com/snail007/goproxy/tree/v3.9)
|
||||
- [v3.8手册](https://github.com/snail007/goproxy/tree/v3.8)
|
||||
- [v3.6-v3.7手册](https://github.com/snail007/goproxy/tree/v3.6)
|
||||
- [v3.5手册](https://github.com/snail007/goproxy/tree/v3.5)
|
||||
- [v3.4手册](https://github.com/snail007/goproxy/tree/v3.4)
|
||||
- [v3.3手册](https://github.com/snail007/goproxy/tree/v3.3)
|
||||
- [v3.2手册](https://github.com/snail007/goproxy/tree/v3.2)
|
||||
- [v3.1手册](https://github.com/snail007/goproxy/tree/v3.1)
|
||||
- [v3.0手册](https://github.com/snail007/goproxy/tree/v3.0)
|
||||
- [v2.x手册](https://github.com/snail007/goproxy/tree/v2.2)
|
||||
27
gui/README.md
Normal file
@ -0,0 +1,27 @@
|
||||
# Proxy-GUI
|
||||
基于proxy的各平台SDK,作者和众多热心人士开发了各平台的GUI版本的proxy,下面分平台介绍.
|
||||
|
||||
## Windows
|
||||
|
||||
- 官方java版本,项目主页:[goproxy-jui](https://github.com/snail007/goproxy-jui)
|
||||
|
||||
## Linux
|
||||
|
||||
- 官方java版本,项目主页:[goproxy-jui](https://github.com/snail007/goproxy-jui)
|
||||
|
||||
## MacOS
|
||||
|
||||
- Coming Soon ...
|
||||
|
||||
## Android
|
||||
|
||||
- proxy-go,一个非官方实现版本,界面比较简陋,但是够用.下载地址:[proxy-go](https://github.com/snail007/goproxy-gui-stuff/releases/tag/proxy-go-release)
|
||||
|
||||
|
||||
## IOS
|
||||
|
||||
- Coming Soon ...
|
||||
|
||||
## 跨平台
|
||||
|
||||
- proxy-web,一个跨平台的web UI版本,项目主页:[proxy-web](https://github.com/yincongcyincong/proxy-web)
|
||||
@ -5,7 +5,7 @@ if [ -e /tmp/proxy ]; then
|
||||
fi
|
||||
mkdir /tmp/proxy
|
||||
cd /tmp/proxy
|
||||
wget https://github.com/snail007/goproxy/releases/download/v4.2/proxy-linux-amd64.tar.gz
|
||||
wget https://github.com/snail007/goproxy/releases/download/v5.4/proxy-linux-amd64.tar.gz
|
||||
|
||||
# #install proxy
|
||||
tar zxvf proxy-linux-amd64.tar.gz
|
||||
@ -19,7 +19,7 @@ fi
|
||||
|
||||
if [ ! -e /etc/proxy/proxy.crt ]; then
|
||||
cd /etc/proxy/
|
||||
proxy keygen >/dev/null 2>&1
|
||||
proxy keygen -C proxy >/dev/null 2>&1
|
||||
fi
|
||||
rm -rf /tmp/proxy
|
||||
echo "install done"
|
||||
|
||||
@ -1,3 +0,0 @@
|
||||
#!/bin/bash
|
||||
openssl genrsa -out proxy.key 2048
|
||||
openssl req -new -key proxy.key -x509 -days 3650 -out proxy.crt -subj /C=CN/ST=BJ/O="Localhost Ltd"/CN=proxy
|
||||
8
main.go
@ -4,11 +4,12 @@ import (
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"proxy/services"
|
||||
"syscall"
|
||||
|
||||
"github.com/snail007/goproxy/services"
|
||||
)
|
||||
|
||||
const APP_VERSION = "4.2"
|
||||
const APP_VERSION = "5.4"
|
||||
|
||||
func main() {
|
||||
err := initConfig()
|
||||
@ -40,6 +41,9 @@ func Clean(s *services.Service) {
|
||||
log.Printf("clean process %d", cmd.Process.Pid)
|
||||
cmd.Process.Kill()
|
||||
}
|
||||
if isDebug {
|
||||
saveProfiling()
|
||||
}
|
||||
cleanupDone <- true
|
||||
}
|
||||
}()
|
||||
|
||||
96
release.sh
@ -1,72 +1,74 @@
|
||||
#!/bin/bash
|
||||
VER="4.2"
|
||||
VER="5.4"
|
||||
RELEASE="release-${VER}"
|
||||
rm -rf .cert
|
||||
mkdir .cert
|
||||
go build
|
||||
go build -o proxy
|
||||
cd .cert
|
||||
../proxy keygen
|
||||
../proxy keygen -C proxy
|
||||
cd ..
|
||||
rm -rf ${RELEASE}
|
||||
mkdir ${RELEASE}
|
||||
#linux
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build && tar zcfv "${RELEASE}/proxy-linux-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build && tar zcfv "${RELEASE}/proxy-linux-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build && tar zcfv "${RELEASE}/proxy-linux-arm-v6.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 GOARM=6 go build && tar zcfv "${RELEASE}/proxy-linux-arm64-v6.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build && tar zcfv "${RELEASE}/proxy-linux-arm-v7.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 GOARM=7 go build && tar zcfv "${RELEASE}/proxy-linux-arm64-v7.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build && tar zcfv "${RELEASE}/proxy-linux-arm-v5.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 GOARM=5 go build && tar zcfv "${RELEASE}/proxy-linux-arm64-v5.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build && tar zcfv "${RELEASE}/proxy-linux-mips.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build && tar zcfv "${RELEASE}/proxy-linux-mips64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build && tar zcfv "${RELEASE}/proxy-linux-mips64le.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build && tar zcfv "${RELEASE}/proxy-linux-mipsle.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=ppc64 go build && tar zcfv "${RELEASE}/proxy-linux-ppc64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=ppc64le go build && tar zcfv "${RELEASE}/proxy-linux-ppc64le.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=s390x go build && tar zcfv "${RELEASE}/proxy-linux-s390x.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -o proxy && tar zcfv "${RELEASE}/proxy-linux-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o proxy && tar zcfv "${RELEASE}/proxy-linux-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -o proxy && tar zcfv "${RELEASE}/proxy-linux-arm-v6.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 GOARM=6 go build -o proxy && tar zcfv "${RELEASE}/proxy-linux-arm64-v6.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -o proxy && tar zcfv "${RELEASE}/proxy-linux-arm-v7.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 GOARM=7 go build -o proxy && tar zcfv "${RELEASE}/proxy-linux-arm64-v7.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build -o proxy && tar zcfv "${RELEASE}/proxy-linux-arm-v5.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 GOARM=5 go build -o proxy && tar zcfv "${RELEASE}/proxy-linux-arm64-v5.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -o proxy && tar zcfv "${RELEASE}/proxy-linux-mips.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -o proxy && tar zcfv "${RELEASE}/proxy-linux-mips64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -o proxy && tar zcfv "${RELEASE}/proxy-linux-mips64le.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -o proxy && tar zcfv "${RELEASE}/proxy-linux-mipsle.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=ppc64 go build -o proxy && tar zcfv "${RELEASE}/proxy-linux-ppc64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=ppc64le go build -o proxy && tar zcfv "${RELEASE}/proxy-linux-ppc64le.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=s390x go build -o proxy && tar zcfv "${RELEASE}/proxy-linux-s390x.tar.gz" proxy direct blocked
|
||||
#android
|
||||
CGO_ENABLED=0 GOOS=android GOARCH=386 go build && tar zcfv "${RELEASE}/proxy-android-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=android GOARCH=amd64 go build && tar zcfv "${RELEASE}/proxy-android-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=android GOARCH=arm go build && tar zcfv "${RELEASE}/proxy-android-arm.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=android GOARCH=arm64 go build && tar zcfv "${RELEASE}/proxy-android-arm64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=android GOARCH=386 go build -o proxy && tar zcfv "${RELEASE}/proxy-android-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=android GOARCH=amd64 go build -o proxy && tar zcfv "${RELEASE}/proxy-android-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=android GOARCH=arm go build -o proxy && tar zcfv "${RELEASE}/proxy-android-arm.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=android GOARCH=arm64 go build -o proxy && tar zcfv "${RELEASE}/proxy-android-arm64.tar.gz" proxy direct blocked
|
||||
#darwin
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=386 go build && tar zcfv "${RELEASE}/proxy-darwin-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build && tar zcfv "${RELEASE}/proxy-darwin-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm go build && tar zcfv "${RELEASE}/proxy-darwin-arm.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build && tar zcfv "${RELEASE}/proxy-darwin-arm64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=386 go build -o proxy && tar zcfv "${RELEASE}/proxy-darwin-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -o proxy && tar zcfv "${RELEASE}/proxy-darwin-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm go build -o proxy && tar zcfv "${RELEASE}/proxy-darwin-arm.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -o proxy && tar zcfv "${RELEASE}/proxy-darwin-arm64.tar.gz" proxy direct blocked
|
||||
#dragonfly
|
||||
CGO_ENABLED=0 GOOS=dragonfly GOARCH=amd64 go build && tar zcfv "${RELEASE}/proxy-dragonfly-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=dragonfly GOARCH=amd64 go build -o proxy && tar zcfv "${RELEASE}/proxy-dragonfly-amd64.tar.gz" proxy direct blocked
|
||||
#freebsd
|
||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build && tar zcfv "${RELEASE}/proxy-freebsd-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build && tar zcfv "${RELEASE}/proxy-freebsd-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build && tar zcfv "${RELEASE}/proxy-freebsd-arm.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -o proxy && tar zcfv "${RELEASE}/proxy-freebsd-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -o proxy && tar zcfv "${RELEASE}/proxy-freebsd-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -o proxy && tar zcfv "${RELEASE}/proxy-freebsd-arm.tar.gz" proxy direct blocked
|
||||
#nacl
|
||||
CGO_ENABLED=0 GOOS=nacl GOARCH=386 go build && tar zcfv "${RELEASE}/proxy-nacl-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=nacl GOARCH=amd64p32 go build && tar zcfv "${RELEASE}/proxy-nacl-amd64p32.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=nacl GOARCH=arm go build && tar zcfv "${RELEASE}/proxy-nacl-arm.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=nacl GOARCH=386 go build -o proxy && tar zcfv "${RELEASE}/proxy-nacl-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=nacl GOARCH=amd64p32 go build -o proxy && tar zcfv "${RELEASE}/proxy-nacl-amd64p32.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=nacl GOARCH=arm go build -o proxy && tar zcfv "${RELEASE}/proxy-nacl-arm.tar.gz" proxy direct blocked
|
||||
#netbsd
|
||||
CGO_ENABLED=0 GOOS=netbsd GOARCH=386 go build && tar zcfv "${RELEASE}/proxy-netbsd-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=netbsd GOARCH=amd64 go build && tar zcfv "${RELEASE}/proxy-netbsd-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=netbsd GOARCH=arm go build && tar zcfv "${RELEASE}/proxy-netbsd-arm.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=netbsd GOARCH=386 go build -o proxy && tar zcfv "${RELEASE}/proxy-netbsd-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=netbsd GOARCH=amd64 go build -o proxy && tar zcfv "${RELEASE}/proxy-netbsd-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=netbsd GOARCH=arm go build -o proxy && tar zcfv "${RELEASE}/proxy-netbsd-arm.tar.gz" proxy direct blocked
|
||||
#openbsd
|
||||
CGO_ENABLED=0 GOOS=openbsd GOARCH=386 go build && tar zcfv "${RELEASE}/proxy-openbsd-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=openbsd GOARCH=amd64 go build && tar zcfv "${RELEASE}/proxy-openbsd-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=openbsd GOARCH=arm go build && tar zcfv "${RELEASE}/proxy-openbsd-arm.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=openbsd GOARCH=386 go build -o proxy && tar zcfv "${RELEASE}/proxy-openbsd-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=openbsd GOARCH=amd64 go build -o proxy && tar zcfv "${RELEASE}/proxy-openbsd-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=openbsd GOARCH=arm go build -o proxy && tar zcfv "${RELEASE}/proxy-openbsd-arm.tar.gz" proxy direct blocked
|
||||
#plan9
|
||||
CGO_ENABLED=0 GOOS=plan9 GOARCH=386 go build && tar zcfv "${RELEASE}/proxy-plan9-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=plan9 GOARCH=amd64 go build && tar zcfv "${RELEASE}/proxy-plan9-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=plan9 GOARCH=arm go build && tar zcfv "${RELEASE}/proxy-plan9-arm.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=plan9 GOARCH=386 go build -o proxy && tar zcfv "${RELEASE}/proxy-plan9-386.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=plan9 GOARCH=amd64 go build -o proxy && tar zcfv "${RELEASE}/proxy-plan9-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=plan9 GOARCH=arm go build -o proxy && tar zcfv "${RELEASE}/proxy-plan9-arm.tar.gz" proxy direct blocked
|
||||
#solaris
|
||||
CGO_ENABLED=0 GOOS=solaris GOARCH=amd64 go build && tar zcfv "${RELEASE}/proxy-solaris-amd64.tar.gz" proxy direct blocked
|
||||
CGO_ENABLED=0 GOOS=solaris GOARCH=amd64 go build -o proxy && tar zcfv "${RELEASE}/proxy-solaris-amd64.tar.gz" proxy direct blocked
|
||||
#windows
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build && tar zcfv "${RELEASE}/proxy-windows-386.tar.gz" proxy.exe direct blocked .cert/proxy.crt .cert/proxy.key
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build && tar zcfv "${RELEASE}/proxy-windows-amd64.tar.gz" proxy.exe direct blocked .cert/proxy.crt .cert/proxy.key
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags="-H=windowsgui" -o proxy-noconsole.exe
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -o proxy.exe && tar zcfv "${RELEASE}/proxy-windows-386.tar.gz" proxy.exe proxy-noconsole.exe direct blocked .cert/proxy.crt .cert/proxy.key
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="-H=windowsgui" -o proxy-noconsole.exe
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o proxy.exe && tar zcfv "${RELEASE}/proxy-windows-amd64.tar.gz" proxy.exe proxy-noconsole.exe direct blocked .cert/proxy.crt .cert/proxy.key
|
||||
|
||||
rm -rf proxy proxy.exe .cert
|
||||
rm -rf proxy proxy.exe proxy-noconsole.exe .cert
|
||||
|
||||
#todo
|
||||
#1.release.sh VER="xxx"
|
||||
#2.main.go APP_VERSION="xxx"
|
||||
#3.install_auto.sh goproxy/releases/download/vxxx
|
||||
#4.README goproxy/releases/download/vxxx
|
||||
#4.README goproxy/releases/download/vxxx
|
||||
|
||||
21
sdk/CHANGELOG
Normal file
@ -0,0 +1,21 @@
|
||||
SDK更新日志
|
||||
v5.4
|
||||
1.去掉了无用参数
|
||||
|
||||
|
||||
v5.3
|
||||
1.增加了支持日志输出回调的方法:
|
||||
StartWithLog(serviceID, serviceArgsStr string, loggerCallback LogCallback)
|
||||
2.优化了socks_client握手端口判断,避免了sstap测试UDP失败的问题..
|
||||
3.修复了HTTP(S)\SPS反向代理无法正常工作的问题.
|
||||
4.优化了智能判断,减少不必要的DNS解析.
|
||||
5.重构了SOCKS和SPS的UDP功能,基于UDP的游戏加速嗖嗖的.
|
||||
|
||||
v4.9
|
||||
1.修复了HTTP Basic代理返回不合适的头部,导致浏览器不会弹框,个别代理插件无法认证的问题.
|
||||
2.内网穿透切换smux到yamux.
|
||||
3.优化了HTTP(S)\SOCKS5代理--always的处理逻辑.
|
||||
|
||||
v4.8
|
||||
1.修复了多个服务同时开启日志,只会输出到最后一个日志文件的bug.
|
||||
2.增加了获取sdk版本的Version()方法.
|
||||
259
sdk/README.md
Normal file
@ -0,0 +1,259 @@
|
||||
|
||||
# Proxy SDK 使用说明
|
||||
|
||||
支持以下平台:
|
||||
- Android,`.arr`库
|
||||
- IOS,`.framework`库
|
||||
- Windows,`.dll`库
|
||||
- Linux,`.so`库
|
||||
- MacOS,`.dylib`库
|
||||
|
||||
proxy使用gombile实现了一份go代码编译为android和ios平台下面可以直接调用的sdk类库,
|
||||
另外还为linux和windows,MacOS提供sdk支持,基于这些类库,APP开发者可以轻松的开发出各种形式的代理工具。
|
||||
|
||||
# 下面分平台介绍SDK的用法
|
||||
|
||||
## Android SDK
|
||||
|
||||
[](https://github.com/snail007/goproxy-sdk-android/) []() [](https://github.com/snail007/goproxy-sdk-android/releases) [](https://github.com/snail007/goproxy-sdk-android/releases)
|
||||
|
||||
[点击下载Android-SDK](https://github.com/snail007/goproxy-sdk-android/releases)
|
||||
在Android系统提供的sdk形式是一个后缀为.aar的类库文件,开发的时候只需要把arr类库文件引入android项目即可.
|
||||
|
||||
### Android-SDK使用实例
|
||||
|
||||
#### 1.导入包
|
||||
|
||||
```java
|
||||
import snail007.proxy.Proxy
|
||||
```
|
||||
|
||||
#### 2.启动一个服务
|
||||
|
||||
```java
|
||||
String serviceID="http01";//这里serviceID是自定义的唯一标识字符串,保证每个启动的服务不一样即可
|
||||
String serviceArgs="http -p :8080";
|
||||
String err=Proxy.start(serviceID,serviceArgs);
|
||||
if (!err.isEmpty()){
|
||||
//启动失败
|
||||
System.out.println("start fail,error:"+err);
|
||||
}else{
|
||||
//启动成功
|
||||
}
|
||||
```
|
||||
|
||||
#### 3.停止一个服务
|
||||
|
||||
```java
|
||||
String serviceID="http01";
|
||||
Proxy.stop(serviceID);
|
||||
//停止完毕
|
||||
|
||||
```
|
||||
|
||||
## IOS SDK
|
||||
|
||||
[](https://github.com/snail007/goproxy-sdk-ios/) []() [](https://github.com/snail007/goproxy-sdk-ios/releases) [](https://github.com/snail007/goproxy-sdk-ios/releases)
|
||||
|
||||
[点击下载IOS-SDK](https://github.com/snail007/goproxy-sdk-ios/releases)
|
||||
在IOS系统提供的sdk形式是一个后缀为.framework的类库文件夹,开发的时候只需要把类库文件引入项目,然后调用方法即可.
|
||||
|
||||
### IOS-SDK使用实例
|
||||
|
||||
#### 导入包
|
||||
|
||||
```objc
|
||||
#import <Proxy/Proxy.objc.h>
|
||||
```
|
||||
|
||||
#### 2.启动一个服务
|
||||
|
||||
```objc
|
||||
-(IBAction)doStart:(id)sender
|
||||
{
|
||||
//这里serviceID是自定义的唯一标识字符串,保证每个启动的服务不一样
|
||||
NSString *serviceID = @"http01";
|
||||
NSString *serviceArgs = @"http -p :8080";
|
||||
NSString *error = ProxyStart(serviceID,serviceArgs);
|
||||
|
||||
if (error != nil && error.length > 0)
|
||||
{
|
||||
NSLog(@"start error %@",error);
|
||||
}else{
|
||||
NSLog(@"启动成功");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 3.停止一个服务
|
||||
|
||||
```objc
|
||||
-(IBAction)doStop:(id)sender
|
||||
{
|
||||
NSString *serviceID = @"http01";
|
||||
ProxyStop(serviceID);
|
||||
//停止完毕
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Windows SDK
|
||||
[](https://github.com/snail007/goproxy-sdk-windows/) []() [](https://github.com/snail007/goproxy-sdk-windows/releases) [](https://github.com/snail007/goproxy-sdk-windows/releases)
|
||||
|
||||
[点击下载Windows-SDK](https://github.com/snail007/goproxy-sdk-windows/releases)
|
||||
在Windows系统提供的sdk形式是一个后缀为.dll的类库文件,开发的时候只需要把dll类库文件加载,然后调用方法即可.
|
||||
|
||||
### Windows-SDK使用实例
|
||||
C++示例,不需要包含头文件,只需要加载proxy-sdk.dll即可,ieshims.dll需要和proxy-sdk.dll在一起。
|
||||
作者:[yjbdsky](https://github.com/yjbdsky)
|
||||
|
||||
```cpp
|
||||
#include <stdio.h>
|
||||
#include<stdlib.h>
|
||||
#include <string.h>
|
||||
#include<pthread.h>
|
||||
#include<Windows.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef char *(*GOSTART)(char *s);
|
||||
typedef char *(*GOSTOP)(char *s);
|
||||
typedef int(*GOISRUN)(char *s);
|
||||
HMODULE GODLL = LoadLibrary("proxy-sdk.dll");
|
||||
|
||||
char * Start(char * p0,char * p1)
|
||||
{
|
||||
if (GODLL != NULL)
|
||||
{
|
||||
GOSTART gostart = *(GOSTART)(GetProcAddress(GODLL, "Start"));
|
||||
if (gostart != NULL){
|
||||
printf("%s:%s\n",p0, p1);
|
||||
char *ret = gostart(p0,p1);
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
return "Cannot Find dll";
|
||||
}
|
||||
char * Stop(char * p)
|
||||
{
|
||||
if (GODLL != NULL)
|
||||
{
|
||||
GOSTOP gostop = *(GOSTOP)(GetProcAddress(GODLL, "Stop"));
|
||||
if (gostop != NULL){
|
||||
printf("%s\n", p);
|
||||
char *ret = gostop(p);
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
return "Cannot Find dll";
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
//这里p0是自定义的唯一标识字符串,保证每个启动的服务不一样
|
||||
char *p0 = "http01";
|
||||
char *p1 = "http -t tcp -p :38080";
|
||||
printf("This is demo application.\n");
|
||||
//启动服务,返回空字符串说明启动成功;返回非空字符串说明启动失败,返回的字符串是错误原因
|
||||
printf("start result %s\n", Start(p0,p1));
|
||||
//停止服务,没有返回值
|
||||
Stop(p0);
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
```
|
||||
|
||||
C++示例2,请移步:[GoProxyForC](https://github.com/SuperPowerLF2/GoProxyForC)
|
||||
|
||||
## Linux SDK
|
||||
[](https://github.com/snail007/goproxy-sdk-linux/) []() [](https://github.com/snail007/goproxy-sdk-linux/releases) [](https://github.com/snail007/goproxy-sdk-linux/releases)
|
||||
|
||||
[点击下载Linux-SDK](https://github.com/snail007/goproxy-sdk-linux/releases)
|
||||
在Linux系统提供的sdk形式是一个后缀为.so的类库文件,开发的时候只需要把so类库加载,调用方法即可.
|
||||
|
||||
### Linux-SDK使用实例
|
||||
Linux下面使用的sdk是so文件即libproxy-sdk.so,下面写一个简单的C程序示例,调用so库里面的方法.
|
||||
|
||||
`vi test-proxy.c`
|
||||
|
||||
```c
|
||||
#include <stdio.h>
|
||||
#include "libproxy-sdk.h"
|
||||
|
||||
int main() {
|
||||
printf("This is demo application.\n");
|
||||
//这里p0是自定义的唯一标识字符串,保证每个启动的服务不一样
|
||||
char *p0 = "http01";
|
||||
char *p1 = "http -t tcp -p :38080";
|
||||
//启动服务,返回空字符串说明启动成功;返回非空字符串说明启动失败,返回的字符串是错误原因
|
||||
printf("start result %s\n",Start(p0,p1));
|
||||
//停止服务,没有返回值
|
||||
Stop(p0);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
#### 编译test-proxy.c ####
|
||||
`export LD_LIBRARY_PATH=./ && gcc -o test-proxy test.c libproxy-sdk.so`
|
||||
|
||||
#### 执行 ####
|
||||
`./test-proxy`
|
||||
|
||||
## MacOS SDK
|
||||
[](https://github.com/snail007/goproxy-sdk-mac/) []() [](https://github.com/snail007/goproxy-sdk-mac/releases) [](https://github.com/snail007/goproxy-sdk-mac/releases)
|
||||
|
||||
[点击下载MacOS-SDK](https://github.com/snail007/goproxy-sdk-mac/releases)
|
||||
在MacOS系统提供的sdk形式是一个后缀为.dylib的类库文件,开发的时候只需要把so类库加载,调用方法即可.
|
||||
|
||||
### MacOS-SDK使用实例
|
||||
MacOS下面使用的sdk是dylib文件即libproxy-sdk.dylib,下面写一个简单的Obj-C程序示例,调用dylib库里面的方法.
|
||||
|
||||
```objc
|
||||
#import "libproxy-sdk.h"
|
||||
-(IBAction)doStart:(id)sender
|
||||
{
|
||||
char *result = Start("http01", "http -t tcp -p :38080");
|
||||
|
||||
if (result)
|
||||
{
|
||||
printf("started");
|
||||
}else{
|
||||
printf("not started");
|
||||
}
|
||||
|
||||
}
|
||||
-(IBAction)doStop:(id)sender
|
||||
{
|
||||
Stop("http01");
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
### 关于服务
|
||||
proxy的服务有11种,分别是:
|
||||
|
||||
```shell
|
||||
http
|
||||
socks
|
||||
sps
|
||||
tcp
|
||||
udp
|
||||
bridge
|
||||
server
|
||||
client
|
||||
tbridge
|
||||
tserver
|
||||
tclient
|
||||
```
|
||||
服务启动时,如果存在正在运行的相同ID的服务,那么之前的服务会被停掉,后面启动的服务覆盖之前的服务.
|
||||
所以要保证每次启动服务的时候,第一个ID参数唯一.
|
||||
上面这些服务的具体使用方式和具体参数,可以参考[proxy手册](https://github.com/snail007/goproxy/blob/master/README_ZH.md)
|
||||
sdk里面的服务不支持手册里面的:--daemon和--forever参数.
|
||||
|
||||
|
||||
7
sdk/android-ios/.gitignore
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
*.jar
|
||||
*.aar
|
||||
*.tar.gz
|
||||
ios
|
||||
android
|
||||
Proxy.framework
|
||||
|
||||
256
sdk/android-ios/dns.go
Normal file
@ -0,0 +1,256 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
logger "log"
|
||||
"net"
|
||||
"runtime/debug"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/proxy"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
gocache "github.com/pmylund/go-cache"
|
||||
services "github.com/snail007/goproxy/services"
|
||||
"github.com/snail007/goproxy/services/kcpcfg"
|
||||
)
|
||||
|
||||
type DNSArgs struct {
|
||||
ParentServiceType *string
|
||||
ParentType *string
|
||||
Parent *string
|
||||
ParentAuth *string
|
||||
ParentKey *string
|
||||
ParentCompress *bool
|
||||
KCP kcpcfg.KCPConfigArgs
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CaCertFile *string
|
||||
Local *string
|
||||
Timeout *int
|
||||
RemoteDNSAddress *string
|
||||
DNSTTL *int
|
||||
CacheFile *string
|
||||
LocalSocks5Port *string
|
||||
}
|
||||
type DNS struct {
|
||||
cfg DNSArgs
|
||||
log *logger.Logger
|
||||
cache *gocache.Cache
|
||||
exitSig chan bool
|
||||
serviceKey string
|
||||
dialer proxy.Dialer
|
||||
}
|
||||
|
||||
func NewDNS() services.Service {
|
||||
return &DNS{
|
||||
cfg: DNSArgs{},
|
||||
exitSig: make(chan bool, 1),
|
||||
serviceKey: "dns-service-" + fmt.Sprintf("%d", time.Now().UnixNano()),
|
||||
}
|
||||
}
|
||||
func (s *DNS) CheckArgs() (err error) {
|
||||
return
|
||||
}
|
||||
func (s *DNS) InitService() (err error) {
|
||||
s.cache = gocache.New(time.Second*time.Duration(*s.cfg.DNSTTL), time.Second*60)
|
||||
s.cache.LoadFile(*s.cfg.CacheFile)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-s.exitSig:
|
||||
return
|
||||
case <-time.After(time.Second * 60):
|
||||
err := s.cache.SaveFile(*s.cfg.CacheFile)
|
||||
if err == nil {
|
||||
//s.log.Printf("cache saved: %s", *s.cfg.CacheFile)
|
||||
} else {
|
||||
s.log.Printf("cache save failed: %s, %s", *s.cfg.CacheFile, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
s.dialer, err = proxy.SOCKS5("tcp", *s.cfg.Parent,
|
||||
nil,
|
||||
&net.Dialer{
|
||||
Timeout: 5 * time.Second,
|
||||
KeepAlive: 2 * time.Second,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
sdkArgs := fmt.Sprintf("sps -S %s -T %s -P %s -C %s -K %s -i %d -p 127.0.0.1:%s --disable-http",
|
||||
*s.cfg.ParentServiceType,
|
||||
*s.cfg.ParentType,
|
||||
*s.cfg.Parent,
|
||||
*s.cfg.CertFile,
|
||||
*s.cfg.KeyFile,
|
||||
*s.cfg.Timeout,
|
||||
*s.cfg.LocalSocks5Port,
|
||||
)
|
||||
if *s.cfg.ParentKey != "" {
|
||||
sdkArgs += " -Z " + *s.cfg.ParentKey
|
||||
}
|
||||
if *s.cfg.ParentAuth != "" {
|
||||
sdkArgs += " -A " + *s.cfg.ParentAuth
|
||||
}
|
||||
if *s.cfg.CaCertFile != "" {
|
||||
sdkArgs += " --ca " + *s.cfg.CaCertFile
|
||||
}
|
||||
if *s.cfg.ParentCompress {
|
||||
sdkArgs += " -M"
|
||||
}
|
||||
s.log.Printf("start sps with : %s", sdkArgs)
|
||||
errStr := Start(s.serviceKey, sdkArgs)
|
||||
if errStr != "" {
|
||||
err = fmt.Errorf("start sps service fail,%s", errStr)
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *DNS) StopService() {
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
s.log.Printf("stop dns service crashed,%s", e)
|
||||
} else {
|
||||
s.log.Printf("service dns stopped")
|
||||
}
|
||||
}()
|
||||
Stop(s.serviceKey)
|
||||
s.cache.Flush()
|
||||
s.exitSig <- true
|
||||
}
|
||||
func (s *DNS) Start(args interface{}, log *logger.Logger) (err error) {
|
||||
s.log = log
|
||||
s.cfg = args.(DNSArgs)
|
||||
if err = s.CheckArgs(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = s.InitService(); err != nil {
|
||||
return
|
||||
}
|
||||
dns.HandleFunc(".", s.callback)
|
||||
go func() {
|
||||
log.Printf("dns server on udp %s", *s.cfg.Local)
|
||||
err := dns.ListenAndServe(*s.cfg.Local, "udp", nil)
|
||||
if err != nil {
|
||||
log.Printf("dns listen error: %s", err)
|
||||
}
|
||||
}()
|
||||
return
|
||||
}
|
||||
|
||||
func (s *DNS) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *DNS) callback(w dns.ResponseWriter, req *dns.Msg) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
s.log.Printf("dns handler crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
var (
|
||||
key string
|
||||
m *dns.Msg
|
||||
err error
|
||||
data []byte
|
||||
id uint16
|
||||
query []string
|
||||
questions []dns.Question
|
||||
)
|
||||
if req.MsgHdr.Response == true {
|
||||
return
|
||||
}
|
||||
query = make([]string, len(req.Question))
|
||||
for i, q := range req.Question {
|
||||
if q.Qtype != dns.TypeAAAA {
|
||||
questions = append(questions, q)
|
||||
}
|
||||
query[i] = fmt.Sprintf("(%s %s %s)", q.Name, dns.ClassToString[q.Qclass], dns.TypeToString[q.Qtype])
|
||||
}
|
||||
|
||||
if len(questions) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
req.Question = questions
|
||||
id = req.Id
|
||||
req.Id = 0
|
||||
key = s.toMd5(req.String())
|
||||
req.Id = id
|
||||
if reply, ok := s.cache.Get(key); ok {
|
||||
data, _ = reply.([]byte)
|
||||
}
|
||||
if data != nil && len(data) > 0 {
|
||||
m = &dns.Msg{}
|
||||
m.Unpack(data)
|
||||
m.Id = id
|
||||
err = w.WriteMsg(m)
|
||||
s.log.Printf("id: %5d cache: HIT %v", id, query)
|
||||
return
|
||||
|
||||
} else {
|
||||
s.log.Printf("id: %5d cache: MISS %v", id, query)
|
||||
}
|
||||
|
||||
s.log.Printf("id: %5d resolve: %v %s", id, query, *s.cfg.RemoteDNSAddress)
|
||||
|
||||
rawConn, err := s.dialer.Dial("tcp", *s.cfg.RemoteDNSAddress)
|
||||
if err != nil {
|
||||
s.log.Printf("dail to %s fail,%s", *s.cfg.RemoteDNSAddress, err)
|
||||
return
|
||||
}
|
||||
defer rawConn.Close()
|
||||
co := new(dns.Conn)
|
||||
co.Conn = rawConn
|
||||
defer co.Close()
|
||||
if err = co.WriteMsg(req); err != nil {
|
||||
s.log.Printf("write dns query fail,%s", err)
|
||||
return
|
||||
}
|
||||
m, err = co.ReadMsg()
|
||||
if err == nil && m.Id != req.Id {
|
||||
s.log.Printf("id: %5d mismath", id)
|
||||
return
|
||||
}
|
||||
if err != nil || len(m.Answer) == 0 {
|
||||
s.log.Printf("dns query fail,%s", err)
|
||||
return
|
||||
}
|
||||
data, err = m.Pack()
|
||||
if err != nil {
|
||||
s.log.Printf("dns query fail,%s", err)
|
||||
return
|
||||
}
|
||||
|
||||
_, err = w.Write(data)
|
||||
if err != nil {
|
||||
s.log.Printf("dns query fail,%s", err)
|
||||
return
|
||||
}
|
||||
m.Id = 0
|
||||
data, _ = m.Pack()
|
||||
ttl := 0
|
||||
if len(m.Answer) > 0 {
|
||||
if *s.cfg.DNSTTL > 0 {
|
||||
ttl = *s.cfg.DNSTTL
|
||||
} else {
|
||||
ttl = int(m.Answer[0].Header().Ttl)
|
||||
if ttl < 0 {
|
||||
ttl = *s.cfg.DNSTTL
|
||||
}
|
||||
}
|
||||
}
|
||||
s.cache.Set(key, data, time.Second*time.Duration(ttl))
|
||||
m.Id = id
|
||||
s.log.Printf("id: %5d cache: CACHED %v TTL %v", id, query, ttl)
|
||||
}
|
||||
func (s *DNS) toMd5(data string) string {
|
||||
m := md5.New()
|
||||
m.Write([]byte(data))
|
||||
return hex.EncodeToString(m.Sum(nil))
|
||||
}
|
||||
24
sdk/android-ios/release_android.sh
Executable file
@ -0,0 +1,24 @@
|
||||
#/bin/bash
|
||||
VER="v5.3"
|
||||
rm -rf sdk-android-*.tar.gz
|
||||
rm -rf android
|
||||
mkdir android
|
||||
|
||||
#android ; jdk,android ndk & android sdk required, install gomobile go1.10 required
|
||||
#export GOPATH="$HOME/go"
|
||||
#export GOROOT="/usr/local/go"
|
||||
#export PATH="$GOROOT/bin:$GOPATH/bin:$PATH"
|
||||
#export ANDROID_HOME="$HOME/Android/Sdk"
|
||||
#export NDK_ROOT="$HOME/Android/Sdk/ndk-bundle"
|
||||
#export PATH="$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools:$NDK_ROOT:$PATH"
|
||||
#go get -v golang.org/x/mobile/cmd/gomobile
|
||||
#gomobile init
|
||||
|
||||
gomobile bind -v -target=android -javapkg=snail007 -ldflags="-s -w"
|
||||
mv proxy.aar android/snail007.goproxy.sdk.aar
|
||||
mv proxy-sources.jar android/snail007.goproxy.sdk-sources.jar
|
||||
cp ../README.md android
|
||||
tar zcfv sdk-android-${VER}.tar.gz android
|
||||
rm -rf android
|
||||
|
||||
echo "done."
|
||||
14
sdk/android-ios/release_ios.sh
Executable file
@ -0,0 +1,14 @@
|
||||
#/bin/bash
|
||||
VER="v5.3"
|
||||
rm -rf sdk-ios-*.tar.gz
|
||||
rm -rf ios
|
||||
mkdir ios
|
||||
|
||||
#ios XCode required
|
||||
gomobile bind -v -target=ios -ldflags="-s -w"
|
||||
mv Proxy.framework ios
|
||||
cp ../README.md ios
|
||||
tar zcfv sdk-ios-${VER}.tar.gz ios
|
||||
rm -rf ios
|
||||
|
||||
echo "done."
|
||||
421
sdk/android-ios/sdk.go
Normal file
@ -0,0 +1,421 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
logger "log"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/snail007/goproxy/services"
|
||||
httpx "github.com/snail007/goproxy/services/http"
|
||||
"github.com/snail007/goproxy/services/kcpcfg"
|
||||
mux "github.com/snail007/goproxy/services/mux"
|
||||
socksx "github.com/snail007/goproxy/services/socks"
|
||||
spsx "github.com/snail007/goproxy/services/sps"
|
||||
tcpx "github.com/snail007/goproxy/services/tcp"
|
||||
tunnel "github.com/snail007/goproxy/services/tunnel"
|
||||
udpx "github.com/snail007/goproxy/services/udp"
|
||||
kcp "github.com/xtaci/kcp-go"
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
kingpin "gopkg.in/alecthomas/kingpin.v2"
|
||||
)
|
||||
|
||||
const SDK_VERSION = "5.3"
|
||||
|
||||
var (
|
||||
app *kingpin.Application
|
||||
)
|
||||
|
||||
type LogCallback interface {
|
||||
Write(line string)
|
||||
}
|
||||
type logCallback interface {
|
||||
Write(line string)
|
||||
}
|
||||
type logWriter struct {
|
||||
callback LogCallback
|
||||
}
|
||||
|
||||
func (s *logWriter) Write(p []byte) (n int, err error) {
|
||||
s.callback.Write(string(p))
|
||||
return
|
||||
}
|
||||
|
||||
func Start(serviceID, serviceArgsStr string) (errStr string) {
|
||||
return StartWithLog(serviceID, serviceArgsStr, nil)
|
||||
}
|
||||
|
||||
//Start
|
||||
//serviceID : is service identify id,different service's id should be difference
|
||||
//serviceArgsStr: is the whole command line args string
|
||||
//such as :
|
||||
//1."http -t tcp -p :8989"
|
||||
//2."socks -t tcp -p :8989"
|
||||
//and so on.
|
||||
//if an error occured , errStr will be the error reason
|
||||
//if start success, errStr is empty.
|
||||
func StartWithLog(serviceID, serviceArgsStr string, loggerCallback LogCallback) (errStr string) {
|
||||
//define args
|
||||
tcpArgs := tcpx.TCPArgs{}
|
||||
httpArgs := httpx.HTTPArgs{}
|
||||
tunnelServerArgs := tunnel.TunnelServerArgs{}
|
||||
tunnelClientArgs := tunnel.TunnelClientArgs{}
|
||||
tunnelBridgeArgs := tunnel.TunnelBridgeArgs{}
|
||||
muxServerArgs := mux.MuxServerArgs{}
|
||||
muxClientArgs := mux.MuxClientArgs{}
|
||||
muxBridgeArgs := mux.MuxBridgeArgs{}
|
||||
udpArgs := udpx.UDPArgs{}
|
||||
socksArgs := socksx.SocksArgs{}
|
||||
spsArgs := spsx.SPSArgs{}
|
||||
dnsArgs := DNSArgs{}
|
||||
kcpArgs := kcpcfg.KCPConfigArgs{}
|
||||
//build srvice args
|
||||
app = kingpin.New("proxy", "happy with proxy")
|
||||
app.Author("snail").Version(SDK_VERSION)
|
||||
debug := app.Flag("debug", "debug log output").Default("false").Bool()
|
||||
logfile := app.Flag("log", "log file path").Default("").String()
|
||||
nolog := app.Flag("nolog", "turn off logging").Default("false").Bool()
|
||||
kcpArgs.Key = app.Flag("kcp-key", "pre-shared secret between client and server").Default("secrect").String()
|
||||
kcpArgs.Crypt = app.Flag("kcp-method", "encrypt/decrypt method, can be: aes, aes-128, aes-192, salsa20, blowfish, twofish, cast5, 3des, tea, xtea, xor, sm4, none").Default("aes").Enum("aes", "aes-128", "aes-192", "salsa20", "blowfish", "twofish", "cast5", "3des", "tea", "xtea", "xor", "sm4", "none")
|
||||
kcpArgs.Mode = app.Flag("kcp-mode", "profiles: fast3, fast2, fast, normal, manual").Default("fast3").Enum("fast3", "fast2", "fast", "normal", "manual")
|
||||
kcpArgs.MTU = app.Flag("kcp-mtu", "set maximum transmission unit for UDP packets").Default("1350").Int()
|
||||
kcpArgs.SndWnd = app.Flag("kcp-sndwnd", "set send window size(num of packets)").Default("1024").Int()
|
||||
kcpArgs.RcvWnd = app.Flag("kcp-rcvwnd", "set receive window size(num of packets)").Default("1024").Int()
|
||||
kcpArgs.DataShard = app.Flag("kcp-ds", "set reed-solomon erasure coding - datashard").Default("10").Int()
|
||||
kcpArgs.ParityShard = app.Flag("kcp-ps", "set reed-solomon erasure coding - parityshard").Default("3").Int()
|
||||
kcpArgs.DSCP = app.Flag("kcp-dscp", "set DSCP(6bit)").Default("0").Int()
|
||||
kcpArgs.NoComp = app.Flag("kcp-nocomp", "disable compression").Default("false").Bool()
|
||||
kcpArgs.AckNodelay = app.Flag("kcp-acknodelay", "be carefull! flush ack immediately when a packet is received").Default("true").Bool()
|
||||
kcpArgs.NoDelay = app.Flag("kcp-nodelay", "be carefull!").Default("0").Int()
|
||||
kcpArgs.Interval = app.Flag("kcp-interval", "be carefull!").Default("50").Int()
|
||||
kcpArgs.Resend = app.Flag("kcp-resend", "be carefull!").Default("0").Int()
|
||||
kcpArgs.NoCongestion = app.Flag("kcp-nc", "be carefull! no congestion").Default("0").Int()
|
||||
kcpArgs.SockBuf = app.Flag("kcp-sockbuf", "be carefull!").Default("4194304").Int()
|
||||
kcpArgs.KeepAlive = app.Flag("kcp-keepalive", "be carefull!").Default("10").Int()
|
||||
|
||||
//########http#########
|
||||
http := app.Command("http", "proxy on http mode")
|
||||
httpArgs.Parent = http.Flag("parent", "parent address, such as: \"23.32.32.19:28008\"").Default("").Short('P').String()
|
||||
httpArgs.CaCertFile = http.Flag("ca", "ca cert file for tls").Default("").String()
|
||||
httpArgs.CertFile = http.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
httpArgs.KeyFile = http.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
httpArgs.LocalType = http.Flag("local-type", "local protocol type <tls|tcp|kcp>").Default("tcp").Short('t').Enum("tls", "tcp", "kcp")
|
||||
httpArgs.ParentType = http.Flag("parent-type", "parent protocol type <tls|tcp|ssh|kcp>").Short('T').Enum("tls", "tcp", "ssh", "kcp")
|
||||
httpArgs.Always = http.Flag("always", "always use parent proxy").Default("false").Bool()
|
||||
httpArgs.Timeout = http.Flag("timeout", "tcp timeout milliseconds when connect to real server or parent proxy").Default("2000").Int()
|
||||
httpArgs.HTTPTimeout = http.Flag("http-timeout", "check domain if blocked , http request timeout milliseconds when connect to host").Default("3000").Int()
|
||||
httpArgs.Interval = http.Flag("interval", "check domain if blocked every interval seconds").Default("10").Int()
|
||||
httpArgs.Blocked = http.Flag("blocked", "blocked domain file , one domain each line").Default("blocked").Short('b').String()
|
||||
httpArgs.Direct = http.Flag("direct", "direct domain file , one domain each line").Default("direct").Short('d').String()
|
||||
httpArgs.AuthFile = http.Flag("auth-file", "http basic auth file,\"username:password\" each line in file").Short('F').String()
|
||||
httpArgs.Auth = http.Flag("auth", "http basic auth username and password, mutiple user repeat -a ,such as: -a user1:pass1 -a user2:pass2").Short('a').Strings()
|
||||
httpArgs.CheckParentInterval = http.Flag("check-parent-interval", "check if proxy is okay every interval seconds,zero: means no check").Short('I').Default("3").Int()
|
||||
httpArgs.Local = http.Flag("local", "local ip:port to listen,multiple address use comma split,such as: 0.0.0.0:80,0.0.0.0:443").Short('p').Default(":33080").String()
|
||||
httpArgs.SSHUser = http.Flag("ssh-user", "user for ssh").Short('u').Default("").String()
|
||||
httpArgs.SSHKeyFile = http.Flag("ssh-key", "private key file for ssh").Short('S').Default("").String()
|
||||
httpArgs.SSHKeyFileSalt = http.Flag("ssh-keysalt", "salt of ssh private key").Short('s').Default("").String()
|
||||
httpArgs.SSHPassword = http.Flag("ssh-password", "password for ssh").Short('A').Default("").String()
|
||||
httpArgs.LocalIPS = http.Flag("local-bind-ips", "if your host behind a nat,set your public ip here avoid dead loop").Short('g').Strings()
|
||||
httpArgs.AuthURL = http.Flag("auth-url", "http basic auth username and password will send to this url,response http code equal to 'auth-code' means ok,others means fail.").Default("").String()
|
||||
httpArgs.AuthURLTimeout = http.Flag("auth-timeout", "access 'auth-url' timeout milliseconds").Default("3000").Int()
|
||||
httpArgs.AuthURLOkCode = http.Flag("auth-code", "access 'auth-url' success http code").Default("204").Int()
|
||||
httpArgs.AuthURLRetry = http.Flag("auth-retry", "access 'auth-url' fail and retry count").Default("1").Int()
|
||||
httpArgs.DNSAddress = http.Flag("dns-address", "if set this, proxy will use this dns for resolve doamin").Short('q').Default("").String()
|
||||
httpArgs.DNSTTL = http.Flag("dns-ttl", "caching seconds of dns query result").Short('e').Default("300").Int()
|
||||
httpArgs.LocalKey = http.Flag("local-key", "the password for auto encrypt/decrypt local connection data").Short('z').Default("").String()
|
||||
httpArgs.ParentKey = http.Flag("parent-key", "the password for auto encrypt/decrypt parent connection data").Short('Z').Default("").String()
|
||||
httpArgs.LocalCompress = http.Flag("local-compress", "auto compress/decompress data on local connection").Short('m').Default("false").Bool()
|
||||
httpArgs.ParentCompress = http.Flag("parent-compress", "auto compress/decompress data on parent connection").Short('M').Default("false").Bool()
|
||||
|
||||
//########tcp#########
|
||||
tcp := app.Command("tcp", "proxy on tcp mode")
|
||||
tcpArgs.Parent = tcp.Flag("parent", "parent address, such as: \"23.32.32.19:28008\"").Default("").Short('P').String()
|
||||
tcpArgs.CertFile = tcp.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
tcpArgs.KeyFile = tcp.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
tcpArgs.Timeout = tcp.Flag("timeout", "tcp timeout milliseconds when connect to real server or parent proxy").Short('e').Default("2000").Int()
|
||||
tcpArgs.ParentType = tcp.Flag("parent-type", "parent protocol type <tls|tcp|kcp|udp>").Short('T').Enum("tls", "tcp", "udp", "kcp")
|
||||
tcpArgs.LocalType = tcp.Flag("local-type", "local protocol type <tls|tcp|kcp>").Default("tcp").Short('t').Enum("tls", "tcp", "kcp")
|
||||
tcpArgs.Local = tcp.Flag("local", "local ip:port to listen").Short('p').Default(":33080").String()
|
||||
tcpArgs.Jumper = tcp.Flag("jumper", "https or socks5 proxies used when connecting to parent, only worked of -T is tls or tcp, format is https://username:password@host:port https://host:port or socks5://username:password@host:port socks5://host:port").Short('J').Default("").String()
|
||||
|
||||
//########udp#########
|
||||
udp := app.Command("udp", "proxy on udp mode")
|
||||
udpArgs.Parent = udp.Flag("parent", "parent address, such as: \"23.32.32.19:28008\"").Default("").Short('P').String()
|
||||
udpArgs.CertFile = udp.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
udpArgs.KeyFile = udp.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
udpArgs.Timeout = udp.Flag("timeout", "tcp timeout milliseconds when connect to parent proxy").Short('t').Default("2000").Int()
|
||||
udpArgs.ParentType = udp.Flag("parent-type", "parent protocol type <tls|tcp|udp>").Short('T').Enum("tls", "tcp", "udp")
|
||||
udpArgs.CheckParentInterval = udp.Flag("check-parent-interval", "check if proxy is okay every interval seconds,zero: means no check").Short('I').Default("3").Int()
|
||||
udpArgs.Local = udp.Flag("local", "local ip:port to listen").Short('p').Default(":33080").String()
|
||||
|
||||
//########mux-server#########
|
||||
muxServer := app.Command("server", "proxy on mux server mode")
|
||||
muxServerArgs.Parent = muxServer.Flag("parent", "parent address, such as: \"23.32.32.19:28008\"").Default("").Short('P').String()
|
||||
muxServerArgs.ParentType = muxServer.Flag("parent-type", "parent protocol type <tls|tcp|kcp>").Default("tls").Short('T').Enum("tls", "tcp", "kcp")
|
||||
muxServerArgs.CertFile = muxServer.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
muxServerArgs.KeyFile = muxServer.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
muxServerArgs.Timeout = muxServer.Flag("timeout", "tcp timeout with milliseconds").Short('i').Default("2000").Int()
|
||||
muxServerArgs.IsUDP = muxServer.Flag("udp", "proxy on udp mux server mode").Default("false").Bool()
|
||||
muxServerArgs.Key = muxServer.Flag("k", "client key").Default("default").String()
|
||||
muxServerArgs.Route = muxServer.Flag("route", "local route to client's network, such as: PROTOCOL://LOCAL_IP:LOCAL_PORT@[CLIENT_KEY]CLIENT_LOCAL_HOST:CLIENT_LOCAL_PORT").Short('r').Default("").Strings()
|
||||
muxServerArgs.IsCompress = muxServer.Flag("c", "compress data when tcp|tls mode").Default("false").Bool()
|
||||
muxServerArgs.SessionCount = muxServer.Flag("session-count", "session count which connect to bridge").Short('n').Default("10").Int()
|
||||
muxServerArgs.Jumper = muxServer.Flag("jumper", "https or socks5 proxies used when connecting to parent, only worked of -T is tls or tcp, format is https://username:password@host:port https://host:port or socks5://username:password@host:port socks5://host:port").Short('J').Default("").String()
|
||||
|
||||
//########mux-client#########
|
||||
muxClient := app.Command("client", "proxy on mux client mode")
|
||||
muxClientArgs.Parent = muxClient.Flag("parent", "parent address, such as: \"23.32.32.19:28008\"").Default("").Short('P').String()
|
||||
muxClientArgs.ParentType = muxClient.Flag("parent-type", "parent protocol type <tls|tcp|kcp>").Default("tls").Short('T').Enum("tls", "tcp", "kcp")
|
||||
muxClientArgs.CertFile = muxClient.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
muxClientArgs.KeyFile = muxClient.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
muxClientArgs.Timeout = muxClient.Flag("timeout", "tcp timeout with milliseconds").Short('i').Default("2000").Int()
|
||||
muxClientArgs.Key = muxClient.Flag("k", "key same with server").Default("default").String()
|
||||
muxClientArgs.IsCompress = muxClient.Flag("c", "compress data when tcp|tls mode").Default("false").Bool()
|
||||
muxClientArgs.SessionCount = muxClient.Flag("session-count", "session count which connect to bridge").Short('n').Default("10").Int()
|
||||
muxClientArgs.Jumper = muxClient.Flag("jumper", "https or socks5 proxies used when connecting to parent, only worked of -T is tls or tcp, format is https://username:password@host:port https://host:port or socks5://username:password@host:port socks5://host:port").Short('J').Default("").String()
|
||||
|
||||
//########mux-bridge#########
|
||||
muxBridge := app.Command("bridge", "proxy on mux bridge mode")
|
||||
muxBridgeArgs.CertFile = muxBridge.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
muxBridgeArgs.KeyFile = muxBridge.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
muxBridgeArgs.Timeout = muxBridge.Flag("timeout", "tcp timeout with milliseconds").Short('i').Default("2000").Int()
|
||||
muxBridgeArgs.Local = muxBridge.Flag("local", "local ip:port to listen").Short('p').Default(":33080").String()
|
||||
muxBridgeArgs.LocalType = muxBridge.Flag("local-type", "local protocol type <tls|tcp|kcp>").Default("tls").Short('t').Enum("tls", "tcp", "kcp")
|
||||
|
||||
//########tunnel-server#########
|
||||
tunnelServer := app.Command("tserver", "proxy on tunnel server mode")
|
||||
tunnelServerArgs.Parent = tunnelServer.Flag("parent", "parent address, such as: \"23.32.32.19:28008\"").Default("").Short('P').String()
|
||||
tunnelServerArgs.CertFile = tunnelServer.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
tunnelServerArgs.KeyFile = tunnelServer.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
tunnelServerArgs.Timeout = tunnelServer.Flag("timeout", "tcp timeout with milliseconds").Short('t').Default("2000").Int()
|
||||
tunnelServerArgs.IsUDP = tunnelServer.Flag("udp", "proxy on udp tunnel server mode").Default("false").Bool()
|
||||
tunnelServerArgs.Key = tunnelServer.Flag("k", "client key").Default("default").String()
|
||||
tunnelServerArgs.Route = tunnelServer.Flag("route", "local route to client's network, such as: PROTOCOL://LOCAL_IP:LOCAL_PORT@[CLIENT_KEY]CLIENT_LOCAL_HOST:CLIENT_LOCAL_PORT").Short('r').Default("").Strings()
|
||||
tunnelServerArgs.Jumper = tunnelServer.Flag("jumper", "https or socks5 proxies used when connecting to parent, only worked of -T is tls or tcp, format is https://username:password@host:port https://host:port or socks5://username:password@host:port socks5://host:port").Short('J').Default("").String()
|
||||
|
||||
//########tunnel-client#########
|
||||
tunnelClient := app.Command("tclient", "proxy on tunnel client mode")
|
||||
tunnelClientArgs.Parent = tunnelClient.Flag("parent", "parent address, such as: \"23.32.32.19:28008\"").Default("").Short('P').String()
|
||||
tunnelClientArgs.CertFile = tunnelClient.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
tunnelClientArgs.KeyFile = tunnelClient.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
tunnelClientArgs.Timeout = tunnelClient.Flag("timeout", "tcp timeout with milliseconds").Short('t').Default("2000").Int()
|
||||
tunnelClientArgs.Key = tunnelClient.Flag("k", "key same with server").Default("default").String()
|
||||
tunnelClientArgs.Jumper = tunnelClient.Flag("jumper", "https or socks5 proxies used when connecting to parent, only worked of -T is tls or tcp, format is https://username:password@host:port https://host:port or socks5://username:password@host:port socks5://host:port").Short('J').Default("").String()
|
||||
|
||||
//########tunnel-bridge#########
|
||||
tunnelBridge := app.Command("tbridge", "proxy on tunnel bridge mode")
|
||||
tunnelBridgeArgs.CertFile = tunnelBridge.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
tunnelBridgeArgs.KeyFile = tunnelBridge.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
tunnelBridgeArgs.Timeout = tunnelBridge.Flag("timeout", "tcp timeout with milliseconds").Short('t').Default("2000").Int()
|
||||
tunnelBridgeArgs.Local = tunnelBridge.Flag("local", "local ip:port to listen").Short('p').Default(":33080").String()
|
||||
|
||||
//########ssh#########
|
||||
socks := app.Command("socks", "proxy on ssh mode")
|
||||
socksArgs.Parent = socks.Flag("parent", "parent ssh address, such as: \"23.32.32.19:22\"").Default("").Short('P').String()
|
||||
socksArgs.ParentType = socks.Flag("parent-type", "parent protocol type <tls|tcp|kcp|ssh>").Default("tcp").Short('T').Enum("tls", "tcp", "kcp", "ssh")
|
||||
socksArgs.LocalType = socks.Flag("local-type", "local protocol type <tls|tcp|kcp>").Default("tcp").Short('t').Enum("tls", "tcp", "kcp")
|
||||
socksArgs.Local = socks.Flag("local", "local ip:port to listen").Short('p').Default(":33080").String()
|
||||
socksArgs.CertFile = socks.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
socksArgs.CaCertFile = socks.Flag("ca", "ca cert file for tls").Default("").String()
|
||||
socksArgs.KeyFile = socks.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
socksArgs.SSHUser = socks.Flag("ssh-user", "user for ssh").Short('u').Default("").String()
|
||||
socksArgs.SSHKeyFile = socks.Flag("ssh-key", "private key file for ssh").Short('S').Default("").String()
|
||||
socksArgs.SSHKeyFileSalt = socks.Flag("ssh-keysalt", "salt of ssh private key").Short('s').Default("").String()
|
||||
socksArgs.SSHPassword = socks.Flag("ssh-password", "password for ssh").Short('A').Default("").String()
|
||||
socksArgs.Always = socks.Flag("always", "always use parent proxy").Default("false").Bool()
|
||||
socksArgs.Timeout = socks.Flag("timeout", "tcp timeout milliseconds when connect to real server or parent proxy").Default("5000").Int()
|
||||
socksArgs.Interval = socks.Flag("interval", "check domain if blocked every interval seconds").Default("10").Int()
|
||||
socksArgs.Blocked = socks.Flag("blocked", "blocked domain file , one domain each line").Default("blocked").Short('b').String()
|
||||
socksArgs.Direct = socks.Flag("direct", "direct domain file , one domain each line").Default("direct").Short('d').String()
|
||||
socksArgs.AuthFile = socks.Flag("auth-file", "http basic auth file,\"username:password\" each line in file").Short('F').String()
|
||||
socksArgs.Auth = socks.Flag("auth", "socks auth username and password, mutiple user repeat -a ,such as: -a user1:pass1 -a user2:pass2").Short('a').Strings()
|
||||
socksArgs.LocalIPS = socks.Flag("local-bind-ips", "if your host behind a nat,set your public ip here avoid dead loop").Short('g').Strings()
|
||||
socksArgs.AuthURL = socks.Flag("auth-url", "auth username and password will send to this url,response http code equal to 'auth-code' means ok,others means fail.").Default("").String()
|
||||
socksArgs.AuthURLTimeout = socks.Flag("auth-timeout", "access 'auth-url' timeout milliseconds").Default("3000").Int()
|
||||
socksArgs.AuthURLOkCode = socks.Flag("auth-code", "access 'auth-url' success http code").Default("204").Int()
|
||||
socksArgs.AuthURLRetry = socks.Flag("auth-retry", "access 'auth-url' fail and retry count").Default("0").Int()
|
||||
socksArgs.DNSAddress = socks.Flag("dns-address", "if set this, proxy will use this dns for resolve doamin").Short('q').Default("").String()
|
||||
socksArgs.DNSTTL = socks.Flag("dns-ttl", "caching seconds of dns query result").Short('e').Default("300").Int()
|
||||
socksArgs.LocalKey = socks.Flag("local-key", "the password for auto encrypt/decrypt local connection data").Short('z').Default("").String()
|
||||
socksArgs.ParentKey = socks.Flag("parent-key", "the password for auto encrypt/decrypt parent connection data").Short('Z').Default("").String()
|
||||
socksArgs.LocalCompress = socks.Flag("local-compress", "auto compress/decompress data on local connection").Short('m').Default("false").Bool()
|
||||
socksArgs.ParentCompress = socks.Flag("parent-compress", "auto compress/decompress data on parent connection").Short('M').Default("false").Bool()
|
||||
|
||||
//########socks+http(s)#########
|
||||
sps := app.Command("sps", "proxy on socks+http(s) mode")
|
||||
spsArgs.Parent = sps.Flag("parent", "parent address, such as: \"23.32.32.19:28008\"").Default("").Short('P').String()
|
||||
spsArgs.CertFile = sps.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
spsArgs.KeyFile = sps.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
spsArgs.CaCertFile = sps.Flag("ca", "ca cert file for tls").Default("").String()
|
||||
spsArgs.Timeout = sps.Flag("timeout", "tcp timeout milliseconds when connect to real server or parent proxy").Short('i').Default("2000").Int()
|
||||
spsArgs.ParentType = sps.Flag("parent-type", "parent protocol type <tls|tcp|kcp>").Short('T').Enum("tls", "tcp", "kcp")
|
||||
spsArgs.LocalType = sps.Flag("local-type", "local protocol type <tls|tcp|kcp>").Default("tcp").Short('t').Enum("tls", "tcp", "kcp")
|
||||
spsArgs.Local = sps.Flag("local", "local ip:port to listen,multiple address use comma split,such as: 0.0.0.0:80,0.0.0.0:443").Short('p').Default(":33080").String()
|
||||
spsArgs.ParentServiceType = sps.Flag("parent-service-type", "parent service type <http|socks>").Short('S').Enum("http", "socks")
|
||||
spsArgs.DNSAddress = sps.Flag("dns-address", "if set this, proxy will use this dns for resolve doamin").Short('q').Default("").String()
|
||||
spsArgs.DNSTTL = sps.Flag("dns-ttl", "caching seconds of dns query result").Short('e').Default("300").Int()
|
||||
spsArgs.AuthFile = sps.Flag("auth-file", "http basic auth file,\"username:password\" each line in file").Short('F').String()
|
||||
spsArgs.Auth = sps.Flag("auth", "socks auth username and password, mutiple user repeat -a ,such as: -a user1:pass1 -a user2:pass2").Short('a').Strings()
|
||||
spsArgs.LocalIPS = sps.Flag("local bind ips", "if your host behind a nat,set your public ip here avoid dead loop").Short('g').Strings()
|
||||
spsArgs.AuthURL = sps.Flag("auth-url", "auth username and password will send to this url,response http code equal to 'auth-code' means ok,others means fail.").Default("").String()
|
||||
spsArgs.AuthURLTimeout = sps.Flag("auth-timeout", "access 'auth-url' timeout milliseconds").Default("3000").Int()
|
||||
spsArgs.AuthURLOkCode = sps.Flag("auth-code", "access 'auth-url' success http code").Default("204").Int()
|
||||
spsArgs.AuthURLRetry = sps.Flag("auth-retry", "access 'auth-url' fail and retry count").Default("0").Int()
|
||||
spsArgs.ParentAuth = sps.Flag("parent-auth", "parent socks auth username and password, such as: -A user1:pass1").Short('A').String()
|
||||
spsArgs.LocalKey = sps.Flag("local-key", "the password for auto encrypt/decrypt local connection data").Short('z').Default("").String()
|
||||
spsArgs.ParentKey = sps.Flag("parent-key", "the password for auto encrypt/decrypt parent connection data").Short('Z').Default("").String()
|
||||
spsArgs.LocalCompress = sps.Flag("local-compress", "auto compress/decompress data on local connection").Short('m').Default("false").Bool()
|
||||
spsArgs.ParentCompress = sps.Flag("parent-compress", "auto compress/decompress data on parent connection").Short('M').Default("false").Bool()
|
||||
spsArgs.DisableHTTP = sps.Flag("disable-http", "disable http(s) proxy").Default("false").Bool()
|
||||
spsArgs.DisableSocks5 = sps.Flag("disable-socks", "disable socks proxy").Default("false").Bool()
|
||||
//########dns#########
|
||||
dns := app.Command("dns", "proxy on dns server mode")
|
||||
dnsArgs.Parent = dns.Flag("parent", "parent address, such as: \"23.32.32.19:28008\"").Default("").Short('P').String()
|
||||
dnsArgs.CertFile = dns.Flag("cert", "cert file for tls").Short('C').Default("proxy.crt").String()
|
||||
dnsArgs.KeyFile = dns.Flag("key", "key file for tls").Short('K').Default("proxy.key").String()
|
||||
dnsArgs.CaCertFile = dns.Flag("ca", "ca cert file for tls").Default("").String()
|
||||
dnsArgs.Timeout = dns.Flag("timeout", "tcp timeout milliseconds when connect to real server or parent proxy").Short('i').Default("2000").Int()
|
||||
dnsArgs.ParentType = dns.Flag("parent-type", "parent protocol type <tls|tcp|kcp>").Short('T').Enum("tls", "tcp", "kcp")
|
||||
dnsArgs.Local = dns.Flag("local", "local ip:port to listen,multiple address use comma split,such as: 0.0.0.0:80,0.0.0.0:443").Short('p').Default(":33080").String()
|
||||
dnsArgs.ParentServiceType = dns.Flag("parent-service-type", "parent service type <http|socks>").Short('S').Enum("http", "socks")
|
||||
dnsArgs.RemoteDNSAddress = dns.Flag("dns-address", "remote dns for resolve doamin").Short('q').Default("8.8.8.8:53").String()
|
||||
dnsArgs.DNSTTL = dns.Flag("dns-ttl", "caching seconds of dns query result").Short('e').Default("300").Int()
|
||||
dnsArgs.ParentAuth = dns.Flag("parent-auth", "parent socks auth username and password, such as: -A user1:pass1").Short('A').String()
|
||||
dnsArgs.ParentKey = dns.Flag("parent-key", "the password for auto encrypt/decrypt parent connection data").Short('Z').Default("").String()
|
||||
dnsArgs.ParentCompress = dns.Flag("parent-compress", "auto compress/decompress data on parent connection").Short('M').Default("false").Bool()
|
||||
dnsArgs.CacheFile = dns.Flag("cache-file", "dns result cached file").Short('f').Default(filepath.Join(path.Dir(os.Args[0]), "cache.dat")).String()
|
||||
dnsArgs.LocalSocks5Port = dns.Flag("socks-port", "local socks5 port").Short('s').Default("65501").String()
|
||||
|
||||
//parse args
|
||||
_args := strings.Fields(strings.Trim(serviceArgsStr, " "))
|
||||
args := []string{}
|
||||
for _, a := range _args {
|
||||
args = append(args, strings.Trim(a, "\""))
|
||||
}
|
||||
serviceName, err := app.Parse(args)
|
||||
if err != nil {
|
||||
return fmt.Sprintf("parse args fail,err: %s", err)
|
||||
}
|
||||
//set kcp config
|
||||
|
||||
switch *kcpArgs.Mode {
|
||||
case "normal":
|
||||
*kcpArgs.NoDelay, *kcpArgs.Interval, *kcpArgs.Resend, *kcpArgs.NoCongestion = 0, 40, 2, 1
|
||||
case "fast":
|
||||
*kcpArgs.NoDelay, *kcpArgs.Interval, *kcpArgs.Resend, *kcpArgs.NoCongestion = 0, 30, 2, 1
|
||||
case "fast2":
|
||||
*kcpArgs.NoDelay, *kcpArgs.Interval, *kcpArgs.Resend, *kcpArgs.NoCongestion = 1, 20, 2, 1
|
||||
case "fast3":
|
||||
*kcpArgs.NoDelay, *kcpArgs.Interval, *kcpArgs.Resend, *kcpArgs.NoCongestion = 1, 10, 2, 1
|
||||
}
|
||||
pass := pbkdf2.Key([]byte(*kcpArgs.Key), []byte("snail007-goproxy"), 4096, 32, sha1.New)
|
||||
|
||||
switch *kcpArgs.Crypt {
|
||||
case "sm4":
|
||||
kcpArgs.Block, _ = kcp.NewSM4BlockCrypt(pass[:16])
|
||||
case "tea":
|
||||
kcpArgs.Block, _ = kcp.NewTEABlockCrypt(pass[:16])
|
||||
case "xor":
|
||||
kcpArgs.Block, _ = kcp.NewSimpleXORBlockCrypt(pass)
|
||||
case "none":
|
||||
kcpArgs.Block, _ = kcp.NewNoneBlockCrypt(pass)
|
||||
case "aes-128":
|
||||
kcpArgs.Block, _ = kcp.NewAESBlockCrypt(pass[:16])
|
||||
case "aes-192":
|
||||
kcpArgs.Block, _ = kcp.NewAESBlockCrypt(pass[:24])
|
||||
case "blowfish":
|
||||
kcpArgs.Block, _ = kcp.NewBlowfishBlockCrypt(pass)
|
||||
case "twofish":
|
||||
kcpArgs.Block, _ = kcp.NewTwofishBlockCrypt(pass)
|
||||
case "cast5":
|
||||
kcpArgs.Block, _ = kcp.NewCast5BlockCrypt(pass[:16])
|
||||
case "3des":
|
||||
kcpArgs.Block, _ = kcp.NewTripleDESBlockCrypt(pass[:24])
|
||||
case "xtea":
|
||||
kcpArgs.Block, _ = kcp.NewXTEABlockCrypt(pass[:16])
|
||||
case "salsa20":
|
||||
kcpArgs.Block, _ = kcp.NewSalsa20BlockCrypt(pass)
|
||||
default:
|
||||
*kcpArgs.Crypt = "aes"
|
||||
kcpArgs.Block, _ = kcp.NewAESBlockCrypt(pass)
|
||||
}
|
||||
//attach kcp config
|
||||
tcpArgs.KCP = kcpArgs
|
||||
httpArgs.KCP = kcpArgs
|
||||
socksArgs.KCP = kcpArgs
|
||||
spsArgs.KCP = kcpArgs
|
||||
muxBridgeArgs.KCP = kcpArgs
|
||||
muxServerArgs.KCP = kcpArgs
|
||||
muxClientArgs.KCP = kcpArgs
|
||||
dnsArgs.KCP = kcpArgs
|
||||
|
||||
log := logger.New(os.Stderr, "", logger.Ldate|logger.Ltime)
|
||||
flags := logger.Ldate
|
||||
if *debug {
|
||||
flags |= logger.Lshortfile | logger.Lmicroseconds
|
||||
} else {
|
||||
flags |= logger.Ltime
|
||||
}
|
||||
log.SetFlags(flags)
|
||||
|
||||
if loggerCallback == nil {
|
||||
if *nolog {
|
||||
log.SetOutput(ioutil.Discard)
|
||||
} else if *logfile != "" {
|
||||
f, e := os.OpenFile(*logfile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
|
||||
if e != nil {
|
||||
log.Fatal(e)
|
||||
}
|
||||
log.SetOutput(f)
|
||||
}
|
||||
} else {
|
||||
log.SetOutput(&logWriter{
|
||||
callback: loggerCallback,
|
||||
})
|
||||
}
|
||||
|
||||
//regist services and run service
|
||||
switch serviceName {
|
||||
case "http":
|
||||
services.Regist(serviceID, httpx.NewHTTP(), httpArgs, log)
|
||||
case "tcp":
|
||||
services.Regist(serviceID, tcpx.NewTCP(), tcpArgs, log)
|
||||
case "udp":
|
||||
services.Regist(serviceID, udpx.NewUDP(), udpArgs, log)
|
||||
case "tserver":
|
||||
services.Regist(serviceID, tunnel.NewTunnelServerManager(), tunnelServerArgs, log)
|
||||
case "tclient":
|
||||
services.Regist(serviceID, tunnel.NewTunnelClient(), tunnelClientArgs, log)
|
||||
case "tbridge":
|
||||
services.Regist(serviceID, tunnel.NewTunnelBridge(), tunnelBridgeArgs, log)
|
||||
case "server":
|
||||
services.Regist(serviceID, mux.NewMuxServerManager(), muxServerArgs, log)
|
||||
case "client":
|
||||
services.Regist(serviceID, mux.NewMuxClient(), muxClientArgs, log)
|
||||
case "bridge":
|
||||
services.Regist(serviceID, mux.NewMuxBridge(), muxBridgeArgs, log)
|
||||
case "socks":
|
||||
services.Regist(serviceID, socksx.NewSocks(), socksArgs, log)
|
||||
case "sps":
|
||||
services.Regist(serviceID, spsx.NewSPS(), spsArgs, log)
|
||||
case "dns":
|
||||
services.Regist(serviceName, NewDNS(), dnsArgs, log)
|
||||
}
|
||||
_, err = services.Run(serviceID, nil)
|
||||
if err != nil {
|
||||
return fmt.Sprintf("run service [%s:%s] fail, ERR:%s", serviceID, serviceName, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func Stop(serviceID string) {
|
||||
services.Stop(serviceID)
|
||||
}
|
||||
|
||||
func Version() string {
|
||||
return SDK_VERSION
|
||||
}
|
||||
6
sdk/windows-linux/.gitignore
vendored
Normal file
@ -0,0 +1,6 @@
|
||||
proxy-sdk.dll
|
||||
proxy-sdk.h
|
||||
proxy-sdk.so
|
||||
proxy-sdk.a
|
||||
*.tar.gz
|
||||
test.c
|
||||
BIN
sdk/windows-linux/ieshims.dll
Normal file
24
sdk/windows-linux/release_linux.sh
Executable file
@ -0,0 +1,24 @@
|
||||
#/bin/bash
|
||||
VER="v5.3"
|
||||
|
||||
rm -rf sdk-linux-*.tar.gz
|
||||
rm -rf README.md libproxy-sdk.so libproxy-sdk.h libproxy-sdk.a
|
||||
|
||||
#linux 32bit
|
||||
CGO_ENABLED=1 GOARCH=386 GOOS=linux go build -buildmode=c-archive -ldflags "-s -w" -o libproxy-sdk.a sdk.go
|
||||
CGO_ENABLED=1 GOARCH=386 GOOS=linux go build -buildmode=c-shared -ldflags "-s -w" -o libproxy-sdk.so sdk.go
|
||||
cp ../README.md .
|
||||
tar zcf sdk-linux-32bit-${VER}.tar.gz README.md libproxy-sdk.so libproxy-sdk.a libproxy-sdk.h
|
||||
rm -rf README.md libproxy-sdk.so libproxy-sdk.h libproxy-sdk.a
|
||||
|
||||
#linux 64bit
|
||||
CGO_ENABLED=1 GOARCH=amd64 GOOS=linux go build -buildmode=c-archive -ldflags "-s -w" -o libproxy-sdk.a sdk.go
|
||||
CGO_ENABLED=1 GOARCH=amd64 GOOS=linux go build -buildmode=c-shared -ldflags "-s -w" -o libproxy-sdk.so sdk.go
|
||||
cp ../README.md .
|
||||
tar zcf sdk-linux-64bit-${VER}.tar.gz README.md libproxy-sdk.so libproxy-sdk.a libproxy-sdk.h
|
||||
rm -rf README.md libproxy-sdk.so libproxy-sdk.h libproxy-sdk.a
|
||||
|
||||
echo "done."
|
||||
|
||||
|
||||
|
||||
13
sdk/windows-linux/release_mac.sh
Executable file
@ -0,0 +1,13 @@
|
||||
#/bin/bash
|
||||
VER="v5.3"
|
||||
|
||||
rm -rf *.tar.gz
|
||||
rm -rf README.md libproxy-sdk.dylib libproxy-sdk.h
|
||||
|
||||
#mac , macos required
|
||||
CGO_ENABLED=1 GOARCH=amd64 GOOS=darwin go build -buildmode=c-shared -ldflags "-s -w" -o libproxy-sdk.dylib sdk.go
|
||||
cp ../README.md .
|
||||
tar zcf sdk-mac-${VER}.tar.gz README.md libproxy-sdk.dylib libproxy-sdk.h
|
||||
rm -rf README.md libproxy-sdk.dylib libproxy-sdk.h
|
||||
|
||||
echo "done."
|
||||
28
sdk/windows-linux/release_windows.sh
Executable file
@ -0,0 +1,28 @@
|
||||
#/bin/bash
|
||||
VER="v5.3"
|
||||
|
||||
#sudo rm /usr/local/go
|
||||
#sudo ln -s /usr/local/go1.10.1 /usr/local/go
|
||||
rm -rf sdk-windows-*.tar.gz
|
||||
rm -rf README.md proxy-sdk.h proxy-sdk.dll
|
||||
|
||||
|
||||
#apt-get install gcc-multilib
|
||||
#apt-get install gcc-mingw-w64
|
||||
|
||||
#windows 64bit
|
||||
CC=x86_64-w64-mingw32-gcc GOARCH=amd64 CGO_ENABLED=1 GOOS=windows go build -buildmode=c-shared -ldflags "-s -w" -o proxy-sdk.dll sdk.go
|
||||
cp ../README.md .
|
||||
tar zcf sdk-windows-64bit-${VER}.tar.gz README.md proxy-sdk.dll proxy-sdk.h ieshims.dll
|
||||
rm -rf README.md proxy-sdk.h proxy-sdk.dll
|
||||
|
||||
#windows 32bit
|
||||
CC=i686-w64-mingw32-gcc-win32 GOARCH=386 CGO_ENABLED=1 GOOS=windows go build -buildmode=c-shared -ldflags "-s -w" -o proxy-sdk.dll sdk.go
|
||||
cp ../README.md .
|
||||
tar zcf sdk-windows-32bit-${VER}.tar.gz README.md proxy-sdk.dll proxy-sdk.h ieshims.dll
|
||||
rm -rf README.md proxy-sdk.h proxy-sdk.dll
|
||||
|
||||
#sudo rm /usr/local/go
|
||||
#sudo ln -s /usr/local/go1.8.5 /usr/local/go
|
||||
|
||||
echo "done."
|
||||
25
sdk/windows-linux/sdk.go
Normal file
@ -0,0 +1,25 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"C"
|
||||
|
||||
sdk "github.com/snail007/goproxy/sdk/android-ios"
|
||||
)
|
||||
|
||||
//export Start
|
||||
func Start(serviceID *C.char, serviceArgsStr *C.char) (errStr *C.char) {
|
||||
return C.CString(sdk.Start(C.GoString(serviceID), C.GoString(serviceArgsStr)))
|
||||
}
|
||||
|
||||
//export Stop
|
||||
func Stop(serviceID *C.char) {
|
||||
sdk.Stop(C.GoString(serviceID))
|
||||
}
|
||||
|
||||
//export Version
|
||||
func Version() (ver *C.char) {
|
||||
return C.CString(sdk.Version())
|
||||
}
|
||||
|
||||
func main() {
|
||||
}
|
||||
197
services/args.go
@ -1,197 +0,0 @@
|
||||
package services
|
||||
|
||||
import "golang.org/x/crypto/ssh"
|
||||
|
||||
// tcp := app.Command("tcp", "proxy on tcp mode")
|
||||
// t := tcp.Flag("tcp-timeout", "tcp timeout milliseconds when connect to real server or parent proxy").Default("2000").Int()
|
||||
|
||||
const (
|
||||
TYPE_TCP = "tcp"
|
||||
TYPE_UDP = "udp"
|
||||
TYPE_HTTP = "http"
|
||||
TYPE_TLS = "tls"
|
||||
TYPE_KCP = "kcp"
|
||||
CONN_CLIENT_CONTROL = uint8(1)
|
||||
CONN_CLIENT_HEARBEAT = uint8(2)
|
||||
CONN_SERVER_HEARBEAT = uint8(3)
|
||||
CONN_SERVER = uint8(4)
|
||||
CONN_CLIENT = uint8(5)
|
||||
CONN_SERVER_MUX = uint8(6)
|
||||
CONN_CLIENT_MUX = uint8(7)
|
||||
)
|
||||
|
||||
type MuxServerArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Local *string
|
||||
IsUDP *bool
|
||||
Key *string
|
||||
Remote *string
|
||||
Timeout *int
|
||||
Route *[]string
|
||||
Mgr *MuxServerManager
|
||||
IsCompress *bool
|
||||
}
|
||||
type MuxClientArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Key *string
|
||||
Timeout *int
|
||||
IsCompress *bool
|
||||
}
|
||||
type MuxBridgeArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Local *string
|
||||
Timeout *int
|
||||
IsCompress *bool
|
||||
}
|
||||
type TunnelServerArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Local *string
|
||||
IsUDP *bool
|
||||
Key *string
|
||||
Remote *string
|
||||
Timeout *int
|
||||
Route *[]string
|
||||
Mgr *TunnelServerManager
|
||||
Mux *bool
|
||||
}
|
||||
type TunnelClientArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Key *string
|
||||
Timeout *int
|
||||
Mux *bool
|
||||
}
|
||||
type TunnelBridgeArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Local *string
|
||||
Timeout *int
|
||||
Mux *bool
|
||||
}
|
||||
type TCPArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Local *string
|
||||
ParentType *string
|
||||
LocalType *string
|
||||
Timeout *int
|
||||
PoolSize *int
|
||||
CheckParentInterval *int
|
||||
KCPMethod *string
|
||||
KCPKey *string
|
||||
}
|
||||
|
||||
type HTTPArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Local *string
|
||||
Always *bool
|
||||
HTTPTimeout *int
|
||||
Interval *int
|
||||
Blocked *string
|
||||
Direct *string
|
||||
AuthFile *string
|
||||
Auth *[]string
|
||||
AuthURL *string
|
||||
AuthURLOkCode *int
|
||||
AuthURLTimeout *int
|
||||
AuthURLRetry *int
|
||||
ParentType *string
|
||||
LocalType *string
|
||||
Timeout *int
|
||||
PoolSize *int
|
||||
CheckParentInterval *int
|
||||
SSHKeyFile *string
|
||||
SSHKeyFileSalt *string
|
||||
SSHPassword *string
|
||||
SSHUser *string
|
||||
SSHKeyBytes []byte
|
||||
SSHAuthMethod ssh.AuthMethod
|
||||
KCPMethod *string
|
||||
KCPKey *string
|
||||
LocalIPS *[]string
|
||||
}
|
||||
type UDPArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Local *string
|
||||
ParentType *string
|
||||
Timeout *int
|
||||
PoolSize *int
|
||||
CheckParentInterval *int
|
||||
}
|
||||
type SocksArgs struct {
|
||||
Parent *string
|
||||
ParentType *string
|
||||
Local *string
|
||||
LocalType *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
SSHKeyFile *string
|
||||
SSHKeyFileSalt *string
|
||||
SSHPassword *string
|
||||
SSHUser *string
|
||||
SSHKeyBytes []byte
|
||||
SSHAuthMethod ssh.AuthMethod
|
||||
Timeout *int
|
||||
Always *bool
|
||||
Interval *int
|
||||
Blocked *string
|
||||
Direct *string
|
||||
AuthFile *string
|
||||
Auth *[]string
|
||||
AuthURL *string
|
||||
AuthURLOkCode *int
|
||||
AuthURLTimeout *int
|
||||
AuthURLRetry *int
|
||||
KCPMethod *string
|
||||
KCPKey *string
|
||||
UDPParent *string
|
||||
UDPLocal *string
|
||||
LocalIPS *[]string
|
||||
}
|
||||
|
||||
func (a *TCPArgs) Protocol() string {
|
||||
switch *a.LocalType {
|
||||
case TYPE_TLS:
|
||||
return TYPE_TLS
|
||||
case TYPE_TCP:
|
||||
return TYPE_TCP
|
||||
case TYPE_KCP:
|
||||
return TYPE_KCP
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
386
services/http.go
@ -1,386 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net"
|
||||
"proxy/utils"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type HTTP struct {
|
||||
outPool utils.OutPool
|
||||
cfg HTTPArgs
|
||||
checker utils.Checker
|
||||
basicAuth utils.BasicAuth
|
||||
sshClient *ssh.Client
|
||||
lockChn chan bool
|
||||
}
|
||||
|
||||
func NewHTTP() Service {
|
||||
return &HTTP{
|
||||
outPool: utils.OutPool{},
|
||||
cfg: HTTPArgs{},
|
||||
checker: utils.Checker{},
|
||||
basicAuth: utils.BasicAuth{},
|
||||
lockChn: make(chan bool, 1),
|
||||
}
|
||||
}
|
||||
func (s *HTTP) CheckArgs() {
|
||||
var err error
|
||||
if *s.cfg.Parent != "" && *s.cfg.ParentType == "" {
|
||||
log.Fatalf("parent type unkown,use -T <tls|tcp|ssh>")
|
||||
}
|
||||
if *s.cfg.ParentType == "tls" || *s.cfg.LocalType == "tls" {
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
}
|
||||
if *s.cfg.ParentType == "ssh" {
|
||||
if *s.cfg.SSHUser == "" {
|
||||
log.Fatalf("ssh user required")
|
||||
}
|
||||
if *s.cfg.SSHKeyFile == "" && *s.cfg.SSHPassword == "" {
|
||||
log.Fatalf("ssh password or key required")
|
||||
}
|
||||
|
||||
if *s.cfg.SSHPassword != "" {
|
||||
s.cfg.SSHAuthMethod = ssh.Password(*s.cfg.SSHPassword)
|
||||
} else {
|
||||
var SSHSigner ssh.Signer
|
||||
s.cfg.SSHKeyBytes, err = ioutil.ReadFile(*s.cfg.SSHKeyFile)
|
||||
if err != nil {
|
||||
log.Fatalf("read key file ERR: %s", err)
|
||||
}
|
||||
if *s.cfg.SSHKeyFileSalt != "" {
|
||||
SSHSigner, err = ssh.ParsePrivateKeyWithPassphrase(s.cfg.SSHKeyBytes, []byte(*s.cfg.SSHKeyFileSalt))
|
||||
} else {
|
||||
SSHSigner, err = ssh.ParsePrivateKey(s.cfg.SSHKeyBytes)
|
||||
}
|
||||
if err != nil {
|
||||
log.Fatalf("parse ssh private key fail,ERR: %s", err)
|
||||
}
|
||||
s.cfg.SSHAuthMethod = ssh.PublicKeys(SSHSigner)
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *HTTP) InitService() {
|
||||
s.InitBasicAuth()
|
||||
if *s.cfg.Parent != "" {
|
||||
s.checker = utils.NewChecker(*s.cfg.HTTPTimeout, int64(*s.cfg.Interval), *s.cfg.Blocked, *s.cfg.Direct)
|
||||
}
|
||||
if *s.cfg.ParentType == "ssh" {
|
||||
err := s.ConnectSSH()
|
||||
if err != nil {
|
||||
log.Fatalf("init service fail, ERR: %s", err)
|
||||
}
|
||||
go func() {
|
||||
//循环检查ssh网络连通性
|
||||
for {
|
||||
conn, err := utils.ConnectHost(*s.cfg.Parent, *s.cfg.Timeout*2)
|
||||
if err == nil {
|
||||
_, err = conn.Write([]byte{0})
|
||||
}
|
||||
if err != nil {
|
||||
if s.sshClient != nil {
|
||||
s.sshClient.Close()
|
||||
if s.sshClient.Conn != nil {
|
||||
s.sshClient.Conn.Close()
|
||||
}
|
||||
}
|
||||
log.Printf("ssh offline, retrying...")
|
||||
s.ConnectSSH()
|
||||
} else {
|
||||
conn.Close()
|
||||
}
|
||||
time.Sleep(time.Second * 3)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
func (s *HTTP) StopService() {
|
||||
if s.outPool.Pool != nil {
|
||||
s.outPool.Pool.ReleaseAll()
|
||||
}
|
||||
}
|
||||
func (s *HTTP) Start(args interface{}) (err error) {
|
||||
s.cfg = args.(HTTPArgs)
|
||||
s.CheckArgs()
|
||||
if *s.cfg.Parent != "" {
|
||||
log.Printf("use %s parent %s", *s.cfg.ParentType, *s.cfg.Parent)
|
||||
s.InitOutConnPool()
|
||||
}
|
||||
s.InitService()
|
||||
for _, addr := range strings.Split(*s.cfg.Local, ",") {
|
||||
if addr != "" {
|
||||
host, port, _ := net.SplitHostPort(addr)
|
||||
p, _ := strconv.Atoi(port)
|
||||
sc := utils.NewServerChannel(host, p)
|
||||
if *s.cfg.LocalType == TYPE_TCP {
|
||||
err = sc.ListenTCP(s.callback)
|
||||
} else if *s.cfg.LocalType == TYPE_TLS {
|
||||
err = sc.ListenTls(s.cfg.CertBytes, s.cfg.KeyBytes, s.callback)
|
||||
} else if *s.cfg.LocalType == TYPE_KCP {
|
||||
err = sc.ListenKCP(*s.cfg.KCPMethod, *s.cfg.KCPKey, s.callback)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
log.Printf("%s http(s) proxy on %s", *s.cfg.LocalType, (*sc.Listener).Addr())
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *HTTP) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *HTTP) callback(inConn net.Conn) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Printf("http(s) conn handler crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
var err interface{}
|
||||
var req utils.HTTPRequest
|
||||
req, err = utils.NewHTTPRequest(&inConn, 4096, s.IsBasicAuth(), &s.basicAuth)
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
log.Printf("decoder error , from %s, ERR:%s", inConn.RemoteAddr(), err)
|
||||
}
|
||||
utils.CloseConn(&inConn)
|
||||
return
|
||||
}
|
||||
address := req.Host
|
||||
host, _, _ := net.SplitHostPort(address)
|
||||
useProxy := false
|
||||
if !utils.IsIternalIP(host) {
|
||||
useProxy = true
|
||||
if *s.cfg.Parent == "" {
|
||||
useProxy = false
|
||||
} else if *s.cfg.Always {
|
||||
useProxy = true
|
||||
} else {
|
||||
s.checker.Add(address)
|
||||
//var n, m uint
|
||||
useProxy, _, _ = s.checker.IsBlocked(req.Host)
|
||||
//log.Printf("blocked ? : %v, %s , fail:%d ,success:%d", useProxy, address, n, m)
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("use proxy : %v, %s", useProxy, address)
|
||||
|
||||
err = s.OutToTCP(useProxy, address, &inConn, &req)
|
||||
|
||||
if err != nil {
|
||||
if *s.cfg.Parent == "" {
|
||||
log.Printf("connect to %s fail, ERR:%s", address, err)
|
||||
} else {
|
||||
log.Printf("connect to %s parent %s fail", *s.cfg.ParentType, *s.cfg.Parent)
|
||||
}
|
||||
utils.CloseConn(&inConn)
|
||||
}
|
||||
}
|
||||
func (s *HTTP) OutToTCP(useProxy bool, address string, inConn *net.Conn, req *utils.HTTPRequest) (err interface{}) {
|
||||
inAddr := (*inConn).RemoteAddr().String()
|
||||
inLocalAddr := (*inConn).LocalAddr().String()
|
||||
//防止死循环
|
||||
if s.IsDeadLoop(inLocalAddr, req.Host) {
|
||||
utils.CloseConn(inConn)
|
||||
err = fmt.Errorf("dead loop detected , %s", req.Host)
|
||||
return
|
||||
}
|
||||
var outConn net.Conn
|
||||
var _outConn interface{}
|
||||
tryCount := 0
|
||||
maxTryCount := 5
|
||||
for {
|
||||
if useProxy {
|
||||
if *s.cfg.ParentType == "ssh" {
|
||||
outConn, err = s.getSSHConn(address)
|
||||
} else {
|
||||
//log.Printf("%v", s.outPool)
|
||||
_outConn, err = s.outPool.Pool.Get()
|
||||
if err == nil {
|
||||
outConn = _outConn.(net.Conn)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
outConn, err = utils.ConnectHost(address, *s.cfg.Timeout)
|
||||
}
|
||||
tryCount++
|
||||
if err == nil || tryCount > maxTryCount {
|
||||
break
|
||||
} else {
|
||||
log.Printf("connect to %s , err:%s,retrying...", *s.cfg.Parent, err)
|
||||
time.Sleep(time.Second * 2)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("connect to %s , err:%s", *s.cfg.Parent, err)
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
|
||||
outAddr := outConn.RemoteAddr().String()
|
||||
//outLocalAddr := outConn.LocalAddr().String()
|
||||
|
||||
if req.IsHTTPS() && (!useProxy || *s.cfg.ParentType == "ssh") {
|
||||
//https无上级或者上级非代理,proxy需要响应connect请求,并直连目标
|
||||
err = req.HTTPSReply()
|
||||
} else {
|
||||
//https或者http,上级是代理,proxy需要转发
|
||||
_, err = outConn.Write(req.HeadBuf)
|
||||
if err != nil {
|
||||
log.Printf("write to %s , err:%s", *s.cfg.Parent, err)
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
utils.IoBind((*inConn), outConn, func(err interface{}) {
|
||||
log.Printf("conn %s - %s released [%s]", inAddr, outAddr, req.Host)
|
||||
})
|
||||
log.Printf("conn %s - %s connected [%s]", inAddr, outAddr, req.Host)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (s *HTTP) getSSHConn(host string) (outConn net.Conn, err interface{}) {
|
||||
maxTryCount := 1
|
||||
tryCount := 0
|
||||
RETRY:
|
||||
if tryCount >= maxTryCount {
|
||||
return
|
||||
}
|
||||
wait := make(chan bool, 1)
|
||||
go func() {
|
||||
defer func() {
|
||||
if err == nil {
|
||||
err = recover()
|
||||
}
|
||||
wait <- true
|
||||
}()
|
||||
outConn, err = s.sshClient.Dial("tcp", host)
|
||||
}()
|
||||
select {
|
||||
case <-wait:
|
||||
case <-time.After(time.Second * 5):
|
||||
err = fmt.Errorf("ssh dial %s timeout", host)
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("connect ssh fail, ERR: %s, retrying...", err)
|
||||
e := s.ConnectSSH()
|
||||
if e == nil {
|
||||
tryCount++
|
||||
time.Sleep(time.Second * 3)
|
||||
goto RETRY
|
||||
} else {
|
||||
err = e
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *HTTP) ConnectSSH() (err error) {
|
||||
select {
|
||||
case s.lockChn <- true:
|
||||
default:
|
||||
err = fmt.Errorf("can not connect at same time")
|
||||
return
|
||||
}
|
||||
config := ssh.ClientConfig{
|
||||
Timeout: time.Duration(*s.cfg.Timeout) * time.Millisecond,
|
||||
User: *s.cfg.SSHUser,
|
||||
Auth: []ssh.AuthMethod{s.cfg.SSHAuthMethod},
|
||||
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
if s.sshClient != nil {
|
||||
s.sshClient.Close()
|
||||
}
|
||||
s.sshClient, err = ssh.Dial("tcp", *s.cfg.Parent, &config)
|
||||
<-s.lockChn
|
||||
return
|
||||
}
|
||||
func (s *HTTP) InitOutConnPool() {
|
||||
if *s.cfg.ParentType == TYPE_TLS || *s.cfg.ParentType == TYPE_TCP || *s.cfg.ParentType == TYPE_KCP {
|
||||
//dur int, isTLS bool, certBytes, keyBytes []byte,
|
||||
//parent string, timeout int, InitialCap int, MaxCap int
|
||||
s.outPool = utils.NewOutPool(
|
||||
*s.cfg.CheckParentInterval,
|
||||
*s.cfg.ParentType,
|
||||
*s.cfg.KCPMethod,
|
||||
*s.cfg.KCPKey,
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes,
|
||||
*s.cfg.Parent,
|
||||
*s.cfg.Timeout,
|
||||
*s.cfg.PoolSize,
|
||||
*s.cfg.PoolSize*2,
|
||||
)
|
||||
}
|
||||
}
|
||||
func (s *HTTP) InitBasicAuth() (err error) {
|
||||
s.basicAuth = utils.NewBasicAuth()
|
||||
if *s.cfg.AuthURL != "" {
|
||||
s.basicAuth.SetAuthURL(*s.cfg.AuthURL, *s.cfg.AuthURLOkCode, *s.cfg.AuthURLTimeout, *s.cfg.AuthURLRetry)
|
||||
log.Printf("auth from %s", *s.cfg.AuthURL)
|
||||
}
|
||||
if *s.cfg.AuthFile != "" {
|
||||
var n = 0
|
||||
n, err = s.basicAuth.AddFromFile(*s.cfg.AuthFile)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("auth-file ERR:%s", err)
|
||||
return
|
||||
}
|
||||
log.Printf("auth data added from file %d , total:%d", n, s.basicAuth.Total())
|
||||
}
|
||||
if len(*s.cfg.Auth) > 0 {
|
||||
n := s.basicAuth.Add(*s.cfg.Auth)
|
||||
log.Printf("auth data added %d, total:%d", n, s.basicAuth.Total())
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *HTTP) IsBasicAuth() bool {
|
||||
return *s.cfg.AuthFile != "" || len(*s.cfg.Auth) > 0 || *s.cfg.AuthURL != ""
|
||||
}
|
||||
func (s *HTTP) IsDeadLoop(inLocalAddr string, host string) bool {
|
||||
inIP, inPort, err := net.SplitHostPort(inLocalAddr)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
outDomain, outPort, err := net.SplitHostPort(host)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if inPort == outPort {
|
||||
var outIPs []net.IP
|
||||
outIPs, err = net.LookupIP(outDomain)
|
||||
if err == nil {
|
||||
for _, ip := range outIPs {
|
||||
if ip.String() == inIP {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
interfaceIPs, err := utils.GetAllInterfaceAddr()
|
||||
for _, ip := range *s.cfg.LocalIPS {
|
||||
interfaceIPs = append(interfaceIPs, net.ParseIP(ip).To4())
|
||||
}
|
||||
if err == nil {
|
||||
for _, localIP := range interfaceIPs {
|
||||
for _, outIP := range outIPs {
|
||||
if localIP.Equal(outIP) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
532
services/http/http.go
Normal file
@ -0,0 +1,532 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
logger "log"
|
||||
"net"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/snail007/goproxy/services"
|
||||
"github.com/snail007/goproxy/services/kcpcfg"
|
||||
"github.com/snail007/goproxy/utils"
|
||||
"github.com/snail007/goproxy/utils/conncrypt"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type HTTPArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CaCertFile *string
|
||||
CaCertBytes []byte
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Local *string
|
||||
Always *bool
|
||||
HTTPTimeout *int
|
||||
Interval *int
|
||||
Blocked *string
|
||||
Direct *string
|
||||
AuthFile *string
|
||||
Auth *[]string
|
||||
AuthURL *string
|
||||
AuthURLOkCode *int
|
||||
AuthURLTimeout *int
|
||||
AuthURLRetry *int
|
||||
ParentType *string
|
||||
LocalType *string
|
||||
Timeout *int
|
||||
CheckParentInterval *int
|
||||
SSHKeyFile *string
|
||||
SSHKeyFileSalt *string
|
||||
SSHPassword *string
|
||||
SSHUser *string
|
||||
SSHKeyBytes []byte
|
||||
SSHAuthMethod ssh.AuthMethod
|
||||
KCP kcpcfg.KCPConfigArgs
|
||||
LocalIPS *[]string
|
||||
DNSAddress *string
|
||||
DNSTTL *int
|
||||
LocalKey *string
|
||||
ParentKey *string
|
||||
LocalCompress *bool
|
||||
ParentCompress *bool
|
||||
}
|
||||
type HTTP struct {
|
||||
outPool utils.OutConn
|
||||
cfg HTTPArgs
|
||||
checker utils.Checker
|
||||
basicAuth utils.BasicAuth
|
||||
sshClient *ssh.Client
|
||||
lockChn chan bool
|
||||
domainResolver utils.DomainResolver
|
||||
isStop bool
|
||||
serverChannels []*utils.ServerChannel
|
||||
userConns utils.ConcurrentMap
|
||||
log *logger.Logger
|
||||
}
|
||||
|
||||
func NewHTTP() services.Service {
|
||||
return &HTTP{
|
||||
outPool: utils.OutConn{},
|
||||
cfg: HTTPArgs{},
|
||||
checker: utils.Checker{},
|
||||
basicAuth: utils.BasicAuth{},
|
||||
lockChn: make(chan bool, 1),
|
||||
isStop: false,
|
||||
serverChannels: []*utils.ServerChannel{},
|
||||
userConns: utils.NewConcurrentMap(),
|
||||
}
|
||||
}
|
||||
func (s *HTTP) CheckArgs() (err error) {
|
||||
if *s.cfg.Parent != "" && *s.cfg.ParentType == "" {
|
||||
err = fmt.Errorf("parent type unkown,use -T <tls|tcp|ssh|kcp>")
|
||||
return
|
||||
}
|
||||
if *s.cfg.ParentType == "tls" || *s.cfg.LocalType == "tls" {
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes, err = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if *s.cfg.CaCertFile != "" {
|
||||
s.cfg.CaCertBytes, err = ioutil.ReadFile(*s.cfg.CaCertFile)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("read ca file error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if *s.cfg.ParentType == "ssh" {
|
||||
if *s.cfg.SSHUser == "" {
|
||||
err = fmt.Errorf("ssh user required")
|
||||
return
|
||||
}
|
||||
if *s.cfg.SSHKeyFile == "" && *s.cfg.SSHPassword == "" {
|
||||
err = fmt.Errorf("ssh password or key required")
|
||||
return
|
||||
}
|
||||
|
||||
if *s.cfg.SSHPassword != "" {
|
||||
s.cfg.SSHAuthMethod = ssh.Password(*s.cfg.SSHPassword)
|
||||
} else {
|
||||
var SSHSigner ssh.Signer
|
||||
s.cfg.SSHKeyBytes, err = ioutil.ReadFile(*s.cfg.SSHKeyFile)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("read key file ERR: %s", err)
|
||||
return
|
||||
}
|
||||
if *s.cfg.SSHKeyFileSalt != "" {
|
||||
SSHSigner, err = ssh.ParsePrivateKeyWithPassphrase(s.cfg.SSHKeyBytes, []byte(*s.cfg.SSHKeyFileSalt))
|
||||
} else {
|
||||
SSHSigner, err = ssh.ParsePrivateKey(s.cfg.SSHKeyBytes)
|
||||
}
|
||||
if err != nil {
|
||||
err = fmt.Errorf("parse ssh private key fail,ERR: %s", err)
|
||||
return
|
||||
}
|
||||
s.cfg.SSHAuthMethod = ssh.PublicKeys(SSHSigner)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *HTTP) InitService() (err error) {
|
||||
s.InitBasicAuth()
|
||||
if *s.cfg.Parent != "" {
|
||||
s.checker = utils.NewChecker(*s.cfg.HTTPTimeout, int64(*s.cfg.Interval), *s.cfg.Blocked, *s.cfg.Direct, s.log)
|
||||
}
|
||||
if *s.cfg.DNSAddress != "" {
|
||||
(*s).domainResolver = utils.NewDomainResolver(*s.cfg.DNSAddress, *s.cfg.DNSTTL, s.log)
|
||||
}
|
||||
if *s.cfg.ParentType == "ssh" {
|
||||
err = s.ConnectSSH()
|
||||
if err != nil {
|
||||
err = fmt.Errorf("init service fail, ERR: %s", err)
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
//循环检查ssh网络连通性
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
conn, err := utils.ConnectHost(s.Resolve(*s.cfg.Parent), *s.cfg.Timeout*2)
|
||||
if err == nil {
|
||||
conn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = conn.Write([]byte{0})
|
||||
conn.SetDeadline(time.Time{})
|
||||
}
|
||||
if err != nil {
|
||||
if s.sshClient != nil {
|
||||
s.sshClient.Close()
|
||||
if s.sshClient.Conn != nil {
|
||||
s.sshClient.Conn.Close()
|
||||
}
|
||||
}
|
||||
s.log.Printf("ssh offline, retrying...")
|
||||
s.ConnectSSH()
|
||||
} else {
|
||||
conn.Close()
|
||||
}
|
||||
time.Sleep(time.Second * 3)
|
||||
}
|
||||
}()
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *HTTP) StopService() {
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
s.log.Printf("stop http(s) service crashed,%s", e)
|
||||
} else {
|
||||
s.log.Printf("service http(s) stopped")
|
||||
}
|
||||
}()
|
||||
s.isStop = true
|
||||
if *s.cfg.Parent != "" {
|
||||
s.checker.Stop()
|
||||
}
|
||||
if s.sshClient != nil {
|
||||
s.sshClient.Close()
|
||||
}
|
||||
for _, sc := range s.serverChannels {
|
||||
if sc.Listener != nil && *sc.Listener != nil {
|
||||
(*sc.Listener).Close()
|
||||
}
|
||||
if sc.UDPListener != nil {
|
||||
(*sc.UDPListener).Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *HTTP) Start(args interface{}, log *logger.Logger) (err error) {
|
||||
s.log = log
|
||||
s.cfg = args.(HTTPArgs)
|
||||
if err = s.CheckArgs(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err = s.InitService(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if *s.cfg.Parent != "" {
|
||||
s.log.Printf("use %s parent %s", *s.cfg.ParentType, *s.cfg.Parent)
|
||||
s.InitOutConnPool()
|
||||
}
|
||||
|
||||
for _, addr := range strings.Split(*s.cfg.Local, ",") {
|
||||
if addr != "" {
|
||||
host, port, _ := net.SplitHostPort(addr)
|
||||
p, _ := strconv.Atoi(port)
|
||||
sc := utils.NewServerChannel(host, p, s.log)
|
||||
if *s.cfg.LocalType == "tcp" {
|
||||
err = sc.ListenTCP(s.callback)
|
||||
} else if *s.cfg.LocalType == "tls" {
|
||||
err = sc.ListenTls(s.cfg.CertBytes, s.cfg.KeyBytes, s.cfg.CaCertBytes, s.callback)
|
||||
} else if *s.cfg.LocalType == "kcp" {
|
||||
err = sc.ListenKCP(s.cfg.KCP, s.callback, s.log)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.log.Printf("%s http(s) proxy on %s", *s.cfg.LocalType, (*sc.Listener).Addr())
|
||||
s.serverChannels = append(s.serverChannels, &sc)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *HTTP) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *HTTP) callback(inConn net.Conn) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
s.log.Printf("http(s) conn handler crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
if *s.cfg.LocalCompress {
|
||||
inConn = utils.NewCompConn(inConn)
|
||||
}
|
||||
if *s.cfg.LocalKey != "" {
|
||||
inConn = conncrypt.New(inConn, &conncrypt.Config{
|
||||
Password: *s.cfg.LocalKey,
|
||||
})
|
||||
}
|
||||
var err interface{}
|
||||
var req utils.HTTPRequest
|
||||
req, err = utils.NewHTTPRequest(&inConn, 4096, s.IsBasicAuth(), &s.basicAuth, s.log)
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
s.log.Printf("decoder error , from %s, ERR:%s", inConn.RemoteAddr(), err)
|
||||
}
|
||||
utils.CloseConn(&inConn)
|
||||
return
|
||||
}
|
||||
address := req.Host
|
||||
host, _, _ := net.SplitHostPort(address)
|
||||
useProxy := false
|
||||
if !utils.IsIternalIP(host, *s.cfg.Always) {
|
||||
useProxy = true
|
||||
if *s.cfg.Parent == "" {
|
||||
useProxy = false
|
||||
} else if *s.cfg.Always {
|
||||
useProxy = true
|
||||
} else {
|
||||
var isInMap bool
|
||||
useProxy, isInMap, _, _ = s.checker.IsBlocked(address)
|
||||
if !isInMap {
|
||||
s.checker.Add(address, s.Resolve(address))
|
||||
}
|
||||
//s.log.Printf("blocked ? : %v, %s , fail:%d ,success:%d", useProxy, address, n, m)
|
||||
}
|
||||
}
|
||||
|
||||
s.log.Printf("use proxy : %v, %s", useProxy, address)
|
||||
|
||||
err = s.OutToTCP(useProxy, address, &inConn, &req)
|
||||
if err != nil {
|
||||
if *s.cfg.Parent == "" {
|
||||
s.log.Printf("connect to %s fail, ERR:%s", address, err)
|
||||
} else {
|
||||
s.log.Printf("connect to %s parent %s fail", *s.cfg.ParentType, *s.cfg.Parent)
|
||||
}
|
||||
utils.CloseConn(&inConn)
|
||||
}
|
||||
}
|
||||
func (s *HTTP) OutToTCP(useProxy bool, address string, inConn *net.Conn, req *utils.HTTPRequest) (err interface{}) {
|
||||
inAddr := (*inConn).RemoteAddr().String()
|
||||
inLocalAddr := (*inConn).LocalAddr().String()
|
||||
//防止死循环
|
||||
if s.IsDeadLoop(inLocalAddr, req.Host) {
|
||||
utils.CloseConn(inConn)
|
||||
err = fmt.Errorf("dead loop detected , %s", req.Host)
|
||||
return
|
||||
}
|
||||
var outConn net.Conn
|
||||
tryCount := 0
|
||||
maxTryCount := 5
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
if useProxy {
|
||||
if *s.cfg.ParentType == "ssh" {
|
||||
outConn, err = s.getSSHConn(address)
|
||||
} else {
|
||||
// s.log.Printf("%v", s.outPool)
|
||||
outConn, err = s.outPool.Get()
|
||||
}
|
||||
} else {
|
||||
outConn, err = utils.ConnectHost(s.Resolve(address), *s.cfg.Timeout)
|
||||
}
|
||||
tryCount++
|
||||
if err == nil || tryCount > maxTryCount {
|
||||
break
|
||||
} else {
|
||||
s.log.Printf("connect to %s , err:%s,retrying...", *s.cfg.Parent, err)
|
||||
time.Sleep(time.Second * 2)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
s.log.Printf("connect to %s , err:%s", *s.cfg.Parent, err)
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
if *s.cfg.ParentCompress {
|
||||
outConn = utils.NewCompConn(outConn)
|
||||
}
|
||||
if *s.cfg.ParentKey != "" {
|
||||
outConn = conncrypt.New(outConn, &conncrypt.Config{
|
||||
Password: *s.cfg.ParentKey,
|
||||
})
|
||||
}
|
||||
outAddr := outConn.RemoteAddr().String()
|
||||
//outLocalAddr := outConn.LocalAddr().String()
|
||||
if req.IsHTTPS() && (!useProxy || *s.cfg.ParentType == "ssh") {
|
||||
//https无上级或者上级非代理,proxy需要响应connect请求,并直连目标
|
||||
err = req.HTTPSReply()
|
||||
} else {
|
||||
//https或者http,上级是代理,proxy需要转发
|
||||
outConn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
//直连目标或上级非代理或非SNI,清理HTTP头部的代理头信息.
|
||||
if (!useProxy || *s.cfg.ParentType == "ssh") && !req.IsSNI {
|
||||
_, err = outConn.Write(utils.RemoveProxyHeaders(req.HeadBuf))
|
||||
} else {
|
||||
_, err = outConn.Write(req.HeadBuf)
|
||||
}
|
||||
outConn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("write to %s , err:%s", *s.cfg.Parent, err)
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
utils.IoBind((*inConn), outConn, func(err interface{}) {
|
||||
s.log.Printf("conn %s - %s released [%s]", inAddr, outAddr, req.Host)
|
||||
s.userConns.Remove(inAddr)
|
||||
}, s.log)
|
||||
s.log.Printf("conn %s - %s connected [%s]", inAddr, outAddr, req.Host)
|
||||
if c, ok := s.userConns.Get(inAddr); ok {
|
||||
(*c.(*net.Conn)).Close()
|
||||
}
|
||||
s.userConns.Set(inAddr, inConn)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *HTTP) getSSHConn(host string) (outConn net.Conn, err interface{}) {
|
||||
maxTryCount := 1
|
||||
tryCount := 0
|
||||
RETRY:
|
||||
if tryCount >= maxTryCount || s.isStop {
|
||||
return
|
||||
}
|
||||
wait := make(chan bool, 1)
|
||||
go func() {
|
||||
defer func() {
|
||||
if err == nil {
|
||||
err = recover()
|
||||
}
|
||||
wait <- true
|
||||
}()
|
||||
outConn, err = s.sshClient.Dial("tcp", host)
|
||||
}()
|
||||
select {
|
||||
case <-wait:
|
||||
case <-time.After(time.Second * 5):
|
||||
err = fmt.Errorf("ssh dial %s timeout", host)
|
||||
}
|
||||
if err != nil {
|
||||
s.log.Printf("connect ssh fail, ERR: %s, retrying...", err)
|
||||
e := s.ConnectSSH()
|
||||
if e == nil {
|
||||
tryCount++
|
||||
time.Sleep(time.Second * 3)
|
||||
goto RETRY
|
||||
} else {
|
||||
err = e
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *HTTP) ConnectSSH() (err error) {
|
||||
select {
|
||||
case s.lockChn <- true:
|
||||
default:
|
||||
err = fmt.Errorf("can not connect at same time")
|
||||
return
|
||||
}
|
||||
config := ssh.ClientConfig{
|
||||
Timeout: time.Duration(*s.cfg.Timeout) * time.Millisecond,
|
||||
User: *s.cfg.SSHUser,
|
||||
Auth: []ssh.AuthMethod{s.cfg.SSHAuthMethod},
|
||||
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
if s.sshClient != nil {
|
||||
s.sshClient.Close()
|
||||
}
|
||||
s.sshClient, err = ssh.Dial("tcp", s.Resolve(*s.cfg.Parent), &config)
|
||||
<-s.lockChn
|
||||
return
|
||||
}
|
||||
func (s *HTTP) InitOutConnPool() {
|
||||
if *s.cfg.ParentType == "tls" || *s.cfg.ParentType == "tcp" || *s.cfg.ParentType == "kcp" {
|
||||
//dur int, isTLS bool, certBytes, keyBytes []byte,
|
||||
//parent string, timeout int, InitialCap int, MaxCap int
|
||||
s.outPool = utils.NewOutConn(
|
||||
*s.cfg.CheckParentInterval,
|
||||
*s.cfg.ParentType,
|
||||
s.cfg.KCP,
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes, s.cfg.CaCertBytes,
|
||||
s.Resolve(*s.cfg.Parent),
|
||||
*s.cfg.Timeout,
|
||||
)
|
||||
}
|
||||
}
|
||||
func (s *HTTP) InitBasicAuth() (err error) {
|
||||
if *s.cfg.DNSAddress != "" {
|
||||
s.basicAuth = utils.NewBasicAuth(&(*s).domainResolver, s.log)
|
||||
} else {
|
||||
s.basicAuth = utils.NewBasicAuth(nil, s.log)
|
||||
}
|
||||
if *s.cfg.AuthURL != "" {
|
||||
s.basicAuth.SetAuthURL(*s.cfg.AuthURL, *s.cfg.AuthURLOkCode, *s.cfg.AuthURLTimeout, *s.cfg.AuthURLRetry)
|
||||
s.log.Printf("auth from %s", *s.cfg.AuthURL)
|
||||
}
|
||||
if *s.cfg.AuthFile != "" {
|
||||
var n = 0
|
||||
n, err = s.basicAuth.AddFromFile(*s.cfg.AuthFile)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("auth-file ERR:%s", err)
|
||||
return
|
||||
}
|
||||
s.log.Printf("auth data added from file %d , total:%d", n, s.basicAuth.Total())
|
||||
}
|
||||
if len(*s.cfg.Auth) > 0 {
|
||||
n := s.basicAuth.Add(*s.cfg.Auth)
|
||||
s.log.Printf("auth data added %d, total:%d", n, s.basicAuth.Total())
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *HTTP) IsBasicAuth() bool {
|
||||
return *s.cfg.AuthFile != "" || len(*s.cfg.Auth) > 0 || *s.cfg.AuthURL != ""
|
||||
}
|
||||
func (s *HTTP) IsDeadLoop(inLocalAddr string, host string) bool {
|
||||
inIP, inPort, err := net.SplitHostPort(inLocalAddr)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
outDomain, outPort, err := net.SplitHostPort(host)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if inPort == outPort {
|
||||
var outIPs []net.IP
|
||||
if *s.cfg.DNSAddress != "" {
|
||||
outIPs = []net.IP{net.ParseIP(s.Resolve(outDomain))}
|
||||
} else {
|
||||
outIPs, err = utils.MyLookupIP(outDomain)
|
||||
}
|
||||
if err == nil {
|
||||
for _, ip := range outIPs {
|
||||
if ip.String() == inIP {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
interfaceIPs, err := utils.GetAllInterfaceAddr()
|
||||
for _, ip := range *s.cfg.LocalIPS {
|
||||
interfaceIPs = append(interfaceIPs, net.ParseIP(ip).To4())
|
||||
}
|
||||
if err == nil {
|
||||
for _, localIP := range interfaceIPs {
|
||||
for _, outIP := range outIPs {
|
||||
if localIP.Equal(outIP) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (s *HTTP) Resolve(address string) string {
|
||||
if *s.cfg.DNSAddress == "" {
|
||||
return address
|
||||
}
|
||||
ip, err := s.domainResolver.Resolve(address)
|
||||
if err != nil {
|
||||
s.log.Printf("dns error %s , ERR:%s", address, err)
|
||||
return address
|
||||
}
|
||||
return ip
|
||||
}
|
||||
24
services/kcpcfg/args.go
Normal file
@ -0,0 +1,24 @@
|
||||
package kcpcfg
|
||||
|
||||
import kcp "github.com/xtaci/kcp-go"
|
||||
|
||||
type KCPConfigArgs struct {
|
||||
Key *string
|
||||
Crypt *string
|
||||
Mode *string
|
||||
MTU *int
|
||||
SndWnd *int
|
||||
RcvWnd *int
|
||||
DataShard *int
|
||||
ParityShard *int
|
||||
DSCP *int
|
||||
NoComp *bool
|
||||
AckNodelay *bool
|
||||
NoDelay *int
|
||||
Interval *int
|
||||
Resend *int
|
||||
NoCongestion *int
|
||||
SockBuf *int
|
||||
KeepAlive *int
|
||||
Block kcp.BlockCrypt
|
||||
}
|
||||
71
services/keygen/keygen.go
Normal file
@ -0,0 +1,71 @@
|
||||
package keygen
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
logger "log"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/snail007/goproxy/services"
|
||||
"github.com/snail007/goproxy/utils"
|
||||
"github.com/snail007/goproxy/utils/cert"
|
||||
)
|
||||
|
||||
type KeygenArgs struct {
|
||||
CaName *string
|
||||
CertName *string
|
||||
Sign *bool
|
||||
SignDays *int
|
||||
CommonName *string
|
||||
}
|
||||
|
||||
type Keygen struct {
|
||||
cfg KeygenArgs
|
||||
log *logger.Logger
|
||||
}
|
||||
|
||||
func NewKeygen() services.Service {
|
||||
return &Keygen{}
|
||||
}
|
||||
func (s *Keygen) CheckArgs() (err error) {
|
||||
if *s.cfg.Sign && (*s.cfg.CertName == "" || *s.cfg.CaName == "") {
|
||||
err = fmt.Errorf("ca name and cert name required for signin")
|
||||
return
|
||||
}
|
||||
if !*s.cfg.Sign && *s.cfg.CaName == "" {
|
||||
err = fmt.Errorf("ca name required")
|
||||
return
|
||||
}
|
||||
if *s.cfg.CommonName == "" {
|
||||
domainSubfixList := []string{".com", ".edu", ".gov", ".int", ".mil", ".net", ".org", ".biz", ".info", ".pro", ".name", ".museum", ".coop", ".aero", ".xxx", ".idv", ".ac", ".ad", ".ae", ".af", ".ag", ".ai", ".al", ".am", ".an", ".ao", ".aq", ".ar", ".as", ".at", ".au", ".aw", ".az", ".ba", ".bb", ".bd", ".be", ".bf", ".bg", ".bh", ".bi", ".bj", ".bm", ".bn", ".bo", ".br", ".bs", ".bt", ".bv", ".bw", ".by", ".bz", ".ca", ".cc", ".cd", ".cf", ".cg", ".ch", ".ci", ".ck", ".cl", ".cm", ".cn", ".co", ".cr", ".cu", ".cv", ".cx", ".cy", ".cz", ".de", ".dj", ".dk", ".dm", ".do", ".dz", ".ec", ".ee", ".eg", ".eh", ".er", ".es", ".et", ".eu", ".fi", ".fj", ".fk", ".fm", ".fo", ".fr", ".ga", ".gd", ".ge", ".gf", ".gg", ".gh", ".gi", ".gl", ".gm", ".gn", ".gp", ".gq", ".gr", ".gs", ".gt", ".gu", ".gw", ".gy", ".hk", ".hm", ".hn", ".hr", ".ht", ".hu", ".id", ".ie", ".il", ".im", ".in", ".io", ".iq", ".ir", ".is", ".it", ".je", ".jm", ".jo", ".jp", ".ke", ".kg", ".kh", ".ki", ".km", ".kn", ".kp", ".kr", ".kw", ".ky", ".kz", ".la", ".lb", ".lc", ".li", ".lk", ".lr", ".ls", ".lt", ".lu", ".lv", ".ly", ".ma", ".mc", ".md", ".mg", ".mh", ".mk", ".ml", ".mm", ".mn", ".mo", ".mp", ".mq", ".mr", ".ms", ".mt", ".mu", ".mv", ".mw", ".mx", ".my", ".mz", ".na", ".nc", ".ne", ".nf", ".ng", ".ni", ".nl", ".no", ".np", ".nr", ".nu", ".nz", ".om", ".pa", ".pe", ".pf", ".pg", ".ph", ".pk", ".pl", ".pm", ".pn", ".pr", ".ps", ".pt", ".pw", ".py", ".qa", ".re", ".ro", ".ru", ".rw", ".sa", ".sb", ".sc", ".sd", ".se", ".sg", ".sh", ".si", ".sj", ".sk", ".sl", ".sm", ".sn", ".so", ".sr", ".st", ".sv", ".sy", ".sz", ".tc", ".td", ".tf", ".tg", ".th", ".tj", ".tk", ".tl", ".tm", ".tn", ".to", ".tp", ".tr", ".tt", ".tv", ".tw", ".tz", ".ua", ".ug", ".uk", ".um", ".us", ".uy", ".uz", ".va", ".vc", ".ve", ".vg", ".vi", ".vn", ".vu", ".wf", ".ws", ".ye", ".yt", ".yu", ".yr", ".za", ".zm", ".zw"}
|
||||
CN := strings.ToLower(utils.RandString(int(utils.RandInt(4)%10)) + domainSubfixList[int(utils.RandInt(4))%len(domainSubfixList)])
|
||||
*s.cfg.CommonName = CN
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *Keygen) Start(args interface{}, log *logger.Logger) (err error) {
|
||||
s.log = log
|
||||
s.cfg = args.(KeygenArgs)
|
||||
if err = s.CheckArgs(); err != nil {
|
||||
return
|
||||
}
|
||||
if *s.cfg.Sign {
|
||||
caCert, caKey, err := cert.ParseCertAndKey(*s.cfg.CaName+".crt", *s.cfg.CaName+".key")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = cert.CreateSignCertToFile(caCert, caKey, *s.cfg.CommonName, *s.cfg.SignDays, *s.cfg.CertName)
|
||||
} else {
|
||||
err = cert.CreateCaToFile(*s.cfg.CaName, *s.cfg.CommonName, *s.cfg.SignDays)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.log.Println("success")
|
||||
os.Exit(0)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Keygen) Clean() {
|
||||
|
||||
}
|
||||
301
services/mux/mux_bridge.go
Normal file
@ -0,0 +1,301 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
logger "log"
|
||||
"math/rand"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/snail007/goproxy/services"
|
||||
"github.com/snail007/goproxy/services/kcpcfg"
|
||||
"github.com/snail007/goproxy/utils"
|
||||
//"github.com/xtaci/smux"
|
||||
smux "github.com/hashicorp/yamux"
|
||||
)
|
||||
|
||||
const (
|
||||
CONN_SERVER = uint8(4)
|
||||
CONN_CLIENT = uint8(5)
|
||||
)
|
||||
|
||||
type MuxBridgeArgs struct {
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Local *string
|
||||
LocalType *string
|
||||
Timeout *int
|
||||
IsCompress *bool
|
||||
KCP kcpcfg.KCPConfigArgs
|
||||
}
|
||||
type MuxBridge struct {
|
||||
cfg MuxBridgeArgs
|
||||
clientControlConns utils.ConcurrentMap
|
||||
serverConns utils.ConcurrentMap
|
||||
router utils.ClientKeyRouter
|
||||
l *sync.Mutex
|
||||
isStop bool
|
||||
sc *utils.ServerChannel
|
||||
log *logger.Logger
|
||||
}
|
||||
|
||||
func NewMuxBridge() services.Service {
|
||||
b := &MuxBridge{
|
||||
cfg: MuxBridgeArgs{},
|
||||
clientControlConns: utils.NewConcurrentMap(),
|
||||
serverConns: utils.NewConcurrentMap(),
|
||||
l: &sync.Mutex{},
|
||||
isStop: false,
|
||||
}
|
||||
b.router = utils.NewClientKeyRouter(&b.clientControlConns, 50000)
|
||||
return b
|
||||
}
|
||||
|
||||
func (s *MuxBridge) InitService() (err error) {
|
||||
return
|
||||
}
|
||||
func (s *MuxBridge) CheckArgs() (err error) {
|
||||
if *s.cfg.CertFile == "" || *s.cfg.KeyFile == "" {
|
||||
err = fmt.Errorf("cert and key file required")
|
||||
return
|
||||
}
|
||||
if *s.cfg.LocalType == "tls" {
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes, err = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *MuxBridge) StopService() {
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
s.log.Printf("stop bridge service crashed,%s", e)
|
||||
} else {
|
||||
s.log.Printf("service bridge stopped")
|
||||
}
|
||||
}()
|
||||
s.isStop = true
|
||||
if s.sc != nil && (*s.sc).Listener != nil {
|
||||
(*(*s.sc).Listener).Close()
|
||||
}
|
||||
for _, g := range s.clientControlConns.Items() {
|
||||
for _, session := range g.(*utils.ConcurrentMap).Items() {
|
||||
(session.(*smux.Session)).Close()
|
||||
}
|
||||
}
|
||||
for _, c := range s.serverConns.Items() {
|
||||
(*c.(*net.Conn)).Close()
|
||||
}
|
||||
}
|
||||
func (s *MuxBridge) Start(args interface{}, log *logger.Logger) (err error) {
|
||||
s.log = log
|
||||
s.cfg = args.(MuxBridgeArgs)
|
||||
if err = s.CheckArgs(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = s.InitService(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
host, port, _ := net.SplitHostPort(*s.cfg.Local)
|
||||
p, _ := strconv.Atoi(port)
|
||||
sc := utils.NewServerChannel(host, p, s.log)
|
||||
if *s.cfg.LocalType == "tcp" {
|
||||
err = sc.ListenTCP(s.handler)
|
||||
} else if *s.cfg.LocalType == "tls" {
|
||||
err = sc.ListenTls(s.cfg.CertBytes, s.cfg.KeyBytes, nil, s.handler)
|
||||
} else if *s.cfg.LocalType == "kcp" {
|
||||
err = sc.ListenKCP(s.cfg.KCP, s.handler, s.log)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.sc = &sc
|
||||
s.log.Printf("%s bridge on %s", *s.cfg.LocalType, (*sc.Listener).Addr())
|
||||
return
|
||||
}
|
||||
func (s *MuxBridge) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *MuxBridge) handler(inConn net.Conn) {
|
||||
reader := bufio.NewReader(inConn)
|
||||
|
||||
var err error
|
||||
var connType uint8
|
||||
var key string
|
||||
inConn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
err = utils.ReadPacket(reader, &connType, &key)
|
||||
inConn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("read error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
switch connType {
|
||||
case CONN_SERVER:
|
||||
var serverID string
|
||||
inAddr := inConn.RemoteAddr().String()
|
||||
inConn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
err = utils.ReadPacketData(reader, &serverID)
|
||||
inConn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("read error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
s.log.Printf("server connection %s %s connected", serverID, key)
|
||||
if c, ok := s.serverConns.Get(inAddr); ok {
|
||||
(*c.(*net.Conn)).Close()
|
||||
}
|
||||
s.serverConns.Set(inAddr, &inConn)
|
||||
session, err := smux.Server(inConn, nil)
|
||||
if err != nil {
|
||||
utils.CloseConn(&inConn)
|
||||
s.log.Printf("server session error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
stream, err := session.AcceptStream()
|
||||
if err != nil {
|
||||
session.Close()
|
||||
utils.CloseConn(&inConn)
|
||||
s.serverConns.Remove(inAddr)
|
||||
s.log.Printf("server connection %s %s released", serverID, key)
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
s.log.Printf("bridge callback crashed,err: %s", e)
|
||||
}
|
||||
}()
|
||||
s.callback(stream, serverID, key)
|
||||
}()
|
||||
}
|
||||
case CONN_CLIENT:
|
||||
s.log.Printf("client connection %s connected", key)
|
||||
session, err := smux.Client(inConn, nil)
|
||||
if err != nil {
|
||||
utils.CloseConn(&inConn)
|
||||
s.log.Printf("client session error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
keyInfo := strings.Split(key, "-")
|
||||
if len(keyInfo) != 2 {
|
||||
utils.CloseConn(&inConn)
|
||||
s.log.Printf("client key format error,key:%s", key)
|
||||
return
|
||||
}
|
||||
groupKey := keyInfo[0]
|
||||
index := keyInfo[1]
|
||||
s.l.Lock()
|
||||
defer s.l.Unlock()
|
||||
if !s.clientControlConns.Has(groupKey) {
|
||||
item := utils.NewConcurrentMap()
|
||||
s.clientControlConns.Set(groupKey, &item)
|
||||
}
|
||||
_group, _ := s.clientControlConns.Get(groupKey)
|
||||
group := _group.(*utils.ConcurrentMap)
|
||||
if v, ok := group.Get(index); ok {
|
||||
v.(*smux.Session).Close()
|
||||
}
|
||||
group.Set(index, session)
|
||||
// s.clientControlConns.Set(key, session)
|
||||
go func() {
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
if session.IsClosed() {
|
||||
s.l.Lock()
|
||||
defer s.l.Unlock()
|
||||
if sess, ok := group.Get(index); ok && sess.(*smux.Session).IsClosed() {
|
||||
group.Remove(index)
|
||||
s.log.Printf("client connection %s released", key)
|
||||
}
|
||||
if group.IsEmpty() {
|
||||
s.clientControlConns.Remove(groupKey)
|
||||
}
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}()
|
||||
//s.log.Printf("set client session,key: %s", key)
|
||||
}
|
||||
|
||||
}
|
||||
func (s *MuxBridge) callback(inConn net.Conn, serverID, key string) {
|
||||
try := 20
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
try--
|
||||
if try == 0 {
|
||||
break
|
||||
}
|
||||
if key == "*" {
|
||||
key = s.router.GetKey()
|
||||
}
|
||||
_group, ok := s.clientControlConns.Get(key)
|
||||
if !ok {
|
||||
s.log.Printf("client %s session not exists for server stream %s, retrying...", key, serverID)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
}
|
||||
group := _group.(*utils.ConcurrentMap)
|
||||
keys := group.Keys()
|
||||
keysLen := len(keys)
|
||||
i := 0
|
||||
if keysLen > 0 {
|
||||
i = rand.Intn(keysLen)
|
||||
} else {
|
||||
s.log.Printf("client %s session empty for server stream %s, retrying...", key, serverID)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
}
|
||||
index := keys[i]
|
||||
s.log.Printf("select client : %s-%s", key, index)
|
||||
session, _ := group.Get(index)
|
||||
//session.(*smux.Session).SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
stream, err := session.(*smux.Session).OpenStream()
|
||||
//session.(*smux.Session).SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("%s client session open stream %s fail, err: %s, retrying...", key, serverID, err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
s.log.Printf("stream %s -> %s created", serverID, key)
|
||||
die1 := make(chan bool, 1)
|
||||
die2 := make(chan bool, 1)
|
||||
go func() {
|
||||
io.Copy(stream, inConn)
|
||||
die1 <- true
|
||||
}()
|
||||
go func() {
|
||||
io.Copy(inConn, stream)
|
||||
die2 <- true
|
||||
}()
|
||||
select {
|
||||
case <-die1:
|
||||
case <-die2:
|
||||
}
|
||||
stream.Close()
|
||||
inConn.Close()
|
||||
s.log.Printf("%s server %s stream released", key, serverID)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
353
services/mux/mux_client.go
Normal file
@ -0,0 +1,353 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
logger "log"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/golang/snappy"
|
||||
"github.com/snail007/goproxy/services"
|
||||
"github.com/snail007/goproxy/services/kcpcfg"
|
||||
"github.com/snail007/goproxy/utils"
|
||||
"github.com/snail007/goproxy/utils/jumper"
|
||||
//"github.com/xtaci/smux"
|
||||
smux "github.com/hashicorp/yamux"
|
||||
)
|
||||
|
||||
type MuxClientArgs struct {
|
||||
Parent *string
|
||||
ParentType *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Key *string
|
||||
Timeout *int
|
||||
IsCompress *bool
|
||||
SessionCount *int
|
||||
KCP kcpcfg.KCPConfigArgs
|
||||
Jumper *string
|
||||
}
|
||||
type MuxClient struct {
|
||||
cfg MuxClientArgs
|
||||
isStop bool
|
||||
sessions utils.ConcurrentMap
|
||||
log *logger.Logger
|
||||
jumper *jumper.Jumper
|
||||
}
|
||||
|
||||
func NewMuxClient() services.Service {
|
||||
return &MuxClient{
|
||||
cfg: MuxClientArgs{},
|
||||
isStop: false,
|
||||
sessions: utils.NewConcurrentMap(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MuxClient) InitService() (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (s *MuxClient) CheckArgs() (err error) {
|
||||
if *s.cfg.Parent != "" {
|
||||
s.log.Printf("use tls parent %s", *s.cfg.Parent)
|
||||
} else {
|
||||
err = fmt.Errorf("parent required")
|
||||
return
|
||||
}
|
||||
if *s.cfg.CertFile == "" || *s.cfg.KeyFile == "" {
|
||||
err = fmt.Errorf("cert and key file required")
|
||||
return
|
||||
}
|
||||
if *s.cfg.ParentType == "tls" {
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes, err = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if *s.cfg.Jumper != "" {
|
||||
if *s.cfg.ParentType != "tls" && *s.cfg.ParentType != "tcp" {
|
||||
err = fmt.Errorf("jumper only worked of -T is tls or tcp")
|
||||
return
|
||||
}
|
||||
var j jumper.Jumper
|
||||
j, err = jumper.New(*s.cfg.Jumper, time.Millisecond*time.Duration(*s.cfg.Timeout))
|
||||
if err != nil {
|
||||
err = fmt.Errorf("parse jumper fail, err %s", err)
|
||||
return
|
||||
}
|
||||
s.jumper = &j
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *MuxClient) StopService() {
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
s.log.Printf("stop client service crashed,%s", e)
|
||||
} else {
|
||||
s.log.Printf("service client stopped")
|
||||
}
|
||||
}()
|
||||
s.isStop = true
|
||||
for _, sess := range s.sessions.Items() {
|
||||
sess.(*smux.Session).Close()
|
||||
}
|
||||
}
|
||||
func (s *MuxClient) Start(args interface{}, log *logger.Logger) (err error) {
|
||||
s.log = log
|
||||
s.cfg = args.(MuxClientArgs)
|
||||
if err = s.CheckArgs(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = s.InitService(); err != nil {
|
||||
return
|
||||
}
|
||||
s.log.Printf("client started")
|
||||
count := 1
|
||||
if *s.cfg.SessionCount > 0 {
|
||||
count = *s.cfg.SessionCount
|
||||
}
|
||||
for i := 1; i <= count; i++ {
|
||||
key := fmt.Sprintf("worker[%d]", i)
|
||||
s.log.Printf("session %s started", key)
|
||||
go func(i int) {
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
s.log.Printf("session worker crashed: %s", e)
|
||||
}
|
||||
}()
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
conn, err := s.getParentConn()
|
||||
if err != nil {
|
||||
s.log.Printf("connection err: %s, retrying...", err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = conn.Write(utils.BuildPacket(CONN_CLIENT, fmt.Sprintf("%s-%d", *s.cfg.Key, i)))
|
||||
conn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
s.log.Printf("connection err: %s, retrying...", err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
}
|
||||
session, err := smux.Server(conn, nil)
|
||||
if err != nil {
|
||||
s.log.Printf("session err: %s, retrying...", err)
|
||||
conn.Close()
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
}
|
||||
if _sess, ok := s.sessions.Get(key); ok {
|
||||
_sess.(*smux.Session).Close()
|
||||
}
|
||||
s.sessions.Set(key, session)
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
stream, err := session.AcceptStream()
|
||||
if err != nil {
|
||||
s.log.Printf("accept stream err: %s, retrying...", err)
|
||||
session.Close()
|
||||
time.Sleep(time.Second * 3)
|
||||
break
|
||||
}
|
||||
go func() {
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
s.log.Printf("stream handler crashed: %s", e)
|
||||
}
|
||||
}()
|
||||
var ID, clientLocalAddr, serverID string
|
||||
stream.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
err = utils.ReadPacketData(stream, &ID, &clientLocalAddr, &serverID)
|
||||
stream.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("read stream signal err: %s", err)
|
||||
stream.Close()
|
||||
return
|
||||
}
|
||||
s.log.Printf("worker[%d] signal revecived,server %s stream %s %s", i, serverID, ID, clientLocalAddr)
|
||||
protocol := clientLocalAddr[:3]
|
||||
localAddr := clientLocalAddr[4:]
|
||||
if protocol == "udp" {
|
||||
s.ServeUDP(stream, localAddr, ID)
|
||||
} else {
|
||||
s.ServeConn(stream, localAddr, ID)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *MuxClient) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *MuxClient) getParentConn() (conn net.Conn, err error) {
|
||||
if *s.cfg.ParentType == "tls" {
|
||||
if s.jumper == nil {
|
||||
var _conn tls.Conn
|
||||
_conn, err = utils.TlsConnectHost(*s.cfg.Parent, *s.cfg.Timeout, s.cfg.CertBytes, s.cfg.KeyBytes, nil)
|
||||
if err == nil {
|
||||
conn = net.Conn(&_conn)
|
||||
}
|
||||
} else {
|
||||
conf, err := utils.TlsConfig(s.cfg.CertBytes, s.cfg.KeyBytes, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var _c net.Conn
|
||||
_c, err = s.jumper.Dial(*s.cfg.Parent, time.Millisecond*time.Duration(*s.cfg.Timeout))
|
||||
if err == nil {
|
||||
conn = net.Conn(tls.Client(_c, conf))
|
||||
}
|
||||
}
|
||||
|
||||
} else if *s.cfg.ParentType == "kcp" {
|
||||
conn, err = utils.ConnectKCPHost(*s.cfg.Parent, s.cfg.KCP)
|
||||
} else {
|
||||
if s.jumper == nil {
|
||||
conn, err = utils.ConnectHost(*s.cfg.Parent, *s.cfg.Timeout)
|
||||
} else {
|
||||
conn, err = s.jumper.Dial(*s.cfg.Parent, time.Millisecond*time.Duration(*s.cfg.Timeout))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *MuxClient) ServeUDP(inConn *smux.Stream, localAddr, ID string) {
|
||||
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
inConn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
srcAddr, body, err := utils.ReadUDPPacket(inConn)
|
||||
inConn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("udp packet revecived fail, err: %s", err)
|
||||
s.log.Printf("connection %s released", ID)
|
||||
inConn.Close()
|
||||
break
|
||||
} else {
|
||||
//s.log.Printf("udp packet revecived:%s,%v", srcAddr, body)
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
s.log.Printf("client processUDPPacket crashed,err: %s", e)
|
||||
}
|
||||
}()
|
||||
s.processUDPPacket(inConn, srcAddr, localAddr, body)
|
||||
}()
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
// }
|
||||
}
|
||||
func (s *MuxClient) processUDPPacket(inConn *smux.Stream, srcAddr, localAddr string, body []byte) {
|
||||
dstAddr, err := net.ResolveUDPAddr("udp", localAddr)
|
||||
if err != nil {
|
||||
s.log.Printf("can't resolve address: %s", err)
|
||||
inConn.Close()
|
||||
return
|
||||
}
|
||||
clientSrcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||
conn, err := net.DialUDP("udp", clientSrcAddr, dstAddr)
|
||||
if err != nil {
|
||||
s.log.Printf("connect to udp %s fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = conn.Write(body)
|
||||
conn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("send udp packet to %s fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
//s.log.Printf("send udp packet to %s success", dstAddr.String())
|
||||
buf := make([]byte, 1024)
|
||||
conn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
length, _, err := conn.ReadFromUDP(buf)
|
||||
conn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("read udp response from %s fail ,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
respBody := buf[0:length]
|
||||
//s.log.Printf("revecived udp packet from %s , %v", dstAddr.String(), respBody)
|
||||
bs := utils.UDPPacket(srcAddr, respBody)
|
||||
(*inConn).SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = (*inConn).Write(bs)
|
||||
(*inConn).SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("send udp response fail ,ERR:%s", err)
|
||||
inConn.Close()
|
||||
return
|
||||
}
|
||||
//s.log.Printf("send udp response success ,from:%s ,%d ,%v", dstAddr.String(), len(bs), bs)
|
||||
}
|
||||
func (s *MuxClient) ServeConn(inConn *smux.Stream, localAddr, ID string) {
|
||||
var err error
|
||||
var outConn net.Conn
|
||||
i := 0
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
i++
|
||||
outConn, err = utils.ConnectHost(localAddr, *s.cfg.Timeout)
|
||||
if err == nil || i == 3 {
|
||||
break
|
||||
} else {
|
||||
if i == 3 {
|
||||
s.log.Printf("connect to %s err: %s, retrying...", localAddr, err)
|
||||
time.Sleep(2 * time.Second)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
inConn.Close()
|
||||
utils.CloseConn(&outConn)
|
||||
s.log.Printf("build connection error, err: %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
s.log.Printf("stream %s created", ID)
|
||||
if *s.cfg.IsCompress {
|
||||
die1 := make(chan bool, 1)
|
||||
die2 := make(chan bool, 1)
|
||||
go func() {
|
||||
io.Copy(outConn, snappy.NewReader(inConn))
|
||||
die1 <- true
|
||||
}()
|
||||
go func() {
|
||||
io.Copy(snappy.NewWriter(inConn), outConn)
|
||||
die2 <- true
|
||||
}()
|
||||
select {
|
||||
case <-die1:
|
||||
case <-die2:
|
||||
}
|
||||
outConn.Close()
|
||||
inConn.Close()
|
||||
s.log.Printf("%s stream %s released", *s.cfg.Key, ID)
|
||||
} else {
|
||||
utils.IoBind(inConn, outConn, func(err interface{}) {
|
||||
s.log.Printf("stream %s released", ID)
|
||||
}, s.log)
|
||||
}
|
||||
}
|
||||
510
services/mux/mux_server.go
Normal file
@ -0,0 +1,510 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
logger "log"
|
||||
"math/rand"
|
||||
"net"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/snail007/goproxy/services"
|
||||
"github.com/snail007/goproxy/services/kcpcfg"
|
||||
"github.com/snail007/goproxy/utils"
|
||||
"github.com/snail007/goproxy/utils/jumper"
|
||||
|
||||
"github.com/golang/snappy"
|
||||
//"github.com/xtaci/smux"
|
||||
smux "github.com/hashicorp/yamux"
|
||||
)
|
||||
|
||||
type MuxServerArgs struct {
|
||||
Parent *string
|
||||
ParentType *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Local *string
|
||||
IsUDP *bool
|
||||
Key *string
|
||||
Remote *string
|
||||
Timeout *int
|
||||
Route *[]string
|
||||
Mgr *MuxServerManager
|
||||
IsCompress *bool
|
||||
SessionCount *int
|
||||
KCP kcpcfg.KCPConfigArgs
|
||||
Jumper *string
|
||||
}
|
||||
|
||||
type MuxUDPItem struct {
|
||||
packet *[]byte
|
||||
localAddr *net.UDPAddr
|
||||
srcAddr *net.UDPAddr
|
||||
}
|
||||
|
||||
type MuxServerManager struct {
|
||||
cfg MuxServerArgs
|
||||
udpChn chan MuxUDPItem
|
||||
serverID string
|
||||
servers []*services.Service
|
||||
log *logger.Logger
|
||||
}
|
||||
|
||||
func NewMuxServerManager() services.Service {
|
||||
return &MuxServerManager{
|
||||
cfg: MuxServerArgs{},
|
||||
udpChn: make(chan MuxUDPItem, 50000),
|
||||
serverID: utils.Uniqueid(),
|
||||
servers: []*services.Service{},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MuxServerManager) Start(args interface{}, log *logger.Logger) (err error) {
|
||||
s.log = log
|
||||
s.cfg = args.(MuxServerArgs)
|
||||
if err = s.CheckArgs(); err != nil {
|
||||
return
|
||||
}
|
||||
if *s.cfg.Parent != "" {
|
||||
s.log.Printf("use %s parent %s", *s.cfg.ParentType, *s.cfg.Parent)
|
||||
} else {
|
||||
err = fmt.Errorf("parent required")
|
||||
return
|
||||
}
|
||||
|
||||
if err = s.InitService(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
s.log.Printf("server id: %s", s.serverID)
|
||||
//s.log.Printf("route:%v", *s.cfg.Route)
|
||||
for _, _info := range *s.cfg.Route {
|
||||
if _info == "" {
|
||||
continue
|
||||
}
|
||||
IsUDP := *s.cfg.IsUDP
|
||||
if strings.HasPrefix(_info, "udp://") {
|
||||
IsUDP = true
|
||||
}
|
||||
info := strings.TrimPrefix(_info, "udp://")
|
||||
info = strings.TrimPrefix(info, "tcp://")
|
||||
_routeInfo := strings.Split(info, "@")
|
||||
server := NewMuxServer()
|
||||
|
||||
local := _routeInfo[0]
|
||||
remote := _routeInfo[1]
|
||||
KEY := *s.cfg.Key
|
||||
if strings.HasPrefix(remote, "[") {
|
||||
KEY = remote[1:strings.LastIndex(remote, "]")]
|
||||
remote = remote[strings.LastIndex(remote, "]")+1:]
|
||||
}
|
||||
if strings.HasPrefix(remote, ":") {
|
||||
remote = fmt.Sprintf("127.0.0.1%s", remote)
|
||||
}
|
||||
err = server.Start(MuxServerArgs{
|
||||
CertBytes: s.cfg.CertBytes,
|
||||
KeyBytes: s.cfg.KeyBytes,
|
||||
Parent: s.cfg.Parent,
|
||||
CertFile: s.cfg.CertFile,
|
||||
KeyFile: s.cfg.KeyFile,
|
||||
Local: &local,
|
||||
IsUDP: &IsUDP,
|
||||
Remote: &remote,
|
||||
Key: &KEY,
|
||||
Timeout: s.cfg.Timeout,
|
||||
Mgr: s,
|
||||
IsCompress: s.cfg.IsCompress,
|
||||
SessionCount: s.cfg.SessionCount,
|
||||
KCP: s.cfg.KCP,
|
||||
ParentType: s.cfg.ParentType,
|
||||
Jumper: s.cfg.Jumper,
|
||||
}, log)
|
||||
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.servers = append(s.servers, &server)
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *MuxServerManager) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *MuxServerManager) StopService() {
|
||||
for _, server := range s.servers {
|
||||
(*server).Clean()
|
||||
}
|
||||
}
|
||||
func (s *MuxServerManager) CheckArgs() (err error) {
|
||||
if *s.cfg.CertFile == "" || *s.cfg.KeyFile == "" {
|
||||
err = fmt.Errorf("cert and key file required")
|
||||
return
|
||||
}
|
||||
if *s.cfg.ParentType == "tls" {
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes, err = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *MuxServerManager) InitService() (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
type MuxServer struct {
|
||||
cfg MuxServerArgs
|
||||
udpChn chan MuxUDPItem
|
||||
sc utils.ServerChannel
|
||||
sessions utils.ConcurrentMap
|
||||
lockChn chan bool
|
||||
isStop bool
|
||||
udpConn *net.Conn
|
||||
log *logger.Logger
|
||||
jumper *jumper.Jumper
|
||||
}
|
||||
|
||||
func NewMuxServer() services.Service {
|
||||
return &MuxServer{
|
||||
cfg: MuxServerArgs{},
|
||||
udpChn: make(chan MuxUDPItem, 50000),
|
||||
lockChn: make(chan bool, 1),
|
||||
sessions: utils.NewConcurrentMap(),
|
||||
isStop: false,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MuxServer) StopService() {
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
s.log.Printf("stop server service crashed,%s", e)
|
||||
} else {
|
||||
s.log.Printf("service server stopped")
|
||||
}
|
||||
}()
|
||||
s.isStop = true
|
||||
for _, sess := range s.sessions.Items() {
|
||||
sess.(*smux.Session).Close()
|
||||
}
|
||||
if s.sc.Listener != nil {
|
||||
(*s.sc.Listener).Close()
|
||||
}
|
||||
if s.sc.UDPListener != nil {
|
||||
(*s.sc.UDPListener).Close()
|
||||
}
|
||||
if s.udpConn != nil {
|
||||
(*s.udpConn).Close()
|
||||
}
|
||||
}
|
||||
func (s *MuxServer) InitService() (err error) {
|
||||
s.UDPConnDeamon()
|
||||
return
|
||||
}
|
||||
func (s *MuxServer) CheckArgs() (err error) {
|
||||
if *s.cfg.Remote == "" {
|
||||
err = fmt.Errorf("remote required")
|
||||
return
|
||||
}
|
||||
if *s.cfg.Jumper != "" {
|
||||
if *s.cfg.ParentType != "tls" && *s.cfg.ParentType != "tcp" {
|
||||
err = fmt.Errorf("jumper only worked of -T is tls or tcp")
|
||||
return
|
||||
}
|
||||
var j jumper.Jumper
|
||||
j, err = jumper.New(*s.cfg.Jumper, time.Millisecond*time.Duration(*s.cfg.Timeout))
|
||||
if err != nil {
|
||||
err = fmt.Errorf("parse jumper fail, err %s", err)
|
||||
return
|
||||
}
|
||||
s.jumper = &j
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *MuxServer) Start(args interface{}, log *logger.Logger) (err error) {
|
||||
s.log = log
|
||||
s.cfg = args.(MuxServerArgs)
|
||||
if err = s.CheckArgs(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = s.InitService(); err != nil {
|
||||
return
|
||||
}
|
||||
host, port, _ := net.SplitHostPort(*s.cfg.Local)
|
||||
p, _ := strconv.Atoi(port)
|
||||
s.sc = utils.NewServerChannel(host, p, s.log)
|
||||
if *s.cfg.IsUDP {
|
||||
err = s.sc.ListenUDP(func(packet []byte, localAddr, srcAddr *net.UDPAddr) {
|
||||
s.udpChn <- MuxUDPItem{
|
||||
packet: &packet,
|
||||
localAddr: localAddr,
|
||||
srcAddr: srcAddr,
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.log.Printf("server on %s", (*s.sc.UDPListener).LocalAddr())
|
||||
} else {
|
||||
err = s.sc.ListenTCP(func(inConn net.Conn) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
s.log.Printf("connection handler crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
var outConn net.Conn
|
||||
var ID string
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
outConn, ID, err = s.GetOutConn()
|
||||
if err != nil {
|
||||
utils.CloseConn(&outConn)
|
||||
s.log.Printf("connect to %s fail, err: %s, retrying...", *s.cfg.Parent, err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
s.log.Printf("%s stream %s created", *s.cfg.Key, ID)
|
||||
if *s.cfg.IsCompress {
|
||||
die1 := make(chan bool, 1)
|
||||
die2 := make(chan bool, 1)
|
||||
go func() {
|
||||
io.Copy(inConn, snappy.NewReader(outConn))
|
||||
die1 <- true
|
||||
}()
|
||||
go func() {
|
||||
io.Copy(snappy.NewWriter(outConn), inConn)
|
||||
die2 <- true
|
||||
}()
|
||||
select {
|
||||
case <-die1:
|
||||
case <-die2:
|
||||
}
|
||||
outConn.Close()
|
||||
inConn.Close()
|
||||
s.log.Printf("%s stream %s released", *s.cfg.Key, ID)
|
||||
} else {
|
||||
utils.IoBind(inConn, outConn, func(err interface{}) {
|
||||
s.log.Printf("%s stream %s released", *s.cfg.Key, ID)
|
||||
}, s.log)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.log.Printf("server on %s", (*s.sc.Listener).Addr())
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *MuxServer) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *MuxServer) GetOutConn() (outConn net.Conn, ID string, err error) {
|
||||
i := 1
|
||||
if *s.cfg.SessionCount > 0 {
|
||||
i = rand.Intn(*s.cfg.SessionCount)
|
||||
}
|
||||
outConn, err = s.GetConn(fmt.Sprintf("%d", i))
|
||||
if err != nil {
|
||||
s.log.Printf("connection err: %s", err)
|
||||
return
|
||||
}
|
||||
remoteAddr := "tcp:" + *s.cfg.Remote
|
||||
if *s.cfg.IsUDP {
|
||||
remoteAddr = "udp:" + *s.cfg.Remote
|
||||
}
|
||||
ID = utils.Uniqueid()
|
||||
outConn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = outConn.Write(utils.BuildPacketData(ID, remoteAddr, s.cfg.Mgr.serverID))
|
||||
outConn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("write stream data err: %s ,retrying...", err)
|
||||
utils.CloseConn(&outConn)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *MuxServer) GetConn(index string) (conn net.Conn, err error) {
|
||||
select {
|
||||
case s.lockChn <- true:
|
||||
default:
|
||||
err = fmt.Errorf("can not connect at same time")
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
<-s.lockChn
|
||||
}()
|
||||
var session *smux.Session
|
||||
_session, ok := s.sessions.Get(index)
|
||||
if !ok {
|
||||
var c net.Conn
|
||||
c, err = s.getParentConn()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = c.Write(utils.BuildPacket(CONN_SERVER, *s.cfg.Key, s.cfg.Mgr.serverID))
|
||||
c.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
session, err = smux.Client(c, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if _sess, ok := s.sessions.Get(index); ok {
|
||||
_sess.(*smux.Session).Close()
|
||||
}
|
||||
s.sessions.Set(index, session)
|
||||
s.log.Printf("session[%s] created", index)
|
||||
go func() {
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
if session.IsClosed() {
|
||||
s.sessions.Remove(index)
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
session = _session.(*smux.Session)
|
||||
}
|
||||
conn, err = session.OpenStream()
|
||||
if err != nil {
|
||||
session.Close()
|
||||
s.sessions.Remove(index)
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *MuxServer) getParentConn() (conn net.Conn, err error) {
|
||||
if *s.cfg.ParentType == "tls" {
|
||||
if s.jumper == nil {
|
||||
var _conn tls.Conn
|
||||
_conn, err = utils.TlsConnectHost(*s.cfg.Parent, *s.cfg.Timeout, s.cfg.CertBytes, s.cfg.KeyBytes, nil)
|
||||
if err == nil {
|
||||
conn = net.Conn(&_conn)
|
||||
}
|
||||
} else {
|
||||
conf, err := utils.TlsConfig(s.cfg.CertBytes, s.cfg.KeyBytes, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var _c net.Conn
|
||||
_c, err = s.jumper.Dial(*s.cfg.Parent, time.Millisecond*time.Duration(*s.cfg.Timeout))
|
||||
if err == nil {
|
||||
conn = net.Conn(tls.Client(_c, conf))
|
||||
}
|
||||
}
|
||||
|
||||
} else if *s.cfg.ParentType == "kcp" {
|
||||
conn, err = utils.ConnectKCPHost(*s.cfg.Parent, s.cfg.KCP)
|
||||
} else {
|
||||
if s.jumper == nil {
|
||||
conn, err = utils.ConnectHost(*s.cfg.Parent, *s.cfg.Timeout)
|
||||
} else {
|
||||
conn, err = s.jumper.Dial(*s.cfg.Parent, time.Millisecond*time.Duration(*s.cfg.Timeout))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *MuxServer) UDPConnDeamon() {
|
||||
go func() {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
s.log.Printf("udp conn deamon crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
var outConn net.Conn
|
||||
var ID string
|
||||
var err error
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
item := <-s.udpChn
|
||||
RETRY:
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
if outConn == nil {
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
outConn, ID, err = s.GetOutConn()
|
||||
if err != nil {
|
||||
outConn = nil
|
||||
utils.CloseConn(&outConn)
|
||||
s.log.Printf("connect to %s fail, err: %s, retrying...", *s.cfg.Parent, err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
go func(outConn net.Conn, ID string) {
|
||||
if s.udpConn != nil {
|
||||
(*s.udpConn).Close()
|
||||
}
|
||||
s.udpConn = &outConn
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
outConn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
srcAddrFromConn, body, err := utils.ReadUDPPacket(outConn)
|
||||
outConn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("parse revecived udp packet fail, err: %s ,%v", err, body)
|
||||
s.log.Printf("UDP deamon connection %s exited", ID)
|
||||
break
|
||||
}
|
||||
//s.log.Printf("udp packet revecived over parent , local:%s", srcAddrFromConn)
|
||||
_srcAddr := strings.Split(srcAddrFromConn, ":")
|
||||
if len(_srcAddr) != 2 {
|
||||
s.log.Printf("parse revecived udp packet fail, addr error : %s", srcAddrFromConn)
|
||||
continue
|
||||
}
|
||||
port, _ := strconv.Atoi(_srcAddr[1])
|
||||
dstAddr := &net.UDPAddr{IP: net.ParseIP(_srcAddr[0]), Port: port}
|
||||
s.sc.UDPListener.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = s.sc.UDPListener.WriteToUDP(body, dstAddr)
|
||||
s.sc.UDPListener.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("udp response to local %s fail,ERR:%s", srcAddrFromConn, err)
|
||||
continue
|
||||
}
|
||||
//s.log.Printf("udp response to local %s success , %v", srcAddrFromConn, body)
|
||||
}
|
||||
}(outConn, ID)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
outConn.SetWriteDeadline(time.Now().Add(time.Second))
|
||||
_, err = outConn.Write(utils.UDPPacket(item.srcAddr.String(), *item.packet))
|
||||
outConn.SetWriteDeadline(time.Time{})
|
||||
if err != nil {
|
||||
utils.CloseConn(&outConn)
|
||||
outConn = nil
|
||||
s.log.Printf("write udp packet to %s fail ,flush err:%s ,retrying...", *s.cfg.Parent, err)
|
||||
goto RETRY
|
||||
}
|
||||
//s.log.Printf("write packet %v", *item.packet)
|
||||
}
|
||||
}()
|
||||
}
|
||||
@ -1,155 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"proxy/utils"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
type MuxBridge struct {
|
||||
cfg MuxBridgeArgs
|
||||
clientControlConns utils.ConcurrentMap
|
||||
}
|
||||
|
||||
func NewMuxBridge() Service {
|
||||
return &MuxBridge{
|
||||
cfg: MuxBridgeArgs{},
|
||||
clientControlConns: utils.NewConcurrentMap(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MuxBridge) InitService() {
|
||||
|
||||
}
|
||||
func (s *MuxBridge) CheckArgs() {
|
||||
if *s.cfg.CertFile == "" || *s.cfg.KeyFile == "" {
|
||||
log.Fatalf("cert and key file required")
|
||||
}
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
}
|
||||
func (s *MuxBridge) StopService() {
|
||||
|
||||
}
|
||||
func (s *MuxBridge) Start(args interface{}) (err error) {
|
||||
s.cfg = args.(MuxBridgeArgs)
|
||||
s.CheckArgs()
|
||||
s.InitService()
|
||||
host, port, _ := net.SplitHostPort(*s.cfg.Local)
|
||||
p, _ := strconv.Atoi(port)
|
||||
sc := utils.NewServerChannel(host, p)
|
||||
|
||||
err = sc.ListenTls(s.cfg.CertBytes, s.cfg.KeyBytes, func(inConn net.Conn) {
|
||||
reader := bufio.NewReader(inConn)
|
||||
|
||||
var err error
|
||||
var connType uint8
|
||||
var key string
|
||||
err = utils.ReadPacket(reader, &connType, &key)
|
||||
if err != nil {
|
||||
log.Printf("read error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
switch connType {
|
||||
case CONN_SERVER:
|
||||
var serverID string
|
||||
err = utils.ReadPacketData(reader, &serverID)
|
||||
if err != nil {
|
||||
log.Printf("read error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
log.Printf("server connection %s %s connected", serverID, key)
|
||||
session, err := smux.Server(inConn, nil)
|
||||
if err != nil {
|
||||
utils.CloseConn(&inConn)
|
||||
log.Printf("server session error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
for {
|
||||
stream, err := session.AcceptStream()
|
||||
if err != nil {
|
||||
session.Close()
|
||||
utils.CloseConn(&inConn)
|
||||
return
|
||||
}
|
||||
go s.callback(stream, serverID, key)
|
||||
}
|
||||
case CONN_CLIENT:
|
||||
|
||||
log.Printf("client connection %s connected", key)
|
||||
session, err := smux.Client(inConn, nil)
|
||||
if err != nil {
|
||||
utils.CloseConn(&inConn)
|
||||
log.Printf("client session error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
s.clientControlConns.Set(key, session)
|
||||
go func() {
|
||||
for {
|
||||
if session.IsClosed() {
|
||||
s.clientControlConns.Remove(key)
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}()
|
||||
//log.Printf("set client session,key: %s", key)
|
||||
}
|
||||
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
log.Printf("proxy on mux bridge mode %s", (*sc.Listener).Addr())
|
||||
return
|
||||
}
|
||||
func (s *MuxBridge) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *MuxBridge) callback(inConn net.Conn, serverID, key string) {
|
||||
try := 20
|
||||
for {
|
||||
try--
|
||||
if try == 0 {
|
||||
break
|
||||
}
|
||||
session, ok := s.clientControlConns.Get(key)
|
||||
if !ok {
|
||||
log.Printf("client %s session not exists for server stream %s", key, serverID)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
}
|
||||
stream, err := session.(*smux.Session).OpenStream()
|
||||
if err != nil {
|
||||
log.Printf("%s client session open stream %s fail, err: %s, retrying...", key, serverID, err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
log.Printf("%s server %s stream created", key, serverID)
|
||||
die1 := make(chan bool, 1)
|
||||
die2 := make(chan bool, 1)
|
||||
go func() {
|
||||
io.Copy(stream, inConn)
|
||||
die1 <- true
|
||||
}()
|
||||
go func() {
|
||||
io.Copy(inConn, stream)
|
||||
die2 <- true
|
||||
}()
|
||||
select {
|
||||
case <-die1:
|
||||
case <-die2:
|
||||
}
|
||||
stream.Close()
|
||||
inConn.Close()
|
||||
log.Printf("%s server %s stream released", key, serverID)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,206 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"proxy/utils"
|
||||
"time"
|
||||
|
||||
"github.com/golang/snappy"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
type MuxClient struct {
|
||||
cfg MuxClientArgs
|
||||
}
|
||||
|
||||
func NewMuxClient() Service {
|
||||
return &MuxClient{
|
||||
cfg: MuxClientArgs{},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MuxClient) InitService() {
|
||||
|
||||
}
|
||||
|
||||
func (s *MuxClient) CheckArgs() {
|
||||
if *s.cfg.Parent != "" {
|
||||
log.Printf("use tls parent %s", *s.cfg.Parent)
|
||||
} else {
|
||||
log.Fatalf("parent required")
|
||||
}
|
||||
if *s.cfg.CertFile == "" || *s.cfg.KeyFile == "" {
|
||||
log.Fatalf("cert and key file required")
|
||||
}
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
}
|
||||
func (s *MuxClient) StopService() {
|
||||
|
||||
}
|
||||
func (s *MuxClient) Start(args interface{}) (err error) {
|
||||
s.cfg = args.(MuxClientArgs)
|
||||
s.CheckArgs()
|
||||
s.InitService()
|
||||
log.Printf("proxy on mux client mode, compress %v", *s.cfg.IsCompress)
|
||||
for {
|
||||
var _conn tls.Conn
|
||||
_conn, err = utils.TlsConnectHost(*s.cfg.Parent, *s.cfg.Timeout, s.cfg.CertBytes, s.cfg.KeyBytes)
|
||||
if err != nil {
|
||||
log.Printf("connection err: %s, retrying...", err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
}
|
||||
conn := net.Conn(&_conn)
|
||||
_, err = conn.Write(utils.BuildPacket(CONN_CLIENT, *s.cfg.Key))
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
log.Printf("connection err: %s, retrying...", err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
}
|
||||
session, err := smux.Server(conn, nil)
|
||||
if err != nil {
|
||||
log.Printf("session err: %s, retrying...", err)
|
||||
conn.Close()
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
}
|
||||
for {
|
||||
stream, err := session.AcceptStream()
|
||||
if err != nil {
|
||||
log.Printf("accept stream err: %s, retrying...", err)
|
||||
session.Close()
|
||||
time.Sleep(time.Second * 3)
|
||||
break
|
||||
}
|
||||
go func() {
|
||||
var ID, clientLocalAddr, serverID string
|
||||
err = utils.ReadPacketData(stream, &ID, &clientLocalAddr, &serverID)
|
||||
if err != nil {
|
||||
log.Printf("read stream signal err: %s", err)
|
||||
stream.Close()
|
||||
return
|
||||
}
|
||||
log.Printf("signal revecived,server %s stream %s %s", serverID, ID, clientLocalAddr)
|
||||
protocol := clientLocalAddr[:3]
|
||||
localAddr := clientLocalAddr[4:]
|
||||
if protocol == "udp" {
|
||||
s.ServeUDP(stream, localAddr, ID)
|
||||
} else {
|
||||
s.ServeConn(stream, localAddr, ID)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
func (s *MuxClient) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
|
||||
func (s *MuxClient) ServeUDP(inConn *smux.Stream, localAddr, ID string) {
|
||||
|
||||
for {
|
||||
srcAddr, body, err := utils.ReadUDPPacket(inConn)
|
||||
if err != nil {
|
||||
log.Printf("udp packet revecived fail, err: %s", err)
|
||||
log.Printf("connection %s released", ID)
|
||||
inConn.Close()
|
||||
break
|
||||
} else {
|
||||
//log.Printf("udp packet revecived:%s,%v", srcAddr, body)
|
||||
go s.processUDPPacket(inConn, srcAddr, localAddr, body)
|
||||
}
|
||||
|
||||
}
|
||||
// }
|
||||
}
|
||||
func (s *MuxClient) processUDPPacket(inConn *smux.Stream, srcAddr, localAddr string, body []byte) {
|
||||
dstAddr, err := net.ResolveUDPAddr("udp", localAddr)
|
||||
if err != nil {
|
||||
log.Printf("can't resolve address: %s", err)
|
||||
inConn.Close()
|
||||
return
|
||||
}
|
||||
clientSrcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||
conn, err := net.DialUDP("udp", clientSrcAddr, dstAddr)
|
||||
if err != nil {
|
||||
log.Printf("connect to udp %s fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = conn.Write(body)
|
||||
if err != nil {
|
||||
log.Printf("send udp packet to %s fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
//log.Printf("send udp packet to %s success", dstAddr.String())
|
||||
buf := make([]byte, 1024)
|
||||
length, _, err := conn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
log.Printf("read udp response from %s fail ,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
respBody := buf[0:length]
|
||||
//log.Printf("revecived udp packet from %s , %v", dstAddr.String(), respBody)
|
||||
bs := utils.UDPPacket(srcAddr, respBody)
|
||||
_, err = (*inConn).Write(bs)
|
||||
if err != nil {
|
||||
log.Printf("send udp response fail ,ERR:%s", err)
|
||||
inConn.Close()
|
||||
return
|
||||
}
|
||||
//log.Printf("send udp response success ,from:%s ,%d ,%v", dstAddr.String(), len(bs), bs)
|
||||
}
|
||||
func (s *MuxClient) ServeConn(inConn *smux.Stream, localAddr, ID string) {
|
||||
var err error
|
||||
var outConn net.Conn
|
||||
i := 0
|
||||
for {
|
||||
i++
|
||||
outConn, err = utils.ConnectHost(localAddr, *s.cfg.Timeout)
|
||||
if err == nil || i == 3 {
|
||||
break
|
||||
} else {
|
||||
if i == 3 {
|
||||
log.Printf("connect to %s err: %s, retrying...", localAddr, err)
|
||||
time.Sleep(2 * time.Second)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
inConn.Close()
|
||||
utils.CloseConn(&outConn)
|
||||
log.Printf("build connection error, err: %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("stream %s created", ID)
|
||||
if *s.cfg.IsCompress {
|
||||
die1 := make(chan bool, 1)
|
||||
die2 := make(chan bool, 1)
|
||||
go func() {
|
||||
io.Copy(outConn, snappy.NewReader(inConn))
|
||||
die1 <- true
|
||||
}()
|
||||
go func() {
|
||||
io.Copy(snappy.NewWriter(inConn), outConn)
|
||||
die2 <- true
|
||||
}()
|
||||
select {
|
||||
case <-die1:
|
||||
case <-die2:
|
||||
}
|
||||
outConn.Close()
|
||||
inConn.Close()
|
||||
log.Printf("%s stream %s released", *s.cfg.Key, ID)
|
||||
} else {
|
||||
utils.IoBind(inConn, outConn, func(err interface{}) {
|
||||
log.Printf("stream %s released", ID)
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -1,333 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"proxy/utils"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/golang/snappy"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
type MuxServer struct {
|
||||
cfg MuxServerArgs
|
||||
udpChn chan MuxUDPItem
|
||||
sc utils.ServerChannel
|
||||
session *smux.Session
|
||||
lockChn chan bool
|
||||
}
|
||||
|
||||
type MuxServerManager struct {
|
||||
cfg MuxServerArgs
|
||||
udpChn chan MuxUDPItem
|
||||
sc utils.ServerChannel
|
||||
serverID string
|
||||
}
|
||||
|
||||
func NewMuxServerManager() Service {
|
||||
return &MuxServerManager{
|
||||
cfg: MuxServerArgs{},
|
||||
udpChn: make(chan MuxUDPItem, 50000),
|
||||
serverID: utils.Uniqueid(),
|
||||
}
|
||||
}
|
||||
func (s *MuxServerManager) Start(args interface{}) (err error) {
|
||||
s.cfg = args.(MuxServerArgs)
|
||||
s.CheckArgs()
|
||||
if *s.cfg.Parent != "" {
|
||||
log.Printf("use tls parent %s", *s.cfg.Parent)
|
||||
} else {
|
||||
log.Fatalf("parent required")
|
||||
}
|
||||
|
||||
s.InitService()
|
||||
|
||||
log.Printf("server id: %s", s.serverID)
|
||||
//log.Printf("route:%v", *s.cfg.Route)
|
||||
for _, _info := range *s.cfg.Route {
|
||||
if _info == "" {
|
||||
continue
|
||||
}
|
||||
IsUDP := *s.cfg.IsUDP
|
||||
if strings.HasPrefix(_info, "udp://") {
|
||||
IsUDP = true
|
||||
}
|
||||
info := strings.TrimPrefix(_info, "udp://")
|
||||
info = strings.TrimPrefix(info, "tcp://")
|
||||
_routeInfo := strings.Split(info, "@")
|
||||
server := NewMuxServer()
|
||||
local := _routeInfo[0]
|
||||
remote := _routeInfo[1]
|
||||
KEY := *s.cfg.Key
|
||||
if strings.HasPrefix(remote, "[") {
|
||||
KEY = remote[1:strings.LastIndex(remote, "]")]
|
||||
remote = remote[strings.LastIndex(remote, "]")+1:]
|
||||
}
|
||||
if strings.HasPrefix(remote, ":") {
|
||||
remote = fmt.Sprintf("127.0.0.1%s", remote)
|
||||
}
|
||||
err = server.Start(MuxServerArgs{
|
||||
CertBytes: s.cfg.CertBytes,
|
||||
KeyBytes: s.cfg.KeyBytes,
|
||||
Parent: s.cfg.Parent,
|
||||
CertFile: s.cfg.CertFile,
|
||||
KeyFile: s.cfg.KeyFile,
|
||||
Local: &local,
|
||||
IsUDP: &IsUDP,
|
||||
Remote: &remote,
|
||||
Key: &KEY,
|
||||
Timeout: s.cfg.Timeout,
|
||||
Mgr: s,
|
||||
IsCompress: s.cfg.IsCompress,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *MuxServerManager) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *MuxServerManager) StopService() {
|
||||
}
|
||||
func (s *MuxServerManager) CheckArgs() {
|
||||
if *s.cfg.CertFile == "" || *s.cfg.KeyFile == "" {
|
||||
log.Fatalf("cert and key file required")
|
||||
}
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
}
|
||||
func (s *MuxServerManager) InitService() {
|
||||
}
|
||||
|
||||
func NewMuxServer() Service {
|
||||
return &MuxServer{
|
||||
cfg: MuxServerArgs{},
|
||||
udpChn: make(chan MuxUDPItem, 50000),
|
||||
lockChn: make(chan bool, 1),
|
||||
}
|
||||
}
|
||||
|
||||
type MuxUDPItem struct {
|
||||
packet *[]byte
|
||||
localAddr *net.UDPAddr
|
||||
srcAddr *net.UDPAddr
|
||||
}
|
||||
|
||||
func (s *MuxServer) InitService() {
|
||||
s.UDPConnDeamon()
|
||||
}
|
||||
func (s *MuxServer) CheckArgs() {
|
||||
if *s.cfg.Remote == "" {
|
||||
log.Fatalf("remote required")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MuxServer) Start(args interface{}) (err error) {
|
||||
s.cfg = args.(MuxServerArgs)
|
||||
s.CheckArgs()
|
||||
s.InitService()
|
||||
host, port, _ := net.SplitHostPort(*s.cfg.Local)
|
||||
p, _ := strconv.Atoi(port)
|
||||
s.sc = utils.NewServerChannel(host, p)
|
||||
if *s.cfg.IsUDP {
|
||||
err = s.sc.ListenUDP(func(packet []byte, localAddr, srcAddr *net.UDPAddr) {
|
||||
s.udpChn <- MuxUDPItem{
|
||||
packet: &packet,
|
||||
localAddr: localAddr,
|
||||
srcAddr: srcAddr,
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
log.Printf("proxy on udp mux server mode %s", (*s.sc.UDPListener).LocalAddr())
|
||||
} else {
|
||||
err = s.sc.ListenTCP(func(inConn net.Conn) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Printf("connection handler crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
var outConn net.Conn
|
||||
var ID string
|
||||
for {
|
||||
outConn, ID, err = s.GetOutConn()
|
||||
if err != nil {
|
||||
utils.CloseConn(&outConn)
|
||||
log.Printf("connect to %s fail, err: %s, retrying...", *s.cfg.Parent, err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
log.Printf("%s stream %s created", *s.cfg.Key, ID)
|
||||
if *s.cfg.IsCompress {
|
||||
die1 := make(chan bool, 1)
|
||||
die2 := make(chan bool, 1)
|
||||
go func() {
|
||||
io.Copy(inConn, snappy.NewReader(outConn))
|
||||
die1 <- true
|
||||
}()
|
||||
go func() {
|
||||
io.Copy(snappy.NewWriter(outConn), inConn)
|
||||
die2 <- true
|
||||
}()
|
||||
select {
|
||||
case <-die1:
|
||||
case <-die2:
|
||||
}
|
||||
outConn.Close()
|
||||
inConn.Close()
|
||||
log.Printf("%s stream %s released", *s.cfg.Key, ID)
|
||||
} else {
|
||||
utils.IoBind(inConn, outConn, func(err interface{}) {
|
||||
log.Printf("%s stream %s released", *s.cfg.Key, ID)
|
||||
})
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
log.Printf("proxy on mux server mode %s, compress %v", (*s.sc.Listener).Addr(), *s.cfg.IsCompress)
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *MuxServer) Clean() {
|
||||
|
||||
}
|
||||
func (s *MuxServer) GetOutConn() (outConn net.Conn, ID string, err error) {
|
||||
outConn, err = s.GetConn()
|
||||
if err != nil {
|
||||
log.Printf("connection err: %s", err)
|
||||
return
|
||||
}
|
||||
remoteAddr := "tcp:" + *s.cfg.Remote
|
||||
if *s.cfg.IsUDP {
|
||||
remoteAddr = "udp:" + *s.cfg.Remote
|
||||
}
|
||||
ID = utils.Uniqueid()
|
||||
_, err = outConn.Write(utils.BuildPacketData(ID, remoteAddr, s.cfg.Mgr.serverID))
|
||||
if err != nil {
|
||||
log.Printf("write stream data err: %s ,retrying...", err)
|
||||
utils.CloseConn(&outConn)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *MuxServer) GetConn() (conn net.Conn, err error) {
|
||||
select {
|
||||
case s.lockChn <- true:
|
||||
default:
|
||||
err = fmt.Errorf("can not connect at same time")
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
<-s.lockChn
|
||||
}()
|
||||
if s.session == nil {
|
||||
var _conn tls.Conn
|
||||
_conn, err = utils.TlsConnectHost(*s.cfg.Parent, *s.cfg.Timeout, s.cfg.CertBytes, s.cfg.KeyBytes)
|
||||
if err != nil {
|
||||
s.session = nil
|
||||
return
|
||||
}
|
||||
c := net.Conn(&_conn)
|
||||
_, err = c.Write(utils.BuildPacket(CONN_SERVER, *s.cfg.Key, s.cfg.Mgr.serverID))
|
||||
if err != nil {
|
||||
c.Close()
|
||||
s.session = nil
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
s.session, err = smux.Client(c, nil)
|
||||
if err != nil {
|
||||
s.session = nil
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
conn, err = s.session.OpenStream()
|
||||
if err != nil {
|
||||
s.session.Close()
|
||||
s.session = nil
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
func (s *MuxServer) UDPConnDeamon() {
|
||||
go func() {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Printf("udp conn deamon crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
var outConn net.Conn
|
||||
var ID string
|
||||
var err error
|
||||
for {
|
||||
item := <-s.udpChn
|
||||
RETRY:
|
||||
if outConn == nil {
|
||||
for {
|
||||
outConn, ID, err = s.GetOutConn()
|
||||
if err != nil {
|
||||
outConn = nil
|
||||
utils.CloseConn(&outConn)
|
||||
log.Printf("connect to %s fail, err: %s, retrying...", *s.cfg.Parent, err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
go func(outConn net.Conn, ID string) {
|
||||
go func() {
|
||||
// outConn.Close()
|
||||
}()
|
||||
for {
|
||||
srcAddrFromConn, body, err := utils.ReadUDPPacket(outConn)
|
||||
if err != nil {
|
||||
log.Printf("parse revecived udp packet fail, err: %s ,%v", err, body)
|
||||
log.Printf("UDP deamon connection %s exited", ID)
|
||||
break
|
||||
}
|
||||
//log.Printf("udp packet revecived over parent , local:%s", srcAddrFromConn)
|
||||
_srcAddr := strings.Split(srcAddrFromConn, ":")
|
||||
if len(_srcAddr) != 2 {
|
||||
log.Printf("parse revecived udp packet fail, addr error : %s", srcAddrFromConn)
|
||||
continue
|
||||
}
|
||||
port, _ := strconv.Atoi(_srcAddr[1])
|
||||
dstAddr := &net.UDPAddr{IP: net.ParseIP(_srcAddr[0]), Port: port}
|
||||
_, err = s.sc.UDPListener.WriteToUDP(body, dstAddr)
|
||||
if err != nil {
|
||||
log.Printf("udp response to local %s fail,ERR:%s", srcAddrFromConn, err)
|
||||
continue
|
||||
}
|
||||
//log.Printf("udp response to local %s success , %v", srcAddrFromConn, body)
|
||||
}
|
||||
}(outConn, ID)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
outConn.SetWriteDeadline(time.Now().Add(time.Second))
|
||||
_, err = outConn.Write(utils.UDPPacket(item.srcAddr.String(), *item.packet))
|
||||
outConn.SetWriteDeadline(time.Time{})
|
||||
if err != nil {
|
||||
utils.CloseConn(&outConn)
|
||||
outConn = nil
|
||||
log.Printf("write udp packet to %s fail ,flush err:%s ,retrying...", *s.cfg.Parent, err)
|
||||
goto RETRY
|
||||
}
|
||||
//log.Printf("write packet %v", *item.packet)
|
||||
}
|
||||
}()
|
||||
}
|
||||
@ -2,50 +2,64 @@ package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
logger "log"
|
||||
"runtime/debug"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Service interface {
|
||||
Start(args interface{}) (err error)
|
||||
Start(args interface{}, log *logger.Logger) (err error)
|
||||
Clean()
|
||||
}
|
||||
type ServiceItem struct {
|
||||
S Service
|
||||
Args interface{}
|
||||
Name string
|
||||
Log *logger.Logger
|
||||
}
|
||||
|
||||
var servicesMap = map[string]*ServiceItem{}
|
||||
var servicesMap = sync.Map{}
|
||||
|
||||
func Regist(name string, s Service, args interface{}) {
|
||||
servicesMap[name] = &ServiceItem{
|
||||
func Regist(name string, s Service, args interface{}, log *logger.Logger) {
|
||||
Stop(name)
|
||||
servicesMap.Store(name, &ServiceItem{
|
||||
S: s,
|
||||
Args: args,
|
||||
Name: name,
|
||||
Log: log,
|
||||
})
|
||||
}
|
||||
func GetService(name string) *ServiceItem {
|
||||
if s, ok := servicesMap.Load(name); ok && s.(*ServiceItem).S != nil {
|
||||
return s.(*ServiceItem)
|
||||
}
|
||||
return nil
|
||||
|
||||
}
|
||||
func Stop(name string) {
|
||||
if s, ok := servicesMap.Load(name); ok && s.(*ServiceItem).S != nil {
|
||||
s.(*ServiceItem).S.Clean()
|
||||
}
|
||||
}
|
||||
func Run(name string, args ...interface{}) (service *ServiceItem, err error) {
|
||||
service, ok := servicesMap[name]
|
||||
func Run(name string, args interface{}) (service *ServiceItem, err error) {
|
||||
_service, ok := servicesMap.Load(name)
|
||||
if ok {
|
||||
go func() {
|
||||
defer func() {
|
||||
err := recover()
|
||||
if err != nil {
|
||||
log.Fatalf("%s servcie crashed, ERR: %s\ntrace:%s", name, err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
if len(args) == 1 {
|
||||
err = service.S.Start(args[0])
|
||||
} else {
|
||||
err = service.S.Start(service.Args)
|
||||
}
|
||||
if err != nil {
|
||||
log.Fatalf("%s servcie fail, ERR: %s", name, err)
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
err = fmt.Errorf("%s servcie crashed, ERR: %s\ntrace:%s", name, e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
}
|
||||
if !ok {
|
||||
service = _service.(*ServiceItem)
|
||||
if args != nil {
|
||||
err = service.S.Start(args, service.Log)
|
||||
} else {
|
||||
err = service.S.Start(service.Args, service.Log)
|
||||
}
|
||||
if err != nil {
|
||||
err = fmt.Errorf("%s servcie fail, ERR: %s", name, err)
|
||||
}
|
||||
} else {
|
||||
err = fmt.Errorf("service %s not found", name)
|
||||
}
|
||||
return
|
||||
|
||||
@ -1,627 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net"
|
||||
"proxy/utils"
|
||||
"proxy/utils/aes"
|
||||
"proxy/utils/socks"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type Socks struct {
|
||||
cfg SocksArgs
|
||||
checker utils.Checker
|
||||
basicAuth utils.BasicAuth
|
||||
sshClient *ssh.Client
|
||||
lockChn chan bool
|
||||
udpSC utils.ServerChannel
|
||||
}
|
||||
|
||||
func NewSocks() Service {
|
||||
return &Socks{
|
||||
cfg: SocksArgs{},
|
||||
checker: utils.Checker{},
|
||||
basicAuth: utils.BasicAuth{},
|
||||
lockChn: make(chan bool, 1),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Socks) CheckArgs() {
|
||||
var err error
|
||||
if *s.cfg.LocalType == "tls" {
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
}
|
||||
if *s.cfg.Parent != "" {
|
||||
if *s.cfg.ParentType == "" {
|
||||
log.Fatalf("parent type unkown,use -T <tls|tcp|ssh>")
|
||||
}
|
||||
if *s.cfg.ParentType == "tls" {
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
}
|
||||
if *s.cfg.ParentType == "ssh" {
|
||||
if *s.cfg.SSHUser == "" {
|
||||
log.Fatalf("ssh user required")
|
||||
}
|
||||
if *s.cfg.SSHKeyFile == "" && *s.cfg.SSHPassword == "" {
|
||||
log.Fatalf("ssh password or key required")
|
||||
}
|
||||
if *s.cfg.SSHPassword != "" {
|
||||
s.cfg.SSHAuthMethod = ssh.Password(*s.cfg.SSHPassword)
|
||||
} else {
|
||||
var SSHSigner ssh.Signer
|
||||
s.cfg.SSHKeyBytes, err = ioutil.ReadFile(*s.cfg.SSHKeyFile)
|
||||
if err != nil {
|
||||
log.Fatalf("read key file ERR: %s", err)
|
||||
}
|
||||
if *s.cfg.SSHKeyFileSalt != "" {
|
||||
SSHSigner, err = ssh.ParsePrivateKeyWithPassphrase(s.cfg.SSHKeyBytes, []byte(*s.cfg.SSHKeyFileSalt))
|
||||
} else {
|
||||
SSHSigner, err = ssh.ParsePrivateKey(s.cfg.SSHKeyBytes)
|
||||
}
|
||||
if err != nil {
|
||||
log.Fatalf("parse ssh private key fail,ERR: %s", err)
|
||||
}
|
||||
s.cfg.SSHAuthMethod = ssh.PublicKeys(SSHSigner)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
func (s *Socks) InitService() {
|
||||
s.InitBasicAuth()
|
||||
s.checker = utils.NewChecker(*s.cfg.Timeout, int64(*s.cfg.Interval), *s.cfg.Blocked, *s.cfg.Direct)
|
||||
if *s.cfg.ParentType == "ssh" {
|
||||
err := s.ConnectSSH()
|
||||
if err != nil {
|
||||
log.Fatalf("init service fail, ERR: %s", err)
|
||||
}
|
||||
go func() {
|
||||
//循环检查ssh网络连通性
|
||||
for {
|
||||
conn, err := utils.ConnectHost(*s.cfg.Parent, *s.cfg.Timeout*2)
|
||||
if err == nil {
|
||||
_, err = conn.Write([]byte{0})
|
||||
}
|
||||
if err != nil {
|
||||
if s.sshClient != nil {
|
||||
s.sshClient.Close()
|
||||
}
|
||||
log.Printf("ssh offline, retrying...")
|
||||
s.ConnectSSH()
|
||||
} else {
|
||||
conn.Close()
|
||||
}
|
||||
time.Sleep(time.Second * 3)
|
||||
}
|
||||
}()
|
||||
}
|
||||
if *s.cfg.ParentType == "ssh" {
|
||||
log.Println("warn: socks udp not suppored for ssh")
|
||||
} else {
|
||||
|
||||
s.udpSC = utils.NewServerChannelHost(*s.cfg.UDPLocal)
|
||||
err := s.udpSC.ListenUDP(s.udpCallback)
|
||||
if err != nil {
|
||||
log.Fatalf("init udp service fail, ERR: %s", err)
|
||||
}
|
||||
log.Printf("udp socks proxy on %s", s.udpSC.UDPListener.LocalAddr())
|
||||
}
|
||||
}
|
||||
func (s *Socks) StopService() {
|
||||
if s.sshClient != nil {
|
||||
s.sshClient.Close()
|
||||
}
|
||||
if s.udpSC.UDPListener != nil {
|
||||
s.udpSC.UDPListener.Close()
|
||||
}
|
||||
}
|
||||
func (s *Socks) Start(args interface{}) (err error) {
|
||||
//start()
|
||||
s.cfg = args.(SocksArgs)
|
||||
s.CheckArgs()
|
||||
s.InitService()
|
||||
if *s.cfg.Parent != "" {
|
||||
log.Printf("use %s parent %s", *s.cfg.ParentType, *s.cfg.Parent)
|
||||
}
|
||||
sc := utils.NewServerChannelHost(*s.cfg.Local)
|
||||
if *s.cfg.LocalType == TYPE_TCP {
|
||||
err = sc.ListenTCP(s.socksConnCallback)
|
||||
} else if *s.cfg.LocalType == TYPE_TLS {
|
||||
err = sc.ListenTls(s.cfg.CertBytes, s.cfg.KeyBytes, s.socksConnCallback)
|
||||
} else if *s.cfg.LocalType == TYPE_KCP {
|
||||
err = sc.ListenKCP(*s.cfg.KCPMethod, *s.cfg.KCPKey, s.socksConnCallback)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
log.Printf("%s socks proxy on %s", *s.cfg.LocalType, (*sc.Listener).Addr())
|
||||
return
|
||||
}
|
||||
func (s *Socks) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *Socks) UDPKey() []byte {
|
||||
return s.cfg.KeyBytes[:32]
|
||||
}
|
||||
func (s *Socks) udpCallback(b []byte, localAddr, srcAddr *net.UDPAddr) {
|
||||
rawB := b
|
||||
var err error
|
||||
if *s.cfg.LocalType == "tls" {
|
||||
//decode b
|
||||
rawB, err = goaes.Decrypt(s.UDPKey(), b)
|
||||
if err != nil {
|
||||
log.Printf("decrypt udp packet fail from %s", srcAddr.String())
|
||||
return
|
||||
}
|
||||
}
|
||||
p, err := socks.ParseUDPPacket(rawB)
|
||||
log.Printf("udp revecived:%v", len(p.Data()))
|
||||
if err != nil {
|
||||
log.Printf("parse udp packet fail, ERR:%s", err)
|
||||
return
|
||||
}
|
||||
//防止死循环
|
||||
if s.IsDeadLoop((*localAddr).String(), p.Host()) {
|
||||
log.Printf("dead loop detected , %s", p.Host())
|
||||
return
|
||||
}
|
||||
//log.Printf("##########udp to -> %s:%s###########", p.Host(), p.Port())
|
||||
if *s.cfg.Parent != "" {
|
||||
//有上级代理,转发给上级
|
||||
if *s.cfg.ParentType == "tls" {
|
||||
//encode b
|
||||
rawB, err = goaes.Encrypt(s.UDPKey(), rawB)
|
||||
if err != nil {
|
||||
log.Printf("encrypt udp data fail to %s", *s.cfg.Parent)
|
||||
return
|
||||
}
|
||||
}
|
||||
parent := *s.cfg.UDPParent
|
||||
if parent == "" {
|
||||
parent = *s.cfg.Parent
|
||||
}
|
||||
dstAddr, err := net.ResolveUDPAddr("udp", parent)
|
||||
if err != nil {
|
||||
log.Printf("can't resolve address: %s", err)
|
||||
return
|
||||
}
|
||||
clientSrcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||
conn, err := net.DialUDP("udp", clientSrcAddr, dstAddr)
|
||||
if err != nil {
|
||||
log.Printf("connect to udp %s fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout*5)))
|
||||
_, err = conn.Write(rawB)
|
||||
log.Printf("udp request:%v", len(rawB))
|
||||
if err != nil {
|
||||
log.Printf("send udp packet to %s fail,ERR:%s", dstAddr.String(), err)
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
|
||||
//log.Printf("send udp packet to %s success", dstAddr.String())
|
||||
buf := make([]byte, 10*1024)
|
||||
length, _, err := conn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
log.Printf("read udp response from %s fail ,ERR:%s", dstAddr.String(), err)
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
respBody := buf[0:length]
|
||||
log.Printf("udp response:%v", len(respBody))
|
||||
//log.Printf("revecived udp packet from %s", dstAddr.String())
|
||||
if *s.cfg.ParentType == "tls" {
|
||||
//decode b
|
||||
respBody, err = goaes.Decrypt(s.UDPKey(), respBody)
|
||||
if err != nil {
|
||||
log.Printf("encrypt udp data fail to %s", *s.cfg.Parent)
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
}
|
||||
if *s.cfg.LocalType == "tls" {
|
||||
d, err := goaes.Encrypt(s.UDPKey(), respBody)
|
||||
if err != nil {
|
||||
log.Printf("encrypt udp data fail from %s", dstAddr.String())
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
s.udpSC.UDPListener.WriteToUDP(d, srcAddr)
|
||||
log.Printf("udp reply:%v", len(d))
|
||||
} else {
|
||||
s.udpSC.UDPListener.WriteToUDP(respBody, srcAddr)
|
||||
log.Printf("udp reply:%v", len(respBody))
|
||||
}
|
||||
|
||||
} else {
|
||||
//本地代理
|
||||
dstAddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(p.Host(), p.Port()))
|
||||
if err != nil {
|
||||
log.Printf("can't resolve address: %s", err)
|
||||
return
|
||||
}
|
||||
clientSrcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||
conn, err := net.DialUDP("udp", clientSrcAddr, dstAddr)
|
||||
if err != nil {
|
||||
log.Printf("connect to udp %s fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout*3)))
|
||||
_, err = conn.Write(p.Data())
|
||||
log.Printf("udp send:%v", len(p.Data()))
|
||||
if err != nil {
|
||||
log.Printf("send udp packet to %s fail,ERR:%s", dstAddr.String(), err)
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
//log.Printf("send udp packet to %s success", dstAddr.String())
|
||||
buf := make([]byte, 10*1024)
|
||||
length, _, err := conn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
log.Printf("read udp response from %s fail ,ERR:%s", dstAddr.String(), err)
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
respBody := buf[0:length]
|
||||
//封装来自真实服务器的数据,返回给访问者
|
||||
respPacket := p.NewReply(respBody)
|
||||
//log.Printf("revecived udp packet from %s", dstAddr.String())
|
||||
if *s.cfg.LocalType == "tls" {
|
||||
d, err := goaes.Encrypt(s.UDPKey(), respPacket)
|
||||
if err != nil {
|
||||
log.Printf("encrypt udp data fail from %s", dstAddr.String())
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
s.udpSC.UDPListener.WriteToUDP(d, srcAddr)
|
||||
} else {
|
||||
s.udpSC.UDPListener.WriteToUDP(respPacket, srcAddr)
|
||||
}
|
||||
log.Printf("udp reply:%v", len(respPacket))
|
||||
}
|
||||
|
||||
}
|
||||
func (s *Socks) socksConnCallback(inConn net.Conn) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Printf("socks conn handler crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
inConn.Close()
|
||||
}
|
||||
}()
|
||||
//协商开始
|
||||
|
||||
//method select request
|
||||
inConn.SetReadDeadline(time.Now().Add(time.Second * 3))
|
||||
methodReq, err := socks.NewMethodsRequest(inConn)
|
||||
inConn.SetReadDeadline(time.Time{})
|
||||
if err != nil {
|
||||
methodReq.Reply(socks.Method_NONE_ACCEPTABLE)
|
||||
utils.CloseConn(&inConn)
|
||||
log.Printf("new methods request fail,ERR: %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
if !s.IsBasicAuth() {
|
||||
if !methodReq.Select(socks.Method_NO_AUTH) {
|
||||
methodReq.Reply(socks.Method_NONE_ACCEPTABLE)
|
||||
utils.CloseConn(&inConn)
|
||||
log.Printf("none method found : Method_NO_AUTH")
|
||||
return
|
||||
}
|
||||
//method select reply
|
||||
err = methodReq.Reply(socks.Method_NO_AUTH)
|
||||
if err != nil {
|
||||
log.Printf("reply answer data fail,ERR: %s", err)
|
||||
utils.CloseConn(&inConn)
|
||||
return
|
||||
}
|
||||
// log.Printf("% x", methodReq.Bytes())
|
||||
} else {
|
||||
//auth
|
||||
if !methodReq.Select(socks.Method_USER_PASS) {
|
||||
methodReq.Reply(socks.Method_NONE_ACCEPTABLE)
|
||||
utils.CloseConn(&inConn)
|
||||
log.Printf("none method found : Method_USER_PASS")
|
||||
return
|
||||
}
|
||||
//method reply need auth
|
||||
err = methodReq.Reply(socks.Method_USER_PASS)
|
||||
if err != nil {
|
||||
log.Printf("reply answer data fail,ERR: %s", err)
|
||||
utils.CloseConn(&inConn)
|
||||
return
|
||||
}
|
||||
//read auth
|
||||
buf := make([]byte, 500)
|
||||
inConn.SetReadDeadline(time.Now().Add(time.Second * 3))
|
||||
n, err := inConn.Read(buf)
|
||||
inConn.SetReadDeadline(time.Time{})
|
||||
if err != nil {
|
||||
utils.CloseConn(&inConn)
|
||||
return
|
||||
}
|
||||
r := buf[:n]
|
||||
user := string(r[2 : r[1]+2])
|
||||
pass := string(r[2+r[1]+1:])
|
||||
//log.Printf("user:%s,pass:%s", user, pass)
|
||||
//auth
|
||||
_addr := strings.Split(inConn.RemoteAddr().String(), ":")
|
||||
if s.basicAuth.CheckUserPass(user, pass, _addr[0], "") {
|
||||
inConn.Write([]byte{0x01, 0x00})
|
||||
} else {
|
||||
inConn.Write([]byte{0x01, 0x01})
|
||||
utils.CloseConn(&inConn)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
//request detail
|
||||
request, err := socks.NewRequest(inConn)
|
||||
if err != nil {
|
||||
log.Printf("read request data fail,ERR: %s", err)
|
||||
utils.CloseConn(&inConn)
|
||||
return
|
||||
}
|
||||
//协商结束
|
||||
|
||||
switch request.CMD() {
|
||||
case socks.CMD_BIND:
|
||||
//bind 不支持
|
||||
request.TCPReply(socks.REP_UNKNOWN)
|
||||
utils.CloseConn(&inConn)
|
||||
return
|
||||
case socks.CMD_CONNECT:
|
||||
//tcp
|
||||
s.proxyTCP(&inConn, methodReq, request)
|
||||
case socks.CMD_ASSOCIATE:
|
||||
//udp
|
||||
s.proxyUDP(&inConn, methodReq, request)
|
||||
}
|
||||
|
||||
}
|
||||
func (s *Socks) proxyUDP(inConn *net.Conn, methodReq socks.MethodsRequest, request socks.Request) {
|
||||
if *s.cfg.ParentType == "ssh" {
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
host, _, _ := net.SplitHostPort((*inConn).LocalAddr().String())
|
||||
_, port, _ := net.SplitHostPort(s.udpSC.UDPListener.LocalAddr().String())
|
||||
log.Printf("proxy udp on %s", net.JoinHostPort(host, port))
|
||||
request.UDPReply(socks.REP_SUCCESS, net.JoinHostPort(host, port))
|
||||
}
|
||||
func (s *Socks) proxyTCP(inConn *net.Conn, methodReq socks.MethodsRequest, request socks.Request) {
|
||||
var outConn net.Conn
|
||||
var err interface{}
|
||||
useProxy := true
|
||||
tryCount := 0
|
||||
maxTryCount := 5
|
||||
//防止死循环
|
||||
if s.IsDeadLoop((*inConn).LocalAddr().String(), request.Host()) {
|
||||
utils.CloseConn(inConn)
|
||||
log.Printf("dead loop detected , %s", request.Host())
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
for {
|
||||
if *s.cfg.Always {
|
||||
outConn, err = s.getOutConn(methodReq.Bytes(), request.Bytes(), request.Addr())
|
||||
} else {
|
||||
if *s.cfg.Parent != "" {
|
||||
host, _, _ := net.SplitHostPort(request.Addr())
|
||||
useProxy := false
|
||||
if utils.IsIternalIP(host) {
|
||||
useProxy = false
|
||||
} else {
|
||||
s.checker.Add(request.Addr())
|
||||
useProxy, _, _ = s.checker.IsBlocked(request.Addr())
|
||||
}
|
||||
if useProxy {
|
||||
outConn, err = s.getOutConn(methodReq.Bytes(), request.Bytes(), request.Addr())
|
||||
} else {
|
||||
outConn, err = utils.ConnectHost(request.Addr(), *s.cfg.Timeout)
|
||||
}
|
||||
} else {
|
||||
outConn, err = utils.ConnectHost(request.Addr(), *s.cfg.Timeout)
|
||||
useProxy = false
|
||||
}
|
||||
}
|
||||
tryCount++
|
||||
if err == nil || tryCount > maxTryCount || *s.cfg.Parent == "" {
|
||||
break
|
||||
} else {
|
||||
log.Printf("get out conn fail,%s,retrying...", err)
|
||||
time.Sleep(time.Second * 2)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("get out conn fail,%s", err)
|
||||
request.TCPReply(socks.REP_NETWOR_UNREACHABLE)
|
||||
return
|
||||
}
|
||||
log.Printf("use proxy %v : %s", useProxy, request.Addr())
|
||||
|
||||
request.TCPReply(socks.REP_SUCCESS)
|
||||
inAddr := (*inConn).RemoteAddr().String()
|
||||
//inLocalAddr := (*inConn).LocalAddr().String()
|
||||
|
||||
log.Printf("conn %s - %s connected", inAddr, request.Addr())
|
||||
utils.IoBind(*inConn, outConn, func(err interface{}) {
|
||||
log.Printf("conn %s - %s released", inAddr, request.Addr())
|
||||
})
|
||||
}
|
||||
func (s *Socks) getOutConn(methodBytes, reqBytes []byte, host string) (outConn net.Conn, err interface{}) {
|
||||
switch *s.cfg.ParentType {
|
||||
case "kcp":
|
||||
fallthrough
|
||||
case "tls":
|
||||
fallthrough
|
||||
case "tcp":
|
||||
if *s.cfg.ParentType == "tls" {
|
||||
var _outConn tls.Conn
|
||||
_outConn, err = utils.TlsConnectHost(*s.cfg.Parent, *s.cfg.Timeout, s.cfg.CertBytes, s.cfg.KeyBytes)
|
||||
outConn = net.Conn(&_outConn)
|
||||
} else if *s.cfg.ParentType == "kcp" {
|
||||
outConn, err = utils.ConnectKCPHost(*s.cfg.Parent, *s.cfg.KCPMethod, *s.cfg.KCPKey)
|
||||
} else {
|
||||
outConn, err = utils.ConnectHost(*s.cfg.Parent, *s.cfg.Timeout)
|
||||
}
|
||||
if err != nil {
|
||||
err = fmt.Errorf("connect fail,%s", err)
|
||||
return
|
||||
}
|
||||
var buf = make([]byte, 1024)
|
||||
//var n int
|
||||
_, err = outConn.Write(methodBytes)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("write method fail,%s", err)
|
||||
return
|
||||
}
|
||||
_, err = outConn.Read(buf)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("read method reply fail,%s", err)
|
||||
return
|
||||
}
|
||||
//resp := buf[:n]
|
||||
//log.Printf("resp:%v", resp)
|
||||
|
||||
_, err = outConn.Write(reqBytes)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("write req detail fail,%s", err)
|
||||
return
|
||||
}
|
||||
_, err = outConn.Read(buf)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("read req reply fail,%s", err)
|
||||
return
|
||||
}
|
||||
//result := buf[:n]
|
||||
//log.Printf("result:%v", result)
|
||||
|
||||
case "ssh":
|
||||
maxTryCount := 1
|
||||
tryCount := 0
|
||||
RETRY:
|
||||
if tryCount >= maxTryCount {
|
||||
return
|
||||
}
|
||||
wait := make(chan bool, 1)
|
||||
go func() {
|
||||
defer func() {
|
||||
if err == nil {
|
||||
err = recover()
|
||||
}
|
||||
wait <- true
|
||||
}()
|
||||
outConn, err = s.sshClient.Dial("tcp", host)
|
||||
}()
|
||||
select {
|
||||
case <-wait:
|
||||
case <-time.After(time.Millisecond * time.Duration(*s.cfg.Timeout) * 2):
|
||||
err = fmt.Errorf("ssh dial %s timeout", host)
|
||||
s.sshClient.Close()
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("connect ssh fail, ERR: %s, retrying...", err)
|
||||
e := s.ConnectSSH()
|
||||
if e == nil {
|
||||
tryCount++
|
||||
time.Sleep(time.Second * 3)
|
||||
goto RETRY
|
||||
} else {
|
||||
err = e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
func (s *Socks) ConnectSSH() (err error) {
|
||||
select {
|
||||
case s.lockChn <- true:
|
||||
default:
|
||||
err = fmt.Errorf("can not connect at same time")
|
||||
return
|
||||
}
|
||||
config := ssh.ClientConfig{
|
||||
Timeout: time.Duration(*s.cfg.Timeout) * time.Millisecond,
|
||||
User: *s.cfg.SSHUser,
|
||||
Auth: []ssh.AuthMethod{s.cfg.SSHAuthMethod},
|
||||
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
if s.sshClient != nil {
|
||||
s.sshClient.Close()
|
||||
}
|
||||
s.sshClient, err = ssh.Dial("tcp", *s.cfg.Parent, &config)
|
||||
<-s.lockChn
|
||||
return
|
||||
}
|
||||
func (s *Socks) InitBasicAuth() (err error) {
|
||||
s.basicAuth = utils.NewBasicAuth()
|
||||
if *s.cfg.AuthURL != "" {
|
||||
s.basicAuth.SetAuthURL(*s.cfg.AuthURL, *s.cfg.AuthURLOkCode, *s.cfg.AuthURLTimeout, *s.cfg.AuthURLRetry)
|
||||
log.Printf("auth from %s", *s.cfg.AuthURL)
|
||||
}
|
||||
if *s.cfg.AuthFile != "" {
|
||||
var n = 0
|
||||
n, err = s.basicAuth.AddFromFile(*s.cfg.AuthFile)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("auth-file ERR:%s", err)
|
||||
return
|
||||
}
|
||||
log.Printf("auth data added from file %d , total:%d", n, s.basicAuth.Total())
|
||||
}
|
||||
if len(*s.cfg.Auth) > 0 {
|
||||
n := s.basicAuth.Add(*s.cfg.Auth)
|
||||
log.Printf("auth data added %d, total:%d", n, s.basicAuth.Total())
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *Socks) IsBasicAuth() bool {
|
||||
return *s.cfg.AuthFile != "" || len(*s.cfg.Auth) > 0 || *s.cfg.AuthURL != ""
|
||||
}
|
||||
func (s *Socks) IsDeadLoop(inLocalAddr string, host string) bool {
|
||||
inIP, inPort, err := net.SplitHostPort(inLocalAddr)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
outDomain, outPort, err := net.SplitHostPort(host)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if inPort == outPort {
|
||||
var outIPs []net.IP
|
||||
outIPs, err = net.LookupIP(outDomain)
|
||||
if err == nil {
|
||||
for _, ip := range outIPs {
|
||||
if ip.String() == inIP {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
interfaceIPs, err := utils.GetAllInterfaceAddr()
|
||||
for _, ip := range *s.cfg.LocalIPS {
|
||||
interfaceIPs = append(interfaceIPs, net.ParseIP(ip).To4())
|
||||
}
|
||||
if err == nil {
|
||||
for _, localIP := range interfaceIPs {
|
||||
for _, outIP := range outIPs {
|
||||
if localIP.Equal(outIP) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
640
services/socks/socks.go
Normal file
@ -0,0 +1,640 @@
|
||||
package socks
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
logger "log"
|
||||
"net"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/snail007/goproxy/services"
|
||||
"github.com/snail007/goproxy/services/kcpcfg"
|
||||
"github.com/snail007/goproxy/utils"
|
||||
"github.com/snail007/goproxy/utils/conncrypt"
|
||||
"github.com/snail007/goproxy/utils/socks"
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type SocksArgs struct {
|
||||
Parent *string
|
||||
ParentType *string
|
||||
Local *string
|
||||
LocalType *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CaCertFile *string
|
||||
CaCertBytes []byte
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
SSHKeyFile *string
|
||||
SSHKeyFileSalt *string
|
||||
SSHPassword *string
|
||||
SSHUser *string
|
||||
SSHKeyBytes []byte
|
||||
SSHAuthMethod ssh.AuthMethod
|
||||
Timeout *int
|
||||
Always *bool
|
||||
Interval *int
|
||||
Blocked *string
|
||||
Direct *string
|
||||
AuthFile *string
|
||||
Auth *[]string
|
||||
AuthURL *string
|
||||
AuthURLOkCode *int
|
||||
AuthURLTimeout *int
|
||||
AuthURLRetry *int
|
||||
KCP kcpcfg.KCPConfigArgs
|
||||
LocalIPS *[]string
|
||||
DNSAddress *string
|
||||
DNSTTL *int
|
||||
LocalKey *string
|
||||
ParentKey *string
|
||||
LocalCompress *bool
|
||||
ParentCompress *bool
|
||||
}
|
||||
type Socks struct {
|
||||
cfg SocksArgs
|
||||
checker utils.Checker
|
||||
basicAuth utils.BasicAuth
|
||||
sshClient *ssh.Client
|
||||
lockChn chan bool
|
||||
udpSC utils.ServerChannel
|
||||
sc *utils.ServerChannel
|
||||
domainResolver utils.DomainResolver
|
||||
isStop bool
|
||||
userConns utils.ConcurrentMap
|
||||
log *logger.Logger
|
||||
udpRelatedPacketConns utils.ConcurrentMap
|
||||
udpLocalKey []byte
|
||||
udpParentKey []byte
|
||||
}
|
||||
|
||||
func NewSocks() services.Service {
|
||||
return &Socks{
|
||||
cfg: SocksArgs{},
|
||||
checker: utils.Checker{},
|
||||
basicAuth: utils.BasicAuth{},
|
||||
lockChn: make(chan bool, 1),
|
||||
isStop: false,
|
||||
userConns: utils.NewConcurrentMap(),
|
||||
udpRelatedPacketConns: utils.NewConcurrentMap(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Socks) CheckArgs() (err error) {
|
||||
|
||||
if *s.cfg.LocalType == "tls" || (*s.cfg.Parent != "" && *s.cfg.ParentType == "tls") {
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes, err = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if *s.cfg.CaCertFile != "" {
|
||||
s.cfg.CaCertBytes, err = ioutil.ReadFile(*s.cfg.CaCertFile)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("read ca file error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if *s.cfg.Parent != "" {
|
||||
if *s.cfg.ParentType == "" {
|
||||
err = fmt.Errorf("parent type unkown,use -T <tls|tcp|ssh|kcp>")
|
||||
return
|
||||
}
|
||||
if *s.cfg.ParentType == "ssh" {
|
||||
if *s.cfg.SSHUser == "" {
|
||||
err = fmt.Errorf("ssh user required")
|
||||
return
|
||||
}
|
||||
if *s.cfg.SSHKeyFile == "" && *s.cfg.SSHPassword == "" {
|
||||
err = fmt.Errorf("ssh password or key required")
|
||||
return
|
||||
}
|
||||
if *s.cfg.SSHPassword != "" {
|
||||
s.cfg.SSHAuthMethod = ssh.Password(*s.cfg.SSHPassword)
|
||||
} else {
|
||||
var SSHSigner ssh.Signer
|
||||
s.cfg.SSHKeyBytes, err = ioutil.ReadFile(*s.cfg.SSHKeyFile)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("read key file ERR: %s", err)
|
||||
return
|
||||
}
|
||||
if *s.cfg.SSHKeyFileSalt != "" {
|
||||
SSHSigner, err = ssh.ParsePrivateKeyWithPassphrase(s.cfg.SSHKeyBytes, []byte(*s.cfg.SSHKeyFileSalt))
|
||||
} else {
|
||||
SSHSigner, err = ssh.ParsePrivateKey(s.cfg.SSHKeyBytes)
|
||||
}
|
||||
if err != nil {
|
||||
err = fmt.Errorf("parse ssh private key fail,ERR: %s", err)
|
||||
return
|
||||
}
|
||||
s.cfg.SSHAuthMethod = ssh.PublicKeys(SSHSigner)
|
||||
}
|
||||
}
|
||||
}
|
||||
s.udpLocalKey = s.LocalUDPKey()
|
||||
s.udpParentKey = s.ParentUDPKey()
|
||||
//s.log.Printf("udpLocalKey : %v , udpParentKey : %v", s.udpLocalKey, s.udpParentKey)
|
||||
return
|
||||
}
|
||||
func (s *Socks) InitService() (err error) {
|
||||
s.InitBasicAuth()
|
||||
if *s.cfg.DNSAddress != "" {
|
||||
(*s).domainResolver = utils.NewDomainResolver(*s.cfg.DNSAddress, *s.cfg.DNSTTL, s.log)
|
||||
}
|
||||
if *s.cfg.Parent != "" {
|
||||
s.checker = utils.NewChecker(*s.cfg.Timeout, int64(*s.cfg.Interval), *s.cfg.Blocked, *s.cfg.Direct, s.log)
|
||||
}
|
||||
if *s.cfg.ParentType == "ssh" {
|
||||
e := s.ConnectSSH()
|
||||
if e != nil {
|
||||
err = fmt.Errorf("init service fail, ERR: %s", e)
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
//循环检查ssh网络连通性
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
conn, err := utils.ConnectHost(s.Resolve(*s.cfg.Parent), *s.cfg.Timeout*2)
|
||||
if err == nil {
|
||||
conn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = conn.Write([]byte{0})
|
||||
conn.SetDeadline(time.Time{})
|
||||
}
|
||||
if err != nil {
|
||||
if s.sshClient != nil {
|
||||
s.sshClient.Close()
|
||||
}
|
||||
s.log.Printf("ssh offline, retrying...")
|
||||
s.ConnectSSH()
|
||||
} else {
|
||||
conn.Close()
|
||||
}
|
||||
time.Sleep(time.Second * 3)
|
||||
}
|
||||
}()
|
||||
}
|
||||
if *s.cfg.ParentType == "ssh" {
|
||||
s.log.Printf("warn: socks udp not suppored for ssh")
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *Socks) StopService() {
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
s.log.Printf("stop socks service crashed,%s", e)
|
||||
} else {
|
||||
s.log.Printf("service socks stopped")
|
||||
}
|
||||
}()
|
||||
s.isStop = true
|
||||
if *s.cfg.Parent != "" {
|
||||
s.checker.Stop()
|
||||
}
|
||||
if s.sshClient != nil {
|
||||
s.sshClient.Close()
|
||||
}
|
||||
if s.udpSC.UDPListener != nil {
|
||||
s.udpSC.UDPListener.Close()
|
||||
}
|
||||
if s.sc != nil && (*s.sc).Listener != nil {
|
||||
(*(*s.sc).Listener).Close()
|
||||
}
|
||||
for _, c := range s.userConns.Items() {
|
||||
(*c.(*net.Conn)).Close()
|
||||
}
|
||||
for _, c := range s.udpRelatedPacketConns.Items() {
|
||||
(*c.(*net.UDPConn)).Close()
|
||||
}
|
||||
}
|
||||
func (s *Socks) Start(args interface{}, log *logger.Logger) (err error) {
|
||||
s.log = log
|
||||
//start()
|
||||
s.cfg = args.(SocksArgs)
|
||||
if err = s.CheckArgs(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = s.InitService(); err != nil {
|
||||
s.InitService()
|
||||
}
|
||||
if *s.cfg.Parent != "" {
|
||||
s.log.Printf("use %s parent %s", *s.cfg.ParentType, *s.cfg.Parent)
|
||||
}
|
||||
sc := utils.NewServerChannelHost(*s.cfg.Local, s.log)
|
||||
if *s.cfg.LocalType == "tcp" {
|
||||
err = sc.ListenTCP(s.socksConnCallback)
|
||||
} else if *s.cfg.LocalType == "tls" {
|
||||
err = sc.ListenTls(s.cfg.CertBytes, s.cfg.KeyBytes, nil, s.socksConnCallback)
|
||||
} else if *s.cfg.LocalType == "kcp" {
|
||||
err = sc.ListenKCP(s.cfg.KCP, s.socksConnCallback, s.log)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.sc = &sc
|
||||
s.log.Printf("%s socks proxy on %s", *s.cfg.LocalType, (*sc.Listener).Addr())
|
||||
return
|
||||
}
|
||||
func (s *Socks) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
|
||||
func (s *Socks) socksConnCallback(inConn net.Conn) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
s.log.Printf("socks conn handler crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
inConn.Close()
|
||||
}
|
||||
}()
|
||||
if *s.cfg.LocalCompress {
|
||||
inConn = utils.NewCompConn(inConn)
|
||||
}
|
||||
if *s.cfg.LocalKey != "" {
|
||||
inConn = conncrypt.New(inConn, &conncrypt.Config{
|
||||
Password: *s.cfg.LocalKey,
|
||||
})
|
||||
}
|
||||
//协商开始
|
||||
|
||||
//method select request
|
||||
inConn.SetReadDeadline(time.Now().Add(time.Second * 3))
|
||||
methodReq, err := socks.NewMethodsRequest(inConn)
|
||||
inConn.SetReadDeadline(time.Time{})
|
||||
if err != nil {
|
||||
methodReq.Reply(socks.Method_NONE_ACCEPTABLE)
|
||||
utils.CloseConn(&inConn)
|
||||
if err != io.EOF {
|
||||
s.log.Printf("new methods request fail,ERR: %s", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if !s.IsBasicAuth() {
|
||||
if !methodReq.Select(socks.Method_NO_AUTH) {
|
||||
methodReq.Reply(socks.Method_NONE_ACCEPTABLE)
|
||||
utils.CloseConn(&inConn)
|
||||
s.log.Printf("none method found : Method_NO_AUTH")
|
||||
return
|
||||
}
|
||||
//method select reply
|
||||
err = methodReq.Reply(socks.Method_NO_AUTH)
|
||||
if err != nil {
|
||||
s.log.Printf("reply answer data fail,ERR: %s", err)
|
||||
utils.CloseConn(&inConn)
|
||||
return
|
||||
}
|
||||
// s.log.Printf("% x", methodReq.Bytes())
|
||||
} else {
|
||||
//auth
|
||||
if !methodReq.Select(socks.Method_USER_PASS) {
|
||||
methodReq.Reply(socks.Method_NONE_ACCEPTABLE)
|
||||
utils.CloseConn(&inConn)
|
||||
s.log.Printf("none method found : Method_USER_PASS")
|
||||
return
|
||||
}
|
||||
//method reply need auth
|
||||
err = methodReq.Reply(socks.Method_USER_PASS)
|
||||
if err != nil {
|
||||
s.log.Printf("reply answer data fail,ERR: %s", err)
|
||||
utils.CloseConn(&inConn)
|
||||
return
|
||||
}
|
||||
//read auth
|
||||
buf := make([]byte, 500)
|
||||
inConn.SetReadDeadline(time.Now().Add(time.Second * 3))
|
||||
n, err := inConn.Read(buf)
|
||||
inConn.SetReadDeadline(time.Time{})
|
||||
if err != nil {
|
||||
utils.CloseConn(&inConn)
|
||||
return
|
||||
}
|
||||
r := buf[:n]
|
||||
user := string(r[2 : r[1]+2])
|
||||
pass := string(r[2+r[1]+1:])
|
||||
//s.log.Printf("user:%s,pass:%s", user, pass)
|
||||
//auth
|
||||
_addr := strings.Split(inConn.RemoteAddr().String(), ":")
|
||||
if s.basicAuth.CheckUserPass(user, pass, _addr[0], "") {
|
||||
inConn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
inConn.Write([]byte{0x01, 0x00})
|
||||
inConn.SetDeadline(time.Time{})
|
||||
|
||||
} else {
|
||||
inConn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
inConn.Write([]byte{0x01, 0x01})
|
||||
inConn.SetDeadline(time.Time{})
|
||||
|
||||
utils.CloseConn(&inConn)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
//request detail
|
||||
request, err := socks.NewRequest(inConn)
|
||||
if err != nil {
|
||||
s.log.Printf("read request data fail,ERR: %s", err)
|
||||
utils.CloseConn(&inConn)
|
||||
return
|
||||
}
|
||||
//协商结束
|
||||
|
||||
switch request.CMD() {
|
||||
case socks.CMD_BIND:
|
||||
//bind 不支持
|
||||
request.TCPReply(socks.REP_UNKNOWN)
|
||||
utils.CloseConn(&inConn)
|
||||
return
|
||||
case socks.CMD_CONNECT:
|
||||
//tcp
|
||||
s.proxyTCP(&inConn, methodReq, request)
|
||||
case socks.CMD_ASSOCIATE:
|
||||
//udp
|
||||
s.proxyUDP(&inConn, methodReq, request)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (s *Socks) proxyTCP(inConn *net.Conn, methodReq socks.MethodsRequest, request socks.Request) {
|
||||
var outConn net.Conn
|
||||
var err interface{}
|
||||
useProxy := true
|
||||
tryCount := 0
|
||||
maxTryCount := 5
|
||||
//防止死循环
|
||||
if s.IsDeadLoop((*inConn).LocalAddr().String(), request.Host()) {
|
||||
utils.CloseConn(inConn)
|
||||
s.log.Printf("dead loop detected , %s", request.Host())
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
if *s.cfg.Always {
|
||||
outConn, err = s.getOutConn(methodReq.Bytes(), request.Bytes(), request.Addr(), true)
|
||||
} else {
|
||||
if *s.cfg.Parent != "" {
|
||||
host, _, _ := net.SplitHostPort(request.Addr())
|
||||
useProxy := false
|
||||
if utils.IsIternalIP(host, *s.cfg.Always) {
|
||||
useProxy = false
|
||||
} else {
|
||||
var isInMap bool
|
||||
useProxy, isInMap, _, _ = s.checker.IsBlocked(request.Addr())
|
||||
if !isInMap {
|
||||
s.checker.Add(request.Addr(), s.Resolve(request.Addr()))
|
||||
}
|
||||
}
|
||||
if useProxy {
|
||||
outConn, err = s.getOutConn(methodReq.Bytes(), request.Bytes(), request.Addr(), true)
|
||||
} else {
|
||||
outConn, err = utils.ConnectHost(s.Resolve(request.Addr()), *s.cfg.Timeout)
|
||||
}
|
||||
} else {
|
||||
outConn, err = utils.ConnectHost(s.Resolve(request.Addr()), *s.cfg.Timeout)
|
||||
useProxy = false
|
||||
}
|
||||
}
|
||||
tryCount++
|
||||
if err == nil || tryCount > maxTryCount || *s.cfg.Parent == "" {
|
||||
break
|
||||
} else {
|
||||
s.log.Printf("get out conn fail,%s,retrying...", err)
|
||||
time.Sleep(time.Second * 2)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
s.log.Printf("get out conn fail,%s", err)
|
||||
request.TCPReply(socks.REP_NETWOR_UNREACHABLE)
|
||||
return
|
||||
}
|
||||
|
||||
s.log.Printf("use proxy %v : %s", useProxy, request.Addr())
|
||||
|
||||
request.TCPReply(socks.REP_SUCCESS)
|
||||
inAddr := (*inConn).RemoteAddr().String()
|
||||
//inLocalAddr := (*inConn).LocalAddr().String()
|
||||
|
||||
s.log.Printf("conn %s - %s connected", inAddr, request.Addr())
|
||||
utils.IoBind(*inConn, outConn, func(err interface{}) {
|
||||
s.log.Printf("conn %s - %s released", inAddr, request.Addr())
|
||||
s.userConns.Remove(inAddr)
|
||||
}, s.log)
|
||||
if c, ok := s.userConns.Get(inAddr); ok {
|
||||
(*c.(*net.Conn)).Close()
|
||||
s.userConns.Remove(inAddr)
|
||||
}
|
||||
s.userConns.Set(inAddr, inConn)
|
||||
}
|
||||
func (s *Socks) getOutConn(methodBytes, reqBytes []byte, host string, handshake bool) (outConn net.Conn, err interface{}) {
|
||||
switch *s.cfg.ParentType {
|
||||
case "kcp":
|
||||
fallthrough
|
||||
case "tls":
|
||||
fallthrough
|
||||
case "tcp":
|
||||
if *s.cfg.ParentType == "tls" {
|
||||
var _outConn tls.Conn
|
||||
_outConn, err = utils.TlsConnectHost(s.Resolve(*s.cfg.Parent), *s.cfg.Timeout, s.cfg.CertBytes, s.cfg.KeyBytes, nil)
|
||||
outConn = net.Conn(&_outConn)
|
||||
} else if *s.cfg.ParentType == "kcp" {
|
||||
outConn, err = utils.ConnectKCPHost(s.Resolve(*s.cfg.Parent), s.cfg.KCP)
|
||||
} else {
|
||||
outConn, err = utils.ConnectHost(s.Resolve(*s.cfg.Parent), *s.cfg.Timeout)
|
||||
}
|
||||
if err != nil {
|
||||
err = fmt.Errorf("connect fail,%s", err)
|
||||
return
|
||||
}
|
||||
if *s.cfg.ParentCompress {
|
||||
outConn = utils.NewCompConn(outConn)
|
||||
}
|
||||
if *s.cfg.ParentKey != "" {
|
||||
outConn = conncrypt.New(outConn, &conncrypt.Config{
|
||||
Password: *s.cfg.ParentKey,
|
||||
})
|
||||
}
|
||||
if !handshake {
|
||||
return
|
||||
}
|
||||
var buf = make([]byte, 1024)
|
||||
//var n int
|
||||
outConn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = outConn.Write(methodBytes)
|
||||
outConn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
err = fmt.Errorf("write method fail,%s", err)
|
||||
return
|
||||
}
|
||||
outConn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = outConn.Read(buf)
|
||||
outConn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
err = fmt.Errorf("read method reply fail,%s", err)
|
||||
return
|
||||
}
|
||||
//resp := buf[:n]
|
||||
//s.log.Printf("resp:%v", resp)
|
||||
outConn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = outConn.Write(reqBytes)
|
||||
outConn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
err = fmt.Errorf("write req detail fail,%s", err)
|
||||
return
|
||||
}
|
||||
outConn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = outConn.Read(buf)
|
||||
outConn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
err = fmt.Errorf("read req reply fail,%s", err)
|
||||
return
|
||||
}
|
||||
//result := buf[:n]
|
||||
//s.log.Printf("result:%v", result)
|
||||
|
||||
case "ssh":
|
||||
maxTryCount := 1
|
||||
tryCount := 0
|
||||
RETRY:
|
||||
if tryCount >= maxTryCount || s.isStop {
|
||||
return
|
||||
}
|
||||
wait := make(chan bool, 1)
|
||||
go func() {
|
||||
defer func() {
|
||||
if err == nil {
|
||||
err = recover()
|
||||
}
|
||||
wait <- true
|
||||
}()
|
||||
outConn, err = s.sshClient.Dial("tcp", host)
|
||||
}()
|
||||
select {
|
||||
case <-wait:
|
||||
case <-time.After(time.Millisecond * time.Duration(*s.cfg.Timeout) * 2):
|
||||
err = fmt.Errorf("ssh dial %s timeout", host)
|
||||
s.sshClient.Close()
|
||||
}
|
||||
if err != nil {
|
||||
s.log.Printf("connect ssh fail, ERR: %s, retrying...", err)
|
||||
e := s.ConnectSSH()
|
||||
if e == nil {
|
||||
tryCount++
|
||||
time.Sleep(time.Second * 3)
|
||||
goto RETRY
|
||||
} else {
|
||||
err = e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
func (s *Socks) ConnectSSH() (err error) {
|
||||
select {
|
||||
case s.lockChn <- true:
|
||||
default:
|
||||
err = fmt.Errorf("can not connect at same time")
|
||||
return
|
||||
}
|
||||
config := ssh.ClientConfig{
|
||||
Timeout: time.Duration(*s.cfg.Timeout) * time.Millisecond,
|
||||
User: *s.cfg.SSHUser,
|
||||
Auth: []ssh.AuthMethod{s.cfg.SSHAuthMethod},
|
||||
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
if s.sshClient != nil {
|
||||
s.sshClient.Close()
|
||||
}
|
||||
s.sshClient, err = ssh.Dial("tcp", s.Resolve(*s.cfg.Parent), &config)
|
||||
<-s.lockChn
|
||||
return
|
||||
}
|
||||
func (s *Socks) InitBasicAuth() (err error) {
|
||||
if *s.cfg.DNSAddress != "" {
|
||||
s.basicAuth = utils.NewBasicAuth(&(*s).domainResolver, s.log)
|
||||
} else {
|
||||
s.basicAuth = utils.NewBasicAuth(nil, s.log)
|
||||
}
|
||||
if *s.cfg.AuthURL != "" {
|
||||
s.basicAuth.SetAuthURL(*s.cfg.AuthURL, *s.cfg.AuthURLOkCode, *s.cfg.AuthURLTimeout, *s.cfg.AuthURLRetry)
|
||||
s.log.Printf("auth from %s", *s.cfg.AuthURL)
|
||||
}
|
||||
if *s.cfg.AuthFile != "" {
|
||||
var n = 0
|
||||
n, err = s.basicAuth.AddFromFile(*s.cfg.AuthFile)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("auth-file ERR:%s", err)
|
||||
return
|
||||
}
|
||||
s.log.Printf("auth data added from file %d , total:%d", n, s.basicAuth.Total())
|
||||
}
|
||||
if len(*s.cfg.Auth) > 0 {
|
||||
n := s.basicAuth.Add(*s.cfg.Auth)
|
||||
s.log.Printf("auth data added %d, total:%d", n, s.basicAuth.Total())
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *Socks) IsBasicAuth() bool {
|
||||
return *s.cfg.AuthFile != "" || len(*s.cfg.Auth) > 0 || *s.cfg.AuthURL != ""
|
||||
}
|
||||
func (s *Socks) IsDeadLoop(inLocalAddr string, host string) bool {
|
||||
inIP, inPort, err := net.SplitHostPort(inLocalAddr)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
outDomain, outPort, err := net.SplitHostPort(host)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if inPort == outPort {
|
||||
var outIPs []net.IP
|
||||
if *s.cfg.DNSAddress != "" {
|
||||
outIPs = []net.IP{net.ParseIP(s.Resolve(outDomain))}
|
||||
} else {
|
||||
outIPs, err = utils.MyLookupIP(outDomain)
|
||||
}
|
||||
if err == nil {
|
||||
for _, ip := range outIPs {
|
||||
if ip.String() == inIP {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
interfaceIPs, err := utils.GetAllInterfaceAddr()
|
||||
for _, ip := range *s.cfg.LocalIPS {
|
||||
interfaceIPs = append(interfaceIPs, net.ParseIP(ip).To4())
|
||||
}
|
||||
if err == nil {
|
||||
for _, localIP := range interfaceIPs {
|
||||
for _, outIP := range outIPs {
|
||||
if localIP.Equal(outIP) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (s *Socks) Resolve(address string) string {
|
||||
if *s.cfg.DNSAddress == "" {
|
||||
return address
|
||||
}
|
||||
ip, err := s.domainResolver.Resolve(address)
|
||||
if err != nil {
|
||||
s.log.Printf("dns error %s , ERR:%s", address, err)
|
||||
return address
|
||||
}
|
||||
return ip
|
||||
}
|
||||
321
services/socks/udp.go
Normal file
@ -0,0 +1,321 @@
|
||||
package socks
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"net"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/snail007/goproxy/utils"
|
||||
goaes "github.com/snail007/goproxy/utils/aes"
|
||||
"github.com/snail007/goproxy/utils/socks"
|
||||
)
|
||||
|
||||
func (s *Socks) ParentUDPKey() (key []byte) {
|
||||
switch *s.cfg.ParentType {
|
||||
case "tcp":
|
||||
if *s.cfg.ParentKey != "" {
|
||||
v := fmt.Sprintf("%x", md5.Sum([]byte(*s.cfg.ParentKey)))
|
||||
return []byte(v)[:24]
|
||||
}
|
||||
case "tls":
|
||||
return s.cfg.KeyBytes[:24]
|
||||
case "kcp":
|
||||
v := fmt.Sprintf("%x", md5.Sum([]byte(*s.cfg.KCP.Key)))
|
||||
return []byte(v)[:24]
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *Socks) LocalUDPKey() (key []byte) {
|
||||
switch *s.cfg.LocalType {
|
||||
case "tcp":
|
||||
if *s.cfg.LocalKey != "" {
|
||||
v := fmt.Sprintf("%x", md5.Sum([]byte(*s.cfg.LocalKey)))
|
||||
return []byte(v)[:24]
|
||||
}
|
||||
case "tls":
|
||||
return s.cfg.KeyBytes[:24]
|
||||
case "kcp":
|
||||
v := fmt.Sprintf("%x", md5.Sum([]byte(*s.cfg.KCP.Key)))
|
||||
return []byte(v)[:24]
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *Socks) proxyUDP(inConn *net.Conn, methodReq socks.MethodsRequest, request socks.Request) {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
s.log.Printf("udp local->out io copy crashed:\n%s\n%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
if *s.cfg.ParentType == "ssh" {
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
srcIP, _, _ := net.SplitHostPort((*inConn).RemoteAddr().String())
|
||||
inconnRemoteAddr := (*inConn).RemoteAddr().String()
|
||||
localAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||
udpListener, err := net.ListenUDP("udp", localAddr)
|
||||
if err != nil {
|
||||
(*inConn).Close()
|
||||
udpListener.Close()
|
||||
s.log.Printf("udp bind fail , %s", err)
|
||||
return
|
||||
}
|
||||
host, _, _ := net.SplitHostPort((*inConn).LocalAddr().String())
|
||||
_, port, _ := net.SplitHostPort(udpListener.LocalAddr().String())
|
||||
if len(*s.cfg.LocalIPS) > 0 {
|
||||
host = (*s.cfg.LocalIPS)[0]
|
||||
}
|
||||
s.log.Printf("proxy udp on %s , for %s", net.JoinHostPort(host, port), inconnRemoteAddr)
|
||||
request.UDPReply(socks.REP_SUCCESS, net.JoinHostPort(host, port))
|
||||
s.userConns.Set(inconnRemoteAddr, inConn)
|
||||
var (
|
||||
outUDPConn *net.UDPConn
|
||||
outconn net.Conn
|
||||
outconnLocalAddr string
|
||||
isClosedErr = func(err error) bool {
|
||||
return err != nil && strings.Contains(err.Error(), "use of closed network connection")
|
||||
}
|
||||
destAddr *net.UDPAddr
|
||||
)
|
||||
var clean = func(msg, err string) {
|
||||
raddr := ""
|
||||
if outUDPConn != nil {
|
||||
raddr = outUDPConn.RemoteAddr().String()
|
||||
outUDPConn.Close()
|
||||
}
|
||||
if msg != "" {
|
||||
if raddr != "" {
|
||||
s.log.Printf("%s , %s , %s -> %s", msg, err, inconnRemoteAddr, raddr)
|
||||
} else {
|
||||
s.log.Printf("%s , %s , from : %s", msg, err, inconnRemoteAddr)
|
||||
}
|
||||
}
|
||||
(*inConn).Close()
|
||||
udpListener.Close()
|
||||
s.userConns.Remove(inconnRemoteAddr)
|
||||
if outconn != nil {
|
||||
outconn.Close()
|
||||
}
|
||||
if outconnLocalAddr != "" {
|
||||
s.userConns.Remove(outconnLocalAddr)
|
||||
}
|
||||
}
|
||||
defer clean("", "")
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
s.log.Printf("udp related client tcp conn read crashed:\n%s\n%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
buf := make([]byte, 1)
|
||||
(*inConn).SetReadDeadline(time.Time{})
|
||||
if _, err := (*inConn).Read(buf); err != nil {
|
||||
clean("udp related tcp conn disconnected with read", err.Error())
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
s.log.Printf("udp related client tcp conn write crashed:\n%s\n%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
for {
|
||||
(*inConn).SetWriteDeadline(time.Now().Add(time.Second * 5))
|
||||
if _, err := (*inConn).Write([]byte{0x00}); err != nil {
|
||||
clean("udp related tcp conn disconnected with write", err.Error())
|
||||
return
|
||||
}
|
||||
(*inConn).SetWriteDeadline(time.Time{})
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}()
|
||||
useProxy := true
|
||||
if *s.cfg.Parent != "" {
|
||||
dstHost, _, _ := net.SplitHostPort(request.Addr())
|
||||
if utils.IsIternalIP(dstHost, *s.cfg.Always) {
|
||||
useProxy = false
|
||||
} else {
|
||||
var isInMap bool
|
||||
useProxy, isInMap, _, _ = s.checker.IsBlocked(request.Addr())
|
||||
if !isInMap {
|
||||
s.checker.Add(request.Addr(), s.Resolve(request.Addr()))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
useProxy = false
|
||||
}
|
||||
if useProxy {
|
||||
//parent proxy
|
||||
outconn, err := s.getOutConn(nil, nil, "", false)
|
||||
if err != nil {
|
||||
clean("connnect fail", fmt.Sprintf("%s", err))
|
||||
return
|
||||
}
|
||||
client := socks.NewClientConn(&outconn, "udp", request.Addr(), time.Millisecond*time.Duration(*s.cfg.Timeout), nil, nil)
|
||||
if err = client.Handshake(); err != nil {
|
||||
clean("handshake fail", fmt.Sprintf("%s", err))
|
||||
return
|
||||
}
|
||||
//outconnRemoteAddr := outconn.RemoteAddr().String()
|
||||
outconnLocalAddr = outconn.LocalAddr().String()
|
||||
s.userConns.Set(outconnLocalAddr, &outconn)
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
s.log.Printf("udp related parent tcp conn read crashed:\n%s\n%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
buf := make([]byte, 1)
|
||||
outconn.SetReadDeadline(time.Time{})
|
||||
if _, err := outconn.Read(buf); err != nil {
|
||||
clean("udp parent tcp conn disconnected", fmt.Sprintf("%s", err))
|
||||
}
|
||||
}()
|
||||
//forward to parent udp
|
||||
//s.log.Printf("parent udp address %s", client.UDPAddr)
|
||||
destAddr, _ = net.ResolveUDPAddr("udp", client.UDPAddr)
|
||||
}
|
||||
s.log.Printf("use proxy %v : udp %s", useProxy, request.Addr())
|
||||
//relay
|
||||
for {
|
||||
buf := utils.LeakyBuffer.Get()
|
||||
defer utils.LeakyBuffer.Put(buf)
|
||||
n, srcAddr, err := udpListener.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
s.log.Printf("udp listener read fail, %s", err.Error())
|
||||
if isClosedErr(err) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
srcIP0, _, _ := net.SplitHostPort(srcAddr.String())
|
||||
//IP not match drop it
|
||||
if srcIP != srcIP0 {
|
||||
continue
|
||||
}
|
||||
p := socks.NewPacketUDP()
|
||||
//convert data to raw
|
||||
if len(s.udpLocalKey) > 0 {
|
||||
var v []byte
|
||||
v, err = goaes.Decrypt(s.udpLocalKey, buf[:n])
|
||||
if err == nil {
|
||||
err = p.Parse(v)
|
||||
}
|
||||
} else {
|
||||
err = p.Parse(buf[:n])
|
||||
}
|
||||
//err = p.Parse(buf[:n])
|
||||
if err != nil {
|
||||
s.log.Printf("udp listener parse packet fail, %s", err.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
port, _ := strconv.Atoi(p.Port())
|
||||
|
||||
if v, ok := s.udpRelatedPacketConns.Get(srcAddr.String()); !ok {
|
||||
if destAddr == nil {
|
||||
destAddr = &net.UDPAddr{IP: net.ParseIP(p.Host()), Port: port}
|
||||
}
|
||||
outUDPConn, err = net.DialUDP("udp", localAddr, destAddr)
|
||||
if err != nil {
|
||||
s.log.Printf("create out udp conn fail , %s , from : %s", err, srcAddr)
|
||||
continue
|
||||
}
|
||||
s.udpRelatedPacketConns.Set(srcAddr.String(), outUDPConn)
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
s.log.Printf("udp out->local io copy crashed:\n%s\n%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
defer s.udpRelatedPacketConns.Remove(srcAddr.String())
|
||||
//out->local io copy
|
||||
buf := utils.LeakyBuffer.Get()
|
||||
defer utils.LeakyBuffer.Put(buf)
|
||||
for {
|
||||
n, err := outUDPConn.Read(buf)
|
||||
if err != nil {
|
||||
s.log.Printf("read out udp data fail , %s , from : %s", err, srcAddr)
|
||||
if isClosedErr(err) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
//var dlen = n
|
||||
if useProxy {
|
||||
//forward to local
|
||||
var v []byte
|
||||
//convert parent data to raw
|
||||
if len(s.udpParentKey) > 0 {
|
||||
v, err = goaes.Decrypt(s.udpParentKey, buf[:n])
|
||||
if err != nil {
|
||||
s.log.Printf("udp outconn parse packet fail, %s", err.Error())
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
v = buf[:n]
|
||||
}
|
||||
//now v is raw, try convert v to local
|
||||
if len(s.udpLocalKey) > 0 {
|
||||
v, _ = goaes.Encrypt(s.udpLocalKey, v)
|
||||
}
|
||||
_, err = udpListener.WriteTo(v, srcAddr)
|
||||
// _, err = udpListener.WriteTo(buf[:n], srcAddr)
|
||||
} else {
|
||||
rp := socks.NewPacketUDP()
|
||||
rp.Build(destAddr.String(), buf[:n])
|
||||
v := rp.Bytes()
|
||||
//dlen = len(v)
|
||||
//rp.Bytes() v is raw, try convert to local
|
||||
if len(s.udpLocalKey) > 0 {
|
||||
v, _ = goaes.Encrypt(s.udpLocalKey, v)
|
||||
}
|
||||
_, err = udpListener.WriteTo(v, srcAddr)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
s.udpRelatedPacketConns.Remove(srcAddr.String())
|
||||
s.log.Printf("write out data to local fail , %s , from : %s", err, srcAddr)
|
||||
if isClosedErr(err) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
} else {
|
||||
//s.log.Printf("send udp data to local success , len %d, for : %s", dlen, srcAddr)
|
||||
}
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
outUDPConn = v.(*net.UDPConn)
|
||||
}
|
||||
//local->out io copy
|
||||
if useProxy {
|
||||
//forward to parent
|
||||
//p is raw, now convert it to parent
|
||||
var v []byte
|
||||
if len(s.udpParentKey) > 0 {
|
||||
v, _ = goaes.Encrypt(s.udpParentKey, p.Bytes())
|
||||
} else {
|
||||
v = p.Bytes()
|
||||
}
|
||||
_, err = outUDPConn.Write(v)
|
||||
// _, err = outUDPConn.Write(p.Bytes())
|
||||
} else {
|
||||
_, err = outUDPConn.Write(p.Data())
|
||||
}
|
||||
if err != nil {
|
||||
if isClosedErr(err) {
|
||||
return
|
||||
}
|
||||
s.log.Printf("send out udp data fail , %s , from : %s", err, srcAddr)
|
||||
continue
|
||||
} else {
|
||||
//s.log.Printf("send udp data to remote success , len %d, for : %s", len(p.Data()), srcAddr)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
306
services/sps/socksudp.go
Normal file
@ -0,0 +1,306 @@
|
||||
package sps
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"net"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/snail007/goproxy/utils"
|
||||
goaes "github.com/snail007/goproxy/utils/aes"
|
||||
"github.com/snail007/goproxy/utils/conncrypt"
|
||||
"github.com/snail007/goproxy/utils/socks"
|
||||
)
|
||||
|
||||
func (s *SPS) ParentUDPKey() (key []byte) {
|
||||
switch *s.cfg.ParentType {
|
||||
case "tcp":
|
||||
if *s.cfg.ParentKey != "" {
|
||||
v := fmt.Sprintf("%x", md5.Sum([]byte(*s.cfg.ParentKey)))
|
||||
return []byte(v)[:24]
|
||||
}
|
||||
case "tls":
|
||||
return s.cfg.KeyBytes[:24]
|
||||
case "kcp":
|
||||
v := fmt.Sprintf("%x", md5.Sum([]byte(*s.cfg.KCP.Key)))
|
||||
return []byte(v)[:24]
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *SPS) LocalUDPKey() (key []byte) {
|
||||
switch *s.cfg.LocalType {
|
||||
case "tcp":
|
||||
if *s.cfg.LocalKey != "" {
|
||||
v := fmt.Sprintf("%x", md5.Sum([]byte(*s.cfg.LocalKey)))
|
||||
return []byte(v)[:24]
|
||||
}
|
||||
case "tls":
|
||||
return s.cfg.KeyBytes[:24]
|
||||
case "kcp":
|
||||
v := fmt.Sprintf("%x", md5.Sum([]byte(*s.cfg.KCP.Key)))
|
||||
return []byte(v)[:24]
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *SPS) proxyUDP(inConn *net.Conn, serverConn *socks.ServerConn) {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
s.log.Printf("udp local->out io copy crashed:\n%s\n%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
if *s.cfg.ParentType == "ssh" {
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
srcIP, _, _ := net.SplitHostPort((*inConn).RemoteAddr().String())
|
||||
inconnRemoteAddr := (*inConn).RemoteAddr().String()
|
||||
localAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||
udpListener := serverConn.UDPConnListener
|
||||
s.log.Printf("proxy udp on %s , for %s", udpListener.LocalAddr(), inconnRemoteAddr)
|
||||
s.userConns.Set(inconnRemoteAddr, inConn)
|
||||
var (
|
||||
outUDPConn *net.UDPConn
|
||||
outconn net.Conn
|
||||
outconnLocalAddr string
|
||||
isClosedErr = func(err error) bool {
|
||||
return err != nil && strings.Contains(err.Error(), "use of closed network connection")
|
||||
}
|
||||
destAddr *net.UDPAddr
|
||||
)
|
||||
var clean = func(msg, err string) {
|
||||
raddr := ""
|
||||
if outUDPConn != nil {
|
||||
raddr = outUDPConn.RemoteAddr().String()
|
||||
outUDPConn.Close()
|
||||
}
|
||||
if msg != "" {
|
||||
if raddr != "" {
|
||||
s.log.Printf("%s , %s , %s -> %s", msg, err, inconnRemoteAddr, raddr)
|
||||
} else {
|
||||
s.log.Printf("%s , %s , from : %s", msg, err, inconnRemoteAddr)
|
||||
}
|
||||
}
|
||||
(*inConn).Close()
|
||||
udpListener.Close()
|
||||
s.userConns.Remove(inconnRemoteAddr)
|
||||
if outconn != nil {
|
||||
outconn.Close()
|
||||
}
|
||||
if outconnLocalAddr != "" {
|
||||
s.userConns.Remove(outconnLocalAddr)
|
||||
}
|
||||
}
|
||||
defer clean("", "")
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
s.log.Printf("udp related client tcp conn read crashed:\n%s\n%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
buf := make([]byte, 1)
|
||||
(*inConn).SetReadDeadline(time.Time{})
|
||||
if _, err := (*inConn).Read(buf); err != nil {
|
||||
clean("udp related tcp conn disconnected with read", err.Error())
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
s.log.Printf("udp related client tcp conn write crashed:\n%s\n%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
for {
|
||||
(*inConn).SetWriteDeadline(time.Now().Add(time.Second * 5))
|
||||
if _, err := (*inConn).Write([]byte{0x00}); err != nil {
|
||||
clean("udp related tcp conn disconnected with write", err.Error())
|
||||
return
|
||||
}
|
||||
(*inConn).SetWriteDeadline(time.Time{})
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}()
|
||||
//parent proxy
|
||||
outconn, err := s.outPool.Get()
|
||||
//outconn, err := s.GetParentConn(nil, nil, "", false)
|
||||
if err != nil {
|
||||
clean("connnect fail", fmt.Sprintf("%s", err))
|
||||
return
|
||||
}
|
||||
if *s.cfg.ParentCompress {
|
||||
outconn = utils.NewCompConn(outconn)
|
||||
}
|
||||
if *s.cfg.ParentKey != "" {
|
||||
outconn = conncrypt.New(outconn, &conncrypt.Config{
|
||||
Password: *s.cfg.ParentKey,
|
||||
})
|
||||
}
|
||||
|
||||
s.log.Printf("connect %s for udp", serverConn.Target())
|
||||
//socks client
|
||||
var client *socks.ClientConn
|
||||
auth := serverConn.AuthData()
|
||||
if *s.cfg.ParentAuth != "" {
|
||||
a := strings.Split(*s.cfg.ParentAuth, ":")
|
||||
if len(a) != 2 {
|
||||
err = fmt.Errorf("parent auth data format error")
|
||||
return
|
||||
}
|
||||
client = socks.NewClientConn(&outconn, "udp", serverConn.Target(), time.Millisecond*time.Duration(*s.cfg.Timeout), &socks.Auth{User: a[0], Password: a[1]}, nil)
|
||||
} else {
|
||||
if !s.IsBasicAuth() && auth.Password != "" && auth.User != "" {
|
||||
client = socks.NewClientConn(&outconn, "udp", serverConn.Target(), time.Millisecond*time.Duration(*s.cfg.Timeout), &auth, nil)
|
||||
} else {
|
||||
client = socks.NewClientConn(&outconn, "udp", serverConn.Target(), time.Millisecond*time.Duration(*s.cfg.Timeout), nil, nil)
|
||||
}
|
||||
}
|
||||
|
||||
if err = client.Handshake(); err != nil {
|
||||
clean("handshake fail", fmt.Sprintf("%s", err))
|
||||
return
|
||||
}
|
||||
|
||||
//outconnRemoteAddr := outconn.RemoteAddr().String()
|
||||
outconnLocalAddr = outconn.LocalAddr().String()
|
||||
s.userConns.Set(outconnLocalAddr, &outconn)
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
s.log.Printf("udp related parent tcp conn read crashed:\n%s\n%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
buf := make([]byte, 1)
|
||||
outconn.SetReadDeadline(time.Time{})
|
||||
if _, err := outconn.Read(buf); err != nil {
|
||||
clean("udp parent tcp conn disconnected", fmt.Sprintf("%s", err))
|
||||
}
|
||||
}()
|
||||
//forward to parent udp
|
||||
//s.log.Printf("parent udp address %s", client.UDPAddr)
|
||||
destAddr, _ = net.ResolveUDPAddr("udp", client.UDPAddr)
|
||||
//relay
|
||||
buf := utils.LeakyBuffer.Get()
|
||||
defer utils.LeakyBuffer.Put(buf)
|
||||
for {
|
||||
n, srcAddr, err := udpListener.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
s.log.Printf("udp listener read fail, %s", err.Error())
|
||||
if isClosedErr(err) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
srcIP0, _, _ := net.SplitHostPort(srcAddr.String())
|
||||
//IP not match drop it
|
||||
if srcIP != srcIP0 {
|
||||
continue
|
||||
}
|
||||
p := socks.NewPacketUDP()
|
||||
//convert data to raw
|
||||
if len(s.udpLocalKey) > 0 {
|
||||
var v []byte
|
||||
v, err = goaes.Decrypt(s.udpLocalKey, buf[:n])
|
||||
if err == nil {
|
||||
err = p.Parse(v)
|
||||
}
|
||||
} else {
|
||||
err = p.Parse(buf[:n])
|
||||
}
|
||||
if err != nil {
|
||||
s.log.Printf("udp listener parse packet fail, %s", err.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
port, _ := strconv.Atoi(p.Port())
|
||||
|
||||
if v, ok := s.udpRelatedPacketConns.Get(srcAddr.String()); !ok {
|
||||
if destAddr == nil {
|
||||
destAddr = &net.UDPAddr{IP: net.ParseIP(p.Host()), Port: port}
|
||||
}
|
||||
outUDPConn, err = net.DialUDP("udp", localAddr, destAddr)
|
||||
if err != nil {
|
||||
s.log.Printf("create out udp conn fail , %s , from : %s", err, srcAddr)
|
||||
continue
|
||||
}
|
||||
s.udpRelatedPacketConns.Set(srcAddr.String(), outUDPConn)
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
s.log.Printf("udp out->local io copy crashed:\n%s\n%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
defer s.udpRelatedPacketConns.Remove(srcAddr.String())
|
||||
//out->local io copy
|
||||
buf := utils.LeakyBuffer.Get()
|
||||
defer utils.LeakyBuffer.Put(buf)
|
||||
for {
|
||||
outUDPConn.SetReadDeadline(time.Now().Add(time.Second * 5))
|
||||
n, err := outUDPConn.Read(buf)
|
||||
outUDPConn.SetReadDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("read out udp data fail , %s , from : %s", err, srcAddr)
|
||||
if isClosedErr(err) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
//var dlen = n
|
||||
//forward to local
|
||||
var v []byte
|
||||
//convert parent data to raw
|
||||
if len(s.udpParentKey) > 0 {
|
||||
v, err = goaes.Decrypt(s.udpParentKey, buf[:n])
|
||||
if err != nil {
|
||||
s.log.Printf("udp outconn parse packet fail, %s", err.Error())
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
v = buf[:n]
|
||||
}
|
||||
//now v is raw, try convert v to local
|
||||
if len(s.udpLocalKey) > 0 {
|
||||
v, _ = goaes.Encrypt(s.udpLocalKey, v)
|
||||
}
|
||||
_, err = udpListener.WriteTo(v, srcAddr)
|
||||
// _, err = udpListener.WriteTo(buf[:n], srcAddr)
|
||||
|
||||
if err != nil {
|
||||
s.udpRelatedPacketConns.Remove(srcAddr.String())
|
||||
s.log.Printf("write out data to local fail , %s , from : %s", err, srcAddr)
|
||||
if isClosedErr(err) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
} else {
|
||||
//s.log.Printf("send udp data to local success , len %d, for : %s", dlen, srcAddr)
|
||||
}
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
outUDPConn = v.(*net.UDPConn)
|
||||
}
|
||||
//local->out io copy
|
||||
//forward to parent
|
||||
//p is raw, now convert it to parent
|
||||
var v []byte
|
||||
if len(s.udpParentKey) > 0 {
|
||||
v, _ = goaes.Encrypt(s.udpParentKey, p.Bytes())
|
||||
} else {
|
||||
v = p.Bytes()
|
||||
}
|
||||
_, err = outUDPConn.Write(v)
|
||||
// _, err = outUDPConn.Write(p.Bytes())
|
||||
if err != nil {
|
||||
if isClosedErr(err) {
|
||||
return
|
||||
}
|
||||
s.log.Printf("send out udp data fail , %s , from : %s", err, srcAddr)
|
||||
continue
|
||||
} else {
|
||||
//s.log.Printf("send udp data to remote success , len %d, for : %s", len(p.Data()), srcAddr)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
517
services/sps/sps.go
Normal file
@ -0,0 +1,517 @@
|
||||
package sps
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
logger "log"
|
||||
"net"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/snail007/goproxy/services"
|
||||
"github.com/snail007/goproxy/services/kcpcfg"
|
||||
"github.com/snail007/goproxy/utils"
|
||||
"github.com/snail007/goproxy/utils/conncrypt"
|
||||
"github.com/snail007/goproxy/utils/sni"
|
||||
"github.com/snail007/goproxy/utils/socks"
|
||||
)
|
||||
|
||||
type SPSArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CaCertFile *string
|
||||
CaCertBytes []byte
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Local *string
|
||||
ParentType *string
|
||||
LocalType *string
|
||||
Timeout *int
|
||||
KCP kcpcfg.KCPConfigArgs
|
||||
ParentServiceType *string
|
||||
DNSAddress *string
|
||||
DNSTTL *int
|
||||
AuthFile *string
|
||||
Auth *[]string
|
||||
AuthURL *string
|
||||
AuthURLOkCode *int
|
||||
AuthURLTimeout *int
|
||||
AuthURLRetry *int
|
||||
LocalIPS *[]string
|
||||
ParentAuth *string
|
||||
LocalKey *string
|
||||
ParentKey *string
|
||||
LocalCompress *bool
|
||||
ParentCompress *bool
|
||||
DisableHTTP *bool
|
||||
DisableSocks5 *bool
|
||||
}
|
||||
type SPS struct {
|
||||
outPool utils.OutConn
|
||||
cfg SPSArgs
|
||||
domainResolver utils.DomainResolver
|
||||
basicAuth utils.BasicAuth
|
||||
serverChannels []*utils.ServerChannel
|
||||
userConns utils.ConcurrentMap
|
||||
log *logger.Logger
|
||||
udpRelatedPacketConns utils.ConcurrentMap
|
||||
udpLocalKey []byte
|
||||
udpParentKey []byte
|
||||
}
|
||||
|
||||
func NewSPS() services.Service {
|
||||
return &SPS{
|
||||
outPool: utils.OutConn{},
|
||||
cfg: SPSArgs{},
|
||||
basicAuth: utils.BasicAuth{},
|
||||
serverChannels: []*utils.ServerChannel{},
|
||||
userConns: utils.NewConcurrentMap(),
|
||||
udpRelatedPacketConns: utils.NewConcurrentMap(),
|
||||
}
|
||||
}
|
||||
func (s *SPS) CheckArgs() (err error) {
|
||||
if *s.cfg.Parent == "" {
|
||||
err = fmt.Errorf("parent required for %s %s", *s.cfg.LocalType, *s.cfg.Local)
|
||||
return
|
||||
}
|
||||
if *s.cfg.ParentType == "" {
|
||||
err = fmt.Errorf("parent type unkown,use -T <tls|tcp|kcp>")
|
||||
return
|
||||
}
|
||||
if *s.cfg.ParentType == "tls" || *s.cfg.LocalType == "tls" {
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes, err = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if *s.cfg.CaCertFile != "" {
|
||||
s.cfg.CaCertBytes, err = ioutil.ReadFile(*s.cfg.CaCertFile)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("read ca file error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
s.udpLocalKey = s.LocalUDPKey()
|
||||
s.udpParentKey = s.ParentUDPKey()
|
||||
return
|
||||
}
|
||||
func (s *SPS) InitService() (err error) {
|
||||
if *s.cfg.DNSAddress != "" {
|
||||
(*s).domainResolver = utils.NewDomainResolver(*s.cfg.DNSAddress, *s.cfg.DNSTTL, s.log)
|
||||
}
|
||||
s.InitOutConnPool()
|
||||
err = s.InitBasicAuth()
|
||||
return
|
||||
}
|
||||
func (s *SPS) InitOutConnPool() {
|
||||
if *s.cfg.ParentType == "tls" || *s.cfg.ParentType == "tcp" || *s.cfg.ParentType == "kcp" {
|
||||
//dur int, isTLS bool, certBytes, keyBytes []byte,
|
||||
//parent string, timeout int, InitialCap int, MaxCap int
|
||||
s.outPool = utils.NewOutConn(
|
||||
0,
|
||||
*s.cfg.ParentType,
|
||||
s.cfg.KCP,
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes, s.cfg.CaCertBytes,
|
||||
*s.cfg.Parent,
|
||||
*s.cfg.Timeout,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SPS) StopService() {
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
s.log.Printf("stop sps service crashed,%s", e)
|
||||
} else {
|
||||
s.log.Printf("service sps stopped")
|
||||
}
|
||||
}()
|
||||
for _, sc := range s.serverChannels {
|
||||
if sc.Listener != nil && *sc.Listener != nil {
|
||||
(*sc.Listener).Close()
|
||||
}
|
||||
if sc.UDPListener != nil {
|
||||
(*sc.UDPListener).Close()
|
||||
}
|
||||
}
|
||||
for _, c := range s.userConns.Items() {
|
||||
if _, ok := c.(*net.Conn); ok {
|
||||
(*c.(*net.Conn)).Close()
|
||||
}
|
||||
if _, ok := c.(**net.Conn); ok {
|
||||
(*(*c.(**net.Conn))).Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *SPS) Start(args interface{}, log *logger.Logger) (err error) {
|
||||
s.log = log
|
||||
s.cfg = args.(SPSArgs)
|
||||
if err = s.CheckArgs(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = s.InitService(); err != nil {
|
||||
return
|
||||
}
|
||||
s.log.Printf("use %s %s parent %s", *s.cfg.ParentType, *s.cfg.ParentServiceType, *s.cfg.Parent)
|
||||
for _, addr := range strings.Split(*s.cfg.Local, ",") {
|
||||
if addr != "" {
|
||||
host, port, _ := net.SplitHostPort(addr)
|
||||
p, _ := strconv.Atoi(port)
|
||||
sc := utils.NewServerChannel(host, p, s.log)
|
||||
if *s.cfg.LocalType == "tcp" {
|
||||
err = sc.ListenTCP(s.callback)
|
||||
} else if *s.cfg.LocalType == "tls" {
|
||||
err = sc.ListenTls(s.cfg.CertBytes, s.cfg.KeyBytes, s.cfg.CaCertBytes, s.callback)
|
||||
} else if *s.cfg.LocalType == "kcp" {
|
||||
err = sc.ListenKCP(s.cfg.KCP, s.callback, s.log)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.log.Printf("%s http(s)+socks proxy on %s", *s.cfg.LocalType, (*sc.Listener).Addr())
|
||||
s.serverChannels = append(s.serverChannels, &sc)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *SPS) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *SPS) callback(inConn net.Conn) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
s.log.Printf("%s conn handler crashed with err : %s \nstack: %s", *s.cfg.LocalType, err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
if *s.cfg.LocalCompress {
|
||||
inConn = utils.NewCompConn(inConn)
|
||||
}
|
||||
if *s.cfg.LocalKey != "" {
|
||||
inConn = conncrypt.New(inConn, &conncrypt.Config{
|
||||
Password: *s.cfg.LocalKey,
|
||||
})
|
||||
}
|
||||
var err error
|
||||
switch *s.cfg.ParentType {
|
||||
case "kcp":
|
||||
fallthrough
|
||||
case "tcp":
|
||||
fallthrough
|
||||
case "tls":
|
||||
err = s.OutToTCP(&inConn)
|
||||
default:
|
||||
err = fmt.Errorf("unkown parent type %s", *s.cfg.ParentType)
|
||||
}
|
||||
if err != nil {
|
||||
s.log.Printf("connect to %s parent %s fail, ERR:%s from %s", *s.cfg.ParentType, *s.cfg.Parent, err, inConn.RemoteAddr())
|
||||
utils.CloseConn(&inConn)
|
||||
}
|
||||
}
|
||||
func (s *SPS) OutToTCP(inConn *net.Conn) (err error) {
|
||||
enableUDP := *s.cfg.ParentServiceType == "socks"
|
||||
udpIP, _, _ := net.SplitHostPort((*inConn).LocalAddr().String())
|
||||
if len(*s.cfg.LocalIPS) > 0 {
|
||||
udpIP = (*s.cfg.LocalIPS)[0]
|
||||
}
|
||||
bInConn := utils.NewBufferedConn(*inConn)
|
||||
//important
|
||||
//action read will regist read event to system,
|
||||
//when data arrived , system call process
|
||||
//so that we can get buffered bytes count
|
||||
//otherwise Buffered() always return 0
|
||||
bInConn.ReadByte()
|
||||
bInConn.UnreadByte()
|
||||
|
||||
n := 2048
|
||||
if n > bInConn.Buffered() {
|
||||
n = bInConn.Buffered()
|
||||
}
|
||||
h, err := bInConn.Peek(n)
|
||||
if err != nil {
|
||||
s.log.Printf("peek error %s ", err)
|
||||
(*inConn).Close()
|
||||
return
|
||||
}
|
||||
isSNI, _ := sni.ServerNameFromBytes(h)
|
||||
*inConn = bInConn
|
||||
address := ""
|
||||
var auth socks.Auth
|
||||
var forwardBytes []byte
|
||||
//fmt.Printf("%v", h)
|
||||
if utils.IsSocks5(h) {
|
||||
if *s.cfg.DisableSocks5 {
|
||||
(*inConn).Close()
|
||||
return
|
||||
}
|
||||
//socks5 server
|
||||
var serverConn *socks.ServerConn
|
||||
if s.IsBasicAuth() {
|
||||
serverConn = socks.NewServerConn(inConn, time.Millisecond*time.Duration(*s.cfg.Timeout), &s.basicAuth, enableUDP, udpIP, nil)
|
||||
} else {
|
||||
serverConn = socks.NewServerConn(inConn, time.Millisecond*time.Duration(*s.cfg.Timeout), nil, enableUDP, udpIP, nil)
|
||||
}
|
||||
if err = serverConn.Handshake(); err != nil {
|
||||
return
|
||||
}
|
||||
address = serverConn.Target()
|
||||
auth = serverConn.AuthData()
|
||||
if serverConn.IsUDP() {
|
||||
s.proxyUDP(inConn, serverConn)
|
||||
return
|
||||
}
|
||||
} else if utils.IsHTTP(h) || isSNI != "" {
|
||||
if *s.cfg.DisableHTTP {
|
||||
(*inConn).Close()
|
||||
return
|
||||
}
|
||||
//http
|
||||
var request utils.HTTPRequest
|
||||
(*inConn).SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
if s.IsBasicAuth() {
|
||||
request, err = utils.NewHTTPRequest(inConn, 1024, true, &s.basicAuth, s.log)
|
||||
} else {
|
||||
request, err = utils.NewHTTPRequest(inConn, 1024, false, nil, s.log)
|
||||
}
|
||||
(*inConn).SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("new http request fail,ERR: %s", err)
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
if len(h) >= 7 && strings.ToLower(string(h[:7])) == "connect" {
|
||||
//https
|
||||
request.HTTPSReply()
|
||||
//s.log.Printf("https reply: %s", request.Host)
|
||||
} else {
|
||||
//forwardBytes = bytes.TrimRight(request.HeadBuf,"\r\n")
|
||||
forwardBytes = request.HeadBuf
|
||||
}
|
||||
address = request.Host
|
||||
var userpass string
|
||||
if s.IsBasicAuth() {
|
||||
userpass, err = request.GetAuthDataStr()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
userpassA := strings.Split(userpass, ":")
|
||||
if len(userpassA) == 2 {
|
||||
auth = socks.Auth{User: userpassA[0], Password: userpassA[1]}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil || address == "" {
|
||||
s.log.Printf("unknown request from: %s,%s", (*inConn).RemoteAddr(), string(h))
|
||||
(*inConn).Close()
|
||||
utils.CloseConn(inConn)
|
||||
err = errors.New("unknown request")
|
||||
return
|
||||
}
|
||||
//connect to parent
|
||||
var outConn net.Conn
|
||||
outConn, err = s.outPool.Get()
|
||||
if err != nil {
|
||||
s.log.Printf("connect to %s , err:%s", *s.cfg.Parent, err)
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
if *s.cfg.ParentCompress {
|
||||
outConn = utils.NewCompConn(outConn)
|
||||
}
|
||||
if *s.cfg.ParentKey != "" {
|
||||
outConn = conncrypt.New(outConn, &conncrypt.Config{
|
||||
Password: *s.cfg.ParentKey,
|
||||
})
|
||||
}
|
||||
|
||||
if *s.cfg.ParentAuth != "" || s.IsBasicAuth() {
|
||||
forwardBytes = utils.RemoveProxyHeaders(forwardBytes)
|
||||
}
|
||||
|
||||
//ask parent for connect to target address
|
||||
if *s.cfg.ParentServiceType == "http" {
|
||||
//http parent
|
||||
isHTTPS := false
|
||||
|
||||
pb := new(bytes.Buffer)
|
||||
if len(forwardBytes) == 0 {
|
||||
isHTTPS = true
|
||||
pb.Write([]byte(fmt.Sprintf("CONNECT %s HTTP/1.1\r\n", address)))
|
||||
}
|
||||
pb.WriteString("Proxy-Connection: Keep-Alive\r\n")
|
||||
|
||||
u := ""
|
||||
if *s.cfg.ParentAuth != "" {
|
||||
a := strings.Split(*s.cfg.ParentAuth, ":")
|
||||
if len(a) != 2 {
|
||||
err = fmt.Errorf("parent auth data format error")
|
||||
return
|
||||
}
|
||||
u = fmt.Sprintf("%s:%s", a[0], a[1])
|
||||
} else {
|
||||
if !s.IsBasicAuth() && auth.Password != "" && auth.User != "" {
|
||||
u = fmt.Sprintf("%s:%s", auth.User, auth.Password)
|
||||
}
|
||||
}
|
||||
if u != "" {
|
||||
pb.Write([]byte(fmt.Sprintf("Proxy-Authorization: Basic %s\r\n", base64.StdEncoding.EncodeToString([]byte(u)))))
|
||||
}
|
||||
|
||||
if isHTTPS {
|
||||
pb.Write([]byte("\r\n"))
|
||||
} else {
|
||||
forwardBytes = utils.InsertProxyHeaders(forwardBytes, string(pb.Bytes()))
|
||||
pb.Reset()
|
||||
pb.Write(forwardBytes)
|
||||
forwardBytes = nil
|
||||
}
|
||||
|
||||
outConn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = outConn.Write(pb.Bytes())
|
||||
outConn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("write CONNECT to %s , err:%s", *s.cfg.Parent, err)
|
||||
utils.CloseConn(inConn)
|
||||
utils.CloseConn(&outConn)
|
||||
return
|
||||
}
|
||||
|
||||
if isHTTPS {
|
||||
reply := make([]byte, 1024)
|
||||
outConn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = outConn.Read(reply)
|
||||
outConn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("read reply from %s , err:%s", *s.cfg.Parent, err)
|
||||
utils.CloseConn(inConn)
|
||||
utils.CloseConn(&outConn)
|
||||
return
|
||||
}
|
||||
//s.log.Printf("reply: %s", string(reply[:n]))
|
||||
}
|
||||
} else if *s.cfg.ParentServiceType == "socks" {
|
||||
s.log.Printf("connect %s", address)
|
||||
//socks client
|
||||
var clientConn *socks.ClientConn
|
||||
if *s.cfg.ParentAuth != "" {
|
||||
a := strings.Split(*s.cfg.ParentAuth, ":")
|
||||
if len(a) != 2 {
|
||||
err = fmt.Errorf("parent auth data format error")
|
||||
return
|
||||
}
|
||||
clientConn = socks.NewClientConn(&outConn, "tcp", address, time.Millisecond*time.Duration(*s.cfg.Timeout), &socks.Auth{User: a[0], Password: a[1]}, nil)
|
||||
} else {
|
||||
if !s.IsBasicAuth() && auth.Password != "" && auth.User != "" {
|
||||
clientConn = socks.NewClientConn(&outConn, "tcp", address, time.Millisecond*time.Duration(*s.cfg.Timeout), &auth, nil)
|
||||
} else {
|
||||
clientConn = socks.NewClientConn(&outConn, "tcp", address, time.Millisecond*time.Duration(*s.cfg.Timeout), nil, nil)
|
||||
}
|
||||
}
|
||||
if err = clientConn.Handshake(); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
//forward client data to target,if necessary.
|
||||
if len(forwardBytes) > 0 {
|
||||
outConn.Write(forwardBytes)
|
||||
}
|
||||
|
||||
//bind
|
||||
inAddr := (*inConn).RemoteAddr().String()
|
||||
outAddr := outConn.RemoteAddr().String()
|
||||
utils.IoBind((*inConn), outConn, func(err interface{}) {
|
||||
s.log.Printf("conn %s - %s released [%s]", inAddr, outAddr, address)
|
||||
s.userConns.Remove(inAddr)
|
||||
}, s.log)
|
||||
s.log.Printf("conn %s - %s connected [%s]", inAddr, outAddr, address)
|
||||
if c, ok := s.userConns.Get(inAddr); ok {
|
||||
(*c.(*net.Conn)).Close()
|
||||
}
|
||||
s.userConns.Set(inAddr, inConn)
|
||||
return
|
||||
}
|
||||
func (s *SPS) InitBasicAuth() (err error) {
|
||||
if *s.cfg.DNSAddress != "" {
|
||||
s.basicAuth = utils.NewBasicAuth(&(*s).domainResolver, s.log)
|
||||
} else {
|
||||
s.basicAuth = utils.NewBasicAuth(nil, s.log)
|
||||
}
|
||||
if *s.cfg.AuthURL != "" {
|
||||
s.basicAuth.SetAuthURL(*s.cfg.AuthURL, *s.cfg.AuthURLOkCode, *s.cfg.AuthURLTimeout, *s.cfg.AuthURLRetry)
|
||||
s.log.Printf("auth from %s", *s.cfg.AuthURL)
|
||||
}
|
||||
if *s.cfg.AuthFile != "" {
|
||||
var n = 0
|
||||
n, err = s.basicAuth.AddFromFile(*s.cfg.AuthFile)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("auth-file ERR:%s", err)
|
||||
return
|
||||
}
|
||||
s.log.Printf("auth data added from file %d , total:%d", n, s.basicAuth.Total())
|
||||
}
|
||||
if len(*s.cfg.Auth) > 0 {
|
||||
n := s.basicAuth.Add(*s.cfg.Auth)
|
||||
s.log.Printf("auth data added %d, total:%d", n, s.basicAuth.Total())
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *SPS) IsBasicAuth() bool {
|
||||
return *s.cfg.AuthFile != "" || len(*s.cfg.Auth) > 0 || *s.cfg.AuthURL != ""
|
||||
}
|
||||
func (s *SPS) buildRequest(address string) (buf []byte, err error) {
|
||||
host, portStr, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
port, err := strconv.Atoi(portStr)
|
||||
if err != nil {
|
||||
err = errors.New("proxy: failed to parse port number: " + portStr)
|
||||
return
|
||||
}
|
||||
if port < 1 || port > 0xffff {
|
||||
err = errors.New("proxy: port number out of range: " + portStr)
|
||||
return
|
||||
}
|
||||
buf = buf[:0]
|
||||
buf = append(buf, 0x05, 0x01, 0 /* reserved */)
|
||||
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
if ip4 := ip.To4(); ip4 != nil {
|
||||
buf = append(buf, 0x01)
|
||||
ip = ip4
|
||||
} else {
|
||||
buf = append(buf, 0x04)
|
||||
}
|
||||
buf = append(buf, ip...)
|
||||
} else {
|
||||
if len(host) > 255 {
|
||||
err = errors.New("proxy: destination host name too long: " + host)
|
||||
return
|
||||
}
|
||||
buf = append(buf, 0x03)
|
||||
buf = append(buf, byte(len(host)))
|
||||
buf = append(buf, host...)
|
||||
}
|
||||
buf = append(buf, byte(port>>8), byte(port))
|
||||
return
|
||||
}
|
||||
func (s *SPS) Resolve(address string) string {
|
||||
if *s.cfg.DNSAddress == "" {
|
||||
return address
|
||||
}
|
||||
ip, err := s.domainResolver.Resolve(address)
|
||||
if err != nil {
|
||||
s.log.Printf("dns error %s , ERR:%s", address, err)
|
||||
return address
|
||||
}
|
||||
return ip
|
||||
}
|
||||
183
services/tcp.go
@ -1,183 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"proxy/utils"
|
||||
"runtime/debug"
|
||||
"time"
|
||||
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type TCP struct {
|
||||
outPool utils.OutPool
|
||||
cfg TCPArgs
|
||||
}
|
||||
|
||||
func NewTCP() Service {
|
||||
return &TCP{
|
||||
outPool: utils.OutPool{},
|
||||
cfg: TCPArgs{},
|
||||
}
|
||||
}
|
||||
func (s *TCP) CheckArgs() {
|
||||
if *s.cfg.Parent == "" {
|
||||
log.Fatalf("parent required for %s %s", s.cfg.Protocol(), *s.cfg.Local)
|
||||
}
|
||||
if *s.cfg.ParentType == "" {
|
||||
log.Fatalf("parent type unkown,use -T <tls|tcp|kcp|udp>")
|
||||
}
|
||||
if *s.cfg.ParentType == TYPE_TLS || *s.cfg.LocalType == TYPE_TLS {
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
}
|
||||
}
|
||||
func (s *TCP) InitService() {
|
||||
s.InitOutConnPool()
|
||||
}
|
||||
func (s *TCP) StopService() {
|
||||
if s.outPool.Pool != nil {
|
||||
s.outPool.Pool.ReleaseAll()
|
||||
}
|
||||
}
|
||||
func (s *TCP) Start(args interface{}) (err error) {
|
||||
s.cfg = args.(TCPArgs)
|
||||
s.CheckArgs()
|
||||
log.Printf("use %s parent %s", *s.cfg.ParentType, *s.cfg.Parent)
|
||||
s.InitService()
|
||||
|
||||
host, port, _ := net.SplitHostPort(*s.cfg.Local)
|
||||
p, _ := strconv.Atoi(port)
|
||||
sc := utils.NewServerChannel(host, p)
|
||||
|
||||
if *s.cfg.LocalType == TYPE_TCP {
|
||||
err = sc.ListenTCP(s.callback)
|
||||
} else if *s.cfg.LocalType == TYPE_TLS {
|
||||
err = sc.ListenTls(s.cfg.CertBytes, s.cfg.KeyBytes, s.callback)
|
||||
} else if *s.cfg.LocalType == TYPE_KCP {
|
||||
err = sc.ListenKCP(*s.cfg.KCPMethod, *s.cfg.KCPKey, s.callback)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
log.Printf("%s proxy on %s", s.cfg.Protocol(), (*sc.Listener).Addr())
|
||||
return
|
||||
}
|
||||
|
||||
func (s *TCP) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *TCP) callback(inConn net.Conn) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Printf("%s conn handler crashed with err : %s \nstack: %s", s.cfg.Protocol(), err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
var err error
|
||||
switch *s.cfg.ParentType {
|
||||
case TYPE_KCP:
|
||||
fallthrough
|
||||
case TYPE_TCP:
|
||||
fallthrough
|
||||
case TYPE_TLS:
|
||||
err = s.OutToTCP(&inConn)
|
||||
case TYPE_UDP:
|
||||
err = s.OutToUDP(&inConn)
|
||||
default:
|
||||
err = fmt.Errorf("unkown parent type %s", *s.cfg.ParentType)
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("connect to %s parent %s fail, ERR:%s", *s.cfg.ParentType, *s.cfg.Parent, err)
|
||||
utils.CloseConn(&inConn)
|
||||
}
|
||||
}
|
||||
func (s *TCP) OutToTCP(inConn *net.Conn) (err error) {
|
||||
var outConn net.Conn
|
||||
var _outConn interface{}
|
||||
_outConn, err = s.outPool.Pool.Get()
|
||||
if err == nil {
|
||||
outConn = _outConn.(net.Conn)
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("connect to %s , err:%s", *s.cfg.Parent, err)
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
inAddr := (*inConn).RemoteAddr().String()
|
||||
//inLocalAddr := (*inConn).LocalAddr().String()
|
||||
outAddr := outConn.RemoteAddr().String()
|
||||
//outLocalAddr := outConn.LocalAddr().String()
|
||||
utils.IoBind((*inConn), outConn, func(err interface{}) {
|
||||
log.Printf("conn %s - %s released", inAddr, outAddr)
|
||||
})
|
||||
log.Printf("conn %s - %s connected", inAddr, outAddr)
|
||||
return
|
||||
}
|
||||
func (s *TCP) OutToUDP(inConn *net.Conn) (err error) {
|
||||
log.Printf("conn created , remote : %s ", (*inConn).RemoteAddr())
|
||||
for {
|
||||
srcAddr, body, err := utils.ReadUDPPacket(bufio.NewReader(*inConn))
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
//log.Printf("connection %s released", srcAddr)
|
||||
utils.CloseConn(inConn)
|
||||
break
|
||||
}
|
||||
//log.Debugf("udp packet revecived:%s,%v", srcAddr, body)
|
||||
dstAddr, err := net.ResolveUDPAddr("udp", *s.cfg.Parent)
|
||||
if err != nil {
|
||||
log.Printf("can't resolve address: %s", err)
|
||||
utils.CloseConn(inConn)
|
||||
break
|
||||
}
|
||||
clientSrcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||
conn, err := net.DialUDP("udp", clientSrcAddr, dstAddr)
|
||||
if err != nil {
|
||||
log.Printf("connect to udp %s fail,ERR:%s", dstAddr.String(), err)
|
||||
continue
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = conn.Write(body)
|
||||
if err != nil {
|
||||
log.Printf("send udp packet to %s fail,ERR:%s", dstAddr.String(), err)
|
||||
continue
|
||||
}
|
||||
//log.Debugf("send udp packet to %s success", dstAddr.String())
|
||||
buf := make([]byte, 512)
|
||||
len, _, err := conn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
log.Printf("read udp response from %s fail ,ERR:%s", dstAddr.String(), err)
|
||||
continue
|
||||
}
|
||||
respBody := buf[0:len]
|
||||
//log.Debugf("revecived udp packet from %s , %v", dstAddr.String(), respBody)
|
||||
_, err = (*inConn).Write(utils.UDPPacket(srcAddr, respBody))
|
||||
if err != nil {
|
||||
log.Printf("send udp response fail ,ERR:%s", err)
|
||||
utils.CloseConn(inConn)
|
||||
break
|
||||
}
|
||||
//log.Printf("send udp response success ,from:%s", dstAddr.String())
|
||||
}
|
||||
return
|
||||
|
||||
}
|
||||
func (s *TCP) InitOutConnPool() {
|
||||
if *s.cfg.ParentType == TYPE_TLS || *s.cfg.ParentType == TYPE_TCP || *s.cfg.ParentType == TYPE_KCP {
|
||||
//dur int, isTLS bool, certBytes, keyBytes []byte,
|
||||
//parent string, timeout int, InitialCap int, MaxCap int
|
||||
s.outPool = utils.NewOutPool(
|
||||
*s.cfg.CheckParentInterval,
|
||||
*s.cfg.ParentType,
|
||||
*s.cfg.KCPMethod,
|
||||
*s.cfg.KCPKey,
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes,
|
||||
*s.cfg.Parent,
|
||||
*s.cfg.Timeout,
|
||||
*s.cfg.PoolSize,
|
||||
*s.cfg.PoolSize*2,
|
||||
)
|
||||
}
|
||||
}
|
||||
266
services/tcp/tcp.go
Normal file
@ -0,0 +1,266 @@
|
||||
package tcp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
logger "log"
|
||||
"net"
|
||||
"runtime/debug"
|
||||
"time"
|
||||
|
||||
"github.com/snail007/goproxy/services"
|
||||
"github.com/snail007/goproxy/services/kcpcfg"
|
||||
"github.com/snail007/goproxy/utils"
|
||||
"github.com/snail007/goproxy/utils/jumper"
|
||||
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type TCPArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Local *string
|
||||
ParentType *string
|
||||
LocalType *string
|
||||
Timeout *int
|
||||
KCP kcpcfg.KCPConfigArgs
|
||||
Jumper *string
|
||||
}
|
||||
|
||||
type TCP struct {
|
||||
cfg TCPArgs
|
||||
sc *utils.ServerChannel
|
||||
isStop bool
|
||||
userConns utils.ConcurrentMap
|
||||
log *logger.Logger
|
||||
jumper *jumper.Jumper
|
||||
}
|
||||
|
||||
func NewTCP() services.Service {
|
||||
return &TCP{
|
||||
cfg: TCPArgs{},
|
||||
isStop: false,
|
||||
userConns: utils.NewConcurrentMap(),
|
||||
}
|
||||
}
|
||||
func (s *TCP) CheckArgs() (err error) {
|
||||
if *s.cfg.Parent == "" {
|
||||
err = fmt.Errorf("parent required for %s %s", *s.cfg.LocalType, *s.cfg.Local)
|
||||
return
|
||||
}
|
||||
if *s.cfg.ParentType == "" {
|
||||
err = fmt.Errorf("parent type unkown,use -T <tls|tcp|kcp|udp>")
|
||||
return
|
||||
}
|
||||
if *s.cfg.ParentType == "tls" || *s.cfg.LocalType == "tls" {
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes, err = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if *s.cfg.Jumper != "" {
|
||||
if *s.cfg.ParentType != "tls" && *s.cfg.ParentType != "tcp" {
|
||||
err = fmt.Errorf("jumper only worked of -T is tls or tcp")
|
||||
return
|
||||
}
|
||||
var j jumper.Jumper
|
||||
j, err = jumper.New(*s.cfg.Jumper, time.Millisecond*time.Duration(*s.cfg.Timeout))
|
||||
if err != nil {
|
||||
err = fmt.Errorf("parse jumper fail, err %s", err)
|
||||
return
|
||||
}
|
||||
s.jumper = &j
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *TCP) InitService() (err error) {
|
||||
|
||||
return
|
||||
}
|
||||
func (s *TCP) StopService() {
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
s.log.Printf("stop tcp service crashed,%s", e)
|
||||
} else {
|
||||
s.log.Printf("service tcp stopped")
|
||||
}
|
||||
}()
|
||||
s.isStop = true
|
||||
if s.sc.Listener != nil && *s.sc.Listener != nil {
|
||||
(*s.sc.Listener).Close()
|
||||
}
|
||||
if s.sc.UDPListener != nil {
|
||||
(*s.sc.UDPListener).Close()
|
||||
}
|
||||
for _, c := range s.userConns.Items() {
|
||||
(*c.(*net.Conn)).Close()
|
||||
}
|
||||
}
|
||||
func (s *TCP) Start(args interface{}, log *logger.Logger) (err error) {
|
||||
s.log = log
|
||||
s.cfg = args.(TCPArgs)
|
||||
if err = s.CheckArgs(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = s.InitService(); err != nil {
|
||||
return
|
||||
}
|
||||
s.log.Printf("use %s parent %s", *s.cfg.ParentType, *s.cfg.Parent)
|
||||
host, port, _ := net.SplitHostPort(*s.cfg.Local)
|
||||
p, _ := strconv.Atoi(port)
|
||||
sc := utils.NewServerChannel(host, p, s.log)
|
||||
|
||||
if *s.cfg.LocalType == "tcp" {
|
||||
err = sc.ListenTCP(s.callback)
|
||||
} else if *s.cfg.LocalType == "tls" {
|
||||
err = sc.ListenTls(s.cfg.CertBytes, s.cfg.KeyBytes, nil, s.callback)
|
||||
} else if *s.cfg.LocalType == "kcp" {
|
||||
err = sc.ListenKCP(s.cfg.KCP, s.callback, s.log)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.log.Printf("%s proxy on %s", *s.cfg.LocalType, (*sc.Listener).Addr())
|
||||
s.sc = &sc
|
||||
return
|
||||
}
|
||||
|
||||
func (s *TCP) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *TCP) callback(inConn net.Conn) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
s.log.Printf("%s conn handler crashed with err : %s \nstack: %s", *s.cfg.LocalType, err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
var err error
|
||||
switch *s.cfg.ParentType {
|
||||
case "kcp":
|
||||
fallthrough
|
||||
case "tcp":
|
||||
fallthrough
|
||||
case "tls":
|
||||
err = s.OutToTCP(&inConn)
|
||||
case "udp":
|
||||
err = s.OutToUDP(&inConn)
|
||||
default:
|
||||
err = fmt.Errorf("unkown parent type %s", *s.cfg.ParentType)
|
||||
}
|
||||
if err != nil {
|
||||
s.log.Printf("connect to %s parent %s fail, ERR:%s", *s.cfg.ParentType, *s.cfg.Parent, err)
|
||||
utils.CloseConn(&inConn)
|
||||
}
|
||||
}
|
||||
func (s *TCP) OutToTCP(inConn *net.Conn) (err error) {
|
||||
var outConn net.Conn
|
||||
outConn, err = s.GetParentConn()
|
||||
if err != nil {
|
||||
s.log.Printf("connect to %s , err:%s", *s.cfg.Parent, err)
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
inAddr := (*inConn).RemoteAddr().String()
|
||||
//inLocalAddr := (*inConn).LocalAddr().String()
|
||||
outAddr := outConn.RemoteAddr().String()
|
||||
//outLocalAddr := outConn.LocalAddr().String()
|
||||
utils.IoBind((*inConn), outConn, func(err interface{}) {
|
||||
s.log.Printf("conn %s - %s released", inAddr, outAddr)
|
||||
s.userConns.Remove(inAddr)
|
||||
}, s.log)
|
||||
s.log.Printf("conn %s - %s connected", inAddr, outAddr)
|
||||
if c, ok := s.userConns.Get(inAddr); ok {
|
||||
(*c.(*net.Conn)).Close()
|
||||
}
|
||||
s.userConns.Set(inAddr, inConn)
|
||||
return
|
||||
}
|
||||
func (s *TCP) OutToUDP(inConn *net.Conn) (err error) {
|
||||
s.log.Printf("conn created , remote : %s ", (*inConn).RemoteAddr())
|
||||
for {
|
||||
if s.isStop {
|
||||
(*inConn).Close()
|
||||
return
|
||||
}
|
||||
srcAddr, body, err := utils.ReadUDPPacket(bufio.NewReader(*inConn))
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
//s.log.Printf("connection %s released", srcAddr)
|
||||
utils.CloseConn(inConn)
|
||||
break
|
||||
}
|
||||
//log.Debugf("udp packet revecived:%s,%v", srcAddr, body)
|
||||
dstAddr, err := net.ResolveUDPAddr("udp", *s.cfg.Parent)
|
||||
if err != nil {
|
||||
s.log.Printf("can't resolve address: %s", err)
|
||||
utils.CloseConn(inConn)
|
||||
break
|
||||
}
|
||||
clientSrcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||
conn, err := net.DialUDP("udp", clientSrcAddr, dstAddr)
|
||||
if err != nil {
|
||||
s.log.Printf("connect to udp %s fail,ERR:%s", dstAddr.String(), err)
|
||||
continue
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = conn.Write(body)
|
||||
if err != nil {
|
||||
s.log.Printf("send udp packet to %s fail,ERR:%s", dstAddr.String(), err)
|
||||
continue
|
||||
}
|
||||
//log.Debugf("send udp packet to %s success", dstAddr.String())
|
||||
buf := make([]byte, 512)
|
||||
len, _, err := conn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
s.log.Printf("read udp response from %s fail ,ERR:%s", dstAddr.String(), err)
|
||||
continue
|
||||
}
|
||||
respBody := buf[0:len]
|
||||
//log.Debugf("revecived udp packet from %s , %v", dstAddr.String(), respBody)
|
||||
_, err = (*inConn).Write(utils.UDPPacket(srcAddr, respBody))
|
||||
if err != nil {
|
||||
s.log.Printf("send udp response fail ,ERR:%s", err)
|
||||
utils.CloseConn(inConn)
|
||||
break
|
||||
}
|
||||
//s.log.Printf("send udp response success ,from:%s", dstAddr.String())
|
||||
}
|
||||
return
|
||||
|
||||
}
|
||||
func (s *TCP) GetParentConn() (conn net.Conn, err error) {
|
||||
if *s.cfg.ParentType == "tls" {
|
||||
if s.jumper == nil {
|
||||
var _conn tls.Conn
|
||||
_conn, err = utils.TlsConnectHost(*s.cfg.Parent, *s.cfg.Timeout, s.cfg.CertBytes, s.cfg.KeyBytes, nil)
|
||||
if err == nil {
|
||||
conn = net.Conn(&_conn)
|
||||
}
|
||||
} else {
|
||||
conf, err := utils.TlsConfig(s.cfg.CertBytes, s.cfg.KeyBytes, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var _c net.Conn
|
||||
_c, err = s.jumper.Dial(*s.cfg.Parent, time.Millisecond*time.Duration(*s.cfg.Timeout))
|
||||
if err == nil {
|
||||
conn = net.Conn(tls.Client(_c, conf))
|
||||
}
|
||||
}
|
||||
|
||||
} else if *s.cfg.ParentType == "kcp" {
|
||||
conn, err = utils.ConnectKCPHost(*s.cfg.Parent, s.cfg.KCP)
|
||||
} else {
|
||||
if s.jumper == nil {
|
||||
conn, err = utils.ConnectHost(*s.cfg.Parent, *s.cfg.Timeout)
|
||||
} else {
|
||||
conn, err = s.jumper.Dial(*s.cfg.Parent, time.Millisecond*time.Duration(*s.cfg.Timeout))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
215
services/tunnel/tunnel_bridge.go
Normal file
@ -0,0 +1,215 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
logger "log"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/snail007/goproxy/services"
|
||||
"github.com/snail007/goproxy/utils"
|
||||
|
||||
//"github.com/xtaci/smux"
|
||||
smux "github.com/hashicorp/yamux"
|
||||
)
|
||||
|
||||
const (
|
||||
CONN_CLIENT_CONTROL = uint8(1)
|
||||
CONN_SERVER = uint8(4)
|
||||
CONN_CLIENT = uint8(5)
|
||||
)
|
||||
|
||||
type TunnelBridgeArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Local *string
|
||||
Timeout *int
|
||||
}
|
||||
type ServerConn struct {
|
||||
//ClientLocalAddr string //tcp:2.2.22:333@ID
|
||||
Conn *net.Conn
|
||||
}
|
||||
type TunnelBridge struct {
|
||||
cfg TunnelBridgeArgs
|
||||
serverConns utils.ConcurrentMap
|
||||
clientControlConns utils.ConcurrentMap
|
||||
isStop bool
|
||||
log *logger.Logger
|
||||
}
|
||||
|
||||
func NewTunnelBridge() services.Service {
|
||||
return &TunnelBridge{
|
||||
cfg: TunnelBridgeArgs{},
|
||||
serverConns: utils.NewConcurrentMap(),
|
||||
clientControlConns: utils.NewConcurrentMap(),
|
||||
isStop: false,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TunnelBridge) InitService() (err error) {
|
||||
return
|
||||
}
|
||||
func (s *TunnelBridge) CheckArgs() (err error) {
|
||||
if *s.cfg.CertFile == "" || *s.cfg.KeyFile == "" {
|
||||
err = fmt.Errorf("cert and key file required")
|
||||
return
|
||||
}
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes, err = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
return
|
||||
}
|
||||
func (s *TunnelBridge) StopService() {
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
s.log.Printf("stop tbridge service crashed,%s", e)
|
||||
} else {
|
||||
s.log.Printf("service tbridge stopped")
|
||||
}
|
||||
}()
|
||||
s.isStop = true
|
||||
for _, sess := range s.clientControlConns.Items() {
|
||||
(*sess.(*net.Conn)).Close()
|
||||
}
|
||||
for _, sess := range s.serverConns.Items() {
|
||||
(*sess.(ServerConn).Conn).Close()
|
||||
}
|
||||
}
|
||||
func (s *TunnelBridge) Start(args interface{}, log *logger.Logger) (err error) {
|
||||
s.log = log
|
||||
s.cfg = args.(TunnelBridgeArgs)
|
||||
if err = s.CheckArgs(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = s.InitService(); err != nil {
|
||||
return
|
||||
}
|
||||
host, port, _ := net.SplitHostPort(*s.cfg.Local)
|
||||
p, _ := strconv.Atoi(port)
|
||||
sc := utils.NewServerChannel(host, p, s.log)
|
||||
|
||||
err = sc.ListenTls(s.cfg.CertBytes, s.cfg.KeyBytes, nil, s.callback)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.log.Printf("proxy on tunnel bridge mode %s", (*sc.Listener).Addr())
|
||||
return
|
||||
}
|
||||
func (s *TunnelBridge) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *TunnelBridge) callback(inConn net.Conn) {
|
||||
var err error
|
||||
//s.log.Printf("connection from %s ", inConn.RemoteAddr())
|
||||
sess, err := smux.Server(inConn, &smux.Config{
|
||||
AcceptBacklog: 256,
|
||||
EnableKeepAlive: true,
|
||||
KeepAliveInterval: 9 * time.Second,
|
||||
ConnectionWriteTimeout: 3 * time.Second,
|
||||
MaxStreamWindowSize: 512 * 1024,
|
||||
LogOutput: os.Stderr,
|
||||
})
|
||||
if err != nil {
|
||||
s.log.Printf("new mux server conn error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
inConn, err = sess.AcceptStream()
|
||||
if err != nil {
|
||||
s.log.Printf("mux server conn accept error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
|
||||
var buf = make([]byte, 1024)
|
||||
n, _ := inConn.Read(buf)
|
||||
reader := bytes.NewReader(buf[:n])
|
||||
//reader := bufio.NewReader(inConn)
|
||||
|
||||
var connType uint8
|
||||
err = utils.ReadPacket(reader, &connType)
|
||||
if err != nil {
|
||||
s.log.Printf("read error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
switch connType {
|
||||
case CONN_SERVER:
|
||||
var key, ID, clientLocalAddr, serverID string
|
||||
err = utils.ReadPacketData(reader, &key, &ID, &clientLocalAddr, &serverID)
|
||||
if err != nil {
|
||||
s.log.Printf("read error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
packet := utils.BuildPacketData(ID, clientLocalAddr, serverID)
|
||||
s.log.Printf("server connection, key: %s , id: %s %s %s", key, ID, clientLocalAddr, serverID)
|
||||
|
||||
//addr := clientLocalAddr + "@" + ID
|
||||
s.serverConns.Set(ID, ServerConn{
|
||||
Conn: &inConn,
|
||||
})
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
item, ok := s.clientControlConns.Get(key)
|
||||
if !ok {
|
||||
s.log.Printf("client %s control conn not exists", key)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
}
|
||||
(*item.(*net.Conn)).SetWriteDeadline(time.Now().Add(time.Second * 3))
|
||||
_, err := (*item.(*net.Conn)).Write(packet)
|
||||
(*item.(*net.Conn)).SetWriteDeadline(time.Time{})
|
||||
if err != nil {
|
||||
s.log.Printf("%s client control conn write signal fail, err: %s, retrying...", key, err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
// s.cmServer.Add(serverID, ID, &inConn)
|
||||
break
|
||||
}
|
||||
}
|
||||
case CONN_CLIENT:
|
||||
var key, ID, serverID string
|
||||
err = utils.ReadPacketData(reader, &key, &ID, &serverID)
|
||||
if err != nil {
|
||||
s.log.Printf("read error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
s.log.Printf("client connection , key: %s , id: %s, server id:%s", key, ID, serverID)
|
||||
|
||||
serverConnItem, ok := s.serverConns.Get(ID)
|
||||
if !ok {
|
||||
inConn.Close()
|
||||
s.log.Printf("server conn %s exists", ID)
|
||||
return
|
||||
}
|
||||
serverConn := serverConnItem.(ServerConn).Conn
|
||||
utils.IoBind(*serverConn, inConn, func(err interface{}) {
|
||||
s.serverConns.Remove(ID)
|
||||
// s.cmClient.RemoveOne(key, ID)
|
||||
// s.cmServer.RemoveOne(serverID, ID)
|
||||
s.log.Printf("conn %s released", ID)
|
||||
}, s.log)
|
||||
// s.cmClient.Add(key, ID, &inConn)
|
||||
s.log.Printf("conn %s created", ID)
|
||||
|
||||
case CONN_CLIENT_CONTROL:
|
||||
var key string
|
||||
err = utils.ReadPacketData(reader, &key)
|
||||
if err != nil {
|
||||
s.log.Printf("read error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
s.log.Printf("client control connection, key: %s", key)
|
||||
if s.clientControlConns.Has(key) {
|
||||
item, _ := s.clientControlConns.Get(key)
|
||||
(*item.(*net.Conn)).Close()
|
||||
}
|
||||
s.clientControlConns.Set(key, &inConn)
|
||||
s.log.Printf("set client %s control conn", key)
|
||||
}
|
||||
}
|
||||
340
services/tunnel/tunnel_client.go
Normal file
@ -0,0 +1,340 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
logger "log"
|
||||
"net"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/snail007/goproxy/services"
|
||||
"github.com/snail007/goproxy/utils"
|
||||
"github.com/snail007/goproxy/utils/jumper"
|
||||
//"github.com/xtaci/smux"
|
||||
smux "github.com/hashicorp/yamux"
|
||||
)
|
||||
|
||||
const (
|
||||
CONN_SERVER_MUX = uint8(6)
|
||||
CONN_CLIENT_MUX = uint8(7)
|
||||
)
|
||||
|
||||
type TunnelClientArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Key *string
|
||||
Timeout *int
|
||||
Jumper *string
|
||||
}
|
||||
type TunnelClient struct {
|
||||
cfg TunnelClientArgs
|
||||
ctrlConn net.Conn
|
||||
isStop bool
|
||||
userConns utils.ConcurrentMap
|
||||
log *logger.Logger
|
||||
jumper *jumper.Jumper
|
||||
}
|
||||
|
||||
func NewTunnelClient() services.Service {
|
||||
return &TunnelClient{
|
||||
cfg: TunnelClientArgs{},
|
||||
userConns: utils.NewConcurrentMap(),
|
||||
isStop: false,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TunnelClient) InitService() (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (s *TunnelClient) CheckArgs() (err error) {
|
||||
if *s.cfg.Parent != "" {
|
||||
s.log.Printf("use tls parent %s", *s.cfg.Parent)
|
||||
} else {
|
||||
err = fmt.Errorf("parent required")
|
||||
return
|
||||
}
|
||||
if *s.cfg.CertFile == "" || *s.cfg.KeyFile == "" {
|
||||
err = fmt.Errorf("cert and key file required")
|
||||
return
|
||||
}
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes, err = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if *s.cfg.Jumper != "" {
|
||||
var j jumper.Jumper
|
||||
j, err = jumper.New(*s.cfg.Jumper, time.Millisecond*time.Duration(*s.cfg.Timeout))
|
||||
if err != nil {
|
||||
err = fmt.Errorf("parse jumper fail, err %s", err)
|
||||
return
|
||||
}
|
||||
s.jumper = &j
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *TunnelClient) StopService() {
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
s.log.Printf("stop tclient service crashed,%s", e)
|
||||
} else {
|
||||
s.log.Printf("service tclient stopped")
|
||||
}
|
||||
}()
|
||||
s.isStop = true
|
||||
if s.ctrlConn != nil {
|
||||
s.ctrlConn.Close()
|
||||
}
|
||||
for _, c := range s.userConns.Items() {
|
||||
(*c.(*net.Conn)).Close()
|
||||
}
|
||||
}
|
||||
func (s *TunnelClient) Start(args interface{}, log *logger.Logger) (err error) {
|
||||
s.log = log
|
||||
s.cfg = args.(TunnelClientArgs)
|
||||
if err = s.CheckArgs(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = s.InitService(); err != nil {
|
||||
return
|
||||
}
|
||||
s.log.Printf("proxy on tunnel client mode")
|
||||
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
if s.ctrlConn != nil {
|
||||
s.ctrlConn.Close()
|
||||
}
|
||||
|
||||
s.ctrlConn, err = s.GetInConn(CONN_CLIENT_CONTROL, *s.cfg.Key)
|
||||
if err != nil {
|
||||
s.log.Printf("control connection err: %s, retrying...", err)
|
||||
time.Sleep(time.Second * 3)
|
||||
if s.ctrlConn != nil {
|
||||
s.ctrlConn.Close()
|
||||
}
|
||||
continue
|
||||
}
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
var ID, clientLocalAddr, serverID string
|
||||
err = utils.ReadPacketData(s.ctrlConn, &ID, &clientLocalAddr, &serverID)
|
||||
if err != nil {
|
||||
if s.ctrlConn != nil {
|
||||
s.ctrlConn.Close()
|
||||
}
|
||||
s.log.Printf("read connection signal err: %s, retrying...", err)
|
||||
break
|
||||
}
|
||||
s.log.Printf("signal revecived:%s %s %s", serverID, ID, clientLocalAddr)
|
||||
protocol := clientLocalAddr[:3]
|
||||
localAddr := clientLocalAddr[4:]
|
||||
if protocol == "udp" {
|
||||
go s.ServeUDP(localAddr, ID, serverID)
|
||||
} else {
|
||||
go s.ServeConn(localAddr, ID, serverID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *TunnelClient) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *TunnelClient) GetInConn(typ uint8, data ...string) (outConn net.Conn, err error) {
|
||||
outConn, err = s.GetConn()
|
||||
if err != nil {
|
||||
err = fmt.Errorf("connection err: %s", err)
|
||||
return
|
||||
}
|
||||
_, err = outConn.Write(utils.BuildPacket(typ, data...))
|
||||
if err != nil {
|
||||
err = fmt.Errorf("write connection data err: %s ,retrying...", err)
|
||||
utils.CloseConn(&outConn)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *TunnelClient) GetConn() (conn net.Conn, err error) {
|
||||
if s.jumper == nil {
|
||||
var _conn tls.Conn
|
||||
_conn, err = utils.TlsConnectHost(*s.cfg.Parent, *s.cfg.Timeout, s.cfg.CertBytes, s.cfg.KeyBytes, nil)
|
||||
if err == nil {
|
||||
conn = net.Conn(&_conn)
|
||||
}
|
||||
} else {
|
||||
conf, err := utils.TlsConfig(s.cfg.CertBytes, s.cfg.KeyBytes, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var _c net.Conn
|
||||
_c, err = s.jumper.Dial(*s.cfg.Parent, time.Millisecond*time.Duration(*s.cfg.Timeout))
|
||||
if err == nil {
|
||||
conn = net.Conn(tls.Client(_c, conf))
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
c, e := smux.Client(conn, &smux.Config{
|
||||
AcceptBacklog: 256,
|
||||
EnableKeepAlive: true,
|
||||
KeepAliveInterval: 9 * time.Second,
|
||||
ConnectionWriteTimeout: 3 * time.Second,
|
||||
MaxStreamWindowSize: 512 * 1024,
|
||||
LogOutput: os.Stderr,
|
||||
})
|
||||
if e != nil {
|
||||
s.log.Printf("new mux client conn error,ERR:%s", e)
|
||||
err = e
|
||||
return
|
||||
}
|
||||
conn, e = c.OpenStream()
|
||||
if e != nil {
|
||||
s.log.Printf("mux client conn open stream error,ERR:%s", e)
|
||||
err = e
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *TunnelClient) ServeUDP(localAddr, ID, serverID string) {
|
||||
var inConn net.Conn
|
||||
var err error
|
||||
// for {
|
||||
for {
|
||||
if s.isStop {
|
||||
if inConn != nil {
|
||||
inConn.Close()
|
||||
}
|
||||
return
|
||||
}
|
||||
// s.cm.RemoveOne(*s.cfg.Key, ID)
|
||||
inConn, err = s.GetInConn(CONN_CLIENT, *s.cfg.Key, ID, serverID)
|
||||
if err != nil {
|
||||
utils.CloseConn(&inConn)
|
||||
s.log.Printf("connection err: %s, retrying...", err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
// s.cm.Add(*s.cfg.Key, ID, &inConn)
|
||||
s.log.Printf("conn %s created", ID)
|
||||
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
srcAddr, body, err := utils.ReadUDPPacket(inConn)
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
s.log.Printf("connection %s released", ID)
|
||||
utils.CloseConn(&inConn)
|
||||
break
|
||||
} else if err != nil {
|
||||
s.log.Printf("udp packet revecived fail, err: %s", err)
|
||||
} else {
|
||||
//s.log.Printf("udp packet revecived:%s,%v", srcAddr, body)
|
||||
go s.processUDPPacket(&inConn, srcAddr, localAddr, body)
|
||||
}
|
||||
|
||||
}
|
||||
// }
|
||||
}
|
||||
func (s *TunnelClient) processUDPPacket(inConn *net.Conn, srcAddr, localAddr string, body []byte) {
|
||||
dstAddr, err := net.ResolveUDPAddr("udp", localAddr)
|
||||
if err != nil {
|
||||
s.log.Printf("can't resolve address: %s", err)
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
clientSrcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||
conn, err := net.DialUDP("udp", clientSrcAddr, dstAddr)
|
||||
if err != nil {
|
||||
s.log.Printf("connect to udp %s fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = conn.Write(body)
|
||||
if err != nil {
|
||||
s.log.Printf("send udp packet to %s fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
//s.log.Printf("send udp packet to %s success", dstAddr.String())
|
||||
buf := make([]byte, 1024)
|
||||
length, _, err := conn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
s.log.Printf("read udp response from %s fail ,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
respBody := buf[0:length]
|
||||
//s.log.Printf("revecived udp packet from %s , %v", dstAddr.String(), respBody)
|
||||
bs := utils.UDPPacket(srcAddr, respBody)
|
||||
_, err = (*inConn).Write(bs)
|
||||
if err != nil {
|
||||
s.log.Printf("send udp response fail ,ERR:%s", err)
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
//s.log.Printf("send udp response success ,from:%s ,%d ,%v", dstAddr.String(), len(bs), bs)
|
||||
}
|
||||
func (s *TunnelClient) ServeConn(localAddr, ID, serverID string) {
|
||||
var inConn, outConn net.Conn
|
||||
var err error
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
inConn, err = s.GetInConn(CONN_CLIENT, *s.cfg.Key, ID, serverID)
|
||||
if err != nil {
|
||||
utils.CloseConn(&inConn)
|
||||
s.log.Printf("connection err: %s, retrying...", err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
i := 0
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
i++
|
||||
outConn, err = utils.ConnectHost(localAddr, *s.cfg.Timeout)
|
||||
if err == nil || i == 3 {
|
||||
break
|
||||
} else {
|
||||
if i == 3 {
|
||||
s.log.Printf("connect to %s err: %s, retrying...", localAddr, err)
|
||||
time.Sleep(2 * time.Second)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
utils.CloseConn(&inConn)
|
||||
utils.CloseConn(&outConn)
|
||||
s.log.Printf("build connection error, err: %s", err)
|
||||
return
|
||||
}
|
||||
inAddr := inConn.RemoteAddr().String()
|
||||
utils.IoBind(inConn, outConn, func(err interface{}) {
|
||||
s.log.Printf("conn %s released", ID)
|
||||
s.userConns.Remove(inAddr)
|
||||
}, s.log)
|
||||
if c, ok := s.userConns.Get(inAddr); ok {
|
||||
(*c.(*net.Conn)).Close()
|
||||
}
|
||||
s.userConns.Set(inAddr, &inConn)
|
||||
s.log.Printf("conn %s created", ID)
|
||||
}
|
||||
434
services/tunnel/tunnel_server.go
Normal file
@ -0,0 +1,434 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
logger "log"
|
||||
"net"
|
||||
"os"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/snail007/goproxy/services"
|
||||
"github.com/snail007/goproxy/utils"
|
||||
"github.com/snail007/goproxy/utils/jumper"
|
||||
|
||||
//"github.com/xtaci/smux"
|
||||
smux "github.com/hashicorp/yamux"
|
||||
)
|
||||
|
||||
type TunnelServerArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Local *string
|
||||
IsUDP *bool
|
||||
Key *string
|
||||
Remote *string
|
||||
Timeout *int
|
||||
Route *[]string
|
||||
Mgr *TunnelServerManager
|
||||
Jumper *string
|
||||
}
|
||||
type UDPItem struct {
|
||||
packet *[]byte
|
||||
localAddr *net.UDPAddr
|
||||
srcAddr *net.UDPAddr
|
||||
}
|
||||
type TunnelServerManager struct {
|
||||
cfg TunnelServerArgs
|
||||
udpChn chan UDPItem
|
||||
serverID string
|
||||
servers []*services.Service
|
||||
log *logger.Logger
|
||||
}
|
||||
|
||||
func NewTunnelServerManager() services.Service {
|
||||
return &TunnelServerManager{
|
||||
cfg: TunnelServerArgs{},
|
||||
udpChn: make(chan UDPItem, 50000),
|
||||
serverID: utils.Uniqueid(),
|
||||
servers: []*services.Service{},
|
||||
}
|
||||
}
|
||||
func (s *TunnelServerManager) Start(args interface{}, log *logger.Logger) (err error) {
|
||||
s.log = log
|
||||
s.cfg = args.(TunnelServerArgs)
|
||||
if err = s.CheckArgs(); err != nil {
|
||||
return
|
||||
}
|
||||
if *s.cfg.Parent != "" {
|
||||
s.log.Printf("use tls parent %s", *s.cfg.Parent)
|
||||
} else {
|
||||
err = fmt.Errorf("parent required")
|
||||
return
|
||||
}
|
||||
|
||||
if err = s.InitService(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
s.log.Printf("server id: %s", s.serverID)
|
||||
//s.log.Printf("route:%v", *s.cfg.Route)
|
||||
for _, _info := range *s.cfg.Route {
|
||||
IsUDP := *s.cfg.IsUDP
|
||||
if strings.HasPrefix(_info, "udp://") {
|
||||
IsUDP = true
|
||||
}
|
||||
info := strings.TrimPrefix(_info, "udp://")
|
||||
info = strings.TrimPrefix(info, "tcp://")
|
||||
_routeInfo := strings.Split(info, "@")
|
||||
server := NewTunnelServer()
|
||||
local := _routeInfo[0]
|
||||
remote := _routeInfo[1]
|
||||
KEY := *s.cfg.Key
|
||||
if strings.HasPrefix(remote, "[") {
|
||||
KEY = remote[1:strings.LastIndex(remote, "]")]
|
||||
remote = remote[strings.LastIndex(remote, "]")+1:]
|
||||
}
|
||||
if strings.HasPrefix(remote, ":") {
|
||||
remote = fmt.Sprintf("127.0.0.1%s", remote)
|
||||
}
|
||||
err = server.Start(TunnelServerArgs{
|
||||
CertBytes: s.cfg.CertBytes,
|
||||
KeyBytes: s.cfg.KeyBytes,
|
||||
Parent: s.cfg.Parent,
|
||||
CertFile: s.cfg.CertFile,
|
||||
KeyFile: s.cfg.KeyFile,
|
||||
Local: &local,
|
||||
IsUDP: &IsUDP,
|
||||
Remote: &remote,
|
||||
Key: &KEY,
|
||||
Timeout: s.cfg.Timeout,
|
||||
Mgr: s,
|
||||
Jumper: s.cfg.Jumper,
|
||||
}, log)
|
||||
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.servers = append(s.servers, &server)
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *TunnelServerManager) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *TunnelServerManager) StopService() {
|
||||
for _, server := range s.servers {
|
||||
(*server).Clean()
|
||||
}
|
||||
}
|
||||
func (s *TunnelServerManager) CheckArgs() (err error) {
|
||||
if *s.cfg.CertFile == "" || *s.cfg.KeyFile == "" {
|
||||
err = fmt.Errorf("cert and key file required")
|
||||
return
|
||||
}
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes, err = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
return
|
||||
}
|
||||
func (s *TunnelServerManager) InitService() (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
type TunnelServer struct {
|
||||
cfg TunnelServerArgs
|
||||
udpChn chan UDPItem
|
||||
sc utils.ServerChannel
|
||||
isStop bool
|
||||
udpConn *net.Conn
|
||||
userConns utils.ConcurrentMap
|
||||
log *logger.Logger
|
||||
jumper *jumper.Jumper
|
||||
}
|
||||
|
||||
func NewTunnelServer() services.Service {
|
||||
return &TunnelServer{
|
||||
cfg: TunnelServerArgs{},
|
||||
udpChn: make(chan UDPItem, 50000),
|
||||
isStop: false,
|
||||
userConns: utils.NewConcurrentMap(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TunnelServer) StopService() {
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
s.log.Printf("stop server service crashed,%s", e)
|
||||
} else {
|
||||
s.log.Printf("service server stopped")
|
||||
}
|
||||
}()
|
||||
s.isStop = true
|
||||
|
||||
if s.sc.Listener != nil {
|
||||
(*s.sc.Listener).Close()
|
||||
}
|
||||
if s.sc.UDPListener != nil {
|
||||
(*s.sc.UDPListener).Close()
|
||||
}
|
||||
if s.udpConn != nil {
|
||||
(*s.udpConn).Close()
|
||||
}
|
||||
for _, c := range s.userConns.Items() {
|
||||
(*c.(*net.Conn)).Close()
|
||||
}
|
||||
}
|
||||
func (s *TunnelServer) InitService() (err error) {
|
||||
s.UDPConnDeamon()
|
||||
return
|
||||
}
|
||||
func (s *TunnelServer) CheckArgs() (err error) {
|
||||
if *s.cfg.Remote == "" {
|
||||
err = fmt.Errorf("remote required")
|
||||
return
|
||||
}
|
||||
if *s.cfg.Jumper != "" {
|
||||
var j jumper.Jumper
|
||||
j, err = jumper.New(*s.cfg.Jumper, time.Millisecond*time.Duration(*s.cfg.Timeout))
|
||||
if err != nil {
|
||||
err = fmt.Errorf("parse jumper fail, err %s", err)
|
||||
return
|
||||
}
|
||||
s.jumper = &j
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *TunnelServer) Start(args interface{}, log *logger.Logger) (err error) {
|
||||
s.log = log
|
||||
s.cfg = args.(TunnelServerArgs)
|
||||
if err = s.CheckArgs(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = s.InitService(); err != nil {
|
||||
return
|
||||
}
|
||||
host, port, _ := net.SplitHostPort(*s.cfg.Local)
|
||||
p, _ := strconv.Atoi(port)
|
||||
s.sc = utils.NewServerChannel(host, p, s.log)
|
||||
if *s.cfg.IsUDP {
|
||||
err = s.sc.ListenUDP(func(packet []byte, localAddr, srcAddr *net.UDPAddr) {
|
||||
s.udpChn <- UDPItem{
|
||||
packet: &packet,
|
||||
localAddr: localAddr,
|
||||
srcAddr: srcAddr,
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.log.Printf("proxy on udp tunnel server mode %s", (*s.sc.UDPListener).LocalAddr())
|
||||
} else {
|
||||
err = s.sc.ListenTCP(func(inConn net.Conn) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
s.log.Printf("tserver conn handler crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
var outConn net.Conn
|
||||
var ID string
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
outConn, ID, err = s.GetOutConn(CONN_SERVER)
|
||||
if err != nil {
|
||||
utils.CloseConn(&outConn)
|
||||
s.log.Printf("connect to %s fail, err: %s, retrying...", *s.cfg.Parent, err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
inAddr := inConn.RemoteAddr().String()
|
||||
utils.IoBind(inConn, outConn, func(err interface{}) {
|
||||
s.userConns.Remove(inAddr)
|
||||
s.log.Printf("%s conn %s released", *s.cfg.Key, ID)
|
||||
}, s.log)
|
||||
if c, ok := s.userConns.Get(inAddr); ok {
|
||||
(*c.(*net.Conn)).Close()
|
||||
}
|
||||
s.userConns.Set(inAddr, &inConn)
|
||||
s.log.Printf("%s conn %s created", *s.cfg.Key, ID)
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.log.Printf("proxy on tunnel server mode %s", (*s.sc.Listener).Addr())
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *TunnelServer) Clean() {
|
||||
|
||||
}
|
||||
func (s *TunnelServer) GetOutConn(typ uint8) (outConn net.Conn, ID string, err error) {
|
||||
outConn, err = s.GetConn()
|
||||
if err != nil {
|
||||
s.log.Printf("connection err: %s", err)
|
||||
return
|
||||
}
|
||||
remoteAddr := "tcp:" + *s.cfg.Remote
|
||||
if *s.cfg.IsUDP {
|
||||
remoteAddr = "udp:" + *s.cfg.Remote
|
||||
}
|
||||
ID = utils.Uniqueid()
|
||||
_, err = outConn.Write(utils.BuildPacket(typ, *s.cfg.Key, ID, remoteAddr, s.cfg.Mgr.serverID))
|
||||
if err != nil {
|
||||
s.log.Printf("write connection data err: %s ,retrying...", err)
|
||||
utils.CloseConn(&outConn)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *TunnelServer) GetConn() (conn net.Conn, err error) {
|
||||
var dconn net.Conn
|
||||
if s.jumper == nil {
|
||||
var _conn tls.Conn
|
||||
_conn, err = utils.TlsConnectHost(*s.cfg.Parent, *s.cfg.Timeout, s.cfg.CertBytes, s.cfg.KeyBytes, nil)
|
||||
if err == nil {
|
||||
dconn = net.Conn(&_conn)
|
||||
}
|
||||
} else {
|
||||
conf, err := utils.TlsConfig(s.cfg.CertBytes, s.cfg.KeyBytes, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var _c net.Conn
|
||||
_c, err = s.jumper.Dial(*s.cfg.Parent, time.Millisecond*time.Duration(*s.cfg.Timeout))
|
||||
if err == nil {
|
||||
dconn = net.Conn(tls.Client(_c, conf))
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
sess, e := smux.Client(dconn, &smux.Config{
|
||||
AcceptBacklog: 256,
|
||||
EnableKeepAlive: true,
|
||||
KeepAliveInterval: 9 * time.Second,
|
||||
ConnectionWriteTimeout: 3 * time.Second,
|
||||
MaxStreamWindowSize: 512 * 1024,
|
||||
LogOutput: os.Stderr,
|
||||
})
|
||||
if e != nil {
|
||||
s.log.Printf("new mux client conn error,ERR:%s", e)
|
||||
err = e
|
||||
dconn.Close()
|
||||
return
|
||||
}
|
||||
conn, e = sess.OpenStream()
|
||||
if e != nil {
|
||||
s.log.Printf("mux client conn open stream error,ERR:%s", e)
|
||||
err = e
|
||||
dconn.Close()
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer func() {
|
||||
_ = recover()
|
||||
}()
|
||||
timer := time.NewTicker(time.Second * 3)
|
||||
for {
|
||||
<-timer.C
|
||||
if sess.NumStreams() == 0 {
|
||||
sess.Close()
|
||||
timer.Stop()
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *TunnelServer) UDPConnDeamon() {
|
||||
go func() {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
s.log.Printf("udp conn deamon crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
var outConn net.Conn
|
||||
// var hb utils.HeartbeatReadWriter
|
||||
var ID string
|
||||
// var cmdChn = make(chan bool, 1000)
|
||||
var err error
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
item := <-s.udpChn
|
||||
RETRY:
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
if outConn == nil {
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
outConn, ID, err = s.GetOutConn(CONN_SERVER)
|
||||
if err != nil {
|
||||
// cmdChn <- true
|
||||
outConn = nil
|
||||
utils.CloseConn(&outConn)
|
||||
s.log.Printf("connect to %s fail, err: %s, retrying...", *s.cfg.Parent, err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
go func(outConn net.Conn, ID string) {
|
||||
if s.udpConn != nil {
|
||||
(*s.udpConn).Close()
|
||||
}
|
||||
s.udpConn = &outConn
|
||||
for {
|
||||
if s.isStop {
|
||||
return
|
||||
}
|
||||
srcAddrFromConn, body, err := utils.ReadUDPPacket(outConn)
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
s.log.Printf("UDP deamon connection %s exited", ID)
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
s.log.Printf("parse revecived udp packet fail, err: %s ,%v", err, body)
|
||||
continue
|
||||
}
|
||||
//s.log.Printf("udp packet revecived over parent , local:%s", srcAddrFromConn)
|
||||
_srcAddr := strings.Split(srcAddrFromConn, ":")
|
||||
if len(_srcAddr) != 2 {
|
||||
s.log.Printf("parse revecived udp packet fail, addr error : %s", srcAddrFromConn)
|
||||
continue
|
||||
}
|
||||
port, _ := strconv.Atoi(_srcAddr[1])
|
||||
dstAddr := &net.UDPAddr{IP: net.ParseIP(_srcAddr[0]), Port: port}
|
||||
_, err = s.sc.UDPListener.WriteToUDP(body, dstAddr)
|
||||
if err != nil {
|
||||
s.log.Printf("udp response to local %s fail,ERR:%s", srcAddrFromConn, err)
|
||||
continue
|
||||
}
|
||||
//s.log.Printf("udp response to local %s success , %v", srcAddrFromConn, body)
|
||||
}
|
||||
}(outConn, ID)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
outConn.SetWriteDeadline(time.Now().Add(time.Second))
|
||||
_, err = outConn.Write(utils.UDPPacket(item.srcAddr.String(), *item.packet))
|
||||
outConn.SetWriteDeadline(time.Time{})
|
||||
if err != nil {
|
||||
utils.CloseConn(&outConn)
|
||||
outConn = nil
|
||||
s.log.Printf("write udp packet to %s fail ,flush err:%s ,retrying...", *s.cfg.Parent, err)
|
||||
goto RETRY
|
||||
}
|
||||
//s.log.Printf("write packet %v", *item.packet)
|
||||
}
|
||||
}()
|
||||
}
|
||||
@ -1,244 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"log"
|
||||
"net"
|
||||
"proxy/utils"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ServerConn struct {
|
||||
//ClientLocalAddr string //tcp:2.2.22:333@ID
|
||||
Conn *net.Conn
|
||||
}
|
||||
type TunnelBridge struct {
|
||||
cfg TunnelBridgeArgs
|
||||
serverConns utils.ConcurrentMap
|
||||
clientControlConns utils.ConcurrentMap
|
||||
// cmServer utils.ConnManager
|
||||
// cmClient utils.ConnManager
|
||||
}
|
||||
|
||||
func NewTunnelBridge() Service {
|
||||
return &TunnelBridge{
|
||||
cfg: TunnelBridgeArgs{},
|
||||
serverConns: utils.NewConcurrentMap(),
|
||||
clientControlConns: utils.NewConcurrentMap(),
|
||||
// cmServer: utils.NewConnManager(),
|
||||
// cmClient: utils.NewConnManager(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TunnelBridge) InitService() {
|
||||
|
||||
}
|
||||
func (s *TunnelBridge) CheckArgs() {
|
||||
if *s.cfg.CertFile == "" || *s.cfg.KeyFile == "" {
|
||||
log.Fatalf("cert and key file required")
|
||||
}
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
}
|
||||
func (s *TunnelBridge) StopService() {
|
||||
|
||||
}
|
||||
func (s *TunnelBridge) Start(args interface{}) (err error) {
|
||||
s.cfg = args.(TunnelBridgeArgs)
|
||||
s.CheckArgs()
|
||||
s.InitService()
|
||||
host, port, _ := net.SplitHostPort(*s.cfg.Local)
|
||||
p, _ := strconv.Atoi(port)
|
||||
sc := utils.NewServerChannel(host, p)
|
||||
|
||||
err = sc.ListenTls(s.cfg.CertBytes, s.cfg.KeyBytes, func(inConn net.Conn) {
|
||||
//log.Printf("connection from %s ", inConn.RemoteAddr())
|
||||
|
||||
reader := bufio.NewReader(inConn)
|
||||
var err error
|
||||
var connType uint8
|
||||
err = utils.ReadPacket(reader, &connType)
|
||||
if err != nil {
|
||||
log.Printf("read error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
switch connType {
|
||||
case CONN_SERVER:
|
||||
var key, ID, clientLocalAddr, serverID string
|
||||
err = utils.ReadPacketData(reader, &key, &ID, &clientLocalAddr, &serverID)
|
||||
if err != nil {
|
||||
log.Printf("read error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
packet := utils.BuildPacketData(ID, clientLocalAddr, serverID)
|
||||
log.Printf("server connection, key: %s , id: %s %s %s", key, ID, clientLocalAddr, serverID)
|
||||
|
||||
//addr := clientLocalAddr + "@" + ID
|
||||
s.serverConns.Set(ID, ServerConn{
|
||||
Conn: &inConn,
|
||||
})
|
||||
for {
|
||||
item, ok := s.clientControlConns.Get(key)
|
||||
if !ok {
|
||||
log.Printf("client %s control conn not exists", key)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
}
|
||||
(*item.(*net.Conn)).SetWriteDeadline(time.Now().Add(time.Second * 3))
|
||||
_, err := (*item.(*net.Conn)).Write(packet)
|
||||
(*item.(*net.Conn)).SetWriteDeadline(time.Time{})
|
||||
if err != nil {
|
||||
log.Printf("%s client control conn write signal fail, err: %s, retrying...", key, err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
// s.cmServer.Add(serverID, ID, &inConn)
|
||||
break
|
||||
}
|
||||
}
|
||||
case CONN_CLIENT:
|
||||
var key, ID, serverID string
|
||||
err = utils.ReadPacketData(reader, &key, &ID, &serverID)
|
||||
if err != nil {
|
||||
log.Printf("read error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
log.Printf("client connection , key: %s , id: %s, server id:%s", key, ID, serverID)
|
||||
|
||||
serverConnItem, ok := s.serverConns.Get(ID)
|
||||
if !ok {
|
||||
inConn.Close()
|
||||
log.Printf("server conn %s exists", ID)
|
||||
return
|
||||
}
|
||||
serverConn := serverConnItem.(ServerConn).Conn
|
||||
utils.IoBind(*serverConn, inConn, func(err interface{}) {
|
||||
s.serverConns.Remove(ID)
|
||||
// s.cmClient.RemoveOne(key, ID)
|
||||
// s.cmServer.RemoveOne(serverID, ID)
|
||||
log.Printf("conn %s released", ID)
|
||||
})
|
||||
// s.cmClient.Add(key, ID, &inConn)
|
||||
log.Printf("conn %s created", ID)
|
||||
|
||||
case CONN_CLIENT_CONTROL:
|
||||
var key string
|
||||
err = utils.ReadPacketData(reader, &key)
|
||||
if err != nil {
|
||||
log.Printf("read error,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
log.Printf("client control connection, key: %s", key)
|
||||
if s.clientControlConns.Has(key) {
|
||||
item, _ := s.clientControlConns.Get(key)
|
||||
(*item.(*net.Conn)).Close()
|
||||
}
|
||||
s.clientControlConns.Set(key, &inConn)
|
||||
log.Printf("set client %s control conn", key)
|
||||
|
||||
// case CONN_SERVER_HEARBEAT:
|
||||
// var serverID string
|
||||
// err = utils.ReadPacketData(reader, &serverID)
|
||||
// if err != nil {
|
||||
// log.Printf("read error,ERR:%s", err)
|
||||
// return
|
||||
// }
|
||||
// log.Printf("server heartbeat connection, id: %s", serverID)
|
||||
// writeDie := make(chan bool)
|
||||
// readDie := make(chan bool)
|
||||
// go func() {
|
||||
// for {
|
||||
// inConn.SetWriteDeadline(time.Now().Add(time.Second * 3))
|
||||
// _, err = inConn.Write([]byte{0x00})
|
||||
// inConn.SetWriteDeadline(time.Time{})
|
||||
// if err != nil {
|
||||
// log.Printf("server heartbeat connection write err %s", err)
|
||||
// break
|
||||
// }
|
||||
// time.Sleep(time.Second * 3)
|
||||
// }
|
||||
// close(writeDie)
|
||||
// }()
|
||||
// go func() {
|
||||
// for {
|
||||
// signal := make([]byte, 1)
|
||||
// inConn.SetReadDeadline(time.Now().Add(time.Second * 6))
|
||||
// _, err := inConn.Read(signal)
|
||||
// inConn.SetReadDeadline(time.Time{})
|
||||
// if err != nil {
|
||||
// log.Printf("server heartbeat connection read err: %s", err)
|
||||
// break
|
||||
// } else {
|
||||
// // log.Printf("heartbeat from server ,id:%s", serverID)
|
||||
// }
|
||||
// }
|
||||
// close(readDie)
|
||||
// }()
|
||||
// select {
|
||||
// case <-readDie:
|
||||
// case <-writeDie:
|
||||
// }
|
||||
// utils.CloseConn(&inConn)
|
||||
// s.cmServer.Remove(serverID)
|
||||
// log.Printf("server heartbeat conn %s released", serverID)
|
||||
// case CONN_CLIENT_HEARBEAT:
|
||||
// var clientID string
|
||||
// err = utils.ReadPacketData(reader, &clientID)
|
||||
// if err != nil {
|
||||
// log.Printf("read error,ERR:%s", err)
|
||||
// return
|
||||
// }
|
||||
// log.Printf("client heartbeat connection, id: %s", clientID)
|
||||
// writeDie := make(chan bool)
|
||||
// readDie := make(chan bool)
|
||||
// go func() {
|
||||
// for {
|
||||
// inConn.SetWriteDeadline(time.Now().Add(time.Second * 3))
|
||||
// _, err = inConn.Write([]byte{0x00})
|
||||
// inConn.SetWriteDeadline(time.Time{})
|
||||
// if err != nil {
|
||||
// log.Printf("client heartbeat connection write err %s", err)
|
||||
// break
|
||||
// }
|
||||
// time.Sleep(time.Second * 3)
|
||||
// }
|
||||
// close(writeDie)
|
||||
// }()
|
||||
// go func() {
|
||||
// for {
|
||||
// signal := make([]byte, 1)
|
||||
// inConn.SetReadDeadline(time.Now().Add(time.Second * 6))
|
||||
// _, err := inConn.Read(signal)
|
||||
// inConn.SetReadDeadline(time.Time{})
|
||||
// if err != nil {
|
||||
// log.Printf("client control connection read err: %s", err)
|
||||
// break
|
||||
// } else {
|
||||
// // log.Printf("heartbeat from client ,id:%s", clientID)
|
||||
// }
|
||||
// }
|
||||
// close(readDie)
|
||||
// }()
|
||||
// select {
|
||||
// case <-readDie:
|
||||
// case <-writeDie:
|
||||
// }
|
||||
// utils.CloseConn(&inConn)
|
||||
// s.cmClient.Remove(clientID)
|
||||
// if s.clientControlConns.Has(clientID) {
|
||||
// item, _ := s.clientControlConns.Get(clientID)
|
||||
// (*item.(*net.Conn)).Close()
|
||||
// }
|
||||
// s.clientControlConns.Remove(clientID)
|
||||
// log.Printf("client heartbeat conn %s released", clientID)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
log.Printf("proxy on tunnel bridge mode %s", (*sc.Listener).Addr())
|
||||
return
|
||||
}
|
||||
func (s *TunnelBridge) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
@ -1,283 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"proxy/utils"
|
||||
"time"
|
||||
)
|
||||
|
||||
type TunnelClient struct {
|
||||
cfg TunnelClientArgs
|
||||
// cm utils.ConnManager
|
||||
ctrlConn net.Conn
|
||||
}
|
||||
|
||||
func NewTunnelClient() Service {
|
||||
return &TunnelClient{
|
||||
cfg: TunnelClientArgs{},
|
||||
// cm: utils.NewConnManager(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TunnelClient) InitService() {
|
||||
// s.InitHeartbeatDeamon()
|
||||
}
|
||||
|
||||
// func (s *TunnelClient) InitHeartbeatDeamon() {
|
||||
// log.Printf("heartbeat started")
|
||||
// go func() {
|
||||
// var heartbeatConn net.Conn
|
||||
// var ID = *s.cfg.Key
|
||||
// for {
|
||||
|
||||
// //close all connection
|
||||
// s.cm.RemoveAll()
|
||||
// if s.ctrlConn != nil {
|
||||
// s.ctrlConn.Close()
|
||||
// }
|
||||
// utils.CloseConn(&heartbeatConn)
|
||||
// heartbeatConn, err := s.GetInConn(CONN_CLIENT_HEARBEAT, ID)
|
||||
// if err != nil {
|
||||
// log.Printf("heartbeat connection err: %s, retrying...", err)
|
||||
// time.Sleep(time.Second * 3)
|
||||
// utils.CloseConn(&heartbeatConn)
|
||||
// continue
|
||||
// }
|
||||
// log.Printf("heartbeat connection created,id:%s", ID)
|
||||
// writeDie := make(chan bool)
|
||||
// readDie := make(chan bool)
|
||||
// go func() {
|
||||
// for {
|
||||
// heartbeatConn.SetWriteDeadline(time.Now().Add(time.Second * 3))
|
||||
// _, err = heartbeatConn.Write([]byte{0x00})
|
||||
// heartbeatConn.SetWriteDeadline(time.Time{})
|
||||
// if err != nil {
|
||||
// log.Printf("heartbeat connection write err %s", err)
|
||||
// break
|
||||
// }
|
||||
// time.Sleep(time.Second * 3)
|
||||
// }
|
||||
// close(writeDie)
|
||||
// }()
|
||||
// go func() {
|
||||
// for {
|
||||
// signal := make([]byte, 1)
|
||||
// heartbeatConn.SetReadDeadline(time.Now().Add(time.Second * 6))
|
||||
// _, err := heartbeatConn.Read(signal)
|
||||
// heartbeatConn.SetReadDeadline(time.Time{})
|
||||
// if err != nil {
|
||||
// log.Printf("heartbeat connection read err: %s", err)
|
||||
// break
|
||||
// } else {
|
||||
// //log.Printf("heartbeat from bridge")
|
||||
// }
|
||||
// }
|
||||
// close(readDie)
|
||||
// }()
|
||||
// select {
|
||||
// case <-readDie:
|
||||
// case <-writeDie:
|
||||
// }
|
||||
// }
|
||||
// }()
|
||||
// }
|
||||
func (s *TunnelClient) CheckArgs() {
|
||||
if *s.cfg.Parent != "" {
|
||||
log.Printf("use tls parent %s", *s.cfg.Parent)
|
||||
} else {
|
||||
log.Fatalf("parent required")
|
||||
}
|
||||
if *s.cfg.CertFile == "" || *s.cfg.KeyFile == "" {
|
||||
log.Fatalf("cert and key file required")
|
||||
}
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
}
|
||||
func (s *TunnelClient) StopService() {
|
||||
// s.cm.RemoveAll()
|
||||
}
|
||||
func (s *TunnelClient) Start(args interface{}) (err error) {
|
||||
s.cfg = args.(TunnelClientArgs)
|
||||
s.CheckArgs()
|
||||
s.InitService()
|
||||
log.Printf("proxy on tunnel client mode")
|
||||
|
||||
for {
|
||||
//close all conn
|
||||
// s.cm.Remove(*s.cfg.Key)
|
||||
if s.ctrlConn != nil {
|
||||
s.ctrlConn.Close()
|
||||
}
|
||||
|
||||
s.ctrlConn, err = s.GetInConn(CONN_CLIENT_CONTROL, *s.cfg.Key)
|
||||
if err != nil {
|
||||
log.Printf("control connection err: %s, retrying...", err)
|
||||
time.Sleep(time.Second * 3)
|
||||
if s.ctrlConn != nil {
|
||||
s.ctrlConn.Close()
|
||||
}
|
||||
continue
|
||||
}
|
||||
for {
|
||||
var ID, clientLocalAddr, serverID string
|
||||
err = utils.ReadPacketData(s.ctrlConn, &ID, &clientLocalAddr, &serverID)
|
||||
if err != nil {
|
||||
if s.ctrlConn != nil {
|
||||
s.ctrlConn.Close()
|
||||
}
|
||||
log.Printf("read connection signal err: %s, retrying...", err)
|
||||
break
|
||||
}
|
||||
log.Printf("signal revecived:%s %s %s", serverID, ID, clientLocalAddr)
|
||||
protocol := clientLocalAddr[:3]
|
||||
localAddr := clientLocalAddr[4:]
|
||||
if protocol == "udp" {
|
||||
go s.ServeUDP(localAddr, ID, serverID)
|
||||
} else {
|
||||
go s.ServeConn(localAddr, ID, serverID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *TunnelClient) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *TunnelClient) GetInConn(typ uint8, data ...string) (outConn net.Conn, err error) {
|
||||
outConn, err = s.GetConn()
|
||||
if err != nil {
|
||||
err = fmt.Errorf("connection err: %s", err)
|
||||
return
|
||||
}
|
||||
_, err = outConn.Write(utils.BuildPacket(typ, data...))
|
||||
if err != nil {
|
||||
err = fmt.Errorf("write connection data err: %s ,retrying...", err)
|
||||
utils.CloseConn(&outConn)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *TunnelClient) GetConn() (conn net.Conn, err error) {
|
||||
var _conn tls.Conn
|
||||
_conn, err = utils.TlsConnectHost(*s.cfg.Parent, *s.cfg.Timeout, s.cfg.CertBytes, s.cfg.KeyBytes)
|
||||
if err == nil {
|
||||
conn = net.Conn(&_conn)
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *TunnelClient) ServeUDP(localAddr, ID, serverID string) {
|
||||
var inConn net.Conn
|
||||
var err error
|
||||
// for {
|
||||
for {
|
||||
// s.cm.RemoveOne(*s.cfg.Key, ID)
|
||||
inConn, err = s.GetInConn(CONN_CLIENT, *s.cfg.Key, ID, serverID)
|
||||
if err != nil {
|
||||
utils.CloseConn(&inConn)
|
||||
log.Printf("connection err: %s, retrying...", err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
// s.cm.Add(*s.cfg.Key, ID, &inConn)
|
||||
log.Printf("conn %s created", ID)
|
||||
|
||||
for {
|
||||
srcAddr, body, err := utils.ReadUDPPacket(inConn)
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
log.Printf("connection %s released", ID)
|
||||
utils.CloseConn(&inConn)
|
||||
break
|
||||
} else if err != nil {
|
||||
log.Printf("udp packet revecived fail, err: %s", err)
|
||||
} else {
|
||||
//log.Printf("udp packet revecived:%s,%v", srcAddr, body)
|
||||
go s.processUDPPacket(&inConn, srcAddr, localAddr, body)
|
||||
}
|
||||
|
||||
}
|
||||
// }
|
||||
}
|
||||
func (s *TunnelClient) processUDPPacket(inConn *net.Conn, srcAddr, localAddr string, body []byte) {
|
||||
dstAddr, err := net.ResolveUDPAddr("udp", localAddr)
|
||||
if err != nil {
|
||||
log.Printf("can't resolve address: %s", err)
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
clientSrcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||
conn, err := net.DialUDP("udp", clientSrcAddr, dstAddr)
|
||||
if err != nil {
|
||||
log.Printf("connect to udp %s fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = conn.Write(body)
|
||||
if err != nil {
|
||||
log.Printf("send udp packet to %s fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
//log.Printf("send udp packet to %s success", dstAddr.String())
|
||||
buf := make([]byte, 1024)
|
||||
length, _, err := conn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
log.Printf("read udp response from %s fail ,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
respBody := buf[0:length]
|
||||
//log.Printf("revecived udp packet from %s , %v", dstAddr.String(), respBody)
|
||||
bs := utils.UDPPacket(srcAddr, respBody)
|
||||
_, err = (*inConn).Write(bs)
|
||||
if err != nil {
|
||||
log.Printf("send udp response fail ,ERR:%s", err)
|
||||
utils.CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
//log.Printf("send udp response success ,from:%s ,%d ,%v", dstAddr.String(), len(bs), bs)
|
||||
}
|
||||
func (s *TunnelClient) ServeConn(localAddr, ID, serverID string) {
|
||||
var inConn, outConn net.Conn
|
||||
var err error
|
||||
for {
|
||||
inConn, err = s.GetInConn(CONN_CLIENT, *s.cfg.Key, ID, serverID)
|
||||
if err != nil {
|
||||
utils.CloseConn(&inConn)
|
||||
log.Printf("connection err: %s, retrying...", err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
i := 0
|
||||
for {
|
||||
i++
|
||||
outConn, err = utils.ConnectHost(localAddr, *s.cfg.Timeout)
|
||||
if err == nil || i == 3 {
|
||||
break
|
||||
} else {
|
||||
if i == 3 {
|
||||
log.Printf("connect to %s err: %s, retrying...", localAddr, err)
|
||||
time.Sleep(2 * time.Second)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
utils.CloseConn(&inConn)
|
||||
utils.CloseConn(&outConn)
|
||||
log.Printf("build connection error, err: %s", err)
|
||||
return
|
||||
}
|
||||
utils.IoBind(inConn, outConn, func(err interface{}) {
|
||||
log.Printf("conn %s released", ID)
|
||||
// s.cm.RemoveOne(*s.cfg.Key, ID)
|
||||
})
|
||||
// s.cm.Add(*s.cfg.Key, ID, &inConn)
|
||||
log.Printf("conn %s created", ID)
|
||||
}
|
||||
@ -1,362 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"proxy/utils"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type TunnelServer struct {
|
||||
cfg TunnelServerArgs
|
||||
udpChn chan UDPItem
|
||||
sc utils.ServerChannel
|
||||
}
|
||||
|
||||
type TunnelServerManager struct {
|
||||
cfg TunnelServerArgs
|
||||
udpChn chan UDPItem
|
||||
sc utils.ServerChannel
|
||||
serverID string
|
||||
// cm utils.ConnManager
|
||||
}
|
||||
|
||||
func NewTunnelServerManager() Service {
|
||||
return &TunnelServerManager{
|
||||
cfg: TunnelServerArgs{},
|
||||
udpChn: make(chan UDPItem, 50000),
|
||||
serverID: utils.Uniqueid(),
|
||||
// cm: utils.NewConnManager(),
|
||||
}
|
||||
}
|
||||
func (s *TunnelServerManager) Start(args interface{}) (err error) {
|
||||
s.cfg = args.(TunnelServerArgs)
|
||||
s.CheckArgs()
|
||||
if *s.cfg.Parent != "" {
|
||||
log.Printf("use tls parent %s", *s.cfg.Parent)
|
||||
} else {
|
||||
log.Fatalf("parent required")
|
||||
}
|
||||
|
||||
s.InitService()
|
||||
|
||||
log.Printf("server id: %s", s.serverID)
|
||||
//log.Printf("route:%v", *s.cfg.Route)
|
||||
for _, _info := range *s.cfg.Route {
|
||||
IsUDP := *s.cfg.IsUDP
|
||||
if strings.HasPrefix(_info, "udp://") {
|
||||
IsUDP = true
|
||||
}
|
||||
info := strings.TrimPrefix(_info, "udp://")
|
||||
info = strings.TrimPrefix(info, "tcp://")
|
||||
_routeInfo := strings.Split(info, "@")
|
||||
server := NewTunnelServer()
|
||||
local := _routeInfo[0]
|
||||
remote := _routeInfo[1]
|
||||
KEY := *s.cfg.Key
|
||||
if strings.HasPrefix(remote, "[") {
|
||||
KEY = remote[1:strings.LastIndex(remote, "]")]
|
||||
remote = remote[strings.LastIndex(remote, "]")+1:]
|
||||
}
|
||||
if strings.HasPrefix(remote, ":") {
|
||||
remote = fmt.Sprintf("127.0.0.1%s", remote)
|
||||
}
|
||||
err = server.Start(TunnelServerArgs{
|
||||
CertBytes: s.cfg.CertBytes,
|
||||
KeyBytes: s.cfg.KeyBytes,
|
||||
Parent: s.cfg.Parent,
|
||||
CertFile: s.cfg.CertFile,
|
||||
KeyFile: s.cfg.KeyFile,
|
||||
Local: &local,
|
||||
IsUDP: &IsUDP,
|
||||
Remote: &remote,
|
||||
Key: &KEY,
|
||||
Timeout: s.cfg.Timeout,
|
||||
Mgr: s,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *TunnelServerManager) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *TunnelServerManager) StopService() {
|
||||
// s.cm.RemoveAll()
|
||||
}
|
||||
func (s *TunnelServerManager) CheckArgs() {
|
||||
if *s.cfg.CertFile == "" || *s.cfg.KeyFile == "" {
|
||||
log.Fatalf("cert and key file required")
|
||||
}
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
}
|
||||
func (s *TunnelServerManager) InitService() {
|
||||
// s.InitHeartbeatDeamon()
|
||||
}
|
||||
|
||||
// func (s *TunnelServerManager) InitHeartbeatDeamon() {
|
||||
// log.Printf("heartbeat started")
|
||||
// go func() {
|
||||
// var heartbeatConn net.Conn
|
||||
// var ID string
|
||||
// for {
|
||||
// //close all connection
|
||||
// s.cm.Remove(ID)
|
||||
// utils.CloseConn(&heartbeatConn)
|
||||
// heartbeatConn, ID, err := s.GetOutConn(CONN_SERVER_HEARBEAT)
|
||||
// if err != nil {
|
||||
// log.Printf("heartbeat connection err: %s, retrying...", err)
|
||||
// time.Sleep(time.Second * 3)
|
||||
// utils.CloseConn(&heartbeatConn)
|
||||
// continue
|
||||
// }
|
||||
// log.Printf("heartbeat connection created,id:%s", ID)
|
||||
// writeDie := make(chan bool)
|
||||
// readDie := make(chan bool)
|
||||
// go func() {
|
||||
// for {
|
||||
// heartbeatConn.SetWriteDeadline(time.Now().Add(time.Second * 3))
|
||||
// _, err = heartbeatConn.Write([]byte{0x00})
|
||||
// heartbeatConn.SetWriteDeadline(time.Time{})
|
||||
// if err != nil {
|
||||
// log.Printf("heartbeat connection write err %s", err)
|
||||
// break
|
||||
// }
|
||||
// time.Sleep(time.Second * 3)
|
||||
// }
|
||||
// close(writeDie)
|
||||
// }()
|
||||
// go func() {
|
||||
// for {
|
||||
// signal := make([]byte, 1)
|
||||
// heartbeatConn.SetReadDeadline(time.Now().Add(time.Second * 6))
|
||||
// _, err := heartbeatConn.Read(signal)
|
||||
// heartbeatConn.SetReadDeadline(time.Time{})
|
||||
// if err != nil {
|
||||
// log.Printf("heartbeat connection read err: %s", err)
|
||||
// break
|
||||
// } else {
|
||||
// // log.Printf("heartbeat from bridge")
|
||||
// }
|
||||
// }
|
||||
// close(readDie)
|
||||
// }()
|
||||
// select {
|
||||
// case <-readDie:
|
||||
// case <-writeDie:
|
||||
// }
|
||||
// }
|
||||
// }()
|
||||
// }
|
||||
func (s *TunnelServerManager) GetOutConn(typ uint8) (outConn net.Conn, ID string, err error) {
|
||||
outConn, err = s.GetConn()
|
||||
if err != nil {
|
||||
log.Printf("connection err: %s", err)
|
||||
return
|
||||
}
|
||||
ID = s.serverID
|
||||
_, err = outConn.Write(utils.BuildPacket(typ, s.serverID))
|
||||
if err != nil {
|
||||
log.Printf("write connection data err: %s ,retrying...", err)
|
||||
utils.CloseConn(&outConn)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *TunnelServerManager) GetConn() (conn net.Conn, err error) {
|
||||
var _conn tls.Conn
|
||||
_conn, err = utils.TlsConnectHost(*s.cfg.Parent, *s.cfg.Timeout, s.cfg.CertBytes, s.cfg.KeyBytes)
|
||||
if err == nil {
|
||||
conn = net.Conn(&_conn)
|
||||
}
|
||||
return
|
||||
}
|
||||
func NewTunnelServer() Service {
|
||||
return &TunnelServer{
|
||||
cfg: TunnelServerArgs{},
|
||||
udpChn: make(chan UDPItem, 50000),
|
||||
}
|
||||
}
|
||||
|
||||
type UDPItem struct {
|
||||
packet *[]byte
|
||||
localAddr *net.UDPAddr
|
||||
srcAddr *net.UDPAddr
|
||||
}
|
||||
|
||||
func (s *TunnelServer) InitService() {
|
||||
s.UDPConnDeamon()
|
||||
}
|
||||
func (s *TunnelServer) CheckArgs() {
|
||||
if *s.cfg.Remote == "" {
|
||||
log.Fatalf("remote required")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TunnelServer) Start(args interface{}) (err error) {
|
||||
s.cfg = args.(TunnelServerArgs)
|
||||
s.CheckArgs()
|
||||
s.InitService()
|
||||
host, port, _ := net.SplitHostPort(*s.cfg.Local)
|
||||
p, _ := strconv.Atoi(port)
|
||||
s.sc = utils.NewServerChannel(host, p)
|
||||
if *s.cfg.IsUDP {
|
||||
err = s.sc.ListenUDP(func(packet []byte, localAddr, srcAddr *net.UDPAddr) {
|
||||
s.udpChn <- UDPItem{
|
||||
packet: &packet,
|
||||
localAddr: localAddr,
|
||||
srcAddr: srcAddr,
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
log.Printf("proxy on udp tunnel server mode %s", (*s.sc.UDPListener).LocalAddr())
|
||||
} else {
|
||||
err = s.sc.ListenTCP(func(inConn net.Conn) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Printf("tserver conn handler crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
var outConn net.Conn
|
||||
var ID string
|
||||
for {
|
||||
outConn, ID, err = s.GetOutConn(CONN_SERVER)
|
||||
if err != nil {
|
||||
utils.CloseConn(&outConn)
|
||||
log.Printf("connect to %s fail, err: %s, retrying...", *s.cfg.Parent, err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
utils.IoBind(inConn, outConn, func(err interface{}) {
|
||||
// s.cfg.Mgr.cm.RemoveOne(s.cfg.Mgr.serverID, ID)
|
||||
log.Printf("%s conn %s released", *s.cfg.Key, ID)
|
||||
})
|
||||
//add conn
|
||||
// s.cfg.Mgr.cm.Add(s.cfg.Mgr.serverID, ID, &inConn)
|
||||
log.Printf("%s conn %s created", *s.cfg.Key, ID)
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
log.Printf("proxy on tunnel server mode %s", (*s.sc.Listener).Addr())
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *TunnelServer) Clean() {
|
||||
|
||||
}
|
||||
func (s *TunnelServer) GetOutConn(typ uint8) (outConn net.Conn, ID string, err error) {
|
||||
outConn, err = s.GetConn()
|
||||
if err != nil {
|
||||
log.Printf("connection err: %s", err)
|
||||
return
|
||||
}
|
||||
remoteAddr := "tcp:" + *s.cfg.Remote
|
||||
if *s.cfg.IsUDP {
|
||||
remoteAddr = "udp:" + *s.cfg.Remote
|
||||
}
|
||||
ID = utils.Uniqueid()
|
||||
_, err = outConn.Write(utils.BuildPacket(typ, *s.cfg.Key, ID, remoteAddr, s.cfg.Mgr.serverID))
|
||||
if err != nil {
|
||||
log.Printf("write connection data err: %s ,retrying...", err)
|
||||
utils.CloseConn(&outConn)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *TunnelServer) GetConn() (conn net.Conn, err error) {
|
||||
var _conn tls.Conn
|
||||
_conn, err = utils.TlsConnectHost(*s.cfg.Parent, *s.cfg.Timeout, s.cfg.CertBytes, s.cfg.KeyBytes)
|
||||
if err == nil {
|
||||
conn = net.Conn(&_conn)
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *TunnelServer) UDPConnDeamon() {
|
||||
go func() {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Printf("udp conn deamon crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
var outConn net.Conn
|
||||
// var hb utils.HeartbeatReadWriter
|
||||
var ID string
|
||||
// var cmdChn = make(chan bool, 1000)
|
||||
var err error
|
||||
for {
|
||||
item := <-s.udpChn
|
||||
RETRY:
|
||||
if outConn == nil {
|
||||
for {
|
||||
outConn, ID, err = s.GetOutConn(CONN_SERVER)
|
||||
if err != nil {
|
||||
// cmdChn <- true
|
||||
outConn = nil
|
||||
utils.CloseConn(&outConn)
|
||||
log.Printf("connect to %s fail, err: %s, retrying...", *s.cfg.Parent, err)
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
} else {
|
||||
go func(outConn net.Conn, ID string) {
|
||||
go func() {
|
||||
// <-cmdChn
|
||||
// outConn.Close()
|
||||
}()
|
||||
for {
|
||||
srcAddrFromConn, body, err := utils.ReadUDPPacket(outConn)
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
log.Printf("UDP deamon connection %s exited", ID)
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("parse revecived udp packet fail, err: %s ,%v", err, body)
|
||||
continue
|
||||
}
|
||||
//log.Printf("udp packet revecived over parent , local:%s", srcAddrFromConn)
|
||||
_srcAddr := strings.Split(srcAddrFromConn, ":")
|
||||
if len(_srcAddr) != 2 {
|
||||
log.Printf("parse revecived udp packet fail, addr error : %s", srcAddrFromConn)
|
||||
continue
|
||||
}
|
||||
port, _ := strconv.Atoi(_srcAddr[1])
|
||||
dstAddr := &net.UDPAddr{IP: net.ParseIP(_srcAddr[0]), Port: port}
|
||||
_, err = s.sc.UDPListener.WriteToUDP(body, dstAddr)
|
||||
if err != nil {
|
||||
log.Printf("udp response to local %s fail,ERR:%s", srcAddrFromConn, err)
|
||||
continue
|
||||
}
|
||||
//log.Printf("udp response to local %s success , %v", srcAddrFromConn, body)
|
||||
}
|
||||
}(outConn, ID)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
outConn.SetWriteDeadline(time.Now().Add(time.Second))
|
||||
_, err = outConn.Write(utils.UDPPacket(item.srcAddr.String(), *item.packet))
|
||||
outConn.SetWriteDeadline(time.Time{})
|
||||
if err != nil {
|
||||
utils.CloseConn(&outConn)
|
||||
outConn = nil
|
||||
log.Printf("write udp packet to %s fail ,flush err:%s ,retrying...", *s.cfg.Parent, err)
|
||||
goto RETRY
|
||||
}
|
||||
//log.Printf("write packet %v", *item.packet)
|
||||
}
|
||||
}()
|
||||
}
|
||||
219
services/udp.go
@ -1,219 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"proxy/utils"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type UDP struct {
|
||||
p utils.ConcurrentMap
|
||||
outPool utils.OutPool
|
||||
cfg UDPArgs
|
||||
sc *utils.ServerChannel
|
||||
}
|
||||
|
||||
func NewUDP() Service {
|
||||
return &UDP{
|
||||
outPool: utils.OutPool{},
|
||||
p: utils.NewConcurrentMap(),
|
||||
}
|
||||
}
|
||||
func (s *UDP) CheckArgs() {
|
||||
if *s.cfg.Parent == "" {
|
||||
log.Fatalf("parent required for udp %s", *s.cfg.Local)
|
||||
}
|
||||
if *s.cfg.ParentType == "" {
|
||||
log.Fatalf("parent type unkown,use -T <tls|tcp>")
|
||||
}
|
||||
if *s.cfg.ParentType == "tls" {
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
}
|
||||
}
|
||||
func (s *UDP) InitService() {
|
||||
if *s.cfg.ParentType != TYPE_UDP {
|
||||
s.InitOutConnPool()
|
||||
}
|
||||
}
|
||||
func (s *UDP) StopService() {
|
||||
if s.outPool.Pool != nil {
|
||||
s.outPool.Pool.ReleaseAll()
|
||||
}
|
||||
}
|
||||
func (s *UDP) Start(args interface{}) (err error) {
|
||||
s.cfg = args.(UDPArgs)
|
||||
s.CheckArgs()
|
||||
log.Printf("use %s parent %s", *s.cfg.ParentType, *s.cfg.Parent)
|
||||
s.InitService()
|
||||
|
||||
host, port, _ := net.SplitHostPort(*s.cfg.Local)
|
||||
p, _ := strconv.Atoi(port)
|
||||
sc := utils.NewServerChannel(host, p)
|
||||
s.sc = &sc
|
||||
err = sc.ListenUDP(s.callback)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
log.Printf("udp proxy on %s", (*sc.UDPListener).LocalAddr())
|
||||
return
|
||||
}
|
||||
|
||||
func (s *UDP) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *UDP) callback(packet []byte, localAddr, srcAddr *net.UDPAddr) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Printf("udp conn handler crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
var err error
|
||||
switch *s.cfg.ParentType {
|
||||
case TYPE_TCP:
|
||||
fallthrough
|
||||
case TYPE_TLS:
|
||||
err = s.OutToTCP(packet, localAddr, srcAddr)
|
||||
case TYPE_UDP:
|
||||
err = s.OutToUDP(packet, localAddr, srcAddr)
|
||||
default:
|
||||
err = fmt.Errorf("unkown parent type %s", *s.cfg.ParentType)
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("connect to %s parent %s fail, ERR:%s", *s.cfg.ParentType, *s.cfg.Parent, err)
|
||||
}
|
||||
}
|
||||
func (s *UDP) GetConn(connKey string) (conn net.Conn, isNew bool, err error) {
|
||||
isNew = !s.p.Has(connKey)
|
||||
var _conn interface{}
|
||||
if isNew {
|
||||
_conn, err = s.outPool.Pool.Get()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
s.p.Set(connKey, _conn)
|
||||
} else {
|
||||
_conn, _ = s.p.Get(connKey)
|
||||
}
|
||||
conn = _conn.(net.Conn)
|
||||
return
|
||||
}
|
||||
func (s *UDP) OutToTCP(packet []byte, localAddr, srcAddr *net.UDPAddr) (err error) {
|
||||
numLocal := crc32.ChecksumIEEE([]byte(localAddr.String()))
|
||||
numSrc := crc32.ChecksumIEEE([]byte(srcAddr.String()))
|
||||
mod := uint32(*s.cfg.PoolSize)
|
||||
if mod == 0 {
|
||||
mod = 10
|
||||
}
|
||||
connKey := uint64((numLocal/10)*10 + numSrc%mod)
|
||||
conn, isNew, err := s.GetConn(fmt.Sprintf("%d", connKey))
|
||||
if err != nil {
|
||||
log.Printf("upd get conn to %s parent %s fail, ERR:%s", *s.cfg.ParentType, *s.cfg.Parent, err)
|
||||
return
|
||||
}
|
||||
if isNew {
|
||||
go func() {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Printf("udp conn handler out to tcp crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
log.Printf("conn %d created , local: %s", connKey, srcAddr.String())
|
||||
for {
|
||||
srcAddrFromConn, body, err := utils.ReadUDPPacket(bufio.NewReader(conn))
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
//log.Printf("connection %d released", connKey)
|
||||
s.p.Remove(fmt.Sprintf("%d", connKey))
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("parse revecived udp packet fail, err: %s", err)
|
||||
continue
|
||||
}
|
||||
//log.Printf("udp packet revecived over parent , local:%s", srcAddrFromConn)
|
||||
_srcAddr := strings.Split(srcAddrFromConn, ":")
|
||||
if len(_srcAddr) != 2 {
|
||||
log.Printf("parse revecived udp packet fail, addr error : %s", srcAddrFromConn)
|
||||
continue
|
||||
}
|
||||
port, _ := strconv.Atoi(_srcAddr[1])
|
||||
dstAddr := &net.UDPAddr{IP: net.ParseIP(_srcAddr[0]), Port: port}
|
||||
_, err = s.sc.UDPListener.WriteToUDP(body, dstAddr)
|
||||
if err != nil {
|
||||
log.Printf("udp response to local %s fail,ERR:%s", srcAddr, err)
|
||||
continue
|
||||
}
|
||||
//log.Printf("udp response to local %s success", srcAddr)
|
||||
}
|
||||
}()
|
||||
}
|
||||
//log.Printf("select conn %d , local: %s", connKey, srcAddr.String())
|
||||
writer := bufio.NewWriter(conn)
|
||||
//fmt.Println(conn, writer)
|
||||
writer.Write(utils.UDPPacket(srcAddr.String(), packet))
|
||||
err = writer.Flush()
|
||||
if err != nil {
|
||||
log.Printf("write udp packet to %s fail ,flush err:%s", *s.cfg.Parent, err)
|
||||
return
|
||||
}
|
||||
//log.Printf("write packet %v", packet)
|
||||
return
|
||||
}
|
||||
func (s *UDP) OutToUDP(packet []byte, localAddr, srcAddr *net.UDPAddr) (err error) {
|
||||
//log.Printf("udp packet revecived:%s,%v", srcAddr, packet)
|
||||
dstAddr, err := net.ResolveUDPAddr("udp", *s.cfg.Parent)
|
||||
if err != nil {
|
||||
log.Printf("resolve udp addr %s fail fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
clientSrcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||
conn, err := net.DialUDP("udp", clientSrcAddr, dstAddr)
|
||||
if err != nil {
|
||||
log.Printf("connect to udp %s fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = conn.Write(packet)
|
||||
if err != nil {
|
||||
log.Printf("send udp packet to %s fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
//log.Printf("send udp packet to %s success", dstAddr.String())
|
||||
buf := make([]byte, 512)
|
||||
len, _, err := conn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
log.Printf("read udp response from %s fail ,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
//log.Printf("revecived udp packet from %s , %v", dstAddr.String(), respBody)
|
||||
_, err = s.sc.UDPListener.WriteToUDP(buf[0:len], srcAddr)
|
||||
if err != nil {
|
||||
log.Printf("send udp response to cluster fail ,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
//log.Printf("send udp response to cluster success ,from:%s", dstAddr.String())
|
||||
return
|
||||
}
|
||||
func (s *UDP) InitOutConnPool() {
|
||||
if *s.cfg.ParentType == TYPE_TLS || *s.cfg.ParentType == TYPE_TCP {
|
||||
//dur int, isTLS bool, certBytes, keyBytes []byte,
|
||||
//parent string, timeout int, InitialCap int, MaxCap int
|
||||
s.outPool = utils.NewOutPool(
|
||||
*s.cfg.CheckParentInterval,
|
||||
*s.cfg.ParentType,
|
||||
"", "",
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes,
|
||||
*s.cfg.Parent,
|
||||
*s.cfg.Timeout,
|
||||
*s.cfg.PoolSize,
|
||||
*s.cfg.PoolSize*2,
|
||||
)
|
||||
}
|
||||
}
|
||||
261
services/udp/udp.go
Normal file
@ -0,0 +1,261 @@
|
||||
package udp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
logger "log"
|
||||
"net"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/snail007/goproxy/services"
|
||||
"github.com/snail007/goproxy/services/kcpcfg"
|
||||
"github.com/snail007/goproxy/utils"
|
||||
)
|
||||
|
||||
type UDPArgs struct {
|
||||
Parent *string
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CertBytes []byte
|
||||
KeyBytes []byte
|
||||
Local *string
|
||||
ParentType *string
|
||||
Timeout *int
|
||||
CheckParentInterval *int
|
||||
}
|
||||
type UDP struct {
|
||||
p utils.ConcurrentMap
|
||||
outPool utils.OutConn
|
||||
cfg UDPArgs
|
||||
sc *utils.ServerChannel
|
||||
isStop bool
|
||||
log *logger.Logger
|
||||
}
|
||||
|
||||
func NewUDP() services.Service {
|
||||
return &UDP{
|
||||
outPool: utils.OutConn{},
|
||||
p: utils.NewConcurrentMap(),
|
||||
isStop: false,
|
||||
}
|
||||
}
|
||||
func (s *UDP) CheckArgs() (err error) {
|
||||
if *s.cfg.Parent == "" {
|
||||
err = fmt.Errorf("parent required for udp %s", *s.cfg.Local)
|
||||
return
|
||||
}
|
||||
if *s.cfg.ParentType == "" {
|
||||
err = fmt.Errorf("parent type unkown,use -T <tls|tcp>")
|
||||
return
|
||||
}
|
||||
if *s.cfg.ParentType == "tls" {
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes, err = utils.TlsBytes(*s.cfg.CertFile, *s.cfg.KeyFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *UDP) InitService() (err error) {
|
||||
if *s.cfg.ParentType != "udp" {
|
||||
s.InitOutConnPool()
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *UDP) StopService() {
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
s.log.Printf("stop udp service crashed,%s", e)
|
||||
} else {
|
||||
s.log.Printf("service udp stopped")
|
||||
}
|
||||
}()
|
||||
s.isStop = true
|
||||
if s.sc.Listener != nil && *s.sc.Listener != nil {
|
||||
(*s.sc.Listener).Close()
|
||||
}
|
||||
if s.sc.UDPListener != nil {
|
||||
(*s.sc.UDPListener).Close()
|
||||
}
|
||||
}
|
||||
func (s *UDP) Start(args interface{}, log *logger.Logger) (err error) {
|
||||
s.log = log
|
||||
s.cfg = args.(UDPArgs)
|
||||
if err = s.CheckArgs(); err != nil {
|
||||
return
|
||||
}
|
||||
s.log.Printf("use %s parent %s", *s.cfg.ParentType, *s.cfg.Parent)
|
||||
if err = s.InitService(); err != nil {
|
||||
return
|
||||
}
|
||||
host, port, _ := net.SplitHostPort(*s.cfg.Local)
|
||||
p, _ := strconv.Atoi(port)
|
||||
sc := utils.NewServerChannel(host, p, s.log)
|
||||
s.sc = &sc
|
||||
err = sc.ListenUDP(s.callback)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.log.Printf("udp proxy on %s", (*sc.UDPListener).LocalAddr())
|
||||
return
|
||||
}
|
||||
|
||||
func (s *UDP) Clean() {
|
||||
s.StopService()
|
||||
}
|
||||
func (s *UDP) callback(packet []byte, localAddr, srcAddr *net.UDPAddr) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
s.log.Printf("udp conn handler crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
var err error
|
||||
switch *s.cfg.ParentType {
|
||||
case "tcp":
|
||||
fallthrough
|
||||
case "tls":
|
||||
err = s.OutToTCP(packet, localAddr, srcAddr)
|
||||
case "udp":
|
||||
err = s.OutToUDP(packet, localAddr, srcAddr)
|
||||
default:
|
||||
err = fmt.Errorf("unkown parent type %s", *s.cfg.ParentType)
|
||||
}
|
||||
if err != nil {
|
||||
s.log.Printf("connect to %s parent %s fail, ERR:%s", *s.cfg.ParentType, *s.cfg.Parent, err)
|
||||
}
|
||||
}
|
||||
func (s *UDP) GetConn(connKey string) (conn net.Conn, isNew bool, err error) {
|
||||
isNew = !s.p.Has(connKey)
|
||||
var _conn interface{}
|
||||
if isNew {
|
||||
_conn, err = s.outPool.Get()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
s.p.Set(connKey, _conn)
|
||||
} else {
|
||||
_conn, _ = s.p.Get(connKey)
|
||||
}
|
||||
conn = _conn.(net.Conn)
|
||||
return
|
||||
}
|
||||
func (s *UDP) OutToTCP(packet []byte, localAddr, srcAddr *net.UDPAddr) (err error) {
|
||||
numLocal := crc32.ChecksumIEEE([]byte(localAddr.String()))
|
||||
numSrc := crc32.ChecksumIEEE([]byte(srcAddr.String()))
|
||||
mod := uint32(10)
|
||||
if mod == 0 {
|
||||
mod = 10
|
||||
}
|
||||
connKey := uint64((numLocal/10)*10 + numSrc%mod)
|
||||
conn, isNew, err := s.GetConn(fmt.Sprintf("%d", connKey))
|
||||
if err != nil {
|
||||
s.log.Printf("upd get conn to %s parent %s fail, ERR:%s", *s.cfg.ParentType, *s.cfg.Parent, err)
|
||||
return
|
||||
}
|
||||
if isNew {
|
||||
go func() {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
s.log.Printf("udp conn handler out to tcp crashed with err : %s \nstack: %s", err, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
s.log.Printf("conn %d created , local: %s", connKey, srcAddr.String())
|
||||
for {
|
||||
if s.isStop {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
srcAddrFromConn, body, err := utils.ReadUDPPacket(bufio.NewReader(conn))
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
//s.log.Printf("connection %d released", connKey)
|
||||
s.p.Remove(fmt.Sprintf("%d", connKey))
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
s.log.Printf("parse revecived udp packet fail, err: %s", err)
|
||||
continue
|
||||
}
|
||||
//s.log.Printf("udp packet revecived over parent , local:%s", srcAddrFromConn)
|
||||
_srcAddr := strings.Split(srcAddrFromConn, ":")
|
||||
if len(_srcAddr) != 2 {
|
||||
s.log.Printf("parse revecived udp packet fail, addr error : %s", srcAddrFromConn)
|
||||
continue
|
||||
}
|
||||
port, _ := strconv.Atoi(_srcAddr[1])
|
||||
dstAddr := &net.UDPAddr{IP: net.ParseIP(_srcAddr[0]), Port: port}
|
||||
_, err = s.sc.UDPListener.WriteToUDP(body, dstAddr)
|
||||
if err != nil {
|
||||
s.log.Printf("udp response to local %s fail,ERR:%s", srcAddr, err)
|
||||
continue
|
||||
}
|
||||
//s.log.Printf("udp response to local %s success", srcAddr)
|
||||
}
|
||||
}()
|
||||
}
|
||||
//s.log.Printf("select conn %d , local: %s", connKey, srcAddr.String())
|
||||
writer := bufio.NewWriter(conn)
|
||||
//fmt.Println(conn, writer)
|
||||
writer.Write(utils.UDPPacket(srcAddr.String(), packet))
|
||||
err = writer.Flush()
|
||||
if err != nil {
|
||||
s.log.Printf("write udp packet to %s fail ,flush err:%s", *s.cfg.Parent, err)
|
||||
return
|
||||
}
|
||||
//s.log.Printf("write packet %v", packet)
|
||||
return
|
||||
}
|
||||
func (s *UDP) OutToUDP(packet []byte, localAddr, srcAddr *net.UDPAddr) (err error) {
|
||||
//s.log.Printf("udp packet revecived:%s,%v", srcAddr, packet)
|
||||
dstAddr, err := net.ResolveUDPAddr("udp", *s.cfg.Parent)
|
||||
if err != nil {
|
||||
s.log.Printf("resolve udp addr %s fail fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
clientSrcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||
conn, err := net.DialUDP("udp", clientSrcAddr, dstAddr)
|
||||
if err != nil {
|
||||
s.log.Printf("connect to udp %s fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(*s.cfg.Timeout)))
|
||||
_, err = conn.Write(packet)
|
||||
if err != nil {
|
||||
s.log.Printf("send udp packet to %s fail,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
//s.log.Printf("send udp packet to %s success", dstAddr.String())
|
||||
buf := make([]byte, 512)
|
||||
len, _, err := conn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
s.log.Printf("read udp response from %s fail ,ERR:%s", dstAddr.String(), err)
|
||||
return
|
||||
}
|
||||
//s.log.Printf("revecived udp packet from %s , %v", dstAddr.String(), respBody)
|
||||
_, err = s.sc.UDPListener.WriteToUDP(buf[0:len], srcAddr)
|
||||
if err != nil {
|
||||
s.log.Printf("send udp response to cluster fail ,ERR:%s", err)
|
||||
return
|
||||
}
|
||||
//s.log.Printf("send udp response to cluster success ,from:%s", dstAddr.String())
|
||||
return
|
||||
}
|
||||
func (s *UDP) InitOutConnPool() {
|
||||
if *s.cfg.ParentType == "tls" || *s.cfg.ParentType == "tcp" {
|
||||
//dur int, isTLS bool, certBytes, keyBytes []byte,
|
||||
//parent string, timeout int, InitialCap int, MaxCap int
|
||||
s.outPool = utils.NewOutConn(
|
||||
*s.cfg.CheckParentInterval,
|
||||
*s.cfg.ParentType,
|
||||
kcpcfg.KCPConfigArgs{},
|
||||
s.cfg.CertBytes, s.cfg.KeyBytes, nil,
|
||||
*s.cfg.Parent,
|
||||
*s.cfg.Timeout,
|
||||
)
|
||||
}
|
||||
}
|
||||
199
utils/cert/cert.go
Normal file
@ -0,0 +1,199 @@
|
||||
package cert
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
cryptorand "crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"io/ioutil"
|
||||
"math/big"
|
||||
"math/rand"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func CreateSignCertToFile(rootCa *x509.Certificate, rootKey *rsa.PrivateKey, domainOrIP string, expireDays int, name string) (err error) {
|
||||
cert, key, err := CreateSignCert(rootCa, rootKey, domainOrIP, expireDays)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = ioutil.WriteFile(name+".crt", cert, 0755)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = ioutil.WriteFile(name+".key", key, 0755)
|
||||
return
|
||||
}
|
||||
func CreateSignCert(rootCa *x509.Certificate, rootKey *rsa.PrivateKey, domainOrIP string, expireDays int) (certBytes []byte, keyBytes []byte, err error) {
|
||||
cer := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(rand.Int63()), //证书序列号
|
||||
Subject: pkix.Name{
|
||||
Country: []string{getCountry()},
|
||||
Organization: []string{domainOrIP},
|
||||
OrganizationalUnit: []string{domainOrIP},
|
||||
CommonName: domainOrIP,
|
||||
},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(time.Hour * 24 * time.Duration(expireDays)),
|
||||
BasicConstraintsValid: true,
|
||||
IsCA: false,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
|
||||
//KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageDataEncipherment,
|
||||
EmailAddresses: []string{},
|
||||
IPAddresses: []net.IP{},
|
||||
}
|
||||
if ip := net.ParseIP(domainOrIP); ip != nil {
|
||||
cer.IPAddresses = append(cer.IPAddresses, ip)
|
||||
} else {
|
||||
cer.DNSNames = append(cer.DNSNames, domainOrIP)
|
||||
}
|
||||
|
||||
// cer.IPAddresses = append(cer.IPAddresses, alternateIPs...)
|
||||
// cer.DNSNames = append(cer.DNSNames, alternateDNS...)
|
||||
|
||||
//生成公钥私钥对
|
||||
priKey, err := rsa.GenerateKey(cryptorand.Reader, 2048)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
certBytes, err = x509.CreateCertificate(cryptorand.Reader, cer, rootCa, &priKey.PublicKey, rootKey)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
//编码证书文件和私钥文件
|
||||
caPem := &pem.Block{
|
||||
Type: "CERTIFICATE",
|
||||
Bytes: certBytes,
|
||||
}
|
||||
certBytes = pem.EncodeToMemory(caPem)
|
||||
|
||||
buf := x509.MarshalPKCS1PrivateKey(priKey)
|
||||
keyPem := &pem.Block{
|
||||
Type: "RSA PRIVATE KEY",
|
||||
Bytes: buf,
|
||||
}
|
||||
keyBytes = pem.EncodeToMemory(keyPem)
|
||||
return
|
||||
}
|
||||
func CreateCaToFile(name, domainOrIP string, expireDays int) (err error) {
|
||||
ca, key, err := CreateCa(domainOrIP, expireDays)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = ioutil.WriteFile(name+".crt", ca, 0755)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = ioutil.WriteFile(name+".key", key, 0755)
|
||||
return
|
||||
}
|
||||
func CreateCa(organization string, expireDays int) (certBytes []byte, keyBytes []byte, err error) {
|
||||
priv, err := rsa.GenerateKey(cryptorand.Reader, 2048)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
template := x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{
|
||||
CommonName: organization,
|
||||
Organization: []string{organization},
|
||||
OrganizationalUnit: []string{organization},
|
||||
Country: []string{getCountry()},
|
||||
},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(time.Hour * 24 * time.Duration(expireDays)),
|
||||
|
||||
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
|
||||
BasicConstraintsValid: true,
|
||||
IsCA: true,
|
||||
}
|
||||
|
||||
derBytes, err := x509.CreateCertificate(cryptorand.Reader, &template, &template, &priv.PublicKey, priv)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// Generate cert
|
||||
certBuffer := bytes.Buffer{}
|
||||
if err := pem.Encode(&certBuffer, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// Generate key
|
||||
keyBuffer := bytes.Buffer{}
|
||||
if err := pem.Encode(&keyBuffer, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return certBuffer.Bytes(), keyBuffer.Bytes(), nil
|
||||
}
|
||||
func ParseCertAndKeyBytes(certPemFileByes, keyFileBytes []byte) (cert *x509.Certificate, privateKey *rsa.PrivateKey, err error) {
|
||||
//解析根证书
|
||||
cert, err = ParseCertBytes(certPemFileByes)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
//解析私钥
|
||||
privateKey, err = ParseKeyBytes(keyFileBytes)
|
||||
return
|
||||
}
|
||||
func ParseCertAndKey(certPemFile, keyFile string) (cert *x509.Certificate, privateKey *rsa.PrivateKey, err error) {
|
||||
//解析根证书
|
||||
cert, err = ParseCert(certPemFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
//解析私钥
|
||||
privateKey, err = ParseKey(keyFile)
|
||||
return
|
||||
}
|
||||
func ParseCert(certPemFile string) (cert *x509.Certificate, err error) {
|
||||
//解析证书
|
||||
certFile_, err := ioutil.ReadFile(certPemFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cert, err = ParseCertBytes(certFile_)
|
||||
return
|
||||
}
|
||||
func ParseKey(keyFile string) (key *rsa.PrivateKey, err error) {
|
||||
//解析证书
|
||||
keyFile_, err := ioutil.ReadFile(keyFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
key, err = ParseKeyBytes(keyFile_)
|
||||
return
|
||||
}
|
||||
func ParseCertBytes(certPemFileBytes []byte) (cert *x509.Certificate, err error) {
|
||||
caBlock, _ := pem.Decode(certPemFileBytes)
|
||||
cert, err = x509.ParseCertificate(caBlock.Bytes)
|
||||
return
|
||||
}
|
||||
func ParseKeyBytes(keyFileBytes []byte) (praKey *rsa.PrivateKey, err error) {
|
||||
keyBlock, _ := pem.Decode(keyFileBytes)
|
||||
praKey, err = x509.ParsePKCS1PrivateKey(keyBlock.Bytes)
|
||||
return
|
||||
}
|
||||
func getCountry() string {
|
||||
CList := []string{"AD", "AE", "AF", "AG", "AI", "AL", "AM", "AO", "AR", "AT", "AU", "AZ", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BR", "BS", "BW", "BY", "BZ", "CA", "CF", "CG", "CH", "CK", "CL", "CM", "CN", "CO", "CR", "CS", "CU", "CY", "CZ", "DE", "DJ", "DK", "DO", "DZ", "EC", "EE", "EG", "ES", "ET", "FI", "FJ", "FR", "GA", "GB", "GD", "GE", "GF", "GH", "GI", "GM", "GN", "GR", "GT", "GU", "GY", "HK", "HN", "HT", "HU", "ID", "IE", "IL", "IN", "IQ", "IR", "IS", "IT", "JM", "JO", "JP", "KE", "KG", "KH", "KP", "KR", "KT", "KW", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "MG", "ML", "MM", "MN", "MO", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NE", "NG", "NI", "NL", "NO", "NP", "NR", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PR", "PT", "PY", "QA", "RO", "RU", "SA", "SB", "SC", "SD", "SE", "SG", "SI", "SK", "SL", "SM", "SN", "SO", "SR", "ST", "SV", "SY", "SZ", "TD", "TG", "TH", "TJ", "TM", "TN", "TO", "TR", "TT", "TW", "TZ", "UA", "UG", "US", "UY", "UZ", "VC", "VE", "VN", "YE", "YU", "ZA", "ZM", "ZR", "ZW"}
|
||||
return CList[int(randInt(4))%len(CList)]
|
||||
}
|
||||
func randInt(strLen int) int64 {
|
||||
codes := "123456789"
|
||||
codeLen := len(codes)
|
||||
data := make([]byte, strLen)
|
||||
rand.Seed(time.Now().UnixNano() + rand.Int63() + rand.Int63() + rand.Int63() + rand.Int63())
|
||||
for i := 0; i < strLen; i++ {
|
||||
idx := rand.Intn(codeLen)
|
||||
data[i] = byte(codes[idx])
|
||||
}
|
||||
i, _ := strconv.ParseInt(string(data), 10, 64)
|
||||
return i
|
||||
}
|
||||
71
utils/cert/cert_test.go
Normal file
@ -0,0 +1,71 @@
|
||||
package cert
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCaGen(t *testing.T) {
|
||||
err := CreateCaToFile("ca", "test", 365)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
ca, key, err := ParseCertAndKey("ca.crt", "ca.key")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
if ca.Subject.Organization[0] != "test" {
|
||||
t.Fatalf("Organization %s not match test", ca.Subject.Organization[0])
|
||||
return
|
||||
}
|
||||
err = key.Validate()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
os.Remove("ca.crt")
|
||||
os.Remove("ca.key")
|
||||
|
||||
}
|
||||
func TestSign(t *testing.T) {
|
||||
err := CreateCaToFile("ca", "test", 365)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
ca, key, err := ParseCertAndKey("ca.crt", "ca.key")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
err = CreateCaToFile("ca", "test", 365)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
err = CreateSignCertToFile(ca, key, "server.com", 365, "server")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
servercrt, serverkey, err := ParseCertAndKey("server.crt", "server.key")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
if servercrt.Subject.CommonName != "server.com" {
|
||||
t.Fatalf("CommonName %s not match server.com", ca.Subject.CommonName)
|
||||
return
|
||||
}
|
||||
err = serverkey.Validate()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
os.Remove("ca.crt")
|
||||
os.Remove("ca.key")
|
||||
os.Remove("server.crt")
|
||||
os.Remove("server.key")
|
||||
}
|
||||
95
utils/conncrypt/conncrypt.go
Normal file
@ -0,0 +1,95 @@
|
||||
package conncrypt
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/sha256"
|
||||
"hash"
|
||||
"io"
|
||||
"net"
|
||||
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
)
|
||||
|
||||
//Confg defaults
|
||||
const DefaultIterations = 1024
|
||||
const DefaultKeySize = 24 //256bits
|
||||
var DefaultHashFunc = sha256.New
|
||||
var DefaultSalt = []byte(`
|
||||
(;QUHj.BQ?RXzYSO]ifkXp/G!kFmWyXyEV6Nt!d|@bo+N$L9+<d$|g6e26T}
|
||||
Ao<:>SOd,6acYKY_ec+(x"R";\'4&fTAVu92GVA-wxBptOTM^2,iP5%)wnhW
|
||||
hwk=]Snsgymt!3gbP2pe=J//}1a?lp9ej=&TB!C_V(cT2?z8wyoL_-13fd[]
|
||||
`) //salt must be predefined in order to derive the same key
|
||||
|
||||
//Config stores the PBKDF2 key generation parameters
|
||||
type Config struct {
|
||||
Password string
|
||||
Salt []byte
|
||||
Iterations int
|
||||
KeySize int
|
||||
HashFunc func() hash.Hash
|
||||
}
|
||||
|
||||
//New creates an AES encrypted net.Conn by generating
|
||||
//a key using PBKDF2 with the provided configuration
|
||||
func New(conn net.Conn, c *Config) net.Conn {
|
||||
//set defaults
|
||||
if len(c.Salt) == 0 {
|
||||
c.Salt = DefaultSalt
|
||||
}
|
||||
if c.Iterations == 0 {
|
||||
c.Iterations = DefaultIterations
|
||||
}
|
||||
if c.KeySize != 16 && c.KeySize != 24 && c.KeySize != 32 {
|
||||
c.KeySize = DefaultKeySize
|
||||
}
|
||||
if c.HashFunc == nil {
|
||||
c.HashFunc = DefaultHashFunc
|
||||
}
|
||||
|
||||
//generate key
|
||||
key := pbkdf2.Key([]byte(c.Password), c.Salt, c.Iterations, c.KeySize, c.HashFunc)
|
||||
|
||||
// could use scrypt, but it's a bit slow...
|
||||
// dk, err := scrypt.Key([]byte(c.Password), c.Salt, 16384, 8, 1, 32)
|
||||
|
||||
//key will be always be the correct size so this will never error
|
||||
conn, _ = NewFromKey(conn, key)
|
||||
return conn
|
||||
}
|
||||
|
||||
//NewFromKey creates an AES encrypted net.Conn using the provided key
|
||||
func NewFromKey(conn net.Conn, key []byte) (net.Conn, error) {
|
||||
block, err := aes.NewCipher([]byte(key))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
//hash(key) -> read IV
|
||||
riv := DefaultHashFunc().Sum(key)
|
||||
rstream := cipher.NewCFBDecrypter(block, riv[:aes.BlockSize])
|
||||
reader := &cipher.StreamReader{S: rstream, R: conn}
|
||||
//hash(read IV) -> write IV
|
||||
wiv := DefaultHashFunc().Sum(riv)
|
||||
wstream := cipher.NewCFBEncrypter(block, wiv[:aes.BlockSize])
|
||||
writer := &cipher.StreamWriter{S: wstream, W: conn}
|
||||
|
||||
return &cryptoConn{
|
||||
Conn: conn,
|
||||
r: reader,
|
||||
w: writer,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type cryptoConn struct {
|
||||
net.Conn
|
||||
r io.Reader
|
||||
w io.Writer
|
||||
}
|
||||
|
||||
//replace read and write methods
|
||||
func (c *cryptoConn) Read(p []byte) (int, error) {
|
||||
return c.r.Read(p)
|
||||
}
|
||||
func (c *cryptoConn) Write(p []byte) (int, error) {
|
||||
return c.w.Write(p)
|
||||
}
|
||||
@ -7,27 +7,32 @@ import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/binary"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
logger "log"
|
||||
"math/rand"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
|
||||
"github.com/snail007/goproxy/services/kcpcfg"
|
||||
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
|
||||
"proxy/utils/id"
|
||||
"context"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/snail007/goproxy/utils/id"
|
||||
|
||||
kcp "github.com/xtaci/kcp-go"
|
||||
)
|
||||
|
||||
func IoBind(dst io.ReadWriteCloser, src io.ReadWriteCloser, fn func(err interface{})) {
|
||||
func IoBind(dst io.ReadWriteCloser, src io.ReadWriteCloser, fn func(err interface{}), log *logger.Logger) {
|
||||
go func() {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
@ -65,11 +70,14 @@ func IoBind(dst io.ReadWriteCloser, src io.ReadWriteCloser, fn func(err interfac
|
||||
}
|
||||
src.Close()
|
||||
dst.Close()
|
||||
fn(err)
|
||||
if fn != nil {
|
||||
fn(err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
func ioCopy(dst io.ReadWriter, src io.ReadWriter) (err error) {
|
||||
buf := make([]byte, 32*1024)
|
||||
buf := LeakyBuffer.Get()
|
||||
defer LeakyBuffer.Put(buf)
|
||||
n := 0
|
||||
for {
|
||||
n, err = src.Read(buf)
|
||||
@ -83,14 +91,14 @@ func ioCopy(dst io.ReadWriter, src io.ReadWriter) (err error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
func TlsConnectHost(host string, timeout int, certBytes, keyBytes []byte) (conn tls.Conn, err error) {
|
||||
func TlsConnectHost(host string, timeout int, certBytes, keyBytes, caCertBytes []byte) (conn tls.Conn, err error) {
|
||||
h := strings.Split(host, ":")
|
||||
port, _ := strconv.Atoi(h[1])
|
||||
return TlsConnect(h[0], port, timeout, certBytes, keyBytes)
|
||||
return TlsConnect(h[0], port, timeout, certBytes, keyBytes, caCertBytes)
|
||||
}
|
||||
|
||||
func TlsConnect(host string, port, timeout int, certBytes, keyBytes []byte) (conn tls.Conn, err error) {
|
||||
conf, err := getRequestTlsConfig(certBytes, keyBytes)
|
||||
func TlsConnect(host string, port, timeout int, certBytes, keyBytes, caCertBytes []byte) (conn tls.Conn, err error) {
|
||||
conf, err := getRequestTlsConfig(certBytes, keyBytes, caCertBytes)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@ -100,22 +108,51 @@ func TlsConnect(host string, port, timeout int, certBytes, keyBytes []byte) (con
|
||||
}
|
||||
return *tls.Client(_conn, conf), err
|
||||
}
|
||||
func getRequestTlsConfig(certBytes, keyBytes []byte) (conf *tls.Config, err error) {
|
||||
func TlsConfig(certBytes, keyBytes, caCertBytes []byte) (conf *tls.Config, err error) {
|
||||
return getRequestTlsConfig(certBytes, keyBytes, caCertBytes)
|
||||
}
|
||||
func getRequestTlsConfig(certBytes, keyBytes, caCertBytes []byte) (conf *tls.Config, err error) {
|
||||
|
||||
var cert tls.Certificate
|
||||
cert, err = tls.X509KeyPair(certBytes, keyBytes)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
serverCertPool := x509.NewCertPool()
|
||||
ok := serverCertPool.AppendCertsFromPEM(certBytes)
|
||||
caBytes := certBytes
|
||||
if caCertBytes != nil {
|
||||
caBytes = caCertBytes
|
||||
}
|
||||
ok := serverCertPool.AppendCertsFromPEM(caBytes)
|
||||
if !ok {
|
||||
err = errors.New("failed to parse root certificate")
|
||||
}
|
||||
block, _ := pem.Decode(caBytes)
|
||||
if block == nil {
|
||||
panic("failed to parse certificate PEM")
|
||||
}
|
||||
x509Cert, _ := x509.ParseCertificate(block.Bytes)
|
||||
if x509Cert == nil {
|
||||
panic("failed to parse block")
|
||||
}
|
||||
conf = &tls.Config{
|
||||
RootCAs: serverCertPool,
|
||||
Certificates: []tls.Certificate{cert},
|
||||
ServerName: "proxy",
|
||||
InsecureSkipVerify: false,
|
||||
InsecureSkipVerify: true,
|
||||
ServerName: x509Cert.Subject.CommonName,
|
||||
VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
||||
opts := x509.VerifyOptions{
|
||||
Roots: serverCertPool,
|
||||
}
|
||||
for _, rawCert := range rawCerts {
|
||||
cert, _ := x509.ParseCertificate(rawCert)
|
||||
_, err := cert.Verify(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
return
|
||||
}
|
||||
@ -124,40 +161,23 @@ func ConnectHost(hostAndPort string, timeout int) (conn net.Conn, err error) {
|
||||
conn, err = net.DialTimeout("tcp", hostAndPort, time.Duration(timeout)*time.Millisecond)
|
||||
return
|
||||
}
|
||||
func ConnectKCPHost(hostAndPort, method, key string) (conn net.Conn, err error) {
|
||||
kcpconn, err := kcp.DialWithOptions(hostAndPort, GetKCPBlock(method, key), 10, 3)
|
||||
func ConnectKCPHost(hostAndPort string, config kcpcfg.KCPConfigArgs) (conn net.Conn, err error) {
|
||||
kcpconn, err := kcp.DialWithOptions(hostAndPort, config.Block, *config.DataShard, *config.ParityShard)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
kcpconn.SetNoDelay(1, 10, 2, 1)
|
||||
kcpconn.SetWindowSize(1024, 1024)
|
||||
kcpconn.SetMtu(1400)
|
||||
kcpconn.SetACKNoDelay(false)
|
||||
return kcpconn, err
|
||||
}
|
||||
func ListenTls(ip string, port int, certBytes, keyBytes []byte) (ln *net.Listener, err error) {
|
||||
var cert tls.Certificate
|
||||
cert, err = tls.X509KeyPair(certBytes, keyBytes)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
clientCertPool := x509.NewCertPool()
|
||||
ok := clientCertPool.AppendCertsFromPEM(certBytes)
|
||||
if !ok {
|
||||
err = errors.New("failed to parse root certificate")
|
||||
}
|
||||
config := &tls.Config{
|
||||
ClientCAs: clientCertPool,
|
||||
ServerName: "proxy",
|
||||
Certificates: []tls.Certificate{cert},
|
||||
ClientAuth: tls.RequireAndVerifyClientCert,
|
||||
}
|
||||
_ln, err := tls.Listen("tcp", fmt.Sprintf("%s:%d", ip, port), config)
|
||||
if err == nil {
|
||||
ln = &_ln
|
||||
}
|
||||
return
|
||||
kcpconn.SetStreamMode(true)
|
||||
kcpconn.SetWriteDelay(true)
|
||||
kcpconn.SetNoDelay(*config.NoDelay, *config.Interval, *config.Resend, *config.NoCongestion)
|
||||
kcpconn.SetMtu(*config.MTU)
|
||||
kcpconn.SetWindowSize(*config.SndWnd, *config.RcvWnd)
|
||||
kcpconn.SetACKNoDelay(*config.AckNodelay)
|
||||
if *config.NoComp {
|
||||
return kcpconn, err
|
||||
}
|
||||
return NewCompStream(kcpconn), err
|
||||
}
|
||||
|
||||
func PathExists(_path string) bool {
|
||||
_, err := os.Stat(_path)
|
||||
if err != nil && os.IsNotExist(err) {
|
||||
@ -192,25 +212,13 @@ func CloseConn(conn *net.Conn) {
|
||||
(*conn).Close()
|
||||
}
|
||||
}
|
||||
func Keygen() (err error) {
|
||||
cmd := exec.Command("sh", "-c", "openssl genrsa -out proxy.key 2048")
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
log.Printf("err:%s", err)
|
||||
return
|
||||
}
|
||||
fmt.Println(string(out))
|
||||
cmd = exec.Command("sh", "-c", `openssl req -new -key proxy.key -x509 -days 3650 -out proxy.crt -subj /C=CN/ST=BJ/O="Localhost Ltd"/CN=proxy`)
|
||||
out, err = cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
log.Printf("err:%s", err)
|
||||
return
|
||||
}
|
||||
fmt.Println(string(out))
|
||||
return
|
||||
}
|
||||
func GetAllInterfaceAddr() ([]net.IP, error) {
|
||||
|
||||
var allInterfaceAddrCache []net.IP
|
||||
|
||||
func GetAllInterfaceAddr() ([]net.IP, error) {
|
||||
if allInterfaceAddrCache != nil {
|
||||
return allInterfaceAddrCache, nil
|
||||
}
|
||||
ifaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -251,6 +259,7 @@ func GetAllInterfaceAddr() ([]net.IP, error) {
|
||||
return nil, fmt.Errorf("no address Found, net.InterfaceAddrs: %v", addresses)
|
||||
}
|
||||
//only need first
|
||||
allInterfaceAddrCache = addresses
|
||||
return addresses, nil
|
||||
}
|
||||
func UDPPacket(srcAddr string, packet []byte) []byte {
|
||||
@ -306,6 +315,29 @@ func Uniqueid() string {
|
||||
// s := fmt.Sprintf("%d", src.Int63())
|
||||
// return s[len(s)-5:len(s)-1] + fmt.Sprintf("%d", uint64(time.Now().UnixNano()))[8:]
|
||||
}
|
||||
func RandString(strlen int) string {
|
||||
codes := "QWERTYUIOPLKJHGFDSAZXCVBNMabcdefghijklmnopqrstuvwxyz0123456789"
|
||||
codeLen := len(codes)
|
||||
data := make([]byte, strlen)
|
||||
rand.Seed(time.Now().UnixNano() + rand.Int63() + rand.Int63() + rand.Int63() + rand.Int63())
|
||||
for i := 0; i < strlen; i++ {
|
||||
idx := rand.Intn(codeLen)
|
||||
data[i] = byte(codes[idx])
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
func RandInt(strLen int) int64 {
|
||||
codes := "123456789"
|
||||
codeLen := len(codes)
|
||||
data := make([]byte, strLen)
|
||||
rand.Seed(time.Now().UnixNano() + rand.Int63() + rand.Int63() + rand.Int63() + rand.Int63())
|
||||
for i := 0; i < strLen; i++ {
|
||||
idx := rand.Intn(codeLen)
|
||||
data[i] = byte(codes[idx])
|
||||
}
|
||||
i, _ := strconv.ParseInt(string(data), 10, 64)
|
||||
return i
|
||||
}
|
||||
func ReadData(r io.Reader) (data string, err error) {
|
||||
var len uint16
|
||||
err = binary.Read(r, binary.LittleEndian, &len)
|
||||
@ -386,15 +418,15 @@ func SubBytes(bytes []byte, start, end int) []byte {
|
||||
}
|
||||
return bytes[start:end]
|
||||
}
|
||||
func TlsBytes(cert, key string) (certBytes, keyBytes []byte) {
|
||||
certBytes, err := ioutil.ReadFile(cert)
|
||||
func TlsBytes(cert, key string) (certBytes, keyBytes []byte, err error) {
|
||||
certBytes, err = ioutil.ReadFile(cert)
|
||||
if err != nil {
|
||||
log.Fatalf("err : %s", err)
|
||||
err = fmt.Errorf("err : %s", err)
|
||||
return
|
||||
}
|
||||
keyBytes, err = ioutil.ReadFile(key)
|
||||
if err != nil {
|
||||
log.Fatalf("err : %s", err)
|
||||
err = fmt.Errorf("err : %s", err)
|
||||
return
|
||||
}
|
||||
return
|
||||
@ -431,7 +463,7 @@ func GetKCPBlock(method, key string) (block kcp.BlockCrypt) {
|
||||
}
|
||||
return
|
||||
}
|
||||
func HttpGet(URL string, timeout int) (body []byte, code int, err error) {
|
||||
func HttpGet(URL string, timeout int, host ...string) (body []byte, code int, err error) {
|
||||
var tr *http.Transport
|
||||
var client *http.Client
|
||||
conf := &tls.Config{
|
||||
@ -445,7 +477,16 @@ func HttpGet(URL string, timeout int) (body []byte, code int, err error) {
|
||||
client = &http.Client{Timeout: time.Millisecond * time.Duration(timeout), Transport: tr}
|
||||
}
|
||||
defer tr.CloseIdleConnections()
|
||||
resp, err := client.Get(URL)
|
||||
|
||||
//resp, err := client.Get(URL)
|
||||
req, err := http.NewRequest("GET", URL, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if len(host) == 1 && host[0] != "" {
|
||||
req.Host = host[0]
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@ -454,9 +495,23 @@ func HttpGet(URL string, timeout int) (body []byte, code int, err error) {
|
||||
body, err = ioutil.ReadAll(resp.Body)
|
||||
return
|
||||
}
|
||||
func IsIternalIP(domainOrIP string) bool {
|
||||
func IsIternalIP(domainOrIP string, always bool) bool {
|
||||
var outIPs []net.IP
|
||||
outIPs, err := net.LookupIP(domainOrIP)
|
||||
var err error
|
||||
var isDomain bool
|
||||
if net.ParseIP(domainOrIP) == nil {
|
||||
isDomain = true
|
||||
}
|
||||
if always && isDomain {
|
||||
return false
|
||||
}
|
||||
|
||||
if isDomain {
|
||||
outIPs, err = MyLookupIP(domainOrIP)
|
||||
} else {
|
||||
outIPs = []net.IP{net.ParseIP(domainOrIP)}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
@ -477,6 +532,59 @@ func IsIternalIP(domainOrIP string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
func IsHTTP(head []byte) bool {
|
||||
keys := []string{"GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH"}
|
||||
for _, key := range keys {
|
||||
if bytes.HasPrefix(head, []byte(key)) || bytes.HasPrefix(head, []byte(strings.ToLower(key))) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func IsSocks5(head []byte) bool {
|
||||
if len(head) < 3 {
|
||||
return false
|
||||
}
|
||||
if head[0] == uint8(0x05) && 0 < int(head[1]) && int(head[1]) < 255 {
|
||||
if len(head) == 2+int(head[1]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func RemoveProxyHeaders(head []byte) []byte {
|
||||
newLines := [][]byte{}
|
||||
var keys = map[string]bool{}
|
||||
lines := bytes.Split(head, []byte("\r\n"))
|
||||
IsBody := false
|
||||
i := -1
|
||||
for _, line := range lines {
|
||||
i++
|
||||
if len(line) == 0 || IsBody {
|
||||
newLines = append(newLines, line)
|
||||
IsBody = true
|
||||
} else {
|
||||
hline := bytes.SplitN(line, []byte(":"), 2)
|
||||
if i == 0 && IsHTTP(head) {
|
||||
newLines = append(newLines, line)
|
||||
continue
|
||||
}
|
||||
if len(hline) != 2 {
|
||||
continue
|
||||
}
|
||||
k := strings.ToUpper(string(hline[0]))
|
||||
if _, ok := keys[k]; ok || strings.HasPrefix(k, "PROXY-") {
|
||||
continue
|
||||
}
|
||||
keys[k] = true
|
||||
newLines = append(newLines, line)
|
||||
}
|
||||
}
|
||||
return bytes.Join(newLines, []byte("\r\n"))
|
||||
}
|
||||
func InsertProxyHeaders(head []byte, headers string) []byte {
|
||||
return bytes.Replace(head, []byte("\r\n"), []byte("\r\n"+headers), 1)
|
||||
}
|
||||
|
||||
// type sockaddr struct {
|
||||
// family uint16
|
||||
@ -534,3 +642,25 @@ func IsIternalIP(domainOrIP string) bool {
|
||||
// }
|
||||
// return
|
||||
// }
|
||||
|
||||
/*
|
||||
net.LookupIP may cause deadlock in windows
|
||||
https://github.com/golang/go/issues/24178
|
||||
*/
|
||||
func MyLookupIP(host string) ([]net.IP, error) {
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*time.Duration(3))
|
||||
defer func() {
|
||||
cancel()
|
||||
//ctx.Done()
|
||||
}()
|
||||
addrs, err := net.DefaultResolver.LookupIPAddr(ctx, host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ips := make([]net.IP, len(addrs))
|
||||
for i, ia := range addrs {
|
||||
ips[i] = ia.IP
|
||||
}
|
||||
return ips, nil
|
||||
}
|
||||
|
||||
100
utils/jumper/jumper.go
Normal file
@ -0,0 +1,100 @@
|
||||
package jumper
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
type Jumper struct {
|
||||
proxyURL *url.URL
|
||||
timeout time.Duration
|
||||
}
|
||||
type socks5Dialer struct {
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func (s socks5Dialer) Dial(network, addr string) (net.Conn, error) {
|
||||
return net.DialTimeout(network, addr, s.timeout)
|
||||
}
|
||||
|
||||
func New(proxyURL string, timeout time.Duration) (j Jumper, err error) {
|
||||
u, err := url.Parse(proxyURL)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
j = Jumper{
|
||||
proxyURL: u,
|
||||
timeout: timeout,
|
||||
}
|
||||
return
|
||||
}
|
||||
func (j *Jumper) Dial(address string, timeout time.Duration) (conn net.Conn, err error) {
|
||||
switch j.proxyURL.Scheme {
|
||||
case "https":
|
||||
return j.dialHTTPS(address, timeout)
|
||||
case "socks5":
|
||||
return j.dialSOCKS5(address, timeout)
|
||||
default:
|
||||
return nil, fmt.Errorf("unkown scheme of %s", j.proxyURL.String())
|
||||
}
|
||||
}
|
||||
func (j *Jumper) dialHTTPS(address string, timeout time.Duration) (conn net.Conn, err error) {
|
||||
conn, err = net.DialTimeout("tcp", j.proxyURL.Host, timeout)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
pb := new(bytes.Buffer)
|
||||
pb.Write([]byte(fmt.Sprintf("CONNECT %s HTTP/1.1\r\n", address)))
|
||||
pb.WriteString("Proxy-Connection: Keep-Alive\r\n")
|
||||
if j.proxyURL.User != nil {
|
||||
p, _ := j.proxyURL.User.Password()
|
||||
u := fmt.Sprintf("%s:%s", j.proxyURL.User.Username(), p)
|
||||
pb.Write([]byte(fmt.Sprintf("Proxy-Authorization: Basic %s\r\n", base64.StdEncoding.EncodeToString([]byte(u)))))
|
||||
}
|
||||
pb.Write([]byte("\r\n"))
|
||||
_, err = conn.Write(pb.Bytes())
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
conn = nil
|
||||
err = fmt.Errorf("error connecting to proxy: %s", err)
|
||||
return
|
||||
}
|
||||
reply := make([]byte, 1024)
|
||||
conn.SetDeadline(time.Now().Add(timeout))
|
||||
n, err := conn.Read(reply)
|
||||
conn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error read reply from proxy: %s", err)
|
||||
conn.Close()
|
||||
conn = nil
|
||||
return
|
||||
}
|
||||
if bytes.Index(reply[:n], []byte("200")) == -1 {
|
||||
err = fmt.Errorf("error greeting to proxy, response: %s", string(reply[:n]))
|
||||
conn.Close()
|
||||
conn = nil
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
func (j *Jumper) dialSOCKS5(address string, timeout time.Duration) (conn net.Conn, err error) {
|
||||
auth := &proxy.Auth{}
|
||||
if j.proxyURL.User != nil {
|
||||
auth.User = j.proxyURL.User.Username()
|
||||
auth.Password, _ = j.proxyURL.User.Password()
|
||||
} else {
|
||||
auth = nil
|
||||
}
|
||||
dialSocksProxy, err := proxy.SOCKS5("tcp", j.proxyURL.Host, auth, socks5Dialer{timeout: timeout})
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error connecting to proxy: %s", err)
|
||||
return
|
||||
}
|
||||
return dialSocksProxy.Dial("tcp", address)
|
||||
}
|
||||
45
utils/leakybuf.go
Normal file
@ -0,0 +1,45 @@
|
||||
// Provides leaky buffer, based on the example in Effective Go.
|
||||
package utils
|
||||
|
||||
type LeakyBuf struct {
|
||||
bufSize int // size of each buffer
|
||||
freeList chan []byte
|
||||
}
|
||||
|
||||
const LeakyBufSize = 2048 // data.len(2) + hmacsha1(10) + data(4096)
|
||||
const maxNBuf = 2048
|
||||
|
||||
var LeakyBuffer = NewLeakyBuf(maxNBuf, LeakyBufSize)
|
||||
|
||||
// NewLeakyBuf creates a leaky buffer which can hold at most n buffer, each
|
||||
// with bufSize bytes.
|
||||
func NewLeakyBuf(n, bufSize int) *LeakyBuf {
|
||||
return &LeakyBuf{
|
||||
bufSize: bufSize,
|
||||
freeList: make(chan []byte, n),
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns a buffer from the leaky buffer or create a new buffer.
|
||||
func (lb *LeakyBuf) Get() (b []byte) {
|
||||
select {
|
||||
case b = <-lb.freeList:
|
||||
default:
|
||||
b = make([]byte, lb.bufSize)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Put add the buffer into the free buffer pool for reuse. Panic if the buffer
|
||||
// size is not the same with the leaky buffer's. This is intended to expose
|
||||
// error usage of leaky buffer.
|
||||
func (lb *LeakyBuf) Put(b []byte) {
|
||||
if len(b) != lb.bufSize {
|
||||
panic("invalid buffer size that's put into leaky buffer")
|
||||
}
|
||||
select {
|
||||
case lb.freeList <- b:
|
||||
default:
|
||||
}
|
||||
return
|
||||
}
|
||||
145
utils/pool.go
@ -1,145 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
//ConnPool to use
|
||||
type ConnPool interface {
|
||||
Get() (conn interface{}, err error)
|
||||
Put(conn interface{})
|
||||
ReleaseAll()
|
||||
Len() (length int)
|
||||
}
|
||||
type poolConfig struct {
|
||||
Factory func() (interface{}, error)
|
||||
IsActive func(interface{}) bool
|
||||
Release func(interface{})
|
||||
InitialCap int
|
||||
MaxCap int
|
||||
}
|
||||
|
||||
func NewConnPool(poolConfig poolConfig) (pool ConnPool, err error) {
|
||||
p := netPool{
|
||||
config: poolConfig,
|
||||
conns: make(chan interface{}, poolConfig.MaxCap),
|
||||
lock: &sync.Mutex{},
|
||||
}
|
||||
//log.Printf("pool MaxCap:%d", poolConfig.MaxCap)
|
||||
if poolConfig.MaxCap > 0 {
|
||||
err = p.initAutoFill(false)
|
||||
if err == nil {
|
||||
p.initAutoFill(true)
|
||||
}
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
type netPool struct {
|
||||
conns chan interface{}
|
||||
lock *sync.Mutex
|
||||
config poolConfig
|
||||
}
|
||||
|
||||
func (p *netPool) initAutoFill(async bool) (err error) {
|
||||
var worker = func() (err error) {
|
||||
for {
|
||||
//log.Printf("pool fill: %v , len: %d", p.Len() <= p.config.InitialCap/2, p.Len())
|
||||
if p.Len() <= p.config.InitialCap/2 {
|
||||
p.lock.Lock()
|
||||
errN := 0
|
||||
for i := 0; i < p.config.InitialCap; i++ {
|
||||
c, err := p.config.Factory()
|
||||
if err != nil {
|
||||
errN++
|
||||
if async {
|
||||
continue
|
||||
} else {
|
||||
p.lock.Unlock()
|
||||
return err
|
||||
}
|
||||
}
|
||||
select {
|
||||
case p.conns <- c:
|
||||
default:
|
||||
p.config.Release(c)
|
||||
break
|
||||
}
|
||||
if p.Len() >= p.config.InitialCap {
|
||||
break
|
||||
}
|
||||
}
|
||||
if errN > 0 {
|
||||
log.Printf("fill conn pool fail , ERRN:%d", errN)
|
||||
}
|
||||
p.lock.Unlock()
|
||||
}
|
||||
if !async {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Second * 2)
|
||||
}
|
||||
}
|
||||
if async {
|
||||
go worker()
|
||||
} else {
|
||||
err = worker()
|
||||
}
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
func (p *netPool) Get() (conn interface{}, err error) {
|
||||
// defer func() {
|
||||
// log.Printf("pool len : %d", p.Len())
|
||||
// }()
|
||||
p.lock.Lock()
|
||||
defer p.lock.Unlock()
|
||||
// for {
|
||||
select {
|
||||
case conn = <-p.conns:
|
||||
if p.config.IsActive(conn) {
|
||||
return
|
||||
}
|
||||
p.config.Release(conn)
|
||||
default:
|
||||
conn, err = p.config.Factory()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
// }
|
||||
return
|
||||
}
|
||||
|
||||
func (p *netPool) Put(conn interface{}) {
|
||||
if conn == nil {
|
||||
return
|
||||
}
|
||||
p.lock.Lock()
|
||||
defer p.lock.Unlock()
|
||||
if !p.config.IsActive(conn) {
|
||||
p.config.Release(conn)
|
||||
}
|
||||
select {
|
||||
case p.conns <- conn:
|
||||
default:
|
||||
p.config.Release(conn)
|
||||
}
|
||||
}
|
||||
func (p *netPool) ReleaseAll() {
|
||||
p.lock.Lock()
|
||||
defer p.lock.Unlock()
|
||||
close(p.conns)
|
||||
for c := range p.conns {
|
||||
p.config.Release(c)
|
||||
}
|
||||
p.conns = make(chan interface{}, p.config.InitialCap)
|
||||
|
||||
}
|
||||
func (p *netPool) Len() (length int) {
|
||||
return len(p.conns)
|
||||
}
|
||||
@ -1,12 +1,17 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
logger "log"
|
||||
"net"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
|
||||
"github.com/snail007/goproxy/services/kcpcfg"
|
||||
|
||||
kcp "github.com/xtaci/kcp-go"
|
||||
)
|
||||
|
||||
@ -16,23 +21,26 @@ type ServerChannel struct {
|
||||
Listener *net.Listener
|
||||
UDPListener *net.UDPConn
|
||||
errAcceptHandler func(err error)
|
||||
log *logger.Logger
|
||||
}
|
||||
|
||||
func NewServerChannel(ip string, port int) ServerChannel {
|
||||
func NewServerChannel(ip string, port int, log *logger.Logger) ServerChannel {
|
||||
return ServerChannel{
|
||||
ip: ip,
|
||||
port: port,
|
||||
log: log,
|
||||
errAcceptHandler: func(err error) {
|
||||
fmt.Printf("accept error , ERR:%s", err)
|
||||
log.Printf("accept error , ERR:%s", err)
|
||||
},
|
||||
}
|
||||
}
|
||||
func NewServerChannelHost(host string) ServerChannel {
|
||||
func NewServerChannelHost(host string, log *logger.Logger) ServerChannel {
|
||||
h, port, _ := net.SplitHostPort(host)
|
||||
p, _ := strconv.Atoi(port)
|
||||
return ServerChannel{
|
||||
ip: h,
|
||||
port: p,
|
||||
log: log,
|
||||
errAcceptHandler: func(err error) {
|
||||
log.Printf("accept error , ERR:%s", err)
|
||||
},
|
||||
@ -41,13 +49,13 @@ func NewServerChannelHost(host string) ServerChannel {
|
||||
func (sc *ServerChannel) SetErrAcceptHandler(fn func(err error)) {
|
||||
sc.errAcceptHandler = fn
|
||||
}
|
||||
func (sc *ServerChannel) ListenTls(certBytes, keyBytes []byte, fn func(conn net.Conn)) (err error) {
|
||||
sc.Listener, err = ListenTls(sc.ip, sc.port, certBytes, keyBytes)
|
||||
func (sc *ServerChannel) ListenTls(certBytes, keyBytes, caCertBytes []byte, fn func(conn net.Conn)) (err error) {
|
||||
sc.Listener, err = sc.listenTls(sc.ip, sc.port, certBytes, keyBytes, caCertBytes)
|
||||
if err == nil {
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
log.Printf("ListenTls crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
sc.log.Printf("ListenTls crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
for {
|
||||
@ -57,7 +65,7 @@ func (sc *ServerChannel) ListenTls(certBytes, keyBytes []byte, fn func(conn net.
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
log.Printf("tls connection handler crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
sc.log.Printf("tls connection handler crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
fn(conn)
|
||||
@ -72,7 +80,33 @@ func (sc *ServerChannel) ListenTls(certBytes, keyBytes []byte, fn func(conn net.
|
||||
}
|
||||
return
|
||||
}
|
||||
func (sc *ServerChannel) listenTls(ip string, port int, certBytes, keyBytes, caCertBytes []byte) (ln *net.Listener, err error) {
|
||||
|
||||
var cert tls.Certificate
|
||||
cert, err = tls.X509KeyPair(certBytes, keyBytes)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
clientCertPool := x509.NewCertPool()
|
||||
caBytes := certBytes
|
||||
if caCertBytes != nil {
|
||||
caBytes = caCertBytes
|
||||
}
|
||||
ok := clientCertPool.AppendCertsFromPEM(caBytes)
|
||||
if !ok {
|
||||
err = errors.New("failed to parse root certificate")
|
||||
}
|
||||
config := &tls.Config{
|
||||
ClientCAs: clientCertPool,
|
||||
Certificates: []tls.Certificate{cert},
|
||||
ClientAuth: tls.RequireAndVerifyClientCert,
|
||||
}
|
||||
_ln, err := tls.Listen("tcp", fmt.Sprintf("%s:%d", ip, port), config)
|
||||
if err == nil {
|
||||
ln = &_ln
|
||||
}
|
||||
return
|
||||
}
|
||||
func (sc *ServerChannel) ListenTCP(fn func(conn net.Conn)) (err error) {
|
||||
var l net.Listener
|
||||
l, err = net.Listen("tcp", fmt.Sprintf("%s:%d", sc.ip, sc.port))
|
||||
@ -81,7 +115,7 @@ func (sc *ServerChannel) ListenTCP(fn func(conn net.Conn)) (err error) {
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
log.Printf("ListenTCP crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
sc.log.Printf("ListenTCP crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
for {
|
||||
@ -91,7 +125,7 @@ func (sc *ServerChannel) ListenTCP(fn func(conn net.Conn)) (err error) {
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
log.Printf("tcp connection handler crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
sc.log.Printf("tcp connection handler crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
fn(conn)
|
||||
@ -113,7 +147,7 @@ func (sc *ServerChannel) ListenUDP(fn func(packet []byte, localAddr, srcAddr *ne
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
log.Printf("ListenUDP crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
sc.log.Printf("ListenUDP crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
for {
|
||||
@ -124,7 +158,7 @@ func (sc *ServerChannel) ListenUDP(fn func(packet []byte, localAddr, srcAddr *ne
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
log.Printf("udp data handler crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
sc.log.Printf("udp data handler crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
fn(packet, addr, srcAddr)
|
||||
@ -138,28 +172,51 @@ func (sc *ServerChannel) ListenUDP(fn func(packet []byte, localAddr, srcAddr *ne
|
||||
}
|
||||
return
|
||||
}
|
||||
func (sc *ServerChannel) ListenKCP(method, key string, fn func(conn net.Conn)) (err error) {
|
||||
var l net.Listener
|
||||
l, err = kcp.ListenWithOptions(fmt.Sprintf("%s:%d", sc.ip, sc.port), GetKCPBlock(method, key), 10, 3)
|
||||
func (sc *ServerChannel) ListenKCP(config kcpcfg.KCPConfigArgs, fn func(conn net.Conn), log *logger.Logger) (err error) {
|
||||
lis, err := kcp.ListenWithOptions(fmt.Sprintf("%s:%d", sc.ip, sc.port), config.Block, *config.DataShard, *config.ParityShard)
|
||||
if err == nil {
|
||||
sc.Listener = &l
|
||||
if err = lis.SetDSCP(*config.DSCP); err != nil {
|
||||
log.Println("SetDSCP:", err)
|
||||
return
|
||||
}
|
||||
if err = lis.SetReadBuffer(*config.SockBuf); err != nil {
|
||||
log.Println("SetReadBuffer:", err)
|
||||
return
|
||||
}
|
||||
if err = lis.SetWriteBuffer(*config.SockBuf); err != nil {
|
||||
log.Println("SetWriteBuffer:", err)
|
||||
return
|
||||
}
|
||||
sc.Listener = new(net.Listener)
|
||||
*sc.Listener = lis
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
log.Printf("ListenKCP crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
sc.log.Printf("ListenKCP crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
for {
|
||||
var conn net.Conn
|
||||
conn, err = (*sc.Listener).Accept()
|
||||
//var conn net.Conn
|
||||
conn, err := lis.AcceptKCP()
|
||||
if err == nil {
|
||||
go func() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
log.Printf("kcp connection handler crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
sc.log.Printf("kcp connection handler crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
fn(conn)
|
||||
conn.SetStreamMode(true)
|
||||
conn.SetWriteDelay(true)
|
||||
conn.SetNoDelay(*config.NoDelay, *config.Interval, *config.Resend, *config.NoCongestion)
|
||||
conn.SetMtu(*config.MTU)
|
||||
conn.SetWindowSize(*config.SndWnd, *config.RcvWnd)
|
||||
conn.SetACKNoDelay(*config.AckNodelay)
|
||||
if *config.NoComp {
|
||||
fn(conn)
|
||||
} else {
|
||||
cconn := NewCompStream(conn)
|
||||
fn(cconn)
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
sc.errAcceptHandler(err)
|
||||
|
||||
253
utils/socks/client.go
Normal file
@ -0,0 +1,253 @@
|
||||
package socks
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
var socks5Errors = []string{
|
||||
"",
|
||||
"general failure",
|
||||
"connection forbidden",
|
||||
"network unreachable",
|
||||
"host unreachable",
|
||||
"connection refused",
|
||||
"TTL expired",
|
||||
"command not supported",
|
||||
"address type not supported",
|
||||
}
|
||||
|
||||
type Auth struct {
|
||||
User, Password string
|
||||
}
|
||||
type ClientConn struct {
|
||||
user string
|
||||
password string
|
||||
conn *net.Conn
|
||||
header []byte
|
||||
timeout time.Duration
|
||||
addr string
|
||||
network string
|
||||
UDPAddr string
|
||||
}
|
||||
|
||||
// SOCKS5 returns a Dialer that makes SOCKSv5 connections to the given address
|
||||
// with an optional username and password. See RFC 1928 and RFC 1929.
|
||||
// target must be a canonical address with a host and port.
|
||||
// network : tcp udp
|
||||
func NewClientConn(conn *net.Conn, network, target string, timeout time.Duration, auth *Auth, header []byte) *ClientConn {
|
||||
s := &ClientConn{
|
||||
conn: conn,
|
||||
network: network,
|
||||
timeout: timeout,
|
||||
}
|
||||
if auth != nil {
|
||||
s.user = auth.User
|
||||
s.password = auth.Password
|
||||
}
|
||||
if header != nil && len(header) > 0 {
|
||||
s.header = header
|
||||
}
|
||||
if network == "udp" && target == "" {
|
||||
target = "0.0.0.0:1"
|
||||
}
|
||||
s.addr = target
|
||||
return s
|
||||
}
|
||||
|
||||
// connect takes an existing connection to a socks5 proxy server,
|
||||
// and commands the server to extend that connection to target,
|
||||
// which must be a canonical address with a host and port.
|
||||
func (s *ClientConn) Handshake() error {
|
||||
host, portStr, err := net.SplitHostPort(s.addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
port, err := strconv.Atoi(portStr)
|
||||
if err != nil {
|
||||
return errors.New("proxy: failed to parse port number: " + portStr)
|
||||
}
|
||||
if s.network == "tcp" && (port < 1 || port > 0xffff) {
|
||||
return errors.New("proxy: port number out of range: " + portStr)
|
||||
}
|
||||
|
||||
if err := s.handshake(host); err != nil {
|
||||
return err
|
||||
}
|
||||
buf := []byte{}
|
||||
if s.network == "tcp" {
|
||||
buf = append(buf, VERSION_V5, CMD_CONNECT, 0 /* reserved */)
|
||||
|
||||
} else {
|
||||
buf = append(buf, VERSION_V5, CMD_ASSOCIATE, 0 /* reserved */)
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
if ip4 := ip.To4(); ip4 != nil {
|
||||
buf = append(buf, ATYP_IPV4)
|
||||
ip = ip4
|
||||
} else {
|
||||
buf = append(buf, ATYP_IPV6)
|
||||
}
|
||||
buf = append(buf, ip...)
|
||||
} else {
|
||||
if len(host) > 255 {
|
||||
return errors.New("proxy: destination host name too long: " + host)
|
||||
}
|
||||
buf = append(buf, ATYP_DOMAIN)
|
||||
buf = append(buf, byte(len(host)))
|
||||
buf = append(buf, host...)
|
||||
}
|
||||
buf = append(buf, byte(port>>8), byte(port))
|
||||
(*s.conn).SetDeadline(time.Now().Add(s.timeout))
|
||||
if _, err := (*s.conn).Write(buf); err != nil {
|
||||
return errors.New("proxy: failed to write connect request to SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||
}
|
||||
(*s.conn).SetDeadline(time.Time{})
|
||||
(*s.conn).SetDeadline(time.Now().Add(s.timeout))
|
||||
if _, err := io.ReadFull((*s.conn), buf[:4]); err != nil {
|
||||
return errors.New("proxy: failed to read connect reply from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||
}
|
||||
(*s.conn).SetDeadline(time.Time{})
|
||||
failure := "unknown error"
|
||||
if int(buf[1]) < len(socks5Errors) {
|
||||
failure = socks5Errors[buf[1]]
|
||||
}
|
||||
|
||||
if len(failure) > 0 {
|
||||
return errors.New("proxy: SOCKS5 proxy at " + s.addr + " failed to connect: " + failure)
|
||||
}
|
||||
|
||||
bytesToDiscard := 0
|
||||
switch buf[3] {
|
||||
case ATYP_IPV4:
|
||||
bytesToDiscard = net.IPv4len
|
||||
case ATYP_IPV6:
|
||||
bytesToDiscard = net.IPv6len
|
||||
case ATYP_DOMAIN:
|
||||
(*s.conn).SetDeadline(time.Now().Add(s.timeout))
|
||||
_, err := io.ReadFull((*s.conn), buf[:1])
|
||||
(*s.conn).SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
return errors.New("proxy: failed to read domain length from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||
}
|
||||
bytesToDiscard = int(buf[0])
|
||||
default:
|
||||
return errors.New("proxy: got unknown address type " + strconv.Itoa(int(buf[3])) + " from SOCKS5 proxy at " + s.addr)
|
||||
}
|
||||
|
||||
if cap(buf) < bytesToDiscard {
|
||||
buf = make([]byte, bytesToDiscard)
|
||||
} else {
|
||||
buf = buf[:bytesToDiscard]
|
||||
}
|
||||
(*s.conn).SetDeadline(time.Now().Add(s.timeout))
|
||||
if _, err := io.ReadFull((*s.conn), buf); err != nil {
|
||||
return errors.New("proxy: failed to read address from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||
}
|
||||
(*s.conn).SetDeadline(time.Time{})
|
||||
var ip net.IP
|
||||
ip = buf
|
||||
ipStr := ""
|
||||
if bytesToDiscard == net.IPv4len || bytesToDiscard == net.IPv6len {
|
||||
if ipv4 := ip.To4(); ipv4 != nil {
|
||||
ipStr = ipv4.String()
|
||||
} else {
|
||||
ipStr = ip.To16().String()
|
||||
}
|
||||
}
|
||||
//log.Printf("%v", ipStr)
|
||||
// Also need to discard the port number
|
||||
(*s.conn).SetDeadline(time.Now().Add(s.timeout))
|
||||
if _, err := io.ReadFull((*s.conn), buf[:2]); err != nil {
|
||||
return errors.New("proxy: failed to read port from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||
}
|
||||
p := binary.BigEndian.Uint16([]byte{buf[0], buf[1]})
|
||||
//log.Printf("%v", p)
|
||||
s.UDPAddr = net.JoinHostPort(ipStr, fmt.Sprintf("%d", p))
|
||||
//log.Printf("%v", s.udpAddr)
|
||||
(*s.conn).SetDeadline(time.Time{})
|
||||
return nil
|
||||
}
|
||||
func (s *ClientConn) SendUDP(data []byte, addr string) (respData []byte, err error) {
|
||||
|
||||
c, err := net.DialTimeout("udp", s.UDPAddr, s.timeout)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
conn := c.(*net.UDPConn)
|
||||
|
||||
p := NewPacketUDP()
|
||||
p.Build(addr, data)
|
||||
conn.SetDeadline(time.Now().Add(s.timeout))
|
||||
conn.Write(p.Bytes())
|
||||
conn.SetDeadline(time.Time{})
|
||||
|
||||
buf := make([]byte, 1024)
|
||||
conn.SetDeadline(time.Now().Add(s.timeout))
|
||||
n, _, err := conn.ReadFrom(buf)
|
||||
conn.SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
respData = buf[:n]
|
||||
return
|
||||
}
|
||||
func (s *ClientConn) handshake(host string) error {
|
||||
|
||||
// the size here is just an estimate
|
||||
buf := make([]byte, 0, 6+len(host))
|
||||
|
||||
buf = append(buf, VERSION_V5)
|
||||
if len(s.user) > 0 && len(s.user) < 256 && len(s.password) < 256 {
|
||||
buf = append(buf, 2 /* num auth methods */, Method_NO_AUTH, Method_USER_PASS)
|
||||
} else {
|
||||
buf = append(buf, 1 /* num auth methods */, Method_NO_AUTH)
|
||||
}
|
||||
(*s.conn).SetDeadline(time.Now().Add(s.timeout))
|
||||
if _, err := (*s.conn).Write(buf); err != nil {
|
||||
return errors.New("proxy: failed to write greeting to SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||
}
|
||||
(*s.conn).SetDeadline(time.Time{})
|
||||
|
||||
(*s.conn).SetDeadline(time.Now().Add(s.timeout))
|
||||
if _, err := io.ReadFull((*s.conn), buf[:2]); err != nil {
|
||||
return errors.New("proxy: failed to read greeting from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||
}
|
||||
(*s.conn).SetDeadline(time.Time{})
|
||||
|
||||
if buf[0] != 5 {
|
||||
return errors.New("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0])))
|
||||
}
|
||||
if buf[1] == 0xff {
|
||||
return errors.New("proxy: SOCKS5 proxy at " + s.addr + " requires authentication")
|
||||
}
|
||||
|
||||
// See RFC 1929
|
||||
if buf[1] == Method_USER_PASS {
|
||||
buf = buf[:0]
|
||||
buf = append(buf, 1 /* password protocol version */)
|
||||
buf = append(buf, uint8(len(s.user)))
|
||||
buf = append(buf, s.user...)
|
||||
buf = append(buf, uint8(len(s.password)))
|
||||
buf = append(buf, s.password...)
|
||||
(*s.conn).SetDeadline(time.Now().Add(s.timeout))
|
||||
if _, err := (*s.conn).Write(buf); err != nil {
|
||||
return errors.New("proxy: failed to write authentication request to SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||
}
|
||||
(*s.conn).SetDeadline(time.Time{})
|
||||
(*s.conn).SetDeadline(time.Now().Add(s.timeout))
|
||||
if _, err := io.ReadFull((*s.conn), buf[:2]); err != nil {
|
||||
return errors.New("proxy: failed to read authentication reply from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||
}
|
||||
(*s.conn).SetDeadline(time.Time{})
|
||||
if buf[1] != 0 {
|
||||
return errors.New("proxy: SOCKS5 proxy at " + s.addr + " rejected username/password")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
252
utils/socks/server.go
Normal file
@ -0,0 +1,252 @@
|
||||
package socks
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/snail007/goproxy/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
Method_NO_AUTH = uint8(0x00)
|
||||
Method_GSSAPI = uint8(0x01)
|
||||
Method_USER_PASS = uint8(0x02)
|
||||
Method_IANA = uint8(0x7F)
|
||||
Method_RESVERVE = uint8(0x80)
|
||||
Method_NONE_ACCEPTABLE = uint8(0xFF)
|
||||
VERSION_V5 = uint8(0x05)
|
||||
CMD_CONNECT = uint8(0x01)
|
||||
CMD_BIND = uint8(0x02)
|
||||
CMD_ASSOCIATE = uint8(0x03)
|
||||
ATYP_IPV4 = uint8(0x01)
|
||||
ATYP_DOMAIN = uint8(0x03)
|
||||
ATYP_IPV6 = uint8(0x04)
|
||||
REP_SUCCESS = uint8(0x00)
|
||||
REP_REQ_FAIL = uint8(0x01)
|
||||
REP_RULE_FORBIDDEN = uint8(0x02)
|
||||
REP_NETWOR_UNREACHABLE = uint8(0x03)
|
||||
REP_HOST_UNREACHABLE = uint8(0x04)
|
||||
REP_CONNECTION_REFUSED = uint8(0x05)
|
||||
REP_TTL_TIMEOUT = uint8(0x06)
|
||||
REP_CMD_UNSUPPORTED = uint8(0x07)
|
||||
REP_ATYP_UNSUPPORTED = uint8(0x08)
|
||||
REP_UNKNOWN = uint8(0x09)
|
||||
RSV = uint8(0x00)
|
||||
)
|
||||
|
||||
var (
|
||||
ZERO_IP = []byte{0x00, 0x00, 0x00, 0x00}
|
||||
ZERO_PORT = []byte{0x00, 0x00}
|
||||
)
|
||||
|
||||
type ServerConn struct {
|
||||
target string
|
||||
user string
|
||||
password string
|
||||
conn *net.Conn
|
||||
timeout time.Duration
|
||||
auth *utils.BasicAuth
|
||||
header []byte
|
||||
ver uint8
|
||||
//method
|
||||
methodsCount uint8
|
||||
methods []uint8
|
||||
method uint8
|
||||
//request
|
||||
cmd uint8
|
||||
reserve uint8
|
||||
addressType uint8
|
||||
dstAddr string
|
||||
dstPort string
|
||||
dstHost string
|
||||
UDPConnListener *net.UDPConn
|
||||
enableUDP bool
|
||||
udpIP string
|
||||
}
|
||||
|
||||
func NewServerConn(conn *net.Conn, timeout time.Duration, auth *utils.BasicAuth, enableUDP bool, udpHost string, header []byte) *ServerConn {
|
||||
|
||||
s := &ServerConn{
|
||||
conn: conn,
|
||||
timeout: timeout,
|
||||
auth: auth,
|
||||
header: header,
|
||||
ver: VERSION_V5,
|
||||
enableUDP: enableUDP,
|
||||
udpIP: udpHost,
|
||||
}
|
||||
return s
|
||||
|
||||
}
|
||||
func (s *ServerConn) Close() {
|
||||
utils.CloseConn(s.conn)
|
||||
}
|
||||
func (s *ServerConn) AuthData() Auth {
|
||||
return Auth{s.user, s.password}
|
||||
}
|
||||
func (s *ServerConn) IsUDP() bool {
|
||||
return s.cmd == CMD_ASSOCIATE
|
||||
}
|
||||
func (s *ServerConn) IsTCP() bool {
|
||||
return s.cmd == CMD_CONNECT
|
||||
}
|
||||
func (s *ServerConn) Method() uint8 {
|
||||
return s.method
|
||||
}
|
||||
func (s *ServerConn) Target() string {
|
||||
return s.target
|
||||
}
|
||||
func (s *ServerConn) Handshake() (err error) {
|
||||
remoteAddr := (*s.conn).RemoteAddr()
|
||||
//协商开始
|
||||
//method select request
|
||||
var methodReq MethodsRequest
|
||||
(*s.conn).SetReadDeadline(time.Now().Add(time.Second * s.timeout))
|
||||
|
||||
methodReq, e := NewMethodsRequest((*s.conn), s.header)
|
||||
(*s.conn).SetReadDeadline(time.Time{})
|
||||
if e != nil {
|
||||
(*s.conn).SetReadDeadline(time.Now().Add(time.Second * s.timeout))
|
||||
methodReq.Reply(Method_NONE_ACCEPTABLE)
|
||||
(*s.conn).SetReadDeadline(time.Time{})
|
||||
err = fmt.Errorf("new methods request fail,ERR: %s", e)
|
||||
return
|
||||
}
|
||||
//log.Printf("%v,s.auth == %v && methodReq.Select(Method_NO_AUTH) %v", methodReq.methods, s.auth, methodReq.Select(Method_NO_AUTH))
|
||||
if s.auth == nil && methodReq.Select(Method_NO_AUTH) && !methodReq.Select(Method_USER_PASS) {
|
||||
// if !methodReq.Select(Method_NO_AUTH) {
|
||||
// (*s.conn).SetReadDeadline(time.Now().Add(time.Second * s.timeout))
|
||||
// methodReq.Reply(Method_NONE_ACCEPTABLE)
|
||||
// (*s.conn).SetReadDeadline(time.Time{})
|
||||
// err = fmt.Errorf("none method found : Method_NO_AUTH")
|
||||
// return
|
||||
// }
|
||||
s.method = Method_NO_AUTH
|
||||
//method select reply
|
||||
(*s.conn).SetReadDeadline(time.Now().Add(time.Second * s.timeout))
|
||||
err = methodReq.Reply(Method_NO_AUTH)
|
||||
(*s.conn).SetReadDeadline(time.Time{})
|
||||
if err != nil {
|
||||
err = fmt.Errorf("reply answer data fail,ERR: %s", err)
|
||||
return
|
||||
}
|
||||
// err = fmt.Errorf("% x", methodReq.Bytes())
|
||||
} else {
|
||||
//auth
|
||||
if !methodReq.Select(Method_USER_PASS) {
|
||||
(*s.conn).SetReadDeadline(time.Now().Add(time.Second * s.timeout))
|
||||
methodReq.Reply(Method_NONE_ACCEPTABLE)
|
||||
(*s.conn).SetReadDeadline(time.Time{})
|
||||
err = fmt.Errorf("none method found : Method_USER_PASS")
|
||||
return
|
||||
}
|
||||
s.method = Method_USER_PASS
|
||||
//method reply need auth
|
||||
(*s.conn).SetReadDeadline(time.Now().Add(time.Second * s.timeout))
|
||||
err = methodReq.Reply(Method_USER_PASS)
|
||||
(*s.conn).SetReadDeadline(time.Time{})
|
||||
if err != nil {
|
||||
err = fmt.Errorf("reply answer data fail,ERR: %s", err)
|
||||
return
|
||||
}
|
||||
//read auth
|
||||
buf := make([]byte, 500)
|
||||
var n int
|
||||
(*s.conn).SetReadDeadline(time.Now().Add(time.Second * s.timeout))
|
||||
n, err = (*s.conn).Read(buf)
|
||||
(*s.conn).SetReadDeadline(time.Time{})
|
||||
if err != nil {
|
||||
err = fmt.Errorf("read auth info fail,ERR: %s", err)
|
||||
return
|
||||
}
|
||||
r := buf[:n]
|
||||
s.user = string(r[2 : r[1]+2])
|
||||
s.password = string(r[2+r[1]+1:])
|
||||
//err = fmt.Errorf("user:%s,pass:%s", user, pass)
|
||||
//auth
|
||||
_addr := strings.Split(remoteAddr.String(), ":")
|
||||
if s.auth == nil || s.auth.CheckUserPass(s.user, s.password, _addr[0], "") {
|
||||
(*s.conn).SetDeadline(time.Now().Add(time.Millisecond * time.Duration(s.timeout)))
|
||||
_, err = (*s.conn).Write([]byte{0x01, 0x00})
|
||||
(*s.conn).SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
err = fmt.Errorf("answer auth success to %s fail,ERR: %s", remoteAddr, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
(*s.conn).SetDeadline(time.Now().Add(time.Millisecond * time.Duration(s.timeout)))
|
||||
_, err = (*s.conn).Write([]byte{0x01, 0x01})
|
||||
(*s.conn).SetDeadline(time.Time{})
|
||||
if err != nil {
|
||||
err = fmt.Errorf("answer auth fail to %s fail,ERR: %s", remoteAddr, err)
|
||||
return
|
||||
}
|
||||
err = fmt.Errorf("auth fail from %s", remoteAddr)
|
||||
return
|
||||
}
|
||||
}
|
||||
//request detail
|
||||
(*s.conn).SetReadDeadline(time.Now().Add(time.Second * s.timeout))
|
||||
request, e := NewRequest(*s.conn)
|
||||
(*s.conn).SetReadDeadline(time.Time{})
|
||||
if e != nil {
|
||||
err = fmt.Errorf("read request data fail,ERR: %s", e)
|
||||
return
|
||||
}
|
||||
//协商结束
|
||||
|
||||
switch request.CMD() {
|
||||
case CMD_BIND:
|
||||
err = request.TCPReply(REP_UNKNOWN)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("TCPReply REP_UNKNOWN to %s fail,ERR: %s", remoteAddr, err)
|
||||
return
|
||||
}
|
||||
err = fmt.Errorf("cmd bind not supported, form: %s", remoteAddr)
|
||||
return
|
||||
case CMD_CONNECT:
|
||||
err = request.TCPReply(REP_SUCCESS)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("TCPReply REP_SUCCESS to %s fail,ERR: %s", remoteAddr, err)
|
||||
return
|
||||
}
|
||||
case CMD_ASSOCIATE:
|
||||
if !s.enableUDP {
|
||||
request.UDPReply(REP_UNKNOWN, "0.0.0.0:0")
|
||||
if err != nil {
|
||||
err = fmt.Errorf("UDPReply REP_UNKNOWN to %s fail,ERR: %s", remoteAddr, err)
|
||||
return
|
||||
}
|
||||
err = fmt.Errorf("cmd associate not supported, form: %s", remoteAddr)
|
||||
return
|
||||
}
|
||||
a, _ := net.ResolveUDPAddr("udp", ":0")
|
||||
s.UDPConnListener, err = net.ListenUDP("udp", a)
|
||||
if err != nil {
|
||||
request.UDPReply(REP_UNKNOWN, "0.0.0.0:0")
|
||||
err = fmt.Errorf("udp bind fail,ERR: %s , for %s", err, remoteAddr)
|
||||
return
|
||||
}
|
||||
_, port, _ := net.SplitHostPort(s.UDPConnListener.LocalAddr().String())
|
||||
err = request.UDPReply(REP_SUCCESS, net.JoinHostPort(s.udpIP, port))
|
||||
if err != nil {
|
||||
err = fmt.Errorf("UDPReply REP_SUCCESS to %s fail,ERR: %s", remoteAddr, err)
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//fill socks info
|
||||
s.target = request.Addr()
|
||||
s.methodsCount = methodReq.MethodsCount()
|
||||
s.methods = methodReq.Methods()
|
||||
s.cmd = request.CMD()
|
||||
s.reserve = request.reserve
|
||||
s.addressType = request.addressType
|
||||
s.dstAddr = request.dstAddr
|
||||
s.dstHost = request.dstHost
|
||||
s.dstPort = request.dstPort
|
||||
return
|
||||
}
|
||||
@ -3,44 +3,13 @@ package socks
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
const (
|
||||
Method_NO_AUTH = uint8(0x00)
|
||||
Method_GSSAPI = uint8(0x01)
|
||||
Method_USER_PASS = uint8(0x02)
|
||||
Method_IANA = uint8(0x7F)
|
||||
Method_RESVERVE = uint8(0x80)
|
||||
Method_NONE_ACCEPTABLE = uint8(0xFF)
|
||||
VERSION_V5 = uint8(0x05)
|
||||
CMD_CONNECT = uint8(0x01)
|
||||
CMD_BIND = uint8(0x02)
|
||||
CMD_ASSOCIATE = uint8(0x03)
|
||||
ATYP_IPV4 = uint8(0x01)
|
||||
ATYP_DOMAIN = uint8(0x03)
|
||||
ATYP_IPV6 = uint8(0x04)
|
||||
REP_SUCCESS = uint8(0x00)
|
||||
REP_REQ_FAIL = uint8(0x01)
|
||||
REP_RULE_FORBIDDEN = uint8(0x02)
|
||||
REP_NETWOR_UNREACHABLE = uint8(0x03)
|
||||
REP_HOST_UNREACHABLE = uint8(0x04)
|
||||
REP_CONNECTION_REFUSED = uint8(0x05)
|
||||
REP_TTL_TIMEOUT = uint8(0x06)
|
||||
REP_CMD_UNSUPPORTED = uint8(0x07)
|
||||
REP_ATYP_UNSUPPORTED = uint8(0x08)
|
||||
REP_UNKNOWN = uint8(0x09)
|
||||
RSV = uint8(0x00)
|
||||
)
|
||||
|
||||
var (
|
||||
ZERO_IP = []byte{0x00, 0x00, 0x00, 0x00}
|
||||
ZERO_PORT = []byte{0x00, 0x00}
|
||||
)
|
||||
|
||||
type Request struct {
|
||||
ver uint8
|
||||
cmd uint8
|
||||
@ -53,20 +22,24 @@ type Request struct {
|
||||
rw io.ReadWriter
|
||||
}
|
||||
|
||||
func NewRequest(rw io.ReadWriter) (req Request, err interface{}) {
|
||||
var b [1024]byte
|
||||
func NewRequest(rw io.ReadWriter, header ...[]byte) (req Request, err interface{}) {
|
||||
var b = make([]byte, 1024)
|
||||
var n int
|
||||
req = Request{rw: rw}
|
||||
n, err = rw.Read(b[:])
|
||||
if err != nil {
|
||||
err = fmt.Errorf("read req data fail,ERR: %s", err)
|
||||
return
|
||||
if header != nil && len(header) == 1 && len(header[0]) > 1 {
|
||||
b = header[0]
|
||||
n = len(header[0])
|
||||
} else {
|
||||
n, err = rw.Read(b[:])
|
||||
if err != nil {
|
||||
err = fmt.Errorf("read req data fail,ERR: %s", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
req.ver = uint8(b[0])
|
||||
req.cmd = uint8(b[1])
|
||||
req.reserve = uint8(b[2])
|
||||
req.addressType = uint8(b[3])
|
||||
|
||||
if b[0] != 0x5 {
|
||||
err = fmt.Errorf("sosck version supported")
|
||||
req.TCPReply(REP_REQ_FAIL)
|
||||
@ -124,7 +97,7 @@ func (s *Request) NewReply(rep uint8, addr string) []byte {
|
||||
ipv6[4], ipv6[5], ipv6[6], ipv6[7],
|
||||
ipv6[8], ipv6[9], ipv6[10], ipv6[11],
|
||||
)
|
||||
if ipv6 != nil && "0000000000255255" != zeroiIPv6 {
|
||||
if ipb == nil && ipv6 != nil && "0000000000255255" != zeroiIPv6 {
|
||||
atyp = ATYP_IPV6
|
||||
ipb = ip.To16()
|
||||
}
|
||||
@ -150,7 +123,7 @@ type MethodsRequest struct {
|
||||
rw *io.ReadWriter
|
||||
}
|
||||
|
||||
func NewMethodsRequest(r io.ReadWriter) (s MethodsRequest, err interface{}) {
|
||||
func NewMethodsRequest(r io.ReadWriter, header ...[]byte) (s MethodsRequest, err interface{}) {
|
||||
defer func() {
|
||||
if err == nil {
|
||||
err = recover()
|
||||
@ -160,9 +133,14 @@ func NewMethodsRequest(r io.ReadWriter) (s MethodsRequest, err interface{}) {
|
||||
s.rw = &r
|
||||
var buf = make([]byte, 300)
|
||||
var n int
|
||||
n, err = r.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
if header != nil && len(header) == 1 && len(header[0]) > 1 {
|
||||
buf = header[0]
|
||||
n = len(header[0])
|
||||
} else {
|
||||
n, err = r.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if buf[0] != 0x05 {
|
||||
err = fmt.Errorf("socks version not supported")
|
||||
@ -172,7 +150,6 @@ func NewMethodsRequest(r io.ReadWriter) (s MethodsRequest, err interface{}) {
|
||||
err = fmt.Errorf("socks methods data length error")
|
||||
return
|
||||
}
|
||||
|
||||
s.ver = buf[0]
|
||||
s.methodsCount = buf[1]
|
||||
s.methods = buf[2:n]
|
||||
@ -185,6 +162,9 @@ func (s *MethodsRequest) Version() uint8 {
|
||||
func (s *MethodsRequest) MethodsCount() uint8 {
|
||||
return s.methodsCount
|
||||
}
|
||||
func (s *MethodsRequest) Methods() []uint8 {
|
||||
return s.methods
|
||||
}
|
||||
func (s *MethodsRequest) Select(method uint8) bool {
|
||||
for _, m := range s.methods {
|
||||
if m == method {
|
||||
@ -201,17 +181,6 @@ func (s *MethodsRequest) Bytes() []byte {
|
||||
return s.bytes
|
||||
}
|
||||
|
||||
type UDPPacket struct {
|
||||
rsv uint16
|
||||
frag uint8
|
||||
atype uint8
|
||||
dstHost string
|
||||
dstPort string
|
||||
data []byte
|
||||
header []byte
|
||||
bytes []byte
|
||||
}
|
||||
|
||||
func ParseUDPPacket(b []byte) (p UDPPacket, err error) {
|
||||
p = UDPPacket{}
|
||||
p.frag = uint8(b[2])
|
||||
@ -239,6 +208,18 @@ func ParseUDPPacket(b []byte) (p UDPPacket, err error) {
|
||||
p.header = b[:portIndex+2]
|
||||
return
|
||||
}
|
||||
|
||||
type UDPPacket struct {
|
||||
rsv uint16
|
||||
frag uint8
|
||||
atype uint8
|
||||
dstHost string
|
||||
dstPort string
|
||||
data []byte
|
||||
header []byte
|
||||
bytes []byte
|
||||
}
|
||||
|
||||
func (s *UDPPacket) Header() []byte {
|
||||
return s.header
|
||||
}
|
||||
@ -258,3 +239,104 @@ func (s *UDPPacket) Port() string {
|
||||
func (s *UDPPacket) Data() []byte {
|
||||
return s.data
|
||||
}
|
||||
|
||||
type PacketUDP struct {
|
||||
rsv uint16
|
||||
frag uint8
|
||||
atype uint8
|
||||
dstHost string
|
||||
dstPort string
|
||||
data []byte
|
||||
}
|
||||
|
||||
func NewPacketUDP() (p PacketUDP) {
|
||||
return PacketUDP{}
|
||||
}
|
||||
func (p *PacketUDP) Build(destAddr string, data []byte) (err error) {
|
||||
host, port, err := net.SplitHostPort(destAddr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
p.rsv = 0
|
||||
p.frag = 0
|
||||
p.dstHost = host
|
||||
p.dstPort = port
|
||||
p.atype = ATYP_IPV4
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
if ip4 := ip.To4(); ip4 != nil {
|
||||
p.atype = ATYP_IPV4
|
||||
ip = ip4
|
||||
} else {
|
||||
p.atype = ATYP_IPV6
|
||||
}
|
||||
} else {
|
||||
if len(host) > 255 {
|
||||
err = errors.New("proxy: destination host name too long: " + host)
|
||||
return
|
||||
}
|
||||
p.atype = ATYP_DOMAIN
|
||||
}
|
||||
p.data = data
|
||||
|
||||
return
|
||||
}
|
||||
func (p *PacketUDP) Parse(b []byte) (err error) {
|
||||
p.frag = uint8(b[2])
|
||||
if p.frag != 0 {
|
||||
err = fmt.Errorf("FRAG only support for 0 , %v ,%v", p.frag, b[:4])
|
||||
return
|
||||
}
|
||||
portIndex := 0
|
||||
p.atype = b[3]
|
||||
switch p.atype {
|
||||
case ATYP_IPV4: //IP V4
|
||||
p.dstHost = net.IPv4(b[4], b[5], b[6], b[7]).String()
|
||||
portIndex = 8
|
||||
case ATYP_DOMAIN: //域名
|
||||
domainLen := uint8(b[4])
|
||||
p.dstHost = string(b[5 : 5+domainLen]) //b[4]表示域名的长度
|
||||
portIndex = int(5 + domainLen)
|
||||
case ATYP_IPV6: //IP V6
|
||||
p.dstHost = net.IP{b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15], b[16], b[17], b[18], b[19]}.String()
|
||||
portIndex = 20
|
||||
}
|
||||
p.dstPort = strconv.Itoa(int(b[portIndex])<<8 | int(b[portIndex+1]))
|
||||
p.data = b[portIndex+2:]
|
||||
return
|
||||
}
|
||||
func (p *PacketUDP) Header() []byte {
|
||||
header := new(bytes.Buffer)
|
||||
header.Write([]byte{0x00, 0x00, p.frag, p.atype})
|
||||
if p.atype == ATYP_IPV4 {
|
||||
ip := net.ParseIP(p.dstHost)
|
||||
header.Write(ip.To4())
|
||||
} else if p.atype == ATYP_IPV6 {
|
||||
ip := net.ParseIP(p.dstHost)
|
||||
header.Write(ip.To16())
|
||||
} else if p.atype == ATYP_DOMAIN {
|
||||
hBytes := []byte(p.dstHost)
|
||||
header.WriteByte(byte(len(hBytes)))
|
||||
header.Write(hBytes)
|
||||
}
|
||||
port, _ := strconv.ParseUint(p.dstPort, 10, 64)
|
||||
portBytes := new(bytes.Buffer)
|
||||
binary.Write(portBytes, binary.BigEndian, port)
|
||||
header.Write(portBytes.Bytes()[portBytes.Len()-2:])
|
||||
return header.Bytes()
|
||||
}
|
||||
func (p *PacketUDP) Bytes() []byte {
|
||||
packBytes := new(bytes.Buffer)
|
||||
packBytes.Write(p.Header())
|
||||
packBytes.Write(p.data)
|
||||
return packBytes.Bytes()
|
||||
}
|
||||
func (p *PacketUDP) Host() string {
|
||||
return p.dstHost
|
||||
}
|
||||
|
||||
func (p *PacketUDP) Port() string {
|
||||
return p.dstPort
|
||||
}
|
||||
func (p *PacketUDP) Data() []byte {
|
||||
return p.data
|
||||
}
|
||||
|
||||
699
utils/structs.go
@ -1,20 +1,26 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
logger "log"
|
||||
"net"
|
||||
"net/url"
|
||||
"proxy/utils/sni"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/snail007/goproxy/services/kcpcfg"
|
||||
"github.com/snail007/goproxy/utils/sni"
|
||||
|
||||
"github.com/golang/snappy"
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
type Checker struct {
|
||||
@ -23,26 +29,27 @@ type Checker struct {
|
||||
directMap ConcurrentMap
|
||||
interval int64
|
||||
timeout int
|
||||
isStop bool
|
||||
log *logger.Logger
|
||||
}
|
||||
type CheckerItem struct {
|
||||
IsHTTPS bool
|
||||
Method string
|
||||
URL string
|
||||
Domain string
|
||||
Host string
|
||||
Data []byte
|
||||
Address string
|
||||
SuccessCount uint
|
||||
FailCount uint
|
||||
Lasttime int64
|
||||
}
|
||||
|
||||
//NewChecker args:
|
||||
//timeout : tcp timeout milliseconds ,connect to host
|
||||
//interval: recheck domain interval seconds
|
||||
func NewChecker(timeout int, interval int64, blockedFile, directFile string) Checker {
|
||||
func NewChecker(timeout int, interval int64, blockedFile, directFile string, log *logger.Logger) Checker {
|
||||
ch := Checker{
|
||||
data: NewConcurrentMap(),
|
||||
interval: interval,
|
||||
timeout: timeout,
|
||||
isStop: false,
|
||||
log: log,
|
||||
}
|
||||
ch.blockedMap = ch.loadMap(blockedFile)
|
||||
ch.directMap = ch.loadMap(directFile)
|
||||
@ -52,7 +59,10 @@ func NewChecker(timeout int, interval int64, blockedFile, directFile string) Che
|
||||
if !ch.directMap.IsEmpty() {
|
||||
log.Printf("direct file loaded , domains : %d", ch.directMap.Count())
|
||||
}
|
||||
ch.start()
|
||||
if interval > 0 {
|
||||
ch.start()
|
||||
}
|
||||
|
||||
return ch
|
||||
}
|
||||
|
||||
@ -61,7 +71,7 @@ func (c *Checker) loadMap(f string) (dataMap ConcurrentMap) {
|
||||
if PathExists(f) {
|
||||
_contents, err := ioutil.ReadFile(f)
|
||||
if err != nil {
|
||||
log.Printf("load file err:%s", err)
|
||||
c.log.Printf("load file err:%s", err)
|
||||
return
|
||||
}
|
||||
for _, line := range strings.Split(string(_contents), "\n") {
|
||||
@ -73,6 +83,9 @@ func (c *Checker) loadMap(f string) (dataMap ConcurrentMap) {
|
||||
}
|
||||
return
|
||||
}
|
||||
func (c *Checker) Stop() {
|
||||
c.isStop = true
|
||||
}
|
||||
func (c *Checker) start() {
|
||||
go func() {
|
||||
//log.Printf("checker started")
|
||||
@ -84,57 +97,71 @@ func (c *Checker) start() {
|
||||
//log.Printf("check %s", item.Host)
|
||||
var conn net.Conn
|
||||
var err error
|
||||
conn, err = ConnectHost(item.Host, c.timeout)
|
||||
var now = time.Now().Unix()
|
||||
conn, err = ConnectHost(item.Address, c.timeout)
|
||||
if err == nil {
|
||||
conn.SetDeadline(time.Now().Add(time.Millisecond))
|
||||
conn.Close()
|
||||
}
|
||||
if now-item.Lasttime > 1800 {
|
||||
item.FailCount = 0
|
||||
item.SuccessCount = 0
|
||||
}
|
||||
if err != nil {
|
||||
item.FailCount = item.FailCount + 1
|
||||
} else {
|
||||
item.SuccessCount = item.SuccessCount + 1
|
||||
}
|
||||
c.data.Set(item.Host, item)
|
||||
item.Lasttime = now
|
||||
c.data.Set(item.Domain, item)
|
||||
}
|
||||
}(v.(CheckerItem))
|
||||
}
|
||||
time.Sleep(time.Second * time.Duration(c.interval))
|
||||
if c.isStop {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
func (c *Checker) isNeedCheck(item CheckerItem) bool {
|
||||
var minCount uint = 5
|
||||
if (item.SuccessCount >= minCount && item.SuccessCount > item.FailCount) ||
|
||||
(item.FailCount >= minCount && item.SuccessCount > item.FailCount) ||
|
||||
c.domainIsInMap(item.Host, false) ||
|
||||
c.domainIsInMap(item.Host, true) {
|
||||
var now = time.Now().Unix()
|
||||
if (item.SuccessCount >= minCount && item.SuccessCount > item.FailCount && now-item.Lasttime < 1800) ||
|
||||
(item.FailCount >= minCount && item.SuccessCount > item.FailCount && now-item.Lasttime < 1800) ||
|
||||
c.domainIsInMap(item.Domain, false) ||
|
||||
c.domainIsInMap(item.Domain, true) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
func (c *Checker) IsBlocked(address string) (blocked bool, failN, successN uint) {
|
||||
if c.domainIsInMap(address, true) {
|
||||
//log.Printf("%s in blocked ? true", address)
|
||||
return true, 0, 0
|
||||
func (c *Checker) IsBlocked(domain string) (blocked, isInMap bool, failN, successN uint) {
|
||||
h, _, _ := net.SplitHostPort(domain)
|
||||
if h != "" {
|
||||
domain = h
|
||||
}
|
||||
if c.domainIsInMap(address, false) {
|
||||
if c.domainIsInMap(domain, true) {
|
||||
//log.Printf("%s in blocked ? true", address)
|
||||
return true, true, 0, 0
|
||||
}
|
||||
if c.domainIsInMap(domain, false) {
|
||||
//log.Printf("%s in direct ? true", address)
|
||||
return false, 0, 0
|
||||
return false, true, 0, 0
|
||||
}
|
||||
|
||||
_item, ok := c.data.Get(address)
|
||||
_item, ok := c.data.Get(domain)
|
||||
if !ok {
|
||||
//log.Printf("%s not in map, blocked true", address)
|
||||
return true, 0, 0
|
||||
return true, false, 0, 0
|
||||
}
|
||||
item := _item.(CheckerItem)
|
||||
|
||||
return item.FailCount >= item.SuccessCount, item.FailCount, item.SuccessCount
|
||||
return (item.FailCount >= item.SuccessCount) && (time.Now().Unix()-item.Lasttime < 1800), true, item.FailCount, item.SuccessCount
|
||||
}
|
||||
func (c *Checker) domainIsInMap(address string, blockedMap bool) bool {
|
||||
u, err := url.Parse("http://" + address)
|
||||
if err != nil {
|
||||
log.Printf("blocked check , url parse err:%s", err)
|
||||
c.log.Printf("blocked check , url parse err:%s", err)
|
||||
return true
|
||||
}
|
||||
domainSlice := strings.Split(u.Hostname(), ".")
|
||||
@ -154,15 +181,20 @@ func (c *Checker) domainIsInMap(address string, blockedMap bool) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (c *Checker) Add(address string) {
|
||||
if c.domainIsInMap(address, false) || c.domainIsInMap(address, true) {
|
||||
func (c *Checker) Add(domain, address string) {
|
||||
h, _, _ := net.SplitHostPort(domain)
|
||||
if h != "" {
|
||||
domain = h
|
||||
}
|
||||
if c.domainIsInMap(domain, false) || c.domainIsInMap(domain, true) {
|
||||
return
|
||||
}
|
||||
var item CheckerItem
|
||||
item = CheckerItem{
|
||||
Host: address,
|
||||
Domain: domain,
|
||||
Address: address,
|
||||
}
|
||||
c.data.SetIfAbsent(item.Host, item)
|
||||
c.data.SetIfAbsent(item.Domain, item)
|
||||
}
|
||||
|
||||
type BasicAuth struct {
|
||||
@ -171,11 +203,15 @@ type BasicAuth struct {
|
||||
authOkCode int
|
||||
authTimeout int
|
||||
authRetry int
|
||||
dns *DomainResolver
|
||||
log *logger.Logger
|
||||
}
|
||||
|
||||
func NewBasicAuth() BasicAuth {
|
||||
func NewBasicAuth(dns *DomainResolver, log *logger.Logger) BasicAuth {
|
||||
return BasicAuth{
|
||||
data: NewConcurrentMap(),
|
||||
dns: dns,
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
func (ba *BasicAuth) SetAuthURL(URL string, code, timeout, retry int) {
|
||||
@ -228,7 +264,7 @@ func (ba *BasicAuth) Check(userpass string, ip, target string) (ok bool) {
|
||||
if err == nil {
|
||||
return true
|
||||
}
|
||||
log.Printf("%s", err)
|
||||
ba.log.Printf("%s", err)
|
||||
}
|
||||
return false
|
||||
}
|
||||
@ -239,18 +275,27 @@ func (ba *BasicAuth) checkFromURL(userpass, ip, target string) (err error) {
|
||||
if len(u) != 2 {
|
||||
return
|
||||
}
|
||||
|
||||
URL := ba.authURL
|
||||
if strings.Contains(URL, "?") {
|
||||
URL += "&"
|
||||
} else {
|
||||
URL += "?"
|
||||
}
|
||||
URL += fmt.Sprintf("user=%s&pass=%s&ip=%s&target=%s", u[0], u[1], ip, target)
|
||||
URL += fmt.Sprintf("user=%s&pass=%s&ip=%s&target=%s", u[0], u[1], ip, url.QueryEscape(target))
|
||||
getURL := URL
|
||||
var domain string
|
||||
if ba.dns != nil {
|
||||
_url, _ := url.Parse(ba.authURL)
|
||||
domain = _url.Host
|
||||
domainIP := ba.dns.MustResolve(domain)
|
||||
getURL = strings.Replace(URL, domain, domainIP, 1)
|
||||
}
|
||||
var code int
|
||||
var tryCount = 0
|
||||
var body []byte
|
||||
for tryCount <= ba.authRetry {
|
||||
body, code, err = HttpGet(URL, ba.authTimeout)
|
||||
body, code, err = HttpGet(getURL, ba.authTimeout, domain)
|
||||
if err == nil && code == ba.authOkCode {
|
||||
break
|
||||
} else if err != nil {
|
||||
@ -261,10 +306,14 @@ func (ba *BasicAuth) checkFromURL(userpass, ip, target string) (err error) {
|
||||
} else {
|
||||
err = fmt.Errorf("token error")
|
||||
}
|
||||
err = fmt.Errorf("auth fail from url %s,resonse code: %d, except: %d , %s , %s", URL, code, ba.authOkCode, ip, string(body))
|
||||
b := string(body)
|
||||
if len(b) > 50 {
|
||||
b = b[:50]
|
||||
}
|
||||
err = fmt.Errorf("auth fail from url %s,resonse code: %d, except: %d , %s , %s", URL, code, ba.authOkCode, ip, b)
|
||||
}
|
||||
if err != nil && tryCount < ba.authRetry {
|
||||
log.Print(err)
|
||||
ba.log.Print(err)
|
||||
time.Sleep(time.Second * 2)
|
||||
}
|
||||
tryCount++
|
||||
@ -290,23 +339,32 @@ type HTTPRequest struct {
|
||||
hostOrURL string
|
||||
isBasicAuth bool
|
||||
basicAuth *BasicAuth
|
||||
log *logger.Logger
|
||||
IsSNI bool
|
||||
}
|
||||
|
||||
func NewHTTPRequest(inConn *net.Conn, bufSize int, isBasicAuth bool, basicAuth *BasicAuth) (req HTTPRequest, err error) {
|
||||
func NewHTTPRequest(inConn *net.Conn, bufSize int, isBasicAuth bool, basicAuth *BasicAuth, log *logger.Logger, header ...[]byte) (req HTTPRequest, err error) {
|
||||
buf := make([]byte, bufSize)
|
||||
len := 0
|
||||
n := 0
|
||||
req = HTTPRequest{
|
||||
conn: inConn,
|
||||
log: log,
|
||||
}
|
||||
len, err = (*inConn).Read(buf[:])
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
err = fmt.Errorf("http decoder read err:%s", err)
|
||||
if header != nil && len(header) == 1 && len(header[0]) > 1 {
|
||||
buf = header[0]
|
||||
n = len(header[0])
|
||||
} else {
|
||||
n, err = (*inConn).Read(buf[:])
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
err = fmt.Errorf("http decoder read err:%s", err)
|
||||
}
|
||||
CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
CloseConn(inConn)
|
||||
return
|
||||
}
|
||||
req.HeadBuf = buf[:len]
|
||||
|
||||
req.HeadBuf = buf[:n]
|
||||
//fmt.Println(string(req.HeadBuf))
|
||||
//try sni
|
||||
serverName, err0 := sni.ServerNameFromBytes(req.HeadBuf)
|
||||
@ -314,6 +372,7 @@ func NewHTTPRequest(inConn *net.Conn, bufSize int, isBasicAuth bool, basicAuth *
|
||||
//sni success
|
||||
req.Method = "SNI"
|
||||
req.hostOrURL = "https://" + serverName + ":443"
|
||||
req.IsSNI = true
|
||||
} else {
|
||||
//sni fail , try http
|
||||
index := bytes.IndexByte(req.HeadBuf, '\n')
|
||||
@ -348,16 +407,14 @@ func (req *HTTPRequest) HTTP() (err error) {
|
||||
return
|
||||
}
|
||||
}
|
||||
req.URL, err = req.getHTTPURL()
|
||||
if err == nil {
|
||||
var u *url.URL
|
||||
u, err = url.Parse(req.URL)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
req.Host = u.Host
|
||||
req.addPortIfNot()
|
||||
req.URL = req.getHTTPURL()
|
||||
var u *url.URL
|
||||
u, err = url.Parse(req.URL)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
req.Host = u.Host
|
||||
req.addPortIfNot()
|
||||
return
|
||||
}
|
||||
func (req *HTTPRequest) HTTPS() (err error) {
|
||||
@ -369,7 +426,6 @@ func (req *HTTPRequest) HTTPS() (err error) {
|
||||
}
|
||||
req.Host = req.hostOrURL
|
||||
req.addPortIfNot()
|
||||
//_, err = fmt.Fprint(*req.conn, "HTTP/1.1 200 Connection established\r\n\r\n")
|
||||
return
|
||||
}
|
||||
func (req *HTTPRequest) HTTPSReply() (err error) {
|
||||
@ -380,26 +436,18 @@ func (req *HTTPRequest) IsHTTPS() bool {
|
||||
return req.Method == "CONNECT"
|
||||
}
|
||||
|
||||
func (req *HTTPRequest) BasicAuth() (err error) {
|
||||
func (req *HTTPRequest) GetAuthDataStr() (basicInfo string, err error) {
|
||||
// log.Printf("request :%s", string(req.HeadBuf))
|
||||
authorization := req.getHeader("Proxy-Authorization")
|
||||
|
||||
//log.Printf("request :%s", string(b[:n]))authorization
|
||||
isProxyAuthorization := false
|
||||
authorization, err := req.getHeader("Authorization")
|
||||
if err != nil {
|
||||
fmt.Fprint((*req.conn), "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"\"\r\n\r\nUnauthorized")
|
||||
authorization = strings.Trim(authorization, " \r\n\t")
|
||||
if authorization == "" {
|
||||
fmt.Fprintf((*req.conn), "HTTP/1.1 %s Proxy Authentication Required\r\nProxy-Authenticate: Basic realm=\"\"\r\n\r\nProxy Authentication Required", "407")
|
||||
CloseConn(req.conn)
|
||||
err = errors.New("require auth header data")
|
||||
return
|
||||
}
|
||||
if authorization == "" {
|
||||
authorization, err = req.getHeader("Proxy-Authorization")
|
||||
if err != nil {
|
||||
fmt.Fprint((*req.conn), "HTTP/1.1 407 Unauthorized\r\nWWW-Authenticate: Basic realm=\"\"\r\n\r\nUnauthorized")
|
||||
CloseConn(req.conn)
|
||||
return
|
||||
}
|
||||
isProxyAuthorization = true
|
||||
}
|
||||
//log.Printf("Authorization:%s", authorization)
|
||||
//log.Printf("Authorization:%authorization = req.getHeader("Authorization")
|
||||
basic := strings.Fields(authorization)
|
||||
if len(basic) != 2 {
|
||||
err = fmt.Errorf("authorization data error,ERR:%s", authorization)
|
||||
@ -412,47 +460,51 @@ func (req *HTTPRequest) BasicAuth() (err error) {
|
||||
CloseConn(req.conn)
|
||||
return
|
||||
}
|
||||
basicInfo = string(user)
|
||||
return
|
||||
}
|
||||
func (req *HTTPRequest) BasicAuth() (err error) {
|
||||
addr := strings.Split((*req.conn).RemoteAddr().String(), ":")
|
||||
URL := ""
|
||||
if req.IsHTTPS() {
|
||||
URL = "https://" + req.Host
|
||||
} else {
|
||||
URL, _ = req.getHTTPURL()
|
||||
URL = req.getHTTPURL()
|
||||
}
|
||||
user, err := req.GetAuthDataStr()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
authOk := (*req.basicAuth).Check(string(user), addr[0], URL)
|
||||
//log.Printf("auth %s,%v", string(user), authOk)
|
||||
if !authOk {
|
||||
code := "401"
|
||||
if isProxyAuthorization {
|
||||
code = "407"
|
||||
}
|
||||
fmt.Fprintf((*req.conn), "HTTP/1.1 %s Unauthorized\r\n\r\nUnauthorized", code)
|
||||
fmt.Fprintf((*req.conn), "HTTP/1.1 %s Proxy Authentication Required\r\n\r\nProxy Authentication Required", "407")
|
||||
CloseConn(req.conn)
|
||||
err = fmt.Errorf("basic auth fail")
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
func (req *HTTPRequest) getHTTPURL() (URL string, err error) {
|
||||
func (req *HTTPRequest) getHTTPURL() (URL string) {
|
||||
if !strings.HasPrefix(req.hostOrURL, "/") {
|
||||
return req.hostOrURL, nil
|
||||
return req.hostOrURL
|
||||
}
|
||||
_host, err := req.getHeader("host")
|
||||
if err != nil {
|
||||
_host := req.getHeader("host")
|
||||
if _host == "" {
|
||||
return
|
||||
}
|
||||
URL = fmt.Sprintf("http://%s%s", _host, req.hostOrURL)
|
||||
return
|
||||
}
|
||||
func (req *HTTPRequest) getHeader(key string) (val string, err error) {
|
||||
func (req *HTTPRequest) getHeader(key string) (val string) {
|
||||
key = strings.ToUpper(key)
|
||||
lines := strings.Split(string(req.HeadBuf), "\r\n")
|
||||
//log.Println(lines)
|
||||
for _, line := range lines {
|
||||
line := strings.SplitN(strings.Trim(line, "\r\n "), ":", 2)
|
||||
if len(line) == 2 {
|
||||
k := strings.ToUpper(strings.Trim(line[0], " "))
|
||||
v := strings.Trim(line[1], " ")
|
||||
hline := strings.SplitN(strings.Trim(line, "\r\n "), ":", 2)
|
||||
if len(hline) == 2 {
|
||||
k := strings.ToUpper(strings.Trim(hline[0], " "))
|
||||
v := strings.Trim(hline[1], " ")
|
||||
if key == k {
|
||||
val = v
|
||||
return
|
||||
@ -476,252 +528,55 @@ func (req *HTTPRequest) addPortIfNot() (newHost string) {
|
||||
return
|
||||
}
|
||||
|
||||
type OutPool struct {
|
||||
Pool ConnPool
|
||||
dur int
|
||||
typ string
|
||||
certBytes []byte
|
||||
keyBytes []byte
|
||||
kcpMethod string
|
||||
kcpKey string
|
||||
address string
|
||||
timeout int
|
||||
type OutConn struct {
|
||||
dur int
|
||||
typ string
|
||||
certBytes []byte
|
||||
keyBytes []byte
|
||||
caCertBytes []byte
|
||||
kcp kcpcfg.KCPConfigArgs
|
||||
address string
|
||||
timeout int
|
||||
}
|
||||
|
||||
func NewOutPool(dur int, typ, kcpMethod, kcpKey string, certBytes, keyBytes []byte, address string, timeout int, InitialCap int, MaxCap int) (op OutPool) {
|
||||
op = OutPool{
|
||||
dur: dur,
|
||||
typ: typ,
|
||||
certBytes: certBytes,
|
||||
keyBytes: keyBytes,
|
||||
kcpMethod: kcpMethod,
|
||||
kcpKey: kcpKey,
|
||||
address: address,
|
||||
timeout: timeout,
|
||||
func NewOutConn(dur int, typ string, kcp kcpcfg.KCPConfigArgs, certBytes, keyBytes, caCertBytes []byte, address string, timeout int) (op OutConn) {
|
||||
return OutConn{
|
||||
dur: dur,
|
||||
typ: typ,
|
||||
certBytes: certBytes,
|
||||
keyBytes: keyBytes,
|
||||
caCertBytes: caCertBytes,
|
||||
kcp: kcp,
|
||||
address: address,
|
||||
timeout: timeout,
|
||||
}
|
||||
var err error
|
||||
op.Pool, err = NewConnPool(poolConfig{
|
||||
IsActive: func(conn interface{}) bool { return true },
|
||||
Release: func(conn interface{}) {
|
||||
if conn != nil {
|
||||
conn.(net.Conn).SetDeadline(time.Now().Add(time.Millisecond))
|
||||
conn.(net.Conn).Close()
|
||||
// log.Println("conn released")
|
||||
}
|
||||
},
|
||||
InitialCap: InitialCap,
|
||||
MaxCap: MaxCap,
|
||||
Factory: func() (conn interface{}, err error) {
|
||||
conn, err = op.getConn()
|
||||
return
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("init conn pool fail ,%s", err)
|
||||
} else {
|
||||
if InitialCap > 0 {
|
||||
log.Printf("init conn pool success")
|
||||
op.initPoolDeamon()
|
||||
} else {
|
||||
log.Printf("conn pool closed")
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (op *OutPool) getConn() (conn interface{}, err error) {
|
||||
func (op *OutConn) Get() (conn net.Conn, err error) {
|
||||
if op.typ == "tls" {
|
||||
var _conn tls.Conn
|
||||
_conn, err = TlsConnectHost(op.address, op.timeout, op.certBytes, op.keyBytes)
|
||||
_conn, err = TlsConnectHost(op.address, op.timeout, op.certBytes, op.keyBytes, op.caCertBytes)
|
||||
if err == nil {
|
||||
conn = net.Conn(&_conn)
|
||||
}
|
||||
} else if op.typ == "kcp" {
|
||||
conn, err = ConnectKCPHost(op.address, op.kcpMethod, op.kcpKey)
|
||||
conn, err = ConnectKCPHost(op.address, op.kcp)
|
||||
} else {
|
||||
conn, err = ConnectHost(op.address, op.timeout)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (op *OutPool) initPoolDeamon() {
|
||||
go func() {
|
||||
if op.dur <= 0 {
|
||||
return
|
||||
}
|
||||
log.Printf("pool deamon started")
|
||||
for {
|
||||
time.Sleep(time.Second * time.Duration(op.dur))
|
||||
conn, err := op.getConn()
|
||||
if err != nil {
|
||||
log.Printf("pool deamon err %s , release pool", err)
|
||||
op.Pool.ReleaseAll()
|
||||
} else {
|
||||
conn.(net.Conn).SetDeadline(time.Now().Add(time.Millisecond))
|
||||
conn.(net.Conn).Close()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
type HeartbeatData struct {
|
||||
Data []byte
|
||||
N int
|
||||
Error error
|
||||
}
|
||||
type HeartbeatReadWriter struct {
|
||||
conn *net.Conn
|
||||
// rchn chan HeartbeatData
|
||||
l *sync.Mutex
|
||||
dur int
|
||||
errHandler func(err error, hb *HeartbeatReadWriter)
|
||||
once *sync.Once
|
||||
datachn chan byte
|
||||
// rbuf bytes.Buffer
|
||||
// signal chan bool
|
||||
rerrchn chan error
|
||||
}
|
||||
|
||||
func NewHeartbeatReadWriter(conn *net.Conn, dur int, fn func(err error, hb *HeartbeatReadWriter)) (hrw HeartbeatReadWriter) {
|
||||
hrw = HeartbeatReadWriter{
|
||||
conn: conn,
|
||||
l: &sync.Mutex{},
|
||||
dur: dur,
|
||||
// rchn: make(chan HeartbeatData, 10000),
|
||||
// signal: make(chan bool, 1),
|
||||
errHandler: fn,
|
||||
datachn: make(chan byte, 4*1024),
|
||||
once: &sync.Once{},
|
||||
rerrchn: make(chan error, 1),
|
||||
// rbuf: bytes.Buffer{},
|
||||
}
|
||||
hrw.heartbeat()
|
||||
hrw.reader()
|
||||
return
|
||||
}
|
||||
|
||||
func (rw *HeartbeatReadWriter) Close() {
|
||||
CloseConn(rw.conn)
|
||||
}
|
||||
func (rw *HeartbeatReadWriter) reader() {
|
||||
go func() {
|
||||
//log.Printf("heartbeat read started")
|
||||
for {
|
||||
n, data, err := rw.read()
|
||||
if n == -1 {
|
||||
continue
|
||||
}
|
||||
//log.Printf("n:%d , data:%s ,err:%s", n, string(data), err)
|
||||
if err == nil {
|
||||
//fmt.Printf("write data %s\n", string(data))
|
||||
for _, b := range data {
|
||||
rw.datachn <- b
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
//log.Printf("heartbeat reader err: %s", err)
|
||||
select {
|
||||
case rw.rerrchn <- err:
|
||||
default:
|
||||
}
|
||||
rw.once.Do(func() {
|
||||
rw.errHandler(err, rw)
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
//log.Printf("heartbeat read exited")
|
||||
}()
|
||||
}
|
||||
func (rw *HeartbeatReadWriter) read() (n int, data []byte, err error) {
|
||||
var typ uint8
|
||||
err = binary.Read((*rw.conn), binary.LittleEndian, &typ)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if typ == 0 {
|
||||
// log.Printf("heartbeat revecived")
|
||||
n = -1
|
||||
return
|
||||
}
|
||||
var dataLength uint32
|
||||
binary.Read((*rw.conn), binary.LittleEndian, &dataLength)
|
||||
_data := make([]byte, dataLength)
|
||||
// log.Printf("dataLength:%d , data:%s", dataLength, string(data))
|
||||
n, err = (*rw.conn).Read(_data)
|
||||
//log.Printf("n:%d , data:%s ,err:%s", n, string(data), err)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if uint32(n) != dataLength {
|
||||
err = fmt.Errorf("read short data body")
|
||||
return
|
||||
}
|
||||
data = _data[:n]
|
||||
return
|
||||
}
|
||||
func (rw *HeartbeatReadWriter) heartbeat() {
|
||||
go func() {
|
||||
//log.Printf("heartbeat started")
|
||||
for {
|
||||
if rw.conn == nil || *rw.conn == nil {
|
||||
//log.Printf("heartbeat err: conn nil")
|
||||
break
|
||||
}
|
||||
rw.l.Lock()
|
||||
_, err := (*rw.conn).Write([]byte{0})
|
||||
rw.l.Unlock()
|
||||
if err != nil {
|
||||
//log.Printf("heartbeat err: %s", err)
|
||||
rw.once.Do(func() {
|
||||
rw.errHandler(err, rw)
|
||||
})
|
||||
break
|
||||
} else {
|
||||
// log.Printf("heartbeat send ok")
|
||||
}
|
||||
time.Sleep(time.Second * time.Duration(rw.dur))
|
||||
}
|
||||
//log.Printf("heartbeat exited")
|
||||
}()
|
||||
}
|
||||
func (rw *HeartbeatReadWriter) Read(p []byte) (n int, err error) {
|
||||
data := make([]byte, cap(p))
|
||||
for i := 0; i < cap(p); i++ {
|
||||
data[i] = <-rw.datachn
|
||||
n++
|
||||
//fmt.Printf("read %d %v\n", i, data[:n])
|
||||
if len(rw.datachn) == 0 {
|
||||
n = i + 1
|
||||
copy(p, data[:n])
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (rw *HeartbeatReadWriter) Write(p []byte) (n int, err error) {
|
||||
defer rw.l.Unlock()
|
||||
rw.l.Lock()
|
||||
pkg := new(bytes.Buffer)
|
||||
binary.Write(pkg, binary.LittleEndian, uint8(1))
|
||||
binary.Write(pkg, binary.LittleEndian, uint32(len(p)))
|
||||
binary.Write(pkg, binary.LittleEndian, p)
|
||||
bs := pkg.Bytes()
|
||||
n, err = (*rw.conn).Write(bs)
|
||||
if err == nil {
|
||||
n = len(p)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type ConnManager struct {
|
||||
pool ConcurrentMap
|
||||
l *sync.Mutex
|
||||
log *logger.Logger
|
||||
}
|
||||
|
||||
func NewConnManager() ConnManager {
|
||||
func NewConnManager(log *logger.Logger) ConnManager {
|
||||
cm := ConnManager{
|
||||
pool: NewConcurrentMap(),
|
||||
l: &sync.Mutex{},
|
||||
log: log,
|
||||
}
|
||||
return cm
|
||||
}
|
||||
@ -738,7 +593,7 @@ func (cm *ConnManager) Add(key, ID string, conn *net.Conn) {
|
||||
(*v.(*net.Conn)).Close()
|
||||
}
|
||||
conns.Set(ID, conn)
|
||||
log.Printf("%s conn added", key)
|
||||
cm.log.Printf("%s conn added", key)
|
||||
return conns
|
||||
})
|
||||
}
|
||||
@ -749,7 +604,7 @@ func (cm *ConnManager) Remove(key string) {
|
||||
conns.IterCb(func(key string, v interface{}) {
|
||||
CloseConn(v.(*net.Conn))
|
||||
})
|
||||
log.Printf("%s conns closed", key)
|
||||
cm.log.Printf("%s conns closed", key)
|
||||
}
|
||||
cm.pool.Remove(key)
|
||||
}
|
||||
@ -764,7 +619,7 @@ func (cm *ConnManager) RemoveOne(key string, ID string) {
|
||||
(*v.(*net.Conn)).Close()
|
||||
conns.Remove(ID)
|
||||
cm.pool.Set(key, conns)
|
||||
log.Printf("%s %s conn closed", key, ID)
|
||||
cm.log.Printf("%s %s conn closed", key, ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -773,3 +628,223 @@ func (cm *ConnManager) RemoveAll() {
|
||||
cm.Remove(k)
|
||||
}
|
||||
}
|
||||
|
||||
type ClientKeyRouter struct {
|
||||
keyChan chan string
|
||||
ctrl *ConcurrentMap
|
||||
lock *sync.Mutex
|
||||
}
|
||||
|
||||
func NewClientKeyRouter(ctrl *ConcurrentMap, size int) ClientKeyRouter {
|
||||
return ClientKeyRouter{
|
||||
keyChan: make(chan string, size),
|
||||
ctrl: ctrl,
|
||||
lock: &sync.Mutex{},
|
||||
}
|
||||
}
|
||||
func (c *ClientKeyRouter) GetKey() string {
|
||||
defer c.lock.Unlock()
|
||||
c.lock.Lock()
|
||||
if len(c.keyChan) == 0 {
|
||||
EXIT:
|
||||
for _, k := range c.ctrl.Keys() {
|
||||
select {
|
||||
case c.keyChan <- k:
|
||||
default:
|
||||
goto EXIT
|
||||
}
|
||||
}
|
||||
}
|
||||
for {
|
||||
if len(c.keyChan) == 0 {
|
||||
return "*"
|
||||
}
|
||||
select {
|
||||
case key := <-c.keyChan:
|
||||
if c.ctrl.Has(key) {
|
||||
return key
|
||||
}
|
||||
default:
|
||||
return "*"
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
type DomainResolver struct {
|
||||
ttl int
|
||||
dnsAddrress string
|
||||
data ConcurrentMap
|
||||
log *logger.Logger
|
||||
}
|
||||
type DomainResolverItem struct {
|
||||
ip string
|
||||
domain string
|
||||
expiredAt int64
|
||||
}
|
||||
|
||||
func NewDomainResolver(dnsAddrress string, ttl int, log *logger.Logger) DomainResolver {
|
||||
return DomainResolver{
|
||||
ttl: ttl,
|
||||
dnsAddrress: dnsAddrress,
|
||||
data: NewConcurrentMap(),
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
func (a *DomainResolver) MustResolve(address string) (ip string) {
|
||||
ip, _ = a.Resolve(address)
|
||||
return
|
||||
}
|
||||
func (a *DomainResolver) Resolve(address string) (ip string, err error) {
|
||||
domain := address
|
||||
port := ""
|
||||
fromCache := "false"
|
||||
defer func() {
|
||||
if port != "" {
|
||||
ip = net.JoinHostPort(ip, port)
|
||||
}
|
||||
a.log.Printf("dns:%s->%s,cache:%s", address, ip, fromCache)
|
||||
//a.PrintData()
|
||||
}()
|
||||
if strings.Contains(domain, ":") {
|
||||
domain, port, err = net.SplitHostPort(domain)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if net.ParseIP(domain) != nil {
|
||||
ip = domain
|
||||
fromCache = "ip ignore"
|
||||
return
|
||||
}
|
||||
item, ok := a.data.Get(domain)
|
||||
if ok {
|
||||
//log.Println("find ", domain)
|
||||
if (*item.(*DomainResolverItem)).expiredAt > time.Now().Unix() {
|
||||
ip = (*item.(*DomainResolverItem)).ip
|
||||
fromCache = "true"
|
||||
//log.Println("from cache ", domain)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
item = &DomainResolverItem{
|
||||
domain: domain,
|
||||
}
|
||||
|
||||
}
|
||||
c := new(dns.Client)
|
||||
c.DialTimeout = time.Millisecond * 5000
|
||||
c.ReadTimeout = time.Millisecond * 5000
|
||||
c.WriteTimeout = time.Millisecond * 5000
|
||||
m := new(dns.Msg)
|
||||
m.SetQuestion(dns.Fqdn(domain), dns.TypeA)
|
||||
m.RecursionDesired = true
|
||||
r, _, err := c.Exchange(m, a.dnsAddrress)
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
if r.Rcode != dns.RcodeSuccess {
|
||||
err = fmt.Errorf(" *** invalid answer name %s after A query for %s", domain, a.dnsAddrress)
|
||||
return
|
||||
}
|
||||
for _, answer := range r.Answer {
|
||||
if answer.Header().Rrtype == dns.TypeA {
|
||||
info := strings.Fields(answer.String())
|
||||
if len(info) >= 5 {
|
||||
ip = info[4]
|
||||
_item := item.(*DomainResolverItem)
|
||||
(*_item).expiredAt = time.Now().Unix() + int64(a.ttl)
|
||||
(*_item).ip = ip
|
||||
a.data.Set(domain, item)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
func (a *DomainResolver) PrintData() {
|
||||
for k, item := range a.data.Items() {
|
||||
d := item.(*DomainResolverItem)
|
||||
a.log.Printf("%s:ip[%s],domain[%s],expired at[%d]\n", k, (*d).ip, (*d).domain, (*d).expiredAt)
|
||||
}
|
||||
}
|
||||
func NewCompStream(conn net.Conn) *CompStream {
|
||||
c := new(CompStream)
|
||||
c.conn = conn
|
||||
c.w = snappy.NewBufferedWriter(conn)
|
||||
c.r = snappy.NewReader(conn)
|
||||
return c
|
||||
}
|
||||
func NewCompConn(conn net.Conn) net.Conn {
|
||||
c := CompStream{}
|
||||
c.conn = conn
|
||||
c.w = snappy.NewBufferedWriter(conn)
|
||||
c.r = snappy.NewReader(conn)
|
||||
return &c
|
||||
}
|
||||
|
||||
type CompStream struct {
|
||||
net.Conn
|
||||
conn net.Conn
|
||||
w *snappy.Writer
|
||||
r *snappy.Reader
|
||||
}
|
||||
|
||||
func (c *CompStream) Read(p []byte) (n int, err error) {
|
||||
return c.r.Read(p)
|
||||
}
|
||||
|
||||
func (c *CompStream) Write(p []byte) (n int, err error) {
|
||||
n, err = c.w.Write(p)
|
||||
err = c.w.Flush()
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (c *CompStream) Close() error {
|
||||
return c.conn.Close()
|
||||
}
|
||||
func (c *CompStream) LocalAddr() net.Addr {
|
||||
return c.conn.LocalAddr()
|
||||
}
|
||||
func (c *CompStream) RemoteAddr() net.Addr {
|
||||
return c.conn.RemoteAddr()
|
||||
}
|
||||
func (c *CompStream) SetDeadline(t time.Time) error {
|
||||
return c.conn.SetDeadline(t)
|
||||
}
|
||||
func (c *CompStream) SetReadDeadline(t time.Time) error {
|
||||
return c.conn.SetReadDeadline(t)
|
||||
}
|
||||
func (c *CompStream) SetWriteDeadline(t time.Time) error {
|
||||
return c.conn.SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
type BufferedConn struct {
|
||||
r *bufio.Reader
|
||||
net.Conn // So that most methods are embedded
|
||||
}
|
||||
|
||||
func NewBufferedConn(c net.Conn) BufferedConn {
|
||||
return BufferedConn{bufio.NewReader(c), c}
|
||||
}
|
||||
|
||||
func NewBufferedConnSize(c net.Conn, n int) BufferedConn {
|
||||
return BufferedConn{bufio.NewReaderSize(c, n), c}
|
||||
}
|
||||
|
||||
func (b BufferedConn) Peek(n int) ([]byte, error) {
|
||||
return b.r.Peek(n)
|
||||
}
|
||||
|
||||
func (b BufferedConn) Read(p []byte) (int, error) {
|
||||
return b.r.Read(p)
|
||||
}
|
||||
func (b BufferedConn) ReadByte() (byte, error) {
|
||||
return b.r.ReadByte()
|
||||
}
|
||||
func (b BufferedConn) UnreadByte() error {
|
||||
return b.r.UnreadByte()
|
||||
}
|
||||
func (b BufferedConn) Buffered() int {
|
||||
return b.r.Buffered()
|
||||
}
|
||||
|
||||
16
vendor/github.com/golang/snappy/.gitignore
generated
vendored
Normal file
@ -0,0 +1,16 @@
|
||||
cmd/snappytool/snappytool
|
||||
testdata/bench
|
||||
|
||||
# These explicitly listed benchmark data files are for an obsolete version of
|
||||
# snappy_test.go.
|
||||
testdata/alice29.txt
|
||||
testdata/asyoulik.txt
|
||||
testdata/fireworks.jpeg
|
||||
testdata/geo.protodata
|
||||
testdata/html
|
||||
testdata/html_x_4
|
||||
testdata/kppkn.gtb
|
||||
testdata/lcet10.txt
|
||||
testdata/paper-100k.pdf
|
||||
testdata/plrabn12.txt
|
||||
testdata/urls.10K
|
||||
19
vendor/github.com/golang/snappy/snappy.go
generated
vendored
@ -2,11 +2,22 @@
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package snappy implements the snappy block-based compression format.
|
||||
// It aims for very high speeds and reasonable compression.
|
||||
// Package snappy implements the Snappy compression format. It aims for very
|
||||
// high speeds and reasonable compression.
|
||||
//
|
||||
// The C++ snappy implementation is at https://github.com/google/snappy
|
||||
package snappy
|
||||
// There are actually two Snappy formats: block and stream. They are related,
|
||||
// but different: trying to decompress block-compressed data as a Snappy stream
|
||||
// will fail, and vice versa. The block format is the Decode and Encode
|
||||
// functions and the stream format is the Reader and Writer types.
|
||||
//
|
||||
// The block format, the more common case, is used when the complete size (the
|
||||
// number of bytes) of the original data is known upfront, at the time
|
||||
// compression starts. The stream format, also known as the framing format, is
|
||||
// for when that isn't always true.
|
||||
//
|
||||
// The canonical, C++ implementation is at https://github.com/google/snappy and
|
||||
// it only implements the block format.
|
||||
package snappy // import "github.com/golang/snappy"
|
||||
|
||||
import (
|
||||
"hash/crc32"
|
||||
|
||||
23
vendor/github.com/hashicorp/yamux/.gitignore
generated
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
*.test
|
||||
362
vendor/github.com/hashicorp/yamux/LICENSE
generated
vendored
Normal file
@ -0,0 +1,362 @@
|
||||
Mozilla Public License, version 2.0
|
||||
|
||||
1. Definitions
|
||||
|
||||
1.1. "Contributor"
|
||||
|
||||
means each individual or legal entity that creates, contributes to the
|
||||
creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
|
||||
means the combination of the Contributions of others (if any) used by a
|
||||
Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
|
||||
means Source Code Form to which the initial Contributor has attached the
|
||||
notice in Exhibit A, the Executable Form of such Source Code Form, and
|
||||
Modifications of such Source Code Form, in each case including portions
|
||||
thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
a. that the initial Contributor has attached the notice described in
|
||||
Exhibit B to the Covered Software; or
|
||||
|
||||
b. that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the terms of
|
||||
a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
|
||||
means a work that combines Covered Software with other material, in a
|
||||
separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
|
||||
means having the right to grant, to the maximum extent possible, whether
|
||||
at the time of the initial grant or subsequently, any and all of the
|
||||
rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
|
||||
means any of the following:
|
||||
|
||||
a. any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered Software; or
|
||||
|
||||
b. any new file in Source Code Form that contains any Covered Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the License,
|
||||
by the making, using, selling, offering for sale, having made, import,
|
||||
or transfer of either its Contributions or its Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
|
||||
means either the GNU General Public License, Version 2.0, the GNU Lesser
|
||||
General Public License, Version 2.1, the GNU Affero General Public
|
||||
License, Version 3.0, or any later versions of those licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that controls, is
|
||||
controlled by, or is under common control with You. For purposes of this
|
||||
definition, "control" means (a) the power, direct or indirect, to cause
|
||||
the direction or management of such entity, whether by contract or
|
||||
otherwise, or (b) ownership of more than fifty percent (50%) of the
|
||||
outstanding shares or beneficial ownership of such entity.
|
||||
|
||||
|
||||
2. License Grants and Conditions
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
a. under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
b. under Patent Claims of such Contributor to make, use, sell, offer for
|
||||
sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
a. for any code that a Contributor has removed from Covered Software; or
|
||||
|
||||
b. for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
c. under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights to
|
||||
grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
|
||||
Section 2.1.
|
||||
|
||||
|
||||
3. Responsibilities
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
a. such Covered Software must also be made available in Source Code Form,
|
||||
as described in Section 3.1, and You must inform recipients of the
|
||||
Executable Form how they can obtain a copy of such Source Code Form by
|
||||
reasonable means in a timely manner, at a charge no more than the cost
|
||||
of distribution to the recipient; and
|
||||
|
||||
b. You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter the
|
||||
recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty, or
|
||||
limitations of liability) contained within the Source Code Form of the
|
||||
Covered Software, except that You may alter any license notices to the
|
||||
extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this License
|
||||
with respect to some or all of the Covered Software due to statute,
|
||||
judicial order, or regulation then You must: (a) comply with the terms of
|
||||
this License to the maximum extent possible; and (b) describe the
|
||||
limitations and the code they affect. Such description must be placed in a
|
||||
text file included with all distributions of the Covered Software under
|
||||
this License. Except to the extent prohibited by statute or regulation,
|
||||
such description must be sufficiently detailed for a recipient of ordinary
|
||||
skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically if You
|
||||
fail to comply with any of its terms. However, if You become compliant,
|
||||
then the rights granted under this License from a particular Contributor
|
||||
are reinstated (a) provisionally, unless and until such Contributor
|
||||
explicitly and finally terminates Your grants, and (b) on an ongoing
|
||||
basis, if such Contributor fails to notify You of the non-compliance by
|
||||
some reasonable means prior to 60 days after You have come back into
|
||||
compliance. Moreover, Your grants from a particular Contributor are
|
||||
reinstated on an ongoing basis if such Contributor notifies You of the
|
||||
non-compliance by some reasonable means, this is the first time You have
|
||||
received notice of non-compliance with this License from such
|
||||
Contributor, and You become compliant prior to 30 days after Your receipt
|
||||
of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
|
||||
license agreements (excluding distributors and resellers) which have been
|
||||
validly granted by You or Your distributors under this License prior to
|
||||
termination shall survive termination.
|
||||
|
||||
6. Disclaimer of Warranty
|
||||
|
||||
Covered Software is provided under this License on an "as is" basis,
|
||||
without warranty of any kind, either expressed, implied, or statutory,
|
||||
including, without limitation, warranties that the Covered Software is free
|
||||
of defects, merchantable, fit for a particular purpose or non-infringing.
|
||||
The entire risk as to the quality and performance of the Covered Software
|
||||
is with You. Should any Covered Software prove defective in any respect,
|
||||
You (not any Contributor) assume the cost of any necessary servicing,
|
||||
repair, or correction. This disclaimer of warranty constitutes an essential
|
||||
part of this License. No use of any Covered Software is authorized under
|
||||
this License except under this disclaimer.
|
||||
|
||||
7. Limitation of Liability
|
||||
|
||||
Under no circumstances and under no legal theory, whether tort (including
|
||||
negligence), contract, or otherwise, shall any Contributor, or anyone who
|
||||
distributes Covered Software as permitted above, be liable to You for any
|
||||
direct, indirect, special, incidental, or consequential damages of any
|
||||
character including, without limitation, damages for lost profits, loss of
|
||||
goodwill, work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses, even if such party shall have been
|
||||
informed of the possibility of such damages. This limitation of liability
|
||||
shall not apply to liability for death or personal injury resulting from
|
||||
such party's negligence to the extent applicable law prohibits such
|
||||
limitation. Some jurisdictions do not allow the exclusion or limitation of
|
||||
incidental or consequential damages, so this exclusion and limitation may
|
||||
not apply to You.
|
||||
|
||||
8. Litigation
|
||||
|
||||
Any litigation relating to this License may be brought only in the courts
|
||||
of a jurisdiction where the defendant maintains its principal place of
|
||||
business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions. Nothing
|
||||
in this Section shall prevent a party's ability to bring cross-claims or
|
||||
counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides that
|
||||
the language of a contract shall be construed against the drafter shall not
|
||||
be used to construe this License against a Contributor.
|
||||
|
||||
|
||||
10. Versions of the License
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses If You choose to distribute Source Code Form that is
|
||||
Incompatible With Secondary Licenses under the terms of this version of
|
||||
the License, the notice described in Exhibit B of this License must be
|
||||
attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular file,
|
||||
then You may include the notice in a location (such as a LICENSE file in a
|
||||
relevant directory) where a recipient would be likely to look for such a
|
||||
notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
|
||||
This Source Code Form is "Incompatible
|
||||
With Secondary Licenses", as defined by
|
||||
the Mozilla Public License, v. 2.0.
|
||||
86
vendor/github.com/hashicorp/yamux/README.md
generated
vendored
Normal file
@ -0,0 +1,86 @@
|
||||
# Yamux
|
||||
|
||||
Yamux (Yet another Multiplexer) is a multiplexing library for Golang.
|
||||
It relies on an underlying connection to provide reliability
|
||||
and ordering, such as TCP or Unix domain sockets, and provides
|
||||
stream-oriented multiplexing. It is inspired by SPDY but is not
|
||||
interoperable with it.
|
||||
|
||||
Yamux features include:
|
||||
|
||||
* Bi-directional streams
|
||||
* Streams can be opened by either client or server
|
||||
* Useful for NAT traversal
|
||||
* Server-side push support
|
||||
* Flow control
|
||||
* Avoid starvation
|
||||
* Back-pressure to prevent overwhelming a receiver
|
||||
* Keep Alives
|
||||
* Enables persistent connections over a load balancer
|
||||
* Efficient
|
||||
* Enables thousands of logical streams with low overhead
|
||||
|
||||
## Documentation
|
||||
|
||||
For complete documentation, see the associated [Godoc](http://godoc.org/github.com/hashicorp/yamux).
|
||||
|
||||
## Specification
|
||||
|
||||
The full specification for Yamux is provided in the `spec.md` file.
|
||||
It can be used as a guide to implementors of interoperable libraries.
|
||||
|
||||
## Usage
|
||||
|
||||
Using Yamux is remarkably simple:
|
||||
|
||||
```go
|
||||
|
||||
func client() {
|
||||
// Get a TCP connection
|
||||
conn, err := net.Dial(...)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Setup client side of yamux
|
||||
session, err := yamux.Client(conn, nil)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Open a new stream
|
||||
stream, err := session.Open()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Stream implements net.Conn
|
||||
stream.Write([]byte("ping"))
|
||||
}
|
||||
|
||||
func server() {
|
||||
// Accept a TCP connection
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Setup server side of yamux
|
||||
session, err := yamux.Server(conn, nil)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Accept a stream
|
||||
stream, err := session.Accept()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Listen for a message
|
||||
buf := make([]byte, 4)
|
||||
stream.Read(buf)
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
60
vendor/github.com/hashicorp/yamux/addr.go
generated
vendored
Normal file
@ -0,0 +1,60 @@
|
||||
package yamux
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
)
|
||||
|
||||
// hasAddr is used to get the address from the underlying connection
|
||||
type hasAddr interface {
|
||||
LocalAddr() net.Addr
|
||||
RemoteAddr() net.Addr
|
||||
}
|
||||
|
||||
// yamuxAddr is used when we cannot get the underlying address
|
||||
type yamuxAddr struct {
|
||||
Addr string
|
||||
}
|
||||
|
||||
func (*yamuxAddr) Network() string {
|
||||
return "yamux"
|
||||
}
|
||||
|
||||
func (y *yamuxAddr) String() string {
|
||||
return fmt.Sprintf("yamux:%s", y.Addr)
|
||||
}
|
||||
|
||||
// Addr is used to get the address of the listener.
|
||||
func (s *Session) Addr() net.Addr {
|
||||
return s.LocalAddr()
|
||||
}
|
||||
|
||||
// LocalAddr is used to get the local address of the
|
||||
// underlying connection.
|
||||
func (s *Session) LocalAddr() net.Addr {
|
||||
addr, ok := s.conn.(hasAddr)
|
||||
if !ok {
|
||||
return &yamuxAddr{"local"}
|
||||
}
|
||||
return addr.LocalAddr()
|
||||
}
|
||||
|
||||
// RemoteAddr is used to get the address of remote end
|
||||
// of the underlying connection
|
||||
func (s *Session) RemoteAddr() net.Addr {
|
||||
addr, ok := s.conn.(hasAddr)
|
||||
if !ok {
|
||||
return &yamuxAddr{"remote"}
|
||||
}
|
||||
return addr.RemoteAddr()
|
||||
}
|
||||
|
||||
// LocalAddr returns the local address
|
||||
func (s *Stream) LocalAddr() net.Addr {
|
||||
return s.session.LocalAddr()
|
||||
}
|
||||
|
||||
// LocalAddr returns the remote address
|
||||
func (s *Stream) RemoteAddr() net.Addr {
|
||||
return s.session.RemoteAddr()
|
||||
}
|
||||
157
vendor/github.com/hashicorp/yamux/const.go
generated
vendored
Normal file
@ -0,0 +1,157 @@
|
||||
package yamux
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidVersion means we received a frame with an
|
||||
// invalid version
|
||||
ErrInvalidVersion = fmt.Errorf("invalid protocol version")
|
||||
|
||||
// ErrInvalidMsgType means we received a frame with an
|
||||
// invalid message type
|
||||
ErrInvalidMsgType = fmt.Errorf("invalid msg type")
|
||||
|
||||
// ErrSessionShutdown is used if there is a shutdown during
|
||||
// an operation
|
||||
ErrSessionShutdown = fmt.Errorf("session shutdown")
|
||||
|
||||
// ErrStreamsExhausted is returned if we have no more
|
||||
// stream ids to issue
|
||||
ErrStreamsExhausted = fmt.Errorf("streams exhausted")
|
||||
|
||||
// ErrDuplicateStream is used if a duplicate stream is
|
||||
// opened inbound
|
||||
ErrDuplicateStream = fmt.Errorf("duplicate stream initiated")
|
||||
|
||||
// ErrReceiveWindowExceeded indicates the window was exceeded
|
||||
ErrRecvWindowExceeded = fmt.Errorf("recv window exceeded")
|
||||
|
||||
// ErrTimeout is used when we reach an IO deadline
|
||||
ErrTimeout = fmt.Errorf("i/o deadline reached")
|
||||
|
||||
// ErrStreamClosed is returned when using a closed stream
|
||||
ErrStreamClosed = fmt.Errorf("stream closed")
|
||||
|
||||
// ErrUnexpectedFlag is set when we get an unexpected flag
|
||||
ErrUnexpectedFlag = fmt.Errorf("unexpected flag")
|
||||
|
||||
// ErrRemoteGoAway is used when we get a go away from the other side
|
||||
ErrRemoteGoAway = fmt.Errorf("remote end is not accepting connections")
|
||||
|
||||
// ErrConnectionReset is sent if a stream is reset. This can happen
|
||||
// if the backlog is exceeded, or if there was a remote GoAway.
|
||||
ErrConnectionReset = fmt.Errorf("connection reset")
|
||||
|
||||
// ErrConnectionWriteTimeout indicates that we hit the "safety valve"
|
||||
// timeout writing to the underlying stream connection.
|
||||
ErrConnectionWriteTimeout = fmt.Errorf("connection write timeout")
|
||||
|
||||
// ErrKeepAliveTimeout is sent if a missed keepalive caused the stream close
|
||||
ErrKeepAliveTimeout = fmt.Errorf("keepalive timeout")
|
||||
)
|
||||
|
||||
const (
|
||||
// protoVersion is the only version we support
|
||||
protoVersion uint8 = 0
|
||||
)
|
||||
|
||||
const (
|
||||
// Data is used for data frames. They are followed
|
||||
// by length bytes worth of payload.
|
||||
typeData uint8 = iota
|
||||
|
||||
// WindowUpdate is used to change the window of
|
||||
// a given stream. The length indicates the delta
|
||||
// update to the window.
|
||||
typeWindowUpdate
|
||||
|
||||
// Ping is sent as a keep-alive or to measure
|
||||
// the RTT. The StreamID and Length value are echoed
|
||||
// back in the response.
|
||||
typePing
|
||||
|
||||
// GoAway is sent to terminate a session. The StreamID
|
||||
// should be 0 and the length is an error code.
|
||||
typeGoAway
|
||||
)
|
||||
|
||||
const (
|
||||
// SYN is sent to signal a new stream. May
|
||||
// be sent with a data payload
|
||||
flagSYN uint16 = 1 << iota
|
||||
|
||||
// ACK is sent to acknowledge a new stream. May
|
||||
// be sent with a data payload
|
||||
flagACK
|
||||
|
||||
// FIN is sent to half-close the given stream.
|
||||
// May be sent with a data payload.
|
||||
flagFIN
|
||||
|
||||
// RST is used to hard close a given stream.
|
||||
flagRST
|
||||
)
|
||||
|
||||
const (
|
||||
// initialStreamWindow is the initial stream window size
|
||||
initialStreamWindow uint32 = 256 * 1024
|
||||
)
|
||||
|
||||
const (
|
||||
// goAwayNormal is sent on a normal termination
|
||||
goAwayNormal uint32 = iota
|
||||
|
||||
// goAwayProtoErr sent on a protocol error
|
||||
goAwayProtoErr
|
||||
|
||||
// goAwayInternalErr sent on an internal error
|
||||
goAwayInternalErr
|
||||
)
|
||||
|
||||
const (
|
||||
sizeOfVersion = 1
|
||||
sizeOfType = 1
|
||||
sizeOfFlags = 2
|
||||
sizeOfStreamID = 4
|
||||
sizeOfLength = 4
|
||||
headerSize = sizeOfVersion + sizeOfType + sizeOfFlags +
|
||||
sizeOfStreamID + sizeOfLength
|
||||
)
|
||||
|
||||
type header []byte
|
||||
|
||||
func (h header) Version() uint8 {
|
||||
return h[0]
|
||||
}
|
||||
|
||||
func (h header) MsgType() uint8 {
|
||||
return h[1]
|
||||
}
|
||||
|
||||
func (h header) Flags() uint16 {
|
||||
return binary.BigEndian.Uint16(h[2:4])
|
||||
}
|
||||
|
||||
func (h header) StreamID() uint32 {
|
||||
return binary.BigEndian.Uint32(h[4:8])
|
||||
}
|
||||
|
||||
func (h header) Length() uint32 {
|
||||
return binary.BigEndian.Uint32(h[8:12])
|
||||
}
|
||||
|
||||
func (h header) String() string {
|
||||
return fmt.Sprintf("Vsn:%d Type:%d Flags:%d StreamID:%d Length:%d",
|
||||
h.Version(), h.MsgType(), h.Flags(), h.StreamID(), h.Length())
|
||||
}
|
||||
|
||||
func (h header) encode(msgType uint8, flags uint16, streamID uint32, length uint32) {
|
||||
h[0] = protoVersion
|
||||
h[1] = msgType
|
||||
binary.BigEndian.PutUint16(h[2:4], flags)
|
||||
binary.BigEndian.PutUint32(h[4:8], streamID)
|
||||
binary.BigEndian.PutUint32(h[8:12], length)
|
||||
}
|
||||
87
vendor/github.com/hashicorp/yamux/mux.go
generated
vendored
Normal file
@ -0,0 +1,87 @@
|
||||
package yamux
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config is used to tune the Yamux session
|
||||
type Config struct {
|
||||
// AcceptBacklog is used to limit how many streams may be
|
||||
// waiting an accept.
|
||||
AcceptBacklog int
|
||||
|
||||
// EnableKeepalive is used to do a period keep alive
|
||||
// messages using a ping.
|
||||
EnableKeepAlive bool
|
||||
|
||||
// KeepAliveInterval is how often to perform the keep alive
|
||||
KeepAliveInterval time.Duration
|
||||
|
||||
// ConnectionWriteTimeout is meant to be a "safety valve" timeout after
|
||||
// we which will suspect a problem with the underlying connection and
|
||||
// close it. This is only applied to writes, where's there's generally
|
||||
// an expectation that things will move along quickly.
|
||||
ConnectionWriteTimeout time.Duration
|
||||
|
||||
// MaxStreamWindowSize is used to control the maximum
|
||||
// window size that we allow for a stream.
|
||||
MaxStreamWindowSize uint32
|
||||
|
||||
// LogOutput is used to control the log destination
|
||||
LogOutput io.Writer
|
||||
}
|
||||
|
||||
// DefaultConfig is used to return a default configuration
|
||||
func DefaultConfig() *Config {
|
||||
return &Config{
|
||||
AcceptBacklog: 256,
|
||||
EnableKeepAlive: true,
|
||||
KeepAliveInterval: 30 * time.Second,
|
||||
ConnectionWriteTimeout: 10 * time.Second,
|
||||
MaxStreamWindowSize: initialStreamWindow,
|
||||
LogOutput: os.Stderr,
|
||||
}
|
||||
}
|
||||
|
||||
// VerifyConfig is used to verify the sanity of configuration
|
||||
func VerifyConfig(config *Config) error {
|
||||
if config.AcceptBacklog <= 0 {
|
||||
return fmt.Errorf("backlog must be positive")
|
||||
}
|
||||
if config.KeepAliveInterval == 0 {
|
||||
return fmt.Errorf("keep-alive interval must be positive")
|
||||
}
|
||||
if config.MaxStreamWindowSize < initialStreamWindow {
|
||||
return fmt.Errorf("MaxStreamWindowSize must be larger than %d", initialStreamWindow)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Server is used to initialize a new server-side connection.
|
||||
// There must be at most one server-side connection. If a nil config is
|
||||
// provided, the DefaultConfiguration will be used.
|
||||
func Server(conn io.ReadWriteCloser, config *Config) (*Session, error) {
|
||||
if config == nil {
|
||||
config = DefaultConfig()
|
||||
}
|
||||
if err := VerifyConfig(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newSession(config, conn, false), nil
|
||||
}
|
||||
|
||||
// Client is used to initialize a new client-side connection.
|
||||
// There must be at most one client-side connection.
|
||||
func Client(conn io.ReadWriteCloser, config *Config) (*Session, error) {
|
||||
if config == nil {
|
||||
config = DefaultConfig()
|
||||
}
|
||||
|
||||
if err := VerifyConfig(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newSession(config, conn, true), nil
|
||||
}
|
||||
648
vendor/github.com/hashicorp/yamux/session.go
generated
vendored
Normal file
@ -0,0 +1,648 @@
|
||||
package yamux
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"math"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Session is used to wrap a reliable ordered connection and to
|
||||
// multiplex it into multiple streams.
|
||||
type Session struct {
|
||||
// remoteGoAway indicates the remote side does
|
||||
// not want futher connections. Must be first for alignment.
|
||||
remoteGoAway int32
|
||||
|
||||
// localGoAway indicates that we should stop
|
||||
// accepting futher connections. Must be first for alignment.
|
||||
localGoAway int32
|
||||
|
||||
// nextStreamID is the next stream we should
|
||||
// send. This depends if we are a client/server.
|
||||
nextStreamID uint32
|
||||
|
||||
// config holds our configuration
|
||||
config *Config
|
||||
|
||||
// logger is used for our logs
|
||||
logger *log.Logger
|
||||
|
||||
// conn is the underlying connection
|
||||
conn io.ReadWriteCloser
|
||||
|
||||
// bufRead is a buffered reader
|
||||
bufRead *bufio.Reader
|
||||
|
||||
// pings is used to track inflight pings
|
||||
pings map[uint32]chan struct{}
|
||||
pingID uint32
|
||||
pingLock sync.Mutex
|
||||
|
||||
// streams maps a stream id to a stream, and inflight has an entry
|
||||
// for any outgoing stream that has not yet been established. Both are
|
||||
// protected by streamLock.
|
||||
streams map[uint32]*Stream
|
||||
inflight map[uint32]struct{}
|
||||
streamLock sync.Mutex
|
||||
|
||||
// synCh acts like a semaphore. It is sized to the AcceptBacklog which
|
||||
// is assumed to be symmetric between the client and server. This allows
|
||||
// the client to avoid exceeding the backlog and instead blocks the open.
|
||||
synCh chan struct{}
|
||||
|
||||
// acceptCh is used to pass ready streams to the client
|
||||
acceptCh chan *Stream
|
||||
|
||||
// sendCh is used to mark a stream as ready to send,
|
||||
// or to send a header out directly.
|
||||
sendCh chan sendReady
|
||||
|
||||
// recvDoneCh is closed when recv() exits to avoid a race
|
||||
// between stream registration and stream shutdown
|
||||
recvDoneCh chan struct{}
|
||||
|
||||
// shutdown is used to safely close a session
|
||||
shutdown bool
|
||||
shutdownErr error
|
||||
shutdownCh chan struct{}
|
||||
shutdownLock sync.Mutex
|
||||
}
|
||||
|
||||
// sendReady is used to either mark a stream as ready
|
||||
// or to directly send a header
|
||||
type sendReady struct {
|
||||
Hdr []byte
|
||||
Body io.Reader
|
||||
Err chan error
|
||||
}
|
||||
|
||||
// newSession is used to construct a new session
|
||||
func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session {
|
||||
s := &Session{
|
||||
config: config,
|
||||
logger: log.New(config.LogOutput, "", log.LstdFlags),
|
||||
conn: conn,
|
||||
bufRead: bufio.NewReader(conn),
|
||||
pings: make(map[uint32]chan struct{}),
|
||||
streams: make(map[uint32]*Stream),
|
||||
inflight: make(map[uint32]struct{}),
|
||||
synCh: make(chan struct{}, config.AcceptBacklog),
|
||||
acceptCh: make(chan *Stream, config.AcceptBacklog),
|
||||
sendCh: make(chan sendReady, 64),
|
||||
recvDoneCh: make(chan struct{}),
|
||||
shutdownCh: make(chan struct{}),
|
||||
}
|
||||
if client {
|
||||
s.nextStreamID = 1
|
||||
} else {
|
||||
s.nextStreamID = 2
|
||||
}
|
||||
go s.recv()
|
||||
go s.send()
|
||||
if config.EnableKeepAlive {
|
||||
go s.keepalive()
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// IsClosed does a safe check to see if we have shutdown
|
||||
func (s *Session) IsClosed() bool {
|
||||
select {
|
||||
case <-s.shutdownCh:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// CloseChan returns a read-only channel which is closed as
|
||||
// soon as the session is closed.
|
||||
func (s *Session) CloseChan() <-chan struct{} {
|
||||
return s.shutdownCh
|
||||
}
|
||||
|
||||
// NumStreams returns the number of currently open streams
|
||||
func (s *Session) NumStreams() int {
|
||||
s.streamLock.Lock()
|
||||
num := len(s.streams)
|
||||
s.streamLock.Unlock()
|
||||
return num
|
||||
}
|
||||
|
||||
// Open is used to create a new stream as a net.Conn
|
||||
func (s *Session) Open() (net.Conn, error) {
|
||||
conn, err := s.OpenStream()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// OpenStream is used to create a new stream
|
||||
func (s *Session) OpenStream() (*Stream, error) {
|
||||
if s.IsClosed() {
|
||||
return nil, ErrSessionShutdown
|
||||
}
|
||||
if atomic.LoadInt32(&s.remoteGoAway) == 1 {
|
||||
return nil, ErrRemoteGoAway
|
||||
}
|
||||
|
||||
// Block if we have too many inflight SYNs
|
||||
select {
|
||||
case s.synCh <- struct{}{}:
|
||||
case <-s.shutdownCh:
|
||||
return nil, ErrSessionShutdown
|
||||
}
|
||||
|
||||
GET_ID:
|
||||
// Get an ID, and check for stream exhaustion
|
||||
id := atomic.LoadUint32(&s.nextStreamID)
|
||||
if id >= math.MaxUint32-1 {
|
||||
return nil, ErrStreamsExhausted
|
||||
}
|
||||
if !atomic.CompareAndSwapUint32(&s.nextStreamID, id, id+2) {
|
||||
goto GET_ID
|
||||
}
|
||||
|
||||
// Register the stream
|
||||
stream := newStream(s, id, streamInit)
|
||||
s.streamLock.Lock()
|
||||
s.streams[id] = stream
|
||||
s.inflight[id] = struct{}{}
|
||||
s.streamLock.Unlock()
|
||||
|
||||
// Send the window update to create
|
||||
if err := stream.sendWindowUpdate(); err != nil {
|
||||
select {
|
||||
case <-s.synCh:
|
||||
default:
|
||||
s.logger.Printf("[ERR] yamux: aborted stream open without inflight syn semaphore")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return stream, nil
|
||||
}
|
||||
|
||||
// Accept is used to block until the next available stream
|
||||
// is ready to be accepted.
|
||||
func (s *Session) Accept() (net.Conn, error) {
|
||||
conn, err := s.AcceptStream()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return conn, err
|
||||
}
|
||||
|
||||
// AcceptStream is used to block until the next available stream
|
||||
// is ready to be accepted.
|
||||
func (s *Session) AcceptStream() (*Stream, error) {
|
||||
select {
|
||||
case stream := <-s.acceptCh:
|
||||
if err := stream.sendWindowUpdate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return stream, nil
|
||||
case <-s.shutdownCh:
|
||||
return nil, s.shutdownErr
|
||||
}
|
||||
}
|
||||
|
||||
// Close is used to close the session and all streams.
|
||||
// Attempts to send a GoAway before closing the connection.
|
||||
func (s *Session) Close() error {
|
||||
s.shutdownLock.Lock()
|
||||
defer s.shutdownLock.Unlock()
|
||||
|
||||
if s.shutdown {
|
||||
return nil
|
||||
}
|
||||
s.shutdown = true
|
||||
if s.shutdownErr == nil {
|
||||
s.shutdownErr = ErrSessionShutdown
|
||||
}
|
||||
close(s.shutdownCh)
|
||||
s.conn.Close()
|
||||
<-s.recvDoneCh
|
||||
|
||||
s.streamLock.Lock()
|
||||
defer s.streamLock.Unlock()
|
||||
for _, stream := range s.streams {
|
||||
stream.forceClose()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// exitErr is used to handle an error that is causing the
|
||||
// session to terminate.
|
||||
func (s *Session) exitErr(err error) {
|
||||
s.shutdownLock.Lock()
|
||||
if s.shutdownErr == nil {
|
||||
s.shutdownErr = err
|
||||
}
|
||||
s.shutdownLock.Unlock()
|
||||
s.Close()
|
||||
}
|
||||
|
||||
// GoAway can be used to prevent accepting further
|
||||
// connections. It does not close the underlying conn.
|
||||
func (s *Session) GoAway() error {
|
||||
return s.waitForSend(s.goAway(goAwayNormal), nil)
|
||||
}
|
||||
|
||||
// goAway is used to send a goAway message
|
||||
func (s *Session) goAway(reason uint32) header {
|
||||
atomic.SwapInt32(&s.localGoAway, 1)
|
||||
hdr := header(make([]byte, headerSize))
|
||||
hdr.encode(typeGoAway, 0, 0, reason)
|
||||
return hdr
|
||||
}
|
||||
|
||||
// Ping is used to measure the RTT response time
|
||||
func (s *Session) Ping() (time.Duration, error) {
|
||||
// Get a channel for the ping
|
||||
ch := make(chan struct{})
|
||||
|
||||
// Get a new ping id, mark as pending
|
||||
s.pingLock.Lock()
|
||||
id := s.pingID
|
||||
s.pingID++
|
||||
s.pings[id] = ch
|
||||
s.pingLock.Unlock()
|
||||
|
||||
// Send the ping request
|
||||
hdr := header(make([]byte, headerSize))
|
||||
hdr.encode(typePing, flagSYN, 0, id)
|
||||
if err := s.waitForSend(hdr, nil); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
// Wait for a response
|
||||
start := time.Now()
|
||||
select {
|
||||
case <-ch:
|
||||
case <-time.After(s.config.ConnectionWriteTimeout):
|
||||
s.pingLock.Lock()
|
||||
delete(s.pings, id) // Ignore it if a response comes later.
|
||||
s.pingLock.Unlock()
|
||||
return 0, ErrTimeout
|
||||
case <-s.shutdownCh:
|
||||
return 0, ErrSessionShutdown
|
||||
}
|
||||
|
||||
// Compute the RTT
|
||||
return time.Now().Sub(start), nil
|
||||
}
|
||||
|
||||
// keepalive is a long running goroutine that periodically does
|
||||
// a ping to keep the connection alive.
|
||||
func (s *Session) keepalive() {
|
||||
for {
|
||||
select {
|
||||
case <-time.After(s.config.KeepAliveInterval):
|
||||
_, err := s.Ping()
|
||||
if err != nil {
|
||||
if err != ErrSessionShutdown {
|
||||
s.logger.Printf("[ERR] yamux: keepalive failed: %v", err)
|
||||
s.exitErr(ErrKeepAliveTimeout)
|
||||
}
|
||||
return
|
||||
}
|
||||
case <-s.shutdownCh:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// waitForSendErr waits to send a header, checking for a potential shutdown
|
||||
func (s *Session) waitForSend(hdr header, body io.Reader) error {
|
||||
errCh := make(chan error, 1)
|
||||
return s.waitForSendErr(hdr, body, errCh)
|
||||
}
|
||||
|
||||
// waitForSendErr waits to send a header with optional data, checking for a
|
||||
// potential shutdown. Since there's the expectation that sends can happen
|
||||
// in a timely manner, we enforce the connection write timeout here.
|
||||
func (s *Session) waitForSendErr(hdr header, body io.Reader, errCh chan error) error {
|
||||
t := timerPool.Get()
|
||||
timer := t.(*time.Timer)
|
||||
timer.Reset(s.config.ConnectionWriteTimeout)
|
||||
defer func() {
|
||||
timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
default:
|
||||
}
|
||||
timerPool.Put(t)
|
||||
}()
|
||||
|
||||
ready := sendReady{Hdr: hdr, Body: body, Err: errCh}
|
||||
select {
|
||||
case s.sendCh <- ready:
|
||||
case <-s.shutdownCh:
|
||||
return ErrSessionShutdown
|
||||
case <-timer.C:
|
||||
return ErrConnectionWriteTimeout
|
||||
}
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
return err
|
||||
case <-s.shutdownCh:
|
||||
return ErrSessionShutdown
|
||||
case <-timer.C:
|
||||
return ErrConnectionWriteTimeout
|
||||
}
|
||||
}
|
||||
|
||||
// sendNoWait does a send without waiting. Since there's the expectation that
|
||||
// the send happens right here, we enforce the connection write timeout if we
|
||||
// can't queue the header to be sent.
|
||||
func (s *Session) sendNoWait(hdr header) error {
|
||||
t := timerPool.Get()
|
||||
timer := t.(*time.Timer)
|
||||
timer.Reset(s.config.ConnectionWriteTimeout)
|
||||
defer func() {
|
||||
timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
default:
|
||||
}
|
||||
timerPool.Put(t)
|
||||
}()
|
||||
|
||||
select {
|
||||
case s.sendCh <- sendReady{Hdr: hdr}:
|
||||
return nil
|
||||
case <-s.shutdownCh:
|
||||
return ErrSessionShutdown
|
||||
case <-timer.C:
|
||||
return ErrConnectionWriteTimeout
|
||||
}
|
||||
}
|
||||
|
||||
// send is a long running goroutine that sends data
|
||||
func (s *Session) send() {
|
||||
for {
|
||||
select {
|
||||
case ready := <-s.sendCh:
|
||||
// Send a header if ready
|
||||
if ready.Hdr != nil {
|
||||
sent := 0
|
||||
for sent < len(ready.Hdr) {
|
||||
n, err := s.conn.Write(ready.Hdr[sent:])
|
||||
if err != nil {
|
||||
s.logger.Printf("[ERR] yamux: Failed to write header: %v", err)
|
||||
asyncSendErr(ready.Err, err)
|
||||
s.exitErr(err)
|
||||
return
|
||||
}
|
||||
sent += n
|
||||
}
|
||||
}
|
||||
|
||||
// Send data from a body if given
|
||||
if ready.Body != nil {
|
||||
_, err := io.Copy(s.conn, ready.Body)
|
||||
if err != nil {
|
||||
s.logger.Printf("[ERR] yamux: Failed to write body: %v", err)
|
||||
asyncSendErr(ready.Err, err)
|
||||
s.exitErr(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// No error, successful send
|
||||
asyncSendErr(ready.Err, nil)
|
||||
case <-s.shutdownCh:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// recv is a long running goroutine that accepts new data
|
||||
func (s *Session) recv() {
|
||||
if err := s.recvLoop(); err != nil {
|
||||
s.exitErr(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure that the index of the handler (typeData/typeWindowUpdate/etc) matches the message type
|
||||
var (
|
||||
handlers = []func(*Session, header) error{
|
||||
typeData: (*Session).handleStreamMessage,
|
||||
typeWindowUpdate: (*Session).handleStreamMessage,
|
||||
typePing: (*Session).handlePing,
|
||||
typeGoAway: (*Session).handleGoAway,
|
||||
}
|
||||
)
|
||||
|
||||
// recvLoop continues to receive data until a fatal error is encountered
|
||||
func (s *Session) recvLoop() error {
|
||||
defer close(s.recvDoneCh)
|
||||
hdr := header(make([]byte, headerSize))
|
||||
for {
|
||||
// Read the header
|
||||
if _, err := io.ReadFull(s.bufRead, hdr); err != nil {
|
||||
if err != io.EOF && !strings.Contains(err.Error(), "closed") && !strings.Contains(err.Error(), "reset by peer") {
|
||||
s.logger.Printf("[ERR] yamux: Failed to read header: %v", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Verify the version
|
||||
if hdr.Version() != protoVersion {
|
||||
s.logger.Printf("[ERR] yamux: Invalid protocol version: %d", hdr.Version())
|
||||
return ErrInvalidVersion
|
||||
}
|
||||
|
||||
mt := hdr.MsgType()
|
||||
if mt < typeData || mt > typeGoAway {
|
||||
return ErrInvalidMsgType
|
||||
}
|
||||
|
||||
if err := handlers[mt](s, hdr); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleStreamMessage handles either a data or window update frame
|
||||
func (s *Session) handleStreamMessage(hdr header) error {
|
||||
// Check for a new stream creation
|
||||
id := hdr.StreamID()
|
||||
flags := hdr.Flags()
|
||||
if flags&flagSYN == flagSYN {
|
||||
if err := s.incomingStream(id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Get the stream
|
||||
s.streamLock.Lock()
|
||||
stream := s.streams[id]
|
||||
s.streamLock.Unlock()
|
||||
|
||||
// If we do not have a stream, likely we sent a RST
|
||||
if stream == nil {
|
||||
// Drain any data on the wire
|
||||
if hdr.MsgType() == typeData && hdr.Length() > 0 {
|
||||
s.logger.Printf("[WARN] yamux: Discarding data for stream: %d", id)
|
||||
if _, err := io.CopyN(ioutil.Discard, s.bufRead, int64(hdr.Length())); err != nil {
|
||||
s.logger.Printf("[ERR] yamux: Failed to discard data: %v", err)
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
s.logger.Printf("[WARN] yamux: frame for missing stream: %v", hdr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Check if this is a window update
|
||||
if hdr.MsgType() == typeWindowUpdate {
|
||||
if err := stream.incrSendWindow(hdr, flags); err != nil {
|
||||
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
|
||||
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Read the new data
|
||||
if err := stream.readData(hdr, flags, s.bufRead); err != nil {
|
||||
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
|
||||
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// handlePing is invokde for a typePing frame
|
||||
func (s *Session) handlePing(hdr header) error {
|
||||
flags := hdr.Flags()
|
||||
pingID := hdr.Length()
|
||||
|
||||
// Check if this is a query, respond back in a separate context so we
|
||||
// don't interfere with the receiving thread blocking for the write.
|
||||
if flags&flagSYN == flagSYN {
|
||||
go func() {
|
||||
hdr := header(make([]byte, headerSize))
|
||||
hdr.encode(typePing, flagACK, 0, pingID)
|
||||
if err := s.sendNoWait(hdr); err != nil {
|
||||
s.logger.Printf("[WARN] yamux: failed to send ping reply: %v", err)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Handle a response
|
||||
s.pingLock.Lock()
|
||||
ch := s.pings[pingID]
|
||||
if ch != nil {
|
||||
delete(s.pings, pingID)
|
||||
close(ch)
|
||||
}
|
||||
s.pingLock.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleGoAway is invokde for a typeGoAway frame
|
||||
func (s *Session) handleGoAway(hdr header) error {
|
||||
code := hdr.Length()
|
||||
switch code {
|
||||
case goAwayNormal:
|
||||
atomic.SwapInt32(&s.remoteGoAway, 1)
|
||||
case goAwayProtoErr:
|
||||
s.logger.Printf("[ERR] yamux: received protocol error go away")
|
||||
return fmt.Errorf("yamux protocol error")
|
||||
case goAwayInternalErr:
|
||||
s.logger.Printf("[ERR] yamux: received internal error go away")
|
||||
return fmt.Errorf("remote yamux internal error")
|
||||
default:
|
||||
s.logger.Printf("[ERR] yamux: received unexpected go away")
|
||||
return fmt.Errorf("unexpected go away received")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// incomingStream is used to create a new incoming stream
|
||||
func (s *Session) incomingStream(id uint32) error {
|
||||
// Reject immediately if we are doing a go away
|
||||
if atomic.LoadInt32(&s.localGoAway) == 1 {
|
||||
hdr := header(make([]byte, headerSize))
|
||||
hdr.encode(typeWindowUpdate, flagRST, id, 0)
|
||||
return s.sendNoWait(hdr)
|
||||
}
|
||||
|
||||
// Allocate a new stream
|
||||
stream := newStream(s, id, streamSYNReceived)
|
||||
|
||||
s.streamLock.Lock()
|
||||
defer s.streamLock.Unlock()
|
||||
|
||||
// Check if stream already exists
|
||||
if _, ok := s.streams[id]; ok {
|
||||
s.logger.Printf("[ERR] yamux: duplicate stream declared")
|
||||
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
|
||||
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
|
||||
}
|
||||
return ErrDuplicateStream
|
||||
}
|
||||
|
||||
// Register the stream
|
||||
s.streams[id] = stream
|
||||
|
||||
// Check if we've exceeded the backlog
|
||||
select {
|
||||
case s.acceptCh <- stream:
|
||||
return nil
|
||||
default:
|
||||
// Backlog exceeded! RST the stream
|
||||
s.logger.Printf("[WARN] yamux: backlog exceeded, forcing connection reset")
|
||||
delete(s.streams, id)
|
||||
stream.sendHdr.encode(typeWindowUpdate, flagRST, id, 0)
|
||||
return s.sendNoWait(stream.sendHdr)
|
||||
}
|
||||
}
|
||||
|
||||
// closeStream is used to close a stream once both sides have
|
||||
// issued a close. If there was an in-flight SYN and the stream
|
||||
// was not yet established, then this will give the credit back.
|
||||
func (s *Session) closeStream(id uint32) {
|
||||
s.streamLock.Lock()
|
||||
if _, ok := s.inflight[id]; ok {
|
||||
select {
|
||||
case <-s.synCh:
|
||||
default:
|
||||
s.logger.Printf("[ERR] yamux: SYN tracking out of sync")
|
||||
}
|
||||
}
|
||||
delete(s.streams, id)
|
||||
s.streamLock.Unlock()
|
||||
}
|
||||
|
||||
// establishStream is used to mark a stream that was in the
|
||||
// SYN Sent state as established.
|
||||
func (s *Session) establishStream(id uint32) {
|
||||
s.streamLock.Lock()
|
||||
if _, ok := s.inflight[id]; ok {
|
||||
delete(s.inflight, id)
|
||||
} else {
|
||||
s.logger.Printf("[ERR] yamux: established stream without inflight SYN (no tracking entry)")
|
||||
}
|
||||
select {
|
||||
case <-s.synCh:
|
||||
default:
|
||||
s.logger.Printf("[ERR] yamux: established stream without inflight SYN (didn't have semaphore)")
|
||||
}
|
||||
s.streamLock.Unlock()
|
||||
}
|
||||
140
vendor/github.com/hashicorp/yamux/spec.md
generated
vendored
Normal file
@ -0,0 +1,140 @@
|
||||
# Specification
|
||||
|
||||
We use this document to detail the internal specification of Yamux.
|
||||
This is used both as a guide for implementing Yamux, but also for
|
||||
alternative interoperable libraries to be built.
|
||||
|
||||
# Framing
|
||||
|
||||
Yamux uses a streaming connection underneath, but imposes a message
|
||||
framing so that it can be shared between many logical streams. Each
|
||||
frame contains a header like:
|
||||
|
||||
* Version (8 bits)
|
||||
* Type (8 bits)
|
||||
* Flags (16 bits)
|
||||
* StreamID (32 bits)
|
||||
* Length (32 bits)
|
||||
|
||||
This means that each header has a 12 byte overhead.
|
||||
All fields are encoded in network order (big endian).
|
||||
Each field is described below:
|
||||
|
||||
## Version Field
|
||||
|
||||
The version field is used for future backward compatibility. At the
|
||||
current time, the field is always set to 0, to indicate the initial
|
||||
version.
|
||||
|
||||
## Type Field
|
||||
|
||||
The type field is used to switch the frame message type. The following
|
||||
message types are supported:
|
||||
|
||||
* 0x0 Data - Used to transmit data. May transmit zero length payloads
|
||||
depending on the flags.
|
||||
|
||||
* 0x1 Window Update - Used to updated the senders receive window size.
|
||||
This is used to implement per-session flow control.
|
||||
|
||||
* 0x2 Ping - Used to measure RTT. It can also be used to heart-beat
|
||||
and do keep-alives over TCP.
|
||||
|
||||
* 0x3 Go Away - Used to close a session.
|
||||
|
||||
## Flag Field
|
||||
|
||||
The flags field is used to provide additional information related
|
||||
to the message type. The following flags are supported:
|
||||
|
||||
* 0x1 SYN - Signals the start of a new stream. May be sent with a data or
|
||||
window update message. Also sent with a ping to indicate outbound.
|
||||
|
||||
* 0x2 ACK - Acknowledges the start of a new stream. May be sent with a data
|
||||
or window update message. Also sent with a ping to indicate response.
|
||||
|
||||
* 0x4 FIN - Performs a half-close of a stream. May be sent with a data
|
||||
message or window update.
|
||||
|
||||
* 0x8 RST - Reset a stream immediately. May be sent with a data or
|
||||
window update message.
|
||||
|
||||
## StreamID Field
|
||||
|
||||
The StreamID field is used to identify the logical stream the frame
|
||||
is addressing. The client side should use odd ID's, and the server even.
|
||||
This prevents any collisions. Additionally, the 0 ID is reserved to represent
|
||||
the session.
|
||||
|
||||
Both Ping and Go Away messages should always use the 0 StreamID.
|
||||
|
||||
## Length Field
|
||||
|
||||
The meaning of the length field depends on the message type:
|
||||
|
||||
* Data - provides the length of bytes following the header
|
||||
* Window update - provides a delta update to the window size
|
||||
* Ping - Contains an opaque value, echoed back
|
||||
* Go Away - Contains an error code
|
||||
|
||||
# Message Flow
|
||||
|
||||
There is no explicit connection setup, as Yamux relies on an underlying
|
||||
transport to be provided. However, there is a distinction between client
|
||||
and server side of the connection.
|
||||
|
||||
## Opening a stream
|
||||
|
||||
To open a stream, an initial data or window update frame is sent
|
||||
with a new StreamID. The SYN flag should be set to signal a new stream.
|
||||
|
||||
The receiver must then reply with either a data or window update frame
|
||||
with the StreamID along with the ACK flag to accept the stream or with
|
||||
the RST flag to reject the stream.
|
||||
|
||||
Because we are relying on the reliable stream underneath, a connection
|
||||
can begin sending data once the SYN flag is sent. The corresponding
|
||||
ACK does not need to be received. This is particularly well suited
|
||||
for an RPC system where a client wants to open a stream and immediately
|
||||
fire a request without waiting for the RTT of the ACK.
|
||||
|
||||
This does introduce the possibility of a connection being rejected
|
||||
after data has been sent already. This is a slight semantic difference
|
||||
from TCP, where the conection cannot be refused after it is opened.
|
||||
Clients should be prepared to handle this by checking for an error
|
||||
that indicates a RST was received.
|
||||
|
||||
## Closing a stream
|
||||
|
||||
To close a stream, either side sends a data or window update frame
|
||||
along with the FIN flag. This does a half-close indicating the sender
|
||||
will send no further data.
|
||||
|
||||
Once both sides have closed the connection, the stream is closed.
|
||||
|
||||
Alternatively, if an error occurs, the RST flag can be used to
|
||||
hard close a stream immediately.
|
||||
|
||||
## Flow Control
|
||||
|
||||
When Yamux is initially starts each stream with a 256KB window size.
|
||||
There is no window size for the session.
|
||||
|
||||
To prevent the streams from stalling, window update frames should be
|
||||
sent regularly. Yamux can be configured to provide a larger limit for
|
||||
windows sizes. Both sides assume the initial 256KB window, but can
|
||||
immediately send a window update as part of the SYN/ACK indicating a
|
||||
larger window.
|
||||
|
||||
Both sides should track the number of bytes sent in Data frames
|
||||
only, as only they are tracked as part of the window size.
|
||||
|
||||
## Session termination
|
||||
|
||||
When a session is being terminated, the Go Away message should
|
||||
be sent. The Length should be set to one of the following to
|
||||
provide an error code:
|
||||
|
||||
* 0x0 Normal termination
|
||||
* 0x1 Protocol error
|
||||
* 0x2 Internal error
|
||||