Compare commits

...
105 Commits
Author SHA1 Message Date
刘河 da899fd3db 守护进程 负载均衡 2019-02-03 00:54:43 +08:00
he liu 662a799f02 Update README.md 2019-02-01 14:52:30 +08:00
he liu 1a415475ce Update README.md 2019-02-01 14:42:48 +08:00
刘河 8115784059 截图 2019-02-01 10:57:51 +08:00
刘河 ffc4961d0c 截图 2019-02-01 10:56:08 +08:00
刘河 4f4ce71654 输出 2019-02-01 10:53:41 +08:00
刘河 bb7a12f5a2 no message 2019-02-01 10:43:48 +08:00
刘河 bdc7718dc3 readme、conf 2019-02-01 10:42:13 +08:00
刘河 ddeae71bc7 readme 2019-02-01 09:33:27 +08:00
刘河 21de0a0ada no message 2019-02-01 09:09:08 +08:00
刘河 c336bf94d8 命令行模式同步 2019-02-01 02:39:28 +08:00
刘河 4e6754deb9 no message 2019-02-01 02:07:50 +08:00
刘河 eccc221e67 https 、客户端与服务端连接优化 2019-02-01 02:06:30 +08:00
刘河 717028e5f1 Image 2019-01-31 16:41:16 +08:00
刘河 1e215d00a6 bug 2019-01-30 03:26:28 +08:00
刘河 f0c6eff23a Web api 2019-01-29 11:20:39 +08:00
刘河 b3dd70062b no message 2019-01-29 11:05:32 +08:00
刘河 34faa8788f readme 2019-01-29 11:02:01 +08:00
刘河 eccf1dbfb8 Bug修复+流量限制+带宽限制 2019-01-28 14:45:55 +08:00
刘河 2af7b3d737 help.html 2019-01-26 18:56:27 +08:00
刘河 40184141e8 readme 2019-01-26 18:45:00 +08:00
刘河 0b90bf3a18 很多修改 2019-01-26 17:27:28 +08:00
刘河 c34e5e1a7d dashboard 备注 客户端管理优化 多客户端支持 流量显示支持 热更新支持 404错误页支持 2019-01-25 12:10:12 +08:00
刘河 c533436c78 调整 2019-01-15 20:59:50 +08:00
刘河 cc90bcf4e9 no message 2019-01-13 22:13:21 +08:00
刘河 53e57ea70d 内存优化 2019-01-13 22:02:58 +08:00
刘河 72290275cc 内存优化 2019-01-13 20:49:45 +08:00
刘河 901048d1e6 Merge branch 'master' of https://github.com/cnlh/easyProxy 2019-01-13 01:44:20 +08:00
刘河 a94cef65a1 host修改 2019-01-13 01:43:58 +08:00
he liu 2ad50ebb46 Update README.md 2019-01-13 00:14:36 +08:00
刘河 851241a0c7 新功能+bug修复 2019-01-13 00:09:12 +08:00
刘河 bb882f348a 删除js文件 2019-01-12 01:39:11 +08:00
刘河 0ce6ab1e15 bug 2019-01-12 01:22:53 +08:00
刘河 a67cdff02a readme 2019-01-11 21:10:19 +08:00
刘河 26c7ba96af 错误处理 2019-01-11 21:07:49 +08:00
刘河 55b0c4b98b 修改 2019-01-11 18:10:37 +08:00
刘河 03aa58cd77 空写 2019-01-11 11:27:37 +08:00
刘河 478226e479 小bug 2019-01-11 10:44:13 +08:00
刘河 69ad2d3761 修改一些传递方法 2019-01-10 23:25:56 +08:00
刘河 f3435ebd40 小bug 2019-01-10 21:40:57 +08:00
刘河 61768ae0aa 锁机制暂时删除 2019-01-10 17:20:17 +08:00
刘河 6c3c09428e maxsize 2019-01-10 11:38:29 +08:00
刘河 12ec5d6b26 bug修复 2019-01-10 09:33:05 +08:00
刘河 60b5ea2959 运行名 2019-01-09 20:37:33 +08:00
刘河 1f61b99387 客户端服务端分离 2019-01-09 20:33:00 +08:00
刘河 dcd21f211d no message 2019-01-08 00:27:49 +08:00
刘河 05e66af647 Udp 多路复用 优化 2019-01-08 00:21:02 +08:00
刘河 7d8b1d02e1 调整 2019-01-07 01:52:54 +08:00
刘河 842e33018c readme 2019-01-06 03:34:56 +08:00
刘河 9bec5366a6 Tcp多路复用 2019-01-06 03:16:46 +08:00
刘河 ade3bb0c71 逻辑调整 2019-01-04 20:23:33 +08:00
刘河 1fb1ea08bd no message 2019-01-04 00:28:49 +08:00
刘河 ffbf1b274e Merge branch 'master' of https://github.com/cnlh/easyProxy 2019-01-04 00:24:54 +08:00
刘河 ec1bbad4be readme 2019-01-04 00:22:37 +08:00
刘河 9202db49b8 代码调整 2019-01-04 00:21:23 +08:00
he liu ed99973960 Update README.md 2019-01-03 05:36:49 +08:00
he liu a325d87bda Update README.md 2019-01-03 01:52:55 +08:00
刘河 11554aadfc Merge branch 'master' of https://github.com/cnlh/easyProxy 2019-01-03 01:46:38 +08:00
刘河 1d89e7dae2 加密传输,代码优化 2019-01-03 01:44:45 +08:00
he liu 53de6d5c06 Update README.md 2018-12-30 22:41:25 +08:00
he liu c678b29d63 Update README.md 2018-12-30 22:40:19 +08:00
刘河 4dad726129 站点保护功能,代码优化 2018-12-30 22:36:15 +08:00
he liu dc1520da1f Update README.md 2018-12-11 19:24:13 +08:00
刘河 0436a5163e 截图 2018-12-11 18:29:33 +08:00
刘河 184523b487 Web管理界面截图 2018-12-11 18:22:38 +08:00
he liu 10c7c49f4b Update .gitattributes 2018-12-11 16:54:21 +08:00
he liu e4ff7cdbf7 Create .gitattributes 2018-12-11 16:51:53 +08:00
he liu 61aab7340c Update README.md 2018-12-11 16:50:50 +08:00
刘河 abc30a9ad1 版本重构,加web管理方式 2018-12-11 16:37:12 +08:00
he liu 974f605ff6 Update README.md 2018-12-07 15:30:52 +08:00
he liu a8c539460c Update README.md 2018-12-07 15:29:18 +08:00
刘河 c35ce71e7c 客户端断线重连bug修复 2018-12-06 20:45:14 +08:00
he liu e6c2de7d9f Update README.md 2018-12-04 00:15:14 +08:00
刘河 34cb814d50 Udp隧道图 2018-12-03 23:28:13 +08:00
刘河 212d74bbc4 sock5验证加密、udp隧道、gzip、snnapy压缩 2018-12-03 23:03:25 +08:00
he liu 83eb8dcb3c Update README.md 2018-12-01 13:56:37 +08:00
he liu b61ff97681 Update README.md 2018-12-01 13:52:48 +08:00
刘河 ed694d1d1d 原理图 2018-12-01 13:48:46 +08:00
刘河 4994476af1 新增http代理模式 2018-12-01 02:38:29 +08:00
刘河 86deb2025f 连接bug修复 2018-11-30 01:13:41 +08:00
he liu a32010fcc0 Update README.md 2018-11-29 23:55:49 +08:00
he liu b220b5801c Update README.md 2018-11-29 23:51:16 +08:00
he liu 95e2db7a38 Update README.md 2018-11-29 23:38:42 +08:00
he liu 85366a87b4 Update README.md 2018-11-29 23:37:12 +08:00
he liu 311b298587 Update README.md 2018-11-29 23:36:22 +08:00
he liu 4cc550932b Update README.md 2018-11-29 23:05:43 +08:00
he liu a55df99199 Update README.md 2018-11-29 19:59:10 +08:00
刘河 3ea895feb5 添加多种模式 2018-11-29 19:55:24 +08:00
he liu 2463116b37 Update README.md 2018-11-27 16:50:23 +08:00
刘河 f0abcd98e4 添加gzip压缩 2018-11-27 16:49:13 +08:00
刘河 ef9bfa3290 修复转换bug 2018-11-09 00:14:58 +08:00
刘河 5f8df0d581 配置更改 2018-11-08 23:09:47 +08:00
cnlh 278292a51a Update README.md 2018-11-08 23:08:47 +08:00
cnlh d5e734d67e Update README.md 2018-11-08 20:02:58 +08:00
刘河 848c44b130 自动替换跨站点url 2018-11-08 19:53:30 +08:00
刘河 079d3dedad 客户端错误处理机制修改 2018-11-06 16:43:06 +08:00
cnlh 9ebb7c3209 Update README.md 2018-11-06 14:28:10 +08:00
刘河 d432e63eec 解决客户端内存泄漏问题 2018-11-05 20:39:31 +08:00
cnlh 2c9906e91c Update README.md 2018-11-05 01:40:56 +08:00
cnlh 9baddc51e1 Update README.md 2018-11-04 23:39:42 +08:00
cnlh a1ccbcde0e Update README.md 2018-11-04 23:27:06 +08:00
cnlh e0cab323ab Update README.md 2018-11-04 23:19:58 +08:00
刘河 ec7d181d5a 初始化 2018-11-04 23:19:22 +08:00
cnlh 952ffb0ddc Update README.md 2018-11-04 23:17:45 +08:00
cnlh f2d8678681 Update README.md 2018-11-04 22:54:27 +08:00
70 changed files with 27516 additions and 198 deletions
+3
View File
@@ -0,0 +1,3 @@
*.js linguist-language=golang
*.css linguist-language=golang
*.html linguist-language=golang
+17 -197
View File
@@ -1,201 +1,21 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
MIT License
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Copyright (c) 2018
1. Definitions.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+565 -1
View File
@@ -1,2 +1,566 @@
# easyProxy
简单、轻量级http代理服务器,主要应用于内网穿透
![](https://img.shields.io/github/stars/cnlh/easyProxy.svg) ![](https://img.shields.io/github/forks/cnlh/easyProxy.svg) ![](https://img.shields.io/github/license/cnlh/easyProxy.svg)
easyProxy是一款轻量级、高性能、功能最为强大的**内网穿透**代理服务器。目前支持**tcp、udp流量转发**,可支持任何tcp、udp上层协议(访问内网网站、本地支付接口调试、ssh访问、远程桌面,内网dns解析等等……),此外还**支持内网http代理、内网socks5代理**,可实现在非内网环境下如同使用vpn一样访问内网资源和设备的效果。
目前市面上提供类似服务的有花生壳、TeamView、GoToMyCloud等等,但要使用第三方的公网服务器就必须为第三方付费,并且这些服务都有各种各样的限制,此外,由于数据包会流经第三方,因此对数据安全也是一大隐患。
go语言编写,无第三方依赖,各个平台都已经编译在release中。
## 背景
![image](https://github.com/cnlh/easyProxy/blob/master/image/web.png?raw=true)
1. web管理模式,可配置多条tcp、udp隧道,多个域名代理等等----> [web管理模式](#web管理模式)
2. 想在外网通过ssh连接内网的机器,做云服务器到内网服务器端口的映射,或者做微信公众号开发、小程序开发等---->[tcp隧道模式](#tcp隧道模式)
3. 在非内网环境下使用内网dns,或者需要通过udp访问内网机器等---->[udp隧道模式](#udp隧道模式)
4. 在外网使用HTTP代理访问内网站点---->[http代理模式](#http代理模式)
5. 搭建一个内网穿透ss,在外网如同使用内网vpn一样访问内网资源或者设备----> [socks5代理模式](#socks5代理模式)
## 目录
* [安装](#安装)
* [编译安装](#源码安装)
* [release安装](#release安装)
* [web管理](#web管理模式)(多隧道时推荐)
* [启动](#启动)
* [服务端测试](#服务端测试)
* [服务端启动](#服务端启动)
* [web管理](#web管理)
* [客户端启动](#客户端启动)
* [服务端停止或重启](#服务端停止或重启)
* [配置文件说明](#服务端配置文件)
* [详细使用说明](#详细说明)
* [http|https域名解析](#域名解析)
* [tcp隧道](#tcp隧道)
* [udp隧道](#udp隧道)
* [socks5代理](#socks5代理)
* [http正向代理](#http正向代理)
* [使用https](#使用https)
* [与nginx配合](#与nginx配合)
* [关闭http|https代理](#关闭代理)
* 单隧道模式及介绍
* [tcp隧道模式](#tcp隧道模式)
* [udp隧道模式](#udp隧道模式)
* [socks5代理模式](#socks5代理模式)
* [http代理模式](#http代理模式)
* [相关功能](#相关功能)
* [数据压缩支持](#数据压缩支持)
* [站点密码保护](#站点保护)
* [加密传输](#加密传输)
* [host修改](#host修改)
* [自定义header](#自定义header)
* [自定义404页面](#404页面配置)
* [流量限制](#流量限制)
* [带宽限制](#带宽限制)
* [负载均衡](#负载均衡)
* [守护进程](#守护进程)
* [相关说明](#相关说明)
* [流量统计](#流量统计)
* [热更新支持](#热更新支持)
* [获取用户真实ip](#获取用户真实ip)
* [客户端地址显示](#客户端地址显示)
* [简单的性能测试](#简单的性能测试)
* [qps](#qps)
* [速度测试](#速度测试)
* [内存和cpu](#内存和cpu)
* [额外消耗连接数](#额外消耗连接数)
* [webAPI](#webAPI)
* [客户端](#客户端)
* [域名代理](#域名代理)
* [其他代理](#其他代理)
## 安装
### release安装
> https://github.com/cnlh/easyProxy/releases
下载对应的系统版本即可,服务端和客户端是单独的,go语言开发,无需任何第三方依赖
### 源码安装
- 安装源码(另有snappy、beego包)
> go get github.com/cnlh/easyProxy
- 编译
> go build cmd/server/proxy_server.go
> go build cmd/client/proxy_client.go
## web管理模式
![image](https://github.com/cnlh/easyProxy/blob/master/image/web2.png?raw=true)
### 介绍
可在网页上配置和管理各个tcp、udp隧道、内网站点代理,http、https解析等,功能极为强大,操作也非常方便。
**提示:使用web模式时,服务端执行文件必须在项目根目录,否则无法正确加载配置文件**
### 启动
#### 服务端测试
```
./proxy_server test
```
如有错误请及时修改配置文件,无错误可继续进行下去
#### 服务端启动
```
./proxy_server start
```
如果无需daemon运行,去掉start即可
#### web管理
进入web界面,公网ip:web界面端口(默认8080),密码默认为123
进入web管理界面,有详细的说明
#### 客户端启动
```
./proxy_server -server=ip:port -vkey=web界面中显示的密钥
```
#### 服务端停止或重启
如果是daemon启动
```
./proxy_server stop|restart
```
### 服务端配置文件
- /conf/app.conf
名称 | 含义
---|---
httpport | web管理端口
password | web界面管理密码
hostPort | 域名代理模式监听端口
tcpport | 服务端客户端通信端口
pemPath | ssl certFile绝对路径
keyPath | ssl keyFile绝对路径
httpsProxyPort | https代理监听端口
httpProxyPort | http代理监听端口
### 详细说明
#### 域名解析
**适用范围:** 小程序开发、微信公众号开发、产品演示
**假设场景:**
- 有一个域名proxy.com,有一台公网机器ip为1.1.1.1
- 两个内网开发站点127.0.0.1:81,127.0.0.1:82
- 想通过(http|https://)a.proxy.com访问127.0.0.1:81,通过(http|https://)b.proxy.com访问127.0.0.1:82
- 例如配置文件中tcpport为8284
**使用步骤**
- 将*.proxy.com解析到公网服务器1.1.1.1
- 在客户端管理中创建一个客户端,记录下验证密钥
- 点击该客户端的域名管理,添加两条规则规则:1、域名:a.proxy.com,内网目标:127.0.0.1:81,2、域名:b.proxy.com,内网目标:127.0.0.1:82
- 内网客户端运行
```
./proxy_client server=1.1.1.1:8284 -vkey=客户端的密钥
```
现在访问(http|https://)a.proxy.com,b.proxy.com即可成功
**https:** 如需使用https请在配置文件中将https端口设置为443,和将对应的证书文件路径添加到配置文件中
#### tcp隧道
**适用范围:** ssh、远程桌面等tcp连接场景
**假设场景:**
想通过访问公网服务器1.1.1.1的8001端口,连接内网机器10.1.50.101的22端口,实现ssh连接,例如配置文件中tcpport为8284
**使用步骤**
- 在客户端管理中创建一个客户端,记录下验证密钥
- -内网客户端运行
```
./proxy_client server=1.1.1.1:8284 -vkey=客户端的密钥
```
- 在该客户端隧道管理中添加一条tcp隧道,填写监听的端口(8001)、内网目标ip和目标端口(10.1.50.101:22),选择压缩方式,保存。
- 访问公网服务器ip(127.0.0.1),填写的监听端口(8001),相当于访问内网ip(10.1.50.101):目标端口(22),例如:ssh -p 8001 root@127.0.0.1
#### udp隧道
**适用范围:** 内网dns解析等udp连接场景
**假设场景:**
内网有一台dns(10.1.50.102:53),在非内网环境下想使用该dns,公网服务器为1.1.1.1,例如配置文件中tcpport为8284
**使用步骤**
- 在客户端管理中创建一个客户端,记录下验证密钥
- -内网客户端运行
```
./proxy_client server=1.1.1.1:8284 -vkey=客户端的密钥
```
- 在该客户端的隧道管理中添加一条udp隧道,填写监听的端口(53)、内网目标ip和目标端口(10.1.50.102:53),选择压缩方式,保存。
- 修改本机dns为127.0.0.1,则相当于使用10.1.50.202作为dns服务器
#### socks5代理
**适用范围:** 在外网环境下如同使用vpn一样访问内网设备或者资源
**假设场景:**
想将公网服务器1.1.1.1的8003端口作为socks5代理,达到访问内网任意设备或者资源的效果,例如配置文件中tcpport为8284
**使用步骤**
- 在客户端管理中创建一个客户端,记录下验证密钥
- -内网客户端运行
```
./proxy_client server=1.1.1.1:8284 -vkey=客户端的密钥
```
- 在该客户端隧道管理中添加一条socks5代理,填写监听的端口(8003),验证用户名和密码自行选择(建议先不填,部分客户端不支持,proxifer支持),选择压缩方式,保存。
- 在外网环境的本机配置socks5代理,ip为公网服务器ip(127.0.0.1),端口为填写的监听端口(8003),即可畅享内网了
#### http正向代理
**适用范围:** 在外网环境下使用http代理访问内网站点
**假设场景:**
想将公网服务器1.1.1.1的8004端口作为http代理,访问内网网站,例如配置文件中tcpport为8284
**使用步骤**
- 在客户端管理中创建一个客户端,记录下验证密钥
- -内网客户端运行
```
./proxy_client server=1.1.1.1:8284 -vkey=客户端的密钥
```
- 在该客户端隧道管理中添加一条http代理,填写监听的端口(8004),选择压缩方式,保存。
- 在外网环境的本机配置http代理,ip为公网服务器ip(127.0.0.1),端口为填写的监听端口(8004),即可访问了
### 使用https
在配置文件中将httpsProxyPort设置为443或者其他你想配置的端口,和将对应的证书文件路径添加到配置文件中,即可畅销https了
### 与nginx配合
有时候我们还需要在云服务器上运行https来保证静态文件缓存等,本代理可和nginx配合使用,在配置文件中将httpProxyPort设置为非80端口,并在nginx中配置代理,例
```
server {
listen 80;
server_name *.proxy.com;
location / {
proxy_pass http://127.0.0.1:8024;
}
}
```
如需使用https也可在nginx监听443端口并配置ssl,再设置如上配置即可,例如。
```
server {
listen 443;
server_name *.proxy.com;
ssl on;
ssl_certificate certificate.crt;
ssl_certificate_key private.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://127.0.0.1:8024;
}
}
```
### 关闭代理
如需关闭http代理可在配置文件中将httpProxyPort设置为空,如需关闭https代理可在配置文件中将httpsProxyPort设置为空。
## tcp隧道模式
### 场景及原理
较为适用于处理tcp连接,例如ssh,同时也适用于http等,访问服务端的8024端口相当于访问内网10.1.50.202机器的4000端口,构成如下所示的隧道。
![image](https://github.com/cnlh/easyProxy/blob/master/image/tcp.png?raw=true)
例如:
**背景:**
- 内网机器10.1.50.203提供了web服务80端口
- 有VPS一个,公网IP:123.206.77.88
**需求:**
在家里能够通过访问VPS的8024端口访问到内网机器A的80端口
### 使用
- 服务端
```
./proxy_server -mode=tunnelServer -vkey=DKibZF5TXvic1g3kY -tcpport=8284 -httpport=8024 -target=10.1.50.203:80
```
名称 | 含义
---|---
mode | 运行模式
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
httpport | 外部访问端口
target | 目标地址,格式如上
- 客户端
```
./proxy_client -server=ip:port -vkey=DKibZF5TXvic1g3kY
```
- 与nginx配合实现访问a.ourcauc.com等同访问10.1.50.203:80效果,将该域名解析道云服务器,nginx配置
```
server {
listen 80;
server_name a.ourcauc.com;
location / {
proxy_pass http://127.0.0.1:8024;
}
}
```
## udp隧道模式
### 场景及原理
**背景**
- 内网机器A提供了DNS解析服务,10.1.50.210:53端口
- 有VPS一个,公网IP:123.206.77.88
**需求:**
在家里能够通过设置本地dns为123.206.77.88,使用内网机器A进行域名解析服务.
访问vps的53端口相当于访问10.1.50.210的53端口,构成如下所示的隧道。
![image](https://github.com/cnlh/easyProxy/blob/master/image/udp.png?raw=true)
### 使用
- 服务端
```
./proxy_server -mode=udpServer -vkey=DKibZF5TXvic1g3kY -tcpport=8284 -httpport=53 -target=10.1.50.210:53
```
名称 | 含义
---|---
mode | 运行模式
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
httpport | 公网vps的访问端口
target | 目标地址,格式如上
- 客户端
```
./proxy_client -server=ip:port -vkey=DKibZF5TXvic1g3kY
```
## socks5代理模式
### 场景及原理
**原理**
主要用于socks5代理,也就是和ss类似,不过是代理内网。使用此模式时,可在非内网环境下配置本机的socks5代理(服务器ip、sock5代理端口),即可实现socks5代理,达到访问内网的网站的效果,配合proxifier等全局代理软件,即可如同使用内网vpn一样,访问内网网站,通过ssh连接内网机器等等……。
![image](https://github.com/cnlh/easyProxy/blob/master/image/sock5.png?raw=true)
### 使用
- 服务端
```
./proxy_server -mode=socks5Server -vkey=DKibZF5TXvic1g3kY -tcpport=8284 -httpport=8024
```
名称 | 含义
---|---
mode | 运行模式
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
httpport | 代理的http端口(socks5连接端口)
u | 验证的用户名
p | 验证的密码
**说明**:用户名和密码验证模式,仅部分socks5客户端支持,例如proxifier。命令行执行加上,web管理模式中可单独配置
```
-u=user -p=password
```
- 客户端
```
./proxy_client -server=ip:port -vkey=DKibZF5TXvic1g3kY
```
- 需要使用内网代理的机器
```
配置socks5代理即可,ip为外网服务器ip,端口为httpport,即可在外网环境使用内网啦!也可使用proxifier等全局代理软件。
```
如果设置了用户名和密码,记得填上用户名和密码(仅部分客户端支持密码验证)
## http代理模式
### 场景及原理
主要用于HTTP代理,区别也就是HTTP代理和sock5代理的区别。使用此模式时,可在非内网环境下配置本机的HTTP代理(服务器ip、HTTP代理端口),即可实现HTTP代理,达到访问内网的网站的效果。
![image](https://github.com/cnlh/easyProxy/blob/master/image/httpProxy.png?raw=true)
### 使用
- 服务端
```
./proxy_server -mode=httpProxyServer -vkey=DKibZF5TXvic1g3kY -tcpport=8284 -httpport=8024
```
名称 | 含义
---|---
mode | 运行模式
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
httpport | http代理连接端口
authip | 免验证ip,适用于web api
- 客户端
```
./proxy_client -server=ip:port -vkey=DKibZF5TXvic1g3kY
```
- 需要使用内网代理的机器
```
配置HTTP代理即可,ip为外网服务器ip,端口为httpport,即可在外网环境访问内网啦!
```
## 相关功能
### 数据压缩支持
由于是内网穿透,内网客户端与服务端之间的隧道存在大量的数据交换,为节省流量,加快传输速度,由此本程序支持SNNAPY形式的压缩。
- 所有模式均支持数据压缩,可以与加密同时使用
- 开启此功能会增加cpu和内存消耗
- 在server端加上参数 -compress=snappy(或在web管理中设置)
```
-compress=snappy
```
### 加密传输
如果公司内网防火墙对外网访问进行了流量识别与屏蔽,例如禁止了ssh协议等,通过设置 配置文件,将服务端与客户端之间的通信内容加密传输,将会有效防止流量被拦截。
- 开启此功能会增加cpu和内存消耗
- 在server端加上参数 -crypt=true(或在web管理中设置)
```
-crypt=true
```
### 站点保护
域名代理模式所有客户端共用一个http服务端口,在知道域名后任何人都可访问,一些开发或者测试环境需要保密,所以可以设置用户名和密码,easyProxy将通过 Http Basic Auth 来保护,访问时需要输入正确的用户名和密码。
- web管理中可配置
### host修改
由于内网站点需要的host可能与公网域名不一致,域名代理支持host修改功能,即修改request的header中的host字段。
**使用方法:在web管理中设置**
### 自定义header
支持对header进行新增或者修改,以配合服务的需要
### 404页面配置
支持域名解析模式的自定义404页面,修改/web/static/page/error.html中内容即可,暂不支持静态文件等内容
### 流量限制
支持客户端级流量限制,当该客户端入口流量与出口流量达到设定的总量后会拒绝服务
,域名代理会返回404页面,其他代理会拒绝连接
### 带宽限制
支持客户端级带宽限制,带宽计算方式为入口和出口总和,权重均衡
### 负载均衡
本代理支持域名解析模式的负载均衡,在web域名添加或者编辑中内网目标分行填写多个目标即可实现轮训级别的负载均衡
### 守护进程
本代理支持守护进程,使用示例如下,服务端客户端所有模式通用,支持linux,darwin,windows。
```
./proxy_(client|server) start|stop|restart xxxxxx
```
```
proxy_(client|server).exe start|stop|restart xxxxxx
```
## 相关说明
### 获取用户真实ip
在域名代理模式中,可以通过request请求 header 中的 X-Forwarded-For 和 X-Real-IP 来获取用户真实 IP。
**本代理前会在每一个请求中添加了这两个 header。**
### 热更新支持
在web管理中的修改将实时使用,无需重启客户端或者服务端
### 客户端地址显示
在web管理中将显示客户端的连接地址
### 流量统计
可统计显示每个代理使用的流量,由于压缩和加密等原因,会和实际环境中的略有差异
## 简单性能测试
### qps
![image](https://github.com/cnlh/easyProxy/blob/master/image/qps.png?raw=true)
### 速度测试
**测试环境:** 1M带宽云服务器,理论125kb/s,带宽与代理无关,与服务器关系较大。
![image](https://github.com/cnlh/easyProxy/blob/master/image/speed.png?raw=true)
### 内存和cpu
**1000次性能测试后**
![image](https://github.com/cnlh/easyProxy/blob/master/image/cpu1.png?raw=true)
**启动时**
![image](https://github.com/cnlh/easyProxy/blob/master/image/cpu2.png?raw=true)
### 额外消耗连接数
为了最大化的提升效率和并发,客户端与服务端之间仅两条tcp连接,减少建立连接的时间消耗和多余tcp连接对机器性能的影响。
## webAPI
为方便第三方扩展,在web模式下可利用webAPI进行相关操作,详情见
[webAPI文档](https://github.com/cnlh/easyProxy/wiki/webAPI%E6%96%87%E6%A1%A3)
+293
View File
@@ -0,0 +1,293 @@
package bridge
import (
"errors"
"github.com/cnlh/easyProxy/utils"
"net"
"sync"
"time"
)
type Client struct {
tunnel *utils.Conn
signal *utils.Conn
linkMap map[int]*utils.Link
linkStatusMap map[int]bool
stop chan bool
sync.RWMutex
}
type Bridge struct {
TunnelPort int //通信隧道端口
listener *net.TCPListener //server端监听
Client map[int]*Client
RunList map[int]interface{} //运行中的任务
lock sync.Mutex
tunnelLock sync.Mutex
clientLock sync.Mutex
}
func NewTunnel(tunnelPort int, runList map[int]interface{}) *Bridge {
t := new(Bridge)
t.TunnelPort = tunnelPort
t.Client = make(map[int]*Client)
t.RunList = runList
return t
}
func (s *Bridge) StartTunnel() error {
var err error
s.listener, err = net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), s.TunnelPort, ""})
if err != nil {
return err
}
go s.tunnelProcess()
return nil
}
//tcp server
func (s *Bridge) tunnelProcess() error {
var err error
for {
conn, err := s.listener.Accept()
if err != nil {
utils.Println(err)
continue
}
go s.cliProcess(utils.NewConn(conn))
}
return err
}
//验证失败,返回错误验证flag,并且关闭连接
func (s *Bridge) verifyError(c *utils.Conn) {
c.Write([]byte(utils.VERIFY_EER))
c.Conn.Close()
}
func (s *Bridge) cliProcess(c *utils.Conn) {
c.SetReadDeadline(5)
var buf []byte
var err error
if buf, err = c.ReadLen(32); err != nil {
c.Close()
return
}
//验证
id, err := utils.GetCsvDb().GetIdByVerifyKey(string(buf), c.Conn.RemoteAddr().String())
if err != nil {
utils.Println("当前客户端连接校验错误,关闭此客户端:", c.Conn.RemoteAddr())
s.verifyError(c)
return
}
//做一个判断 添加到对应的channel里面以供使用
if flag, err := c.ReadFlag(); err == nil {
s.typeDeal(flag, c, id)
}
return
}
func (s *Bridge) closeClient(id int) {
s.clientLock.Lock()
defer s.clientLock.Unlock()
if v, ok := s.Client[id]; ok {
v.signal.WriteClose()
delete(s.Client, id)
}
}
//tcp连接类型区分
func (s *Bridge) typeDeal(typeVal string, c *utils.Conn, id int) {
switch typeVal {
case utils.WORK_MAIN:
//客户端已经存在,下线
s.clientLock.Lock()
if _, ok := s.Client[id]; ok {
s.clientLock.Unlock()
s.closeClient(id)
} else {
s.clientLock.Unlock()
}
s.clientLock.Lock()
s.Client[id] = &Client{
linkMap: make(map[int]*utils.Link),
stop: make(chan bool),
linkStatusMap: make(map[int]bool),
}
utils.Printf("客户端%d连接成功,地址为:%s", id, c.Conn.RemoteAddr())
s.Client[id].signal = c
s.clientLock.Unlock()
go s.GetStatus(id)
case utils.WORK_CHAN:
s.clientLock.Lock()
if v, ok := s.Client[id]; ok {
s.clientLock.Unlock()
v.tunnel = c
} else {
s.clientLock.Unlock()
return
}
go s.clientCopy(id)
}
c.SetAlive()
return
}
//等待
func (s *Bridge) waitStatus(clientId, id int) (bool) {
ticker := time.NewTicker(time.Millisecond * 100)
stop := time.After(time.Second * 10)
for {
select {
case <-ticker.C:
s.clientLock.Lock()
if v, ok := s.Client[clientId]; ok {
s.clientLock.Unlock()
v.Lock()
if vv, ok := v.linkStatusMap[id]; ok {
ticker.Stop()
v.Unlock()
return vv
}
v.Unlock()
} else {
s.clientLock.Unlock()
}
case <-stop:
return false
}
}
return false
}
func (s *Bridge) SendLinkInfo(clientId int, link *utils.Link) (tunnel *utils.Conn, err error) {
s.clientLock.Lock()
if v, ok := s.Client[clientId]; ok {
s.clientLock.Unlock()
v.signal.SendLinkInfo(link)
if err != nil {
utils.Println("send error:", err, link.Id)
s.DelClient(clientId)
return
}
if v.tunnel == nil {
err = errors.New("tunnel获取错误")
return
} else {
tunnel = v.tunnel
}
v.Lock()
v.linkMap[link.Id] = link
v.Unlock()
if !s.waitStatus(clientId, link.Id) {
err = errors.New("连接失败")
return
}
} else {
s.clientLock.Unlock()
err = errors.New("客户端未连接")
}
return
}
//得到一个tcp隧道
func (s *Bridge) GetTunnel(id int, en, de int, crypt, mux bool) (conn *utils.Conn, err error) {
s.clientLock.Lock()
defer s.clientLock.Unlock()
if v, ok := s.Client[id]; !ok {
err = errors.New("客户端未连接")
} else {
conn = v.tunnel
}
return
}
//得到一个通信通道
func (s *Bridge) GetSignal(id int) (conn *utils.Conn, err error) {
s.clientLock.Lock()
defer s.clientLock.Unlock()
if v, ok := s.Client[id]; !ok {
err = errors.New("客户端未连接")
} else {
conn = v.signal
}
return
}
//删除通信通道
func (s *Bridge) DelClient(id int) {
s.closeClient(id)
}
func (s *Bridge) verify(id int) bool {
for k := range s.RunList {
if k == id {
return true
}
}
return false
}
func (s *Bridge) GetStatus(clientId int) {
s.clientLock.Lock()
client := s.Client[clientId]
s.clientLock.Unlock()
if client == nil {
return
}
for {
if id, status, err := client.signal.GetConnStatus(); err != nil {
s.closeClient(clientId)
return
} else {
client.Lock()
client.linkStatusMap[id] = status
client.Unlock()
}
}
}
func (s *Bridge) clientCopy(clientId int) {
s.clientLock.Lock()
client := s.Client[clientId]
s.clientLock.Unlock()
for {
if id, err := client.tunnel.GetLen(); err != nil {
s.closeClient(clientId)
utils.Println("读取msg id 错误", err, id)
break
} else {
client.Lock()
if link, ok := client.linkMap[id]; ok {
client.Unlock()
if content, err := client.tunnel.GetMsgContent(link); err != nil {
utils.PutBufPoolCopy(content)
s.closeClient(clientId)
utils.Println("read msg content error", err, "close client")
break
} else {
if len(content) == len(utils.IO_EOF) && string(content) == utils.IO_EOF {
if link.Conn != nil {
link.Conn.Close()
}
} else {
if link.UdpListener != nil && link.UdpRemoteAddr != nil {
link.UdpListener.WriteToUDP(content, link.UdpRemoteAddr)
} else {
link.Conn.Write(content)
}
link.Flow.Add(0, len(content))
}
utils.PutBufPoolCopy(content)
}
} else {
client.Unlock()
continue
}
}
}
}
+179
View File
@@ -0,0 +1,179 @@
package client
import (
"github.com/cnlh/easyProxy/utils"
"net"
"sync"
"time"
)
type TRPClient struct {
svrAddr string
linkMap map[int]*utils.Link
stop chan bool
tunnel *utils.Conn
sync.Mutex
vKey string
}
//new client
func NewRPClient(svraddr string, vKey string) *TRPClient {
return &TRPClient{
svrAddr: svraddr,
linkMap: make(map[int]*utils.Link),
stop: make(chan bool),
tunnel: nil,
Mutex: sync.Mutex{},
vKey: vKey,
}
}
//start
func (s *TRPClient) Start() error {
s.NewConn()
return nil
}
//新建
func (s *TRPClient) NewConn() {
retry:
conn, err := net.Dial("tcp", s.svrAddr)
if err != nil {
utils.Println("连接服务端失败,五秒后将重连")
time.Sleep(time.Second * 5)
goto retry
return
}
s.processor(utils.NewConn(conn))
}
//处理
func (s *TRPClient) processor(c *utils.Conn) {
c.SetAlive()
if _, err := c.Write([]byte(utils.Getverifyval(s.vKey))); err != nil {
return
}
c.WriteMain()
go s.dealChan()
for {
flags, err := c.ReadFlag()
if err != nil {
utils.Println("服务端断开,正在重新连接")
break
}
switch flags {
case utils.VERIFY_EER:
utils.Fatalf("vKey:%s不正确,服务端拒绝连接,请检查", s.vKey)
case utils.NEW_CONN:
if link, err := c.GetLinkInfo(); err != nil {
break
} else {
s.Lock()
s.linkMap[link.Id] = link
s.Unlock()
go s.linkProcess(link, c)
}
case utils.RES_CLOSE:
utils.Fatalln("该vkey被另一客户连接")
case utils.RES_MSG:
utils.Println("服务端返回错误,重新连接")
break
default:
utils.Println("无法解析该错误,重新连接")
break
}
}
s.stop <- true
s.linkMap = make(map[int]*utils.Link)
go s.NewConn()
}
func (s *TRPClient) linkProcess(link *utils.Link, c *utils.Conn) {
//与目标建立连接
server, err := net.DialTimeout(link.ConnType, link.Host, time.Second*3)
if err != nil {
c.WriteFail(link.Id)
utils.Println("connect to ", link.Host, "error:", err)
return
}
c.WriteSuccess(link.Id)
link.Conn = utils.NewConn(server)
for {
buf := utils.BufPoolCopy.Get().([]byte)
if n, err := server.Read(buf); err != nil {
utils.PutBufPoolCopy(buf)
s.tunnel.SendMsg([]byte(utils.IO_EOF), link)
break
} else {
if _, err := s.tunnel.SendMsg(buf[:n], link); err != nil {
utils.PutBufPoolCopy(buf)
c.Close()
break
}
utils.PutBufPoolCopy(buf)
//if link.ConnType == utils.CONN_UDP {
// c.Close()
// break
//}
}
}
s.Lock()
delete(s.linkMap, link.Id)
s.Unlock()
}
//隧道模式处理
func (s *TRPClient) dealChan() {
var err error
//创建一个tcp连接
conn, err := net.Dial("tcp", s.svrAddr)
if err != nil {
utils.Println("connect to ", s.svrAddr, "error:", err)
return
}
//验证
if _, err := conn.Write([]byte(utils.Getverifyval(s.vKey))); err != nil {
utils.Println("connect to ", s.svrAddr, "error:", err)
return
}
//默认长连接保持
s.tunnel = utils.NewConn(conn)
s.tunnel.SetAlive()
//写标志
s.tunnel.WriteChan()
go func() {
for {
if id, err := s.tunnel.GetLen(); err != nil {
utils.Println("get msg id error")
break
} else {
s.Lock()
if v, ok := s.linkMap[id]; ok {
s.Unlock()
if content, err := s.tunnel.GetMsgContent(v); err != nil {
utils.Println("get msg content error:", err, id)
break
} else {
if len(content) == len(utils.IO_EOF) && string(content) == utils.IO_EOF {
v.Conn.Close()
} else if v.Conn != nil {
v.Conn.Write(content)
}
}
} else {
s.Unlock()
}
}
}
}()
select {
case <-s.stop:
}
}
+33
View File
@@ -0,0 +1,33 @@
package main
import (
"flag"
"github.com/cnlh/easyProxy/client"
"github.com/cnlh/easyProxy/utils"
_ "github.com/cnlh/easyProxy/utils"
"strings"
)
const VERSION = "v0.0.13"
var (
serverAddr = flag.String("server", "", "服务器地址ip:端口")
verifyKey = flag.String("vkey", "", "验证密钥")
logType = flag.String("log", "stdout", "日志输出方式(stdout|file)")
)
func main() {
flag.Parse()
utils.InitDaemon("client")
if *logType == "stdout" {
utils.InitLogFile("client", true)
} else {
utils.InitLogFile("client", false)
}
stop := make(chan int)
for _, v := range strings.Split(*verifyKey, ",") {
utils.Println("客户端启动,连接:", *serverAddr, " 验证令牌:", v)
go client.NewRPClient(*serverAddr, v).Start()
}
<-stop
}
+81
View File
@@ -0,0 +1,81 @@
package main
import (
"flag"
"github.com/astaxie/beego"
"github.com/cnlh/easyProxy/server"
"github.com/cnlh/easyProxy/utils"
_ "github.com/cnlh/easyProxy/web/routers"
"os"
)
const VERSION = "v0.0.13"
var (
TcpPort = flag.Int("tcpport", 0, "客户端与服务端通信端口")
httpPort = flag.Int("httpport", 8024, "对外监听的端口")
rpMode = flag.String("mode", "webServer", "启动模式")
tunnelTarget = flag.String("target", "127.0.0.1:80", "远程目标")
VerifyKey = flag.String("vkey", "", "验证密钥")
u = flag.String("u", "", "验证用户名(socks5和web)")
p = flag.String("p", "", "验证密码(socks5和web)")
compress = flag.String("compress", "", "数据压缩方式(snappy)")
crypt = flag.String("crypt", "false", "是否加密(true|false)")
logType = flag.String("log", "stdout", "日志输出方式(stdout|file)")
)
func main() {
flag.Parse()
var test bool
if len(os.Args) > 1 && os.Args[1] == "test" {
test = true
}
utils.InitDaemon("server")
if *logType == "stdout" || test {
utils.InitLogFile("server", true)
} else {
utils.InitLogFile("server", false)
}
task := &utils.Tunnel{
TcpPort: *httpPort,
Mode: *rpMode,
Target: *tunnelTarget,
Config: &utils.Config{
U: *u,
P: *p,
Compress: *compress,
Crypt: utils.GetBoolByStr(*crypt),
},
Flow: &utils.Flow{},
UseClientCnf: false,
}
if *VerifyKey != "" {
c := &utils.Client{
Id: 0,
VerifyKey: *VerifyKey,
Addr: "",
Remark: "",
Status: true,
IsConnect: false,
Cnf: &utils.Config{},
Flow: &utils.Flow{},
}
c.Cnf.CompressDecode, c.Cnf.CompressEncode = utils.GetCompressType(c.Cnf.Compress)
server.CsvDb.Clients[0] = c
task.Client = c
}
if *TcpPort == 0 {
p, err := beego.AppConfig.Int("tcpport")
if err == nil && *rpMode == "webServer" {
*TcpPort = p
} else {
*TcpPort = 8284
}
}
utils.Println("服务端启动,监听tcp服务端端口:", *TcpPort)
task.Config.CompressDecode, task.Config.CompressEncode = utils.GetCompressType(task.Config.Compress)
if *rpMode != "webServer" {
server.CsvDb.Tasks[0] = task
}
server.StartNewServer(*TcpPort, task, test)
}
Executable
+28
View File
@@ -0,0 +1,28 @@
appname = easyProxy
#web管理端口
httpport = 8080
#启动模式dev|pro
runmode = dev
#web管理密码
password=123
##客户端与服务端通信端口
tcpport=8284
#web api免验证IP地址
authip=127.0.0.1
##http代理端口
httpProxyPort=80
##https代理端口
httpsProxyPort=
##certFile绝对路径
pemPath=/etc/nginx/certificate.crt
##keyFile绝对路径
keyPath=/etc/nginx/private.key
+1
View File
@@ -0,0 +1 @@
1,wajajb6bl086s2aq,111,true,1,2,1,,20000,1000
1 1 wajajb6bl086s2aq 111 true 1 2 1 20000 1000
+2
View File
@@ -0,0 +1,2 @@
a.o.com,"127.0.0.1:8082
127.0.0.1:8080",1,,www.baidu.com,测试
1 a.o.com 127.0.0.1:8082 127.0.0.1:8080 1 www.baidu.com 测试
+4
View File
@@ -0,0 +1,4 @@
9002,tunnelServer,127.0.0.1:8082,2,2,,1,1,0,0,1,1,false,123
53,udpServer,114.114.114.114:53,,,,1,0,0,0,2,1,true,udp测试
9003,httpProxyServer,,,,,1,0,0,0,3,1,false,
8024,socks5Server,,,,,1,0,0,0,4,1,true,
1 9002 tunnelServer 127.0.0.1:8082 2 2 1 1 0 0 1 1 false 123
2 53 udpServer 114.114.114.114:53 1 0 0 0 2 1 true udp测试
3 9003 httpProxyServer 1 0 0 0 3 1 false
4 8024 socks5Server 1 0 0 0 4 1 true
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 276 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 276 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 712 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 690 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 233 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 281 KiB

+107
View File
@@ -0,0 +1,107 @@
package server
import (
"errors"
"github.com/cnlh/easyProxy/bridge"
"github.com/cnlh/easyProxy/utils"
"net"
"net/http"
"sync"
)
//server base struct
type server struct {
id int
bridge *bridge.Bridge
task *utils.Tunnel
config *utils.Config
errorContent []byte
sync.Mutex
}
func (s *server) FlowAdd(in, out int64) {
s.Lock()
defer s.Unlock()
s.task.Flow.ExportFlow += out
s.task.Flow.InletFlow += in
}
func (s *server) FlowAddHost(host *utils.Host, in, out int64) {
s.Lock()
defer s.Unlock()
host.Flow.ExportFlow += out
host.Flow.InletFlow += in
}
//热更新配置
func (s *server) ResetConfig() bool {
//获取最新数据
task, err := CsvDb.GetTask(s.task.Id)
if err != nil {
return false
}
if s.task.Client.Flow.FlowLimit > 0 && (s.task.Client.Flow.FlowLimit<<20) < (s.task.Client.Flow.ExportFlow+s.task.Client.Flow.InletFlow) {
return false
}
s.task.UseClientCnf = task.UseClientCnf
//使用客户端配置
client, err := CsvDb.GetClient(s.task.Client.Id)
if s.task.UseClientCnf {
if err == nil {
s.config.U = client.Cnf.U
s.config.P = client.Cnf.P
s.config.Compress = client.Cnf.Compress
s.config.Crypt = client.Cnf.Crypt
}
} else {
if err == nil {
s.config.U = task.Config.U
s.config.P = task.Config.P
s.config.Compress = task.Config.Compress
s.config.Crypt = task.Config.Crypt
}
}
s.task.Client.Rate = client.Rate
s.config.CompressDecode, s.config.CompressEncode = utils.GetCompressType(s.config.Compress)
return true
}
func (s *server) linkCopy(link *utils.Link, c *utils.Conn, rb []byte, tunnel *utils.Conn, flow *utils.Flow) {
if rb != nil {
if _, err := tunnel.SendMsg(rb, link); err != nil {
c.Close()
return
}
flow.Add(len(rb), 0)
}
for {
buf := utils.BufPoolCopy.Get().([]byte)
if n, err := c.Read(buf); err != nil {
tunnel.SendMsg([]byte(utils.IO_EOF), link)
break
} else {
if _, err := tunnel.SendMsg(buf[:n], link); err != nil {
utils.PutBufPoolCopy(buf)
c.Close()
break
}
utils.PutBufPoolCopy(buf)
flow.Add(n, 0)
}
}
}
func (s *server) writeConnFail(c net.Conn) {
c.Write([]byte(utils.ConnectionFailBytes))
c.Write(s.errorContent)
}
//权限认证
func (s *server) auth(r *http.Request, c *utils.Conn, u, p string) error {
if u != "" && p != "" && !utils.CheckAuth(r, u, p) {
c.Write([]byte(utils.UnauthorizedBytes))
c.Close()
return errors.New("401 Unauthorized")
}
return nil
}
+191
View File
@@ -0,0 +1,191 @@
package server
import (
"bufio"
"crypto/tls"
"github.com/astaxie/beego"
"github.com/cnlh/easyProxy/bridge"
"github.com/cnlh/easyProxy/utils"
"net"
"net/http"
"net/http/httputil"
"strconv"
"sync"
)
type httpServer struct {
server
httpPort int //http端口
httpsPort int //https监听端口
pemPath string
keyPath string
stop chan bool
}
func NewHttp(bridge *bridge.Bridge, c *utils.Tunnel) *httpServer {
httpPort, _ := beego.AppConfig.Int("httpProxyPort")
httpsPort, _ := beego.AppConfig.Int("httpsProxyPort")
pemPath := beego.AppConfig.String("pemPath")
keyPath := beego.AppConfig.String("keyPath")
return &httpServer{
server: server{
task: c,
bridge: bridge,
Mutex: sync.Mutex{},
},
httpPort: httpPort,
httpsPort: httpsPort,
pemPath: pemPath,
keyPath: keyPath,
stop: make(chan bool),
}
}
func (s *httpServer) Start() error {
var err error
var http, https *http.Server
if s.errorContent, err = utils.ReadAllFromFile(beego.AppPath + "/web/static/page/error.html"); err != nil {
s.errorContent = []byte("easyProxy 404")
}
if s.httpPort > 0 {
if !s.TestTcpPort(s.httpPort) {
utils.Fatalln("http端口", s.httpPort, "被占用!")
}
http = s.NewServer(s.httpPort)
go func() {
utils.Println("启动http监听,端口为", s.httpPort)
err := http.ListenAndServe()
if err != nil {
utils.Fatalln(err)
}
}()
}
if s.httpsPort > 0 {
if !s.TestTcpPort(s.httpsPort) {
utils.Fatalln("https端口", s.httpsPort, "被占用!")
}
if !utils.FileExists(s.pemPath) {
utils.Fatalf("ssl certFile文件%s不存在", s.pemPath)
}
if !utils.FileExists(s.keyPath) {
utils.Fatalf("ssl keyFile文件%s不存在", s.keyPath)
}
https = s.NewServer(s.httpsPort)
go func() {
utils.Println("启动https监听,端口为", s.httpsPort)
err := https.ListenAndServeTLS(s.pemPath, s.keyPath)
if err != nil {
utils.Fatalln(err)
}
}()
}
startFinish <- true
select {
case <-s.stop:
if http != nil {
http.Close()
}
if https != nil {
https.Close()
}
}
return nil
}
func (s *httpServer) Close() {
s.stop <- true
}
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
}
conn, _, err := hijacker.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
s.process(utils.NewConn(conn), r)
}
func (s *httpServer) process(c *utils.Conn, r *http.Request) {
//多客户端域名代理
var (
isConn = true
link *utils.Link
host *utils.Host
tunnel *utils.Conn
err error
)
for {
//首次获取conn
if isConn {
if host, err = GetInfoByHost(r.Host); err != nil {
utils.Printf("the host %s is not found !", r.Host)
break
}
//流量限制
if host.Client.Flow.FlowLimit > 0 && (host.Client.Flow.FlowLimit<<20) < (host.Client.Flow.ExportFlow+host.Client.Flow.InletFlow) {
break
}
host.Client.Cnf.CompressDecode, host.Client.Cnf.CompressEncode = utils.GetCompressType(host.Client.Cnf.Compress)
//权限控制
if err = s.auth(r, c, host.Client.Cnf.U, host.Client.Cnf.P); err != nil {
break
}
link = utils.NewLink(host.Client.GetId(), utils.CONN_TCP, host.GetRandomTarget(), host.Client.Cnf.CompressEncode, host.Client.Cnf.CompressDecode, host.Client.Cnf.Crypt, c, host.Flow, nil, host.Client.Rate, nil)
if tunnel, err = s.bridge.SendLinkInfo(host.Client.Id, link); err != nil {
break
}
isConn = false
} else {
r, err = http.ReadRequest(bufio.NewReader(c))
if err != nil {
break
}
}
//根据设定,修改header和host
utils.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, c.Conn.RemoteAddr().String())
b, err := httputil.DumpRequest(r, true)
if err != nil {
break
}
host.Flow.Add(len(b), 0)
if _, err := tunnel.SendMsg(b, link); err != nil {
c.Close()
break
}
}
if isConn {
s.writeConnFail(c.Conn)
} else {
tunnel.SendMsg([]byte(utils.IO_EOF), link)
}
c.Close()
}
func (s *httpServer) NewServer(port int) *http.Server {
return &http.Server{
Addr: ":" + strconv.Itoa(port),
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s.handleTunneling(w, r)
}),
// Disable HTTP/2.
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
}
}
func (s *httpServer) TestTcpPort(port int) bool {
l, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), port, ""})
defer l.Close()
if err != nil {
return false
}
return true
}
+268
View File
@@ -0,0 +1,268 @@
package server
import (
"errors"
"github.com/cnlh/easyProxy/bridge"
"github.com/cnlh/easyProxy/utils"
"log"
"os"
"reflect"
"strings"
)
var (
Bridge *bridge.Bridge
RunList map[int]interface{} //运行中的任务
CsvDb = utils.GetCsvDb()
startFinish chan bool
)
func init() {
RunList = make(map[int]interface{})
startFinish = make(chan bool)
}
//从csv文件中恢复任务
func InitFromCsv() {
for _, v := range CsvDb.Tasks {
if v.Status {
utils.Println("启动模式:", v.Mode, "监听端口:", v.TcpPort)
AddTask(v)
}
}
}
//start a new server
func StartNewServer(bridgePort int, cnf *utils.Tunnel, test bool) {
go func() {
Bridge = bridge.NewTunnel(bridgePort, RunList)
if err := Bridge.StartTunnel(); err != nil {
utils.Fatalln("服务端开启失败", err)
}
if svr := NewMode(Bridge, cnf); svr != nil {
RunList[cnf.Id] = svr
err := reflect.ValueOf(svr).MethodByName("Start").Call(nil)[0]
if err.Interface() != nil {
utils.Fatalln(err)
}
} else {
utils.Fatalln("启动模式不正确")
}
}()
for {
select {
case <-startFinish:
if test {
log.Println("测试完成,未发现错误")
os.Exit(0)
}
}
}
}
//new a server by mode name
func NewMode(Bridge *bridge.Bridge, c *utils.Tunnel) interface{} {
switch c.Mode {
case "tunnelServer":
return NewTunnelModeServer(ProcessTunnel, Bridge, c)
case "socks5Server":
return NewSock5ModeServer(Bridge, c)
case "httpProxyServer":
return NewTunnelModeServer(ProcessHttp, Bridge, c)
case "udpServer":
return NewUdpModeServer(Bridge, c)
case "webServer":
InitFromCsv()
t := &utils.Tunnel{
TcpPort: 0,
Mode: "httpHostServer",
Target: "",
Config: &utils.Config{},
Status: true,
}
AddTask(t)
return NewWebServer(Bridge)
case "hostServer":
return NewHostServer(c)
case "httpHostServer":
return NewHttp(Bridge, c)
}
return nil
}
//stop server
func StopServer(id int) error {
if v, ok := RunList[id]; ok {
reflect.ValueOf(v).MethodByName("Close").Call(nil)
if t, err := CsvDb.GetTask(id); err != nil {
return err
} else {
t.Status = false
CsvDb.UpdateTask(t)
}
return nil
}
return errors.New("未在运行中")
}
//add task
func AddTask(t *utils.Tunnel) error {
if svr := NewMode(Bridge, t); svr != nil {
RunList[t.Id] = svr
go func() {
err := reflect.ValueOf(svr).MethodByName("Start").Call(nil)[0]
if err.Interface() != nil {
utils.Fatalln("服务端", t.Id, "启动失败,错误:", err)
delete(RunList, t.Id)
}
}()
} else {
return errors.New("启动模式不正确")
}
return nil
}
//start task
func StartTask(id int) error {
if t, err := CsvDb.GetTask(id); err != nil {
return err
} else {
AddTask(t)
t.Status = true
CsvDb.UpdateTask(t)
}
return nil
}
//delete task
func DelTask(id int) error {
if err := StopServer(id); err != nil {
return err
}
return CsvDb.DelTask(id)
}
//get key by host from x
func GetInfoByHost(host string) (h *utils.Host, err error) {
for _, v := range CsvDb.Hosts {
s := strings.Split(host, ":")
if s[0] == v.Host {
h = v
return
}
}
err = errors.New("未找到host对应的内网目标")
return
}
//get task list by page num
func GetTunnel(start, length int, typeVal string, clientId int) ([]*utils.Tunnel, int) {
list := make([]*utils.Tunnel, 0)
var cnt int
for _, v := range CsvDb.Tasks {
if (typeVal != "" && v.Mode != typeVal) || (typeVal == "" && clientId != v.Client.Id) {
continue
}
cnt++
if _, ok := Bridge.Client[v.Client.Id]; ok {
v.Client.IsConnect = true
} else {
v.Client.IsConnect = false
}
if start--; start < 0 {
if length--; length > 0 {
if _, ok := RunList[v.Id]; ok {
v.Client.Status = true
} else {
v.Client.Status = false
}
list = append(list, v)
}
}
}
return list, cnt
}
//获取客户端列表
func GetClientList(start, length int) (list []*utils.Client, cnt int) {
list, cnt = CsvDb.GetClientList(start, length)
dealClientData(list)
return
}
func dealClientData(list []*utils.Client) {
for _, v := range list {
if _, ok := Bridge.Client[v.Id]; ok {
v.IsConnect = true
} else {
v.IsConnect = false
}
v.Flow.InletFlow = 0
v.Flow.ExportFlow = 0
for _, h := range CsvDb.Hosts {
if h.Client.Id == v.Id {
v.Flow.InletFlow += h.Flow.InletFlow
v.Flow.ExportFlow += h.Flow.ExportFlow
}
}
for _, t := range CsvDb.Tasks {
if t.Client.Id == v.Id {
v.Flow.InletFlow += t.Flow.InletFlow
v.Flow.ExportFlow += t.Flow.ExportFlow
}
}
}
return
}
//根据客户端id删除其所属的所有隧道和域名
func DelTunnelAndHostByClientId(clientId int) {
for _, v := range CsvDb.Tasks {
if v.Client.Id == clientId {
DelTask(v.Id)
}
}
for _, v := range CsvDb.Hosts {
if v.Client.Id == clientId {
CsvDb.DelHost(v.Host)
}
}
}
//关闭客户端连接
func DelClientConnect(clientId int) {
Bridge.DelClient(clientId)
}
func GetDashboardData() map[string]int {
data := make(map[string]int)
data["hostCount"] = len(CsvDb.Hosts)
data["clientCount"] = len(CsvDb.Clients)
list := CsvDb.Clients
dealClientData(list)
c := 0
var in, out int64
for _, v := range list {
if v.IsConnect {
c += 1
}
in += v.Flow.InletFlow
out += v.Flow.ExportFlow
}
data["clientOnlineCount"] = c
data["inletFlowCount"] = int(in)
data["exportFlowCount"] = int(out)
for _, v := range CsvDb.Tasks {
switch v.Mode {
case "tunnelServer":
data["tunnelServerCount"] += 1
case "socks5Server":
data["socks5ServerCount"] += 1
case "httpProxyServer":
data["httpProxyServerCount"] += 1
case "udpServer":
data["udpServerCount"] += 1
}
}
return data
}
+300
View File
@@ -0,0 +1,300 @@
package server
import (
"encoding/binary"
"errors"
"github.com/cnlh/easyProxy/bridge"
"github.com/cnlh/easyProxy/utils"
"io"
"net"
"strconv"
"strings"
)
const (
ipV4 = 1
domainName = 3
ipV6 = 4
connectMethod = 1
bindMethod = 2
associateMethod = 3
// The maximum packet size of any udp Associate packet, based on ethernet's max size,
// minus the IP and UDP headers. IPv4 has a 20 byte header, UDP adds an
// additional 4 bytes. This is a total overhead of 24 bytes. Ethernet's
// max packet size is 1500 bytes, 1500 - 24 = 1476.
maxUDPPacketSize = 1476
)
const (
succeeded uint8 = iota
serverFailure
notAllowed
networkUnreachable
hostUnreachable
connectionRefused
ttlExpired
commandNotSupported
addrTypeNotSupported
)
const (
UserPassAuth = uint8(2)
userAuthVersion = uint8(1)
authSuccess = uint8(0)
authFailure = uint8(1)
)
type Sock5ModeServer struct {
server
isVerify bool
listener net.Listener
}
//req
func (s *Sock5ModeServer) handleRequest(c net.Conn) {
/*
The SOCKS request is formed as follows:
+----+-----+-------+------+----------+----------+
|VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
+----+-----+-------+------+----------+----------+
| 1 | 1 | X'00' | 1 | Variable | 2 |
+----+-----+-------+------+----------+----------+
*/
header := make([]byte, 3)
_, err := io.ReadFull(c, header)
if err != nil {
utils.Println("illegal request", err)
c.Close()
return
}
switch header[1] {
case connectMethod:
s.handleConnect(c)
case bindMethod:
s.handleBind(c)
case associateMethod:
s.handleUDP(c)
default:
s.sendReply(c, commandNotSupported)
c.Close()
}
}
//reply
func (s *Sock5ModeServer) sendReply(c net.Conn, rep uint8) {
reply := []byte{
5,
rep,
0,
1,
}
localAddr := c.LocalAddr().String()
localHost, localPort, _ := net.SplitHostPort(localAddr)
ipBytes := net.ParseIP(localHost).To4()
nPort, _ := strconv.Atoi(localPort)
reply = append(reply, ipBytes...)
portBytes := make([]byte, 2)
binary.BigEndian.PutUint16(portBytes, uint16(nPort))
reply = append(reply, portBytes...)
c.Write(reply)
}
//do conn
func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
addrType := make([]byte, 1)
c.Read(addrType)
var host string
switch addrType[0] {
case ipV4:
ipv4 := make(net.IP, net.IPv4len)
c.Read(ipv4)
host = ipv4.String()
case ipV6:
ipv6 := make(net.IP, net.IPv6len)
c.Read(ipv6)
host = ipv6.String()
case domainName:
var domainLen uint8
binary.Read(c, binary.BigEndian, &domainLen)
domain := make([]byte, domainLen)
c.Read(domain)
host = string(domain)
default:
s.sendReply(c, addrTypeNotSupported)
return
}
var port uint16
binary.Read(c, binary.BigEndian, &port)
// connect to host
addr := net.JoinHostPort(host, strconv.Itoa(int(port)))
var ltype string
if command == associateMethod {
ltype = utils.CONN_UDP
} else {
ltype = utils.CONN_TCP
}
link := utils.NewLink(s.task.Client.GetId(), ltype, addr, s.config.CompressEncode, s.config.CompressDecode, s.config.Crypt, utils.NewConn(c), s.task.Flow, nil, s.task.Client.Rate, nil)
if tunnel, err := s.bridge.SendLinkInfo(s.task.Client.Id, link); err != nil {
c.Close()
return
} else {
s.sendReply(c, succeeded)
s.linkCopy(link, utils.NewConn(c), nil, tunnel, s.task.Flow)
}
return
}
//conn
func (s *Sock5ModeServer) handleConnect(c net.Conn) {
s.doConnect(c, connectMethod)
}
// passive mode
func (s *Sock5ModeServer) handleBind(c net.Conn) {
}
//udp
func (s *Sock5ModeServer) handleUDP(c net.Conn) {
utils.Println("UDP Associate")
/*
+----+------+------+----------+----------+----------+
|RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
+----+------+------+----------+----------+----------+
| 2 | 1 | 1 | Variable | 2 | Variable |
+----+------+------+----------+----------+----------+
*/
buf := make([]byte, 3)
c.Read(buf)
// relay udp datagram silently, without any notification to the requesting client
if buf[2] != 0 {
// does not support fragmentation, drop it
utils.Println("does not support fragmentation, drop")
dummy := make([]byte, maxUDPPacketSize)
c.Read(dummy)
}
s.doConnect(c, associateMethod)
}
//new conn
func (s *Sock5ModeServer) handleConn(c net.Conn) {
buf := make([]byte, 2)
if _, err := io.ReadFull(c, buf); err != nil {
utils.Println("negotiation err", err)
c.Close()
return
}
if version := buf[0]; version != 5 {
utils.Println("only support socks5, request from: ", c.RemoteAddr())
c.Close()
return
}
nMethods := buf[1]
methods := make([]byte, nMethods)
if len, err := c.Read(methods); len != int(nMethods) || err != nil {
utils.Println("wrong method")
c.Close()
return
}
if s.isVerify {
buf[1] = UserPassAuth
c.Write(buf)
if err := s.Auth(c); err != nil {
c.Close()
utils.Println("验证失败:", err)
return
}
} else {
buf[1] = 0
c.Write(buf)
}
s.handleRequest(c)
}
//socks5 auth
func (s *Sock5ModeServer) Auth(c net.Conn) error {
header := []byte{0, 0}
if _, err := io.ReadAtLeast(c, header, 2); err != nil {
return err
}
if header[0] != userAuthVersion {
return errors.New("验证方式不被支持")
}
userLen := int(header[1])
user := make([]byte, userLen)
if _, err := io.ReadAtLeast(c, user, userLen); err != nil {
return err
}
if _, err := c.Read(header[:1]); err != nil {
return errors.New("密码长度获取错误")
}
passLen := int(header[0])
pass := make([]byte, passLen)
if _, err := io.ReadAtLeast(c, pass, passLen); err != nil {
return err
}
if string(pass) == s.config.U && string(user) == s.config.P {
if _, err := c.Write([]byte{userAuthVersion, authSuccess}); err != nil {
return err
}
return nil
} else {
if _, err := c.Write([]byte{userAuthVersion, authFailure}); err != nil {
return err
}
return errors.New("验证不通过")
}
return errors.New("未知错误")
}
//start
func (s *Sock5ModeServer) Start() error {
var err error
s.listener, err = net.Listen("tcp", ":"+strconv.Itoa(s.task.TcpPort))
if err != nil {
return err
}
for {
conn, err := s.listener.Accept()
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
break
}
utils.Fatalln("accept error: ", err)
}
if !s.ResetConfig() {
conn.Close()
continue
}
go s.handleConn(conn)
}
return nil
}
//close
func (s *Sock5ModeServer) Close() error {
return s.listener.Close()
}
//new
func NewSock5ModeServer(bridge *bridge.Bridge, task *utils.Tunnel) *Sock5ModeServer {
s := new(Sock5ModeServer)
s.bridge = bridge
s.task = task
s.config = utils.DeepCopyConfig(task.Config)
if s.config.U != "" && s.config.P != "" {
s.isVerify = true
} else {
s.isVerify = false
}
return s
}
Executable
+137
View File
@@ -0,0 +1,137 @@
package server
import (
"errors"
"github.com/astaxie/beego"
"github.com/cnlh/easyProxy/bridge"
"github.com/cnlh/easyProxy/utils"
"net"
"strings"
)
type TunnelModeServer struct {
server
process process
listener *net.TCPListener
}
//tcp|http|host
func NewTunnelModeServer(process process, bridge *bridge.Bridge, task *utils.Tunnel) *TunnelModeServer {
s := new(TunnelModeServer)
s.bridge = bridge
s.process = process
s.task = task
s.config = utils.DeepCopyConfig(task.Config)
return s
}
//开始
func (s *TunnelModeServer) Start() error {
var err error
s.listener, err = net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), s.task.TcpPort, ""})
if err != nil {
return err
}
for {
conn, err := s.listener.AcceptTCP()
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
break
}
utils.Println(err)
continue
}
go s.process(utils.NewConn(conn), s)
}
return nil
}
//与客户端建立通道
func (s *TunnelModeServer) dealClient(c *utils.Conn, cnf *utils.Config, addr string, method string, rb []byte) error {
link := utils.NewLink(s.task.Client.GetId(), utils.CONN_TCP, addr, cnf.CompressEncode, cnf.CompressDecode, cnf.Crypt, c, s.task.Flow, nil, s.task.Client.Rate, nil)
if tunnel, err := s.bridge.SendLinkInfo(s.task.Client.Id, link); err != nil {
c.Close()
return err
} else {
s.linkCopy(link, c, rb, tunnel, s.task.Flow)
}
return nil
}
//close
func (s *TunnelModeServer) Close() error {
return s.listener.Close()
}
//web管理方式
type WebServer struct {
server
}
//开始
func (s *WebServer) Start() error {
beego.BConfig.WebConfig.Session.SessionOn = true
utils.Println("web管理启动,访问端口为", beego.AppConfig.String("httpport"))
beego.SetViewsPath(beego.AppPath + "/web/views")
beego.SetStaticPath("/static", beego.AppPath+"/web/static")
beego.Run()
return errors.New("web管理启动失败")
}
//new
func NewWebServer(bridge *bridge.Bridge) *WebServer {
s := new(WebServer)
s.bridge = bridge
return s
}
//host
type HostServer struct {
server
}
//开始
func (s *HostServer) Start() error {
return nil
}
func NewHostServer(task *utils.Tunnel) *HostServer {
s := new(HostServer)
s.task = task
s.config = utils.DeepCopyConfig(task.Config)
return s
}
//close
func (s *HostServer) Close() error {
return nil
}
type process func(c *utils.Conn, s *TunnelModeServer) error
//tcp隧道模式
func ProcessTunnel(c *utils.Conn, s *TunnelModeServer) error {
if !s.ResetConfig() {
c.Close()
return errors.New("流量超出")
}
return s.dealClient(c, s.config, s.task.Target, "", nil)
}
//http代理模式
func ProcessHttp(c *utils.Conn, s *TunnelModeServer) error {
if !s.ResetConfig() {
c.Close()
return errors.New("流量超出")
}
method, addr, rb, err, r := c.GetHost()
if err != nil {
c.Close()
return err
}
if err := s.auth(r, c, s.config.U, s.config.P); err != nil {
return err
}
return s.dealClient(c, s.config, addr, method, rb)
}
Executable
+62
View File
@@ -0,0 +1,62 @@
package server
import (
"github.com/cnlh/easyProxy/bridge"
"github.com/cnlh/easyProxy/utils"
"net"
"strings"
)
type UdpModeServer struct {
server
listener *net.UDPConn
udpMap map[string]*utils.Conn
}
func NewUdpModeServer(bridge *bridge.Bridge, task *utils.Tunnel) *UdpModeServer {
s := new(UdpModeServer)
s.bridge = bridge
s.udpMap = make(map[string]*utils.Conn)
s.task = task
s.config = utils.DeepCopyConfig(task.Config)
return s
}
//开始
func (s *UdpModeServer) Start() error {
var err error
s.listener, err = net.ListenUDP("udp", &net.UDPAddr{net.ParseIP("0.0.0.0"), s.task.TcpPort, ""})
if err != nil {
return err
}
buf := utils.BufPoolUdp.Get().([]byte)
for {
n, addr, err := s.listener.ReadFromUDP(buf)
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
break
}
continue
}
if !s.ResetConfig() {
continue
}
go s.process(addr, buf[:n])
}
return nil
}
func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
link := utils.NewLink(s.task.Client.GetId(), utils.CONN_UDP, s.task.Target, s.config.CompressEncode, s.config.CompressDecode, s.config.Crypt, nil, s.task.Flow, s.listener, s.task.Client.Rate, addr)
if tunnel, err := s.bridge.SendLinkInfo(s.task.Client.Id, link); err != nil {
return
} else {
s.task.Flow.Add(len(data), 0)
tunnel.SendMsg(data, link)
}
}
func (s *UdpModeServer) Close() error {
return s.listener.Close()
}
Executable
+438
View File
@@ -0,0 +1,438 @@
package utils
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"github.com/golang/snappy"
"io"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
)
const cryptKey = "1234567812345678"
type CryptConn struct {
conn net.Conn
crypt bool
rate *Rate
}
func NewCryptConn(conn net.Conn, crypt bool, rate *Rate) *CryptConn {
c := new(CryptConn)
c.conn = conn
c.crypt = crypt
c.rate = rate
return c
}
//加密写
func (s *CryptConn) Write(b []byte) (n int, err error) {
n = len(b)
if s.crypt {
if b, err = AesEncrypt(b, []byte(cryptKey)); err != nil {
return
}
}
if b, err = GetLenBytes(b); err != nil {
return
}
_, err = s.conn.Write(b)
if s.rate != nil {
s.rate.Get(int64(n))
}
return
}
//解密读
func (s *CryptConn) Read(b []byte) (n int, err error) {
var lens int
var buf []byte
var rb []byte
c := NewConn(s.conn)
if lens, err = c.GetLen(); err != nil {
return
}
if buf, err = c.ReadLen(lens); err != nil {
return
}
if s.crypt {
if rb, err = AesDecrypt(buf, []byte(cryptKey)); err != nil {
return
}
} else {
rb = buf
}
copy(b, rb)
n = len(rb)
if s.rate != nil {
s.rate.Get(int64(n))
}
return
}
type SnappyConn struct {
w *snappy.Writer
r *snappy.Reader
crypt bool
rate *Rate
}
func NewSnappyConn(conn net.Conn, crypt bool, rate *Rate) *SnappyConn {
c := new(SnappyConn)
c.w = snappy.NewBufferedWriter(conn)
c.r = snappy.NewReader(conn)
c.crypt = crypt
c.rate = rate
return c
}
//snappy压缩写 包含加密
func (s *SnappyConn) Write(b []byte) (n int, err error) {
n = len(b)
if s.crypt {
if b, err = AesEncrypt(b, []byte(cryptKey)); err != nil {
Println("encode crypt error:", err)
return
}
}
if _, err = s.w.Write(b); err != nil {
return
}
if err = s.w.Flush(); err != nil {
return
}
if s.rate != nil {
s.rate.Get(int64(n))
}
return
}
//snappy压缩读 包含解密
func (s *SnappyConn) Read(b []byte) (n int, err error) {
buf := BufPool.Get().([]byte)
defer BufPool.Put(buf)
if n, err = s.r.Read(buf); err != nil {
return
}
var bs []byte
if s.crypt {
if bs, err = AesDecrypt(buf[:n], []byte(cryptKey)); err != nil {
Println("decode crypt error:", err)
return
}
} else {
bs = buf[:n]
}
n = len(bs)
copy(b, bs)
if s.rate != nil {
s.rate.Get(int64(n))
}
return
}
type Conn struct {
Conn net.Conn
sync.Mutex
}
//new conn
func NewConn(conn net.Conn) *Conn {
c := new(Conn)
c.Conn = conn
return c
}
//从tcp报文中解析出host,连接类型等
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 {
return
}
rb = b[:n]
r, err = http.ReadRequest(bufio.NewReader(bytes.NewReader(rb)))
if err != nil {
return
}
hostPortURL, err := url.Parse(r.Host)
if err != nil {
address = r.Host
err = nil
return
}
if hostPortURL.Opaque == "443" { //https访问
if strings.Index(r.Host, ":") == -1 { //host不带端口, 默认80
address = r.Host + ":443"
} else {
address = r.Host
}
} else { //http访问
if strings.Index(r.Host, ":") == -1 { //host不带端口, 默认80
address = r.Host + ":80"
} else {
address = r.Host
}
}
return
}
//读取指定长度内容
func (s *Conn) ReadLen(cLen int) ([]byte, error) {
if cLen > poolSize {
return nil, errors.New("长度错误" + strconv.Itoa(cLen))
}
var buf []byte
if cLen <= poolSizeSmall {
buf = BufPoolSmall.Get().([]byte)[:cLen]
defer BufPoolSmall.Put(buf)
} else {
buf = BufPoolMax.Get().([]byte)[:cLen]
defer BufPoolMax.Put(buf)
}
if n, err := io.ReadFull(s, buf); err != nil || n != cLen {
return buf, errors.New("读取指定长度错误" + err.Error())
}
return buf, nil
}
//read length or id (content length=4)
func (s *Conn) GetLen() (int, error) {
val, err := s.ReadLen(4)
if err != nil {
return 0, err
}
return GetLenByBytes(val)
}
//read flag
func (s *Conn) ReadFlag() (string, error) {
val, err := s.ReadLen(4)
if err != nil {
return "", err
}
return string(val), err
}
//read connect status
func (s *Conn) GetConnStatus() (id int, status bool, err error) {
id, err = s.GetLen()
if err != nil {
return
}
var b []byte
if b, err = s.ReadLen(1); err != nil {
return
} else {
status = GetBoolByStr(string(b[0]))
}
return
}
//设置连接为长连接
func (s *Conn) SetAlive() {
conn := s.Conn.(*net.TCPConn)
conn.SetReadDeadline(time.Time{})
conn.SetKeepAlive(true)
conn.SetKeepAlivePeriod(time.Duration(2 * time.Second))
}
//set read dead time
func (s *Conn) SetReadDeadline(t time.Duration) {
s.Conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
}
//单独读(加密|压缩)
func (s *Conn) ReadFrom(b []byte, compress int, crypt bool, rate *Rate) (int, error) {
if COMPRESS_SNAPY_DECODE == compress {
return NewSnappyConn(s.Conn, crypt, rate).Read(b)
}
return NewCryptConn(s.Conn, crypt, rate).Read(b)
}
//单独写(加密|压缩)
func (s *Conn) WriteTo(b []byte, compress int, crypt bool, rate *Rate) (n int, err error) {
if COMPRESS_SNAPY_ENCODE == compress {
return NewSnappyConn(s.Conn, crypt, rate).Write(b)
}
return NewCryptConn(s.Conn, crypt, rate).Write(b)
}
//send msg
func (s *Conn) SendMsg(content []byte, link *Link) (n int, err error) {
/*
The msg info is formed as follows:
+----+--------+
|id | content |
+----+--------+
| 4 | ... |
+----+--------+
*/
s.Lock()
defer s.Unlock()
raw := bytes.NewBuffer([]byte{})
binary.Write(raw, binary.LittleEndian, int32(link.Id))
if n, err = s.Write(raw.Bytes()); err != nil {
return
}
raw.Reset()
binary.Write(raw, binary.LittleEndian, content)
n, err = s.WriteTo(raw.Bytes(), link.En, link.Crypt, link.Rate)
return
}
//get msg content from conn
func (s *Conn) GetMsgContent(link *Link) (content []byte, err error) {
s.Lock()
defer s.Unlock()
buf := BufPoolCopy.Get().([]byte)
if n, err := s.ReadFrom(buf, link.De, link.Crypt, link.Rate); err == nil && n > 4 {
content = buf[:n]
}
return
}
//send info for link
func (s *Conn) SendLinkInfo(link *Link) (int, error) {
/*
The link info is formed as follows:
+----------+------+----------+------+----------+-----+
| id | len | type | hostlen | host | en | de |crypt |
+----------+------+----------+------+---------+------+
| 4 | 4 | 3 | 4 | host | 1 | 1 | 1 |
+----------+------+----------+------+----+----+------+
*/
raw := bytes.NewBuffer([]byte{})
binary.Write(raw, binary.LittleEndian, []byte(NEW_CONN))
binary.Write(raw, binary.LittleEndian, int32(14+len(link.Host)))
binary.Write(raw, binary.LittleEndian, int32(link.Id))
binary.Write(raw, binary.LittleEndian, []byte(link.ConnType))
binary.Write(raw, binary.LittleEndian, int32(len(link.Host)))
binary.Write(raw, binary.LittleEndian, []byte(link.Host))
binary.Write(raw, binary.LittleEndian, []byte(strconv.Itoa(link.En)))
binary.Write(raw, binary.LittleEndian, []byte(strconv.Itoa(link.De)))
binary.Write(raw, binary.LittleEndian, []byte(GetStrByBool(link.Crypt)))
s.Lock()
defer s.Unlock()
return s.Write(raw.Bytes())
}
func (s *Conn) GetLinkInfo() (link *Link, err error) {
s.Lock()
defer s.Unlock()
var hostLen, n int
var buf []byte
if n, err = s.GetLen(); err != nil {
return
}
link = new(Link)
if buf, err = s.ReadLen(n); err != nil {
return
}
if link.Id, err = GetLenByBytes(buf[:4]); err != nil {
return
}
link.ConnType = string(buf[4:7])
if hostLen, err = GetLenByBytes(buf[7:11]); err != nil {
return
} else {
link.Host = string(buf[11 : 11+hostLen])
link.En = GetIntNoErrByStr(string(buf[11+hostLen]))
link.De = GetIntNoErrByStr(string(buf[12+hostLen]))
link.Crypt = GetBoolByStr(string(buf[13+hostLen]))
}
return
}
//write connect success
func (s *Conn) WriteSuccess(id int) (int, error) {
raw := bytes.NewBuffer([]byte{})
binary.Write(raw, binary.LittleEndian, int32(id))
binary.Write(raw, binary.LittleEndian, []byte("1"))
s.Lock()
defer s.Unlock()
return s.Write(raw.Bytes())
}
//write connect fail
func (s *Conn) WriteFail(id int) (int, error) {
raw := bytes.NewBuffer([]byte{})
binary.Write(raw, binary.LittleEndian, int32(id))
binary.Write(raw, binary.LittleEndian, []byte("0"))
s.Lock()
defer s.Unlock()
return s.Write(raw.Bytes())
}
//close
func (s *Conn) Close() error {
return s.Conn.Close()
}
//write
func (s *Conn) Write(b []byte) (int, error) {
return s.Conn.Write(b)
}
//read
func (s *Conn) Read(b []byte) (int, error) {
return s.Conn.Read(b)
}
//write error
func (s *Conn) WriteError() (int, error) {
return s.Write([]byte(RES_MSG))
}
//write sign flag
func (s *Conn) WriteSign() (int, error) {
return s.Write([]byte(RES_SIGN))
}
//write sign flag
func (s *Conn) WriteClose() (int, error) {
return s.Write([]byte(RES_CLOSE))
}
//write main
func (s *Conn) WriteMain() (int, error) {
s.Lock()
defer s.Unlock()
return s.Write([]byte(WORK_MAIN))
}
//write chan
func (s *Conn) WriteChan() (int, error) {
s.Lock()
defer s.Unlock()
return s.Write([]byte(WORK_CHAN))
}
//获取长度+内容
func GetLenBytes(buf []byte) (b []byte, err error) {
raw := bytes.NewBuffer([]byte{})
if err = binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
return
}
if err = binary.Write(raw, binary.LittleEndian, buf); err != nil {
return
}
b = raw.Bytes()
return
}
//解析出长度
func GetLenByBytes(buf []byte) (int, error) {
nlen := binary.LittleEndian.Uint32(buf)
if nlen <= 0 {
return 0, errors.New("数据长度错误")
}
return int(nlen), nil
}
+82
View File
@@ -0,0 +1,82 @@
package utils
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"encoding/hex"
"errors"
"math/rand"
"time"
)
//en
func AesEncrypt(origData, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData = PKCS5Padding(origData, blockSize)
// origData = ZeroPadding(origData, block.BlockSize())
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
crypted := make([]byte, len(origData))
// 根据CryptBlocks方法的说明,如下方式初始化crypted也可以
// crypted := origData
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
//de
func AesDecrypt(crypted, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
origData := make([]byte, len(crypted))
// origData := crypted
blockMode.CryptBlocks(origData, crypted)
err, origData = PKCS5UnPadding(origData)
// origData = ZeroUnPadding(origData)
return origData, err
}
//补全
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
//去补
func PKCS5UnPadding(origData []byte) (error, []byte) {
length := len(origData)
// 去掉最后一个字节 unpadding 次
unpadding := int(origData[length-1])
if (length - unpadding) < 0 {
return errors.New("len error"), nil
}
return nil, origData[:(length - unpadding)]
}
//生成32位md5字串
func Md5(s string) string {
h := md5.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}
//生成随机验证密钥
func GetRandomString(l int) string {
str := "0123456789abcdefghijklmnopqrstuvwxyz"
bytes := []byte(str)
result := []byte{}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < l; i++ {
result = append(result, bytes[r.Intn(len(bytes))])
}
return string(result)
}
+69
View File
@@ -0,0 +1,69 @@
package utils
import (
"github.com/astaxie/beego"
"io/ioutil"
"log"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
)
func InitDaemon(f string) {
if len(os.Args) < 2 {
return
}
var args []string
args = append(args, os.Args[0])
if len(os.Args) >= 2 {
args = append(args, os.Args[2:]...)
}
args = append(args, "-log=file")
switch os.Args[1] {
case "start":
start(args, f)
os.Exit(0)
case "stop":
stop(f, args[0])
os.Exit(0)
case "restart":
stop(f, args[0])
start(args, f)
os.Exit(0)
}
}
func start(osArgs []string, f string) {
cmd := exec.Command(osArgs[0], osArgs[1:]...)
cmd.Start()
log.Println("执行启动成功")
if cmd.Process.Pid > 0 {
d1 := []byte(strconv.Itoa(cmd.Process.Pid))
ioutil.WriteFile(beego.AppPath+"/proxy_"+f+".pid", d1, 0600)
}
}
func stop(f string, p string) {
var c *exec.Cmd
var err error
switch runtime.GOOS {
case "windows":
p := strings.Split(p, `\`)
c = exec.Command("taskkill", "/F", "/IM", p[len(p)-1])
case "linux", "darwin":
b, err := ioutil.ReadFile(beego.AppPath + "/proxy_" + f + ".pid")
if err == nil {
c = exec.Command("/bin/bash", "-c", `kill -9 `+string(b))
} else {
log.Println("停止服务失败,pid文件不存在")
}
}
err = c.Run()
if err != nil {
log.Println("停止服务失败,", err)
} else {
log.Println("停止服务成功")
}
}
+426
View File
@@ -0,0 +1,426 @@
package utils
import (
"encoding/csv"
"errors"
"github.com/astaxie/beego"
"os"
"strconv"
"strings"
"sync"
)
var (
CsvDb *Csv
once sync.Once
)
func NewCsv() *Csv {
return new(Csv)
}
type Csv struct {
Tasks []*Tunnel
Path string
Hosts []*Host //域名列表
Clients []*Client //客户端
ClientIncreaseId int //客户端id
TaskIncreaseId int //任务自增ID
sync.Mutex
}
func (s *Csv) Init() {
s.LoadClientFromCsv()
s.LoadTaskFromCsv()
s.LoadHostFromCsv()
}
func (s *Csv) StoreTasksToCsv() {
// 创建文件
csvFile, err := os.Create(beego.AppPath + "/conf/tasks.csv")
if err != nil {
Fatalf(err.Error())
}
defer csvFile.Close()
writer := csv.NewWriter(csvFile)
for _, task := range s.Tasks {
record := []string{
strconv.Itoa(task.TcpPort),
task.Mode,
task.Target,
task.Config.U,
task.Config.P,
task.Config.Compress,
GetStrByBool(task.Status),
GetStrByBool(task.Config.Crypt),
strconv.Itoa(task.Config.CompressEncode),
strconv.Itoa(task.Config.CompressDecode),
strconv.Itoa(task.Id),
strconv.Itoa(task.Client.Id),
strconv.FormatBool(task.UseClientCnf),
task.Remark,
}
err := writer.Write(record)
if err != nil {
Fatalf(err.Error())
}
}
writer.Flush()
}
func (s *Csv) openFile(path string) ([][]string, error) {
// 打开文件
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer file.Close()
// 获取csv的reader
reader := csv.NewReader(file)
// 设置FieldsPerRecord为-1
reader.FieldsPerRecord = -1
// 读取文件中所有行保存到slice中
return reader.ReadAll()
}
func (s *Csv) LoadTaskFromCsv() {
path := beego.AppPath + "/conf/tasks.csv"
records, err := s.openFile(path)
if err != nil {
Fatalln("配置文件打开错误:", path)
}
var tasks []*Tunnel
// 将每一行数据保存到内存slice中
for _, item := range records {
post := &Tunnel{
TcpPort: GetIntNoErrByStr(item[0]),
Mode: item[1],
Target: item[2],
Config: &Config{
U: item[3],
P: item[4],
Compress: item[5],
Crypt: GetBoolByStr(item[7]),
CompressEncode: GetIntNoErrByStr(item[8]),
CompressDecode: GetIntNoErrByStr(item[9]),
},
Status: GetBoolByStr(item[6]),
Id: GetIntNoErrByStr(item[10]),
UseClientCnf: GetBoolByStr(item[12]),
Remark: item[13],
}
post.Flow = new(Flow)
if post.Client, err = s.GetClient(GetIntNoErrByStr(item[11])); err != nil {
continue
}
tasks = append(tasks, post)
if post.Id > s.TaskIncreaseId {
s.TaskIncreaseId = post.Id
}
}
s.Tasks = tasks
}
func (s *Csv) GetTaskId() int {
s.Lock()
defer s.Unlock()
s.TaskIncreaseId++
return s.TaskIncreaseId
}
func (s *Csv) GetIdByVerifyKey(vKey string, addr string) (int, error) {
s.Lock()
defer s.Unlock()
for _, v := range s.Clients {
if Getverifyval(v.VerifyKey) == vKey && v.Status {
if arr := strings.Split(addr, ":"); len(arr) > 0 {
v.Addr = arr[0]
}
return v.Id, nil
}
}
return 0, errors.New("not found")
}
func (s *Csv) NewTask(t *Tunnel) {
t.Flow = new(Flow)
s.Tasks = append(s.Tasks, t)
s.StoreTasksToCsv()
}
func (s *Csv) UpdateTask(t *Tunnel) error {
for k, v := range s.Tasks {
if v.Id == t.Id {
s.Tasks = append(s.Tasks[:k], s.Tasks[k+1:]...)
s.Tasks = append(s.Tasks, t)
s.StoreTasksToCsv()
return nil
}
}
return errors.New("不存在")
}
func (s *Csv) DelTask(id int) error {
for k, v := range s.Tasks {
if v.Id == id {
s.Tasks = append(s.Tasks[:k], s.Tasks[k+1:]...)
s.StoreTasksToCsv()
return nil
}
}
return errors.New("不存在")
}
func (s *Csv) GetTask(id int) (v *Tunnel, err error) {
for _, v = range s.Tasks {
if v.Id == id {
return
}
}
err = errors.New("未找到")
return
}
func (s *Csv) StoreHostToCsv() {
// 创建文件
csvFile, err := os.Create(beego.AppPath + "/conf/hosts.csv")
if err != nil {
panic(err)
}
defer csvFile.Close()
// 获取csv的Writer
writer := csv.NewWriter(csvFile)
// 将map中的Post转换成slice,因为csv的Write需要slice参数
// 并写入csv文件
for _, host := range s.Hosts {
record := []string{
host.Host,
host.Target,
strconv.Itoa(host.Client.Id),
host.HeaderChange,
host.HostChange,
host.Remark,
}
err1 := writer.Write(record)
if err1 != nil {
panic(err1)
}
}
// 确保所有内存数据刷到csv文件
writer.Flush()
}
func (s *Csv) LoadClientFromCsv() {
path := beego.AppPath + "/conf/clients.csv"
records, err := s.openFile(path)
if err != nil {
Fatalln("配置文件打开错误:", path)
}
var clients []*Client
// 将每一行数据保存到内存slice中
for _, item := range records {
post := &Client{
Id: GetIntNoErrByStr(item[0]),
VerifyKey: item[1],
Remark: item[2],
Status: GetBoolByStr(item[3]),
RateLimit: GetIntNoErrByStr(item[8]),
Cnf: &Config{
U: item[4],
P: item[5],
Crypt: GetBoolByStr(item[6]),
Compress: item[7],
},
}
if post.Id > s.ClientIncreaseId {
s.ClientIncreaseId = post.Id
}
if post.RateLimit > 0 {
post.Rate = NewRate(int64(post.RateLimit * 1024))
post.Rate.Start()
}
post.Flow = new(Flow)
post.Flow.FlowLimit = int64(GetIntNoErrByStr(item[9]))
clients = append(clients, post)
}
s.Clients = clients
}
func (s *Csv) LoadHostFromCsv() {
path := beego.AppPath + "/conf/hosts.csv"
records, err := s.openFile(path)
if err != nil {
Fatalln("配置文件打开错误:", path)
}
var hosts []*Host
// 将每一行数据保存到内存slice中
for _, item := range records {
post := &Host{
Host: item[0],
Target: item[1],
HeaderChange: item[3],
HostChange: item[4],
Remark: item[5],
}
if post.Client, err = s.GetClient(GetIntNoErrByStr(item[2])); err != nil {
continue
}
post.Flow = new(Flow)
hosts = append(hosts, post)
}
s.Hosts = hosts
}
func (s *Csv) DelHost(host string) error {
for k, v := range s.Hosts {
if v.Host == host {
s.Hosts = append(s.Hosts[:k], s.Hosts[k+1:]...)
s.StoreHostToCsv()
return nil
}
}
return errors.New("不存在")
}
func (s *Csv) NewHost(t *Host) {
t.Flow = new(Flow)
s.Hosts = append(s.Hosts, t)
s.StoreHostToCsv()
}
func (s *Csv) UpdateHost(t *Host) error {
for k, v := range s.Hosts {
if v.Host == t.Host {
s.Hosts = append(s.Hosts[:k], s.Hosts[k+1:]...)
s.Hosts = append(s.Hosts, t)
s.StoreHostToCsv()
return nil
}
}
return errors.New("不存在")
}
func (s *Csv) GetHost(start, length int, id int) ([]*Host, int) {
list := make([]*Host, 0)
var cnt int
for _, v := range s.Hosts {
if id == 0 || v.Client.Id == id {
cnt++
if start--; start < 0 {
if length--; length > 0 {
list = append(list, v)
}
}
}
}
return list, cnt
}
func (s *Csv) DelClient(id int) error {
for k, v := range s.Clients {
if v.Id == id {
s.Clients = append(s.Clients[:k], s.Clients[k+1:]...)
s.StoreClientsToCsv()
return nil
}
}
return errors.New("不存在")
}
func (s *Csv) NewClient(c *Client) {
s.Lock()
defer s.Unlock()
c.Flow = new(Flow)
s.Clients = append(s.Clients, c)
s.StoreClientsToCsv()
}
func (s *Csv) GetClientId() int {
s.Lock()
defer s.Unlock()
s.ClientIncreaseId++
return s.ClientIncreaseId
}
func (s *Csv) UpdateClient(t *Client) error {
s.Lock()
defer s.Unlock()
for _, v := range s.Clients {
if v.Id == t.Id {
v.Cnf = t.Cnf
v.VerifyKey = t.VerifyKey
v.Remark = t.Remark
v.RateLimit = t.RateLimit
v.Flow = t.Flow
v.Rate = t.Rate
s.StoreClientsToCsv()
return nil
}
}
return errors.New("不存在")
}
func (s *Csv) GetClientList(start, length int) ([]*Client, int) {
list := make([]*Client, 0)
var cnt int
for _, v := range s.Clients {
cnt++
if start--; start < 0 {
if length--; length > 0 {
list = append(list, v)
}
}
}
return list, cnt
}
func (s *Csv) GetClient(id int) (v *Client, err error) {
for _, v = range s.Clients {
if v.Id == id {
return
}
}
err = errors.New("未找到")
return
}
func (s *Csv) StoreClientsToCsv() {
// 创建文件
csvFile, err := os.Create(beego.AppPath + "/conf/clients.csv")
if err != nil {
Fatalln(err.Error())
}
defer csvFile.Close()
writer := csv.NewWriter(csvFile)
for _, client := range s.Clients {
record := []string{
strconv.Itoa(client.Id),
client.VerifyKey,
client.Remark,
strconv.FormatBool(client.Status),
client.Cnf.U,
client.Cnf.P,
GetStrByBool(client.Cnf.Crypt),
client.Cnf.Compress,
strconv.Itoa(client.RateLimit),
strconv.Itoa(int(client.Flow.FlowLimit)),
}
err := writer.Write(record)
if err != nil {
Fatalln(err.Error())
}
}
writer.Flush()
}
//init csv from file
func GetCsvDb() *Csv {
once.Do(func() {
CsvDb = NewCsv()
CsvDb.Init()
})
return CsvDb
}
+134
View File
@@ -0,0 +1,134 @@
package utils
import (
"net"
"strings"
"sync"
)
type Link struct {
Id int //id
ConnType string //连接类型
Host string //目标
En int //加密
De int //解密
Crypt bool //加密
Conn *Conn
Flow *Flow
UdpListener *net.UDPConn
Rate *Rate
UdpRemoteAddr *net.UDPAddr
}
func NewLink(id int, connType string, host string, en, de int, crypt bool, conn *Conn, flow *Flow, udpListener *net.UDPConn, rate *Rate, UdpRemoteAddr *net.UDPAddr) *Link {
return &Link{
Id: id,
ConnType: connType,
Host: host,
En: en,
De: de,
Crypt: crypt,
Conn: conn,
Flow: flow,
UdpListener: udpListener,
Rate: rate,
UdpRemoteAddr: UdpRemoteAddr,
}
}
type Flow struct {
ExportFlow int64 //出口流量
InletFlow int64 //入口流量
FlowLimit int64 //流量限制,出口+入口 /M
sync.RWMutex
}
func (s *Flow) Add(in, out int) {
s.Lock()
defer s.Unlock()
s.InletFlow += int64(in)
s.ExportFlow += int64(out)
}
type Client struct {
Cnf *Config
Id int //id
VerifyKey string //验证密钥
Addr string //客户端ip地址
Remark string //备注
Status bool //是否开启
IsConnect bool //是否连接
RateLimit int //速度限制 /kb
Flow *Flow //流量
Rate *Rate //速度控制
id int
sync.RWMutex
}
func (s *Client) GetId() int {
s.Lock()
defer s.Unlock()
s.id++
return s.id
}
type Tunnel struct {
Id int //Id
TcpPort int //服务端与客户端通信端口
Mode string //启动方式
Target string //目标
Status bool //是否开启
Client *Client //所属客户端id
Flow *Flow
Config *Config
UseClientCnf bool //是否继承客户端配置
Remark string //备注
}
type Config struct {
U string //socks5验证用户名
P string //socks5验证密码
Compress string //压缩方式
Crypt bool //是否加密
CompressEncode int //加密方式
CompressDecode int //解密方式
}
type Host struct {
Host string //启动方式
Target string //目标
HeaderChange string //host修改
HostChange string //host修改
Flow *Flow
Client *Client
Remark string //备注
NowIndex int
TargetArr []string
sync.RWMutex
}
func (s *Host) GetRandomTarget() string {
if s.TargetArr == nil {
s.TargetArr = strings.Split(s.Target, "\n")
}
s.Lock()
defer s.Unlock()
if s.NowIndex >= len(s.TargetArr)-1 {
s.NowIndex = 0
} else {
s.NowIndex++
}
return s.TargetArr[s.NowIndex]
}
//深拷贝Config
func DeepCopyConfig(c *Config) *Config {
return &Config{
U: c.U,
P: c.P,
Compress: c.Compress,
Crypt: c.Crypt,
CompressEncode: c.CompressEncode,
CompressDecode: c.CompressDecode,
}
}
+45
View File
@@ -0,0 +1,45 @@
package utils
import (
"github.com/astaxie/beego"
"log"
"os"
"runtime"
)
var Log *log.Logger
func InitLogFile(f string, isStdout bool) {
var prefix string
if !isStdout {
logFile, err := os.OpenFile(beego.AppPath+"/proxy_"+f+"_log.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
if err != nil {
log.Fatalln("open file error !")
}
if runtime.GOOS == "windows" {
prefix = "\r\n"
}
Log = log.New(logFile, prefix, log.Ldate|log.Ltime)
} else {
Log = log.New(os.Stdout, "", log.Ldate|log.Ltime)
}
}
func Println(v ...interface{}) {
Log.Println(v ...)
}
func Fatalln(v ...interface{}) {
Log.SetPrefix("error ")
Log.Fatalln(v ...)
Log.SetPrefix("")
}
func Fatalf(format string, v ...interface{}) {
Log.SetPrefix("error ")
Log.Fatalf(format, v...)
Log.SetPrefix("")
}
func Printf(format string, v ...interface{}) {
Log.Printf(format, v...)
}
+43
View File
@@ -0,0 +1,43 @@
package utils
import (
"sync"
)
const poolSize = 64 * 1024
const poolSizeSmall = 100
const poolSizeUdp = 1472
const poolSizeCopy = 32 * 1024
var BufPool = sync.Pool{
New: func() interface{} {
return make([]byte, poolSize)
},
}
var BufPoolUdp = sync.Pool{
New: func() interface{} {
return make([]byte, poolSizeUdp)
},
}
var BufPoolMax = sync.Pool{
New: func() interface{} {
return make([]byte, poolSize)
},
}
var BufPoolSmall = sync.Pool{
New: func() interface{} {
return make([]byte, poolSizeSmall)
},
}
var BufPoolCopy = sync.Pool{
New: func() interface{} {
return make([]byte, poolSizeCopy)
},
}
func PutBufPoolCopy(buf []byte) {
if cap(buf) == poolSizeCopy {
BufPoolCopy.Put(buf[:poolSizeCopy])
}
}
+74
View File
@@ -0,0 +1,74 @@
package utils
import (
"sync/atomic"
"time"
)
type Rate struct {
bucketSize int64 //木桶容量
bucketSurplusSize int64 //当前桶中体积
bucketAddSize int64 //每次加水大小
stopChan chan bool //停止
}
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 (s.bucketSize - s.bucketSurplusSize) < s.bucketAddSize {
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:
s.add(s.bucketAddSize)
case <-s.stopChan:
ticker.Stop()
return
}
}
}
Executable
+163
View File
@@ -0,0 +1,163 @@
package utils
import (
"encoding/base64"
"io/ioutil"
"net"
"net/http"
"os"
"regexp"
"strconv"
"strings"
)
const (
COMPRESS_NONE_ENCODE = iota
COMPRESS_NONE_DECODE
COMPRESS_SNAPY_ENCODE
COMPRESS_SNAPY_DECODE
VERIFY_EER = "vkey"
WORK_MAIN = "main"
WORK_CHAN = "chan"
RES_SIGN = "sign"
RES_MSG = "msg0"
RES_CLOSE = "clse"
NEW_CONN = "conn" //新连接标志
CONN_SUCCESS = "sucs"
CONN_TCP = "tcp"
CONN_UDP = "udp"
UnauthorizedBytes = `HTTP/1.1 401 Unauthorized
Content-Type: text/plain; charset=utf-8
WWW-Authenticate: Basic realm="easyProxy"
401 Unauthorized`
IO_EOF = "PROXYEOF"
ConnectionFailBytes = `HTTP/1.1 404 Not Found
`
)
//判断压缩方式
func GetCompressType(compress string) (int, int) {
switch compress {
case "":
return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
case "snappy":
return COMPRESS_SNAPY_DECODE, COMPRESS_SNAPY_ENCODE
default:
Fatalln("数据压缩格式错误")
}
return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
}
//通过host获取对应的ip地址
func GetHostByName(hostname string) string {
if !DomainCheck(hostname) {
return hostname
}
ips, _ := net.LookupIP(hostname)
if ips != nil {
for _, v := range ips {
if v.To4() != nil {
return v.String()
}
}
}
return ""
}
//检查是否是域名
func DomainCheck(domain string) bool {
var match bool
IsLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}(/)"
NotLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}"
match, _ = regexp.MatchString(IsLine, domain)
if !match {
match, _ = regexp.MatchString(NotLine, domain)
}
return match
}
//检查basic认证
func CheckAuth(r *http.Request, user, passwd string) bool {
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(s) != 2 {
return false
}
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
return false
}
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
return false
}
return pair[0] == user && pair[1] == passwd
}
//get bool by str
func GetBoolByStr(s string) bool {
switch s {
case "1", "true":
return true
}
return false
}
//get str by bool
func GetStrByBool(b bool) string {
if b {
return "1"
}
return "0"
}
//int
func GetIntNoErrByStr(str string) int {
i, _ := strconv.Atoi(str)
return i
}
//简单的一个校验值
func Getverifyval(vkey string) string {
return Md5(vkey)
}
func ChangeHostAndHeader(r *http.Request, host string, header string, addr string) {
if host != "" {
r.Host = host
}
if header != "" {
h := strings.Split(header, "\n")
for _, v := range h {
hd := strings.Split(v, ":")
if len(hd) == 2 {
r.Header.Set(hd[0], hd[1])
}
}
}
addr = strings.Split(addr, ":")[0]
r.Header.Set("X-Forwarded-For", addr)
r.Header.Set("X-Real-IP", addr)
}
func ReadAllFromFile(filePath string) ([]byte, error) {
f, err := os.Open(filePath)
if err != nil {
return nil, err
}
return ioutil.ReadAll(f)
}
// FileExists reports whether the named file or directory exists.
func FileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
+126
View File
@@ -0,0 +1,126 @@
package controllers
import (
"github.com/astaxie/beego"
"github.com/cnlh/easyProxy/server"
"github.com/cnlh/easyProxy/utils"
"strconv"
"strings"
)
type BaseController struct {
beego.Controller
controllerName string
actionName string
}
//初始化参数
func (s *BaseController) Prepare() {
controllerName, actionName := s.GetControllerAndAction()
s.controllerName = strings.ToLower(controllerName[0 : len(controllerName)-10])
s.actionName = strings.ToLower(actionName)
arr := strings.Split(s.Ctx.Request.RemoteAddr, ":")
if len(arr) > 0 && arr[0] != beego.AppConfig.String("authip") {
if s.GetSession("auth") != true {
s.Redirect("/login/index", 302)
}
}
}
//加载模板
func (s *BaseController) display(tpl ...string) {
var tplname string
if s.Data["menu"] == nil {
s.Data["menu"] = s.actionName
}
if len(tpl) > 0 {
tplname = strings.Join([]string{tpl[0], "html"}, ".")
} else {
tplname = s.controllerName + "/" + s.actionName + ".html"
}
ip := s.Ctx.Request.Host
if strings.LastIndex(ip, ":") > 0 {
arr := strings.Split(utils.GetHostByName(ip), ":")
s.Data["ip"] = arr[0]
}
s.Data["p"] = server.Bridge.TunnelPort
s.Data["proxyPort"] = beego.AppConfig.String("hostPort")
s.Layout = "public/layout.html"
s.TplName = tplname
}
//错误
func (s *BaseController) error() {
s.Layout = "public/layout.html"
s.TplName = "public/error.html"
}
//去掉没有err返回值的int
func (s *BaseController) GetIntNoErr(key string, def ...int) int {
strv := s.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
return def[0]
}
val, _ := strconv.Atoi(strv)
return val
}
//获取去掉错误的bool值
func (s *BaseController) GetBoolNoErr(key string, def ...bool) bool {
strv := s.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
return def[0]
}
val, _ := strconv.ParseBool(strv)
return val
}
//ajax正确返回
func (s *BaseController) AjaxOk(str string) {
s.Data["json"] = ajax(str, 1)
s.ServeJSON()
s.StopRun()
}
//ajax错误返回
func (s *BaseController) AjaxErr(str string) {
s.Data["json"] = ajax(str, 0)
s.ServeJSON()
s.StopRun()
}
//组装ajax
func ajax(str string, status int) (map[string]interface{}) {
json := make(map[string]interface{})
json["status"] = status
json["msg"] = str
return json
}
//ajax table返回
func (s *BaseController) AjaxTable(list interface{}, cnt int, recordsTotal int) {
json := make(map[string]interface{})
json["data"] = list
json["draw"] = s.GetIntNoErr("draw")
json["err"] = ""
json["recordsTotal"] = recordsTotal
json["recordsFiltered"] = cnt
s.Data["json"] = json
s.ServeJSON()
s.StopRun()
}
//ajax table参数
func (s *BaseController) GetAjaxParams() (start, limit int) {
s.Ctx.Input.Bind(&start, "start")
s.Ctx.Input.Bind(&limit, "length")
return
}
func (s *BaseController) SetInfo(name string) {
s.Data["name"] = name
}
func (s *BaseController) SetType(name string) {
s.Data["type"] = name
}
+132
View File
@@ -0,0 +1,132 @@
package controllers
import (
"github.com/cnlh/easyProxy/server"
"github.com/cnlh/easyProxy/utils"
)
type ClientController struct {
BaseController
}
func (s *ClientController) List() {
if s.Ctx.Request.Method == "GET" {
s.Data["menu"] = "client"
s.SetInfo("客户端管理")
s.display("client/list")
return
}
start, length := s.GetAjaxParams()
list, cnt := server.GetClientList(start, length)
s.AjaxTable(list, cnt, cnt)
}
//添加客户端
func (s *ClientController) Add() {
if s.Ctx.Request.Method == "GET" {
s.Data["menu"] = "client"
s.SetInfo("新增")
s.display()
} else {
t := &utils.Client{
VerifyKey: utils.GetRandomString(16),
Id: server.CsvDb.GetClientId(),
Status: true,
Remark: s.GetString("remark"),
Cnf: &utils.Config{
U: s.GetString("u"),
P: s.GetString("p"),
Compress: s.GetString("compress"),
Crypt: s.GetBoolNoErr("crypt"),
},
RateLimit: s.GetIntNoErr("rate_limit"),
Flow: &utils.Flow{
ExportFlow: 0,
InletFlow: 0,
FlowLimit: int64(s.GetIntNoErr("flow_limit")),
},
}
if t.RateLimit > 0 {
t.Rate = utils.NewRate(int64(t.RateLimit * 1024))
t.Rate.Start()
}
server.CsvDb.NewClient(t)
s.AjaxOk("添加成功")
}
}
func (s *ClientController) GetClient() {
if s.Ctx.Request.Method == "POST" {
id := s.GetIntNoErr("id")
data := make(map[string]interface{})
if c, err := server.CsvDb.GetClient(id); err != nil {
data["code"] = 0
} else {
data["code"] = 1
data["data"] = c
}
s.Data["json"] = data
s.ServeJSON()
}
}
//修改客户端
func (s *ClientController) Edit() {
id := s.GetIntNoErr("id")
if s.Ctx.Request.Method == "GET" {
s.Data["menu"] = "client"
if c, err := server.CsvDb.GetClient(id); err != nil {
s.error()
} else {
s.Data["c"] = c
}
s.SetInfo("修改")
s.display()
} else {
if c, err := server.CsvDb.GetClient(id); err != nil {
s.error()
} else {
c.Remark = s.GetString("remark")
c.Cnf.U = s.GetString("u")
c.Cnf.P = s.GetString("p")
c.Cnf.Compress = s.GetString("compress")
c.Cnf.Crypt = s.GetBoolNoErr("crypt")
c.Flow.FlowLimit = int64(s.GetIntNoErr("flow_limit"))
c.RateLimit = s.GetIntNoErr("rate_limit")
if c.Rate != nil {
c.Rate.Stop()
}
if c.RateLimit > 0 {
c.Rate = utils.NewRate(int64(c.RateLimit * 1024))
c.Rate.Start()
} else {
c.Rate = nil
}
server.CsvDb.UpdateClient(c)
}
s.AjaxOk("修改成功")
}
}
//更改状态
func (s *ClientController) ChangeStatus() {
id := s.GetIntNoErr("id")
if client, err := server.CsvDb.GetClient(id); err == nil {
client.Status = s.GetBoolNoErr("status")
if client.Status == false {
server.DelClientConnect(client.Id)
}
s.AjaxOk("修改成功")
}
s.AjaxErr("修改失败")
}
//删除客户端
func (s *ClientController) Del() {
id := s.GetIntNoErr("id")
if err := server.CsvDb.DelClient(id); err != nil {
s.AjaxErr("删除失败")
}
server.DelTunnelAndHostByClientId(id)
server.DelClientConnect(id)
s.AjaxOk("删除成功")
}
+262
View File
@@ -0,0 +1,262 @@
package controllers
import (
"github.com/cnlh/easyProxy/server"
"github.com/cnlh/easyProxy/utils"
)
type IndexController struct {
BaseController
}
func (s *IndexController) Index() {
s.Data["data"] = server.GetDashboardData()
s.SetInfo("dashboard")
s.display("index/index")
}
func (s *IndexController) Help() {
s.SetInfo("使用说明")
s.display("index/help")
}
func (s *IndexController) Tcp() {
s.SetInfo("tcp隧道管理")
s.SetType("tunnelServer")
s.display("index/list")
}
func (s *IndexController) Udp() {
s.SetInfo("udp隧道管理")
s.SetType("udpServer")
s.display("index/list")
}
func (s *IndexController) Socks5() {
s.SetInfo("socks5管理")
s.SetType("socks5Server")
s.display("index/list")
}
func (s *IndexController) Http() {
s.SetInfo("http代理管理")
s.SetType("httpProxyServer")
s.display("index/list")
}
func (s *IndexController) Host() {
s.SetInfo("host模式管理")
s.SetType("hostServer")
s.display("index/list")
}
func (s *IndexController) All() {
s.Data["menu"] = "client"
clientId := s.GetString("client_id")
s.Data["client_id"] = clientId
s.SetInfo("客户端" + clientId + "的所有隧道")
s.display("index/list")
}
func (s *IndexController) GetTunnel() {
start, length := s.GetAjaxParams()
taskType := s.GetString("type")
clientId := s.GetIntNoErr("client_id")
list, cnt := server.GetTunnel(start, length, taskType, clientId)
s.AjaxTable(list, cnt, cnt)
}
func (s *IndexController) Add() {
if s.Ctx.Request.Method == "GET" {
s.Data["type"] = s.GetString("type")
s.Data["client_id"] = s.GetString("client_id")
s.SetInfo("新增")
s.display()
} else {
t := &utils.Tunnel{
TcpPort: s.GetIntNoErr("port"),
Mode: s.GetString("type"),
Target: s.GetString("target"),
Config: &utils.Config{
U: s.GetString("u"),
P: s.GetString("p"),
Compress: s.GetString("compress"),
Crypt: s.GetBoolNoErr("crypt"),
},
Id: server.CsvDb.GetTaskId(),
UseClientCnf: s.GetBoolNoErr("use_client"),
Status: true,
Remark: s.GetString("remark"),
Flow: &utils.Flow{},
}
var err error
if t.Client, err = server.CsvDb.GetClient(s.GetIntNoErr("client_id")); err != nil {
s.AjaxErr(err.Error())
}
server.CsvDb.NewTask(t)
if err := server.AddTask(t); err != nil {
s.AjaxErr(err.Error())
} else {
s.AjaxOk("添加成功")
}
}
}
func (s *IndexController) GetOneTunnel() {
id := s.GetIntNoErr("id")
data := make(map[string]interface{})
if t, err := server.CsvDb.GetTask(id); err != nil {
data["code"] = 0
} else {
data["code"] = 1
data["data"] = t
}
s.Data["json"] = data
s.ServeJSON()
}
func (s *IndexController) Edit() {
id := s.GetIntNoErr("id")
if s.Ctx.Request.Method == "GET" {
if t, err := server.CsvDb.GetTask(id); err != nil {
s.error()
} else {
s.Data["t"] = t
}
s.SetInfo("修改")
s.display()
} else {
if t, err := server.CsvDb.GetTask(id); err != nil {
s.error()
} else {
t.TcpPort = s.GetIntNoErr("port")
t.Mode = s.GetString("type")
t.Target = s.GetString("target")
t.Id = id
t.Client.Id = s.GetIntNoErr("client_id")
t.Config.U = s.GetString("u")
t.Config.P = s.GetString("p")
t.Config.Compress = s.GetString("compress")
t.Config.Crypt = s.GetBoolNoErr("crypt")
t.UseClientCnf = s.GetBoolNoErr("use_client")
t.Remark = s.GetString("remark")
if t.Client, err = server.CsvDb.GetClient(s.GetIntNoErr("client_id")); err != nil {
s.AjaxErr("修改失败")
}
server.CsvDb.UpdateTask(t)
}
s.AjaxOk("修改成功")
}
}
func (s *IndexController) Stop() {
id := s.GetIntNoErr("id")
if err := server.StopServer(id); err != nil {
s.AjaxErr("停止失败")
}
s.AjaxOk("停止成功")
}
func (s *IndexController) Del() {
id := s.GetIntNoErr("id")
if err := server.DelTask(id); err != nil {
s.AjaxErr("删除失败")
}
s.AjaxOk("删除成功")
}
func (s *IndexController) Start() {
id := s.GetIntNoErr("id")
if err := server.StartTask(id); err != nil {
s.AjaxErr("开启失败")
}
s.AjaxOk("开启成功")
}
func (s *IndexController) HostList() {
if s.Ctx.Request.Method == "GET" {
s.Data["client_id"] = s.GetString("client_id")
s.Data["menu"] = "host"
s.SetInfo("域名列表")
s.display("index/hlist")
} else {
start, length := s.GetAjaxParams()
clientId := s.GetIntNoErr("client_id")
list, cnt := server.CsvDb.GetHost(start, length, clientId)
s.AjaxTable(list, cnt, cnt)
}
}
func (s *IndexController) GetHost() {
if s.Ctx.Request.Method == "POST" {
data := make(map[string]interface{})
if h, err := server.GetInfoByHost(s.GetString("host")); err != nil {
data["code"] = 0
} else {
data["data"] = h
data["code"] = 1
}
s.Data["json"] = data
s.ServeJSON()
}
}
func (s *IndexController) DelHost() {
host := s.GetString("host")
if err := server.CsvDb.DelHost(host); err != nil {
s.AjaxErr("删除失败")
}
s.AjaxOk("删除成功")
}
func (s *IndexController) AddHost() {
if s.Ctx.Request.Method == "GET" {
s.Data["client_id"] = s.GetString("client_id")
s.Data["menu"] = "host"
s.SetInfo("新增")
s.display("index/hadd")
} else {
h := &utils.Host{
Host: s.GetString("host"),
Target: s.GetString("target"),
HeaderChange: s.GetString("header"),
HostChange: s.GetString("hostchange"),
Remark: s.GetString("remark"),
Flow: &utils.Flow{},
}
var err error
if h.Client, err = server.CsvDb.GetClient(s.GetIntNoErr("client_id")); err != nil {
s.AjaxErr("添加失败")
}
server.CsvDb.NewHost(h)
s.AjaxOk("添加成功")
}
}
func (s *IndexController) EditHost() {
host := s.GetString("host")
if s.Ctx.Request.Method == "GET" {
s.Data["menu"] = "host"
if h, err := server.GetInfoByHost(host); err != nil {
s.error()
} else {
s.Data["h"] = h
}
s.SetInfo("修改")
s.display("index/hedit")
} else {
if h, err := server.GetInfoByHost(host); err != nil {
s.error()
} else {
h.Host = s.GetString("nhost")
h.Target = s.GetString("target")
h.HeaderChange = s.GetString("header")
h.HostChange = s.GetString("hostchange")
h.Remark = s.GetString("remark")
h.TargetArr = nil
server.CsvDb.UpdateHost(h)
var err error
if h.Client, err = server.CsvDb.GetClient(s.GetIntNoErr("client_id")); err != nil {
s.AjaxErr("修改失败")
}
}
s.AjaxOk("修改成功")
}
}
+27
View File
@@ -0,0 +1,27 @@
package controllers
import (
"github.com/astaxie/beego"
)
type LoginController struct {
beego.Controller
}
func (self *LoginController) Index() {
self.TplName = "login/index.html"
}
func (self *LoginController) Verify() {
if self.GetString("psd") == beego.AppConfig.String("password") {
self.SetSession("auth", true)
self.Data["json"] = map[string]interface{}{"status": 1, "msg": "验证成功"}
self.ServeJSON()
} else {
self.Data["json"] = map[string]interface{}{"status": 0, "msg": "验证失败"}
self.ServeJSON()
}
}
func (self *LoginController) Out() {
self.SetSession("auth", false)
self.Redirect("/login/index", 302)
}
+13
View File
@@ -0,0 +1,13 @@
package routers
import (
"github.com/astaxie/beego"
"github.com/cnlh/easyProxy/web/controllers"
)
func init() {
beego.Router("/", &controllers.IndexController{}, "*:Index")
beego.AutoRouter(&controllers.IndexController{})
beego.AutoRouter(&controllers.LoginController{})
beego.AutoRouter(&controllers.ClientController{})
}
+4
View File
File diff suppressed because one or more lines are too long
+15240
View File
File diff suppressed because it is too large Load Diff
BIN
View File
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 434 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

+3477
View File
File diff suppressed because it is too large Load Diff
+234
View File
File diff suppressed because one or more lines are too long
+48
View File
@@ -0,0 +1,48 @@
(function () {
"use strict";
var treeviewMenu = $('.app-menu');
// Toggle Sidebar
$('[data-toggle="sidebar"]').click(function (event) {
event.preventDefault();
$('.app').toggleClass('sidenav-toggled');
});
// Activate sidebar treeview toggle
$("[data-toggle='treeview']").click(function (event) {
event.preventDefault();
if (!$(this).parent().hasClass('is-expanded')) {
treeviewMenu.find("[data-toggle='treeview']").parent().removeClass('is-expanded');
}
$(this).parent().toggleClass('is-expanded');
});
// Set initial active toggle
$("[data-toggle='treeview.'].is-expanded").parent().toggleClass('is-expanded');
//Activate bootstrip tooltips
// $("[data-toggle='tooltip']").tooltip();
})();
function change(limit) {
var size = "";
if (limit < 0.1 * 1024) {
size = limit.toFixed(2) + "B"
} else if (limit < 0.1 * 1024 * 1024) {
size = (limit / 1024).toFixed(2) + "KB"
} else if (limit < 0.1 * 1024 * 1024 * 1024) {
size = (limit / (1024 * 1024)).toFixed(2) + "MB"
} else {
size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB"
}
var sizeStr = size + "";
var index = sizeStr.indexOf(".");
var dou = sizeStr.substr(index + 1, 2)
if (dou == "00") {
return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
}
return size;
}
+10
View File
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>easyProxy error</title>
</head>
<body>
404 not found,power by easyProxy
</body>
</html>
+68
View File
@@ -0,0 +1,68 @@
<div class="row tile">
<div class="col-md-6 col-md-auto">
<div>
<h3 class="tile-title">添加</h3>
<div class="tile-body">
<form>
<div class="form-group" id="target">
<label class="control-label">备注</label>
<input class="form-control" type="text" name="remark" placeholder="客户端备注">
</div>
<div class="form-group" id="flow_limit">
<label class="control-label">流量限制(单位:M,为空不限制)</label>
<input class="form-control" type="text" name="flow_limit" placeholder="为空不限制">
</div>
<div class="form-group" id="rate_limit">
<label class="control-label">速度限制(单位:KB,为空不限制)</label>
<input class="form-control" type="text" name="rate_limit" placeholder="为空不限制">
</div>
<div class="form-group" id="u">
<label class="control-label">验证用户名(仅socks5,web穿透支持)</label>
<input class="form-control" type="text" name="u" placeholder="不填则无需验证">
</div>
<div class="form-group" id="p">
<label class="control-label">验证密码(仅socks5,web穿透支持)</label>
<input class="form-control" type="text" name="p" placeholder="不填则无需验证">
</div>
<div class="form-group" id="compress">
<label class="control-label">数据压缩方式</label>
<select class="form-control" name="compress">
<option value="">不压缩</option>
<option value="snappy">snappy</option>
</select>
</div>
<div class="form-group" id="compress">
<label class="control-label">是否加密传输</label>
<select class="form-control" name="crypt">
<option value="0">不加密</option>
<option value="1">加密</option>
</select>
</div>
</form>
</div>
<div class="tile-footer">
&nbsp;&nbsp;<button class="btn btn-success" href="#" id="add"><i
class="fa fa-fw fa-lg fa-eye"></i>添加
</button>
</div>
</div>
</div>
</div>
</main>
<script>
$(function () {
$("#add").on("click", function () {
$.ajax({
type: "POST",
url: "/client/add",
data: $("form").serializeArray(),
success: function (res) {
alert(res.msg)
if (res.status) {
history.back(-1)
}
}
})
})
})
</script>
+74
View File
@@ -0,0 +1,74 @@
<div class="row tile">
<div class="col-md-6 col-md-auto">
<div>
<h3 class="tile-title">添加</h3>
<div class="tile-body">
<form>
<input type="hidden" name="id" value="{{.c.Id}}">
<div class="form-group" id="target">
<label class="control-label">备注</label>
<input class="form-control" value="{{.c.Remark}}" type="text" name="remark" placeholder="客户端备注">
</div>
<div class="form-group" id="flow_limit">
<label class="control-label">流量限制(单位:M,为空不限制)</label>
<input class="form-control" value="{{.c.Flow.FlowLimit}}" type="text" name="flow_limit"
placeholder="为空不限制">
</div>
<div class="form-group" id="rate_limit">
<label class="control-label">速度限制(单位:KB,为空不限制)</label>
<input class="form-control" value="{{.c.RateLimit}}" type="text" name="rate_limit"
placeholder="为空不限制">
</div>
<div class="form-group" id="u">
<label class="control-label">验证用户名(仅socks5,web穿透支持)</label>
<input class="form-control" value="{{.c.Cnf.U}}" type="text" name="u"
placeholder="不填则无需验证">
</div>
<div class="form-group" id="p">
<label class="control-label">验证密码(仅socks5,web穿透支持)</label>
<input class="form-control" value="{{.c.Cnf.P}}" type="text" name="p"
placeholder="不填则无需验证">
</div>
<div class="form-group" id="compress">
<label class="control-label">数据压缩方式(所有模式均支持)</label>
<select class="form-control" name="compress">
<option {{if eq "" .c.Cnf.Compress}}selected{{end}} value="">不压缩</option>
<option {{if eq "snappy" .c.Cnf.Compress}}selected{{end}} value="snappy">snappy压缩</option>
</select>
</div>
<div class="form-group" id="compress">
<label class="control-label">是否加密传输(所有模式均支持)</label>
<select class="form-control" name="crypt">
<option {{if eq false .c.Cnf.Crypt}}selected{{end}} value="0">不加密</option>
<option {{if eq true .c.Cnf.Crypt}}selected{{end}} value="1">加密</option>
</select>
</div>
</form>
</div>
<div class="tile-footer">
&nbsp;&nbsp;<button class="btn btn-success" href="#" id="add"><i
class="fa fa-fw fa-lg fa-eye"></i>保存
</button>
</div>
</div>
</div>
</div>
</main>
<script>
$(function () {
$("#add").on("click", function () {
$.ajax({
type: "POST",
url: "/client/edit",
data: $("form").serializeArray(),
success: function (res) {
alert(res.msg)
if (res.status) {
history.back(-1)
}
}
})
})
})
</script>
+222
View File
@@ -0,0 +1,222 @@
<div class="row">
<div class="col-md-12">
<div class="tile">
<div class="tile-body">
<table class="table table-hover table-bordered" id="sampleTable">
<thead>
<tr>
<th>Id</th>
<th>验证密钥</th>
<th>客户端地址</th>
<th>备注</th>
<th>压缩方式</th>
<th>加密</th>
<th>用户名</th>
<th>密码</th>
<th>状态</th>
<th>客户端连接状态</th>
<th>出口流量</th>
<th>入口流量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</main>
<script type="text/javascript">
function del(id) {
if (confirm("确定要删除数据吗?")) {
$.ajax({
type: "POST",
url: "/client/del",
data: {"id": id},
success: function (res) {
alert(res.msg)
if (res.status) {
document.location.reload();
}
}
})
}
}
function start(id) {
if (confirm("确定要开始任务吗?")) {
$.ajax({
type: "POST",
url: "/client/changestatus",
data: {"id": id, "status": 1},
success: function (res) {
alert(res.msg)
if (res.status) {
document.location.reload();
}
}
})
}
}
function stop(id) {
if (confirm("确定要暂停吗?")) {
$.ajax({
type: "POST",
url: "/client/changestatus",
data: {
"id": id, "status": 0
},
success:
function (res) {
alert(res.msg)
if (res.status) {
document.location.reload();
}
}
})
}
}
function edit(id) {
window.location.href = "/client/edit?id=" + id
}
function add() {
window.location.href = "/client/add"
}
function show_tunnel_list(id) {
window.location.href = "/index/all?client_id=" + id
}
function show_host_list(id) {
window.location.href = "/index/hostlist?client_id=" + id
}
$(document)
.ready(function () {
var table = $('#sampleTable').DataTable({
responsive: {
details: {
display: $.fn.dataTable.Responsive.display.childRowImmediate
}
},
dom: 'Bfrtip',
processing: true,
serverSide: true,
autoWidth: false,
ordering: false,
ajax: {
url: '/client/list',
type: 'POST'
},
dom: '<"top"fl><"toolbar">rt<"bottom"ip><"clear">',
columns: [ //这个是显示到界面上的个数据 格式为 {data:'显示的字段名'}
{data: 'Id'},
{data: 'VerifyKey'},
{data: "Addr"},
{data: "Remark"},
{data: "Addr"},
{data: "Addr"},
{data: "Addr"},
{data: "Remark"},
{data: "Status"},
{data: "IsConnect"},
{data: "Addr"},
{data: "Addr"},
{data: ""},
],
bFilter: false,
columnDefs: [{
targets: -1,
render: function (data, type, row, meta) {
if (row.Status == true) {
btn = "<button onclick=\"stop('" + row.Id + "')\" class=\"btn btn-secondary btn-sm\" type=\"button\">关闭</button>"
} else {
btn = "<button onclick=\"start('" + row.Id + "')\" class=\"btn btn-success btn-sm\" type=\"button\">打开</button>"
}
btn_del = '<button onclick="del(\'' + row.Id + '\')" class="btn btn-danger btn-sm">删除</button> '
btn_edit = '<button onclick="edit(\'' + row.Id + '\')" class="btn btn-primary btn-sm">查看编辑</button> '
btn_list = '<button onclick="show_tunnel_list(\'' + row.Id + '\')" class="btn btn-info btn-sm">隧道</button> '
btn_host = '<button onclick="show_host_list(\'' + row.Id + '\')" class="btn btn-info btn-sm">域名</button> '
return '<div class="btn-group" role="group" aria-label="..."> ' + btn + btn_del + btn_edit + btn_host + btn_list + '</div>'
}
},
{
targets: -5,
render: function (data, type, row, meta) {
if (data == false) {
return "<span class=\"badge badge-pill badge-secondary\">暂停</span>"
} else {
return "<span class=\"badge badge-pill badge-success\">正常</span>"
}
}
},
{
targets: -4,
render: function (data, type, row, meta) {
if (data == false) {
return "<span class=\"badge badge-pill badge-secondary\">未连接</span>"
} else {
return "<span class=\"badge badge-pill badge-success\">已连接</span>"
}
}
},
{
targets: -2,
render: function (data, type, row, meta) {
return change(row.Flow.InletFlow)
}
},
{
targets: -3,
render: function (data, type, row, meta) {
return change(row.Flow.ExportFlow)
}
},
{
targets: -6,
render: function (data, type, row, meta) {
return row.Cnf.P
}
},
{
targets: -7,
render: function (data, type, row, meta) {
return row.Cnf.U
}
}
,
{
targets: -8,
render: function (data, type, row, meta) {
if (row.Cnf.Crypt == "0") {
return "不加密"
} else {
return "加密"
}
}
}
,
{
targets: -9,
render: function (data, type, row, meta) {
return row.Cnf.Compress
}
}
],
buttons: []
});
$("#sampleTable_length").html('<button class="btn btn-primary" onclick="add()" type="button">新增</button>')
})
;
</script>
+138
View File
@@ -0,0 +1,138 @@
<div class="row tile">
<div class="col-lg-12">
<div class="bs-component">
<div class="alert alert-dismissible alert-success">
<button class="close" type="button" data-dismiss="alert">×</button>
<span id="info"></span>
</div>
</div>
</div>
<div class="col-md-6 col-md-auto">
<div>
<h3 class="tile-title">添加</h3>
<div class="tile-body">
<form>
<div class="form-group">
<label class="control-label">模式</label>
<select class="form-control" name="type" id="type">
<option {{if eq "tunnelServer" .type}}selected{{end}} value="tunnelServer">tcp隧道</option>
<option {{if eq "udpServer" .type}}selected{{end}} value="udpServer">udp隧道</option>
<option {{if eq "socks5Server" .type}}selected{{end}} value="socks5Server">socks5代理</option>
<option {{if eq "httpProxyServer" .type}}selected{{end}} value="httpProxyServer">http代理
</select>
</div>
<div class="form-group">
<label class="control-label">备注</label>
<input class="form-control" type="text" name="remark" placeholder="备注">
</div>
<div class="form-group" id="port">
<label class="control-label">监听的端口</label>
<input class="form-control" type="text" name="port" placeholder="公网服务器对外访问端口,例如8024">
</div>
<div class="form-group" id="target">
<label class="control-label">内网目标(ip:端口)</label>
<input class="form-control" type="text" name="target" placeholder="内网代理地址,例如10.1.50.203:22">
</div>
<div class="form-group" id="client_id">
<label class="control-label">客户端ID</label>
<input value="{{.client_id}}" class="form-control" type="text" name="client_id"
placeholder="客户端id">
</div>
<div class="form-group" id="use_client">
<label class="control-label">是否使用客户端配置</label>
<select class="form-control" name="use_client">
<option value="1">是</option>
<option value="0">否</option>
</select>
</div>
<div class="form-group" id="compress">
<label class="control-label">数据压缩方式</label>
<select class="form-control" name="compress">
<option value="">不压缩</option>
<option value="snappy">snappy</option>
</select>
</div>
<div class="form-group" id="crypt">
<label class="control-label">是否加密传输</label>
<select class="form-control" name="crypt">
<option value="0">不加密</option>
<option value="1">加密</option>
</select>
</div>
<div class="form-group" id="u">
<label class="control-label">验证用户名(仅socks5,web穿透支持)</label>
<input class="form-control" type="text" name="u" placeholder="不填则无需验证">
</div>
<div class="form-group" id="p">
<label class="control-label">验证密码(仅socks5,web穿透支持)</label>
<input class="form-control" type="text" name="p" placeholder="不填则无需验证">
</div>
</form>
</div>
<div class="tile-footer">
&nbsp;&nbsp;<button class="btn btn-success" href="#" id="add"><i
class="fa fa-fw fa-lg fa-eye"></i>添加
</button>
</div>
</div>
</div>
</div>
</main>
<script>
var arr = []
arr["all"] = ["type", "port", "compress", "u", "p", "target"]
arr["tunnelServer"] = ["type", "port", "target", "compress", "u", "p", "tcp隧道模式,提供一条tcp隧道,适用于ssh、远程桌面等,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,访问公网服务器的设定端口,则相当于访问内网目标地址的目标端口"]
arr["udpServer"] = ["type", "port", "target", "compress", "udp隧道模式,提供一条udp隧道,适用于dns、内网dns访问等,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,访问公网服务器的设定端口,则相当于访问内网目标地址的udp目标端口"]
arr["socks5Server"] = ["type", "port", "compress", "u", "p", "socks5代理模式,内网socks5代理,配合proxifer,可如同使用vpn一样访问内网设备或资源,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置socks5代理,即访问内网设备或者资源 "]
arr["httpProxyServer"] = ["type", "port", "compress", "u", "p", " http代理模式,内网http代理,可访问内网网站,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置http代理,即访问内网站点"]
arrClientHide = ["compress", "u", "p", "crypt", "mux"]
function resetForm() {
for (var i = 0; i < arr["all"].length; i++) {
$("#" + arr["all"][i]).css("display", "none")
}
o = $("#type option:selected").val()
for (var i = 0; i < arr[o].length - 1; i++) {
$("#" + arr[o][i]).css("display", "block")
}
$("#info").html(arr[o][arr[o].length - 1])
}
function resetClientCnf() {
for (var i = 0; i < arrClientHide.length; i++) {
$("#" + arrClientHide[i]).css("display", "block")
}
op = $("#use_client option:selected").val()
if (op == 1) {
for (var i = 0; i < arrClientHide.length; i++) {
$("#" + arrClientHide[i]).css("display", "none")
}
}
}
$(function () {
resetForm()
resetClientCnf()
$("#type").on("change", function () {
resetForm()
resetClientCnf()
})
$("#use_client").on("change", function () {
resetForm()
resetClientCnf()
})
$("#add").on("click", function () {
$.ajax({
type: "POST",
url: "/index/add",
data: $("form").serializeArray(),
success: function (res) {
alert(res.msg)
if (res.status) {
history.back(-1)
}
}
})
})
})
</script>
+135
View File
@@ -0,0 +1,135 @@
<div class="row tile">
<div class="col-md-6 col-md-auto">
<div>
<h3 class="tile-title">添加</h3>
<div class="tile-body">
<form>
<input type="hidden" name="id" value="{{.t.Id}}">
<div class="form-group">
<label class="control-label">模式</label>
<select class="form-control" name="type" id="type">
<option {{if eq "tunnelServer" .t.Mode}}selected{{end}} value="tunnelServer">tcp隧道</option>
<option {{if eq "udpServer" .t.Mode}}selected{{end}} value="udpServer">udp隧道</option>
<option {{if eq "socks5Server" .t.Mode}}selected{{end}} value="socks5Server">socks5代理
</option>
<option {{if eq "httpProxyServer" .t.Mode}}selected{{end}} value="httpProxyServer">http代理
</select>
</div>
<div class="form-group">
<label class="control-label">备注</label>
<input class="form-control" value="{{.t.Remark}}" type="text" name="remark" placeholder="备注">
</div>
<div class="form-group" id="port">
<label class="control-label">监听的端口</label>
<input class="form-control" value="{{.t.TcpPort}}" type="text" name="port"
placeholder="公网服务器对外访问端口,例如8024">
</div>
<div class="form-group" id="target">
<label class="control-label">内网目标(仅tcp、udp隧道模式需填写)</label>
<input class="form-control" value="{{.t.Target}}" type="text" name="target"
placeholder="内网隧道目标,例如10.1.50.203:22">
</div>
<div class="form-group" id="client_id">
<label class="control-label">客户端ID</label>
<input class="form-control" value="{{.t.Client.Id}}" type="text" name="client_id"
placeholder="客户端id">
</div>
<div class="form-group" id="use_client">
<label class="control-label">是否使用客户端配置</label>
<select class="form-control" name="use_client">
<option {{if eq false .t.UseClientCnf}}selected{{end}} value="0">否</option>
<option {{if eq true .t.UseClientCnf}}selected{{end}} value="1">是</option>
</select>
</div>
<div class="form-group" id="compress">
<label class="control-label">数据压缩方式(所有模式均支持)</label>
<select class="form-control" name="compress">
<option {{if eq "" .t.Config.Compress}}selected{{end}} value="">不压缩</option>
<option {{if eq "snappy" .t.Config.Compress}}selected{{end}} value="snappy">snappy压缩</option>
</select>
</div>
<div class="form-group" id="crypt">
<label class="control-label">是否加密传输(所有模式均支持)</label>
<select class="form-control" name="crypt">
<option {{if eq false .t.Config.Crypt}}selected{{end}} value="0">不加密</option>
<option {{if eq true .t.Config.Crypt}}selected{{end}} value="1">加密</option>
</select>
</div>
<div class="form-group" id="u">
<label class="control-label">验证用户名(仅socks5,web穿透支持)</label>
<input class="form-control" value="{{.t.Config.U}}" type="text" name="u"
placeholder="不填则无需验证">
</div>
<div class="form-group" id="p">
<label class="control-label">验证密码(仅socks5,web穿透支持)</label>
<input class="form-control" value="{{.t.Config.P}}" type="text" name="p"
placeholder="不填则无需验证">
</div>
</form>
</div>
<div class="tile-footer">
&nbsp;&nbsp;<button class="btn btn-success" href="#" id="add"><i
class="fa fa-fw fa-lg fa-eye"></i>保存
</button>
</div>
</div>
</div>
</div>
</main>
<script>
var arr = []
arr["all"] = ["type", "port", "compress", "u", "p", "target"]
arr["tunnelServer"] = ["type", "port", "target", "u", "p", "compress"]
arr["udpServer"] = ["type", "port", "target", "compress"]
arr["socks5Server"] = ["type", "port", "compress", "u", "p"]
arr["httpProxyServer"] = ["type", "port", "compress", "u", "p"]
arrClientHide = ["compress", "u", "p", "crypt", "mux"]
function resetForm() {
for (var i = 0; i < arr["all"].length; i++) {
$("#" + arr["all"][i]).css("display", "none")
}
o = $("#type option:selected").val()
for (var i = 0; i < arr[o].length; i++) {
$("#" + arr[o][i]).css("display", "block")
}
}
function resetClientCnf() {
for (var i = 0; i < arrClientHide.length; i++) {
$("#" + arrClientHide[i]).css("display", "block")
}
op = $("#use_client option:selected").val()
if (op == 1) {
for (var i = 0; i < arrClientHide.length; i++) {
$("#" + arrClientHide[i]).css("display", "none")
}
}
}
$(function () {
resetForm()
resetClientCnf()
$("#type").on("change", function () {
resetForm()
resetClientCnf()
})
$("#use_client").on("change", function () {
resetForm()
resetClientCnf()
})
$("#add").on("click", function () {
$.ajax({
type: "POST",
url: "/index/edit",
data: $("form").serializeArray(),
success: function (res) {
alert(res.msg)
if (res.status) {
history.back(-1)
}
}
})
})
})
</script>
+62
View File
@@ -0,0 +1,62 @@
<div class="row tile">
<div class="col-md-6 col-md-auto">
<div>
<h3 class="tile-title">添加</h3>
<div class="tile-body">
<form>
<div class="form-group">
<label class="control-label">备注</label>
<input class="form-control" type="text" name="remark" placeholder="备注">
</div>
<div class="form-group">
<label class="control-label">域名</label>
<input class="form-control" type="text" name="host" placeholder="域名">
</div>
<div class="form-group">
<label class="control-label">客户端id</label>
<input value="{{.client_id}}" class="form-control" type="text" name="client_id"
placeholder="客户端id">
</div>
<div class="form-group">
<label class="control-label">内网目标</label>
<textarea class="form-control" rows="4" type="text" name="target"
placeholder="内网隧道目标,例如10.1.50.203:22,换行分隔"></textarea>
</div>
<div class="form-group" id="header">
<label class="control-label">header头修改(冒号分隔,多个请换行填写)</label>
<textarea class="form-control" rows="4" type="text" name="header"
placeholder="Cache-Control: no-cache"></textarea>
</div>
<div class="form-group" id="hostchange">
<label class="control-label">host修改</label>
<input class="form-control" value="" type="text" name="hostchange"
placeholder="host修改">
</div>
</form>
</div>
<div class="tile-footer">
&nbsp;&nbsp;<button class="btn btn-success" href="#" id="add"><i
class="fa fa-fw fa-lg fa-eye"></i>添加
</button>
</div>
</div>
</div>
</div>
</main>
<script>
$(function () {
$("#add").on("click", function () {
$.ajax({
type: "POST",
url: "/index/addhost",
data: $("form").serializeArray(),
success: function (res) {
alert(res.msg)
if (res.status) {
history.back(-1)
}
}
})
})
})
</script>
+63
View File
@@ -0,0 +1,63 @@
<div class="row tile">
<div class="col-md-6 col-md-auto">
<div>
<h3 class="tile-title">修改</h3>
<div class="tile-body">
<form>
<div class="form-group">
<label class="control-label">域名</label>
<input class="form-control" value="{{.h.Host}}" type="hidden" name="host" placeholder="域名">
<input class="form-control" value="{{.h.Host}}" type="text" name="nhost" placeholder="域名">
</div>
<div class="form-group">
<label class="control-label">备注</label>
<input class="form-control" value="{{.h.Remark}}" type="text" name="remark" placeholder="备注">
</div>
<div class="form-group">
<label class="control-label">客户端id</label>
<input class="form-control" value="{{.h.Client.Id}}" type="text" name="client_id"
placeholder="客户端id">
</div>
<div class="form-group">
<label class="control-label">内网目标</label>
<textarea class="form-control" rows="4" type="text" name="target"
placeholder="内网隧道目标,例如10.1.50.203:22,换行分隔">{{.h.Target}}</textarea>
</div>
<div class="form-group" id="header">
<label class="control-label">header头修改(冒号分隔,多个请换行填写)</label>
<textarea class="form-control" rows="4" type="text" name="header"
placeholder="Cache-Control: no-cache">{{.h.HeaderChange}}</textarea>
</div>
<div class="form-group" id="hostchange">
<label class="control-label">host修改</label>
<input class="form-control" value="{{.h.HostChange}}" type="text" name="hostchange"
placeholder="host修改">
</div>
</form>
</div>
<div class="tile-footer">
&nbsp;&nbsp;<button class="btn btn-success" href="#" id="add"><i
class="fa fa-fw fa-lg fa-eye"></i>保存
</button>
</div>
</div>
</div>
</div>
</main>
<script>
$(function () {
$("#add").on("click", function () {
$.ajax({
type: "POST",
url: "/index/edithost",
data: $("form").serializeArray(),
success: function (res) {
alert(res.msg)
if (res.status) {
history.back(-1)
}
}
})
})
})
</script>
+141
View File
@@ -0,0 +1,141 @@
<div class="row">
<div class="col-md-12">
<div class="tile">
<iframe src="https://ghbtns.com/github-btn.html?user=cnlh&repo=easyProxy&type=star&count=true&size=large"
frameborder="0" scrolling="0" width="160px" height="30px"></iframe>
<iframe src="https://ghbtns.com/github-btn.html?user=cnlh&repo=easyProxy&type=watch&count=true&size=large&v=2"
frameborder="0" scrolling="0" width="160px" height="30px"></iframe>
<iframe src="https://ghbtns.com/github-btn.html?user=cnlh&repo=easyProxy&type=fork&count=true&size=large"
frameborder="0" scrolling="0" width="158px" height="30px"></iframe>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="tile">
<h3 class="tile-title">域名代理模式</h3>
<p>
<b>适用范围:</b> 小程序开发、微信公众号开发、产品演示
</p>
<p>
<b>假设场景:</b>
<li>有一个域名proxy.com,有一台公网机器ip为{{.ip}}</li>
<li>两个内网开发站点127.0.0.1:81,127.0.0.1:82</li>
<li>想通过a.proxy.com访问127.0.0.1:81,通过b.proxy.com访问127.0.0.1:82</li>
</p>
<p><b>使用步骤:</b></p>
<ul>
<li>将*.proxy.com解析到公网服务器{{.ip}}</li>
<li>在客户端管理中创建一个客户端,记录下验证密钥</li>
<li>点击该客户端的域名管理,添加两条规则规则:1、域名:a.proxy.com,内网目标:127.0.0.1:81,2、域名:b.proxy.com,内网目标:127.0.0.1:82</li>
<li>内网客户端运行<code>
<pre>./proxy_client server={{.ip}}:{{.p}} -vkey=客户端的密钥</pre>
</code></pre></li>
<li>现在访问a.proxy.com,b.proxy.com即可成功</li>
</ul>
<p>注:上文中提到公网ip({{.ip}})为系统自动识别,如果是在测试环境中请自行对应,<b>如需使用https请在配置文件中将https端口设置为443,和将对应的证书文件路径添加到配置文件中
</b></p>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="tile">
<h3 class="tile-title">tcp隧道模式</h3>
<p>
<b>适用范围:</b> ssh、远程桌面等tcp连接场景
</p>
<p>
<b>假设场景:</b> 想通过访问公网服务器{{.ip}}的8001端口,连接内网机器10.1.50.101的22端口,实现ssh连接
</p>
<p><b>使用步骤:</b></p>
<ul>
<li>在客户端管理中创建一个客户端,记录下验证密钥</li>
<li>内网客户端运行<code>
<pre>./proxy_client server={{.ip}}:{{.p}} -vkey=客户端的密钥</pre>
</code></pre>
</li>
<li>在该客户端隧道管理中添加一条tcp隧道,填写监听的端口(8001)、内网目标ip和目标端口(10.1.50.101:22),选择压缩方式,保存。</li>
<li>访问公网服务器ip({{.ip}}),填写的监听端口(8001),相当于访问内网ip(10.1.50.101):目标端口(22),例如:ssh -p 8001 root@{{.ip}}</li>
</ul>
<p>注:上文中提到公网ip({{.ip}})为系统自动识别,如果是在测试环境中请自行对应,默认内网客户端已经启动</p>
</div>
</div>
<div class="col-md-6">
<div class="tile">
<h3 class="tile-title">udp隧道模式</h3>
<p>
<b>适用范围:</b> 内网dns解析等udp连接场景
</p>
<p>
<b>假设场景:</b> 内网有一台dns(10.1.50.102:53),在非内网环境下想使用该dns,公网服务器为{{.ip}}
</p>
<p><b>使用步骤:</b></p>
<ul>
<li>在客户端管理中创建一个客户端,记录下验证密钥</li>
<li>内网客户端运行<code>
<pre>./proxy_client server={{.ip}}:{{.p}} -vkey=客户端的密钥</pre>
</code></pre>
</li>
<li>在该客户端的隧道管理中添加一条udp隧道,填写监听的端口(53)、内网目标ip和目标端口(10.1.50.102:53),选择压缩方式,保存。</li>
<li>修改本机dns为{{.ip}},则相当于使用10.1.50.202作为dns服务器</li>
</ul>
<p>注:上文中提到公网ip({{.ip}})为系统自动识别,如果是在测试环境中请自行对应,默认内网客户端已经启动</p>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="tile">
<h3 class="tile-title">socks5代理模式</h3>
<p>
<b>适用范围:</b> 在外网环境下如同使用vpn一样访问内网设备或者资源
</p>
<p>
<b>假设场景:</b> 想将公网服务器{{.ip}}的8003端口作为socks5代理,达到访问内网任意设备或者资源的效果
</p>
<p><b>使用步骤:</b></p>
<ul>
<li>在客户端管理中创建一个客户端,记录下验证密钥</li>
<li>内网客户端运行<code>
<pre>./proxy_client server={{.ip}}:{{.p}} -vkey=客户端的密钥</pre>
</code></pre>
</li>
<li>在该客户端隧道管理中添加一条socks5代理,填写监听的端口(8003),验证用户名和密码自行选择(建议先不填,部分客户端不支持,proxifer支持),选择压缩方式,保存。</li>
<li>在外网环境的本机配置socks5代理,ip为公网服务器ip({{.ip}}),端口为填写的监听端口(8003),即可畅享内网了</li>
</ul>
<p>注:上文中提到公网ip({{.ip}})为系统自动识别,如果是在测试环境中请自行对应,默认内网客户端已经启动</p>
</div>
</div>
<div class="col-md-6">
<div class="tile">
<h3 class="tile-title">http代理模式</h3>
<p>
<b>适用范围:</b> 在外网环境下访问内网站点
</p>
<p>
<b>假设场景:</b> 想将公网服务器{{.ip}}的8004端口作为http代理,访问内网网站
</p>
<p><b>使用步骤:</b></p>
<ul>
<li>在客户端管理中创建一个客户端,记录下验证密钥</li>
<li>内网客户端运行<code>
<pre>./proxy_client server={{.ip}}:{{.p}} -vkey=客户端的密钥</pre>
</code></pre>
</li>
<li>在该客户端隧道管理中添加一条http代理,填写监听的端口(8004),选择压缩方式,保存。</li>
<li>在外网环境的本机配置http代理,ip为公网服务器ip({{.ip}}),端口为填写的监听端口(8004),即可访问了</li>
</ul>
<p>注:上文中提到公网ip({{.ip}})为系统自动识别,如果是在测试环境中请自行对应,默认内网客户端已经启动</p>
</div>
</div>
<div class="col-md-12">
<div class="tile">
<p><b>单个客户端可以田间多条隧道或者域名解析</b></p>
</div>
</div>
</div>
</main>
+155
View File
@@ -0,0 +1,155 @@
<div class="row">
<div class="col-md-12">
<div class="tile">
<div class="tile-body">
<table class="table table-hover table-bordered" id="sampleTable">
<thead>
<tr>
<th>客户端id</th>
<th>备注</th>
<th>host</th>
<th>内网目标</th>
<th>host改写</th>
<th>压缩方式</th>
<th>加密</th>
<th>用户名</th>
<th>密码</th>
<th>出口流量</th>
<th>入口流量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</main>
<script type="text/javascript">
function del(host) {
if (confirm("确定要删除数据吗?")) {
$.ajax({
type: "POST",
url: "/index/delhost",
data: {"host": host},
success: function (res) {
alert(res.msg)
if (res.status) {
document.location.reload();
}
}
})
}
}
function add() {
window.location.href = "/index/addhost?vkey={{.task_id}}&client_id={{.client_id}}"
}
function edit(host) {
window.location.href = "/index/edithost?host=" + host
}
$(document).ready(function () {
var table = $('#sampleTable').DataTable({
responsive: {
details: {
display: $.fn.dataTable.Responsive.display.childRowImmediate
}
},
dom: 'Bfrtip',
processing: true,
serverSide: true,
autoWidth: false,
ordering: false,
ajax: {
url: window.location,
type: 'POST'
},
dom: '<"top"fl><"toolbar">rt<"bottom"ip><"clear">',
columns: [ //这个是显示到界面上的个数据 格式为 {data:'显示的字段名'}
{data: 'Remark'},
{data: 'Remark'},
{data: 'Host'},
{data: 'Target'},
{data: 'HostChange'},
{data: 'HostChange'},
{data: 'HostChange'},
{data: 'HostChange'},
{data: 'HostChange'},
{data: 'HostChange'},
{data: 'HostChange'},
{data: 'Target'},
],
bFilter: false,
columnDefs: [{
targets: -1,
render: function (data, type, row, meta) {
return '<div class="btn-group" role="group" aria-label="..."> ' +
'<button onclick="del(\'' + row.Host + '\')" type="button" class="btn btn-danger btn-sm">删除</button>' +
'<button onclick="edit(\'' + row.Host + '\')" type="button" class="btn btn-primary btn-sm">编辑查看</button> '
+ ' </div>'
}
},
{
targets: 0,
render: function (data, type, row, meta) {
return row.Client.Id
}
},
{
targets: -2,
render: function (data, type, row, meta) {
return change(row.Flow.InletFlow)
}
},
{
targets: -3,
render: function (data, type, row, meta) {
return change(row.Flow.ExportFlow)
}
},
{
targets: -4,
render: function (data, type, row, meta) {
return row.Client.Cnf.P
}
},
{
targets: -5,
render: function (data, type, row, meta) {
return row.Client.Cnf.U
}
}
,
{
targets: -6,
render: function (data, type, row, meta) {
if (row.Client.Cnf.Crypt == "0") {
return "不加密"
} else {
return "加密"
}
}
}
,
{
targets: -7,
render: function (data, type, row, meta) {
return row.Client.Cnf.Compress
}
}
],
buttons: []
});
$("#sampleTable_length").html('<button class="btn btn-primary" onclick="add()" type="button">新增</button>')
})
;
</script>
+104
View File
@@ -0,0 +1,104 @@
<div class="row">
<div class="col-md-3">
<div class="widget-small warning coloured-icon"><i class="icon fa fa-html5 fa-3x"></i>
<div class="info">
<h4>HTTP端口</h4>
<p><b>{{.p}}</b></p>
</div>
</div>
</div>
<div class="col-md-3">
<div class="widget-small danger coloured-icon"><i class="icon fa fa-home fa-3x"></i>
<div class="info">
<h4>域名解析数</h4>
<p><b>{{.data.hostCount}}</b></p>
</div>
</div>
</div>
<div class="col-md-3">
<div class="widget-small primary coloured-icon"><i class="icon fa fa-users fa-3x"></i>
<div class="info">
<h4>总客户端数</h4>
<p><b>{{.data.clientCount}}</b></p>
</div>
</div>
</div>
<div class="col-md-3">
<div class="widget-small info coloured-icon"><i class="icon fa fa-user-secret fa-3x"></i>
<div class="info">
<h4>在线客户端数</h4>
<p><b>{{.data.clientOnlineCount}}</b></p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="tile">
<h3 class="tile-title">流量</h3>
<div class="embed-responsive embed-responsive-16by9">
<canvas class="embed-responsive-item" id="flow"></canvas>
</div>
</div>
</div>
<div class="col-md-6">
<div class="tile">
<h3 class="tile-title">代理类型</h3>
<div class="embed-responsive embed-responsive-16by9">
<canvas class="embed-responsive-item" id="types"></canvas>
</div>
</div>
</div>
</div>
<script>
var pdataFlow = [
{
value: {{.data.inletFlowCount}},
color: "#46BFBD",
highlight: "#5AD3D1",
label: "入口流量"
},
{
value: {{.data.exportFlowCount}},
color: "#FDB45C",
highlight: "#FFC870",
label: "出口流量"
}
]
var pdataTypes = [
{
value: {{.data.tunnelServerCount}},
color: "#46BFBD",
highlight: "#5AD3D1",
label: "tcp隧道"
},
{
value: {{.data.socks5ServerCount}},
color: "#85FEAA",
highlight: "#85FEAA",
label: "socks5隧道"
},
{
value: {{.data.httpProxyServerCount}},
color: "#4B653C",
highlight: "#4B653C",
label: "http代理"
},
{
value: {{.data.udpServerCount}},
color: "#90653C",
highlight: "#90653C",
label: "udp代理"
},
{
value: {{.data.hostCount}},
color: "#FDB45C",
highlight: "#FDB45C",
label: "域名解析"
}
]
var ctxp = $("#flow").get(0).getContext("2d");
var pieChart = new Chart(ctxp).Pie(pdataFlow);
var ctxd = $("#types").get(0).getContext("2d");
var doughnutChart = new Chart(ctxd).Doughnut(pdataTypes);
</script>
+226
View File
@@ -0,0 +1,226 @@
<div class="row">
<div class="col-md-12">
<div class="tile">
<div class="tile-body">
<table class="table table-hover table-bordered" id="sampleTable">
<thead>
<tr>
<th>Id</th>
<th>备注</th>
<th>客户端Id</th>
<th>监听端口</th>
<th>内网目标</th>
<th>压缩方式</th>
<th>加密传输</th>
<th>用户名</th>
<th>密码</th>
<th>客户端状态</th>
<th>状态</th>
<th>出口流量</th>
<th>入口流量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</main>
<script type="text/javascript">
function del(id) {
if (confirm("确定要删除数据吗?")) {
$.ajax({
type: "POST",
url: "/index/del",
data: {"id": id},
success: function (res) {
alert(res.msg)
if (res.status) {
document.location.reload();
}
}
})
}
}
function start(id) {
if (confirm("确定要开始任务吗?")) {
$.ajax({
type: "POST",
url: "/index/start",
data: {"id": id},
success: function (res) {
alert(res.msg)
if (res.status) {
document.location.reload();
}
}
})
}
}
function stop(id) {
if (confirm("确定要暂停吗?")) {
$.ajax({
type: "POST",
url: "/index/stop",
data: {"id": id},
success: function (res) {
alert(res.msg)
if (res.status) {
document.location.reload();
}
}
})
}
}
function edit(id) {
window.location.href = "/index/edit?id=" + id
}
function add() {
window.location.href = "/index/add?type={{.type}}" + "&client_id={{.client_id}}"
}
$(document).ready(function () {
var table = $('#sampleTable').DataTable({
responsive: {
details: {
display: $.fn.dataTable.Responsive.display.childRowImmediate
}
},
dom: 'Bfrtip',
processing: true,
serverSide: true,
autoWidth: false,
ordering: false,
ajax: {
url: '/index/gettunnel?type={{.type}}' + "&client_id=" +{{.client_id}},
type: 'POST'
},
dom: '<"top"fl><"toolbar">rt<"bottom"ip><"clear">',
columns: [ //这个是显示到界面上的个数据 格式为 {data:'显示的字段名'}
{data: 'Id'},
{data: 'Remark'},
{data: 'ClientId'},
{data: 'TcpPort'},
{data: 'Target'},
{data: 'Compress'},
{data: 'Crypt'},
{data: 'U'},
{data: 'P'},
{data: 'ClientStatus'},
{data: 'Status'},
{data: 'ExportFlow'},
{data: 'InletFlow'},
{data: "Id"}
],
bFilter: false,
columnDefs: [{
targets: -1,
render: function (data, type, row, meta) {
if (row.Status == 1) {
btn = "<button onclick=\"stop('" + row.Id + "')\" class=\"btn btn-secondary btn-sm\" type=\"button\">关闭</button>"
} else {
btn = "<button onclick=\"start('" + row.Id + "')\" class=\"btn btn-success btn-sm\" type=\"button\">打开</button>"
}
btn_edit = '<button onclick="edit(\'' + row.Id + '\')" type="button" class="btn btn-primary btn-sm">查看编辑</button> '
return '<div class="btn-group" role="group" aria-label="..."> ' +
'<button onclick="del(\'' + row.Id + '\')" type="button" class="btn btn-danger btn-sm">删除</button>' +
btn_edit + btn + ' </div>'
}
}, {
targets: 2,
render: function (data, type, row, meta) {
return row.Client.Id
}
}, {
targets: 5,
render: function (data, type, row, meta) {
if (row.UseClientCnf == true) {
return row.Client.Cnf.Compress
} else {
return row.Config.Compress
}
}
}, {
targets: 7,
render: function (data, type, row, meta) {
if (row.UseClientCnf == true) {
return row.Client.Cnf.U
} else {
return row.Config.U
}
}
}, {
targets: 8,
render: function (data, type, row, meta) {
if (row.UseClientCnf == true) {
return row.Client.Cnf.P
} else {
return row.Config.P
}
}
},
{
targets: -4,
render: function (data, type, row, meta) {
if (data == false) {
return "<span class=\"badge badge-pill badge-secondary\">暂停</span>"
} else {
return "<span class=\"badge badge-pill badge-success\">正常</span>"
}
}
},
{
targets: -8,
render: function (data, type, row, meta) {
if (row.UseClientCnf == true) {
crypt = row.Client.Cnf.Crypt
} else {
crypt = row.Config.Crypt
}
if (crypt == "0") {
return "不加密"
} else {
return "加密"
}
}
},
{
targets: -5,
render: function (data, type, row, meta) {
if (row.Client.IsConnect == false) {
return "<span class=\"badge badge-pill badge-secondary\">离线</span>"
} else {
return "<span class=\"badge badge-pill badge-success\">在线</span>"
}
}
},
{
targets: -2,
render: function (data, type, row, meta) {
return change(row.Flow.InletFlow)
}
},
{
targets: -3,
render: function (data, type, row, meta) {
return change(row.Flow.ExportFlow)
}
}
],
buttons: []
});
$("#sampleTable_length").html('<button class="btn btn-primary" onclick="add()" type="button">新增</button>')
})
;
</script>
+58
View File
@@ -0,0 +1,58 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="/static/img/favicon.ico">
<!-- Main CSS-->
<link rel="stylesheet" type="text/css" href="/static/css/main.css">
<!-- Font-icon css-->
<link rel="stylesheet" type="text/css" href="/static/css/font-awesome.min.css">
<title>easyProxy内网穿透</title>
</head>
<body>
<section class="material-half-bg">
<div class="cover"></div>
</section>
<section class="login-content">
<div class="logo">
<h1></h1>
</div>
<div class="login-box">
<form class="login-form" onsubmit="return false">
<h3 class="login-head"><i class="fa fa-lg fa-fw fa-user"></i>内网穿透管理登陆</h3>
<div class="form-group">
<label class="control-label">密码</label>
<input class="form-control" name="psd" type="password" placeholder="" autofocus>
</div>
<div class="form-group btn-container">
<button onclick="login()" class="btn btn-primary btn-block"><i class="fa fa-sign-in fa-lg fa-fw"></i>登陆
</button>
</div>
</form>
</div>
</section>
<script type="text/javascript" src="/static/js/datatables.min.js"></script>
<script src="/static/js/main.js"></script>
<script type="text/javascript">
// Login Page Flipbox control
function login() {
$.ajax({
type: "POST",
url: "/login/verify",
data: $("form").serializeArray(),
success: function (res) {
if (res.status) {
window.location.href = "/index/index"
} else {
alert(res.msg)
}
}
})
return false
}
</script>
</body>
</html>
+5
View File
@@ -0,0 +1,5 @@
<div class="page-error tile">
<h1><i class="fa fa-exclamation-circle"></i> Error 404: Page not found</h1>
<p>The page you have requested is not found.</p>
<p><a class="btn btn-primary" href="javascript:window.history.back();">Go Back</a></p>
</div>
+76
View File
@@ -0,0 +1,76 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="description"
content="Vali is a responsive and free admin theme built with Bootstrap 4, SASS and PUG.js. It's fully customizable and modular.">
<link rel="shortcut icon" href="/static/img/favicon.ico">
<title>easyProxy内网穿透</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Font-icon css-->
<link rel="stylesheet" type="text/css" href="/static/css/font-awesome.min.css">
<!-- Main CSS-->
<link rel="stylesheet" type="text/css" href="/static/css/main.css">
</head>
<body class="app sidebar-mini rtl">
<!-- Navbar-->
<header class="app-header">
<a class="app-header__logo" href="/"></a>
<!-- Sidebar toggle button--><a class="app-sidebar__toggle" href="#" data-toggle="sidebar"
aria-label="Hide Sidebar"></a>
<ul class="app-nav">
<!--Notification Menu-->
<!-- User Menu-->
<li class="dropdown"><a class="app-nav__item" href="/login/out" data-toggle="dropdown"
aria-label="Open Profile Menu"><i class="fa fa-sign-out fa-lg"></i>退出登陆</a>
</li>
</ul>
</header>
<!-- Sidebar menu-->
<div class="app-sidebar__overlay" data-toggle="sidebar"></div>
<aside class="app-sidebar">
<div class="app-sidebar__user"><img class="app-sidebar__user-avatar"
src="/static/img/48.jpg"
alt="User Image">
<div>
<p class="app-sidebar__user-name">System</p>
<p class="app-sidebar__user-designation">欢迎使用</p>
</div>
</div>
<ul class="app-menu">
<li><a class="app-menu__item {{if eq "index" .menu}}active{{end}}" href="/"><i
class="app-menu__icon fa fa-dashboard"></i><span class="app-menu__label">dashboard</span></a></li>
<li><a class="app-menu__item {{if eq "client" .menu}}active{{end}}" href="/client/list"><i
class="app-menu__icon fa fa-dot-circle-o"></i><span class="app-menu__label">客户端管理</span></a></li>
<li><a class="app-menu__item {{if eq "host" .menu}}active{{end}}" href="/index/hostlist"><i
class="app-menu__icon fa fa-lemon-o"></i><span class="app-menu__label">域名代理</span></a></li>
<li><a class="app-menu__item {{if eq "tcp" .menu}}active{{end}}" href="/index/tcp"><i
class="app-menu__icon fa fa-life-buoy"></i><span class="app-menu__label">tcp隧道管理</span></a></li>
<li><a class="app-menu__item {{if eq "udp" .menu}}active{{end}}" href="/index/udp"><i
class="app-menu__icon fa fa-laptop"></i><span class="app-menu__label">udp隧道管理</span></a></li>
<li><a class="app-menu__item {{if eq "socks5" .menu}}active{{end}}" href="/index/socks5"><i
class="app-menu__icon fa fa-lightbulb-o"></i><span class="app-menu__label">socks5代理</span></a></li>
<li><a class="app-menu__item {{if eq "http" .menu}}active{{end}}" href="/index/http"><i
class="app-menu__icon fa fa-magic"></i><span class="app-menu__label">http代理</span></a></li>
<li><a class="app-menu__item {{if eq "help" .menu}}active{{end}}" href="/index/help"><i
class="app-menu__icon fa fa-question-circle"></i><span class="app-menu__label">使用说明</span></a></li>
</ul>
</aside>
<script type="text/javascript" src="/static/js/datatables.min.js"></script>
<script src="/static/js/main.js"></script>
<script src="/static/js/chart.js"></script>
<main class="app-content">
<div class="app-title">
<div>
<h1><i class="fa fa-th-list"></i> {{.name}}</h1>
<a href="javascript:history.back(-1);"><i class="fa fa-mail-reply"></i>返回</a>
</div>
</div>
{{.LayoutContent}}
</body>
</html>