Compare commits

...
33 Commits
Author SHA1 Message Date
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
19 changed files with 2011 additions and 198 deletions
+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.
+492 -1
View File
@@ -1,2 +1,493 @@
# easyProxy
简单、轻量级http代理服务器,主要应用于内网穿透
轻量级、高性能http代理服务器,主要应用于**内网穿透**。支持五种模式,**http代理请求**、**tcp隧道模式**、**udp隧道模式**、**sock5代理模式**、**http代理模式**,可根据自身需求进行选择,同时支持sock5验证,gzip、snnapy压缩等。
支持客户端与服务端连接中断自动重连,多路传输,大大的提高请求处理速度,go语言编写,无第三方依赖,经过测试内存占用小,普通场景下,仅占用10m内存。
水平很有限,不足指出请大家指出,交流QQ群:206610006
## 背景
1. 我有一个小程序的需求,但是小程序的数据源必须从内网才能抓取到,但是内网服务器没有公网ip,所以只能内网穿透了。----> [http反向代理请求](#http代理请求)
2. 想在外网通过ssh连接内网的机器,做云服务器到内网服务器端口的映射,或者做微信公众号开发---->[tcp隧道模式](#tcp隧道模式)
3. 在非内网环境下使用内网dns,或者需要通过udp访问内网机器等---->[udp隧道模式](#udp隧道模式)
4. 在外网使用HTTP代理访问内网站点---->[http代理模式](#http代理模式)
5. 搭建一个内网穿透ss,在外网如同使用内网vpn一样访问内网资源或者设备----> [socks5代理模式](#socks5代理模式)
## 特点
- [x] 支持gzip、snnapy压缩,减小传输过程流量消耗
- [x] 支持多站点配置,兼容多个内网网站,可处理相互之间的跳转包含关系
- [x] 断线自动重连
- [x] 支持多路传输,提高并发
- [x] 跨站自动匹配替换
- [x] 支持tcp隧道,提升访问效率
- [x] 支持udp隧道
- [x] 支持http代理
- [x] 支持内网穿透sock5代理,配合proxifer可达到vpn的效果,在外网访问内网资源或者设备,同时可以设置用户名和密码验证
## 目录
1. [安装](#安装)
2. [http反向代理请求](#http代理请求)
3. [tcp隧道模式](#tcp隧道模式)
4. [udp隧道模式](#udp隧道模式)
5. [sock5代理模式](#sock5代理模式)
6. [http代理模式](#http代理模式)
7. [数据压缩支持](#数据压缩支持)
8. [操作系统支持](#操作系统支持)
## 安装
1. release安装
> https://github.com/cnlh/easyProxy/releases
下载对应的系统版本即可(目前linux和windows只编译了64位的),服务端和客户端共用一个程序,go语言开发,无需任何第三方依赖
2. 源码安装
- 安装源码
> go get github.com/cnlh/easyProxy
- 编译(无第三方模块)
> go build
## http代理请求
### 场景及原理
较为适用于http,也就是web站点的穿透,服务端与客户端之间建立连接,服务端收到http请求后,将请求发送到客户端,客户端再执行这个请求,并将结果返回给服务端,服务端收到后再返回。
<html>
<span style="color:red">特点:支持同时代理多个站点,不同站点之间有联系还可以实现匹配替换</span>
</html>
![image](https://github.com/cnlh/easyProxy/blob/master/image/http.png?raw=true)
**最终效果**:
- 访问a.server.com和访问10.1.50.203的80端口相同
- 访问b.server.com和访问10.1.50.202的80端口相同
- 访问c.server.com和访问10.1.50.201的80端口相同
### 使用
- 服务端
```
./easyProxy -mode httpServer -vkey DKibZF5TXvic1g3kY -tcpport=8284 -httpport=8024
```
名称 | 含义
---|---
mode | 运行模式(client、server不写默认client)
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
httpport | 代理的http端口(与nginx配合使用)
- 客户端
```
建立配置文件 config.json
```
```
./easyProxy -config config.json
```
名称 | 含义
---|---
config | 配置文件路径
### 配置文件config.json
```
{
"Server": {
"ip": "123.206.77.88",
"tcp": 8284,
"vkey": "DKibZF5TXvic1g3kY",
"num": 10
},
"SiteList": [
{
"host": "a.ourcauc.com",
"url": "10.1.50.203",
"port": 80
},
{
"host": "b.ourcauc.com",
"url": "10.1.50.202",
"port": 80
},
{
"host": "c.ourcauc.com",
"url": "10.1.50.203",
"port": 80
}
],
"Replace": 0
}
```
名称 | 含义
---|---
ip | 服务端ip地址
tcp | 服务端与客户端通信端口
vkey | 验证密钥
num | 服务端与客户端通信连接数
SiteList | 本地解析的域名列表
host | 域名地址
url | 内网代理的地址
port | 内网代理的地址对应的端口
Replace | 是否自动匹配替换[(查看场景)](https://github.com/cnlh/easyProxy/issues/1)
### nginx代理配置示例
```
upstream nodejs {
server 127.0.0.1:8024;
keepalive 64;
}
server {
listen 80;
server_name a.ourcauc.com b.ourcauc.com c.ourcauc.com ;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host:8024;
proxy_set_header X-Nginx-Proxy true;
proxy_set_header Connection "";
proxy_pass http://nodejs;
}
}
```
## 域名配置示例
> -a A 123.206.77.88
> -b A 123.206.77.88
> -c A 123.206.77.88
### 跨站自动匹配替换说明
例如,访问:a.ourcauc.com,该页面里面有一个超链接为10.1.50.202:80,将根据配置文件自动该将url替换为b.ourcauc.com,以达到跨站也可访问的效果,但需要提前在配置文件中配置这些站点。
如需开启,请加配置文件Replace值设置为1
>注意:开启可能导致不应该被替换的内容被替换,请谨慎开启
### 二级域名示范
[二级域名](https://github.com/cnlh/easyProxy/wiki/%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B)
## 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端口
### 使用
- 服务端
```
./easyProxy -mode tunnelServer -vkey DKibZF5TXvic1g3kY -tcpport=8284 -httpport=8024 -target=10.1.50.203:80
```
名称 | 含义
---|---
mode | 运行模式(client、server不写默认client)
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
httpport | 代理的http端口(与nginx配合使用)
target | 目标地址,格式如上
- 客户端
```
建立配置文件 config.json
```
```
./easyProxy -config config.json
```
名称 | 含义
---|---
config | 配置文件路径
### 配置文件config.json
```
{
"Server": {
"ip": "123.206.77.88",
"tcp": 8284,
"vkey": "DKibZF5TXvic1g3kY",
"num": 10
}
}
```
名称 | 含义
---|---
ip | 服务端ip地址
tcp | 服务端与客户端通信端口
vkey | 验证密钥
num | 服务端与客户端通信连接数
## 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)
### 使用
- 服务端
```
./easyProxy -mode udpServer -vkey DKibZF5TXvic1g3kY -tcpport=8284 -httpport=53 -target=10.1.50.210:53
```
名称 | 含义
---|---
mode | 运行模式(client、server不写默认client)
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
httpport | 公网vpn的端口
target | 目标地址,格式如上
- 客户端
```
建立配置文件 config.json
```
```
./easyProxy -config config.json
```
名称 | 含义
---|---
config | 配置文件路径
- 本机
```
设置本机dns解析服务器地址为123.206.77.88
```
### 配置文件config.json
```
{
"Server": {
"ip": "123.206.77.88",
"tcp": 8284,
"vkey": "DKibZF5TXvic1g3kY",
"num": 10
}
}
```
名称 | 含义
---|---
ip | 服务端ip地址
tcp | 服务端与客户端通信端口
vkey | 验证密钥
num | 服务端与客户端通信连接数
## socks5代理模式
### 场景及原理
**原理**
主要用于socks5代理,也就是和ss类似,不过是代理内网。使用此模式时,可在非内网环境下配置本机的socks5代理(服务器ip、sock5代理端口),即可实现socks5代理,达到访问内网的网站的效果,配合proxifer等全局代理软件,即可如同使用内网vpn一样,访问内网网站,通过ssh连接内网机器等等……。
![image](https://github.com/cnlh/easyProxy/blob/master/image/sock5.png?raw=true)
### 使用
- 服务端
```
./easyProxy -mode sock5Server -vkey DKibZF5TXvic1g3kY -tcpport=8284 -httpport=8024
```
名称 | 含义
---|---
mode | 运行模式(client、server不写默认client)
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
httpport | 代理的http端口(与nginx配合使用)
u | 验证的用户名
p | 验证的密码
**说明**:用户名和密码验证模式,仅部分socks5客户端支持,例如proxifer。
如需验证,在服务端命令后加上
```
-u=user -p=password
```
即可
- 客户端
```
建立配置文件 config.json
```
```
./easyProxy -config config.json
```
名称 | 含义
---|---
config | 配置文件路径
- 需要使用内网代理的机器
```
配置sock5代理即可,ip为外网服务器ip,端口为httpport,即可在外网环境使用内网啦!也可使用proxifer等全局代理软件。
```
如果设置了用户名和密码,记得填上用户名和密码
### 配置文件config.json
```
{
"Server": {
"ip": "123.206.77.88",
"tcp": 8284,
"vkey": "DKibZF5TXvic1g3kY",
"num": 10
}
}
```
名称 | 含义
---|---
ip | 服务端ip地址
tcp | 服务端与客户端通信端口
vkey | 验证密钥
num | 服务端与客户端通信连接数
## http代理模式
### 场景及原理
主要用于HTTP代理,区别也就是HTTP代理和sock5代理的区别。使用此模式时,可在非内网环境下配置本机的HTTP代理(服务器ip、HTTP代理端口),即可实现HTTP代理,达到访问内网的网站的效果。
![image](https://github.com/cnlh/easyProxy/blob/master/image/httpProxy.png?raw=true)
### 使用
- 服务端
```
./easyProxy -mode httpProxyServer -vkey DKibZF5TXvic1g3kY -tcpport=8284 -httpport=8024
```
名称 | 含义
---|---
mode | 运行模式(client、server不写默认client)
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
httpport | 代理的http端口(与nginx配合使用)
- 客户端
```
建立配置文件 config.json
```
```
./easyProxy -config config.json
```
- 需要使用内网代理的机器
```
配置HTTP代理即可,ip为外网服务器ip,端口为httpport,即可在外网环境访问内网啦!
```
名称 | 含义
---|---
config | 配置文件路径
### 配置文件config.json
```
{
"Server": {
"ip": "123.206.77.88",
"tcp": 8284,
"vkey": "DKibZF5TXvic1g3kY",
"num": 10
}
}
```
名称 | 含义
---|---
ip | 服务端ip地址
tcp | 服务端与客户端通信端口
vkey | 验证密钥
num | 服务端与客户端通信连接数
## 数据压缩支持
### 场景及原理
由于是内网穿透,内网客户端与服务端之间的隧道存在大量的数据交换,为节省流量,加快传输速度,由此本程序支持GZIP、SNNAPY两种形式的压缩,两者差异请自行选择。
### 注意点
- 所有模式均支持数据压缩
- 如使用数据压缩,客户端与服务端的压缩方式必须相同,否则将无法正常工作。
### 如何使用
**GZIP压缩**
- 在server端加上参数 -compress=gzip,例如在TCP隧道模式
```
./easyProxy -mode tunnelServer -vkey DKibZF5TXvic1g3kY -tcpport=8284 -httpport=8024 -target=10.1.50.203:80 -compress=gzip
```
- 在client端同时加上参数 -compress=gzip,例如
```
./easyProxy -config=config.json -compress=gzip
```
**SNNAPY压缩**
将参数修改为snnapy即可
## 操作系统支持
支持Windows、Linux、MacOSX等,无第三方依赖库。
Executable
+144
View File
@@ -0,0 +1,144 @@
package main
import (
"errors"
"fmt"
"log"
"net"
"sync"
"time"
)
type TRPClient struct {
svrAddr string
tcpNum int
sync.Mutex
}
func NewRPClient(svraddr string, tcpNum int) *TRPClient {
c := new(TRPClient)
c.svrAddr = svraddr
c.tcpNum = tcpNum
return c
}
func (s *TRPClient) Start() error {
for i := 0; i < s.tcpNum; i++ {
go s.newConn()
}
for {
time.Sleep(time.Second * 5)
}
return nil
}
//新建
func (s *TRPClient) newConn() error {
s.Lock()
conn, err := net.Dial("tcp", s.svrAddr)
if err != nil {
log.Println("连接服务端失败,五秒后将重连")
time.Sleep(time.Second * 5)
s.Unlock()
go s.newConn()
return err
}
s.Unlock()
return s.process(NewConn(conn))
}
func (s *TRPClient) process(c *Conn) error {
c.SetAlive()
if _, err := c.Write(getverifyval()); err != nil {
return err
}
c.wMain()
for {
flags, err := c.ReadFlag()
if err != nil {
log.Println("服务端断开,五秒后将重连", err)
time.Sleep(5 * time.Second)
go s.newConn()
break
}
switch flags {
case VERIFY_EER:
log.Fatal("vkey不正确,请检查配置文件")
case RES_SIGN: //代理请求模式
if err := s.dealHttp(c); err != nil {
log.Println(err)
return err
}
case WORK_CHAN: //隧道模式,每次开启10个,加快连接速度
for i := 0; i < 100; i++ {
go s.dealChan()
}
case RES_MSG:
log.Println("服务端返回错误。")
default:
log.Println("无法解析该错误。")
}
}
return nil
}
//隧道模式处理
func (s *TRPClient) dealChan() error {
//创建一个tcp连接
conn, err := net.Dial("tcp", s.svrAddr)
if err != nil {
return err
}
//验证
if _, err := conn.Write(getverifyval()); err != nil {
return err
}
//默认长连接保持
c := NewConn(conn)
c.SetAlive()
//写标志
c.wChan()
//获取连接的host type(tcp or udp)
typeStr, host, err := c.GetHostFromConn()
if err != nil {
return err
}
//与目标建立连接
server, err := net.Dial(typeStr, host)
if err != nil {
log.Println(err)
return err
}
go relay(NewConn(server), c, DataDecode)
relay(c, NewConn(server), DataEncode)
return nil
}
//http模式处理
func (s *TRPClient) dealHttp(c *Conn) error {
buf := make([]byte, 1024*32)
n, err := c.ReadFromCompress(buf, DataDecode)
if err != nil {
c.wError()
return err
}
req, err := DecodeRequest(buf[:n])
if err != nil {
c.wError()
return err
}
respBytes, err := GetEncodeResponse(req)
if err != nil {
c.wError()
return err
}
c.wSign()
n, err = c.WriteCompress(respBytes, DataEncode)
if err != nil {
return err
}
if n != len(respBytes) {
return errors.New(fmt.Sprintf("发送数据长度错误,已经发送:%dbyte,总字节长:%dbyte\n", n, len(respBytes)))
}
return nil
}
Executable
+20
View File
@@ -0,0 +1,20 @@
{
"Server": {
"ip": "123.206.77.88",
"tcp": 8224,
"vkey": "DKibZF5TXvic1g3kY",
"num": 10
},
"SiteList": [
{
"host": "a.server.ourcauc.com",
"url": "10.1.50.203",
"port": 80
},
{
"host": "b.server.ourcauc.com",
"url": "10.1.50.196",
"port": 4000
}
]
}
+216
View File
@@ -0,0 +1,216 @@
package main
import (
"bytes"
"compress/gzip"
"encoding/binary"
"errors"
"fmt"
"github.com/golang/snappy"
"io"
"log"
"net"
"net/url"
"regexp"
"strings"
"time"
)
type Conn struct {
conn net.Conn
}
func NewConn(conn net.Conn) *Conn {
c := new(Conn)
c.conn = conn
return c
}
//读取指定内容长度
func (s *Conn) ReadLen(len int) ([]byte, error) {
raw := make([]byte, 0)
buff := make([]byte, 1024)
c := 0
for {
clen, err := s.conn.Read(buff)
if err != nil && err != io.EOF {
return raw, err
}
raw = append(raw, buff[:clen]...)
if c += clen; c >= len {
break
}
}
if c != len {
return raw, errors.New(fmt.Sprintf("已读取长度错误,已读取%dbyte,需要读取%dbyte。", c, len))
}
return raw, nil
}
//获取长度
func (s *Conn) GetLen() (int, error) {
val := make([]byte, 4)
_, err := s.Read(val)
if err != nil {
return 0, err
}
nlen := binary.LittleEndian.Uint32(val)
if nlen <= 0 {
return 0, errors.New("数据长度错误")
}
return int(nlen), nil
}
//写入长度
func (s *Conn) WriteLen(buf []byte) (int, error) {
raw := bytes.NewBuffer([]byte{})
if err := binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
log.Println(err)
return 0, err
}
if err = binary.Write(raw, binary.LittleEndian, buf); err != nil {
log.Println(err)
return 0, err
}
return s.Write(raw.Bytes())
}
//读取flag
func (s *Conn) ReadFlag() (string, error) {
val := make([]byte, 4)
_, err := s.conn.Read(val)
if err != nil {
return "", err
}
return string(val), err
}
//读取host
func (s *Conn) GetHostFromConn() (typeStr string, host string, err error) {
ltype := make([]byte, 3)
_, err = s.Read(ltype)
if err != nil {
return
}
typeStr = string(ltype)
len, err := s.GetLen()
if err != nil {
return
}
hostByte := make([]byte, len)
_, err = s.conn.Read(hostByte)
if err != nil {
return
}
host = string(hostByte)
return
}
//写tcp host
func (s *Conn) WriteHost(ltype string, host string) (int, error) {
raw := bytes.NewBuffer([]byte{})
binary.Write(raw, binary.LittleEndian, []byte(ltype))
binary.Write(raw, binary.LittleEndian, int32(len([]byte(host))))
binary.Write(raw, binary.LittleEndian, []byte(host))
return s.Write(raw.Bytes())
}
//设置连接为长连接
func (s *Conn) SetAlive() {
conn := s.conn.(*net.TCPConn)
conn.SetReadDeadline(time.Time{})
conn.SetKeepAlive(true)
conn.SetKeepAlivePeriod(time.Duration(2 * time.Second))
}
//从tcp报文中解析出host
func (s *Conn) GetHost() (method, address string, rb []byte, err error) {
var b [2048]byte
var n int
var host string
if n, err = s.Read(b[:]); err != nil {
return
}
rb = b[:n]
//TODO:某些不规范报文可能会有问题
fmt.Sscanf(string(b[:n]), "%s", &method)
reg, err := regexp.Compile(`(\w+:\/\/)([^/:]+)(:\d*)?`)
if err != nil {
return
}
host = string(reg.Find(b[:]))
hostPortURL, err := url.Parse(host)
if err != nil {
return
}
if hostPortURL.Opaque == "443" { //https访问
address = hostPortURL.Scheme + ":443"
} else { //http访问
if strings.Index(hostPortURL.Host, ":") == -1 { //host不带端口, 默认80
address = hostPortURL.Host + ":80"
} else {
address = hostPortURL.Host
}
}
return
}
func (s *Conn) Close() error {
return s.conn.Close()
}
func (s *Conn) Write(b []byte) (int, error) {
return s.conn.Write(b)
}
func (s *Conn) Read(b []byte) (int, error) {
return s.conn.Read(b)
}
func (s *Conn) ReadFromCompress(b []byte, compress int) (int, error) {
switch compress {
case COMPRESS_GZIP_DECODE:
r, err := gzip.NewReader(s)
if err != nil {
return 0, err
}
return r.Read(b)
case COMPRESS_SNAPY_DECODE:
r := snappy.NewReader(s)
return r.Read(b)
case COMPRESS_NONE:
return s.Read(b)
}
return 0, nil
}
func (s *Conn) WriteCompress(b []byte, compress int) (n int, err error) {
switch compress {
case COMPRESS_GZIP_ENCODE:
w := gzip.NewWriter(s)
if n, err = w.Write(b); err == nil {
w.Flush()
}
case COMPRESS_SNAPY_ENCODE:
w := snappy.NewBufferedWriter(s)
if n, err = w.Write(b); err == nil {
w.Flush()
}
case COMPRESS_NONE:
n, err = s.Write(b)
}
return
}
func (s *Conn) wError() {
s.conn.Write([]byte(RES_MSG))
}
func (s *Conn) wSign() {
s.conn.Write([]byte(RES_SIGN))
}
func (s *Conn) wMain() {
s.conn.Write([]byte(WORK_MAIN))
}
func (s *Conn) wChan() {
s.conn.Write([]byte(WORK_CHAN))
}
Executable
+121
View File
@@ -0,0 +1,121 @@
package main
import (
"bufio"
"bytes"
"compress/gzip"
"encoding/binary"
"errors"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"strconv"
"strings"
)
/*
http.ReadRequest()
http.ReadResponse()
httputil.DumpRequest()
httputil.DumpResponse()
*/
// 将request 的处理
func EncodeRequest(r *http.Request) ([]byte, error) {
raw := bytes.NewBuffer([]byte{})
// 写签名
binary.Write(raw, binary.LittleEndian, []byte("sign"))
reqBytes, err := httputil.DumpRequest(r, true)
if err != nil {
return nil, err
}
// 写body数据长度 + 1
binary.Write(raw, binary.LittleEndian, int32(len(reqBytes)+1))
// 判断是否为http或者https的标识1字节
binary.Write(raw, binary.LittleEndian, bool(r.URL.Scheme == "https"))
if err := binary.Write(raw, binary.LittleEndian, reqBytes); err != nil {
return nil, err
}
return raw.Bytes(), nil
}
// 将字节转为request
func DecodeRequest(data []byte) (*http.Request, error) {
if len(data) <= 100 {
return nil, errors.New("待解码的字节长度太小")
}
req, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(data[1:])))
if err != nil {
return nil, err
}
str := strings.Split(req.Host, ":")
req.Host, err = getHost(str[0])
if err != nil {
return nil, err
}
scheme := "http"
if data[0] == 1 {
scheme = "https"
}
req.URL, _ = url.Parse(fmt.Sprintf("%s://%s%s", scheme, req.Host, req.RequestURI))
req.RequestURI = ""
return req, nil
}
//// 将response转为字节
func EncodeResponse(r *http.Response) ([]byte, error) {
raw := bytes.NewBuffer([]byte{})
binary.Write(raw, binary.LittleEndian, []byte("sign"))
respBytes, err := httputil.DumpResponse(r, true)
if config.Replace == 1 {
respBytes = replaceHost(respBytes)
}
if err != nil {
return nil, err
}
var buf bytes.Buffer
zw := gzip.NewWriter(&buf)
zw.Write(respBytes)
zw.Close()
binary.Write(raw, binary.LittleEndian, int32(len(buf.Bytes())))
if err := binary.Write(raw, binary.LittleEndian, buf.Bytes()); err != nil {
fmt.Println(err)
return nil, err
}
return raw.Bytes(), nil
}
//// 将字节转为response
func DecodeResponse(data []byte) (*http.Response, error) {
zr, err := gzip.NewReader(bytes.NewReader(data))
if err != nil {
return nil, err
}
defer zr.Close()
resp, err := http.ReadResponse(bufio.NewReader(zr), nil)
if err != nil {
return nil, err
}
return resp, nil
}
func getHost(str string) (string, error) {
for _, v := range config.SiteList {
if v.Host == str {
return v.Url + ":" + strconv.Itoa(v.Port), nil
}
}
return "", errors.New("没有找到解析的的host!")
}
func replaceHost(resp []byte) []byte {
str := string(resp)
for _, v := range config.SiteList {
str = strings.Replace(str, v.Url+":"+strconv.Itoa(v.Port), v.Host, -1)
str = strings.Replace(str, v.Url, v.Host, -1)
}
return []byte(str)
}
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: 97 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

Executable
+51
View File
@@ -0,0 +1,51 @@
package main
import (
"encoding/json"
"errors"
"io/ioutil"
)
//定义配置文件解析后的结构
type Server struct {
Ip string
Port int
Tcp int
Vkey string
Num int
}
type Site struct {
Host string
Url string
Port int
}
type Config struct {
Server Server
SiteList []Site
Replace int
}
type JsonStruct struct {
}
func NewJsonStruct() *JsonStruct {
return &JsonStruct{}
}
func (jst *JsonStruct) Load(filename string) (Config, error) {
data, err := ioutil.ReadFile(filename)
config := Config{}
if err != nil {
return config, errors.New("配置文件打开错误")
}
err = json.Unmarshal(data, &config)
if err != nil {
return config, errors.New("配置文件解析错误")
}
if config.Server.Tcp <= 0 || config.Server.Tcp >= 65536 {
return config, errors.New("请输入正确的tcp端口")
}
if config.Server.Vkey == "" {
return config, errors.New("密钥不能为空!")
}
return config, nil
}
Executable
+81
View File
@@ -0,0 +1,81 @@
package main
import (
"flag"
"fmt"
"log"
)
var (
configPath = flag.String("config", "config.json", "配置文件路径")
tcpPort = flag.Int("tcpport", 8284, "Socket连接或者监听的端口")
httpPort = flag.Int("httpport", 8024, "当mode为server时为服务端监听端口,当为mode为client时为转发至本地客户端的端口")
rpMode = flag.String("mode", "client", "启动模式,可选为client、server")
tunnelTarget = flag.String("target", "10.1.50.203:80", "远程目标")
verifyKey = flag.String("vkey", "", "验证密钥")
u = flag.String("u", "", "sock5验证用户名")
p = flag.String("p", "", "sock5验证密码")
compress = flag.String("compress", "", "数据压缩(gizp|snappy)")
config Config
err error
DataEncode int
DataDecode int
)
func main() {
flag.Parse()
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
switch *compress {
case "":
DataDecode = COMPRESS_NONE
DataEncode = COMPRESS_NONE
case "gzip":
DataDecode = COMPRESS_GZIP_DECODE
DataEncode = COMPRESS_GZIP_ENCODE
case "snnapy":
DataDecode = COMPRESS_SNAPY_DECODE
DataEncode = COMPRESS_SNAPY_ENCODE
default:
log.Fatalln("数据压缩格式错误")
}
if *rpMode == "client" {
JsonParse := NewJsonStruct()
config, err = JsonParse.Load(*configPath)
if err != nil {
log.Fatalln(err)
}
*verifyKey = config.Server.Vkey
log.Println("客户端启动,连接:", config.Server.Ip, ", 端口:", config.Server.Tcp)
cli := NewRPClient(fmt.Sprintf("%s:%d", config.Server.Ip, config.Server.Tcp), config.Server.Num)
cli.Start()
} else {
if *verifyKey == "" {
log.Fatalln("必须输入一个验证的key")
}
if *tcpPort <= 0 || *tcpPort >= 65536 {
log.Fatalln("请输入正确的tcp端口。")
}
if *httpPort <= 0 || *httpPort >= 65536 {
log.Fatalln("请输入正确的http端口。")
}
log.Println("服务端启动,监听tcp服务端端口:", *tcpPort, ", 外部服务端端口:", *httpPort)
if *rpMode == "httpServer" {
svr := NewHttpModeServer(*tcpPort, *httpPort)
if err := svr.Start(); err != nil {
log.Fatalln(err)
}
} else if *rpMode == "tunnelServer" {
svr := NewTunnelModeServer(*tcpPort, *httpPort, *tunnelTarget, ProcessTunnel)
svr.Start()
} else if *rpMode == "sock5Server" {
svr := NewSock5ModeServer(*tcpPort, *httpPort, *u, *p)
svr.Start()
} else if *rpMode == "httpProxyServer" {
svr := NewTunnelModeServer(*tcpPort, *httpPort, *tunnelTarget, ProcessHttp)
svr.Start()
} else if *rpMode == "udpServer" {
svr := NewUdpModeServer(*tcpPort, *httpPort, *tunnelTarget)
svr.Start()
}
}
}
Executable
+207
View File
@@ -0,0 +1,207 @@
package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
)
const (
VERIFY_EER = "vkey"
WORK_MAIN = "main"
WORK_CHAN = "chan"
RES_SIGN = "sign"
RES_MSG = "msg0"
)
type HttpModeServer struct {
Tunnel
httpPort int
}
func NewHttpModeServer(tcpPort, httpPort int) *HttpModeServer {
s := new(HttpModeServer)
s.tunnelPort = tcpPort
s.httpPort = httpPort
s.signalList = make(chan *Conn, 1000)
return s
}
//开始
func (s *HttpModeServer) Start() (error) {
err := s.StartTunnel()
if err != nil {
log.Fatalln("开启客户端失败!", err)
return err
}
s.startHttpServer()
return nil
}
//开启http端口监听
func (s *HttpModeServer) startHttpServer() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
retry:
if len(s.signalList) == 0 {
BadRequest(w)
return
}
conn := <-s.signalList
if err := s.writeRequest(r, conn); err != nil {
log.Println(err)
conn.Close()
goto retry
return
}
err = s.writeResponse(w, conn)
if err != nil {
log.Println(err)
conn.Close()
goto retry
return
}
s.signalList <- conn
})
log.Fatalln(http.ListenAndServe(fmt.Sprintf(":%d", s.httpPort), nil))
}
//req转为bytes发送给client端
func (s *HttpModeServer) writeRequest(r *http.Request, conn *Conn) error {
raw, err := EncodeRequest(r)
if err != nil {
return err
}
conn.wSign()
c, err := conn.WriteCompress(raw, DataEncode)
if err != nil {
return err
}
if c != len(raw) {
return errors.New("写出长度与字节长度不一致。")
}
return nil
}
//从client读取出Response
func (s *HttpModeServer) writeResponse(w http.ResponseWriter, c *Conn) error {
flags, err := c.ReadFlag()
if err != nil {
return err
}
switch flags {
case RES_SIGN:
buf := make([]byte, 1024*32)
n, err := c.ReadFromCompress(buf, DataDecode)
if err != nil {
return err
}
resp, err := DecodeResponse(buf[:n])
if err != nil {
return err
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
for k, v := range resp.Header {
for _, v2 := range v {
w.Header().Set(k, v2)
}
}
w.WriteHeader(resp.StatusCode)
w.Write(bodyBytes)
case RES_MSG:
BadRequest(w)
return errors.New("客户端请求出错")
default:
BadRequest(w)
return errors.New("无法解析此错误")
}
return nil
}
type process func(c *Conn, s *TunnelModeServer) error
type TunnelModeServer struct {
Tunnel
httpPort int
tunnelTarget string
process process
}
func NewTunnelModeServer(tcpPort, httpPort int, tunnelTarget string, process process) *TunnelModeServer {
s := new(TunnelModeServer)
s.tunnelPort = tcpPort
s.httpPort = httpPort
s.tunnelTarget = tunnelTarget
s.tunnelList = make(chan *Conn, 1000)
s.signalList = make(chan *Conn, 10)
s.process = process
return s
}
//开始
func (s *TunnelModeServer) Start() (error) {
err := s.StartTunnel()
if err != nil {
log.Fatalln("开启客户端失败!", err)
return err
}
s.startTunnelServer()
return nil
}
//隧道模式server
func (s *TunnelModeServer) startTunnelServer() {
listener, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), s.httpPort, ""})
if err != nil {
log.Fatalln(err)
}
for {
conn, err := listener.AcceptTCP()
if err != nil {
log.Println(err)
continue
}
go s.process(NewConn(conn), s)
}
}
//TODO:这种实现方式……
//tcp隧道模式
func ProcessTunnel(c *Conn, s *TunnelModeServer) error {
retry:
link := s.GetTunnel()
if _, err := link.WriteHost("tcp", s.tunnelTarget); err != nil {
link.Close()
goto retry
}
go relay(link, c, DataEncode)
relay(c, link, DataDecode)
return nil
}
//http代理模式
func ProcessHttp(c *Conn, s *TunnelModeServer) error {
method, addr, rb, err := c.GetHost()
if err != nil {
c.Close()
return err
}
retry:
link := s.GetTunnel()
if _, err := link.WriteHost("tcp", addr); err != nil {
link.Close()
goto retry
}
if method == "CONNECT" {
fmt.Fprint(c, "HTTP/1.1 200 Connection established\r\n")
} else {
link.WriteCompress(rb, DataEncode)
}
go relay(link, c, DataEncode)
relay(c, link, DataDecode)
return nil
}
+289
View File
@@ -0,0 +1,289 @@
package main
import (
"encoding/binary"
"errors"
"io"
"log"
"net"
"strconv"
)
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 {
Tunnel
httpPort int
u string //用户名
p string //密码
isVerify bool
}
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 {
log.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()
}
}
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)
}
func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) (proxyConn *Conn, err error) {
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)
err = errors.New("Address type not supported")
return nil, err
}
var port uint16
binary.Read(c, binary.BigEndian, &port)
// connect to host
addr := net.JoinHostPort(host, strconv.Itoa(int(port)))
client := s.GetTunnel()
s.sendReply(c, succeeded)
var ltype string
if command == associateMethod {
ltype = "udp"
} else {
ltype = "tcp"
}
_, err = client.WriteHost(ltype, addr)
return client, nil
}
func (s *Sock5ModeServer) handleConnect(c net.Conn) {
proxyConn, err := s.doConnect(c, connectMethod)
if err != nil {
log.Println(err)
c.Close()
} else {
go relay(proxyConn, NewConn(c), DataEncode)
go relay(NewConn(c), proxyConn, DataDecode)
}
}
// passive mode
func (s *Sock5ModeServer) handleBind(c net.Conn) {
}
func (s *Sock5ModeServer) handleUDP(c net.Conn) {
log.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
log.Println("does not support fragmentation, drop")
dummy := make([]byte, maxUDPPacketSize)
c.Read(dummy)
}
proxyConn, err := s.doConnect(c, associateMethod)
if err != nil {
c.Close()
} else {
go relay(proxyConn, NewConn(c), DataEncode)
go relay(NewConn(c), proxyConn, DataDecode)
}
}
func (s *Sock5ModeServer) handleNewConn(c net.Conn) {
buf := make([]byte, 2)
if _, err := io.ReadFull(c, buf); err != nil {
log.Println("negotiation err", err)
c.Close()
return
}
if version := buf[0]; version != 5 {
log.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 {
log.Println("wrong method")
c.Close()
return
}
if s.isVerify {
buf[1] = UserPassAuth
c.Write(buf)
if err := s.Auth(c); err != nil {
c.Close()
log.Println("验证失败:", err)
return
}
} else {
buf[1] = 0
c.Write(buf)
}
s.handleRequest(c)
}
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.p && string(user) == s.u {
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("未知错误")
}
func (s *Sock5ModeServer) Start() {
l, err := net.Listen("tcp", ":"+strconv.Itoa(s.httpPort))
if err != nil {
log.Fatal("listen error: ", err)
}
s.StartTunnel()
for {
conn, err := l.Accept()
if err != nil {
log.Fatal("accept error: ", err)
}
go s.handleNewConn(conn)
}
}
func NewSock5ModeServer(tcpPort, httpPort int, u, p string) *Sock5ModeServer {
s := new(Sock5ModeServer)
s.tunnelPort = tcpPort
s.httpPort = httpPort
s.tunnelList = make(chan *Conn, 1000)
s.signalList = make(chan *Conn, 10)
if u != "" && p != "" {
s.isVerify = true
s.u = u
s.p = p
} else {
s.isVerify = false
}
return s
}
+104
View File
@@ -0,0 +1,104 @@
package main
import (
"bytes"
"errors"
"log"
"net"
"sync"
"time"
)
type Tunnel struct {
tunnelPort int //通信隧道端口
listener *net.TCPListener //server端监听
signalList chan *Conn //通信
tunnelList chan *Conn //隧道
sync.RWMutex
}
func (s *Tunnel) 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 *Tunnel) tunnelProcess() error {
var err error
for {
conn, err := s.listener.Accept()
if err != nil {
log.Println(err)
continue
}
go s.cliProcess(NewConn(conn))
}
return err
}
//验证失败,返回错误验证flag,并且关闭连接
func (s *Tunnel) verifyError(c *Conn) {
c.conn.Write([]byte(VERIFY_EER))
c.conn.Close()
}
func (s *Tunnel) cliProcess(c *Conn) error {
c.conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(time.Duration(5) * time.Second))
vval := make([]byte, 20)
_, err := c.conn.Read(vval)
if err != nil {
log.Println("客户端读超时。客户端地址为::", c.conn.RemoteAddr())
c.conn.Close()
return err
}
if bytes.Compare(vval, getverifyval()[:]) != 0 {
log.Println("当前客户端连接校验错误,关闭此客户端:", c.conn.RemoteAddr())
s.verifyError(c)
return err
}
c.conn.(*net.TCPConn).SetReadDeadline(time.Time{})
//做一个判断 添加到对应的channel里面以供使用
flag, err := c.ReadFlag()
if err != nil {
return err
}
return s.typeDeal(flag, c)
}
//tcp连接类型区分
func (s *Tunnel) typeDeal(typeVal string, c *Conn) error {
switch typeVal {
case WORK_MAIN:
s.signalList <- c
case WORK_CHAN:
s.tunnelList <- c
default:
return errors.New("无法识别")
}
c.SetAlive()
return nil
}
//新建隧道
func (s *Tunnel) newChan() {
retry:
connPass := <-s.signalList
_, err := connPass.conn.Write([]byte("chan"))
if err != nil {
log.Println(err)
goto retry
}
s.signalList <- connPass
}
func (s *Tunnel) GetTunnel() *Conn {
if len(s.tunnelList) < 10 { //新建通道
go s.newChan()
}
return <-s.tunnelList
}
Executable
+80
View File
@@ -0,0 +1,80 @@
package main
import (
"io"
"log"
"net"
"time"
)
type UdpModeServer struct {
Tunnel
udpPort int //监听的udp端口
tunnelTarget string //udp目标地址
listener *net.UDPConn
udpMap map[string]*Conn
}
func NewUdpModeServer(tcpPort, udpPort int, tunnelTarget string) *UdpModeServer {
s := new(UdpModeServer)
s.tunnelPort = tcpPort
s.udpPort = udpPort
s.tunnelTarget = tunnelTarget
s.tunnelList = make(chan *Conn, 1000)
s.signalList = make(chan *Conn, 10)
s.udpMap = make(map[string]*Conn)
return s
}
//开始
func (s *UdpModeServer) Start() (error) {
err := s.StartTunnel()
if err != nil {
log.Fatalln("启动失败!", err)
return err
}
s.startTunnelServer()
return nil
}
//udp监听
func (s *UdpModeServer) startTunnelServer() {
s.listener, err = net.ListenUDP("udp", &net.UDPAddr{net.ParseIP("0.0.0.0"), s.udpPort, ""})
if err != nil {
log.Fatalln(err)
}
data := make([]byte, 1472) //udp数据包大小
for {
n, addr, err := s.listener.ReadFromUDP(data)
if err != nil {
log.Println(err)
continue
}
go s.process(addr, data[:n])
}
}
func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
conn := s.GetTunnel()
conn.WriteHost("udp", s.tunnelTarget)
go func() {
for {
buf := make([]byte, 1024)
conn.conn.SetReadDeadline(time.Now().Add(time.Duration(time.Second * 3)))
n, err := conn.ReadFromCompress(buf, DataDecode)
if err != nil || err == io.EOF {
conn.Close()
break
}
_, err = s.listener.WriteToUDP(buf[:n], addr)
if err != nil {
conn.Close()
break
}
}
}()
if _, err = conn.WriteCompress(data, DataEncode); err != nil {
conn.Close()
}
}
+177
View File
@@ -0,0 +1,177 @@
package main
import (
"bufio"
"bytes"
"compress/gzip"
"encoding/binary"
"errors"
"fmt"
"github.com/golang/snappy"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
"strconv"
"strings"
)
var (
disabledRedirect = errors.New("disabled redirect.")
)
const (
COMPRESS_NONE = iota
COMPRESS_SNAPY_ENCODE
COMPRESS_SNAPY_DECODE
COMPRESS_GZIP_ENCODE
COMPRESS_GZIP_DECODE
)
func BadRequest(w http.ResponseWriter) {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
}
//发送请求并转为bytes
func GetEncodeResponse(req *http.Request) ([]byte, error) {
var respBytes []byte
client := new(http.Client)
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return disabledRedirect
}
resp, err := client.Do(req)
disRedirect := err != nil && strings.Contains(err.Error(), disabledRedirect.Error())
if err != nil && !disRedirect {
return respBytes, err
}
if !disRedirect {
defer resp.Body.Close()
} else {
resp.Body = nil
resp.ContentLength = 0
}
respBytes, err = EncodeResponse(resp)
return respBytes, nil
}
// 将request转为bytes
func EncodeRequest(r *http.Request) ([]byte, error) {
raw := bytes.NewBuffer([]byte{})
reqBytes, err := httputil.DumpRequest(r, true)
if err != nil {
return nil, err
}
binary.Write(raw, binary.LittleEndian, bool(r.URL.Scheme == "https"))
binary.Write(raw, binary.LittleEndian, reqBytes)
return raw.Bytes(), nil
}
// 将字节转为request
func DecodeRequest(data []byte) (*http.Request, error) {
req, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(data[1:])))
if err != nil {
return nil, err
}
str := strings.Split(req.Host, ":")
req.Host, err = getHost(str[0])
if err != nil {
return nil, err
}
scheme := "http"
if data[0] == 1 {
scheme = "https"
}
req.URL, _ = url.Parse(fmt.Sprintf("%s://%s%s", scheme, req.Host, req.RequestURI))
req.RequestURI = ""
return req, nil
}
//// 将response转为字节
func EncodeResponse(r *http.Response) ([]byte, error) {
respBytes, err := httputil.DumpResponse(r, true)
if err != nil {
return nil, err
}
if config.Replace == 1 {
respBytes = replaceHost(respBytes)
}
return respBytes, nil
}
// 将字节转为response
func DecodeResponse(data []byte) (*http.Response, error) {
resp, err := http.ReadResponse(bufio.NewReader(bytes.NewReader(data)), nil)
if err != nil {
return nil, err
}
return resp, nil
}
func getHost(str string) (string, error) {
for _, v := range config.SiteList {
if v.Host == str {
return v.Url + ":" + strconv.Itoa(v.Port), nil
}
}
return "", errors.New("没有找到解析的的host!")
}
func replaceHost(resp []byte) []byte {
str := string(resp)
for _, v := range config.SiteList {
str = strings.Replace(str, v.Url+":"+strconv.Itoa(v.Port), v.Host, -1)
str = strings.Replace(str, v.Url, v.Host, -1)
}
return []byte(str)
}
func relay(in, out *Conn, compressType int) {
buf := make([]byte, 32*1024)
switch compressType {
case COMPRESS_GZIP_ENCODE:
w := gzip.NewWriter(in)
for {
n, err := out.Read(buf)
if err != nil || err == io.EOF {
break
}
if _, err = w.Write(buf[:n]); err != nil {
break
}
if err = w.Flush(); err != nil {
log.Println(err)
break
}
}
w.Close()
case COMPRESS_SNAPY_ENCODE:
w := snappy.NewBufferedWriter(in)
for {
n, err := out.Read(buf)
if err != nil || err == io.EOF {
break
}
if _, err = w.Write(buf[:n]); err != nil {
break
}
if err = w.Flush(); err != nil {
log.Println(err)
break
}
}
w.Close()
case COMPRESS_GZIP_DECODE:
r, err := gzip.NewReader(out)
if err != nil {
return
}
io.Copy(in, r)
case COMPRESS_SNAPY_DECODE:
r := snappy.NewReader(out)
io.Copy(in, r)
default:
io.Copy(in, out)
}
out.Close()
}
Executable
+12
View File
@@ -0,0 +1,12 @@
package main
import (
"crypto/sha1"
"time"
)
// 简单的一个校验值
func getverifyval() []byte {
b := sha1.Sum([]byte(time.Now().Format("2006-01-02 15") + *verifyKey))
return b[:]
}