forked from getlantern/marionette
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_proxy.go
92 lines (75 loc) · 1.88 KB
/
server_proxy.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
package marionette
import (
"io"
"net"
"sync"
"github.com/armon/go-socks5"
"go.uber.org/zap"
)
// ServerProxy represents a proxy between a marionette listener and another server.
type ServerProxy struct {
ln *Listener
wg sync.WaitGroup
// Host and port to proxy requests to.
// Ignored if a socks5 server is enabled.
Addr string
// Server used for proxying requests.
Socks5Server *socks5.Server
}
// NewServerProxy returns a new instance of ServerProxy.
func NewServerProxy(ln *Listener) *ServerProxy {
return &ServerProxy{ln: ln}
}
func (p *ServerProxy) Open() error {
p.wg.Add(1)
go func() { defer p.wg.Done(); p.run() }()
return nil
}
func (p *ServerProxy) Close() error {
return nil
}
func (p *ServerProxy) run() {
Logger.Debug("server proxy: listening")
defer Logger.Debug("server proxy: closed")
for {
conn, err := p.ln.Accept()
if err != nil {
Logger.Debug("server proxy: listener error", zap.Error(err))
return
}
p.wg.Add(1)
go func() { defer p.wg.Done(); p.handleConn(conn) }()
}
}
func (p *ServerProxy) handleConn(conn net.Conn) {
defer conn.Close()
Logger.Debug("server proxy: connection open")
defer Logger.Debug("server proxy: connection closed")
// If the proxy address is "socks5" then hand off to socks5 server.
if p.Socks5Server != nil {
if err := p.Socks5Server.ServeConn(conn); err != nil {
Logger.Debug("server proxy: socks5 error", zap.Error(err))
}
return
}
// Connect to remote server.
proxyConn, err := net.Dial("tcp", p.Addr)
if err != nil {
Logger.Debug("server proxy: cannot connect to remote server", zap.String("address", p.Addr))
return
}
defer proxyConn.Close()
// Copy between connection and proxy until an error occurs.
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
io.Copy(proxyConn, conn)
proxyConn.Close()
}()
go func() {
defer wg.Done()
io.Copy(conn, proxyConn)
}()
wg.Wait()
}