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
|
package main
import (
"io"
"net"
"strconv"
"log"
)
func println(s...interface{}){
log.Println(s...)
}
func parseProtocol(c net.Conn) {
buf := make([]byte, 1024)
len, err := c.Read(buf)
if len == 0 || err != nil {
println("[parse protol] read data fail!")
return
}
if buf[0] != 0x05 {
println("[parse protol] illegal data!")
return
}
len, err = c.Write([]byte{0x05, 0x00})
if len != 2 || err != nil {
println("[parse protol] write data fail!")
return
}
len, err = c.Read(buf)
if len == 0 || err != nil {
println("[parse protol] read data fail!")
return
}
if buf[0] != 0x05 || buf[1] != 0x01 {
println("[parse protol] illegal data!")
return
}
var ip string
var port int
switch buf[3] {
case 0x01:
ip = net.IPv4(buf[4], buf[5], buf[6], buf[7]).String()
port = int(buf[len-2:][0])<<8 | int(buf[len-2:][1])
case 0x03:
ip = string(buf[4 : len-2])
port = int(buf[len-2:][0])<<8 | int(buf[len-2:][1])
}
addr := net.JoinHostPort(ip, strconv.Itoa(port))
println("start proxy:",addr)
r, err := net.Dial("tcp", addr)
if err != nil {
println("connect proxy addr fail!", err.Error())
return
}
len, err = c.Write([]byte{0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})
if len != 10 || err != nil {
println("[parse protol] write data fail!",err.Error())
return
}
go forward(c, r, buf)
go forward(r, c, buf)
}
func forward(c, r net.Conn, buf []byte) {
defer c.Close()
defer r.Close()
for {
len, err := c.Read(buf)
if len <= 0 || (err != nil && err != io.EOF) {
break
}
len, err = r.Write(buf[0:len])
if len <= 0 || err != nil {
break
}
}
}
func main() {
in, err := net.Listen("tcp", ":8080")
if err != nil {
println("bind 8080 fail!",err.Error())
return
}
println("start server ok. listen port 8080")
for {
c, err := in.Accept()
if err != nil {
println("accept fail!",err.Error())
continue
}
go parseProtocol(c)
}
}
|