• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nats-io / nats-server / 17966560402

23 Sep 2025 04:09PM UTC coverage: 85.965% (-0.07%) from 86.036%
17966560402

push

github

web-flow
(2.12) Filestore cache improvements (#7346)

74278 of 86405 relevant lines covered (85.96%)

360065.15 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.15
/server/leafnode.go
1
// Copyright 2019-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
        "bufio"
18
        "bytes"
19
        "crypto/tls"
20
        "encoding/base64"
21
        "encoding/json"
22
        "fmt"
23
        "io"
24
        "math/rand"
25
        "net"
26
        "net/http"
27
        "net/url"
28
        "os"
29
        "path"
30
        "reflect"
31
        "regexp"
32
        "runtime"
33
        "strconv"
34
        "strings"
35
        "sync"
36
        "sync/atomic"
37
        "time"
38

39
        "github.com/klauspost/compress/s2"
40
        "github.com/nats-io/jwt/v2"
41
        "github.com/nats-io/nkeys"
42
        "github.com/nats-io/nuid"
43
)
44

45
const (
46
        // Warning when user configures leafnode TLS insecure
47
        leafnodeTLSInsecureWarning = "TLS certificate chain and hostname of solicited leafnodes will not be verified. DO NOT USE IN PRODUCTION!"
48

49
        // When a loop is detected, delay the reconnect of solicited connection.
50
        leafNodeReconnectDelayAfterLoopDetected = 30 * time.Second
51

52
        // When a server receives a message causing a permission violation, the
53
        // connection is closed and it won't attempt to reconnect for that long.
54
        leafNodeReconnectAfterPermViolation = 30 * time.Second
55

56
        // When we have the same cluster name as the hub.
57
        leafNodeReconnectDelayAfterClusterNameSame = 30 * time.Second
58

59
        // Prefix for loop detection subject
60
        leafNodeLoopDetectionSubjectPrefix = "$LDS."
61

62
        // Path added to URL to indicate to WS server that the connection is a
63
        // LEAF connection as opposed to a CLIENT.
64
        leafNodeWSPath = "/leafnode"
65

66
        // This is the time the server will wait, when receiving a CONNECT,
67
        // before closing the connection if the required minimum version is not met.
68
        leafNodeWaitBeforeClose = 5 * time.Second
69
)
70

71
type leaf struct {
72
        // We have any auth stuff here for solicited connections.
73
        remote *leafNodeCfg
74
        // isSpoke tells us what role we are playing.
75
        // Used when we receive a connection but otherside tells us they are a hub.
76
        isSpoke bool
77
        // remoteCluster is when we are a hub but the spoke leafnode is part of a cluster.
78
        remoteCluster string
79
        // remoteServer holds onto the remote server's name or ID.
80
        remoteServer string
81
        // domain name of remote server
82
        remoteDomain string
83
        // account name of remote server
84
        remoteAccName string
85
        // Whether or not we want to propagate east-west interest from other LNs.
86
        isolated bool
87
        // Used to suppress sub and unsub interest. Same as routes but our audience
88
        // here is tied to this leaf node. This will hold all subscriptions except this
89
        // leaf nodes. This represents all the interest we want to send to the other side.
90
        smap map[string]int32
91
        // This map will contain all the subscriptions that have been added to the smap
92
        // during initLeafNodeSmapAndSendSubs. It is short lived and is there to avoid
93
        // race between processing of a sub where sub is added to account sublist but
94
        // updateSmap has not be called on that "thread", while in the LN readloop,
95
        // when processing CONNECT, initLeafNodeSmapAndSendSubs is invoked and add
96
        // this subscription to smap. When processing of the sub then calls updateSmap,
97
        // we would add it a second time in the smap causing later unsub to suppress the LS-.
98
        tsub  map[*subscription]struct{}
99
        tsubt *time.Timer
100
        // Selected compression mode, which may be different from the server configured mode.
101
        compression string
102
        // This is for GW map replies.
103
        gwSub *subscription
104
}
105

106
// Used for remote (solicited) leafnodes.
107
type leafNodeCfg struct {
108
        sync.RWMutex
109
        *RemoteLeafOpts
110
        urls           []*url.URL
111
        curURL         *url.URL
112
        tlsName        string
113
        username       string
114
        password       string
115
        perms          *Permissions
116
        connDelay      time.Duration // Delay before a connect, could be used while detecting loop condition, etc..
117
        jsMigrateTimer *time.Timer
118
}
119

120
// Check to see if this is a solicited leafnode. We do special processing for solicited.
121
func (c *client) isSolicitedLeafNode() bool {
2,090✔
122
        return c.kind == LEAF && c.leaf.remote != nil
2,090✔
123
}
2,090✔
124

125
// Returns true if this is a solicited leafnode and is not configured to be treated as a hub or a receiving
126
// connection leafnode where the otherside has declared itself to be the hub.
127
func (c *client) isSpokeLeafNode() bool {
6,596,152✔
128
        return c.kind == LEAF && c.leaf.isSpoke
6,596,152✔
129
}
6,596,152✔
130

131
func (c *client) isHubLeafNode() bool {
18,286✔
132
        return c.kind == LEAF && !c.leaf.isSpoke
18,286✔
133
}
18,286✔
134

135
func (c *client) isIsolatedLeafNode() bool {
11,447✔
136
        // TODO(nat): In future we may want to pass in and consider an isolation
11,447✔
137
        // group name here, which the hub and/or leaf could provide, so that we
11,447✔
138
        // can isolate away certain LNs but not others on an opt-in basis. For
11,447✔
139
        // now we will just isolate all LN interest until then.
11,447✔
140
        return c.kind == LEAF && c.leaf.isolated
11,447✔
141
}
11,447✔
142

143
// This will spin up go routines to solicit the remote leaf node connections.
144
func (s *Server) solicitLeafNodeRemotes(remotes []*RemoteLeafOpts) {
1,180✔
145
        sysAccName := _EMPTY_
1,180✔
146
        sAcc := s.SystemAccount()
1,180✔
147
        if sAcc != nil {
2,337✔
148
                sysAccName = sAcc.Name
1,157✔
149
        }
1,157✔
150
        addRemote := func(r *RemoteLeafOpts, isSysAccRemote bool) *leafNodeCfg {
2,504✔
151
                s.mu.Lock()
1,324✔
152
                remote := newLeafNodeCfg(r)
1,324✔
153
                creds := remote.Credentials
1,324✔
154
                accName := remote.LocalAccount
1,324✔
155
                s.leafRemoteCfgs = append(s.leafRemoteCfgs, remote)
1,324✔
156
                // Print notice if
1,324✔
157
                if isSysAccRemote {
1,415✔
158
                        if len(remote.DenyExports) > 0 {
92✔
159
                                s.Noticef("Remote for System Account uses restricted export permissions")
1✔
160
                        }
1✔
161
                        if len(remote.DenyImports) > 0 {
92✔
162
                                s.Noticef("Remote for System Account uses restricted import permissions")
1✔
163
                        }
1✔
164
                }
165
                s.mu.Unlock()
1,324✔
166
                if creds != _EMPTY_ {
1,374✔
167
                        contents, err := os.ReadFile(creds)
50✔
168
                        defer wipeSlice(contents)
50✔
169
                        if err != nil {
50✔
170
                                s.Errorf("Error reading LeafNode Remote Credentials file %q: %v", creds, err)
×
171
                        } else if items := credsRe.FindAllSubmatch(contents, -1); len(items) < 2 {
50✔
172
                                s.Errorf("LeafNode Remote Credentials file %q malformed", creds)
×
173
                        } else if _, err := nkeys.FromSeed(items[1][1]); err != nil {
50✔
174
                                s.Errorf("LeafNode Remote Credentials file %q has malformed seed", creds)
×
175
                        } else if uc, err := jwt.DecodeUserClaims(string(items[0][1])); err != nil {
50✔
176
                                s.Errorf("LeafNode Remote Credentials file %q has malformed user jwt", creds)
×
177
                        } else if isSysAccRemote {
54✔
178
                                if !uc.Permissions.Pub.Empty() || !uc.Permissions.Sub.Empty() || uc.Permissions.Resp != nil {
5✔
179
                                        s.Noticef("LeafNode Remote for System Account uses credentials file %q with restricted permissions", creds)
1✔
180
                                }
1✔
181
                        } else {
46✔
182
                                if !uc.Permissions.Pub.Empty() || !uc.Permissions.Sub.Empty() || uc.Permissions.Resp != nil {
52✔
183
                                        s.Noticef("LeafNode Remote for Account %s uses credentials file %q with restricted permissions", accName, creds)
6✔
184
                                }
6✔
185
                        }
186
                }
187
                return remote
1,324✔
188
        }
189
        for _, r := range remotes {
2,504✔
190
                // We need to call this, even if the leaf is disabled. This is so that
1,324✔
191
                // the number of internal configuration matches the options' remote leaf
1,324✔
192
                // configuration required for configuration reload.
1,324✔
193
                remote := addRemote(r, r.LocalAccount == sysAccName)
1,324✔
194
                if !r.Disabled {
2,647✔
195
                        s.startGoRoutine(func() { s.connectToRemoteLeafNode(remote, true) })
2,646✔
196
                }
197
        }
198
}
199

200
func (s *Server) remoteLeafNodeStillValid(remote *leafNodeCfg) bool {
7,707✔
201
        if remote.Disabled {
7,708✔
202
                return false
1✔
203
        }
1✔
204
        for _, ri := range s.getOpts().LeafNode.Remotes {
15,790✔
205
                // FIXME(dlc) - What about auth changes?
8,084✔
206
                if reflect.DeepEqual(ri.URLs, remote.URLs) {
15,790✔
207
                        return true
7,706✔
208
                }
7,706✔
209
        }
210
        return false
×
211
}
212

213
// Ensure that leafnode is properly configured.
214
func validateLeafNode(o *Options) error {
8,806✔
215
        if err := validateLeafNodeAuthOptions(o); err != nil {
8,808✔
216
                return err
2✔
217
        }
2✔
218

219
        // Users can bind to any local account, if its empty we will assume the $G account.
220
        for _, r := range o.LeafNode.Remotes {
10,169✔
221
                if r.LocalAccount == _EMPTY_ {
1,801✔
222
                        r.LocalAccount = globalAccountName
436✔
223
                }
436✔
224
        }
225

226
        // In local config mode, check that leafnode configuration refers to accounts that exist.
227
        if len(o.TrustedOperators) == 0 {
17,287✔
228
                accNames := map[string]struct{}{}
8,483✔
229
                for _, a := range o.Accounts {
17,740✔
230
                        accNames[a.Name] = struct{}{}
9,257✔
231
                }
9,257✔
232
                // global account is always created
233
                accNames[DEFAULT_GLOBAL_ACCOUNT] = struct{}{}
8,483✔
234
                // in the context of leaf nodes, empty account means global account
8,483✔
235
                accNames[_EMPTY_] = struct{}{}
8,483✔
236
                // system account either exists or, if not disabled, will be created
8,483✔
237
                if o.SystemAccount == _EMPTY_ && !o.NoSystemAccount {
15,239✔
238
                        accNames[DEFAULT_SYSTEM_ACCOUNT] = struct{}{}
6,756✔
239
                }
6,756✔
240
                checkAccountExists := func(accName string, cfgType string) error {
18,337✔
241
                        if _, ok := accNames[accName]; !ok {
9,856✔
242
                                return fmt.Errorf("cannot find local account %q specified in leafnode %s", accName, cfgType)
2✔
243
                        }
2✔
244
                        return nil
9,852✔
245
                }
246
                if err := checkAccountExists(o.LeafNode.Account, "authorization"); err != nil {
8,484✔
247
                        return err
1✔
248
                }
1✔
249
                for _, lu := range o.LeafNode.Users {
8,499✔
250
                        if lu.Account == nil { // means global account
27✔
251
                                continue
10✔
252
                        }
253
                        if err := checkAccountExists(lu.Account.Name, "authorization"); err != nil {
7✔
254
                                return err
×
255
                        }
×
256
                }
257
                for _, r := range o.LeafNode.Remotes {
9,846✔
258
                        if err := checkAccountExists(r.LocalAccount, "remote"); err != nil {
1,365✔
259
                                return err
1✔
260
                        }
1✔
261
                }
262
        } else {
321✔
263
                if len(o.LeafNode.Users) != 0 {
322✔
264
                        return fmt.Errorf("operator mode does not allow specifying users in leafnode config")
1✔
265
                }
1✔
266
                for _, r := range o.LeafNode.Remotes {
321✔
267
                        if !nkeys.IsValidPublicAccountKey(r.LocalAccount) {
2✔
268
                                return fmt.Errorf(
1✔
269
                                        "operator mode requires account nkeys in remotes. " +
1✔
270
                                                "Please add an `account` key to each remote in your `leafnodes` section, to assign it to an account. " +
1✔
271
                                                "Each account value should be a 56 character public key, starting with the letter 'A'")
1✔
272
                        }
1✔
273
                }
274
                if o.LeafNode.Port != 0 && o.LeafNode.Account != "" && !nkeys.IsValidPublicAccountKey(o.LeafNode.Account) {
320✔
275
                        return fmt.Errorf("operator mode and non account nkeys are incompatible")
1✔
276
                }
1✔
277
        }
278

279
        // Validate compression settings
280
        if o.LeafNode.Compression.Mode != _EMPTY_ {
12,981✔
281
                if err := validateAndNormalizeCompressionOption(&o.LeafNode.Compression, CompressionS2Auto); err != nil {
4,187✔
282
                        return err
5✔
283
                }
5✔
284
        }
285

286
        // If a remote has a websocket scheme, all need to have it.
287
        for _, rcfg := range o.LeafNode.Remotes {
10,157✔
288
                if len(rcfg.URLs) >= 2 {
1,565✔
289
                        firstIsWS, ok := isWSURL(rcfg.URLs[0]), true
202✔
290
                        for i := 1; i < len(rcfg.URLs); i++ {
649✔
291
                                u := rcfg.URLs[i]
447✔
292
                                if isWS := isWSURL(u); isWS && !firstIsWS || !isWS && firstIsWS {
454✔
293
                                        ok = false
7✔
294
                                        break
7✔
295
                                }
296
                        }
297
                        if !ok {
209✔
298
                                return fmt.Errorf("remote leaf node configuration cannot have a mix of websocket and non-websocket urls: %q", redactURLList(rcfg.URLs))
7✔
299
                        }
7✔
300
                }
301
                // Validate compression settings
302
                if rcfg.Compression.Mode != _EMPTY_ {
2,712✔
303
                        if err := validateAndNormalizeCompressionOption(&rcfg.Compression, CompressionS2Auto); err != nil {
1,361✔
304
                                return err
5✔
305
                        }
5✔
306
                }
307
        }
308

309
        if o.LeafNode.Port == 0 {
13,977✔
310
                return nil
5,195✔
311
        }
5,195✔
312

313
        // If MinVersion is defined, check that it is valid.
314
        if mv := o.LeafNode.MinVersion; mv != _EMPTY_ {
3,591✔
315
                if err := checkLeafMinVersionConfig(mv); err != nil {
6✔
316
                        return err
2✔
317
                }
2✔
318
        }
319

320
        // The checks below will be done only when detecting that we are configured
321
        // with gateways. So if an option validation needs to be done regardless,
322
        // it MUST be done before this point!
323

324
        if o.Gateway.Name == _EMPTY_ && o.Gateway.Port == 0 {
6,486✔
325
                return nil
2,901✔
326
        }
2,901✔
327
        // If we are here we have both leaf nodes and gateways defined, make sure there
328
        // is a system account defined.
329
        if o.SystemAccount == _EMPTY_ {
685✔
330
                return fmt.Errorf("leaf nodes and gateways (both being defined) require a system account to also be configured")
1✔
331
        }
1✔
332
        if err := validatePinnedCerts(o.LeafNode.TLSPinnedCerts); err != nil {
683✔
333
                return fmt.Errorf("leafnode: %v", err)
×
334
        }
×
335
        return nil
683✔
336
}
337

338
func checkLeafMinVersionConfig(mv string) error {
8✔
339
        if ok, err := versionAtLeastCheckError(mv, 2, 8, 0); !ok || err != nil {
12✔
340
                if err != nil {
6✔
341
                        return fmt.Errorf("invalid leafnode's minimum version: %v", err)
2✔
342
                } else {
4✔
343
                        return fmt.Errorf("the minimum version should be at least 2.8.0")
2✔
344
                }
2✔
345
        }
346
        return nil
4✔
347
}
348

349
// Used to validate user names in LeafNode configuration.
350
// - rejects mix of single and multiple users.
351
// - rejects duplicate user names.
352
func validateLeafNodeAuthOptions(o *Options) error {
8,865✔
353
        if len(o.LeafNode.Users) == 0 {
17,703✔
354
                return nil
8,838✔
355
        }
8,838✔
356
        if o.LeafNode.Username != _EMPTY_ {
29✔
357
                return fmt.Errorf("can not have a single user/pass and a users array")
2✔
358
        }
2✔
359
        if o.LeafNode.Nkey != _EMPTY_ {
25✔
360
                return fmt.Errorf("can not have a single nkey and a users array")
×
361
        }
×
362
        users := map[string]struct{}{}
25✔
363
        for _, u := range o.LeafNode.Users {
66✔
364
                if _, exists := users[u.Username]; exists {
43✔
365
                        return fmt.Errorf("duplicate user %q detected in leafnode authorization", u.Username)
2✔
366
                }
2✔
367
                users[u.Username] = struct{}{}
39✔
368
        }
369
        return nil
23✔
370
}
371

372
// Update remote LeafNode TLS configurations after a config reload.
373
func (s *Server) updateRemoteLeafNodesTLSConfig(opts *Options) {
15✔
374
        max := len(opts.LeafNode.Remotes)
15✔
375
        if max == 0 {
15✔
376
                return
×
377
        }
×
378

379
        s.mu.RLock()
15✔
380
        defer s.mu.RUnlock()
15✔
381

15✔
382
        // Changes in the list of remote leaf nodes is not supported.
15✔
383
        // However, make sure that we don't go over the arrays.
15✔
384
        if len(s.leafRemoteCfgs) < max {
15✔
385
                max = len(s.leafRemoteCfgs)
×
386
        }
×
387
        for i := 0; i < max; i++ {
34✔
388
                ro := opts.LeafNode.Remotes[i]
19✔
389
                cfg := s.leafRemoteCfgs[i]
19✔
390
                if ro.TLSConfig != nil {
21✔
391
                        cfg.Lock()
2✔
392
                        cfg.TLSConfig = ro.TLSConfig.Clone()
2✔
393
                        cfg.TLSHandshakeFirst = ro.TLSHandshakeFirst
2✔
394
                        cfg.Unlock()
2✔
395
                }
2✔
396
        }
397
}
398

399
func (s *Server) reConnectToRemoteLeafNode(remote *leafNodeCfg) {
238✔
400
        delay := s.getOpts().LeafNode.ReconnectInterval
238✔
401
        select {
238✔
402
        case <-time.After(delay):
182✔
403
        case <-s.quitCh:
56✔
404
                s.grWG.Done()
56✔
405
                return
56✔
406
        }
407
        s.connectToRemoteLeafNode(remote, false)
182✔
408
}
409

410
// Creates a leafNodeCfg object that wraps the RemoteLeafOpts.
411
func newLeafNodeCfg(remote *RemoteLeafOpts) *leafNodeCfg {
1,324✔
412
        cfg := &leafNodeCfg{
1,324✔
413
                RemoteLeafOpts: remote,
1,324✔
414
                urls:           make([]*url.URL, 0, len(remote.URLs)),
1,324✔
415
        }
1,324✔
416
        if len(remote.DenyExports) > 0 || len(remote.DenyImports) > 0 {
1,332✔
417
                perms := &Permissions{}
8✔
418
                if len(remote.DenyExports) > 0 {
16✔
419
                        perms.Publish = &SubjectPermission{Deny: remote.DenyExports}
8✔
420
                }
8✔
421
                if len(remote.DenyImports) > 0 {
15✔
422
                        perms.Subscribe = &SubjectPermission{Deny: remote.DenyImports}
7✔
423
                }
7✔
424
                cfg.perms = perms
8✔
425
        }
426
        // Start with the one that is configured. We will add to this
427
        // array when receiving async leafnode INFOs.
428
        cfg.urls = append(cfg.urls, cfg.URLs...)
1,324✔
429
        // If allowed to randomize, do it on our copy of URLs
1,324✔
430
        if !remote.NoRandomize {
2,646✔
431
                rand.Shuffle(len(cfg.urls), func(i, j int) {
1,726✔
432
                        cfg.urls[i], cfg.urls[j] = cfg.urls[j], cfg.urls[i]
404✔
433
                })
404✔
434
        }
435
        // If we are TLS make sure we save off a proper servername if possible.
436
        // Do same for user/password since we may need them to connect to
437
        // a bare URL that we get from INFO protocol.
438
        for _, u := range cfg.urls {
3,082✔
439
                cfg.saveTLSHostname(u)
1,758✔
440
                cfg.saveUserPassword(u)
1,758✔
441
                // If the url(s) have the "wss://" scheme, and we don't have a TLS
1,758✔
442
                // config, mark that we should be using TLS anyway.
1,758✔
443
                if !cfg.TLS && isWSSURL(u) {
1,759✔
444
                        cfg.TLS = true
1✔
445
                }
1✔
446
        }
447
        return cfg
1,324✔
448
}
449

450
// Will pick an URL from the list of available URLs.
451
func (cfg *leafNodeCfg) pickNextURL() *url.URL {
6,911✔
452
        cfg.Lock()
6,911✔
453
        defer cfg.Unlock()
6,911✔
454
        // If the current URL is the first in the list and we have more than
6,911✔
455
        // one URL, then move that one to end of the list.
6,911✔
456
        if cfg.curURL != nil && len(cfg.urls) > 1 && urlsAreEqual(cfg.curURL, cfg.urls[0]) {
10,475✔
457
                first := cfg.urls[0]
3,564✔
458
                copy(cfg.urls, cfg.urls[1:])
3,564✔
459
                cfg.urls[len(cfg.urls)-1] = first
3,564✔
460
        }
3,564✔
461
        cfg.curURL = cfg.urls[0]
6,911✔
462
        return cfg.curURL
6,911✔
463
}
464

465
// Returns the current URL
466
func (cfg *leafNodeCfg) getCurrentURL() *url.URL {
76✔
467
        cfg.RLock()
76✔
468
        defer cfg.RUnlock()
76✔
469
        return cfg.curURL
76✔
470
}
76✔
471

472
// Returns how long the server should wait before attempting
473
// to solicit a remote leafnode connection.
474
func (cfg *leafNodeCfg) getConnectDelay() time.Duration {
1,507✔
475
        cfg.RLock()
1,507✔
476
        delay := cfg.connDelay
1,507✔
477
        cfg.RUnlock()
1,507✔
478
        return delay
1,507✔
479
}
1,507✔
480

481
// Sets the connect delay.
482
func (cfg *leafNodeCfg) setConnectDelay(delay time.Duration) {
146✔
483
        cfg.Lock()
146✔
484
        cfg.connDelay = delay
146✔
485
        cfg.Unlock()
146✔
486
}
146✔
487

488
// Ensure that non-exported options (used in tests) have
489
// been properly set.
490
func (s *Server) setLeafNodeNonExportedOptions() {
7,270✔
491
        opts := s.getOpts()
7,270✔
492
        s.leafNodeOpts.dialTimeout = opts.LeafNode.dialTimeout
7,270✔
493
        if s.leafNodeOpts.dialTimeout == 0 {
14,539✔
494
                // Use same timeouts as routes for now.
7,269✔
495
                s.leafNodeOpts.dialTimeout = DEFAULT_ROUTE_DIAL
7,269✔
496
        }
7,269✔
497
        s.leafNodeOpts.resolver = opts.LeafNode.resolver
7,270✔
498
        if s.leafNodeOpts.resolver == nil {
14,536✔
499
                s.leafNodeOpts.resolver = net.DefaultResolver
7,266✔
500
        }
7,266✔
501
}
502

503
const sharedSysAccDelay = 250 * time.Millisecond
504

505
func (s *Server) connectToRemoteLeafNode(remote *leafNodeCfg, firstConnect bool) {
1,507✔
506
        defer s.grWG.Done()
1,507✔
507

1,507✔
508
        if remote == nil || len(remote.URLs) == 0 {
1,507✔
509
                s.Debugf("Empty remote leafnode definition, nothing to connect")
×
510
                return
×
511
        }
×
512

513
        opts := s.getOpts()
1,507✔
514
        reconnectDelay := opts.LeafNode.ReconnectInterval
1,507✔
515
        s.mu.RLock()
1,507✔
516
        dialTimeout := s.leafNodeOpts.dialTimeout
1,507✔
517
        resolver := s.leafNodeOpts.resolver
1,507✔
518
        var isSysAcc bool
1,507✔
519
        if s.eventsEnabled() {
2,981✔
520
                isSysAcc = remote.LocalAccount == s.sys.account.Name
1,474✔
521
        }
1,474✔
522
        jetstreamMigrateDelay := remote.JetStreamClusterMigrateDelay
1,507✔
523
        s.mu.RUnlock()
1,507✔
524

1,507✔
525
        // If we are sharing a system account and we are not standalone delay to gather some info prior.
1,507✔
526
        if firstConnect && isSysAcc && !s.standAloneMode() {
1,575✔
527
                s.Debugf("Will delay first leafnode connect to shared system account due to clustering")
68✔
528
                remote.setConnectDelay(sharedSysAccDelay)
68✔
529
        }
68✔
530

531
        if connDelay := remote.getConnectDelay(); connDelay > 0 {
1,581✔
532
                select {
74✔
533
                case <-time.After(connDelay):
68✔
534
                case <-s.quitCh:
6✔
535
                        return
6✔
536
                }
537
                remote.setConnectDelay(0)
68✔
538
        }
539

540
        var conn net.Conn
1,501✔
541

1,501✔
542
        const connErrFmt = "Error trying to connect as leafnode to remote server %q (attempt %v): %v"
1,501✔
543

1,501✔
544
        attempts := 0
1,501✔
545

1,501✔
546
        for s.isRunning() && s.remoteLeafNodeStillValid(remote) {
8,412✔
547
                rURL := remote.pickNextURL()
6,911✔
548
                url, err := s.getRandomIP(resolver, rURL.Host, nil)
6,911✔
549
                if err == nil {
13,815✔
550
                        var ipStr string
6,904✔
551
                        if url != rURL.Host {
6,973✔
552
                                ipStr = fmt.Sprintf(" (%s)", url)
69✔
553
                        }
69✔
554
                        // Some test may want to disable remotes from connecting
555
                        if s.isLeafConnectDisabled() {
7,038✔
556
                                s.Debugf("Will not attempt to connect to remote server on %q%s, leafnodes currently disabled", rURL.Host, ipStr)
134✔
557
                                err = ErrLeafNodeDisabled
134✔
558
                        } else {
6,904✔
559
                                s.Debugf("Trying to connect as leafnode to remote server on %q%s", rURL.Host, ipStr)
6,770✔
560
                                conn, err = natsDialTimeout("tcp", url, dialTimeout)
6,770✔
561
                        }
6,770✔
562
                }
563
                if err != nil {
13,027✔
564
                        jitter := time.Duration(rand.Int63n(int64(reconnectDelay)))
6,116✔
565
                        delay := reconnectDelay + jitter
6,116✔
566
                        attempts++
6,116✔
567
                        if s.shouldReportConnectErr(firstConnect, attempts) {
10,405✔
568
                                s.Errorf(connErrFmt, rURL.Host, attempts, err)
4,289✔
569
                        } else {
6,116✔
570
                                s.Debugf(connErrFmt, rURL.Host, attempts, err)
1,827✔
571
                        }
1,827✔
572
                        remote.Lock()
6,116✔
573
                        // if we are using a delay to start migrating assets, kick off a migrate timer.
6,116✔
574
                        if remote.jsMigrateTimer == nil && jetstreamMigrateDelay > 0 {
6,124✔
575
                                remote.jsMigrateTimer = time.AfterFunc(jetstreamMigrateDelay, func() {
16✔
576
                                        s.checkJetStreamMigrate(remote)
8✔
577
                                })
8✔
578
                        }
579
                        remote.Unlock()
6,116✔
580
                        select {
6,116✔
581
                        case <-s.quitCh:
697✔
582
                                remote.cancelMigrateTimer()
697✔
583
                                return
697✔
584
                        case <-time.After(delay):
5,418✔
585
                                // Check if we should migrate any JetStream assets immediately while this remote is down.
5,418✔
586
                                // This will be used if JetStreamClusterMigrateDelay was not set
5,418✔
587
                                if jetstreamMigrateDelay == 0 {
10,757✔
588
                                        s.checkJetStreamMigrate(remote)
5,339✔
589
                                }
5,339✔
590
                                continue
5,418✔
591
                        }
592
                }
593
                remote.cancelMigrateTimer()
795✔
594
                if !s.remoteLeafNodeStillValid(remote) {
795✔
595
                        conn.Close()
×
596
                        return
×
597
                }
×
598

599
                // We have a connection here to a remote server.
600
                // Go ahead and create our leaf node and return.
601
                s.createLeafNode(conn, rURL, remote, nil)
795✔
602

795✔
603
                // Clear any observer states if we had them.
795✔
604
                s.clearObserverState(remote)
795✔
605

795✔
606
                return
795✔
607
        }
608
}
609

610
func (cfg *leafNodeCfg) cancelMigrateTimer() {
1,492✔
611
        cfg.Lock()
1,492✔
612
        stopAndClearTimer(&cfg.jsMigrateTimer)
1,492✔
613
        cfg.Unlock()
1,492✔
614
}
1,492✔
615

616
// This will clear any observer state such that stream or consumer assets on this server can become leaders again.
617
func (s *Server) clearObserverState(remote *leafNodeCfg) {
795✔
618
        s.mu.RLock()
795✔
619
        accName := remote.LocalAccount
795✔
620
        s.mu.RUnlock()
795✔
621

795✔
622
        acc, err := s.LookupAccount(accName)
795✔
623
        if err != nil {
797✔
624
                s.Warnf("Error looking up account [%s] checking for JetStream clear observer state on a leafnode", accName)
2✔
625
                return
2✔
626
        }
2✔
627

628
        acc.jscmMu.Lock()
793✔
629
        defer acc.jscmMu.Unlock()
793✔
630

793✔
631
        // Walk all streams looking for any clustered stream, skip otherwise.
793✔
632
        for _, mset := range acc.streams() {
812✔
633
                node := mset.raftNode()
19✔
634
                if node == nil {
30✔
635
                        // Not R>1
11✔
636
                        continue
11✔
637
                }
638
                // Check consumers
639
                for _, o := range mset.getConsumers() {
10✔
640
                        if n := o.raftNode(); n != nil {
4✔
641
                                // Ensure we can become a leader again.
2✔
642
                                n.SetObserver(false)
2✔
643
                        }
2✔
644
                }
645
                // Ensure we can not become a leader again.
646
                node.SetObserver(false)
8✔
647
        }
648
}
649

650
// Check to see if we should migrate any assets from this account.
651
func (s *Server) checkJetStreamMigrate(remote *leafNodeCfg) {
5,347✔
652
        s.mu.RLock()
5,347✔
653
        accName, shouldMigrate := remote.LocalAccount, remote.JetStreamClusterMigrate
5,347✔
654
        s.mu.RUnlock()
5,347✔
655

5,347✔
656
        if !shouldMigrate {
10,631✔
657
                return
5,284✔
658
        }
5,284✔
659

660
        acc, err := s.LookupAccount(accName)
63✔
661
        if err != nil {
63✔
662
                s.Warnf("Error looking up account [%s] checking for JetStream migration on a leafnode", accName)
×
663
                return
×
664
        }
×
665

666
        acc.jscmMu.Lock()
63✔
667
        defer acc.jscmMu.Unlock()
63✔
668

63✔
669
        // Walk all streams looking for any clustered stream, skip otherwise.
63✔
670
        // If we are the leader force stepdown.
63✔
671
        for _, mset := range acc.streams() {
95✔
672
                node := mset.raftNode()
32✔
673
                if node == nil {
32✔
674
                        // Not R>1
×
675
                        continue
×
676
                }
677
                // Collect any consumers
678
                for _, o := range mset.getConsumers() {
50✔
679
                        if n := o.raftNode(); n != nil {
36✔
680
                                n.StepDown()
18✔
681
                                // Ensure we can not become a leader while in this state.
18✔
682
                                n.SetObserver(true)
18✔
683
                        }
18✔
684
                }
685
                // Stepdown if this stream was leader.
686
                node.StepDown()
32✔
687
                // Ensure we can not become a leader while in this state.
32✔
688
                node.SetObserver(true)
32✔
689
        }
690
}
691

692
// Helper for checking.
693
func (s *Server) isLeafConnectDisabled() bool {
6,904✔
694
        s.mu.RLock()
6,904✔
695
        defer s.mu.RUnlock()
6,904✔
696
        return s.leafDisableConnect
6,904✔
697
}
6,904✔
698

699
// Save off the tlsName for when we use TLS and mix hostnames and IPs. IPs usually
700
// come from the server we connect to.
701
//
702
// We used to save the name only if there was a TLSConfig or scheme equal to "tls".
703
// However, this was causing failures for users that did not set the scheme (and
704
// their remote connections did not have a tls{} block).
705
// We now save the host name regardless in case the remote returns an INFO indicating
706
// that TLS is required.
707
func (cfg *leafNodeCfg) saveTLSHostname(u *url.URL) {
2,430✔
708
        if cfg.tlsName == _EMPTY_ && net.ParseIP(u.Hostname()) == nil {
2,450✔
709
                cfg.tlsName = u.Hostname()
20✔
710
        }
20✔
711
}
712

713
// Save off the username/password for when we connect using a bare URL
714
// that we get from the INFO protocol.
715
func (cfg *leafNodeCfg) saveUserPassword(u *url.URL) {
1,758✔
716
        if cfg.username == _EMPTY_ && u.User != nil {
2,056✔
717
                cfg.username = u.User.Username()
298✔
718
                cfg.password, _ = u.User.Password()
298✔
719
        }
298✔
720
}
721

722
// This starts the leafnode accept loop in a go routine, unless it
723
// is detected that the server has already been shutdown.
724
func (s *Server) startLeafNodeAcceptLoop() {
3,553✔
725
        // Snapshot server options.
3,553✔
726
        opts := s.getOpts()
3,553✔
727

3,553✔
728
        port := opts.LeafNode.Port
3,553✔
729
        if port == -1 {
6,929✔
730
                port = 0
3,376✔
731
        }
3,376✔
732

733
        if s.isShuttingDown() {
3,554✔
734
                return
1✔
735
        }
1✔
736

737
        s.mu.Lock()
3,552✔
738
        hp := net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(port))
3,552✔
739
        l, e := natsListen("tcp", hp)
3,552✔
740
        s.leafNodeListenerErr = e
3,552✔
741
        if e != nil {
3,552✔
742
                s.mu.Unlock()
×
743
                s.Fatalf("Error listening on leafnode port: %d - %v", opts.LeafNode.Port, e)
×
744
                return
×
745
        }
×
746

747
        s.Noticef("Listening for leafnode connections on %s",
3,552✔
748
                net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
3,552✔
749

3,552✔
750
        tlsRequired := opts.LeafNode.TLSConfig != nil
3,552✔
751
        tlsVerify := tlsRequired && opts.LeafNode.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert
3,552✔
752
        // Do not set compression in this Info object, it would possibly cause
3,552✔
753
        // issues when sending asynchronous INFO to the remote.
3,552✔
754
        info := Info{
3,552✔
755
                ID:            s.info.ID,
3,552✔
756
                Name:          s.info.Name,
3,552✔
757
                Version:       s.info.Version,
3,552✔
758
                GitCommit:     gitCommit,
3,552✔
759
                GoVersion:     runtime.Version(),
3,552✔
760
                AuthRequired:  true,
3,552✔
761
                TLSRequired:   tlsRequired,
3,552✔
762
                TLSVerify:     tlsVerify,
3,552✔
763
                MaxPayload:    s.info.MaxPayload, // TODO(dlc) - Allow override?
3,552✔
764
                Headers:       s.supportsHeaders(),
3,552✔
765
                JetStream:     opts.JetStream,
3,552✔
766
                Domain:        opts.JetStreamDomain,
3,552✔
767
                Proto:         s.getServerProto(),
3,552✔
768
                InfoOnConnect: true,
3,552✔
769
                JSApiLevel:    JSApiLevel,
3,552✔
770
        }
3,552✔
771
        // If we have selected a random port...
3,552✔
772
        if port == 0 {
6,927✔
773
                // Write resolved port back to options.
3,375✔
774
                opts.LeafNode.Port = l.Addr().(*net.TCPAddr).Port
3,375✔
775
        }
3,375✔
776

777
        s.leafNodeInfo = info
3,552✔
778
        // Possibly override Host/Port and set IP based on Cluster.Advertise
3,552✔
779
        if err := s.setLeafNodeInfoHostPortAndIP(); err != nil {
3,552✔
780
                s.Fatalf("Error setting leafnode INFO with LeafNode.Advertise value of %s, err=%v", opts.LeafNode.Advertise, err)
×
781
                l.Close()
×
782
                s.mu.Unlock()
×
783
                return
×
784
        }
×
785
        s.leafURLsMap[s.leafNodeInfo.IP]++
3,552✔
786
        s.generateLeafNodeInfoJSON()
3,552✔
787

3,552✔
788
        // Setup state that can enable shutdown
3,552✔
789
        s.leafNodeListener = l
3,552✔
790

3,552✔
791
        // As of now, a server that does not have remotes configured would
3,552✔
792
        // never solicit a connection, so we should not have to warn if
3,552✔
793
        // InsecureSkipVerify is set in main LeafNodes config (since
3,552✔
794
        // this TLS setting matters only when soliciting a connection).
3,552✔
795
        // Still, warn if insecure is set in any of LeafNode block.
3,552✔
796
        // We need to check remotes, even if tls is not required on accept.
3,552✔
797
        warn := tlsRequired && opts.LeafNode.TLSConfig.InsecureSkipVerify
3,552✔
798
        if !warn {
7,100✔
799
                for _, r := range opts.LeafNode.Remotes {
3,742✔
800
                        if r.TLSConfig != nil && r.TLSConfig.InsecureSkipVerify {
195✔
801
                                warn = true
1✔
802
                                break
1✔
803
                        }
804
                }
805
        }
806
        if warn {
3,557✔
807
                s.Warnf(leafnodeTLSInsecureWarning)
5✔
808
        }
5✔
809
        go s.acceptConnections(l, "Leafnode", func(conn net.Conn) { s.createLeafNode(conn, nil, nil, nil) }, nil)
4,389✔
810
        s.mu.Unlock()
3,552✔
811
}
812

813
// RegEx to match a creds file with user JWT and Seed.
814
var credsRe = regexp.MustCompile(`\s*(?:(?:[-]{3,}.*[-]{3,}\r?\n)([\w\-.=]+)(?:\r?\n[-]{3,}.*[-]{3,}(\r?\n|\z)))`)
815

816
// clusterName is provided as argument to avoid lock ordering issues with the locked client c
817
// Lock should be held entering here.
818
func (c *client) sendLeafConnect(clusterName string, headers bool) error {
679✔
819
        // We support basic user/pass and operator based user JWT with signatures.
679✔
820
        cinfo := leafConnectInfo{
679✔
821
                Version:       VERSION,
679✔
822
                ID:            c.srv.info.ID,
679✔
823
                Domain:        c.srv.info.Domain,
679✔
824
                Name:          c.srv.info.Name,
679✔
825
                Hub:           c.leaf.remote.Hub,
679✔
826
                Cluster:       clusterName,
679✔
827
                Headers:       headers,
679✔
828
                JetStream:     c.acc.jetStreamConfigured(),
679✔
829
                DenyPub:       c.leaf.remote.DenyImports,
679✔
830
                Compression:   c.leaf.compression,
679✔
831
                RemoteAccount: c.acc.GetName(),
679✔
832
                Proto:         c.srv.getServerProto(),
679✔
833
                Isolate:       c.leaf.remote.RequestIsolation,
679✔
834
        }
679✔
835

679✔
836
        // If a signature callback is specified, this takes precedence over anything else.
679✔
837
        if cb := c.leaf.remote.SignatureCB; cb != nil {
684✔
838
                nonce := c.nonce
5✔
839
                c.mu.Unlock()
5✔
840
                jwt, sigraw, err := cb(nonce)
5✔
841
                c.mu.Lock()
5✔
842
                if err == nil && c.isClosed() {
6✔
843
                        err = ErrConnectionClosed
1✔
844
                }
1✔
845
                if err != nil {
7✔
846
                        c.Errorf("Error signing the nonce: %v", err)
2✔
847
                        return err
2✔
848
                }
2✔
849
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
3✔
850
                cinfo.JWT, cinfo.Sig = jwt, sig
3✔
851

852
        } else if creds := c.leaf.remote.Credentials; creds != _EMPTY_ {
728✔
853
                // Check for credentials first, that will take precedence..
54✔
854
                c.Debugf("Authenticating with credentials file %q", c.leaf.remote.Credentials)
54✔
855
                contents, err := os.ReadFile(creds)
54✔
856
                if err != nil {
54✔
857
                        c.Errorf("%v", err)
×
858
                        return err
×
859
                }
×
860
                defer wipeSlice(contents)
54✔
861
                items := credsRe.FindAllSubmatch(contents, -1)
54✔
862
                if len(items) < 2 {
54✔
863
                        c.Errorf("Credentials file malformed")
×
864
                        return err
×
865
                }
×
866
                // First result should be the user JWT.
867
                // We copy here so that the file containing the seed will be wiped appropriately.
868
                raw := items[0][1]
54✔
869
                tmp := make([]byte, len(raw))
54✔
870
                copy(tmp, raw)
54✔
871
                // Seed is second item.
54✔
872
                kp, err := nkeys.FromSeed(items[1][1])
54✔
873
                if err != nil {
54✔
874
                        c.Errorf("Credentials file has malformed seed")
×
875
                        return err
×
876
                }
×
877
                // Wipe our key on exit.
878
                defer kp.Wipe()
54✔
879

54✔
880
                sigraw, _ := kp.Sign(c.nonce)
54✔
881
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
54✔
882
                cinfo.JWT = bytesToString(tmp)
54✔
883
                cinfo.Sig = sig
54✔
884
        } else if nkey := c.leaf.remote.Nkey; nkey != _EMPTY_ {
625✔
885
                kp, err := nkeys.FromSeed([]byte(nkey))
5✔
886
                if err != nil {
5✔
887
                        c.Errorf("Remote nkey has malformed seed")
×
888
                        return err
×
889
                }
×
890
                // Wipe our key on exit.
891
                defer kp.Wipe()
5✔
892
                sigraw, _ := kp.Sign(c.nonce)
5✔
893
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
5✔
894
                pkey, _ := kp.PublicKey()
5✔
895
                cinfo.Nkey = pkey
5✔
896
                cinfo.Sig = sig
5✔
897
        }
898
        // In addition, and this is to allow auth callout, set user/password or
899
        // token if applicable.
900
        if userInfo := c.leaf.remote.curURL.User; userInfo != nil {
999✔
901
                // For backward compatibility, if only username is provided, set both
322✔
902
                // Token and User, not just Token.
322✔
903
                cinfo.User = userInfo.Username()
322✔
904
                var ok bool
322✔
905
                cinfo.Pass, ok = userInfo.Password()
322✔
906
                if !ok {
328✔
907
                        cinfo.Token = cinfo.User
6✔
908
                }
6✔
909
        } else if c.leaf.remote.username != _EMPTY_ {
361✔
910
                cinfo.User = c.leaf.remote.username
6✔
911
                cinfo.Pass = c.leaf.remote.password
6✔
912
        }
6✔
913
        b, err := json.Marshal(cinfo)
677✔
914
        if err != nil {
677✔
915
                c.Errorf("Error marshaling CONNECT to remote leafnode: %v\n", err)
×
916
                return err
×
917
        }
×
918
        // Although this call is made before the writeLoop is created,
919
        // we don't really need to send in place. The protocol will be
920
        // sent out by the writeLoop.
921
        c.enqueueProto([]byte(fmt.Sprintf(ConProto, b)))
677✔
922
        return nil
677✔
923
}
924

925
// Makes a deep copy of the LeafNode Info structure.
926
// The server lock is held on entry.
927
func (s *Server) copyLeafNodeInfo() *Info {
2,722✔
928
        clone := s.leafNodeInfo
2,722✔
929
        // Copy the array of urls.
2,722✔
930
        if len(s.leafNodeInfo.LeafNodeURLs) > 0 {
4,937✔
931
                clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...)
2,215✔
932
        }
2,215✔
933
        return &clone
2,722✔
934
}
935

936
// Adds a LeafNode URL that we get when a route connects to the Info structure.
937
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
938
// Returns a boolean indicating if the URL was added or not.
939
// Server lock is held on entry
940
func (s *Server) addLeafNodeURL(urlStr string) bool {
7,036✔
941
        if s.leafURLsMap.addUrl(urlStr) {
14,067✔
942
                s.generateLeafNodeInfoJSON()
7,031✔
943
                return true
7,031✔
944
        }
7,031✔
945
        return false
5✔
946
}
947

948
// Removes a LeafNode URL of the route that is disconnecting from the Info structure.
949
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
950
// Returns a boolean indicating if the URL was removed or not.
951
// Server lock is held on entry.
952
func (s *Server) removeLeafNodeURL(urlStr string) bool {
7,036✔
953
        // Don't need to do this if we are removing the route connection because
7,036✔
954
        // we are shuting down...
7,036✔
955
        if s.isShuttingDown() {
10,727✔
956
                return false
3,691✔
957
        }
3,691✔
958
        if s.leafURLsMap.removeUrl(urlStr) {
6,686✔
959
                s.generateLeafNodeInfoJSON()
3,341✔
960
                return true
3,341✔
961
        }
3,341✔
962
        return false
4✔
963
}
964

965
// Server lock is held on entry
966
func (s *Server) generateLeafNodeInfoJSON() {
13,924✔
967
        s.leafNodeInfo.Cluster = s.cachedClusterName()
13,924✔
968
        s.leafNodeInfo.LeafNodeURLs = s.leafURLsMap.getAsStringSlice()
13,924✔
969
        s.leafNodeInfo.WSConnectURLs = s.websocket.connectURLsMap.getAsStringSlice()
13,924✔
970
        s.leafNodeInfoJSON = generateInfoJSON(&s.leafNodeInfo)
13,924✔
971
}
13,924✔
972

973
// Sends an async INFO protocol so that the connected servers can update
974
// their list of LeafNode urls.
975
func (s *Server) sendAsyncLeafNodeInfo() {
10,372✔
976
        for _, c := range s.leafs {
10,471✔
977
                c.mu.Lock()
99✔
978
                c.enqueueProto(s.leafNodeInfoJSON)
99✔
979
                c.mu.Unlock()
99✔
980
        }
99✔
981
}
982

983
// Called when an inbound leafnode connection is accepted or we create one for a solicited leafnode.
984
func (s *Server) createLeafNode(conn net.Conn, rURL *url.URL, remote *leafNodeCfg, ws *websocket) *client {
1,659✔
985
        // Snapshot server options.
1,659✔
986
        opts := s.getOpts()
1,659✔
987

1,659✔
988
        maxPay := int32(opts.MaxPayload)
1,659✔
989
        maxSubs := int32(opts.MaxSubs)
1,659✔
990
        // For system, maxSubs of 0 means unlimited, so re-adjust here.
1,659✔
991
        if maxSubs == 0 {
3,317✔
992
                maxSubs = -1
1,658✔
993
        }
1,658✔
994
        now := time.Now().UTC()
1,659✔
995

1,659✔
996
        c := &client{srv: s, nc: conn, kind: LEAF, opts: defaultOpts, mpay: maxPay, msubs: maxSubs, start: now, last: now}
1,659✔
997
        // Do not update the smap here, we need to do it in initLeafNodeSmapAndSendSubs
1,659✔
998
        c.leaf = &leaf{}
1,659✔
999

1,659✔
1000
        // If the leafnode subject interest should be isolated, flag it here.
1,659✔
1001
        s.optsMu.RLock()
1,659✔
1002
        if c.leaf.isolated = s.opts.LeafNode.IsolateLeafnodeInterest; !c.leaf.isolated && remote != nil {
2,452✔
1003
                c.leaf.isolated = remote.LocalIsolation
793✔
1004
        }
793✔
1005
        s.optsMu.RUnlock()
1,659✔
1006

1,659✔
1007
        // For accepted LN connections, ws will be != nil if it was accepted
1,659✔
1008
        // through the Websocket port.
1,659✔
1009
        c.ws = ws
1,659✔
1010

1,659✔
1011
        // For remote, check if the scheme starts with "ws", if so, we will initiate
1,659✔
1012
        // a remote Leaf Node connection as a websocket connection.
1,659✔
1013
        if remote != nil && rURL != nil && isWSURL(rURL) {
1,702✔
1014
                remote.RLock()
43✔
1015
                c.ws = &websocket{compress: remote.Websocket.Compression, maskwrite: !remote.Websocket.NoMasking}
43✔
1016
                remote.RUnlock()
43✔
1017
        }
43✔
1018

1019
        // Determines if we are soliciting the connection or not.
1020
        var solicited bool
1,659✔
1021
        var acc *Account
1,659✔
1022
        var remoteSuffix string
1,659✔
1023
        if remote != nil {
2,454✔
1024
                // For now, if lookup fails, we will constantly try
795✔
1025
                // to recreate this LN connection.
795✔
1026
                lacc := remote.LocalAccount
795✔
1027
                var err error
795✔
1028
                acc, err = s.LookupAccount(lacc)
795✔
1029
                if err != nil {
797✔
1030
                        // An account not existing is something that can happen with nats/http account resolver and the account
2✔
1031
                        // has not yet been pushed, or the request failed for other reasons.
2✔
1032
                        // remote needs to be set or retry won't happen
2✔
1033
                        c.leaf.remote = remote
2✔
1034
                        c.closeConnection(MissingAccount)
2✔
1035
                        s.Errorf("Unable to lookup account %s for solicited leafnode connection: %v", lacc, err)
2✔
1036
                        return nil
2✔
1037
                }
2✔
1038
                remoteSuffix = fmt.Sprintf(" for account: %s", acc.traceLabel())
793✔
1039
        }
1040

1041
        c.mu.Lock()
1,657✔
1042
        c.initClient()
1,657✔
1043
        c.Noticef("Leafnode connection created%s %s", remoteSuffix, c.opts.Name)
1,657✔
1044

1,657✔
1045
        var (
1,657✔
1046
                tlsFirst         bool
1,657✔
1047
                tlsFirstFallback time.Duration
1,657✔
1048
                infoTimeout      time.Duration
1,657✔
1049
        )
1,657✔
1050
        if remote != nil {
2,450✔
1051
                solicited = true
793✔
1052
                remote.Lock()
793✔
1053
                c.leaf.remote = remote
793✔
1054
                c.setPermissions(remote.perms)
793✔
1055
                if !c.leaf.remote.Hub {
1,570✔
1056
                        c.leaf.isSpoke = true
777✔
1057
                }
777✔
1058
                tlsFirst = remote.TLSHandshakeFirst
793✔
1059
                infoTimeout = remote.FirstInfoTimeout
793✔
1060
                remote.Unlock()
793✔
1061
                c.acc = acc
793✔
1062
        } else {
864✔
1063
                c.flags.set(expectConnect)
864✔
1064
                if ws != nil {
891✔
1065
                        c.Debugf("Leafnode compression=%v", c.ws.compress)
27✔
1066
                }
27✔
1067
                tlsFirst = opts.LeafNode.TLSHandshakeFirst
864✔
1068
                if f := opts.LeafNode.TLSHandshakeFirstFallback; f > 0 {
865✔
1069
                        tlsFirstFallback = f
1✔
1070
                }
1✔
1071
        }
1072
        c.mu.Unlock()
1,657✔
1073

1,657✔
1074
        var nonce [nonceLen]byte
1,657✔
1075
        var info *Info
1,657✔
1076

1,657✔
1077
        // Grab this before the client lock below.
1,657✔
1078
        if !solicited {
2,521✔
1079
                // Grab server variables
864✔
1080
                s.mu.Lock()
864✔
1081
                info = s.copyLeafNodeInfo()
864✔
1082
                // For tests that want to simulate old servers, do not set the compression
864✔
1083
                // on the INFO protocol if configured with CompressionNotSupported.
864✔
1084
                if cm := opts.LeafNode.Compression.Mode; cm != CompressionNotSupported {
1,727✔
1085
                        info.Compression = cm
863✔
1086
                }
863✔
1087
                // We always send a nonce for LEAF connections. Do not change that without
1088
                // taking into account presence of proxy trusted keys.
1089
                s.generateNonce(nonce[:])
864✔
1090
                s.mu.Unlock()
864✔
1091
        }
1092

1093
        // Grab lock
1094
        c.mu.Lock()
1,657✔
1095

1,657✔
1096
        var preBuf []byte
1,657✔
1097
        if solicited {
2,450✔
1098
                // For websocket connection, we need to send an HTTP request,
793✔
1099
                // and get the response before starting the readLoop to get
793✔
1100
                // the INFO, etc..
793✔
1101
                if c.isWebsocket() {
836✔
1102
                        var err error
43✔
1103
                        var closeReason ClosedState
43✔
1104

43✔
1105
                        preBuf, closeReason, err = c.leafNodeSolicitWSConnection(opts, rURL, remote)
43✔
1106
                        if err != nil {
59✔
1107
                                c.Errorf("Error soliciting websocket connection: %v", err)
16✔
1108
                                c.mu.Unlock()
16✔
1109
                                if closeReason != 0 {
28✔
1110
                                        c.closeConnection(closeReason)
12✔
1111
                                }
12✔
1112
                                return nil
16✔
1113
                        }
1114
                } else {
750✔
1115
                        // If configured to do TLS handshake first
750✔
1116
                        if tlsFirst {
754✔
1117
                                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
5✔
1118
                                        c.mu.Unlock()
1✔
1119
                                        return nil
1✔
1120
                                }
1✔
1121
                        }
1122
                        // We need to wait for the info, but not for too long.
1123
                        c.nc.SetReadDeadline(time.Now().Add(infoTimeout))
749✔
1124
                }
1125

1126
                // We will process the INFO from the readloop and finish by
1127
                // sending the CONNECT and finish registration later.
1128
        } else {
864✔
1129
                // Send our info to the other side.
864✔
1130
                // Remember the nonce we sent here for signatures, etc.
864✔
1131
                c.nonce = make([]byte, nonceLen)
864✔
1132
                copy(c.nonce, nonce[:])
864✔
1133
                info.Nonce = bytesToString(c.nonce)
864✔
1134
                info.CID = c.cid
864✔
1135
                proto := generateInfoJSON(info)
864✔
1136

864✔
1137
                var pre []byte
864✔
1138
                // We need first to check for "TLS First" fallback delay.
864✔
1139
                if tlsFirstFallback > 0 {
865✔
1140
                        // We wait and see if we are getting any data. Since we did not send
1✔
1141
                        // the INFO protocol yet, only clients that use TLS first should be
1✔
1142
                        // sending data (the TLS handshake). We don't really check the content:
1✔
1143
                        // if it is a rogue agent and not an actual client performing the
1✔
1144
                        // TLS handshake, the error will be detected when performing the
1✔
1145
                        // handshake on our side.
1✔
1146
                        pre = make([]byte, 4)
1✔
1147
                        c.nc.SetReadDeadline(time.Now().Add(tlsFirstFallback))
1✔
1148
                        n, _ := io.ReadFull(c.nc, pre[:])
1✔
1149
                        c.nc.SetReadDeadline(time.Time{})
1✔
1150
                        // If we get any data (regardless of possible timeout), we will proceed
1✔
1151
                        // with the TLS handshake.
1✔
1152
                        if n > 0 {
1✔
1153
                                pre = pre[:n]
×
1154
                        } else {
1✔
1155
                                // We did not get anything so we will send the INFO protocol.
1✔
1156
                                pre = nil
1✔
1157
                                // Set the boolean to false for the rest of the function.
1✔
1158
                                tlsFirst = false
1✔
1159
                        }
1✔
1160
                }
1161

1162
                if !tlsFirst {
1,723✔
1163
                        // We have to send from this go routine because we may
859✔
1164
                        // have to block for TLS handshake before we start our
859✔
1165
                        // writeLoop go routine. The other side needs to receive
859✔
1166
                        // this before it can initiate the TLS handshake..
859✔
1167
                        c.sendProtoNow(proto)
859✔
1168

859✔
1169
                        // The above call could have marked the connection as closed (due to TCP error).
859✔
1170
                        if c.isClosed() {
859✔
1171
                                c.mu.Unlock()
×
1172
                                c.closeConnection(WriteError)
×
1173
                                return nil
×
1174
                        }
×
1175
                }
1176

1177
                // Check to see if we need to spin up TLS.
1178
                if !c.isWebsocket() && info.TLSRequired {
933✔
1179
                        // If we have a prebuffer create a multi-reader.
69✔
1180
                        if len(pre) > 0 {
69✔
1181
                                c.nc = &tlsMixConn{c.nc, bytes.NewBuffer(pre)}
×
1182
                        }
×
1183
                        // Perform server-side TLS handshake.
1184
                        if err := c.doTLSServerHandshake(tlsHandshakeLeaf, opts.LeafNode.TLSConfig, opts.LeafNode.TLSTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
111✔
1185
                                c.mu.Unlock()
42✔
1186
                                return nil
42✔
1187
                        }
42✔
1188
                }
1189

1190
                // If the user wants the TLS handshake to occur first, now that it is
1191
                // done, send the INFO protocol.
1192
                if tlsFirst {
825✔
1193
                        c.flags.set(didTLSFirst)
3✔
1194
                        c.sendProtoNow(proto)
3✔
1195
                        if c.isClosed() {
3✔
1196
                                c.mu.Unlock()
×
1197
                                c.closeConnection(WriteError)
×
1198
                                return nil
×
1199
                        }
×
1200
                }
1201

1202
                // Leaf nodes will always require a CONNECT to let us know
1203
                // when we are properly bound to an account.
1204
                //
1205
                // If compression is configured, we can't set the authTimer here because
1206
                // it would cause the parser to fail any incoming protocol that is not a
1207
                // CONNECT (and we need to exchange INFO protocols for compression
1208
                // negotiation). So instead, use the ping timer until we are done with
1209
                // negotiation and can set the auth timer.
1210
                timeout := secondsToDuration(opts.LeafNode.AuthTimeout)
822✔
1211
                if needsCompression(opts.LeafNode.Compression.Mode) {
1,426✔
1212
                        c.ping.tmr = time.AfterFunc(timeout, func() {
612✔
1213
                                c.authTimeout()
8✔
1214
                        })
8✔
1215
                } else {
218✔
1216
                        c.setAuthTimer(timeout)
218✔
1217
                }
218✔
1218
        }
1219

1220
        // Keep track in case server is shutdown before we can successfully register.
1221
        if !s.addToTempClients(c.cid, c) {
1,599✔
1222
                c.mu.Unlock()
1✔
1223
                c.setNoReconnect()
1✔
1224
                c.closeConnection(ServerShutdown)
1✔
1225
                return nil
1✔
1226
        }
1✔
1227

1228
        // Spin up the read loop.
1229
        s.startGoRoutine(func() { c.readLoop(preBuf) })
3,194✔
1230

1231
        // We will spin the write loop for solicited connections only
1232
        // when processing the INFO and after switching to TLS if needed.
1233
        if !solicited {
2,419✔
1234
                s.startGoRoutine(func() { c.writeLoop() })
1,644✔
1235
        }
1236

1237
        c.mu.Unlock()
1,597✔
1238

1,597✔
1239
        return c
1,597✔
1240
}
1241

1242
// Will perform the client-side TLS handshake if needed. Assumes that this
1243
// is called by the solicit side (remote will be non nil). Returns `true`
1244
// if TLS is required, `false` otherwise.
1245
// Lock held on entry.
1246
func (c *client) leafClientHandshakeIfNeeded(remote *leafNodeCfg, opts *Options) (bool, error) {
1,934✔
1247
        // Check if TLS is required and gather TLS config variables.
1,934✔
1248
        tlsRequired, tlsConfig, tlsName, tlsTimeout := c.leafNodeGetTLSConfigForSolicit(remote)
1,934✔
1249
        if !tlsRequired {
3,792✔
1250
                return false, nil
1,858✔
1251
        }
1,858✔
1252

1253
        // If TLS required, peform handshake.
1254
        // Get the URL that was used to connect to the remote server.
1255
        rURL := remote.getCurrentURL()
76✔
1256

76✔
1257
        // Perform the client-side TLS handshake.
76✔
1258
        if resetTLSName, err := c.doTLSClientHandshake(tlsHandshakeLeaf, rURL, tlsConfig, tlsName, tlsTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
111✔
1259
                // Check if we need to reset the remote's TLS name.
35✔
1260
                if resetTLSName {
35✔
1261
                        remote.Lock()
×
1262
                        remote.tlsName = _EMPTY_
×
1263
                        remote.Unlock()
×
1264
                }
×
1265
                return false, err
35✔
1266
        }
1267
        return true, nil
41✔
1268
}
1269

1270
func (c *client) processLeafnodeInfo(info *Info) {
2,675✔
1271
        c.mu.Lock()
2,675✔
1272
        if c.leaf == nil || c.isClosed() {
2,675✔
1273
                c.mu.Unlock()
×
1274
                return
×
1275
        }
×
1276
        s := c.srv
2,675✔
1277
        opts := s.getOpts()
2,675✔
1278
        remote := c.leaf.remote
2,675✔
1279
        didSolicit := remote != nil
2,675✔
1280
        firstINFO := !c.flags.isSet(infoReceived)
2,675✔
1281

2,675✔
1282
        // In case of websocket, the TLS handshake has been already done.
2,675✔
1283
        // So check only for non websocket connections and for configurations
2,675✔
1284
        // where the TLS Handshake was not done first.
2,675✔
1285
        if didSolicit && !c.flags.isSet(handshakeComplete) && !c.isWebsocket() && !remote.TLSHandshakeFirst {
4,562✔
1286
                // If the server requires TLS, we need to set this in the remote
1,887✔
1287
                // otherwise if there is no TLS configuration block for the remote,
1,887✔
1288
                // the solicit side will not attempt to perform the TLS handshake.
1,887✔
1289
                if firstINFO && info.TLSRequired {
1,947✔
1290
                        remote.TLS = true
60✔
1291
                }
60✔
1292
                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
1,917✔
1293
                        c.mu.Unlock()
30✔
1294
                        return
30✔
1295
                }
30✔
1296
        }
1297

1298
        // Check for compression, unless already done.
1299
        if firstINFO && !c.flags.isSet(compressionNegotiated) {
3,957✔
1300
                // Prevent from getting back here.
1,312✔
1301
                c.flags.set(compressionNegotiated)
1,312✔
1302

1,312✔
1303
                var co *CompressionOpts
1,312✔
1304
                if !didSolicit {
1,890✔
1305
                        co = &opts.LeafNode.Compression
578✔
1306
                } else {
1,312✔
1307
                        co = &remote.Compression
734✔
1308
                }
734✔
1309
                if needsCompression(co.Mode) {
2,613✔
1310
                        // Release client lock since following function will need server lock.
1,301✔
1311
                        c.mu.Unlock()
1,301✔
1312
                        compress, err := s.negotiateLeafCompression(c, didSolicit, info.Compression, co)
1,301✔
1313
                        if err != nil {
1,301✔
1314
                                c.sendErrAndErr(err.Error())
×
1315
                                c.closeConnection(ProtocolViolation)
×
1316
                                return
×
1317
                        }
×
1318
                        if compress {
2,474✔
1319
                                // Done for now, will get back another INFO protocol...
1,173✔
1320
                                return
1,173✔
1321
                        }
1,173✔
1322
                        // No compression because one side does not want/can't, so proceed.
1323
                        c.mu.Lock()
128✔
1324
                        // Check that the connection did not close if the lock was released.
128✔
1325
                        if c.isClosed() {
128✔
1326
                                c.mu.Unlock()
×
1327
                                return
×
1328
                        }
×
1329
                } else {
11✔
1330
                        // Coming from an old server, the Compression field would be the empty
11✔
1331
                        // string. For servers that are configured with CompressionNotSupported,
11✔
1332
                        // this makes them behave as old servers.
11✔
1333
                        if info.Compression == _EMPTY_ || co.Mode == CompressionNotSupported {
14✔
1334
                                c.leaf.compression = CompressionNotSupported
3✔
1335
                        } else {
11✔
1336
                                c.leaf.compression = CompressionOff
8✔
1337
                        }
8✔
1338
                }
1339
                // Accepting side does not normally process an INFO protocol during
1340
                // initial connection handshake. So we keep it consistent by returning
1341
                // if we are not soliciting.
1342
                if !didSolicit {
140✔
1343
                        // If we had created the ping timer instead of the auth timer, we will
1✔
1344
                        // clear the ping timer and set the auth timer now that the compression
1✔
1345
                        // negotiation is done.
1✔
1346
                        if info.Compression != _EMPTY_ && c.ping.tmr != nil {
1✔
1347
                                clearTimer(&c.ping.tmr)
×
1348
                                c.setAuthTimer(secondsToDuration(opts.LeafNode.AuthTimeout))
×
1349
                        }
×
1350
                        c.mu.Unlock()
1✔
1351
                        return
1✔
1352
                }
1353
                // Fall through and process the INFO protocol as usual.
1354
        }
1355

1356
        // Note: For now, only the initial INFO has a nonce. We
1357
        // will probably do auto key rotation at some point.
1358
        if firstINFO {
2,246✔
1359
                // Mark that the INFO protocol has been received.
775✔
1360
                c.flags.set(infoReceived)
775✔
1361
                // Prevent connecting to non leafnode port. Need to do this only for
775✔
1362
                // the first INFO, not for async INFO updates...
775✔
1363
                //
775✔
1364
                // Content of INFO sent by the server when accepting a tcp connection.
775✔
1365
                // -------------------------------------------------------------------
775✔
1366
                // Listen Port Of | CID | ClientConnectURLs | LeafNodeURLs | Gateway |
775✔
1367
                // -------------------------------------------------------------------
775✔
1368
                //      CLIENT    |  X* |        X**        |              |         |
775✔
1369
                //      ROUTE     |     |        X**        |      X***    |         |
775✔
1370
                //     GATEWAY    |     |                   |              |    X    |
775✔
1371
                //     LEAFNODE   |  X  |                   |       X      |         |
775✔
1372
                // -------------------------------------------------------------------
775✔
1373
                // *   Not on older servers.
775✔
1374
                // **  Not if "no advertise" is enabled.
775✔
1375
                // *** Not if leafnode's "no advertise" is enabled.
775✔
1376
                //
775✔
1377
                // As seen from above, a solicited LeafNode connection should receive
775✔
1378
                // from the remote server an INFO with CID and LeafNodeURLs. Anything
775✔
1379
                // else should be considered an attempt to connect to a wrong port.
775✔
1380
                if didSolicit && (info.CID == 0 || info.LeafNodeURLs == nil) {
827✔
1381
                        c.mu.Unlock()
52✔
1382
                        c.Errorf(ErrConnectedToWrongPort.Error())
52✔
1383
                        c.closeConnection(WrongPort)
52✔
1384
                        return
52✔
1385
                }
52✔
1386
                // Reject a cluster that contains spaces.
1387
                if info.Cluster != _EMPTY_ && strings.Contains(info.Cluster, " ") {
724✔
1388
                        c.mu.Unlock()
1✔
1389
                        c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
1390
                        c.closeConnection(ProtocolViolation)
1✔
1391
                        return
1✔
1392
                }
1✔
1393
                // Capture a nonce here.
1394
                c.nonce = []byte(info.Nonce)
722✔
1395
                if info.TLSRequired && didSolicit {
752✔
1396
                        remote.TLS = true
30✔
1397
                }
30✔
1398
                supportsHeaders := c.srv.supportsHeaders()
722✔
1399
                c.headers = supportsHeaders && info.Headers
722✔
1400

722✔
1401
                // Remember the remote server.
722✔
1402
                // Pre 2.2.0 servers are not sending their server name.
722✔
1403
                // In that case, use info.ID, which, for those servers, matches
722✔
1404
                // the content of the field `Name` in the leafnode CONNECT protocol.
722✔
1405
                if info.Name == _EMPTY_ {
722✔
1406
                        c.leaf.remoteServer = info.ID
×
1407
                } else {
722✔
1408
                        c.leaf.remoteServer = info.Name
722✔
1409
                }
722✔
1410
                c.leaf.remoteDomain = info.Domain
722✔
1411
                c.leaf.remoteCluster = info.Cluster
722✔
1412
                // We send the protocol version in the INFO protocol.
722✔
1413
                // Keep track of it, so we know if this connection supports message
722✔
1414
                // tracing for instance.
722✔
1415
                c.opts.Protocol = info.Proto
722✔
1416
        }
1417

1418
        // For both initial INFO and async INFO protocols, Possibly
1419
        // update our list of remote leafnode URLs we can connect to.
1420
        if didSolicit && (len(info.LeafNodeURLs) > 0 || len(info.WSConnectURLs) > 0) {
2,751✔
1421
                // Consider the incoming array as the most up-to-date
1,333✔
1422
                // representation of the remote cluster's list of URLs.
1,333✔
1423
                c.updateLeafNodeURLs(info)
1,333✔
1424
        }
1,333✔
1425

1426
        // Check to see if we have permissions updates here.
1427
        if info.Import != nil || info.Export != nil {
1,433✔
1428
                perms := &Permissions{
15✔
1429
                        Publish:   info.Export,
15✔
1430
                        Subscribe: info.Import,
15✔
1431
                }
15✔
1432
                // Check if we have local deny clauses that we need to merge.
15✔
1433
                if remote := c.leaf.remote; remote != nil {
30✔
1434
                        if len(remote.DenyExports) > 0 {
16✔
1435
                                if perms.Publish == nil {
1✔
1436
                                        perms.Publish = &SubjectPermission{}
×
1437
                                }
×
1438
                                perms.Publish.Deny = append(perms.Publish.Deny, remote.DenyExports...)
1✔
1439
                        }
1440
                        if len(remote.DenyImports) > 0 {
16✔
1441
                                if perms.Subscribe == nil {
1✔
1442
                                        perms.Subscribe = &SubjectPermission{}
×
1443
                                }
×
1444
                                perms.Subscribe.Deny = append(perms.Subscribe.Deny, remote.DenyImports...)
1✔
1445
                        }
1446
                }
1447
                c.setPermissions(perms)
15✔
1448
        }
1449

1450
        var resumeConnect bool
1,418✔
1451

1,418✔
1452
        // If this is a remote connection and this is the first INFO protocol,
1,418✔
1453
        // then we need to finish the connect process by sending CONNECT, etc..
1,418✔
1454
        if firstINFO && didSolicit {
2,097✔
1455
                // Clear deadline that was set in createLeafNode while waiting for the INFO.
679✔
1456
                c.nc.SetDeadline(time.Time{})
679✔
1457
                resumeConnect = true
679✔
1458
        } else if !firstINFO && didSolicit {
2,072✔
1459
                c.leaf.remoteAccName = info.RemoteAccount
654✔
1460
        }
654✔
1461

1462
        // Check if we have the remote account information and if so make sure it's stored.
1463
        if info.RemoteAccount != _EMPTY_ {
2,061✔
1464
                s.leafRemoteAccounts.Store(c.acc.Name, info.RemoteAccount)
643✔
1465
        }
643✔
1466
        c.mu.Unlock()
1,418✔
1467

1,418✔
1468
        finishConnect := info.ConnectInfo
1,418✔
1469
        if resumeConnect && s != nil {
2,097✔
1470
                s.leafNodeResumeConnectProcess(c)
679✔
1471
                if !info.InfoOnConnect {
679✔
1472
                        finishConnect = true
×
1473
                }
×
1474
        }
1475
        if finishConnect {
2,061✔
1476
                s.leafNodeFinishConnectProcess(c)
643✔
1477
        }
643✔
1478

1479
        // Check to see if we need to kick any internal source or mirror consumers.
1480
        // This will be a no-op if JetStream not enabled for this server or if the bound account
1481
        // does not have jetstream.
1482
        s.checkInternalSyncConsumers(c.acc)
1,418✔
1483
}
1484

1485
func (s *Server) negotiateLeafCompression(c *client, didSolicit bool, infoCompression string, co *CompressionOpts) (bool, error) {
1,301✔
1486
        // Negotiate the appropriate compression mode (or no compression)
1,301✔
1487
        cm, err := selectCompressionMode(co.Mode, infoCompression)
1,301✔
1488
        if err != nil {
1,301✔
1489
                return false, err
×
1490
        }
×
1491
        c.mu.Lock()
1,301✔
1492
        // For "auto" mode, set the initial compression mode based on RTT
1,301✔
1493
        if cm == CompressionS2Auto {
2,435✔
1494
                if c.rttStart.IsZero() {
2,268✔
1495
                        c.rtt = computeRTT(c.start)
1,134✔
1496
                }
1,134✔
1497
                cm = selectS2AutoModeBasedOnRTT(c.rtt, co.RTTThresholds)
1,134✔
1498
        }
1499
        // Keep track of the negotiated compression mode.
1500
        c.leaf.compression = cm
1,301✔
1501
        cid := c.cid
1,301✔
1502
        var nonce string
1,301✔
1503
        if !didSolicit {
1,878✔
1504
                nonce = bytesToString(c.nonce)
577✔
1505
        }
577✔
1506
        c.mu.Unlock()
1,301✔
1507

1,301✔
1508
        if !needsCompression(cm) {
1,429✔
1509
                return false, nil
128✔
1510
        }
128✔
1511

1512
        // If we end-up doing compression...
1513

1514
        // Generate an INFO with the chosen compression mode.
1515
        s.mu.Lock()
1,173✔
1516
        info := s.copyLeafNodeInfo()
1,173✔
1517
        info.Compression, info.CID, info.Nonce = compressionModeForInfoProtocol(co, cm), cid, nonce
1,173✔
1518
        infoProto := generateInfoJSON(info)
1,173✔
1519
        s.mu.Unlock()
1,173✔
1520

1,173✔
1521
        // If we solicited, then send this INFO protocol BEFORE switching
1,173✔
1522
        // to compression writer. However, if we did not, we send it after.
1,173✔
1523
        c.mu.Lock()
1,173✔
1524
        if didSolicit {
1,769✔
1525
                c.enqueueProto(infoProto)
596✔
1526
                // Make sure it is completely flushed (the pending bytes goes to
596✔
1527
                // 0) before proceeding.
596✔
1528
                for c.out.pb > 0 && !c.isClosed() {
1,192✔
1529
                        c.flushOutbound()
596✔
1530
                }
596✔
1531
        }
1532
        // This is to notify the readLoop that it should switch to a
1533
        // (de)compression reader.
1534
        c.in.flags.set(switchToCompression)
1,173✔
1535
        // Create the compress writer before queueing the INFO protocol for
1,173✔
1536
        // a route that did not solicit. It will make sure that that proto
1,173✔
1537
        // is sent with compression on.
1,173✔
1538
        c.out.cw = s2.NewWriter(nil, s2WriterOptions(cm)...)
1,173✔
1539
        if !didSolicit {
1,750✔
1540
                c.enqueueProto(infoProto)
577✔
1541
        }
577✔
1542
        c.mu.Unlock()
1,173✔
1543
        return true, nil
1,173✔
1544
}
1545

1546
// When getting a leaf node INFO protocol, use the provided
1547
// array of urls to update the list of possible endpoints.
1548
func (c *client) updateLeafNodeURLs(info *Info) {
1,333✔
1549
        cfg := c.leaf.remote
1,333✔
1550
        cfg.Lock()
1,333✔
1551
        defer cfg.Unlock()
1,333✔
1552

1,333✔
1553
        // We have ensured that if a remote has a WS scheme, then all are.
1,333✔
1554
        // So check if first is WS, then add WS URLs, otherwise, add non WS ones.
1,333✔
1555
        if len(cfg.URLs) > 0 && isWSURL(cfg.URLs[0]) {
1,387✔
1556
                // It does not really matter if we use "ws://" or "wss://" here since
54✔
1557
                // we will have already marked that the remote should use TLS anyway.
54✔
1558
                // But use proper scheme for log statements, etc...
54✔
1559
                proto := wsSchemePrefix
54✔
1560
                if cfg.TLS {
54✔
1561
                        proto = wsSchemePrefixTLS
×
1562
                }
×
1563
                c.doUpdateLNURLs(cfg, proto, info.WSConnectURLs)
54✔
1564
                return
54✔
1565
        }
1566
        c.doUpdateLNURLs(cfg, "nats-leaf", info.LeafNodeURLs)
1,279✔
1567
}
1568

1569
func (c *client) doUpdateLNURLs(cfg *leafNodeCfg, scheme string, URLs []string) {
1,333✔
1570
        cfg.urls = make([]*url.URL, 0, 1+len(URLs))
1,333✔
1571
        // Add the ones we receive in the protocol
1,333✔
1572
        for _, surl := range URLs {
3,691✔
1573
                url, err := url.Parse(fmt.Sprintf("%s://%s", scheme, surl))
2,358✔
1574
                if err != nil {
2,358✔
1575
                        // As per below, the URLs we receive should not have contained URL info, so this should be safe to log.
×
1576
                        c.Errorf("Error parsing url %q: %v", surl, err)
×
1577
                        continue
×
1578
                }
1579
                // Do not add if it's the same as what we already have configured.
1580
                var dup bool
2,358✔
1581
                for _, u := range cfg.URLs {
5,960✔
1582
                        // URLs that we receive never have user info, but the
3,602✔
1583
                        // ones that were configured may have. Simply compare
3,602✔
1584
                        // host and port to decide if they are equal or not.
3,602✔
1585
                        if url.Host == u.Host && url.Port() == u.Port() {
5,288✔
1586
                                dup = true
1,686✔
1587
                                break
1,686✔
1588
                        }
1589
                }
1590
                if !dup {
3,030✔
1591
                        cfg.urls = append(cfg.urls, url)
672✔
1592
                        cfg.saveTLSHostname(url)
672✔
1593
                }
672✔
1594
        }
1595
        // Add the configured one
1596
        cfg.urls = append(cfg.urls, cfg.URLs...)
1,333✔
1597
}
1598

1599
// Similar to setInfoHostPortAndGenerateJSON, but for leafNodeInfo.
1600
func (s *Server) setLeafNodeInfoHostPortAndIP() error {
3,552✔
1601
        opts := s.getOpts()
3,552✔
1602
        if opts.LeafNode.Advertise != _EMPTY_ {
3,563✔
1603
                advHost, advPort, err := parseHostPort(opts.LeafNode.Advertise, opts.LeafNode.Port)
11✔
1604
                if err != nil {
11✔
1605
                        return err
×
1606
                }
×
1607
                s.leafNodeInfo.Host = advHost
11✔
1608
                s.leafNodeInfo.Port = advPort
11✔
1609
        } else {
3,541✔
1610
                s.leafNodeInfo.Host = opts.LeafNode.Host
3,541✔
1611
                s.leafNodeInfo.Port = opts.LeafNode.Port
3,541✔
1612
                // If the host is "0.0.0.0" or "::" we need to resolve to a public IP.
3,541✔
1613
                // This will return at most 1 IP.
3,541✔
1614
                hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(s.leafNodeInfo.Host, false)
3,541✔
1615
                if err != nil {
3,541✔
1616
                        return err
×
1617
                }
×
1618
                if hostIsIPAny {
3,847✔
1619
                        if len(ips) == 0 {
306✔
1620
                                s.Errorf("Could not find any non-local IP for leafnode's listen specification %q",
×
1621
                                        s.leafNodeInfo.Host)
×
1622
                        } else {
306✔
1623
                                // Take the first from the list...
306✔
1624
                                s.leafNodeInfo.Host = ips[0]
306✔
1625
                        }
306✔
1626
                }
1627
        }
1628
        // Use just host:port for the IP
1629
        s.leafNodeInfo.IP = net.JoinHostPort(s.leafNodeInfo.Host, strconv.Itoa(s.leafNodeInfo.Port))
3,552✔
1630
        if opts.LeafNode.Advertise != _EMPTY_ {
3,563✔
1631
                s.Noticef("Advertise address for leafnode is set to %s", s.leafNodeInfo.IP)
11✔
1632
        }
11✔
1633
        return nil
3,552✔
1634
}
1635

1636
// Add the connection to the map of leaf nodes.
1637
// If `checkForDup` is true (invoked when a leafnode is accepted), then we check
1638
// if a connection already exists for the same server name and account.
1639
// That can happen when the remote is attempting to reconnect while the accepting
1640
// side did not detect the connection as broken yet.
1641
// But it can also happen when there is a misconfiguration and the remote is
1642
// creating two (or more) connections that bind to the same account on the accept
1643
// side.
1644
// When a duplicate is found, the new connection is accepted and the old is closed
1645
// (this solves the stale connection situation). An error is returned to help the
1646
// remote detect the misconfiguration when the duplicate is the result of that
1647
// misconfiguration.
1648
func (s *Server) addLeafNodeConnection(c *client, srvName, clusterName string, checkForDup bool) {
1,325✔
1649
        var accName string
1,325✔
1650
        c.mu.Lock()
1,325✔
1651
        cid := c.cid
1,325✔
1652
        acc := c.acc
1,325✔
1653
        if acc != nil {
2,650✔
1654
                accName = acc.Name
1,325✔
1655
        }
1,325✔
1656
        myRemoteDomain := c.leaf.remoteDomain
1,325✔
1657
        mySrvName := c.leaf.remoteServer
1,325✔
1658
        remoteAccName := c.leaf.remoteAccName
1,325✔
1659
        myClustName := c.leaf.remoteCluster
1,325✔
1660
        solicited := c.leaf.remote != nil
1,325✔
1661
        c.mu.Unlock()
1,325✔
1662

1,325✔
1663
        var old *client
1,325✔
1664
        s.mu.Lock()
1,325✔
1665
        // We check for empty because in some test we may send empty CONNECT{}
1,325✔
1666
        if checkForDup && srvName != _EMPTY_ {
1,969✔
1667
                for _, ol := range s.leafs {
1,035✔
1668
                        ol.mu.Lock()
391✔
1669
                        // We care here only about non solicited Leafnode. This function
391✔
1670
                        // is more about replacing stale connections than detecting loops.
391✔
1671
                        // We have code for the loop detection elsewhere, which also delays
391✔
1672
                        // attempt to reconnect.
391✔
1673
                        if !ol.isSolicitedLeafNode() && ol.leaf.remoteServer == srvName &&
391✔
1674
                                ol.leaf.remoteCluster == clusterName && ol.acc.Name == accName &&
391✔
1675
                                remoteAccName != _EMPTY_ && ol.leaf.remoteAccName == remoteAccName {
393✔
1676
                                old = ol
2✔
1677
                        }
2✔
1678
                        ol.mu.Unlock()
391✔
1679
                        if old != nil {
393✔
1680
                                break
2✔
1681
                        }
1682
                }
1683
        }
1684
        // Store new connection in the map
1685
        s.leafs[cid] = c
1,325✔
1686
        s.mu.Unlock()
1,325✔
1687
        s.removeFromTempClients(cid)
1,325✔
1688

1,325✔
1689
        // If applicable, evict the old one.
1,325✔
1690
        if old != nil {
1,327✔
1691
                old.sendErrAndErr(DuplicateRemoteLeafnodeConnection.String())
2✔
1692
                old.closeConnection(DuplicateRemoteLeafnodeConnection)
2✔
1693
                c.Warnf("Replacing connection from same server")
2✔
1694
        }
2✔
1695

1696
        srvDecorated := func() string {
1,530✔
1697
                if myClustName == _EMPTY_ {
227✔
1698
                        return mySrvName
22✔
1699
                }
22✔
1700
                return fmt.Sprintf("%s/%s", mySrvName, myClustName)
183✔
1701
        }
1702

1703
        opts := s.getOpts()
1,325✔
1704
        sysAcc := s.SystemAccount()
1,325✔
1705
        js := s.getJetStream()
1,325✔
1706
        var meta *raft
1,325✔
1707
        if js != nil {
1,858✔
1708
                if mg := js.getMetaGroup(); mg != nil {
953✔
1709
                        meta = mg.(*raft)
420✔
1710
                }
420✔
1711
        }
1712
        blockMappingOutgoing := false
1,325✔
1713
        // Deny (non domain) JetStream API traffic unless system account is shared
1,325✔
1714
        // and domain names are identical and extending is not disabled
1,325✔
1715

1,325✔
1716
        // Check if backwards compatibility has been enabled and needs to be acted on
1,325✔
1717
        forceSysAccDeny := false
1,325✔
1718
        if len(opts.JsAccDefaultDomain) > 0 {
1,362✔
1719
                if acc == sysAcc {
48✔
1720
                        for _, d := range opts.JsAccDefaultDomain {
22✔
1721
                                if d == _EMPTY_ {
19✔
1722
                                        // Extending JetStream via leaf node is mutually exclusive with a domain mapping to the empty/default domain.
8✔
1723
                                        // As soon as one mapping to "" is found, disable the ability to extend JS via a leaf node.
8✔
1724
                                        c.Noticef("Not extending remote JetStream domain %q due to presence of empty default domain", myRemoteDomain)
8✔
1725
                                        forceSysAccDeny = true
8✔
1726
                                        break
8✔
1727
                                }
1728
                        }
1729
                } else if domain, ok := opts.JsAccDefaultDomain[accName]; ok && domain == _EMPTY_ {
41✔
1730
                        // for backwards compatibility with old setups that do not have a domain name set
15✔
1731
                        c.Debugf("Skipping deny %q for account %q due to default domain", jsAllAPI, accName)
15✔
1732
                        return
15✔
1733
                }
15✔
1734
        }
1735

1736
        // If the server has JS disabled, it may still be part of a JetStream that could be extended.
1737
        // This is either signaled by js being disabled and a domain set,
1738
        // or in cases where no domain name exists, an extension hint is set.
1739
        // However, this is only relevant in mixed setups.
1740
        //
1741
        // If the system account connects but default domains are present, JetStream can't be extended.
1742
        if opts.JetStreamDomain != myRemoteDomain || (!opts.JetStream && (opts.JetStreamDomain == _EMPTY_ && opts.JetStreamExtHint != jsWillExtend)) ||
1,310✔
1743
                sysAcc == nil || acc == nil || forceSysAccDeny {
2,462✔
1744
                // If domain names mismatch always deny. This applies to system accounts as well as non system accounts.
1,152✔
1745
                // Not having a system account, account or JetStream disabled is considered a mismatch as well.
1,152✔
1746
                if acc != nil && acc == sysAcc {
1,285✔
1747
                        c.Noticef("System account connected from %s", srvDecorated())
133✔
1748
                        c.Noticef("JetStream not extended, domains differ")
133✔
1749
                        c.mergeDenyPermissionsLocked(both, denyAllJs)
133✔
1750
                        // When a remote with a system account is present in a server, unless otherwise disabled, the server will be
133✔
1751
                        // started in observer mode. Now that it is clear that this not used, turn the observer mode off.
133✔
1752
                        if solicited && meta != nil && meta.IsObserver() {
162✔
1753
                                meta.setObserver(false, extNotExtended)
29✔
1754
                                c.Debugf("Turning JetStream metadata controller Observer Mode off")
29✔
1755
                                // Take note that the domain was not extended to avoid this state from startup.
29✔
1756
                                writePeerState(js.config.StoreDir, meta.currentPeerState())
29✔
1757
                                // Meta controller can't be leader yet.
29✔
1758
                                // Yet it is possible that due to observer mode every server already stopped campaigning.
29✔
1759
                                // Therefore this server needs to be kicked into campaigning gear explicitly.
29✔
1760
                                meta.Campaign()
29✔
1761
                        }
29✔
1762
                } else {
1,019✔
1763
                        c.Noticef("JetStream using domains: local %q, remote %q", opts.JetStreamDomain, myRemoteDomain)
1,019✔
1764
                        c.mergeDenyPermissionsLocked(both, denyAllClientJs)
1,019✔
1765
                }
1,019✔
1766
                blockMappingOutgoing = true
1,152✔
1767
        } else if acc == sysAcc {
230✔
1768
                // system account and same domain
72✔
1769
                s.sys.client.Noticef("Extending JetStream domain %q as System Account connected from server %s",
72✔
1770
                        myRemoteDomain, srvDecorated())
72✔
1771
                // In an extension use case, pin leadership to server remotes connect to.
72✔
1772
                // Therefore, server with a remote that are not already in observer mode, need to be put into it.
72✔
1773
                if solicited && meta != nil && !meta.IsObserver() {
76✔
1774
                        meta.setObserver(true, extExtended)
4✔
1775
                        c.Debugf("Turning JetStream metadata controller Observer Mode on - System Account Connected")
4✔
1776
                        // Take note that the domain was not extended to avoid this state next startup.
4✔
1777
                        writePeerState(js.config.StoreDir, meta.currentPeerState())
4✔
1778
                        // If this server is the leader already, step down so a new leader can be elected (that is not an observer)
4✔
1779
                        meta.StepDown()
4✔
1780
                }
4✔
1781
        } else {
86✔
1782
                // This deny is needed in all cases (system account shared or not)
86✔
1783
                // If the system account is shared, jsAllAPI traffic will go through the system account.
86✔
1784
                // So in order to prevent duplicate delivery (from system and actual account) suppress it on the account.
86✔
1785
                // If the system account is NOT shared, jsAllAPI traffic has no business
86✔
1786
                c.Debugf("Adding deny %+v for account %q", denyAllClientJs, accName)
86✔
1787
                c.mergeDenyPermissionsLocked(both, denyAllClientJs)
86✔
1788
        }
86✔
1789
        // If we have a specified JetStream domain we will want to add a mapping to
1790
        // allow access cross domain for each non-system account.
1791
        if opts.JetStreamDomain != _EMPTY_ && opts.JetStream && acc != nil && acc != sysAcc {
1,558✔
1792
                for src, dest := range generateJSMappingTable(opts.JetStreamDomain) {
2,480✔
1793
                        if err := acc.AddMapping(src, dest); err != nil {
2,232✔
1794
                                c.Debugf("Error adding JetStream domain mapping: %s", err.Error())
×
1795
                        } else {
2,232✔
1796
                                c.Debugf("Adding JetStream Domain Mapping %q -> %s to account %q", src, dest, accName)
2,232✔
1797
                        }
2,232✔
1798
                }
1799
                if blockMappingOutgoing {
465✔
1800
                        src := fmt.Sprintf(jsDomainAPI, opts.JetStreamDomain)
217✔
1801
                        // make sure that messages intended for this domain, do not leave the cluster via this leaf node connection
217✔
1802
                        // This is a guard against a miss-config with two identical domain names and will only cover some forms
217✔
1803
                        // of this issue, not all of them.
217✔
1804
                        // This guards against a hub and a spoke having the same domain name.
217✔
1805
                        // But not two spokes having the same one and the request coming from the hub.
217✔
1806
                        c.mergeDenyPermissionsLocked(pub, []string{src})
217✔
1807
                        c.Debugf("Adding deny %q for outgoing messages to account %q", src, accName)
217✔
1808
                }
217✔
1809
        }
1810
}
1811

1812
func (s *Server) removeLeafNodeConnection(c *client) {
1,659✔
1813
        c.mu.Lock()
1,659✔
1814
        cid := c.cid
1,659✔
1815
        if c.leaf != nil {
3,318✔
1816
                if c.leaf.tsubt != nil {
2,870✔
1817
                        c.leaf.tsubt.Stop()
1,211✔
1818
                        c.leaf.tsubt = nil
1,211✔
1819
                }
1,211✔
1820
                if c.leaf.gwSub != nil {
2,300✔
1821
                        s.gwLeafSubs.Remove(c.leaf.gwSub)
641✔
1822
                        // We need to set this to nil for GC to release the connection
641✔
1823
                        c.leaf.gwSub = nil
641✔
1824
                }
641✔
1825
        }
1826
        proxyKey := c.proxyKey
1,659✔
1827
        c.mu.Unlock()
1,659✔
1828
        s.mu.Lock()
1,659✔
1829
        delete(s.leafs, cid)
1,659✔
1830
        if proxyKey != _EMPTY_ {
1,663✔
1831
                s.removeProxiedConn(proxyKey, cid)
4✔
1832
        }
4✔
1833
        s.mu.Unlock()
1,659✔
1834
        s.removeFromTempClients(cid)
1,659✔
1835
}
1836

1837
// Connect information for solicited leafnodes.
1838
type leafConnectInfo struct {
1839
        Version   string   `json:"version,omitempty"`
1840
        Nkey      string   `json:"nkey,omitempty"`
1841
        JWT       string   `json:"jwt,omitempty"`
1842
        Sig       string   `json:"sig,omitempty"`
1843
        User      string   `json:"user,omitempty"`
1844
        Pass      string   `json:"pass,omitempty"`
1845
        Token     string   `json:"auth_token,omitempty"`
1846
        ID        string   `json:"server_id,omitempty"`
1847
        Domain    string   `json:"domain,omitempty"`
1848
        Name      string   `json:"name,omitempty"`
1849
        Hub       bool     `json:"is_hub,omitempty"`
1850
        Cluster   string   `json:"cluster,omitempty"`
1851
        Headers   bool     `json:"headers,omitempty"`
1852
        JetStream bool     `json:"jetstream,omitempty"`
1853
        DenyPub   []string `json:"deny_pub,omitempty"`
1854
        Isolate   bool     `json:"isolate,omitempty"`
1855

1856
        // There was an existing field called:
1857
        // >> Comp bool `json:"compression,omitempty"`
1858
        // that has never been used. With support for compression, we now need
1859
        // a field that is a string. So we use a different json tag:
1860
        Compression string `json:"compress_mode,omitempty"`
1861

1862
        // Just used to detect wrong connection attempts.
1863
        Gateway string `json:"gateway,omitempty"`
1864

1865
        // Tells the accept side which account the remote is binding to.
1866
        RemoteAccount string `json:"remote_account,omitempty"`
1867

1868
        // The accept side of a LEAF connection, unlike ROUTER and GATEWAY, receives
1869
        // only the CONNECT protocol, and no INFO. So we need to send the protocol
1870
        // version as part of the CONNECT. It will indicate if a connection supports
1871
        // some features, such as message tracing.
1872
        // We use `protocol` as the JSON tag, so this is automatically unmarshal'ed
1873
        // in the low level process CONNECT.
1874
        Proto int `json:"protocol,omitempty"`
1875
}
1876

1877
// processLeafNodeConnect will process the inbound connect args.
1878
// Once we are here we are bound to an account, so can send any interest that
1879
// we would have to the other side.
1880
func (c *client) processLeafNodeConnect(s *Server, arg []byte, lang string) error {
689✔
1881
        // Way to detect clients that incorrectly connect to the route listen
689✔
1882
        // port. Client provided "lang" in the CONNECT protocol while LEAFNODEs don't.
689✔
1883
        if lang != _EMPTY_ {
689✔
1884
                c.sendErrAndErr(ErrClientConnectedToLeafNodePort.Error())
×
1885
                c.closeConnection(WrongPort)
×
1886
                return ErrClientConnectedToLeafNodePort
×
1887
        }
×
1888

1889
        // Unmarshal as a leaf node connect protocol
1890
        proto := &leafConnectInfo{}
689✔
1891
        if err := json.Unmarshal(arg, proto); err != nil {
689✔
1892
                return err
×
1893
        }
×
1894

1895
        // Reject a cluster that contains spaces.
1896
        if proto.Cluster != _EMPTY_ && strings.Contains(proto.Cluster, " ") {
690✔
1897
                c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
1898
                c.closeConnection(ProtocolViolation)
1✔
1899
                return ErrClusterNameHasSpaces
1✔
1900
        }
1✔
1901

1902
        // Check for cluster name collisions.
1903
        if cn := s.cachedClusterName(); cn != _EMPTY_ && proto.Cluster != _EMPTY_ && proto.Cluster == cn {
691✔
1904
                c.sendErrAndErr(ErrLeafNodeHasSameClusterName.Error())
3✔
1905
                c.closeConnection(ClusterNamesIdentical)
3✔
1906
                return ErrLeafNodeHasSameClusterName
3✔
1907
        }
3✔
1908

1909
        // Reject if this has Gateway which means that it would be from a gateway
1910
        // connection that incorrectly connects to the leafnode port.
1911
        if proto.Gateway != _EMPTY_ {
685✔
1912
                errTxt := fmt.Sprintf("Rejecting connection from gateway %q on the leafnode port", proto.Gateway)
×
1913
                c.Errorf(errTxt)
×
1914
                c.sendErr(errTxt)
×
1915
                c.closeConnection(WrongGateway)
×
1916
                return ErrWrongGateway
×
1917
        }
×
1918

1919
        if mv := s.getOpts().LeafNode.MinVersion; mv != _EMPTY_ {
687✔
1920
                major, minor, update, _ := versionComponents(mv)
2✔
1921
                if !versionAtLeast(proto.Version, major, minor, update) {
3✔
1922
                        // We are going to send back an INFO because otherwise recent
1✔
1923
                        // versions of the remote server would simply break the connection
1✔
1924
                        // after 2 seconds if not receiving it. Instead, we want the
1✔
1925
                        // other side to just "stall" until we finish waiting for the holding
1✔
1926
                        // period and close the connection below.
1✔
1927
                        s.sendPermsAndAccountInfo(c)
1✔
1928
                        c.sendErrAndErr(fmt.Sprintf("connection rejected since minimum version required is %q", mv))
1✔
1929
                        select {
1✔
1930
                        case <-c.srv.quitCh:
1✔
1931
                        case <-time.After(leafNodeWaitBeforeClose):
×
1932
                        }
1933
                        c.closeConnection(MinimumVersionRequired)
1✔
1934
                        return ErrMinimumVersionRequired
1✔
1935
                }
1936
        }
1937

1938
        // Check if this server supports headers.
1939
        supportHeaders := c.srv.supportsHeaders()
684✔
1940

684✔
1941
        c.mu.Lock()
684✔
1942
        // Leaf Nodes do not do echo or verbose or pedantic.
684✔
1943
        c.opts.Verbose = false
684✔
1944
        c.opts.Echo = false
684✔
1945
        c.opts.Pedantic = false
684✔
1946
        // This inbound connection will be marked as supporting headers if this server
684✔
1947
        // support headers and the remote has sent in the CONNECT protocol that it does
684✔
1948
        // support headers too.
684✔
1949
        c.headers = supportHeaders && proto.Headers
684✔
1950
        // If the compression level is still not set, set it based on what has been
684✔
1951
        // given to us in the CONNECT protocol.
684✔
1952
        if c.leaf.compression == _EMPTY_ {
819✔
1953
                // But if proto.Compression is _EMPTY_, set it to CompressionNotSupported
135✔
1954
                if proto.Compression == _EMPTY_ {
175✔
1955
                        c.leaf.compression = CompressionNotSupported
40✔
1956
                } else {
135✔
1957
                        c.leaf.compression = proto.Compression
95✔
1958
                }
95✔
1959
        }
1960

1961
        // Remember the remote server.
1962
        c.leaf.remoteServer = proto.Name
684✔
1963
        // Remember the remote account name
684✔
1964
        c.leaf.remoteAccName = proto.RemoteAccount
684✔
1965
        // Remember if the leafnode requested isolation.
684✔
1966
        c.leaf.isolated = c.leaf.isolated || proto.Isolate
684✔
1967

684✔
1968
        // If the other side has declared itself a hub, so we will take on the spoke role.
684✔
1969
        if proto.Hub {
700✔
1970
                c.leaf.isSpoke = true
16✔
1971
        }
16✔
1972

1973
        // The soliciting side is part of a cluster.
1974
        if proto.Cluster != _EMPTY_ {
1,214✔
1975
                c.leaf.remoteCluster = proto.Cluster
530✔
1976
        }
530✔
1977

1978
        c.leaf.remoteDomain = proto.Domain
684✔
1979

684✔
1980
        // When a leaf solicits a connection to a hub, the perms that it will use on the soliciting leafnode's
684✔
1981
        // behalf are correct for them, but inside the hub need to be reversed since data is flowing in the opposite direction.
684✔
1982
        if !c.isSolicitedLeafNode() && c.perms != nil {
700✔
1983
                sp, pp := c.perms.sub, c.perms.pub
16✔
1984
                c.perms.sub, c.perms.pub = pp, sp
16✔
1985
                if c.opts.Import != nil {
31✔
1986
                        c.darray = c.opts.Import.Deny
15✔
1987
                } else {
16✔
1988
                        c.darray = nil
1✔
1989
                }
1✔
1990
        }
1991

1992
        // Set the Ping timer
1993
        c.setFirstPingTimer()
684✔
1994

684✔
1995
        // If we received pub deny permissions from the other end, merge with existing ones.
684✔
1996
        c.mergeDenyPermissions(pub, proto.DenyPub)
684✔
1997

684✔
1998
        acc := c.acc
684✔
1999
        c.mu.Unlock()
684✔
2000

684✔
2001
        // Register the cluster, even if empty, as long as we are acting as a hub.
684✔
2002
        if !proto.Hub {
1,352✔
2003
                acc.registerLeafNodeCluster(proto.Cluster)
668✔
2004
        }
668✔
2005

2006
        // Add in the leafnode here since we passed through auth at this point.
2007
        s.addLeafNodeConnection(c, proto.Name, proto.Cluster, true)
684✔
2008

684✔
2009
        // If we have permissions bound to this leafnode we need to send then back to the
684✔
2010
        // origin server for local enforcement.
684✔
2011
        s.sendPermsAndAccountInfo(c)
684✔
2012

684✔
2013
        // Create and initialize the smap since we know our bound account now.
684✔
2014
        // This will send all registered subs too.
684✔
2015
        s.initLeafNodeSmapAndSendSubs(c)
684✔
2016

684✔
2017
        // Announce the account connect event for a leaf node.
684✔
2018
        // This will be a no-op as needed.
684✔
2019
        s.sendLeafNodeConnect(c.acc)
684✔
2020

684✔
2021
        // Check to see if we need to kick any internal source or mirror consumers.
684✔
2022
        // This will be a no-op if JetStream not enabled for this server or if the bound account
684✔
2023
        // does not have jetstream.
684✔
2024
        s.checkInternalSyncConsumers(acc)
684✔
2025

684✔
2026
        return nil
684✔
2027
}
2028

2029
// checkInternalSyncConsumers
2030
func (s *Server) checkInternalSyncConsumers(acc *Account) {
2,102✔
2031
        // Grab our js
2,102✔
2032
        js := s.getJetStream()
2,102✔
2033

2,102✔
2034
        // Only applicable if we have JS and the leafnode has JS as well.
2,102✔
2035
        // We check for remote JS outside.
2,102✔
2036
        if !js.isEnabled() || acc == nil {
3,324✔
2037
                return
1,222✔
2038
        }
1,222✔
2039

2040
        // We will check all streams in our local account. They must be a leader and
2041
        // be sourcing or mirroring. We will check the external config on the stream itself
2042
        // if this is cross domain, or if the remote domain is empty, meaning we might be
2043
        // extending the system across this leafnode connection and hence we would be extending
2044
        // our own domain.
2045
        jsa := js.lookupAccount(acc)
880✔
2046
        if jsa == nil {
1,220✔
2047
                return
340✔
2048
        }
340✔
2049

2050
        var streams []*stream
540✔
2051
        jsa.mu.RLock()
540✔
2052
        for _, mset := range jsa.streams {
597✔
2053
                mset.cfgMu.RLock()
57✔
2054
                // We need to have a mirror or source defined.
57✔
2055
                // We do not want to force another lock here to look for leader status,
57✔
2056
                // so collect and after we release jsa will make sure.
57✔
2057
                if mset.cfg.Mirror != nil || len(mset.cfg.Sources) > 0 {
69✔
2058
                        streams = append(streams, mset)
12✔
2059
                }
12✔
2060
                mset.cfgMu.RUnlock()
57✔
2061
        }
2062
        jsa.mu.RUnlock()
540✔
2063

540✔
2064
        // Now loop through all candidates and check if we are the leader and have NOT
540✔
2065
        // created the sync up consumer.
540✔
2066
        for _, mset := range streams {
552✔
2067
                mset.retryDisconnectedSyncConsumers()
12✔
2068
        }
12✔
2069
}
2070

2071
// Returns the remote cluster name. This is set only once so does not require a lock.
2072
func (c *client) remoteCluster() string {
216,255✔
2073
        if c.leaf == nil {
216,255✔
2074
                return _EMPTY_
×
2075
        }
×
2076
        return c.leaf.remoteCluster
216,255✔
2077
}
2078

2079
// Sends back an info block to the soliciting leafnode to let it know about
2080
// its permission settings for local enforcement.
2081
func (s *Server) sendPermsAndAccountInfo(c *client) {
685✔
2082
        // Copy
685✔
2083
        s.mu.Lock()
685✔
2084
        info := s.copyLeafNodeInfo()
685✔
2085
        s.mu.Unlock()
685✔
2086
        c.mu.Lock()
685✔
2087
        info.CID = c.cid
685✔
2088
        info.Import = c.opts.Import
685✔
2089
        info.Export = c.opts.Export
685✔
2090
        info.RemoteAccount = c.acc.Name
685✔
2091
        // s.SystemAccount() uses an atomic operation and does not get the server lock, so this is safe.
685✔
2092
        info.IsSystemAccount = c.acc == s.SystemAccount()
685✔
2093
        info.ConnectInfo = true
685✔
2094
        c.enqueueProto(generateInfoJSON(info))
685✔
2095
        c.mu.Unlock()
685✔
2096
}
685✔
2097

2098
// Snapshot the current subscriptions from the sublist into our smap which
2099
// we will keep updated from now on.
2100
// Also send the registered subscriptions.
2101
func (s *Server) initLeafNodeSmapAndSendSubs(c *client) {
1,325✔
2102
        acc := c.acc
1,325✔
2103
        if acc == nil {
1,325✔
2104
                c.Debugf("Leafnode does not have an account bound")
×
2105
                return
×
2106
        }
×
2107
        // Collect all account subs here.
2108
        _subs := [1024]*subscription{}
1,325✔
2109
        subs := _subs[:0]
1,325✔
2110
        ims := []string{}
1,325✔
2111

1,325✔
2112
        // Hold the client lock otherwise there can be a race and miss some subs.
1,325✔
2113
        c.mu.Lock()
1,325✔
2114
        defer c.mu.Unlock()
1,325✔
2115

1,325✔
2116
        acc.mu.RLock()
1,325✔
2117
        accName := acc.Name
1,325✔
2118
        accNTag := acc.nameTag
1,325✔
2119

1,325✔
2120
        // To make printing look better when no friendly name present.
1,325✔
2121
        if accNTag != _EMPTY_ {
1,336✔
2122
                accNTag = "/" + accNTag
11✔
2123
        }
11✔
2124

2125
        // If we are solicited we only send interest for local clients.
2126
        if c.isSpokeLeafNode() {
1,966✔
2127
                acc.sl.localSubs(&subs, true)
641✔
2128
        } else {
1,325✔
2129
                acc.sl.All(&subs)
684✔
2130
        }
684✔
2131

2132
        // Check if we have an existing service import reply.
2133
        siReply := copyBytes(acc.siReply)
1,325✔
2134

1,325✔
2135
        // Since leaf nodes only send on interest, if the bound
1,325✔
2136
        // account has import services we need to send those over.
1,325✔
2137
        for isubj := range acc.imports.services {
6,279✔
2138
                if c.isSpokeLeafNode() && !c.canSubscribe(isubj) {
5,237✔
2139
                        c.Debugf("Not permitted to import service %q on behalf of %s%s", isubj, accName, accNTag)
283✔
2140
                        continue
283✔
2141
                }
2142
                ims = append(ims, isubj)
4,671✔
2143
        }
2144
        // Likewise for mappings.
2145
        for _, m := range acc.mappings {
3,677✔
2146
                if c.isSpokeLeafNode() && !c.canSubscribe(m.src) {
2,388✔
2147
                        c.Debugf("Not permitted to import mapping %q on behalf of %s%s", m.src, accName, accNTag)
36✔
2148
                        continue
36✔
2149
                }
2150
                ims = append(ims, m.src)
2,316✔
2151
        }
2152

2153
        // Create a unique subject that will be used for loop detection.
2154
        lds := acc.lds
1,325✔
2155
        acc.mu.RUnlock()
1,325✔
2156

1,325✔
2157
        // Check if we have to create the LDS.
1,325✔
2158
        if lds == _EMPTY_ {
2,355✔
2159
                lds = leafNodeLoopDetectionSubjectPrefix + nuid.Next()
1,030✔
2160
                acc.mu.Lock()
1,030✔
2161
                acc.lds = lds
1,030✔
2162
                acc.mu.Unlock()
1,030✔
2163
        }
1,030✔
2164

2165
        // Now check for gateway interest. Leafnodes will put this into
2166
        // the proper mode to propagate, but they are not held in the account.
2167
        gwsa := [16]*client{}
1,325✔
2168
        gws := gwsa[:0]
1,325✔
2169
        s.getOutboundGatewayConnections(&gws)
1,325✔
2170
        for _, cgw := range gws {
1,407✔
2171
                cgw.mu.Lock()
82✔
2172
                gw := cgw.gw
82✔
2173
                cgw.mu.Unlock()
82✔
2174
                if gw != nil {
164✔
2175
                        if ei, _ := gw.outsim.Load(accName); ei != nil {
164✔
2176
                                if e := ei.(*outsie); e != nil && e.sl != nil {
164✔
2177
                                        e.sl.All(&subs)
82✔
2178
                                }
82✔
2179
                        }
2180
                }
2181
        }
2182

2183
        applyGlobalRouting := s.gateway.enabled
1,325✔
2184
        if c.isSpokeLeafNode() {
1,966✔
2185
                // Add a fake subscription for this solicited leafnode connection
641✔
2186
                // so that we can send back directly for mapped GW replies.
641✔
2187
                // We need to keep track of this subscription so it can be removed
641✔
2188
                // when the connection is closed so that the GC can release it.
641✔
2189
                c.leaf.gwSub = &subscription{client: c, subject: []byte(gwReplyPrefix + ">")}
641✔
2190
                c.srv.gwLeafSubs.Insert(c.leaf.gwSub)
641✔
2191
        }
641✔
2192

2193
        // Now walk the results and add them to our smap
2194
        rc := c.leaf.remoteCluster
1,325✔
2195
        c.leaf.smap = make(map[string]int32)
1,325✔
2196
        for _, sub := range subs {
39,091✔
2197
                // Check perms regardless of role.
37,766✔
2198
                if c.perms != nil && !c.canSubscribe(string(sub.subject)) {
40,083✔
2199
                        c.Debugf("Not permitted to subscribe to %q on behalf of %s%s", sub.subject, accName, accNTag)
2,317✔
2200
                        continue
2,317✔
2201
                }
2202
                // Don't advertise interest from leafnodes to other isolated leafnodes.
2203
                if sub.client.kind == LEAF && c.isIsolatedLeafNode() {
35,464✔
2204
                        continue
15✔
2205
                }
2206
                // We ignore ourselves here.
2207
                // Also don't add the subscription if it has a origin cluster and the
2208
                // cluster name matches the one of the client we are sending to.
2209
                if c != sub.client && (sub.origin == nil || (bytesToString(sub.origin) != rc)) {
65,591✔
2210
                        count := int32(1)
30,157✔
2211
                        if len(sub.queue) > 0 && sub.qw > 0 {
30,167✔
2212
                                count = sub.qw
10✔
2213
                        }
10✔
2214
                        c.leaf.smap[keyFromSub(sub)] += count
30,157✔
2215
                        if c.leaf.tsub == nil {
31,405✔
2216
                                c.leaf.tsub = make(map[*subscription]struct{})
1,248✔
2217
                        }
1,248✔
2218
                        c.leaf.tsub[sub] = struct{}{}
30,157✔
2219
                }
2220
        }
2221
        // FIXME(dlc) - We need to update appropriately on an account claims update.
2222
        for _, isubj := range ims {
8,312✔
2223
                c.leaf.smap[isubj]++
6,987✔
2224
        }
6,987✔
2225
        // If we have gateways enabled we need to make sure the other side sends us responses
2226
        // that have been augmented from the original subscription.
2227
        // TODO(dlc) - Should we lock this down more?
2228
        if applyGlobalRouting {
1,428✔
2229
                c.leaf.smap[oldGWReplyPrefix+"*.>"]++
103✔
2230
                c.leaf.smap[gwReplyPrefix+">"]++
103✔
2231
        }
103✔
2232
        // Detect loops by subscribing to a specific subject and checking
2233
        // if this sub is coming back to us.
2234
        c.leaf.smap[lds]++
1,325✔
2235

1,325✔
2236
        // Check if we need to add an existing siReply to our map.
1,325✔
2237
        // This will be a prefix so add on the wildcard.
1,325✔
2238
        if siReply != nil {
1,342✔
2239
                wcsub := append(siReply, '>')
17✔
2240
                c.leaf.smap[string(wcsub)]++
17✔
2241
        }
17✔
2242
        // Queue all protocols. There is no max pending limit for LN connection,
2243
        // so we don't need chunking. The writes will happen from the writeLoop.
2244
        var b bytes.Buffer
1,325✔
2245
        for key, n := range c.leaf.smap {
27,897✔
2246
                c.writeLeafSub(&b, key, n)
26,572✔
2247
        }
26,572✔
2248
        if b.Len() > 0 {
2,650✔
2249
                c.enqueueProto(b.Bytes())
1,325✔
2250
        }
1,325✔
2251
        if c.leaf.tsub != nil {
2,574✔
2252
                // Clear the tsub map after 5 seconds.
1,249✔
2253
                c.leaf.tsubt = time.AfterFunc(5*time.Second, func() {
1,287✔
2254
                        c.mu.Lock()
38✔
2255
                        if c.leaf != nil {
76✔
2256
                                c.leaf.tsub = nil
38✔
2257
                                c.leaf.tsubt = nil
38✔
2258
                        }
38✔
2259
                        c.mu.Unlock()
38✔
2260
                })
2261
        }
2262
}
2263

2264
// updateInterestForAccountOnGateway called from gateway code when processing RS+ and RS-.
2265
func (s *Server) updateInterestForAccountOnGateway(accName string, sub *subscription, delta int32) {
197,774✔
2266
        acc, err := s.LookupAccount(accName)
197,774✔
2267
        if acc == nil || err != nil {
197,933✔
2268
                s.Debugf("No or bad account for %q, failed to update interest from gateway", accName)
159✔
2269
                return
159✔
2270
        }
159✔
2271
        acc.updateLeafNodes(sub, delta)
197,615✔
2272
}
2273

2274
// updateLeafNodesEx will make sure to update the account smap for the subscription.
2275
// Will also forward to all leaf nodes as needed.
2276
// If `hubOnly` is true, then will update only leaf nodes that connect to this server
2277
// (that is, for which this server acts as a hub to them).
2278
func (acc *Account) updateLeafNodesEx(sub *subscription, delta int32, hubOnly bool) {
2,456,394✔
2279
        if acc == nil || sub == nil {
2,456,394✔
2280
                return
×
2281
        }
×
2282

2283
        // We will do checks for no leafnodes and same cluster here inline and under the
2284
        // general account read lock.
2285
        // If we feel we need to update the leafnodes we will do that out of line to avoid
2286
        // blocking routes or GWs.
2287

2288
        acc.mu.RLock()
2,456,394✔
2289
        // First check if we even have leafnodes here.
2,456,394✔
2290
        if acc.nleafs == 0 {
4,844,390✔
2291
                acc.mu.RUnlock()
2,387,996✔
2292
                return
2,387,996✔
2293
        }
2,387,996✔
2294

2295
        // Is this a loop detection subject.
2296
        isLDS := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
68,398✔
2297

68,398✔
2298
        // Capture the cluster even if its empty.
68,398✔
2299
        var cluster string
68,398✔
2300
        if sub.origin != nil {
117,937✔
2301
                cluster = bytesToString(sub.origin)
49,539✔
2302
        }
49,539✔
2303

2304
        // If we have an isolated cluster we can return early, as long as it is not a loop detection subject.
2305
        // Empty clusters will return false for the check.
2306
        if !isLDS && acc.isLeafNodeClusterIsolated(cluster) {
89,470✔
2307
                acc.mu.RUnlock()
21,072✔
2308
                return
21,072✔
2309
        }
21,072✔
2310

2311
        // We can release the general account lock.
2312
        acc.mu.RUnlock()
47,326✔
2313

47,326✔
2314
        // We can hold the list lock here to avoid having to copy a large slice.
47,326✔
2315
        acc.lmu.RLock()
47,326✔
2316
        defer acc.lmu.RUnlock()
47,326✔
2317

47,326✔
2318
        // Do this once.
47,326✔
2319
        subject := string(sub.subject)
47,326✔
2320

47,326✔
2321
        // Walk the connected leafnodes.
47,326✔
2322
        for _, ln := range acc.lleafs {
105,520✔
2323
                if ln == sub.client {
88,886✔
2324
                        continue
30,692✔
2325
                }
2326
                ln.mu.Lock()
27,502✔
2327
                // Don't advertise interest from leafnodes to other isolated leafnodes.
27,502✔
2328
                if sub.client.kind == LEAF && ln.isIsolatedLeafNode() {
27,538✔
2329
                        ln.mu.Unlock()
36✔
2330
                        continue
36✔
2331
                }
2332
                // If `hubOnly` is true, it means that we want to update only leafnodes
2333
                // that connect to this server (so isHubLeafNode() would return `true`).
2334
                if hubOnly && !ln.isHubLeafNode() {
27,472✔
2335
                        ln.mu.Unlock()
6✔
2336
                        continue
6✔
2337
                }
2338
                // Check to make sure this sub does not have an origin cluster that matches the leafnode.
2339
                // If skipped, make sure that we still let go the "$LDS." subscription that allows
2340
                // the detection of loops as long as different cluster.
2341
                clusterDifferent := cluster != ln.remoteCluster()
27,460✔
2342
                if (isLDS && clusterDifferent) || ((cluster == _EMPTY_ || clusterDifferent) && (delta <= 0 || ln.canSubscribe(subject))) {
50,600✔
2343
                        ln.updateSmap(sub, delta, isLDS)
23,140✔
2344
                }
23,140✔
2345
                ln.mu.Unlock()
27,460✔
2346
        }
2347
}
2348

2349
// updateLeafNodes will make sure to update the account smap for the subscription.
2350
// Will also forward to all leaf nodes as needed.
2351
func (acc *Account) updateLeafNodes(sub *subscription, delta int32) {
2,456,371✔
2352
        acc.updateLeafNodesEx(sub, delta, false)
2,456,371✔
2353
}
2,456,371✔
2354

2355
// This will make an update to our internal smap and determine if we should send out
2356
// an interest update to the remote side.
2357
// Lock should be held.
2358
func (c *client) updateSmap(sub *subscription, delta int32, isLDS bool) {
23,140✔
2359
        if c.leaf.smap == nil {
23,168✔
2360
                return
28✔
2361
        }
28✔
2362

2363
        // If we are solicited make sure this is a local client or a non-solicited leaf node
2364
        skind := sub.client.kind
23,112✔
2365
        updateClient := skind == CLIENT || skind == SYSTEM || skind == JETSTREAM || skind == ACCOUNT
23,112✔
2366
        if !isLDS && c.isSpokeLeafNode() && !(updateClient || (skind == LEAF && !sub.client.isSpokeLeafNode())) {
31,118✔
2367
                return
8,006✔
2368
        }
8,006✔
2369

2370
        // For additions, check if that sub has just been processed during initLeafNodeSmapAndSendSubs
2371
        if delta > 0 && c.leaf.tsub != nil {
22,462✔
2372
                if _, present := c.leaf.tsub[sub]; present {
7,360✔
2373
                        delete(c.leaf.tsub, sub)
4✔
2374
                        if len(c.leaf.tsub) == 0 {
4✔
2375
                                c.leaf.tsub = nil
×
2376
                                c.leaf.tsubt.Stop()
×
2377
                                c.leaf.tsubt = nil
×
2378
                        }
×
2379
                        return
4✔
2380
                }
2381
        }
2382

2383
        key := keyFromSub(sub)
15,102✔
2384
        n, ok := c.leaf.smap[key]
15,102✔
2385
        if delta < 0 && !ok {
16,025✔
2386
                return
923✔
2387
        }
923✔
2388

2389
        // We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
2390
        update := sub.queue != nil || (n <= 0 && n+delta > 0) || (n > 0 && n+delta <= 0)
14,179✔
2391
        n += delta
14,179✔
2392
        if n > 0 {
24,641✔
2393
                c.leaf.smap[key] = n
10,462✔
2394
        } else {
14,179✔
2395
                delete(c.leaf.smap, key)
3,717✔
2396
        }
3,717✔
2397
        if update {
24,089✔
2398
                c.sendLeafNodeSubUpdate(key, n)
9,910✔
2399
        }
9,910✔
2400
}
2401

2402
// Used to force add subjects to the subject map.
2403
func (c *client) forceAddToSmap(subj string) {
4✔
2404
        c.mu.Lock()
4✔
2405
        defer c.mu.Unlock()
4✔
2406

4✔
2407
        if c.leaf.smap == nil {
4✔
2408
                return
×
2409
        }
×
2410
        n := c.leaf.smap[subj]
4✔
2411
        if n != 0 {
5✔
2412
                return
1✔
2413
        }
1✔
2414
        // Place into the map since it was not there.
2415
        c.leaf.smap[subj] = 1
3✔
2416
        c.sendLeafNodeSubUpdate(subj, 1)
3✔
2417
}
2418

2419
// Used to force remove a subject from the subject map.
2420
func (c *client) forceRemoveFromSmap(subj string) {
1✔
2421
        c.mu.Lock()
1✔
2422
        defer c.mu.Unlock()
1✔
2423

1✔
2424
        if c.leaf.smap == nil {
1✔
2425
                return
×
2426
        }
×
2427
        n := c.leaf.smap[subj]
1✔
2428
        if n == 0 {
1✔
2429
                return
×
2430
        }
×
2431
        n--
1✔
2432
        if n == 0 {
2✔
2433
                // Remove is now zero
1✔
2434
                delete(c.leaf.smap, subj)
1✔
2435
                c.sendLeafNodeSubUpdate(subj, 0)
1✔
2436
        } else {
1✔
2437
                c.leaf.smap[subj] = n
×
2438
        }
×
2439
}
2440

2441
// Send the subscription interest change to the other side.
2442
// Lock should be held.
2443
func (c *client) sendLeafNodeSubUpdate(key string, n int32) {
9,914✔
2444
        // If we are a spoke, we need to check if we are allowed to send this subscription over to the hub.
9,914✔
2445
        if c.isSpokeLeafNode() {
12,366✔
2446
                checkPerms := true
2,452✔
2447
                if len(key) > 0 && (key[0] == '$' || key[0] == '_') {
3,923✔
2448
                        if strings.HasPrefix(key, leafNodeLoopDetectionSubjectPrefix) ||
1,471✔
2449
                                strings.HasPrefix(key, oldGWReplyPrefix) ||
1,471✔
2450
                                strings.HasPrefix(key, gwReplyPrefix) {
1,560✔
2451
                                checkPerms = false
89✔
2452
                        }
89✔
2453
                }
2454
                if checkPerms {
4,815✔
2455
                        var subject string
2,363✔
2456
                        if sep := strings.IndexByte(key, ' '); sep != -1 {
2,856✔
2457
                                subject = key[:sep]
493✔
2458
                        } else {
2,363✔
2459
                                subject = key
1,870✔
2460
                        }
1,870✔
2461
                        if !c.canSubscribe(subject) {
2,363✔
2462
                                return
×
2463
                        }
×
2464
                }
2465
        }
2466
        // If we are here we can send over to the other side.
2467
        _b := [64]byte{}
9,914✔
2468
        b := bytes.NewBuffer(_b[:0])
9,914✔
2469
        c.writeLeafSub(b, key, n)
9,914✔
2470
        c.enqueueProto(b.Bytes())
9,914✔
2471
}
2472

2473
// Helper function to build the key.
2474
func keyFromSub(sub *subscription) string {
46,292✔
2475
        var sb strings.Builder
46,292✔
2476
        sb.Grow(len(sub.subject) + len(sub.queue) + 1)
46,292✔
2477
        sb.Write(sub.subject)
46,292✔
2478
        if sub.queue != nil {
50,089✔
2479
                // Just make the key subject spc group, e.g. 'foo bar'
3,797✔
2480
                sb.WriteByte(' ')
3,797✔
2481
                sb.Write(sub.queue)
3,797✔
2482
        }
3,797✔
2483
        return sb.String()
46,292✔
2484
}
2485

2486
const (
2487
        keyRoutedSub         = "R"
2488
        keyRoutedSubByte     = 'R'
2489
        keyRoutedLeafSub     = "L"
2490
        keyRoutedLeafSubByte = 'L'
2491
)
2492

2493
// Helper function to build the key that prevents collisions between normal
2494
// routed subscriptions and routed subscriptions on behalf of a leafnode.
2495
// Keys will look like this:
2496
// "R foo"          -> plain routed sub on "foo"
2497
// "R foo bar"      -> queue routed sub on "foo", queue "bar"
2498
// "L foo bar"      -> plain routed leaf sub on "foo", leaf "bar"
2499
// "L foo bar baz"  -> queue routed sub on "foo", queue "bar", leaf "baz"
2500
func keyFromSubWithOrigin(sub *subscription) string {
681,506✔
2501
        var sb strings.Builder
681,506✔
2502
        sb.Grow(2 + len(sub.origin) + 1 + len(sub.subject) + 1 + len(sub.queue))
681,506✔
2503
        leaf := len(sub.origin) > 0
681,506✔
2504
        if leaf {
697,983✔
2505
                sb.WriteByte(keyRoutedLeafSubByte)
16,477✔
2506
        } else {
681,506✔
2507
                sb.WriteByte(keyRoutedSubByte)
665,029✔
2508
        }
665,029✔
2509
        sb.WriteByte(' ')
681,506✔
2510
        sb.Write(sub.subject)
681,506✔
2511
        if sub.queue != nil {
704,512✔
2512
                sb.WriteByte(' ')
23,006✔
2513
                sb.Write(sub.queue)
23,006✔
2514
        }
23,006✔
2515
        if leaf {
697,983✔
2516
                sb.WriteByte(' ')
16,477✔
2517
                sb.Write(sub.origin)
16,477✔
2518
        }
16,477✔
2519
        return sb.String()
681,506✔
2520
}
2521

2522
// Lock should be held.
2523
func (c *client) writeLeafSub(w *bytes.Buffer, key string, n int32) {
36,486✔
2524
        if key == _EMPTY_ {
36,486✔
2525
                return
×
2526
        }
×
2527
        if n > 0 {
69,254✔
2528
                w.WriteString("LS+ " + key)
32,768✔
2529
                // Check for queue semantics, if found write n.
32,768✔
2530
                if strings.Contains(key, " ") {
35,058✔
2531
                        w.WriteString(" ")
2,290✔
2532
                        var b [12]byte
2,290✔
2533
                        var i = len(b)
2,290✔
2534
                        for l := n; l > 0; l /= 10 {
5,474✔
2535
                                i--
3,184✔
2536
                                b[i] = digits[l%10]
3,184✔
2537
                        }
3,184✔
2538
                        w.Write(b[i:])
2,290✔
2539
                        if c.trace {
2,290✔
2540
                                arg := fmt.Sprintf("%s %d", key, n)
×
2541
                                c.traceOutOp("LS+", []byte(arg))
×
2542
                        }
×
2543
                } else if c.trace {
30,674✔
2544
                        c.traceOutOp("LS+", []byte(key))
196✔
2545
                }
196✔
2546
        } else {
3,718✔
2547
                w.WriteString("LS- " + key)
3,718✔
2548
                if c.trace {
3,726✔
2549
                        c.traceOutOp("LS-", []byte(key))
8✔
2550
                }
8✔
2551
        }
2552
        w.WriteString(CR_LF)
36,486✔
2553
}
2554

2555
// processLeafSub will process an inbound sub request for the remote leaf node.
2556
func (c *client) processLeafSub(argo []byte) (err error) {
32,475✔
2557
        // Indicate activity.
32,475✔
2558
        c.in.subs++
32,475✔
2559

32,475✔
2560
        srv := c.srv
32,475✔
2561
        if srv == nil {
32,475✔
2562
                return nil
×
2563
        }
×
2564

2565
        // Copy so we do not reference a potentially large buffer
2566
        arg := make([]byte, len(argo))
32,475✔
2567
        copy(arg, argo)
32,475✔
2568

32,475✔
2569
        args := splitArg(arg)
32,475✔
2570
        sub := &subscription{client: c}
32,475✔
2571

32,475✔
2572
        delta := int32(1)
32,475✔
2573
        switch len(args) {
32,475✔
2574
        case 1:
30,223✔
2575
                sub.queue = nil
30,223✔
2576
        case 3:
2,251✔
2577
                sub.queue = args[1]
2,251✔
2578
                sub.qw = int32(parseSize(args[2]))
2,251✔
2579
                // TODO: (ik) We should have a non empty queue name and a queue
2,251✔
2580
                // weight >= 1. For 2.11, we may want to return an error if that
2,251✔
2581
                // is not the case, but for now just overwrite `delta` if queue
2,251✔
2582
                // weight is greater than 1 (it is possible after a reconnect/
2,251✔
2583
                // server restart to receive a queue weight > 1 for a new sub).
2,251✔
2584
                if sub.qw > 1 {
3,896✔
2585
                        delta = sub.qw
1,645✔
2586
                }
1,645✔
2587
        default:
1✔
2588
                return fmt.Errorf("processLeafSub Parse Error: '%s'", arg)
1✔
2589
        }
2590
        sub.subject = args[0]
32,474✔
2591

32,474✔
2592
        c.mu.Lock()
32,474✔
2593
        if c.isClosed() {
32,486✔
2594
                c.mu.Unlock()
12✔
2595
                return nil
12✔
2596
        }
12✔
2597

2598
        acc := c.acc
32,462✔
2599
        // Check if we have a loop.
32,462✔
2600
        ldsPrefix := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
32,462✔
2601

32,462✔
2602
        if ldsPrefix && bytesToString(sub.subject) == acc.getLDSubject() {
32,468✔
2603
                c.mu.Unlock()
6✔
2604
                c.handleLeafNodeLoop(true)
6✔
2605
                return nil
6✔
2606
        }
6✔
2607

2608
        // Check permissions if applicable. (but exclude the $LDS, $GR and _GR_)
2609
        checkPerms := true
32,456✔
2610
        if sub.subject[0] == '$' || sub.subject[0] == '_' {
61,962✔
2611
                if ldsPrefix ||
29,506✔
2612
                        bytes.HasPrefix(sub.subject, []byte(oldGWReplyPrefix)) ||
29,506✔
2613
                        bytes.HasPrefix(sub.subject, []byte(gwReplyPrefix)) {
31,558✔
2614
                        checkPerms = false
2,052✔
2615
                }
2,052✔
2616
        }
2617

2618
        // If we are a hub check that we can publish to this subject.
2619
        if checkPerms {
62,860✔
2620
                subj := string(sub.subject)
30,404✔
2621
                if subjectIsLiteral(subj) && !c.pubAllowedFullCheck(subj, true, true) {
30,730✔
2622
                        c.mu.Unlock()
326✔
2623
                        c.leafSubPermViolation(sub.subject)
326✔
2624
                        c.Debugf(fmt.Sprintf("Permissions Violation for Subscription to %q", sub.subject))
326✔
2625
                        return nil
326✔
2626
                }
326✔
2627
        }
2628

2629
        // Check if we have a maximum on the number of subscriptions.
2630
        if c.subsAtLimit() {
32,138✔
2631
                c.mu.Unlock()
8✔
2632
                c.maxSubsExceeded()
8✔
2633
                return nil
8✔
2634
        }
8✔
2635

2636
        // If we have an origin cluster associated mark that in the sub.
2637
        if rc := c.remoteCluster(); rc != _EMPTY_ {
60,673✔
2638
                sub.origin = []byte(rc)
28,551✔
2639
        }
28,551✔
2640

2641
        // Like Routes, we store local subs by account and subject and optionally queue name.
2642
        // If we have a queue it will have a trailing weight which we do not want.
2643
        if sub.queue != nil {
34,083✔
2644
                sub.sid = arg[:len(arg)-len(args[2])-1]
1,961✔
2645
        } else {
32,122✔
2646
                sub.sid = arg
30,161✔
2647
        }
30,161✔
2648
        key := bytesToString(sub.sid)
32,122✔
2649
        osub := c.subs[key]
32,122✔
2650
        if osub == nil {
62,737✔
2651
                c.subs[key] = sub
30,615✔
2652
                // Now place into the account sl.
30,615✔
2653
                if err := acc.sl.Insert(sub); err != nil {
30,615✔
2654
                        delete(c.subs, key)
×
2655
                        c.mu.Unlock()
×
2656
                        c.Errorf("Could not insert subscription: %v", err)
×
2657
                        c.sendErr("Invalid Subscription")
×
2658
                        return nil
×
2659
                }
×
2660
        } else if sub.queue != nil {
3,013✔
2661
                // For a queue we need to update the weight.
1,506✔
2662
                delta = sub.qw - atomic.LoadInt32(&osub.qw)
1,506✔
2663
                atomic.StoreInt32(&osub.qw, sub.qw)
1,506✔
2664
                acc.sl.UpdateRemoteQSub(osub)
1,506✔
2665
        }
1,506✔
2666
        spoke := c.isSpokeLeafNode()
32,122✔
2667
        c.mu.Unlock()
32,122✔
2668

32,122✔
2669
        // Only add in shadow subs if a new sub or qsub.
32,122✔
2670
        if osub == nil {
62,737✔
2671
                if err := c.addShadowSubscriptions(acc, sub, true); err != nil {
30,615✔
2672
                        c.Errorf(err.Error())
×
2673
                }
×
2674
        }
2675

2676
        // If we are not solicited, treat leaf node subscriptions similar to a
2677
        // client subscription, meaning we forward them to routes, gateways and
2678
        // other leaf nodes as needed.
2679
        if !spoke {
43,385✔
2680
                // If we are routing add to the route map for the associated account.
11,263✔
2681
                srv.updateRouteSubscriptionMap(acc, sub, delta)
11,263✔
2682
                if srv.gateway.enabled {
12,788✔
2683
                        srv.gatewayUpdateSubInterest(acc.Name, sub, delta)
1,525✔
2684
                }
1,525✔
2685
        }
2686
        // Now check on leafnode updates for other leaf nodes. We understand solicited
2687
        // and non-solicited state in this call so we will do the right thing.
2688
        acc.updateLeafNodes(sub, delta)
32,122✔
2689

32,122✔
2690
        return nil
32,122✔
2691
}
2692

2693
// If the leafnode is a solicited, set the connect delay based on default
2694
// or private option (for tests). Sends the error to the other side, log and
2695
// close the connection.
2696
func (c *client) handleLeafNodeLoop(sendErr bool) {
15✔
2697
        accName, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterLoopDetected)
15✔
2698
        errTxt := fmt.Sprintf("Loop detected for leafnode account=%q. Delaying attempt to reconnect for %v", accName, delay)
15✔
2699
        if sendErr {
23✔
2700
                c.sendErr(errTxt)
8✔
2701
        }
8✔
2702

2703
        c.Errorf(errTxt)
15✔
2704
        // If we are here with "sendErr" false, it means that this is the server
15✔
2705
        // that received the error. The other side will have closed the connection,
15✔
2706
        // but does not hurt to close here too.
15✔
2707
        c.closeConnection(ProtocolViolation)
15✔
2708
}
2709

2710
// processLeafUnsub will process an inbound unsub request for the remote leaf node.
2711
func (c *client) processLeafUnsub(arg []byte) error {
3,464✔
2712
        // Indicate any activity, so pub and sub or unsubs.
3,464✔
2713
        c.in.subs++
3,464✔
2714

3,464✔
2715
        acc := c.acc
3,464✔
2716
        srv := c.srv
3,464✔
2717

3,464✔
2718
        c.mu.Lock()
3,464✔
2719
        if c.isClosed() {
3,504✔
2720
                c.mu.Unlock()
40✔
2721
                return nil
40✔
2722
        }
40✔
2723

2724
        spoke := c.isSpokeLeafNode()
3,424✔
2725
        // We store local subs by account and subject and optionally queue name.
3,424✔
2726
        // LS- will have the arg exactly as the key.
3,424✔
2727
        sub, ok := c.subs[string(arg)]
3,424✔
2728
        if !ok {
3,434✔
2729
                // If not found, don't try to update routes/gws/leaf nodes.
10✔
2730
                c.mu.Unlock()
10✔
2731
                return nil
10✔
2732
        }
10✔
2733
        delta := int32(1)
3,414✔
2734
        if len(sub.queue) > 0 {
3,830✔
2735
                delta = sub.qw
416✔
2736
        }
416✔
2737
        c.mu.Unlock()
3,414✔
2738

3,414✔
2739
        c.unsubscribe(acc, sub, true, true)
3,414✔
2740
        if !spoke {
4,479✔
2741
                // If we are routing subtract from the route map for the associated account.
1,065✔
2742
                srv.updateRouteSubscriptionMap(acc, sub, -delta)
1,065✔
2743
                // Gateways
1,065✔
2744
                if srv.gateway.enabled {
1,339✔
2745
                        srv.gatewayUpdateSubInterest(acc.Name, sub, -delta)
274✔
2746
                }
274✔
2747
        }
2748
        // Now check on leafnode updates for other leaf nodes.
2749
        acc.updateLeafNodes(sub, -delta)
3,414✔
2750
        return nil
3,414✔
2751
}
2752

2753
func (c *client) processLeafHeaderMsgArgs(arg []byte) error {
484✔
2754
        // Unroll splitArgs to avoid runtime/heap issues
484✔
2755
        a := [MAX_MSG_ARGS][]byte{}
484✔
2756
        args := a[:0]
484✔
2757
        start := -1
484✔
2758
        for i, b := range arg {
32,004✔
2759
                switch b {
31,520✔
2760
                case ' ', '\t', '\r', '\n':
1,384✔
2761
                        if start >= 0 {
2,768✔
2762
                                args = append(args, arg[start:i])
1,384✔
2763
                                start = -1
1,384✔
2764
                        }
1,384✔
2765
                default:
30,136✔
2766
                        if start < 0 {
32,004✔
2767
                                start = i
1,868✔
2768
                        }
1,868✔
2769
                }
2770
        }
2771
        if start >= 0 {
968✔
2772
                args = append(args, arg[start:])
484✔
2773
        }
484✔
2774

2775
        c.pa.arg = arg
484✔
2776
        switch len(args) {
484✔
2777
        case 0, 1, 2:
×
2778
                return fmt.Errorf("processLeafHeaderMsgArgs Parse Error: '%s'", args)
×
2779
        case 3:
86✔
2780
                c.pa.reply = nil
86✔
2781
                c.pa.queues = nil
86✔
2782
                c.pa.hdb = args[1]
86✔
2783
                c.pa.hdr = parseSize(args[1])
86✔
2784
                c.pa.szb = args[2]
86✔
2785
                c.pa.size = parseSize(args[2])
86✔
2786
        case 4:
384✔
2787
                c.pa.reply = args[1]
384✔
2788
                c.pa.queues = nil
384✔
2789
                c.pa.hdb = args[2]
384✔
2790
                c.pa.hdr = parseSize(args[2])
384✔
2791
                c.pa.szb = args[3]
384✔
2792
                c.pa.size = parseSize(args[3])
384✔
2793
        default:
14✔
2794
                // args[1] is our reply indicator. Should be + or | normally.
14✔
2795
                if len(args[1]) != 1 {
14✔
2796
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2797
                }
×
2798
                switch args[1][0] {
14✔
2799
                case '+':
4✔
2800
                        c.pa.reply = args[2]
4✔
2801
                case '|':
10✔
2802
                        c.pa.reply = nil
10✔
2803
                default:
×
2804
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2805
                }
2806
                // Grab header size.
2807
                c.pa.hdb = args[len(args)-2]
14✔
2808
                c.pa.hdr = parseSize(c.pa.hdb)
14✔
2809

14✔
2810
                // Grab size.
14✔
2811
                c.pa.szb = args[len(args)-1]
14✔
2812
                c.pa.size = parseSize(c.pa.szb)
14✔
2813

14✔
2814
                // Grab queue names.
14✔
2815
                if c.pa.reply != nil {
18✔
2816
                        c.pa.queues = args[3 : len(args)-2]
4✔
2817
                } else {
14✔
2818
                        c.pa.queues = args[2 : len(args)-2]
10✔
2819
                }
10✔
2820
        }
2821
        if c.pa.hdr < 0 {
484✔
2822
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Header Size: '%s'", arg)
×
2823
        }
×
2824
        if c.pa.size < 0 {
484✔
2825
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Size: '%s'", args)
×
2826
        }
×
2827
        if c.pa.hdr > c.pa.size {
485✔
2828
                return fmt.Errorf("processLeafHeaderMsgArgs Header Size larger then TotalSize: '%s'", arg)
1✔
2829
        }
1✔
2830

2831
        // Common ones processed after check for arg length
2832
        c.pa.subject = args[0]
483✔
2833

483✔
2834
        return nil
483✔
2835
}
2836

2837
func (c *client) processLeafMsgArgs(arg []byte) error {
131,651✔
2838
        // Unroll splitArgs to avoid runtime/heap issues
131,651✔
2839
        a := [MAX_MSG_ARGS][]byte{}
131,651✔
2840
        args := a[:0]
131,651✔
2841
        start := -1
131,651✔
2842
        for i, b := range arg {
4,227,905✔
2843
                switch b {
4,096,254✔
2844
                case ' ', '\t', '\r', '\n':
183,314✔
2845
                        if start >= 0 {
366,628✔
2846
                                args = append(args, arg[start:i])
183,314✔
2847
                                start = -1
183,314✔
2848
                        }
183,314✔
2849
                default:
3,912,940✔
2850
                        if start < 0 {
4,227,905✔
2851
                                start = i
314,965✔
2852
                        }
314,965✔
2853
                }
2854
        }
2855
        if start >= 0 {
263,302✔
2856
                args = append(args, arg[start:])
131,651✔
2857
        }
131,651✔
2858

2859
        c.pa.arg = arg
131,651✔
2860
        switch len(args) {
131,651✔
2861
        case 0, 1:
×
2862
                return fmt.Errorf("processLeafMsgArgs Parse Error: '%s'", args)
×
2863
        case 2:
102,710✔
2864
                c.pa.reply = nil
102,710✔
2865
                c.pa.queues = nil
102,710✔
2866
                c.pa.szb = args[1]
102,710✔
2867
                c.pa.size = parseSize(args[1])
102,710✔
2868
        case 3:
6,381✔
2869
                c.pa.reply = args[1]
6,381✔
2870
                c.pa.queues = nil
6,381✔
2871
                c.pa.szb = args[2]
6,381✔
2872
                c.pa.size = parseSize(args[2])
6,381✔
2873
        default:
22,560✔
2874
                // args[1] is our reply indicator. Should be + or | normally.
22,560✔
2875
                if len(args[1]) != 1 {
22,561✔
2876
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
1✔
2877
                }
1✔
2878
                switch args[1][0] {
22,559✔
2879
                case '+':
161✔
2880
                        c.pa.reply = args[2]
161✔
2881
                case '|':
22,398✔
2882
                        c.pa.reply = nil
22,398✔
2883
                default:
×
2884
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2885
                }
2886
                // Grab size.
2887
                c.pa.szb = args[len(args)-1]
22,559✔
2888
                c.pa.size = parseSize(c.pa.szb)
22,559✔
2889

22,559✔
2890
                // Grab queue names.
22,559✔
2891
                if c.pa.reply != nil {
22,720✔
2892
                        c.pa.queues = args[3 : len(args)-1]
161✔
2893
                } else {
22,559✔
2894
                        c.pa.queues = args[2 : len(args)-1]
22,398✔
2895
                }
22,398✔
2896
        }
2897
        if c.pa.size < 0 {
131,650✔
2898
                return fmt.Errorf("processLeafMsgArgs Bad or Missing Size: '%s'", args)
×
2899
        }
×
2900

2901
        // Common ones processed after check for arg length
2902
        c.pa.subject = args[0]
131,650✔
2903

131,650✔
2904
        return nil
131,650✔
2905
}
2906

2907
// processInboundLeafMsg is called to process an inbound msg from a leaf node.
2908
func (c *client) processInboundLeafMsg(msg []byte) {
129,781✔
2909
        // Update statistics
129,781✔
2910
        // The msg includes the CR_LF, so pull back out for accounting.
129,781✔
2911
        c.in.msgs++
129,781✔
2912
        c.in.bytes += int32(len(msg) - LEN_CR_LF)
129,781✔
2913

129,781✔
2914
        srv, acc, subject := c.srv, c.acc, string(c.pa.subject)
129,781✔
2915

129,781✔
2916
        // Mostly under testing scenarios.
129,781✔
2917
        if srv == nil || acc == nil {
129,783✔
2918
                return
2✔
2919
        }
2✔
2920

2921
        // Match the subscriptions. We will use our own L1 map if
2922
        // it's still valid, avoiding contention on the shared sublist.
2923
        var r *SublistResult
129,779✔
2924
        var ok bool
129,779✔
2925

129,779✔
2926
        genid := atomic.LoadUint64(&c.acc.sl.genid)
129,779✔
2927
        if genid == c.in.genid && c.in.results != nil {
257,185✔
2928
                r, ok = c.in.results[subject]
127,406✔
2929
        } else {
129,779✔
2930
                // Reset our L1 completely.
2,373✔
2931
                c.in.results = make(map[string]*SublistResult)
2,373✔
2932
                c.in.genid = genid
2,373✔
2933
        }
2,373✔
2934

2935
        // Go back to the sublist data structure.
2936
        if !ok {
229,413✔
2937
                r = c.acc.sl.Match(subject)
99,634✔
2938
                // Prune the results cache. Keeps us from unbounded growth. Random delete.
99,634✔
2939
                if len(c.in.results) >= maxResultCacheSize {
102,478✔
2940
                        n := 0
2,844✔
2941
                        for subj := range c.in.results {
96,696✔
2942
                                delete(c.in.results, subj)
93,852✔
2943
                                if n++; n > pruneSize {
96,696✔
2944
                                        break
2,844✔
2945
                                }
2946
                        }
2947
                }
2948
                // Then add the new cache entry.
2949
                c.in.results[subject] = r
99,634✔
2950
        }
2951

2952
        // Collect queue names if needed.
2953
        var qnames [][]byte
129,779✔
2954

129,779✔
2955
        // Check for no interest, short circuit if so.
129,779✔
2956
        // This is the fanout scale.
129,779✔
2957
        if len(r.psubs)+len(r.qsubs) > 0 {
259,305✔
2958
                flag := pmrNoFlag
129,526✔
2959
                // If we have queue subs in this cluster, then if we run in gateway
129,526✔
2960
                // mode and the remote gateways have queue subs, then we need to
129,526✔
2961
                // collect the queue groups this message was sent to so that we
129,526✔
2962
                // exclude them when sending to gateways.
129,526✔
2963
                if len(r.qsubs) > 0 && c.srv.gateway.enabled &&
129,526✔
2964
                        atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 {
141,735✔
2965
                        flag |= pmrCollectQueueNames
12,209✔
2966
                }
12,209✔
2967
                // If this is a mapped subject that means the mapped interest
2968
                // is what got us here, but this might not have a queue designation
2969
                // If that is the case, make sure we ignore to process local queue subscribers.
2970
                if len(c.pa.mapped) > 0 && len(c.pa.queues) == 0 {
129,842✔
2971
                        flag |= pmrIgnoreEmptyQueueFilter
316✔
2972
                }
316✔
2973
                _, qnames = c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, flag)
129,526✔
2974
        }
2975

2976
        // Now deal with gateways
2977
        if c.srv.gateway.enabled {
142,965✔
2978
                c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, qnames, true)
13,186✔
2979
        }
13,186✔
2980
}
2981

2982
// Handles a subscription permission violation.
2983
// See leafPermViolation() for details.
2984
func (c *client) leafSubPermViolation(subj []byte) {
326✔
2985
        c.leafPermViolation(false, subj)
326✔
2986
}
326✔
2987

2988
// Common function to process publish or subscribe leafnode permission violation.
2989
// Sends the permission violation error to the remote, logs it and closes the connection.
2990
// If this is from a server soliciting, the reconnection will be delayed.
2991
func (c *client) leafPermViolation(pub bool, subj []byte) {
326✔
2992
        if c.isSpokeLeafNode() {
652✔
2993
                // For spokes these are no-ops since the hub server told us our permissions.
326✔
2994
                // We just need to not send these over to the other side since we will get cutoff.
326✔
2995
                return
326✔
2996
        }
326✔
2997
        // FIXME(dlc) ?
2998
        c.setLeafConnectDelayIfSoliciting(leafNodeReconnectAfterPermViolation)
×
2999
        var action string
×
3000
        if pub {
×
3001
                c.sendErr(fmt.Sprintf("Permissions Violation for Publish to %q", subj))
×
3002
                action = "Publish"
×
3003
        } else {
×
3004
                c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q", subj))
×
3005
                action = "Subscription"
×
3006
        }
×
3007
        c.Errorf("%s Violation on %q - Check other side configuration", action, subj)
×
3008
        // TODO: add a new close reason that is more appropriate?
×
3009
        c.closeConnection(ProtocolViolation)
×
3010
}
3011

3012
// Invoked from generic processErr() for LEAF connections.
3013
func (c *client) leafProcessErr(errStr string) {
45✔
3014
        // Check if we got a cluster name collision.
45✔
3015
        if strings.Contains(errStr, ErrLeafNodeHasSameClusterName.Error()) {
48✔
3016
                _, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterClusterNameSame)
3✔
3017
                c.Errorf("Leafnode connection dropped with same cluster name error. Delaying attempt to reconnect for %v", delay)
3✔
3018
                return
3✔
3019
        }
3✔
3020

3021
        // We will look for Loop detected error coming from the other side.
3022
        // If we solicit, set the connect delay.
3023
        if !strings.Contains(errStr, "Loop detected") {
77✔
3024
                return
35✔
3025
        }
35✔
3026
        c.handleLeafNodeLoop(false)
7✔
3027
}
3028

3029
// If this leaf connection solicits, sets the connect delay to the given value,
3030
// or the one from the server option's LeafNode.connDelay if one is set (for tests).
3031
// Returns the connection's account name and delay.
3032
func (c *client) setLeafConnectDelayIfSoliciting(delay time.Duration) (string, time.Duration) {
18✔
3033
        c.mu.Lock()
18✔
3034
        if c.isSolicitedLeafNode() {
28✔
3035
                if s := c.srv; s != nil {
20✔
3036
                        if srvdelay := s.getOpts().LeafNode.connDelay; srvdelay != 0 {
14✔
3037
                                delay = srvdelay
4✔
3038
                        }
4✔
3039
                }
3040
                c.leaf.remote.setConnectDelay(delay)
10✔
3041
        }
3042
        accName := c.acc.Name
18✔
3043
        c.mu.Unlock()
18✔
3044
        return accName, delay
18✔
3045
}
3046

3047
// For the given remote Leafnode configuration, this function returns
3048
// if TLS is required, and if so, will return a clone of the TLS Config
3049
// (since some fields will be changed during handshake), the TLS server
3050
// name that is remembered, and the TLS timeout.
3051
func (c *client) leafNodeGetTLSConfigForSolicit(remote *leafNodeCfg) (bool, *tls.Config, string, float64) {
1,934✔
3052
        var (
1,934✔
3053
                tlsConfig  *tls.Config
1,934✔
3054
                tlsName    string
1,934✔
3055
                tlsTimeout float64
1,934✔
3056
        )
1,934✔
3057

1,934✔
3058
        remote.RLock()
1,934✔
3059
        defer remote.RUnlock()
1,934✔
3060

1,934✔
3061
        tlsRequired := remote.TLS || remote.TLSConfig != nil
1,934✔
3062
        if tlsRequired {
2,010✔
3063
                if remote.TLSConfig != nil {
127✔
3064
                        tlsConfig = remote.TLSConfig.Clone()
51✔
3065
                } else {
76✔
3066
                        tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}
25✔
3067
                }
25✔
3068
                tlsName = remote.tlsName
76✔
3069
                tlsTimeout = remote.TLSTimeout
76✔
3070
                if tlsTimeout == 0 {
118✔
3071
                        tlsTimeout = float64(TLS_TIMEOUT / time.Second)
42✔
3072
                }
42✔
3073
        }
3074

3075
        return tlsRequired, tlsConfig, tlsName, tlsTimeout
1,934✔
3076
}
3077

3078
// Initiates the LeafNode Websocket connection by:
3079
// - doing the TLS handshake if needed
3080
// - sending the HTTP request
3081
// - waiting for the HTTP response
3082
//
3083
// Since some bufio reader is used to consume the HTTP response, this function
3084
// returns the slice of buffered bytes (if any) so that the readLoop that will
3085
// be started after that consume those first before reading from the socket.
3086
// The boolean
3087
//
3088
// Lock held on entry.
3089
func (c *client) leafNodeSolicitWSConnection(opts *Options, rURL *url.URL, remote *leafNodeCfg) ([]byte, ClosedState, error) {
43✔
3090
        remote.RLock()
43✔
3091
        compress := remote.Websocket.Compression
43✔
3092
        // By default the server will mask outbound frames, but it can be disabled with this option.
43✔
3093
        noMasking := remote.Websocket.NoMasking
43✔
3094
        infoTimeout := remote.FirstInfoTimeout
43✔
3095
        remote.RUnlock()
43✔
3096
        // Will do the client-side TLS handshake if needed.
43✔
3097
        tlsRequired, err := c.leafClientHandshakeIfNeeded(remote, opts)
43✔
3098
        if err != nil {
47✔
3099
                // 0 will indicate that the connection was already closed
4✔
3100
                return nil, 0, err
4✔
3101
        }
4✔
3102

3103
        // For http request, we need the passed URL to contain either http or https scheme.
3104
        scheme := "http"
39✔
3105
        if tlsRequired {
47✔
3106
                scheme = "https"
8✔
3107
        }
8✔
3108
        // We will use the `/leafnode` path to tell the accepting WS server that it should
3109
        // create a LEAF connection, not a CLIENT.
3110
        // In case we use the user's URL path in the future, make sure we append the user's
3111
        // path to our `/leafnode` path.
3112
        lpath := leafNodeWSPath
39✔
3113
        if curPath := rURL.EscapedPath(); curPath != _EMPTY_ {
60✔
3114
                if curPath[0] == '/' {
42✔
3115
                        curPath = curPath[1:]
21✔
3116
                }
21✔
3117
                lpath = path.Join(curPath, lpath)
21✔
3118
        } else {
18✔
3119
                lpath = lpath[1:]
18✔
3120
        }
18✔
3121
        ustr := fmt.Sprintf("%s://%s/%s", scheme, rURL.Host, lpath)
39✔
3122
        u, _ := url.Parse(ustr)
39✔
3123
        req := &http.Request{
39✔
3124
                Method:     "GET",
39✔
3125
                URL:        u,
39✔
3126
                Proto:      "HTTP/1.1",
39✔
3127
                ProtoMajor: 1,
39✔
3128
                ProtoMinor: 1,
39✔
3129
                Header:     make(http.Header),
39✔
3130
                Host:       u.Host,
39✔
3131
        }
39✔
3132
        wsKey, err := wsMakeChallengeKey()
39✔
3133
        if err != nil {
39✔
3134
                return nil, WriteError, err
×
3135
        }
×
3136

3137
        req.Header["Upgrade"] = []string{"websocket"}
39✔
3138
        req.Header["Connection"] = []string{"Upgrade"}
39✔
3139
        req.Header["Sec-WebSocket-Key"] = []string{wsKey}
39✔
3140
        req.Header["Sec-WebSocket-Version"] = []string{"13"}
39✔
3141
        if compress {
48✔
3142
                req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue)
9✔
3143
        }
9✔
3144
        if noMasking {
49✔
3145
                req.Header.Add(wsNoMaskingHeader, wsNoMaskingValue)
10✔
3146
        }
10✔
3147
        c.nc.SetDeadline(time.Now().Add(infoTimeout))
39✔
3148
        if err := req.Write(c.nc); err != nil {
39✔
3149
                return nil, WriteError, err
×
3150
        }
×
3151

3152
        var resp *http.Response
39✔
3153

39✔
3154
        br := bufio.NewReaderSize(c.nc, MAX_CONTROL_LINE_SIZE)
39✔
3155
        resp, err = http.ReadResponse(br, req)
39✔
3156
        if err == nil &&
39✔
3157
                (resp.StatusCode != 101 ||
39✔
3158
                        !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
39✔
3159
                        !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
39✔
3160
                        resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) {
40✔
3161

1✔
3162
                err = fmt.Errorf("invalid websocket connection")
1✔
3163
        }
1✔
3164
        // Check compression extension...
3165
        if err == nil && c.ws.compress {
48✔
3166
                // Check that not only permessage-deflate extension is present, but that
9✔
3167
                // we also have server and client no context take over.
9✔
3168
                srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header, false)
9✔
3169

9✔
3170
                // If server does not support compression, then simply disable it in our side.
9✔
3171
                if !srvCompress {
13✔
3172
                        c.ws.compress = false
4✔
3173
                } else if !noCtxTakeover {
9✔
3174
                        err = fmt.Errorf("compression negotiation error")
×
3175
                }
×
3176
        }
3177
        // Same for no masking...
3178
        if err == nil && noMasking {
49✔
3179
                // Check if server accepts no masking
10✔
3180
                if resp.Header.Get(wsNoMaskingHeader) != wsNoMaskingValue {
11✔
3181
                        // Nope, need to mask our writes as any client would do.
1✔
3182
                        c.ws.maskwrite = true
1✔
3183
                }
1✔
3184
        }
3185
        if resp != nil {
67✔
3186
                resp.Body.Close()
28✔
3187
        }
28✔
3188
        if err != nil {
51✔
3189
                return nil, ReadError, err
12✔
3190
        }
12✔
3191
        c.Debugf("Leafnode compression=%v masking=%v", c.ws.compress, c.ws.maskwrite)
27✔
3192

27✔
3193
        var preBuf []byte
27✔
3194
        // We have to slurp whatever is in the bufio reader and pass that to the readloop.
27✔
3195
        if n := br.Buffered(); n != 0 {
27✔
3196
                preBuf, _ = br.Peek(n)
×
3197
        }
×
3198
        return preBuf, 0, nil
27✔
3199
}
3200

3201
const connectProcessTimeout = 2 * time.Second
3202

3203
// This is invoked for remote LEAF remote connections after processing the INFO
3204
// protocol.
3205
func (s *Server) leafNodeResumeConnectProcess(c *client) {
679✔
3206
        clusterName := s.ClusterName()
679✔
3207

679✔
3208
        c.mu.Lock()
679✔
3209
        if c.isClosed() {
679✔
3210
                c.mu.Unlock()
×
3211
                return
×
3212
        }
×
3213
        if err := c.sendLeafConnect(clusterName, c.headers); err != nil {
681✔
3214
                c.mu.Unlock()
2✔
3215
                c.closeConnection(WriteError)
2✔
3216
                return
2✔
3217
        }
2✔
3218

3219
        // Spin up the write loop.
3220
        s.startGoRoutine(func() { c.writeLoop() })
1,354✔
3221

3222
        // timeout leafNodeFinishConnectProcess
3223
        c.ping.tmr = time.AfterFunc(connectProcessTimeout, func() {
677✔
3224
                c.mu.Lock()
×
3225
                // check if leafNodeFinishConnectProcess was called and prevent later leafNodeFinishConnectProcess
×
3226
                if !c.flags.setIfNotSet(connectProcessFinished) {
×
3227
                        c.mu.Unlock()
×
3228
                        return
×
3229
                }
×
3230
                clearTimer(&c.ping.tmr)
×
3231
                closed := c.isClosed()
×
3232
                c.mu.Unlock()
×
3233
                if !closed {
×
3234
                        c.sendErrAndDebug("Stale Leaf Node Connection - Closing")
×
3235
                        c.closeConnection(StaleConnection)
×
3236
                }
×
3237
        })
3238
        c.mu.Unlock()
677✔
3239
        c.Debugf("Remote leafnode connect msg sent")
677✔
3240
}
3241

3242
// This is invoked for remote LEAF connections after processing the INFO
3243
// protocol and leafNodeResumeConnectProcess.
3244
// This will send LS+ the CONNECT protocol and register the leaf node.
3245
func (s *Server) leafNodeFinishConnectProcess(c *client) {
643✔
3246
        c.mu.Lock()
643✔
3247
        if !c.flags.setIfNotSet(connectProcessFinished) {
643✔
3248
                c.mu.Unlock()
×
3249
                return
×
3250
        }
×
3251
        if c.isClosed() {
643✔
3252
                c.mu.Unlock()
×
3253
                s.removeLeafNodeConnection(c)
×
3254
                return
×
3255
        }
×
3256
        remote := c.leaf.remote
643✔
3257
        // Check if we will need to send the system connect event.
643✔
3258
        remote.RLock()
643✔
3259
        sendSysConnectEvent := remote.Hub
643✔
3260
        remote.RUnlock()
643✔
3261

643✔
3262
        // Capture account before releasing lock
643✔
3263
        acc := c.acc
643✔
3264
        // cancel connectProcessTimeout
643✔
3265
        clearTimer(&c.ping.tmr)
643✔
3266
        c.mu.Unlock()
643✔
3267

643✔
3268
        // Make sure we register with the account here.
643✔
3269
        if err := c.registerWithAccount(acc); err != nil {
645✔
3270
                if err == ErrTooManyAccountConnections {
2✔
3271
                        c.maxAccountConnExceeded()
×
3272
                        return
×
3273
                } else if err == ErrLeafNodeLoop {
4✔
3274
                        c.handleLeafNodeLoop(true)
2✔
3275
                        return
2✔
3276
                }
2✔
3277
                c.Errorf("Registering leaf with account %s resulted in error: %v", acc.Name, err)
×
3278
                c.closeConnection(ProtocolViolation)
×
3279
                return
×
3280
        }
3281
        s.addLeafNodeConnection(c, _EMPTY_, _EMPTY_, false)
641✔
3282
        s.initLeafNodeSmapAndSendSubs(c)
641✔
3283
        if sendSysConnectEvent {
657✔
3284
                s.sendLeafNodeConnect(acc)
16✔
3285
        }
16✔
3286

3287
        // The above functions are not atomically under the client
3288
        // lock doing those operations. It is possible - since we
3289
        // have started the read/write loops - that the connection
3290
        // is closed before or in between. This would leave the
3291
        // closed LN connection possible registered with the account
3292
        // and/or the server's leafs map. So check if connection
3293
        // is closed, and if so, manually cleanup.
3294
        c.mu.Lock()
641✔
3295
        closed := c.isClosed()
641✔
3296
        if !closed {
1,282✔
3297
                c.setFirstPingTimer()
641✔
3298
        }
641✔
3299
        c.mu.Unlock()
641✔
3300
        if closed {
641✔
3301
                s.removeLeafNodeConnection(c)
×
3302
                if prev := acc.removeClient(c); prev == 1 {
×
3303
                        s.decActiveAccounts()
×
3304
                }
×
3305
        }
3306
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc