Compare commits

...
245 Commits
Author SHA1 Message Date
yisier ab81f5b68e API 鉴权漏洞修复 2022-12-30 12:24:48 +08:00
yisier ae2010c984 version 0.26.13 2022-12-19 17:40:38 +08:00
yisier b7aee56575 修复:某些场景下丢包导致服务端意外退出
优化:新增隧道时,不指定服务端口时,将自动生成端口号
优化:API返回ID, /client/add/, /index/addhost/,/index/add/
优化:域名解析、隧道页面,增加[唯一验证密钥],方便搜查
2022-12-19 17:39:29 +08:00
yisier 5145273283 Merge pull request #20 from Mrdotdotdot/master
Update socks5.go
2022-11-09 14:18:06 +08:00
dotdotdot 8a2a142ddb Update socks5.go
修复:开启socks5多用户,个别sockes5客户端使用空用户名或空密码可以连接成功
2022-11-09 11:47:25 +08:00
yisier 3808aa38db http 连接释放优化 2022-11-08 14:55:27 +08:00
yisier 021b97045b Update pkg.yml 2022-11-04 17:42:21 +08:00
yisier da79a8a1d1 Delete release.yml 2022-11-04 17:41:46 +08:00
yisier 9d0edc5663 Update README.md 2022-11-04 17:26:14 +08:00
yisier e94acba817 action test 2022-11-04 17:05:46 +08:00
yisier 6dda9a7d4c Merge remote-tracking branch 'origin/master' 2022-11-04 17:04:40 +08:00
yisier 50757324fb Update docker.yml 2022-11-04 17:02:31 +08:00
yisier 7ed25bf8be Update docker.yml 2022-11-04 17:02:13 +08:00
yisier f4d7ed0842 判断connection 是否为http协议 2022-11-04 17:00:56 +08:00
yisier a58ebd2c83 action test 2022-11-04 16:59:34 +08:00
yisier fc02709aea Update release.yml 2022-11-04 16:45:49 +08:00
yisier 6a2570b794 Update release.yml 2022-11-04 16:40:59 +08:00
yisier 0b379afd38 action test 2022-11-04 16:19:01 +08:00
yisier 1f3b145a8c Create docker.yml 2022-11-04 16:03:11 +08:00
yisier 8c5c0a8737 docker test 2022-11-04 15:25:45 +08:00
yisier f1e579eeef Create docker.yml 2022-11-04 15:23:48 +08:00
yisier f7d86c524d 修改http协议无法响应bug 2022-11-04 14:53:34 +08:00
yisier 00315a8892 client bug fix 2022-11-01 14:35:13 +08:00
yisier 8be1e9f865 工作目录bug修复 2022-10-31 10:40:47 +08:00
yisier c0667e2dca Update README.md 2022-10-30 00:45:51 +08:00
yisier ccd9cede1b rollback install server 2022-10-30 00:36:03 +08:00
yisier 91d5a35981 add black ip 2022-10-29 23:59:53 +08:00
yisier 7b1774308f IP 黑名单 2022-10-28 18:01:21 +08:00
yisier d0a958426f 判断connection 是否为http协议 2022-10-28 13:35:59 +08:00
yisier 4d21655a1e Update README.md 2022-10-27 13:40:46 +08:00
yiser 1eb10e3882 在管理面板登录时开启验证码校验 2022-10-27 13:39:29 +08:00
yiser fa447891be Merge remote-tracking branch 'origin/master' 2022-10-27 13:29:16 +08:00
yisier a403246ee0 Merge pull request #4 from dongFangTuring/dev
Added verification code function to prevent blasting
2022-10-27 13:28:49 +08:00
yiser eb131757ac Merge remote-tracking branch 'origin/master' 2022-10-27 11:55:42 +08:00
yiser 3b1923bbfd Update version 2022-10-27 11:55:29 +08:00
陈东方 5a16772d13 Merge pull request #1 from yisier/master
merge yisier nps
2022-10-26 18:09:29 +08:00
yisier 3f728b2f9d Update pkg.yml 2022-10-25 10:40:25 +08:00
yisier ed3fc3beb4 Update release.yml 2022-10-25 10:37:54 +08:00
yisier 57f080cab5 Create pkg.yml 2022-10-25 10:14:35 +08:00
yisier 4ccdd28f29 Delete go.yml 2022-10-25 10:14:04 +08:00
yisier ed7884b0e0 Create go.yml 2022-10-25 09:52:05 +08:00
yiser d35bde9123 http协议不支持websocket 2022-10-24 16:35:59 +08:00
yiser b0611fc007 web socket TODO 2022-10-24 16:34:01 +08:00
yiser dea5b3d558 web socket TODO 2022-10-21 18:01:37 +08:00
yiser ccb27f0253 HTTP 流量控制 2022-10-21 14:41:01 +08:00
yiser 302a5c52d2 HTTP 流量控制 2022-10-21 14:40:07 +08:00
yiser 648f61c1b7 HTTP 流量控制 2022-10-21 14:39:19 +08:00
yiser 07b20bd29d HTTP 流量控制 2022-10-21 14:38:57 +08:00
yiser eef3686fff HTTP 流量控制 2022-10-21 14:36:27 +08:00
yiser 329d8dd44d HTTP 流量控制 2022-10-21 14:33:55 +08:00
yiser 859fbf70e3 TCP 流量控制 2022-10-20 14:11:56 +08:00
yiser cd8fe01cf4 上下行对等 2022-10-20 09:41:22 +08:00
yiser b6d62cf8ac md 2022-10-19 17:48:04 +08:00
yiser 1c58c6f131 修复:TCP协议下实时统计流量,能够精准的限制住流量(出入流量对等)
优化:删除TCP隧道时,客户端已用流量不再清空
2022-10-19 17:46:42 +08:00
yiser f6a93ef531 修改工作目录为当前可执行文件目录,去除注册系统服务,启动、停止、升级等命令 2022-09-14 18:01:11 +08:00
Jireh 7aaa831589 add server stop log detail info 2021-10-15 10:52:16 +08:00
he liu ab648d6f0c Merge pull request #866 from freeoa/master
add build to apple silicon(M1)
2021-10-09 15:18:41 +08:00
he liu 8257673d2d Merge branch 'master' of https://github.com/ehang-io/nps 2021-10-08 00:29:38 +08:00
he liu f1793a740e change syno build 2021-10-08 00:29:30 +08:00
he liu 92c06df0c0 Merge pull request #839 from lidenggao/patch-1
Update nps_extend.md
2021-10-07 23:02:54 +08:00
he liu 968d03d58b Merge pull request #807 from geek981108/fix
fix: 🐛 fix wrong api response
2021-10-07 23:00:41 +08:00
chirs c6fcb444ab add build to apple silicon(M1)
add build release package for Apple silicon
2021-09-03 15:46:40 +08:00
CoLee 5107fdfe6c Update nps_extend.md
更新HTTPS文档
2021-07-13 17:00:06 +08:00
Jireh_Lin 1f8b1f2e89 Merge pull request #1 from Jireh012/master
merge to deb
2021-06-29 14:31:24 +08:00
Jireh 76975bd75c Added verification code function to prevent blasting 2021-06-29 13:51:05 +08:00
GeekXu 4f6b35d38d fix: 🐛 fix wrong api response
fix wrong api response

✅ Closes: #806
2021-05-23 01:05:08 +08:00
ffdfgdfg c9a4d8285b Merge pull request #772 from ehang-io/dev
Dev
2021-04-08 14:06:28 +08:00
ffdfgdfg 2b68fbdc13 bump version to 0.26.10, close #595 close #674 2021-04-08 04:01:39 +08:00
ffdfgdfg 09e69c7202 change android build script 2021-04-08 03:53:22 +08:00
ffdfgdfg 36d858d1c7 change sdk to block function call, close #480, close #745 2021-04-08 02:40:32 +08:00
ffdfgdfg 96188ee6ed change client closed text 2021-04-08 02:25:46 +08:00
ffdfgdfg 5c13ceecc8 update android package to v2 2021-04-08 02:24:47 +08:00
ffdfgdfg cb8464f4a8 add android auto reconnect 2021-04-08 02:09:46 +08:00
ffdfgdfg d251431baa update android package 2021-04-08 01:59:48 +08:00
ffdfgdfg 1c9424c4ba update go version 2021-04-07 21:38:43 +08:00
ffdfgdfg 9142347855 update package snappy 2021-04-07 21:35:36 +08:00
ffdfgdfg 0518995921 update package kcp, fix some arm device crash by cpuid package, fix #652, fix #677, fix #719, fix #708 2021-04-07 21:33:56 +08:00
ffdfgdfg e4e342397c update mux 2021-04-07 21:13:31 +08:00
ffdfgdfg bebb6e989b update psutil 2021-04-07 20:02:47 +08:00
ffdfgdfg f8dc745aa2 update service, close #407 2021-04-07 19:25:08 +08:00
ffdfgdfg 9d5c3fd870 Merge pull request #750 from hellodword/patch-1
enable comment of conf titles
2021-04-07 18:39:48 +08:00
ffdfgdfg d331db723b Merge pull request #764 from caiych/noauth-better
skip the login window if web_username/password is empty
2021-04-07 17:11:40 +08:00
caiych e2d85edbfb Extract login logic from Verify. Also try an implicit login in /login/index -- to skip the login window if web_username/password is empty. 2021-03-19 08:40:25 +00:00
hellodword f08d2eb500 enable comment of conf titles 2021-02-14 10:49:48 +08:00
ffdfgdfg 3433d32457 Merge pull request #666 from tianjindong/patch-1
Update server_config.md
2021-02-08 19:40:05 +08:00
ffdfgdfg 371c2ab1c0 Merge pull request #727 from wuhanstudio/fix-login-page
Improving the login page
2021-02-08 19:39:41 +08:00
Wu Han ef3315233e [fix] justify lists 2021-01-11 16:42:18 +00:00
Wu Han 9dd569be36 [fix] justify two columns 2021-01-11 16:37:55 +00:00
Wu Han 50b006bf72 [fix] set header space using bootstrap mt-3 2021-01-11 16:37:18 +00:00
Wu Han ad571da40d [fix] add extra space between tables 2021-01-11 16:34:37 +00:00
HearingSmile 75d13b0649 Update server_config.md
更改配置文件位置说明
2020-10-24 09:25:13 +08:00
ffdfgdfg d1bbbdf67a Merge pull request #650 from ehang-io/master
merge ci, readme
2020-10-07 14:46:22 +08:00
ffdfgdfg 63ba9774f9 change build status 2020-10-07 14:44:23 +08:00
ffdfgdfg f8a22a5013 Merge pull request #649 from clh021/patch-1
Update README.md
2020-10-07 14:37:13 +08:00
chenlianghong d3ce4e7491 Update README.md
Fix Qunhui to Synology
2020-10-07 12:07:59 +08:00
ffdfgdfg a8a0a1d65d Update release.yml 2020-10-06 17:54:12 +08:00
ffdfgdfg b7d7d9eccc Update release.yml 2020-10-06 17:30:36 +08:00
ffdfgdfg 3bed88a75d Update release.yml 2020-10-06 16:45:20 +08:00
ffdfgdfg a01e0100ed fine ci 2020-10-06 16:25:20 +08:00
ffdfgdfg e4215735f5 Create release.yml 2020-10-06 16:18:29 +08:00
ffdfgdfg 754714b381 Merge pull request #648 from ehang-io/dev
Dev
2020-10-06 02:35:13 +08:00
ffdfgdfg 9e56409063 bump version to 0.26.9, fix #576 fix #572 2020-10-06 02:33:26 +08:00
ffdfgdfg 2c3126c489 show raw error msg on web, fix #524, fix #636 2020-10-06 01:26:47 +08:00
ffdfgdfg b5c0b4d895 show id in proxy edit page 2020-10-06 01:15:29 +08:00
ffdfgdfg 720f842d4b fix http cache panic, fix #626, fix #509 2020-10-06 00:57:10 +08:00
ffdfgdfg 5224307da7 fix snappy not close connection, fix #456, fix #584, fix #600 2020-10-06 00:28:33 +08:00
ffdfgdfg d7de698fc8 Revert "remove docker arm, 386 image"
This reverts commit d4f3e46277.
2020-10-05 23:47:42 +08:00
ffdfgdfg 894d0c7503 add tcp keep alive option for signal connections 2020-10-05 23:38:46 +08:00
ffdfgdfg b4604bc4da fix gui build 2020-10-05 21:39:54 +08:00
ffdfgdfg bc60a0f184 bump golang to 1.14 2020-10-05 20:19:35 +08:00
ffdfgdfg 40bc744ea6 update dependencies 2020-10-05 20:17:44 +08:00
ffdfgdfg 22e1eabb55 Merge pull request #613 from xiexiao/master
Windows服务运行npc时读取程序目录下的config文件
2020-10-05 19:25:19 +08:00
xiexiao d43cbde1f6 Windows服务运行npc时读取程序目录下的config文件 2020-08-22 13:14:34 +08:00
ffdfgdfg acffdd76a1 freeze docker build image version 2020-07-01 21:40:55 +08:00
ffdfgdfg c7720066ec bump fyne version, change android build image to official, fix #572 2020-06-18 19:46:10 +08:00
ffdfgdfg 54743588bb Merge pull request #571 from ehang-io/dev
Dev
2020-06-18 00:12:22 +08:00
ffdfgdfg 0d4c13e0a5 bump version to 0.26.8 2020-06-18 00:05:27 +08:00
ffdfgdfg f95c25cf73 bump mux version, fix conn.Close block, close #569, close #567, close #542, close #538 2020-06-18 00:00:55 +08:00
ffdfgdfg cfe1747160 bump mux version 2020-06-10 23:54:10 +08:00
ffdfgdfg 60041da54c Merge pull request #546 from thelittlefox/patch-1
Update use.md
2020-05-20 21:46:09 +08:00
ffdfgdfg ebd1a11392 Merge pull request #545 from DeltaXrayDelta/patch-3
翻译修正
2020-05-20 21:45:30 +08:00
thelittlefox 73e63027db Update use.md
server_addr can be domain. 
Has been tested,it works fine.
2020-05-19 10:38:29 +08:00
DeltaXrayDelta 880ace7445 翻译修正
你确定你要停止它吗?
Are you sure you want to stop it?
2020-05-19 04:14:06 +08:00
ffdfgdfg f391813a28 Merge pull request #533 from ehang-io/dev
update docs
2020-05-09 13:58:52 +08:00
ffdfgdfg 03e32ba989 Merge pull request #532 from DeltaXrayDelta/patch-2
新增文档描述:客户端连接超时 disconnect_timeout
2020-05-09 13:58:00 +08:00
ffdfgdfg 3674a99c8c Update feature.md 2020-05-09 13:57:35 +08:00
ffdfgdfg 5a91bc2077 Merge pull request #531 from DeltaXrayDelta/patch-1
新增配置文件描述:客户端连接超时 disconnect_timeout
2020-05-09 13:09:54 +08:00
DeltaXrayDelta da6e392bb1 新增文档描述:客户端连接超时 disconnect_timeout
新增文档描述:客户端连接超时 disconnect_timeout
2020-05-09 01:33:21 +08:00
DeltaXrayDelta 88d25391af 新增配置文件描述:客户端连接超时 disconnect_timeout
新增配置文件描述:客户端连接超时 disconnect_timeout
2020-05-09 01:29:03 +08:00
ffdfgdfg e6b825dfc9 Merge pull request #526 from ehang-io/dev, close #483
Dev
2020-05-07 23:52:16 +08:00
ffdfgdfg 55c263902e bump version to 0.26.7 2020-05-07 23:47:33 +08:00
ffdfgdfg f459acdfb4 add custom client disconnect timeout option, close #485 2020-05-07 23:29:45 +08:00
ffdfgdfg 6f1b32a152 update docs 2020-05-07 20:47:15 +08:00
ffdfgdfg 878c717f89 Merge pull request #522 from ehang-io/pull/508, close #507
Pull/508
2020-04-30 23:47:26 +08:00
ffdfgdfg 7e60ed14b5 change tls key pair name 2020-04-30 23:25:59 +08:00
snowie2000 16be6d1b55 Revert http reverse proxy changes 2020-04-29 20:49:02 +08:00
ffdfgdfg 96e7b0255f Revert "Update npc.go", fix #515
This reverts commit 27a7a67e
2020-04-21 20:52:48 +08:00
ffdfgdfg 805b129c3b change gui startup, close #476, bump fyne version, fix #479 2020-04-15 19:54:12 +08:00
snowie2000 89e2a4c2eb removed unnecessary host fetch in revereproxy.Director 2020-04-15 11:08:05 +08:00
snowie2000 a732febf3b fixed typo in test.go
replaced self-made http reverseproxy with a more robust and versatile one.
dynamically generate cert for client-server tls encryption
2020-04-15 10:59:48 +08:00
ffdfgdfg 494d59cc93 add bridge status for api 2020-04-02 21:52:14 +08:00
ffdfgdfg b73491cde1 Merge pull request #487 from kekxv/patch-1
Update index.html
2020-03-31 18:47:45 +08:00
kekxv 8c8af7c6b6 Update index.html
修复手机浏览输入框或者按钮被遮挡问题
2020-03-31 14:58:29 +08:00
ffdfgdfg c9b755360c Merge pull request #478 from ehang-io/dev, close #475, close #461
Dev
2020-03-25 22:17:51 +08:00
ffdfgdfg 1b3dc6d831 bump version to v0.26.6 2020-03-25 22:11:27 +08:00
ffdfgdfg b3966c98fe fix missing server_ip 2020-03-25 22:07:52 +08:00
ffdfgdfg 72e10ced88 Merge pull request #471 from wyaode/patch-1, close #470
Update nps.go
2020-03-25 20:04:15 +08:00
ffdfgdfg bcf9334aa5 Merge pull request #473 from wyaode/patch-2
Update npc.go
2020-03-25 19:50:50 +08:00
wyaode 27a7a67e3c Update npc.go
解决npc同时支持客户端和私密代理访问端的问题  #472
暂不支持网页配置私密代理访问端
2020-03-25 09:36:51 +08:00
wyaode cf58f113c0 Update nps.go
解决服务无法启动问题,issues #470
2020-03-25 09:07:41 +08:00
ffdfgdfg de63b7df43 bump mux version 2020-03-19 20:43:52 +08:00
cnlh 9ff29c810c fix rete limit bug when add client first 2020-03-16 11:00:40 +08:00
cnlh 77ed98d407 show the input of client id, fixed:#453 2020-03-12 14:46:49 +08:00
ffdfgdfg f22914c3ad Merge pull request #452 from ehang-io/dev
remove docker arm, 386 image
2020-03-11 16:26:47 +08:00
ffdfgdfg d4f3e46277 remove docker arm, 386 image 2020-03-11 16:20:58 +08:00
ffdfgdfg fe6f6043e2 Merge pull request #449 from ehang-io/dev
Dev
2020-03-10 22:19:53 +08:00
ffdfgdfgandyzy613 33b7f9f570 master (#448)
* update ci (#429)

* Update .travis.yml

* Update .travis.yml

* Optimize compilation speed

del "master"
change "1.13" to 1.13.x

Co-authored-by: yzy613 <59520517+yzy613@users.noreply.github.com>
2020-03-10 21:46:58 +08:00
cnlh ead0f19f60 remove incorrect documentation 2020-03-10 20:51:15 +08:00
ffdfgdfg 671a0eae8b Merge pull request #446 from yzy613/patch-1
Optimize compilation speed
2020-03-10 20:10:17 +08:00
yzy613 3f08bf96f9 Optimize compilation speed
del "master"
change "1.13" to 1.13.x
2020-03-10 17:09:09 +08:00
ffdfgdfg 41e38fa6f2 Merge pull request #445 from ehang-io/dev
update ci
2020-03-10 15:57:52 +08:00
ffdfgdfg 47ea9419ab update ci 2020-03-10 15:51:36 +08:00
ffdfgdfg 7be6f51785 Merge pull request #444 from ehang-io/dev
Dev
2020-03-10 14:24:23 +08:00
ffdfgdfg 40489de7f7 change goproxy to direct 2020-03-10 14:16:22 +08:00
ffdfgdfg ccb6bafb93 pkg tidy 2020-03-10 13:44:26 +08:00
ffdfgdfg 9289a4472a bump mux version, close #390, close #438 2020-03-10 11:39:16 +08:00
ffdfgdfg 3cdd228d36 add npc linux sdk 2020-03-07 23:17:38 +08:00
ffdfgdfg 6bd853b6f6 update AndroidManifest.xml, fix #439 2020-03-07 21:56:03 +08:00
ffdfgdfg a296e0733f bump version to 0.26.5 2020-03-05 23:53:48 +08:00
ffdfgdfg b6d6fedca2 add print version 2020-03-05 23:49:24 +08:00
ffdfgdfg f1ae3ca758 bump ants version 2020-03-05 22:00:17 +08:00
ffdfgdfg 1fcad2a9fc bump fyne version 2020-03-05 21:55:47 +08:00
cnlh 8dabf5af1d fix:#433 2020-03-03 14:33:32 +08:00
ffdfgdfg b79def8dbf Merge pull request #430 from hzgjq/dev,close #410
Dev
2020-03-03 09:54:43 +08:00
hzgjq 4b39a94d88 Update add.html 2020-03-02 20:56:32 +08:00
hzgjq 7dcb696492 Update edit.html
增加选择模式时的使用场景提示,清理冗余代码
2020-03-02 18:33:46 +08:00
hzgjq dd76c2c1c9 Update add.html
增加各模式使用场景提示信息,清理冗余代码
2020-03-02 18:28:15 +08:00
hzgjq 7c9f777eac Update hlist.html
hostlist 列表中,客户端在线时点击在线状态可以直接进行访问
2020-03-02 18:26:45 +08:00
hzgjq f6e62c1241 Delete datatables.min.js
不再需要的文件
2020-03-02 18:21:30 +08:00
hzgjq db6cdf941e Update languages.xml
增加使用场景提示文字
2020-03-02 18:20:59 +08:00
ffdfgdfg 9fbdbb1c02 update ci (#429)
* Update .travis.yml

* Update .travis.yml
2020-03-02 13:52:00 +08:00
ffdfgdfg 4f5d575aa4 Update .travis.yml 2020-03-02 12:51:15 +08:00
ffdfgdfg ddd68f7f87 Update .travis.yml 2020-03-02 11:19:41 +08:00
ffdfgdfg 8e655777f4 Merge pull request #427 from ehang-io/dev
Dev
2020-03-01 22:27:11 +08:00
ffdfgdfg 7014f91864 update docs 2020-03-01 22:25:14 +08:00
ffdfgdfg c6a7aeaca4 update web copyright, change documents url 2020-03-01 21:29:07 +08:00
ffdfgdfg 6d2ab40638 Merge pull request #426 from hzgjq/dev
Update web, thanks @hzgjq
2020-03-01 20:59:20 +08:00
ffdfgdfg 2d81bdc286 update docs 2020-03-01 20:40:50 +08:00
ffdfgdfg 7f38e1fa0d update docs, close #424 2020-03-01 20:35:34 +08:00
ffdfgdfg f522bdb6ee fix client use http proxy 2020-03-01 18:36:38 +08:00
hzgjq b0cfea6f21 Update add.html 2020-03-01 17:05:03 +08:00
root 0897f84a04 hzgjq 2020-03-01 15:05:26 +08:00
cnlh 0865c98a7f fixed:client http proxy 2020-02-29 00:38:51 +08:00
ffdfgdfg aec1a25557 Freeze docker image golang version to 1.13.8 2020-02-28 15:18:47 +08:00
ffdfgdfg 6186af44df bump version to v0.26.4 2020-02-28 13:59:37 +08:00
ffdfgdfg 9061201684 Merge branch 'dev' of https://ehang.io/nps into dev 2020-02-28 00:32:05 +08:00
ffdfgdfg 6abfa6de1a support busyBox and sysV, for openWrt, fix #419, change update url 2020-02-28 00:31:17 +08:00
cnlh 77c4a0cea4 fix #409, support custom stun server 2020-02-23 01:49:41 +08:00
ffdfgdfg 2f9ee7130f Merge pull request #415 from ehang-io/dev
fix file not close before rename
2020-02-19 23:51:16 +08:00
ffdfgdfg f6063e0d6c fix file not close before rename 2020-02-19 23:20:44 +08:00
ffdfgdfg 090be360c8 Merge pull request #413 from ehang-io/dev
Dev
2020-02-19 01:07:21 +08:00
ffdfgdfg 3ec790d98d run without service #407 2020-02-18 22:53:37 +08:00
ffdfgdfg 876d3ccc6f change file storage, fix #412 2020-02-18 19:45:11 +08:00
cnlh 05c27b9365 fix:udp buf 2020-02-17 02:30:34 +08:00
ffdfgdfg 1fec6c3649 bump version to v0.26.3 2020-02-17 00:31:39 +08:00
ffdfgdfg 1776dc7289 Merge remote-tracking branch 'origin/dev' into dev 2020-02-17 00:17:04 +08:00
ffdfgdfg d3915e3b6d bump mux version 2020-02-17 00:16:34 +08:00
cnlh 26f48aa7f1 close client connection when tcp lost connection in socks5 2020-02-16 20:42:36 +08:00
cnlh 3dc16414c5 merge 2020-02-16 20:34:28 +08:00
yzy613andffdfgdfg acb4e50ee7 Update p2p tips (#408)
* Update example.md

新增p2p防火墙端口开放范围

* Update faq.md

* Update faq.md

添加p2p引导

Co-authored-by: ffdfgdfg <heyingtingaaa@gmail.com>
2020-02-14 22:42:59 +08:00
cnlh 8a04e17631 change md 2020-02-13 17:52:49 +08:00
ffdfgdfg 66133d6cbb update docs 2020-02-12 16:22:56 +08:00
ffdfgdfg 7ede000597 Merge pull request #401 from ehang-io/dev
Dev
2020-02-12 00:24:43 +08:00
ffdfgdfg a4247eb4b5 Merge remote-tracking branch 'origin/dev' into dev 2020-02-11 21:37:46 +08:00
ffdfgdfg 0fc993aeb5 bump fyne version 2020-02-11 21:37:05 +08:00
cnlh 5010ed7f57 merge 2020-02-11 19:56:29 +08:00
cnlh ef3dc10215 sync file when save 2020-02-11 19:54:16 +08:00
yzy613 8018a57344 Update faq.md (#400)
* Update faq.md

文字排版美化

* Update faq.md
2020-02-11 16:45:58 +08:00
cnlh b43bcb1c96 fix read request 2020-02-11 14:01:16 +08:00
ffdfgdfg e2d249a576 read full http proxy request, fix UnexpectedEOF error 2020-02-11 00:38:24 +08:00
cnlh 196c08cb32 change ci address 2020-02-10 17:52:51 +08:00
cnlh dc9eea6cc7 fix:bind local udp port error causes program to crash 2020-02-10 16:22:56 +08:00
ffdfgdfg 1be9e5472f bump version to 0.26.2 2020-02-09 20:25:10 +08:00
ffdfgdfg 824393c5c3 Merge pull request #395 from yzy613/patch-1
Update nps_use.md
2020-02-09 16:58:22 +08:00
ffdfgdfg 533dd083fe pprof configuration support, #382 2020-02-09 16:54:40 +08:00
yzy613 ed68410220 Update nps_use.md 2020-02-09 16:15:16 +08:00
yzy613 f95bb6c6d3 Update nps_use.md 2020-02-09 16:00:11 +08:00
ffdfgdfg 704bba92d1 bump ants version 2020-02-09 00:59:07 +08:00
ffdfgdfg 632bd12bfa add wait after invoke goroutine pool, fix #391 2020-02-09 00:44:09 +08:00
ffdfgdfg 72c695de4a update docs 2020-02-08 21:25:48 +08:00
ffdfgdfg 5c37505430 Merge remote-tracking branch 'remotes/origin/dev'
# Conflicts:
#	lib/mux/conn.go
#	lib/mux/queue.go
2020-01-31 15:23:26 +08:00
ffdfgdfg 099d3fcf2c custom npc systemd service script, increase open files limit 2020-01-22 11:54:40 +08:00
ffdfgdfg c7a5388cfd custom systemd service script, increase open files limit 2020-01-22 11:47:24 +08:00
ffdfgdfg 109821b068 remove duplicated description
web management protection
2020-01-21 10:26:00 +08:00
ffdfgdfg 4a34eb80dc bump mux version 2020-01-18 17:10:48 +08:00
ffdfgdfg b4f72d295e change server global value to concurrency safety, fix #315 2020-01-18 16:53:52 +08:00
cnlh b2d1de472b change all version 2020-01-16 16:27:18 +08:00
cnlh f7412501e7 Merge branch 'dev' of https://github.com/cnlh/nps into dev 2020-01-16 15:17:45 +08:00
cnlh 5bf52e9e24 fixes #367 2020-01-16 15:17:21 +08:00
cnlh b5a0daa69d close tunnel when finish udp data 2020-01-15 22:32:41 +08:00
cnlh 13d90df9ef merge 2020-01-15 21:59:33 +08:00
cnlh f72e3565e5 fixes #370 #368 2020-01-15 21:58:31 +08:00
cnlh 0af9943540 fixes #353 2020-01-13 18:31:03 +08:00
cnlh f73a55f254 fixed #347,api is not enabled by default 2020-01-13 17:29:25 +08:00
ffdfgdfg 5fedde1475 migrate mux to nps-mux 2020-01-09 22:59:24 +08:00
155 changed files with 17491 additions and 28114 deletions
+55
View File
@@ -0,0 +1,55 @@
name: Docker
on:
workflow_dispatch:
release:
types: [published]
# branches: [ master ]
tags: [v*]
jobs:
build_docker:
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Set env
run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Cache Docker layers
uses: actions/cache@v2
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-${{ github.sha }}
restore-keys: |
${{ runner.os }}-buildx-
- name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push nps
uses: docker/build-push-action@v2
with:
context: .
file: ./Dockerfile.nps
platforms: linux/amd64,linux/arm,linux/arm64
push: true
tags: |
${{ secrets.DOCKERHUB_USERNAME }}/nps:latest
${{ secrets.DOCKERHUB_USERNAME }}/nps:${{ env.RELEASE_VERSION }}
- name: Build and push npc
uses: docker/build-push-action@v2
with:
context: .
file: ./Dockerfile.npc
platforms: linux/amd64,linux/arm,linux/arm64
push: true
tags: |
${{ secrets.DOCKERHUB_USERNAME }}/npc:latest
${{ secrets.DOCKERHUB_USERNAME }}/npc:${{ env.RELEASE_VERSION }}
+73
View File
@@ -0,0 +1,73 @@
name: Release
on:
workflow_dispatch:
release:
types: [published]
branches: [ master ]
jobs:
build_assets:
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.x
uses: actions/setup-go@v2
with:
go-version: 1.15
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Get dependencies
run: |
go get -v -t -d ./...
if [ -f Gopkg.toml ]; then
curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
dep ensure
fi
- name: Build
run: |
chmod +x build.assets.sh
./build.assets.sh
- name: Upload
uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/')
with:
files: |
freebsd_386_client.tar.gz
freebsd_386_server.tar.gz
freebsd_amd64_client.tar.gz
freebsd_amd64_server.tar.gz
freebsd_arm_client.tar.gz
freebsd_arm_server.tar.gz
linux_386_client.tar.gz
linux_386_server.tar.gz
linux_amd64_client.tar.gz
linux_amd64_server.tar.gz
linux_arm64_client.tar.gz
linux_arm64_server.tar.gz
linux_arm_v5_client.tar.gz
linux_arm_v6_client.tar.gz
linux_arm_v7_client.tar.gz
linux_arm_v5_server.tar.gz
linux_arm_v6_server.tar.gz
linux_arm_v7_server.tar.gz
linux_mips64le_client.tar.gz
linux_mips64le_server.tar.gz
linux_mips64_client.tar.gz
linux_mips64_server.tar.gz
linux_mipsle_client.tar.gz
linux_mipsle_server.tar.gz
linux_mips_client.tar.gz
linux_mips_server.tar.gz
darwin_amd64_client.tar.gz
darwin_amd64_server.tar.gz
windows_386_client.tar.gz
windows_386_server.tar.gz
windows_amd64_client.tar.gz
windows_amd64_server.tar.gz
npc_sdk.tar.gz
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+5 -6
View File
@@ -1,12 +1,11 @@
language: go
go:
- "1.13"
- master
- 1.14.x
services:
- docker
script:
- go test -v ./cmd/nps/
- GOPROXY=direct go test -v ./cmd/nps/
os:
- linux
before_deploy:
@@ -14,9 +13,9 @@ before_deploy:
deploy:
provider: releases
api_key:
secure: ${TOKEN}
skip_cleanup: true
edge: true
token: ${GH_TOKEN}
cleanup: false
file:
- freebsd_386_client.tar.gz
- freebsd_386_server.tar.gz
+2 -1
View File
@@ -1,4 +1,5 @@
FROM golang as builder
FROM golang:1.15 as builder
ARG GOPROXY=direct
WORKDIR /go/src/ehang.io/nps
COPY . .
RUN go get -d -v ./...
+2 -1
View File
@@ -1,4 +1,5 @@
FROM golang as builder
FROM golang:1.15 as builder
ARG GOPROXY=direct
WORKDIR /go/src/ehang.io/nps
COPY . .
RUN go get -d -v ./...
+42 -63
View File
@@ -1,76 +1,55 @@
# NPS
![](https://img.shields.io/github/stars/ehang-io/nps.svg) ![](https://img.shields.io/github/forks/ehang-io/nps.svg)
[![Gitter](https://badges.gitter.im/cnlh-nps/community.svg)](https://gitter.im/cnlh-nps/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
[![Build Status](https://travis-ci.org/ehang-io/nps.svg?branch=master)](https://travis-ci.org/ehang-io/nps)
![GitHub All Releases](https://img.shields.io/github/downloads/ehang-io/nps/total)
[README](https://github.com/ehang-io/nps/blob/master/README.md)|[中文文档](https://github.com/ehang-io/nps/blob/master/README_zh.md)
NPS is a lightweight, high-performance, powerful **intranet penetration** proxy server, with a powerful web management terminal.
# 说明
由于nps已经有一年多的时间没有更新了,存留了不少bug和未完善的功能。
此版本基于 nps 0.26.10的基础上二次开发而来。
***DockerHub***: [NPS](https://hub.docker.com/r/yisier1/nps) [NPC](https://hub.docker.com/r/yisier1/npc)
![image](https://github.com/ehang-io/nps/blob/master/image/web.png?raw=true)
## Feature
## 更新日志
- Comprehensive protocol support, compatible with almost all commonly used protocols, such as tcp, udp, http(s), socks5, p2p, http proxy ...
- Full platform compatibility (linux, windows, macos, Qunhui, etc.), support installation as a system service simply.
- Comprehensive control, both client and server control are allowed.
- Https integration, support to convert backend proxy and web services to https, and support multiple certificates.
- Just simple configuration on web ui can complete most requirements.
- Complete information display, such as traffic, system information, real-time bandwidth, client version, etc.
- Powerful extension functions, everything is available (cache, compression, encryption, traffic limit, bandwidth limit, port reuse, etc.)
- Domain name resolution has functions such as custom headers, 404 page configuration, host modification, site protection, URL routing, and pan-resolution.
- Multi-user and user registration support on server.
**Didn't find the feature you want? It doesn't matter, click [Enter the document](https://ehang-io.github.io/nps/) to find it!**
## Quick start
### Installation
> [releases](https://github.com/ehang-io/nps/releases)
Download the corresponding system version, the server and client are separate.
### Server start
After downloading the server compressed package, unzip it, and then enter the unzipped folder.
- execute installation command
For linux、darwin ```sudo ./nps install```
For windows, run cmd as administrator and enter the installation directory ```nps.exe install```
- start up
For linux、darwin ```sudo nps start```
For windows, run cmd as administrator and enter the program directory ```nps.exe start```
```After installation, the windows configuration file is located at C:\Program Files\nps, linux or darwin is located at /etc/nps```
**If you don't find it started successfully, you can check the log (Windows log files are located in the current running directory, linux and darwin are located in /var/log/nps.log).**
- Access server IP:web service port (default is 8080).
- Login with username and password (default is admin/123, must be modified when officially used).
- Create a client.
### Client connection
- Click the + sign in front of the client in web management and copy the startup command.
- Execute the startup command, Linux can be executed directly, Windows will replace ./npc with npc.exe and execute it with cmd.
- 2022-12-30 v0.26.14
***修复***:API 鉴权漏洞修复
If you need to register to the system service, you can check [Register to the system service](https://ehang-io.github.io/nps/#/use?id=注册到系统服务)
- 2022-12-19
***修复***:某些场景下丢包导致服务端意外退出
***优化***:新增隧道时,不指定服务端口时,将自动生成端口号
***优化***:API返回ID, `/client/add/, /index/addhost/,/index/add/ `
***优化***:域名解析、隧道页面,增加[唯一验证密钥],方便搜查
### Configuration
- After the client connects, configure the corresponding penetration service in the web.
- For more advanced usage, see [Complete Documentation](https://ehang-io.github.io/nps/)
## Contribution
- If you encounter a bug, you can submit it to the dev branch directly.
- If you encounter a problem, you can feedback through the issue.
- The project is under development, and there is still a lot of room for improvement. If you can contribute code, please submit PR to the dev branch.
- If there is feedback on new features, you can feedback via issues or qq group.
- 2022-10-30
***新增***:在管理面板中新增客户端时,可以配置多个黑名单IP,用于防止被肉鸡扫描端口或被恶意攻击。
***优化***:0.26.12 版本还原了注册系统功能,使用方式和以前一样。无论是否注册了系统服务,直接执行 nps 时只会读取当前目录下的配置文件。
- 2022-10-27
***新增***:在管理面板登录时开启验证码校验,开启方式:nps.conf `open_captcha=true`,感谢 [@dongFangTuring](https://github.com/dongFangTuring) 提供的PR
- 2022-10-24:
***修复***:HTTP协议支持WebSocket(稳定性待测试)
- 2022-10-21:
***修复***:HTTP协议下实时统计流量,能够精准的限制住流量(上下行对等)
***优化***:删除HTTP隧道时,客户端已用流量不再清空
- 2022-10-19:
***BUG***:在TCP协议下,流量统计有问题,只有当连接断开时才会统计流量。例如,限制客户端流量20m,当传输100m的文件时,也能传输成功。
***修复***:TCP协议下实时统计流量,能够精准的限制住流量(上下行对等)
***优化***:删除TCP隧道时,客户端已用流量不再清空
![image](image/new/tcp_limit.png)
- 2022-09-14:
修改NPS工作目录为当前可执行文件目录(即配置文件和nps可执行文件放在同一目录下,直接执行nps文件即可),去除注册系统服务,启动、停止、升级等命令
+11 -1
View File
@@ -2,7 +2,7 @@
# nps
![](https://img.shields.io/github/stars/ehang-io/nps.svg) ![](https://img.shields.io/github/forks/ehang-io/nps.svg)
[![Gitter](https://badges.gitter.im/cnlh-nps/community.svg)](https://gitter.im/cnlh-nps/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
[![Build Status](https://travis-ci.org/ehang-io/nps.svg?branch=master)](https://travis-ci.org/ehang-io/nps)
![Release](https://github.com/ehang-io/nps/workflows/Release/badge.svg)
![GitHub All Releases](https://img.shields.io/github/downloads/ehang-io/nps/total)
[README](https://github.com/ehang-io/nps/blob/master/README.md)|[中文文档](https://github.com/ehang-io/nps/blob/master/README_zh.md)
@@ -50,6 +50,16 @@ nps是一款轻量级、高性能、功能强大的**内网穿透**代理服务
对于windows,管理员身份运行cmd,进入安装目录 ```nps.exe install```
- 默认端口
nps默认配置文件使用了80,443,8080,8024端口
80与443端口为域名解析模式默认端口
8080为web管理访问端口
8024为网桥端口,用于客户端与服务器通信
- 启动
对于linux|darwin ```sudo nps start```
+36 -27
View File
@@ -1,6 +1,7 @@
package bridge
import (
"ehang.io/nps/lib/nps_mux"
"encoding/binary"
"errors"
"fmt"
@@ -15,7 +16,6 @@ import (
"ehang.io/nps/lib/conn"
"ehang.io/nps/lib/crypt"
"ehang.io/nps/lib/file"
"ehang.io/nps/lib/mux"
"ehang.io/nps/lib/version"
"ehang.io/nps/server/connection"
"ehang.io/nps/server/tool"
@@ -24,14 +24,14 @@ import (
)
type Client struct {
tunnel *mux.Mux
tunnel *nps_mux.Mux
signal *conn.Conn
file *mux.Mux
file *nps_mux.Mux
Version string
retryTime int // it will be add 1 when ping not ok until to 3 will close the client
}
func NewClient(t, f *mux.Mux, s *conn.Conn, vs string) *Client {
func NewClient(t, f *nps_mux.Mux, s *conn.Conn, vs string) *Client {
return &Client{
signal: s,
tunnel: t,
@@ -41,28 +41,30 @@ func NewClient(t, f *mux.Mux, s *conn.Conn, vs string) *Client {
}
type Bridge struct {
TunnelPort int //通信隧道端口
Client sync.Map
Register sync.Map
tunnelType string //bridge type kcp or tcp
OpenTask chan *file.Tunnel
CloseTask chan *file.Tunnel
CloseClient chan int
SecretChan chan *conn.Secret
ipVerify bool
runList map[int]interface{}
TunnelPort int //通信隧道端口
Client sync.Map
Register sync.Map
tunnelType string //bridge type kcp or tcp
OpenTask chan *file.Tunnel
CloseTask chan *file.Tunnel
CloseClient chan int
SecretChan chan *conn.Secret
ipVerify bool
runList sync.Map //map[int]interface{}
disconnectTime int
}
func NewTunnel(tunnelPort int, tunnelType string, ipVerify bool, runList map[int]interface{}) *Bridge {
func NewTunnel(tunnelPort int, tunnelType string, ipVerify bool, runList sync.Map, disconnectTime int) *Bridge {
return &Bridge{
TunnelPort: tunnelPort,
tunnelType: tunnelType,
OpenTask: make(chan *file.Tunnel),
CloseTask: make(chan *file.Tunnel),
CloseClient: make(chan int),
SecretChan: make(chan *conn.Secret),
ipVerify: ipVerify,
runList: runList,
TunnelPort: tunnelPort,
tunnelType: tunnelType,
OpenTask: make(chan *file.Tunnel),
CloseTask: make(chan *file.Tunnel),
CloseClient: make(chan int),
SecretChan: make(chan *conn.Secret),
ipVerify: ipVerify,
runList: runList,
disconnectTime: disconnectTime,
}
}
@@ -231,6 +233,12 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
c.Close()
return
}
tcpConn, ok := c.Conn.(*net.TCPConn)
if ok {
// add tcp keep alive option for signal connection
_ = tcpConn.SetKeepAlive(true)
_ = tcpConn.SetKeepAlivePeriod(5 * time.Second)
}
//the vKey connect by another ,close the client of before
if v, ok := s.Client.LoadOrStore(id, NewClient(nil, nil, c, vs)); ok {
if v.(*Client).signal != nil {
@@ -242,7 +250,7 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
go s.GetHealthFromClient(id, c)
logs.Info("clientId %d connection succeeded, address:%s ", id, c.Conn.RemoteAddr())
case common.WORK_CHAN:
muxConn := mux.NewMux(c.Conn, s.tunnelType)
muxConn := nps_mux.NewMux(c.Conn, s.tunnelType, s.disconnectTime)
if v, ok := s.Client.LoadOrStore(id, NewClient(muxConn, nil, nil, vs)); ok {
v.(*Client).tunnel = muxConn
}
@@ -263,7 +271,7 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
logs.Error("secret error, failed to match the key successfully")
}
case common.WORK_FILE:
muxConn := mux.NewMux(c.Conn, s.tunnelType)
muxConn := nps_mux.NewMux(c.Conn, s.tunnelType, s.disconnectTime)
if v, ok := s.Client.LoadOrStore(id, NewClient(nil, muxConn, nil, vs)); ok {
v.(*Client).file = muxConn
}
@@ -321,7 +329,7 @@ func (s *Bridge) SendLinkInfo(clientId int, link *conn.Link, t *file.Tunnel) (ta
}
}
}
var tunnel *mux.Mux
var tunnel *nps_mux.Mux
if t != nil && t.Mode == "file" {
tunnel = v.(*Client).file
} else {
@@ -407,7 +415,8 @@ loop:
})
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
v := value.(*file.Tunnel)
if _, ok := s.runList[v.Id]; ok && v.Client.Id == id {
//if _, ok := s.runList[v.Id]; ok && v.Client.Id == id {
if _, ok := s.runList.Load(v.Id); ok && v.Client.Id == id {
str += v.Remark + common.CONN_DATA_SEQ
}
return true
Regular → Executable
+9 -14
View File
@@ -1,17 +1,14 @@
#/bin/bash
#sudo apt-get install libgl1-mesa-dev xorg-dev
#go get github.com/ffdfgdfg/fyne-cross
#fyne-cross --targets=linux/amd64,windows/amd64,darwin/amd64 gui/npc/npc.go
cd /go
apt-get install libegl1-mesa-dev libgles2-mesa-dev libx11-dev -y
#go get -u fyne.io/fyne/cmd/fyne fyne.io/fyne
mkdir -p /go/src/fyne.io
cd src/fyne.io
git clone https://github.com/fyne-io/fyne.git
cd fyne
git checkout v1.2.0
go install -v ./cmd/fyne
apt-get install libegl1-mesa-dev libgles2-mesa-dev libx11-dev xorg-dev -y
go get -u fyne.io/fyne/v2/cmd/fyne fyne.io/fyne/v2
#mkdir -p /go/src/fyne.io
#cd src/fyne.io
#git clone https://github.com/fyne-io/fyne.git
#cd fyne
#git checkout v1.2.0
#go install -v ./cmd/fyne
#fyne package -os android fyne.io/fyne/cmd/hello
echo "fyne install success"
mkdir -p /go/src/ehang.io/nps
@@ -32,8 +29,6 @@ rm -rf vendor
#rm -rf ~/.cache/*
echo "vendor success"
cd gui/npc
#rm -rf /go/src/golang.org/x/mobile
#go get -u fyne.io/fyne/cmd/fyne@v1.2.0
#export ANDROID_NDK_HOME=/usr/local/android_sdk/ndk-bundle
fyne package -appID org.nps.client -os android -icon ../../docs/logo.png
mv npc.apk /app/android_client.apk
echo "android build success"
+156
View File
@@ -0,0 +1,156 @@
export GOPROXY=direct
sudo apt-get update
sudo apt-get install gcc-mingw-w64-i686 gcc-multilib
env GOOS=windows GOARCH=386 CGO_ENABLED=1 CC=i686-w64-mingw32-gcc go build -ldflags "-s -w -extldflags -static -extldflags -static" -buildmode=c-shared -o npc_sdk.dll cmd/npc/sdk.go
env GOOS=linux GOARCH=386 CGO_ENABLED=1 CC=gcc go build -ldflags "-s -w -extldflags -static -extldflags -static" -buildmode=c-shared -o npc_sdk.so cmd/npc/sdk.go
tar -czvf npc_sdk.tar.gz npc_sdk.dll npc_sdk.so npc_sdk.h
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_386_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_386_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_arm_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v7_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v6_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v5_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64le_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mipsle_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf windows_386_client.tar.gz npc.exe conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf windows_amd64_client.tar.gz npc.exe conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf darwin_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_386_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_arm_v5_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_arm_v6_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_arm_v7_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_arm64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf freebsd_arm_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf freebsd_386_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf freebsd_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_mips_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_mips64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_mips64le_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_mipsle_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf darwin_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf windows_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps.exe
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf windows_386_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps.exe
+30 -41
View File
@@ -1,161 +1,150 @@
#/bash/sh
export VERSION=0.26.0
export VERSION=0.26.12
export GOPROXY=direct
sudo apt-get install gcc-mingw-w64-i686
sudo apt-get update
sudo apt-get install gcc-mingw-w64-i686 gcc-multilib
env GOOS=windows GOARCH=386 CGO_ENABLED=1 CC=i686-w64-mingw32-gcc go build -ldflags "-s -w -extldflags -static -extldflags -static" -buildmode=c-shared -o npc_sdk.dll cmd/npc/sdk.go
tar -czvf npc_sdk.tar.gz npc_sdk.dll npc_sdk.h
env GOOS=linux GOARCH=386 CGO_ENABLED=1 CC=gcc go build -ldflags "-s -w -extldflags -static -extldflags -static" -buildmode=c-shared -o npc_sdk.so cmd/npc/sdk.go
tar -czvf npc_sdk.tar.gz npc_sdk.dll npc_sdk.so npc_sdk.h
wget https://github.com/upx/upx/releases/download/v3.95/upx-3.95-amd64_linux.tar.xz
tar -xvf upx-3.95-amd64_linux.tar.xz
cp upx-3.95-amd64_linux/upx ./
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_386_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_386_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_arm_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v7_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v6_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v5_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64le_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mipsle_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf windows_386_client.tar.gz npc.exe conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf windows_amd64_client.tar.gz npc.exe conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf darwin_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf darwin_arm64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_386_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_arm_v5_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_arm_v6_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_arm_v7_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_arm64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf freebsd_arm_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf freebsd_386_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf freebsd_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_mips_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_mips64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_mips64le_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_mipsle_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf darwin_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf darwin_arm64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf windows_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps.exe
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf windows_386_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps.exe
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
@@ -163,12 +152,12 @@ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubun
sudo apt-get update
sudo apt-get -y -o Dpkg::Options::="--force-confnew" install docker-ce
docker --version
docker run --rm -i -w /app -v $(pwd):/app -e ANDROID_HOME=/usr/local/android_sdk ffdfgdfg/fyne-cross:android /app/build.android.sh
docker run --rm -i -w /app -v $(pwd):/app -e ANDROID_HOME=/usr/local/android_sdk -e GOPROXY=direct lucor/fyne-cross:android-latest /app/build.android.sh
git clone https://github.com/cnlh/spksrc.git ~/spksrc
mkdir ~/spksrc/nps && cp -rf ./* ~/spksrc/nps/
docker run -itd --name spksrc --env VERSION=$VERSION -v ~/spksrc:/spksrc synocommunity/spksrc /bin/bash
docker exec -it spksrc /bin/bash -c 'cd /spksrc && make setup && cd /spksrc/spk/npc && make'
cp ~/spksrc/packages/npc_noarch-all_$VERSION-1.spk ./npc_syno.spk
docker run -itd --name spksrc --env VERSION=$VERSION -e GOPROXY=direct -v ~/spksrc:/spksrc synocommunity/spksrc /bin/bash
docker exec -it spksrc /bin/bash -c 'cd /spksrc && make setup && cd /spksrc/spk/npc && make arch-x64-7.0'
cp ~/spksrc/packages/npc_x64-7.0_$VERSION-1.spk ./npc_syno.spk
echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin
+19 -10
View File
@@ -3,9 +3,11 @@ package client
import (
"bufio"
"bytes"
"ehang.io/nps/lib/nps_mux"
"net"
"net/http"
"strconv"
"sync"
"time"
"github.com/astaxie/beego/logs"
@@ -15,7 +17,6 @@ import (
"ehang.io/nps/lib/config"
"ehang.io/nps/lib/conn"
"ehang.io/nps/lib/crypt"
"ehang.io/nps/lib/mux"
)
type TRPClient struct {
@@ -24,14 +25,16 @@ type TRPClient struct {
proxyUrl string
vKey string
p2pAddr map[string]string
tunnel *mux.Mux
tunnel *nps_mux.Mux
signal *conn.Conn
ticker *time.Ticker
cnf *config.Config
disconnectTime int
once sync.Once
}
//new client
func NewRPClient(svraddr string, vKey string, bridgeConnType string, proxyUrl string, cnf *config.Config) *TRPClient {
func NewRPClient(svraddr string, vKey string, bridgeConnType string, proxyUrl string, cnf *config.Config, disconnectTime int) *TRPClient {
return &TRPClient{
svrAddr: svraddr,
p2pAddr: make(map[string]string, 0),
@@ -39,6 +42,8 @@ func NewRPClient(svraddr string, vKey string, bridgeConnType string, proxyUrl st
bridgeConnType: bridgeConnType,
proxyUrl: proxyUrl,
cnf: cnf,
disconnectTime: disconnectTime,
once: sync.Once{},
}
}
@@ -138,7 +143,7 @@ func (s *TRPClient) newUdpConn(localAddr, rAddr string, md5Password string) {
conn.SetUdpSession(udpTunnel)
logs.Trace("successful connection with client ,address %s", udpTunnel.RemoteAddr().String())
//read link info from remote
conn.Accept(mux.NewMux(udpTunnel, s.bridgeConnType), func(c net.Conn) {
conn.Accept(nps_mux.NewMux(udpTunnel, s.bridgeConnType, s.disconnectTime), func(c net.Conn) {
go s.handleChan(c)
})
break
@@ -146,14 +151,14 @@ func (s *TRPClient) newUdpConn(localAddr, rAddr string, md5Password string) {
}
}
//mux tunnel
//pmux tunnel
func (s *TRPClient) newChan() {
tunnel, err := NewConn(s.bridgeConnType, s.vKey, s.svrAddr, common.WORK_CHAN, s.proxyUrl)
if err != nil {
logs.Error("connect to ", s.svrAddr, "error:", err)
return
}
s.tunnel = mux.NewMux(tunnel.Conn, s.bridgeConnType)
s.tunnel = nps_mux.NewMux(tunnel.Conn, s.bridgeConnType, s.disconnectTime)
for {
src, err := s.tunnel.Accept()
if err != nil {
@@ -209,19 +214,19 @@ func (s *TRPClient) handleChan(src net.Conn) {
src.Close()
} else {
logs.Trace("new %s connection with the goal of %s, remote address:%s", lk.ConnType, lk.Host, lk.RemoteAddr)
conn.CopyWaitGroup(src, targetConn, lk.Crypt, lk.Compress, nil, nil, false, nil)
conn.CopyWaitGroup(src, targetConn, lk.Crypt, lk.Compress, nil, nil, false, nil, nil)
}
}
func (s *TRPClient) handleUdp(serverConn net.Conn) {
// bind a local udp port
local, err := net.ListenUDP("udp", nil)
defer local.Close()
defer serverConn.Close()
if err != nil {
logs.Error("bind local udp port error ", err.Error())
return
}
defer local.Close()
go func() {
defer serverConn.Close()
b := common.BufPoolUdp.Get().([]byte)
@@ -288,13 +293,17 @@ loop:
}
func (s *TRPClient) Close() {
s.once.Do(s.closing)
}
func (s *TRPClient) closing() {
CloseClient = true
NowStatus = 0
if s.tunnel != nil {
s.tunnel.Close()
_ = s.tunnel.Close()
}
if s.signal != nil {
s.signal.Close()
_ = s.signal.Close()
}
if s.ticker != nil {
s.ticker.Stop()
+13 -15
View File
@@ -1,6 +1,7 @@
package client
import (
"bufio"
"encoding/base64"
"encoding/binary"
"errors"
@@ -11,7 +12,6 @@ import (
"math/rand"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
@@ -175,7 +175,7 @@ re:
} else {
logs.Notice("web access login username:%s password:%s", cnf.CommonConfig.Client.WebUserName, cnf.CommonConfig.Client.WebPassword)
}
NewRPClient(cnf.CommonConfig.Server, vkey, cnf.CommonConfig.Tp, cnf.CommonConfig.ProxyUrl, cnf).Start()
NewRPClient(cnf.CommonConfig.Server, vkey, cnf.CommonConfig.Tp, cnf.CommonConfig.ProxyUrl, cnf, cnf.CommonConfig.DisconnectTime).Start()
CloseLocalServer()
goto re
}
@@ -253,30 +253,28 @@ func NewConn(tp string, vkey string, server string, connType string, proxyUrl st
//http proxy connection
func NewHttpProxyConn(url *url.URL, remoteAddr string) (net.Conn, error) {
req := &http.Request{
Method: "CONNECT",
URL: url,
Host: remoteAddr,
Header: http.Header{},
Proto: "HTTP/1.1",
}
password, _ := url.User.Password()
req.Header.Set("Authorization", "Basic "+basicAuth(strings.Trim(url.User.Username(), " "), password))
b, err := httputil.DumpRequest(req, false)
req, err := http.NewRequest("CONNECT", "http://"+remoteAddr, nil)
if err != nil {
return nil, err
}
password, _ := url.User.Password()
req.Header.Set("Authorization", "Basic "+basicAuth(strings.Trim(url.User.Username(), " "), password))
// we make a http proxy request
proxyConn, err := net.Dial("tcp", url.Host)
if err != nil {
return nil, err
}
if _, err := proxyConn.Write(b); err != nil {
if err := req.Write(proxyConn); err != nil {
return nil, err
}
buf := make([]byte, 1024)
if _, err := proxyConn.Read(buf); err != nil {
res, err := http.ReadResponse(bufio.NewReader(proxyConn), req)
if err != nil {
return nil, err
}
_ = res.Body.Close()
if res.StatusCode != 200 {
return nil, errors.New("Proxy error " + res.Status)
}
return proxyConn, nil
}
+6 -6
View File
@@ -1,6 +1,7 @@
package client
import (
"ehang.io/nps/lib/nps_mux"
"errors"
"net"
"net/http"
@@ -13,7 +14,6 @@ import (
"ehang.io/nps/lib/conn"
"ehang.io/nps/lib/crypt"
"ehang.io/nps/lib/file"
"ehang.io/nps/lib/mux"
"ehang.io/nps/server/proxy"
"github.com/astaxie/beego/logs"
"github.com/xtaci/kcp-go"
@@ -22,7 +22,7 @@ import (
var (
LocalServer []*net.TCPListener
udpConn net.Conn
muxSession *mux.Mux
muxSession *nps_mux.Mux
fileServer []*http.Server
p2pNetBridge *p2pBridge
lock sync.RWMutex
@@ -73,7 +73,7 @@ func startLocalFileServer(config *config.CommonConfig, t *file.Tunnel, vkey stri
}
logs.Info("start local file system, local path %s, strip prefix %s ,remote port %s ", t.LocalPath, t.StripPre, t.Ports)
fileServer = append(fileServer, srv)
listener := mux.NewMux(remoteConn.Conn, common.CONN_TCP)
listener := nps_mux.NewMux(remoteConn.Conn, common.CONN_TCP, config.DisconnectTime)
logs.Error(srv.Serve(listener))
}
@@ -161,7 +161,7 @@ func handleSecret(localTcpConn net.Conn, config *config.CommonConfig, l *config.
logs.Error("Local connection server failed ", err.Error())
return
}
conn.CopyWaitGroup(remoteConn.Conn, localTcpConn, false, false, nil, nil, false, nil)
conn.CopyWaitGroup(remoteConn.Conn, localTcpConn, false, false, nil, nil, false, nil, nil)
}
func handleP2PVisitor(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
@@ -178,7 +178,7 @@ func handleP2PVisitor(localTcpConn net.Conn, config *config.CommonConfig, l *con
udpConnStatus = false
return
} else {
conn.CopyWaitGroup(target, localTcpConn, false, config.Client.Cnf.Compress, nil, nil, false, nil)
conn.CopyWaitGroup(target, localTcpConn, false, config.Client.Cnf.Compress, nil, nil, false, nil, nil)
}
}
@@ -214,6 +214,6 @@ func newUdpConn(localAddr string, config *config.CommonConfig, l *config.LocalSe
logs.Trace("successful create a connection with server", remoteAddress)
conn.SetUdpSession(udpTunnel)
udpConn = udpTunnel
muxSession = mux.NewMux(udpConn, "kcp")
muxSession = nps_mux.NewMux(udpConn, "kcp", config.DisconnectTime)
p2pNetBridge = &p2pBridge{}
}
+85 -32
View File
@@ -13,26 +13,32 @@ import (
"github.com/ccding/go-stun/stun"
"github.com/kardianos/service"
"os"
"os/exec"
"runtime"
"strings"
"sync"
"time"
)
var (
serverAddr = flag.String("server", "", "Server addr (ip:port)")
configPath = flag.String("config", "", "Configuration file path")
verifyKey = flag.String("vkey", "", "Authentication key")
logType = flag.String("log", "stdout", "Log output mode(stdout|file)")
connType = flag.String("type", "tcp", "Connection type with the server(kcp|tcp)")
proxyUrl = flag.String("proxy", "", "proxy socks5 url(eg:socks5://111:222@127.0.0.1:9007)")
logLevel = flag.String("log_level", "7", "log level 0~7")
registerTime = flag.Int("time", 2, "register time long /h")
localPort = flag.Int("local_port", 2000, "p2p local port")
password = flag.String("password", "", "p2p password flag")
target = flag.String("target", "", "p2p target")
localType = flag.String("local_type", "p2p", "p2p target")
logPath = flag.String("log_path", "", "npc log path")
debug = flag.Bool("debug", true, "npc debug")
serverAddr = flag.String("server", "", "Server addr (ip:port)")
configPath = flag.String("config", "", "Configuration file path")
verifyKey = flag.String("vkey", "", "Authentication key")
logType = flag.String("log", "stdout", "Log output mode(stdout|file)")
connType = flag.String("type", "tcp", "Connection type with the server(kcp|tcp)")
proxyUrl = flag.String("proxy", "", "proxy socks5 url(eg:socks5://111:222@127.0.0.1:9007)")
logLevel = flag.String("log_level", "7", "log level 0~7")
registerTime = flag.Int("time", 2, "register time long /h")
localPort = flag.Int("local_port", 2000, "p2p local port")
password = flag.String("password", "", "p2p password flag")
target = flag.String("target", "", "p2p target")
localType = flag.String("local_type", "p2p", "p2p target")
logPath = flag.String("log_path", "", "npc log path")
debug = flag.Bool("debug", true, "npc debug")
pprofAddr = flag.String("pprof", "", "PProf debug addr (ip:port)")
stunAddr = flag.String("stun_addr", "stun.stunprotocol.org:3478", "stun server address (eg:stun.stunprotocol.org:3478)")
ver = flag.Bool("version", false, "show current version")
disconnectTime = flag.Int("disconnect_timeout", 60, "not receiving check packet times, until timeout will disconnect the client")
)
func main() {
@@ -40,6 +46,10 @@ func main() {
logs.Reset()
logs.EnableFuncCallDepth(true)
logs.SetLogFuncCallDepth(3)
if *ver {
common.PrintVersion()
return
}
if *logPath == "" {
*logPath = common.GetNpcLogPath()
}
@@ -54,8 +64,6 @@ func main() {
// init service
options := make(service.KeyValue)
options["Restart"] = "on-success"
options["SuccessExitStatus"] = "1 2 8 SIGKILL"
svcConfig := &service.Config{
Name: "Npc",
DisplayName: "nps内网穿透客户端",
@@ -66,6 +74,8 @@ func main() {
svcConfig.Dependencies = []string{
"Requires=network.target",
"After=network-online.target syslog.target"}
svcConfig.Option["SystemdScript"] = install.SystemdScript
svcConfig.Option["SysvScript"] = install.SysvScript
}
for _, v := range os.Args[1:] {
switch v {
@@ -82,7 +92,12 @@ func main() {
}
s, err := service.New(prg, svcConfig)
if err != nil {
logs.Error(err)
logs.Error(err, "service function disabled")
run()
// run without service
wg := sync.WaitGroup{}
wg.Add(1)
wg.Wait()
return
}
if len(os.Args) >= 2 {
@@ -99,24 +114,57 @@ func main() {
install.UpdateNpc()
return
case "nat":
nat, host, err := stun.NewClient().Discover()
c := stun.NewClient()
c.SetServerAddr(*stunAddr)
nat, host, err := c.Discover()
if err != nil || host == nil {
logs.Error("get nat type error", err)
return
}
fmt.Printf("nat type: %s \npublic address: %s\n", nat.String(), host.String())
os.Exit(0)
case "install", "start", "stop", "uninstall", "restart":
if os.Args[1] == "install" {
service.Control(s, "stop")
service.Control(s, "uninstall")
install.InstallNpc()
case "start", "stop", "restart":
// support busyBox and sysV, for openWrt
if service.Platform() == "unix-systemv" {
logs.Info("unix-systemv service")
cmd := exec.Command("/etc/init.d/"+svcConfig.Name, os.Args[1])
err := cmd.Run()
if err != nil {
logs.Error(err)
}
return
}
err := service.Control(s, os.Args[1])
if err != nil {
logs.Error("Valid actions: %q\n%s", service.ControlAction, err.Error())
}
return
case "install":
service.Control(s, "stop")
service.Control(s, "uninstall")
install.InstallNpc()
err := service.Control(s, os.Args[1])
if err != nil {
logs.Error("Valid actions: %q\n%s", service.ControlAction, err.Error())
}
if service.Platform() == "unix-systemv" {
logs.Info("unix-systemv service")
confPath := "/etc/init.d/" + svcConfig.Name
os.Symlink(confPath, "/etc/rc.d/S90"+svcConfig.Name)
os.Symlink(confPath, "/etc/rc.d/K02"+svcConfig.Name)
}
return
case "uninstall":
err := service.Control(s, os.Args[1])
if err != nil {
logs.Error("Valid actions: %q\n%s", service.ControlAction, err.Error())
}
if service.Platform() == "unix-systemv" {
logs.Info("unix-systemv service")
os.Remove("/etc/rc.d/S90" + svcConfig.Name)
os.Remove("/etc/rc.d/K02" + svcConfig.Name)
}
return
}
}
s.Run()
@@ -147,6 +195,16 @@ func (p *npc) run() error {
logs.Warning("npc: panic serving %v: %v\n%s", err, string(buf))
}
}()
run()
select {
case <-p.exit:
logs.Warning("stop...")
}
return nil
}
func run() {
common.InitPProfFromArg(*pprofAddr)
//p2p or secret command
if *password != "" {
commonConfig := new(config.CommonConfig)
@@ -161,7 +219,7 @@ func (p *npc) run() error {
commonConfig.Client = new(file.Client)
commonConfig.Client.Cnf = new(file.Config)
go client.StartLocalServer(localServer, commonConfig)
return nil
return
}
env := common.GetEnvMap()
if *serverAddr == "" {
@@ -174,20 +232,15 @@ func (p *npc) run() error {
if *verifyKey != "" && *serverAddr != "" && *configPath == "" {
go func() {
for {
client.NewRPClient(*serverAddr, *verifyKey, *connType, *proxyUrl, nil).Start()
logs.Info("It will be reconnected in five seconds")
client.NewRPClient(*serverAddr, *verifyKey, *connType, *proxyUrl, nil, *disconnectTime).Start()
logs.Info("Client closed! It will be reconnected in five seconds")
time.Sleep(time.Second * 5)
}
}()
} else {
if *configPath == "" {
*configPath = "conf/npc.conf"
*configPath = common.GetConfigPath()
}
go client.StartFromFile(*configPath)
}
select {
case <-p.exit:
logs.Warning("stop...")
}
return nil
}
+3 -6
View File
@@ -12,15 +12,12 @@ var cl *client.TRPClient
//export StartClientByVerifyKey
func StartClientByVerifyKey(serverAddr, verifyKey, connType, proxyUrl *C.char) int {
logs.SetLogger("store")
_ = logs.SetLogger("store")
if cl != nil {
cl.Close()
}
cl = client.NewRPClient(C.GoString(serverAddr), C.GoString(verifyKey), C.GoString(connType), C.GoString(proxyUrl), nil)
go func() {
cl.Start()
return
}()
cl = client.NewRPClient(C.GoString(serverAddr), C.GoString(verifyKey), C.GoString(connType), C.GoString(proxyUrl), nil, 60)
cl.Start()
return 1
}
+76 -21
View File
@@ -1,39 +1,50 @@
package main
import (
"ehang.io/nps/lib/install"
"ehang.io/nps/lib/daemon"
"flag"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/crypt"
"ehang.io/nps/lib/daemon"
"ehang.io/nps/lib/file"
"ehang.io/nps/lib/install"
"ehang.io/nps/lib/version"
"ehang.io/nps/server"
"ehang.io/nps/server/connection"
"ehang.io/nps/server/tool"
"ehang.io/nps/web/routers"
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/crypt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"ehang.io/nps/web/routers"
"github.com/kardianos/service"
)
var (
level string
ver = flag.Bool("version", false, "show current version")
)
func main() {
flag.Parse()
// init log
if *ver {
common.PrintVersion()
return
}
if err := beego.LoadAppConfig("ini", filepath.Join(common.GetRunPath(), "conf", "nps.conf")); err != nil {
log.Fatalln("load config file error", err.Error())
}
common.InitPProfFromFile()
if level = beego.AppConfig.String("log_level"); level == "" {
level = "7"
}
@@ -49,8 +60,6 @@ func main() {
}
// init service
options := make(service.KeyValue)
options["Restart"] = "on-success"
options["SuccessExitStatus"] = "1 2 8 SIGKILL"
svcConfig := &service.Config{
Name: "Nps",
DisplayName: "nps内网穿透代理服务器",
@@ -59,22 +68,30 @@ func main() {
}
svcConfig.Arguments = append(svcConfig.Arguments, "service")
if len(os.Args) > 1 && os.Args[1] == "service" {
logs.SetLogger(logs.AdapterFile, `{"level":`+level+`,"filename":"`+logPath+`","daily":false,"maxlines":100000,"color":true}`)
_ = logs.SetLogger(logs.AdapterFile, `{"level":`+level+`,"filename":"`+logPath+`","daily":false,"maxlines":100000,"color":true}`)
} else {
logs.SetLogger(logs.AdapterConsole, `{"level":`+level+`,"color":true}`)
_ = logs.SetLogger(logs.AdapterConsole, `{"level":`+level+`,"color":true}`)
}
if !common.IsWindows() {
svcConfig.Dependencies = []string{
"Requires=network.target",
"After=network-online.target syslog.target"}
svcConfig.Option["SystemdScript"] = install.SystemdScript
svcConfig.Option["SysvScript"] = install.SysvScript
}
prg := &nps{}
prg.exit = make(chan struct{})
s, err := service.New(prg, svcConfig)
if err != nil {
logs.Error(err)
logs.Error(err, "service function disabled")
run()
// run without service
wg := sync.WaitGroup{}
wg.Add(1)
wg.Wait()
return
}
if len(os.Args) > 1 && os.Args[1] != "service" {
switch os.Args[1] {
case "reload":
@@ -82,8 +99,8 @@ func main() {
return
case "install":
// uninstall before
service.Control(s, "stop")
service.Control(s, "uninstall")
_ = service.Control(s, "stop")
_ = service.Control(s, "uninstall")
binPath := install.InstallNps()
svcConfig.Executable = binPath
@@ -96,13 +113,39 @@ func main() {
if err != nil {
logs.Error("Valid actions: %q\n%s", service.ControlAction, err.Error())
}
if service.Platform() == "unix-systemv" {
logs.Info("unix-systemv service")
confPath := "/etc/init.d/" + svcConfig.Name
os.Symlink(confPath, "/etc/rc.d/S90"+svcConfig.Name)
os.Symlink(confPath, "/etc/rc.d/K02"+svcConfig.Name)
}
return
case "start", "restart", "stop", "uninstall":
case "start", "restart", "stop":
if service.Platform() == "unix-systemv" {
logs.Info("unix-systemv service")
cmd := exec.Command("/etc/init.d/"+svcConfig.Name, os.Args[1])
err := cmd.Run()
if err != nil {
logs.Error(err)
}
return
}
err := service.Control(s, os.Args[1])
if err != nil {
logs.Error("Valid actions: %q\n%s", service.ControlAction, err.Error())
}
return
case "uninstall":
err := service.Control(s, os.Args[1])
if err != nil {
logs.Error("Valid actions: %q\n%s", service.ControlAction, err.Error())
}
if service.Platform() == "unix-systemv" {
logs.Info("unix-systemv service")
os.Remove("/etc/rc.d/S90" + svcConfig.Name)
os.Remove("/etc/rc.d/K02" + svcConfig.Name)
}
return
case "update":
install.UpdateNps()
return
@@ -111,7 +154,8 @@ func main() {
return
}
}
s.Run()
_ = s.Run()
}
type nps struct {
@@ -119,10 +163,12 @@ type nps struct {
}
func (p *nps) Start(s service.Service) error {
p.run()
_, _ = s.Status()
go p.run()
return nil
}
func (p *nps) Stop(s service.Service) error {
_, _ = s.Status()
close(p.exit)
if service.Interactive() {
os.Exit(0)
@@ -139,6 +185,15 @@ func (p *nps) run() error {
logs.Warning("nps: panic serving %v: %v\n%s", err, string(buf))
}
}()
run()
select {
case <-p.exit:
logs.Warning("stop...")
}
return nil
}
func run() {
routers.Init()
task := &file.Tunnel{
Mode: "webServer",
@@ -150,13 +205,13 @@ func (p *nps) run() error {
}
logs.Info("the version of server is %s ,allow client core version to be %s", version.VERSION, version.GetVersion())
connection.InitConnectionService()
crypt.InitTls(filepath.Join(common.GetRunPath(), "conf", "server.pem"), filepath.Join(common.GetRunPath(), "conf", "server.key"))
//crypt.InitTls(filepath.Join(common.GetRunPath(), "conf", "server.pem"), filepath.Join(common.GetRunPath(), "conf", "server.key"))
crypt.InitTls()
tool.InitAllowPort()
tool.StartSystemInfo()
go server.StartNewServer(bridgePort, task, beego.AppConfig.String("bridge_type"))
select {
case <-p.exit:
logs.Warning("stop...")
timeout, err := beego.AppConfig.Int("disconnect_timeout")
if err != nil {
timeout = 60
}
return nil
go server.StartNewServer(bridgePort, task, beego.AppConfig.String("bridge_type"), timeout)
}
+2
View File
@@ -12,6 +12,8 @@ web_username=user
web_password=1234
crypt=true
compress=true
#pprof_addr=0.0.0.0:9999
disconnect_timeout=60
[health_check_test1]
health_check_timeout=1
+31 -12
View File
@@ -22,11 +22,11 @@ public_vkey=123
#Traffic data persistence interval(minute)
#Ignorance means no persistence
#flow_store_interval=1
flow_store_interval=1
# log level LevelEmergency->0 LevelAlert->1 LevelCritical->2 LevelError->3 LevelWarning->4 LevelNotice->5 LevelInformational->6 LevelDebug->7
log_level=7
#log_path=nps.log
log_level=6
log_path=nps.log
#Whether to restrict IP access, true or false or ignore
#ip_limit=true
@@ -39,7 +39,7 @@ log_level=7
web_host=a.o.com
web_username=admin
web_password=123
web_port = 8080
web_port = 8081
web_ip=0.0.0.0
web_base_url=
web_open_ssl=false
@@ -49,7 +49,8 @@ web_key_file=conf/server.key
#web_base_url=/nps
#Web API unauthenticated IP address(the len of auth_crypt_key must be 16)
auth_key=test
#Remove comments if needed
#auth_key=test
auth_crypt_key =1234567812345678
#allow_ports=9001-9009,10001,11000-12000
@@ -59,18 +60,36 @@ allow_user_login=false
allow_user_register=false
allow_user_change_username=false
#extension
allow_flow_limit=false
allow_rate_limit=false
allow_tunnel_num_limit=false
#流量限制
allow_flow_limit=true
#带宽限制
allow_rate_limit=true
#客户端最大隧道数限制
allow_tunnel_num_limit=true
allow_local_proxy=false
allow_connection_num_limit=false
allow_multi_ip=false
system_info_display=false
#客户端最大连接数
allow_connection_num_limit=true
#每个隧道监听不同的服务端端口
allow_multi_ip=true
system_info_display=true
#获取用户真实ip
http_add_origin_header=true
#cache
http_cache=false
http_cache_length=100
#get origin ip
http_add_origin_header=false
#pprof debug options
#pprof_ip=0.0.0.0
#pprof_port=9999
#client disconnect timeout
disconnect_timeout=60
#管理面板开启验证码校验
open_captcha=true
+1 -1
View File
@@ -1,7 +1,7 @@
# nps
![](https://img.shields.io/github/stars/cnlh/nps.svg) ![](https://img.shields.io/github/forks/cnlh/nps.svg)
[![Gitter](https://badges.gitter.im/cnlh-nps/community.svg)](https://gitter.im/cnlh-nps/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
[![Build Status](https://travis-ci.org/cnlh/nps.svg?branch=master)](https://travis-ci.org/cnlh/nps)
[![Build Status](https://travis-ci.org/ehang-io/nps.svg?branch=master)](https://travis-ci.org/cnlh/nps)
nps是一款轻量级、高性能、功能强大的**内网穿透**代理服务器。目前支持**tcp、udp流量转发**,可支持任何**tcp、udp**上层协议(访问内网网站、本地支付接口调试、ssh访问、远程桌面,内网dns解析等等……),此外还**支持内网http代理、内网socks5代理**、**p2p等**,并带有功能强大的web管理端。
+1 -1
View File
@@ -1,6 +1,6 @@
![logo](logo.svg)
# NPS <small>0.26.0</small>
# NPS <small>0.26.10</small>
> 一款轻量级、高性能、功能强大的内网穿透代理服务器
+3
View File
@@ -0,0 +1,3 @@
* [![GitHub stars](https://img.shields.io/github/stars/ehang-io/nps?style=social)](https://github.com/ehang-io/nps/stargazers)
* [![GitHub forks](https://img.shields.io/github/forks/ehang-io/nps?style=social)](https://github.com/ehang-io/nps/network)
+1
View File
@@ -22,6 +22,7 @@
* 其他
* [FAQ](faq.md)
* [贡献](contribute.md)
* [捐助](donate.md)
* [致谢](thanks.md)
+3 -4
View File
@@ -1,4 +1,6 @@
# web api
需要开启请先去掉`nps.conf`中`auth_key`的注释并配置一个合适的密钥
## webAPI验证说明
- 采用auth_key的验证方式
- 在提交的每个请求后面附带两个参数,`auth_key` 和`timestamp`
@@ -40,7 +42,4 @@ POST /auth/getauthkey
- 解密串编码方式 十六进制
## 详细文档
- **此文档近期可能更新较慢,建议自行抓包**
为方便第三方扩展,在web模式下可利用webAPI进行相关操作,详情见
[webAPI文档](https://github.com/ehang-io/nps/wiki/webAPI%E6%96%87%E6%A1%A3)
- **[详见](webapi.md)** (感谢@avengexyz)
+1 -3
View File
@@ -1,5 +1,6 @@
# 说明
## 获取用户真实ip
如需使用需要在`nps.conf`中设置`http_add_origin_header=true`
在域名代理模式中,可以通过request请求 header 中的 X-Forwarded-For 和 X-Real-IP 来获取用户真实 IP。
@@ -8,9 +9,6 @@
## 热更新支持
对于绝大多数配置,在web管理中的修改将实时使用,无需重启客户端或者服务端
## web端保护
在一分钟内,如果密码错误次数超过10次,该ip在一分钟内将不能再次登陆。
## 客户端地址显示
在web管理中将显示客户端的连接地址
+10 -5
View File
@@ -1,12 +1,12 @@
# 使用示例
## 统一准备工作(必做)
- 开启服务端,假设公网服务器ip为1.1.1.1,配置文件中`bridge_port`为8284,配置文件中`web_port`为8080
- 开启服务端,假设公网服务器ip为1.1.1.1,配置文件中`bridge_port`为8024,配置文件中`web_port`为8080
- 访问1.1.1.1:8080
- 在客户端管理中创建一个客户端,记录下验证密钥
- 内网客户端运行(windows使用cmd运行加.exe)
```shell
./npc -server=1.1.1.1:8284 -vkey=客户端的密钥
./npc -server=1.1.1.1:8024 -vkey=客户端的密钥
```
**注意:运行服务端后,请确保能从客户端设备上正常访问配置文件中所配置的`bridge_port`端口,telnet,netcat这类的来检查**
@@ -14,6 +14,8 @@
**适用范围:** 小程序开发、微信公众号开发、产品演示
**注意:域名解析模式为http反向代理,不是dns服务器,在web上能够轻松灵活配置**
**假设场景:**
- 有一个域名proxy.com,有一台公网机器ip为1.1.1.1
- 两个内网开发站点127.0.0.1:81,127.0.0.1:82
@@ -77,6 +79,8 @@
- 在刚才创建的客户端隧道管理中添加一条http代理,填写监听的端口(8004),保存。
- 在外网环境的本机配置http代理,ip为公网服务器ip(1.1.1.1),端口为填写的监听端口(8004),即可访问了
**注意:对于私密代理与p2p,除了统一配置的客户端和服务端,还需要一个客户端作为访问端提供一个端口来访问**
## 私密代理
**适用范围:** 无需占用多余的端口、安全性要求较高可以防止其他人连接的tcp服务,例如ssh。
@@ -89,13 +93,13 @@
- 在需要连接ssh的机器上以执行命令
```
./npc -server=1.1.1.1:8284 -vkey=vkey -type=tcp -password=secrettest -local_type=secret
./npc -server=1.1.1.1:8024 -vkey=vkey -type=tcp -password=secrettest -local_type=secret
```
如需指定本地端口可加参数`-local_port=xx`,默认为2000
**注意:** password为web管理上添加的唯一密钥,具体命令可查看web管理上的命令提示
假设10.1.50.2用户名为root,现在执行`ssh -p 2000 root@1.1.1.1`即可访问ssh
假设10.1.50.2用户名为root,现在执行`ssh -p 2000 root@127.0.0.1`即可访问ssh
## p2p服务
@@ -108,11 +112,12 @@
**使用步骤**
- 在`nps.conf`中设置`p2p_ip`(nps服务器ip)和`p2p_port`(nps服务器udp端口)
> 注:若 `p2p_port` 设置为6000,请在防火墙开放6000~6002(额外添加2个端口)udp端口
- 在刚才刚才创建的客户端中添加一条p2p代理,并设置唯一密钥p2pssh
- 在使用端机器(本机)执行命令
```
./npc -server=1.1.1.1:8284 -vkey=123 -password=p2pssh -target=10.2.50.2:22
./npc -server=1.1.1.1:8024 -vkey=123 -password=p2pssh -target=10.2.50.2:22
```
如需指定本地端口可加参数`-local_port=xx`,默认为2000
+20
View File
@@ -0,0 +1,20 @@
# FAQ
- 服务端无法启动
```
服务端默认配置启用了8024,8080,80,443端口,端口冲突无法启动,请修改配置
```
- 客户端无法连接服务端
```
请检查配置文件中的所有端口是否在安全组,防火墙放行
请检查vkey是否对应
请检查版本是否对应
```
- 服务端配置文件修改无效
```
install 之后,Linux 配置文件在 /etc/nps
```
- p2p穿透失败 [p2p服务](https://ehang-io.github.io/nps/#/example?id=p2p%e6%9c%8d%e5%8a%a1)
```
双方nat类型都是Symmetric Nat一定不成功,建议先查看nat类型。请按照文档操作(标题上有超链接)
```
+19 -12
View File
@@ -16,8 +16,7 @@
## 加密传输
如果公司内网防火墙对外网访问进行了流量识别与屏蔽,例如禁止了ssh协议等,通过设置 配置文件,将服务端与客户端之间的通信内容加密传输,将会有效防止流量被拦截。
- nps使用tls加密,所以一定要保留conf目录下的密钥文件,同时也可以自行生成
- 在web管理或客户端配置文件中设置
- nps现在默认每次启动时随机生成tls证书,用于加密传输
@@ -79,17 +78,10 @@ target_port=8001-8009,10002,13000-14000
target_ip=10.1.50.2
```
填写target_ip后则表示映射的该地址机器的端口,忽略则便是映射本地127.0.0.1,仅范围映射时有效
## 守护进程
本代理支持守护进程,使用示例如下,服务端客户端所有模式通用,支持linux,darwin,windows。
```
./(nps|npc) start|stop|restart|status 若有其他参数可加其他参数
```
```
(nps|npc).exe start|stop|restart|status 若有其他参数可加其他参数
```
## KCP协议支持
KCP 是一个快速可靠协议,能以比 TCP浪费10%-20%的带宽的代价,换取平均延迟降低 30%-40%,在弱网环境下对性能能有一定的提升。可在nps.conf中修改`bridge_type`为kcp
在网络质量非常好的情况下,例如专线,内网,可以开启略微降低延迟。如需使用可在nps.conf中修改`bridge_type`为kcp
,设置后本代理将开启udp端口(`bridge_port`)
注意:当服务端为kcp时,客户端连接时也需要使用相同配置,无配置文件模式加上参数type=kcp,配置文件模式在配置文件中设置tp=kcp
@@ -167,7 +159,7 @@ npc支持环境变量渲染以适应在某些特殊场景下的要求。
**在无配置文件启动模式下:**
设置环境变量
```
export NPC_SERVER_ADDR=1.1.1.1:8284
export NPC_SERVER_ADDR=1.1.1.1:8024
export NPC_SERVER_VKEY=xxxxx
```
直接执行./npc即可运行
@@ -245,3 +237,18 @@ LevelInformational->6 LevelDebug->7
**对于nps:**
在`nps.conf`中设置相关配置即可
## pprof性能分析与调试
可在服务端与客户端配置中开启pprof端口,用于性能分析与调试,注释或留空相应参数为关闭。
默认为关闭状态
## 自定义客户端超时检测断开时间
客户端与服务端间会间隔5s相互发送延迟测量包,这个时间间隔不可修改。
可修改延迟测量包丢包的次数,默认为60也就是5分钟都收不到一个延迟测量回包,则会断开客户端连接。
值得注意的是需要客户端的socket关闭,才会进行重连,也就是当客户端无法收到服务端的fin包时,只有客户端自行关闭socket才行。
也就是假如服务端设置为较低值,而客户端设置较高值,而此时服务端断开连接而客户端无法收到服务端的fin包,客户端也会继续等着直到触发客户端的超时设置。
在`nps.conf`或`npc.conf`中设置`disconnect_timeout`即可,客户端还可附带`-disconnect_timeout=60`参数启动
+1
View File
@@ -20,6 +20,7 @@
repo: '',
loadSidebar: true,
coverpage: true,
loadNavbar: true,
subMaxLevel: 2,
maxLevel: 4,
search: {
+1 -1
View File
@@ -6,7 +6,7 @@
## 源码安装
- 安装源码
```go get -u ehang.io/nps...```
```go get -u ehang.io/nps```
- 编译
服务端```go build cmd/nps/nps.go```
+2 -2
View File
@@ -1,9 +1,9 @@
# 增强功能
## nat类型检测
```
./npc nat
./npc nat -stun_addr=stun.stunprotocol.org:3478
```
如果p2p双方都是Symmetric Nat,肯定不能成功,其他组合都有较大成功率。
如果p2p双方都是Symmetric Nat,肯定不能成功,其他组合都有较大成功率。`stun_addr`可以指定stun服务器地址。
## 状态检查
```
./npc status -config=npc配置文件路径
+1
View File
@@ -2,6 +2,7 @@
```
命令行模式启动客户端
从v0.26.10开始,此函数会阻塞,直到客户端退出返回,请自行管理是否重连
p0->连接地址
p1->vkey
p2->连接类型(tcp or udp)
+5 -5
View File
@@ -3,7 +3,7 @@
**方式一:** 类似于nginx实现https的处理
在配置文件中将https_proxy_port设置为443或者其他你想配置的端口,和在web中对应域名编辑中设置对应的证书路径,将`https_just_proxy`设置为false,然后就和http代理一样了
在配置文件中将https_proxy_port设置为443或者其他你想配置的端口,将`https_just_proxy`设置为false,nps 重启后,在web管理界面,域名新增或修改界面中修改域名证书和密钥。
**此外:** 可以在`nps.conf`中设置一个默认的https配置,当遇到未在web中设置https证书的域名解析时,将自动使用默认证书,另还有一种情况就是对于某些请求的clienthello不携带sni扩展信息,nps也将自动使用默认证书
@@ -14,18 +14,18 @@
## 与nginx配合
有时候我们还需要在云服务器上运行nginx来保证静态文件缓存等,本代理可和nginx配合使用,在配置文件中将httpProxyPort设置为非80端口,并在nginx中配置代理,例如httpProxyPort为8024时
有时候我们还需要在云服务器上运行nginx来保证静态文件缓存等,本代理可和nginx配合使用,在配置文件中将httpProxyPort设置为非80端口,并在nginx中配置代理,例如httpProxyPort为8010时
```
server {
listen 80;
server_name *.proxy.com;
location / {
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:8024;
proxy_pass http://127.0.0.1:8010;
}
}
```
如需使用https也可在nginx监听443端口并配置ssl,并将本代理的httpsProxyPort设置为空关闭https即可,例如httpProxyPort为8024时
如需使用https也可在nginx监听443端口并配置ssl,并将本代理的httpsProxyPort设置为空关闭https即可,例如httpProxyPort为8020时
```
server {
@@ -40,7 +40,7 @@ server {
ssl_prefer_server_ciphers on;
location / {
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:8024;
proxy_pass http://127.0.0.1:8020;
}
}
```
+4 -2
View File
@@ -29,7 +29,7 @@
nps.exe stop|restart
```
## 服务端更新
请首先执行`sudo nps stop`或者`nps.exe stop`停止运行,然后
请首先执行 `sudo nps stop` 或者 `nps.exe stop` 停止运行,然后
对于linux
```shell
@@ -40,6 +40,8 @@
nps-update.exe update
```
更新完成后,执行执行`sudo nps start`或者`nps.exe start`重新运行即可完成升级
更新完成后,执行执行 `sudo nps start` 或者 `nps.exe start` 重新运行即可完成升级
如果无法更新成功,可以直接自行下载releases压缩包然后覆盖原有的nps二进制文件和web目录
注意:`nps install` 之后的 nps 不在原位置,请使用 `whereis nps` 查找具体目录覆盖 nps 二进制文件
+8 -1
View File
@@ -26,10 +26,17 @@
## 客户端
- 下载客户端安装包并解压,进入到解压目录
- 点击web管理中客户端前的+号,复制启动命令
- 执行启动命令,linux直接执行即可,windows将./npc换成npc.exe用cmd执行
- 执行启动命令,linux直接执行即可,windows将./npc换成npc.exe用**cmd执行**
如果使用`powershell`运行,**请将ip括起来!**
如果需要注册到系统服务可查看[注册到系统服务](/use?id=注册到系统服务)
## 版本检查
- 对客户端以及服务的均可以使用参数`-version`打印版本
- `nps -version`或`./nps -version`
- `npc -version`或`./npc -version`
## 配置
- 客户端连接后,在web中配置对应穿透服务即可
- 可以查看[使用示例](/example)
+4 -1
View File
@@ -1,5 +1,5 @@
# 服务端配置文件
- /conf/nps.conf
- /etc/nps/conf/nps.conf
名称 | 含义
---|---
@@ -19,3 +19,6 @@ log_level|日志输出级别
auth_crypt_key | 获取服务端authKey时的aes加密密钥,16位
p2p_ip| 服务端Ip,使用p2p模式必填
p2p_port|p2p模式开启的udp端口
pprof_ip|debug pprof 服务端ip
pprof_port|debug pprof 端口
disconnect_timeout|客户端连接超时,单位 5s,默认值 60,即 300s = 5mins
+14 -10
View File
@@ -17,6 +17,8 @@
- 启动:`npc.exe start`
- 停止:`npc.exe stop`
- 如果需要更换命令内容需要先卸载`npc.exe uninstall`,再重新注册
- 如果需要当客户端退出时自动重启客户端,请按照如图所示配置
![image](https://github.com/ehang-io/nps/blob/master/docs/windows_client_service_configuration.png?raw=true)
注册到服务后,日志文件windows位于当前目录下,linux和darwin位于/var/log/npc.log
@@ -48,7 +50,7 @@ npc-update.exe update
#### 全局配置
```ini
[common]
server_addr=1.1.1.1:8284
server_addr=1.1.1.1:8024
conn_type=tcp
vkey=123
username=111
@@ -59,10 +61,11 @@ rate_limit=10000
flow_limit=100
remark=test
max_conn=10
#pprof_addr=0.0.0.0:9999
```
项 | 含义
---|---
server_addr | 服务端ip:port
server_addr | 服务端ip/域名:port
conn_type | 与服务端通信模式(tcp或kcp)
vkey|服务端配置文件中的密钥(非web)
username|socks5或http(s)密码保护用户名(可忽略)
@@ -73,11 +76,12 @@ rate_limit|速度限制,可忽略
flow_limit|流量限制,可忽略
remark|客户端备注,可忽略
max_conn|最大连接数,可忽略
pprof_addr|debug pprof ip:port
#### 域名代理
```ini
[common]
server_addr=1.1.1.1:8284
server_addr=1.1.1.1:8024
vkey=123
[web1]
host=a.proxy.com
@@ -97,7 +101,7 @@ header_xxx|请求header修改或添加,header_proxy表示添加header proxy:np
```ini
[common]
server_addr=1.1.1.1:8284
server_addr=1.1.1.1:8024
vkey=123
[tcp]
mode=tcp
@@ -114,7 +118,7 @@ tartget_addr|内网目标
```ini
[common]
server_addr=1.1.1.1:8284
server_addr=1.1.1.1:8024
vkey=123
[udp]
mode=udp
@@ -130,7 +134,7 @@ target_addr|内网目标
```ini
[common]
server_addr=1.1.1.1:8284
server_addr=1.1.1.1:8024
vkey=123
[http]
mode=httpProxy
@@ -144,7 +148,7 @@ server_port | 在服务端的代理端口
```ini
[common]
server_addr=1.1.1.1:8284
server_addr=1.1.1.1:8024
vkey=123
[socks5]
mode=socks5
@@ -160,7 +164,7 @@ multi_account | socks5多账号配置文件(可选),配置后使用basic_usern
```ini
[common]
server_addr=1.1.1.1:8284
server_addr=1.1.1.1:8024
vkey=123
[secret_ssh]
mode=secret
@@ -177,7 +181,7 @@ target_addr|内网目标
```ini
[common]
server_addr=1.1.1.1:8284
server_addr=1.1.1.1:8024
vkey=123
[p2p_ssh]
mode=p2p
@@ -196,7 +200,7 @@ target_addr|内网目标
```ini
[common]
server_addr=1.1.1.1:8284
server_addr=1.1.1.1:8024
vkey=123
[file]
mode=file
+1 -1
View File
@@ -47,7 +47,7 @@ POST /client/add/
| max\_tunnel | 客户端最大隧道数量 空则为不限制 |
***
修改客户端(25.4版本有问题暂时不能用)
修改客户端
```
POST /client/edit/
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

+17 -17
View File
@@ -1,33 +1,33 @@
module ehang.io/nps
go 1.13
go 1.15
require (
fyne.io/fyne v1.2.0
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect
fyne.io/fyne/v2 v2.0.2
github.com/astaxie/beego v1.12.0
github.com/bradfitz/iter v0.0.0-20190303215204-33e6a9893b0c // indirect
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect
github.com/c4milo/unpackit v0.0.0-20170704181138-4ed373e9ef1c
github.com/ccding/go-stun v0.0.0-20180726100737-be486d185f3d
github.com/dsnet/compress v0.0.1 // indirect
github.com/go-ole/go-ole v1.2.4 // indirect
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db
github.com/golang/snappy v0.0.3
github.com/hooklift/assert v0.0.0-20170704181755-9d1defd6d214 // indirect
github.com/kardianos/service v1.0.0
github.com/klauspost/cpuid v1.2.1 // indirect
github.com/kardianos/service v1.2.0
github.com/klauspost/cpuid v1.3.1 // indirect
github.com/klauspost/cpuid/v2 v2.0.6 // indirect
github.com/klauspost/pgzip v1.2.1 // indirect
github.com/klauspost/reedsolomon v1.9.2 // indirect
github.com/panjf2000/ants/v2 v2.2.2
github.com/pkg/errors v0.8.1
github.com/klauspost/reedsolomon v1.9.12 // indirect
github.com/panjf2000/ants/v2 v2.4.2
github.com/pkg/errors v0.9.1
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect
github.com/shirou/gopsutil v2.19.11+incompatible
github.com/shirou/gopsutil/v3 v3.21.3
github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161 // indirect
github.com/templexxx/xor v0.0.0-20181023030647-4e92f724b73b // indirect
github.com/tjfoc/gmsm v1.0.1 // indirect
github.com/xtaci/kcp-go v5.4.4+incompatible
github.com/templexxx/xor v0.0.0-20191217153810-f85b25db303b // indirect
github.com/tjfoc/gmsm v1.4.0 // indirect
github.com/xtaci/kcp-go v5.4.20+incompatible
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae // indirect
golang.org/x/net v0.0.0-20181220203305-927f97764cc3
golang.org/x/sys v0.0.0-20190804053845-51ab0e2deafa // indirect
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 // indirect
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4
golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57 // indirect
)
replace github.com/astaxie/beego => github.com/exfly/beego v1.12.0-export-init
+168 -55
View File
@@ -1,5 +1,9 @@
fyne.io/fyne v1.2.0 h1:mdp7Cs7QmSJTeazYxEDa9wWeJNig7paBcjm0dooFtLE=
fyne.io/fyne v1.2.0/go.mod h1:Ab+3DIB/FVteW0y4DXfmZv4N3JdnCBh2lHkINI02BOU=
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
ehang.io/nps-mux v0.0.0-20210407130203-4afa0c10c992 h1:LvlcB+8JveSBprHnva0g+OyLwAH8CRxEwtWzTe6ocoE=
ehang.io/nps-mux v0.0.0-20210407130203-4afa0c10c992/go.mod h1:v54y/8ICChiM/aVUuKxGIcWwjm4HGNRyyAwbgLBoMbI=
fyne.io/fyne/v2 v2.0.2 h1:6pDvFuCmL1odyT/fPI+2L54hMJW1Zt9Dno41HmLInRs=
fyne.io/fyne/v2 v2.0.2/go.mod h1:3+FYmLJVgeb8EvTPJ5YzZeo7LkAq4bbuY3Zrir6xHbg=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
github.com/Kodeworks/golang-image-ico v0.0.0-20141118225523-73f0f4cfade9/go.mod h1:7uhhqiBaR4CpN0k9rMjOtjpcfGd6DG2m04zQxKnWQ0I=
github.com/OwnLocal/goes v1.0.0/go.mod h1:8rIFjBGTue3lCU0wplczcUgt9Gxgrkkrw7etMIcn8TM=
@@ -9,124 +13,233 @@ github.com/akavel/rsrc v0.8.0/go.mod h1:uLoCtb9J+EyAqh+26kdrTgmzRBFPGOolLWKpdxkK
github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ=
github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU=
github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60=
github.com/bradfitz/iter v0.0.0-20190303215204-33e6a9893b0c h1:FUUopH4brHNO2kJoNN3pV+OBEYmgraLT/KHZrMM69r0=
github.com/bradfitz/iter v0.0.0-20190303215204-33e6a9893b0c/go.mod h1:PyRFw1Lt2wKX4ZVSQ2mk+PeDa1rxyObEDlApuIsUKuo=
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 h1:GKTyiRCL6zVf5wWaqKnf+7Qs6GbEPfd4iMOitWzXJx8=
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8/go.mod h1:spo1JLcs67NmW1aVLEgtA8Yy1elc+X8y5SRW1sFW4Og=
github.com/c4milo/unpackit v0.0.0-20170704181138-4ed373e9ef1c h1:aprLqMn7gSPT+vdDSl+/E6NLEuArwD/J7IWd8bJt5lQ=
github.com/c4milo/unpackit v0.0.0-20170704181138-4ed373e9ef1c/go.mod h1:Ie6SubJv/NTO9Q0UBH0QCl3Ve50lu9hjbi5YJUw03TE=
github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE=
github.com/ccding/go-stun v0.0.0-20180726100737-be486d185f3d h1:As4937T5NVbJ/DmZT9z33pyLEprMd6CUSfhbmMY57Io=
github.com/ccding/go-stun v0.0.0-20180726100737-be486d185f3d/go.mod h1:3FK1bMar37f7jqVY7q/63k3OMX1c47pGCufzt3X0sYE=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/couchbase/go-couchbase v0.0.0-20181122212707-3e9b6e1258bb/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U=
github.com/couchbase/gomemcached v0.0.0-20181122193126-5125a94a666c/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c=
github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs=
github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dsnet/compress v0.0.1 h1:PlZu0n3Tuv04TzpfPbrnI0HW/YwodEXDS+oPKahKF0Q=
github.com/dsnet/compress v0.0.1/go.mod h1:Aw8dCMJ7RioblQeTqt88akK31OvO8Dhf5JflhBbQEHo=
github.com/dsnet/golib v0.0.0-20171103203638-1ea166775780/go.mod h1:Lj+Z9rebOhdfkVLjJ8T6VcRQv3SXugXy999NBtR9aFY=
github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M=
github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk=
github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/exfly/beego v1.12.0-export-init h1:VQNYKdXhAwZGUaFmQv8Aj921O3rQJZRIF8xeGrhsjrI=
github.com/exfly/beego v1.12.0-export-init/go.mod h1:fysx+LZNZKnvh4GED/xND7jWtjCR6HzydR2Hh2Im57o=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fredbi/uri v0.0.0-20181227131451-3dcfdacbaaf3 h1:FDqhDm7pcsLhhWl1QtD8vlzI4mm59llRvNzrFg6/LAA=
github.com/fredbi/uri v0.0.0-20181227131451-3dcfdacbaaf3/go.mod h1:CzM2G82Q9BDUvMTGHnXf/6OExw/Dz2ivDj48nVg7Lg8=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/fyne-io/mobile v0.1.3-0.20210318200029-09e9c4e13a8f h1:rguJ/t99j/6zRSFzsBKlsmmyl+vOvCeTJ+2uTBvuXFI=
github.com/fyne-io/mobile v0.1.3-0.20210318200029-09e9c4e13a8f/go.mod h1:/kOrWrZB6sasLbEy2JIvr4arEzQTXBTZGb3Y96yWbHY=
github.com/go-gl/gl v0.0.0-20190320180904-bf2b1f2f34d7 h1:SCYMcCJ89LjRGwEa0tRluNRiMjZHalQZrVrvTbPh+qw=
github.com/go-gl/gl v0.0.0-20190320180904-bf2b1f2f34d7/go.mod h1:482civXOzJJCPzJ4ZOX/pwvXBWSnzD4OKMdH4ClKGbk=
github.com/go-gl/glfw v0.0.0-20181213070059-819e8ce5125f h1:7MsFMbSn8Lcw0blK4+NEOf8DuHoOBDhJsHz04yh13pM=
github.com/go-gl/glfw v0.0.0-20181213070059-819e8ce5125f/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20210311203641-62640a716d48 h1:QrUfZrT8n72FUuiABt4tbu8PwDnOPAbnj3Mql1UhdRI=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20210311203641-62640a716d48/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-ole/go-ole v1.2.4 h1:nNBDSCOigTSiarFpYE9J/KtEA1IOW4CNeqT9TQDqCxI=
github.com/go-ole/go-ole v1.2.4/go.mod h1:XCwSNxSkXRo4vlyPy93sltvi/qJq0jqQhjqQNIwKuxM=
github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/godbus/dbus/v5 v5.0.3 h1:ZqHaoEF7TBzh4jzPmqVhE/5A1z9of6orkAe5uHoAeME=
github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/goki/freetype v0.0.0-20181231101311-fa8a33aabaff h1:W71vTCKoxtdXgnm1ECDFkfQnpdqAO00zzGXLA5yaEX8=
github.com/goki/freetype v0.0.0-20181231101311-fa8a33aabaff/go.mod h1:wfqRWLHRBsRgkp5dmbG56SA0DmVtwrF5N3oPdI8t+Aw=
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db h1:woRePGFeVFfLKN/pOkfl+p/TAqKOfFu+7KPlMVpok/w=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.3 h1:fHPg5GQYlCeLIPB9BZqMVR5nR9A+IM5zcgeTdjMYmLA=
github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/hooklift/assert v0.0.0-20170704181755-9d1defd6d214 h1:WgfvpuKg42WVLkxNwzfFraXkTXPK36bMqXvMFN67clI=
github.com/hooklift/assert v0.0.0-20170704181755-9d1defd6d214/go.mod h1:kj6hFWqfwSjFjLnYW5PK1DoxZ4O0uapwHRmd9jhln4E=
github.com/jackmordaunt/icns v0.0.0-20181231085925-4f16af745526/go.mod h1:UQkeMHVoNcyXYq9otUupF7/h/2tmHlhrS2zw7ZVvUqc=
github.com/josephspurrier/goversioninfo v0.0.0-20190124120936-8611f5a5ff3f/go.mod h1:eJTEwMjXb7kZ633hO3Ln9mBUCOjX2+FlTljvpl9SYdE=
github.com/kardianos/service v1.0.0 h1:HgQS3mFfOlyntWX8Oke98JcJLqt1DBcHR4kxShpYef0=
github.com/kardianos/service v1.0.0/go.mod h1:8CzDhVuCuugtsHyZoTvsOBuvonN/UDBvl0kH+BUxvbo=
github.com/josephspurrier/goversioninfo v0.0.0-20200309025242-14b0ab84c6ca/go.mod h1:eJTEwMjXb7kZ633hO3Ln9mBUCOjX2+FlTljvpl9SYdE=
github.com/kardianos/service v1.2.0 h1:bGuZ/epo3vrt8IPC7mnKQolqFeYJb7Cs8Rk4PSOBB/g=
github.com/kardianos/service v1.2.0/go.mod h1:CIMRFEJVL+0DS1a3Nx06NaMn4Dz63Ng6O7dl0qH0zVM=
github.com/klauspost/compress v1.4.1 h1:8VMb5+0wMgdBykOV96DwNwKFQ+WTI4pzYURP99CcB9E=
github.com/klauspost/compress v1.4.1/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
github.com/klauspost/cpuid v1.2.0/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
github.com/klauspost/cpuid v1.2.1 h1:vJi+O/nMdFt0vqm8NZBI6wzALWdA2X+egi0ogNyrC/w=
github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
github.com/klauspost/cpuid v1.3.1 h1:5JNjFYYQrZeKRJ0734q51WCEEn2huer72Dc7K+R/b6s=
github.com/klauspost/cpuid v1.3.1/go.mod h1:bYW4mA6ZgKPob1/Dlai2LviZJO7KGI3uoWLd42rAQw4=
github.com/klauspost/cpuid/v2 v2.0.2/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.0.6 h1:dQ5ueTiftKxp0gyjKSx5+8BtPWkyQbd95m8Gys/RarI=
github.com/klauspost/cpuid/v2 v2.0.6/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/pgzip v1.2.1 h1:oIPZROsWuPHpOdMVWLuJZXwgjhrW8r1yEX8UqMyeNHM=
github.com/klauspost/pgzip v1.2.1/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs=
github.com/klauspost/reedsolomon v1.9.2 h1:E9CMS2Pqbv+C7tsrYad4YC9MfhnMVWhMRsTi7U0UB18=
github.com/klauspost/reedsolomon v1.9.2/go.mod h1:CwCi+NUr9pqSVktrkN+Ondf06rkhYZ/pcNv7fu+8Un4=
github.com/klauspost/reedsolomon v1.9.12 h1:EyOucRmcrLH+2hqKGdoA5SM8pwPKR6BJsf3r6zpYOA0=
github.com/klauspost/reedsolomon v1.9.12/go.mod h1:nLvuzNvy1ZDNQW30IuMc2ZWCbiqrJgdLoUS2X8HAUVg=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/lucor/goinfo v0.0.0-20200401173949-526b5363a13a/go.mod h1:ORP3/rB5IsulLEBwQZCJyyV6niqmI7P4EWSmkug+1Ng=
github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
github.com/panjf2000/ants/v2 v2.2.2 h1:TWzusBjq/IflXhy+/S6u5wmMLCBdJnB9tPIx9Zmhvok=
github.com/panjf2000/ants/v2 v2.2.2/go.mod h1:1GFm8bV8nyCQvU5K4WvBCTG1/YBFOD2VzjffD8fV55A=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/panjf2000/ants/v2 v2.4.2 h1:kesjjo8JipN3vNNg1XaiXaeSs6xJweBTgenkBtsrHf8=
github.com/panjf2000/ants/v2 v2.4.2/go.mod h1:f6F0NZVFsGCp5A7QW/Zj/m92atWwOkY0OIhFxRNFr4A=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo=
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg=
github.com/shirou/gopsutil v2.19.11+incompatible h1:lJHR0foqAjI4exXqWsU3DbH7bX1xvdhGdnXTIARA9W4=
github.com/shirou/gopsutil v2.19.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/shirou/gopsutil/v3 v3.21.3 h1:wgcdAHZS2H6qy4JFewVTtqfiYxFzCeEJod/mLztdPG8=
github.com/shirou/gopsutil/v3 v3.21.3/go.mod h1:ghfMypLDrFSWN2c9cDYFLHyynQ+QUht0cv/18ZqVczw=
github.com/siddontang/go v0.0.0-20180604090527-bdc77568d726/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw=
github.com/siddontang/ledisdb v0.0.0-20181029004158-becf5f38d373/go.mod h1:mF1DpOSOUiJRMR+FDqaqu3EBqrybQtrDDszLUZ6oxPg=
github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA=
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/srwiley/oksvg v0.0.0-20190829233741-58e08c8fe40e h1:LJUrNHytcMXWKxnULIHPe5SCb1jDpO9o672VB1x2EuQ=
github.com/srwiley/oksvg v0.0.0-20190829233741-58e08c8fe40e/go.mod h1:afMbS0qvv1m5tfENCwnOdZGOF8RGR/FsZ7bvBxQGZG4=
github.com/srwiley/rasterx v0.0.0-20181219215540-696f7edb7a7e h1:FFotfUvew9Eg02LYRl8YybAnm0HCwjjfY5JlOI1oB00=
github.com/srwiley/rasterx v0.0.0-20181219215540-696f7edb7a7e/go.mod h1:mvWM0+15UqyrFKqdRjY6LuAVJR0HOVhJlEgZ5JWtSWU=
github.com/srwiley/oksvg v0.0.0-20200311192757-870daf9aa564 h1:HunZiaEKNGVdhTRQOVpMmj5MQnGnv+e8uZNu3xFLgyM=
github.com/srwiley/oksvg v0.0.0-20200311192757-870daf9aa564/go.mod h1:afMbS0qvv1m5tfENCwnOdZGOF8RGR/FsZ7bvBxQGZG4=
github.com/srwiley/rasterx v0.0.0-20200120212402-85cb7272f5e9 h1:m59mIOBO4kfcNCEzJNy71UkeF4XIx2EVmL9KLwDQdmM=
github.com/srwiley/rasterx v0.0.0-20200120212402-85cb7272f5e9/go.mod h1:mvWM0+15UqyrFKqdRjY6LuAVJR0HOVhJlEgZ5JWtSWU=
github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.1-0.20190311161405-34c6fa2dc709 h1:Ko2LQMrRU+Oy/+EDBwX7eZ2jp3C47eDBB8EIhKTun+I=
github.com/stretchr/testify v1.3.1-0.20190311161405-34c6fa2dc709/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0=
github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161 h1:89CEmDvlq/F7SJEOqkIdNDGJXrQIhuIx9D2DBXjavSU=
github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161/go.mod h1:wM7WEvslTq+iOEAMDLSzhVuOt5BRZ05WirO+b09GHQU=
github.com/templexxx/xor v0.0.0-20181023030647-4e92f724b73b h1:mnG1fcsIB1d/3vbkBak2MM0u+vhGhlQwpeimUi7QncM=
github.com/templexxx/xor v0.0.0-20181023030647-4e92f724b73b/go.mod h1:5XA7W9S6mni3h5uvOC75dA3m9CCCaS83lltmc0ukdi4=
github.com/tjfoc/gmsm v1.0.1 h1:R11HlqhXkDospckjZEihx9SW/2VW0RgdwrykyWMFOQU=
github.com/tjfoc/gmsm v1.0.1/go.mod h1:XxO4hdhhrzAd+G4CjDqaOkd0hUzmtPR/d3EiBBMn/wc=
github.com/templexxx/xor v0.0.0-20191217153810-f85b25db303b h1:fj5tQ8acgNUr6O8LEplsxDhUIe2573iLkJc+PqnzZTI=
github.com/templexxx/xor v0.0.0-20191217153810-f85b25db303b/go.mod h1:5XA7W9S6mni3h5uvOC75dA3m9CCCaS83lltmc0ukdi4=
github.com/tjfoc/gmsm v1.4.0 h1:8nbaiZG+iVdh+fXVw0DZoZZa7a4TGm3Qab+xdrdzj8s=
github.com/tjfoc/gmsm v1.4.0/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE=
github.com/tklauser/go-sysconf v0.3.4 h1:HT8SVixZd3IzLdfs/xlpq0jeSfTX57g1v6wB1EuzV7M=
github.com/tklauser/go-sysconf v0.3.4/go.mod h1:Cl2c8ZRWfHD5IrfHo9VN+FX9kCFjIOyVklgXycLB6ek=
github.com/tklauser/numcpus v0.2.1 h1:ct88eFm+Q7m2ZfXJdan1xYoXKlmwsfP+k88q05KvlZc=
github.com/tklauser/numcpus v0.2.1/go.mod h1:9aU+wOc6WjUIZEwWMP62PL/41d65P+iks1gBkr4QyP8=
github.com/ulikunitz/xz v0.5.6 h1:jGHAfXawEGZQ3blwU5wnWKQJvAraT7Ftq9EXjnXYgt8=
github.com/ulikunitz/xz v0.5.6/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8=
github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc=
github.com/xtaci/kcp-go v5.4.4+incompatible h1:QIJ0a0Q0N1G20yLHL2+fpdzyy2v/Cb3PI+xiwx/KK9c=
github.com/xtaci/kcp-go v5.4.4+incompatible/go.mod h1:bN6vIwHQbfHaHtFpEssmWsN45a+AZwO7eyRCmEIbtvE=
github.com/xtaci/kcp-go v5.4.20+incompatible h1:TN1uey3Raw0sTz0Fg8GkfM0uH3YwzhnZWQ1bABv5xAg=
github.com/xtaci/kcp-go v5.4.20+incompatible/go.mod h1:bN6vIwHQbfHaHtFpEssmWsN45a+AZwO7eyRCmEIbtvE=
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae h1:J0GxkO96kL4WF+AIT3M4mfUVinOCPgf2uUWYFUzN0sM=
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae/go.mod h1:gXtu8J62kEgmN++bm9BVICuT/e8yiLI2KFobd/TRFsE=
golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85 h1:et7+NAX3lLIk5qUCTA9QelBjGE/NkhzYw/mhnr0s7nI=
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8 h1:idBdZTd9UioThJp8KpM/rTSinK/ChZFBE43/WtIy8zg=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b h1:+qEpEAPhDZ1o0x3tHzZTQDArnOixOzGD9HUJfcg0mb4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 h1:It14KIkyBFYkHkwZ7k45minvA9aorojkyjGk9KJ5B/w=
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028 h1:4+4C/Iv2U4fMZBiMCc98MG1In4gJY5YRhtpDNeDeHWs=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a h1:gOpx8G595UYyvj8UK4+OFyY4rx037g3fmfhe5SasG3U=
golang.org/x/image v0.0.0-20200430140353-33d19683fad8 h1:6WW6V3x1P/jokJBpRQYUJnMHRP6isStQwCozxnU7XQw=
golang.org/x/image v0.0.0-20200430140353-33d19683fad8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181220203305-927f97764cc3 h1:eH6Eip3UpmR+yM/qI9Ijluzb1bNv/cAU/n+6l8tRSis=
golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190804053845-51ab0e2deafa h1:KIDDMLT1O0Nr7TSxp8xM5tJcdn8tgyAONntO829og1M=
golang.org/x/sys v0.0.0-20190804053845-51ab0e2deafa/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 h1:4nGaVu0QrbjT/AK2PRLuQfQuh6DJve+pELhqTdAj3x0=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200720211630-cb9d2d5c5666/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210217105451-b926d437f341/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57 h1:F5Gozwx4I1xtr/sr/8CFbb57iKi3297KFs0QDbGN60A=
golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190808195139-e713427fea3f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200328031815-3db5fc6bac03/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
+11 -28
View File
@@ -1,37 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="0.26.0"
package="org.nps.client"
platformBuildVersionCode="15"
platformBuildVersionName="4.0.4-1406430">
<uses-permission
android:name="android.permission.INTERNET"/>
<application
android:label="Npc"
android:debuggable="true">
<activity
android:label="Npc"
android:name="org.golang.app.GoNativeActivity"
android:configChanges="0xa0">
<meta-data
android:name="android.app.lib_name"
android:value="npc"/>
android:versionCode="1"
android:versionName="0.26.10">
<application android:label="Npc" android:debuggable="true">
<activity android:name="org.golang.app.GoNativeActivity"
android:label="Npc"
android:configChanges="orientation|keyboardHidden">
<meta-data android:name="android.app.lib_name" android:value="npc"/>
<intent-filter>
<action
android:name="android.intent.action.MAIN"/>
<category
android:name="android.intent.category.LAUNCHER"/>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
+57 -36
View File
@@ -6,10 +6,11 @@ import (
"ehang.io/nps/lib/daemon"
"ehang.io/nps/lib/version"
"fmt"
"fyne.io/fyne"
"fyne.io/fyne/app"
"fyne.io/fyne/layout"
"fyne.io/fyne/widget"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/layout"
"fyne.io/fyne/v2/widget"
"github.com/astaxie/beego/logs"
"io/ioutil"
"os"
@@ -32,10 +33,12 @@ func main() {
}
var (
start bool
status = "Start!"
connType = "tcp"
cl = new(client.TRPClient)
start bool
closing bool
status = "Start!"
connType = "tcp"
cl = new(client.TRPClient)
refreshCh = make(chan struct{})
)
func WidgetScreen() fyne.CanvasObject {
@@ -44,38 +47,17 @@ func WidgetScreen() fyne.CanvasObject {
)
}
func makeMainTab() fyne.Widget {
func makeMainTab() *fyne.Container {
serverPort := widget.NewEntry()
serverPort.SetPlaceHolder("Server:Port")
vKey := widget.NewEntry()
vKey.SetPlaceHolder("Vkey")
radio := widget.NewRadio([]string{"tcp", "kcp"}, func(s string) { connType = s })
radio := widget.NewRadioGroup([]string{"tcp", "kcp"}, func(s string) { connType = s })
radio.Horizontal = true
refreshCh := make(chan struct{})
button := widget.NewButton(status, func() {
start = !start
if start {
status = "Stop!"
// init the npc
fmt.Println("submit", serverPort.Text, vKey.Text, connType)
sp, vk, ct := loadConfig()
if sp != serverPort.Text || vk != vKey.Text || ct != connType {
saveConfig(serverPort.Text, vKey.Text, connType)
}
cl = client.NewRPClient(serverPort.Text, vKey.Text, connType, "", nil)
go cl.Start()
} else {
// close the npc
status = "Start!"
if cl != nil {
go cl.Close()
cl = nil
}
}
refreshCh <- struct{}{}
onclick(serverPort.Text, vKey.Text, connType)
})
go func() {
for {
@@ -85,9 +67,9 @@ func makeMainTab() fyne.Widget {
}()
lo := widget.NewMultiLineEntry()
lo.SetReadOnly(true)
lo.Disable()
lo.Resize(fyne.NewSize(910, 250))
slo := widget.NewScrollContainer(lo)
slo := container.NewScroll(lo)
slo.Resize(fyne.NewSize(910, 250))
go func() {
for {
@@ -103,9 +85,10 @@ func makeMainTab() fyne.Widget {
vKey.SetText(vk)
connType = ct
radio.SetSelected(ct)
onclick(sp, vk, ct)
}
return widget.NewVBox(
return container.NewVBox(
widget.NewLabel("Npc "+version.VERSION),
serverPort,
vKey,
@@ -115,6 +98,44 @@ func makeMainTab() fyne.Widget {
)
}
func onclick(s, v, c string) {
start = !start
if start {
closing = false
status = "Stop!"
// init the npc
fmt.Println("submit", s, v, c)
sp, vk, ct := loadConfig()
if sp != s || vk != v || ct != c {
saveConfig(s, v, c)
}
go func() {
for {
cl = client.NewRPClient(s, v, c, "", nil, 60)
status = "Stop!"
refreshCh <- struct{}{}
cl.Start()
logs.Warn("client closed, reconnecting in 5 seconds...")
if closing {
return
}
status = "Reconnecting..."
refreshCh <- struct{}{}
time.Sleep(time.Second * 5)
}
}()
} else {
// close the npc
status = "Start!"
closing = true
if cl != nil {
go cl.Close()
cl = nil
}
}
refreshCh <- struct{}{}
}
func getDir() (dir string, err error) {
if runtime.GOOS != "android" {
dir, err = os.UserConfigDir()
@@ -142,7 +163,7 @@ func saveConfig(host, vkey, connType string) {
return
}
if _, err := f.Write([]byte(data)); err != nil {
f.Close() // ignore error; Write error takes precedence
_ = f.Close() // ignore error; Write error takes precedence
logs.Error(err)
return
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

-16
View File
@@ -36,19 +36,3 @@ WWW-Authenticate: Basic realm="easyProxy"
`
)
const (
MUX_PING_FLAG uint8 = iota
MUX_NEW_CONN_OK
MUX_NEW_CONN_Fail
MUX_NEW_MSG
MUX_NEW_MSG_PART
MUX_MSG_SEND_OK
MUX_NEW_CONN
MUX_CONN_CLOSE
MUX_PING_RETURN
MUX_PING int32 = -1
MAXIMUM_SEGMENT_SIZE = PoolSizeWindow
MAXIMUM_WINDOW_SIZE = 1 << 27 // 1<<31-1 TCP slide window size is very large,
// we use 128M, reduce memory usage
)
-218
View File
@@ -3,13 +3,11 @@ package common
import (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net"
"strconv"
"strings"
)
type NetPackager interface {
@@ -17,222 +15,6 @@ type NetPackager interface {
UnPack(reader io.Reader) (err error)
}
type BasePackager struct {
Length uint16
Content []byte
}
func (Self *BasePackager) NewPac(contents ...interface{}) (err error) {
Self.clean()
for _, content := range contents {
switch content.(type) {
case nil:
Self.Content = Self.Content[:0]
case []byte:
err = Self.appendByte(content.([]byte))
case string:
err = Self.appendByte([]byte(content.(string)))
if err != nil {
return
}
err = Self.appendByte([]byte(CONN_DATA_SEQ))
default:
err = Self.marshal(content)
}
}
Self.setLength()
if Self.Length > MAXIMUM_SEGMENT_SIZE {
err = errors.New("mux:packer: newpack content segment too large")
}
return
}
func (Self *BasePackager) appendByte(data []byte) (err error) {
m := len(Self.Content)
n := m + len(data)
if n <= cap(Self.Content) {
Self.Content = Self.Content[0:n] // grow the length for copy
copy(Self.Content[m:n], data)
return nil
} else {
return errors.New("pack content too large")
}
}
//似乎这里涉及到父类作用域问题,当子类调用父类的方法时,其struct仅仅为父类的
func (Self *BasePackager) Pack(writer io.Writer) (err error) {
err = binary.Write(writer, binary.LittleEndian, Self.Length)
if err != nil {
return
}
err = binary.Write(writer, binary.LittleEndian, Self.Content)
return
}
//Unpack 会导致传入的数字类型转化成float64!!
//主要原因是json unmarshal并未传入正确的数据类型
func (Self *BasePackager) UnPack(reader io.Reader) (n uint16, err error) {
Self.clean()
n += 2 // uint16
err = binary.Read(reader, binary.LittleEndian, &Self.Length)
if err != nil {
return
}
if int(Self.Length) > cap(Self.Content) {
err = errors.New("unpack err, content length too large")
return
}
if Self.Length > MAXIMUM_SEGMENT_SIZE {
err = errors.New("mux:packer: unpack content segment too large")
return
}
Self.Content = Self.Content[:int(Self.Length)]
//n, err := io.ReadFull(reader, Self.Content)
//if n != int(Self.Length) {
// err = io.ErrUnexpectedEOF
//}
err = binary.Read(reader, binary.LittleEndian, Self.Content)
n += Self.Length
return
}
func (Self *BasePackager) marshal(content interface{}) (err error) {
tmp, err := json.Marshal(content)
if err != nil {
return err
}
err = Self.appendByte(tmp)
return
}
func (Self *BasePackager) Unmarshal(content interface{}) (err error) {
err = json.Unmarshal(Self.Content, content)
if err != nil {
return err
}
return
}
func (Self *BasePackager) setLength() {
Self.Length = uint16(len(Self.Content))
return
}
func (Self *BasePackager) clean() {
Self.Length = 0
Self.Content = Self.Content[:0] // reset length
}
func (Self *BasePackager) Split() (strList []string) {
n := bytes.IndexByte(Self.Content, 0)
strList = strings.Split(string(Self.Content[:n]), CONN_DATA_SEQ)
strList = strList[0 : len(strList)-1]
return
}
type ConnPackager struct {
// Todo
ConnType uint8
BasePackager
}
func (Self *ConnPackager) NewPac(connType uint8, content ...interface{}) (err error) {
Self.ConnType = connType
err = Self.BasePackager.NewPac(content...)
return
}
func (Self *ConnPackager) Pack(writer io.Writer) (err error) {
err = binary.Write(writer, binary.LittleEndian, Self.ConnType)
if err != nil {
return
}
err = Self.BasePackager.Pack(writer)
return
}
func (Self *ConnPackager) UnPack(reader io.Reader) (n uint16, err error) {
err = binary.Read(reader, binary.LittleEndian, &Self.ConnType)
if err != nil && err != io.EOF {
return
}
n, err = Self.BasePackager.UnPack(reader)
n += 2
return
}
type MuxPackager struct {
Flag uint8
Id int32
Window uint64
BasePackager
}
func (Self *MuxPackager) NewPac(flag uint8, id int32, content ...interface{}) (err error) {
Self.Flag = flag
Self.Id = id
switch flag {
case MUX_PING_FLAG, MUX_PING_RETURN, MUX_NEW_MSG, MUX_NEW_MSG_PART:
Self.Content = WindowBuff.Get()
err = Self.BasePackager.NewPac(content...)
//logs.Warn(Self.Length, string(Self.Content))
case MUX_MSG_SEND_OK:
// MUX_MSG_SEND_OK contains one data
Self.Window = content[0].(uint64)
}
return
}
func (Self *MuxPackager) Pack(writer io.Writer) (err error) {
err = binary.Write(writer, binary.LittleEndian, Self.Flag)
if err != nil {
return
}
err = binary.Write(writer, binary.LittleEndian, Self.Id)
if err != nil {
return
}
switch Self.Flag {
case MUX_NEW_MSG, MUX_NEW_MSG_PART, MUX_PING_FLAG, MUX_PING_RETURN:
err = Self.BasePackager.Pack(writer)
WindowBuff.Put(Self.Content)
case MUX_MSG_SEND_OK:
err = binary.Write(writer, binary.LittleEndian, Self.Window)
}
return
}
func (Self *MuxPackager) UnPack(reader io.Reader) (n uint16, err error) {
err = binary.Read(reader, binary.LittleEndian, &Self.Flag)
if err != nil {
return
}
err = binary.Read(reader, binary.LittleEndian, &Self.Id)
if err != nil {
return
}
switch Self.Flag {
case MUX_NEW_MSG, MUX_NEW_MSG_PART, MUX_PING_FLAG, MUX_PING_RETURN:
Self.Content = WindowBuff.Get() // need get a window buf from pool
Self.BasePackager.clean() // also clean the content
n, err = Self.BasePackager.UnPack(reader)
//logs.Warn("unpack", Self.Length, string(Self.Content))
case MUX_MSG_SEND_OK:
err = binary.Read(reader, binary.LittleEndian, &Self.Window)
n += 8 // uint64
}
n += 5 //uint8 int32
return
}
func (Self *MuxPackager) reset() {
Self.Id = 0
Self.Flag = 0
Self.Length = 0
Self.Content = nil
Self.Window = 0
}
const (
ipV4 = 1
domainName = 3
-107
View File
@@ -1,7 +1,6 @@
package common
import (
"bytes"
"sync"
)
@@ -9,8 +8,6 @@ const PoolSize = 64 * 1024
const PoolSizeSmall = 100
const PoolSizeUdp = 1472 + 200
const PoolSizeCopy = 32 << 10
const PoolSizeBuffer = 4096
const PoolSizeWindow = PoolSizeBuffer - 2 - 4 - 4 - 1
var BufPool = sync.Pool{
New: func() interface{} {
@@ -86,115 +83,11 @@ func (Self *copyBufferPool) Put(x []byte) {
}
}
type windowBufferPool struct {
pool sync.Pool
}
func (Self *windowBufferPool) New() {
Self.pool = sync.Pool{
New: func() interface{} {
return make([]byte, PoolSizeWindow)
},
}
}
func (Self *windowBufferPool) Get() (buf []byte) {
buf = Self.pool.Get().([]byte)
buf = buf[:PoolSizeWindow]
return buf
}
func (Self *windowBufferPool) Put(x []byte) {
x = x[:0] // clean buf
Self.pool.Put(x)
}
type bufferPool struct {
pool sync.Pool
}
func (Self *bufferPool) New() {
Self.pool = sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 0, PoolSizeBuffer))
},
}
}
func (Self *bufferPool) Get() *bytes.Buffer {
return Self.pool.Get().(*bytes.Buffer)
}
func (Self *bufferPool) Put(x *bytes.Buffer) {
x.Reset()
Self.pool.Put(x)
}
type muxPackagerPool struct {
pool sync.Pool
}
func (Self *muxPackagerPool) New() {
Self.pool = sync.Pool{
New: func() interface{} {
pack := MuxPackager{}
return &pack
},
}
}
func (Self *muxPackagerPool) Get() *MuxPackager {
return Self.pool.Get().(*MuxPackager)
}
func (Self *muxPackagerPool) Put(pack *MuxPackager) {
pack.reset()
Self.pool.Put(pack)
}
type ListElement struct {
Buf []byte
L uint16
Part bool
}
type listElementPool struct {
pool sync.Pool
}
func (Self *listElementPool) New() {
Self.pool = sync.Pool{
New: func() interface{} {
element := ListElement{}
return &element
},
}
}
func (Self *listElementPool) Get() *ListElement {
return Self.pool.Get().(*ListElement)
}
func (Self *listElementPool) Put(element *ListElement) {
element.L = 0
element.Buf = nil
element.Part = false
Self.pool.Put(element)
}
var once = sync.Once{}
var BuffPool = bufferPool{}
var CopyBuff = copyBufferPool{}
var MuxPack = muxPackagerPool{}
var WindowBuff = windowBufferPool{}
var ListElementPool = listElementPool{}
func newPool() {
BuffPool.New()
CopyBuff.New()
MuxPack.New()
WindowBuff.New()
ListElementPool.New()
}
func init() {
+29
View File
@@ -0,0 +1,29 @@
package common
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"net/http"
_ "net/http/pprof"
)
func InitPProfFromFile() {
ip := beego.AppConfig.String("pprof_ip")
p := beego.AppConfig.String("pprof_port")
if len(ip) > 0 && len(p) > 0 && IsPort(p) {
runPProf(ip + ":" + p)
}
}
func InitPProfFromArg(arg string) {
if len(arg) > 0 {
runPProf(arg)
}
}
func runPProf(ipPort string) {
go func() {
_ = http.ListenAndServe(ipPort, nil)
}()
logs.Info("PProf debug listen on", ipPort)
}
+18 -2
View File
@@ -11,8 +11,12 @@ import (
//windows system, select the C:\Program Files\nps as config directory if exist, or select ./
func GetRunPath() string {
var path string
if path = GetInstallPath(); !FileExists(path) {
return GetAppPath()
if len(os.Args) <= 1 {
return "./"
} else {
if path = GetInstallPath(); !FileExists(path) {
return GetAppPath()
}
}
return path
}
@@ -25,6 +29,7 @@ func GetInstallPath() string {
} else {
path = "/etc/nps"
}
return path
}
@@ -76,3 +81,14 @@ func GetTmpPath() string {
}
return path
}
//config file path
func GetConfigPath() string {
var path string
if IsWindows() {
path = filepath.Join(GetAppPath(), "conf/npc.conf")
} else {
path = "conf/npc.conf"
}
return path
}
+33 -3
View File
@@ -2,9 +2,12 @@ package common
import (
"bytes"
"ehang.io/nps/lib/version"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"github.com/astaxie/beego/logs"
"html/template"
"io"
"io/ioutil"
@@ -12,6 +15,7 @@ import (
"net/http"
"os"
"regexp"
"sort"
"strconv"
"strings"
"sync"
@@ -98,7 +102,7 @@ func Getverifyval(vkey string) string {
}
//Change headers and host of request
func ChangeHostAndHeader(r *http.Request, host string, header string, addr string) {
func ChangeHostAndHeader(r *http.Request, host string, header string, addr string, addOrigin bool) {
if host != "" {
r.Host = host
}
@@ -115,8 +119,10 @@ func ChangeHostAndHeader(r *http.Request, host string, header string, addr strin
if prior, ok := r.Header["X-Forwarded-For"]; ok {
addr = strings.Join(prior, ", ") + ", " + addr
}
r.Header.Set("X-Forwarded-For", addr)
r.Header.Set("X-Real-IP", addr)
if addOrigin {
r.Header.Set("X-Forwarded-For", addr)
r.Header.Set("X-Real-IP", addr)
}
}
//Read file content by file path
@@ -271,6 +277,26 @@ func GetPortByAddr(addr string) int {
return p
}
func in(target string, str_array []string) bool {
sort.Strings(str_array)
index := sort.SearchStrings(str_array, target)
if index < len(str_array) && str_array[index] == target {
return true
}
return false
}
// 判断访问地址是否在黑名单内
func IsBlackIp(ipPort, vkey string, blackIpList []string) bool {
ip := GetIpByAddr(ipPort)
if in(ip, blackIpList) {
logs.Error("IP地址[" + ip + "]在隧道[" + vkey + "]黑名单列表内")
return true
}
return false
}
func CopyBuffer(dst io.Writer, src io.Reader, label ...string) (written int64, err error) {
buf := CopyBuff.Get()
defer CopyBuff.Put(buf)
@@ -459,3 +485,7 @@ func GetServerIpByClientIp(clientIp net.IP) string {
_, ip := GetIntranetIp()
return ip
}
func PrintVersion() {
fmt.Printf("Version: %s\nCore version: %s\nSame core version of client and server can connect each other\n", version.VERSION, version.GetVersion())
}
+6 -1
View File
@@ -17,6 +17,7 @@ type CommonConfig struct {
AutoReconnection bool
ProxyUrl string
Client *file.Client
DisconnectTime int
}
type LocalServer struct {
@@ -145,6 +146,10 @@ func dealCommon(s string) *CommonConfig {
c.Client.MaxConn = common.GetIntNoErrByStr(item[1])
case "remark":
c.Client.Remark = item[1]
case "pprof_addr":
common.InitPProfFromArg(item[1])
case "disconnect_timeout":
c.DisconnectTime = common.GetIntNoErrByStr(item[1])
}
}
return c
@@ -297,7 +302,7 @@ func delLocalService(s string) *LocalServer {
func getAllTitle(content string) (arr []string, err error) {
var re *regexp.Regexp
re, err = regexp.Compile(`\[.+?\]`)
re, err = regexp.Compile(`(?m)^\[[^\[\]\r\n]+\]`)
if err != nil {
return
}
+35 -8
View File
@@ -14,12 +14,13 @@ import (
"net/url"
"strconv"
"strings"
"sync"
"time"
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/crypt"
"ehang.io/nps/lib/file"
"ehang.io/nps/lib/mux"
"ehang.io/nps/lib/pmux"
"ehang.io/nps/lib/rate"
"github.com/xtaci/kcp-go"
)
@@ -34,11 +35,33 @@ func NewConn(conn net.Conn) *Conn {
return &Conn{Conn: conn}
}
func (s *Conn) readRequest(buf []byte) (n int, err error) {
var rd int
for {
rd, err = s.Read(buf[n:])
if err != nil {
return
}
n += rd
if n < 4 {
continue
}
if string(buf[n-4:n]) == "\r\n\r\n" {
return
}
// buf is full, can't contain the request
if n == cap(buf) {
err = io.ErrUnexpectedEOF
return
}
}
}
//get host 、connection type、method...from connection
func (s *Conn) GetHost() (method, address string, rb []byte, err error, r *http.Request) {
var b [32 * 1024]byte
var n int
if n, err = s.Read(b[:]); err != nil {
if n, err = s.readRequest(b[:]); err != nil {
return
}
rb = b[:n]
@@ -126,8 +149,8 @@ func (s *Conn) SetAlive(tp string) {
conn.SetReadDeadline(time.Time{})
//conn.SetKeepAlive(false)
//conn.SetKeepAlivePeriod(time.Duration(2 * time.Second))
case *mux.PortConn:
s.Conn.(*mux.PortConn).SetReadDeadline(time.Time{})
case *pmux.PortConn:
s.Conn.(*pmux.PortConn).SetReadDeadline(time.Time{})
}
}
@@ -138,8 +161,8 @@ func (s *Conn) SetReadDeadlineBySecond(t time.Duration) {
s.Conn.(*kcp.UDPSession).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
case *net.TCPConn:
s.Conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
case *mux.PortConn:
s.Conn.(*mux.PortConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
case *pmux.PortConn:
s.Conn.(*pmux.PortConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
}
}
@@ -350,7 +373,8 @@ func SetUdpSession(sess *kcp.UDPSession) {
}
//conn1 mux conn
func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Rate, flow *file.Flow, isServer bool, rb []byte) {
func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Rate,
flow *file.Flow, isServer bool, rb []byte, task *file.Tunnel) {
//var in, out int64
//var wg sync.WaitGroup
connHandle := GetConn(conn1, crypt, snappy, rate, isServer)
@@ -371,7 +395,10 @@ func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Ra
//if flow != nil {
// flow.Add(in, out)
//}
err := goroutine.CopyConnsPool.Invoke(goroutine.NewConns(connHandle, conn2, flow))
wg := new(sync.WaitGroup)
wg.Add(1)
err := goroutine.CopyConnsPool.Invoke(goroutine.NewConns(connHandle, conn2, flow, wg, task))
wg.Wait()
if err != nil {
logs.Error(err)
}
+15 -2
View File
@@ -1,6 +1,7 @@
package conn
import (
"errors"
"io"
"github.com/golang/snappy"
@@ -9,12 +10,14 @@ import (
type SnappyConn struct {
w *snappy.Writer
r *snappy.Reader
c io.Closer
}
func NewSnappyConn(conn io.ReadWriteCloser) *SnappyConn {
c := new(SnappyConn)
c.w = snappy.NewBufferedWriter(conn)
c.r = snappy.NewReader(conn)
c.c = conn.(io.Closer)
return c
}
@@ -35,6 +38,16 @@ func (s *SnappyConn) Read(b []byte) (n int, err error) {
}
func (s *SnappyConn) Close() error {
s.w.Close()
return s.w.Close()
err := s.w.Close()
err2 := s.c.Close()
if err != nil && err2 == nil {
return err
}
if err == nil && err2 != nil {
return err2
}
if err != nil && err2 != nil {
return errors.New(err.Error() + err2.Error())
}
return nil
}
+58 -5
View File
@@ -1,22 +1,37 @@
package crypt
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"log"
"math/big"
"net"
"os"
"time"
"github.com/astaxie/beego/logs"
)
var pemPath, keyPath string
var (
cert tls.Certificate
)
func InitTls(pem, key string) {
pemPath = pem
keyPath = key
func InitTls() {
c, k, err := generateKeyPair("NPS Org")
if err == nil {
cert, err = tls.X509KeyPair(c, k)
}
if err != nil {
log.Fatalln("Error initializing crypto certs", err)
}
}
func NewTlsServerConn(conn net.Conn) net.Conn {
cert, err := tls.LoadX509KeyPair(pemPath, keyPath)
var err error
if err != nil {
logs.Error(err)
os.Exit(0)
@@ -32,3 +47,41 @@ func NewTlsClientConn(conn net.Conn) net.Conn {
}
return tls.Client(conn, conf)
}
func generateKeyPair(CommonName string) (rawCert, rawKey []byte, err error) {
// Create private key and self-signed certificate
// Adapted from https://golang.org/src/crypto/tls/generate_cert.go
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return
}
validFor := time.Hour * 24 * 365 * 10 // ten years
notBefore := time.Now()
notAfter := notBefore.Add(validFor)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"My Company Name LTD."},
CommonName: CommonName,
Country: []string{"US"},
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return
}
rawCert = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
rawKey = pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
return
}
+9 -7
View File
@@ -4,7 +4,6 @@ import (
"errors"
"fmt"
"net/http"
"regexp"
"sort"
"strings"
"sync"
@@ -182,7 +181,7 @@ func (s *DbUtils) GetHost(start, length int, id int, search string) ([]*Host, in
for _, key := range keys {
if value, ok := s.JsonDb.Hosts.Load(key); ok {
v := value.(*Host)
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.Host, search) || strings.Contains(v.Remark, search)) {
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.Host, search) || strings.Contains(v.Remark, search) || strings.Contains(v.Client.VerifyKey, search)) {
continue
}
if id == 0 || v.Client.Id == id {
@@ -328,13 +327,16 @@ func (s *DbUtils) GetInfoByHost(host string, r *http.Request) (h *Host, err erro
}
//Remove http(s) http(s)://a.proxy.com
//*.proxy.com *.a.proxy.com Do some pan-parsing
tmp := strings.Replace(v.Host, "*", `\w+?`, -1)
var re *regexp.Regexp
if re, err = regexp.Compile(tmp); err != nil {
if v.Scheme != "all" && v.Scheme != r.URL.Scheme {
return true
}
if len(re.FindAllString(host, -1)) > 0 && (v.Scheme == "all" || v.Scheme == r.URL.Scheme) {
//URL routing
tmpHost := v.Host
if strings.Contains(tmpHost, "*") {
tmpHost = strings.Replace(tmpHost, "*", "", -1)
if strings.Contains(host, tmpHost) {
hosts = append(hosts, v)
}
} else if v.Host == host {
hosts = append(hosts, v)
}
return true
+23 -2
View File
@@ -3,6 +3,7 @@ package file
import (
"encoding/json"
"errors"
"github.com/astaxie/beego/logs"
"os"
"path/filepath"
"strings"
@@ -99,16 +100,28 @@ func (s *JsonDb) GetClient(id int) (c *Client, err error) {
return
}
var hostLock sync.Mutex
func (s *JsonDb) StoreHostToJsonFile() {
hostLock.Lock()
storeSyncMapToFile(s.Hosts, s.HostFilePath)
hostLock.Unlock()
}
var taskLock sync.Mutex
func (s *JsonDb) StoreTasksToJsonFile() {
taskLock.Lock()
storeSyncMapToFile(s.Tasks, s.TaskFilePath)
taskLock.Unlock()
}
var clientLock sync.Mutex
func (s *JsonDb) StoreClientsToJsonFile() {
clientLock.Lock()
storeSyncMapToFile(s.Clients, s.ClientFilePath)
clientLock.Unlock()
}
func (s *JsonDb) GetClientId() int32 {
@@ -134,11 +147,11 @@ func loadSyncMapFromFile(filePath string, f func(value string)) {
}
func storeSyncMapToFile(m sync.Map, filePath string) {
file, err := os.Create(filePath)
file, err := os.Create(filePath + ".tmp")
// first create a temporary file to store
if err != nil {
panic(err)
}
defer file.Close()
m.Range(func(key, value interface{}) bool {
var b []byte
var err error
@@ -177,4 +190,12 @@ func storeSyncMapToFile(m sync.Map, filePath string) {
}
return true
})
_ = file.Sync()
_ = file.Close()
// must close file first, then rename it
err = os.Rename(filePath+".tmp", filePath)
if err != nil {
logs.Error(err, "store to file err, data will lost")
}
// replace the file, maybe provides atomic operation
}
+2
View File
@@ -51,6 +51,7 @@ type Client struct {
ConfigConnAllow bool //is allow connected by config file
MaxTunnelNum int
Version string
BlackIpList []string
sync.RWMutex
}
@@ -138,6 +139,7 @@ type Tunnel struct {
Remark string
TargetAddr string
NoStore bool
IsHttp bool
LocalPath string
StripPre string
Target *Target
+108 -16
View File
@@ -3,40 +3,125 @@ package goroutine
import (
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/file"
"github.com/astaxie/beego/logs"
"github.com/panjf2000/ants/v2"
"io"
"net"
"strings"
"sync"
)
type connGroup struct {
src io.ReadWriteCloser
dst io.ReadWriteCloser
wg *sync.WaitGroup
n *int64
src io.ReadWriteCloser
dst io.ReadWriteCloser
wg *sync.WaitGroup
n *int64
flow *file.Flow
task *file.Tunnel
remote string
}
func newConnGroup(dst, src io.ReadWriteCloser, wg *sync.WaitGroup, n *int64) connGroup {
//func newConnGroup(dst, src io.ReadWriteCloser, wg *sync.WaitGroup, n *int64) connGroup {
// return connGroup{
// src: src,
// dst: dst,
// wg: wg,
// n: n,
// }
//}
func newConnGroup(dst, src io.ReadWriteCloser, wg *sync.WaitGroup, n *int64, flow *file.Flow, task *file.Tunnel, remote string) connGroup {
return connGroup{
src: src,
dst: dst,
wg: wg,
n: n,
src: src,
dst: dst,
wg: wg,
n: n,
flow: flow,
task: task,
remote: remote,
}
}
func CopyBuffer(dst io.Writer, src io.Reader, flow *file.Flow, task *file.Tunnel, remote string) (err error) {
buf := common.CopyBuff.Get()
defer common.CopyBuff.Put(buf)
for {
if len(buf) <= 0 {
break
}
nr, er := src.Read(buf)
//if len(pr)>0 && pr[0] && nr > 50 {
// logs.Warn(string(buf[:50]))
//}
if task != nil {
task.IsHttp = false
firstLine := string(buf[0:nr])
if len(firstLine) > 3 {
method := firstLine[0:3]
if method != "" && (method == "HTT" || method == "GET" || method == "POS" || method == "HEA" || method == "PUT" || method == "DEL") {
if method != "HTT" {
heads := strings.Split(firstLine, "\r\n")
if len(heads) >= 2 {
logs.Info("HTTP Request method %s, %s, remote address %s, target %s", heads[0], heads[1], remote, task.Target.TargetStr)
}
}
task.IsHttp = true
}
}
}
if nr > 0 {
nw, ew := dst.Write(buf[0:nr])
if nw > 0 {
//written += int64(nw)
if flow != nil {
flow.Add(int64(nw), int64(nw))
// <<20 = 1024 * 1024
if flow.FlowLimit > 0 && (flow.FlowLimit<<20) < (flow.ExportFlow+flow.InletFlow) {
logs.Info("流量已经超出.........")
break
}
}
}
if ew != nil {
err = ew
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
}
if er != nil {
err = er
break
}
}
//return written, err
return err
}
func copyConnGroup(group interface{}) {
//logs.Info("copyConnGroup.........")
cg, ok := group.(connGroup)
if !ok {
return
}
var err error
*cg.n, err = common.CopyBuffer(cg.dst, cg.src)
err = CopyBuffer(cg.dst, cg.src, cg.flow, cg.task, cg.remote)
if err != nil {
cg.src.Close()
cg.dst.Close()
//logs.Warn("close npc by copy from nps", err, c.connId)
}
//if conns.flow != nil {
// conns.flow.Add(in, out)
//}
cg.wg.Done()
}
@@ -44,29 +129,36 @@ type Conns struct {
conn1 io.ReadWriteCloser // mux connection
conn2 net.Conn // outside connection
flow *file.Flow
wg *sync.WaitGroup
task *file.Tunnel
}
func NewConns(c1 io.ReadWriteCloser, c2 net.Conn, flow *file.Flow) Conns {
func NewConns(c1 io.ReadWriteCloser, c2 net.Conn, flow *file.Flow, wg *sync.WaitGroup, task *file.Tunnel) Conns {
return Conns{
conn1: c1,
conn2: c2,
flow: flow,
wg: wg,
task: task,
}
}
func copyConns(group interface{}) {
//logs.Info("copyConns.........")
conns := group.(Conns)
wg := new(sync.WaitGroup)
wg.Add(2)
var in, out int64
_ = connCopyPool.Invoke(newConnGroup(conns.conn1, conns.conn2, wg, &in))
remoteAddr := conns.conn2.RemoteAddr().String()
_ = connCopyPool.Invoke(newConnGroup(conns.conn1, conns.conn2, wg, &in, conns.flow, conns.task, remoteAddr))
// outside to mux : incoming
_ = connCopyPool.Invoke(newConnGroup(conns.conn2, conns.conn1, wg, &out))
_ = connCopyPool.Invoke(newConnGroup(conns.conn2, conns.conn1, wg, &out, conns.flow, conns.task, remoteAddr))
// mux to outside : outgoing
wg.Wait()
if conns.flow != nil {
conns.flow.Add(in, out)
}
//if conns.flow != nil {
// conns.flow.Add(in, out)
//}
conns.wg.Done()
}
var connCopyPool, _ = ants.NewPoolWithFunc(200000, copyConnGroup, ants.WithNonblocking(false))
+120 -1
View File
@@ -16,6 +16,124 @@ import (
"strings"
)
// Keep it in sync with the template from service_sysv_linux.go file
// Use "ps | grep -v grep | grep $(get_pid)" because "ps PID" may not work on OpenWrt
const SysvScript = `#!/bin/sh
# For RedHat and cousins:
# chkconfig: - 99 01
# description: {{.Description}}
# processname: {{.Path}}
### BEGIN INIT INFO
# Provides: {{.Path}}
# Required-Start:
# Required-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: {{.DisplayName}}
# Description: {{.Description}}
### END INIT INFO
cmd="{{.Path}}{{range .Arguments}} {{.|cmd}}{{end}}"
name=$(basename $(readlink -f $0))
pid_file="/var/run/$name.pid"
stdout_log="/var/log/$name.log"
stderr_log="/var/log/$name.err"
[ -e /etc/sysconfig/$name ] && . /etc/sysconfig/$name
get_pid() {
cat "$pid_file"
}
is_running() {
[ -f "$pid_file" ] && ps | grep -v grep | grep $(get_pid) > /dev/null 2>&1
}
case "$1" in
start)
if is_running; then
echo "Already started"
else
echo "Starting $name"
{{if .WorkingDirectory}}cd '{{.WorkingDirectory}}'{{end}}
$cmd >> "$stdout_log" 2>> "$stderr_log" &
echo $! > "$pid_file"
if ! is_running; then
echo "Unable to start, see $stdout_log and $stderr_log"
exit 1
fi
fi
;;
stop)
if is_running; then
echo -n "Stopping $name.."
kill $(get_pid)
for i in $(seq 1 10)
do
if ! is_running; then
break
fi
echo -n "."
sleep 1
done
echo
if is_running; then
echo "Not stopped; may still be shutting down or shutdown may have failed"
exit 1
else
echo "Stopped"
if [ -f "$pid_file" ]; then
rm "$pid_file"
fi
fi
else
echo "Not running"
fi
;;
restart)
$0 stop
if is_running; then
echo "Unable to stop, will not attempt to start"
exit 1
fi
$0 start
;;
status)
if is_running; then
echo "Running"
else
echo "Stopped"
exit 1
fi
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
exit 1
;;
esac
exit 0
`
const SystemdScript = `[Unit]
Description={{.Description}}
ConditionFileIsExecutable={{.Path|cmdEscape}}
{{range $i, $dep := .Dependencies}}
{{$dep}} {{end}}
[Service]
LimitNOFILE=65536
StartLimitInterval=5
StartLimitBurst=10
ExecStart={{.Path|cmdEscape}}{{range .Arguments}} {{.|cmd}}{{end}}
{{if .ChRoot}}RootDirectory={{.ChRoot|cmd}}{{end}}
{{if .WorkingDirectory}}WorkingDirectory={{.WorkingDirectory|cmdEscape}}{{end}}
{{if .UserName}}User={{.UserName}}{{end}}
{{if .ReloadSignal}}ExecReload=/bin/kill -{{.ReloadSignal}} "$MAINPID"{{end}}
{{if .PIDFile}}PIDFile={{.PIDFile|cmd}}{{end}}
{{if and .LogOutput .HasOutputFileSupport -}}
StandardOutput=file:/var/log/{{.Name}}.out
StandardError=file:/var/log/{{.Name}}.err
{{- end}}
Restart=always
RestartSec=120
[Install]
WantedBy=multi-user.target
`
func UpdateNps() {
destPath := downloadLatest("server")
//复制文件到对应目录
@@ -36,7 +154,7 @@ type release struct {
func downloadLatest(bin string) string {
// get version
data, err := http.Get("https://api.github.com/repos/cnlh/nps/releases/latest")
data, err := http.Get("https://api.github.com/repos/ehang-io/nps/releases/latest")
if err != nil {
log.Fatal(err.Error())
}
@@ -121,6 +239,7 @@ func InstallNpc() {
func InstallNps() string {
path := common.GetInstallPath()
log.Println("install path:" + path)
if common.FileExists(path) {
MkidrDirAll(path, "web/static", "web/views")
} else {
-32
View File
@@ -1,32 +0,0 @@
package mux
import (
"bytes"
"encoding/binary"
"io"
)
//write bytes with int32 length
func WriteLenBytes(buf []byte, w io.Writer) (int, error) {
raw := bytes.NewBuffer([]byte{})
if err := binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
return 0, err
}
if err := binary.Write(raw, binary.LittleEndian, buf); err != nil {
return 0, err
}
return w.Write(raw.Bytes())
}
//read bytes by length
func ReadLenBytes(buf []byte, r io.Reader) (int, error) {
var l uint32
var err error
if binary.Read(r, binary.LittleEndian, &l) != nil {
return 0, err
}
if _, err = io.ReadFull(r, buf[:l]); err != nil {
return 0, err
}
return int(l), nil
}
-75
View File
@@ -1,75 +0,0 @@
package mux
import (
"sync"
)
type connMap struct {
connMap map[int32]*conn
//closeCh chan struct{}
sync.RWMutex
}
func NewConnMap() *connMap {
connMap := &connMap{
connMap: make(map[int32]*conn),
//closeCh: make(chan struct{}),
}
//go connMap.clean()
return connMap
}
func (s *connMap) Size() (n int) {
s.Lock()
n = len(s.connMap)
s.Unlock()
return
}
func (s *connMap) Get(id int32) (*conn, bool) {
s.Lock()
v, ok := s.connMap[id]
s.Unlock()
if ok && v != nil {
return v, true
}
return nil, false
}
func (s *connMap) Set(id int32, v *conn) {
s.Lock()
s.connMap[id] = v
s.Unlock()
}
func (s *connMap) Close() {
//s.closeCh <- struct{}{} // stop the clean goroutine first
for _, v := range s.connMap {
v.Close() // close all the connections in the mux
}
}
func (s *connMap) Delete(id int32) {
s.Lock()
delete(s.connMap, id)
s.Unlock()
}
//func (s *connMap) clean() {
// ticker := time.NewTimer(time.Minute * 1)
// for {
// select {
// case <-ticker.C:
// s.Lock()
// for _, v := range s.connMap {
// if v.isClose {
// delete(s.connMap, v.connId)
// }
// }
// s.Unlock()
// case <-s.closeCh:
// ticker.Stop()
// return
// }
// }
//}
-453
View File
@@ -1,453 +0,0 @@
package mux
import (
"bufio"
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/goroutine"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
_ "net/http/pprof"
"strconv"
"testing"
"time"
"unsafe"
"github.com/astaxie/beego/logs"
)
var conn1 net.Conn
var conn2 net.Conn
func TestNewMux(t *testing.T) {
go func() {
http.ListenAndServe("0.0.0.0:8889", nil)
}()
logs.EnableFuncCallDepth(true)
logs.SetLogFuncCallDepth(3)
server()
client()
//poolConnCopy, _ := ants.NewPoolWithFunc(200000, common.copyConn, ants.WithNonblocking(false))
time.Sleep(time.Second * 3)
go func() {
m2 := NewMux(conn2, "tcp")
//m2 := NewMux(conn2, "kcp")
for {
//logs.Warn("npc starting accept")
c, err := m2.Accept()
if err != nil {
logs.Warn(err)
continue
}
//logs.Warn("npc accept success ")
c2, err := net.Dial("tcp", "127.0.0.1:80")
if err != nil {
logs.Warn(err)
c.Close()
continue
}
//c2.(*net.TCPConn).SetReadBuffer(0)
//c2.(*net.TCPConn).SetReadBuffer(0)
_ = goroutine.CopyConnsPool.Invoke(goroutine.NewConns(c, c2, nil))
//go func(c2 net.Conn, c *conn) {
// wg := new(sync.WaitGroup)
// wg.Add(2)
// _ = poolConnCopy.Invoke(common.newConnGroup(c2, c, wg))
// //go func() {
// // _, err = common.CopyBuffer(c2, c)
// // if err != nil {
// // c2.Close()
// // c.Close()
// // //logs.Warn("close npc by copy from nps", err, c.connId)
// // }
// // wg.Done()
// //}()
// //wg.Add(1)
// _ = poolConnCopy.Invoke(common.newConnGroup(c, c2, wg))
// //go func() {
// // _, err = common.CopyBuffer(c, c2)
// // if err != nil {
// // c2.Close()
// // c.Close()
// // //logs.Warn("close npc by copy from server", err, c.connId)
// // }
// // wg.Done()
// //}()
// //logs.Warn("npc wait")
// wg.Wait()
//}(c2, c.(*conn))
}
}()
go func() {
m1 := NewMux(conn1, "tcp")
//m1 := NewMux(conn1, "kcp")
l, err := net.Listen("tcp", "127.0.0.1:7777")
if err != nil {
logs.Warn(err)
}
for {
//logs.Warn("nps starting accept")
conns, err := l.Accept()
if err != nil {
logs.Warn(err)
continue
}
//conns.(*net.TCPConn).SetReadBuffer(0)
//conns.(*net.TCPConn).SetReadBuffer(0)
//logs.Warn("nps accept success starting new conn")
tmpCpnn, err := m1.NewConn()
if err != nil {
logs.Warn("nps new conn err ", err)
continue
}
//logs.Warn("nps new conn success ", tmpCpnn.connId)
_ = goroutine.CopyConnsPool.Invoke(goroutine.NewConns(tmpCpnn, conns, nil))
//go func(tmpCpnn *conn, conns net.Conn) {
// wg := new(sync.WaitGroup)
// wg.Add(2)
// _ = poolConnCopy.Invoke(common.newConnGroup(tmpCpnn, conns, wg))
// //go func() {
// // _, err := common.CopyBuffer(tmpCpnn, conns)
// // if err != nil {
// // conns.Close()
// // tmpCpnn.Close()
// // //logs.Warn("close nps by copy from user", tmpCpnn.connId, err)
// // }
// //}()
// //wg.Add(1)
// _ = poolConnCopy.Invoke(common.newConnGroup(conns, tmpCpnn, wg))
// //time.Sleep(time.Second)
// //_, err = common.CopyBuffer(conns, tmpCpnn)
// //if err != nil {
// // conns.Close()
// // tmpCpnn.Close()
// // //logs.Warn("close nps by copy from npc ", tmpCpnn.connId, err)
// //}
// wg.Wait()
//}(tmpCpnn, conns)
}
}()
//go NewLogServer()
time.Sleep(time.Second * 5)
//for i := 0; i < 1; i++ {
// go test_raw(i)
//}
//test_request()
for {
time.Sleep(time.Second * 5)
}
}
func server() {
var err error
l, err := net.Listen("tcp", "127.0.0.1:9999")
//l, err := kcp.Listen("127.0.0.1:9999")
if err != nil {
logs.Warn(err)
}
go func() {
conn1, err = l.Accept()
//logs.Info("accept", conn1)
if err != nil {
logs.Warn(err)
}
}()
return
}
func client() {
var err error
conn2, err = net.Dial("tcp", "127.0.0.1:9999")
//logs.Warn("dial")
//conn2, err = kcp.Dial("127.0.0.1:9999")
if err != nil {
logs.Warn(err)
}
}
func test_request() {
conn, _ := net.Dial("tcp", "127.0.0.1:7777")
for i := 0; i < 1000; i++ {
conn.Write([]byte(`GET / HTTP/1.1
Host: 127.0.0.1:7777
Connection: keep-alive
`))
r, err := http.ReadResponse(bufio.NewReader(conn), nil)
if err != nil {
logs.Warn("close by read response err", err)
break
}
logs.Warn("read response success", r)
b, err := httputil.DumpResponse(r, true)
if err != nil {
logs.Warn("close by dump response err", err)
break
}
fmt.Println(string(b[:20]), err)
//time.Sleep(time.Second)
}
logs.Warn("finish")
}
func test_raw(k int) {
for i := 0; i < 1000; i++ {
ti := time.Now()
conn, err := net.Dial("tcp", "127.0.0.1:7777")
if err != nil {
logs.Warn("conn dial err", err)
}
tid := time.Now()
conn.Write([]byte(`GET /videojs5/video.js HTTP/1.1
Host: 127.0.0.1:7777
`))
tiw := time.Now()
buf := make([]byte, 3572)
n, err := io.ReadFull(conn, buf)
//n, err := conn.Read(buf)
if err != nil {
logs.Warn("close by read response err", err)
break
}
logs.Warn(n, string(buf[:50]), "\n--------------\n", string(buf[n-50:n]))
//time.Sleep(time.Second)
err = conn.Close()
if err != nil {
logs.Warn("close conn err ", err)
}
now := time.Now()
du := now.Sub(ti).Seconds()
dud := now.Sub(tid).Seconds()
duw := now.Sub(tiw).Seconds()
if du > 1 {
logs.Warn("duration long", du, dud, duw, k, i)
}
if n != 3572 {
logs.Warn("n loss", n, string(buf))
}
}
logs.Warn("finish")
}
func TestNewConn(t *testing.T) {
buf := common.GetBufPoolCopy()
logs.Warn(len(buf), cap(buf))
//b := pool.GetBufPoolCopy()
//b[0] = 1
//b[1] = 2
//b[2] = 3
b := []byte{1, 2, 3}
logs.Warn(copy(buf[:3], b), len(buf), cap(buf))
logs.Warn(len(buf), buf[0])
}
func TestDQueue(t *testing.T) {
logs.EnableFuncCallDepth(true)
logs.SetLogFuncCallDepth(3)
d := new(bufDequeue)
d.vals = make([]unsafe.Pointer, 8)
go func() {
time.Sleep(time.Second)
for i := 0; i < 10; i++ {
logs.Warn(i)
logs.Warn(d.popTail())
}
}()
go func() {
time.Sleep(time.Second)
for i := 0; i < 10; i++ {
data := "test"
go logs.Warn(i, unsafe.Pointer(&data), d.pushHead(unsafe.Pointer(&data)))
}
}()
time.Sleep(time.Second * 3)
}
func TestChain(t *testing.T) {
go func() {
log.Println(http.ListenAndServe("0.0.0.0:8889", nil))
}()
logs.EnableFuncCallDepth(true)
logs.SetLogFuncCallDepth(3)
time.Sleep(time.Second * 5)
d := new(bufChain)
d.new(256)
go func() {
time.Sleep(time.Second)
for i := 0; i < 30000; i++ {
unsa, ok := d.popTail()
str := (*string)(unsa)
if ok {
fmt.Println(i, str, *str, ok)
//logs.Warn(i, str, *str, ok)
} else {
fmt.Println("nil", i, ok)
//logs.Warn("nil", i, ok)
}
}
}()
go func() {
time.Sleep(time.Second)
for i := 0; i < 3000; i++ {
go func(i int) {
for n := 0; n < 10; n++ {
data := "test " + strconv.Itoa(i) + strconv.Itoa(n)
fmt.Println(data, unsafe.Pointer(&data))
//logs.Warn(data, unsafe.Pointer(&data))
d.pushHead(unsafe.Pointer(&data))
}
}(i)
}
}()
time.Sleep(time.Second * 100000)
}
func TestFIFO(t *testing.T) {
go func() {
log.Println(http.ListenAndServe("0.0.0.0:8889", nil))
}()
logs.EnableFuncCallDepth(true)
logs.SetLogFuncCallDepth(3)
time.Sleep(time.Second * 5)
d := new(ReceiveWindowQueue)
d.New()
go func() {
time.Sleep(time.Second)
for i := 0; i < 1001; i++ {
data, err := d.Pop()
if err == nil {
//fmt.Println(i, string(data.buf), err)
logs.Warn(i, string(data.Buf), err)
common.ListElementPool.Put(data)
} else {
//fmt.Println("err", err)
logs.Warn("err", err)
}
//logs.Warn(d.Len())
}
logs.Warn("pop finish")
}()
go func() {
time.Sleep(time.Second * 10)
for i := 0; i < 1000; i++ {
by := []byte("test " + strconv.Itoa(i) + " ") //
data, _ := NewListElement(by, uint16(len(by)), true)
//fmt.Println(string((*data).buf), data)
//logs.Warn(string((*data).buf), data)
d.Push(data)
}
}()
time.Sleep(time.Second * 100000)
}
func TestPriority(t *testing.T) {
go func() {
log.Println(http.ListenAndServe("0.0.0.0:8889", nil))
}()
logs.EnableFuncCallDepth(true)
logs.SetLogFuncCallDepth(3)
time.Sleep(time.Second * 5)
d := new(PriorityQueue)
d.New()
go func() {
time.Sleep(time.Second)
for i := 0; i < 360050; i++ {
data := d.Pop()
//fmt.Println(i, string(data.buf), err)
logs.Warn(i, string(data.Content), data)
}
logs.Warn("pop finish")
}()
go func() {
time.Sleep(time.Second * 10)
for i := 0; i < 30000; i++ {
go func(i int) {
for n := 0; n < 10; n++ {
data := new(common.MuxPackager)
by := []byte("test " + strconv.Itoa(i) + strconv.Itoa(n))
_ = data.NewPac(common.MUX_NEW_MSG_PART, int32(i), by)
//fmt.Println(string((*data).buf), data)
logs.Warn(string((*data).Content), data)
d.Push(data)
}
}(i)
go func(i int) {
data := new(common.MuxPackager)
_ = data.NewPac(common.MUX_NEW_CONN, int32(i), nil)
//fmt.Println(string((*data).buf), data)
logs.Warn(data)
d.Push(data)
}(i)
go func(i int) {
data := new(common.MuxPackager)
_ = data.NewPac(common.MUX_NEW_CONN_OK, int32(i), nil)
//fmt.Println(string((*data).buf), data)
logs.Warn(data)
d.Push(data)
}(i)
}
}()
time.Sleep(time.Second * 100000)
}
//func TestReceive(t *testing.T) {
// go func() {
// log.Println(http.ListenAndServe("0.0.0.0:8889", nil))
// }()
// logs.EnableFuncCallDepth(true)
// logs.SetLogFuncCallDepth(3)
// time.Sleep(time.Second * 5)
// mux := new(Mux)
// mux.bw.readBandwidth = float64(1*1024*1024)
// mux.latency = float64(1/1000)
// wind := new(ReceiveWindow)
// wind.New(mux)
// wind.
// go func() {
// time.Sleep(time.Second)
// for i := 0; i < 36000; i++ {
// data := d.Pop()
// //fmt.Println(i, string(data.buf), err)
// logs.Warn(i, string(data.Content), data)
// }
// }()
// go func() {
// time.Sleep(time.Second*10)
// for i := 0; i < 3000; i++ {
// go func(i int) {
// for n := 0; n < 10; n++{
// data := new(common.MuxPackager)
// by := []byte("test " + strconv.Itoa(i) + strconv.Itoa(n))
// _ = data.NewPac(common.MUX_NEW_MSG_PART, int32(i), by)
// //fmt.Println(string((*data).buf), data)
// logs.Warn(string((*data).Content), data)
// d.Push(data)
// }
// }(i)
// go func(i int) {
// data := new(common.MuxPackager)
// _ = data.NewPac(common.MUX_NEW_CONN, int32(i), nil)
// //fmt.Println(string((*data).buf), data)
// logs.Warn(data)
// d.Push(data)
// }(i)
// go func(i int) {
// data := new(common.MuxPackager)
// _ = data.NewPac(common.MUX_NEW_CONN_OK, int32(i), nil)
// //fmt.Println(string((*data).buf), data)
// logs.Warn(data)
// d.Push(data)
// }(i)
// }
// }()
// time.Sleep(time.Second * 100000)
//}
-154
View File
@@ -1,154 +0,0 @@
package mux
import (
"fmt"
"github.com/astaxie/beego/logs"
"net/http"
"sort"
"strconv"
"strings"
"sync"
"time"
)
type connLog struct {
startTime time.Time
isClose bool
logs []string
}
var logms map[int]*connLog
var logmc map[int]*connLog
var copyMaps map[int]*connLog
var copyMapc map[int]*connLog
var stashTimeNow time.Time
var mutex sync.Mutex
func deepCopyMaps() {
copyMaps = make(map[int]*connLog)
for k, v := range logms {
copyMaps[k] = &connLog{
startTime: v.startTime,
isClose: v.isClose,
logs: v.logs,
}
}
}
func deepCopyMapc() {
copyMapc = make(map[int]*connLog)
for k, v := range logmc {
copyMapc[k] = &connLog{
startTime: v.startTime,
isClose: v.isClose,
logs: v.logs,
}
}
}
func init() {
logms = make(map[int]*connLog)
logmc = make(map[int]*connLog)
}
type IntSlice []int
func (s IntSlice) Len() int { return len(s) }
func (s IntSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s IntSlice) Less(i, j int) bool { return s[i] < s[j] }
func NewLogServer() {
http.HandleFunc("/", index)
http.HandleFunc("/detail", detail)
http.HandleFunc("/stash", stash)
fmt.Println(http.ListenAndServe(":8899", nil))
}
func stash(w http.ResponseWriter, r *http.Request) {
stashTimeNow = time.Now()
deepCopyMaps()
deepCopyMapc()
w.Write([]byte("ok"))
}
func getM(label string, id int) (cL *connLog) {
label = strings.TrimSpace(label)
mutex.Lock()
defer mutex.Unlock()
if label == "nps" {
cL = logms[id]
}
if label == "npc" {
cL = logmc[id]
}
return
}
func setM(label string, id int, cL *connLog) {
label = strings.TrimSpace(label)
mutex.Lock()
defer mutex.Unlock()
if label == "nps" {
logms[id] = cL
}
if label == "npc" {
logmc[id] = cL
}
}
func index(w http.ResponseWriter, r *http.Request) {
var keys []int
for k := range copyMaps {
keys = append(keys, k)
}
sort.Sort(IntSlice(keys))
var s string
s += "<h1>nps</h1>"
for _, v := range keys {
connL := copyMaps[v]
s += "<a href='/detail?id=" + strconv.Itoa(v) + "&label=nps" + "'>" + strconv.Itoa(v) + "</a>----------"
s += strconv.Itoa(int(stashTimeNow.Sub(connL.startTime).Milliseconds())) + "ms----------"
s += strconv.FormatBool(connL.isClose)
s += "<br>"
}
keys = keys[:0]
s += "<h1>npc</h1>"
for k := range copyMapc {
keys = append(keys, k)
}
sort.Sort(IntSlice(keys))
for _, v := range keys {
connL := copyMapc[v]
s += "<a href='/detail?id=" + strconv.Itoa(v) + "&label=npc" + "'>" + strconv.Itoa(v) + "</a>----------"
s += strconv.Itoa(int(stashTimeNow.Sub(connL.startTime).Milliseconds())) + "ms----------"
s += strconv.FormatBool(connL.isClose)
s += "<br>"
}
w.Write([]byte(s))
}
func detail(w http.ResponseWriter, r *http.Request) {
id := r.FormValue("id")
label := r.FormValue("label")
logs.Warn(label)
i, _ := strconv.Atoi(id)
var v *connLog
if label == "nps" {
v, _ = copyMaps[i]
}
if label == "npc" {
v, _ = copyMapc[i]
}
var s string
if v != nil {
for i, vv := range v.logs {
s += "<p>" + strconv.Itoa(i+1) + ":" + vv + "</p>"
}
}
w.Write([]byte(s))
}
-7
View File
@@ -1,7 +0,0 @@
package mux
import "testing"
func TestWeb(t *testing.T) {
NewLogServer()
}
+104 -134
View File
@@ -1,10 +1,9 @@
package mux
package nps_mux
import (
"ehang.io/nps/lib/common"
"errors"
"github.com/astaxie/beego/logs"
"io"
"log"
"math"
"net"
"runtime"
@@ -15,39 +14,27 @@ import (
type conn struct {
net.Conn
getStatusCh chan struct{}
connStatusOkCh chan struct{}
connStatusFailCh chan struct{}
connId int32
isClose bool
closeFlag bool // close conn flag
receiveWindow *ReceiveWindow
sendWindow *SendWindow
closingFlag bool // closing conn flag
receiveWindow *receiveWindow
sendWindow *sendWindow
once sync.Once
//label string
}
func NewConn(connId int32, mux *Mux, label ...string) *conn {
func NewConn(connId int32, mux *Mux) *conn {
c := &conn{
getStatusCh: make(chan struct{}),
connStatusOkCh: make(chan struct{}),
connStatusFailCh: make(chan struct{}),
connId: connId,
receiveWindow: new(ReceiveWindow),
sendWindow: new(SendWindow),
receiveWindow: new(receiveWindow),
sendWindow: new(sendWindow),
once: sync.Once{},
}
//if len(label) > 0 {
// c.label = label[0]
//}
c.receiveWindow.New(mux)
c.sendWindow.New(mux)
//logm := &connLog{
// startTime: time.Now(),
// isClose: false,
// logs: []string{c.label + "new conn success"},
//}
//setM(label[0], int(connId), logm)
return c
}
@@ -59,21 +46,7 @@ func (s *conn) Read(buf []byte) (n int, err error) {
return 0, nil
}
// waiting for takeout from receive window finish or timeout
//now := time.Now()
n, err = s.receiveWindow.Read(buf, s.connId)
//t := time.Now().Sub(now)
//if t.Seconds() > 0.5 {
//logs.Warn("conn read long", n, t.Seconds())
//}
//var errstr string
//if err == nil {
// errstr = "err:nil"
//} else {
// errstr = err.Error()
//}
//d := getM(s.label, int(s.connId))
//d.logs = append(d.logs, s.label+"read "+strconv.Itoa(n)+" "+errstr+" "+string(buf[:100]))
//setM(s.label, int(s.connId), d)
return
}
@@ -81,20 +54,13 @@ func (s *conn) Write(buf []byte) (n int, err error) {
if s.isClose {
return 0, errors.New("the conn has closed")
}
if s.closeFlag {
//s.Close()
if s.closingFlag {
return 0, errors.New("io: write on closed conn")
}
if len(buf) == 0 {
return 0, nil
}
//logs.Warn("write buf", len(buf))
//now := time.Now()
n, err = s.sendWindow.WriteFull(buf, s.connId)
//t := time.Now().Sub(now)
//if t.Seconds() > 0.5 {
// logs.Warn("conn write long", n, t.Seconds())
//}
return
}
@@ -107,16 +73,12 @@ func (s *conn) closeProcess() {
s.isClose = true
s.receiveWindow.mux.connMap.Delete(s.connId)
if !s.receiveWindow.mux.IsClose {
// if server or user close the conn while reading, will get a io.EOF
// if server or user close the conn while reading, will Get a io.EOF
// and this Close method will be invoke, send this signal to close other side
s.receiveWindow.mux.sendInfo(common.MUX_CONN_CLOSE, s.connId, nil)
s.receiveWindow.mux.sendInfo(muxConnClose, s.connId, nil)
}
s.sendWindow.CloseWindow()
s.receiveWindow.CloseWindow()
//d := getM(s.label, int(s.connId))
//d.isClose = true
//d.logs = append(d.logs, s.label+"close "+time.Now().String())
//setM(s.label, int(s.connId), d)
return
}
@@ -165,7 +127,6 @@ const mask31 = 1<<windowBits - 1
func (Self *window) unpack(ptrs uint64) (maxSize, done uint32, wait bool) {
maxSize = uint32((ptrs >> dequeueBits) & mask31)
done = uint32(ptrs & mask31)
//logs.Warn("unpack", maxSize, done)
if ((ptrs >> waitBits) & mask1) == 1 {
wait = true
return
@@ -174,7 +135,6 @@ func (Self *window) unpack(ptrs uint64) (maxSize, done uint32, wait bool) {
}
func (Self *window) pack(maxSize, done uint32, wait bool) uint64 {
//logs.Warn("pack", maxSize, done, wait)
if wait {
return (uint64(1)<<waitBits |
uint64(maxSize&mask31)<<dequeueBits) |
@@ -197,10 +157,10 @@ func (Self *window) CloseWindow() {
}
}
type ReceiveWindow struct {
type receiveWindow struct {
window
bufQueue *ReceiveWindowQueue
element *common.ListElement
bufQueue *receiveWindowQueue
element *listElement
count int8
bw *writeBandwidth
once sync.Once
@@ -208,17 +168,17 @@ type ReceiveWindow struct {
// means done size actually store the size receive window has read
}
func (Self *ReceiveWindow) New(mux *Mux) {
func (Self *receiveWindow) New(mux *Mux) {
// initial a window for receive
Self.bufQueue = NewReceiveWindowQueue()
Self.element = common.ListElementPool.Get()
Self.maxSizeDone = Self.pack(common.MAXIMUM_SEGMENT_SIZE*30, 0, false)
Self.bufQueue = newReceiveWindowQueue()
Self.element = listEle.Get()
Self.maxSizeDone = Self.pack(maximumSegmentSize*30, 0, false)
Self.mux = mux
Self.window.New()
Self.bw = NewWriteBandwidth()
Self.bw = newWriteBandwidth()
}
func (Self *ReceiveWindow) remainingSize(maxSize uint32, delta uint16) (n uint32) {
func (Self *receiveWindow) remainingSize(maxSize uint32, delta uint16) (n uint32) {
// receive window remaining
l := int64(maxSize) - int64(Self.bufQueue.Len())
l -= int64(delta)
@@ -228,45 +188,64 @@ func (Self *ReceiveWindow) remainingSize(maxSize uint32, delta uint16) (n uint32
return
}
func (Self *ReceiveWindow) calcSize() {
func (Self *receiveWindow) calcSize() {
// calculating maximum receive window size
if Self.count == 0 {
//logs.Warn("ping, bw", Self.mux.latency, Self.bw.Get())
//conns := Self.mux.connMap.Size()
muxBw := Self.mux.bw.Get()
connBw := Self.bw.Get()
//logs.Warn("muxbw connbw", muxBw, connBw)
latency := math.Float64frombits(atomic.LoadUint64(&Self.mux.latency))
var n uint32
if connBw > 0 && muxBw > 0 {
n = uint32(math.Float64frombits(atomic.LoadUint64(&Self.mux.latency)) *
(muxBw + connBw))
if connBw > muxBw {
connBw = muxBw
Self.bw.GrowRatio()
}
n = uint32(latency * (muxBw + connBw))
}
//logs.Warn(n)
if n < common.MAXIMUM_SEGMENT_SIZE*30 {
//logs.Warn("window small", n, Self.mux.bw.Get(), Self.bw.Get())
n = common.MAXIMUM_SEGMENT_SIZE * 30
if n < maximumSegmentSize*30 {
n = maximumSegmentSize * 30
}
if n < uint32(float64(maximumSegmentSize*3000)*latency) {
// latency gain
// if there are some latency more than 10ms will trigger this gain
// network pipeline need fill more data that we can measure the max bandwidth
n = uint32(float64(maximumSegmentSize*3000) * latency)
}
for {
ptrs := atomic.LoadUint64(&Self.maxSizeDone)
size, read, wait := Self.unpack(ptrs)
rem := Self.remainingSize(size, 0)
ra := float64(rem) / float64(size)
if ra > 0.8 {
// low fill window gain
// if receive window keep low fill, maybe pipeline fill the data, we need a gain
// less than 20% fill, gain will trigger
n = uint32(float64(n) * 1.5625 * ra * ra)
}
if n < size/2 {
n = size / 2
// half reduce
}
// set the minimal size
if n > 2*size {
n = 2 * size
// twice grow
if size == maximumSegmentSize*30 {
// we give more ratio when the initial window size, to reduce the time window grow up
if n > size*6 {
n = size * 6
}
} else {
n = 2 * size
// twice grow
}
}
if connBw > 0 && muxBw > 0 {
limit := uint32(common.MAXIMUM_WINDOW_SIZE * (connBw / (muxBw + connBw)))
limit := uint32(maximumWindowSize * (connBw / (muxBw + connBw)))
if n > limit {
logs.Warn("window too large, calculated:", n, "limit:", limit, connBw, muxBw)
log.Println("window too large, calculated:", n, "limit:", limit, connBw, muxBw)
n = limit
}
}
// set the maximum size
//logs.Warn("n", n)
if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(n, read, wait)) {
// only change the maxSize
break
@@ -278,12 +257,11 @@ func (Self *ReceiveWindow) calcSize() {
return
}
func (Self *ReceiveWindow) Write(buf []byte, l uint16, part bool, id int32) (err error) {
func (Self *receiveWindow) Write(buf []byte, l uint16, part bool, id int32) (err error) {
if Self.closeOp {
return errors.New("conn.receiveWindow: write on closed window")
}
element, err := NewListElement(buf, l, part)
//logs.Warn("push the buf", len(buf), l, element.L)
element, err := newListElement(buf, l, part)
if err != nil {
return
}
@@ -296,14 +274,12 @@ start:
remain := Self.remainingSize(maxSize, l)
// calculate the remaining window size now, plus the element we will push
if remain == 0 && !wait {
//logs.Warn("window full true", remaining)
wait = true
if !atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, read, wait)) {
// only change the wait status, not send the read size
goto start
// another goroutine change the status, make sure shall we need wait
}
//logs.Warn("receive window full")
} else if !wait {
if !atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, 0, wait)) {
// reset read size here, and send the read size directly
@@ -315,13 +291,13 @@ start:
Self.bufQueue.Push(element)
// status check finish, now we can push the element into the queue
if !wait {
Self.mux.sendInfo(common.MUX_MSG_SEND_OK, id, Self.pack(maxSize, read, false))
Self.mux.sendInfo(muxMsgSendOk, id, Self.pack(maxSize, read, false))
// send the current status to send window
}
return nil
}
func (Self *ReceiveWindow) Read(p []byte, id int32) (n int, err error) {
func (Self *receiveWindow) Read(p []byte, id int32) (n int, err error) {
if Self.closeOp {
return 0, io.EOF // receive close signal, returns eof
}
@@ -331,15 +307,14 @@ func (Self *ReceiveWindow) Read(p []byte, id int32) (n int, err error) {
return
}
func (Self *ReceiveWindow) readFromQueue(p []byte, id int32) (n int, err error) {
func (Self *receiveWindow) readFromQueue(p []byte, id int32) (n int, err error) {
pOff := 0
l := 0
//logs.Warn("receive window read off, element.l", Self.off, Self.element.L)
copyData:
if Self.off == uint32(Self.element.L) {
// on the first Read method invoked, Self.off and Self.element.l
// both zero value
common.ListElementPool.Put(Self.element)
listEle.Put(Self.element)
if Self.closeOp {
return 0, io.EOF
}
@@ -352,17 +327,14 @@ copyData:
Self.CloseWindow() // also close the window, to avoid read twice
return // queue receive stop or time out, break the loop and return
}
//logs.Warn("pop element", Self.element.L, Self.element.Part)
}
l = copy(p[pOff:], Self.element.Buf[Self.off:Self.element.L])
pOff += l
Self.off += uint32(l)
//logs.Warn("window read length buf len", Self.readLength, Self.bufQueue.Len())
n += l
l = 0
if Self.off == uint32(Self.element.L) {
//logs.Warn("put the element end ", string(Self.element.buf[:15]))
common.WindowBuff.Put(Self.element.Buf)
windowBuff.Put(Self.element.Buf)
Self.sendStatus(id, Self.element.L)
// check the window full status
}
@@ -373,7 +345,7 @@ copyData:
return // buf p is full or all of segments in buf, return
}
func (Self *ReceiveWindow) sendStatus(id int32, l uint16) {
func (Self *receiveWindow) sendStatus(id int32, l uint16) {
var maxSize, read uint32
var wait bool
for {
@@ -388,8 +360,7 @@ func (Self *ReceiveWindow) sendStatus(id int32, l uint16) {
// receive window free up some space we need acknowledge send window, also reset the read size
// still having a condition that receive window is empty and not send the status to send window
// so send the status here
//logs.Warn("receive window free up some space", remain)
Self.mux.sendInfo(common.MUX_MSG_SEND_OK, id, Self.pack(maxSize, read, false))
Self.mux.sendInfo(muxMsgSendOk, id, Self.pack(maxSize, read, false))
break
}
} else {
@@ -403,7 +374,7 @@ func (Self *ReceiveWindow) sendStatus(id int32, l uint16) {
//overflow
if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, uint32(l), wait)) {
// reset to l
Self.mux.sendInfo(common.MUX_MSG_SEND_OK, id, Self.pack(maxSize, read, false))
Self.mux.sendInfo(muxMsgSendOk, id, Self.pack(maxSize, read, false))
break
}
}
@@ -413,23 +384,23 @@ func (Self *ReceiveWindow) sendStatus(id int32, l uint16) {
return
}
func (Self *ReceiveWindow) SetTimeOut(t time.Time) {
func (Self *receiveWindow) SetTimeOut(t time.Time) {
// waiting for FIFO queue Pop method
Self.bufQueue.SetTimeOut(t)
}
func (Self *ReceiveWindow) Stop() {
func (Self *receiveWindow) Stop() {
// queue has no more data to push, so unblock pop method
Self.once.Do(Self.bufQueue.Stop)
}
func (Self *ReceiveWindow) CloseWindow() {
func (Self *receiveWindow) CloseWindow() {
Self.window.CloseWindow()
Self.Stop()
Self.release()
}
func (Self *ReceiveWindow) release() {
func (Self *receiveWindow) release() {
//if Self.element != nil {
// if Self.element.Buf != nil {
// common.WindowBuff.Put(Self.element.Buf)
@@ -442,13 +413,13 @@ func (Self *ReceiveWindow) release() {
return
}
if ele.Buf != nil {
common.WindowBuff.Put(ele.Buf)
windowBuff.Put(ele.Buf)
}
common.ListElementPool.Put(ele)
listEle.Put(ele)
} // release resource
}
type SendWindow struct {
type sendWindow struct {
window
buf []byte
setSizeCh chan struct{}
@@ -458,20 +429,20 @@ type SendWindow struct {
// so send minus read, send window can get the current window size remaining
}
func (Self *SendWindow) New(mux *Mux) {
func (Self *sendWindow) New(mux *Mux) {
Self.setSizeCh = make(chan struct{})
Self.maxSizeDone = Self.pack(common.MAXIMUM_SEGMENT_SIZE*30, 0, false)
Self.maxSizeDone = Self.pack(maximumSegmentSize*30, 0, false)
Self.mux = mux
Self.window.New()
}
func (Self *SendWindow) SetSendBuf(buf []byte) {
func (Self *sendWindow) SetSendBuf(buf []byte) {
// send window buff from conn write method, set it to send window
Self.buf = buf
Self.off = 0
}
func (Self *SendWindow) remainingSize(maxSize, send uint32) uint32 {
func (Self *sendWindow) remainingSize(maxSize, send uint32) uint32 {
l := int64(maxSize&mask31) - int64(send&mask31)
if l > 0 {
return uint32(l)
@@ -479,7 +450,7 @@ func (Self *SendWindow) remainingSize(maxSize, send uint32) uint32 {
return 0
}
func (Self *SendWindow) SetSize(currentMaxSizeDone uint64) (closed bool) {
func (Self *sendWindow) SetSize(currentMaxSizeDone uint64) (closed bool) {
// set the window size from receive window
defer func() {
if recover() != nil {
@@ -490,7 +461,6 @@ func (Self *SendWindow) SetSize(currentMaxSizeDone uint64) (closed bool) {
close(Self.setSizeCh)
return true
}
//logs.Warn("set send window size to ", windowSize, newRemaining)
var maxsize, send uint32
var wait, newWait bool
currentMaxSize, read, _ := Self.unpack(currentMaxSizeDone)
@@ -498,7 +468,7 @@ func (Self *SendWindow) SetSize(currentMaxSizeDone uint64) (closed bool) {
ptrs := atomic.LoadUint64(&Self.maxSizeDone)
maxsize, send, wait = Self.unpack(ptrs)
if read > send {
logs.Error("window read > send: max size:", currentMaxSize, "read:", read, "send", send)
log.Println("window read > send: max size:", currentMaxSize, "read:", read, "send", send)
return
}
if read == 0 && currentMaxSize == maxsize {
@@ -512,23 +482,22 @@ func (Self *SendWindow) SetSize(currentMaxSizeDone uint64) (closed bool) {
}
// remain > 0, change wait to false. or remain == 0, wait is false, just keep it
if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(currentMaxSize, send, newWait)) {
//log.Printf("currentMaxSize:%d read:%d send:%d", currentMaxSize, read, send)
break
}
// anther goroutine change wait status or window size
}
if wait && !newWait {
// send window into the wait status, need notice the channel
//logs.Warn("send window allow")
Self.allow()
}
// send window not into the wait status, so just do slide
return false
}
func (Self *SendWindow) allow() {
func (Self *sendWindow) allow() {
select {
case Self.setSizeCh <- struct{}{}:
//logs.Warn("send window remaining size is 0 finish")
return
case <-Self.closeOpCh:
close(Self.setSizeCh)
@@ -536,7 +505,7 @@ func (Self *SendWindow) allow() {
}
}
func (Self *SendWindow) sent(sentSize uint32) {
func (Self *sendWindow) sent(sentSize uint32) {
var maxSie, send uint32
var wait bool
for {
@@ -549,19 +518,18 @@ func (Self *SendWindow) sent(sentSize uint32) {
}
if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSie, send+sentSize, wait)) {
// set the send size
//logs.Warn("sent", maxSie, send+sentSize, wait)
break
}
}
}
func (Self *SendWindow) WriteTo() (p []byte, sendSize uint32, part bool, err error) {
func (Self *sendWindow) WriteTo() (p []byte, sendSize uint32, part bool, err error) {
// returns buf segments, return only one segments, need a loop outside
// until err = io.EOF
if Self.closeOp {
return nil, 0, false, errors.New("conn.writeWindow: window closed")
}
if Self.off == uint32(len(Self.buf)) {
if Self.off >= uint32(len(Self.buf)) {
return nil, 0, false, io.EOF
// send window buff is drain, return eof and get another one
}
@@ -576,19 +544,21 @@ start:
goto start // another goroutine change the window, try again
}
// into the wait status
//logs.Warn("send window into wait status")
err = Self.waitReceiveWindow()
if err != nil {
return nil, 0, false, err
}
//logs.Warn("rem into wait finish")
goto start
}
if Self.off > uint32(len(Self.buf)) {
return nil, 0, false, io.EOF
}
//logs.Info("Self size:", len(Self.buf), "Self.off " ,Self.off)
// there are still remaining window
//logs.Warn("rem", remain, maxSize, send)
if len(Self.buf[Self.off:]) > common.MAXIMUM_SEGMENT_SIZE {
sendSize = common.MAXIMUM_SEGMENT_SIZE
//logs.Warn("cut buf by mss")
if len(Self.buf[Self.off:]) > maximumSegmentSize {
sendSize = maximumSegmentSize
} else {
sendSize = uint32(len(Self.buf[Self.off:]))
}
@@ -596,19 +566,18 @@ start:
// usable window size is small than
// window MAXIMUM_SEGMENT_SIZE or send buf left
sendSize = remain
//logs.Warn("cut buf by remainingsize", sendSize, len(Self.buf[Self.off:]))
}
//logs.Warn("send size", sendSize)
if sendSize < uint32(len(Self.buf[Self.off:])) {
part = true
}
p = Self.buf[Self.off : sendSize+Self.off]
Self.off += sendSize
Self.sent(sendSize)
//logs.Info("sendSize", sendSize, "Self.off " ,Self.off)
return
}
func (Self *SendWindow) waitReceiveWindow() (err error) {
func (Self *sendWindow) waitReceiveWindow() (err error) {
t := Self.timeout.Sub(time.Now())
if t < 0 { // not set the timeout, wait for it as long as connection close
select {
@@ -637,15 +606,13 @@ func (Self *SendWindow) waitReceiveWindow() (err error) {
}
}
func (Self *SendWindow) WriteFull(buf []byte, id int32) (n int, err error) {
func (Self *sendWindow) WriteFull(buf []byte, id int32) (n int, err error) {
Self.SetSendBuf(buf) // set the buf to send window
//logs.Warn("set the buf to send window")
var bufSeg []byte
var part bool
var l uint32
for {
bufSeg, l, part, err = Self.WriteTo()
//logs.Warn("buf seg", len(bufSeg), part, err)
// get the buf segments from send window
if bufSeg == nil && part == false && err == io.EOF {
// send window is drain, break the loop
@@ -658,18 +625,16 @@ func (Self *SendWindow) WriteFull(buf []byte, id int32) (n int, err error) {
n += int(l)
l = 0
if part {
Self.mux.sendInfo(common.MUX_NEW_MSG_PART, id, bufSeg)
Self.mux.sendInfo(muxNewMsgPart, id, bufSeg)
} else {
Self.mux.sendInfo(common.MUX_NEW_MSG, id, bufSeg)
//logs.Warn("buf seg sent", len(bufSeg), part, err)
Self.mux.sendInfo(muxNewMsg, id, bufSeg)
}
// send to other side, not send nil data to other side
}
//logs.Warn("buf seg write success")
return
}
func (Self *SendWindow) SetTimeOut(t time.Time) {
func (Self *sendWindow) SetTimeOut(t time.Time) {
// waiting for receive a receive window size
Self.timeout = t
}
@@ -679,12 +644,13 @@ type writeBandwidth struct {
readEnd time.Time
duration float64
bufLength uint32
ratio uint32
}
const writeCalcThreshold uint32 = 5 * 1024 * 1024
func NewWriteBandwidth() *writeBandwidth {
return &writeBandwidth{}
func newWriteBandwidth() *writeBandwidth {
return &writeBandwidth{ratio: 1}
}
func (Self *writeBandwidth) StartRead() {
@@ -692,7 +658,7 @@ func (Self *writeBandwidth) StartRead() {
Self.readEnd = time.Now()
}
Self.duration += time.Now().Sub(Self.readEnd).Seconds()
if Self.bufLength >= writeCalcThreshold {
if Self.bufLength >= writeCalcThreshold*atomic.LoadUint32(&Self.ratio) {
Self.calcBandWidth()
}
}
@@ -720,3 +686,7 @@ func (Self *writeBandwidth) Get() (bw float64) {
}
return
}
func (Self *writeBandwidth) GrowRatio() {
atomic.AddUint32(&Self.ratio, 1)
}
+53
View File
@@ -0,0 +1,53 @@
package nps_mux
import (
"sync"
)
type connMap struct {
cMap map[int32]*conn
//closeCh chan struct{}
sync.RWMutex
}
func NewConnMap() *connMap {
cMap := &connMap{
cMap: make(map[int32]*conn),
}
return cMap
}
func (s *connMap) Size() (n int) {
s.RLock()
n = len(s.cMap)
s.RUnlock()
return
}
func (s *connMap) Get(id int32) (*conn, bool) {
s.RLock()
v, ok := s.cMap[id]
s.RUnlock()
if ok && v != nil {
return v, true
}
return nil, false
}
func (s *connMap) Set(id int32, v *conn) {
s.Lock()
s.cMap[id] = v
s.Unlock()
}
func (s *connMap) Close() {
for _, v := range s.cMap {
_ = v.Close() // close all the connections in the mux
}
}
func (s *connMap) Delete(id int32) {
s.Lock()
delete(s.cMap, id)
s.Unlock()
}
+167 -188
View File
@@ -1,56 +1,80 @@
package mux
package nps_mux
import (
"errors"
"io"
"log"
"math"
"net"
"os"
"sync/atomic"
"time"
)
"ehang.io/nps/lib/common"
"github.com/astaxie/beego/logs"
const (
muxPingFlag uint8 = iota
muxNewConnOk
muxNewConnFail
muxNewMsg
muxNewMsgPart
muxMsgSendOk
muxNewConn
muxConnClose
muxPingReturn
muxPing int32 = -1
maximumSegmentSize = poolSizeWindow
maximumWindowSize = 1 << 27 // 1<<31-1 TCP slide window size is very large,
// we use 128M, reduce memory usage
)
type Mux struct {
latency uint64 // we store latency in bits, but it's float64
net.Listener
conn net.Conn
connMap *connMap
newConnCh chan *conn
id int32
closeChan chan struct{}
IsClose bool
pingOk uint32
counter *latencyCounter
bw *bandwidth
pingCh chan []byte
pingCheckTime uint32
connType string
writeQueue PriorityQueue
newConnQueue ConnQueue
conn net.Conn
connMap *connMap
newConnCh chan *conn
id int32
closeChan chan struct{}
IsClose bool
counter *latencyCounter
bw *bandwidth
pingCh chan []byte
pingCheckTime uint32 // we check the ping per 5s
pingCheckThreshold uint32
connType string
writeQueue priorityQueue
newConnQueue connQueue
}
func NewMux(c net.Conn, connType string) *Mux {
func NewMux(c net.Conn, connType string, pingCheckThreshold int) *Mux {
//c.(*net.TCPConn).SetReadBuffer(0)
//c.(*net.TCPConn).SetWriteBuffer(0)
_ = c.SetDeadline(time.Time{})
fd, err := getConnFd(c)
if err != nil {
logs.Warn(err)
log.Println(err)
}
var checkThreshold uint32
if pingCheckThreshold <= 0 {
if connType == "kcp" {
checkThreshold = 20
} else {
checkThreshold = 60
}
} else {
checkThreshold = uint32(pingCheckThreshold)
}
m := &Mux{
conn: c,
connMap: NewConnMap(),
id: 0,
closeChan: make(chan struct{}, 1),
newConnCh: make(chan *conn),
bw: NewBandwidth(fd),
IsClose: false,
connType: connType,
pingCh: make(chan []byte),
counter: newLatencyCounter(),
conn: c,
connMap: NewConnMap(),
id: 0,
closeChan: make(chan struct{}, 1),
newConnCh: make(chan *conn),
bw: NewBandwidth(fd),
IsClose: false,
connType: connType,
pingCh: make(chan []byte),
pingCheckThreshold: checkThreshold,
counter: newLatencyCounter(),
}
m.writeQueue.New()
m.newConnQueue.New()
@@ -58,7 +82,6 @@ func NewMux(c net.Conn, connType string) *Mux {
m.readSession()
//ping
m.ping()
m.pingReturn()
m.writeSession()
return m
}
@@ -67,17 +90,16 @@ func (s *Mux) NewConn() (*conn, error) {
if s.IsClose {
return nil, errors.New("the mux has closed")
}
conn := NewConn(s.getId(), s, "nps ")
//it must be set before send
conn := NewConn(s.getId(), s)
//it must be Set before send
s.connMap.Set(conn.connId, conn)
s.sendInfo(common.MUX_NEW_CONN, conn.connId, nil)
//set a timer timeout 30 second
s.sendInfo(muxNewConn, conn.connId, nil)
//Set a timer timeout 120 second
timer := time.NewTimer(time.Minute * 2)
defer timer.Stop()
select {
case <-conn.connStatusOkCh:
return conn, nil
case <-conn.connStatusFailCh:
case <-timer.C:
}
return nil, errors.New("create connection fail,the server refused the connection")
@@ -98,17 +120,17 @@ func (s *Mux) Addr() net.Addr {
return s.conn.LocalAddr()
}
func (s *Mux) sendInfo(flag uint8, id int32, data ...interface{}) {
func (s *Mux) sendInfo(flag uint8, id int32, data interface{}) {
if s.IsClose {
return
}
var err error
pack := common.MuxPack.Get()
err = pack.NewPac(flag, id, data...)
pack := muxPack.Get()
err = pack.Set(flag, id, data)
if err != nil {
common.MuxPack.Put(pack)
logs.Error("mux: new pack err", err)
s.Close()
muxPack.Put(pack)
log.Println("mux: New Pack err", err)
_ = s.Close()
return
}
s.writeQueue.Push(pack)
@@ -116,68 +138,38 @@ func (s *Mux) sendInfo(flag uint8, id int32, data ...interface{}) {
}
func (s *Mux) writeSession() {
go s.packBuf()
//go s.writeBuf()
go func() {
for {
if s.IsClose {
break
}
pack := s.writeQueue.Pop()
if s.IsClose {
break
}
//if pack.flag == muxNewMsg || pack.flag == muxNewMsgPart {
// if pack.length >= 100 {
// log.Println("write session id", pack.id, "\n", string(pack.content[:100]))
// } else {
// log.Println("write session id", pack.id, "\n", string(pack.content[:pack.length]))
// }
//}
err := pack.Pack(s.conn)
muxPack.Put(pack)
if err != nil {
log.Println("mux: Pack err", err)
_ = s.Close()
break
}
}
}()
}
func (s *Mux) packBuf() {
//buffer := common.BuffPool.Get()
for {
if s.IsClose {
break
}
//buffer.Reset()
pack := s.writeQueue.Pop()
if s.IsClose {
break
}
//buffer := common.BuffPool.Get()
err := pack.Pack(s.conn)
common.MuxPack.Put(pack)
if err != nil {
logs.Error("mux: pack err", err)
//common.BuffPool.Put(buffer)
s.Close()
break
}
//logs.Warn(buffer.String())
//s.bufQueue.Push(buffer)
//l := buffer.Len()
//n, err := buffer.WriteTo(s.conn)
//common.BuffPool.Put(buffer)
//if err != nil || int(n) != l {
// logs.Error("mux: close from write session fail ", err, n, l)
// s.Close()
// break
//}
}
}
//func (s *Mux) writeBuf() {
// for {
// if s.IsClose {
// break
// }
// buffer, err := s.bufQueue.Pop()
// if err != nil {
// break
// }
// l := buffer.Len()
// n, err := buffer.WriteTo(s.conn)
// common.BuffPool.Put(buffer)
// if err != nil || int(n) != l {
// logs.Warn("close from write session fail ", err, n, l)
// s.Close()
// break
// }
// }
//}
func (s *Mux) ping() {
go func() {
now, _ := time.Now().UTC().MarshalText()
s.sendInfo(common.MUX_PING_FLAG, common.MUX_PING, now)
// send the ping flag and get the latency first
s.sendInfo(muxPingFlag, muxPing, now)
// send the ping flag and Get the latency first
ticker := time.NewTicker(time.Second * 5)
defer ticker.Stop()
for {
@@ -187,28 +179,20 @@ func (s *Mux) ping() {
select {
case <-ticker.C:
}
if atomic.LoadUint32(&s.pingCheckTime) >= 60 {
logs.Error("mux: ping time out")
s.Close()
// more than 5 minutes not receive the ping return package,
if atomic.LoadUint32(&s.pingCheckTime) > s.pingCheckThreshold {
log.Println("mux: ping time out, checktime", s.pingCheckTime, "threshold", s.pingCheckThreshold)
_ = s.Close()
// more than limit times not receive the ping return package,
// mux conn is damaged, maybe a packet drop, close it
break
}
now, _ := time.Now().UTC().MarshalText()
s.sendInfo(common.MUX_PING_FLAG, common.MUX_PING, now)
now, _ = time.Now().UTC().MarshalText()
s.sendInfo(muxPingFlag, muxPing, now)
atomic.AddUint32(&s.pingCheckTime, 1)
if atomic.LoadUint32(&s.pingOk) > 10 && s.connType == "kcp" {
logs.Error("mux: kcp ping err")
s.Close()
break
}
atomic.AddUint32(&s.pingOk, 1)
}
return
}()
}
func (s *Mux) pingReturn() {
go func() {
var now time.Time
var data []byte
@@ -220,17 +204,17 @@ func (s *Mux) pingReturn() {
case data = <-s.pingCh:
atomic.StoreUint32(&s.pingCheckTime, 0)
case <-s.closeChan:
return
break
}
_ = now.UnmarshalText(data)
latency := time.Now().UTC().Sub(now).Seconds() / 2
latency := time.Now().UTC().Sub(now).Seconds()
if latency > 0 {
atomic.StoreUint64(&s.latency, math.Float64bits(s.counter.Latency(latency)))
// convert float64 to bits, store it atomic
//log.Println("ping", math.Float64frombits(atomic.LoadUint64(&s.latency)))
}
//logs.Warn("latency", math.Float64frombits(atomic.LoadUint64(&s.latency)))
if cap(data) > 0 {
common.WindowBuff.Put(data)
if cap(data) > 0 && !s.IsClose {
windowBuff.Put(data)
}
}
}()
@@ -247,112 +231,110 @@ func (s *Mux) readSession() {
if s.IsClose {
break // make sure that is closed
}
s.connMap.Set(connection.connId, connection) //it has been set before send ok
s.connMap.Set(connection.connId, connection) //it has been Set before send ok
s.newConnCh <- connection
s.sendInfo(common.MUX_NEW_CONN_OK, connection.connId, nil)
s.sendInfo(muxNewConnOk, connection.connId, nil)
}
}()
go func() {
pack := common.MuxPack.Get()
var pack *muxPackager
var l uint16
var err error
for {
if s.IsClose {
break
return
}
pack = common.MuxPack.Get()
pack = muxPack.Get()
s.bw.StartRead()
if l, err = pack.UnPack(s.conn); err != nil {
logs.Error("mux: read session unpack from connection err", err)
s.Close()
log.Println("mux: read session unpack from connection err", err)
_ = s.Close()
break
}
s.bw.SetCopySize(l)
atomic.StoreUint32(&s.pingOk, 0)
switch pack.Flag {
case common.MUX_NEW_CONN: //new connection
connection := NewConn(pack.Id, s)
//if pack.flag == muxNewMsg || pack.flag == muxNewMsgPart {
// if pack.length >= 100 {
// log.Printf("read session id %d pointer %p\n%v", pack.id, pack.content, string(pack.content[:100]))
// } else {
// log.Printf("read session id %d pointer %p\n%v", pack.id, pack.content, string(pack.content[:pack.length]))
// }
//}
switch pack.flag {
case muxNewConn: //New connection
connection := NewConn(pack.id, s)
s.newConnQueue.Push(connection)
continue
case common.MUX_PING_FLAG: //ping
s.sendInfo(common.MUX_PING_RETURN, common.MUX_PING, pack.Content)
common.WindowBuff.Put(pack.Content)
case muxPingFlag: //ping
s.sendInfo(muxPingReturn, muxPing, pack.content)
windowBuff.Put(pack.content)
continue
case common.MUX_PING_RETURN:
//go func(content []byte) {
s.pingCh <- pack.Content
//}(pack.Content)
case muxPingReturn:
s.pingCh <- pack.content
continue
}
if connection, ok := s.connMap.Get(pack.Id); ok && !connection.isClose {
switch pack.Flag {
case common.MUX_NEW_MSG, common.MUX_NEW_MSG_PART: //new msg from remote connection
if connection, ok := s.connMap.Get(pack.id); ok && !connection.isClose {
switch pack.flag {
case muxNewMsg, muxNewMsgPart: //New msg from remote connection
err = s.newMsg(connection, pack)
if err != nil {
logs.Error("mux: read session connection new msg err", err)
connection.Close()
log.Println("mux: read session connection New msg err", err)
_ = connection.Close()
}
continue
case common.MUX_NEW_CONN_OK: //connection ok
case muxNewConnOk: //connection ok
connection.connStatusOkCh <- struct{}{}
continue
case common.MUX_NEW_CONN_Fail:
case muxNewConnFail:
connection.connStatusFailCh <- struct{}{}
continue
case common.MUX_MSG_SEND_OK:
case muxMsgSendOk:
if connection.isClose {
continue
}
connection.sendWindow.SetSize(pack.Window)
connection.sendWindow.SetSize(pack.window)
continue
case common.MUX_CONN_CLOSE: //close the connection
connection.closeFlag = true
//s.connMap.Delete(pack.Id)
//go func(connection *conn) {
case muxConnClose: //close the connection
connection.closingFlag = true
connection.receiveWindow.Stop() // close signal to receive window
//}(connection)
continue
}
} else if pack.Flag == common.MUX_CONN_CLOSE {
} else if pack.flag == muxConnClose {
continue
}
common.MuxPack.Put(pack)
muxPack.Put(pack)
}
common.MuxPack.Put(pack)
s.Close()
}()
}
func (s *Mux) newMsg(connection *conn, pack *common.MuxPackager) (err error) {
func (s *Mux) newMsg(connection *conn, pack *muxPackager) (err error) {
if connection.isClose {
err = io.ErrClosedPipe
return
}
//logs.Warn("read session receive new msg", pack.Length)
//go func(connection *conn, pack *common.MuxPackager) { // do not block read session
//insert into queue
if pack.Flag == common.MUX_NEW_MSG_PART {
err = connection.receiveWindow.Write(pack.Content, pack.Length, true, pack.Id)
if pack.flag == muxNewMsgPart {
err = connection.receiveWindow.Write(pack.content, pack.length, true, pack.id)
}
if pack.Flag == common.MUX_NEW_MSG {
err = connection.receiveWindow.Write(pack.Content, pack.Length, false, pack.Id)
if pack.flag == muxNewMsg {
err = connection.receiveWindow.Write(pack.content, pack.length, false, pack.id)
}
//logs.Warn("read session write success", pack.Length)
return
}
func (s *Mux) Close() (err error) {
logs.Warn("close mux")
if s.IsClose {
return errors.New("the mux has closed")
}
s.IsClose = true
log.Println("close mux")
s.connMap.Close()
s.connMap = nil
//s.bufQueue.Stop()
//s.connMap = nil
s.closeChan <- struct{}{}
close(s.newConnCh)
err = s.conn.Close()
// while target host close socket without finish steps, conn.Close method maybe blocked
// and tcp status change to CLOSE WAIT or TIME WAIT, so we close it in other goroutine
_ = s.conn.SetDeadline(time.Now().Add(time.Second * 5))
go s.conn.Close()
s.release()
return
}
@@ -363,10 +345,10 @@ func (s *Mux) release() {
if pack == nil {
break
}
if pack.BasePackager.Content != nil {
common.WindowBuff.Put(pack.BasePackager.Content)
if pack.basePackager.content != nil {
windowBuff.Put(pack.basePackager.content)
}
common.MuxPack.Put(pack)
muxPack.Put(pack)
}
for {
connection := s.newConnQueue.TryPop()
@@ -379,7 +361,7 @@ func (s *Mux) release() {
s.newConnQueue.Stop()
}
//get new connId as unique flag
//Get New connId as unique flag
func (s *Mux) getId() (id int32) {
//Avoid going beyond the scope
if (math.MaxInt32 - s.id) < 10000 {
@@ -422,16 +404,14 @@ func (Self *bandwidth) SetCopySize(n uint16) {
func (Self *bandwidth) calcBandWidth() {
t := Self.readStart.Sub(Self.lastReadStart)
bufferSize, err := sysGetSock(Self.fd)
//logs.Warn(bufferSize)
if err != nil {
logs.Warn(err)
log.Println(err)
Self.bufLength = 0
return
}
if Self.bufLength >= uint32(bufferSize) {
atomic.StoreUint64(&Self.readBandwidth, math.Float64bits(float64(Self.bufLength)/t.Seconds()))
// calculate the whole socket buffer, the time meaning to fill the buffer
//logs.Warn(Self.Get())
} else {
Self.calcThreshold = uint32(bufferSize)
}
@@ -445,7 +425,6 @@ func (Self *bandwidth) Get() (bw float64) {
if bw <= 0 {
bw = 0
}
//logs.Warn(bw)
return
}
@@ -461,22 +440,25 @@ func newLatencyCounter() *latencyCounter {
type latencyCounter struct {
buf []float64 //buf is a fixed length ring buffer,
// if buffer is full, new value will replace the oldest one.
// if buffer is full, New value will replace the oldest one.
headMin uint8 //head indicate the head in ring buffer,
// in meaning, slot in list will be replaced;
// min indicate this slot value is minimal in list.
// we delineate the effective range with three times the minimum latency
// average of effective latency for all current data as a mux latency
}
func (Self *latencyCounter) unpack(idxs uint8) (head, min uint8) {
head = uint8((idxs >> counterBits) & counterMask)
// we set head is 4 bits
min = uint8(idxs & counterMask)
head = (idxs >> counterBits) & counterMask
// we Set head is 4 bits
min = idxs & counterMask
return
}
func (Self *latencyCounter) pack(head, min uint8) uint8 {
return uint8(head<<counterBits) |
uint8(min&counterMask)
return head<<counterBits |
min&counterMask
}
func (Self *latencyCounter) add(value float64) {
@@ -511,25 +493,22 @@ func (Self *latencyCounter) minimal() (min uint8) {
func (Self *latencyCounter) Latency(value float64) (latency float64) {
Self.add(value)
_, min := Self.unpack(Self.headMin)
latency = Self.buf[min] * Self.countSuccess()
latency = Self.countSuccess()
return
}
const lossRatio = 1.6
const lossRatio = 3
func (Self *latencyCounter) countSuccess() (successRate float64) {
var success, loss, i uint8
var i, success uint8
_, min := Self.unpack(Self.headMin)
for i = 0; i < counterMask; i++ {
if Self.buf[i] > lossRatio*Self.buf[min] && Self.buf[i] > 0 {
loss++
}
if Self.buf[i] <= lossRatio*Self.buf[min] && Self.buf[i] > 0 {
success++
successRate += Self.buf[i]
}
}
// counting all the data in the ring buf, except zero
successRate = float64(success) / float64(loss+success)
successRate = successRate / float64(success)
return
}
+703
View File
@@ -0,0 +1,703 @@
package nps_mux
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
"math"
"net"
"net/http"
"net/http/httputil"
_ "net/http/pprof"
"os"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"unsafe"
)
var conn1 net.Conn
var conn2 net.Conn
var clientIp = "172.18.0.5"
var serverIp = "172.18.0.2"
var appIp = "172.18.0.3"
var userIp = "172.18.0.4"
var bridgePort = "9999"
var appPort = "9998"
var serverPort = "9997"
var appResultFileName = "app.txt"
var userResultFileName = "user.txt"
var serverResultFileName = "server.txt"
var clientResultFileName = "client.txt"
var dockerNetWorkName = "test"
var network = "172.18.0.0/16"
var fileSavePath = "/usr/src/myapp/"
var dataSize = 1024 * 1024 * 100
func TestMux(t *testing.T) {
pwd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
wg.Add(3)
_ = createNetwork(dockerNetWorkName, network)
go func() {
defer wg.Done()
_ = runDocker("server", dockerNetWorkName, serverIp, "TestServer", pwd)
}()
time.Sleep(time.Second * 5)
go func() {
defer wg.Done()
_ = runDocker("client", dockerNetWorkName, clientIp, "TestClient", pwd)
}()
go func() {
defer wg.Done()
_ = runDocker("app", dockerNetWorkName, appIp, "TestApp", pwd)
}()
time.Sleep(time.Second * 5)
_ = runDocker("user", dockerNetWorkName, userIp, "TestUser", pwd)
wg.Wait()
_ = deleteNetwork(dockerNetWorkName)
}
func writeResult(values []float64, outfile string) error {
file, err := os.Create(fileSavePath + outfile)
if err != nil {
fmt.Println("writer", err)
return err
}
defer file.Close()
writer := bufio.NewWriter(file)
for _, v := range values {
_, _ = writer.WriteString(fmt.Sprintf("%.2f", v))
_, _ = writer.WriteString("\n")
_ = writer.Flush()
}
return err
}
func appendResult(values []float64, outfile string) error {
file, err := os.OpenFile(fileSavePath+outfile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println("writer", err)
return err
}
defer file.Close()
writer := bufio.NewWriter(file)
for _, v := range values {
_, _ = writer.WriteString(fmt.Sprintf("%.2f", v))
_, _ = writer.WriteString("\n")
_ = writer.Flush()
}
return err
}
func TestServer(t *testing.T) {
tc, err := NewTrafficControl(serverIp)
if err != nil {
t.Fatal(err, tc)
}
// do some tc settings
tc.delay("add", "50ms", "10ms", "10%")
_ = tc.Run()
_ = tc.bandwidth("1Mbit")
// start bridge
bridgeListener, err := net.Listen("tcp", serverIp+":"+bridgePort)
if err != nil {
t.Fatal(err)
}
// wait for client
clientBridgeConn, err := bridgeListener.Accept()
if err != nil {
t.Fatal(err)
}
defer clientBridgeConn.Close()
// new mux
mux := NewMux(clientBridgeConn, "tcp", 60)
// start server port
serverListener, err := net.Listen("tcp", serverIp+":"+serverPort)
if err != nil {
t.Fatal(err)
}
defer serverListener.Close()
for {
// accept user connection
userConn, err := serverListener.Accept()
if err != nil {
t.Fatal(err)
}
go func(userConn net.Conn) {
// create a conn from mux
clientConn, err := mux.NewConn()
if err != nil {
t.Fatal(err)
}
go io.Copy(userConn, clientConn)
go func() {
_ = writeResult([]float64{
mux.bw.Get() / 1024 / 1024,
math.Float64frombits(atomic.LoadUint64(&mux.latency)),
}, serverResultFileName)
ticker := time.NewTicker(time.Second * 1)
for {
select {
case <-ticker.C:
fmt.Println(mux.bw.Get()/1024/1024, math.Float64frombits(atomic.LoadUint64(&mux.latency)))
_ = appendResult([]float64{
mux.bw.Get() / 1024 / 1024,
math.Float64frombits(atomic.LoadUint64(&mux.latency)),
}, serverResultFileName)
}
}
}()
_, _ = io.Copy(clientConn, userConn)
os.Exit(0)
}(userConn)
}
}
func TestClient(t *testing.T) {
tc, err := NewTrafficControl(clientIp)
if err != nil {
t.Fatal(err, tc)
}
// do some tc settings
tc.delay("add", "30ms", "10ms", "5%")
_ = tc.Run()
_ = tc.bandwidth("1Mbit")
serverConn, err := net.Dial("tcp", serverIp+":"+bridgePort)
if err != nil {
t.Fatal(err)
}
// crete mux by serverConn
mux := NewMux(serverConn, "tcp", 60)
// start accept user connection
for {
userConn, err := mux.Accept()
if err != nil {
t.Fatal(err)
}
go func(userConn net.Conn) {
// connect to app
appConn, err := net.Dial("tcp", appIp+":"+appPort)
if err != nil {
t.Fatal()
}
defer appConn.Close()
defer userConn.Close()
go io.Copy(userConn, appConn)
go func() {
_ = writeResult([]float64{
mux.bw.Get() / 1024 / 1024,
math.Float64frombits(atomic.LoadUint64(&mux.latency)),
}, clientResultFileName)
ticker := time.NewTicker(time.Second * 1)
for {
select {
case <-ticker.C:
_ = appendResult([]float64{
mux.bw.Get() / 1024 / 1024,
math.Float64frombits(atomic.LoadUint64(&mux.latency)),
}, clientResultFileName)
}
}
}()
_, _ = io.Copy(appConn, userConn)
os.Exit(0)
}(userConn)
}
}
func TestApp(t *testing.T) {
tc, err := NewTrafficControl(appIp)
if err != nil {
t.Fatal(err, tc)
}
// do some tc settings
tc.delay("add", "40ms", "5ms", "1%")
_ = tc.Run()
_ = tc.bandwidth("1Mbit")
appListener, err := net.Listen("tcp", appIp+":"+appPort)
if err != nil {
t.Fatal(err)
}
for {
userConn, err := appListener.Accept()
if err != nil {
t.Fatal(err)
}
go func(userConn net.Conn) {
b := bytes.Repeat([]byte{0}, 1024)
startTime := time.Now()
// send data to user
for i := 0; i < dataSize/1024; i++ {
n, err := userConn.Write(b)
if err != nil {
t.Fatal(err)
}
if n != 1024 {
t.Fatal("the write len is not right")
}
}
// send bandwidth
writeBw := float64(dataSize/1024/1024) / time.Now().Sub(startTime).Seconds()
// get 100md from user
startTime = time.Now()
readLen := 0
for i := 0; i < 2<<32; i++ {
n, err := userConn.Read(b)
fmt.Println(n)
if err != nil {
log.Fatal(err)
}
fmt.Println(readLen)
readLen += n
if readLen == dataSize {
break
}
}
if readLen != dataSize {
t.Fatal("the read len is not right")
}
_, _ = userConn.Write([]byte{0})
// read bandwidth
readBw := float64(dataSize/1024/1024) / time.Now().Sub(startTime).Seconds()
// save result
err := writeResult([]float64{writeBw, readBw}, appResultFileName)
if err != nil {
t.Fatal(err)
}
os.Exit(0)
}(userConn)
}
}
func TestUser(t *testing.T) {
tc, err := NewTrafficControl(userIp)
if err != nil {
t.Fatal(err, tc)
}
// do some tc settings
tc.delay("add", "20ms", "40ms", "50%")
_ = tc.Run()
_ = tc.bandwidth("1Mbit")
appConn, err := net.Dial("tcp", serverIp+":"+serverPort)
if err != nil {
t.Fatal(err)
}
b := bytes.Repeat([]byte{0}, 1024)
startTime := time.Now()
// get 100md from app
readLen := 0
for i := 0; i < 2<<32; i++ {
n, err := appConn.Read(b)
if err != nil {
log.Fatal(err)
}
readLen += n
if readLen == dataSize {
break
}
}
if readLen != dataSize {
t.Fatal("the read len is not right", readLen, dataSize)
}
// read bandwidth
readBw := float64(dataSize/1024/1024) / time.Now().Sub(startTime).Seconds()
// send 100mb data to app
startTime = time.Now()
b = bytes.Repeat([]byte{0}, 1024)
for i := 0; i < dataSize/1024; i++ {
n, err := appConn.Write(b)
if err != nil {
t.Fatal(err)
}
if n != 1024 {
t.Fatal("the write len is not right")
}
}
b = make([]byte, 1)
_, err = io.ReadFull(appConn, b)
if err != nil {
t.Fatal(err)
}
// send bandwidth
writeBw := float64(dataSize/1024/1024) / time.Now().Sub(startTime).Seconds()
// save result
err = writeResult([]float64{readBw, writeBw}, userResultFileName)
if err != nil {
t.Fatal(err)
}
}
func TestNewMux2(t *testing.T) {
tc, err := NewTrafficControl("")
if err != nil {
t.Fatal(err)
}
err = tc.RunNetRangeTest(func() {
server(tc.Eth.EthAddr)
client(tc.Eth.EthAddr)
time.Sleep(time.Second * 3)
rate := NewRate(1024 * 1024 * 3)
rate.Start()
conn2 = NewRateConn(rate, conn2)
go func() {
m2 := NewMux(conn2, "tcp", 60)
for {
c, err := m2.Accept()
if err != nil {
log.Println(err)
continue
}
go func() {
_, _ = c.Write(bytes.Repeat([]byte{0}, 1024*1024*100))
_ = c.Close()
}()
}
}()
m1 := NewMux(conn1, "tcp", 60)
tmpCpnn, err := m1.NewConn()
if err != nil {
log.Println("nps new conn err ", err)
return
}
buf := make([]byte, 1024*1024)
var count float64
count = 0
start := time.Now()
for {
n, err := tmpCpnn.Read(buf)
count += float64(n)
log.Println(m1.bw.Get())
log.Println(uint32(math.Float64frombits(atomic.LoadUint64(&m1.latency))))
if err != nil {
log.Println(err)
break
}
}
log.Println("now rate", count/time.Now().Sub(start).Seconds()/1024/1024)
})
log.Println(err.Error())
}
func TestNewMux(t *testing.T) {
go func() {
_ = http.ListenAndServe("0.0.0.0:8889", nil)
}()
server("")
client("")
time.Sleep(time.Second * 3)
go func() {
m2 := NewMux(conn2, "tcp", 60)
for {
//log.Println("npc starting accept")
c, err := m2.Accept()
if err != nil {
log.Println(err)
continue
}
//log.Println("npc accept success ")
c2, err := net.Dial("tcp", "127.0.0.1:80")
if err != nil {
log.Println(err)
_ = c.Close()
continue
}
//c2.(*net.TCPConn).SetReadBuffer(0)
//c2.(*net.TCPConn).SetReadBuffer(0)
go func(c2 net.Conn, c *conn) {
go func() {
buf := make([]byte, 32<<10)
_, err = io.CopyBuffer(c2, c, buf)
//if err != nil {
// log.Println("close npc by copy from nps", err, c.connId)
//}
_ = c2.Close()
_ = c.Close()
}()
buf := make([]byte, 32<<10)
_, err = io.CopyBuffer(c, c2, buf)
//if err != nil {
// log.Println("close npc by copy from server", err, c.connId)
//}
_ = c2.Close()
_ = c.Close()
}(c2, c.(*conn))
}
}()
go func() {
m1 := NewMux(conn1, "tcp", 60)
l, err := net.Listen("tcp", "127.0.0.1:7777")
if err != nil {
log.Println(err)
}
for {
//log.Println("nps starting accept")
conns, err := l.Accept()
if err != nil {
log.Println(err)
continue
}
//conns.(*net.TCPConn).SetReadBuffer(0)
//conns.(*net.TCPConn).SetReadBuffer(0)
//log.Println("nps accept success starting New conn")
tmpCpnn, err := m1.NewConn()
if err != nil {
log.Println("nps New conn err ", err)
continue
}
//logs.Warn("nps New conn success ", tmpCpnn.connId)
go func(tmpCpnn *conn, conns net.Conn) {
go func() {
buf := make([]byte, 32<<10)
_, _ = io.CopyBuffer(tmpCpnn, conns, buf)
//if err != nil {
// log.Println("close nps by copy from user", tmpCpnn.connId, err)
//}
_ = conns.Close()
_ = tmpCpnn.Close()
}()
time.Sleep(time.Second)
buf := make([]byte, 32<<10)
_, err = io.CopyBuffer(conns, tmpCpnn, buf)
//if err != nil {
// log.Println("close nps by copy from npc ", tmpCpnn.connId, err)
//}
_ = conns.Close()
_ = tmpCpnn.Close()
}(tmpCpnn, conns)
}
}()
//go NewLogServer()
time.Sleep(time.Second * 5)
//for i := 0; i < 1; i++ {
// go test_raw(i)
//}
//test_request()
for {
time.Sleep(time.Second * 5)
}
}
func server(ip string) {
if ip == "" {
ip = "127.0.0.1"
}
var err error
l, err := net.Listen("tcp", ip+":9999")
if err != nil {
log.Println(err)
}
go func() {
conn1, err = l.Accept()
if err != nil {
log.Println(err)
}
}()
return
}
func client(ip string) {
if ip == "" {
ip = "127.0.0.1"
}
var err error
conn2, err = net.Dial("tcp", ip+":9999")
if err != nil {
log.Println(err)
}
}
func test_request() {
conn, _ := net.Dial("tcp", "127.0.0.1:7777")
for i := 0; i < 1000; i++ {
_, _ = conn.Write([]byte(`GET / HTTP/1.1
Host: 127.0.0.1:7777
Connection: keep-alive
`))
r, err := http.ReadResponse(bufio.NewReader(conn), nil)
if err != nil {
log.Println("close by read response err", err)
break
}
log.Println("read response success", r)
b, err := httputil.DumpResponse(r, true)
if err != nil {
log.Println("close by dump response err", err)
break
}
fmt.Println(string(b[:20]), err)
//time.Sleep(time.Second)
}
log.Println("finish")
}
func test_raw(k int) {
for i := 0; i < 1000; i++ {
ti := time.Now()
conn, err := net.Dial("tcp", "127.0.0.1:7777")
if err != nil {
log.Println("conn dial err", err)
}
tid := time.Now()
_, _ = conn.Write([]byte(`GET /videojs5/video.js HTTP/1.1
Host: 127.0.0.1:7777
`))
tiw := time.Now()
buf := make([]byte, 3572)
n, err := io.ReadFull(conn, buf)
//n, err := conn.Read(buf)
if err != nil {
log.Println("close by read response err", err)
break
}
log.Println(n, string(buf[:50]), "\n--------------\n", string(buf[n-50:n]))
//time.Sleep(time.Second)
err = conn.Close()
if err != nil {
log.Println("close conn err ", err)
}
now := time.Now()
du := now.Sub(ti).Seconds()
dud := now.Sub(tid).Seconds()
duw := now.Sub(tiw).Seconds()
if du > 1 {
log.Println("duration long", du, dud, duw, k, i)
}
if n != 3572 {
log.Println("n loss", n, string(buf))
}
}
log.Println("finish")
}
func TestNewConn(t *testing.T) {
buf := make([]byte, 1024)
log.Println(len(buf), cap(buf))
//b := pool.GetBufPoolCopy()
//b[0] = 1
//b[1] = 2
//b[2] = 3
b := []byte{1, 2, 3}
log.Println(copy(buf[:3], b), len(buf), cap(buf))
log.Println(len(buf), buf[0])
}
func TestDQueue(t *testing.T) {
d := new(bufDequeue)
d.vals = make([]unsafe.Pointer, 8)
go func() {
time.Sleep(time.Second)
for i := 0; i < 10; i++ {
log.Println(i)
log.Println(d.popTail())
}
}()
go func() {
time.Sleep(time.Second)
for i := 0; i < 10; i++ {
data := "test"
go log.Println(i, unsafe.Pointer(&data), d.pushHead(unsafe.Pointer(&data)))
}
}()
time.Sleep(time.Second * 3)
}
func TestChain(t *testing.T) {
go func() {
log.Println(http.ListenAndServe("0.0.0.0:8889", nil))
}()
time.Sleep(time.Second * 5)
d := new(bufChain)
d.new(256)
go func() {
time.Sleep(time.Second)
for i := 0; i < 30000; i++ {
unsa, ok := d.popTail()
str := (*string)(unsa)
if ok {
fmt.Println(i, str, *str, ok)
//logs.Warn(i, str, *str, ok)
} else {
fmt.Println("nil", i, ok)
//logs.Warn("nil", i, ok)
}
}
}()
go func() {
time.Sleep(time.Second)
for i := 0; i < 3000; i++ {
go func(i int) {
for n := 0; n < 10; n++ {
data := "test " + strconv.Itoa(i) + strconv.Itoa(n)
fmt.Println(data, unsafe.Pointer(&data))
//logs.Warn(data, unsafe.Pointer(&data))
d.pushHead(unsafe.Pointer(&data))
}
}(i)
}
}()
time.Sleep(time.Second * 100000)
}
//func TestReceive(t *testing.T) {
// go func() {
// log.Println(http.ListenAndServe("0.0.0.0:8889", nil))
// }()
// logs.EnableFuncCallDepth(true)
// logs.SetLogFuncCallDepth(3)
// time.Sleep(time.Second * 5)
// mux := New(Mux)
// mux.bw.readBandwidth = float64(1*1024*1024)
// mux.latency = float64(1/1000)
// wind := New(receiveWindow)
// wind.New(mux)
// wind.
// go func() {
// time.Sleep(time.Second)
// for i := 0; i < 36000; i++ {
// data := d.Pop()
// //fmt.Println(i, string(data.buf), err)
// logs.Warn(i, string(data.content), data)
// }
// }()
// go func() {
// time.Sleep(time.Second*10)
// for i := 0; i < 3000; i++ {
// go func(i int) {
// for n := 0; n < 10; n++{
// data := New(common.muxPackager)
// by := []byte("test " + strconv.Itoa(i) + strconv.Itoa(n))
// _ = data.NewPac(common.MUX_NEW_MSG_PART, int32(i), by)
// //fmt.Println(string((*data).buf), data)
// logs.Warn(string((*data).content), data)
// d.Push(data)
// }
// }(i)
// go func(i int) {
// data := New(common.muxPackager)
// _ = data.NewPac(common.MUX_NEW_CONN, int32(i), nil)
// //fmt.Println(string((*data).buf), data)
// logs.Warn(data)
// d.Push(data)
// }(i)
// go func(i int) {
// data := New(common.muxPackager)
// _ = data.NewPac(common.MUX_NEW_CONN_OK, int32(i), nil)
// //fmt.Println(string((*data).buf), data)
// logs.Warn(data)
// d.Push(data)
// }(i)
// }
// }()
// time.Sleep(time.Second * 100000)
//}
+165
View File
@@ -0,0 +1,165 @@
package nps_mux
import (
"encoding/binary"
"errors"
"github.com/astaxie/beego/logs"
"io"
)
type basePackager struct {
buf []byte
// buf contain the mux protocol struct binary data, we copy data to buf firstly.
// replace binary.Read/Write method, it may use reflect shows slowly.
// also reduce conn.Read/Write calls which use syscall.
// due to our test, conn.Write method reduce by two-thirds CPU times,
// conn.Write method has 20% reduction of the CPU times,
// totally provides more than twice of the CPU performance improvement.
length uint16
content []byte
}
func (Self *basePackager) Set(content []byte) (err error) {
Self.reset()
if content != nil {
n := len(content)
//fmt.Println(content)
if n == 0 {
// 长度为0的包,不应该向上抛,不然客户端会EOF,这里暂时没解决空包的问题 TODO
//logs.Error("mux:packer: newpack content is zero length")
//err = errors.New("mux:packer: newpack content is zero length")
}
if n > maximumSegmentSize {
logs.Error("mux:packer: newpack content segment too large")
//err = errors.New("mux:packer: newpack content segment too large")
return
}
Self.content = Self.content[:n]
copy(Self.content, content)
} else {
logs.Error("mux:packer: newpack content is nil")
return
//panic("mux:packer: newpack content is nil")
//err = errors.New("mux:packer: newpack content is nil")
}
Self.setLength()
return
}
func (Self *basePackager) Pack(writer io.Writer) (err error) {
binary.LittleEndian.PutUint16(Self.buf[5:7], Self.length)
_, err = writer.Write(Self.buf[:7])
if err != nil {
return
}
_, err = writer.Write(Self.content[:Self.length])
return
}
func (Self *basePackager) UnPack(reader io.Reader) (n uint16, err error) {
Self.reset()
l, err := io.ReadFull(reader, Self.buf[5:7])
if err != nil {
return
}
n += uint16(l)
Self.length = binary.LittleEndian.Uint16(Self.buf[5:7])
if int(Self.length) > cap(Self.content) {
err = errors.New("mux:packer: unpack err, content length too large")
return
}
if Self.length > maximumSegmentSize {
err = errors.New("mux:packer: unpack content segment too large")
return
}
Self.content = Self.content[:int(Self.length)]
l, err = io.ReadFull(reader, Self.content)
n += uint16(l)
return
}
func (Self *basePackager) setLength() {
Self.length = uint16(len(Self.content))
return
}
func (Self *basePackager) reset() {
Self.length = 0
Self.content = Self.content[:0] // reset length
}
type muxPackager struct {
flag uint8
id int32
window uint64
basePackager
}
func (Self *muxPackager) Set(flag uint8, id int32, content interface{}) (err error) {
Self.buf = windowBuff.Get()
Self.flag = flag
Self.id = id
switch flag {
case muxPingFlag, muxPingReturn, muxNewMsg, muxNewMsgPart:
Self.content = windowBuff.Get()
if content != nil {
err = Self.basePackager.Set(content.([]byte))
}
case muxMsgSendOk:
// MUX_MSG_SEND_OK contains one data
Self.window = content.(uint64)
}
return
}
func (Self *muxPackager) Pack(writer io.Writer) (err error) {
Self.buf = Self.buf[0:13]
Self.buf[0] = byte(Self.flag)
binary.LittleEndian.PutUint32(Self.buf[1:5], uint32(Self.id))
switch Self.flag {
case muxNewMsg, muxNewMsgPart, muxPingFlag, muxPingReturn:
err = Self.basePackager.Pack(writer)
windowBuff.Put(Self.content)
case muxMsgSendOk:
binary.LittleEndian.PutUint64(Self.buf[5:13], Self.window)
_, err = writer.Write(Self.buf[:13])
default:
_, err = writer.Write(Self.buf[:5])
}
windowBuff.Put(Self.buf)
return
}
func (Self *muxPackager) UnPack(reader io.Reader) (n uint16, err error) {
Self.buf = windowBuff.Get()
Self.buf = Self.buf[0:13]
l, err := io.ReadFull(reader, Self.buf[:5])
if err != nil {
return
}
n += uint16(l)
Self.flag = uint8(Self.buf[0])
Self.id = int32(binary.LittleEndian.Uint32(Self.buf[1:5]))
switch Self.flag {
case muxNewMsg, muxNewMsgPart, muxPingFlag, muxPingReturn:
var m uint16
Self.content = windowBuff.Get() // need Get a window buf from pool
m, err = Self.basePackager.UnPack(reader)
n += m
case muxMsgSendOk:
l, err = io.ReadFull(reader, Self.buf[5:13])
Self.window = binary.LittleEndian.Uint64(Self.buf[5:13])
n += uint16(l) // uint64
}
windowBuff.Put(Self.buf)
return
}
func (Self *muxPackager) reset() {
Self.id = 0
Self.flag = 0
Self.length = 0
Self.content = nil
Self.window = 0
Self.buf = nil
}
+100
View File
@@ -0,0 +1,100 @@
package nps_mux
import (
"sync"
)
const (
poolSizeBuffer = 4096
//poolSizeBuffer = 4096 * 10 // a mux packager total length
poolSizeWindow = poolSizeBuffer - 2 - 4 - 4 - 1 // content length
)
type windowBufferPool struct {
pool sync.Pool
}
func newWindowBufferPool() *windowBufferPool {
return &windowBufferPool{
pool: sync.Pool{
New: func() interface{} {
return make([]byte, poolSizeWindow, poolSizeWindow)
},
},
}
}
//func trace(buf []byte, ty string) {
// pc := make([]uintptr, 10) // at least 1 entry needed
// n := runtime.Callers(0, pc)
// for i := 0; i < n; i++ {
// f := runtime.FuncForPC(pc[i])
// file, line := f.FileLine(pc[i])
// log.Printf("%v %p %s:%d %s\n", ty, buf, file, line, f.Name())
// }
//}
func (Self *windowBufferPool) Get() (buf []byte) {
buf = Self.pool.Get().([]byte)
//trace(buf, "get")
return buf[:poolSizeWindow]
}
func (Self *windowBufferPool) Put(x []byte) {
//trace(x, "put")
Self.pool.Put(x[:poolSizeWindow]) // make buf to full
}
type muxPackagerPool struct {
pool sync.Pool
}
func newMuxPackagerPool() *muxPackagerPool {
return &muxPackagerPool{
pool: sync.Pool{
New: func() interface{} {
pack := muxPackager{}
return &pack
},
},
}
}
func (Self *muxPackagerPool) Get() *muxPackager {
return Self.pool.Get().(*muxPackager)
}
func (Self *muxPackagerPool) Put(pack *muxPackager) {
pack.reset()
Self.pool.Put(pack)
}
type listElementPool struct {
pool sync.Pool
}
func newListElementPool() *listElementPool {
return &listElementPool{
pool: sync.Pool{
New: func() interface{} {
element := listElement{}
return &element
},
},
}
}
func (Self *listElementPool) Get() *listElement {
return Self.pool.Get().(*listElement)
}
func (Self *listElementPool) Put(element *listElement) {
element.Reset()
Self.pool.Put(element)
}
var (
muxPack = newMuxPackagerPool()
windowBuff = newWindowBufferPool()
listEle = newListElementPool()
)
+78 -80
View File
@@ -1,7 +1,6 @@
package mux
package nps_mux
import (
"ehang.io/nps/lib/common"
"errors"
"io"
"math"
@@ -12,7 +11,7 @@ import (
"unsafe"
)
type PriorityQueue struct {
type priorityQueue struct {
highestChain *bufChain
middleChain *bufChain
lowestChain *bufChain
@@ -21,7 +20,7 @@ type PriorityQueue struct {
cond *sync.Cond
}
func (Self *PriorityQueue) New() {
func (Self *priorityQueue) New() {
Self.highestChain = new(bufChain)
Self.highestChain.new(4)
Self.middleChain = new(bufChain)
@@ -32,22 +31,20 @@ func (Self *PriorityQueue) New() {
Self.cond = sync.NewCond(locker)
}
func (Self *PriorityQueue) Push(packager *common.MuxPackager) {
//logs.Warn("push start")
func (Self *priorityQueue) Push(packager *muxPackager) {
Self.push(packager)
Self.cond.Broadcast()
//logs.Warn("push finish")
return
}
func (Self *PriorityQueue) push(packager *common.MuxPackager) {
switch packager.Flag {
case common.MUX_PING_FLAG, common.MUX_PING_RETURN:
func (Self *priorityQueue) push(packager *muxPackager) {
switch packager.flag {
case muxPingFlag, muxPingReturn:
Self.highestChain.pushHead(unsafe.Pointer(packager))
// the ping package need highest priority
// prevent ping calculation error
case common.MUX_NEW_CONN, common.MUX_NEW_CONN_OK, common.MUX_NEW_CONN_Fail:
// the new conn package need some priority too
case muxNewConn, muxNewConnOk, muxNewConnFail:
// the New conn package need some priority too
Self.middleChain.pushHead(unsafe.Pointer(packager))
default:
Self.lowestChain.pushHead(unsafe.Pointer(packager))
@@ -56,7 +53,7 @@ func (Self *PriorityQueue) push(packager *common.MuxPackager) {
const maxStarving uint8 = 8
func (Self *PriorityQueue) Pop() (packager *common.MuxPackager) {
func (Self *priorityQueue) Pop() (packager *muxPackager) {
var iter bool
for {
packager = Self.TryPop()
@@ -79,42 +76,40 @@ func (Self *PriorityQueue) Pop() (packager *common.MuxPackager) {
if Self.stop {
return
}
//logs.Warn("queue into wait")
Self.cond.Wait()
// wait for it with no more iter
packager = Self.TryPop()
//logs.Warn("queue wait finish", packager)
}
return
}
func (Self *PriorityQueue) TryPop() (packager *common.MuxPackager) {
func (Self *priorityQueue) TryPop() (packager *muxPackager) {
ptr, ok := Self.highestChain.popTail()
if ok {
packager = (*common.MuxPackager)(ptr)
packager = (*muxPackager)(ptr)
return
}
if Self.starving < maxStarving {
// not pop too much, lowestChain will wait too long
ptr, ok = Self.middleChain.popTail()
if ok {
packager = (*common.MuxPackager)(ptr)
packager = (*muxPackager)(ptr)
Self.starving++
return
}
}
ptr, ok = Self.lowestChain.popTail()
if ok {
packager = (*common.MuxPackager)(ptr)
packager = (*muxPackager)(ptr)
if Self.starving > 0 {
Self.starving = uint8(Self.starving / 2)
Self.starving = Self.starving / 2
}
return
}
if Self.starving > 0 {
ptr, ok = Self.middleChain.popTail()
if ok {
packager = (*common.MuxPackager)(ptr)
packager = (*muxPackager)(ptr)
Self.starving++
return
}
@@ -122,32 +117,32 @@ func (Self *PriorityQueue) TryPop() (packager *common.MuxPackager) {
return
}
func (Self *PriorityQueue) Stop() {
func (Self *priorityQueue) Stop() {
Self.stop = true
Self.cond.Broadcast()
}
type ConnQueue struct {
type connQueue struct {
chain *bufChain
starving uint8
stop bool
cond *sync.Cond
}
func (Self *ConnQueue) New() {
func (Self *connQueue) New() {
Self.chain = new(bufChain)
Self.chain.new(32)
locker := new(sync.Mutex)
Self.cond = sync.NewCond(locker)
}
func (Self *ConnQueue) Push(connection *conn) {
func (Self *connQueue) Push(connection *conn) {
Self.chain.pushHead(unsafe.Pointer(connection))
Self.cond.Broadcast()
return
}
func (Self *ConnQueue) Pop() (connection *conn) {
func (Self *connQueue) Pop() (connection *conn) {
var iter bool
for {
connection = Self.TryPop()
@@ -170,16 +165,14 @@ func (Self *ConnQueue) Pop() (connection *conn) {
if Self.stop {
return
}
//logs.Warn("queue into wait")
Self.cond.Wait()
// wait for it with no more iter
connection = Self.TryPop()
//logs.Warn("queue wait finish", packager)
}
return
}
func (Self *ConnQueue) TryPop() (connection *conn) {
func (Self *connQueue) TryPop() (connection *conn) {
ptr, ok := Self.chain.popTail()
if ok {
connection = (*conn)(ptr)
@@ -188,27 +181,36 @@ func (Self *ConnQueue) TryPop() (connection *conn) {
return
}
func (Self *ConnQueue) Stop() {
func (Self *connQueue) Stop() {
Self.stop = true
Self.cond.Broadcast()
}
func NewListElement(buf []byte, l uint16, part bool) (element *common.ListElement, err error) {
type listElement struct {
Buf []byte
L uint16
Part bool
}
func (Self *listElement) Reset() {
Self.L = 0
Self.Buf = nil
Self.Part = false
}
func newListElement(buf []byte, l uint16, part bool) (element *listElement, err error) {
if uint16(len(buf)) != l {
err = errors.New("ListElement: buf length not match")
err = errors.New("listElement: buf length not match")
return
}
//if l == 0 {
// logs.Warn("push zero")
//}
element = common.ListElementPool.Get()
element = listEle.Get()
element.Buf = buf
element.L = l
element.Part = part
return
}
type ReceiveWindowQueue struct {
type receiveWindowQueue struct {
lengthWait uint64
chain *bufChain
stopOp chan struct{}
@@ -218,11 +220,13 @@ type ReceiveWindowQueue struct {
// On ARM, x86-32, and 32-bit MIPS, it is the caller's responsibility
// to arrange for 64-bit alignment of 64-bit words accessed atomically.
// The first word in a variable or in an allocated struct, array, or slice can be relied upon to be 64-bit aligned.
// if there are implicit struct, careful the first word
timeout time.Time
}
func NewReceiveWindowQueue() *ReceiveWindowQueue {
queue := ReceiveWindowQueue{
func newReceiveWindowQueue() *receiveWindowQueue {
queue := receiveWindowQueue{
chain: new(bufChain),
stopOp: make(chan struct{}, 2),
readOp: make(chan struct{}),
@@ -231,7 +235,7 @@ func NewReceiveWindowQueue() *ReceiveWindowQueue {
return &queue
}
func (Self *ReceiveWindowQueue) Push(element *common.ListElement) {
func (Self *receiveWindowQueue) Push(element *listElement) {
var length, wait uint32
for {
ptrs := atomic.LoadUint64(&Self.lengthWait)
@@ -242,16 +246,14 @@ func (Self *ReceiveWindowQueue) Push(element *common.ListElement) {
}
// another goroutine change the length or into wait, make sure
}
//logs.Warn("window push before", Self.Len(), uint32(element.l), len(element.buf))
Self.chain.pushHead(unsafe.Pointer(element))
//logs.Warn("window push", Self.Len())
if wait == 1 {
Self.allowPop()
}
return
}
func (Self *ReceiveWindowQueue) Pop() (element *common.ListElement, err error) {
func (Self *receiveWindowQueue) Pop() (element *listElement, err error) {
var length uint32
startPop:
ptrs := atomic.LoadUint64(&Self.lengthWait)
@@ -265,7 +267,7 @@ startPop:
if err != nil {
return
}
goto startPop // wait finish, trying to get the new status
goto startPop // wait finish, trying to Get the New status
}
// length is not zero, so try to pop
for {
@@ -277,20 +279,17 @@ startPop:
}
}
func (Self *ReceiveWindowQueue) TryPop() (element *common.ListElement) {
func (Self *receiveWindowQueue) TryPop() (element *listElement) {
ptr, ok := Self.chain.popTail()
if ok {
//logs.Warn("window pop before", Self.Len())
element = (*common.ListElement)(ptr)
element = (*listElement)(ptr)
atomic.AddUint64(&Self.lengthWait, ^(uint64(element.L)<<dequeueBits - 1))
//logs.Warn("window pop", Self.Len(), uint32(element.l))
return
}
return nil
}
func (Self *ReceiveWindowQueue) allowPop() (closed bool) {
//logs.Warn("allow pop", Self.Len())
func (Self *receiveWindowQueue) allowPop() (closed bool) {
select {
case Self.readOp <- struct{}{}:
return false
@@ -299,11 +298,10 @@ func (Self *ReceiveWindowQueue) allowPop() (closed bool) {
}
}
func (Self *ReceiveWindowQueue) waitPush() (err error) {
//logs.Warn("wait push")
//defer logs.Warn("wait push finish")
func (Self *receiveWindowQueue) waitPush() (err error) {
t := Self.timeout.Sub(time.Now())
if t <= 0 { // not set the timeout, so wait for it without timeout, just like a tcp connection
if t <= 0 {
// not Set the timeout, so wait for it without timeout, just like a tcp connection
select {
case <-Self.readOp:
return nil
@@ -314,10 +312,8 @@ func (Self *ReceiveWindowQueue) waitPush() (err error) {
}
timer := time.NewTimer(t)
defer timer.Stop()
//logs.Warn("queue into wait")
select {
case <-Self.readOp:
//logs.Warn("queue wait finish")
return nil
case <-Self.stopOp:
err = io.EOF
@@ -328,18 +324,19 @@ func (Self *ReceiveWindowQueue) waitPush() (err error) {
}
}
func (Self *ReceiveWindowQueue) Len() (n uint32) {
func (Self *receiveWindowQueue) Len() (n uint32) {
ptrs := atomic.LoadUint64(&Self.lengthWait)
n, _ = Self.chain.head.unpack(ptrs)
// just for unpack method use
return
}
func (Self *ReceiveWindowQueue) Stop() {
func (Self *receiveWindowQueue) Stop() {
Self.stopOp <- struct{}{}
Self.stopOp <- struct{}{}
}
func (Self *ReceiveWindowQueue) SetTimeOut(t time.Time) {
func (Self *receiveWindowQueue) SetTimeOut(t time.Time) {
Self.timeout = t
}
@@ -366,8 +363,8 @@ type bufDequeue struct {
// dequeue. The size of this must be a power of 2.
//
// A slot is still in use until *both* the tail
// index has moved beyond it and typ has been set to nil. This
// is set to nil atomically by the consumer and read
// index has moved beyond it and typ has been Set to nil. This
// is Set to nil atomically by the consumer and read
// atomically by the producer.
vals []unsafe.Pointer
starving uint32
@@ -432,29 +429,30 @@ func (d *bufDequeue) pushHead(val unsafe.Pointer) bool {
// It returns false if the queue is empty. It may be called by any
// number of consumers.
func (d *bufDequeue) popTail() (unsafe.Pointer, bool) {
ptrs := atomic.LoadUint64(&d.headTail)
head, tail := d.unpack(ptrs)
if tail == head {
// Queue is empty.
return nil, false
}
slot := &d.vals[tail&uint32(len(d.vals)-1)]
var val unsafe.Pointer
var head, tail uint32
for {
ptrs := atomic.LoadUint64(&d.headTail)
head, tail = d.unpack(ptrs)
if tail == head {
// Queue is empty.
return nil, false
}
slot := &d.vals[tail&uint32(len(d.vals)-1)]
val = atomic.LoadPointer(slot)
if val != nil {
// We now own slot.
break
// We now get a slot.
if atomic.CompareAndSwapPointer(slot, val, nil) {
break
// Tell pushHead that we're done with this slot. Zeroing the
// slot is also important so we don't leave behind references
// that could keep this object live longer than necessary.
//
// We write to val first and then publish that we're done with
}
}
// Another goroutine is still pushing data on the tail.
// Maybe the value was taken by other goroutine or not push yet.
}
// Tell pushHead that we're done with this slot. Zeroing the
// slot is also important so we don't leave behind references
// that could keep this object live longer than necessary.
//
// We write to val first and then publish that we're done with
atomic.StorePointer(slot, nil)
// At this point pushHead owns the slot.
if tail < math.MaxUint32 {
atomic.AddUint64(&d.headTail, 1)
@@ -468,7 +466,7 @@ func (d *bufDequeue) popTail() (unsafe.Pointer, bool) {
//
// This is implemented as a doubly-linked list queue of poolDequeues
// where each dequeue is double the size of the previous one. Once a
// dequeue fills up, this allocates a new one and only ever pushes to
// dequeue fills up, this allocates a New one and only ever pushes to
// the latest dequeue. Pops happen from the other end of the list and
// once a dequeue is exhausted, it gets removed from the list.
type bufChain struct {
@@ -531,7 +529,7 @@ startPush:
return
}
// The current dequeue is full. Allocate a new one of twice
// The current dequeue is full. Allocate a New one of twice
// the size.
if atomic.CompareAndSwapUint32(&c.newChain, 0, 1) {
newSize := len(d.vals) * 2
+132
View File
@@ -0,0 +1,132 @@
package nps_mux
import (
"net"
"sync/atomic"
"time"
)
type Rate struct {
bucketSize int64
bucketSurplusSize int64
bucketAddSize int64
stopChan chan bool
NowRate int64
}
func NewRate(addSize int64) *Rate {
return &Rate{
bucketSize: addSize * 2,
bucketSurplusSize: 0,
bucketAddSize: addSize,
stopChan: make(chan bool),
}
}
func (s *Rate) Start() {
go s.session()
}
func (s *Rate) add(size int64) {
if res := s.bucketSize - s.bucketSurplusSize; res < s.bucketAddSize {
atomic.AddInt64(&s.bucketSurplusSize, res)
return
}
atomic.AddInt64(&s.bucketSurplusSize, size)
}
//回桶
func (s *Rate) ReturnBucket(size int64) {
s.add(size)
}
//停止
func (s *Rate) Stop() {
s.stopChan <- true
}
func (s *Rate) Get(size int64) {
if s.bucketSurplusSize >= size {
atomic.AddInt64(&s.bucketSurplusSize, -size)
return
}
ticker := time.NewTicker(time.Millisecond * 100)
for {
select {
case <-ticker.C:
if s.bucketSurplusSize >= size {
atomic.AddInt64(&s.bucketSurplusSize, -size)
ticker.Stop()
return
}
}
}
}
func (s *Rate) session() {
ticker := time.NewTicker(time.Second * 1)
for {
select {
case <-ticker.C:
if rs := s.bucketAddSize - s.bucketSurplusSize; rs > 0 {
s.NowRate = rs
} else {
s.NowRate = s.bucketSize - s.bucketSurplusSize
}
s.add(s.bucketAddSize)
case <-s.stopChan:
ticker.Stop()
return
}
}
}
type Conn struct {
conn net.Conn
rate *Rate
}
func NewRateConn(rate *Rate, conn net.Conn) *Conn {
return &Conn{
conn: conn,
rate: rate,
}
}
func (conn *Conn) Read(b []byte) (n int, err error) {
defer func() {
conn.rate.Get(int64(n))
}()
return conn.conn.Read(b)
}
func (conn *Conn) Write(b []byte) (n int, err error) {
defer func() {
conn.rate.Get(int64(n))
}()
return conn.conn.Write(b)
}
func (conn *Conn) LocalAddr() net.Addr {
return conn.conn.LocalAddr()
}
func (conn *Conn) RemoteAddr() net.Addr {
return conn.conn.RemoteAddr()
}
func (conn *Conn) SetDeadline(t time.Time) error {
return conn.conn.SetDeadline(t)
}
func (conn *Conn) SetWriteDeadline(t time.Time) error {
return conn.conn.SetWriteDeadline(t)
}
func (conn *Conn) SetReadDeadline(t time.Time) error {
return conn.conn.SetReadDeadline(t)
}
func (conn *Conn) Close() error {
return conn.conn.Close()
}
@@ -1,10 +1,9 @@
//go:build !windows
// +build !windows
package mux
package nps_mux
import (
"errors"
"github.com/xtaci/kcp-go"
"net"
"os"
"syscall"
@@ -32,15 +31,7 @@ func getConnFd(c net.Conn) (fd *os.File, err error) {
return
}
return
case *kcp.UDPSession:
//fd, err = (*net.UDPConn)(unsafe.Pointer(c.(*kcp.UDPSession))).File()
//if err != nil {
// return
//}
// Todo
return
default:
err = errors.New("mux:unknown conn type, only tcp or kcp")
return
}
}
@@ -1,10 +1,9 @@
//go:build windows
// +build windows
package mux
package nps_mux
import (
"errors"
"github.com/xtaci/kcp-go"
"net"
"os"
)
@@ -14,7 +13,7 @@ func sysGetSock(fd *os.File) (bufferSize int, err error) {
// not support, WTF???
// Todo
// return syscall.GetsockoptInt((syscall.Handle)(unsafe.Pointer(fd.Fd())), syscall.SOL_SOCKET, syscall.SO_RCVBUF)
bufferSize = 5 * 1024 * 1024
bufferSize = 15 * 1024 * 1024
return
}
@@ -32,15 +31,7 @@ func getConnFd(c net.Conn) (fd *os.File, err error) {
// return
//}
return
case *kcp.UDPSession:
//fd, err = (*net.UDPConn)(unsafe.Pointer(c.(*kcp.UDPSession))).File()
//if err != nil {
// return
//}
// Todo
return
default:
err = errors.New("mux:unknown conn type, only tcp or kcp")
return
}
}
+224
View File
@@ -0,0 +1,224 @@
package nps_mux
import (
"bytes"
"errors"
"fmt"
"math"
"net"
"os/exec"
"strings"
)
type Eth struct {
EthName string
EthAddr string
}
type TrafficControl struct {
Eth *Eth
params []string
}
func Ips() (map[string]string, error) {
ips := make(map[string]string)
interfaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, i := range interfaces {
byName, err := net.InterfaceByName(i.Name)
if err != nil {
return nil, err
}
if !strings.Contains(byName.Name, "Loopback") && !strings.Contains(byName.Name, "isatap") {
addresses, _ := byName.Addrs()
for _, v := range addresses {
ips[byName.Name] = v.String()
}
}
}
return ips, nil
}
// get ip and Eth information by Eth name
func GetEthByIp(ipAddr string) (eth *Eth, err error) {
var interfaces []net.Interface
interfaces, err = net.Interfaces()
if err != nil {
return
}
for _, i := range interfaces {
var byName *net.Interface
byName, err = net.InterfaceByName(i.Name)
if err != nil {
return
}
// except lo
if !strings.Contains(byName.Name, "Loopback") && !strings.Contains(byName.Name, "isatap") && !strings.Contains(byName.Name, "lo") {
addresses, _ := byName.Addrs()
for _, v := range addresses {
ipMask := strings.Split(v.String(), "/")
if len(ipMask) == 2 {
if ipAddr == "" || ipMask[0] == ipAddr {
eth = new(Eth)
eth.EthAddr = ipMask[0]
eth.EthName = byName.Name
return
}
}
}
}
}
err = errors.New("not found interface")
return
}
type tcFunc func()
func getArrayExhaustivity(arr []tcFunc) (result [][]tcFunc) {
var l = int(math.Pow(float64(2), float64(len(arr))) - 1)
var t []tcFunc
for i := 1; i <= l; i++ {
s := i
t = []tcFunc{}
for k := 0; s > 0; k++ {
if s&1 == 1 {
t = append(t, arr[k])
}
s >>= 1
}
result = append(result, t)
}
return
}
func NewTrafficControl(ipAddr string) (*TrafficControl, error) {
Eth, err := GetEthByIp(ipAddr)
if err != nil {
return nil, err
}
t := new(TrafficControl)
t.params = make([]string, 0)
t.Eth = Eth
return t, nil
}
// test the network randomly
func (tc *TrafficControl) RunNetRangeTest(f func()) error {
funcs := tc.getTestVariable()
groups := getArrayExhaustivity(funcs)
for _, v := range groups {
tc.del()
// execute bandwidth control, not good work
//if err := tc.bandwidth("1mbit"); err != nil {
// return err
//}
// execute random strategy
for _, vv := range v {
vv()
}
err := tc.Run()
if err != nil {
return err
}
// execute test func
f()
// clear strategy
if err := tc.del(); err != nil {
return err
}
}
return nil
}
// create test variables
func (tc *TrafficControl) getTestVariable() []tcFunc {
return []tcFunc{
func() { tc.delay("add", "100ms", "10ms", "30%") },
func() { tc.loss("add", "1%", "30%") },
func() { tc.duplicate("add", "1%") },
func() { tc.corrupt("add", "0.2%") },
}
}
// this command sets the transmission of the network card to delayVal. At the same time,
// about waveRatio of the packets will be delayed by ± wave.
func (tc *TrafficControl) delay(opt, delayVal, wave, waveRatio string) {
tc.params = append(tc.params, []string{"delay", delayVal, wave, waveRatio}...)
}
// this command sets the transmission of the network card to randomly drop lossRatio of packets with a success rate of lossSuccessRatio.
func (tc *TrafficControl) loss(opt, lossRatio, lossSuccessRatio string) {
tc.params = append(tc.params, []string{"loss", lossRatio, lossSuccessRatio}...)
}
// this command sets the transmission of the network card to randomly generate repeatRatio duplicate packets
func (tc *TrafficControl) duplicate(opt, duplicateRatio string) {
tc.params = append(tc.params, []string{"duplicate", duplicateRatio}...)
}
// this command sets the transmission of the network card to randomly generate corruptRatio corrupted packets.
// the kernel version must be above 2.6.16
func (tc *TrafficControl) corrupt(opt, corruptRatio string) {
tc.params = append(tc.params, []string{"corrupt", corruptRatio}...)
}
func (tc *TrafficControl) Run() error {
tc.params = append([]string{"qdisc", "add", "dev", tc.Eth.EthName, "root", "netem"}, tc.params...)
return runCmd(exec.Command("tc", tc.params...))
}
// remove all tc setting
func (tc *TrafficControl) del() error {
tc.clear()
return runCmd(exec.Command("tc", "qdisc", "del", "dev", tc.Eth.EthName, "root"))
}
// clear the old settings
func (tc *TrafficControl) clear() {
tc.params = tc.params[:0]
}
// remove all tc setting
func (tc *TrafficControl) bandwidth(bw string) error {
runCmd(exec.Command("tc", "qdisc", "add", "dev", tc.Eth.EthName, "root", "handle", "2:", "htb", "default", "30"))
return runCmd(exec.Command("tc", "qdisc", "add", "dev", tc.Eth.EthName, "parent", "2:", "classid", "2:30", "htb", "rate", bw))
}
func runCmd(cmd *exec.Cmd) error {
fmt.Println("run cmd:", cmd.Args)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
return err
}
return nil
}
func createNetwork(name, networok string) error {
// docker network create --subnet=172.18.0.0/16 test
return runCmd(exec.Command("docker", "network", "create", "--subnet="+networok, name))
}
func deleteNetwork(name string) error {
return runCmd(exec.Command("docker", "network", "rm", name))
}
func runDocker(dockerName, networkName, ip, testFunName, nowDir string) error {
// docker run --env GOPROXY=https://goproxy.cn --rm --name client --net test --cap-add=NET_ADMIN --ip 172.18.0.5 -v "$PWD":/usr/src/myapp -w /usr/src/myapp golang go test -v -run TestClient ./
return runCmd(exec.Command("docker", "run", "--env", "GOPROXY=https://goproxy.cn", "--rm", "--name", dockerName, "--net", networkName,
"--cap-add=NET_ADMIN", "--ip", ip, "-v", nowDir+`:/usr/src/myapp`, "-w", `/usr/src/myapp`, "golang", "go", "test",
"-v", "-run", testFunName, "./"))
}
func stopDocker(dockerName string) error {
return runCmd(exec.Command("docker", "stop", dockerName))
}
+1 -1
View File
@@ -1,4 +1,4 @@
package mux
package pmux
import (
"net"
@@ -1,4 +1,4 @@
package mux
package pmux
import (
"errors"
+2 -2
View File
@@ -1,6 +1,6 @@
// This module is used for port reuse
// Distinguish client, web manager , HTTP and HTTPS according to the difference of protocol
package mux
package pmux
import (
"bufio"
@@ -139,7 +139,7 @@ func (pMux *PortMux) process(conn net.Conn) {
func (pMux *PortMux) Close() error {
if pMux.isClose {
return errors.New("the port mux has closed")
return errors.New("the port pmux has closed")
}
pMux.isClose = true
close(pMux.clientConn)
@@ -1,4 +1,4 @@
package mux
package pmux
import (
"testing"
+1 -1
View File
@@ -1,6 +1,6 @@
package version
const VERSION = "0.26.0"
const VERSION = "0.26.14"
// Compulsory minimum version, Minimum downward compatibility to this version
func GetVersion() string {
+3 -3
View File
@@ -5,12 +5,12 @@ import (
"os"
"strconv"
"ehang.io/nps/lib/mux"
"ehang.io/nps/lib/pmux"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
)
var pMux *mux.PortMux
var pMux *pmux.PortMux
var bridgePort string
var httpsPort string
var httpPort string
@@ -28,7 +28,7 @@ func InitConnectionService() {
logs.Error(err)
os.Exit(0)
}
pMux = mux.NewPortMux(port, beego.AppConfig.String("web_host"))
pMux = pmux.NewPortMux(port, beego.AppConfig.String("web_host"))
}
}
+20 -2
View File
@@ -4,6 +4,7 @@ import (
"errors"
"net"
"net/http"
"sort"
"sync"
"ehang.io/nps/bridge"
@@ -83,8 +84,25 @@ func (s *BaseServer) CheckFlowAndConnNum(client *file.Client) error {
return nil
}
func in(target string, str_array []string) bool {
sort.Strings(str_array)
index := sort.SearchStrings(str_array, target)
if index < len(str_array) && str_array[index] == target {
return true
}
return false
}
//create a new connection and start bytes copying
func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string, rb []byte, tp string, f func(), flow *file.Flow, localProxy bool) error {
func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string,
rb []byte, tp string, f func(), flow *file.Flow, localProxy bool, task *file.Tunnel) error {
// 判断访问地址是否在黑名单内
if common.IsBlackIp(c.RemoteAddr().String(), client.VerifyKey, client.BlackIpList) {
c.Close()
return nil
}
link := conn.NewLink(tp, addr, client.Cnf.Crypt, client.Cnf.Compress, c.Conn.RemoteAddr().String(), localProxy)
if target, err := s.bridge.SendLinkInfo(client.Id, link, s.task); err != nil {
logs.Warn("get connection from client id %d error %s", client.Id, err.Error())
@@ -94,7 +112,7 @@ func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string,
if f != nil {
f()
}
conn.CopyWaitGroup(target, c.Conn, link.Crypt, link.Compress, client.Rate, flow, true, rb)
conn.CopyWaitGroup(target, c.Conn, link.Crypt, link.Compress, client.Rate, flow, true, rb, task)
}
return nil
}
+72 -54
View File
@@ -3,23 +3,22 @@ package proxy
import (
"bufio"
"crypto/tls"
"io"
"net"
"net/http"
"net/http/httputil"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"ehang.io/nps/bridge"
"ehang.io/nps/lib/cache"
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/conn"
"ehang.io/nps/lib/file"
"ehang.io/nps/lib/goroutine"
"ehang.io/nps/server/connection"
"github.com/astaxie/beego/logs"
"io"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
)
type httpServer struct {
@@ -30,11 +29,12 @@ type httpServer struct {
httpsServer *http.Server
httpsListener net.Listener
useCache bool
addOrigin bool
cache *cache.Cache
cacheLen int
}
func NewHttp(bridge *bridge.Bridge, c *file.Tunnel, httpPort, httpsPort int, useCache bool, cacheLen int) *httpServer {
func NewHttp(bridge *bridge.Bridge, c *file.Tunnel, httpPort, httpsPort int, useCache bool, cacheLen int, addOrigin bool) *httpServer {
httpServer := &httpServer{
BaseServer: BaseServer{
task: c,
@@ -45,6 +45,7 @@ func NewHttp(bridge *bridge.Bridge, c *file.Tunnel, httpPort, httpsPort int, use
httpsPort: httpsPort,
useCache: useCache,
cacheLen: cacheLen,
addOrigin: addOrigin,
}
if useCache {
httpServer.cache = cache.New(cacheLen)
@@ -55,7 +56,7 @@ func NewHttp(bridge *bridge.Bridge, c *file.Tunnel, httpPort, httpsPort int, use
func (s *httpServer) Start() error {
var err error
if s.errorContent, err = common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "error.html")); err != nil {
s.errorContent = []byte("easyProxy 404")
s.errorContent = []byte("nps 404")
}
if s.httpPort > 0 {
s.httpServer = s.NewServer(s.httpPort, "http")
@@ -100,23 +101,30 @@ func (s *httpServer) Close() error {
}
func (s *httpServer) handleTunneling(w http.ResponseWriter, r *http.Request) {
hijacker, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
return
if r.Header.Get("Upgrade") != "" {
rProxy := NewHttpReverseProxy(s)
rProxy.ServeHTTP(w, r)
} else {
hijacker, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
return
}
c, _, err := hijacker.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
s.handleHttp(conn.NewConn(c), r)
}
c, _, err := hijacker.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
s.handleHttp(conn.NewConn(c), r)
}
func (s *httpServer) handleHttp(c *conn.Conn, r *http.Request) {
var (
host *file.Host
target net.Conn
lastHost *file.Host
err error
connClient io.ReadWriteCloser
scheme = r.URL.Scheme
@@ -128,11 +136,16 @@ func (s *httpServer) handleHttp(c *conn.Conn, r *http.Request) {
)
defer func() {
if connClient != nil {
s.writeConnFail(c.Conn)
connClient.Close()
} else {
s.writeConnFail(c.Conn)
}
c.Close()
}()
reset:
if isReset {
host.Client.AddConn()
}
if host, err = file.GetDb().GetInfoByHost(r.Host, r); err != nil {
logs.Notice("the url %s %s %s can't be parsed!", r.URL.Scheme, r.Host, r.RequestURI)
return
@@ -141,23 +154,30 @@ func (s *httpServer) handleHttp(c *conn.Conn, r *http.Request) {
logs.Warn("client id %d, host id %d, error %s, when https connection", host.Client.Id, host.Id, err.Error())
return
}
defer host.Client.AddConn()
if !isReset {
defer host.Client.AddConn()
}
if err = s.auth(r, c, host.Client.Cnf.U, host.Client.Cnf.P); err != nil {
logs.Warn("auth error", err, r.RemoteAddr)
return
}
reset:
if targetAddr, err = host.Target.GetRandomTarget(); err != nil {
logs.Warn(err.Error())
return
}
// 判断访问地址是否在黑名单内
if common.IsBlackIp(c.RemoteAddr().String(), host.Client.VerifyKey, host.Client.BlackIpList) {
c.Close()
return
}
lk = conn.NewLink("http", targetAddr, host.Client.Cnf.Crypt, host.Client.Cnf.Compress, r.RemoteAddr, host.Target.LocalProxy)
if target, err = s.bridge.SendLinkInfo(host.Client.Id, lk, nil); err != nil {
logs.Notice("connect to target %s error %s", lk.Host, err)
return
}
connClient = conn.GetConn(target, lk.Crypt, lk.Compress, host.Client.Rate, true)
lastHost = host
//read from inc-client
go func() {
@@ -170,27 +190,23 @@ reset:
c.Close()
}
}()
for {
if resp, err := http.ReadResponse(bufio.NewReader(connClient), r); err != nil || resp == nil {
err1 := goroutine.CopyBuffer(c, connClient, host.Client.Flow, nil, "")
if err1 != nil {
return
}
resp, err := http.ReadResponse(bufio.NewReader(connClient), r)
if err != nil || resp == nil || r == nil {
// if there got broken pipe, http.ReadResponse will get a nil
//break
return
} else {
lenConn := conn.NewLenConn(c)
if err := resp.Write(lenConn); err != nil {
logs.Error(err)
//break
return
} else {
//if the cache is start and the response is in the extension,store the response to the cache list
if s.useCache && r.URL != nil && strings.Contains(r.URL.Path, ".") {
b, err := httputil.DumpResponse(resp, true)
if err != nil {
return
}
c.Write(b)
host.Flow.Add(0, int64(len(b)))
s.cache.Add(filepath.Join(host.Host, r.URL.Path), b)
} else {
lenConn := conn.NewLenConn(c)
if err := resp.Write(lenConn); err != nil {
logs.Error(err)
return
}
host.Flow.Add(0, int64(lenConn.Len))
}
}
}
}()
@@ -204,7 +220,7 @@ reset:
break
}
logs.Trace("%s request, method %s, host %s, url %s, remote address %s, return cache", r.URL.Scheme, r.Method, r.Host, r.URL.Path, c.RemoteAddr().String())
host.Flow.Add(0, int64(n))
host.Client.Flow.Add(int64(n), int64(n))
//if return cache and does not create a new conn with client and Connection is not set or close, close the connection.
if strings.ToLower(r.Header.Get("Connection")) == "close" || strings.ToLower(r.Header.Get("Connection")) == "" {
break
@@ -214,20 +230,23 @@ reset:
}
//change the host and header and set proxy setting
common.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, c.Conn.RemoteAddr().String())
logs.Trace("%s request, method %s, host %s, url %s, remote address %s, target %s", r.URL.Scheme, r.Method, r.Host, r.URL.Path, c.RemoteAddr().String(), lk.Host)
common.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, c.Conn.RemoteAddr().String(), s.addOrigin)
logs.Info("%s request, method %s, host %s, url %s, remote address %s, target %s", r.URL.Scheme, r.Method, r.Host, r.URL.Path, c.RemoteAddr().String(), lk.Host)
//write
lenConn = conn.NewLenConn(connClient)
//lenConn = conn.LenConn
if err := r.Write(lenConn); err != nil {
logs.Error(err)
break
}
host.Flow.Add(int64(lenConn.Len), 0)
host.Client.Flow.Add(int64(lenConn.Len), int64(lenConn.Len))
readReq:
//read req from connection
if r, err = http.ReadRequest(bufio.NewReader(c)); err != nil {
break
r, err = http.ReadRequest(bufio.NewReader(c))
if err != nil {
//break
return
}
r.URL.Scheme = scheme
//What happened ,Why one character less???
@@ -235,9 +254,8 @@ reset:
if hostTmp, err := file.GetDb().GetInfoByHost(r.Host, r); err != nil {
logs.Notice("the url %s %s %s can't be parsed!", r.URL.Scheme, r.Host, r.RequestURI)
break
} else if host != lastHost {
} else if host != hostTmp {
host = hostTmp
lastHost = host
isReset = true
connClient.Close()
goto reset
+1 -1
View File
@@ -125,7 +125,7 @@ func (https *HttpsServer) handleHttps(c net.Conn) {
logs.Warn(err.Error())
}
logs.Trace("new https connection,clientId %d,host %s,remote address %s", host.Client.Id, r.Host, c.RemoteAddr().String())
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Flow, host.Target.LocalProxy)
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Flow, host.Target.LocalProxy, nil)
}
type HttpsListener struct {
+5 -1
View File
@@ -142,7 +142,7 @@ func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
}
s.DealClient(conn.NewConn(c), s.task.Client, addr, nil, ltype, func() {
s.sendReply(c, succeeded)
}, s.task.Flow, s.task.Target.LocalProxy)
}, s.task.Flow, s.task.Target.LocalProxy, nil)
return
}
@@ -270,6 +270,7 @@ func (s *Sock5ModeServer) handleUDP(c net.Conn) {
b := common.BufPoolUdp.Get().([]byte)
defer common.BufPoolUdp.Put(b)
defer target.Close()
for {
_, err := c.Read(b)
if err != nil {
@@ -343,6 +344,9 @@ func (s *Sock5ModeServer) Auth(c net.Conn) error {
if s.task.MultiAccount != nil {
// enable multi user auth
U = string(user)
if len(U) == 0 {
return errors.New("验证不通过")
}
var ok bool
P, ok = s.task.MultiAccount.AccountMap[U]
if !ok {
+5 -2
View File
@@ -103,11 +103,13 @@ func ProcessTunnel(c *conn.Conn, s *TunnelModeServer) error {
logs.Warn("tcp port %d ,client id %d,task id %d connect error %s", s.task.Port, s.task.Client.Id, s.task.Id, err.Error())
return err
}
return s.DealClient(c, s.task.Client, targetAddr, nil, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
return s.DealClient(c, s.task.Client, targetAddr, nil, common.CONN_TCP, nil, s.task.Client.Flow, s.task.Target.LocalProxy, s.task)
}
//http proxy
func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
_, addr, rb, err, r := c.GetHost()
if err != nil {
c.Close()
@@ -121,5 +123,6 @@ func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
if err := s.auth(r, c, s.task.Client.Cnf.U, s.task.Client.Cnf.P); err != nil {
return err
}
return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP, nil, s.task.Client.Flow, s.task.Target.LocalProxy, nil)
}
+2 -1
View File
@@ -1,3 +1,4 @@
//go:build !windows
// +build !windows
package proxy
@@ -15,7 +16,7 @@ func HandleTrans(c *conn.Conn, s *TunnelModeServer) error {
if addr, err := getAddress(c.Conn); err != nil {
return err
} else {
return s.DealClient(c, s.task.Client, addr, nil, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
return s.DealClient(c, s.task.Client, addr, nil, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy, nil)
}
}
+61 -18
View File
@@ -1,8 +1,11 @@
package proxy
import (
"io"
"net"
"strings"
"sync"
"time"
"ehang.io/nps/bridge"
"ehang.io/nps/lib/common"
@@ -13,6 +16,7 @@ import (
type UdpModeServer struct {
BaseServer
addrMap sync.Map
listener *net.UDPConn
}
@@ -33,8 +37,8 @@ func (s *UdpModeServer) Start() error {
if err != nil {
return err
}
buf := common.BufPoolUdp.Get().([]byte)
for {
buf := common.BufPoolUdp.Get().([]byte)
n, addr, err := s.listener.ReadFromUDP(buf)
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
@@ -42,6 +46,12 @@ func (s *UdpModeServer) Start() error {
}
continue
}
// 判断访问地址是否在黑名单内
if common.IsBlackIp(addr.String(), s.task.Client.VerifyKey, s.task.Client.BlackIpList) {
break
}
logs.Trace("New udp connection,client %d,remote address %s", s.task.Client.Id, addr)
go s.process(addr, buf[:n])
}
@@ -49,26 +59,59 @@ func (s *UdpModeServer) Start() error {
}
func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
if err := s.CheckFlowAndConnNum(s.task.Client); err != nil {
logs.Warn("client id %d, task id %d,error %s, when udp connection", s.task.Client.Id, s.task.Id, err.Error())
return
}
defer s.task.Client.AddConn()
link := conn.NewLink(common.CONN_UDP, s.task.Target.TargetStr, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, addr.String(), s.task.Target.LocalProxy)
if target, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, s.task); err != nil {
return
if v, ok := s.addrMap.Load(addr.String()); ok {
clientConn, ok := v.(io.ReadWriteCloser)
if ok {
_, err := clientConn.Write(data)
if err != nil {
logs.Warn(err)
return
}
s.task.Client.Flow.Add(int64(len(data)), int64(len(data)))
}
} else {
s.task.Flow.Add(int64(len(data)), 0)
buf := common.BufPoolUdp.Get().([]byte)
defer common.BufPoolUdp.Put(buf)
target.Write(data)
s.task.Flow.Add(int64(len(data)), 0)
if n, err := target.Read(buf); err != nil {
logs.Warn(err)
if err := s.CheckFlowAndConnNum(s.task.Client); err != nil {
logs.Warn("client id %d, task id %d,error %s, when udp connection", s.task.Client.Id, s.task.Id, err.Error())
return
}
defer s.task.Client.AddConn()
link := conn.NewLink(common.CONN_UDP, s.task.Target.TargetStr, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, addr.String(), s.task.Target.LocalProxy)
if clientConn, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, s.task); err != nil {
return
} else {
s.listener.WriteTo(buf[:n], addr)
s.task.Flow.Add(0, int64(n))
target := conn.GetConn(clientConn, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, nil, true)
s.addrMap.Store(addr.String(), target)
defer target.Close()
_, err := target.Write(data)
if err != nil {
logs.Warn(err)
return
}
buf := common.BufPoolUdp.Get().([]byte)
defer common.BufPoolUdp.Put(buf)
s.task.Client.Flow.Add(int64(len(data)), int64(len(data)))
for {
clientConn.SetReadDeadline(time.Now().Add(time.Minute * 10))
if n, err := target.Read(buf); err != nil {
s.addrMap.Delete(addr.String())
logs.Warn(err)
return
} else {
_, err := s.listener.WriteTo(buf[:n], addr)
if err != nil {
logs.Warn(err)
return
}
s.task.Client.Flow.Add(int64(n), int64(n))
}
if err := s.CheckFlowAndConnNum(s.task.Client); err != nil {
logs.Warn("client id %d, task id %d,error %s, when udp connection", s.task.Client.Id, s.task.Id, err.Error())
return
}
}
}
}
}
+270
View File
@@ -0,0 +1,270 @@
package proxy
import (
"context"
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/conn"
"ehang.io/nps/lib/file"
"ehang.io/nps/lib/goroutine"
"errors"
"github.com/astaxie/beego/logs"
"io"
"net"
"net/http"
"net/http/httputil"
"strings"
"sync"
"time"
)
type HTTPError struct {
error
HTTPCode int
}
type HttpReverseProxy struct {
proxy *ReverseProxy
responseHeaderTimeout time.Duration
}
type flowConn struct {
io.ReadWriteCloser
fakeAddr net.Addr
host *file.Host
flowIn int64
flowOut int64
once sync.Once
}
func (rp *HttpReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
var (
host *file.Host
targetAddr string
err error
)
if host, err = file.GetDb().GetInfoByHost(req.Host, req); err != nil {
rw.WriteHeader(http.StatusNotFound)
rw.Write([]byte(req.Host + " not found"))
return
}
if host.Client.Cnf.U != "" && host.Client.Cnf.P != "" && !common.CheckAuth(req, host.Client.Cnf.U, host.Client.Cnf.P) {
rw.WriteHeader(http.StatusUnauthorized)
rw.Write([]byte("Unauthorized"))
return
}
if targetAddr, err = host.Target.GetRandomTarget(); err != nil {
rw.WriteHeader(http.StatusBadGateway)
rw.Write([]byte("502 Bad Gateway"))
return
}
host.Client.CutConn()
req = req.WithContext(context.WithValue(req.Context(), "host", host))
req = req.WithContext(context.WithValue(req.Context(), "target", targetAddr))
req = req.WithContext(context.WithValue(req.Context(), "req", req))
rp.proxy.ServeHTTP(rw, req, host)
defer host.Client.AddConn()
}
func (c *flowConn) Read(p []byte) (n int, err error) {
n, err = c.ReadWriteCloser.Read(p)
return n, err
}
func (c *flowConn) Write(p []byte) (n int, err error) {
n, err = c.ReadWriteCloser.Write(p)
return n, err
}
func (c *flowConn) Close() error {
//c.once.Do(func() { c.host.Flow.Add(c.flowIn, c.flowOut) })
return c.ReadWriteCloser.Close()
}
func (c *flowConn) LocalAddr() net.Addr { return c.fakeAddr }
func (c *flowConn) RemoteAddr() net.Addr { return c.fakeAddr }
func (*flowConn) SetDeadline(t time.Time) error { return nil }
func (*flowConn) SetReadDeadline(t time.Time) error { return nil }
func (*flowConn) SetWriteDeadline(t time.Time) error { return nil }
func NewHttpReverseProxy(s *httpServer) *HttpReverseProxy {
rp := &HttpReverseProxy{
responseHeaderTimeout: 30 * time.Second,
}
local, _ := net.ResolveTCPAddr("tcp", "127.0.0.1")
proxy := NewReverseProxy(&httputil.ReverseProxy{
Director: func(r *http.Request) {
host := r.Context().Value("host").(*file.Host)
common.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, "", false)
},
Transport: &http.Transport{
ResponseHeaderTimeout: rp.responseHeaderTimeout,
DisableKeepAlives: true,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
var (
host *file.Host
target net.Conn
err error
connClient io.ReadWriteCloser
targetAddr string
lk *conn.Link
)
r := ctx.Value("req").(*http.Request)
host = ctx.Value("host").(*file.Host)
targetAddr = ctx.Value("target").(string)
lk = conn.NewLink("http", targetAddr, host.Client.Cnf.Crypt, host.Client.Cnf.Compress, r.RemoteAddr, host.Target.LocalProxy)
if target, err = s.bridge.SendLinkInfo(host.Client.Id, lk, nil); err != nil {
logs.Notice("connect to target %s error %s", lk.Host, err)
return nil, NewHTTPError(http.StatusBadGateway, "Cannot connect to the server")
}
connClient = conn.GetConn(target, lk.Crypt, lk.Compress, host.Client.Rate, true)
return &flowConn{
ReadWriteCloser: connClient,
fakeAddr: local,
host: host,
}, nil
},
},
ErrorHandler: func(rw http.ResponseWriter, req *http.Request, err error) {
logs.Warn("do http proxy request error: %v", err)
rw.WriteHeader(http.StatusNotFound)
},
})
proxy.WebSocketDialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
var (
host *file.Host
target net.Conn
err error
connClient io.ReadWriteCloser
targetAddr string
lk *conn.Link
)
r := ctx.Value("req").(*http.Request)
host = ctx.Value("host").(*file.Host)
targetAddr = ctx.Value("target").(string)
lk = conn.NewLink("tcp", targetAddr, host.Client.Cnf.Crypt, host.Client.Cnf.Compress, r.RemoteAddr, host.Target.LocalProxy)
if target, err = s.bridge.SendLinkInfo(host.Client.Id, lk, nil); err != nil {
logs.Notice("connect to target %s error %s", lk.Host, err)
return nil, NewHTTPError(http.StatusBadGateway, "Cannot connect to the target")
}
connClient = conn.GetConn(target, lk.Crypt, lk.Compress, host.Client.Rate, true)
return &flowConn{
ReadWriteCloser: connClient,
fakeAddr: local,
host: host,
}, nil
}
rp.proxy = proxy
return rp
}
func NewHTTPError(code int, errmsg string) error {
return &HTTPError{
error: errors.New(errmsg),
HTTPCode: code,
}
}
type ReverseProxy struct {
*httputil.ReverseProxy
WebSocketDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
}
func IsWebsocketRequest(req *http.Request) bool {
containsHeader := func(name, value string) bool {
items := strings.Split(req.Header.Get(name), ",")
for _, item := range items {
if value == strings.ToLower(strings.TrimSpace(item)) {
return true
}
}
return false
}
return containsHeader("Connection", "upgrade") && containsHeader("Upgrade", "websocket")
}
func NewReverseProxy(orp *httputil.ReverseProxy) *ReverseProxy {
rp := &ReverseProxy{
ReverseProxy: orp,
WebSocketDialContext: nil,
}
rp.ErrorHandler = rp.errHandler
return rp
}
func (p *ReverseProxy) errHandler(rw http.ResponseWriter, r *http.Request, e error) {
if e == io.EOF {
rw.WriteHeader(521)
//rw.Write(getWaitingPageContent())
} else {
if httperr, ok := e.(*HTTPError); ok {
rw.WriteHeader(httperr.HTTPCode)
} else {
rw.WriteHeader(http.StatusNotFound)
}
rw.Write([]byte("error: " + e.Error()))
}
}
func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request, host *file.Host) {
if IsWebsocketRequest(req) {
p.serveWebSocket(rw, req, host)
}
}
func (p *ReverseProxy) serveWebSocket(rw http.ResponseWriter, req *http.Request, host *file.Host) {
if p.WebSocketDialContext == nil {
rw.WriteHeader(500)
return
}
targetConn, err := p.WebSocketDialContext(req.Context(), "tcp", "")
if err != nil {
rw.WriteHeader(501)
return
}
defer targetConn.Close()
p.Director(req)
hijacker, ok := rw.(http.Hijacker)
if !ok {
rw.WriteHeader(500)
return
}
conn, _, errHijack := hijacker.Hijack()
if errHijack != nil {
rw.WriteHeader(500)
return
}
defer conn.Close()
req.Write(targetConn)
Join(conn, targetConn, host)
}
func Join(c1 io.ReadWriteCloser, c2 io.ReadWriteCloser, host *file.Host) (inCount int64, outCount int64) {
var wait sync.WaitGroup
pipe := func(to io.ReadWriteCloser, from io.ReadWriteCloser, count *int64) {
defer to.Close()
defer from.Close()
defer wait.Done()
goroutine.CopyBuffer(to, from, host.Client.Flow, nil, "")
//*count, _ = io.Copy(to, from)
}
wait.Add(2)
go pipe(c1, c2, &inCount)
go pipe(c2, c1, &outCount)
wait.Wait()
return
}
+63 -38
View File
@@ -7,6 +7,7 @@ import (
"os"
"strconv"
"strings"
"sync"
"time"
"ehang.io/nps/bridge"
@@ -16,19 +17,19 @@ import (
"ehang.io/nps/server/tool"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/load"
"github.com/shirou/gopsutil/mem"
"github.com/shirou/gopsutil/net"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/load"
"github.com/shirou/gopsutil/v3/mem"
"github.com/shirou/gopsutil/v3/net"
)
var (
Bridge *bridge.Bridge
RunList map[int]interface{}
RunList sync.Map //map[int]interface{}
)
func init() {
RunList = make(map[int]interface{})
RunList = sync.Map{}
}
//init task from db
@@ -37,7 +38,8 @@ func InitFromCsv() {
if vkey := beego.AppConfig.String("public_vkey"); vkey != "" {
c := file.NewClient(vkey, true, true)
file.GetDb().NewClient(c)
RunList[c.Id] = nil
RunList.Store(c.Id, nil)
//RunList[c.Id] = nil
}
//Initialize services in server-side files
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
@@ -69,7 +71,7 @@ func DealBridgeTask() {
logs.Trace("New secret connection, addr", s.Conn.Conn.RemoteAddr())
if t := file.GetDb().GetTaskByMd5Password(s.Password); t != nil {
if t.Status {
go proxy.NewBaseServer(Bridge, t).DealClient(s.Conn, t.Client, t.Target.TargetStr, nil, common.CONN_TCP, nil, t.Flow, t.Target.LocalProxy)
go proxy.NewBaseServer(Bridge, t).DealClient(s.Conn, t.Client, t.Target.TargetStr, nil, common.CONN_TCP, nil, t.Flow, t.Target.LocalProxy, nil)
} else {
s.Conn.Close()
logs.Trace("This key %s cannot be processed,status is close", s.Password)
@@ -83,8 +85,8 @@ func DealBridgeTask() {
}
//start a new server
func StartNewServer(bridgePort int, cnf *file.Tunnel, bridgeType string) {
Bridge = bridge.NewTunnel(bridgePort, bridgeType, common.GetBoolByStr(beego.AppConfig.String("ip_limit")), RunList)
func StartNewServer(bridgePort int, cnf *file.Tunnel, bridgeType string, bridgeDisconnect int) {
Bridge = bridge.NewTunnel(bridgePort, bridgeType, common.GetBoolByStr(beego.AppConfig.String("ip_limit")), RunList, bridgeDisconnect)
go func() {
if err := Bridge.StartTunnel(); err != nil {
logs.Error("start server bridge error", err)
@@ -102,7 +104,8 @@ func StartNewServer(bridgePort int, cnf *file.Tunnel, bridgeType string) {
if err := svr.Start(); err != nil {
logs.Error(err)
}
RunList[cnf.Id] = svr
RunList.Store(cnf.Id, svr)
//RunList[cnf.Id] = svr
} else {
logs.Error("Incorrect startup mode %s", cnf.Mode)
}
@@ -147,14 +150,16 @@ func NewMode(Bridge *bridge.Bridge, c *file.Tunnel) proxy.Service {
httpsPort, _ := beego.AppConfig.Int("https_proxy_port")
useCache, _ := beego.AppConfig.Bool("http_cache")
cacheLen, _ := beego.AppConfig.Int("http_cache_length")
service = proxy.NewHttp(Bridge, c, httpPort, httpsPort, useCache, cacheLen)
addOrigin, _ := beego.AppConfig.Bool("http_add_origin_header")
service = proxy.NewHttp(Bridge, c, httpPort, httpsPort, useCache, cacheLen, addOrigin)
}
return service
}
//stop server
func StopServer(id int) error {
if v, ok := RunList[id]; ok {
//if v, ok := RunList[id]; ok {
if v, ok := RunList.Load(id); ok {
if svr, ok := v.(proxy.Service); ok {
if err := svr.Close(); err != nil {
return err
@@ -167,9 +172,11 @@ func StopServer(id int) error {
return err
} else {
t.Status = false
logs.Info("close port %d,remark %s,client id %d,task id %d", t.Port, t.Remark, t.Client.Id, t.Id)
file.GetDb().UpdateTask(t)
}
delete(RunList, id)
//delete(RunList, id)
RunList.Delete(id)
return nil
}
return errors.New("task is not running")
@@ -179,7 +186,8 @@ func StopServer(id int) error {
func AddTask(t *file.Tunnel) error {
if t.Mode == "secret" || t.Mode == "p2p" {
logs.Info("secret task %s start ", t.Remark)
RunList[t.Id] = nil
//RunList[t.Id] = nil
RunList.Store(t.Id, nil)
return nil
}
if b := tool.TestServerPort(t.Port, t.Mode); !b && t.Mode != "httpHostServer" {
@@ -191,11 +199,13 @@ func AddTask(t *file.Tunnel) error {
}
if svr := NewMode(Bridge, t); svr != nil {
logs.Info("tunnel task %s start mode:%s port %d", t.Remark, t.Mode, t.Port)
RunList[t.Id] = svr
//RunList[t.Id] = svr
RunList.Store(t.Id, svr)
go func() {
if err := svr.Start(); err != nil {
logs.Error("clientId %d taskId %d start error %s", t.Client.Id, t.Id, err)
delete(RunList, t.Id)
//delete(RunList, t.Id)
RunList.Delete(t.Id)
return
}
}()
@@ -219,7 +229,8 @@ func StartTask(id int) error {
//delete task
func DelTask(id int) error {
if _, ok := RunList[id]; ok {
//if _, ok := RunList[id]; ok {
if _, ok := RunList.Load(id); ok {
if err := StopServer(id); err != nil {
return err
}
@@ -238,7 +249,7 @@ func GetTunnel(start, length int, typeVal string, clientId int, search string) (
if (typeVal != "" && v.Mode != typeVal || (clientId != 0 && v.Client.Id != clientId)) || (typeVal == "" && clientId != v.Client.Id) {
continue
}
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search)) {
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search) || strings.Contains(v.Client.VerifyKey, search)) {
continue
}
cnt++
@@ -249,7 +260,8 @@ func GetTunnel(start, length int, typeVal string, clientId int, search string) (
}
if start--; start < 0 {
if length--; length >= 0 {
if _, ok := RunList[v.Id]; ok {
//if _, ok := RunList[v.Id]; ok {
if _, ok := RunList.Load(v.Id); ok {
v.RunStatus = true
} else {
v.RunStatus = false
@@ -270,6 +282,8 @@ func GetClientList(start, length int, search, sort, order string, clientId int)
}
func dealClientData() {
//logs.Info("dealClientData.........")
file.GetDb().JsonDb.Clients.Range(func(key, value interface{}) bool {
v := value.(*file.Client)
if vv, ok := Bridge.Client.Load(v.Id); ok {
@@ -278,24 +292,34 @@ func dealClientData() {
} else {
v.IsConnect = false
}
v.Flow.InletFlow = 0
v.Flow.ExportFlow = 0
file.GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
h := value.(*file.Host)
if h.Client.Id == v.Id {
v.Flow.InletFlow += h.Flow.InletFlow
v.Flow.ExportFlow += h.Flow.ExportFlow
}
return true
})
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
t := value.(*file.Tunnel)
if t.Client.Id == v.Id {
v.Flow.InletFlow += t.Flow.InletFlow
v.Flow.ExportFlow += t.Flow.ExportFlow
}
return true
})
//v.Flow.InletFlow = 0
//v.Flow.ExportFlow = 0
//if len(file.GetDb().JsonDb.Hosts) == 0 {
//
//}
//var inflow int64 = 0
//var outflow int64 = 0
//file.GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
// h := value.(*file.Host)
// if h.Client.Id == v.Id {
// inflow += h.Flow.InletFlow
// outflow += h.Flow.ExportFlow
// }
// return true
//})
//file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
// t := value.(*file.Tunnel)
// if t.Client.Id == v.Id {
// inflow += t.Flow.InletFlow
// outflow += t.Flow.ExportFlow
// }
// return true
//})
//
//if inflow >0 || outflow >0{
// v.Flow.InletFlow = inflow
// v.Flow.ExportFlow = outflow
//}
return true
})
return
@@ -435,6 +459,7 @@ func GetDashboardData() map[string]interface{} {
return data
}
// 实例化流量数据到文件
func flowSession(m time.Duration) {
ticker := time.NewTicker(m)
defer ticker.Stop()
+2 -2
View File
@@ -52,10 +52,10 @@ func TestServerConfig() {
if port, err := strconv.Atoi(p); err != nil {
log.Fatalln("get https port error", err)
} else {
if !common.FileExists(filepath.Join(common.GetRunPath(), beego.AppConfig.String("pemPath"))) {
if beego.AppConfig.String("pemPath") != "" && !common.FileExists(filepath.Join(common.GetRunPath(), beego.AppConfig.String("pemPath"))) {
log.Fatalf("ssl certFile %s is not exist", beego.AppConfig.String("pemPath"))
}
if !common.FileExists(filepath.Join(common.GetRunPath(), beego.AppConfig.String("ketPath"))) {
if beego.AppConfig.String("keyPath") != "" && !common.FileExists(filepath.Join(common.GetRunPath(), beego.AppConfig.String("keyPath"))) {
log.Fatalf("ssl keyFile %s is not exist", beego.AppConfig.String("pemPath"))
}
isInArr(&postTcpArr, port, "http port", "tcp")
+19 -4
View File
@@ -2,15 +2,16 @@ package tool
import (
"math"
"math/rand"
"strconv"
"time"
"ehang.io/nps/lib/common"
"github.com/astaxie/beego"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/load"
"github.com/shirou/gopsutil/mem"
"github.com/shirou/gopsutil/net"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/load"
"github.com/shirou/gopsutil/v3/mem"
"github.com/shirou/gopsutil/v3/net"
)
var (
@@ -50,6 +51,20 @@ func TestServerPort(p int, m string) (b bool) {
return
}
func GenerateServerPort(m string) int {
for {
//生成随机数 1024 - 65535
serverPort := rand.Intn(65535)
if serverPort < 1024 {
serverPort = 1024
}
if TestServerPort(serverPort, m) {
return serverPort
}
}
}
func getSeverStatus() {
for {
if len(ServerStatus) < 10 {
+31 -2
View File
@@ -32,11 +32,17 @@ func (s *BaseController) Prepare() {
md5Key := s.getEscapeString("auth_key")
timestamp := s.GetIntNoErr("timestamp")
configKey := beego.AppConfig.String("auth_key")
if configKey == "" {
configKey = crypt.GetRandomString(64)
}
timeNowUnix := time.Now().Unix()
if !((math.Abs(float64(timeNowUnix-int64(timestamp))) <= 20) && (crypt.Md5(configKey+strconv.Itoa(timestamp)) == md5Key)) {
if !(md5Key != "" && (math.Abs(float64(timeNowUnix-int64(timestamp))) <= 20) && (crypt.Md5(configKey+strconv.Itoa(timestamp)) == md5Key)) {
if s.GetSession("auth") != true {
s.Redirect(beego.AppConfig.String("web_base_url")+"/login/index", 302)
}
} else {
s.SetSession("isAdmin", true)
s.Data["isAdmin"] = true
}
if s.GetSession("isAdmin") != nil && !s.GetSession("isAdmin").(bool) {
s.Ctx.Input.SetData("client_id", s.GetSession("clientId").(int))
@@ -122,6 +128,13 @@ func (s *BaseController) AjaxOk(str string) {
s.StopRun()
}
//ajax正确返回
func (s *BaseController) AjaxOkWithId(str string, id int) {
s.Data["json"] = ajaxWithId(str, 1, id)
s.ServeJSON()
s.StopRun()
}
//ajax错误返回
func (s *BaseController) AjaxErr(str string) {
s.Data["json"] = ajax(str, 0)
@@ -137,11 +150,27 @@ func ajax(str string, status int) map[string]interface{} {
return json
}
//组装ajax
func ajaxWithId(str string, status int, id int) map[string]interface{} {
json := make(map[string]interface{})
json["status"] = status
json["msg"] = str
json["id"] = id
return json
}
//ajax table返回
func (s *BaseController) AjaxTable(list interface{}, cnt int, recordsTotal int) {
func (s *BaseController) AjaxTable(list interface{}, cnt int, recordsTotal int, kwargs map[string]interface{}) {
json := make(map[string]interface{})
json["rows"] = list
json["total"] = recordsTotal
if kwargs != nil {
for k, v := range kwargs {
if v != nil {
json[k] = v
}
}
}
s.Data["json"] = json
s.ServeJSON()
s.StopRun()
+33 -7
View File
@@ -6,6 +6,7 @@ import (
"ehang.io/nps/lib/rate"
"ehang.io/nps/server"
"github.com/astaxie/beego"
"strings"
)
type ClientController struct {
@@ -28,7 +29,12 @@ func (s *ClientController) List() {
clientId = clientIdSession.(int)
}
list, cnt := server.GetClientList(start, length, s.getEscapeString("search"), s.getEscapeString("sort"), s.getEscapeString("order"), clientId)
s.AjaxTable(list, cnt, cnt)
cmd := make(map[string]interface{})
ip := s.Ctx.Request.Host
cmd["ip"] = common.GetIpByAddr(ip)
cmd["bridgeType"] = beego.AppConfig.String("bridge_type")
cmd["bridgePort"] = server.Bridge.TunnelPort
s.AjaxTable(list, cnt, cnt, cmd)
}
//添加客户端
@@ -38,9 +44,10 @@ func (s *ClientController) Add() {
s.SetInfo("add client")
s.display()
} else {
id := int(file.GetDb().JsonDb.GetClientId())
t := &file.Client{
VerifyKey: s.getEscapeString("vkey"),
Id: int(file.GetDb().JsonDb.GetClientId()),
Id: id,
Status: true,
Remark: s.getEscapeString("remark"),
Cnf: &file.Config{
@@ -60,15 +67,12 @@ func (s *ClientController) Add() {
InletFlow: 0,
FlowLimit: int64(s.GetIntNoErr("flow_limit")),
},
}
if t.RateLimit > 0 {
t.Rate = rate.NewRate(int64(t.RateLimit * 1024))
t.Rate.Start()
BlackIpList: RemoveRepeatedElement(strings.Split(s.getEscapeString("blackiplist"), "\r\n")),
}
if err := file.GetDb().NewClient(t); err != nil {
s.AjaxErr(err.Error())
}
s.AjaxOk("add success")
s.AjaxOkWithId("add success", id)
}
}
func (s *ClientController) GetClient() {
@@ -95,12 +99,15 @@ func (s *ClientController) Edit() {
s.error()
} else {
s.Data["c"] = c
s.Data["BlackIpList"] = strings.Join(c.BlackIpList, "\r\n")
}
s.SetInfo("edit client")
s.display()
} else {
if c, err := file.GetDb().GetClient(id); err != nil {
s.error()
s.AjaxErr("client ID not found")
return
} else {
if s.getEscapeString("web_username") != "" {
if s.getEscapeString("web_username") == beego.AppConfig.String("web_username") || !file.GetDb().VerifyUserName(s.getEscapeString("web_username"), c.Id) {
@@ -140,12 +147,31 @@ func (s *ClientController) Edit() {
c.Rate = rate.NewRate(int64(2 << 23))
c.Rate.Start()
}
c.BlackIpList = RemoveRepeatedElement(strings.Split(s.getEscapeString("blackiplist"), "\r\n"))
file.GetDb().JsonDb.StoreClientsToJsonFile()
}
s.AjaxOk("save success")
}
}
func RemoveRepeatedElement(arr []string) (newArr []string) {
newArr = make([]string, 0)
for i := 0; i < len(arr); i++ {
repeat := false
for j := i + 1; j < len(arr); j++ {
if arr[i] == arr[j] {
repeat = true
break
}
}
if !repeat {
newArr = append(newArr, arr[i])
}
}
return
}
//更改状态
func (s *ClientController) ChangeStatus() {
id := s.GetIntNoErr("id")
+19 -7
View File
@@ -82,7 +82,7 @@ func (s *IndexController) GetTunnel() {
taskType := s.getEscapeString("type")
clientId := s.GetIntNoErr("client_id")
list, cnt := server.GetTunnel(start, length, taskType, clientId, s.getEscapeString("search"))
s.AjaxTable(list, cnt, cnt)
s.AjaxTable(list, cnt, cnt, nil)
}
func (s *IndexController) Add() {
@@ -92,12 +92,13 @@ func (s *IndexController) Add() {
s.SetInfo("add tunnel")
s.display()
} else {
id := int(file.GetDb().JsonDb.GetTaskId())
t := &file.Tunnel{
Port: s.GetIntNoErr("port"),
ServerIp: s.getEscapeString("server_ip"),
Mode: s.getEscapeString("type"),
Target: &file.Target{TargetStr: s.getEscapeString("target"), LocalProxy: s.GetBoolNoErr("local_proxy")},
Id: int(file.GetDb().JsonDb.GetTaskId()),
Id: id,
Status: true,
Remark: s.getEscapeString("remark"),
Password: s.getEscapeString("password"),
@@ -105,6 +106,11 @@ func (s *IndexController) Add() {
StripPre: s.getEscapeString("strip_pre"),
Flow: &file.Flow{},
}
if t.Port <= 0 {
t.Port = tool.GenerateServerPort(t.Mode)
}
if !tool.TestServerPort(t.Port, t.Mode) {
s.AjaxErr("The port cannot be opened because it may has been occupied or is no longer allowed.")
}
@@ -121,7 +127,7 @@ func (s *IndexController) Add() {
if err := server.AddTask(t); err != nil {
s.AjaxErr(err.Error())
} else {
s.AjaxOk("add success")
s.AjaxOkWithId("add success", id)
}
}
}
@@ -158,11 +164,16 @@ func (s *IndexController) Edit() {
t.Client = client
}
if s.GetIntNoErr("port") != t.Port {
t.Port = s.GetIntNoErr("port")
if t.Port <= 0 {
t.Port = tool.GenerateServerPort(t.Mode)
}
if !tool.TestServerPort(s.GetIntNoErr("port"), t.Mode) {
s.AjaxErr("The port cannot be opened because it may has been occupied or is no longer allowed.")
return
}
t.Port = s.GetIntNoErr("port")
}
t.ServerIp = s.getEscapeString("server_ip")
t.Mode = s.getEscapeString("type")
@@ -215,7 +226,7 @@ func (s *IndexController) HostList() {
start, length := s.GetAjaxParams()
clientId := s.GetIntNoErr("client_id")
list, cnt := file.GetDb().GetHost(start, length, clientId, s.getEscapeString("search"))
s.AjaxTable(list, cnt, cnt)
s.AjaxTable(list, cnt, cnt, nil)
}
}
@@ -248,8 +259,9 @@ func (s *IndexController) AddHost() {
s.SetInfo("add host")
s.display("index/hadd")
} else {
id := int(file.GetDb().JsonDb.GetHostId())
h := &file.Host{
Id: int(file.GetDb().JsonDb.GetHostId()),
Id: id,
Host: s.getEscapeString("host"),
Target: &file.Target{TargetStr: s.getEscapeString("target"), LocalProxy: s.GetBoolNoErr("local_proxy")},
HeaderChange: s.getEscapeString("header"),
@@ -268,7 +280,7 @@ func (s *IndexController) AddHost() {
if err := file.GetDb().NewHost(h); err != nil {
s.AjaxErr("add fail" + err.Error())
}
s.AjaxOk("add success")
s.AjaxOkWithId("add success", id)
}
}
+48 -17
View File
@@ -1,6 +1,8 @@
package controllers
import (
"github.com/astaxie/beego/cache"
"github.com/astaxie/beego/utils/captcha"
"math/rand"
"net"
"sync"
@@ -17,18 +19,50 @@ type LoginController struct {
}
var ipRecord sync.Map
var cpt *captcha.Captcha
type record struct {
hasLoginFailTimes int
lastLoginTime time.Time
}
func init() {
// use beego cache system store the captcha data
store := cache.NewMemoryCache()
cpt = captcha.NewWithFilter("/captcha/", store)
}
func (self *LoginController) Index() {
self.Data["web_base_url"] = beego.AppConfig.String("web_base_url")
// Try login implicitly, will succeed if it's configured as no-auth(empty username&password).
webBaseUrl := beego.AppConfig.String("web_base_url")
if self.doLogin("", "", false) {
self.Redirect(webBaseUrl+"/index/index", 302)
}
self.Data["web_base_url"] = webBaseUrl
self.Data["register_allow"], _ = beego.AppConfig.Bool("allow_user_register")
self.Data["captcha_open"], _ = beego.AppConfig.Bool("open_captcha")
self.TplName = "login/index.html"
}
func (self *LoginController) Verify() {
username := self.GetString("username")
password := self.GetString("password")
captchaOpen, _ := beego.AppConfig.Bool("open_captcha")
if captchaOpen {
if !cpt.VerifyReq(self.Ctx.Request) {
self.Data["json"] = map[string]interface{}{"status": 0, "msg": "the verification code is wrong, please get it again and try again"}
self.ServeJSON()
}
}
if self.doLogin(username, password, true) {
self.Data["json"] = map[string]interface{}{"status": 1, "msg": "login success"}
} else {
self.Data["json"] = map[string]interface{}{"status": 0, "msg": "username or password incorrect"}
}
self.ServeJSON()
}
func (self *LoginController) doLogin(username, password string, explicit bool) bool {
clearIprecord()
ip, _, _ := net.SplitHostPort(self.Ctx.Request.RemoteAddr)
if v, ok := ipRecord.Load(ip); ok {
@@ -37,13 +71,11 @@ func (self *LoginController) Verify() {
vv.hasLoginFailTimes = 0
}
if vv.hasLoginFailTimes >= 10 {
self.Data["json"] = map[string]interface{}{"status": 0, "msg": "username or password incorrect"}
self.ServeJSON()
return
return false
}
}
var auth bool
if self.GetString("password") == beego.AppConfig.String("web_password") && self.GetString("username") == beego.AppConfig.String("web_username") {
if password == beego.AppConfig.String("web_password") && username == beego.AppConfig.String("web_username") {
self.SetSession("isAdmin", true)
self.DelSession("clientId")
self.DelSession("username")
@@ -58,13 +90,13 @@ func (self *LoginController) Verify() {
return true
}
if v.WebUserName == "" && v.WebPassword == "" {
if self.GetString("username") != "user" || v.VerifyKey != self.GetString("password") {
if username != "user" || v.VerifyKey != password {
return true
} else {
auth = true
}
}
if !auth && v.WebPassword == self.GetString("password") && self.GetString("username") == v.WebUserName {
if !auth && v.WebPassword == password && v.WebUserName == username {
auth = true
}
if auth {
@@ -78,18 +110,17 @@ func (self *LoginController) Verify() {
}
if auth {
self.SetSession("auth", true)
self.Data["json"] = map[string]interface{}{"status": 1, "msg": "login success"}
ipRecord.Delete(ip)
} else {
if v, load := ipRecord.LoadOrStore(ip, &record{hasLoginFailTimes: 1, lastLoginTime: time.Now()}); load {
vv := v.(*record)
vv.lastLoginTime = time.Now()
vv.hasLoginFailTimes += 1
ipRecord.Store(ip, vv)
}
self.Data["json"] = map[string]interface{}{"status": 0, "msg": "username or password incorrect"}
return true
}
self.ServeJSON()
if v, load := ipRecord.LoadOrStore(ip, &record{hasLoginFailTimes: 1, lastLoginTime: time.Now()}); load && explicit {
vv := v.(*record)
vv.lastLoginTime = time.Now()
vv.hasLoginFailTimes += 1
ipRecord.Store(ip, vv)
}
return false
}
func (self *LoginController) Register() {
if self.Ctx.Request.Method == "GET" {
File diff suppressed because one or more lines are too long
+4 -3
View File
File diff suppressed because one or more lines are too long
+462
View File
@@ -0,0 +1,462 @@
/*
* This combined file was created by the DataTables downloader builder:
* https://datatables.net/download
*
* To rebuild or modify this file with the latest versions of the included
* software please visit:
* https://datatables.net/download/#dt/dt-1.10.20
*
* Included libraries:
* DataTables 1.10.20
*/
/*
* Table styles
*/
table.dataTable {
width: 100%;
margin: 0 auto;
clear: both;
border-collapse: separate;
border-spacing: 0;
/*
* Header and footer styles
*/
/*
* Body styles
*/
}
table.dataTable thead th,
table.dataTable tfoot th {
font-weight: bold;
}
table.dataTable thead th,
table.dataTable thead td {
padding: 10px 18px;
border-bottom: 1px solid #111;
}
table.dataTable thead th:active,
table.dataTable thead td:active {
outline: none;
}
table.dataTable tfoot th,
table.dataTable tfoot td {
padding: 10px 18px 6px 18px;
border-top: 1px solid #111;
}
table.dataTable thead .sorting,
table.dataTable thead .sorting_asc,
table.dataTable thead .sorting_desc,
table.dataTable thead .sorting_asc_disabled,
table.dataTable thead .sorting_desc_disabled {
cursor: pointer;
*cursor: hand;
background-repeat: no-repeat;
background-position: center right;
}
table.dataTable thead .sorting {
background-image: url("DataTables-1.10.20/images/sort_both.png");
}
table.dataTable thead .sorting_asc {
background-image: url("DataTables-1.10.20/images/sort_asc.png");
}
table.dataTable thead .sorting_desc {
background-image: url("DataTables-1.10.20/images/sort_desc.png");
}
table.dataTable thead .sorting_asc_disabled {
background-image: url("DataTables-1.10.20/images/sort_asc_disabled.png");
}
table.dataTable thead .sorting_desc_disabled {
background-image: url("DataTables-1.10.20/images/sort_desc_disabled.png");
}
table.dataTable tbody tr {
background-color: #ffffff;
}
table.dataTable tbody tr.selected {
background-color: #B0BED9;
}
table.dataTable tbody th,
table.dataTable tbody td {
padding: 8px 10px;
}
table.dataTable.row-border tbody th, table.dataTable.row-border tbody td, table.dataTable.display tbody th, table.dataTable.display tbody td {
border-top: 1px solid #ddd;
}
table.dataTable.row-border tbody tr:first-child th,
table.dataTable.row-border tbody tr:first-child td, table.dataTable.display tbody tr:first-child th,
table.dataTable.display tbody tr:first-child td {
border-top: none;
}
table.dataTable.cell-border tbody th, table.dataTable.cell-border tbody td {
border-top: 1px solid #ddd;
border-right: 1px solid #ddd;
}
table.dataTable.cell-border tbody tr th:first-child,
table.dataTable.cell-border tbody tr td:first-child {
border-left: 1px solid #ddd;
}
table.dataTable.cell-border tbody tr:first-child th,
table.dataTable.cell-border tbody tr:first-child td {
border-top: none;
}
table.dataTable.stripe tbody tr.odd, table.dataTable.display tbody tr.odd {
background-color: #f9f9f9;
}
table.dataTable.stripe tbody tr.odd.selected, table.dataTable.display tbody tr.odd.selected {
background-color: #acbad4;
}
table.dataTable.hover tbody tr:hover, table.dataTable.display tbody tr:hover {
background-color: #f6f6f6;
}
table.dataTable.hover tbody tr:hover.selected, table.dataTable.display tbody tr:hover.selected {
background-color: #aab7d1;
}
table.dataTable.order-column tbody tr > .sorting_1,
table.dataTable.order-column tbody tr > .sorting_2,
table.dataTable.order-column tbody tr > .sorting_3, table.dataTable.display tbody tr > .sorting_1,
table.dataTable.display tbody tr > .sorting_2,
table.dataTable.display tbody tr > .sorting_3 {
background-color: #fafafa;
}
table.dataTable.order-column tbody tr.selected > .sorting_1,
table.dataTable.order-column tbody tr.selected > .sorting_2,
table.dataTable.order-column tbody tr.selected > .sorting_3, table.dataTable.display tbody tr.selected > .sorting_1,
table.dataTable.display tbody tr.selected > .sorting_2,
table.dataTable.display tbody tr.selected > .sorting_3 {
background-color: #acbad5;
}
table.dataTable.display tbody tr.odd > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd > .sorting_1 {
background-color: #f1f1f1;
}
table.dataTable.display tbody tr.odd > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd > .sorting_2 {
background-color: #f3f3f3;
}
table.dataTable.display tbody tr.odd > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd > .sorting_3 {
background-color: whitesmoke;
}
table.dataTable.display tbody tr.odd.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_1 {
background-color: #a6b4cd;
}
table.dataTable.display tbody tr.odd.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_2 {
background-color: #a8b5cf;
}
table.dataTable.display tbody tr.odd.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_3 {
background-color: #a9b7d1;
}
table.dataTable.display tbody tr.even > .sorting_1, table.dataTable.order-column.stripe tbody tr.even > .sorting_1 {
background-color: #fafafa;
}
table.dataTable.display tbody tr.even > .sorting_2, table.dataTable.order-column.stripe tbody tr.even > .sorting_2 {
background-color: #fcfcfc;
}
table.dataTable.display tbody tr.even > .sorting_3, table.dataTable.order-column.stripe tbody tr.even > .sorting_3 {
background-color: #fefefe;
}
table.dataTable.display tbody tr.even.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_1 {
background-color: #acbad5;
}
table.dataTable.display tbody tr.even.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_2 {
background-color: #aebcd6;
}
table.dataTable.display tbody tr.even.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_3 {
background-color: #afbdd8;
}
table.dataTable.display tbody tr:hover > .sorting_1, table.dataTable.order-column.hover tbody tr:hover > .sorting_1 {
background-color: #eaeaea;
}
table.dataTable.display tbody tr:hover > .sorting_2, table.dataTable.order-column.hover tbody tr:hover > .sorting_2 {
background-color: #ececec;
}
table.dataTable.display tbody tr:hover > .sorting_3, table.dataTable.order-column.hover tbody tr:hover > .sorting_3 {
background-color: #efefef;
}
table.dataTable.display tbody tr:hover.selected > .sorting_1, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_1 {
background-color: #a2aec7;
}
table.dataTable.display tbody tr:hover.selected > .sorting_2, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_2 {
background-color: #a3b0c9;
}
table.dataTable.display tbody tr:hover.selected > .sorting_3, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_3 {
background-color: #a5b2cb;
}
table.dataTable.no-footer {
border-bottom: 1px solid #111;
}
table.dataTable.nowrap th, table.dataTable.nowrap td {
white-space: nowrap;
}
table.dataTable.compact thead th,
table.dataTable.compact thead td {
padding: 4px 17px 4px 4px;
}
table.dataTable.compact tfoot th,
table.dataTable.compact tfoot td {
padding: 4px;
}
table.dataTable.compact tbody th,
table.dataTable.compact tbody td {
padding: 4px;
}
table.dataTable th.dt-left,
table.dataTable td.dt-left {
text-align: left;
}
table.dataTable th.dt-center,
table.dataTable td.dt-center,
table.dataTable td.dataTables_empty {
text-align: center;
}
table.dataTable th.dt-right,
table.dataTable td.dt-right {
text-align: right;
}
table.dataTable th.dt-justify,
table.dataTable td.dt-justify {
text-align: justify;
}
table.dataTable th.dt-nowrap,
table.dataTable td.dt-nowrap {
white-space: nowrap;
}
table.dataTable thead th.dt-head-left,
table.dataTable thead td.dt-head-left,
table.dataTable tfoot th.dt-head-left,
table.dataTable tfoot td.dt-head-left {
text-align: left;
}
table.dataTable thead th.dt-head-center,
table.dataTable thead td.dt-head-center,
table.dataTable tfoot th.dt-head-center,
table.dataTable tfoot td.dt-head-center {
text-align: center;
}
table.dataTable thead th.dt-head-right,
table.dataTable thead td.dt-head-right,
table.dataTable tfoot th.dt-head-right,
table.dataTable tfoot td.dt-head-right {
text-align: right;
}
table.dataTable thead th.dt-head-justify,
table.dataTable thead td.dt-head-justify,
table.dataTable tfoot th.dt-head-justify,
table.dataTable tfoot td.dt-head-justify {
text-align: justify;
}
table.dataTable thead th.dt-head-nowrap,
table.dataTable thead td.dt-head-nowrap,
table.dataTable tfoot th.dt-head-nowrap,
table.dataTable tfoot td.dt-head-nowrap {
white-space: nowrap;
}
table.dataTable tbody th.dt-body-left,
table.dataTable tbody td.dt-body-left {
text-align: left;
}
table.dataTable tbody th.dt-body-center,
table.dataTable tbody td.dt-body-center {
text-align: center;
}
table.dataTable tbody th.dt-body-right,
table.dataTable tbody td.dt-body-right {
text-align: right;
}
table.dataTable tbody th.dt-body-justify,
table.dataTable tbody td.dt-body-justify {
text-align: justify;
}
table.dataTable tbody th.dt-body-nowrap,
table.dataTable tbody td.dt-body-nowrap {
white-space: nowrap;
}
table.dataTable,
table.dataTable th,
table.dataTable td {
box-sizing: content-box;
}
/*
* Control feature layout
*/
.dataTables_wrapper {
position: relative;
clear: both;
*zoom: 1;
zoom: 1;
}
.dataTables_wrapper .dataTables_length {
float: left;
}
.dataTables_wrapper .dataTables_filter {
float: right;
text-align: right;
}
.dataTables_wrapper .dataTables_filter input {
margin-left: 0.5em;
}
.dataTables_wrapper .dataTables_info {
clear: both;
float: left;
padding-top: 0.755em;
}
.dataTables_wrapper .dataTables_paginate {
float: right;
text-align: right;
padding-top: 0.25em;
}
.dataTables_wrapper .dataTables_paginate .paginate_button {
box-sizing: border-box;
display: inline-block;
min-width: 1.5em;
padding: 0.5em 1em;
margin-left: 2px;
text-align: center;
text-decoration: none !important;
cursor: pointer;
*cursor: hand;
color: #333 !important;
border: 1px solid transparent;
border-radius: 2px;
}
.dataTables_wrapper .dataTables_paginate .paginate_button.current, .dataTables_wrapper .dataTables_paginate .paginate_button.current:hover {
color: #333 !important;
border: 1px solid #979797;
background-color: white;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, white), color-stop(100%, #dcdcdc));
/* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, white 0%, #dcdcdc 100%);
/* Chrome10+,Safari5.1+ */
background: -moz-linear-gradient(top, white 0%, #dcdcdc 100%);
/* FF3.6+ */
background: -ms-linear-gradient(top, white 0%, #dcdcdc 100%);
/* IE10+ */
background: -o-linear-gradient(top, white 0%, #dcdcdc 100%);
/* Opera 11.10+ */
background: linear-gradient(to bottom, white 0%, #dcdcdc 100%);
/* W3C */
}
.dataTables_wrapper .dataTables_paginate .paginate_button.disabled, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:hover, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:active {
cursor: default;
color: #666 !important;
border: 1px solid transparent;
background: transparent;
box-shadow: none;
}
.dataTables_wrapper .dataTables_paginate .paginate_button:hover {
color: white !important;
border: 1px solid #111;
background-color: #585858;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #585858), color-stop(100%, #111));
/* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #585858 0%, #111 100%);
/* Chrome10+,Safari5.1+ */
background: -moz-linear-gradient(top, #585858 0%, #111 100%);
/* FF3.6+ */
background: -ms-linear-gradient(top, #585858 0%, #111 100%);
/* IE10+ */
background: -o-linear-gradient(top, #585858 0%, #111 100%);
/* Opera 11.10+ */
background: linear-gradient(to bottom, #585858 0%, #111 100%);
/* W3C */
}
.dataTables_wrapper .dataTables_paginate .paginate_button:active {
outline: none;
background-color: #2b2b2b;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #2b2b2b), color-stop(100%, #0c0c0c));
/* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
/* Chrome10+,Safari5.1+ */
background: -moz-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
/* FF3.6+ */
background: -ms-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
/* IE10+ */
background: -o-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
/* Opera 11.10+ */
background: linear-gradient(to bottom, #2b2b2b 0%, #0c0c0c 100%);
/* W3C */
box-shadow: inset 0 0 3px #111;
}
.dataTables_wrapper .dataTables_paginate .ellipsis {
padding: 0 1em;
}
.dataTables_wrapper .dataTables_processing {
position: absolute;
top: 50%;
left: 50%;
width: 100%;
height: 40px;
margin-left: -50%;
margin-top: -25px;
padding-top: 20px;
text-align: center;
font-size: 1.2em;
background-color: white;
background: -webkit-gradient(linear, left top, right top, color-stop(0%, rgba(255, 255, 255, 0)), color-stop(25%, rgba(255, 255, 255, 0.9)), color-stop(75%, rgba(255, 255, 255, 0.9)), color-stop(100%, rgba(255, 255, 255, 0)));
background: -webkit-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
background: -moz-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
background: -ms-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
background: -o-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
background: linear-gradient(to right, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
}
.dataTables_wrapper .dataTables_length,
.dataTables_wrapper .dataTables_filter,
.dataTables_wrapper .dataTables_info,
.dataTables_wrapper .dataTables_processing,
.dataTables_wrapper .dataTables_paginate {
color: #333;
}
.dataTables_wrapper .dataTables_scroll {
clear: both;
}
.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody {
*margin-top: -1px;
-webkit-overflow-scrolling: touch;
}
.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > thead > tr > th, .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > thead > tr > td, .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > tbody > tr > th, .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > tbody > tr > td {
vertical-align: middle;
}
.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > thead > tr > th > div.dataTables_sizing,
.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > thead > tr > td > div.dataTables_sizing, .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > tbody > tr > th > div.dataTables_sizing,
.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > tbody > tr > td > div.dataTables_sizing {
height: 0;
overflow: hidden;
margin: 0 !important;
padding: 0 !important;
}
.dataTables_wrapper.no-footer .dataTables_scrollBody {
border-bottom: 1px solid #111;
}
.dataTables_wrapper.no-footer div.dataTables_scrollHead table.dataTable,
.dataTables_wrapper.no-footer div.dataTables_scrollBody > table {
border-bottom: none;
}
.dataTables_wrapper:after {
visibility: hidden;
display: block;
content: "";
clear: both;
height: 0;
}
@media screen and (max-width: 767px) {
.dataTables_wrapper .dataTables_info,
.dataTables_wrapper .dataTables_paginate {
float: none;
text-align: center;
}
.dataTables_wrapper .dataTables_paginate {
margin-top: 0.5em;
}
}
@media screen and (max-width: 640px) {
.dataTables_wrapper .dataTables_length,
.dataTables_wrapper .dataTables_filter {
float: none;
text-align: center;
}
.dataTables_wrapper .dataTables_filter {
margin-top: 0.5em;
}
}
File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More