generated from vshn/go-bootstrap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
91 lines (76 loc) · 1.8 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"fmt"
"io"
"net"
"os"
"github.com/micro/cli/v2"
"golang.org/x/net/proxy"
)
func main() {
app := cli.NewApp()
app.Usage = "Connect TCP over SOCKS5"
app.Flags = []cli.Flag{
&cli.IntFlag{
Name: "port",
Aliases: []string{"p"},
Usage: "local listen port",
Value: 12345,
},
&cli.StringFlag{
Name: "socks5",
Aliases: []string{"x"},
Usage: "socks5 server",
Value: "127.0.0.1:1080",
},
&cli.StringFlag{
Name: "target",
Aliases: []string{"t"},
Usage: "target address including port",
Required: true,
},
}
app.Action = func(c *cli.Context) error {
port := c.Int("port")
socks5 := c.String("socks5")
target := c.String("target")
addr := fmt.Sprintf(":%d", port)
l, err := net.Listen("tcp", addr)
if err != nil {
fmt.Printf("listen fail: %v\n", err)
return err
}
socks5dialer, err := proxy.SOCKS5("tcp", socks5, nil, nil)
if err != nil {
fmt.Printf("new socks5 dialer fail: %v\n", err)
return err
}
fmt.Printf("listen address: '%v'\n", addr)
for {
conn, err := l.Accept()
if err != nil {
fmt.Printf("accept fail: %v\n", err)
continue
}
go handleConnection(socks5dialer.Dial, conn, target)
}
}
err := app.Run(os.Args)
if err != nil {
fmt.Printf("run fail: %v", err)
}
}
func handleConnection(dialer func(network, address string) (net.Conn, error), conn net.Conn, addr string) {
defer conn.Close()
fmt.Printf("new connection %s -> %s\n", conn.RemoteAddr().String(), addr)
remote, err := dialer("tcp", addr)
if err != nil {
fmt.Printf("dial %s fail: %v\n", addr, err)
return
}
defer remote.Close()
fmt.Printf("connect proxy %s ok\n", addr)
go io.Copy(conn, remote)
io.Copy(remote, conn)
fmt.Printf("connection %s -> %s closed\n", conn.RemoteAddr().String(), addr)
}