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

nats-io / nats-server / 25844402541

13 May 2026 04:18PM UTC coverage: 80.18% (-2.9%) from 83.11%
25844402541

push

github

web-flow
Reduce lock contention on leafnode client  (#8139)

This series reduces lock contention on hub-side leaf connections:

- Start leafnode update traversal at a random offset to reduce lock
convoys.
- Use a client read lock for read only leaf permission checks, and move
deny filter setup to the delivery path so canSubscribe stays read-only.
- Disable subscribe permission sublist caches, since those caches can
still add lock contention even when callers only need a client read
lock.

74721 of 93191 relevant lines covered (80.18%)

569093.61 hits per line

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

89.67
/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,059✔
124
        return c.kind == LEAF && c.leaf != nil && c.leaf.remote != nil
2,059✔
125
}
2,059✔
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 {
13,214,842✔
130
        return c.kind == LEAF && c.leaf != nil && c.leaf.isSpoke
13,214,842✔
131
}
13,214,842✔
132

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

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

145
// This will spin up go routines to solicit the remote leaf node connections.
146
func (s *Server) solicitLeafNodeRemotes(remotes []*RemoteLeafOpts) {
1,254✔
147
        sysAccName := _EMPTY_
1,254✔
148
        sAcc := s.SystemAccount()
1,254✔
149
        if sAcc != nil {
2,485✔
150
                sysAccName = sAcc.Name
1,231✔
151
        }
1,231✔
152
        addRemote := func(r *RemoteLeafOpts, isSysAccRemote bool) *leafNodeCfg {
2,641✔
153
                s.mu.Lock()
1,387✔
154
                remote := newLeafNodeCfg(r)
1,387✔
155
                creds := remote.Credentials
1,387✔
156
                accName := remote.LocalAccount
1,387✔
157
                if s.leafRemoteCfgs == nil {
2,640✔
158
                        s.leafRemoteCfgs = make(map[*leafNodeCfg]struct{})
1,253✔
159
                }
1,253✔
160
                s.leafRemoteCfgs[remote] = struct{}{}
1,387✔
161
                // Print notice if
1,387✔
162
                if isSysAccRemote {
1,470✔
163
                        if len(remote.DenyExports) > 0 {
84✔
164
                                s.Noticef("Remote for System Account uses restricted export permissions")
1✔
165
                        }
1✔
166
                        if len(remote.DenyImports) > 0 {
84✔
167
                                s.Noticef("Remote for System Account uses restricted import permissions")
1✔
168
                        }
1✔
169
                }
170
                s.mu.Unlock()
1,387✔
171
                if creds != _EMPTY_ {
1,439✔
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
1,387✔
193
        }
194
        for _, r := range remotes {
2,641✔
195
                // We need to call this, even if the leaf is disabled. This is so that
1,387✔
196
                // the number of internal configuration matches the options' remote leaf
1,387✔
197
                // configuration required for configuration reload.
1,387✔
198
                remote := addRemote(r, r.LocalAccount == sysAccName)
1,387✔
199
                if !r.Disabled {
2,773✔
200
                        s.connectToRemoteLeafNodeAsynchronously(remote, true)
1,386✔
201
                }
1,386✔
202
        }
203
}
204

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

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

227
        // In local config mode, check that leafnode configuration refers to accounts that exist.
228
        if len(o.TrustedOperators) == 0 {
15,509✔
229
                accNames := map[string]struct{}{}
7,597✔
230
                for _, a := range o.Accounts {
16,165✔
231
                        accNames[a.Name] = struct{}{}
8,568✔
232
                }
8,568✔
233
                // global account is always created
234
                accNames[DEFAULT_GLOBAL_ACCOUNT] = struct{}{}
7,597✔
235
                // in the context of leaf nodes, empty account means global account
7,597✔
236
                accNames[_EMPTY_] = struct{}{}
7,597✔
237
                // system account either exists or, if not disabled, will be created
7,597✔
238
                if o.SystemAccount == _EMPTY_ && !o.NoSystemAccount {
13,691✔
239
                        accNames[DEFAULT_SYSTEM_ACCOUNT] = struct{}{}
6,094✔
240
                }
6,094✔
241
                checkAccountExists := func(accName string, cfgType string) error {
16,631✔
242
                        if _, ok := accNames[accName]; !ok {
9,036✔
243
                                return fmt.Errorf("cannot find local account %q specified in leafnode %s", accName, cfgType)
2✔
244
                        }
2✔
245
                        return nil
9,032✔
246
                }
247
                if err := checkAccountExists(o.LeafNode.Account, "authorization"); err != nil {
7,598✔
248
                        return err
1✔
249
                }
1✔
250
                for _, lu := range o.LeafNode.Users {
7,613✔
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 {
9,026✔
259
                        if err := checkAccountExists(r.LocalAccount, "remote"); err != nil {
1,431✔
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,444✔
282
                if err := validateAndNormalizeCompressionOption(&o.LeafNode.Compression, CompressionS2Auto); err != nil {
4,542✔
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 {
9,331✔
289
                // Validate proxy configuration
1,429✔
290
                if _, err := validateLeafNodeProxyOptions(rcfg); err != nil {
1,435✔
291
                        return err
6✔
292
                }
6✔
293

294
                if len(rcfg.URLs) >= 2 {
1,597✔
295
                        firstIsWS, ok := isWSURL(rcfg.URLs[0]), true
174✔
296
                        for i := 1; i < len(rcfg.URLs); i++ {
531✔
297
                                u := rcfg.URLs[i]
357✔
298
                                if isWS := isWSURL(u); isWS && !firstIsWS || !isWS && firstIsWS {
364✔
299
                                        ok = false
7✔
300
                                        break
7✔
301
                                }
302
                        }
303
                        if !ok {
181✔
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() {
1,416✔
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_ {
2,826✔
316
                        if err := validateAndNormalizeCompressionOption(&rcfg.Compression, CompressionS2Auto); err != nil {
1,415✔
317
                                return err
5✔
318
                        }
5✔
319
                }
320
        }
321

322
        if o.LeafNode.Port == 0 {
11,823✔
323
                return nil
3,939✔
324
        }
3,939✔
325

326
        // If MinVersion is defined, check that it is valid.
327
        if mv := o.LeafNode.MinVersion; mv != _EMPTY_ {
3,949✔
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,216✔
338
                return nil
3,273✔
339
        }
3,273✔
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_ {
671✔
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 {
669✔
346
                return fmt.Errorf("leafnode: %v", err)
×
347
        }
×
348
        return nil
669✔
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 {
7,967✔
366
        if len(o.LeafNode.Users) == 0 {
15,908✔
367
                return nil
7,941✔
368
        }
7,941✔
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,987✔
386
        var warnings []string
1,987✔
387

1,987✔
388
        if remote.Proxy.URL == _EMPTY_ {
3,948✔
389
                return warnings, nil
1,961✔
390
        }
1,961✔
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) {
258✔
442
        clearInProgress := true
258✔
443
        defer func() {
515✔
444
                s.grWG.Done()
257✔
445
                if clearInProgress {
325✔
446
                        remote.setConnectInProgress(false)
68✔
447
                }
68✔
448
        }()
449
        delay := s.getOpts().LeafNode.ReconnectInterval
258✔
450
        select {
258✔
451
        case <-time.After(delay):
195✔
452
        case <-remote.quitCh:
×
453
                return
×
454
        case <-s.quitCh:
63✔
455
                return
63✔
456
        }
457
        clearInProgress = !connectToRemoteLeafNode(s, remote, false)
195✔
458
}
459

460
// Creates a leafNodeCfg object that wraps the RemoteLeafOpts.
461
func newLeafNodeCfg(remote *RemoteLeafOpts) *leafNodeCfg {
1,387✔
462
        cfg := &leafNodeCfg{
1,387✔
463
                RemoteLeafOpts: remote,
1,387✔
464
                urls:           make([]*url.URL, 0, len(remote.URLs)),
1,387✔
465
                quitCh:         make(chan struct{}, 1),
1,387✔
466
        }
1,387✔
467
        if len(remote.DenyExports) > 0 || len(remote.DenyImports) > 0 {
1,397✔
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...)
1,387✔
480
        // If allowed to randomize, do it on our copy of URLs
1,387✔
481
        if !remote.NoRandomize {
2,773✔
482
                rand.Shuffle(len(cfg.urls), func(i, j int) {
1,720✔
483
                        cfg.urls[i], cfg.urls[j] = cfg.urls[j], cfg.urls[i]
334✔
484
                })
334✔
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 {
3,123✔
490
                cfg.saveTLSHostname(u)
1,736✔
491
                cfg.saveUserPassword(u)
1,736✔
492
                // If the url(s) have the "wss://" scheme, and we don't have a TLS
1,736✔
493
                // config, mark that we should be using TLS anyway.
1,736✔
494
                if !cfg.TLS && isWSSURL(u) {
1,737✔
495
                        cfg.TLS = true
1✔
496
                }
1✔
497
        }
498
        return cfg
1,387✔
499
}
500

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

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

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

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

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

548
// Will pick an URL from the list of available URLs.
549
func (cfg *leafNodeCfg) pickNextURL() *url.URL {
5,994✔
550
        cfg.Lock()
5,994✔
551
        defer cfg.Unlock()
5,994✔
552
        // If the current URL is the first in the list and we have more than
5,994✔
553
        // one URL, then move that one to end of the list.
5,994✔
554
        if cfg.curURL != nil && len(cfg.urls) > 1 && urlsAreEqual(cfg.curURL, cfg.urls[0]) {
8,381✔
555
                first := cfg.urls[0]
2,387✔
556
                copy(cfg.urls, cfg.urls[1:])
2,387✔
557
                cfg.urls[len(cfg.urls)-1] = first
2,387✔
558
        }
2,387✔
559
        cfg.curURL = cfg.urls[0]
5,994✔
560
        return cfg.curURL
5,994✔
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 {
1,583✔
573
        cfg.RLock()
1,583✔
574
        delay := cfg.connDelay
1,583✔
575
        cfg.RUnlock()
1,583✔
576
        return delay
1,583✔
577
}
1,583✔
578

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

586
// Ensure that non-exported options (used in tests) have
587
// been properly set.
588
func (s *Server) setLeafNodeNonExportedOptions() {
6,724✔
589
        opts := s.getOpts()
6,724✔
590
        s.leafNodeOpts.dialTimeout = opts.LeafNode.dialTimeout
6,724✔
591
        if s.leafNodeOpts.dialTimeout == 0 {
13,447✔
592
                // Use same timeouts as routes for now.
6,723✔
593
                s.leafNodeOpts.dialTimeout = DEFAULT_ROUTE_DIAL
6,723✔
594
        }
6,723✔
595
        s.leafNodeOpts.resolver = opts.LeafNode.resolver
6,724✔
596
        if s.leafNodeOpts.resolver == nil {
13,445✔
597
                s.leafNodeOpts.resolver = net.DefaultResolver
6,721✔
598
        }
6,721✔
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) {
1,388✔
667
        remote.setConnectInProgress(true)
1,388✔
668
        s.startGoRoutine(func() {
2,776✔
669
                defer s.grWG.Done()
1,388✔
670
                if !connectToRemoteLeafNode(s, remote, firstConnect) {
2,180✔
671
                        remote.setConnectInProgress(false)
792✔
672
                }
792✔
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 {
1,583✔
680

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

686
        opts := s.getOpts()
1,583✔
687
        reconnectDelay := opts.LeafNode.ReconnectInterval
1,583✔
688
        s.mu.RLock()
1,583✔
689
        dialTimeout := s.leafNodeOpts.dialTimeout
1,583✔
690
        resolver := s.leafNodeOpts.resolver
1,583✔
691
        var isSysAcc bool
1,583✔
692
        if s.eventsEnabled() {
3,131✔
693
                isSysAcc = remote.LocalAccount == s.sys.account.Name
1,548✔
694
        }
1,548✔
695
        jetstreamMigrateDelay := remote.JetStreamClusterMigrateDelay
1,583✔
696
        s.mu.RUnlock()
1,583✔
697

1,583✔
698
        // If we are sharing a system account and we are not standalone delay to gather some info prior.
1,583✔
699
        if firstConnect && isSysAcc && !s.standAloneMode() {
1,642✔
700
                s.Debugf("Will delay first leafnode connect to shared system account due to clustering")
59✔
701
                remote.setConnectDelay(sharedSysAccDelay)
59✔
702
        }
59✔
703

704
        if connDelay := remote.getConnectDelay(); connDelay > 0 {
1,648✔
705
                select {
65✔
706
                case <-time.After(connDelay):
61✔
707
                case <-remote.quitCh:
×
708
                        return false
×
709
                case <-s.quitCh:
4✔
710
                        return false
4✔
711
                }
712
                remote.setConnectDelay(0)
61✔
713
        }
714

715
        var conn net.Conn
1,579✔
716

1,579✔
717
        const connErrFmt = "Error trying to connect as leafnode to remote server %q (attempt %v): %v"
1,579✔
718

1,579✔
719
        // Capture proxy configuration once before the loop with proper locking
1,579✔
720
        remote.RLock()
1,579✔
721
        proxyURL := remote.Proxy.URL
1,579✔
722
        proxyUsername := remote.Proxy.Username
1,579✔
723
        proxyPassword := remote.Proxy.Password
1,579✔
724
        proxyTimeout := remote.Proxy.Timeout
1,579✔
725
        remote.RUnlock()
1,579✔
726

1,579✔
727
        // Set default proxy timeout if not specified
1,579✔
728
        if proxyTimeout == 0 {
3,150✔
729
                proxyTimeout = dialTimeout
1,571✔
730
        }
1,571✔
731

732
        attempts := 0
1,579✔
733

1,579✔
734
        // In case the migrate timer was created but not canceled, do it when
1,579✔
735
        // this function exits. Note that the timer would not be created if
1,579✔
736
        // `jetstreamMigrateDelay == 0`.
1,579✔
737
        if jetstreamMigrateDelay > 0 {
1,587✔
738
                defer remote.cancelMigrateTimer()
8✔
739
        }
8✔
740

741
        for s.isRunning() && remote.stillValid() {
7,573✔
742
                rURL := remote.pickNextURL()
5,994✔
743
                url, err := s.getRandomIP(resolver, rURL.Host, nil)
5,994✔
744
                if err == nil {
11,983✔
745
                        var ipStr string
5,989✔
746
                        if url != rURL.Host {
6,067✔
747
                                ipStr = fmt.Sprintf(" (%s)", url)
78✔
748
                        }
78✔
749
                        // Some test may want to disable remotes from connecting
750
                        if s.isLeafConnectDisabled() {
6,117✔
751
                                s.Debugf("Will not attempt to connect to remote server on %q%s, leafnodes currently disabled", rURL.Host, ipStr)
128✔
752
                                err = ErrLeafNodeDisabled
128✔
753
                        } else {
5,989✔
754
                                s.Debugf("Trying to connect as leafnode to remote server on %q%s", rURL.Host, ipStr)
5,861✔
755

5,861✔
756
                                // Check if proxy is configured
5,861✔
757
                                if proxyURL != _EMPTY_ {
5,869✔
758
                                        targetHost := rURL.Host
8✔
759
                                        // If URL doesn't include port, add the default port for the scheme
8✔
760
                                        if rURL.Port() == _EMPTY_ {
8✔
761
                                                defaultPort := "80"
×
762
                                                if rURL.Scheme == wsSchemePrefixTLS {
×
763
                                                        defaultPort = "443"
×
764
                                                }
×
765
                                                targetHost = net.JoinHostPort(rURL.Hostname(), defaultPort)
×
766
                                        }
767

768
                                        conn, err = establishHTTPProxyTunnel(proxyURL, targetHost, proxyTimeout, proxyUsername, proxyPassword)
8✔
769
                                } else {
5,853✔
770
                                        // Direct connection
5,853✔
771
                                        conn, err = natsDialTimeout("tcp", url, dialTimeout)
5,853✔
772
                                }
5,853✔
773
                        }
774
                }
775
                if err != nil {
11,203✔
776
                        jitter := time.Duration(rand.Int63n(int64(reconnectDelay)))
5,209✔
777
                        delay := reconnectDelay + jitter
5,209✔
778
                        attempts++
5,209✔
779
                        if s.shouldReportConnectErr(firstConnect, attempts) {
8,398✔
780
                                s.Errorf(connErrFmt, rURL.Host, attempts, err)
3,189✔
781
                        } else {
5,209✔
782
                                s.Debugf(connErrFmt, rURL.Host, attempts, err)
2,020✔
783
                        }
2,020✔
784
                        remote.Lock()
5,209✔
785
                        // if we are using a delay to start migrating assets, kick off a migrate timer.
5,209✔
786
                        if remote.jsMigrateTimer == nil && jetstreamMigrateDelay > 0 {
5,217✔
787
                                remote.jsMigrateTimer = time.AfterFunc(jetstreamMigrateDelay, func() {
16✔
788
                                        s.checkJetStreamMigrate(remote)
8✔
789
                                })
8✔
790
                        }
791
                        remote.Unlock()
5,209✔
792
                        select {
5,209✔
793
                        case <-s.quitCh:
783✔
794
                                return false
783✔
795
                        case <-remote.quitCh:
1✔
796
                                return false
1✔
797
                        case <-time.After(delay):
4,424✔
798
                                // Check if we should migrate any JetStream assets immediately while this remote is down.
4,424✔
799
                                // This will be used if JetStreamClusterMigrateDelay was not set
4,424✔
800
                                if jetstreamMigrateDelay == 0 {
8,777✔
801
                                        s.checkJetStreamMigrate(remote)
4,353✔
802
                                }
4,353✔
803
                                continue
4,424✔
804
                        }
805
                }
806
                remote.cancelMigrateTimer()
785✔
807
                // We can check here, but really we will have to check again when the server
785✔
808
                // is about to add to the `s.leafs` map later in the process.
785✔
809
                if !remote.stillValid() {
785✔
810
                        conn.Close()
×
811
                        return false
×
812
                }
×
813

814
                // We have a connection here to a remote server.
815
                // Go ahead and create our leaf node and return.
816
                s.createLeafNode(conn, rURL, remote, nil)
785✔
817

785✔
818
                // Clear any observer states if we had them.
785✔
819
                s.clearObserverState(remote)
785✔
820

785✔
821
                return true
785✔
822
        }
823

824
        return false
9✔
825
}
826

827
func (cfg *leafNodeCfg) cancelMigrateTimer() {
793✔
828
        cfg.Lock()
793✔
829
        stopAndClearTimer(&cfg.jsMigrateTimer)
793✔
830
        cfg.Unlock()
793✔
831
}
793✔
832

833
// This will clear any observer state such that stream or consumer assets on this server can become leaders again.
834
func (s *Server) clearObserverState(remote *leafNodeCfg) {
785✔
835
        s.mu.RLock()
785✔
836
        accName := remote.LocalAccount
785✔
837
        s.mu.RUnlock()
785✔
838

785✔
839
        acc, err := s.LookupAccount(accName)
785✔
840
        if err != nil {
787✔
841
                s.Warnf("Error looking up account [%s] checking for JetStream clear observer state on a leafnode", accName)
2✔
842
                return
2✔
843
        }
2✔
844

845
        acc.jscmMu.Lock()
783✔
846
        defer acc.jscmMu.Unlock()
783✔
847

783✔
848
        // Walk all streams looking for any clustered stream, skip otherwise.
783✔
849
        for _, mset := range acc.streams() {
803✔
850
                node := mset.raftNode()
20✔
851
                if node == nil {
32✔
852
                        // Not R>1
12✔
853
                        continue
12✔
854
                }
855
                // Check consumers
856
                for _, o := range mset.getConsumers() {
10✔
857
                        if n := o.raftNode(); n != nil {
4✔
858
                                // Ensure we can become a leader again.
2✔
859
                                n.SetObserver(false)
2✔
860
                        }
2✔
861
                }
862
                // Ensure we can not become a leader again.
863
                node.SetObserver(false)
8✔
864
        }
865
}
866

867
// Check to see if we should migrate any assets from this account.
868
func (s *Server) checkJetStreamMigrate(remote *leafNodeCfg) {
4,361✔
869
        s.mu.RLock()
4,361✔
870
        accName, shouldMigrate := remote.LocalAccount, remote.JetStreamClusterMigrate
4,361✔
871
        s.mu.RUnlock()
4,361✔
872

4,361✔
873
        if !shouldMigrate {
8,657✔
874
                return
4,296✔
875
        }
4,296✔
876

877
        acc, err := s.LookupAccount(accName)
65✔
878
        if err != nil {
65✔
879
                s.Warnf("Error looking up account [%s] checking for JetStream migration on a leafnode", accName)
×
880
                return
×
881
        }
×
882

883
        acc.jscmMu.Lock()
65✔
884
        defer acc.jscmMu.Unlock()
65✔
885

65✔
886
        // Walk all streams looking for any clustered stream, skip otherwise.
65✔
887
        // If we are the leader force stepdown.
65✔
888
        for _, mset := range acc.streams() {
97✔
889
                node := mset.raftNode()
32✔
890
                if node == nil {
32✔
891
                        // Not R>1
×
892
                        continue
×
893
                }
894
                // Collect any consumers
895
                for _, o := range mset.getConsumers() {
52✔
896
                        if n := o.raftNode(); n != nil {
40✔
897
                                n.StepDown()
20✔
898
                                // Ensure we can not become a leader while in this state.
20✔
899
                                n.SetObserver(true)
20✔
900
                        }
20✔
901
                }
902
                // Stepdown if this stream was leader.
903
                node.StepDown()
32✔
904
                // Ensure we can not become a leader while in this state.
32✔
905
                node.SetObserver(true)
32✔
906
        }
907
}
908

909
// Helper for checking.
910
func (s *Server) isLeafConnectDisabled() bool {
5,989✔
911
        s.mu.RLock()
5,989✔
912
        defer s.mu.RUnlock()
5,989✔
913
        return s.leafDisableConnect
5,989✔
914
}
5,989✔
915

916
// Save off the tlsName for when we use TLS and mix hostnames and IPs. IPs usually
917
// come from the server we connect to.
918
//
919
// We used to save the name only if there was a TLSConfig or scheme equal to "tls".
920
// However, this was causing failures for users that did not set the scheme (and
921
// their remote connections did not have a tls{} block).
922
// We now save the host name regardless in case the remote returns an INFO indicating
923
// that TLS is required.
924
//
925
// Lock held on entry.
926
func (cfg *leafNodeCfg) saveTLSHostname(u *url.URL) {
2,352✔
927
        if cfg.tlsName == _EMPTY_ && net.ParseIP(u.Hostname()) == nil {
2,369✔
928
                cfg.tlsName = u.Hostname()
17✔
929
        }
17✔
930
}
931

932
// Save off the username/password for when we connect using a bare URL
933
// that we get from the INFO protocol.
934
//
935
// Lock held on entry.
936
func (cfg *leafNodeCfg) saveUserPassword(u *url.URL) {
1,736✔
937
        if cfg.username == _EMPTY_ && u.User != nil {
2,028✔
938
                cfg.username = u.User.Username()
292✔
939
                cfg.password, _ = u.User.Password()
292✔
940
        }
292✔
941
}
942

943
// This starts the leafnode accept loop in a go routine, unless it
944
// is detected that the server has already been shutdown.
945
func (s *Server) startLeafNodeAcceptLoop() {
3,923✔
946
        // Snapshot server options.
3,923✔
947
        opts := s.getOpts()
3,923✔
948

3,923✔
949
        port := opts.LeafNode.Port
3,923✔
950
        if port == -1 {
7,670✔
951
                port = 0
3,747✔
952
        }
3,747✔
953

954
        if s.isShuttingDown() {
3,923✔
955
                return
×
956
        }
×
957

958
        s.mu.Lock()
3,923✔
959
        hp := net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(port))
3,923✔
960
        l, e := natsListen("tcp", hp)
3,923✔
961
        s.leafNodeListenerErr = e
3,923✔
962
        if e != nil {
3,923✔
963
                s.mu.Unlock()
×
964
                s.Fatalf("Error listening on leafnode port: %d - %v", opts.LeafNode.Port, e)
×
965
                return
×
966
        }
×
967

968
        s.Noticef("Listening for leafnode connections on %s",
3,923✔
969
                net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
3,923✔
970

3,923✔
971
        tlsRequired := opts.LeafNode.TLSConfig != nil
3,923✔
972
        tlsVerify := tlsRequired && opts.LeafNode.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert
3,923✔
973
        // Do not set compression in this Info object, it would possibly cause
3,923✔
974
        // issues when sending asynchronous INFO to the remote.
3,923✔
975
        info := Info{
3,923✔
976
                ID:            s.info.ID,
3,923✔
977
                Name:          s.info.Name,
3,923✔
978
                Version:       s.info.Version,
3,923✔
979
                GitCommit:     gitCommit,
3,923✔
980
                GoVersion:     runtime.Version(),
3,923✔
981
                AuthRequired:  true,
3,923✔
982
                TLSRequired:   tlsRequired,
3,923✔
983
                TLSVerify:     tlsVerify,
3,923✔
984
                MaxPayload:    s.info.MaxPayload, // TODO(dlc) - Allow override?
3,923✔
985
                Headers:       s.supportsHeaders(),
3,923✔
986
                JetStream:     opts.JetStream,
3,923✔
987
                Domain:        opts.JetStreamDomain,
3,923✔
988
                Proto:         s.getServerProto(),
3,923✔
989
                InfoOnConnect: true,
3,923✔
990
                JSApiLevel:    JSApiLevel,
3,923✔
991
        }
3,923✔
992
        // If we have selected a random port...
3,923✔
993
        if port == 0 {
7,670✔
994
                // Write resolved port back to options.
3,747✔
995
                opts.LeafNode.Port = l.Addr().(*net.TCPAddr).Port
3,747✔
996
        }
3,747✔
997

998
        s.leafNodeInfo = info
3,923✔
999
        // Possibly override Host/Port and set IP based on Cluster.Advertise
3,923✔
1000
        if err := s.setLeafNodeInfoHostPortAndIP(); err != nil {
3,923✔
1001
                s.Fatalf("Error setting leafnode INFO with LeafNode.Advertise value of %s, err=%v", opts.LeafNode.Advertise, err)
×
1002
                l.Close()
×
1003
                s.mu.Unlock()
×
1004
                return
×
1005
        }
×
1006
        s.leafURLsMap[s.leafNodeInfo.IP]++
3,923✔
1007
        s.generateLeafNodeInfoJSON()
3,923✔
1008

3,923✔
1009
        // Setup state that can enable shutdown
3,923✔
1010
        s.leafNodeListener = l
3,923✔
1011

3,923✔
1012
        // As of now, a server that does not have remotes configured would
3,923✔
1013
        // never solicit a connection, so we should not have to warn if
3,923✔
1014
        // InsecureSkipVerify is set in main LeafNodes config (since
3,923✔
1015
        // this TLS setting matters only when soliciting a connection).
3,923✔
1016
        // Still, warn if insecure is set in any of LeafNode block.
3,923✔
1017
        // We need to check remotes, even if tls is not required on accept.
3,923✔
1018
        warn := tlsRequired && opts.LeafNode.TLSConfig.InsecureSkipVerify
3,923✔
1019
        if !warn {
7,844✔
1020
                for _, r := range opts.LeafNode.Remotes {
4,111✔
1021
                        if r.TLSConfig != nil && r.TLSConfig.InsecureSkipVerify {
190✔
1022
                                warn = true
×
1023
                                break
×
1024
                        }
1025
                }
1026
        }
1027
        if warn {
3,925✔
1028
                s.Warnf(leafnodeTLSInsecureWarning)
2✔
1029
        }
2✔
1030
        go s.acceptConnections(l, "Leafnode", func(conn net.Conn) { s.createLeafNode(conn, nil, nil, nil) }, nil)
4,758✔
1031
        s.mu.Unlock()
3,923✔
1032
}
1033

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

1037
// clusterName is provided as argument to avoid lock ordering issues with the locked client c
1038
// Lock should be held entering here.
1039
func (c *client) sendLeafConnect(clusterName string, headers bool) error {
650✔
1040
        // We support basic user/pass and operator based user JWT with signatures.
650✔
1041
        cinfo := leafConnectInfo{
650✔
1042
                Version:       VERSION,
650✔
1043
                ID:            c.srv.info.ID,
650✔
1044
                Domain:        c.srv.info.Domain,
650✔
1045
                Name:          c.srv.info.Name,
650✔
1046
                Hub:           c.leaf.remote.Hub,
650✔
1047
                Cluster:       clusterName,
650✔
1048
                Headers:       headers,
650✔
1049
                JetStream:     c.acc.jetStreamConfigured(),
650✔
1050
                DenyPub:       c.leaf.remote.DenyImports,
650✔
1051
                Compression:   c.leaf.compression,
650✔
1052
                RemoteAccount: c.acc.GetName(),
650✔
1053
                Proto:         c.srv.getServerProto(),
650✔
1054
                Isolate:       c.leaf.remote.RequestIsolation,
650✔
1055
        }
650✔
1056

650✔
1057
        // If a signature callback is specified, this takes precedence over anything else.
650✔
1058
        if cb := c.leaf.remote.SignatureCB; cb != nil {
655✔
1059
                nonce := c.nonce
5✔
1060
                c.mu.Unlock()
5✔
1061
                jwt, sigraw, err := cb(nonce)
5✔
1062
                c.mu.Lock()
5✔
1063
                if err == nil && c.isClosed() {
6✔
1064
                        err = ErrConnectionClosed
1✔
1065
                }
1✔
1066
                if err != nil {
7✔
1067
                        c.Errorf("Error signing the nonce: %v", err)
2✔
1068
                        return err
2✔
1069
                }
2✔
1070
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
3✔
1071
                cinfo.JWT, cinfo.Sig = jwt, sig
3✔
1072

1073
        } else if creds := c.leaf.remote.Credentials; creds != _EMPTY_ {
701✔
1074
                // Check for credentials first, that will take precedence..
56✔
1075
                c.Debugf("Authenticating with credentials file %q", c.leaf.remote.Credentials)
56✔
1076
                contents, err := os.ReadFile(creds)
56✔
1077
                if err != nil {
56✔
1078
                        c.Errorf("%v", err)
×
1079
                        return err
×
1080
                }
×
1081
                defer wipeSlice(contents)
56✔
1082
                items := credsRe.FindAllSubmatch(contents, -1)
56✔
1083
                if len(items) < 2 {
56✔
1084
                        c.Errorf("Credentials file malformed")
×
1085
                        return err
×
1086
                }
×
1087
                // First result should be the user JWT.
1088
                // We copy here so that the file containing the seed will be wiped appropriately.
1089
                raw := items[0][1]
56✔
1090
                tmp := make([]byte, len(raw))
56✔
1091
                copy(tmp, raw)
56✔
1092
                // Seed is second item.
56✔
1093
                kp, err := nkeys.FromSeed(items[1][1])
56✔
1094
                if err != nil {
56✔
1095
                        c.Errorf("Credentials file has malformed seed")
×
1096
                        return err
×
1097
                }
×
1098
                // Wipe our key on exit.
1099
                defer kp.Wipe()
56✔
1100

56✔
1101
                sigraw, _ := kp.Sign(c.nonce)
56✔
1102
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
56✔
1103
                cinfo.JWT = bytesToString(tmp)
56✔
1104
                cinfo.Sig = sig
56✔
1105
        } else if nkey := c.leaf.remote.Nkey; nkey != _EMPTY_ {
594✔
1106
                kp, err := nkeys.FromSeed([]byte(nkey))
5✔
1107
                if err != nil {
5✔
1108
                        c.Errorf("Remote nkey has malformed seed")
×
1109
                        return err
×
1110
                }
×
1111
                // Wipe our key on exit.
1112
                defer kp.Wipe()
5✔
1113
                sigraw, _ := kp.Sign(c.nonce)
5✔
1114
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
5✔
1115
                pkey, _ := kp.PublicKey()
5✔
1116
                cinfo.Nkey = pkey
5✔
1117
                cinfo.Sig = sig
5✔
1118
        }
1119
        // In addition, and this is to allow auth callout, set user/password or
1120
        // token if applicable.
1121
        if userInfo := c.leaf.remote.curURL.User; userInfo != nil {
966✔
1122
                cinfo.User = userInfo.Username()
318✔
1123
                var ok bool
318✔
1124
                cinfo.Pass, ok = userInfo.Password()
318✔
1125
                // For backward compatibility, if only username is provided, set both
318✔
1126
                // Token and User, not just Token.
318✔
1127
                if !ok {
327✔
1128
                        cinfo.Token = cinfo.User
9✔
1129
                }
9✔
1130
        } else if c.leaf.remote.username != _EMPTY_ {
337✔
1131
                cinfo.User = c.leaf.remote.username
7✔
1132
                cinfo.Pass = c.leaf.remote.password
7✔
1133
                // For backward compatibility, if only username is provided, set both
7✔
1134
                // Token and User, not just Token.
7✔
1135
                if cinfo.Pass == _EMPTY_ {
7✔
1136
                        cinfo.Token = cinfo.User
×
1137
                }
×
1138
        }
1139
        b, err := json.Marshal(cinfo)
648✔
1140
        if err != nil {
648✔
1141
                c.Errorf("Error marshaling CONNECT to remote leafnode: %v\n", err)
×
1142
                return err
×
1143
        }
×
1144
        // Although this call is made before the writeLoop is created,
1145
        // we don't really need to send in place. The protocol will be
1146
        // sent out by the writeLoop.
1147
        c.enqueueProto([]byte(fmt.Sprintf(ConProto, b)))
648✔
1148
        return nil
648✔
1149
}
1150

1151
// Makes a deep copy of the LeafNode Info structure.
1152
// The server lock is held on entry.
1153
func (s *Server) copyLeafNodeInfo() *Info {
2,619✔
1154
        clone := s.leafNodeInfo
2,619✔
1155
        // Copy the array of urls.
2,619✔
1156
        if len(s.leafNodeInfo.LeafNodeURLs) > 0 {
4,775✔
1157
                clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...)
2,156✔
1158
        }
2,156✔
1159
        return &clone
2,619✔
1160
}
1161

1162
// Adds a LeafNode URL that we get when a route connects to the Info structure.
1163
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
1164
// Returns a boolean indicating if the URL was added or not.
1165
// Server lock is held on entry
1166
func (s *Server) addLeafNodeURL(urlStr string) bool {
7,841✔
1167
        if s.leafURLsMap.addUrl(urlStr) {
15,677✔
1168
                s.generateLeafNodeInfoJSON()
7,836✔
1169
                return true
7,836✔
1170
        }
7,836✔
1171
        return false
5✔
1172
}
1173

1174
// Removes a LeafNode URL of the route that is disconnecting from the Info structure.
1175
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
1176
// Returns a boolean indicating if the URL was removed or not.
1177
// Server lock is held on entry.
1178
func (s *Server) removeLeafNodeURL(urlStr string) bool {
7,841✔
1179
        // Don't need to do this if we are removing the route connection because
7,841✔
1180
        // we are shuting down...
7,841✔
1181
        if s.isShuttingDown() {
12,076✔
1182
                return false
4,235✔
1183
        }
4,235✔
1184
        if s.leafURLsMap.removeUrl(urlStr) {
7,209✔
1185
                s.generateLeafNodeInfoJSON()
3,603✔
1186
                return true
3,603✔
1187
        }
3,603✔
1188
        return false
3✔
1189
}
1190

1191
// Server lock is held on entry
1192
func (s *Server) generateLeafNodeInfoJSON() {
15,362✔
1193
        s.leafNodeInfo.Cluster = s.cachedClusterName()
15,362✔
1194
        s.leafNodeInfo.LeafNodeURLs = s.leafURLsMap.getAsStringSlice()
15,362✔
1195
        s.leafNodeInfo.WSConnectURLs = s.websocket.connectURLsMap.getAsStringSlice()
15,362✔
1196
        s.leafNodeInfoJSON = generateInfoJSON(&s.leafNodeInfo)
15,362✔
1197
}
15,362✔
1198

1199
// Sends an async INFO protocol so that the connected servers can update
1200
// their list of LeafNode urls.
1201
func (s *Server) sendAsyncLeafNodeInfo() {
11,439✔
1202
        for _, c := range s.leafs {
11,537✔
1203
                c.mu.Lock()
98✔
1204
                c.enqueueProto(s.leafNodeInfoJSON)
98✔
1205
                c.mu.Unlock()
98✔
1206
        }
98✔
1207
}
1208

1209
// Called when an inbound leafnode connection is accepted or we create one for a solicited leafnode.
1210
func (s *Server) createLeafNode(conn net.Conn, rURL *url.URL, remote *leafNodeCfg, ws *websocket) *client {
1,649✔
1211
        // Snapshot server options.
1,649✔
1212
        opts := s.getOpts()
1,649✔
1213

1,649✔
1214
        maxPay := int32(opts.MaxPayload)
1,649✔
1215
        maxSubs := int32(opts.MaxSubs)
1,649✔
1216
        // For system, maxSubs of 0 means unlimited, so re-adjust here.
1,649✔
1217
        if maxSubs == 0 {
3,297✔
1218
                maxSubs = -1
1,648✔
1219
        }
1,648✔
1220
        now := time.Now().UTC()
1,649✔
1221

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

1,649✔
1226
        // If the leafnode subject interest should be isolated, flag it here.
1,649✔
1227
        s.optsMu.RLock()
1,649✔
1228
        if c.leaf.isolated = s.opts.LeafNode.IsolateLeafnodeInterest; !c.leaf.isolated && remote != nil {
2,432✔
1229
                c.leaf.isolated = remote.LocalIsolation
783✔
1230
        }
783✔
1231
        s.optsMu.RUnlock()
1,649✔
1232

1,649✔
1233
        // For accepted LN connections, ws will be != nil if it was accepted
1,649✔
1234
        // through the Websocket port.
1,649✔
1235
        c.ws = ws
1,649✔
1236

1,649✔
1237
        // For remote, check if the scheme starts with "ws", if so, we will initiate
1,649✔
1238
        // a remote Leaf Node connection as a websocket connection.
1,649✔
1239
        if remote != nil && rURL != nil && isWSURL(rURL) {
1,699✔
1240
                remote.RLock()
50✔
1241
                c.ws = &websocket{compress: remote.Websocket.Compression, maskwrite: !remote.Websocket.NoMasking}
50✔
1242
                remote.RUnlock()
50✔
1243
        }
50✔
1244

1245
        // Determines if we are soliciting the connection or not.
1246
        var solicited bool
1,649✔
1247
        var acc *Account
1,649✔
1248
        var remoteSuffix string
1,649✔
1249
        if remote != nil {
2,434✔
1250
                // For now, if lookup fails, we will constantly try
785✔
1251
                // to recreate this LN connection.
785✔
1252
                lacc := remote.LocalAccount
785✔
1253
                var err error
785✔
1254
                acc, err = s.LookupAccount(lacc)
785✔
1255
                if err != nil {
787✔
1256
                        // An account not existing is something that can happen with nats/http account resolver and the account
2✔
1257
                        // has not yet been pushed, or the request failed for other reasons.
2✔
1258
                        // remote needs to be set or retry won't happen
2✔
1259
                        c.leaf.remote = remote
2✔
1260
                        c.closeConnection(MissingAccount)
2✔
1261
                        s.Errorf("Unable to lookup account %s for solicited leafnode connection: %v", lacc, err)
2✔
1262
                        return nil
2✔
1263
                }
2✔
1264
                remoteSuffix = fmt.Sprintf(" for account: %s", acc.traceLabel())
783✔
1265
        }
1266

1267
        c.mu.Lock()
1,647✔
1268
        c.initClient()
1,647✔
1269
        c.Noticef("Leafnode connection created%s %s", remoteSuffix, c.opts.Name)
1,647✔
1270

1,647✔
1271
        var (
1,647✔
1272
                tlsFirst         bool
1,647✔
1273
                tlsFirstFallback time.Duration
1,647✔
1274
                infoTimeout      time.Duration
1,647✔
1275
        )
1,647✔
1276
        if remote != nil {
2,430✔
1277
                solicited = true
783✔
1278
                remote.Lock()
783✔
1279
                c.leaf.remote = remote
783✔
1280
                c.setPermissions(remote.perms)
783✔
1281
                if !c.leaf.remote.Hub {
1,548✔
1282
                        c.leaf.isSpoke = true
765✔
1283
                }
765✔
1284
                tlsFirst = remote.TLSHandshakeFirst
783✔
1285
                infoTimeout = remote.FirstInfoTimeout
783✔
1286
                remote.Unlock()
783✔
1287
                c.acc = acc
783✔
1288
        } else {
864✔
1289
                c.flags.set(expectConnect)
864✔
1290
                if ws != nil {
893✔
1291
                        c.Debugf("Leafnode compression=%v", c.ws.compress)
29✔
1292
                }
29✔
1293
                tlsFirst = opts.LeafNode.TLSHandshakeFirst
864✔
1294
                if f := opts.LeafNode.TLSHandshakeFirstFallback; f > 0 {
865✔
1295
                        tlsFirstFallback = f
1✔
1296
                }
1✔
1297
        }
1298
        c.mu.Unlock()
1,647✔
1299

1,647✔
1300
        var nonce [nonceLen]byte
1,647✔
1301
        var info *Info
1,647✔
1302

1,647✔
1303
        // Grab this before the client lock below.
1,647✔
1304
        if !solicited {
2,511✔
1305
                // Grab server variables
864✔
1306
                s.mu.Lock()
864✔
1307
                info = s.copyLeafNodeInfo()
864✔
1308
                // For tests that want to simulate old servers, do not set the compression
864✔
1309
                // on the INFO protocol if configured with CompressionNotSupported.
864✔
1310
                if cm := opts.LeafNode.Compression.Mode; cm != CompressionNotSupported {
1,727✔
1311
                        info.Compression = cm
863✔
1312
                }
863✔
1313
                // We always send a nonce for LEAF connections. Do not change that without
1314
                // taking into account presence of proxy trusted keys.
1315
                s.generateNonce(nonce[:])
864✔
1316
                s.mu.Unlock()
864✔
1317
        }
1318

1319
        // Grab lock
1320
        c.mu.Lock()
1,647✔
1321

1,647✔
1322
        var preBuf []byte
1,647✔
1323
        if solicited {
2,430✔
1324
                // For websocket connection, we need to send an HTTP request,
783✔
1325
                // and get the response before starting the readLoop to get
783✔
1326
                // the INFO, etc..
783✔
1327
                if c.isWebsocket() {
833✔
1328
                        var err error
50✔
1329
                        var closeReason ClosedState
50✔
1330

50✔
1331
                        preBuf, closeReason, err = c.leafNodeSolicitWSConnection(opts, rURL, remote)
50✔
1332
                        if err != nil {
71✔
1333
                                c.Errorf("Error soliciting websocket connection: %v", err)
21✔
1334
                                c.mu.Unlock()
21✔
1335
                                if closeReason != 0 {
38✔
1336
                                        c.closeConnection(closeReason)
17✔
1337
                                }
17✔
1338
                                return nil
21✔
1339
                        }
1340
                } else {
733✔
1341
                        // If configured to do TLS handshake first
733✔
1342
                        if tlsFirst {
737✔
1343
                                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
5✔
1344
                                        c.mu.Unlock()
1✔
1345
                                        return nil
1✔
1346
                                }
1✔
1347
                        }
1348
                        // We need to wait for the info, but not for too long.
1349
                        c.nc.SetReadDeadline(time.Now().Add(infoTimeout))
732✔
1350
                }
1351

1352
                // We will process the INFO from the readloop and finish by
1353
                // sending the CONNECT and finish registration later.
1354
        } else {
864✔
1355
                // Send our info to the other side.
864✔
1356
                // Remember the nonce we sent here for signatures, etc.
864✔
1357
                c.nonce = make([]byte, nonceLen)
864✔
1358
                copy(c.nonce, nonce[:])
864✔
1359
                info.Nonce = bytesToString(c.nonce)
864✔
1360
                info.CID = c.cid
864✔
1361
                proto := generateInfoJSON(info)
864✔
1362

864✔
1363
                var pre []byte
864✔
1364
                // We need first to check for "TLS First" fallback delay.
864✔
1365
                if tlsFirstFallback > 0 {
865✔
1366
                        // We wait and see if we are getting any data. Since we did not send
1✔
1367
                        // the INFO protocol yet, only clients that use TLS first should be
1✔
1368
                        // sending data (the TLS handshake). We don't really check the content:
1✔
1369
                        // if it is a rogue agent and not an actual client performing the
1✔
1370
                        // TLS handshake, the error will be detected when performing the
1✔
1371
                        // handshake on our side.
1✔
1372
                        pre = make([]byte, 4)
1✔
1373
                        c.nc.SetReadDeadline(time.Now().Add(tlsFirstFallback))
1✔
1374
                        n, _ := io.ReadFull(c.nc, pre[:])
1✔
1375
                        c.nc.SetReadDeadline(time.Time{})
1✔
1376
                        // If we get any data (regardless of possible timeout), we will proceed
1✔
1377
                        // with the TLS handshake.
1✔
1378
                        if n > 0 {
1✔
1379
                                pre = pre[:n]
×
1380
                        } else {
1✔
1381
                                // We did not get anything so we will send the INFO protocol.
1✔
1382
                                pre = nil
1✔
1383
                                // Set the boolean to false for the rest of the function.
1✔
1384
                                tlsFirst = false
1✔
1385
                        }
1✔
1386
                }
1387

1388
                if !tlsFirst {
1,723✔
1389
                        // We have to send from this go routine because we may
859✔
1390
                        // have to block for TLS handshake before we start our
859✔
1391
                        // writeLoop go routine. The other side needs to receive
859✔
1392
                        // this before it can initiate the TLS handshake..
859✔
1393
                        c.sendProtoNow(proto)
859✔
1394

859✔
1395
                        // The above call could have marked the connection as closed (due to TCP error).
859✔
1396
                        if c.isClosed() {
859✔
1397
                                c.mu.Unlock()
×
1398
                                c.closeConnection(WriteError)
×
1399
                                return nil
×
1400
                        }
×
1401
                }
1402

1403
                // Check to see if we need to spin up TLS.
1404
                if !c.isWebsocket() && info.TLSRequired {
948✔
1405
                        // If we have a prebuffer create a multi-reader.
84✔
1406
                        if len(pre) > 0 {
84✔
1407
                                c.nc = &tlsMixConn{c.nc, bytes.NewBuffer(pre)}
×
1408
                        }
×
1409
                        // Perform server-side TLS handshake.
1410
                        if err := c.doTLSServerHandshake(tlsHandshakeLeaf, opts.LeafNode.TLSConfig, opts.LeafNode.TLSTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
142✔
1411
                                c.mu.Unlock()
58✔
1412
                                return nil
58✔
1413
                        }
58✔
1414
                }
1415

1416
                // If the user wants the TLS handshake to occur first, now that it is
1417
                // done, send the INFO protocol.
1418
                if tlsFirst {
809✔
1419
                        c.flags.set(didTLSFirst)
3✔
1420
                        c.sendProtoNow(proto)
3✔
1421
                        if c.isClosed() {
3✔
1422
                                c.mu.Unlock()
×
1423
                                c.closeConnection(WriteError)
×
1424
                                return nil
×
1425
                        }
×
1426
                }
1427

1428
                // Leaf nodes will always require a CONNECT to let us know
1429
                // when we are properly bound to an account.
1430
                //
1431
                // If compression is configured, we can't set the authTimer here because
1432
                // it would cause the parser to fail any incoming protocol that is not a
1433
                // CONNECT (and we need to exchange INFO protocols for compression
1434
                // negotiation). So instead, use the ping timer until we are done with
1435
                // negotiation and can set the auth timer.
1436
                timeout := secondsToDuration(opts.LeafNode.AuthTimeout)
806✔
1437
                if needsCompression(opts.LeafNode.Compression.Mode) {
1,386✔
1438
                        c.ping.tmr = time.AfterFunc(timeout, func() {
585✔
1439
                                c.authTimeout()
5✔
1440
                        })
5✔
1441
                } else {
226✔
1442
                        c.setAuthTimer(timeout)
226✔
1443
                }
226✔
1444
        }
1445

1446
        // Keep track in case server is shutdown before we can successfully register.
1447
        if !s.addToTempClients(c.cid, c) {
1,568✔
1448
                c.mu.Unlock()
1✔
1449
                c.setNoReconnect()
1✔
1450
                c.closeConnection(ServerShutdown)
1✔
1451
                return nil
1✔
1452
        }
1✔
1453

1454
        // Spin up the read loop.
1455
        s.startGoRoutine(func() { c.readLoop(preBuf) })
3,132✔
1456

1457
        // We will spin the write loop for solicited connections only
1458
        // when processing the INFO and after switching to TLS if needed.
1459
        if !solicited {
2,372✔
1460
                s.startGoRoutine(func() { c.writeLoop() })
1,612✔
1461
        }
1462

1463
        c.mu.Unlock()
1,566✔
1464

1,566✔
1465
        return c
1,566✔
1466
}
1467

1468
// Will perform the client-side TLS handshake if needed. Assumes that this
1469
// is called by the solicit side (remote will be non nil). Returns `true`
1470
// if TLS is required, `false` otherwise.
1471
// Lock held on entry.
1472
func (c *client) leafClientHandshakeIfNeeded(remote *leafNodeCfg, opts *Options) (bool, error) {
1,845✔
1473
        // Check if TLS is required and gather TLS config variables.
1,845✔
1474
        tlsRequired, tlsConfig, tlsName, tlsTimeout := c.leafNodeGetTLSConfigForSolicit(remote)
1,845✔
1475
        if !tlsRequired {
3,604✔
1476
                return false, nil
1,759✔
1477
        }
1,759✔
1478

1479
        // If TLS required, peform handshake.
1480
        // Get the URL that was used to connect to the remote server.
1481
        rURL := remote.getCurrentURL()
86✔
1482

86✔
1483
        // Perform the client-side TLS handshake.
86✔
1484
        if resetTLSName, err := c.doTLSClientHandshake(tlsHandshakeLeaf, rURL, tlsConfig, tlsName, tlsTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
132✔
1485
                // Check if we need to reset the remote's TLS name.
46✔
1486
                if resetTLSName {
46✔
1487
                        remote.Lock()
×
1488
                        remote.tlsName = _EMPTY_
×
1489
                        remote.Unlock()
×
1490
                }
×
1491
                return false, err
46✔
1492
        }
1493
        return true, nil
40✔
1494
}
1495

1496
func (c *client) processLeafnodeInfo(info *Info) {
2,561✔
1497
        c.mu.Lock()
2,561✔
1498
        if c.leaf == nil || c.isClosed() {
2,562✔
1499
                c.mu.Unlock()
1✔
1500
                return
1✔
1501
        }
1✔
1502
        s := c.srv
2,560✔
1503
        opts := s.getOpts()
2,560✔
1504
        remote := c.leaf.remote
2,560✔
1505
        didSolicit := remote != nil
2,560✔
1506
        firstINFO := !c.flags.isSet(infoReceived)
2,560✔
1507

2,560✔
1508
        // In case of websocket, the TLS handshake has been already done.
2,560✔
1509
        // So check only for non websocket connections and for configurations
2,560✔
1510
        // where the TLS Handshake was not done first.
2,560✔
1511
        if didSolicit && !c.flags.isSet(handshakeComplete) && !c.isWebsocket() && !remote.TLSHandshakeFirst {
4,351✔
1512
                // If the server requires TLS, we need to set this in the remote
1,791✔
1513
                // otherwise if there is no TLS configuration block for the remote,
1,791✔
1514
                // the solicit side will not attempt to perform the TLS handshake.
1,791✔
1515
                if firstINFO && info.TLSRequired {
1,861✔
1516
                        // Check for TLS/proxy configuration mismatch
70✔
1517
                        if remote.Proxy.URL != _EMPTY_ && !remote.TLS && remote.TLSConfig == nil {
70✔
1518
                                c.mu.Unlock()
×
1519
                                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.")
×
1520
                                c.closeConnection(TLSHandshakeError)
×
1521
                                return
×
1522
                        }
×
1523
                        remote.TLS = true
70✔
1524
                }
1525
                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
1,832✔
1526
                        c.mu.Unlock()
41✔
1527
                        return
41✔
1528
                }
41✔
1529
        }
1530

1531
        // Check for compression, unless already done.
1532
        if firstINFO && !c.flags.isSet(compressionNegotiated) {
3,778✔
1533
                // A solicited leafnode connection must first receive a leafnode INFO.
1,259✔
1534
                // Classify wrong-port connections before any leaf-specific negotiation.
1,259✔
1535
                if didSolicit && (info.CID == 0 || info.LeafNodeURLs == nil) {
1,313✔
1536
                        c.mu.Unlock()
54✔
1537
                        c.Errorf(ErrConnectedToWrongPort.Error())
54✔
1538
                        c.closeConnection(WrongPort)
54✔
1539
                        return
54✔
1540
                }
54✔
1541

1542
                // Prevent from getting back here.
1543
                c.flags.set(compressionNegotiated)
1,205✔
1544

1,205✔
1545
                var co *CompressionOpts
1,205✔
1546
                if !didSolicit {
1,756✔
1547
                        co = &opts.LeafNode.Compression
551✔
1548
                } else {
1,205✔
1549
                        co = &remote.Compression
654✔
1550
                }
654✔
1551
                if needsCompression(co.Mode) {
2,395✔
1552
                        // Release client lock since following function will need server lock.
1,190✔
1553
                        c.mu.Unlock()
1,190✔
1554
                        compress, err := s.negotiateLeafCompression(c, didSolicit, info.Compression, co)
1,190✔
1555
                        if err != nil {
1,190✔
1556
                                c.sendErrAndErr(err.Error())
×
1557
                                c.closeConnection(ProtocolViolation)
×
1558
                                return
×
1559
                        }
×
1560
                        if compress {
2,288✔
1561
                                // Done for now, will get back another INFO protocol...
1,098✔
1562
                                return
1,098✔
1563
                        }
1,098✔
1564
                        // No compression because one side does not want/can't, so proceed.
1565
                        c.mu.Lock()
92✔
1566
                        // Check that the connection did not close if the lock was released.
92✔
1567
                        if c.isClosed() {
92✔
1568
                                c.mu.Unlock()
×
1569
                                return
×
1570
                        }
×
1571
                } else {
15✔
1572
                        // Coming from an old server, the Compression field would be the empty
15✔
1573
                        // string. For servers that are configured with CompressionNotSupported,
15✔
1574
                        // this makes them behave as old servers.
15✔
1575
                        if info.Compression == _EMPTY_ || co.Mode == CompressionNotSupported {
17✔
1576
                                c.leaf.compression = CompressionNotSupported
2✔
1577
                        } else {
15✔
1578
                                c.leaf.compression = CompressionOff
13✔
1579
                        }
13✔
1580
                }
1581
                // Accepting side does not normally process an INFO protocol during
1582
                // initial connection handshake. So we keep it consistent by returning
1583
                // if we are not soliciting.
1584
                if !didSolicit {
111✔
1585
                        // If we had created the ping timer instead of the auth timer, we will
4✔
1586
                        // clear the ping timer and set the auth timer now that the compression
4✔
1587
                        // negotiation is done.
4✔
1588
                        if info.Compression != _EMPTY_ && c.ping.tmr != nil {
5✔
1589
                                clearTimer(&c.ping.tmr)
1✔
1590
                                c.setAuthTimer(secondsToDuration(opts.LeafNode.AuthTimeout))
1✔
1591
                        }
1✔
1592
                        c.mu.Unlock()
4✔
1593
                        return
4✔
1594
                }
1595
                // Fall through and process the INFO protocol as usual.
1596
        }
1597

1598
        // Note: For now, only the initial INFO has a nonce. We
1599
        // will probably do auto key rotation at some point.
1600
        if firstINFO {
2,058✔
1601
                // Mark that the INFO protocol has been received.
695✔
1602
                c.flags.set(infoReceived)
695✔
1603
                // Prevent connecting to non leafnode port. Need to do this only for
695✔
1604
                // the first INFO, not for async INFO updates...
695✔
1605
                //
695✔
1606
                // Content of INFO sent by the server when accepting a tcp connection.
695✔
1607
                // -------------------------------------------------------------------
695✔
1608
                // Listen Port Of | CID | ClientConnectURLs | LeafNodeURLs | Gateway |
695✔
1609
                // -------------------------------------------------------------------
695✔
1610
                //      CLIENT    |  X* |        X**        |              |         |
695✔
1611
                //      ROUTE     |     |        X**        |      X***    |         |
695✔
1612
                //     GATEWAY    |     |                   |              |    X    |
695✔
1613
                //     LEAFNODE   |  X  |                   |       X      |         |
695✔
1614
                // -------------------------------------------------------------------
695✔
1615
                // *   Not on older servers.
695✔
1616
                // **  Not if "no advertise" is enabled.
695✔
1617
                // *** Not if leafnode's "no advertise" is enabled.
695✔
1618
                //
695✔
1619
                // Reject a cluster that contains spaces.
695✔
1620
                if info.Cluster != _EMPTY_ && strings.Contains(info.Cluster, " ") {
696✔
1621
                        c.mu.Unlock()
1✔
1622
                        c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
1623
                        c.closeConnection(ProtocolViolation)
1✔
1624
                        return
1✔
1625
                }
1✔
1626
                // For solicited outbound leaf connections, capture the remote's nonce.
1627
                // For inbound leaf connections, keep using the server-issued nonce that
1628
                // was sent in our initial INFO and must be signed in CONNECT.
1629
                if didSolicit {
1,344✔
1630
                        c.nonce = []byte(info.Nonce)
650✔
1631
                }
650✔
1632
                if info.TLSRequired && didSolicit {
723✔
1633
                        remote.TLS = true
29✔
1634
                }
29✔
1635
                supportsHeaders := c.srv.supportsHeaders()
694✔
1636
                c.headers = supportsHeaders && info.Headers
694✔
1637

694✔
1638
                // Remember the remote server.
694✔
1639
                // Pre 2.2.0 servers are not sending their server name.
694✔
1640
                // In that case, use info.ID, which, for those servers, matches
694✔
1641
                // the content of the field `Name` in the leafnode CONNECT protocol.
694✔
1642
                if info.Name == _EMPTY_ {
696✔
1643
                        c.leaf.remoteServer = info.ID
2✔
1644
                } else {
694✔
1645
                        c.leaf.remoteServer = info.Name
692✔
1646
                }
692✔
1647
                c.leaf.remoteDomain = info.Domain
694✔
1648
                c.leaf.remoteCluster = info.Cluster
694✔
1649
                // We send the protocol version in the INFO protocol.
694✔
1650
                // Keep track of it, so we know if this connection supports message
694✔
1651
                // tracing for instance.
694✔
1652
                c.opts.Protocol = info.Proto
694✔
1653
        }
1654

1655
        // For both initial INFO and async INFO protocols, Possibly
1656
        // update our list of remote leafnode URLs we can connect to,
1657
        // unless we are instructed not to.
1658
        if didSolicit && !remote.IgnoreDiscoveredServers &&
1,362✔
1659
                (len(info.LeafNodeURLs) > 0 || len(info.WSConnectURLs) > 0) {
2,633✔
1660
                // Consider the incoming array as the most up-to-date
1,271✔
1661
                // representation of the remote cluster's list of URLs.
1,271✔
1662
                c.updateLeafNodeURLs(info)
1,271✔
1663
        }
1,271✔
1664

1665
        // Only solicited leafnode connections trust permission updates from INFO.
1666
        if didSolicit && (info.Import != nil || info.Export != nil) {
1,381✔
1667
                perms := &Permissions{
19✔
1668
                        Publish:   info.Export,
19✔
1669
                        Subscribe: info.Import,
19✔
1670
                }
19✔
1671
                // Check if we have local deny clauses that we need to merge.
19✔
1672
                if remote := c.leaf.remote; remote != nil {
38✔
1673
                        if len(remote.DenyExports) > 0 {
20✔
1674
                                if perms.Publish == nil {
1✔
1675
                                        perms.Publish = &SubjectPermission{}
×
1676
                                }
×
1677
                                perms.Publish.Deny = append(perms.Publish.Deny, remote.DenyExports...)
1✔
1678
                        }
1679
                        if len(remote.DenyImports) > 0 {
20✔
1680
                                if perms.Subscribe == nil {
1✔
1681
                                        perms.Subscribe = &SubjectPermission{}
×
1682
                                }
×
1683
                                perms.Subscribe.Deny = append(perms.Subscribe.Deny, remote.DenyImports...)
1✔
1684
                        }
1685
                }
1686
                c.setPermissions(perms)
19✔
1687
        }
1688

1689
        var resumeConnect bool
1,362✔
1690

1,362✔
1691
        // If this is a remote connection and this is the first INFO protocol,
1,362✔
1692
        // then we need to finish the connect process by sending CONNECT, etc..
1,362✔
1693
        if firstINFO && didSolicit {
2,012✔
1694
                // Clear deadline that was set in createLeafNode while waiting for the INFO.
650✔
1695
                c.nc.SetDeadline(time.Time{})
650✔
1696
                resumeConnect = true
650✔
1697
        } else if !firstINFO && didSolicit {
1,986✔
1698
                c.leaf.remoteAccName = info.RemoteAccount
624✔
1699
        }
624✔
1700

1701
        // Check if we have the remote account information and if so make sure it's stored.
1702
        if info.RemoteAccount != _EMPTY_ {
1,976✔
1703
                if c.acc == nil {
615✔
1704
                        c.mu.Unlock()
1✔
1705
                        c.sendErr("Authorization Violation")
1✔
1706
                        c.closeConnection(ProtocolViolation)
1✔
1707
                        return
1✔
1708
                }
1✔
1709
                s.leafRemoteAccounts.Store(c.acc.Name, info.RemoteAccount)
613✔
1710
        }
1711
        c.mu.Unlock()
1,361✔
1712

1,361✔
1713
        finishConnect := info.ConnectInfo
1,361✔
1714
        if resumeConnect && s != nil {
2,011✔
1715
                s.leafNodeResumeConnectProcess(c)
650✔
1716
                if !info.InfoOnConnect {
650✔
1717
                        finishConnect = true
×
1718
                }
×
1719
        }
1720
        if finishConnect {
1,975✔
1721
                s.leafNodeFinishConnectProcess(c)
614✔
1722
        }
614✔
1723

1724
        // Check to see if we need to kick any internal source or mirror consumers.
1725
        // This will be a no-op if JetStream not enabled for this server or if the bound account
1726
        // does not have jetstream.
1727
        s.checkInternalSyncConsumers(c.acc)
1,361✔
1728
}
1729

1730
func (s *Server) negotiateLeafCompression(c *client, didSolicit bool, infoCompression string, co *CompressionOpts) (bool, error) {
1,190✔
1731
        // Negotiate the appropriate compression mode (or no compression)
1,190✔
1732
        cm, err := selectCompressionMode(co.Mode, infoCompression)
1,190✔
1733
        if err != nil {
1,190✔
1734
                return false, err
×
1735
        }
×
1736
        c.mu.Lock()
1,190✔
1737
        // For "auto" mode, set the initial compression mode based on RTT
1,190✔
1738
        if cm == CompressionS2Auto {
2,256✔
1739
                if c.rttStart.IsZero() {
2,132✔
1740
                        c.rtt = computeRTT(c.start)
1,066✔
1741
                }
1,066✔
1742
                cm = selectS2AutoModeBasedOnRTT(c.rtt, co.RTTThresholds)
1,066✔
1743
        }
1744
        // Keep track of the negotiated compression mode.
1745
        c.leaf.compression = cm
1,190✔
1746
        cid := c.cid
1,190✔
1747
        var nonce string
1,190✔
1748
        if !didSolicit {
1,740✔
1749
                nonce = bytesToString(c.nonce)
550✔
1750
        }
550✔
1751
        c.mu.Unlock()
1,190✔
1752

1,190✔
1753
        if !needsCompression(cm) {
1,282✔
1754
                return false, nil
92✔
1755
        }
92✔
1756

1757
        // If we end-up doing compression...
1758

1759
        // Generate an INFO with the chosen compression mode.
1760
        s.mu.Lock()
1,098✔
1761
        info := s.copyLeafNodeInfo()
1,098✔
1762
        info.Compression, info.CID, info.Nonce = compressionModeForInfoProtocol(co, cm), cid, nonce
1,098✔
1763
        infoProto := generateInfoJSON(info)
1,098✔
1764
        s.mu.Unlock()
1,098✔
1765

1,098✔
1766
        // If we solicited, then send this INFO protocol BEFORE switching
1,098✔
1767
        // to compression writer. However, if we did not, we send it after.
1,098✔
1768
        c.mu.Lock()
1,098✔
1769
        if didSolicit {
1,649✔
1770
                c.enqueueProto(infoProto)
551✔
1771
                // Make sure it is completely flushed (the pending bytes goes to
551✔
1772
                // 0) before proceeding.
551✔
1773
                for c.out.pb > 0 && !c.isClosed() {
1,101✔
1774
                        c.flushOutbound()
550✔
1775
                }
550✔
1776
        }
1777
        // This is to notify the readLoop that it should switch to a
1778
        // (de)compression reader.
1779
        c.in.flags.set(switchToCompression)
1,098✔
1780
        // Create the compress writer before queueing the INFO protocol for
1,098✔
1781
        // a route that did not solicit. It will make sure that that proto
1,098✔
1782
        // is sent with compression on.
1,098✔
1783
        c.out.cw = s2.NewWriter(nil, s2WriterOptions(cm)...)
1,098✔
1784
        if !didSolicit {
1,645✔
1785
                c.enqueueProto(infoProto)
547✔
1786
        }
547✔
1787
        c.mu.Unlock()
1,098✔
1788
        return true, nil
1,098✔
1789
}
1790

1791
// When getting a leaf node INFO protocol, use the provided
1792
// array of urls to update the list of possible endpoints.
1793
func (c *client) updateLeafNodeURLs(info *Info) {
1,271✔
1794
        cfg := c.leaf.remote
1,271✔
1795
        cfg.Lock()
1,271✔
1796
        defer cfg.Unlock()
1,271✔
1797

1,271✔
1798
        // We have ensured that if a remote has a WS scheme, then all are.
1,271✔
1799
        // So check if first is WS, then add WS URLs, otherwise, add non WS ones.
1,271✔
1800
        if len(cfg.URLs) > 0 && isWSURL(cfg.URLs[0]) {
1,329✔
1801
                // It does not really matter if we use "ws://" or "wss://" here since
58✔
1802
                // we will have already marked that the remote should use TLS anyway.
58✔
1803
                // But use proper scheme for log statements, etc...
58✔
1804
                proto := wsSchemePrefix
58✔
1805
                if cfg.TLS {
58✔
1806
                        proto = wsSchemePrefixTLS
×
1807
                }
×
1808
                c.doUpdateLNURLs(cfg, proto, info.WSConnectURLs)
58✔
1809
                return
58✔
1810
        }
1811
        c.doUpdateLNURLs(cfg, "nats-leaf", info.LeafNodeURLs)
1,213✔
1812
}
1813

1814
func (c *client) doUpdateLNURLs(cfg *leafNodeCfg, scheme string, URLs []string) {
1,271✔
1815
        cfg.urls = make([]*url.URL, 0, 1+len(URLs))
1,271✔
1816
        // Add the ones we receive in the protocol
1,271✔
1817
        for _, surl := range URLs {
3,454✔
1818
                url, err := url.Parse(fmt.Sprintf("%s://%s", scheme, surl))
2,183✔
1819
                if err != nil {
2,183✔
1820
                        // As per below, the URLs we receive should not have contained URL info, so this should be safe to log.
×
1821
                        c.Errorf("Error parsing url %q: %v", surl, err)
×
1822
                        continue
×
1823
                }
1824
                // Do not add if it's the same as what we already have configured.
1825
                var dup bool
2,183✔
1826
                for _, u := range cfg.URLs {
5,450✔
1827
                        // URLs that we receive never have user info, but the
3,267✔
1828
                        // ones that were configured may have. Simply compare
3,267✔
1829
                        // host and port to decide if they are equal or not.
3,267✔
1830
                        if url.Host == u.Host && url.Port() == u.Port() {
4,834✔
1831
                                dup = true
1,567✔
1832
                                break
1,567✔
1833
                        }
1834
                }
1835
                if !dup {
2,799✔
1836
                        cfg.urls = append(cfg.urls, url)
616✔
1837
                        cfg.saveTLSHostname(url)
616✔
1838
                }
616✔
1839
        }
1840
        // Add the configured one
1841
        cfg.urls = append(cfg.urls, cfg.URLs...)
1,271✔
1842
}
1843

1844
// Similar to setInfoHostPortAndGenerateJSON, but for leafNodeInfo.
1845
func (s *Server) setLeafNodeInfoHostPortAndIP() error {
3,923✔
1846
        opts := s.getOpts()
3,923✔
1847
        if opts.LeafNode.Advertise != _EMPTY_ {
3,934✔
1848
                advHost, advPort, err := parseHostPort(opts.LeafNode.Advertise, opts.LeafNode.Port)
11✔
1849
                if err != nil {
11✔
1850
                        return err
×
1851
                }
×
1852
                s.leafNodeInfo.Host = advHost
11✔
1853
                s.leafNodeInfo.Port = advPort
11✔
1854
        } else {
3,912✔
1855
                s.leafNodeInfo.Host = opts.LeafNode.Host
3,912✔
1856
                s.leafNodeInfo.Port = opts.LeafNode.Port
3,912✔
1857
                // If the host is "0.0.0.0" or "::" we need to resolve to a public IP.
3,912✔
1858
                // This will return at most 1 IP.
3,912✔
1859
                hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(s.leafNodeInfo.Host, false)
3,912✔
1860
                if err != nil {
3,912✔
1861
                        return err
×
1862
                }
×
1863
                if hostIsIPAny {
4,205✔
1864
                        if len(ips) == 0 {
293✔
1865
                                s.Errorf("Could not find any non-local IP for leafnode's listen specification %q",
×
1866
                                        s.leafNodeInfo.Host)
×
1867
                        } else {
293✔
1868
                                // Take the first from the list...
293✔
1869
                                s.leafNodeInfo.Host = ips[0]
293✔
1870
                        }
293✔
1871
                }
1872
        }
1873
        // Use just host:port for the IP
1874
        s.leafNodeInfo.IP = net.JoinHostPort(s.leafNodeInfo.Host, strconv.Itoa(s.leafNodeInfo.Port))
3,923✔
1875
        if opts.LeafNode.Advertise != _EMPTY_ {
3,934✔
1876
                s.Noticef("Advertise address for leafnode is set to %s", s.leafNodeInfo.IP)
11✔
1877
        }
11✔
1878
        return nil
3,923✔
1879
}
1880

1881
// Add the connection to the map of leaf nodes.
1882
// If `checkForDup` is true (invoked when a leafnode is accepted), then we check
1883
// if a connection already exists for the same server name and account.
1884
// That can happen when the remote is attempting to reconnect while the accepting
1885
// side did not detect the connection as broken yet.
1886
// But it can also happen when there is a misconfiguration and the remote is
1887
// creating two (or more) connections that bind to the same account on the accept
1888
// side.
1889
// When a duplicate is found, the new connection is accepted and the old is closed
1890
// (this solves the stale connection situation). An error is returned to help the
1891
// remote detect the misconfiguration when the duplicate is the result of that
1892
// misconfiguration.
1893
func (s *Server) addLeafNodeConnection(c *client, srvName, clusterName string, checkForDup bool) bool {
1,267✔
1894
        var accName string
1,267✔
1895
        c.mu.Lock()
1,267✔
1896
        cid := c.cid
1,267✔
1897
        acc := c.acc
1,267✔
1898
        if acc != nil {
2,534✔
1899
                accName = acc.Name
1,267✔
1900
        }
1,267✔
1901
        myRemoteDomain := c.leaf.remoteDomain
1,267✔
1902
        mySrvName := c.leaf.remoteServer
1,267✔
1903
        remoteAccName := c.leaf.remoteAccName
1,267✔
1904
        myClustName := c.leaf.remoteCluster
1,267✔
1905
        remote := c.leaf.remote
1,267✔
1906
        solicited := remote != nil
1,267✔
1907
        c.mu.Unlock()
1,267✔
1908

1,267✔
1909
        var old *client
1,267✔
1910
        s.mu.Lock()
1,267✔
1911
        // We check for empty because in some test we may send empty CONNECT{}
1,267✔
1912
        if checkForDup && srvName != _EMPTY_ {
1,884✔
1913
                for _, ol := range s.leafs {
976✔
1914
                        ol.mu.Lock()
359✔
1915
                        // We care here only about non solicited Leafnode. This function
359✔
1916
                        // is more about replacing stale connections than detecting loops.
359✔
1917
                        // We have code for the loop detection elsewhere, which also delays
359✔
1918
                        // attempt to reconnect.
359✔
1919
                        if !ol.isSolicitedLeafNode() && ol.leaf.remoteServer == srvName &&
359✔
1920
                                ol.leaf.remoteCluster == clusterName && ol.acc.Name == accName &&
359✔
1921
                                remoteAccName != _EMPTY_ && ol.leaf.remoteAccName == remoteAccName {
361✔
1922
                                old = ol
2✔
1923
                        }
2✔
1924
                        ol.mu.Unlock()
359✔
1925
                        if old != nil {
361✔
1926
                                break
2✔
1927
                        }
1928
                }
1929
        }
1930
        // Now that we are under the server lock and before adding it to the map,
1931
        // for a solicited leaf, we need to make sure that it has not been removed
1932
        // from the config or disabled.
1933
        if solicited {
1,878✔
1934
                // If no longer valid, do not add to the server map. The connection
611✔
1935
                // should have been marked so that it can't reconnect. When the caller
611✔
1936
                // calls closeConnection(), cleanup (including clearing the connect-
611✔
1937
                // in-progress flag) will occur at the appropriate time.
611✔
1938
                if !remote.stillValid() {
611✔
1939
                        // Prevent reconnect in case it was not yet done.
×
1940
                        c.setNoReconnect()
×
1941
                        s.mu.Unlock()
×
1942
                        s.removeFromTempClients(cid)
×
1943
                        return false
×
1944
                }
×
1945
                remote.setConnectInProgress(false)
611✔
1946
        }
1947
        // Store new connection in the map
1948
        s.leafs[cid] = c
1,267✔
1949
        s.mu.Unlock()
1,267✔
1950
        s.removeFromTempClients(cid)
1,267✔
1951

1,267✔
1952
        // If applicable, evict the old one.
1,267✔
1953
        if old != nil {
1,269✔
1954
                old.sendErrAndErr(DuplicateRemoteLeafnodeConnection.String())
2✔
1955
                old.closeConnection(DuplicateRemoteLeafnodeConnection)
2✔
1956
                c.Warnf("Replacing connection from same server")
2✔
1957
        }
2✔
1958

1959
        srvDecorated := func() string {
1,458✔
1960
                if myClustName == _EMPTY_ {
217✔
1961
                        return mySrvName
26✔
1962
                }
26✔
1963
                return fmt.Sprintf("%s/%s", mySrvName, myClustName)
165✔
1964
        }
1965

1966
        opts := s.getOpts()
1,267✔
1967
        sysAcc := s.SystemAccount()
1,267✔
1968
        js := s.getJetStream()
1,267✔
1969
        var meta *raft
1,267✔
1970
        if js != nil {
1,765✔
1971
                if mg := js.getMetaGroup(); mg != nil {
877✔
1972
                        meta = mg.(*raft)
379✔
1973
                }
379✔
1974
        }
1975
        blockMappingOutgoing := false
1,267✔
1976
        // Deny (non domain) JetStream API traffic unless system account is shared
1,267✔
1977
        // and domain names are identical and extending is not disabled
1,267✔
1978

1,267✔
1979
        // Check if backwards compatibility has been enabled and needs to be acted on
1,267✔
1980
        forceSysAccDeny := false
1,267✔
1981
        if len(opts.JsAccDefaultDomain) > 0 {
1,301✔
1982
                if acc == sysAcc {
45✔
1983
                        for _, d := range opts.JsAccDefaultDomain {
22✔
1984
                                if d == _EMPTY_ {
19✔
1985
                                        // Extending JetStream via leaf node is mutually exclusive with a domain mapping to the empty/default domain.
8✔
1986
                                        // As soon as one mapping to "" is found, disable the ability to extend JS via a leaf node.
8✔
1987
                                        c.Noticef("Not extending remote JetStream domain %q due to presence of empty default domain", myRemoteDomain)
8✔
1988
                                        forceSysAccDeny = true
8✔
1989
                                        break
8✔
1990
                                }
1991
                        }
1992
                } else if domain, ok := opts.JsAccDefaultDomain[accName]; ok && domain == _EMPTY_ {
37✔
1993
                        // for backwards compatibility with old setups that do not have a domain name set
14✔
1994
                        c.Debugf("Skipping deny %q for account %q due to default domain", jsAllAPI, accName)
14✔
1995
                        return true
14✔
1996
                }
14✔
1997
        }
1998

1999
        // If the server has JS disabled, it may still be part of a JetStream that could be extended.
2000
        // This is either signaled by js being disabled and a domain set,
2001
        // or in cases where no domain name exists, an extension hint is set.
2002
        // However, this is only relevant in mixed setups.
2003
        //
2004
        // If the system account connects but default domains are present, JetStream can't be extended.
2005
        if opts.JetStreamDomain != myRemoteDomain || (!opts.JetStream && (opts.JetStreamDomain == _EMPTY_ && opts.JetStreamExtHint != jsWillExtend)) ||
1,253✔
2006
                sysAcc == nil || acc == nil || forceSysAccDeny {
2,360✔
2007
                // If domain names mismatch always deny. This applies to system accounts as well as non system accounts.
1,107✔
2008
                // Not having a system account, account or JetStream disabled is considered a mismatch as well.
1,107✔
2009
                if acc != nil && acc == sysAcc {
1,232✔
2010
                        c.Noticef("System account connected from %s", srvDecorated())
125✔
2011
                        c.Noticef("JetStream not extended, domains differ")
125✔
2012
                        c.mergeDenyPermissionsLocked(both, denyAllJs)
125✔
2013
                        // When a remote with a system account is present in a server, unless otherwise disabled, the server will be
125✔
2014
                        // started in observer mode. Now that it is clear that this not used, turn the observer mode off.
125✔
2015
                        if solicited && meta != nil && meta.IsObserver() {
148✔
2016
                                meta.setObserver(false, extNotExtended)
23✔
2017
                                c.Debugf("Turning JetStream metadata controller Observer Mode off")
23✔
2018
                                // Take note that the domain was not extended to avoid this state from startup.
23✔
2019
                                writePeerState(js.config.StoreDir, meta.currentPeerState())
23✔
2020
                                // Meta controller can't be leader yet.
23✔
2021
                                // Yet it is possible that due to observer mode every server already stopped campaigning.
23✔
2022
                                // Therefore this server needs to be kicked into campaigning gear explicitly.
23✔
2023
                                meta.Campaign()
23✔
2024
                        }
23✔
2025
                } else {
982✔
2026
                        c.Noticef("JetStream using domains: local %q, remote %q", opts.JetStreamDomain, myRemoteDomain)
982✔
2027
                        c.mergeDenyPermissionsLocked(both, denyAllClientJs)
982✔
2028
                }
982✔
2029
                blockMappingOutgoing = true
1,107✔
2030
        } else if acc == sysAcc {
212✔
2031
                // system account and same domain
66✔
2032
                s.sys.client.Noticef("Extending JetStream domain %q as System Account connected from server %s",
66✔
2033
                        myRemoteDomain, srvDecorated())
66✔
2034
                // In an extension use case, pin leadership to server remotes connect to.
66✔
2035
                // Therefore, server with a remote that are not already in observer mode, need to be put into it.
66✔
2036
                if solicited && meta != nil && !meta.IsObserver() {
70✔
2037
                        meta.setObserver(true, extExtended)
4✔
2038
                        c.Debugf("Turning JetStream metadata controller Observer Mode on - System Account Connected")
4✔
2039
                        // Take note that the domain was not extended to avoid this state next startup.
4✔
2040
                        writePeerState(js.config.StoreDir, meta.currentPeerState())
4✔
2041
                        // If this server is the leader already, step down so a new leader can be elected (that is not an observer)
4✔
2042
                        meta.StepDown()
4✔
2043
                }
4✔
2044
        } else {
80✔
2045
                // This deny is needed in all cases (system account shared or not)
80✔
2046
                // If the system account is shared, jsAllAPI traffic will go through the system account.
80✔
2047
                // So in order to prevent duplicate delivery (from system and actual account) suppress it on the account.
80✔
2048
                // If the system account is NOT shared, jsAllAPI traffic has no business
80✔
2049
                c.Debugf("Adding deny %+v for account %q", denyAllClientJs, accName)
80✔
2050
                c.mergeDenyPermissionsLocked(both, denyAllClientJs)
80✔
2051
        }
80✔
2052
        // If we have a specified JetStream domain we will want to add a mapping to
2053
        // allow access cross domain for each non-system account.
2054
        if opts.JetStreamDomain != _EMPTY_ && opts.JetStream && acc != nil && acc != sysAcc {
1,495✔
2055
                for src, dest := range generateJSMappingTable(opts.JetStreamDomain) {
2,420✔
2056
                        if err := acc.AddMapping(src, dest); err != nil {
2,178✔
2057
                                c.Debugf("Error adding JetStream domain mapping: %s", err.Error())
×
2058
                        } else {
2,178✔
2059
                                c.Debugf("Adding JetStream Domain Mapping %q -> %s to account %q", src, dest, accName)
2,178✔
2060
                        }
2,178✔
2061
                }
2062
                if blockMappingOutgoing {
453✔
2063
                        src := fmt.Sprintf(jsDomainAPI, opts.JetStreamDomain)
211✔
2064
                        // make sure that messages intended for this domain, do not leave the cluster via this leaf node connection
211✔
2065
                        // This is a guard against a miss-config with two identical domain names and will only cover some forms
211✔
2066
                        // of this issue, not all of them.
211✔
2067
                        // This guards against a hub and a spoke having the same domain name.
211✔
2068
                        // But not two spokes having the same one and the request coming from the hub.
211✔
2069
                        c.mergeDenyPermissionsLocked(pub, []string{src})
211✔
2070
                        c.Debugf("Adding deny %q for outgoing messages to account %q", src, accName)
211✔
2071
                }
211✔
2072
        }
2073
        return true
1,253✔
2074
}
2075

2076
func (s *Server) removeLeafNodeConnection(c *client) {
1,649✔
2077
        s.mu.Lock()
1,649✔
2078
        c.mu.Lock()
1,649✔
2079
        cid := c.cid
1,649✔
2080
        if c.leaf != nil {
3,298✔
2081
                if c.leaf.tsubt != nil {
2,799✔
2082
                        c.leaf.tsubt.Stop()
1,150✔
2083
                        c.leaf.tsubt = nil
1,150✔
2084
                }
1,150✔
2085
                if c.leaf.gwSub != nil {
2,260✔
2086
                        s.gwLeafSubs.Remove(c.leaf.gwSub)
611✔
2087
                        // We need to set this to nil for GC to release the connection
611✔
2088
                        c.leaf.gwSub = nil
611✔
2089
                }
611✔
2090
                if remote := c.leaf.remote; remote != nil {
2,434✔
2091
                        // If "noReconnect" is true, then we won't attempt to reconnect, so
785✔
2092
                        // we will clear the "connect-in-progress" flag. However, if we can
785✔
2093
                        // reconnect, then we should set "connect-in-progress" to true while
785✔
2094
                        // we are under the server/client lock. The go routine that performs
785✔
2095
                        // the reconnect will be started later and there would be a gap with
785✔
2096
                        // the wrong flag value otherwise.
785✔
2097
                        remote.setConnectInProgress(!c.flags.isSet(noReconnect))
785✔
2098
                }
785✔
2099
        }
2100
        proxyKey := c.proxyKey
1,649✔
2101
        c.mu.Unlock()
1,649✔
2102
        delete(s.leafs, cid)
1,649✔
2103
        if proxyKey != _EMPTY_ {
1,653✔
2104
                s.removeProxiedConn(proxyKey, cid)
4✔
2105
        }
4✔
2106
        s.mu.Unlock()
1,649✔
2107
        s.removeFromTempClients(cid)
1,649✔
2108
}
2109

2110
// Connect information for solicited leafnodes.
2111
type leafConnectInfo struct {
2112
        Version   string   `json:"version,omitempty"`
2113
        Nkey      string   `json:"nkey,omitempty"`
2114
        JWT       string   `json:"jwt,omitempty"`
2115
        Sig       string   `json:"sig,omitempty"`
2116
        User      string   `json:"user,omitempty"`
2117
        Pass      string   `json:"pass,omitempty"`
2118
        Token     string   `json:"auth_token,omitempty"`
2119
        ID        string   `json:"server_id,omitempty"`
2120
        Domain    string   `json:"domain,omitempty"`
2121
        Name      string   `json:"name,omitempty"`
2122
        Hub       bool     `json:"is_hub,omitempty"`
2123
        Cluster   string   `json:"cluster,omitempty"`
2124
        Headers   bool     `json:"headers,omitempty"`
2125
        JetStream bool     `json:"jetstream,omitempty"`
2126
        DenyPub   []string `json:"deny_pub,omitempty"`
2127
        Isolate   bool     `json:"isolate,omitempty"`
2128

2129
        // There was an existing field called:
2130
        // >> Comp bool `json:"compression,omitempty"`
2131
        // that has never been used. With support for compression, we now need
2132
        // a field that is a string. So we use a different json tag:
2133
        Compression string `json:"compress_mode,omitempty"`
2134

2135
        // Just used to detect wrong connection attempts.
2136
        Gateway string `json:"gateway,omitempty"`
2137

2138
        // Tells the accept side which account the remote is binding to.
2139
        RemoteAccount string `json:"remote_account,omitempty"`
2140

2141
        // The accept side of a LEAF connection, unlike ROUTER and GATEWAY, receives
2142
        // only the CONNECT protocol, and no INFO. So we need to send the protocol
2143
        // version as part of the CONNECT. It will indicate if a connection supports
2144
        // some features, such as message tracing.
2145
        // We use `protocol` as the JSON tag, so this is automatically unmarshal'ed
2146
        // in the low level process CONNECT.
2147
        Proto int `json:"protocol,omitempty"`
2148
}
2149

2150
// processLeafNodeConnect will process the inbound connect args.
2151
// Once we are here we are bound to an account, so can send any interest that
2152
// we would have to the other side.
2153
func (c *client) processLeafNodeConnect(s *Server, arg []byte, lang string) error {
661✔
2154
        // Way to detect clients that incorrectly connect to the route listen
661✔
2155
        // port. Client provided "lang" in the CONNECT protocol while LEAFNODEs don't.
661✔
2156
        if lang != _EMPTY_ {
661✔
2157
                c.sendErrAndErr(ErrClientConnectedToLeafNodePort.Error())
×
2158
                c.closeConnection(WrongPort)
×
2159
                return ErrClientConnectedToLeafNodePort
×
2160
        }
×
2161

2162
        // Unmarshal as a leaf node connect protocol
2163
        proto := &leafConnectInfo{}
661✔
2164
        if err := json.Unmarshal(arg, proto); err != nil {
661✔
2165
                return err
×
2166
        }
×
2167

2168
        // Reject a cluster that contains spaces.
2169
        if proto.Cluster != _EMPTY_ && strings.Contains(proto.Cluster, " ") {
662✔
2170
                c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
2171
                c.closeConnection(ProtocolViolation)
1✔
2172
                return ErrClusterNameHasSpaces
1✔
2173
        }
1✔
2174

2175
        // Check for cluster name collisions.
2176
        if cn := s.cachedClusterName(); cn != _EMPTY_ && proto.Cluster != _EMPTY_ && proto.Cluster == cn {
663✔
2177
                c.sendErrAndErr(ErrLeafNodeHasSameClusterName.Error())
3✔
2178
                c.closeConnection(ClusterNamesIdentical)
3✔
2179
                return ErrLeafNodeHasSameClusterName
3✔
2180
        }
3✔
2181

2182
        // Reject if this has Gateway which means that it would be from a gateway
2183
        // connection that incorrectly connects to the leafnode port.
2184
        if proto.Gateway != _EMPTY_ {
657✔
2185
                errTxt := fmt.Sprintf("Rejecting connection from gateway %q on the leafnode port", proto.Gateway)
×
2186
                c.Errorf(errTxt)
×
2187
                c.sendErr(errTxt)
×
2188
                c.closeConnection(WrongGateway)
×
2189
                return ErrWrongGateway
×
2190
        }
×
2191

2192
        if mv := s.getOpts().LeafNode.MinVersion; mv != _EMPTY_ {
659✔
2193
                major, minor, update, _ := versionComponents(mv)
2✔
2194
                if !versionAtLeast(proto.Version, major, minor, update) {
3✔
2195
                        // Send back an INFO so recent remote servers process the rejection
1✔
2196
                        // cleanly, then close immediately. The soliciting side applies the
1✔
2197
                        // reconnect delay when it processes the error.
1✔
2198
                        s.sendPermsAndAccountInfo(c)
1✔
2199
                        c.sendErrAndErr(fmt.Sprintf("%s %q", ErrLeafNodeMinVersionRejected, mv))
1✔
2200
                        c.closeConnection(MinimumVersionRequired)
1✔
2201
                        return ErrMinimumVersionRequired
1✔
2202
                }
1✔
2203
        }
2204

2205
        // Check if this server supports headers.
2206
        supportHeaders := c.srv.supportsHeaders()
656✔
2207

656✔
2208
        c.mu.Lock()
656✔
2209
        // Leaf Nodes do not do echo or verbose or pedantic.
656✔
2210
        c.opts.Verbose = false
656✔
2211
        c.opts.Echo = false
656✔
2212
        c.opts.Pedantic = false
656✔
2213
        // This inbound connection will be marked as supporting headers if this server
656✔
2214
        // support headers and the remote has sent in the CONNECT protocol that it does
656✔
2215
        // support headers too.
656✔
2216
        c.headers = supportHeaders && proto.Headers
656✔
2217
        // If the compression level is still not set, set it based on what has been
656✔
2218
        // given to us in the CONNECT protocol.
656✔
2219
        if c.leaf.compression == _EMPTY_ {
794✔
2220
                // But if proto.Compression is _EMPTY_, set it to CompressionNotSupported
138✔
2221
                if proto.Compression == _EMPTY_ {
180✔
2222
                        c.leaf.compression = CompressionNotSupported
42✔
2223
                } else {
138✔
2224
                        c.leaf.compression = proto.Compression
96✔
2225
                }
96✔
2226
        }
2227

2228
        // Remember the remote server.
2229
        c.leaf.remoteServer = proto.Name
656✔
2230
        // Remember the remote account name
656✔
2231
        c.leaf.remoteAccName = proto.RemoteAccount
656✔
2232
        // Remember if the leafnode requested isolation.
656✔
2233
        c.leaf.isolated = c.leaf.isolated || proto.Isolate
656✔
2234

656✔
2235
        // If the other side has declared itself a hub, so we will take on the spoke role.
656✔
2236
        if proto.Hub {
674✔
2237
                c.leaf.isSpoke = true
18✔
2238
        }
18✔
2239

2240
        // The soliciting side is part of a cluster.
2241
        if proto.Cluster != _EMPTY_ {
1,147✔
2242
                c.leaf.remoteCluster = proto.Cluster
491✔
2243
        }
491✔
2244

2245
        c.leaf.remoteDomain = proto.Domain
656✔
2246

656✔
2247
        // When a leaf solicits a connection to a hub, the perms that it will use on the soliciting leafnode's
656✔
2248
        // behalf are correct for them, but inside the hub need to be reversed since data is flowing in the opposite direction.
656✔
2249
        if !c.isSolicitedLeafNode() && c.perms != nil {
678✔
2250
                sp, pp := c.perms.sub, c.perms.pub
22✔
2251
                c.perms.sub, c.perms.pub = pp, sp
22✔
2252
                if c.opts.Import != nil {
43✔
2253
                        c.darray = c.opts.Import.Deny
21✔
2254
                } else {
22✔
2255
                        c.darray = nil
1✔
2256
                }
1✔
2257
        }
2258

2259
        // Set the Ping timer
2260
        c.setFirstPingTimer()
656✔
2261

656✔
2262
        // If we received pub deny permissions from the other end, merge with existing ones.
656✔
2263
        c.mergeDenyPermissions(pub, proto.DenyPub)
656✔
2264

656✔
2265
        acc := c.acc
656✔
2266
        c.mu.Unlock()
656✔
2267

656✔
2268
        // If the account is not set (e.g. connection was closed due to auth
656✔
2269
        // timeout while still being processed), bail out to avoid a panic.
656✔
2270
        if acc == nil {
656✔
2271
                c.closeConnection(MissingAccount)
×
2272
                return ErrMissingAccount
×
2273
        }
×
2274

2275
        // Register the cluster, even if empty, as long as we are acting as a hub.
2276
        if !proto.Hub {
1,294✔
2277
                acc.registerLeafNodeCluster(proto.Cluster)
638✔
2278
        }
638✔
2279

2280
        // Add in the leafnode here since we passed through auth at this point.
2281
        s.addLeafNodeConnection(c, proto.Name, proto.Cluster, true)
656✔
2282

656✔
2283
        // If we have permissions bound to this leafnode we need to send then back to the
656✔
2284
        // origin server for local enforcement.
656✔
2285
        s.sendPermsAndAccountInfo(c)
656✔
2286

656✔
2287
        // Create and initialize the smap since we know our bound account now.
656✔
2288
        // This will send all registered subs too.
656✔
2289
        s.initLeafNodeSmapAndSendSubs(c)
656✔
2290

656✔
2291
        // Announce the account connect event for a leaf node.
656✔
2292
        // This will be a no-op as needed.
656✔
2293
        s.sendLeafNodeConnect(c.acc)
656✔
2294

656✔
2295
        // Check to see if we need to kick any internal source or mirror consumers.
656✔
2296
        // This will be a no-op if JetStream not enabled for this server or if the bound account
656✔
2297
        // does not have jetstream.
656✔
2298
        s.checkInternalSyncConsumers(acc)
656✔
2299

656✔
2300
        return nil
656✔
2301
}
2302

2303
// checkInternalSyncConsumers
2304
func (s *Server) checkInternalSyncConsumers(acc *Account) {
2,017✔
2305
        // Grab our js
2,017✔
2306
        js := s.getJetStream()
2,017✔
2307

2,017✔
2308
        // Only applicable if we have JS and the leafnode has JS as well.
2,017✔
2309
        // We check for remote JS outside.
2,017✔
2310
        if !js.isEnabled() || acc == nil {
3,203✔
2311
                return
1,186✔
2312
        }
1,186✔
2313

2314
        // We will check all streams in our local account. They must be a leader and
2315
        // be sourcing or mirroring. We will check the external config on the stream itself
2316
        // if this is cross domain, or if the remote domain is empty, meaning we might be
2317
        // extending the system across this leafnode connection and hence we would be extending
2318
        // our own domain.
2319
        jsa := js.lookupAccount(acc)
831✔
2320
        if jsa == nil {
1,141✔
2321
                return
310✔
2322
        }
310✔
2323

2324
        var streams []*stream
521✔
2325
        jsa.mu.RLock()
521✔
2326
        for _, mset := range jsa.streams {
582✔
2327
                mset.cfgMu.RLock()
61✔
2328
                // We need to have a mirror or source defined.
61✔
2329
                // We do not want to force another lock here to look for leader status,
61✔
2330
                // so collect and after we release jsa will make sure.
61✔
2331
                if mset.cfg.Mirror != nil || len(mset.cfg.Sources) > 0 {
74✔
2332
                        streams = append(streams, mset)
13✔
2333
                }
13✔
2334
                mset.cfgMu.RUnlock()
61✔
2335
        }
2336
        jsa.mu.RUnlock()
521✔
2337

521✔
2338
        // Now loop through all candidates and check if we are the leader and have NOT
521✔
2339
        // created the sync up consumer.
521✔
2340
        for _, mset := range streams {
534✔
2341
                mset.retryDisconnectedSyncConsumers()
13✔
2342
        }
13✔
2343
}
2344

2345
// Returns the remote cluster name. This is set only once so does not require a lock.
2346
func (c *client) remoteCluster() string {
144,217✔
2347
        if c.leaf == nil {
144,217✔
2348
                return _EMPTY_
×
2349
        }
×
2350
        return c.leaf.remoteCluster
144,217✔
2351
}
2352

2353
// Sends back an info block to the soliciting leafnode to let it know about
2354
// its permission settings for local enforcement.
2355
func (s *Server) sendPermsAndAccountInfo(c *client) {
657✔
2356
        // Copy
657✔
2357
        s.mu.Lock()
657✔
2358
        info := s.copyLeafNodeInfo()
657✔
2359
        s.mu.Unlock()
657✔
2360
        c.mu.Lock()
657✔
2361
        info.CID = c.cid
657✔
2362
        info.Import = c.opts.Import
657✔
2363
        info.Export = c.opts.Export
657✔
2364
        info.RemoteAccount = c.acc.Name
657✔
2365
        // s.SystemAccount() uses an atomic operation and does not get the server lock, so this is safe.
657✔
2366
        info.IsSystemAccount = c.acc == s.SystemAccount()
657✔
2367
        info.ConnectInfo = true
657✔
2368
        c.enqueueProto(generateInfoJSON(info))
657✔
2369
        c.mu.Unlock()
657✔
2370
}
657✔
2371

2372
// Snapshot the current subscriptions from the sublist into our smap which
2373
// we will keep updated from now on.
2374
// Also send the registered subscriptions.
2375
func (s *Server) initLeafNodeSmapAndSendSubs(c *client) {
1,267✔
2376
        acc := c.acc
1,267✔
2377
        if acc == nil {
1,267✔
2378
                c.Debugf("Leafnode does not have an account bound")
×
2379
                return
×
2380
        }
×
2381
        // Collect all account subs here.
2382
        _subs := [1024]*subscription{}
1,267✔
2383
        subs := _subs[:0]
1,267✔
2384
        ims := []string{}
1,267✔
2385

1,267✔
2386
        // Hold the client lock otherwise there can be a race and miss some subs.
1,267✔
2387
        c.mu.Lock()
1,267✔
2388
        defer c.mu.Unlock()
1,267✔
2389

1,267✔
2390
        acc.mu.RLock()
1,267✔
2391
        accName := acc.Name
1,267✔
2392
        accNTag := acc.nameTag
1,267✔
2393

1,267✔
2394
        // To make printing look better when no friendly name present.
1,267✔
2395
        if accNTag != _EMPTY_ {
1,279✔
2396
                accNTag = "/" + accNTag
12✔
2397
        }
12✔
2398

2399
        // If we are solicited we only send interest for local clients.
2400
        if c.isSpokeLeafNode() {
1,878✔
2401
                acc.sl.localSubs(&subs, true)
611✔
2402
        } else {
1,267✔
2403
                acc.sl.All(&subs)
656✔
2404
        }
656✔
2405

2406
        // Check if we have an existing service import reply.
2407
        siReply := copyBytes(acc.siReply)
1,267✔
2408

1,267✔
2409
        // Since leaf nodes only send on interest, if the bound
1,267✔
2410
        // account has import services we need to send those over.
1,267✔
2411
        for isubj := range acc.imports.services {
6,014✔
2412
                if c.isSpokeLeafNode() && !c.canSubscribe(isubj) {
5,032✔
2413
                        c.Debugf("Not permitted to import service %q on behalf of %s%s", isubj, accName, accNTag)
285✔
2414
                        continue
285✔
2415
                }
2416
                ims = append(ims, isubj)
4,462✔
2417
        }
2418
        // Likewise for mappings.
2419
        for _, m := range acc.mappings {
3,538✔
2420
                if c.isSpokeLeafNode() && !c.canSubscribe(m.src) {
2,289✔
2421
                        c.Debugf("Not permitted to import mapping %q on behalf of %s%s", m.src, accName, accNTag)
18✔
2422
                        continue
18✔
2423
                }
2424
                ims = append(ims, m.src)
2,253✔
2425
        }
2426

2427
        // Create a unique subject that will be used for loop detection.
2428
        lds := acc.lds
1,267✔
2429
        acc.mu.RUnlock()
1,267✔
2430

1,267✔
2431
        // Check if we have to create the LDS.
1,267✔
2432
        if lds == _EMPTY_ {
2,251✔
2433
                lds = leafNodeLoopDetectionSubjectPrefix + nuid.Next()
984✔
2434
                acc.mu.Lock()
984✔
2435
                acc.lds = lds
984✔
2436
                acc.mu.Unlock()
984✔
2437
        }
984✔
2438

2439
        // Now check for gateway interest. Leafnodes will put this into
2440
        // the proper mode to propagate, but they are not held in the account.
2441
        gwsa := [16]*client{}
1,267✔
2442
        gws := gwsa[:0]
1,267✔
2443
        s.getOutboundGatewayConnections(&gws)
1,267✔
2444
        for _, cgw := range gws {
1,342✔
2445
                cgw.mu.Lock()
75✔
2446
                gw := cgw.gw
75✔
2447
                cgw.mu.Unlock()
75✔
2448
                if gw != nil {
150✔
2449
                        if ei, _ := gw.outsim.Load(accName); ei != nil {
150✔
2450
                                if e := ei.(*outsie); e != nil && e.sl != nil {
150✔
2451
                                        e.sl.All(&subs)
75✔
2452
                                }
75✔
2453
                        }
2454
                }
2455
        }
2456

2457
        applyGlobalRouting := s.gateway.enabled
1,267✔
2458
        if c.isSpokeLeafNode() {
1,878✔
2459
                // Add a fake subscription for this solicited leafnode connection
611✔
2460
                // so that we can send back directly for mapped GW replies.
611✔
2461
                // We need to keep track of this subscription so it can be removed
611✔
2462
                // when the connection is closed so that the GC can release it.
611✔
2463
                c.leaf.gwSub = &subscription{client: c, subject: []byte(gwReplyPrefix + ">")}
611✔
2464
                c.srv.gwLeafSubs.Insert(c.leaf.gwSub)
611✔
2465
        }
611✔
2466

2467
        // Now walk the results and add them to our smap
2468
        rc := c.leaf.remoteCluster
1,267✔
2469
        c.leaf.smap = make(map[string]int32)
1,267✔
2470
        for _, sub := range subs {
35,870✔
2471
                // Check perms regardless of role.
34,603✔
2472
                if c.perms != nil && !c.canSubscribe(string(sub.subject)) {
36,755✔
2473
                        c.Debugf("Not permitted to subscribe to %q on behalf of %s%s", sub.subject, accName, accNTag)
2,152✔
2474
                        continue
2,152✔
2475
                }
2476
                // Don't advertise interest from leafnodes to other isolated leafnodes.
2477
                if sub.client.kind == LEAF && c.isIsolatedLeafNode() {
32,466✔
2478
                        continue
15✔
2479
                }
2480
                // We ignore ourselves here.
2481
                // Also don't add the subscription if it has a origin cluster and the
2482
                // cluster name matches the one of the client we are sending to.
2483
                if c != sub.client && (sub.origin == nil || (bytesToString(sub.origin) != rc)) {
60,019✔
2484
                        count := int32(1)
27,583✔
2485
                        if len(sub.queue) > 0 && sub.qw > 0 {
27,593✔
2486
                                count = sub.qw
10✔
2487
                        }
10✔
2488
                        c.leaf.smap[keyFromSub(sub)] += count
27,583✔
2489
                        if c.leaf.tsub == nil {
28,767✔
2490
                                c.leaf.tsub = make(map[*subscription]struct{})
1,184✔
2491
                        }
1,184✔
2492
                        c.leaf.tsub[sub] = struct{}{}
27,583✔
2493
                }
2494
        }
2495
        // FIXME(dlc) - We need to update appropriately on an account claims update.
2496
        for _, isubj := range ims {
7,982✔
2497
                c.leaf.smap[isubj]++
6,715✔
2498
        }
6,715✔
2499
        // If we have gateways enabled we need to make sure the other side sends us responses
2500
        // that have been augmented from the original subscription.
2501
        // TODO(dlc) - Should we lock this down more?
2502
        if applyGlobalRouting {
1,362✔
2503
                c.leaf.smap[oldGWReplyPrefix+"*.>"]++
95✔
2504
                c.leaf.smap[gwReplyPrefix+">"]++
95✔
2505
        }
95✔
2506
        // Detect loops by subscribing to a specific subject and checking
2507
        // if this sub is coming back to us.
2508
        c.leaf.smap[lds]++
1,267✔
2509

1,267✔
2510
        // Check if we need to add an existing siReply to our map.
1,267✔
2511
        // This will be a prefix so add on the wildcard.
1,267✔
2512
        if siReply != nil {
1,286✔
2513
                wcsub := append(siReply, '>')
19✔
2514
                c.leaf.smap[string(wcsub)]++
19✔
2515
        }
19✔
2516
        // Queue all protocols. There is no max pending limit for LN connection,
2517
        // so we don't need chunking. The writes will happen from the writeLoop.
2518
        var b bytes.Buffer
1,267✔
2519
        for key, n := range c.leaf.smap {
25,918✔
2520
                c.writeLeafSub(&b, key, n)
24,651✔
2521
        }
24,651✔
2522
        if b.Len() > 0 {
2,534✔
2523
                c.enqueueProto(b.Bytes())
1,267✔
2524
        }
1,267✔
2525
        if c.leaf.tsub != nil {
2,452✔
2526
                // Clear the tsub map after 5 seconds.
1,185✔
2527
                c.leaf.tsubt = time.AfterFunc(5*time.Second, func() {
1,220✔
2528
                        c.mu.Lock()
35✔
2529
                        if c.leaf != nil {
70✔
2530
                                c.leaf.tsub = nil
35✔
2531
                                c.leaf.tsubt = nil
35✔
2532
                        }
35✔
2533
                        c.mu.Unlock()
35✔
2534
                })
2535
        }
2536
}
2537

2538
// updateInterestForAccountOnGateway called from gateway code when processing RS+ and RS-.
2539
func (s *Server) updateInterestForAccountOnGateway(accName string, sub *subscription, delta int32) {
197,728✔
2540
        // Since we're in the gateway's readLoop, and we would otherwise block, don't allow fetching.
197,728✔
2541
        acc, err := s.lookupOrFetchAccount(accName, false)
197,728✔
2542
        if acc == nil || err != nil {
198,079✔
2543
                s.Debugf("No or bad account for %q, failed to update interest from gateway", accName)
351✔
2544
                return
351✔
2545
        }
351✔
2546
        acc.updateLeafNodes(sub, delta)
197,377✔
2547
}
2548

2549
// updateLeafNodesEx will make sure to update the account smap for the subscription.
2550
// Will also forward to all leaf nodes as needed.
2551
// If `hubOnly` is true, then will update only leaf nodes that connect to this server
2552
// (that is, for which this server acts as a hub to them).
2553
func (acc *Account) updateLeafNodesEx(sub *subscription, delta int32, hubOnly bool) {
2,484,516✔
2554
        if acc == nil || sub == nil {
2,484,516✔
2555
                return
×
2556
        }
×
2557

2558
        // We will do checks for no leafnodes and same cluster here inline and under the
2559
        // general account read lock.
2560
        // If we feel we need to update the leafnodes we will do that out of line to avoid
2561
        // blocking routes or GWs.
2562

2563
        acc.mu.RLock()
2,484,516✔
2564
        // First check if we even have leafnodes here.
2,484,516✔
2565
        if acc.nleafs == 0 {
4,907,683✔
2566
                acc.mu.RUnlock()
2,423,167✔
2567
                return
2,423,167✔
2568
        }
2,423,167✔
2569

2570
        // Is this a loop detection subject.
2571
        isLDS := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
61,349✔
2572

61,349✔
2573
        // Capture the cluster even if its empty.
61,349✔
2574
        var cluster string
61,349✔
2575
        if sub.origin != nil {
105,983✔
2576
                cluster = bytesToString(sub.origin)
44,634✔
2577
        }
44,634✔
2578

2579
        // If we have an isolated cluster we can return early, as long as it is not a loop detection subject.
2580
        // Empty clusters will return false for the check.
2581
        if !isLDS && acc.isLeafNodeClusterIsolated(cluster) {
79,598✔
2582
                acc.mu.RUnlock()
18,249✔
2583
                return
18,249✔
2584
        }
18,249✔
2585

2586
        // We can release the general account lock.
2587
        acc.mu.RUnlock()
43,100✔
2588

43,100✔
2589
        // We can hold the list lock here to avoid having to copy a large slice.
43,100✔
2590
        acc.lmu.RLock()
43,100✔
2591
        defer acc.lmu.RUnlock()
43,100✔
2592

43,100✔
2593
        // Do this once.
43,100✔
2594
        subject := string(sub.subject)
43,100✔
2595

43,100✔
2596
        // Walk the connected leafnodes from a random starting point to avoid
43,100✔
2597
        // concurrent callers all contending over leafs in the same order.
43,100✔
2598
        nleafs := len(acc.lleafs)
43,100✔
2599
        start := 0
43,100✔
2600
        if nleafs > 1 {
50,507✔
2601
                start = rand.Intn(nleafs)
7,407✔
2602
        }
7,407✔
2603
        for i := 0; i < nleafs; i++ {
98,256✔
2604
                ln := acc.lleafs[(start+i)%nleafs]
55,156✔
2605
                if ln == sub.client {
84,402✔
2606
                        continue
29,246✔
2607
                }
2608
                ln.mu.RLock()
25,910✔
2609
                // Don't advertise interest from leafnodes to other isolated leafnodes.
25,910✔
2610
                if sub.client.kind == LEAF && ln.isIsolatedLeafNode() {
25,941✔
2611
                        ln.mu.RUnlock()
31✔
2612
                        continue
31✔
2613
                }
2614
                // If `hubOnly` is true, it means that we want to update only leafnodes
2615
                // that connect to this server (so isHubLeafNode() would return `true`).
2616
                if hubOnly && !ln.isHubLeafNode() {
25,885✔
2617
                        ln.mu.RUnlock()
6✔
2618
                        continue
6✔
2619
                }
2620
                // Check to make sure this sub does not have an origin cluster that matches the leafnode.
2621
                // If skipped, make sure that we still let go the "$LDS." subscription that allows
2622
                // the detection of loops as long as different cluster.
2623
                clusterDifferent := cluster != ln.remoteCluster()
25,873✔
2624
                update := (isLDS && clusterDifferent) ||
25,873✔
2625
                        ((cluster == _EMPTY_ || clusterDifferent) && (delta <= 0 || ln.canSubscribeInternal(subject)))
25,873✔
2626
                ln.mu.RUnlock()
25,873✔
2627
                if update {
48,201✔
2628
                        ln.mu.Lock()
22,328✔
2629
                        // The leaf role, isolation mode, and remote cluster are stable
22,328✔
2630
                        // for the connection. Recheck canSubscribe here since permissions
22,328✔
2631
                        // can change, and to initializes mperms for wildcard subscriptions
22,328✔
2632
                        // that collide with deny rules.
22,328✔
2633
                        if isLDS || delta <= 0 || ln.canSubscribe(subject) {
44,656✔
2634
                                ln.updateSmap(sub, delta, isLDS)
22,328✔
2635
                        }
22,328✔
2636
                        ln.mu.Unlock()
22,328✔
2637
                }
2638
        }
2639
}
2640

2641
// updateLeafNodes will make sure to update the account smap for the subscription.
2642
// Will also forward to all leaf nodes as needed.
2643
func (acc *Account) updateLeafNodes(sub *subscription, delta int32) {
2,484,493✔
2644
        acc.updateLeafNodesEx(sub, delta, false)
2,484,493✔
2645
}
2,484,493✔
2646

2647
// This will make an update to our internal smap and determine if we should send out
2648
// an interest update to the remote side.
2649
// Lock should be held.
2650
func (c *client) updateSmap(sub *subscription, delta int32, isLDS bool) {
22,328✔
2651
        if c.leaf.smap == nil {
22,337✔
2652
                return
9✔
2653
        }
9✔
2654

2655
        // If we are solicited make sure this is a local client or a non-solicited leaf node
2656
        skind := sub.client.kind
22,319✔
2657
        updateClient := skind == CLIENT || skind == SYSTEM || skind == JETSTREAM || skind == ACCOUNT
22,319✔
2658
        if !isLDS && c.isSpokeLeafNode() && !(updateClient || (skind == LEAF && !sub.client.isSpokeLeafNode())) {
29,440✔
2659
                return
7,121✔
2660
        }
7,121✔
2661

2662
        // For additions, check if that sub has just been processed during initLeafNodeSmapAndSendSubs
2663
        if delta > 0 && c.leaf.tsub != nil {
22,618✔
2664
                if _, present := c.leaf.tsub[sub]; present {
7,422✔
2665
                        delete(c.leaf.tsub, sub)
2✔
2666
                        if len(c.leaf.tsub) == 0 {
2✔
2667
                                c.leaf.tsub = nil
×
2668
                                c.leaf.tsubt.Stop()
×
2669
                                c.leaf.tsubt = nil
×
2670
                        }
×
2671
                        return
2✔
2672
                }
2673
        }
2674

2675
        key := keyFromSub(sub)
15,196✔
2676
        n, ok := c.leaf.smap[key]
15,196✔
2677
        if delta < 0 && !ok {
15,979✔
2678
                return
783✔
2679
        }
783✔
2680

2681
        // We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
2682
        update := sub.queue != nil || (n <= 0 && n+delta > 0) || (n > 0 && n+delta <= 0)
14,413✔
2683
        n += delta
14,413✔
2684
        if n > 0 {
25,382✔
2685
                c.leaf.smap[key] = n
10,969✔
2686
        } else {
14,413✔
2687
                delete(c.leaf.smap, key)
3,444✔
2688
        }
3,444✔
2689
        if update {
23,719✔
2690
                c.sendLeafNodeSubUpdate(key, n)
9,306✔
2691
        }
9,306✔
2692
}
2693

2694
// Used to force add subjects to the subject map.
2695
func (c *client) forceAddToSmap(subj string) {
4✔
2696
        c.mu.Lock()
4✔
2697
        defer c.mu.Unlock()
4✔
2698

4✔
2699
        if c.leaf.smap == nil {
4✔
2700
                return
×
2701
        }
×
2702
        n := c.leaf.smap[subj]
4✔
2703
        if n != 0 {
5✔
2704
                return
1✔
2705
        }
1✔
2706
        // Place into the map since it was not there.
2707
        c.leaf.smap[subj] = 1
3✔
2708
        c.sendLeafNodeSubUpdate(subj, 1)
3✔
2709
}
2710

2711
// Used to force remove a subject from the subject map.
2712
func (c *client) forceRemoveFromSmap(subj string) {
1✔
2713
        c.mu.Lock()
1✔
2714
        defer c.mu.Unlock()
1✔
2715

1✔
2716
        if c.leaf.smap == nil {
1✔
2717
                return
×
2718
        }
×
2719
        n := c.leaf.smap[subj]
1✔
2720
        if n == 0 {
1✔
2721
                return
×
2722
        }
×
2723
        n--
1✔
2724
        if n == 0 {
2✔
2725
                // Remove is now zero
1✔
2726
                delete(c.leaf.smap, subj)
1✔
2727
                c.sendLeafNodeSubUpdate(subj, 0)
1✔
2728
        } else {
1✔
2729
                c.leaf.smap[subj] = n
×
2730
        }
×
2731
}
2732

2733
// Send the subscription interest change to the other side.
2734
// Lock should be held.
2735
func (c *client) sendLeafNodeSubUpdate(key string, n int32) {
9,310✔
2736
        // If we are a spoke, we need to check if we are allowed to send this subscription over to the hub.
9,310✔
2737
        if c.isSpokeLeafNode() {
11,471✔
2738
                checkPerms := true
2,161✔
2739
                if len(key) > 0 && (key[0] == '$' || key[0] == '_') {
3,398✔
2740
                        if strings.HasPrefix(key, leafNodeLoopDetectionSubjectPrefix) ||
1,237✔
2741
                                strings.HasPrefix(key, oldGWReplyPrefix) ||
1,237✔
2742
                                strings.HasPrefix(key, gwReplyPrefix) {
1,316✔
2743
                                checkPerms = false
79✔
2744
                        }
79✔
2745
                }
2746
                if checkPerms {
4,243✔
2747
                        var subject string
2,082✔
2748
                        if sep := strings.IndexByte(key, ' '); sep != -1 {
2,564✔
2749
                                subject = key[:sep]
482✔
2750
                        } else {
2,082✔
2751
                                subject = key
1,600✔
2752
                        }
1,600✔
2753
                        if !c.canSubscribe(subject) {
2,082✔
2754
                                return
×
2755
                        }
×
2756
                }
2757
        }
2758
        // If we are here we can send over to the other side.
2759
        _b := [64]byte{}
9,310✔
2760
        b := bytes.NewBuffer(_b[:0])
9,310✔
2761
        c.writeLeafSub(b, key, n)
9,310✔
2762
        c.enqueueProto(b.Bytes())
9,310✔
2763
}
2764

2765
// Helper function to build the key.
2766
func keyFromSub(sub *subscription) string {
43,682✔
2767
        var sb strings.Builder
43,682✔
2768
        sb.Grow(len(sub.subject) + len(sub.queue) + 1)
43,682✔
2769
        sb.Write(sub.subject)
43,682✔
2770
        if sub.queue != nil {
47,361✔
2771
                // Just make the key subject spc group, e.g. 'foo bar'
3,679✔
2772
                sb.WriteByte(' ')
3,679✔
2773
                sb.Write(sub.queue)
3,679✔
2774
        }
3,679✔
2775
        return sb.String()
43,682✔
2776
}
2777

2778
const (
2779
        keyRoutedSub         = "R"
2780
        keyRoutedSubByte     = 'R'
2781
        keyRoutedLeafSub     = "L"
2782
        keyRoutedLeafSubByte = 'L'
2783
)
2784

2785
// Helper function to build the key that prevents collisions between normal
2786
// routed subscriptions and routed subscriptions on behalf of a leafnode.
2787
// Keys will look like this:
2788
// "R foo"          -> plain routed sub on "foo"
2789
// "R foo bar"      -> queue routed sub on "foo", queue "bar"
2790
// "L foo bar"      -> plain routed leaf sub on "foo", leaf "bar"
2791
// "L foo bar baz"  -> queue routed sub on "foo", queue "bar", leaf "baz"
2792
func keyFromSubWithOrigin(sub *subscription) string {
708,897✔
2793
        var sb strings.Builder
708,897✔
2794
        sb.Grow(2 + len(sub.origin) + 1 + len(sub.subject) + 1 + len(sub.queue))
708,897✔
2795
        leaf := len(sub.origin) > 0
708,897✔
2796
        if leaf {
723,607✔
2797
                sb.WriteByte(keyRoutedLeafSubByte)
14,710✔
2798
        } else {
708,897✔
2799
                sb.WriteByte(keyRoutedSubByte)
694,187✔
2800
        }
694,187✔
2801
        sb.WriteByte(' ')
708,897✔
2802
        sb.Write(sub.subject)
708,897✔
2803
        if sub.queue != nil {
735,303✔
2804
                sb.WriteByte(' ')
26,406✔
2805
                sb.Write(sub.queue)
26,406✔
2806
        }
26,406✔
2807
        if leaf {
723,607✔
2808
                sb.WriteByte(' ')
14,710✔
2809
                sb.Write(sub.origin)
14,710✔
2810
        }
14,710✔
2811
        return sb.String()
708,897✔
2812
}
2813

2814
// Lock should be held.
2815
func (c *client) writeLeafSub(w *bytes.Buffer, key string, n int32) {
33,961✔
2816
        if key == _EMPTY_ {
33,961✔
2817
                return
×
2818
        }
×
2819
        if n > 0 {
64,477✔
2820
                w.WriteString("LS+ " + key)
30,516✔
2821
                // Check for queue semantics, if found write n.
30,516✔
2822
                if strings.Contains(key, " ") {
32,823✔
2823
                        w.WriteString(" ")
2,307✔
2824
                        var b [12]byte
2,307✔
2825
                        var i = len(b)
2,307✔
2826
                        for l := n; l > 0; l /= 10 {
5,521✔
2827
                                i--
3,214✔
2828
                                b[i] = digits[l%10]
3,214✔
2829
                        }
3,214✔
2830
                        w.Write(b[i:])
2,307✔
2831
                        if c.trace {
2,307✔
2832
                                arg := fmt.Sprintf("%s %d", key, n)
×
2833
                                c.traceOutOp("LS+", []byte(arg))
×
2834
                        }
×
2835
                } else if c.trace {
28,226✔
2836
                        c.traceOutOp("LS+", []byte(key))
17✔
2837
                }
17✔
2838
        } else {
3,445✔
2839
                w.WriteString("LS- " + key)
3,445✔
2840
                if c.trace {
3,445✔
2841
                        c.traceOutOp("LS-", []byte(key))
×
2842
                }
×
2843
        }
2844
        w.WriteString(CR_LF)
33,961✔
2845
}
2846

2847
// processLeafSub will process an inbound sub request for the remote leaf node.
2848
func (c *client) processLeafSub(argo []byte) (err error) {
30,207✔
2849
        // Indicate activity.
30,207✔
2850
        c.in.subs++
30,207✔
2851

30,207✔
2852
        srv := c.srv
30,207✔
2853
        if srv == nil {
30,207✔
2854
                return nil
×
2855
        }
×
2856

2857
        // Copy so we do not reference a potentially large buffer
2858
        arg := make([]byte, len(argo))
30,207✔
2859
        copy(arg, argo)
30,207✔
2860

30,207✔
2861
        args := splitArg(arg)
30,207✔
2862
        sub := &subscription{client: c}
30,207✔
2863

30,207✔
2864
        delta := int32(1)
30,207✔
2865
        switch len(args) {
30,207✔
2866
        case 1:
27,931✔
2867
                sub.queue = nil
27,931✔
2868
        case 3:
2,276✔
2869
                sub.queue = args[1]
2,276✔
2870
                sub.qw = int32(parseSize(args[2]))
2,276✔
2871
                // TODO: (ik) We should have a non empty queue name and a queue
2,276✔
2872
                // weight >= 1. For 2.11, we may want to return an error if that
2,276✔
2873
                // is not the case, but for now just overwrite `delta` if queue
2,276✔
2874
                // weight is greater than 1 (it is possible after a reconnect/
2,276✔
2875
                // server restart to receive a queue weight > 1 for a new sub).
2,276✔
2876
                if sub.qw > 1 {
3,952✔
2877
                        delta = sub.qw
1,676✔
2878
                }
1,676✔
2879
        default:
×
2880
                return fmt.Errorf("processLeafSub Parse Error: '%s'", arg)
×
2881
        }
2882
        sub.subject = args[0]
30,207✔
2883

30,207✔
2884
        c.mu.Lock()
30,207✔
2885
        if c.isClosed() {
30,221✔
2886
                c.mu.Unlock()
14✔
2887
                return nil
14✔
2888
        }
14✔
2889

2890
        acc := c.acc
30,193✔
2891
        // Guard against LS+ arriving before CONNECT has been processed, which
30,193✔
2892
        // can happen when compression is enabled.
30,193✔
2893
        if acc == nil {
30,193✔
2894
                c.mu.Unlock()
×
2895
                c.sendErr("Authorization Violation")
×
2896
                c.closeConnection(ProtocolViolation)
×
2897
                return nil
×
2898
        }
×
2899
        // Check if we have a loop.
2900
        ldsPrefix := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
30,193✔
2901

30,193✔
2902
        if ldsPrefix && bytesToString(sub.subject) == acc.getLDSubject() {
30,200✔
2903
                c.mu.Unlock()
7✔
2904
                c.handleLeafNodeLoop(true)
7✔
2905
                return nil
7✔
2906
        }
7✔
2907

2908
        // Check permissions if applicable. (but exclude the $LDS, $GR and _GR_)
2909
        checkPerms := true
30,186✔
2910
        if sub.subject[0] == '$' || sub.subject[0] == '_' {
57,469✔
2911
                if ldsPrefix ||
27,283✔
2912
                        bytes.HasPrefix(sub.subject, []byte(oldGWReplyPrefix)) ||
27,283✔
2913
                        bytes.HasPrefix(sub.subject, []byte(gwReplyPrefix)) {
29,217✔
2914
                        checkPerms = false
1,934✔
2915
                }
1,934✔
2916
        }
2917

2918
        // If we are a hub check that we can publish to this subject.
2919
        if checkPerms {
58,438✔
2920
                subj := string(sub.subject)
28,252✔
2921
                if subjectIsLiteral(subj) && !c.pubAllowedFullCheck(subj, true, true) {
28,585✔
2922
                        c.mu.Unlock()
333✔
2923
                        c.leafSubPermViolation(sub.subject)
333✔
2924
                        c.Debugf(fmt.Sprintf("Permissions Violation for Subscription to %q", sub.subject))
333✔
2925
                        return nil
333✔
2926
                }
333✔
2927
        }
2928

2929
        // Check if we have a maximum on the number of subscriptions.
2930
        if c.subsAtLimit() {
29,861✔
2931
                c.mu.Unlock()
8✔
2932
                c.maxSubsExceeded()
8✔
2933
                return nil
8✔
2934
        }
8✔
2935

2936
        // If we have an origin cluster associated mark that in the sub.
2937
        if rc := c.remoteCluster(); rc != _EMPTY_ {
55,705✔
2938
                sub.origin = []byte(rc)
25,860✔
2939
        }
25,860✔
2940

2941
        // Like Routes, we store local subs by account and subject and optionally queue name.
2942
        // If we have a queue it will have a trailing weight which we do not want.
2943
        if sub.queue != nil {
31,829✔
2944
                sub.sid = arg[:len(arg)-len(args[2])-1]
1,984✔
2945
        } else {
29,845✔
2946
                sub.sid = arg
27,861✔
2947
        }
27,861✔
2948
        key := bytesToString(sub.sid)
29,845✔
2949
        osub := c.subs[key]
29,845✔
2950
        if osub == nil {
58,155✔
2951
                c.subs[key] = sub
28,310✔
2952
                // Now place into the account sl.
28,310✔
2953
                if err := acc.sl.Insert(sub); err != nil {
28,310✔
2954
                        delete(c.subs, key)
×
2955
                        c.mu.Unlock()
×
2956
                        c.Errorf("Could not insert subscription: %v", err)
×
2957
                        c.sendErr("Invalid Subscription")
×
2958
                        return nil
×
2959
                }
×
2960
        } else if sub.queue != nil {
3,069✔
2961
                // For a queue we need to update the weight.
1,534✔
2962
                delta = sub.qw - atomic.LoadInt32(&osub.qw)
1,534✔
2963
                atomic.StoreInt32(&osub.qw, sub.qw)
1,534✔
2964
                acc.sl.UpdateRemoteQSub(osub)
1,534✔
2965
        }
1,534✔
2966
        spoke := c.isSpokeLeafNode()
29,845✔
2967
        c.mu.Unlock()
29,845✔
2968

29,845✔
2969
        // Only add in shadow subs if a new sub or qsub.
29,845✔
2970
        if osub == nil {
58,155✔
2971
                if err := c.addShadowSubscriptions(acc, sub); err != nil {
28,310✔
2972
                        c.Errorf(err.Error())
×
2973
                }
×
2974
        }
2975

2976
        // If we are not solicited, treat leaf node subscriptions similar to a
2977
        // client subscription, meaning we forward them to routes, gateways and
2978
        // other leaf nodes as needed.
2979
        if !spoke {
40,368✔
2980
                // If we are routing add to the route map for the associated account.
10,523✔
2981
                srv.updateRouteSubscriptionMap(acc, sub, delta)
10,523✔
2982
                if srv.gateway.enabled {
11,712✔
2983
                        srv.gatewayUpdateSubInterest(acc.Name, sub, delta)
1,189✔
2984
                }
1,189✔
2985
        }
2986
        // Now check on leafnode updates for other leaf nodes. We understand solicited
2987
        // and non-solicited state in this call so we will do the right thing.
2988
        acc.updateLeafNodes(sub, delta)
29,845✔
2989

29,845✔
2990
        return nil
29,845✔
2991
}
2992

2993
// If the leafnode is a solicited, set the connect delay based on default
2994
// or private option (for tests). Sends the error to the other side, log and
2995
// close the connection.
2996
func (c *client) handleLeafNodeLoop(sendErr bool) {
17✔
2997
        accName, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterLoopDetected)
17✔
2998
        errTxt := fmt.Sprintf("Loop detected for leafnode account=%q. Delaying attempt to reconnect for %v", accName, delay)
17✔
2999
        if sendErr {
26✔
3000
                c.sendErr(errTxt)
9✔
3001
        }
9✔
3002

3003
        c.Errorf(errTxt)
17✔
3004
        // If we are here with "sendErr" false, it means that this is the server
17✔
3005
        // that received the error. The other side will have closed the connection,
17✔
3006
        // but does not hurt to close here too.
17✔
3007
        c.closeConnection(ProtocolViolation)
17✔
3008
}
3009

3010
// processLeafUnsub will process an inbound unsub request for the remote leaf node.
3011
func (c *client) processLeafUnsub(arg []byte) error {
3,091✔
3012
        // Indicate any activity, so pub and sub or unsubs.
3,091✔
3013
        c.in.subs++
3,091✔
3014

3,091✔
3015
        srv := c.srv
3,091✔
3016

3,091✔
3017
        c.mu.Lock()
3,091✔
3018
        if c.isClosed() {
3,133✔
3019
                c.mu.Unlock()
42✔
3020
                return nil
42✔
3021
        }
42✔
3022

3023
        acc := c.acc
3,049✔
3024
        // Guard against LS- arriving before CONNECT has been processed.
3,049✔
3025
        if acc == nil {
3,049✔
3026
                c.mu.Unlock()
×
3027
                c.sendErr("Authorization Violation")
×
3028
                c.closeConnection(ProtocolViolation)
×
3029
                return nil
×
3030
        }
×
3031

3032
        spoke := c.isSpokeLeafNode()
3,049✔
3033
        // We store local subs by account and subject and optionally queue name.
3,049✔
3034
        // LS- will have the arg exactly as the key.
3,049✔
3035
        sub, ok := c.subs[string(arg)]
3,049✔
3036
        if !ok {
3,058✔
3037
                // If not found, don't try to update routes/gws/leaf nodes.
9✔
3038
                c.mu.Unlock()
9✔
3039
                return nil
9✔
3040
        }
9✔
3041
        delta := int32(1)
3,040✔
3042
        if len(sub.queue) > 0 {
3,458✔
3043
                delta = sub.qw
418✔
3044
        }
418✔
3045
        c.mu.Unlock()
3,040✔
3046

3,040✔
3047
        c.unsubscribe(acc, sub, true, true)
3,040✔
3048
        if !spoke {
3,955✔
3049
                // If we are routing subtract from the route map for the associated account.
915✔
3050
                srv.updateRouteSubscriptionMap(acc, sub, -delta)
915✔
3051
                // Gateways
915✔
3052
                if srv.gateway.enabled {
1,105✔
3053
                        srv.gatewayUpdateSubInterest(acc.Name, sub, -delta)
190✔
3054
                }
190✔
3055
        }
3056
        // Now check on leafnode updates for other leaf nodes.
3057
        acc.updateLeafNodes(sub, -delta)
3,040✔
3058
        return nil
3,040✔
3059
}
3060

3061
func (c *client) processLeafHeaderMsgArgs(arg []byte) error {
228✔
3062
        // Unroll splitArgs to avoid runtime/heap issues
228✔
3063
        args := c.argsa[:0]
228✔
3064
        start := -1
228✔
3065
        for i, b := range arg {
12,717✔
3066
                switch b {
12,489✔
3067
                case ' ', '\t', '\r', '\n':
668✔
3068
                        if start >= 0 {
1,336✔
3069
                                args = append(args, arg[start:i])
668✔
3070
                                start = -1
668✔
3071
                        }
668✔
3072
                default:
11,821✔
3073
                        if start < 0 {
12,717✔
3074
                                start = i
896✔
3075
                        }
896✔
3076
                }
3077
        }
3078
        if start >= 0 {
456✔
3079
                args = append(args, arg[start:])
228✔
3080
        }
228✔
3081

3082
        c.pa.arg = arg
228✔
3083
        switch len(args) {
228✔
3084
        case 0, 1, 2:
×
3085
                return fmt.Errorf("processLeafHeaderMsgArgs Parse Error: '%s'", args)
×
3086
        case 3:
21✔
3087
                c.pa.reply = nil
21✔
3088
                c.pa.queues = nil
21✔
3089
                c.pa.hdb = args[1]
21✔
3090
                c.pa.hdr = parseSize(args[1])
21✔
3091
                c.pa.szb = args[2]
21✔
3092
                c.pa.size = parseSize(args[2])
21✔
3093
        case 4:
204✔
3094
                c.pa.reply = args[1]
204✔
3095
                c.pa.queues = nil
204✔
3096
                c.pa.hdb = args[2]
204✔
3097
                c.pa.hdr = parseSize(args[2])
204✔
3098
                c.pa.szb = args[3]
204✔
3099
                c.pa.size = parseSize(args[3])
204✔
3100
        default:
3✔
3101
                // args[1] is our reply indicator. Should be + or | normally.
3✔
3102
                if len(args[1]) != 1 {
3✔
3103
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3104
                }
×
3105
                switch args[1][0] {
3✔
3106
                case '+':
2✔
3107
                        c.pa.reply = args[2]
2✔
3108
                case '|':
1✔
3109
                        c.pa.reply = nil
1✔
3110
                default:
×
3111
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3112
                }
3113
                // Grab header size.
3114
                c.pa.hdb = args[len(args)-2]
3✔
3115
                c.pa.hdr = parseSize(c.pa.hdb)
3✔
3116

3✔
3117
                // Grab size.
3✔
3118
                c.pa.szb = args[len(args)-1]
3✔
3119
                c.pa.size = parseSize(c.pa.szb)
3✔
3120

3✔
3121
                // Grab queue names.
3✔
3122
                if c.pa.reply != nil {
5✔
3123
                        c.pa.queues = args[3 : len(args)-2]
2✔
3124
                } else {
3✔
3125
                        c.pa.queues = args[2 : len(args)-2]
1✔
3126
                }
1✔
3127
        }
3128
        if c.pa.hdr < 0 {
228✔
3129
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Header Size: '%s'", arg)
×
3130
        }
×
3131
        if c.pa.size < 0 {
228✔
3132
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Size: '%s'", args)
×
3133
        }
×
3134
        if c.pa.hdr > c.pa.size {
228✔
3135
                return fmt.Errorf("processLeafHeaderMsgArgs Header Size larger then TotalSize: '%s'", arg)
×
3136
        }
×
3137
        maxPayload := atomic.LoadInt32(&c.mpay)
228✔
3138
        if maxPayload != jwt.NoLimit && int64(c.pa.size) > int64(maxPayload) {
228✔
3139
                c.maxPayloadViolation(c.pa.size, maxPayload)
×
3140
                return ErrMaxPayload
×
3141
        }
×
3142

3143
        // Common ones processed after check for arg length
3144
        c.pa.subject = args[0]
228✔
3145

228✔
3146
        return nil
228✔
3147
}
3148

3149
func (c *client) processLeafMsgArgs(arg []byte) error {
65,339✔
3150
        // Unroll splitArgs to avoid runtime/heap issues
65,339✔
3151
        args := c.argsa[:0]
65,339✔
3152
        start := -1
65,339✔
3153
        for i, b := range arg {
2,155,688✔
3154
                switch b {
2,090,349✔
3155
                case ' ', '\t', '\r', '\n':
116,948✔
3156
                        if start >= 0 {
233,896✔
3157
                                args = append(args, arg[start:i])
116,948✔
3158
                                start = -1
116,948✔
3159
                        }
116,948✔
3160
                default:
1,973,401✔
3161
                        if start < 0 {
2,155,688✔
3162
                                start = i
182,287✔
3163
                        }
182,287✔
3164
                }
3165
        }
3166
        if start >= 0 {
130,678✔
3167
                args = append(args, arg[start:])
65,339✔
3168
        }
65,339✔
3169

3170
        c.pa.arg = arg
65,339✔
3171
        switch len(args) {
65,339✔
3172
        case 0, 1:
×
3173
                return fmt.Errorf("processLeafMsgArgs Parse Error: '%s'", args)
×
3174
        case 2:
36,444✔
3175
                c.pa.reply = nil
36,444✔
3176
                c.pa.queues = nil
36,444✔
3177
                c.pa.szb = args[1]
36,444✔
3178
                c.pa.size = parseSize(args[1])
36,444✔
3179
        case 3:
6,341✔
3180
                c.pa.reply = args[1]
6,341✔
3181
                c.pa.queues = nil
6,341✔
3182
                c.pa.szb = args[2]
6,341✔
3183
                c.pa.size = parseSize(args[2])
6,341✔
3184
        default:
22,554✔
3185
                // args[1] is our reply indicator. Should be + or | normally.
22,554✔
3186
                if len(args[1]) != 1 {
22,554✔
3187
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3188
                }
×
3189
                switch args[1][0] {
22,554✔
3190
                case '+':
160✔
3191
                        c.pa.reply = args[2]
160✔
3192
                case '|':
22,394✔
3193
                        c.pa.reply = nil
22,394✔
3194
                default:
×
3195
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3196
                }
3197
                // Grab size.
3198
                c.pa.szb = args[len(args)-1]
22,554✔
3199
                c.pa.size = parseSize(c.pa.szb)
22,554✔
3200

22,554✔
3201
                // Grab queue names.
22,554✔
3202
                if c.pa.reply != nil {
22,714✔
3203
                        c.pa.queues = args[3 : len(args)-1]
160✔
3204
                } else {
22,554✔
3205
                        c.pa.queues = args[2 : len(args)-1]
22,394✔
3206
                }
22,394✔
3207
        }
3208
        if c.pa.size < 0 {
65,339✔
3209
                return fmt.Errorf("processLeafMsgArgs Bad or Missing Size: '%s'", args)
×
3210
        }
×
3211
        maxPayload := atomic.LoadInt32(&c.mpay)
65,339✔
3212
        if maxPayload != jwt.NoLimit && int64(c.pa.size) > int64(maxPayload) {
65,339✔
3213
                c.maxPayloadViolation(c.pa.size, maxPayload)
×
3214
                return ErrMaxPayload
×
3215
        }
×
3216

3217
        // Common ones processed after check for arg length
3218
        c.pa.subject = args[0]
65,339✔
3219

65,339✔
3220
        return nil
65,339✔
3221
}
3222

3223
// processInboundLeafMsg is called to process an inbound msg from a leaf node.
3224
func (c *client) processInboundLeafMsg(msg []byte) {
64,259✔
3225
        // Update statistics
64,259✔
3226
        // The msg includes the CR_LF, so pull back out for accounting.
64,259✔
3227
        c.in.msgs++
64,259✔
3228
        c.in.bytes += int32(len(msg) - LEN_CR_LF)
64,259✔
3229

64,259✔
3230
        srv, acc, subject := c.srv, c.acc, string(c.pa.subject)
64,259✔
3231

64,259✔
3232
        // Mostly under testing scenarios.
64,259✔
3233
        if srv == nil || acc == nil {
64,259✔
3234
                return
×
3235
        }
×
3236

3237
        // Check that leaf messages respect the subject permissions.
3238
        if c.perms != nil && !c.leafMsgAllowed() {
64,264✔
3239
                c.leafPubPermViolation(c.pa.subject)
5✔
3240
                return
5✔
3241
        }
5✔
3242

3243
        // Match the subscriptions. We will use our own L1 map if
3244
        // it's still valid, avoiding contention on the shared sublist.
3245
        var r *SublistResult
64,254✔
3246
        var ok bool
64,254✔
3247

64,254✔
3248
        genid := atomic.LoadUint64(&c.acc.sl.genid)
64,254✔
3249
        if genid == c.in.genid && c.in.results != nil {
126,495✔
3250
                r, ok = c.in.results[subject]
62,241✔
3251
        } else {
64,254✔
3252
                // Reset our L1 completely.
2,013✔
3253
                c.in.results = make(map[string]*SublistResult)
2,013✔
3254
                c.in.genid = genid
2,013✔
3255
        }
2,013✔
3256

3257
        // Go back to the sublist data structure.
3258
        if !ok {
98,502✔
3259
                r = c.acc.sl.Match(subject)
34,248✔
3260
                // Prune the results cache. Keeps us from unbounded growth. Random delete.
34,248✔
3261
                if len(c.in.results) >= maxResultCacheSize {
35,133✔
3262
                        n := 0
885✔
3263
                        for subj := range c.in.results {
30,090✔
3264
                                delete(c.in.results, subj)
29,205✔
3265
                                if n++; n > pruneSize {
30,090✔
3266
                                        break
885✔
3267
                                }
3268
                        }
3269
                }
3270
                // Then add the new cache entry.
3271
                c.in.results[subject] = r
34,248✔
3272
        }
3273

3274
        // Collect queue names if needed.
3275
        var qnames [][]byte
64,254✔
3276

64,254✔
3277
        // Check for no interest, short circuit if so.
64,254✔
3278
        // This is the fanout scale.
64,254✔
3279
        if len(r.psubs)+len(r.qsubs) > 0 {
128,161✔
3280
                flag := pmrNoFlag
63,907✔
3281
                // If we have queue subs in this cluster, then if we run in gateway
63,907✔
3282
                // mode and the remote gateways have queue subs, then we need to
63,907✔
3283
                // collect the queue groups this message was sent to so that we
63,907✔
3284
                // exclude them when sending to gateways.
63,907✔
3285
                if len(r.qsubs) > 0 && c.srv.gateway.enabled &&
63,907✔
3286
                        atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 {
76,104✔
3287
                        flag |= pmrCollectQueueNames
12,197✔
3288
                }
12,197✔
3289
                // If this is a mapped subject that means the mapped interest
3290
                // is what got us here, but this might not have a queue designation
3291
                // If that is the case, make sure we ignore to process local queue subscribers.
3292
                if len(c.pa.mapped) > 0 && len(c.pa.queues) == 0 {
64,157✔
3293
                        flag |= pmrIgnoreEmptyQueueFilter
250✔
3294
                }
250✔
3295
                _, qnames = c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, flag)
63,907✔
3296
        }
3297

3298
        // Now deal with gateways
3299
        if c.srv.gateway.enabled {
77,272✔
3300
                c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, qnames, true)
13,018✔
3301
        }
13,018✔
3302
}
3303

3304
// Checks whether the inbound leaf message is allowed by the
3305
// connection's permissions. On the hub side this enforces what
3306
// the remote leaf may publish. On the spoke side this enforces
3307
// import restrictions such as deny_imports.
3308
func (c *client) leafMsgAllowed() bool {
60,509✔
3309
        wireSubject := c.pa.subject
60,509✔
3310
        if len(c.pa.mapped) > 0 {
60,759✔
3311
                // Mappings rewrite c.pa.subject to the internal
250✔
3312
                // destination. For leaf ACLs, need to check
250✔
3313
                // the original wire subject from the remote side.
250✔
3314
                wireSubject = c.pa.mapped
250✔
3315
        }
250✔
3316
        // Strip any gateway routing prefix for the permission check.
3317
        subjectToCheck, isGW := getGWRoutedSubjectOrSelf(wireSubject)
60,509✔
3318

60,509✔
3319
        // Service-import replies (_R_), JS ack subjects ($JS.ACK.)
60,509✔
3320
        // are internal routing subjects forwarded via LS+ without
60,509✔
3321
        // permission checks.
60,509✔
3322
        if isServiceReply(subjectToCheck) || isJSAckSubject(subjectToCheck) {
60,540✔
3323
                return true
31✔
3324
        }
31✔
3325

3326
        c.mu.RLock()
60,478✔
3327
        if c.isSpokeLeafNode() {
88,948✔
3328
                // Gateway routed replies are forwarded without
28,470✔
3329
                // permission checks.
28,470✔
3330
                if isGW || c.leafReceiveAllowed(subjectToCheck) {
56,938✔
3331
                        c.mu.RUnlock()
28,468✔
3332
                        return true
28,468✔
3333
                }
28,468✔
3334
        } else if c.leafSendAllowed(subjectToCheck) {
64,010✔
3335
                c.mu.RUnlock()
32,002✔
3336
                return true
32,002✔
3337
        }
32,002✔
3338
        c.mu.RUnlock()
8✔
3339

8✔
3340
        // Check tracked reply permissions (allow_responses).
8✔
3341
        // Use the pre-strip subject since deliverMsg tracks
8✔
3342
        // replies under the original form, which includes
8✔
3343
        // the GW routing prefix for routed requests.
8✔
3344
        c.mu.Lock()
8✔
3345
        defer c.mu.Unlock()
8✔
3346
        return c.responseAllowed(bytesToString(wireSubject))
8✔
3347
}
3348

3349
// Returns true if the leaf side ACLs allow importing this subject,
3350
// based on the permissions received over INFO and any local deny_imports.
3351
// At least a read lock must be held.
3352
func (c *client) leafReceiveAllowed(subject []byte) bool {
28,470✔
3353
        return c.canSubscribeInternal(bytesToString(subject))
28,470✔
3354
}
28,470✔
3355

3356
// Returns true if the hub side ACLs allow the remote leaf to send
3357
// this subject.
3358
// At least a read lock must be held.
3359
func (c *client) leafSendAllowed(bsubject []byte) bool {
32,008✔
3360
        // Use the original export ACL captured for this accepted leaf.
32,008✔
3361
        // The live perms also contain additional JetStream denies used by
32,008✔
3362
        // the normal forwarding path, and applying them here would reject
32,008✔
3363
        // legitimate inbound JS API requests.
32,008✔
3364
        subject := bytesToString(bsubject)
32,008✔
3365
        perms := c.opts.Export
32,008✔
3366
        if perms == nil || (perms.Allow == nil && perms.Deny == nil) {
63,991✔
3367
                return true
31,983✔
3368
        }
31,983✔
3369

3370
        allowed := true
25✔
3371
        if perms.Allow != nil && !strings.HasPrefix(subject, mqttPrefix) {
36✔
3372
                allowed = false
11✔
3373
                for _, allowSubj := range perms.Allow {
21✔
3374
                        if matchLiteral(subject, allowSubj) {
16✔
3375
                                allowed = true
6✔
3376
                                break
6✔
3377
                        }
3378
                }
3379
        }
3380

3381
        if allowed && len(perms.Deny) > 0 {
39✔
3382
                for _, denySubj := range perms.Deny {
40✔
3383
                        if matchLiteral(subject, denySubj) {
27✔
3384
                                allowed = false
1✔
3385
                                break
1✔
3386
                        }
3387
                }
3388
        }
3389
        return allowed
25✔
3390
}
3391

3392
// Handles a subscription permission violation.
3393
// See leafPermViolation() for details.
3394
func (c *client) leafSubPermViolation(subj []byte) {
333✔
3395
        c.leafPermViolation(false, subj)
333✔
3396
}
333✔
3397

3398
// Handles a publish permission violation.
3399
// See leafPermViolation() for details.
3400
func (c *client) leafPubPermViolation(subj []byte) {
5✔
3401
        c.leafPermViolation(true, subj)
5✔
3402
}
5✔
3403

3404
// Common function to process publish or subscribe leafnode permission violation.
3405
// Sends the permission violation error to the remote, logs it and closes the connection.
3406
// If this is from a server soliciting, the reconnection will be delayed.
3407
func (c *client) leafPermViolation(pub bool, subj []byte) {
338✔
3408
        if c.isSpokeLeafNode() {
673✔
3409
                // For spokes these are no-ops since the hub server told us our permissions.
335✔
3410
                // We just need to not send these over to the other side since we will get cutoff.
335✔
3411
                return
335✔
3412
        }
335✔
3413
        // FIXME(dlc) ?
3414
        c.setLeafConnectDelayIfSoliciting(leafNodeReconnectAfterPermViolation)
3✔
3415
        var action string
3✔
3416
        if pub {
6✔
3417
                c.sendErr(fmt.Sprintf("Permissions Violation for Publish to %q", subj))
3✔
3418
                action = "Publish"
3✔
3419
        } else {
3✔
3420
                c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q", subj))
×
3421
                action = "Subscription"
×
3422
        }
×
3423
        c.Errorf("%s Violation on %q - Check other side configuration", action, subj)
3✔
3424
        // TODO: add a new close reason that is more appropriate?
3✔
3425
        c.closeConnection(ProtocolViolation)
3✔
3426
}
3427

3428
// Invoked from generic processErr() for LEAF connections.
3429
func (c *client) leafProcessErr(errStr string) {
49✔
3430
        // Check if we got a cluster name collision.
49✔
3431
        if strings.Contains(errStr, ErrLeafNodeHasSameClusterName.Error()) {
52✔
3432
                _, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterClusterNameSame)
3✔
3433
                c.Errorf("Leafnode connection dropped with same cluster name error. Delaying attempt to reconnect for %v", delay)
3✔
3434
                return
3✔
3435
        }
3✔
3436
        if strings.Contains(errStr, ErrLeafNodeMinVersionRejected.Error()) {
47✔
3437
                _, delay := c.setLeafConnectDelayIfSoliciting(leafNodeMinVersionReconnectDelay)
1✔
3438
                c.Errorf("Leafnode connection dropped due to minimum version requirement. Delaying attempt to reconnect for %v", delay)
1✔
3439
                return
1✔
3440
        }
1✔
3441

3442
        // We will look for Loop detected error coming from the other side.
3443
        // If we solicit, set the connect delay.
3444
        if !strings.Contains(errStr, "Loop detected") {
82✔
3445
                return
37✔
3446
        }
37✔
3447
        c.handleLeafNodeLoop(false)
8✔
3448
}
3449

3450
// If this leaf connection solicits, sets the connect delay to the given value,
3451
// or the one from the server option's LeafNode.connDelay if one is set (for tests).
3452
// Returns the connection's account name and delay.
3453
func (c *client) setLeafConnectDelayIfSoliciting(delay time.Duration) (string, time.Duration) {
24✔
3454
        c.mu.Lock()
24✔
3455
        if c.isSolicitedLeafNode() {
37✔
3456
                if s := c.srv; s != nil {
26✔
3457
                        if srvdelay := s.getOpts().LeafNode.connDelay; srvdelay != 0 {
18✔
3458
                                delay = srvdelay
5✔
3459
                        }
5✔
3460
                }
3461
                c.leaf.remote.setConnectDelay(delay)
13✔
3462
        }
3463
        var accName string
24✔
3464
        if c.acc != nil {
48✔
3465
                accName = c.acc.Name
24✔
3466
        }
24✔
3467
        c.mu.Unlock()
24✔
3468
        return accName, delay
24✔
3469
}
3470

3471
// For the given remote Leafnode configuration, this function returns
3472
// if TLS is required, and if so, will return a clone of the TLS Config
3473
// (since some fields will be changed during handshake), the TLS server
3474
// name that is remembered, and the TLS timeout.
3475
func (c *client) leafNodeGetTLSConfigForSolicit(remote *leafNodeCfg) (bool, *tls.Config, string, float64) {
1,845✔
3476
        var (
1,845✔
3477
                tlsConfig  *tls.Config
1,845✔
3478
                tlsName    string
1,845✔
3479
                tlsTimeout float64
1,845✔
3480
        )
1,845✔
3481

1,845✔
3482
        remote.RLock()
1,845✔
3483
        defer remote.RUnlock()
1,845✔
3484

1,845✔
3485
        tlsRequired := remote.TLS || remote.TLSConfig != nil
1,845✔
3486
        if tlsRequired {
1,931✔
3487
                if remote.TLSConfig != nil {
136✔
3488
                        tlsConfig = remote.TLSConfig.Clone()
50✔
3489
                } else {
86✔
3490
                        tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}
36✔
3491
                }
36✔
3492
                tlsName = remote.tlsName
86✔
3493
                tlsTimeout = remote.TLSTimeout
86✔
3494
                if tlsTimeout == 0 {
139✔
3495
                        tlsTimeout = float64(TLS_TIMEOUT / time.Second)
53✔
3496
                }
53✔
3497
        }
3498

3499
        return tlsRequired, tlsConfig, tlsName, tlsTimeout
1,845✔
3500
}
3501

3502
// Initiates the LeafNode Websocket connection by:
3503
// - doing the TLS handshake if needed
3504
// - sending the HTTP request
3505
// - waiting for the HTTP response
3506
//
3507
// Since some bufio reader is used to consume the HTTP response, this function
3508
// returns the slice of buffered bytes (if any) so that the readLoop that will
3509
// be started after that consume those first before reading from the socket.
3510
// The boolean
3511
//
3512
// Lock held on entry.
3513
func (c *client) leafNodeSolicitWSConnection(opts *Options, rURL *url.URL, remote *leafNodeCfg) ([]byte, ClosedState, error) {
50✔
3514
        remote.RLock()
50✔
3515
        compress := remote.Websocket.Compression
50✔
3516
        // By default the server will mask outbound frames, but it can be disabled with this option.
50✔
3517
        noMasking := remote.Websocket.NoMasking
50✔
3518
        infoTimeout := remote.FirstInfoTimeout
50✔
3519
        remote.RUnlock()
50✔
3520
        // Will do the client-side TLS handshake if needed.
50✔
3521
        tlsRequired, err := c.leafClientHandshakeIfNeeded(remote, opts)
50✔
3522
        if err != nil {
54✔
3523
                // 0 will indicate that the connection was already closed
4✔
3524
                return nil, 0, err
4✔
3525
        }
4✔
3526

3527
        // For http request, we need the passed URL to contain either http or https scheme.
3528
        scheme := "http"
46✔
3529
        if tlsRequired {
54✔
3530
                scheme = "https"
8✔
3531
        }
8✔
3532
        // We will use the `/leafnode` path to tell the accepting WS server that it should
3533
        // create a LEAF connection, not a CLIENT.
3534
        // In case we use the user's URL path in the future, make sure we append the user's
3535
        // path to our `/leafnode` path.
3536
        lpath := leafNodeWSPath
46✔
3537
        if curPath := rURL.EscapedPath(); curPath != _EMPTY_ {
67✔
3538
                if curPath[0] == '/' {
42✔
3539
                        curPath = curPath[1:]
21✔
3540
                }
21✔
3541
                lpath = path.Join(curPath, lpath)
21✔
3542
        } else {
25✔
3543
                lpath = lpath[1:]
25✔
3544
        }
25✔
3545
        ustr := fmt.Sprintf("%s://%s/%s", scheme, rURL.Host, lpath)
46✔
3546
        u, _ := url.Parse(ustr)
46✔
3547
        req := &http.Request{
46✔
3548
                Method:     "GET",
46✔
3549
                URL:        u,
46✔
3550
                Proto:      "HTTP/1.1",
46✔
3551
                ProtoMajor: 1,
46✔
3552
                ProtoMinor: 1,
46✔
3553
                Header:     make(http.Header),
46✔
3554
                Host:       u.Host,
46✔
3555
        }
46✔
3556
        wsKey, err := wsMakeChallengeKey()
46✔
3557
        if err != nil {
46✔
3558
                return nil, WriteError, err
×
3559
        }
×
3560

3561
        req.Header["Upgrade"] = []string{"websocket"}
46✔
3562
        req.Header["Connection"] = []string{"Upgrade"}
46✔
3563
        req.Header["Sec-WebSocket-Key"] = []string{wsKey}
46✔
3564
        req.Header["Sec-WebSocket-Version"] = []string{"13"}
46✔
3565
        if compress {
55✔
3566
                req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue)
9✔
3567
        }
9✔
3568
        if noMasking {
56✔
3569
                req.Header.Add(wsNoMaskingHeader, wsNoMaskingValue)
10✔
3570
        }
10✔
3571
        c.nc.SetDeadline(time.Now().Add(infoTimeout))
46✔
3572
        if err := req.Write(c.nc); err != nil {
46✔
3573
                return nil, WriteError, err
×
3574
        }
×
3575

3576
        var resp *http.Response
46✔
3577

46✔
3578
        br := bufio.NewReaderSize(c.nc, MAX_CONTROL_LINE_SIZE)
46✔
3579
        resp, err = http.ReadResponse(br, req)
46✔
3580
        if err == nil &&
46✔
3581
                (resp.StatusCode != 101 ||
46✔
3582
                        !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
46✔
3583
                        !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
46✔
3584
                        resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) {
47✔
3585

1✔
3586
                err = fmt.Errorf("invalid websocket connection")
1✔
3587
        }
1✔
3588
        // Check compression extension...
3589
        if err == nil && c.ws.compress {
55✔
3590
                // Check that not only permessage-deflate extension is present, but that
9✔
3591
                // we also have server and client no context take over.
9✔
3592
                srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header, false)
9✔
3593

9✔
3594
                // If server does not support compression, then simply disable it in our side.
9✔
3595
                if !srvCompress {
13✔
3596
                        c.ws.compress = false
4✔
3597
                } else if !noCtxTakeover {
9✔
3598
                        err = fmt.Errorf("compression negotiation error")
×
3599
                }
×
3600
        }
3601
        // Same for no masking...
3602
        if err == nil && noMasking {
56✔
3603
                // Check if server accepts no masking
10✔
3604
                if resp.Header.Get(wsNoMaskingHeader) != wsNoMaskingValue {
11✔
3605
                        // Nope, need to mask our writes as any client would do.
1✔
3606
                        c.ws.maskwrite = true
1✔
3607
                }
1✔
3608
        }
3609
        if resp != nil {
76✔
3610
                resp.Body.Close()
30✔
3611
        }
30✔
3612
        if err != nil {
63✔
3613
                return nil, ReadError, err
17✔
3614
        }
17✔
3615
        c.Debugf("Leafnode compression=%v masking=%v", c.ws.compress, c.ws.maskwrite)
29✔
3616

29✔
3617
        var preBuf []byte
29✔
3618
        // We have to slurp whatever is in the bufio reader and pass that to the readloop.
29✔
3619
        if n := br.Buffered(); n != 0 {
30✔
3620
                preBuf, _ = br.Peek(n)
1✔
3621
        }
1✔
3622
        return preBuf, 0, nil
29✔
3623
}
3624

3625
const connectProcessTimeout = 2 * time.Second
3626

3627
// This is invoked for remote LEAF remote connections after processing the INFO
3628
// protocol.
3629
func (s *Server) leafNodeResumeConnectProcess(c *client) {
650✔
3630
        clusterName := s.ClusterName()
650✔
3631

650✔
3632
        c.mu.Lock()
650✔
3633
        if c.isClosed() {
650✔
3634
                c.mu.Unlock()
×
3635
                return
×
3636
        }
×
3637
        if err := c.sendLeafConnect(clusterName, c.headers); err != nil {
652✔
3638
                c.mu.Unlock()
2✔
3639
                c.closeConnection(WriteError)
2✔
3640
                return
2✔
3641
        }
2✔
3642

3643
        // Spin up the write loop.
3644
        s.startGoRoutine(func() { c.writeLoop() })
1,296✔
3645

3646
        // timeout leafNodeFinishConnectProcess
3647
        c.ping.tmr = time.AfterFunc(connectProcessTimeout, func() {
648✔
3648
                c.mu.Lock()
×
3649
                // check if leafNodeFinishConnectProcess was called and prevent later leafNodeFinishConnectProcess
×
3650
                if !c.flags.setIfNotSet(connectProcessFinished) {
×
3651
                        c.mu.Unlock()
×
3652
                        return
×
3653
                }
×
3654
                clearTimer(&c.ping.tmr)
×
3655
                closed := c.isClosed()
×
3656
                c.mu.Unlock()
×
3657
                if !closed {
×
3658
                        c.sendErrAndDebug("Stale Leaf Node Connection - Closing")
×
3659
                        c.closeConnection(StaleConnection)
×
3660
                }
×
3661
        })
3662
        c.mu.Unlock()
648✔
3663
        c.Debugf("Remote leafnode connect msg sent")
648✔
3664
}
3665

3666
// This is invoked for remote LEAF connections after processing the INFO
3667
// protocol and leafNodeResumeConnectProcess.
3668
// This will send LS+ the CONNECT protocol and register the leaf node.
3669
func (s *Server) leafNodeFinishConnectProcess(c *client) {
614✔
3670
        c.mu.Lock()
614✔
3671
        if !c.flags.setIfNotSet(connectProcessFinished) {
614✔
3672
                c.mu.Unlock()
×
3673
                return
×
3674
        }
×
3675
        if c.isClosed() {
614✔
3676
                c.mu.Unlock()
×
3677
                s.removeLeafNodeConnection(c)
×
3678
                return
×
3679
        }
×
3680
        remote := c.leaf.remote
614✔
3681
        if remote == nil || c.acc == nil {
615✔
3682
                c.mu.Unlock()
1✔
3683
                c.sendErr("Authorization Violation")
1✔
3684
                c.closeConnection(ProtocolViolation)
1✔
3685
                return
1✔
3686
        }
1✔
3687
        // Check if we will need to send the system connect event.
3688
        remote.RLock()
613✔
3689
        sendSysConnectEvent := remote.Hub
613✔
3690
        remote.RUnlock()
613✔
3691

613✔
3692
        // Capture account before releasing lock
613✔
3693
        acc := c.acc
613✔
3694
        // cancel connectProcessTimeout
613✔
3695
        clearTimer(&c.ping.tmr)
613✔
3696
        c.mu.Unlock()
613✔
3697

613✔
3698
        // Make sure we register with the account here.
613✔
3699
        if err := c.registerWithAccount(acc); err != nil {
615✔
3700
                if err == ErrTooManyAccountConnections {
2✔
3701
                        c.maxAccountConnExceeded()
×
3702
                        return
×
3703
                } else if err == ErrLeafNodeLoop {
4✔
3704
                        c.handleLeafNodeLoop(true)
2✔
3705
                        return
2✔
3706
                }
2✔
3707
                c.Errorf("Registering leaf with account %s resulted in error: %v", acc.Name, err)
×
3708
                c.closeConnection(ProtocolViolation)
×
3709
                return
×
3710
        }
3711
        if !s.addLeafNodeConnection(c, _EMPTY_, _EMPTY_, false) {
611✔
3712
                // Was not added, could be because the remote configuration has been removed.
×
3713
                c.closeConnection(ClientClosed)
×
3714
                return
×
3715
        }
×
3716
        s.initLeafNodeSmapAndSendSubs(c)
611✔
3717
        if sendSysConnectEvent {
629✔
3718
                s.sendLeafNodeConnect(acc)
18✔
3719
        }
18✔
3720
        s.accountConnectEvent(c)
611✔
3721

611✔
3722
        // The above functions are not running under the client lock, so it is
611✔
3723
        // possible that between the time we have started the read/write loops
611✔
3724
        // and now, that the connection was closed. This would leave the closed
611✔
3725
        // LN connection possibly registered with the account and/or the server's
611✔
3726
        // leafs map. So check if connection is closed, and if so, manually cleanup.
611✔
3727
        c.mu.Lock()
611✔
3728
        closed := c.isClosed()
611✔
3729
        if !closed {
1,222✔
3730
                c.setFirstPingTimer()
611✔
3731
        }
611✔
3732
        c.mu.Unlock()
611✔
3733
        if closed {
611✔
3734
                s.removeLeafNodeConnection(c)
×
3735
                if prev := acc.removeClient(c); prev == 1 {
×
3736
                        s.decActiveAccounts()
×
3737
                }
×
3738
        }
3739
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc