-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
622 lines (573 loc) · 14.8 KB
/
server.go
File metadata and controls
622 lines (573 loc) · 14.8 KB
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
package fcbreak
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"errors"
"io"
"log"
"net"
"net/http"
"reflect"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
dissector "github.com/go-gost/tls-dissector"
)
var (
ErrorServiceNotFound = errors.New("Service is not found")
)
// getServiceInfoForOutput filters fields for output
func getServiceInfoForOutput(svc *ServiceReflector) *ServiceInfo {
info := svc.GetServiceInfo()
info.ProxyAddr = ""
return info
}
type Server struct {
User string
Pass string
mutex sync.RWMutex
httpServer *http.Server
shutdown chan struct{}
reflectors map[string]*ServiceReflector
httpMux map[string]*ServiceReflector
httpsMux map[string]*ServiceReflector
connGroup sync.WaitGroup
listenerGroup sync.WaitGroup
conns map[*net.Conn]struct{}
listeners map[*net.Listener]struct{}
}
func NewServer(user, pass string, tlsConf *tls.Config) *Server {
s := &Server{
User: user,
Pass: pass,
mutex: sync.RWMutex{},
shutdown: make(chan struct{}),
reflectors: map[string]*ServiceReflector{},
httpMux: map[string]*ServiceReflector{},
httpsMux: map[string]*ServiceReflector{},
conns: make(map[*net.Conn]struct{}),
listeners: make(map[*net.Listener]struct{}),
}
router := gin.Default()
s.httpServer = &http.Server{
Handler: router,
IdleTimeout: 30 * time.Minute,
TLSConfig: tlsConf,
ConnContext: saveConnInContext,
ConnState: s.connState,
}
var r *gin.RouterGroup
if s.User != "" && s.Pass != "" {
r = router.Group("/", gin.BasicAuth(gin.Accounts{s.User: s.Pass}))
} else {
r = router.Group("/")
}
r.GET("/services", s.GetServices)
r.GET("/services/:name", s.GetServiceByName)
r.POST("/services", s.PostService)
r.PUT("/services/:name", s.PutService)
r.PUT("/services/:name/addr", s.PutServiceExposedAddr)
r.PUT("/services/:name/proxy_addr", s.PutServiceProxyAddr)
r.DELETE("/services/:name", s.DeleteService)
return s
}
// not thread-safe!
func (s *Server) addService(svc *ServiceInfo) (*ServiceInfo, error) {
if r, found := s.reflectors[svc.Name]; found {
info := r.GetServiceInfo()
return info, errors.New("service [" + svc.Name + "] already exists")
}
if svc.Scheme == "http" {
for _, host := range svc.Hostnames {
if len(host) == 0 {
return svc, errors.New("empty host is illegal")
}
if ! verifyHostname(host) {
return svc, errors.New("host is illegal, host can contains no or one * at the beginning or at the ending")
}
if r, ok := s.httpMux[host]; ok {
info := r.GetServiceInfo()
return svc, errors.New("service [" + info.Name + "] already registered for the hostname: " + host)
}
}
}
if svc.Scheme == "https" {
for _, host := range svc.Hostnames {
if len(host) == 0 {
return svc, errors.New("empty host is illegal")
}
if r, ok := s.httpsMux[host]; ok {
info := r.GetServiceInfo()
return svc, errors.New("service [" + info.Name + "] already registered for the hostname: " + host)
}
}
}
r := NewServiceReflector(svc)
if len(r.info.RemoteAddr) > 0 {
if err := r.Listen(); err != nil {
return nil, err
}
go r.Serve()
}
s.reflectors[svc.Name] = r
if svc.Scheme == "http" {
for _, host := range svc.Hostnames {
s.httpMux[host] = r
}
} else if svc.Scheme == "https" {
for _, host := range svc.Hostnames {
s.httpsMux[host] = r
}
}
return svc, nil
}
// not thread-safe!
func (s *Server) updateService(ctx context.Context, name string, svc *ServiceInfo) (*ServiceInfo, error) {
if oldSvc, found := s.reflectors[name]; found {
if name != svc.Name {
log.Printf("Rename Service: [%s] -> [%s]", name, svc.Name)
oldSvc.Rename(name)
delete(s.reflectors, name)
s.reflectors[svc.Name] = oldSvc
}
oldInfo := oldSvc.GetServiceInfo()
// Need to restart
if oldInfo.RemoteAddr != svc.RemoteAddr ||
oldInfo.Scheme != svc.Scheme ||
!reflect.DeepEqual(oldInfo.Hostnames, svc.Hostnames) {
log.Printf("Update Service: [%s]", svc.Name)
if err := s.delService(ctx, oldInfo.Name); err != nil {
return nil, err
}
return s.addService(svc)
}
// Update Address
if oldInfo.ExposedAddr != svc.ExposedAddr || oldInfo.ProxyAddr != svc.ProxyAddr {
log.Printf("Update Service Address: [%s]", svc.Name)
oldSvc.UpdateAddr(&svc.ExposedAddr, &svc.ProxyAddr)
}
return oldSvc.GetServiceInfo(), nil
}
return nil, ErrorServiceNotFound
}
// not thread-safe!
func (s *Server) delService(ctx context.Context, name string) error {
if svc, found := s.reflectors[name]; found {
svc.Stop(ctx)
info := svc.GetServiceInfo()
if info.Scheme == "http" {
for _, host := range info.Hostnames {
delete(s.httpMux, host)
}
} else if info.Scheme == "https" {
for _, host := range info.Hostnames {
delete(s.httpsMux, host)
}
}
delete(s.reflectors, name)
return nil
}
return ErrorServiceNotFound
}
func (s *Server) labelConn(req *http.Request, svcName string) {
conn := getConnUnwarpTLS(req)
if wc, ok := conn.(*wrappedConn); ok {
wc.svc = &svcName
}
}
func (s *Server) AddService(svc *ServiceInfo) (*ServiceInfo, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.addService(svc)
}
func (s *Server) UpdateService(ctx context.Context, name string, svc *ServiceInfo) (*ServiceInfo, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.updateService(ctx, name, svc)
}
func (s *Server) DelService(ctx context.Context, name string) error {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.delService(ctx, name)
}
func (s *Server) GetServices(c *gin.Context) {
svcs := make(map[string]*ServiceInfo)
s.mutex.RLock()
for n, r := range s.reflectors {
svcs[n] = getServiceInfoForOutput(r)
}
s.mutex.RUnlock()
c.IndentedJSON(http.StatusOK, svcs)
}
func (s *Server) GetServiceByName(c *gin.Context) {
name := c.Param("name")
s.mutex.RLock()
r, ok := s.reflectors[name]
s.mutex.RUnlock()
if !ok {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "service not found"})
return
}
c.IndentedJSON(http.StatusOK, getServiceInfoForOutput(r))
}
func (s *Server) PostService(c *gin.Context) {
svc := &ServiceInfo{}
if err := c.BindJSON(&svc); err != nil {
c.IndentedJSON(http.StatusBadRequest, gin.H{"message": err.Error()})
return
}
svc.ExposedAddr = c.Request.RemoteAddr
log.Printf("Register Service [%s]: %s://%s -> %s://%s", svc.Name, svc.Scheme, svc.RemoteAddr, svc.Scheme, svc.ExposedAddr)
info, err := s.AddService(svc)
if err != nil {
log.Printf("Register Service [%s] Error: %v", svc.Name, err)
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
return
}
s.labelConn(c.Request, info.Name)
c.IndentedJSON(http.StatusCreated, info)
}
func (s *Server) PutService(c *gin.Context) {
name := c.Param("name")
svc := &ServiceInfo{}
if err := c.BindJSON(&svc); err != nil {
c.IndentedJSON(http.StatusBadRequest, gin.H{"message": err.Error()})
return
}
svc.ExposedAddr = c.Request.RemoteAddr
log.Printf("Update Service [%s]: %s://%s -> %s://%s", name, svc.Scheme, svc.RemoteAddr, svc.Scheme, svc.ExposedAddr)
status := http.StatusOK
s.mutex.Lock()
info, err := s.updateService(c.Request.Context(), name, svc)
if err == ErrorServiceNotFound {
status = http.StatusCreated
info, err = s.addService(svc)
}
s.mutex.Unlock()
if err != nil {
log.Printf("Update Service [%s] Error: %v", svc.Name, err)
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
return
}
s.labelConn(c.Request, info.Name)
c.IndentedJSON(status, info)
}
func (s *Server) PutServiceExposedAddr(c *gin.Context) {
name := c.Param("name")
s.mutex.RLock()
r, ok := s.reflectors[name]
s.mutex.RUnlock()
if !ok {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "service not found"})
return
}
info := r.GetServiceInfo()
remoteAddr := c.Request.RemoteAddr
if info.ExposedAddr != remoteAddr {
r.UpdateAddr(&remoteAddr, nil)
info.ExposedAddr = remoteAddr
log.Printf("Update Service [%s]: %s://%s -> %s://%s", name, info.Scheme, info.RemoteAddr, info.Scheme, info.ExposedAddr)
}
s.labelConn(c.Request, info.Name)
c.IndentedJSON(http.StatusOK, info)
}
func (s *Server) PutServiceProxyAddr(c *gin.Context) {
name := c.Param("name")
s.mutex.RLock()
r, ok := s.reflectors[name]
s.mutex.RUnlock()
if !ok {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "service not found"})
return
}
info := r.GetServiceInfo()
remoteAddr := c.Request.RemoteAddr
if info.ProxyAddr != remoteAddr {
info.ProxyAddr = remoteAddr
log.Printf("Update Service [%s]: %s://%s -> %s://%s", name, info.Scheme, info.RemoteAddr, info.Scheme, info.ExposedAddr)
r.UpdateAddr(nil, &remoteAddr)
}
s.labelConn(c.Request, info.Name)
c.IndentedJSON(http.StatusOK, info)
}
func (s *Server) DeleteService(c *gin.Context) {
name := c.Param("name")
log.Printf("Delete Service [%s]", name)
if err := s.DelService(c.Request.Context(), name); err != nil {
log.Printf("Delete Service [%s] Error: %v", name, err)
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
return
}
c.IndentedJSON(http.StatusOK, gin.H{"message": "service deleted"})
}
type wrappedConn struct {
net.Conn
br *bufio.Reader
prepend []byte
svc *string // Tracking service corresponding to conn
}
func (c *wrappedConn) Read(b []byte) (int, error) {
if len(c.prepend) > 0 {
n := copy(b, c.prepend)
if n == len(c.prepend) {
c.prepend = nil
} else {
c.prepend = c.prepend[n:]
}
return n, nil
}
return c.br.Read(b)
}
func (s *Server) handle(conn net.Conn, fl *forwardListener, isTLS bool) {
// track only conns under server's control
s.trackConn(&conn, true)
defer s.trackConn(&conn, false)
br := bufio.NewReader(conn)
var readahead []byte
host := ""
var err error
if !isTLS {
// We assume it is an HTTP request
// HTTP sniff
readahead, host, err = readHTTPHost(br)
} else {
// TLS sniff
readahead, host, err = readClientHelloRecord(br)
}
if err != nil {
log.Printf("[handle] %s -> %s : %s",
conn.RemoteAddr(), conn.LocalAddr(), err)
conn.Close()
return
}
conn = &wrappedConn{br: br, Conn: conn, prepend: readahead}
if r, found := s.matchHost(host, isTLS); found {
err = r.Handle(conn)
if err != nil {
log.Printf("[service] %s -> %s : %s",
conn.RemoteAddr(), conn.LocalAddr(), err)
}
conn.Close()
} else {
fl.Forward(conn)
}
}
func (s *Server) matchHost(host string, isTLS bool) (*ServiceReflector, bool) {
if len(host) == 0 {
return nil, false
}
var mux *map[string]*ServiceReflector
if !isTLS {
mux = &s.httpMux
} else {
mux = &s.httpsMux
}
// Match Exact hostname
if r, ok := (*mux)[host]; ok {
return r, true
}
// Match leading asterisk
for key, reflector := range (*mux) {
if !strings.HasPrefix(key, "*") {
continue
}
if strings.HasSuffix(host, key[1:]) {
return reflector, true
}
}
// Match trailing asterisk
for key, reflector := range (*mux) {
if !strings.HasSuffix(key, "*") {
continue
}
if strings.HasPrefix(host, key[:len(key)-1]) {
return reflector, true
}
}
return nil, false
}
func (s *Server) connState(conn net.Conn, state http.ConnState) {
if state != http.StateClosed {
return
}
if tc, ok := conn.(*tls.Conn); ok {
conn = tc.NetConn()
}
wc, ok := conn.(*wrappedConn)
if !ok || wc.svc == nil {
return
}
name := *wc.svc
log.Printf("Service [%s] conn closed, Deleting.", name)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
if err := s.DelService(ctx, name); err != nil && err != ErrorServiceNotFound {
log.Printf("Delete Service [%s] Error: %v", name, err)
}
cancel()
}
func (s *Server) serve(l net.Listener, isTLS bool) error {
if s.shuttingDown() {
return errors.New("cannot serve on closed server")
}
l = &onceCloseListener{Listener: l}
defer func() {
s.trackListener(&l, false)
l.Close()
}()
s.trackListener(&l, true)
fl := newForwardListener(l.Addr())
if isTLS {
go s.httpServer.ServeTLS(fl, "", "")
} else {
go s.httpServer.Serve(fl)
}
for {
conn, err := l.Accept()
if err != nil {
if s.shuttingDown() {
return http.ErrServerClosed
}
return err
}
go s.handle(conn, fl, isTLS)
}
}
func (s *Server) Serve(l net.Listener) error {
return s.serve(l, false)
}
func (s *Server) ServeTLS(l net.Listener) error {
return s.serve(l, true)
}
func (s *Server) Shutdown(ctx context.Context) error {
close(s.shutdown)
// Graceful Shutdown until context done
waitCh := make(chan struct{})
go func() {
for ln := range s.listeners {
(*ln).Close()
}
s.connGroup.Wait() // wait for conns
s.listenerGroup.Wait()
s.httpServer.Shutdown(ctx)
close(waitCh)
}()
select {
case <-ctx.Done():
// Force close
for c := range s.conns {
(*c).Close()
}
return ctx.Err()
case <-waitCh:
return nil
}
}
func (s *Server) shuttingDown() bool {
select {
case <-s.shutdown:
return true
default:
}
return false
}
func (s *Server) trackListener(ln *net.Listener, add bool) bool {
s.mutex.Lock()
defer s.mutex.Unlock()
if add {
if s.shuttingDown() {
return false
}
s.listeners[ln] = struct{}{}
s.listenerGroup.Add(1)
} else {
delete(s.listeners, ln)
s.listenerGroup.Done()
}
return true
}
func (s *Server) trackConn(conn *net.Conn, add bool) {
s.mutex.Lock()
defer s.mutex.Unlock()
if add {
s.conns[conn] = struct{}{}
s.connGroup.Add(1)
} else {
delete(s.conns, conn)
s.connGroup.Done()
}
}
type forwardListener struct {
pipe chan net.Conn
addr net.Addr
}
func newForwardListener(addr net.Addr) *forwardListener {
return &forwardListener{
pipe: make(chan net.Conn),
addr: addr,
}
}
func (l *forwardListener) Forward(conn net.Conn) {
l.pipe <- conn
}
func (l *forwardListener) Accept() (net.Conn, error) {
conn, ok := <-l.pipe
if !ok {
return nil, net.ErrClosed
}
return conn, nil
}
func (l *forwardListener) Addr() net.Addr {
return l.addr
}
func (l *forwardListener) Close() error {
close(l.pipe)
return nil
}
func readHTTPHost(r *bufio.Reader) ([]byte, string, error) {
host := ""
req, err := http.ReadRequest(r)
if err != nil {
return nil, "", err
}
// Prepend the read part
buf := &bytes.Buffer{}
if req.URL.IsAbs() {
req.WriteProxy(buf)
} else {
req.Write(buf)
}
if h, _, err := net.SplitHostPort(req.Host); err == nil {
host = h
}
return buf.Bytes(), host, nil
}
func readClientHelloRecord(r io.Reader) ([]byte, string, error) {
host := ""
record, err := dissector.ReadRecord(r)
if err != nil {
return nil, "", err
}
clientHello := &dissector.ClientHelloHandshake{}
if err := clientHello.Decode(record.Opaque); err != nil {
return nil, "", err
}
for _, ext := range clientHello.Extensions {
if ext.Type() == dissector.ExtServerName {
snExtension := ext.(*dissector.ServerNameExtension)
host = snExtension.Name
break
}
}
record.Opaque, err = clientHello.Encode()
if err != nil {
return nil, "", err
}
buf := &bytes.Buffer{}
if _, err := record.WriteTo(buf); err != nil {
return nil, "", err
}
return buf.Bytes(), host, nil
}