Debian Codegraph @

server/client.go

raw
1 // Copyright 2012-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 "crypto/sha256"
19 "crypto/tls"
20 "crypto/x509"
21 "encoding/hex"
22 "encoding/json"
23 "errors"
24 "fmt"
25 "io"
26 "math"
27 "math/rand"
28 "net"
29 "net/http"
30 "net/url"
31 "regexp"
32 "runtime"
33 "slices"
34 "strconv"
35 "strings"
36 "sync"
37 "sync/atomic"
38 "time"
39
40 "github.com/klauspost/compress/s2"
41 "github.com/nats-io/jwt/v2"
42 "github.com/nats-io/nats-server/v2/internal/fastrand"
43 )
44
45 // Type of client connection.
46 const (
47 // CLIENT is an end user.
48 CLIENT = iota
49 // ROUTER represents another server in the cluster.
50 ROUTER
51 // GATEWAY is a link between 2 clusters.
52 GATEWAY
53 // SYSTEM is an internal system client.
54 SYSTEM
55 // LEAF is for leaf node connections.
56 LEAF
57 // JETSTREAM is an internal jetstream client.
58 JETSTREAM
59 // ACCOUNT is for the internal client for accounts.
60 ACCOUNT
61 )
62
63 // Internal clients. kind should be SYSTEM, JETSTREAM or ACCOUNT
64 func isInternalClient(kind int) bool {
65 return kind == SYSTEM || kind == JETSTREAM || kind == ACCOUNT
66 }
67
68 // Extended type of a CLIENT connection. This is returned by c.clientType()
69 // and indicate what type of client connection we are dealing with.
70 // If invoked on a non CLIENT connection, NON_CLIENT type is returned.
71 const (
72 // If the connection is not a CLIENT connection.
73 NON_CLIENT = iota
74 // Regular NATS client.
75 NATS
76 // MQTT client.
77 MQTT
78 // Websocket client.
79 WS
80 )
81
82 const (
83 // ClientProtoZero is the original Client protocol from 2009.
84 // http://nats.io/documentation/internals/nats-protocol/
85 ClientProtoZero = iota
86 // ClientProtoInfo signals a client can receive more then the original INFO block.
87 // This can be used to update clients on other cluster members, etc.
88 ClientProtoInfo
89 )
90
91 const (
92 pingProto = "PING" + _CRLF_
93 pongProto = "PONG" + _CRLF_
94 errProto = "-ERR '%s'" + _CRLF_
95 okProto = "+OK" + _CRLF_
96 )
97
98 // TLS Hanshake client types
99 const (
100 tlsHandshakeLeaf = "leafnode"
101 tlsHandshakeMQTT = "mqtt"
102 )
103
104 const (
105 // Scratch buffer size for the processMsg() calls.
106 msgScratchSize = 1024
107 msgHeadProto = "RMSG "
108 msgHeadProtoLen = len(msgHeadProto)
109
110 // For controlling dynamic buffer sizes.
111 startBufSize = 512 // For INFO/CONNECT block
112 minBufSize = 64 // Smallest to shrink to for PING/PONG
113 maxBufSize = 65536 // 64k
114 shortsToShrink = 2 // Trigger to shrink dynamic buffers
115 maxFlushPending = 10 // Max fsps to have in order to wait for writeLoop
116 readLoopReport = 2 * time.Second
117
118 // Server should not send a PING (for RTT) before the first PONG has
119 // been sent to the client. However, in case some client libs don't
120 // send CONNECT+PING, cap the maximum time before server can send
121 // the RTT PING.
122 maxNoRTTPingBeforeFirstPong = 2 * time.Second
123
124 // For stalling fast producers
125 stallClientMinDuration = 2 * time.Millisecond
126 stallClientMaxDuration = 5 * time.Millisecond
127 stallTotalAllowed = 10 * time.Millisecond
128 )
129
130 var readLoopReportThreshold = readLoopReport
131
132 // Represent client booleans with a bitmask
133 type clientFlag uint16
134
135 const (
136 hdrLine = "NATS/1.0\r\n"
137 emptyHdrLine = "NATS/1.0\r\n\r\n"
138 )
139
140 // Some client state represented as flags
141 const (
142 connectReceived clientFlag = 1 << iota // The CONNECT proto has been received
143 infoReceived // The INFO protocol has been received
144 firstPongSent // The first PONG has been sent
145 handshakeComplete // For TLS clients, indicate that the handshake is complete
146 flushOutbound // Marks client as having a flushOutbound call in progress.
147 noReconnect // Indicate that on close, this connection should not attempt a reconnect
148 closeConnection // Marks that closeConnection has already been called.
149 connMarkedClosed // Marks that markConnAsClosed has already been called.
150 writeLoopStarted // Marks that the writeLoop has been started.
151 skipFlushOnClose // Marks that flushOutbound() should not be called on connection close.
152 expectConnect // Marks if this connection is expected to send a CONNECT
153 connectProcessFinished // Marks if this connection has finished the connect process.
154 compressionNegotiated // Marks if this connection has negotiated compression level with remote.
155 didTLSFirst // Marks if this connection requested and was accepted doing the TLS handshake first (prior to INFO).
156 isSlowConsumer // Marks connection as a slow consumer.
157 )
158
159 // set the flag (would be equivalent to set the boolean to true)
160 func (cf *clientFlag) set(c clientFlag) {
161 *cf |= c
162 }
163
164 // clear the flag (would be equivalent to set the boolean to false)
165 func (cf *clientFlag) clear(c clientFlag) {
166 *cf &= ^c
167 }
168
169 // isSet returns true if the flag is set, false otherwise
170 func (cf clientFlag) isSet(c clientFlag) bool {
171 return cf&c != 0
172 }
173
174 // setIfNotSet will set the flag `c` only if that flag was not already
175 // set and return true to indicate that the flag has been set. Returns
176 // false otherwise.
177 func (cf *clientFlag) setIfNotSet(c clientFlag) bool {
178 if *cf&c == 0 {
179 *cf |= c
180 return true
181 }
182 return false
183 }
184
185 // ClosedState is the reason client was closed. This will
186 // be passed into calls to clearConnection, but will only
187 // be stored in ConnInfo for monitoring.
188 type ClosedState int
189
190 const (
191 ClientClosed = ClosedState(iota + 1)
192 AuthenticationTimeout
193 AuthenticationViolation
194 TLSHandshakeError
195 SlowConsumerPendingBytes
196 SlowConsumerWriteDeadline
197 WriteError
198 ReadError
199 ParseError
200 StaleConnection
201 ProtocolViolation
202 BadClientProtocolVersion
203 WrongPort
204 MaxAccountConnectionsExceeded
205 MaxConnectionsExceeded
206 MaxPayloadExceeded
207 MaxControlLineExceeded
208 MaxSubscriptionsExceeded
209 DuplicateRoute
210 RouteRemoved
211 ServerShutdown
212 AuthenticationExpired
213 WrongGateway
214 MissingAccount
215 Revocation
216 InternalClient
217 MsgHeaderViolation
218 NoRespondersRequiresHeaders
219 ClusterNameConflict
220 DuplicateRemoteLeafnodeConnection
221 DuplicateClientID
222 DuplicateServerName
223 MinimumVersionRequired
224 ClusterNamesIdentical
225 Kicked
226 ProxyNotTrusted
227 ProxyRequired
228 )
229
230 // Some flags passed to processMsgResults
231 const pmrNoFlag int = 0
232 const (
233 pmrCollectQueueNames int = 1 << iota
234 pmrIgnoreEmptyQueueFilter
235 pmrAllowSendFromRouteToRoute
236 pmrMsgImportedFromService
237 )
238
239 type WriteTimeoutPolicy uint8
240
241 const (
242 WriteTimeoutPolicyDefault = iota
243 WriteTimeoutPolicyClose
244 WriteTimeoutPolicyRetry
245 )
246
247 // String returns a human-friendly value. Only used in varz.
248 func (p WriteTimeoutPolicy) String() string {
249 switch p {
250 case WriteTimeoutPolicyClose:
251 return "close"
252 case WriteTimeoutPolicyRetry:
253 return "retry"
254 default:
255 return _EMPTY_
256 }
257 }
258
259 type client struct {
260 // Here first because of use of atomics, and memory alignment.
261 stats
262 gwReplyMapping
263 kind int
264 srv *Server
265 acc *Account
266 perms *permissions
267 in readCache
268 parseState
269 opts ClientOpts
270 rrTracking *rrTracking
271 mpay int32
272 msubs int32
273 mcl int32
274 mu sync.RWMutex
275 cid uint64
276 start time.Time
277 nonce []byte
278 pubKey string
279 nc net.Conn
280 ncs atomic.Value
281 ncsAcc atomic.Value
282 ncsUser atomic.Value
283 out outbound
284 user *NkeyUser
285 host string
286 port uint16
287 subs map[string]*subscription
288 replies map[string]*resp
289 mperms *msgDeny
290 darray []*subscription // Parsed subscribe deny entries used to build the delivery-time filter.
291 pcd map[*client]struct{}
292 atmr *time.Timer
293 expires time.Time
294 ping pinfo
295 msgb [msgScratchSize]byte
296 last time.Time
297 lastIn time.Time
298 proxyKey string
299
300 repliesSincePrune uint16
301 lastReplyPrune time.Time
302
303 headers bool
304
305 rtt time.Duration
306 rttStart time.Time
307
308 route *route
309 gw *gateway
310 leaf *leaf
311 ws *websocket
312 mqtt *mqtt
313
314 flags clientFlag // Compact booleans into a single field. Size will be increased when needed.
315
316 rref byte
317
318 trace bool
319 echo bool
320 noIcb bool
321 iproc bool // In-Process connection, set at creation and immutable.
322
323 tags jwt.TagList
324 nameTag string
325
326 tlsTo *time.Timer
327
328 // Authentication error override. This is used because the authentication
329 // stack is simply returning a boolean, and the only authentication error
330 // reported is the generic `ErrAuthentication`. In the authentication code,
331 // if we want to report a different error, we can now set this field
332 // and `authViolation()` will use that one.
333 authErr error
334 }
335
336 type rrTracking struct {
337 rmap map[string]*remoteLatency
338 ptmr *time.Timer
339 lrt time.Duration
340 }
341
342 // Struct for PING initiation from the server.
343 type pinfo struct {
344 tmr *time.Timer
345 out int
346 }
347
348 // outbound holds pending data for a socket.
349 type outbound struct {
350 nb net.Buffers // Pending buffers for send, each has fixed capacity as per nbPool below.
351 wnb net.Buffers // Working copy of "nb", reused on each flushOutbound call, partial writes may leave entries here for next iteration.
352 pb int64 // Total pending/queued bytes.
353 fsp int32 // Flush signals that are pending per producer from readLoop's pcd.
354 wtp WriteTimeoutPolicy // What do we do on a write timeout?
355 sg *sync.Cond // To signal writeLoop that there is data to flush.
356 wdl time.Duration // Snapshot of write deadline.
357 mp int64 // Snapshot of max pending for client.
358 lft time.Duration // Last flush time for Write.
359 stc chan struct{} // Stall chan we create to slow down producers on overrun, e.g. fan-in.
360 cw *s2.Writer
361 }
362
363 const nbMaxVectorSize = 1024 // == IOV_MAX on Linux/Darwin and most other Unices (except Solaris/AIX)
364
365 const nbPoolSizeSmall = 512 // Underlying array size of small buffer
366 const nbPoolSizeMedium = 4096 // Underlying array size of medium buffer
367 const nbPoolSizeLarge = 65536 // Underlying array size of large buffer
368
369 var nbPoolSmall = &sync.Pool{
370 New: func() any {
371 b := [nbPoolSizeSmall]byte{}
372 return &b
373 },
374 }
375
376 var nbPoolMedium = &sync.Pool{
377 New: func() any {
378 b := [nbPoolSizeMedium]byte{}
379 return &b
380 },
381 }
382
383 var nbPoolLarge = &sync.Pool{
384 New: func() any {
385 b := [nbPoolSizeLarge]byte{}
386 return &b
387 },
388 }
389
390 // nbPoolGet returns a frame that is a best-effort match for the given size.
391 // Once a pooled frame is no longer needed, it should be recycled by passing
392 // it to nbPoolPut.
393 func nbPoolGet(sz int) []byte {
394 switch {
395 case sz <= nbPoolSizeSmall:
396 return nbPoolSmall.Get().(*[nbPoolSizeSmall]byte)[:0]
397 case sz <= nbPoolSizeMedium:
398 return nbPoolMedium.Get().(*[nbPoolSizeMedium]byte)[:0]
399 default:
400 return nbPoolLarge.Get().(*[nbPoolSizeLarge]byte)[:0]
401 }
402 }
403
404 // nbPoolPut recycles a frame that was retrieved from nbPoolGet. It is not
405 // safe to return multiple slices referring to chunks of the same underlying
406 // array as this may create overlaps when the buffers are returned to their
407 // original size, resulting in race conditions.
408 func nbPoolPut(b []byte) {
409 switch cap(b) {
410 case nbPoolSizeSmall:
411 b := (*[nbPoolSizeSmall]byte)(b[0:nbPoolSizeSmall])
412 nbPoolSmall.Put(b)
413 case nbPoolSizeMedium:
414 b := (*[nbPoolSizeMedium]byte)(b[0:nbPoolSizeMedium])
415 nbPoolMedium.Put(b)
416 case nbPoolSizeLarge:
417 b := (*[nbPoolSizeLarge]byte)(b[0:nbPoolSizeLarge])
418 nbPoolLarge.Put(b)
419 default:
420 // Ignore frames that are the wrong size, this might happen
421 // with WebSocket/MQTT messages as they are framed
422 }
423 }
424
425 type perm struct {
426 allow *Sublist
427 deny *Sublist
428 }
429
430 type permissions struct {
431 // Have these 2 first for memory alignment due to the use of atomic.
432 pcsz int32
433 prun int32
434 sub perm
435 pub perm
436 resp *ResponsePermission
437 pcache sync.Map
438 }
439
440 // This is used to dynamically track responses and reply subjects
441 // for dynamic permissioning.
442 type resp struct {
443 t time.Time
444 n int
445 }
446
447 // msgDeny is used when a user permission for subscriptions has a deny
448 // clause but a subscription could be made that is of broader scope.
449 // e.g. deny = "foo", but user subscribes to "*". That subscription should
450 // succeed but no message sent on foo should be delivered.
451 type msgDeny struct {
452 deny *Sublist
453 dcache map[msgDenyKey]bool
454 }
455
456 type msgDenyKey struct {
457 subject string
458 queue string
459 }
460
461 // routeTarget collects information regarding routes and queue groups for
462 // sending information to a remote.
463 type routeTarget struct {
464 sub *subscription
465 qs []byte
466 qsubs []*subscription
467 _qs [32]byte
468 _qsubs [4]*subscription
469 }
470
471 const (
472 maxResultCacheSize = 512
473 maxDenyPermCacheSize = 256
474 maxPermCacheSize = 128
475 pruneSize = 32
476 routeTargetInit = 8
477 replyPermLimit = 4096
478 replyPruneTime = time.Second
479 )
480
481 // Represent read cache booleans with a bitmask
482 type readCacheFlag uint16
483
484 const (
485 hasMappings readCacheFlag = 1 << iota // For account subject mappings.
486 switchToCompression readCacheFlag = 1 << 1
487 )
488
489 const sysGroup = "_sys_"
490
491 // Used in readloop to cache hot subject lookups and group statistics.
492 type readCache struct {
493 // These are for clients who are bound to a single account.
494 genid uint64
495 results map[string]*SublistResult
496
497 // This is for routes and gateways to have their own L1 as well that is account aware.
498 pacache map[string]*perAccountCache
499
500 // This is for when we deliver messages across a route. We use this structure
501 // to make sure to only send one message and properly scope to queues as needed.
502 rts []routeTarget
503
504 // These are all temporary totals for an invocation of a read in readloop.
505 msgs int32
506 bytes int32
507 subs int32
508
509 rsz int32 // Read buffer size
510 srs int32 // Short reads, used for dynamic buffer resizing.
511
512 // These are for readcache flags to avoid locks.
513 flags readCacheFlag
514
515 // Capture the time we started processing our readLoop.
516 start time.Time
517
518 // Total time stalled so far for readLoop processing.
519 tst time.Duration
520 }
521
522 // set the flag (would be equivalent to set the boolean to true)
523 func (rcf *readCacheFlag) set(c readCacheFlag) {
524 *rcf |= c
525 }
526
527 // clear the flag (would be equivalent to set the boolean to false)
528 func (rcf *readCacheFlag) clear(c readCacheFlag) {
529 *rcf &= ^c
530 }
531
532 // isSet returns true if the flag is set, false otherwise
533 func (rcf readCacheFlag) isSet(c readCacheFlag) bool {
534 return rcf&c != 0
535 }
536
537 const (
538 defaultMaxPerAccountCacheSize = 8192
539 defaultClosedSubsCheckInterval = 5 * time.Minute
540 )
541
542 var (
543 maxPerAccountCacheSize = defaultMaxPerAccountCacheSize
544 closedSubsCheckInterval = defaultClosedSubsCheckInterval
545 )
546
547 // perAccountCache is for L1 semantics for inbound messages from a route or gateway to mimic the performance of clients.
548 type perAccountCache struct {
549 acc *Account
550 results *SublistResult
551 genid uint64
552 }
553
554 func (c *client) String() (id string) {
555 loaded := c.ncs.Load()
556 if loaded != nil {
557 return loaded.(string)
558 }
559
560 return _EMPTY_
561 }
562
563 // GetNonce returns the nonce that was presented to the user on connection
564 func (c *client) GetNonce() []byte {
565 c.mu.Lock()
566 defer c.mu.Unlock()
567
568 return c.nonce
569 }
570
571 // GetID returns the client ID
572 func (c *client) GetID() uint64 {
573 c.mu.Lock()
574 defer c.mu.Unlock()
575 return c.cid
576 }
577
578 // GetName returns the application supplied name for the connection.
579 func (c *client) GetName() string {
580 c.mu.Lock()
581 name := c.opts.Name
582 c.mu.Unlock()
583 return name
584 }
585
586 // GetOpts returns the client options provided by the application.
587 func (c *client) GetOpts() *ClientOpts {
588 return &c.opts
589 }
590
591 // GetTLSConnectionState returns the TLS ConnectionState if TLS is enabled, nil
592 // otherwise. Implements the ClientAuth interface.
593 func (c *client) GetTLSConnectionState() *tls.ConnectionState {
594 c.mu.Lock()
595 defer c.mu.Unlock()
596 if c.nc == nil {
597 return nil
598 }
599 tc, ok := c.nc.(*tls.Conn)
600 if !ok {
601 return nil
602 }
603 state := tc.ConnectionState()
604 return &state
605 }
606
607 // For CLIENT connections, this function returns the client type, that is,
608 // NATS (for regular clients), MQTT or WS for websocket.
609 // If this is invoked for a non CLIENT connection, NON_CLIENT is returned.
610 //
611 // This function does not lock the client and accesses fields that are supposed
612 // to be immutable and therefore it can be invoked outside of the client's lock.
613 func (c *client) clientType() int {
614 switch c.kind {
615 case CLIENT:
616 if c.isMqtt() {
617 return MQTT
618 } else if c.isWebsocket() {
619 return WS
620 }
621 return NATS
622 default:
623 return NON_CLIENT
624 }
625 }
626
627 var clientTypeStringMap = map[int]string{
628 NON_CLIENT: _EMPTY_,
629 NATS: "nats",
630 WS: "websocket",
631 MQTT: "mqtt",
632 }
633
634 func (c *client) clientTypeString() string {
635 if typeStringVal, ok := clientTypeStringMap[c.clientType()]; ok {
636 return typeStringVal
637 }
638 return _EMPTY_
639 }
640
641 // This is the main subscription struct that indicates
642 // interest in published messages.
643 // FIXME(dlc) - This is getting bloated for normal subs, need
644 // to optionally have an opts section for non-normal stuff.
645 type subscription struct {
646 client *client
647 im *streamImport // This is for import stream support.
648 rsi bool
649 si bool
650 shadow []*subscription // This is to track shadowed accounts.
651 icb msgHandler
652 subject []byte
653 queue []byte
654 sid []byte
655 origin []byte
656 nm int64
657 max int64
658 qw int32
659 closed int32
660 mqtt *mqttSub
661 }
662
663 // Indicate that this subscription is closed.
664 // This is used in pruning of route and gateway cache items.
665 func (s *subscription) close() {
666 atomic.StoreInt32(&s.closed, 1)
667 }
668
669 // Return true if this subscription was unsubscribed
670 // or its connection has been closed.
671 func (s *subscription) isClosed() bool {
672 return atomic.LoadInt32(&s.closed) == 1
673 }
674
675 type ClientOpts struct {
676 Echo bool `json:"echo"`
677 Verbose bool `json:"verbose"`
678 Pedantic bool `json:"pedantic"`
679 TLSRequired bool `json:"tls_required"`
680 Nkey string `json:"nkey,omitempty"`
681 JWT string `json:"jwt,omitempty"`
682 Sig string `json:"sig,omitempty"`
683 Token string `json:"auth_token,omitempty"`
684 Username string `json:"user,omitempty"`
685 Password string `json:"pass,omitempty"`
686 Name string `json:"name"`
687 Lang string `json:"lang"`
688 Version string `json:"version"`
689 Protocol int `json:"protocol"`
690 Account string `json:"account,omitempty"`
691 AccountNew bool `json:"new_account,omitempty"`
692 Headers bool `json:"headers,omitempty"`
693 NoResponders bool `json:"no_responders,omitempty"`
694
695 // Routes and Leafnodes only
696 Import *SubjectPermission `json:"import,omitempty"`
697 Export *SubjectPermission `json:"export,omitempty"`
698
699 // Leafnodes
700 RemoteAccount string `json:"remote_account,omitempty"`
701
702 // Proxy would include its own nonce signature.
703 ProxySig string `json:"proxy_sig,omitempty"`
704 }
705
706 var defaultOpts = ClientOpts{Verbose: true, Pedantic: true, Echo: true}
707 var internalOpts = ClientOpts{Verbose: false, Pedantic: false, Echo: false}
708
709 func (c *client) setTraceLevel() {
710 if c.kind == SYSTEM && !(atomic.LoadInt32(&c.srv.logging.traceSysAcc) != 0) {
711 c.trace = false
712 } else {
713 c.trace = (atomic.LoadInt32(&c.srv.logging.trace) != 0)
714 }
715 }
716
717 // Lock should be held
718 func (c *client) initClient() {
719 s := c.srv
720 c.cid = atomic.AddUint64(&s.gcid, 1)
721
722 // Outbound data structure setup
723 c.out.sg = sync.NewCond(&(c.mu))
724 opts := s.getOpts()
725 // Snapshots to avoid mutex access in fast paths.
726 c.out.wdl = opts.WriteDeadline
727 switch {
728 case c.kind == ROUTER && opts.Cluster.WriteDeadline > 0:
729 c.out.wdl = opts.Cluster.WriteDeadline
730 case c.kind == GATEWAY && opts.Gateway.WriteDeadline > 0:
731 c.out.wdl = opts.Gateway.WriteDeadline
732 case c.kind == LEAF && opts.LeafNode.WriteDeadline > 0:
733 c.out.wdl = opts.LeafNode.WriteDeadline
734 }
735 switch c.kind {
736 case ROUTER:
737 if c.out.wtp = opts.Cluster.WriteTimeout; c.out.wtp == WriteTimeoutPolicyDefault {
738 c.out.wtp = WriteTimeoutPolicyRetry
739 }
740 case LEAF:
741 if c.out.wtp = opts.LeafNode.WriteTimeout; c.out.wtp == WriteTimeoutPolicyDefault {
742 c.out.wtp = WriteTimeoutPolicyRetry
743 }
744 case GATEWAY:
745 if c.out.wtp = opts.Gateway.WriteTimeout; c.out.wtp == WriteTimeoutPolicyDefault {
746 c.out.wtp = WriteTimeoutPolicyRetry
747 }
748 default:
749 if c.out.wtp = opts.WriteTimeout; c.out.wtp == WriteTimeoutPolicyDefault {
750 c.out.wtp = WriteTimeoutPolicyClose
751 }
752 }
753 c.out.mp = opts.MaxPending
754 // Snapshot max control line since currently can not be changed on reload and we
755 // were checking it on each call to parse. If this changes and we allow MaxControlLine
756 // to be reloaded without restart, this code will need to change.
757 c.mcl = int32(opts.MaxControlLine)
758 if c.mcl == 0 {
759 c.mcl = MAX_CONTROL_LINE_SIZE
760 }
761
762 c.subs = make(map[string]*subscription)
763 c.echo = true
764
765 c.setTraceLevel()
766
767 // This is a scratch buffer used for processMsg()
768 // The msg header starts with "RMSG ", which can be used
769 // for both local and routes.
770 // in bytes that is [82 77 83 71 32].
771 c.msgb = [msgScratchSize]byte{82, 77, 83, 71, 32}
772
773 // This is to track pending clients that have data to be flushed
774 // after we process inbound msgs from our own connection.
775 c.pcd = make(map[*client]struct{})
776
777 // snapshot the string version of the connection
778 var conn string
779 if c.nc != nil {
780 if addr := c.nc.RemoteAddr(); addr != nil {
781 if conn = addr.String(); conn != _EMPTY_ {
782 host, port, _ := net.SplitHostPort(conn)
783 iPort, _ := strconv.ParseUint(port, 10, 16)
784 c.host, c.port = host, uint16(iPort)
785 if c.isWebsocket() && c.ws.clientIP != _EMPTY_ {
786 cip := c.ws.clientIP
787 // Surround IPv6 addresses with square brackets, as
788 // net.JoinHostPort would do...
789 if strings.Contains(cip, ":") {
790 cip = "[" + cip + "]"
791 }
792 conn = fmt.Sprintf("%s/%s", cip, conn)
793 }
794 // Now that we have extracted host and port, escape
795 // the string because it is going to be used in Sprintf
796 conn = strings.ReplaceAll(conn, "%", "%%")
797 }
798 }
799 }
800
801 switch c.kind {
802 case CLIENT:
803 switch c.clientType() {
804 case NATS:
805 c.ncs.Store(fmt.Sprintf("%s - cid:%d", conn, c.cid))
806 case WS:
807 c.ncs.Store(fmt.Sprintf("%s - wid:%d", conn, c.cid))
808 case MQTT:
809 var ws string
810 if c.isWebsocket() {
811 ws = "_ws"
812 }
813 c.ncs.Store(fmt.Sprintf("%s - mid%s:%d", conn, ws, c.cid))
814 }
815 case ROUTER:
816 c.ncs.Store(fmt.Sprintf("%s - rid:%d", conn, c.cid))
817 case GATEWAY:
818 c.ncs.Store(fmt.Sprintf("%s - gid:%d", conn, c.cid))
819 case LEAF:
820 var ws string
821 if c.isWebsocket() {
822 ws = "_ws"
823 }
824 c.ncs.Store(fmt.Sprintf("%s - lid%s:%d", conn, ws, c.cid))
825 case SYSTEM:
826 c.ncs.Store("SYSTEM")
827 case JETSTREAM:
828 c.ncs.Store("JETSTREAM")
829 case ACCOUNT:
830 c.ncs.Store("ACCOUNT")
831 }
832 }
833
834 // RemoteAddress expose the Address of the client connection,
835 // nil when not connected or unknown
836 func (c *client) RemoteAddress() net.Addr {
837 c.mu.Lock()
838 defer c.mu.Unlock()
839
840 if c.nc == nil {
841 return nil
842 }
843
844 return c.nc.RemoteAddr()
845 }
846
847 // Helper function to report errors.
848 func (c *client) reportErrRegisterAccount(acc *Account, err error) {
849 if err == ErrTooManyAccountConnections {
850 c.maxAccountConnExceeded()
851 return
852 }
853 c.Errorf("Problem registering with account %q: %s", acc.Name, err)
854 c.sendErr("Failed Account Registration")
855 }
856
857 // Kind returns the client kind and will be one of the defined constants like CLIENT, ROUTER, GATEWAY, LEAF
858 func (c *client) Kind() int {
859 c.mu.Lock()
860 kind := c.kind
861 c.mu.Unlock()
862
863 return kind
864 }
865
866 // registerWithAccount will register the given user with a specific
867 // account. This will change the subject namespace.
868 func (c *client) registerWithAccount(acc *Account) error {
869 if acc == nil {
870 return ErrBadAccount
871 }
872 acc.mu.RLock()
873 bad := acc.sl == nil
874 acc.mu.RUnlock()
875 if bad {
876 return ErrBadAccount
877 }
878 // If we were previously registered, usually to $G, do accounting here to remove.
879 if c.acc != nil {
880 if prev := c.acc.removeClient(c); prev == 1 && c.srv != nil {
881 c.srv.decActiveAccounts()
882 }
883 }
884
885 c.mu.Lock()
886 // This check does not apply to SYSTEM or JETSTREAM or ACCOUNT clients (because they don't have a `nc`...)
887 if c.isClosed() && !isInternalClient(c.kind) {
888 c.mu.Unlock()
889 return ErrConnectionClosed
890 }
891 kind := c.kind
892 srv := c.srv
893 c.acc = acc
894 c.applyAccountLimits()
895 c.mu.Unlock()
896
897 // Check if we have a max connections violation
898 if kind == CLIENT && acc.MaxTotalConnectionsReached() {
899 return ErrTooManyAccountConnections
900 } else if kind == LEAF {
901 // Check if we are already connected to this cluster.
902 if rc := c.remoteCluster(); rc != _EMPTY_ && acc.hasLeafNodeCluster(rc) {
903 return ErrLeafNodeLoop
904 }
905 if acc.MaxTotalLeafNodesReached() {
906 return ErrTooManyAccountConnections
907 }
908 }
909
910 // Add in new one.
911 if prev := acc.addClient(c); prev == 0 && srv != nil {
912 srv.incActiveAccounts()
913 }
914
915 return nil
916 }
917
918 // Helper to determine if we have met or exceeded max subs.
919 func (c *client) subsAtLimit() bool {
920 return c.msubs != jwt.NoLimit && len(c.subs) >= int(c.msubs)
921 }
922
923 func minLimit(value *int32, limit int32) bool {
924 v := atomic.LoadInt32(value)
925 if v != jwt.NoLimit {
926 if limit != jwt.NoLimit {
927 if limit < v {
928 atomic.StoreInt32(value, limit)
929 return true
930 }
931 }
932 } else if limit != jwt.NoLimit {
933 atomic.StoreInt32(value, limit)
934 return true
935 }
936 return false
937 }
938
939 // Apply account limits
940 // Lock is held on entry.
941 // FIXME(dlc) - Should server be able to override here?
942 func (c *client) applyAccountLimits() {
943 if c.acc == nil || (c.kind != CLIENT && c.kind != LEAF) {
944 return
945 }
946 atomic.StoreInt32(&c.mpay, jwt.NoLimit)
947 c.msubs = jwt.NoLimit
948 if c.opts.JWT != _EMPTY_ { // user jwt implies account
949 if uc, _ := jwt.DecodeUserClaims(c.opts.JWT); uc != nil {
950 atomic.StoreInt32(&c.mpay, clampInt64ToInt32(uc.Limits.Payload))
951 c.msubs = clampInt64ToInt32(uc.Limits.Subs)
952 if uc.IssuerAccount != _EMPTY_ && uc.IssuerAccount != uc.Issuer {
953 if scope, ok := c.acc.hasIssuer(uc.Issuer); ok {
954 if userScope, ok := scope.(*jwt.UserScope); ok {
955 // if signing key disappeared or changed and we don't get here, the client will be disconnected
956 atomic.StoreInt32(&c.mpay, clampInt64ToInt32(userScope.Template.Limits.Payload))
957 c.msubs = clampInt64ToInt32(userScope.Template.Limits.Subs)
958 }
959 }
960 }
961 }
962 }
963
964 c.acc.mu.RLock()
965 minLimit(&c.mpay, c.acc.mpay)
966 minLimit(&c.msubs, c.acc.msubs)
967 c.acc.mu.RUnlock()
968
969 s := c.srv
970 opts := s.getOpts()
971 mPay := opts.MaxPayload
972 // options encode unlimited differently
973 if mPay == 0 {
974 mPay = jwt.NoLimit
975 }
976 mSubs := int32(opts.MaxSubs)
977 if mSubs == 0 {
978 mSubs = jwt.NoLimit
979 }
980 wasUnlimited := atomic.LoadInt32(&c.mpay) == jwt.NoLimit
981 if minLimit(&c.mpay, mPay) && !wasUnlimited {
982 c.Debugf("Max Payload set to %d from server overrides account or user config", opts.MaxPayload)
983 }
984 wasUnlimited = c.msubs == jwt.NoLimit
985 if minLimit(&c.msubs, mSubs) && !wasUnlimited {
986 c.Debugf("Max Subscriptions set to %d from server overrides account or user config", opts.MaxSubs)
987 }
988 if c.subsAtLimit() {
989 go func() {
990 c.maxSubsExceeded()
991 time.Sleep(20 * time.Millisecond)
992 c.closeConnection(MaxSubscriptionsExceeded)
993 }()
994 }
995 }
996
997 // RegisterUser allows auth to call back into a new client
998 // with the authenticated user. This is used to map
999 // any permissions into the client and setup accounts.
1000 func (c *client) RegisterUser(user *User) {
1001 // Register with proper account and sublist.
1002 if user.Account != nil {
1003 if err := c.registerWithAccount(user.Account); err != nil {
1004 c.reportErrRegisterAccount(user.Account, err)
1005 return
1006 }
1007 }
1008
1009 c.mu.Lock()
1010
1011 // Assign permissions.
1012 if user.Permissions == nil {
1013 // Reset perms to nil in case client previously had them.
1014 c.perms = nil
1015 c.mperms = nil
1016 c.darray = nil
1017 } else {
1018 c.setPermissions(user.Permissions)
1019 }
1020
1021 // allows custom authenticators to set a username to be reported in
1022 // server events and more
1023 if user.Username != _EMPTY_ {
1024 c.opts.Username = user.Username
1025 }
1026
1027 // if a deadline time stamp is set we start a timer to disconnect the user at that time
1028 if !user.ConnectionDeadline.IsZero() {
1029 c.setExpirationTimerUnlocked(time.Until(user.ConnectionDeadline))
1030 }
1031
1032 c.mu.Unlock()
1033 }
1034
1035 // RegisterNkeyUser allows auth to call back into a new nkey
1036 // client with the authenticated user. This is used to map
1037 // any permissions into the client and setup accounts.
1038 func (c *client) RegisterNkeyUser(user *NkeyUser) error {
1039 // Register with proper account and sublist.
1040 if user.Account != nil {
1041 if err := c.registerWithAccount(user.Account); err != nil {
1042 c.reportErrRegisterAccount(user.Account, err)
1043 return err
1044 }
1045 }
1046
1047 c.mu.Lock()
1048 c.user = user
1049 // Assign permissions.
1050 if user.Permissions == nil {
1051 // Reset perms to nil in case client previously had them.
1052 c.perms = nil
1053 c.mperms = nil
1054 c.darray = nil
1055 } else {
1056 c.setPermissions(user.Permissions)
1057 }
1058 c.mu.Unlock()
1059 return nil
1060 }
1061
1062 func (c *client) updateDefaultPermissions(perms *Permissions) bool {
1063 c.mu.Lock()
1064 defer c.mu.Unlock()
1065 if c.user == nil || !c.user.defaultPerms {
1066 return false
1067 }
1068 if perms == nil {
1069 c.user.Permissions = nil
1070 c.perms = nil
1071 c.mperms = nil
1072 c.darray = nil
1073 return true
1074 }
1075 c.user.Permissions = perms.clone()
1076 c.setPermissions(c.user.Permissions)
1077 return true
1078 }
1079
1080 func splitSubjectQueue(sq string) ([]byte, []byte, error) {
1081 vals := strings.Fields(strings.TrimSpace(sq))
1082 if len(vals) == 0 {
1083 return nil, nil, fmt.Errorf("invalid subject-queue %q", sq)
1084 }
1085 s := []byte(vals[0])
1086 var q []byte
1087 if len(vals) == 2 {
1088 q = []byte(vals[1])
1089 } else if len(vals) > 2 {
1090 return nil, nil, fmt.Errorf("invalid subject-queue %q", sq)
1091 }
1092 if !IsValidSubject(vals[0]) || (len(q) > 0 && !IsValidSubject(vals[1])) {
1093 return nil, nil, fmt.Errorf("invalid subject-queue %q", sq)
1094 }
1095 return s, q, nil
1096 }
1097
1098 // Initializes client.perms structure.
1099 // Lock is held on entry.
1100 func (c *client) setPermissions(perms *Permissions) {
1101 if perms == nil {
1102 return
1103 }
1104 c.perms = &permissions{}
1105 c.mperms = nil
1106 c.darray = nil
1107 slcache := c.srv != nil && !c.srv.getOpts().NoSublistCache
1108
1109 // Loop over publish permissions
1110 if perms.Publish != nil {
1111 if perms.Publish.Allow != nil {
1112 c.perms.pub.allow = NewSublist(slcache)
1113 }
1114 for _, pubSubject := range perms.Publish.Allow {
1115 if !IsValidSubject(pubSubject) {
1116 c.Errorf("invalid publish subject %q", pubSubject)
1117 continue
1118 }
1119 sub := &subscription{subject: []byte(pubSubject)}
1120 if err := c.perms.pub.allow.Insert(sub); err != nil {
1121 c.Errorf("invalid publish subject %q", pubSubject)
1122 }
1123 }
1124 if len(perms.Publish.Deny) > 0 {
1125 c.perms.pub.deny = NewSublist(slcache)
1126 }
1127 for _, pubSubject := range perms.Publish.Deny {
1128 subject := []byte(pubSubject)
1129 if !IsValidSubject(pubSubject) {
1130 var err error
1131 subject, _, err = splitSubjectQueue(pubSubject)
1132 if err != nil {
1133 c.Errorf("invalid publish deny subject %q", pubSubject)
1134 continue
1135 }
1136 // Queue qualifiers have no meaning for publish permissions. If
1137 // one reaches this defensive path, retain the deny's subject
1138 // scope instead of silently creating an unreachable trie node.
1139 c.Errorf("queue qualifier is not valid for publish deny subject %q", pubSubject)
1140 }
1141 if err := c.perms.pub.deny.Insert(&subscription{subject: subject}); err != nil {
1142 c.Errorf("invalid publish deny subject %q", pubSubject)
1143 }
1144 }
1145 }
1146
1147 // Check if we are allowed to send responses.
1148 if perms.Response != nil {
1149 rp := *perms.Response
1150 c.perms.resp = &rp
1151 c.replies = make(map[string]*resp)
1152 }
1153
1154 // Loop over subscribe permissions
1155 if perms.Subscribe != nil {
1156 var err error
1157 if len(perms.Subscribe.Allow) > 0 {
1158 c.perms.sub.allow = NewSublistNoCache()
1159 }
1160 for _, subSubject := range perms.Subscribe.Allow {
1161 sub := &subscription{}
1162 sub.subject, sub.queue, err = splitSubjectQueue(subSubject)
1163 if err != nil {
1164 c.Errorf("%s", err.Error())
1165 continue
1166 }
1167 if err := c.perms.sub.allow.Insert(sub); err != nil {
1168 c.Errorf("invalid subscribe allow subject %q", subSubject)
1169 }
1170 }
1171 if len(perms.Subscribe.Deny) > 0 {
1172 c.perms.sub.deny = NewSublistNoCache()
1173 }
1174 for _, subSubject := range perms.Subscribe.Deny {
1175 sub := &subscription{}
1176 sub.subject, sub.queue, err = splitSubjectQueue(subSubject)
1177 if err != nil {
1178 c.Errorf("%s", err.Error())
1179 continue
1180 }
1181 if err := c.perms.sub.deny.Insert(sub); err != nil {
1182 c.Errorf("invalid subscribe deny subject %q", subSubject)
1183 continue
1184 }
1185 // Retain the parsed representation for delivery-time filtering.
1186 c.darray = append(c.darray, sub)
1187 }
1188 }
1189
1190 // If we are a leafnode and we are the hub copy the extracted perms
1191 // to resend back to soliciting server. These are reversed from the
1192 // way routes interpret them since this is how the soliciting server
1193 // will receive these back in an update INFO.
1194 if c.isHubLeafNode() {
1195 c.opts.Import = perms.Subscribe
1196 c.opts.Export = perms.Publish
1197 }
1198 }
1199
1200 // Build public permissions from internal ones.
1201 // Used for user info requests.
1202 func (c *client) publicPermissions() *Permissions {
1203 c.mu.Lock()
1204 defer c.mu.Unlock()
1205
1206 if c.perms == nil {
1207 return nil
1208 }
1209 perms := &Permissions{
1210 Publish: &SubjectPermission{},
1211 Subscribe: &SubjectPermission{},
1212 }
1213
1214 _subs := [32]*subscription{}
1215
1216 // Publish
1217 if c.perms.pub.allow != nil {
1218 subs := _subs[:0]
1219 c.perms.pub.allow.All(&subs)
1220 for _, sub := range subs {
1221 perms.Publish.Allow = append(perms.Publish.Allow, string(sub.subject))
1222 }
1223 }
1224 if c.perms.pub.deny != nil {
1225 subs := _subs[:0]
1226 c.perms.pub.deny.All(&subs)
1227 for _, sub := range subs {
1228 perms.Publish.Deny = append(perms.Publish.Deny, string(sub.subject))
1229 }
1230 }
1231 // Subsribe
1232 if c.perms.sub.allow != nil {
1233 subs := _subs[:0]
1234 c.perms.sub.allow.All(&subs)
1235 for _, sub := range subs {
1236 perms.Subscribe.Allow = append(perms.Subscribe.Allow, subjectQueueString(sub))
1237 }
1238 }
1239 if c.perms.sub.deny != nil {
1240 subs := _subs[:0]
1241 c.perms.sub.deny.All(&subs)
1242 for _, sub := range subs {
1243 perms.Subscribe.Deny = append(perms.Subscribe.Deny, subjectQueueString(sub))
1244 }
1245 }
1246 // Responses.
1247 if c.perms.resp != nil {
1248 rp := *c.perms.resp
1249 perms.Response = &rp
1250 }
1251
1252 return perms
1253 }
1254
1255 func subjectQueueString(sub *subscription) string {
1256 if len(sub.queue) == 0 {
1257 return string(sub.subject)
1258 }
1259 return string(sub.subject) + " " + string(sub.queue)
1260 }
1261
1262 type denyType int
1263
1264 const (
1265 pub = denyType(iota + 1)
1266 sub
1267 both
1268 )
1269
1270 // Merge client.perms structure with additional pub deny permissions
1271 // Lock is held on entry.
1272 func (c *client) mergeDenyPermissions(what denyType, denyPubs []string) {
1273 if len(denyPubs) == 0 {
1274 return
1275 }
1276 if c.perms == nil {
1277 c.perms = &permissions{}
1278 }
1279 if what == pub || what == both {
1280 if c.perms.pub.deny == nil {
1281 c.perms.pub.deny = NewSublistForServer(c.srv)
1282 }
1283 mergeDenyPerm(&c.perms.pub, denyPubs, false)
1284 }
1285 if what == sub || what == both {
1286 if c.perms.sub.deny == nil {
1287 // Avoid sublist cache contention in canSubscribe.
1288 c.perms.sub.deny = NewSublistNoCache()
1289 }
1290 c.darray = append(c.darray, mergeDenyPerm(&c.perms.sub, denyPubs, true)...)
1291 }
1292 }
1293
1294 // mergeDenyPerm inserts new deny permissions, skipping subjects that already exist.
1295 func mergeDenyPerm(p *perm, denyPubs []string, allowQueue bool) []*subscription {
1296 var inserted []*subscription
1297 FOR_DENY:
1298 for _, deny := range denyPubs {
1299 subject, queue, err := splitSubjectQueue(deny)
1300 if err != nil {
1301 continue
1302 }
1303 if !allowQueue {
1304 queue = nil
1305 }
1306 r := p.deny.Match(string(subject))
1307 for _, v := range r.qsubs {
1308 for _, s := range v {
1309 if bytes.Equal(s.subject, subject) && bytes.Equal(s.queue, queue) {
1310 continue FOR_DENY
1311 }
1312 }
1313 }
1314 for _, s := range r.psubs {
1315 if bytes.Equal(s.subject, subject) && len(queue) == 0 {
1316 continue FOR_DENY
1317 }
1318 }
1319 sub := &subscription{subject: subject, queue: queue}
1320 if p.deny.Insert(sub) == nil {
1321 inserted = append(inserted, sub)
1322 }
1323 }
1324 return inserted
1325 }
1326
1327 // Merge client.perms structure with additional pub deny permissions
1328 // Client lock must not be held on entry
1329 func (c *client) mergeDenyPermissionsLocked(what denyType, denyPubs []string) {
1330 c.mu.Lock()
1331 c.mergeDenyPermissions(what, denyPubs)
1332 c.mu.Unlock()
1333 }
1334
1335 // Check to see if we have an expiration for the user JWT via base claims.
1336 // FIXME(dlc) - Clear on connect with new JWT.
1337 func (c *client) setExpiration(claims *jwt.ClaimsData, validFor time.Duration) {
1338 if claims.Expires == 0 {
1339 if validFor != 0 {
1340 c.setExpirationTimer(validFor)
1341 }
1342 return
1343 }
1344 expiresAt := time.Duration(0)
1345 tn := time.Now().Unix()
1346 if claims.Expires > tn {
1347 expiresAt = time.Duration(claims.Expires-tn) * time.Second
1348 }
1349 if validFor != 0 && validFor < expiresAt {
1350 c.setExpirationTimer(validFor)
1351 } else {
1352 c.setExpirationTimer(expiresAt)
1353 }
1354 }
1355
1356 // This will load up the deny structure used for filtering delivered
1357 // messages based on a deny clause for subscriptions.
1358 // Lock should be held.
1359 func (c *client) loadMsgDenyFilter() {
1360 c.mperms = &msgDeny{NewSublistWithCache(), make(map[msgDenyKey]bool)}
1361 for _, sub := range c.darray {
1362 c.mperms.deny.Insert(&subscription{subject: sub.subject, queue: sub.queue})
1363 }
1364 }
1365
1366 // writeLoop is the main socket write functionality.
1367 // Runs in its own Go routine.
1368 func (c *client) writeLoop() {
1369 defer c.srv.grWG.Done()
1370 c.mu.Lock()
1371 if c.isClosed() {
1372 c.mu.Unlock()
1373 return
1374 }
1375 c.flags.set(writeLoopStarted)
1376 c.mu.Unlock()
1377
1378 // Used to check that we did flush from last wake up.
1379 waitOk := true
1380 var closed bool
1381
1382 // Main loop. Will wait to be signaled and then will use
1383 // buffered outbound structure for efficient writev to the underlying socket.
1384 for {
1385 c.mu.Lock()
1386 if closed = c.isClosed(); !closed {
1387 owtf := c.out.fsp > 0 && c.out.pb < maxBufSize && c.out.fsp < maxFlushPending
1388 if waitOk && (c.out.pb == 0 || owtf) {
1389 c.out.sg.Wait()
1390 // Check that connection has not been closed while lock was released
1391 // in the conditional wait.
1392 closed = c.isClosed()
1393 }
1394 }
1395 if closed {
1396 c.flushAndClose(false)
1397 c.mu.Unlock()
1398
1399 // We should always call closeConnection() to ensure that state is
1400 // properly cleaned-up. It will be a no-op if already done.
1401 c.closeConnection(WriteError)
1402
1403 // Now explicitly call reconnect(). Thanks to ref counting, we know
1404 // that the reconnect will execute only after connection has been
1405 // removed from the server state.
1406 c.reconnect()
1407 return
1408 }
1409 // Flush data
1410 waitOk = c.flushOutbound()
1411 c.mu.Unlock()
1412 }
1413 }
1414
1415 // flushClients will make sure to flush any clients we may have
1416 // sent to during processing. We pass in a budget as a time.Duration
1417 // for how much time to spend in place flushing for this client.
1418 func (c *client) flushClients(budget time.Duration) time.Time {
1419 last := time.Now()
1420
1421 // Check pending clients for flush.
1422 for cp := range c.pcd {
1423 // TODO(dlc) - Wonder if it makes more sense to create a new map?
1424 delete(c.pcd, cp)
1425
1426 // Queue up a flush for those in the set
1427 cp.mu.Lock()
1428 // Update last activity for message delivery
1429 cp.last = last
1430 // Remove ourselves from the pending list.
1431 cp.out.fsp--
1432
1433 // Just ignore if this was closed.
1434 if cp.isClosed() {
1435 cp.mu.Unlock()
1436 continue
1437 }
1438
1439 if budget > 0 && cp.out.lft < 2*budget && cp.flushOutbound() {
1440 budget -= cp.out.lft
1441 } else {
1442 cp.flushSignal()
1443 }
1444
1445 cp.mu.Unlock()
1446 }
1447 return last
1448 }
1449
1450 func (c *client) resetReadLoopStallTime() {
1451 if c.in.tst >= stallClientMaxDuration {
1452 c.rateLimitFormatWarnf("Producer was stalled for a total of %v", c.in.tst.Round(time.Millisecond))
1453 }
1454 c.in.tst = 0
1455 }
1456
1457 // readLoop is the main socket read functionality.
1458 // Runs in its own Go routine.
1459 func (c *client) readLoop(pre []byte) {
1460 // Grab the connection off the client, it will be cleared on a close.
1461 // We check for that after the loop, but want to avoid a nil dereference
1462 c.mu.Lock()
1463 s := c.srv
1464 defer s.grWG.Done()
1465 if c.isClosed() {
1466 c.mu.Unlock()
1467 return
1468 }
1469 nc := c.nc
1470 ws := c.isWebsocket()
1471 if c.isMqtt() {
1472 c.mqtt.r = &mqttReader{reader: nc}
1473 }
1474 c.in.rsz = startBufSize
1475
1476 // Check the per-account-cache for closed subscriptions
1477 cpacc := c.kind == ROUTER || c.kind == GATEWAY
1478 // Last per-account-cache check for closed subscriptions
1479 lpacc := time.Now()
1480 acc := c.acc
1481 var masking bool
1482 if ws {
1483 masking = c.ws.maskread
1484 }
1485 checkCompress := c.kind == ROUTER || c.kind == LEAF
1486 c.mu.Unlock()
1487
1488 defer func() {
1489 if c.isMqtt() {
1490 s.mqttHandleClosedClient(c)
1491 }
1492 // These are used only in the readloop, so we can set them to nil
1493 // on exit of the readLoop.
1494 c.in.results, c.in.pacache = nil, nil
1495 }()
1496
1497 // Start read buffer.
1498 b := make([]byte, c.in.rsz)
1499
1500 // Websocket clients will return several slices if there are multiple
1501 // websocket frames in the blind read. For non WS clients though, we
1502 // will always have 1 slice per loop iteration. So we define this here
1503 // so non WS clients will use bufs[0] = b[:n].
1504 var _bufs [1][]byte
1505 bufs := _bufs[:1]
1506
1507 var wsr *wsReadInfo
1508 if ws {
1509 wsr = &wsReadInfo{mask: masking}
1510 wsr.init()
1511 }
1512
1513 var decompress bool
1514 var reader io.Reader
1515 reader = nc
1516
1517 for {
1518 var n int
1519 var err error
1520
1521 // If we have a pre buffer parse that first.
1522 if len(pre) > 0 {
1523 b = pre
1524 n = len(pre)
1525 pre = nil
1526 } else {
1527 n, err = reader.Read(b)
1528 // If we have any data we will try to parse and exit at the end.
1529 if n == 0 && err != nil {
1530 c.closeConnection(closedStateForErr(err))
1531 return
1532 }
1533 }
1534 // Check if the account has mappings and if so set the local readcache flag.
1535 // We check here to make sure any changes such as config reload are reflected here.
1536 if c.kind == CLIENT || c.kind == LEAF {
1537 if acc.hasMappings() {
1538 c.in.flags.set(hasMappings)
1539 } else {
1540 c.in.flags.clear(hasMappings)
1541 }
1542 }
1543
1544 c.in.start = time.Now()
1545
1546 // Clear inbound stats cache
1547 c.in.msgs = 0
1548 c.in.bytes = 0
1549 c.in.subs = 0
1550
1551 if ws {
1552 err = c.wsReadAndParse(wsr, reader, b[:n])
1553 if err != nil {
1554 // Match the normal parse path: any already-buffered deliveries
1555 // need their pending flush signals drained before we close.
1556 c.flushClients(0)
1557 if err != io.EOF {
1558 c.Errorf("read error: %v", err)
1559 }
1560 c.closeConnection(closedStateForErr(err))
1561 return
1562 }
1563 c.resetReadLoopStallTime()
1564 goto postParse
1565 } else {
1566 bufs[0] = b[:n]
1567 }
1568
1569 // Main call into parser for inbound data. This will generate callouts
1570 // to process messages, etc.
1571 for i := 0; i < len(bufs); i++ {
1572 if err := c.parse(bufs[i]); err != nil {
1573 if err == ErrMinimumVersionRequired {
1574 // Special case here, currently only for leaf node connections.
1575 // processLeafConnect() already sent the rejection and closed
1576 // the connection, so there is nothing else to do here.
1577 return
1578 }
1579 if dur := time.Since(c.in.start); dur >= readLoopReportThreshold {
1580 c.Warnf("Readloop processing time: %v", dur)
1581 }
1582 // Need to call flushClients because some of the clients have been
1583 // assigned messages and their "fsp" incremented, and need now to be
1584 // decremented and their writeLoop signaled.
1585 c.flushClients(0)
1586 // handled inline
1587 if err != ErrMaxPayload && err != ErrAuthentication {
1588 c.Error(err)
1589 c.closeConnection(ProtocolViolation)
1590 }
1591 return
1592 }
1593 c.resetReadLoopStallTime()
1594 }
1595
1596 postParse:
1597 // If we are a ROUTER/LEAF and have processed an INFO, it is possible that
1598 // we are asked to switch to compression now.
1599 if checkCompress && c.in.flags.isSet(switchToCompression) {
1600 c.in.flags.clear(switchToCompression)
1601 // For now we support only s2 compression...
1602 reader = s2.NewReader(nc)
1603 decompress = true
1604 }
1605
1606 // Updates stats for client and server that were collected
1607 // from parsing through the buffer.
1608 if c.in.msgs > 0 {
1609 inMsgs := int64(c.in.msgs)
1610 inBytes := int64(c.in.bytes)
1611
1612 atomic.AddInt64(&c.inMsgs, inMsgs)
1613 atomic.AddInt64(&c.inBytes, inBytes)
1614
1615 if acc != nil {
1616 acc.stats.Lock()
1617 acc.stats.inMsgs += inMsgs
1618 acc.stats.inBytes += inBytes
1619 if c.kind == LEAF {
1620 acc.stats.ln.inMsgs += int64(inMsgs)
1621 acc.stats.ln.inBytes += int64(inBytes)
1622 }
1623 acc.stats.Unlock()
1624 }
1625
1626 if c.kind == CLIENT {
1627 atomic.AddInt64(&s.inClientMsgs, inMsgs)
1628 atomic.AddInt64(&s.inClientBytes, inBytes)
1629 }
1630
1631 atomic.AddInt64(&s.inMsgs, inMsgs)
1632 atomic.AddInt64(&s.inBytes, inBytes)
1633 }
1634
1635 // Signal to writeLoop to flush to socket.
1636 last := c.flushClients(0)
1637
1638 // Update activity, check read buffer size.
1639 c.mu.Lock()
1640
1641 // Activity based on interest changes or data/msgs.
1642 // Also update last receive activity for ping sender
1643 if c.in.msgs > 0 || c.in.subs > 0 {
1644 c.last = last
1645 c.lastIn = last
1646 }
1647
1648 if n >= cap(b) {
1649 c.in.srs = 0
1650 } else if n < cap(b)/2 { // divide by 2 b/c we want less than what we would shrink to.
1651 c.in.srs++
1652 }
1653
1654 // Update read buffer size as/if needed.
1655 if n >= cap(b) && cap(b) < maxBufSize {
1656 // Grow
1657 c.in.rsz = int32(cap(b) * 2)
1658 b = make([]byte, c.in.rsz)
1659 } else if n < cap(b) && cap(b) > minBufSize && c.in.srs > shortsToShrink {
1660 // Shrink, for now don't accelerate, ping/pong will eventually sort it out.
1661 c.in.rsz = int32(cap(b) / 2)
1662 b = make([]byte, c.in.rsz)
1663 }
1664 // re-snapshot the account since it can change during reload, etc.
1665 acc = c.acc
1666 // Refresh nc because in some cases, we have upgraded c.nc to TLS.
1667 if nc != c.nc {
1668 nc = c.nc
1669 if decompress && nc != nil {
1670 // For now we support only s2 compression...
1671 reader.(*s2.Reader).Reset(nc)
1672 } else if !decompress {
1673 reader = nc
1674 }
1675 }
1676 c.mu.Unlock()
1677
1678 // Connection was closed
1679 if nc == nil {
1680 return
1681 }
1682
1683 if dur := time.Since(c.in.start); dur >= readLoopReportThreshold {
1684 c.Warnf("Readloop processing time: %v", dur)
1685 }
1686
1687 // We could have had a read error from above but still read some data.
1688 // If so do the close here unconditionally.
1689 if err != nil {
1690 c.closeConnection(closedStateForErr(err))
1691 return
1692 }
1693
1694 if cpacc && (c.in.start.Sub(lpacc)) >= closedSubsCheckInterval {
1695 c.pruneClosedSubFromPerAccountCache()
1696 lpacc = time.Now()
1697 }
1698 }
1699 }
1700
1701 // Returns the appropriate closed state for a given read error.
1702 func closedStateForErr(err error) ClosedState {
1703 if err == io.EOF {
1704 return ClientClosed
1705 }
1706 return ReadError
1707 }
1708
1709 // collapsePtoNB will either returned framed WebSocket buffers or it will
1710 // return a reference to c.out.nb.
1711 func (c *client) collapsePtoNB() (net.Buffers, int64) {
1712 if c.isWebsocket() {
1713 return c.wsCollapsePtoNB()
1714 }
1715 return c.out.nb, c.out.pb
1716 }
1717
1718 // flushOutbound will flush outbound buffer to a client.
1719 // Will return true if data was attempted to be written.
1720 // Lock must be held
1721 func (c *client) flushOutbound() bool {
1722 if c.flags.isSet(flushOutbound) {
1723 // For CLIENT connections, it is possible that the readLoop calls
1724 // flushOutbound(). If writeLoop and readLoop compete and we are
1725 // here we should release the lock to reduce the risk of spinning.
1726 c.mu.Unlock()
1727 runtime.Gosched()
1728 c.mu.Lock()
1729 return false
1730 }
1731 c.flags.set(flushOutbound)
1732 defer func() {
1733 // Check flushAndClose() for explanation on why we do this.
1734 if c.isClosed() {
1735 for i := range c.out.wnb {
1736 nbPoolPut(c.out.wnb[i])
1737 }
1738 c.out.wnb = nil
1739 }
1740 c.flags.clear(flushOutbound)
1741 }()
1742
1743 // Check for nothing to do.
1744 if c.nc == nil || c.srv == nil || c.out.pb == 0 {
1745 return true // true because no need to queue a signal.
1746 }
1747
1748 // In the case of a normal socket connection, "collapsed" is just a ref
1749 // to "nb". In the case of WebSockets, additional framing is added to
1750 // anything that is waiting in "nb". Also keep a note of how many bytes
1751 // were queued before we release the mutex.
1752 collapsed, attempted := c.collapsePtoNB()
1753
1754 // Frustratingly, (net.Buffers).WriteTo() modifies the receiver so we
1755 // can't work on "nb" directly — while the mutex is unlocked during IO,
1756 // something else might call queueOutbound and modify it. So instead we
1757 // need a working copy — we'll operate on "wnb" instead. Note that in
1758 // the case of a partial write, "wnb" may have remaining data from the
1759 // previous write, and in the case of WebSockets, that data may already
1760 // be framed, so we are careful not to re-frame "wnb" here. Instead we
1761 // will just frame up "nb" and append it onto whatever is left on "wnb".
1762 // "nb" will be set to nil so that we can manipulate "collapsed" outside
1763 // of the client's lock, which is interesting in case of compression.
1764 c.out.nb = nil
1765
1766 // In case it goes away after releasing the lock.
1767 nc := c.nc
1768
1769 // Capture this (we change the value in some tests)
1770 wdl := c.out.wdl
1771
1772 // Check for compression
1773 cw := c.out.cw
1774 if cw != nil {
1775 // We will have to adjust once we have compressed, so remove for now.
1776 c.out.pb -= attempted
1777 if c.isWebsocket() {
1778 c.ws.fs -= attempted
1779 }
1780 }
1781
1782 // Do NOT hold lock during actual IO.
1783 c.mu.Unlock()
1784
1785 // Compress outside of the lock
1786 if cw != nil {
1787 var err error
1788 bb := bytes.Buffer{}
1789
1790 cw.Reset(&bb)
1791 for _, buf := range collapsed {
1792 if err == nil {
1793 _, err = cw.Write(buf)
1794 }
1795 // Return always after consumed or error.
1796 nbPoolPut(buf)
1797 }
1798 if err == nil {
1799 err = cw.Close()
1800 }
1801 if err != nil {
1802 c.Errorf("Error compressing data: %v", err)
1803 // We need to grab the lock now before marking as closed and exiting
1804 c.mu.Lock()
1805 c.markConnAsClosed(WriteError)
1806 return false
1807 }
1808 collapsed = append(net.Buffers(nil), bb.Bytes())
1809 attempted = int64(len(collapsed[0]))
1810 }
1811
1812 // This is safe to do outside of the lock since "collapsed" is no longer
1813 // referenced in c.out.nb (which can be modified in queueOutboud() while
1814 // the lock is released).
1815 c.out.wnb = append(c.out.wnb, collapsed...)
1816 var _orig [nbMaxVectorSize][]byte
1817 orig := append(_orig[:0], c.out.wnb...)
1818
1819 // Since WriteTo is lopping things off the beginning, we need to remember
1820 // the start position of the underlying array so that we can get back to it.
1821 // Otherwise we'll always "slide forward" and that will result in reallocs.
1822 startOfWnb := c.out.wnb[0:]
1823
1824 // flush here
1825 start := time.Now()
1826
1827 var n int64 // Total bytes written
1828 var wn int64 // Bytes written per loop
1829 var err error // Error from last write, if any
1830 for len(c.out.wnb) > 0 {
1831 // Limit the number of vectors to no more than nbMaxVectorSize,
1832 // which if 1024, will mean a maximum of 64MB in one go.
1833 wnb := c.out.wnb
1834 if len(wnb) > nbMaxVectorSize {
1835 wnb = wnb[:nbMaxVectorSize]
1836 }
1837 consumed := len(wnb)
1838
1839 // Actual write to the socket. The deadline applies to each batch
1840 // rather than the total write, such that the configured deadline
1841 // can be tuned to a known maximum quantity (64MB).
1842 nc.SetWriteDeadline(time.Now().Add(wdl))
1843 wn, err = wnb.WriteTo(nc)
1844
1845 // Update accounting, move wnb slice onwards if needed, or stop
1846 // if a write error was reported that wasn't a short write.
1847 n += wn
1848 c.out.wnb = c.out.wnb[consumed-len(wnb):]
1849 if err != nil && err != io.ErrShortWrite {
1850 break
1851 }
1852 }
1853
1854 // The deadline is overwritten at the start of each iteration anyway,
1855 // so only needed to clear the write deadline once after the loop.
1856 nc.SetWriteDeadline(time.Time{})
1857
1858 lft := time.Since(start)
1859
1860 // Re-acquire client lock.
1861 c.mu.Lock()
1862
1863 // Adjust if we were compressing.
1864 if cw != nil {
1865 c.out.pb += attempted
1866 if c.isWebsocket() {
1867 c.ws.fs += attempted
1868 }
1869 }
1870
1871 // At this point, "wnb" has been mutated by WriteTo and any consumed
1872 // buffers have been lopped off the beginning, so in order to return
1873 // them to the pool, we need to look at the difference between "orig"
1874 // and "wnb".
1875 for i := 0; i < len(orig)-len(c.out.wnb); i++ {
1876 nbPoolPut(orig[i])
1877 }
1878
1879 // At this point it's possible that "nb" has been modified by another
1880 // call to queueOutbound while the lock was released, so we'll leave
1881 // those for the next iteration. Meanwhile it's possible that we only
1882 // managed a partial write of "wnb", so we'll shift anything that
1883 // remains up to the beginning of the array to prevent reallocating.
1884 // Anything left in "wnb" has already been framed for WebSocket conns
1885 // so leave them alone for the next call to flushOutbound.
1886 c.out.wnb = append(startOfWnb[:0], c.out.wnb...)
1887
1888 // If we've written everything but the underlying array of our working
1889 // buffer has grown excessively then free it — the GC will tidy it up
1890 // and we can allocate a new one next time.
1891 if len(c.out.wnb) == 0 && cap(c.out.wnb) > nbMaxVectorSize {
1892 c.out.wnb = nil
1893 }
1894
1895 // Ignore ErrShortWrite errors, they will be handled as partials.
1896 var gotWriteTimeout bool
1897 if err != nil && err != io.ErrShortWrite {
1898 // Handle timeout error (slow consumer) differently
1899 if ne, ok := err.(net.Error); ok && ne.Timeout() {
1900 gotWriteTimeout = true
1901 if closed := c.handleWriteTimeout(n, attempted, len(orig)); closed {
1902 return true
1903 }
1904 } else {
1905 // Other errors will cause connection to be closed.
1906 // For clients, report as debug but for others report as error.
1907 report := c.Debugf
1908 if c.kind != CLIENT {
1909 report = c.Errorf
1910 }
1911 report("Error flushing: %v", err)
1912 c.markConnAsClosed(WriteError)
1913 return true
1914 }
1915 }
1916
1917 // Update flush time statistics.
1918 c.out.lft = lft
1919
1920 // Subtract from pending bytes and messages.
1921 c.out.pb -= n
1922 if c.isWebsocket() {
1923 c.ws.fs -= n
1924 }
1925
1926 // Check that if there is still data to send and writeLoop is in wait,
1927 // then we need to signal.
1928 if c.out.pb > 0 {
1929 c.flushSignal()
1930 }
1931
1932 // Check if we have a stalled gate and if so and we are recovering release
1933 // any stalled producers. Only kind==CLIENT will stall.
1934 if c.out.stc != nil && (n == attempted || c.out.pb < c.out.mp/4*3) {
1935 close(c.out.stc)
1936 c.out.stc = nil
1937 }
1938 // Check if the connection is recovering from being a slow consumer.
1939 if !gotWriteTimeout && c.flags.isSet(isSlowConsumer) {
1940 c.Noticef("Slow Consumer Recovered: Flush took %.3fs with %d chunks of %d total bytes.", time.Since(start).Seconds(), len(orig), attempted)
1941 c.flags.clear(isSlowConsumer)
1942 }
1943
1944 return true
1945 }
1946
1947 // This is invoked from flushOutbound() for io/timeout error (slow consumer).
1948 // Returns a boolean to indicate if the connection has been closed or not.
1949 // Lock is held on entry.
1950 func (c *client) handleWriteTimeout(written, attempted int64, numChunks int) bool {
1951 if tlsConn, ok := c.nc.(*tls.Conn); ok {
1952 if !tlsConn.ConnectionState().HandshakeComplete {
1953 // Likely a TLSTimeout error instead...
1954 c.markConnAsClosed(TLSHandshakeError)
1955 // Would need to coordinate with tlstimeout()
1956 // to avoid double logging, so skip logging
1957 // here, and don't report a slow consumer error.
1958 return true
1959 }
1960 } else if c.flags.isSet(expectConnect) && !c.flags.isSet(connectReceived) {
1961 // Under some conditions, a connection may hit a slow consumer write deadline
1962 // before the authorization timeout. If that is the case, then we handle
1963 // as slow consumer though we do not increase the counter as that can be
1964 // misleading.
1965 c.markConnAsClosed(SlowConsumerWriteDeadline)
1966 return true
1967 }
1968 alreadySC := c.flags.isSet(isSlowConsumer)
1969 scState := "Detected"
1970 if alreadySC {
1971 scState = "State"
1972 }
1973
1974 // Aggregate slow consumers.
1975 atomic.AddInt64(&c.srv.slowConsumers, 1)
1976 switch c.kind {
1977 case CLIENT:
1978 c.srv.scStats.clients.Add(1)
1979 case ROUTER:
1980 // Only count each Slow Consumer event once.
1981 if !alreadySC {
1982 c.srv.scStats.routes.Add(1)
1983 }
1984 case GATEWAY:
1985 c.srv.scStats.gateways.Add(1)
1986 case LEAF:
1987 c.srv.scStats.leafs.Add(1)
1988 }
1989 if c.acc != nil {
1990 c.acc.stats.Lock()
1991 c.acc.stats.slowConsumers++
1992 c.acc.stats.Unlock()
1993 }
1994 c.Noticef("Slow Consumer %s: WriteDeadline of %v exceeded with %d chunks of %d total bytes.",
1995 scState, c.out.wdl, numChunks, attempted)
1996
1997 // We always close CLIENT connections, or when nothing was written at all...
1998 if c.out.wtp == WriteTimeoutPolicyClose || written == 0 {
1999 c.markConnAsClosed(SlowConsumerWriteDeadline)
2000 return true
2001 } else {
2002 c.flags.setIfNotSet(isSlowConsumer)
2003 }
2004 return false
2005 }
2006
2007 // Marks this connection has closed with the given reason.
2008 // Sets the connMarkedClosed flag and skipFlushOnClose depending on the reason.
2009 // Depending on the kind of connection, the connection will be saved.
2010 // If a writeLoop has been started, the final flush will be done there, otherwise
2011 // flush and close of TCP connection is done here in place.
2012 // Returns true if closed in place, flase otherwise.
2013 // Lock is held on entry.
2014 func (c *client) markConnAsClosed(reason ClosedState) {
2015 // Possibly set skipFlushOnClose flag even if connection has already been
2016 // mark as closed. The rationale is that a connection may be closed with
2017 // a reason that justifies a flush (say after sending an -ERR), but then
2018 // the flushOutbound() gets a write error. If that happens, connection
2019 // being lost, there is no reason to attempt to flush again during the
2020 // teardown when the writeLoop exits.
2021 var skipFlush bool
2022 switch reason {
2023 case ReadError, WriteError, SlowConsumerPendingBytes, SlowConsumerWriteDeadline, TLSHandshakeError:
2024 c.flags.set(skipFlushOnClose)
2025 skipFlush = true
2026 case StaleConnection:
2027 // Track stale connections statistics.
2028 atomic.AddInt64(&c.srv.staleConnections, 1)
2029 switch c.kind {
2030 case CLIENT:
2031 c.srv.staleStats.clients.Add(1)
2032 case ROUTER:
2033 c.srv.staleStats.routes.Add(1)
2034 case GATEWAY:
2035 c.srv.staleStats.gateways.Add(1)
2036 case LEAF:
2037 c.srv.staleStats.leafs.Add(1)
2038 }
2039 }
2040 if c.flags.isSet(connMarkedClosed) {
2041 return
2042 }
2043 c.flags.set(connMarkedClosed)
2044 // For a websocket client, unless we are told not to flush, enqueue
2045 // a websocket CloseMessage based on the reason.
2046 if !skipFlush && c.isWebsocket() && !c.ws.closeSent {
2047 c.wsEnqueueCloseMessage(reason)
2048 }
2049 // Be consistent with the creation: for routes, gateways and leaf,
2050 // we use Noticef on create, so use that too for delete.
2051 if c.srv != nil {
2052 if c.kind == LEAF || c.kind == ROUTER || c.kind == GATEWAY {
2053 var tags []string
2054 var remoteName string
2055 switch {
2056 case c.kind == LEAF && c.leaf != nil:
2057 remoteName = c.leaf.remoteServer
2058 case c.kind == ROUTER && c.route != nil:
2059 remoteName = c.route.remoteName
2060 case c.kind == GATEWAY && c.gw != nil:
2061 remoteName = c.gw.remoteName
2062 }
2063 if remoteName != _EMPTY_ {
2064 tags = append(tags, fmt.Sprintf("Remote: %s", remoteName))
2065 }
2066 if len(tags) > 0 {
2067 c.Noticef("%s connection closed: %s - %s", c.kindString(), reason, strings.Join(tags, ", "))
2068 } else {
2069 c.Noticef("%s connection closed: %s", c.kindString(), reason)
2070 }
2071 } else { // Client, System, Jetstream, and Account connections.
2072 c.Debugf("%s connection closed: %s", c.kindString(), reason)
2073 }
2074 }
2075
2076 // Save off the connection if its a client or leafnode.
2077 if c.kind == CLIENT || c.kind == LEAF {
2078 if nc := c.nc; nc != nil && c.srv != nil {
2079 // TODO: May want to send events to single go routine instead
2080 // of creating a new go routine for each save.
2081 // Pass the c.subs as a reference. It may be set to nil in
2082 // closeConnection.
2083 go c.srv.saveClosedClient(c, nc, c.subs, reason)
2084 }
2085 }
2086 // If writeLoop exists, let it do the final flush, close and teardown.
2087 if c.flags.isSet(writeLoopStarted) {
2088 // Since we want the writeLoop to do the final flush and tcp close,
2089 // we want the reconnect to be done there too. However, it should'nt
2090 // happen before the connection has been removed from the server
2091 // state (end of closeConnection()). This ref count allows us to
2092 // guarantee that.
2093 c.rref++
2094 c.flushSignal()
2095 return
2096 }
2097 // Flush (if skipFlushOnClose is not set) and close in place. If flushing,
2098 // use a small WriteDeadline.
2099 c.flushAndClose(true)
2100 }
2101
2102 // flushSignal will use server to queue the flush IO operation to a pool of flushers.
2103 // Lock must be held.
2104 func (c *client) flushSignal() {
2105 // Check that sg is not nil, which will happen if the connection is closed.
2106 if c.out.sg != nil {
2107 c.out.sg.Signal()
2108 }
2109 }
2110
2111 // Traces a message.
2112 // Will NOT check if tracing is enabled, does NOT need the client lock.
2113 func (c *client) traceMsgInternal(msg []byte, delivered bool, hdrSize int) {
2114 opts := c.srv.getOpts()
2115 maxTrace := opts.MaxTracedMsgLen
2116 headersOnly := opts.TraceHeaders
2117 suffix := LEN_CR_LF
2118
2119 // If TraceHeaders is enabled, extract only the header portion of the msg.
2120 // If a header is present, it ends with an additional trailing CRLF.
2121 if headersOnly {
2122 if hdrSize > 0 && len(msg) >= hdrSize {
2123 msg = msg[:hdrSize]
2124 suffix += LEN_CR_LF
2125 } else {
2126 // No headers present, so nothing to trace.
2127 return
2128 }
2129 }
2130
2131 // Do not emit a log line for zero-length payloads.
2132 l := len(msg) - suffix
2133 if l <= 0 {
2134 return
2135 }
2136
2137 const (
2138 traceInPrefix string = "<<-"
2139 traceOutPrefix string = "->>"
2140 )
2141 var prefix string
2142 if delivered {
2143 prefix = traceOutPrefix
2144 } else {
2145 prefix = traceInPrefix
2146 }
2147 if maxTrace > 0 && l > maxTrace {
2148 tm := fmt.Sprintf("%q", msg[:maxTrace])
2149 c.Tracef("%s MSG_PAYLOAD: [\"%s...\"]", prefix, tm[1:len(tm)-1])
2150 } else {
2151 c.Tracef("%s MSG_PAYLOAD: [%q]", prefix, msg[:l])
2152 }
2153 }
2154
2155 func (c *client) traceMsg(msg []byte) {
2156 c.traceMsgInternal(msg, false, c.pa.hdr)
2157 }
2158
2159 func (c *client) traceMsgDelivery(msg []byte, hdrSize int) {
2160 c.traceMsgInternal(msg, true, hdrSize)
2161 }
2162
2163 // Traces an incoming operation.
2164 // Will NOT check if tracing is enabled, does NOT need the client lock.
2165 func (c *client) traceInOp(op string, arg []byte) {
2166 c.traceOp("<<- %s", op, arg)
2167 }
2168
2169 // Traces an outgoing operation.
2170 // Will NOT check if tracing is enabled, does NOT need the client lock.
2171 func (c *client) traceOutOp(op string, arg []byte) {
2172 c.traceOp("->> %s", op, arg)
2173 }
2174
2175 func (c *client) traceOp(format, op string, arg []byte) {
2176 opa := []any{}
2177 if op != _EMPTY_ {
2178 opa = append(opa, op)
2179 }
2180 if arg != nil {
2181 opa = append(opa, bytesToString(arg))
2182 }
2183 c.Tracef(format, opa)
2184 }
2185
2186 // Process the information messages from Clients and other Routes.
2187 func (c *client) processInfo(arg []byte) error {
2188 info := Info{}
2189 if err := json.Unmarshal(arg, &info); err != nil {
2190 return err
2191 }
2192 switch c.kind {
2193 case ROUTER:
2194 c.processRouteInfo(&info)
2195 case GATEWAY:
2196 c.processGatewayInfo(&info)
2197 case LEAF:
2198 c.processLeafnodeInfo(&info)
2199 }
2200 return nil
2201 }
2202
2203 func (c *client) processErr(errStr string) {
2204 close := true
2205 switch c.kind {
2206 case CLIENT:
2207 c.Errorf("Client Error %s", errStr)
2208 case ROUTER:
2209 c.Errorf("Route Error %s", errStr)
2210 case GATEWAY:
2211 c.Errorf("Gateway Error %s", errStr)
2212 case LEAF:
2213 c.Errorf("Leafnode Error %s", errStr)
2214 c.leafProcessErr(errStr)
2215 close = false
2216 case JETSTREAM:
2217 c.Errorf("JetStream Error %s", errStr)
2218 }
2219 if close {
2220 c.closeConnection(ParseError)
2221 }
2222 }
2223
2224 // Matcher for pass/password and auth_token fields.
2225 var prefixAuthPat = regexp.MustCompile(`"?\s*(?:auth_token\S*?|pass\S*?)"?\s*[:=]\s*"?([^",\r\n}]*)`)
2226
2227 // Exact matcher for fields sig, proxy_sig and nkey.
2228 // Overlapping field "sig" does not match inside "proxy_sig".
2229 var exactAuthPat = regexp.MustCompile(`(?:^|[^A-Za-z0-9_])"?\s*(?:proxy_sig|nkey|sig)"?\s*[:=]\s*"?([^",\r\n}]*)`)
2230
2231 // removeSecretsFromTrace removes any notion of passwords/tokens from trace
2232 // messages for logging.
2233 func removeSecretsFromTrace(arg []byte) []byte {
2234 buf := redact(prefixAuthPat, arg)
2235 return redact(exactAuthPat, buf)
2236 }
2237
2238 func redact(pat *regexp.Regexp, proto []byte) []byte {
2239 m := pat.FindAllSubmatchIndex(proto, -1)
2240 if len(m) == 0 {
2241 return proto
2242 }
2243 // Take a copy of the connect proto just for the trace message.
2244 var _arg [4096]byte
2245 buf := append(_arg[:0], proto...)
2246 redactedPass := []byte("[REDACTED]")
2247 for i := len(m) - 1; i >= 0; i-- {
2248 match := m[i]
2249 if len(match) < 4 {
2250 continue
2251 }
2252 start, end := match[2], match[3]
2253 // Replace value substring.
2254 buf = append(buf[:start], append(redactedPass, buf[end:]...)...)
2255 }
2256 return buf
2257 }
2258
2259 // Returns the RTT by computing the elapsed time since now and `start`.
2260 // On Windows VM where I (IK) run tests, time.Since() will return 0
2261 // (I suspect some time granularity issues). So return at minimum 1ns.
2262 func computeRTT(start time.Time) time.Duration {
2263 rtt := time.Since(start)
2264 if rtt <= 0 {
2265 rtt = time.Nanosecond
2266 }
2267 return rtt
2268 }
2269
2270 // processConnect will process a client connect op.
2271 func (c *client) processConnect(arg []byte) error {
2272 supportsHeaders := c.srv.supportsHeaders()
2273 c.mu.Lock()
2274 // If we can't stop the timer because the callback is in progress...
2275 if !c.clearAuthTimer() {
2276 // wait for it to finish and handle sending the failure back to
2277 // the client.
2278 for !c.isClosed() {
2279 c.mu.Unlock()
2280 time.Sleep(25 * time.Millisecond)
2281 c.mu.Lock()
2282 }
2283 c.mu.Unlock()
2284 return nil
2285 }
2286 c.last = time.Now().UTC()
2287 // Estimate RTT to start.
2288 if c.kind == CLIENT {
2289 c.rtt = computeRTT(c.start)
2290 if c.srv != nil {
2291 c.clearPingTimer()
2292 c.setFirstPingTimer()
2293 }
2294 }
2295 kind := c.kind
2296 srv := c.srv
2297
2298 // Moved unmarshalling of clients' Options under the lock.
2299 // The client has already been added to the server map, so it is possible
2300 // that other routines lookup the client, and access its options under
2301 // the client's lock, so unmarshalling the options outside of the lock
2302 // would cause data RACEs.
2303 if err := json.Unmarshal(arg, &c.opts); err != nil {
2304 c.mu.Unlock()
2305 return err
2306 }
2307 // Indicate that the CONNECT protocol has been received, and that the
2308 // server now knows which protocol this client supports.
2309 firstConnect := !c.flags.isSet(connectReceived)
2310 c.flags.set(connectReceived)
2311 // Capture these under lock
2312 c.echo = c.opts.Echo
2313 proto := c.opts.Protocol
2314 verbose := c.opts.Verbose
2315 lang := c.opts.Lang
2316 account := c.opts.Account
2317 accountNew := c.opts.AccountNew
2318
2319 // if websocket client, maybe some options through cookies
2320 if ws := c.ws; ws != nil {
2321 // if JWT not in the CONNECT, use the cookie JWT (possibly empty).
2322 if c.opts.JWT == _EMPTY_ {
2323 c.opts.JWT = ws.cookieJwt
2324 }
2325 // if user not in the CONNECT, use the cookie user (possibly empty)
2326 if c.opts.Username == _EMPTY_ {
2327 c.opts.Username = ws.cookieUsername
2328 }
2329 // if pass not in the CONNECT, use the cookie password (possibly empty).
2330 if c.opts.Password == _EMPTY_ {
2331 c.opts.Password = ws.cookiePassword
2332 }
2333 // if token not in the CONNECT, use the cookie token (possibly empty).
2334 if c.opts.Token == _EMPTY_ {
2335 c.opts.Token = ws.cookieToken
2336 }
2337 }
2338
2339 // when not in operator mode, discard the jwt
2340 if srv != nil && srv.trustedKeys == nil {
2341 c.opts.JWT = _EMPTY_
2342 }
2343 ujwt := c.opts.JWT
2344
2345 // For headers both client and server need to support.
2346 c.headers = supportsHeaders && c.opts.Headers
2347 c.mu.Unlock()
2348
2349 if srv != nil {
2350 // Applicable to clients only:
2351 // As soon as c.opts is unmarshalled and if the proto is at
2352 // least ClientProtoInfo, we need to increment the following counter.
2353 // This is decremented when client is removed from the server's
2354 // clients map.
2355 if kind == CLIENT && proto >= ClientProtoInfo && firstConnect {
2356 srv.mu.Lock()
2357 srv.cproto++
2358 srv.mu.Unlock()
2359 }
2360
2361 // A second CONNECT may move the client into a different account via
2362 // checkAuthentication. Drop any previously-registered subscriptions
2363 // from the current account first so they don't leak in that account's
2364 // sublist after the client switches.
2365 if !firstConnect {
2366 c.clearAccountSubs(false)
2367 }
2368
2369 // Check for Auth
2370 if ok := srv.checkAuthentication(c); !ok {
2371 // We may fail here because we reached max limits on an account.
2372 if ujwt != _EMPTY_ {
2373 c.mu.Lock()
2374 acc := c.acc
2375 c.mu.Unlock()
2376 srv.mu.Lock()
2377 tooManyAccCons := acc != nil && acc != srv.gacc
2378 srv.mu.Unlock()
2379 if tooManyAccCons {
2380 return ErrTooManyAccountConnections
2381 }
2382 }
2383 c.authViolation()
2384 return ErrAuthentication
2385 }
2386
2387 // Check for Account designation, we used to have this as an optional feature for dynamic
2388 // sandbox environments. Now its considered an error.
2389 if accountNew || account != _EMPTY_ {
2390 c.authViolation()
2391 return ErrAuthentication
2392 }
2393
2394 // If no account designation.
2395 // Do this only for CLIENT and LEAF connections.
2396 if c.acc == nil && (c.kind == CLIENT || c.kind == LEAF) {
2397 // By default register with the global account.
2398 c.registerWithAccount(srv.globalAccount())
2399 }
2400
2401 // Initialize user info used in logs.
2402 c.mu.Lock()
2403 acc := c.acc
2404 if c.getRawAuthUser() != _EMPTY_ {
2405 c.ncsUser.Store(c.getAuthUserLabel())
2406 }
2407 c.mu.Unlock()
2408 if acc != nil {
2409 acc.mu.RLock()
2410 c.ncsAcc.Store(acc.traceLabel())
2411 acc.mu.RUnlock()
2412 }
2413
2414 // Enable logging connection details and auth info for this client.
2415 if c.kind == CLIENT && firstConnect && c.srv != nil {
2416 var ncs string
2417 if c.opts.Version != _EMPTY_ {
2418 ncs = fmt.Sprintf("v%s", c.opts.Version)
2419 }
2420 if c.opts.Lang != _EMPTY_ {
2421 if c.opts.Version == _EMPTY_ {
2422 ncs = c.opts.Lang
2423 } else {
2424 ncs = fmt.Sprintf("%s:%s", ncs, c.opts.Lang)
2425 }
2426 }
2427 if c.opts.Name != _EMPTY_ {
2428 if c.opts.Version == _EMPTY_ && c.opts.Lang == _EMPTY_ {
2429 ncs = c.opts.Name
2430 } else {
2431 ncs = fmt.Sprintf("%s:%s", ncs, c.opts.Name)
2432 }
2433 }
2434 var acs string
2435 accl := c.ncsAcc.Load()
2436 authUser := c.ncsUser.Load()
2437 if accl != nil && authUser != nil {
2438 acs = fmt.Sprintf("%s/%s", accl, authUser)
2439 }
2440 switch {
2441 case ncs != _EMPTY_ && acs != _EMPTY_:
2442 c.ncs.Store(fmt.Sprintf("%s - %q - %q", c, ncs, acs))
2443 case ncs != _EMPTY_:
2444 c.ncs.Store(fmt.Sprintf("%s - %q", c, ncs))
2445 case acs != _EMPTY_:
2446 c.ncs.Store(fmt.Sprintf("%s - %q", c, acs))
2447 }
2448 }
2449 }
2450
2451 switch kind {
2452 case CLIENT:
2453 // Check client protocol request if it exists.
2454 if proto < ClientProtoZero || proto > ClientProtoInfo {
2455 c.sendErr(ErrBadClientProtocol.Error())
2456 c.closeConnection(BadClientProtocolVersion)
2457 return ErrBadClientProtocol
2458 }
2459 // Check to see that if no_responders is requested
2460 // they have header support on as well.
2461 c.mu.Lock()
2462 misMatch := c.opts.NoResponders && !c.headers
2463 c.mu.Unlock()
2464 if misMatch {
2465 c.sendErr(ErrNoRespondersRequiresHeaders.Error())
2466 c.closeConnection(NoRespondersRequiresHeaders)
2467 return ErrNoRespondersRequiresHeaders
2468 }
2469 if verbose {
2470 c.sendOK()
2471 }
2472 case ROUTER:
2473 // Delegate the rest of processing to the route
2474 return c.processRouteConnect(srv, arg, lang)
2475 case GATEWAY:
2476 // Delegate the rest of processing to the gateway
2477 return c.processGatewayConnect(arg)
2478 case LEAF:
2479 // Delegate the rest of processing to the leaf node
2480 return c.processLeafNodeConnect(srv, arg, lang)
2481 }
2482 return nil
2483 }
2484
2485 func (c *client) sendErrAndErr(err string) {
2486 c.sendErr(err)
2487 c.RateLimitErrorf(err)
2488 }
2489
2490 func (c *client) sendErrAndDebug(err string) {
2491 c.sendErr(err)
2492 c.RateLimitDebugf(err)
2493 }
2494
2495 func (c *client) authTimeout() {
2496 c.sendErrAndDebug("Authentication Timeout")
2497 c.closeConnection(AuthenticationTimeout)
2498 }
2499
2500 func (c *client) authExpired() {
2501 c.sendErrAndDebug("User Authentication Expired")
2502 c.closeConnection(AuthenticationExpired)
2503 }
2504
2505 func (c *client) accountAuthExpired() {
2506 c.sendErrAndDebug("Account Authentication Expired")
2507 c.closeConnection(AuthenticationExpired)
2508 }
2509
2510 func (c *client) authViolation() {
2511 authErr := c.getAuthError()
2512 if authErr == nil {
2513 authErr = ErrAuthentication
2514 }
2515 reason := getAuthErrClosedState(authErr)
2516
2517 var s *Server
2518 if s = c.srv; s != nil {
2519 defer s.sendAuthErrorEvent(c, reason.String())
2520 if c.getRawAuthUser() != _EMPTY_ {
2521 c.Errorf("%v - %s", ErrAuthentication, c.getAuthUser())
2522 } else {
2523 c.Errorf(ErrAuthentication.Error())
2524 }
2525 }
2526 if c.isMqtt() {
2527 c.mqttEnqueueConnAck(mqttConnAckRCNotAuthorized, false)
2528 } else {
2529 // Send this to client, regardless of the authErr override.
2530 c.sendErr("Authorization Violation")
2531 }
2532 c.closeConnection(reason)
2533 }
2534
2535 func (c *client) maxAccountConnExceeded() {
2536 c.sendErrAndErr(ErrTooManyAccountConnections.Error())
2537 c.closeConnection(MaxAccountConnectionsExceeded)
2538 }
2539
2540 func (c *client) maxConnExceeded() {
2541 c.sendErrAndErr(ErrTooManyConnections.Error())
2542 c.closeConnection(MaxConnectionsExceeded)
2543 }
2544
2545 func (c *client) maxSubsExceeded() {
2546 if c.acc.shouldLogMaxSubErr() {
2547 c.Errorf(ErrTooManySubs.Error())
2548 }
2549 c.sendErr(ErrTooManySubs.Error())
2550 }
2551
2552 func (c *client) maxPayloadViolation(sz int, max int32) {
2553 c.Errorf("%s: %d vs %d", ErrMaxPayload.Error(), sz, max)
2554 c.sendErr("Maximum Payload Violation")
2555 c.closeConnection(MaxPayloadExceeded)
2556 }
2557
2558 // queueOutbound queues data for a clientconnection.
2559 // Lock should be held.
2560 func (c *client) queueOutbound(data []byte) {
2561 // Do not keep going if closed
2562 if c.isClosed() {
2563 return
2564 }
2565
2566 // Add to pending bytes total.
2567 c.out.pb += int64(len(data))
2568
2569 // Take a copy of the slice ref so that we can chop bits off the beginning
2570 // without affecting the original "data" slice.
2571 toBuffer := data
2572
2573 // All of the queued []byte have a fixed capacity, so if there's a []byte
2574 // at the tail of the buffer list that isn't full yet, we should top that
2575 // up first. This helps to ensure we aren't pulling more []bytes from the
2576 // pool than we need to.
2577 if len(c.out.nb) > 0 {
2578 last := &c.out.nb[len(c.out.nb)-1]
2579 if free := cap(*last) - len(*last); free > 0 {
2580 if l := len(toBuffer); l < free {
2581 free = l
2582 }
2583 *last = append(*last, toBuffer[:free]...)
2584 toBuffer = toBuffer[free:]
2585 }
2586 }
2587
2588 // Now we can push the rest of the data into new []bytes from the pool
2589 // in fixed size chunks. This ensures we don't go over the capacity of any
2590 // of the buffers and end up reallocating.
2591 for len(toBuffer) > 0 {
2592 new := nbPoolGet(len(toBuffer))
2593 n := copy(new[:cap(new)], toBuffer)
2594 c.out.nb = append(c.out.nb, new[:n])
2595 toBuffer = toBuffer[n:]
2596 }
2597
2598 // Check for slow consumer via pending bytes limit.
2599 // ok to return here, client is going away.
2600 if c.kind == CLIENT && c.out.pb > c.out.mp {
2601 // Perf wise, it looks like it is faster to optimistically add than
2602 // checking current pb+len(data) and then add to pb.
2603 c.out.pb -= int64(len(data))
2604
2605 // Increment the total and client's slow consumer counters.
2606 atomic.AddInt64(&c.srv.slowConsumers, 1)
2607 c.srv.scStats.clients.Add(1)
2608 if c.acc != nil {
2609 c.acc.stats.Lock()
2610 c.acc.stats.slowConsumers++
2611 c.acc.stats.Unlock()
2612 }
2613 c.Noticef("Slow Consumer Detected: MaxPending of %d Exceeded", c.out.mp)
2614 c.markConnAsClosed(SlowConsumerPendingBytes)
2615 return
2616 }
2617
2618 // Check here if we should create a stall channel if we are falling behind.
2619 // We do this here since if we wait for consumer's writeLoop it could be
2620 // too late with large number of fan in producers.
2621 // If the outbound connection is > 75% of maximum pending allowed, create a stall gate.
2622 if c.out.pb > c.out.mp/4*3 && c.out.stc == nil {
2623 c.out.stc = make(chan struct{})
2624 }
2625 }
2626
2627 // Assume the lock is held upon entry.
2628 func (c *client) enqueueProtoAndFlush(proto []byte, doFlush bool) {
2629 if c.isClosed() {
2630 return
2631 }
2632 c.queueOutbound(proto)
2633 if !(doFlush && c.flushOutbound()) {
2634 c.flushSignal()
2635 }
2636 }
2637
2638 // Queues and then flushes the connection. This should only be called when
2639 // the writeLoop cannot be started yet. Use enqueueProto() otherwise.
2640 // Lock is held on entry.
2641 func (c *client) sendProtoNow(proto []byte) {
2642 c.enqueueProtoAndFlush(proto, true)
2643 }
2644
2645 // Enqueues the given protocol and signal the writeLoop if necessary.
2646 // Lock is held on entry.
2647 func (c *client) enqueueProto(proto []byte) {
2648 c.enqueueProtoAndFlush(proto, false)
2649 }
2650
2651 // Assume the lock is held upon entry.
2652 func (c *client) sendPong() {
2653 if c.trace {
2654 c.traceOutOp("PONG", nil)
2655 }
2656 c.enqueueProto([]byte(pongProto))
2657 }
2658
2659 // Used to kick off a RTT measurement for latency tracking.
2660 func (c *client) sendRTTPing() bool {
2661 c.mu.Lock()
2662 sent := c.sendRTTPingLocked()
2663 c.mu.Unlock()
2664 return sent
2665 }
2666
2667 // Used to kick off a RTT measurement for latency tracking.
2668 // This is normally called only when the caller has checked that
2669 // the c.rtt is 0 and wants to force an update by sending a PING.
2670 // Client lock held on entry.
2671 func (c *client) sendRTTPingLocked() bool {
2672 if c.isMqtt() {
2673 return false
2674 }
2675 // Most client libs send a CONNECT+PING and wait for a PONG from the
2676 // server. So if firstPongSent flag is set, it is ok for server to
2677 // send the PING. But in case we have client libs that don't do that,
2678 // allow the send of the PING if more than 2 secs have elapsed since
2679 // the client TCP connection was accepted.
2680 if !c.isClosed() &&
2681 (c.flags.isSet(firstPongSent) || time.Since(c.start) > maxNoRTTPingBeforeFirstPong) {
2682 c.sendPing()
2683 return true
2684 }
2685 return false
2686 }
2687
2688 // Assume the lock is held upon entry.
2689 func (c *client) sendPing() {
2690 c.rttStart = time.Now().UTC()
2691 c.ping.out++
2692 if c.trace {
2693 c.traceOutOp("PING", nil)
2694 }
2695 c.enqueueProto([]byte(pingProto))
2696 }
2697
2698 // Generates the INFO to be sent to the client with the client ID included.
2699 // info arg will be copied since passed by value.
2700 // Assume lock is held.
2701 func (c *client) generateClientInfoJSON(info Info, includeClientIP bool) []byte {
2702 info.CID = c.cid
2703 if includeClientIP {
2704 info.ClientIP = c.host
2705 }
2706 info.MaxPayload = atomic.LoadInt32(&c.mpay)
2707 if c.isWebsocket() {
2708 info.ClientConnectURLs = info.WSConnectURLs
2709 // Otherwise lame duck info can panic
2710 if c.srv != nil {
2711 ws := &c.srv.websocket
2712 info.TLSAvailable, info.TLSRequired = ws.tls, ws.tls
2713 info.Host, info.Port = ws.host, ws.port
2714 }
2715 }
2716 info.WSConnectURLs = nil
2717 return generateInfoJSON(&info)
2718 }
2719
2720 func (c *client) sendErr(err string) {
2721 c.mu.Lock()
2722 if c.trace {
2723 c.traceOutOp("-ERR", []byte(err))
2724 }
2725 if !c.isMqtt() {
2726 c.enqueueProto([]byte(fmt.Sprintf(errProto, err)))
2727 }
2728 c.mu.Unlock()
2729 }
2730
2731 func (c *client) sendOK() {
2732 c.mu.Lock()
2733 if c.trace {
2734 c.traceOutOp("OK", nil)
2735 }
2736 c.enqueueProto([]byte(okProto))
2737 c.mu.Unlock()
2738 }
2739
2740 func (c *client) processPing() {
2741 c.mu.Lock()
2742
2743 if c.isClosed() {
2744 c.mu.Unlock()
2745 return
2746 }
2747
2748 c.sendPong()
2749
2750 // Record this to suppress us sending one if this
2751 // is within a given time interval for activity.
2752 c.lastIn = time.Now()
2753
2754 // If not a CLIENT, we are done. Also the CONNECT should
2755 // have been received, but make sure it is so before proceeding
2756 if c.kind != CLIENT || !c.flags.isSet(connectReceived) {
2757 c.mu.Unlock()
2758 return
2759 }
2760
2761 // If we are here, the CONNECT has been received so we know
2762 // if this client supports async INFO or not.
2763 var (
2764 sendConnectInfo bool
2765 srv = c.srv
2766 )
2767 // For the first PING (so firstPongSet is false) and for clients
2768 // that support async INFO protocols, we will send one with ConnectInfo=true,
2769 // the name of the account the client is bound to, and if the
2770 // account is the system account.
2771 if !c.flags.isSet(firstPongSent) {
2772 // Flip the flag.
2773 c.flags.set(firstPongSent)
2774 // Evaluate if we should send the INFO protocol.
2775 sendConnectInfo = srv != nil && c.opts.Protocol >= ClientProtoInfo
2776 }
2777 c.mu.Unlock()
2778
2779 if sendConnectInfo {
2780 srv.mu.Lock()
2781 info := srv.copyInfo()
2782 c.mu.Lock()
2783 // Keep the in-process tls_required override from the initial INFO,
2784 // otherwise this async INFO would flip it back to true.
2785 if c.iproc && info.TLSRequired && !c.flags.isSet(didTLSFirst) {
2786 info.TLSRequired = false
2787 info.TLSAvailable = true
2788 }
2789 info.RemoteAccount = c.acc.Name
2790 info.IsSystemAccount = c.acc == srv.SystemAccount()
2791 info.ConnectInfo = true
2792 c.enqueueProto(c.generateClientInfoJSON(info, true))
2793 c.mu.Unlock()
2794 srv.mu.Unlock()
2795 }
2796 }
2797
2798 func (c *client) processPong() {
2799 c.mu.Lock()
2800 c.ping.out = 0
2801 c.rtt = computeRTT(c.rttStart)
2802 srv := c.srv
2803 reorderGWs := c.kind == GATEWAY && c.gw.outbound
2804 var ri *routeInfo
2805 // For a route with pooling, we may be instructed to start a new route.
2806 if c.kind == ROUTER && c.route != nil && c.route.startNewRoute != nil {
2807 ri = c.route.startNewRoute
2808 c.route.startNewRoute = nil
2809 }
2810 // If compression is currently active for a route/leaf connection, if the
2811 // compression configuration is s2_auto, check if we should change
2812 // the compression level.
2813 if c.kind == ROUTER && needsCompression(c.route.compression) {
2814 c.updateS2AutoCompressionLevel(&srv.getOpts().Cluster.Compression, &c.route.compression)
2815 } else if c.kind == LEAF && needsCompression(c.leaf.compression) {
2816 var co *CompressionOpts
2817 if r := c.leaf.remote; r != nil {
2818 co = &r.Compression
2819 } else {
2820 co = &srv.getOpts().LeafNode.Compression
2821 }
2822 c.updateS2AutoCompressionLevel(co, &c.leaf.compression)
2823 }
2824 c.mu.Unlock()
2825 if reorderGWs {
2826 srv.gateway.orderOutboundConnections()
2827 }
2828 if ri != nil {
2829 srv.startGoRoutine(func() {
2830 srv.connectToRoute(ri.url, ri.rtype, true, ri.gossipMode, _EMPTY_)
2831 })
2832 }
2833 }
2834
2835 // Select the s2 compression level based on the client's current RTT and the configured
2836 // RTT thresholds slice. If current level is different than selected one, save the
2837 // new compression level string and create a new s2 writer.
2838 // Lock held on entry.
2839 func (c *client) updateS2AutoCompressionLevel(co *CompressionOpts, compression *string) {
2840 if co.Mode != CompressionS2Auto {
2841 return
2842 }
2843 if cm := selectS2AutoModeBasedOnRTT(c.rtt, co.RTTThresholds); cm != *compression {
2844 *compression = cm
2845 c.out.cw = s2.NewWriter(nil, s2WriterOptions(cm)...)
2846 }
2847 }
2848
2849 // Will return the parts from the raw wire msg.
2850 // We return the `hdr` as a slice that is capped to the length of the headers
2851 // so that if the caller later tries to append to the returned header slice it
2852 // does not affect the message content.
2853 func (c *client) msgParts(data []byte) (hdr []byte, msg []byte) {
2854 if c != nil && c.pa.hdr > 0 {
2855 return data[:c.pa.hdr:c.pa.hdr], data[c.pa.hdr:]
2856 }
2857 return nil, data
2858 }
2859
2860 // Header pubs take form HPUB <subject> [reply] <hdr_len> <total_len>\r\n
2861 func (c *client) processHeaderPub(arg, remaining []byte) error {
2862 if !c.headers {
2863 return ErrMsgHeadersNotSupported
2864 }
2865
2866 // Unroll splitArgs to avoid runtime/heap issues
2867 a := [MAX_HPUB_ARGS][]byte{}
2868 args := a[:0]
2869 start := -1
2870 for i, b := range arg {
2871 switch b {
2872 case ' ', '\t':
2873 if start >= 0 {
2874 args = append(args, arg[start:i])
2875 start = -1
2876 }
2877 default:
2878 if start < 0 {
2879 start = i
2880 }
2881 }
2882 }
2883 if start >= 0 {
2884 args = append(args, arg[start:])
2885 }
2886
2887 c.pa.arg = arg
2888 switch len(args) {
2889 case 3:
2890 c.pa.subject = args[0]
2891 c.pa.reply = nil
2892 c.pa.hdr = parseSize(args[1])
2893 c.pa.size = parseSize(args[2])
2894 c.pa.hdb = args[1]
2895 c.pa.szb = args[2]
2896 case 4:
2897 c.pa.subject = args[0]
2898 c.pa.reply = args[1]
2899 c.pa.hdr = parseSize(args[2])
2900 c.pa.size = parseSize(args[3])
2901 c.pa.hdb = args[2]
2902 c.pa.szb = args[3]
2903 default:
2904 return fmt.Errorf("processHeaderPub Parse Error: %q", arg)
2905 }
2906 if c.pa.hdr < 0 {
2907 return fmt.Errorf("processHeaderPub Bad or Missing Header Size: %q", arg)
2908 }
2909 // If number overruns an int64, parseSize() will have returned a negative value
2910 if c.pa.size < 0 {
2911 return fmt.Errorf("processHeaderPub Bad or Missing Total Size: %q", arg)
2912 }
2913 if c.pa.hdr > c.pa.size {
2914 return fmt.Errorf("processHeaderPub Header Size larger then TotalSize: %q", arg)
2915 }
2916 maxPayload := atomic.LoadInt32(&c.mpay)
2917 // Use int64() to avoid int32 overrun...
2918 if maxPayload != jwt.NoLimit && int64(c.pa.size) > int64(maxPayload) {
2919 // If we are given the remaining read buffer (since we do blind reads
2920 // we may have the beginning of the message header/payload), we will
2921 // look for the tracing header and if found, we will generate a
2922 // trace event with the max payload ingress error.
2923 // Do this only for CLIENT connections.
2924 if c.kind == CLIENT && c.pa.hdr > 0 && len(remaining) > 0 {
2925 hdr := remaining[:min(len(remaining), c.pa.hdr)]
2926 c.sendMsgTraceIngressErrEvent(hdr, ErrMaxPayload)
2927 }
2928 c.maxPayloadViolation(c.pa.size, maxPayload)
2929 return ErrMaxPayload
2930 }
2931 if c.opts.Pedantic && !IsValidLiteralSubject(bytesToString(c.pa.subject)) {
2932 c.sendErr("Invalid Publish Subject")
2933 }
2934 return nil
2935 }
2936
2937 func (c *client) processPub(arg []byte) error {
2938 // Unroll splitArgs to avoid runtime/heap issues
2939 a := [MAX_PUB_ARGS][]byte{}
2940 args := a[:0]
2941 start := -1
2942 for i, b := range arg {
2943 switch b {
2944 case ' ', '\t':
2945 if start >= 0 {
2946 args = append(args, arg[start:i])
2947 start = -1
2948 }
2949 default:
2950 if start < 0 {
2951 start = i
2952 }
2953 }
2954 }
2955 if start >= 0 {
2956 args = append(args, arg[start:])
2957 }
2958
2959 c.pa.arg = arg
2960 switch len(args) {
2961 case 2:
2962 c.pa.subject = args[0]
2963 c.pa.reply = nil
2964 c.pa.size = parseSize(args[1])
2965 c.pa.szb = args[1]
2966 case 3:
2967 c.pa.subject = args[0]
2968 c.pa.reply = args[1]
2969 c.pa.size = parseSize(args[2])
2970 c.pa.szb = args[2]
2971 default:
2972 return fmt.Errorf("processPub Parse Error: %q", arg)
2973 }
2974 // If number overruns an int64, parseSize() will have returned a negative value
2975 if c.pa.size < 0 {
2976 return fmt.Errorf("processPub Bad or Missing Size: %q", arg)
2977 }
2978 maxPayload := atomic.LoadInt32(&c.mpay)
2979 // Use int64() to avoid int32 overrun...
2980 if maxPayload != jwt.NoLimit && int64(c.pa.size) > int64(maxPayload) {
2981 c.maxPayloadViolation(c.pa.size, maxPayload)
2982 return ErrMaxPayload
2983 }
2984 if c.opts.Pedantic && !IsValidLiteralSubject(bytesToString(c.pa.subject)) {
2985 c.sendErr("Invalid Publish Subject")
2986 }
2987 return nil
2988 }
2989
2990 func splitArg(arg []byte) [][]byte {
2991 a := [MAX_MSG_ARGS][]byte{}
2992 args := a[:0]
2993 start := -1
2994 for i, b := range arg {
2995 switch b {
2996 case ' ', '\t', '\r', '\n':
2997 if start >= 0 {
2998 args = append(args, arg[start:i])
2999 start = -1
3000 }
3001 default:
3002 if start < 0 {
3003 start = i
3004 }
3005 }
3006 }
3007 if start >= 0 {
3008 args = append(args, arg[start:])
3009 }
3010 return args
3011 }
3012
3013 func (c *client) parseSub(argo []byte, noForward bool) error {
3014 // Copy so we do not reference a potentially large buffer
3015 // FIXME(dlc) - make more efficient.
3016 arg := make([]byte, len(argo))
3017 copy(arg, argo)
3018 args := splitArg(arg)
3019 var (
3020 subject []byte
3021 queue []byte
3022 sid []byte
3023 )
3024 switch len(args) {
3025 case 2:
3026 subject = args[0]
3027 queue = nil
3028 sid = args[1]
3029 case 3:
3030 subject = args[0]
3031 queue = args[1]
3032 sid = args[2]
3033 default:
3034 return fmt.Errorf("processSub Parse Error: %q", arg)
3035 }
3036 // If there was an error, it has been sent to the client. We don't return an
3037 // error here to not close the connection as a parsing error.
3038 c.processSub(subject, queue, sid, nil, noForward)
3039 return nil
3040 }
3041
3042 func (c *client) processSub(subject, queue, bsid []byte, cb msgHandler, noForward bool) (*subscription, error) {
3043 return c.processSubEx(subject, queue, bsid, cb, noForward, false, false)
3044 }
3045
3046 func (c *client) processSubEx(subject, queue, bsid []byte, cb msgHandler, noForward, si, rsi bool) (*subscription, error) {
3047 // Create the subscription
3048 sub := &subscription{client: c, subject: subject, queue: queue, sid: bsid, icb: cb, si: si, rsi: rsi}
3049
3050 c.mu.Lock()
3051
3052 // Indicate activity.
3053 c.in.subs++
3054
3055 // Grab connection type, account and server info.
3056 kind := c.kind
3057 acc := c.acc
3058 srv := c.srv
3059
3060 sid := bytesToString(sub.sid)
3061
3062 // This check does not apply to SYSTEM or JETSTREAM or ACCOUNT clients (because they don't have a `nc`...)
3063 // When a connection is closed though, we set c.subs to nil. So check for the map to not be nil.
3064 if (c.isClosed() && !isInternalClient(kind)) || (c.subs == nil) {
3065 c.mu.Unlock()
3066 return nil, ErrConnectionClosed
3067 }
3068
3069 // Check permissions if applicable.
3070 if kind == CLIENT {
3071 // First do a pass whether queue subscription is valid. This does not necessarily
3072 // mean that it will not be able to plain subscribe.
3073 //
3074 // allow = ["foo"] -> can subscribe or queue subscribe to foo using any queue
3075 // allow = ["foo v1"] -> can only queue subscribe to 'foo v1', no plain subs allowed.
3076 // allow = ["foo", "foo v1"] -> can subscribe to 'foo' but can only queue subscribe to 'foo v1'
3077 //
3078 if sub.queue != nil {
3079 if !c.canSubscribe(string(sub.subject), string(sub.queue)) || string(sub.queue) == sysGroup {
3080 c.mu.Unlock()
3081 c.subPermissionViolation(sub)
3082 return nil, ErrSubscribePermissionViolation
3083 }
3084 } else if !c.canSubscribe(string(sub.subject)) {
3085 c.mu.Unlock()
3086 c.subPermissionViolation(sub)
3087 return nil, ErrSubscribePermissionViolation
3088 }
3089
3090 if opts := srv.getOpts(); opts != nil && opts.MaxSubTokens > 0 {
3091 if len(bytes.Split(sub.subject, []byte(tsep))) > int(opts.MaxSubTokens) {
3092 c.mu.Unlock()
3093 c.maxTokensViolation(sub)
3094 return nil, ErrTooManySubTokens
3095 }
3096 }
3097 }
3098
3099 // Check if we have a maximum on the number of subscriptions.
3100 if c.subsAtLimit() {
3101 c.mu.Unlock()
3102 c.maxSubsExceeded()
3103 return nil, ErrTooManySubs
3104 }
3105
3106 var updateGWs bool
3107 var err error
3108
3109 // Subscribe here.
3110 es := c.subs[sid]
3111 if es == nil {
3112 c.subs[sid] = sub
3113 if acc != nil && acc.sl != nil {
3114 err = acc.sl.Insert(sub)
3115 if err != nil {
3116 delete(c.subs, sid)
3117 } else {
3118 updateGWs = c.srv.gateway.enabled
3119 }
3120 }
3121 }
3122 // Unlocked from here onward
3123 c.mu.Unlock()
3124
3125 if err != nil {
3126 c.sendErr("Invalid Subject")
3127 return nil, ErrMalformedSubject
3128 } else if c.opts.Verbose && kind != SYSTEM {
3129 c.sendOK()
3130 }
3131
3132 // If it was already registered, return it.
3133 if es != nil {
3134 return es, nil
3135 }
3136
3137 // No account just return.
3138 if acc == nil {
3139 return sub, nil
3140 }
3141
3142 if err := c.addShadowSubscriptions(acc, sub); err != nil {
3143 c.Errorf(err.Error())
3144 }
3145
3146 if noForward {
3147 return sub, nil
3148 }
3149
3150 // If we are routing and this is a local sub, add to the route map for the associated account.
3151 if kind == CLIENT || kind == SYSTEM || kind == JETSTREAM || kind == ACCOUNT {
3152 srv.updateRouteSubscriptionMap(acc, sub, 1)
3153 if updateGWs {
3154 srv.gatewayUpdateSubInterest(acc.Name, sub, 1)
3155 }
3156 }
3157 // Now check on leafnode updates.
3158 acc.updateLeafNodes(sub, 1)
3159 return sub, nil
3160 }
3161
3162 // Used to pass stream import matches to addShadowSub
3163 type ime struct {
3164 im *streamImport
3165 overlapSubj string
3166 dyn bool
3167 }
3168
3169 // If the client's account has stream imports and there are matches for this
3170 // subscription's subject, then add shadow subscriptions in the other accounts
3171 // that export this subject.
3172 func (c *client) addShadowSubscriptions(acc *Account, sub *subscription) error {
3173 if acc == nil {
3174 return ErrMissingAccount
3175 }
3176
3177 var (
3178 _ims [16]ime
3179 ims = _ims[:0]
3180 imTsa [32]string
3181 tokens []string
3182 tsa [32]string
3183 hasWC bool
3184 tokensModified bool
3185 )
3186
3187 acc.mu.RLock()
3188 // If this is from a service import, ignore.
3189 if sub.si {
3190 acc.mu.RUnlock()
3191 return nil
3192 }
3193 subj := bytesToString(sub.subject)
3194 if len(acc.imports.streams) > 0 {
3195 tokens = tokenizeSubjectIntoSlice(tsa[:0], subj)
3196 for _, tk := range tokens {
3197 if tk == pwcs {
3198 hasWC = true
3199 break
3200 }
3201 }
3202 if !hasWC && tokens[len(tokens)-1] == fwcs {
3203 hasWC = true
3204 }
3205 }
3206 // Loop over the import subjects. We have 4 scenarios. If we have an
3207 // exact match or a superset match we should use the from field from
3208 // the import. If we are a subset or overlap, we have to dynamically calculate
3209 // the subject. On overlap, ime requires the overlap subject.
3210 for _, im := range acc.imports.streams {
3211 if im.invalid {
3212 continue
3213 }
3214 if subj == im.to {
3215 ims = append(ims, ime{im, _EMPTY_, false})
3216 continue
3217 }
3218 if tokensModified {
3219 // re-tokenize subj to overwrite modifications from a previous iteration
3220 tokens = tokenizeSubjectIntoSlice(tsa[:0], subj)
3221 tokensModified = false
3222 }
3223 imTokens := tokenizeSubjectIntoSlice(imTsa[:0], im.to)
3224
3225 if isSubsetMatchTokenized(tokens, imTokens) {
3226 ims = append(ims, ime{im, _EMPTY_, true})
3227 } else if hasWC {
3228 if isSubsetMatchTokenized(imTokens, tokens) {
3229 ims = append(ims, ime{im, _EMPTY_, false})
3230 } else {
3231 imTokensLen := len(imTokens)
3232 for i, t := range tokens {
3233 if i >= imTokensLen {
3234 break
3235 }
3236 if t == pwcs && imTokens[i] != fwcs {
3237 tokens[i] = imTokens[i]
3238 tokensModified = true
3239 }
3240 }
3241 tokensLen := len(tokens)
3242 lastIdx := tokensLen - 1
3243 if tokens[lastIdx] == fwcs {
3244 if imTokensLen >= tokensLen {
3245 // rewrite ">" in tokens to be more specific
3246 tokens[lastIdx] = imTokens[lastIdx]
3247 tokensModified = true
3248 if imTokensLen > tokensLen {
3249 // copy even more specific parts from import
3250 tokens = append(tokens, imTokens[tokensLen:]...)
3251 }
3252 }
3253 }
3254 if isSubsetMatchTokenized(tokens, imTokens) {
3255 // As isSubsetMatchTokenized was already called with tokens and imTokens,
3256 // we wouldn't be here if it where not for tokens being modified.
3257 // Hence, Join to re compute the subject string
3258 ims = append(ims, ime{im, strings.Join(tokens, tsep), true})
3259 }
3260 }
3261 }
3262 }
3263 acc.mu.RUnlock()
3264
3265 var shadow []*subscription
3266
3267 if len(ims) > 0 {
3268 shadow = make([]*subscription, 0, len(ims))
3269 }
3270
3271 // Now walk through collected stream imports that matched.
3272 for i := 0; i < len(ims); i++ {
3273 ime := &ims[i]
3274 // We will create a shadow subscription.
3275 nsub, err := c.addShadowSub(sub, ime)
3276 if err != nil {
3277 return err
3278 }
3279 shadow = append(shadow, nsub)
3280 }
3281
3282 if shadow != nil {
3283 c.mu.Lock()
3284 sub.shadow = shadow
3285 c.mu.Unlock()
3286 }
3287
3288 return nil
3289 }
3290
3291 // Add in the shadow subscription.
3292 func (c *client) addShadowSub(sub *subscription, ime *ime) (*subscription, error) {
3293 c.mu.Lock()
3294 nsub := *sub // copy
3295 c.mu.Unlock()
3296
3297 im := ime.im
3298 nsub.im = im
3299
3300 if !im.usePub && ime.dyn && im.tr != nil {
3301 if im.rtr == nil {
3302 im.rtr = im.tr.reverse()
3303 }
3304 s := bytesToString(nsub.subject)
3305 if ime.overlapSubj != _EMPTY_ {
3306 s = ime.overlapSubj
3307 }
3308 subj := im.rtr.TransformSubject(s)
3309
3310 nsub.subject = []byte(subj)
3311 } else if !im.usePub || (im.usePub && ime.overlapSubj != _EMPTY_) || !ime.dyn {
3312 if ime.overlapSubj != _EMPTY_ {
3313 nsub.subject = []byte(ime.overlapSubj)
3314 } else {
3315 nsub.subject = []byte(im.from)
3316 }
3317 }
3318 // Else use original subject
3319
3320 c.Debugf("Creating import subscription on %q from account %q", nsub.subject, im.acc.Name)
3321
3322 if err := im.acc.sl.Insert(&nsub); err != nil {
3323 errs := fmt.Sprintf("Could not add shadow import subscription for account %q", im.acc.Name)
3324 c.Debugf(errs)
3325 return nil, errors.New(errs)
3326 }
3327
3328 // Update our route map here. But only if we are not a leaf node or a hub leafnode.
3329 if c.kind != LEAF || c.isHubLeafNode() {
3330 c.srv.updateRemoteSubscription(im.acc, &nsub, 1)
3331 } else if c.kind == LEAF {
3332 // Update all leafnodes that connect to this server. Note that we could have
3333 // used the updateLeafNodes() function since when it does invoke updateSmap()
3334 // this function already takes care of not sending to a spoke leafnode since
3335 // the `nsub` here is already from a spoke leafnode, but to be explicit, we
3336 // use this version that updates only leafnodes that connect to this server.
3337 im.acc.updateLeafNodesEx(&nsub, 1, true)
3338 }
3339
3340 return &nsub, nil
3341 }
3342
3343 // canSubscribeInternal determines if the client is authorized to subscribe to
3344 // the given subject. Assumes caller is holding at least a read lock.
3345 func (c *client) canSubscribeInternal(subject string, optQueue ...string) bool {
3346 if c.perms == nil {
3347 return true
3348 }
3349
3350 allowed, checkAllow := true, true
3351
3352 // Optional queue group.
3353 var queue string
3354 if len(optQueue) > 0 {
3355 queue = optQueue[0]
3356 }
3357
3358 // For CLIENT connections that are MQTT we will implicitly allow anything that starts with
3359 // the "$MQTT.sub." or "$MQTT.deliver.pubrel." prefix. For other types of connections, we
3360 // will implicitly allow anything that starts with the full "$MQTT." prefix. However,
3361 // we don't just return here, we skip the check for "allow" but will check "deny".
3362 if (c.isMqtt() && (strings.HasPrefix(subject, mqttSubPrefix) || strings.HasPrefix(subject, mqttPubRelDeliverySubjectPrefix))) ||
3363 (c.kind != CLIENT && strings.HasPrefix(subject, mqttPrefix)) {
3364 checkAllow = false
3365 }
3366 // Check allow list. If no allow list that means all are allowed. Deny can overrule.
3367 if checkAllow && c.perms.sub.allow != nil {
3368 r := c.perms.sub.allow.Match(subject)
3369 allowed = len(r.psubs) > 0
3370 if queue != _EMPTY_ && len(r.qsubs) > 0 {
3371 // If the queue appears in the allow list, then DO allow.
3372 allowed = queueMatches(queue, r.qsubs)
3373 }
3374 // Leafnodes operate slightly differently in that they allow broader scoped subjects.
3375 // They will prune based on publish perms before sending to a leafnode client.
3376 if !allowed && c.kind == LEAF && subjectHasWildcard(subject) {
3377 r := c.perms.sub.allow.ReverseMatch(subject)
3378 allowed = len(r.psubs) != 0
3379 }
3380 }
3381 // If we have a deny list and we think we are allowed, check that as well.
3382 if allowed && c.perms.sub.deny != nil {
3383 r := c.perms.sub.deny.Match(subject)
3384 allowed = len(r.psubs) == 0
3385
3386 if allowed && queue != _EMPTY_ && len(r.qsubs) > 0 {
3387 // If the queue appears in the deny list, then DO NOT allow.
3388 allowed = !queueMatches(queue, r.qsubs)
3389 }
3390 }
3391 return allowed
3392 }
3393
3394 // canSubscribe determines if the client is authorized to subscribe to the
3395 // given subject and initializes the delivery-time deny filter when needed.
3396 // Assumes caller is holding the write lock.
3397 func (c *client) canSubscribe(subject string, optQueue ...string) bool {
3398 if !c.canSubscribeInternal(subject, optQueue...) {
3399 return false
3400 }
3401 c.loadMsgDenyFilterIfNeeded(subject, len(optQueue) > 0 && optQueue[0] != _EMPTY_)
3402 return true
3403 }
3404
3405 // Initializes the delivery-time deny filter when a wildcard subscription, or
3406 // an exact queue subscription, can overlap a deny entry. Assumes caller is
3407 // holding the write lock.
3408 func (c *client) loadMsgDenyFilterIfNeeded(subject string, hasQueue bool) {
3409 // We use the actual subscription to signal us to spin up the deny mperms
3410 // and cache. We check if the subject is a wildcard that intersects any of
3411 // the deny clauses.
3412 // FIXME(dlc) - We could be smarter and track when these go away and remove.
3413 if c.mperms == nil && (hasQueue || subjectHasWildcard(subject)) {
3414 // Whip through the deny array and check if this wildcard subject can
3415 // overlap with any denied deliveries.
3416 for _, sub := range c.darray {
3417 if SubjectsCollide(bytesToString(sub.subject), subject) {
3418 c.loadMsgDenyFilter()
3419 break
3420 }
3421 }
3422 }
3423 }
3424
3425 func queueMatches(queue string, qsubs [][]*subscription) bool {
3426 if len(qsubs) == 0 {
3427 return true
3428 }
3429 for _, qsub := range qsubs {
3430 qs := qsub[0]
3431 qname := bytesToString(qs.queue)
3432
3433 // NOTE: '*' and '>' tokens can also be valid
3434 // queue names so we first check against the
3435 // literal name. e.g. v1.* == v1.*
3436 if queue == qname || (subjectHasWildcard(qname) && subjectIsSubsetMatch(queue, qname)) {
3437 return true
3438 }
3439 }
3440 return false
3441 }
3442
3443 // Low level unsubscribe for a given client.
3444 func (c *client) unsubscribe(acc *Account, sub *subscription, force, remove bool) {
3445 if s := c.srv; s != nil && s.isShuttingDown() {
3446 return
3447 }
3448
3449 c.mu.Lock()
3450 if !force && sub.max > 0 && sub.nm < sub.max {
3451 c.Debugf("Deferring actual UNSUB(%s): %d max, %d received", sub.subject, sub.max, sub.nm)
3452 c.mu.Unlock()
3453 return
3454 }
3455
3456 if c.trace {
3457 c.traceOp("<-> %s", "DELSUB", sub.sid)
3458 }
3459
3460 // Remove accounting if requested. This will be false when we close a connection
3461 // with open subscriptions.
3462 if remove {
3463 delete(c.subs, bytesToString(sub.sid))
3464 if acc != nil {
3465 acc.sl.Remove(sub)
3466 }
3467 }
3468
3469 // Check to see if we have shadow subscriptions.
3470 var updateRoute bool
3471 var isSpokeLeaf bool
3472 shadowSubs := sub.shadow
3473 sub.shadow = nil
3474 if len(shadowSubs) > 0 {
3475 isSpokeLeaf = c.isSpokeLeafNode()
3476 updateRoute = !isSpokeLeaf && (c.kind == CLIENT || c.kind == SYSTEM || c.kind == LEAF || c.kind == JETSTREAM) && c.srv != nil
3477 }
3478 sub.close()
3479 c.mu.Unlock()
3480
3481 // Process shadow subs if we have them.
3482 for _, nsub := range shadowSubs {
3483 if err := nsub.im.acc.sl.Remove(nsub); err != nil {
3484 c.Debugf("Could not remove shadow import subscription for account %q", nsub.im.acc.Name)
3485 }
3486 if updateRoute {
3487 c.srv.updateRemoteSubscription(nsub.im.acc, nsub, -1)
3488 } else if isSpokeLeaf {
3489 nsub.im.acc.updateLeafNodesEx(nsub, -1, true)
3490 }
3491 }
3492
3493 // Now check to see if this was part of a respMap entry for service imports.
3494 // We can skip subscriptions on reserved replies.
3495 if acc != nil && !isReservedReply(sub.subject) {
3496 acc.checkForReverseEntry(string(sub.subject), nil, true)
3497 }
3498 }
3499
3500 func (c *client) processUnsub(arg []byte) error {
3501 args := splitArg(arg)
3502 var sid []byte
3503 max := int64(-1)
3504
3505 switch len(args) {
3506 case 1:
3507 sid = args[0]
3508 case 2:
3509 sid = args[0]
3510 max = int64(parseSize(args[1]))
3511 default:
3512 return fmt.Errorf("processUnsub Parse Error: %q", arg)
3513 }
3514
3515 var sub *subscription
3516 var ok, unsub bool
3517
3518 c.mu.Lock()
3519
3520 // Indicate activity.
3521 c.in.subs++
3522
3523 // Grab connection type.
3524 kind := c.kind
3525 srv := c.srv
3526 var acc *Account
3527
3528 updateGWs := false
3529 if sub, ok = c.subs[string(sid)]; ok {
3530 acc = c.acc
3531 if max > 0 && max > sub.nm {
3532 sub.max = max
3533 } else {
3534 // Clear it here to override
3535 sub.max = 0
3536 unsub = true
3537 }
3538 updateGWs = srv.gateway.enabled
3539 }
3540 c.mu.Unlock()
3541
3542 if c.opts.Verbose {
3543 c.sendOK()
3544 }
3545
3546 if unsub {
3547 c.unsubscribe(acc, sub, false, true)
3548 if acc != nil && (kind == CLIENT || kind == SYSTEM || kind == ACCOUNT || kind == JETSTREAM) {
3549 srv.updateRouteSubscriptionMap(acc, sub, -1)
3550 if updateGWs {
3551 srv.gatewayUpdateSubInterest(acc.Name, sub, -1)
3552 }
3553 }
3554 // Now check on leafnode updates.
3555 acc.updateLeafNodes(sub, -1)
3556 }
3557
3558 return nil
3559 }
3560
3561 // checkDenySub will check if we are allowed to deliver this message in the
3562 // presence of deny clauses for subscriptions. Deny clauses will not prevent
3563 // larger scoped wildcard subscriptions, so we need to check at delivery time.
3564 // Lock should be held.
3565 func (c *client) checkDenySub(subject, queue string) bool {
3566 key := msgDenyKey{subject, queue}
3567 if denied, ok := c.mperms.dcache[key]; ok {
3568 return denied
3569 }
3570 r := c.mperms.deny.Match(subject)
3571 denied := len(r.psubs) != 0
3572 if !denied && queue != _EMPTY_ && len(r.qsubs) != 0 {
3573 denied = queueMatches(queue, r.qsubs)
3574 }
3575 c.mperms.dcache[key] = denied
3576 if len(c.mperms.dcache) > maxDenyPermCacheSize {
3577 c.pruneDenyCache()
3578 }
3579 return denied
3580 }
3581
3582 // Create a message header for routes or leafnodes. Header and origin cluster aware.
3583 func (c *client) msgHeaderForRouteOrLeaf(subj, reply []byte, rt *routeTarget, acc *Account) []byte {
3584 hasHeader := c.pa.hdr > 0
3585 subclient := rt.sub.client
3586 canReceiveHeader := subclient.headers
3587
3588 mh := c.msgb[:msgHeadProtoLen]
3589 kind := subclient.kind
3590 var lnoc bool
3591
3592 if kind == ROUTER {
3593 // If we are coming from a leaf with an origin cluster we need to handle differently
3594 // if we can. We will send a route based LMSG which has origin cluster and headers
3595 // by default.
3596 if c.kind == LEAF && c.remoteCluster() != _EMPTY_ {
3597 subclient.mu.Lock()
3598 lnoc = subclient.route.lnoc
3599 subclient.mu.Unlock()
3600 }
3601 if lnoc {
3602 mh[0] = 'L'
3603 mh = append(mh, c.remoteCluster()...)
3604 mh = append(mh, ' ')
3605 } else {
3606 // Router (and Gateway) nodes are RMSG. Set here since leafnodes may rewrite.
3607 mh[0] = 'R'
3608 }
3609 if len(subclient.route.accName) == 0 {
3610 mh = append(mh, acc.Name...)
3611 mh = append(mh, ' ')
3612 }
3613 } else {
3614 // Leaf nodes are LMSG
3615 mh[0] = 'L'
3616 // Remap subject if its a shadow subscription, treat like a normal client.
3617 if rt.sub.im != nil {
3618 if rt.sub.im.tr != nil {
3619 to := rt.sub.im.tr.TransformSubject(bytesToString(subj))
3620 subj = []byte(to)
3621 } else if !rt.sub.im.usePub {
3622 subj = []byte(rt.sub.im.to)
3623 }
3624 }
3625 }
3626 mh = append(mh, subj...)
3627 mh = append(mh, ' ')
3628
3629 if len(rt.qs) > 0 {
3630 if len(reply) > 0 {
3631 mh = append(mh, "+ "...) // Signal that there is a reply.
3632 mh = append(mh, reply...)
3633 mh = append(mh, ' ')
3634 } else {
3635 mh = append(mh, "| "...) // Only queues
3636 }
3637 mh = append(mh, rt.qs...)
3638 } else if len(reply) > 0 {
3639 mh = append(mh, reply...)
3640 mh = append(mh, ' ')
3641 }
3642
3643 if lnoc {
3644 // leafnode origin LMSG always have a header entry even if zero.
3645 if c.pa.hdr <= 0 {
3646 mh = append(mh, '0')
3647 } else {
3648 mh = append(mh, c.pa.hdb...)
3649 }
3650 mh = append(mh, ' ')
3651 mh = append(mh, c.pa.szb...)
3652 } else if hasHeader {
3653 if canReceiveHeader {
3654 mh[0] = 'H'
3655 mh = append(mh, c.pa.hdb...)
3656 mh = append(mh, ' ')
3657 mh = append(mh, c.pa.szb...)
3658 } else {
3659 // If we are here we need to truncate the payload size
3660 nsz := strconv.Itoa(c.pa.size - c.pa.hdr)
3661 mh = append(mh, nsz...)
3662 }
3663 } else {
3664 mh = append(mh, c.pa.szb...)
3665 }
3666 return append(mh, _CRLF_...)
3667 }
3668
3669 // Create a message header for clients. Header aware.
3670 func (c *client) msgHeader(subj, reply []byte, sub *subscription) []byte {
3671 // See if we should do headers. We have to have a headers msg and
3672 // the client we are going to deliver to needs to support headers as well.
3673 hasHeader := c.pa.hdr > 0
3674 canReceiveHeader := sub.client != nil && sub.client.headers
3675
3676 var mh []byte
3677 if hasHeader && canReceiveHeader {
3678 mh = c.msgb[:msgHeadProtoLen]
3679 mh[0] = 'H'
3680 } else {
3681 mh = c.msgb[1:msgHeadProtoLen]
3682 }
3683 mh = append(mh, subj...)
3684 mh = append(mh, ' ')
3685
3686 if len(sub.sid) > 0 {
3687 mh = append(mh, sub.sid...)
3688 mh = append(mh, ' ')
3689 }
3690 if reply != nil {
3691 mh = append(mh, reply...)
3692 mh = append(mh, ' ')
3693 }
3694 if hasHeader {
3695 if canReceiveHeader {
3696 mh = append(mh, c.pa.hdb...)
3697 mh = append(mh, ' ')
3698 mh = append(mh, c.pa.szb...)
3699 } else {
3700 // If we are here we need to truncate the payload size
3701 nsz := strconv.Itoa(c.pa.size - c.pa.hdr)
3702 mh = append(mh, nsz...)
3703 }
3704 } else {
3705 mh = append(mh, c.pa.szb...)
3706 }
3707 mh = append(mh, _CRLF_...)
3708 return mh
3709 }
3710
3711 func (c *client) stalledWait(producer *client) {
3712 // Check to see if we have exceeded our total wait time per readLoop invocation.
3713 if producer.in.tst > stallTotalAllowed {
3714 return
3715 }
3716
3717 // Grab stall channel which the slow consumer will close when caught up.
3718 stall := c.out.stc
3719
3720 // Calculate stall time.
3721 ttl := stallClientMinDuration
3722 if c.out.pb >= c.out.mp {
3723 ttl = stallClientMaxDuration
3724 }
3725
3726 c.mu.Unlock()
3727 defer c.mu.Lock()
3728
3729 // Track per client and total client stalls.
3730 atomic.AddInt64(&c.stalls, 1)
3731 if c.srv != nil {
3732 atomic.AddInt64(&c.srv.stalls, 1)
3733 }
3734
3735 // Now check if we are close to total allowed.
3736 if producer.in.tst+ttl > stallTotalAllowed {
3737 ttl = stallTotalAllowed - producer.in.tst
3738 }
3739 delay := time.NewTimer(ttl)
3740 defer delay.Stop()
3741
3742 start := time.Now()
3743 select {
3744 case <-stall:
3745 case <-delay.C:
3746 producer.Debugf("Timed out of fast producer stall (%v)", ttl)
3747 }
3748 producer.in.tst += time.Since(start)
3749 }
3750
3751 // Used to treat maps as efficient set
3752 var needFlush = struct{}{}
3753
3754 // deliverMsg will deliver a message to a matching subscription and its underlying client.
3755 // We process all connection/client types. mh is the part that will be protocol/client specific.
3756 func (c *client) deliverMsg(prodIsMQTT bool, sub *subscription, acc *Account, subject, reply, mh, msg []byte, gwrply bool) bool {
3757 // Check if message tracing is enabled.
3758 mt, traceOnly := c.isMsgTraceEnabled()
3759
3760 client := sub.client
3761 // Check sub client and check echo. Only do this if not a service import.
3762 if client == nil || (c == client && !client.echo && !sub.si && !sub.rsi) {
3763 if client != nil && mt != nil {
3764 client.mu.Lock()
3765 mt.addEgressEvent(client, sub, errMsgTraceNoEcho)
3766 client.mu.Unlock()
3767 }
3768 return false
3769 }
3770
3771 client.mu.Lock()
3772
3773 // Check if we have a subscribe deny clause. This will trigger us to check the subject
3774 // for a match against the denied subjects.
3775 if client.mperms != nil && client.checkDenySub(string(subject), bytesToString(sub.queue)) {
3776 mt.addEgressEvent(client, sub, errMsgTraceSubDeny)
3777 client.mu.Unlock()
3778 return false
3779 }
3780
3781 // New race detector forces this now.
3782 if sub.isClosed() {
3783 mt.addEgressEvent(client, sub, errMsgTraceSubClosed)
3784 client.mu.Unlock()
3785 return false
3786 }
3787
3788 // Check if we are a leafnode and have perms to check.
3789 if client.kind == LEAF && client.perms != nil {
3790 subjectToCheck, _ := getGWRoutedSubjectOrSelf(subject)
3791 if !client.pubAllowedFullCheck(string(subjectToCheck), true, true) {
3792 mt.addEgressEvent(client, sub, errMsgTracePubViolation)
3793 client.mu.Unlock()
3794 client.Debugf("Not permitted to deliver to %q", subjectToCheck)
3795 return false
3796 }
3797 }
3798
3799 var mtErr string
3800 if mt != nil {
3801 // For non internal subscription, and if the remote does not support
3802 // the tracing feature...
3803 if sub.icb == nil && !client.msgTraceSupport() {
3804 if traceOnly {
3805 // We are not sending the message at all because the user
3806 // expects a trace-only and the remote does not support
3807 // tracing, which means that it would process/deliver this
3808 // message, which may break applications.
3809 // Add the Egress with the no-support error message.
3810 mt.addEgressEvent(client, sub, errMsgTraceOnlyNoSupport)
3811 client.mu.Unlock()
3812 return false
3813 }
3814 // If we are doing delivery, we will still forward the message,
3815 // but we add an error to the Egress event to hint that one should
3816 // not expect a tracing event from that remote.
3817 mtErr = errMsgTraceNoSupport
3818 }
3819 // For ROUTER, GATEWAY and LEAF, even if we intend to do tracing only,
3820 // we will still deliver the message. The remote side will
3821 // generate an event based on what happened on that server.
3822 if traceOnly && (client.kind == ROUTER || client.kind == GATEWAY || client.kind == LEAF) {
3823 traceOnly = false
3824 }
3825 // If we skip delivery and this is not for a service import, we are done.
3826 if traceOnly && (sub.icb == nil || c.noIcb) {
3827 mt.addEgressEvent(client, sub, _EMPTY_)
3828 client.mu.Unlock()
3829 // Although the message is not actually delivered, for the
3830 // purpose of "didDeliver", we need to return "true" here.
3831 return true
3832 }
3833 }
3834
3835 srv := client.srv
3836
3837 // We don't want to bump the number of delivered messages to the subscription
3838 // if we are doing trace-only (since really we are not sending it to the sub).
3839 if !traceOnly {
3840 sub.nm++
3841 }
3842
3843 // Check if we should auto-unsubscribe.
3844 if sub.max > 0 {
3845 if client.kind == ROUTER && sub.nm >= sub.max {
3846 // The only router based messages that we will see here are remoteReplies.
3847 // We handle these slightly differently.
3848 defer client.removeReplySub(sub)
3849 } else {
3850 // For routing..
3851 shouldForward := client.kind == CLIENT || client.kind == SYSTEM && client.srv != nil
3852 // If we are at the exact number, unsubscribe but
3853 // still process the message in hand, otherwise
3854 // unsubscribe and drop message on the floor.
3855 if sub.nm == sub.max {
3856 client.Debugf("Auto-unsubscribe limit of %d reached for sid '%s'", sub.max, sub.sid)
3857 // Due to defer, reverse the code order so that execution
3858 // is consistent with other cases where we unsubscribe.
3859 if shouldForward {
3860 defer srv.updateRemoteSubscription(client.acc, sub, -1)
3861 }
3862 defer client.unsubscribe(client.acc, sub, true, true)
3863 } else if sub.nm > sub.max {
3864 client.Debugf("Auto-unsubscribe limit [%d] exceeded", sub.max)
3865 mt.addEgressEvent(client, sub, errMsgTraceAutoSubExceeded)
3866 client.mu.Unlock()
3867 client.unsubscribe(client.acc, sub, true, true)
3868 if shouldForward {
3869 srv.updateRemoteSubscription(client.acc, sub, -1)
3870 }
3871 return false
3872 }
3873 }
3874 }
3875
3876 // Check here if we have a header with our message. If this client can not
3877 // support we need to strip the headers from the payload.
3878 // The actual header would have been processed correctly for us, so just
3879 // need to update payload.
3880 hdrSize := c.pa.hdr
3881 if c.pa.hdr > 0 && !sub.client.headers {
3882 msg = msg[c.pa.hdr:]
3883 }
3884
3885 // Update statistics
3886
3887 // The msg includes the CR_LF, so pull back out for accounting.
3888 msgSize := int64(len(msg))
3889 // MQTT producers send messages without CR_LF, so don't remove it for them.
3890 if !prodIsMQTT {
3891 msgSize -= int64(LEN_CR_LF)
3892 }
3893
3894 // We do not update the outbound stats if we are doing trace only since
3895 // this message will not be sent out.
3896 // Also do not update on internal callbacks.
3897 if !traceOnly && sub.icb == nil {
3898 // No atomic needed since accessed under client lock.
3899 // Monitor is reading those also under client's lock.
3900 client.outMsgs++
3901 client.outBytes += msgSize
3902 }
3903
3904 // Check for internal subscriptions.
3905 if sub.icb != nil && !c.noIcb {
3906 if gwrply {
3907 // We will store in the account, not the client since it will likely
3908 // be a different client that will send the reply.
3909 srv.trackGWReply(nil, client.acc, reply, c.pa.reply)
3910 }
3911 client.mu.Unlock()
3912
3913 // For service imports, track if we delivered.
3914 didDeliver := true
3915
3916 // Internal account clients are for service imports and need the '\r\n'.
3917 start := time.Now()
3918 if client.kind == ACCOUNT {
3919 sub.icb(sub, c, acc, string(subject), string(reply), msg)
3920 // If we are a service import check to make sure we delivered the message somewhere.
3921 if sub.si {
3922 didDeliver = c.pa.delivered
3923 }
3924 } else {
3925 sub.icb(sub, c, acc, string(subject), string(reply), msg[:msgSize])
3926 }
3927 if dur := time.Since(start); dur >= readLoopReportThreshold {
3928 srv.Warnf("Internal subscription on %q took too long: %v", subject, dur)
3929 }
3930
3931 return didDeliver
3932 }
3933
3934 // If we are a client and we detect that the consumer we are
3935 // sending to is in a stalled state, go ahead and wait here
3936 // with a limit.
3937 if c.kind == CLIENT && client.out.stc != nil {
3938 if srv.getOpts().NoFastProducerStall {
3939 mt.addEgressEvent(client, sub, errMsgTraceFastProdNoStall)
3940 client.mu.Unlock()
3941 return false
3942 }
3943 client.stalledWait(c)
3944 }
3945
3946 // Check for closed connection
3947 if client.isClosed() {
3948 mt.addEgressEvent(client, sub, errMsgTraceClientClosed)
3949 client.mu.Unlock()
3950 return false
3951 }
3952
3953 // We have passed cases where we could possibly fail to deliver.
3954 // Do not call for service-import.
3955 if mt != nil && sub.icb == nil {
3956 mt.addEgressEvent(client, sub, mtErr)
3957 }
3958
3959 // Do a fast check here to see if we should be tracking this from a latency
3960 // perspective. This will be for a request being received for an exported service.
3961 // This needs to be from a non-client (otherwise tracking happens at requestor).
3962 //
3963 // Also this check captures if the original reply (c.pa.reply) is a GW routed
3964 // reply (since it is known to be > minReplyLen). If that is the case, we need to
3965 // track the binding between the routed reply and the reply set in the message
3966 // header (which is c.pa.reply without the GNR routing prefix).
3967 if client.kind == CLIENT && len(c.pa.reply) > minReplyLen {
3968 if gwrply {
3969 // Note that we keep track of the GW routed reply in the destination
3970 // connection (`client`). The routed reply subject is in `c.pa.reply`,
3971 // should that change, we would have to pass the GW routed reply as
3972 // a parameter of deliverMsg().
3973 srv.trackGWReply(client, nil, reply, c.pa.reply)
3974 }
3975
3976 // If we do not have a registered RTT queue that up now.
3977 if client.rtt == 0 {
3978 client.sendRTTPingLocked()
3979 }
3980 // FIXME(dlc) - We may need to optimize this.
3981 // We will have tagged this with a suffix ('.T') if we are tracking. This is
3982 // needed from sampling. Not all will be tracked.
3983 if c.kind != CLIENT && isTrackedReply(c.pa.reply) {
3984 client.trackRemoteReply(string(subject), string(c.pa.reply))
3985 }
3986 }
3987
3988 // Queue to outbound buffer
3989 client.queueOutbound(mh)
3990 client.queueOutbound(msg)
3991 if prodIsMQTT {
3992 // Need to add CR_LF since MQTT producers don't send CR_LF
3993 client.queueOutbound([]byte(CR_LF))
3994 }
3995
3996 // If we are tracking dynamic publish permissions that track reply subjects,
3997 // do that accounting here. We only look at client.replies which will be non-nil.
3998 // Only reply subject permissions if the client is not already allowed to publish to the reply subject.
3999 if client.replies != nil && len(reply) > 0 && !client.pubAllowedFullCheck(string(reply), true, true) {
4000 client.replies[string(reply)] = &resp{time.Now(), 0}
4001 client.repliesSincePrune++
4002 if client.repliesSincePrune > replyPermLimit || time.Since(client.lastReplyPrune) > replyPruneTime {
4003 client.pruneReplyPerms()
4004 }
4005 }
4006
4007 // Check outbound threshold and queue IO flush if needed.
4008 // This is specifically looking at situations where we are getting behind and may want
4009 // to intervene before this producer goes back to top of readloop. We are in the producer's
4010 // readloop go routine at this point.
4011 // FIXME(dlc) - We may call this alot, maybe suppress after first call?
4012 if len(client.out.nb) != 0 {
4013 client.flushSignal()
4014 }
4015
4016 // Add the data size we are responsible for here. This will be processed when we
4017 // return to the top of the readLoop.
4018 c.addToPCD(client)
4019
4020 if client.trace {
4021 client.traceOutOp(bytesToString(mh[:len(mh)-LEN_CR_LF]), nil)
4022 client.traceMsgDelivery(msg, hdrSize)
4023 }
4024
4025 client.mu.Unlock()
4026
4027 return true
4028 }
4029
4030 // Add the given sub's client to the list of clients that need flushing.
4031 // This must be invoked from `c`'s readLoop. No lock for c is required,
4032 // however, `client` lock must be held on entry. This holds true even
4033 // if `client` is same than `c`.
4034 func (c *client) addToPCD(client *client) {
4035 if _, ok := c.pcd[client]; !ok {
4036 client.out.fsp++
4037 c.pcd[client] = needFlush
4038 }
4039 }
4040
4041 // This will track a remote reply for an exported service that has requested
4042 // latency tracking.
4043 // Lock assumed to be held.
4044 func (c *client) trackRemoteReply(subject, reply string) {
4045 a := c.acc
4046 if a == nil {
4047 return
4048 }
4049
4050 var lrt time.Duration
4051 var respThresh time.Duration
4052
4053 a.mu.RLock()
4054 se := a.getServiceExport(subject)
4055 if se != nil {
4056 lrt = a.lowestServiceExportResponseTime()
4057 respThresh = se.respThresh
4058 }
4059 a.mu.RUnlock()
4060
4061 if se == nil {
4062 return
4063 }
4064
4065 if c.rrTracking == nil {
4066 c.rrTracking = &rrTracking{
4067 rmap: make(map[string]*remoteLatency),
4068 ptmr: time.AfterFunc(lrt, c.pruneRemoteTracking),
4069 lrt: lrt,
4070 }
4071 }
4072 rl := remoteLatency{
4073 Account: a.Name,
4074 ReqId: reply,
4075 respThresh: respThresh,
4076 }
4077 rl.M2.RequestStart = time.Now().UTC()
4078 c.rrTracking.rmap[reply] = &rl
4079 }
4080
4081 // pruneRemoteTracking will prune any remote tracking objects
4082 // that are too old. These are orphaned when a service is not
4083 // sending reponses etc.
4084 // Lock should be held upon entry.
4085 func (c *client) pruneRemoteTracking() {
4086 c.mu.Lock()
4087 if c.rrTracking == nil {
4088 c.mu.Unlock()
4089 return
4090 }
4091 now := time.Now()
4092 for subject, rl := range c.rrTracking.rmap {
4093 if now.After(rl.M2.RequestStart.Add(rl.respThresh)) {
4094 delete(c.rrTracking.rmap, subject)
4095 }
4096 }
4097 if len(c.rrTracking.rmap) > 0 {
4098 t := c.rrTracking.ptmr
4099 t.Stop()
4100 t.Reset(c.rrTracking.lrt)
4101 } else {
4102 c.rrTracking.ptmr.Stop()
4103 c.rrTracking = nil
4104 }
4105 c.mu.Unlock()
4106 }
4107
4108 // pruneReplyPerms will remove any stale or expired entries
4109 // in our reply cache. We make sure to not check too often.
4110 func (c *client) pruneReplyPerms() {
4111 // Make sure we do not check too often.
4112 if c.perms.resp == nil {
4113 return
4114 }
4115
4116 mm := c.perms.resp.MaxMsgs
4117 ttl := c.perms.resp.Expires
4118 now := time.Now()
4119
4120 for k, resp := range c.replies {
4121 if mm > 0 && resp.n >= mm {
4122 delete(c.replies, k)
4123 } else if ttl > 0 && now.Sub(resp.t) > ttl {
4124 delete(c.replies, k)
4125 }
4126 }
4127
4128 c.repliesSincePrune = 0
4129 c.lastReplyPrune = now
4130 }
4131
4132 // pruneDenyCache will prune the deny cache via randomly
4133 // deleting items. Doing so pruneSize items at a time.
4134 // Lock must be held for this one since it is shared under
4135 // deliverMsg.
4136 func (c *client) pruneDenyCache() {
4137 r := 0
4138 for key := range c.mperms.dcache {
4139 delete(c.mperms.dcache, key)
4140 if r++; r > pruneSize {
4141 break
4142 }
4143 }
4144 }
4145
4146 // prunePubPermsCache will prune the cache via randomly
4147 // deleting items. Doing so pruneSize items at a time.
4148 func (c *client) prunePubPermsCache() {
4149 // With parallel additions to the cache, it is possible that this function
4150 // would not be able to reduce the cache to its max size in one go. We
4151 // will try a few times but will release/reacquire the "lock" at each
4152 // attempt to give a chance to another go routine to take over and not
4153 // have this go routine do too many attempts.
4154 for i := 0; i < 5; i++ {
4155 // There is a case where we can invoke this from multiple go routines,
4156 // (in deliverMsg() if sub.client is a LEAF), so we make sure to prune
4157 // from only one go routine at a time.
4158 if !atomic.CompareAndSwapInt32(&c.perms.prun, 0, 1) {
4159 return
4160 }
4161 const maxPruneAtOnce = 1000
4162 r := 0
4163 c.perms.pcache.Range(func(k, _ any) bool {
4164 c.perms.pcache.Delete(k)
4165 if r++; (r > pruneSize && atomic.LoadInt32(&c.perms.pcsz) < int32(maxPermCacheSize)) ||
4166 (r > maxPruneAtOnce) {
4167 return false
4168 }
4169 return true
4170 })
4171 n := atomic.AddInt32(&c.perms.pcsz, -int32(r))
4172 atomic.StoreInt32(&c.perms.prun, 0)
4173 if n <= int32(maxPermCacheSize) {
4174 return
4175 }
4176 }
4177 }
4178
4179 // pubAllowed checks on publish permissioning.
4180 // Lock should not be held.
4181 func (c *client) pubAllowed(subject string) bool {
4182 return c.pubAllowedFullCheck(subject, true, false)
4183 }
4184
4185 // pubAllowedFullCheck checks on all publish permissioning depending
4186 // on the flag for dynamic reply permissions.
4187 func (c *client) pubAllowedFullCheck(subject string, fullCheck, hasLock bool) bool {
4188 if c.perms == nil || (c.perms.pub.allow == nil && c.perms.pub.deny == nil) {
4189 return true
4190 }
4191 // Check if published subject is allowed if we have permissions in place.
4192 v, ok := c.perms.pcache.Load(subject)
4193 if ok {
4194 return v.(bool)
4195 }
4196 allowed, checkAllow := true, true
4197 // For any connections, other than CLIENT, we will implicitly allow anything that
4198 // starts with the "$MQTT." prefix. However, we don't just return here,
4199 // we skip the check for "allow" but will check "deny".
4200 if c.kind != CLIENT && strings.HasPrefix(subject, mqttPrefix) {
4201 checkAllow = false
4202 }
4203 // Cache miss, check allow then deny as needed.
4204 if checkAllow && c.perms.pub.allow != nil {
4205 np, _ := c.perms.pub.allow.NumInterest(subject)
4206 allowed = np != 0
4207 }
4208 // If we have a deny list and are currently allowed, check that as well.
4209 if allowed && c.perms.pub.deny != nil {
4210 np, _ := c.perms.pub.deny.NumInterest(subject)
4211 allowed = np == 0
4212 }
4213
4214 // If we are tracking reply subjects
4215 // dynamically, check to see if we are allowed here but avoid pcache.
4216 // We need to acquire the lock though.
4217 if !allowed && fullCheck && c.perms.resp != nil {
4218 if !hasLock {
4219 c.mu.Lock()
4220 }
4221 allowed = c.responseAllowed(subject)
4222 if !hasLock {
4223 c.mu.Unlock()
4224 }
4225 } else {
4226 // Update our cache here.
4227 c.perms.pcache.Store(subject, allowed)
4228 if n := atomic.AddInt32(&c.perms.pcsz, 1); n > maxPermCacheSize {
4229 c.prunePubPermsCache()
4230 }
4231 }
4232 return allowed
4233 }
4234
4235 // Returns true if this subject matches a tracked dynamic reply permission.
4236 // Lock must be held.
4237 func (c *client) responseAllowed(subject string) bool {
4238 if c.perms == nil || c.perms.resp == nil {
4239 return false
4240 }
4241 if resp := c.replies[subject]; resp != nil {
4242 resp.n++
4243 if c.perms.resp.MaxMsgs > 0 && resp.n > c.perms.resp.MaxMsgs {
4244 delete(c.replies, subject)
4245 } else if c.perms.resp.Expires > 0 && time.Since(resp.t) > c.perms.resp.Expires {
4246 delete(c.replies, subject)
4247 } else {
4248 return true
4249 }
4250 }
4251 return false
4252 }
4253
4254 // Test whether a reply subject is a service import reply.
4255 func isServiceReply(reply []byte) bool {
4256 // This function is inlined and checking this way is actually faster
4257 // than byte-by-byte comparison.
4258 return len(reply) > 3 && bytesToString(reply[:4]) == replyPrefix
4259 }
4260
4261 // Test whether a subject is a JetStream ACK.
4262 func isJSAckSubject(subject []byte) bool {
4263 return len(subject) > jsAckPreLen && bytesToString(subject[:jsAckPreLen]) == jsAckPre
4264 }
4265
4266 // jsAckDeliverIdx returns the byte offset of the `@` separator in an encoded
4267 // `$JS.ACK....@<deliver>` reply, or -1 if reply is not in that form. Stream,
4268 // consumer, and subject tokens may legally contain `@`, so we accept only the
4269 // first `@` that follows the eight dots of the JS ACK token:
4270 //
4271 // $JS.ACK.<stream>.<consumer>.<delivered>.<sseq>.<cseq>.<tm>.<pending>@<deliver>
4272 func jsAckDeliverIdx(reply []byte) int {
4273 if !isJSAckSubject(reply) {
4274 return -1
4275 }
4276 dots := 0
4277 for i, b := range reply {
4278 switch b {
4279 case '.':
4280 dots++
4281 case '@':
4282 if dots >= 8 {
4283 return i
4284 }
4285 }
4286 }
4287 return -1
4288 }
4289
4290 // replyHasJSAckSuffix reports whether reply is already in `$JS.ACK....@<deliver>`
4291 // form, so callers don't double-append the suffix on a re-entrant pass
4292 // (service-import or chained JS push).
4293 func replyHasJSAckSuffix(reply []byte) bool {
4294 return jsAckDeliverIdx(reply) != -1
4295 }
4296
4297 // Test whether a reply subject is a service import or a gateway routed reply.
4298 func isReservedReply(reply []byte) bool {
4299 if isServiceReply(reply) {
4300 return true
4301 }
4302 // Faster to check with string([:]) than byte-by-byte
4303 if isJSAckSubject(reply) {
4304 return true
4305 } else if len(reply) > gwReplyPrefixLen && bytesToString(reply[:gwReplyPrefixLen]) == gwReplyPrefix {
4306 return true
4307 }
4308 return false
4309 }
4310
4311 // This will decide to call the client code or router code.
4312 func (c *client) processInboundMsg(msg []byte) {
4313 switch c.kind {
4314 case CLIENT:
4315 c.processInboundClientMsg(msg)
4316 case ROUTER:
4317 c.processInboundRoutedMsg(msg)
4318 case GATEWAY:
4319 c.processInboundGatewayMsg(msg)
4320 case LEAF:
4321 c.processInboundLeafMsg(msg)
4322 }
4323 }
4324
4325 // selectMappedSubject will choose the mapped subject based on the client's inbound subject.
4326 func (c *client) selectMappedSubject() bool {
4327 nsubj, changed := c.acc.selectMappedSubject(bytesToString(c.pa.subject))
4328 if changed {
4329 c.pa.mapped = c.pa.subject
4330 c.pa.subject = []byte(nsubj)
4331 }
4332 return changed
4333 }
4334
4335 // clientNRGPrefix is used in processInboundClientMsg to detect if publishes
4336 // are being made from normal clients to NRG subjects.
4337 var clientNRGPrefix = []byte("$NRG.")
4338
4339 // processInboundClientMsg is called to process an inbound msg from a client.
4340 // Return if the message was delivered, and if the message was not delivered
4341 // due to a permission issue.
4342 func (c *client) processInboundClientMsg(msg []byte) (bool, bool) {
4343 // Update statistics
4344 // The msg includes the CR_LF, so pull back out for accounting.
4345 c.in.msgs++
4346 c.in.bytes += int32(len(msg) - LEN_CR_LF)
4347
4348 // Check that client (could be here with SYSTEM) is not publishing on reserved "$GNR" prefix.
4349 if c.kind == CLIENT && hasGWRoutedReplyPrefix(c.pa.subject) {
4350 c.pubPermissionViolation(c.pa.subject)
4351 return false, true
4352 }
4353
4354 // Mostly under testing scenarios.
4355 c.mu.Lock()
4356 if c.srv == nil || c.acc == nil {
4357 c.mu.Unlock()
4358 return false, false
4359 }
4360 acc := c.acc
4361 genidAddr := &acc.sl.genid
4362
4363 // Check pub permissions
4364 if c.perms != nil && (c.perms.pub.allow != nil || c.perms.pub.deny != nil) {
4365 if !c.pubAllowedFullCheck(string(c.pa.subject), true, true) {
4366 c.mu.Unlock()
4367 c.pubPermissionViolation(c.pa.subject)
4368 return false, true
4369 }
4370 }
4371 c.mu.Unlock()
4372
4373 // Check if the client is trying to publish to reserved NRG subjects.
4374 // Doesn't apply to NRGs themselves as they use SYSTEM-kind clients instead.
4375 if c.kind == CLIENT && bytes.HasPrefix(c.pa.subject, clientNRGPrefix) && acc != c.srv.SystemAccount() {
4376 c.pubPermissionViolation(c.pa.subject)
4377 return false, true
4378 }
4379
4380 // Now check for reserved replies. These are used for service imports.
4381 if c.kind == CLIENT && len(c.pa.reply) > 0 && isReservedReply(c.pa.reply) {
4382 c.replySubjectViolation(c.pa.reply)
4383 return false, true
4384 }
4385
4386 if c.opts.Verbose {
4387 c.sendOK()
4388 }
4389
4390 // If MQTT client, check for retain flag now that we have passed permissions check
4391 if c.isMqtt() {
4392 c.mqttHandlePubRetain()
4393 }
4394
4395 // Doing this inline as opposed to create a function (which otherwise has a measured
4396 // performance impact reported in our bench)
4397 var isGWRouted bool
4398 if c.kind != CLIENT {
4399 if atomic.LoadInt32(&acc.gwReplyMapping.check) > 0 {
4400 acc.mu.RLock()
4401 c.pa.subject, isGWRouted = acc.gwReplyMapping.get(c.pa.subject)
4402 acc.mu.RUnlock()
4403 }
4404 } else if atomic.LoadInt32(&c.gwReplyMapping.check) > 0 {
4405 c.mu.Lock()
4406 c.pa.subject, isGWRouted = c.gwReplyMapping.get(c.pa.subject)
4407 c.mu.Unlock()
4408 }
4409
4410 // If we have an exported service and we are doing remote tracking, check this subject
4411 // to see if we need to report the latency.
4412 if c.rrTracking != nil {
4413 c.mu.Lock()
4414 rl := c.rrTracking.rmap[string(c.pa.subject)]
4415 if rl != nil {
4416 delete(c.rrTracking.rmap, bytesToString(c.pa.subject))
4417 }
4418 c.mu.Unlock()
4419
4420 if rl != nil {
4421 sl := &rl.M2
4422 // Fill this in and send it off to the other side.
4423 sl.Status = 200
4424 sl.Responder = c.getClientInfo(true)
4425 sl.ServiceLatency = time.Since(sl.RequestStart) - sl.Responder.RTT
4426 sl.TotalLatency = sl.ServiceLatency + sl.Responder.RTT
4427 sanitizeLatencyMetric(sl)
4428 lsub := remoteLatencySubjectForResponse(c.pa.subject)
4429 c.srv.sendInternalAccountMsg(nil, lsub, rl) // Send to SYS account
4430 }
4431 }
4432
4433 // If the subject was converted to the gateway routed subject, then handle it now
4434 // and be done with the rest of this function.
4435 if isGWRouted {
4436 c.handleGWReplyMap(msg)
4437 return true, false
4438 }
4439
4440 // Match the subscriptions. We will use our own L1 map if
4441 // it's still valid, avoiding contention on the shared sublist.
4442 var r *SublistResult
4443 var ok bool
4444
4445 genid := atomic.LoadUint64(genidAddr)
4446 if genid == c.in.genid && c.in.results != nil {
4447 r, ok = c.in.results[string(c.pa.subject)]
4448 } else {
4449 // Reset our L1 completely.
4450 c.in.results = make(map[string]*SublistResult)
4451 c.in.genid = genid
4452 }
4453
4454 // Go back to the sublist data structure.
4455 if !ok {
4456 // Match may use the subject here to populate a cache, so can not use bytesToString here.
4457 r = acc.sl.Match(string(c.pa.subject))
4458 if len(r.psubs)+len(r.qsubs) > 0 {
4459 // Prune the results cache. Keeps us from unbounded growth. Random delete.
4460 if len(c.in.results) >= maxResultCacheSize {
4461 n := 0
4462 for subject := range c.in.results {
4463 delete(c.in.results, subject)
4464 if n++; n > pruneSize {
4465 break
4466 }
4467 }
4468 }
4469 // Then add the new cache entry.
4470 c.in.results[string(c.pa.subject)] = r
4471 }
4472 }
4473
4474 // Indication if we attempted to deliver the message to anyone.
4475 var didDeliver bool
4476 var qnames [][]byte
4477
4478 // Check for no interest, short circuit if so.
4479 // This is the fanout scale.
4480 if len(r.psubs)+len(r.qsubs) > 0 {
4481 flag := pmrNoFlag
4482 // If there are matching queue subs and we are in gateway mode,
4483 // we need to keep track of the queue names the messages are
4484 // delivered to. When sending to the GWs, the RMSG will include
4485 // those names so that the remote clusters do not deliver messages
4486 // to their queue subs of the same names.
4487 if len(r.qsubs) > 0 && c.srv.gateway.enabled &&
4488 atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 {
4489 flag |= pmrCollectQueueNames
4490 }
4491 didDeliver, qnames = c.processMsgResults(acc, r, msg, c.pa.deliver, c.pa.subject, c.pa.reply, flag)
4492 }
4493
4494 // Now deal with gateways
4495 if c.srv.gateway.enabled {
4496 reply := c.pa.reply
4497 if len(c.pa.deliver) > 0 && c.kind == JETSTREAM && len(reply) > 0 && !replyHasJSAckSuffix(reply) {
4498 reply = append(slices.Clip(reply), '@')
4499 reply = append(reply, c.pa.deliver...)
4500 }
4501 didDeliver = c.sendMsgToGateways(acc, msg, c.pa.subject, reply, qnames, false) || didDeliver
4502 }
4503
4504 // Check to see if we did not deliver to anyone and the client has a reply subject set
4505 // and wants notification of no_responders.
4506 if !didDeliver && len(c.pa.reply) > 0 {
4507 c.mu.Lock()
4508 if c.opts.NoResponders {
4509 if sub := c.subForReply(c.pa.reply); sub != nil {
4510 hdrLen := 32 /* header without the subject */ + len(c.pa.subject)
4511 proto := fmt.Sprintf("HMSG %s %s %d %d\r\nNATS/1.0 503\r\nNats-Subject: %s\r\n\r\n\r\n", c.pa.reply, sub.sid, hdrLen, hdrLen, c.pa.subject)
4512 c.queueOutbound([]byte(proto))
4513 c.addToPCD(c)
4514 }
4515 }
4516 c.mu.Unlock()
4517 }
4518
4519 return didDeliver, false
4520 }
4521
4522 // Return the subscription for this reply subject. Only look at normal subs for this client.
4523 func (c *client) subForReply(reply []byte) *subscription {
4524 r := c.acc.sl.Match(string(reply))
4525 for _, sub := range r.psubs {
4526 if sub.client == c {
4527 return sub
4528 }
4529 }
4530 return nil
4531 }
4532
4533 // This is invoked knowing that c.pa.subject has been set to the gateway routed subject.
4534 // This function will send the message to possibly LEAFs and directly back to the origin
4535 // gateway.
4536 func (c *client) handleGWReplyMap(msg []byte) bool {
4537 // Check for leaf nodes
4538 if c.srv.gwLeafSubs.Count() > 0 {
4539 if r := c.srv.gwLeafSubs.MatchBytes(c.pa.subject); len(r.psubs) > 0 {
4540 c.processMsgResults(c.acc, r, msg, c.pa.deliver, c.pa.subject, c.pa.reply, pmrNoFlag)
4541 }
4542 }
4543 if c.srv.gateway.enabled {
4544 reply := c.pa.reply
4545 if len(c.pa.deliver) > 0 && c.kind == JETSTREAM && len(reply) > 0 && !replyHasJSAckSuffix(reply) {
4546 reply = append(slices.Clip(reply), '@')
4547 reply = append(reply, c.pa.deliver...)
4548 }
4549 c.sendMsgToGateways(c.acc, msg, c.pa.subject, reply, nil, false)
4550 }
4551 return true
4552 }
4553
4554 // Used to setup the response map for a service import request that has a reply subject.
4555 func (c *client) setupResponseServiceImport(acc *Account, si *serviceImport, tracking bool, header http.Header) *serviceImport {
4556 rsi := si.acc.addRespServiceImport(acc, string(c.pa.reply), si, tracking, header, nil)
4557 if si.latency != nil {
4558 if c.rtt == 0 {
4559 // We have a service import that we are tracking but have not established RTT.
4560 c.sendRTTPing()
4561 }
4562 si.acc.mu.Lock()
4563 rsi.rc = c
4564 si.acc.mu.Unlock()
4565 }
4566 return rsi
4567 }
4568
4569 // Will remove a status and description from the header if present.
4570 func removeHeaderStatusIfPresent(hdr []byte) []byte {
4571 k := []byte("NATS/1.0")
4572 kl, i := len(k), bytes.IndexByte(hdr, '\r')
4573 if !bytes.HasPrefix(hdr, k) || i <= kl {
4574 return hdr
4575 }
4576 hdr = append(hdr[:kl], hdr[i:]...)
4577 if len(hdr) == len(emptyHdrLine) {
4578 return nil
4579 }
4580 return hdr
4581 }
4582
4583 // Will remove a header if present.
4584 func removeHeaderIfPresent(hdr []byte, key string) []byte {
4585 for {
4586 start := getHeaderKeyIndex(key, hdr)
4587 // key can't be first and we want to check that it is preceded by a '\n'
4588 if start < 1 || hdr[start-1] != '\n' {
4589 return hdr
4590 }
4591 index := start + len(key)
4592 if index >= len(hdr) || hdr[index] != ':' {
4593 return hdr
4594 }
4595 end := bytes.Index(hdr[start:], []byte(_CRLF_))
4596 if end < 0 {
4597 return hdr
4598 }
4599 hdr = append(hdr[:start], hdr[start+end+len(_CRLF_):]...)
4600 if len(hdr) <= len(emptyHdrLine) {
4601 return nil
4602 }
4603 }
4604 }
4605
4606 func removeHeaderIfPrefixPresent(hdr []byte, prefix string) []byte {
4607 var index int
4608 for {
4609 if index >= len(hdr) {
4610 return hdr
4611 }
4612
4613 start := bytes.Index(hdr[index:], []byte(prefix))
4614 if start < 0 {
4615 return hdr
4616 }
4617 index += start
4618 if index < 1 || hdr[index-1] != '\n' {
4619 index += len(prefix)
4620 continue
4621 }
4622
4623 end := bytes.Index(hdr[index+len(prefix):], []byte(_CRLF_))
4624 if end < 0 {
4625 return hdr
4626 }
4627
4628 hdr = append(hdr[:index], hdr[index+end+len(prefix)+len(_CRLF_):]...)
4629 if len(hdr) <= len(emptyHdrLine) {
4630 return nil
4631 }
4632 }
4633 }
4634
4635 // Generate a new header based on optional original header and key value.
4636 // More used in JetStream layers.
4637 func genHeader(hdr []byte, key, value string) []byte {
4638 var bb bytes.Buffer
4639 if len(hdr) > LEN_CR_LF {
4640 bb.Write(hdr[:len(hdr)-LEN_CR_LF])
4641 } else {
4642 bb.WriteString(hdrLine)
4643 }
4644 http.Header{key: []string{value}}.Write(&bb)
4645 bb.WriteString(CR_LF)
4646 return bb.Bytes()
4647 }
4648
4649 // This will set a header for the message.
4650 // Lock does not need to be held but this should only be called
4651 // from the inbound go routine. We will update the pubArgs.
4652 // This will replace any previously set header and not add to it per normal spec.
4653 func (c *client) setHeader(key, value string, msg []byte) []byte {
4654 var bb bytes.Buffer
4655 var omi int
4656 // Write original header if present.
4657 if c.pa.hdr > LEN_CR_LF {
4658 omi = c.pa.hdr
4659 // Need to copy since we're removing the header in place.
4660 hdr := removeHeaderIfPresent(copyBytes(msg[:c.pa.hdr-LEN_CR_LF]), key)
4661 if len(hdr) == 0 {
4662 bb.WriteString(hdrLine)
4663 } else {
4664 bb.Write(hdr)
4665 }
4666 } else {
4667 bb.WriteString(hdrLine)
4668 }
4669 http.Header{key: []string{value}}.Write(&bb)
4670 bb.WriteString(CR_LF)
4671 nhdr := bb.Len()
4672 // Put the original message back.
4673 // FIXME(dlc) - This is inefficient.
4674 bb.Write(msg[omi:])
4675 nsize := bb.Len() - LEN_CR_LF
4676 // MQTT producers don't have CRLF, so add it back.
4677 if c.isMqtt() {
4678 nsize += LEN_CR_LF
4679 }
4680 // Update pubArgs
4681 // If others will use this later we need to save and restore original.
4682 c.pa.hdr = nhdr
4683 c.pa.size = nsize
4684 c.pa.hdb = []byte(strconv.Itoa(nhdr))
4685 c.pa.szb = []byte(strconv.Itoa(nsize))
4686 return bb.Bytes()
4687 }
4688
4689 // Will return a copy of the value for the header denoted by key or nil if it does not exist.
4690 // If you know that it is safe to refer to the underlying hdr slice for the period that the
4691 // return value is used, then sliceHeader() will be faster.
4692 func getHeader(key string, hdr []byte) []byte {
4693 v := sliceHeader(key, hdr)
4694 if v == nil {
4695 return nil
4696 }
4697 return append(make([]byte, 0, len(v)), v...)
4698 }
4699
4700 // Will return the sliced value for the header denoted by key or nil if it does not exists.
4701 // This function ignores errors and tries to achieve speed and no additional allocations.
4702 func sliceHeader(key string, hdr []byte) []byte {
4703 if len(hdr) == 0 {
4704 return nil
4705 }
4706 index := getHeaderKeyIndex(key, hdr)
4707 if index == -1 {
4708 return nil
4709 }
4710 // Skip over the key and the : separator.
4711 index += len(key) + 1
4712 hdrLen := len(hdr)
4713 // Skip over whitespace before the value.
4714 for index < hdrLen && hdr[index] == ' ' {
4715 index++
4716 }
4717 // Collect together the rest of the value until we hit a CRLF.
4718 start := index
4719 for index < hdrLen {
4720 if hdr[index] == '\r' && index < hdrLen-1 && hdr[index+1] == '\n' {
4721 break
4722 }
4723 index++
4724 }
4725 return hdr[start:index:index]
4726 }
4727
4728 // getHeaderKeyIndex returns an index into the header slice for the given key.
4729 // Returns -1 if not found.
4730 func getHeaderKeyIndex(key string, hdr []byte) int {
4731 if len(hdr) == 0 {
4732 return -1
4733 }
4734 bkey := stringToBytes(key)
4735 keyLen, hdrLen := len(key), len(hdr)
4736 var offset int
4737 for {
4738 index := bytes.Index(hdr[offset:], bkey)
4739 // Check that we have enough characters, this will handle the -1 case of the key not
4740 // being found and will also handle not having enough characters for trailing CRLF.
4741 if index < 2 {
4742 return -1
4743 }
4744 index += offset
4745 // There should be a terminating CRLF.
4746 if index >= hdrLen-1 || hdr[index-1] != '\n' || hdr[index-2] != '\r' {
4747 offset = index + keyLen
4748 continue
4749 }
4750 // The key should be immediately followed by a : separator.
4751 if index+keyLen >= hdrLen {
4752 return -1
4753 }
4754 if hdr[index+keyLen] != ':' {
4755 offset = index + keyLen
4756 continue
4757 }
4758 return index
4759 }
4760 }
4761
4762 // setHeader will replace the value of the first existing key `key`
4763 // with the given value `val`, or add this new key at the end of
4764 // the headers.
4765 //
4766 // Note: If the key does not exist, or if it exists but the new value
4767 // would make the resulting byte slice larger than the original one,
4768 // a new byte slice is returned and the original is left untouched.
4769 // This is to prevent situations where caller may have a `hdr` and
4770 // `msg` that are the parts of an underlying buffer. Extending the
4771 // `hdr` would otherwise overwrite the `msg` part.
4772 //
4773 // If the new value is smaller, then the original `hdr` byte slice
4774 // is modified.
4775 func setHeader(key, val string, hdr []byte) []byte {
4776 start := getHeaderKeyIndex(key, hdr)
4777 if start >= 0 {
4778 valStart := start + len(key) + 1
4779 // Preserve single whitespace if used.
4780 hdrLen := len(hdr)
4781 if valStart < hdrLen && hdr[valStart] == ' ' {
4782 valStart++
4783 }
4784 valEnd := bytes.Index(hdr[valStart:], []byte("\r"))
4785 if valEnd < 0 {
4786 return hdr // malformed headers
4787 }
4788 valEnd += valStart
4789 // Length of the existing value (before the `\r`)
4790 oldValLen := valEnd - valStart
4791 // This is how many extra bytes we need for the new value.
4792 // If <= 0, it means that we need less and so will reuse the `hdr` buffer.
4793 if extra := len(val) - oldValLen; extra > 0 {
4794 // Check that we don't overflow an "int".
4795 if rem := math.MaxInt - hdrLen; rem < extra {
4796 // We don't grow, and return the existing header.
4797 return hdr
4798 }
4799 // The new size is the old size plus the extra bytes.
4800 newHdrSize := hdrLen + extra
4801 newHdr := make([]byte, newHdrSize)
4802 // Copy the parts from `hdr` and `val` into the new buffer.
4803 n := copy(newHdr, hdr[:valStart])
4804 n += copy(newHdr[n:], val)
4805 copy(newHdr[n:], hdr[valEnd:])
4806 return newHdr
4807 }
4808 // We can write in place since it fits in the existing `hdr` buffer.
4809 n := copy(hdr[valStart:], val)
4810 n += copy(hdr[valStart+n:], hdr[valEnd:])
4811 hdr = hdr[:valStart+n]
4812 return hdr
4813 }
4814 if len(hdr) > 0 && bytes.HasSuffix(hdr, []byte("\r\n")) {
4815 hdr = hdr[:len(hdr)-2]
4816 val += "\r\n"
4817 }
4818 // Create the new buffer based on length of existing one and
4819 // length of the new "<key>: <value>\r\n". Protect against "int" overflow.
4820 newSize := uint64(len(hdr)) + uint64(len(key)) + 1 + 1 + uint64(len(val)) + 2
4821 if newSize > uint64(math.MaxInt) {
4822 // We don't grow, and return the existing header.
4823 return hdr
4824 }
4825 newHdr := make([]byte, 0, int(newSize))
4826 newHdr = append(newHdr, hdr...)
4827 return fmt.Appendf(newHdr, "%s: %s\r\n", key, val)
4828 }
4829
4830 // For bytes.HasPrefix below.
4831 var (
4832 jsRequestNextPreB = []byte(jsRequestNextPre)
4833 jsDirectGetPreB = []byte(jsDirectGetPre)
4834 )
4835
4836 // processServiceImport is an internal callback when a subscription matches an imported service
4837 // from another account. This includes response mappings as well.
4838 func (c *client) processServiceImport(si *serviceImport, acc *Account, msg []byte) bool {
4839 // If we are a GW and this is not a direct serviceImport ignore.
4840 isResponse := si.isRespServiceImport()
4841 if (c.kind == GATEWAY || c.kind == ROUTER) && !isResponse {
4842 return false
4843 }
4844 // Detect cycles and ignore (return) when we detect one.
4845 if len(c.pa.psi) > 0 {
4846 for i := len(c.pa.psi) - 1; i >= 0; i-- {
4847 if psi := c.pa.psi[i]; psi.se == si.se {
4848 return false
4849 }
4850 }
4851 }
4852
4853 acc.mu.RLock()
4854 var checkJS bool
4855 shouldReturn := si.invalid || acc.sl == nil
4856 if !shouldReturn && !isResponse && si.to == jsAllAPI {
4857 if bytes.HasPrefix(c.pa.subject, jsDirectGetPreB) || bytes.HasPrefix(c.pa.subject, jsRequestNextPreB) {
4858 checkJS = true
4859 }
4860 }
4861 siAcc := si.acc
4862 allowTrace := si.atrc
4863 isMsgTraceResp := isResponse && si.mt != nil
4864 acc.mu.RUnlock()
4865
4866 // We have a special case where JetStream pulls in all service imports through one export.
4867 // However the GetNext for consumers and DirectGet for streams are a no-op and causes buildups of service imports,
4868 // response service imports and rrMap entries which all will need to simply expire.
4869 // TODO(dlc) - Come up with something better.
4870 if shouldReturn || (checkJS && si.se != nil && si.se.acc == c.srv.SystemAccount()) {
4871 return false
4872 }
4873
4874 mt, traceOnly := c.isMsgTraceEnabled()
4875
4876 var nrr []byte
4877 var rsi *serviceImport
4878
4879 // Check if there is a reply present and set up a response.
4880 tracking, headers := shouldSample(si.latency, c)
4881 if len(c.pa.reply) > 0 {
4882 // Special case for now, need to formalize.
4883 // TODO(dlc) - Formalize as a service import option for reply rewrite.
4884 // For now we can't do $JS.ACK since that breaks pull consumers across accounts.
4885 if !bytes.HasPrefix(c.pa.reply, []byte(jsAckPre)) {
4886 if rsi = c.setupResponseServiceImport(acc, si, tracking, headers); rsi != nil {
4887 nrr = []byte(rsi.from)
4888 }
4889 } else {
4890 // This only happens when we do a pull subscriber that trampolines through another account.
4891 // Normally this code is not called.
4892 nrr = c.pa.reply
4893 }
4894 } else if !isResponse && si.latency != nil && tracking {
4895 // Check to see if this was a bad request with no reply and we were supposed to be tracking.
4896 siAcc.sendBadRequestTrackingLatency(si, c, headers)
4897 }
4898
4899 // Send tracking info here if we are tracking this response.
4900 // This is always a response.
4901 var didSendTL bool
4902 if si.tracking && !si.didDeliver {
4903 // Stamp that we attempted delivery.
4904 si.didDeliver = true
4905 didSendTL = acc.sendTrackingLatency(si, c)
4906 }
4907
4908 // Pick correct "to" subject. If we matched on a wildcard use the literal publish subject.
4909 to, subject := si.to, string(c.pa.subject)
4910
4911 if si.tr != nil {
4912 // FIXME(dlc) - This could be slow, may want to look at adding cache to bare transforms?
4913 to = si.tr.TransformSubject(subject)
4914 } else if si.usePub {
4915 to = subject
4916 }
4917
4918 // Copy our pubArg since this gets modified as we process the service import itself.
4919 pacopy := c.pa
4920
4921 // Now check to see if this account has mappings that could affect the service import.
4922 // Can't use non-locked trick like in processInboundClientMsg, so just call into selectMappedSubject
4923 // so we only lock once.
4924 nsubj, changed := siAcc.selectMappedSubject(to)
4925 if changed {
4926 c.pa.mapped = []byte(to)
4927 to = nsubj
4928 }
4929
4930 // Set previous service import to detect chaining.
4931 lpsi := len(c.pa.psi)
4932 hadPrevSi, share := lpsi > 0, si.share
4933 if hadPrevSi {
4934 share = c.pa.psi[lpsi-1].share
4935 }
4936 c.pa.psi = append(c.pa.psi, si)
4937
4938 // Place our client info for the request in the original message.
4939 // This will survive going across routes, etc.
4940 if !isResponse {
4941 isSysImport := siAcc == c.srv.SystemAccount()
4942 var ci *ClientInfo
4943 var cis *ClientInfo
4944 if c.pa.hdr >= 0 {
4945 var hci ClientInfo
4946 if err := json.Unmarshal(sliceHeader(ClientInfoHdr, msg[:c.pa.hdr]), &hci); err == nil {
4947 cis = &hci
4948 }
4949 }
4950 if c.kind == LEAF && c.pa.hdr >= 0 && len(sliceHeader(ClientInfoHdr, msg[:c.pa.hdr])) > 0 {
4951 // Leaf nodes may forward a Nats-Request-Info from a remote domain,
4952 // but the local server must replace it with the identity of the
4953 // authenticated leaf connection instead of trusting forwarded values.
4954 ci = c.getClientInfo(share)
4955 if hadPrevSi && cis != nil && cis.Reply != _EMPTY_ {
4956 ci.Reply = cis.Reply
4957 } else if bytes.HasSuffix(c.pa.reply, []byte(FastBatchSuffix)) {
4958 // Fast batch requires knowledge of the original reply subject.
4959 ci.Reply = bytesToString(c.pa.reply)
4960 }
4961 if hadPrevSi {
4962 ci.Service = acc.Name
4963 if !share && (si.share || isSysImport) {
4964 c.addServerAndClusterInfo(ci)
4965 }
4966 } else if !share && isSysImport {
4967 c.addServerAndClusterInfo(ci)
4968 }
4969 } else if hadPrevSi && cis != nil {
4970 ci = cis
4971 ci.Service = acc.Name
4972 // Check if we are moving into a share details account from a non-shared
4973 // and add in server and cluster details.
4974 if !share && (si.share || isSysImport) {
4975 c.addServerAndClusterInfo(ci)
4976 }
4977 } else if c.kind != LEAF || c.pa.hdr < 0 || len(sliceHeader(ClientInfoHdr, msg[:c.pa.hdr])) == 0 {
4978 ci = c.getClientInfo(share)
4979 // Fast batch requires knowledge of the original reply subject.
4980 if bytes.HasSuffix(c.pa.reply, []byte(FastBatchSuffix)) {
4981 ci.Reply = bytesToString(c.pa.reply)
4982 }
4983 // If we did not share but the imports destination is the system account add in the server and cluster info.
4984 if !share && isSysImport {
4985 c.addServerAndClusterInfo(ci)
4986 }
4987 }
4988 // Set clientInfo if present.
4989 if ci != nil {
4990 if b, _ := json.Marshal(ci); b != nil {
4991 msg = c.setHeader(ClientInfoHdr, bytesToString(b), msg)
4992 }
4993 }
4994 }
4995
4996 // Set our optional subject(to) and reply.
4997 if !isResponse && to != subject {
4998 c.pa.subject = []byte(to)
4999 }
5000 c.pa.reply = nrr
5001
5002 if changed && c.isMqtt() && c.pa.hdr > 0 {
5003 c.srv.mqttStoreQoSMsgForAccountOnNewSubject(c.pa.hdr, msg, siAcc.GetName(), to)
5004 }
5005
5006 // FIXME(dlc) - Do L1 cache trick like normal client?
5007 rr := siAcc.sl.Match(to)
5008
5009 // If we are a route or gateway or leafnode and this message is flipped to a queue subscriber we
5010 // need to handle that since the processMsgResults will want a queue filter.
5011 flags := pmrMsgImportedFromService
5012 if c.kind == GATEWAY || c.kind == ROUTER || c.kind == LEAF {
5013 flags |= pmrIgnoreEmptyQueueFilter
5014 }
5015
5016 // If this is a response service import that arrived via a route, allow delivery
5017 // to route subscriptions. Service import replies use one-time _R_ subjects.
5018 if isResponse && c.kind == ROUTER {
5019 flags |= pmrAllowSendFromRouteToRoute
5020 }
5021
5022 // We will be calling back into processMsgResults since we are now being called as a normal sub.
5023 // We need to take care of the c.in.rts, so save off what is there and use a local version. We
5024 // will put back what was there after.
5025
5026 orts := c.in.rts
5027
5028 var lrts [routeTargetInit]routeTarget
5029 c.in.rts = lrts[:0]
5030
5031 var skipProcessing bool
5032 var mtrsi *serviceImport
5033 // If message tracing enabled, add the service import trace.
5034 if mt != nil {
5035 mt.addServiceImportEvent(siAcc.GetName(), string(pacopy.subject), to)
5036 // If we are not allowing tracing and doing trace only, we stop at this level.
5037 if !allowTrace {
5038 if traceOnly {
5039 skipProcessing = true
5040 } else {
5041 // We are going to do normal processing, and possibly chainning
5042 // with other server imports, but the rest won't be traced.
5043 // We do so by setting the c.pa.trace to nil (it will be restored
5044 // with c.pa = pacopy).
5045 c.pa.trace = nil
5046 // We also need to disable the message trace headers so that
5047 // if the message is routed, it does not initialize tracing in the
5048 // remote.
5049 msg = c.setHeader(MsgTraceDest, MsgTraceDestDisabled, msg)
5050 }
5051 } else {
5052 // This code is invoked from a single thread so mutation of mt.dest
5053 // here is safe.
5054 dest := mt.dest
5055 defer func() { mt.dest = dest }()
5056 mtrsi, msg = mt.setupResponseServiceImport(c, acc, si, msg)
5057 }
5058 }
5059
5060 var didDeliver bool
5061
5062 if !skipProcessing {
5063 // If this is not a gateway connection but gateway is enabled,
5064 // try to send this converted message to all gateways.
5065 if c.srv.gateway.enabled {
5066 flags |= pmrCollectQueueNames
5067 var queues [][]byte
5068 didDeliver, queues = c.processMsgResults(siAcc, rr, msg, c.pa.deliver, []byte(to), nrr, flags)
5069 didDeliver = c.sendMsgToGateways(siAcc, msg, []byte(to), nrr, queues, false) || didDeliver
5070 } else {
5071 didDeliver, _ = c.processMsgResults(siAcc, rr, msg, c.pa.deliver, []byte(to), nrr, flags)
5072 }
5073 }
5074
5075 // Restore to original values.
5076 c.in.rts = orts
5077 c.pa = pacopy
5078
5079 // Mark in the c.pa if the message was delivered or not (no responders status).
5080 c.pa.delivered = didDeliver
5081
5082 // Determine if we should remove this service import. This is for response service imports.
5083 // We will remove if we did not deliver, or if we are a response service import and we are
5084 // a singleton, or we have an EOF message.
5085 shouldRemove := !didDeliver || (isResponse && (si.rt == Singleton || len(msg) == LEN_CR_LF))
5086 // If we are tracking and we did not actually send the latency info we need to suppress the removal.
5087 if si.tracking && !didSendTL {
5088 shouldRemove = false
5089 }
5090 // If we are streamed or chunked we need to update our timestamp to avoid cleanup.
5091 if si.rt != Singleton && didDeliver {
5092 acc.mu.Lock()
5093 si.ts = time.Now().UnixNano()
5094 acc.mu.Unlock()
5095 }
5096 // This is a message trace...
5097 if mt != nil {
5098 // If it was not routed anywhere, we can remove mtrsi that we created earlier.
5099 mt.siMu.RLock()
5100 remove := mt.rsi == nil
5101 mt.siMu.RUnlock()
5102 if remove {
5103 reason := rsiOk
5104 if !didDeliver {
5105 reason = rsiNoDelivery
5106 }
5107 siAcc.removeRespServiceImport(mtrsi, reason)
5108 }
5109 // If we skip last-mile delivery, we need to remove the rsi that we
5110 // may have created if there was a reply subject.
5111 if rsi != nil && traceOnly {
5112 shouldRemove = true
5113 }
5114
5115 } else if isMsgTraceResp {
5116 shouldRemove = false
5117 if !strings.HasPrefix(si.to, replyPrefix) {
5118 var evt MsgTraceEvent
5119 if err := json.Unmarshal(msg, &evt); err == nil {
5120 si.mt.handleRespServiceImport(&evt)
5121 }
5122 }
5123 }
5124
5125 // Cleanup of a response service import
5126 if shouldRemove {
5127 reason := rsiOk
5128 if !didDeliver {
5129 reason = rsiNoDelivery
5130 }
5131 if isResponse {
5132 acc.removeRespServiceImport(si, reason)
5133 } else {
5134 // This is a main import and since we could not even deliver to the exporting account
5135 // go ahead and remove the respServiceImport we created above.
5136 siAcc.removeRespServiceImport(rsi, reason)
5137 }
5138 }
5139
5140 return didDeliver
5141 }
5142
5143 func (c *client) addSubToRouteTargets(sub *subscription) {
5144 if c.in.rts == nil {
5145 c.in.rts = make([]routeTarget, 0, routeTargetInit)
5146 }
5147
5148 for i := range c.in.rts {
5149 rt := &c.in.rts[i]
5150 if rt.sub.client == sub.client {
5151 if sub.queue != nil {
5152 rt.qs = append(rt.qs, sub.queue...)
5153 rt.qs = append(rt.qs, ' ')
5154 rt.qsubs = append(rt.qsubs, sub)
5155 }
5156 return
5157 }
5158 }
5159
5160 var rt *routeTarget
5161 lrts := len(c.in.rts)
5162
5163 // If we are here we do not have the sub yet in our list
5164 // If we have to grow do so here.
5165 if lrts == cap(c.in.rts) {
5166 c.in.rts = append(c.in.rts, routeTarget{})
5167 }
5168
5169 c.in.rts = c.in.rts[:lrts+1]
5170 rt = &c.in.rts[lrts]
5171 rt.sub = sub
5172 rt.qs = rt._qs[:0]
5173 rt.qsubs = rt._qsubs[:0]
5174 if sub.queue != nil {
5175 rt.qs = append(rt.qs, sub.queue...)
5176 rt.qs = append(rt.qs, ' ')
5177 rt.qsubs = append(rt.qsubs, sub)
5178 }
5179 }
5180
5181 // Filters queue groups in a coalesced route or leaf target against the
5182 // destination connection's delivery-time subscription denies.
5183 func filterRouteTargetDeny(subject []byte, rt *routeTarget) bool {
5184 dc := rt.sub.client
5185 dc.mu.Lock()
5186 defer dc.mu.Unlock()
5187 if dc.mperms == nil {
5188 return true
5189 }
5190
5191 dsubject := string(subject)
5192 if len(rt.sub.queue) == 0 {
5193 if dc.checkDenySub(dsubject, _EMPTY_) {
5194 return false
5195 }
5196 } else {
5197 rt.sub = nil
5198 }
5199
5200 qs := rt.qs[:0]
5201 qsubs := rt.qsubs[:0]
5202 for _, qsub := range rt.qsubs {
5203 if dc.checkDenySub(dsubject, bytesToString(qsub.queue)) {
5204 continue
5205 }
5206 if rt.sub == nil {
5207 rt.sub = qsub
5208 }
5209 qs = append(qs, qsub.queue...)
5210 qs = append(qs, ' ')
5211 qsubs = append(qsubs, qsub)
5212 }
5213 rt.qs = qs
5214 rt.qsubs = qsubs
5215 return rt.sub != nil
5216 }
5217
5218 // This processes the sublist results for a given message.
5219 // Returns if the message was delivered to at least target and queue filters.
5220 func (c *client) processMsgResults(acc *Account, r *SublistResult, msg, deliver, subject, reply []byte, flags int) (bool, [][]byte) {
5221 // For sending messages across routes and leafnodes.
5222 // Reset if we have one since we reuse this data structure.
5223 if c.in.rts != nil {
5224 c.in.rts = c.in.rts[:0]
5225 }
5226
5227 var rplyHasGWPrefix bool
5228 var creply = reply
5229
5230 // If the reply subject is a GW routed reply, we will perform some
5231 // tracking in deliverMsg(). We also want to send to the user the
5232 // reply without the prefix. `creply` will be set to that and be
5233 // used to create the message header for client connections.
5234 if rplyHasGWPrefix = isGWRoutedReply(reply); rplyHasGWPrefix {
5235 creply = reply[gwSubjectOffset:]
5236 }
5237
5238 // With JetStream we now have times where we want to match a subscription
5239 // on one subject, but deliver it with another. e.g. JetStream deliverables.
5240 // This only works for last mile, meaning to a client. For other types we need
5241 // to use the original subject.
5242 subj := subject
5243 if len(deliver) > 0 {
5244 subj = deliver
5245 }
5246
5247 // Check for JetStream encoded reply subjects.
5248 // For now these will only be on $JS.ACK prefixed reply subjects.
5249 var remapped bool
5250 if len(creply) > 0 && c.kind != CLIENT && !isInternalClient(c.kind) {
5251 // We need to rewrite the subject and the reply.
5252 if li := jsAckDeliverIdx(creply); li != -1 && li < len(creply)-1 {
5253 remapped = true
5254 subj, creply = creply[li+1:], creply[:li]
5255 }
5256 }
5257
5258 var didDeliver bool
5259
5260 // delivery subject for clients
5261 var dsubj []byte
5262 // Used as scratch if mapping
5263 var _dsubj [128]byte
5264
5265 // For stats, we will keep track of the number of messages that have been
5266 // delivered and then multiply by the size of that message and update
5267 // server and account stats in a "single" operation (instead of per-sub).
5268 // However, we account for situations where the message is possibly changed
5269 // by having an extra size
5270 var dlvMsgs int64
5271 var dlvExtraSize int64
5272 var dlvRouteMsgs int64
5273 var dlvLeafMsgs int64
5274 var dlvClientMsgs int64
5275
5276 // We need to know if this is a MQTT producer because they send messages
5277 // without CR_LF (we otherwise remove the size of CR_LF from message size).
5278 prodIsMQTT := c.isMqtt()
5279
5280 updateStats := func() {
5281 if dlvMsgs == 0 {
5282 return
5283 }
5284
5285 totalBytes := dlvMsgs*int64(len(msg)) + dlvExtraSize
5286 routeBytes := dlvRouteMsgs*int64(len(msg)) + dlvExtraSize
5287 leafBytes := dlvLeafMsgs*int64(len(msg)) + dlvExtraSize
5288 // dlvExtraSize applies to route/leaf header overhead, not client deliveries
5289 clientBytes := dlvClientMsgs * int64(len(msg))
5290
5291 // For non MQTT producers, remove the CR_LF * number of messages
5292 if !prodIsMQTT {
5293 totalBytes -= dlvMsgs * int64(LEN_CR_LF)
5294 routeBytes -= dlvRouteMsgs * int64(LEN_CR_LF)
5295 leafBytes -= dlvLeafMsgs * int64(LEN_CR_LF)
5296 clientBytes -= dlvClientMsgs * int64(LEN_CR_LF)
5297 }
5298
5299 if acc != nil {
5300 acc.stats.Lock()
5301 acc.stats.outMsgs += dlvMsgs
5302 acc.stats.outBytes += totalBytes
5303 if dlvRouteMsgs > 0 {
5304 acc.stats.rt.outMsgs += dlvRouteMsgs
5305 acc.stats.rt.outBytes += routeBytes
5306 }
5307 if dlvLeafMsgs > 0 {
5308 acc.stats.ln.outMsgs += dlvLeafMsgs
5309 acc.stats.ln.outBytes += leafBytes
5310 }
5311 acc.stats.Unlock()
5312 }
5313
5314 if srv := c.srv; srv != nil {
5315 atomic.AddInt64(&srv.outMsgs, dlvMsgs)
5316 atomic.AddInt64(&srv.outBytes, totalBytes)
5317
5318 atomic.AddInt64(&srv.outClientMsgs, dlvClientMsgs)
5319 atomic.AddInt64(&srv.outClientBytes, clientBytes)
5320 }
5321 }
5322
5323 mt, traceOnly := c.isMsgTraceEnabled()
5324
5325 // Loop over all normal subscriptions that match.
5326 for _, sub := range r.psubs {
5327 // Check if this is a send to a ROUTER. We now process
5328 // these after everything else.
5329 switch sub.client.kind {
5330 case ROUTER:
5331 if (c.kind != ROUTER && !c.isSpokeLeafNode()) || (flags&pmrAllowSendFromRouteToRoute != 0) {
5332 c.addSubToRouteTargets(sub)
5333 }
5334 continue
5335 case GATEWAY:
5336 // Never send to gateway from here.
5337 continue
5338 case LEAF:
5339 // We handle similarly to routes and use the same data structures.
5340 // Leaf node delivery audience is different however.
5341 // Also leaf nodes are always no echo, so we make sure we are not
5342 // going to send back to ourselves here. For messages from routes we want
5343 // to suppress in general unless we know from the hub or its a service reply.
5344 if c != sub.client && (c.kind != ROUTER || sub.client.isHubLeafNode() || isServiceReply(c.pa.subject)) {
5345 c.addSubToRouteTargets(sub)
5346 }
5347 continue
5348 }
5349
5350 // Assume delivery subject is the normal subject to this point.
5351 dsubj = subj
5352
5353 // We may need to disable tracing, by setting c.pa.trace to `nil`
5354 // before the call to deliverMsg, if so, this will indicate that
5355 // we need to put it back.
5356 var restorePaTrace bool
5357
5358 // Check for stream import mapped subs (shadow subs). These apply to local subs only.
5359 if sub.im != nil {
5360 // If this message was a service import do not re-export to an exported stream.
5361 if flags&pmrMsgImportedFromService != 0 {
5362 continue
5363 }
5364 if sub.im.tr != nil {
5365 to := sub.im.tr.TransformSubject(bytesToString(subject))
5366 dsubj = append(_dsubj[:0], to...)
5367 } else if sub.im.usePub {
5368 dsubj = append(_dsubj[:0], subj...)
5369 } else {
5370 dsubj = append(_dsubj[:0], sub.im.to...)
5371 }
5372
5373 if mt != nil {
5374 mt.addStreamExportEvent(sub.client, dsubj)
5375 // If allow_trace is false...
5376 if !sub.im.atrc {
5377 // If we are doing only message tracing, we can move to the
5378 // next sub.
5379 if traceOnly {
5380 // Although the message was not delivered, for the purpose
5381 // of didDeliver, we need to set to true (to avoid possible
5382 // no responders).
5383 didDeliver = true
5384 continue
5385 }
5386 // If we are delivering the message, we need to disable tracing
5387 // before calling deliverMsg().
5388 c.pa.trace, restorePaTrace = nil, true
5389 }
5390 }
5391
5392 // Make sure deliver is set if inbound from a route.
5393 if remapped && (c.kind == GATEWAY || c.kind == ROUTER || c.kind == LEAF) {
5394 deliver = subj
5395 }
5396 // If we are mapping for a deliver subject we will reverse roles.
5397 // The original subj we set from above is correct for the msg header,
5398 // but we need to transform the deliver subject to properly route.
5399 if len(deliver) > 0 {
5400 dsubj, subj = subj, dsubj
5401 }
5402 }
5403
5404 // Remap to the original subject if internal.
5405 if sub.icb != nil && sub.rsi {
5406 dsubj = subject
5407 }
5408
5409 // Normal delivery
5410 mh := c.msgHeader(dsubj, creply, sub)
5411 if c.deliverMsg(prodIsMQTT, sub, acc, dsubj, creply, mh, msg, rplyHasGWPrefix) {
5412 // We don't count internal deliveries, so do only when sub.icb is nil.
5413 if sub.icb == nil {
5414 dlvMsgs++
5415 if sub.client.kind == CLIENT {
5416 dlvClientMsgs++
5417 }
5418 }
5419 didDeliver = true
5420 }
5421 if restorePaTrace {
5422 c.pa.trace = mt
5423 }
5424 }
5425
5426 // Set these up to optionally filter based on the queue lists.
5427 // This is for messages received from routes which will have directed
5428 // guidance on which queue groups we should deliver to.
5429 qf := c.pa.queues
5430
5431 // Declared here because of goto.
5432 var queues [][]byte
5433
5434 var leafOrigin string
5435 switch c.kind {
5436 case ROUTER:
5437 if len(c.pa.origin) > 0 {
5438 // Picture a message sent from a leafnode to a server that then routes
5439 // this message: CluserA -leaf-> HUB1 -route-> HUB2
5440 // Here we are in HUB2, so c.kind is a ROUTER, but the message will
5441 // contain a c.pa.origin set to "ClusterA" to indicate that this message
5442 // originated from that leafnode cluster.
5443 leafOrigin = bytesToString(c.pa.origin)
5444 }
5445 case LEAF:
5446 leafOrigin = c.remoteCluster()
5447 }
5448
5449 // For all routes/leaf/gateway connections, we may still want to send messages to
5450 // leaf nodes or routes even if there are no queue filters since we collect
5451 // them above and do not process inline like normal clients.
5452 // However, do select queue subs if asked to ignore empty queue filter.
5453 if (c.kind == LEAF || c.kind == ROUTER || c.kind == GATEWAY) && len(qf) == 0 && flags&pmrIgnoreEmptyQueueFilter == 0 {
5454 goto sendToRoutesOrLeafs
5455 }
5456
5457 // Process queue subs
5458 for i := 0; i < len(r.qsubs); i++ {
5459 qsubs := r.qsubs[i]
5460 // If we have a filter check that here. We could make this a map or someting more
5461 // complex but linear search since we expect queues to be small. Should be faster
5462 // and more cache friendly.
5463 if qf != nil && len(qsubs) > 0 {
5464 tqn := qsubs[0].queue
5465 for _, qn := range qf {
5466 if bytes.Equal(qn, tqn) {
5467 goto selectQSub
5468 }
5469 }
5470 continue
5471 }
5472
5473 selectQSub:
5474 // We will hold onto remote or lead qsubs when we are coming from
5475 // a route or a leaf node just in case we can no longer do local delivery.
5476 var rsub, sub *subscription
5477 var _ql [32]*subscription
5478
5479 src := c.kind
5480 // If we just came from a route we want to prefer local subs.
5481 // So only select from local subs but remember the first rsub
5482 // in case all else fails.
5483 if src == ROUTER {
5484 ql := _ql[:0]
5485 for i := 0; i < len(qsubs); i++ {
5486 sub = qsubs[i]
5487 if dst := sub.client.kind; dst == LEAF || dst == ROUTER {
5488 // If the destination is a LEAF, we first need to make sure
5489 // that we would not pick one that was the origin of this
5490 // message.
5491 if dst == LEAF && leafOrigin != _EMPTY_ && leafOrigin == sub.client.remoteCluster() {
5492 continue
5493 }
5494 // If we have assigned a ROUTER rsub already, replace if
5495 // the destination is a LEAF since we want to favor that.
5496 if rsub == nil || (rsub.client.kind == ROUTER && dst == LEAF) {
5497 rsub = sub
5498 } else if dst == LEAF {
5499 // We already have a LEAF and this is another one.
5500 // Flip a coin to see if we swap it or not.
5501 // See https://github.com/nats-io/nats-server/issues/6040
5502 if fastrand.Uint32()%2 == 1 {
5503 rsub = sub
5504 }
5505 }
5506 } else {
5507 ql = append(ql, sub)
5508 }
5509 }
5510 qsubs = ql
5511 }
5512
5513 sindex := 0
5514 lqs := len(qsubs)
5515 if lqs > 1 {
5516 sindex = int(fastrand.Uint32() % uint32(lqs))
5517 }
5518
5519 // Find a subscription that is able to deliver this message starting at a random index.
5520 // Note that if the message came from a ROUTER, we will only have CLIENT or LEAF
5521 // queue subs here, otherwise we can have all types.
5522 for i := 0; i < lqs; i++ {
5523 if sindex+i < lqs {
5524 sub = qsubs[sindex+i]
5525 } else {
5526 sub = qsubs[(sindex+i)%lqs]
5527 }
5528 if sub == nil {
5529 continue
5530 }
5531
5532 // If we are a spoke leaf node make sure to not forward across routes.
5533 // This mimics same behavior for normal subs above.
5534 if c.kind == LEAF && c.isSpokeLeafNode() && sub.client.kind == ROUTER {
5535 continue
5536 }
5537
5538 // We have taken care of preferring local subs for a message from a route above.
5539 // Here we just care about a client or leaf and skipping a leaf and preferring locals.
5540 if dst := sub.client.kind; dst == ROUTER || dst == LEAF {
5541 if (src == LEAF || src == CLIENT) && dst == LEAF {
5542 // If we come from a LEAF and are about to pick a LEAF connection,
5543 // make sure this is not the same leaf cluster.
5544 if src == LEAF && leafOrigin != _EMPTY_ && leafOrigin == sub.client.remoteCluster() {
5545 continue
5546 }
5547 // Remember that leaf in case we don't find any other candidate.
5548 // We already start randomly in lqs slice, so we don't need
5549 // to do a random swap if we already have an rsub like we do
5550 // when src == ROUTER above.
5551 if rsub == nil {
5552 rsub = sub
5553 }
5554 continue
5555 } else {
5556 // We want to favor qsubs in our own cluster. If the routed
5557 // qsub has an origin, it means that is on behalf of a leaf.
5558 // We need to treat it differently.
5559 if len(sub.origin) > 0 {
5560 // If we already have an rsub, nothing to do. Also, do
5561 // not pick a routed qsub for a LEAF origin cluster
5562 // that is the same than where the message comes from.
5563 if rsub == nil && (leafOrigin == _EMPTY_ || leafOrigin != bytesToString(sub.origin)) {
5564 rsub = sub
5565 }
5566 continue
5567 }
5568 // This is a qsub that is local on the remote server (or
5569 // we are connected to an older server and we don't know).
5570 // Pick this one and be done.
5571 rsub = sub
5572 break
5573 }
5574 }
5575
5576 // Assume delivery subject is normal subject to this point.
5577 dsubj = subj
5578
5579 // We may need to disable tracing, by setting c.pa.trace to `nil`
5580 // before the call to deliverMsg, if so, this will indicate that
5581 // we need to put it back.
5582 var restorePaTrace bool
5583 var skipDelivery bool
5584
5585 // Check for stream import mapped subs. These apply to local subs only.
5586 if sub.im != nil {
5587 // If this message was a service import do not re-export to an exported stream.
5588 if flags&pmrMsgImportedFromService != 0 {
5589 continue
5590 }
5591 if sub.im.tr != nil {
5592 to := sub.im.tr.TransformSubject(bytesToString(subject))
5593 dsubj = append(_dsubj[:0], to...)
5594 } else if sub.im.usePub {
5595 dsubj = append(_dsubj[:0], subj...)
5596 } else {
5597 dsubj = append(_dsubj[:0], sub.im.to...)
5598 }
5599
5600 if mt != nil {
5601 mt.addStreamExportEvent(sub.client, dsubj)
5602 // If allow_trace is false...
5603 if !sub.im.atrc {
5604 // If we are doing only message tracing, we are done
5605 // with this queue group.
5606 if traceOnly {
5607 skipDelivery = true
5608 } else {
5609 // If we are delivering, we need to disable tracing
5610 // before the call to deliverMsg()
5611 c.pa.trace, restorePaTrace = nil, true
5612 }
5613 }
5614 }
5615
5616 // Make sure deliver is set if inbound from a route.
5617 if remapped && (c.kind == GATEWAY || c.kind == ROUTER || c.kind == LEAF) {
5618 deliver = subj
5619 }
5620 // If we are mapping for a deliver subject we will reverse roles.
5621 // The original subj we set from above is correct for the msg header,
5622 // but we need to transform the deliver subject to properly route.
5623 if len(deliver) > 0 {
5624 dsubj, subj = subj, dsubj
5625 }
5626 }
5627
5628 var delivered bool
5629 if !skipDelivery {
5630 mh := c.msgHeader(dsubj, creply, sub)
5631 delivered = c.deliverMsg(prodIsMQTT, sub, acc, subject, creply, mh, msg, rplyHasGWPrefix)
5632 if restorePaTrace {
5633 c.pa.trace = mt
5634 }
5635 }
5636 if skipDelivery || delivered {
5637 // Update only if not skipped.
5638 if !skipDelivery && sub.icb == nil {
5639 dlvMsgs++
5640 switch sub.client.kind {
5641 case ROUTER:
5642 dlvRouteMsgs++
5643 case LEAF:
5644 dlvLeafMsgs++
5645 case CLIENT:
5646 dlvClientMsgs++
5647 }
5648 }
5649 // Do the rest even when message delivery was skipped.
5650 didDeliver = true
5651 // Clear rsub
5652 rsub = nil
5653 if flags&pmrCollectQueueNames != 0 {
5654 queues = append(queues, sub.queue)
5655 }
5656 break
5657 }
5658 }
5659
5660 if rsub != nil {
5661 // We are here if we have selected a leaf or route as the destination,
5662 // or if we tried to deliver to a local qsub but failed.
5663 c.addSubToRouteTargets(rsub)
5664 }
5665 }
5666
5667 sendToRoutesOrLeafs:
5668
5669 // If no messages for routes or leafnodes return here.
5670 if len(c.in.rts) == 0 {
5671 updateStats()
5672 return didDeliver, queues
5673 }
5674
5675 // If we do have a deliver subject we need to do something with it.
5676 // Again this is when JetStream (but possibly others) wants the system
5677 // to rewrite the delivered subject. The way we will do that is place it
5678 // at the end of the reply subject if it exists. But only if this wasn't
5679 // already performed, otherwise we'd end up with a duplicate '@' suffix
5680 // resulting in a protocol error.
5681 if len(deliver) > 0 && len(reply) > 0 && !remapped && !replyHasJSAckSuffix(reply) {
5682 reply = append(slices.Clip(reply), '@')
5683 reply = append(reply, deliver...)
5684 }
5685
5686 // Copy off original pa in case it changes.
5687 pa := c.pa
5688
5689 // We address by index to avoid struct copy.
5690 // We have inline structs for memory layout and cache coherency.
5691 for i := range c.in.rts {
5692 rt := &c.in.rts[i]
5693 if (len(rt.qsubs) > 1 || (len(rt.sub.queue) == 0 && len(rt.qsubs) > 0)) &&
5694 !filterRouteTargetDeny(subject, rt) {
5695 continue
5696 }
5697 dc := rt.sub.client
5698 dmsg, hset := msg, false
5699
5700 // Check if we have an origin cluster set from a leafnode message.
5701 // If so make sure we do not send it back to the same cluster for a different
5702 // leafnode. Cluster wide no echo.
5703 if dc.kind == LEAF {
5704 // Check two scenarios. One is inbound from a route (c.pa.origin),
5705 // and the other is leaf to leaf. In both case, leafOrigin is the one
5706 // to use for the comparison.
5707 if leafOrigin != _EMPTY_ && leafOrigin == dc.remoteCluster() {
5708 continue
5709 }
5710
5711 // We need to check if this is a request that has a stamped client information header.
5712 // This will contain an account but will represent the account from the leafnode. If
5713 // they are not named the same this would cause an account lookup failure trying to
5714 // process the request for something like JetStream or other system services that rely
5715 // on the client info header. We can just check for reply and the presence of a header
5716 // to avoid slow downs for all traffic.
5717 if len(c.pa.reply) > 0 && c.pa.hdr >= 0 {
5718 dmsg, hset = c.checkLeafClientInfoHeader(msg)
5719 }
5720 }
5721
5722 if mt != nil {
5723 dmsg = mt.setHopHeader(c, dmsg)
5724 hset = true
5725 }
5726
5727 mh := c.msgHeaderForRouteOrLeaf(subject, reply, rt, acc)
5728 if c.deliverMsg(prodIsMQTT, rt.sub, acc, subject, reply, mh, dmsg, false) {
5729 if flags&pmrCollectQueueNames != 0 {
5730 for _, qsub := range rt.qsubs {
5731 queues = append(queues, qsub.queue)
5732 }
5733 }
5734 if rt.sub.icb == nil {
5735 dlvMsgs++
5736 switch dc.kind {
5737 case ROUTER:
5738 dlvRouteMsgs++
5739 case LEAF:
5740 dlvLeafMsgs++
5741 }
5742 dlvExtraSize += int64(len(dmsg) - len(msg))
5743 }
5744 didDeliver = true
5745 }
5746
5747 // If we set the header reset the origin pub args.
5748 if hset {
5749 c.pa = pa
5750 }
5751 }
5752 updateStats()
5753 return didDeliver, queues
5754 }
5755
5756 // Check and swap accounts on a client info header destined across a leafnode.
5757 func (c *client) checkLeafClientInfoHeader(msg []byte) (dmsg []byte, setHdr bool) {
5758 if c.pa.hdr < 0 || len(msg) < c.pa.hdr {
5759 return msg, false
5760 }
5761 cir := sliceHeader(ClientInfoHdr, msg[:c.pa.hdr])
5762 if len(cir) == 0 {
5763 return msg, false
5764 }
5765
5766 dmsg = msg
5767
5768 var ci ClientInfo
5769 if err := json.Unmarshal(cir, &ci); err == nil {
5770 if v, _ := c.srv.leafRemoteAccounts.Load(ci.Account); v != nil {
5771 remoteAcc := v.(string)
5772 if ci.Account != remoteAcc {
5773 ci.Account = remoteAcc
5774 if b, _ := json.Marshal(ci); b != nil {
5775 dmsg, setHdr = c.setHeader(ClientInfoHdr, bytesToString(b), msg), true
5776 }
5777 }
5778 }
5779 }
5780 return dmsg, setHdr
5781 }
5782
5783 func (c *client) pubPermissionViolation(subject []byte) {
5784 errTxt := fmt.Sprintf("Permissions Violation for Publish to %q", subject)
5785 if mt, _ := c.isMsgTraceEnabled(); mt != nil {
5786 mt.setIngressError(errTxt)
5787 }
5788 c.sendErr(errTxt)
5789 c.Errorf("Publish Violation - Subject %q", subject)
5790 }
5791
5792 func (c *client) subPermissionViolation(sub *subscription) {
5793 errTxt := fmt.Sprintf("Permissions Violation for Subscription to %q", sub.subject)
5794 logTxt := fmt.Sprintf("Subscription Violation - Subject %q, SID %s", sub.subject, sub.sid)
5795
5796 if sub.queue != nil {
5797 errTxt = fmt.Sprintf("Permissions Violation for Subscription to %q using queue %q", sub.subject, sub.queue)
5798 logTxt = fmt.Sprintf("Subscription Violation - Subject %q, Queue: %q, SID %s", sub.subject, sub.queue, sub.sid)
5799 }
5800
5801 c.sendErr(errTxt)
5802 c.Errorf(logTxt)
5803 }
5804
5805 func (c *client) replySubjectViolation(reply []byte) {
5806 errTxt := fmt.Sprintf("Permissions Violation for Publish with Reply of %q", reply)
5807 if mt, _ := c.isMsgTraceEnabled(); mt != nil {
5808 mt.setIngressError(errTxt)
5809 }
5810 c.sendErr(errTxt)
5811 c.Errorf("Publish Violation - Reply %q", reply)
5812 }
5813
5814 func (c *client) maxTokensViolation(sub *subscription) {
5815 errTxt := fmt.Sprintf("Permissions Violation for Subscription to %q, too many tokens", sub.subject)
5816 logTxt := fmt.Sprintf("Subscription Violation Too Many Tokens - Subject %q, SID %s", sub.subject, sub.sid)
5817 c.sendErr(errTxt)
5818 c.Errorf(logTxt)
5819 }
5820
5821 func (c *client) processPingTimer() {
5822 c.mu.Lock()
5823 c.ping.tmr = nil
5824 // Check if connection is still opened
5825 if c.isClosed() {
5826 c.mu.Unlock()
5827 return
5828 }
5829
5830 c.Debugf("%s Ping Timer", c.kindString())
5831
5832 var sendPing bool
5833
5834 opts := c.srv.getOpts()
5835 pingInterval := opts.PingInterval
5836 if c.kind == ROUTER && opts.Cluster.PingInterval > 0 {
5837 pingInterval = opts.Cluster.PingInterval
5838 }
5839 if c.isWebsocket() && opts.Websocket.PingInterval > 0 {
5840 pingInterval = opts.Websocket.PingInterval
5841 }
5842 pingInterval = adjustPingInterval(c.kind, pingInterval)
5843 now := time.Now()
5844 needRTT := c.rtt == 0 || now.Sub(c.rttStart) > DEFAULT_RTT_MEASUREMENT_INTERVAL
5845
5846 // Do not delay PINGs for ROUTER, GATEWAY or spoke LEAF connections.
5847 if c.kind == ROUTER || c.kind == GATEWAY || c.isSpokeLeafNode() {
5848 sendPing = true
5849 } else {
5850 // If we received client data or a ping from the other side within the PingInterval,
5851 // then there is no need to send a ping.
5852 if delta := now.Sub(c.lastIn); delta < pingInterval && !needRTT {
5853 c.Debugf("Delaying PING due to remote client data or ping %v ago", delta.Round(time.Second))
5854 } else {
5855 sendPing = true
5856 }
5857 }
5858
5859 if sendPing {
5860 // Check for violation
5861 maxPingsOut := opts.MaxPingsOut
5862 if c.kind == ROUTER && opts.Cluster.MaxPingsOut > 0 {
5863 maxPingsOut = opts.Cluster.MaxPingsOut
5864 }
5865 if c.ping.out+1 > maxPingsOut {
5866 c.Debugf("Stale Client Connection - Closing")
5867 c.enqueueProto([]byte(fmt.Sprintf(errProto, "Stale Connection")))
5868 c.mu.Unlock()
5869 c.closeConnection(StaleConnection)
5870 return
5871 }
5872 // Send PING
5873 c.sendPing()
5874 }
5875
5876 // Reset to fire again.
5877 c.setPingTimer()
5878 c.mu.Unlock()
5879 }
5880
5881 // Returns the smallest value between the given `d` and some max value
5882 // based on the connection kind.
5883 func adjustPingInterval(kind int, d time.Duration) time.Duration {
5884 switch kind {
5885 case ROUTER:
5886 if d > routeMaxPingInterval {
5887 return routeMaxPingInterval
5888 }
5889 case GATEWAY:
5890 if d > gatewayMaxPingInterval {
5891 return gatewayMaxPingInterval
5892 }
5893 }
5894 return d
5895 }
5896
5897 // This is used when a connection cannot yet start to send PINGs because
5898 // the remote would not be able to handle them (case of compression,
5899 // or outbound gateway, etc...), but we still want to close the connection
5900 // if the timer has not been reset by the time we reach the time equivalent
5901 // to have sent the max number of pings.
5902 //
5903 // Lock should be held
5904 func (c *client) watchForStaleConnection(pingInterval time.Duration, pingMax int) {
5905 c.ping.tmr = time.AfterFunc(pingInterval*time.Duration(pingMax+1), func() {
5906 c.mu.Lock()
5907 c.Debugf("Stale Client Connection - Closing")
5908 c.enqueueProto([]byte(fmt.Sprintf(errProto, "Stale Connection")))
5909 c.mu.Unlock()
5910 c.closeConnection(StaleConnection)
5911 })
5912 }
5913
5914 // Lock should be held
5915 func (c *client) setPingTimer() {
5916 if c.srv == nil {
5917 return
5918 }
5919 opts := c.srv.getOpts()
5920 d := opts.PingInterval
5921 if c.kind == ROUTER && opts.Cluster.PingInterval > 0 {
5922 d = opts.Cluster.PingInterval
5923 }
5924 if c.isWebsocket() && opts.Websocket.PingInterval > 0 {
5925 d = opts.Websocket.PingInterval
5926 }
5927 d = adjustPingInterval(c.kind, d)
5928 c.ping.tmr = time.AfterFunc(d, c.processPingTimer)
5929 }
5930
5931 // Lock should be held
5932 func (c *client) clearPingTimer() {
5933 if c.ping.tmr == nil {
5934 return
5935 }
5936 c.ping.tmr.Stop()
5937 c.ping.tmr = nil
5938 }
5939
5940 func (c *client) clearTlsToTimer() {
5941 if c.tlsTo == nil {
5942 return
5943 }
5944 c.tlsTo.Stop()
5945 c.tlsTo = nil
5946 }
5947
5948 // Lock should be held
5949 func (c *client) setAuthTimer(d time.Duration) {
5950 c.atmr = time.AfterFunc(d, c.authTimeout)
5951 }
5952
5953 // Lock should be held
5954 func (c *client) clearAuthTimer() bool {
5955 if c.atmr == nil {
5956 return true
5957 }
5958 stopped := c.atmr.Stop()
5959 c.atmr = nil
5960 return stopped
5961 }
5962
5963 // Track whether the parser should still enforce pre-CONNECT rules.
5964 // This is handshake state, not timer state, since some handshakes
5965 // use a different timer while still expecting CONNECT.
5966 // Lock assume held on entry.
5967 func (c *client) awaitingAuth() bool {
5968 return c.flags.isSet(expectConnect) && !c.flags.isSet(connectReceived)
5969 }
5970
5971 // This will set the atmr for the JWT expiration time.
5972 // We will lock on entry.
5973 func (c *client) setExpirationTimer(d time.Duration) {
5974 c.mu.Lock()
5975 c.setExpirationTimerUnlocked(d)
5976 c.mu.Unlock()
5977 }
5978
5979 // This will set the atmr for the JWT expiration time. client lock should be held before call
5980 func (c *client) setExpirationTimerUnlocked(d time.Duration) {
5981 c.atmr = time.AfterFunc(d, c.authExpired)
5982 // This is an JWT expiration.
5983 if c.flags.isSet(connectReceived) {
5984 c.expires = time.Now().Add(d).Truncate(time.Second)
5985 }
5986 }
5987
5988 // Return when this client expires via a claim, or 0 if not set.
5989 func (c *client) claimExpiration() time.Duration {
5990 c.mu.Lock()
5991 defer c.mu.Unlock()
5992 if c.expires.IsZero() {
5993 return 0
5994 }
5995 return time.Until(c.expires).Truncate(time.Second)
5996 }
5997
5998 // Possibly flush the connection and then close the low level connection.
5999 // The boolean `minimalFlush` indicates if the flush operation should have a
6000 // minimal write deadline.
6001 // Lock is held on entry.
6002 func (c *client) flushAndClose(minimalFlush bool) {
6003 if !c.flags.isSet(skipFlushOnClose) && c.out.pb > 0 {
6004 if minimalFlush {
6005 const lowWriteDeadline = 100 * time.Millisecond
6006
6007 // Reduce the write deadline if needed.
6008 if c.out.wdl > lowWriteDeadline {
6009 c.out.wdl = lowWriteDeadline
6010 }
6011 }
6012 c.flushOutbound()
6013 }
6014 for i := range c.out.nb {
6015 nbPoolPut(c.out.nb[i])
6016 }
6017 c.out.nb = nil
6018 // We can't touch c.out.wnb when a flushOutbound is in progress since it
6019 // is accessed outside the lock there. If in progress, the cleanup will be
6020 // done in flushOutbound when detecting that connection is closed.
6021 if !c.flags.isSet(flushOutbound) {
6022 for i := range c.out.wnb {
6023 nbPoolPut(c.out.wnb[i])
6024 }
6025 c.out.wnb = nil
6026 }
6027 // This seem to be important (from experimentation) for the GC to release
6028 // the connection.
6029 c.out.sg = nil
6030
6031 // Close the low level connection.
6032 if c.nc != nil {
6033 // Starting with Go 1.16, the low level close will set its own deadline
6034 // of 5 seconds, so setting our own deadline does not work. Instead,
6035 // we will close the TLS connection in separate go routine.
6036 nc := c.nc
6037 c.nc = nil
6038 if _, ok := nc.(*tls.Conn); ok {
6039 go func() { nc.Close() }()
6040 } else {
6041 nc.Close()
6042 }
6043 }
6044 }
6045
6046 var kindStringMap = map[int]string{
6047 CLIENT: "Client",
6048 ROUTER: "Router",
6049 GATEWAY: "Gateway",
6050 LEAF: "Leafnode",
6051 JETSTREAM: "JetStream",
6052 ACCOUNT: "Account",
6053 SYSTEM: "System",
6054 }
6055
6056 func (c *client) kindString() string {
6057 if kindStringVal, ok := kindStringMap[c.kind]; ok {
6058 return kindStringVal
6059 }
6060 return "Unknown Type"
6061 }
6062
6063 // swapAccountAfterReload will check to make sure the bound account for this client
6064 // is current. Under certain circumstances after a reload we could be pointing to
6065 // an older one.
6066 func (c *client) swapAccountAfterReload() {
6067 c.mu.Lock()
6068 srv := c.srv
6069 an := c.acc.GetName()
6070 c.mu.Unlock()
6071 if srv == nil {
6072 return
6073 }
6074 if acc, _ := srv.LookupAccount(an); acc != nil {
6075 c.mu.Lock()
6076 if c.acc != acc {
6077 c.acc = acc
6078 }
6079 c.mu.Unlock()
6080 }
6081 }
6082
6083 // processSubsOnConfigReload removes any subscriptions the client has that are no
6084 // longer authorized, and checks for imports (accounts) due to a config reload.
6085 func (c *client) processSubsOnConfigReload(awcsti map[string]struct{}) {
6086 c.mu.Lock()
6087 var (
6088 checkPerms = c.perms != nil
6089 checkAcc = c.acc != nil
6090 acc = c.acc
6091 )
6092 if !checkPerms && !checkAcc {
6093 c.mu.Unlock()
6094 return
6095 }
6096 var (
6097 _subs [32]*subscription
6098 subs = _subs[:0]
6099 _removed [32]*subscription
6100 removed = _removed[:0]
6101 srv = c.srv
6102 )
6103 if checkAcc {
6104 // We actually only want to check if stream imports have changed.
6105 if _, ok := awcsti[acc.Name]; !ok {
6106 checkAcc = false
6107 }
6108 }
6109 // We will clear any mperms we have here. It will rebuild on the fly with canSubscribe,
6110 // so we do that here as we collect them. We will check result down below.
6111 c.mperms = nil
6112 // Collect client's subs under the lock
6113 for _, sub := range c.subs {
6114 // Just checking to rebuild mperms under the lock, will collect removed though here.
6115 // Only collect under subs array of canSubscribe and checkAcc true.
6116 var allowed bool
6117 if len(sub.queue) > 0 {
6118 allowed = c.canSubscribe(string(sub.subject), string(sub.queue))
6119 } else {
6120 allowed = c.canSubscribe(string(sub.subject))
6121 }
6122 if !allowed {
6123 removed = append(removed, sub)
6124 } else if checkAcc {
6125 subs = append(subs, sub)
6126 }
6127 }
6128 c.mu.Unlock()
6129
6130 // This list is all subs who are allowed and we need to check accounts.
6131 for _, sub := range subs {
6132 c.mu.Lock()
6133 oldShadows := sub.shadow
6134 sub.shadow = nil
6135 c.mu.Unlock()
6136 c.addShadowSubscriptions(acc, sub)
6137 for _, nsub := range oldShadows {
6138 nsub.im.acc.sl.Remove(nsub)
6139 }
6140 }
6141
6142 // Unsubscribe all that need to be removed and report back to client and logs.
6143 for _, sub := range removed {
6144 c.unsubscribe(acc, sub, true, true)
6145 if len(sub.queue) > 0 {
6146 c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q using queue %q (sid %q)", sub.subject, sub.queue, sub.sid))
6147 srv.Noticef("Removed sub %q using queue %q (sid %q) for %s - not authorized", sub.subject, sub.queue, sub.sid, c.getAuthUser())
6148 } else {
6149 c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q (sid %q)", sub.subject, sub.sid))
6150 srv.Noticef("Removed sub %q (sid %q) for %s - not authorized", sub.subject, sub.sid, c.getAuthUser())
6151 }
6152 }
6153 }
6154
6155 // Allows us to count up all the queue subscribers during close.
6156 type qsub struct {
6157 sub *subscription
6158 n int32
6159 }
6160
6161 func (c *client) closeConnection(reason ClosedState) {
6162 c.mu.Lock()
6163 if c.flags.isSet(closeConnection) {
6164 c.mu.Unlock()
6165 return
6166 }
6167 // Note that we may have markConnAsClosed() invoked before closeConnection(),
6168 // so don't set this to 1, instead bump the count.
6169 c.rref++
6170 c.flags.set(closeConnection)
6171 c.clearAuthTimer()
6172 c.clearPingTimer()
6173 c.clearTlsToTimer()
6174 c.markConnAsClosed(reason)
6175
6176 // Unblock anyone who is potentially stalled waiting on us.
6177 if c.out.stc != nil {
6178 close(c.out.stc)
6179 c.out.stc = nil
6180 }
6181
6182 // If we have remote latency tracking running shut that down.
6183 if c.rrTracking != nil {
6184 c.rrTracking.ptmr.Stop()
6185 c.rrTracking = nil
6186 }
6187
6188 // If we are shutting down, no need to do all the accounting on subs, etc.
6189 // During LDM we'll still do the accounting, otherwise account limits could close others after this reconnects.
6190 if reason == ServerShutdown && c.srv.isShuttingDown() {
6191 s := c.srv
6192 c.mu.Unlock()
6193 if s != nil {
6194 // Unregister
6195 s.removeClient(c)
6196 }
6197 return
6198 }
6199
6200 var (
6201 kind = c.kind
6202 srv = c.srv
6203 noReconnect = c.flags.isSet(noReconnect)
6204 acc = c.acc
6205 )
6206 c.mu.Unlock()
6207
6208 if kind == ROUTER {
6209 c.removeRemoteSubs()
6210 }
6211 if srv != nil {
6212 // Unregister
6213 srv.removeClient(c)
6214
6215 if acc != nil {
6216 // Update remote subscriptions.
6217 if kind == CLIENT || kind == LEAF || kind == JETSTREAM {
6218 // Remove client's subscriptions from the account and unregister
6219 // client from that account. Keep c.subs populated because
6220 // saveClosedClient (started as a goroutine in markConnAsClosed)
6221 // still needs to read it.
6222 c.clearAccountSubs(true)
6223 }
6224 // Always remove from the account, otherwise we can leak clients.
6225 // Note that SYSTEM and ACCOUNT types from above cleanup their own subs.
6226 if prev := acc.removeClient(c); prev == 1 {
6227 srv.decActiveAccounts()
6228 }
6229 }
6230 }
6231
6232 // Now that we are done with subscriptions, clear the field so that the
6233 // connection can be released and gc'ed.
6234 if kind == CLIENT || kind == LEAF {
6235 c.mu.Lock()
6236 c.subs = nil
6237 c.mu.Unlock()
6238 }
6239
6240 // Don't reconnect connections that have been marked with
6241 // the no reconnect flag.
6242 if noReconnect {
6243 return
6244 }
6245
6246 c.reconnect()
6247 }
6248
6249 // clearAccountSubs removes the client's subscriptions from its current account
6250 // and unregisters it from that account. If close is true, c.subs is left
6251 // populated for saveClosedClient; otherwise c.subs is cleared and c.acc
6252 // registered back to the global account.
6253 // Client lock MUST NOT be held on entry.
6254 func (c *client) clearAccountSubs(close bool) {
6255 c.mu.Lock()
6256 kind := c.kind
6257 srv := c.srv
6258 acc := c.acc
6259 if acc == nil || (kind != CLIENT && kind != LEAF && kind != JETSTREAM) {
6260 c.mu.Unlock()
6261 return
6262 }
6263 var _subs [32]*subscription
6264 subs := _subs[:0]
6265 // Do not set c.subs to nil or delete the sub from c.subs here because
6266 // it will be needed in saveClosedClient (which has been started as a
6267 // go routine in markConnAsClosed). Cleanup will be done there.
6268 for _, sub := range c.subs {
6269 // Auto-unsubscribe subscriptions must be unsubscribed forcibly.
6270 sub.max = 0
6271 sub.close()
6272 subs = append(subs, sub)
6273 if !close {
6274 delete(c.subs, string(sub.sid))
6275 }
6276 }
6277 spoke := c.isSpokeLeafNode()
6278 c.mu.Unlock()
6279
6280 acc.sl.RemoveBatch(subs)
6281
6282 if srv != nil {
6283 qsubs := map[string]*qsub{}
6284 for _, sub := range subs {
6285 // Call unsubscribe here to cleanup shadow subscriptions and such.
6286 c.unsubscribe(acc, sub, true, false)
6287 // Update route as normal for a normal subscriber.
6288 if sub.queue == nil {
6289 if !spoke {
6290 srv.updateRouteSubscriptionMap(acc, sub, -1)
6291 if srv.gateway.enabled {
6292 srv.gatewayUpdateSubInterest(acc.Name, sub, -1)
6293 }
6294 }
6295 acc.updateLeafNodes(sub, -1)
6296 } else {
6297 // We handle queue subscribers special in case we
6298 // have a bunch we can just send one update to the
6299 // connected routes.
6300 num := int32(1)
6301 if kind == LEAF {
6302 num = sub.qw
6303 }
6304 key := keyFromSub(sub)
6305 if esub, ok := qsubs[key]; ok {
6306 esub.n += num
6307 } else {
6308 qsubs[key] = &qsub{sub, num}
6309 }
6310 }
6311 }
6312 // Process any qsubs here.
6313 for _, esub := range qsubs {
6314 if !spoke {
6315 srv.updateRouteSubscriptionMap(acc, esub.sub, -(esub.n))
6316 if srv.gateway.enabled {
6317 srv.gatewayUpdateSubInterest(acc.Name, esub.sub, -(esub.n))
6318 }
6319 }
6320 acc.updateLeafNodes(esub.sub, -(esub.n))
6321 }
6322 }
6323
6324 if !close {
6325 // Register back to global account, mimicking the state after client initialization.
6326 c.registerWithAccount(srv.globalAccount())
6327 }
6328 }
6329
6330 // Depending on the kind of connections, this may attempt to recreate a connection.
6331 // The actual reconnect attempt will be started in a go routine.
6332 func (c *client) reconnect() {
6333 var (
6334 retryImplicit bool
6335 gwName string
6336 gwIsOutbound bool
6337 gwCfg *gatewayCfg
6338 leafCfg *leafNodeCfg
6339 )
6340
6341 c.mu.Lock()
6342 // Decrease the ref count and perform the reconnect only if == 0.
6343 c.rref--
6344 if c.flags.isSet(noReconnect) || c.rref > 0 {
6345 c.mu.Unlock()
6346 return
6347 }
6348 if c.route != nil {
6349 // A route is marked as solicited if it was given an URL to connect to,
6350 // which would be the case even with implicit (due to gossip), so mark this
6351 // as a retry for a route that is solicited and not explicit.
6352 retryImplicit = c.route.retry || (c.route.didSolicit && c.route.routeType == Implicit)
6353 }
6354 kind := c.kind
6355 switch kind {
6356 case GATEWAY:
6357 gwName = c.gw.name
6358 gwIsOutbound = c.gw.outbound
6359 gwCfg = c.gw.cfg
6360 case LEAF:
6361 if c.isSolicitedLeafNode() {
6362 leafCfg = c.leaf.remote
6363 }
6364 }
6365 srv := c.srv
6366 c.mu.Unlock()
6367
6368 // Check for a solicited route. If it was, start up a reconnect unless
6369 // we are already connected to the other end.
6370 if didSolicit := c.isSolicitedRoute(); didSolicit || retryImplicit {
6371 srv.mu.Lock()
6372 defer srv.mu.Unlock()
6373
6374 // Capture these under lock
6375 c.mu.Lock()
6376 rid := c.route.remoteID
6377 rtype := c.route.routeType
6378 rurl := c.route.url
6379 accName := string(c.route.accName)
6380 checkRID := accName == _EMPTY_ && srv.getOpts().Cluster.PoolSize < 1 && rid != _EMPTY_
6381 c.mu.Unlock()
6382
6383 // It is possible that the server is being shutdown.
6384 // If so, don't try to reconnect
6385 if !srv.isRunning() {
6386 return
6387 }
6388
6389 if checkRID && srv.routes[rid] != nil {
6390 // This is the case of "no pool". Make sure that the registered one
6391 // is upgraded to solicited if the connection trying to reconnect
6392 // was a solicited one.
6393 if didSolicit {
6394 if remote := srv.routes[rid][0]; remote != nil {
6395 upgradeRouteToSolicited(remote, rurl, rtype)
6396 }
6397 }
6398 srv.Debugf("Not attempting reconnect for solicited route, already connected to %q", rid)
6399 return
6400 } else if rid == srv.info.ID {
6401 srv.Debugf("Detected route to self, ignoring %q", rurl.Redacted())
6402 return
6403 } else if rtype != Implicit || retryImplicit {
6404 srv.Debugf("Attempting reconnect for solicited route %q", rurl.Redacted())
6405 // Keep track of this go-routine so we can wait for it on
6406 // server shutdown.
6407 srv.startGoRoutine(func() { srv.reConnectToRoute(rurl, rtype, accName) })
6408 }
6409 } else if srv != nil && kind == GATEWAY && gwIsOutbound {
6410 if gwCfg != nil {
6411 srv.Debugf("Attempting reconnect for gateway %q", gwName)
6412 // Run this as a go routine since we may be called within
6413 // the solicitGateway itself if there was an error during
6414 // the creation of the gateway connection.
6415 srv.startGoRoutine(func() { srv.reconnectGateway(gwCfg) })
6416 } else {
6417 srv.Debugf("Gateway %q not in configuration, not attempting reconnect", gwName)
6418 }
6419 } else if leafCfg != nil {
6420 // This is a solicited leaf node. Start up a reconnect.
6421 srv.startGoRoutine(func() { srv.reConnectToRemoteLeafNode(leafCfg) })
6422 }
6423 }
6424
6425 // Set the noReconnect flag. This is used before a call to closeConnection()
6426 // to prevent the connection to reconnect (routes, gateways).
6427 func (c *client) setNoReconnect() {
6428 c.mu.Lock()
6429 c.flags.set(noReconnect)
6430 c.mu.Unlock()
6431 }
6432
6433 // Returns the client's RTT value with the protection of the client's lock.
6434 func (c *client) getRTTValue() time.Duration {
6435 c.mu.Lock()
6436 rtt := c.rtt
6437 c.mu.Unlock()
6438 return rtt
6439 }
6440
6441 // This function is used by ROUTER and GATEWAY connections to
6442 // look for a subject on a given account (since these type of
6443 // connections are not bound to a specific account).
6444 // If the c.pa.subject is found in the cache, the cached result
6445 // is returned, otherwse, we match the account's sublist and update
6446 // the cache. The cache is pruned if reaching a certain size.
6447 func (c *client) getAccAndResultFromCache() (*Account, *SublistResult) {
6448 var (
6449 acc *Account
6450 pac *perAccountCache
6451 r *SublistResult
6452 ok bool
6453 )
6454 // Check our cache.
6455 if pac, ok = c.in.pacache[string(c.pa.pacache)]; ok {
6456 // Check the genid to see if it's still valid.
6457 // Since v2.10.0, the config reload of accounts has been fixed
6458 // and an account's sublist pointer should not change, so no need to
6459 // lock to access it.
6460 sl := pac.acc.sl
6461
6462 if genid := atomic.LoadUint64(&sl.genid); genid != pac.genid {
6463 ok = false
6464 clear(c.in.pacache)
6465 } else {
6466 acc = pac.acc
6467 r = pac.results
6468 }
6469 }
6470
6471 if !ok {
6472 if c.kind == ROUTER && len(c.route.accName) > 0 {
6473 if acc = c.acc; acc == nil {
6474 return nil, nil
6475 }
6476 } else {
6477 // Match correct account and sublist.
6478 if acc, _ = c.srv.LookupAccount(bytesToString(c.pa.account)); acc == nil {
6479 return nil, nil
6480 }
6481 }
6482 sl := acc.sl
6483
6484 // Match against the account sublist.
6485 r = sl.MatchBytes(c.pa.subject)
6486
6487 // Check if we need to prune. This should give us a perAccountCache struct
6488 // to reuse instead of having to allocate a new one.
6489 // Previously we would have removed multiple entries but now we will only
6490 // prune the minimum number required to maintain the cache size, so that
6491 // we reduce the amount of GC pressure and maintain cache stability as best
6492 // as possible.
6493 if len(c.in.pacache) >= maxPerAccountCacheSize {
6494 for cacheKey, p := range c.in.pacache {
6495 delete(c.in.pacache, cacheKey)
6496 pac = p
6497 if len(c.in.pacache) < maxPerAccountCacheSize {
6498 break
6499 }
6500 }
6501 }
6502
6503 // If we can reuse the pac from earlier (i.e. we loaded one but it was an
6504 // old generation or we pruned the cache) then do so.
6505 if pac == nil {
6506 pac = &perAccountCache{}
6507 }
6508 pac.acc = acc
6509 pac.results = r
6510 pac.genid = atomic.LoadUint64(&sl.genid)
6511
6512 // Store in our cache,make sure to do so after we prune.
6513 c.in.pacache[string(c.pa.pacache)] = pac
6514 }
6515 return acc, r
6516 }
6517
6518 // Account will return the associated account for this client.
6519 func (c *client) Account() *Account {
6520 if c == nil {
6521 return nil
6522 }
6523 c.mu.Lock()
6524 acc := c.acc
6525 c.mu.Unlock()
6526 return acc
6527 }
6528
6529 // pruneClosedSubFromPerAccountCache remove entries that contain subscriptions
6530 // that have been closed.
6531 func (c *client) pruneClosedSubFromPerAccountCache() {
6532 for cacheKey, pac := range c.in.pacache {
6533 for _, sub := range pac.results.psubs {
6534 if sub.isClosed() {
6535 goto REMOVE
6536 }
6537 }
6538 for _, qsub := range pac.results.qsubs {
6539 for _, sub := range qsub {
6540 if sub.isClosed() {
6541 goto REMOVE
6542 }
6543 }
6544 }
6545 continue
6546 REMOVE:
6547 delete(c.in.pacache, cacheKey)
6548 }
6549 }
6550
6551 // Returns our service account for this request.
6552 func (ci *ClientInfo) serviceAccount() string {
6553 if ci == nil {
6554 return _EMPTY_
6555 }
6556 if ci.Service != _EMPTY_ {
6557 return ci.Service
6558 }
6559 return ci.Account
6560 }
6561
6562 // Add in our server and cluster information to this client info.
6563 func (c *client) addServerAndClusterInfo(ci *ClientInfo) {
6564 if ci == nil {
6565 return
6566 }
6567 // Server
6568 if c.kind != LEAF {
6569 ci.Server = c.srv.Name()
6570 } else if c.kind == LEAF {
6571 ci.Server = c.leaf.remoteServer
6572 }
6573 // Cluster
6574 ci.Cluster = c.srv.cachedClusterName()
6575 // If we have gateways fill in cluster alternates.
6576 // These will be in RTT asc order.
6577 if c.srv.gateway.enabled {
6578 var gws []*client
6579 c.srv.getOutboundGatewayConnections(&gws)
6580 for _, c := range gws {
6581 c.mu.Lock()
6582 cn := c.gw.name
6583 c.mu.Unlock()
6584 ci.Alternates = append(ci.Alternates, cn)
6585 }
6586 }
6587 }
6588
6589 // Grabs the information for this client.
6590 func (c *client) getClientInfo(detailed bool) *ClientInfo {
6591 if c == nil || (c.kind != CLIENT && c.kind != LEAF && c.kind != JETSTREAM && c.kind != ACCOUNT) {
6592 return nil
6593 }
6594
6595 // Result
6596 var ci ClientInfo
6597
6598 if detailed {
6599 c.addServerAndClusterInfo(&ci)
6600 }
6601
6602 c.mu.Lock()
6603 // RTT and Account are always added.
6604 ci.Account = accForClient(c)
6605 ci.RTT = c.rtt
6606 // Detailed signals additional opt in.
6607 if detailed {
6608 ci.Start = &c.start
6609 ci.Host = c.host
6610 ci.ID = c.cid
6611 ci.Name = c.opts.Name
6612 ci.User = c.getRawAuthUser()
6613 ci.Lang = c.opts.Lang
6614 ci.Version = c.opts.Version
6615 ci.Jwt = c.opts.JWT
6616 ci.IssuerKey = issuerForClient(c)
6617 ci.NameTag = c.nameTag
6618 ci.Tags = c.tags
6619 ci.Kind = c.kindString()
6620 ci.ClientType = c.clientTypeString()
6621 }
6622 c.mu.Unlock()
6623 return &ci
6624 }
6625
6626 func (c *client) doTLSServerHandshake(typ string, tlsConfig *tls.Config, timeout float64, pCerts PinnedCertSet) error {
6627 _, err := c.doTLSHandshake(typ, false, nil, tlsConfig, _EMPTY_, timeout, pCerts)
6628 return err
6629 }
6630
6631 func (c *client) doTLSClientHandshake(typ string, url *url.URL, tlsConfig *tls.Config, tlsName string, timeout float64, pCerts PinnedCertSet) (bool, error) {
6632 return c.doTLSHandshake(typ, true, url, tlsConfig, tlsName, timeout, pCerts)
6633 }
6634
6635 // Performs either server or client side (if solicit is true) TLS Handshake.
6636 // On error, the TLS handshake error has been logged and the connection
6637 // has been closed.
6638 //
6639 // Lock is held on entry.
6640 func (c *client) doTLSHandshake(typ string, solicit bool, url *url.URL, tlsConfig *tls.Config, tlsName string, timeout float64, pCerts PinnedCertSet) (bool, error) {
6641 var host string
6642 var resetTLSName bool
6643 var err error
6644
6645 // Capture kind for some debug/error statements.
6646 kind := c.kind
6647
6648 // If we solicited, we will act like the client, otherwise the server.
6649 if solicit {
6650 c.Debugf("Starting TLS %s client handshake", typ)
6651 if tlsConfig.ServerName == _EMPTY_ {
6652 // If the given url is a hostname, use this hostname for the
6653 // ServerName. If it is an IP, use the cfg's tlsName. If none
6654 // is available, resort to current IP.
6655 host = url.Hostname()
6656 if tlsName != _EMPTY_ && net.ParseIP(host) != nil {
6657 host = tlsName
6658 }
6659 tlsConfig.ServerName = host
6660 }
6661 c.nc = tls.Client(c.nc, tlsConfig)
6662 } else {
6663 if kind == CLIENT {
6664 c.Debugf("Starting TLS client connection handshake")
6665 } else {
6666 c.Debugf("Starting TLS %s server handshake", typ)
6667 }
6668 c.nc = tls.Server(c.nc, tlsConfig)
6669 }
6670
6671 conn := c.nc.(*tls.Conn)
6672
6673 // Setup the timeout
6674 ttl := secondsToDuration(timeout)
6675 c.tlsTo = time.AfterFunc(ttl, func() { tlsTimeout(c, conn) })
6676 conn.SetReadDeadline(time.Now().Add(ttl))
6677
6678 c.mu.Unlock()
6679 if err = conn.Handshake(); err != nil {
6680 if solicit {
6681 // Based on type of error, possibly clear the saved tlsName
6682 // See: https://github.com/nats-io/nats-server/issues/1256
6683 // NOTE: As of Go 1.20, the HostnameError is wrapped so cannot
6684 // type assert to check directly.
6685 var hostnameErr x509.HostnameError
6686 if errors.As(err, &hostnameErr) {
6687 if host == tlsName {
6688 resetTLSName = true
6689 }
6690 }
6691 }
6692 } else if !c.matchesPinnedCert(pCerts) {
6693 err = ErrCertNotPinned
6694 }
6695
6696 if err != nil {
6697 var detail string
6698 var subjs []string
6699 if ve, ok := err.(*tls.CertificateVerificationError); ok {
6700 for _, cert := range ve.UnverifiedCertificates {
6701 fp := sha256.Sum256(cert.Raw)
6702 fph := hex.EncodeToString(fp[:])
6703 subjs = append(subjs, fmt.Sprintf("%s SHA-256: %s", cert.Subject.String(), fph))
6704 }
6705 }
6706 if len(subjs) > 0 {
6707 detail = fmt.Sprintf(" (%s)", strings.Join(subjs, "; "))
6708 }
6709 if kind == ROUTER || kind == GATEWAY {
6710 // Always surface these as errors, as these ports shouldn't be behind a load
6711 // balancer or regularly probed.
6712 c.Errorf("TLS %s handshake error: %v%s", typ, err, detail)
6713 } else {
6714 logf := c.Errorf
6715 if isClientProbeTLSHandshakeError(err) {
6716 logf = c.Debugf
6717 }
6718 if kind == CLIENT {
6719 logf("TLS handshake error: %v%s", err, detail)
6720 } else {
6721 logf("TLS %s handshake error: %v%s", typ, err, detail)
6722 }
6723 }
6724 c.closeConnection(TLSHandshakeError)
6725
6726 // Grab the lock before returning since the caller was holding the lock on entry
6727 c.mu.Lock()
6728 // Returning any error is fine. Since the connection is closed ErrConnectionClosed
6729 // is appropriate.
6730 return resetTLSName, ErrConnectionClosed
6731 }
6732
6733 // Reset the read deadline
6734 conn.SetReadDeadline(time.Time{})
6735
6736 // Re-Grab lock
6737 c.mu.Lock()
6738
6739 // To be consistent with client, set this flag to indicate that handshake is done
6740 c.flags.set(handshakeComplete)
6741
6742 // The connection still may have been closed on success handshake due
6743 // to a race with tls timeout. If that the case, return error indicating
6744 // that the connection is closed.
6745 if c.isClosed() {
6746 err = ErrConnectionClosed
6747 }
6748
6749 return false, err
6750 }
6751
6752 func isClientProbeTLSHandshakeError(err error) bool {
6753 var netErr net.Error
6754 if errors.As(err, &netErr) && netErr.Timeout() {
6755 return true
6756 }
6757 var recordHeaderErr tls.RecordHeaderError
6758 // Conn is only set by crypto/tls when the invalid record was the peer's
6759 // initial handshake bytes, which is the non-TLS probe/load-balancer case.
6760 return errors.As(err, &recordHeaderErr) && recordHeaderErr.Conn != nil
6761 }
6762
6763 // getRawAuthUser returns the raw auth user for the client.
6764 // Lock should be held.
6765 func (c *client) getRawAuthUser() string {
6766 switch {
6767 case c.opts.Nkey != _EMPTY_:
6768 return c.opts.Nkey
6769 case c.opts.Username != _EMPTY_:
6770 return c.opts.Username
6771 case c.opts.JWT != _EMPTY_:
6772 return c.pubKey
6773 case c.opts.Token != _EMPTY_:
6774 return "[REDACTED]"
6775 default:
6776 return _EMPTY_
6777 }
6778 }
6779
6780 // getAuthUser returns the auth user for the client.
6781 // Lock should be held.
6782 func (c *client) getAuthUser() string {
6783 switch {
6784 case c.opts.Nkey != _EMPTY_:
6785 return fmt.Sprintf("Nkey %q", c.opts.Nkey)
6786 case c.opts.Username != _EMPTY_:
6787 return fmt.Sprintf("User %q", c.opts.Username)
6788 case c.opts.JWT != _EMPTY_:
6789 return fmt.Sprintf("JWT User %q", c.pubKey)
6790 case c.opts.Token != _EMPTY_:
6791 return fmt.Sprintf("Token %q", "[REDACTED]")
6792 default:
6793 return `User "N/A"`
6794 }
6795 }
6796
6797 // getAuthUserLabel returns a label for the auth user for the client.
6798 func (c *client) getAuthUserLabel() string {
6799 switch {
6800 case c.opts.Nkey != _EMPTY_:
6801 return fmt.Sprintf("nkey:%s", c.opts.Nkey)
6802 case c.opts.Username != _EMPTY_:
6803 return fmt.Sprintf("user:%s", c.opts.Username)
6804 case c.opts.JWT != _EMPTY_:
6805 return fmt.Sprintf("jwt:%s", c.pubKey)
6806 case c.opts.Token != _EMPTY_:
6807 return "token"
6808 default:
6809 return ""
6810 }
6811 }
6812
6813 // Given an array of strings, this function converts it to a map as long
6814 // as all the content (converted to upper-case) matches some constants.
6815
6816 // Converts the given array of strings to a map of string.
6817 // The strings are converted to upper-case and added to the map only
6818 // if the server recognize them as valid connection types.
6819 // If there are unknown connection types, the map of valid ones is returned
6820 // along with an error that contains the name of the unknown.
6821 func convertAllowedConnectionTypes(cts []string) (map[string]struct{}, error) {
6822 var unknown []string
6823 m := make(map[string]struct{}, len(cts))
6824 for _, i := range cts {
6825 i = strings.ToUpper(i)
6826 switch i {
6827 case jwt.ConnectionTypeStandard, jwt.ConnectionTypeWebsocket,
6828 jwt.ConnectionTypeLeafnode, jwt.ConnectionTypeLeafnodeWS,
6829 jwt.ConnectionTypeMqtt, jwt.ConnectionTypeMqttWS,
6830 jwt.ConnectionTypeInProcess:
6831 m[i] = struct{}{}
6832 default:
6833 unknown = append(unknown, i)
6834 }
6835 }
6836 var err error
6837 // We will still return the map of valid ones.
6838 if len(unknown) != 0 {
6839 err = fmt.Errorf("invalid connection types %q", unknown)
6840 }
6841 return m, err
6842 }
6843
6844 // This will return true if the connection is of a type present in the given `acts` map.
6845 // Note that so far this is used only for CLIENT or LEAF connections.
6846 // But a CLIENT can be standard or websocket (and other types in the future).
6847 func (c *client) connectionTypeAllowed(acts map[string]struct{}) bool {
6848 // Empty means all type of clients are allowed
6849 if len(acts) == 0 {
6850 return true
6851 }
6852 var want string
6853 switch c.kind {
6854 case CLIENT:
6855 switch c.clientType() {
6856 case NATS:
6857 if c.iproc {
6858 want = jwt.ConnectionTypeInProcess
6859 } else {
6860 want = jwt.ConnectionTypeStandard
6861 }
6862 case WS:
6863 want = jwt.ConnectionTypeWebsocket
6864 case MQTT:
6865 if c.isWebsocket() {
6866 want = jwt.ConnectionTypeMqttWS
6867 } else {
6868 want = jwt.ConnectionTypeMqtt
6869 }
6870 }
6871 case LEAF:
6872 if c.isWebsocket() {
6873 want = jwt.ConnectionTypeLeafnodeWS
6874 } else {
6875 want = jwt.ConnectionTypeLeafnode
6876 }
6877 }
6878 _, ok := acts[want]
6879 return ok
6880 }
6881
6882 // isClosed returns true if either closeConnection or connMarkedClosed
6883 // flag have been set, or if `nc` is nil, which may happen in tests.
6884 func (c *client) isClosed() bool {
6885 return c.flags.isSet(closeConnection) || c.flags.isSet(connMarkedClosed) || c.nc == nil
6886 }
6887
6888 func (c *client) format(format string) string {
6889 if s := c.String(); s != _EMPTY_ {
6890 return fmt.Sprintf("%s - %s", s, format)
6891 } else {
6892 return format
6893 }
6894 }
6895
6896 func (c *client) formatNoClientInfo(format string) string {
6897 acc := c.ncsAcc.Load()
6898 if acc != nil {
6899 return fmt.Sprintf("%s - Account:%s", format, acc)
6900 } else {
6901 return format
6902 }
6903 }
6904
6905 func (c *client) formatClientSuffix() string {
6906 user := c.ncsUser.Load()
6907 if user == nil || user.(string) == _EMPTY_ {
6908 return _EMPTY_
6909 }
6910 return fmt.Sprintf(" - %s", user)
6911 }
6912
6913 // Logging functionality scoped to a client or route.
6914 func (c *client) Error(err error) {
6915 c.srv.Errorf(c.format(err.Error()))
6916 }
6917
6918 func (c *client) Errorf(format string, v ...any) {
6919 c.srv.Errorf(c.format(format), v...)
6920 }
6921
6922 func (c *client) Debugf(format string, v ...any) {
6923 c.srv.Debugf(c.format(format), v...)
6924 }
6925
6926 func (c *client) Noticef(format string, v ...any) {
6927 c.srv.Noticef(c.format(format), v...)
6928 }
6929
6930 func (c *client) Tracef(format string, v ...any) {
6931 c.srv.Tracef(c.format(format), v...)
6932 }
6933
6934 func (c *client) Warnf(format string, v ...any) {
6935 c.srv.Warnf(c.format(format), v...)
6936 }
6937
6938 func (c *client) RateLimitErrorf(format string, v ...any) {
6939 // Do the check before adding the client info to the format...
6940 statement := fmt.Sprintf(c.formatNoClientInfo(format), v...)
6941 if _, loaded := c.srv.rateLimitLogging.LoadOrStore(statement, time.Now()); loaded {
6942 return
6943 }
6944 if s := c.String(); s != _EMPTY_ {
6945 c.srv.Errorf("%s - %s%s", c, statement, c.formatClientSuffix())
6946 } else {
6947 c.srv.Errorf("%s%s", statement, c.formatClientSuffix())
6948 }
6949 }
6950
6951 func (c *client) rateLimitFormatWarnf(format string, v ...any) {
6952 // Do the check before adding the client info to the format...
6953 format = c.formatNoClientInfo(format)
6954 if _, loaded := c.srv.rateLimitLogging.LoadOrStore(format, time.Now()); loaded {
6955 return
6956 }
6957 statement := fmt.Sprintf(format, v...)
6958 if s := c.String(); s != _EMPTY_ {
6959 c.srv.Warnf("%s - %s%s", c, statement, c.formatClientSuffix())
6960 } else {
6961 c.srv.Warnf("%s%s", statement, c.formatClientSuffix())
6962 }
6963 }
6964
6965 func (c *client) RateLimitWarnf(format string, v ...any) {
6966 // Do the check before adding the client info to the format...
6967 statement := fmt.Sprintf(c.formatNoClientInfo(format), v...)
6968 if _, loaded := c.srv.rateLimitLogging.LoadOrStore(statement, time.Now()); loaded {
6969 return
6970 }
6971 if s := c.String(); s != _EMPTY_ {
6972 c.srv.Warnf("%s - %s%s", c, statement, c.formatClientSuffix())
6973 } else {
6974 c.srv.Warnf("%s%s", statement, c.formatClientSuffix())
6975 }
6976 }
6977
6978 func (c *client) RateLimitDebugf(format string, v ...any) {
6979 // Do the check before adding the client info to the format...
6980 statement := fmt.Sprintf(c.formatNoClientInfo(format), v...)
6981 if _, loaded := c.srv.rateLimitLogging.LoadOrStore(statement, time.Now()); loaded {
6982 return
6983 }
6984 if s := c.String(); s != _EMPTY_ {
6985 c.srv.Debugf("%s - %s%s", c, statement, c.formatClientSuffix())
6986 } else {
6987 c.srv.Debugf("%s%s", statement, c.formatClientSuffix())
6988 }
6989 }
6990
6991 // Set the very first PING to a lower interval to capture the initial RTT.
6992 // After that the PING interval will be set to the user defined value.
6993 // Client lock should be held.
6994 func (c *client) setFirstPingTimer() {
6995 s := c.srv
6996 if s == nil {
6997 return
6998 }
6999 opts := s.getOpts()
7000 d := opts.PingInterval
7001
7002 if c.kind == ROUTER && opts.Cluster.PingInterval > 0 {
7003 d = opts.Cluster.PingInterval
7004 }
7005 if c.isWebsocket() && opts.Websocket.PingInterval > 0 {
7006 d = opts.Websocket.PingInterval
7007 }
7008 if !opts.DisableShortFirstPing {
7009 if c.kind != CLIENT {
7010 if d > firstPingInterval {
7011 d = firstPingInterval
7012 }
7013 d = adjustPingInterval(c.kind, d)
7014 } else if d > firstClientPingInterval {
7015 d = firstClientPingInterval
7016 }
7017 }
7018 // We randomize the first one by an offset up to 20%, e.g. 2m ~= max 24s.
7019 addDelay := rand.Int63n(int64(d / 5))
7020 d += time.Duration(addDelay)
7021 // In the case of ROUTER/LEAF and when compression is configured, it is possible
7022 // that this timer was already set, but just to detect a stale connection
7023 // since we have to delay the first PING after compression negotiation
7024 // occurred.
7025 if c.ping.tmr != nil {
7026 c.ping.tmr.Stop()
7027 }
7028 c.ping.tmr = time.AfterFunc(d, c.processPingTimer)
7029 }
7030
7031 // Sets this error as the authentication error. To be used in authViolation()
7032 // to report an error different of `ErrAuthentication`.
7033 func (c *client) setAuthError(err error) {
7034 c.mu.Lock()
7035 c.authErr = err
7036 c.mu.Unlock()
7037 }
7038
7039 // Returns the authentication error set in the connection, possibly nil.
7040 func (c *client) getAuthError() error {
7041 c.mu.Lock()
7042 defer c.mu.Unlock()
7043 return c.authErr
7044 }