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

nats-io / nats-server / 28352462621

24 Jun 2026 02:23PM UTC coverage: 80.32% (+2.4%) from 77.963%
28352462621

push

github

web-flow
NRG: Fix uncommitted membership change handling across truncate/snapshot/apply (#8332)

When an uncommitted membership change (`EntryAddPeer`/`EntryRemovePeer`)
is truncated, the speculative peer-set change wasn't reverted. This PR
replaces `membChangeIndex` with a `membChange` struct that records the
peer and its previous state (if removing), which can be reverted on
truncate.

The follow-up commits drop the redundant known peer flag (`Known: false`
is still exposed in `Raftz` for an uncommitted peer add, but now based
on the `membChange` struct), and ensures only committed peer state ends
up in a snapshot.

75544 of 94054 relevant lines covered (80.32%)

636991.72 hits per line

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

90.18
/server/leafnode.go
1
// Copyright 2019-2026 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
        "regexp"
31
        "runtime"
32
        "strconv"
33
        "strings"
34
        "sync"
35
        "sync/atomic"
36
        "time"
37

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

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

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

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

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

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

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

65
        // When a soliciting leafnode is rejected because it does not meet the
66
        // configured minimum version, delay the next reconnect attempt by this long.
67
        leafNodeMinVersionReconnectDelay = 5 * time.Second
68
)
69

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

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

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

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

133
func (c *client) isHubLeafNode() bool {
16,024✔
134
        return c.kind == LEAF && c.leaf != nil && !c.leaf.isSpoke
16,024✔
135
}
16,024✔
136

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

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

205
// Ensure that leafnode is properly configured.
206
func validateLeafNode(o *Options) error {
8,106✔
207
        if err := validateLeafNodeAuthOptions(o); err != nil {
8,108✔
208
                return err
2✔
209
        }
2✔
210

211
        if len(o.LeafNode.Remotes) > 0 {
8,699✔
212
                names := make(map[string]struct{})
595✔
213
                // Check for duplicate remotes, also, users can bind to any local account,
595✔
214
                // if its empty we will assume the $G account.
595✔
215
                for _, r := range o.LeafNode.Remotes {
1,342✔
216
                        if r.LocalAccount == _EMPTY_ {
1,189✔
217
                                r.LocalAccount = globalAccountName
442✔
218
                        }
442✔
219
                        rn := r.name()
747✔
220
                        if _, dup := names[rn]; dup {
750✔
221
                                return fmt.Errorf("duplicate remote %s", r.safeName())
3✔
222
                        }
3✔
223
                        names[rn] = struct{}{}
744✔
224
                }
225
        }
226

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

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

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

294
                if len(rcfg.URLs) >= 2 {
922✔
295
                        firstIsWS, ok := isWSURL(rcfg.URLs[0]), true
192✔
296
                        for i := 1; i < len(rcfg.URLs); i++ {
573✔
297
                                u := rcfg.URLs[i]
381✔
298
                                if isWS := isWSURL(u); isWS && !firstIsWS || !isWS && firstIsWS {
388✔
299
                                        ok = false
7✔
300
                                        break
7✔
301
                                }
302
                        }
303
                        if !ok {
199✔
304
                                return fmt.Errorf("remote leaf node configuration cannot have a mix of websocket and non-websocket urls: %q", redactURLList(rcfg.URLs))
7✔
305
                        }
7✔
306
                }
307
                if !wsAllowedFIPS() {
723✔
308
                        for _, u := range rcfg.URLs {
×
309
                                if isWSURL(u) {
×
310
                                        return fmt.Errorf("remote leaf node URL %q cannot be used in FIPS-140 mode when built with this Go version, use Go 1.26 or later", redactURLString(u.String()))
×
311
                                }
×
312
                        }
313
                }
314
                // Validate compression settings
315
                if rcfg.Compression.Mode != _EMPTY_ {
1,440✔
316
                        if err := validateAndNormalizeCompressionOption(&rcfg.Compression, CompressionS2Auto); err != nil {
722✔
317
                                return err
5✔
318
                        }
5✔
319
                }
320
        }
321

322
        if o.LeafNode.Port == 0 {
12,073✔
323
                return nil
4,000✔
324
        }
4,000✔
325

326
        // If MinVersion is defined, check that it is valid.
327
        if mv := o.LeafNode.MinVersion; mv != _EMPTY_ {
4,077✔
328
                if err := checkLeafMinVersionConfig(mv); err != nil {
6✔
329
                        return err
2✔
330
                }
2✔
331
        }
332

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

337
        if o.Gateway.Name == _EMPTY_ && o.Gateway.Port == 0 {
7,466✔
338
                return nil
3,395✔
339
        }
3,395✔
340
        // If we are here we have both leaf nodes and gateways defined, make sure there
341
        // is a system account defined.
342
        if o.SystemAccount == _EMPTY_ {
677✔
343
                return fmt.Errorf("leaf nodes and gateways (both being defined) require a system account to also be configured")
1✔
344
        }
1✔
345
        if err := validatePinnedCerts(o.LeafNode.TLSPinnedCerts); err != nil {
675✔
346
                return fmt.Errorf("leafnode: %v", err)
×
347
        }
×
348
        return nil
675✔
349
}
350

351
func checkLeafMinVersionConfig(mv string) error {
8✔
352
        if ok, err := versionAtLeastCheckError(mv, 2, 8, 0); !ok || err != nil {
12✔
353
                if err != nil {
6✔
354
                        return fmt.Errorf("invalid leafnode's minimum version: %v", err)
2✔
355
                } else {
4✔
356
                        return fmt.Errorf("the minimum version should be at least 2.8.0")
2✔
357
                }
2✔
358
        }
359
        return nil
4✔
360
}
361

362
// Used to validate user names in LeafNode configuration.
363
// - rejects mix of single and multiple users.
364
// - rejects duplicate user names.
365
func validateLeafNodeAuthOptions(o *Options) error {
8,156✔
366
        if len(o.LeafNode.Users) == 0 {
16,286✔
367
                return nil
8,130✔
368
        }
8,130✔
369
        if o.LeafNode.Username != _EMPTY_ {
28✔
370
                return fmt.Errorf("can not have a single user/pass and a users array")
2✔
371
        }
2✔
372
        if o.LeafNode.Nkey != _EMPTY_ {
24✔
373
                return fmt.Errorf("can not have a single nkey and a users array")
×
374
        }
×
375
        users := map[string]struct{}{}
24✔
376
        for _, u := range o.LeafNode.Users {
62✔
377
                if _, exists := users[u.Username]; exists {
40✔
378
                        return fmt.Errorf("duplicate user %q detected in leafnode authorization", u.Username)
2✔
379
                }
2✔
380
                users[u.Username] = struct{}{}
36✔
381
        }
382
        return nil
22✔
383
}
384

385
func validateLeafNodeProxyOptions(remote *RemoteLeafOpts) ([]string, error) {
1,317✔
386
        var warnings []string
1,317✔
387

1,317✔
388
        if remote.Proxy.URL == _EMPTY_ {
2,608✔
389
                return warnings, nil
1,291✔
390
        }
1,291✔
391

392
        proxyURL, err := url.Parse(remote.Proxy.URL)
26✔
393
        if err != nil {
27✔
394
                return warnings, fmt.Errorf("invalid proxy URL: %v", err)
1✔
395
        }
1✔
396

397
        if proxyURL.Scheme != "http" && proxyURL.Scheme != "https" {
27✔
398
                return warnings, fmt.Errorf("proxy URL scheme must be http or https, got: %s", proxyURL.Scheme)
2✔
399
        }
2✔
400

401
        if proxyURL.Host == _EMPTY_ {
25✔
402
                return warnings, fmt.Errorf("proxy URL must specify a host")
2✔
403
        }
2✔
404

405
        if remote.Proxy.Timeout < 0 {
22✔
406
                return warnings, fmt.Errorf("proxy timeout must be >= 0")
1✔
407
        }
1✔
408

409
        if (remote.Proxy.Username == _EMPTY_) != (remote.Proxy.Password == _EMPTY_) {
24✔
410
                return warnings, fmt.Errorf("proxy username and password must both be specified or both be empty")
4✔
411
        }
4✔
412

413
        if len(remote.URLs) > 0 {
32✔
414
                hasWebSocketURL := false
16✔
415
                hasNonWebSocketURL := false
16✔
416

16✔
417
                for _, remoteURL := range remote.URLs {
33✔
418
                        if remoteURL.Scheme == wsSchemePrefix || remoteURL.Scheme == wsSchemePrefixTLS {
30✔
419
                                hasWebSocketURL = true
13✔
420
                                if (remoteURL.Scheme == wsSchemePrefixTLS) &&
13✔
421
                                        remote.TLSConfig == nil && !remote.TLS {
14✔
422
                                        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✔
423
                                }
1✔
424
                        } else {
4✔
425
                                hasNonWebSocketURL = true
4✔
426
                        }
4✔
427
                }
428

429
                if !hasWebSocketURL {
18✔
430
                        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://)")
3✔
431
                } else if hasNonWebSocketURL {
16✔
432
                        warnings = append(warnings, "proxy configuration will only be used for WebSocket URLs: proxy settings do not apply to TCP connections (nats://)")
1✔
433
                }
1✔
434
        }
435

436
        return warnings, nil
15✔
437
}
438

439
// Wait for the configured reconnect interval before attempting to connect
440
// again to the remote leafnode.
441
func (s *Server) reConnectToRemoteLeafNode(remote *leafNodeCfg) {
260✔
442
        clearInProgress := true
260✔
443
        defer func() {
519✔
444
                s.grWG.Done()
259✔
445
                if clearInProgress {
331✔
446
                        remote.setConnectInProgress(false)
72✔
447
                }
72✔
448
        }()
449
        delay := s.getOpts().LeafNode.ReconnectInterval
260✔
450
        select {
260✔
451
        case <-time.After(delay):
198✔
452
        case <-remote.quitCh:
×
453
                return
×
454
        case <-s.quitCh:
62✔
455
                return
62✔
456
        }
457
        clearInProgress = !connectToRemoteLeafNode(s, remote, false)
198✔
458
}
459

460
// Creates a leafNodeCfg object that wraps the RemoteLeafOpts.
461
func newLeafNodeCfg(remote *RemoteLeafOpts) *leafNodeCfg {
702✔
462
        cfg := &leafNodeCfg{
702✔
463
                RemoteLeafOpts: remote,
702✔
464
                urls:           make([]*url.URL, 0, len(remote.URLs)),
702✔
465
                quitCh:         make(chan struct{}, 1),
702✔
466
        }
702✔
467
        if len(remote.DenyExports) > 0 || len(remote.DenyImports) > 0 {
712✔
468
                perms := &Permissions{}
10✔
469
                if len(remote.DenyExports) > 0 {
19✔
470
                        perms.Publish = &SubjectPermission{Deny: remote.DenyExports}
9✔
471
                }
9✔
472
                if len(remote.DenyImports) > 0 {
18✔
473
                        perms.Subscribe = &SubjectPermission{Deny: remote.DenyImports}
8✔
474
                }
8✔
475
                cfg.perms = perms
10✔
476
        }
477
        // Start with the one that is configured. We will add to this
478
        // array when receiving async leafnode INFOs.
479
        cfg.urls = append(cfg.urls, cfg.URLs...)
702✔
480
        // If allowed to randomize, do it on our copy of URLs
702✔
481
        if !remote.NoRandomize {
1,403✔
482
                rand.Shuffle(len(cfg.urls), func(i, j int) {
1,059✔
483
                        cfg.urls[i], cfg.urls[j] = cfg.urls[j], cfg.urls[i]
358✔
484
                })
358✔
485
        }
486
        // If we are TLS make sure we save off a proper servername if possible.
487
        // Do same for user/password since we may need them to connect to
488
        // a bare URL that we get from INFO protocol.
489
        for _, u := range cfg.urls {
1,777✔
490
                cfg.saveTLSHostname(u)
1,075✔
491
                cfg.saveUserPassword(u)
1,075✔
492
                // If the url(s) have the "wss://" scheme, and we don't have a TLS
1,075✔
493
                // config, mark that we should be using TLS anyway.
1,075✔
494
                if !cfg.TLS && isWSSURL(u) {
1,076✔
495
                        cfg.TLS = true
1✔
496
                }
1✔
497
        }
498
        return cfg
702✔
499
}
500

501
// Notifies the quit channel without blocking.
502
// No lock is needed to invoke this function.
503
func (cfg *leafNodeCfg) notifyQuitChannel() {
4✔
504
        select {
4✔
505
        case cfg.quitCh <- struct{}{}:
4✔
506
        default:
×
507
        }
508
}
509

510
// Sets the connect-in-progress status for this remote leaf configuration.
511
func (cfg *leafNodeCfg) setConnectInProgress(inProgress bool) {
2,290✔
512
        cfg.Lock()
2,290✔
513
        defer cfg.Unlock()
2,290✔
514
        // In both cases we want to drain the "quit" channel.
2,290✔
515
        select {
2,290✔
516
        case <-cfg.quitCh:
1✔
517
        default:
2,289✔
518
        }
519
        cfg.connInProgress = inProgress
2,290✔
520
}
521

522
// Returns `true` if this remote is in the middle of a connect, `false` otherwise.
523
func (cfg *leafNodeCfg) isConnectInProgress() bool {
2✔
524
        cfg.RLock()
2✔
525
        defer cfg.RUnlock()
2✔
526
        return cfg.connInProgress
2✔
527
}
2✔
528

529
// Mark that this remote is being removed from the configuration.
530
func (cfg *leafNodeCfg) markAsRemoved() {
2✔
531
        cfg.Lock()
2✔
532
        defer cfg.Unlock()
2✔
533
        // This function should be invoked only once, but protect.
2✔
534
        if cfg.removed {
2✔
535
                return
×
536
        }
×
537
        cfg.removed = true
2✔
538
        cfg.notifyQuitChannel()
2✔
539
}
540

541
// Returns false if it has been disabled or removed.
542
func (cfg *leafNodeCfg) stillValid() bool {
5,597✔
543
        cfg.RLock()
5,597✔
544
        defer cfg.RUnlock()
5,597✔
545
        return !cfg.Disabled && !cfg.removed
5,597✔
546
}
5,597✔
547

548
// Will pick an URL from the list of available URLs.
549
func (cfg *leafNodeCfg) pickNextURL() *url.URL {
3,272✔
550
        cfg.Lock()
3,272✔
551
        defer cfg.Unlock()
3,272✔
552
        // If the current URL is the first in the list and we have more than
3,272✔
553
        // one URL, then move that one to end of the list.
3,272✔
554
        if cfg.curURL != nil && len(cfg.urls) > 1 && urlsAreEqual(cfg.curURL, cfg.urls[0]) {
5,642✔
555
                first := cfg.urls[0]
2,370✔
556
                copy(cfg.urls, cfg.urls[1:])
2,370✔
557
                cfg.urls[len(cfg.urls)-1] = first
2,370✔
558
        }
2,370✔
559
        cfg.curURL = cfg.urls[0]
3,272✔
560
        return cfg.curURL
3,272✔
561
}
562

563
// Returns the current URL
564
func (cfg *leafNodeCfg) getCurrentURL() *url.URL {
86✔
565
        cfg.RLock()
86✔
566
        defer cfg.RUnlock()
86✔
567
        return cfg.curURL
86✔
568
}
86✔
569

570
// Returns how long the server should wait before attempting
571
// to solicit a remote leafnode connection.
572
func (cfg *leafNodeCfg) getConnectDelay() time.Duration {
901✔
573
        cfg.RLock()
901✔
574
        delay := cfg.connDelay
901✔
575
        cfg.RUnlock()
901✔
576
        return delay
901✔
577
}
901✔
578

579
// Sets the connect delay.
580
func (cfg *leafNodeCfg) setConnectDelay(delay time.Duration) {
144✔
581
        cfg.Lock()
144✔
582
        cfg.connDelay = delay
144✔
583
        cfg.Unlock()
144✔
584
}
144✔
585

586
// Ensure that non-exported options (used in tests) have
587
// been properly set.
588
func (s *Server) setLeafNodeNonExportedOptions() {
6,912✔
589
        opts := s.getOpts()
6,912✔
590
        s.leafNodeOpts.dialTimeout = opts.LeafNode.dialTimeout
6,912✔
591
        if s.leafNodeOpts.dialTimeout == 0 {
13,823✔
592
                // Use same timeouts as routes for now.
6,911✔
593
                s.leafNodeOpts.dialTimeout = DEFAULT_ROUTE_DIAL
6,911✔
594
        }
6,911✔
595
        s.leafNodeOpts.resolver = opts.LeafNode.resolver
6,912✔
596
        if s.leafNodeOpts.resolver == nil {
13,821✔
597
                s.leafNodeOpts.resolver = net.DefaultResolver
6,909✔
598
        }
6,909✔
599
}
600

601
const sharedSysAccDelay = 250 * time.Millisecond
602

603
// establishHTTPProxyTunnel establishes an HTTP CONNECT tunnel through a proxy server
604
func establishHTTPProxyTunnel(proxyURL, targetHost string, timeout time.Duration, username, password string) (net.Conn, error) {
11✔
605
        proxyAddr, err := url.Parse(proxyURL)
11✔
606
        if err != nil {
11✔
607
                // This should not happen since proxy URL is validated during configuration parsing
×
608
                return nil, fmt.Errorf("unexpected proxy URL parse error (URL was pre-validated): %v", err)
×
609
        }
×
610

611
        // Connect to the proxy server
612
        conn, err := natsDialTimeout("tcp", proxyAddr.Host, timeout)
11✔
613
        if err != nil {
11✔
614
                return nil, fmt.Errorf("failed to connect to proxy: %v", err)
×
615
        }
×
616

617
        // Set deadline for the entire proxy handshake
618
        if err := conn.SetDeadline(time.Now().Add(timeout)); err != nil {
11✔
619
                conn.Close()
×
620
                return nil, fmt.Errorf("failed to set deadline: %v", err)
×
621
        }
×
622

623
        req := &http.Request{
11✔
624
                Method: http.MethodConnect,
11✔
625
                URL:    &url.URL{Opaque: targetHost}, // Opaque is required for CONNECT
11✔
626
                Host:   targetHost,
11✔
627
                Header: make(http.Header),
11✔
628
        }
11✔
629

11✔
630
        // Add proxy authentication if provided
11✔
631
        if username != "" && password != "" {
13✔
632
                req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password)))
2✔
633
        }
2✔
634

635
        if err := req.Write(conn); err != nil {
11✔
636
                conn.Close()
×
637
                return nil, fmt.Errorf("failed to write CONNECT request: %v", err)
×
638
        }
×
639

640
        resp, err := http.ReadResponse(bufio.NewReader(conn), req)
11✔
641
        if err != nil {
11✔
642
                conn.Close()
×
643
                return nil, fmt.Errorf("failed to read proxy response: %v", err)
×
644
        }
×
645

646
        if resp.StatusCode != http.StatusOK {
12✔
647
                resp.Body.Close()
1✔
648
                conn.Close()
1✔
649
                return nil, fmt.Errorf("proxy CONNECT failed: %s", resp.Status)
1✔
650
        }
1✔
651

652
        // Close the response body
653
        resp.Body.Close()
10✔
654

10✔
655
        // Clear the deadline now that we've finished the proxy handshake
10✔
656
        if err := conn.SetDeadline(time.Time{}); err != nil {
10✔
657
                conn.Close()
×
658
                return nil, fmt.Errorf("failed to clear deadline: %v", err)
×
659
        }
×
660

661
        return conn, nil
10✔
662
}
663

664
// Connect to a remote leaf node asynchronously (that is, this function will do
665
// the connect in a go routine).
666
func (s *Server) connectToRemoteLeafNodeAsynchronously(remote *leafNodeCfg, firstConnect bool) {
703✔
667
        remote.setConnectInProgress(true)
703✔
668
        s.startGoRoutine(func() {
1,406✔
669
                defer s.grWG.Done()
703✔
670
                if !connectToRemoteLeafNode(s, remote, firstConnect) {
793✔
671
                        remote.setConnectInProgress(false)
90✔
672
                }
90✔
673
        })
674
}
675

676
// Connect to a remote leaf node. Should only be invoked from
677
// `s.connectToRemoteLeafNodeAsynchronously()` or `s.reConnectToRemoteLeafNode()`.
678
// Returns `true` if this function invoked `s.createLeafNode()`, false otherwise.
679
func connectToRemoteLeafNode(s *Server, remote *leafNodeCfg, firstConnect bool) bool {
901✔
680

901✔
681
        if remote == nil || len(remote.URLs) == 0 {
901✔
682
                s.Debugf("Empty remote leafnode definition, nothing to connect")
×
683
                return false
×
684
        }
×
685

686
        // If this remote is no longer valid by the time we return (e.g. it was
687
        // removed or disabled through a configuration reload), we will never
688
        // reconnect, so clear any JetStream observer state. Otherwise, the raft
689
        // nodes of this account's assets would remain observers.
690
        defer func() {
1,801✔
691
                if remote.stillValid() {
1,797✔
692
                        return
897✔
693
                }
897✔
694
                s.mu.RLock()
3✔
695
                shouldMigrate := remote.JetStreamClusterMigrate
3✔
696
                s.mu.RUnlock()
3✔
697
                if shouldMigrate {
5✔
698
                        s.clearObserverState(remote)
2✔
699
                }
2✔
700
        }()
701

702
        opts := s.getOpts()
901✔
703
        reconnectDelay := opts.LeafNode.ReconnectInterval
901✔
704
        s.mu.RLock()
901✔
705
        dialTimeout := s.leafNodeOpts.dialTimeout
901✔
706
        resolver := s.leafNodeOpts.resolver
901✔
707
        var isSysAcc bool
901✔
708
        if s.eventsEnabled() {
1,770✔
709
                isSysAcc = remote.LocalAccount == s.sys.account.Name
869✔
710
        }
869✔
711
        jetstreamMigrateDelay := remote.JetStreamClusterMigrateDelay
901✔
712
        s.mu.RUnlock()
901✔
713

901✔
714
        // If we are sharing a system account and we are not standalone delay to gather some info prior.
901✔
715
        if firstConnect && isSysAcc && !s.standAloneMode() {
969✔
716
                s.Debugf("Will delay first leafnode connect to shared system account due to clustering")
68✔
717
                remote.setConnectDelay(sharedSysAccDelay)
68✔
718
        }
68✔
719

720
        if connDelay := remote.getConnectDelay(); connDelay > 0 {
976✔
721
                select {
75✔
722
                case <-time.After(connDelay):
63✔
723
                case <-remote.quitCh:
×
724
                        return false
×
725
                case <-s.quitCh:
12✔
726
                        return false
12✔
727
                }
728
                remote.setConnectDelay(0)
63✔
729
        }
730

731
        var conn net.Conn
889✔
732

889✔
733
        const connErrFmt = "Error trying to connect as leafnode to remote server %q (attempt %v): %v"
889✔
734

889✔
735
        // Capture proxy configuration once before the loop with proper locking
889✔
736
        remote.RLock()
889✔
737
        proxyURL := remote.Proxy.URL
889✔
738
        proxyUsername := remote.Proxy.Username
889✔
739
        proxyPassword := remote.Proxy.Password
889✔
740
        proxyTimeout := remote.Proxy.Timeout
889✔
741
        remote.RUnlock()
889✔
742

889✔
743
        // Set default proxy timeout if not specified
889✔
744
        if proxyTimeout == 0 {
1,770✔
745
                proxyTimeout = dialTimeout
881✔
746
        }
881✔
747

748
        attempts := 0
889✔
749

889✔
750
        // In case the migrate timer was created but not canceled, do it when
889✔
751
        // this function exits. Note that the timer would not be created if
889✔
752
        // `jetstreamMigrateDelay == 0`.
889✔
753
        if jetstreamMigrateDelay > 0 {
897✔
754
                defer remote.cancelMigrateTimer()
8✔
755
        }
8✔
756

757
        reconnectTimer := time.NewTimer(reconnectDelay)
889✔
758
        reconnectTimer.Stop()
889✔
759
        defer stopAndClearTimer(&reconnectTimer)
889✔
760

889✔
761
        for s.isRunning() && remote.stillValid() {
4,161✔
762
                rURL := remote.pickNextURL()
3,272✔
763
                url, err := s.getRandomIP(resolver, rURL.Host, nil)
3,272✔
764
                if err == nil {
6,539✔
765
                        var ipStr string
3,267✔
766
                        if url != rURL.Host {
3,337✔
767
                                ipStr = fmt.Sprintf(" (%s)", url)
70✔
768
                        }
70✔
769
                        // Some test may want to disable remotes from connecting
770
                        if s.isLeafConnectDisabled() {
3,400✔
771
                                s.Debugf("Will not attempt to connect to remote server on %q%s, leafnodes currently disabled", rURL.Host, ipStr)
133✔
772
                                err = ErrLeafNodeDisabled
133✔
773
                        } else {
3,267✔
774
                                s.Debugf("Trying to connect as leafnode to remote server on %q%s", rURL.Host, ipStr)
3,134✔
775

3,134✔
776
                                // Check if proxy is configured
3,134✔
777
                                if proxyURL != _EMPTY_ {
3,142✔
778
                                        targetHost := rURL.Host
8✔
779
                                        // If URL doesn't include port, add the default port for the scheme
8✔
780
                                        if rURL.Port() == _EMPTY_ {
8✔
781
                                                defaultPort := "80"
×
782
                                                if rURL.Scheme == wsSchemePrefixTLS {
×
783
                                                        defaultPort = "443"
×
784
                                                }
×
785
                                                targetHost = net.JoinHostPort(rURL.Hostname(), defaultPort)
×
786
                                        }
787

788
                                        conn, err = establishHTTPProxyTunnel(proxyURL, targetHost, proxyTimeout, proxyUsername, proxyPassword)
8✔
789
                                } else {
3,126✔
790
                                        // Direct connection
3,126✔
791
                                        conn, err = natsDialTimeout("tcp", url, dialTimeout)
3,126✔
792
                                }
3,126✔
793
                        }
794
                }
795
                if err != nil {
5,744✔
796
                        jitter := time.Duration(rand.Int63n(int64(reconnectDelay)))
2,472✔
797
                        delay := reconnectDelay + jitter
2,472✔
798
                        attempts++
2,472✔
799
                        if s.shouldReportConnectErr(firstConnect, attempts) {
4,937✔
800
                                s.Errorf(connErrFmt, rURL.Host, attempts, err)
2,465✔
801
                        } else {
2,472✔
802
                                s.Debugf(connErrFmt, rURL.Host, attempts, err)
7✔
803
                        }
7✔
804
                        remote.Lock()
2,472✔
805
                        // if we are using a delay to start migrating assets, kick off a migrate timer.
2,472✔
806
                        if remote.jsMigrateTimer == nil && jetstreamMigrateDelay > 0 {
2,480✔
807
                                remote.jsMigrateTimer = time.AfterFunc(jetstreamMigrateDelay, func() {
16✔
808
                                        s.checkJetStreamMigrate(remote)
8✔
809
                                })
8✔
810
                        }
811
                        remote.Unlock()
2,472✔
812
                        reconnectTimer.Reset(delay)
2,472✔
813
                        select {
2,472✔
814
                        case <-s.quitCh:
82✔
815
                                return false
82✔
816
                        case <-remote.quitCh:
3✔
817
                                return false
3✔
818
                        case <-reconnectTimer.C:
2,386✔
819
                                // Check if we should migrate any JetStream assets immediately while this remote is down.
2,386✔
820
                                // This will be used if JetStreamClusterMigrateDelay was not set
2,386✔
821
                                if jetstreamMigrateDelay == 0 {
4,700✔
822
                                        s.checkJetStreamMigrate(remote)
2,314✔
823
                                }
2,314✔
824
                                continue
2,386✔
825
                        }
826
                }
827
                remote.cancelMigrateTimer()
800✔
828
                // We can check here, but really we will have to check again when the server
800✔
829
                // is about to add to the `s.leafs` map later in the process.
800✔
830
                if !remote.stillValid() {
800✔
831
                        conn.Close()
×
832
                        return false
×
833
                }
×
834

835
                // We have a connection here to a remote server.
836
                // Go ahead and create our leaf node and return.
837
                s.createLeafNode(conn, rURL, remote, nil)
800✔
838

800✔
839
                // Clear any observer states if we had them.
800✔
840
                s.clearObserverState(remote)
800✔
841

800✔
842
                return true
800✔
843
        }
844

845
        return false
3✔
846
}
847

848
func (cfg *leafNodeCfg) cancelMigrateTimer() {
808✔
849
        cfg.Lock()
808✔
850
        stopAndClearTimer(&cfg.jsMigrateTimer)
808✔
851
        cfg.Unlock()
808✔
852
}
808✔
853

854
// This will clear any observer state such that stream or consumer assets on this server can become leaders again.
855
func (s *Server) clearObserverState(remote *leafNodeCfg) {
802✔
856
        s.mu.RLock()
802✔
857
        accName := remote.LocalAccount
802✔
858
        s.mu.RUnlock()
802✔
859

802✔
860
        acc, err := s.LookupAccount(accName)
802✔
861
        if err != nil {
804✔
862
                s.Warnf("Error looking up account [%s] checking for JetStream clear observer state on a leafnode", accName)
2✔
863
                return
2✔
864
        }
2✔
865

866
        acc.jscmMu.Lock()
800✔
867
        defer acc.jscmMu.Unlock()
800✔
868

800✔
869
        // Walk all streams looking for any clustered stream, skip otherwise.
800✔
870
        for _, mset := range acc.streams() {
827✔
871
                node := mset.raftNode()
27✔
872
                if node == nil {
45✔
873
                        // Not R>1
18✔
874
                        continue
18✔
875
                }
876
                // Check consumers
877
                for _, o := range mset.getConsumers() {
11✔
878
                        if n := o.raftNode(); n != nil {
4✔
879
                                // Ensure we can become a leader again.
2✔
880
                                n.SetObserver(false)
2✔
881
                        }
2✔
882
                }
883
                // Ensure we can not become a leader again.
884
                node.SetObserver(false)
9✔
885
        }
886
}
887

888
// Check to see if we should migrate any assets from this account.
889
func (s *Server) checkJetStreamMigrate(remote *leafNodeCfg) {
2,322✔
890
        s.mu.RLock()
2,322✔
891
        accName, shouldMigrate := remote.LocalAccount, remote.JetStreamClusterMigrate
2,322✔
892
        s.mu.RUnlock()
2,322✔
893

2,322✔
894
        if !shouldMigrate {
4,577✔
895
                return
2,255✔
896
        }
2,255✔
897

898
        acc, err := s.LookupAccount(accName)
67✔
899
        if err != nil {
67✔
900
                s.Warnf("Error looking up account [%s] checking for JetStream migration on a leafnode", accName)
×
901
                return
×
902
        }
×
903

904
        acc.jscmMu.Lock()
67✔
905
        defer acc.jscmMu.Unlock()
67✔
906

67✔
907
        // Walk all streams looking for any clustered stream, skip otherwise.
67✔
908
        // If we are the leader force stepdown.
67✔
909
        for _, mset := range acc.streams() {
100✔
910
                node := mset.raftNode()
33✔
911
                if node == nil {
33✔
912
                        // Not R>1
×
913
                        continue
×
914
                }
915
                // Collect any consumers
916
                for _, o := range mset.getConsumers() {
52✔
917
                        if n := o.raftNode(); n != nil {
38✔
918
                                n.StepDown()
19✔
919
                                // Ensure we can not become a leader while in this state.
19✔
920
                                n.SetObserver(true)
19✔
921
                        }
19✔
922
                }
923
                // Stepdown if this stream was leader.
924
                node.StepDown()
33✔
925
                // Ensure we can not become a leader while in this state.
33✔
926
                node.SetObserver(true)
33✔
927
        }
928
}
929

930
// Helper for checking.
931
func (s *Server) isLeafConnectDisabled() bool {
3,267✔
932
        s.mu.RLock()
3,267✔
933
        defer s.mu.RUnlock()
3,267✔
934
        return s.leafDisableConnect
3,267✔
935
}
3,267✔
936

937
// Save off the tlsName for when we use TLS and mix hostnames and IPs. IPs usually
938
// come from the server we connect to.
939
//
940
// We used to save the name only if there was a TLSConfig or scheme equal to "tls".
941
// However, this was causing failures for users that did not set the scheme (and
942
// their remote connections did not have a tls{} block).
943
// We now save the host name regardless in case the remote returns an INFO indicating
944
// that TLS is required.
945
//
946
// Lock held on entry.
947
func (cfg *leafNodeCfg) saveTLSHostname(u *url.URL) {
1,693✔
948
        if cfg.tlsName == _EMPTY_ && net.ParseIP(u.Hostname()) == nil {
1,710✔
949
                cfg.tlsName = u.Hostname()
17✔
950
        }
17✔
951
}
952

953
// Save off the username/password for when we connect using a bare URL
954
// that we get from the INFO protocol.
955
//
956
// Lock held on entry.
957
func (cfg *leafNodeCfg) saveUserPassword(u *url.URL) {
1,075✔
958
        if cfg.username == _EMPTY_ && u.User != nil {
1,377✔
959
                cfg.username = u.User.Username()
302✔
960
                cfg.password, _ = u.User.Password()
302✔
961
        }
302✔
962
}
963

964
// This starts the leafnode accept loop in a go routine, unless it
965
// is detected that the server has already been shutdown.
966
func (s *Server) startLeafNodeAcceptLoop() {
4,051✔
967
        // Snapshot server options.
4,051✔
968
        opts := s.getOpts()
4,051✔
969

4,051✔
970
        port := opts.LeafNode.Port
4,051✔
971
        if port == -1 {
7,926✔
972
                port = 0
3,875✔
973
        }
3,875✔
974

975
        if s.isShuttingDown() {
4,051✔
976
                return
×
977
        }
×
978

979
        s.mu.Lock()
4,051✔
980
        hp := net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(port))
4,051✔
981
        l, e := natsListen("tcp", hp)
4,051✔
982
        s.leafNodeListenerErr = e
4,051✔
983
        if e != nil {
4,051✔
984
                s.mu.Unlock()
×
985
                s.Fatalf("Error listening on leafnode port: %d - %v", opts.LeafNode.Port, e)
×
986
                return
×
987
        }
×
988

989
        s.Noticef("Listening for leafnode connections on %s",
4,051✔
990
                net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
4,051✔
991

4,051✔
992
        tlsRequired := opts.LeafNode.TLSConfig != nil
4,051✔
993
        tlsVerify := tlsRequired && opts.LeafNode.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert
4,051✔
994
        // Do not set compression in this Info object, it would possibly cause
4,051✔
995
        // issues when sending asynchronous INFO to the remote.
4,051✔
996
        info := Info{
4,051✔
997
                ID:            s.info.ID,
4,051✔
998
                Name:          s.info.Name,
4,051✔
999
                Version:       s.info.Version,
4,051✔
1000
                GitCommit:     gitCommit,
4,051✔
1001
                GoVersion:     runtime.Version(),
4,051✔
1002
                AuthRequired:  true,
4,051✔
1003
                TLSRequired:   tlsRequired,
4,051✔
1004
                TLSVerify:     tlsVerify,
4,051✔
1005
                MaxPayload:    s.info.MaxPayload, // TODO(dlc) - Allow override?
4,051✔
1006
                Headers:       s.supportsHeaders(),
4,051✔
1007
                JetStream:     opts.JetStream,
4,051✔
1008
                Domain:        opts.JetStreamDomain,
4,051✔
1009
                Proto:         s.getServerProto(),
4,051✔
1010
                InfoOnConnect: true,
4,051✔
1011
                JSApiLevel:    JSApiLevel,
4,051✔
1012
        }
4,051✔
1013
        // If we have selected a random port...
4,051✔
1014
        if port == 0 {
7,926✔
1015
                // Write resolved port back to options.
3,875✔
1016
                opts.LeafNode.Port = l.Addr().(*net.TCPAddr).Port
3,875✔
1017
        }
3,875✔
1018

1019
        s.leafNodeInfo = info
4,051✔
1020
        // Possibly override Host/Port and set IP based on Cluster.Advertise
4,051✔
1021
        if err := s.setLeafNodeInfoHostPortAndIP(); err != nil {
4,051✔
1022
                s.Fatalf("Error setting leafnode INFO with LeafNode.Advertise value of %s, err=%v", opts.LeafNode.Advertise, err)
×
1023
                l.Close()
×
1024
                s.mu.Unlock()
×
1025
                return
×
1026
        }
×
1027
        s.leafURLsMap[s.leafNodeInfo.IP]++
4,051✔
1028
        s.generateLeafNodeInfoJSON()
4,051✔
1029

4,051✔
1030
        // Setup state that can enable shutdown
4,051✔
1031
        s.leafNodeListener = l
4,051✔
1032

4,051✔
1033
        // As of now, a server that does not have remotes configured would
4,051✔
1034
        // never solicit a connection, so we should not have to warn if
4,051✔
1035
        // InsecureSkipVerify is set in main LeafNodes config (since
4,051✔
1036
        // this TLS setting matters only when soliciting a connection).
4,051✔
1037
        // Still, warn if insecure is set in any of LeafNode block.
4,051✔
1038
        // We need to check remotes, even if tls is not required on accept.
4,051✔
1039
        warn := tlsRequired && opts.LeafNode.TLSConfig.InsecureSkipVerify
4,051✔
1040
        if !warn {
8,100✔
1041
                for _, r := range opts.LeafNode.Remotes {
4,210✔
1042
                        if r.TLSConfig != nil && r.TLSConfig.InsecureSkipVerify {
161✔
1043
                                warn = true
×
1044
                                break
×
1045
                        }
1046
                }
1047
        }
1048
        if warn {
4,053✔
1049
                s.Warnf(leafnodeTLSInsecureWarning)
2✔
1050
        }
2✔
1051
        go s.acceptConnections(l, "Leafnode", func(conn net.Conn) { s.createLeafNode(conn, nil, nil, nil) }, nil)
4,904✔
1052
        s.mu.Unlock()
4,051✔
1053
}
1054

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

1058
// clusterName is provided as argument to avoid lock ordering issues with the locked client c
1059
// Lock should be held entering here.
1060
func (c *client) sendLeafConnect(clusterName string, headers bool) error {
667✔
1061
        // We support basic user/pass and operator based user JWT with signatures.
667✔
1062
        cinfo := leafConnectInfo{
667✔
1063
                Version:       VERSION,
667✔
1064
                ID:            c.srv.info.ID,
667✔
1065
                Domain:        c.srv.info.Domain,
667✔
1066
                Name:          c.srv.info.Name,
667✔
1067
                Hub:           c.leaf.remote.Hub,
667✔
1068
                Cluster:       clusterName,
667✔
1069
                Headers:       headers,
667✔
1070
                JetStream:     c.acc.jetStreamConfigured(),
667✔
1071
                DenyPub:       c.leaf.remote.DenyImports,
667✔
1072
                Compression:   c.leaf.compression,
667✔
1073
                RemoteAccount: c.acc.GetName(),
667✔
1074
                Proto:         c.srv.getServerProto(),
667✔
1075
                Isolate:       c.leaf.remote.RequestIsolation,
667✔
1076
        }
667✔
1077

667✔
1078
        // If a signature callback is specified, this takes precedence over anything else.
667✔
1079
        if cb := c.leaf.remote.SignatureCB; cb != nil {
672✔
1080
                nonce := c.nonce
5✔
1081
                c.mu.Unlock()
5✔
1082
                jwt, sigraw, err := cb(nonce)
5✔
1083
                c.mu.Lock()
5✔
1084
                if err == nil && c.isClosed() {
6✔
1085
                        err = ErrConnectionClosed
1✔
1086
                }
1✔
1087
                if err != nil {
7✔
1088
                        c.Errorf("Error signing the nonce: %v", err)
2✔
1089
                        return err
2✔
1090
                }
2✔
1091
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
3✔
1092
                cinfo.JWT, cinfo.Sig = jwt, sig
3✔
1093

1094
        } else if creds := c.leaf.remote.Credentials; creds != _EMPTY_ {
718✔
1095
                // Check for credentials first, that will take precedence..
56✔
1096
                c.Debugf("Authenticating with credentials file %q", c.leaf.remote.Credentials)
56✔
1097
                contents, err := os.ReadFile(creds)
56✔
1098
                if err != nil {
56✔
1099
                        c.Errorf("%v", err)
×
1100
                        return err
×
1101
                }
×
1102
                defer wipeSlice(contents)
56✔
1103
                items := credsRe.FindAllSubmatch(contents, -1)
56✔
1104
                if len(items) < 2 {
56✔
1105
                        c.Errorf("Credentials file malformed")
×
1106
                        return err
×
1107
                }
×
1108
                // First result should be the user JWT.
1109
                // We copy here so that the file containing the seed will be wiped appropriately.
1110
                raw := items[0][1]
56✔
1111
                tmp := make([]byte, len(raw))
56✔
1112
                copy(tmp, raw)
56✔
1113
                // Seed is second item.
56✔
1114
                kp, err := nkeys.FromSeed(items[1][1])
56✔
1115
                if err != nil {
56✔
1116
                        c.Errorf("Credentials file has malformed seed")
×
1117
                        return err
×
1118
                }
×
1119
                // Wipe our key on exit.
1120
                defer kp.Wipe()
56✔
1121

56✔
1122
                sigraw, _ := kp.Sign(c.nonce)
56✔
1123
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
56✔
1124
                cinfo.JWT = bytesToString(tmp)
56✔
1125
                cinfo.Sig = sig
56✔
1126
        } else if nkey := c.leaf.remote.Nkey; nkey != _EMPTY_ {
611✔
1127
                kp, err := nkeys.FromSeed([]byte(nkey))
5✔
1128
                if err != nil {
5✔
1129
                        c.Errorf("Remote nkey has malformed seed")
×
1130
                        return err
×
1131
                }
×
1132
                // Wipe our key on exit.
1133
                defer kp.Wipe()
5✔
1134
                sigraw, _ := kp.Sign(c.nonce)
5✔
1135
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
5✔
1136
                pkey, _ := kp.PublicKey()
5✔
1137
                cinfo.Nkey = pkey
5✔
1138
                cinfo.Sig = sig
5✔
1139
        }
1140
        // In addition, and this is to allow auth callout, set user/password or
1141
        // token if applicable.
1142
        if userInfo := c.leaf.remote.curURL.User; userInfo != nil {
987✔
1143
                cinfo.User = userInfo.Username()
322✔
1144
                var ok bool
322✔
1145
                cinfo.Pass, ok = userInfo.Password()
322✔
1146
                // For backward compatibility, if only username is provided, set both
322✔
1147
                // Token and User, not just Token.
322✔
1148
                if !ok {
331✔
1149
                        cinfo.Token = cinfo.User
9✔
1150
                }
9✔
1151
        } else if c.leaf.remote.username != _EMPTY_ {
350✔
1152
                cinfo.User = c.leaf.remote.username
7✔
1153
                cinfo.Pass = c.leaf.remote.password
7✔
1154
                // For backward compatibility, if only username is provided, set both
7✔
1155
                // Token and User, not just Token.
7✔
1156
                if cinfo.Pass == _EMPTY_ {
7✔
1157
                        cinfo.Token = cinfo.User
×
1158
                }
×
1159
        }
1160
        b, err := json.Marshal(cinfo)
665✔
1161
        if err != nil {
665✔
1162
                c.Errorf("Error marshaling CONNECT to remote leafnode: %v\n", err)
×
1163
                return err
×
1164
        }
×
1165
        // Although this call is made before the writeLoop is created,
1166
        // we don't really need to send in place. The protocol will be
1167
        // sent out by the writeLoop.
1168
        c.enqueueProto([]byte(fmt.Sprintf(ConProto, b)))
665✔
1169
        return nil
665✔
1170
}
1171

1172
// Makes a deep copy of the LeafNode Info structure.
1173
// The server lock is held on entry.
1174
func (s *Server) copyLeafNodeInfo() *Info {
2,679✔
1175
        clone := s.leafNodeInfo
2,679✔
1176
        // Copy the array of urls.
2,679✔
1177
        if len(s.leafNodeInfo.LeafNodeURLs) > 0 {
4,884✔
1178
                clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...)
2,205✔
1179
        }
2,205✔
1180
        return &clone
2,679✔
1181
}
1182

1183
// Adds a LeafNode URL that we get when a route connects to the Info structure.
1184
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
1185
// Returns a boolean indicating if the URL was added or not.
1186
// Server lock is held on entry
1187
func (s *Server) addLeafNodeURL(urlStr string) bool {
8,109✔
1188
        if s.leafURLsMap.addUrl(urlStr) {
16,213✔
1189
                s.generateLeafNodeInfoJSON()
8,104✔
1190
                return true
8,104✔
1191
        }
8,104✔
1192
        return false
5✔
1193
}
1194

1195
// Removes a LeafNode URL of the route that is disconnecting from the Info structure.
1196
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
1197
// Returns a boolean indicating if the URL was removed or not.
1198
// Server lock is held on entry.
1199
func (s *Server) removeLeafNodeURL(urlStr string) bool {
8,109✔
1200
        // Don't need to do this if we are removing the route connection because
8,109✔
1201
        // we are shuting down...
8,109✔
1202
        if s.isShuttingDown() {
12,499✔
1203
                return false
4,390✔
1204
        }
4,390✔
1205
        if s.leafURLsMap.removeUrl(urlStr) {
7,434✔
1206
                s.generateLeafNodeInfoJSON()
3,715✔
1207
                return true
3,715✔
1208
        }
3,715✔
1209
        return false
4✔
1210
}
1211

1212
// Server lock is held on entry
1213
func (s *Server) generateLeafNodeInfoJSON() {
15,870✔
1214
        s.leafNodeInfo.Cluster = s.cachedClusterName()
15,870✔
1215
        s.leafNodeInfo.LeafNodeURLs = s.leafURLsMap.getAsStringSlice()
15,870✔
1216
        s.leafNodeInfo.WSConnectURLs = s.websocket.connectURLsMap.getAsStringSlice()
15,870✔
1217
        s.leafNodeInfoJSON = generateInfoJSON(&s.leafNodeInfo)
15,870✔
1218
}
15,870✔
1219

1220
// Sends an async INFO protocol so that the connected servers can update
1221
// their list of LeafNode urls.
1222
func (s *Server) sendAsyncLeafNodeInfo() {
11,819✔
1223
        for _, c := range s.leafs {
11,914✔
1224
                c.mu.Lock()
95✔
1225
                c.enqueueProto(s.leafNodeInfoJSON)
95✔
1226
                c.mu.Unlock()
95✔
1227
        }
95✔
1228
}
1229

1230
// Called when an inbound leafnode connection is accepted or we create one for a solicited leafnode.
1231
func (s *Server) createLeafNode(conn net.Conn, rURL *url.URL, remote *leafNodeCfg, ws *websocket) *client {
1,688✔
1232
        // Snapshot server options.
1,688✔
1233
        opts := s.getOpts()
1,688✔
1234

1,688✔
1235
        maxPay := int32(opts.MaxPayload)
1,688✔
1236
        maxSubs := int32(opts.MaxSubs)
1,688✔
1237
        // For system, maxSubs of 0 means unlimited, so re-adjust here.
1,688✔
1238
        if maxSubs == 0 {
3,375✔
1239
                maxSubs = -1
1,687✔
1240
        }
1,687✔
1241
        now := time.Now().UTC()
1,688✔
1242

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

1,688✔
1247
        // If the leafnode subject interest should be isolated, flag it here.
1,688✔
1248
        s.optsMu.RLock()
1,688✔
1249
        if c.leaf.isolated = s.opts.LeafNode.IsolateLeafnodeInterest; !c.leaf.isolated && remote != nil {
2,486✔
1250
                c.leaf.isolated = remote.LocalIsolation
798✔
1251
        }
798✔
1252
        s.optsMu.RUnlock()
1,688✔
1253

1,688✔
1254
        // For accepted LN connections, ws will be != nil if it was accepted
1,688✔
1255
        // through the Websocket port.
1,688✔
1256
        c.ws = ws
1,688✔
1257

1,688✔
1258
        // For remote, check if the scheme starts with "ws", if so, we will initiate
1,688✔
1259
        // a remote Leaf Node connection as a websocket connection.
1,688✔
1260
        if remote != nil && rURL != nil && isWSURL(rURL) {
1,742✔
1261
                remote.RLock()
54✔
1262
                c.ws = &websocket{compress: remote.Websocket.Compression, maskwrite: !remote.Websocket.NoMasking}
54✔
1263
                remote.RUnlock()
54✔
1264
        }
54✔
1265

1266
        // Determines if we are soliciting the connection or not.
1267
        var solicited bool
1,688✔
1268
        var acc *Account
1,688✔
1269
        var remoteSuffix string
1,688✔
1270
        if remote != nil {
2,488✔
1271
                // For now, if lookup fails, we will constantly try
800✔
1272
                // to recreate this LN connection.
800✔
1273
                lacc := remote.LocalAccount
800✔
1274
                var err error
800✔
1275
                acc, err = s.LookupAccount(lacc)
800✔
1276
                if err != nil {
802✔
1277
                        // An account not existing is something that can happen with nats/http account resolver and the account
2✔
1278
                        // has not yet been pushed, or the request failed for other reasons.
2✔
1279
                        // remote needs to be set or retry won't happen
2✔
1280
                        c.leaf.remote = remote
2✔
1281
                        c.closeConnection(MissingAccount)
2✔
1282
                        s.Errorf("Unable to lookup account %s for solicited leafnode connection: %v", lacc, err)
2✔
1283
                        return nil
2✔
1284
                }
2✔
1285
                remoteSuffix = fmt.Sprintf(" for account: %s", acc.traceLabel())
798✔
1286
        }
1287

1288
        c.mu.Lock()
1,686✔
1289
        c.initClient()
1,686✔
1290
        c.Noticef("Leafnode connection created%s %s", remoteSuffix, c.opts.Name)
1,686✔
1291

1,686✔
1292
        var (
1,686✔
1293
                tlsFirst         bool
1,686✔
1294
                tlsFirstFallback time.Duration
1,686✔
1295
                infoTimeout      time.Duration
1,686✔
1296
        )
1,686✔
1297
        if remote != nil {
2,484✔
1298
                solicited = true
798✔
1299
                remote.Lock()
798✔
1300
                c.leaf.remote = remote
798✔
1301
                c.setPermissions(remote.perms)
798✔
1302
                if !c.leaf.remote.Hub {
1,578✔
1303
                        c.leaf.isSpoke = true
780✔
1304
                }
780✔
1305
                tlsFirst = remote.TLSHandshakeFirst
798✔
1306
                infoTimeout = remote.FirstInfoTimeout
798✔
1307
                remote.Unlock()
798✔
1308
                c.acc = acc
798✔
1309
        } else {
888✔
1310
                c.flags.set(expectConnect)
888✔
1311
                if ws != nil {
923✔
1312
                        c.Debugf("Leafnode compression=%v", c.ws.compress)
35✔
1313
                }
35✔
1314
                tlsFirst = opts.LeafNode.TLSHandshakeFirst
888✔
1315
                if f := opts.LeafNode.TLSHandshakeFirstFallback; f > 0 {
889✔
1316
                        tlsFirstFallback = f
1✔
1317
                }
1✔
1318
        }
1319
        c.mu.Unlock()
1,686✔
1320

1,686✔
1321
        var nonce [nonceLen]byte
1,686✔
1322
        var info *Info
1,686✔
1323

1,686✔
1324
        // Grab this before the client lock below.
1,686✔
1325
        if !solicited {
2,574✔
1326
                // Grab server variables
888✔
1327
                s.mu.Lock()
888✔
1328
                info = s.copyLeafNodeInfo()
888✔
1329
                // For tests that want to simulate old servers, do not set the compression
888✔
1330
                // on the INFO protocol if configured with CompressionNotSupported.
888✔
1331
                // Also suppress it if WebSocket compression is already in use, otherwise
888✔
1332
                // an old soliciting peer would honor the advertised mode, switch to S2,
888✔
1333
                // and then wait forever for a compressed INFO response from us.
888✔
1334
                if cm := opts.LeafNode.Compression.Mode; cm != CompressionNotSupported && (ws == nil || !ws.compress) {
1,768✔
1335
                        info.Compression = cm
880✔
1336
                }
880✔
1337
                // We always send a nonce for LEAF connections. Do not change that without
1338
                // taking into account presence of proxy trusted keys.
1339
                s.generateNonce(nonce[:])
888✔
1340
                s.mu.Unlock()
888✔
1341
        }
1342

1343
        // Grab lock
1344
        c.mu.Lock()
1,686✔
1345

1,686✔
1346
        var preBuf []byte
1,686✔
1347
        if solicited {
2,484✔
1348
                // For websocket connection, we need to send an HTTP request,
798✔
1349
                // and get the response before starting the readLoop to get
798✔
1350
                // the INFO, etc..
798✔
1351
                if c.isWebsocket() {
852✔
1352
                        var err error
54✔
1353
                        var closeReason ClosedState
54✔
1354

54✔
1355
                        preBuf, closeReason, err = c.leafNodeSolicitWSConnection(opts, rURL, remote)
54✔
1356
                        if err != nil {
75✔
1357
                                c.Errorf("Error soliciting websocket connection: %v", err)
21✔
1358
                                c.mu.Unlock()
21✔
1359
                                if closeReason != 0 {
38✔
1360
                                        c.closeConnection(closeReason)
17✔
1361
                                }
17✔
1362
                                return nil
21✔
1363
                        }
1364
                } else {
744✔
1365
                        // If configured to do TLS handshake first
744✔
1366
                        if tlsFirst {
748✔
1367
                                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
5✔
1368
                                        c.mu.Unlock()
1✔
1369
                                        return nil
1✔
1370
                                }
1✔
1371
                        }
1372
                        // We need to wait for the info, but not for too long.
1373
                        c.nc.SetReadDeadline(time.Now().Add(infoTimeout))
743✔
1374
                }
1375

1376
                // We will process the INFO from the readloop and finish by
1377
                // sending the CONNECT and finish registration later.
1378
        } else {
888✔
1379
                // Send our info to the other side.
888✔
1380
                // Remember the nonce we sent here for signatures, etc.
888✔
1381
                c.nonce = make([]byte, nonceLen)
888✔
1382
                copy(c.nonce, nonce[:])
888✔
1383
                info.Nonce = bytesToString(c.nonce)
888✔
1384
                info.CID = c.cid
888✔
1385
                proto := generateInfoJSON(info)
888✔
1386

888✔
1387
                var pre []byte
888✔
1388
                // We need first to check for "TLS First" fallback delay.
888✔
1389
                if tlsFirstFallback > 0 {
889✔
1390
                        // We wait and see if we are getting any data. Since we did not send
1✔
1391
                        // the INFO protocol yet, only clients that use TLS first should be
1✔
1392
                        // sending data (the TLS handshake). We don't really check the content:
1✔
1393
                        // if it is a rogue agent and not an actual client performing the
1✔
1394
                        // TLS handshake, the error will be detected when performing the
1✔
1395
                        // handshake on our side.
1✔
1396
                        pre = make([]byte, 4)
1✔
1397
                        c.nc.SetReadDeadline(time.Now().Add(tlsFirstFallback))
1✔
1398
                        n, _ := io.ReadFull(c.nc, pre[:])
1✔
1399
                        c.nc.SetReadDeadline(time.Time{})
1✔
1400
                        // If we get any data (regardless of possible timeout), we will proceed
1✔
1401
                        // with the TLS handshake.
1✔
1402
                        if n > 0 {
1✔
1403
                                pre = pre[:n]
×
1404
                        } else {
1✔
1405
                                // We did not get anything so we will send the INFO protocol.
1✔
1406
                                pre = nil
1✔
1407
                                // Set the boolean to false for the rest of the function.
1✔
1408
                                tlsFirst = false
1✔
1409
                        }
1✔
1410
                }
1411

1412
                if !tlsFirst {
1,771✔
1413
                        // We have to send from this go routine because we may
883✔
1414
                        // have to block for TLS handshake before we start our
883✔
1415
                        // writeLoop go routine. The other side needs to receive
883✔
1416
                        // this before it can initiate the TLS handshake..
883✔
1417
                        c.sendProtoNow(proto)
883✔
1418

883✔
1419
                        // The above call could have marked the connection as closed (due to TCP error).
883✔
1420
                        if c.isClosed() {
883✔
1421
                                c.mu.Unlock()
×
1422
                                c.closeConnection(WriteError)
×
1423
                                return nil
×
1424
                        }
×
1425
                }
1426

1427
                // Check to see if we need to spin up TLS.
1428
                if !c.isWebsocket() && info.TLSRequired {
972✔
1429
                        // If we have a prebuffer create a multi-reader.
84✔
1430
                        if len(pre) > 0 {
84✔
1431
                                c.nc = &tlsMixConn{c.nc, bytes.NewBuffer(pre)}
×
1432
                        }
×
1433
                        // Perform server-side TLS handshake.
1434
                        if err := c.doTLSServerHandshake(tlsHandshakeLeaf, opts.LeafNode.TLSConfig, opts.LeafNode.TLSTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
141✔
1435
                                c.mu.Unlock()
57✔
1436
                                return nil
57✔
1437
                        }
57✔
1438
                }
1439

1440
                // If the user wants the TLS handshake to occur first, now that it is
1441
                // done, send the INFO protocol.
1442
                if tlsFirst {
834✔
1443
                        c.flags.set(didTLSFirst)
3✔
1444
                        c.sendProtoNow(proto)
3✔
1445
                        if c.isClosed() {
3✔
1446
                                c.mu.Unlock()
×
1447
                                c.closeConnection(WriteError)
×
1448
                                return nil
×
1449
                        }
×
1450
                }
1451

1452
                // Leaf nodes will always require a CONNECT to let us know
1453
                // when we are properly bound to an account.
1454
                //
1455
                // If compression is configured, we can't set the authTimer here because
1456
                // it would cause the parser to fail any incoming protocol that is not a
1457
                // CONNECT (and we need to exchange INFO protocols for compression
1458
                // negotiation). So instead, use the ping timer until we are done with
1459
                // negotiation and can set the auth timer.
1460
                timeout := secondsToDuration(opts.LeafNode.AuthTimeout)
831✔
1461
                if needsCompression(opts.LeafNode.Compression.Mode) {
1,433✔
1462
                        c.ping.tmr = time.AfterFunc(timeout, func() {
611✔
1463
                                c.authTimeout()
9✔
1464
                        })
9✔
1465
                } else {
229✔
1466
                        c.setAuthTimer(timeout)
229✔
1467
                }
229✔
1468
        }
1469

1470
        // Keep track in case server is shutdown before we can successfully register.
1471
        if !s.addToTempClients(c.cid, c) {
1,607✔
1472
                c.mu.Unlock()
×
1473
                c.setNoReconnect()
×
1474
                c.closeConnection(ServerShutdown)
×
1475
                return nil
×
1476
        }
×
1477

1478
        // Spin up the read loop.
1479
        s.startGoRoutine(func() { c.readLoop(preBuf) })
3,214✔
1480

1481
        // We will spin the write loop for solicited connections only
1482
        // when processing the INFO and after switching to TLS if needed.
1483
        if !solicited {
2,438✔
1484
                s.startGoRoutine(func() { c.writeLoop() })
1,662✔
1485
        }
1486

1487
        c.mu.Unlock()
1,607✔
1488

1,607✔
1489
        return c
1,607✔
1490
}
1491

1492
// Will perform the client-side TLS handshake if needed. Assumes that this
1493
// is called by the solicit side (remote will be non nil). Returns `true`
1494
// if TLS is required, `false` otherwise.
1495
// Lock held on entry.
1496
func (c *client) leafClientHandshakeIfNeeded(remote *leafNodeCfg, opts *Options) (bool, error) {
1,885✔
1497
        // Check if TLS is required and gather TLS config variables.
1,885✔
1498
        tlsRequired, tlsConfig, tlsName, tlsTimeout := c.leafNodeGetTLSConfigForSolicit(remote)
1,885✔
1499
        if !tlsRequired {
3,684✔
1500
                return false, nil
1,799✔
1501
        }
1,799✔
1502

1503
        // If TLS required, peform handshake.
1504
        // Get the URL that was used to connect to the remote server.
1505
        rURL := remote.getCurrentURL()
86✔
1506

86✔
1507
        // Perform the client-side TLS handshake.
86✔
1508
        if resetTLSName, err := c.doTLSClientHandshake(tlsHandshakeLeaf, rURL, tlsConfig, tlsName, tlsTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
131✔
1509
                // Check if we need to reset the remote's TLS name.
45✔
1510
                if resetTLSName {
45✔
1511
                        remote.Lock()
×
1512
                        remote.tlsName = _EMPTY_
×
1513
                        remote.Unlock()
×
1514
                }
×
1515
                return false, err
45✔
1516
        }
1517
        return true, nil
41✔
1518
}
1519

1520
func (c *client) processLeafnodeInfo(info *Info) {
2,609✔
1521
        c.mu.Lock()
2,609✔
1522
        if c.leaf == nil || c.isClosed() {
2,610✔
1523
                c.mu.Unlock()
1✔
1524
                return
1✔
1525
        }
1✔
1526
        s := c.srv
2,608✔
1527
        opts := s.getOpts()
2,608✔
1528
        remote := c.leaf.remote
2,608✔
1529
        didSolicit := remote != nil
2,608✔
1530
        firstINFO := !c.flags.isSet(infoReceived)
2,608✔
1531

2,608✔
1532
        // In case of websocket, the TLS handshake has been already done.
2,608✔
1533
        // So check only for non websocket connections and for configurations
2,608✔
1534
        // where the TLS Handshake was not done first.
2,608✔
1535
        if didSolicit && !c.flags.isSet(handshakeComplete) && !c.isWebsocket() && !remote.TLSHandshakeFirst {
4,435✔
1536
                // If the server requires TLS, we need to set this in the remote
1,827✔
1537
                // otherwise if there is no TLS configuration block for the remote,
1,827✔
1538
                // the solicit side will not attempt to perform the TLS handshake.
1,827✔
1539
                if firstINFO && info.TLSRequired {
1,897✔
1540
                        // Check for TLS/proxy configuration mismatch
70✔
1541
                        if remote.Proxy.URL != _EMPTY_ && !remote.TLS && remote.TLSConfig == nil {
70✔
1542
                                c.mu.Unlock()
×
1543
                                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.")
×
1544
                                c.closeConnection(TLSHandshakeError)
×
1545
                                return
×
1546
                        }
×
1547
                        remote.TLS = true
70✔
1548
                }
1549
                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
1,867✔
1550
                        c.mu.Unlock()
40✔
1551
                        return
40✔
1552
                }
40✔
1553
        }
1554

1555
        // Check for compression, unless already done.
1556
        if firstINFO && !c.flags.isSet(compressionNegotiated) {
3,854✔
1557
                // A solicited leafnode connection must first receive a leafnode INFO.
1,286✔
1558
                // Classify wrong-port connections before any leaf-specific negotiation.
1,286✔
1559
                if didSolicit && (info.CID == 0 || info.LeafNodeURLs == nil) {
1,340✔
1560
                        c.mu.Unlock()
54✔
1561
                        c.Errorf(ErrConnectedToWrongPort.Error())
54✔
1562
                        c.closeConnection(WrongPort)
54✔
1563
                        return
54✔
1564
                }
54✔
1565

1566
                // Prevent from getting back here.
1567
                c.flags.set(compressionNegotiated)
1,232✔
1568

1,232✔
1569
                var co *CompressionOpts
1,232✔
1570
                if !didSolicit {
1,793✔
1571
                        co = &opts.LeafNode.Compression
561✔
1572
                } else {
1,232✔
1573
                        co = &remote.Compression
671✔
1574
                }
671✔
1575
                if needsCompression(co.Mode) {
2,449✔
1576
                        // Release client lock since following function will need server lock.
1,217✔
1577
                        c.mu.Unlock()
1,217✔
1578
                        compress, err := s.negotiateLeafCompression(c, didSolicit, info.Compression, co)
1,217✔
1579
                        if err != nil {
1,217✔
1580
                                c.sendErrAndErr(err.Error())
×
1581
                                c.closeConnection(ProtocolViolation)
×
1582
                                return
×
1583
                        }
×
1584
                        if compress {
2,335✔
1585
                                // Done for now, will get back another INFO protocol...
1,118✔
1586
                                return
1,118✔
1587
                        }
1,118✔
1588
                        // No compression because one side does not want/can't, so proceed.
1589
                        c.mu.Lock()
99✔
1590
                        // Check that the connection did not close if the lock was released.
99✔
1591
                        if c.isClosed() {
99✔
1592
                                c.mu.Unlock()
×
1593
                                return
×
1594
                        }
×
1595
                } else {
15✔
1596
                        // Coming from an old server, the Compression field would be the empty
15✔
1597
                        // string. For servers that are configured with CompressionNotSupported,
15✔
1598
                        // this makes them behave as old servers.
15✔
1599
                        if info.Compression == _EMPTY_ || co.Mode == CompressionNotSupported {
17✔
1600
                                c.leaf.compression = CompressionNotSupported
2✔
1601
                        } else {
15✔
1602
                                c.leaf.compression = CompressionOff
13✔
1603
                        }
13✔
1604
                }
1605
                // Accepting side does not normally process an INFO protocol during
1606
                // initial connection handshake. So we keep it consistent by returning
1607
                // if we are not soliciting.
1608
                if !didSolicit {
118✔
1609
                        // If we had created the ping timer instead of the auth timer, we will
4✔
1610
                        // clear the ping timer and set the auth timer now that the compression
4✔
1611
                        // negotiation is done.
4✔
1612
                        if info.Compression != _EMPTY_ && c.ping.tmr != nil {
5✔
1613
                                clearTimer(&c.ping.tmr)
1✔
1614
                                c.setAuthTimer(secondsToDuration(opts.LeafNode.AuthTimeout))
1✔
1615
                        }
1✔
1616
                        c.mu.Unlock()
4✔
1617
                        return
4✔
1618
                }
1619
                // Fall through and process the INFO protocol as usual.
1620
        }
1621

1622
        // Note: For now, only the initial INFO has a nonce. We
1623
        // will probably do auto key rotation at some point.
1624
        if firstINFO {
2,105✔
1625
                // Mark that the INFO protocol has been received.
713✔
1626
                c.flags.set(infoReceived)
713✔
1627
                // Prevent connecting to non leafnode port. Need to do this only for
713✔
1628
                // the first INFO, not for async INFO updates...
713✔
1629
                //
713✔
1630
                // Content of INFO sent by the server when accepting a tcp connection.
713✔
1631
                // -------------------------------------------------------------------
713✔
1632
                // Listen Port Of | CID | ClientConnectURLs | LeafNodeURLs | Gateway |
713✔
1633
                // -------------------------------------------------------------------
713✔
1634
                //      CLIENT    |  X* |        X**        |              |         |
713✔
1635
                //      ROUTE     |     |        X**        |      X***    |         |
713✔
1636
                //     GATEWAY    |     |                   |              |    X    |
713✔
1637
                //     LEAFNODE   |  X  |                   |       X      |         |
713✔
1638
                // -------------------------------------------------------------------
713✔
1639
                // *   Not on older servers.
713✔
1640
                // **  Not if "no advertise" is enabled.
713✔
1641
                // *** Not if leafnode's "no advertise" is enabled.
713✔
1642
                //
713✔
1643
                // Reject a cluster that contains spaces.
713✔
1644
                if info.Cluster != _EMPTY_ && strings.Contains(info.Cluster, " ") {
714✔
1645
                        c.mu.Unlock()
1✔
1646
                        c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
1647
                        c.closeConnection(ProtocolViolation)
1✔
1648
                        return
1✔
1649
                }
1✔
1650
                // For solicited outbound leaf connections, capture the remote's nonce.
1651
                // For inbound leaf connections, keep using the server-issued nonce that
1652
                // was sent in our initial INFO and must be signed in CONNECT.
1653
                if didSolicit {
1,379✔
1654
                        c.nonce = []byte(info.Nonce)
667✔
1655
                }
667✔
1656
                if info.TLSRequired && didSolicit {
742✔
1657
                        remote.TLS = true
30✔
1658
                }
30✔
1659
                supportsHeaders := c.srv.supportsHeaders()
712✔
1660
                c.headers = supportsHeaders && info.Headers
712✔
1661

712✔
1662
                // Remember the remote server.
712✔
1663
                // Pre 2.2.0 servers are not sending their server name.
712✔
1664
                // In that case, use info.ID, which, for those servers, matches
712✔
1665
                // the content of the field `Name` in the leafnode CONNECT protocol.
712✔
1666
                if info.Name == _EMPTY_ {
714✔
1667
                        c.leaf.remoteServer = info.ID
2✔
1668
                } else {
712✔
1669
                        c.leaf.remoteServer = info.Name
710✔
1670
                }
710✔
1671
                c.leaf.remoteDomain = info.Domain
712✔
1672
                c.leaf.remoteCluster = info.Cluster
712✔
1673
                // We send the protocol version in the INFO protocol.
712✔
1674
                // Keep track of it, so we know if this connection supports message
712✔
1675
                // tracing for instance.
712✔
1676
                c.opts.Protocol = info.Proto
712✔
1677
        }
1678

1679
        // For both initial INFO and async INFO protocols, Possibly
1680
        // update our list of remote leafnode URLs we can connect to,
1681
        // unless we are instructed not to.
1682
        if didSolicit && !remote.IgnoreDiscoveredServers &&
1,391✔
1683
                (len(info.LeafNodeURLs) > 0 || len(info.WSConnectURLs) > 0) {
2,695✔
1684
                // Consider the incoming array as the most up-to-date
1,304✔
1685
                // representation of the remote cluster's list of URLs.
1,304✔
1686
                c.updateLeafNodeURLs(info)
1,304✔
1687
        }
1,304✔
1688

1689
        // Only solicited leafnode connections trust permission updates from INFO.
1690
        if didSolicit && (info.Import != nil || info.Export != nil) {
1,410✔
1691
                perms := &Permissions{
19✔
1692
                        Publish:   info.Export,
19✔
1693
                        Subscribe: info.Import,
19✔
1694
                }
19✔
1695
                // Check if we have local deny clauses that we need to merge.
19✔
1696
                if remote := c.leaf.remote; remote != nil {
38✔
1697
                        if len(remote.DenyExports) > 0 {
20✔
1698
                                if perms.Publish == nil {
1✔
1699
                                        perms.Publish = &SubjectPermission{}
×
1700
                                }
×
1701
                                perms.Publish.Deny = append(perms.Publish.Deny, remote.DenyExports...)
1✔
1702
                        }
1703
                        if len(remote.DenyImports) > 0 {
20✔
1704
                                if perms.Subscribe == nil {
1✔
1705
                                        perms.Subscribe = &SubjectPermission{}
×
1706
                                }
×
1707
                                perms.Subscribe.Deny = append(perms.Subscribe.Deny, remote.DenyImports...)
1✔
1708
                        }
1709
                }
1710
                c.setPermissions(perms)
19✔
1711
        }
1712

1713
        var resumeConnect bool
1,391✔
1714

1,391✔
1715
        // If this is a remote connection and this is the first INFO protocol,
1,391✔
1716
        // then we need to finish the connect process by sending CONNECT, etc..
1,391✔
1717
        if firstINFO && didSolicit {
2,058✔
1718
                // Clear deadline that was set in createLeafNode while waiting for the INFO.
667✔
1719
                c.nc.SetDeadline(time.Time{})
667✔
1720
                resumeConnect = true
667✔
1721
        } else if !firstINFO && didSolicit {
2,031✔
1722
                c.leaf.remoteAccName = info.RemoteAccount
640✔
1723
        }
640✔
1724

1725
        // Check if we have the remote account information and if so make sure it's stored.
1726
        if info.RemoteAccount != _EMPTY_ {
2,020✔
1727
                if c.acc == nil {
630✔
1728
                        c.mu.Unlock()
1✔
1729
                        c.sendErr("Authorization Violation")
1✔
1730
                        c.closeConnection(ProtocolViolation)
1✔
1731
                        return
1✔
1732
                }
1✔
1733
                s.leafRemoteAccounts.Store(c.acc.Name, info.RemoteAccount)
628✔
1734
        }
1735
        c.mu.Unlock()
1,390✔
1736

1,390✔
1737
        finishConnect := info.ConnectInfo
1,390✔
1738
        if resumeConnect && s != nil {
2,057✔
1739
                s.leafNodeResumeConnectProcess(c)
667✔
1740
                if !info.InfoOnConnect {
667✔
1741
                        finishConnect = true
×
1742
                }
×
1743
        }
1744
        if finishConnect {
2,019✔
1745
                s.leafNodeFinishConnectProcess(c)
629✔
1746
        }
629✔
1747

1748
        // Check to see if we need to kick any internal source or mirror consumers.
1749
        // This will be a no-op if JetStream not enabled for this server or if the bound account
1750
        // does not have jetstream.
1751
        s.checkInternalSyncConsumers(c.acc)
1,390✔
1752
}
1753

1754
func (s *Server) negotiateLeafCompression(c *client, didSolicit bool, infoCompression string, co *CompressionOpts) (bool, error) {
1,217✔
1755
        // If WebSocket compression is already negotiated on this connection then
1,217✔
1756
        // we shouldn't layer S2 compression on top of it.
1,217✔
1757
        c.mu.Lock()
1,217✔
1758
        if c.ws != nil && c.ws.compress {
1,223✔
1759
                c.leaf.compression = CompressionOff
6✔
1760
                c.mu.Unlock()
6✔
1761
                return false, nil
6✔
1762
        }
6✔
1763
        c.mu.Unlock()
1,211✔
1764
        // Negotiate the appropriate compression mode (or no compression)
1,211✔
1765
        cm, err := selectCompressionMode(co.Mode, infoCompression)
1,211✔
1766
        if err != nil {
1,211✔
1767
                return false, err
×
1768
        }
×
1769
        c.mu.Lock()
1,211✔
1770
        // For "auto" mode, set the initial compression mode based on RTT
1,211✔
1771
        if cm == CompressionS2Auto {
2,293✔
1772
                if c.rttStart.IsZero() {
2,164✔
1773
                        c.rtt = computeRTT(c.start)
1,082✔
1774
                }
1,082✔
1775
                cm = selectS2AutoModeBasedOnRTT(c.rtt, co.RTTThresholds)
1,082✔
1776
        }
1777
        // Keep track of the negotiated compression mode.
1778
        c.leaf.compression = cm
1,211✔
1779
        cid := c.cid
1,211✔
1780
        var nonce string
1,211✔
1781
        if !didSolicit {
1,771✔
1782
                nonce = bytesToString(c.nonce)
560✔
1783
        }
560✔
1784
        c.mu.Unlock()
1,211✔
1785

1,211✔
1786
        if !needsCompression(cm) {
1,304✔
1787
                return false, nil
93✔
1788
        }
93✔
1789

1790
        // If we end-up doing compression...
1791

1792
        // Generate an INFO with the chosen compression mode.
1793
        s.mu.Lock()
1,118✔
1794
        info := s.copyLeafNodeInfo()
1,118✔
1795
        info.Compression, info.CID, info.Nonce = compressionModeForInfoProtocol(co, cm), cid, nonce
1,118✔
1796
        infoProto := generateInfoJSON(info)
1,118✔
1797
        s.mu.Unlock()
1,118✔
1798

1,118✔
1799
        // If we solicited, then send this INFO protocol BEFORE switching
1,118✔
1800
        // to compression writer. However, if we did not, we send it after.
1,118✔
1801
        c.mu.Lock()
1,118✔
1802
        if didSolicit {
1,679✔
1803
                c.enqueueProto(infoProto)
561✔
1804
                // Make sure it is completely flushed (the pending bytes goes to
561✔
1805
                // 0) before proceeding.
561✔
1806
                for c.out.pb > 0 && !c.isClosed() {
1,121✔
1807
                        c.flushOutbound()
560✔
1808
                }
560✔
1809
        }
1810
        // This is to notify the readLoop that it should switch to a
1811
        // (de)compression reader.
1812
        c.in.flags.set(switchToCompression)
1,118✔
1813
        // Create the compress writer before queueing the INFO protocol for
1,118✔
1814
        // a route that did not solicit. It will make sure that that proto
1,118✔
1815
        // is sent with compression on.
1,118✔
1816
        c.out.cw = s2.NewWriter(nil, s2WriterOptions(cm)...)
1,118✔
1817
        if !didSolicit {
1,675✔
1818
                c.enqueueProto(infoProto)
557✔
1819
        }
557✔
1820
        c.mu.Unlock()
1,118✔
1821
        return true, nil
1,118✔
1822
}
1823

1824
// When getting a leaf node INFO protocol, use the provided
1825
// array of urls to update the list of possible endpoints.
1826
func (c *client) updateLeafNodeURLs(info *Info) {
1,304✔
1827
        cfg := c.leaf.remote
1,304✔
1828
        cfg.Lock()
1,304✔
1829
        defer cfg.Unlock()
1,304✔
1830

1,304✔
1831
        // We have ensured that if a remote has a WS scheme, then all are.
1,304✔
1832
        // So check if first is WS, then add WS URLs, otherwise, add non WS ones.
1,304✔
1833
        if len(cfg.URLs) > 0 && isWSURL(cfg.URLs[0]) {
1,370✔
1834
                // It does not really matter if we use "ws://" or "wss://" here since
66✔
1835
                // we will have already marked that the remote should use TLS anyway.
66✔
1836
                // But use proper scheme for log statements, etc...
66✔
1837
                proto := wsSchemePrefix
66✔
1838
                if cfg.TLS {
66✔
1839
                        proto = wsSchemePrefixTLS
×
1840
                }
×
1841
                c.doUpdateLNURLs(cfg, proto, info.WSConnectURLs)
66✔
1842
                return
66✔
1843
        }
1844
        c.doUpdateLNURLs(cfg, "nats-leaf", info.LeafNodeURLs)
1,238✔
1845
}
1846

1847
func (c *client) doUpdateLNURLs(cfg *leafNodeCfg, scheme string, URLs []string) {
1,304✔
1848
        cfg.urls = make([]*url.URL, 0, 1+len(URLs))
1,304✔
1849
        // Add the ones we receive in the protocol
1,304✔
1850
        for _, surl := range URLs {
3,551✔
1851
                url, err := url.Parse(fmt.Sprintf("%s://%s", scheme, surl))
2,247✔
1852
                if err != nil {
2,247✔
1853
                        // As per below, the URLs we receive should not have contained URL info, so this should be safe to log.
×
1854
                        c.Errorf("Error parsing url %q: %v", surl, err)
×
1855
                        continue
×
1856
                }
1857
                // Do not add if it's the same as what we already have configured.
1858
                var dup bool
2,247✔
1859
                for _, u := range cfg.URLs {
5,634✔
1860
                        // URLs that we receive never have user info, but the
3,387✔
1861
                        // ones that were configured may have. Simply compare
3,387✔
1862
                        // host and port to decide if they are equal or not.
3,387✔
1863
                        if url.Host == u.Host && url.Port() == u.Port() {
5,016✔
1864
                                dup = true
1,629✔
1865
                                break
1,629✔
1866
                        }
1867
                }
1868
                if !dup {
2,865✔
1869
                        cfg.urls = append(cfg.urls, url)
618✔
1870
                        cfg.saveTLSHostname(url)
618✔
1871
                }
618✔
1872
        }
1873
        // Add the configured one
1874
        cfg.urls = append(cfg.urls, cfg.URLs...)
1,304✔
1875
}
1876

1877
// Similar to setInfoHostPortAndGenerateJSON, but for leafNodeInfo.
1878
func (s *Server) setLeafNodeInfoHostPortAndIP() error {
4,051✔
1879
        opts := s.getOpts()
4,051✔
1880
        if opts.LeafNode.Advertise != _EMPTY_ {
4,062✔
1881
                advHost, advPort, err := parseHostPort(opts.LeafNode.Advertise, opts.LeafNode.Port)
11✔
1882
                if err != nil {
11✔
1883
                        return err
×
1884
                }
×
1885
                s.leafNodeInfo.Host = advHost
11✔
1886
                s.leafNodeInfo.Port = advPort
11✔
1887
        } else {
4,040✔
1888
                s.leafNodeInfo.Host = opts.LeafNode.Host
4,040✔
1889
                s.leafNodeInfo.Port = opts.LeafNode.Port
4,040✔
1890
                // If the host is "0.0.0.0" or "::" we need to resolve to a public IP.
4,040✔
1891
                // This will return at most 1 IP.
4,040✔
1892
                hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(s.leafNodeInfo.Host, false)
4,040✔
1893
                if err != nil {
4,040✔
1894
                        return err
×
1895
                }
×
1896
                if hostIsIPAny {
4,339✔
1897
                        if len(ips) == 0 {
299✔
1898
                                s.Errorf("Could not find any non-local IP for leafnode's listen specification %q",
×
1899
                                        s.leafNodeInfo.Host)
×
1900
                        } else {
299✔
1901
                                // Take the first from the list...
299✔
1902
                                s.leafNodeInfo.Host = ips[0]
299✔
1903
                        }
299✔
1904
                }
1905
        }
1906
        // Use just host:port for the IP
1907
        s.leafNodeInfo.IP = net.JoinHostPort(s.leafNodeInfo.Host, strconv.Itoa(s.leafNodeInfo.Port))
4,051✔
1908
        if opts.LeafNode.Advertise != _EMPTY_ {
4,062✔
1909
                s.Noticef("Advertise address for leafnode is set to %s", s.leafNodeInfo.IP)
11✔
1910
        }
11✔
1911
        return nil
4,051✔
1912
}
1913

1914
// Add the connection to the map of leaf nodes.
1915
// If `checkForDup` is true (invoked when a leafnode is accepted), then we check
1916
// if a connection already exists for the same server name and account.
1917
// That can happen when the remote is attempting to reconnect while the accepting
1918
// side did not detect the connection as broken yet.
1919
// But it can also happen when there is a misconfiguration and the remote is
1920
// creating two (or more) connections that bind to the same account on the accept
1921
// side.
1922
// When a duplicate is found, the new connection is accepted and the old is closed
1923
// (this solves the stale connection situation). An error is returned to help the
1924
// remote detect the misconfiguration when the duplicate is the result of that
1925
// misconfiguration.
1926
func (s *Server) addLeafNodeConnection(c *client, srvName, clusterName string, checkForDup bool) bool {
1,297✔
1927
        var accName string
1,297✔
1928
        c.mu.Lock()
1,297✔
1929
        cid := c.cid
1,297✔
1930
        acc := c.acc
1,297✔
1931
        if acc != nil {
2,594✔
1932
                accName = acc.Name
1,297✔
1933
        }
1,297✔
1934
        myRemoteDomain := c.leaf.remoteDomain
1,297✔
1935
        mySrvName := c.leaf.remoteServer
1,297✔
1936
        remoteAccName := c.leaf.remoteAccName
1,297✔
1937
        myClustName := c.leaf.remoteCluster
1,297✔
1938
        remote := c.leaf.remote
1,297✔
1939
        solicited := remote != nil
1,297✔
1940
        c.mu.Unlock()
1,297✔
1941

1,297✔
1942
        var old *client
1,297✔
1943
        s.mu.Lock()
1,297✔
1944
        // We check for empty because in some test we may send empty CONNECT{}
1,297✔
1945
        if checkForDup && srvName != _EMPTY_ {
1,930✔
1946
                for _, ol := range s.leafs {
1,035✔
1947
                        ol.mu.Lock()
402✔
1948
                        // We care here only about non solicited Leafnode. This function
402✔
1949
                        // is more about replacing stale connections than detecting loops.
402✔
1950
                        // We have code for the loop detection elsewhere, which also delays
402✔
1951
                        // attempt to reconnect.
402✔
1952
                        if !ol.isSolicitedLeafNode() && ol.leaf.remoteServer == srvName &&
402✔
1953
                                ol.leaf.remoteCluster == clusterName && ol.acc.Name == accName &&
402✔
1954
                                remoteAccName != _EMPTY_ && ol.leaf.remoteAccName == remoteAccName {
404✔
1955
                                old = ol
2✔
1956
                        }
2✔
1957
                        ol.mu.Unlock()
402✔
1958
                        if old != nil {
404✔
1959
                                break
2✔
1960
                        }
1961
                }
1962
        }
1963
        // Now that we are under the server lock and before adding it to the map,
1964
        // for a solicited leaf, we need to make sure that it has not been removed
1965
        // from the config or disabled.
1966
        if solicited {
1,922✔
1967
                // If no longer valid, do not add to the server map. The connection
625✔
1968
                // should have been marked so that it can't reconnect. When the caller
625✔
1969
                // calls closeConnection(), cleanup (including clearing the connect-
625✔
1970
                // in-progress flag) will occur at the appropriate time.
625✔
1971
                if !remote.stillValid() {
625✔
1972
                        // Prevent reconnect in case it was not yet done.
×
1973
                        c.setNoReconnect()
×
1974
                        s.mu.Unlock()
×
1975
                        s.removeFromTempClients(cid)
×
1976
                        return false
×
1977
                }
×
1978
                remote.setConnectInProgress(false)
625✔
1979
        }
1980
        // Store new connection in the map
1981
        s.leafs[cid] = c
1,297✔
1982
        s.mu.Unlock()
1,297✔
1983
        s.removeFromTempClients(cid)
1,297✔
1984

1,297✔
1985
        // If applicable, evict the old one.
1,297✔
1986
        if old != nil {
1,299✔
1987
                old.sendErrAndErr(DuplicateRemoteLeafnodeConnection.String())
2✔
1988
                old.closeConnection(DuplicateRemoteLeafnodeConnection)
2✔
1989
                c.Warnf("Replacing connection from same server")
2✔
1990
        }
2✔
1991

1992
        srvDecorated := func() string {
1,494✔
1993
                if myClustName == _EMPTY_ {
223✔
1994
                        return mySrvName
26✔
1995
                }
26✔
1996
                return fmt.Sprintf("%s/%s", mySrvName, myClustName)
171✔
1997
        }
1998

1999
        opts := s.getOpts()
1,297✔
2000
        sysAcc := s.SystemAccount()
1,297✔
2001
        js := s.getJetStream()
1,297✔
2002
        var meta *raft
1,297✔
2003
        if js != nil {
1,819✔
2004
                if mg := js.getMetaGroup(); mg != nil {
925✔
2005
                        meta = mg.(*raft)
403✔
2006
                }
403✔
2007
        }
2008
        blockMappingOutgoing := false
1,297✔
2009
        // Deny (non domain) JetStream API traffic unless system account is shared
1,297✔
2010
        // and domain names are identical and extending is not disabled
1,297✔
2011

1,297✔
2012
        // Check if backwards compatibility has been enabled and needs to be acted on
1,297✔
2013
        forceSysAccDeny := false
1,297✔
2014
        if len(opts.JsAccDefaultDomain) > 0 {
1,331✔
2015
                if acc == sysAcc {
45✔
2016
                        for _, d := range opts.JsAccDefaultDomain {
22✔
2017
                                if d == _EMPTY_ {
19✔
2018
                                        // Extending JetStream via leaf node is mutually exclusive with a domain mapping to the empty/default domain.
8✔
2019
                                        // As soon as one mapping to "" is found, disable the ability to extend JS via a leaf node.
8✔
2020
                                        c.Noticef("Not extending remote JetStream domain %q due to presence of empty default domain", myRemoteDomain)
8✔
2021
                                        forceSysAccDeny = true
8✔
2022
                                        break
8✔
2023
                                }
2024
                        }
2025
                } else if domain, ok := opts.JsAccDefaultDomain[accName]; ok && domain == _EMPTY_ {
37✔
2026
                        // for backwards compatibility with old setups that do not have a domain name set
14✔
2027
                        c.Debugf("Skipping deny %q for account %q due to default domain", jsAllAPI, accName)
14✔
2028
                        return true
14✔
2029
                }
14✔
2030
        }
2031

2032
        // If the server has JS disabled, it may still be part of a JetStream that could be extended.
2033
        // This is either signaled by js being disabled and a domain set,
2034
        // or in cases where no domain name exists, an extension hint is set.
2035
        // However, this is only relevant in mixed setups.
2036
        //
2037
        // If the system account connects but default domains are present, JetStream can't be extended.
2038
        if opts.JetStreamDomain != myRemoteDomain || (!opts.JetStream && (opts.JetStreamDomain == _EMPTY_ && opts.JetStreamExtHint != jsWillExtend)) ||
1,283✔
2039
                sysAcc == nil || acc == nil || forceSysAccDeny {
2,420✔
2040
                // If domain names mismatch always deny. This applies to system accounts as well as non system accounts.
1,137✔
2041
                // Not having a system account, account or JetStream disabled is considered a mismatch as well.
1,137✔
2042
                if acc != nil && acc == sysAcc {
1,268✔
2043
                        c.Noticef("System account connected from %s", srvDecorated())
131✔
2044
                        c.Noticef("JetStream not extended, domains differ")
131✔
2045
                        c.mergeDenyPermissionsLocked(both, denyAllJs)
131✔
2046
                        // When a remote with a system account is present in a server, unless otherwise disabled, the server will be
131✔
2047
                        // started in observer mode. Now that it is clear that this not used, turn the observer mode off.
131✔
2048
                        if solicited && meta != nil && meta.IsObserver() {
157✔
2049
                                meta.setObserver(false, extNotExtended)
26✔
2050
                                c.Debugf("Turning JetStream metadata controller Observer Mode off")
26✔
2051
                                // Take note that the domain was not extended to avoid this state from startup.
26✔
2052
                                writePeerState(js.config.StoreDir, meta.currentPeerState())
26✔
2053
                                // Meta controller can't be leader yet.
26✔
2054
                                // Yet it is possible that due to observer mode every server already stopped campaigning.
26✔
2055
                                // Therefore this server needs to be kicked into campaigning gear explicitly.
26✔
2056
                                meta.Campaign()
26✔
2057
                        }
26✔
2058
                } else {
1,006✔
2059
                        c.Noticef("JetStream using domains: local %q, remote %q", opts.JetStreamDomain, myRemoteDomain)
1,006✔
2060
                        c.mergeDenyPermissionsLocked(both, denyAllClientJs)
1,006✔
2061
                }
1,006✔
2062
                blockMappingOutgoing = true
1,137✔
2063
        } else if acc == sysAcc {
212✔
2064
                // system account and same domain
66✔
2065
                s.sys.client.Noticef("Extending JetStream domain %q as System Account connected from server %s",
66✔
2066
                        myRemoteDomain, srvDecorated())
66✔
2067
                // In an extension use case, pin leadership to server remotes connect to.
66✔
2068
                // Therefore, server with a remote that are not already in observer mode, need to be put into it.
66✔
2069
                if solicited && meta != nil && !meta.IsObserver() {
70✔
2070
                        c.Debugf("Turning JetStream metadata controller Observer Mode on - System Account Connected")
4✔
2071
                        // Discard any local metagroup state accumulated before the SYS-account
4✔
2072
                        // leaf came up (e.g. the wrong-hint case where this server bootstrapped
4✔
2073
                        // its own metagroup). The parent's view is now authoritative; without
4✔
2074
                        // this reset the two raft logs stay forked because the standalone log's
4✔
2075
                        // commit prefix short-circuits the follower's AE handling.
4✔
2076
                        meta.setObserver(true, extExtended)
4✔
2077
                        meta.Reset()
4✔
2078
                }
4✔
2079
        } else {
80✔
2080
                // This deny is needed in all cases (system account shared or not)
80✔
2081
                // If the system account is shared, jsAllAPI traffic will go through the system account.
80✔
2082
                // So in order to prevent duplicate delivery (from system and actual account) suppress it on the account.
80✔
2083
                // If the system account is NOT shared, jsAllAPI traffic has no business
80✔
2084
                c.Debugf("Adding deny %+v for account %q", denyAllClientJs, accName)
80✔
2085
                c.mergeDenyPermissionsLocked(both, denyAllClientJs)
80✔
2086
        }
80✔
2087
        // If we have a specified JetStream domain we will want to add a mapping to
2088
        // allow access cross domain for each non-system account.
2089
        if opts.JetStreamDomain != _EMPTY_ && opts.JetStream && acc != nil && acc != sysAcc {
1,537✔
2090
                for src, dest := range generateJSMappingTable(opts.JetStreamDomain) {
2,540✔
2091
                        if err := acc.AddMapping(src, dest); err != nil {
2,286✔
2092
                                c.Debugf("Error adding JetStream domain mapping: %s", err.Error())
×
2093
                        } else {
2,286✔
2094
                                c.Debugf("Adding JetStream Domain Mapping %q -> %s to account %q", src, dest, accName)
2,286✔
2095
                        }
2,286✔
2096
                }
2097
                if blockMappingOutgoing {
477✔
2098
                        src := fmt.Sprintf(jsDomainAPI, opts.JetStreamDomain)
223✔
2099
                        // make sure that messages intended for this domain, do not leave the cluster via this leaf node connection
223✔
2100
                        // This is a guard against a miss-config with two identical domain names and will only cover some forms
223✔
2101
                        // of this issue, not all of them.
223✔
2102
                        // This guards against a hub and a spoke having the same domain name.
223✔
2103
                        // But not two spokes having the same one and the request coming from the hub.
223✔
2104
                        c.mergeDenyPermissionsLocked(pub, []string{src})
223✔
2105
                        c.Debugf("Adding deny %q for outgoing messages to account %q", src, accName)
223✔
2106
                }
223✔
2107
        }
2108
        return true
1,283✔
2109
}
2110

2111
func (s *Server) removeLeafNodeConnection(c *client) {
1,689✔
2112
        s.mu.Lock()
1,689✔
2113
        c.mu.Lock()
1,689✔
2114
        cid := c.cid
1,689✔
2115
        if c.leaf != nil {
3,377✔
2116
                if c.leaf.tsubt != nil {
2,866✔
2117
                        c.leaf.tsubt.Stop()
1,178✔
2118
                        c.leaf.tsubt = nil
1,178✔
2119
                }
1,178✔
2120
                if c.leaf.gwSub != nil {
2,313✔
2121
                        s.gwLeafSubs.Remove(c.leaf.gwSub)
625✔
2122
                        // We need to set this to nil for GC to release the connection
625✔
2123
                        c.leaf.gwSub = nil
625✔
2124
                }
625✔
2125
                if remote := c.leaf.remote; remote != nil {
2,488✔
2126
                        // If "noReconnect" is true, then we won't attempt to reconnect, so
800✔
2127
                        // we will clear the "connect-in-progress" flag. However, if we can
800✔
2128
                        // reconnect, then we should set "connect-in-progress" to true while
800✔
2129
                        // we are under the server/client lock. The go routine that performs
800✔
2130
                        // the reconnect will be started later and there would be a gap with
800✔
2131
                        // the wrong flag value otherwise.
800✔
2132
                        remote.setConnectInProgress(!c.flags.isSet(noReconnect))
800✔
2133
                }
800✔
2134
        }
2135
        proxyKey := c.proxyKey
1,689✔
2136
        c.mu.Unlock()
1,689✔
2137
        delete(s.leafs, cid)
1,689✔
2138
        if proxyKey != _EMPTY_ {
1,693✔
2139
                s.removeProxiedConn(proxyKey, cid)
4✔
2140
        }
4✔
2141
        s.mu.Unlock()
1,689✔
2142
        s.removeFromTempClients(cid)
1,689✔
2143
}
2144

2145
// Connect information for solicited leafnodes.
2146
type leafConnectInfo struct {
2147
        Version   string   `json:"version,omitempty"`
2148
        Nkey      string   `json:"nkey,omitempty"`
2149
        JWT       string   `json:"jwt,omitempty"`
2150
        Sig       string   `json:"sig,omitempty"`
2151
        User      string   `json:"user,omitempty"`
2152
        Pass      string   `json:"pass,omitempty"`
2153
        Token     string   `json:"auth_token,omitempty"`
2154
        ID        string   `json:"server_id,omitempty"`
2155
        Domain    string   `json:"domain,omitempty"`
2156
        Name      string   `json:"name,omitempty"`
2157
        Hub       bool     `json:"is_hub,omitempty"`
2158
        Cluster   string   `json:"cluster,omitempty"`
2159
        Headers   bool     `json:"headers,omitempty"`
2160
        JetStream bool     `json:"jetstream,omitempty"`
2161
        DenyPub   []string `json:"deny_pub,omitempty"`
2162
        Isolate   bool     `json:"isolate,omitempty"`
2163

2164
        // There was an existing field called:
2165
        // >> Comp bool `json:"compression,omitempty"`
2166
        // that has never been used. With support for compression, we now need
2167
        // a field that is a string. So we use a different json tag:
2168
        Compression string `json:"compress_mode,omitempty"`
2169

2170
        // Just used to detect wrong connection attempts.
2171
        Gateway string `json:"gateway,omitempty"`
2172

2173
        // Tells the accept side which account the remote is binding to.
2174
        RemoteAccount string `json:"remote_account,omitempty"`
2175

2176
        // The accept side of a LEAF connection, unlike ROUTER and GATEWAY, receives
2177
        // only the CONNECT protocol, and no INFO. So we need to send the protocol
2178
        // version as part of the CONNECT. It will indicate if a connection supports
2179
        // some features, such as message tracing.
2180
        // We use `protocol` as the JSON tag, so this is automatically unmarshal'ed
2181
        // in the low level process CONNECT.
2182
        Proto int `json:"protocol,omitempty"`
2183
}
2184

2185
// processLeafNodeConnect will process the inbound connect args.
2186
// Once we are here we are bound to an account, so can send any interest that
2187
// we would have to the other side.
2188
func (c *client) processLeafNodeConnect(s *Server, arg []byte, lang string) error {
682✔
2189
        // Way to detect clients that incorrectly connect to the route listen
682✔
2190
        // port. Client provided "lang" in the CONNECT protocol while LEAFNODEs don't.
682✔
2191
        if lang != _EMPTY_ {
687✔
2192
                c.sendErrAndErr(ErrClientConnectedToLeafNodePort.Error())
5✔
2193
                c.closeConnection(WrongPort)
5✔
2194
                return ErrClientConnectedToLeafNodePort
5✔
2195
        }
5✔
2196

2197
        // Unmarshal as a leaf node connect protocol
2198
        proto := &leafConnectInfo{}
677✔
2199
        if err := json.Unmarshal(arg, proto); err != nil {
677✔
2200
                return err
×
2201
        }
×
2202

2203
        // Reject a cluster that contains spaces.
2204
        if proto.Cluster != _EMPTY_ && strings.Contains(proto.Cluster, " ") {
678✔
2205
                c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
2206
                c.closeConnection(ProtocolViolation)
1✔
2207
                return ErrClusterNameHasSpaces
1✔
2208
        }
1✔
2209

2210
        // Check for cluster name collisions.
2211
        if cn := s.cachedClusterName(); cn != _EMPTY_ && proto.Cluster != _EMPTY_ && proto.Cluster == cn {
679✔
2212
                c.sendErrAndErr(ErrLeafNodeHasSameClusterName.Error())
3✔
2213
                c.closeConnection(ClusterNamesIdentical)
3✔
2214
                return ErrLeafNodeHasSameClusterName
3✔
2215
        }
3✔
2216

2217
        // Reject if this has Gateway which means that it would be from a gateway
2218
        // connection that incorrectly connects to the leafnode port.
2219
        if proto.Gateway != _EMPTY_ {
673✔
2220
                errTxt := fmt.Sprintf("Rejecting connection from gateway %q on the leafnode port", proto.Gateway)
×
2221
                c.Errorf(errTxt)
×
2222
                c.sendErr(errTxt)
×
2223
                c.closeConnection(WrongGateway)
×
2224
                return ErrWrongGateway
×
2225
        }
×
2226

2227
        if mv := s.getOpts().LeafNode.MinVersion; mv != _EMPTY_ {
675✔
2228
                major, minor, update, _ := versionComponents(mv)
2✔
2229
                if !versionAtLeast(proto.Version, major, minor, update) {
3✔
2230
                        // Send back an INFO so recent remote servers process the rejection
1✔
2231
                        // cleanly, then close immediately. The soliciting side applies the
1✔
2232
                        // reconnect delay when it processes the error.
1✔
2233
                        s.sendPermsAndAccountInfo(c)
1✔
2234
                        c.sendErrAndErr(fmt.Sprintf("%s %q", ErrLeafNodeMinVersionRejected, mv))
1✔
2235
                        c.closeConnection(MinimumVersionRequired)
1✔
2236
                        return ErrMinimumVersionRequired
1✔
2237
                }
1✔
2238
        }
2239

2240
        // Check if this server supports headers.
2241
        supportHeaders := c.srv.supportsHeaders()
672✔
2242

672✔
2243
        c.mu.Lock()
672✔
2244
        // Leaf Nodes do not do echo or verbose or pedantic.
672✔
2245
        c.opts.Verbose = false
672✔
2246
        c.opts.Echo = false
672✔
2247
        c.opts.Pedantic = false
672✔
2248
        // This inbound connection will be marked as supporting headers if this server
672✔
2249
        // support headers and the remote has sent in the CONNECT protocol that it does
672✔
2250
        // support headers too.
672✔
2251
        c.headers = supportHeaders && proto.Headers
672✔
2252
        // If the compression level is still not set, set it based on what has been
672✔
2253
        // given to us in the CONNECT protocol.
672✔
2254
        if c.leaf.compression == _EMPTY_ {
816✔
2255
                // But if proto.Compression is _EMPTY_, set it to CompressionNotSupported
144✔
2256
                if proto.Compression == _EMPTY_ {
186✔
2257
                        c.leaf.compression = CompressionNotSupported
42✔
2258
                } else {
144✔
2259
                        c.leaf.compression = proto.Compression
102✔
2260
                }
102✔
2261
        }
2262

2263
        // Remember the remote server.
2264
        c.leaf.remoteServer = proto.Name
672✔
2265
        // Remember the remote account name
672✔
2266
        c.leaf.remoteAccName = proto.RemoteAccount
672✔
2267
        // Remember if the leafnode requested isolation.
672✔
2268
        c.leaf.isolated = c.leaf.isolated || proto.Isolate
672✔
2269

672✔
2270
        // If the other side has declared itself a hub, so we will take on the spoke role.
672✔
2271
        if proto.Hub {
690✔
2272
                c.leaf.isSpoke = true
18✔
2273
        }
18✔
2274

2275
        // The soliciting side is part of a cluster.
2276
        if proto.Cluster != _EMPTY_ {
1,179✔
2277
                c.leaf.remoteCluster = proto.Cluster
507✔
2278
        }
507✔
2279

2280
        c.leaf.remoteDomain = proto.Domain
672✔
2281

672✔
2282
        // When a leaf solicits a connection to a hub, the perms that it will use on the soliciting leafnode's
672✔
2283
        // behalf are correct for them, but inside the hub need to be reversed since data is flowing in the opposite direction.
672✔
2284
        if !c.isSolicitedLeafNode() && c.perms != nil {
694✔
2285
                sp, pp := c.perms.sub, c.perms.pub
22✔
2286
                c.perms.sub, c.perms.pub = pp, sp
22✔
2287
                if c.opts.Import != nil {
43✔
2288
                        c.darray = c.opts.Import.Deny
21✔
2289
                } else {
22✔
2290
                        c.darray = nil
1✔
2291
                }
1✔
2292
        }
2293

2294
        // Set the Ping timer
2295
        c.setFirstPingTimer()
672✔
2296

672✔
2297
        // If we received pub deny permissions from the other end, merge with existing ones.
672✔
2298
        c.mergeDenyPermissions(pub, proto.DenyPub)
672✔
2299

672✔
2300
        acc := c.acc
672✔
2301
        c.mu.Unlock()
672✔
2302

672✔
2303
        // If the account is not set (e.g. connection was closed due to auth
672✔
2304
        // timeout while still being processed), bail out to avoid a panic.
672✔
2305
        if acc == nil {
672✔
2306
                c.closeConnection(MissingAccount)
×
2307
                return ErrMissingAccount
×
2308
        }
×
2309

2310
        // Register the cluster, even if empty, as long as we are acting as a hub.
2311
        if !proto.Hub {
1,326✔
2312
                acc.registerLeafNodeCluster(proto.Cluster)
654✔
2313
        }
654✔
2314

2315
        // Add in the leafnode here since we passed through auth at this point.
2316
        s.addLeafNodeConnection(c, proto.Name, proto.Cluster, true)
672✔
2317

672✔
2318
        // If we have permissions bound to this leafnode we need to send then back to the
672✔
2319
        // origin server for local enforcement.
672✔
2320
        s.sendPermsAndAccountInfo(c)
672✔
2321

672✔
2322
        // Create and initialize the smap since we know our bound account now.
672✔
2323
        // This will send all registered subs too.
672✔
2324
        s.initLeafNodeSmapAndSendSubs(c)
672✔
2325

672✔
2326
        // Announce the account connect event for a leaf node.
672✔
2327
        // This will be a no-op as needed.
672✔
2328
        s.sendLeafNodeConnect(c.acc)
672✔
2329

672✔
2330
        // Check to see if we need to kick any internal source or mirror consumers.
672✔
2331
        // This will be a no-op if JetStream not enabled for this server or if the bound account
672✔
2332
        // does not have jetstream.
672✔
2333
        s.checkInternalSyncConsumers(acc)
672✔
2334

672✔
2335
        return nil
672✔
2336
}
2337

2338
// checkInternalSyncConsumers
2339
func (s *Server) checkInternalSyncConsumers(acc *Account) {
2,062✔
2340
        // Grab our js
2,062✔
2341
        js := s.getJetStream()
2,062✔
2342

2,062✔
2343
        // Only applicable if we have JS and the leafnode has JS as well.
2,062✔
2344
        // We check for remote JS outside.
2,062✔
2345
        if !js.isEnabled() || acc == nil {
3,259✔
2346
                return
1,197✔
2347
        }
1,197✔
2348

2349
        // We will check all streams in our local account. They must be a leader and
2350
        // be sourcing or mirroring. We will check the external config on the stream itself
2351
        // if this is cross domain, or if the remote domain is empty, meaning we might be
2352
        // extending the system across this leafnode connection and hence we would be extending
2353
        // our own domain.
2354
        jsa := js.lookupAccount(acc)
865✔
2355
        if jsa == nil {
1,182✔
2356
                return
317✔
2357
        }
317✔
2358

2359
        var streams []*stream
548✔
2360
        jsa.mu.RLock()
548✔
2361
        for _, mset := range jsa.streams {
620✔
2362
                mset.cfgMu.RLock()
72✔
2363
                // We need to have a mirror or source defined.
72✔
2364
                // We do not want to force another lock here to look for leader status,
72✔
2365
                // so collect and after we release jsa will make sure.
72✔
2366
                if mset.cfg.Mirror != nil || len(mset.cfg.Sources) > 0 {
85✔
2367
                        streams = append(streams, mset)
13✔
2368
                }
13✔
2369
                mset.cfgMu.RUnlock()
72✔
2370
        }
2371
        jsa.mu.RUnlock()
548✔
2372

548✔
2373
        // Now loop through all candidates and check if we are the leader and have NOT
548✔
2374
        // created the sync up consumer.
548✔
2375
        for _, mset := range streams {
561✔
2376
                mset.retryDisconnectedSyncConsumers()
13✔
2377
        }
13✔
2378
}
2379

2380
// Returns the remote cluster name. This is set only once so does not require a lock.
2381
func (c *client) remoteCluster() string {
145,074✔
2382
        if c.leaf == nil {
145,074✔
2383
                return _EMPTY_
×
2384
        }
×
2385
        return c.leaf.remoteCluster
145,074✔
2386
}
2387

2388
// Sends back an info block to the soliciting leafnode to let it know about
2389
// its permission settings for local enforcement.
2390
func (s *Server) sendPermsAndAccountInfo(c *client) {
673✔
2391
        // Copy
673✔
2392
        s.mu.Lock()
673✔
2393
        info := s.copyLeafNodeInfo()
673✔
2394
        s.mu.Unlock()
673✔
2395
        c.mu.Lock()
673✔
2396
        info.CID = c.cid
673✔
2397
        info.Import = c.opts.Import
673✔
2398
        info.Export = c.opts.Export
673✔
2399
        info.RemoteAccount = c.acc.Name
673✔
2400
        // s.SystemAccount() uses an atomic operation and does not get the server lock, so this is safe.
673✔
2401
        info.IsSystemAccount = c.acc == s.SystemAccount()
673✔
2402
        info.ConnectInfo = true
673✔
2403
        c.enqueueProto(generateInfoJSON(info))
673✔
2404
        c.mu.Unlock()
673✔
2405
}
673✔
2406

2407
// Snapshot the current subscriptions from the sublist into our smap which
2408
// we will keep updated from now on.
2409
// Also send the registered subscriptions.
2410
func (s *Server) initLeafNodeSmapAndSendSubs(c *client) {
1,297✔
2411
        acc := c.acc
1,297✔
2412
        if acc == nil {
1,297✔
2413
                c.Debugf("Leafnode does not have an account bound")
×
2414
                return
×
2415
        }
×
2416
        // Collect all account subs here.
2417
        _subs := [1024]*subscription{}
1,297✔
2418
        subs := _subs[:0]
1,297✔
2419
        ims := []string{}
1,297✔
2420

1,297✔
2421
        // Hold the client lock otherwise there can be a race and miss some subs.
1,297✔
2422
        c.mu.Lock()
1,297✔
2423
        defer c.mu.Unlock()
1,297✔
2424

1,297✔
2425
        acc.mu.RLock()
1,297✔
2426
        accName := acc.Name
1,297✔
2427
        accNTag := acc.nameTag
1,297✔
2428

1,297✔
2429
        // To make printing look better when no friendly name present.
1,297✔
2430
        if accNTag != _EMPTY_ {
1,309✔
2431
                accNTag = "/" + accNTag
12✔
2432
        }
12✔
2433

2434
        // If we are solicited we only send interest for local clients.
2435
        if c.isSpokeLeafNode() {
1,922✔
2436
                acc.sl.localSubs(&subs, true)
625✔
2437
        } else {
1,297✔
2438
                acc.sl.All(&subs)
672✔
2439
        }
672✔
2440

2441
        // Check if we have an existing service import reply.
2442
        siReply := copyBytes(acc.siReply)
1,297✔
2443

1,297✔
2444
        // Since leaf nodes only send on interest, if the bound
1,297✔
2445
        // account has import services we need to send those over.
1,297✔
2446
        for isubj := range acc.imports.services {
6,164✔
2447
                if c.isSpokeLeafNode() && !c.canSubscribe(isubj) {
5,161✔
2448
                        c.Debugf("Not permitted to import service %q on behalf of %s%s", isubj, accName, accNTag)
294✔
2449
                        continue
294✔
2450
                }
2451
                ims = append(ims, isubj)
4,573✔
2452
        }
2453
        // Likewise for mappings.
2454
        for _, m := range acc.mappings {
3,676✔
2455
                if c.isSpokeLeafNode() && !c.canSubscribe(m.src) {
2,397✔
2456
                        c.Debugf("Not permitted to import mapping %q on behalf of %s%s", m.src, accName, accNTag)
18✔
2457
                        continue
18✔
2458
                }
2459
                ims = append(ims, m.src)
2,361✔
2460
        }
2461

2462
        // Create a unique subject that will be used for loop detection.
2463
        lds := acc.lds
1,297✔
2464
        acc.mu.RUnlock()
1,297✔
2465

1,297✔
2466
        // Check if we have to create the LDS.
1,297✔
2467
        if lds == _EMPTY_ {
2,311✔
2468
                lds = leafNodeLoopDetectionSubjectPrefix + nuid.Next()
1,014✔
2469
                acc.mu.Lock()
1,014✔
2470
                acc.lds = lds
1,014✔
2471
                acc.mu.Unlock()
1,014✔
2472
        }
1,014✔
2473

2474
        // Now check for gateway interest. Leafnodes will put this into
2475
        // the proper mode to propagate, but they are not held in the account.
2476
        gwsa := [16]*client{}
1,297✔
2477
        gws := gwsa[:0]
1,297✔
2478
        s.getOutboundGatewayConnections(&gws)
1,297✔
2479
        for _, cgw := range gws {
1,372✔
2480
                cgw.mu.Lock()
75✔
2481
                gw := cgw.gw
75✔
2482
                cgw.mu.Unlock()
75✔
2483
                if gw != nil {
150✔
2484
                        if ei, _ := gw.outsim.Load(accName); ei != nil {
150✔
2485
                                if e := ei.(*outsie); e != nil && e.sl != nil {
150✔
2486
                                        e.sl.All(&subs)
75✔
2487
                                }
75✔
2488
                        }
2489
                }
2490
        }
2491

2492
        applyGlobalRouting := s.gateway.enabled
1,297✔
2493
        if c.isSpokeLeafNode() {
1,922✔
2494
                // Add a fake subscription for this solicited leafnode connection
625✔
2495
                // so that we can send back directly for mapped GW replies.
625✔
2496
                // We need to keep track of this subscription so it can be removed
625✔
2497
                // when the connection is closed so that the GC can release it.
625✔
2498
                c.leaf.gwSub = &subscription{client: c, subject: []byte(gwReplyPrefix + ">")}
625✔
2499
                c.srv.gwLeafSubs.Insert(c.leaf.gwSub)
625✔
2500
        }
625✔
2501

2502
        // Now walk the results and add them to our smap
2503
        rc := c.leaf.remoteCluster
1,297✔
2504
        c.leaf.smap = make(map[string]int32)
1,297✔
2505
        for _, sub := range subs {
37,023✔
2506
                // Check perms regardless of role.
35,726✔
2507
                if c.perms != nil && !c.canSubscribe(string(sub.subject)) {
37,987✔
2508
                        c.Debugf("Not permitted to subscribe to %q on behalf of %s%s", sub.subject, accName, accNTag)
2,261✔
2509
                        continue
2,261✔
2510
                }
2511
                // Don't advertise interest from leafnodes to other isolated leafnodes.
2512
                if sub.client.kind == LEAF && c.isIsolatedLeafNode() {
33,480✔
2513
                        continue
15✔
2514
                }
2515
                // We ignore ourselves here.
2516
                // Also don't add the subscription if it has a origin cluster and the
2517
                // cluster name matches the one of the client we are sending to.
2518
                if c != sub.client && (sub.origin == nil || (bytesToString(sub.origin) != rc)) {
61,886✔
2519
                        count := int32(1)
28,436✔
2520
                        if len(sub.queue) > 0 && sub.qw > 0 {
28,448✔
2521
                                count = sub.qw
12✔
2522
                        }
12✔
2523
                        c.leaf.smap[keyFromSub(sub)] += count
28,436✔
2524
                        if c.leaf.tsub == nil {
29,650✔
2525
                                c.leaf.tsub = make(map[*subscription]struct{})
1,214✔
2526
                        }
1,214✔
2527
                        c.leaf.tsub[sub] = struct{}{}
28,436✔
2528
                }
2529
        }
2530
        // FIXME(dlc) - We need to update appropriately on an account claims update.
2531
        for _, isubj := range ims {
8,231✔
2532
                c.leaf.smap[isubj]++
6,934✔
2533
        }
6,934✔
2534
        // If we have gateways enabled we need to make sure the other side sends us responses
2535
        // that have been augmented from the original subscription.
2536
        // TODO(dlc) - Should we lock this down more?
2537
        if applyGlobalRouting {
1,392✔
2538
                c.leaf.smap[oldGWReplyPrefix+"*.>"]++
95✔
2539
                c.leaf.smap[gwReplyPrefix+">"]++
95✔
2540
        }
95✔
2541
        // Detect loops by subscribing to a specific subject and checking
2542
        // if this sub is coming back to us.
2543
        c.leaf.smap[lds]++
1,297✔
2544

1,297✔
2545
        // Check if we need to add an existing siReply to our map.
1,297✔
2546
        // This will be a prefix so add on the wildcard.
1,297✔
2547
        if siReply != nil {
1,312✔
2548
                wcsub := append(siReply, '>')
15✔
2549
                c.leaf.smap[string(wcsub)]++
15✔
2550
        }
15✔
2551
        // Queue all protocols. There is no max pending limit for LN connection,
2552
        // so we don't need chunking. The writes will happen from the writeLoop.
2553
        var b bytes.Buffer
1,297✔
2554
        for key, n := range c.leaf.smap {
26,673✔
2555
                c.writeLeafSub(&b, key, n)
25,376✔
2556
        }
25,376✔
2557
        if b.Len() > 0 {
2,594✔
2558
                c.enqueueProto(b.Bytes())
1,297✔
2559
        }
1,297✔
2560
        if c.leaf.tsub != nil {
2,512✔
2561
                // Clear the tsub map after 5 seconds.
1,215✔
2562
                c.leaf.tsubt = time.AfterFunc(5*time.Second, func() {
1,252✔
2563
                        c.mu.Lock()
37✔
2564
                        if c.leaf != nil {
74✔
2565
                                c.leaf.tsub = nil
37✔
2566
                                c.leaf.tsubt = nil
37✔
2567
                        }
37✔
2568
                        c.mu.Unlock()
37✔
2569
                })
2570
        }
2571
}
2572

2573
// updateInterestForAccountOnGateway called from gateway code when processing RS+ and RS-.
2574
func (s *Server) updateInterestForAccountOnGateway(accName string, sub *subscription, delta int32) {
203,632✔
2575
        // Since we're in the gateway's readLoop, and we would otherwise block, don't allow fetching.
203,632✔
2576
        acc, err := s.lookupOrFetchAccount(accName, false)
203,632✔
2577
        if acc == nil || err != nil {
203,996✔
2578
                s.Debugf("No or bad account for %q, failed to update interest from gateway", accName)
364✔
2579
                return
364✔
2580
        }
364✔
2581
        acc.updateLeafNodes(sub, delta)
203,268✔
2582
}
2583

2584
// updateLeafNodesEx will make sure to update the account smap for the subscription.
2585
// Will also forward to all leaf nodes as needed.
2586
// If `hubOnly` is true, then will update only leaf nodes that connect to this server
2587
// (that is, for which this server acts as a hub to them).
2588
func (acc *Account) updateLeafNodesEx(sub *subscription, delta int32, hubOnly bool) {
2,540,545✔
2589
        if acc == nil || sub == nil {
2,540,545✔
2590
                return
×
2591
        }
×
2592

2593
        // We will do checks for no leafnodes and same cluster here inline and under the
2594
        // general account read lock.
2595
        // If we feel we need to update the leafnodes we will do that out of line to avoid
2596
        // blocking routes or GWs.
2597

2598
        acc.mu.RLock()
2,540,545✔
2599
        // First check if we even have leafnodes here.
2,540,545✔
2600
        if acc.nleafs == 0 {
5,017,178✔
2601
                acc.mu.RUnlock()
2,476,633✔
2602
                return
2,476,633✔
2603
        }
2,476,633✔
2604

2605
        // Is this a loop detection subject.
2606
        isLDS := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
63,912✔
2607

63,912✔
2608
        // Capture the cluster even if its empty.
63,912✔
2609
        var cluster string
63,912✔
2610
        if sub.origin != nil {
109,679✔
2611
                cluster = bytesToString(sub.origin)
45,767✔
2612
        }
45,767✔
2613

2614
        // If we have an isolated cluster we can return early, as long as it is not a loop detection subject.
2615
        // Empty clusters will return false for the check.
2616
        if !isLDS && acc.isLeafNodeClusterIsolated(cluster) {
83,006✔
2617
                acc.mu.RUnlock()
19,094✔
2618
                return
19,094✔
2619
        }
19,094✔
2620

2621
        // We can release the general account lock.
2622
        acc.mu.RUnlock()
44,818✔
2623

44,818✔
2624
        // We can hold the list lock here to avoid having to copy a large slice.
44,818✔
2625
        acc.lmu.RLock()
44,818✔
2626
        defer acc.lmu.RUnlock()
44,818✔
2627

44,818✔
2628
        // Do this once.
44,818✔
2629
        subject := string(sub.subject)
44,818✔
2630

44,818✔
2631
        // Walk the connected leafnodes from a random starting point to avoid
44,818✔
2632
        // concurrent callers all contending over leafs in the same order.
44,818✔
2633
        nleafs := len(acc.lleafs)
44,818✔
2634
        start := 0
44,818✔
2635
        if nleafs > 1 {
51,603✔
2636
                start = rand.Intn(nleafs)
6,785✔
2637
        }
6,785✔
2638
        for i := 0; i < nleafs; i++ {
100,589✔
2639
                ln := acc.lleafs[(start+i)%nleafs]
55,771✔
2640
                if ln == sub.client {
85,401✔
2641
                        continue
29,630✔
2642
                }
2643
                ln.mu.RLock()
26,141✔
2644
                // Don't advertise interest from leafnodes to other isolated leafnodes.
26,141✔
2645
                if sub.client.kind == LEAF && ln.isIsolatedLeafNode() {
26,172✔
2646
                        ln.mu.RUnlock()
31✔
2647
                        continue
31✔
2648
                }
2649
                // If `hubOnly` is true, it means that we want to update only leafnodes
2650
                // that connect to this server (so isHubLeafNode() would return `true`).
2651
                if hubOnly && !ln.isHubLeafNode() {
26,116✔
2652
                        ln.mu.RUnlock()
6✔
2653
                        continue
6✔
2654
                }
2655
                // Check to make sure this sub does not have an origin cluster that matches the leafnode.
2656
                // If skipped, make sure that we still let go the "$LDS." subscription that allows
2657
                // the detection of loops as long as different cluster.
2658
                clusterDifferent := cluster != ln.remoteCluster()
26,104✔
2659
                update := (isLDS && clusterDifferent) ||
26,104✔
2660
                        ((cluster == _EMPTY_ || clusterDifferent) && (delta <= 0 || ln.canSubscribeInternal(subject)))
26,104✔
2661
                ln.mu.RUnlock()
26,104✔
2662
                if update {
48,607✔
2663
                        ln.mu.Lock()
22,503✔
2664
                        // The leaf role, isolation mode, and remote cluster are stable
22,503✔
2665
                        // for the connection. Recheck canSubscribe here since permissions
22,503✔
2666
                        // can change, and to initializes mperms for wildcard subscriptions
22,503✔
2667
                        // that collide with deny rules.
22,503✔
2668
                        if isLDS || delta <= 0 || ln.canSubscribe(subject) {
45,006✔
2669
                                ln.updateSmap(sub, delta, isLDS)
22,503✔
2670
                        }
22,503✔
2671
                        ln.mu.Unlock()
22,503✔
2672
                }
2673
        }
2674
}
2675

2676
// updateLeafNodes will make sure to update the account smap for the subscription.
2677
// Will also forward to all leaf nodes as needed.
2678
func (acc *Account) updateLeafNodes(sub *subscription, delta int32) {
2,540,522✔
2679
        acc.updateLeafNodesEx(sub, delta, false)
2,540,522✔
2680
}
2,540,522✔
2681

2682
// This will make an update to our internal smap and determine if we should send out
2683
// an interest update to the remote side.
2684
// Lock should be held.
2685
func (c *client) updateSmap(sub *subscription, delta int32, isLDS bool) {
22,503✔
2686
        if c.leaf.smap == nil {
22,556✔
2687
                return
53✔
2688
        }
53✔
2689

2690
        // If we are solicited make sure this is a local client or a non-solicited leaf node
2691
        skind := sub.client.kind
22,450✔
2692
        updateClient := skind == CLIENT || skind == SYSTEM || skind == JETSTREAM || skind == ACCOUNT
22,450✔
2693
        if !isLDS && c.isSpokeLeafNode() && !(updateClient || (skind == LEAF && !sub.client.isSpokeLeafNode())) {
30,187✔
2694
                return
7,737✔
2695
        }
7,737✔
2696

2697
        // For additions, check if that sub has just been processed during initLeafNodeSmapAndSendSubs
2698
        if delta > 0 && c.leaf.tsub != nil {
21,800✔
2699
                if _, present := c.leaf.tsub[sub]; present {
7,090✔
2700
                        delete(c.leaf.tsub, sub)
3✔
2701
                        if len(c.leaf.tsub) == 0 {
3✔
2702
                                c.leaf.tsub = nil
×
2703
                                c.leaf.tsubt.Stop()
×
2704
                                c.leaf.tsubt = nil
×
2705
                        }
×
2706
                        return
3✔
2707
                }
2708
        }
2709

2710
        key := keyFromSub(sub)
14,710✔
2711
        n, ok := c.leaf.smap[key]
14,710✔
2712
        if delta < 0 && !ok {
15,520✔
2713
                return
810✔
2714
        }
810✔
2715

2716
        // We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
2717
        update := sub.queue != nil || (n <= 0 && n+delta > 0) || (n > 0 && n+delta <= 0)
13,900✔
2718
        n += delta
13,900✔
2719
        if n > 0 {
24,311✔
2720
                c.leaf.smap[key] = n
10,411✔
2721
        } else {
13,900✔
2722
                delete(c.leaf.smap, key)
3,489✔
2723
        }
3,489✔
2724
        if update {
23,229✔
2725
                c.sendLeafNodeSubUpdate(key, n)
9,329✔
2726
        }
9,329✔
2727
}
2728

2729
// Used to force add subjects to the subject map.
2730
func (c *client) forceAddToSmap(subj string) {
4✔
2731
        c.mu.Lock()
4✔
2732
        defer c.mu.Unlock()
4✔
2733

4✔
2734
        if c.leaf.smap == nil {
4✔
2735
                return
×
2736
        }
×
2737
        n := c.leaf.smap[subj]
4✔
2738
        if n != 0 {
5✔
2739
                return
1✔
2740
        }
1✔
2741
        // Place into the map since it was not there.
2742
        c.leaf.smap[subj] = 1
3✔
2743
        c.sendLeafNodeSubUpdate(subj, 1)
3✔
2744
}
2745

2746
// Used to force remove a subject from the subject map.
2747
func (c *client) forceRemoveFromSmap(subj string) {
1✔
2748
        c.mu.Lock()
1✔
2749
        defer c.mu.Unlock()
1✔
2750

1✔
2751
        if c.leaf.smap == nil {
1✔
2752
                return
×
2753
        }
×
2754
        n := c.leaf.smap[subj]
1✔
2755
        if n == 0 {
1✔
2756
                return
×
2757
        }
×
2758
        n--
1✔
2759
        if n == 0 {
2✔
2760
                // Remove is now zero
1✔
2761
                delete(c.leaf.smap, subj)
1✔
2762
                c.sendLeafNodeSubUpdate(subj, 0)
1✔
2763
        } else {
1✔
2764
                c.leaf.smap[subj] = n
×
2765
        }
×
2766
}
2767

2768
// Send the subscription interest change to the other side.
2769
// Lock should be held.
2770
func (c *client) sendLeafNodeSubUpdate(key string, n int32) {
9,333✔
2771
        // If we are a spoke, we need to check if we are allowed to send this subscription over to the hub.
9,333✔
2772
        if c.isSpokeLeafNode() {
11,417✔
2773
                checkPerms := true
2,084✔
2774
                if len(key) > 0 && (key[0] == '$' || key[0] == '_') {
3,233✔
2775
                        if strings.HasPrefix(key, leafNodeLoopDetectionSubjectPrefix) ||
1,149✔
2776
                                strings.HasPrefix(key, oldGWReplyPrefix) ||
1,149✔
2777
                                strings.HasPrefix(key, gwReplyPrefix) {
1,231✔
2778
                                checkPerms = false
82✔
2779
                        }
82✔
2780
                }
2781
                if checkPerms {
4,086✔
2782
                        var subject string
2,002✔
2783
                        if sep := strings.IndexByte(key, ' '); sep != -1 {
2,486✔
2784
                                subject = key[:sep]
484✔
2785
                        } else {
2,002✔
2786
                                subject = key
1,518✔
2787
                        }
1,518✔
2788
                        if !c.canSubscribe(subject) {
2,002✔
2789
                                return
×
2790
                        }
×
2791
                }
2792
        }
2793
        // If we are here we can send over to the other side.
2794
        _b := [64]byte{}
9,333✔
2795
        b := bytes.NewBuffer(_b[:0])
9,333✔
2796
        c.writeLeafSub(b, key, n)
9,333✔
2797
        c.enqueueProto(b.Bytes())
9,333✔
2798
}
2799

2800
// Helper function to build the key.
2801
func keyFromSub(sub *subscription) string {
44,162✔
2802
        var sb strings.Builder
44,162✔
2803
        sb.Grow(len(sub.subject) + len(sub.queue) + 1)
44,162✔
2804
        sb.Write(sub.subject)
44,162✔
2805
        if sub.queue != nil {
47,963✔
2806
                // Just make the key subject spc group, e.g. 'foo bar'
3,801✔
2807
                sb.WriteByte(' ')
3,801✔
2808
                sb.Write(sub.queue)
3,801✔
2809
        }
3,801✔
2810
        return sb.String()
44,162✔
2811
}
2812

2813
const (
2814
        keyRoutedSub         = "R"
2815
        keyRoutedSubByte     = 'R'
2816
        keyRoutedLeafSub     = "L"
2817
        keyRoutedLeafSubByte = 'L'
2818
)
2819

2820
// Helper function to build the key that prevents collisions between normal
2821
// routed subscriptions and routed subscriptions on behalf of a leafnode.
2822
// Keys will look like this:
2823
// "R foo"          -> plain routed sub on "foo"
2824
// "R foo bar"      -> queue routed sub on "foo", queue "bar"
2825
// "L foo bar"      -> plain routed leaf sub on "foo", leaf "bar"
2826
// "L foo bar baz"  -> queue routed sub on "foo", queue "bar", leaf "baz"
2827
func keyFromSubWithOrigin(sub *subscription) string {
727,566✔
2828
        var sb strings.Builder
727,566✔
2829
        sb.Grow(2 + len(sub.origin) + 1 + len(sub.subject) + 1 + len(sub.queue))
727,566✔
2830
        leaf := len(sub.origin) > 0
727,566✔
2831
        if leaf {
742,728✔
2832
                sb.WriteByte(keyRoutedLeafSubByte)
15,162✔
2833
        } else {
727,566✔
2834
                sb.WriteByte(keyRoutedSubByte)
712,404✔
2835
        }
712,404✔
2836
        sb.WriteByte(' ')
727,566✔
2837
        sb.Write(sub.subject)
727,566✔
2838
        if sub.queue != nil {
759,735✔
2839
                sb.WriteByte(' ')
32,169✔
2840
                sb.Write(sub.queue)
32,169✔
2841
        }
32,169✔
2842
        if leaf {
742,728✔
2843
                sb.WriteByte(' ')
15,162✔
2844
                sb.Write(sub.origin)
15,162✔
2845
        }
15,162✔
2846
        return sb.String()
727,566✔
2847
}
2848

2849
// Lock should be held.
2850
func (c *client) writeLeafSub(w *bytes.Buffer, key string, n int32) {
34,709✔
2851
        if key == _EMPTY_ {
34,709✔
2852
                return
×
2853
        }
×
2854
        if n > 0 {
65,928✔
2855
                w.WriteString("LS+ " + key)
31,219✔
2856
                // Check for queue semantics, if found write n.
31,219✔
2857
                if strings.Contains(key, " ") {
33,533✔
2858
                        w.WriteString(" ")
2,314✔
2859
                        var b [12]byte
2,314✔
2860
                        var i = len(b)
2,314✔
2861
                        for l := n; l > 0; l /= 10 {
5,541✔
2862
                                i--
3,227✔
2863
                                b[i] = digits[l%10]
3,227✔
2864
                        }
3,227✔
2865
                        w.Write(b[i:])
2,314✔
2866
                        if c.trace {
2,314✔
2867
                                arg := fmt.Sprintf("%s %d", key, n)
×
2868
                                c.traceOutOp("LS+", []byte(arg))
×
2869
                        }
×
2870
                } else if c.trace {
28,922✔
2871
                        c.traceOutOp("LS+", []byte(key))
17✔
2872
                }
17✔
2873
        } else {
3,490✔
2874
                w.WriteString("LS- " + key)
3,490✔
2875
                if c.trace {
3,490✔
2876
                        c.traceOutOp("LS-", []byte(key))
×
2877
                }
×
2878
        }
2879
        w.WriteString(CR_LF)
34,709✔
2880
}
2881

2882
// processLeafSub will process an inbound sub request for the remote leaf node.
2883
func (c *client) processLeafSub(argo []byte) (err error) {
30,901✔
2884
        // Indicate activity.
30,901✔
2885
        c.in.subs++
30,901✔
2886

30,901✔
2887
        srv := c.srv
30,901✔
2888
        if srv == nil {
30,901✔
2889
                return nil
×
2890
        }
×
2891

2892
        // Copy so we do not reference a potentially large buffer
2893
        arg := make([]byte, len(argo))
30,901✔
2894
        copy(arg, argo)
30,901✔
2895

30,901✔
2896
        args := splitArg(arg)
30,901✔
2897
        sub := &subscription{client: c}
30,901✔
2898

30,901✔
2899
        delta := int32(1)
30,901✔
2900
        switch len(args) {
30,901✔
2901
        case 1:
28,627✔
2902
                sub.queue = nil
28,627✔
2903
        case 3:
2,274✔
2904
                sub.queue = args[1]
2,274✔
2905
                sub.qw = int32(parseSize(args[2]))
2,274✔
2906
                // TODO: (ik) We should have a non empty queue name and a queue
2,274✔
2907
                // weight >= 1. For 2.11, we may want to return an error if that
2,274✔
2908
                // is not the case, but for now just overwrite `delta` if queue
2,274✔
2909
                // weight is greater than 1 (it is possible after a reconnect/
2,274✔
2910
                // server restart to receive a queue weight > 1 for a new sub).
2,274✔
2911
                if sub.qw > 1 {
3,945✔
2912
                        delta = sub.qw
1,671✔
2913
                }
1,671✔
2914
        default:
×
2915
                return fmt.Errorf("processLeafSub Parse Error: '%s'", arg)
×
2916
        }
2917
        sub.subject = args[0]
30,901✔
2918

30,901✔
2919
        c.mu.Lock()
30,901✔
2920
        if c.isClosed() {
30,918✔
2921
                c.mu.Unlock()
17✔
2922
                return nil
17✔
2923
        }
17✔
2924

2925
        acc := c.acc
30,884✔
2926
        // Guard against LS+ arriving before CONNECT has been processed, which
30,884✔
2927
        // can happen when compression is enabled.
30,884✔
2928
        if acc == nil {
30,884✔
2929
                c.mu.Unlock()
×
2930
                c.sendErr("Authorization Violation")
×
2931
                c.closeConnection(ProtocolViolation)
×
2932
                return nil
×
2933
        }
×
2934
        // Check if we have a loop.
2935
        ldsPrefix := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
30,884✔
2936

30,884✔
2937
        if ldsPrefix && bytesToString(sub.subject) == acc.getLDSubject() {
30,889✔
2938
                c.mu.Unlock()
5✔
2939
                c.handleLeafNodeLoop(true)
5✔
2940
                return nil
5✔
2941
        }
5✔
2942

2943
        // Check permissions if applicable. (but exclude the $LDS, $GR and _GR_)
2944
        checkPerms := true
30,879✔
2945
        if sub.subject[0] == '$' || sub.subject[0] == '_' {
58,854✔
2946
                if ldsPrefix ||
27,975✔
2947
                        bytes.HasPrefix(sub.subject, []byte(oldGWReplyPrefix)) ||
27,975✔
2948
                        bytes.HasPrefix(sub.subject, []byte(gwReplyPrefix)) {
29,939✔
2949
                        checkPerms = false
1,964✔
2950
                }
1,964✔
2951
        }
2952

2953
        // If we are a hub check that we can publish to this subject.
2954
        if checkPerms {
59,794✔
2955
                subj := string(sub.subject)
28,915✔
2956
                if subjectIsLiteral(subj) && !c.pubAllowedFullCheck(subj, true, true) {
29,247✔
2957
                        c.mu.Unlock()
332✔
2958
                        c.leafSubPermViolation(sub.subject)
332✔
2959
                        c.Debugf(fmt.Sprintf("Permissions Violation for Subscription to %q", sub.subject))
332✔
2960
                        return nil
332✔
2961
                }
332✔
2962
        }
2963

2964
        // Check if we have a maximum on the number of subscriptions.
2965
        if c.subsAtLimit() {
30,555✔
2966
                c.mu.Unlock()
8✔
2967
                c.maxSubsExceeded()
8✔
2968
                return nil
8✔
2969
        }
8✔
2970

2971
        // If we have an origin cluster associated mark that in the sub.
2972
        if rc := c.remoteCluster(); rc != _EMPTY_ {
57,068✔
2973
                sub.origin = []byte(rc)
26,529✔
2974
        }
26,529✔
2975

2976
        // Like Routes, we store local subs by account and subject and optionally queue name.
2977
        // If we have a queue it will have a trailing weight which we do not want.
2978
        if sub.queue != nil {
32,525✔
2979
                sub.sid = arg[:len(arg)-len(args[2])-1]
1,986✔
2980
        } else {
30,539✔
2981
                sub.sid = arg
28,553✔
2982
        }
28,553✔
2983
        key := bytesToString(sub.sid)
30,539✔
2984
        osub := c.subs[key]
30,539✔
2985
        if osub == nil {
59,543✔
2986
                c.subs[key] = sub
29,004✔
2987
                // Now place into the account sl.
29,004✔
2988
                if err := acc.sl.Insert(sub); err != nil {
29,004✔
2989
                        delete(c.subs, key)
×
2990
                        c.mu.Unlock()
×
2991
                        c.Errorf("Could not insert subscription: %v", err)
×
2992
                        c.sendErr("Invalid Subscription")
×
2993
                        return nil
×
2994
                }
×
2995
        } else if sub.queue != nil {
3,069✔
2996
                // For a queue we need to update the weight.
1,534✔
2997
                delta = sub.qw - atomic.LoadInt32(&osub.qw)
1,534✔
2998
                atomic.StoreInt32(&osub.qw, sub.qw)
1,534✔
2999
                acc.sl.UpdateRemoteQSub(osub)
1,534✔
3000
        }
1,534✔
3001
        spoke := c.isSpokeLeafNode()
30,539✔
3002
        c.mu.Unlock()
30,539✔
3003

30,539✔
3004
        // Only add in shadow subs if a new sub or qsub.
30,539✔
3005
        if osub == nil {
59,543✔
3006
                if err := c.addShadowSubscriptions(acc, sub); err != nil {
29,004✔
3007
                        c.Errorf(err.Error())
×
3008
                }
×
3009
        }
3010

3011
        // If we are not solicited, treat leaf node subscriptions similar to a
3012
        // client subscription, meaning we forward them to routes, gateways and
3013
        // other leaf nodes as needed.
3014
        if !spoke {
41,338✔
3015
                // If we are routing add to the route map for the associated account.
10,799✔
3016
                srv.updateRouteSubscriptionMap(acc, sub, delta)
10,799✔
3017
                if srv.gateway.enabled {
11,990✔
3018
                        srv.gatewayUpdateSubInterest(acc.Name, sub, delta)
1,191✔
3019
                }
1,191✔
3020
        }
3021
        // Now check on leafnode updates for other leaf nodes. We understand solicited
3022
        // and non-solicited state in this call so we will do the right thing.
3023
        acc.updateLeafNodes(sub, delta)
30,539✔
3024

30,539✔
3025
        return nil
30,539✔
3026
}
3027

3028
// If the leafnode is a solicited, set the connect delay based on default
3029
// or private option (for tests). Sends the error to the other side, log and
3030
// close the connection.
3031
func (c *client) handleLeafNodeLoop(sendErr bool) {
15✔
3032
        accName, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterLoopDetected)
15✔
3033
        errTxt := fmt.Sprintf("Loop detected for leafnode account=%q. Delaying attempt to reconnect for %v", accName, delay)
15✔
3034
        if sendErr {
23✔
3035
                c.sendErr(errTxt)
8✔
3036
        }
8✔
3037

3038
        c.Errorf(errTxt)
15✔
3039
        // If we are here with "sendErr" false, it means that this is the server
15✔
3040
        // that received the error. The other side will have closed the connection,
15✔
3041
        // but does not hurt to close here too.
15✔
3042
        c.closeConnection(ProtocolViolation)
15✔
3043
}
3044

3045
// processLeafUnsub will process an inbound unsub request for the remote leaf node.
3046
func (c *client) processLeafUnsub(arg []byte) error {
3,159✔
3047
        // Indicate any activity, so pub and sub or unsubs.
3,159✔
3048
        c.in.subs++
3,159✔
3049

3,159✔
3050
        srv := c.srv
3,159✔
3051

3,159✔
3052
        c.mu.Lock()
3,159✔
3053
        if c.isClosed() {
3,188✔
3054
                c.mu.Unlock()
29✔
3055
                return nil
29✔
3056
        }
29✔
3057

3058
        acc := c.acc
3,130✔
3059
        // Guard against LS- arriving before CONNECT has been processed.
3,130✔
3060
        if acc == nil {
3,130✔
3061
                c.mu.Unlock()
×
3062
                c.sendErr("Authorization Violation")
×
3063
                c.closeConnection(ProtocolViolation)
×
3064
                return nil
×
3065
        }
×
3066

3067
        spoke := c.isSpokeLeafNode()
3,130✔
3068
        // We store local subs by account and subject and optionally queue name.
3,130✔
3069
        // LS- will have the arg exactly as the key.
3,130✔
3070
        sub, ok := c.subs[string(arg)]
3,130✔
3071
        if !ok {
3,142✔
3072
                // If not found, don't try to update routes/gws/leaf nodes.
12✔
3073
                c.mu.Unlock()
12✔
3074
                return nil
12✔
3075
        }
12✔
3076
        delta := int32(1)
3,118✔
3077
        if len(sub.queue) > 0 {
3,533✔
3078
                delta = sub.qw
415✔
3079
        }
415✔
3080
        c.mu.Unlock()
3,118✔
3081

3,118✔
3082
        c.unsubscribe(acc, sub, true, true)
3,118✔
3083
        if !spoke {
4,013✔
3084
                // If we are routing subtract from the route map for the associated account.
895✔
3085
                srv.updateRouteSubscriptionMap(acc, sub, -delta)
895✔
3086
                // Gateways
895✔
3087
                if srv.gateway.enabled {
1,091✔
3088
                        srv.gatewayUpdateSubInterest(acc.Name, sub, -delta)
196✔
3089
                }
196✔
3090
        }
3091
        // Now check on leafnode updates for other leaf nodes.
3092
        acc.updateLeafNodes(sub, -delta)
3,118✔
3093
        return nil
3,118✔
3094
}
3095

3096
func (c *client) processLeafHeaderMsgArgs(arg []byte) error {
227✔
3097
        // Unroll splitArgs to avoid runtime/heap issues
227✔
3098
        args := c.argsa[:0]
227✔
3099
        start := -1
227✔
3100
        for i, b := range arg {
12,540✔
3101
                switch b {
12,313✔
3102
                case ' ', '\t', '\r', '\n':
665✔
3103
                        if start >= 0 {
1,330✔
3104
                                args = append(args, arg[start:i])
665✔
3105
                                start = -1
665✔
3106
                        }
665✔
3107
                default:
11,648✔
3108
                        if start < 0 {
12,540✔
3109
                                start = i
892✔
3110
                        }
892✔
3111
                }
3112
        }
3113
        if start >= 0 {
454✔
3114
                args = append(args, arg[start:])
227✔
3115
        }
227✔
3116

3117
        c.pa.arg = arg
227✔
3118
        switch len(args) {
227✔
3119
        case 0, 1, 2:
×
3120
                return fmt.Errorf("processLeafHeaderMsgArgs Parse Error: '%s'", args)
×
3121
        case 3:
21✔
3122
                c.pa.reply = nil
21✔
3123
                c.pa.queues = nil
21✔
3124
                c.pa.hdb = args[1]
21✔
3125
                c.pa.hdr = parseSize(args[1])
21✔
3126
                c.pa.szb = args[2]
21✔
3127
                c.pa.size = parseSize(args[2])
21✔
3128
        case 4:
203✔
3129
                c.pa.reply = args[1]
203✔
3130
                c.pa.queues = nil
203✔
3131
                c.pa.hdb = args[2]
203✔
3132
                c.pa.hdr = parseSize(args[2])
203✔
3133
                c.pa.szb = args[3]
203✔
3134
                c.pa.size = parseSize(args[3])
203✔
3135
        default:
3✔
3136
                // args[1] is our reply indicator. Should be + or | normally.
3✔
3137
                if len(args[1]) != 1 {
3✔
3138
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3139
                }
×
3140
                switch args[1][0] {
3✔
3141
                case '+':
2✔
3142
                        c.pa.reply = args[2]
2✔
3143
                case '|':
1✔
3144
                        c.pa.reply = nil
1✔
3145
                default:
×
3146
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3147
                }
3148
                // Grab header size.
3149
                c.pa.hdb = args[len(args)-2]
3✔
3150
                c.pa.hdr = parseSize(c.pa.hdb)
3✔
3151

3✔
3152
                // Grab size.
3✔
3153
                c.pa.szb = args[len(args)-1]
3✔
3154
                c.pa.size = parseSize(c.pa.szb)
3✔
3155

3✔
3156
                // Grab queue names.
3✔
3157
                if c.pa.reply != nil {
5✔
3158
                        c.pa.queues = args[3 : len(args)-2]
2✔
3159
                } else {
3✔
3160
                        c.pa.queues = args[2 : len(args)-2]
1✔
3161
                }
1✔
3162
        }
3163
        if c.pa.hdr < 0 {
227✔
3164
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Header Size: '%s'", arg)
×
3165
        }
×
3166
        if c.pa.size < 0 {
227✔
3167
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Size: '%s'", args)
×
3168
        }
×
3169
        if c.pa.hdr > c.pa.size {
227✔
3170
                return fmt.Errorf("processLeafHeaderMsgArgs Header Size larger then TotalSize: '%s'", arg)
×
3171
        }
×
3172
        maxPayload := atomic.LoadInt32(&c.mpay)
227✔
3173
        if maxPayload != jwt.NoLimit && int64(c.pa.size) > int64(maxPayload) {
227✔
3174
                c.maxPayloadViolation(c.pa.size, maxPayload)
×
3175
                return ErrMaxPayload
×
3176
        }
×
3177

3178
        // Common ones processed after check for arg length
3179
        c.pa.subject = args[0]
227✔
3180

227✔
3181
        return nil
227✔
3182
}
3183

3184
func (c *client) processLeafMsgArgs(arg []byte) error {
67,245✔
3185
        // Unroll splitArgs to avoid runtime/heap issues
67,245✔
3186
        args := c.argsa[:0]
67,245✔
3187
        start := -1
67,245✔
3188
        for i, b := range arg {
2,217,133✔
3189
                switch b {
2,149,888✔
3190
                case ' ', '\t', '\r', '\n':
118,754✔
3191
                        if start >= 0 {
237,508✔
3192
                                args = append(args, arg[start:i])
118,754✔
3193
                                start = -1
118,754✔
3194
                        }
118,754✔
3195
                default:
2,031,134✔
3196
                        if start < 0 {
2,217,133✔
3197
                                start = i
185,999✔
3198
                        }
185,999✔
3199
                }
3200
        }
3201
        if start >= 0 {
134,490✔
3202
                args = append(args, arg[start:])
67,245✔
3203
        }
67,245✔
3204

3205
        c.pa.arg = arg
67,245✔
3206
        switch len(args) {
67,245✔
3207
        case 0, 1:
×
3208
                return fmt.Errorf("processLeafMsgArgs Parse Error: '%s'", args)
×
3209
        case 2:
38,450✔
3210
                c.pa.reply = nil
38,450✔
3211
                c.pa.queues = nil
38,450✔
3212
                c.pa.szb = args[1]
38,450✔
3213
                c.pa.size = parseSize(args[1])
38,450✔
3214
        case 3:
6,240✔
3215
                c.pa.reply = args[1]
6,240✔
3216
                c.pa.queues = nil
6,240✔
3217
                c.pa.szb = args[2]
6,240✔
3218
                c.pa.size = parseSize(args[2])
6,240✔
3219
        default:
22,555✔
3220
                // args[1] is our reply indicator. Should be + or | normally.
22,555✔
3221
                if len(args[1]) != 1 {
22,555✔
3222
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3223
                }
×
3224
                switch args[1][0] {
22,555✔
3225
                case '+':
159✔
3226
                        c.pa.reply = args[2]
159✔
3227
                case '|':
22,396✔
3228
                        c.pa.reply = nil
22,396✔
3229
                default:
×
3230
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3231
                }
3232
                // Grab size.
3233
                c.pa.szb = args[len(args)-1]
22,555✔
3234
                c.pa.size = parseSize(c.pa.szb)
22,555✔
3235

22,555✔
3236
                // Grab queue names.
22,555✔
3237
                if c.pa.reply != nil {
22,714✔
3238
                        c.pa.queues = args[3 : len(args)-1]
159✔
3239
                } else {
22,555✔
3240
                        c.pa.queues = args[2 : len(args)-1]
22,396✔
3241
                }
22,396✔
3242
        }
3243
        if c.pa.size < 0 {
67,245✔
3244
                return fmt.Errorf("processLeafMsgArgs Bad or Missing Size: '%s'", args)
×
3245
        }
×
3246
        maxPayload := atomic.LoadInt32(&c.mpay)
67,245✔
3247
        if maxPayload != jwt.NoLimit && int64(c.pa.size) > int64(maxPayload) {
67,245✔
3248
                c.maxPayloadViolation(c.pa.size, maxPayload)
×
3249
                return ErrMaxPayload
×
3250
        }
×
3251

3252
        // Common ones processed after check for arg length
3253
        c.pa.subject = args[0]
67,245✔
3254

67,245✔
3255
        return nil
67,245✔
3256
}
3257

3258
// processInboundLeafMsg is called to process an inbound msg from a leaf node.
3259
func (c *client) processInboundLeafMsg(msg []byte) {
66,105✔
3260
        // Update statistics
66,105✔
3261
        // The msg includes the CR_LF, so pull back out for accounting.
66,105✔
3262
        c.in.msgs++
66,105✔
3263
        c.in.bytes += int32(len(msg) - LEN_CR_LF)
66,105✔
3264

66,105✔
3265
        srv, acc, subject := c.srv, c.acc, string(c.pa.subject)
66,105✔
3266

66,105✔
3267
        // Mostly under testing scenarios.
66,105✔
3268
        if srv == nil || acc == nil {
66,105✔
3269
                return
×
3270
        }
×
3271

3272
        // Check that leaf messages respect the subject permissions.
3273
        if c.perms != nil && !c.leafMsgAllowed() {
66,110✔
3274
                c.leafPubPermViolation(c.pa.subject)
5✔
3275
                return
5✔
3276
        }
5✔
3277

3278
        // Match the subscriptions. We will use our own L1 map if
3279
        // it's still valid, avoiding contention on the shared sublist.
3280
        var r *SublistResult
66,100✔
3281
        var ok bool
66,100✔
3282

66,100✔
3283
        genid := atomic.LoadUint64(&c.acc.sl.genid)
66,100✔
3284
        if genid == c.in.genid && c.in.results != nil {
130,149✔
3285
                r, ok = c.in.results[subject]
64,049✔
3286
        } else {
66,100✔
3287
                // Reset our L1 completely.
2,051✔
3288
                c.in.results = make(map[string]*SublistResult)
2,051✔
3289
                c.in.genid = genid
2,051✔
3290
        }
2,051✔
3291

3292
        // Go back to the sublist data structure.
3293
        if !ok {
102,427✔
3294
                r = c.acc.sl.Match(subject)
36,327✔
3295
                // Prune the results cache. Keeps us from unbounded growth. Random delete.
36,327✔
3296
                if len(c.in.results) >= maxResultCacheSize {
37,276✔
3297
                        n := 0
949✔
3298
                        for subj := range c.in.results {
32,266✔
3299
                                delete(c.in.results, subj)
31,317✔
3300
                                if n++; n > pruneSize {
32,266✔
3301
                                        break
949✔
3302
                                }
3303
                        }
3304
                }
3305
                // Then add the new cache entry.
3306
                c.in.results[subject] = r
36,327✔
3307
        }
3308

3309
        // Collect queue names if needed.
3310
        var qnames [][]byte
66,100✔
3311

66,100✔
3312
        // Check for no interest, short circuit if so.
66,100✔
3313
        // This is the fanout scale.
66,100✔
3314
        if len(r.psubs)+len(r.qsubs) > 0 {
131,892✔
3315
                flag := pmrNoFlag
65,792✔
3316
                // If we have queue subs in this cluster, then if we run in gateway
65,792✔
3317
                // mode and the remote gateways have queue subs, then we need to
65,792✔
3318
                // collect the queue groups this message was sent to so that we
65,792✔
3319
                // exclude them when sending to gateways.
65,792✔
3320
                if len(r.qsubs) > 0 && c.srv.gateway.enabled &&
65,792✔
3321
                        atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 {
78,036✔
3322
                        flag |= pmrCollectQueueNames
12,244✔
3323
                }
12,244✔
3324
                // If this is a mapped subject that means the mapped interest
3325
                // is what got us here, but this might not have a queue designation
3326
                // If that is the case, make sure we ignore to process local queue subscribers.
3327
                if len(c.pa.mapped) > 0 && len(c.pa.queues) == 0 {
66,042✔
3328
                        flag |= pmrIgnoreEmptyQueueFilter
250✔
3329
                }
250✔
3330
                _, qnames = c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, flag)
65,792✔
3331
        }
3332

3333
        // Now deal with gateways
3334
        if c.srv.gateway.enabled {
79,129✔
3335
                c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, qnames, true)
13,029✔
3336
        }
13,029✔
3337
}
3338

3339
// Checks whether the inbound leaf message is allowed by the
3340
// connection's permissions. On the hub side this enforces what
3341
// the remote leaf may publish. On the spoke side this enforces
3342
// import restrictions such as deny_imports.
3343
func (c *client) leafMsgAllowed() bool {
62,645✔
3344
        wireSubject := c.pa.subject
62,645✔
3345
        if len(c.pa.mapped) > 0 {
62,895✔
3346
                // Mappings rewrite c.pa.subject to the internal
250✔
3347
                // destination. For leaf ACLs, need to check
250✔
3348
                // the original wire subject from the remote side.
250✔
3349
                wireSubject = c.pa.mapped
250✔
3350
        }
250✔
3351
        // Strip any gateway routing prefix for the permission check.
3352
        subjectToCheck, isGW := getGWRoutedSubjectOrSelf(wireSubject)
62,645✔
3353

62,645✔
3354
        // Service-import replies (_R_), JS ack subjects ($JS.ACK.)
62,645✔
3355
        // are internal routing subjects forwarded via LS+ without
62,645✔
3356
        // permission checks.
62,645✔
3357
        if isServiceReply(subjectToCheck) || isJSAckSubject(subjectToCheck) {
62,676✔
3358
                return true
31✔
3359
        }
31✔
3360

3361
        c.mu.RLock()
62,614✔
3362
        if c.isSpokeLeafNode() {
91,285✔
3363
                // Gateway routed replies are forwarded without
28,671✔
3364
                // permission checks.
28,671✔
3365
                if isGW || c.leafReceiveAllowed(subjectToCheck) {
57,340✔
3366
                        c.mu.RUnlock()
28,669✔
3367
                        return true
28,669✔
3368
                }
28,669✔
3369
        } else if c.leafSendAllowed(subjectToCheck) {
67,880✔
3370
                c.mu.RUnlock()
33,937✔
3371
                return true
33,937✔
3372
        }
33,937✔
3373

3374
        // If allow_responses is not configured, or there is no tracked reply for
3375
        // this subject, the answer is "denied" and we can return it while still
3376
        // holding only the read lock.
3377
        replySubject := bytesToString(wireSubject)
8✔
3378
        if c.perms == nil || c.perms.resp == nil || c.replies[replySubject] == nil {
13✔
3379
                c.mu.RUnlock()
5✔
3380
                return false
5✔
3381
        }
5✔
3382
        c.mu.RUnlock()
3✔
3383

3✔
3384
        // Check tracked reply permissions (allow_responses).
3✔
3385
        // Use the pre-strip subject since deliverMsg tracks
3✔
3386
        // replies under the original form, which includes
3✔
3387
        // the GW routing prefix for routed requests.
3✔
3388
        c.mu.Lock()
3✔
3389
        defer c.mu.Unlock()
3✔
3390
        return c.responseAllowed(replySubject)
3✔
3391
}
3392

3393
// Returns true if the leaf side ACLs allow importing this subject,
3394
// based on the permissions received over INFO and any local deny_imports.
3395
// At least a read lock must be held.
3396
func (c *client) leafReceiveAllowed(subject []byte) bool {
28,671✔
3397
        return c.canSubscribeInternal(bytesToString(subject))
28,671✔
3398
}
28,671✔
3399

3400
// Returns true if the hub side ACLs allow the remote leaf to send
3401
// this subject.
3402
// At least a read lock must be held.
3403
func (c *client) leafSendAllowed(bsubject []byte) bool {
33,943✔
3404
        // Use the original export ACL captured for this accepted leaf.
33,943✔
3405
        // The live perms also contain additional JetStream denies used by
33,943✔
3406
        // the normal forwarding path, and applying them here would reject
33,943✔
3407
        // legitimate inbound JS API requests.
33,943✔
3408
        subject := bytesToString(bsubject)
33,943✔
3409
        perms := c.opts.Export
33,943✔
3410
        if perms == nil || (perms.Allow == nil && perms.Deny == nil) {
67,861✔
3411
                return true
33,918✔
3412
        }
33,918✔
3413

3414
        allowed := true
25✔
3415
        if perms.Allow != nil && !strings.HasPrefix(subject, mqttPrefix) {
36✔
3416
                allowed = false
11✔
3417
                for _, allowSubj := range perms.Allow {
21✔
3418
                        if matchLiteral(subject, allowSubj) {
16✔
3419
                                allowed = true
6✔
3420
                                break
6✔
3421
                        }
3422
                }
3423
        }
3424

3425
        if allowed && len(perms.Deny) > 0 {
39✔
3426
                for _, denySubj := range perms.Deny {
40✔
3427
                        if matchLiteral(subject, denySubj) {
27✔
3428
                                allowed = false
1✔
3429
                                break
1✔
3430
                        }
3431
                }
3432
        }
3433
        return allowed
25✔
3434
}
3435

3436
// Handles a subscription permission violation.
3437
// See leafPermViolation() for details.
3438
func (c *client) leafSubPermViolation(subj []byte) {
332✔
3439
        c.leafPermViolation(false, subj)
332✔
3440
}
332✔
3441

3442
// Handles a publish permission violation.
3443
// See leafPermViolation() for details.
3444
func (c *client) leafPubPermViolation(subj []byte) {
5✔
3445
        c.leafPermViolation(true, subj)
5✔
3446
}
5✔
3447

3448
// Common function to process publish or subscribe leafnode permission violation.
3449
// Sends the permission violation error to the remote, logs it and closes the connection.
3450
// If this is from a server soliciting, the reconnection will be delayed.
3451
func (c *client) leafPermViolation(pub bool, subj []byte) {
337✔
3452
        if c.isSpokeLeafNode() {
671✔
3453
                // For spokes these are no-ops since the hub server told us our permissions.
334✔
3454
                // We just need to not send these over to the other side since we will get cutoff.
334✔
3455
                return
334✔
3456
        }
334✔
3457
        // FIXME(dlc) ?
3458
        c.setLeafConnectDelayIfSoliciting(leafNodeReconnectAfterPermViolation)
3✔
3459
        var action string
3✔
3460
        if pub {
6✔
3461
                c.sendErr(fmt.Sprintf("Permissions Violation for Publish to %q", subj))
3✔
3462
                action = "Publish"
3✔
3463
        } else {
3✔
3464
                c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q", subj))
×
3465
                action = "Subscription"
×
3466
        }
×
3467
        c.Errorf("%s Violation on %q - Check other side configuration", action, subj)
3✔
3468
        // TODO: add a new close reason that is more appropriate?
3✔
3469
        c.closeConnection(ProtocolViolation)
3✔
3470
}
3471

3472
// Invoked from generic processErr() for LEAF connections.
3473
func (c *client) leafProcessErr(errStr string) {
48✔
3474
        // Check if we got a cluster name collision.
48✔
3475
        if strings.Contains(errStr, ErrLeafNodeHasSameClusterName.Error()) {
51✔
3476
                _, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterClusterNameSame)
3✔
3477
                c.Errorf("Leafnode connection dropped with same cluster name error. Delaying attempt to reconnect for %v", delay)
3✔
3478
                return
3✔
3479
        }
3✔
3480
        if strings.Contains(errStr, ErrLeafNodeMinVersionRejected.Error()) {
46✔
3481
                _, delay := c.setLeafConnectDelayIfSoliciting(leafNodeMinVersionReconnectDelay)
1✔
3482
                c.Errorf("Leafnode connection dropped due to minimum version requirement. Delaying attempt to reconnect for %v", delay)
1✔
3483
                return
1✔
3484
        }
1✔
3485

3486
        // We will look for Loop detected error coming from the other side.
3487
        // If we solicit, set the connect delay.
3488
        if !strings.Contains(errStr, "Loop detected") {
81✔
3489
                return
37✔
3490
        }
37✔
3491
        c.handleLeafNodeLoop(false)
7✔
3492
}
3493

3494
// If this leaf connection solicits, sets the connect delay to the given value,
3495
// or the one from the server option's LeafNode.connDelay if one is set (for tests).
3496
// Returns the connection's account name and delay.
3497
func (c *client) setLeafConnectDelayIfSoliciting(delay time.Duration) (string, time.Duration) {
22✔
3498
        c.mu.Lock()
22✔
3499
        if c.isSolicitedLeafNode() {
35✔
3500
                if s := c.srv; s != nil {
26✔
3501
                        if srvdelay := s.getOpts().LeafNode.connDelay; srvdelay != 0 {
18✔
3502
                                delay = srvdelay
5✔
3503
                        }
5✔
3504
                }
3505
                c.leaf.remote.setConnectDelay(delay)
13✔
3506
        }
3507
        var accName string
22✔
3508
        if c.acc != nil {
44✔
3509
                accName = c.acc.Name
22✔
3510
        }
22✔
3511
        c.mu.Unlock()
22✔
3512
        return accName, delay
22✔
3513
}
3514

3515
// For the given remote Leafnode configuration, this function returns
3516
// if TLS is required, and if so, will return a clone of the TLS Config
3517
// (since some fields will be changed during handshake), the TLS server
3518
// name that is remembered, and the TLS timeout.
3519
func (c *client) leafNodeGetTLSConfigForSolicit(remote *leafNodeCfg) (bool, *tls.Config, string, float64) {
1,885✔
3520
        var (
1,885✔
3521
                tlsConfig  *tls.Config
1,885✔
3522
                tlsName    string
1,885✔
3523
                tlsTimeout float64
1,885✔
3524
        )
1,885✔
3525

1,885✔
3526
        remote.RLock()
1,885✔
3527
        defer remote.RUnlock()
1,885✔
3528

1,885✔
3529
        tlsRequired := remote.TLS || remote.TLSConfig != nil
1,885✔
3530
        if tlsRequired {
1,971✔
3531
                if remote.TLSConfig != nil {
137✔
3532
                        tlsConfig = remote.TLSConfig.Clone()
51✔
3533
                } else {
86✔
3534
                        tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}
35✔
3535
                }
35✔
3536
                tlsName = remote.tlsName
86✔
3537
                tlsTimeout = remote.TLSTimeout
86✔
3538
                if tlsTimeout == 0 {
138✔
3539
                        tlsTimeout = float64(TLS_TIMEOUT / time.Second)
52✔
3540
                }
52✔
3541
        }
3542

3543
        return tlsRequired, tlsConfig, tlsName, tlsTimeout
1,885✔
3544
}
3545

3546
// Initiates the LeafNode Websocket connection by:
3547
// - doing the TLS handshake if needed
3548
// - sending the HTTP request
3549
// - waiting for the HTTP response
3550
//
3551
// Since some bufio reader is used to consume the HTTP response, this function
3552
// returns the slice of buffered bytes (if any) so that the readLoop that will
3553
// be started after that consume those first before reading from the socket.
3554
// The boolean
3555
//
3556
// Lock held on entry.
3557
func (c *client) leafNodeSolicitWSConnection(opts *Options, rURL *url.URL, remote *leafNodeCfg) ([]byte, ClosedState, error) {
54✔
3558
        remote.RLock()
54✔
3559
        compress := remote.Websocket.Compression
54✔
3560
        // By default the server will mask outbound frames, but it can be disabled with this option.
54✔
3561
        noMasking := remote.Websocket.NoMasking
54✔
3562
        infoTimeout := remote.FirstInfoTimeout
54✔
3563
        remote.RUnlock()
54✔
3564
        // Will do the client-side TLS handshake if needed.
54✔
3565
        tlsRequired, err := c.leafClientHandshakeIfNeeded(remote, opts)
54✔
3566
        if err != nil {
58✔
3567
                // 0 will indicate that the connection was already closed
4✔
3568
                return nil, 0, err
4✔
3569
        }
4✔
3570

3571
        // For http request, we need the passed URL to contain either http or https scheme.
3572
        scheme := "http"
50✔
3573
        if tlsRequired {
58✔
3574
                scheme = "https"
8✔
3575
        }
8✔
3576
        // We will use the `/leafnode` path to tell the accepting WS server that it should
3577
        // create a LEAF connection, not a CLIENT.
3578
        // In case we use the user's URL path in the future, make sure we append the user's
3579
        // path to our `/leafnode` path.
3580
        lpath := leafNodeWSPath
50✔
3581
        if curPath := rURL.EscapedPath(); curPath != _EMPTY_ {
71✔
3582
                if curPath[0] == '/' {
42✔
3583
                        curPath = curPath[1:]
21✔
3584
                }
21✔
3585
                lpath = path.Join(curPath, lpath)
21✔
3586
        } else {
29✔
3587
                lpath = lpath[1:]
29✔
3588
        }
29✔
3589
        ustr := fmt.Sprintf("%s://%s/%s", scheme, rURL.Host, lpath)
50✔
3590
        u, _ := url.Parse(ustr)
50✔
3591
        req := &http.Request{
50✔
3592
                Method:     "GET",
50✔
3593
                URL:        u,
50✔
3594
                Proto:      "HTTP/1.1",
50✔
3595
                ProtoMajor: 1,
50✔
3596
                ProtoMinor: 1,
50✔
3597
                Header:     make(http.Header),
50✔
3598
                Host:       u.Host,
50✔
3599
        }
50✔
3600
        wsKey, err := wsMakeChallengeKey()
50✔
3601
        if err != nil {
50✔
3602
                return nil, WriteError, err
×
3603
        }
×
3604

3605
        req.Header["Upgrade"] = []string{"websocket"}
50✔
3606
        req.Header["Connection"] = []string{"Upgrade"}
50✔
3607
        req.Header["Sec-WebSocket-Key"] = []string{wsKey}
50✔
3608
        req.Header["Sec-WebSocket-Version"] = []string{"13"}
50✔
3609
        if compress {
61✔
3610
                req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue)
11✔
3611
        }
11✔
3612
        if noMasking {
60✔
3613
                req.Header.Add(wsNoMaskingHeader, wsNoMaskingValue)
10✔
3614
        }
10✔
3615
        c.nc.SetDeadline(time.Now().Add(infoTimeout))
50✔
3616
        if err := req.Write(c.nc); err != nil {
50✔
3617
                return nil, WriteError, err
×
3618
        }
×
3619

3620
        var resp *http.Response
50✔
3621

50✔
3622
        br := bufio.NewReaderSize(c.nc, MAX_CONTROL_LINE_SIZE)
50✔
3623
        resp, err = http.ReadResponse(br, req)
50✔
3624
        if err == nil &&
50✔
3625
                (resp.StatusCode != 101 ||
50✔
3626
                        !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
50✔
3627
                        !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
50✔
3628
                        resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) {
51✔
3629

1✔
3630
                err = fmt.Errorf("invalid websocket connection")
1✔
3631
        }
1✔
3632
        // Check compression extension...
3633
        if err == nil && c.ws.compress {
61✔
3634
                // Check that not only permessage-deflate extension is present, but that
11✔
3635
                // we also have server and client no context take over.
11✔
3636
                srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header, false)
11✔
3637

11✔
3638
                // If server does not support compression, then simply disable it in our side.
11✔
3639
                if !srvCompress {
16✔
3640
                        c.ws.compress = false
5✔
3641
                } else if !noCtxTakeover {
11✔
3642
                        err = fmt.Errorf("compression negotiation error")
×
3643
                }
×
3644
        }
3645
        // Same for no masking...
3646
        if err == nil && noMasking {
60✔
3647
                // Check if server accepts no masking
10✔
3648
                if resp.Header.Get(wsNoMaskingHeader) != wsNoMaskingValue {
11✔
3649
                        // Nope, need to mask our writes as any client would do.
1✔
3650
                        c.ws.maskwrite = true
1✔
3651
                }
1✔
3652
        }
3653
        if resp != nil {
84✔
3654
                resp.Body.Close()
34✔
3655
        }
34✔
3656
        if err != nil {
67✔
3657
                return nil, ReadError, err
17✔
3658
        }
17✔
3659
        c.Debugf("Leafnode compression=%v masking=%v", c.ws.compress, c.ws.maskwrite)
33✔
3660

33✔
3661
        var preBuf []byte
33✔
3662
        // We have to slurp whatever is in the bufio reader and pass that to the readloop.
33✔
3663
        if n := br.Buffered(); n != 0 {
34✔
3664
                preBuf, _ = br.Peek(n)
1✔
3665
        }
1✔
3666
        return preBuf, 0, nil
33✔
3667
}
3668

3669
const connectProcessTimeout = 2 * time.Second
3670

3671
// This is invoked for remote LEAF remote connections after processing the INFO
3672
// protocol.
3673
func (s *Server) leafNodeResumeConnectProcess(c *client) {
667✔
3674
        clusterName := s.ClusterName()
667✔
3675

667✔
3676
        c.mu.Lock()
667✔
3677
        if c.isClosed() {
667✔
3678
                c.mu.Unlock()
×
3679
                return
×
3680
        }
×
3681
        if err := c.sendLeafConnect(clusterName, c.headers); err != nil {
669✔
3682
                c.mu.Unlock()
2✔
3683
                c.closeConnection(WriteError)
2✔
3684
                return
2✔
3685
        }
2✔
3686

3687
        // Spin up the write loop.
3688
        s.startGoRoutine(func() { c.writeLoop() })
1,330✔
3689

3690
        // timeout leafNodeFinishConnectProcess
3691
        c.ping.tmr = time.AfterFunc(connectProcessTimeout, func() {
665✔
3692
                c.mu.Lock()
×
3693
                // check if leafNodeFinishConnectProcess was called and prevent later leafNodeFinishConnectProcess
×
3694
                if !c.flags.setIfNotSet(connectProcessFinished) {
×
3695
                        c.mu.Unlock()
×
3696
                        return
×
3697
                }
×
3698
                clearTimer(&c.ping.tmr)
×
3699
                closed := c.isClosed()
×
3700
                c.mu.Unlock()
×
3701
                if !closed {
×
3702
                        c.sendErrAndDebug("Stale Leaf Node Connection - Closing")
×
3703
                        c.closeConnection(StaleConnection)
×
3704
                }
×
3705
        })
3706
        c.mu.Unlock()
665✔
3707
        c.Debugf("Remote leafnode connect msg sent")
665✔
3708
}
3709

3710
// This is invoked for remote LEAF connections after processing the INFO
3711
// protocol and leafNodeResumeConnectProcess.
3712
// This will send LS+ the CONNECT protocol and register the leaf node.
3713
func (s *Server) leafNodeFinishConnectProcess(c *client) {
629✔
3714
        c.mu.Lock()
629✔
3715
        if !c.flags.setIfNotSet(connectProcessFinished) {
629✔
3716
                c.mu.Unlock()
×
3717
                return
×
3718
        }
×
3719
        if c.isClosed() {
629✔
3720
                c.mu.Unlock()
×
3721
                s.removeLeafNodeConnection(c)
×
3722
                return
×
3723
        }
×
3724
        remote := c.leaf.remote
629✔
3725
        if remote == nil || c.acc == nil {
630✔
3726
                c.mu.Unlock()
1✔
3727
                c.sendErr("Authorization Violation")
1✔
3728
                c.closeConnection(ProtocolViolation)
1✔
3729
                return
1✔
3730
        }
1✔
3731
        // Check if we will need to send the system connect event.
3732
        remote.RLock()
628✔
3733
        sendSysConnectEvent := remote.Hub
628✔
3734
        remote.RUnlock()
628✔
3735

628✔
3736
        // Capture account before releasing lock
628✔
3737
        acc := c.acc
628✔
3738
        // cancel connectProcessTimeout
628✔
3739
        clearTimer(&c.ping.tmr)
628✔
3740
        c.mu.Unlock()
628✔
3741

628✔
3742
        // Make sure we register with the account here.
628✔
3743
        if err := c.registerWithAccount(acc); err != nil {
631✔
3744
                if err == ErrTooManyAccountConnections {
3✔
3745
                        c.maxAccountConnExceeded()
×
3746
                        return
×
3747
                } else if err == ErrLeafNodeLoop {
6✔
3748
                        c.handleLeafNodeLoop(true)
3✔
3749
                        return
3✔
3750
                }
3✔
3751
                c.Errorf("Registering leaf with account %s resulted in error: %v", acc.Name, err)
×
3752
                c.closeConnection(ProtocolViolation)
×
3753
                return
×
3754
        }
3755
        if !s.addLeafNodeConnection(c, _EMPTY_, _EMPTY_, false) {
625✔
3756
                // Was not added, could be because the remote configuration has been removed.
×
3757
                c.closeConnection(ClientClosed)
×
3758
                return
×
3759
        }
×
3760
        s.initLeafNodeSmapAndSendSubs(c)
625✔
3761
        if sendSysConnectEvent {
643✔
3762
                s.sendLeafNodeConnect(acc)
18✔
3763
        }
18✔
3764
        s.accountConnectEvent(c)
625✔
3765

625✔
3766
        // The above functions are not running under the client lock, so it is
625✔
3767
        // possible that between the time we have started the read/write loops
625✔
3768
        // and now, that the connection was closed. This would leave the closed
625✔
3769
        // LN connection possibly registered with the account and/or the server's
625✔
3770
        // leafs map. So check if connection is closed, and if so, manually cleanup.
625✔
3771
        c.mu.Lock()
625✔
3772
        closed := c.isClosed()
625✔
3773
        if !closed {
1,250✔
3774
                c.setFirstPingTimer()
625✔
3775
        }
625✔
3776
        c.mu.Unlock()
625✔
3777
        if closed {
625✔
3778
                s.removeLeafNodeConnection(c)
×
3779
                if prev := acc.removeClient(c); prev == 1 {
×
3780
                        s.decActiveAccounts()
×
3781
                }
×
3782
        }
3783
}
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