-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_conn.go
122 lines (100 loc) · 1.74 KB
/
client_conn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"io"
"strings"
"context"
"net/http"
"sync"
"log"
"net"
"bufio"
"github.com/armon/go-socks5"
)
var socksServer *socks5.Server
func init() {
conf := &socks5.Config{
Dial: proxyDial,
}
var err error
socksServer, err = socks5.New(conf)
if err != nil {
panic(err)
}
}
type clientConn struct {
net.Conn
r *bufio.Reader
}
func newClientConn(c net.Conn) *clientConn {
return &clientConn {
Conn: c,
r: bufio.NewReader(c),
}
}
func (cc *clientConn) Read(p []byte) (int, error) {
return cc.r.Read(p)
}
func (cc *clientConn) serve() {
defer func(){
cc.Close()
}()
wg := &sync.WaitGroup{}
buf,err:=cc.r.Peek(1)
if err != nil {
return
}
if buf[0] == uint8(5) {
cc.serveSocks5(wg)
} else {
cc.serveHTTP(wg)
}
wg.Wait()
}
func (cc *clientConn) serveSocks5(wg *sync.WaitGroup) {
wg.Add(1)
socksServer.ServeConn(cc)
}
func (cc *clientConn) serveHTTP(wg *sync.WaitGroup) {
req,err:=http.ReadRequest(cc.r)
if err != nil {
return
}
log.Println(req)
host := req.Host
if !strings.Contains(req.Host, ":") {
host += ":80"
}
serverConn, err := proxyDial(context.TODO(), "tcp", host)
if err != nil {
return
}
if req.Method == "CONNECT" {
rsp:="HTTP/1.1 200 Connection Established\r\nProxy-Agent: simpless\r\n\r\n"
_, err = cc.Write([]byte(rsp))
if err != nil {
return
}
} else {
err = req.Write(serverConn)
if err != nil {
return
}
}
wg.Add(2)
splice := func(r io.ReadCloser, w io.Writer, closeReader bool) {
defer wg.Done()
b := make([]byte, 1024)
for {
n,err:=r.Read(b)
if n == 0 || err != nil {
break
}
nn,err:=w.Write(b[:n])
if n != nn || err != nil {
break
}
}
}
go splice(cc, serverConn, false)
go splice(serverConn, cc, true)
}