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

nats-io / nats-server / 17367850263

31 Aug 2025 08:02PM UTC coverage: 85.062% (-1.0%) from 86.059%
17367850263

push

github

neilalexander
Release v2.12.0-preview.2

Signed-off-by: Neil Twigg <neil@nats.io>

73172 of 86022 relevant lines covered (85.06%)

355681.11 hits per line

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

90.86
/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 remove 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,064✔
122
        return c.kind == LEAF && c.leaf.remote != nil
2,064✔
123
}
2,064✔
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,361,878✔
128
        return c.kind == LEAF && c.leaf.isSpoke
6,361,878✔
129
}
6,361,878✔
130

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

135
func (c *client) isIsolatedLeafNode() bool {
10,959✔
136
        return c.kind == LEAF && c.leaf.isolated
10,959✔
137
}
10,959✔
138

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

196
func (s *Server) remoteLeafNodeStillValid(remote *leafNodeCfg) bool {
7,803✔
197
        if remote.Disabled {
7,804✔
198
                return false
1✔
199
        }
1✔
200
        for _, ri := range s.getOpts().LeafNode.Remotes {
15,960✔
201
                // FIXME(dlc) - What about auth changes?
8,158✔
202
                if reflect.DeepEqual(ri.URLs, remote.URLs) {
15,960✔
203
                        return true
7,802✔
204
                }
7,802✔
205
        }
206
        return false
×
207
}
208

209
// Ensure that leafnode is properly configured.
210
func validateLeafNode(o *Options) error {
8,555✔
211
        if err := validateLeafNodeAuthOptions(o); err != nil {
8,557✔
212
                return err
2✔
213
        }
2✔
214

215
        // Users can bind to any local account, if its empty we will assume the $G account.
216
        for _, r := range o.LeafNode.Remotes {
9,883✔
217
                if r.LocalAccount == _EMPTY_ {
1,767✔
218
                        r.LocalAccount = globalAccountName
437✔
219
                }
437✔
220
        }
221

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

275
        // Validate compression settings
276
        if o.LeafNode.Compression.Mode != _EMPTY_ {
12,626✔
277
                if err := validateAndNormalizeCompressionOption(&o.LeafNode.Compression, CompressionS2Auto); err != nil {
4,083✔
278
                        return err
5✔
279
                }
5✔
280
        }
281

282
        // If a remote has a websocket scheme, all need to have it.
283
        for _, rcfg := range o.LeafNode.Remotes {
9,871✔
284
                if len(rcfg.URLs) >= 2 {
1,532✔
285
                        firstIsWS, ok := isWSURL(rcfg.URLs[0]), true
204✔
286
                        for i := 1; i < len(rcfg.URLs); i++ {
653✔
287
                                u := rcfg.URLs[i]
449✔
288
                                if isWS := isWSURL(u); isWS && !firstIsWS || !isWS && firstIsWS {
456✔
289
                                        ok = false
7✔
290
                                        break
7✔
291
                                }
292
                        }
293
                        if !ok {
211✔
294
                                return fmt.Errorf("remote leaf node configuration cannot have a mix of websocket and non-websocket urls: %q", redactURLList(rcfg.URLs))
7✔
295
                        }
7✔
296
                }
297
                // Validate compression settings
298
                if rcfg.Compression.Mode != _EMPTY_ {
2,642✔
299
                        if err := validateAndNormalizeCompressionOption(&rcfg.Compression, CompressionS2Auto); err != nil {
1,326✔
300
                                return err
5✔
301
                        }
5✔
302
                }
303
        }
304

305
        if o.LeafNode.Port == 0 {
13,590✔
306
                return nil
5,059✔
307
        }
5,059✔
308

309
        // If MinVersion is defined, check that it is valid.
310
        if mv := o.LeafNode.MinVersion; mv != _EMPTY_ {
3,476✔
311
                if err := checkLeafMinVersionConfig(mv); err != nil {
6✔
312
                        return err
2✔
313
                }
2✔
314
        }
315

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

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

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

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

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

375
        s.mu.RLock()
15✔
376
        defer s.mu.RUnlock()
15✔
377

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

395
func (s *Server) reConnectToRemoteLeafNode(remote *leafNodeCfg) {
247✔
396
        delay := s.getOpts().LeafNode.ReconnectInterval
247✔
397
        select {
247✔
398
        case <-time.After(delay):
193✔
399
        case <-s.quitCh:
54✔
400
                s.grWG.Done()
54✔
401
                return
54✔
402
        }
403
        s.connectToRemoteLeafNode(remote, false)
193✔
404
}
405

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

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

461
// Returns the current URL
462
func (cfg *leafNodeCfg) getCurrentURL() *url.URL {
80✔
463
        cfg.RLock()
80✔
464
        defer cfg.RUnlock()
80✔
465
        return cfg.curURL
80✔
466
}
80✔
467

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

477
// Sets the connect delay.
478
func (cfg *leafNodeCfg) setConnectDelay(delay time.Duration) {
150✔
479
        cfg.Lock()
150✔
480
        cfg.connDelay = delay
150✔
481
        cfg.Unlock()
150✔
482
}
150✔
483

484
// Ensure that non-exported options (used in tests) have
485
// been properly set.
486
func (s *Server) setLeafNodeNonExportedOptions() {
7,027✔
487
        opts := s.getOpts()
7,027✔
488
        s.leafNodeOpts.dialTimeout = opts.LeafNode.dialTimeout
7,027✔
489
        if s.leafNodeOpts.dialTimeout == 0 {
14,053✔
490
                // Use same timeouts as routes for now.
7,026✔
491
                s.leafNodeOpts.dialTimeout = DEFAULT_ROUTE_DIAL
7,026✔
492
        }
7,026✔
493
        s.leafNodeOpts.resolver = opts.LeafNode.resolver
7,027✔
494
        if s.leafNodeOpts.resolver == nil {
14,050✔
495
                s.leafNodeOpts.resolver = net.DefaultResolver
7,023✔
496
        }
7,023✔
497
}
498

499
const sharedSysAccDelay = 250 * time.Millisecond
500

501
func (s *Server) connectToRemoteLeafNode(remote *leafNodeCfg, firstConnect bool) {
1,483✔
502
        defer s.grWG.Done()
1,483✔
503

1,483✔
504
        if remote == nil || len(remote.URLs) == 0 {
1,483✔
505
                s.Debugf("Empty remote leafnode definition, nothing to connect")
×
506
                return
×
507
        }
×
508

509
        opts := s.getOpts()
1,483✔
510
        reconnectDelay := opts.LeafNode.ReconnectInterval
1,483✔
511
        s.mu.RLock()
1,483✔
512
        dialTimeout := s.leafNodeOpts.dialTimeout
1,483✔
513
        resolver := s.leafNodeOpts.resolver
1,483✔
514
        var isSysAcc bool
1,483✔
515
        if s.eventsEnabled() {
2,929✔
516
                isSysAcc = remote.LocalAccount == s.sys.account.Name
1,446✔
517
        }
1,446✔
518
        jetstreamMigrateDelay := remote.JetStreamClusterMigrateDelay
1,483✔
519
        s.mu.RUnlock()
1,483✔
520

1,483✔
521
        // If we are sharing a system account and we are not standalone delay to gather some info prior.
1,483✔
522
        if firstConnect && isSysAcc && !s.standAloneMode() {
1,552✔
523
                s.Debugf("Will delay first leafnode connect to shared system account due to clustering")
69✔
524
                remote.setConnectDelay(sharedSysAccDelay)
69✔
525
        }
69✔
526

527
        if connDelay := remote.getConnectDelay(); connDelay > 0 {
1,559✔
528
                select {
76✔
529
                case <-time.After(connDelay):
70✔
530
                case <-s.quitCh:
6✔
531
                        return
6✔
532
                }
533
                remote.setConnectDelay(0)
70✔
534
        }
535

536
        var conn net.Conn
1,477✔
537

1,477✔
538
        const connErrFmt = "Error trying to connect as leafnode to remote server %q (attempt %v): %v"
1,477✔
539

1,477✔
540
        attempts := 0
1,477✔
541

1,477✔
542
        for s.isRunning() && s.remoteLeafNodeStillValid(remote) {
8,498✔
543
                rURL := remote.pickNextURL()
7,021✔
544
                url, err := s.getRandomIP(resolver, rURL.Host, nil)
7,021✔
545
                if err == nil {
14,035✔
546
                        var ipStr string
7,014✔
547
                        if url != rURL.Host {
7,082✔
548
                                ipStr = fmt.Sprintf(" (%s)", url)
68✔
549
                        }
68✔
550
                        // Some test may want to disable remotes from connecting
551
                        if s.isLeafConnectDisabled() {
7,143✔
552
                                s.Debugf("Will not attempt to connect to remote server on %q%s, leafnodes currently disabled", rURL.Host, ipStr)
129✔
553
                                err = ErrLeafNodeDisabled
129✔
554
                        } else {
7,014✔
555
                                s.Debugf("Trying to connect as leafnode to remote server on %q%s", rURL.Host, ipStr)
6,885✔
556
                                conn, err = natsDialTimeout("tcp", url, dialTimeout)
6,885✔
557
                        }
6,885✔
558
                }
559
                if err != nil {
13,261✔
560
                        jitter := time.Duration(rand.Int63n(int64(reconnectDelay)))
6,240✔
561
                        delay := reconnectDelay + jitter
6,240✔
562
                        attempts++
6,240✔
563
                        if s.shouldReportConnectErr(firstConnect, attempts) {
10,617✔
564
                                s.Errorf(connErrFmt, rURL.Host, attempts, err)
4,377✔
565
                        } else {
6,240✔
566
                                s.Debugf(connErrFmt, rURL.Host, attempts, err)
1,863✔
567
                        }
1,863✔
568
                        remote.Lock()
6,240✔
569
                        // if we are using a delay to start migrating assets, kick off a migrate timer.
6,240✔
570
                        if remote.jsMigrateTimer == nil && jetstreamMigrateDelay > 0 {
6,248✔
571
                                remote.jsMigrateTimer = time.AfterFunc(jetstreamMigrateDelay, func() {
16✔
572
                                        s.checkJetStreamMigrate(remote)
8✔
573
                                })
8✔
574
                        }
575
                        remote.Unlock()
6,240✔
576
                        select {
6,240✔
577
                        case <-s.quitCh:
685✔
578
                                remote.cancelMigrateTimer()
685✔
579
                                return
685✔
580
                        case <-time.After(delay):
5,554✔
581
                                // Check if we should migrate any JetStream assets immediately while this remote is down.
5,554✔
582
                                // This will be used if JetStreamClusterMigrateDelay was not set
5,554✔
583
                                if jetstreamMigrateDelay == 0 {
11,033✔
584
                                        s.checkJetStreamMigrate(remote)
5,479✔
585
                                }
5,479✔
586
                                continue
5,554✔
587
                        }
588
                }
589
                remote.cancelMigrateTimer()
781✔
590
                if !s.remoteLeafNodeStillValid(remote) {
781✔
591
                        conn.Close()
×
592
                        return
×
593
                }
×
594

595
                // We have a connection here to a remote server.
596
                // Go ahead and create our leaf node and return.
597
                s.createLeafNode(conn, rURL, remote, nil)
781✔
598

781✔
599
                // Clear any observer states if we had them.
781✔
600
                s.clearObserverState(remote)
781✔
601

781✔
602
                return
781✔
603
        }
604
}
605

606
func (cfg *leafNodeCfg) cancelMigrateTimer() {
1,466✔
607
        cfg.Lock()
1,466✔
608
        stopAndClearTimer(&cfg.jsMigrateTimer)
1,466✔
609
        cfg.Unlock()
1,466✔
610
}
1,466✔
611

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

781✔
618
        acc, err := s.LookupAccount(accName)
781✔
619
        if err != nil {
783✔
620
                s.Warnf("Error looking up account [%s] checking for JetStream clear observer state on a leafnode", accName)
2✔
621
                return
2✔
622
        }
2✔
623

624
        acc.jscmMu.Lock()
779✔
625
        defer acc.jscmMu.Unlock()
779✔
626

779✔
627
        // Walk all streams looking for any clustered stream, skip otherwise.
779✔
628
        for _, mset := range acc.streams() {
822✔
629
                node := mset.raftNode()
43✔
630
                if node == nil {
78✔
631
                        // Not R>1
35✔
632
                        continue
35✔
633
                }
634
                // Check consumers
635
                for _, o := range mset.getConsumers() {
10✔
636
                        if n := o.raftNode(); n != nil {
4✔
637
                                // Ensure we can become a leader again.
2✔
638
                                n.SetObserver(false)
2✔
639
                        }
2✔
640
                }
641
                // Ensure we can not become a leader again.
642
                node.SetObserver(false)
8✔
643
        }
644
}
645

646
// Check to see if we should migrate any assets from this account.
647
func (s *Server) checkJetStreamMigrate(remote *leafNodeCfg) {
5,487✔
648
        s.mu.RLock()
5,487✔
649
        accName, shouldMigrate := remote.LocalAccount, remote.JetStreamClusterMigrate
5,487✔
650
        s.mu.RUnlock()
5,487✔
651

5,487✔
652
        if !shouldMigrate {
10,912✔
653
                return
5,425✔
654
        }
5,425✔
655

656
        acc, err := s.LookupAccount(accName)
62✔
657
        if err != nil {
62✔
658
                s.Warnf("Error looking up account [%s] checking for JetStream migration on a leafnode", accName)
×
659
                return
×
660
        }
×
661

662
        acc.jscmMu.Lock()
62✔
663
        defer acc.jscmMu.Unlock()
62✔
664

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

688
// Helper for checking.
689
func (s *Server) isLeafConnectDisabled() bool {
7,014✔
690
        s.mu.RLock()
7,014✔
691
        defer s.mu.RUnlock()
7,014✔
692
        return s.leafDisableConnect
7,014✔
693
}
7,014✔
694

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

709
// Save off the username/password for when we connect using a bare URL
710
// that we get from the INFO protocol.
711
func (cfg *leafNodeCfg) saveUserPassword(u *url.URL) {
1,725✔
712
        if cfg.username == _EMPTY_ && u.User != nil {
2,000✔
713
                cfg.username = u.User.Username()
275✔
714
                cfg.password, _ = u.User.Password()
275✔
715
        }
275✔
716
}
717

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

3,438✔
724
        port := opts.LeafNode.Port
3,438✔
725
        if port == -1 {
6,699✔
726
                port = 0
3,261✔
727
        }
3,261✔
728

729
        if s.isShuttingDown() {
3,439✔
730
                return
1✔
731
        }
1✔
732

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

743
        s.Noticef("Listening for leafnode connections on %s",
3,437✔
744
                net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
3,437✔
745

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

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

3,437✔
784
        // Setup state that can enable shutdown
3,437✔
785
        s.leafNodeListener = l
3,437✔
786

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

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

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

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

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

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

920
// Makes a deep copy of the LeafNode Info structure.
921
// The server lock is held on entry.
922
func (s *Server) copyLeafNodeInfo() *Info {
2,641✔
923
        clone := s.leafNodeInfo
2,641✔
924
        // Copy the array of urls.
2,641✔
925
        if len(s.leafNodeInfo.LeafNodeURLs) > 0 {
4,788✔
926
                clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...)
2,147✔
927
        }
2,147✔
928
        return &clone
2,641✔
929
}
930

931
// Adds a LeafNode URL that we get when a route connects to the Info structure.
932
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
933
// Returns a boolean indicating if the URL was added or not.
934
// Server lock is held on entry
935
func (s *Server) addLeafNodeURL(urlStr string) bool {
6,867✔
936
        if s.leafURLsMap.addUrl(urlStr) {
13,729✔
937
                s.generateLeafNodeInfoJSON()
6,862✔
938
                return true
6,862✔
939
        }
6,862✔
940
        return false
5✔
941
}
942

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

960
// Server lock is held on entry
961
func (s *Server) generateLeafNodeInfoJSON() {
13,579✔
962
        s.leafNodeInfo.Cluster = s.cachedClusterName()
13,579✔
963
        s.leafNodeInfo.LeafNodeURLs = s.leafURLsMap.getAsStringSlice()
13,579✔
964
        s.leafNodeInfo.WSConnectURLs = s.websocket.connectURLsMap.getAsStringSlice()
13,579✔
965
        s.leafNodeInfoJSON = generateInfoJSON(&s.leafNodeInfo)
13,579✔
966
}
13,579✔
967

968
// Sends an async INFO protocol so that the connected servers can update
969
// their list of LeafNode urls.
970
func (s *Server) sendAsyncLeafNodeInfo() {
10,142✔
971
        for _, c := range s.leafs {
10,247✔
972
                c.mu.Lock()
105✔
973
                c.enqueueProto(s.leafNodeInfoJSON)
105✔
974
                c.mu.Unlock()
105✔
975
        }
105✔
976
}
977

978
// Called when an inbound leafnode connection is accepted or we create one for a solicited leafnode.
979
func (s *Server) createLeafNode(conn net.Conn, rURL *url.URL, remote *leafNodeCfg, ws *websocket) *client {
1,627✔
980
        // Snapshot server options.
1,627✔
981
        opts := s.getOpts()
1,627✔
982

1,627✔
983
        maxPay := int32(opts.MaxPayload)
1,627✔
984
        maxSubs := int32(opts.MaxSubs)
1,627✔
985
        // For system, maxSubs of 0 means unlimited, so re-adjust here.
1,627✔
986
        if maxSubs == 0 {
3,253✔
987
                maxSubs = -1
1,626✔
988
        }
1,626✔
989
        now := time.Now().UTC()
1,627✔
990

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

1,627✔
995
        // If the leafnode subject interest should be isolated, flag it here.
1,627✔
996
        s.optsMu.RLock()
1,627✔
997
        c.leaf.isolated = s.opts.LeafNode.IsolateLeafnodeInterest
1,627✔
998
        s.optsMu.RUnlock()
1,627✔
999

1,627✔
1000
        // For accepted LN connections, ws will be != nil if it was accepted
1,627✔
1001
        // through the Websocket port.
1,627✔
1002
        c.ws = ws
1,627✔
1003

1,627✔
1004
        // For remote, check if the scheme starts with "ws", if so, we will initiate
1,627✔
1005
        // a remote Leaf Node connection as a websocket connection.
1,627✔
1006
        if remote != nil && rURL != nil && isWSURL(rURL) {
1,670✔
1007
                remote.RLock()
43✔
1008
                c.ws = &websocket{compress: remote.Websocket.Compression, maskwrite: !remote.Websocket.NoMasking}
43✔
1009
                remote.RUnlock()
43✔
1010
        }
43✔
1011

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

1034
        c.mu.Lock()
1,625✔
1035
        c.initClient()
1,625✔
1036
        c.Noticef("Leafnode connection created%s %s", remoteSuffix, c.opts.Name)
1,625✔
1037

1,625✔
1038
        var (
1,625✔
1039
                tlsFirst         bool
1,625✔
1040
                tlsFirstFallback time.Duration
1,625✔
1041
                infoTimeout      time.Duration
1,625✔
1042
        )
1,625✔
1043
        if remote != nil {
2,404✔
1044
                solicited = true
779✔
1045
                remote.Lock()
779✔
1046
                c.leaf.remote = remote
779✔
1047
                c.setPermissions(remote.perms)
779✔
1048
                if !c.leaf.remote.Hub {
1,552✔
1049
                        c.leaf.isSpoke = true
773✔
1050
                }
773✔
1051
                tlsFirst = remote.TLSHandshakeFirst
779✔
1052
                infoTimeout = remote.FirstInfoTimeout
779✔
1053
                remote.Unlock()
779✔
1054
                c.acc = acc
779✔
1055
        } else {
846✔
1056
                c.flags.set(expectConnect)
846✔
1057
                if ws != nil {
873✔
1058
                        c.Debugf("Leafnode compression=%v", c.ws.compress)
27✔
1059
                }
27✔
1060
                tlsFirst = opts.LeafNode.TLSHandshakeFirst
846✔
1061
                if f := opts.LeafNode.TLSHandshakeFirstFallback; f > 0 {
847✔
1062
                        tlsFirstFallback = f
1✔
1063
                }
1✔
1064
        }
1065
        c.mu.Unlock()
1,625✔
1066

1,625✔
1067
        var nonce [nonceLen]byte
1,625✔
1068
        var info *Info
1,625✔
1069

1,625✔
1070
        // Grab this before the client lock below.
1,625✔
1071
        if !solicited {
2,471✔
1072
                // Grab server variables
846✔
1073
                s.mu.Lock()
846✔
1074
                info = s.copyLeafNodeInfo()
846✔
1075
                // For tests that want to simulate old servers, do not set the compression
846✔
1076
                // on the INFO protocol if configured with CompressionNotSupported.
846✔
1077
                if cm := opts.LeafNode.Compression.Mode; cm != CompressionNotSupported {
1,691✔
1078
                        info.Compression = cm
845✔
1079
                }
845✔
1080
                // We always send a nonce for LEAF connections. Do not change that without
1081
                // taking into account presence of proxy trusted keys.
1082
                s.generateNonce(nonce[:])
846✔
1083
                s.mu.Unlock()
846✔
1084
        }
1085

1086
        // Grab lock
1087
        c.mu.Lock()
1,625✔
1088

1,625✔
1089
        var preBuf []byte
1,625✔
1090
        if solicited {
2,404✔
1091
                // For websocket connection, we need to send an HTTP request,
779✔
1092
                // and get the response before starting the readLoop to get
779✔
1093
                // the INFO, etc..
779✔
1094
                if c.isWebsocket() {
822✔
1095
                        var err error
43✔
1096
                        var closeReason ClosedState
43✔
1097

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

1119
                // We will process the INFO from the readloop and finish by
1120
                // sending the CONNECT and finish registration later.
1121
        } else {
846✔
1122
                // Send our info to the other side.
846✔
1123
                // Remember the nonce we sent here for signatures, etc.
846✔
1124
                c.nonce = make([]byte, nonceLen)
846✔
1125
                copy(c.nonce, nonce[:])
846✔
1126
                info.Nonce = bytesToString(c.nonce)
846✔
1127
                info.CID = c.cid
846✔
1128
                proto := generateInfoJSON(info)
846✔
1129

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

1155
                if !tlsFirst {
1,687✔
1156
                        // We have to send from this go routine because we may
841✔
1157
                        // have to block for TLS handshake before we start our
841✔
1158
                        // writeLoop go routine. The other side needs to receive
841✔
1159
                        // this before it can initiate the TLS handshake..
841✔
1160
                        c.sendProtoNow(proto)
841✔
1161

841✔
1162
                        // The above call could have marked the connection as closed (due to TCP error).
841✔
1163
                        if c.isClosed() {
841✔
1164
                                c.mu.Unlock()
×
1165
                                c.closeConnection(WriteError)
×
1166
                                return nil
×
1167
                        }
×
1168
                }
1169

1170
                // Check to see if we need to spin up TLS.
1171
                if !c.isWebsocket() && info.TLSRequired {
919✔
1172
                        // If we have a prebuffer create a multi-reader.
73✔
1173
                        if len(pre) > 0 {
73✔
1174
                                c.nc = &tlsMixConn{c.nc, bytes.NewBuffer(pre)}
×
1175
                        }
×
1176
                        // Perform server-side TLS handshake.
1177
                        if err := c.doTLSServerHandshake(tlsHandshakeLeaf, opts.LeafNode.TLSConfig, opts.LeafNode.TLSTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
119✔
1178
                                c.mu.Unlock()
46✔
1179
                                return nil
46✔
1180
                        }
46✔
1181
                }
1182

1183
                // If the user wants the TLS handshake to occur first, now that it is
1184
                // done, send the INFO protocol.
1185
                if tlsFirst {
803✔
1186
                        c.flags.set(didTLSFirst)
3✔
1187
                        c.sendProtoNow(proto)
3✔
1188
                        if c.isClosed() {
3✔
1189
                                c.mu.Unlock()
×
1190
                                c.closeConnection(WriteError)
×
1191
                                return nil
×
1192
                        }
×
1193
                }
1194

1195
                // Leaf nodes will always require a CONNECT to let us know
1196
                // when we are properly bound to an account.
1197
                //
1198
                // If compression is configured, we can't set the authTimer here because
1199
                // it would cause the parser to fail any incoming protocol that is not a
1200
                // CONNECT (and we need to exchange INFO protocols for compression
1201
                // negotiation). So instead, use the ping timer until we are done with
1202
                // negotiation and can set the auth timer.
1203
                timeout := secondsToDuration(opts.LeafNode.AuthTimeout)
800✔
1204
                if needsCompression(opts.LeafNode.Compression.Mode) {
1,386✔
1205
                        c.ping.tmr = time.AfterFunc(timeout, func() {
590✔
1206
                                c.authTimeout()
4✔
1207
                        })
4✔
1208
                } else {
214✔
1209
                        c.setAuthTimer(timeout)
214✔
1210
                }
214✔
1211
        }
1212

1213
        // Keep track in case server is shutdown before we can successfully register.
1214
        if !s.addToTempClients(c.cid, c) {
1,563✔
1215
                c.mu.Unlock()
1✔
1216
                c.setNoReconnect()
1✔
1217
                c.closeConnection(ServerShutdown)
1✔
1218
                return nil
1✔
1219
        }
1✔
1220

1221
        // Spin up the read loop.
1222
        s.startGoRoutine(func() { c.readLoop(preBuf) })
3,122✔
1223

1224
        // We will spin the write loop for solicited connections only
1225
        // when processing the INFO and after switching to TLS if needed.
1226
        if !solicited {
2,361✔
1227
                s.startGoRoutine(func() { c.writeLoop() })
1,600✔
1228
        }
1229

1230
        c.mu.Unlock()
1,561✔
1231

1,561✔
1232
        return c
1,561✔
1233
}
1234

1235
// Will perform the client-side TLS handshake if needed. Assumes that this
1236
// is called by the solicit side (remote will be non nil). Returns `true`
1237
// if TLS is required, `false` otherwise.
1238
// Lock held on entry.
1239
func (c *client) leafClientHandshakeIfNeeded(remote *leafNodeCfg, opts *Options) (bool, error) {
1,878✔
1240
        // Check if TLS is required and gather TLS config variables.
1,878✔
1241
        tlsRequired, tlsConfig, tlsName, tlsTimeout := c.leafNodeGetTLSConfigForSolicit(remote)
1,878✔
1242
        if !tlsRequired {
3,676✔
1243
                return false, nil
1,798✔
1244
        }
1,798✔
1245

1246
        // If TLS required, peform handshake.
1247
        // Get the URL that was used to connect to the remote server.
1248
        rURL := remote.getCurrentURL()
80✔
1249

80✔
1250
        // Perform the client-side TLS handshake.
80✔
1251
        if resetTLSName, err := c.doTLSClientHandshake(tlsHandshakeLeaf, rURL, tlsConfig, tlsName, tlsTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
119✔
1252
                // Check if we need to reset the remote's TLS name.
39✔
1253
                if resetTLSName {
39✔
1254
                        remote.Lock()
×
1255
                        remote.tlsName = _EMPTY_
×
1256
                        remote.Unlock()
×
1257
                }
×
1258
                return false, err
39✔
1259
        }
1260
        return true, nil
41✔
1261
}
1262

1263
func (c *client) processLeafnodeInfo(info *Info) {
2,606✔
1264
        c.mu.Lock()
2,606✔
1265
        if c.leaf == nil || c.isClosed() {
2,606✔
1266
                c.mu.Unlock()
×
1267
                return
×
1268
        }
×
1269
        s := c.srv
2,606✔
1270
        opts := s.getOpts()
2,606✔
1271
        remote := c.leaf.remote
2,606✔
1272
        didSolicit := remote != nil
2,606✔
1273
        firstINFO := !c.flags.isSet(infoReceived)
2,606✔
1274

2,606✔
1275
        // In case of websocket, the TLS handshake has been already done.
2,606✔
1276
        // So check only for non websocket connections and for configurations
2,606✔
1277
        // where the TLS Handshake was not done first.
2,606✔
1278
        if didSolicit && !c.flags.isSet(handshakeComplete) && !c.isWebsocket() && !remote.TLSHandshakeFirst {
4,437✔
1279
                // If the server requires TLS, we need to set this in the remote
1,831✔
1280
                // otherwise if there is no TLS configuration block for the remote,
1,831✔
1281
                // the solicit side will not attempt to perform the TLS handshake.
1,831✔
1282
                if firstINFO && info.TLSRequired {
1,895✔
1283
                        remote.TLS = true
64✔
1284
                }
64✔
1285
                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
1,865✔
1286
                        c.mu.Unlock()
34✔
1287
                        return
34✔
1288
                }
34✔
1289
        }
1290

1291
        // Check for compression, unless already done.
1292
        if firstINFO && !c.flags.isSet(compressionNegotiated) {
3,848✔
1293
                // Prevent from getting back here.
1,276✔
1294
                c.flags.set(compressionNegotiated)
1,276✔
1295

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

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

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

1411
        // For both initial INFO and async INFO protocols, Possibly
1412
        // update our list of remote leafnode URLs we can connect to.
1413
        if didSolicit && (len(info.LeafNodeURLs) > 0 || len(info.WSConnectURLs) > 0) {
2,674✔
1414
                // Consider the incoming array as the most up-to-date
1,292✔
1415
                // representation of the remote cluster's list of URLs.
1,292✔
1416
                c.updateLeafNodeURLs(info)
1,292✔
1417
        }
1,292✔
1418

1419
        // Check to see if we have permissions updates here.
1420
        if info.Import != nil || info.Export != nil {
1,394✔
1421
                perms := &Permissions{
12✔
1422
                        Publish:   info.Export,
12✔
1423
                        Subscribe: info.Import,
12✔
1424
                }
12✔
1425
                // Check if we have local deny clauses that we need to merge.
12✔
1426
                if remote := c.leaf.remote; remote != nil {
24✔
1427
                        if len(remote.DenyExports) > 0 {
13✔
1428
                                if perms.Publish == nil {
1✔
1429
                                        perms.Publish = &SubjectPermission{}
×
1430
                                }
×
1431
                                perms.Publish.Deny = append(perms.Publish.Deny, remote.DenyExports...)
1✔
1432
                        }
1433
                        if len(remote.DenyImports) > 0 {
13✔
1434
                                if perms.Subscribe == nil {
1✔
1435
                                        perms.Subscribe = &SubjectPermission{}
×
1436
                                }
×
1437
                                perms.Subscribe.Deny = append(perms.Subscribe.Deny, remote.DenyImports...)
1✔
1438
                        }
1439
                }
1440
                c.setPermissions(perms)
12✔
1441
        }
1442

1443
        var resumeConnect, checkSyncConsumers bool
1,382✔
1444

1,382✔
1445
        // If this is a remote connection and this is the first INFO protocol,
1,382✔
1446
        // then we need to finish the connect process by sending CONNECT, etc..
1,382✔
1447
        if firstINFO && didSolicit {
2,043✔
1448
                // Clear deadline that was set in createLeafNode while waiting for the INFO.
661✔
1449
                c.nc.SetDeadline(time.Time{})
661✔
1450
                resumeConnect = true
661✔
1451
        } else if !firstINFO && didSolicit {
2,013✔
1452
                c.leaf.remoteAccName = info.RemoteAccount
631✔
1453
                checkSyncConsumers = info.JetStream
631✔
1454
        }
631✔
1455

1456
        // Check if we have the remote account information and if so make sure it's stored.
1457
        if info.RemoteAccount != _EMPTY_ {
2,001✔
1458
                s.leafRemoteAccounts.Store(c.acc.Name, info.RemoteAccount)
619✔
1459
        }
619✔
1460
        c.mu.Unlock()
1,382✔
1461

1,382✔
1462
        finishConnect := info.ConnectInfo
1,382✔
1463
        if resumeConnect && s != nil {
2,043✔
1464
                s.leafNodeResumeConnectProcess(c)
661✔
1465
                if !info.InfoOnConnect {
661✔
1466
                        finishConnect = true
×
1467
                }
×
1468
        }
1469
        if finishConnect {
2,001✔
1470
                s.leafNodeFinishConnectProcess(c)
619✔
1471
        }
619✔
1472

1473
        // If we have JS enabled and so does the other side, we will
1474
        // check to see if we need to kick any internal source or mirror consumers.
1475
        if checkSyncConsumers {
1,638✔
1476
                s.checkInternalSyncConsumers(c.acc, info.Domain)
256✔
1477
        }
256✔
1478
}
1479

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

1,265✔
1503
        if !needsCompression(cm) {
1,394✔
1504
                return false, nil
129✔
1505
        }
129✔
1506

1507
        // If we end-up doing compression...
1508

1509
        // Generate an INFO with the chosen compression mode.
1510
        s.mu.Lock()
1,136✔
1511
        info := s.copyLeafNodeInfo()
1,136✔
1512
        info.Compression, info.CID, info.Nonce = compressionModeForInfoProtocol(co, cm), cid, nonce
1,136✔
1513
        infoProto := generateInfoJSON(info)
1,136✔
1514
        s.mu.Unlock()
1,136✔
1515

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

1541
// When getting a leaf node INFO protocol, use the provided
1542
// array of urls to update the list of possible endpoints.
1543
func (c *client) updateLeafNodeURLs(info *Info) {
1,292✔
1544
        cfg := c.leaf.remote
1,292✔
1545
        cfg.Lock()
1,292✔
1546
        defer cfg.Unlock()
1,292✔
1547

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

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

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

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

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

1,275✔
1684
        // If applicable, evict the old one.
1,275✔
1685
        if old != nil {
1,277✔
1686
                old.sendErrAndErr(DuplicateRemoteLeafnodeConnection.String())
2✔
1687
                old.closeConnection(DuplicateRemoteLeafnodeConnection)
2✔
1688
                c.Warnf("Replacing connection from same server")
2✔
1689
        }
2✔
1690

1691
        srvDecorated := func() string {
1,482✔
1692
                if myClustName == _EMPTY_ {
229✔
1693
                        return mySrvName
22✔
1694
                }
22✔
1695
                return fmt.Sprintf("%s/%s", mySrvName, myClustName)
185✔
1696
        }
1697

1698
        opts := s.getOpts()
1,275✔
1699
        sysAcc := s.SystemAccount()
1,275✔
1700
        js := s.getJetStream()
1,275✔
1701
        var meta *raft
1,275✔
1702
        if js != nil {
1,792✔
1703
                if mg := js.getMetaGroup(); mg != nil {
941✔
1704
                        meta = mg.(*raft)
424✔
1705
                }
424✔
1706
        }
1707
        blockMappingOutgoing := false
1,275✔
1708
        // Deny (non domain) JetStream API traffic unless system account is shared
1,275✔
1709
        // and domain names are identical and extending is not disabled
1,275✔
1710

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

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

1807
func (s *Server) removeLeafNodeConnection(c *client) {
1,627✔
1808
        c.mu.Lock()
1,627✔
1809
        cid := c.cid
1,627✔
1810
        if c.leaf != nil {
3,254✔
1811
                if c.leaf.tsubt != nil {
2,752✔
1812
                        c.leaf.tsubt.Stop()
1,125✔
1813
                        c.leaf.tsubt = nil
1,125✔
1814
                }
1,125✔
1815
                if c.leaf.gwSub != nil {
2,244✔
1816
                        s.gwLeafSubs.Remove(c.leaf.gwSub)
617✔
1817
                        // We need to set this to nil for GC to release the connection
617✔
1818
                        c.leaf.gwSub = nil
617✔
1819
                }
617✔
1820
        }
1821
        proxyKey := c.proxyKey
1,627✔
1822
        c.mu.Unlock()
1,627✔
1823
        s.mu.Lock()
1,627✔
1824
        delete(s.leafs, cid)
1,627✔
1825
        if proxyKey != _EMPTY_ {
1,631✔
1826
                s.removeProxiedConn(proxyKey, cid)
4✔
1827
        }
4✔
1828
        s.mu.Unlock()
1,627✔
1829
        s.removeFromTempClients(cid)
1,627✔
1830
}
1831

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

1850
        // There was an existing field called:
1851
        // >> Comp bool `json:"compression,omitempty"`
1852
        // that has never been used. With support for compression, we now need
1853
        // a field that is a string. So we use a different json tag:
1854
        Compression string `json:"compress_mode,omitempty"`
1855

1856
        // Just used to detect wrong connection attempts.
1857
        Gateway string `json:"gateway,omitempty"`
1858

1859
        // Tells the accept side which account the remote is binding to.
1860
        RemoteAccount string `json:"remote_account,omitempty"`
1861

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

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

1883
        // Unmarshal as a leaf node connect protocol
1884
        proto := &leafConnectInfo{}
663✔
1885
        if err := json.Unmarshal(arg, proto); err != nil {
663✔
1886
                return err
×
1887
        }
×
1888

1889
        // Reject a cluster that contains spaces.
1890
        if proto.Cluster != _EMPTY_ && strings.Contains(proto.Cluster, " ") {
664✔
1891
                c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
1892
                c.closeConnection(ProtocolViolation)
1✔
1893
                return ErrClusterNameHasSpaces
1✔
1894
        }
1✔
1895

1896
        // Check for cluster name collisions.
1897
        if cn := s.cachedClusterName(); cn != _EMPTY_ && proto.Cluster != _EMPTY_ && proto.Cluster == cn {
665✔
1898
                c.sendErrAndErr(ErrLeafNodeHasSameClusterName.Error())
3✔
1899
                c.closeConnection(ClusterNamesIdentical)
3✔
1900
                return ErrLeafNodeHasSameClusterName
3✔
1901
        }
3✔
1902

1903
        // Reject if this has Gateway which means that it would be from a gateway
1904
        // connection that incorrectly connects to the leafnode port.
1905
        if proto.Gateway != _EMPTY_ {
659✔
1906
                errTxt := fmt.Sprintf("Rejecting connection from gateway %q on the leafnode port", proto.Gateway)
×
1907
                c.Errorf(errTxt)
×
1908
                c.sendErr(errTxt)
×
1909
                c.closeConnection(WrongGateway)
×
1910
                return ErrWrongGateway
×
1911
        }
×
1912

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

1932
        // Check if this server supports headers.
1933
        supportHeaders := c.srv.supportsHeaders()
658✔
1934

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

1955
        // Remember the remote server.
1956
        c.leaf.remoteServer = proto.Name
658✔
1957
        // Remember the remote account name
658✔
1958
        c.leaf.remoteAccName = proto.RemoteAccount
658✔
1959

658✔
1960
        // If the other side has declared itself a hub, so we will take on the spoke role.
658✔
1961
        if proto.Hub {
664✔
1962
                c.leaf.isSpoke = true
6✔
1963
        }
6✔
1964

1965
        // The soliciting side is part of a cluster.
1966
        if proto.Cluster != _EMPTY_ {
1,164✔
1967
                c.leaf.remoteCluster = proto.Cluster
506✔
1968
        }
506✔
1969

1970
        c.leaf.remoteDomain = proto.Domain
658✔
1971

658✔
1972
        // When a leaf solicits a connection to a hub, the perms that it will use on the soliciting leafnode's
658✔
1973
        // behalf are correct for them, but inside the hub need to be reversed since data is flowing in the opposite direction.
658✔
1974
        if !c.isSolicitedLeafNode() && c.perms != nil {
671✔
1975
                sp, pp := c.perms.sub, c.perms.pub
13✔
1976
                c.perms.sub, c.perms.pub = pp, sp
13✔
1977
                if c.opts.Import != nil {
25✔
1978
                        c.darray = c.opts.Import.Deny
12✔
1979
                } else {
13✔
1980
                        c.darray = nil
1✔
1981
                }
1✔
1982
        }
1983

1984
        // Set the Ping timer
1985
        c.setFirstPingTimer()
658✔
1986

658✔
1987
        // If we received pub deny permissions from the other end, merge with existing ones.
658✔
1988
        c.mergeDenyPermissions(pub, proto.DenyPub)
658✔
1989

658✔
1990
        acc := c.acc
658✔
1991
        c.mu.Unlock()
658✔
1992

658✔
1993
        // Register the cluster, even if empty, as long as we are acting as a hub.
658✔
1994
        if !proto.Hub {
1,310✔
1995
                acc.registerLeafNodeCluster(proto.Cluster)
652✔
1996
        }
652✔
1997

1998
        // Add in the leafnode here since we passed through auth at this point.
1999
        s.addLeafNodeConnection(c, proto.Name, proto.Cluster, true)
658✔
2000

658✔
2001
        // If we have permissions bound to this leafnode we need to send then back to the
658✔
2002
        // origin server for local enforcement.
658✔
2003
        s.sendPermsAndAccountInfo(c)
658✔
2004

658✔
2005
        // Create and initialize the smap since we know our bound account now.
658✔
2006
        // This will send all registered subs too.
658✔
2007
        s.initLeafNodeSmapAndSendSubs(c)
658✔
2008

658✔
2009
        // Announce the account connect event for a leaf node.
658✔
2010
        // This will be a no-op as needed.
658✔
2011
        s.sendLeafNodeConnect(c.acc)
658✔
2012

658✔
2013
        // If we have JS enabled and so does the other side, we will
658✔
2014
        // check to see if we need to kick any internal source or mirror consumers.
658✔
2015
        if proto.JetStream {
895✔
2016
                s.checkInternalSyncConsumers(acc, proto.Domain)
237✔
2017
        }
237✔
2018
        return nil
658✔
2019
}
2020

2021
// checkInternalSyncConsumers
2022
func (s *Server) checkInternalSyncConsumers(acc *Account, remoteDomain string) {
493✔
2023
        // Grab our js
493✔
2024
        js := s.getJetStream()
493✔
2025

493✔
2026
        // Only applicable if we have JS and the leafnode has JS as well.
493✔
2027
        // We check for remote JS outside.
493✔
2028
        if !js.isEnabled() || acc == nil {
616✔
2029
                return
123✔
2030
        }
123✔
2031

2032
        // We will check all streams in our local account. They must be a leader and
2033
        // be sourcing or mirroring. We will check the external config on the stream itself
2034
        // if this is cross domain, or if the remote domain is empty, meaning we might be
2035
        // extedning the system across this leafnode connection and hence we would be extending
2036
        // our own domain.
2037
        jsa := js.lookupAccount(acc)
370✔
2038
        if jsa == nil {
479✔
2039
                return
109✔
2040
        }
109✔
2041
        var streams []*stream
261✔
2042
        jsa.mu.RLock()
261✔
2043
        for _, mset := range jsa.streams {
281✔
2044
                mset.cfgMu.RLock()
20✔
2045
                // We need to have a mirror or source defined.
20✔
2046
                // We do not want to force another lock here to look for leader status,
20✔
2047
                // so collect and after we release jsa will make sure.
20✔
2048
                if mset.cfg.Mirror != nil || len(mset.cfg.Sources) > 0 {
24✔
2049
                        streams = append(streams, mset)
4✔
2050
                }
4✔
2051
                mset.cfgMu.RUnlock()
20✔
2052
        }
2053
        jsa.mu.RUnlock()
261✔
2054

261✔
2055
        // Now loop through all candidates and check if we are the leader and have NOT
261✔
2056
        // created the sync up consumer.
261✔
2057
        for _, mset := range streams {
265✔
2058
                mset.retryDisconnectedSyncConsumers(remoteDomain)
4✔
2059
        }
4✔
2060
}
2061

2062
// Returns the remote cluster name. This is set only once so does not require a lock.
2063
func (c *client) remoteCluster() string {
126,760✔
2064
        if c.leaf == nil {
126,760✔
2065
                return _EMPTY_
×
2066
        }
×
2067
        return c.leaf.remoteCluster
126,760✔
2068
}
2069

2070
// Sends back an info block to the soliciting leafnode to let it know about
2071
// its permission settings for local enforcement.
2072
func (s *Server) sendPermsAndAccountInfo(c *client) {
659✔
2073
        // Copy
659✔
2074
        s.mu.Lock()
659✔
2075
        info := s.copyLeafNodeInfo()
659✔
2076
        s.mu.Unlock()
659✔
2077
        c.mu.Lock()
659✔
2078
        info.CID = c.cid
659✔
2079
        info.Import = c.opts.Import
659✔
2080
        info.Export = c.opts.Export
659✔
2081
        info.RemoteAccount = c.acc.Name
659✔
2082
        // s.SystemAccount() uses an atomic operation and does not get the server lock, so this is safe.
659✔
2083
        info.IsSystemAccount = c.acc == s.SystemAccount()
659✔
2084
        info.ConnectInfo = true
659✔
2085
        c.enqueueProto(generateInfoJSON(info))
659✔
2086
        c.mu.Unlock()
659✔
2087
}
659✔
2088

2089
// Snapshot the current subscriptions from the sublist into our smap which
2090
// we will keep updated from now on.
2091
// Also send the registered subscriptions.
2092
func (s *Server) initLeafNodeSmapAndSendSubs(c *client) {
1,275✔
2093
        acc := c.acc
1,275✔
2094
        if acc == nil {
1,275✔
2095
                c.Debugf("Leafnode does not have an account bound")
×
2096
                return
×
2097
        }
×
2098
        // Collect all account subs here.
2099
        _subs := [1024]*subscription{}
1,275✔
2100
        subs := _subs[:0]
1,275✔
2101
        ims := []string{}
1,275✔
2102

1,275✔
2103
        // Hold the client lock otherwise there can be a race and miss some subs.
1,275✔
2104
        c.mu.Lock()
1,275✔
2105
        defer c.mu.Unlock()
1,275✔
2106

1,275✔
2107
        acc.mu.RLock()
1,275✔
2108
        accName := acc.Name
1,275✔
2109
        accNTag := acc.nameTag
1,275✔
2110

1,275✔
2111
        // To make printing look better when no friendly name present.
1,275✔
2112
        if accNTag != _EMPTY_ {
1,286✔
2113
                accNTag = "/" + accNTag
11✔
2114
        }
11✔
2115

2116
        // If we are solicited we only send interest for local clients.
2117
        if c.isSpokeLeafNode() {
1,892✔
2118
                acc.sl.localSubs(&subs, true)
617✔
2119
        } else {
1,275✔
2120
                acc.sl.All(&subs)
658✔
2121
        }
658✔
2122

2123
        // Check if we have an existing service import reply.
2124
        siReply := copyBytes(acc.siReply)
1,275✔
2125

1,275✔
2126
        // Since leaf nodes only send on interest, if the bound
1,275✔
2127
        // account has import services we need to send those over.
1,275✔
2128
        for isubj := range acc.imports.services {
5,999✔
2129
                if c.isSpokeLeafNode() && !c.canSubscribe(isubj) {
4,996✔
2130
                        c.Debugf("Not permitted to import service %q on behalf of %s%s", isubj, accName, accNTag)
272✔
2131
                        continue
272✔
2132
                }
2133
                ims = append(ims, isubj)
4,452✔
2134
        }
2135
        // Likewise for mappings.
2136
        for _, m := range acc.mappings {
3,456✔
2137
                if c.isSpokeLeafNode() && !c.canSubscribe(m.src) {
2,217✔
2138
                        c.Debugf("Not permitted to import mapping %q on behalf of %s%s", m.src, accName, accNTag)
36✔
2139
                        continue
36✔
2140
                }
2141
                ims = append(ims, m.src)
2,145✔
2142
        }
2143

2144
        // Create a unique subject that will be used for loop detection.
2145
        lds := acc.lds
1,275✔
2146
        acc.mu.RUnlock()
1,275✔
2147

1,275✔
2148
        // Check if we have to create the LDS.
1,275✔
2149
        if lds == _EMPTY_ {
2,274✔
2150
                lds = leafNodeLoopDetectionSubjectPrefix + nuid.Next()
999✔
2151
                acc.mu.Lock()
999✔
2152
                acc.lds = lds
999✔
2153
                acc.mu.Unlock()
999✔
2154
        }
999✔
2155

2156
        // Now check for gateway interest. Leafnodes will put this into
2157
        // the proper mode to propagate, but they are not held in the account.
2158
        gwsa := [16]*client{}
1,275✔
2159
        gws := gwsa[:0]
1,275✔
2160
        s.getOutboundGatewayConnections(&gws)
1,275✔
2161
        for _, cgw := range gws {
1,357✔
2162
                cgw.mu.Lock()
82✔
2163
                gw := cgw.gw
82✔
2164
                cgw.mu.Unlock()
82✔
2165
                if gw != nil {
164✔
2166
                        if ei, _ := gw.outsim.Load(accName); ei != nil {
164✔
2167
                                if e := ei.(*outsie); e != nil && e.sl != nil {
164✔
2168
                                        e.sl.All(&subs)
82✔
2169
                                }
82✔
2170
                        }
2171
                }
2172
        }
2173

2174
        applyGlobalRouting := s.gateway.enabled
1,275✔
2175
        if c.isSpokeLeafNode() {
1,892✔
2176
                // Add a fake subscription for this solicited leafnode connection
617✔
2177
                // so that we can send back directly for mapped GW replies.
617✔
2178
                // We need to keep track of this subscription so it can be removed
617✔
2179
                // when the connection is closed so that the GC can release it.
617✔
2180
                c.leaf.gwSub = &subscription{client: c, subject: []byte(gwReplyPrefix + ">")}
617✔
2181
                c.srv.gwLeafSubs.Insert(c.leaf.gwSub)
617✔
2182
        }
617✔
2183

2184
        // Now walk the results and add them to our smap
2185
        rc := c.leaf.remoteCluster
1,275✔
2186
        c.leaf.smap = make(map[string]int32)
1,275✔
2187
        for _, sub := range subs {
38,442✔
2188
                // Check perms regardless of role.
37,167✔
2189
                if c.perms != nil && !c.canSubscribe(string(sub.subject)) {
39,485✔
2190
                        c.Debugf("Not permitted to subscribe to %q on behalf of %s%s", sub.subject, accName, accNTag)
2,318✔
2191
                        continue
2,318✔
2192
                }
2193
                // Don't advertise interest from leafnodes to other isolated leafnodes.
2194
                if sub.client.kind == LEAF && c.isIsolatedLeafNode() {
34,854✔
2195
                        continue
5✔
2196
                }
2197
                // We ignore ourselves here.
2198
                // Also don't add the subscription if it has a origin cluster and the
2199
                // cluster name matches the one of the client we are sending to.
2200
                if c != sub.client && (sub.origin == nil || (bytesToString(sub.origin) != rc)) {
64,423✔
2201
                        count := int32(1)
29,579✔
2202
                        if len(sub.queue) > 0 && sub.qw > 0 {
29,590✔
2203
                                count = sub.qw
11✔
2204
                        }
11✔
2205
                        c.leaf.smap[keyFromSub(sub)] += count
29,579✔
2206
                        if c.leaf.tsub == nil {
30,778✔
2207
                                c.leaf.tsub = make(map[*subscription]struct{})
1,199✔
2208
                        }
1,199✔
2209
                        c.leaf.tsub[sub] = struct{}{}
29,579✔
2210
                }
2211
        }
2212
        // FIXME(dlc) - We need to update appropriately on an account claims update.
2213
        for _, isubj := range ims {
7,872✔
2214
                c.leaf.smap[isubj]++
6,597✔
2215
        }
6,597✔
2216
        // If we have gateways enabled we need to make sure the other side sends us responses
2217
        // that have been augmented from the original subscription.
2218
        // TODO(dlc) - Should we lock this down more?
2219
        if applyGlobalRouting {
1,378✔
2220
                c.leaf.smap[oldGWReplyPrefix+"*.>"]++
103✔
2221
                c.leaf.smap[gwReplyPrefix+">"]++
103✔
2222
        }
103✔
2223
        // Detect loops by subscribing to a specific subject and checking
2224
        // if this sub is coming back to us.
2225
        c.leaf.smap[lds]++
1,275✔
2226

1,275✔
2227
        // Check if we need to add an existing siReply to our map.
1,275✔
2228
        // This will be a prefix so add on the wildcard.
1,275✔
2229
        if siReply != nil {
1,294✔
2230
                wcsub := append(siReply, '>')
19✔
2231
                c.leaf.smap[string(wcsub)]++
19✔
2232
        }
19✔
2233
        // Queue all protocols. There is no max pending limit for LN connection,
2234
        // so we don't need chunking. The writes will happen from the writeLoop.
2235
        var b bytes.Buffer
1,275✔
2236
        for key, n := range c.leaf.smap {
27,333✔
2237
                c.writeLeafSub(&b, key, n)
26,058✔
2238
        }
26,058✔
2239
        if b.Len() > 0 {
2,550✔
2240
                c.enqueueProto(b.Bytes())
1,275✔
2241
        }
1,275✔
2242
        if c.leaf.tsub != nil {
2,475✔
2243
                // Clear the tsub map after 5 seconds.
1,200✔
2244
                c.leaf.tsubt = time.AfterFunc(5*time.Second, func() {
1,275✔
2245
                        c.mu.Lock()
75✔
2246
                        if c.leaf != nil {
150✔
2247
                                c.leaf.tsub = nil
75✔
2248
                                c.leaf.tsubt = nil
75✔
2249
                        }
75✔
2250
                        c.mu.Unlock()
75✔
2251
                })
2252
        }
2253
}
2254

2255
// updateInterestForAccountOnGateway called from gateway code when processing RS+ and RS-.
2256
func (s *Server) updateInterestForAccountOnGateway(accName string, sub *subscription, delta int32) {
197,315✔
2257
        acc, err := s.LookupAccount(accName)
197,315✔
2258
        if acc == nil || err != nil {
197,474✔
2259
                s.Debugf("No or bad account for %q, failed to update interest from gateway", accName)
159✔
2260
                return
159✔
2261
        }
159✔
2262
        acc.updateLeafNodes(sub, delta)
197,156✔
2263
}
2264

2265
// updateLeafNodes will make sure to update the account smap for the subscription.
2266
// Will also forward to all leaf nodes as needed.
2267
func (acc *Account) updateLeafNodes(sub *subscription, delta int32) {
2,454,967✔
2268
        if acc == nil || sub == nil {
2,454,967✔
2269
                return
×
2270
        }
×
2271

2272
        // We will do checks for no leafnodes and same cluster here inline and under the
2273
        // general account read lock.
2274
        // If we feel we need to update the leafnodes we will do that out of line to avoid
2275
        // blocking routes or GWs.
2276

2277
        acc.mu.RLock()
2,454,967✔
2278
        // First check if we even have leafnodes here.
2,454,967✔
2279
        if acc.nleafs == 0 {
4,844,009✔
2280
                acc.mu.RUnlock()
2,389,042✔
2281
                return
2,389,042✔
2282
        }
2,389,042✔
2283

2284
        // Is this a loop detection subject.
2285
        isLDS := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
65,925✔
2286

65,925✔
2287
        // Capture the cluster even if its empty.
65,925✔
2288
        var cluster string
65,925✔
2289
        if sub.origin != nil {
113,475✔
2290
                cluster = bytesToString(sub.origin)
47,550✔
2291
        }
47,550✔
2292

2293
        // If we have an isolated cluster we can return early, as long as it is not a loop detection subject.
2294
        // Empty clusters will return false for the check.
2295
        if !isLDS && acc.isLeafNodeClusterIsolated(cluster) {
86,698✔
2296
                acc.mu.RUnlock()
20,773✔
2297
                return
20,773✔
2298
        }
20,773✔
2299

2300
        // We can release the general account lock.
2301
        acc.mu.RUnlock()
45,152✔
2302

45,152✔
2303
        // We can hold the list lock here to avoid having to copy a large slice.
45,152✔
2304
        acc.lmu.RLock()
45,152✔
2305
        defer acc.lmu.RUnlock()
45,152✔
2306

45,152✔
2307
        // Do this once.
45,152✔
2308
        subject := string(sub.subject)
45,152✔
2309

45,152✔
2310
        // Walk the connected leafnodes.
45,152✔
2311
        for _, ln := range acc.lleafs {
101,692✔
2312
                if ln == sub.client {
85,703✔
2313
                        continue
29,163✔
2314
                }
2315
                // Don't advertise interest from leafnodes to other isolated leafnodes.
2316
                if sub.client.kind == LEAF && ln.isIsolatedLeafNode() {
27,389✔
2317
                        continue
12✔
2318
                }
2319
                // Check to make sure this sub does not have an origin cluster that matches the leafnode.
2320
                ln.mu.Lock()
27,365✔
2321
                // If skipped, make sure that we still let go the "$LDS." subscription that allows
27,365✔
2322
                // the detection of loops as long as different cluster.
27,365✔
2323
                clusterDifferent := cluster != ln.remoteCluster()
27,365✔
2324
                if (isLDS && clusterDifferent) || ((cluster == _EMPTY_ || clusterDifferent) && (delta <= 0 || ln.canSubscribe(subject))) {
50,692✔
2325
                        ln.updateSmap(sub, delta, isLDS)
23,327✔
2326
                }
23,327✔
2327
                ln.mu.Unlock()
27,365✔
2328
        }
2329
}
2330

2331
// This will make an update to our internal smap and determine if we should send out
2332
// an interest update to the remote side.
2333
// Lock should be held.
2334
func (c *client) updateSmap(sub *subscription, delta int32, isLDS bool) {
23,327✔
2335
        if c.leaf.smap == nil {
23,336✔
2336
                return
9✔
2337
        }
9✔
2338

2339
        // If we are solicited make sure this is a local client or a non-solicited leaf node
2340
        skind := sub.client.kind
23,318✔
2341
        updateClient := skind == CLIENT || skind == SYSTEM || skind == JETSTREAM || skind == ACCOUNT
23,318✔
2342
        if !isLDS && c.isSpokeLeafNode() && !(updateClient || (skind == LEAF && !sub.client.isSpokeLeafNode())) {
31,555✔
2343
                return
8,237✔
2344
        }
8,237✔
2345

2346
        // For additions, check if that sub has just been processed during initLeafNodeSmapAndSendSubs
2347
        if delta > 0 && c.leaf.tsub != nil {
22,285✔
2348
                if _, present := c.leaf.tsub[sub]; present {
7,205✔
2349
                        delete(c.leaf.tsub, sub)
1✔
2350
                        if len(c.leaf.tsub) == 0 {
1✔
2351
                                c.leaf.tsub = nil
×
2352
                                c.leaf.tsubt.Stop()
×
2353
                                c.leaf.tsubt = nil
×
2354
                        }
×
2355
                        return
1✔
2356
                }
2357
        }
2358

2359
        key := keyFromSub(sub)
15,080✔
2360
        n, ok := c.leaf.smap[key]
15,080✔
2361
        if delta < 0 && !ok {
15,999✔
2362
                return
919✔
2363
        }
919✔
2364

2365
        // We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
2366
        update := sub.queue != nil || (n <= 0 && n+delta > 0) || (n > 0 && n+delta <= 0)
14,161✔
2367
        n += delta
14,161✔
2368
        if n > 0 {
24,769✔
2369
                c.leaf.smap[key] = n
10,608✔
2370
        } else {
14,161✔
2371
                delete(c.leaf.smap, key)
3,553✔
2372
        }
3,553✔
2373
        if update {
23,617✔
2374
                c.sendLeafNodeSubUpdate(key, n)
9,456✔
2375
        }
9,456✔
2376
}
2377

2378
// Used to force add subjects to the subject map.
2379
func (c *client) forceAddToSmap(subj string) {
4✔
2380
        c.mu.Lock()
4✔
2381
        defer c.mu.Unlock()
4✔
2382

4✔
2383
        if c.leaf.smap == nil {
4✔
2384
                return
×
2385
        }
×
2386
        n := c.leaf.smap[subj]
4✔
2387
        if n != 0 {
5✔
2388
                return
1✔
2389
        }
1✔
2390
        // Place into the map since it was not there.
2391
        c.leaf.smap[subj] = 1
3✔
2392
        c.sendLeafNodeSubUpdate(subj, 1)
3✔
2393
}
2394

2395
// Used to force remove a subject from the subject map.
2396
func (c *client) forceRemoveFromSmap(subj string) {
1✔
2397
        c.mu.Lock()
1✔
2398
        defer c.mu.Unlock()
1✔
2399

1✔
2400
        if c.leaf.smap == nil {
1✔
2401
                return
×
2402
        }
×
2403
        n := c.leaf.smap[subj]
1✔
2404
        if n == 0 {
1✔
2405
                return
×
2406
        }
×
2407
        n--
1✔
2408
        if n == 0 {
2✔
2409
                // Remove is now zero
1✔
2410
                delete(c.leaf.smap, subj)
1✔
2411
                c.sendLeafNodeSubUpdate(subj, 0)
1✔
2412
        } else {
1✔
2413
                c.leaf.smap[subj] = n
×
2414
        }
×
2415
}
2416

2417
// Send the subscription interest change to the other side.
2418
// Lock should be held.
2419
func (c *client) sendLeafNodeSubUpdate(key string, n int32) {
9,460✔
2420
        // If we are a spoke, we need to check if we are allowed to send this subscription over to the hub.
9,460✔
2421
        if c.isSpokeLeafNode() {
11,760✔
2422
                checkPerms := true
2,300✔
2423
                if len(key) > 0 && (key[0] == '$' || key[0] == '_') {
3,639✔
2424
                        if strings.HasPrefix(key, leafNodeLoopDetectionSubjectPrefix) ||
1,339✔
2425
                                strings.HasPrefix(key, oldGWReplyPrefix) ||
1,339✔
2426
                                strings.HasPrefix(key, gwReplyPrefix) {
1,423✔
2427
                                checkPerms = false
84✔
2428
                        }
84✔
2429
                }
2430
                if checkPerms {
4,516✔
2431
                        var subject string
2,216✔
2432
                        if sep := strings.IndexByte(key, ' '); sep != -1 {
2,707✔
2433
                                subject = key[:sep]
491✔
2434
                        } else {
2,216✔
2435
                                subject = key
1,725✔
2436
                        }
1,725✔
2437
                        if !c.canSubscribe(subject) {
2,216✔
2438
                                return
×
2439
                        }
×
2440
                }
2441
        }
2442
        // If we are here we can send over to the other side.
2443
        _b := [64]byte{}
9,460✔
2444
        b := bytes.NewBuffer(_b[:0])
9,460✔
2445
        c.writeLeafSub(b, key, n)
9,460✔
2446
        c.enqueueProto(b.Bytes())
9,460✔
2447
}
2448

2449
// Helper function to build the key.
2450
func keyFromSub(sub *subscription) string {
45,689✔
2451
        var sb strings.Builder
45,689✔
2452
        sb.Grow(len(sub.subject) + len(sub.queue) + 1)
45,689✔
2453
        sb.Write(sub.subject)
45,689✔
2454
        if sub.queue != nil {
49,498✔
2455
                // Just make the key subject spc group, e.g. 'foo bar'
3,809✔
2456
                sb.WriteByte(' ')
3,809✔
2457
                sb.Write(sub.queue)
3,809✔
2458
        }
3,809✔
2459
        return sb.String()
45,689✔
2460
}
2461

2462
const (
2463
        keyRoutedSub         = "R"
2464
        keyRoutedSubByte     = 'R'
2465
        keyRoutedLeafSub     = "L"
2466
        keyRoutedLeafSubByte = 'L'
2467
)
2468

2469
// Helper function to build the key that prevents collisions between normal
2470
// routed subscriptions and routed subscriptions on behalf of a leafnode.
2471
// Keys will look like this:
2472
// "R foo"          -> plain routed sub on "foo"
2473
// "R foo bar"      -> queue routed sub on "foo", queue "bar"
2474
// "L foo bar"      -> plain routed leaf sub on "foo", leaf "bar"
2475
// "L foo bar baz"  -> queue routed sub on "foo", queue "bar", leaf "baz"
2476
func keyFromSubWithOrigin(sub *subscription) string {
672,989✔
2477
        var sb strings.Builder
672,989✔
2478
        sb.Grow(2 + len(sub.origin) + 1 + len(sub.subject) + 1 + len(sub.queue))
672,989✔
2479
        leaf := len(sub.origin) > 0
672,989✔
2480
        if leaf {
689,548✔
2481
                sb.WriteByte(keyRoutedLeafSubByte)
16,559✔
2482
        } else {
672,989✔
2483
                sb.WriteByte(keyRoutedSubByte)
656,430✔
2484
        }
656,430✔
2485
        sb.WriteByte(' ')
672,989✔
2486
        sb.Write(sub.subject)
672,989✔
2487
        if sub.queue != nil {
694,945✔
2488
                sb.WriteByte(' ')
21,956✔
2489
                sb.Write(sub.queue)
21,956✔
2490
        }
21,956✔
2491
        if leaf {
689,548✔
2492
                sb.WriteByte(' ')
16,559✔
2493
                sb.Write(sub.origin)
16,559✔
2494
        }
16,559✔
2495
        return sb.String()
672,989✔
2496
}
2497

2498
// Lock should be held.
2499
func (c *client) writeLeafSub(w *bytes.Buffer, key string, n int32) {
35,518✔
2500
        if key == _EMPTY_ {
35,518✔
2501
                return
×
2502
        }
×
2503
        if n > 0 {
67,482✔
2504
                w.WriteString("LS+ " + key)
31,964✔
2505
                // Check for queue semantics, if found write n.
31,964✔
2506
                if strings.Contains(key, " ") {
34,275✔
2507
                        w.WriteString(" ")
2,311✔
2508
                        var b [12]byte
2,311✔
2509
                        var i = len(b)
2,311✔
2510
                        for l := n; l > 0; l /= 10 {
5,522✔
2511
                                i--
3,211✔
2512
                                b[i] = digits[l%10]
3,211✔
2513
                        }
3,211✔
2514
                        w.Write(b[i:])
2,311✔
2515
                        if c.trace {
2,311✔
2516
                                arg := fmt.Sprintf("%s %d", key, n)
×
2517
                                c.traceOutOp("LS+", []byte(arg))
×
2518
                        }
×
2519
                } else if c.trace {
29,849✔
2520
                        c.traceOutOp("LS+", []byte(key))
196✔
2521
                }
196✔
2522
        } else {
3,554✔
2523
                w.WriteString("LS- " + key)
3,554✔
2524
                if c.trace {
3,563✔
2525
                        c.traceOutOp("LS-", []byte(key))
9✔
2526
                }
9✔
2527
        }
2528
        w.WriteString(CR_LF)
35,518✔
2529
}
2530

2531
// processLeafSub will process an inbound sub request for the remote leaf node.
2532
func (c *client) processLeafSub(argo []byte) (err error) {
31,664✔
2533
        // Indicate activity.
31,664✔
2534
        c.in.subs++
31,664✔
2535

31,664✔
2536
        srv := c.srv
31,664✔
2537
        if srv == nil {
31,664✔
2538
                return nil
×
2539
        }
×
2540

2541
        // Copy so we do not reference a potentially large buffer
2542
        arg := make([]byte, len(argo))
31,664✔
2543
        copy(arg, argo)
31,664✔
2544

31,664✔
2545
        args := splitArg(arg)
31,664✔
2546
        sub := &subscription{client: c}
31,664✔
2547

31,664✔
2548
        delta := int32(1)
31,664✔
2549
        switch len(args) {
31,664✔
2550
        case 1:
29,399✔
2551
                sub.queue = nil
29,399✔
2552
        case 3:
2,265✔
2553
                sub.queue = args[1]
2,265✔
2554
                sub.qw = int32(parseSize(args[2]))
2,265✔
2555
                // TODO: (ik) We should have a non empty queue name and a queue
2,265✔
2556
                // weight >= 1. For 2.11, we may want to return an error if that
2,265✔
2557
                // is not the case, but for now just overwrite `delta` if queue
2,265✔
2558
                // weight is greater than 1 (it is possible after a reconnect/
2,265✔
2559
                // server restart to receive a queue weight > 1 for a new sub).
2,265✔
2560
                if sub.qw > 1 {
3,924✔
2561
                        delta = sub.qw
1,659✔
2562
                }
1,659✔
2563
        default:
×
2564
                return fmt.Errorf("processLeafSub Parse Error: '%s'", arg)
×
2565
        }
2566
        sub.subject = args[0]
31,664✔
2567

31,664✔
2568
        c.mu.Lock()
31,664✔
2569
        if c.isClosed() {
31,677✔
2570
                c.mu.Unlock()
13✔
2571
                return nil
13✔
2572
        }
13✔
2573

2574
        acc := c.acc
31,651✔
2575
        // Check if we have a loop.
31,651✔
2576
        ldsPrefix := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
31,651✔
2577

31,651✔
2578
        if ldsPrefix && bytesToString(sub.subject) == acc.getLDSubject() {
31,658✔
2579
                c.mu.Unlock()
7✔
2580
                c.handleLeafNodeLoop(true)
7✔
2581
                return nil
7✔
2582
        }
7✔
2583

2584
        // Check permissions if applicable. (but exclude the $LDS, $GR and _GR_)
2585
        checkPerms := true
31,644✔
2586
        if sub.subject[0] == '$' || sub.subject[0] == '_' {
60,383✔
2587
                if ldsPrefix ||
28,739✔
2588
                        bytes.HasPrefix(sub.subject, []byte(oldGWReplyPrefix)) ||
28,739✔
2589
                        bytes.HasPrefix(sub.subject, []byte(gwReplyPrefix)) {
30,693✔
2590
                        checkPerms = false
1,954✔
2591
                }
1,954✔
2592
        }
2593

2594
        // If we are a hub check that we can publish to this subject.
2595
        if checkPerms {
61,334✔
2596
                subj := string(sub.subject)
29,690✔
2597
                if subjectIsLiteral(subj) && !c.pubAllowedFullCheck(subj, true, true) {
30,016✔
2598
                        c.mu.Unlock()
326✔
2599
                        c.leafSubPermViolation(sub.subject)
326✔
2600
                        c.Debugf(fmt.Sprintf("Permissions Violation for Subscription to %q", sub.subject))
326✔
2601
                        return nil
326✔
2602
                }
326✔
2603
        }
2604

2605
        // Check if we have a maximum on the number of subscriptions.
2606
        if c.subsAtLimit() {
31,326✔
2607
                c.mu.Unlock()
8✔
2608
                c.maxSubsExceeded()
8✔
2609
                return nil
8✔
2610
        }
8✔
2611

2612
        // If we have an origin cluster associated mark that in the sub.
2613
        if rc := c.remoteCluster(); rc != _EMPTY_ {
59,505✔
2614
                sub.origin = []byte(rc)
28,195✔
2615
        }
28,195✔
2616

2617
        // Like Routes, we store local subs by account and subject and optionally queue name.
2618
        // If we have a queue it will have a trailing weight which we do not want.
2619
        if sub.queue != nil {
33,285✔
2620
                sub.sid = arg[:len(arg)-len(args[2])-1]
1,975✔
2621
        } else {
31,310✔
2622
                sub.sid = arg
29,335✔
2623
        }
29,335✔
2624
        key := bytesToString(sub.sid)
31,310✔
2625
        osub := c.subs[key]
31,310✔
2626
        if osub == nil {
61,096✔
2627
                c.subs[key] = sub
29,786✔
2628
                // Now place into the account sl.
29,786✔
2629
                if err := acc.sl.Insert(sub); err != nil {
29,786✔
2630
                        delete(c.subs, key)
×
2631
                        c.mu.Unlock()
×
2632
                        c.Errorf("Could not insert subscription: %v", err)
×
2633
                        c.sendErr("Invalid Subscription")
×
2634
                        return nil
×
2635
                }
×
2636
        } else if sub.queue != nil {
3,047✔
2637
                // For a queue we need to update the weight.
1,523✔
2638
                delta = sub.qw - atomic.LoadInt32(&osub.qw)
1,523✔
2639
                atomic.StoreInt32(&osub.qw, sub.qw)
1,523✔
2640
                acc.sl.UpdateRemoteQSub(osub)
1,523✔
2641
        }
1,523✔
2642
        spoke := c.isSpokeLeafNode()
31,310✔
2643
        c.mu.Unlock()
31,310✔
2644

31,310✔
2645
        // Only add in shadow subs if a new sub or qsub.
31,310✔
2646
        if osub == nil {
61,096✔
2647
                if err := c.addShadowSubscriptions(acc, sub, true); err != nil {
29,786✔
2648
                        c.Errorf(err.Error())
×
2649
                }
×
2650
        }
2651

2652
        // If we are not solicited, treat leaf node subscriptions similar to a
2653
        // client subscription, meaning we forward them to routes, gateways and
2654
        // other leaf nodes as needed.
2655
        if !spoke {
42,264✔
2656
                // If we are routing add to the route map for the associated account.
10,954✔
2657
                srv.updateRouteSubscriptionMap(acc, sub, delta)
10,954✔
2658
                if srv.gateway.enabled {
12,479✔
2659
                        srv.gatewayUpdateSubInterest(acc.Name, sub, delta)
1,525✔
2660
                }
1,525✔
2661
        }
2662
        // Now check on leafnode updates for other leaf nodes. We understand solicited
2663
        // and non-solicited state in this call so we will do the right thing.
2664
        acc.updateLeafNodes(sub, delta)
31,310✔
2665

31,310✔
2666
        return nil
31,310✔
2667
}
2668

2669
// If the leafnode is a solicited, set the connect delay based on default
2670
// or private option (for tests). Sends the error to the other side, log and
2671
// close the connection.
2672
func (c *client) handleLeafNodeLoop(sendErr bool) {
17✔
2673
        accName, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterLoopDetected)
17✔
2674
        errTxt := fmt.Sprintf("Loop detected for leafnode account=%q. Delaying attempt to reconnect for %v", accName, delay)
17✔
2675
        if sendErr {
26✔
2676
                c.sendErr(errTxt)
9✔
2677
        }
9✔
2678

2679
        c.Errorf(errTxt)
17✔
2680
        // If we are here with "sendErr" false, it means that this is the server
17✔
2681
        // that received the error. The other side will have closed the connection,
17✔
2682
        // but does not hurt to close here too.
17✔
2683
        c.closeConnection(ProtocolViolation)
17✔
2684
}
2685

2686
// processLeafUnsub will process an inbound unsub request for the remote leaf node.
2687
func (c *client) processLeafUnsub(arg []byte) error {
3,304✔
2688
        // Indicate any activity, so pub and sub or unsubs.
3,304✔
2689
        c.in.subs++
3,304✔
2690

3,304✔
2691
        acc := c.acc
3,304✔
2692
        srv := c.srv
3,304✔
2693

3,304✔
2694
        c.mu.Lock()
3,304✔
2695
        if c.isClosed() {
3,356✔
2696
                c.mu.Unlock()
52✔
2697
                return nil
52✔
2698
        }
52✔
2699

2700
        spoke := c.isSpokeLeafNode()
3,252✔
2701
        // We store local subs by account and subject and optionally queue name.
3,252✔
2702
        // LS- will have the arg exactly as the key.
3,252✔
2703
        sub, ok := c.subs[string(arg)]
3,252✔
2704
        if !ok {
3,262✔
2705
                // If not found, don't try to update routes/gws/leaf nodes.
10✔
2706
                c.mu.Unlock()
10✔
2707
                return nil
10✔
2708
        }
10✔
2709
        delta := int32(1)
3,242✔
2710
        if len(sub.queue) > 0 {
3,652✔
2711
                delta = sub.qw
410✔
2712
        }
410✔
2713
        c.mu.Unlock()
3,242✔
2714

3,242✔
2715
        c.unsubscribe(acc, sub, true, true)
3,242✔
2716
        if !spoke {
4,258✔
2717
                // If we are routing subtract from the route map for the associated account.
1,016✔
2718
                srv.updateRouteSubscriptionMap(acc, sub, -delta)
1,016✔
2719
                // Gateways
1,016✔
2720
                if srv.gateway.enabled {
1,302✔
2721
                        srv.gatewayUpdateSubInterest(acc.Name, sub, -delta)
286✔
2722
                }
286✔
2723
        }
2724
        // Now check on leafnode updates for other leaf nodes.
2725
        acc.updateLeafNodes(sub, -delta)
3,242✔
2726
        return nil
3,242✔
2727
}
2728

2729
func (c *client) processLeafHeaderMsgArgs(arg []byte) error {
487✔
2730
        // Unroll splitArgs to avoid runtime/heap issues
487✔
2731
        a := [MAX_MSG_ARGS][]byte{}
487✔
2732
        args := a[:0]
487✔
2733
        start := -1
487✔
2734
        for i, b := range arg {
31,973✔
2735
                switch b {
31,486✔
2736
                case ' ', '\t', '\r', '\n':
1,392✔
2737
                        if start >= 0 {
2,784✔
2738
                                args = append(args, arg[start:i])
1,392✔
2739
                                start = -1
1,392✔
2740
                        }
1,392✔
2741
                default:
30,094✔
2742
                        if start < 0 {
31,973✔
2743
                                start = i
1,879✔
2744
                        }
1,879✔
2745
                }
2746
        }
2747
        if start >= 0 {
974✔
2748
                args = append(args, arg[start:])
487✔
2749
        }
487✔
2750

2751
        c.pa.arg = arg
487✔
2752
        switch len(args) {
487✔
2753
        case 0, 1, 2:
×
2754
                return fmt.Errorf("processLeafHeaderMsgArgs Parse Error: '%s'", args)
×
2755
        case 3:
87✔
2756
                c.pa.reply = nil
87✔
2757
                c.pa.queues = nil
87✔
2758
                c.pa.hdb = args[1]
87✔
2759
                c.pa.hdr = parseSize(args[1])
87✔
2760
                c.pa.szb = args[2]
87✔
2761
                c.pa.size = parseSize(args[2])
87✔
2762
        case 4:
386✔
2763
                c.pa.reply = args[1]
386✔
2764
                c.pa.queues = nil
386✔
2765
                c.pa.hdb = args[2]
386✔
2766
                c.pa.hdr = parseSize(args[2])
386✔
2767
                c.pa.szb = args[3]
386✔
2768
                c.pa.size = parseSize(args[3])
386✔
2769
        default:
14✔
2770
                // args[1] is our reply indicator. Should be + or | normally.
14✔
2771
                if len(args[1]) != 1 {
14✔
2772
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2773
                }
×
2774
                switch args[1][0] {
14✔
2775
                case '+':
4✔
2776
                        c.pa.reply = args[2]
4✔
2777
                case '|':
10✔
2778
                        c.pa.reply = nil
10✔
2779
                default:
×
2780
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2781
                }
2782
                // Grab header size.
2783
                c.pa.hdb = args[len(args)-2]
14✔
2784
                c.pa.hdr = parseSize(c.pa.hdb)
14✔
2785

14✔
2786
                // Grab size.
14✔
2787
                c.pa.szb = args[len(args)-1]
14✔
2788
                c.pa.size = parseSize(c.pa.szb)
14✔
2789

14✔
2790
                // Grab queue names.
14✔
2791
                if c.pa.reply != nil {
18✔
2792
                        c.pa.queues = args[3 : len(args)-2]
4✔
2793
                } else {
14✔
2794
                        c.pa.queues = args[2 : len(args)-2]
10✔
2795
                }
10✔
2796
        }
2797
        if c.pa.hdr < 0 {
487✔
2798
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Header Size: '%s'", arg)
×
2799
        }
×
2800
        if c.pa.size < 0 {
487✔
2801
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Size: '%s'", args)
×
2802
        }
×
2803
        if c.pa.hdr > c.pa.size {
487✔
2804
                return fmt.Errorf("processLeafHeaderMsgArgs Header Size larger then TotalSize: '%s'", arg)
×
2805
        }
×
2806

2807
        // Common ones processed after check for arg length
2808
        c.pa.subject = args[0]
487✔
2809

487✔
2810
        return nil
487✔
2811
}
2812

2813
func (c *client) processLeafMsgArgs(arg []byte) error {
45,282✔
2814
        // Unroll splitArgs to avoid runtime/heap issues
45,282✔
2815
        a := [MAX_MSG_ARGS][]byte{}
45,282✔
2816
        args := a[:0]
45,282✔
2817
        start := -1
45,282✔
2818
        for i, b := range arg {
1,470,086✔
2819
                switch b {
1,424,804✔
2820
                case ' ', '\t', '\r', '\n':
96,967✔
2821
                        if start >= 0 {
193,934✔
2822
                                args = append(args, arg[start:i])
96,967✔
2823
                                start = -1
96,967✔
2824
                        }
96,967✔
2825
                default:
1,327,837✔
2826
                        if start < 0 {
1,470,086✔
2827
                                start = i
142,249✔
2828
                        }
142,249✔
2829
                }
2830
        }
2831
        if start >= 0 {
90,564✔
2832
                args = append(args, arg[start:])
45,282✔
2833
        }
45,282✔
2834

2835
        c.pa.arg = arg
45,282✔
2836
        switch len(args) {
45,282✔
2837
        case 0, 1:
×
2838
                return fmt.Errorf("processLeafMsgArgs Parse Error: '%s'", args)
×
2839
        case 2:
16,311✔
2840
                c.pa.reply = nil
16,311✔
2841
                c.pa.queues = nil
16,311✔
2842
                c.pa.szb = args[1]
16,311✔
2843
                c.pa.size = parseSize(args[1])
16,311✔
2844
        case 3:
6,418✔
2845
                c.pa.reply = args[1]
6,418✔
2846
                c.pa.queues = nil
6,418✔
2847
                c.pa.szb = args[2]
6,418✔
2848
                c.pa.size = parseSize(args[2])
6,418✔
2849
        default:
22,553✔
2850
                // args[1] is our reply indicator. Should be + or | normally.
22,553✔
2851
                if len(args[1]) != 1 {
22,553✔
2852
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2853
                }
×
2854
                switch args[1][0] {
22,553✔
2855
                case '+':
161✔
2856
                        c.pa.reply = args[2]
161✔
2857
                case '|':
22,392✔
2858
                        c.pa.reply = nil
22,392✔
2859
                default:
×
2860
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2861
                }
2862
                // Grab size.
2863
                c.pa.szb = args[len(args)-1]
22,553✔
2864
                c.pa.size = parseSize(c.pa.szb)
22,553✔
2865

22,553✔
2866
                // Grab queue names.
22,553✔
2867
                if c.pa.reply != nil {
22,714✔
2868
                        c.pa.queues = args[3 : len(args)-1]
161✔
2869
                } else {
22,553✔
2870
                        c.pa.queues = args[2 : len(args)-1]
22,392✔
2871
                }
22,392✔
2872
        }
2873
        if c.pa.size < 0 {
45,282✔
2874
                return fmt.Errorf("processLeafMsgArgs Bad or Missing Size: '%s'", args)
×
2875
        }
×
2876

2877
        // Common ones processed after check for arg length
2878
        c.pa.subject = args[0]
45,282✔
2879

45,282✔
2880
        return nil
45,282✔
2881
}
2882

2883
// processInboundLeafMsg is called to process an inbound msg from a leaf node.
2884
func (c *client) processInboundLeafMsg(msg []byte) {
44,308✔
2885
        // Update statistics
44,308✔
2886
        // The msg includes the CR_LF, so pull back out for accounting.
44,308✔
2887
        c.in.msgs++
44,308✔
2888
        c.in.bytes += int32(len(msg) - LEN_CR_LF)
44,308✔
2889

44,308✔
2890
        srv, acc, subject := c.srv, c.acc, string(c.pa.subject)
44,308✔
2891

44,308✔
2892
        // Mostly under testing scenarios.
44,308✔
2893
        if srv == nil || acc == nil {
44,310✔
2894
                return
2✔
2895
        }
2✔
2896

2897
        // Match the subscriptions. We will use our own L1 map if
2898
        // it's still valid, avoiding contention on the shared sublist.
2899
        var r *SublistResult
44,306✔
2900
        var ok bool
44,306✔
2901

44,306✔
2902
        genid := atomic.LoadUint64(&c.acc.sl.genid)
44,306✔
2903
        if genid == c.in.genid && c.in.results != nil {
86,228✔
2904
                r, ok = c.in.results[subject]
41,922✔
2905
        } else {
44,306✔
2906
                // Reset our L1 completely.
2,384✔
2907
                c.in.results = make(map[string]*SublistResult)
2,384✔
2908
                c.in.genid = genid
2,384✔
2909
        }
2,384✔
2910

2911
        // Go back to the sublist data structure.
2912
        if !ok {
58,040✔
2913
                r = c.acc.sl.Match(subject)
13,734✔
2914
                // Prune the results cache. Keeps us from unbounded growth. Random delete.
13,734✔
2915
                if len(c.in.results) >= maxResultCacheSize {
13,974✔
2916
                        n := 0
240✔
2917
                        for subj := range c.in.results {
8,160✔
2918
                                delete(c.in.results, subj)
7,920✔
2919
                                if n++; n > pruneSize {
8,160✔
2920
                                        break
240✔
2921
                                }
2922
                        }
2923
                }
2924
                // Then add the new cache entry.
2925
                c.in.results[subject] = r
13,734✔
2926
        }
2927

2928
        // Collect queue names if needed.
2929
        var qnames [][]byte
44,306✔
2930

44,306✔
2931
        // Check for no interest, short circuit if so.
44,306✔
2932
        // This is the fanout scale.
44,306✔
2933
        if len(r.psubs)+len(r.qsubs) > 0 {
88,123✔
2934
                flag := pmrNoFlag
43,817✔
2935
                // If we have queue subs in this cluster, then if we run in gateway
43,817✔
2936
                // mode and the remote gateways have queue subs, then we need to
43,817✔
2937
                // collect the queue groups this message was sent to so that we
43,817✔
2938
                // exclude them when sending to gateways.
43,817✔
2939
                if len(r.qsubs) > 0 && c.srv.gateway.enabled &&
43,817✔
2940
                        atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 {
56,096✔
2941
                        flag |= pmrCollectQueueNames
12,279✔
2942
                }
12,279✔
2943
                // If this is a mapped subject that means the mapped interest
2944
                // is what got us here, but this might not have a queue designation
2945
                // If that is the case, make sure we ignore to process local queue subscribers.
2946
                if len(c.pa.mapped) > 0 && len(c.pa.queues) == 0 {
44,127✔
2947
                        flag |= pmrIgnoreEmptyQueueFilter
310✔
2948
                }
310✔
2949
                _, qnames = c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, flag)
43,817✔
2950
        }
2951

2952
        // Now deal with gateways
2953
        if c.srv.gateway.enabled {
57,683✔
2954
                c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, qnames, true)
13,377✔
2955
        }
13,377✔
2956
}
2957

2958
// Handles a subscription permission violation.
2959
// See leafPermViolation() for details.
2960
func (c *client) leafSubPermViolation(subj []byte) {
326✔
2961
        c.leafPermViolation(false, subj)
326✔
2962
}
326✔
2963

2964
// Common function to process publish or subscribe leafnode permission violation.
2965
// Sends the permission violation error to the remote, logs it and closes the connection.
2966
// If this is from a server soliciting, the reconnection will be delayed.
2967
func (c *client) leafPermViolation(pub bool, subj []byte) {
326✔
2968
        if c.isSpokeLeafNode() {
652✔
2969
                // For spokes these are no-ops since the hub server told us our permissions.
326✔
2970
                // We just need to not send these over to the other side since we will get cutoff.
326✔
2971
                return
326✔
2972
        }
326✔
2973
        // FIXME(dlc) ?
2974
        c.setLeafConnectDelayIfSoliciting(leafNodeReconnectAfterPermViolation)
×
2975
        var action string
×
2976
        if pub {
×
2977
                c.sendErr(fmt.Sprintf("Permissions Violation for Publish to %q", subj))
×
2978
                action = "Publish"
×
2979
        } else {
×
2980
                c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q", subj))
×
2981
                action = "Subscription"
×
2982
        }
×
2983
        c.Errorf("%s Violation on %q - Check other side configuration", action, subj)
×
2984
        // TODO: add a new close reason that is more appropriate?
×
2985
        c.closeConnection(ProtocolViolation)
×
2986
}
2987

2988
// Invoked from generic processErr() for LEAF connections.
2989
func (c *client) leafProcessErr(errStr string) {
53✔
2990
        // Check if we got a cluster name collision.
53✔
2991
        if strings.Contains(errStr, ErrLeafNodeHasSameClusterName.Error()) {
56✔
2992
                _, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterClusterNameSame)
3✔
2993
                c.Errorf("Leafnode connection dropped with same cluster name error. Delaying attempt to reconnect for %v", delay)
3✔
2994
                return
3✔
2995
        }
3✔
2996

2997
        // We will look for Loop detected error coming from the other side.
2998
        // If we solicit, set the connect delay.
2999
        if !strings.Contains(errStr, "Loop detected") {
92✔
3000
                return
42✔
3001
        }
42✔
3002
        c.handleLeafNodeLoop(false)
8✔
3003
}
3004

3005
// If this leaf connection solicits, sets the connect delay to the given value,
3006
// or the one from the server option's LeafNode.connDelay if one is set (for tests).
3007
// Returns the connection's account name and delay.
3008
func (c *client) setLeafConnectDelayIfSoliciting(delay time.Duration) (string, time.Duration) {
20✔
3009
        c.mu.Lock()
20✔
3010
        if c.isSolicitedLeafNode() {
31✔
3011
                if s := c.srv; s != nil {
22✔
3012
                        if srvdelay := s.getOpts().LeafNode.connDelay; srvdelay != 0 {
16✔
3013
                                delay = srvdelay
5✔
3014
                        }
5✔
3015
                }
3016
                c.leaf.remote.setConnectDelay(delay)
11✔
3017
        }
3018
        accName := c.acc.Name
20✔
3019
        c.mu.Unlock()
20✔
3020
        return accName, delay
20✔
3021
}
3022

3023
// For the given remote Leafnode configuration, this function returns
3024
// if TLS is required, and if so, will return a clone of the TLS Config
3025
// (since some fields will be changed during handshake), the TLS server
3026
// name that is remembered, and the TLS timeout.
3027
func (c *client) leafNodeGetTLSConfigForSolicit(remote *leafNodeCfg) (bool, *tls.Config, string, float64) {
1,878✔
3028
        var (
1,878✔
3029
                tlsConfig  *tls.Config
1,878✔
3030
                tlsName    string
1,878✔
3031
                tlsTimeout float64
1,878✔
3032
        )
1,878✔
3033

1,878✔
3034
        remote.RLock()
1,878✔
3035
        defer remote.RUnlock()
1,878✔
3036

1,878✔
3037
        tlsRequired := remote.TLS || remote.TLSConfig != nil
1,878✔
3038
        if tlsRequired {
1,958✔
3039
                if remote.TLSConfig != nil {
131✔
3040
                        tlsConfig = remote.TLSConfig.Clone()
51✔
3041
                } else {
80✔
3042
                        tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}
29✔
3043
                }
29✔
3044
                tlsName = remote.tlsName
80✔
3045
                tlsTimeout = remote.TLSTimeout
80✔
3046
                if tlsTimeout == 0 {
126✔
3047
                        tlsTimeout = float64(TLS_TIMEOUT / time.Second)
46✔
3048
                }
46✔
3049
        }
3050

3051
        return tlsRequired, tlsConfig, tlsName, tlsTimeout
1,878✔
3052
}
3053

3054
// Initiates the LeafNode Websocket connection by:
3055
// - doing the TLS handshake if needed
3056
// - sending the HTTP request
3057
// - waiting for the HTTP response
3058
//
3059
// Since some bufio reader is used to consume the HTTP response, this function
3060
// returns the slice of buffered bytes (if any) so that the readLoop that will
3061
// be started after that consume those first before reading from the socket.
3062
// The boolean
3063
//
3064
// Lock held on entry.
3065
func (c *client) leafNodeSolicitWSConnection(opts *Options, rURL *url.URL, remote *leafNodeCfg) ([]byte, ClosedState, error) {
43✔
3066
        remote.RLock()
43✔
3067
        compress := remote.Websocket.Compression
43✔
3068
        // By default the server will mask outbound frames, but it can be disabled with this option.
43✔
3069
        noMasking := remote.Websocket.NoMasking
43✔
3070
        infoTimeout := remote.FirstInfoTimeout
43✔
3071
        remote.RUnlock()
43✔
3072
        // Will do the client-side TLS handshake if needed.
43✔
3073
        tlsRequired, err := c.leafClientHandshakeIfNeeded(remote, opts)
43✔
3074
        if err != nil {
47✔
3075
                // 0 will indicate that the connection was already closed
4✔
3076
                return nil, 0, err
4✔
3077
        }
4✔
3078

3079
        // For http request, we need the passed URL to contain either http or https scheme.
3080
        scheme := "http"
39✔
3081
        if tlsRequired {
47✔
3082
                scheme = "https"
8✔
3083
        }
8✔
3084
        // We will use the `/leafnode` path to tell the accepting WS server that it should
3085
        // create a LEAF connection, not a CLIENT.
3086
        // In case we use the user's URL path in the future, make sure we append the user's
3087
        // path to our `/leafnode` path.
3088
        lpath := leafNodeWSPath
39✔
3089
        if curPath := rURL.EscapedPath(); curPath != _EMPTY_ {
60✔
3090
                if curPath[0] == '/' {
42✔
3091
                        curPath = curPath[1:]
21✔
3092
                }
21✔
3093
                lpath = path.Join(curPath, lpath)
21✔
3094
        } else {
18✔
3095
                lpath = lpath[1:]
18✔
3096
        }
18✔
3097
        ustr := fmt.Sprintf("%s://%s/%s", scheme, rURL.Host, lpath)
39✔
3098
        u, _ := url.Parse(ustr)
39✔
3099
        req := &http.Request{
39✔
3100
                Method:     "GET",
39✔
3101
                URL:        u,
39✔
3102
                Proto:      "HTTP/1.1",
39✔
3103
                ProtoMajor: 1,
39✔
3104
                ProtoMinor: 1,
39✔
3105
                Header:     make(http.Header),
39✔
3106
                Host:       u.Host,
39✔
3107
        }
39✔
3108
        wsKey, err := wsMakeChallengeKey()
39✔
3109
        if err != nil {
39✔
3110
                return nil, WriteError, err
×
3111
        }
×
3112

3113
        req.Header["Upgrade"] = []string{"websocket"}
39✔
3114
        req.Header["Connection"] = []string{"Upgrade"}
39✔
3115
        req.Header["Sec-WebSocket-Key"] = []string{wsKey}
39✔
3116
        req.Header["Sec-WebSocket-Version"] = []string{"13"}
39✔
3117
        if compress {
48✔
3118
                req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue)
9✔
3119
        }
9✔
3120
        if noMasking {
49✔
3121
                req.Header.Add(wsNoMaskingHeader, wsNoMaskingValue)
10✔
3122
        }
10✔
3123
        c.nc.SetDeadline(time.Now().Add(infoTimeout))
39✔
3124
        if err := req.Write(c.nc); err != nil {
39✔
3125
                return nil, WriteError, err
×
3126
        }
×
3127

3128
        var resp *http.Response
39✔
3129

39✔
3130
        br := bufio.NewReaderSize(c.nc, MAX_CONTROL_LINE_SIZE)
39✔
3131
        resp, err = http.ReadResponse(br, req)
39✔
3132
        if err == nil &&
39✔
3133
                (resp.StatusCode != 101 ||
39✔
3134
                        !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
39✔
3135
                        !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
39✔
3136
                        resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) {
40✔
3137

1✔
3138
                err = fmt.Errorf("invalid websocket connection")
1✔
3139
        }
1✔
3140
        // Check compression extension...
3141
        if err == nil && c.ws.compress {
48✔
3142
                // Check that not only permessage-deflate extension is present, but that
9✔
3143
                // we also have server and client no context take over.
9✔
3144
                srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header, false)
9✔
3145

9✔
3146
                // If server does not support compression, then simply disable it in our side.
9✔
3147
                if !srvCompress {
13✔
3148
                        c.ws.compress = false
4✔
3149
                } else if !noCtxTakeover {
9✔
3150
                        err = fmt.Errorf("compression negotiation error")
×
3151
                }
×
3152
        }
3153
        // Same for no masking...
3154
        if err == nil && noMasking {
49✔
3155
                // Check if server accepts no masking
10✔
3156
                if resp.Header.Get(wsNoMaskingHeader) != wsNoMaskingValue {
11✔
3157
                        // Nope, need to mask our writes as any client would do.
1✔
3158
                        c.ws.maskwrite = true
1✔
3159
                }
1✔
3160
        }
3161
        if resp != nil {
67✔
3162
                resp.Body.Close()
28✔
3163
        }
28✔
3164
        if err != nil {
51✔
3165
                return nil, ReadError, err
12✔
3166
        }
12✔
3167
        c.Debugf("Leafnode compression=%v masking=%v", c.ws.compress, c.ws.maskwrite)
27✔
3168

27✔
3169
        var preBuf []byte
27✔
3170
        // We have to slurp whatever is in the bufio reader and pass that to the readloop.
27✔
3171
        if n := br.Buffered(); n != 0 {
27✔
3172
                preBuf, _ = br.Peek(n)
×
3173
        }
×
3174
        return preBuf, 0, nil
27✔
3175
}
3176

3177
const connectProcessTimeout = 2 * time.Second
3178

3179
// This is invoked for remote LEAF remote connections after processing the INFO
3180
// protocol.
3181
func (s *Server) leafNodeResumeConnectProcess(c *client) {
661✔
3182
        clusterName := s.ClusterName()
661✔
3183

661✔
3184
        c.mu.Lock()
661✔
3185
        if c.isClosed() {
661✔
3186
                c.mu.Unlock()
×
3187
                return
×
3188
        }
×
3189
        if err := c.sendLeafConnect(clusterName, c.headers); err != nil {
663✔
3190
                c.mu.Unlock()
2✔
3191
                c.closeConnection(WriteError)
2✔
3192
                return
2✔
3193
        }
2✔
3194

3195
        // Spin up the write loop.
3196
        s.startGoRoutine(func() { c.writeLoop() })
1,318✔
3197

3198
        // timeout leafNodeFinishConnectProcess
3199
        c.ping.tmr = time.AfterFunc(connectProcessTimeout, func() {
659✔
3200
                c.mu.Lock()
×
3201
                // check if leafNodeFinishConnectProcess was called and prevent later leafNodeFinishConnectProcess
×
3202
                if !c.flags.setIfNotSet(connectProcessFinished) {
×
3203
                        c.mu.Unlock()
×
3204
                        return
×
3205
                }
×
3206
                clearTimer(&c.ping.tmr)
×
3207
                closed := c.isClosed()
×
3208
                c.mu.Unlock()
×
3209
                if !closed {
×
3210
                        c.sendErrAndDebug("Stale Leaf Node Connection - Closing")
×
3211
                        c.closeConnection(StaleConnection)
×
3212
                }
×
3213
        })
3214
        c.mu.Unlock()
659✔
3215
        c.Debugf("Remote leafnode connect msg sent")
659✔
3216
}
3217

3218
// This is invoked for remote LEAF connections after processing the INFO
3219
// protocol and leafNodeResumeConnectProcess.
3220
// This will send LS+ the CONNECT protocol and register the leaf node.
3221
func (s *Server) leafNodeFinishConnectProcess(c *client) {
619✔
3222
        c.mu.Lock()
619✔
3223
        if !c.flags.setIfNotSet(connectProcessFinished) {
619✔
3224
                c.mu.Unlock()
×
3225
                return
×
3226
        }
×
3227
        if c.isClosed() {
619✔
3228
                c.mu.Unlock()
×
3229
                s.removeLeafNodeConnection(c)
×
3230
                return
×
3231
        }
×
3232
        remote := c.leaf.remote
619✔
3233
        // Check if we will need to send the system connect event.
619✔
3234
        remote.RLock()
619✔
3235
        sendSysConnectEvent := remote.Hub
619✔
3236
        remote.RUnlock()
619✔
3237

619✔
3238
        // Capture account before releasing lock
619✔
3239
        acc := c.acc
619✔
3240
        // cancel connectProcessTimeout
619✔
3241
        clearTimer(&c.ping.tmr)
619✔
3242
        c.mu.Unlock()
619✔
3243

619✔
3244
        // Make sure we register with the account here.
619✔
3245
        if err := c.registerWithAccount(acc); err != nil {
621✔
3246
                if err == ErrTooManyAccountConnections {
2✔
3247
                        c.maxAccountConnExceeded()
×
3248
                        return
×
3249
                } else if err == ErrLeafNodeLoop {
4✔
3250
                        c.handleLeafNodeLoop(true)
2✔
3251
                        return
2✔
3252
                }
2✔
3253
                c.Errorf("Registering leaf with account %s resulted in error: %v", acc.Name, err)
×
3254
                c.closeConnection(ProtocolViolation)
×
3255
                return
×
3256
        }
3257
        s.addLeafNodeConnection(c, _EMPTY_, _EMPTY_, false)
617✔
3258
        s.initLeafNodeSmapAndSendSubs(c)
617✔
3259
        if sendSysConnectEvent {
623✔
3260
                s.sendLeafNodeConnect(acc)
6✔
3261
        }
6✔
3262

3263
        // The above functions are not atomically under the client
3264
        // lock doing those operations. It is possible - since we
3265
        // have started the read/write loops - that the connection
3266
        // is closed before or in between. This would leave the
3267
        // closed LN connection possible registered with the account
3268
        // and/or the server's leafs map. So check if connection
3269
        // is closed, and if so, manually cleanup.
3270
        c.mu.Lock()
617✔
3271
        closed := c.isClosed()
617✔
3272
        if !closed {
1,234✔
3273
                c.setFirstPingTimer()
617✔
3274
        }
617✔
3275
        c.mu.Unlock()
617✔
3276
        if closed {
617✔
3277
                s.removeLeafNodeConnection(c)
×
3278
                if prev := acc.removeClient(c); prev == 1 {
×
3279
                        s.decActiveAccounts()
×
3280
                }
×
3281
        }
3282
}
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