forked from getlantern/marionette
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_proxy.go
88 lines (74 loc) · 1.85 KB
/
client_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
package marionette
import (
"io"
"net"
"sync"
"go.uber.org/zap"
)
// ClientProxy represents a proxy between incoming connections and a marionette dialer.
type ClientProxy struct {
ln net.Listener
dialer *Dialer
wg sync.WaitGroup
}
// NewClientProxy returns a new instance of ClientProxy.
func NewClientProxy(ln net.Listener, dialer *Dialer) *ClientProxy {
return &ClientProxy{
ln: ln,
dialer: dialer,
}
}
// Open starts the proxy listeners and waits for connections.
func (p *ClientProxy) Open() error {
p.wg.Add(1)
go func() { defer p.wg.Done(); p.run() }()
return nil
}
// Close stops the listener.
func (p *ClientProxy) Close() error {
if p.ln != nil {
return p.ln.Close()
}
return nil
}
// run executes in a separate goroutine and continually processes incoming connections.
func (p *ClientProxy) run() {
Logger.Debug("client proxy: listening")
defer Logger.Debug("client proxy: closed")
for {
conn, err := p.ln.Accept()
if err != nil {
Logger.Debug("client proxy: listener error", zap.Error(err))
return
}
p.wg.Add(1)
go func() { defer p.wg.Done(); p.handleConn(conn) }()
}
}
// handleConn continually copies between the incoming connection and stream.
func (p *ClientProxy) handleConn(incomingConn net.Conn) {
defer incomingConn.Close()
Logger.Debug("client proxy: connection open")
defer Logger.Debug("client proxy: connection closed")
// Create a new stream.
stream, err := p.dialer.Dial()
if err != nil {
Logger.Debug("client proxy: cannot connect create new stream", zap.Error(err))
return
}
defer stream.Close()
// Copy between incoming connection and stream until an error occurs.
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
io.Copy(incomingConn, stream)
incomingConn.Close()
}()
go func() {
defer wg.Done()
io.Copy(stream, incomingConn)
stream.Close()
}()
wg.Wait()
}