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

nats-io / nats-server / 18424568976

10 Oct 2025 04:26PM UTC coverage: 85.112% (-1.0%) from 86.107%
18424568976

push

github

web-flow
Offline assets: Improve error reporting/logging (#7416)

This improves the error logging for offline assets to:

- Report the same API level errors on the API responses and the log
- Report which specific config fields were invalid or unexpected
- Report which consumers caused a stream to be stopped

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

73858 of 86777 relevant lines covered (85.11%)

351779.76 hits per line

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

90.3
/server/leafnode.go
1
// Copyright 2019-2025 The NATS Authors
2
// Licensed under the Apache License, Version 2.0 (the "License");
3
// you may not use this file except in compliance with the License.
4
// You may obtain a copy of the License at
5
//
6
// http://www.apache.org/licenses/LICENSE-2.0
7
//
8
// Unless required by applicable law or agreed to in writing, software
9
// distributed under the License is distributed on an "AS IS" BASIS,
10
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
// See the License for the specific language governing permissions and
12
// limitations under the License.
13

14
package server
15

16
import (
17
        "bufio"
18
        "bytes"
19
        "crypto/tls"
20
        "encoding/base64"
21
        "encoding/json"
22
        "fmt"
23
        "io"
24
        "math/rand"
25
        "net"
26
        "net/http"
27
        "net/url"
28
        "os"
29
        "path"
30
        "reflect"
31
        "regexp"
32
        "runtime"
33
        "strconv"
34
        "strings"
35
        "sync"
36
        "sync/atomic"
37
        "time"
38

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

286
        // If a remote has a websocket scheme, all need to have it.
287
        for _, rcfg := range o.LeafNode.Remotes {
10,152✔
288
                // Validate proxy configuration
1,381✔
289
                if _, err := validateLeafNodeProxyOptions(rcfg); err != nil {
1,387✔
290
                        return err
6✔
291
                }
6✔
292

293
                if len(rcfg.URLs) >= 2 {
1,575✔
294
                        firstIsWS, ok := isWSURL(rcfg.URLs[0]), true
200✔
295
                        for i := 1; i < len(rcfg.URLs); i++ {
645✔
296
                                u := rcfg.URLs[i]
445✔
297
                                if isWS := isWSURL(u); isWS && !firstIsWS || !isWS && firstIsWS {
452✔
298
                                        ok = false
7✔
299
                                        break
7✔
300
                                }
301
                        }
302
                        if !ok {
207✔
303
                                return fmt.Errorf("remote leaf node configuration cannot have a mix of websocket and non-websocket urls: %q", redactURLList(rcfg.URLs))
7✔
304
                        }
7✔
305
                }
306
                // Validate compression settings
307
                if rcfg.Compression.Mode != _EMPTY_ {
2,732✔
308
                        if err := validateAndNormalizeCompressionOption(&rcfg.Compression, CompressionS2Auto); err != nil {
1,369✔
309
                                return err
5✔
310
                        }
5✔
311
                }
312
        }
313

314
        if o.LeafNode.Port == 0 {
13,855✔
315
                return nil
5,102✔
316
        }
5,102✔
317

318
        // If MinVersion is defined, check that it is valid.
319
        if mv := o.LeafNode.MinVersion; mv != _EMPTY_ {
3,655✔
320
                if err := checkLeafMinVersionConfig(mv); err != nil {
6✔
321
                        return err
2✔
322
                }
2✔
323
        }
324

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

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

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

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

377
func validateLeafNodeProxyOptions(remote *RemoteLeafOpts) ([]string, error) {
1,393✔
378
        var warnings []string
1,393✔
379

1,393✔
380
        if remote.Proxy.URL == _EMPTY_ {
2,762✔
381
                return warnings, nil
1,369✔
382
        }
1,369✔
383

384
        proxyURL, err := url.Parse(remote.Proxy.URL)
24✔
385
        if err != nil {
25✔
386
                return warnings, fmt.Errorf("invalid proxy URL: %v", err)
1✔
387
        }
1✔
388

389
        if proxyURL.Scheme != "http" && proxyURL.Scheme != "https" {
25✔
390
                return warnings, fmt.Errorf("proxy URL scheme must be http or https, got: %s", proxyURL.Scheme)
2✔
391
        }
2✔
392

393
        if proxyURL.Host == _EMPTY_ {
23✔
394
                return warnings, fmt.Errorf("proxy URL must specify a host")
2✔
395
        }
2✔
396

397
        if remote.Proxy.Timeout < 0 {
20✔
398
                return warnings, fmt.Errorf("proxy timeout must be >= 0")
1✔
399
        }
1✔
400

401
        if (remote.Proxy.Username == _EMPTY_) != (remote.Proxy.Password == _EMPTY_) {
22✔
402
                return warnings, fmt.Errorf("proxy username and password must both be specified or both be empty")
4✔
403
        }
4✔
404

405
        if len(remote.URLs) > 0 {
28✔
406
                hasWebSocketURL := false
14✔
407
                hasNonWebSocketURL := false
14✔
408

14✔
409
                for _, remoteURL := range remote.URLs {
29✔
410
                        if remoteURL.Scheme == wsSchemePrefix || remoteURL.Scheme == wsSchemePrefixTLS {
28✔
411
                                hasWebSocketURL = true
13✔
412
                                if (remoteURL.Scheme == wsSchemePrefixTLS) &&
13✔
413
                                        remote.TLSConfig == nil && !remote.TLS {
14✔
414
                                        return warnings, fmt.Errorf("proxy is configured but remote URL %s requires TLS and no TLS configuration is provided. When using proxy with TLS endpoints, ensure TLS is properly configured for the leafnode remote", remoteURL.String())
1✔
415
                                }
1✔
416
                        } else {
2✔
417
                                hasNonWebSocketURL = true
2✔
418
                        }
2✔
419
                }
420

421
                if !hasWebSocketURL {
14✔
422
                        warnings = append(warnings, "proxy configuration will be ignored: proxy settings only apply to WebSocket connections (ws:// or wss://), but all configured URLs use TCP connections (nats://)")
1✔
423
                } else if hasNonWebSocketURL {
14✔
424
                        warnings = append(warnings, "proxy configuration will only be used for WebSocket URLs: proxy settings do not apply to TCP connections (nats://)")
1✔
425
                }
1✔
426
        }
427

428
        return warnings, nil
13✔
429
}
430

431
// Update remote LeafNode TLS configurations after a config reload.
432
func (s *Server) updateRemoteLeafNodesTLSConfig(opts *Options) {
15✔
433
        max := len(opts.LeafNode.Remotes)
15✔
434
        if max == 0 {
15✔
435
                return
×
436
        }
×
437

438
        s.mu.RLock()
15✔
439
        defer s.mu.RUnlock()
15✔
440

15✔
441
        // Changes in the list of remote leaf nodes is not supported.
15✔
442
        // However, make sure that we don't go over the arrays.
15✔
443
        if len(s.leafRemoteCfgs) < max {
15✔
444
                max = len(s.leafRemoteCfgs)
×
445
        }
×
446
        for i := 0; i < max; i++ {
34✔
447
                ro := opts.LeafNode.Remotes[i]
19✔
448
                cfg := s.leafRemoteCfgs[i]
19✔
449
                if ro.TLSConfig != nil {
21✔
450
                        cfg.Lock()
2✔
451
                        cfg.TLSConfig = ro.TLSConfig.Clone()
2✔
452
                        cfg.TLSHandshakeFirst = ro.TLSHandshakeFirst
2✔
453
                        cfg.Unlock()
2✔
454
                }
2✔
455
        }
456
}
457

458
func (s *Server) reConnectToRemoteLeafNode(remote *leafNodeCfg) {
255✔
459
        delay := s.getOpts().LeafNode.ReconnectInterval
255✔
460
        select {
255✔
461
        case <-time.After(delay):
196✔
462
        case <-s.quitCh:
59✔
463
                s.grWG.Done()
59✔
464
                return
59✔
465
        }
466
        s.connectToRemoteLeafNode(remote, false)
196✔
467
}
468

469
// Creates a leafNodeCfg object that wraps the RemoteLeafOpts.
470
func newLeafNodeCfg(remote *RemoteLeafOpts) *leafNodeCfg {
1,332✔
471
        cfg := &leafNodeCfg{
1,332✔
472
                RemoteLeafOpts: remote,
1,332✔
473
                urls:           make([]*url.URL, 0, len(remote.URLs)),
1,332✔
474
        }
1,332✔
475
        if len(remote.DenyExports) > 0 || len(remote.DenyImports) > 0 {
1,340✔
476
                perms := &Permissions{}
8✔
477
                if len(remote.DenyExports) > 0 {
16✔
478
                        perms.Publish = &SubjectPermission{Deny: remote.DenyExports}
8✔
479
                }
8✔
480
                if len(remote.DenyImports) > 0 {
15✔
481
                        perms.Subscribe = &SubjectPermission{Deny: remote.DenyImports}
7✔
482
                }
7✔
483
                cfg.perms = perms
8✔
484
        }
485
        // Start with the one that is configured. We will add to this
486
        // array when receiving async leafnode INFOs.
487
        cfg.urls = append(cfg.urls, cfg.URLs...)
1,332✔
488
        // If allowed to randomize, do it on our copy of URLs
1,332✔
489
        if !remote.NoRandomize {
2,662✔
490
                rand.Shuffle(len(cfg.urls), func(i, j int) {
1,732✔
491
                        cfg.urls[i], cfg.urls[j] = cfg.urls[j], cfg.urls[i]
402✔
492
                })
402✔
493
        }
494
        // If we are TLS make sure we save off a proper servername if possible.
495
        // Do same for user/password since we may need them to connect to
496
        // a bare URL that we get from INFO protocol.
497
        for _, u := range cfg.urls {
3,096✔
498
                cfg.saveTLSHostname(u)
1,764✔
499
                cfg.saveUserPassword(u)
1,764✔
500
                // If the url(s) have the "wss://" scheme, and we don't have a TLS
1,764✔
501
                // config, mark that we should be using TLS anyway.
1,764✔
502
                if !cfg.TLS && isWSSURL(u) {
1,765✔
503
                        cfg.TLS = true
1✔
504
                }
1✔
505
        }
506
        return cfg
1,332✔
507
}
508

509
// Will pick an URL from the list of available URLs.
510
func (cfg *leafNodeCfg) pickNextURL() *url.URL {
7,085✔
511
        cfg.Lock()
7,085✔
512
        defer cfg.Unlock()
7,085✔
513
        // If the current URL is the first in the list and we have more than
7,085✔
514
        // one URL, then move that one to end of the list.
7,085✔
515
        if cfg.curURL != nil && len(cfg.urls) > 1 && urlsAreEqual(cfg.curURL, cfg.urls[0]) {
10,699✔
516
                first := cfg.urls[0]
3,614✔
517
                copy(cfg.urls, cfg.urls[1:])
3,614✔
518
                cfg.urls[len(cfg.urls)-1] = first
3,614✔
519
        }
3,614✔
520
        cfg.curURL = cfg.urls[0]
7,085✔
521
        return cfg.curURL
7,085✔
522
}
523

524
// Returns the current URL
525
func (cfg *leafNodeCfg) getCurrentURL() *url.URL {
84✔
526
        cfg.RLock()
84✔
527
        defer cfg.RUnlock()
84✔
528
        return cfg.curURL
84✔
529
}
84✔
530

531
// Returns how long the server should wait before attempting
532
// to solicit a remote leafnode connection.
533
func (cfg *leafNodeCfg) getConnectDelay() time.Duration {
1,529✔
534
        cfg.RLock()
1,529✔
535
        delay := cfg.connDelay
1,529✔
536
        cfg.RUnlock()
1,529✔
537
        return delay
1,529✔
538
}
1,529✔
539

540
// Sets the connect delay.
541
func (cfg *leafNodeCfg) setConnectDelay(delay time.Duration) {
147✔
542
        cfg.Lock()
147✔
543
        cfg.connDelay = delay
147✔
544
        cfg.Unlock()
147✔
545
}
147✔
546

547
// Ensure that non-exported options (used in tests) have
548
// been properly set.
549
func (s *Server) setLeafNodeNonExportedOptions() {
7,245✔
550
        opts := s.getOpts()
7,245✔
551
        s.leafNodeOpts.dialTimeout = opts.LeafNode.dialTimeout
7,245✔
552
        if s.leafNodeOpts.dialTimeout == 0 {
14,489✔
553
                // Use same timeouts as routes for now.
7,244✔
554
                s.leafNodeOpts.dialTimeout = DEFAULT_ROUTE_DIAL
7,244✔
555
        }
7,244✔
556
        s.leafNodeOpts.resolver = opts.LeafNode.resolver
7,245✔
557
        if s.leafNodeOpts.resolver == nil {
14,486✔
558
                s.leafNodeOpts.resolver = net.DefaultResolver
7,241✔
559
        }
7,241✔
560
}
561

562
const sharedSysAccDelay = 250 * time.Millisecond
563

564
// establishHTTPProxyTunnel establishes an HTTP CONNECT tunnel through a proxy server
565
func establishHTTPProxyTunnel(proxyURL, targetHost string, timeout time.Duration, username, password string) (net.Conn, error) {
10✔
566
        proxyAddr, err := url.Parse(proxyURL)
10✔
567
        if err != nil {
10✔
568
                // This should not happen since proxy URL is validated during configuration parsing
×
569
                return nil, fmt.Errorf("unexpected proxy URL parse error (URL was pre-validated): %v", err)
×
570
        }
×
571

572
        // Connect to the proxy server
573
        conn, err := natsDialTimeout("tcp", proxyAddr.Host, timeout)
10✔
574
        if err != nil {
10✔
575
                return nil, fmt.Errorf("failed to connect to proxy: %v", err)
×
576
        }
×
577

578
        // Set deadline for the entire proxy handshake
579
        if err := conn.SetDeadline(time.Now().Add(timeout)); err != nil {
10✔
580
                conn.Close()
×
581
                return nil, fmt.Errorf("failed to set deadline: %v", err)
×
582
        }
×
583

584
        req := &http.Request{
10✔
585
                Method: http.MethodConnect,
10✔
586
                URL:    &url.URL{Opaque: targetHost}, // Opaque is required for CONNECT
10✔
587
                Host:   targetHost,
10✔
588
                Header: make(http.Header),
10✔
589
        }
10✔
590

10✔
591
        // Add proxy authentication if provided
10✔
592
        if username != "" && password != "" {
12✔
593
                req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password)))
2✔
594
        }
2✔
595

596
        if err := req.Write(conn); err != nil {
10✔
597
                conn.Close()
×
598
                return nil, fmt.Errorf("failed to write CONNECT request: %v", err)
×
599
        }
×
600

601
        resp, err := http.ReadResponse(bufio.NewReader(conn), req)
10✔
602
        if err != nil {
10✔
603
                conn.Close()
×
604
                return nil, fmt.Errorf("failed to read proxy response: %v", err)
×
605
        }
×
606

607
        if resp.StatusCode != http.StatusOK {
11✔
608
                resp.Body.Close()
1✔
609
                conn.Close()
1✔
610
                return nil, fmt.Errorf("proxy CONNECT failed: %s", resp.Status)
1✔
611
        }
1✔
612

613
        // Close the response body
614
        resp.Body.Close()
9✔
615

9✔
616
        // Clear the deadline now that we've finished the proxy handshake
9✔
617
        if err := conn.SetDeadline(time.Time{}); err != nil {
9✔
618
                conn.Close()
×
619
                return nil, fmt.Errorf("failed to clear deadline: %v", err)
×
620
        }
×
621

622
        return conn, nil
9✔
623
}
624

625
func (s *Server) connectToRemoteLeafNode(remote *leafNodeCfg, firstConnect bool) {
1,529✔
626
        defer s.grWG.Done()
1,529✔
627

1,529✔
628
        if remote == nil || len(remote.URLs) == 0 {
1,529✔
629
                s.Debugf("Empty remote leafnode definition, nothing to connect")
×
630
                return
×
631
        }
×
632

633
        opts := s.getOpts()
1,529✔
634
        reconnectDelay := opts.LeafNode.ReconnectInterval
1,529✔
635
        s.mu.RLock()
1,529✔
636
        dialTimeout := s.leafNodeOpts.dialTimeout
1,529✔
637
        resolver := s.leafNodeOpts.resolver
1,529✔
638
        var isSysAcc bool
1,529✔
639
        if s.eventsEnabled() {
3,023✔
640
                isSysAcc = remote.LocalAccount == s.sys.account.Name
1,494✔
641
        }
1,494✔
642
        jetstreamMigrateDelay := remote.JetStreamClusterMigrateDelay
1,529✔
643
        s.mu.RUnlock()
1,529✔
644

1,529✔
645
        // If we are sharing a system account and we are not standalone delay to gather some info prior.
1,529✔
646
        if firstConnect && isSysAcc && !s.standAloneMode() {
1,596✔
647
                s.Debugf("Will delay first leafnode connect to shared system account due to clustering")
67✔
648
                remote.setConnectDelay(sharedSysAccDelay)
67✔
649
        }
67✔
650

651
        if connDelay := remote.getConnectDelay(); connDelay > 0 {
1,603✔
652
                select {
74✔
653
                case <-time.After(connDelay):
69✔
654
                case <-s.quitCh:
5✔
655
                        return
5✔
656
                }
657
                remote.setConnectDelay(0)
69✔
658
        }
659

660
        var conn net.Conn
1,524✔
661

1,524✔
662
        const connErrFmt = "Error trying to connect as leafnode to remote server %q (attempt %v): %v"
1,524✔
663

1,524✔
664
        // Capture proxy configuration once before the loop with proper locking
1,524✔
665
        remote.RLock()
1,524✔
666
        proxyURL := remote.Proxy.URL
1,524✔
667
        proxyUsername := remote.Proxy.Username
1,524✔
668
        proxyPassword := remote.Proxy.Password
1,524✔
669
        proxyTimeout := remote.Proxy.Timeout
1,524✔
670
        remote.RUnlock()
1,524✔
671

1,524✔
672
        // Set default proxy timeout if not specified
1,524✔
673
        if proxyTimeout == 0 {
3,041✔
674
                proxyTimeout = dialTimeout
1,517✔
675
        }
1,517✔
676

677
        attempts := 0
1,524✔
678

1,524✔
679
        for s.isRunning() && s.remoteLeafNodeStillValid(remote) {
8,609✔
680
                rURL := remote.pickNextURL()
7,085✔
681
                url, err := s.getRandomIP(resolver, rURL.Host, nil)
7,085✔
682
                if err == nil {
14,163✔
683
                        var ipStr string
7,078✔
684
                        if url != rURL.Host {
7,152✔
685
                                ipStr = fmt.Sprintf(" (%s)", url)
74✔
686
                        }
74✔
687
                        // Some test may want to disable remotes from connecting
688
                        if s.isLeafConnectDisabled() {
7,204✔
689
                                s.Debugf("Will not attempt to connect to remote server on %q%s, leafnodes currently disabled", rURL.Host, ipStr)
126✔
690
                                err = ErrLeafNodeDisabled
126✔
691
                        } else {
7,078✔
692
                                s.Debugf("Trying to connect as leafnode to remote server on %q%s", rURL.Host, ipStr)
6,952✔
693

6,952✔
694
                                // Check if proxy is configured first, then check if URL supports it
6,952✔
695
                                if proxyURL != _EMPTY_ && isWSURL(rURL) {
6,959✔
696
                                        // Use proxy for WebSocket connections - use original hostname, resolved IP for connection
7✔
697
                                        targetHost := rURL.Host
7✔
698
                                        // If URL doesn't include port, add the default port for the scheme
7✔
699
                                        if rURL.Port() == _EMPTY_ {
7✔
700
                                                defaultPort := "80"
×
701
                                                if rURL.Scheme == wsSchemePrefixTLS {
×
702
                                                        defaultPort = "443"
×
703
                                                }
×
704
                                                targetHost = net.JoinHostPort(rURL.Hostname(), defaultPort)
×
705
                                        }
706

707
                                        conn, err = establishHTTPProxyTunnel(proxyURL, targetHost, proxyTimeout, proxyUsername, proxyPassword)
7✔
708
                                } else {
6,945✔
709
                                        // Direct connection
6,945✔
710
                                        conn, err = natsDialTimeout("tcp", url, dialTimeout)
6,945✔
711
                                }
6,945✔
712
                        }
713
                }
714
                if err != nil {
13,359✔
715
                        jitter := time.Duration(rand.Int63n(int64(reconnectDelay)))
6,274✔
716
                        delay := reconnectDelay + jitter
6,274✔
717
                        attempts++
6,274✔
718
                        if s.shouldReportConnectErr(firstConnect, attempts) {
10,613✔
719
                                s.Errorf(connErrFmt, rURL.Host, attempts, err)
4,339✔
720
                        } else {
6,274✔
721
                                s.Debugf(connErrFmt, rURL.Host, attempts, err)
1,935✔
722
                        }
1,935✔
723
                        remote.Lock()
6,274✔
724
                        // if we are using a delay to start migrating assets, kick off a migrate timer.
6,274✔
725
                        if remote.jsMigrateTimer == nil && jetstreamMigrateDelay > 0 {
6,282✔
726
                                remote.jsMigrateTimer = time.AfterFunc(jetstreamMigrateDelay, func() {
16✔
727
                                        s.checkJetStreamMigrate(remote)
8✔
728
                                })
8✔
729
                        }
730
                        remote.Unlock()
6,274✔
731
                        select {
6,274✔
732
                        case <-s.quitCh:
699✔
733
                                remote.cancelMigrateTimer()
699✔
734
                                return
699✔
735
                        case <-time.After(delay):
5,574✔
736
                                // Check if we should migrate any JetStream assets immediately while this remote is down.
5,574✔
737
                                // This will be used if JetStreamClusterMigrateDelay was not set
5,574✔
738
                                if jetstreamMigrateDelay == 0 {
11,074✔
739
                                        s.checkJetStreamMigrate(remote)
5,500✔
740
                                }
5,500✔
741
                                continue
5,574✔
742
                        }
743
                }
744
                remote.cancelMigrateTimer()
811✔
745
                if !s.remoteLeafNodeStillValid(remote) {
811✔
746
                        conn.Close()
×
747
                        return
×
748
                }
×
749

750
                // We have a connection here to a remote server.
751
                // Go ahead and create our leaf node and return.
752
                s.createLeafNode(conn, rURL, remote, nil)
811✔
753

811✔
754
                // Clear any observer states if we had them.
811✔
755
                s.clearObserverState(remote)
811✔
756

811✔
757
                return
811✔
758
        }
759
}
760

761
func (cfg *leafNodeCfg) cancelMigrateTimer() {
1,510✔
762
        cfg.Lock()
1,510✔
763
        stopAndClearTimer(&cfg.jsMigrateTimer)
1,510✔
764
        cfg.Unlock()
1,510✔
765
}
1,510✔
766

767
// This will clear any observer state such that stream or consumer assets on this server can become leaders again.
768
func (s *Server) clearObserverState(remote *leafNodeCfg) {
811✔
769
        s.mu.RLock()
811✔
770
        accName := remote.LocalAccount
811✔
771
        s.mu.RUnlock()
811✔
772

811✔
773
        acc, err := s.LookupAccount(accName)
811✔
774
        if err != nil {
813✔
775
                s.Warnf("Error looking up account [%s] checking for JetStream clear observer state on a leafnode", accName)
2✔
776
                return
2✔
777
        }
2✔
778

779
        acc.jscmMu.Lock()
809✔
780
        defer acc.jscmMu.Unlock()
809✔
781

809✔
782
        // Walk all streams looking for any clustered stream, skip otherwise.
809✔
783
        for _, mset := range acc.streams() {
827✔
784
                node := mset.raftNode()
18✔
785
                if node == nil {
28✔
786
                        // Not R>1
10✔
787
                        continue
10✔
788
                }
789
                // Check consumers
790
                for _, o := range mset.getConsumers() {
10✔
791
                        if n := o.raftNode(); n != nil {
4✔
792
                                // Ensure we can become a leader again.
2✔
793
                                n.SetObserver(false)
2✔
794
                        }
2✔
795
                }
796
                // Ensure we can not become a leader again.
797
                node.SetObserver(false)
8✔
798
        }
799
}
800

801
// Check to see if we should migrate any assets from this account.
802
func (s *Server) checkJetStreamMigrate(remote *leafNodeCfg) {
5,508✔
803
        s.mu.RLock()
5,508✔
804
        accName, shouldMigrate := remote.LocalAccount, remote.JetStreamClusterMigrate
5,508✔
805
        s.mu.RUnlock()
5,508✔
806

5,508✔
807
        if !shouldMigrate {
10,956✔
808
                return
5,448✔
809
        }
5,448✔
810

811
        acc, err := s.LookupAccount(accName)
60✔
812
        if err != nil {
60✔
813
                s.Warnf("Error looking up account [%s] checking for JetStream migration on a leafnode", accName)
×
814
                return
×
815
        }
×
816

817
        acc.jscmMu.Lock()
60✔
818
        defer acc.jscmMu.Unlock()
60✔
819

60✔
820
        // Walk all streams looking for any clustered stream, skip otherwise.
60✔
821
        // If we are the leader force stepdown.
60✔
822
        for _, mset := range acc.streams() {
90✔
823
                node := mset.raftNode()
30✔
824
                if node == nil {
30✔
825
                        // Not R>1
×
826
                        continue
×
827
                }
828
                // Collect any consumers
829
                for _, o := range mset.getConsumers() {
48✔
830
                        if n := o.raftNode(); n != nil {
36✔
831
                                n.StepDown()
18✔
832
                                // Ensure we can not become a leader while in this state.
18✔
833
                                n.SetObserver(true)
18✔
834
                        }
18✔
835
                }
836
                // Stepdown if this stream was leader.
837
                node.StepDown()
30✔
838
                // Ensure we can not become a leader while in this state.
30✔
839
                node.SetObserver(true)
30✔
840
        }
841
}
842

843
// Helper for checking.
844
func (s *Server) isLeafConnectDisabled() bool {
7,078✔
845
        s.mu.RLock()
7,078✔
846
        defer s.mu.RUnlock()
7,078✔
847
        return s.leafDisableConnect
7,078✔
848
}
7,078✔
849

850
// Save off the tlsName for when we use TLS and mix hostnames and IPs. IPs usually
851
// come from the server we connect to.
852
//
853
// We used to save the name only if there was a TLSConfig or scheme equal to "tls".
854
// However, this was causing failures for users that did not set the scheme (and
855
// their remote connections did not have a tls{} block).
856
// We now save the host name regardless in case the remote returns an INFO indicating
857
// that TLS is required.
858
func (cfg *leafNodeCfg) saveTLSHostname(u *url.URL) {
2,440✔
859
        if cfg.tlsName == _EMPTY_ && net.ParseIP(u.Hostname()) == nil {
2,460✔
860
                cfg.tlsName = u.Hostname()
20✔
861
        }
20✔
862
}
863

864
// Save off the username/password for when we connect using a bare URL
865
// that we get from the INFO protocol.
866
func (cfg *leafNodeCfg) saveUserPassword(u *url.URL) {
1,764✔
867
        if cfg.username == _EMPTY_ && u.User != nil {
2,061✔
868
                cfg.username = u.User.Username()
297✔
869
                cfg.password, _ = u.User.Password()
297✔
870
        }
297✔
871
}
872

873
// This starts the leafnode accept loop in a go routine, unless it
874
// is detected that the server has already been shutdown.
875
func (s *Server) startLeafNodeAcceptLoop() {
3,617✔
876
        // Snapshot server options.
3,617✔
877
        opts := s.getOpts()
3,617✔
878

3,617✔
879
        port := opts.LeafNode.Port
3,617✔
880
        if port == -1 {
7,057✔
881
                port = 0
3,440✔
882
        }
3,440✔
883

884
        if s.isShuttingDown() {
3,618✔
885
                return
1✔
886
        }
1✔
887

888
        s.mu.Lock()
3,616✔
889
        hp := net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(port))
3,616✔
890
        l, e := natsListen("tcp", hp)
3,616✔
891
        s.leafNodeListenerErr = e
3,616✔
892
        if e != nil {
3,616✔
893
                s.mu.Unlock()
×
894
                s.Fatalf("Error listening on leafnode port: %d - %v", opts.LeafNode.Port, e)
×
895
                return
×
896
        }
×
897

898
        s.Noticef("Listening for leafnode connections on %s",
3,616✔
899
                net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
3,616✔
900

3,616✔
901
        tlsRequired := opts.LeafNode.TLSConfig != nil
3,616✔
902
        tlsVerify := tlsRequired && opts.LeafNode.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert
3,616✔
903
        // Do not set compression in this Info object, it would possibly cause
3,616✔
904
        // issues when sending asynchronous INFO to the remote.
3,616✔
905
        info := Info{
3,616✔
906
                ID:            s.info.ID,
3,616✔
907
                Name:          s.info.Name,
3,616✔
908
                Version:       s.info.Version,
3,616✔
909
                GitCommit:     gitCommit,
3,616✔
910
                GoVersion:     runtime.Version(),
3,616✔
911
                AuthRequired:  true,
3,616✔
912
                TLSRequired:   tlsRequired,
3,616✔
913
                TLSVerify:     tlsVerify,
3,616✔
914
                MaxPayload:    s.info.MaxPayload, // TODO(dlc) - Allow override?
3,616✔
915
                Headers:       s.supportsHeaders(),
3,616✔
916
                JetStream:     opts.JetStream,
3,616✔
917
                Domain:        opts.JetStreamDomain,
3,616✔
918
                Proto:         s.getServerProto(),
3,616✔
919
                InfoOnConnect: true,
3,616✔
920
                JSApiLevel:    JSApiLevel,
3,616✔
921
        }
3,616✔
922
        // If we have selected a random port...
3,616✔
923
        if port == 0 {
7,055✔
924
                // Write resolved port back to options.
3,439✔
925
                opts.LeafNode.Port = l.Addr().(*net.TCPAddr).Port
3,439✔
926
        }
3,439✔
927

928
        s.leafNodeInfo = info
3,616✔
929
        // Possibly override Host/Port and set IP based on Cluster.Advertise
3,616✔
930
        if err := s.setLeafNodeInfoHostPortAndIP(); err != nil {
3,616✔
931
                s.Fatalf("Error setting leafnode INFO with LeafNode.Advertise value of %s, err=%v", opts.LeafNode.Advertise, err)
×
932
                l.Close()
×
933
                s.mu.Unlock()
×
934
                return
×
935
        }
×
936
        s.leafURLsMap[s.leafNodeInfo.IP]++
3,616✔
937
        s.generateLeafNodeInfoJSON()
3,616✔
938

3,616✔
939
        // Setup state that can enable shutdown
3,616✔
940
        s.leafNodeListener = l
3,616✔
941

3,616✔
942
        // As of now, a server that does not have remotes configured would
3,616✔
943
        // never solicit a connection, so we should not have to warn if
3,616✔
944
        // InsecureSkipVerify is set in main LeafNodes config (since
3,616✔
945
        // this TLS setting matters only when soliciting a connection).
3,616✔
946
        // Still, warn if insecure is set in any of LeafNode block.
3,616✔
947
        // We need to check remotes, even if tls is not required on accept.
3,616✔
948
        warn := tlsRequired && opts.LeafNode.TLSConfig.InsecureSkipVerify
3,616✔
949
        if !warn {
7,228✔
950
                for _, r := range opts.LeafNode.Remotes {
3,806✔
951
                        if r.TLSConfig != nil && r.TLSConfig.InsecureSkipVerify {
195✔
952
                                warn = true
1✔
953
                                break
1✔
954
                        }
955
                }
956
        }
957
        if warn {
3,621✔
958
                s.Warnf(leafnodeTLSInsecureWarning)
5✔
959
        }
5✔
960
        go s.acceptConnections(l, "Leafnode", func(conn net.Conn) { s.createLeafNode(conn, nil, nil, nil) }, nil)
4,465✔
961
        s.mu.Unlock()
3,616✔
962
}
963

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

967
// clusterName is provided as argument to avoid lock ordering issues with the locked client c
968
// Lock should be held entering here.
969
func (c *client) sendLeafConnect(clusterName string, headers bool) error {
682✔
970
        // We support basic user/pass and operator based user JWT with signatures.
682✔
971
        cinfo := leafConnectInfo{
682✔
972
                Version:       VERSION,
682✔
973
                ID:            c.srv.info.ID,
682✔
974
                Domain:        c.srv.info.Domain,
682✔
975
                Name:          c.srv.info.Name,
682✔
976
                Hub:           c.leaf.remote.Hub,
682✔
977
                Cluster:       clusterName,
682✔
978
                Headers:       headers,
682✔
979
                JetStream:     c.acc.jetStreamConfigured(),
682✔
980
                DenyPub:       c.leaf.remote.DenyImports,
682✔
981
                Compression:   c.leaf.compression,
682✔
982
                RemoteAccount: c.acc.GetName(),
682✔
983
                Proto:         c.srv.getServerProto(),
682✔
984
                Isolate:       c.leaf.remote.RequestIsolation,
682✔
985
        }
682✔
986

682✔
987
        // If a signature callback is specified, this takes precedence over anything else.
682✔
988
        if cb := c.leaf.remote.SignatureCB; cb != nil {
687✔
989
                nonce := c.nonce
5✔
990
                c.mu.Unlock()
5✔
991
                jwt, sigraw, err := cb(nonce)
5✔
992
                c.mu.Lock()
5✔
993
                if err == nil && c.isClosed() {
6✔
994
                        err = ErrConnectionClosed
1✔
995
                }
1✔
996
                if err != nil {
7✔
997
                        c.Errorf("Error signing the nonce: %v", err)
2✔
998
                        return err
2✔
999
                }
2✔
1000
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
3✔
1001
                cinfo.JWT, cinfo.Sig = jwt, sig
3✔
1002

1003
        } else if creds := c.leaf.remote.Credentials; creds != _EMPTY_ {
731✔
1004
                // Check for credentials first, that will take precedence..
54✔
1005
                c.Debugf("Authenticating with credentials file %q", c.leaf.remote.Credentials)
54✔
1006
                contents, err := os.ReadFile(creds)
54✔
1007
                if err != nil {
54✔
1008
                        c.Errorf("%v", err)
×
1009
                        return err
×
1010
                }
×
1011
                defer wipeSlice(contents)
54✔
1012
                items := credsRe.FindAllSubmatch(contents, -1)
54✔
1013
                if len(items) < 2 {
54✔
1014
                        c.Errorf("Credentials file malformed")
×
1015
                        return err
×
1016
                }
×
1017
                // First result should be the user JWT.
1018
                // We copy here so that the file containing the seed will be wiped appropriately.
1019
                raw := items[0][1]
54✔
1020
                tmp := make([]byte, len(raw))
54✔
1021
                copy(tmp, raw)
54✔
1022
                // Seed is second item.
54✔
1023
                kp, err := nkeys.FromSeed(items[1][1])
54✔
1024
                if err != nil {
54✔
1025
                        c.Errorf("Credentials file has malformed seed")
×
1026
                        return err
×
1027
                }
×
1028
                // Wipe our key on exit.
1029
                defer kp.Wipe()
54✔
1030

54✔
1031
                sigraw, _ := kp.Sign(c.nonce)
54✔
1032
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
54✔
1033
                cinfo.JWT = bytesToString(tmp)
54✔
1034
                cinfo.Sig = sig
54✔
1035
        } else if nkey := c.leaf.remote.Nkey; nkey != _EMPTY_ {
628✔
1036
                kp, err := nkeys.FromSeed([]byte(nkey))
5✔
1037
                if err != nil {
5✔
1038
                        c.Errorf("Remote nkey has malformed seed")
×
1039
                        return err
×
1040
                }
×
1041
                // Wipe our key on exit.
1042
                defer kp.Wipe()
5✔
1043
                sigraw, _ := kp.Sign(c.nonce)
5✔
1044
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
5✔
1045
                pkey, _ := kp.PublicKey()
5✔
1046
                cinfo.Nkey = pkey
5✔
1047
                cinfo.Sig = sig
5✔
1048
        }
1049
        // In addition, and this is to allow auth callout, set user/password or
1050
        // token if applicable.
1051
        if userInfo := c.leaf.remote.curURL.User; userInfo != nil {
1,001✔
1052
                // For backward compatibility, if only username is provided, set both
321✔
1053
                // Token and User, not just Token.
321✔
1054
                cinfo.User = userInfo.Username()
321✔
1055
                var ok bool
321✔
1056
                cinfo.Pass, ok = userInfo.Password()
321✔
1057
                if !ok {
327✔
1058
                        cinfo.Token = cinfo.User
6✔
1059
                }
6✔
1060
        } else if c.leaf.remote.username != _EMPTY_ {
366✔
1061
                cinfo.User = c.leaf.remote.username
7✔
1062
                cinfo.Pass = c.leaf.remote.password
7✔
1063
        }
7✔
1064
        b, err := json.Marshal(cinfo)
680✔
1065
        if err != nil {
680✔
1066
                c.Errorf("Error marshaling CONNECT to remote leafnode: %v\n", err)
×
1067
                return err
×
1068
        }
×
1069
        // Although this call is made before the writeLoop is created,
1070
        // we don't really need to send in place. The protocol will be
1071
        // sent out by the writeLoop.
1072
        c.enqueueProto([]byte(fmt.Sprintf(ConProto, b)))
680✔
1073
        return nil
680✔
1074
}
1075

1076
// Makes a deep copy of the LeafNode Info structure.
1077
// The server lock is held on entry.
1078
func (s *Server) copyLeafNodeInfo() *Info {
2,744✔
1079
        clone := s.leafNodeInfo
2,744✔
1080
        // Copy the array of urls.
2,744✔
1081
        if len(s.leafNodeInfo.LeafNodeURLs) > 0 {
4,980✔
1082
                clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...)
2,236✔
1083
        }
2,236✔
1084
        return &clone
2,744✔
1085
}
1086

1087
// Adds a LeafNode URL that we get when a route connects to the Info structure.
1088
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
1089
// Returns a boolean indicating if the URL was added or not.
1090
// Server lock is held on entry
1091
func (s *Server) addLeafNodeURL(urlStr string) bool {
7,170✔
1092
        if s.leafURLsMap.addUrl(urlStr) {
14,335✔
1093
                s.generateLeafNodeInfoJSON()
7,165✔
1094
                return true
7,165✔
1095
        }
7,165✔
1096
        return false
5✔
1097
}
1098

1099
// Removes a LeafNode URL of the route that is disconnecting from the Info structure.
1100
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
1101
// Returns a boolean indicating if the URL was removed or not.
1102
// Server lock is held on entry.
1103
func (s *Server) removeLeafNodeURL(urlStr string) bool {
7,170✔
1104
        // Don't need to do this if we are removing the route connection because
7,170✔
1105
        // we are shuting down...
7,170✔
1106
        if s.isShuttingDown() {
10,916✔
1107
                return false
3,746✔
1108
        }
3,746✔
1109
        if s.leafURLsMap.removeUrl(urlStr) {
6,844✔
1110
                s.generateLeafNodeInfoJSON()
3,420✔
1111
                return true
3,420✔
1112
        }
3,420✔
1113
        return false
4✔
1114
}
1115

1116
// Server lock is held on entry
1117
func (s *Server) generateLeafNodeInfoJSON() {
14,201✔
1118
        s.leafNodeInfo.Cluster = s.cachedClusterName()
14,201✔
1119
        s.leafNodeInfo.LeafNodeURLs = s.leafURLsMap.getAsStringSlice()
14,201✔
1120
        s.leafNodeInfo.WSConnectURLs = s.websocket.connectURLsMap.getAsStringSlice()
14,201✔
1121
        s.leafNodeInfoJSON = generateInfoJSON(&s.leafNodeInfo)
14,201✔
1122
}
14,201✔
1123

1124
// Sends an async INFO protocol so that the connected servers can update
1125
// their list of LeafNode urls.
1126
func (s *Server) sendAsyncLeafNodeInfo() {
10,585✔
1127
        for _, c := range s.leafs {
10,695✔
1128
                c.mu.Lock()
110✔
1129
                c.enqueueProto(s.leafNodeInfoJSON)
110✔
1130
                c.mu.Unlock()
110✔
1131
        }
110✔
1132
}
1133

1134
// Called when an inbound leafnode connection is accepted or we create one for a solicited leafnode.
1135
func (s *Server) createLeafNode(conn net.Conn, rURL *url.URL, remote *leafNodeCfg, ws *websocket) *client {
1,689✔
1136
        // Snapshot server options.
1,689✔
1137
        opts := s.getOpts()
1,689✔
1138

1,689✔
1139
        maxPay := int32(opts.MaxPayload)
1,689✔
1140
        maxSubs := int32(opts.MaxSubs)
1,689✔
1141
        // For system, maxSubs of 0 means unlimited, so re-adjust here.
1,689✔
1142
        if maxSubs == 0 {
3,377✔
1143
                maxSubs = -1
1,688✔
1144
        }
1,688✔
1145
        now := time.Now().UTC()
1,689✔
1146

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

1,689✔
1151
        // If the leafnode subject interest should be isolated, flag it here.
1,689✔
1152
        s.optsMu.RLock()
1,689✔
1153
        if c.leaf.isolated = s.opts.LeafNode.IsolateLeafnodeInterest; !c.leaf.isolated && remote != nil {
2,498✔
1154
                c.leaf.isolated = remote.LocalIsolation
809✔
1155
        }
809✔
1156
        s.optsMu.RUnlock()
1,689✔
1157

1,689✔
1158
        // For accepted LN connections, ws will be != nil if it was accepted
1,689✔
1159
        // through the Websocket port.
1,689✔
1160
        c.ws = ws
1,689✔
1161

1,689✔
1162
        // For remote, check if the scheme starts with "ws", if so, we will initiate
1,689✔
1163
        // a remote Leaf Node connection as a websocket connection.
1,689✔
1164
        if remote != nil && rURL != nil && isWSURL(rURL) {
1,739✔
1165
                remote.RLock()
50✔
1166
                c.ws = &websocket{compress: remote.Websocket.Compression, maskwrite: !remote.Websocket.NoMasking}
50✔
1167
                remote.RUnlock()
50✔
1168
        }
50✔
1169

1170
        // Determines if we are soliciting the connection or not.
1171
        var solicited bool
1,689✔
1172
        var acc *Account
1,689✔
1173
        var remoteSuffix string
1,689✔
1174
        if remote != nil {
2,500✔
1175
                // For now, if lookup fails, we will constantly try
811✔
1176
                // to recreate this LN connection.
811✔
1177
                lacc := remote.LocalAccount
811✔
1178
                var err error
811✔
1179
                acc, err = s.LookupAccount(lacc)
811✔
1180
                if err != nil {
813✔
1181
                        // An account not existing is something that can happen with nats/http account resolver and the account
2✔
1182
                        // has not yet been pushed, or the request failed for other reasons.
2✔
1183
                        // remote needs to be set or retry won't happen
2✔
1184
                        c.leaf.remote = remote
2✔
1185
                        c.closeConnection(MissingAccount)
2✔
1186
                        s.Errorf("Unable to lookup account %s for solicited leafnode connection: %v", lacc, err)
2✔
1187
                        return nil
2✔
1188
                }
2✔
1189
                remoteSuffix = fmt.Sprintf(" for account: %s", acc.traceLabel())
809✔
1190
        }
1191

1192
        c.mu.Lock()
1,687✔
1193
        c.initClient()
1,687✔
1194
        c.Noticef("Leafnode connection created%s %s", remoteSuffix, c.opts.Name)
1,687✔
1195

1,687✔
1196
        var (
1,687✔
1197
                tlsFirst         bool
1,687✔
1198
                tlsFirstFallback time.Duration
1,687✔
1199
                infoTimeout      time.Duration
1,687✔
1200
        )
1,687✔
1201
        if remote != nil {
2,496✔
1202
                solicited = true
809✔
1203
                remote.Lock()
809✔
1204
                c.leaf.remote = remote
809✔
1205
                c.setPermissions(remote.perms)
809✔
1206
                if !c.leaf.remote.Hub {
1,602✔
1207
                        c.leaf.isSpoke = true
793✔
1208
                }
793✔
1209
                tlsFirst = remote.TLSHandshakeFirst
809✔
1210
                infoTimeout = remote.FirstInfoTimeout
809✔
1211
                remote.Unlock()
809✔
1212
                c.acc = acc
809✔
1213
        } else {
878✔
1214
                c.flags.set(expectConnect)
878✔
1215
                if ws != nil {
907✔
1216
                        c.Debugf("Leafnode compression=%v", c.ws.compress)
29✔
1217
                }
29✔
1218
                tlsFirst = opts.LeafNode.TLSHandshakeFirst
878✔
1219
                if f := opts.LeafNode.TLSHandshakeFirstFallback; f > 0 {
879✔
1220
                        tlsFirstFallback = f
1✔
1221
                }
1✔
1222
        }
1223
        c.mu.Unlock()
1,687✔
1224

1,687✔
1225
        var nonce [nonceLen]byte
1,687✔
1226
        var info *Info
1,687✔
1227

1,687✔
1228
        // Grab this before the client lock below.
1,687✔
1229
        if !solicited {
2,565✔
1230
                // Grab server variables
878✔
1231
                s.mu.Lock()
878✔
1232
                info = s.copyLeafNodeInfo()
878✔
1233
                // For tests that want to simulate old servers, do not set the compression
878✔
1234
                // on the INFO protocol if configured with CompressionNotSupported.
878✔
1235
                if cm := opts.LeafNode.Compression.Mode; cm != CompressionNotSupported {
1,755✔
1236
                        info.Compression = cm
877✔
1237
                }
877✔
1238
                // We always send a nonce for LEAF connections. Do not change that without
1239
                // taking into account presence of proxy trusted keys.
1240
                s.generateNonce(nonce[:])
878✔
1241
                s.mu.Unlock()
878✔
1242
        }
1243

1244
        // Grab lock
1245
        c.mu.Lock()
1,687✔
1246

1,687✔
1247
        var preBuf []byte
1,687✔
1248
        if solicited {
2,496✔
1249
                // For websocket connection, we need to send an HTTP request,
809✔
1250
                // and get the response before starting the readLoop to get
809✔
1251
                // the INFO, etc..
809✔
1252
                if c.isWebsocket() {
859✔
1253
                        var err error
50✔
1254
                        var closeReason ClosedState
50✔
1255

50✔
1256
                        preBuf, closeReason, err = c.leafNodeSolicitWSConnection(opts, rURL, remote)
50✔
1257
                        if err != nil {
71✔
1258
                                c.Errorf("Error soliciting websocket connection: %v", err)
21✔
1259
                                c.mu.Unlock()
21✔
1260
                                if closeReason != 0 {
38✔
1261
                                        c.closeConnection(closeReason)
17✔
1262
                                }
17✔
1263
                                return nil
21✔
1264
                        }
1265
                } else {
759✔
1266
                        // If configured to do TLS handshake first
759✔
1267
                        if tlsFirst {
763✔
1268
                                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
5✔
1269
                                        c.mu.Unlock()
1✔
1270
                                        return nil
1✔
1271
                                }
1✔
1272
                        }
1273
                        // We need to wait for the info, but not for too long.
1274
                        c.nc.SetReadDeadline(time.Now().Add(infoTimeout))
758✔
1275
                }
1276

1277
                // We will process the INFO from the readloop and finish by
1278
                // sending the CONNECT and finish registration later.
1279
        } else {
878✔
1280
                // Send our info to the other side.
878✔
1281
                // Remember the nonce we sent here for signatures, etc.
878✔
1282
                c.nonce = make([]byte, nonceLen)
878✔
1283
                copy(c.nonce, nonce[:])
878✔
1284
                info.Nonce = bytesToString(c.nonce)
878✔
1285
                info.CID = c.cid
878✔
1286
                proto := generateInfoJSON(info)
878✔
1287

878✔
1288
                var pre []byte
878✔
1289
                // We need first to check for "TLS First" fallback delay.
878✔
1290
                if tlsFirstFallback > 0 {
879✔
1291
                        // We wait and see if we are getting any data. Since we did not send
1✔
1292
                        // the INFO protocol yet, only clients that use TLS first should be
1✔
1293
                        // sending data (the TLS handshake). We don't really check the content:
1✔
1294
                        // if it is a rogue agent and not an actual client performing the
1✔
1295
                        // TLS handshake, the error will be detected when performing the
1✔
1296
                        // handshake on our side.
1✔
1297
                        pre = make([]byte, 4)
1✔
1298
                        c.nc.SetReadDeadline(time.Now().Add(tlsFirstFallback))
1✔
1299
                        n, _ := io.ReadFull(c.nc, pre[:])
1✔
1300
                        c.nc.SetReadDeadline(time.Time{})
1✔
1301
                        // If we get any data (regardless of possible timeout), we will proceed
1✔
1302
                        // with the TLS handshake.
1✔
1303
                        if n > 0 {
1✔
1304
                                pre = pre[:n]
×
1305
                        } else {
1✔
1306
                                // We did not get anything so we will send the INFO protocol.
1✔
1307
                                pre = nil
1✔
1308
                                // Set the boolean to false for the rest of the function.
1✔
1309
                                tlsFirst = false
1✔
1310
                        }
1✔
1311
                }
1312

1313
                if !tlsFirst {
1,751✔
1314
                        // We have to send from this go routine because we may
873✔
1315
                        // have to block for TLS handshake before we start our
873✔
1316
                        // writeLoop go routine. The other side needs to receive
873✔
1317
                        // this before it can initiate the TLS handshake..
873✔
1318
                        c.sendProtoNow(proto)
873✔
1319

873✔
1320
                        // The above call could have marked the connection as closed (due to TCP error).
873✔
1321
                        if c.isClosed() {
873✔
1322
                                c.mu.Unlock()
×
1323
                                c.closeConnection(WriteError)
×
1324
                                return nil
×
1325
                        }
×
1326
                }
1327

1328
                // Check to see if we need to spin up TLS.
1329
                if !c.isWebsocket() && info.TLSRequired {
960✔
1330
                        // If we have a prebuffer create a multi-reader.
82✔
1331
                        if len(pre) > 0 {
82✔
1332
                                c.nc = &tlsMixConn{c.nc, bytes.NewBuffer(pre)}
×
1333
                        }
×
1334
                        // Perform server-side TLS handshake.
1335
                        if err := c.doTLSServerHandshake(tlsHandshakeLeaf, opts.LeafNode.TLSConfig, opts.LeafNode.TLSTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
137✔
1336
                                c.mu.Unlock()
55✔
1337
                                return nil
55✔
1338
                        }
55✔
1339
                }
1340

1341
                // If the user wants the TLS handshake to occur first, now that it is
1342
                // done, send the INFO protocol.
1343
                if tlsFirst {
826✔
1344
                        c.flags.set(didTLSFirst)
3✔
1345
                        c.sendProtoNow(proto)
3✔
1346
                        if c.isClosed() {
3✔
1347
                                c.mu.Unlock()
×
1348
                                c.closeConnection(WriteError)
×
1349
                                return nil
×
1350
                        }
×
1351
                }
1352

1353
                // Leaf nodes will always require a CONNECT to let us know
1354
                // when we are properly bound to an account.
1355
                //
1356
                // If compression is configured, we can't set the authTimer here because
1357
                // it would cause the parser to fail any incoming protocol that is not a
1358
                // CONNECT (and we need to exchange INFO protocols for compression
1359
                // negotiation). So instead, use the ping timer until we are done with
1360
                // negotiation and can set the auth timer.
1361
                timeout := secondsToDuration(opts.LeafNode.AuthTimeout)
823✔
1362
                if needsCompression(opts.LeafNode.Compression.Mode) {
1,430✔
1363
                        c.ping.tmr = time.AfterFunc(timeout, func() {
615✔
1364
                                c.authTimeout()
8✔
1365
                        })
8✔
1366
                } else {
216✔
1367
                        c.setAuthTimer(timeout)
216✔
1368
                }
216✔
1369
        }
1370

1371
        // Keep track in case server is shutdown before we can successfully register.
1372
        if !s.addToTempClients(c.cid, c) {
1,611✔
1373
                c.mu.Unlock()
1✔
1374
                c.setNoReconnect()
1✔
1375
                c.closeConnection(ServerShutdown)
1✔
1376
                return nil
1✔
1377
        }
1✔
1378

1379
        // Spin up the read loop.
1380
        s.startGoRoutine(func() { c.readLoop(preBuf) })
3,218✔
1381

1382
        // We will spin the write loop for solicited connections only
1383
        // when processing the INFO and after switching to TLS if needed.
1384
        if !solicited {
2,432✔
1385
                s.startGoRoutine(func() { c.writeLoop() })
1,646✔
1386
        }
1387

1388
        c.mu.Unlock()
1,609✔
1389

1,609✔
1390
        return c
1,609✔
1391
}
1392

1393
// Will perform the client-side TLS handshake if needed. Assumes that this
1394
// is called by the solicit side (remote will be non nil). Returns `true`
1395
// if TLS is required, `false` otherwise.
1396
// Lock held on entry.
1397
func (c *client) leafClientHandshakeIfNeeded(remote *leafNodeCfg, opts *Options) (bool, error) {
1,954✔
1398
        // Check if TLS is required and gather TLS config variables.
1,954✔
1399
        tlsRequired, tlsConfig, tlsName, tlsTimeout := c.leafNodeGetTLSConfigForSolicit(remote)
1,954✔
1400
        if !tlsRequired {
3,824✔
1401
                return false, nil
1,870✔
1402
        }
1,870✔
1403

1404
        // If TLS required, peform handshake.
1405
        // Get the URL that was used to connect to the remote server.
1406
        rURL := remote.getCurrentURL()
84✔
1407

84✔
1408
        // Perform the client-side TLS handshake.
84✔
1409
        if resetTLSName, err := c.doTLSClientHandshake(tlsHandshakeLeaf, rURL, tlsConfig, tlsName, tlsTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
127✔
1410
                // Check if we need to reset the remote's TLS name.
43✔
1411
                if resetTLSName {
43✔
1412
                        remote.Lock()
×
1413
                        remote.tlsName = _EMPTY_
×
1414
                        remote.Unlock()
×
1415
                }
×
1416
                return false, err
43✔
1417
        }
1418
        return true, nil
41✔
1419
}
1420

1421
func (c *client) processLeafnodeInfo(info *Info) {
2,707✔
1422
        c.mu.Lock()
2,707✔
1423
        if c.leaf == nil || c.isClosed() {
2,707✔
1424
                c.mu.Unlock()
×
1425
                return
×
1426
        }
×
1427
        s := c.srv
2,707✔
1428
        opts := s.getOpts()
2,707✔
1429
        remote := c.leaf.remote
2,707✔
1430
        didSolicit := remote != nil
2,707✔
1431
        firstINFO := !c.flags.isSet(infoReceived)
2,707✔
1432

2,707✔
1433
        // In case of websocket, the TLS handshake has been already done.
2,707✔
1434
        // So check only for non websocket connections and for configurations
2,707✔
1435
        // where the TLS Handshake was not done first.
2,707✔
1436
        if didSolicit && !c.flags.isSet(handshakeComplete) && !c.isWebsocket() && !remote.TLSHandshakeFirst {
4,607✔
1437
                // If the server requires TLS, we need to set this in the remote
1,900✔
1438
                // otherwise if there is no TLS configuration block for the remote,
1,900✔
1439
                // the solicit side will not attempt to perform the TLS handshake.
1,900✔
1440
                if firstINFO && info.TLSRequired {
1,968✔
1441
                        // Check for TLS/proxy configuration mismatch
68✔
1442
                        if remote.Proxy.URL != _EMPTY_ && !remote.TLS && remote.TLSConfig == nil {
68✔
1443
                                c.mu.Unlock()
×
1444
                                c.Errorf("TLS configuration mismatch: Hub requires TLS but leafnode remote is not configured for TLS. When using a proxy, ensure TLS leafnode configuration matches the Hub requirements.")
×
1445
                                c.closeConnection(TLSHandshakeError)
×
1446
                                return
×
1447
                        }
×
1448
                        remote.TLS = true
68✔
1449
                }
1450
                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
1,938✔
1451
                        c.mu.Unlock()
38✔
1452
                        return
38✔
1453
                }
38✔
1454
        }
1455

1456
        // Check for compression, unless already done.
1457
        if firstINFO && !c.flags.isSet(compressionNegotiated) {
3,987✔
1458
                // Prevent from getting back here.
1,318✔
1459
                c.flags.set(compressionNegotiated)
1,318✔
1460

1,318✔
1461
                var co *CompressionOpts
1,318✔
1462
                if !didSolicit {
1,899✔
1463
                        co = &opts.LeafNode.Compression
581✔
1464
                } else {
1,318✔
1465
                        co = &remote.Compression
737✔
1466
                }
737✔
1467
                if needsCompression(co.Mode) {
2,625✔
1468
                        // Release client lock since following function will need server lock.
1,307✔
1469
                        c.mu.Unlock()
1,307✔
1470
                        compress, err := s.negotiateLeafCompression(c, didSolicit, info.Compression, co)
1,307✔
1471
                        if err != nil {
1,307✔
1472
                                c.sendErrAndErr(err.Error())
×
1473
                                c.closeConnection(ProtocolViolation)
×
1474
                                return
×
1475
                        }
×
1476
                        if compress {
2,486✔
1477
                                // Done for now, will get back another INFO protocol...
1,179✔
1478
                                return
1,179✔
1479
                        }
1,179✔
1480
                        // No compression because one side does not want/can't, so proceed.
1481
                        c.mu.Lock()
128✔
1482
                        // Check that the connection did not close if the lock was released.
128✔
1483
                        if c.isClosed() {
128✔
1484
                                c.mu.Unlock()
×
1485
                                return
×
1486
                        }
×
1487
                } else {
11✔
1488
                        // Coming from an old server, the Compression field would be the empty
11✔
1489
                        // string. For servers that are configured with CompressionNotSupported,
11✔
1490
                        // this makes them behave as old servers.
11✔
1491
                        if info.Compression == _EMPTY_ || co.Mode == CompressionNotSupported {
14✔
1492
                                c.leaf.compression = CompressionNotSupported
3✔
1493
                        } else {
11✔
1494
                                c.leaf.compression = CompressionOff
8✔
1495
                        }
8✔
1496
                }
1497
                // Accepting side does not normally process an INFO protocol during
1498
                // initial connection handshake. So we keep it consistent by returning
1499
                // if we are not soliciting.
1500
                if !didSolicit {
140✔
1501
                        // If we had created the ping timer instead of the auth timer, we will
1✔
1502
                        // clear the ping timer and set the auth timer now that the compression
1✔
1503
                        // negotiation is done.
1✔
1504
                        if info.Compression != _EMPTY_ && c.ping.tmr != nil {
1✔
1505
                                clearTimer(&c.ping.tmr)
×
1506
                                c.setAuthTimer(secondsToDuration(opts.LeafNode.AuthTimeout))
×
1507
                        }
×
1508
                        c.mu.Unlock()
1✔
1509
                        return
1✔
1510
                }
1511
                // Fall through and process the INFO protocol as usual.
1512
        }
1513

1514
        // Note: For now, only the initial INFO has a nonce. We
1515
        // will probably do auto key rotation at some point.
1516
        if firstINFO {
2,268✔
1517
                // Mark that the INFO protocol has been received.
779✔
1518
                c.flags.set(infoReceived)
779✔
1519
                // Prevent connecting to non leafnode port. Need to do this only for
779✔
1520
                // the first INFO, not for async INFO updates...
779✔
1521
                //
779✔
1522
                // Content of INFO sent by the server when accepting a tcp connection.
779✔
1523
                // -------------------------------------------------------------------
779✔
1524
                // Listen Port Of | CID | ClientConnectURLs | LeafNodeURLs | Gateway |
779✔
1525
                // -------------------------------------------------------------------
779✔
1526
                //      CLIENT    |  X* |        X**        |              |         |
779✔
1527
                //      ROUTE     |     |        X**        |      X***    |         |
779✔
1528
                //     GATEWAY    |     |                   |              |    X    |
779✔
1529
                //     LEAFNODE   |  X  |                   |       X      |         |
779✔
1530
                // -------------------------------------------------------------------
779✔
1531
                // *   Not on older servers.
779✔
1532
                // **  Not if "no advertise" is enabled.
779✔
1533
                // *** Not if leafnode's "no advertise" is enabled.
779✔
1534
                //
779✔
1535
                // As seen from above, a solicited LeafNode connection should receive
779✔
1536
                // from the remote server an INFO with CID and LeafNodeURLs. Anything
779✔
1537
                // else should be considered an attempt to connect to a wrong port.
779✔
1538
                if didSolicit && (info.CID == 0 || info.LeafNodeURLs == nil) {
831✔
1539
                        c.mu.Unlock()
52✔
1540
                        c.Errorf(ErrConnectedToWrongPort.Error())
52✔
1541
                        c.closeConnection(WrongPort)
52✔
1542
                        return
52✔
1543
                }
52✔
1544
                // Reject a cluster that contains spaces.
1545
                if info.Cluster != _EMPTY_ && strings.Contains(info.Cluster, " ") {
728✔
1546
                        c.mu.Unlock()
1✔
1547
                        c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
1548
                        c.closeConnection(ProtocolViolation)
1✔
1549
                        return
1✔
1550
                }
1✔
1551
                // Capture a nonce here.
1552
                c.nonce = []byte(info.Nonce)
726✔
1553
                if info.TLSRequired && didSolicit {
756✔
1554
                        remote.TLS = true
30✔
1555
                }
30✔
1556
                supportsHeaders := c.srv.supportsHeaders()
726✔
1557
                c.headers = supportsHeaders && info.Headers
726✔
1558

726✔
1559
                // Remember the remote server.
726✔
1560
                // Pre 2.2.0 servers are not sending their server name.
726✔
1561
                // In that case, use info.ID, which, for those servers, matches
726✔
1562
                // the content of the field `Name` in the leafnode CONNECT protocol.
726✔
1563
                if info.Name == _EMPTY_ {
726✔
1564
                        c.leaf.remoteServer = info.ID
×
1565
                } else {
726✔
1566
                        c.leaf.remoteServer = info.Name
726✔
1567
                }
726✔
1568
                c.leaf.remoteDomain = info.Domain
726✔
1569
                c.leaf.remoteCluster = info.Cluster
726✔
1570
                // We send the protocol version in the INFO protocol.
726✔
1571
                // Keep track of it, so we know if this connection supports message
726✔
1572
                // tracing for instance.
726✔
1573
                c.opts.Protocol = info.Proto
726✔
1574
        }
1575

1576
        // For both initial INFO and async INFO protocols, Possibly
1577
        // update our list of remote leafnode URLs we can connect to.
1578
        if didSolicit && (len(info.LeafNodeURLs) > 0 || len(info.WSConnectURLs) > 0) {
2,777✔
1579
                // Consider the incoming array as the most up-to-date
1,341✔
1580
                // representation of the remote cluster's list of URLs.
1,341✔
1581
                c.updateLeafNodeURLs(info)
1,341✔
1582
        }
1,341✔
1583

1584
        // Check to see if we have permissions updates here.
1585
        if info.Import != nil || info.Export != nil {
1,451✔
1586
                perms := &Permissions{
15✔
1587
                        Publish:   info.Export,
15✔
1588
                        Subscribe: info.Import,
15✔
1589
                }
15✔
1590
                // Check if we have local deny clauses that we need to merge.
15✔
1591
                if remote := c.leaf.remote; remote != nil {
30✔
1592
                        if len(remote.DenyExports) > 0 {
16✔
1593
                                if perms.Publish == nil {
1✔
1594
                                        perms.Publish = &SubjectPermission{}
×
1595
                                }
×
1596
                                perms.Publish.Deny = append(perms.Publish.Deny, remote.DenyExports...)
1✔
1597
                        }
1598
                        if len(remote.DenyImports) > 0 {
16✔
1599
                                if perms.Subscribe == nil {
1✔
1600
                                        perms.Subscribe = &SubjectPermission{}
×
1601
                                }
×
1602
                                perms.Subscribe.Deny = append(perms.Subscribe.Deny, remote.DenyImports...)
1✔
1603
                        }
1604
                }
1605
                c.setPermissions(perms)
15✔
1606
        }
1607

1608
        var resumeConnect bool
1,436✔
1609

1,436✔
1610
        // If this is a remote connection and this is the first INFO protocol,
1,436✔
1611
        // then we need to finish the connect process by sending CONNECT, etc..
1,436✔
1612
        if firstINFO && didSolicit {
2,118✔
1613
                // Clear deadline that was set in createLeafNode while waiting for the INFO.
682✔
1614
                c.nc.SetDeadline(time.Time{})
682✔
1615
                resumeConnect = true
682✔
1616
        } else if !firstINFO && didSolicit {
2,095✔
1617
                c.leaf.remoteAccName = info.RemoteAccount
659✔
1618
        }
659✔
1619

1620
        // Check if we have the remote account information and if so make sure it's stored.
1621
        if info.RemoteAccount != _EMPTY_ {
2,082✔
1622
                s.leafRemoteAccounts.Store(c.acc.Name, info.RemoteAccount)
646✔
1623
        }
646✔
1624
        c.mu.Unlock()
1,436✔
1625

1,436✔
1626
        finishConnect := info.ConnectInfo
1,436✔
1627
        if resumeConnect && s != nil {
2,118✔
1628
                s.leafNodeResumeConnectProcess(c)
682✔
1629
                if !info.InfoOnConnect {
682✔
1630
                        finishConnect = true
×
1631
                }
×
1632
        }
1633
        if finishConnect {
2,082✔
1634
                s.leafNodeFinishConnectProcess(c)
646✔
1635
        }
646✔
1636

1637
        // Check to see if we need to kick any internal source or mirror consumers.
1638
        // This will be a no-op if JetStream not enabled for this server or if the bound account
1639
        // does not have jetstream.
1640
        s.checkInternalSyncConsumers(c.acc)
1,436✔
1641
}
1642

1643
func (s *Server) negotiateLeafCompression(c *client, didSolicit bool, infoCompression string, co *CompressionOpts) (bool, error) {
1,307✔
1644
        // Negotiate the appropriate compression mode (or no compression)
1,307✔
1645
        cm, err := selectCompressionMode(co.Mode, infoCompression)
1,307✔
1646
        if err != nil {
1,307✔
1647
                return false, err
×
1648
        }
×
1649
        c.mu.Lock()
1,307✔
1650
        // For "auto" mode, set the initial compression mode based on RTT
1,307✔
1651
        if cm == CompressionS2Auto {
2,447✔
1652
                if c.rttStart.IsZero() {
2,280✔
1653
                        c.rtt = computeRTT(c.start)
1,140✔
1654
                }
1,140✔
1655
                cm = selectS2AutoModeBasedOnRTT(c.rtt, co.RTTThresholds)
1,140✔
1656
        }
1657
        // Keep track of the negotiated compression mode.
1658
        c.leaf.compression = cm
1,307✔
1659
        cid := c.cid
1,307✔
1660
        var nonce string
1,307✔
1661
        if !didSolicit {
1,887✔
1662
                nonce = bytesToString(c.nonce)
580✔
1663
        }
580✔
1664
        c.mu.Unlock()
1,307✔
1665

1,307✔
1666
        if !needsCompression(cm) {
1,435✔
1667
                return false, nil
128✔
1668
        }
128✔
1669

1670
        // If we end-up doing compression...
1671

1672
        // Generate an INFO with the chosen compression mode.
1673
        s.mu.Lock()
1,179✔
1674
        info := s.copyLeafNodeInfo()
1,179✔
1675
        info.Compression, info.CID, info.Nonce = compressionModeForInfoProtocol(co, cm), cid, nonce
1,179✔
1676
        infoProto := generateInfoJSON(info)
1,179✔
1677
        s.mu.Unlock()
1,179✔
1678

1,179✔
1679
        // If we solicited, then send this INFO protocol BEFORE switching
1,179✔
1680
        // to compression writer. However, if we did not, we send it after.
1,179✔
1681
        c.mu.Lock()
1,179✔
1682
        if didSolicit {
1,778✔
1683
                c.enqueueProto(infoProto)
599✔
1684
                // Make sure it is completely flushed (the pending bytes goes to
599✔
1685
                // 0) before proceeding.
599✔
1686
                for c.out.pb > 0 && !c.isClosed() {
1,198✔
1687
                        c.flushOutbound()
599✔
1688
                }
599✔
1689
        }
1690
        // This is to notify the readLoop that it should switch to a
1691
        // (de)compression reader.
1692
        c.in.flags.set(switchToCompression)
1,179✔
1693
        // Create the compress writer before queueing the INFO protocol for
1,179✔
1694
        // a route that did not solicit. It will make sure that that proto
1,179✔
1695
        // is sent with compression on.
1,179✔
1696
        c.out.cw = s2.NewWriter(nil, s2WriterOptions(cm)...)
1,179✔
1697
        if !didSolicit {
1,759✔
1698
                c.enqueueProto(infoProto)
580✔
1699
        }
580✔
1700
        c.mu.Unlock()
1,179✔
1701
        return true, nil
1,179✔
1702
}
1703

1704
// When getting a leaf node INFO protocol, use the provided
1705
// array of urls to update the list of possible endpoints.
1706
func (c *client) updateLeafNodeURLs(info *Info) {
1,341✔
1707
        cfg := c.leaf.remote
1,341✔
1708
        cfg.Lock()
1,341✔
1709
        defer cfg.Unlock()
1,341✔
1710

1,341✔
1711
        // We have ensured that if a remote has a WS scheme, then all are.
1,341✔
1712
        // So check if first is WS, then add WS URLs, otherwise, add non WS ones.
1,341✔
1713
        if len(cfg.URLs) > 0 && isWSURL(cfg.URLs[0]) {
1,399✔
1714
                // It does not really matter if we use "ws://" or "wss://" here since
58✔
1715
                // we will have already marked that the remote should use TLS anyway.
58✔
1716
                // But use proper scheme for log statements, etc...
58✔
1717
                proto := wsSchemePrefix
58✔
1718
                if cfg.TLS {
58✔
1719
                        proto = wsSchemePrefixTLS
×
1720
                }
×
1721
                c.doUpdateLNURLs(cfg, proto, info.WSConnectURLs)
58✔
1722
                return
58✔
1723
        }
1724
        c.doUpdateLNURLs(cfg, "nats-leaf", info.LeafNodeURLs)
1,283✔
1725
}
1726

1727
func (c *client) doUpdateLNURLs(cfg *leafNodeCfg, scheme string, URLs []string) {
1,341✔
1728
        cfg.urls = make([]*url.URL, 0, 1+len(URLs))
1,341✔
1729
        // Add the ones we receive in the protocol
1,341✔
1730
        for _, surl := range URLs {
3,701✔
1731
                url, err := url.Parse(fmt.Sprintf("%s://%s", scheme, surl))
2,360✔
1732
                if err != nil {
2,360✔
1733
                        // As per below, the URLs we receive should not have contained URL info, so this should be safe to log.
×
1734
                        c.Errorf("Error parsing url %q: %v", surl, err)
×
1735
                        continue
×
1736
                }
1737
                // Do not add if it's the same as what we already have configured.
1738
                var dup bool
2,360✔
1739
                for _, u := range cfg.URLs {
5,962✔
1740
                        // URLs that we receive never have user info, but the
3,602✔
1741
                        // ones that were configured may have. Simply compare
3,602✔
1742
                        // host and port to decide if they are equal or not.
3,602✔
1743
                        if url.Host == u.Host && url.Port() == u.Port() {
5,286✔
1744
                                dup = true
1,684✔
1745
                                break
1,684✔
1746
                        }
1747
                }
1748
                if !dup {
3,036✔
1749
                        cfg.urls = append(cfg.urls, url)
676✔
1750
                        cfg.saveTLSHostname(url)
676✔
1751
                }
676✔
1752
        }
1753
        // Add the configured one
1754
        cfg.urls = append(cfg.urls, cfg.URLs...)
1,341✔
1755
}
1756

1757
// Similar to setInfoHostPortAndGenerateJSON, but for leafNodeInfo.
1758
func (s *Server) setLeafNodeInfoHostPortAndIP() error {
3,616✔
1759
        opts := s.getOpts()
3,616✔
1760
        if opts.LeafNode.Advertise != _EMPTY_ {
3,627✔
1761
                advHost, advPort, err := parseHostPort(opts.LeafNode.Advertise, opts.LeafNode.Port)
11✔
1762
                if err != nil {
11✔
1763
                        return err
×
1764
                }
×
1765
                s.leafNodeInfo.Host = advHost
11✔
1766
                s.leafNodeInfo.Port = advPort
11✔
1767
        } else {
3,605✔
1768
                s.leafNodeInfo.Host = opts.LeafNode.Host
3,605✔
1769
                s.leafNodeInfo.Port = opts.LeafNode.Port
3,605✔
1770
                // If the host is "0.0.0.0" or "::" we need to resolve to a public IP.
3,605✔
1771
                // This will return at most 1 IP.
3,605✔
1772
                hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(s.leafNodeInfo.Host, false)
3,605✔
1773
                if err != nil {
3,605✔
1774
                        return err
×
1775
                }
×
1776
                if hostIsIPAny {
3,911✔
1777
                        if len(ips) == 0 {
306✔
1778
                                s.Errorf("Could not find any non-local IP for leafnode's listen specification %q",
×
1779
                                        s.leafNodeInfo.Host)
×
1780
                        } else {
306✔
1781
                                // Take the first from the list...
306✔
1782
                                s.leafNodeInfo.Host = ips[0]
306✔
1783
                        }
306✔
1784
                }
1785
        }
1786
        // Use just host:port for the IP
1787
        s.leafNodeInfo.IP = net.JoinHostPort(s.leafNodeInfo.Host, strconv.Itoa(s.leafNodeInfo.Port))
3,616✔
1788
        if opts.LeafNode.Advertise != _EMPTY_ {
3,627✔
1789
                s.Noticef("Advertise address for leafnode is set to %s", s.leafNodeInfo.IP)
11✔
1790
        }
11✔
1791
        return nil
3,616✔
1792
}
1793

1794
// Add the connection to the map of leaf nodes.
1795
// If `checkForDup` is true (invoked when a leafnode is accepted), then we check
1796
// if a connection already exists for the same server name and account.
1797
// That can happen when the remote is attempting to reconnect while the accepting
1798
// side did not detect the connection as broken yet.
1799
// But it can also happen when there is a misconfiguration and the remote is
1800
// creating two (or more) connections that bind to the same account on the accept
1801
// side.
1802
// When a duplicate is found, the new connection is accepted and the old is closed
1803
// (this solves the stale connection situation). An error is returned to help the
1804
// remote detect the misconfiguration when the duplicate is the result of that
1805
// misconfiguration.
1806
func (s *Server) addLeafNodeConnection(c *client, srvName, clusterName string, checkForDup bool) {
1,330✔
1807
        var accName string
1,330✔
1808
        c.mu.Lock()
1,330✔
1809
        cid := c.cid
1,330✔
1810
        acc := c.acc
1,330✔
1811
        if acc != nil {
2,660✔
1812
                accName = acc.Name
1,330✔
1813
        }
1,330✔
1814
        myRemoteDomain := c.leaf.remoteDomain
1,330✔
1815
        mySrvName := c.leaf.remoteServer
1,330✔
1816
        remoteAccName := c.leaf.remoteAccName
1,330✔
1817
        myClustName := c.leaf.remoteCluster
1,330✔
1818
        solicited := c.leaf.remote != nil
1,330✔
1819
        c.mu.Unlock()
1,330✔
1820

1,330✔
1821
        var old *client
1,330✔
1822
        s.mu.Lock()
1,330✔
1823
        // We check for empty because in some test we may send empty CONNECT{}
1,330✔
1824
        if checkForDup && srvName != _EMPTY_ {
1,977✔
1825
                for _, ol := range s.leafs {
1,024✔
1826
                        ol.mu.Lock()
377✔
1827
                        // We care here only about non solicited Leafnode. This function
377✔
1828
                        // is more about replacing stale connections than detecting loops.
377✔
1829
                        // We have code for the loop detection elsewhere, which also delays
377✔
1830
                        // attempt to reconnect.
377✔
1831
                        if !ol.isSolicitedLeafNode() && ol.leaf.remoteServer == srvName &&
377✔
1832
                                ol.leaf.remoteCluster == clusterName && ol.acc.Name == accName &&
377✔
1833
                                remoteAccName != _EMPTY_ && ol.leaf.remoteAccName == remoteAccName {
379✔
1834
                                old = ol
2✔
1835
                        }
2✔
1836
                        ol.mu.Unlock()
377✔
1837
                        if old != nil {
379✔
1838
                                break
2✔
1839
                        }
1840
                }
1841
        }
1842
        // Store new connection in the map
1843
        s.leafs[cid] = c
1,330✔
1844
        s.mu.Unlock()
1,330✔
1845
        s.removeFromTempClients(cid)
1,330✔
1846

1,330✔
1847
        // If applicable, evict the old one.
1,330✔
1848
        if old != nil {
1,332✔
1849
                old.sendErrAndErr(DuplicateRemoteLeafnodeConnection.String())
2✔
1850
                old.closeConnection(DuplicateRemoteLeafnodeConnection)
2✔
1851
                c.Warnf("Replacing connection from same server")
2✔
1852
        }
2✔
1853

1854
        srvDecorated := func() string {
1,535✔
1855
                if myClustName == _EMPTY_ {
227✔
1856
                        return mySrvName
22✔
1857
                }
22✔
1858
                return fmt.Sprintf("%s/%s", mySrvName, myClustName)
183✔
1859
        }
1860

1861
        opts := s.getOpts()
1,330✔
1862
        sysAcc := s.SystemAccount()
1,330✔
1863
        js := s.getJetStream()
1,330✔
1864
        var meta *raft
1,330✔
1865
        if js != nil {
1,861✔
1866
                if mg := js.getMetaGroup(); mg != nil {
949✔
1867
                        meta = mg.(*raft)
418✔
1868
                }
418✔
1869
        }
1870
        blockMappingOutgoing := false
1,330✔
1871
        // Deny (non domain) JetStream API traffic unless system account is shared
1,330✔
1872
        // and domain names are identical and extending is not disabled
1,330✔
1873

1,330✔
1874
        // Check if backwards compatibility has been enabled and needs to be acted on
1,330✔
1875
        forceSysAccDeny := false
1,330✔
1876
        if len(opts.JsAccDefaultDomain) > 0 {
1,367✔
1877
                if acc == sysAcc {
48✔
1878
                        for _, d := range opts.JsAccDefaultDomain {
22✔
1879
                                if d == _EMPTY_ {
19✔
1880
                                        // Extending JetStream via leaf node is mutually exclusive with a domain mapping to the empty/default domain.
8✔
1881
                                        // As soon as one mapping to "" is found, disable the ability to extend JS via a leaf node.
8✔
1882
                                        c.Noticef("Not extending remote JetStream domain %q due to presence of empty default domain", myRemoteDomain)
8✔
1883
                                        forceSysAccDeny = true
8✔
1884
                                        break
8✔
1885
                                }
1886
                        }
1887
                } else if domain, ok := opts.JsAccDefaultDomain[accName]; ok && domain == _EMPTY_ {
41✔
1888
                        // for backwards compatibility with old setups that do not have a domain name set
15✔
1889
                        c.Debugf("Skipping deny %q for account %q due to default domain", jsAllAPI, accName)
15✔
1890
                        return
15✔
1891
                }
15✔
1892
        }
1893

1894
        // If the server has JS disabled, it may still be part of a JetStream that could be extended.
1895
        // This is either signaled by js being disabled and a domain set,
1896
        // or in cases where no domain name exists, an extension hint is set.
1897
        // However, this is only relevant in mixed setups.
1898
        //
1899
        // If the system account connects but default domains are present, JetStream can't be extended.
1900
        if opts.JetStreamDomain != myRemoteDomain || (!opts.JetStream && (opts.JetStreamDomain == _EMPTY_ && opts.JetStreamExtHint != jsWillExtend)) ||
1,315✔
1901
                sysAcc == nil || acc == nil || forceSysAccDeny {
2,472✔
1902
                // If domain names mismatch always deny. This applies to system accounts as well as non system accounts.
1,157✔
1903
                // Not having a system account, account or JetStream disabled is considered a mismatch as well.
1,157✔
1904
                if acc != nil && acc == sysAcc {
1,290✔
1905
                        c.Noticef("System account connected from %s", srvDecorated())
133✔
1906
                        c.Noticef("JetStream not extended, domains differ")
133✔
1907
                        c.mergeDenyPermissionsLocked(both, denyAllJs)
133✔
1908
                        // When a remote with a system account is present in a server, unless otherwise disabled, the server will be
133✔
1909
                        // started in observer mode. Now that it is clear that this not used, turn the observer mode off.
133✔
1910
                        if solicited && meta != nil && meta.IsObserver() {
162✔
1911
                                meta.setObserver(false, extNotExtended)
29✔
1912
                                c.Debugf("Turning JetStream metadata controller Observer Mode off")
29✔
1913
                                // Take note that the domain was not extended to avoid this state from startup.
29✔
1914
                                writePeerState(js.config.StoreDir, meta.currentPeerState())
29✔
1915
                                // Meta controller can't be leader yet.
29✔
1916
                                // Yet it is possible that due to observer mode every server already stopped campaigning.
29✔
1917
                                // Therefore this server needs to be kicked into campaigning gear explicitly.
29✔
1918
                                meta.Campaign()
29✔
1919
                        }
29✔
1920
                } else {
1,024✔
1921
                        c.Noticef("JetStream using domains: local %q, remote %q", opts.JetStreamDomain, myRemoteDomain)
1,024✔
1922
                        c.mergeDenyPermissionsLocked(both, denyAllClientJs)
1,024✔
1923
                }
1,024✔
1924
                blockMappingOutgoing = true
1,157✔
1925
        } else if acc == sysAcc {
230✔
1926
                // system account and same domain
72✔
1927
                s.sys.client.Noticef("Extending JetStream domain %q as System Account connected from server %s",
72✔
1928
                        myRemoteDomain, srvDecorated())
72✔
1929
                // In an extension use case, pin leadership to server remotes connect to.
72✔
1930
                // Therefore, server with a remote that are not already in observer mode, need to be put into it.
72✔
1931
                if solicited && meta != nil && !meta.IsObserver() {
76✔
1932
                        meta.setObserver(true, extExtended)
4✔
1933
                        c.Debugf("Turning JetStream metadata controller Observer Mode on - System Account Connected")
4✔
1934
                        // Take note that the domain was not extended to avoid this state next startup.
4✔
1935
                        writePeerState(js.config.StoreDir, meta.currentPeerState())
4✔
1936
                        // If this server is the leader already, step down so a new leader can be elected (that is not an observer)
4✔
1937
                        meta.StepDown()
4✔
1938
                }
4✔
1939
        } else {
86✔
1940
                // This deny is needed in all cases (system account shared or not)
86✔
1941
                // If the system account is shared, jsAllAPI traffic will go through the system account.
86✔
1942
                // So in order to prevent duplicate delivery (from system and actual account) suppress it on the account.
86✔
1943
                // If the system account is NOT shared, jsAllAPI traffic has no business
86✔
1944
                c.Debugf("Adding deny %+v for account %q", denyAllClientJs, accName)
86✔
1945
                c.mergeDenyPermissionsLocked(both, denyAllClientJs)
86✔
1946
        }
86✔
1947
        // If we have a specified JetStream domain we will want to add a mapping to
1948
        // allow access cross domain for each non-system account.
1949
        if opts.JetStreamDomain != _EMPTY_ && opts.JetStream && acc != nil && acc != sysAcc {
1,562✔
1950
                for src, dest := range generateJSMappingTable(opts.JetStreamDomain) {
2,470✔
1951
                        if err := acc.AddMapping(src, dest); err != nil {
2,223✔
1952
                                c.Debugf("Error adding JetStream domain mapping: %s", err.Error())
×
1953
                        } else {
2,223✔
1954
                                c.Debugf("Adding JetStream Domain Mapping %q -> %s to account %q", src, dest, accName)
2,223✔
1955
                        }
2,223✔
1956
                }
1957
                if blockMappingOutgoing {
463✔
1958
                        src := fmt.Sprintf(jsDomainAPI, opts.JetStreamDomain)
216✔
1959
                        // make sure that messages intended for this domain, do not leave the cluster via this leaf node connection
216✔
1960
                        // This is a guard against a miss-config with two identical domain names and will only cover some forms
216✔
1961
                        // of this issue, not all of them.
216✔
1962
                        // This guards against a hub and a spoke having the same domain name.
216✔
1963
                        // But not two spokes having the same one and the request coming from the hub.
216✔
1964
                        c.mergeDenyPermissionsLocked(pub, []string{src})
216✔
1965
                        c.Debugf("Adding deny %q for outgoing messages to account %q", src, accName)
216✔
1966
                }
216✔
1967
        }
1968
}
1969

1970
func (s *Server) removeLeafNodeConnection(c *client) {
1,689✔
1971
        c.mu.Lock()
1,689✔
1972
        cid := c.cid
1,689✔
1973
        if c.leaf != nil {
3,378✔
1974
                if c.leaf.tsubt != nil {
2,897✔
1975
                        c.leaf.tsubt.Stop()
1,208✔
1976
                        c.leaf.tsubt = nil
1,208✔
1977
                }
1,208✔
1978
                if c.leaf.gwSub != nil {
2,333✔
1979
                        s.gwLeafSubs.Remove(c.leaf.gwSub)
644✔
1980
                        // We need to set this to nil for GC to release the connection
644✔
1981
                        c.leaf.gwSub = nil
644✔
1982
                }
644✔
1983
        }
1984
        proxyKey := c.proxyKey
1,689✔
1985
        c.mu.Unlock()
1,689✔
1986
        s.mu.Lock()
1,689✔
1987
        delete(s.leafs, cid)
1,689✔
1988
        if proxyKey != _EMPTY_ {
1,693✔
1989
                s.removeProxiedConn(proxyKey, cid)
4✔
1990
        }
4✔
1991
        s.mu.Unlock()
1,689✔
1992
        s.removeFromTempClients(cid)
1,689✔
1993
}
1994

1995
// Connect information for solicited leafnodes.
1996
type leafConnectInfo struct {
1997
        Version   string   `json:"version,omitempty"`
1998
        Nkey      string   `json:"nkey,omitempty"`
1999
        JWT       string   `json:"jwt,omitempty"`
2000
        Sig       string   `json:"sig,omitempty"`
2001
        User      string   `json:"user,omitempty"`
2002
        Pass      string   `json:"pass,omitempty"`
2003
        Token     string   `json:"auth_token,omitempty"`
2004
        ID        string   `json:"server_id,omitempty"`
2005
        Domain    string   `json:"domain,omitempty"`
2006
        Name      string   `json:"name,omitempty"`
2007
        Hub       bool     `json:"is_hub,omitempty"`
2008
        Cluster   string   `json:"cluster,omitempty"`
2009
        Headers   bool     `json:"headers,omitempty"`
2010
        JetStream bool     `json:"jetstream,omitempty"`
2011
        DenyPub   []string `json:"deny_pub,omitempty"`
2012
        Isolate   bool     `json:"isolate,omitempty"`
2013

2014
        // There was an existing field called:
2015
        // >> Comp bool `json:"compression,omitempty"`
2016
        // that has never been used. With support for compression, we now need
2017
        // a field that is a string. So we use a different json tag:
2018
        Compression string `json:"compress_mode,omitempty"`
2019

2020
        // Just used to detect wrong connection attempts.
2021
        Gateway string `json:"gateway,omitempty"`
2022

2023
        // Tells the accept side which account the remote is binding to.
2024
        RemoteAccount string `json:"remote_account,omitempty"`
2025

2026
        // The accept side of a LEAF connection, unlike ROUTER and GATEWAY, receives
2027
        // only the CONNECT protocol, and no INFO. So we need to send the protocol
2028
        // version as part of the CONNECT. It will indicate if a connection supports
2029
        // some features, such as message tracing.
2030
        // We use `protocol` as the JSON tag, so this is automatically unmarshal'ed
2031
        // in the low level process CONNECT.
2032
        Proto int `json:"protocol,omitempty"`
2033
}
2034

2035
// processLeafNodeConnect will process the inbound connect args.
2036
// Once we are here we are bound to an account, so can send any interest that
2037
// we would have to the other side.
2038
func (c *client) processLeafNodeConnect(s *Server, arg []byte, lang string) error {
691✔
2039
        // Way to detect clients that incorrectly connect to the route listen
691✔
2040
        // port. Client provided "lang" in the CONNECT protocol while LEAFNODEs don't.
691✔
2041
        if lang != _EMPTY_ {
691✔
2042
                c.sendErrAndErr(ErrClientConnectedToLeafNodePort.Error())
×
2043
                c.closeConnection(WrongPort)
×
2044
                return ErrClientConnectedToLeafNodePort
×
2045
        }
×
2046

2047
        // Unmarshal as a leaf node connect protocol
2048
        proto := &leafConnectInfo{}
691✔
2049
        if err := json.Unmarshal(arg, proto); err != nil {
691✔
2050
                return err
×
2051
        }
×
2052

2053
        // Reject a cluster that contains spaces.
2054
        if proto.Cluster != _EMPTY_ && strings.Contains(proto.Cluster, " ") {
692✔
2055
                c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
2056
                c.closeConnection(ProtocolViolation)
1✔
2057
                return ErrClusterNameHasSpaces
1✔
2058
        }
1✔
2059

2060
        // Check for cluster name collisions.
2061
        if cn := s.cachedClusterName(); cn != _EMPTY_ && proto.Cluster != _EMPTY_ && proto.Cluster == cn {
693✔
2062
                c.sendErrAndErr(ErrLeafNodeHasSameClusterName.Error())
3✔
2063
                c.closeConnection(ClusterNamesIdentical)
3✔
2064
                return ErrLeafNodeHasSameClusterName
3✔
2065
        }
3✔
2066

2067
        // Reject if this has Gateway which means that it would be from a gateway
2068
        // connection that incorrectly connects to the leafnode port.
2069
        if proto.Gateway != _EMPTY_ {
687✔
2070
                errTxt := fmt.Sprintf("Rejecting connection from gateway %q on the leafnode port", proto.Gateway)
×
2071
                c.Errorf(errTxt)
×
2072
                c.sendErr(errTxt)
×
2073
                c.closeConnection(WrongGateway)
×
2074
                return ErrWrongGateway
×
2075
        }
×
2076

2077
        if mv := s.getOpts().LeafNode.MinVersion; mv != _EMPTY_ {
689✔
2078
                major, minor, update, _ := versionComponents(mv)
2✔
2079
                if !versionAtLeast(proto.Version, major, minor, update) {
3✔
2080
                        // We are going to send back an INFO because otherwise recent
1✔
2081
                        // versions of the remote server would simply break the connection
1✔
2082
                        // after 2 seconds if not receiving it. Instead, we want the
1✔
2083
                        // other side to just "stall" until we finish waiting for the holding
1✔
2084
                        // period and close the connection below.
1✔
2085
                        s.sendPermsAndAccountInfo(c)
1✔
2086
                        c.sendErrAndErr(fmt.Sprintf("connection rejected since minimum version required is %q", mv))
1✔
2087
                        select {
1✔
2088
                        case <-c.srv.quitCh:
1✔
2089
                        case <-time.After(leafNodeWaitBeforeClose):
×
2090
                        }
2091
                        c.closeConnection(MinimumVersionRequired)
1✔
2092
                        return ErrMinimumVersionRequired
1✔
2093
                }
2094
        }
2095

2096
        // Check if this server supports headers.
2097
        supportHeaders := c.srv.supportsHeaders()
686✔
2098

686✔
2099
        c.mu.Lock()
686✔
2100
        // Leaf Nodes do not do echo or verbose or pedantic.
686✔
2101
        c.opts.Verbose = false
686✔
2102
        c.opts.Echo = false
686✔
2103
        c.opts.Pedantic = false
686✔
2104
        // This inbound connection will be marked as supporting headers if this server
686✔
2105
        // support headers and the remote has sent in the CONNECT protocol that it does
686✔
2106
        // support headers too.
686✔
2107
        c.headers = supportHeaders && proto.Headers
686✔
2108
        // If the compression level is still not set, set it based on what has been
686✔
2109
        // given to us in the CONNECT protocol.
686✔
2110
        if c.leaf.compression == _EMPTY_ {
820✔
2111
                // But if proto.Compression is _EMPTY_, set it to CompressionNotSupported
134✔
2112
                if proto.Compression == _EMPTY_ {
173✔
2113
                        c.leaf.compression = CompressionNotSupported
39✔
2114
                } else {
134✔
2115
                        c.leaf.compression = proto.Compression
95✔
2116
                }
95✔
2117
        }
2118

2119
        // Remember the remote server.
2120
        c.leaf.remoteServer = proto.Name
686✔
2121
        // Remember the remote account name
686✔
2122
        c.leaf.remoteAccName = proto.RemoteAccount
686✔
2123
        // Remember if the leafnode requested isolation.
686✔
2124
        c.leaf.isolated = c.leaf.isolated || proto.Isolate
686✔
2125

686✔
2126
        // If the other side has declared itself a hub, so we will take on the spoke role.
686✔
2127
        if proto.Hub {
702✔
2128
                c.leaf.isSpoke = true
16✔
2129
        }
16✔
2130

2131
        // The soliciting side is part of a cluster.
2132
        if proto.Cluster != _EMPTY_ {
1,217✔
2133
                c.leaf.remoteCluster = proto.Cluster
531✔
2134
        }
531✔
2135

2136
        c.leaf.remoteDomain = proto.Domain
686✔
2137

686✔
2138
        // When a leaf solicits a connection to a hub, the perms that it will use on the soliciting leafnode's
686✔
2139
        // behalf are correct for them, but inside the hub need to be reversed since data is flowing in the opposite direction.
686✔
2140
        if !c.isSolicitedLeafNode() && c.perms != nil {
702✔
2141
                sp, pp := c.perms.sub, c.perms.pub
16✔
2142
                c.perms.sub, c.perms.pub = pp, sp
16✔
2143
                if c.opts.Import != nil {
31✔
2144
                        c.darray = c.opts.Import.Deny
15✔
2145
                } else {
16✔
2146
                        c.darray = nil
1✔
2147
                }
1✔
2148
        }
2149

2150
        // Set the Ping timer
2151
        c.setFirstPingTimer()
686✔
2152

686✔
2153
        // If we received pub deny permissions from the other end, merge with existing ones.
686✔
2154
        c.mergeDenyPermissions(pub, proto.DenyPub)
686✔
2155

686✔
2156
        acc := c.acc
686✔
2157
        c.mu.Unlock()
686✔
2158

686✔
2159
        // Register the cluster, even if empty, as long as we are acting as a hub.
686✔
2160
        if !proto.Hub {
1,356✔
2161
                acc.registerLeafNodeCluster(proto.Cluster)
670✔
2162
        }
670✔
2163

2164
        // Add in the leafnode here since we passed through auth at this point.
2165
        s.addLeafNodeConnection(c, proto.Name, proto.Cluster, true)
686✔
2166

686✔
2167
        // If we have permissions bound to this leafnode we need to send then back to the
686✔
2168
        // origin server for local enforcement.
686✔
2169
        s.sendPermsAndAccountInfo(c)
686✔
2170

686✔
2171
        // Create and initialize the smap since we know our bound account now.
686✔
2172
        // This will send all registered subs too.
686✔
2173
        s.initLeafNodeSmapAndSendSubs(c)
686✔
2174

686✔
2175
        // Announce the account connect event for a leaf node.
686✔
2176
        // This will be a no-op as needed.
686✔
2177
        s.sendLeafNodeConnect(c.acc)
686✔
2178

686✔
2179
        // Check to see if we need to kick any internal source or mirror consumers.
686✔
2180
        // This will be a no-op if JetStream not enabled for this server or if the bound account
686✔
2181
        // does not have jetstream.
686✔
2182
        s.checkInternalSyncConsumers(acc)
686✔
2183

686✔
2184
        return nil
686✔
2185
}
2186

2187
// checkInternalSyncConsumers
2188
func (s *Server) checkInternalSyncConsumers(acc *Account) {
2,122✔
2189
        // Grab our js
2,122✔
2190
        js := s.getJetStream()
2,122✔
2191

2,122✔
2192
        // Only applicable if we have JS and the leafnode has JS as well.
2,122✔
2193
        // We check for remote JS outside.
2,122✔
2194
        if !js.isEnabled() || acc == nil {
3,358✔
2195
                return
1,236✔
2196
        }
1,236✔
2197

2198
        // We will check all streams in our local account. They must be a leader and
2199
        // be sourcing or mirroring. We will check the external config on the stream itself
2200
        // if this is cross domain, or if the remote domain is empty, meaning we might be
2201
        // extending the system across this leafnode connection and hence we would be extending
2202
        // our own domain.
2203
        jsa := js.lookupAccount(acc)
886✔
2204
        if jsa == nil {
1,230✔
2205
                return
344✔
2206
        }
344✔
2207

2208
        var streams []*stream
542✔
2209
        jsa.mu.RLock()
542✔
2210
        for _, mset := range jsa.streams {
597✔
2211
                mset.cfgMu.RLock()
55✔
2212
                // We need to have a mirror or source defined.
55✔
2213
                // We do not want to force another lock here to look for leader status,
55✔
2214
                // so collect and after we release jsa will make sure.
55✔
2215
                if mset.cfg.Mirror != nil || len(mset.cfg.Sources) > 0 {
67✔
2216
                        streams = append(streams, mset)
12✔
2217
                }
12✔
2218
                mset.cfgMu.RUnlock()
55✔
2219
        }
2220
        jsa.mu.RUnlock()
542✔
2221

542✔
2222
        // Now loop through all candidates and check if we are the leader and have NOT
542✔
2223
        // created the sync up consumer.
542✔
2224
        for _, mset := range streams {
554✔
2225
                mset.retryDisconnectedSyncConsumers()
12✔
2226
        }
12✔
2227
}
2228

2229
// Returns the remote cluster name. This is set only once so does not require a lock.
2230
func (c *client) remoteCluster() string {
198,040✔
2231
        if c.leaf == nil {
198,040✔
2232
                return _EMPTY_
×
2233
        }
×
2234
        return c.leaf.remoteCluster
198,040✔
2235
}
2236

2237
// Sends back an info block to the soliciting leafnode to let it know about
2238
// its permission settings for local enforcement.
2239
func (s *Server) sendPermsAndAccountInfo(c *client) {
687✔
2240
        // Copy
687✔
2241
        s.mu.Lock()
687✔
2242
        info := s.copyLeafNodeInfo()
687✔
2243
        s.mu.Unlock()
687✔
2244
        c.mu.Lock()
687✔
2245
        info.CID = c.cid
687✔
2246
        info.Import = c.opts.Import
687✔
2247
        info.Export = c.opts.Export
687✔
2248
        info.RemoteAccount = c.acc.Name
687✔
2249
        // s.SystemAccount() uses an atomic operation and does not get the server lock, so this is safe.
687✔
2250
        info.IsSystemAccount = c.acc == s.SystemAccount()
687✔
2251
        info.ConnectInfo = true
687✔
2252
        c.enqueueProto(generateInfoJSON(info))
687✔
2253
        c.mu.Unlock()
687✔
2254
}
687✔
2255

2256
// Snapshot the current subscriptions from the sublist into our smap which
2257
// we will keep updated from now on.
2258
// Also send the registered subscriptions.
2259
func (s *Server) initLeafNodeSmapAndSendSubs(c *client) {
1,330✔
2260
        acc := c.acc
1,330✔
2261
        if acc == nil {
1,330✔
2262
                c.Debugf("Leafnode does not have an account bound")
×
2263
                return
×
2264
        }
×
2265
        // Collect all account subs here.
2266
        _subs := [1024]*subscription{}
1,330✔
2267
        subs := _subs[:0]
1,330✔
2268
        ims := []string{}
1,330✔
2269

1,330✔
2270
        // Hold the client lock otherwise there can be a race and miss some subs.
1,330✔
2271
        c.mu.Lock()
1,330✔
2272
        defer c.mu.Unlock()
1,330✔
2273

1,330✔
2274
        acc.mu.RLock()
1,330✔
2275
        accName := acc.Name
1,330✔
2276
        accNTag := acc.nameTag
1,330✔
2277

1,330✔
2278
        // To make printing look better when no friendly name present.
1,330✔
2279
        if accNTag != _EMPTY_ {
1,341✔
2280
                accNTag = "/" + accNTag
11✔
2281
        }
11✔
2282

2283
        // If we are solicited we only send interest for local clients.
2284
        if c.isSpokeLeafNode() {
1,974✔
2285
                acc.sl.localSubs(&subs, true)
644✔
2286
        } else {
1,330✔
2287
                acc.sl.All(&subs)
686✔
2288
        }
686✔
2289

2290
        // Check if we have an existing service import reply.
2291
        siReply := copyBytes(acc.siReply)
1,330✔
2292

1,330✔
2293
        // Since leaf nodes only send on interest, if the bound
1,330✔
2294
        // account has import services we need to send those over.
1,330✔
2295
        for isubj := range acc.imports.services {
6,308✔
2296
                if c.isSpokeLeafNode() && !c.canSubscribe(isubj) {
5,261✔
2297
                        c.Debugf("Not permitted to import service %q on behalf of %s%s", isubj, accName, accNTag)
283✔
2298
                        continue
283✔
2299
                }
2300
                ims = append(ims, isubj)
4,695✔
2301
        }
2302
        // Likewise for mappings.
2303
        for _, m := range acc.mappings {
3,673✔
2304
                if c.isSpokeLeafNode() && !c.canSubscribe(m.src) {
2,379✔
2305
                        c.Debugf("Not permitted to import mapping %q on behalf of %s%s", m.src, accName, accNTag)
36✔
2306
                        continue
36✔
2307
                }
2308
                ims = append(ims, m.src)
2,307✔
2309
        }
2310

2311
        // Create a unique subject that will be used for loop detection.
2312
        lds := acc.lds
1,330✔
2313
        acc.mu.RUnlock()
1,330✔
2314

1,330✔
2315
        // Check if we have to create the LDS.
1,330✔
2316
        if lds == _EMPTY_ {
2,367✔
2317
                lds = leafNodeLoopDetectionSubjectPrefix + nuid.Next()
1,037✔
2318
                acc.mu.Lock()
1,037✔
2319
                acc.lds = lds
1,037✔
2320
                acc.mu.Unlock()
1,037✔
2321
        }
1,037✔
2322

2323
        // Now check for gateway interest. Leafnodes will put this into
2324
        // the proper mode to propagate, but they are not held in the account.
2325
        gwsa := [16]*client{}
1,330✔
2326
        gws := gwsa[:0]
1,330✔
2327
        s.getOutboundGatewayConnections(&gws)
1,330✔
2328
        for _, cgw := range gws {
1,412✔
2329
                cgw.mu.Lock()
82✔
2330
                gw := cgw.gw
82✔
2331
                cgw.mu.Unlock()
82✔
2332
                if gw != nil {
164✔
2333
                        if ei, _ := gw.outsim.Load(accName); ei != nil {
164✔
2334
                                if e := ei.(*outsie); e != nil && e.sl != nil {
164✔
2335
                                        e.sl.All(&subs)
82✔
2336
                                }
82✔
2337
                        }
2338
                }
2339
        }
2340

2341
        applyGlobalRouting := s.gateway.enabled
1,330✔
2342
        if c.isSpokeLeafNode() {
1,974✔
2343
                // Add a fake subscription for this solicited leafnode connection
644✔
2344
                // so that we can send back directly for mapped GW replies.
644✔
2345
                // We need to keep track of this subscription so it can be removed
644✔
2346
                // when the connection is closed so that the GC can release it.
644✔
2347
                c.leaf.gwSub = &subscription{client: c, subject: []byte(gwReplyPrefix + ">")}
644✔
2348
                c.srv.gwLeafSubs.Insert(c.leaf.gwSub)
644✔
2349
        }
644✔
2350

2351
        // Now walk the results and add them to our smap
2352
        rc := c.leaf.remoteCluster
1,330✔
2353
        c.leaf.smap = make(map[string]int32)
1,330✔
2354
        for _, sub := range subs {
39,396✔
2355
                // Check perms regardless of role.
38,066✔
2356
                if c.perms != nil && !c.canSubscribe(string(sub.subject)) {
40,381✔
2357
                        c.Debugf("Not permitted to subscribe to %q on behalf of %s%s", sub.subject, accName, accNTag)
2,315✔
2358
                        continue
2,315✔
2359
                }
2360
                // Don't advertise interest from leafnodes to other isolated leafnodes.
2361
                if sub.client.kind == LEAF && c.isIsolatedLeafNode() {
35,766✔
2362
                        continue
15✔
2363
                }
2364
                // We ignore ourselves here.
2365
                // Also don't add the subscription if it has a origin cluster and the
2366
                // cluster name matches the one of the client we are sending to.
2367
                if c != sub.client && (sub.origin == nil || (bytesToString(sub.origin) != rc)) {
66,133✔
2368
                        count := int32(1)
30,397✔
2369
                        if len(sub.queue) > 0 && sub.qw > 0 {
30,407✔
2370
                                count = sub.qw
10✔
2371
                        }
10✔
2372
                        c.leaf.smap[keyFromSub(sub)] += count
30,397✔
2373
                        if c.leaf.tsub == nil {
31,651✔
2374
                                c.leaf.tsub = make(map[*subscription]struct{})
1,254✔
2375
                        }
1,254✔
2376
                        c.leaf.tsub[sub] = struct{}{}
30,397✔
2377
                }
2378
        }
2379
        // FIXME(dlc) - We need to update appropriately on an account claims update.
2380
        for _, isubj := range ims {
8,332✔
2381
                c.leaf.smap[isubj]++
7,002✔
2382
        }
7,002✔
2383
        // If we have gateways enabled we need to make sure the other side sends us responses
2384
        // that have been augmented from the original subscription.
2385
        // TODO(dlc) - Should we lock this down more?
2386
        if applyGlobalRouting {
1,433✔
2387
                c.leaf.smap[oldGWReplyPrefix+"*.>"]++
103✔
2388
                c.leaf.smap[gwReplyPrefix+">"]++
103✔
2389
        }
103✔
2390
        // Detect loops by subscribing to a specific subject and checking
2391
        // if this sub is coming back to us.
2392
        c.leaf.smap[lds]++
1,330✔
2393

1,330✔
2394
        // Check if we need to add an existing siReply to our map.
1,330✔
2395
        // This will be a prefix so add on the wildcard.
1,330✔
2396
        if siReply != nil {
1,352✔
2397
                wcsub := append(siReply, '>')
22✔
2398
                c.leaf.smap[string(wcsub)]++
22✔
2399
        }
22✔
2400
        // Queue all protocols. There is no max pending limit for LN connection,
2401
        // so we don't need chunking. The writes will happen from the writeLoop.
2402
        var b bytes.Buffer
1,330✔
2403
        for key, n := range c.leaf.smap {
27,919✔
2404
                c.writeLeafSub(&b, key, n)
26,589✔
2405
        }
26,589✔
2406
        if b.Len() > 0 {
2,660✔
2407
                c.enqueueProto(b.Bytes())
1,330✔
2408
        }
1,330✔
2409
        if c.leaf.tsub != nil {
2,585✔
2410
                // Clear the tsub map after 5 seconds.
1,255✔
2411
                c.leaf.tsubt = time.AfterFunc(5*time.Second, func() {
1,302✔
2412
                        c.mu.Lock()
47✔
2413
                        if c.leaf != nil {
94✔
2414
                                c.leaf.tsub = nil
47✔
2415
                                c.leaf.tsubt = nil
47✔
2416
                        }
47✔
2417
                        c.mu.Unlock()
47✔
2418
                })
2419
        }
2420
}
2421

2422
// updateInterestForAccountOnGateway called from gateway code when processing RS+ and RS-.
2423
func (s *Server) updateInterestForAccountOnGateway(accName string, sub *subscription, delta int32) {
198,404✔
2424
        acc, err := s.LookupAccount(accName)
198,404✔
2425
        if acc == nil || err != nil {
198,563✔
2426
                s.Debugf("No or bad account for %q, failed to update interest from gateway", accName)
159✔
2427
                return
159✔
2428
        }
159✔
2429
        acc.updateLeafNodes(sub, delta)
198,245✔
2430
}
2431

2432
// updateLeafNodesEx will make sure to update the account smap for the subscription.
2433
// Will also forward to all leaf nodes as needed.
2434
// If `hubOnly` is true, then will update only leaf nodes that connect to this server
2435
// (that is, for which this server acts as a hub to them).
2436
func (acc *Account) updateLeafNodesEx(sub *subscription, delta int32, hubOnly bool) {
2,501,339✔
2437
        if acc == nil || sub == nil {
2,501,339✔
2438
                return
×
2439
        }
×
2440

2441
        // We will do checks for no leafnodes and same cluster here inline and under the
2442
        // general account read lock.
2443
        // If we feel we need to update the leafnodes we will do that out of line to avoid
2444
        // blocking routes or GWs.
2445

2446
        acc.mu.RLock()
2,501,339✔
2447
        // First check if we even have leafnodes here.
2,501,339✔
2448
        if acc.nleafs == 0 {
4,934,310✔
2449
                acc.mu.RUnlock()
2,432,971✔
2450
                return
2,432,971✔
2451
        }
2,432,971✔
2452

2453
        // Is this a loop detection subject.
2454
        isLDS := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
68,368✔
2455

68,368✔
2456
        // Capture the cluster even if its empty.
68,368✔
2457
        var cluster string
68,368✔
2458
        if sub.origin != nil {
117,834✔
2459
                cluster = bytesToString(sub.origin)
49,466✔
2460
        }
49,466✔
2461

2462
        // If we have an isolated cluster we can return early, as long as it is not a loop detection subject.
2463
        // Empty clusters will return false for the check.
2464
        if !isLDS && acc.isLeafNodeClusterIsolated(cluster) {
88,729✔
2465
                acc.mu.RUnlock()
20,361✔
2466
                return
20,361✔
2467
        }
20,361✔
2468

2469
        // We can release the general account lock.
2470
        acc.mu.RUnlock()
48,007✔
2471

48,007✔
2472
        // We can hold the list lock here to avoid having to copy a large slice.
48,007✔
2473
        acc.lmu.RLock()
48,007✔
2474
        defer acc.lmu.RUnlock()
48,007✔
2475

48,007✔
2476
        // Do this once.
48,007✔
2477
        subject := string(sub.subject)
48,007✔
2478

48,007✔
2479
        // Walk the connected leafnodes.
48,007✔
2480
        for _, ln := range acc.lleafs {
107,606✔
2481
                if ln == sub.client {
90,467✔
2482
                        continue
30,868✔
2483
                }
2484
                ln.mu.Lock()
28,731✔
2485
                // Don't advertise interest from leafnodes to other isolated leafnodes.
28,731✔
2486
                if sub.client.kind == LEAF && ln.isIsolatedLeafNode() {
28,762✔
2487
                        ln.mu.Unlock()
31✔
2488
                        continue
31✔
2489
                }
2490
                // If `hubOnly` is true, it means that we want to update only leafnodes
2491
                // that connect to this server (so isHubLeafNode() would return `true`).
2492
                if hubOnly && !ln.isHubLeafNode() {
28,706✔
2493
                        ln.mu.Unlock()
6✔
2494
                        continue
6✔
2495
                }
2496
                // Check to make sure this sub does not have an origin cluster that matches the leafnode.
2497
                // If skipped, make sure that we still let go the "$LDS." subscription that allows
2498
                // the detection of loops as long as different cluster.
2499
                clusterDifferent := cluster != ln.remoteCluster()
28,694✔
2500
                if (isLDS && clusterDifferent) || ((cluster == _EMPTY_ || clusterDifferent) && (delta <= 0 || ln.canSubscribe(subject))) {
52,830✔
2501
                        ln.updateSmap(sub, delta, isLDS)
24,136✔
2502
                }
24,136✔
2503
                ln.mu.Unlock()
28,694✔
2504
        }
2505
}
2506

2507
// updateLeafNodes will make sure to update the account smap for the subscription.
2508
// Will also forward to all leaf nodes as needed.
2509
func (acc *Account) updateLeafNodes(sub *subscription, delta int32) {
2,501,316✔
2510
        acc.updateLeafNodesEx(sub, delta, false)
2,501,316✔
2511
}
2,501,316✔
2512

2513
// This will make an update to our internal smap and determine if we should send out
2514
// an interest update to the remote side.
2515
// Lock should be held.
2516
func (c *client) updateSmap(sub *subscription, delta int32, isLDS bool) {
24,136✔
2517
        if c.leaf.smap == nil {
24,159✔
2518
                return
23✔
2519
        }
23✔
2520

2521
        // If we are solicited make sure this is a local client or a non-solicited leaf node
2522
        skind := sub.client.kind
24,113✔
2523
        updateClient := skind == CLIENT || skind == SYSTEM || skind == JETSTREAM || skind == ACCOUNT
24,113✔
2524
        if !isLDS && c.isSpokeLeafNode() && !(updateClient || (skind == LEAF && !sub.client.isSpokeLeafNode())) {
32,041✔
2525
                return
7,928✔
2526
        }
7,928✔
2527

2528
        // For additions, check if that sub has just been processed during initLeafNodeSmapAndSendSubs
2529
        if delta > 0 && c.leaf.tsub != nil {
24,085✔
2530
                if _, present := c.leaf.tsub[sub]; present {
7,902✔
2531
                        delete(c.leaf.tsub, sub)
2✔
2532
                        if len(c.leaf.tsub) == 0 {
2✔
2533
                                c.leaf.tsub = nil
×
2534
                                c.leaf.tsubt.Stop()
×
2535
                                c.leaf.tsubt = nil
×
2536
                        }
×
2537
                        return
2✔
2538
                }
2539
        }
2540

2541
        key := keyFromSub(sub)
16,183✔
2542
        n, ok := c.leaf.smap[key]
16,183✔
2543
        if delta < 0 && !ok {
17,110✔
2544
                return
927✔
2545
        }
927✔
2546

2547
        // We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
2548
        update := sub.queue != nil || (n <= 0 && n+delta > 0) || (n > 0 && n+delta <= 0)
15,256✔
2549
        n += delta
15,256✔
2550
        if n > 0 {
26,799✔
2551
                c.leaf.smap[key] = n
11,543✔
2552
        } else {
15,256✔
2553
                delete(c.leaf.smap, key)
3,713✔
2554
        }
3,713✔
2555
        if update {
25,209✔
2556
                c.sendLeafNodeSubUpdate(key, n)
9,953✔
2557
        }
9,953✔
2558
}
2559

2560
// Used to force add subjects to the subject map.
2561
func (c *client) forceAddToSmap(subj string) {
4✔
2562
        c.mu.Lock()
4✔
2563
        defer c.mu.Unlock()
4✔
2564

4✔
2565
        if c.leaf.smap == nil {
4✔
2566
                return
×
2567
        }
×
2568
        n := c.leaf.smap[subj]
4✔
2569
        if n != 0 {
5✔
2570
                return
1✔
2571
        }
1✔
2572
        // Place into the map since it was not there.
2573
        c.leaf.smap[subj] = 1
3✔
2574
        c.sendLeafNodeSubUpdate(subj, 1)
3✔
2575
}
2576

2577
// Used to force remove a subject from the subject map.
2578
func (c *client) forceRemoveFromSmap(subj string) {
1✔
2579
        c.mu.Lock()
1✔
2580
        defer c.mu.Unlock()
1✔
2581

1✔
2582
        if c.leaf.smap == nil {
1✔
2583
                return
×
2584
        }
×
2585
        n := c.leaf.smap[subj]
1✔
2586
        if n == 0 {
1✔
2587
                return
×
2588
        }
×
2589
        n--
1✔
2590
        if n == 0 {
2✔
2591
                // Remove is now zero
1✔
2592
                delete(c.leaf.smap, subj)
1✔
2593
                c.sendLeafNodeSubUpdate(subj, 0)
1✔
2594
        } else {
1✔
2595
                c.leaf.smap[subj] = n
×
2596
        }
×
2597
}
2598

2599
// Send the subscription interest change to the other side.
2600
// Lock should be held.
2601
func (c *client) sendLeafNodeSubUpdate(key string, n int32) {
9,957✔
2602
        // If we are a spoke, we need to check if we are allowed to send this subscription over to the hub.
9,957✔
2603
        if c.isSpokeLeafNode() {
12,369✔
2604
                checkPerms := true
2,412✔
2605
                if len(key) > 0 && (key[0] == '$' || key[0] == '_') {
3,852✔
2606
                        if strings.HasPrefix(key, leafNodeLoopDetectionSubjectPrefix) ||
1,440✔
2607
                                strings.HasPrefix(key, oldGWReplyPrefix) ||
1,440✔
2608
                                strings.HasPrefix(key, gwReplyPrefix) {
1,535✔
2609
                                checkPerms = false
95✔
2610
                        }
95✔
2611
                }
2612
                if checkPerms {
4,729✔
2613
                        var subject string
2,317✔
2614
                        if sep := strings.IndexByte(key, ' '); sep != -1 {
2,808✔
2615
                                subject = key[:sep]
491✔
2616
                        } else {
2,317✔
2617
                                subject = key
1,826✔
2618
                        }
1,826✔
2619
                        if !c.canSubscribe(subject) {
2,317✔
2620
                                return
×
2621
                        }
×
2622
                }
2623
        }
2624
        // If we are here we can send over to the other side.
2625
        _b := [64]byte{}
9,957✔
2626
        b := bytes.NewBuffer(_b[:0])
9,957✔
2627
        c.writeLeafSub(b, key, n)
9,957✔
2628
        c.enqueueProto(b.Bytes())
9,957✔
2629
}
2630

2631
// Helper function to build the key.
2632
func keyFromSub(sub *subscription) string {
47,510✔
2633
        var sb strings.Builder
47,510✔
2634
        sb.Grow(len(sub.subject) + len(sub.queue) + 1)
47,510✔
2635
        sb.Write(sub.subject)
47,510✔
2636
        if sub.queue != nil {
51,240✔
2637
                // Just make the key subject spc group, e.g. 'foo bar'
3,730✔
2638
                sb.WriteByte(' ')
3,730✔
2639
                sb.Write(sub.queue)
3,730✔
2640
        }
3,730✔
2641
        return sb.String()
47,510✔
2642
}
2643

2644
const (
2645
        keyRoutedSub         = "R"
2646
        keyRoutedSubByte     = 'R'
2647
        keyRoutedLeafSub     = "L"
2648
        keyRoutedLeafSubByte = 'L'
2649
)
2650

2651
// Helper function to build the key that prevents collisions between normal
2652
// routed subscriptions and routed subscriptions on behalf of a leafnode.
2653
// Keys will look like this:
2654
// "R foo"          -> plain routed sub on "foo"
2655
// "R foo bar"      -> queue routed sub on "foo", queue "bar"
2656
// "L foo bar"      -> plain routed leaf sub on "foo", leaf "bar"
2657
// "L foo bar baz"  -> queue routed sub on "foo", queue "bar", leaf "baz"
2658
func keyFromSubWithOrigin(sub *subscription) string {
688,098✔
2659
        var sb strings.Builder
688,098✔
2660
        sb.Grow(2 + len(sub.origin) + 1 + len(sub.subject) + 1 + len(sub.queue))
688,098✔
2661
        leaf := len(sub.origin) > 0
688,098✔
2662
        if leaf {
704,544✔
2663
                sb.WriteByte(keyRoutedLeafSubByte)
16,446✔
2664
        } else {
688,098✔
2665
                sb.WriteByte(keyRoutedSubByte)
671,652✔
2666
        }
671,652✔
2667
        sb.WriteByte(' ')
688,098✔
2668
        sb.Write(sub.subject)
688,098✔
2669
        if sub.queue != nil {
711,468✔
2670
                sb.WriteByte(' ')
23,370✔
2671
                sb.Write(sub.queue)
23,370✔
2672
        }
23,370✔
2673
        if leaf {
704,544✔
2674
                sb.WriteByte(' ')
16,446✔
2675
                sb.Write(sub.origin)
16,446✔
2676
        }
16,446✔
2677
        return sb.String()
688,098✔
2678
}
2679

2680
// Lock should be held.
2681
func (c *client) writeLeafSub(w *bytes.Buffer, key string, n int32) {
36,546✔
2682
        if key == _EMPTY_ {
36,546✔
2683
                return
×
2684
        }
×
2685
        if n > 0 {
69,378✔
2686
                w.WriteString("LS+ " + key)
32,832✔
2687
                // Check for queue semantics, if found write n.
32,832✔
2688
                if strings.Contains(key, " ") {
35,149✔
2689
                        w.WriteString(" ")
2,317✔
2690
                        var b [12]byte
2,317✔
2691
                        var i = len(b)
2,317✔
2692
                        for l := n; l > 0; l /= 10 {
5,533✔
2693
                                i--
3,216✔
2694
                                b[i] = digits[l%10]
3,216✔
2695
                        }
3,216✔
2696
                        w.Write(b[i:])
2,317✔
2697
                        if c.trace {
2,317✔
2698
                                arg := fmt.Sprintf("%s %d", key, n)
×
2699
                                c.traceOutOp("LS+", []byte(arg))
×
2700
                        }
×
2701
                } else if c.trace {
30,711✔
2702
                        c.traceOutOp("LS+", []byte(key))
196✔
2703
                }
196✔
2704
        } else {
3,714✔
2705
                w.WriteString("LS- " + key)
3,714✔
2706
                if c.trace {
3,731✔
2707
                        c.traceOutOp("LS-", []byte(key))
17✔
2708
                }
17✔
2709
        }
2710
        w.WriteString(CR_LF)
36,546✔
2711
}
2712

2713
// processLeafSub will process an inbound sub request for the remote leaf node.
2714
func (c *client) processLeafSub(argo []byte) (err error) {
32,543✔
2715
        // Indicate activity.
32,543✔
2716
        c.in.subs++
32,543✔
2717

32,543✔
2718
        srv := c.srv
32,543✔
2719
        if srv == nil {
32,543✔
2720
                return nil
×
2721
        }
×
2722

2723
        // Copy so we do not reference a potentially large buffer
2724
        arg := make([]byte, len(argo))
32,543✔
2725
        copy(arg, argo)
32,543✔
2726

32,543✔
2727
        args := splitArg(arg)
32,543✔
2728
        sub := &subscription{client: c}
32,543✔
2729

32,543✔
2730
        delta := int32(1)
32,543✔
2731
        switch len(args) {
32,543✔
2732
        case 1:
30,260✔
2733
                sub.queue = nil
30,260✔
2734
        case 3:
2,283✔
2735
                sub.queue = args[1]
2,283✔
2736
                sub.qw = int32(parseSize(args[2]))
2,283✔
2737
                // TODO: (ik) We should have a non empty queue name and a queue
2,283✔
2738
                // weight >= 1. For 2.11, we may want to return an error if that
2,283✔
2739
                // is not the case, but for now just overwrite `delta` if queue
2,283✔
2740
                // weight is greater than 1 (it is possible after a reconnect/
2,283✔
2741
                // server restart to receive a queue weight > 1 for a new sub).
2,283✔
2742
                if sub.qw > 1 {
3,948✔
2743
                        delta = sub.qw
1,665✔
2744
                }
1,665✔
2745
        default:
×
2746
                return fmt.Errorf("processLeafSub Parse Error: '%s'", arg)
×
2747
        }
2748
        sub.subject = args[0]
32,543✔
2749

32,543✔
2750
        c.mu.Lock()
32,543✔
2751
        if c.isClosed() {
32,562✔
2752
                c.mu.Unlock()
19✔
2753
                return nil
19✔
2754
        }
19✔
2755

2756
        acc := c.acc
32,524✔
2757
        // Check if we have a loop.
32,524✔
2758
        ldsPrefix := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
32,524✔
2759

32,524✔
2760
        if ldsPrefix && bytesToString(sub.subject) == acc.getLDSubject() {
32,531✔
2761
                c.mu.Unlock()
7✔
2762
                c.handleLeafNodeLoop(true)
7✔
2763
                return nil
7✔
2764
        }
7✔
2765

2766
        // Check permissions if applicable. (but exclude the $LDS, $GR and _GR_)
2767
        checkPerms := true
32,517✔
2768
        if sub.subject[0] == '$' || sub.subject[0] == '_' {
62,054✔
2769
                if ldsPrefix ||
29,537✔
2770
                        bytes.HasPrefix(sub.subject, []byte(oldGWReplyPrefix)) ||
29,537✔
2771
                        bytes.HasPrefix(sub.subject, []byte(gwReplyPrefix)) {
31,599✔
2772
                        checkPerms = false
2,062✔
2773
                }
2,062✔
2774
        }
2775

2776
        // If we are a hub check that we can publish to this subject.
2777
        if checkPerms {
62,972✔
2778
                subj := string(sub.subject)
30,455✔
2779
                if subjectIsLiteral(subj) && !c.pubAllowedFullCheck(subj, true, true) {
30,780✔
2780
                        c.mu.Unlock()
325✔
2781
                        c.leafSubPermViolation(sub.subject)
325✔
2782
                        c.Debugf(fmt.Sprintf("Permissions Violation for Subscription to %q", sub.subject))
325✔
2783
                        return nil
325✔
2784
                }
325✔
2785
        }
2786

2787
        // Check if we have a maximum on the number of subscriptions.
2788
        if c.subsAtLimit() {
32,200✔
2789
                c.mu.Unlock()
8✔
2790
                c.maxSubsExceeded()
8✔
2791
                return nil
8✔
2792
        }
8✔
2793

2794
        // If we have an origin cluster associated mark that in the sub.
2795
        if rc := c.remoteCluster(); rc != _EMPTY_ {
60,772✔
2796
                sub.origin = []byte(rc)
28,588✔
2797
        }
28,588✔
2798

2799
        // Like Routes, we store local subs by account and subject and optionally queue name.
2800
        // If we have a queue it will have a trailing weight which we do not want.
2801
        if sub.queue != nil {
34,177✔
2802
                sub.sid = arg[:len(arg)-len(args[2])-1]
1,993✔
2803
        } else {
32,184✔
2804
                sub.sid = arg
30,191✔
2805
        }
30,191✔
2806
        key := bytesToString(sub.sid)
32,184✔
2807
        osub := c.subs[key]
32,184✔
2808
        if osub == nil {
62,836✔
2809
                c.subs[key] = sub
30,652✔
2810
                // Now place into the account sl.
30,652✔
2811
                if err := acc.sl.Insert(sub); err != nil {
30,652✔
2812
                        delete(c.subs, key)
×
2813
                        c.mu.Unlock()
×
2814
                        c.Errorf("Could not insert subscription: %v", err)
×
2815
                        c.sendErr("Invalid Subscription")
×
2816
                        return nil
×
2817
                }
×
2818
        } else if sub.queue != nil {
3,063✔
2819
                // For a queue we need to update the weight.
1,531✔
2820
                delta = sub.qw - atomic.LoadInt32(&osub.qw)
1,531✔
2821
                atomic.StoreInt32(&osub.qw, sub.qw)
1,531✔
2822
                acc.sl.UpdateRemoteQSub(osub)
1,531✔
2823
        }
1,531✔
2824
        spoke := c.isSpokeLeafNode()
32,184✔
2825
        c.mu.Unlock()
32,184✔
2826

32,184✔
2827
        // Only add in shadow subs if a new sub or qsub.
32,184✔
2828
        if osub == nil {
62,836✔
2829
                if err := c.addShadowSubscriptions(acc, sub, true); err != nil {
30,652✔
2830
                        c.Errorf(err.Error())
×
2831
                }
×
2832
        }
2833

2834
        // If we are not solicited, treat leaf node subscriptions similar to a
2835
        // client subscription, meaning we forward them to routes, gateways and
2836
        // other leaf nodes as needed.
2837
        if !spoke {
43,445✔
2838
                // If we are routing add to the route map for the associated account.
11,261✔
2839
                srv.updateRouteSubscriptionMap(acc, sub, delta)
11,261✔
2840
                if srv.gateway.enabled {
12,787✔
2841
                        srv.gatewayUpdateSubInterest(acc.Name, sub, delta)
1,526✔
2842
                }
1,526✔
2843
        }
2844
        // Now check on leafnode updates for other leaf nodes. We understand solicited
2845
        // and non-solicited state in this call so we will do the right thing.
2846
        acc.updateLeafNodes(sub, delta)
32,184✔
2847

32,184✔
2848
        return nil
32,184✔
2849
}
2850

2851
// If the leafnode is a solicited, set the connect delay based on default
2852
// or private option (for tests). Sends the error to the other side, log and
2853
// close the connection.
2854
func (c *client) handleLeafNodeLoop(sendErr bool) {
17✔
2855
        accName, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterLoopDetected)
17✔
2856
        errTxt := fmt.Sprintf("Loop detected for leafnode account=%q. Delaying attempt to reconnect for %v", accName, delay)
17✔
2857
        if sendErr {
26✔
2858
                c.sendErr(errTxt)
9✔
2859
        }
9✔
2860

2861
        c.Errorf(errTxt)
17✔
2862
        // If we are here with "sendErr" false, it means that this is the server
17✔
2863
        // that received the error. The other side will have closed the connection,
17✔
2864
        // but does not hurt to close here too.
17✔
2865
        c.closeConnection(ProtocolViolation)
17✔
2866
}
2867

2868
// processLeafUnsub will process an inbound unsub request for the remote leaf node.
2869
func (c *client) processLeafUnsub(arg []byte) error {
3,479✔
2870
        // Indicate any activity, so pub and sub or unsubs.
3,479✔
2871
        c.in.subs++
3,479✔
2872

3,479✔
2873
        acc := c.acc
3,479✔
2874
        srv := c.srv
3,479✔
2875

3,479✔
2876
        c.mu.Lock()
3,479✔
2877
        if c.isClosed() {
3,517✔
2878
                c.mu.Unlock()
38✔
2879
                return nil
38✔
2880
        }
38✔
2881

2882
        spoke := c.isSpokeLeafNode()
3,441✔
2883
        // We store local subs by account and subject and optionally queue name.
3,441✔
2884
        // LS- will have the arg exactly as the key.
3,441✔
2885
        sub, ok := c.subs[string(arg)]
3,441✔
2886
        if !ok {
3,453✔
2887
                // If not found, don't try to update routes/gws/leaf nodes.
12✔
2888
                c.mu.Unlock()
12✔
2889
                return nil
12✔
2890
        }
12✔
2891
        delta := int32(1)
3,429✔
2892
        if len(sub.queue) > 0 {
3,849✔
2893
                delta = sub.qw
420✔
2894
        }
420✔
2895
        c.mu.Unlock()
3,429✔
2896

3,429✔
2897
        c.unsubscribe(acc, sub, true, true)
3,429✔
2898
        if !spoke {
4,469✔
2899
                // If we are routing subtract from the route map for the associated account.
1,040✔
2900
                srv.updateRouteSubscriptionMap(acc, sub, -delta)
1,040✔
2901
                // Gateways
1,040✔
2902
                if srv.gateway.enabled {
1,321✔
2903
                        srv.gatewayUpdateSubInterest(acc.Name, sub, -delta)
281✔
2904
                }
281✔
2905
        }
2906
        // Now check on leafnode updates for other leaf nodes.
2907
        acc.updateLeafNodes(sub, -delta)
3,429✔
2908
        return nil
3,429✔
2909
}
2910

2911
func (c *client) processLeafHeaderMsgArgs(arg []byte) error {
472✔
2912
        // Unroll splitArgs to avoid runtime/heap issues
472✔
2913
        a := [MAX_MSG_ARGS][]byte{}
472✔
2914
        args := a[:0]
472✔
2915
        start := -1
472✔
2916
        for i, b := range arg {
31,269✔
2917
                switch b {
30,797✔
2918
                case ' ', '\t', '\r', '\n':
1,349✔
2919
                        if start >= 0 {
2,698✔
2920
                                args = append(args, arg[start:i])
1,349✔
2921
                                start = -1
1,349✔
2922
                        }
1,349✔
2923
                default:
29,448✔
2924
                        if start < 0 {
31,269✔
2925
                                start = i
1,821✔
2926
                        }
1,821✔
2927
                }
2928
        }
2929
        if start >= 0 {
944✔
2930
                args = append(args, arg[start:])
472✔
2931
        }
472✔
2932

2933
        c.pa.arg = arg
472✔
2934
        switch len(args) {
472✔
2935
        case 0, 1, 2:
×
2936
                return fmt.Errorf("processLeafHeaderMsgArgs Parse Error: '%s'", args)
×
2937
        case 3:
85✔
2938
                c.pa.reply = nil
85✔
2939
                c.pa.queues = nil
85✔
2940
                c.pa.hdb = args[1]
85✔
2941
                c.pa.hdr = parseSize(args[1])
85✔
2942
                c.pa.szb = args[2]
85✔
2943
                c.pa.size = parseSize(args[2])
85✔
2944
        case 4:
373✔
2945
                c.pa.reply = args[1]
373✔
2946
                c.pa.queues = nil
373✔
2947
                c.pa.hdb = args[2]
373✔
2948
                c.pa.hdr = parseSize(args[2])
373✔
2949
                c.pa.szb = args[3]
373✔
2950
                c.pa.size = parseSize(args[3])
373✔
2951
        default:
14✔
2952
                // args[1] is our reply indicator. Should be + or | normally.
14✔
2953
                if len(args[1]) != 1 {
14✔
2954
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2955
                }
×
2956
                switch args[1][0] {
14✔
2957
                case '+':
4✔
2958
                        c.pa.reply = args[2]
4✔
2959
                case '|':
10✔
2960
                        c.pa.reply = nil
10✔
2961
                default:
×
2962
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2963
                }
2964
                // Grab header size.
2965
                c.pa.hdb = args[len(args)-2]
14✔
2966
                c.pa.hdr = parseSize(c.pa.hdb)
14✔
2967

14✔
2968
                // Grab size.
14✔
2969
                c.pa.szb = args[len(args)-1]
14✔
2970
                c.pa.size = parseSize(c.pa.szb)
14✔
2971

14✔
2972
                // Grab queue names.
14✔
2973
                if c.pa.reply != nil {
18✔
2974
                        c.pa.queues = args[3 : len(args)-2]
4✔
2975
                } else {
14✔
2976
                        c.pa.queues = args[2 : len(args)-2]
10✔
2977
                }
10✔
2978
        }
2979
        if c.pa.hdr < 0 {
472✔
2980
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Header Size: '%s'", arg)
×
2981
        }
×
2982
        if c.pa.size < 0 {
472✔
2983
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Size: '%s'", args)
×
2984
        }
×
2985
        if c.pa.hdr > c.pa.size {
472✔
2986
                return fmt.Errorf("processLeafHeaderMsgArgs Header Size larger then TotalSize: '%s'", arg)
×
2987
        }
×
2988

2989
        // Common ones processed after check for arg length
2990
        c.pa.subject = args[0]
472✔
2991

472✔
2992
        return nil
472✔
2993
}
2994

2995
func (c *client) processLeafMsgArgs(arg []byte) error {
111,809✔
2996
        // Unroll splitArgs to avoid runtime/heap issues
111,809✔
2997
        a := [MAX_MSG_ARGS][]byte{}
111,809✔
2998
        args := a[:0]
111,809✔
2999
        start := -1
111,809✔
3000
        for i, b := range arg {
3,597,243✔
3001
                switch b {
3,485,434✔
3002
                case ' ', '\t', '\r', '\n':
163,561✔
3003
                        if start >= 0 {
327,122✔
3004
                                args = append(args, arg[start:i])
163,561✔
3005
                                start = -1
163,561✔
3006
                        }
163,561✔
3007
                default:
3,321,873✔
3008
                        if start < 0 {
3,597,243✔
3009
                                start = i
275,370✔
3010
                        }
275,370✔
3011
                }
3012
        }
3013
        if start >= 0 {
223,618✔
3014
                args = append(args, arg[start:])
111,809✔
3015
        }
111,809✔
3016

3017
        c.pa.arg = arg
111,809✔
3018
        switch len(args) {
111,809✔
3019
        case 0, 1:
×
3020
                return fmt.Errorf("processLeafMsgArgs Parse Error: '%s'", args)
×
3021
        case 2:
82,770✔
3022
                c.pa.reply = nil
82,770✔
3023
                c.pa.queues = nil
82,770✔
3024
                c.pa.szb = args[1]
82,770✔
3025
                c.pa.size = parseSize(args[1])
82,770✔
3026
        case 3:
6,487✔
3027
                c.pa.reply = args[1]
6,487✔
3028
                c.pa.queues = nil
6,487✔
3029
                c.pa.szb = args[2]
6,487✔
3030
                c.pa.size = parseSize(args[2])
6,487✔
3031
        default:
22,552✔
3032
                // args[1] is our reply indicator. Should be + or | normally.
22,552✔
3033
                if len(args[1]) != 1 {
22,552✔
3034
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3035
                }
×
3036
                switch args[1][0] {
22,552✔
3037
                case '+':
161✔
3038
                        c.pa.reply = args[2]
161✔
3039
                case '|':
22,391✔
3040
                        c.pa.reply = nil
22,391✔
3041
                default:
×
3042
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3043
                }
3044
                // Grab size.
3045
                c.pa.szb = args[len(args)-1]
22,552✔
3046
                c.pa.size = parseSize(c.pa.szb)
22,552✔
3047

22,552✔
3048
                // Grab queue names.
22,552✔
3049
                if c.pa.reply != nil {
22,713✔
3050
                        c.pa.queues = args[3 : len(args)-1]
161✔
3051
                } else {
22,552✔
3052
                        c.pa.queues = args[2 : len(args)-1]
22,391✔
3053
                }
22,391✔
3054
        }
3055
        if c.pa.size < 0 {
111,809✔
3056
                return fmt.Errorf("processLeafMsgArgs Bad or Missing Size: '%s'", args)
×
3057
        }
×
3058

3059
        // Common ones processed after check for arg length
3060
        c.pa.subject = args[0]
111,809✔
3061

111,809✔
3062
        return nil
111,809✔
3063
}
3064

3065
// processInboundLeafMsg is called to process an inbound msg from a leaf node.
3066
func (c *client) processInboundLeafMsg(msg []byte) {
110,123✔
3067
        // Update statistics
110,123✔
3068
        // The msg includes the CR_LF, so pull back out for accounting.
110,123✔
3069
        c.in.msgs++
110,123✔
3070
        c.in.bytes += int32(len(msg) - LEN_CR_LF)
110,123✔
3071

110,123✔
3072
        srv, acc, subject := c.srv, c.acc, string(c.pa.subject)
110,123✔
3073

110,123✔
3074
        // Mostly under testing scenarios.
110,123✔
3075
        if srv == nil || acc == nil {
110,125✔
3076
                return
2✔
3077
        }
2✔
3078

3079
        // Match the subscriptions. We will use our own L1 map if
3080
        // it's still valid, avoiding contention on the shared sublist.
3081
        var r *SublistResult
110,121✔
3082
        var ok bool
110,121✔
3083

110,121✔
3084
        genid := atomic.LoadUint64(&c.acc.sl.genid)
110,121✔
3085
        if genid == c.in.genid && c.in.results != nil {
217,897✔
3086
                r, ok = c.in.results[subject]
107,776✔
3087
        } else {
110,121✔
3088
                // Reset our L1 completely.
2,345✔
3089
                c.in.results = make(map[string]*SublistResult)
2,345✔
3090
                c.in.genid = genid
2,345✔
3091
        }
2,345✔
3092

3093
        // Go back to the sublist data structure.
3094
        if !ok {
189,736✔
3095
                r = c.acc.sl.Match(subject)
79,615✔
3096
                // Prune the results cache. Keeps us from unbounded growth. Random delete.
79,615✔
3097
                if len(c.in.results) >= maxResultCacheSize {
81,853✔
3098
                        n := 0
2,238✔
3099
                        for subj := range c.in.results {
76,092✔
3100
                                delete(c.in.results, subj)
73,854✔
3101
                                if n++; n > pruneSize {
76,092✔
3102
                                        break
2,238✔
3103
                                }
3104
                        }
3105
                }
3106
                // Then add the new cache entry.
3107
                c.in.results[subject] = r
79,615✔
3108
        }
3109

3110
        // Collect queue names if needed.
3111
        var qnames [][]byte
110,121✔
3112

110,121✔
3113
        // Check for no interest, short circuit if so.
110,121✔
3114
        // This is the fanout scale.
110,121✔
3115
        if len(r.psubs)+len(r.qsubs) > 0 {
219,989✔
3116
                flag := pmrNoFlag
109,868✔
3117
                // If we have queue subs in this cluster, then if we run in gateway
109,868✔
3118
                // mode and the remote gateways have queue subs, then we need to
109,868✔
3119
                // collect the queue groups this message was sent to so that we
109,868✔
3120
                // exclude them when sending to gateways.
109,868✔
3121
                if len(r.qsubs) > 0 && c.srv.gateway.enabled &&
109,868✔
3122
                        atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 {
122,170✔
3123
                        flag |= pmrCollectQueueNames
12,302✔
3124
                }
12,302✔
3125
                // If this is a mapped subject that means the mapped interest
3126
                // is what got us here, but this might not have a queue designation
3127
                // If that is the case, make sure we ignore to process local queue subscribers.
3128
                if len(c.pa.mapped) > 0 && len(c.pa.queues) == 0 {
110,184✔
3129
                        flag |= pmrIgnoreEmptyQueueFilter
316✔
3130
                }
316✔
3131
                _, qnames = c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, flag)
109,868✔
3132
        }
3133

3134
        // Now deal with gateways
3135
        if c.srv.gateway.enabled {
123,399✔
3136
                c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, qnames, true)
13,278✔
3137
        }
13,278✔
3138
}
3139

3140
// Handles a subscription permission violation.
3141
// See leafPermViolation() for details.
3142
func (c *client) leafSubPermViolation(subj []byte) {
325✔
3143
        c.leafPermViolation(false, subj)
325✔
3144
}
325✔
3145

3146
// Common function to process publish or subscribe leafnode permission violation.
3147
// Sends the permission violation error to the remote, logs it and closes the connection.
3148
// If this is from a server soliciting, the reconnection will be delayed.
3149
func (c *client) leafPermViolation(pub bool, subj []byte) {
325✔
3150
        if c.isSpokeLeafNode() {
650✔
3151
                // For spokes these are no-ops since the hub server told us our permissions.
325✔
3152
                // We just need to not send these over to the other side since we will get cutoff.
325✔
3153
                return
325✔
3154
        }
325✔
3155
        // FIXME(dlc) ?
3156
        c.setLeafConnectDelayIfSoliciting(leafNodeReconnectAfterPermViolation)
×
3157
        var action string
×
3158
        if pub {
×
3159
                c.sendErr(fmt.Sprintf("Permissions Violation for Publish to %q", subj))
×
3160
                action = "Publish"
×
3161
        } else {
×
3162
                c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q", subj))
×
3163
                action = "Subscription"
×
3164
        }
×
3165
        c.Errorf("%s Violation on %q - Check other side configuration", action, subj)
×
3166
        // TODO: add a new close reason that is more appropriate?
×
3167
        c.closeConnection(ProtocolViolation)
×
3168
}
3169

3170
// Invoked from generic processErr() for LEAF connections.
3171
func (c *client) leafProcessErr(errStr string) {
46✔
3172
        // Check if we got a cluster name collision.
46✔
3173
        if strings.Contains(errStr, ErrLeafNodeHasSameClusterName.Error()) {
49✔
3174
                _, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterClusterNameSame)
3✔
3175
                c.Errorf("Leafnode connection dropped with same cluster name error. Delaying attempt to reconnect for %v", delay)
3✔
3176
                return
3✔
3177
        }
3✔
3178

3179
        // We will look for Loop detected error coming from the other side.
3180
        // If we solicit, set the connect delay.
3181
        if !strings.Contains(errStr, "Loop detected") {
78✔
3182
                return
35✔
3183
        }
35✔
3184
        c.handleLeafNodeLoop(false)
8✔
3185
}
3186

3187
// If this leaf connection solicits, sets the connect delay to the given value,
3188
// or the one from the server option's LeafNode.connDelay if one is set (for tests).
3189
// Returns the connection's account name and delay.
3190
func (c *client) setLeafConnectDelayIfSoliciting(delay time.Duration) (string, time.Duration) {
20✔
3191
        c.mu.Lock()
20✔
3192
        if c.isSolicitedLeafNode() {
31✔
3193
                if s := c.srv; s != nil {
22✔
3194
                        if srvdelay := s.getOpts().LeafNode.connDelay; srvdelay != 0 {
16✔
3195
                                delay = srvdelay
5✔
3196
                        }
5✔
3197
                }
3198
                c.leaf.remote.setConnectDelay(delay)
11✔
3199
        }
3200
        accName := c.acc.Name
20✔
3201
        c.mu.Unlock()
20✔
3202
        return accName, delay
20✔
3203
}
3204

3205
// For the given remote Leafnode configuration, this function returns
3206
// if TLS is required, and if so, will return a clone of the TLS Config
3207
// (since some fields will be changed during handshake), the TLS server
3208
// name that is remembered, and the TLS timeout.
3209
func (c *client) leafNodeGetTLSConfigForSolicit(remote *leafNodeCfg) (bool, *tls.Config, string, float64) {
1,954✔
3210
        var (
1,954✔
3211
                tlsConfig  *tls.Config
1,954✔
3212
                tlsName    string
1,954✔
3213
                tlsTimeout float64
1,954✔
3214
        )
1,954✔
3215

1,954✔
3216
        remote.RLock()
1,954✔
3217
        defer remote.RUnlock()
1,954✔
3218

1,954✔
3219
        tlsRequired := remote.TLS || remote.TLSConfig != nil
1,954✔
3220
        if tlsRequired {
2,038✔
3221
                if remote.TLSConfig != nil {
135✔
3222
                        tlsConfig = remote.TLSConfig.Clone()
51✔
3223
                } else {
84✔
3224
                        tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}
33✔
3225
                }
33✔
3226
                tlsName = remote.tlsName
84✔
3227
                tlsTimeout = remote.TLSTimeout
84✔
3228
                if tlsTimeout == 0 {
134✔
3229
                        tlsTimeout = float64(TLS_TIMEOUT / time.Second)
50✔
3230
                }
50✔
3231
        }
3232

3233
        return tlsRequired, tlsConfig, tlsName, tlsTimeout
1,954✔
3234
}
3235

3236
// Initiates the LeafNode Websocket connection by:
3237
// - doing the TLS handshake if needed
3238
// - sending the HTTP request
3239
// - waiting for the HTTP response
3240
//
3241
// Since some bufio reader is used to consume the HTTP response, this function
3242
// returns the slice of buffered bytes (if any) so that the readLoop that will
3243
// be started after that consume those first before reading from the socket.
3244
// The boolean
3245
//
3246
// Lock held on entry.
3247
func (c *client) leafNodeSolicitWSConnection(opts *Options, rURL *url.URL, remote *leafNodeCfg) ([]byte, ClosedState, error) {
50✔
3248
        remote.RLock()
50✔
3249
        compress := remote.Websocket.Compression
50✔
3250
        // By default the server will mask outbound frames, but it can be disabled with this option.
50✔
3251
        noMasking := remote.Websocket.NoMasking
50✔
3252
        infoTimeout := remote.FirstInfoTimeout
50✔
3253
        remote.RUnlock()
50✔
3254
        // Will do the client-side TLS handshake if needed.
50✔
3255
        tlsRequired, err := c.leafClientHandshakeIfNeeded(remote, opts)
50✔
3256
        if err != nil {
54✔
3257
                // 0 will indicate that the connection was already closed
4✔
3258
                return nil, 0, err
4✔
3259
        }
4✔
3260

3261
        // For http request, we need the passed URL to contain either http or https scheme.
3262
        scheme := "http"
46✔
3263
        if tlsRequired {
54✔
3264
                scheme = "https"
8✔
3265
        }
8✔
3266
        // We will use the `/leafnode` path to tell the accepting WS server that it should
3267
        // create a LEAF connection, not a CLIENT.
3268
        // In case we use the user's URL path in the future, make sure we append the user's
3269
        // path to our `/leafnode` path.
3270
        lpath := leafNodeWSPath
46✔
3271
        if curPath := rURL.EscapedPath(); curPath != _EMPTY_ {
67✔
3272
                if curPath[0] == '/' {
42✔
3273
                        curPath = curPath[1:]
21✔
3274
                }
21✔
3275
                lpath = path.Join(curPath, lpath)
21✔
3276
        } else {
25✔
3277
                lpath = lpath[1:]
25✔
3278
        }
25✔
3279
        ustr := fmt.Sprintf("%s://%s/%s", scheme, rURL.Host, lpath)
46✔
3280
        u, _ := url.Parse(ustr)
46✔
3281
        req := &http.Request{
46✔
3282
                Method:     "GET",
46✔
3283
                URL:        u,
46✔
3284
                Proto:      "HTTP/1.1",
46✔
3285
                ProtoMajor: 1,
46✔
3286
                ProtoMinor: 1,
46✔
3287
                Header:     make(http.Header),
46✔
3288
                Host:       u.Host,
46✔
3289
        }
46✔
3290
        wsKey, err := wsMakeChallengeKey()
46✔
3291
        if err != nil {
46✔
3292
                return nil, WriteError, err
×
3293
        }
×
3294

3295
        req.Header["Upgrade"] = []string{"websocket"}
46✔
3296
        req.Header["Connection"] = []string{"Upgrade"}
46✔
3297
        req.Header["Sec-WebSocket-Key"] = []string{wsKey}
46✔
3298
        req.Header["Sec-WebSocket-Version"] = []string{"13"}
46✔
3299
        if compress {
55✔
3300
                req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue)
9✔
3301
        }
9✔
3302
        if noMasking {
56✔
3303
                req.Header.Add(wsNoMaskingHeader, wsNoMaskingValue)
10✔
3304
        }
10✔
3305
        c.nc.SetDeadline(time.Now().Add(infoTimeout))
46✔
3306
        if err := req.Write(c.nc); err != nil {
46✔
3307
                return nil, WriteError, err
×
3308
        }
×
3309

3310
        var resp *http.Response
46✔
3311

46✔
3312
        br := bufio.NewReaderSize(c.nc, MAX_CONTROL_LINE_SIZE)
46✔
3313
        resp, err = http.ReadResponse(br, req)
46✔
3314
        if err == nil &&
46✔
3315
                (resp.StatusCode != 101 ||
46✔
3316
                        !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
46✔
3317
                        !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
46✔
3318
                        resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) {
47✔
3319

1✔
3320
                err = fmt.Errorf("invalid websocket connection")
1✔
3321
        }
1✔
3322
        // Check compression extension...
3323
        if err == nil && c.ws.compress {
55✔
3324
                // Check that not only permessage-deflate extension is present, but that
9✔
3325
                // we also have server and client no context take over.
9✔
3326
                srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header, false)
9✔
3327

9✔
3328
                // If server does not support compression, then simply disable it in our side.
9✔
3329
                if !srvCompress {
13✔
3330
                        c.ws.compress = false
4✔
3331
                } else if !noCtxTakeover {
9✔
3332
                        err = fmt.Errorf("compression negotiation error")
×
3333
                }
×
3334
        }
3335
        // Same for no masking...
3336
        if err == nil && noMasking {
56✔
3337
                // Check if server accepts no masking
10✔
3338
                if resp.Header.Get(wsNoMaskingHeader) != wsNoMaskingValue {
11✔
3339
                        // Nope, need to mask our writes as any client would do.
1✔
3340
                        c.ws.maskwrite = true
1✔
3341
                }
1✔
3342
        }
3343
        if resp != nil {
76✔
3344
                resp.Body.Close()
30✔
3345
        }
30✔
3346
        if err != nil {
63✔
3347
                return nil, ReadError, err
17✔
3348
        }
17✔
3349
        c.Debugf("Leafnode compression=%v masking=%v", c.ws.compress, c.ws.maskwrite)
29✔
3350

29✔
3351
        var preBuf []byte
29✔
3352
        // We have to slurp whatever is in the bufio reader and pass that to the readloop.
29✔
3353
        if n := br.Buffered(); n != 0 {
29✔
3354
                preBuf, _ = br.Peek(n)
×
3355
        }
×
3356
        return preBuf, 0, nil
29✔
3357
}
3358

3359
const connectProcessTimeout = 2 * time.Second
3360

3361
// This is invoked for remote LEAF remote connections after processing the INFO
3362
// protocol.
3363
func (s *Server) leafNodeResumeConnectProcess(c *client) {
682✔
3364
        clusterName := s.ClusterName()
682✔
3365

682✔
3366
        c.mu.Lock()
682✔
3367
        if c.isClosed() {
682✔
3368
                c.mu.Unlock()
×
3369
                return
×
3370
        }
×
3371
        if err := c.sendLeafConnect(clusterName, c.headers); err != nil {
684✔
3372
                c.mu.Unlock()
2✔
3373
                c.closeConnection(WriteError)
2✔
3374
                return
2✔
3375
        }
2✔
3376

3377
        // Spin up the write loop.
3378
        s.startGoRoutine(func() { c.writeLoop() })
1,360✔
3379

3380
        // timeout leafNodeFinishConnectProcess
3381
        c.ping.tmr = time.AfterFunc(connectProcessTimeout, func() {
680✔
3382
                c.mu.Lock()
×
3383
                // check if leafNodeFinishConnectProcess was called and prevent later leafNodeFinishConnectProcess
×
3384
                if !c.flags.setIfNotSet(connectProcessFinished) {
×
3385
                        c.mu.Unlock()
×
3386
                        return
×
3387
                }
×
3388
                clearTimer(&c.ping.tmr)
×
3389
                closed := c.isClosed()
×
3390
                c.mu.Unlock()
×
3391
                if !closed {
×
3392
                        c.sendErrAndDebug("Stale Leaf Node Connection - Closing")
×
3393
                        c.closeConnection(StaleConnection)
×
3394
                }
×
3395
        })
3396
        c.mu.Unlock()
680✔
3397
        c.Debugf("Remote leafnode connect msg sent")
680✔
3398
}
3399

3400
// This is invoked for remote LEAF connections after processing the INFO
3401
// protocol and leafNodeResumeConnectProcess.
3402
// This will send LS+ the CONNECT protocol and register the leaf node.
3403
func (s *Server) leafNodeFinishConnectProcess(c *client) {
646✔
3404
        c.mu.Lock()
646✔
3405
        if !c.flags.setIfNotSet(connectProcessFinished) {
646✔
3406
                c.mu.Unlock()
×
3407
                return
×
3408
        }
×
3409
        if c.isClosed() {
646✔
3410
                c.mu.Unlock()
×
3411
                s.removeLeafNodeConnection(c)
×
3412
                return
×
3413
        }
×
3414
        remote := c.leaf.remote
646✔
3415
        // Check if we will need to send the system connect event.
646✔
3416
        remote.RLock()
646✔
3417
        sendSysConnectEvent := remote.Hub
646✔
3418
        remote.RUnlock()
646✔
3419

646✔
3420
        // Capture account before releasing lock
646✔
3421
        acc := c.acc
646✔
3422
        // cancel connectProcessTimeout
646✔
3423
        clearTimer(&c.ping.tmr)
646✔
3424
        c.mu.Unlock()
646✔
3425

646✔
3426
        // Make sure we register with the account here.
646✔
3427
        if err := c.registerWithAccount(acc); err != nil {
648✔
3428
                if err == ErrTooManyAccountConnections {
2✔
3429
                        c.maxAccountConnExceeded()
×
3430
                        return
×
3431
                } else if err == ErrLeafNodeLoop {
4✔
3432
                        c.handleLeafNodeLoop(true)
2✔
3433
                        return
2✔
3434
                }
2✔
3435
                c.Errorf("Registering leaf with account %s resulted in error: %v", acc.Name, err)
×
3436
                c.closeConnection(ProtocolViolation)
×
3437
                return
×
3438
        }
3439
        s.addLeafNodeConnection(c, _EMPTY_, _EMPTY_, false)
644✔
3440
        s.initLeafNodeSmapAndSendSubs(c)
644✔
3441
        if sendSysConnectEvent {
660✔
3442
                s.sendLeafNodeConnect(acc)
16✔
3443
        }
16✔
3444

3445
        // The above functions are not atomically under the client
3446
        // lock doing those operations. It is possible - since we
3447
        // have started the read/write loops - that the connection
3448
        // is closed before or in between. This would leave the
3449
        // closed LN connection possible registered with the account
3450
        // and/or the server's leafs map. So check if connection
3451
        // is closed, and if so, manually cleanup.
3452
        c.mu.Lock()
644✔
3453
        closed := c.isClosed()
644✔
3454
        if !closed {
1,288✔
3455
                c.setFirstPingTimer()
644✔
3456
        }
644✔
3457
        c.mu.Unlock()
644✔
3458
        if closed {
644✔
3459
                s.removeLeafNodeConnection(c)
×
3460
                if prev := acc.removeClient(c); prev == 1 {
×
3461
                        s.decActiveAccounts()
×
3462
                }
×
3463
        }
3464
}
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