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

nats-io / nats-server / 15514983917

06 Jun 2025 03:53PM UTC coverage: 85.666% (+0.1%) from 85.557%
15514983917

push

github

web-flow
Include leaf node connections in `connz` (#6949)

This worked if you used `nats server report connections` inside an
account because we would automatically fill in `Account` in that case,
and this worked if you specified `Account` because the account map
included both clients and leafs, but the global `s.clients` map didn't
so `/connz` or a system account request would omit `s.leafs`.

Fixes #6930.

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

69973 of 81681 relevant lines covered (85.67%)

362629.51 hits per line

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

90.48
/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,974✔
120
        return c.kind == LEAF && c.leaf.remote != nil
1,974✔
121
}
1,974✔
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,299,569✔
126
        return c.kind == LEAF && c.leaf.isSpoke
6,299,569✔
127
}
6,299,569✔
128

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

133
// This will spin up go routines to solicit the remote leaf node connections.
134
func (s *Server) solicitLeafNodeRemotes(remotes []*RemoteLeafOpts) {
541✔
135
        sysAccName := _EMPTY_
541✔
136
        sAcc := s.SystemAccount()
541✔
137
        if sAcc != nil {
1,059✔
138
                sysAccName = sAcc.Name
518✔
139
        }
518✔
140
        addRemote := func(r *RemoteLeafOpts, isSysAccRemote bool) *leafNodeCfg {
1,216✔
141
                s.mu.Lock()
675✔
142
                remote := newLeafNodeCfg(r)
675✔
143
                creds := remote.Credentials
675✔
144
                accName := remote.LocalAccount
675✔
145
                s.leafRemoteCfgs = append(s.leafRemoteCfgs, remote)
675✔
146
                // Print notice if
675✔
147
                if isSysAccRemote {
767✔
148
                        if len(remote.DenyExports) > 0 {
93✔
149
                                s.Noticef("Remote for System Account uses restricted export permissions")
1✔
150
                        }
1✔
151
                        if len(remote.DenyImports) > 0 {
93✔
152
                                s.Noticef("Remote for System Account uses restricted import permissions")
1✔
153
                        }
1✔
154
                }
155
                s.mu.Unlock()
675✔
156
                if creds != _EMPTY_ {
723✔
157
                        contents, err := os.ReadFile(creds)
48✔
158
                        defer wipeSlice(contents)
48✔
159
                        if err != nil {
48✔
160
                                s.Errorf("Error reading LeafNode Remote Credentials file %q: %v", creds, err)
×
161
                        } else if items := credsRe.FindAllSubmatch(contents, -1); len(items) < 2 {
48✔
162
                                s.Errorf("LeafNode Remote Credentials file %q malformed", creds)
×
163
                        } else if _, err := nkeys.FromSeed(items[1][1]); err != nil {
48✔
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 {
48✔
166
                                s.Errorf("LeafNode Remote Credentials file %q has malformed user jwt", creds)
×
167
                        } else if isSysAccRemote {
52✔
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 {
44✔
172
                                if !uc.Permissions.Pub.Empty() || !uc.Permissions.Sub.Empty() || uc.Permissions.Resp != nil {
50✔
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
675✔
178
        }
179
        for _, r := range remotes {
1,216✔
180
                remote := addRemote(r, r.LocalAccount == sysAccName)
675✔
181
                s.startGoRoutine(func() { s.connectToRemoteLeafNode(remote, true) })
1,350✔
182
        }
183
}
184

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

195
// Ensure that leafnode is properly configured.
196
func validateLeafNode(o *Options) error {
8,060✔
197
        if err := validateLeafNodeAuthOptions(o); err != nil {
8,062✔
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,758✔
203
                if r.LocalAccount == _EMPTY_ {
1,128✔
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 {
15,807✔
210
                accNames := map[string]struct{}{}
7,749✔
211
                for _, a := range o.Accounts {
16,420✔
212
                        accNames[a.Name] = struct{}{}
8,671✔
213
                }
8,671✔
214
                // global account is always created
215
                accNames[DEFAULT_GLOBAL_ACCOUNT] = struct{}{}
7,749✔
216
                // in the context of leaf nodes, empty account means global account
7,749✔
217
                accNames[_EMPTY_] = struct{}{}
7,749✔
218
                // system account either exists or, if not disabled, will be created
7,749✔
219
                if o.SystemAccount == _EMPTY_ && !o.NoSystemAccount {
13,808✔
220
                        accNames[DEFAULT_SYSTEM_ACCOUNT] = struct{}{}
6,059✔
221
                }
6,059✔
222
                checkAccountExists := func(accName string, cfgType string) error {
16,204✔
223
                        if _, ok := accNames[accName]; !ok {
8,457✔
224
                                return fmt.Errorf("cannot find local account %q specified in leafnode %s", accName, cfgType)
2✔
225
                        }
2✔
226
                        return nil
8,453✔
227
                }
228
                if err := checkAccountExists(o.LeafNode.Account, "authorization"); err != nil {
7,750✔
229
                        return err
1✔
230
                }
1✔
231
                for _, lu := range o.LeafNode.Users {
7,758✔
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,447✔
240
                        if err := checkAccountExists(r.LocalAccount, "remote"); err != nil {
700✔
241
                                return err
1✔
242
                        }
1✔
243
                }
244
        } else {
309✔
245
                if len(o.LeafNode.Users) != 0 {
310✔
246
                        return fmt.Errorf("operator mode does not allow specifying users in leafnode config")
1✔
247
                }
1✔
248
                for _, r := range o.LeafNode.Remotes {
309✔
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) {
308✔
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_ {
11,699✔
263
                if err := validateAndNormalizeCompressionOption(&o.LeafNode.Compression, CompressionS2Auto); err != nil {
3,651✔
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,746✔
270
                if len(rcfg.URLs) >= 2 {
902✔
271
                        firstIsWS, ok := isWSURL(rcfg.URLs[0]), true
204✔
272
                        for i := 1; i < len(rcfg.URLs); i++ {
653✔
273
                                u := rcfg.URLs[i]
449✔
274
                                if isWS := isWSURL(u); isWS && !firstIsWS || !isWS && firstIsWS {
456✔
275
                                        ok = false
7✔
276
                                        break
7✔
277
                                }
278
                        }
279
                        if !ok {
211✔
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,382✔
285
                        if err := validateAndNormalizeCompressionOption(&rcfg.Compression, CompressionS2Auto); err != nil {
696✔
286
                                return err
5✔
287
                        }
5✔
288
                }
289
        }
290

291
        if o.LeafNode.Port == 0 {
13,028✔
292
                return nil
4,992✔
293
        }
4,992✔
294

295
        // If MinVersion is defined, check that it is valid.
296
        if mv := o.LeafNode.MinVersion; mv != _EMPTY_ {
3,048✔
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,403✔
307
                return nil
2,361✔
308
        }
2,361✔
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_ {
682✔
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 {
680✔
315
                return fmt.Errorf("leafnode: %v", err)
×
316
        }
×
317
        return nil
680✔
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,109✔
335
        if len(o.LeafNode.Users) == 0 {
16,198✔
336
                return nil
8,089✔
337
        }
8,089✔
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 {
675✔
394
        cfg := &leafNodeCfg{
675✔
395
                RemoteLeafOpts: remote,
675✔
396
                urls:           make([]*url.URL, 0, len(remote.URLs)),
675✔
397
        }
675✔
398
        if len(remote.DenyExports) > 0 || len(remote.DenyImports) > 0 {
683✔
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...)
675✔
411
        // If allowed to randomize, do it on our copy of URLs
675✔
412
        if !remote.NoRandomize {
1,348✔
413
                rand.Shuffle(len(cfg.urls), func(i, j int) {
1,079✔
414
                        cfg.urls[i], cfg.urls[j] = cfg.urls[j], cfg.urls[i]
406✔
415
                })
406✔
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,786✔
421
                cfg.saveTLSHostname(u)
1,111✔
422
                cfg.saveUserPassword(u)
1,111✔
423
                // If the url(s) have the "wss://" scheme, and we don't have a TLS
1,111✔
424
                // config, mark that we should be using TLS anyway.
1,111✔
425
                if !cfg.TLS && isWSSURL(u) {
1,112✔
426
                        cfg.TLS = true
1✔
427
                }
1✔
428
        }
429
        return cfg
675✔
430
}
431

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

447
// Returns the current URL
448
func (cfg *leafNodeCfg) getCurrentURL() *url.URL {
80✔
449
        cfg.RLock()
80✔
450
        defer cfg.RUnlock()
80✔
451
        return cfg.curURL
80✔
452
}
80✔
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 {
847✔
457
        cfg.RLock()
847✔
458
        delay := cfg.connDelay
847✔
459
        cfg.RUnlock()
847✔
460
        return delay
847✔
461
}
847✔
462

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

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

485
const sharedSysAccDelay = 250 * time.Millisecond
486

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

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

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

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

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

522
        var conn net.Conn
841✔
523

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

841✔
526
        attempts := 0
841✔
527

841✔
528
        for s.isRunning() && s.remoteLeafNodeStillValid(remote) {
1,865✔
529
                rURL := remote.pickNextURL()
1,024✔
530
                url, err := s.getRandomIP(resolver, rURL.Host, nil)
1,024✔
531
                if err == nil {
2,043✔
532
                        var ipStr string
1,019✔
533
                        if url != rURL.Host {
1,089✔
534
                                ipStr = fmt.Sprintf(" (%s)", url)
70✔
535
                        }
70✔
536
                        // Some test may want to disable remotes from connecting
537
                        if s.isLeafConnectDisabled() {
1,154✔
538
                                s.Debugf("Will not attempt to connect to remote server on %q%s, leafnodes currently disabled", rURL.Host, ipStr)
135✔
539
                                err = ErrLeafNodeDisabled
135✔
540
                        } else {
1,019✔
541
                                s.Debugf("Trying to connect as leafnode to remote server on %q%s", rURL.Host, ipStr)
884✔
542
                                conn, err = natsDialTimeout("tcp", url, dialTimeout)
884✔
543
                        }
884✔
544
                }
545
                if err != nil {
1,299✔
546
                        jitter := time.Duration(rand.Int63n(int64(reconnectDelay)))
275✔
547
                        delay := reconnectDelay + jitter
275✔
548
                        attempts++
275✔
549
                        if s.shouldReportConnectErr(firstConnect, attempts) {
536✔
550
                                s.Errorf(connErrFmt, rURL.Host, attempts, err)
261✔
551
                        } else {
275✔
552
                                s.Debugf(connErrFmt, rURL.Host, attempts, err)
14✔
553
                        }
14✔
554
                        remote.Lock()
275✔
555
                        // if we are using a delay to start migrating assets, kick off a migrate timer.
275✔
556
                        if remote.jsMigrateTimer == nil && jetstreamMigrateDelay > 0 {
283✔
557
                                remote.jsMigrateTimer = time.AfterFunc(jetstreamMigrateDelay, func() {
16✔
558
                                        s.checkJetStreamMigrate(remote)
8✔
559
                                })
8✔
560
                        }
561
                        remote.Unlock()
275✔
562
                        select {
275✔
563
                        case <-s.quitCh:
90✔
564
                                remote.cancelMigrateTimer()
90✔
565
                                return
90✔
566
                        case <-time.After(delay):
185✔
567
                                // Check if we should migrate any JetStream assets immediately while this remote is down.
185✔
568
                                // This will be used if JetStreamClusterMigrateDelay was not set
185✔
569
                                if jetstreamMigrateDelay == 0 {
296✔
570
                                        s.checkJetStreamMigrate(remote)
111✔
571
                                }
111✔
572
                                continue
185✔
573
                        }
574
                }
575
                remote.cancelMigrateTimer()
749✔
576
                if !s.remoteLeafNodeStillValid(remote) {
749✔
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)
749✔
584

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

749✔
588
                return
749✔
589
        }
590
}
591

592
func (cfg *leafNodeCfg) cancelMigrateTimer() {
839✔
593
        cfg.Lock()
839✔
594
        stopAndClearTimer(&cfg.jsMigrateTimer)
839✔
595
        cfg.Unlock()
839✔
596
}
839✔
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) {
749✔
600
        s.mu.RLock()
749✔
601
        accName := remote.LocalAccount
749✔
602
        s.mu.RUnlock()
749✔
603

749✔
604
        acc, err := s.LookupAccount(accName)
749✔
605
        if err != nil {
751✔
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()
747✔
611
        defer acc.jscmMu.Unlock()
747✔
612

747✔
613
        // Walk all streams looking for any clustered stream, skip otherwise.
747✔
614
        for _, mset := range acc.streams() {
762✔
615
                node := mset.raftNode()
15✔
616
                if node == nil {
22✔
617
                        // Not R>1
7✔
618
                        continue
7✔
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) {
119✔
634
        s.mu.RLock()
119✔
635
        accName, shouldMigrate := remote.LocalAccount, remote.JetStreamClusterMigrate
119✔
636
        s.mu.RUnlock()
119✔
637

119✔
638
        if !shouldMigrate {
169✔
639
                return
50✔
640
        }
50✔
641

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

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

69✔
651
        // Walk all streams looking for any clustered stream, skip otherwise.
69✔
652
        // If we are the leader force stepdown.
69✔
653
        for _, mset := range acc.streams() {
104✔
654
                node := mset.raftNode()
35✔
655
                if node == nil {
35✔
656
                        // Not R>1
×
657
                        continue
×
658
                }
659
                // Collect any consumers
660
                for _, o := range mset.getConsumers() {
56✔
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()
35✔
669
                // Ensure we can not become a leader while in this state.
35✔
670
                node.SetObserver(true)
35✔
671
        }
672
}
673

674
// Helper for checking.
675
func (s *Server) isLeafConnectDisabled() bool {
1,019✔
676
        s.mu.RLock()
1,019✔
677
        defer s.mu.RUnlock()
1,019✔
678
        return s.leafDisableConnect
1,019✔
679
}
1,019✔
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,716✔
690
        if cfg.tlsName == _EMPTY_ && net.ParseIP(u.Hostname()) == nil {
1,736✔
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,111✔
698
        if cfg.username == _EMPTY_ && u.User != nil {
1,370✔
699
                cfg.username = u.User.Username()
259✔
700
                cfg.password, _ = u.User.Password()
259✔
701
        }
259✔
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,011✔
707
        // Snapshot server options.
3,011✔
708
        opts := s.getOpts()
3,011✔
709

3,011✔
710
        port := opts.LeafNode.Port
3,011✔
711
        if port == -1 {
5,873✔
712
                port = 0
2,862✔
713
        }
2,862✔
714

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

719
        s.mu.Lock()
3,010✔
720
        hp := net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(port))
3,010✔
721
        l, e := natsListen("tcp", hp)
3,010✔
722
        s.leafNodeListenerErr = e
3,010✔
723
        if e != nil {
3,010✔
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,010✔
730
                net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
3,010✔
731

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

758
        s.leafNodeInfo = info
3,010✔
759
        // Possibly override Host/Port and set IP based on Cluster.Advertise
3,010✔
760
        if err := s.setLeafNodeInfoHostPortAndIP(); err != nil {
3,010✔
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,010✔
767
        s.generateLeafNodeInfoJSON()
3,010✔
768

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

3,010✔
772
        // As of now, a server that does not have remotes configured would
3,010✔
773
        // never solicit a connection, so we should not have to warn if
3,010✔
774
        // InsecureSkipVerify is set in main LeafNodes config (since
3,010✔
775
        // this TLS setting matters only when soliciting a connection).
3,010✔
776
        // Still, warn if insecure is set in any of LeafNode block.
3,010✔
777
        // We need to check remotes, even if tls is not required on accept.
3,010✔
778
        warn := tlsRequired && opts.LeafNode.TLSConfig.InsecureSkipVerify
3,010✔
779
        if !warn {
6,016✔
780
                for _, r := range opts.LeafNode.Remotes {
3,163✔
781
                        if r.TLSConfig != nil && r.TLSConfig.InsecureSkipVerify {
158✔
782
                                warn = true
1✔
783
                                break
1✔
784
                        }
785
                }
786
        }
787
        if warn {
3,015✔
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,786✔
791
        s.mu.Unlock()
3,010✔
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 {
628✔
800
        // We support basic user/pass and operator based user JWT with signatures.
628✔
801
        cinfo := leafConnectInfo{
628✔
802
                Version:       VERSION,
628✔
803
                ID:            c.srv.info.ID,
628✔
804
                Domain:        c.srv.info.Domain,
628✔
805
                Name:          c.srv.info.Name,
628✔
806
                Hub:           c.leaf.remote.Hub,
628✔
807
                Cluster:       clusterName,
628✔
808
                Headers:       headers,
628✔
809
                JetStream:     c.acc.jetStreamConfigured(),
628✔
810
                DenyPub:       c.leaf.remote.DenyImports,
628✔
811
                Compression:   c.leaf.compression,
628✔
812
                RemoteAccount: c.acc.GetName(),
628✔
813
                Proto:         c.srv.getServerProto(),
628✔
814
        }
628✔
815

628✔
816
        // If a signature callback is specified, this takes precedence over anything else.
628✔
817
        if cb := c.leaf.remote.SignatureCB; cb != nil {
631✔
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_ {
675✔
833
                // Check for credentials first, that will take precedence..
50✔
834
                c.Debugf("Authenticating with credentials file %q", c.leaf.remote.Credentials)
50✔
835
                contents, err := os.ReadFile(creds)
50✔
836
                if err != nil {
50✔
837
                        c.Errorf("%v", err)
×
838
                        return err
×
839
                }
×
840
                defer wipeSlice(contents)
50✔
841
                items := credsRe.FindAllSubmatch(contents, -1)
50✔
842
                if len(items) < 2 {
50✔
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]
50✔
849
                tmp := make([]byte, len(raw))
50✔
850
                copy(tmp, raw)
50✔
851
                // Seed is second item.
50✔
852
                kp, err := nkeys.FromSeed(items[1][1])
50✔
853
                if err != nil {
50✔
854
                        c.Errorf("Credentials file has malformed seed")
×
855
                        return err
×
856
                }
×
857
                // Wipe our key on exit.
858
                defer kp.Wipe()
50✔
859

50✔
860
                sigraw, _ := kp.Sign(c.nonce)
50✔
861
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
50✔
862
                cinfo.JWT = bytesToString(tmp)
50✔
863
                cinfo.Sig = sig
50✔
864
        } else if nkey := c.leaf.remote.Nkey; nkey != _EMPTY_ {
577✔
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 {
905✔
881
                // For backward compatibility, if only username is provided, set both
279✔
882
                // Token and User, not just Token.
279✔
883
                cinfo.User = userInfo.Username()
279✔
884
                var ok bool
279✔
885
                cinfo.Pass, ok = userInfo.Password()
279✔
886
                if !ok {
285✔
887
                        cinfo.Token = cinfo.User
6✔
888
                }
6✔
889
        } else if c.leaf.remote.username != _EMPTY_ {
350✔
890
                cinfo.User = c.leaf.remote.username
3✔
891
                cinfo.Pass = c.leaf.remote.password
3✔
892
        }
3✔
893
        b, err := json.Marshal(cinfo)
626✔
894
        if err != nil {
626✔
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)))
626✔
902
        return nil
626✔
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,515✔
908
        clone := s.leafNodeInfo
2,515✔
909
        // Copy the array of urls.
2,515✔
910
        if len(s.leafNodeInfo.LeafNodeURLs) > 0 {
4,567✔
911
                clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...)
2,052✔
912
        }
2,052✔
913
        return &clone
2,515✔
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 {
5,991✔
921
        if s.leafURLsMap.addUrl(urlStr) {
11,977✔
922
                s.generateLeafNodeInfoJSON()
5,986✔
923
                return true
5,986✔
924
        }
5,986✔
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 {
5,991✔
933
        // Don't need to do this if we are removing the route connection because
5,991✔
934
        // we are shuting down...
5,991✔
935
        if s.isShuttingDown() {
9,147✔
936
                return false
3,156✔
937
        }
3,156✔
938
        if s.leafURLsMap.removeUrl(urlStr) {
5,666✔
939
                s.generateLeafNodeInfoJSON()
2,831✔
940
                return true
2,831✔
941
        }
2,831✔
942
        return false
4✔
943
}
944

945
// Server lock is held on entry
946
func (s *Server) generateLeafNodeInfoJSON() {
11,827✔
947
        s.leafNodeInfo.Cluster = s.cachedClusterName()
11,827✔
948
        s.leafNodeInfo.LeafNodeURLs = s.leafURLsMap.getAsStringSlice()
11,827✔
949
        s.leafNodeInfo.WSConnectURLs = s.websocket.connectURLsMap.getAsStringSlice()
11,827✔
950
        s.leafNodeInfoJSON = generateInfoJSON(&s.leafNodeInfo)
11,827✔
951
}
11,827✔
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() {
8,817✔
956
        for _, c := range s.leafs {
8,920✔
957
                c.mu.Lock()
103✔
958
                c.enqueueProto(s.leafNodeInfoJSON)
103✔
959
                c.mu.Unlock()
103✔
960
        }
103✔
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,552✔
965
        // Snapshot server options.
1,552✔
966
        opts := s.getOpts()
1,552✔
967

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

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

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

1,552✔
984
        // For remote, check if the scheme starts with "ws", if so, we will initiate
1,552✔
985
        // a remote Leaf Node connection as a websocket connection.
1,552✔
986
        if remote != nil && rURL != nil && isWSURL(rURL) {
1,595✔
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,552✔
994
        var acc *Account
1,552✔
995
        var remoteSuffix string
1,552✔
996
        if remote != nil {
2,301✔
997
                // For now, if lookup fails, we will constantly try
749✔
998
                // to recreate this LN connection.
749✔
999
                lacc := remote.LocalAccount
749✔
1000
                var err error
749✔
1001
                acc, err = s.LookupAccount(lacc)
749✔
1002
                if err != nil {
751✔
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())
747✔
1012
        }
1013

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

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

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

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

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

1,550✔
1067
        var preBuf []byte
1,550✔
1068
        if solicited {
2,297✔
1069
                // For websocket connection, we need to send an HTTP request,
747✔
1070
                // and get the response before starting the readLoop to get
747✔
1071
                // the INFO, etc..
747✔
1072
                if c.isWebsocket() {
790✔
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 {
704✔
1086
                        // If configured to do TLS handshake first
704✔
1087
                        if tlsFirst {
708✔
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))
703✔
1095
                }
1096

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

803✔
1108
                var pre []byte
803✔
1109
                // We need first to check for "TLS First" fallback delay.
803✔
1110
                if tlsFirstFallback > 0 {
804✔
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,601✔
1134
                        // We have to send from this go routine because we may
798✔
1135
                        // have to block for TLS handshake before we start our
798✔
1136
                        // writeLoop go routine. The other side needs to receive
798✔
1137
                        // this before it can initiate the TLS handshake..
798✔
1138
                        c.sendProtoNow(proto)
798✔
1139

798✔
1140
                        // The above call could have marked the connection as closed (due to TCP error).
798✔
1141
                        if c.isClosed() {
798✔
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 {
876✔
1150
                        // If we have a prebuffer create a multi-reader.
73✔
1151
                        if len(pre) > 0 {
73✔
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 {
119✔
1156
                                c.mu.Unlock()
46✔
1157
                                return nil
46✔
1158
                        }
46✔
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 {
760✔
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)
757✔
1182
                if needsCompression(opts.LeafNode.Compression.Mode) {
1,309✔
1183
                        c.ping.tmr = time.AfterFunc(timeout, func() {
561✔
1184
                                c.authTimeout()
9✔
1185
                        })
9✔
1186
                } else {
205✔
1187
                        c.setAuthTimer(timeout)
205✔
1188
                }
205✔
1189
        }
1190

1191
        // Keep track in case server is shutdown before we can successfully register.
1192
        if !s.addToTempClients(c.cid, c) {
1,488✔
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) })
2,972✔
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,243✔
1205
                s.startGoRoutine(func() { c.writeLoop() })
1,514✔
1206
        }
1207

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

1,486✔
1210
        return c
1,486✔
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,803✔
1218
        // Check if TLS is required and gather TLS config variables.
1,803✔
1219
        tlsRequired, tlsConfig, tlsName, tlsTimeout := c.leafNodeGetTLSConfigForSolicit(remote)
1,803✔
1220
        if !tlsRequired {
3,526✔
1221
                return false, nil
1,723✔
1222
        }
1,723✔
1223

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

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

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

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

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

1,210✔
1274
                var co *CompressionOpts
1,210✔
1275
                if !didSolicit {
1,737✔
1276
                        co = &opts.LeafNode.Compression
527✔
1277
                } else {
1,210✔
1278
                        co = &remote.Compression
683✔
1279
                }
683✔
1280
                if needsCompression(co.Mode) {
2,409✔
1281
                        // Release client lock since following function will need server lock.
1,199✔
1282
                        c.mu.Unlock()
1,199✔
1283
                        compress, err := s.negotiateLeafCompression(c, didSolicit, info.Compression, co)
1,199✔
1284
                        if err != nil {
1,199✔
1285
                                c.sendErrAndErr(err.Error())
×
1286
                                c.closeConnection(ProtocolViolation)
×
1287
                                return
×
1288
                        }
×
1289
                        if compress {
2,270✔
1290
                                // Done for now, will get back another INFO protocol...
1,071✔
1291
                                return
1,071✔
1292
                        }
1,071✔
1293
                        // No compression because one side does not want/can't, so proceed.
1294
                        c.mu.Lock()
128✔
1295
                        // Check that the connection did not close if the lock was released.
128✔
1296
                        if c.isClosed() {
128✔
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 {
140✔
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,109✔
1330
                // Mark that the INFO protocol has been received.
722✔
1331
                c.flags.set(infoReceived)
722✔
1332
                // Prevent connecting to non leafnode port. Need to do this only for
722✔
1333
                // the first INFO, not for async INFO updates...
722✔
1334
                //
722✔
1335
                // Content of INFO sent by the server when accepting a tcp connection.
722✔
1336
                // -------------------------------------------------------------------
722✔
1337
                // Listen Port Of | CID | ClientConnectURLs | LeafNodeURLs | Gateway |
722✔
1338
                // -------------------------------------------------------------------
722✔
1339
                //      CLIENT    |  X* |        X**        |              |         |
722✔
1340
                //      ROUTE     |     |        X**        |      X***    |         |
722✔
1341
                //     GATEWAY    |     |                   |              |    X    |
722✔
1342
                //     LEAFNODE   |  X  |                   |       X      |         |
722✔
1343
                // -------------------------------------------------------------------
722✔
1344
                // *   Not on older servers.
722✔
1345
                // **  Not if "no advertise" is enabled.
722✔
1346
                // *** Not if leafnode's "no advertise" is enabled.
722✔
1347
                //
722✔
1348
                // As seen from above, a solicited LeafNode connection should receive
722✔
1349
                // from the remote server an INFO with CID and LeafNodeURLs. Anything
722✔
1350
                // else should be considered an attempt to connect to a wrong port.
722✔
1351
                if didSolicit && (info.CID == 0 || info.LeafNodeURLs == nil) {
774✔
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, " ") {
671✔
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)
669✔
1366
                if info.TLSRequired && didSolicit {
699✔
1367
                        remote.TLS = true
30✔
1368
                }
30✔
1369
                supportsHeaders := c.srv.supportsHeaders()
669✔
1370
                c.headers = supportsHeaders && info.Headers
669✔
1371

669✔
1372
                // Remember the remote server.
669✔
1373
                // Pre 2.2.0 servers are not sending their server name.
669✔
1374
                // In that case, use info.ID, which, for those servers, matches
669✔
1375
                // the content of the field `Name` in the leafnode CONNECT protocol.
669✔
1376
                if info.Name == _EMPTY_ {
669✔
1377
                        c.leaf.remoteServer = info.ID
×
1378
                } else {
669✔
1379
                        c.leaf.remoteServer = info.Name
669✔
1380
                }
669✔
1381
                c.leaf.remoteDomain = info.Domain
669✔
1382
                c.leaf.remoteCluster = info.Cluster
669✔
1383
                // We send the protocol version in the INFO protocol.
669✔
1384
                // Keep track of it, so we know if this connection supports message
669✔
1385
                // tracing for instance.
669✔
1386
                c.opts.Protocol = info.Proto
669✔
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,583✔
1392
                // Consider the incoming array as the most up-to-date
1,249✔
1393
                // representation of the remote cluster's list of URLs.
1,249✔
1394
                c.updateLeafNodeURLs(info)
1,249✔
1395
        }
1,249✔
1396

1397
        // Check to see if we have permissions updates here.
1398
        if info.Import != nil || info.Export != nil {
1,346✔
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 bool
1,334✔
1422

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

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

1,334✔
1439
        finishConnect := info.ConnectInfo
1,334✔
1440
        if resumeConnect && s != nil {
1,962✔
1441
                s.leafNodeResumeConnectProcess(c)
628✔
1442
                if !info.InfoOnConnect {
628✔
1443
                        finishConnect = true
×
1444
                }
×
1445
        }
1446
        if finishConnect {
1,941✔
1447
                s.leafNodeFinishConnectProcess(c)
607✔
1448
        }
607✔
1449
}
1450

1451
func (s *Server) negotiateLeafCompression(c *client, didSolicit bool, infoCompression string, co *CompressionOpts) (bool, error) {
1,199✔
1452
        // Negotiate the appropriate compression mode (or no compression)
1,199✔
1453
        cm, err := selectCompressionMode(co.Mode, infoCompression)
1,199✔
1454
        if err != nil {
1,199✔
1455
                return false, err
×
1456
        }
×
1457
        c.mu.Lock()
1,199✔
1458
        // For "auto" mode, set the initial compression mode based on RTT
1,199✔
1459
        if cm == CompressionS2Auto {
2,231✔
1460
                if c.rttStart.IsZero() {
2,064✔
1461
                        c.rtt = computeRTT(c.start)
1,032✔
1462
                }
1,032✔
1463
                cm = selectS2AutoModeBasedOnRTT(c.rtt, co.RTTThresholds)
1,032✔
1464
        }
1465
        // Keep track of the negotiated compression mode.
1466
        c.leaf.compression = cm
1,199✔
1467
        cid := c.cid
1,199✔
1468
        var nonce string
1,199✔
1469
        if !didSolicit {
1,725✔
1470
                nonce = bytesToString(c.nonce)
526✔
1471
        }
526✔
1472
        c.mu.Unlock()
1,199✔
1473

1,199✔
1474
        if !needsCompression(cm) {
1,327✔
1475
                return false, nil
128✔
1476
        }
128✔
1477

1478
        // If we end-up doing compression...
1479

1480
        // Generate an INFO with the chosen compression mode.
1481
        s.mu.Lock()
1,071✔
1482
        info := s.copyLeafNodeInfo()
1,071✔
1483
        info.Compression, info.CID, info.Nonce = compressionModeForInfoProtocol(co, cm), cid, nonce
1,071✔
1484
        infoProto := generateInfoJSON(info)
1,071✔
1485
        s.mu.Unlock()
1,071✔
1486

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

1512
// When getting a leaf node INFO protocol, use the provided
1513
// array of urls to update the list of possible endpoints.
1514
func (c *client) updateLeafNodeURLs(info *Info) {
1,249✔
1515
        cfg := c.leaf.remote
1,249✔
1516
        cfg.Lock()
1,249✔
1517
        defer cfg.Unlock()
1,249✔
1518

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

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

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

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

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

1,245✔
1655
        // If applicable, evict the old one.
1,245✔
1656
        if old != nil {
1,248✔
1657
                old.sendErrAndErr(DuplicateRemoteLeafnodeConnection.String())
3✔
1658
                old.closeConnection(DuplicateRemoteLeafnodeConnection)
3✔
1659
                c.Warnf("Replacing connection from same server")
3✔
1660
        }
3✔
1661

1662
        srvDecorated := func() string {
1,452✔
1663
                if myClustName == _EMPTY_ {
229✔
1664
                        return mySrvName
22✔
1665
                }
22✔
1666
                return fmt.Sprintf("%s/%s", mySrvName, myClustName)
185✔
1667
        }
1668

1669
        opts := s.getOpts()
1,245✔
1670
        sysAcc := s.SystemAccount()
1,245✔
1671
        js := s.getJetStream()
1,245✔
1672
        var meta *raft
1,245✔
1673
        if js != nil {
1,757✔
1674
                if mg := js.getMetaGroup(); mg != nil {
935✔
1675
                        meta = mg.(*raft)
423✔
1676
                }
423✔
1677
        }
1678
        blockMappingOutgoing := false
1,245✔
1679
        // Deny (non domain) JetStream API traffic unless system account is shared
1,245✔
1680
        // and domain names are identical and extending is not disabled
1,245✔
1681

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

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

1778
func (s *Server) removeLeafNodeConnection(c *client) {
1,552✔
1779
        c.mu.Lock()
1,552✔
1780
        cid := c.cid
1,552✔
1781
        if c.leaf != nil {
3,104✔
1782
                if c.leaf.tsubt != nil {
2,687✔
1783
                        c.leaf.tsubt.Stop()
1,135✔
1784
                        c.leaf.tsubt = nil
1,135✔
1785
                }
1,135✔
1786
                if c.leaf.gwSub != nil {
2,157✔
1787
                        s.gwLeafSubs.Remove(c.leaf.gwSub)
605✔
1788
                        // We need to set this to nil for GC to release the connection
605✔
1789
                        c.leaf.gwSub = nil
605✔
1790
                }
605✔
1791
        }
1792
        c.mu.Unlock()
1,552✔
1793
        s.mu.Lock()
1,552✔
1794
        delete(s.leafs, cid)
1,552✔
1795
        s.mu.Unlock()
1,552✔
1796
        s.removeFromTempClients(cid)
1,552✔
1797
}
1798

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

1817
        // There was an existing field called:
1818
        // >> Comp bool `json:"compression,omitempty"`
1819
        // that has never been used. With support for compression, we now need
1820
        // a field that is a string. So we use a different json tag:
1821
        Compression string `json:"compress_mode,omitempty"`
1822

1823
        // Just used to detect wrong connection attempts.
1824
        Gateway string `json:"gateway,omitempty"`
1825

1826
        // Tells the accept side which account the remote is binding to.
1827
        RemoteAccount string `json:"remote_account,omitempty"`
1828

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

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

1850
        // Unmarshal as a leaf node connect protocol
1851
        proto := &leafConnectInfo{}
645✔
1852
        if err := json.Unmarshal(arg, proto); err != nil {
645✔
1853
                return err
×
1854
        }
×
1855

1856
        // Reject a cluster that contains spaces.
1857
        if proto.Cluster != _EMPTY_ && strings.Contains(proto.Cluster, " ") {
646✔
1858
                c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
1859
                c.closeConnection(ProtocolViolation)
1✔
1860
                return ErrClusterNameHasSpaces
1✔
1861
        }
1✔
1862

1863
        // Check for cluster name collisions.
1864
        if cn := s.cachedClusterName(); cn != _EMPTY_ && proto.Cluster != _EMPTY_ && proto.Cluster == cn {
647✔
1865
                c.sendErrAndErr(ErrLeafNodeHasSameClusterName.Error())
3✔
1866
                c.closeConnection(ClusterNamesIdentical)
3✔
1867
                return ErrLeafNodeHasSameClusterName
3✔
1868
        }
3✔
1869

1870
        // Reject if this has Gateway which means that it would be from a gateway
1871
        // connection that incorrectly connects to the leafnode port.
1872
        if proto.Gateway != _EMPTY_ {
641✔
1873
                errTxt := fmt.Sprintf("Rejecting connection from gateway %q on the leafnode port", proto.Gateway)
×
1874
                c.Errorf(errTxt)
×
1875
                c.sendErr(errTxt)
×
1876
                c.closeConnection(WrongGateway)
×
1877
                return ErrWrongGateway
×
1878
        }
×
1879

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

1899
        // Check if this server supports headers.
1900
        supportHeaders := c.srv.supportsHeaders()
640✔
1901

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

1922
        // Remember the remote server.
1923
        c.leaf.remoteServer = proto.Name
640✔
1924
        // Remember the remote account name
640✔
1925
        c.leaf.remoteAccName = proto.RemoteAccount
640✔
1926

640✔
1927
        // If the other side has declared itself a hub, so we will take on the spoke role.
640✔
1928
        if proto.Hub {
646✔
1929
                c.leaf.isSpoke = true
6✔
1930
        }
6✔
1931

1932
        // The soliciting side is part of a cluster.
1933
        if proto.Cluster != _EMPTY_ {
1,135✔
1934
                c.leaf.remoteCluster = proto.Cluster
495✔
1935
        }
495✔
1936

1937
        c.leaf.remoteDomain = proto.Domain
640✔
1938

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

1951
        // Set the Ping timer
1952
        c.setFirstPingTimer()
640✔
1953

640✔
1954
        // If we received pub deny permissions from the other end, merge with existing ones.
640✔
1955
        c.mergeDenyPermissions(pub, proto.DenyPub)
640✔
1956

640✔
1957
        c.mu.Unlock()
640✔
1958

640✔
1959
        // Register the cluster, even if empty, as long as we are acting as a hub.
640✔
1960
        if !proto.Hub {
1,274✔
1961
                c.acc.registerLeafNodeCluster(proto.Cluster)
634✔
1962
        }
634✔
1963

1964
        // Add in the leafnode here since we passed through auth at this point.
1965
        s.addLeafNodeConnection(c, proto.Name, proto.Cluster, true)
640✔
1966

640✔
1967
        // If we have permissions bound to this leafnode we need to send then back to the
640✔
1968
        // origin server for local enforcement.
640✔
1969
        s.sendPermsAndAccountInfo(c)
640✔
1970

640✔
1971
        // Create and initialize the smap since we know our bound account now.
640✔
1972
        // This will send all registered subs too.
640✔
1973
        s.initLeafNodeSmapAndSendSubs(c)
640✔
1974

640✔
1975
        // Announce the account connect event for a leaf node.
640✔
1976
        // This will no-op as needed.
640✔
1977
        s.sendLeafNodeConnect(c.acc)
640✔
1978

640✔
1979
        return nil
640✔
1980
}
1981

1982
// Returns the remote cluster name. This is set only once so does not require a lock.
1983
func (c *client) remoteCluster() string {
187,617✔
1984
        if c.leaf == nil {
187,617✔
1985
                return _EMPTY_
×
1986
        }
×
1987
        return c.leaf.remoteCluster
187,617✔
1988
}
1989

1990
// Sends back an info block to the soliciting leafnode to let it know about
1991
// its permission settings for local enforcement.
1992
func (s *Server) sendPermsAndAccountInfo(c *client) {
641✔
1993
        // Copy
641✔
1994
        s.mu.Lock()
641✔
1995
        info := s.copyLeafNodeInfo()
641✔
1996
        s.mu.Unlock()
641✔
1997
        c.mu.Lock()
641✔
1998
        info.CID = c.cid
641✔
1999
        info.Import = c.opts.Import
641✔
2000
        info.Export = c.opts.Export
641✔
2001
        info.RemoteAccount = c.acc.Name
641✔
2002
        // s.SystemAccount() uses an atomic operation and does not get the server lock, so this is safe.
641✔
2003
        info.IsSystemAccount = c.acc == s.SystemAccount()
641✔
2004
        info.ConnectInfo = true
641✔
2005
        c.enqueueProto(generateInfoJSON(info))
641✔
2006
        c.mu.Unlock()
641✔
2007
}
641✔
2008

2009
// Snapshot the current subscriptions from the sublist into our smap which
2010
// we will keep updated from now on.
2011
// Also send the registered subscriptions.
2012
func (s *Server) initLeafNodeSmapAndSendSubs(c *client) {
1,245✔
2013
        acc := c.acc
1,245✔
2014
        if acc == nil {
1,245✔
2015
                c.Debugf("Leafnode does not have an account bound")
×
2016
                return
×
2017
        }
×
2018
        // Collect all account subs here.
2019
        _subs := [1024]*subscription{}
1,245✔
2020
        subs := _subs[:0]
1,245✔
2021
        ims := []string{}
1,245✔
2022

1,245✔
2023
        // Hold the client lock otherwise there can be a race and miss some subs.
1,245✔
2024
        c.mu.Lock()
1,245✔
2025
        defer c.mu.Unlock()
1,245✔
2026

1,245✔
2027
        acc.mu.RLock()
1,245✔
2028
        accName := acc.Name
1,245✔
2029
        accNTag := acc.nameTag
1,245✔
2030

1,245✔
2031
        // To make printing look better when no friendly name present.
1,245✔
2032
        if accNTag != _EMPTY_ {
1,255✔
2033
                accNTag = "/" + accNTag
10✔
2034
        }
10✔
2035

2036
        // If we are solicited we only send interest for local clients.
2037
        if c.isSpokeLeafNode() {
1,850✔
2038
                acc.sl.localSubs(&subs, true)
605✔
2039
        } else {
1,245✔
2040
                acc.sl.All(&subs)
640✔
2041
        }
640✔
2042

2043
        // Check if we have an existing service import reply.
2044
        siReply := copyBytes(acc.siReply)
1,245✔
2045

1,245✔
2046
        // Since leaf nodes only send on interest, if the bound
1,245✔
2047
        // account has import services we need to send those over.
1,245✔
2048
        for isubj := range acc.imports.services {
5,844✔
2049
                if c.isSpokeLeafNode() && !c.canSubscribe(isubj) {
4,869✔
2050
                        c.Debugf("Not permitted to import service %q on behalf of %s%s", isubj, accName, accNTag)
270✔
2051
                        continue
270✔
2052
                }
2053
                ims = append(ims, isubj)
4,329✔
2054
        }
2055
        // Likewise for mappings.
2056
        for _, m := range acc.mappings {
3,390✔
2057
                if c.isSpokeLeafNode() && !c.canSubscribe(m.src) {
2,181✔
2058
                        c.Debugf("Not permitted to import mapping %q on behalf of %s%s", m.src, accName, accNTag)
36✔
2059
                        continue
36✔
2060
                }
2061
                ims = append(ims, m.src)
2,109✔
2062
        }
2063

2064
        // Create a unique subject that will be used for loop detection.
2065
        lds := acc.lds
1,245✔
2066
        acc.mu.RUnlock()
1,245✔
2067

1,245✔
2068
        // Check if we have to create the LDS.
1,245✔
2069
        if lds == _EMPTY_ {
2,227✔
2070
                lds = leafNodeLoopDetectionSubjectPrefix + nuid.Next()
982✔
2071
                acc.mu.Lock()
982✔
2072
                acc.lds = lds
982✔
2073
                acc.mu.Unlock()
982✔
2074
        }
982✔
2075

2076
        // Now check for gateway interest. Leafnodes will put this into
2077
        // the proper mode to propagate, but they are not held in the account.
2078
        gwsa := [16]*client{}
1,245✔
2079
        gws := gwsa[:0]
1,245✔
2080
        s.getOutboundGatewayConnections(&gws)
1,245✔
2081
        for _, cgw := range gws {
1,327✔
2082
                cgw.mu.Lock()
82✔
2083
                gw := cgw.gw
82✔
2084
                cgw.mu.Unlock()
82✔
2085
                if gw != nil {
164✔
2086
                        if ei, _ := gw.outsim.Load(accName); ei != nil {
164✔
2087
                                if e := ei.(*outsie); e != nil && e.sl != nil {
164✔
2088
                                        e.sl.All(&subs)
82✔
2089
                                }
82✔
2090
                        }
2091
                }
2092
        }
2093

2094
        applyGlobalRouting := s.gateway.enabled
1,245✔
2095
        if c.isSpokeLeafNode() {
1,850✔
2096
                // Add a fake subscription for this solicited leafnode connection
605✔
2097
                // so that we can send back directly for mapped GW replies.
605✔
2098
                // We need to keep track of this subscription so it can be removed
605✔
2099
                // when the connection is closed so that the GC can release it.
605✔
2100
                c.leaf.gwSub = &subscription{client: c, subject: []byte(gwReplyPrefix + ">")}
605✔
2101
                c.srv.gwLeafSubs.Insert(c.leaf.gwSub)
605✔
2102
        }
605✔
2103

2104
        // Now walk the results and add them to our smap
2105
        rc := c.leaf.remoteCluster
1,245✔
2106
        c.leaf.smap = make(map[string]int32)
1,245✔
2107
        for _, sub := range subs {
38,839✔
2108
                // Check perms regardless of role.
37,594✔
2109
                if c.perms != nil && !c.canSubscribe(string(sub.subject)) {
39,903✔
2110
                        c.Debugf("Not permitted to subscribe to %q on behalf of %s%s", sub.subject, accName, accNTag)
2,309✔
2111
                        continue
2,309✔
2112
                }
2113
                // We ignore ourselves here.
2114
                // Also don't add the subscription if it has a origin cluster and the
2115
                // cluster name matches the one of the client we are sending to.
2116
                if c != sub.client && (sub.origin == nil || (bytesToString(sub.origin) != rc)) {
65,160✔
2117
                        count := int32(1)
29,875✔
2118
                        if len(sub.queue) > 0 && sub.qw > 0 {
29,887✔
2119
                                count = sub.qw
12✔
2120
                        }
12✔
2121
                        c.leaf.smap[keyFromSub(sub)] += count
29,875✔
2122
                        if c.leaf.tsub == nil {
31,044✔
2123
                                c.leaf.tsub = make(map[*subscription]struct{})
1,169✔
2124
                        }
1,169✔
2125
                        c.leaf.tsub[sub] = struct{}{}
29,875✔
2126
                }
2127
        }
2128
        // FIXME(dlc) - We need to update appropriately on an account claims update.
2129
        for _, isubj := range ims {
7,683✔
2130
                c.leaf.smap[isubj]++
6,438✔
2131
        }
6,438✔
2132
        // If we have gateways enabled we need to make sure the other side sends us responses
2133
        // that have been augmented from the original subscription.
2134
        // TODO(dlc) - Should we lock this down more?
2135
        if applyGlobalRouting {
1,347✔
2136
                c.leaf.smap[oldGWReplyPrefix+"*.>"]++
102✔
2137
                c.leaf.smap[gwReplyPrefix+">"]++
102✔
2138
        }
102✔
2139
        // Detect loops by subscribing to a specific subject and checking
2140
        // if this sub is coming back to us.
2141
        c.leaf.smap[lds]++
1,245✔
2142

1,245✔
2143
        // Check if we need to add an existing siReply to our map.
1,245✔
2144
        // This will be a prefix so add on the wildcard.
1,245✔
2145
        if siReply != nil {
1,261✔
2146
                wcsub := append(siReply, '>')
16✔
2147
                c.leaf.smap[string(wcsub)]++
16✔
2148
        }
16✔
2149
        // Queue all protocols. There is no max pending limit for LN connection,
2150
        // so we don't need chunking. The writes will happen from the writeLoop.
2151
        var b bytes.Buffer
1,245✔
2152
        for key, n := range c.leaf.smap {
27,129✔
2153
                c.writeLeafSub(&b, key, n)
25,884✔
2154
        }
25,884✔
2155
        if b.Len() > 0 {
2,490✔
2156
                c.enqueueProto(b.Bytes())
1,245✔
2157
        }
1,245✔
2158
        if c.leaf.tsub != nil {
2,415✔
2159
                // Clear the tsub map after 5 seconds.
1,170✔
2160
                c.leaf.tsubt = time.AfterFunc(5*time.Second, func() {
1,205✔
2161
                        c.mu.Lock()
35✔
2162
                        if c.leaf != nil {
70✔
2163
                                c.leaf.tsub = nil
35✔
2164
                                c.leaf.tsubt = nil
35✔
2165
                        }
35✔
2166
                        c.mu.Unlock()
35✔
2167
                })
2168
        }
2169
}
2170

2171
// updateInterestForAccountOnGateway called from gateway code when processing RS+ and RS-.
2172
func (s *Server) updateInterestForAccountOnGateway(accName string, sub *subscription, delta int32) {
198,553✔
2173
        acc, err := s.LookupAccount(accName)
198,553✔
2174
        if acc == nil || err != nil {
198,715✔
2175
                s.Debugf("No or bad account for %q, failed to update interest from gateway", accName)
162✔
2176
                return
162✔
2177
        }
162✔
2178
        acc.updateLeafNodes(sub, delta)
198,391✔
2179
}
2180

2181
// updateLeafNodes will make sure to update the account smap for the subscription.
2182
// Will also forward to all leaf nodes as needed.
2183
func (acc *Account) updateLeafNodes(sub *subscription, delta int32) {
2,313,267✔
2184
        if acc == nil || sub == nil {
2,313,267✔
2185
                return
×
2186
        }
×
2187

2188
        // We will do checks for no leafnodes and same cluster here inline and under the
2189
        // general account read lock.
2190
        // If we feel we need to update the leafnodes we will do that out of line to avoid
2191
        // blocking routes or GWs.
2192

2193
        acc.mu.RLock()
2,313,267✔
2194
        // First check if we even have leafnodes here.
2,313,267✔
2195
        if acc.nleafs == 0 {
4,559,873✔
2196
                acc.mu.RUnlock()
2,246,606✔
2197
                return
2,246,606✔
2198
        }
2,246,606✔
2199

2200
        // Is this a loop detection subject.
2201
        isLDS := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
66,661✔
2202

66,661✔
2203
        // Capture the cluster even if its empty.
66,661✔
2204
        var cluster string
66,661✔
2205
        if sub.origin != nil {
115,073✔
2206
                cluster = bytesToString(sub.origin)
48,412✔
2207
        }
48,412✔
2208

2209
        // If we have an isolated cluster we can return early, as long as it is not a loop detection subject.
2210
        // Empty clusters will return false for the check.
2211
        if !isLDS && acc.isLeafNodeClusterIsolated(cluster) {
87,954✔
2212
                acc.mu.RUnlock()
21,293✔
2213
                return
21,293✔
2214
        }
21,293✔
2215

2216
        // We can release the general account lock.
2217
        acc.mu.RUnlock()
45,368✔
2218

45,368✔
2219
        // We can hold the list lock here to avoid having to copy a large slice.
45,368✔
2220
        acc.lmu.RLock()
45,368✔
2221
        defer acc.lmu.RUnlock()
45,368✔
2222

45,368✔
2223
        // Do this once.
45,368✔
2224
        subject := string(sub.subject)
45,368✔
2225

45,368✔
2226
        // Walk the connected leafnodes.
45,368✔
2227
        for _, ln := range acc.lleafs {
101,010✔
2228
                if ln == sub.client {
84,329✔
2229
                        continue
28,687✔
2230
                }
2231
                // Check to make sure this sub does not have an origin cluster that matches the leafnode.
2232
                ln.mu.Lock()
26,955✔
2233
                // If skipped, make sure that we still let go the "$LDS." subscription that allows
26,955✔
2234
                // the detection of loops as long as different cluster.
26,955✔
2235
                clusterDifferent := cluster != ln.remoteCluster()
26,955✔
2236
                if (isLDS && clusterDifferent) || ((cluster == _EMPTY_ || clusterDifferent) && (delta <= 0 || ln.canSubscribe(subject))) {
49,781✔
2237
                        ln.updateSmap(sub, delta, isLDS)
22,826✔
2238
                }
22,826✔
2239
                ln.mu.Unlock()
26,955✔
2240
        }
2241
}
2242

2243
// This will make an update to our internal smap and determine if we should send out
2244
// an interest update to the remote side.
2245
// Lock should be held.
2246
func (c *client) updateSmap(sub *subscription, delta int32, isLDS bool) {
22,826✔
2247
        if c.leaf.smap == nil {
22,831✔
2248
                return
5✔
2249
        }
5✔
2250

2251
        // If we are solicited make sure this is a local client or a non-solicited leaf node
2252
        skind := sub.client.kind
22,821✔
2253
        updateClient := skind == CLIENT || skind == SYSTEM || skind == JETSTREAM || skind == ACCOUNT
22,821✔
2254
        if !isLDS && c.isSpokeLeafNode() && !(updateClient || (skind == LEAF && !sub.client.isSpokeLeafNode())) {
30,977✔
2255
                return
8,156✔
2256
        }
8,156✔
2257

2258
        // For additions, check if that sub has just been processed during initLeafNodeSmapAndSendSubs
2259
        if delta > 0 && c.leaf.tsub != nil {
21,681✔
2260
                if _, present := c.leaf.tsub[sub]; present {
7,016✔
2261
                        delete(c.leaf.tsub, sub)
×
2262
                        if len(c.leaf.tsub) == 0 {
×
2263
                                c.leaf.tsub = nil
×
2264
                                c.leaf.tsubt.Stop()
×
2265
                                c.leaf.tsubt = nil
×
2266
                        }
×
2267
                        return
×
2268
                }
2269
        }
2270

2271
        key := keyFromSub(sub)
14,665✔
2272
        n, ok := c.leaf.smap[key]
14,665✔
2273
        if delta < 0 && !ok {
15,561✔
2274
                return
896✔
2275
        }
896✔
2276

2277
        // We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
2278
        update := sub.queue != nil || (n <= 0 && n+delta > 0) || (n > 0 && n+delta <= 0)
13,769✔
2279
        n += delta
13,769✔
2280
        if n > 0 {
24,033✔
2281
                c.leaf.smap[key] = n
10,264✔
2282
        } else {
13,769✔
2283
                delete(c.leaf.smap, key)
3,505✔
2284
        }
3,505✔
2285
        if update {
23,056✔
2286
                c.sendLeafNodeSubUpdate(key, n)
9,287✔
2287
        }
9,287✔
2288
}
2289

2290
// Used to force add subjects to the subject map.
2291
func (c *client) forceAddToSmap(subj string) {
4✔
2292
        c.mu.Lock()
4✔
2293
        defer c.mu.Unlock()
4✔
2294

4✔
2295
        if c.leaf.smap == nil {
4✔
2296
                return
×
2297
        }
×
2298
        n := c.leaf.smap[subj]
4✔
2299
        if n != 0 {
5✔
2300
                return
1✔
2301
        }
1✔
2302
        // Place into the map since it was not there.
2303
        c.leaf.smap[subj] = 1
3✔
2304
        c.sendLeafNodeSubUpdate(subj, 1)
3✔
2305
}
2306

2307
// Used to force remove a subject from the subject map.
2308
func (c *client) forceRemoveFromSmap(subj string) {
1✔
2309
        c.mu.Lock()
1✔
2310
        defer c.mu.Unlock()
1✔
2311

1✔
2312
        if c.leaf.smap == nil {
1✔
2313
                return
×
2314
        }
×
2315
        n := c.leaf.smap[subj]
1✔
2316
        if n == 0 {
1✔
2317
                return
×
2318
        }
×
2319
        n--
1✔
2320
        if n == 0 {
2✔
2321
                // Remove is now zero
1✔
2322
                delete(c.leaf.smap, subj)
1✔
2323
                c.sendLeafNodeSubUpdate(subj, 0)
1✔
2324
        } else {
1✔
2325
                c.leaf.smap[subj] = n
×
2326
        }
×
2327
}
2328

2329
// Send the subscription interest change to the other side.
2330
// Lock should be held.
2331
func (c *client) sendLeafNodeSubUpdate(key string, n int32) {
9,291✔
2332
        // If we are a spoke, we need to check if we are allowed to send this subscription over to the hub.
9,291✔
2333
        if c.isSpokeLeafNode() {
11,555✔
2334
                checkPerms := true
2,264✔
2335
                if len(key) > 0 && (key[0] == '$' || key[0] == '_') {
3,568✔
2336
                        if strings.HasPrefix(key, leafNodeLoopDetectionSubjectPrefix) ||
1,304✔
2337
                                strings.HasPrefix(key, oldGWReplyPrefix) ||
1,304✔
2338
                                strings.HasPrefix(key, gwReplyPrefix) {
1,382✔
2339
                                checkPerms = false
78✔
2340
                        }
78✔
2341
                }
2342
                if checkPerms {
4,450✔
2343
                        var subject string
2,186✔
2344
                        if sep := strings.IndexByte(key, ' '); sep != -1 {
2,679✔
2345
                                subject = key[:sep]
493✔
2346
                        } else {
2,186✔
2347
                                subject = key
1,693✔
2348
                        }
1,693✔
2349
                        if !c.canSubscribe(subject) {
2,186✔
2350
                                return
×
2351
                        }
×
2352
                }
2353
        }
2354
        // If we are here we can send over to the other side.
2355
        _b := [64]byte{}
9,291✔
2356
        b := bytes.NewBuffer(_b[:0])
9,291✔
2357
        c.writeLeafSub(b, key, n)
9,291✔
2358
        c.enqueueProto(b.Bytes())
9,291✔
2359
}
2360

2361
// Helper function to build the key.
2362
func keyFromSub(sub *subscription) string {
45,549✔
2363
        var sb strings.Builder
45,549✔
2364
        sb.Grow(len(sub.subject) + len(sub.queue) + 1)
45,549✔
2365
        sb.Write(sub.subject)
45,549✔
2366
        if sub.queue != nil {
49,349✔
2367
                // Just make the key subject spc group, e.g. 'foo bar'
3,800✔
2368
                sb.WriteByte(' ')
3,800✔
2369
                sb.Write(sub.queue)
3,800✔
2370
        }
3,800✔
2371
        return sb.String()
45,549✔
2372
}
2373

2374
const (
2375
        keyRoutedSub         = "R"
2376
        keyRoutedSubByte     = 'R'
2377
        keyRoutedLeafSub     = "L"
2378
        keyRoutedLeafSubByte = 'L'
2379
)
2380

2381
// Helper function to build the key that prevents collisions between normal
2382
// routed subscriptions and routed subscriptions on behalf of a leafnode.
2383
// Keys will look like this:
2384
// "R foo"          -> plain routed sub on "foo"
2385
// "R foo bar"      -> queue routed sub on "foo", queue "bar"
2386
// "L foo bar"      -> plain routed leaf sub on "foo", leaf "bar"
2387
// "L foo bar baz"  -> queue routed sub on "foo", queue "bar", leaf "baz"
2388
func keyFromSubWithOrigin(sub *subscription) string {
635,297✔
2389
        var sb strings.Builder
635,297✔
2390
        sb.Grow(2 + len(sub.origin) + 1 + len(sub.subject) + 1 + len(sub.queue))
635,297✔
2391
        leaf := len(sub.origin) > 0
635,297✔
2392
        if leaf {
651,793✔
2393
                sb.WriteByte(keyRoutedLeafSubByte)
16,496✔
2394
        } else {
635,297✔
2395
                sb.WriteByte(keyRoutedSubByte)
618,801✔
2396
        }
618,801✔
2397
        sb.WriteByte(' ')
635,297✔
2398
        sb.Write(sub.subject)
635,297✔
2399
        if sub.queue != nil {
657,822✔
2400
                sb.WriteByte(' ')
22,525✔
2401
                sb.Write(sub.queue)
22,525✔
2402
        }
22,525✔
2403
        if leaf {
651,793✔
2404
                sb.WriteByte(' ')
16,496✔
2405
                sb.Write(sub.origin)
16,496✔
2406
        }
16,496✔
2407
        return sb.String()
635,297✔
2408
}
2409

2410
// Lock should be held.
2411
func (c *client) writeLeafSub(w *bytes.Buffer, key string, n int32) {
35,175✔
2412
        if key == _EMPTY_ {
35,175✔
2413
                return
×
2414
        }
×
2415
        if n > 0 {
66,844✔
2416
                w.WriteString("LS+ " + key)
31,669✔
2417
                // Check for queue semantics, if found write n.
31,669✔
2418
                if strings.Contains(key, " ") {
33,983✔
2419
                        w.WriteString(" ")
2,314✔
2420
                        var b [12]byte
2,314✔
2421
                        var i = len(b)
2,314✔
2422
                        for l := n; l > 0; l /= 10 {
5,560✔
2423
                                i--
3,246✔
2424
                                b[i] = digits[l%10]
3,246✔
2425
                        }
3,246✔
2426
                        w.Write(b[i:])
2,314✔
2427
                        if c.trace {
2,314✔
2428
                                arg := fmt.Sprintf("%s %d", key, n)
×
2429
                                c.traceOutOp("LS+", []byte(arg))
×
2430
                        }
×
2431
                } else if c.trace {
29,551✔
2432
                        c.traceOutOp("LS+", []byte(key))
196✔
2433
                }
196✔
2434
        } else {
3,506✔
2435
                w.WriteString("LS- " + key)
3,506✔
2436
                if c.trace {
3,519✔
2437
                        c.traceOutOp("LS-", []byte(key))
13✔
2438
                }
13✔
2439
        }
2440
        w.WriteString(CR_LF)
35,175✔
2441
}
2442

2443
// processLeafSub will process an inbound sub request for the remote leaf node.
2444
func (c *client) processLeafSub(argo []byte) (err error) {
31,401✔
2445
        // Indicate activity.
31,401✔
2446
        c.in.subs++
31,401✔
2447

31,401✔
2448
        srv := c.srv
31,401✔
2449
        if srv == nil {
31,401✔
2450
                return nil
×
2451
        }
×
2452

2453
        // Copy so we do not reference a potentially large buffer
2454
        arg := make([]byte, len(argo))
31,401✔
2455
        copy(arg, argo)
31,401✔
2456

31,401✔
2457
        args := splitArg(arg)
31,401✔
2458
        sub := &subscription{client: c}
31,401✔
2459

31,401✔
2460
        delta := int32(1)
31,401✔
2461
        switch len(args) {
31,401✔
2462
        case 1:
29,131✔
2463
                sub.queue = nil
29,131✔
2464
        case 3:
2,270✔
2465
                sub.queue = args[1]
2,270✔
2466
                sub.qw = int32(parseSize(args[2]))
2,270✔
2467
                // TODO: (ik) We should have a non empty queue name and a queue
2,270✔
2468
                // weight >= 1. For 2.11, we may want to return an error if that
2,270✔
2469
                // is not the case, but for now just overwrite `delta` if queue
2,270✔
2470
                // weight is greater than 1 (it is possible after a reconnect/
2,270✔
2471
                // server restart to receive a queue weight > 1 for a new sub).
2,270✔
2472
                if sub.qw > 1 {
3,938✔
2473
                        delta = sub.qw
1,668✔
2474
                }
1,668✔
2475
        default:
×
2476
                return fmt.Errorf("processLeafSub Parse Error: '%s'", arg)
×
2477
        }
2478
        sub.subject = args[0]
31,401✔
2479

31,401✔
2480
        c.mu.Lock()
31,401✔
2481
        if c.isClosed() {
31,426✔
2482
                c.mu.Unlock()
25✔
2483
                return nil
25✔
2484
        }
25✔
2485

2486
        acc := c.acc
31,376✔
2487
        // Check if we have a loop.
31,376✔
2488
        ldsPrefix := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
31,376✔
2489

31,376✔
2490
        if ldsPrefix && bytesToString(sub.subject) == acc.getLDSubject() {
31,382✔
2491
                c.mu.Unlock()
6✔
2492
                c.handleLeafNodeLoop(true)
6✔
2493
                return nil
6✔
2494
        }
6✔
2495

2496
        // Check permissions if applicable. (but exclude the $LDS, $GR and _GR_)
2497
        checkPerms := true
31,370✔
2498
        if sub.subject[0] == '$' || sub.subject[0] == '_' {
59,856✔
2499
                if ldsPrefix ||
28,486✔
2500
                        bytes.HasPrefix(sub.subject, []byte(oldGWReplyPrefix)) ||
28,486✔
2501
                        bytes.HasPrefix(sub.subject, []byte(gwReplyPrefix)) {
30,408✔
2502
                        checkPerms = false
1,922✔
2503
                }
1,922✔
2504
        }
2505

2506
        // If we are a hub check that we can publish to this subject.
2507
        if checkPerms {
60,818✔
2508
                subj := string(sub.subject)
29,448✔
2509
                if subjectIsLiteral(subj) && !c.pubAllowedFullCheck(subj, true, true) {
29,776✔
2510
                        c.mu.Unlock()
328✔
2511
                        c.leafSubPermViolation(sub.subject)
328✔
2512
                        c.Debugf(fmt.Sprintf("Permissions Violation for Subscription to %q", sub.subject))
328✔
2513
                        return nil
328✔
2514
                }
328✔
2515
        }
2516

2517
        // Check if we have a maximum on the number of subscriptions.
2518
        if c.subsAtLimit() {
31,050✔
2519
                c.mu.Unlock()
8✔
2520
                c.maxSubsExceeded()
8✔
2521
                return nil
8✔
2522
        }
8✔
2523

2524
        // If we have an origin cluster associated mark that in the sub.
2525
        if rc := c.remoteCluster(); rc != _EMPTY_ {
59,050✔
2526
                sub.origin = []byte(rc)
28,016✔
2527
        }
28,016✔
2528

2529
        // Like Routes, we store local subs by account and subject and optionally queue name.
2530
        // If we have a queue it will have a trailing weight which we do not want.
2531
        if sub.queue != nil {
33,003✔
2532
                sub.sid = arg[:len(arg)-len(args[2])-1]
1,969✔
2533
        } else {
31,034✔
2534
                sub.sid = arg
29,065✔
2535
        }
29,065✔
2536
        key := bytesToString(sub.sid)
31,034✔
2537
        osub := c.subs[key]
31,034✔
2538
        if osub == nil {
60,554✔
2539
                c.subs[key] = sub
29,520✔
2540
                // Now place into the account sl.
29,520✔
2541
                if err := acc.sl.Insert(sub); err != nil {
29,520✔
2542
                        delete(c.subs, key)
×
2543
                        c.mu.Unlock()
×
2544
                        c.Errorf("Could not insert subscription: %v", err)
×
2545
                        c.sendErr("Invalid Subscription")
×
2546
                        return nil
×
2547
                }
×
2548
        } else if sub.queue != nil {
3,027✔
2549
                // For a queue we need to update the weight.
1,513✔
2550
                delta = sub.qw - atomic.LoadInt32(&osub.qw)
1,513✔
2551
                atomic.StoreInt32(&osub.qw, sub.qw)
1,513✔
2552
                acc.sl.UpdateRemoteQSub(osub)
1,513✔
2553
        }
1,513✔
2554
        spoke := c.isSpokeLeafNode()
31,034✔
2555
        c.mu.Unlock()
31,034✔
2556

31,034✔
2557
        // Only add in shadow subs if a new sub or qsub.
31,034✔
2558
        if osub == nil {
60,554✔
2559
                if err := c.addShadowSubscriptions(acc, sub, true); err != nil {
29,520✔
2560
                        c.Errorf(err.Error())
×
2561
                }
×
2562
        }
2563

2564
        // If we are not solicited, treat leaf node subscriptions similar to a
2565
        // client subscription, meaning we forward them to routes, gateways and
2566
        // other leaf nodes as needed.
2567
        if !spoke {
41,881✔
2568
                // If we are routing add to the route map for the associated account.
10,847✔
2569
                srv.updateRouteSubscriptionMap(acc, sub, delta)
10,847✔
2570
                if srv.gateway.enabled {
12,367✔
2571
                        srv.gatewayUpdateSubInterest(acc.Name, sub, delta)
1,520✔
2572
                }
1,520✔
2573
        }
2574
        // Now check on leafnode updates for other leaf nodes. We understand solicited
2575
        // and non-solicited state in this call so we will do the right thing.
2576
        acc.updateLeafNodes(sub, delta)
31,034✔
2577

31,034✔
2578
        return nil
31,034✔
2579
}
2580

2581
// If the leafnode is a solicited, set the connect delay based on default
2582
// or private option (for tests). Sends the error to the other side, log and
2583
// close the connection.
2584
func (c *client) handleLeafNodeLoop(sendErr bool) {
16✔
2585
        accName, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterLoopDetected)
16✔
2586
        errTxt := fmt.Sprintf("Loop detected for leafnode account=%q. Delaying attempt to reconnect for %v", accName, delay)
16✔
2587
        if sendErr {
24✔
2588
                c.sendErr(errTxt)
8✔
2589
        }
8✔
2590

2591
        c.Errorf(errTxt)
16✔
2592
        // If we are here with "sendErr" false, it means that this is the server
16✔
2593
        // that received the error. The other side will have closed the connection,
16✔
2594
        // but does not hurt to close here too.
16✔
2595
        c.closeConnection(ProtocolViolation)
16✔
2596
}
2597

2598
// processLeafUnsub will process an inbound unsub request for the remote leaf node.
2599
func (c *client) processLeafUnsub(arg []byte) error {
3,252✔
2600
        // Indicate any activity, so pub and sub or unsubs.
3,252✔
2601
        c.in.subs++
3,252✔
2602

3,252✔
2603
        acc := c.acc
3,252✔
2604
        srv := c.srv
3,252✔
2605

3,252✔
2606
        c.mu.Lock()
3,252✔
2607
        if c.isClosed() {
3,285✔
2608
                c.mu.Unlock()
33✔
2609
                return nil
33✔
2610
        }
33✔
2611

2612
        spoke := c.isSpokeLeafNode()
3,219✔
2613
        // We store local subs by account and subject and optionally queue name.
3,219✔
2614
        // LS- will have the arg exactly as the key.
3,219✔
2615
        sub, ok := c.subs[string(arg)]
3,219✔
2616
        if !ok {
3,230✔
2617
                // If not found, don't try to update routes/gws/leaf nodes.
11✔
2618
                c.mu.Unlock()
11✔
2619
                return nil
11✔
2620
        }
11✔
2621
        delta := int32(1)
3,208✔
2622
        if len(sub.queue) > 0 {
3,628✔
2623
                delta = sub.qw
420✔
2624
        }
420✔
2625
        c.mu.Unlock()
3,208✔
2626

3,208✔
2627
        c.unsubscribe(acc, sub, true, true)
3,208✔
2628
        if !spoke {
4,229✔
2629
                // If we are routing subtract from the route map for the associated account.
1,021✔
2630
                srv.updateRouteSubscriptionMap(acc, sub, -delta)
1,021✔
2631
                // Gateways
1,021✔
2632
                if srv.gateway.enabled {
1,313✔
2633
                        srv.gatewayUpdateSubInterest(acc.Name, sub, -delta)
292✔
2634
                }
292✔
2635
        }
2636
        // Now check on leafnode updates for other leaf nodes.
2637
        acc.updateLeafNodes(sub, -delta)
3,208✔
2638
        return nil
3,208✔
2639
}
2640

2641
func (c *client) processLeafHeaderMsgArgs(arg []byte) error {
482✔
2642
        // Unroll splitArgs to avoid runtime/heap issues
482✔
2643
        a := [MAX_MSG_ARGS][]byte{}
482✔
2644
        args := a[:0]
482✔
2645
        start := -1
482✔
2646
        for i, b := range arg {
31,712✔
2647
                switch b {
31,230✔
2648
                case ' ', '\t', '\r', '\n':
1,378✔
2649
                        if start >= 0 {
2,756✔
2650
                                args = append(args, arg[start:i])
1,378✔
2651
                                start = -1
1,378✔
2652
                        }
1,378✔
2653
                default:
29,852✔
2654
                        if start < 0 {
31,712✔
2655
                                start = i
1,860✔
2656
                        }
1,860✔
2657
                }
2658
        }
2659
        if start >= 0 {
964✔
2660
                args = append(args, arg[start:])
482✔
2661
        }
482✔
2662

2663
        c.pa.arg = arg
482✔
2664
        switch len(args) {
482✔
2665
        case 0, 1, 2:
×
2666
                return fmt.Errorf("processLeafHeaderMsgArgs Parse Error: '%s'", args)
×
2667
        case 3:
86✔
2668
                c.pa.reply = nil
86✔
2669
                c.pa.queues = nil
86✔
2670
                c.pa.hdb = args[1]
86✔
2671
                c.pa.hdr = parseSize(args[1])
86✔
2672
                c.pa.szb = args[2]
86✔
2673
                c.pa.size = parseSize(args[2])
86✔
2674
        case 4:
382✔
2675
                c.pa.reply = args[1]
382✔
2676
                c.pa.queues = nil
382✔
2677
                c.pa.hdb = args[2]
382✔
2678
                c.pa.hdr = parseSize(args[2])
382✔
2679
                c.pa.szb = args[3]
382✔
2680
                c.pa.size = parseSize(args[3])
382✔
2681
        default:
14✔
2682
                // args[1] is our reply indicator. Should be + or | normally.
14✔
2683
                if len(args[1]) != 1 {
14✔
2684
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2685
                }
×
2686
                switch args[1][0] {
14✔
2687
                case '+':
4✔
2688
                        c.pa.reply = args[2]
4✔
2689
                case '|':
10✔
2690
                        c.pa.reply = nil
10✔
2691
                default:
×
2692
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2693
                }
2694
                // Grab header size.
2695
                c.pa.hdb = args[len(args)-2]
14✔
2696
                c.pa.hdr = parseSize(c.pa.hdb)
14✔
2697

14✔
2698
                // Grab size.
14✔
2699
                c.pa.szb = args[len(args)-1]
14✔
2700
                c.pa.size = parseSize(c.pa.szb)
14✔
2701

14✔
2702
                // Grab queue names.
14✔
2703
                if c.pa.reply != nil {
18✔
2704
                        c.pa.queues = args[3 : len(args)-2]
4✔
2705
                } else {
14✔
2706
                        c.pa.queues = args[2 : len(args)-2]
10✔
2707
                }
10✔
2708
        }
2709
        if c.pa.hdr < 0 {
482✔
2710
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Header Size: '%s'", arg)
×
2711
        }
×
2712
        if c.pa.size < 0 {
482✔
2713
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Size: '%s'", args)
×
2714
        }
×
2715
        if c.pa.hdr > c.pa.size {
482✔
2716
                return fmt.Errorf("processLeafHeaderMsgArgs Header Size larger then TotalSize: '%s'", arg)
×
2717
        }
×
2718

2719
        // Common ones processed after check for arg length
2720
        c.pa.subject = args[0]
482✔
2721

482✔
2722
        return nil
482✔
2723
}
2724

2725
func (c *client) processLeafMsgArgs(arg []byte) error {
106,838✔
2726
        // Unroll splitArgs to avoid runtime/heap issues
106,838✔
2727
        a := [MAX_MSG_ARGS][]byte{}
106,838✔
2728
        args := a[:0]
106,838✔
2729
        start := -1
106,838✔
2730
        for i, b := range arg {
3,231,760✔
2731
                switch b {
3,124,922✔
2732
                case ' ', '\t', '\r', '\n':
154,280✔
2733
                        if start >= 0 {
308,560✔
2734
                                args = append(args, arg[start:i])
154,280✔
2735
                                start = -1
154,280✔
2736
                        }
154,280✔
2737
                default:
2,970,642✔
2738
                        if start < 0 {
3,231,760✔
2739
                                start = i
261,118✔
2740
                        }
261,118✔
2741
                }
2742
        }
2743
        if start >= 0 {
213,676✔
2744
                args = append(args, arg[start:])
106,838✔
2745
        }
106,838✔
2746

2747
        c.pa.arg = arg
106,838✔
2748
        switch len(args) {
106,838✔
2749
        case 0, 1:
×
2750
                return fmt.Errorf("processLeafMsgArgs Parse Error: '%s'", args)
×
2751
        case 2:
82,115✔
2752
                c.pa.reply = nil
82,115✔
2753
                c.pa.queues = nil
82,115✔
2754
                c.pa.szb = args[1]
82,115✔
2755
                c.pa.size = parseSize(args[1])
82,115✔
2756
        case 3:
2,165✔
2757
                c.pa.reply = args[1]
2,165✔
2758
                c.pa.queues = nil
2,165✔
2759
                c.pa.szb = args[2]
2,165✔
2760
                c.pa.size = parseSize(args[2])
2,165✔
2761
        default:
22,558✔
2762
                // args[1] is our reply indicator. Should be + or | normally.
22,558✔
2763
                if len(args[1]) != 1 {
22,558✔
2764
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2765
                }
×
2766
                switch args[1][0] {
22,558✔
2767
                case '+':
161✔
2768
                        c.pa.reply = args[2]
161✔
2769
                case '|':
22,397✔
2770
                        c.pa.reply = nil
22,397✔
2771
                default:
×
2772
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2773
                }
2774
                // Grab size.
2775
                c.pa.szb = args[len(args)-1]
22,558✔
2776
                c.pa.size = parseSize(c.pa.szb)
22,558✔
2777

22,558✔
2778
                // Grab queue names.
22,558✔
2779
                if c.pa.reply != nil {
22,719✔
2780
                        c.pa.queues = args[3 : len(args)-1]
161✔
2781
                } else {
22,558✔
2782
                        c.pa.queues = args[2 : len(args)-1]
22,397✔
2783
                }
22,397✔
2784
        }
2785
        if c.pa.size < 0 {
106,838✔
2786
                return fmt.Errorf("processLeafMsgArgs Bad or Missing Size: '%s'", args)
×
2787
        }
×
2788

2789
        // Common ones processed after check for arg length
2790
        c.pa.subject = args[0]
106,838✔
2791

106,838✔
2792
        return nil
106,838✔
2793
}
2794

2795
// processInboundLeafMsg is called to process an inbound msg from a leaf node.
2796
func (c *client) processInboundLeafMsg(msg []byte) {
105,296✔
2797
        // Update statistics
105,296✔
2798
        // The msg includes the CR_LF, so pull back out for accounting.
105,296✔
2799
        c.in.msgs++
105,296✔
2800
        c.in.bytes += int32(len(msg) - LEN_CR_LF)
105,296✔
2801

105,296✔
2802
        srv, acc, subject := c.srv, c.acc, string(c.pa.subject)
105,296✔
2803

105,296✔
2804
        // Mostly under testing scenarios.
105,296✔
2805
        if srv == nil || acc == nil {
105,298✔
2806
                return
2✔
2807
        }
2✔
2808

2809
        // Match the subscriptions. We will use our own L1 map if
2810
        // it's still valid, avoiding contention on the shared sublist.
2811
        var r *SublistResult
105,294✔
2812
        var ok bool
105,294✔
2813

105,294✔
2814
        genid := atomic.LoadUint64(&c.acc.sl.genid)
105,294✔
2815
        if genid == c.in.genid && c.in.results != nil {
208,211✔
2816
                r, ok = c.in.results[subject]
102,917✔
2817
        } else {
105,294✔
2818
                // Reset our L1 completely.
2,377✔
2819
                c.in.results = make(map[string]*SublistResult)
2,377✔
2820
                c.in.genid = genid
2,377✔
2821
        }
2,377✔
2822

2823
        // Go back to the sublist data structure.
2824
        if !ok {
184,603✔
2825
                r = c.acc.sl.Match(subject)
79,309✔
2826
                // Prune the results cache. Keeps us from unbounded growth. Random delete.
79,309✔
2827
                if len(c.in.results) >= maxResultCacheSize {
81,538✔
2828
                        n := 0
2,229✔
2829
                        for subj := range c.in.results {
75,786✔
2830
                                delete(c.in.results, subj)
73,557✔
2831
                                if n++; n > pruneSize {
75,786✔
2832
                                        break
2,229✔
2833
                                }
2834
                        }
2835
                }
2836
                // Then add the new cache entry.
2837
                c.in.results[subject] = r
79,309✔
2838
        }
2839

2840
        // Collect queue names if needed.
2841
        var qnames [][]byte
105,294✔
2842

105,294✔
2843
        // Check for no interest, short circuit if so.
105,294✔
2844
        // This is the fanout scale.
105,294✔
2845
        if len(r.psubs)+len(r.qsubs) > 0 {
210,137✔
2846
                flag := pmrNoFlag
104,843✔
2847
                // If we have queue subs in this cluster, then if we run in gateway
104,843✔
2848
                // mode and the remote gateways have queue subs, then we need to
104,843✔
2849
                // collect the queue groups this message was sent to so that we
104,843✔
2850
                // exclude them when sending to gateways.
104,843✔
2851
                if len(r.qsubs) > 0 && c.srv.gateway.enabled &&
104,843✔
2852
                        atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 {
117,143✔
2853
                        flag |= pmrCollectQueueNames
12,300✔
2854
                }
12,300✔
2855
                // If this is a mapped subject that means the mapped interest
2856
                // is what got us here, but this might not have a queue designation
2857
                // If that is the case, make sure we ignore to process local queue subscribers.
2858
                if len(c.pa.mapped) > 0 && len(c.pa.queues) == 0 {
105,145✔
2859
                        flag |= pmrIgnoreEmptyQueueFilter
302✔
2860
                }
302✔
2861
                _, qnames = c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, flag)
104,843✔
2862
        }
2863

2864
        // Now deal with gateways
2865
        if c.srv.gateway.enabled {
118,664✔
2866
                c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, qnames, true)
13,370✔
2867
        }
13,370✔
2868
}
2869

2870
// Handles a subscription permission violation.
2871
// See leafPermViolation() for details.
2872
func (c *client) leafSubPermViolation(subj []byte) {
328✔
2873
        c.leafPermViolation(false, subj)
328✔
2874
}
328✔
2875

2876
// Common function to process publish or subscribe leafnode permission violation.
2877
// Sends the permission violation error to the remote, logs it and closes the connection.
2878
// If this is from a server soliciting, the reconnection will be delayed.
2879
func (c *client) leafPermViolation(pub bool, subj []byte) {
328✔
2880
        if c.isSpokeLeafNode() {
656✔
2881
                // For spokes these are no-ops since the hub server told us our permissions.
328✔
2882
                // We just need to not send these over to the other side since we will get cutoff.
328✔
2883
                return
328✔
2884
        }
328✔
2885
        // FIXME(dlc) ?
2886
        c.setLeafConnectDelayIfSoliciting(leafNodeReconnectAfterPermViolation)
×
2887
        var action string
×
2888
        if pub {
×
2889
                c.sendErr(fmt.Sprintf("Permissions Violation for Publish to %q", subj))
×
2890
                action = "Publish"
×
2891
        } else {
×
2892
                c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q", subj))
×
2893
                action = "Subscription"
×
2894
        }
×
2895
        c.Errorf("%s Violation on %q - Check other side configuration", action, subj)
×
2896
        // TODO: add a new close reason that is more appropriate?
×
2897
        c.closeConnection(ProtocolViolation)
×
2898
}
2899

2900
// Invoked from generic processErr() for LEAF connections.
2901
func (c *client) leafProcessErr(errStr string) {
32✔
2902
        // Check if we got a cluster name collision.
32✔
2903
        if strings.Contains(errStr, ErrLeafNodeHasSameClusterName.Error()) {
35✔
2904
                _, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterClusterNameSame)
3✔
2905
                c.Errorf("Leafnode connection dropped with same cluster name error. Delaying attempt to reconnect for %v", delay)
3✔
2906
                return
3✔
2907
        }
3✔
2908

2909
        // We will look for Loop detected error coming from the other side.
2910
        // If we solicit, set the connect delay.
2911
        if !strings.Contains(errStr, "Loop detected") {
50✔
2912
                return
21✔
2913
        }
21✔
2914
        c.handleLeafNodeLoop(false)
8✔
2915
}
2916

2917
// If this leaf connection solicits, sets the connect delay to the given value,
2918
// or the one from the server option's LeafNode.connDelay if one is set (for tests).
2919
// Returns the connection's account name and delay.
2920
func (c *client) setLeafConnectDelayIfSoliciting(delay time.Duration) (string, time.Duration) {
19✔
2921
        c.mu.Lock()
19✔
2922
        if c.isSolicitedLeafNode() {
30✔
2923
                if s := c.srv; s != nil {
22✔
2924
                        if srvdelay := s.getOpts().LeafNode.connDelay; srvdelay != 0 {
15✔
2925
                                delay = srvdelay
4✔
2926
                        }
4✔
2927
                }
2928
                c.leaf.remote.setConnectDelay(delay)
11✔
2929
        }
2930
        accName := c.acc.Name
19✔
2931
        c.mu.Unlock()
19✔
2932
        return accName, delay
19✔
2933
}
2934

2935
// For the given remote Leafnode configuration, this function returns
2936
// if TLS is required, and if so, will return a clone of the TLS Config
2937
// (since some fields will be changed during handshake), the TLS server
2938
// name that is remembered, and the TLS timeout.
2939
func (c *client) leafNodeGetTLSConfigForSolicit(remote *leafNodeCfg) (bool, *tls.Config, string, float64) {
1,803✔
2940
        var (
1,803✔
2941
                tlsConfig  *tls.Config
1,803✔
2942
                tlsName    string
1,803✔
2943
                tlsTimeout float64
1,803✔
2944
        )
1,803✔
2945

1,803✔
2946
        remote.RLock()
1,803✔
2947
        defer remote.RUnlock()
1,803✔
2948

1,803✔
2949
        tlsRequired := remote.TLS || remote.TLSConfig != nil
1,803✔
2950
        if tlsRequired {
1,883✔
2951
                if remote.TLSConfig != nil {
131✔
2952
                        tlsConfig = remote.TLSConfig.Clone()
51✔
2953
                } else {
80✔
2954
                        tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}
29✔
2955
                }
29✔
2956
                tlsName = remote.tlsName
80✔
2957
                tlsTimeout = remote.TLSTimeout
80✔
2958
                if tlsTimeout == 0 {
126✔
2959
                        tlsTimeout = float64(TLS_TIMEOUT / time.Second)
46✔
2960
                }
46✔
2961
        }
2962

2963
        return tlsRequired, tlsConfig, tlsName, tlsTimeout
1,803✔
2964
}
2965

2966
// Initiates the LeafNode Websocket connection by:
2967
// - doing the TLS handshake if needed
2968
// - sending the HTTP request
2969
// - waiting for the HTTP response
2970
//
2971
// Since some bufio reader is used to consume the HTTP response, this function
2972
// returns the slice of buffered bytes (if any) so that the readLoop that will
2973
// be started after that consume those first before reading from the socket.
2974
// The boolean
2975
//
2976
// Lock held on entry.
2977
func (c *client) leafNodeSolicitWSConnection(opts *Options, rURL *url.URL, remote *leafNodeCfg) ([]byte, ClosedState, error) {
43✔
2978
        remote.RLock()
43✔
2979
        compress := remote.Websocket.Compression
43✔
2980
        // By default the server will mask outbound frames, but it can be disabled with this option.
43✔
2981
        noMasking := remote.Websocket.NoMasking
43✔
2982
        infoTimeout := remote.FirstInfoTimeout
43✔
2983
        remote.RUnlock()
43✔
2984
        // Will do the client-side TLS handshake if needed.
43✔
2985
        tlsRequired, err := c.leafClientHandshakeIfNeeded(remote, opts)
43✔
2986
        if err != nil {
47✔
2987
                // 0 will indicate that the connection was already closed
4✔
2988
                return nil, 0, err
4✔
2989
        }
4✔
2990

2991
        // For http request, we need the passed URL to contain either http or https scheme.
2992
        scheme := "http"
39✔
2993
        if tlsRequired {
47✔
2994
                scheme = "https"
8✔
2995
        }
8✔
2996
        // We will use the `/leafnode` path to tell the accepting WS server that it should
2997
        // create a LEAF connection, not a CLIENT.
2998
        // In case we use the user's URL path in the future, make sure we append the user's
2999
        // path to our `/leafnode` path.
3000
        lpath := leafNodeWSPath
39✔
3001
        if curPath := rURL.EscapedPath(); curPath != _EMPTY_ {
60✔
3002
                if curPath[0] == '/' {
42✔
3003
                        curPath = curPath[1:]
21✔
3004
                }
21✔
3005
                lpath = path.Join(curPath, lpath)
21✔
3006
        } else {
18✔
3007
                lpath = lpath[1:]
18✔
3008
        }
18✔
3009
        ustr := fmt.Sprintf("%s://%s/%s", scheme, rURL.Host, lpath)
39✔
3010
        u, _ := url.Parse(ustr)
39✔
3011
        req := &http.Request{
39✔
3012
                Method:     "GET",
39✔
3013
                URL:        u,
39✔
3014
                Proto:      "HTTP/1.1",
39✔
3015
                ProtoMajor: 1,
39✔
3016
                ProtoMinor: 1,
39✔
3017
                Header:     make(http.Header),
39✔
3018
                Host:       u.Host,
39✔
3019
        }
39✔
3020
        wsKey, err := wsMakeChallengeKey()
39✔
3021
        if err != nil {
39✔
3022
                return nil, WriteError, err
×
3023
        }
×
3024

3025
        req.Header["Upgrade"] = []string{"websocket"}
39✔
3026
        req.Header["Connection"] = []string{"Upgrade"}
39✔
3027
        req.Header["Sec-WebSocket-Key"] = []string{wsKey}
39✔
3028
        req.Header["Sec-WebSocket-Version"] = []string{"13"}
39✔
3029
        if compress {
48✔
3030
                req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue)
9✔
3031
        }
9✔
3032
        if noMasking {
49✔
3033
                req.Header.Add(wsNoMaskingHeader, wsNoMaskingValue)
10✔
3034
        }
10✔
3035
        c.nc.SetDeadline(time.Now().Add(infoTimeout))
39✔
3036
        if err := req.Write(c.nc); err != nil {
39✔
3037
                return nil, WriteError, err
×
3038
        }
×
3039

3040
        var resp *http.Response
39✔
3041

39✔
3042
        br := bufio.NewReaderSize(c.nc, MAX_CONTROL_LINE_SIZE)
39✔
3043
        resp, err = http.ReadResponse(br, req)
39✔
3044
        if err == nil &&
39✔
3045
                (resp.StatusCode != 101 ||
39✔
3046
                        !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
39✔
3047
                        !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
39✔
3048
                        resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) {
40✔
3049

1✔
3050
                err = fmt.Errorf("invalid websocket connection")
1✔
3051
        }
1✔
3052
        // Check compression extension...
3053
        if err == nil && c.ws.compress {
48✔
3054
                // Check that not only permessage-deflate extension is present, but that
9✔
3055
                // we also have server and client no context take over.
9✔
3056
                srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header, false)
9✔
3057

9✔
3058
                // If server does not support compression, then simply disable it in our side.
9✔
3059
                if !srvCompress {
13✔
3060
                        c.ws.compress = false
4✔
3061
                } else if !noCtxTakeover {
9✔
3062
                        err = fmt.Errorf("compression negotiation error")
×
3063
                }
×
3064
        }
3065
        // Same for no masking...
3066
        if err == nil && noMasking {
49✔
3067
                // Check if server accepts no masking
10✔
3068
                if resp.Header.Get(wsNoMaskingHeader) != wsNoMaskingValue {
11✔
3069
                        // Nope, need to mask our writes as any client would do.
1✔
3070
                        c.ws.maskwrite = true
1✔
3071
                }
1✔
3072
        }
3073
        if resp != nil {
67✔
3074
                resp.Body.Close()
28✔
3075
        }
28✔
3076
        if err != nil {
51✔
3077
                return nil, ReadError, err
12✔
3078
        }
12✔
3079
        c.Debugf("Leafnode compression=%v masking=%v", c.ws.compress, c.ws.maskwrite)
27✔
3080

27✔
3081
        var preBuf []byte
27✔
3082
        // We have to slurp whatever is in the bufio reader and pass that to the readloop.
27✔
3083
        if n := br.Buffered(); n != 0 {
27✔
3084
                preBuf, _ = br.Peek(n)
×
3085
        }
×
3086
        return preBuf, 0, nil
27✔
3087
}
3088

3089
const connectProcessTimeout = 2 * time.Second
3090

3091
// This is invoked for remote LEAF remote connections after processing the INFO
3092
// protocol.
3093
func (s *Server) leafNodeResumeConnectProcess(c *client) {
628✔
3094
        clusterName := s.ClusterName()
628✔
3095

628✔
3096
        c.mu.Lock()
628✔
3097
        if c.isClosed() {
628✔
3098
                c.mu.Unlock()
×
3099
                return
×
3100
        }
×
3101
        if err := c.sendLeafConnect(clusterName, c.headers); err != nil {
630✔
3102
                c.mu.Unlock()
2✔
3103
                c.closeConnection(WriteError)
2✔
3104
                return
2✔
3105
        }
2✔
3106

3107
        // Spin up the write loop.
3108
        s.startGoRoutine(func() { c.writeLoop() })
1,252✔
3109

3110
        // timeout leafNodeFinishConnectProcess
3111
        c.ping.tmr = time.AfterFunc(connectProcessTimeout, func() {
626✔
3112
                c.mu.Lock()
×
3113
                // check if leafNodeFinishConnectProcess was called and prevent later leafNodeFinishConnectProcess
×
3114
                if !c.flags.setIfNotSet(connectProcessFinished) {
×
3115
                        c.mu.Unlock()
×
3116
                        return
×
3117
                }
×
3118
                clearTimer(&c.ping.tmr)
×
3119
                closed := c.isClosed()
×
3120
                c.mu.Unlock()
×
3121
                if !closed {
×
3122
                        c.sendErrAndDebug("Stale Leaf Node Connection - Closing")
×
3123
                        c.closeConnection(StaleConnection)
×
3124
                }
×
3125
        })
3126
        c.mu.Unlock()
626✔
3127
        c.Debugf("Remote leafnode connect msg sent")
626✔
3128
}
3129

3130
// This is invoked for remote LEAF connections after processing the INFO
3131
// protocol and leafNodeResumeConnectProcess.
3132
// This will send LS+ the CONNECT protocol and register the leaf node.
3133
func (s *Server) leafNodeFinishConnectProcess(c *client) {
607✔
3134
        c.mu.Lock()
607✔
3135
        if !c.flags.setIfNotSet(connectProcessFinished) {
607✔
3136
                c.mu.Unlock()
×
3137
                return
×
3138
        }
×
3139
        if c.isClosed() {
607✔
3140
                c.mu.Unlock()
×
3141
                s.removeLeafNodeConnection(c)
×
3142
                return
×
3143
        }
×
3144
        remote := c.leaf.remote
607✔
3145
        // Check if we will need to send the system connect event.
607✔
3146
        remote.RLock()
607✔
3147
        sendSysConnectEvent := remote.Hub
607✔
3148
        remote.RUnlock()
607✔
3149

607✔
3150
        // Capture account before releasing lock
607✔
3151
        acc := c.acc
607✔
3152
        // cancel connectProcessTimeout
607✔
3153
        clearTimer(&c.ping.tmr)
607✔
3154
        c.mu.Unlock()
607✔
3155

607✔
3156
        // Make sure we register with the account here.
607✔
3157
        if err := c.registerWithAccount(acc); err != nil {
609✔
3158
                if err == ErrTooManyAccountConnections {
2✔
3159
                        c.maxAccountConnExceeded()
×
3160
                        return
×
3161
                } else if err == ErrLeafNodeLoop {
4✔
3162
                        c.handleLeafNodeLoop(true)
2✔
3163
                        return
2✔
3164
                }
2✔
3165
                c.Errorf("Registering leaf with account %s resulted in error: %v", acc.Name, err)
×
3166
                c.closeConnection(ProtocolViolation)
×
3167
                return
×
3168
        }
3169
        s.addLeafNodeConnection(c, _EMPTY_, _EMPTY_, false)
605✔
3170
        s.initLeafNodeSmapAndSendSubs(c)
605✔
3171
        if sendSysConnectEvent {
611✔
3172
                s.sendLeafNodeConnect(acc)
6✔
3173
        }
6✔
3174

3175
        // The above functions are not atomically under the client
3176
        // lock doing those operations. It is possible - since we
3177
        // have started the read/write loops - that the connection
3178
        // is closed before or in between. This would leave the
3179
        // closed LN connection possible registered with the account
3180
        // and/or the server's leafs map. So check if connection
3181
        // is closed, and if so, manually cleanup.
3182
        c.mu.Lock()
605✔
3183
        closed := c.isClosed()
605✔
3184
        if !closed {
1,210✔
3185
                c.setFirstPingTimer()
605✔
3186
        }
605✔
3187
        c.mu.Unlock()
605✔
3188
        if closed {
605✔
3189
                s.removeLeafNodeConnection(c)
×
3190
                if prev := acc.removeClient(c); prev == 1 {
×
3191
                        s.decActiveAccounts()
×
3192
                }
×
3193
        }
3194
}
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