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

nats-io / nats-server / 17453561676

03 Sep 2025 11:36PM UTC coverage: 86.046% (-0.002%) from 86.048%
17453561676

push

github

web-flow
[FIXED] LeafNode: Subject propagation with daisy chain and import/export (#7255)

The issue can be observed for instance with JetStream and source
streams, that would not be populating properly depending on where a
server connects to in a given topology. See the new test
`TestLeafNodeDaisyChainWithAccountImportExport` for a demonstration of
the issue without the fix in place.

Signed-off-by: Ivan Kozlovic <ivan@synadia.com>

74036 of 86042 relevant lines covered (86.05%)

362214.27 hits per line

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

91.0
/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,050✔
122
        return c.kind == LEAF && c.leaf.remote != nil
2,050✔
123
}
2,050✔
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,780,560✔
128
        return c.kind == LEAF && c.leaf.isSpoke
6,780,560✔
129
}
6,780,560✔
130

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

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

139
// This will spin up go routines to solicit the remote leaf node connections.
140
func (s *Server) solicitLeafNodeRemotes(remotes []*RemoteLeafOpts) {
1,160✔
141
        sysAccName := _EMPTY_
1,160✔
142
        sAcc := s.SystemAccount()
1,160✔
143
        if sAcc != nil {
2,297✔
144
                sysAccName = sAcc.Name
1,137✔
145
        }
1,137✔
146
        addRemote := func(r *RemoteLeafOpts, isSysAccRemote bool) *leafNodeCfg {
2,459✔
147
                s.mu.Lock()
1,299✔
148
                remote := newLeafNodeCfg(r)
1,299✔
149
                creds := remote.Credentials
1,299✔
150
                accName := remote.LocalAccount
1,299✔
151
                s.leafRemoteCfgs = append(s.leafRemoteCfgs, remote)
1,299✔
152
                // Print notice if
1,299✔
153
                if isSysAccRemote {
1,393✔
154
                        if len(remote.DenyExports) > 0 {
95✔
155
                                s.Noticef("Remote for System Account uses restricted export permissions")
1✔
156
                        }
1✔
157
                        if len(remote.DenyImports) > 0 {
95✔
158
                                s.Noticef("Remote for System Account uses restricted import permissions")
1✔
159
                        }
1✔
160
                }
161
                s.mu.Unlock()
1,299✔
162
                if creds != _EMPTY_ {
1,349✔
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,299✔
184
        }
185
        for _, r := range remotes {
2,459✔
186
                // We need to call this, even if the leaf is disabled. This is so that
1,299✔
187
                // the number of internal configuration matches the options' remote leaf
1,299✔
188
                // configuration required for configuration reload.
1,299✔
189
                remote := addRemote(r, r.LocalAccount == sysAccName)
1,299✔
190
                if !r.Disabled {
2,597✔
191
                        s.startGoRoutine(func() { s.connectToRemoteLeafNode(remote, true) })
2,596✔
192
                }
193
        }
194
}
195

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

209
// Ensure that leafnode is properly configured.
210
func validateLeafNode(o *Options) error {
8,677✔
211
        if err := validateLeafNodeAuthOptions(o); err != nil {
8,679✔
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 {
10,015✔
217
                if r.LocalAccount == _EMPTY_ {
1,779✔
218
                        r.LocalAccount = globalAccountName
439✔
219
                }
439✔
220
        }
221

222
        // In local config mode, check that leafnode configuration refers to accounts that exist.
223
        if len(o.TrustedOperators) == 0 {
17,029✔
224
                accNames := map[string]struct{}{}
8,354✔
225
                for _, a := range o.Accounts {
17,480✔
226
                        accNames[a.Name] = struct{}{}
9,126✔
227
                }
9,126✔
228
                // global account is always created
229
                accNames[DEFAULT_GLOBAL_ACCOUNT] = struct{}{}
8,354✔
230
                // in the context of leaf nodes, empty account means global account
8,354✔
231
                accNames[_EMPTY_] = struct{}{}
8,354✔
232
                // system account either exists or, if not disabled, will be created
8,354✔
233
                if o.SystemAccount == _EMPTY_ && !o.NoSystemAccount {
14,984✔
234
                        accNames[DEFAULT_SYSTEM_ACCOUNT] = struct{}{}
6,630✔
235
                }
6,630✔
236
                checkAccountExists := func(accName string, cfgType string) error {
18,054✔
237
                        if _, ok := accNames[accName]; !ok {
9,702✔
238
                                return fmt.Errorf("cannot find local account %q specified in leafnode %s", accName, cfgType)
2✔
239
                        }
2✔
240
                        return nil
9,698✔
241
                }
242
                if err := checkAccountExists(o.LeafNode.Account, "authorization"); err != nil {
8,355✔
243
                        return err
1✔
244
                }
1✔
245
                for _, lu := range o.LeafNode.Users {
8,370✔
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,692✔
254
                        if err := checkAccountExists(r.LocalAccount, "remote"); err != nil {
1,340✔
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,744✔
277
                if err := validateAndNormalizeCompressionOption(&o.LeafNode.Compression, CompressionS2Auto); err != nil {
4,079✔
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 {
10,003✔
284
                if len(rcfg.URLs) >= 2 {
1,546✔
285
                        firstIsWS, ok := isWSURL(rcfg.URLs[0]), true
208✔
286
                        for i := 1; i < len(rcfg.URLs); i++ {
661✔
287
                                u := rcfg.URLs[i]
453✔
288
                                if isWS := isWSURL(u); isWS && !firstIsWS || !isWS && firstIsWS {
460✔
289
                                        ok = false
7✔
290
                                        break
7✔
291
                                }
292
                        }
293
                        if !ok {
215✔
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,662✔
299
                        if err := validateAndNormalizeCompressionOption(&rcfg.Compression, CompressionS2Auto); err != nil {
1,336✔
300
                                return err
5✔
301
                        }
5✔
302
                }
303
        }
304

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

309
        // If MinVersion is defined, check that it is valid.
310
        if mv := o.LeafNode.MinVersion; mv != _EMPTY_ {
3,484✔
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,272✔
321
                return nil
2,794✔
322
        }
2,794✔
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,736✔
349
        if len(o.LeafNode.Users) == 0 {
17,445✔
350
                return nil
8,709✔
351
        }
8,709✔
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) {
242✔
396
        delay := s.getOpts().LeafNode.ReconnectInterval
242✔
397
        select {
242✔
398
        case <-time.After(delay):
187✔
399
        case <-s.quitCh:
55✔
400
                s.grWG.Done()
55✔
401
                return
55✔
402
        }
403
        s.connectToRemoteLeafNode(remote, false)
187✔
404
}
405

406
// Creates a leafNodeCfg object that wraps the RemoteLeafOpts.
407
func newLeafNodeCfg(remote *RemoteLeafOpts) *leafNodeCfg {
1,299✔
408
        cfg := &leafNodeCfg{
1,299✔
409
                RemoteLeafOpts: remote,
1,299✔
410
                urls:           make([]*url.URL, 0, len(remote.URLs)),
1,299✔
411
        }
1,299✔
412
        if len(remote.DenyExports) > 0 || len(remote.DenyImports) > 0 {
1,307✔
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,299✔
425
        // If allowed to randomize, do it on our copy of URLs
1,299✔
426
        if !remote.NoRandomize {
2,596✔
427
                rand.Shuffle(len(cfg.urls), func(i, j int) {
1,707✔
428
                        cfg.urls[i], cfg.urls[j] = cfg.urls[j], cfg.urls[i]
410✔
429
                })
410✔
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,038✔
435
                cfg.saveTLSHostname(u)
1,739✔
436
                cfg.saveUserPassword(u)
1,739✔
437
                // If the url(s) have the "wss://" scheme, and we don't have a TLS
1,739✔
438
                // config, mark that we should be using TLS anyway.
1,739✔
439
                if !cfg.TLS && isWSSURL(u) {
1,740✔
440
                        cfg.TLS = true
1✔
441
                }
1✔
442
        }
443
        return cfg
1,299✔
444
}
445

446
// Will pick an URL from the list of available URLs.
447
func (cfg *leafNodeCfg) pickNextURL() *url.URL {
6,848✔
448
        cfg.Lock()
6,848✔
449
        defer cfg.Unlock()
6,848✔
450
        // If the current URL is the first in the list and we have more than
6,848✔
451
        // one URL, then move that one to end of the list.
6,848✔
452
        if cfg.curURL != nil && len(cfg.urls) > 1 && urlsAreEqual(cfg.curURL, cfg.urls[0]) {
10,372✔
453
                first := cfg.urls[0]
3,524✔
454
                copy(cfg.urls, cfg.urls[1:])
3,524✔
455
                cfg.urls[len(cfg.urls)-1] = first
3,524✔
456
        }
3,524✔
457
        cfg.curURL = cfg.urls[0]
6,848✔
458
        return cfg.curURL
6,848✔
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,487✔
471
        cfg.RLock()
1,487✔
472
        delay := cfg.connDelay
1,487✔
473
        cfg.RUnlock()
1,487✔
474
        return delay
1,487✔
475
}
1,487✔
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,141✔
487
        opts := s.getOpts()
7,141✔
488
        s.leafNodeOpts.dialTimeout = opts.LeafNode.dialTimeout
7,141✔
489
        if s.leafNodeOpts.dialTimeout == 0 {
14,281✔
490
                // Use same timeouts as routes for now.
7,140✔
491
                s.leafNodeOpts.dialTimeout = DEFAULT_ROUTE_DIAL
7,140✔
492
        }
7,140✔
493
        s.leafNodeOpts.resolver = opts.LeafNode.resolver
7,141✔
494
        if s.leafNodeOpts.resolver == nil {
14,278✔
495
                s.leafNodeOpts.resolver = net.DefaultResolver
7,137✔
496
        }
7,137✔
497
}
498

499
const sharedSysAccDelay = 250 * time.Millisecond
500

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

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

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

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

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

536
        var conn net.Conn
1,481✔
537

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

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

1,481✔
542
        for s.isRunning() && s.remoteLeafNodeStillValid(remote) {
8,329✔
543
                rURL := remote.pickNextURL()
6,848✔
544
                url, err := s.getRandomIP(resolver, rURL.Host, nil)
6,848✔
545
                if err == nil {
13,689✔
546
                        var ipStr string
6,841✔
547
                        if url != rURL.Host {
6,915✔
548
                                ipStr = fmt.Sprintf(" (%s)", url)
74✔
549
                        }
74✔
550
                        // Some test may want to disable remotes from connecting
551
                        if s.isLeafConnectDisabled() {
6,977✔
552
                                s.Debugf("Will not attempt to connect to remote server on %q%s, leafnodes currently disabled", rURL.Host, ipStr)
136✔
553
                                err = ErrLeafNodeDisabled
136✔
554
                        } else {
6,841✔
555
                                s.Debugf("Trying to connect as leafnode to remote server on %q%s", rURL.Host, ipStr)
6,705✔
556
                                conn, err = natsDialTimeout("tcp", url, dialTimeout)
6,705✔
557
                        }
6,705✔
558
                }
559
                if err != nil {
12,911✔
560
                        jitter := time.Duration(rand.Int63n(int64(reconnectDelay)))
6,063✔
561
                        delay := reconnectDelay + jitter
6,063✔
562
                        attempts++
6,063✔
563
                        if s.shouldReportConnectErr(firstConnect, attempts) {
10,291✔
564
                                s.Errorf(connErrFmt, rURL.Host, attempts, err)
4,228✔
565
                        } else {
6,063✔
566
                                s.Debugf(connErrFmt, rURL.Host, attempts, err)
1,835✔
567
                        }
1,835✔
568
                        remote.Lock()
6,063✔
569
                        // if we are using a delay to start migrating assets, kick off a migrate timer.
6,063✔
570
                        if remote.jsMigrateTimer == nil && jetstreamMigrateDelay > 0 {
6,071✔
571
                                remote.jsMigrateTimer = time.AfterFunc(jetstreamMigrateDelay, func() {
16✔
572
                                        s.checkJetStreamMigrate(remote)
8✔
573
                                })
8✔
574
                        }
575
                        remote.Unlock()
6,063✔
576
                        select {
6,063✔
577
                        case <-s.quitCh:
684✔
578
                                remote.cancelMigrateTimer()
684✔
579
                                return
684✔
580
                        case <-time.After(delay):
5,378✔
581
                                // Check if we should migrate any JetStream assets immediately while this remote is down.
5,378✔
582
                                // This will be used if JetStreamClusterMigrateDelay was not set
5,378✔
583
                                if jetstreamMigrateDelay == 0 {
10,681✔
584
                                        s.checkJetStreamMigrate(remote)
5,303✔
585
                                }
5,303✔
586
                                continue
5,378✔
587
                        }
588
                }
589
                remote.cancelMigrateTimer()
785✔
590
                if !s.remoteLeafNodeStillValid(remote) {
785✔
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)
785✔
598

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

785✔
602
                return
785✔
603
        }
604
}
605

606
func (cfg *leafNodeCfg) cancelMigrateTimer() {
1,469✔
607
        cfg.Lock()
1,469✔
608
        stopAndClearTimer(&cfg.jsMigrateTimer)
1,469✔
609
        cfg.Unlock()
1,469✔
610
}
1,469✔
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) {
785✔
614
        s.mu.RLock()
785✔
615
        accName := remote.LocalAccount
785✔
616
        s.mu.RUnlock()
785✔
617

785✔
618
        acc, err := s.LookupAccount(accName)
785✔
619
        if err != nil {
787✔
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()
783✔
625
        defer acc.jscmMu.Unlock()
783✔
626

783✔
627
        // Walk all streams looking for any clustered stream, skip otherwise.
783✔
628
        for _, mset := range acc.streams() {
814✔
629
                node := mset.raftNode()
31✔
630
                if node == nil {
54✔
631
                        // Not R>1
23✔
632
                        continue
23✔
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,311✔
648
        s.mu.RLock()
5,311✔
649
        accName, shouldMigrate := remote.LocalAccount, remote.JetStreamClusterMigrate
5,311✔
650
        s.mu.RUnlock()
5,311✔
651

5,311✔
652
        if !shouldMigrate {
10,553✔
653
                return
5,242✔
654
        }
5,242✔
655

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

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

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

688
// Helper for checking.
689
func (s *Server) isLeafConnectDisabled() bool {
6,841✔
690
        s.mu.RLock()
6,841✔
691
        defer s.mu.RUnlock()
6,841✔
692
        return s.leafDisableConnect
6,841✔
693
}
6,841✔
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,371✔
704
        if cfg.tlsName == _EMPTY_ && net.ParseIP(u.Hostname()) == nil {
2,391✔
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,739✔
712
        if cfg.username == _EMPTY_ && u.User != nil {
2,020✔
713
                cfg.username = u.User.Username()
281✔
714
                cfg.password, _ = u.User.Password()
281✔
715
        }
281✔
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,446✔
721
        // Snapshot server options.
3,446✔
722
        opts := s.getOpts()
3,446✔
723

3,446✔
724
        port := opts.LeafNode.Port
3,446✔
725
        if port == -1 {
6,715✔
726
                port = 0
3,269✔
727
        }
3,269✔
728

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

733
        s.mu.Lock()
3,445✔
734
        hp := net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(port))
3,445✔
735
        l, e := natsListen("tcp", hp)
3,445✔
736
        s.leafNodeListenerErr = e
3,445✔
737
        if e != nil {
3,445✔
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,445✔
744
                net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
3,445✔
745

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

773
        s.leafNodeInfo = info
3,445✔
774
        // Possibly override Host/Port and set IP based on Cluster.Advertise
3,445✔
775
        if err := s.setLeafNodeInfoHostPortAndIP(); err != nil {
3,445✔
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,445✔
782
        s.generateLeafNodeInfoJSON()
3,445✔
783

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

3,445✔
787
        // As of now, a server that does not have remotes configured would
3,445✔
788
        // never solicit a connection, so we should not have to warn if
3,445✔
789
        // InsecureSkipVerify is set in main LeafNodes config (since
3,445✔
790
        // this TLS setting matters only when soliciting a connection).
3,445✔
791
        // Still, warn if insecure is set in any of LeafNode block.
3,445✔
792
        // We need to check remotes, even if tls is not required on accept.
3,445✔
793
        warn := tlsRequired && opts.LeafNode.TLSConfig.InsecureSkipVerify
3,445✔
794
        if !warn {
6,886✔
795
                for _, r := range opts.LeafNode.Remotes {
3,631✔
796
                        if r.TLSConfig != nil && r.TLSConfig.InsecureSkipVerify {
191✔
797
                                warn = true
1✔
798
                                break
1✔
799
                        }
800
                }
801
        }
802
        if warn {
3,450✔
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,270✔
806
        s.mu.Unlock()
3,445✔
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 {
662✔
815
        // We support basic user/pass and operator based user JWT with signatures.
662✔
816
        cinfo := leafConnectInfo{
662✔
817
                Version:       VERSION,
662✔
818
                ID:            c.srv.info.ID,
662✔
819
                Domain:        c.srv.info.Domain,
662✔
820
                Name:          c.srv.info.Name,
662✔
821
                Hub:           c.leaf.remote.Hub,
662✔
822
                Cluster:       clusterName,
662✔
823
                Headers:       headers,
662✔
824
                JetStream:     c.acc.jetStreamConfigured(),
662✔
825
                DenyPub:       c.leaf.remote.DenyImports,
662✔
826
                Compression:   c.leaf.compression,
662✔
827
                RemoteAccount: c.acc.GetName(),
662✔
828
                Proto:         c.srv.getServerProto(),
662✔
829
        }
662✔
830

662✔
831
        // If a signature callback is specified, this takes precedence over anything else.
662✔
832
        if cb := c.leaf.remote.SignatureCB; cb != nil {
667✔
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_ {
711✔
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_ {
608✔
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 {
962✔
896
                // For backward compatibility, if only username is provided, set both
302✔
897
                // Token and User, not just Token.
302✔
898
                cinfo.User = userInfo.Username()
302✔
899
                var ok bool
302✔
900
                cinfo.Pass, ok = userInfo.Password()
302✔
901
                if !ok {
308✔
902
                        cinfo.Token = cinfo.User
6✔
903
                }
6✔
904
        } else if c.leaf.remote.username != _EMPTY_ {
365✔
905
                cinfo.User = c.leaf.remote.username
7✔
906
                cinfo.Pass = c.leaf.remote.password
7✔
907
        }
7✔
908
        b, err := json.Marshal(cinfo)
660✔
909
        if err != nil {
660✔
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)))
660✔
917
        return nil
660✔
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,662✔
923
        clone := s.leafNodeInfo
2,662✔
924
        // Copy the array of urls.
2,662✔
925
        if len(s.leafNodeInfo.LeafNodeURLs) > 0 {
4,827✔
926
                clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...)
2,165✔
927
        }
2,165✔
928
        return &clone
2,662✔
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,832✔
936
        if s.leafURLsMap.addUrl(urlStr) {
13,659✔
937
                s.generateLeafNodeInfoJSON()
6,827✔
938
                return true
6,827✔
939
        }
6,827✔
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,832✔
948
        // Don't need to do this if we are removing the route connection because
6,832✔
949
        // we are shuting down...
6,832✔
950
        if s.isShuttingDown() {
10,419✔
951
                return false
3,587✔
952
        }
3,587✔
953
        if s.leafURLsMap.removeUrl(urlStr) {
6,486✔
954
                s.generateLeafNodeInfoJSON()
3,241✔
955
                return true
3,241✔
956
        }
3,241✔
957
        return false
4✔
958
}
959

960
// Server lock is held on entry
961
func (s *Server) generateLeafNodeInfoJSON() {
13,513✔
962
        s.leafNodeInfo.Cluster = s.cachedClusterName()
13,513✔
963
        s.leafNodeInfo.LeafNodeURLs = s.leafURLsMap.getAsStringSlice()
13,513✔
964
        s.leafNodeInfo.WSConnectURLs = s.websocket.connectURLsMap.getAsStringSlice()
13,513✔
965
        s.leafNodeInfoJSON = generateInfoJSON(&s.leafNodeInfo)
13,513✔
966
}
13,513✔
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,068✔
971
        for _, c := range s.leafs {
10,170✔
972
                c.mu.Lock()
102✔
973
                c.enqueueProto(s.leafNodeInfoJSON)
102✔
974
                c.mu.Unlock()
102✔
975
        }
102✔
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,637✔
980
        // Snapshot server options.
1,637✔
981
        opts := s.getOpts()
1,637✔
982

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

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

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

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

1,637✔
1004
        // For remote, check if the scheme starts with "ws", if so, we will initiate
1,637✔
1005
        // a remote Leaf Node connection as a websocket connection.
1,637✔
1006
        if remote != nil && rURL != nil && isWSURL(rURL) {
1,680✔
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,637✔
1014
        var acc *Account
1,637✔
1015
        var remoteSuffix string
1,637✔
1016
        if remote != nil {
2,422✔
1017
                // For now, if lookup fails, we will constantly try
785✔
1018
                // to recreate this LN connection.
785✔
1019
                lacc := remote.LocalAccount
785✔
1020
                var err error
785✔
1021
                acc, err = s.LookupAccount(lacc)
785✔
1022
                if err != nil {
787✔
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())
783✔
1032
        }
1033

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

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

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

1,635✔
1070
        // Grab this before the client lock below.
1,635✔
1071
        if !solicited {
2,487✔
1072
                // Grab server variables
852✔
1073
                s.mu.Lock()
852✔
1074
                info = s.copyLeafNodeInfo()
852✔
1075
                // For tests that want to simulate old servers, do not set the compression
852✔
1076
                // on the INFO protocol if configured with CompressionNotSupported.
852✔
1077
                if cm := opts.LeafNode.Compression.Mode; cm != CompressionNotSupported {
1,703✔
1078
                        info.Compression = cm
851✔
1079
                }
851✔
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[:])
852✔
1083
                s.mu.Unlock()
852✔
1084
        }
1085

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

1,635✔
1089
        var preBuf []byte
1,635✔
1090
        if solicited {
2,418✔
1091
                // For websocket connection, we need to send an HTTP request,
783✔
1092
                // and get the response before starting the readLoop to get
783✔
1093
                // the INFO, etc..
783✔
1094
                if c.isWebsocket() {
826✔
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 {
740✔
1108
                        // If configured to do TLS handshake first
740✔
1109
                        if tlsFirst {
744✔
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))
739✔
1117
                }
1118

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

852✔
1130
                var pre []byte
852✔
1131
                // We need first to check for "TLS First" fallback delay.
852✔
1132
                if tlsFirstFallback > 0 {
853✔
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,699✔
1156
                        // We have to send from this go routine because we may
847✔
1157
                        // have to block for TLS handshake before we start our
847✔
1158
                        // writeLoop go routine. The other side needs to receive
847✔
1159
                        // this before it can initiate the TLS handshake..
847✔
1160
                        c.sendProtoNow(proto)
847✔
1161

847✔
1162
                        // The above call could have marked the connection as closed (due to TCP error).
847✔
1163
                        if c.isClosed() {
847✔
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 {
925✔
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 {
809✔
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)
806✔
1204
                if needsCompression(opts.LeafNode.Compression.Mode) {
1,393✔
1205
                        c.ping.tmr = time.AfterFunc(timeout, func() {
591✔
1206
                                c.authTimeout()
4✔
1207
                        })
4✔
1208
                } else {
219✔
1209
                        c.setAuthTimer(timeout)
219✔
1210
                }
219✔
1211
        }
1212

1213
        // Keep track in case server is shutdown before we can successfully register.
1214
        if !s.addToTempClients(c.cid, c) {
1,573✔
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,142✔
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,377✔
1227
                s.startGoRoutine(func() { c.writeLoop() })
1,612✔
1228
        }
1229

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

1,571✔
1232
        return c
1,571✔
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,894✔
1240
        // Check if TLS is required and gather TLS config variables.
1,894✔
1241
        tlsRequired, tlsConfig, tlsName, tlsTimeout := c.leafNodeGetTLSConfigForSolicit(remote)
1,894✔
1242
        if !tlsRequired {
3,708✔
1243
                return false, nil
1,814✔
1244
        }
1,814✔
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,620✔
1264
        c.mu.Lock()
2,620✔
1265
        if c.leaf == nil || c.isClosed() {
2,620✔
1266
                c.mu.Unlock()
×
1267
                return
×
1268
        }
×
1269
        s := c.srv
2,620✔
1270
        opts := s.getOpts()
2,620✔
1271
        remote := c.leaf.remote
2,620✔
1272
        didSolicit := remote != nil
2,620✔
1273
        firstINFO := !c.flags.isSet(infoReceived)
2,620✔
1274

2,620✔
1275
        // In case of websocket, the TLS handshake has been already done.
2,620✔
1276
        // So check only for non websocket connections and for configurations
2,620✔
1277
        // where the TLS Handshake was not done first.
2,620✔
1278
        if didSolicit && !c.flags.isSet(handshakeComplete) && !c.isWebsocket() && !remote.TLSHandshakeFirst {
4,467✔
1279
                // If the server requires TLS, we need to set this in the remote
1,847✔
1280
                // otherwise if there is no TLS configuration block for the remote,
1,847✔
1281
                // the solicit side will not attempt to perform the TLS handshake.
1,847✔
1282
                if firstINFO && info.TLSRequired {
1,911✔
1283
                        remote.TLS = true
64✔
1284
                }
64✔
1285
                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
1,881✔
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,867✔
1293
                // Prevent from getting back here.
1,281✔
1294
                c.flags.set(compressionNegotiated)
1,281✔
1295

1,281✔
1296
                var co *CompressionOpts
1,281✔
1297
                if !didSolicit {
1,842✔
1298
                        co = &opts.LeafNode.Compression
561✔
1299
                } else {
1,281✔
1300
                        co = &remote.Compression
720✔
1301
                }
720✔
1302
                if needsCompression(co.Mode) {
2,551✔
1303
                        // Release client lock since following function will need server lock.
1,270✔
1304
                        c.mu.Unlock()
1,270✔
1305
                        compress, err := s.negotiateLeafCompression(c, didSolicit, info.Compression, co)
1,270✔
1306
                        if err != nil {
1,270✔
1307
                                c.sendErrAndErr(err.Error())
×
1308
                                c.closeConnection(ProtocolViolation)
×
1309
                                return
×
1310
                        }
×
1311
                        if compress {
2,412✔
1312
                                // Done for now, will get back another INFO protocol...
1,142✔
1313
                                return
1,142✔
1314
                        }
1,142✔
1315
                        // No compression because one side does not want/can't, so proceed.
1316
                        c.mu.Lock()
128✔
1317
                        // Check that the connection did not close if the lock was released.
128✔
1318
                        if c.isClosed() {
128✔
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 {
140✔
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,205✔
1352
                // Mark that the INFO protocol has been received.
762✔
1353
                c.flags.set(infoReceived)
762✔
1354
                // Prevent connecting to non leafnode port. Need to do this only for
762✔
1355
                // the first INFO, not for async INFO updates...
762✔
1356
                //
762✔
1357
                // Content of INFO sent by the server when accepting a tcp connection.
762✔
1358
                // -------------------------------------------------------------------
762✔
1359
                // Listen Port Of | CID | ClientConnectURLs | LeafNodeURLs | Gateway |
762✔
1360
                // -------------------------------------------------------------------
762✔
1361
                //      CLIENT    |  X* |        X**        |              |         |
762✔
1362
                //      ROUTE     |     |        X**        |      X***    |         |
762✔
1363
                //     GATEWAY    |     |                   |              |    X    |
762✔
1364
                //     LEAFNODE   |  X  |                   |       X      |         |
762✔
1365
                // -------------------------------------------------------------------
762✔
1366
                // *   Not on older servers.
762✔
1367
                // **  Not if "no advertise" is enabled.
762✔
1368
                // *** Not if leafnode's "no advertise" is enabled.
762✔
1369
                //
762✔
1370
                // As seen from above, a solicited LeafNode connection should receive
762✔
1371
                // from the remote server an INFO with CID and LeafNodeURLs. Anything
762✔
1372
                // else should be considered an attempt to connect to a wrong port.
762✔
1373
                if didSolicit && (info.CID == 0 || info.LeafNodeURLs == nil) {
817✔
1374
                        c.mu.Unlock()
55✔
1375
                        c.Errorf(ErrConnectedToWrongPort.Error())
55✔
1376
                        c.closeConnection(WrongPort)
55✔
1377
                        return
55✔
1378
                }
55✔
1379
                // Reject a cluster that contains spaces.
1380
                if info.Cluster != _EMPTY_ && strings.Contains(info.Cluster, " ") {
708✔
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)
706✔
1388
                if info.TLSRequired && didSolicit {
736✔
1389
                        remote.TLS = true
30✔
1390
                }
30✔
1391
                supportsHeaders := c.srv.supportsHeaders()
706✔
1392
                c.headers = supportsHeaders && info.Headers
706✔
1393

706✔
1394
                // Remember the remote server.
706✔
1395
                // Pre 2.2.0 servers are not sending their server name.
706✔
1396
                // In that case, use info.ID, which, for those servers, matches
706✔
1397
                // the content of the field `Name` in the leafnode CONNECT protocol.
706✔
1398
                if info.Name == _EMPTY_ {
706✔
1399
                        c.leaf.remoteServer = info.ID
×
1400
                } else {
706✔
1401
                        c.leaf.remoteServer = info.Name
706✔
1402
                }
706✔
1403
                c.leaf.remoteDomain = info.Domain
706✔
1404
                c.leaf.remoteCluster = info.Cluster
706✔
1405
                // We send the protocol version in the INFO protocol.
706✔
1406
                // Keep track of it, so we know if this connection supports message
706✔
1407
                // tracing for instance.
706✔
1408
                c.opts.Protocol = info.Proto
706✔
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,687✔
1414
                // Consider the incoming array as the most up-to-date
1,300✔
1415
                // representation of the remote cluster's list of URLs.
1,300✔
1416
                c.updateLeafNodeURLs(info)
1,300✔
1417
        }
1,300✔
1418

1419
        // Check to see if we have permissions updates here.
1420
        if info.Import != nil || info.Export != nil {
1,402✔
1421
                perms := &Permissions{
15✔
1422
                        Publish:   info.Export,
15✔
1423
                        Subscribe: info.Import,
15✔
1424
                }
15✔
1425
                // Check if we have local deny clauses that we need to merge.
15✔
1426
                if remote := c.leaf.remote; remote != nil {
30✔
1427
                        if len(remote.DenyExports) > 0 {
16✔
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 {
16✔
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)
15✔
1441
        }
1442

1443
        var resumeConnect, checkSyncConsumers bool
1,387✔
1444

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

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

1,387✔
1462
        finishConnect := info.ConnectInfo
1,387✔
1463
        if resumeConnect && s != nil {
2,049✔
1464
                s.leafNodeResumeConnectProcess(c)
662✔
1465
                if !info.InfoOnConnect {
662✔
1466
                        finishConnect = true
×
1467
                }
×
1468
        }
1469
        if finishConnect {
2,013✔
1470
                s.leafNodeFinishConnectProcess(c)
626✔
1471
        }
626✔
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,647✔
1476
                s.checkInternalSyncConsumers(c.acc, info.Domain)
260✔
1477
        }
260✔
1478
}
1479

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

1,270✔
1503
        if !needsCompression(cm) {
1,398✔
1504
                return false, nil
128✔
1505
        }
128✔
1506

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

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

1,142✔
1516
        // If we solicited, then send this INFO protocol BEFORE switching
1,142✔
1517
        // to compression writer. However, if we did not, we send it after.
1,142✔
1518
        c.mu.Lock()
1,142✔
1519
        if didSolicit {
1,724✔
1520
                c.enqueueProto(infoProto)
582✔
1521
                // Make sure it is completely flushed (the pending bytes goes to
582✔
1522
                // 0) before proceeding.
582✔
1523
                for c.out.pb > 0 && !c.isClosed() {
1,164✔
1524
                        c.flushOutbound()
582✔
1525
                }
582✔
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,142✔
1530
        // Create the compress writer before queueing the INFO protocol for
1,142✔
1531
        // a route that did not solicit. It will make sure that that proto
1,142✔
1532
        // is sent with compression on.
1,142✔
1533
        c.out.cw = s2.NewWriter(nil, s2WriterOptions(cm)...)
1,142✔
1534
        if !didSolicit {
1,702✔
1535
                c.enqueueProto(infoProto)
560✔
1536
        }
560✔
1537
        c.mu.Unlock()
1,142✔
1538
        return true, nil
1,142✔
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,300✔
1544
        cfg := c.leaf.remote
1,300✔
1545
        cfg.Lock()
1,300✔
1546
        defer cfg.Unlock()
1,300✔
1547

1,300✔
1548
        // We have ensured that if a remote has a WS scheme, then all are.
1,300✔
1549
        // So check if first is WS, then add WS URLs, otherwise, add non WS ones.
1,300✔
1550
        if len(cfg.URLs) > 0 && isWSURL(cfg.URLs[0]) {
1,354✔
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,246✔
1562
}
1563

1564
func (c *client) doUpdateLNURLs(cfg *leafNodeCfg, scheme string, URLs []string) {
1,300✔
1565
        cfg.urls = make([]*url.URL, 0, 1+len(URLs))
1,300✔
1566
        // Add the ones we receive in the protocol
1,300✔
1567
        for _, surl := range URLs {
3,633✔
1568
                url, err := url.Parse(fmt.Sprintf("%s://%s", scheme, surl))
2,333✔
1569
                if err != nil {
2,333✔
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,333✔
1576
                for _, u := range cfg.URLs {
5,917✔
1577
                        // URLs that we receive never have user info, but the
3,584✔
1578
                        // ones that were configured may have. Simply compare
3,584✔
1579
                        // host and port to decide if they are equal or not.
3,584✔
1580
                        if url.Host == u.Host && url.Port() == u.Port() {
5,285✔
1581
                                dup = true
1,701✔
1582
                                break
1,701✔
1583
                        }
1584
                }
1585
                if !dup {
2,965✔
1586
                        cfg.urls = append(cfg.urls, url)
632✔
1587
                        cfg.saveTLSHostname(url)
632✔
1588
                }
632✔
1589
        }
1590
        // Add the configured one
1591
        cfg.urls = append(cfg.urls, cfg.URLs...)
1,300✔
1592
}
1593

1594
// Similar to setInfoHostPortAndGenerateJSON, but for leafNodeInfo.
1595
func (s *Server) setLeafNodeInfoHostPortAndIP() error {
3,445✔
1596
        opts := s.getOpts()
3,445✔
1597
        if opts.LeafNode.Advertise != _EMPTY_ {
3,456✔
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,434✔
1605
                s.leafNodeInfo.Host = opts.LeafNode.Host
3,434✔
1606
                s.leafNodeInfo.Port = opts.LeafNode.Port
3,434✔
1607
                // If the host is "0.0.0.0" or "::" we need to resolve to a public IP.
3,434✔
1608
                // This will return at most 1 IP.
3,434✔
1609
                hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(s.leafNodeInfo.Host, false)
3,434✔
1610
                if err != nil {
3,434✔
1611
                        return err
×
1612
                }
×
1613
                if hostIsIPAny {
3,729✔
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,445✔
1625
        if opts.LeafNode.Advertise != _EMPTY_ {
3,456✔
1626
                s.Noticef("Advertise address for leafnode is set to %s", s.leafNodeInfo.IP)
11✔
1627
        }
11✔
1628
        return nil
3,445✔
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,291✔
1644
        var accName string
1,291✔
1645
        c.mu.Lock()
1,291✔
1646
        cid := c.cid
1,291✔
1647
        acc := c.acc
1,291✔
1648
        if acc != nil {
2,582✔
1649
                accName = acc.Name
1,291✔
1650
        }
1,291✔
1651
        myRemoteDomain := c.leaf.remoteDomain
1,291✔
1652
        mySrvName := c.leaf.remoteServer
1,291✔
1653
        remoteAccName := c.leaf.remoteAccName
1,291✔
1654
        myClustName := c.leaf.remoteCluster
1,291✔
1655
        solicited := c.leaf.remote != nil
1,291✔
1656
        c.mu.Unlock()
1,291✔
1657

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

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

1691
        srvDecorated := func() string {
1,498✔
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,291✔
1699
        sysAcc := s.SystemAccount()
1,291✔
1700
        js := s.getJetStream()
1,291✔
1701
        var meta *raft
1,291✔
1702
        if js != nil {
1,814✔
1703
                if mg := js.getMetaGroup(); mg != nil {
951✔
1704
                        meta = mg.(*raft)
428✔
1705
                }
428✔
1706
        }
1707
        blockMappingOutgoing := false
1,291✔
1708
        // Deny (non domain) JetStream API traffic unless system account is shared
1,291✔
1709
        // and domain names are identical and extending is not disabled
1,291✔
1710

1,291✔
1711
        // Check if backwards compatibility has been enabled and needs to be acted on
1,291✔
1712
        forceSysAccDeny := false
1,291✔
1713
        if len(opts.JsAccDefaultDomain) > 0 {
1,328✔
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,276✔
1738
                sysAcc == nil || acc == nil || forceSysAccDeny {
2,394✔
1739
                // If domain names mismatch always deny. This applies to system accounts as well as non system accounts.
1,118✔
1740
                // Not having a system account, account or JetStream disabled is considered a mismatch as well.
1,118✔
1741
                if acc != nil && acc == sysAcc {
1,253✔
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 {
983✔
1758
                        c.Noticef("JetStream using domains: local %q, remote %q", opts.JetStreamDomain, myRemoteDomain)
983✔
1759
                        c.mergeDenyPermissionsLocked(both, denyAllClientJs)
983✔
1760
                }
983✔
1761
                blockMappingOutgoing = true
1,118✔
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,509✔
1787
                for src, dest := range generateJSMappingTable(opts.JetStreamDomain) {
2,330✔
1788
                        if err := acc.AddMapping(src, dest); err != nil {
2,097✔
1789
                                c.Debugf("Error adding JetStream domain mapping: %s", err.Error())
×
1790
                        } else {
2,097✔
1791
                                c.Debugf("Adding JetStream Domain Mapping %q -> %s to account %q", src, dest, accName)
2,097✔
1792
                        }
2,097✔
1793
                }
1794
                if blockMappingOutgoing {
435✔
1795
                        src := fmt.Sprintf(jsDomainAPI, opts.JetStreamDomain)
202✔
1796
                        // make sure that messages intended for this domain, do not leave the cluster via this leaf node connection
202✔
1797
                        // This is a guard against a miss-config with two identical domain names and will only cover some forms
202✔
1798
                        // of this issue, not all of them.
202✔
1799
                        // This guards against a hub and a spoke having the same domain name.
202✔
1800
                        // But not two spokes having the same one and the request coming from the hub.
202✔
1801
                        c.mergeDenyPermissionsLocked(pub, []string{src})
202✔
1802
                        c.Debugf("Adding deny %q for outgoing messages to account %q", src, accName)
202✔
1803
                }
202✔
1804
        }
1805
}
1806

1807
func (s *Server) removeLeafNodeConnection(c *client) {
1,637✔
1808
        c.mu.Lock()
1,637✔
1809
        cid := c.cid
1,637✔
1810
        if c.leaf != nil {
3,274✔
1811
                if c.leaf.tsubt != nil {
2,816✔
1812
                        c.leaf.tsubt.Stop()
1,179✔
1813
                        c.leaf.tsubt = nil
1,179✔
1814
                }
1,179✔
1815
                if c.leaf.gwSub != nil {
2,261✔
1816
                        s.gwLeafSubs.Remove(c.leaf.gwSub)
624✔
1817
                        // We need to set this to nil for GC to release the connection
624✔
1818
                        c.leaf.gwSub = nil
624✔
1819
                }
624✔
1820
        }
1821
        proxyKey := c.proxyKey
1,637✔
1822
        c.mu.Unlock()
1,637✔
1823
        s.mu.Lock()
1,637✔
1824
        delete(s.leafs, cid)
1,637✔
1825
        if proxyKey != _EMPTY_ {
1,641✔
1826
                s.removeProxiedConn(proxyKey, cid)
4✔
1827
        }
4✔
1828
        s.mu.Unlock()
1,637✔
1829
        s.removeFromTempClients(cid)
1,637✔
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 {
672✔
1875
        // Way to detect clients that incorrectly connect to the route listen
672✔
1876
        // port. Client provided "lang" in the CONNECT protocol while LEAFNODEs don't.
672✔
1877
        if lang != _EMPTY_ {
672✔
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{}
672✔
1885
        if err := json.Unmarshal(arg, proto); err != nil {
672✔
1886
                return err
×
1887
        }
×
1888

1889
        // Reject a cluster that contains spaces.
1890
        if proto.Cluster != _EMPTY_ && strings.Contains(proto.Cluster, " ") {
673✔
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 {
674✔
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_ {
668✔
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_ {
670✔
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()
667✔
1934

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

501✔
2026
        // Only applicable if we have JS and the leafnode has JS as well.
501✔
2027
        // We check for remote JS outside.
501✔
2028
        if !js.isEnabled() || acc == nil {
626✔
2029
                return
125✔
2030
        }
125✔
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)
376✔
2038
        if jsa == nil {
487✔
2039
                return
111✔
2040
        }
111✔
2041
        var streams []*stream
265✔
2042
        jsa.mu.RLock()
265✔
2043
        for _, mset := range jsa.streams {
286✔
2044
                mset.cfgMu.RLock()
21✔
2045
                // We need to have a mirror or source defined.
21✔
2046
                // We do not want to force another lock here to look for leader status,
21✔
2047
                // so collect and after we release jsa will make sure.
21✔
2048
                if mset.cfg.Mirror != nil || len(mset.cfg.Sources) > 0 {
25✔
2049
                        streams = append(streams, mset)
4✔
2050
                }
4✔
2051
                mset.cfgMu.RUnlock()
21✔
2052
        }
2053
        jsa.mu.RUnlock()
265✔
2054

265✔
2055
        // Now loop through all candidates and check if we are the leader and have NOT
265✔
2056
        // created the sync up consumer.
265✔
2057
        for _, mset := range streams {
269✔
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 {
195,227✔
2064
        if c.leaf == nil {
195,227✔
2065
                return _EMPTY_
×
2066
        }
×
2067
        return c.leaf.remoteCluster
195,227✔
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) {
668✔
2073
        // Copy
668✔
2074
        s.mu.Lock()
668✔
2075
        info := s.copyLeafNodeInfo()
668✔
2076
        s.mu.Unlock()
668✔
2077
        c.mu.Lock()
668✔
2078
        info.CID = c.cid
668✔
2079
        info.Import = c.opts.Import
668✔
2080
        info.Export = c.opts.Export
668✔
2081
        info.RemoteAccount = c.acc.Name
668✔
2082
        // s.SystemAccount() uses an atomic operation and does not get the server lock, so this is safe.
668✔
2083
        info.IsSystemAccount = c.acc == s.SystemAccount()
668✔
2084
        info.ConnectInfo = true
668✔
2085
        c.enqueueProto(generateInfoJSON(info))
668✔
2086
        c.mu.Unlock()
668✔
2087
}
668✔
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,291✔
2093
        acc := c.acc
1,291✔
2094
        if acc == nil {
1,291✔
2095
                c.Debugf("Leafnode does not have an account bound")
×
2096
                return
×
2097
        }
×
2098
        // Collect all account subs here.
2099
        _subs := [1024]*subscription{}
1,291✔
2100
        subs := _subs[:0]
1,291✔
2101
        ims := []string{}
1,291✔
2102

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

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

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

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

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

1,291✔
2126
        // Since leaf nodes only send on interest, if the bound
1,291✔
2127
        // account has import services we need to send those over.
1,291✔
2128
        for isubj := range acc.imports.services {
6,089✔
2129
                if c.isSpokeLeafNode() && !c.canSubscribe(isubj) {
5,074✔
2130
                        c.Debugf("Not permitted to import service %q on behalf of %s%s", isubj, accName, accNTag)
276✔
2131
                        continue
276✔
2132
                }
2133
                ims = append(ims, isubj)
4,522✔
2134
        }
2135
        // Likewise for mappings.
2136
        for _, m := range acc.mappings {
3,508✔
2137
                if c.isSpokeLeafNode() && !c.canSubscribe(m.src) {
2,253✔
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,181✔
2142
        }
2143

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

1,291✔
2148
        // Check if we have to create the LDS.
1,291✔
2149
        if lds == _EMPTY_ {
2,301✔
2150
                lds = leafNodeLoopDetectionSubjectPrefix + nuid.Next()
1,010✔
2151
                acc.mu.Lock()
1,010✔
2152
                acc.lds = lds
1,010✔
2153
                acc.mu.Unlock()
1,010✔
2154
        }
1,010✔
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,291✔
2159
        gws := gwsa[:0]
1,291✔
2160
        s.getOutboundGatewayConnections(&gws)
1,291✔
2161
        for _, cgw := range gws {
1,373✔
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,291✔
2175
        if c.isSpokeLeafNode() {
1,915✔
2176
                // Add a fake subscription for this solicited leafnode connection
624✔
2177
                // so that we can send back directly for mapped GW replies.
624✔
2178
                // We need to keep track of this subscription so it can be removed
624✔
2179
                // when the connection is closed so that the GC can release it.
624✔
2180
                c.leaf.gwSub = &subscription{client: c, subject: []byte(gwReplyPrefix + ">")}
624✔
2181
                c.srv.gwLeafSubs.Insert(c.leaf.gwSub)
624✔
2182
        }
624✔
2183

2184
        // Now walk the results and add them to our smap
2185
        rc := c.leaf.remoteCluster
1,291✔
2186
        c.leaf.smap = make(map[string]int32)
1,291✔
2187
        for _, sub := range subs {
38,896✔
2188
                // Check perms regardless of role.
37,605✔
2189
                if c.perms != nil && !c.canSubscribe(string(sub.subject)) {
39,937✔
2190
                        c.Debugf("Not permitted to subscribe to %q on behalf of %s%s", sub.subject, accName, accNTag)
2,332✔
2191
                        continue
2,332✔
2192
                }
2193
                // Don't advertise interest from leafnodes to other isolated leafnodes.
2194
                if sub.client.kind == LEAF && c.isIsolatedLeafNode() {
35,278✔
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)) {
65,221✔
2201
                        count := int32(1)
29,953✔
2202
                        if len(sub.queue) > 0 && sub.qw > 0 {
29,965✔
2203
                                count = sub.qw
12✔
2204
                        }
12✔
2205
                        c.leaf.smap[keyFromSub(sub)] += count
29,953✔
2206
                        if c.leaf.tsub == nil {
31,167✔
2207
                                c.leaf.tsub = make(map[*subscription]struct{})
1,214✔
2208
                        }
1,214✔
2209
                        c.leaf.tsub[sub] = struct{}{}
29,953✔
2210
                }
2211
        }
2212
        // FIXME(dlc) - We need to update appropriately on an account claims update.
2213
        for _, isubj := range ims {
7,994✔
2214
                c.leaf.smap[isubj]++
6,703✔
2215
        }
6,703✔
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,394✔
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,291✔
2226

1,291✔
2227
        // Check if we need to add an existing siReply to our map.
1,291✔
2228
        // This will be a prefix so add on the wildcard.
1,291✔
2229
        if siReply != nil {
1,310✔
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,291✔
2236
        for key, n := range c.leaf.smap {
27,525✔
2237
                c.writeLeafSub(&b, key, n)
26,234✔
2238
        }
26,234✔
2239
        if b.Len() > 0 {
2,582✔
2240
                c.enqueueProto(b.Bytes())
1,291✔
2241
        }
1,291✔
2242
        if c.leaf.tsub != nil {
2,506✔
2243
                // Clear the tsub map after 5 seconds.
1,215✔
2244
                c.leaf.tsubt = time.AfterFunc(5*time.Second, func() {
1,251✔
2245
                        c.mu.Lock()
36✔
2246
                        if c.leaf != nil {
72✔
2247
                                c.leaf.tsub = nil
36✔
2248
                                c.leaf.tsubt = nil
36✔
2249
                        }
36✔
2250
                        c.mu.Unlock()
36✔
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) {
198,154✔
2257
        acc, err := s.LookupAccount(accName)
198,154✔
2258
        if acc == nil || err != nil {
198,313✔
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,995✔
2263
}
2264

2265
// updateLeafNodesEx will make sure to update the account smap for the subscription.
2266
// Will also forward to all leaf nodes as needed.
2267
// If `hubOnly` is true, then will update only leaf nodes that connect to this server
2268
// (that is, for which this server acts as a hub to them).
2269
func (acc *Account) updateLeafNodesEx(sub *subscription, delta int32, hubOnly bool) {
2,431,413✔
2270
        if acc == nil || sub == nil {
2,431,413✔
2271
                return
×
2272
        }
×
2273

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

2279
        acc.mu.RLock()
2,431,413✔
2280
        // First check if we even have leafnodes here.
2,431,413✔
2281
        if acc.nleafs == 0 {
4,794,702✔
2282
                acc.mu.RUnlock()
2,363,289✔
2283
                return
2,363,289✔
2284
        }
2,363,289✔
2285

2286
        // Is this a loop detection subject.
2287
        isLDS := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
68,124✔
2288

68,124✔
2289
        // Capture the cluster even if its empty.
68,124✔
2290
        var cluster string
68,124✔
2291
        if sub.origin != nil {
117,523✔
2292
                cluster = bytesToString(sub.origin)
49,399✔
2293
        }
49,399✔
2294

2295
        // If we have an isolated cluster we can return early, as long as it is not a loop detection subject.
2296
        // Empty clusters will return false for the check.
2297
        if !isLDS && acc.isLeafNodeClusterIsolated(cluster) {
89,474✔
2298
                acc.mu.RUnlock()
21,350✔
2299
                return
21,350✔
2300
        }
21,350✔
2301

2302
        // We can release the general account lock.
2303
        acc.mu.RUnlock()
46,774✔
2304

46,774✔
2305
        // We can hold the list lock here to avoid having to copy a large slice.
46,774✔
2306
        acc.lmu.RLock()
46,774✔
2307
        defer acc.lmu.RUnlock()
46,774✔
2308

46,774✔
2309
        // Do this once.
46,774✔
2310
        subject := string(sub.subject)
46,774✔
2311

46,774✔
2312
        // Walk the connected leafnodes.
46,774✔
2313
        for _, ln := range acc.lleafs {
104,215✔
2314
                if ln == sub.client {
86,796✔
2315
                        continue
29,355✔
2316
                }
2317
                ln.mu.Lock()
28,086✔
2318
                // Don't advertise interest from leafnodes to other isolated leafnodes.
28,086✔
2319
                if sub.client.kind == LEAF && ln.isIsolatedLeafNode() {
28,098✔
2320
                        ln.mu.Unlock()
12✔
2321
                        continue
12✔
2322
                }
2323
                // If `hubOnly` is true, it means that we want to update only leafnodes
2324
                // that connect to this server (so isHubLeafNode() would return `true`).
2325
                if hubOnly && !ln.isHubLeafNode() {
28,077✔
2326
                        ln.mu.Unlock()
3✔
2327
                        continue
3✔
2328
                }
2329
                // Check to make sure this sub does not have an origin cluster that matches the leafnode.
2330
                // If skipped, make sure that we still let go the "$LDS." subscription that allows
2331
                // the detection of loops as long as different cluster.
2332
                clusterDifferent := cluster != ln.remoteCluster()
28,071✔
2333
                if (isLDS && clusterDifferent) || ((cluster == _EMPTY_ || clusterDifferent) && (delta <= 0 || ln.canSubscribe(subject))) {
51,812✔
2334
                        ln.updateSmap(sub, delta, isLDS)
23,741✔
2335
                }
23,741✔
2336
                ln.mu.Unlock()
28,071✔
2337
        }
2338
}
2339

2340
// updateLeafNodes will make sure to update the account smap for the subscription.
2341
// Will also forward to all leaf nodes as needed.
2342
func (acc *Account) updateLeafNodes(sub *subscription, delta int32) {
2,431,397✔
2343
        acc.updateLeafNodesEx(sub, delta, false)
2,431,397✔
2344
}
2,431,397✔
2345

2346
// This will make an update to our internal smap and determine if we should send out
2347
// an interest update to the remote side.
2348
// Lock should be held.
2349
func (c *client) updateSmap(sub *subscription, delta int32, isLDS bool) {
23,741✔
2350
        if c.leaf.smap == nil {
23,747✔
2351
                return
6✔
2352
        }
6✔
2353

2354
        // If we are solicited make sure this is a local client or a non-solicited leaf node
2355
        skind := sub.client.kind
23,735✔
2356
        updateClient := skind == CLIENT || skind == SYSTEM || skind == JETSTREAM || skind == ACCOUNT
23,735✔
2357
        if !isLDS && c.isSpokeLeafNode() && !(updateClient || (skind == LEAF && !sub.client.isSpokeLeafNode())) {
32,053✔
2358
                return
8,318✔
2359
        }
8,318✔
2360

2361
        // For additions, check if that sub has just been processed during initLeafNodeSmapAndSendSubs
2362
        if delta > 0 && c.leaf.tsub != nil {
22,833✔
2363
                if _, present := c.leaf.tsub[sub]; present {
7,416✔
2364
                        delete(c.leaf.tsub, sub)
×
2365
                        if len(c.leaf.tsub) == 0 {
×
2366
                                c.leaf.tsub = nil
×
2367
                                c.leaf.tsubt.Stop()
×
2368
                                c.leaf.tsubt = nil
×
2369
                        }
×
2370
                        return
×
2371
                }
2372
        }
2373

2374
        key := keyFromSub(sub)
15,417✔
2375
        n, ok := c.leaf.smap[key]
15,417✔
2376
        if delta < 0 && !ok {
16,366✔
2377
                return
949✔
2378
        }
949✔
2379

2380
        // We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
2381
        update := sub.queue != nil || (n <= 0 && n+delta > 0) || (n > 0 && n+delta <= 0)
14,468✔
2382
        n += delta
14,468✔
2383
        if n > 0 {
25,394✔
2384
                c.leaf.smap[key] = n
10,926✔
2385
        } else {
14,468✔
2386
                delete(c.leaf.smap, key)
3,542✔
2387
        }
3,542✔
2388
        if update {
23,886✔
2389
                c.sendLeafNodeSubUpdate(key, n)
9,418✔
2390
        }
9,418✔
2391
}
2392

2393
// Used to force add subjects to the subject map.
2394
func (c *client) forceAddToSmap(subj string) {
4✔
2395
        c.mu.Lock()
4✔
2396
        defer c.mu.Unlock()
4✔
2397

4✔
2398
        if c.leaf.smap == nil {
4✔
2399
                return
×
2400
        }
×
2401
        n := c.leaf.smap[subj]
4✔
2402
        if n != 0 {
5✔
2403
                return
1✔
2404
        }
1✔
2405
        // Place into the map since it was not there.
2406
        c.leaf.smap[subj] = 1
3✔
2407
        c.sendLeafNodeSubUpdate(subj, 1)
3✔
2408
}
2409

2410
// Used to force remove a subject from the subject map.
2411
func (c *client) forceRemoveFromSmap(subj string) {
1✔
2412
        c.mu.Lock()
1✔
2413
        defer c.mu.Unlock()
1✔
2414

1✔
2415
        if c.leaf.smap == nil {
1✔
2416
                return
×
2417
        }
×
2418
        n := c.leaf.smap[subj]
1✔
2419
        if n == 0 {
1✔
2420
                return
×
2421
        }
×
2422
        n--
1✔
2423
        if n == 0 {
2✔
2424
                // Remove is now zero
1✔
2425
                delete(c.leaf.smap, subj)
1✔
2426
                c.sendLeafNodeSubUpdate(subj, 0)
1✔
2427
        } else {
1✔
2428
                c.leaf.smap[subj] = n
×
2429
        }
×
2430
}
2431

2432
// Send the subscription interest change to the other side.
2433
// Lock should be held.
2434
func (c *client) sendLeafNodeSubUpdate(key string, n int32) {
9,422✔
2435
        // If we are a spoke, we need to check if we are allowed to send this subscription over to the hub.
9,422✔
2436
        if c.isSpokeLeafNode() {
11,753✔
2437
                checkPerms := true
2,331✔
2438
                if len(key) > 0 && (key[0] == '$' || key[0] == '_') {
3,703✔
2439
                        if strings.HasPrefix(key, leafNodeLoopDetectionSubjectPrefix) ||
1,372✔
2440
                                strings.HasPrefix(key, oldGWReplyPrefix) ||
1,372✔
2441
                                strings.HasPrefix(key, gwReplyPrefix) {
1,463✔
2442
                                checkPerms = false
91✔
2443
                        }
91✔
2444
                }
2445
                if checkPerms {
4,571✔
2446
                        var subject string
2,240✔
2447
                        if sep := strings.IndexByte(key, ' '); sep != -1 {
2,732✔
2448
                                subject = key[:sep]
492✔
2449
                        } else {
2,240✔
2450
                                subject = key
1,748✔
2451
                        }
1,748✔
2452
                        if !c.canSubscribe(subject) {
2,240✔
2453
                                return
×
2454
                        }
×
2455
                }
2456
        }
2457
        // If we are here we can send over to the other side.
2458
        _b := [64]byte{}
9,422✔
2459
        b := bytes.NewBuffer(_b[:0])
9,422✔
2460
        c.writeLeafSub(b, key, n)
9,422✔
2461
        c.enqueueProto(b.Bytes())
9,422✔
2462
}
2463

2464
// Helper function to build the key.
2465
func keyFromSub(sub *subscription) string {
46,294✔
2466
        var sb strings.Builder
46,294✔
2467
        sb.Grow(len(sub.subject) + len(sub.queue) + 1)
46,294✔
2468
        sb.Write(sub.subject)
46,294✔
2469
        if sub.queue != nil {
50,017✔
2470
                // Just make the key subject spc group, e.g. 'foo bar'
3,723✔
2471
                sb.WriteByte(' ')
3,723✔
2472
                sb.Write(sub.queue)
3,723✔
2473
        }
3,723✔
2474
        return sb.String()
46,294✔
2475
}
2476

2477
const (
2478
        keyRoutedSub         = "R"
2479
        keyRoutedSubByte     = 'R'
2480
        keyRoutedLeafSub     = "L"
2481
        keyRoutedLeafSubByte = 'L'
2482
)
2483

2484
// Helper function to build the key that prevents collisions between normal
2485
// routed subscriptions and routed subscriptions on behalf of a leafnode.
2486
// Keys will look like this:
2487
// "R foo"          -> plain routed sub on "foo"
2488
// "R foo bar"      -> queue routed sub on "foo", queue "bar"
2489
// "L foo bar"      -> plain routed leaf sub on "foo", leaf "bar"
2490
// "L foo bar baz"  -> queue routed sub on "foo", queue "bar", leaf "baz"
2491
func keyFromSubWithOrigin(sub *subscription) string {
674,507✔
2492
        var sb strings.Builder
674,507✔
2493
        sb.Grow(2 + len(sub.origin) + 1 + len(sub.subject) + 1 + len(sub.queue))
674,507✔
2494
        leaf := len(sub.origin) > 0
674,507✔
2495
        if leaf {
691,187✔
2496
                sb.WriteByte(keyRoutedLeafSubByte)
16,680✔
2497
        } else {
674,507✔
2498
                sb.WriteByte(keyRoutedSubByte)
657,827✔
2499
        }
657,827✔
2500
        sb.WriteByte(' ')
674,507✔
2501
        sb.Write(sub.subject)
674,507✔
2502
        if sub.queue != nil {
697,645✔
2503
                sb.WriteByte(' ')
23,138✔
2504
                sb.Write(sub.queue)
23,138✔
2505
        }
23,138✔
2506
        if leaf {
691,187✔
2507
                sb.WriteByte(' ')
16,680✔
2508
                sb.Write(sub.origin)
16,680✔
2509
        }
16,680✔
2510
        return sb.String()
674,507✔
2511
}
2512

2513
// Lock should be held.
2514
func (c *client) writeLeafSub(w *bytes.Buffer, key string, n int32) {
35,656✔
2515
        if key == _EMPTY_ {
35,656✔
2516
                return
×
2517
        }
×
2518
        if n > 0 {
67,769✔
2519
                w.WriteString("LS+ " + key)
32,113✔
2520
                // Check for queue semantics, if found write n.
32,113✔
2521
                if strings.Contains(key, " ") {
34,429✔
2522
                        w.WriteString(" ")
2,316✔
2523
                        var b [12]byte
2,316✔
2524
                        var i = len(b)
2,316✔
2525
                        for l := n; l > 0; l /= 10 {
5,547✔
2526
                                i--
3,231✔
2527
                                b[i] = digits[l%10]
3,231✔
2528
                        }
3,231✔
2529
                        w.Write(b[i:])
2,316✔
2530
                        if c.trace {
2,316✔
2531
                                arg := fmt.Sprintf("%s %d", key, n)
×
2532
                                c.traceOutOp("LS+", []byte(arg))
×
2533
                        }
×
2534
                } else if c.trace {
29,993✔
2535
                        c.traceOutOp("LS+", []byte(key))
196✔
2536
                }
196✔
2537
        } else {
3,543✔
2538
                w.WriteString("LS- " + key)
3,543✔
2539
                if c.trace {
3,554✔
2540
                        c.traceOutOp("LS-", []byte(key))
11✔
2541
                }
11✔
2542
        }
2543
        w.WriteString(CR_LF)
35,656✔
2544
}
2545

2546
// processLeafSub will process an inbound sub request for the remote leaf node.
2547
func (c *client) processLeafSub(argo []byte) (err error) {
31,803✔
2548
        // Indicate activity.
31,803✔
2549
        c.in.subs++
31,803✔
2550

31,803✔
2551
        srv := c.srv
31,803✔
2552
        if srv == nil {
31,803✔
2553
                return nil
×
2554
        }
×
2555

2556
        // Copy so we do not reference a potentially large buffer
2557
        arg := make([]byte, len(argo))
31,803✔
2558
        copy(arg, argo)
31,803✔
2559

31,803✔
2560
        args := splitArg(arg)
31,803✔
2561
        sub := &subscription{client: c}
31,803✔
2562

31,803✔
2563
        delta := int32(1)
31,803✔
2564
        switch len(args) {
31,803✔
2565
        case 1:
29,542✔
2566
                sub.queue = nil
29,542✔
2567
        case 3:
2,260✔
2568
                sub.queue = args[1]
2,260✔
2569
                sub.qw = int32(parseSize(args[2]))
2,260✔
2570
                // TODO: (ik) We should have a non empty queue name and a queue
2,260✔
2571
                // weight >= 1. For 2.11, we may want to return an error if that
2,260✔
2572
                // is not the case, but for now just overwrite `delta` if queue
2,260✔
2573
                // weight is greater than 1 (it is possible after a reconnect/
2,260✔
2574
                // server restart to receive a queue weight > 1 for a new sub).
2,260✔
2575
                if sub.qw > 1 {
3,915✔
2576
                        delta = sub.qw
1,655✔
2577
                }
1,655✔
2578
        default:
1✔
2579
                return fmt.Errorf("processLeafSub Parse Error: '%s'", arg)
1✔
2580
        }
2581
        sub.subject = args[0]
31,802✔
2582

31,802✔
2583
        c.mu.Lock()
31,802✔
2584
        if c.isClosed() {
31,821✔
2585
                c.mu.Unlock()
19✔
2586
                return nil
19✔
2587
        }
19✔
2588

2589
        acc := c.acc
31,783✔
2590
        // Check if we have a loop.
31,783✔
2591
        ldsPrefix := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
31,783✔
2592

31,783✔
2593
        if ldsPrefix && bytesToString(sub.subject) == acc.getLDSubject() {
31,789✔
2594
                c.mu.Unlock()
6✔
2595
                c.handleLeafNodeLoop(true)
6✔
2596
                return nil
6✔
2597
        }
6✔
2598

2599
        // Check permissions if applicable. (but exclude the $LDS, $GR and _GR_)
2600
        checkPerms := true
31,777✔
2601
        if sub.subject[0] == '$' || sub.subject[0] == '_' {
60,654✔
2602
                if ldsPrefix ||
28,877✔
2603
                        bytes.HasPrefix(sub.subject, []byte(oldGWReplyPrefix)) ||
28,877✔
2604
                        bytes.HasPrefix(sub.subject, []byte(gwReplyPrefix)) {
30,855✔
2605
                        checkPerms = false
1,978✔
2606
                }
1,978✔
2607
        }
2608

2609
        // If we are a hub check that we can publish to this subject.
2610
        if checkPerms {
61,576✔
2611
                subj := string(sub.subject)
29,799✔
2612
                if subjectIsLiteral(subj) && !c.pubAllowedFullCheck(subj, true, true) {
30,129✔
2613
                        c.mu.Unlock()
330✔
2614
                        c.leafSubPermViolation(sub.subject)
330✔
2615
                        c.Debugf(fmt.Sprintf("Permissions Violation for Subscription to %q", sub.subject))
330✔
2616
                        return nil
330✔
2617
                }
330✔
2618
        }
2619

2620
        // Check if we have a maximum on the number of subscriptions.
2621
        if c.subsAtLimit() {
31,455✔
2622
                c.mu.Unlock()
8✔
2623
                c.maxSubsExceeded()
8✔
2624
                return nil
8✔
2625
        }
8✔
2626

2627
        // If we have an origin cluster associated mark that in the sub.
2628
        if rc := c.remoteCluster(); rc != _EMPTY_ {
59,704✔
2629
                sub.origin = []byte(rc)
28,265✔
2630
        }
28,265✔
2631

2632
        // Like Routes, we store local subs by account and subject and optionally queue name.
2633
        // If we have a queue it will have a trailing weight which we do not want.
2634
        if sub.queue != nil {
33,399✔
2635
                sub.sid = arg[:len(arg)-len(args[2])-1]
1,960✔
2636
        } else {
31,439✔
2637
                sub.sid = arg
29,479✔
2638
        }
29,479✔
2639
        key := bytesToString(sub.sid)
31,439✔
2640
        osub := c.subs[key]
31,439✔
2641
        if osub == nil {
61,377✔
2642
                c.subs[key] = sub
29,938✔
2643
                // Now place into the account sl.
29,938✔
2644
                if err := acc.sl.Insert(sub); err != nil {
29,938✔
2645
                        delete(c.subs, key)
×
2646
                        c.mu.Unlock()
×
2647
                        c.Errorf("Could not insert subscription: %v", err)
×
2648
                        c.sendErr("Invalid Subscription")
×
2649
                        return nil
×
2650
                }
×
2651
        } else if sub.queue != nil {
3,001✔
2652
                // For a queue we need to update the weight.
1,500✔
2653
                delta = sub.qw - atomic.LoadInt32(&osub.qw)
1,500✔
2654
                atomic.StoreInt32(&osub.qw, sub.qw)
1,500✔
2655
                acc.sl.UpdateRemoteQSub(osub)
1,500✔
2656
        }
1,500✔
2657
        spoke := c.isSpokeLeafNode()
31,439✔
2658
        c.mu.Unlock()
31,439✔
2659

31,439✔
2660
        // Only add in shadow subs if a new sub or qsub.
31,439✔
2661
        if osub == nil {
61,377✔
2662
                if err := c.addShadowSubscriptions(acc, sub, true); err != nil {
29,938✔
2663
                        c.Errorf(err.Error())
×
2664
                }
×
2665
        }
2666

2667
        // If we are not solicited, treat leaf node subscriptions similar to a
2668
        // client subscription, meaning we forward them to routes, gateways and
2669
        // other leaf nodes as needed.
2670
        if !spoke {
42,495✔
2671
                // If we are routing add to the route map for the associated account.
11,056✔
2672
                srv.updateRouteSubscriptionMap(acc, sub, delta)
11,056✔
2673
                if srv.gateway.enabled {
12,582✔
2674
                        srv.gatewayUpdateSubInterest(acc.Name, sub, delta)
1,526✔
2675
                }
1,526✔
2676
        }
2677
        // Now check on leafnode updates for other leaf nodes. We understand solicited
2678
        // and non-solicited state in this call so we will do the right thing.
2679
        acc.updateLeafNodes(sub, delta)
31,439✔
2680

31,439✔
2681
        return nil
31,439✔
2682
}
2683

2684
// If the leafnode is a solicited, set the connect delay based on default
2685
// or private option (for tests). Sends the error to the other side, log and
2686
// close the connection.
2687
func (c *client) handleLeafNodeLoop(sendErr bool) {
14✔
2688
        accName, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterLoopDetected)
14✔
2689
        errTxt := fmt.Sprintf("Loop detected for leafnode account=%q. Delaying attempt to reconnect for %v", accName, delay)
14✔
2690
        if sendErr {
22✔
2691
                c.sendErr(errTxt)
8✔
2692
        }
8✔
2693

2694
        c.Errorf(errTxt)
14✔
2695
        // If we are here with "sendErr" false, it means that this is the server
14✔
2696
        // that received the error. The other side will have closed the connection,
14✔
2697
        // but does not hurt to close here too.
14✔
2698
        c.closeConnection(ProtocolViolation)
14✔
2699
}
2700

2701
// processLeafUnsub will process an inbound unsub request for the remote leaf node.
2702
func (c *client) processLeafUnsub(arg []byte) error {
3,326✔
2703
        // Indicate any activity, so pub and sub or unsubs.
3,326✔
2704
        c.in.subs++
3,326✔
2705

3,326✔
2706
        acc := c.acc
3,326✔
2707
        srv := c.srv
3,326✔
2708

3,326✔
2709
        c.mu.Lock()
3,326✔
2710
        if c.isClosed() {
3,384✔
2711
                c.mu.Unlock()
58✔
2712
                return nil
58✔
2713
        }
58✔
2714

2715
        spoke := c.isSpokeLeafNode()
3,268✔
2716
        // We store local subs by account and subject and optionally queue name.
3,268✔
2717
        // LS- will have the arg exactly as the key.
3,268✔
2718
        sub, ok := c.subs[string(arg)]
3,268✔
2719
        if !ok {
3,279✔
2720
                // If not found, don't try to update routes/gws/leaf nodes.
11✔
2721
                c.mu.Unlock()
11✔
2722
                return nil
11✔
2723
        }
11✔
2724
        delta := int32(1)
3,257✔
2725
        if len(sub.queue) > 0 {
3,677✔
2726
                delta = sub.qw
420✔
2727
        }
420✔
2728
        c.mu.Unlock()
3,257✔
2729

3,257✔
2730
        c.unsubscribe(acc, sub, true, true)
3,257✔
2731
        if !spoke {
4,294✔
2732
                // If we are routing subtract from the route map for the associated account.
1,037✔
2733
                srv.updateRouteSubscriptionMap(acc, sub, -delta)
1,037✔
2734
                // Gateways
1,037✔
2735
                if srv.gateway.enabled {
1,324✔
2736
                        srv.gatewayUpdateSubInterest(acc.Name, sub, -delta)
287✔
2737
                }
287✔
2738
        }
2739
        // Now check on leafnode updates for other leaf nodes.
2740
        acc.updateLeafNodes(sub, -delta)
3,257✔
2741
        return nil
3,257✔
2742
}
2743

2744
func (c *client) processLeafHeaderMsgArgs(arg []byte) error {
479✔
2745
        // Unroll splitArgs to avoid runtime/heap issues
479✔
2746
        a := [MAX_MSG_ARGS][]byte{}
479✔
2747
        args := a[:0]
479✔
2748
        start := -1
479✔
2749
        for i, b := range arg {
31,406✔
2750
                switch b {
30,927✔
2751
                case ' ', '\t', '\r', '\n':
1,365✔
2752
                        if start >= 0 {
2,730✔
2753
                                args = append(args, arg[start:i])
1,365✔
2754
                                start = -1
1,365✔
2755
                        }
1,365✔
2756
                default:
29,562✔
2757
                        if start < 0 {
31,406✔
2758
                                start = i
1,844✔
2759
                        }
1,844✔
2760
                }
2761
        }
2762
        if start >= 0 {
958✔
2763
                args = append(args, arg[start:])
479✔
2764
        }
479✔
2765

2766
        c.pa.arg = arg
479✔
2767
        switch len(args) {
479✔
2768
        case 0, 1, 2:
×
2769
                return fmt.Errorf("processLeafHeaderMsgArgs Parse Error: '%s'", args)
×
2770
        case 3:
90✔
2771
                c.pa.reply = nil
90✔
2772
                c.pa.queues = nil
90✔
2773
                c.pa.hdb = args[1]
90✔
2774
                c.pa.hdr = parseSize(args[1])
90✔
2775
                c.pa.szb = args[2]
90✔
2776
                c.pa.size = parseSize(args[2])
90✔
2777
        case 4:
375✔
2778
                c.pa.reply = args[1]
375✔
2779
                c.pa.queues = nil
375✔
2780
                c.pa.hdb = args[2]
375✔
2781
                c.pa.hdr = parseSize(args[2])
375✔
2782
                c.pa.szb = args[3]
375✔
2783
                c.pa.size = parseSize(args[3])
375✔
2784
        default:
14✔
2785
                // args[1] is our reply indicator. Should be + or | normally.
14✔
2786
                if len(args[1]) != 1 {
14✔
2787
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2788
                }
×
2789
                switch args[1][0] {
14✔
2790
                case '+':
4✔
2791
                        c.pa.reply = args[2]
4✔
2792
                case '|':
10✔
2793
                        c.pa.reply = nil
10✔
2794
                default:
×
2795
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2796
                }
2797
                // Grab header size.
2798
                c.pa.hdb = args[len(args)-2]
14✔
2799
                c.pa.hdr = parseSize(c.pa.hdb)
14✔
2800

14✔
2801
                // Grab size.
14✔
2802
                c.pa.szb = args[len(args)-1]
14✔
2803
                c.pa.size = parseSize(c.pa.szb)
14✔
2804

14✔
2805
                // Grab queue names.
14✔
2806
                if c.pa.reply != nil {
18✔
2807
                        c.pa.queues = args[3 : len(args)-2]
4✔
2808
                } else {
14✔
2809
                        c.pa.queues = args[2 : len(args)-2]
10✔
2810
                }
10✔
2811
        }
2812
        if c.pa.hdr < 0 {
479✔
2813
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Header Size: '%s'", arg)
×
2814
        }
×
2815
        if c.pa.size < 0 {
479✔
2816
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Size: '%s'", args)
×
2817
        }
×
2818
        if c.pa.hdr > c.pa.size {
480✔
2819
                return fmt.Errorf("processLeafHeaderMsgArgs Header Size larger then TotalSize: '%s'", arg)
1✔
2820
        }
1✔
2821

2822
        // Common ones processed after check for arg length
2823
        c.pa.subject = args[0]
478✔
2824

478✔
2825
        return nil
478✔
2826
}
2827

2828
func (c *client) processLeafMsgArgs(arg []byte) error {
109,861✔
2829
        // Unroll splitArgs to avoid runtime/heap issues
109,861✔
2830
        a := [MAX_MSG_ARGS][]byte{}
109,861✔
2831
        args := a[:0]
109,861✔
2832
        start := -1
109,861✔
2833
        for i, b := range arg {
3,528,096✔
2834
                switch b {
3,418,235✔
2835
                case ' ', '\t', '\r', '\n':
161,158✔
2836
                        if start >= 0 {
322,316✔
2837
                                args = append(args, arg[start:i])
161,158✔
2838
                                start = -1
161,158✔
2839
                        }
161,158✔
2840
                default:
3,257,077✔
2841
                        if start < 0 {
3,528,096✔
2842
                                start = i
271,019✔
2843
                        }
271,019✔
2844
                }
2845
        }
2846
        if start >= 0 {
219,722✔
2847
                args = append(args, arg[start:])
109,861✔
2848
        }
109,861✔
2849

2850
        c.pa.arg = arg
109,861✔
2851
        switch len(args) {
109,861✔
2852
        case 0, 1:
×
2853
                return fmt.Errorf("processLeafMsgArgs Parse Error: '%s'", args)
×
2854
        case 2:
81,272✔
2855
                c.pa.reply = nil
81,272✔
2856
                c.pa.queues = nil
81,272✔
2857
                c.pa.szb = args[1]
81,272✔
2858
                c.pa.size = parseSize(args[1])
81,272✔
2859
        case 3:
6,043✔
2860
                c.pa.reply = args[1]
6,043✔
2861
                c.pa.queues = nil
6,043✔
2862
                c.pa.szb = args[2]
6,043✔
2863
                c.pa.size = parseSize(args[2])
6,043✔
2864
        default:
22,546✔
2865
                // args[1] is our reply indicator. Should be + or | normally.
22,546✔
2866
                if len(args[1]) != 1 {
22,547✔
2867
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
1✔
2868
                }
1✔
2869
                switch args[1][0] {
22,545✔
2870
                case '+':
161✔
2871
                        c.pa.reply = args[2]
161✔
2872
                case '|':
22,384✔
2873
                        c.pa.reply = nil
22,384✔
2874
                default:
×
2875
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2876
                }
2877
                // Grab size.
2878
                c.pa.szb = args[len(args)-1]
22,545✔
2879
                c.pa.size = parseSize(c.pa.szb)
22,545✔
2880

22,545✔
2881
                // Grab queue names.
22,545✔
2882
                if c.pa.reply != nil {
22,706✔
2883
                        c.pa.queues = args[3 : len(args)-1]
161✔
2884
                } else {
22,545✔
2885
                        c.pa.queues = args[2 : len(args)-1]
22,384✔
2886
                }
22,384✔
2887
        }
2888
        if c.pa.size < 0 {
109,860✔
2889
                return fmt.Errorf("processLeafMsgArgs Bad or Missing Size: '%s'", args)
×
2890
        }
×
2891

2892
        // Common ones processed after check for arg length
2893
        c.pa.subject = args[0]
109,860✔
2894

109,860✔
2895
        return nil
109,860✔
2896
}
2897

2898
// processInboundLeafMsg is called to process an inbound msg from a leaf node.
2899
func (c *client) processInboundLeafMsg(msg []byte) {
108,292✔
2900
        // Update statistics
108,292✔
2901
        // The msg includes the CR_LF, so pull back out for accounting.
108,292✔
2902
        c.in.msgs++
108,292✔
2903
        c.in.bytes += int32(len(msg) - LEN_CR_LF)
108,292✔
2904

108,292✔
2905
        srv, acc, subject := c.srv, c.acc, string(c.pa.subject)
108,292✔
2906

108,292✔
2907
        // Mostly under testing scenarios.
108,292✔
2908
        if srv == nil || acc == nil {
108,294✔
2909
                return
2✔
2910
        }
2✔
2911

2912
        // Match the subscriptions. We will use our own L1 map if
2913
        // it's still valid, avoiding contention on the shared sublist.
2914
        var r *SublistResult
108,290✔
2915
        var ok bool
108,290✔
2916

108,290✔
2917
        genid := atomic.LoadUint64(&c.acc.sl.genid)
108,290✔
2918
        if genid == c.in.genid && c.in.results != nil {
214,245✔
2919
                r, ok = c.in.results[subject]
105,955✔
2920
        } else {
108,290✔
2921
                // Reset our L1 completely.
2,335✔
2922
                c.in.results = make(map[string]*SublistResult)
2,335✔
2923
                c.in.genid = genid
2,335✔
2924
        }
2,335✔
2925

2926
        // Go back to the sublist data structure.
2927
        if !ok {
186,639✔
2928
                r = c.acc.sl.Match(subject)
78,349✔
2929
                // Prune the results cache. Keeps us from unbounded growth. Random delete.
78,349✔
2930
                if len(c.in.results) >= maxResultCacheSize {
80,551✔
2931
                        n := 0
2,202✔
2932
                        for subj := range c.in.results {
74,868✔
2933
                                delete(c.in.results, subj)
72,666✔
2934
                                if n++; n > pruneSize {
74,868✔
2935
                                        break
2,202✔
2936
                                }
2937
                        }
2938
                }
2939
                // Then add the new cache entry.
2940
                c.in.results[subject] = r
78,349✔
2941
        }
2942

2943
        // Collect queue names if needed.
2944
        var qnames [][]byte
108,290✔
2945

108,290✔
2946
        // Check for no interest, short circuit if so.
108,290✔
2947
        // This is the fanout scale.
108,290✔
2948
        if len(r.psubs)+len(r.qsubs) > 0 {
216,113✔
2949
                flag := pmrNoFlag
107,823✔
2950
                // If we have queue subs in this cluster, then if we run in gateway
107,823✔
2951
                // mode and the remote gateways have queue subs, then we need to
107,823✔
2952
                // collect the queue groups this message was sent to so that we
107,823✔
2953
                // exclude them when sending to gateways.
107,823✔
2954
                if len(r.qsubs) > 0 && c.srv.gateway.enabled &&
107,823✔
2955
                        atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 {
120,052✔
2956
                        flag |= pmrCollectQueueNames
12,229✔
2957
                }
12,229✔
2958
                // If this is a mapped subject that means the mapped interest
2959
                // is what got us here, but this might not have a queue designation
2960
                // If that is the case, make sure we ignore to process local queue subscribers.
2961
                if len(c.pa.mapped) > 0 && len(c.pa.queues) == 0 {
108,134✔
2962
                        flag |= pmrIgnoreEmptyQueueFilter
311✔
2963
                }
311✔
2964
                _, qnames = c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, flag)
107,823✔
2965
        }
2966

2967
        // Now deal with gateways
2968
        if c.srv.gateway.enabled {
121,597✔
2969
                c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, qnames, true)
13,307✔
2970
        }
13,307✔
2971
}
2972

2973
// Handles a subscription permission violation.
2974
// See leafPermViolation() for details.
2975
func (c *client) leafSubPermViolation(subj []byte) {
330✔
2976
        c.leafPermViolation(false, subj)
330✔
2977
}
330✔
2978

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

3003
// Invoked from generic processErr() for LEAF connections.
3004
func (c *client) leafProcessErr(errStr string) {
45✔
3005
        // Check if we got a cluster name collision.
45✔
3006
        if strings.Contains(errStr, ErrLeafNodeHasSameClusterName.Error()) {
48✔
3007
                _, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterClusterNameSame)
3✔
3008
                c.Errorf("Leafnode connection dropped with same cluster name error. Delaying attempt to reconnect for %v", delay)
3✔
3009
                return
3✔
3010
        }
3✔
3011

3012
        // We will look for Loop detected error coming from the other side.
3013
        // If we solicit, set the connect delay.
3014
        if !strings.Contains(errStr, "Loop detected") {
78✔
3015
                return
36✔
3016
        }
36✔
3017
        c.handleLeafNodeLoop(false)
6✔
3018
}
3019

3020
// If this leaf connection solicits, sets the connect delay to the given value,
3021
// or the one from the server option's LeafNode.connDelay if one is set (for tests).
3022
// Returns the connection's account name and delay.
3023
func (c *client) setLeafConnectDelayIfSoliciting(delay time.Duration) (string, time.Duration) {
17✔
3024
        c.mu.Lock()
17✔
3025
        if c.isSolicitedLeafNode() {
27✔
3026
                if s := c.srv; s != nil {
20✔
3027
                        if srvdelay := s.getOpts().LeafNode.connDelay; srvdelay != 0 {
14✔
3028
                                delay = srvdelay
4✔
3029
                        }
4✔
3030
                }
3031
                c.leaf.remote.setConnectDelay(delay)
10✔
3032
        }
3033
        accName := c.acc.Name
17✔
3034
        c.mu.Unlock()
17✔
3035
        return accName, delay
17✔
3036
}
3037

3038
// For the given remote Leafnode configuration, this function returns
3039
// if TLS is required, and if so, will return a clone of the TLS Config
3040
// (since some fields will be changed during handshake), the TLS server
3041
// name that is remembered, and the TLS timeout.
3042
func (c *client) leafNodeGetTLSConfigForSolicit(remote *leafNodeCfg) (bool, *tls.Config, string, float64) {
1,894✔
3043
        var (
1,894✔
3044
                tlsConfig  *tls.Config
1,894✔
3045
                tlsName    string
1,894✔
3046
                tlsTimeout float64
1,894✔
3047
        )
1,894✔
3048

1,894✔
3049
        remote.RLock()
1,894✔
3050
        defer remote.RUnlock()
1,894✔
3051

1,894✔
3052
        tlsRequired := remote.TLS || remote.TLSConfig != nil
1,894✔
3053
        if tlsRequired {
1,974✔
3054
                if remote.TLSConfig != nil {
131✔
3055
                        tlsConfig = remote.TLSConfig.Clone()
51✔
3056
                } else {
80✔
3057
                        tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}
29✔
3058
                }
29✔
3059
                tlsName = remote.tlsName
80✔
3060
                tlsTimeout = remote.TLSTimeout
80✔
3061
                if tlsTimeout == 0 {
126✔
3062
                        tlsTimeout = float64(TLS_TIMEOUT / time.Second)
46✔
3063
                }
46✔
3064
        }
3065

3066
        return tlsRequired, tlsConfig, tlsName, tlsTimeout
1,894✔
3067
}
3068

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

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

3128
        req.Header["Upgrade"] = []string{"websocket"}
39✔
3129
        req.Header["Connection"] = []string{"Upgrade"}
39✔
3130
        req.Header["Sec-WebSocket-Key"] = []string{wsKey}
39✔
3131
        req.Header["Sec-WebSocket-Version"] = []string{"13"}
39✔
3132
        if compress {
48✔
3133
                req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue)
9✔
3134
        }
9✔
3135
        if noMasking {
49✔
3136
                req.Header.Add(wsNoMaskingHeader, wsNoMaskingValue)
10✔
3137
        }
10✔
3138
        c.nc.SetDeadline(time.Now().Add(infoTimeout))
39✔
3139
        if err := req.Write(c.nc); err != nil {
39✔
3140
                return nil, WriteError, err
×
3141
        }
×
3142

3143
        var resp *http.Response
39✔
3144

39✔
3145
        br := bufio.NewReaderSize(c.nc, MAX_CONTROL_LINE_SIZE)
39✔
3146
        resp, err = http.ReadResponse(br, req)
39✔
3147
        if err == nil &&
39✔
3148
                (resp.StatusCode != 101 ||
39✔
3149
                        !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
39✔
3150
                        !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
39✔
3151
                        resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) {
40✔
3152

1✔
3153
                err = fmt.Errorf("invalid websocket connection")
1✔
3154
        }
1✔
3155
        // Check compression extension...
3156
        if err == nil && c.ws.compress {
48✔
3157
                // Check that not only permessage-deflate extension is present, but that
9✔
3158
                // we also have server and client no context take over.
9✔
3159
                srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header, false)
9✔
3160

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

27✔
3184
        var preBuf []byte
27✔
3185
        // We have to slurp whatever is in the bufio reader and pass that to the readloop.
27✔
3186
        if n := br.Buffered(); n != 0 {
27✔
3187
                preBuf, _ = br.Peek(n)
×
3188
        }
×
3189
        return preBuf, 0, nil
27✔
3190
}
3191

3192
const connectProcessTimeout = 2 * time.Second
3193

3194
// This is invoked for remote LEAF remote connections after processing the INFO
3195
// protocol.
3196
func (s *Server) leafNodeResumeConnectProcess(c *client) {
662✔
3197
        clusterName := s.ClusterName()
662✔
3198

662✔
3199
        c.mu.Lock()
662✔
3200
        if c.isClosed() {
662✔
3201
                c.mu.Unlock()
×
3202
                return
×
3203
        }
×
3204
        if err := c.sendLeafConnect(clusterName, c.headers); err != nil {
664✔
3205
                c.mu.Unlock()
2✔
3206
                c.closeConnection(WriteError)
2✔
3207
                return
2✔
3208
        }
2✔
3209

3210
        // Spin up the write loop.
3211
        s.startGoRoutine(func() { c.writeLoop() })
1,320✔
3212

3213
        // timeout leafNodeFinishConnectProcess
3214
        c.ping.tmr = time.AfterFunc(connectProcessTimeout, func() {
660✔
3215
                c.mu.Lock()
×
3216
                // check if leafNodeFinishConnectProcess was called and prevent later leafNodeFinishConnectProcess
×
3217
                if !c.flags.setIfNotSet(connectProcessFinished) {
×
3218
                        c.mu.Unlock()
×
3219
                        return
×
3220
                }
×
3221
                clearTimer(&c.ping.tmr)
×
3222
                closed := c.isClosed()
×
3223
                c.mu.Unlock()
×
3224
                if !closed {
×
3225
                        c.sendErrAndDebug("Stale Leaf Node Connection - Closing")
×
3226
                        c.closeConnection(StaleConnection)
×
3227
                }
×
3228
        })
3229
        c.mu.Unlock()
660✔
3230
        c.Debugf("Remote leafnode connect msg sent")
660✔
3231
}
3232

3233
// This is invoked for remote LEAF connections after processing the INFO
3234
// protocol and leafNodeResumeConnectProcess.
3235
// This will send LS+ the CONNECT protocol and register the leaf node.
3236
func (s *Server) leafNodeFinishConnectProcess(c *client) {
626✔
3237
        c.mu.Lock()
626✔
3238
        if !c.flags.setIfNotSet(connectProcessFinished) {
626✔
3239
                c.mu.Unlock()
×
3240
                return
×
3241
        }
×
3242
        if c.isClosed() {
626✔
3243
                c.mu.Unlock()
×
3244
                s.removeLeafNodeConnection(c)
×
3245
                return
×
3246
        }
×
3247
        remote := c.leaf.remote
626✔
3248
        // Check if we will need to send the system connect event.
626✔
3249
        remote.RLock()
626✔
3250
        sendSysConnectEvent := remote.Hub
626✔
3251
        remote.RUnlock()
626✔
3252

626✔
3253
        // Capture account before releasing lock
626✔
3254
        acc := c.acc
626✔
3255
        // cancel connectProcessTimeout
626✔
3256
        clearTimer(&c.ping.tmr)
626✔
3257
        c.mu.Unlock()
626✔
3258

626✔
3259
        // Make sure we register with the account here.
626✔
3260
        if err := c.registerWithAccount(acc); err != nil {
628✔
3261
                if err == ErrTooManyAccountConnections {
2✔
3262
                        c.maxAccountConnExceeded()
×
3263
                        return
×
3264
                } else if err == ErrLeafNodeLoop {
4✔
3265
                        c.handleLeafNodeLoop(true)
2✔
3266
                        return
2✔
3267
                }
2✔
3268
                c.Errorf("Registering leaf with account %s resulted in error: %v", acc.Name, err)
×
3269
                c.closeConnection(ProtocolViolation)
×
3270
                return
×
3271
        }
3272
        s.addLeafNodeConnection(c, _EMPTY_, _EMPTY_, false)
624✔
3273
        s.initLeafNodeSmapAndSendSubs(c)
624✔
3274
        if sendSysConnectEvent {
630✔
3275
                s.sendLeafNodeConnect(acc)
6✔
3276
        }
6✔
3277

3278
        // The above functions are not atomically under the client
3279
        // lock doing those operations. It is possible - since we
3280
        // have started the read/write loops - that the connection
3281
        // is closed before or in between. This would leave the
3282
        // closed LN connection possible registered with the account
3283
        // and/or the server's leafs map. So check if connection
3284
        // is closed, and if so, manually cleanup.
3285
        c.mu.Lock()
624✔
3286
        closed := c.isClosed()
624✔
3287
        if !closed {
1,248✔
3288
                c.setFirstPingTimer()
624✔
3289
        }
624✔
3290
        c.mu.Unlock()
624✔
3291
        if closed {
624✔
3292
                s.removeLeafNodeConnection(c)
×
3293
                if prev := acc.removeClient(c); prev == 1 {
×
3294
                        s.decActiveAccounts()
×
3295
                }
×
3296
        }
3297
}
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