Compare commits

...
27 Commits
Author SHA1 Message Date
刘河 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
13 changed files with 1555 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.
+277 -1
View File
@@ -1,2 +1,278 @@
# easyProxy
简单、轻量级http代理服务器,主要应用于内网穿透
轻量级、高性能http代理服务器,主要应用于内网穿透。支持三种模式,**http代理请求**、**tcp隧道模式**、**sock5代理模式**,可根据自身需求进行选择。
支持客户端与服务端连接中断自动重连,多路传输,大大的提高请求处理速度,go语言编写,无第三方依赖,经过测试内存占用小,普通场景下,仅占用10m内存。
水平很有限,不足指出请大家指出
## 背景
1. 我有一个小程序的需求,但是小程序的数据源必须从内网才能抓取到,但是又苦于内网服务器没有公网ip,所以只能内网穿透了。----> [http代理请求](#http代理请求)
2. 想在外网通过ssh连接内网的机器,或者做云服务器到内网服务器端口的映射备---->[tcp隧道模式](#tcp隧道模式)
3. 在外网如同使用内网vpn一样访问内网资源或者设备----> [sock5代理模式](#sock5代理模式)
## 特点
- [x] 支持gzip压缩,减小流量消耗
- [x] 支持多站点配置,兼容多个内网网站
- [x] 断线自动重连
- [x] 支持多路传输,提高并发
- [x] 跨站自动匹配替换
- [x] 支持tcp隧道,提升访问效率
- [x] 支持内网穿透sock5代理,达到在非内网环境下访问内网的效果
- [x] 专注内网穿透
## 目录
1. [安装](#安装)
2. [http代理请求](#http代理请求)
3. [tcp隧道模式](#tcp隧道模式)
4. [sock5代理模式](#sock5代理模式)
5. [操作系统支持](#操作系统支持)
## 安装
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请求后,将请求发送到客户端,客户端再执行这个请求,并将结果返回给服务端,服务端收到后再返回给用户。
### 使用
- 服务端
```
./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": "server1.ourcauc.com",
"url": "10.1.50.203",
"port": 80
},
{
"host": "server2.ourcauc.com",
"url": "10.1.50.196",
"port": 4000
}
],
"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 server1.ourcauc.com server2.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;
}
}
```
## 域名配置示例
> -server1 A 123.206.77.88
> -server2 A 123.206.77.88
### 跨站自动匹配替换说明
例如,访问:server1.ourcauc.com,该页面里面有一个超链接为10.1.50.196:4000,将根据配置文件自动该将url替换为server2.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端口相当于访问内网目标ip的目标端口,构成如下所示的隧道。
服务端<----->客户端<----->目标地址
### 使用
- 服务端
```
./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 | 服务端与客户端通信连接数
## sock5代理模式
### 场景及原理
主要用于sock5代理,也就是和ss类似,不过是代理内网。使用此模式时,可在非内网环境下配置本机的sock5代理(服务器ip、sock5代理端口),即可实现sock5代理,达到访问内网的网站的效果。
### 使用
- 服务端
```
./easyProxy -mode sock5Server -vkey DKibZF5TXvic1g3kY -tcpport=8284 -httpport=8024
```
名称 | 含义
---|---
mode | 运行模式(client、server不写默认client)
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
httpport | 代理的http端口(与nginx配合使用)
- 客户端
```
建立配置文件 config.json
```
```
./easyProxy -config config.json
```
- 需要使用内网代理的机器
```
配置sock5即可,ip为外网服务器ip,端口为httpport,即可在外网环境使用内网啦!
```
名称 | 含义
---|---
config | 配置文件路径
### 配置文件config.json
```
{
"Server": {
"ip": "123.206.77.88",
"tcp": 8284,
"vkey": "DKibZF5TXvic1g3kY",
"num": 10
}
}
```
名称 | 含义
---|---
ip | 服务端ip地址
tcp | 服务端与客户端通信端口
vkey | 验证密钥
num | 服务端与客户端通信连接数
## 操作系统支持
支持Windows、Linux、MacOSX等,无第三方依赖库。
Executable
+145
View File
@@ -0,0 +1,145 @@
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 < 10; 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 := conn.Write(getverifyval()); err != nil {
return err
}
//默认长连接保持
c := NewConn(conn)
c.SetAlive()
//写标志
c.wChan()
//获取连接的host
host, err := c.GetHostFromConn()
if err != nil {
return err
}
//与目标建立连接
server, err := net.Dial("tcp", host)
if err != nil {
fmt.Println(err)
return err
}
//创建成功后io.copy
go relay(server, c.conn)
relay(c.conn, server)
return nil
}
//http模式处理
func (s *TRPClient) dealHttp(c *Conn) error {
nlen, err := c.GetLen()
if err != nil {
c.wError()
return err
}
raw, err := c.ReadLen(int(nlen))
if err != nil {
c.wError()
return err
}
req, err := DecodeRequest(raw)
if err != nil {
c.wError()
return err
}
respBytes, err := GetEncodeResponse(req)
if err != nil {
c.wError()
return err
}
n, err := c.Write(respBytes)
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
}
]
}
+153
View File
@@ -0,0 +1,153 @@
package main
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"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.conn.Read(val)
if err != nil {
return 0, err
}
nlen := binary.LittleEndian.Uint32(val)
if nlen <= 0 {
return 0, errors.New("数据长度错误")
}
return int(nlen), nil
}
//读取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() (string, error) {
len, err := s.GetLen()
if err != nil {
return "", err
}
hostByte := make([]byte, len)
_, err = s.conn.Read(hostByte)
if err != nil {
return "", err
}
return string(hostByte), nil
}
//获取host
func (s *Conn) WriteHost(host string) (int, error) {
raw := bytes.NewBuffer([]byte{})
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) wError() {
s.conn.Write([]byte(RES_MSG))
}
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)
}
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
+60
View File
@@ -0,0 +1,60 @@
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", "tunnel模式远程目标")
verifyKey = flag.String("vkey", "", "验证密钥")
config Config
err error
)
func main() {
flag.Parse()
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
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)
svr.Start()
} else if *rpMode == "httpProxyServer" {
svr := NewTunnelModeServer(*tcpPort, *httpPort, *tunnelTarget, ProcessHttp)
svr.Start()
}
}
}
Executable
+209
View File
@@ -0,0 +1,209 @@
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
}
c, err := conn.Write(raw)
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:
nlen, err := c.GetLen()
if err != nil {
return err
}
raw, err := c.ReadLen(nlen)
if err != nil {
return err
}
resp, err := DecodeResponse(raw)
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(s.tunnelTarget); err != nil {
link.Close()
goto retry
}
go relay(link.conn, c.conn)
relay(c.conn, link.conn)
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(addr); err != nil {
link.Close()
goto retry
}
if method == "CONNECT" {
fmt.Fprint(c, "HTTP/1.1 200 Connection established\r\n")
} else {
link.Write(rb)
}
go relay(link.conn, c.conn)
relay(c.conn, link.conn)
return nil
}
+236
View File
@@ -0,0 +1,236 @@
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
)
type Sock5ModeServer struct {
Tunnel
httpPort int
}
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)))
//取出一个连接
if len(s.tunnelList) < 10 { //新建通道
go s.newChan()
}
client := <-s.tunnelList
s.sendReply(c, succeeded)
_, err = client.WriteHost(addr)
return client, nil
}
func (s *Sock5ModeServer) handleConnect(c net.Conn) {
proxyConn, err := s.doConnect(c, connectMethod)
if err != nil {
c.Close()
} else {
go io.Copy(c, proxyConn)
go io.Copy(proxyConn, c)
}
}
func (s *Sock5ModeServer) relay(in, out net.Conn) {
if _, err := io.Copy(in, out); err != nil {
log.Println("copy error", err)
}
in.Close() // will trigger an error in the other relay, then call out.Close()
}
// 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 io.Copy(c, proxyConn)
go io.Copy(proxyConn, c)
}
}
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
}
// no authentication required for now
buf[1] = 0
// send a METHOD selection message
c.Write(buf)
s.handleRequest(c)
}
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) *Sock5ModeServer {
s := new(Sock5ModeServer)
s.tunnelPort = tcpPort
s.httpPort = httpPort
s.tunnelList = make(chan *Conn, 1000)
s.signalList = make(chan *Conn, 10)
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
}
+150
View File
@@ -0,0 +1,150 @@
package main
import (
"bufio"
"bytes"
"compress/gzip"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strconv"
"strings"
)
var (
disabledRedirect = errors.New("disabled redirect.")
)
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 的处理
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))
fmt.Println(req.URL)
req.RequestURI = ""
return req, nil
}
//// 将response转为字节
func EncodeResponse(r *http.Response) ([]byte, error) {
raw := bytes.NewBuffer([]byte{})
binary.Write(raw, binary.LittleEndian, []byte(RES_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)
}
func relay(in, out net.Conn) {
io.Copy(in, out);
in.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[:]
}