Debian Codegraph @

server/server.go

raw
1 // Copyright 2012-2025 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 "context"
19 "crypto/fips140"
20 "crypto/tls"
21 "encoding/json"
22 "errors"
23 "flag"
24 "fmt"
25 "io"
26 "log"
27 "math/rand"
28 "net"
29 "net/http"
30 "net/url"
31 "os"
32 "path"
33 "path/filepath"
34 "regexp"
35 "runtime"
36 "runtime/pprof"
37 "strconv"
38 "strings"
39 "sync"
40 "sync/atomic"
41 "time"
42
43 // Allow dynamic profiling.
44 _ "net/http/pprof"
45
46 "expvar"
47
48 "github.com/klauspost/compress/s2"
49 "github.com/nats-io/jwt/v2"
50 "github.com/nats-io/nats-server/v2/logger"
51 "github.com/nats-io/nkeys"
52 "github.com/nats-io/nuid"
53 )
54
55 const (
56 // Interval for the first PING for non client connections.
57 firstPingInterval = time.Second
58
59 // This is for the first ping for client connections.
60 firstClientPingInterval = 2 * time.Second
61 )
62
63 // These are protocol versions sent between server connections: ROUTER, LEAF and
64 // GATEWAY. We may have protocol versions that have a meaning only for a certain
65 // type of connections, but we don't have to have separate enums for that.
66 // However, it is CRITICAL to not change the order of those constants since they
67 // are exchanged between servers. When adding a new protocol version, add to the
68 // end of the list, don't try to group them by connection types.
69 const (
70 // RouteProtoZero is the original Route protocol from 2009.
71 // http://nats.io/documentation/internals/nats-protocol/
72 RouteProtoZero = iota
73 // RouteProtoInfo signals a route can receive more then the original INFO block.
74 // This can be used to update remote cluster permissions, etc...
75 RouteProtoInfo
76 // RouteProtoV2 is the new route/cluster protocol that provides account support.
77 RouteProtoV2
78 // MsgTraceProto indicates that this server understands distributed message tracing.
79 MsgTraceProto
80 )
81
82 // Will return the latest server-to-server protocol versions, unless the
83 // option to override it is set.
84 func (s *Server) getServerProto() int {
85 opts := s.getOpts()
86 // Initialize with the latest protocol version.
87 proto := MsgTraceProto
88 // For tests, we want to be able to make this server behave
89 // as an older server so check this option to see if we should override.
90 if opts.overrideProto < 0 {
91 // The option overrideProto is set to 0 by default (when creating an
92 // Options structure). Since this is the same value than the original
93 // proto RouteProtoZero, tests call setServerProtoForTest() with the
94 // desired protocol level, which sets it as negative value equal to:
95 // (wantedProto + 1) * -1. Here we compute back the real value.
96 proto = (opts.overrideProto * -1) - 1
97 }
98 return proto
99 }
100
101 // Used by tests.
102 func setServerProtoForTest(wantedProto int) int {
103 return (wantedProto + 1) * -1
104 }
105
106 // Info is the information sent to clients, routes, gateways, and leaf nodes,
107 // to help them understand information about this server.
108 type Info struct {
109 ID string `json:"server_id"`
110 Name string `json:"server_name"`
111 Version string `json:"version"`
112 Proto int `json:"proto"`
113 GitCommit string `json:"git_commit,omitempty"`
114 GoVersion string `json:"go"`
115 Host string `json:"host"`
116 Port int `json:"port"`
117 Headers bool `json:"headers"`
118 AuthRequired bool `json:"auth_required,omitempty"`
119 TLSRequired bool `json:"tls_required,omitempty"`
120 TLSVerify bool `json:"tls_verify,omitempty"`
121 TLSAvailable bool `json:"tls_available,omitempty"`
122 MaxPayload int32 `json:"max_payload"`
123 JetStream bool `json:"jetstream,omitempty"`
124 IP string `json:"ip,omitempty"`
125 CID uint64 `json:"client_id,omitempty"`
126 ClientIP string `json:"client_ip,omitempty"`
127 Nonce string `json:"nonce,omitempty"`
128 Cluster string `json:"cluster,omitempty"`
129 Dynamic bool `json:"cluster_dynamic,omitempty"`
130 Domain string `json:"domain,omitempty"`
131 ClientConnectURLs []string `json:"connect_urls,omitempty"` // Contains URLs a client can connect to.
132 WSConnectURLs []string `json:"ws_connect_urls,omitempty"` // Contains URLs a ws client can connect to.
133 LameDuckMode bool `json:"ldm,omitempty"`
134 Compression string `json:"compression,omitempty"`
135 ConnectInfo bool `json:"connect_info,omitempty"` // When true this is the server INFO response to CONNECT
136 RemoteAccount string `json:"remote_account,omitempty"` // Lets the client or leafnode side know the remote account that they bind to.
137 IsSystemAccount bool `json:"acc_is_sys,omitempty"` // Indicates if the account is a system account.
138 JSApiLevel int `json:"api_lvl,omitempty"`
139
140 // Route Specific
141 Import *SubjectPermission `json:"import,omitempty"`
142 Export *SubjectPermission `json:"export,omitempty"`
143 LNOC bool `json:"lnoc,omitempty"`
144 LNOCU bool `json:"lnocu,omitempty"`
145 InfoOnConnect bool `json:"info_on_connect,omitempty"` // When true the server will respond to CONNECT with an INFO
146 RoutePoolSize int `json:"route_pool_size,omitempty"`
147 RoutePoolIdx int `json:"route_pool_idx,omitempty"`
148 RouteAccount string `json:"route_account,omitempty"`
149 RouteAccReqID string `json:"route_acc_add_reqid,omitempty"`
150 GossipMode byte `json:"gossip_mode,omitempty"`
151
152 // Gateways Specific
153 Gateway string `json:"gateway,omitempty"` // Name of the origin Gateway (sent by gateway's INFO)
154 GatewayURLs []string `json:"gateway_urls,omitempty"` // Gateway URLs in the originating cluster (sent by gateway's INFO)
155 GatewayURL string `json:"gateway_url,omitempty"` // Gateway URL on that server (sent by route's INFO)
156 GatewayCmd byte `json:"gateway_cmd,omitempty"` // Command code for the receiving server to know what to do
157 GatewayCmdPayload []byte `json:"gateway_cmd_payload,omitempty"` // Command payload when needed
158 GatewayNRP bool `json:"gateway_nrp,omitempty"` // Uses new $GNR. prefix for mapped replies
159 GatewayIOM bool `json:"gateway_iom,omitempty"` // Indicate that all accounts will be switched to InterestOnly mode "right away"
160
161 // LeafNode Specific
162 LeafNodeURLs []string `json:"leafnode_urls,omitempty"` // LeafNode URLs that the server can reconnect to.
163
164 XKey string `json:"xkey,omitempty"` // Public server's x25519 key.
165 }
166
167 // Server is our main struct.
168 type Server struct {
169 // Fields accessed with atomic operations need to be 64-bit aligned
170 gcid uint64
171 // How often user logon fails due to the issuer account not being pinned.
172 pinnedAccFail uint64
173 stats
174 scStats
175 staleStats
176 mu sync.RWMutex
177 reloadMu sync.RWMutex // Write-locked when a config reload is taking place ONLY
178 kp nkeys.KeyPair
179 xkp nkeys.KeyPair
180 xpub string
181 info Info
182 configFile string
183 optsMu sync.RWMutex
184 opts *Options
185 running atomic.Bool
186 shutdown atomic.Bool
187 listener net.Listener
188 listenerErr error
189 gacc *Account
190 sys *internal
191 sysAcc atomic.Pointer[Account]
192 js atomic.Pointer[jetStream]
193 dios *diskIOSemaphore
194 isMetaLeader atomic.Bool
195 jsClustered atomic.Bool
196 accounts sync.Map
197 tmpAccounts sync.Map // Temporarily stores accounts that are being built
198 activeAccounts int32
199 accResolver AccountResolver
200 clients map[uint64]*client
201 routes map[string][]*client
202 remoteRoutePoolSize map[string]int // Map for remote's configure route pool size
203 routesPoolSize int // Configured pool size
204 routesReject bool // During reload, we may want to reject adding routes until some conditions are met
205 routesNoPool int // Number of routes that don't use pooling (connecting to older server for instance)
206 accRoutes map[string]map[string]*client // Key is account name, value is key=remoteID/value=route connection
207 accRouteByHash sync.Map // Key is account name, value is nil or a pool index
208 accAddedCh chan struct{}
209 accAddedReqID string
210 leafs map[uint64]*client
211 users map[string]*User
212 nkeys map[string]*NkeyUser
213 totalClients uint64
214 closed *closedRingBuffer
215 done chan bool
216 start time.Time
217 http net.Listener
218 httpHandler http.Handler
219 httpBasePath string
220 profiler net.Listener
221 httpReqStats map[string]uint64
222 routeListener net.Listener
223 routeListenerErr error
224 routeInfo Info
225 routeResolver netResolver
226 routesToSelf map[string]struct{}
227 routeTLSName string
228 leafNodeListener net.Listener
229 leafNodeListenerErr error
230 leafNodeInfo Info
231 leafNodeInfoJSON []byte
232 leafURLsMap refCountedUrlSet
233 leafNodeOpts struct {
234 resolver netResolver
235 dialTimeout time.Duration
236 dialer leafNodeDialer
237 }
238 leafRemoteCfgs map[*leafNodeCfg]struct{}
239 rmLeafRemoteCfgs map[string]*leafNodeCfg
240 leafRemoteAccounts sync.Map
241 leafNodeEnabled bool
242 leafDisableConnect bool // Used in test only
243 leafNoCluster bool // Indicate that this server has only remotes and no cluster defined
244
245 quitCh chan struct{}
246 startupComplete chan struct{}
247 shutdownComplete chan struct{}
248
249 // Tracking Go routines
250 grMu sync.Mutex
251 grTmpClients map[uint64]*client
252 grRunning bool
253 grWG sync.WaitGroup // to wait on various go routines
254
255 cproto int64 // number of clients supporting async INFO
256 configTime time.Time // last time config was loaded
257
258 logging struct {
259 sync.RWMutex
260 logger Logger
261 trace int32
262 debug int32
263 traceSysAcc int32
264 }
265
266 clientConnectURLs []string
267
268 // Used internally for quick look-ups.
269 clientConnectURLsMap refCountedUrlSet
270
271 // For Gateways
272 gatewayListener net.Listener // Accept listener
273 gatewayListenerErr error
274 gateway *srvGateway
275
276 // Used by tests to check that http.Servers do
277 // not set any timeout.
278 monitoringServer *http.Server
279 profilingServer *http.Server
280
281 // LameDuck mode
282 ldm bool
283 ldmCh chan bool
284
285 // Trusted public operator keys.
286 trustedKeys []string
287 // map of trusted keys to operator setting StrictSigningKeyUsage
288 strictSigningKeyUsage map[string]struct{}
289
290 // We use this to minimize mem copies for requests to monitoring
291 // endpoint /varz (when it comes from http).
292 varzMu sync.Mutex
293 varz *Varz
294 // This is set during a config reload if we detect that we have
295 // added/removed routes. The monitoring code then check that
296 // to know if it should update the cluster's URLs array.
297 varzUpdateRouteURLs bool
298
299 // Keeps a sublist of subscriptions attached to leafnode connections
300 // for the $GNR.*.*.*.> subject so that a server can send back a mapped
301 // gateway reply.
302 gwLeafSubs *Sublist
303
304 // Used for expiration of mapped GW replies
305 gwrm struct {
306 w int32
307 ch chan time.Duration
308 m sync.Map
309 }
310
311 // For eventIDs
312 eventIds *nuid.NUID
313
314 // Websocket structure
315 websocket srvWebsocket
316
317 // MQTT structure
318 mqtt srvMQTT
319
320 // OCSP monitoring
321 ocsps []*OCSPMonitor
322
323 // OCSP peer verification (at least one TLS block)
324 ocspPeerVerify bool
325
326 // OCSP response cache
327 ocsprc OCSPResponseCache
328
329 // exporting account name the importer experienced issues with
330 incompleteAccExporterMap sync.Map
331
332 // Holds cluster name under different lock for mapping
333 cnMu sync.RWMutex
334 cn string
335
336 // For registering raft nodes with the server.
337 rnMu sync.RWMutex
338 raftNodes map[string]RaftNode
339
340 // For mapping from a raft node name back to a server name and cluster. Node has to be in the same domain.
341 nodeToInfo sync.Map
342
343 // For out of resources to not log errors too fast.
344 rerrMu sync.Mutex
345 rerrLast time.Time
346
347 connRateCounter *rateCounter
348
349 // If there is a system account configured, to still support the $G account,
350 // the server will create a fake user and add it to the list of users.
351 // Keep track of what that user name is for config reload purposes.
352 sysAccOnlyNoAuthUser string
353
354 // IPQueues map
355 ipQueues sync.Map
356
357 // To limit logging frequency
358 rateLimitLogging sync.Map
359 rateLimitLoggingCh chan time.Duration
360
361 // Total outstanding catchup bytes in flight.
362 gcbMu sync.RWMutex
363 gcbOut int64
364 gcbOutMax int64 // Taken from JetStreamMaxCatchup or defaultMaxTotalCatchupOutBytes
365 // A global chanel to kick out stalled catchup sequences.
366 gcbKick chan struct{}
367
368 // Total outbound syncRequests
369 syncOutSem chan struct{}
370
371 // Queue to process JS API requests that come from routes (or gateways)
372 jsAPIRoutedReqs *ipQueue[*jsAPIRoutedReq]
373 jsAPIRoutedInfoReqs *ipQueue[*jsAPIRoutedReq]
374
375 // Delayed API responses.
376 delayedAPIResponses *ipQueue[*delayedAPIResponse]
377
378 // Whether moving NRG traffic into accounts is permitted on this server.
379 // Controls whether or not the account NRG capability is set in statsz.
380 // Currently used by unit tests to simulate nodes not supporting account NRG.
381 accountNRGAllowed atomic.Bool
382
383 // List of proxies trusted keys in `KeyPair` form so we can do signature
384 // verification when processing incoming proxy connections.
385 proxiesKeyPairs []nkeys.KeyPair
386 proxiedConns map[string]map[uint64]*client
387 }
388
389 // For tracking JS nodes.
390 type nodeInfo struct {
391 name string
392 version string
393 cluster string
394 domain string
395 id string
396 tags jwt.TagList
397 cfg *JetStreamConfig
398 stats *JetStreamStats
399 offline bool
400 js bool
401 binarySnapshots bool
402 accountNRG bool
403 }
404
405 type stats struct {
406 inMsgs int64
407 inBytes int64
408 inClientMsgs int64
409 inClientBytes int64
410 outMsgs int64
411 outBytes int64
412 outClientMsgs int64
413 outClientBytes int64
414 slowConsumers int64
415 staleConnections int64
416 stalls int64
417 }
418
419 // scStats includes the total and per connection counters of Slow Consumers.
420 type scStats struct {
421 clients atomic.Uint64
422 routes atomic.Uint64
423 leafs atomic.Uint64
424 gateways atomic.Uint64
425 }
426
427 // staleStats includes the total and per connection counters of Stale Connections.
428 type staleStats struct {
429 clients atomic.Uint64
430 routes atomic.Uint64
431 leafs atomic.Uint64
432 gateways atomic.Uint64
433 }
434
435 // This is used by tests so we can run all server tests with a default route
436 // or leafnode compression mode. For instance:
437 // go test -race -v ./server -cluster_compression=fast
438 var (
439 testDefaultClusterCompression string
440 testDefaultLeafNodeCompression string
441 )
442
443 // Compression modes.
444 const (
445 CompressionNotSupported = "not supported"
446 CompressionOff = "off"
447 CompressionAccept = "accept"
448 CompressionS2Auto = "s2_auto"
449 CompressionS2Uncompressed = "s2_uncompressed"
450 CompressionS2Fast = "s2_fast"
451 CompressionS2Better = "s2_better"
452 CompressionS2Best = "s2_best"
453 )
454
455 // defaultCompressionS2AutoRTTThresholds is the default of RTT thresholds for
456 // the CompressionS2Auto mode.
457 var defaultCompressionS2AutoRTTThresholds = []time.Duration{
458 // [0..10ms] -> CompressionS2Uncompressed
459 10 * time.Millisecond,
460 // ]10ms..50ms] -> CompressionS2Fast
461 50 * time.Millisecond,
462 // ]50ms..100ms] -> CompressionS2Better
463 100 * time.Millisecond,
464 // ]100ms..] -> CompressionS2Best
465 }
466
467 // For a given user provided string, matches to one of the compression mode
468 // constant and updates the provided string to that constant. Returns an
469 // error if the provided compression mode is not known.
470 // The parameter `chosenModeForOn` indicates which compression mode to use
471 // when the user selects "on" (or enabled, true, etc..). This is because
472 // we may have different defaults depending on where the compression is used.
473 func validateAndNormalizeCompressionOption(c *CompressionOpts, chosenModeForOn string) error {
474 if c == nil {
475 return nil
476 }
477 cmtl := strings.ToLower(c.Mode)
478 // First, check for the "on" case so that we set to the default compression
479 // mode for that. The other switch/case will finish setup if needed (for
480 // instance if the default mode is s2Auto).
481 switch cmtl {
482 case "on", "enabled", "true":
483 cmtl = chosenModeForOn
484 default:
485 }
486 // Check (again) with the proper mode.
487 switch cmtl {
488 case "not supported", "not_supported":
489 c.Mode = CompressionNotSupported
490 case "disabled", "off", "false":
491 c.Mode = CompressionOff
492 case "accept":
493 c.Mode = CompressionAccept
494 case "auto", "s2_auto":
495 var rtts []time.Duration
496 if len(c.RTTThresholds) == 0 {
497 rtts = defaultCompressionS2AutoRTTThresholds
498 } else {
499 for _, n := range c.RTTThresholds {
500 // Do not error on negative, but simply set to 0
501 if n < 0 {
502 n = 0
503 }
504 // Make sure they are properly ordered. However, it is possible
505 // to have a "0" anywhere in the list to indicate that this
506 // compression level should not be used.
507 if l := len(rtts); l > 0 && n != 0 {
508 for _, v := range rtts {
509 if n < v {
510 return fmt.Errorf("RTT threshold values %v should be in ascending order", c.RTTThresholds)
511 }
512 }
513 }
514 rtts = append(rtts, n)
515 }
516 if len(rtts) > 0 {
517 // Trim 0 that are at the end.
518 stop := -1
519 for i := len(rtts) - 1; i >= 0; i-- {
520 if rtts[i] != 0 {
521 stop = i
522 break
523 }
524 }
525 rtts = rtts[:stop+1]
526 }
527 if len(rtts) > 4 {
528 // There should be at most values for "uncompressed", "fast",
529 // "better" and "best" (when some 0 are present).
530 return fmt.Errorf("compression mode %q should have no more than 4 RTT thresholds: %v", c.Mode, c.RTTThresholds)
531 } else if len(rtts) == 0 {
532 // But there should be at least 1 if the user provided the slice.
533 // We would be here only if it was provided by say with values
534 // being a single or all zeros.
535 return fmt.Errorf("compression mode %q requires at least one RTT threshold", c.Mode)
536 }
537 }
538 c.Mode = CompressionS2Auto
539 c.RTTThresholds = rtts
540 case "fast", "s2_fast":
541 c.Mode = CompressionS2Fast
542 case "better", "s2_better":
543 c.Mode = CompressionS2Better
544 case "best", "s2_best":
545 c.Mode = CompressionS2Best
546 default:
547 return fmt.Errorf("unsupported compression mode %q", c.Mode)
548 }
549 return nil
550 }
551
552 // Returns `true` if the compression mode `m` indicates that the server
553 // will negotiate compression with the remote server, `false` otherwise.
554 // Note that the provided compression mode is assumed to have been
555 // normalized and validated.
556 func needsCompression(m string) bool {
557 return m != _EMPTY_ && m != CompressionOff && m != CompressionNotSupported
558 }
559
560 // Compression is asymmetric, meaning that one side can have a different
561 // compression level than the other. However, we need to check for cases
562 // when this server `scm` or the remote `rcm` do not support compression
563 // (say older server, or test to make it behave as it is not), or have
564 // the compression off.
565 // Note that `scm` is assumed to not be "off" or "not supported".
566 func selectCompressionMode(scm, rcm string) (mode string, err error) {
567 if rcm == CompressionNotSupported || rcm == _EMPTY_ {
568 return CompressionNotSupported, nil
569 }
570 switch rcm {
571 case CompressionOff:
572 // If the remote explicitly disables compression, then we won't
573 // use compression.
574 return CompressionOff, nil
575 case CompressionAccept:
576 // If the remote is ok with compression (but is not initiating it),
577 // and if we too are in this mode, then it means no compression.
578 if scm == CompressionAccept {
579 return CompressionOff, nil
580 }
581 // Otherwise use our compression mode.
582 return scm, nil
583 case CompressionS2Auto, CompressionS2Uncompressed, CompressionS2Fast, CompressionS2Better, CompressionS2Best:
584 // This case is here to make sure that if we don't recognize a
585 // compression setting, we error out.
586 if scm == CompressionAccept {
587 // If our compression mode is "accept", then we will use the remote
588 // compression mode, except if it is "auto", in which case we will
589 // default to "fast". This is not a configuration (auto in one
590 // side and accept in the other) that would be recommended.
591 if rcm == CompressionS2Auto {
592 return CompressionS2Fast, nil
593 }
594 // Use their compression mode.
595 return rcm, nil
596 }
597 // Otherwise use our compression mode.
598 return scm, nil
599 default:
600 return _EMPTY_, fmt.Errorf("unsupported route compression mode %q", rcm)
601 }
602 }
603
604 // If the configured compression mode is "auto" then will return that,
605 // otherwise will return the given `cm` compression mode.
606 func compressionModeForInfoProtocol(co *CompressionOpts, cm string) string {
607 if co.Mode == CompressionS2Auto {
608 return CompressionS2Auto
609 }
610 return cm
611 }
612
613 // Given a connection RTT and a list of thresholds durations, this
614 // function will return an S2 compression level such as "uncompressed",
615 // "fast", "better" or "best". For instance, with the following slice:
616 // [5ms, 10ms, 15ms, 20ms], a RTT of up to 5ms will result
617 // in the compression level "uncompressed", ]5ms..10ms] will result in
618 // "fast" compression, etc..
619 // However, the 0 value allows for disabling of some compression levels.
620 // For instance, the following slice: [0, 0, 20, 30] means that a RTT of
621 // [0..20ms] would result in the "better" compression - effectively disabling
622 // the use of "uncompressed" and "fast", then anything above 20ms would
623 // result in the use of "best" level (the 30 in the list has no effect
624 // and the list could have been simplified to [0, 0, 20]).
625 func selectS2AutoModeBasedOnRTT(rtt time.Duration, rttThresholds []time.Duration) string {
626 var idx int
627 var found bool
628 for i, d := range rttThresholds {
629 if rtt <= d {
630 idx = i
631 found = true
632 break
633 }
634 }
635 if !found {
636 // If we did not find but we have all levels, then use "best",
637 // otherwise use the last one in array.
638 if l := len(rttThresholds); l >= 3 {
639 idx = 3
640 } else {
641 idx = l - 1
642 }
643 }
644 switch idx {
645 case 0:
646 return CompressionS2Uncompressed
647 case 1:
648 return CompressionS2Fast
649 case 2:
650 return CompressionS2Better
651 }
652 return CompressionS2Best
653 }
654
655 // Returns an array of s2 WriterOption based on the route compression mode.
656 // So far we return a single option, but this way we can call s2.NewWriter()
657 // with a nil []s2.WriterOption, but not with a nil s2.WriterOption, so
658 // this is more versatile.
659 func s2WriterOptions(cm string) []s2.WriterOption {
660 _opts := [2]s2.WriterOption{}
661 opts := append(
662 _opts[:0],
663 s2.WriterConcurrency(1), // Stop asynchronous flushing in separate goroutines
664 )
665 switch cm {
666 case CompressionS2Uncompressed:
667 return append(opts, s2.WriterUncompressed())
668 case CompressionS2Fast:
669 return opts
670 case CompressionS2Best:
671 return append(opts, s2.WriterBestCompression())
672 case CompressionS2Better:
673 return append(opts, s2.WriterBetterCompression())
674 default:
675 return nil
676 }
677 }
678
679 // New will setup a new server struct after parsing the options.
680 // DEPRECATED: Use NewServer(opts)
681 func New(opts *Options) *Server {
682 s, _ := NewServer(opts)
683 return s
684 }
685
686 func NewServerFromConfig(opts *Options) (*Server, error) {
687 if opts.ConfigFile != _EMPTY_ && opts.configDigest == "" {
688 if err := opts.ProcessConfigFile(opts.ConfigFile); err != nil {
689 return nil, err
690 }
691 }
692 return NewServer(opts)
693 }
694
695 // NewServer will setup a new server struct after parsing the options.
696 // Could return an error if options can not be validated.
697 // The provided Options type should not be re-used afterwards.
698 // Either use Options.Clone() to pass a copy, or make a new one.
699 func NewServer(opts *Options) (*Server, error) {
700 setBaselineOptions(opts)
701
702 // Process TLS options, including whether we require client certificates.
703 tlsReq := opts.TLSConfig != nil
704 verify := (tlsReq && opts.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert)
705
706 // Create our server's nkey identity.
707 kp, _ := nkeys.CreateServer()
708 pub, _ := kp.PublicKey()
709
710 // Create an xkey for encrypting messages from this server.
711 var xkp nkeys.KeyPair
712 var xpub string
713 if !fips140.Enabled() {
714 xkp, _ = nkeys.CreateCurveKeys()
715 xpub, _ = xkp.PublicKey()
716 }
717
718 serverName := pub
719 if opts.ServerName != _EMPTY_ {
720 serverName = opts.ServerName
721 }
722
723 httpBasePath := normalizeBasePath(opts.HTTPBasePath)
724
725 // Validate some options. This is here because we cannot assume that
726 // server will always be started with configuration parsing (that could
727 // report issues). Its options can be (incorrectly) set by hand when
728 // server is embedded. If there is an error, return nil.
729 if err := validateOptions(opts); err != nil {
730 return nil, err
731 }
732
733 info := Info{
734 ID: pub,
735 XKey: xpub,
736 Version: VERSION,
737 Proto: PROTO,
738 GitCommit: gitCommit,
739 GoVersion: runtime.Version(),
740 Name: serverName,
741 Host: opts.Host,
742 Port: opts.Port,
743 AuthRequired: false,
744 TLSRequired: tlsReq && !opts.AllowNonTLS,
745 TLSVerify: verify,
746 MaxPayload: opts.MaxPayload,
747 JetStream: opts.JetStream,
748 Headers: !opts.NoHeaderSupport,
749 Cluster: opts.Cluster.Name,
750 Domain: opts.JetStreamDomain,
751 JSApiLevel: JSApiLevel,
752 }
753
754 if tlsReq && !info.TLSRequired {
755 info.TLSAvailable = true
756 }
757
758 now := time.Now()
759
760 s := &Server{
761 kp: kp,
762 xkp: xkp,
763 xpub: xpub,
764 configFile: opts.ConfigFile,
765 info: info,
766 opts: opts,
767 done: make(chan bool, 1),
768 start: now,
769 configTime: now,
770 gwLeafSubs: NewSublistWithCache(),
771 httpBasePath: httpBasePath,
772 eventIds: nuid.New(),
773 routesToSelf: make(map[string]struct{}),
774 httpReqStats: make(map[string]uint64), // Used to track HTTP requests
775 rateLimitLoggingCh: make(chan time.Duration, 1),
776 leafNodeEnabled: opts.LeafNode.Port != 0 || len(opts.LeafNode.Remotes) > 0,
777 syncOutSem: make(chan struct{}, maxConcurrentSyncRequests),
778 dios: newDiskIOSemaphore(opts.JetStreamConcurrentIOs),
779 }
780
781 // Delayed API response queue. Create regardless if JetStream is configured
782 // or not (since it can be enabled/disabled with config reload, we want this
783 // queue to exist at all times).
784 s.delayedAPIResponses = newIPQueue[*delayedAPIResponse](s, "delayed API responses")
785
786 // By default we'll allow account NRG.
787 s.accountNRGAllowed.Store(true)
788
789 // Fill up the maximum in flight syncRequests for this server.
790 // Used in JetStream catchup semantics.
791 for i := 0; i < maxConcurrentSyncRequests; i++ {
792 s.syncOutSem <- struct{}{}
793 }
794
795 if opts.TLSRateLimit > 0 {
796 s.connRateCounter = newRateCounter(opts.tlsConfigOpts.RateLimit)
797 }
798
799 // Trusted root operator keys.
800 if !s.processTrustedKeys() {
801 return nil, fmt.Errorf("Error processing trusted operator keys")
802 }
803
804 // If we have solicited leafnodes but no clustering and no clustername.
805 // However we may need a stable clustername so use the server name.
806 if len(opts.LeafNode.Remotes) > 0 && opts.Cluster.Port == 0 && opts.Cluster.Name == _EMPTY_ {
807 s.leafNoCluster = true
808 opts.Cluster.Name = opts.ServerName
809 }
810
811 if opts.Cluster.Name != _EMPTY_ {
812 // Also place into mapping cn with cnMu lock.
813 s.cnMu.Lock()
814 s.cn = opts.Cluster.Name
815 s.cnMu.Unlock()
816 }
817
818 s.mu.Lock()
819 defer s.mu.Unlock()
820
821 // If there are proxies trusted public keys in the configuration
822 // this will fill create the corresponding list of nkeys.KeyPair
823 // that we can use for signature verification.
824 s.processProxiesTrustedKeys()
825
826 // Place ourselves in the JetStream nodeInfo if needed.
827 if opts.JetStream {
828 ourNode := getHash(serverName)
829 s.nodeToInfo.Store(ourNode, nodeInfo{
830 name: serverName,
831 version: VERSION,
832 cluster: opts.Cluster.Name,
833 domain: opts.JetStreamDomain,
834 id: info.ID,
835 tags: opts.Tags,
836 cfg: &JetStreamConfig{MaxMemory: opts.JetStreamMaxMemory, MaxStore: opts.JetStreamMaxStore, CompressOK: true},
837 stats: nil,
838 offline: false,
839 js: true,
840 binarySnapshots: true,
841 accountNRG: true,
842 })
843 }
844
845 s.routeResolver = opts.Cluster.resolver
846 if s.routeResolver == nil {
847 s.routeResolver = net.DefaultResolver
848 }
849
850 // Used internally for quick look-ups.
851 s.clientConnectURLsMap = make(refCountedUrlSet)
852 s.websocket.connectURLsMap = make(refCountedUrlSet)
853 s.leafURLsMap = make(refCountedUrlSet)
854
855 // Ensure that non-exported options (used in tests) are properly set.
856 s.setLeafNodeNonExportedOptions()
857
858 // Setup OCSP Stapling and OCSP Peer. This will abort server from starting if there
859 // are no valid staples and OCSP Stapling policy is set to Always or MustStaple.
860 if err := s.enableOCSP(); err != nil {
861 return nil, err
862 }
863
864 // Call this even if there is no gateway defined. It will
865 // initialize the structure so we don't have to check for
866 // it to be nil or not in various places in the code.
867 if err := s.newGateway(opts); err != nil {
868 return nil, err
869 }
870
871 // If we have a cluster definition but do not have a cluster name, create one.
872 if opts.Cluster.Port != 0 && opts.Cluster.Name == _EMPTY_ {
873 s.info.Cluster = nuid.Next()
874 } else if opts.Cluster.Name != _EMPTY_ {
875 // Likewise here if we have a cluster name set.
876 s.info.Cluster = opts.Cluster.Name
877 }
878
879 // This is normally done in the AcceptLoop, once the
880 // listener has been created (possibly with random port),
881 // but since some tests may expect the INFO to be properly
882 // set after New(), let's do it now.
883 s.setInfoHostPort()
884
885 // For tracking clients
886 s.clients = make(map[uint64]*client)
887
888 // For tracking closed clients.
889 s.closed = newClosedRingBuffer(opts.MaxClosedClients)
890
891 // For tracking connections that are not yet registered
892 // in s.routes, but for which readLoop has started.
893 s.grTmpClients = make(map[uint64]*client)
894
895 // For tracking routes and their remote ids
896 s.initRouteStructures(opts)
897
898 // For tracking leaf nodes.
899 s.leafs = make(map[uint64]*client)
900
901 // Used to kick out all go routines possibly waiting on server
902 // to shutdown.
903 s.quitCh = make(chan struct{})
904
905 // Closed when startup is complete. ReadyForConnections() will block on
906 // this before checking the presence of listening sockets.
907 s.startupComplete = make(chan struct{})
908
909 // Closed when Shutdown() is complete. Allows WaitForShutdown() to block
910 // waiting for complete shutdown.
911 s.shutdownComplete = make(chan struct{})
912
913 // Check for configured account resolvers.
914 if err := s.configureResolver(); err != nil {
915 return nil, err
916 }
917 // If there is an URL account resolver, do basic test to see if anyone is home.
918 if ar := opts.AccountResolver; ar != nil {
919 if ur, ok := ar.(*URLAccResolver); ok {
920 if _, err := ur.Fetch(_EMPTY_); err != nil {
921 return nil, err
922 }
923 }
924 }
925 // For other resolver:
926 // In operator mode, when the account resolver depends on an external system and
927 // the system account can't be fetched, inject a temporary one.
928 if ar := s.accResolver; len(opts.TrustedOperators) == 1 && ar != nil &&
929 opts.SystemAccount != _EMPTY_ && opts.SystemAccount != DEFAULT_SYSTEM_ACCOUNT {
930 if _, ok := ar.(*MemAccResolver); !ok {
931 s.mu.Unlock()
932 var a *Account
933 // perform direct lookup to avoid warning trace
934 if _, err := fetchAccount(ar, opts.SystemAccount); err == nil {
935 a, _ = s.lookupAccount(opts.SystemAccount)
936 }
937 s.mu.Lock()
938 if a == nil {
939 sac := NewAccount(opts.SystemAccount)
940 sac.Issuer = opts.TrustedOperators[0].Issuer
941 sac.signingKeys = map[string]jwt.Scope{}
942 sac.signingKeys[opts.SystemAccount] = nil
943 s.registerAccountNoLock(sac)
944 }
945 }
946 }
947
948 // For tracking accounts
949 if _, err := s.configureAccounts(false); err != nil {
950 return nil, err
951 }
952
953 // Used to setup Authorization.
954 s.configureAuthorization()
955
956 // Start signal handler
957 s.handleSignals()
958
959 return s, nil
960 }
961
962 // Initializes route structures based on pooling and/or per-account routes.
963 //
964 // Server lock is held on entry
965 func (s *Server) initRouteStructures(opts *Options) {
966 s.routes = make(map[string][]*client)
967 if ps := opts.Cluster.PoolSize; ps > 0 {
968 s.routesPoolSize = ps
969 } else {
970 s.routesPoolSize = 1
971 }
972 // If we have per-account routes, we create accRoutes and initialize it
973 // with nil values. The presence of an account as the key will allow us
974 // to know if a given account is supposed to have dedicated routes.
975 if l := len(opts.Cluster.PinnedAccounts); l > 0 {
976 s.accRoutes = make(map[string]map[string]*client, l)
977 for _, acc := range opts.Cluster.PinnedAccounts {
978 s.accRoutes[acc] = make(map[string]*client)
979 }
980 }
981 }
982
983 func (s *Server) logRejectedTLSConns() {
984 defer s.grWG.Done()
985 t := time.NewTicker(time.Second)
986 defer t.Stop()
987 for {
988 select {
989 case <-s.quitCh:
990 return
991 case <-t.C:
992 blocked := s.connRateCounter.countBlocked()
993 if blocked > 0 {
994 s.Warnf("Rejected %d connections due to TLS rate limiting", blocked)
995 }
996 }
997 }
998 }
999
1000 // clusterName returns our cluster name which could be dynamic.
1001 func (s *Server) ClusterName() string {
1002 s.mu.RLock()
1003 cn := s.info.Cluster
1004 s.mu.RUnlock()
1005 return cn
1006 }
1007
1008 // Grabs cluster name with cluster name specific lock.
1009 func (s *Server) cachedClusterName() string {
1010 s.cnMu.RLock()
1011 cn := s.cn
1012 s.cnMu.RUnlock()
1013 return cn
1014 }
1015
1016 // setClusterName will update the cluster name for this server.
1017 func (s *Server) setClusterName(name string) {
1018 s.mu.Lock()
1019 var resetCh chan struct{}
1020 if s.sys != nil && s.info.Cluster != name {
1021 // can't hold the lock as go routine reading it may be waiting for lock as well
1022 resetCh = s.sys.resetCh
1023 }
1024 s.info.Cluster = name
1025 s.routeInfo.Cluster = name
1026
1027 // Need to close solicited leaf nodes. The close has to be done outside of the server lock.
1028 var leafs []*client
1029 for _, c := range s.leafs {
1030 c.mu.Lock()
1031 if c.leaf != nil && c.leaf.remote != nil {
1032 leafs = append(leafs, c)
1033 }
1034 c.mu.Unlock()
1035 }
1036 s.mu.Unlock()
1037
1038 // Also place into mapping cn with cnMu lock.
1039 s.cnMu.Lock()
1040 s.cn = name
1041 s.cnMu.Unlock()
1042
1043 for _, l := range leafs {
1044 l.closeConnection(ClusterNameConflict)
1045 }
1046 if resetCh != nil {
1047 select {
1048 case resetCh <- struct{}{}:
1049 case <-s.quitCh:
1050 }
1051 }
1052 s.Noticef("Cluster name updated to %s", name)
1053 }
1054
1055 // Return whether the cluster name is dynamic.
1056 func (s *Server) isClusterNameDynamic() bool {
1057 // We need to lock the whole "Cluster.Name" check and not use s.getOpts()
1058 // because otherwise this could cause a data race with setting the name in
1059 // route.go's processRouteConnect().
1060 s.optsMu.RLock()
1061 dynamic := s.opts.Cluster.Name == _EMPTY_
1062 s.optsMu.RUnlock()
1063 return dynamic
1064 }
1065
1066 // Returns our configured serverName.
1067 func (s *Server) serverName() string {
1068 return s.getOpts().ServerName
1069 }
1070
1071 // ClientURL returns the URL used to connect clients.
1072 // Helpful in tests and with in-process servers using a random client port (-1).
1073 func (s *Server) ClientURL() string {
1074 // FIXME(dlc) - should we add in user and pass if defined single?
1075 opts := s.getOpts()
1076 var u url.URL
1077 u.Scheme = "nats"
1078 if opts.TLSConfig != nil {
1079 u.Scheme = "tls"
1080 }
1081 u.Host = net.JoinHostPort(opts.Host, fmt.Sprintf("%d", opts.Port))
1082 return u.String()
1083 }
1084
1085 // WebsocketURL returns the URL used to connect websocket clients.
1086 // Helpful in tests and with in-process servers using a random websocket port (-1).
1087 func (s *Server) WebsocketURL() string {
1088 opts := s.getOpts()
1089 var u url.URL
1090 u.Scheme = "ws"
1091 if opts.Websocket.TLSConfig != nil {
1092 u.Scheme = "wss"
1093 }
1094 u.Host = net.JoinHostPort(opts.Websocket.Host, fmt.Sprintf("%d", opts.Websocket.Port))
1095 return u.String()
1096 }
1097
1098 func validateCluster(o *Options) error {
1099 if o.Cluster.Name != _EMPTY_ && strings.Contains(o.Cluster.Name, " ") {
1100 return ErrClusterNameHasSpaces
1101 }
1102 if p := o.Cluster.Permissions; p != nil {
1103 perms := &Permissions{Publish: p.Import, Subscribe: p.Export}
1104 if err := checkClusterPermissionSubjects(perms); err != nil {
1105 return err
1106 }
1107 }
1108 if o.Cluster.Compression.Mode != _EMPTY_ {
1109 if err := validateAndNormalizeCompressionOption(&o.Cluster.Compression, CompressionS2Fast); err != nil {
1110 return err
1111 }
1112 }
1113 if err := validatePinnedCerts(o.Cluster.TLSPinnedCerts); err != nil {
1114 return fmt.Errorf("cluster: %v", err)
1115 }
1116 // Check that cluster name if defined matches any gateway name.
1117 // Note that we have already verified that the gateway name does not have spaces.
1118 if o.Gateway.Name != _EMPTY_ && o.Gateway.Name != o.Cluster.Name {
1119 if o.Cluster.Name != _EMPTY_ {
1120 return ErrClusterNameConfigConflict
1121 }
1122 // Set this here so we do not consider it dynamic.
1123 o.Cluster.Name = o.Gateway.Name
1124 }
1125 if l := len(o.Cluster.PinnedAccounts); l > 0 {
1126 if o.Cluster.PoolSize < 0 {
1127 return fmt.Errorf("pool_size cannot be negative if pinned accounts are specified")
1128 }
1129 m := make(map[string]struct{}, l)
1130 for _, a := range o.Cluster.PinnedAccounts {
1131 if _, exists := m[a]; exists {
1132 return fmt.Errorf("found duplicate account name %q in pinned accounts list %q", a, o.Cluster.PinnedAccounts)
1133 }
1134 m[a] = struct{}{}
1135 }
1136 }
1137 return nil
1138 }
1139
1140 func validatePinnedCerts(pinned PinnedCertSet) error {
1141 re := regexp.MustCompile("^[a-f0-9]{64}$")
1142 for certId := range pinned {
1143 entry := strings.ToLower(certId)
1144 if !re.MatchString(entry) {
1145 return fmt.Errorf("error parsing 'pinned_certs' key %s does not look like lower case hex-encoded sha256 of DER encoded SubjectPublicKeyInfo", entry)
1146 }
1147 }
1148 return nil
1149 }
1150
1151 func validateOptions(o *Options) error {
1152 if o.LameDuckDuration > 0 && o.LameDuckGracePeriod >= o.LameDuckDuration {
1153 return fmt.Errorf("lame duck grace period (%v) should be strictly lower than lame duck duration (%v)",
1154 o.LameDuckGracePeriod, o.LameDuckDuration)
1155 }
1156 if int64(o.MaxPayload) > o.MaxPending {
1157 return fmt.Errorf("max_payload (%v) cannot be higher than max_pending (%v)",
1158 o.MaxPayload, o.MaxPending)
1159 }
1160 if o.ServerName != _EMPTY_ && strings.Contains(o.ServerName, " ") {
1161 return errors.New("server name cannot contain spaces")
1162 }
1163 // Check that the trust configuration is correct.
1164 if err := validateTrustedOperators(o); err != nil {
1165 return err
1166 }
1167 // Check on leaf nodes which will require a system
1168 // account when gateways are also configured.
1169 if err := validateLeafNode(o); err != nil {
1170 return err
1171 }
1172 // Check that authentication is properly configured.
1173 if err := validateAuth(o); err != nil {
1174 return err
1175 }
1176 // Check that proxies is properly configured.
1177 if err := validateProxies(o); err != nil {
1178 return err
1179 }
1180 // Check that gateway is properly configured. Returns no error
1181 // if there is no gateway defined.
1182 if err := validateGatewayOptions(o); err != nil {
1183 return err
1184 }
1185 // Check that cluster name if defined matches any gateway name.
1186 if err := validateCluster(o); err != nil {
1187 return err
1188 }
1189 if err := validateMQTTOptions(o); err != nil {
1190 return err
1191 }
1192 if err := validateJetStreamOptions(o); err != nil {
1193 return err
1194 }
1195 // Finally check websocket options.
1196 return validateWebsocketOptions(o)
1197 }
1198
1199 func (s *Server) getOpts() *Options {
1200 s.optsMu.RLock()
1201 opts := s.opts
1202 s.optsMu.RUnlock()
1203 return opts
1204 }
1205
1206 func (s *Server) setOpts(opts *Options) {
1207 s.optsMu.Lock()
1208 s.opts = opts
1209 s.optsMu.Unlock()
1210 }
1211
1212 func (s *Server) globalAccount() *Account {
1213 s.mu.RLock()
1214 gacc := s.gacc
1215 s.mu.RUnlock()
1216 return gacc
1217 }
1218
1219 // Used to setup or update Accounts.
1220 // Returns a map that indicates which accounts have had their stream imports
1221 // changed (in case of an update in configuration reload).
1222 // Lock is held upon entry, but will be released/reacquired in this function.
1223 func (s *Server) configureAccounts(reloading bool) (map[string]struct{}, error) {
1224 awcsti := make(map[string]struct{})
1225
1226 // Create the global account.
1227 if s.gacc == nil {
1228 s.gacc = NewAccount(globalAccountName)
1229 s.registerAccountNoLock(s.gacc)
1230 }
1231
1232 opts := s.getOpts()
1233
1234 // We need to track service imports since we can not swap them out (unsub and re-sub)
1235 // until the proper server struct accounts have been swapped in properly. Doing it in
1236 // place could lead to data loss or server panic since account under new si has no real
1237 // account and hence no sublist, so will panic on inbound message.
1238 siMap := make(map[*Account][][]byte)
1239
1240 // Check opts and walk through them. We need to copy them here
1241 // so that we do not keep a real one sitting in the options.
1242 for _, acc := range opts.Accounts {
1243 var a *Account
1244 create := true
1245 // For the global account, we want to skip the reload process
1246 // and fall back into the "create" case which will in that
1247 // case really be just an update (shallowCopy will make sure
1248 // that mappings are copied over).
1249 if reloading && acc.Name != globalAccountName {
1250 if ai, ok := s.accounts.Load(acc.Name); ok {
1251 a = ai.(*Account)
1252 // Before updating the account, check if stream imports have changed.
1253 if !a.checkStreamImportsEqual(acc) {
1254 awcsti[acc.Name] = struct{}{}
1255 }
1256 a.mu.Lock()
1257 // Collect the sids for the service imports since we are going to
1258 // replace with new ones.
1259 var sids [][]byte
1260 for _, sis := range a.imports.services {
1261 for _, si := range sis {
1262 if si.sid != nil {
1263 sids = append(sids, si.sid)
1264 }
1265 }
1266 }
1267 // Setup to process later if needed.
1268 if len(sids) > 0 || len(acc.imports.services) > 0 {
1269 siMap[a] = sids
1270 }
1271
1272 // Now reset all export/imports fields since they are going to be
1273 // filled in shallowCopy()
1274 a.imports.streams, a.imports.services = nil, nil
1275 a.exports.streams, a.exports.services = nil, nil
1276 // We call shallowCopy from the account `acc` (the one in Options)
1277 // and pass `a` (our existing account) to get it updated.
1278 acc.shallowCopy(a)
1279 a.mu.Unlock()
1280 create = false
1281 }
1282 }
1283 // Track old mappings if global account.
1284 var oldGMappings []*mapping
1285 if create {
1286 if acc.Name == globalAccountName {
1287 a = s.gacc
1288 a.mu.Lock()
1289 oldGMappings = append(oldGMappings, a.mappings...)
1290 a.mu.Unlock()
1291 } else {
1292 a = NewAccount(acc.Name)
1293 }
1294 // Locking matters in the case of an update of the global account
1295 a.mu.Lock()
1296 acc.shallowCopy(a)
1297 a.mu.Unlock()
1298 // Will be a no-op in case of the global account since it is already registered.
1299 s.registerAccountNoLock(a)
1300 }
1301
1302 // The `acc` account is stored in options, not in the server, and these can be cleared.
1303 acc.sl, acc.clients, acc.mappings = nil, nil, nil
1304
1305 // Check here if we have been reloaded and we have a global account with mappings that may have changed.
1306 // If we have leafnodes they need to be updated.
1307 if reloading && a == s.gacc {
1308 a.mu.Lock()
1309 mappings := make(map[string]*mapping)
1310 if len(a.mappings) > 0 && a.nleafs > 0 {
1311 for _, em := range a.mappings {
1312 mappings[em.src] = em
1313 }
1314 }
1315 a.mu.Unlock()
1316 if len(mappings) > 0 || len(oldGMappings) > 0 {
1317 a.lmu.RLock()
1318 for _, lc := range a.lleafs {
1319 for _, em := range mappings {
1320 lc.forceAddToSmap(em.src)
1321 }
1322 // Remove any old ones if needed.
1323 for _, em := range oldGMappings {
1324 // Only remove if not in the new ones.
1325 if _, ok := mappings[em.src]; !ok {
1326 lc.forceRemoveFromSmap(em.src)
1327 }
1328 }
1329 }
1330 a.lmu.RUnlock()
1331 }
1332 }
1333
1334 // If we see an account defined using $SYS we will make sure that is set as system account.
1335 if acc.Name == DEFAULT_SYSTEM_ACCOUNT && opts.SystemAccount == _EMPTY_ {
1336 opts.SystemAccount = DEFAULT_SYSTEM_ACCOUNT
1337 }
1338 }
1339
1340 // Now that we have this we need to remap any referenced accounts in
1341 // import or export maps to the new ones.
1342 swapApproved := func(ea *exportAuth) {
1343 for sub, a := range ea.approved {
1344 var acc *Account
1345 if v, ok := s.accounts.Load(a.Name); ok {
1346 acc = v.(*Account)
1347 }
1348 ea.approved[sub] = acc
1349 }
1350 }
1351 var numAccounts int
1352 s.accounts.Range(func(k, v any) bool {
1353 numAccounts++
1354 acc := v.(*Account)
1355 acc.mu.Lock()
1356 // Exports
1357 for _, se := range acc.exports.streams {
1358 if se != nil {
1359 swapApproved(&se.exportAuth)
1360 }
1361 }
1362 for _, se := range acc.exports.services {
1363 if se != nil {
1364 // Swap over the bound account for service exports.
1365 if se.acc != nil {
1366 if v, ok := s.accounts.Load(se.acc.Name); ok {
1367 se.acc = v.(*Account)
1368 }
1369 }
1370 swapApproved(&se.exportAuth)
1371 }
1372 }
1373 // Imports
1374 for _, si := range acc.imports.streams {
1375 if v, ok := s.accounts.Load(si.acc.Name); ok {
1376 si.acc = v.(*Account)
1377 }
1378 }
1379 for _, sis := range acc.imports.services {
1380 for _, si := range sis {
1381 if v, ok := s.accounts.Load(si.acc.Name); ok {
1382 si.acc = v.(*Account)
1383
1384 // It is possible to allow for latency tracking inside your
1385 // own account, so lock only when not the same account.
1386 if si.acc == acc {
1387 si.se = si.acc.getServiceExport(si.to)
1388 continue
1389 }
1390 si.acc.mu.RLock()
1391 si.se = si.acc.getServiceExport(si.to)
1392 si.acc.mu.RUnlock()
1393 }
1394 }
1395 }
1396 // Make sure the subs are running, but only if not reloading.
1397 if len(acc.imports.services) > 0 && acc.ic == nil && !reloading {
1398 acc.ic = s.createInternalAccountClient()
1399 acc.ic.acc = acc
1400 // Need to release locks to invoke this function.
1401 acc.mu.Unlock()
1402 s.mu.Unlock()
1403 acc.addAllServiceImportSubs()
1404 s.mu.Lock()
1405 acc.mu.Lock()
1406 }
1407 acc.updated = time.Now()
1408 acc.mu.Unlock()
1409 return true
1410 })
1411
1412 // Check if we need to process service imports pending from above.
1413 // This processing needs to be after we swap in the real accounts above.
1414 for acc, sids := range siMap {
1415 c := acc.ic
1416 for _, sid := range sids {
1417 c.processUnsub(sid)
1418 }
1419 acc.addAllServiceImportSubs()
1420 s.mu.Unlock()
1421 s.registerSystemImports(acc)
1422 s.mu.Lock()
1423 }
1424
1425 // Set the system account if it was configured.
1426 // Otherwise create a default one.
1427 if opts.SystemAccount != _EMPTY_ {
1428 // Lock may be acquired in lookupAccount, so release to call lookupAccount.
1429 s.mu.Unlock()
1430 acc, err := s.lookupAccount(opts.SystemAccount)
1431 s.mu.Lock()
1432 if err == nil && s.sys != nil && acc != s.sys.account {
1433 // sys.account.clients (including internal client)/respmap/etc... are transferred separately
1434 s.sys.account = acc
1435 s.sysAcc.Store(acc)
1436 }
1437 if err != nil {
1438 return awcsti, fmt.Errorf("error resolving system account: %v", err)
1439 }
1440
1441 // If we have defined a system account here check to see if its just us and the $G account.
1442 // We would do this to add user/pass to the system account. If this is the case add in
1443 // no-auth-user for $G.
1444 // Only do this if non-operator mode and we did not have an authorization block defined.
1445 if len(opts.TrustedOperators) == 0 && numAccounts == 2 && opts.NoAuthUser == _EMPTY_ && !opts.authBlockDefined {
1446 // If we come here from config reload, let's not recreate the fake user name otherwise
1447 // it will cause currently clients to be disconnected.
1448 uname := s.sysAccOnlyNoAuthUser
1449 if uname == _EMPTY_ {
1450 // Create a unique name so we do not collide.
1451 var b [8]byte
1452 rn := rand.Int63()
1453 for i, l := 0, rn; i < len(b); i++ {
1454 b[i] = digits[l%base]
1455 l /= base
1456 }
1457 uname = fmt.Sprintf("nats-%s", b[:])
1458 s.sysAccOnlyNoAuthUser = uname
1459 }
1460 opts.Users = append(opts.Users, &User{Username: uname, Password: uname[6:], Account: s.gacc})
1461 opts.NoAuthUser = uname
1462 }
1463 }
1464
1465 // Add any required exports from system account.
1466 if s.sys != nil {
1467 sysAcc := s.sys.account
1468 s.mu.Unlock()
1469 s.addSystemAccountExports(sysAcc)
1470 s.mu.Lock()
1471 }
1472
1473 return awcsti, nil
1474 }
1475
1476 // Setup the account resolver. For memory resolver, make sure the JWTs are
1477 // properly formed but do not enforce expiration etc.
1478 // Lock is held on entry, but may be released/reacquired during this call.
1479 func (s *Server) configureResolver() error {
1480 opts := s.getOpts()
1481 s.accResolver = opts.AccountResolver
1482 if opts.AccountResolver != nil {
1483 // For URL resolver, set the TLSConfig if specified.
1484 if opts.AccountResolverTLSConfig != nil {
1485 if ar, ok := opts.AccountResolver.(*URLAccResolver); ok {
1486 if t, ok := ar.c.Transport.(*http.Transport); ok {
1487 t.CloseIdleConnections()
1488 t.TLSClientConfig = opts.AccountResolverTLSConfig.Clone()
1489 }
1490 }
1491 }
1492 if len(opts.resolverPreloads) > 0 {
1493 // Lock ordering is account resolver -> server, so we need to release
1494 // the lock and reacquire it when done with account resolver's calls.
1495 ar := s.accResolver
1496 s.mu.Unlock()
1497 defer s.mu.Lock()
1498 if ar.IsReadOnly() {
1499 return fmt.Errorf("resolver preloads only available for writeable resolver types MEM/DIR/CACHE_DIR")
1500 }
1501 for k, v := range opts.resolverPreloads {
1502 _, err := jwt.DecodeAccountClaims(v)
1503 if err != nil {
1504 return fmt.Errorf("preload account error for %q: %v", k, err)
1505 }
1506 ar.Store(k, v)
1507 }
1508 }
1509 }
1510 return nil
1511 }
1512
1513 // This will check preloads for validation issues.
1514 func (s *Server) checkResolvePreloads() {
1515 opts := s.getOpts()
1516 // We can just check the read-only opts versions here, that way we do not need
1517 // to grab server lock or access s.accResolver.
1518 for k, v := range opts.resolverPreloads {
1519 claims, err := jwt.DecodeAccountClaims(v)
1520 if err != nil {
1521 s.Errorf("Preloaded account [%s] not valid", k)
1522 continue
1523 }
1524 // Check if it is expired.
1525 vr := jwt.CreateValidationResults()
1526 claims.Validate(vr)
1527 if vr.IsBlocking(true) {
1528 s.Warnf("Account [%s] has validation issues:", k)
1529 for _, v := range vr.Issues {
1530 s.Warnf(" - %s", v.Description)
1531 }
1532 }
1533 }
1534 }
1535
1536 // Determines if we are in pre NATS 2.0 setup with no accounts.
1537 func (s *Server) globalAccountOnly() bool {
1538 var hasOthers bool
1539
1540 if s.trustedKeys != nil {
1541 return false
1542 }
1543
1544 s.mu.RLock()
1545 s.accounts.Range(func(k, v any) bool {
1546 acc := v.(*Account)
1547 // Ignore global and system
1548 if acc == s.gacc || (s.sys != nil && acc == s.sys.account) {
1549 return true
1550 }
1551 hasOthers = true
1552 return false
1553 })
1554 s.mu.RUnlock()
1555
1556 return !hasOthers
1557 }
1558
1559 // Determines if this server is in standalone mode, meaning no routes or gateways.
1560 func (s *Server) standAloneMode() bool {
1561 opts := s.getOpts()
1562 return opts.Cluster.Port == 0 && opts.Gateway.Port == 0
1563 }
1564
1565 func (s *Server) configuredRoutes() int {
1566 return len(s.getOpts().Routes)
1567 }
1568
1569 // activePeers is used in bootstrapping raft groups like the JetStream meta controller.
1570 func (s *Server) ActivePeers() (peers []string) {
1571 s.nodeToInfo.Range(func(k, v any) bool {
1572 si := v.(nodeInfo)
1573 if !si.offline {
1574 peers = append(peers, k.(string))
1575 }
1576 return true
1577 })
1578 return peers
1579 }
1580
1581 // isTrustedIssuer will check that the issuer is a trusted public key.
1582 // This is used to make sure an account was signed by a trusted operator.
1583 func (s *Server) isTrustedIssuer(issuer string) bool {
1584 s.mu.RLock()
1585 defer s.mu.RUnlock()
1586 // If we are not running in trusted mode and there is no issuer, that is ok.
1587 if s.trustedKeys == nil && issuer == _EMPTY_ {
1588 return true
1589 }
1590 for _, tk := range s.trustedKeys {
1591 if tk == issuer {
1592 return true
1593 }
1594 }
1595 return false
1596 }
1597
1598 // processTrustedKeys will process binary stamped and
1599 // options-based trusted nkeys. Returns success.
1600 func (s *Server) processTrustedKeys() bool {
1601 s.strictSigningKeyUsage = map[string]struct{}{}
1602 opts := s.getOpts()
1603 if trustedKeys != _EMPTY_ && !s.initStampedTrustedKeys() {
1604 return false
1605 } else if opts.TrustedKeys != nil {
1606 for _, key := range opts.TrustedKeys {
1607 if !nkeys.IsValidPublicOperatorKey(key) {
1608 return false
1609 }
1610 }
1611 s.trustedKeys = append([]string(nil), opts.TrustedKeys...)
1612 for _, claim := range opts.TrustedOperators {
1613 if !claim.StrictSigningKeyUsage {
1614 continue
1615 }
1616 for _, key := range claim.SigningKeys {
1617 s.strictSigningKeyUsage[key] = struct{}{}
1618 }
1619 }
1620 }
1621 return true
1622 }
1623
1624 // checkTrustedKeyString will check that the string is a valid array
1625 // of public operator nkeys.
1626 func checkTrustedKeyString(keys string) []string {
1627 tks := strings.Fields(keys)
1628 if len(tks) == 0 {
1629 return nil
1630 }
1631 // Walk all the keys and make sure they are valid.
1632 for _, key := range tks {
1633 if !nkeys.IsValidPublicOperatorKey(key) {
1634 return nil
1635 }
1636 }
1637 return tks
1638 }
1639
1640 // initStampedTrustedKeys will check the stamped trusted keys
1641 // and will set the server field 'trustedKeys'. Returns whether
1642 // it succeeded or not.
1643 func (s *Server) initStampedTrustedKeys() bool {
1644 // Check to see if we have an override in options, which will cause us to fail.
1645 if len(s.getOpts().TrustedKeys) > 0 {
1646 return false
1647 }
1648 tks := checkTrustedKeyString(trustedKeys)
1649 if len(tks) == 0 {
1650 return false
1651 }
1652 s.trustedKeys = tks
1653 return true
1654 }
1655
1656 // PrintAndDie is exported for access in other packages.
1657 func PrintAndDie(msg string) {
1658 fmt.Fprintln(os.Stderr, msg)
1659 os.Exit(1)
1660 }
1661
1662 // PrintServerAndExit will print our version and exit.
1663 func PrintServerAndExit() {
1664 fmt.Printf("nats-server: v%s\n", VERSION)
1665 os.Exit(0)
1666 }
1667
1668 // ProcessCommandLineArgs takes the command line arguments
1669 // validating and setting flags for handling in case any
1670 // sub command was present.
1671 func ProcessCommandLineArgs(cmd *flag.FlagSet) (showVersion bool, showHelp bool, err error) {
1672 if len(cmd.Args()) > 0 {
1673 arg := cmd.Args()[0]
1674 switch strings.ToLower(arg) {
1675 case "version":
1676 return true, false, nil
1677 case "help":
1678 return false, true, nil
1679 default:
1680 return false, false, fmt.Errorf("unrecognized command: %q", arg)
1681 }
1682 }
1683
1684 return false, false, nil
1685 }
1686
1687 // Public version.
1688 func (s *Server) Running() bool {
1689 return s.isRunning()
1690 }
1691
1692 // Protected check on running state
1693 func (s *Server) isRunning() bool {
1694 return s.running.Load()
1695 }
1696
1697 func (s *Server) logPid() error {
1698 pidStr := strconv.Itoa(os.Getpid())
1699 return os.WriteFile(s.getOpts().PidFile, []byte(pidStr), defaultFilePerms)
1700 }
1701
1702 // numReservedAccounts will return the number of reserved accounts configured in the server.
1703 // Currently this is 1, one for the global default account.
1704 func (s *Server) numReservedAccounts() int {
1705 return 1
1706 }
1707
1708 // NumActiveAccounts reports number of active accounts on this server.
1709 func (s *Server) NumActiveAccounts() int32 {
1710 return atomic.LoadInt32(&s.activeAccounts)
1711 }
1712
1713 // incActiveAccounts() just adds one under lock.
1714 func (s *Server) incActiveAccounts() {
1715 atomic.AddInt32(&s.activeAccounts, 1)
1716 }
1717
1718 // decActiveAccounts() just subtracts one under lock.
1719 func (s *Server) decActiveAccounts() {
1720 atomic.AddInt32(&s.activeAccounts, -1)
1721 }
1722
1723 // This should be used for testing only. Will be slow since we have to
1724 // range over all accounts in the sync.Map to count.
1725 func (s *Server) numAccounts() int {
1726 count := 0
1727 s.mu.RLock()
1728 s.accounts.Range(func(k, v any) bool {
1729 count++
1730 return true
1731 })
1732 s.mu.RUnlock()
1733 return count
1734 }
1735
1736 // NumLoadedAccounts returns the number of loaded accounts.
1737 func (s *Server) NumLoadedAccounts() int {
1738 return s.numAccounts()
1739 }
1740
1741 // LookupOrRegisterAccount will return the given account if known or create a new entry.
1742 func (s *Server) LookupOrRegisterAccount(name string) (account *Account, isNew bool) {
1743 s.mu.Lock()
1744 defer s.mu.Unlock()
1745 if v, ok := s.accounts.Load(name); ok {
1746 return v.(*Account), false
1747 }
1748 acc := NewAccount(name)
1749 s.registerAccountNoLock(acc)
1750 return acc, true
1751 }
1752
1753 // RegisterAccount will register an account. The account must be new
1754 // or this call will fail.
1755 func (s *Server) RegisterAccount(name string) (*Account, error) {
1756 s.mu.Lock()
1757 defer s.mu.Unlock()
1758 if _, ok := s.accounts.Load(name); ok {
1759 return nil, ErrAccountExists
1760 }
1761 acc := NewAccount(name)
1762 s.registerAccountNoLock(acc)
1763 return acc, nil
1764 }
1765
1766 // SetSystemAccount will set the internal system account.
1767 // If root operators are present it will also check validity.
1768 func (s *Server) SetSystemAccount(accName string) error {
1769 // Lookup from sync.Map first.
1770 if v, ok := s.accounts.Load(accName); ok {
1771 return s.setSystemAccount(v.(*Account))
1772 }
1773
1774 // If we are here we do not have local knowledge of this account.
1775 // Do this one by hand to return more useful error.
1776 ac, jwt, err := s.fetchAccountClaims(accName)
1777 if err != nil {
1778 return err
1779 }
1780 acc := s.buildInternalAccount(ac)
1781 acc.claimJWT = jwt
1782 // Due to race, we need to make sure that we are not
1783 // registering twice.
1784 if racc := s.registerAccount(acc); racc != nil {
1785 return nil
1786 }
1787 return s.setSystemAccount(acc)
1788 }
1789
1790 // SystemAccount returns the system account if set.
1791 func (s *Server) SystemAccount() *Account {
1792 return s.sysAcc.Load()
1793 }
1794
1795 // GlobalAccount returns the global account.
1796 // Default clients will use the global account.
1797 func (s *Server) GlobalAccount() *Account {
1798 s.mu.RLock()
1799 defer s.mu.RUnlock()
1800 return s.gacc
1801 }
1802
1803 // SetDefaultSystemAccount will create a default system account if one is not present.
1804 func (s *Server) SetDefaultSystemAccount() error {
1805 if _, isNew := s.LookupOrRegisterAccount(DEFAULT_SYSTEM_ACCOUNT); !isNew {
1806 return nil
1807 }
1808 s.Debugf("Created system account: %q", DEFAULT_SYSTEM_ACCOUNT)
1809 return s.SetSystemAccount(DEFAULT_SYSTEM_ACCOUNT)
1810 }
1811
1812 // Assign a system account. Should only be called once.
1813 // This sets up a server to send and receive messages from
1814 // inside the server itself.
1815 func (s *Server) setSystemAccount(acc *Account) error {
1816 if acc == nil {
1817 return ErrMissingAccount
1818 }
1819 // Don't try to fix this here.
1820 if acc.IsExpired() {
1821 return ErrAccountExpired
1822 }
1823 // If we are running with trusted keys for an operator
1824 // make sure we check the account is legit.
1825 if !s.isTrustedIssuer(acc.Issuer) {
1826 return ErrAccountValidation
1827 }
1828
1829 s.mu.Lock()
1830
1831 if s.sys != nil {
1832 s.mu.Unlock()
1833 return ErrAccountExists
1834 }
1835
1836 // This is here in an attempt to quiet the race detector and not have to place
1837 // locks on fast path for inbound messages and checking service imports.
1838 acc.mu.Lock()
1839 if acc.imports.services == nil {
1840 acc.imports.services = make(map[string][]*serviceImport)
1841 }
1842 acc.mu.Unlock()
1843
1844 s.sys = &internal{
1845 account: acc,
1846 client: s.createInternalSystemClient(),
1847 seq: 1,
1848 sid: 1,
1849 servers: make(map[string]*serverUpdate),
1850 replies: make(map[string]msgHandler),
1851 sendq: newIPQueue[*pubMsg](s, "System sendQ"),
1852 recvq: newIPQueue[*inSysMsg](s, "System recvQ"),
1853 recvqp: newIPQueue[*inSysMsg](s, "System recvQ Pings"),
1854 resetCh: make(chan struct{}),
1855 sq: s.newSendQ(acc),
1856 statsz: statsHBInterval,
1857 orphMax: 5 * eventsHBInterval,
1858 chkOrph: 3 * eventsHBInterval,
1859 }
1860 recvq, recvqp := s.sys.recvq, s.sys.recvqp
1861 s.sys.wg.Add(1)
1862 s.mu.Unlock()
1863
1864 // Store in atomic for fast lookup.
1865 s.sysAcc.Store(acc)
1866
1867 // Register with the account.
1868 s.sys.client.registerWithAccount(acc)
1869
1870 s.addSystemAccountExports(acc)
1871
1872 // Start our internal loop to serialize outbound messages.
1873 // We do our own wg here since we will stop first during shutdown.
1874 go s.internalSendLoop(&s.sys.wg)
1875
1876 // Start the internal loop for inbound messages.
1877 go s.internalReceiveLoop(recvq)
1878 // Start the internal loop for inbound STATSZ/Ping messages.
1879 go s.internalReceiveLoop(recvqp)
1880
1881 // Start up our general subscriptions
1882 s.initEventTracking()
1883
1884 // Track for dead remote servers.
1885 s.wrapChk(s.startRemoteServerSweepTimer)()
1886
1887 // Send out statsz updates periodically.
1888 s.wrapChk(s.startStatszTimer)()
1889
1890 // If we have existing accounts make sure we enable account tracking.
1891 s.mu.Lock()
1892 s.accounts.Range(func(k, v any) bool {
1893 acc := v.(*Account)
1894 s.enableAccountTracking(acc)
1895 return true
1896 })
1897 s.mu.Unlock()
1898
1899 return nil
1900 }
1901
1902 // Creates an internal system client.
1903 func (s *Server) createInternalSystemClient() *client {
1904 return s.createInternalClient(SYSTEM)
1905 }
1906
1907 // Creates an internal jetstream client.
1908 func (s *Server) createInternalJetStreamClient() *client {
1909 return s.createInternalClient(JETSTREAM)
1910 }
1911
1912 // Creates an internal client for Account.
1913 func (s *Server) createInternalAccountClient() *client {
1914 return s.createInternalClient(ACCOUNT)
1915 }
1916
1917 // Internal clients. kind should be SYSTEM, JETSTREAM or ACCOUNT
1918 func (s *Server) createInternalClient(kind int) *client {
1919 if !isInternalClient(kind) {
1920 return nil
1921 }
1922 now := time.Now()
1923 c := &client{srv: s, kind: kind, opts: internalOpts, msubs: -1, mpay: -1, start: now, last: now}
1924 c.initClient()
1925 c.echo = false
1926 c.headers = true
1927 c.flags.set(noReconnect)
1928 return c
1929 }
1930
1931 // Determine if accounts should track subscriptions for
1932 // efficient propagation.
1933 // Lock should be held on entry.
1934 func (s *Server) shouldTrackSubscriptions() bool {
1935 opts := s.getOpts()
1936 return (opts.Cluster.Port != 0 || opts.Gateway.Port != 0)
1937 }
1938
1939 // Invokes registerAccountNoLock under the protection of the server lock.
1940 // That is, server lock is acquired/released in this function.
1941 // See registerAccountNoLock for comment on returned value.
1942 func (s *Server) registerAccount(acc *Account) *Account {
1943 s.mu.Lock()
1944 racc := s.registerAccountNoLock(acc)
1945 s.mu.Unlock()
1946 return racc
1947 }
1948
1949 // Helper to set the sublist based on preferences.
1950 func (s *Server) setAccountSublist(acc *Account) {
1951 if acc != nil && acc.sl == nil {
1952 acc.sl = NewSublistForServer(s)
1953 }
1954 }
1955
1956 // Registers an account in the server.
1957 // Due to some locking considerations, we may end-up trying
1958 // to register the same account twice. This function will
1959 // then return the already registered account.
1960 // Lock should be held on entry.
1961 func (s *Server) registerAccountNoLock(acc *Account) *Account {
1962 // We are under the server lock. Lookup from map, if present
1963 // return existing account.
1964 if a, _ := s.accounts.Load(acc.Name); a != nil {
1965 s.tmpAccounts.Delete(acc.Name)
1966 return a.(*Account)
1967 }
1968 // Finish account setup and store.
1969 s.setAccountSublist(acc)
1970
1971 acc.mu.Lock()
1972 s.setRouteInfo(acc)
1973 if acc.clients == nil {
1974 acc.clients = make(map[*client]struct{})
1975 }
1976
1977 // If we are capable of routing we will track subscription
1978 // information for efficient interest propagation.
1979 // During config reload, it is possible that account was
1980 // already created (global account), so use locking and
1981 // make sure we create only if needed.
1982 // TODO(dlc)- Double check that we need this for GWs.
1983 if acc.rm == nil && s.opts != nil && s.shouldTrackSubscriptions() {
1984 acc.rm = make(map[string]int32)
1985 acc.lws = make(map[string]int32)
1986 }
1987 acc.srv = s
1988 acc.updated = time.Now()
1989 accName := acc.Name
1990 jsEnabled := len(acc.jsLimits) > 0
1991 acc.mu.Unlock()
1992
1993 if opts := s.getOpts(); opts != nil && len(opts.JsAccDefaultDomain) > 0 {
1994 if defDomain, ok := opts.JsAccDefaultDomain[accName]; ok {
1995 if jsEnabled {
1996 s.Warnf("Skipping Default Domain %q, set for JetStream enabled account %q", defDomain, accName)
1997 } else if defDomain != _EMPTY_ {
1998 for src, dest := range generateJSMappingTable(defDomain) {
1999 // flip src and dest around so the domain is inserted
2000 s.Noticef("Adding default domain mapping %q -> %q to account %q %p", dest, src, accName, acc)
2001 if err := acc.AddMapping(dest, src); err != nil {
2002 s.Errorf("Error adding JetStream default domain mapping: %v", err)
2003 }
2004 }
2005 }
2006 }
2007 }
2008
2009 s.accounts.Store(acc.Name, acc)
2010 s.tmpAccounts.Delete(acc.Name)
2011 s.enableAccountTracking(acc)
2012
2013 // Can not have server lock here.
2014 s.mu.Unlock()
2015 s.registerSystemImports(acc)
2016 // Starting 2.9.0, we are phasing out the optimistic mode, so change
2017 // the account to interest-only mode (except if instructed not to do
2018 // it in some tests).
2019 if s.gateway.enabled && !gwDoNotForceInterestOnlyMode {
2020 s.switchAccountToInterestMode(acc.GetName())
2021 }
2022 s.mu.Lock()
2023
2024 return nil
2025 }
2026
2027 // Sets the account's routePoolIdx depending on presence or not of
2028 // pooling or per-account routes. Also updates a map used by
2029 // gateway code to retrieve a route based on some route hash.
2030 //
2031 // Both Server and Account lock held on entry.
2032 func (s *Server) setRouteInfo(acc *Account) {
2033 // If there is a dedicated route configured for this account
2034 if _, ok := s.accRoutes[acc.Name]; ok {
2035 // We want the account name to be in the map, but we don't
2036 // need a value (we could store empty string)
2037 s.accRouteByHash.Store(acc.Name, nil)
2038 // Set the route pool index to -1 so that it is easy when
2039 // ranging over accounts to exclude those accounts when
2040 // trying to get accounts for a given pool index.
2041 acc.routePoolIdx = accDedicatedRoute
2042 } else {
2043 // If pool size more than 1, we will compute a hash code and
2044 // use modulo to assign to an index of the pool slice. For 1
2045 // and below, all accounts will be bound to the single connection
2046 // at index 0.
2047 acc.routePoolIdx = computeRoutePoolIdx(s.routesPoolSize, acc.Name)
2048 if s.routesPoolSize > 1 {
2049 s.accRouteByHash.Store(acc.Name, acc.routePoolIdx)
2050 }
2051 }
2052 }
2053
2054 // lookupAccount is a function to return the account structure
2055 // associated with an account name.
2056 // Lock MUST NOT be held upon entry.
2057 func (s *Server) lookupAccount(name string) (*Account, error) {
2058 return s.lookupOrFetchAccount(name, true)
2059 }
2060
2061 // lookupOrFetchAccount is a function to return the account structure
2062 // associated with an account name.
2063 // Lock MUST NOT be held upon entry.
2064 func (s *Server) lookupOrFetchAccount(name string, fetch bool) (*Account, error) {
2065 var acc *Account
2066 if v, ok := s.accounts.Load(name); ok {
2067 acc = v.(*Account)
2068 }
2069 if acc != nil {
2070 // If we are expired and we have a resolver, then
2071 // return the latest information from the resolver.
2072 if acc.IsExpired() {
2073 s.Debugf("Requested account [%s] has expired", name)
2074 if s.AccountResolver() != nil && fetch {
2075 if err := s.updateAccount(acc); err != nil {
2076 // This error could mask expired, so just return expired here.
2077 return nil, ErrAccountExpired
2078 }
2079 } else {
2080 return nil, ErrAccountExpired
2081 }
2082 }
2083 return acc, nil
2084 }
2085 // If we have a resolver see if it can fetch the account.
2086 if s.AccountResolver() == nil || !fetch {
2087 return nil, ErrMissingAccount
2088 }
2089 return s.fetchAccount(name)
2090 }
2091
2092 // LookupAccount is a public function to return the account structure
2093 // associated with name.
2094 func (s *Server) LookupAccount(name string) (*Account, error) {
2095 return s.lookupAccount(name)
2096 }
2097
2098 // This will fetch new claims and if found update the account with new claims.
2099 // Lock MUST NOT be held upon entry.
2100 func (s *Server) updateAccount(acc *Account) error {
2101 acc.mu.RLock()
2102 // TODO(dlc) - Make configurable
2103 if !acc.incomplete && time.Since(acc.updated) < time.Second {
2104 acc.mu.RUnlock()
2105 s.Debugf("Requested account update for [%s] ignored, too soon", acc.Name)
2106 return ErrAccountResolverUpdateTooSoon
2107 }
2108 acc.mu.RUnlock()
2109 claimJWT, err := s.fetchRawAccountClaims(acc.Name)
2110 if err != nil {
2111 return err
2112 }
2113 return s.updateAccountWithClaimJWT(acc, claimJWT)
2114 }
2115
2116 // updateAccountWithClaimJWT will check and apply the claim update.
2117 // Lock MUST NOT be held upon entry.
2118 func (s *Server) updateAccountWithClaimJWT(acc *Account, claimJWT string) error {
2119 if acc == nil {
2120 return ErrMissingAccount
2121 }
2122 acc.mu.RLock()
2123 sameClaim := acc.claimJWT != _EMPTY_ && acc.claimJWT == claimJWT && !acc.incomplete
2124 acc.mu.RUnlock()
2125 if sameClaim {
2126 s.Debugf("Requested account update for [%s], same claims detected", acc.Name)
2127 return nil
2128 }
2129 accClaims, _, err := s.verifyAccountClaims(claimJWT)
2130 if err == nil && accClaims != nil {
2131 acc.mu.Lock()
2132 // if an account is updated with a different operator signing key, we want to
2133 // show a consistent issuer.
2134 acc.Issuer = accClaims.Issuer
2135 if acc.Name != accClaims.Subject {
2136 acc.mu.Unlock()
2137 return ErrAccountValidation
2138 }
2139 acc.mu.Unlock()
2140 s.UpdateAccountClaims(acc, accClaims)
2141 acc.mu.Lock()
2142 // needs to be set after update completed.
2143 // This causes concurrent calls to return with sameClaim=true if the change is effective.
2144 acc.claimJWT = claimJWT
2145 acc.mu.Unlock()
2146 return nil
2147 }
2148 return err
2149 }
2150
2151 // fetchRawAccountClaims will grab raw account claims iff we have a resolver.
2152 // Lock is NOT held upon entry.
2153 func (s *Server) fetchRawAccountClaims(name string) (string, error) {
2154 accResolver := s.AccountResolver()
2155 if accResolver == nil {
2156 return _EMPTY_, ErrNoAccountResolver
2157 }
2158 // Need to do actual Fetch
2159 start := time.Now()
2160 claimJWT, err := fetchAccount(accResolver, name)
2161 fetchTime := time.Since(start)
2162 if fetchTime > time.Second {
2163 s.Warnf("Account [%s] fetch took %v", name, fetchTime)
2164 } else {
2165 s.Debugf("Account [%s] fetch took %v", name, fetchTime)
2166 }
2167 if err != nil {
2168 s.Warnf("Account fetch failed: %v", err)
2169 return "", err
2170 }
2171 return claimJWT, nil
2172 }
2173
2174 // fetchAccountClaims will attempt to fetch new claims if a resolver is present.
2175 // Lock is NOT held upon entry.
2176 func (s *Server) fetchAccountClaims(name string) (*jwt.AccountClaims, string, error) {
2177 claimJWT, err := s.fetchRawAccountClaims(name)
2178 if err != nil {
2179 return nil, _EMPTY_, err
2180 }
2181 var claim *jwt.AccountClaims
2182 claim, claimJWT, err = s.verifyAccountClaims(claimJWT)
2183 if claim != nil && claim.Subject != name {
2184 return nil, _EMPTY_, ErrAccountValidation
2185 }
2186 return claim, claimJWT, err
2187 }
2188
2189 // verifyAccountClaims will decode and validate any account claims.
2190 func (s *Server) verifyAccountClaims(claimJWT string) (*jwt.AccountClaims, string, error) {
2191 accClaims, err := jwt.DecodeAccountClaims(claimJWT)
2192 if err != nil {
2193 return nil, _EMPTY_, err
2194 }
2195 if !s.isTrustedIssuer(accClaims.Issuer) {
2196 return nil, _EMPTY_, ErrAccountValidation
2197 }
2198 vr := jwt.CreateValidationResults()
2199 accClaims.Validate(vr)
2200 if vr.IsBlocking(true) {
2201 return nil, _EMPTY_, ErrAccountValidation
2202 }
2203 return accClaims, claimJWT, nil
2204 }
2205
2206 // This will fetch an account from a resolver if defined.
2207 // Lock is NOT held upon entry.
2208 func (s *Server) fetchAccount(name string) (*Account, error) {
2209 accClaims, claimJWT, err := s.fetchAccountClaims(name)
2210 if accClaims == nil {
2211 return nil, err
2212 }
2213 acc := s.buildInternalAccount(accClaims)
2214 // Due to possible race, if registerAccount() returns a non
2215 // nil account, it means the same account was already
2216 // registered and we should use this one.
2217 if racc := s.registerAccount(acc); racc != nil {
2218 // Update with the new claims in case they are new.
2219 if err = s.updateAccountWithClaimJWT(racc, claimJWT); err != nil {
2220 return nil, err
2221 }
2222 return racc, nil
2223 }
2224 // The sub imports may have been setup but will not have had their
2225 // subscriptions properly setup. Do that here.
2226 var needImportSubs bool
2227
2228 acc.mu.Lock()
2229 acc.claimJWT = claimJWT
2230 if len(acc.imports.services) > 0 {
2231 if acc.ic == nil {
2232 acc.ic = s.createInternalAccountClient()
2233 acc.ic.acc = acc
2234 }
2235 needImportSubs = true
2236 }
2237 acc.mu.Unlock()
2238
2239 // Do these outside the lock.
2240 if needImportSubs {
2241 acc.addAllServiceImportSubs()
2242 }
2243
2244 return acc, nil
2245 }
2246
2247 // Start up the server, this will not block.
2248 //
2249 // WaitForShutdown can be used to block and wait for the server to shutdown properly if needed
2250 // after calling s.Shutdown()
2251 func (s *Server) Start() {
2252 s.Noticef("Starting nats-server")
2253
2254 gc := gitCommit
2255 if gc == _EMPTY_ {
2256 gc = "not set"
2257 }
2258
2259 // Snapshot server options.
2260 opts := s.getOpts()
2261
2262 // Capture if this server is a leaf that has no cluster, so we don't
2263 // display the cluster name if that is the case.
2264 s.mu.RLock()
2265 leafNoCluster := s.leafNoCluster
2266 s.mu.RUnlock()
2267
2268 var clusterName string
2269 if !leafNoCluster {
2270 clusterName = s.ClusterName()
2271 }
2272
2273 s.Noticef(" Version: %s", VERSION)
2274 s.Noticef(" Git: [%s]", gc)
2275 s.Debugf(" Go build: %s", s.info.GoVersion)
2276 if clusterName != _EMPTY_ {
2277 s.Noticef(" Cluster: %s", clusterName)
2278 }
2279 s.Noticef(" Name: %s", s.info.Name)
2280 if opts.JetStream {
2281 s.Noticef(" Node: %s", getHash(s.info.Name))
2282 }
2283 s.Noticef(" ID: %s", s.info.ID)
2284 s.printFeatureFlags(opts)
2285
2286 defer s.Noticef("Server is ready")
2287
2288 // Check for insecure configurations.
2289 s.checkAuthforWarnings()
2290
2291 // Avoid RACE between Start() and Shutdown()
2292 s.running.Store(true)
2293 s.mu.Lock()
2294 // Update leafNodeEnabled in case options have changed post NewServer()
2295 // and before Start() (we should not be able to allow that, but server has
2296 // direct reference to user-provided options - at least before a Reload() is
2297 // performed.
2298 s.leafNodeEnabled = opts.LeafNode.Port != 0 || len(opts.LeafNode.Remotes) > 0
2299 s.mu.Unlock()
2300
2301 s.grMu.Lock()
2302 s.grRunning = true
2303 s.grMu.Unlock()
2304
2305 s.startRateLimitLogExpiration()
2306
2307 // Pprof http endpoint for the profiler.
2308 if opts.ProfPort != 0 {
2309 s.StartProfiler()
2310 } else {
2311 // It's still possible to access this profile via a SYS endpoint, so set
2312 // this anyway. (Otherwise StartProfiler would have called it.)
2313 s.setBlockProfileRate(opts.ProfBlockRate)
2314 }
2315
2316 if opts.ConfigFile != _EMPTY_ {
2317 var cd string
2318 if opts.configDigest != "" {
2319 cd = fmt.Sprintf("(%s)", opts.configDigest)
2320 }
2321 s.Noticef("Using configuration file: %s %s", opts.ConfigFile, cd)
2322 }
2323
2324 hasOperators := len(opts.TrustedOperators) > 0
2325 if hasOperators {
2326 s.Noticef("Trusted Operators")
2327 }
2328 for _, opc := range opts.TrustedOperators {
2329 s.Noticef(" System : %q", opc.Audience)
2330 s.Noticef(" Operator: %q", opc.Name)
2331 s.Noticef(" Issued : %v", time.Unix(opc.IssuedAt, 0))
2332 switch opc.Expires {
2333 case 0:
2334 s.Noticef(" Expires : Never")
2335 default:
2336 s.Noticef(" Expires : %v", time.Unix(opc.Expires, 0))
2337 }
2338 }
2339 if hasOperators && opts.SystemAccount == _EMPTY_ {
2340 s.Warnf("Trusted Operators should utilize a System Account")
2341 }
2342 if opts.MaxPayload > MAX_PAYLOAD_MAX_SIZE {
2343 s.Warnf("Maximum payloads over %v are generally discouraged and could lead to poor performance",
2344 friendlyBytes(int64(MAX_PAYLOAD_MAX_SIZE)))
2345 }
2346
2347 if len(opts.JsAccDefaultDomain) > 0 {
2348 s.Warnf("The option `default_js_domain` is a temporary backwards compatibility measure and will be removed")
2349 }
2350
2351 // If we have a memory resolver, check the accounts here for validation exceptions.
2352 // This allows them to be logged right away vs when they are accessed via a client.
2353 if hasOperators && len(opts.resolverPreloads) > 0 {
2354 s.checkResolvePreloads()
2355 }
2356
2357 // Log the pid to a file.
2358 if opts.PidFile != _EMPTY_ {
2359 if err := s.logPid(); err != nil {
2360 s.Fatalf("Could not write pidfile: %v", err)
2361 return
2362 }
2363 }
2364
2365 // Setup system account which will start the eventing stack.
2366 if sa := opts.SystemAccount; sa != _EMPTY_ {
2367 if err := s.SetSystemAccount(sa); err != nil {
2368 s.Fatalf("Can't set system account: %v", err)
2369 return
2370 }
2371 } else if !opts.NoSystemAccount {
2372 // We will create a default system account here.
2373 s.SetDefaultSystemAccount()
2374 }
2375
2376 // Start monitoring before enabling other subsystems of the
2377 // server to be able to monitor during startup.
2378 if err := s.StartMonitoring(); err != nil {
2379 s.Fatalf("Can't start monitoring: %v", err)
2380 return
2381 }
2382
2383 // Start up resolver machinery.
2384 if ar := s.AccountResolver(); ar != nil {
2385 if err := ar.Start(s); err != nil {
2386 s.Fatalf("Could not start resolver: %v", err)
2387 return
2388 }
2389 // In operator mode, when the account resolver depends on an external system and
2390 // the system account is the bootstrapping account, start fetching it.
2391 if len(opts.TrustedOperators) == 1 && opts.SystemAccount != _EMPTY_ && opts.SystemAccount != DEFAULT_SYSTEM_ACCOUNT {
2392 opts := s.getOpts()
2393 _, isMemResolver := ar.(*MemAccResolver)
2394 if v, ok := s.accounts.Load(opts.SystemAccount); !isMemResolver && ok && v.(*Account).claimJWT == _EMPTY_ {
2395 s.Noticef("Using bootstrapping system account")
2396 s.startGoRoutine(func() {
2397 defer s.grWG.Done()
2398 t := time.NewTicker(time.Second)
2399 defer t.Stop()
2400 for {
2401 select {
2402 case <-s.quitCh:
2403 return
2404 case <-t.C:
2405 sacc := s.SystemAccount()
2406 if claimJWT, err := fetchAccount(ar, opts.SystemAccount); err != nil {
2407 continue
2408 } else if err = s.updateAccountWithClaimJWT(sacc, claimJWT); err != nil {
2409 continue
2410 }
2411 s.Noticef("System account fetched and updated")
2412 return
2413 }
2414 }
2415 })
2416 }
2417 }
2418 }
2419
2420 // Start expiration of mapped GW replies, regardless if
2421 // this server is configured with gateway or not.
2422 s.startGWReplyMapExpiration()
2423
2424 // Check if JetStream has been enabled. This needs to be after
2425 // the system account setup above. JetStream will create its
2426 // own system account if one is not present.
2427 if opts.JetStream {
2428 // Make sure someone is not trying to enable on the system account.
2429 if sa := s.SystemAccount(); sa != nil && len(sa.jsLimits) > 0 {
2430 s.Fatalf("Not allowed to enable JetStream on the system account")
2431 }
2432 cfg := &JetStreamConfig{
2433 StoreDir: opts.StoreDir,
2434 SyncInterval: opts.SyncInterval,
2435 SyncAlways: opts.SyncAlways,
2436 Strict: !opts.NoJetStreamStrict,
2437 MaxMemory: opts.JetStreamMaxMemory,
2438 MaxStore: opts.JetStreamMaxStore,
2439 Domain: opts.JetStreamDomain,
2440 CompressOK: true,
2441 UniqueTag: opts.JetStreamUniqueTag,
2442 }
2443 if err := s.EnableJetStream(cfg); err != nil {
2444 s.Fatalf("Can't start JetStream: %v", err)
2445 return
2446 }
2447 } else {
2448 // Check to see if any configured accounts have JetStream enabled.
2449 sa, ga := s.SystemAccount(), s.GlobalAccount()
2450 var hasSys, hasGlobal bool
2451 var total int
2452
2453 s.accounts.Range(func(k, v any) bool {
2454 total++
2455 acc := v.(*Account)
2456 if acc == sa {
2457 hasSys = true
2458 } else if acc == ga {
2459 hasGlobal = true
2460 }
2461 acc.mu.RLock()
2462 hasJs := len(acc.jsLimits) > 0
2463 acc.mu.RUnlock()
2464 if hasJs {
2465 s.checkJetStreamExports()
2466 acc.enableAllJetStreamServiceImportsAndMappings()
2467 }
2468 return true
2469 })
2470 // If we only have the system account and the global account and we are not standalone,
2471 // go ahead and enable JS on $G in case we are in simple mixed mode setup.
2472 if total == 2 && hasSys && hasGlobal && !s.standAloneMode() {
2473 ga.mu.Lock()
2474 ga.jsLimits = map[string]JetStreamAccountLimits{
2475 _EMPTY_: dynamicJSAccountLimits,
2476 }
2477 ga.mu.Unlock()
2478 s.checkJetStreamExports()
2479 ga.enableAllJetStreamServiceImportsAndMappings()
2480 }
2481 }
2482
2483 // Delayed API response handling. Start regardless of JetStream being
2484 // currently configured or not (since it can be enabled/disabled with
2485 // configuration reload).
2486 s.startGoRoutine(s.delayedAPIResponder)
2487
2488 // Start OCSP Stapling monitoring for TLS certificates if enabled. Hook TLS handshake for
2489 // OCSP check on peers (LEAF and CLIENT kind) if enabled.
2490 s.startOCSPMonitoring()
2491
2492 // Configure OCSP Response Cache for peer OCSP checks if enabled.
2493 s.initOCSPResponseCache()
2494
2495 // Start up gateway if needed. Do this before starting the routes, because
2496 // we want to resolve the gateway host:port so that this information can
2497 // be sent to other routes.
2498 if opts.Gateway.Port != 0 {
2499 s.startGateways()
2500 }
2501
2502 // Start websocket server if needed. Do this before starting the routes, and
2503 // leaf node because we want to resolve the gateway host:port so that this
2504 // information can be sent to other routes.
2505 if opts.Websocket.Port != 0 {
2506 s.startWebsocketServer()
2507 }
2508
2509 // Start up listen if we want to accept leaf node connections.
2510 if opts.LeafNode.Port != 0 {
2511 // Will resolve or assign the advertise address for the leafnode listener.
2512 // We need that in StartRouting().
2513 s.startLeafNodeAcceptLoop()
2514 }
2515
2516 // Solicit remote servers for leaf node connections.
2517 if len(opts.LeafNode.Remotes) > 0 {
2518 s.solicitLeafNodeRemotes(opts.LeafNode.Remotes)
2519 }
2520
2521 // TODO (ik): I wanted to refactor this by starting the client
2522 // accept loop first, that is, it would resolve listen spec
2523 // in place, but start the accept-for-loop in a different go
2524 // routine. This would get rid of the synchronization between
2525 // this function and StartRouting, which I also would have wanted
2526 // to refactor, but both AcceptLoop() and StartRouting() have
2527 // been exported and not sure if that would break users using them.
2528 // We could mark them as deprecated and remove in a release or two...
2529
2530 // The Routing routine needs to wait for the client listen
2531 // port to be opened and potential ephemeral port selected.
2532 clientListenReady := make(chan struct{})
2533
2534 // MQTT
2535 if opts.MQTT.Port != 0 {
2536 s.startMQTT()
2537 }
2538
2539 // Start up routing as well if needed.
2540 if opts.Cluster.Port != 0 {
2541 s.startGoRoutine(func() {
2542 s.StartRouting(clientListenReady)
2543 })
2544 }
2545
2546 if opts.PortsFileDir != _EMPTY_ {
2547 s.logPorts()
2548 }
2549
2550 if opts.TLSRateLimit > 0 {
2551 s.startGoRoutine(s.logRejectedTLSConns)
2552 }
2553
2554 // We've finished starting up.
2555 close(s.startupComplete)
2556
2557 // Wait for clients.
2558 if !opts.DontListen {
2559 s.AcceptLoop(clientListenReady)
2560 }
2561
2562 // Bring OSCP Response cache online after accept loop started in anticipation of NATS-enabled cache types
2563 s.startOCSPResponseCache()
2564 }
2565
2566 func (s *Server) isShuttingDown() bool {
2567 return s.shutdown.Load()
2568 }
2569
2570 // Shutdown will shutdown the server instance by kicking out the AcceptLoop
2571 // and closing all associated clients.
2572 func (s *Server) Shutdown() {
2573 if s == nil {
2574 return
2575 }
2576 // Prevent issues with multiple calls.
2577 if !s.shutdown.CompareAndSwap(false, true) {
2578 return
2579 }
2580 // This is for JetStream R1 Pull Consumers to allow signaling
2581 // that pending pull requests are invalid.
2582 s.signalPullConsumers()
2583
2584 // Transfer off any raft nodes that we are a leader by stepping them down.
2585 s.stepdownRaftNodes()
2586
2587 // Shutdown the eventing system as needed.
2588 // This is done first to send out any messages for
2589 // account status. We will also clean up any
2590 // eventing items associated with accounts.
2591 s.shutdownEventing()
2592
2593 s.mu.Lock()
2594 s.Noticef("Initiating Shutdown...")
2595
2596 accRes := s.accResolver
2597
2598 opts := s.getOpts()
2599
2600 s.running.Store(false)
2601 s.grMu.Lock()
2602 s.grRunning = false
2603 s.grMu.Unlock()
2604 s.mu.Unlock()
2605
2606 if accRes != nil {
2607 accRes.Close()
2608 }
2609
2610 // Now check and shutdown jetstream.
2611 s.shutdownJetStream()
2612
2613 // Now shutdown the nodes
2614 s.shutdownRaftNodes()
2615
2616 s.mu.Lock()
2617 conns := make(map[uint64]*client)
2618
2619 // Copy off the clients
2620 for i, c := range s.clients {
2621 conns[i] = c
2622 }
2623 // Copy off the connections that are not yet registered
2624 // in s.routes, but for which the readLoop has started
2625 s.grMu.Lock()
2626 for i, c := range s.grTmpClients {
2627 conns[i] = c
2628 }
2629 s.grMu.Unlock()
2630 // Copy off the routes
2631 s.forEachRoute(func(r *client) {
2632 r.mu.Lock()
2633 conns[r.cid] = r
2634 r.mu.Unlock()
2635 })
2636 // Copy off the gateways
2637 s.getAllGatewayConnections(conns)
2638
2639 // Copy off the leaf nodes
2640 for i, c := range s.leafs {
2641 conns[i] = c
2642 }
2643
2644 // Number of done channel responses we expect.
2645 doneExpected := 0
2646
2647 // Kick client AcceptLoop()
2648 if s.listener != nil {
2649 doneExpected++
2650 s.listener.Close()
2651 s.listener = nil
2652 }
2653
2654 // Kick websocket server
2655 doneExpected += s.closeWebsocketServer()
2656
2657 // Kick MQTT accept loop
2658 if s.mqtt.listener != nil {
2659 doneExpected++
2660 s.mqtt.listener.Close()
2661 s.mqtt.listener = nil
2662 }
2663
2664 // Kick leafnodes AcceptLoop()
2665 if s.leafNodeListener != nil {
2666 doneExpected++
2667 s.leafNodeListener.Close()
2668 s.leafNodeListener = nil
2669 }
2670
2671 // Kick route AcceptLoop()
2672 if s.routeListener != nil {
2673 doneExpected++
2674 s.routeListener.Close()
2675 s.routeListener = nil
2676 }
2677
2678 // Kick Gateway AcceptLoop()
2679 if s.gatewayListener != nil {
2680 doneExpected++
2681 s.gatewayListener.Close()
2682 s.gatewayListener = nil
2683 }
2684
2685 // Kick HTTP monitoring if its running
2686 if s.http != nil {
2687 doneExpected++
2688 s.http.Close()
2689 s.http = nil
2690 }
2691
2692 // Kick Profiling if its running
2693 if s.profiler != nil {
2694 doneExpected++
2695 s.profiler.Close()
2696 }
2697
2698 s.mu.Unlock()
2699
2700 // Release go routines that wait on that channel
2701 close(s.quitCh)
2702
2703 // Close client and route connections
2704 for _, c := range conns {
2705 c.setNoReconnect()
2706 c.closeConnection(ServerShutdown)
2707 }
2708
2709 // Block until the accept loops exit
2710 for doneExpected > 0 {
2711 <-s.done
2712 doneExpected--
2713 }
2714
2715 // Wait for go routines to be done.
2716 s.grWG.Wait()
2717
2718 if opts.PortsFileDir != _EMPTY_ {
2719 s.deletePortsFile(opts.PortsFileDir)
2720 }
2721
2722 s.Noticef("Server Exiting..")
2723
2724 // Stop OCSP Response Cache
2725 if s.ocsprc != nil {
2726 s.ocsprc.Stop(s)
2727 }
2728
2729 // Close logger if applicable. It allows tests on Windows
2730 // to be able to do proper cleanup (delete log file).
2731 s.logging.RLock()
2732 log := s.logging.logger
2733 s.logging.RUnlock()
2734 if log != nil {
2735 if l, ok := log.(*logger.Logger); ok {
2736 l.Close()
2737 }
2738 }
2739 // Notify that the shutdown is complete
2740 close(s.shutdownComplete)
2741 }
2742
2743 // Close the websocket server if running. If so, returns 1, else 0.
2744 // Server lock held on entry.
2745 func (s *Server) closeWebsocketServer() int {
2746 ws := &s.websocket
2747 ws.mu.Lock()
2748 hs := ws.server
2749 if hs != nil {
2750 ws.server = nil
2751 ws.listener = nil
2752 }
2753 ws.mu.Unlock()
2754 if hs != nil {
2755 hs.Close()
2756 return 1
2757 }
2758 return 0
2759 }
2760
2761 // WaitForShutdown will block until the server has been fully shutdown.
2762 func (s *Server) WaitForShutdown() {
2763 <-s.shutdownComplete
2764 }
2765
2766 // AcceptLoop is exported for easier testing.
2767 func (s *Server) AcceptLoop(clr chan struct{}) {
2768 // If we were to exit before the listener is setup properly,
2769 // make sure we close the channel.
2770 defer func() {
2771 if clr != nil {
2772 close(clr)
2773 }
2774 }()
2775
2776 if s.isShuttingDown() {
2777 return
2778 }
2779
2780 // Snapshot server options.
2781 opts := s.getOpts()
2782
2783 // Setup state that can enable shutdown
2784 s.mu.Lock()
2785 hp := net.JoinHostPort(opts.Host, strconv.Itoa(opts.Port))
2786 l, e := s.getServerListener(hp)
2787 s.listenerErr = e
2788 if e != nil {
2789 s.mu.Unlock()
2790 s.Fatalf("Error listening on port: %s, %q", hp, e)
2791 return
2792 }
2793 s.Noticef("Listening for client connections on %s",
2794 net.JoinHostPort(opts.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
2795
2796 // Alert if PROXY protocol is enabled
2797 if opts.ProxyProtocol {
2798 s.Noticef("PROXY protocol enabled for client connections")
2799 }
2800
2801 // Alert of TLS enabled.
2802 if opts.TLSConfig != nil {
2803 // "TLS Handshake First" without a fallback delay always requires the
2804 // handshake, which overrides "allow_non_tls".
2805 tlsHandshakeFirstOnly := opts.TLSHandshakeFirst && opts.TLSHandshakeFirstFallback == 0
2806 if opts.AllowNonTLS && !tlsHandshakeFirstOnly {
2807 s.Noticef("TLS available for client connections")
2808 } else {
2809 s.Noticef("TLS required for client connections")
2810 }
2811 if tlsHandshakeFirstOnly {
2812 s.Warnf("Clients that are not using \"TLS Handshake First\" option will fail to connect")
2813 }
2814 }
2815
2816 // If server was started with RANDOM_PORT (-1), opts.Port would be equal
2817 // to 0 at the beginning this function. So we need to get the actual port
2818 if opts.Port == 0 {
2819 // Write resolved port back to options.
2820 opts.Port = l.Addr().(*net.TCPAddr).Port
2821 }
2822
2823 // Now that port has been set (if it was set to RANDOM), set the
2824 // server's info Host/Port with either values from Options or
2825 // ClientAdvertise.
2826 if err := s.setInfoHostPort(); err != nil {
2827 s.Fatalf("Error setting server INFO with ClientAdvertise value of %s, err=%v", opts.ClientAdvertise, err)
2828 l.Close()
2829 s.mu.Unlock()
2830 return
2831 }
2832 // Keep track of client connect URLs. We may need them later.
2833 s.clientConnectURLs = s.getClientConnectURLs()
2834 s.listener = l
2835
2836 go s.acceptConnections(l, "Client", func(conn net.Conn) { s.createClient(conn) },
2837 func(_ error) bool {
2838 if s.isLameDuckMode() {
2839 // Signal that we are not accepting new clients
2840 s.ldmCh <- true
2841 // Now wait for the Shutdown...
2842 <-s.quitCh
2843 return true
2844 }
2845 return false
2846 })
2847 s.mu.Unlock()
2848
2849 // Let the caller know that we are ready
2850 close(clr)
2851 clr = nil
2852 }
2853
2854 // getServerListener returns a network listener for the given host-port address.
2855 // If the Server already has an active listener (s.listener), it returns that listener
2856 // along with any previous error (s.listenerErr). Otherwise, it creates and returns
2857 // a new TCP listener on the specified address using natsListen.
2858 func (s *Server) getServerListener(hp string) (net.Listener, error) {
2859 if s.listener != nil {
2860 return s.listener, s.listenerErr
2861 }
2862
2863 return natsListen("tcp", hp)
2864 }
2865
2866 // InProcessConn returns an in-process connection to the server,
2867 // avoiding the need to use a TCP listener for local connectivity
2868 // within the same process. This can be used regardless of the
2869 // state of the DontListen option.
2870 func (s *Server) InProcessConn() (net.Conn, error) {
2871 pl, pr := net.Pipe()
2872 if !s.startGoRoutine(func() {
2873 s.createClientInProcess(pl)
2874 s.grWG.Done()
2875 }) {
2876 pl.Close()
2877 pr.Close()
2878 return nil, fmt.Errorf("failed to create connection")
2879 }
2880 return pr, nil
2881 }
2882
2883 func (s *Server) acceptConnections(l net.Listener, acceptName string, createFunc func(conn net.Conn), errFunc func(err error) bool) {
2884 tmpDelay := ACCEPT_MIN_SLEEP
2885
2886 for {
2887 conn, err := l.Accept()
2888 if err != nil {
2889 if errFunc != nil && errFunc(err) {
2890 return
2891 }
2892 if tmpDelay = s.acceptError(acceptName, err, tmpDelay); tmpDelay < 0 {
2893 break
2894 }
2895 continue
2896 }
2897 tmpDelay = ACCEPT_MIN_SLEEP
2898 if !s.startGoRoutine(func() {
2899 s.reloadMu.RLock()
2900 createFunc(conn)
2901 s.reloadMu.RUnlock()
2902 s.grWG.Done()
2903 }) {
2904 conn.Close()
2905 }
2906 }
2907 s.Debugf(acceptName + " accept loop exiting..")
2908 s.done <- true
2909 }
2910
2911 // This function sets the server's info Host/Port based on server Options.
2912 // Note that this function may be called during config reload, this is why
2913 // Host/Port may be reset to original Options if the ClientAdvertise option
2914 // is not set (since it may have previously been).
2915 func (s *Server) setInfoHostPort() error {
2916 // When this function is called, opts.Port is set to the actual listen
2917 // port (if option was originally set to RANDOM), even during a config
2918 // reload. So use of s.opts.Port is safe.
2919 opts := s.getOpts()
2920 if opts.ClientAdvertise != _EMPTY_ {
2921 h, p, err := parseHostPort(opts.ClientAdvertise, opts.Port)
2922 if err != nil {
2923 return err
2924 }
2925 s.info.Host = h
2926 s.info.Port = p
2927 } else {
2928 s.info.Host = opts.Host
2929 s.info.Port = opts.Port
2930 }
2931 return nil
2932 }
2933
2934 // StartProfiler is called to enable dynamic profiling.
2935 func (s *Server) StartProfiler() {
2936 if s.isShuttingDown() {
2937 return
2938 }
2939
2940 // Snapshot server options.
2941 opts := s.getOpts()
2942
2943 port := opts.ProfPort
2944
2945 // Check for Random Port
2946 if port == -1 {
2947 port = 0
2948 }
2949
2950 s.mu.Lock()
2951 hp := net.JoinHostPort(opts.Host, strconv.Itoa(port))
2952 l, err := net.Listen("tcp", hp)
2953
2954 if err != nil {
2955 s.mu.Unlock()
2956 s.Fatalf("error starting profiler: %s", err)
2957 return
2958 }
2959 s.Noticef("profiling port: %d", l.Addr().(*net.TCPAddr).Port)
2960
2961 srv := &http.Server{
2962 Addr: hp,
2963 Handler: http.DefaultServeMux,
2964 MaxHeaderBytes: 1 << 20,
2965 ReadTimeout: time.Second * 5,
2966 }
2967 s.profiler = l
2968 s.profilingServer = srv
2969
2970 s.setBlockProfileRate(opts.ProfBlockRate)
2971
2972 go func() {
2973 // if this errors out, it's probably because the server is being shutdown
2974 err := srv.Serve(l)
2975 if err != nil {
2976 if !s.isShuttingDown() {
2977 s.Fatalf("error starting profiler: %s", err)
2978 }
2979 }
2980 srv.Close()
2981 s.done <- true
2982 }()
2983 s.mu.Unlock()
2984 }
2985
2986 func (s *Server) setBlockProfileRate(rate int) {
2987 // Passing i ProfBlockRate <= 0 here will disable or > 0 will enable.
2988 runtime.SetBlockProfileRate(rate)
2989
2990 if rate > 0 {
2991 s.Warnf("Block profiling is enabled (rate %d), this may have a performance impact", rate)
2992 }
2993 }
2994
2995 // StartHTTPMonitoring will enable the HTTP monitoring port.
2996 // DEPRECATED: Should use StartMonitoring.
2997 func (s *Server) StartHTTPMonitoring() {
2998 s.startMonitoring(false)
2999 }
3000
3001 // StartHTTPSMonitoring will enable the HTTPS monitoring port.
3002 // DEPRECATED: Should use StartMonitoring.
3003 func (s *Server) StartHTTPSMonitoring() {
3004 s.startMonitoring(true)
3005 }
3006
3007 // StartMonitoring starts the HTTP or HTTPs server if needed.
3008 func (s *Server) StartMonitoring() error {
3009 // Snapshot server options.
3010 opts := s.getOpts()
3011
3012 // Specifying both HTTP and HTTPS ports is a misconfiguration
3013 if opts.HTTPPort != 0 && opts.HTTPSPort != 0 {
3014 return fmt.Errorf("can't specify both HTTP (%v) and HTTPs (%v) ports", opts.HTTPPort, opts.HTTPSPort)
3015 }
3016 var err error
3017 if opts.HTTPPort != 0 {
3018 err = s.startMonitoring(false)
3019 } else if opts.HTTPSPort != 0 {
3020 if opts.TLSConfig == nil {
3021 return fmt.Errorf("TLS cert and key required for HTTPS")
3022 }
3023 err = s.startMonitoring(true)
3024 }
3025 return err
3026 }
3027
3028 // HTTP endpoints
3029 const (
3030 RootPath = "/"
3031 VarzPath = "/varz"
3032 ConnzPath = "/connz"
3033 RoutezPath = "/routez"
3034 GatewayzPath = "/gatewayz"
3035 LeafzPath = "/leafz"
3036 SubszPath = "/subsz"
3037 StackszPath = "/stacksz"
3038 AccountzPath = "/accountz"
3039 AccountStatzPath = "/accstatz"
3040 JszPath = "/jsz"
3041 HealthzPath = "/healthz"
3042 IPQueuesPath = "/ipqueuesz"
3043 RaftzPath = "/raftz"
3044 ExpvarzPath = "/debug/vars"
3045 )
3046
3047 func (s *Server) basePath(p string) string {
3048 return path.Join(s.httpBasePath, p)
3049 }
3050
3051 type captureHTTPServerLog struct {
3052 s *Server
3053 prefix string
3054 }
3055
3056 func (cl *captureHTTPServerLog) Write(p []byte) (int, error) {
3057 var buf [128]byte
3058 var b = buf[:0]
3059
3060 b = append(b, []byte(cl.prefix)...)
3061 offset := 0
3062 if bytes.HasPrefix(p, []byte("http:")) {
3063 offset = 6
3064 }
3065 b = append(b, p[offset:]...)
3066 cl.s.Errorf(string(b))
3067 return len(p), nil
3068 }
3069
3070 // The TLS configuration is passed to the listener when the monitoring
3071 // "server" is setup. That prevents TLS configuration updates on reload
3072 // from being used. By setting this function in tls.Config.GetConfigForClient
3073 // we instruct the TLS handshake to ask for the tls configuration to be
3074 // used for a specific client. We don't care which client, we always use
3075 // the same TLS configuration.
3076 func (s *Server) getMonitoringTLSConfig(_ *tls.ClientHelloInfo) (*tls.Config, error) {
3077 opts := s.getOpts()
3078 tc := opts.TLSConfig.Clone()
3079 tc.ClientAuth = tls.NoClientCert
3080 return tc, nil
3081 }
3082
3083 // Start the monitoring server
3084 func (s *Server) startMonitoring(secure bool) error {
3085 if s.isShuttingDown() {
3086 return nil
3087 }
3088
3089 // Snapshot server options.
3090 opts := s.getOpts()
3091
3092 var (
3093 hp string
3094 err error
3095 httpListener net.Listener
3096 port int
3097 )
3098
3099 monitorProtocol := "http"
3100
3101 if secure {
3102 monitorProtocol += "s"
3103 port = opts.HTTPSPort
3104 if port == -1 {
3105 port = 0
3106 }
3107 hp = net.JoinHostPort(opts.HTTPHost, strconv.Itoa(port))
3108 config := opts.TLSConfig.Clone()
3109 if !s.ocspPeerVerify {
3110 config.GetConfigForClient = s.getMonitoringTLSConfig
3111 config.ClientAuth = tls.NoClientCert
3112 }
3113 httpListener, err = tls.Listen("tcp", hp, config)
3114
3115 } else {
3116 port = opts.HTTPPort
3117 if port == -1 {
3118 port = 0
3119 }
3120 hp = net.JoinHostPort(opts.HTTPHost, strconv.Itoa(port))
3121 httpListener, err = net.Listen("tcp", hp)
3122 }
3123
3124 if err != nil {
3125 return fmt.Errorf("can't listen to the monitor port: %v", err)
3126 }
3127
3128 rport := httpListener.Addr().(*net.TCPAddr).Port
3129 s.Noticef("Starting %s monitor on %s", monitorProtocol, net.JoinHostPort(opts.HTTPHost, strconv.Itoa(rport)))
3130
3131 mux := http.NewServeMux()
3132
3133 // Root
3134 mux.HandleFunc(s.basePath(RootPath), s.HandleRoot)
3135 // Varz
3136 mux.HandleFunc(s.basePath(VarzPath), s.HandleVarz)
3137 // Connz
3138 mux.HandleFunc(s.basePath(ConnzPath), s.HandleConnz)
3139 // Routez
3140 mux.HandleFunc(s.basePath(RoutezPath), s.HandleRoutez)
3141 // Gatewayz
3142 mux.HandleFunc(s.basePath(GatewayzPath), s.HandleGatewayz)
3143 // Leafz
3144 mux.HandleFunc(s.basePath(LeafzPath), s.HandleLeafz)
3145 // Subz
3146 mux.HandleFunc(s.basePath(SubszPath), s.HandleSubsz)
3147 // Subz alias for backwards compatibility
3148 mux.HandleFunc(s.basePath("/subscriptionsz"), s.HandleSubsz)
3149 // Stacksz
3150 mux.HandleFunc(s.basePath(StackszPath), s.HandleStacksz)
3151 // Accountz
3152 mux.HandleFunc(s.basePath(AccountzPath), s.HandleAccountz)
3153 // Accstatz
3154 mux.HandleFunc(s.basePath(AccountStatzPath), s.HandleAccountStatz)
3155 // Jsz
3156 mux.HandleFunc(s.basePath(JszPath), s.HandleJsz)
3157 // Healthz
3158 mux.HandleFunc(s.basePath(HealthzPath), s.HandleHealthz)
3159 // IPQueuesz
3160 mux.HandleFunc(s.basePath(IPQueuesPath), s.HandleIPQueuesz)
3161 // Raftz
3162 mux.HandleFunc(s.basePath(RaftzPath), s.HandleRaftz)
3163 // Expvarz
3164 mux.Handle(s.basePath(ExpvarzPath), expvar.Handler())
3165
3166 // Do not set a WriteTimeout because it could cause cURL/browser
3167 // to return empty response or unable to display page if the
3168 // server needs more time to build the response.
3169 srv := &http.Server{
3170 Addr: hp,
3171 Handler: mux,
3172 MaxHeaderBytes: 1 << 20,
3173 ErrorLog: log.New(&captureHTTPServerLog{s, "monitoring: "}, _EMPTY_, 0),
3174 ReadHeaderTimeout: time.Second * 5,
3175 }
3176 s.mu.Lock()
3177 s.http = httpListener
3178 s.httpHandler = mux
3179 s.monitoringServer = srv
3180 s.mu.Unlock()
3181
3182 go func() {
3183 if err := srv.Serve(httpListener); err != nil {
3184 if !s.isShuttingDown() {
3185 s.Fatalf("Error starting monitor on %q: %v", hp, err)
3186 }
3187 }
3188 srv.Close()
3189 s.mu.Lock()
3190 s.httpHandler = nil
3191 s.mu.Unlock()
3192 s.done <- true
3193 }()
3194
3195 return nil
3196 }
3197
3198 // HTTPHandler returns the http.Handler object used to handle monitoring
3199 // endpoints. It will return nil if the server is not configured for
3200 // monitoring, or if the server has not been started yet (Server.Start()).
3201 func (s *Server) HTTPHandler() http.Handler {
3202 s.mu.Lock()
3203 defer s.mu.Unlock()
3204 return s.httpHandler
3205 }
3206
3207 // Perform a conditional deep copy due to reference nature of [Client|WS]ConnectURLs.
3208 // If updates are made to Info, this function should be consulted and updated.
3209 // Assume lock is held.
3210 func (s *Server) copyInfo() Info {
3211 info := s.info
3212 if len(info.ClientConnectURLs) > 0 {
3213 info.ClientConnectURLs = append([]string(nil), s.info.ClientConnectURLs...)
3214 }
3215 if len(info.WSConnectURLs) > 0 {
3216 info.WSConnectURLs = append([]string(nil), s.info.WSConnectURLs...)
3217 }
3218 return info
3219 }
3220
3221 // tlsMixConn is used when we can receive both TLS and non-TLS connections on same port.
3222 type tlsMixConn struct {
3223 net.Conn
3224 pre *bytes.Buffer
3225 }
3226
3227 // Read for our mixed multi-reader.
3228 func (c *tlsMixConn) Read(b []byte) (int, error) {
3229 if c.pre != nil {
3230 n, err := c.pre.Read(b)
3231 if c.pre.Len() == 0 {
3232 c.pre = nil
3233 }
3234 return n, err
3235 }
3236 return c.Conn.Read(b)
3237 }
3238
3239 func (s *Server) createClient(conn net.Conn) *client {
3240 return s.createClientEx(conn, false)
3241 }
3242
3243 func (s *Server) createClientInProcess(conn net.Conn) *client {
3244 return s.createClientEx(conn, true)
3245 }
3246
3247 func (s *Server) createClientEx(conn net.Conn, inProcess bool) *client {
3248 // Snapshot server options.
3249 opts := s.getOpts()
3250
3251 maxPay := int32(opts.MaxPayload)
3252 maxSubs := int32(opts.MaxSubs)
3253 // For system, maxSubs of 0 means unlimited, so re-adjust here.
3254 if maxSubs == 0 {
3255 maxSubs = -1
3256 }
3257 now := time.Now()
3258
3259 c := &client{
3260 srv: s,
3261 nc: conn,
3262 opts: defaultOpts,
3263 mpay: maxPay,
3264 msubs: maxSubs,
3265 start: now,
3266 last: now,
3267 iproc: inProcess,
3268 }
3269
3270 c.registerWithAccount(s.globalAccount())
3271
3272 var info Info
3273 var authRequired bool
3274
3275 s.mu.Lock()
3276 // Grab JSON info string
3277 info = s.copyInfo()
3278 if s.nonceRequired() {
3279 // Nonce handling
3280 var raw [nonceLen]byte
3281 nonce := raw[:]
3282 s.generateNonce(nonce)
3283 info.Nonce = string(nonce)
3284 }
3285 c.nonce = []byte(info.Nonce)
3286 authRequired = info.AuthRequired
3287
3288 // Check to see if we have auth_required set but we also have a no_auth_user.
3289 // If so set back to false.
3290 if info.AuthRequired && opts.NoAuthUser != _EMPTY_ && opts.NoAuthUser != s.sysAccOnlyNoAuthUser {
3291 info.AuthRequired = false
3292 }
3293
3294 // Check to see if this is an in-process connection with tls_required.
3295 // If so, set as not required, but available.
3296 if inProcess && info.TLSRequired {
3297 info.TLSRequired = false
3298 info.TLSAvailable = true
3299 }
3300
3301 s.totalClients++
3302 s.mu.Unlock()
3303
3304 // Grab lock
3305 c.mu.Lock()
3306 if authRequired {
3307 c.flags.set(expectConnect)
3308 }
3309
3310 // Initialize
3311 c.initClient()
3312
3313 c.Debugf("Client connection created")
3314
3315 // Save info.TLSRequired value since we may neeed to change it back and forth.
3316 orgInfoTLSReq := info.TLSRequired
3317
3318 var tlsFirstFallback time.Duration
3319 // Check if we should do TLS first.
3320 tlsFirst := opts.TLSConfig != nil && opts.TLSHandshakeFirst
3321 if tlsFirst {
3322 // Make sure info.TLSRequired is set to true (it could be false
3323 // if AllowNonTLS is enabled).
3324 info.TLSRequired = true
3325 // Get the fallback delay value if applicable.
3326 if f := opts.TLSHandshakeFirstFallback; f > 0 {
3327 tlsFirstFallback = f
3328 } else if inProcess {
3329 // For in-process connection, we will always have a fallback
3330 // delay. It allows support for non-TLS, TLS and "TLS First"
3331 // in-process clients to successfully connect.
3332 tlsFirstFallback = DEFAULT_TLS_HANDSHAKE_FIRST_FALLBACK_DELAY
3333 }
3334 }
3335
3336 // Decide if we are going to require TLS or not and generate INFO json.
3337 // If we have ProxyProtocol enabled then we won't include the client
3338 // IP in the initial INFO, as that would leak the proxy IP itself.
3339 // In that case we'll send another INFO after the client introduces itself.
3340 tlsRequired := info.TLSRequired
3341 infoBytes := c.generateClientInfoJSON(info, !opts.ProxyProtocol)
3342
3343 // Send our information, except if TLS and TLSHandshakeFirst is requested.
3344 if !tlsFirst {
3345 // Need to be sent in place since writeLoop cannot be started until
3346 // TLS handshake is done (if applicable).
3347 c.sendProtoNow(infoBytes)
3348 }
3349
3350 // Unlock to register
3351 c.mu.Unlock()
3352
3353 // Register with the server.
3354 s.mu.Lock()
3355 // If server is not running, Shutdown() may have already gathered the
3356 // list of connections to close. It won't contain this one, so we need
3357 // to bail out now otherwise the readLoop started down there would not
3358 // be interrupted. Skip also if in lame duck mode.
3359 if !s.isRunning() || s.ldm {
3360 // There are some tests that create a server but don't start it,
3361 // and use "async" clients and perform the parsing manually. Such
3362 // clients would branch here (since server is not running). However,
3363 // when a server was really running and has been shutdown, we must
3364 // close this connection.
3365 if s.isShuttingDown() {
3366 conn.Close()
3367 }
3368 s.mu.Unlock()
3369 return c
3370 }
3371
3372 // If there is a max connections specified, check that adding
3373 // this new client would not push us over the max
3374 if opts.MaxConn < 0 || (opts.MaxConn > 0 && len(s.clients) >= opts.MaxConn) {
3375 s.mu.Unlock()
3376 c.maxConnExceeded()
3377 return nil
3378 }
3379 s.clients[c.cid] = c
3380
3381 s.mu.Unlock()
3382
3383 // Re-Grab lock
3384 c.mu.Lock()
3385
3386 isClosed := c.isClosed()
3387 var pre []byte
3388 // We need first to check for "TLS First" fallback delay.
3389 if !isClosed && tlsFirstFallback > 0 {
3390 // We wait and see if we are getting any data. Since we did not send
3391 // the INFO protocol yet, only clients that use TLS first should be
3392 // sending data (the TLS handshake). We don't really check the content:
3393 // if it is a rogue agent and not an actual client performing the
3394 // TLS handshake, the error will be detected when performing the
3395 // handshake on our side.
3396 pre = make([]byte, 4)
3397 c.nc.SetReadDeadline(time.Now().Add(tlsFirstFallback))
3398 n, _ := io.ReadFull(c.nc, pre[:])
3399 c.nc.SetReadDeadline(time.Time{})
3400 // If we get any data (regardless of possible timeout), we will proceed
3401 // with the TLS handshake.
3402 if n > 0 {
3403 pre = pre[:n]
3404 } else {
3405 // We did not get anything so we will send the INFO protocol.
3406 pre = nil
3407
3408 // Restore the original info.TLSRequired value if it is
3409 // different that the current value and regenerate infoBytes.
3410 if orgInfoTLSReq != info.TLSRequired {
3411 info.TLSRequired = orgInfoTLSReq
3412 infoBytes = c.generateClientInfoJSON(info, !opts.ProxyProtocol)
3413 }
3414 c.sendProtoNow(infoBytes)
3415 // Set the boolean to false for the rest of the function.
3416 tlsFirst = false
3417 // Check closed status again
3418 isClosed = c.isClosed()
3419 }
3420 }
3421 // If we have both TLS and non-TLS allowed we need to see which
3422 // one the client wants. We'll always allow this for in-process
3423 // connections.
3424 sniffTLS := !tlsFirst && opts.TLSConfig != nil && (inProcess || opts.AllowNonTLS)
3425 if !isClosed && sniffTLS {
3426 pre = make([]byte, 6) // Minimum 6 bytes for proxy proto in next step.
3427 c.nc.SetReadDeadline(time.Now().Add(secondsToDuration(opts.TLSTimeout)))
3428 n, _ := io.ReadFull(c.nc, pre[:])
3429 c.nc.SetReadDeadline(time.Time{})
3430 pre = pre[:n]
3431 tlsRequired = n > 0 && pre[0] == 0x16
3432 }
3433
3434 // Check for proxy protocol if enabled. The PROXY header is sent as
3435 // plaintext before any TLS handshake per the spec, so we must read it
3436 // before doing TLS even when TLS is required. Any bytes read past the
3437 // header are kept in `pre` and replayed into the TLS handshake (or the
3438 // non-TLS protocol parser) by the tlsMixConn wrapper used below.
3439 if !isClosed && opts.ProxyProtocol {
3440 if len(pre) == 0 {
3441 // There has been no pre-read yet, do so so we can work out
3442 // if the client is trying to negotiate PROXY.
3443 pre = make([]byte, 6)
3444 c.nc.SetReadDeadline(time.Now().Add(proxyProtoReadTimeout))
3445 n, _ := io.ReadFull(c.nc, pre)
3446 c.nc.SetReadDeadline(time.Time{})
3447 pre = pre[:n]
3448 }
3449 conn = &tlsMixConn{conn, bytes.NewBuffer(pre)}
3450 addr, proxyPre, err := readProxyProtoHeader(conn)
3451 if err != nil && err != errProxyProtoUnrecognized {
3452 // err != errProxyProtoUnrecognized implies that we detected a proxy
3453 // protocol header but we failed to parse it, so don't continue.
3454 c.mu.Unlock()
3455 s.Warnf("Error reading PROXY protocol header from %s: %v", conn.RemoteAddr(), err)
3456 c.closeConnection(ProtocolViolation)
3457 return nil
3458 }
3459 // If addr is nil, it was a LOCAL/UNKNOWN command (health check)
3460 // Use the connection as-is
3461 if addr != nil {
3462 c.nc = &proxyConn{
3463 Conn: conn,
3464 remoteAddr: addr,
3465 }
3466 // These were set already by initClient, override them.
3467 c.host = addr.srcIP.String()
3468 c.port = addr.srcPort
3469 }
3470 // At this point, err is either:
3471 // - nil => we parsed the proxy protocol header successfully and
3472 // proxyPre holds any bytes read past the header
3473 // - errProxyProtoUnrecognized => we didn't detect proxy protocol at
3474 // all and proxyPre holds the bytes that detection consumed (which
3475 // may include bytes read directly from the socket beyond the
3476 // original pre-read), so they must be replayed to the next step.
3477 pre = proxyPre
3478 if err == nil && sniffTLS {
3479 // If we sniffed for TLS-vs-plaintext above, the byte we looked
3480 // at belonged to the PROXY header, not to the client's actual
3481 // traffic. Re-evaluate using the first byte that follows the
3482 // header (reading it from the connection if needed).
3483 if len(pre) == 0 {
3484 buf := make([]byte, 1)
3485 c.nc.SetReadDeadline(time.Now().Add(secondsToDuration(opts.TLSTimeout)))
3486 n, _ := io.ReadFull(c.nc, buf)
3487 c.nc.SetReadDeadline(time.Time{})
3488 pre = buf[:n]
3489 }
3490 tlsRequired = len(pre) > 0 && pre[0] == 0x16
3491 }
3492 // Because we have ProxyProtocol enabled, our earlier INFO message didn't
3493 // include the client_ip. If we need to send it again then we will include
3494 // it, but sending it here immediately can confuse clients who have just
3495 // PING'd.
3496 infoBytes = c.generateClientInfoJSON(info, true)
3497 }
3498
3499 // Check for TLS
3500 if !isClosed && tlsRequired {
3501 if s.connRateCounter != nil && !s.connRateCounter.allow() {
3502 c.mu.Unlock()
3503 c.sendErr("Connection throttling is active. Please try again later.")
3504 c.closeConnection(MaxConnectionsExceeded)
3505 return nil
3506 }
3507
3508 // If we have a prebuffer create a multi-reader.
3509 if len(pre) > 0 {
3510 c.nc = &tlsMixConn{c.nc, bytes.NewBuffer(pre)}
3511 // Clear pre so it is not parsed.
3512 pre = nil
3513 }
3514 // Performs server-side TLS handshake.
3515 if err := c.doTLSServerHandshake(_EMPTY_, opts.TLSConfig, opts.TLSTimeout, opts.TLSPinnedCerts); err != nil {
3516 c.mu.Unlock()
3517 return nil
3518 }
3519 }
3520
3521 // Now, send the INFO if it was delayed
3522 if !isClosed && tlsFirst {
3523 c.flags.set(didTLSFirst)
3524 c.sendProtoNow(infoBytes)
3525 // Check closed status
3526 isClosed = c.isClosed()
3527 }
3528
3529 // Connection could have been closed while sending the INFO proto.
3530 if isClosed {
3531 c.mu.Unlock()
3532 // We need to call closeConnection() to make sure that proper cleanup is done.
3533 c.closeConnection(WriteError)
3534 return nil
3535 }
3536
3537 // Check for Auth. We schedule this timer after the TLS handshake to avoid
3538 // the race where the timer fires during the handshake and causes the
3539 // server to write bad data to the socket. See issue #432.
3540 if authRequired {
3541 c.setAuthTimer(secondsToDuration(opts.AuthTimeout))
3542 }
3543
3544 // Do final client initialization
3545
3546 // Set the Ping timer. Will be reset once connect was received.
3547 c.setPingTimer()
3548
3549 // Spin up the read loop.
3550 s.startGoRoutine(func() { c.readLoop(pre) })
3551
3552 // Spin up the write loop.
3553 s.startGoRoutine(func() { c.writeLoop() })
3554
3555 if tlsRequired {
3556 c.Debugf("TLS handshake complete")
3557 cs := c.nc.(*tls.Conn).ConnectionState()
3558 c.Debugf("TLS version %s, cipher suite %s", tlsVersion(cs.Version), tls.CipherSuiteName(cs.CipherSuite))
3559 }
3560
3561 c.mu.Unlock()
3562
3563 return c
3564 }
3565
3566 // This will save off a closed client in a ring buffer such that
3567 // /connz can inspect. Useful for debugging, etc.
3568 func (s *Server) saveClosedClient(c *client, nc net.Conn, subs map[string]*subscription, reason ClosedState) {
3569 now := time.Now()
3570
3571 s.accountDisconnectEvent(c, now, reason.String())
3572
3573 c.mu.Lock()
3574
3575 cc := &closedClient{}
3576 cc.fill(c, nc, now, false)
3577 // Note that cc.fill is using len(c.subs), which may have been set to nil by now,
3578 // so replace cc.NumSubs with len(subs).
3579 cc.NumSubs = uint32(len(subs))
3580 cc.Stop = &now
3581 cc.Reason = reason.String()
3582
3583 // Do subs, do not place by default in main ConnInfo
3584 if len(subs) > 0 {
3585 cc.subs = make([]SubDetail, 0, len(subs))
3586 for _, sub := range subs {
3587 cc.subs = append(cc.subs, newSubDetail(sub))
3588 }
3589 }
3590 // Hold user as well.
3591 cc.user = c.getRawAuthUser()
3592 // Hold account name if not the global account.
3593 if c.acc != nil && c.acc.Name != globalAccountName {
3594 cc.acc = c.acc.Name
3595 }
3596 cc.JWT = redactBearerJWT(c.opts.JWT)
3597 cc.IssuerKey = issuerForClient(c)
3598 cc.Tags = c.tags
3599 cc.NameTag = c.nameTag
3600 c.mu.Unlock()
3601
3602 // Place in the ring buffer
3603 s.mu.Lock()
3604 if s.closed != nil {
3605 s.closed.append(cc)
3606 }
3607 s.mu.Unlock()
3608 }
3609
3610 // Adds to the list of client and websocket clients connect URLs.
3611 // If there was a change, an INFO protocol is sent to registered clients
3612 // that support async INFO protocols.
3613 // Server lock held on entry.
3614 func (s *Server) addConnectURLsAndSendINFOToClients(curls, wsurls []string) {
3615 s.updateServerINFOAndSendINFOToClients(curls, wsurls, true)
3616 }
3617
3618 // Removes from the list of client and websocket clients connect URLs.
3619 // If there was a change, an INFO protocol is sent to registered clients
3620 // that support async INFO protocols.
3621 // Server lock held on entry.
3622 func (s *Server) removeConnectURLsAndSendINFOToClients(curls, wsurls []string) {
3623 s.updateServerINFOAndSendINFOToClients(curls, wsurls, false)
3624 }
3625
3626 // Updates the list of client and websocket clients connect URLs and if any change
3627 // sends an async INFO update to clients that support it.
3628 // Server lock held on entry.
3629 func (s *Server) updateServerINFOAndSendINFOToClients(curls, wsurls []string, add bool) {
3630 remove := !add
3631 // Will return true if we need alter the server's Info object.
3632 updateMap := func(urls []string, m refCountedUrlSet) bool {
3633 wasUpdated := false
3634 for _, url := range urls {
3635 if add && m.addUrl(url) {
3636 wasUpdated = true
3637 } else if remove && m.removeUrl(url) {
3638 wasUpdated = true
3639 }
3640 }
3641 return wasUpdated
3642 }
3643 cliUpdated := updateMap(curls, s.clientConnectURLsMap)
3644 wsUpdated := updateMap(wsurls, s.websocket.connectURLsMap)
3645
3646 updateInfo := func(infoURLs *[]string, urls []string, m refCountedUrlSet) {
3647 // Recreate the info's slice from the map
3648 *infoURLs = (*infoURLs)[:0]
3649 // Add this server client connect ULRs first...
3650 *infoURLs = append(*infoURLs, urls...)
3651 // Then the ones from the map
3652 for url := range m {
3653 *infoURLs = append(*infoURLs, url)
3654 }
3655 }
3656 if cliUpdated {
3657 updateInfo(&s.info.ClientConnectURLs, s.clientConnectURLs, s.clientConnectURLsMap)
3658 }
3659 if wsUpdated {
3660 updateInfo(&s.info.WSConnectURLs, s.websocket.connectURLs, s.websocket.connectURLsMap)
3661 }
3662 if cliUpdated || wsUpdated {
3663 // Send to all registered clients that support async INFO protocols.
3664 s.sendAsyncInfoToClients(cliUpdated, wsUpdated)
3665 }
3666 }
3667
3668 // Handle closing down a connection when the handshake has timedout.
3669 func tlsTimeout(c *client, conn *tls.Conn) {
3670 c.mu.Lock()
3671 closed := c.isClosed()
3672 c.mu.Unlock()
3673 // Check if already closed
3674 if closed {
3675 return
3676 }
3677 cs := conn.ConnectionState()
3678 if !cs.HandshakeComplete {
3679 if c.kind == CLIENT || c.kind == LEAF {
3680 c.Debugf("TLS handshake timeout")
3681 } else {
3682 c.Errorf("TLS handshake timeout")
3683 }
3684 c.sendErr("Secure Connection - TLS Required")
3685 c.closeConnection(TLSHandshakeError)
3686 }
3687 }
3688
3689 // Seems silly we have to write these
3690 func tlsVersion(ver uint16) string {
3691 switch ver {
3692 case tls.VersionTLS10:
3693 return "1.0"
3694 case tls.VersionTLS11:
3695 return "1.1"
3696 case tls.VersionTLS12:
3697 return "1.2"
3698 case tls.VersionTLS13:
3699 return "1.3"
3700 }
3701 return fmt.Sprintf("Unknown [0x%x]", ver)
3702 }
3703
3704 func tlsVersionFromString(ver string) (uint16, error) {
3705 switch ver {
3706 case "1.0":
3707 return tls.VersionTLS10, nil
3708 case "1.1":
3709 return tls.VersionTLS11, nil
3710 case "1.2":
3711 return tls.VersionTLS12, nil
3712 case "1.3":
3713 return tls.VersionTLS13, nil
3714 }
3715 return 0, fmt.Errorf("unknown version: %v", ver)
3716 }
3717
3718 // Remove a client or route from our internal accounting.
3719 func (s *Server) removeClient(c *client) {
3720 // kind is immutable, so can check without lock
3721 switch c.kind {
3722 case CLIENT:
3723 c.mu.Lock()
3724 cid := c.cid
3725 updateProtoInfoCount := false
3726 if c.kind == CLIENT && c.opts.Protocol >= ClientProtoInfo {
3727 updateProtoInfoCount = true
3728 }
3729 proxyKey := c.proxyKey
3730 c.mu.Unlock()
3731
3732 s.mu.Lock()
3733 delete(s.clients, cid)
3734 if updateProtoInfoCount {
3735 s.cproto--
3736 }
3737 if proxyKey != _EMPTY_ {
3738 s.removeProxiedConn(proxyKey, cid)
3739 }
3740 s.mu.Unlock()
3741 case ROUTER:
3742 s.removeRoute(c)
3743 case GATEWAY:
3744 s.removeRemoteGatewayConnection(c)
3745 case LEAF:
3746 s.removeLeafNodeConnection(c)
3747 }
3748 }
3749
3750 // Remove the connection with id `cid` from the map of connections
3751 // under the public key `key` of the trusted proxies.
3752 //
3753 // Server lock must be held on entry.
3754 func (s *Server) removeProxiedConn(key string, cid uint64) {
3755 conns := s.proxiedConns[key]
3756 delete(conns, cid)
3757 if len(conns) == 0 {
3758 delete(s.proxiedConns, key)
3759 }
3760 }
3761
3762 func (s *Server) removeFromTempClients(cid uint64) {
3763 s.grMu.Lock()
3764 delete(s.grTmpClients, cid)
3765 s.grMu.Unlock()
3766 }
3767
3768 func (s *Server) addToTempClients(cid uint64, c *client) bool {
3769 added := false
3770 s.grMu.Lock()
3771 if s.grRunning {
3772 s.grTmpClients[cid] = c
3773 added = true
3774 }
3775 s.grMu.Unlock()
3776 return added
3777 }
3778
3779 /////////////////////////////////////////////////////////////////
3780 // These are some helpers for accounting in functional tests.
3781 /////////////////////////////////////////////////////////////////
3782
3783 // NumRoutes will report the number of registered routes.
3784 func (s *Server) NumRoutes() int {
3785 s.mu.RLock()
3786 defer s.mu.RUnlock()
3787 return s.numRoutes()
3788 }
3789
3790 // numRoutes will report the number of registered routes.
3791 // Server lock held on entry
3792 func (s *Server) numRoutes() int {
3793 var nr int
3794 s.forEachRoute(func(c *client) {
3795 nr++
3796 })
3797 return nr
3798 }
3799
3800 // NumRemotes will report number of registered remotes.
3801 func (s *Server) NumRemotes() int {
3802 s.mu.RLock()
3803 defer s.mu.RUnlock()
3804 return s.numRemotes()
3805 }
3806
3807 // numRemotes will report number of registered remotes.
3808 // Server lock held on entry
3809 func (s *Server) numRemotes() int {
3810 return len(s.routes)
3811 }
3812
3813 // NumLeafNodes will report number of leaf node connections.
3814 func (s *Server) NumLeafNodes() int {
3815 s.mu.RLock()
3816 defer s.mu.RUnlock()
3817 return len(s.leafs)
3818 }
3819
3820 // NumClients will report the number of registered clients.
3821 func (s *Server) NumClients() int {
3822 s.mu.RLock()
3823 defer s.mu.RUnlock()
3824 return len(s.clients)
3825 }
3826
3827 // GetClient will return the client associated with cid.
3828 func (s *Server) GetClient(cid uint64) *client {
3829 return s.getClient(cid)
3830 }
3831
3832 // getClient will return the client associated with cid.
3833 func (s *Server) getClient(cid uint64) *client {
3834 s.mu.RLock()
3835 defer s.mu.RUnlock()
3836 return s.clients[cid]
3837 }
3838
3839 // GetLeafNode returns the leafnode associated with the cid.
3840 func (s *Server) GetLeafNode(cid uint64) *client {
3841 s.mu.RLock()
3842 defer s.mu.RUnlock()
3843 return s.leafs[cid]
3844 }
3845
3846 // NumSubscriptions will report how many subscriptions are active.
3847 func (s *Server) NumSubscriptions() uint32 {
3848 s.mu.RLock()
3849 defer s.mu.RUnlock()
3850 return s.numSubscriptions()
3851 }
3852
3853 // numSubscriptions will report how many subscriptions are active.
3854 // Lock should be held.
3855 func (s *Server) numSubscriptions() uint32 {
3856 var subs int
3857 s.accounts.Range(func(k, v any) bool {
3858 acc := v.(*Account)
3859 subs += acc.TotalSubs()
3860 return true
3861 })
3862 return uint32(subs)
3863 }
3864
3865 // NumSlowConsumers will report the number of slow consumers.
3866 func (s *Server) NumSlowConsumers() int64 {
3867 return atomic.LoadInt64(&s.slowConsumers)
3868 }
3869
3870 // NumStalledClients will report the total number of times clients have been stalled.
3871 func (s *Server) NumStalledClients() int64 {
3872 return atomic.LoadInt64(&s.stalls)
3873 }
3874
3875 // NumSlowConsumersClients will report the number of slow consumers clients.
3876 func (s *Server) NumSlowConsumersClients() uint64 {
3877 return s.scStats.clients.Load()
3878 }
3879
3880 // NumSlowConsumersRoutes will report the number of slow consumers routes.
3881 func (s *Server) NumSlowConsumersRoutes() uint64 {
3882 return s.scStats.routes.Load()
3883 }
3884
3885 // NumSlowConsumersGateways will report the number of slow consumers leafs.
3886 func (s *Server) NumSlowConsumersGateways() uint64 {
3887 return s.scStats.gateways.Load()
3888 }
3889
3890 // NumSlowConsumersLeafs will report the number of slow consumers leafs.
3891 func (s *Server) NumSlowConsumersLeafs() uint64 {
3892 return s.scStats.leafs.Load()
3893 }
3894
3895 // NumStaleConnections will report the number of stale connections.
3896 func (s *Server) NumStaleConnections() int64 {
3897 return atomic.LoadInt64(&s.staleConnections)
3898 }
3899
3900 // NumStaleConnectionsClients will report the number of stale client connections.
3901 func (s *Server) NumStaleConnectionsClients() uint64 {
3902 return s.staleStats.clients.Load()
3903 }
3904
3905 // NumStaleConnectionsRoutes will report the number of stale route connections.
3906 func (s *Server) NumStaleConnectionsRoutes() uint64 {
3907 return s.staleStats.routes.Load()
3908 }
3909
3910 // NumStaleConnectionsGateways will report the number of stale gateway connections.
3911 func (s *Server) NumStaleConnectionsGateways() uint64 {
3912 return s.staleStats.gateways.Load()
3913 }
3914
3915 // NumStaleConnectionsLeafs will report the number of stale leaf connections.
3916 func (s *Server) NumStaleConnectionsLeafs() uint64 {
3917 return s.staleStats.leafs.Load()
3918 }
3919
3920 // ConfigTime will report the last time the server configuration was loaded.
3921 func (s *Server) ConfigTime() time.Time {
3922 s.mu.RLock()
3923 defer s.mu.RUnlock()
3924 return s.configTime
3925 }
3926
3927 // Addr will return the net.Addr object for the current listener.
3928 func (s *Server) Addr() net.Addr {
3929 s.mu.RLock()
3930 defer s.mu.RUnlock()
3931 if s.listener == nil {
3932 return nil
3933 }
3934 return s.listener.Addr()
3935 }
3936
3937 // MonitorAddr will return the net.Addr object for the monitoring listener.
3938 func (s *Server) MonitorAddr() *net.TCPAddr {
3939 s.mu.RLock()
3940 defer s.mu.RUnlock()
3941 if s.http == nil {
3942 return nil
3943 }
3944 return s.http.Addr().(*net.TCPAddr)
3945 }
3946
3947 // ClusterAddr returns the net.Addr object for the route listener.
3948 func (s *Server) ClusterAddr() *net.TCPAddr {
3949 s.mu.RLock()
3950 defer s.mu.RUnlock()
3951 if s.routeListener == nil {
3952 return nil
3953 }
3954 return s.routeListener.Addr().(*net.TCPAddr)
3955 }
3956
3957 // ProfilerAddr returns the net.Addr object for the profiler listener.
3958 func (s *Server) ProfilerAddr() *net.TCPAddr {
3959 s.mu.RLock()
3960 defer s.mu.RUnlock()
3961 if s.profiler == nil {
3962 return nil
3963 }
3964 return s.profiler.Addr().(*net.TCPAddr)
3965 }
3966
3967 func (s *Server) readyForConnections(d time.Duration) error {
3968 // Snapshot server options.
3969 opts := s.getOpts()
3970
3971 type info struct {
3972 ok bool
3973 err error
3974 }
3975 chk := make(map[string]info)
3976
3977 end := time.Now().Add(d)
3978 for time.Now().Before(end) {
3979 s.mu.RLock()
3980 chk["server"] = info{ok: s.listener != nil || opts.DontListen, err: s.listenerErr}
3981 chk["route"] = info{ok: (opts.Cluster.Port == 0 || s.routeListener != nil), err: s.routeListenerErr}
3982 chk["gateway"] = info{ok: (opts.Gateway.Name == _EMPTY_ || s.gatewayListener != nil), err: s.gatewayListenerErr}
3983 chk["leafnode"] = info{ok: (opts.LeafNode.Port == 0 || s.leafNodeListener != nil), err: s.leafNodeListenerErr}
3984 chk["websocket"] = info{ok: (opts.Websocket.Port == 0 || s.websocket.listener != nil), err: s.websocket.listenerErr}
3985 chk["mqtt"] = info{ok: (opts.MQTT.Port == 0 || s.mqtt.listener != nil), err: s.mqtt.listenerErr}
3986 s.mu.RUnlock()
3987
3988 var numOK int
3989 for _, inf := range chk {
3990 if inf.ok {
3991 numOK++
3992 }
3993 }
3994 if numOK == len(chk) {
3995 // In the case of DontListen option (no accept loop), we still want
3996 // to make sure that Start() has done all the work, so we wait on
3997 // that.
3998 if opts.DontListen {
3999 select {
4000 case <-s.startupComplete:
4001 case <-time.After(d):
4002 return fmt.Errorf("failed to be ready for connections after %s: startup did not complete", d)
4003 }
4004 }
4005 return nil
4006 }
4007 if d > 25*time.Millisecond {
4008 time.Sleep(25 * time.Millisecond)
4009 }
4010 }
4011
4012 failed := make([]string, 0, len(chk))
4013 for name, inf := range chk {
4014 if inf.ok && inf.err != nil {
4015 failed = append(failed, fmt.Sprintf("%s(ok, but %s)", name, inf.err))
4016 }
4017 if !inf.ok && inf.err == nil {
4018 failed = append(failed, name)
4019 }
4020 if !inf.ok && inf.err != nil {
4021 failed = append(failed, fmt.Sprintf("%s(%s)", name, inf.err))
4022 }
4023 }
4024
4025 return fmt.Errorf(
4026 "failed to be ready for connections after %s: %s",
4027 d, strings.Join(failed, ", "),
4028 )
4029 }
4030
4031 // ReadyForConnections returns `true` if the server is ready to accept clients
4032 // and, if routing is enabled, route connections. If after the duration
4033 // `dur` the server is still not ready, returns `false`.
4034 func (s *Server) ReadyForConnections(dur time.Duration) bool {
4035 return s.readyForConnections(dur) == nil
4036 }
4037
4038 // Quick utility to function to tell if the server supports headers.
4039 func (s *Server) supportsHeaders() bool {
4040 if s == nil {
4041 return false
4042 }
4043 return !(s.getOpts().NoHeaderSupport)
4044 }
4045
4046 // ID returns the server's ID
4047 func (s *Server) ID() string {
4048 return s.info.ID
4049 }
4050
4051 // NodeName returns the node name for this server.
4052 func (s *Server) NodeName() string {
4053 return getHash(s.info.Name)
4054 }
4055
4056 // Name returns the server's name. This will be the same as the ID if it was not set.
4057 func (s *Server) Name() string {
4058 return s.info.Name
4059 }
4060
4061 func (s *Server) String() string {
4062 return s.info.Name
4063 }
4064
4065 type pprofLabels map[string]string
4066
4067 func setGoRoutineLabels(tags ...pprofLabels) {
4068 var labels []string
4069 for _, m := range tags {
4070 for k, v := range m {
4071 labels = append(labels, k, v)
4072 }
4073 }
4074 if len(labels) > 0 {
4075 pprof.SetGoroutineLabels(
4076 pprof.WithLabels(context.Background(), pprof.Labels(labels...)),
4077 )
4078 }
4079 }
4080
4081 func (s *Server) startGoRoutine(f func(), tags ...pprofLabels) bool {
4082 var started bool
4083 s.grMu.Lock()
4084 defer s.grMu.Unlock()
4085 if s.grRunning {
4086 s.grWG.Add(1)
4087 go func() {
4088 setGoRoutineLabels(tags...)
4089 f()
4090 }()
4091 started = true
4092 }
4093 return started
4094 }
4095
4096 func (s *Server) numClosedConns() int {
4097 s.mu.RLock()
4098 defer s.mu.RUnlock()
4099 return s.closed.len()
4100 }
4101
4102 func (s *Server) totalClosedConns() uint64 {
4103 s.mu.RLock()
4104 defer s.mu.RUnlock()
4105 return s.closed.totalConns()
4106 }
4107
4108 func (s *Server) closedClients() []*closedClient {
4109 s.mu.RLock()
4110 defer s.mu.RUnlock()
4111 return s.closed.closedClients()
4112 }
4113
4114 // getClientConnectURLs returns suitable URLs for clients to connect to the listen
4115 // port based on the server options' Host and Port. If the Host corresponds to
4116 // "any" interfaces, this call returns the list of resolved IP addresses.
4117 // If ClientAdvertise is set, returns the client advertise host and port.
4118 // The server lock is assumed held on entry.
4119 func (s *Server) getClientConnectURLs() []string {
4120 // Snapshot server options.
4121 opts := s.getOpts()
4122 // Ignore error here since we know that if there is client advertise, the
4123 // parseHostPort is correct because we did it right before calling this
4124 // function in Server.New().
4125 urls, _ := s.getConnectURLs(opts.ClientAdvertise, opts.Host, opts.Port)
4126 return urls
4127 }
4128
4129 // Generic version that will return an array of URLs based on the given
4130 // advertise, host and port values.
4131 func (s *Server) getConnectURLs(advertise, host string, port int) ([]string, error) {
4132 urls := make([]string, 0, 1)
4133
4134 // short circuit if advertise is set
4135 if advertise != "" {
4136 h, p, err := parseHostPort(advertise, port)
4137 if err != nil {
4138 return nil, err
4139 }
4140 urls = append(urls, net.JoinHostPort(h, strconv.Itoa(p)))
4141 } else {
4142 sPort := strconv.Itoa(port)
4143 _, ips, err := s.getNonLocalIPsIfHostIsIPAny(host, true)
4144 for _, ip := range ips {
4145 urls = append(urls, net.JoinHostPort(ip, sPort))
4146 }
4147 if err != nil || len(urls) == 0 {
4148 // We are here if s.opts.Host is not "0.0.0.0" nor "::", or if for some
4149 // reason we could not add any URL in the loop above.
4150 // We had a case where a Windows VM was hosed and would have err == nil
4151 // and not add any address in the array in the loop above, and we
4152 // ended-up returning 0.0.0.0, which is problematic for Windows clients.
4153 // Check for 0.0.0.0 or :: specifically, and ignore if that's the case.
4154 if host == "0.0.0.0" || host == "::" {
4155 s.Errorf("Address %q can not be resolved properly", host)
4156 } else {
4157 urls = append(urls, net.JoinHostPort(host, sPort))
4158 }
4159 }
4160 }
4161 return urls, nil
4162 }
4163
4164 // Returns an array of non local IPs if the provided host is
4165 // 0.0.0.0 or ::. It returns the first resolved if `all` is
4166 // false.
4167 // The boolean indicate if the provided host was 0.0.0.0 (or ::)
4168 // so that if the returned array is empty caller can decide
4169 // what to do next.
4170 func (s *Server) getNonLocalIPsIfHostIsIPAny(host string, all bool) (bool, []string, error) {
4171 ip := net.ParseIP(host)
4172 // If this is not an IP, we are done
4173 if ip == nil {
4174 return false, nil, nil
4175 }
4176 // If this is not 0.0.0.0 or :: we have nothing to do.
4177 if !ip.IsUnspecified() {
4178 return false, nil, nil
4179 }
4180 s.Debugf("Get non local IPs for %q", host)
4181 var ips []string
4182 ifaces, _ := net.Interfaces()
4183 for _, i := range ifaces {
4184 addrs, _ := i.Addrs()
4185 for _, addr := range addrs {
4186 switch v := addr.(type) {
4187 case *net.IPNet:
4188 ip = v.IP
4189 case *net.IPAddr:
4190 ip = v.IP
4191 }
4192 ipStr := ip.String()
4193 // Skip non global unicast addresses
4194 if !ip.IsGlobalUnicast() || ip.IsUnspecified() {
4195 ip = nil
4196 continue
4197 }
4198 s.Debugf(" ip=%s", ipStr)
4199 ips = append(ips, ipStr)
4200 if !all {
4201 break
4202 }
4203 }
4204 }
4205 return true, ips, nil
4206 }
4207
4208 // if the ip is not specified, attempt to resolve it
4209 func resolveHostPorts(addr net.Listener) []string {
4210 hostPorts := make([]string, 0)
4211 hp := addr.Addr().(*net.TCPAddr)
4212 port := strconv.Itoa(hp.Port)
4213 if hp.IP.IsUnspecified() {
4214 var ip net.IP
4215 ifaces, _ := net.Interfaces()
4216 for _, i := range ifaces {
4217 addrs, _ := i.Addrs()
4218 for _, addr := range addrs {
4219 switch v := addr.(type) {
4220 case *net.IPNet:
4221 ip = v.IP
4222 hostPorts = append(hostPorts, net.JoinHostPort(ip.String(), port))
4223 case *net.IPAddr:
4224 ip = v.IP
4225 hostPorts = append(hostPorts, net.JoinHostPort(ip.String(), port))
4226 default:
4227 continue
4228 }
4229 }
4230 }
4231 } else {
4232 hostPorts = append(hostPorts, net.JoinHostPort(hp.IP.String(), port))
4233 }
4234 return hostPorts
4235 }
4236
4237 // format the address of a net.Listener with a protocol
4238 func formatURL(protocol string, addr net.Listener) []string {
4239 hostports := resolveHostPorts(addr)
4240 for i, hp := range hostports {
4241 hostports[i] = fmt.Sprintf("%s://%s", protocol, hp)
4242 }
4243 return hostports
4244 }
4245
4246 // Ports describes URLs that the server can be contacted in
4247 type Ports struct {
4248 Nats []string `json:"nats,omitempty"`
4249 Monitoring []string `json:"monitoring,omitempty"`
4250 Cluster []string `json:"cluster,omitempty"`
4251 Profile []string `json:"profile,omitempty"`
4252 WebSocket []string `json:"websocket,omitempty"`
4253 }
4254
4255 // PortsInfo attempts to resolve all the ports. If after maxWait the ports are not
4256 // resolved, it returns nil. Otherwise it returns a Ports struct
4257 // describing ports where the server can be contacted
4258 func (s *Server) PortsInfo(maxWait time.Duration) *Ports {
4259 if s.readyForListeners(maxWait) {
4260 opts := s.getOpts()
4261
4262 s.mu.RLock()
4263 tls := s.info.TLSRequired
4264 listener := s.listener
4265 httpListener := s.http
4266 clusterListener := s.routeListener
4267 profileListener := s.profiler
4268 wsListener := s.websocket.listener
4269 wss := s.websocket.tls
4270 s.mu.RUnlock()
4271
4272 ports := Ports{}
4273
4274 if listener != nil {
4275 natsProto := "nats"
4276 if tls {
4277 natsProto = "tls"
4278 }
4279 ports.Nats = formatURL(natsProto, listener)
4280 }
4281
4282 if httpListener != nil {
4283 monProto := "http"
4284 if opts.HTTPSPort != 0 {
4285 monProto = "https"
4286 }
4287 ports.Monitoring = formatURL(monProto, httpListener)
4288 }
4289
4290 if clusterListener != nil {
4291 clusterProto := "nats"
4292 if opts.Cluster.TLSConfig != nil {
4293 clusterProto = "tls"
4294 }
4295 ports.Cluster = formatURL(clusterProto, clusterListener)
4296 }
4297
4298 if profileListener != nil {
4299 ports.Profile = formatURL("http", profileListener)
4300 }
4301
4302 if wsListener != nil {
4303 protocol := wsSchemePrefix
4304 if wss {
4305 protocol = wsSchemePrefixTLS
4306 }
4307 ports.WebSocket = formatURL(protocol, wsListener)
4308 }
4309
4310 return &ports
4311 }
4312
4313 return nil
4314 }
4315
4316 // Returns the portsFile. If a non-empty dirHint is provided, the dirHint
4317 // path is used instead of the server option value
4318 func (s *Server) portFile(dirHint string) string {
4319 dirname := s.getOpts().PortsFileDir
4320 if dirHint != "" {
4321 dirname = dirHint
4322 }
4323 if dirname == _EMPTY_ {
4324 return _EMPTY_
4325 }
4326 return filepath.Join(dirname, fmt.Sprintf("%s_%d.ports", filepath.Base(os.Args[0]), os.Getpid()))
4327 }
4328
4329 // Delete the ports file. If a non-empty dirHint is provided, the dirHint
4330 // path is used instead of the server option value
4331 func (s *Server) deletePortsFile(hintDir string) {
4332 portsFile := s.portFile(hintDir)
4333 if portsFile != "" {
4334 if err := os.Remove(portsFile); err != nil {
4335 s.Errorf("Error cleaning up ports file %s: %v", portsFile, err)
4336 }
4337 }
4338 }
4339
4340 // Writes a file with a serialized Ports to the specified ports_file_dir.
4341 // The name of the file is `exename_pid.ports`, typically nats-server_pid.ports.
4342 // if ports file is not set, this function has no effect
4343 func (s *Server) logPorts() {
4344 opts := s.getOpts()
4345 portsFile := s.portFile(opts.PortsFileDir)
4346 if portsFile != _EMPTY_ {
4347 go func() {
4348 info := s.PortsInfo(5 * time.Second)
4349 if info == nil {
4350 s.Errorf("Unable to resolve the ports in the specified time")
4351 return
4352 }
4353 data, err := json.Marshal(info)
4354 if err != nil {
4355 s.Errorf("Error marshaling ports file: %v", err)
4356 return
4357 }
4358 if err := os.WriteFile(portsFile, data, 0666); err != nil {
4359 s.Errorf("Error writing ports file (%s): %v", portsFile, err)
4360 return
4361 }
4362
4363 }()
4364 }
4365 }
4366
4367 // waits until a calculated list of listeners is resolved or a timeout
4368 func (s *Server) readyForListeners(dur time.Duration) bool {
4369 end := time.Now().Add(dur)
4370 for time.Now().Before(end) {
4371 s.mu.RLock()
4372 listeners := s.serviceListeners()
4373 s.mu.RUnlock()
4374 if len(listeners) == 0 {
4375 return false
4376 }
4377
4378 ok := true
4379 for _, l := range listeners {
4380 if l == nil {
4381 ok = false
4382 break
4383 }
4384 }
4385 if ok {
4386 return true
4387 }
4388 select {
4389 case <-s.quitCh:
4390 return false
4391 case <-time.After(25 * time.Millisecond):
4392 // continue - unable to select from quit - we are still running
4393 }
4394 }
4395 return false
4396 }
4397
4398 // returns a list of listeners that are intended for the process
4399 // if the entry is nil, the interface is yet to be resolved
4400 func (s *Server) serviceListeners() []net.Listener {
4401 listeners := make([]net.Listener, 0)
4402 opts := s.getOpts()
4403 listeners = append(listeners, s.listener)
4404 if opts.Cluster.Port != 0 {
4405 listeners = append(listeners, s.routeListener)
4406 }
4407 if opts.HTTPPort != 0 || opts.HTTPSPort != 0 {
4408 listeners = append(listeners, s.http)
4409 }
4410 if opts.ProfPort != 0 {
4411 listeners = append(listeners, s.profiler)
4412 }
4413 if opts.Websocket.Port != 0 {
4414 listeners = append(listeners, s.websocket.listener)
4415 }
4416 return listeners
4417 }
4418
4419 // Returns true if in lame duck mode.
4420 func (s *Server) isLameDuckMode() bool {
4421 s.mu.RLock()
4422 defer s.mu.RUnlock()
4423 return s.ldm
4424 }
4425
4426 // LameDuckShutdown will perform a lame duck shutdown of NATS, whereby
4427 // the client listener is closed, existing client connections are
4428 // kicked, Raft leaderships are transferred, JetStream is shutdown
4429 // and then finally shutdown the NATS Server itself.
4430 // This function blocks and will not return until the NATS Server
4431 // has completed the entire shutdown operation.
4432 func (s *Server) LameDuckShutdown() {
4433 s.lameDuckMode()
4434 }
4435
4436 // This function will close the client listener then close the clients
4437 // at some interval to avoid a reconnect storm.
4438 // We will also transfer any raft leaders and shutdown JetStream.
4439 func (s *Server) lameDuckMode() {
4440 s.mu.Lock()
4441 // Check if there is actually anything to do
4442 if s.isShuttingDown() || s.ldm || s.listener == nil {
4443 s.mu.Unlock()
4444 return
4445 }
4446 s.Noticef("Entering lame duck mode, stop accepting new clients")
4447 s.ldm = true
4448 s.sendLDMShutdownEventLocked()
4449 expected := 1
4450 s.listener.Close()
4451 s.listener = nil
4452 expected += s.closeWebsocketServer()
4453 s.ldmCh = make(chan bool, expected)
4454 opts := s.getOpts()
4455 gp := opts.LameDuckGracePeriod
4456 // For tests, we want the grace period to be in some cases bigger
4457 // than the ldm duration, so to by-pass the validateOptions() check,
4458 // we use negative number and flip it here.
4459 if gp < 0 {
4460 gp *= -1
4461 }
4462 s.mu.Unlock()
4463
4464 // If we are running any raftNodes transfer leaders.
4465 if hadTransfers := s.transferRaftLeaders(); hadTransfers {
4466 // They will transfer leadership quickly, but wait here for a second.
4467 select {
4468 case <-time.After(time.Second):
4469 case <-s.quitCh:
4470 return
4471 }
4472 }
4473
4474 // Now check and shutdown jetstream.
4475 s.shutdownJetStream()
4476
4477 // Now shutdown the nodes
4478 s.shutdownRaftNodes()
4479
4480 // Wait for accept loops to be done to make sure that no new
4481 // client can connect
4482 for i := 0; i < expected; i++ {
4483 <-s.ldmCh
4484 }
4485
4486 s.mu.Lock()
4487 // Need to recheck few things
4488 if s.isShuttingDown() || len(s.clients) == 0 {
4489 s.mu.Unlock()
4490 // If there is no client, we need to call Shutdown() to complete
4491 // the LDMode. If server has been shutdown while lock was released,
4492 // calling Shutdown() should be no-op.
4493 s.Shutdown()
4494 return
4495 }
4496 dur := int64(opts.LameDuckDuration)
4497 dur -= int64(gp)
4498 if dur <= 0 {
4499 dur = int64(time.Second)
4500 }
4501 numClients := int64(len(s.clients))
4502 batch := 1
4503 // Sleep interval between each client connection close.
4504 var si int64
4505 if numClients != 0 {
4506 si = dur / numClients
4507 }
4508 if si < 1 {
4509 // Should not happen (except in test with very small LD duration), but
4510 // if there are too many clients, batch the number of close and
4511 // use a tiny sleep interval that will result in yield likely.
4512 si = 1
4513 batch = int(numClients / dur)
4514 } else if si > int64(time.Second) {
4515 // Conversely, there is no need to sleep too long between clients
4516 // and spread say 10 clients for the 2min duration. Sleeping no
4517 // more than 1sec.
4518 si = int64(time.Second)
4519 }
4520
4521 // Now capture all clients
4522 clients := make([]*client, 0, len(s.clients))
4523 for _, client := range s.clients {
4524 clients = append(clients, client)
4525 }
4526 // Now that we know that no new client can be accepted,
4527 // send INFO to routes and clients to notify this state.
4528 s.sendLDMToRoutes()
4529 s.sendLDMToClients()
4530 s.mu.Unlock()
4531
4532 t := time.NewTimer(gp)
4533 // Delay start of closing of client connections in case
4534 // we have several servers that we want to signal to enter LD mode
4535 // and not have their client reconnect to each other.
4536 select {
4537 case <-t.C:
4538 s.Noticef("Closing existing clients")
4539 case <-s.quitCh:
4540 t.Stop()
4541 return
4542 }
4543 for i, client := range clients {
4544 client.closeConnection(ServerShutdown)
4545 if i == len(clients)-1 {
4546 break
4547 }
4548 if batch == 1 || i%batch == 0 {
4549 // We pick a random interval which will be at least si/2
4550 v := rand.Int63n(si)
4551 if v < si/2 {
4552 v = si / 2
4553 }
4554 t.Reset(time.Duration(v))
4555 // Sleep for given interval or bail out if kicked by Shutdown().
4556 select {
4557 case <-t.C:
4558 case <-s.quitCh:
4559 t.Stop()
4560 return
4561 }
4562 }
4563 }
4564 s.Shutdown()
4565 s.WaitForShutdown()
4566 }
4567
4568 // Send an INFO update to routes with the indication that this server is in LDM mode.
4569 // Server lock is held on entry.
4570 func (s *Server) sendLDMToRoutes() {
4571 s.routeInfo.LameDuckMode = true
4572 infoJSON := generateInfoJSON(&s.routeInfo)
4573 s.forEachRemote(func(r *client) {
4574 r.mu.Lock()
4575 r.enqueueProto(infoJSON)
4576 r.mu.Unlock()
4577 })
4578 // Clear now so that we notify only once, should we have to send other INFOs.
4579 s.routeInfo.LameDuckMode = false
4580 }
4581
4582 // Send an INFO update to clients with the indication that this server is in
4583 // LDM mode and with only URLs of other nodes.
4584 // Server lock is held on entry.
4585 func (s *Server) sendLDMToClients() {
4586 s.info.LameDuckMode = true
4587 // Clear this so that if there are further updates, we don't send our URLs.
4588 s.clientConnectURLs = s.clientConnectURLs[:0]
4589 if s.websocket.connectURLs != nil {
4590 s.websocket.connectURLs = s.websocket.connectURLs[:0]
4591 }
4592 // Reset content first.
4593 s.info.ClientConnectURLs = s.info.ClientConnectURLs[:0]
4594 s.info.WSConnectURLs = s.info.WSConnectURLs[:0]
4595 // Only add the other nodes if we are allowed to.
4596 if !s.getOpts().Cluster.NoAdvertise {
4597 for url := range s.clientConnectURLsMap {
4598 s.info.ClientConnectURLs = append(s.info.ClientConnectURLs, url)
4599 }
4600 for url := range s.websocket.connectURLsMap {
4601 s.info.WSConnectURLs = append(s.info.WSConnectURLs, url)
4602 }
4603 }
4604 // Send to all registered clients that support async INFO protocols.
4605 s.sendAsyncInfoToClients(true, true)
4606 // We now clear the info.LameDuckMode flag so that if there are
4607 // cluster updates and we send the INFO, we don't have the boolean
4608 // set which would cause multiple LDM notifications to clients.
4609 s.info.LameDuckMode = false
4610 }
4611
4612 // If given error is a net.Error and is temporary, sleeps for the given
4613 // delay and double it, but cap it to ACCEPT_MAX_SLEEP. The sleep is
4614 // interrupted if the server is shutdown.
4615 // An error message is displayed depending on the type of error.
4616 // Returns the new (or unchanged) delay, or a negative value if the
4617 // server has been or is being shutdown.
4618 func (s *Server) acceptError(acceptName string, err error, tmpDelay time.Duration) time.Duration {
4619 if !s.isRunning() {
4620 return -1
4621 }
4622 //lint:ignore SA1019 We want to retry on a bunch of errors here.
4623 if ne, ok := err.(net.Error); ok && ne.Temporary() { // nolint:staticcheck
4624 s.Errorf("Temporary %s Accept Error(%v), sleeping %dms", acceptName, ne, tmpDelay/time.Millisecond)
4625 select {
4626 case <-time.After(tmpDelay):
4627 case <-s.quitCh:
4628 return -1
4629 }
4630 tmpDelay *= 2
4631 if tmpDelay > ACCEPT_MAX_SLEEP {
4632 tmpDelay = ACCEPT_MAX_SLEEP
4633 }
4634 } else {
4635 s.Errorf("%s Accept error: %v", acceptName, err)
4636 }
4637 return tmpDelay
4638 }
4639
4640 var errNoIPAvail = errors.New("no IP available")
4641
4642 func (s *Server) getRandomIP(resolver netResolver, url string, excludedAddresses map[string]struct{}) (string, error) {
4643 host, port, err := net.SplitHostPort(url)
4644 if err != nil {
4645 return "", err
4646 }
4647 // If already an IP, skip.
4648 if net.ParseIP(host) != nil {
4649 return url, nil
4650 }
4651 ips, err := resolver.LookupHost(context.Background(), host)
4652 if err != nil {
4653 return "", fmt.Errorf("lookup for host %q: %v", host, err)
4654 }
4655 if len(excludedAddresses) > 0 {
4656 for i := 0; i < len(ips); i++ {
4657 ip := ips[i]
4658 addr := net.JoinHostPort(ip, port)
4659 if _, excluded := excludedAddresses[addr]; excluded {
4660 if len(ips) == 1 {
4661 ips = nil
4662 break
4663 }
4664 ips[i] = ips[len(ips)-1]
4665 ips = ips[:len(ips)-1]
4666 i--
4667 }
4668 }
4669 if len(ips) == 0 {
4670 return "", errNoIPAvail
4671 }
4672 }
4673 var address string
4674 if len(ips) == 0 {
4675 s.Warnf("Unable to get IP for %s, will try with %s: %v", host, url, err)
4676 address = url
4677 } else {
4678 var ip string
4679 if len(ips) == 1 {
4680 ip = ips[0]
4681 } else {
4682 ip = ips[rand.Int31n(int32(len(ips)))]
4683 }
4684 // add the port
4685 address = net.JoinHostPort(ip, port)
4686 }
4687 return address, nil
4688 }
4689
4690 // Returns true for the first attempt and depending on the nature
4691 // of the attempt (first connect or a reconnect), when the number
4692 // of attempts is equal to the configured report attempts.
4693 func (s *Server) shouldReportConnectErr(firstConnect bool, attempts int) bool {
4694 opts := s.getOpts()
4695 if firstConnect {
4696 if attempts == 1 || attempts%opts.ConnectErrorReports == 0 {
4697 return true
4698 }
4699 return false
4700 }
4701 if attempts == 1 || attempts%opts.ReconnectErrorReports == 0 {
4702 return true
4703 }
4704 return false
4705 }
4706
4707 func (s *Server) updateRemoteSubscription(acc *Account, sub *subscription, delta int32) {
4708 s.updateRouteSubscriptionMap(acc, sub, delta)
4709 if s.gateway.enabled {
4710 s.gatewayUpdateSubInterest(acc.Name, sub, delta)
4711 }
4712
4713 acc.updateLeafNodes(sub, delta)
4714 }
4715
4716 func (s *Server) startRateLimitLogExpiration() {
4717 interval := time.Second
4718 s.startGoRoutine(func() {
4719 defer s.grWG.Done()
4720
4721 ticker := time.NewTicker(time.Second)
4722 defer ticker.Stop()
4723 for {
4724 select {
4725 case <-s.quitCh:
4726 return
4727 case interval = <-s.rateLimitLoggingCh:
4728 ticker.Reset(interval)
4729 case <-ticker.C:
4730 s.rateLimitLogging.Range(func(k, v any) bool {
4731 start := v.(time.Time)
4732 if time.Since(start) >= interval {
4733 s.rateLimitLogging.Delete(k)
4734 }
4735 return true
4736 })
4737 }
4738 }
4739 })
4740 }
4741
4742 func (s *Server) changeRateLimitLogInterval(d time.Duration) {
4743 if d <= 0 {
4744 return
4745 }
4746 select {
4747 case s.rateLimitLoggingCh <- d:
4748 default:
4749 }
4750 }
4751
4752 // DisconnectClientByID disconnects a client by connection ID
4753 func (s *Server) DisconnectClientByID(id uint64) error {
4754 if s == nil {
4755 return ErrServerNotRunning
4756 }
4757 if client := s.getClient(id); client != nil {
4758 client.closeConnection(Kicked)
4759 return nil
4760 } else if client = s.GetLeafNode(id); client != nil {
4761 client.closeConnection(Kicked)
4762 return nil
4763 }
4764 return errors.New("no such client or leafnode id")
4765 }
4766
4767 // LDMClientByID sends a Lame Duck Mode info message to a client by connection ID
4768 func (s *Server) LDMClientByID(id uint64) error {
4769 if s == nil {
4770 return ErrServerNotRunning
4771 }
4772 s.mu.RLock()
4773 c := s.clients[id]
4774 if c == nil {
4775 s.mu.RUnlock()
4776 return errors.New("no such client id")
4777 }
4778 info := s.copyInfo()
4779 info.LameDuckMode = true
4780 s.mu.RUnlock()
4781 c.mu.Lock()
4782 defer c.mu.Unlock()
4783 if c.opts.Protocol >= ClientProtoInfo && c.flags.isSet(firstPongSent) {
4784 // sendInfo takes care of checking if the connection is still
4785 // valid or not, so don't duplicate tests here.
4786 c.Debugf("Sending Lame Duck Mode info to client")
4787 c.enqueueProto(c.generateClientInfoJSON(info, true))
4788 return nil
4789 } else {
4790 return errors.New("client does not support Lame Duck Mode or is not ready to receive the notification")
4791 }
4792 }
4793
4794 func (s *Server) diskIOSemaphore() *diskIOSemaphore {
4795 if s == nil || s.dios == nil {
4796 return defaultDiskIOSemaphore()
4797 }
4798 return s.dios
4799 }