Debian Codegraph @

server/websocket.go

raw
1 // Copyright 2020-2026 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 server
15
16 import (
17 "bytes"
18 crand "crypto/rand"
19 "crypto/tls"
20 "encoding/base64"
21 "encoding/binary"
22 "errors"
23 "fmt"
24 "io"
25 "log"
26 mrand "math/rand"
27 "net"
28 "net/http"
29 "net/url"
30 "strconv"
31 "strings"
32 "sync"
33 "sync/atomic"
34 "time"
35 "unicode/utf8"
36
37 "github.com/klauspost/compress/flate"
38 )
39
40 type wsOpCode int
41
42 const (
43 // From https://tools.ietf.org/html/rfc6455#section-5.2
44 wsTextMessage = wsOpCode(1)
45 wsBinaryMessage = wsOpCode(2)
46 wsCloseMessage = wsOpCode(8)
47 wsPingMessage = wsOpCode(9)
48 wsPongMessage = wsOpCode(10)
49
50 wsFinalBit = 1 << 7
51 wsRsv1Bit = 1 << 6 // Used for compression, from https://tools.ietf.org/html/rfc7692#section-6
52 wsRsv2Bit = 1 << 5
53 wsRsv3Bit = 1 << 4
54
55 wsMaskBit = 1 << 7
56
57 wsContinuationFrame = 0
58 wsMaxFrameHeaderSize = 14 // Since LeafNode may need to behave as a client
59 wsMaxControlPayloadSize = 125
60 wsFrameSizeForBrowsers = 4096 // From experiment, webrowsers behave better with limited frame size
61 wsCompressThreshold = 64 // Don't compress for small buffer(s)
62 wsMaxMsgPayloadMultiple = 8
63 wsMaxMsgPayloadLimit = 64 * 1024 * 1024
64 wsCloseSatusSize = 2
65
66 // From https://tools.ietf.org/html/rfc6455#section-11.7
67 wsCloseStatusNormalClosure = 1000
68 wsCloseStatusGoingAway = 1001
69 wsCloseStatusProtocolError = 1002
70 wsCloseStatusUnsupportedData = 1003
71 wsCloseStatusNoStatusReceived = 1005
72 wsCloseStatusInvalidPayloadData = 1007
73 wsCloseStatusPolicyViolation = 1008
74 wsCloseStatusMessageTooBig = 1009
75 wsCloseStatusInternalSrvError = 1011
76 wsCloseStatusTLSHandshake = 1015
77
78 wsFirstFrame = true
79 wsContFrame = false
80 wsFinalFrame = true
81 wsUncompressedFrame = false
82
83 wsSchemePrefix = "ws"
84 wsSchemePrefixTLS = "wss"
85
86 wsNoMaskingHeader = "Nats-No-Masking"
87 wsNoMaskingValue = "true"
88 wsXForwardedForHeader = "X-Forwarded-For"
89 wsNoMaskingFullResponse = wsNoMaskingHeader + ": " + wsNoMaskingValue + CR_LF
90 wsPMCExtension = "permessage-deflate" // per-message compression
91 wsPMCSrvNoCtx = "server_no_context_takeover"
92 wsPMCCliNoCtx = "client_no_context_takeover"
93 wsPMCReqHeaderValue = wsPMCExtension + "; " + wsPMCSrvNoCtx + "; " + wsPMCCliNoCtx
94 wsPMCFullResponse = "Sec-WebSocket-Extensions: " + wsPMCExtension + "; " + wsPMCSrvNoCtx + "; " + wsPMCCliNoCtx + _CRLF_
95 wsSecProto = "Sec-Websocket-Protocol"
96 wsMQTTSecProtoVal = "mqtt"
97 wsMQTTSecProto = wsSecProto + ": " + wsMQTTSecProtoVal + CR_LF
98 )
99
100 var decompressorPool sync.Pool
101 var compressLastBlock = []byte{0x00, 0x00, 0xff, 0xff, 0x01, 0x00, 0x00, 0xff, 0xff}
102
103 // From https://tools.ietf.org/html/rfc6455#section-1.3
104 var wsGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
105
106 // Test can enable this so that server does not support "no-masking" requests.
107 var wsTestRejectNoMasking = false
108
109 type websocket struct {
110 frames net.Buffers
111 fs int64
112 closeMsg []byte
113 compress bool
114 closeSent bool
115 browser bool
116 nocompfrag bool // No fragment for compressed frames
117 maskread bool
118 maskwrite bool
119 compressor *flate.Writer
120 cookieJwt string
121 cookieUsername string
122 cookiePassword string
123 cookieToken string
124 clientIP string
125 }
126
127 type srvWebsocket struct {
128 mu sync.RWMutex
129 server *http.Server
130 listener net.Listener
131 listenerErr error
132 allowedOrigins map[string][]*allowedOrigin // host will be the key
133 sameOrigin bool
134 connectURLs []string
135 connectURLsMap refCountedUrlSet
136 authOverride bool // indicate if there is auth override in websocket config
137 rawHeaders string // raw headers to be used in the upgrade response.
138
139 // These are immutable and can be accessed without lock.
140 // This is the case when generating the client INFO.
141 tls bool // True if TLS is required (TLSConfig is specified).
142 host string // Host/IP the webserver is listening on (shortcut to opts.Websocket.Host).
143 port int // Port the webserver is listening on. This is after an ephemeral port may have been selected (shortcut to opts.Websocket.Port).
144 }
145
146 type allowedOrigin struct {
147 scheme string
148 port string
149 }
150
151 type wsUpgradeResult struct {
152 conn net.Conn
153 ws *websocket
154 kind int
155 }
156
157 type wsReadInfo struct {
158 rem uint64
159 fs bool
160 ff bool
161 fc bool
162 mask bool // Incoming leafnode connections may not have masking.
163 mkpos byte
164 mkey [4]byte
165 cbufs [][]byte
166 coff int
167 csz uint64
168 }
169
170 func (r *wsReadInfo) init() {
171 r.fs, r.ff = true, true
172 }
173
174 func (r *wsReadInfo) resetCompressedState() {
175 r.fs = true
176 r.ff = true
177 r.fc = false
178 r.rem = 0
179 r.cbufs = nil
180 r.coff = 0
181 r.csz = 0
182 }
183
184 // Compressed WebSocket messages have to be accumulated before they can be
185 // decompressed and handed to the parser, so this transport limit needs to
186 // allow batching several max_payload-sized NATS operations while still
187 // capping resource usage on the buffered compressed path.
188 func wsMaxMessageSize(mpay int) uint64 {
189 if mpay <= 0 {
190 mpay = MAX_PAYLOAD_SIZE
191 }
192 limit := uint64(mpay) * wsMaxMsgPayloadMultiple
193 if limit > wsMaxMsgPayloadLimit {
194 limit = wsMaxMsgPayloadLimit
195 }
196 return limit
197 }
198
199 // Returns a slice containing `needed` bytes from the given buffer `buf`
200 // starting at position `pos`, and possibly read from the given reader `r`.
201 // When bytes are present in `buf`, the `pos` is incremented by the number
202 // of bytes found up to `needed` and the new position is returned. If not
203 // enough bytes are found, the bytes found in `buf` are copied to the returned
204 // slice and the remaning bytes are read from `r`.
205 func wsGet(r io.Reader, buf []byte, pos, needed uint64) ([]byte, uint64, error) {
206 avail := uint64(len(buf)) - pos
207 if avail >= needed {
208 return buf[pos : pos+needed], pos + needed, nil
209 }
210 b := make([]byte, needed)
211 start := uint64(copy(b, buf[pos:]))
212 for start != needed {
213 n, err := r.Read(b[start:cap(b)])
214 if err != nil {
215 return nil, 0, err
216 }
217 start += uint64(n)
218 }
219 return b, pos + avail, nil
220 }
221
222 // Returns true if this connection is from a Websocket client.
223 // Lock held on entry.
224 func (c *client) isWebsocket() bool {
225 return c.ws != nil
226 }
227
228 // Returns a slice of byte slices corresponding to payload of websocket frames.
229 // The byte slice `buf` is filled with bytes from the connection's read loop.
230 // This function will decode the frame headers and unmask the payload(s).
231 // It is possible that the returned slices point to the given `buf` slice, so
232 // `buf` should not be overwritten until the returned slices have been parsed.
233 //
234 // Client lock MUST NOT be held on entry.
235 func (c *client) wsRead(r *wsReadInfo, ior io.Reader, buf []byte) ([][]byte, error) {
236 var bufs [][]byte
237 err := c.wsReadLoop(r, ior, buf, func(b []byte, compressed, final bool) error {
238 if compressed {
239 return errors.New("compressed websocket frames require wsReadAndParse")
240 }
241 bufs = append(bufs, b)
242 return nil
243 })
244 return bufs, err
245 }
246
247 func (c *client) wsReadAndParse(r *wsReadInfo, ior io.Reader, buf []byte) error {
248 mpay := int(atomic.LoadInt32(&c.mpay))
249 if mpay <= 0 {
250 mpay = MAX_PAYLOAD_SIZE
251 }
252 return c.wsReadLoop(r, ior, buf, func(b []byte, compressed, final bool) error {
253 if compressed {
254 if err := c.wsDecompressAndParse(r, b, final, mpay); err != nil {
255 r.resetCompressedState()
256 return err
257 }
258 if final {
259 r.fc = false
260 }
261 return nil
262 }
263 return c.parse(b)
264 })
265 }
266
267 func (c *client) wsReadLoop(r *wsReadInfo, ior io.Reader, buf []byte, handle func([]byte, bool, bool) error) error {
268 var (
269 tmpBuf []byte
270 err error
271 pos uint64
272 max = uint64(len(buf))
273 )
274 for pos != max {
275 if r.fs {
276 b0 := buf[pos]
277 frameType := wsOpCode(b0 & 0xF)
278 final := b0&wsFinalBit != 0
279 compressed := b0&wsRsv1Bit != 0
280 if b0&(wsRsv2Bit|wsRsv3Bit) != 0 {
281 return c.wsHandleProtocolError("RSV2 and RSV3 must be clear")
282 }
283 if compressed && !c.ws.compress {
284 return c.wsHandleProtocolError("compressed frame received without negotiated permessage-deflate")
285 }
286 pos++
287
288 tmpBuf, pos, err = wsGet(ior, buf, pos, 1)
289 if err != nil {
290 return err
291 }
292 b1 := tmpBuf[0]
293
294 // Clients MUST set the mask bit. If not set, reject.
295 // However, LEAF by default will not have masking, unless they are forced to, by configuration.
296 if r.mask && b1&wsMaskBit == 0 {
297 return c.wsHandleProtocolError("mask bit missing")
298 }
299
300 // Store size in case it is < 125
301 r.rem = uint64(b1 & 0x7F)
302
303 switch frameType {
304 case wsPingMessage, wsPongMessage, wsCloseMessage:
305 if r.rem > wsMaxControlPayloadSize {
306 return c.wsHandleProtocolError(
307 fmt.Sprintf("control frame length bigger than maximum allowed of %v bytes",
308 wsMaxControlPayloadSize))
309 }
310 if !final {
311 return c.wsHandleProtocolError("control frame does not have final bit set")
312 }
313 if compressed {
314 return c.wsHandleProtocolError("control frame must not be compressed")
315 }
316 case wsTextMessage, wsBinaryMessage:
317 if !r.ff {
318 return c.wsHandleProtocolError("new message started before final frame for previous message was received")
319 }
320 r.ff = final
321 r.fc = compressed
322 case wsContinuationFrame:
323 // Compressed bit must be only set in the first frame
324 if r.ff || compressed {
325 return c.wsHandleProtocolError("invalid continuation frame")
326 }
327 r.ff = final
328 default:
329 return c.wsHandleProtocolError(fmt.Sprintf("unknown opcode %v", frameType))
330 }
331
332 switch r.rem {
333 case 126:
334 tmpBuf, pos, err = wsGet(ior, buf, pos, 2)
335 if err != nil {
336 return err
337 }
338 r.rem = uint64(binary.BigEndian.Uint16(tmpBuf))
339 case 127:
340 tmpBuf, pos, err = wsGet(ior, buf, pos, 8)
341 if err != nil {
342 return err
343 }
344 if r.rem = binary.BigEndian.Uint64(tmpBuf); r.rem&(uint64(1)<<63) != 0 {
345 return c.wsHandleProtocolError("invalid 64-bit payload length")
346 }
347 }
348
349 if r.mask {
350 // Read masking key
351 tmpBuf, pos, err = wsGet(ior, buf, pos, 4)
352 if err != nil {
353 return err
354 }
355 copy(r.mkey[:], tmpBuf)
356 r.mkpos = 0
357 }
358
359 // Handle control messages in place...
360 if wsIsControlFrame(frameType) {
361 pos, err = c.wsHandleControlFrame(r, frameType, ior, buf, pos)
362 if err != nil {
363 return err
364 }
365 continue
366 }
367
368 // Done with the frame header
369 r.fs = false
370 }
371 if pos < max {
372 n := r.rem
373 if pos+n > max {
374 n = max - pos
375 }
376 b := buf[pos : pos+n]
377 pos += n
378 r.rem -= n
379 // If needed, unmask the buffer
380 if r.mask {
381 r.unmask(b)
382 }
383 if err := handle(b, r.fc, r.ff && r.rem == 0); err != nil {
384 return err
385 }
386 if r.rem == 0 {
387 r.fs = true
388 }
389 }
390 }
391 return nil
392 }
393
394 func (r *wsReadInfo) Read(dst []byte) (int, error) {
395 if len(dst) == 0 {
396 return 0, nil
397 }
398 if len(r.cbufs) == 0 {
399 return 0, io.EOF
400 }
401 copied := 0
402 rem := len(dst)
403 for buf := r.cbufs[0]; buf != nil && rem > 0; {
404 n := len(buf[r.coff:])
405 if n > rem {
406 n = rem
407 }
408 copy(dst[copied:], buf[r.coff:r.coff+n])
409 copied += n
410 rem -= n
411 r.coff += n
412 buf = r.nextCBuf()
413 }
414 return copied, nil
415 }
416
417 func (r *wsReadInfo) nextCBuf() []byte {
418 // We still have remaining data in the first buffer
419 if r.coff != len(r.cbufs[0]) {
420 return r.cbufs[0]
421 }
422 // We read the full first buffer. Reset offset.
423 r.coff = 0
424 // We were at the last buffer, so we are done.
425 if len(r.cbufs) == 1 {
426 r.cbufs = nil
427 return nil
428 }
429 // Here we move to the next buffer.
430 r.cbufs = r.cbufs[1:]
431 return r.cbufs[0]
432 }
433
434 func (r *wsReadInfo) ReadByte() (byte, error) {
435 for len(r.cbufs) > 0 && len(r.cbufs[0]) == 0 {
436 r.nextCBuf()
437 }
438 if len(r.cbufs) == 0 {
439 return 0, io.EOF
440 }
441 b := r.cbufs[0][r.coff]
442 r.coff++
443 r.nextCBuf()
444 return b, nil
445 }
446
447 func (c *client) wsDecompressAndParse(r *wsReadInfo, b []byte, final bool, mpay int) error {
448 limit := wsMaxMessageSize(mpay)
449 if len(b) > 0 {
450 if r.csz+uint64(len(b)) > limit {
451 return ErrMaxPayload
452 }
453 r.cbufs = append(r.cbufs, append([]byte(nil), b...))
454 r.csz += uint64(len(b))
455 }
456 if !final {
457 return nil
458 }
459 if r.csz+uint64(len(compressLastBlock)) > limit {
460 return ErrMaxPayload
461 }
462 r.cbufs = append(r.cbufs, compressLastBlock)
463 r.csz += uint64(len(compressLastBlock))
464 r.coff = 0
465 d, _ := decompressorPool.Get().(io.ReadCloser)
466 if d == nil {
467 d = flate.NewReader(r)
468 } else {
469 d.(flate.Resetter).Reset(r, nil)
470 }
471 defer func() {
472 d.Close()
473 decompressorPool.Put(d)
474 r.cbufs = nil
475 r.coff = 0
476 r.csz = 0
477 }()
478 lr := io.LimitedReader{R: d, N: int64(mpay + 1)}
479 buf := make([]byte, 32*1024)
480 total := 0
481 for {
482 n, err := lr.Read(buf)
483 if n > 0 {
484 pn := n
485 if total+n > mpay {
486 pn = mpay - total
487 }
488 if pn > 0 {
489 if err := c.parse(buf[:pn]); err != nil {
490 return err
491 }
492 }
493 total += n
494 if total > mpay {
495 return ErrMaxPayload
496 }
497 }
498 if err == nil {
499 continue
500 }
501 if err == io.EOF {
502 return nil
503 }
504 return err
505 }
506 }
507
508 // Handles the PING, PONG and CLOSE websocket control frames.
509 //
510 // Client lock MUST NOT be held on entry.
511 func (c *client) wsHandleControlFrame(r *wsReadInfo, frameType wsOpCode, nc io.Reader, buf []byte, pos uint64) (uint64, error) {
512 var payload []byte
513 var err error
514
515 if r.rem > 0 {
516 payload, pos, err = wsGet(nc, buf, pos, r.rem)
517 if err != nil {
518 return pos, err
519 }
520 if r.mask {
521 r.unmask(payload)
522 }
523 r.rem = 0
524 }
525 switch frameType {
526 case wsCloseMessage:
527 status := wsCloseStatusNoStatusReceived
528 var body string
529 lp := len(payload)
530 if lp == 1 {
531 return pos, c.wsHandleProtocolError("close frame payload cannot be 1 byte")
532 }
533 // If there is a payload, the status is represented as a 2-byte
534 // unsigned integer (in network byte order). Then, there may be an
535 // optional body.
536 hasStatus, hasBody := lp >= wsCloseSatusSize, lp > wsCloseSatusSize
537 if hasStatus {
538 // Decode the status
539 status = int(binary.BigEndian.Uint16(payload[:wsCloseSatusSize]))
540 if !wsIsValidCloseStatus(status) {
541 return pos, c.wsHandleProtocolError(fmt.Sprintf("invalid close status code %v", status))
542 }
543 // Now if there is a body, capture it and make sure this is a valid UTF-8.
544 if hasBody {
545 body = string(payload[wsCloseSatusSize:])
546 if !utf8.ValidString(body) {
547 // https://tools.ietf.org/html/rfc6455#section-5.5.1
548 // If body is present, it must be a valid utf8
549 status = wsCloseStatusInvalidPayloadData
550 body = "invalid utf8 body in close frame"
551 }
552 }
553 }
554 // If the status indicates that nothing was received, then we don't
555 // send anything back.
556 // From https://datatracker.ietf.org/doc/html/rfc6455#section-7.4
557 // it says that code 1005 is a reserved value and MUST NOT be set as a
558 // status code in a Close control frame by an endpoint. It is
559 // designated for use in applications expecting a status code to indicate
560 // that no status code was actually present.
561 var clm []byte
562 if status != wsCloseStatusNoStatusReceived {
563 clm = wsCreateCloseMessage(status, body)
564 }
565 c.wsEnqueueControlMessage(wsCloseMessage, clm)
566 if len(clm) > 0 {
567 nbPoolPut(clm) // wsEnqueueControlMessage has taken a copy.
568 }
569 // Return io.EOF so that readLoop will close the connection as ClientClosed
570 // after processing pending buffers.
571 return pos, io.EOF
572 case wsPingMessage:
573 c.wsEnqueueControlMessage(wsPongMessage, payload)
574 case wsPongMessage:
575 // Nothing to do..
576 }
577 return pos, nil
578 }
579
580 // Unmask the given slice.
581 func (r *wsReadInfo) unmask(buf []byte) {
582 p := int(r.mkpos)
583 if len(buf) < 16 {
584 for i := 0; i < len(buf); i++ {
585 buf[i] ^= r.mkey[p&3]
586 p++
587 }
588 r.mkpos = byte(p & 3)
589 return
590 }
591 var k [8]byte
592 for i := 0; i < 8; i++ {
593 k[i] = r.mkey[(p+i)&3]
594 }
595 km := binary.BigEndian.Uint64(k[:])
596 n := (len(buf) / 8) * 8
597 for i := 0; i < n; i += 8 {
598 tmp := binary.BigEndian.Uint64(buf[i : i+8])
599 tmp ^= km
600 binary.BigEndian.PutUint64(buf[i:], tmp)
601 }
602 buf = buf[n:]
603 for i := 0; i < len(buf); i++ {
604 buf[i] ^= r.mkey[p&3]
605 p++
606 }
607 r.mkpos = byte(p & 3)
608 }
609
610 // Returns true if the op code corresponds to a control frame.
611 func wsIsControlFrame(frameType wsOpCode) bool {
612 return frameType >= wsCloseMessage
613 }
614
615 // Create the frame header.
616 // Encodes the frame type and optional compression flag, and the size of the payload.
617 func wsCreateFrameHeader(useMasking, compressed bool, frameType wsOpCode, l int) ([]byte, []byte) {
618 fh := nbPoolGet(wsMaxFrameHeaderSize)[:wsMaxFrameHeaderSize]
619 n, key := wsFillFrameHeader(fh, useMasking, wsFirstFrame, wsFinalFrame, compressed, frameType, l)
620 return fh[:n], key
621 }
622
623 func wsFillFrameHeader(fh []byte, useMasking, first, final, compressed bool, frameType wsOpCode, l int) (int, []byte) {
624 var n int
625 var b byte
626 if first {
627 b = byte(frameType)
628 }
629 if final {
630 b |= wsFinalBit
631 }
632 if compressed {
633 b |= wsRsv1Bit
634 }
635 b1 := byte(0)
636 if useMasking {
637 b1 |= wsMaskBit
638 }
639 switch {
640 case l <= 125:
641 n = 2
642 fh[0] = b
643 fh[1] = b1 | byte(l)
644 case l < 65536:
645 n = 4
646 fh[0] = b
647 fh[1] = b1 | 126
648 binary.BigEndian.PutUint16(fh[2:], uint16(l))
649 default:
650 n = 10
651 fh[0] = b
652 fh[1] = b1 | 127
653 binary.BigEndian.PutUint64(fh[2:], uint64(l))
654 }
655 var key []byte
656 if useMasking {
657 var keyBuf [4]byte
658 if _, err := io.ReadFull(crand.Reader, keyBuf[:4]); err != nil {
659 kv := mrand.Int31()
660 binary.LittleEndian.PutUint32(keyBuf[:4], uint32(kv))
661 }
662 copy(fh[n:], keyBuf[:4])
663 key = fh[n : n+4]
664 n += 4
665 }
666 return n, key
667 }
668
669 // Invokes wsEnqueueControlMessageLocked under client lock.
670 //
671 // Client lock MUST NOT be held on entry
672 func (c *client) wsEnqueueControlMessage(controlMsg wsOpCode, payload []byte) {
673 c.mu.Lock()
674 c.wsEnqueueControlMessageLocked(controlMsg, payload)
675 c.mu.Unlock()
676 }
677
678 // Mask the buffer with the given key
679 func wsMaskBuf(key, buf []byte) {
680 for i := 0; i < len(buf); i++ {
681 buf[i] ^= key[i&3]
682 }
683 }
684
685 // Mask the buffers, as if they were contiguous, with the given key
686 func wsMaskBufs(key []byte, bufs [][]byte) {
687 pos := 0
688 for i := 0; i < len(bufs); i++ {
689 buf := bufs[i]
690 for j := 0; j < len(buf); j++ {
691 buf[j] ^= key[pos&3]
692 pos++
693 }
694 }
695 }
696
697 // Enqueues a websocket control message.
698 // If the control message is a wsCloseMessage, then marks this client
699 // has having sent the close message (since only one should be sent).
700 // This will prevent the generic closeConnection() to enqueue one.
701 //
702 // Client lock held on entry.
703 func (c *client) wsEnqueueControlMessageLocked(controlMsg wsOpCode, payload []byte) {
704 // Control messages are never compressed and their size will be
705 // less than wsMaxControlPayloadSize, which means the frame header
706 // will be only 2 or 6 bytes.
707 useMasking := c.ws.maskwrite
708 sz := 2
709 if useMasking {
710 sz += 4
711 }
712 cm := nbPoolGet(sz + len(payload))
713 cm = cm[:cap(cm)]
714 n, key := wsFillFrameHeader(cm, useMasking, wsFirstFrame, wsFinalFrame, wsUncompressedFrame, controlMsg, len(payload))
715 cm = cm[:n]
716 // Note that payload is optional.
717 if len(payload) > 0 {
718 cm = append(cm, payload...)
719 if useMasking {
720 wsMaskBuf(key, cm[n:])
721 }
722 }
723 c.out.pb += int64(len(cm))
724 if controlMsg == wsCloseMessage {
725 // We can't add the close message to the frames buffers
726 // now. It will be done on a flushOutbound() when there
727 // are no more pending buffers to send.
728 c.ws.closeSent = true
729 c.ws.closeMsg = cm
730 } else {
731 c.ws.frames = append(c.ws.frames, cm)
732 c.ws.fs += int64(len(cm))
733 }
734 c.flushSignal()
735 }
736
737 // Enqueues a websocket close message with a status mapped from the given `reason`.
738 //
739 // Client lock held on entry
740 func (c *client) wsEnqueueCloseMessage(reason ClosedState) {
741 var status int
742 switch reason {
743 case ClientClosed:
744 status = wsCloseStatusNormalClosure
745 case AuthenticationTimeout, AuthenticationViolation, SlowConsumerPendingBytes, SlowConsumerWriteDeadline,
746 MaxAccountConnectionsExceeded, MaxConnectionsExceeded, MaxControlLineExceeded, MaxSubscriptionsExceeded,
747 MissingAccount, AuthenticationExpired, Revocation:
748 status = wsCloseStatusPolicyViolation
749 case TLSHandshakeError:
750 status = wsCloseStatusTLSHandshake
751 case ParseError, ProtocolViolation, BadClientProtocolVersion:
752 status = wsCloseStatusProtocolError
753 case MaxPayloadExceeded:
754 status = wsCloseStatusMessageTooBig
755 case WriteError, ReadError, StaleConnection, ServerShutdown:
756 // We used to have WriteError, ReadError and StaleConnection result in
757 // code 1006, which the spec says that it must not be used to set the
758 // status in the close message. So using this one instead.
759 status = wsCloseStatusGoingAway
760 default:
761 status = wsCloseStatusInternalSrvError
762 }
763 body := wsCreateCloseMessage(status, reason.String())
764 c.wsEnqueueControlMessageLocked(wsCloseMessage, body)
765 nbPoolPut(body) // wsEnqueueControlMessageLocked has taken a copy.
766 }
767
768 // Create and then enqueue a close message with a protocol error and the
769 // given message. This is invoked when parsing websocket frames.
770 //
771 // Lock MUST NOT be held on entry.
772 func (c *client) wsHandleProtocolError(message string) error {
773 buf := wsCreateCloseMessage(wsCloseStatusProtocolError, message)
774 c.wsEnqueueControlMessage(wsCloseMessage, buf)
775 nbPoolPut(buf) // wsEnqueueControlMessage has taken a copy.
776 return errors.New(message)
777 }
778
779 func wsIsValidCloseStatus(code int) bool {
780 switch code {
781 case wsCloseStatusNoStatusReceived, 1004, 1006, wsCloseStatusTLSHandshake:
782 return false
783 }
784 if code < 1000 || code >= 5000 {
785 return false
786 }
787 // 1016-2999 are currently reserved.
788 if code >= 1016 && code <= 2999 {
789 return false
790 }
791 return true
792 }
793
794 // Create a close message with the given `status` and `body`.
795 // If the `body` is more than the maximum allows control frame payload size,
796 // it is truncated and "..." is added at the end (as a hint that message
797 // is not complete).
798 func wsCreateCloseMessage(status int, body string) []byte {
799 // Since a control message payload is limited in size, we
800 // will limit the text and add trailing "..." if truncated.
801 // The body of a Close Message must be preceded with 2 bytes,
802 // so take that into account for limiting the body length.
803 if len(body) > wsMaxControlPayloadSize-2 {
804 body = body[:wsMaxControlPayloadSize-5]
805 body += "..."
806 }
807 buf := nbPoolGet(2 + len(body))[:2+len(body)]
808 // We need to have a 2 byte unsigned int that represents the error status code
809 // https://tools.ietf.org/html/rfc6455#section-5.5.1
810 binary.BigEndian.PutUint16(buf[:2], uint16(status))
811 copy(buf[2:], []byte(body))
812 return buf
813 }
814
815 // Process websocket client handshake. On success, returns the raw net.Conn that
816 // will be used to create a *client object.
817 // Invoked from the HTTP server listening on websocket port.
818 func (s *Server) wsUpgrade(w http.ResponseWriter, r *http.Request) (*wsUpgradeResult, error) {
819 kind := CLIENT
820 if r.URL != nil {
821 ep := r.URL.EscapedPath()
822 if strings.HasSuffix(ep, leafNodeWSPath) {
823 kind = LEAF
824 } else if strings.HasSuffix(ep, mqttWSPath) {
825 kind = MQTT
826 }
827 }
828
829 opts := s.getOpts()
830
831 // Reject MQTT-over-WebSocket upgrades unless MQTT is enabled.
832 if kind == MQTT && opts.MQTT.Port == 0 {
833 return nil, wsReturnHTTPError(w, r, http.StatusNotFound, "mqtt websocket endpoint not enabled")
834 }
835
836 // From https://tools.ietf.org/html/rfc6455#section-4.2.1
837 // Point 1.
838 if r.Method != "GET" {
839 return nil, wsReturnHTTPError(w, r, http.StatusMethodNotAllowed, "request method must be GET")
840 }
841 // Point 2.
842 if r.Host == _EMPTY_ {
843 return nil, wsReturnHTTPError(w, r, http.StatusBadRequest, "'Host' missing in request")
844 }
845 // Point 3.
846 if !wsHeaderContains(r.Header, "Upgrade", "websocket") {
847 return nil, wsReturnHTTPError(w, r, http.StatusBadRequest, "invalid value for header 'Upgrade'")
848 }
849 // Point 4.
850 if !wsHeaderContains(r.Header, "Connection", "Upgrade") {
851 return nil, wsReturnHTTPError(w, r, http.StatusBadRequest, "invalid value for header 'Connection'")
852 }
853 // Point 5.
854 key := r.Header.Get("Sec-Websocket-Key")
855 if key == _EMPTY_ {
856 return nil, wsReturnHTTPError(w, r, http.StatusBadRequest, "key missing")
857 }
858 decoded, err := base64.StdEncoding.DecodeString(key)
859 if err != nil || len(decoded) != 16 {
860 return nil, wsReturnHTTPError(w, r, http.StatusBadRequest, "invalid websocket key")
861 }
862 // Point 6.
863 if !wsHeaderContains(r.Header, "Sec-Websocket-Version", "13") {
864 return nil, wsReturnHTTPError(w, r, http.StatusBadRequest, "invalid version")
865 }
866 // Others are optional
867 // Point 7.
868 if err := s.websocket.checkOrigin(r); err != nil {
869 return nil, wsReturnHTTPError(w, r, http.StatusForbidden, fmt.Sprintf("origin not allowed: %v", err))
870 }
871 // Point 8.
872 // We don't have protocols, so ignore.
873 // Point 9.
874 // Extensions, only support for compression at the moment
875 compress := opts.Websocket.Compression
876 if compress {
877 // Simply check if permessage-deflate extension is present.
878 compress, _ = wsPMCExtensionSupport(r.Header, true)
879 }
880 // We will do masking if asked (unless we reject for tests)
881 noMasking := r.Header.Get(wsNoMaskingHeader) == wsNoMaskingValue && !wsTestRejectNoMasking
882
883 h, ok := w.(http.Hijacker)
884 if !ok {
885 return nil, wsReturnHTTPError(w, r, http.StatusBadRequest, "websocket upgrade not supported")
886 }
887 conn, brw, err := h.Hijack()
888 if err != nil {
889 if conn != nil {
890 conn.Close()
891 }
892 return nil, wsReturnHTTPError(w, r, http.StatusInternalServerError, err.Error())
893 }
894 if brw.Reader.Buffered() > 0 {
895 conn.Close()
896 return nil, wsReturnHTTPError(w, r, http.StatusBadRequest, "client sent data before handshake is complete")
897 }
898
899 var buf [1024]byte
900 p := buf[:0]
901
902 // From https://tools.ietf.org/html/rfc6455#section-4.2.2
903 p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
904 p = append(p, wsAcceptKey(key)...)
905 p = append(p, _CRLF_...)
906 if compress {
907 p = append(p, wsPMCFullResponse...)
908 }
909 if noMasking {
910 p = append(p, wsNoMaskingFullResponse...)
911 }
912 if kind == MQTT {
913 p = append(p, wsMQTTSecProto...)
914 }
915 if s.websocket.rawHeaders != _EMPTY_ {
916 p = append(p, s.websocket.rawHeaders...)
917 }
918 p = append(p, _CRLF_...)
919
920 if _, err = conn.Write(p); err != nil {
921 conn.Close()
922 return nil, err
923 }
924 // If there was a deadline set for the handshake, clear it now.
925 if opts.Websocket.HandshakeTimeout > 0 {
926 conn.SetDeadline(time.Time{})
927 }
928 // Server always expect "clients" to send masked payload, unless the option
929 // "no-masking" has been enabled.
930 ws := &websocket{compress: compress, maskread: !noMasking}
931
932 // Check for X-Forwarded-For header
933 if cips, ok := r.Header[wsXForwardedForHeader]; ok {
934 if len(cips) > 0 {
935 cip := cips[0]
936 if net.ParseIP(cip) != nil {
937 ws.clientIP = cip
938 }
939 }
940 }
941
942 if kind == CLIENT || kind == MQTT {
943 // Indicate if this is likely coming from a browser.
944 if ua := r.Header.Get("User-Agent"); ua != _EMPTY_ && strings.HasPrefix(ua, "Mozilla/") {
945 ws.browser = true
946 // Disable fragmentation of compressed frames for Safari browsers.
947 // Unfortunately, you could be running Chrome on macOS and this
948 // string will contain "Safari/" (along "Chrome/"). However, what
949 // I have found is that actual Safari browser also have "Version/".
950 // So make the combination of the two.
951 ws.nocompfrag = ws.compress && strings.Contains(ua, "Version/") && strings.Contains(ua, "Safari/")
952 }
953
954 if cookies := r.Cookies(); len(cookies) > 0 {
955 ows := &opts.Websocket
956 for _, c := range cookies {
957 if ows.JWTCookie == c.Name {
958 ws.cookieJwt = c.Value
959 } else if ows.UsernameCookie == c.Name {
960 ws.cookieUsername = c.Value
961 } else if ows.PasswordCookie == c.Name {
962 ws.cookiePassword = c.Value
963 } else if ows.TokenCookie == c.Name {
964 ws.cookieToken = c.Value
965 }
966 }
967 }
968 }
969 return &wsUpgradeResult{conn: conn, ws: ws, kind: kind}, nil
970 }
971
972 // Returns true if the header named `name` contains a token with value `value`.
973 func wsHeaderContains(header http.Header, name string, value string) bool {
974 for _, s := range header[name] {
975 tokens := strings.Split(s, ",")
976 for _, t := range tokens {
977 t = strings.Trim(t, " \t")
978 if strings.EqualFold(t, value) {
979 return true
980 }
981 }
982 }
983 return false
984 }
985
986 func wsPMCExtensionSupport(header http.Header, checkPMCOnly bool) (bool, bool) {
987 for _, extensionList := range header["Sec-Websocket-Extensions"] {
988 extensions := strings.Split(extensionList, ",")
989 for _, extension := range extensions {
990 extension = strings.Trim(extension, " \t")
991 params := strings.Split(extension, ";")
992 for i, p := range params {
993 p = strings.Trim(p, " \t")
994 if strings.EqualFold(p, wsPMCExtension) {
995 if checkPMCOnly {
996 return true, false
997 }
998 var snc bool
999 var cnc bool
1000 for j := i + 1; j < len(params); j++ {
1001 p = params[j]
1002 p = strings.Trim(p, " \t")
1003 if strings.EqualFold(p, wsPMCSrvNoCtx) {
1004 snc = true
1005 } else if strings.EqualFold(p, wsPMCCliNoCtx) {
1006 cnc = true
1007 }
1008 if snc && cnc {
1009 return true, true
1010 }
1011 }
1012 return true, false
1013 }
1014 }
1015 }
1016 }
1017 return false, false
1018 }
1019
1020 // Send an HTTP error with the given `status` to the given http response writer `w`.
1021 // Return an error created based on the `reason` string.
1022 func wsReturnHTTPError(w http.ResponseWriter, r *http.Request, status int, reason string) error {
1023 err := fmt.Errorf("%s - websocket handshake error: %s", r.RemoteAddr, reason)
1024 w.Header().Set("Sec-Websocket-Version", "13")
1025 http.Error(w, http.StatusText(status), status)
1026 return err
1027 }
1028
1029 // If the server is configured to accept any origin, then this function returns
1030 // `nil` without checking if the Origin is present and valid. This is also
1031 // the case if the request does not have the Origin header.
1032 // Otherwise, this will check that the Origin matches the same origin or
1033 // any origin in the allowed list.
1034 func (w *srvWebsocket) checkOrigin(r *http.Request) error {
1035 w.mu.RLock()
1036 checkSame := w.sameOrigin
1037 listEmpty := len(w.allowedOrigins) == 0
1038 w.mu.RUnlock()
1039 if !checkSame && listEmpty {
1040 return nil
1041 }
1042 origin := r.Header.Get("Origin")
1043 if origin == _EMPTY_ {
1044 origin = r.Header.Get("Sec-Websocket-Origin")
1045 }
1046 // If the header is not present, we will accept.
1047 // From https://datatracker.ietf.org/doc/html/rfc6455#section-1.6
1048 // "Naturally, when the WebSocket Protocol is used by a dedicated client
1049 // directly (i.e., not from a web page through a web browser), the origin
1050 // model is not useful, as the client can provide any arbitrary origin string."
1051 if origin == _EMPTY_ {
1052 return nil
1053 }
1054 u, err := url.ParseRequestURI(origin)
1055 if err != nil {
1056 return err
1057 }
1058 oh, op, err := wsGetHostAndPort(u.Scheme == "https", u.Host)
1059 if err != nil {
1060 return err
1061 }
1062 // If checking same origin, compare with the http's request's Host.
1063 if checkSame {
1064 rh, rp, err := wsGetHostAndPort(r.TLS != nil, r.Host)
1065 if err != nil {
1066 return err
1067 }
1068 rs := "http"
1069 if r.TLS != nil {
1070 rs = "https"
1071 }
1072 if oh != rh || op != rp || !strings.EqualFold(u.Scheme, rs) {
1073 return errors.New("not same origin")
1074 }
1075 // I guess it is possible to have cases where one wants to check
1076 // same origin, but also that the origin is in the allowed list.
1077 // So continue with the next check.
1078 }
1079 if !listEmpty {
1080 w.mu.RLock()
1081 origins := w.allowedOrigins[oh]
1082 w.mu.RUnlock()
1083 var allowed bool
1084 for _, ao := range origins {
1085 if u.Scheme == ao.scheme && op == ao.port {
1086 allowed = true
1087 break
1088 }
1089 }
1090 if !allowed {
1091 return errors.New("not in the allowed list")
1092 }
1093 }
1094 return nil
1095 }
1096
1097 func wsGetHostAndPort(tls bool, hostport string) (string, string, error) {
1098 host, port, err := net.SplitHostPort(hostport)
1099 if err != nil {
1100 // If error is missing port, then use defaults based on the scheme
1101 if ae, ok := err.(*net.AddrError); ok && strings.Contains(ae.Err, "missing port") {
1102 err = nil
1103 host = hostport
1104 if tls {
1105 port = "443"
1106 } else {
1107 port = "80"
1108 }
1109 }
1110 }
1111 return strings.ToLower(host), port, err
1112 }
1113
1114 func wsMakeChallengeKey() (string, error) {
1115 p := make([]byte, 16)
1116 if _, err := io.ReadFull(crand.Reader, p); err != nil {
1117 return _EMPTY_, err
1118 }
1119 return base64.StdEncoding.EncodeToString(p), nil
1120 }
1121
1122 // Validate the websocket related options.
1123 func validateWebsocketOptions(o *Options) error {
1124 wo := &o.Websocket
1125 // If no port is defined, we don't care about other options
1126 if wo.Port == 0 {
1127 return nil
1128 }
1129 if !wsAllowedFIPS() {
1130 return fmt.Errorf("websocket: cannot be used in FIPS-140 mode when built with this Go version, use Go 1.26 or later")
1131 }
1132 // Enforce TLS... unless NoTLS is set to true.
1133 if wo.TLSConfig == nil && !wo.NoTLS {
1134 return errors.New("websocket requires TLS configuration")
1135 }
1136 // Make sure that allowed origins, if specified, can be parsed.
1137 for _, ao := range wo.AllowedOrigins {
1138 u, err := url.ParseRequestURI(ao)
1139 if err != nil {
1140 return fmt.Errorf("unable to parse allowed origin: %v", err)
1141 }
1142 if u.Scheme != "http" && u.Scheme != "https" {
1143 return fmt.Errorf("unable to parse allowed origin %q: allowed origins must be absolute URLs with http or https scheme", ao)
1144 }
1145 if u.Host == _EMPTY_ {
1146 return fmt.Errorf("unable to parse allowed origin %q: host is required", ao)
1147 }
1148 if _, _, err := wsGetHostAndPort(u.Scheme == "https", u.Host); err != nil {
1149 return fmt.Errorf("unable to parse allowed origin: %v", err)
1150 }
1151 }
1152 // If there is a NoAuthUser, we need to have Users defined and
1153 // the user to be present.
1154 if wo.NoAuthUser != _EMPTY_ {
1155 if err := validateNoAuthUser(o, wo.NoAuthUser); err != nil {
1156 return err
1157 }
1158 }
1159 // Token/Username not possible if there are users/nkeys
1160 if len(o.Users) > 0 || len(o.Nkeys) > 0 {
1161 if wo.Username != _EMPTY_ {
1162 return fmt.Errorf("websocket authentication username not compatible with presence of users/nkeys")
1163 }
1164 if wo.Token != _EMPTY_ {
1165 return fmt.Errorf("websocket authentication token not compatible with presence of users/nkeys")
1166 }
1167 }
1168 // Using JWT requires Trusted Keys
1169 if wo.JWTCookie != _EMPTY_ {
1170 if len(o.TrustedOperators) == 0 && len(o.TrustedKeys) == 0 {
1171 return fmt.Errorf("trusted operators or trusted keys configuration is required for JWT authentication via cookie %q", wo.JWTCookie)
1172 }
1173 }
1174 if err := validatePinnedCerts(wo.TLSPinnedCerts); err != nil {
1175 return fmt.Errorf("websocket: %v", err)
1176 }
1177
1178 // Check for invalid headers here.
1179 for key := range wo.Headers {
1180 k := strings.ToLower(key)
1181 switch k {
1182 case "host",
1183 "content-length",
1184 "connection",
1185 "upgrade",
1186 "nats-no-masking":
1187 return fmt.Errorf("websocket: invalid header %q not allowed", key)
1188 }
1189
1190 if strings.HasPrefix(k, "sec-websocket-") {
1191 return fmt.Errorf("websocket: invalid header %q, \"Sec-WebSocket-\" prefix not allowed", key)
1192 }
1193 }
1194
1195 return nil
1196 }
1197
1198 // Creates or updates the existing map
1199 func (s *Server) wsSetOriginOptions(o *WebsocketOpts) {
1200 ws := &s.websocket
1201 ws.mu.Lock()
1202 defer ws.mu.Unlock()
1203 // Copy over the option's same origin boolean
1204 ws.sameOrigin = o.SameOrigin
1205 // Reset the map. Will help for config reload if/when we support it.
1206 ws.allowedOrigins = nil
1207 if o.AllowedOrigins == nil {
1208 return
1209 }
1210 for _, ao := range o.AllowedOrigins {
1211 // We have previously checked (during options validation) that the urls
1212 // are parseable, but if we get an error, report and skip.
1213 u, err := url.ParseRequestURI(ao)
1214 if err != nil {
1215 s.Errorf("error parsing allowed origin: %v", err)
1216 continue
1217 }
1218 h, p, _ := wsGetHostAndPort(u.Scheme == "https", u.Host)
1219 if ws.allowedOrigins == nil {
1220 ws.allowedOrigins = make(map[string][]*allowedOrigin, len(o.AllowedOrigins))
1221 }
1222 ws.allowedOrigins[h] = append(ws.allowedOrigins[h], &allowedOrigin{scheme: u.Scheme, port: p})
1223 }
1224 }
1225
1226 // Calculate the raw headers for websocket upgrade response.
1227 func (s *Server) wsSetHeadersOptions(o *WebsocketOpts) {
1228 var sb strings.Builder
1229 for k, v := range o.Headers {
1230 sb.WriteString(k)
1231 sb.WriteString(": ")
1232 sb.WriteString(v)
1233 sb.WriteString(_CRLF_)
1234 }
1235 ws := &s.websocket
1236 ws.mu.Lock()
1237 defer ws.mu.Unlock()
1238 ws.rawHeaders = sb.String()
1239 }
1240
1241 // Given the websocket options, we check if any auth configuration
1242 // has been provided. If so, possibly create users/nkey users and
1243 // store them in s.websocket.users/nkeys.
1244 // Also update a boolean that indicates if auth is required for
1245 // websocket clients.
1246 // Server lock is held on entry.
1247 func (s *Server) wsConfigAuth(opts *WebsocketOpts) {
1248 ws := &s.websocket
1249 // If any of those is specified, we consider that there is an override.
1250 ws.authOverride = opts.Username != _EMPTY_ || opts.Token != _EMPTY_ || opts.NoAuthUser != _EMPTY_
1251 }
1252
1253 func (s *Server) startWebsocketServer() {
1254 if s.isShuttingDown() {
1255 return
1256 }
1257
1258 sopts := s.getOpts()
1259 o := &sopts.Websocket
1260
1261 s.wsSetOriginOptions(o)
1262 s.wsSetHeadersOptions(o)
1263
1264 var hl net.Listener
1265 var proto string
1266 var err error
1267
1268 port := o.Port
1269 if port == -1 {
1270 port = 0
1271 }
1272 hp := net.JoinHostPort(o.Host, strconv.Itoa(port))
1273
1274 // We are enforcing (when validating the options) the use of TLS, but the
1275 // code was originally supporting both modes. The reason for TLS only is
1276 // that we expect users to send JWTs with bearer tokens and we want to
1277 // avoid the possibility of it being "intercepted".
1278
1279 s.mu.Lock()
1280 // Do not check o.NoTLS here. If a TLS configuration is available, use it,
1281 // regardless of NoTLS. If we don't have a TLS config, it means that the
1282 // user has configured NoTLS because otherwise the server would have failed
1283 // to start due to options validation.
1284 var config *tls.Config
1285 if o.TLSConfig != nil {
1286 proto = wsSchemePrefixTLS
1287 config = o.TLSConfig.Clone()
1288 config.GetConfigForClient = s.wsGetTLSConfig
1289 } else {
1290 proto = wsSchemePrefix
1291 }
1292 hl, err = natsListen("tcp", hp)
1293 s.websocket.listenerErr = err
1294 if err != nil {
1295 s.mu.Unlock()
1296 s.Fatalf("Unable to listen for websocket connections: %v", err)
1297 return
1298 }
1299 if config != nil {
1300 hl = tls.NewListener(hl, config)
1301 }
1302 if port == 0 {
1303 o.Port = hl.Addr().(*net.TCPAddr).Port
1304 }
1305 s.Noticef("Listening for websocket clients on %s://%s:%d", proto, o.Host, o.Port)
1306 if proto == wsSchemePrefix {
1307 s.Warnf("Websocket not configured with TLS. DO NOT USE IN PRODUCTION!")
1308 }
1309
1310 // These 3 are immutable and will be accessed without lock by the client
1311 // when generating/sending the INFO protocols.
1312 s.websocket.tls = proto == wsSchemePrefixTLS
1313 s.websocket.host, s.websocket.port = o.Host, o.Port
1314
1315 // This will be updated when/if the cluster changes.
1316 s.websocket.connectURLs, err = s.getConnectURLs(o.Advertise, o.Host, o.Port)
1317 if err != nil {
1318 s.Fatalf("Unable to get websocket connect URLs: %v", err)
1319 hl.Close()
1320 s.mu.Unlock()
1321 return
1322 }
1323 hasLeaf := sopts.LeafNode.Port != 0
1324 mux := http.NewServeMux()
1325 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1326 res, err := s.wsUpgrade(w, r)
1327 if err != nil {
1328 s.Errorf(err.Error())
1329 return
1330 }
1331 switch res.kind {
1332 case CLIENT:
1333 s.createWSClient(res.conn, res.ws)
1334 case MQTT:
1335 s.createMQTTClient(res.conn, res.ws)
1336 case LEAF:
1337 if !hasLeaf {
1338 s.Errorf("Not configured to accept leaf node connections")
1339 // Silently close for now. If we want to send an error back, we would
1340 // need to create the leafnode client anyway, so that is handling websocket
1341 // frames, then send the error to the remote.
1342 res.conn.Close()
1343 return
1344 }
1345 s.createLeafNode(res.conn, nil, nil, res.ws)
1346 }
1347 })
1348 hs := &http.Server{
1349 Addr: hp,
1350 Handler: mux,
1351 ReadTimeout: o.HandshakeTimeout,
1352 ErrorLog: log.New(&captureHTTPServerLog{s, "websocket: "}, _EMPTY_, 0),
1353 }
1354 s.websocket.mu.Lock()
1355 s.websocket.server = hs
1356 s.websocket.listener = hl
1357 s.websocket.mu.Unlock()
1358 go func() {
1359 if err := hs.Serve(hl); err != http.ErrServerClosed {
1360 s.Fatalf("websocket listener error: %v", err)
1361 }
1362 if s.isLameDuckMode() {
1363 // Signal that we are not accepting new clients
1364 s.ldmCh <- true
1365 // Now wait for the Shutdown...
1366 <-s.quitCh
1367 return
1368 }
1369 s.done <- true
1370 }()
1371 s.mu.Unlock()
1372 }
1373
1374 // The TLS configuration is passed to the listener when the websocket
1375 // "server" is setup. That prevents TLS configuration updates on reload
1376 // from being used. By setting this function in tls.Config.GetConfigForClient
1377 // we instruct the TLS handshake to ask for the tls configuration to be
1378 // used for a specific client. We don't care which client, we always use
1379 // the same TLS configuration.
1380 func (s *Server) wsGetTLSConfig(_ *tls.ClientHelloInfo) (*tls.Config, error) {
1381 opts := s.getOpts()
1382 return opts.Websocket.TLSConfig, nil
1383 }
1384
1385 // This is similar to createClient() but has some modifications
1386 // specific to handle websocket clients.
1387 // The comments have been kept to minimum to reduce code size.
1388 // Check createClient() for more details.
1389 func (s *Server) createWSClient(conn net.Conn, ws *websocket) *client {
1390 opts := s.getOpts()
1391
1392 maxPay := int32(opts.MaxPayload)
1393 maxSubs := int32(opts.MaxSubs)
1394 if maxSubs == 0 {
1395 maxSubs = -1
1396 }
1397 now := time.Now().UTC()
1398
1399 c := &client{srv: s, nc: conn, opts: defaultOpts, mpay: maxPay, msubs: maxSubs, start: now, last: now, ws: ws}
1400
1401 c.registerWithAccount(s.globalAccount())
1402
1403 var info Info
1404 var authRequired bool
1405
1406 s.mu.Lock()
1407 info = s.copyInfo()
1408 // Check auth, override if applicable.
1409 if !info.AuthRequired {
1410 // Set info.AuthRequired since this is what is sent to the client.
1411 info.AuthRequired = s.websocket.authOverride
1412 }
1413 if s.nonceRequired() {
1414 var raw [nonceLen]byte
1415 nonce := raw[:]
1416 s.generateNonce(nonce)
1417 info.Nonce = string(nonce)
1418 }
1419 c.nonce = []byte(info.Nonce)
1420 authRequired = info.AuthRequired
1421
1422 s.totalClients++
1423 s.mu.Unlock()
1424
1425 c.mu.Lock()
1426 if authRequired {
1427 c.flags.set(expectConnect)
1428 }
1429 c.initClient()
1430 c.Debugf("Client connection created")
1431 c.sendProtoNow(c.generateClientInfoJSON(info, true))
1432 c.mu.Unlock()
1433
1434 s.mu.Lock()
1435 if !s.isRunning() || s.ldm {
1436 if s.isShuttingDown() {
1437 conn.Close()
1438 }
1439 s.mu.Unlock()
1440 return c
1441 }
1442
1443 if opts.MaxConn < 0 || (opts.MaxConn > 0 && len(s.clients) >= opts.MaxConn) {
1444 s.mu.Unlock()
1445 c.maxConnExceeded()
1446 return nil
1447 }
1448 s.clients[c.cid] = c
1449 s.mu.Unlock()
1450
1451 c.mu.Lock()
1452 // Websocket clients do TLS in the websocket http server.
1453 // So no TLS initiation here...
1454 if _, ok := conn.(*tls.Conn); ok {
1455 c.flags.set(handshakeComplete)
1456 }
1457
1458 if c.isClosed() {
1459 c.mu.Unlock()
1460 c.closeConnection(WriteError)
1461 return nil
1462 }
1463
1464 if authRequired {
1465 timeout := opts.AuthTimeout
1466 // Possibly override with Websocket specific value.
1467 if opts.Websocket.AuthTimeout != 0 {
1468 timeout = opts.Websocket.AuthTimeout
1469 }
1470 c.setAuthTimer(secondsToDuration(timeout))
1471 }
1472
1473 c.setPingTimer()
1474
1475 s.startGoRoutine(func() { c.readLoop(nil) })
1476 s.startGoRoutine(func() { c.writeLoop() })
1477
1478 c.mu.Unlock()
1479
1480 return c
1481 }
1482
1483 func (c *client) wsCollapsePtoNB() (net.Buffers, int64) {
1484 nb := c.out.nb
1485 var mfs int
1486 var usz int
1487 if c.ws.browser {
1488 mfs = wsFrameSizeForBrowsers
1489 }
1490 mask := c.ws.maskwrite
1491 // Start with possible already framed buffers (that we could have
1492 // got from partials or control messages such as ws pings or pongs).
1493 bufs := c.ws.frames
1494 compress := c.ws.compress
1495 if compress && len(nb) > 0 {
1496 // First, make sure we don't compress for very small cumulative buffers.
1497 for _, b := range nb {
1498 usz += len(b)
1499 }
1500 if usz <= wsCompressThreshold {
1501 compress = false
1502 if cp := c.ws.compressor; cp != nil {
1503 cp.Reset(nil)
1504 }
1505 }
1506 }
1507 if compress && len(nb) > 0 {
1508 // Overwrite mfs if this connection does not support fragmented compressed frames.
1509 if mfs > 0 && c.ws.nocompfrag {
1510 mfs = 0
1511 }
1512 seed := nbPoolGet(usz)
1513 buf := bytes.NewBuffer(seed)
1514 cp := c.ws.compressor
1515 if cp == nil {
1516 c.ws.compressor, _ = flate.NewWriter(buf, flate.BestSpeed)
1517 cp = c.ws.compressor
1518 } else {
1519 cp.Reset(buf)
1520 }
1521 var csz int
1522 for i, b := range nb {
1523 for len(b) > 0 {
1524 n, err := cp.Write(b)
1525 if err != nil {
1526 // Whatever this error is, it'll be handled by the cp.Flush()
1527 // call below, as the same error will be returned there.
1528 // Let the outer loop return all the buffers back to the pool
1529 // and fall through naturally.
1530 break
1531 }
1532 b = b[n:]
1533 }
1534 // Use original slice since capacity will change to zero
1535 // in the loop after consuming the buffer, which will make
1536 // nbPoolPut discard it.
1537 nbPoolPut(nb[i])
1538 }
1539 if err := cp.Flush(); err != nil {
1540 c.Errorf("Error during compression: %v", err)
1541 c.markConnAsClosed(WriteError)
1542 cp.Reset(nil)
1543 nbPoolPut(seed)
1544 return nil, 0
1545 }
1546
1547 // Recycle seed buffer already if capacity changed.
1548 b := buf.Bytes()
1549 if cap(b) > cap(seed) {
1550 nbPoolPut(seed)
1551 }
1552 p := b[:len(b)-4]
1553 if mfs > 0 && len(p) > mfs {
1554 for first, final := true, false; len(p) > 0; first = false {
1555 lp := len(p)
1556 if lp > mfs {
1557 lp = mfs
1558 } else {
1559 final = true
1560 }
1561 // Only the first frame should be marked as compressed, so pass
1562 // `first` for the compressed boolean.
1563 fh := nbPoolGet(wsMaxFrameHeaderSize)[:wsMaxFrameHeaderSize]
1564 n, key := wsFillFrameHeader(fh, mask, first, final, first, wsBinaryMessage, lp)
1565 if mask {
1566 wsMaskBuf(key, p[:lp])
1567 }
1568 bufs = append(bufs, fh[:n], append(nbPoolGet(lp), p[:lp]...))
1569 csz += n + lp
1570 p = p[lp:]
1571 }
1572 nbPoolPut(b)
1573 } else {
1574 ol := len(p)
1575 h, key := wsCreateFrameHeader(mask, true, wsBinaryMessage, ol)
1576 if mask {
1577 wsMaskBuf(key, p)
1578 }
1579 if ol > 0 {
1580 bufs = append(bufs, h, p)
1581 }
1582 csz = len(h) + ol
1583 }
1584 // Make sure that the compressor no longer holds a reference to
1585 // the bytes.Buffer, so that the underlying memory gets cleaned
1586 // up after flushOutbound/flushAndClose. For this to be safe, we
1587 // always cp.Reset(...) before reusing the compressor again.
1588 cp.Reset(nil)
1589 // Add to pb the compressed data size (including headers), but
1590 // remove the original uncompressed data size that was added
1591 // during the queueing.
1592 c.out.pb += int64(csz) - int64(usz)
1593 c.ws.fs += int64(csz)
1594 } else if len(nb) > 0 {
1595 var total int
1596 if mfs > 0 {
1597 // We are limiting the frame size.
1598 startFrame := func() int {
1599 bufs = append(bufs, nbPoolGet(wsMaxFrameHeaderSize))
1600 return len(bufs) - 1
1601 }
1602 endFrame := func(idx, size int) {
1603 bufs[idx] = bufs[idx][:wsMaxFrameHeaderSize]
1604 n, key := wsFillFrameHeader(bufs[idx], mask, wsFirstFrame, wsFinalFrame, wsUncompressedFrame, wsBinaryMessage, size)
1605 bufs[idx] = bufs[idx][:n]
1606 c.out.pb += int64(n)
1607 c.ws.fs += int64(n + size)
1608 if mask {
1609 wsMaskBufs(key, bufs[idx+1:])
1610 }
1611 }
1612
1613 fhIdx := startFrame()
1614 for i := 0; i < len(nb); i++ {
1615 b := nb[i]
1616 if total+len(b) <= mfs {
1617 buf := nbPoolGet(len(b))
1618 bufs = append(bufs, append(buf, b...))
1619 total += len(b)
1620 nbPoolPut(nb[i])
1621 continue
1622 }
1623 for len(b) > 0 {
1624 endStart := total != 0
1625 if endStart {
1626 endFrame(fhIdx, total)
1627 }
1628 total = len(b)
1629 if total >= mfs {
1630 total = mfs
1631 }
1632 if endStart {
1633 fhIdx = startFrame()
1634 }
1635 buf := nbPoolGet(total)
1636 bufs = append(bufs, append(buf, b[:total]...))
1637 b = b[total:]
1638 }
1639 nbPoolPut(nb[i]) // No longer needed as copied into smaller frames.
1640 }
1641 if total > 0 {
1642 endFrame(fhIdx, total)
1643 }
1644 } else {
1645 // If there is no limit on the frame size, create a single frame for
1646 // all pending buffers.
1647 for _, b := range nb {
1648 total += len(b)
1649 }
1650 wsfh, key := wsCreateFrameHeader(mask, false, wsBinaryMessage, total)
1651 c.out.pb += int64(len(wsfh))
1652 bufs = append(bufs, wsfh)
1653 idx := len(bufs)
1654 bufs = append(bufs, nb...)
1655 if mask {
1656 wsMaskBufs(key, bufs[idx:])
1657 }
1658 c.ws.fs += int64(len(wsfh) + total)
1659 }
1660 }
1661 if len(c.ws.closeMsg) > 0 {
1662 bufs = append(bufs, c.ws.closeMsg)
1663 c.ws.fs += int64(len(c.ws.closeMsg))
1664 c.ws.closeMsg = nil
1665 c.ws.compressor = nil
1666 }
1667 c.ws.frames = nil
1668 return bufs, c.ws.fs
1669 }
1670
1671 func isWSURL(u *url.URL) bool {
1672 return strings.HasPrefix(strings.ToLower(u.Scheme), wsSchemePrefix)
1673 }
1674
1675 func isWSSURL(u *url.URL) bool {
1676 return strings.HasPrefix(strings.ToLower(u.Scheme), wsSchemePrefixTLS)
1677 }