forked from mmatczuk/go-http-tunnel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
320 lines (273 loc) · 7.42 KB
/
server.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package tunnel
import (
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
"github.com/andrew-d/id"
"github.com/koding/logging"
"github.com/mmatczuk/tunnel/proto"
"golang.org/x/net/http2"
)
// AllowedClient specifies client entry points on server.
type AllowedClient struct {
// ID is client TLS certificate ID.
ID id.ID
// Host is URL host name, http requests to that host will be routed to the client.
Host string
// Listeners is a list of listeners, connections the listeners accept
// will be routed to the client.
Listeners []net.Listener
}
// ServerConfig defines configuration for the Server.
type ServerConfig struct {
// Addr is tcp address to listen on for client connections, ":0" if empty.
Addr string
// TLSConfig specifies the tls configuration to use with tls.Listener.
TLSConfig *tls.Config
// Listener specifies optional listener that clients would connect to.
// If Listener is nil tls.Listen("tcp", Addr, TLSConfig) is used.
Listener net.Listener
// AllowedClients specifies clients that can connect to the server.
AllowedClients []*AllowedClient
// Log specifies the logger. If nil a default logging.Logger is used.
Log logging.Logger
}
// Server is responsible for proxying public connections to the client over a
// tunnel connection.
type Server struct {
config *ServerConfig
listener net.Listener
connPool *connPool
httpClient *http.Client
log logging.Logger
}
// NewServer creates a new Server.
func NewServer(config *ServerConfig) (*Server, error) {
l, err := listener(config)
if err != nil {
return nil, fmt.Errorf("tls listener failed :%s", err)
}
t := &http2.Transport{}
p := newConnPool(t)
t.ConnPool = p
log := logging.NewLogger("server")
if config.Log != nil {
log = config.Log
}
return &Server{
config: config,
listener: l,
connPool: p,
httpClient: &http.Client{Transport: t},
log: log,
}, nil
}
func listener(config *ServerConfig) (net.Listener, error) {
if config.Listener != nil {
return config.Listener, nil
}
addr := ":0"
if config.Addr != "" {
addr = config.Addr
}
return tls.Listen("tcp", addr, config.TLSConfig)
}
// Start starts accepting connections form clients and allowed clients listeners.
// For accepting http traffic one must run server as a handler to http server.
func (s *Server) Start() {
go s.listenControl()
s.listenClientListeners()
}
func (s *Server) listenControl() {
for {
conn, err := s.listener.Accept()
if err != nil {
s.log.Warning("Accept %s control connection to %q failed: %s",
s.listener.Addr().Network(), s.listener.Addr().String(), err)
if strings.Contains(err.Error(), "use of closed network connection") {
return
}
continue
}
s.log.Info("Accepted %s control connection from %q to %q",
s.listener.Addr().Network(), conn.RemoteAddr(), s.listener.Addr().String())
go s.handleClient(conn)
}
}
func (s *Server) handleClient(conn net.Conn) {
var (
client *AllowedClient
req *http.Request
resp *http.Response
err error
ok bool
)
id, err := peerID(conn.(*tls.Conn))
if err != nil {
s.log.Warning("Certificate error: %s", err)
goto reject
}
client, ok = s.checkID(id)
if !ok {
s.log.Warning("Unknown certificate: %q", id.String())
goto reject
}
req, err = http.NewRequest(http.MethodConnect, clientURL(client.Host), nil)
if err != nil {
s.log.Error("Invalid host %q for client %q", client.Host, client.ID)
goto reject
}
if err = conn.SetDeadline(time.Time{}); err != nil {
s.log.Warning("Setting no deadline failed: %s", err)
// recoverable
}
if err := s.connPool.addHostConn(client.Host, conn); err != nil {
s.log.Warning("Could not add host: %s", err)
goto reject
}
resp, err = s.httpClient.Do(req)
if err != nil {
s.log.Warning("Handshake failed %s", err)
goto reject
}
if resp.StatusCode != http.StatusOK {
s.log.Warning("Handshake failed")
goto reject
}
s.log.Info("Client %q connected from %q", client.ID, conn.RemoteAddr().String())
return
reject:
conn.Close()
if client != nil {
s.connPool.markHostDead(client.Host)
}
}
func (s *Server) checkID(id id.ID) (*AllowedClient, bool) {
for _, c := range s.config.AllowedClients {
if id.Equals(c.ID) {
return c, true
}
}
return nil, false
}
func (s *Server) listenClientListeners() {
for _, client := range s.config.AllowedClients {
if client.Listeners == nil {
continue
}
for _, l := range client.Listeners {
go s.listen(l, client)
}
}
}
func (s *Server) listen(l net.Listener, client *AllowedClient) {
for {
conn, err := l.Accept()
if err != nil {
s.log.Warning("Accept %s connection to %q failed: %s",
s.listener.Addr().Network(), s.listener.Addr().String(), err)
if strings.Contains(err.Error(), "use of closed network connection") {
return
}
continue
}
s.log.Debug("Accepted %s connection from %q to %q",
l.Addr().Network(), conn.RemoteAddr(), l.Addr().String())
msg := &proto.ControlMessage{
Action: proto.RequestClientSession,
Protocol: l.Addr().Network(),
ForwardedFor: conn.RemoteAddr().String(),
ForwardedBy: l.Addr().String(),
}
go func() {
err := s.proxyConn(client.Host, conn, msg)
if err != nil {
s.log.Warning("Error %s: %s", msg, err)
}
}()
}
}
func (s *Server) proxyConn(host string, conn net.Conn, msg *proto.ControlMessage) error {
pr, pw := io.Pipe()
defer pr.Close()
defer pw.Close()
req, err := http.NewRequest(http.MethodPut, clientURL(host), pr)
if err != nil {
return fmt.Errorf("request creation error: %s", err)
}
msg.WriteTo(req.Header)
go transfer("local to remote", pw, conn)
resp, err := s.httpClient.Do(req)
if err != nil {
return fmt.Errorf("proxy request error: %s", err)
}
transfer("remote to local", conn, resp.Body)
return nil
}
// ServeHTTP proxies http connection to the client.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
resp, err := s.RoundTrip(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
}
copyHeader(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
if resp.Body != nil {
transfer("remote to local", w, resp.Body)
}
}
// RoundTrip is http.RoundTriper implementation.
func (s *Server) RoundTrip(r *http.Request) (*http.Response, error) {
msg := &proto.ControlMessage{
Action: proto.RequestClientSession,
Protocol: proto.HTTP,
ForwardedFor: r.RemoteAddr,
ForwardedBy: r.Host,
URLPath: r.URL.Path,
}
return s.proxyHTTP(trimPort(r.Host), r, msg)
}
func (s *Server) proxyHTTP(host string, r *http.Request, msg *proto.ControlMessage) (*http.Response, error) {
pr, pw := io.Pipe()
defer pr.Close()
defer pw.Close()
req, err := http.NewRequest(http.MethodPut, clientURL(host), pr)
if err != nil {
return nil, fmt.Errorf("request creation error: %s", err)
}
msg.WriteTo(req.Header)
go func() {
cw := &countWriter{pw, 0}
err := r.Write(cw)
if err != nil {
s.log.Error("Write to pipe failed: %s", err)
}
TransferLog.Debug("Coppied %d bytes from %s", cw.count, "local to remote")
if r.Body != nil {
r.Body.Close()
}
}()
resp, err := s.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("proxy request error: %s", err)
}
return resp, nil
}
// Addr returns network address clients connect to.
func (s *Server) Addr() string {
if s.listener == nil {
return ""
}
return s.listener.Addr().String()
}
// Close closes the server.
func (s *Server) Close() error {
if s.listener == nil {
return nil
}
return s.listener.Close()
}