This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
http.go
565 lines (498 loc) · 12.1 KB
/
http.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
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
package main
import (
"bytes"
"crypto/md5"
"crypto/rand"
"crypto/tls"
"encoding/base64"
"encoding/hex"
"errors"
"io"
"io/ioutil"
"log"
mathrand "math/rand"
"net"
"net/http"
"net/http/httputil"
"strconv"
"strings"
"sync"
"time"
"code.google.com/p/go.crypto/nacl/secretbox"
"github.com/flynn/go-discoverd"
"github.com/flynn/strowger/types"
"github.com/inconshreveable/go-vhost"
)
type HTTPListener struct {
Watcher
DataStoreReader
Addr string
TLSAddr string
TLSConfig *tls.Config
mtx sync.RWMutex
domains map[string]*httpRoute
routes map[string]*httpRoute
services map[string]*httpService
discoverd DiscoverdClient
ds DataStore
wm *WatchManager
listener net.Listener
tlsListener net.Listener
closed bool
cookieKey *[32]byte
}
type DiscoverdClient interface {
NewServiceSet(string) (discoverd.ServiceSet, error)
}
func NewHTTPListener(addr, tlsAddr string, cookieKey *[32]byte, ds DataStore, discoverdc DiscoverdClient) *HTTPListener {
l := &HTTPListener{
Addr: addr,
TLSAddr: tlsAddr,
ds: ds,
discoverd: discoverdc,
routes: make(map[string]*httpRoute),
domains: make(map[string]*httpRoute),
services: make(map[string]*httpService),
wm: NewWatchManager(),
cookieKey: cookieKey,
}
if cookieKey == nil {
var k [32]byte
l.cookieKey = &k
}
l.Watcher = l.wm
l.DataStoreReader = l.ds
return l
}
func (s *HTTPListener) Close() error {
s.mtx.Lock()
defer s.mtx.Unlock()
for _, service := range s.services {
service.ss.Close()
}
s.listener.Close()
s.tlsListener.Close()
s.ds.StopSync()
s.closed = true
return nil
}
func (s *HTTPListener) Start() error {
started := make(chan error)
go s.ds.Sync(&httpSyncHandler{l: s}, started)
if err := <-started; err != nil {
return err
}
go s.serve(started)
if err := <-started; err != nil {
s.ds.StopSync()
return err
}
s.Addr = s.listener.Addr().String()
go s.serveTLS(started)
if err := <-started; err != nil {
s.ds.StopSync()
s.listener.Close()
return err
}
s.TLSAddr = s.tlsListener.Addr().String()
return nil
}
var ErrClosed = errors.New("strowger: listener has been closed")
func (s *HTTPListener) AddRoute(r *strowger.Route) error {
s.mtx.RLock()
defer s.mtx.RUnlock()
if s.closed {
return ErrClosed
}
r.ID = md5sum(r.HTTPRoute().Domain)
return s.ds.Add(r)
}
func (s *HTTPListener) SetRoute(r *strowger.Route) error {
s.mtx.RLock()
defer s.mtx.RUnlock()
if s.closed {
return ErrClosed
}
r.ID = md5sum(r.HTTPRoute().Domain)
return s.ds.Set(r)
}
func md5sum(data string) string {
digest := md5.Sum([]byte(data))
return hex.EncodeToString(digest[:])
}
func (s *HTTPListener) RemoveRoute(id string) error {
s.mtx.RLock()
defer s.mtx.RUnlock()
if s.closed {
return ErrClosed
}
return s.ds.Remove(id)
}
type httpSyncHandler struct {
l *HTTPListener
}
func (h *httpSyncHandler) Set(data *strowger.Route) error {
route := data.HTTPRoute()
r := &httpRoute{
Domain: route.Domain,
Service: route.Service,
TLSCert: route.TLSCert,
TLSKey: route.TLSKey,
Sticky: route.Sticky,
}
if r.TLSCert != "" && r.TLSKey != "" {
kp, err := tls.X509KeyPair([]byte(r.TLSCert), []byte(r.TLSKey))
if err != nil {
return err
}
r.keypair = &kp
r.TLSCert = ""
r.TLSKey = ""
}
h.l.mtx.Lock()
defer h.l.mtx.Unlock()
if h.l.closed {
return nil
}
service := h.l.services[r.Service]
if service != nil && service.name != r.Service {
service.refs--
if service.refs <= 0 {
service.ss.Close()
delete(h.l.services, service.name)
}
service = nil
}
if service == nil {
ss, err := h.l.discoverd.NewServiceSet(r.Service)
if err != nil {
return err
}
service = &httpService{name: r.Service, ss: ss, cookieKey: h.l.cookieKey}
h.l.services[r.Service] = service
}
service.refs++
r.service = service
h.l.routes[data.ID] = r
h.l.domains[r.Domain] = r
go h.l.wm.Send(&strowger.Event{Event: "set", ID: r.Domain})
return nil
}
func (h *httpSyncHandler) Remove(id string) error {
h.l.mtx.Lock()
defer h.l.mtx.Unlock()
if h.l.closed {
return nil
}
r, ok := h.l.routes[id]
if !ok {
return ErrNotFound
}
r.service.refs--
if r.service.refs <= 0 {
r.service.ss.Close()
delete(h.l.services, r.service.name)
}
delete(h.l.routes, id)
delete(h.l.domains, r.Domain)
go h.l.wm.Send(&strowger.Event{Event: "remove", ID: id})
return nil
}
func (s *HTTPListener) serve(started chan<- error) {
var err error
s.listener, err = net.Listen("tcp", s.Addr)
started <- err
if err != nil {
return
}
for {
conn, err := s.listener.Accept()
if err != nil {
// TODO: log error
break
}
go s.handle(conn, false)
}
}
func (s *HTTPListener) serveTLS(started chan<- error) {
var err error
s.tlsListener, err = net.Listen("tcp", s.TLSAddr)
started <- err
if err != nil {
return
}
for {
conn, err := s.tlsListener.Accept()
if err != nil {
// TODO: log error
break
}
go s.handle(conn, true)
}
}
func (s *HTTPListener) findRouteForHost(host string) *httpRoute {
s.mtx.RLock()
defer s.mtx.RUnlock()
// TODO: handle wildcard domains
backend := s.domains[host]
return backend
}
func fail(sc *httputil.ServerConn, req *http.Request, code int, msg string) {
resp := &http.Response{
StatusCode: code,
ProtoMajor: 1,
ProtoMinor: 0,
Request: req,
Body: ioutil.NopCloser(bytes.NewBufferString(msg)),
ContentLength: int64(len(msg)),
}
sc.Write(req, resp)
}
func (s *HTTPListener) handle(conn net.Conn, isTLS bool) {
defer conn.Close()
var r *httpRoute
// For TLS, use the SNI hello to determine the domain.
// At this stage, if we don't find a match, we simply
// close the connection down.
if isTLS {
// Parse out host via SNI first
vhostConn, err := vhost.TLS(conn)
if err != nil {
log.Println("Failed to decode TLS connection", err)
return
}
host := vhostConn.Host()
// Find a backend for the key
r = s.findRouteForHost(host)
if r == nil {
return
}
if r.keypair == nil {
log.Println("Cannot serve TLS, no certificate defined for this domain")
return
}
// Init a TLS decryptor
tlscfg := &tls.Config{Certificates: []tls.Certificate{*r.keypair}}
conn = tls.Server(vhostConn, tlscfg)
}
// Decode the first request from the connection
sc := httputil.NewServerConn(conn, nil)
req, err := sc.Read()
if err != nil {
if err != httputil.ErrPersistEOF {
// TODO: log error
}
return
}
// If we do not have a backend yet (unencrypted connection),
// look at the host header to find one or 404 out.
if r == nil {
r = s.findRouteForHost(req.Host)
if r == nil {
fail(sc, req, 404, "Not Found")
return
}
}
r.service.handle(req, sc, isTLS, r.Sticky)
}
// A domain served by a listener, associated TLS certs,
// and link to backend service set.
type httpRoute struct {
Domain string
Service string
TLSCert string
TLSKey string
Sticky bool
keypair *tls.Certificate
service *httpService
}
// A service definition: name, and set of backends.
type httpService struct {
name string
ss discoverd.ServiceSet
refs int
cookieKey *[32]byte
}
func (s *httpService) getBackend() *httputil.ClientConn {
backend, _ := s.connectBackend()
return backend
}
func (s *httpService) connectBackend() (*httputil.ClientConn, string) {
for _, addr := range shuffle(s.ss.Addrs()) {
// TODO: set connection timeout
backend, err := net.Dial("tcp", addr)
if err != nil {
// TODO: log error
// TODO: limit number of backends tried
// TODO: temporarily quarantine failing backends
log.Println("backend error", err)
continue
}
return httputil.NewClientConn(backend, nil), addr
}
// TODO: log no backends found error
return nil, ""
}
const stickyCookie = "_backend"
func (s *httpService) getNewBackendSticky() (*httputil.ClientConn, *http.Cookie) {
backend, addr := s.connectBackend()
if backend == nil {
return nil, nil
}
var nonce [24]byte
_, err := io.ReadFull(rand.Reader, nonce[:])
if err != nil {
panic(err)
}
out := make([]byte, len(nonce), len(nonce)+len(addr)+secretbox.Overhead)
copy(out, nonce[:])
out = secretbox.Seal(out, []byte(addr), &nonce, s.cookieKey)
return backend, &http.Cookie{Name: stickyCookie, Value: base64.StdEncoding.EncodeToString(out), Path: "/"}
}
func (s *httpService) getBackendSticky(req *http.Request) (*httputil.ClientConn, *http.Cookie) {
cookie, err := req.Cookie(stickyCookie)
if err != nil {
return s.getNewBackendSticky()
}
data, err := base64.StdEncoding.DecodeString(cookie.Value)
if err != nil {
return s.getNewBackendSticky()
}
var nonce [24]byte
if len(data) < len(nonce) {
return s.getNewBackendSticky()
}
copy(nonce[:], data)
res, ok := secretbox.Open(nil, data[len(nonce):], &nonce, s.cookieKey)
if !ok {
return s.getNewBackendSticky()
}
addr := string(res)
ok = false
for _, a := range s.ss.Addrs() {
if a == addr {
ok = true
break
}
}
if !ok {
return s.getNewBackendSticky()
}
backend, err := net.Dial("tcp", string(addr))
if err != nil {
return s.getNewBackendSticky()
}
return httputil.NewClientConn(backend, nil), nil
}
func (s *httpService) handle(req *http.Request, sc *httputil.ServerConn, tls, sticky bool) {
for {
req.Header.Set("X-Request-Start", strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10))
var backend *httputil.ClientConn
var stickyCookie *http.Cookie
if sticky {
backend, stickyCookie = s.getBackendSticky(req)
} else {
backend = s.getBackend()
}
if backend == nil {
log.Println("no backend found")
fail(sc, req, 503, "Service Unavailable")
return
}
if req.Method != "GET" && req.Method != "POST" && req.Method != "HEAD" &&
req.Method != "OPTIONS" && req.Method != "PUT" && req.Method != "DELETE" && req.Method != "TRACE" {
fail(sc, req, 405, "Method not allowed")
return
}
req.Proto = "HTTP/1.1"
req.ProtoMajor = 1
req.ProtoMinor = 1
delete(req.Header, "Te")
delete(req.Header, "Transfer-Encoding")
if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
// If we aren't the first proxy retain prior
// X-Forwarded-For information as a comma+space
// separated list and fold multiple headers into one.
if prior, ok := req.Header["X-Forwarded-For"]; ok {
clientIP = strings.Join(prior, ", ") + ", " + clientIP
}
req.Header.Set("X-Forwarded-For", clientIP)
}
if tls {
req.Header.Set("X-Forwarded-Proto", "https")
} else {
req.Header.Set("X-Forwarded-Proto", "http")
}
// TODO: Set X-Forwarded-Port
if err := backend.Write(req); err != nil {
log.Println("server write err:", err)
return
}
res, err := backend.Read(req)
if res != nil {
if stickyCookie != nil {
res.Header.Add("Set-Cookie", stickyCookie.String())
}
if res.StatusCode == http.StatusSwitchingProtocols {
res.Body = nil
}
if err := sc.Write(req, res); err != nil {
if err != io.EOF && err != httputil.ErrPersistEOF {
log.Println("client write err:", err)
// TODO: log error
}
return
}
}
if err != nil {
if err != io.EOF && err != httputil.ErrPersistEOF {
log.Println("server read err:", err)
// TODO: log error
fail(sc, req, 502, "Bad Gateway")
}
return
}
// TODO: Proxy HTTP CONNECT? (example: Go RPC over HTTP)
if res.StatusCode == http.StatusSwitchingProtocols {
serverW, serverR := backend.Hijack()
clientW, clientR := sc.Hijack()
defer serverW.Close()
done := make(chan struct{})
go func() {
serverR.WriteTo(clientW)
if cw, ok := clientW.(writeCloser); ok {
cw.CloseWrite()
}
close(done)
}()
clientR.WriteTo(serverW)
serverW.(writeCloser).CloseWrite()
<-done
return
}
// close the backend connection, so we don't accidently send to
// a closed socket on the backend
backend.Close()
// TODO: http pipelining
req, err = sc.Read()
if err != nil {
if err != io.EOF && err != httputil.ErrPersistEOF {
log.Println("client read err:", err)
}
return
}
}
}
type writeCloser interface {
CloseWrite() error
}
func shuffle(s []string) []string {
for i := len(s) - 1; i > 0; i-- {
j := mathrand.Intn(i + 1)
s[i], s[j] = s[j], s[i]
}
return s
}
func init() {
mathrand.Seed(time.Now().UnixNano())
}