Repository navigation
Expand file tree
/
Copy pathhandler.go
More file actions
952 lines (881 loc) · 30.9 KB
/
Copy pathhandler.go
File metadata and controls
952 lines (881 loc) · 30.9 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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
//go:build linux || darwin || dragonfly || freebsd || netbsd || openbsd || windows
package websocket
import (
"bytes"
"crypto/rand"
"crypto/sha1"
"encoding/base64"
"encoding/binary"
"errors"
stdhttp "net/http"
"strings"
"sync"
"sync/atomic"
"unicode/utf8"
fib "github.com/lesismal/fib"
"github.com/lesismal/fib/bufferpool"
epollhttp "github.com/lesismal/fib/http"
)
const websocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
type Config struct {
// MaxMessageBytes bounds one message, reassembled, or one frame of it
// when the handler implements FrameHandler.
MaxMessageBytes int64
Subprotocols []string
// CheckOrigin decides whether a handshake request may open a WebSocket.
// When it is nil, CheckSameOrigin decides: a request with no Origin
// header, or whose Origin names the request's Host, is accepted, and a
// browser page of another site is refused with 403 Forbidden. To accept
// every origin, as before this default, set
//
// CheckOrigin: func(*http.Request) bool { return true },
//
// knowing that a page of any site can then open a WebSocket carrying
// the user's cookies. A non-nil CheckOrigin makes every handshake parse
// into an *http.Request, which the default does not need.
CheckOrigin func(*stdhttp.Request) bool
// EnableCompression accepts a client's offer of permessage-deflate (RFC
// 7692). Messages are then sent compressed, and a client may send its own
// compressed. MaxMessageBytes bounds a message once decompressed.
EnableCompression bool
HTTP epollhttp.Config
}
func DefaultConfig() Config {
return Config{MaxMessageBytes: 16 << 20, HTTP: epollhttp.DefaultConfig()}
}
type Handler interface {
OnOpen(*Connection, *stdhttp.Request)
// OnMessage payload is valid only for the duration of the callback. Copy it
// before returning if it must be retained.
OnMessage(*Connection, Opcode, []byte)
OnClose(*Connection, uint16, string, error)
}
// FrameHandler is implemented by a Handler that takes a data message one
// frame at a time instead of waiting for the whole of it. OnMessage is then
// never called for Text or Binary: every frame of such a message reaches
// OnFrame instead, carrying the message's own opcode, never Continuation, and
// fin on the last frame of the message.
//
// Nothing is held between frames, so a peer may stream a message far larger
// than Config.MaxMessageBytes, which then bounds a single frame rather than
// the message, and a handler that only forwards or writes what arrives needs
// no buffer of its own. A message that arrives compressed is the exception:
// its frames cannot be inflated one by one, so it is reassembled and reaches
// OnFrame whole, with fin set.
//
// The payload is valid only for the duration of the callback.
type FrameHandler interface {
OnFrame(c *Connection, opcode Opcode, fin bool, payload []byte)
}
// PingHandler is implemented by a Handler that handles pings itself. OnPing
// replaces the default reply, so it sends the pong itself, with
// Connection.Pong, if it wants one sent. A Handler that does not implement it
// has every ping answered with a pong carrying the same payload, as RFC 6455
// requires.
//
// The payload is valid only for the duration of the callback.
type PingHandler interface {
OnPing(*Connection, []byte)
}
// PongHandler is implemented by a Handler that wants the pongs it receives,
// to measure round trips or to tell that a peer is alive. Without it pongs
// are discarded.
//
// The payload is valid only for the duration of the callback.
type PongHandler interface {
OnPong(*Connection, []byte)
}
// HandlerFuncs implements Handler, PingHandler and PongHandler from whichever
// functions are set. A nil Ping keeps the default reply to pings, and a nil
// Pong discards pongs.
type HandlerFuncs struct {
Open func(*Connection, *stdhttp.Request)
Message func(*Connection, Opcode, []byte)
Close func(*Connection, uint16, string, error)
// Frame, when set, receives a data message frame by frame and Message is
// not called for Text or Binary. See FrameHandler.
Frame func(c *Connection, opcode Opcode, fin bool, payload []byte)
// Ping replaces the default reply to a ping: it has to call
// Connection.Pong itself for a pong to be sent.
Ping func(*Connection, []byte)
Pong func(*Connection, []byte)
}
func (h HandlerFuncs) OnOpen(c *Connection, r *stdhttp.Request) {
if h.Open != nil {
h.Open(c, r)
}
}
func (h HandlerFuncs) OnMessage(c *Connection, opcode Opcode, data []byte) {
if h.Message != nil {
h.Message(c, opcode, data)
}
}
func (h HandlerFuncs) OnClose(c *Connection, code uint16, reason string, err error) {
if h.Close != nil {
h.Close(c, code, reason, err)
}
}
func (h HandlerFuncs) OnFrame(c *Connection, opcode Opcode, fin bool, payload []byte) {
if h.Frame != nil {
h.Frame(c, opcode, fin, payload)
}
}
func (h HandlerFuncs) OnPing(c *Connection, payload []byte) {
if h.Ping != nil {
h.Ping(c, payload)
return
}
_ = c.replyPing(payload)
}
func (h HandlerFuncs) OnPong(c *Connection, payload []byte) {
if h.Pong != nil {
h.Pong(c, payload)
}
}
// frameHandler reports how handler takes the frames of a data message, and nil
// when it wants whole messages. A HandlerFuncs implements OnFrame whether or
// not its Frame is set, so it is asked for the field instead.
func frameHandler(handler Handler) FrameHandler {
switch typed := handler.(type) {
case HandlerFuncs:
if typed.Frame == nil {
return nil
}
return typed
case *HandlerFuncs:
if typed == nil || typed.Frame == nil {
return nil
}
return typed
case FrameHandler:
return typed
}
return nil
}
// Connection is a WebSocket connection. Its write methods are safe to call
// from application goroutines.
type Connection struct {
// conn is what the frames go through: the fib.Connection of a server or
// client of this package's own, or the http.Tunnel of a request that
// ServerHandler.Upgrade switched, on HTTP/1.1, HTTP/2 or HTTP/3.
conn transport
subprotocol string
closeState atomic.Pointer[connectionCloseState]
closeSent atomic.Bool
// client marks the dialing side, whose frames must be masked.
client bool
// compress says permessage-deflate is in use, and windowBits bounds how
// far back what this side sends may refer.
compress bool
windowBits uint8
}
// transport is what a Connection sends its frames through, which a
// *fib.Connection and an *http.Tunnel both are.
type transport interface {
SendParts(first, second []byte) error
SendOwned(data []byte) error
// SendShared sends a frame that other connections may be sending too,
// which is never written into; see PreparedMessage.
SendShared(data []byte) error
CloseAfterSend()
Close() error
}
var (
errDataOpcode = errors.New("websocket: a message requires Text or Binary opcode")
errCloseSent = errors.New("websocket: close already sent")
)
type connectionCloseState struct {
code uint16
reason string
}
func (c *Connection) Subprotocol() string { return c.subprotocol }
func (c *Connection) WriteMessage(opcode Opcode, payload []byte) error {
if opcode != Text && opcode != Binary {
return errDataOpcode
}
if opcode == Text && !utf8.Valid(payload) {
return ErrInvalidPayload
}
return c.writeFrame(opcode, payload)
}
func (c *Connection) WriteText(text string) error {
return c.WriteMessage(Text, []byte(text))
}
func (c *Connection) WriteBinary(payload []byte) error {
return c.WriteMessage(Binary, payload)
}
// Ping sends a ping. The peer answers with a pong carrying the same payload,
// which reaches a PongHandler. The payload is at most 125 bytes.
func (c *Connection) Ping(payload []byte) error { return c.writeFrame(Ping, payload) }
// Pong sends a pong. Pongs are sent on their own only to answer pings, which
// the default handling already does, or as an unsolicited heartbeat.
func (c *Connection) Pong(payload []byte) error { return c.writeFrame(Pong, payload) }
// replyPing is the default answer to a ping. A connection that cannot even
// send a pong is closed, and replyPing reports false.
func (c *Connection) replyPing(payload []byte) bool {
if err := c.Pong(payload); err != nil {
c.conn.Close()
return false
}
return true
}
func (c *Connection) Close(code uint16, reason string) error {
if !validCloseCode(code) || !utf8.ValidString(reason) {
return ErrInvalidPayload
}
payload := make([]byte, 2+len(reason))
if len(payload) > 125 {
return errors.New("websocket: close reason too long")
}
binary.BigEndian.PutUint16(payload, code)
copy(payload[2:], reason)
return c.sendClose(payload)
}
func (c *Connection) writeFrame(opcode Opcode, payload []byte) error {
if c.closeSent.Load() {
return errCloseSent
}
if c.compress && (opcode == Text || opcode == Binary) {
compressor, compressed := compressMessage(payload, int(c.windowBits))
err := c.sendFrame(opcode, compressed, true)
compressor.release()
return err
}
return c.sendFrame(opcode, payload, false)
}
// sendFrame frames payload for the peer. A server's frames go out as they are,
// with the header beside the payload rather than copied in front of it. A
// client has to mask every frame instead (RFC 6455 section 5.3), which
// sendMaskedFrame does. compressed sets RSV1, which marks a compressed
// message.
func (c *Connection) sendFrame(opcode Opcode, payload []byte, compressed bool) error {
if c.client {
return c.sendMaskedFrame(opcode, payload, compressed)
}
// The header stays on this stack only if nothing it is handed to can keep
// it. A *fib.Connection writes it beside the payload and copies only what
// the socket cannot take yet, which the compiler sees through a direct
// call on every platform (TestServerWriteMessageAllocs holds it to that);
// through the transport interface it cannot, so any other transport gets
// a pooled copy instead.
var header [maxFrameHeader]byte
headerLen, err := frameHeader(header[:], opcode, len(payload))
if err != nil {
return err
}
if compressed {
header[0] |= 0x40
}
if conn, ok := c.conn.(*fib.Connection); ok {
return conn.SendParts(header[:headerLen], payload)
}
return sendPartsCopied(c.conn, header[:headerLen], payload)
}
// sendPartsCopied sends first and second through t with first copied into a
// pooled buffer, so that first itself does not escape.
func sendPartsCopied(t transport, first, second []byte) error {
copied := bufferpool.Get(len(first))
defer bufferpool.Put(copied)
copy(copied, first)
return t.SendParts(copied[:len(first)], second)
}
// sendMaskedFrame is sendFrame for a client, which has to mask every frame
// with a key the server cannot predict. Masking rewrites the payload, which is
// the caller's buffer and not this connection's to scramble, so the frame is
// built whole in a buffer of its own and the header never leaves this frame.
func (c *Connection) sendMaskedFrame(opcode Opcode, payload []byte, compressed bool) error {
var header [maxFrameHeader]byte
headerLen, err := frameHeader(header[:], opcode, len(payload))
if err != nil {
return err
}
if compressed {
header[0] |= 0x40
}
frame := make([]byte, headerLen+4+len(payload))
copy(frame, header[:headerLen])
frame[1] |= 0x80
mask := frame[headerLen : headerLen+4]
// RFC 6455 section 5.3 wants the key from a strong source of entropy.
// crypto/rand.Read never fails: it crashes the program rather than
// return an error.
_, _ = rand.Read(mask)
copy(frame[headerLen+4:], payload)
applyMask(frame[headerLen+4:], mask)
return c.conn.SendOwned(frame)
}
func (c *Connection) sendClose(payload []byte) error {
if !c.closeSent.CompareAndSwap(false, true) {
return nil
}
// Every caller hands over at most 125 bytes: Close checks the reason's
// length, and the parser bounds a received close frame.
code, reason := closePayload(payload)
c.closeState.Store(&connectionCloseState{code: code, reason: reason})
if err := c.sendFrame(Close, payload, false); err != nil {
return err
}
c.conn.CloseAfterSend()
return nil
}
// connectionState is what a server keeps for each connection. Every
// connection of a server has one, so it is kept within 160 bytes on a 64-bit
// platform, a size class of its own: the parser holds the state of only some
// messages behind a pointer, and whether the handshake is done is read from
// websocket rather than kept beside it.
type connectionState struct {
handshake *handshakeParser
wsParser Parser
// websocket is the connection the handshake opened. Its conn is nil until
// then.
websocket Connection
}
// upgraded reports whether the opening handshake has completed.
func (s *connectionState) upgraded() bool { return s.websocket.conn != nil }
// openState is a connectionState whose opening handshake has completed and
// whose handler has had OnOpen, attached under a type of its own once it
// has: OnShutdown, which runs on the event loop, learns it from the
// attachment, which a worker writes atomically, rather than from websocket,
// which the worker fills in, and the state needs no room for it.
type openState connectionState
// stateOf returns c's connectionState, whether its handshake has completed
// or not, or nil.
func stateOf(c *fib.Connection) *connectionState {
switch state := c.Attachment().(type) {
case *openState:
return (*connectionState)(state)
case *connectionState:
return state
}
return nil
}
type ServerHandler struct {
config Config
handler Handler
frames FrameHandler
needsRequest bool
handshakeParsers sync.Pool
}
func NewHandler(handler Handler) *ServerHandler {
return NewHandlerWithConfig(DefaultConfig(), handler)
}
func NewHandlerWithConfig(config Config, handler Handler) *ServerHandler {
defaults := DefaultConfig()
if config.MaxMessageBytes <= 0 {
config.MaxMessageBytes = defaults.MaxMessageBytes
}
if config.HTTP.MaxHeaderBytes <= 0 {
config.HTTP.MaxHeaderBytes = defaults.HTTP.MaxHeaderBytes
}
if config.HTTP.MaxBodyBytes <= 0 {
config.HTTP.MaxBodyBytes = defaults.HTTP.MaxBodyBytes
}
if handler == nil {
handler = HandlerFuncs{}
}
needsRequest := config.CheckOrigin != nil
if !needsRequest {
switch typed := handler.(type) {
case HandlerFuncs:
needsRequest = typed.Open != nil
case *HandlerFuncs:
needsRequest = typed == nil || typed.Open != nil
default:
needsRequest = true
}
}
h := &ServerHandler{config: config, handler: handler, frames: frameHandler(handler),
needsRequest: needsRequest}
h.handshakeParsers.New = func() any {
return &handshakeParser{maxHeaderBytes: config.HTTP.MaxHeaderBytes}
}
return h
}
func (h *ServerHandler) OnOpen(c *fib.Connection) {
c.SetAttachment(&connectionState{})
}
func (h *ServerHandler) OnData(c *fib.Connection, data []byte) {
state := stateOf(c)
if state == nil {
h.OnOpen(c)
state, _ = c.Attachment().(*connectionState)
}
if state.upgraded() {
h.handleFrames(state, data)
return
}
if !h.needsRequest && state.handshake == nil {
key, result, remainder, complete, err := h.validateMinimalHandshake(data)
if err != nil {
h.reject(c, nil, rejectStatus(err))
return
}
if complete {
h.upgrade(c, state, nil, key, result, remainder)
return
}
}
var request *stdhttp.Request
var remainder []byte
var complete bool
var err error
if state.handshake == nil {
request, remainder, complete, err = parseCompleteHandshake(data, h.config.HTTP.MaxHeaderBytes)
if !complete && err == nil {
state.handshake = h.handshakeParsers.Get().(*handshakeParser)
request, complete, err = state.handshake.Feed(data)
}
} else {
request, complete, err = state.handshake.Feed(data)
}
if err != nil {
h.reject(c, request, stdhttp.StatusBadRequest)
return
}
if !complete {
return
}
result, err := h.validateHandshake(request)
if err != nil {
h.reject(c, request, rejectStatus(err))
return
}
key := []byte(request.Header.Get("Sec-Websocket-Key"))
h.upgrade(c, state, request, key, result, remainder)
}
// handshakeResult is what the server agreed to in the opening handshake.
type handshakeResult struct {
subprotocol string
// extensions is the Sec-WebSocket-Extensions response, empty when no
// extension is in use.
extensions string
deflate deflateParams
}
// negotiateExtensions accepts what the server supports of the client's offers.
func (h *ServerHandler) negotiateExtensions(result *handshakeResult, offers []string) {
if h.config.EnableCompression && len(offers) != 0 {
result.extensions, result.deflate = acceptDeflateOffer(offers)
}
}
func (h *ServerHandler) upgrade(c *fib.Connection, state *connectionState, request *stdhttp.Request, key []byte, result handshakeResult, remainder []byte) {
if err := sendHandshakeResponse(c, key, result); err != nil {
c.Close()
return
}
compress := result.extensions != ""
state.websocket = Connection{conn: c, subprotocol: result.subprotocol, compress: compress,
windowBits: uint8(result.deflate.windowBits)}
state.wsParser.maxMessageBytes = h.config.MaxMessageBytes
state.wsParser.deflate = compress
state.wsParser.contextTakeover = compress && result.deflate.peerContextTakeover
state.wsParser.perFrame = h.frames != nil
if state.handshake != nil && remainder == nil {
remainder = state.handshake.TakeBuffered()
}
h.releaseHandshakeParser(state)
if request != nil {
if ap := c.RemoteAddrPort(); ap.IsValid() {
request.RemoteAddr = ap.String()
} else if addr := c.RemoteAddr(); addr != nil {
request.RemoteAddr = addr.String()
}
h.handler.OnOpen(&state.websocket, request)
}
c.SetAttachment((*openState)(state))
if len(remainder) != 0 {
h.handleFrames(state, remainder)
}
}
func (h *ServerHandler) handleFrames(state *connectionState, data []byte) {
serveFrames(h.handler, h.frames, &state.websocket, &state.wsParser, data)
}
// serveFrames feeds bytes from the peer through parser and acts on every frame
// they complete: messages go to handler, or their frames to frames when it is
// not nil, pings are answered or handed to a PingHandler, pongs go to a
// PongHandler, and a close is echoed. Both ends of a connection run it; they
// differ only in the parser's direction and in whether ws masks what it sends.
//
// Nothing that arrives once ws has sent its Close is acted on: the
// connection closes behind that Close, and a reply to a frame after it, such
// as the pong to a ping, could not be sent, which the default ping handling
// answers by closing the connection at once, taking the queued Close with it.
// Over TLS each record is a call of its own, so a ping in the record after a
// Close arrives here after the Close has been answered.
func serveFrames(handler Handler, frames FrameHandler, ws *Connection, parser *Parser, data []byte) {
defer parser.ReleaseBorrowed()
for {
if ws.closeSent.Load() {
return
}
event, complete, err := parser.FeedOneBorrowed(data)
data = nil
if err != nil {
closeParserError(ws, err)
return
}
if !complete {
return
}
switch event.Opcode {
case Text, Binary:
if frames != nil {
frames.OnFrame(ws, event.Opcode, event.Fin, event.Payload)
} else {
handler.OnMessage(ws, event.Opcode, event.Payload)
}
case Ping:
if pinged, ok := handler.(PingHandler); ok {
pinged.OnPing(ws, event.Payload)
} else if !ws.replyPing(event.Payload) {
return
}
case Pong:
if ponged, ok := handler.(PongHandler); ok {
ponged.OnPong(ws, event.Payload)
}
case Close:
_ = ws.sendClose(event.Payload)
return
}
}
}
func closeParserError(ws *Connection, err error) {
code := uint16(CloseProtocolError)
if errors.Is(err, ErrMessageTooBig) {
code = CloseMessageTooBig
} else if errors.Is(err, ErrInvalidPayload) {
code = CloseInvalidPayload
}
var payload [2]byte
binary.BigEndian.PutUint16(payload[:], code)
_ = ws.sendClose(payload[:])
}
func (h *ServerHandler) validateHandshake(request *stdhttp.Request) (handshakeResult, error) {
var result handshakeResult
var err error
result.subprotocol, err = h.validateHandshakeRequest(request)
if err != nil {
return handshakeResult{}, err
}
h.negotiateExtensions(&result, request.Header.Values("Sec-Websocket-Extensions"))
return result, nil
}
func (h *ServerHandler) validateHandshakeRequest(request *stdhttp.Request) (string, error) {
if request.Method != stdhttp.MethodGet || request.ProtoMajor != 1 || request.ProtoMinor < 1 {
return "", ErrProtocol
}
if !headerHasToken(request.Header, "Connection", "upgrade") ||
!strings.EqualFold(strings.TrimSpace(request.Header.Get("Upgrade")), "websocket") ||
request.Header.Get("Sec-Websocket-Version") != "13" {
return "", ErrProtocol
}
key := request.Header.Get("Sec-Websocket-Key")
var decodedKey [16]byte
n, err := base64.StdEncoding.Decode(decodedKey[:], []byte(key))
if err != nil || len(key) != base64.StdEncoding.EncodedLen(len(decodedKey)) || n != len(decodedKey) {
return "", ErrProtocol
}
if !h.checkOrigin(request) {
return "", errOriginRejected
}
return h.selectSubprotocol(request)
}
// selectSubprotocol picks the first of the subprotocols request offers that
// the server supports, or none.
func (h *ServerHandler) selectSubprotocol(request *stdhttp.Request) (string, error) {
for _, value := range request.Header.Values("Sec-Websocket-Protocol") {
for len(value) != 0 {
candidate, rest := nextHeaderToken(value)
value = rest
if candidate == "" {
continue
}
if !validToken(candidate) {
return "", ErrProtocol
}
for _, supported := range h.config.Subprotocols {
if candidate == supported && validToken(supported) {
return candidate, nil
}
}
}
}
return "", nil
}
func (h *ServerHandler) validateMinimalHandshake(data []byte) ([]byte, handshakeResult, []byte, bool, error) {
headerAt := bytes.Index(data, []byte("\r\n\r\n"))
if headerAt < 0 {
if len(data) > h.config.HTTP.MaxHeaderBytes {
return nil, handshakeResult{}, nil, false, errHandshakeHeaderTooLarge
}
return nil, handshakeResult{}, nil, false, nil
}
headerEnd := headerAt + 4
if headerEnd > h.config.HTTP.MaxHeaderBytes {
return nil, handshakeResult{}, nil, false, errHandshakeHeaderTooLarge
}
lineEnd := bytes.Index(data[:headerAt], []byte("\r\n"))
if lineEnd <= len("GET HTTP/1.1") || !bytes.HasPrefix(data[:lineEnd], []byte("GET ")) ||
!bytes.HasSuffix(data[:lineEnd], []byte(" HTTP/1.1")) {
return nil, handshakeResult{}, nil, false, errMalformedHandshake
}
requestURI := data[len("GET ") : lineEnd-len(" HTTP/1.1")]
if !validMinimalRequestURI(requestURI) {
return nil, handshakeResult{}, nil, false, errMalformedHandshake
}
var key, host, origin []byte
var subprotocol string
var offers []string
hostSeen, connectionUpgrade, upgradeWebsocket, version13 := false, false, false, false
origins := 0
for offset := lineEnd + 2; offset < headerAt; {
// The line ends at the latest at headerAt, and is not empty, since
// headerAt is where the first empty line is.
relativeEnd := bytes.Index(data[offset:headerAt+2], []byte("\r\n"))
line := data[offset : offset+relativeEnd]
offset += relativeEnd + 2
colon := bytes.IndexByte(line, ':')
if colon <= 0 || line[0] == ' ' || line[0] == '\t' || !validTokenBytes(line[:colon]) {
return nil, handshakeResult{}, nil, false, errMalformedHandshake
}
name, value := line[:colon], trimOWS(line[colon+1:])
if !validHeaderValue(value) {
return nil, handshakeResult{}, nil, false, errMalformedHandshake
}
switch {
case bytes.EqualFold(name, []byte("Host")):
if hostSeen || len(value) == 0 {
return nil, handshakeResult{}, nil, false, errMalformedHandshake
}
hostSeen, host = true, value
case bytes.EqualFold(name, []byte("Connection")):
connectionUpgrade = connectionUpgrade || byteHeaderHasToken(value, []byte("upgrade"))
case bytes.EqualFold(name, []byte("Upgrade")):
upgradeWebsocket = bytes.EqualFold(value, []byte("websocket"))
case bytes.EqualFold(name, []byte("Sec-WebSocket-Version")):
version13 = bytes.Equal(value, []byte("13"))
case bytes.EqualFold(name, []byte("Sec-WebSocket-Key")):
if key == nil {
key = value
}
case bytes.EqualFold(name, []byte("Sec-WebSocket-Protocol")):
selected, valid := h.selectMinimalSubprotocol(value)
if !valid {
return nil, handshakeResult{}, nil, false, ErrProtocol
}
if subprotocol == "" {
subprotocol = selected
}
case bytes.EqualFold(name, []byte("Sec-WebSocket-Extensions")):
if h.config.EnableCompression {
offers = append(offers, string(value))
}
case len(name) == len("Origin") && bytes.EqualFold(name, []byte("Origin")):
origins++
origin = value
case bytes.EqualFold(name, []byte("Content-Length")), bytes.EqualFold(name, []byte("Transfer-Encoding")):
if len(value) != 0 {
return nil, handshakeResult{}, nil, false, errMalformedHandshake
}
}
}
var decodedKey [16]byte
n, decodeErr := base64.StdEncoding.Decode(decodedKey[:], key)
if !hostSeen || !connectionUpgrade || !upgradeWebsocket || !version13 ||
decodeErr != nil || len(key) != 24 || n != len(decodedKey) {
return nil, handshakeResult{}, nil, false, ErrProtocol
}
// CheckOrigin is nil on this path: the default of CheckSameOrigin.
if origins > 1 || origins == 1 && !sameOrigin(origin, host) {
return nil, handshakeResult{}, nil, false, errOriginRejected
}
result := handshakeResult{subprotocol: subprotocol}
h.negotiateExtensions(&result, offers)
return key, result, data[headerEnd:], true, nil
}
func (h *ServerHandler) selectMinimalSubprotocol(value []byte) (string, bool) {
for len(value) != 0 {
candidate, rest := nextByteHeaderToken(value)
value = rest
if len(candidate) == 0 {
continue
}
if !validTokenBytes(candidate) {
return "", false
}
for _, supported := range h.config.Subprotocols {
if validToken(supported) && bytes.Equal(candidate, []byte(supported)) {
return supported, true
}
}
}
return "", true
}
func byteHeaderHasToken(value, token []byte) bool {
for len(value) != 0 {
candidate, rest := nextByteHeaderToken(value)
if bytes.EqualFold(candidate, token) {
return true
}
value = rest
}
return false
}
func nextByteHeaderToken(value []byte) (token, rest []byte) {
if comma := bytes.IndexByte(value, ','); comma >= 0 {
token, rest = value[:comma], value[comma+1:]
} else {
token = value
}
return trimOWS(token), rest
}
func validMinimalRequestURI(uri []byte) bool {
if len(uri) == 0 || uri[0] != '/' {
return false
}
for i, c := range uri {
if c <= ' ' || c == 0x7f || c == '#' {
return false
}
if c == '%' && (i+2 >= len(uri) || !isHex(uri[i+1]) || !isHex(uri[i+2])) {
return false
}
}
return true
}
func isHex(c byte) bool {
return c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F'
}
// rejectStatus is the status a handshake refused for err is answered with:
// 403 Forbidden for an origin CheckOrigin refuses, 400 Bad Request otherwise.
func rejectStatus(err error) int {
if errors.Is(err, errOriginRejected) {
return stdhttp.StatusForbidden
}
return stdhttp.StatusBadRequest
}
func (h *ServerHandler) reject(c *fib.Connection, request *stdhttp.Request, status int) {
if request == nil {
request = &stdhttp.Request{ProtoMajor: 1, ProtoMinor: 1, Header: make(stdhttp.Header)}
}
context := &epollhttp.Context{Conn: c, Request: request}
_ = context.WriteResponse(epollhttp.Response{
StatusCode: status,
Header: stdhttp.Header{"Content-Type": {"text/plain; charset=utf-8"}},
Body: []byte(stdhttp.StatusText(status) + "\n"),
Close: true,
})
}
func (h *ServerHandler) OnPriorityData(*fib.Connection, []byte) {}
// OnShutdown ends the connection as its engine shuts down; see
// fib.Engine.Shutdown. An open WebSocket is sent a close frame with 1001
// (going away) and closes once it has gone, and one still in its opening
// handshake closes at once: it would be told to go away as soon as it
// opened. It runs on the event loop, and the close frame is sent from the
// engine's handler pool, since sending may wait on a layer such as TLS.
func (h *ServerHandler) OnShutdown(c *fib.Connection) {
switch state := c.Attachment().(type) {
case *openState:
if ws := &state.websocket; !ws.closeSent.Load() {
elsewhere(c, func() { _ = ws.Close(CloseGoingAway, "") })
}
case *connectionState:
_ = c.Close()
}
}
var _ fib.ShutdownHandler = (*ServerHandler)(nil)
// elsewhere runs fn on the engine's handler pool, or on a goroutine of its
// own once the pool has stopped taking work.
func elsewhere(c *fib.Connection, fn func()) {
if pool := c.Engine().HandlerPool(); pool == nil || !pool.Go(fn) {
go fn()
}
}
func (h *ServerHandler) OnClose(c *fib.Connection, err error) {
state := stateOf(c)
c.SetAttachment(nil)
if state == nil {
return
}
h.releaseHandshakeParser(state)
if state.upgraded() {
code, reason := state.websocket.closeStatus()
h.handler.OnClose(&state.websocket, code, reason, err)
}
}
// closeStatus is the code and reason OnClose reports: those of the close frame
// this end sent, which echoes the peer's when the peer closed first, or 1006
// when the connection ended without a close handshake.
func (c *Connection) closeStatus() (uint16, string) {
if closeState := c.closeState.Load(); closeState != nil {
return closeState.code, closeState.reason
}
return 1006, ""
}
func (h *ServerHandler) releaseHandshakeParser(state *connectionState) {
if state.handshake == nil {
return
}
state.handshake.Reset()
h.handshakeParsers.Put(state.handshake)
state.handshake = nil
}
var handshakeResponsePrefix = []byte("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ")
func sendHandshakeResponse(c *fib.Connection, key []byte, result handshakeResult) error {
var accept [28]byte
websocketAccept(accept[:], key)
subprotocol := result.subprotocol
if subprotocol == "" && result.extensions == "" {
var tail [32]byte
copy(tail[:], accept[:])
copy(tail[len(accept):], "\r\n\r\n")
return c.SendParts(handshakeResponsePrefix, tail[:])
}
response := make([]byte, 0, len(handshakeResponsePrefix)+len(accept)+60+len(subprotocol)+len(result.extensions))
response = append(response, handshakeResponsePrefix...)
response = append(response, accept[:]...)
if subprotocol != "" {
response = append(response, "\r\nSec-WebSocket-Protocol: "...)
response = append(response, subprotocol...)
}
if result.extensions != "" {
response = append(response, "\r\nSec-WebSocket-Extensions: "...)
response = append(response, result.extensions...)
}
response = append(response, "\r\n\r\n"...)
return c.SendOwned(response)
}
func websocketAccept(dst, key []byte) {
var challenge [24 + len(websocketGUID)]byte
n := copy(challenge[:], key)
copy(challenge[n:], websocketGUID)
sum := sha1.Sum(challenge[:n+len(websocketGUID)])
base64.StdEncoding.Encode(dst, sum[:])
}
func headerHasToken(header stdhttp.Header, name, token string) bool {
for _, value := range header.Values(name) {
for len(value) != 0 {
candidate, rest := nextHeaderToken(value)
value = rest
if strings.EqualFold(candidate, token) {
return true
}
}
}
return false
}
func nextHeaderToken(value string) (token, rest string) {
if comma := strings.IndexByte(value, ','); comma >= 0 {
token, rest = value[:comma], value[comma+1:]
} else {
token = value
}
return strings.TrimSpace(token), rest
}
func closePayload(payload []byte) (uint16, string) {
if len(payload) < 2 {
return CloseNormal, ""
}
return binary.BigEndian.Uint16(payload[:2]), string(payload[2:])
}
var _ fib.Handler = (*ServerHandler)(nil)