Debian Codegraph @

ws.go

raw
1 // Copyright 2021-2023 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package nats
15
16 import (
17 "bufio"
18 "bytes"
19 "crypto/rand"
20 "crypto/sha1"
21 "encoding/base64"
22 "encoding/binary"
23 "errors"
24 "fmt"
25 "io"
26 mrand "math/rand"
27 "net/http"
28 "net/url"
29 "strings"
30 "time"
31 "unicode/utf8"
32
33 "github.com/klauspost/compress/flate"
34 )
35
36 type wsOpCode int
37
38 const (
39 // From https://tools.ietf.org/html/rfc6455#section-5.2
40 wsTextMessage = wsOpCode(1)
41 wsBinaryMessage = wsOpCode(2)
42 wsCloseMessage = wsOpCode(8)
43 wsPingMessage = wsOpCode(9)
44 wsPongMessage = wsOpCode(10)
45
46 wsFinalBit = 1 << 7
47 wsRsv1Bit = 1 << 6 // Used for compression, from https://tools.ietf.org/html/rfc7692#section-6
48 wsRsv2Bit = 1 << 5
49 wsRsv3Bit = 1 << 4
50
51 wsMaskBit = 1 << 7
52
53 wsContinuationFrame = 0
54 wsMaxFrameHeaderSize = 14
55 wsMaxControlPayloadSize = 125
56 wsCloseSatusSize = 2
57
58 // wsMaxMsgPayloadMultiple is the multiplier applied to MaxPayload to
59 // determine the maximum WebSocket frame size.
60 wsMaxMsgPayloadMultiple = 8
61 // wsMaxMsgPayloadLimit is the absolute cap on WebSocket frame size (64MB).
62 wsMaxMsgPayloadLimit = 64 * 1024 * 1024
63
64 // From https://tools.ietf.org/html/rfc6455#section-11.7
65 wsCloseStatusNormalClosure = 1000
66 wsCloseStatusNoStatusReceived = 1005
67 wsCloseStatusAbnormalClosure = 1006
68 wsCloseStatusInvalidPayloadData = 1007
69
70 wsScheme = "ws"
71 wsSchemeTLS = "wss"
72
73 wsPMCExtension = "permessage-deflate" // per-message compression
74 wsPMCSrvNoCtx = "server_no_context_takeover"
75 wsPMCCliNoCtx = "client_no_context_takeover"
76 wsPMCReqHeaderValue = wsPMCExtension + "; " + wsPMCSrvNoCtx + "; " + wsPMCCliNoCtx
77 )
78
79 // From https://tools.ietf.org/html/rfc6455#section-1.3
80 var wsGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
81
82 var compressFinalBlock = []byte{0x00, 0x00, 0xff, 0xff, 0x01, 0x00, 0x00, 0xff, 0xff}
83
84 type websocketReader struct {
85 r io.Reader
86 pending [][]byte
87 compress bool
88 ib []byte
89 ff bool
90 fc bool
91 nl bool
92 dc *wsDecompressor
93 nc *Conn
94 closeErr error
95 }
96
97 type wsDecompressor struct {
98 flate io.ReadCloser
99 bufs [][]byte
100 off int
101 }
102
103 type websocketWriter struct {
104 w io.Writer
105 compress bool
106 compressor *flate.Writer
107 ctrlFrames [][]byte // pending frames that should be sent at the next Write()
108 cm []byte // close message that needs to be sent when everything else has been sent
109 cmDone bool // a close message has been added or sent (never going back to false)
110 noMoreSend bool // if true, even if there is a Write() call, we should not send anything
111 }
112
113 func (d *wsDecompressor) Read(dst []byte) (int, error) {
114 if len(dst) == 0 {
115 return 0, nil
116 }
117 if len(d.bufs) == 0 {
118 return 0, io.EOF
119 }
120 copied := 0
121 rem := len(dst)
122 for buf := d.bufs[0]; buf != nil && rem > 0; {
123 n := min(len(buf[d.off:]), rem)
124 copy(dst[copied:], buf[d.off:d.off+n])
125 copied += n
126 rem -= n
127 d.off += n
128 buf = d.nextBuf()
129 }
130 return copied, nil
131 }
132
133 func (d *wsDecompressor) nextBuf() []byte {
134 // We still have remaining data in the first buffer
135 if d.off != len(d.bufs[0]) {
136 return d.bufs[0]
137 }
138 // We read the full first buffer. Reset offset.
139 d.off = 0
140 // We were at the last buffer, so we are done.
141 if len(d.bufs) == 1 {
142 d.bufs = nil
143 return nil
144 }
145 // Here we move to the next buffer.
146 d.bufs = d.bufs[1:]
147 return d.bufs[0]
148 }
149
150 func (d *wsDecompressor) ReadByte() (byte, error) {
151 if len(d.bufs) == 0 {
152 return 0, io.EOF
153 }
154 b := d.bufs[0][d.off]
155 d.off++
156 d.nextBuf()
157 return b, nil
158 }
159
160 func (d *wsDecompressor) addBuf(b []byte) {
161 d.bufs = append(d.bufs, b)
162 }
163
164 func (d *wsDecompressor) decompress() ([]byte, error) {
165 d.off = 0
166 // As per https://tools.ietf.org/html/rfc7692#section-7.2.2
167 // add 0x00, 0x00, 0xff, 0xff and then a final block so that flate reader
168 // does not report unexpected EOF.
169 d.bufs = append(d.bufs, compressFinalBlock)
170 // Create or reset the decompressor with his object (wsDecompressor)
171 // that provides Read() and ReadByte() APIs that will consume from
172 // the compressed buffers (d.bufs).
173 if d.flate == nil {
174 d.flate = flate.NewReader(d)
175 } else {
176 d.flate.(flate.Resetter).Reset(d, nil)
177 }
178 b, err := io.ReadAll(d.flate)
179 // Now reset the compressed buffers list
180 d.bufs = nil
181 return b, err
182 }
183
184 func wsNewReader(r io.Reader) *websocketReader {
185 return &websocketReader{r: r, ff: true}
186 }
187
188 // maxFrameSize returns the maximum allowed WebSocket frame size based on the
189 // negotiated MaxPayload. This mirrors the server-side wsMaxMessageSize logic.
190 func (r *websocketReader) maxFrameSize() uint64 {
191 if r.nc != nil {
192 mp := r.nc.info.MaxPayload
193 if mp > 0 && uint64(mp) <= wsMaxMsgPayloadLimit/wsMaxMsgPayloadMultiple {
194 return uint64(mp) * wsMaxMsgPayloadMultiple
195 }
196 }
197 return wsMaxMsgPayloadLimit
198 }
199
200 // From now on, reads will be from the readLoop and we will need to
201 // acquire the connection lock should we have to send/write a control
202 // message from handleControlFrame.
203 //
204 // Note: this runs under the connection lock.
205 func (r *websocketReader) doneWithConnect() {
206 r.nl = true
207 }
208
209 func (r *websocketReader) Read(p []byte) (int, error) {
210 var err error
211 var buf []byte
212
213 if l := len(r.ib); l > 0 {
214 buf = r.ib
215 r.ib = nil
216 } else {
217 if len(r.pending) > 0 {
218 return r.drainPending(p), nil
219 }
220
221 // If we have a deferred close error (from a previous Read that
222 // had both data frames and a close frame), return it now that
223 // pending data has been drained.
224 if r.closeErr != nil {
225 err := r.closeErr
226 r.closeErr = nil
227 return 0, err
228 }
229
230 // Get some data from the underlying reader.
231 n, err := r.r.Read(p)
232 if err != nil {
233 return 0, err
234 }
235 buf = p[:n]
236 }
237
238 // Now parse this and decode frames. We will possibly read more to
239 // ensure that we get a full frame.
240 var (
241 tmpBuf []byte
242 pos int
243 max = len(buf)
244 rem = 0
245 )
246 for pos < max {
247 b0 := buf[pos]
248 frameType := wsOpCode(b0 & 0xF)
249 final := b0&wsFinalBit != 0
250 compressed := b0&wsRsv1Bit != 0
251 pos++
252
253 tmpBuf, pos, err = wsGet(r.r, buf, pos, 1)
254 if err != nil {
255 return 0, err
256 }
257 b1 := tmpBuf[0]
258
259 // Store size in case it is < 125
260 rem = int(b1 & 0x7F)
261
262 switch frameType {
263 case wsPingMessage, wsPongMessage, wsCloseMessage:
264 if rem > wsMaxControlPayloadSize {
265 return 0, fmt.Errorf(
266 "control frame length bigger than maximum allowed of %v bytes",
267 wsMaxControlPayloadSize)
268 }
269 if compressed {
270 return 0, errors.New("control frame should not be compressed")
271 }
272 if !final {
273 return 0, errors.New("control frame does not have final bit set")
274 }
275 case wsTextMessage, wsBinaryMessage:
276 if !r.ff {
277 return 0, errors.New("new message started before final frame for previous message was received")
278 }
279 r.ff = final
280 r.fc = compressed
281 case wsContinuationFrame:
282 // Compressed bit must be only set in the first frame
283 if r.ff || compressed {
284 return 0, errors.New("invalid continuation frame")
285 }
286 r.ff = final
287 default:
288 return 0, fmt.Errorf("unknown opcode %v", frameType)
289 }
290
291 // If the encoded size is <= 125, then `rem` is simply the remainder size of the
292 // frame. If it is 126, then the actual size is encoded as a uint16. For larger
293 // frames, `rem` will initially be 127 and the actual size is encoded as a uint64.
294 switch rem {
295 case 126:
296 tmpBuf, pos, err = wsGet(r.r, buf, pos, 2)
297 if err != nil {
298 return 0, err
299 }
300 rem = int(binary.BigEndian.Uint16(tmpBuf))
301 case 127:
302 tmpBuf, pos, err = wsGet(r.r, buf, pos, 8)
303 if err != nil {
304 return 0, err
305 }
306 rem64 := binary.BigEndian.Uint64(tmpBuf)
307 if rem64&(1<<63) != 0 {
308 return 0, errors.New("invalid websocket frame: MSB set in 64-bit payload length")
309 }
310 if rem64 > r.maxFrameSize() {
311 return 0, fmt.Errorf("websocket frame too large: %d", rem64)
312 }
313 rem = int(rem64)
314 }
315
316 // Handle control messages in place...
317 if wsIsControlFrame(frameType) {
318 pos, err = r.handleControlFrame(frameType, buf, pos, rem)
319 if err != nil {
320 // If we already have pending data (e.g. a -ERR message
321 // that arrived before this close frame), defer the error
322 // so the pending data can be returned to the caller first.
323 if len(r.pending) > 0 {
324 r.closeErr = err
325 break
326 }
327 return 0, err
328 }
329 rem = 0
330 continue
331 }
332
333 var b []byte
334 // This ensures that we get the full payload for this frame.
335 b, pos, err = wsGet(r.r, buf, pos, rem)
336 if err != nil {
337 return 0, err
338 }
339 // We read the full frame.
340 rem = 0
341 addToPending := true
342 if r.fc {
343 // Don't add to pending if we are not dealing with the final frame.
344 addToPending = r.ff
345 // Add the compressed payload buffer to the list.
346 r.addCBuf(b)
347 // Decompress only when this is the final frame.
348 if r.ff {
349 b, err = r.dc.decompress()
350 if err != nil {
351 return 0, err
352 }
353 r.fc = false
354 }
355 } else if r.compress {
356 b = bytes.Clone(b)
357 }
358 // Add to the pending list if dealing with uncompressed frames or
359 // after we have received the full compressed message and decompressed it.
360 if addToPending {
361 r.pending = append(r.pending, b)
362 }
363 }
364 // In case of compression, there may be nothing to drain
365 if len(r.pending) > 0 {
366 return r.drainPending(p), nil
367 }
368 return 0, nil
369 }
370
371 func (r *websocketReader) addCBuf(b []byte) {
372 if r.dc == nil {
373 r.dc = &wsDecompressor{}
374 }
375 // Add a copy of the incoming buffer to the list of compressed buffers.
376 r.dc.addBuf(append([]byte(nil), b...))
377 }
378
379 func (r *websocketReader) drainPending(p []byte) int {
380 var n int
381 var max = len(p)
382
383 for i, buf := range r.pending {
384 if n+len(buf) <= max {
385 copy(p[n:], buf)
386 n += len(buf)
387 } else {
388 // Is there room left?
389 if n < max {
390 // Write the partial and update this slice.
391 rem := max - n
392 copy(p[n:], buf[:rem])
393 n += rem
394 r.pending[i] = buf[rem:]
395 }
396 // These are the remaining slices that will need to be used at
397 // the next Read() call.
398 r.pending = r.pending[i:]
399 return n
400 }
401 }
402 r.pending = r.pending[:0]
403 return n
404 }
405
406 func wsGet(r io.Reader, buf []byte, pos, needed int) ([]byte, int, error) {
407 avail := len(buf) - pos
408 if avail >= needed {
409 return buf[pos : pos+needed], pos + needed, nil
410 }
411 b := make([]byte, needed)
412 start := copy(b, buf[pos:])
413 for start != needed {
414 n, err := r.Read(b[start:cap(b)])
415 start += n
416 if err != nil {
417 return b, start, err
418 }
419 }
420 return b, pos + avail, nil
421 }
422
423 func (r *websocketReader) handleControlFrame(frameType wsOpCode, buf []byte, pos, rem int) (int, error) {
424 var payload []byte
425 var err error
426
427 if rem > 0 {
428 payload, pos, err = wsGet(r.r, buf, pos, rem)
429 if err != nil {
430 return pos, err
431 }
432 }
433 switch frameType {
434 case wsCloseMessage:
435 status := wsCloseStatusNoStatusReceived
436 var body string
437 lp := len(payload)
438 // If there is a payload, the status is represented as a 2-byte
439 // unsigned integer (in network byte order). Then, there may be an
440 // optional body.
441 hasStatus, hasBody := lp >= wsCloseSatusSize, lp > wsCloseSatusSize
442 if hasStatus {
443 // Decode the status
444 status = int(binary.BigEndian.Uint16(payload[:wsCloseSatusSize]))
445 // Now if there is a body, capture it and make sure this is a valid UTF-8.
446 if hasBody {
447 body = string(payload[wsCloseSatusSize:])
448 if !utf8.ValidString(body) {
449 // https://tools.ietf.org/html/rfc6455#section-5.5.1
450 // If body is present, it must be a valid utf8
451 status = wsCloseStatusInvalidPayloadData
452 body = "invalid utf8 body in close frame"
453 }
454 }
455 }
456 r.nc.wsEnqueueCloseMsg(r.nl, status, body)
457 // Return io.EOF so that readLoop will close the connection as client closed
458 // after processing pending buffers.
459 return pos, io.EOF
460 case wsPingMessage:
461 r.nc.wsEnqueueControlMsg(r.nl, wsPongMessage, payload)
462 case wsPongMessage:
463 // Nothing to do..
464 }
465 return pos, nil
466 }
467
468 func (w *websocketWriter) Write(p []byte) (int, error) {
469 if w.noMoreSend {
470 return 0, nil
471 }
472 var total int
473 var n int
474 var err error
475 // If there are control frames, they can be sent now. Actually spec says
476 // that they should be sent ASAP, so we will send before any application data.
477 if len(w.ctrlFrames) > 0 {
478 n, err = w.writeCtrlFrames()
479 if err != nil {
480 return n, err
481 }
482 total += n
483 }
484 // Do the following only if there is something to send.
485 // We will end with checking for need to send close message.
486 if len(p) > 0 {
487 if w.compress {
488 buf := &bytes.Buffer{}
489 if w.compressor == nil {
490 w.compressor, _ = flate.NewWriter(buf, flate.BestSpeed)
491 } else {
492 w.compressor.Reset(buf)
493 }
494 if n, err = w.compressor.Write(p); err != nil {
495 return n, err
496 }
497 if err = w.compressor.Flush(); err != nil {
498 return n, err
499 }
500 b := buf.Bytes()
501 p = b[:len(b)-4]
502 }
503 fh, key := wsCreateFrameHeader(w.compress, wsBinaryMessage, len(p))
504 wsMaskBuf(key, p)
505 n, err = w.w.Write(fh)
506 total += n
507 if err == nil {
508 n, err = w.w.Write(p)
509 total += n
510 }
511 }
512 if err == nil && w.cm != nil {
513 n, err = w.writeCloseMsg()
514 total += n
515 }
516 return total, err
517 }
518
519 func (w *websocketWriter) writeCtrlFrames() (int, error) {
520 var (
521 n int
522 total int
523 i int
524 err error
525 )
526 for ; i < len(w.ctrlFrames); i++ {
527 buf := w.ctrlFrames[i]
528 n, err = w.w.Write(buf)
529 total += n
530 if err != nil {
531 break
532 }
533 }
534 if i != len(w.ctrlFrames) {
535 w.ctrlFrames = w.ctrlFrames[i+1:]
536 } else {
537 w.ctrlFrames = w.ctrlFrames[:0]
538 }
539 return total, err
540 }
541
542 func (w *websocketWriter) writeCloseMsg() (int, error) {
543 n, err := w.w.Write(w.cm)
544 w.cm, w.noMoreSend = nil, true
545 return n, err
546 }
547
548 func wsMaskBuf(key, buf []byte) {
549 for i := 0; i < len(buf); i++ {
550 buf[i] ^= key[i&3]
551 }
552 }
553
554 // Create the frame header.
555 // Encodes the frame type and optional compression flag, and the size of the payload.
556 func wsCreateFrameHeader(compressed bool, frameType wsOpCode, l int) ([]byte, []byte) {
557 fh := make([]byte, wsMaxFrameHeaderSize)
558 n, key := wsFillFrameHeader(fh, compressed, frameType, l)
559 return fh[:n], key
560 }
561
562 func wsFillFrameHeader(fh []byte, compressed bool, frameType wsOpCode, l int) (int, []byte) {
563 var n int
564 b := byte(frameType)
565 b |= wsFinalBit
566 if compressed {
567 b |= wsRsv1Bit
568 }
569 b1 := byte(wsMaskBit)
570 switch {
571 case l <= 125:
572 n = 2
573 fh[0] = b
574 fh[1] = b1 | byte(l)
575 case l < 65536:
576 n = 4
577 fh[0] = b
578 fh[1] = b1 | 126
579 binary.BigEndian.PutUint16(fh[2:], uint16(l))
580 default:
581 n = 10
582 fh[0] = b
583 fh[1] = b1 | 127
584 binary.BigEndian.PutUint64(fh[2:], uint64(l))
585 }
586 var key []byte
587 var keyBuf [4]byte
588 if _, err := io.ReadFull(rand.Reader, keyBuf[:4]); err != nil {
589 kv := mrand.Int31()
590 binary.LittleEndian.PutUint32(keyBuf[:4], uint32(kv))
591 }
592 copy(fh[n:], keyBuf[:4])
593 key = fh[n : n+4]
594 n += 4
595 return n, key
596 }
597
598 func (nc *Conn) wsInitHandshake(u *url.URL) error {
599 compress := nc.Opts.Compression
600 tlsRequired := u.Scheme == wsSchemeTLS || nc.Opts.Secure || nc.Opts.TLSConfig != nil || nc.Opts.TLSCertCB != nil || nc.Opts.RootCAsCB != nil
601 // Do TLS here as needed.
602 if tlsRequired {
603 if err := nc.makeTLSConn(); err != nil {
604 return err
605 }
606 } else {
607 nc.bindToNewConn()
608 }
609
610 var err error
611
612 // For http request, we need the passed URL to contain either http or https scheme.
613 scheme := "http"
614 if tlsRequired {
615 scheme = "https"
616 }
617 ustr := fmt.Sprintf("%s://%s", scheme, u.Host)
618
619 if nc.Opts.ProxyPath != "" {
620 proxyPath := nc.Opts.ProxyPath
621 if !strings.HasPrefix(proxyPath, "/") {
622 proxyPath = "/" + proxyPath
623 }
624 ustr += proxyPath
625 } else if u.Path != "" {
626 ustr += u.Path
627 }
628 if u.RawQuery != "" {
629 ustr += "?" + u.RawQuery
630 }
631
632 u, err = url.Parse(ustr)
633 if err != nil {
634 return err
635 }
636 req := &http.Request{
637 Method: "GET",
638 URL: u,
639 Proto: "HTTP/1.1",
640 ProtoMajor: 1,
641 ProtoMinor: 1,
642 Header: make(http.Header),
643 Host: u.Host,
644 }
645 wsKey, err := wsMakeChallengeKey()
646 if err != nil {
647 return err
648 }
649
650 req.Header["Upgrade"] = []string{"websocket"}
651 req.Header["Connection"] = []string{"Upgrade"}
652 req.Header["Sec-WebSocket-Key"] = []string{wsKey}
653 req.Header["Sec-WebSocket-Version"] = []string{"13"}
654 if compress {
655 req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue)
656 }
657 if err := nc.wsUpdateConnectionHeaders(req); err != nil {
658 return err
659 }
660 if err := req.Write(nc.conn); err != nil {
661 return err
662 }
663
664 var resp *http.Response
665
666 br := bufio.NewReaderSize(nc.conn, 4096)
667 nc.conn.SetReadDeadline(time.Now().Add(nc.Opts.Timeout))
668 resp, err = http.ReadResponse(br, req)
669 if err == nil &&
670 (resp.StatusCode != 101 ||
671 !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
672 !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
673 resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) {
674
675 err = errors.New("invalid websocket connection")
676 }
677 // Check compression extension...
678 if err == nil && compress {
679 // Check that not only permessage-deflate extension is present, but that
680 // we also have server and client no context take over.
681 srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header)
682
683 // If server does not support compression, then simply disable it in our side.
684 if !srvCompress {
685 compress = false
686 } else if !noCtxTakeover {
687 err = errors.New("compression negotiation error")
688 }
689 }
690 if resp != nil {
691 resp.Body.Close()
692 }
693 nc.conn.SetReadDeadline(time.Time{})
694 if err != nil {
695 return err
696 }
697
698 wsr := wsNewReader(nc.br.r)
699 wsr.nc = nc
700 wsr.compress = compress
701 // We have to slurp whatever is in the bufio reader and copy to br.r
702 if n := br.Buffered(); n != 0 {
703 wsr.ib, _ = br.Peek(n)
704 }
705 nc.br.r = wsr
706 nc.bw.w = &websocketWriter{w: nc.bw.w, compress: compress}
707 nc.ws = true
708 return nil
709 }
710
711 func (nc *Conn) wsClose() {
712 nc.mu.Lock()
713 defer nc.mu.Unlock()
714 if !nc.ws {
715 return
716 }
717 nc.wsEnqueueCloseMsgLocked(wsCloseStatusNormalClosure, _EMPTY_)
718 }
719
720 func (nc *Conn) wsEnqueueCloseMsg(needsLock bool, status int, payload string) {
721 // In some low-level unit tests it will happen...
722 if nc == nil {
723 return
724 }
725 if needsLock {
726 nc.mu.Lock()
727 defer nc.mu.Unlock()
728 }
729 nc.wsEnqueueCloseMsgLocked(status, payload)
730 }
731
732 func (nc *Conn) wsEnqueueCloseMsgLocked(status int, payload string) {
733 wr, ok := nc.bw.w.(*websocketWriter)
734 if !ok || wr.cmDone {
735 return
736 }
737 statusAndPayloadLen := 2 + len(payload)
738 frame := make([]byte, 2+4+statusAndPayloadLen)
739 n, key := wsFillFrameHeader(frame, false, wsCloseMessage, statusAndPayloadLen)
740 // Set the status
741 binary.BigEndian.PutUint16(frame[n:], uint16(status))
742 // If there is a payload, copy
743 if len(payload) > 0 {
744 copy(frame[n+2:], payload)
745 }
746 // Mask status + payload
747 wsMaskBuf(key, frame[n:n+statusAndPayloadLen])
748 wr.cm = frame
749 wr.cmDone = true
750 nc.bw.flush()
751 if c := wr.compressor; c != nil {
752 c.Close()
753 }
754 }
755
756 func (nc *Conn) wsEnqueueControlMsg(needsLock bool, frameType wsOpCode, payload []byte) {
757 // In some low-level unit tests it will happen...
758 if nc == nil {
759 return
760 }
761 if needsLock {
762 nc.mu.Lock()
763 defer nc.mu.Unlock()
764 }
765 wr, ok := nc.bw.w.(*websocketWriter)
766 if !ok {
767 return
768 }
769 fh, key := wsCreateFrameHeader(false, frameType, len(payload))
770 wr.ctrlFrames = append(wr.ctrlFrames, fh)
771 if len(payload) > 0 {
772 wsMaskBuf(key, payload)
773 wr.ctrlFrames = append(wr.ctrlFrames, payload)
774 }
775 nc.bw.flush()
776 }
777
778 func (nc *Conn) wsUpdateConnectionHeaders(req *http.Request) error {
779 var headers http.Header
780 var err error
781 if nc.Opts.WebSocketConnectionHeadersHandler != nil {
782 headers, err = nc.Opts.WebSocketConnectionHeadersHandler()
783 if err != nil {
784 return err
785 }
786 } else {
787 headers = nc.Opts.WebSocketConnectionHeaders
788 }
789 for key, values := range headers {
790 for _, val := range values {
791 req.Header.Add(key, val)
792 }
793 }
794 return nil
795 }
796
797 func wsPMCExtensionSupport(header http.Header) (bool, bool) {
798 for _, extensionList := range header["Sec-Websocket-Extensions"] {
799 extensions := strings.Split(extensionList, ",")
800 for _, extension := range extensions {
801 extension = strings.Trim(extension, " \t")
802 params := strings.Split(extension, ";")
803 for i, p := range params {
804 p = strings.Trim(p, " \t")
805 if strings.EqualFold(p, wsPMCExtension) {
806 var snc bool
807 var cnc bool
808 for j := i + 1; j < len(params); j++ {
809 p = params[j]
810 p = strings.Trim(p, " \t")
811 if strings.EqualFold(p, wsPMCSrvNoCtx) {
812 snc = true
813 } else if strings.EqualFold(p, wsPMCCliNoCtx) {
814 cnc = true
815 }
816 if snc && cnc {
817 return true, true
818 }
819 }
820 return true, false
821 }
822 }
823 }
824 }
825 return false, false
826 }
827
828 func wsMakeChallengeKey() (string, error) {
829 p := make([]byte, 16)
830 if _, err := io.ReadFull(rand.Reader, p); err != nil {
831 return "", err
832 }
833 return base64.StdEncoding.EncodeToString(p), nil
834 }
835
836 func wsAcceptKey(key string) string {
837 h := sha1.New()
838 h.Write([]byte(key))
839 h.Write(wsGUID)
840 return base64.StdEncoding.EncodeToString(h.Sum(nil))
841 }
842
843 // Returns true if the op code corresponds to a control frame.
844 func wsIsControlFrame(frameType wsOpCode) bool {
845 return frameType >= wsCloseMessage
846 }
847
848 func isWebsocketScheme(u *url.URL) bool {
849 return u.Scheme == wsScheme || u.Scheme == wsSchemeTLS
850 }