-
Notifications
You must be signed in to change notification settings - Fork 1
/
sockstun.go
194 lines (175 loc) · 4.33 KB
/
sockstun.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package sockstun
import (
"context"
"fmt"
"io"
"log"
"net"
"net/url"
"strings"
"sync"
"time"
"github.com/pkg/errors"
"golang.org/x/net/proxy"
"golang.org/x/sync/errgroup"
)
type fwdRule struct {
name string
localSock, remoteSock string
}
func (r fwdRule) String() string {
return fmt.Sprintf("%s (%s->%s)", r.name, r.localSock, r.remoteSock)
}
type SOCKSTunnel struct {
proto string
socksDialer proxy.ContextDialer
rwTimeout time.Duration
fwdTable []fwdRule
fwdTableMu sync.RWMutex
log *log.Logger
}
func (st *SOCKSTunnel) Add(name, lsock, rsock string) {
r := fwdRule{name: name, localSock: lsock, remoteSock: rsock}
st.fwdTableMu.Lock()
st.fwdTable = append(st.fwdTable, r)
st.fwdTableMu.Unlock()
}
func (st *SOCKSTunnel) Run(ctx context.Context) error {
eg, ctx := errgroup.WithContext(ctx)
st.fwdTableMu.RLock()
for _, r := range st.fwdTable {
r := r
eg.Go(func() error {
return st.enable(ctx, r)
})
}
st.fwdTableMu.RUnlock()
return eg.Wait()
}
func (st *SOCKSTunnel) enable(ctx context.Context, r fwdRule) error {
l, err := net.Listen(st.proto, r.localSock)
if err != nil {
return errors.Wrap(err, "failed to listen on local socket")
}
close := (func() func() {
var once sync.Once
return func() {
once.Do(func() {
if err := l.Close(); err != nil {
st.log.Printf("failed to close local socket %s: %v", r.localSock, err)
}
})
}
})()
defer close()
st.log.Printf("enabling proxy rule %s", r)
go func() {
<-ctx.Done()
close()
}()
for {
conn, err := l.Accept()
if err != nil {
// TODO(leon): remove this string search. That might involve
// modifying the standard library to return better error types.
if strings.Contains(err.Error(), "use of closed network connection") {
return ctx.Err()
}
st.log.Printf("failed to accept on local socket %s: %v", r.localSock, err)
continue
}
go func() {
if err := st.handle(ctx, conn, r); err != nil {
st.log.Printf("failed to handle conn on local socket %s: %v", r.localSock, err)
}
}()
}
}
func (st *SOCKSTunnel) handle(ctx context.Context, conn net.Conn, r fwdRule) error {
var (
doCleanup = true
cleanupFunc = func() {
if err := conn.Close(); err != nil {
st.log.Printf("%s: failed to close: %v", r, err)
}
}
cleanup = (func() func() {
var once sync.Once
return func() {
once.Do(cleanupFunc)
}
})()
)
defer func() {
if doCleanup {
cleanup()
}
}()
sconn, err := st.socksDialer.DialContext(ctx, st.proto, r.remoteSock)
if err != nil {
return errors.Wrap(err, "failed to dial SOCKS proxy")
}
oldFunc := cleanupFunc
cleanupFunc = func() {
oldFunc()
if err := sconn.Close(); err != nil {
st.log.Printf("%s: failed to close SOCKS conn: %v", r, err)
}
}
if t := st.rwTimeout; t > 0 {
dl := time.Now().Add(t)
if err := conn.SetDeadline(dl); err != nil {
return errors.Wrap(err, "failed to set conn deadline")
}
if err := sconn.SetDeadline(dl); err != nil {
return errors.Wrap(err, "failed to set SOCKS deadline")
}
}
pipe := func(src, dst net.Conn) {
defer cleanup()
const maxSize = 65535
buf := make([]byte, maxSize)
for {
n, err := src.Read(buf)
if err != nil {
// TODO(leon): remove this string search. That might involve
// modifying the standard library to return better error types.
if err != io.EOF && !strings.Contains(err.Error(), "use of closed network connection") {
st.log.Printf("%s: failed to read: %v", r, err)
}
return
}
b := buf[:n]
_, err = dst.Write(b)
if err != nil {
st.log.Printf("%s: failed to write: %v", r, err)
return
}
}
}
doCleanup = false
go pipe(conn, sconn)
go pipe(sconn, conn)
return nil
}
func New(socksURI string, rwTimeout time.Duration, log *log.Logger) (*SOCKSTunnel, error) {
su, err := url.Parse(socksURI)
if err != nil {
return nil, errors.Wrap(err, "failed to parse SOCKS URL")
}
dialer, err := proxy.FromURL(su, proxy.Direct)
if err != nil {
return nil, errors.Wrap(err, "failed to create SOCKS dialer")
}
ctxDialer, ok := dialer.(proxy.ContextDialer)
if !ok {
// This will never happen. proxy.Direct implements proxy.ContextDialer.
panic("failed to type assert to proxy.ContextDialer")
}
return &SOCKSTunnel{
proto: "tcp",
socksDialer: ctxDialer,
rwTimeout: rwTimeout,
log: log,
}, nil
}