/
main.go
75 lines (62 loc) · 1.33 KB
/
main.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
package main
import (
"bytes"
"flag"
httproxy "github.com/justmao945/httproxy/http"
socks5 "github.com/justmao945/httproxy/socks"
"io"
"log"
"net"
"time"
)
const (
socks5Version = uint8(5)
)
type combConn struct {
net.Conn
r io.Reader
}
func (c combConn) Read(p []byte) (int, error) {
return c.r.Read(p)
}
var socks5Server = socks5.New(&socks5.Config{})
func handConn(conn net.Conn) {
firstByte := []byte{0}
_, err := conn.Read(firstByte)
if err != nil {
log.Printf("read fist byte failed: %v\n", err)
return
}
conn2 := combConn{
conn,
io.MultiReader(bytes.NewReader(firstByte), conn),
}
if firstByte[0] == socks5Version {
socks5Server.ServeConn(conn2)
} else {
httproxy.ServeConn(conn2)
}
}
func main() {
var flagAddr string
log.SetFlags(log.Lshortfile | log.LstdFlags)
flag.StringVar(&flagAddr, "addr", ":8080", "serve HTTP and SOCKS5 proxy address")
flag.Parse()
listener, err := net.Listen("tcp", flagAddr)
if err != nil {
log.Fatalf("listen failed: %v\n", err)
}
log.Printf("listen HTTP and SOCKS5 proxy on %v\n", flagAddr)
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("accept failed: %v\n", err)
if nerr, ok := err.(net.Error); ok && nerr.Temporary() {
time.Sleep(10 * time.Millisecond)
continue
}
return // fatal error, stop
}
go handConn(conn)
}
}