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

nats-io / nats-server / 16245493848

11 Jul 2025 02:02PM UTC coverage: 85.614% (-0.2%) from 85.783%
16245493848

push

github

web-flow
Fix lack of check for priority groups on push consumers (#7053)

Signed-off-by: Tomasz Pietrek <tomasz@synadia.com>

70866 of 82774 relevant lines covered (85.61%)

368340.5 hits per line

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

90.77
/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
        // Used to suppress sub and unsub interest. Same as routes but our audience
86
        // here is tied to this leaf node. This will hold all subscriptions except this
87
        // leaf nodes. This represents all the interest we want to send to the other side.
88
        smap map[string]int32
89
        // This map will contain all the subscriptions that have been added to the smap
90
        // during initLeafNodeSmapAndSendSubs. It is short lived and is there to avoid
91
        // race between processing of a sub where sub is added to account sublist but
92
        // updateSmap has not be called on that "thread", while in the LN readloop,
93
        // when processing CONNECT, initLeafNodeSmapAndSendSubs is invoked and add
94
        // this subscription to smap. When processing of the sub then calls updateSmap,
95
        // we would add it a second time in the smap causing later unsub to suppress the LS-.
96
        tsub  map[*subscription]struct{}
97
        tsubt *time.Timer
98
        // Selected compression mode, which may be different from the server configured mode.
99
        compression string
100
        // This is for GW map replies.
101
        gwSub *subscription
102
}
103

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

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

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

129
func (c *client) isHubLeafNode() bool {
17,494✔
130
        return c.kind == LEAF && !c.leaf.isSpoke
17,494✔
131
}
17,494✔
132

133
// This will spin up go routines to solicit the remote leaf node connections.
134
func (s *Server) solicitLeafNodeRemotes(remotes []*RemoteLeafOpts) {
549✔
135
        sysAccName := _EMPTY_
549✔
136
        sAcc := s.SystemAccount()
549✔
137
        if sAcc != nil {
1,075✔
138
                sysAccName = sAcc.Name
526✔
139
        }
526✔
140
        addRemote := func(r *RemoteLeafOpts, isSysAccRemote bool) *leafNodeCfg {
1,238✔
141
                s.mu.Lock()
689✔
142
                remote := newLeafNodeCfg(r)
689✔
143
                creds := remote.Credentials
689✔
144
                accName := remote.LocalAccount
689✔
145
                s.leafRemoteCfgs = append(s.leafRemoteCfgs, remote)
689✔
146
                // Print notice if
689✔
147
                if isSysAccRemote {
787✔
148
                        if len(remote.DenyExports) > 0 {
99✔
149
                                s.Noticef("Remote for System Account uses restricted export permissions")
1✔
150
                        }
1✔
151
                        if len(remote.DenyImports) > 0 {
99✔
152
                                s.Noticef("Remote for System Account uses restricted import permissions")
1✔
153
                        }
1✔
154
                }
155
                s.mu.Unlock()
689✔
156
                if creds != _EMPTY_ {
738✔
157
                        contents, err := os.ReadFile(creds)
49✔
158
                        defer wipeSlice(contents)
49✔
159
                        if err != nil {
49✔
160
                                s.Errorf("Error reading LeafNode Remote Credentials file %q: %v", creds, err)
×
161
                        } else if items := credsRe.FindAllSubmatch(contents, -1); len(items) < 2 {
49✔
162
                                s.Errorf("LeafNode Remote Credentials file %q malformed", creds)
×
163
                        } else if _, err := nkeys.FromSeed(items[1][1]); err != nil {
49✔
164
                                s.Errorf("LeafNode Remote Credentials file %q has malformed seed", creds)
×
165
                        } else if uc, err := jwt.DecodeUserClaims(string(items[0][1])); err != nil {
49✔
166
                                s.Errorf("LeafNode Remote Credentials file %q has malformed user jwt", creds)
×
167
                        } else if isSysAccRemote {
53✔
168
                                if !uc.Permissions.Pub.Empty() || !uc.Permissions.Sub.Empty() || uc.Permissions.Resp != nil {
5✔
169
                                        s.Noticef("LeafNode Remote for System Account uses credentials file %q with restricted permissions", creds)
1✔
170
                                }
1✔
171
                        } else {
45✔
172
                                if !uc.Permissions.Pub.Empty() || !uc.Permissions.Sub.Empty() || uc.Permissions.Resp != nil {
51✔
173
                                        s.Noticef("LeafNode Remote for Account %s uses credentials file %q with restricted permissions", accName, creds)
6✔
174
                                }
6✔
175
                        }
176
                }
177
                return remote
689✔
178
        }
179
        for _, r := range remotes {
1,238✔
180
                remote := addRemote(r, r.LocalAccount == sysAccName)
689✔
181
                s.startGoRoutine(func() { s.connectToRemoteLeafNode(remote, true) })
1,378✔
182
        }
183
}
184

185
func (s *Server) remoteLeafNodeStillValid(remote *leafNodeCfg) bool {
5,143✔
186
        for _, ri := range s.getOpts().LeafNode.Remotes {
10,646✔
187
                // FIXME(dlc) - What about auth changes?
5,503✔
188
                if reflect.DeepEqual(ri.URLs, remote.URLs) {
10,646✔
189
                        return true
5,143✔
190
                }
5,143✔
191
        }
192
        return false
×
193
}
194

195
// Ensure that leafnode is properly configured.
196
func validateLeafNode(o *Options) error {
8,254✔
197
        if err := validateLeafNodeAuthOptions(o); err != nil {
8,256✔
198
                return err
2✔
199
        }
2✔
200

201
        // Users can bind to any local account, if its empty we will assume the $G account.
202
        for _, r := range o.LeafNode.Remotes {
8,966✔
203
                if r.LocalAccount == _EMPTY_ {
1,142✔
204
                        r.LocalAccount = globalAccountName
428✔
205
                }
428✔
206
        }
207

208
        // In local config mode, check that leafnode configuration refers to accounts that exist.
209
        if len(o.TrustedOperators) == 0 {
16,191✔
210
                accNames := map[string]struct{}{}
7,939✔
211
                for _, a := range o.Accounts {
16,779✔
212
                        accNames[a.Name] = struct{}{}
8,840✔
213
                }
8,840✔
214
                // global account is always created
215
                accNames[DEFAULT_GLOBAL_ACCOUNT] = struct{}{}
7,939✔
216
                // in the context of leaf nodes, empty account means global account
7,939✔
217
                accNames[_EMPTY_] = struct{}{}
7,939✔
218
                // system account either exists or, if not disabled, will be created
7,939✔
219
                if o.SystemAccount == _EMPTY_ && !o.NoSystemAccount {
14,186✔
220
                        accNames[DEFAULT_SYSTEM_ACCOUNT] = struct{}{}
6,247✔
221
                }
6,247✔
222
                checkAccountExists := func(accName string, cfgType string) error {
16,598✔
223
                        if _, ok := accNames[accName]; !ok {
8,661✔
224
                                return fmt.Errorf("cannot find local account %q specified in leafnode %s", accName, cfgType)
2✔
225
                        }
2✔
226
                        return nil
8,657✔
227
                }
228
                if err := checkAccountExists(o.LeafNode.Account, "authorization"); err != nil {
7,940✔
229
                        return err
1✔
230
                }
1✔
231
                for _, lu := range o.LeafNode.Users {
7,948✔
232
                        if lu.Account == nil { // means global account
13✔
233
                                continue
3✔
234
                        }
235
                        if err := checkAccountExists(lu.Account.Name, "authorization"); err != nil {
7✔
236
                                return err
×
237
                        }
×
238
                }
239
                for _, r := range o.LeafNode.Remotes {
8,651✔
240
                        if err := checkAccountExists(r.LocalAccount, "remote"); err != nil {
714✔
241
                                return err
1✔
242
                        }
1✔
243
                }
244
        } else {
313✔
245
                if len(o.LeafNode.Users) != 0 {
314✔
246
                        return fmt.Errorf("operator mode does not allow specifying users in leafnode config")
1✔
247
                }
1✔
248
                for _, r := range o.LeafNode.Remotes {
313✔
249
                        if !nkeys.IsValidPublicAccountKey(r.LocalAccount) {
2✔
250
                                return fmt.Errorf(
1✔
251
                                        "operator mode requires account nkeys in remotes. " +
1✔
252
                                                "Please add an `account` key to each remote in your `leafnodes` section, to assign it to an account. " +
1✔
253
                                                "Each account value should be a 56 character public key, starting with the letter 'A'")
1✔
254
                        }
1✔
255
                }
256
                if o.LeafNode.Port != 0 && o.LeafNode.Account != "" && !nkeys.IsValidPublicAccountKey(o.LeafNode.Account) {
312✔
257
                        return fmt.Errorf("operator mode and non account nkeys are incompatible")
1✔
258
                }
1✔
259
        }
260

261
        // Validate compression settings
262
        if o.LeafNode.Compression.Mode != _EMPTY_ {
12,052✔
263
                if err := validateAndNormalizeCompressionOption(&o.LeafNode.Compression, CompressionS2Auto); err != nil {
3,810✔
264
                        return err
5✔
265
                }
5✔
266
        }
267

268
        // If a remote has a websocket scheme, all need to have it.
269
        for _, rcfg := range o.LeafNode.Remotes {
8,954✔
270
                if len(rcfg.URLs) >= 2 {
928✔
271
                        firstIsWS, ok := isWSURL(rcfg.URLs[0]), true
216✔
272
                        for i := 1; i < len(rcfg.URLs); i++ {
677✔
273
                                u := rcfg.URLs[i]
461✔
274
                                if isWS := isWSURL(u); isWS && !firstIsWS || !isWS && firstIsWS {
468✔
275
                                        ok = false
7✔
276
                                        break
7✔
277
                                }
278
                        }
279
                        if !ok {
223✔
280
                                return fmt.Errorf("remote leaf node configuration cannot have a mix of websocket and non-websocket urls: %q", redactURLList(rcfg.URLs))
7✔
281
                        }
7✔
282
                }
283
                // Validate compression settings
284
                if rcfg.Compression.Mode != _EMPTY_ {
1,410✔
285
                        if err := validateAndNormalizeCompressionOption(&rcfg.Compression, CompressionS2Auto); err != nil {
710✔
286
                                return err
5✔
287
                        }
5✔
288
                }
289
        }
290

291
        if o.LeafNode.Port == 0 {
13,253✔
292
                return nil
5,023✔
293
        }
5,023✔
294

295
        // If MinVersion is defined, check that it is valid.
296
        if mv := o.LeafNode.MinVersion; mv != _EMPTY_ {
3,211✔
297
                if err := checkLeafMinVersionConfig(mv); err != nil {
6✔
298
                        return err
2✔
299
                }
2✔
300
        }
301

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

306
        if o.Gateway.Name == _EMPTY_ && o.Gateway.Port == 0 {
5,726✔
307
                return nil
2,521✔
308
        }
2,521✔
309
        // If we are here we have both leaf nodes and gateways defined, make sure there
310
        // is a system account defined.
311
        if o.SystemAccount == _EMPTY_ {
685✔
312
                return fmt.Errorf("leaf nodes and gateways (both being defined) require a system account to also be configured")
1✔
313
        }
1✔
314
        if err := validatePinnedCerts(o.LeafNode.TLSPinnedCerts); err != nil {
683✔
315
                return fmt.Errorf("leafnode: %v", err)
×
316
        }
×
317
        return nil
683✔
318
}
319

320
func checkLeafMinVersionConfig(mv string) error {
8✔
321
        if ok, err := versionAtLeastCheckError(mv, 2, 8, 0); !ok || err != nil {
12✔
322
                if err != nil {
6✔
323
                        return fmt.Errorf("invalid leafnode's minimum version: %v", err)
2✔
324
                } else {
4✔
325
                        return fmt.Errorf("the minimum version should be at least 2.8.0")
2✔
326
                }
2✔
327
        }
328
        return nil
4✔
329
}
330

331
// Used to validate user names in LeafNode configuration.
332
// - rejects mix of single and multiple users.
333
// - rejects duplicate user names.
334
func validateLeafNodeAuthOptions(o *Options) error {
8,303✔
335
        if len(o.LeafNode.Users) == 0 {
16,586✔
336
                return nil
8,283✔
337
        }
8,283✔
338
        if o.LeafNode.Username != _EMPTY_ {
22✔
339
                return fmt.Errorf("can not have a single user/pass and a users array")
2✔
340
        }
2✔
341
        if o.LeafNode.Nkey != _EMPTY_ {
18✔
342
                return fmt.Errorf("can not have a single nkey and a users array")
×
343
        }
×
344
        users := map[string]struct{}{}
18✔
345
        for _, u := range o.LeafNode.Users {
42✔
346
                if _, exists := users[u.Username]; exists {
26✔
347
                        return fmt.Errorf("duplicate user %q detected in leafnode authorization", u.Username)
2✔
348
                }
2✔
349
                users[u.Username] = struct{}{}
22✔
350
        }
351
        return nil
16✔
352
}
353

354
// Update remote LeafNode TLS configurations after a config reload.
355
func (s *Server) updateRemoteLeafNodesTLSConfig(opts *Options) {
11✔
356
        max := len(opts.LeafNode.Remotes)
11✔
357
        if max == 0 {
11✔
358
                return
×
359
        }
×
360

361
        s.mu.RLock()
11✔
362
        defer s.mu.RUnlock()
11✔
363

11✔
364
        // Changes in the list of remote leaf nodes is not supported.
11✔
365
        // However, make sure that we don't go over the arrays.
11✔
366
        if len(s.leafRemoteCfgs) < max {
11✔
367
                max = len(s.leafRemoteCfgs)
×
368
        }
×
369
        for i := 0; i < max; i++ {
22✔
370
                ro := opts.LeafNode.Remotes[i]
11✔
371
                cfg := s.leafRemoteCfgs[i]
11✔
372
                if ro.TLSConfig != nil {
13✔
373
                        cfg.Lock()
2✔
374
                        cfg.TLSConfig = ro.TLSConfig.Clone()
2✔
375
                        cfg.TLSHandshakeFirst = ro.TLSHandshakeFirst
2✔
376
                        cfg.Unlock()
2✔
377
                }
2✔
378
        }
379
}
380

381
func (s *Server) reConnectToRemoteLeafNode(remote *leafNodeCfg) {
224✔
382
        delay := s.getOpts().LeafNode.ReconnectInterval
224✔
383
        select {
224✔
384
        case <-time.After(delay):
172✔
385
        case <-s.quitCh:
52✔
386
                s.grWG.Done()
52✔
387
                return
52✔
388
        }
389
        s.connectToRemoteLeafNode(remote, false)
172✔
390
}
391

392
// Creates a leafNodeCfg object that wraps the RemoteLeafOpts.
393
func newLeafNodeCfg(remote *RemoteLeafOpts) *leafNodeCfg {
689✔
394
        cfg := &leafNodeCfg{
689✔
395
                RemoteLeafOpts: remote,
689✔
396
                urls:           make([]*url.URL, 0, len(remote.URLs)),
689✔
397
        }
689✔
398
        if len(remote.DenyExports) > 0 || len(remote.DenyImports) > 0 {
697✔
399
                perms := &Permissions{}
8✔
400
                if len(remote.DenyExports) > 0 {
16✔
401
                        perms.Publish = &SubjectPermission{Deny: remote.DenyExports}
8✔
402
                }
8✔
403
                if len(remote.DenyImports) > 0 {
15✔
404
                        perms.Subscribe = &SubjectPermission{Deny: remote.DenyImports}
7✔
405
                }
7✔
406
                cfg.perms = perms
8✔
407
        }
408
        // Start with the one that is configured. We will add to this
409
        // array when receiving async leafnode INFOs.
410
        cfg.urls = append(cfg.urls, cfg.URLs...)
689✔
411
        // If allowed to randomize, do it on our copy of URLs
689✔
412
        if !remote.NoRandomize {
1,376✔
413
                rand.Shuffle(len(cfg.urls), func(i, j int) {
1,105✔
414
                        cfg.urls[i], cfg.urls[j] = cfg.urls[j], cfg.urls[i]
418✔
415
                })
418✔
416
        }
417
        // If we are TLS make sure we save off a proper servername if possible.
418
        // Do same for user/password since we may need them to connect to
419
        // a bare URL that we get from INFO protocol.
420
        for _, u := range cfg.urls {
1,826✔
421
                cfg.saveTLSHostname(u)
1,137✔
422
                cfg.saveUserPassword(u)
1,137✔
423
                // If the url(s) have the "wss://" scheme, and we don't have a TLS
1,137✔
424
                // config, mark that we should be using TLS anyway.
1,137✔
425
                if !cfg.TLS && isWSSURL(u) {
1,138✔
426
                        cfg.TLS = true
1✔
427
                }
1✔
428
        }
429
        return cfg
689✔
430
}
431

432
// Will pick an URL from the list of available URLs.
433
func (cfg *leafNodeCfg) pickNextURL() *url.URL {
4,385✔
434
        cfg.Lock()
4,385✔
435
        defer cfg.Unlock()
4,385✔
436
        // If the current URL is the first in the list and we have more than
4,385✔
437
        // one URL, then move that one to end of the list.
4,385✔
438
        if cfg.curURL != nil && len(cfg.urls) > 1 && urlsAreEqual(cfg.curURL, cfg.urls[0]) {
7,887✔
439
                first := cfg.urls[0]
3,502✔
440
                copy(cfg.urls, cfg.urls[1:])
3,502✔
441
                cfg.urls[len(cfg.urls)-1] = first
3,502✔
442
        }
3,502✔
443
        cfg.curURL = cfg.urls[0]
4,385✔
444
        return cfg.curURL
4,385✔
445
}
446

447
// Returns the current URL
448
func (cfg *leafNodeCfg) getCurrentURL() *url.URL {
75✔
449
        cfg.RLock()
75✔
450
        defer cfg.RUnlock()
75✔
451
        return cfg.curURL
75✔
452
}
75✔
453

454
// Returns how long the server should wait before attempting
455
// to solicit a remote leafnode connection.
456
func (cfg *leafNodeCfg) getConnectDelay() time.Duration {
861✔
457
        cfg.RLock()
861✔
458
        delay := cfg.connDelay
861✔
459
        cfg.RUnlock()
861✔
460
        return delay
861✔
461
}
861✔
462

463
// Sets the connect delay.
464
func (cfg *leafNodeCfg) setConnectDelay(delay time.Duration) {
158✔
465
        cfg.Lock()
158✔
466
        cfg.connDelay = delay
158✔
467
        cfg.Unlock()
158✔
468
}
158✔
469

470
// Ensure that non-exported options (used in tests) have
471
// been properly set.
472
func (s *Server) setLeafNodeNonExportedOptions() {
6,725✔
473
        opts := s.getOpts()
6,725✔
474
        s.leafNodeOpts.dialTimeout = opts.LeafNode.dialTimeout
6,725✔
475
        if s.leafNodeOpts.dialTimeout == 0 {
13,449✔
476
                // Use same timeouts as routes for now.
6,724✔
477
                s.leafNodeOpts.dialTimeout = DEFAULT_ROUTE_DIAL
6,724✔
478
        }
6,724✔
479
        s.leafNodeOpts.resolver = opts.LeafNode.resolver
6,725✔
480
        if s.leafNodeOpts.resolver == nil {
13,446✔
481
                s.leafNodeOpts.resolver = net.DefaultResolver
6,721✔
482
        }
6,721✔
483
}
484

485
const sharedSysAccDelay = 250 * time.Millisecond
486

487
func (s *Server) connectToRemoteLeafNode(remote *leafNodeCfg, firstConnect bool) {
861✔
488
        defer s.grWG.Done()
861✔
489

861✔
490
        if remote == nil || len(remote.URLs) == 0 {
861✔
491
                s.Debugf("Empty remote leafnode definition, nothing to connect")
×
492
                return
×
493
        }
×
494

495
        opts := s.getOpts()
861✔
496
        reconnectDelay := opts.LeafNode.ReconnectInterval
861✔
497
        s.mu.RLock()
861✔
498
        dialTimeout := s.leafNodeOpts.dialTimeout
861✔
499
        resolver := s.leafNodeOpts.resolver
861✔
500
        var isSysAcc bool
861✔
501
        if s.eventsEnabled() {
1,690✔
502
                isSysAcc = remote.LocalAccount == s.sys.account.Name
829✔
503
        }
829✔
504
        jetstreamMigrateDelay := remote.JetStreamClusterMigrateDelay
861✔
505
        s.mu.RUnlock()
861✔
506

861✔
507
        // If we are sharing a system account and we are not standalone delay to gather some info prior.
861✔
508
        if firstConnect && isSysAcc && !s.standAloneMode() {
936✔
509
                s.Debugf("Will delay first leafnode connect to shared system account due to clustering")
75✔
510
                remote.setConnectDelay(sharedSysAccDelay)
75✔
511
        }
75✔
512

513
        if connDelay := remote.getConnectDelay(); connDelay > 0 {
943✔
514
                select {
82✔
515
                case <-time.After(connDelay):
72✔
516
                case <-s.quitCh:
10✔
517
                        return
10✔
518
                }
519
                remote.setConnectDelay(0)
72✔
520
        }
521

522
        var conn net.Conn
851✔
523

851✔
524
        const connErrFmt = "Error trying to connect as leafnode to remote server %q (attempt %v): %v"
851✔
525

851✔
526
        attempts := 0
851✔
527

851✔
528
        for s.isRunning() && s.remoteLeafNodeStillValid(remote) {
5,236✔
529
                rURL := remote.pickNextURL()
4,385✔
530
                url, err := s.getRandomIP(resolver, rURL.Host, nil)
4,385✔
531
                if err == nil {
8,763✔
532
                        var ipStr string
4,378✔
533
                        if url != rURL.Host {
4,445✔
534
                                ipStr = fmt.Sprintf(" (%s)", url)
67✔
535
                        }
67✔
536
                        // Some test may want to disable remotes from connecting
537
                        if s.isLeafConnectDisabled() {
4,507✔
538
                                s.Debugf("Will not attempt to connect to remote server on %q%s, leafnodes currently disabled", rURL.Host, ipStr)
129✔
539
                                err = ErrLeafNodeDisabled
129✔
540
                        } else {
4,378✔
541
                                s.Debugf("Trying to connect as leafnode to remote server on %q%s", rURL.Host, ipStr)
4,249✔
542
                                conn, err = natsDialTimeout("tcp", url, dialTimeout)
4,249✔
543
                        }
4,249✔
544
                }
545
                if err != nil {
8,012✔
546
                        jitter := time.Duration(rand.Int63n(int64(reconnectDelay)))
3,627✔
547
                        delay := reconnectDelay + jitter
3,627✔
548
                        attempts++
3,627✔
549
                        if s.shouldReportConnectErr(firstConnect, attempts) {
7,241✔
550
                                s.Errorf(connErrFmt, rURL.Host, attempts, err)
3,614✔
551
                        } else {
3,627✔
552
                                s.Debugf(connErrFmt, rURL.Host, attempts, err)
13✔
553
                        }
13✔
554
                        remote.Lock()
3,627✔
555
                        // if we are using a delay to start migrating assets, kick off a migrate timer.
3,627✔
556
                        if remote.jsMigrateTimer == nil && jetstreamMigrateDelay > 0 {
3,635✔
557
                                remote.jsMigrateTimer = time.AfterFunc(jetstreamMigrateDelay, func() {
16✔
558
                                        s.checkJetStreamMigrate(remote)
8✔
559
                                })
8✔
560
                        }
561
                        remote.Unlock()
3,627✔
562
                        select {
3,627✔
563
                        case <-s.quitCh:
89✔
564
                                remote.cancelMigrateTimer()
89✔
565
                                return
89✔
566
                        case <-time.After(delay):
3,537✔
567
                                // Check if we should migrate any JetStream assets immediately while this remote is down.
3,537✔
568
                                // This will be used if JetStreamClusterMigrateDelay was not set
3,537✔
569
                                if jetstreamMigrateDelay == 0 {
7,001✔
570
                                        s.checkJetStreamMigrate(remote)
3,464✔
571
                                }
3,464✔
572
                                continue
3,537✔
573
                        }
574
                }
575
                remote.cancelMigrateTimer()
758✔
576
                if !s.remoteLeafNodeStillValid(remote) {
758✔
577
                        conn.Close()
×
578
                        return
×
579
                }
×
580

581
                // We have a connection here to a remote server.
582
                // Go ahead and create our leaf node and return.
583
                s.createLeafNode(conn, rURL, remote, nil)
758✔
584

758✔
585
                // Clear any observer states if we had them.
758✔
586
                s.clearObserverState(remote)
758✔
587

758✔
588
                return
758✔
589
        }
590
}
591

592
func (cfg *leafNodeCfg) cancelMigrateTimer() {
847✔
593
        cfg.Lock()
847✔
594
        stopAndClearTimer(&cfg.jsMigrateTimer)
847✔
595
        cfg.Unlock()
847✔
596
}
847✔
597

598
// This will clear any observer state such that stream or consumer assets on this server can become leaders again.
599
func (s *Server) clearObserverState(remote *leafNodeCfg) {
758✔
600
        s.mu.RLock()
758✔
601
        accName := remote.LocalAccount
758✔
602
        s.mu.RUnlock()
758✔
603

758✔
604
        acc, err := s.LookupAccount(accName)
758✔
605
        if err != nil {
760✔
606
                s.Warnf("Error looking up account [%s] checking for JetStream clear observer state on a leafnode", accName)
2✔
607
                return
2✔
608
        }
2✔
609

610
        acc.jscmMu.Lock()
756✔
611
        defer acc.jscmMu.Unlock()
756✔
612

756✔
613
        // Walk all streams looking for any clustered stream, skip otherwise.
756✔
614
        for _, mset := range acc.streams() {
774✔
615
                node := mset.raftNode()
18✔
616
                if node == nil {
28✔
617
                        // Not R>1
10✔
618
                        continue
10✔
619
                }
620
                // Check consumers
621
                for _, o := range mset.getConsumers() {
10✔
622
                        if n := o.raftNode(); n != nil {
4✔
623
                                // Ensure we can become a leader again.
2✔
624
                                n.SetObserver(false)
2✔
625
                        }
2✔
626
                }
627
                // Ensure we can not become a leader again.
628
                node.SetObserver(false)
8✔
629
        }
630
}
631

632
// Check to see if we should migrate any assets from this account.
633
func (s *Server) checkJetStreamMigrate(remote *leafNodeCfg) {
3,472✔
634
        s.mu.RLock()
3,472✔
635
        accName, shouldMigrate := remote.LocalAccount, remote.JetStreamClusterMigrate
3,472✔
636
        s.mu.RUnlock()
3,472✔
637

3,472✔
638
        if !shouldMigrate {
6,880✔
639
                return
3,408✔
640
        }
3,408✔
641

642
        acc, err := s.LookupAccount(accName)
64✔
643
        if err != nil {
64✔
644
                s.Warnf("Error looking up account [%s] checking for JetStream migration on a leafnode", accName)
×
645
                return
×
646
        }
×
647

648
        acc.jscmMu.Lock()
64✔
649
        defer acc.jscmMu.Unlock()
64✔
650

64✔
651
        // Walk all streams looking for any clustered stream, skip otherwise.
64✔
652
        // If we are the leader force stepdown.
64✔
653
        for _, mset := range acc.streams() {
96✔
654
                node := mset.raftNode()
32✔
655
                if node == nil {
32✔
656
                        // Not R>1
×
657
                        continue
×
658
                }
659
                // Collect any consumers
660
                for _, o := range mset.getConsumers() {
53✔
661
                        if n := o.raftNode(); n != nil {
42✔
662
                                n.StepDown()
21✔
663
                                // Ensure we can not become a leader while in this state.
21✔
664
                                n.SetObserver(true)
21✔
665
                        }
21✔
666
                }
667
                // Stepdown if this stream was leader.
668
                node.StepDown()
32✔
669
                // Ensure we can not become a leader while in this state.
32✔
670
                node.SetObserver(true)
32✔
671
        }
672
}
673

674
// Helper for checking.
675
func (s *Server) isLeafConnectDisabled() bool {
4,378✔
676
        s.mu.RLock()
4,378✔
677
        defer s.mu.RUnlock()
4,378✔
678
        return s.leafDisableConnect
4,378✔
679
}
4,378✔
680

681
// Save off the tlsName for when we use TLS and mix hostnames and IPs. IPs usually
682
// come from the server we connect to.
683
//
684
// We used to save the name only if there was a TLSConfig or scheme equal to "tls".
685
// However, this was causing failures for users that did not set the scheme (and
686
// their remote connections did not have a tls{} block).
687
// We now save the host name regardless in case the remote returns an INFO indicating
688
// that TLS is required.
689
func (cfg *leafNodeCfg) saveTLSHostname(u *url.URL) {
1,749✔
690
        if cfg.tlsName == _EMPTY_ && net.ParseIP(u.Hostname()) == nil {
1,769✔
691
                cfg.tlsName = u.Hostname()
20✔
692
        }
20✔
693
}
694

695
// Save off the username/password for when we connect using a bare URL
696
// that we get from the INFO protocol.
697
func (cfg *leafNodeCfg) saveUserPassword(u *url.URL) {
1,137✔
698
        if cfg.username == _EMPTY_ && u.User != nil {
1,403✔
699
                cfg.username = u.User.Username()
266✔
700
                cfg.password, _ = u.User.Password()
266✔
701
        }
266✔
702
}
703

704
// This starts the leafnode accept loop in a go routine, unless it
705
// is detected that the server has already been shutdown.
706
func (s *Server) startLeafNodeAcceptLoop() {
3,174✔
707
        // Snapshot server options.
3,174✔
708
        opts := s.getOpts()
3,174✔
709

3,174✔
710
        port := opts.LeafNode.Port
3,174✔
711
        if port == -1 {
6,196✔
712
                port = 0
3,022✔
713
        }
3,022✔
714

715
        if s.isShuttingDown() {
3,175✔
716
                return
1✔
717
        }
1✔
718

719
        s.mu.Lock()
3,173✔
720
        hp := net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(port))
3,173✔
721
        l, e := natsListen("tcp", hp)
3,173✔
722
        s.leafNodeListenerErr = e
3,173✔
723
        if e != nil {
3,173✔
724
                s.mu.Unlock()
×
725
                s.Fatalf("Error listening on leafnode port: %d - %v", opts.LeafNode.Port, e)
×
726
                return
×
727
        }
×
728

729
        s.Noticef("Listening for leafnode connections on %s",
3,173✔
730
                net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
3,173✔
731

3,173✔
732
        tlsRequired := opts.LeafNode.TLSConfig != nil
3,173✔
733
        tlsVerify := tlsRequired && opts.LeafNode.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert
3,173✔
734
        // Do not set compression in this Info object, it would possibly cause
3,173✔
735
        // issues when sending asynchronous INFO to the remote.
3,173✔
736
        info := Info{
3,173✔
737
                ID:            s.info.ID,
3,173✔
738
                Name:          s.info.Name,
3,173✔
739
                Version:       s.info.Version,
3,173✔
740
                GitCommit:     gitCommit,
3,173✔
741
                GoVersion:     runtime.Version(),
3,173✔
742
                AuthRequired:  true,
3,173✔
743
                TLSRequired:   tlsRequired,
3,173✔
744
                TLSVerify:     tlsVerify,
3,173✔
745
                MaxPayload:    s.info.MaxPayload, // TODO(dlc) - Allow override?
3,173✔
746
                Headers:       s.supportsHeaders(),
3,173✔
747
                JetStream:     opts.JetStream,
3,173✔
748
                Domain:        opts.JetStreamDomain,
3,173✔
749
                Proto:         s.getServerProto(),
3,173✔
750
                InfoOnConnect: true,
3,173✔
751
        }
3,173✔
752
        // If we have selected a random port...
3,173✔
753
        if port == 0 {
6,194✔
754
                // Write resolved port back to options.
3,021✔
755
                opts.LeafNode.Port = l.Addr().(*net.TCPAddr).Port
3,021✔
756
        }
3,021✔
757

758
        s.leafNodeInfo = info
3,173✔
759
        // Possibly override Host/Port and set IP based on Cluster.Advertise
3,173✔
760
        if err := s.setLeafNodeInfoHostPortAndIP(); err != nil {
3,173✔
761
                s.Fatalf("Error setting leafnode INFO with LeafNode.Advertise value of %s, err=%v", opts.LeafNode.Advertise, err)
×
762
                l.Close()
×
763
                s.mu.Unlock()
×
764
                return
×
765
        }
×
766
        s.leafURLsMap[s.leafNodeInfo.IP]++
3,173✔
767
        s.generateLeafNodeInfoJSON()
3,173✔
768

3,173✔
769
        // Setup state that can enable shutdown
3,173✔
770
        s.leafNodeListener = l
3,173✔
771

3,173✔
772
        // As of now, a server that does not have remotes configured would
3,173✔
773
        // never solicit a connection, so we should not have to warn if
3,173✔
774
        // InsecureSkipVerify is set in main LeafNodes config (since
3,173✔
775
        // this TLS setting matters only when soliciting a connection).
3,173✔
776
        // Still, warn if insecure is set in any of LeafNode block.
3,173✔
777
        // We need to check remotes, even if tls is not required on accept.
3,173✔
778
        warn := tlsRequired && opts.LeafNode.TLSConfig.InsecureSkipVerify
3,173✔
779
        if !warn {
6,342✔
780
                for _, r := range opts.LeafNode.Remotes {
3,326✔
781
                        if r.TLSConfig != nil && r.TLSConfig.InsecureSkipVerify {
158✔
782
                                warn = true
1✔
783
                                break
1✔
784
                        }
785
                }
786
        }
787
        if warn {
3,178✔
788
                s.Warnf(leafnodeTLSInsecureWarning)
5✔
789
        }
5✔
790
        go s.acceptConnections(l, "Leafnode", func(conn net.Conn) { s.createLeafNode(conn, nil, nil, nil) }, nil)
3,959✔
791
        s.mu.Unlock()
3,173✔
792
}
793

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

797
// clusterName is provided as argument to avoid lock ordering issues with the locked client c
798
// Lock should be held entering here.
799
func (c *client) sendLeafConnect(clusterName string, headers bool) error {
642✔
800
        // We support basic user/pass and operator based user JWT with signatures.
642✔
801
        cinfo := leafConnectInfo{
642✔
802
                Version:       VERSION,
642✔
803
                ID:            c.srv.info.ID,
642✔
804
                Domain:        c.srv.info.Domain,
642✔
805
                Name:          c.srv.info.Name,
642✔
806
                Hub:           c.leaf.remote.Hub,
642✔
807
                Cluster:       clusterName,
642✔
808
                Headers:       headers,
642✔
809
                JetStream:     c.acc.jetStreamConfigured(),
642✔
810
                DenyPub:       c.leaf.remote.DenyImports,
642✔
811
                Compression:   c.leaf.compression,
642✔
812
                RemoteAccount: c.acc.GetName(),
642✔
813
                Proto:         c.srv.getServerProto(),
642✔
814
        }
642✔
815

642✔
816
        // If a signature callback is specified, this takes precedence over anything else.
642✔
817
        if cb := c.leaf.remote.SignatureCB; cb != nil {
645✔
818
                nonce := c.nonce
3✔
819
                c.mu.Unlock()
3✔
820
                jwt, sigraw, err := cb(nonce)
3✔
821
                c.mu.Lock()
3✔
822
                if err == nil && c.isClosed() {
4✔
823
                        err = ErrConnectionClosed
1✔
824
                }
1✔
825
                if err != nil {
5✔
826
                        c.Errorf("Error signing the nonce: %v", err)
2✔
827
                        return err
2✔
828
                }
2✔
829
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
1✔
830
                cinfo.JWT, cinfo.Sig = jwt, sig
1✔
831

832
        } else if creds := c.leaf.remote.Credentials; creds != _EMPTY_ {
690✔
833
                // Check for credentials first, that will take precedence..
51✔
834
                c.Debugf("Authenticating with credentials file %q", c.leaf.remote.Credentials)
51✔
835
                contents, err := os.ReadFile(creds)
51✔
836
                if err != nil {
51✔
837
                        c.Errorf("%v", err)
×
838
                        return err
×
839
                }
×
840
                defer wipeSlice(contents)
51✔
841
                items := credsRe.FindAllSubmatch(contents, -1)
51✔
842
                if len(items) < 2 {
51✔
843
                        c.Errorf("Credentials file malformed")
×
844
                        return err
×
845
                }
×
846
                // First result should be the user JWT.
847
                // We copy here so that the file containing the seed will be wiped appropriately.
848
                raw := items[0][1]
51✔
849
                tmp := make([]byte, len(raw))
51✔
850
                copy(tmp, raw)
51✔
851
                // Seed is second item.
51✔
852
                kp, err := nkeys.FromSeed(items[1][1])
51✔
853
                if err != nil {
51✔
854
                        c.Errorf("Credentials file has malformed seed")
×
855
                        return err
×
856
                }
×
857
                // Wipe our key on exit.
858
                defer kp.Wipe()
51✔
859

51✔
860
                sigraw, _ := kp.Sign(c.nonce)
51✔
861
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
51✔
862
                cinfo.JWT = bytesToString(tmp)
51✔
863
                cinfo.Sig = sig
51✔
864
        } else if nkey := c.leaf.remote.Nkey; nkey != _EMPTY_ {
590✔
865
                kp, err := nkeys.FromSeed([]byte(nkey))
2✔
866
                if err != nil {
2✔
867
                        c.Errorf("Remote nkey has malformed seed")
×
868
                        return err
×
869
                }
×
870
                // Wipe our key on exit.
871
                defer kp.Wipe()
2✔
872
                sigraw, _ := kp.Sign(c.nonce)
2✔
873
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
2✔
874
                pkey, _ := kp.PublicKey()
2✔
875
                cinfo.Nkey = pkey
2✔
876
                cinfo.Sig = sig
2✔
877
        }
878
        // In addition, and this is to allow auth callout, set user/password or
879
        // token if applicable.
880
        if userInfo := c.leaf.remote.curURL.User; userInfo != nil {
922✔
881
                // For backward compatibility, if only username is provided, set both
282✔
882
                // Token and User, not just Token.
282✔
883
                cinfo.User = userInfo.Username()
282✔
884
                var ok bool
282✔
885
                cinfo.Pass, ok = userInfo.Password()
282✔
886
                if !ok {
288✔
887
                        cinfo.Token = cinfo.User
6✔
888
                }
6✔
889
        } else if c.leaf.remote.username != _EMPTY_ {
362✔
890
                cinfo.User = c.leaf.remote.username
4✔
891
                cinfo.Pass = c.leaf.remote.password
4✔
892
        }
4✔
893
        b, err := json.Marshal(cinfo)
640✔
894
        if err != nil {
640✔
895
                c.Errorf("Error marshaling CONNECT to remote leafnode: %v\n", err)
×
896
                return err
×
897
        }
×
898
        // Although this call is made before the writeLoop is created,
899
        // we don't really need to send in place. The protocol will be
900
        // sent out by the writeLoop.
901
        c.enqueueProto([]byte(fmt.Sprintf(ConProto, b)))
640✔
902
        return nil
640✔
903
}
904

905
// Makes a deep copy of the LeafNode Info structure.
906
// The server lock is held on entry.
907
func (s *Server) copyLeafNodeInfo() *Info {
2,564✔
908
        clone := s.leafNodeInfo
2,564✔
909
        // Copy the array of urls.
2,564✔
910
        if len(s.leafNodeInfo.LeafNodeURLs) > 0 {
4,653✔
911
                clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...)
2,089✔
912
        }
2,089✔
913
        return &clone
2,564✔
914
}
915

916
// Adds a LeafNode URL that we get when a route connects to the Info structure.
917
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
918
// Returns a boolean indicating if the URL was added or not.
919
// Server lock is held on entry
920
func (s *Server) addLeafNodeURL(urlStr string) bool {
6,331✔
921
        if s.leafURLsMap.addUrl(urlStr) {
12,657✔
922
                s.generateLeafNodeInfoJSON()
6,326✔
923
                return true
6,326✔
924
        }
6,326✔
925
        return false
5✔
926
}
927

928
// Removes a LeafNode URL of the route that is disconnecting from the Info structure.
929
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
930
// Returns a boolean indicating if the URL was removed or not.
931
// Server lock is held on entry.
932
func (s *Server) removeLeafNodeURL(urlStr string) bool {
6,331✔
933
        // Don't need to do this if we are removing the route connection because
6,331✔
934
        // we are shuting down...
6,331✔
935
        if s.isShuttingDown() {
9,651✔
936
                return false
3,320✔
937
        }
3,320✔
938
        if s.leafURLsMap.removeUrl(urlStr) {
6,018✔
939
                s.generateLeafNodeInfoJSON()
3,007✔
940
                return true
3,007✔
941
        }
3,007✔
942
        return false
4✔
943
}
944

945
// Server lock is held on entry
946
func (s *Server) generateLeafNodeInfoJSON() {
12,506✔
947
        s.leafNodeInfo.Cluster = s.cachedClusterName()
12,506✔
948
        s.leafNodeInfo.LeafNodeURLs = s.leafURLsMap.getAsStringSlice()
12,506✔
949
        s.leafNodeInfo.WSConnectURLs = s.websocket.connectURLsMap.getAsStringSlice()
12,506✔
950
        s.leafNodeInfoJSON = generateInfoJSON(&s.leafNodeInfo)
12,506✔
951
}
12,506✔
952

953
// Sends an async INFO protocol so that the connected servers can update
954
// their list of LeafNode urls.
955
func (s *Server) sendAsyncLeafNodeInfo() {
9,333✔
956
        for _, c := range s.leafs {
9,434✔
957
                c.mu.Lock()
101✔
958
                c.enqueueProto(s.leafNodeInfoJSON)
101✔
959
                c.mu.Unlock()
101✔
960
        }
101✔
961
}
962

963
// Called when an inbound leafnode connection is accepted or we create one for a solicited leafnode.
964
func (s *Server) createLeafNode(conn net.Conn, rURL *url.URL, remote *leafNodeCfg, ws *websocket) *client {
1,571✔
965
        // Snapshot server options.
1,571✔
966
        opts := s.getOpts()
1,571✔
967

1,571✔
968
        maxPay := int32(opts.MaxPayload)
1,571✔
969
        maxSubs := int32(opts.MaxSubs)
1,571✔
970
        // For system, maxSubs of 0 means unlimited, so re-adjust here.
1,571✔
971
        if maxSubs == 0 {
3,141✔
972
                maxSubs = -1
1,570✔
973
        }
1,570✔
974
        now := time.Now().UTC()
1,571✔
975

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

1,571✔
980
        // For accepted LN connections, ws will be != nil if it was accepted
1,571✔
981
        // through the Websocket port.
1,571✔
982
        c.ws = ws
1,571✔
983

1,571✔
984
        // For remote, check if the scheme starts with "ws", if so, we will initiate
1,571✔
985
        // a remote Leaf Node connection as a websocket connection.
1,571✔
986
        if remote != nil && rURL != nil && isWSURL(rURL) {
1,614✔
987
                remote.RLock()
43✔
988
                c.ws = &websocket{compress: remote.Websocket.Compression, maskwrite: !remote.Websocket.NoMasking}
43✔
989
                remote.RUnlock()
43✔
990
        }
43✔
991

992
        // Determines if we are soliciting the connection or not.
993
        var solicited bool
1,571✔
994
        var acc *Account
1,571✔
995
        var remoteSuffix string
1,571✔
996
        if remote != nil {
2,329✔
997
                // For now, if lookup fails, we will constantly try
758✔
998
                // to recreate this LN connection.
758✔
999
                lacc := remote.LocalAccount
758✔
1000
                var err error
758✔
1001
                acc, err = s.LookupAccount(lacc)
758✔
1002
                if err != nil {
760✔
1003
                        // An account not existing is something that can happen with nats/http account resolver and the account
2✔
1004
                        // has not yet been pushed, or the request failed for other reasons.
2✔
1005
                        // remote needs to be set or retry won't happen
2✔
1006
                        c.leaf.remote = remote
2✔
1007
                        c.closeConnection(MissingAccount)
2✔
1008
                        s.Errorf("Unable to lookup account %s for solicited leafnode connection: %v", lacc, err)
2✔
1009
                        return nil
2✔
1010
                }
2✔
1011
                remoteSuffix = fmt.Sprintf(" for account: %s", acc.traceLabel())
756✔
1012
        }
1013

1014
        c.mu.Lock()
1,569✔
1015
        c.initClient()
1,569✔
1016
        c.Noticef("Leafnode connection created%s %s", remoteSuffix, c.opts.Name)
1,569✔
1017

1,569✔
1018
        var (
1,569✔
1019
                tlsFirst         bool
1,569✔
1020
                tlsFirstFallback time.Duration
1,569✔
1021
                infoTimeout      time.Duration
1,569✔
1022
        )
1,569✔
1023
        if remote != nil {
2,325✔
1024
                solicited = true
756✔
1025
                remote.Lock()
756✔
1026
                c.leaf.remote = remote
756✔
1027
                c.setPermissions(remote.perms)
756✔
1028
                if !c.leaf.remote.Hub {
1,506✔
1029
                        c.leaf.isSpoke = true
750✔
1030
                }
750✔
1031
                tlsFirst = remote.TLSHandshakeFirst
756✔
1032
                infoTimeout = remote.FirstInfoTimeout
756✔
1033
                remote.Unlock()
756✔
1034
                c.acc = acc
756✔
1035
        } else {
813✔
1036
                c.flags.set(expectConnect)
813✔
1037
                if ws != nil {
840✔
1038
                        c.Debugf("Leafnode compression=%v", c.ws.compress)
27✔
1039
                }
27✔
1040
                tlsFirst = opts.LeafNode.TLSHandshakeFirst
813✔
1041
                if f := opts.LeafNode.TLSHandshakeFirstFallback; f > 0 {
814✔
1042
                        tlsFirstFallback = f
1✔
1043
                }
1✔
1044
        }
1045
        c.mu.Unlock()
1,569✔
1046

1,569✔
1047
        var nonce [nonceLen]byte
1,569✔
1048
        var info *Info
1,569✔
1049

1,569✔
1050
        // Grab this before the client lock below.
1,569✔
1051
        if !solicited {
2,382✔
1052
                // Grab server variables
813✔
1053
                s.mu.Lock()
813✔
1054
                info = s.copyLeafNodeInfo()
813✔
1055
                // For tests that want to simulate old servers, do not set the compression
813✔
1056
                // on the INFO protocol if configured with CompressionNotSupported.
813✔
1057
                if cm := opts.LeafNode.Compression.Mode; cm != CompressionNotSupported {
1,625✔
1058
                        info.Compression = cm
812✔
1059
                }
812✔
1060
                s.generateNonce(nonce[:])
813✔
1061
                s.mu.Unlock()
813✔
1062
        }
1063

1064
        // Grab lock
1065
        c.mu.Lock()
1,569✔
1066

1,569✔
1067
        var preBuf []byte
1,569✔
1068
        if solicited {
2,325✔
1069
                // For websocket connection, we need to send an HTTP request,
756✔
1070
                // and get the response before starting the readLoop to get
756✔
1071
                // the INFO, etc..
756✔
1072
                if c.isWebsocket() {
799✔
1073
                        var err error
43✔
1074
                        var closeReason ClosedState
43✔
1075

43✔
1076
                        preBuf, closeReason, err = c.leafNodeSolicitWSConnection(opts, rURL, remote)
43✔
1077
                        if err != nil {
59✔
1078
                                c.Errorf("Error soliciting websocket connection: %v", err)
16✔
1079
                                c.mu.Unlock()
16✔
1080
                                if closeReason != 0 {
28✔
1081
                                        c.closeConnection(closeReason)
12✔
1082
                                }
12✔
1083
                                return nil
16✔
1084
                        }
1085
                } else {
713✔
1086
                        // If configured to do TLS handshake first
713✔
1087
                        if tlsFirst {
717✔
1088
                                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
5✔
1089
                                        c.mu.Unlock()
1✔
1090
                                        return nil
1✔
1091
                                }
1✔
1092
                        }
1093
                        // We need to wait for the info, but not for too long.
1094
                        c.nc.SetReadDeadline(time.Now().Add(infoTimeout))
712✔
1095
                }
1096

1097
                // We will process the INFO from the readloop and finish by
1098
                // sending the CONNECT and finish registration later.
1099
        } else {
813✔
1100
                // Send our info to the other side.
813✔
1101
                // Remember the nonce we sent here for signatures, etc.
813✔
1102
                c.nonce = make([]byte, nonceLen)
813✔
1103
                copy(c.nonce, nonce[:])
813✔
1104
                info.Nonce = bytesToString(c.nonce)
813✔
1105
                info.CID = c.cid
813✔
1106
                proto := generateInfoJSON(info)
813✔
1107

813✔
1108
                var pre []byte
813✔
1109
                // We need first to check for "TLS First" fallback delay.
813✔
1110
                if tlsFirstFallback > 0 {
814✔
1111
                        // We wait and see if we are getting any data. Since we did not send
1✔
1112
                        // the INFO protocol yet, only clients that use TLS first should be
1✔
1113
                        // sending data (the TLS handshake). We don't really check the content:
1✔
1114
                        // if it is a rogue agent and not an actual client performing the
1✔
1115
                        // TLS handshake, the error will be detected when performing the
1✔
1116
                        // handshake on our side.
1✔
1117
                        pre = make([]byte, 4)
1✔
1118
                        c.nc.SetReadDeadline(time.Now().Add(tlsFirstFallback))
1✔
1119
                        n, _ := io.ReadFull(c.nc, pre[:])
1✔
1120
                        c.nc.SetReadDeadline(time.Time{})
1✔
1121
                        // If we get any data (regardless of possible timeout), we will proceed
1✔
1122
                        // with the TLS handshake.
1✔
1123
                        if n > 0 {
1✔
1124
                                pre = pre[:n]
×
1125
                        } else {
1✔
1126
                                // We did not get anything so we will send the INFO protocol.
1✔
1127
                                pre = nil
1✔
1128
                                // Set the boolean to false for the rest of the function.
1✔
1129
                                tlsFirst = false
1✔
1130
                        }
1✔
1131
                }
1132

1133
                if !tlsFirst {
1,621✔
1134
                        // We have to send from this go routine because we may
808✔
1135
                        // have to block for TLS handshake before we start our
808✔
1136
                        // writeLoop go routine. The other side needs to receive
808✔
1137
                        // this before it can initiate the TLS handshake..
808✔
1138
                        c.sendProtoNow(proto)
808✔
1139

808✔
1140
                        // The above call could have marked the connection as closed (due to TCP error).
808✔
1141
                        if c.isClosed() {
808✔
1142
                                c.mu.Unlock()
×
1143
                                c.closeConnection(WriteError)
×
1144
                                return nil
×
1145
                        }
×
1146
                }
1147

1148
                // Check to see if we need to spin up TLS.
1149
                if !c.isWebsocket() && info.TLSRequired {
881✔
1150
                        // If we have a prebuffer create a multi-reader.
68✔
1151
                        if len(pre) > 0 {
68✔
1152
                                c.nc = &tlsMixConn{c.nc, bytes.NewBuffer(pre)}
×
1153
                        }
×
1154
                        // Perform server-side TLS handshake.
1155
                        if err := c.doTLSServerHandshake(tlsHandshakeLeaf, opts.LeafNode.TLSConfig, opts.LeafNode.TLSTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
108✔
1156
                                c.mu.Unlock()
40✔
1157
                                return nil
40✔
1158
                        }
40✔
1159
                }
1160

1161
                // If the user wants the TLS handshake to occur first, now that it is
1162
                // done, send the INFO protocol.
1163
                if tlsFirst {
776✔
1164
                        c.flags.set(didTLSFirst)
3✔
1165
                        c.sendProtoNow(proto)
3✔
1166
                        if c.isClosed() {
3✔
1167
                                c.mu.Unlock()
×
1168
                                c.closeConnection(WriteError)
×
1169
                                return nil
×
1170
                        }
×
1171
                }
1172

1173
                // Leaf nodes will always require a CONNECT to let us know
1174
                // when we are properly bound to an account.
1175
                //
1176
                // If compression is configured, we can't set the authTimer here because
1177
                // it would cause the parser to fail any incoming protocol that is not a
1178
                // CONNECT (and we need to exchange INFO protocols for compression
1179
                // negotiation). So instead, use the ping timer until we are done with
1180
                // negotiation and can set the auth timer.
1181
                timeout := secondsToDuration(opts.LeafNode.AuthTimeout)
773✔
1182
                if needsCompression(opts.LeafNode.Compression.Mode) {
1,339✔
1183
                        c.ping.tmr = time.AfterFunc(timeout, func() {
576✔
1184
                                c.authTimeout()
10✔
1185
                        })
10✔
1186
                } else {
207✔
1187
                        c.setAuthTimer(timeout)
207✔
1188
                }
207✔
1189
        }
1190

1191
        // Keep track in case server is shutdown before we can successfully register.
1192
        if !s.addToTempClients(c.cid, c) {
1,513✔
1193
                c.mu.Unlock()
1✔
1194
                c.setNoReconnect()
1✔
1195
                c.closeConnection(ServerShutdown)
1✔
1196
                return nil
1✔
1197
        }
1✔
1198

1199
        // Spin up the read loop.
1200
        s.startGoRoutine(func() { c.readLoop(preBuf) })
3,022✔
1201

1202
        // We will spin the write loop for solicited connections only
1203
        // when processing the INFO and after switching to TLS if needed.
1204
        if !solicited {
2,284✔
1205
                s.startGoRoutine(func() { c.writeLoop() })
1,546✔
1206
        }
1207

1208
        c.mu.Unlock()
1,511✔
1209

1,511✔
1210
        return c
1,511✔
1211
}
1212

1213
// Will perform the client-side TLS handshake if needed. Assumes that this
1214
// is called by the solicit side (remote will be non nil). Returns `true`
1215
// if TLS is required, `false` otherwise.
1216
// Lock held on entry.
1217
func (c *client) leafClientHandshakeIfNeeded(remote *leafNodeCfg, opts *Options) (bool, error) {
1,835✔
1218
        // Check if TLS is required and gather TLS config variables.
1,835✔
1219
        tlsRequired, tlsConfig, tlsName, tlsTimeout := c.leafNodeGetTLSConfigForSolicit(remote)
1,835✔
1220
        if !tlsRequired {
3,595✔
1221
                return false, nil
1,760✔
1222
        }
1,760✔
1223

1224
        // If TLS required, peform handshake.
1225
        // Get the URL that was used to connect to the remote server.
1226
        rURL := remote.getCurrentURL()
75✔
1227

75✔
1228
        // Perform the client-side TLS handshake.
75✔
1229
        if resetTLSName, err := c.doTLSClientHandshake(tlsHandshakeLeaf, rURL, tlsConfig, tlsName, tlsTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
108✔
1230
                // Check if we need to reset the remote's TLS name.
33✔
1231
                if resetTLSName {
33✔
1232
                        remote.Lock()
×
1233
                        remote.tlsName = _EMPTY_
×
1234
                        remote.Unlock()
×
1235
                }
×
1236
                return false, err
33✔
1237
        }
1238
        return true, nil
42✔
1239
}
1240

1241
func (c *client) processLeafnodeInfo(info *Info) {
2,541✔
1242
        c.mu.Lock()
2,541✔
1243
        if c.leaf == nil || c.isClosed() {
2,542✔
1244
                c.mu.Unlock()
1✔
1245
                return
1✔
1246
        }
1✔
1247
        s := c.srv
2,540✔
1248
        opts := s.getOpts()
2,540✔
1249
        remote := c.leaf.remote
2,540✔
1250
        didSolicit := remote != nil
2,540✔
1251
        firstINFO := !c.flags.isSet(infoReceived)
2,540✔
1252

2,540✔
1253
        // In case of websocket, the TLS handshake has been already done.
2,540✔
1254
        // So check only for non websocket connections and for configurations
2,540✔
1255
        // where the TLS Handshake was not done first.
2,540✔
1256
        if didSolicit && !c.flags.isSet(handshakeComplete) && !c.isWebsocket() && !remote.TLSHandshakeFirst {
4,328✔
1257
                // If the server requires TLS, we need to set this in the remote
1,788✔
1258
                // otherwise if there is no TLS configuration block for the remote,
1,788✔
1259
                // the solicit side will not attempt to perform the TLS handshake.
1,788✔
1260
                if firstINFO && info.TLSRequired {
1,847✔
1261
                        remote.TLS = true
59✔
1262
                }
59✔
1263
                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
1,816✔
1264
                        c.mu.Unlock()
28✔
1265
                        return
28✔
1266
                }
28✔
1267
        }
1268

1269
        // Check for compression, unless already done.
1270
        if firstINFO && !c.flags.isSet(compressionNegotiated) {
3,749✔
1271
                // Prevent from getting back here.
1,237✔
1272
                c.flags.set(compressionNegotiated)
1,237✔
1273

1,237✔
1274
                var co *CompressionOpts
1,237✔
1275
                if !didSolicit {
1,777✔
1276
                        co = &opts.LeafNode.Compression
540✔
1277
                } else {
1,237✔
1278
                        co = &remote.Compression
697✔
1279
                }
697✔
1280
                if needsCompression(co.Mode) {
2,463✔
1281
                        // Release client lock since following function will need server lock.
1,226✔
1282
                        c.mu.Unlock()
1,226✔
1283
                        compress, err := s.negotiateLeafCompression(c, didSolicit, info.Compression, co)
1,226✔
1284
                        if err != nil {
1,226✔
1285
                                c.sendErrAndErr(err.Error())
×
1286
                                c.closeConnection(ProtocolViolation)
×
1287
                                return
×
1288
                        }
×
1289
                        if compress {
2,323✔
1290
                                // Done for now, will get back another INFO protocol...
1,097✔
1291
                                return
1,097✔
1292
                        }
1,097✔
1293
                        // No compression because one side does not want/can't, so proceed.
1294
                        c.mu.Lock()
129✔
1295
                        // Check that the connection did not close if the lock was released.
129✔
1296
                        if c.isClosed() {
129✔
1297
                                c.mu.Unlock()
×
1298
                                return
×
1299
                        }
×
1300
                } else {
11✔
1301
                        // Coming from an old server, the Compression field would be the empty
11✔
1302
                        // string. For servers that are configured with CompressionNotSupported,
11✔
1303
                        // this makes them behave as old servers.
11✔
1304
                        if info.Compression == _EMPTY_ || co.Mode == CompressionNotSupported {
14✔
1305
                                c.leaf.compression = CompressionNotSupported
3✔
1306
                        } else {
11✔
1307
                                c.leaf.compression = CompressionOff
8✔
1308
                        }
8✔
1309
                }
1310
                // Accepting side does not normally process an INFO protocol during
1311
                // initial connection handshake. So we keep it consistent by returning
1312
                // if we are not soliciting.
1313
                if !didSolicit {
141✔
1314
                        // If we had created the ping timer instead of the auth timer, we will
1✔
1315
                        // clear the ping timer and set the auth timer now that the compression
1✔
1316
                        // negotiation is done.
1✔
1317
                        if info.Compression != _EMPTY_ && c.ping.tmr != nil {
1✔
1318
                                clearTimer(&c.ping.tmr)
×
1319
                                c.setAuthTimer(secondsToDuration(opts.LeafNode.AuthTimeout))
×
1320
                        }
×
1321
                        c.mu.Unlock()
1✔
1322
                        return
1✔
1323
                }
1324
                // Fall through and process the INFO protocol as usual.
1325
        }
1326

1327
        // Note: For now, only the initial INFO has a nonce. We
1328
        // will probably do auto key rotation at some point.
1329
        if firstINFO {
2,150✔
1330
                // Mark that the INFO protocol has been received.
736✔
1331
                c.flags.set(infoReceived)
736✔
1332
                // Prevent connecting to non leafnode port. Need to do this only for
736✔
1333
                // the first INFO, not for async INFO updates...
736✔
1334
                //
736✔
1335
                // Content of INFO sent by the server when accepting a tcp connection.
736✔
1336
                // -------------------------------------------------------------------
736✔
1337
                // Listen Port Of | CID | ClientConnectURLs | LeafNodeURLs | Gateway |
736✔
1338
                // -------------------------------------------------------------------
736✔
1339
                //      CLIENT    |  X* |        X**        |              |         |
736✔
1340
                //      ROUTE     |     |        X**        |      X***    |         |
736✔
1341
                //     GATEWAY    |     |                   |              |    X    |
736✔
1342
                //     LEAFNODE   |  X  |                   |       X      |         |
736✔
1343
                // -------------------------------------------------------------------
736✔
1344
                // *   Not on older servers.
736✔
1345
                // **  Not if "no advertise" is enabled.
736✔
1346
                // *** Not if leafnode's "no advertise" is enabled.
736✔
1347
                //
736✔
1348
                // As seen from above, a solicited LeafNode connection should receive
736✔
1349
                // from the remote server an INFO with CID and LeafNodeURLs. Anything
736✔
1350
                // else should be considered an attempt to connect to a wrong port.
736✔
1351
                if didSolicit && (info.CID == 0 || info.LeafNodeURLs == nil) {
788✔
1352
                        c.mu.Unlock()
52✔
1353
                        c.Errorf(ErrConnectedToWrongPort.Error())
52✔
1354
                        c.closeConnection(WrongPort)
52✔
1355
                        return
52✔
1356
                }
52✔
1357
                // Reject a cluster that contains spaces.
1358
                if info.Cluster != _EMPTY_ && strings.Contains(info.Cluster, " ") {
685✔
1359
                        c.mu.Unlock()
1✔
1360
                        c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
1361
                        c.closeConnection(ProtocolViolation)
1✔
1362
                        return
1✔
1363
                }
1✔
1364
                // Capture a nonce here.
1365
                c.nonce = []byte(info.Nonce)
683✔
1366
                if info.TLSRequired && didSolicit {
714✔
1367
                        remote.TLS = true
31✔
1368
                }
31✔
1369
                supportsHeaders := c.srv.supportsHeaders()
683✔
1370
                c.headers = supportsHeaders && info.Headers
683✔
1371

683✔
1372
                // Remember the remote server.
683✔
1373
                // Pre 2.2.0 servers are not sending their server name.
683✔
1374
                // In that case, use info.ID, which, for those servers, matches
683✔
1375
                // the content of the field `Name` in the leafnode CONNECT protocol.
683✔
1376
                if info.Name == _EMPTY_ {
683✔
1377
                        c.leaf.remoteServer = info.ID
×
1378
                } else {
683✔
1379
                        c.leaf.remoteServer = info.Name
683✔
1380
                }
683✔
1381
                c.leaf.remoteDomain = info.Domain
683✔
1382
                c.leaf.remoteCluster = info.Cluster
683✔
1383
                // We send the protocol version in the INFO protocol.
683✔
1384
                // Keep track of it, so we know if this connection supports message
683✔
1385
                // tracing for instance.
683✔
1386
                c.opts.Protocol = info.Proto
683✔
1387
        }
1388

1389
        // For both initial INFO and async INFO protocols, Possibly
1390
        // update our list of remote leafnode URLs we can connect to.
1391
        if didSolicit && (len(info.LeafNodeURLs) > 0 || len(info.WSConnectURLs) > 0) {
2,635✔
1392
                // Consider the incoming array as the most up-to-date
1,274✔
1393
                // representation of the remote cluster's list of URLs.
1,274✔
1394
                c.updateLeafNodeURLs(info)
1,274✔
1395
        }
1,274✔
1396

1397
        // Check to see if we have permissions updates here.
1398
        if info.Import != nil || info.Export != nil {
1,373✔
1399
                perms := &Permissions{
12✔
1400
                        Publish:   info.Export,
12✔
1401
                        Subscribe: info.Import,
12✔
1402
                }
12✔
1403
                // Check if we have local deny clauses that we need to merge.
12✔
1404
                if remote := c.leaf.remote; remote != nil {
24✔
1405
                        if len(remote.DenyExports) > 0 {
13✔
1406
                                if perms.Publish == nil {
1✔
1407
                                        perms.Publish = &SubjectPermission{}
×
1408
                                }
×
1409
                                perms.Publish.Deny = append(perms.Publish.Deny, remote.DenyExports...)
1✔
1410
                        }
1411
                        if len(remote.DenyImports) > 0 {
13✔
1412
                                if perms.Subscribe == nil {
1✔
1413
                                        perms.Subscribe = &SubjectPermission{}
×
1414
                                }
×
1415
                                perms.Subscribe.Deny = append(perms.Subscribe.Deny, remote.DenyImports...)
1✔
1416
                        }
1417
                }
1418
                c.setPermissions(perms)
12✔
1419
        }
1420

1421
        var resumeConnect, checkSyncConsumers bool
1,361✔
1422

1,361✔
1423
        // If this is a remote connection and this is the first INFO protocol,
1,361✔
1424
        // then we need to finish the connect process by sending CONNECT, etc..
1,361✔
1425
        if firstINFO && didSolicit {
2,003✔
1426
                // Clear deadline that was set in createLeafNode while waiting for the INFO.
642✔
1427
                c.nc.SetDeadline(time.Time{})
642✔
1428
                resumeConnect = true
642✔
1429
        } else if !firstINFO && didSolicit {
1,993✔
1430
                c.leaf.remoteAccName = info.RemoteAccount
632✔
1431
                checkSyncConsumers = info.JetStream
632✔
1432
        }
632✔
1433

1434
        // Check if we have the remote account information and if so make sure it's stored.
1435
        if info.RemoteAccount != _EMPTY_ {
1,982✔
1436
                s.leafRemoteAccounts.Store(c.acc.Name, info.RemoteAccount)
621✔
1437
        }
621✔
1438
        c.mu.Unlock()
1,361✔
1439

1,361✔
1440
        finishConnect := info.ConnectInfo
1,361✔
1441
        if resumeConnect && s != nil {
2,003✔
1442
                s.leafNodeResumeConnectProcess(c)
642✔
1443
                if !info.InfoOnConnect {
642✔
1444
                        finishConnect = true
×
1445
                }
×
1446
        }
1447
        if finishConnect {
1,982✔
1448
                s.leafNodeFinishConnectProcess(c)
621✔
1449
        }
621✔
1450

1451
        // If we have JS enabled and so does the other side, we will
1452
        // check to see if we need to kick any internal source or mirror consumers.
1453
        if checkSyncConsumers {
1,625✔
1454
                s.checkInternalSyncConsumers(c.acc, info.Domain)
264✔
1455
        }
264✔
1456
}
1457

1458
func (s *Server) negotiateLeafCompression(c *client, didSolicit bool, infoCompression string, co *CompressionOpts) (bool, error) {
1,226✔
1459
        // Negotiate the appropriate compression mode (or no compression)
1,226✔
1460
        cm, err := selectCompressionMode(co.Mode, infoCompression)
1,226✔
1461
        if err != nil {
1,226✔
1462
                return false, err
×
1463
        }
×
1464
        c.mu.Lock()
1,226✔
1465
        // For "auto" mode, set the initial compression mode based on RTT
1,226✔
1466
        if cm == CompressionS2Auto {
2,284✔
1467
                if c.rttStart.IsZero() {
2,116✔
1468
                        c.rtt = computeRTT(c.start)
1,058✔
1469
                }
1,058✔
1470
                cm = selectS2AutoModeBasedOnRTT(c.rtt, co.RTTThresholds)
1,058✔
1471
        }
1472
        // Keep track of the negotiated compression mode.
1473
        c.leaf.compression = cm
1,226✔
1474
        cid := c.cid
1,226✔
1475
        var nonce string
1,226✔
1476
        if !didSolicit {
1,765✔
1477
                nonce = bytesToString(c.nonce)
539✔
1478
        }
539✔
1479
        c.mu.Unlock()
1,226✔
1480

1,226✔
1481
        if !needsCompression(cm) {
1,355✔
1482
                return false, nil
129✔
1483
        }
129✔
1484

1485
        // If we end-up doing compression...
1486

1487
        // Generate an INFO with the chosen compression mode.
1488
        s.mu.Lock()
1,097✔
1489
        info := s.copyLeafNodeInfo()
1,097✔
1490
        info.Compression, info.CID, info.Nonce = compressionModeForInfoProtocol(co, cm), cid, nonce
1,097✔
1491
        infoProto := generateInfoJSON(info)
1,097✔
1492
        s.mu.Unlock()
1,097✔
1493

1,097✔
1494
        // If we solicited, then send this INFO protocol BEFORE switching
1,097✔
1495
        // to compression writer. However, if we did not, we send it after.
1,097✔
1496
        c.mu.Lock()
1,097✔
1497
        if didSolicit {
1,655✔
1498
                c.enqueueProto(infoProto)
558✔
1499
                // Make sure it is completely flushed (the pending bytes goes to
558✔
1500
                // 0) before proceeding.
558✔
1501
                for c.out.pb > 0 && !c.isClosed() {
1,116✔
1502
                        c.flushOutbound()
558✔
1503
                }
558✔
1504
        }
1505
        // This is to notify the readLoop that it should switch to a
1506
        // (de)compression reader.
1507
        c.in.flags.set(switchToCompression)
1,097✔
1508
        // Create the compress writer before queueing the INFO protocol for
1,097✔
1509
        // a route that did not solicit. It will make sure that that proto
1,097✔
1510
        // is sent with compression on.
1,097✔
1511
        c.out.cw = s2.NewWriter(nil, s2WriterOptions(cm)...)
1,097✔
1512
        if !didSolicit {
1,636✔
1513
                c.enqueueProto(infoProto)
539✔
1514
        }
539✔
1515
        c.mu.Unlock()
1,097✔
1516
        return true, nil
1,097✔
1517
}
1518

1519
// When getting a leaf node INFO protocol, use the provided
1520
// array of urls to update the list of possible endpoints.
1521
func (c *client) updateLeafNodeURLs(info *Info) {
1,274✔
1522
        cfg := c.leaf.remote
1,274✔
1523
        cfg.Lock()
1,274✔
1524
        defer cfg.Unlock()
1,274✔
1525

1,274✔
1526
        // We have ensured that if a remote has a WS scheme, then all are.
1,274✔
1527
        // So check if first is WS, then add WS URLs, otherwise, add non WS ones.
1,274✔
1528
        if len(cfg.URLs) > 0 && isWSURL(cfg.URLs[0]) {
1,328✔
1529
                // It does not really matter if we use "ws://" or "wss://" here since
54✔
1530
                // we will have already marked that the remote should use TLS anyway.
54✔
1531
                // But use proper scheme for log statements, etc...
54✔
1532
                proto := wsSchemePrefix
54✔
1533
                if cfg.TLS {
54✔
1534
                        proto = wsSchemePrefixTLS
×
1535
                }
×
1536
                c.doUpdateLNURLs(cfg, proto, info.WSConnectURLs)
54✔
1537
                return
54✔
1538
        }
1539
        c.doUpdateLNURLs(cfg, "nats-leaf", info.LeafNodeURLs)
1,220✔
1540
}
1541

1542
func (c *client) doUpdateLNURLs(cfg *leafNodeCfg, scheme string, URLs []string) {
1,274✔
1543
        cfg.urls = make([]*url.URL, 0, 1+len(URLs))
1,274✔
1544
        // Add the ones we receive in the protocol
1,274✔
1545
        for _, surl := range URLs {
3,588✔
1546
                url, err := url.Parse(fmt.Sprintf("%s://%s", scheme, surl))
2,314✔
1547
                if err != nil {
2,314✔
1548
                        // As per below, the URLs we receive should not have contained URL info, so this should be safe to log.
×
1549
                        c.Errorf("Error parsing url %q: %v", surl, err)
×
1550
                        continue
×
1551
                }
1552
                // Do not add if it's the same as what we already have configured.
1553
                var dup bool
2,314✔
1554
                for _, u := range cfg.URLs {
5,883✔
1555
                        // URLs that we receive never have user info, but the
3,569✔
1556
                        // ones that were configured may have. Simply compare
3,569✔
1557
                        // host and port to decide if they are equal or not.
3,569✔
1558
                        if url.Host == u.Host && url.Port() == u.Port() {
5,271✔
1559
                                dup = true
1,702✔
1560
                                break
1,702✔
1561
                        }
1562
                }
1563
                if !dup {
2,926✔
1564
                        cfg.urls = append(cfg.urls, url)
612✔
1565
                        cfg.saveTLSHostname(url)
612✔
1566
                }
612✔
1567
        }
1568
        // Add the configured one
1569
        cfg.urls = append(cfg.urls, cfg.URLs...)
1,274✔
1570
}
1571

1572
// Similar to setInfoHostPortAndGenerateJSON, but for leafNodeInfo.
1573
func (s *Server) setLeafNodeInfoHostPortAndIP() error {
3,173✔
1574
        opts := s.getOpts()
3,173✔
1575
        if opts.LeafNode.Advertise != _EMPTY_ {
3,184✔
1576
                advHost, advPort, err := parseHostPort(opts.LeafNode.Advertise, opts.LeafNode.Port)
11✔
1577
                if err != nil {
11✔
1578
                        return err
×
1579
                }
×
1580
                s.leafNodeInfo.Host = advHost
11✔
1581
                s.leafNodeInfo.Port = advPort
11✔
1582
        } else {
3,162✔
1583
                s.leafNodeInfo.Host = opts.LeafNode.Host
3,162✔
1584
                s.leafNodeInfo.Port = opts.LeafNode.Port
3,162✔
1585
                // If the host is "0.0.0.0" or "::" we need to resolve to a public IP.
3,162✔
1586
                // This will return at most 1 IP.
3,162✔
1587
                hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(s.leafNodeInfo.Host, false)
3,162✔
1588
                if err != nil {
3,162✔
1589
                        return err
×
1590
                }
×
1591
                if hostIsIPAny {
3,449✔
1592
                        if len(ips) == 0 {
287✔
1593
                                s.Errorf("Could not find any non-local IP for leafnode's listen specification %q",
×
1594
                                        s.leafNodeInfo.Host)
×
1595
                        } else {
287✔
1596
                                // Take the first from the list...
287✔
1597
                                s.leafNodeInfo.Host = ips[0]
287✔
1598
                        }
287✔
1599
                }
1600
        }
1601
        // Use just host:port for the IP
1602
        s.leafNodeInfo.IP = net.JoinHostPort(s.leafNodeInfo.Host, strconv.Itoa(s.leafNodeInfo.Port))
3,173✔
1603
        if opts.LeafNode.Advertise != _EMPTY_ {
3,184✔
1604
                s.Noticef("Advertise address for leafnode is set to %s", s.leafNodeInfo.IP)
11✔
1605
        }
11✔
1606
        return nil
3,173✔
1607
}
1608

1609
// Add the connection to the map of leaf nodes.
1610
// If `checkForDup` is true (invoked when a leafnode is accepted), then we check
1611
// if a connection already exists for the same server name and account.
1612
// That can happen when the remote is attempting to reconnect while the accepting
1613
// side did not detect the connection as broken yet.
1614
// But it can also happen when there is a misconfiguration and the remote is
1615
// creating two (or more) connections that bind to the same account on the accept
1616
// side.
1617
// When a duplicate is found, the new connection is accepted and the old is closed
1618
// (this solves the stale connection situation). An error is returned to help the
1619
// remote detect the misconfiguration when the duplicate is the result of that
1620
// misconfiguration.
1621
func (s *Server) addLeafNodeConnection(c *client, srvName, clusterName string, checkForDup bool) {
1,272✔
1622
        var accName string
1,272✔
1623
        c.mu.Lock()
1,272✔
1624
        cid := c.cid
1,272✔
1625
        acc := c.acc
1,272✔
1626
        if acc != nil {
2,544✔
1627
                accName = acc.Name
1,272✔
1628
        }
1,272✔
1629
        myRemoteDomain := c.leaf.remoteDomain
1,272✔
1630
        mySrvName := c.leaf.remoteServer
1,272✔
1631
        remoteAccName := c.leaf.remoteAccName
1,272✔
1632
        myClustName := c.leaf.remoteCluster
1,272✔
1633
        solicited := c.leaf.remote != nil
1,272✔
1634
        c.mu.Unlock()
1,272✔
1635

1,272✔
1636
        var old *client
1,272✔
1637
        s.mu.Lock()
1,272✔
1638
        // We check for empty because in some test we may send empty CONNECT{}
1,272✔
1639
        if checkForDup && srvName != _EMPTY_ {
1,893✔
1640
                for _, ol := range s.leafs {
1,003✔
1641
                        ol.mu.Lock()
382✔
1642
                        // We care here only about non solicited Leafnode. This function
382✔
1643
                        // is more about replacing stale connections than detecting loops.
382✔
1644
                        // We have code for the loop detection elsewhere, which also delays
382✔
1645
                        // attempt to reconnect.
382✔
1646
                        if !ol.isSolicitedLeafNode() && ol.leaf.remoteServer == srvName &&
382✔
1647
                                ol.leaf.remoteCluster == clusterName && ol.acc.Name == accName &&
382✔
1648
                                remoteAccName != _EMPTY_ && ol.leaf.remoteAccName == remoteAccName {
384✔
1649
                                old = ol
2✔
1650
                        }
2✔
1651
                        ol.mu.Unlock()
382✔
1652
                        if old != nil {
384✔
1653
                                break
2✔
1654
                        }
1655
                }
1656
        }
1657
        // Store new connection in the map
1658
        s.leafs[cid] = c
1,272✔
1659
        s.mu.Unlock()
1,272✔
1660
        s.removeFromTempClients(cid)
1,272✔
1661

1,272✔
1662
        // If applicable, evict the old one.
1,272✔
1663
        if old != nil {
1,274✔
1664
                old.sendErrAndErr(DuplicateRemoteLeafnodeConnection.String())
2✔
1665
                old.closeConnection(DuplicateRemoteLeafnodeConnection)
2✔
1666
                c.Warnf("Replacing connection from same server")
2✔
1667
        }
2✔
1668

1669
        srvDecorated := func() string {
1,483✔
1670
                if myClustName == _EMPTY_ {
233✔
1671
                        return mySrvName
22✔
1672
                }
22✔
1673
                return fmt.Sprintf("%s/%s", mySrvName, myClustName)
189✔
1674
        }
1675

1676
        opts := s.getOpts()
1,272✔
1677
        sysAcc := s.SystemAccount()
1,272✔
1678
        js := s.getJetStream()
1,272✔
1679
        var meta *raft
1,272✔
1680
        if js != nil {
1,805✔
1681
                if mg := js.getMetaGroup(); mg != nil {
973✔
1682
                        meta = mg.(*raft)
440✔
1683
                }
440✔
1684
        }
1685
        blockMappingOutgoing := false
1,272✔
1686
        // Deny (non domain) JetStream API traffic unless system account is shared
1,272✔
1687
        // and domain names are identical and extending is not disabled
1,272✔
1688

1,272✔
1689
        // Check if backwards compatibility has been enabled and needs to be acted on
1,272✔
1690
        forceSysAccDeny := false
1,272✔
1691
        if len(opts.JsAccDefaultDomain) > 0 {
1,309✔
1692
                if acc == sysAcc {
48✔
1693
                        for _, d := range opts.JsAccDefaultDomain {
22✔
1694
                                if d == _EMPTY_ {
19✔
1695
                                        // Extending JetStream via leaf node is mutually exclusive with a domain mapping to the empty/default domain.
8✔
1696
                                        // As soon as one mapping to "" is found, disable the ability to extend JS via a leaf node.
8✔
1697
                                        c.Noticef("Not extending remote JetStream domain %q due to presence of empty default domain", myRemoteDomain)
8✔
1698
                                        forceSysAccDeny = true
8✔
1699
                                        break
8✔
1700
                                }
1701
                        }
1702
                } else if domain, ok := opts.JsAccDefaultDomain[accName]; ok && domain == _EMPTY_ {
41✔
1703
                        // for backwards compatibility with old setups that do not have a domain name set
15✔
1704
                        c.Debugf("Skipping deny %q for account %q due to default domain", jsAllAPI, accName)
15✔
1705
                        return
15✔
1706
                }
15✔
1707
        }
1708

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

1785
func (s *Server) removeLeafNodeConnection(c *client) {
1,571✔
1786
        c.mu.Lock()
1,571✔
1787
        cid := c.cid
1,571✔
1788
        if c.leaf != nil {
3,142✔
1789
                if c.leaf.tsubt != nil {
2,723✔
1790
                        c.leaf.tsubt.Stop()
1,152✔
1791
                        c.leaf.tsubt = nil
1,152✔
1792
                }
1,152✔
1793
                if c.leaf.gwSub != nil {
2,190✔
1794
                        s.gwLeafSubs.Remove(c.leaf.gwSub)
619✔
1795
                        // We need to set this to nil for GC to release the connection
619✔
1796
                        c.leaf.gwSub = nil
619✔
1797
                }
619✔
1798
        }
1799
        c.mu.Unlock()
1,571✔
1800
        s.mu.Lock()
1,571✔
1801
        delete(s.leafs, cid)
1,571✔
1802
        s.mu.Unlock()
1,571✔
1803
        s.removeFromTempClients(cid)
1,571✔
1804
}
1805

1806
// Connect information for solicited leafnodes.
1807
type leafConnectInfo struct {
1808
        Version   string   `json:"version,omitempty"`
1809
        Nkey      string   `json:"nkey,omitempty"`
1810
        JWT       string   `json:"jwt,omitempty"`
1811
        Sig       string   `json:"sig,omitempty"`
1812
        User      string   `json:"user,omitempty"`
1813
        Pass      string   `json:"pass,omitempty"`
1814
        Token     string   `json:"auth_token,omitempty"`
1815
        ID        string   `json:"server_id,omitempty"`
1816
        Domain    string   `json:"domain,omitempty"`
1817
        Name      string   `json:"name,omitempty"`
1818
        Hub       bool     `json:"is_hub,omitempty"`
1819
        Cluster   string   `json:"cluster,omitempty"`
1820
        Headers   bool     `json:"headers,omitempty"`
1821
        JetStream bool     `json:"jetstream,omitempty"`
1822
        DenyPub   []string `json:"deny_pub,omitempty"`
1823

1824
        // There was an existing field called:
1825
        // >> Comp bool `json:"compression,omitempty"`
1826
        // that has never been used. With support for compression, we now need
1827
        // a field that is a string. So we use a different json tag:
1828
        Compression string `json:"compress_mode,omitempty"`
1829

1830
        // Just used to detect wrong connection attempts.
1831
        Gateway string `json:"gateway,omitempty"`
1832

1833
        // Tells the accept side which account the remote is binding to.
1834
        RemoteAccount string `json:"remote_account,omitempty"`
1835

1836
        // The accept side of a LEAF connection, unlike ROUTER and GATEWAY, receives
1837
        // only the CONNECT protocol, and no INFO. So we need to send the protocol
1838
        // version as part of the CONNECT. It will indicate if a connection supports
1839
        // some features, such as message tracing.
1840
        // We use `protocol` as the JSON tag, so this is automatically unmarshal'ed
1841
        // in the low level process CONNECT.
1842
        Proto int `json:"protocol,omitempty"`
1843
}
1844

1845
// processLeafNodeConnect will process the inbound connect args.
1846
// Once we are here we are bound to an account, so can send any interest that
1847
// we would have to the other side.
1848
func (c *client) processLeafNodeConnect(s *Server, arg []byte, lang string) error {
658✔
1849
        // Way to detect clients that incorrectly connect to the route listen
658✔
1850
        // port. Client provided "lang" in the CONNECT protocol while LEAFNODEs don't.
658✔
1851
        if lang != _EMPTY_ {
658✔
1852
                c.sendErrAndErr(ErrClientConnectedToLeafNodePort.Error())
×
1853
                c.closeConnection(WrongPort)
×
1854
                return ErrClientConnectedToLeafNodePort
×
1855
        }
×
1856

1857
        // Unmarshal as a leaf node connect protocol
1858
        proto := &leafConnectInfo{}
658✔
1859
        if err := json.Unmarshal(arg, proto); err != nil {
658✔
1860
                return err
×
1861
        }
×
1862

1863
        // Reject a cluster that contains spaces.
1864
        if proto.Cluster != _EMPTY_ && strings.Contains(proto.Cluster, " ") {
659✔
1865
                c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
1866
                c.closeConnection(ProtocolViolation)
1✔
1867
                return ErrClusterNameHasSpaces
1✔
1868
        }
1✔
1869

1870
        // Check for cluster name collisions.
1871
        if cn := s.cachedClusterName(); cn != _EMPTY_ && proto.Cluster != _EMPTY_ && proto.Cluster == cn {
660✔
1872
                c.sendErrAndErr(ErrLeafNodeHasSameClusterName.Error())
3✔
1873
                c.closeConnection(ClusterNamesIdentical)
3✔
1874
                return ErrLeafNodeHasSameClusterName
3✔
1875
        }
3✔
1876

1877
        // Reject if this has Gateway which means that it would be from a gateway
1878
        // connection that incorrectly connects to the leafnode port.
1879
        if proto.Gateway != _EMPTY_ {
654✔
1880
                errTxt := fmt.Sprintf("Rejecting connection from gateway %q on the leafnode port", proto.Gateway)
×
1881
                c.Errorf(errTxt)
×
1882
                c.sendErr(errTxt)
×
1883
                c.closeConnection(WrongGateway)
×
1884
                return ErrWrongGateway
×
1885
        }
×
1886

1887
        if mv := s.getOpts().LeafNode.MinVersion; mv != _EMPTY_ {
656✔
1888
                major, minor, update, _ := versionComponents(mv)
2✔
1889
                if !versionAtLeast(proto.Version, major, minor, update) {
3✔
1890
                        // We are going to send back an INFO because otherwise recent
1✔
1891
                        // versions of the remote server would simply break the connection
1✔
1892
                        // after 2 seconds if not receiving it. Instead, we want the
1✔
1893
                        // other side to just "stall" until we finish waiting for the holding
1✔
1894
                        // period and close the connection below.
1✔
1895
                        s.sendPermsAndAccountInfo(c)
1✔
1896
                        c.sendErrAndErr(fmt.Sprintf("connection rejected since minimum version required is %q", mv))
1✔
1897
                        select {
1✔
1898
                        case <-c.srv.quitCh:
1✔
1899
                        case <-time.After(leafNodeWaitBeforeClose):
×
1900
                        }
1901
                        c.closeConnection(MinimumVersionRequired)
1✔
1902
                        return ErrMinimumVersionRequired
1✔
1903
                }
1904
        }
1905

1906
        // Check if this server supports headers.
1907
        supportHeaders := c.srv.supportsHeaders()
653✔
1908

653✔
1909
        c.mu.Lock()
653✔
1910
        // Leaf Nodes do not do echo or verbose or pedantic.
653✔
1911
        c.opts.Verbose = false
653✔
1912
        c.opts.Echo = false
653✔
1913
        c.opts.Pedantic = false
653✔
1914
        // This inbound connection will be marked as supporting headers if this server
653✔
1915
        // support headers and the remote has sent in the CONNECT protocol that it does
653✔
1916
        // support headers too.
653✔
1917
        c.headers = supportHeaders && proto.Headers
653✔
1918
        // If the compression level is still not set, set it based on what has been
653✔
1919
        // given to us in the CONNECT protocol.
653✔
1920
        if c.leaf.compression == _EMPTY_ {
780✔
1921
                // But if proto.Compression is _EMPTY_, set it to CompressionNotSupported
127✔
1922
                if proto.Compression == _EMPTY_ {
159✔
1923
                        c.leaf.compression = CompressionNotSupported
32✔
1924
                } else {
127✔
1925
                        c.leaf.compression = proto.Compression
95✔
1926
                }
95✔
1927
        }
1928

1929
        // Remember the remote server.
1930
        c.leaf.remoteServer = proto.Name
653✔
1931
        // Remember the remote account name
653✔
1932
        c.leaf.remoteAccName = proto.RemoteAccount
653✔
1933

653✔
1934
        // If the other side has declared itself a hub, so we will take on the spoke role.
653✔
1935
        if proto.Hub {
659✔
1936
                c.leaf.isSpoke = true
6✔
1937
        }
6✔
1938

1939
        // The soliciting side is part of a cluster.
1940
        if proto.Cluster != _EMPTY_ {
1,159✔
1941
                c.leaf.remoteCluster = proto.Cluster
506✔
1942
        }
506✔
1943

1944
        c.leaf.remoteDomain = proto.Domain
653✔
1945

653✔
1946
        // When a leaf solicits a connection to a hub, the perms that it will use on the soliciting leafnode's
653✔
1947
        // behalf are correct for them, but inside the hub need to be reversed since data is flowing in the opposite direction.
653✔
1948
        if !c.isSolicitedLeafNode() && c.perms != nil {
666✔
1949
                sp, pp := c.perms.sub, c.perms.pub
13✔
1950
                c.perms.sub, c.perms.pub = pp, sp
13✔
1951
                if c.opts.Import != nil {
25✔
1952
                        c.darray = c.opts.Import.Deny
12✔
1953
                } else {
13✔
1954
                        c.darray = nil
1✔
1955
                }
1✔
1956
        }
1957

1958
        // Set the Ping timer
1959
        c.setFirstPingTimer()
653✔
1960

653✔
1961
        // If we received pub deny permissions from the other end, merge with existing ones.
653✔
1962
        c.mergeDenyPermissions(pub, proto.DenyPub)
653✔
1963

653✔
1964
        acc := c.acc
653✔
1965
        c.mu.Unlock()
653✔
1966

653✔
1967
        // Register the cluster, even if empty, as long as we are acting as a hub.
653✔
1968
        if !proto.Hub {
1,300✔
1969
                acc.registerLeafNodeCluster(proto.Cluster)
647✔
1970
        }
647✔
1971

1972
        // Add in the leafnode here since we passed through auth at this point.
1973
        s.addLeafNodeConnection(c, proto.Name, proto.Cluster, true)
653✔
1974

653✔
1975
        // If we have permissions bound to this leafnode we need to send then back to the
653✔
1976
        // origin server for local enforcement.
653✔
1977
        s.sendPermsAndAccountInfo(c)
653✔
1978

653✔
1979
        // Create and initialize the smap since we know our bound account now.
653✔
1980
        // This will send all registered subs too.
653✔
1981
        s.initLeafNodeSmapAndSendSubs(c)
653✔
1982

653✔
1983
        // Announce the account connect event for a leaf node.
653✔
1984
        // This will be a no-op as needed.
653✔
1985
        s.sendLeafNodeConnect(c.acc)
653✔
1986

653✔
1987
        // If we have JS enabled and so does the other side, we will
653✔
1988
        // check to see if we need to kick any internal source or mirror consumers.
653✔
1989
        if proto.JetStream {
896✔
1990
                s.checkInternalSyncConsumers(acc, proto.Domain)
243✔
1991
        }
243✔
1992
        return nil
653✔
1993
}
1994

1995
// checkInternalSyncConsumers
1996
func (s *Server) checkInternalSyncConsumers(acc *Account, remoteDomain string) {
507✔
1997
        // Grab our js
507✔
1998
        js := s.getJetStream()
507✔
1999

507✔
2000
        // Only applicable if we have JS and the leafnode has JS as well.
507✔
2001
        // We check for remote JS outside.
507✔
2002
        if !js.isEnabled() || acc == nil {
630✔
2003
                return
123✔
2004
        }
123✔
2005

2006
        // We will check all streams in our local account. They must be a leader and
2007
        // be sourcing or mirroring. We will check the external config on the stream itself
2008
        // if this is cross domain, or if the remote domain is empty, meaning we might be
2009
        // extedning the system across this leafnode connection and hence we would be extending
2010
        // our own domain.
2011
        jsa := js.lookupAccount(acc)
384✔
2012
        if jsa == nil {
495✔
2013
                return
111✔
2014
        }
111✔
2015
        var streams []*stream
273✔
2016
        jsa.mu.RLock()
273✔
2017
        for _, mset := range jsa.streams {
292✔
2018
                mset.cfgMu.RLock()
19✔
2019
                // We need to have a mirror or source defined.
19✔
2020
                // We do not want to force another lock here to look for leader status,
19✔
2021
                // so collect and after we release jsa will make sure.
19✔
2022
                if mset.cfg.Mirror != nil || len(mset.cfg.Sources) > 0 {
23✔
2023
                        streams = append(streams, mset)
4✔
2024
                }
4✔
2025
                mset.cfgMu.RUnlock()
19✔
2026
        }
2027
        jsa.mu.RUnlock()
273✔
2028

273✔
2029
        // Now loop through all candidates and check if we are the leader and have NOT
273✔
2030
        // created the sync up consumer.
273✔
2031
        for _, mset := range streams {
277✔
2032
                mset.retryDisconnectedSyncConsumers(remoteDomain)
4✔
2033
        }
4✔
2034
}
2035

2036
// Returns the remote cluster name. This is set only once so does not require a lock.
2037
func (c *client) remoteCluster() string {
186,440✔
2038
        if c.leaf == nil {
186,440✔
2039
                return _EMPTY_
×
2040
        }
×
2041
        return c.leaf.remoteCluster
186,440✔
2042
}
2043

2044
// Sends back an info block to the soliciting leafnode to let it know about
2045
// its permission settings for local enforcement.
2046
func (s *Server) sendPermsAndAccountInfo(c *client) {
654✔
2047
        // Copy
654✔
2048
        s.mu.Lock()
654✔
2049
        info := s.copyLeafNodeInfo()
654✔
2050
        s.mu.Unlock()
654✔
2051
        c.mu.Lock()
654✔
2052
        info.CID = c.cid
654✔
2053
        info.Import = c.opts.Import
654✔
2054
        info.Export = c.opts.Export
654✔
2055
        info.RemoteAccount = c.acc.Name
654✔
2056
        // s.SystemAccount() uses an atomic operation and does not get the server lock, so this is safe.
654✔
2057
        info.IsSystemAccount = c.acc == s.SystemAccount()
654✔
2058
        info.ConnectInfo = true
654✔
2059
        c.enqueueProto(generateInfoJSON(info))
654✔
2060
        c.mu.Unlock()
654✔
2061
}
654✔
2062

2063
// Snapshot the current subscriptions from the sublist into our smap which
2064
// we will keep updated from now on.
2065
// Also send the registered subscriptions.
2066
func (s *Server) initLeafNodeSmapAndSendSubs(c *client) {
1,272✔
2067
        acc := c.acc
1,272✔
2068
        if acc == nil {
1,272✔
2069
                c.Debugf("Leafnode does not have an account bound")
×
2070
                return
×
2071
        }
×
2072
        // Collect all account subs here.
2073
        _subs := [1024]*subscription{}
1,272✔
2074
        subs := _subs[:0]
1,272✔
2075
        ims := []string{}
1,272✔
2076

1,272✔
2077
        // Hold the client lock otherwise there can be a race and miss some subs.
1,272✔
2078
        c.mu.Lock()
1,272✔
2079
        defer c.mu.Unlock()
1,272✔
2080

1,272✔
2081
        acc.mu.RLock()
1,272✔
2082
        accName := acc.Name
1,272✔
2083
        accNTag := acc.nameTag
1,272✔
2084

1,272✔
2085
        // To make printing look better when no friendly name present.
1,272✔
2086
        if accNTag != _EMPTY_ {
1,283✔
2087
                accNTag = "/" + accNTag
11✔
2088
        }
11✔
2089

2090
        // If we are solicited we only send interest for local clients.
2091
        if c.isSpokeLeafNode() {
1,891✔
2092
                acc.sl.localSubs(&subs, true)
619✔
2093
        } else {
1,272✔
2094
                acc.sl.All(&subs)
653✔
2095
        }
653✔
2096

2097
        // Check if we have an existing service import reply.
2098
        siReply := copyBytes(acc.siReply)
1,272✔
2099

1,272✔
2100
        // Since leaf nodes only send on interest, if the bound
1,272✔
2101
        // account has import services we need to send those over.
1,272✔
2102
        for isubj := range acc.imports.services {
5,985✔
2103
                if c.isSpokeLeafNode() && !c.canSubscribe(isubj) {
4,991✔
2104
                        c.Debugf("Not permitted to import service %q on behalf of %s%s", isubj, accName, accNTag)
278✔
2105
                        continue
278✔
2106
                }
2107
                ims = append(ims, isubj)
4,435✔
2108
        }
2109
        // Likewise for mappings.
2110
        for _, m := range acc.mappings {
3,507✔
2111
                if c.isSpokeLeafNode() && !c.canSubscribe(m.src) {
2,271✔
2112
                        c.Debugf("Not permitted to import mapping %q on behalf of %s%s", m.src, accName, accNTag)
36✔
2113
                        continue
36✔
2114
                }
2115
                ims = append(ims, m.src)
2,199✔
2116
        }
2117

2118
        // Create a unique subject that will be used for loop detection.
2119
        lds := acc.lds
1,272✔
2120
        acc.mu.RUnlock()
1,272✔
2121

1,272✔
2122
        // Check if we have to create the LDS.
1,272✔
2123
        if lds == _EMPTY_ {
2,272✔
2124
                lds = leafNodeLoopDetectionSubjectPrefix + nuid.Next()
1,000✔
2125
                acc.mu.Lock()
1,000✔
2126
                acc.lds = lds
1,000✔
2127
                acc.mu.Unlock()
1,000✔
2128
        }
1,000✔
2129

2130
        // Now check for gateway interest. Leafnodes will put this into
2131
        // the proper mode to propagate, but they are not held in the account.
2132
        gwsa := [16]*client{}
1,272✔
2133
        gws := gwsa[:0]
1,272✔
2134
        s.getOutboundGatewayConnections(&gws)
1,272✔
2135
        for _, cgw := range gws {
1,354✔
2136
                cgw.mu.Lock()
82✔
2137
                gw := cgw.gw
82✔
2138
                cgw.mu.Unlock()
82✔
2139
                if gw != nil {
164✔
2140
                        if ei, _ := gw.outsim.Load(accName); ei != nil {
164✔
2141
                                if e := ei.(*outsie); e != nil && e.sl != nil {
164✔
2142
                                        e.sl.All(&subs)
82✔
2143
                                }
82✔
2144
                        }
2145
                }
2146
        }
2147

2148
        applyGlobalRouting := s.gateway.enabled
1,272✔
2149
        if c.isSpokeLeafNode() {
1,891✔
2150
                // Add a fake subscription for this solicited leafnode connection
619✔
2151
                // so that we can send back directly for mapped GW replies.
619✔
2152
                // We need to keep track of this subscription so it can be removed
619✔
2153
                // when the connection is closed so that the GC can release it.
619✔
2154
                c.leaf.gwSub = &subscription{client: c, subject: []byte(gwReplyPrefix + ">")}
619✔
2155
                c.srv.gwLeafSubs.Insert(c.leaf.gwSub)
619✔
2156
        }
619✔
2157

2158
        // Now walk the results and add them to our smap
2159
        rc := c.leaf.remoteCluster
1,272✔
2160
        c.leaf.smap = make(map[string]int32)
1,272✔
2161
        for _, sub := range subs {
39,853✔
2162
                // Check perms regardless of role.
38,581✔
2163
                if c.perms != nil && !c.canSubscribe(string(sub.subject)) {
40,980✔
2164
                        c.Debugf("Not permitted to subscribe to %q on behalf of %s%s", sub.subject, accName, accNTag)
2,399✔
2165
                        continue
2,399✔
2166
                }
2167
                // We ignore ourselves here.
2168
                // Also don't add the subscription if it has a origin cluster and the
2169
                // cluster name matches the one of the client we are sending to.
2170
                if c != sub.client && (sub.origin == nil || (bytesToString(sub.origin) != rc)) {
66,871✔
2171
                        count := int32(1)
30,689✔
2172
                        if len(sub.queue) > 0 && sub.qw > 0 {
30,698✔
2173
                                count = sub.qw
9✔
2174
                        }
9✔
2175
                        c.leaf.smap[keyFromSub(sub)] += count
30,689✔
2176
                        if c.leaf.tsub == nil {
31,885✔
2177
                                c.leaf.tsub = make(map[*subscription]struct{})
1,196✔
2178
                        }
1,196✔
2179
                        c.leaf.tsub[sub] = struct{}{}
30,689✔
2180
                }
2181
        }
2182
        // FIXME(dlc) - We need to update appropriately on an account claims update.
2183
        for _, isubj := range ims {
7,906✔
2184
                c.leaf.smap[isubj]++
6,634✔
2185
        }
6,634✔
2186
        // If we have gateways enabled we need to make sure the other side sends us responses
2187
        // that have been augmented from the original subscription.
2188
        // TODO(dlc) - Should we lock this down more?
2189
        if applyGlobalRouting {
1,375✔
2190
                c.leaf.smap[oldGWReplyPrefix+"*.>"]++
103✔
2191
                c.leaf.smap[gwReplyPrefix+">"]++
103✔
2192
        }
103✔
2193
        // Detect loops by subscribing to a specific subject and checking
2194
        // if this sub is coming back to us.
2195
        c.leaf.smap[lds]++
1,272✔
2196

1,272✔
2197
        // Check if we need to add an existing siReply to our map.
1,272✔
2198
        // This will be a prefix so add on the wildcard.
1,272✔
2199
        if siReply != nil {
1,290✔
2200
                wcsub := append(siReply, '>')
18✔
2201
                c.leaf.smap[string(wcsub)]++
18✔
2202
        }
18✔
2203
        // Queue all protocols. There is no max pending limit for LN connection,
2204
        // so we don't need chunking. The writes will happen from the writeLoop.
2205
        var b bytes.Buffer
1,272✔
2206
        for key, n := range c.leaf.smap {
27,693✔
2207
                c.writeLeafSub(&b, key, n)
26,421✔
2208
        }
26,421✔
2209
        if b.Len() > 0 {
2,544✔
2210
                c.enqueueProto(b.Bytes())
1,272✔
2211
        }
1,272✔
2212
        if c.leaf.tsub != nil {
2,469✔
2213
                // Clear the tsub map after 5 seconds.
1,197✔
2214
                c.leaf.tsubt = time.AfterFunc(5*time.Second, func() {
1,242✔
2215
                        c.mu.Lock()
45✔
2216
                        if c.leaf != nil {
90✔
2217
                                c.leaf.tsub = nil
45✔
2218
                                c.leaf.tsubt = nil
45✔
2219
                        }
45✔
2220
                        c.mu.Unlock()
45✔
2221
                })
2222
        }
2223
}
2224

2225
// updateInterestForAccountOnGateway called from gateway code when processing RS+ and RS-.
2226
func (s *Server) updateInterestForAccountOnGateway(accName string, sub *subscription, delta int32) {
201,175✔
2227
        acc, err := s.LookupAccount(accName)
201,175✔
2228
        if acc == nil || err != nil {
201,337✔
2229
                s.Debugf("No or bad account for %q, failed to update interest from gateway", accName)
162✔
2230
                return
162✔
2231
        }
162✔
2232
        acc.updateLeafNodes(sub, delta)
201,013✔
2233
}
2234

2235
// updateLeafNodes will make sure to update the account smap for the subscription.
2236
// Will also forward to all leaf nodes as needed.
2237
func (acc *Account) updateLeafNodes(sub *subscription, delta int32) {
2,366,166✔
2238
        if acc == nil || sub == nil {
2,366,166✔
2239
                return
×
2240
        }
×
2241

2242
        // We will do checks for no leafnodes and same cluster here inline and under the
2243
        // general account read lock.
2244
        // If we feel we need to update the leafnodes we will do that out of line to avoid
2245
        // blocking routes or GWs.
2246

2247
        acc.mu.RLock()
2,366,166✔
2248
        // First check if we even have leafnodes here.
2,366,166✔
2249
        if acc.nleafs == 0 {
4,664,200✔
2250
                acc.mu.RUnlock()
2,298,034✔
2251
                return
2,298,034✔
2252
        }
2,298,034✔
2253

2254
        // Is this a loop detection subject.
2255
        isLDS := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
68,132✔
2256

68,132✔
2257
        // Capture the cluster even if its empty.
68,132✔
2258
        var cluster string
68,132✔
2259
        if sub.origin != nil {
117,645✔
2260
                cluster = bytesToString(sub.origin)
49,513✔
2261
        }
49,513✔
2262

2263
        // If we have an isolated cluster we can return early, as long as it is not a loop detection subject.
2264
        // Empty clusters will return false for the check.
2265
        if !isLDS && acc.isLeafNodeClusterIsolated(cluster) {
88,951✔
2266
                acc.mu.RUnlock()
20,819✔
2267
                return
20,819✔
2268
        }
20,819✔
2269

2270
        // We can release the general account lock.
2271
        acc.mu.RUnlock()
47,313✔
2272

47,313✔
2273
        // We can hold the list lock here to avoid having to copy a large slice.
47,313✔
2274
        acc.lmu.RLock()
47,313✔
2275
        defer acc.lmu.RUnlock()
47,313✔
2276

47,313✔
2277
        // Do this once.
47,313✔
2278
        subject := string(sub.subject)
47,313✔
2279

47,313✔
2280
        // Walk the connected leafnodes.
47,313✔
2281
        for _, ln := range acc.lleafs {
105,713✔
2282
                if ln == sub.client {
88,128✔
2283
                        continue
29,728✔
2284
                }
2285
                // Check to make sure this sub does not have an origin cluster that matches the leafnode.
2286
                ln.mu.Lock()
28,672✔
2287
                // If skipped, make sure that we still let go the "$LDS." subscription that allows
28,672✔
2288
                // the detection of loops as long as different cluster.
28,672✔
2289
                clusterDifferent := cluster != ln.remoteCluster()
28,672✔
2290
                if (isLDS && clusterDifferent) || ((cluster == _EMPTY_ || clusterDifferent) && (delta <= 0 || ln.canSubscribe(subject))) {
52,744✔
2291
                        ln.updateSmap(sub, delta, isLDS)
24,072✔
2292
                }
24,072✔
2293
                ln.mu.Unlock()
28,672✔
2294
        }
2295
}
2296

2297
// This will make an update to our internal smap and determine if we should send out
2298
// an interest update to the remote side.
2299
// Lock should be held.
2300
func (c *client) updateSmap(sub *subscription, delta int32, isLDS bool) {
24,072✔
2301
        if c.leaf.smap == nil {
24,083✔
2302
                return
11✔
2303
        }
11✔
2304

2305
        // If we are solicited make sure this is a local client or a non-solicited leaf node
2306
        skind := sub.client.kind
24,061✔
2307
        updateClient := skind == CLIENT || skind == SYSTEM || skind == JETSTREAM || skind == ACCOUNT
24,061✔
2308
        if !isLDS && c.isSpokeLeafNode() && !(updateClient || (skind == LEAF && !sub.client.isSpokeLeafNode())) {
32,715✔
2309
                return
8,654✔
2310
        }
8,654✔
2311

2312
        // For additions, check if that sub has just been processed during initLeafNodeSmapAndSendSubs
2313
        if delta > 0 && c.leaf.tsub != nil {
22,776✔
2314
                if _, present := c.leaf.tsub[sub]; present {
7,369✔
2315
                        delete(c.leaf.tsub, sub)
×
2316
                        if len(c.leaf.tsub) == 0 {
×
2317
                                c.leaf.tsub = nil
×
2318
                                c.leaf.tsubt.Stop()
×
2319
                                c.leaf.tsubt = nil
×
2320
                        }
×
2321
                        return
×
2322
                }
2323
        }
2324

2325
        key := keyFromSub(sub)
15,407✔
2326
        n, ok := c.leaf.smap[key]
15,407✔
2327
        if delta < 0 && !ok {
16,328✔
2328
                return
921✔
2329
        }
921✔
2330

2331
        // We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
2332
        update := sub.queue != nil || (n <= 0 && n+delta > 0) || (n > 0 && n+delta <= 0)
14,486✔
2333
        n += delta
14,486✔
2334
        if n > 0 {
25,416✔
2335
                c.leaf.smap[key] = n
10,930✔
2336
        } else {
14,486✔
2337
                delete(c.leaf.smap, key)
3,556✔
2338
        }
3,556✔
2339
        if update {
23,876✔
2340
                c.sendLeafNodeSubUpdate(key, n)
9,390✔
2341
        }
9,390✔
2342
}
2343

2344
// Used to force add subjects to the subject map.
2345
func (c *client) forceAddToSmap(subj string) {
4✔
2346
        c.mu.Lock()
4✔
2347
        defer c.mu.Unlock()
4✔
2348

4✔
2349
        if c.leaf.smap == nil {
4✔
2350
                return
×
2351
        }
×
2352
        n := c.leaf.smap[subj]
4✔
2353
        if n != 0 {
5✔
2354
                return
1✔
2355
        }
1✔
2356
        // Place into the map since it was not there.
2357
        c.leaf.smap[subj] = 1
3✔
2358
        c.sendLeafNodeSubUpdate(subj, 1)
3✔
2359
}
2360

2361
// Used to force remove a subject from the subject map.
2362
func (c *client) forceRemoveFromSmap(subj string) {
1✔
2363
        c.mu.Lock()
1✔
2364
        defer c.mu.Unlock()
1✔
2365

1✔
2366
        if c.leaf.smap == nil {
1✔
2367
                return
×
2368
        }
×
2369
        n := c.leaf.smap[subj]
1✔
2370
        if n == 0 {
1✔
2371
                return
×
2372
        }
×
2373
        n--
1✔
2374
        if n == 0 {
2✔
2375
                // Remove is now zero
1✔
2376
                delete(c.leaf.smap, subj)
1✔
2377
                c.sendLeafNodeSubUpdate(subj, 0)
1✔
2378
        } else {
1✔
2379
                c.leaf.smap[subj] = n
×
2380
        }
×
2381
}
2382

2383
// Send the subscription interest change to the other side.
2384
// Lock should be held.
2385
func (c *client) sendLeafNodeSubUpdate(key string, n int32) {
9,394✔
2386
        // If we are a spoke, we need to check if we are allowed to send this subscription over to the hub.
9,394✔
2387
        if c.isSpokeLeafNode() {
11,691✔
2388
                checkPerms := true
2,297✔
2389
                if len(key) > 0 && (key[0] == '$' || key[0] == '_') {
3,650✔
2390
                        if strings.HasPrefix(key, leafNodeLoopDetectionSubjectPrefix) ||
1,353✔
2391
                                strings.HasPrefix(key, oldGWReplyPrefix) ||
1,353✔
2392
                                strings.HasPrefix(key, gwReplyPrefix) {
1,435✔
2393
                                checkPerms = false
82✔
2394
                        }
82✔
2395
                }
2396
                if checkPerms {
4,512✔
2397
                        var subject string
2,215✔
2398
                        if sep := strings.IndexByte(key, ' '); sep != -1 {
2,705✔
2399
                                subject = key[:sep]
490✔
2400
                        } else {
2,215✔
2401
                                subject = key
1,725✔
2402
                        }
1,725✔
2403
                        if !c.canSubscribe(subject) {
2,215✔
2404
                                return
×
2405
                        }
×
2406
                }
2407
        }
2408
        // If we are here we can send over to the other side.
2409
        _b := [64]byte{}
9,394✔
2410
        b := bytes.NewBuffer(_b[:0])
9,394✔
2411
        c.writeLeafSub(b, key, n)
9,394✔
2412
        c.enqueueProto(b.Bytes())
9,394✔
2413
}
2414

2415
// Helper function to build the key.
2416
func keyFromSub(sub *subscription) string {
47,113✔
2417
        var sb strings.Builder
47,113✔
2418
        sb.Grow(len(sub.subject) + len(sub.queue) + 1)
47,113✔
2419
        sb.Write(sub.subject)
47,113✔
2420
        if sub.queue != nil {
50,899✔
2421
                // Just make the key subject spc group, e.g. 'foo bar'
3,786✔
2422
                sb.WriteByte(' ')
3,786✔
2423
                sb.Write(sub.queue)
3,786✔
2424
        }
3,786✔
2425
        return sb.String()
47,113✔
2426
}
2427

2428
const (
2429
        keyRoutedSub         = "R"
2430
        keyRoutedSubByte     = 'R'
2431
        keyRoutedLeafSub     = "L"
2432
        keyRoutedLeafSubByte = 'L'
2433
)
2434

2435
// Helper function to build the key that prevents collisions between normal
2436
// routed subscriptions and routed subscriptions on behalf of a leafnode.
2437
// Keys will look like this:
2438
// "R foo"          -> plain routed sub on "foo"
2439
// "R foo bar"      -> queue routed sub on "foo", queue "bar"
2440
// "L foo bar"      -> plain routed leaf sub on "foo", leaf "bar"
2441
// "L foo bar baz"  -> queue routed sub on "foo", queue "bar", leaf "baz"
2442
func keyFromSubWithOrigin(sub *subscription) string {
653,440✔
2443
        var sb strings.Builder
653,440✔
2444
        sb.Grow(2 + len(sub.origin) + 1 + len(sub.subject) + 1 + len(sub.queue))
653,440✔
2445
        leaf := len(sub.origin) > 0
653,440✔
2446
        if leaf {
670,426✔
2447
                sb.WriteByte(keyRoutedLeafSubByte)
16,986✔
2448
        } else {
653,440✔
2449
                sb.WriteByte(keyRoutedSubByte)
636,454✔
2450
        }
636,454✔
2451
        sb.WriteByte(' ')
653,440✔
2452
        sb.Write(sub.subject)
653,440✔
2453
        if sub.queue != nil {
679,151✔
2454
                sb.WriteByte(' ')
25,711✔
2455
                sb.Write(sub.queue)
25,711✔
2456
        }
25,711✔
2457
        if leaf {
670,426✔
2458
                sb.WriteByte(' ')
16,986✔
2459
                sb.Write(sub.origin)
16,986✔
2460
        }
16,986✔
2461
        return sb.String()
653,440✔
2462
}
2463

2464
// Lock should be held.
2465
func (c *client) writeLeafSub(w *bytes.Buffer, key string, n int32) {
35,815✔
2466
        if key == _EMPTY_ {
35,815✔
2467
                return
×
2468
        }
×
2469
        if n > 0 {
68,073✔
2470
                w.WriteString("LS+ " + key)
32,258✔
2471
                // Check for queue semantics, if found write n.
32,258✔
2472
                if strings.Contains(key, " ") {
34,565✔
2473
                        w.WriteString(" ")
2,307✔
2474
                        var b [12]byte
2,307✔
2475
                        var i = len(b)
2,307✔
2476
                        for l := n; l > 0; l /= 10 {
5,502✔
2477
                                i--
3,195✔
2478
                                b[i] = digits[l%10]
3,195✔
2479
                        }
3,195✔
2480
                        w.Write(b[i:])
2,307✔
2481
                        if c.trace {
2,307✔
2482
                                arg := fmt.Sprintf("%s %d", key, n)
×
2483
                                c.traceOutOp("LS+", []byte(arg))
×
2484
                        }
×
2485
                } else if c.trace {
30,147✔
2486
                        c.traceOutOp("LS+", []byte(key))
196✔
2487
                }
196✔
2488
        } else {
3,557✔
2489
                w.WriteString("LS- " + key)
3,557✔
2490
                if c.trace {
3,569✔
2491
                        c.traceOutOp("LS-", []byte(key))
12✔
2492
                }
12✔
2493
        }
2494
        w.WriteString(CR_LF)
35,815✔
2495
}
2496

2497
// processLeafSub will process an inbound sub request for the remote leaf node.
2498
func (c *client) processLeafSub(argo []byte) (err error) {
31,974✔
2499
        // Indicate activity.
31,974✔
2500
        c.in.subs++
31,974✔
2501

31,974✔
2502
        srv := c.srv
31,974✔
2503
        if srv == nil {
31,974✔
2504
                return nil
×
2505
        }
×
2506

2507
        // Copy so we do not reference a potentially large buffer
2508
        arg := make([]byte, len(argo))
31,974✔
2509
        copy(arg, argo)
31,974✔
2510

31,974✔
2511
        args := splitArg(arg)
31,974✔
2512
        sub := &subscription{client: c}
31,974✔
2513

31,974✔
2514
        delta := int32(1)
31,974✔
2515
        switch len(args) {
31,974✔
2516
        case 1:
29,733✔
2517
                sub.queue = nil
29,733✔
2518
        case 3:
2,241✔
2519
                sub.queue = args[1]
2,241✔
2520
                sub.qw = int32(parseSize(args[2]))
2,241✔
2521
                // TODO: (ik) We should have a non empty queue name and a queue
2,241✔
2522
                // weight >= 1. For 2.11, we may want to return an error if that
2,241✔
2523
                // is not the case, but for now just overwrite `delta` if queue
2,241✔
2524
                // weight is greater than 1 (it is possible after a reconnect/
2,241✔
2525
                // server restart to receive a queue weight > 1 for a new sub).
2,241✔
2526
                if sub.qw > 1 {
3,878✔
2527
                        delta = sub.qw
1,637✔
2528
                }
1,637✔
2529
        default:
×
2530
                return fmt.Errorf("processLeafSub Parse Error: '%s'", arg)
×
2531
        }
2532
        sub.subject = args[0]
31,974✔
2533

31,974✔
2534
        c.mu.Lock()
31,974✔
2535
        if c.isClosed() {
32,000✔
2536
                c.mu.Unlock()
26✔
2537
                return nil
26✔
2538
        }
26✔
2539

2540
        acc := c.acc
31,948✔
2541
        // Check if we have a loop.
31,948✔
2542
        ldsPrefix := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
31,948✔
2543

31,948✔
2544
        if ldsPrefix && bytesToString(sub.subject) == acc.getLDSubject() {
31,955✔
2545
                c.mu.Unlock()
7✔
2546
                c.handleLeafNodeLoop(true)
7✔
2547
                return nil
7✔
2548
        }
7✔
2549

2550
        // Check permissions if applicable. (but exclude the $LDS, $GR and _GR_)
2551
        checkPerms := true
31,941✔
2552
        if sub.subject[0] == '$' || sub.subject[0] == '_' {
61,022✔
2553
                if ldsPrefix ||
29,081✔
2554
                        bytes.HasPrefix(sub.subject, []byte(oldGWReplyPrefix)) ||
29,081✔
2555
                        bytes.HasPrefix(sub.subject, []byte(gwReplyPrefix)) {
31,037✔
2556
                        checkPerms = false
1,956✔
2557
                }
1,956✔
2558
        }
2559

2560
        // If we are a hub check that we can publish to this subject.
2561
        if checkPerms {
61,926✔
2562
                subj := string(sub.subject)
29,985✔
2563
                if subjectIsLiteral(subj) && !c.pubAllowedFullCheck(subj, true, true) {
30,294✔
2564
                        c.mu.Unlock()
309✔
2565
                        c.leafSubPermViolation(sub.subject)
309✔
2566
                        c.Debugf(fmt.Sprintf("Permissions Violation for Subscription to %q", sub.subject))
309✔
2567
                        return nil
309✔
2568
                }
309✔
2569
        }
2570

2571
        // Check if we have a maximum on the number of subscriptions.
2572
        if c.subsAtLimit() {
31,640✔
2573
                c.mu.Unlock()
8✔
2574
                c.maxSubsExceeded()
8✔
2575
                return nil
8✔
2576
        }
8✔
2577

2578
        // If we have an origin cluster associated mark that in the sub.
2579
        if rc := c.remoteCluster(); rc != _EMPTY_ {
60,161✔
2580
                sub.origin = []byte(rc)
28,537✔
2581
        }
28,537✔
2582

2583
        // Like Routes, we store local subs by account and subject and optionally queue name.
2584
        // If we have a queue it will have a trailing weight which we do not want.
2585
        if sub.queue != nil {
33,578✔
2586
                sub.sid = arg[:len(arg)-len(args[2])-1]
1,954✔
2587
        } else {
31,624✔
2588
                sub.sid = arg
29,670✔
2589
        }
29,670✔
2590
        key := bytesToString(sub.sid)
31,624✔
2591
        osub := c.subs[key]
31,624✔
2592
        if osub == nil {
61,747✔
2593
                c.subs[key] = sub
30,123✔
2594
                // Now place into the account sl.
30,123✔
2595
                if err := acc.sl.Insert(sub); err != nil {
30,123✔
2596
                        delete(c.subs, key)
×
2597
                        c.mu.Unlock()
×
2598
                        c.Errorf("Could not insert subscription: %v", err)
×
2599
                        c.sendErr("Invalid Subscription")
×
2600
                        return nil
×
2601
                }
×
2602
        } else if sub.queue != nil {
3,001✔
2603
                // For a queue we need to update the weight.
1,500✔
2604
                delta = sub.qw - atomic.LoadInt32(&osub.qw)
1,500✔
2605
                atomic.StoreInt32(&osub.qw, sub.qw)
1,500✔
2606
                acc.sl.UpdateRemoteQSub(osub)
1,500✔
2607
        }
1,500✔
2608
        spoke := c.isSpokeLeafNode()
31,624✔
2609
        c.mu.Unlock()
31,624✔
2610

31,624✔
2611
        // Only add in shadow subs if a new sub or qsub.
31,624✔
2612
        if osub == nil {
61,747✔
2613
                if err := c.addShadowSubscriptions(acc, sub, true); err != nil {
30,123✔
2614
                        c.Errorf(err.Error())
×
2615
                }
×
2616
        }
2617

2618
        // If we are not solicited, treat leaf node subscriptions similar to a
2619
        // client subscription, meaning we forward them to routes, gateways and
2620
        // other leaf nodes as needed.
2621
        if !spoke {
42,756✔
2622
                // If we are routing add to the route map for the associated account.
11,132✔
2623
                srv.updateRouteSubscriptionMap(acc, sub, delta)
11,132✔
2624
                if srv.gateway.enabled {
12,658✔
2625
                        srv.gatewayUpdateSubInterest(acc.Name, sub, delta)
1,526✔
2626
                }
1,526✔
2627
        }
2628
        // Now check on leafnode updates for other leaf nodes. We understand solicited
2629
        // and non-solicited state in this call so we will do the right thing.
2630
        acc.updateLeafNodes(sub, delta)
31,624✔
2631

31,624✔
2632
        return nil
31,624✔
2633
}
2634

2635
// If the leafnode is a solicited, set the connect delay based on default
2636
// or private option (for tests). Sends the error to the other side, log and
2637
// close the connection.
2638
func (c *client) handleLeafNodeLoop(sendErr bool) {
17✔
2639
        accName, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterLoopDetected)
17✔
2640
        errTxt := fmt.Sprintf("Loop detected for leafnode account=%q. Delaying attempt to reconnect for %v", accName, delay)
17✔
2641
        if sendErr {
26✔
2642
                c.sendErr(errTxt)
9✔
2643
        }
9✔
2644

2645
        c.Errorf(errTxt)
17✔
2646
        // If we are here with "sendErr" false, it means that this is the server
17✔
2647
        // that received the error. The other side will have closed the connection,
17✔
2648
        // but does not hurt to close here too.
17✔
2649
        c.closeConnection(ProtocolViolation)
17✔
2650
}
2651

2652
// processLeafUnsub will process an inbound unsub request for the remote leaf node.
2653
func (c *client) processLeafUnsub(arg []byte) error {
3,283✔
2654
        // Indicate any activity, so pub and sub or unsubs.
3,283✔
2655
        c.in.subs++
3,283✔
2656

3,283✔
2657
        acc := c.acc
3,283✔
2658
        srv := c.srv
3,283✔
2659

3,283✔
2660
        c.mu.Lock()
3,283✔
2661
        if c.isClosed() {
3,355✔
2662
                c.mu.Unlock()
72✔
2663
                return nil
72✔
2664
        }
72✔
2665

2666
        spoke := c.isSpokeLeafNode()
3,211✔
2667
        // We store local subs by account and subject and optionally queue name.
3,211✔
2668
        // LS- will have the arg exactly as the key.
3,211✔
2669
        sub, ok := c.subs[string(arg)]
3,211✔
2670
        if !ok {
3,213✔
2671
                // If not found, don't try to update routes/gws/leaf nodes.
2✔
2672
                c.mu.Unlock()
2✔
2673
                return nil
2✔
2674
        }
2✔
2675
        delta := int32(1)
3,209✔
2676
        if len(sub.queue) > 0 {
3,623✔
2677
                delta = sub.qw
414✔
2678
        }
414✔
2679
        c.mu.Unlock()
3,209✔
2680

3,209✔
2681
        c.unsubscribe(acc, sub, true, true)
3,209✔
2682
        if !spoke {
4,228✔
2683
                // If we are routing subtract from the route map for the associated account.
1,019✔
2684
                srv.updateRouteSubscriptionMap(acc, sub, -delta)
1,019✔
2685
                // Gateways
1,019✔
2686
                if srv.gateway.enabled {
1,298✔
2687
                        srv.gatewayUpdateSubInterest(acc.Name, sub, -delta)
279✔
2688
                }
279✔
2689
        }
2690
        // Now check on leafnode updates for other leaf nodes.
2691
        acc.updateLeafNodes(sub, -delta)
3,209✔
2692
        return nil
3,209✔
2693
}
2694

2695
func (c *client) processLeafHeaderMsgArgs(arg []byte) error {
479✔
2696
        // Unroll splitArgs to avoid runtime/heap issues
479✔
2697
        a := [MAX_MSG_ARGS][]byte{}
479✔
2698
        args := a[:0]
479✔
2699
        start := -1
479✔
2700
        for i, b := range arg {
31,467✔
2701
                switch b {
30,988✔
2702
                case ' ', '\t', '\r', '\n':
1,368✔
2703
                        if start >= 0 {
2,736✔
2704
                                args = append(args, arg[start:i])
1,368✔
2705
                                start = -1
1,368✔
2706
                        }
1,368✔
2707
                default:
29,620✔
2708
                        if start < 0 {
31,467✔
2709
                                start = i
1,847✔
2710
                        }
1,847✔
2711
                }
2712
        }
2713
        if start >= 0 {
958✔
2714
                args = append(args, arg[start:])
479✔
2715
        }
479✔
2716

2717
        c.pa.arg = arg
479✔
2718
        switch len(args) {
479✔
2719
        case 0, 1, 2:
×
2720
                return fmt.Errorf("processLeafHeaderMsgArgs Parse Error: '%s'", args)
×
2721
        case 3:
87✔
2722
                c.pa.reply = nil
87✔
2723
                c.pa.queues = nil
87✔
2724
                c.pa.hdb = args[1]
87✔
2725
                c.pa.hdr = parseSize(args[1])
87✔
2726
                c.pa.szb = args[2]
87✔
2727
                c.pa.size = parseSize(args[2])
87✔
2728
        case 4:
378✔
2729
                c.pa.reply = args[1]
378✔
2730
                c.pa.queues = nil
378✔
2731
                c.pa.hdb = args[2]
378✔
2732
                c.pa.hdr = parseSize(args[2])
378✔
2733
                c.pa.szb = args[3]
378✔
2734
                c.pa.size = parseSize(args[3])
378✔
2735
        default:
14✔
2736
                // args[1] is our reply indicator. Should be + or | normally.
14✔
2737
                if len(args[1]) != 1 {
14✔
2738
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2739
                }
×
2740
                switch args[1][0] {
14✔
2741
                case '+':
4✔
2742
                        c.pa.reply = args[2]
4✔
2743
                case '|':
10✔
2744
                        c.pa.reply = nil
10✔
2745
                default:
×
2746
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2747
                }
2748
                // Grab header size.
2749
                c.pa.hdb = args[len(args)-2]
14✔
2750
                c.pa.hdr = parseSize(c.pa.hdb)
14✔
2751

14✔
2752
                // Grab size.
14✔
2753
                c.pa.szb = args[len(args)-1]
14✔
2754
                c.pa.size = parseSize(c.pa.szb)
14✔
2755

14✔
2756
                // Grab queue names.
14✔
2757
                if c.pa.reply != nil {
18✔
2758
                        c.pa.queues = args[3 : len(args)-2]
4✔
2759
                } else {
14✔
2760
                        c.pa.queues = args[2 : len(args)-2]
10✔
2761
                }
10✔
2762
        }
2763
        if c.pa.hdr < 0 {
479✔
2764
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Header Size: '%s'", arg)
×
2765
        }
×
2766
        if c.pa.size < 0 {
479✔
2767
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Size: '%s'", args)
×
2768
        }
×
2769
        if c.pa.hdr > c.pa.size {
479✔
2770
                return fmt.Errorf("processLeafHeaderMsgArgs Header Size larger then TotalSize: '%s'", arg)
×
2771
        }
×
2772

2773
        // Common ones processed after check for arg length
2774
        c.pa.subject = args[0]
479✔
2775

479✔
2776
        return nil
479✔
2777
}
2778

2779
func (c *client) processLeafMsgArgs(arg []byte) error {
101,361✔
2780
        // Unroll splitArgs to avoid runtime/heap issues
101,361✔
2781
        a := [MAX_MSG_ARGS][]byte{}
101,361✔
2782
        args := a[:0]
101,361✔
2783
        start := -1
101,361✔
2784
        for i, b := range arg {
3,256,424✔
2785
                switch b {
3,155,063✔
2786
                case ' ', '\t', '\r', '\n':
152,713✔
2787
                        if start >= 0 {
305,426✔
2788
                                args = append(args, arg[start:i])
152,713✔
2789
                                start = -1
152,713✔
2790
                        }
152,713✔
2791
                default:
3,002,350✔
2792
                        if start < 0 {
3,256,424✔
2793
                                start = i
254,074✔
2794
                        }
254,074✔
2795
                }
2796
        }
2797
        if start >= 0 {
202,722✔
2798
                args = append(args, arg[start:])
101,361✔
2799
        }
101,361✔
2800

2801
        c.pa.arg = arg
101,361✔
2802
        switch len(args) {
101,361✔
2803
        case 0, 1:
×
2804
                return fmt.Errorf("processLeafMsgArgs Parse Error: '%s'", args)
×
2805
        case 2:
72,721✔
2806
                c.pa.reply = nil
72,721✔
2807
                c.pa.queues = nil
72,721✔
2808
                c.pa.szb = args[1]
72,721✔
2809
                c.pa.size = parseSize(args[1])
72,721✔
2810
        case 3:
6,089✔
2811
                c.pa.reply = args[1]
6,089✔
2812
                c.pa.queues = nil
6,089✔
2813
                c.pa.szb = args[2]
6,089✔
2814
                c.pa.size = parseSize(args[2])
6,089✔
2815
        default:
22,551✔
2816
                // args[1] is our reply indicator. Should be + or | normally.
22,551✔
2817
                if len(args[1]) != 1 {
22,551✔
2818
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2819
                }
×
2820
                switch args[1][0] {
22,551✔
2821
                case '+':
161✔
2822
                        c.pa.reply = args[2]
161✔
2823
                case '|':
22,390✔
2824
                        c.pa.reply = nil
22,390✔
2825
                default:
×
2826
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2827
                }
2828
                // Grab size.
2829
                c.pa.szb = args[len(args)-1]
22,551✔
2830
                c.pa.size = parseSize(c.pa.szb)
22,551✔
2831

22,551✔
2832
                // Grab queue names.
22,551✔
2833
                if c.pa.reply != nil {
22,712✔
2834
                        c.pa.queues = args[3 : len(args)-1]
161✔
2835
                } else {
22,551✔
2836
                        c.pa.queues = args[2 : len(args)-1]
22,390✔
2837
                }
22,390✔
2838
        }
2839
        if c.pa.size < 0 {
101,361✔
2840
                return fmt.Errorf("processLeafMsgArgs Bad or Missing Size: '%s'", args)
×
2841
        }
×
2842

2843
        // Common ones processed after check for arg length
2844
        c.pa.subject = args[0]
101,361✔
2845

101,361✔
2846
        return nil
101,361✔
2847
}
2848

2849
// processInboundLeafMsg is called to process an inbound msg from a leaf node.
2850
func (c *client) processInboundLeafMsg(msg []byte) {
99,929✔
2851
        // Update statistics
99,929✔
2852
        // The msg includes the CR_LF, so pull back out for accounting.
99,929✔
2853
        c.in.msgs++
99,929✔
2854
        c.in.bytes += int32(len(msg) - LEN_CR_LF)
99,929✔
2855

99,929✔
2856
        srv, acc, subject := c.srv, c.acc, string(c.pa.subject)
99,929✔
2857

99,929✔
2858
        // Mostly under testing scenarios.
99,929✔
2859
        if srv == nil || acc == nil {
99,931✔
2860
                return
2✔
2861
        }
2✔
2862

2863
        // Match the subscriptions. We will use our own L1 map if
2864
        // it's still valid, avoiding contention on the shared sublist.
2865
        var r *SublistResult
99,927✔
2866
        var ok bool
99,927✔
2867

99,927✔
2868
        genid := atomic.LoadUint64(&c.acc.sl.genid)
99,927✔
2869
        if genid == c.in.genid && c.in.results != nil {
197,474✔
2870
                r, ok = c.in.results[subject]
97,547✔
2871
        } else {
99,927✔
2872
                // Reset our L1 completely.
2,380✔
2873
                c.in.results = make(map[string]*SublistResult)
2,380✔
2874
                c.in.genid = genid
2,380✔
2875
        }
2,380✔
2876

2877
        // Go back to the sublist data structure.
2878
        if !ok {
170,035✔
2879
                r = c.acc.sl.Match(subject)
70,108✔
2880
                // Prune the results cache. Keeps us from unbounded growth. Random delete.
70,108✔
2881
                if len(c.in.results) >= maxResultCacheSize {
72,059✔
2882
                        n := 0
1,951✔
2883
                        for subj := range c.in.results {
66,334✔
2884
                                delete(c.in.results, subj)
64,383✔
2885
                                if n++; n > pruneSize {
66,334✔
2886
                                        break
1,951✔
2887
                                }
2888
                        }
2889
                }
2890
                // Then add the new cache entry.
2891
                c.in.results[subject] = r
70,108✔
2892
        }
2893

2894
        // Collect queue names if needed.
2895
        var qnames [][]byte
99,927✔
2896

99,927✔
2897
        // Check for no interest, short circuit if so.
99,927✔
2898
        // This is the fanout scale.
99,927✔
2899
        if len(r.psubs)+len(r.qsubs) > 0 {
199,543✔
2900
                flag := pmrNoFlag
99,616✔
2901
                // If we have queue subs in this cluster, then if we run in gateway
99,616✔
2902
                // mode and the remote gateways have queue subs, then we need to
99,616✔
2903
                // collect the queue groups this message was sent to so that we
99,616✔
2904
                // exclude them when sending to gateways.
99,616✔
2905
                if len(r.qsubs) > 0 && c.srv.gateway.enabled &&
99,616✔
2906
                        atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 {
111,887✔
2907
                        flag |= pmrCollectQueueNames
12,271✔
2908
                }
12,271✔
2909
                // If this is a mapped subject that means the mapped interest
2910
                // is what got us here, but this might not have a queue designation
2911
                // If that is the case, make sure we ignore to process local queue subscribers.
2912
                if len(c.pa.mapped) > 0 && len(c.pa.queues) == 0 {
99,926✔
2913
                        flag |= pmrIgnoreEmptyQueueFilter
310✔
2914
                }
310✔
2915
                _, qnames = c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, flag)
99,616✔
2916
        }
2917

2918
        // Now deal with gateways
2919
        if c.srv.gateway.enabled {
113,197✔
2920
                c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, qnames, true)
13,270✔
2921
        }
13,270✔
2922
}
2923

2924
// Handles a subscription permission violation.
2925
// See leafPermViolation() for details.
2926
func (c *client) leafSubPermViolation(subj []byte) {
309✔
2927
        c.leafPermViolation(false, subj)
309✔
2928
}
309✔
2929

2930
// Common function to process publish or subscribe leafnode permission violation.
2931
// Sends the permission violation error to the remote, logs it and closes the connection.
2932
// If this is from a server soliciting, the reconnection will be delayed.
2933
func (c *client) leafPermViolation(pub bool, subj []byte) {
309✔
2934
        if c.isSpokeLeafNode() {
618✔
2935
                // For spokes these are no-ops since the hub server told us our permissions.
309✔
2936
                // We just need to not send these over to the other side since we will get cutoff.
309✔
2937
                return
309✔
2938
        }
309✔
2939
        // FIXME(dlc) ?
2940
        c.setLeafConnectDelayIfSoliciting(leafNodeReconnectAfterPermViolation)
×
2941
        var action string
×
2942
        if pub {
×
2943
                c.sendErr(fmt.Sprintf("Permissions Violation for Publish to %q", subj))
×
2944
                action = "Publish"
×
2945
        } else {
×
2946
                c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q", subj))
×
2947
                action = "Subscription"
×
2948
        }
×
2949
        c.Errorf("%s Violation on %q - Check other side configuration", action, subj)
×
2950
        // TODO: add a new close reason that is more appropriate?
×
2951
        c.closeConnection(ProtocolViolation)
×
2952
}
2953

2954
// Invoked from generic processErr() for LEAF connections.
2955
func (c *client) leafProcessErr(errStr string) {
32✔
2956
        // Check if we got a cluster name collision.
32✔
2957
        if strings.Contains(errStr, ErrLeafNodeHasSameClusterName.Error()) {
35✔
2958
                _, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterClusterNameSame)
3✔
2959
                c.Errorf("Leafnode connection dropped with same cluster name error. Delaying attempt to reconnect for %v", delay)
3✔
2960
                return
3✔
2961
        }
3✔
2962

2963
        // We will look for Loop detected error coming from the other side.
2964
        // If we solicit, set the connect delay.
2965
        if !strings.Contains(errStr, "Loop detected") {
50✔
2966
                return
21✔
2967
        }
21✔
2968
        c.handleLeafNodeLoop(false)
8✔
2969
}
2970

2971
// If this leaf connection solicits, sets the connect delay to the given value,
2972
// or the one from the server option's LeafNode.connDelay if one is set (for tests).
2973
// Returns the connection's account name and delay.
2974
func (c *client) setLeafConnectDelayIfSoliciting(delay time.Duration) (string, time.Duration) {
20✔
2975
        c.mu.Lock()
20✔
2976
        if c.isSolicitedLeafNode() {
31✔
2977
                if s := c.srv; s != nil {
22✔
2978
                        if srvdelay := s.getOpts().LeafNode.connDelay; srvdelay != 0 {
16✔
2979
                                delay = srvdelay
5✔
2980
                        }
5✔
2981
                }
2982
                c.leaf.remote.setConnectDelay(delay)
11✔
2983
        }
2984
        accName := c.acc.Name
20✔
2985
        c.mu.Unlock()
20✔
2986
        return accName, delay
20✔
2987
}
2988

2989
// For the given remote Leafnode configuration, this function returns
2990
// if TLS is required, and if so, will return a clone of the TLS Config
2991
// (since some fields will be changed during handshake), the TLS server
2992
// name that is remembered, and the TLS timeout.
2993
func (c *client) leafNodeGetTLSConfigForSolicit(remote *leafNodeCfg) (bool, *tls.Config, string, float64) {
1,835✔
2994
        var (
1,835✔
2995
                tlsConfig  *tls.Config
1,835✔
2996
                tlsName    string
1,835✔
2997
                tlsTimeout float64
1,835✔
2998
        )
1,835✔
2999

1,835✔
3000
        remote.RLock()
1,835✔
3001
        defer remote.RUnlock()
1,835✔
3002

1,835✔
3003
        tlsRequired := remote.TLS || remote.TLSConfig != nil
1,835✔
3004
        if tlsRequired {
1,910✔
3005
                if remote.TLSConfig != nil {
127✔
3006
                        tlsConfig = remote.TLSConfig.Clone()
52✔
3007
                } else {
75✔
3008
                        tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}
23✔
3009
                }
23✔
3010
                tlsName = remote.tlsName
75✔
3011
                tlsTimeout = remote.TLSTimeout
75✔
3012
                if tlsTimeout == 0 {
115✔
3013
                        tlsTimeout = float64(TLS_TIMEOUT / time.Second)
40✔
3014
                }
40✔
3015
        }
3016

3017
        return tlsRequired, tlsConfig, tlsName, tlsTimeout
1,835✔
3018
}
3019

3020
// Initiates the LeafNode Websocket connection by:
3021
// - doing the TLS handshake if needed
3022
// - sending the HTTP request
3023
// - waiting for the HTTP response
3024
//
3025
// Since some bufio reader is used to consume the HTTP response, this function
3026
// returns the slice of buffered bytes (if any) so that the readLoop that will
3027
// be started after that consume those first before reading from the socket.
3028
// The boolean
3029
//
3030
// Lock held on entry.
3031
func (c *client) leafNodeSolicitWSConnection(opts *Options, rURL *url.URL, remote *leafNodeCfg) ([]byte, ClosedState, error) {
43✔
3032
        remote.RLock()
43✔
3033
        compress := remote.Websocket.Compression
43✔
3034
        // By default the server will mask outbound frames, but it can be disabled with this option.
43✔
3035
        noMasking := remote.Websocket.NoMasking
43✔
3036
        infoTimeout := remote.FirstInfoTimeout
43✔
3037
        remote.RUnlock()
43✔
3038
        // Will do the client-side TLS handshake if needed.
43✔
3039
        tlsRequired, err := c.leafClientHandshakeIfNeeded(remote, opts)
43✔
3040
        if err != nil {
47✔
3041
                // 0 will indicate that the connection was already closed
4✔
3042
                return nil, 0, err
4✔
3043
        }
4✔
3044

3045
        // For http request, we need the passed URL to contain either http or https scheme.
3046
        scheme := "http"
39✔
3047
        if tlsRequired {
47✔
3048
                scheme = "https"
8✔
3049
        }
8✔
3050
        // We will use the `/leafnode` path to tell the accepting WS server that it should
3051
        // create a LEAF connection, not a CLIENT.
3052
        // In case we use the user's URL path in the future, make sure we append the user's
3053
        // path to our `/leafnode` path.
3054
        lpath := leafNodeWSPath
39✔
3055
        if curPath := rURL.EscapedPath(); curPath != _EMPTY_ {
60✔
3056
                if curPath[0] == '/' {
42✔
3057
                        curPath = curPath[1:]
21✔
3058
                }
21✔
3059
                lpath = path.Join(curPath, lpath)
21✔
3060
        } else {
18✔
3061
                lpath = lpath[1:]
18✔
3062
        }
18✔
3063
        ustr := fmt.Sprintf("%s://%s/%s", scheme, rURL.Host, lpath)
39✔
3064
        u, _ := url.Parse(ustr)
39✔
3065
        req := &http.Request{
39✔
3066
                Method:     "GET",
39✔
3067
                URL:        u,
39✔
3068
                Proto:      "HTTP/1.1",
39✔
3069
                ProtoMajor: 1,
39✔
3070
                ProtoMinor: 1,
39✔
3071
                Header:     make(http.Header),
39✔
3072
                Host:       u.Host,
39✔
3073
        }
39✔
3074
        wsKey, err := wsMakeChallengeKey()
39✔
3075
        if err != nil {
39✔
3076
                return nil, WriteError, err
×
3077
        }
×
3078

3079
        req.Header["Upgrade"] = []string{"websocket"}
39✔
3080
        req.Header["Connection"] = []string{"Upgrade"}
39✔
3081
        req.Header["Sec-WebSocket-Key"] = []string{wsKey}
39✔
3082
        req.Header["Sec-WebSocket-Version"] = []string{"13"}
39✔
3083
        if compress {
48✔
3084
                req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue)
9✔
3085
        }
9✔
3086
        if noMasking {
49✔
3087
                req.Header.Add(wsNoMaskingHeader, wsNoMaskingValue)
10✔
3088
        }
10✔
3089
        c.nc.SetDeadline(time.Now().Add(infoTimeout))
39✔
3090
        if err := req.Write(c.nc); err != nil {
39✔
3091
                return nil, WriteError, err
×
3092
        }
×
3093

3094
        var resp *http.Response
39✔
3095

39✔
3096
        br := bufio.NewReaderSize(c.nc, MAX_CONTROL_LINE_SIZE)
39✔
3097
        resp, err = http.ReadResponse(br, req)
39✔
3098
        if err == nil &&
39✔
3099
                (resp.StatusCode != 101 ||
39✔
3100
                        !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
39✔
3101
                        !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
39✔
3102
                        resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) {
40✔
3103

1✔
3104
                err = fmt.Errorf("invalid websocket connection")
1✔
3105
        }
1✔
3106
        // Check compression extension...
3107
        if err == nil && c.ws.compress {
48✔
3108
                // Check that not only permessage-deflate extension is present, but that
9✔
3109
                // we also have server and client no context take over.
9✔
3110
                srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header, false)
9✔
3111

9✔
3112
                // If server does not support compression, then simply disable it in our side.
9✔
3113
                if !srvCompress {
13✔
3114
                        c.ws.compress = false
4✔
3115
                } else if !noCtxTakeover {
9✔
3116
                        err = fmt.Errorf("compression negotiation error")
×
3117
                }
×
3118
        }
3119
        // Same for no masking...
3120
        if err == nil && noMasking {
49✔
3121
                // Check if server accepts no masking
10✔
3122
                if resp.Header.Get(wsNoMaskingHeader) != wsNoMaskingValue {
11✔
3123
                        // Nope, need to mask our writes as any client would do.
1✔
3124
                        c.ws.maskwrite = true
1✔
3125
                }
1✔
3126
        }
3127
        if resp != nil {
67✔
3128
                resp.Body.Close()
28✔
3129
        }
28✔
3130
        if err != nil {
51✔
3131
                return nil, ReadError, err
12✔
3132
        }
12✔
3133
        c.Debugf("Leafnode compression=%v masking=%v", c.ws.compress, c.ws.maskwrite)
27✔
3134

27✔
3135
        var preBuf []byte
27✔
3136
        // We have to slurp whatever is in the bufio reader and pass that to the readloop.
27✔
3137
        if n := br.Buffered(); n != 0 {
27✔
3138
                preBuf, _ = br.Peek(n)
×
3139
        }
×
3140
        return preBuf, 0, nil
27✔
3141
}
3142

3143
const connectProcessTimeout = 2 * time.Second
3144

3145
// This is invoked for remote LEAF remote connections after processing the INFO
3146
// protocol.
3147
func (s *Server) leafNodeResumeConnectProcess(c *client) {
642✔
3148
        clusterName := s.ClusterName()
642✔
3149

642✔
3150
        c.mu.Lock()
642✔
3151
        if c.isClosed() {
642✔
3152
                c.mu.Unlock()
×
3153
                return
×
3154
        }
×
3155
        if err := c.sendLeafConnect(clusterName, c.headers); err != nil {
644✔
3156
                c.mu.Unlock()
2✔
3157
                c.closeConnection(WriteError)
2✔
3158
                return
2✔
3159
        }
2✔
3160

3161
        // Spin up the write loop.
3162
        s.startGoRoutine(func() { c.writeLoop() })
1,280✔
3163

3164
        // timeout leafNodeFinishConnectProcess
3165
        c.ping.tmr = time.AfterFunc(connectProcessTimeout, func() {
640✔
3166
                c.mu.Lock()
×
3167
                // check if leafNodeFinishConnectProcess was called and prevent later leafNodeFinishConnectProcess
×
3168
                if !c.flags.setIfNotSet(connectProcessFinished) {
×
3169
                        c.mu.Unlock()
×
3170
                        return
×
3171
                }
×
3172
                clearTimer(&c.ping.tmr)
×
3173
                closed := c.isClosed()
×
3174
                c.mu.Unlock()
×
3175
                if !closed {
×
3176
                        c.sendErrAndDebug("Stale Leaf Node Connection - Closing")
×
3177
                        c.closeConnection(StaleConnection)
×
3178
                }
×
3179
        })
3180
        c.mu.Unlock()
640✔
3181
        c.Debugf("Remote leafnode connect msg sent")
640✔
3182
}
3183

3184
// This is invoked for remote LEAF connections after processing the INFO
3185
// protocol and leafNodeResumeConnectProcess.
3186
// This will send LS+ the CONNECT protocol and register the leaf node.
3187
func (s *Server) leafNodeFinishConnectProcess(c *client) {
621✔
3188
        c.mu.Lock()
621✔
3189
        if !c.flags.setIfNotSet(connectProcessFinished) {
621✔
3190
                c.mu.Unlock()
×
3191
                return
×
3192
        }
×
3193
        if c.isClosed() {
621✔
3194
                c.mu.Unlock()
×
3195
                s.removeLeafNodeConnection(c)
×
3196
                return
×
3197
        }
×
3198
        remote := c.leaf.remote
621✔
3199
        // Check if we will need to send the system connect event.
621✔
3200
        remote.RLock()
621✔
3201
        sendSysConnectEvent := remote.Hub
621✔
3202
        remote.RUnlock()
621✔
3203

621✔
3204
        // Capture account before releasing lock
621✔
3205
        acc := c.acc
621✔
3206
        // cancel connectProcessTimeout
621✔
3207
        clearTimer(&c.ping.tmr)
621✔
3208
        c.mu.Unlock()
621✔
3209

621✔
3210
        // Make sure we register with the account here.
621✔
3211
        if err := c.registerWithAccount(acc); err != nil {
623✔
3212
                if err == ErrTooManyAccountConnections {
2✔
3213
                        c.maxAccountConnExceeded()
×
3214
                        return
×
3215
                } else if err == ErrLeafNodeLoop {
4✔
3216
                        c.handleLeafNodeLoop(true)
2✔
3217
                        return
2✔
3218
                }
2✔
3219
                c.Errorf("Registering leaf with account %s resulted in error: %v", acc.Name, err)
×
3220
                c.closeConnection(ProtocolViolation)
×
3221
                return
×
3222
        }
3223
        s.addLeafNodeConnection(c, _EMPTY_, _EMPTY_, false)
619✔
3224
        s.initLeafNodeSmapAndSendSubs(c)
619✔
3225
        if sendSysConnectEvent {
625✔
3226
                s.sendLeafNodeConnect(acc)
6✔
3227
        }
6✔
3228

3229
        // The above functions are not atomically under the client
3230
        // lock doing those operations. It is possible - since we
3231
        // have started the read/write loops - that the connection
3232
        // is closed before or in between. This would leave the
3233
        // closed LN connection possible registered with the account
3234
        // and/or the server's leafs map. So check if connection
3235
        // is closed, and if so, manually cleanup.
3236
        c.mu.Lock()
619✔
3237
        closed := c.isClosed()
619✔
3238
        if !closed {
1,238✔
3239
                c.setFirstPingTimer()
619✔
3240
        }
619✔
3241
        c.mu.Unlock()
619✔
3242
        if closed {
619✔
3243
                s.removeLeafNodeConnection(c)
×
3244
                if prev := acc.removeClient(c); prev == 1 {
×
3245
                        s.decActiveAccounts()
×
3246
                }
×
3247
        }
3248
}
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