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

nats-io / nats-server / 26621023318

26 May 2026 03:29PM UTC coverage: 77.138% (+0.8%) from 76.295%
26621023318

push

github

web-flow
(2.14) fix: JetStream consumer lock leak on start sequence error (#8230)

## Summary

This PR fixes a lock leak in JetStream consumer creation.

In `addConsumerWithAssignment`, `mset.mu` is held while creating a
consumer. In the direct/standalone path, if `o.selectStartingSeqNo()`
returns an error, the function currently returns without releasing
`mset.mu`.

This adds the missing `mset.mu.Unlock()` before returning the error.

Resolves #8229 

## Impact

Without this unlock, the stream mutex can remain locked after a starting
sequence error, which may cause later operations on the same stream to
block.

## Changes

- Add the missing `mset.mu.Unlock()` before returning from the
`selectStartingSeqNo()` error path.

## Detection

This issue was reported by
[`goconcurrencylint`](https://github.com/sanbricio/goconcurrencylint).

## Testing

- Not added yet. This is a minimal error-path fix identified by static
analysis.

Signed-off-by: Santiago Bricio <sanbriciorojas11@gmail.com>

72077 of 93439 relevant lines covered (77.14%)

502472.26 hits per line

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

85.8
/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 {
1,679✔
124
        return c.kind == LEAF && c.leaf != nil && c.leaf.remote != nil
1,679✔
125
}
1,679✔
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 {
11,034,839✔
130
        return c.kind == LEAF && c.leaf != nil && c.leaf.isSpoke
11,034,839✔
131
}
11,034,839✔
132

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

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

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

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

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

227
        // In local config mode, check that leafnode configuration refers to accounts that exist.
228
        if len(o.TrustedOperators) == 0 {
14,358✔
229
                accNames := map[string]struct{}{}
7,039✔
230
                for _, a := range o.Accounts {
15,356✔
231
                        accNames[a.Name] = struct{}{}
8,317✔
232
                }
8,317✔
233
                // global account is always created
234
                accNames[DEFAULT_GLOBAL_ACCOUNT] = struct{}{}
7,039✔
235
                // in the context of leaf nodes, empty account means global account
7,039✔
236
                accNames[_EMPTY_] = struct{}{}
7,039✔
237
                // system account either exists or, if not disabled, will be created
7,039✔
238
                if o.SystemAccount == _EMPTY_ && !o.NoSystemAccount {
12,692✔
239
                        accNames[DEFAULT_SYSTEM_ACCOUNT] = struct{}{}
5,653✔
240
                }
5,653✔
241
                checkAccountExists := func(accName string, cfgType string) error {
15,286✔
242
                        if _, ok := accNames[accName]; !ok {
8,249✔
243
                                return fmt.Errorf("cannot find local account %q specified in leafnode %s", accName, cfgType)
2✔
244
                        }
2✔
245
                        return nil
8,245✔
246
                }
247
                if err := checkAccountExists(o.LeafNode.Account, "authorization"); err != nil {
7,040✔
248
                        return err
1✔
249
                }
1✔
250
                for _, lu := range o.LeafNode.Users {
7,055✔
251
                        if lu.Account == nil { // means global account
27✔
252
                                continue
10✔
253
                        }
254
                        if err := checkAccountExists(lu.Account.Name, "authorization"); err != nil {
7✔
255
                                return err
×
256
                        }
×
257
                }
258
                for _, r := range o.LeafNode.Remotes {
8,239✔
259
                        if err := checkAccountExists(r.LocalAccount, "remote"); err != nil {
1,202✔
260
                                return err
1✔
261
                        }
1✔
262
                }
263
        } else {
280✔
264
                if len(o.LeafNode.Users) != 0 {
281✔
265
                        return fmt.Errorf("operator mode does not allow specifying users in leafnode config")
1✔
266
                }
1✔
267
                for _, r := range o.LeafNode.Remotes {
280✔
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) {
279✔
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_ {
11,559✔
282
                if err := validateAndNormalizeCompressionOption(&o.LeafNode.Compression, CompressionS2Auto); err != nil {
4,245✔
283
                        return err
×
284
                }
×
285
        }
286

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

294
                if len(rcfg.URLs) >= 2 {
1,345✔
295
                        firstIsWS, ok := isWSURL(rcfg.URLs[0]), true
151✔
296
                        for i := 1; i < len(rcfg.URLs); i++ {
448✔
297
                                u := rcfg.URLs[i]
297✔
298
                                if isWS := isWSURL(u); isWS && !firstIsWS || !isWS && firstIsWS {
304✔
299
                                        ok = false
7✔
300
                                        break
7✔
301
                                }
302
                        }
303
                        if !ok {
158✔
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,187✔
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,368✔
316
                        if err := validateAndNormalizeCompressionOption(&rcfg.Compression, CompressionS2Auto); err != nil {
1,181✔
317
                                return err
×
318
                        }
×
319
                }
320
        }
321

322
        if o.LeafNode.Port == 0 {
10,937✔
323
                return nil
3,636✔
324
        }
3,636✔
325

326
        // If MinVersion is defined, check that it is valid.
327
        if mv := o.LeafNode.MinVersion; mv != _EMPTY_ {
3,669✔
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 {
6,694✔
338
                return nil
3,031✔
339
        }
3,031✔
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_ {
633✔
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 {
631✔
346
                return fmt.Errorf("leafnode: %v", err)
×
347
        }
×
348
        return nil
631✔
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,370✔
366
        if len(o.LeafNode.Users) == 0 {
14,714✔
367
                return nil
7,344✔
368
        }
7,344✔
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,571✔
386
        var warnings []string
1,571✔
387

1,571✔
388
        if remote.Proxy.URL == _EMPTY_ {
3,116✔
389
                return warnings, nil
1,545✔
390
        }
1,545✔
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) {
232✔
442
        clearInProgress := true
232✔
443
        defer func() {
462✔
444
                s.grWG.Done()
230✔
445
                if clearInProgress {
292✔
446
                        remote.setConnectInProgress(false)
62✔
447
                }
62✔
448
        }()
449
        delay := s.getOpts().LeafNode.ReconnectInterval
232✔
450
        select {
232✔
451
        case <-time.After(delay):
174✔
452
        case <-remote.quitCh:
×
453
                return
×
454
        case <-s.quitCh:
57✔
455
                return
57✔
456
        }
457
        clearInProgress = !connectToRemoteLeafNode(s, remote, false)
174✔
458
}
459

460
// Creates a leafNodeCfg object that wraps the RemoteLeafOpts.
461
func newLeafNodeCfg(remote *RemoteLeafOpts) *leafNodeCfg {
1,172✔
462
        cfg := &leafNodeCfg{
1,172✔
463
                RemoteLeafOpts: remote,
1,172✔
464
                urls:           make([]*url.URL, 0, len(remote.URLs)),
1,172✔
465
                quitCh:         make(chan struct{}, 1),
1,172✔
466
        }
1,172✔
467
        if len(remote.DenyExports) > 0 || len(remote.DenyImports) > 0 {
1,177✔
468
                perms := &Permissions{}
5✔
469
                if len(remote.DenyExports) > 0 {
10✔
470
                        perms.Publish = &SubjectPermission{Deny: remote.DenyExports}
5✔
471
                }
5✔
472
                if len(remote.DenyImports) > 0 {
9✔
473
                        perms.Subscribe = &SubjectPermission{Deny: remote.DenyImports}
4✔
474
                }
4✔
475
                cfg.perms = perms
5✔
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,172✔
480
        // If allowed to randomize, do it on our copy of URLs
1,172✔
481
        if !remote.NoRandomize {
2,343✔
482
                rand.Shuffle(len(cfg.urls), func(i, j int) {
1,445✔
483
                        cfg.urls[i], cfg.urls[j] = cfg.urls[j], cfg.urls[i]
274✔
484
                })
274✔
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 {
2,633✔
490
                cfg.saveTLSHostname(u)
1,461✔
491
                cfg.saveUserPassword(u)
1,461✔
492
                // If the url(s) have the "wss://" scheme, and we don't have a TLS
1,461✔
493
                // config, mark that we should be using TLS anyway.
1,461✔
494
                if !cfg.TLS && isWSSURL(u) {
1,462✔
495
                        cfg.TLS = true
1✔
496
                }
1✔
497
        }
498
        return cfg
1,172✔
499
}
500

501
// Notifies the quit channel without blocking.
502
// No lock is needed to invoke this function.
503
func (cfg *leafNodeCfg) notifyQuitChannel() {
×
504
        select {
×
505
        case cfg.quitCh <- struct{}{}:
×
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,033✔
512
        cfg.Lock()
3,033✔
513
        defer cfg.Unlock()
3,033✔
514
        // In both cases we want to drain the "quit" channel.
3,033✔
515
        select {
3,033✔
516
        case <-cfg.quitCh:
×
517
        default:
3,033✔
518
        }
519
        cfg.connInProgress = inProgress
3,033✔
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 {
6,624✔
543
        cfg.RLock()
6,624✔
544
        defer cfg.RUnlock()
6,624✔
545
        return !cfg.Disabled && !cfg.removed
6,624✔
546
}
6,624✔
547

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

563
// Returns the current URL
564
func (cfg *leafNodeCfg) getCurrentURL() *url.URL {
69✔
565
        cfg.RLock()
69✔
566
        defer cfg.RUnlock()
69✔
567
        return cfg.curURL
69✔
568
}
69✔
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,346✔
573
        cfg.RLock()
1,346✔
574
        delay := cfg.connDelay
1,346✔
575
        cfg.RUnlock()
1,346✔
576
        return delay
1,346✔
577
}
1,346✔
578

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

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

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

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

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

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

715
        var conn net.Conn
1,341✔
716

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

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

1,341✔
727
        // Set default proxy timeout if not specified
1,341✔
728
        if proxyTimeout == 0 {
2,674✔
729
                proxyTimeout = dialTimeout
1,333✔
730
        }
1,333✔
731

732
        attempts := 0
1,341✔
733

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

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

5,414✔
756
                                // Check if proxy is configured
5,414✔
757
                                if proxyURL != _EMPTY_ {
5,422✔
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,406✔
770
                                        // Direct connection
5,406✔
771
                                        conn, err = natsDialTimeout("tcp", url, dialTimeout)
5,406✔
772
                                }
5,406✔
773
                        }
774
                }
775
                if err != nil {
10,479✔
776
                        jitter := time.Duration(rand.Int63n(int64(reconnectDelay)))
4,931✔
777
                        delay := reconnectDelay + jitter
4,931✔
778
                        attempts++
4,931✔
779
                        if s.shouldReportConnectErr(firstConnect, attempts) {
7,819✔
780
                                s.Errorf(connErrFmt, rURL.Host, attempts, err)
2,888✔
781
                        } else {
4,931✔
782
                                s.Debugf(connErrFmt, rURL.Host, attempts, err)
2,043✔
783
                        }
2,043✔
784
                        remote.Lock()
4,931✔
785
                        // if we are using a delay to start migrating assets, kick off a migrate timer.
4,931✔
786
                        if remote.jsMigrateTimer == nil && jetstreamMigrateDelay > 0 {
4,939✔
787
                                remote.jsMigrateTimer = time.AfterFunc(jetstreamMigrateDelay, func() {
16✔
788
                                        s.checkJetStreamMigrate(remote)
8✔
789
                                })
8✔
790
                        }
791
                        remote.Unlock()
4,931✔
792
                        select {
4,931✔
793
                        case <-s.quitCh:
714✔
794
                                return false
714✔
795
                        case <-remote.quitCh:
×
796
                                return false
×
797
                        case <-time.After(delay):
4,216✔
798
                                // Check if we should migrate any JetStream assets immediately while this remote is down.
4,216✔
799
                                // This will be used if JetStreamClusterMigrateDelay was not set
4,216✔
800
                                if jetstreamMigrateDelay == 0 {
8,357✔
801
                                        s.checkJetStreamMigrate(remote)
4,141✔
802
                                }
4,141✔
803
                                continue
4,216✔
804
                        }
805
                }
806
                remote.cancelMigrateTimer()
617✔
807
                // We can check here, but really we will have to check again when the server
617✔
808
                // is about to add to the `s.leafs` map later in the process.
617✔
809
                if !remote.stillValid() {
617✔
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)
617✔
817

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

617✔
821
                return true
617✔
822
        }
823

824
        return false
9✔
825
}
826

827
func (cfg *leafNodeCfg) cancelMigrateTimer() {
625✔
828
        cfg.Lock()
625✔
829
        stopAndClearTimer(&cfg.jsMigrateTimer)
625✔
830
        cfg.Unlock()
625✔
831
}
625✔
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) {
617✔
835
        s.mu.RLock()
617✔
836
        accName := remote.LocalAccount
617✔
837
        s.mu.RUnlock()
617✔
838

617✔
839
        acc, err := s.LookupAccount(accName)
617✔
840
        if err != nil {
619✔
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()
615✔
846
        defer acc.jscmMu.Unlock()
615✔
847

615✔
848
        // Walk all streams looking for any clustered stream, skip otherwise.
615✔
849
        for _, mset := range acc.streams() {
634✔
850
                node := mset.raftNode()
19✔
851
                if node == nil {
30✔
852
                        // Not R>1
11✔
853
                        continue
11✔
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,149✔
869
        s.mu.RLock()
4,149✔
870
        accName, shouldMigrate := remote.LocalAccount, remote.JetStreamClusterMigrate
4,149✔
871
        s.mu.RUnlock()
4,149✔
872

4,149✔
873
        if !shouldMigrate {
8,236✔
874
                return
4,087✔
875
        }
4,087✔
876

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

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

62✔
886
        // Walk all streams looking for any clustered stream, skip otherwise.
62✔
887
        // If we are the leader force stepdown.
62✔
888
        for _, mset := range acc.streams() {
94✔
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() {
53✔
896
                        if n := o.raftNode(); n != nil {
42✔
897
                                n.StepDown()
21✔
898
                                // Ensure we can not become a leader while in this state.
21✔
899
                                n.SetObserver(true)
21✔
900
                        }
21✔
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,543✔
911
        s.mu.RLock()
5,543✔
912
        defer s.mu.RUnlock()
5,543✔
913
        return s.leafDisableConnect
5,543✔
914
}
5,543✔
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) {
1,852✔
927
        if cfg.tlsName == _EMPTY_ && net.ParseIP(u.Hostname()) == nil {
1,865✔
928
                cfg.tlsName = u.Hostname()
13✔
929
        }
13✔
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,461✔
937
        if cfg.username == _EMPTY_ && u.User != nil {
1,670✔
938
                cfg.username = u.User.Username()
209✔
939
                cfg.password, _ = u.User.Password()
209✔
940
        }
209✔
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,649✔
946
        // Snapshot server options.
3,649✔
947
        opts := s.getOpts()
3,649✔
948

3,649✔
949
        port := opts.LeafNode.Port
3,649✔
950
        if port == -1 {
7,223✔
951
                port = 0
3,574✔
952
        }
3,574✔
953

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

958
        s.mu.Lock()
3,649✔
959
        hp := net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(port))
3,649✔
960
        l, e := natsListen("tcp", hp)
3,649✔
961
        s.leafNodeListenerErr = e
3,649✔
962
        if e != nil {
3,649✔
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,649✔
969
                net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
3,649✔
970

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

998
        s.leafNodeInfo = info
3,649✔
999
        // Possibly override Host/Port and set IP based on Cluster.Advertise
3,649✔
1000
        if err := s.setLeafNodeInfoHostPortAndIP(); err != nil {
3,649✔
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,649✔
1007
        s.generateLeafNodeInfoJSON()
3,649✔
1008

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

3,649✔
1012
        // As of now, a server that does not have remotes configured would
3,649✔
1013
        // never solicit a connection, so we should not have to warn if
3,649✔
1014
        // InsecureSkipVerify is set in main LeafNodes config (since
3,649✔
1015
        // this TLS setting matters only when soliciting a connection).
3,649✔
1016
        // Still, warn if insecure is set in any of LeafNode block.
3,649✔
1017
        // We need to check remotes, even if tls is not required on accept.
3,649✔
1018
        warn := tlsRequired && opts.LeafNode.TLSConfig.InsecureSkipVerify
3,649✔
1019
        if !warn {
7,296✔
1020
                for _, r := range opts.LeafNode.Remotes {
3,720✔
1021
                        if r.TLSConfig != nil && r.TLSConfig.InsecureSkipVerify {
73✔
1022
                                warn = true
×
1023
                                break
×
1024
                        }
1025
                }
1026
        }
1027
        if warn {
3,651✔
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,307✔
1031
        s.mu.Unlock()
3,649✔
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 {
498✔
1040
        // We support basic user/pass and operator based user JWT with signatures.
498✔
1041
        cinfo := leafConnectInfo{
498✔
1042
                Version:       VERSION,
498✔
1043
                ID:            c.srv.info.ID,
498✔
1044
                Domain:        c.srv.info.Domain,
498✔
1045
                Name:          c.srv.info.Name,
498✔
1046
                Hub:           c.leaf.remote.Hub,
498✔
1047
                Cluster:       clusterName,
498✔
1048
                Headers:       headers,
498✔
1049
                JetStream:     c.acc.jetStreamConfigured(),
498✔
1050
                DenyPub:       c.leaf.remote.DenyImports,
498✔
1051
                Compression:   c.leaf.compression,
498✔
1052
                RemoteAccount: c.acc.GetName(),
498✔
1053
                Proto:         c.srv.getServerProto(),
498✔
1054
                Isolate:       c.leaf.remote.RequestIsolation,
498✔
1055
        }
498✔
1056

498✔
1057
        // If a signature callback is specified, this takes precedence over anything else.
498✔
1058
        if cb := c.leaf.remote.SignatureCB; cb != nil {
503✔
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_ {
537✔
1074
                // Check for credentials first, that will take precedence..
44✔
1075
                c.Debugf("Authenticating with credentials file %q", c.leaf.remote.Credentials)
44✔
1076
                contents, err := os.ReadFile(creds)
44✔
1077
                if err != nil {
44✔
1078
                        c.Errorf("%v", err)
×
1079
                        return err
×
1080
                }
×
1081
                defer wipeSlice(contents)
44✔
1082
                items := credsRe.FindAllSubmatch(contents, -1)
44✔
1083
                if len(items) < 2 {
44✔
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]
44✔
1090
                tmp := make([]byte, len(raw))
44✔
1091
                copy(tmp, raw)
44✔
1092
                // Seed is second item.
44✔
1093
                kp, err := nkeys.FromSeed(items[1][1])
44✔
1094
                if err != nil {
44✔
1095
                        c.Errorf("Credentials file has malformed seed")
×
1096
                        return err
×
1097
                }
×
1098
                // Wipe our key on exit.
1099
                defer kp.Wipe()
44✔
1100

44✔
1101
                sigraw, _ := kp.Sign(c.nonce)
44✔
1102
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
44✔
1103
                cinfo.JWT = bytesToString(tmp)
44✔
1104
                cinfo.Sig = sig
44✔
1105
        } else if nkey := c.leaf.remote.Nkey; nkey != _EMPTY_ {
452✔
1106
                kp, err := nkeys.FromSeed([]byte(nkey))
3✔
1107
                if err != nil {
3✔
1108
                        c.Errorf("Remote nkey has malformed seed")
×
1109
                        return err
×
1110
                }
×
1111
                // Wipe our key on exit.
1112
                defer kp.Wipe()
3✔
1113
                sigraw, _ := kp.Sign(c.nonce)
3✔
1114
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
3✔
1115
                pkey, _ := kp.PublicKey()
3✔
1116
                cinfo.Nkey = pkey
3✔
1117
                cinfo.Sig = sig
3✔
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 {
728✔
1122
                cinfo.User = userInfo.Username()
232✔
1123
                var ok bool
232✔
1124
                cinfo.Pass, ok = userInfo.Password()
232✔
1125
                // For backward compatibility, if only username is provided, set both
232✔
1126
                // Token and User, not just Token.
232✔
1127
                if !ok {
240✔
1128
                        cinfo.Token = cinfo.User
8✔
1129
                }
8✔
1130
        } else if c.leaf.remote.username != _EMPTY_ {
270✔
1131
                cinfo.User = c.leaf.remote.username
6✔
1132
                cinfo.Pass = c.leaf.remote.password
6✔
1133
                // For backward compatibility, if only username is provided, set both
6✔
1134
                // Token and User, not just Token.
6✔
1135
                if cinfo.Pass == _EMPTY_ {
6✔
1136
                        cinfo.Token = cinfo.User
×
1137
                }
×
1138
        }
1139
        b, err := json.Marshal(cinfo)
496✔
1140
        if err != nil {
496✔
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)))
496✔
1148
        return nil
496✔
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,011✔
1154
        clone := s.leafNodeInfo
2,011✔
1155
        // Copy the array of urls.
2,011✔
1156
        if len(s.leafNodeInfo.LeafNodeURLs) > 0 {
3,650✔
1157
                clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...)
1,639✔
1158
        }
1,639✔
1159
        return &clone
2,011✔
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,826✔
1167
        if s.leafURLsMap.addUrl(urlStr) {
15,647✔
1168
                s.generateLeafNodeInfoJSON()
7,821✔
1169
                return true
7,821✔
1170
        }
7,821✔
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,826✔
1179
        // Don't need to do this if we are removing the route connection because
7,826✔
1180
        // we are shuting down...
7,826✔
1181
        if s.isShuttingDown() {
12,005✔
1182
                return false
4,179✔
1183
        }
4,179✔
1184
        if s.leafURLsMap.removeUrl(urlStr) {
7,290✔
1185
                s.generateLeafNodeInfoJSON()
3,643✔
1186
                return true
3,643✔
1187
        }
3,643✔
1188
        return false
4✔
1189
}
1190

1191
// Server lock is held on entry
1192
func (s *Server) generateLeafNodeInfoJSON() {
15,113✔
1193
        s.leafNodeInfo.Cluster = s.cachedClusterName()
15,113✔
1194
        s.leafNodeInfo.LeafNodeURLs = s.leafURLsMap.getAsStringSlice()
15,113✔
1195
        s.leafNodeInfo.WSConnectURLs = s.websocket.connectURLsMap.getAsStringSlice()
15,113✔
1196
        s.leafNodeInfoJSON = generateInfoJSON(&s.leafNodeInfo)
15,113✔
1197
}
15,113✔
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,464✔
1202
        for _, c := range s.leafs {
11,515✔
1203
                c.mu.Lock()
51✔
1204
                c.enqueueProto(s.leafNodeInfoJSON)
51✔
1205
                c.mu.Unlock()
51✔
1206
        }
51✔
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,301✔
1211
        // Snapshot server options.
1,301✔
1212
        opts := s.getOpts()
1,301✔
1213

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

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

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

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

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

1245
        // Determines if we are soliciting the connection or not.
1246
        var solicited bool
1,301✔
1247
        var acc *Account
1,301✔
1248
        var remoteSuffix string
1,301✔
1249
        if remote != nil {
1,918✔
1250
                // For now, if lookup fails, we will constantly try
617✔
1251
                // to recreate this LN connection.
617✔
1252
                lacc := remote.LocalAccount
617✔
1253
                var err error
617✔
1254
                acc, err = s.LookupAccount(lacc)
617✔
1255
                if err != nil {
619✔
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())
615✔
1265
        }
1266

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

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

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

1,299✔
1303
        // Grab this before the client lock below.
1,299✔
1304
        if !solicited {
1,983✔
1305
                // Grab server variables
684✔
1306
                s.mu.Lock()
684✔
1307
                info = s.copyLeafNodeInfo()
684✔
1308
                // For tests that want to simulate old servers, do not set the compression
684✔
1309
                // on the INFO protocol if configured with CompressionNotSupported.
684✔
1310
                // Also suppress it if WebSocket compression is already in use, otherwise
684✔
1311
                // an old soliciting peer would honor the advertised mode, switch to S2,
684✔
1312
                // and then wait forever for a compressed INFO response from us.
684✔
1313
                if cm := opts.LeafNode.Compression.Mode; cm != CompressionNotSupported && (ws == nil || !ws.compress) {
1,364✔
1314
                        info.Compression = cm
680✔
1315
                }
680✔
1316
                // We always send a nonce for LEAF connections. Do not change that without
1317
                // taking into account presence of proxy trusted keys.
1318
                s.generateNonce(nonce[:])
684✔
1319
                s.mu.Unlock()
684✔
1320
        }
1321

1322
        // Grab lock
1323
        c.mu.Lock()
1,299✔
1324

1,299✔
1325
        var preBuf []byte
1,299✔
1326
        if solicited {
1,914✔
1327
                // For websocket connection, we need to send an HTTP request,
615✔
1328
                // and get the response before starting the readLoop to get
615✔
1329
                // the INFO, etc..
615✔
1330
                if c.isWebsocket() {
661✔
1331
                        var err error
46✔
1332
                        var closeReason ClosedState
46✔
1333

46✔
1334
                        preBuf, closeReason, err = c.leafNodeSolicitWSConnection(opts, rURL, remote)
46✔
1335
                        if err != nil {
66✔
1336
                                c.Errorf("Error soliciting websocket connection: %v", err)
20✔
1337
                                c.mu.Unlock()
20✔
1338
                                if closeReason != 0 {
36✔
1339
                                        c.closeConnection(closeReason)
16✔
1340
                                }
16✔
1341
                                return nil
20✔
1342
                        }
1343
                } else {
569✔
1344
                        // If configured to do TLS handshake first
569✔
1345
                        if tlsFirst {
569✔
1346
                                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
×
1347
                                        c.mu.Unlock()
×
1348
                                        return nil
×
1349
                                }
×
1350
                        }
1351
                        // We need to wait for the info, but not for too long.
1352
                        c.nc.SetReadDeadline(time.Now().Add(infoTimeout))
569✔
1353
                }
1354

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

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

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

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

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

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

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

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

1457
        // Spin up the read loop.
1458
        s.startGoRoutine(func() { c.readLoop(preBuf) })
2,470✔
1459

1460
        // We will spin the write loop for solicited connections only
1461
        // when processing the INFO and after switching to TLS if needed.
1462
        if !solicited {
1,876✔
1463
                s.startGoRoutine(func() { c.writeLoop() })
1,282✔
1464
        }
1465

1466
        c.mu.Unlock()
1,235✔
1467

1,235✔
1468
        return c
1,235✔
1469
}
1470

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

1482
        // If TLS required, peform handshake.
1483
        // Get the URL that was used to connect to the remote server.
1484
        rURL := remote.getCurrentURL()
69✔
1485

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

1499
func (c *client) processLeafnodeInfo(info *Info) {
1,920✔
1500
        c.mu.Lock()
1,920✔
1501
        if c.leaf == nil || c.isClosed() {
1,920✔
1502
                c.mu.Unlock()
×
1503
                return
×
1504
        }
×
1505
        s := c.srv
1,920✔
1506
        opts := s.getOpts()
1,920✔
1507
        remote := c.leaf.remote
1,920✔
1508
        didSolicit := remote != nil
1,920✔
1509
        firstINFO := !c.flags.isSet(infoReceived)
1,920✔
1510

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

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

1545
                // Prevent from getting back here.
1546
                c.flags.set(compressionNegotiated)
914✔
1547

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

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

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

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

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

1692
        var resumeConnect bool
1,009✔
1693

1,009✔
1694
        // If this is a remote connection and this is the first INFO protocol,
1,009✔
1695
        // then we need to finish the connect process by sending CONNECT, etc..
1,009✔
1696
        if firstINFO && didSolicit {
1,507✔
1697
                // Clear deadline that was set in createLeafNode while waiting for the INFO.
498✔
1698
                c.nc.SetDeadline(time.Time{})
498✔
1699
                resumeConnect = true
498✔
1700
        } else if !firstINFO && didSolicit {
1,481✔
1701
                c.leaf.remoteAccName = info.RemoteAccount
472✔
1702
        }
472✔
1703

1704
        // Check if we have the remote account information and if so make sure it's stored.
1705
        if info.RemoteAccount != _EMPTY_ {
1,470✔
1706
                if c.acc == nil {
461✔
1707
                        c.mu.Unlock()
×
1708
                        c.sendErr("Authorization Violation")
×
1709
                        c.closeConnection(ProtocolViolation)
×
1710
                        return
×
1711
                }
×
1712
                s.leafRemoteAccounts.Store(c.acc.Name, info.RemoteAccount)
461✔
1713
        }
1714
        c.mu.Unlock()
1,009✔
1715

1,009✔
1716
        finishConnect := info.ConnectInfo
1,009✔
1717
        if resumeConnect && s != nil {
1,507✔
1718
                s.leafNodeResumeConnectProcess(c)
498✔
1719
                if !info.InfoOnConnect {
498✔
1720
                        finishConnect = true
×
1721
                }
×
1722
        }
1723
        if finishConnect {
1,470✔
1724
                s.leafNodeFinishConnectProcess(c)
461✔
1725
        }
461✔
1726

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

1733
func (s *Server) negotiateLeafCompression(c *client, didSolicit bool, infoCompression string, co *CompressionOpts) (bool, error) {
912✔
1734
        // If WebSocket compression is already negotiated on this connection then
912✔
1735
        // we shouldn't layer S2 compression on top of it.
912✔
1736
        c.mu.Lock()
912✔
1737
        if c.ws != nil && c.ws.compress {
916✔
1738
                c.leaf.compression = CompressionOff
4✔
1739
                c.mu.Unlock()
4✔
1740
                return false, nil
4✔
1741
        }
4✔
1742
        c.mu.Unlock()
908✔
1743
        // Negotiate the appropriate compression mode (or no compression)
908✔
1744
        cm, err := selectCompressionMode(co.Mode, infoCompression)
908✔
1745
        if err != nil {
908✔
1746
                return false, err
×
1747
        }
×
1748
        c.mu.Lock()
908✔
1749
        // For "auto" mode, set the initial compression mode based on RTT
908✔
1750
        if cm == CompressionS2Auto {
1,734✔
1751
                if c.rttStart.IsZero() {
1,652✔
1752
                        c.rtt = computeRTT(c.start)
826✔
1753
                }
826✔
1754
                cm = selectS2AutoModeBasedOnRTT(c.rtt, co.RTTThresholds)
826✔
1755
        }
1756
        // Keep track of the negotiated compression mode.
1757
        c.leaf.compression = cm
908✔
1758
        cid := c.cid
908✔
1759
        var nonce string
908✔
1760
        if !didSolicit {
1,319✔
1761
                nonce = bytesToString(c.nonce)
411✔
1762
        }
411✔
1763
        c.mu.Unlock()
908✔
1764

908✔
1765
        if !needsCompression(cm) {
990✔
1766
                return false, nil
82✔
1767
        }
82✔
1768

1769
        // If we end-up doing compression...
1770

1771
        // Generate an INFO with the chosen compression mode.
1772
        s.mu.Lock()
826✔
1773
        info := s.copyLeafNodeInfo()
826✔
1774
        info.Compression, info.CID, info.Nonce = compressionModeForInfoProtocol(co, cm), cid, nonce
826✔
1775
        infoProto := generateInfoJSON(info)
826✔
1776
        s.mu.Unlock()
826✔
1777

826✔
1778
        // If we solicited, then send this INFO protocol BEFORE switching
826✔
1779
        // to compression writer. However, if we did not, we send it after.
826✔
1780
        c.mu.Lock()
826✔
1781
        if didSolicit {
1,241✔
1782
                c.enqueueProto(infoProto)
415✔
1783
                // Make sure it is completely flushed (the pending bytes goes to
415✔
1784
                // 0) before proceeding.
415✔
1785
                for c.out.pb > 0 && !c.isClosed() {
829✔
1786
                        c.flushOutbound()
414✔
1787
                }
414✔
1788
        }
1789
        // This is to notify the readLoop that it should switch to a
1790
        // (de)compression reader.
1791
        c.in.flags.set(switchToCompression)
826✔
1792
        // Create the compress writer before queueing the INFO protocol for
826✔
1793
        // a route that did not solicit. It will make sure that that proto
826✔
1794
        // is sent with compression on.
826✔
1795
        c.out.cw = s2.NewWriter(nil, s2WriterOptions(cm)...)
826✔
1796
        if !didSolicit {
1,237✔
1797
                c.enqueueProto(infoProto)
411✔
1798
        }
411✔
1799
        c.mu.Unlock()
826✔
1800
        return true, nil
826✔
1801
}
1802

1803
// When getting a leaf node INFO protocol, use the provided
1804
// array of urls to update the list of possible endpoints.
1805
func (c *client) updateLeafNodeURLs(info *Info) {
969✔
1806
        cfg := c.leaf.remote
969✔
1807
        cfg.Lock()
969✔
1808
        defer cfg.Unlock()
969✔
1809

969✔
1810
        // We have ensured that if a remote has a WS scheme, then all are.
969✔
1811
        // So check if first is WS, then add WS URLs, otherwise, add non WS ones.
969✔
1812
        if len(cfg.URLs) > 0 && isWSURL(cfg.URLs[0]) {
1,021✔
1813
                // It does not really matter if we use "ws://" or "wss://" here since
52✔
1814
                // we will have already marked that the remote should use TLS anyway.
52✔
1815
                // But use proper scheme for log statements, etc...
52✔
1816
                proto := wsSchemePrefix
52✔
1817
                if cfg.TLS {
52✔
1818
                        proto = wsSchemePrefixTLS
×
1819
                }
×
1820
                c.doUpdateLNURLs(cfg, proto, info.WSConnectURLs)
52✔
1821
                return
52✔
1822
        }
1823
        c.doUpdateLNURLs(cfg, "nats-leaf", info.LeafNodeURLs)
917✔
1824
}
1825

1826
func (c *client) doUpdateLNURLs(cfg *leafNodeCfg, scheme string, URLs []string) {
969✔
1827
        cfg.urls = make([]*url.URL, 0, 1+len(URLs))
969✔
1828
        // Add the ones we receive in the protocol
969✔
1829
        for _, surl := range URLs {
2,682✔
1830
                url, err := url.Parse(fmt.Sprintf("%s://%s", scheme, surl))
1,713✔
1831
                if err != nil {
1,713✔
1832
                        // As per below, the URLs we receive should not have contained URL info, so this should be safe to log.
×
1833
                        c.Errorf("Error parsing url %q: %v", surl, err)
×
1834
                        continue
×
1835
                }
1836
                // Do not add if it's the same as what we already have configured.
1837
                var dup bool
1,713✔
1838
                for _, u := range cfg.URLs {
4,259✔
1839
                        // URLs that we receive never have user info, but the
2,546✔
1840
                        // ones that were configured may have. Simply compare
2,546✔
1841
                        // host and port to decide if they are equal or not.
2,546✔
1842
                        if url.Host == u.Host && url.Port() == u.Port() {
3,868✔
1843
                                dup = true
1,322✔
1844
                                break
1,322✔
1845
                        }
1846
                }
1847
                if !dup {
2,104✔
1848
                        cfg.urls = append(cfg.urls, url)
391✔
1849
                        cfg.saveTLSHostname(url)
391✔
1850
                }
391✔
1851
        }
1852
        // Add the configured one
1853
        cfg.urls = append(cfg.urls, cfg.URLs...)
969✔
1854
}
1855

1856
// Similar to setInfoHostPortAndGenerateJSON, but for leafNodeInfo.
1857
func (s *Server) setLeafNodeInfoHostPortAndIP() error {
3,649✔
1858
        opts := s.getOpts()
3,649✔
1859
        if opts.LeafNode.Advertise != _EMPTY_ {
3,660✔
1860
                advHost, advPort, err := parseHostPort(opts.LeafNode.Advertise, opts.LeafNode.Port)
11✔
1861
                if err != nil {
11✔
1862
                        return err
×
1863
                }
×
1864
                s.leafNodeInfo.Host = advHost
11✔
1865
                s.leafNodeInfo.Port = advPort
11✔
1866
        } else {
3,638✔
1867
                s.leafNodeInfo.Host = opts.LeafNode.Host
3,638✔
1868
                s.leafNodeInfo.Port = opts.LeafNode.Port
3,638✔
1869
                // If the host is "0.0.0.0" or "::" we need to resolve to a public IP.
3,638✔
1870
                // This will return at most 1 IP.
3,638✔
1871
                hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(s.leafNodeInfo.Host, false)
3,638✔
1872
                if err != nil {
3,638✔
1873
                        return err
×
1874
                }
×
1875
                if hostIsIPAny {
3,690✔
1876
                        if len(ips) == 0 {
52✔
1877
                                s.Errorf("Could not find any non-local IP for leafnode's listen specification %q",
×
1878
                                        s.leafNodeInfo.Host)
×
1879
                        } else {
52✔
1880
                                // Take the first from the list...
52✔
1881
                                s.leafNodeInfo.Host = ips[0]
52✔
1882
                        }
52✔
1883
                }
1884
        }
1885
        // Use just host:port for the IP
1886
        s.leafNodeInfo.IP = net.JoinHostPort(s.leafNodeInfo.Host, strconv.Itoa(s.leafNodeInfo.Port))
3,649✔
1887
        if opts.LeafNode.Advertise != _EMPTY_ {
3,660✔
1888
                s.Noticef("Advertise address for leafnode is set to %s", s.leafNodeInfo.IP)
11✔
1889
        }
11✔
1890
        return nil
3,649✔
1891
}
1892

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

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

959✔
1964
        // If applicable, evict the old one.
959✔
1965
        if old != nil {
962✔
1966
                old.sendErrAndErr(DuplicateRemoteLeafnodeConnection.String())
3✔
1967
                old.closeConnection(DuplicateRemoteLeafnodeConnection)
3✔
1968
                c.Warnf("Replacing connection from same server")
3✔
1969
        }
3✔
1970

1971
        srvDecorated := func() string {
1,144✔
1972
                if myClustName == _EMPTY_ {
207✔
1973
                        return mySrvName
22✔
1974
                }
22✔
1975
                return fmt.Sprintf("%s/%s", mySrvName, myClustName)
163✔
1976
        }
1977

1978
        opts := s.getOpts()
959✔
1979
        sysAcc := s.SystemAccount()
959✔
1980
        js := s.getJetStream()
959✔
1981
        var meta *raft
959✔
1982
        if js != nil {
1,400✔
1983
                if mg := js.getMetaGroup(); mg != nil {
766✔
1984
                        meta = mg.(*raft)
325✔
1985
                }
325✔
1986
        }
1987
        blockMappingOutgoing := false
959✔
1988
        // Deny (non domain) JetStream API traffic unless system account is shared
959✔
1989
        // and domain names are identical and extending is not disabled
959✔
1990

959✔
1991
        // Check if backwards compatibility has been enabled and needs to be acted on
959✔
1992
        forceSysAccDeny := false
959✔
1993
        if len(opts.JsAccDefaultDomain) > 0 {
992✔
1994
                if acc == sysAcc {
44✔
1995
                        for _, d := range opts.JsAccDefaultDomain {
22✔
1996
                                if d == _EMPTY_ {
19✔
1997
                                        // Extending JetStream via leaf node is mutually exclusive with a domain mapping to the empty/default domain.
8✔
1998
                                        // As soon as one mapping to "" is found, disable the ability to extend JS via a leaf node.
8✔
1999
                                        c.Noticef("Not extending remote JetStream domain %q due to presence of empty default domain", myRemoteDomain)
8✔
2000
                                        forceSysAccDeny = true
8✔
2001
                                        break
8✔
2002
                                }
2003
                        }
2004
                } else if domain, ok := opts.JsAccDefaultDomain[accName]; ok && domain == _EMPTY_ {
35✔
2005
                        // for backwards compatibility with old setups that do not have a domain name set
13✔
2006
                        c.Debugf("Skipping deny %q for account %q due to default domain", jsAllAPI, accName)
13✔
2007
                        return true
13✔
2008
                }
13✔
2009
        }
2010

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

2090
func (s *Server) removeLeafNodeConnection(c *client) {
1,302✔
2091
        s.mu.Lock()
1,302✔
2092
        c.mu.Lock()
1,302✔
2093
        cid := c.cid
1,302✔
2094
        if c.leaf != nil {
2,603✔
2095
                if c.leaf.tsubt != nil {
2,160✔
2096
                        c.leaf.tsubt.Stop()
859✔
2097
                        c.leaf.tsubt = nil
859✔
2098
                }
859✔
2099
                if c.leaf.gwSub != nil {
1,760✔
2100
                        s.gwLeafSubs.Remove(c.leaf.gwSub)
459✔
2101
                        // We need to set this to nil for GC to release the connection
459✔
2102
                        c.leaf.gwSub = nil
459✔
2103
                }
459✔
2104
                if remote := c.leaf.remote; remote != nil {
1,918✔
2105
                        // If "noReconnect" is true, then we won't attempt to reconnect, so
617✔
2106
                        // we will clear the "connect-in-progress" flag. However, if we can
617✔
2107
                        // reconnect, then we should set "connect-in-progress" to true while
617✔
2108
                        // we are under the server/client lock. The go routine that performs
617✔
2109
                        // the reconnect will be started later and there would be a gap with
617✔
2110
                        // the wrong flag value otherwise.
617✔
2111
                        remote.setConnectInProgress(!c.flags.isSet(noReconnect))
617✔
2112
                }
617✔
2113
        }
2114
        proxyKey := c.proxyKey
1,302✔
2115
        c.mu.Unlock()
1,302✔
2116
        delete(s.leafs, cid)
1,302✔
2117
        if proxyKey != _EMPTY_ {
1,306✔
2118
                s.removeProxiedConn(proxyKey, cid)
4✔
2119
        }
4✔
2120
        s.mu.Unlock()
1,302✔
2121
        s.removeFromTempClients(cid)
1,302✔
2122
}
2123

2124
// Connect information for solicited leafnodes.
2125
type leafConnectInfo struct {
2126
        Version   string   `json:"version,omitempty"`
2127
        Nkey      string   `json:"nkey,omitempty"`
2128
        JWT       string   `json:"jwt,omitempty"`
2129
        Sig       string   `json:"sig,omitempty"`
2130
        User      string   `json:"user,omitempty"`
2131
        Pass      string   `json:"pass,omitempty"`
2132
        Token     string   `json:"auth_token,omitempty"`
2133
        ID        string   `json:"server_id,omitempty"`
2134
        Domain    string   `json:"domain,omitempty"`
2135
        Name      string   `json:"name,omitempty"`
2136
        Hub       bool     `json:"is_hub,omitempty"`
2137
        Cluster   string   `json:"cluster,omitempty"`
2138
        Headers   bool     `json:"headers,omitempty"`
2139
        JetStream bool     `json:"jetstream,omitempty"`
2140
        DenyPub   []string `json:"deny_pub,omitempty"`
2141
        Isolate   bool     `json:"isolate,omitempty"`
2142

2143
        // There was an existing field called:
2144
        // >> Comp bool `json:"compression,omitempty"`
2145
        // that has never been used. With support for compression, we now need
2146
        // a field that is a string. So we use a different json tag:
2147
        Compression string `json:"compress_mode,omitempty"`
2148

2149
        // Just used to detect wrong connection attempts.
2150
        Gateway string `json:"gateway,omitempty"`
2151

2152
        // Tells the accept side which account the remote is binding to.
2153
        RemoteAccount string `json:"remote_account,omitempty"`
2154

2155
        // The accept side of a LEAF connection, unlike ROUTER and GATEWAY, receives
2156
        // only the CONNECT protocol, and no INFO. So we need to send the protocol
2157
        // version as part of the CONNECT. It will indicate if a connection supports
2158
        // some features, such as message tracing.
2159
        // We use `protocol` as the JSON tag, so this is automatically unmarshal'ed
2160
        // in the low level process CONNECT.
2161
        Proto int `json:"protocol,omitempty"`
2162
}
2163

2164
// processLeafNodeConnect will process the inbound connect args.
2165
// Once we are here we are bound to an account, so can send any interest that
2166
// we would have to the other side.
2167
func (c *client) processLeafNodeConnect(s *Server, arg []byte, lang string) error {
505✔
2168
        // Way to detect clients that incorrectly connect to the route listen
505✔
2169
        // port. Client provided "lang" in the CONNECT protocol while LEAFNODEs don't.
505✔
2170
        if lang != _EMPTY_ {
505✔
2171
                c.sendErrAndErr(ErrClientConnectedToLeafNodePort.Error())
×
2172
                c.closeConnection(WrongPort)
×
2173
                return ErrClientConnectedToLeafNodePort
×
2174
        }
×
2175

2176
        // Unmarshal as a leaf node connect protocol
2177
        proto := &leafConnectInfo{}
505✔
2178
        if err := json.Unmarshal(arg, proto); err != nil {
505✔
2179
                return err
×
2180
        }
×
2181

2182
        // Reject a cluster that contains spaces.
2183
        if proto.Cluster != _EMPTY_ && strings.Contains(proto.Cluster, " ") {
506✔
2184
                c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
2185
                c.closeConnection(ProtocolViolation)
1✔
2186
                return ErrClusterNameHasSpaces
1✔
2187
        }
1✔
2188

2189
        // Check for cluster name collisions.
2190
        if cn := s.cachedClusterName(); cn != _EMPTY_ && proto.Cluster != _EMPTY_ && proto.Cluster == cn {
507✔
2191
                c.sendErrAndErr(ErrLeafNodeHasSameClusterName.Error())
3✔
2192
                c.closeConnection(ClusterNamesIdentical)
3✔
2193
                return ErrLeafNodeHasSameClusterName
3✔
2194
        }
3✔
2195

2196
        // Reject if this has Gateway which means that it would be from a gateway
2197
        // connection that incorrectly connects to the leafnode port.
2198
        if proto.Gateway != _EMPTY_ {
501✔
2199
                errTxt := fmt.Sprintf("Rejecting connection from gateway %q on the leafnode port", proto.Gateway)
×
2200
                c.Errorf(errTxt)
×
2201
                c.sendErr(errTxt)
×
2202
                c.closeConnection(WrongGateway)
×
2203
                return ErrWrongGateway
×
2204
        }
×
2205

2206
        if mv := s.getOpts().LeafNode.MinVersion; mv != _EMPTY_ {
503✔
2207
                major, minor, update, _ := versionComponents(mv)
2✔
2208
                if !versionAtLeast(proto.Version, major, minor, update) {
3✔
2209
                        // Send back an INFO so recent remote servers process the rejection
1✔
2210
                        // cleanly, then close immediately. The soliciting side applies the
1✔
2211
                        // reconnect delay when it processes the error.
1✔
2212
                        s.sendPermsAndAccountInfo(c)
1✔
2213
                        c.sendErrAndErr(fmt.Sprintf("%s %q", ErrLeafNodeMinVersionRejected, mv))
1✔
2214
                        c.closeConnection(MinimumVersionRequired)
1✔
2215
                        return ErrMinimumVersionRequired
1✔
2216
                }
1✔
2217
        }
2218

2219
        // Check if this server supports headers.
2220
        supportHeaders := c.srv.supportsHeaders()
500✔
2221

500✔
2222
        c.mu.Lock()
500✔
2223
        // Leaf Nodes do not do echo or verbose or pedantic.
500✔
2224
        c.opts.Verbose = false
500✔
2225
        c.opts.Echo = false
500✔
2226
        c.opts.Pedantic = false
500✔
2227
        // This inbound connection will be marked as supporting headers if this server
500✔
2228
        // support headers and the remote has sent in the CONNECT protocol that it does
500✔
2229
        // support headers too.
500✔
2230
        c.headers = supportHeaders && proto.Headers
500✔
2231
        // If the compression level is still not set, set it based on what has been
500✔
2232
        // given to us in the CONNECT protocol.
500✔
2233
        if c.leaf.compression == _EMPTY_ {
618✔
2234
                // But if proto.Compression is _EMPTY_, set it to CompressionNotSupported
118✔
2235
                if proto.Compression == _EMPTY_ {
156✔
2236
                        c.leaf.compression = CompressionNotSupported
38✔
2237
                } else {
118✔
2238
                        c.leaf.compression = proto.Compression
80✔
2239
                }
80✔
2240
        }
2241

2242
        // Remember the remote server.
2243
        c.leaf.remoteServer = proto.Name
500✔
2244
        // Remember the remote account name
500✔
2245
        c.leaf.remoteAccName = proto.RemoteAccount
500✔
2246
        // Remember if the leafnode requested isolation.
500✔
2247
        c.leaf.isolated = c.leaf.isolated || proto.Isolate
500✔
2248

500✔
2249
        // If the other side has declared itself a hub, so we will take on the spoke role.
500✔
2250
        if proto.Hub {
512✔
2251
                c.leaf.isSpoke = true
12✔
2252
        }
12✔
2253

2254
        // The soliciting side is part of a cluster.
2255
        if proto.Cluster != _EMPTY_ {
861✔
2256
                c.leaf.remoteCluster = proto.Cluster
361✔
2257
        }
361✔
2258

2259
        c.leaf.remoteDomain = proto.Domain
500✔
2260

500✔
2261
        // When a leaf solicits a connection to a hub, the perms that it will use on the soliciting leafnode's
500✔
2262
        // behalf are correct for them, but inside the hub need to be reversed since data is flowing in the opposite direction.
500✔
2263
        if !c.isSolicitedLeafNode() && c.perms != nil {
505✔
2264
                sp, pp := c.perms.sub, c.perms.pub
5✔
2265
                c.perms.sub, c.perms.pub = pp, sp
5✔
2266
                if c.opts.Import != nil {
9✔
2267
                        c.darray = c.opts.Import.Deny
4✔
2268
                } else {
5✔
2269
                        c.darray = nil
1✔
2270
                }
1✔
2271
        }
2272

2273
        // Set the Ping timer
2274
        c.setFirstPingTimer()
500✔
2275

500✔
2276
        // If we received pub deny permissions from the other end, merge with existing ones.
500✔
2277
        c.mergeDenyPermissions(pub, proto.DenyPub)
500✔
2278

500✔
2279
        acc := c.acc
500✔
2280
        c.mu.Unlock()
500✔
2281

500✔
2282
        // If the account is not set (e.g. connection was closed due to auth
500✔
2283
        // timeout while still being processed), bail out to avoid a panic.
500✔
2284
        if acc == nil {
500✔
2285
                c.closeConnection(MissingAccount)
×
2286
                return ErrMissingAccount
×
2287
        }
×
2288

2289
        // Register the cluster, even if empty, as long as we are acting as a hub.
2290
        if !proto.Hub {
988✔
2291
                acc.registerLeafNodeCluster(proto.Cluster)
488✔
2292
        }
488✔
2293

2294
        // Add in the leafnode here since we passed through auth at this point.
2295
        s.addLeafNodeConnection(c, proto.Name, proto.Cluster, true)
500✔
2296

500✔
2297
        // If we have permissions bound to this leafnode we need to send then back to the
500✔
2298
        // origin server for local enforcement.
500✔
2299
        s.sendPermsAndAccountInfo(c)
500✔
2300

500✔
2301
        // Create and initialize the smap since we know our bound account now.
500✔
2302
        // This will send all registered subs too.
500✔
2303
        s.initLeafNodeSmapAndSendSubs(c)
500✔
2304

500✔
2305
        // Announce the account connect event for a leaf node.
500✔
2306
        // This will be a no-op as needed.
500✔
2307
        s.sendLeafNodeConnect(c.acc)
500✔
2308

500✔
2309
        // Check to see if we need to kick any internal source or mirror consumers.
500✔
2310
        // This will be a no-op if JetStream not enabled for this server or if the bound account
500✔
2311
        // does not have jetstream.
500✔
2312
        s.checkInternalSyncConsumers(acc)
500✔
2313

500✔
2314
        return nil
500✔
2315
}
2316

2317
// checkInternalSyncConsumers
2318
func (s *Server) checkInternalSyncConsumers(acc *Account) {
1,509✔
2319
        // Grab our js
1,509✔
2320
        js := s.getJetStream()
1,509✔
2321

1,509✔
2322
        // Only applicable if we have JS and the leafnode has JS as well.
1,509✔
2323
        // We check for remote JS outside.
1,509✔
2324
        if !js.isEnabled() || acc == nil {
2,313✔
2325
                return
804✔
2326
        }
804✔
2327

2328
        // We will check all streams in our local account. They must be a leader and
2329
        // be sourcing or mirroring. We will check the external config on the stream itself
2330
        // if this is cross domain, or if the remote domain is empty, meaning we might be
2331
        // extending the system across this leafnode connection and hence we would be extending
2332
        // our own domain.
2333
        jsa := js.lookupAccount(acc)
705✔
2334
        if jsa == nil {
973✔
2335
                return
268✔
2336
        }
268✔
2337

2338
        var streams []*stream
437✔
2339
        jsa.mu.RLock()
437✔
2340
        for _, mset := range jsa.streams {
495✔
2341
                mset.cfgMu.RLock()
58✔
2342
                // We need to have a mirror or source defined.
58✔
2343
                // We do not want to force another lock here to look for leader status,
58✔
2344
                // so collect and after we release jsa will make sure.
58✔
2345
                if mset.cfg.Mirror != nil || len(mset.cfg.Sources) > 0 {
71✔
2346
                        streams = append(streams, mset)
13✔
2347
                }
13✔
2348
                mset.cfgMu.RUnlock()
58✔
2349
        }
2350
        jsa.mu.RUnlock()
437✔
2351

437✔
2352
        // Now loop through all candidates and check if we are the leader and have NOT
437✔
2353
        // created the sync up consumer.
437✔
2354
        for _, mset := range streams {
450✔
2355
                mset.retryDisconnectedSyncConsumers()
13✔
2356
        }
13✔
2357
}
2358

2359
// Returns the remote cluster name. This is set only once so does not require a lock.
2360
func (c *client) remoteCluster() string {
118,215✔
2361
        if c.leaf == nil {
118,215✔
2362
                return _EMPTY_
×
2363
        }
×
2364
        return c.leaf.remoteCluster
118,215✔
2365
}
2366

2367
// Sends back an info block to the soliciting leafnode to let it know about
2368
// its permission settings for local enforcement.
2369
func (s *Server) sendPermsAndAccountInfo(c *client) {
501✔
2370
        // Copy
501✔
2371
        s.mu.Lock()
501✔
2372
        info := s.copyLeafNodeInfo()
501✔
2373
        s.mu.Unlock()
501✔
2374
        c.mu.Lock()
501✔
2375
        info.CID = c.cid
501✔
2376
        info.Import = c.opts.Import
501✔
2377
        info.Export = c.opts.Export
501✔
2378
        info.RemoteAccount = c.acc.Name
501✔
2379
        // s.SystemAccount() uses an atomic operation and does not get the server lock, so this is safe.
501✔
2380
        info.IsSystemAccount = c.acc == s.SystemAccount()
501✔
2381
        info.ConnectInfo = true
501✔
2382
        c.enqueueProto(generateInfoJSON(info))
501✔
2383
        c.mu.Unlock()
501✔
2384
}
501✔
2385

2386
// Snapshot the current subscriptions from the sublist into our smap which
2387
// we will keep updated from now on.
2388
// Also send the registered subscriptions.
2389
func (s *Server) initLeafNodeSmapAndSendSubs(c *client) {
959✔
2390
        acc := c.acc
959✔
2391
        if acc == nil {
959✔
2392
                c.Debugf("Leafnode does not have an account bound")
×
2393
                return
×
2394
        }
×
2395
        // Collect all account subs here.
2396
        _subs := [1024]*subscription{}
959✔
2397
        subs := _subs[:0]
959✔
2398
        ims := []string{}
959✔
2399

959✔
2400
        // Hold the client lock otherwise there can be a race and miss some subs.
959✔
2401
        c.mu.Lock()
959✔
2402
        defer c.mu.Unlock()
959✔
2403

959✔
2404
        acc.mu.RLock()
959✔
2405
        accName := acc.Name
959✔
2406
        accNTag := acc.nameTag
959✔
2407

959✔
2408
        // To make printing look better when no friendly name present.
959✔
2409
        if accNTag != _EMPTY_ {
962✔
2410
                accNTag = "/" + accNTag
3✔
2411
        }
3✔
2412

2413
        // If we are solicited we only send interest for local clients.
2414
        if c.isSpokeLeafNode() {
1,418✔
2415
                acc.sl.localSubs(&subs, true)
459✔
2416
        } else {
959✔
2417
                acc.sl.All(&subs)
500✔
2418
        }
500✔
2419

2420
        // Check if we have an existing service import reply.
2421
        siReply := copyBytes(acc.siReply)
959✔
2422

959✔
2423
        // Since leaf nodes only send on interest, if the bound
959✔
2424
        // account has import services we need to send those over.
959✔
2425
        for isubj := range acc.imports.services {
4,428✔
2426
                if c.isSpokeLeafNode() && !c.canSubscribe(isubj) {
3,691✔
2427
                        c.Debugf("Not permitted to import service %q on behalf of %s%s", isubj, accName, accNTag)
222✔
2428
                        continue
222✔
2429
                }
2430
                ims = append(ims, isubj)
3,247✔
2431
        }
2432
        // Likewise for mappings.
2433
        for _, m := range acc.mappings {
3,020✔
2434
                if c.isSpokeLeafNode() && !c.canSubscribe(m.src) {
2,079✔
2435
                        c.Debugf("Not permitted to import mapping %q on behalf of %s%s", m.src, accName, accNTag)
18✔
2436
                        continue
18✔
2437
                }
2438
                ims = append(ims, m.src)
2,043✔
2439
        }
2440

2441
        // Create a unique subject that will be used for loop detection.
2442
        lds := acc.lds
959✔
2443
        acc.mu.RUnlock()
959✔
2444

959✔
2445
        // Check if we have to create the LDS.
959✔
2446
        if lds == _EMPTY_ {
1,696✔
2447
                lds = leafNodeLoopDetectionSubjectPrefix + nuid.Next()
737✔
2448
                acc.mu.Lock()
737✔
2449
                acc.lds = lds
737✔
2450
                acc.mu.Unlock()
737✔
2451
        }
737✔
2452

2453
        // Now check for gateway interest. Leafnodes will put this into
2454
        // the proper mode to propagate, but they are not held in the account.
2455
        gwsa := [16]*client{}
959✔
2456
        gws := gwsa[:0]
959✔
2457
        s.getOutboundGatewayConnections(&gws)
959✔
2458
        for _, cgw := range gws {
1,018✔
2459
                cgw.mu.Lock()
59✔
2460
                gw := cgw.gw
59✔
2461
                cgw.mu.Unlock()
59✔
2462
                if gw != nil {
118✔
2463
                        if ei, _ := gw.outsim.Load(accName); ei != nil {
118✔
2464
                                if e := ei.(*outsie); e != nil && e.sl != nil {
118✔
2465
                                        e.sl.All(&subs)
59✔
2466
                                }
59✔
2467
                        }
2468
                }
2469
        }
2470

2471
        applyGlobalRouting := s.gateway.enabled
959✔
2472
        if c.isSpokeLeafNode() {
1,418✔
2473
                // Add a fake subscription for this solicited leafnode connection
459✔
2474
                // so that we can send back directly for mapped GW replies.
459✔
2475
                // We need to keep track of this subscription so it can be removed
459✔
2476
                // when the connection is closed so that the GC can release it.
459✔
2477
                c.leaf.gwSub = &subscription{client: c, subject: []byte(gwReplyPrefix + ">")}
459✔
2478
                c.srv.gwLeafSubs.Insert(c.leaf.gwSub)
459✔
2479
        }
459✔
2480

2481
        // Now walk the results and add them to our smap
2482
        rc := c.leaf.remoteCluster
959✔
2483
        c.leaf.smap = make(map[string]int32)
959✔
2484
        for _, sub := range subs {
33,244✔
2485
                // Check perms regardless of role.
32,285✔
2486
                if c.perms != nil && !c.canSubscribe(string(sub.subject)) {
34,267✔
2487
                        c.Debugf("Not permitted to subscribe to %q on behalf of %s%s", sub.subject, accName, accNTag)
1,982✔
2488
                        continue
1,982✔
2489
                }
2490
                // Don't advertise interest from leafnodes to other isolated leafnodes.
2491
                if sub.client.kind == LEAF && c.isIsolatedLeafNode() {
30,303✔
2492
                        continue
×
2493
                }
2494
                // We ignore ourselves here.
2495
                // Also don't add the subscription if it has a origin cluster and the
2496
                // cluster name matches the one of the client we are sending to.
2497
                if c != sub.client && (sub.origin == nil || (bytesToString(sub.origin) != rc)) {
56,218✔
2498
                        count := int32(1)
25,915✔
2499
                        if len(sub.queue) > 0 && sub.qw > 0 {
25,924✔
2500
                                count = sub.qw
9✔
2501
                        }
9✔
2502
                        c.leaf.smap[keyFromSub(sub)] += count
25,915✔
2503
                        if c.leaf.tsub == nil {
26,812✔
2504
                                c.leaf.tsub = make(map[*subscription]struct{})
897✔
2505
                        }
897✔
2506
                        c.leaf.tsub[sub] = struct{}{}
25,915✔
2507
                }
2508
        }
2509
        // FIXME(dlc) - We need to update appropriately on an account claims update.
2510
        for _, isubj := range ims {
6,249✔
2511
                c.leaf.smap[isubj]++
5,290✔
2512
        }
5,290✔
2513
        // If we have gateways enabled we need to make sure the other side sends us responses
2514
        // that have been augmented from the original subscription.
2515
        // TODO(dlc) - Should we lock this down more?
2516
        if applyGlobalRouting {
1,031✔
2517
                c.leaf.smap[oldGWReplyPrefix+"*.>"]++
72✔
2518
                c.leaf.smap[gwReplyPrefix+">"]++
72✔
2519
        }
72✔
2520
        // Detect loops by subscribing to a specific subject and checking
2521
        // if this sub is coming back to us.
2522
        c.leaf.smap[lds]++
959✔
2523

959✔
2524
        // Check if we need to add an existing siReply to our map.
959✔
2525
        // This will be a prefix so add on the wildcard.
959✔
2526
        if siReply != nil {
978✔
2527
                wcsub := append(siReply, '>')
19✔
2528
                c.leaf.smap[string(wcsub)]++
19✔
2529
        }
19✔
2530
        // Queue all protocols. There is no max pending limit for LN connection,
2531
        // so we don't need chunking. The writes will happen from the writeLoop.
2532
        var b bytes.Buffer
959✔
2533
        for key, n := range c.leaf.smap {
23,532✔
2534
                c.writeLeafSub(&b, key, n)
22,573✔
2535
        }
22,573✔
2536
        if b.Len() > 0 {
1,918✔
2537
                c.enqueueProto(b.Bytes())
959✔
2538
        }
959✔
2539
        if c.leaf.tsub != nil {
1,857✔
2540
                // Clear the tsub map after 5 seconds.
898✔
2541
                c.leaf.tsubt = time.AfterFunc(5*time.Second, func() {
937✔
2542
                        c.mu.Lock()
39✔
2543
                        if c.leaf != nil {
78✔
2544
                                c.leaf.tsub = nil
39✔
2545
                                c.leaf.tsubt = nil
39✔
2546
                        }
39✔
2547
                        c.mu.Unlock()
39✔
2548
                })
2549
        }
2550
}
2551

2552
// updateInterestForAccountOnGateway called from gateway code when processing RS+ and RS-.
2553
func (s *Server) updateInterestForAccountOnGateway(accName string, sub *subscription, delta int32) {
190,717✔
2554
        // Since we're in the gateway's readLoop, and we would otherwise block, don't allow fetching.
190,717✔
2555
        acc, err := s.lookupOrFetchAccount(accName, false)
190,717✔
2556
        if acc == nil || err != nil {
191,041✔
2557
                s.Debugf("No or bad account for %q, failed to update interest from gateway", accName)
324✔
2558
                return
324✔
2559
        }
324✔
2560
        acc.updateLeafNodes(sub, delta)
190,393✔
2561
}
2562

2563
// updateLeafNodesEx will make sure to update the account smap for the subscription.
2564
// Will also forward to all leaf nodes as needed.
2565
// If `hubOnly` is true, then will update only leaf nodes that connect to this server
2566
// (that is, for which this server acts as a hub to them).
2567
func (acc *Account) updateLeafNodesEx(sub *subscription, delta int32, hubOnly bool) {
2,419,454✔
2568
        if acc == nil || sub == nil {
2,419,454✔
2569
                return
×
2570
        }
×
2571

2572
        // We will do checks for no leafnodes and same cluster here inline and under the
2573
        // general account read lock.
2574
        // If we feel we need to update the leafnodes we will do that out of line to avoid
2575
        // blocking routes or GWs.
2576

2577
        acc.mu.RLock()
2,419,454✔
2578
        // First check if we even have leafnodes here.
2,419,454✔
2579
        if acc.nleafs == 0 {
4,785,314✔
2580
                acc.mu.RUnlock()
2,365,860✔
2581
                return
2,365,860✔
2582
        }
2,365,860✔
2583

2584
        // Is this a loop detection subject.
2585
        isLDS := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
53,594✔
2586

53,594✔
2587
        // Capture the cluster even if its empty.
53,594✔
2588
        var cluster string
53,594✔
2589
        if sub.origin != nil {
93,590✔
2590
                cluster = bytesToString(sub.origin)
39,996✔
2591
        }
39,996✔
2592

2593
        // If we have an isolated cluster we can return early, as long as it is not a loop detection subject.
2594
        // Empty clusters will return false for the check.
2595
        if !isLDS && acc.isLeafNodeClusterIsolated(cluster) {
69,663✔
2596
                acc.mu.RUnlock()
16,069✔
2597
                return
16,069✔
2598
        }
16,069✔
2599

2600
        // We can release the general account lock.
2601
        acc.mu.RUnlock()
37,525✔
2602

37,525✔
2603
        // We can hold the list lock here to avoid having to copy a large slice.
37,525✔
2604
        acc.lmu.RLock()
37,525✔
2605
        defer acc.lmu.RUnlock()
37,525✔
2606

37,525✔
2607
        // Do this once.
37,525✔
2608
        subject := string(sub.subject)
37,525✔
2609

37,525✔
2610
        // Walk the connected leafnodes from a random starting point to avoid
37,525✔
2611
        // concurrent callers all contending over leafs in the same order.
37,525✔
2612
        nleafs := len(acc.lleafs)
37,525✔
2613
        start := 0
37,525✔
2614
        if nleafs > 1 {
42,854✔
2615
                start = rand.Intn(nleafs)
5,329✔
2616
        }
5,329✔
2617
        for i := 0; i < nleafs; i++ {
83,262✔
2618
                ln := acc.lleafs[(start+i)%nleafs]
45,737✔
2619
                if ln == sub.client {
71,393✔
2620
                        continue
25,656✔
2621
                }
2622
                ln.mu.RLock()
20,081✔
2623
                // Don't advertise interest from leafnodes to other isolated leafnodes.
20,081✔
2624
                if sub.client.kind == LEAF && ln.isIsolatedLeafNode() {
20,081✔
2625
                        ln.mu.RUnlock()
×
2626
                        continue
×
2627
                }
2628
                // If `hubOnly` is true, it means that we want to update only leafnodes
2629
                // that connect to this server (so isHubLeafNode() would return `true`).
2630
                if hubOnly && !ln.isHubLeafNode() {
20,087✔
2631
                        ln.mu.RUnlock()
6✔
2632
                        continue
6✔
2633
                }
2634
                // Check to make sure this sub does not have an origin cluster that matches the leafnode.
2635
                // If skipped, make sure that we still let go the "$LDS." subscription that allows
2636
                // the detection of loops as long as different cluster.
2637
                clusterDifferent := cluster != ln.remoteCluster()
20,075✔
2638
                update := (isLDS && clusterDifferent) ||
20,075✔
2639
                        ((cluster == _EMPTY_ || clusterDifferent) && (delta <= 0 || ln.canSubscribeInternal(subject)))
20,075✔
2640
                ln.mu.RUnlock()
20,075✔
2641
                if update {
37,420✔
2642
                        ln.mu.Lock()
17,345✔
2643
                        // The leaf role, isolation mode, and remote cluster are stable
17,345✔
2644
                        // for the connection. Recheck canSubscribe here since permissions
17,345✔
2645
                        // can change, and to initializes mperms for wildcard subscriptions
17,345✔
2646
                        // that collide with deny rules.
17,345✔
2647
                        if isLDS || delta <= 0 || ln.canSubscribe(subject) {
34,690✔
2648
                                ln.updateSmap(sub, delta, isLDS)
17,345✔
2649
                        }
17,345✔
2650
                        ln.mu.Unlock()
17,345✔
2651
                }
2652
        }
2653
}
2654

2655
// updateLeafNodes will make sure to update the account smap for the subscription.
2656
// Will also forward to all leaf nodes as needed.
2657
func (acc *Account) updateLeafNodes(sub *subscription, delta int32) {
2,419,441✔
2658
        acc.updateLeafNodesEx(sub, delta, false)
2,419,441✔
2659
}
2,419,441✔
2660

2661
// This will make an update to our internal smap and determine if we should send out
2662
// an interest update to the remote side.
2663
// Lock should be held.
2664
func (c *client) updateSmap(sub *subscription, delta int32, isLDS bool) {
17,345✔
2665
        if c.leaf.smap == nil {
17,350✔
2666
                return
5✔
2667
        }
5✔
2668

2669
        // If we are solicited make sure this is a local client or a non-solicited leaf node
2670
        skind := sub.client.kind
17,340✔
2671
        updateClient := skind == CLIENT || skind == SYSTEM || skind == JETSTREAM || skind == ACCOUNT
17,340✔
2672
        if !isLDS && c.isSpokeLeafNode() && !(updateClient || (skind == LEAF && !sub.client.isSpokeLeafNode())) {
22,049✔
2673
                return
4,709✔
2674
        }
4,709✔
2675

2676
        // For additions, check if that sub has just been processed during initLeafNodeSmapAndSendSubs
2677
        if delta > 0 && c.leaf.tsub != nil {
18,763✔
2678
                if _, present := c.leaf.tsub[sub]; present {
6,134✔
2679
                        delete(c.leaf.tsub, sub)
2✔
2680
                        if len(c.leaf.tsub) == 0 {
2✔
2681
                                c.leaf.tsub = nil
×
2682
                                c.leaf.tsubt.Stop()
×
2683
                                c.leaf.tsubt = nil
×
2684
                        }
×
2685
                        return
2✔
2686
                }
2687
        }
2688

2689
        key := keyFromSub(sub)
12,629✔
2690
        n, ok := c.leaf.smap[key]
12,629✔
2691
        if delta < 0 && !ok {
13,310✔
2692
                return
681✔
2693
        }
681✔
2694

2695
        // We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
2696
        update := sub.queue != nil || (n <= 0 && n+delta > 0) || (n > 0 && n+delta <= 0)
11,948✔
2697
        n += delta
11,948✔
2698
        if n > 0 {
20,682✔
2699
                c.leaf.smap[key] = n
8,734✔
2700
        } else {
11,948✔
2701
                delete(c.leaf.smap, key)
3,214✔
2702
        }
3,214✔
2703
        if update {
19,148✔
2704
                c.sendLeafNodeSubUpdate(key, n)
7,200✔
2705
        }
7,200✔
2706
}
2707

2708
// Used to force add subjects to the subject map.
2709
func (c *client) forceAddToSmap(subj string) {
2✔
2710
        c.mu.Lock()
2✔
2711
        defer c.mu.Unlock()
2✔
2712

2✔
2713
        if c.leaf.smap == nil {
2✔
2714
                return
×
2715
        }
×
2716
        n := c.leaf.smap[subj]
2✔
2717
        if n != 0 {
2✔
2718
                return
×
2719
        }
×
2720
        // Place into the map since it was not there.
2721
        c.leaf.smap[subj] = 1
2✔
2722
        c.sendLeafNodeSubUpdate(subj, 1)
2✔
2723
}
2724

2725
// Used to force remove a subject from the subject map.
2726
func (c *client) forceRemoveFromSmap(subj string) {
×
2727
        c.mu.Lock()
×
2728
        defer c.mu.Unlock()
×
2729

×
2730
        if c.leaf.smap == nil {
×
2731
                return
×
2732
        }
×
2733
        n := c.leaf.smap[subj]
×
2734
        if n == 0 {
×
2735
                return
×
2736
        }
×
2737
        n--
×
2738
        if n == 0 {
×
2739
                // Remove is now zero
×
2740
                delete(c.leaf.smap, subj)
×
2741
                c.sendLeafNodeSubUpdate(subj, 0)
×
2742
        } else {
×
2743
                c.leaf.smap[subj] = n
×
2744
        }
×
2745
}
2746

2747
// Send the subscription interest change to the other side.
2748
// Lock should be held.
2749
func (c *client) sendLeafNodeSubUpdate(key string, n int32) {
7,202✔
2750
        // If we are a spoke, we need to check if we are allowed to send this subscription over to the hub.
7,202✔
2751
        if c.isSpokeLeafNode() {
9,174✔
2752
                checkPerms := true
1,972✔
2753
                if len(key) > 0 && (key[0] == '$' || key[0] == '_') {
3,188✔
2754
                        if strings.HasPrefix(key, leafNodeLoopDetectionSubjectPrefix) ||
1,216✔
2755
                                strings.HasPrefix(key, oldGWReplyPrefix) ||
1,216✔
2756
                                strings.HasPrefix(key, gwReplyPrefix) {
1,280✔
2757
                                checkPerms = false
64✔
2758
                        }
64✔
2759
                }
2760
                if checkPerms {
3,880✔
2761
                        var subject string
1,908✔
2762
                        if sep := strings.IndexByte(key, ' '); sep != -1 {
2,333✔
2763
                                subject = key[:sep]
425✔
2764
                        } else {
1,908✔
2765
                                subject = key
1,483✔
2766
                        }
1,483✔
2767
                        if !c.canSubscribe(subject) {
1,908✔
2768
                                return
×
2769
                        }
×
2770
                }
2771
        }
2772
        // If we are here we can send over to the other side.
2773
        _b := [64]byte{}
7,202✔
2774
        b := bytes.NewBuffer(_b[:0])
7,202✔
2775
        c.writeLeafSub(b, key, n)
7,202✔
2776
        c.enqueueProto(b.Bytes())
7,202✔
2777
}
2778

2779
// Helper function to build the key.
2780
func keyFromSub(sub *subscription) string {
39,411✔
2781
        var sb strings.Builder
39,411✔
2782
        sb.Grow(len(sub.subject) + len(sub.queue) + 1)
39,411✔
2783
        sb.Write(sub.subject)
39,411✔
2784
        if sub.queue != nil {
41,428✔
2785
                // Just make the key subject spc group, e.g. 'foo bar'
2,017✔
2786
                sb.WriteByte(' ')
2,017✔
2787
                sb.Write(sub.queue)
2,017✔
2788
        }
2,017✔
2789
        return sb.String()
39,411✔
2790
}
2791

2792
const (
2793
        keyRoutedSub         = "R"
2794
        keyRoutedSubByte     = 'R'
2795
        keyRoutedLeafSub     = "L"
2796
        keyRoutedLeafSubByte = 'L'
2797
)
2798

2799
// Helper function to build the key that prevents collisions between normal
2800
// routed subscriptions and routed subscriptions on behalf of a leafnode.
2801
// Keys will look like this:
2802
// "R foo"          -> plain routed sub on "foo"
2803
// "R foo bar"      -> queue routed sub on "foo", queue "bar"
2804
// "L foo bar"      -> plain routed leaf sub on "foo", leaf "bar"
2805
// "L foo bar baz"  -> queue routed sub on "foo", queue "bar", leaf "baz"
2806
func keyFromSubWithOrigin(sub *subscription) string {
702,236✔
2807
        var sb strings.Builder
702,236✔
2808
        sb.Grow(2 + len(sub.origin) + 1 + len(sub.subject) + 1 + len(sub.queue))
702,236✔
2809
        leaf := len(sub.origin) > 0
702,236✔
2810
        if leaf {
715,950✔
2811
                sb.WriteByte(keyRoutedLeafSubByte)
13,714✔
2812
        } else {
702,236✔
2813
                sb.WriteByte(keyRoutedSubByte)
688,522✔
2814
        }
688,522✔
2815
        sb.WriteByte(' ')
702,236✔
2816
        sb.Write(sub.subject)
702,236✔
2817
        if sub.queue != nil {
727,826✔
2818
                sb.WriteByte(' ')
25,590✔
2819
                sb.Write(sub.queue)
25,590✔
2820
        }
25,590✔
2821
        if leaf {
715,950✔
2822
                sb.WriteByte(' ')
13,714✔
2823
                sb.Write(sub.origin)
13,714✔
2824
        }
13,714✔
2825
        return sb.String()
702,236✔
2826
}
2827

2828
// Lock should be held.
2829
func (c *client) writeLeafSub(w *bytes.Buffer, key string, n int32) {
29,775✔
2830
        if key == _EMPTY_ {
29,775✔
2831
                return
×
2832
        }
×
2833
        if n > 0 {
56,336✔
2834
                w.WriteString("LS+ " + key)
26,561✔
2835
                // Check for queue semantics, if found write n.
26,561✔
2836
                if strings.Contains(key, " ") {
27,298✔
2837
                        w.WriteString(" ")
737✔
2838
                        var b [12]byte
737✔
2839
                        var i = len(b)
737✔
2840
                        for l := n; l > 0; l /= 10 {
1,474✔
2841
                                i--
737✔
2842
                                b[i] = digits[l%10]
737✔
2843
                        }
737✔
2844
                        w.Write(b[i:])
737✔
2845
                        if c.trace {
737✔
2846
                                arg := fmt.Sprintf("%s %d", key, n)
×
2847
                                c.traceOutOp("LS+", []byte(arg))
×
2848
                        }
×
2849
                } else if c.trace {
25,840✔
2850
                        c.traceOutOp("LS+", []byte(key))
16✔
2851
                }
16✔
2852
        } else {
3,214✔
2853
                w.WriteString("LS- " + key)
3,214✔
2854
                if c.trace {
3,214✔
2855
                        c.traceOutOp("LS-", []byte(key))
×
2856
                }
×
2857
        }
2858
        w.WriteString(CR_LF)
29,775✔
2859
}
2860

2861
// processLeafSub will process an inbound sub request for the remote leaf node.
2862
func (c *client) processLeafSub(argo []byte) (err error) {
26,304✔
2863
        // Indicate activity.
26,304✔
2864
        c.in.subs++
26,304✔
2865

26,304✔
2866
        srv := c.srv
26,304✔
2867
        if srv == nil {
26,304✔
2868
                return nil
×
2869
        }
×
2870

2871
        // Copy so we do not reference a potentially large buffer
2872
        arg := make([]byte, len(argo))
26,304✔
2873
        copy(arg, argo)
26,304✔
2874

26,304✔
2875
        args := splitArg(arg)
26,304✔
2876
        sub := &subscription{client: c}
26,304✔
2877

26,304✔
2878
        delta := int32(1)
26,304✔
2879
        switch len(args) {
26,304✔
2880
        case 1:
25,580✔
2881
                sub.queue = nil
25,580✔
2882
        case 3:
724✔
2883
                sub.queue = args[1]
724✔
2884
                sub.qw = int32(parseSize(args[2]))
724✔
2885
                // TODO: (ik) We should have a non empty queue name and a queue
724✔
2886
                // weight >= 1. For 2.11, we may want to return an error if that
724✔
2887
                // is not the case, but for now just overwrite `delta` if queue
724✔
2888
                // weight is greater than 1 (it is possible after a reconnect/
724✔
2889
                // server restart to receive a queue weight > 1 for a new sub).
724✔
2890
                if sub.qw > 1 {
941✔
2891
                        delta = sub.qw
217✔
2892
                }
217✔
2893
        default:
×
2894
                return fmt.Errorf("processLeafSub Parse Error: '%s'", arg)
×
2895
        }
2896
        sub.subject = args[0]
26,304✔
2897

26,304✔
2898
        c.mu.Lock()
26,304✔
2899
        if c.isClosed() {
26,317✔
2900
                c.mu.Unlock()
13✔
2901
                return nil
13✔
2902
        }
13✔
2903

2904
        acc := c.acc
26,291✔
2905
        // Guard against LS+ arriving before CONNECT has been processed, which
26,291✔
2906
        // can happen when compression is enabled.
26,291✔
2907
        if acc == nil {
26,291✔
2908
                c.mu.Unlock()
×
2909
                c.sendErr("Authorization Violation")
×
2910
                c.closeConnection(ProtocolViolation)
×
2911
                return nil
×
2912
        }
×
2913
        // Check if we have a loop.
2914
        ldsPrefix := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
26,291✔
2915

26,291✔
2916
        if ldsPrefix && bytesToString(sub.subject) == acc.getLDSubject() {
26,296✔
2917
                c.mu.Unlock()
5✔
2918
                c.handleLeafNodeLoop(true)
5✔
2919
                return nil
5✔
2920
        }
5✔
2921

2922
        // Check permissions if applicable. (but exclude the $LDS, $GR and _GR_)
2923
        checkPerms := true
26,286✔
2924
        if sub.subject[0] == '$' || sub.subject[0] == '_' {
51,383✔
2925
                if ldsPrefix ||
25,097✔
2926
                        bytes.HasPrefix(sub.subject, []byte(oldGWReplyPrefix)) ||
25,097✔
2927
                        bytes.HasPrefix(sub.subject, []byte(gwReplyPrefix)) {
26,651✔
2928
                        checkPerms = false
1,554✔
2929
                }
1,554✔
2930
        }
2931

2932
        // If we are a hub check that we can publish to this subject.
2933
        if checkPerms {
51,018✔
2934
                subj := string(sub.subject)
24,732✔
2935
                if subjectIsLiteral(subj) && !c.pubAllowedFullCheck(subj, true, true) {
24,745✔
2936
                        c.mu.Unlock()
13✔
2937
                        c.leafSubPermViolation(sub.subject)
13✔
2938
                        c.Debugf(fmt.Sprintf("Permissions Violation for Subscription to %q", sub.subject))
13✔
2939
                        return nil
13✔
2940
                }
13✔
2941
        }
2942

2943
        // Check if we have a maximum on the number of subscriptions.
2944
        if c.subsAtLimit() {
26,281✔
2945
                c.mu.Unlock()
8✔
2946
                c.maxSubsExceeded()
8✔
2947
                return nil
8✔
2948
        }
8✔
2949

2950
        // If we have an origin cluster associated mark that in the sub.
2951
        if rc := c.remoteCluster(); rc != _EMPTY_ {
49,434✔
2952
                sub.origin = []byte(rc)
23,169✔
2953
        }
23,169✔
2954

2955
        // Like Routes, we store local subs by account and subject and optionally queue name.
2956
        // If we have a queue it will have a trailing weight which we do not want.
2957
        if sub.queue != nil {
26,989✔
2958
                sub.sid = arg[:len(arg)-len(args[2])-1]
724✔
2959
        } else {
26,265✔
2960
                sub.sid = arg
25,541✔
2961
        }
25,541✔
2962
        key := bytesToString(sub.sid)
26,265✔
2963
        osub := c.subs[key]
26,265✔
2964
        if osub == nil {
52,220✔
2965
                c.subs[key] = sub
25,955✔
2966
                // Now place into the account sl.
25,955✔
2967
                if err := acc.sl.Insert(sub); err != nil {
25,955✔
2968
                        delete(c.subs, key)
×
2969
                        c.mu.Unlock()
×
2970
                        c.Errorf("Could not insert subscription: %v", err)
×
2971
                        c.sendErr("Invalid Subscription")
×
2972
                        return nil
×
2973
                }
×
2974
        } else if sub.queue != nil {
619✔
2975
                // For a queue we need to update the weight.
309✔
2976
                delta = sub.qw - atomic.LoadInt32(&osub.qw)
309✔
2977
                atomic.StoreInt32(&osub.qw, sub.qw)
309✔
2978
                acc.sl.UpdateRemoteQSub(osub)
309✔
2979
        }
309✔
2980
        spoke := c.isSpokeLeafNode()
26,265✔
2981
        c.mu.Unlock()
26,265✔
2982

26,265✔
2983
        // Only add in shadow subs if a new sub or qsub.
26,265✔
2984
        if osub == nil {
52,220✔
2985
                if err := c.addShadowSubscriptions(acc, sub); err != nil {
25,955✔
2986
                        c.Errorf(err.Error())
×
2987
                }
×
2988
        }
2989

2990
        // If we are not solicited, treat leaf node subscriptions similar to a
2991
        // client subscription, meaning we forward them to routes, gateways and
2992
        // other leaf nodes as needed.
2993
        if !spoke {
35,554✔
2994
                // If we are routing add to the route map for the associated account.
9,289✔
2995
                srv.updateRouteSubscriptionMap(acc, sub, delta)
9,289✔
2996
                if srv.gateway.enabled {
10,187✔
2997
                        srv.gatewayUpdateSubInterest(acc.Name, sub, delta)
898✔
2998
                }
898✔
2999
        }
3000
        // Now check on leafnode updates for other leaf nodes. We understand solicited
3001
        // and non-solicited state in this call so we will do the right thing.
3002
        acc.updateLeafNodes(sub, delta)
26,265✔
3003

26,265✔
3004
        return nil
26,265✔
3005
}
3006

3007
// If the leafnode is a solicited, set the connect delay based on default
3008
// or private option (for tests). Sends the error to the other side, log and
3009
// close the connection.
3010
func (c *client) handleLeafNodeLoop(sendErr bool) {
12✔
3011
        accName, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterLoopDetected)
12✔
3012
        errTxt := fmt.Sprintf("Loop detected for leafnode account=%q. Delaying attempt to reconnect for %v", accName, delay)
12✔
3013
        if sendErr {
19✔
3014
                c.sendErr(errTxt)
7✔
3015
        }
7✔
3016

3017
        c.Errorf(errTxt)
12✔
3018
        // If we are here with "sendErr" false, it means that this is the server
12✔
3019
        // that received the error. The other side will have closed the connection,
12✔
3020
        // but does not hurt to close here too.
12✔
3021
        c.closeConnection(ProtocolViolation)
12✔
3022
}
3023

3024
// processLeafUnsub will process an inbound unsub request for the remote leaf node.
3025
func (c *client) processLeafUnsub(arg []byte) error {
2,954✔
3026
        // Indicate any activity, so pub and sub or unsubs.
2,954✔
3027
        c.in.subs++
2,954✔
3028

2,954✔
3029
        srv := c.srv
2,954✔
3030

2,954✔
3031
        c.mu.Lock()
2,954✔
3032
        if c.isClosed() {
2,967✔
3033
                c.mu.Unlock()
13✔
3034
                return nil
13✔
3035
        }
13✔
3036

3037
        acc := c.acc
2,941✔
3038
        // Guard against LS- arriving before CONNECT has been processed.
2,941✔
3039
        if acc == nil {
2,941✔
3040
                c.mu.Unlock()
×
3041
                c.sendErr("Authorization Violation")
×
3042
                c.closeConnection(ProtocolViolation)
×
3043
                return nil
×
3044
        }
×
3045

3046
        spoke := c.isSpokeLeafNode()
2,941✔
3047
        // We store local subs by account and subject and optionally queue name.
2,941✔
3048
        // LS- will have the arg exactly as the key.
2,941✔
3049
        sub, ok := c.subs[string(arg)]
2,941✔
3050
        if !ok {
2,941✔
3051
                // If not found, don't try to update routes/gws/leaf nodes.
×
3052
                c.mu.Unlock()
×
3053
                return nil
×
3054
        }
×
3055
        delta := int32(1)
2,941✔
3056
        if len(sub.queue) > 0 {
3,324✔
3057
                delta = sub.qw
383✔
3058
        }
383✔
3059
        c.mu.Unlock()
2,941✔
3060

2,941✔
3061
        c.unsubscribe(acc, sub, true, true)
2,941✔
3062
        if !spoke {
3,787✔
3063
                // If we are routing subtract from the route map for the associated account.
846✔
3064
                srv.updateRouteSubscriptionMap(acc, sub, -delta)
846✔
3065
                // Gateways
846✔
3066
                if srv.gateway.enabled {
1,025✔
3067
                        srv.gatewayUpdateSubInterest(acc.Name, sub, -delta)
179✔
3068
                }
179✔
3069
        }
3070
        // Now check on leafnode updates for other leaf nodes.
3071
        acc.updateLeafNodes(sub, -delta)
2,941✔
3072
        return nil
2,941✔
3073
}
3074

3075
func (c *client) processLeafHeaderMsgArgs(arg []byte) error {
231✔
3076
        // Unroll splitArgs to avoid runtime/heap issues
231✔
3077
        args := c.argsa[:0]
231✔
3078
        start := -1
231✔
3079
        for i, b := range arg {
12,739✔
3080
                switch b {
12,508✔
3081
                case ' ', '\t', '\r', '\n':
677✔
3082
                        if start >= 0 {
1,354✔
3083
                                args = append(args, arg[start:i])
677✔
3084
                                start = -1
677✔
3085
                        }
677✔
3086
                default:
11,831✔
3087
                        if start < 0 {
12,739✔
3088
                                start = i
908✔
3089
                        }
908✔
3090
                }
3091
        }
3092
        if start >= 0 {
462✔
3093
                args = append(args, arg[start:])
231✔
3094
        }
231✔
3095

3096
        c.pa.arg = arg
231✔
3097
        switch len(args) {
231✔
3098
        case 0, 1, 2:
×
3099
                return fmt.Errorf("processLeafHeaderMsgArgs Parse Error: '%s'", args)
×
3100
        case 3:
21✔
3101
                c.pa.reply = nil
21✔
3102
                c.pa.queues = nil
21✔
3103
                c.pa.hdb = args[1]
21✔
3104
                c.pa.hdr = parseSize(args[1])
21✔
3105
                c.pa.szb = args[2]
21✔
3106
                c.pa.size = parseSize(args[2])
21✔
3107
        case 4:
207✔
3108
                c.pa.reply = args[1]
207✔
3109
                c.pa.queues = nil
207✔
3110
                c.pa.hdb = args[2]
207✔
3111
                c.pa.hdr = parseSize(args[2])
207✔
3112
                c.pa.szb = args[3]
207✔
3113
                c.pa.size = parseSize(args[3])
207✔
3114
        default:
3✔
3115
                // args[1] is our reply indicator. Should be + or | normally.
3✔
3116
                if len(args[1]) != 1 {
3✔
3117
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3118
                }
×
3119
                switch args[1][0] {
3✔
3120
                case '+':
2✔
3121
                        c.pa.reply = args[2]
2✔
3122
                case '|':
1✔
3123
                        c.pa.reply = nil
1✔
3124
                default:
×
3125
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3126
                }
3127
                // Grab header size.
3128
                c.pa.hdb = args[len(args)-2]
3✔
3129
                c.pa.hdr = parseSize(c.pa.hdb)
3✔
3130

3✔
3131
                // Grab size.
3✔
3132
                c.pa.szb = args[len(args)-1]
3✔
3133
                c.pa.size = parseSize(c.pa.szb)
3✔
3134

3✔
3135
                // Grab queue names.
3✔
3136
                if c.pa.reply != nil {
5✔
3137
                        c.pa.queues = args[3 : len(args)-2]
2✔
3138
                } else {
3✔
3139
                        c.pa.queues = args[2 : len(args)-2]
1✔
3140
                }
1✔
3141
        }
3142
        if c.pa.hdr < 0 {
231✔
3143
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Header Size: '%s'", arg)
×
3144
        }
×
3145
        if c.pa.size < 0 {
231✔
3146
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Size: '%s'", args)
×
3147
        }
×
3148
        if c.pa.hdr > c.pa.size {
231✔
3149
                return fmt.Errorf("processLeafHeaderMsgArgs Header Size larger then TotalSize: '%s'", arg)
×
3150
        }
×
3151
        maxPayload := atomic.LoadInt32(&c.mpay)
231✔
3152
        if maxPayload != jwt.NoLimit && int64(c.pa.size) > int64(maxPayload) {
231✔
3153
                c.maxPayloadViolation(c.pa.size, maxPayload)
×
3154
                return ErrMaxPayload
×
3155
        }
×
3156

3157
        // Common ones processed after check for arg length
3158
        c.pa.subject = args[0]
231✔
3159

231✔
3160
        return nil
231✔
3161
}
3162

3163
func (c *client) processLeafMsgArgs(arg []byte) error {
59,835✔
3164
        // Unroll splitArgs to avoid runtime/heap issues
59,835✔
3165
        args := c.argsa[:0]
59,835✔
3166
        start := -1
59,835✔
3167
        for i, b := range arg {
2,108,518✔
3168
                switch b {
2,048,683✔
3169
                case ' ', '\t', '\r', '\n':
96,738✔
3170
                        if start >= 0 {
193,476✔
3171
                                args = append(args, arg[start:i])
96,738✔
3172
                                start = -1
96,738✔
3173
                        }
96,738✔
3174
                default:
1,951,945✔
3175
                        if start < 0 {
2,108,518✔
3176
                                start = i
156,573✔
3177
                        }
156,573✔
3178
                }
3179
        }
3180
        if start >= 0 {
119,670✔
3181
                args = append(args, arg[start:])
59,835✔
3182
        }
59,835✔
3183

3184
        c.pa.arg = arg
59,835✔
3185
        switch len(args) {
59,835✔
3186
        case 0, 1:
×
3187
                return fmt.Errorf("processLeafMsgArgs Parse Error: '%s'", args)
×
3188
        case 2:
38,294✔
3189
                c.pa.reply = nil
38,294✔
3190
                c.pa.queues = nil
38,294✔
3191
                c.pa.szb = args[1]
38,294✔
3192
                c.pa.size = parseSize(args[1])
38,294✔
3193
        case 3:
6,338✔
3194
                c.pa.reply = args[1]
6,338✔
3195
                c.pa.queues = nil
6,338✔
3196
                c.pa.szb = args[2]
6,338✔
3197
                c.pa.size = parseSize(args[2])
6,338✔
3198
        default:
15,203✔
3199
                // args[1] is our reply indicator. Should be + or | normally.
15,203✔
3200
                if len(args[1]) != 1 {
15,203✔
3201
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3202
                }
×
3203
                switch args[1][0] {
15,203✔
3204
                case '+':
159✔
3205
                        c.pa.reply = args[2]
159✔
3206
                case '|':
15,044✔
3207
                        c.pa.reply = nil
15,044✔
3208
                default:
×
3209
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3210
                }
3211
                // Grab size.
3212
                c.pa.szb = args[len(args)-1]
15,203✔
3213
                c.pa.size = parseSize(c.pa.szb)
15,203✔
3214

15,203✔
3215
                // Grab queue names.
15,203✔
3216
                if c.pa.reply != nil {
15,362✔
3217
                        c.pa.queues = args[3 : len(args)-1]
159✔
3218
                } else {
15,203✔
3219
                        c.pa.queues = args[2 : len(args)-1]
15,044✔
3220
                }
15,044✔
3221
        }
3222
        if c.pa.size < 0 {
59,835✔
3223
                return fmt.Errorf("processLeafMsgArgs Bad or Missing Size: '%s'", args)
×
3224
        }
×
3225
        maxPayload := atomic.LoadInt32(&c.mpay)
59,835✔
3226
        if maxPayload != jwt.NoLimit && int64(c.pa.size) > int64(maxPayload) {
59,835✔
3227
                c.maxPayloadViolation(c.pa.size, maxPayload)
×
3228
                return ErrMaxPayload
×
3229
        }
×
3230

3231
        // Common ones processed after check for arg length
3232
        c.pa.subject = args[0]
59,835✔
3233

59,835✔
3234
        return nil
59,835✔
3235
}
3236

3237
// processInboundLeafMsg is called to process an inbound msg from a leaf node.
3238
func (c *client) processInboundLeafMsg(msg []byte) {
58,795✔
3239
        // Update statistics
58,795✔
3240
        // The msg includes the CR_LF, so pull back out for accounting.
58,795✔
3241
        c.in.msgs++
58,795✔
3242
        c.in.bytes += int32(len(msg) - LEN_CR_LF)
58,795✔
3243

58,795✔
3244
        srv, acc, subject := c.srv, c.acc, string(c.pa.subject)
58,795✔
3245

58,795✔
3246
        // Mostly under testing scenarios.
58,795✔
3247
        if srv == nil || acc == nil {
58,795✔
3248
                return
×
3249
        }
×
3250

3251
        // Check that leaf messages respect the subject permissions.
3252
        if c.perms != nil && !c.leafMsgAllowed() {
58,795✔
3253
                c.leafPubPermViolation(c.pa.subject)
×
3254
                return
×
3255
        }
×
3256

3257
        // Match the subscriptions. We will use our own L1 map if
3258
        // it's still valid, avoiding contention on the shared sublist.
3259
        var r *SublistResult
58,795✔
3260
        var ok bool
58,795✔
3261

58,795✔
3262
        genid := atomic.LoadUint64(&c.acc.sl.genid)
58,795✔
3263
        if genid == c.in.genid && c.in.results != nil {
115,692✔
3264
                r, ok = c.in.results[subject]
56,897✔
3265
        } else {
58,795✔
3266
                // Reset our L1 completely.
1,898✔
3267
                c.in.results = make(map[string]*SublistResult)
1,898✔
3268
                c.in.genid = genid
1,898✔
3269
        }
1,898✔
3270

3271
        // Go back to the sublist data structure.
3272
        if !ok {
95,262✔
3273
                r = c.acc.sl.Match(subject)
36,467✔
3274
                // Prune the results cache. Keeps us from unbounded growth. Random delete.
36,467✔
3275
                if len(c.in.results) >= maxResultCacheSize {
37,423✔
3276
                        n := 0
956✔
3277
                        for subj := range c.in.results {
32,504✔
3278
                                delete(c.in.results, subj)
31,548✔
3279
                                if n++; n > pruneSize {
32,504✔
3280
                                        break
956✔
3281
                                }
3282
                        }
3283
                }
3284
                // Then add the new cache entry.
3285
                c.in.results[subject] = r
36,467✔
3286
        }
3287

3288
        // Collect queue names if needed.
3289
        var qnames [][]byte
58,795✔
3290

58,795✔
3291
        // Check for no interest, short circuit if so.
58,795✔
3292
        // This is the fanout scale.
58,795✔
3293
        if len(r.psubs)+len(r.qsubs) > 0 {
117,344✔
3294
                flag := pmrNoFlag
58,549✔
3295
                // If we have queue subs in this cluster, then if we run in gateway
58,549✔
3296
                // mode and the remote gateways have queue subs, then we need to
58,549✔
3297
                // collect the queue groups this message was sent to so that we
58,549✔
3298
                // exclude them when sending to gateways.
58,549✔
3299
                if len(r.qsubs) > 0 && c.srv.gateway.enabled &&
58,549✔
3300
                        atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 {
63,755✔
3301
                        flag |= pmrCollectQueueNames
5,206✔
3302
                }
5,206✔
3303
                // If this is a mapped subject that means the mapped interest
3304
                // is what got us here, but this might not have a queue designation
3305
                // If that is the case, make sure we ignore to process local queue subscribers.
3306
                if len(c.pa.mapped) > 0 && len(c.pa.queues) == 0 {
58,793✔
3307
                        flag |= pmrIgnoreEmptyQueueFilter
244✔
3308
                }
244✔
3309
                _, qnames = c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, flag)
58,549✔
3310
        }
3311

3312
        // Now deal with gateways
3313
        if c.srv.gateway.enabled {
64,772✔
3314
                c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, qnames, true)
5,977✔
3315
        }
5,977✔
3316
}
3317

3318
// Checks whether the inbound leaf message is allowed by the
3319
// connection's permissions. On the hub side this enforces what
3320
// the remote leaf may publish. On the spoke side this enforces
3321
// import restrictions such as deny_imports.
3322
func (c *client) leafMsgAllowed() bool {
55,062✔
3323
        wireSubject := c.pa.subject
55,062✔
3324
        if len(c.pa.mapped) > 0 {
55,306✔
3325
                // Mappings rewrite c.pa.subject to the internal
244✔
3326
                // destination. For leaf ACLs, need to check
244✔
3327
                // the original wire subject from the remote side.
244✔
3328
                wireSubject = c.pa.mapped
244✔
3329
        }
244✔
3330
        // Strip any gateway routing prefix for the permission check.
3331
        subjectToCheck, isGW := getGWRoutedSubjectOrSelf(wireSubject)
55,062✔
3332

55,062✔
3333
        // Service-import replies (_R_), JS ack subjects ($JS.ACK.)
55,062✔
3334
        // are internal routing subjects forwarded via LS+ without
55,062✔
3335
        // permission checks.
55,062✔
3336
        if isServiceReply(subjectToCheck) || isJSAckSubject(subjectToCheck) {
55,091✔
3337
                return true
29✔
3338
        }
29✔
3339

3340
        c.mu.RLock()
55,033✔
3341
        if c.isSpokeLeafNode() {
83,755✔
3342
                // Gateway routed replies are forwarded without
28,722✔
3343
                // permission checks.
28,722✔
3344
                if isGW || c.leafReceiveAllowed(subjectToCheck) {
57,444✔
3345
                        c.mu.RUnlock()
28,722✔
3346
                        return true
28,722✔
3347
                }
28,722✔
3348
        } else if c.leafSendAllowed(subjectToCheck) {
52,622✔
3349
                c.mu.RUnlock()
26,311✔
3350
                return true
26,311✔
3351
        }
26,311✔
3352

3353
        // If allow_responses is not configured, or there is no tracked reply for
3354
        // this subject, the answer is "denied" and we can return it while still
3355
        // holding only the read lock.
3356
        replySubject := bytesToString(wireSubject)
×
3357
        if c.perms == nil || c.perms.resp == nil || c.replies[replySubject] == nil {
×
3358
                c.mu.RUnlock()
×
3359
                return false
×
3360
        }
×
3361
        c.mu.RUnlock()
×
3362

×
3363
        // Check tracked reply permissions (allow_responses).
×
3364
        // Use the pre-strip subject since deliverMsg tracks
×
3365
        // replies under the original form, which includes
×
3366
        // the GW routing prefix for routed requests.
×
3367
        c.mu.Lock()
×
3368
        defer c.mu.Unlock()
×
3369
        return c.responseAllowed(replySubject)
×
3370
}
3371

3372
// Returns true if the leaf side ACLs allow importing this subject,
3373
// based on the permissions received over INFO and any local deny_imports.
3374
// At least a read lock must be held.
3375
func (c *client) leafReceiveAllowed(subject []byte) bool {
28,722✔
3376
        return c.canSubscribeInternal(bytesToString(subject))
28,722✔
3377
}
28,722✔
3378

3379
// Returns true if the hub side ACLs allow the remote leaf to send
3380
// this subject.
3381
// At least a read lock must be held.
3382
func (c *client) leafSendAllowed(bsubject []byte) bool {
26,311✔
3383
        // Use the original export ACL captured for this accepted leaf.
26,311✔
3384
        // The live perms also contain additional JetStream denies used by
26,311✔
3385
        // the normal forwarding path, and applying them here would reject
26,311✔
3386
        // legitimate inbound JS API requests.
26,311✔
3387
        subject := bytesToString(bsubject)
26,311✔
3388
        perms := c.opts.Export
26,311✔
3389
        if perms == nil || (perms.Allow == nil && perms.Deny == nil) {
52,619✔
3390
                return true
26,308✔
3391
        }
26,308✔
3392

3393
        allowed := true
3✔
3394
        if perms.Allow != nil && !strings.HasPrefix(subject, mqttPrefix) {
5✔
3395
                allowed = false
2✔
3396
                for _, allowSubj := range perms.Allow {
5✔
3397
                        if matchLiteral(subject, allowSubj) {
5✔
3398
                                allowed = true
2✔
3399
                                break
2✔
3400
                        }
3401
                }
3402
        }
3403

3404
        if allowed && len(perms.Deny) > 0 {
4✔
3405
                for _, denySubj := range perms.Deny {
2✔
3406
                        if matchLiteral(subject, denySubj) {
1✔
3407
                                allowed = false
×
3408
                                break
×
3409
                        }
3410
                }
3411
        }
3412
        return allowed
3✔
3413
}
3414

3415
// Handles a subscription permission violation.
3416
// See leafPermViolation() for details.
3417
func (c *client) leafSubPermViolation(subj []byte) {
13✔
3418
        c.leafPermViolation(false, subj)
13✔
3419
}
13✔
3420

3421
// Handles a publish permission violation.
3422
// See leafPermViolation() for details.
3423
func (c *client) leafPubPermViolation(subj []byte) {
×
3424
        c.leafPermViolation(true, subj)
×
3425
}
×
3426

3427
// Common function to process publish or subscribe leafnode permission violation.
3428
// Sends the permission violation error to the remote, logs it and closes the connection.
3429
// If this is from a server soliciting, the reconnection will be delayed.
3430
func (c *client) leafPermViolation(pub bool, subj []byte) {
13✔
3431
        if c.isSpokeLeafNode() {
26✔
3432
                // For spokes these are no-ops since the hub server told us our permissions.
13✔
3433
                // We just need to not send these over to the other side since we will get cutoff.
13✔
3434
                return
13✔
3435
        }
13✔
3436
        // FIXME(dlc) ?
3437
        c.setLeafConnectDelayIfSoliciting(leafNodeReconnectAfterPermViolation)
×
3438
        var action string
×
3439
        if pub {
×
3440
                c.sendErr(fmt.Sprintf("Permissions Violation for Publish to %q", subj))
×
3441
                action = "Publish"
×
3442
        } else {
×
3443
                c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q", subj))
×
3444
                action = "Subscription"
×
3445
        }
×
3446
        c.Errorf("%s Violation on %q - Check other side configuration", action, subj)
×
3447
        // TODO: add a new close reason that is more appropriate?
×
3448
        c.closeConnection(ProtocolViolation)
×
3449
}
3450

3451
// Invoked from generic processErr() for LEAF connections.
3452
func (c *client) leafProcessErr(errStr string) {
46✔
3453
        // Check if we got a cluster name collision.
46✔
3454
        if strings.Contains(errStr, ErrLeafNodeHasSameClusterName.Error()) {
49✔
3455
                _, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterClusterNameSame)
3✔
3456
                c.Errorf("Leafnode connection dropped with same cluster name error. Delaying attempt to reconnect for %v", delay)
3✔
3457
                return
3✔
3458
        }
3✔
3459
        if strings.Contains(errStr, ErrLeafNodeMinVersionRejected.Error()) {
44✔
3460
                _, delay := c.setLeafConnectDelayIfSoliciting(leafNodeMinVersionReconnectDelay)
1✔
3461
                c.Errorf("Leafnode connection dropped due to minimum version requirement. Delaying attempt to reconnect for %v", delay)
1✔
3462
                return
1✔
3463
        }
1✔
3464

3465
        // We will look for Loop detected error coming from the other side.
3466
        // If we solicit, set the connect delay.
3467
        if !strings.Contains(errStr, "Loop detected") {
79✔
3468
                return
37✔
3469
        }
37✔
3470
        c.handleLeafNodeLoop(false)
5✔
3471
}
3472

3473
// If this leaf connection solicits, sets the connect delay to the given value,
3474
// or the one from the server option's LeafNode.connDelay if one is set (for tests).
3475
// Returns the connection's account name and delay.
3476
func (c *client) setLeafConnectDelayIfSoliciting(delay time.Duration) (string, time.Duration) {
16✔
3477
        c.mu.Lock()
16✔
3478
        if c.isSolicitedLeafNode() {
26✔
3479
                if s := c.srv; s != nil {
20✔
3480
                        if srvdelay := s.getOpts().LeafNode.connDelay; srvdelay != 0 {
14✔
3481
                                delay = srvdelay
4✔
3482
                        }
4✔
3483
                }
3484
                c.leaf.remote.setConnectDelay(delay)
10✔
3485
        }
3486
        var accName string
16✔
3487
        if c.acc != nil {
32✔
3488
                accName = c.acc.Name
16✔
3489
        }
16✔
3490
        c.mu.Unlock()
16✔
3491
        return accName, delay
16✔
3492
}
3493

3494
// For the given remote Leafnode configuration, this function returns
3495
// if TLS is required, and if so, will return a clone of the TLS Config
3496
// (since some fields will be changed during handshake), the TLS server
3497
// name that is remembered, and the TLS timeout.
3498
func (c *client) leafNodeGetTLSConfigForSolicit(remote *leafNodeCfg) (bool, *tls.Config, string, float64) {
1,409✔
3499
        var (
1,409✔
3500
                tlsConfig  *tls.Config
1,409✔
3501
                tlsName    string
1,409✔
3502
                tlsTimeout float64
1,409✔
3503
        )
1,409✔
3504

1,409✔
3505
        remote.RLock()
1,409✔
3506
        defer remote.RUnlock()
1,409✔
3507

1,409✔
3508
        tlsRequired := remote.TLS || remote.TLSConfig != nil
1,409✔
3509
        if tlsRequired {
1,478✔
3510
                if remote.TLSConfig != nil {
114✔
3511
                        tlsConfig = remote.TLSConfig.Clone()
45✔
3512
                } else {
69✔
3513
                        tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}
24✔
3514
                }
24✔
3515
                tlsName = remote.tlsName
69✔
3516
                tlsTimeout = remote.TLSTimeout
69✔
3517
                if tlsTimeout == 0 {
110✔
3518
                        tlsTimeout = float64(TLS_TIMEOUT / time.Second)
41✔
3519
                }
41✔
3520
        }
3521

3522
        return tlsRequired, tlsConfig, tlsName, tlsTimeout
1,409✔
3523
}
3524

3525
// Initiates the LeafNode Websocket connection by:
3526
// - doing the TLS handshake if needed
3527
// - sending the HTTP request
3528
// - waiting for the HTTP response
3529
//
3530
// Since some bufio reader is used to consume the HTTP response, this function
3531
// returns the slice of buffered bytes (if any) so that the readLoop that will
3532
// be started after that consume those first before reading from the socket.
3533
// The boolean
3534
//
3535
// Lock held on entry.
3536
func (c *client) leafNodeSolicitWSConnection(opts *Options, rURL *url.URL, remote *leafNodeCfg) ([]byte, ClosedState, error) {
46✔
3537
        remote.RLock()
46✔
3538
        compress := remote.Websocket.Compression
46✔
3539
        // By default the server will mask outbound frames, but it can be disabled with this option.
46✔
3540
        noMasking := remote.Websocket.NoMasking
46✔
3541
        infoTimeout := remote.FirstInfoTimeout
46✔
3542
        remote.RUnlock()
46✔
3543
        // Will do the client-side TLS handshake if needed.
46✔
3544
        tlsRequired, err := c.leafClientHandshakeIfNeeded(remote, opts)
46✔
3545
        if err != nil {
50✔
3546
                // 0 will indicate that the connection was already closed
4✔
3547
                return nil, 0, err
4✔
3548
        }
4✔
3549

3550
        // For http request, we need the passed URL to contain either http or https scheme.
3551
        scheme := "http"
42✔
3552
        if tlsRequired {
50✔
3553
                scheme = "https"
8✔
3554
        }
8✔
3555
        // We will use the `/leafnode` path to tell the accepting WS server that it should
3556
        // create a LEAF connection, not a CLIENT.
3557
        // In case we use the user's URL path in the future, make sure we append the user's
3558
        // path to our `/leafnode` path.
3559
        lpath := leafNodeWSPath
42✔
3560
        if curPath := rURL.EscapedPath(); curPath != _EMPTY_ {
63✔
3561
                if curPath[0] == '/' {
42✔
3562
                        curPath = curPath[1:]
21✔
3563
                }
21✔
3564
                lpath = path.Join(curPath, lpath)
21✔
3565
        } else {
21✔
3566
                lpath = lpath[1:]
21✔
3567
        }
21✔
3568
        ustr := fmt.Sprintf("%s://%s/%s", scheme, rURL.Host, lpath)
42✔
3569
        u, _ := url.Parse(ustr)
42✔
3570
        req := &http.Request{
42✔
3571
                Method:     "GET",
42✔
3572
                URL:        u,
42✔
3573
                Proto:      "HTTP/1.1",
42✔
3574
                ProtoMajor: 1,
42✔
3575
                ProtoMinor: 1,
42✔
3576
                Header:     make(http.Header),
42✔
3577
                Host:       u.Host,
42✔
3578
        }
42✔
3579
        wsKey, err := wsMakeChallengeKey()
42✔
3580
        if err != nil {
42✔
3581
                return nil, WriteError, err
×
3582
        }
×
3583

3584
        req.Header["Upgrade"] = []string{"websocket"}
42✔
3585
        req.Header["Connection"] = []string{"Upgrade"}
42✔
3586
        req.Header["Sec-WebSocket-Key"] = []string{wsKey}
42✔
3587
        req.Header["Sec-WebSocket-Version"] = []string{"13"}
42✔
3588
        if compress {
50✔
3589
                req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue)
8✔
3590
        }
8✔
3591
        if noMasking {
51✔
3592
                req.Header.Add(wsNoMaskingHeader, wsNoMaskingValue)
9✔
3593
        }
9✔
3594
        c.nc.SetDeadline(time.Now().Add(infoTimeout))
42✔
3595
        if err := req.Write(c.nc); err != nil {
42✔
3596
                return nil, WriteError, err
×
3597
        }
×
3598

3599
        var resp *http.Response
42✔
3600

42✔
3601
        br := bufio.NewReaderSize(c.nc, MAX_CONTROL_LINE_SIZE)
42✔
3602
        resp, err = http.ReadResponse(br, req)
42✔
3603
        if err == nil &&
42✔
3604
                (resp.StatusCode != 101 ||
42✔
3605
                        !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
42✔
3606
                        !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
42✔
3607
                        resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) {
43✔
3608

1✔
3609
                err = fmt.Errorf("invalid websocket connection")
1✔
3610
        }
1✔
3611
        // Check compression extension...
3612
        if err == nil && c.ws.compress {
50✔
3613
                // Check that not only permessage-deflate extension is present, but that
8✔
3614
                // we also have server and client no context take over.
8✔
3615
                srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header, false)
8✔
3616

8✔
3617
                // If server does not support compression, then simply disable it in our side.
8✔
3618
                if !srvCompress {
12✔
3619
                        c.ws.compress = false
4✔
3620
                } else if !noCtxTakeover {
8✔
3621
                        err = fmt.Errorf("compression negotiation error")
×
3622
                }
×
3623
        }
3624
        // Same for no masking...
3625
        if err == nil && noMasking {
51✔
3626
                // Check if server accepts no masking
9✔
3627
                if resp.Header.Get(wsNoMaskingHeader) != wsNoMaskingValue {
10✔
3628
                        // Nope, need to mask our writes as any client would do.
1✔
3629
                        c.ws.maskwrite = true
1✔
3630
                }
1✔
3631
        }
3632
        if resp != nil {
69✔
3633
                resp.Body.Close()
27✔
3634
        }
27✔
3635
        if err != nil {
58✔
3636
                return nil, ReadError, err
16✔
3637
        }
16✔
3638
        c.Debugf("Leafnode compression=%v masking=%v", c.ws.compress, c.ws.maskwrite)
26✔
3639

26✔
3640
        var preBuf []byte
26✔
3641
        // We have to slurp whatever is in the bufio reader and pass that to the readloop.
26✔
3642
        if n := br.Buffered(); n != 0 {
26✔
3643
                preBuf, _ = br.Peek(n)
×
3644
        }
×
3645
        return preBuf, 0, nil
26✔
3646
}
3647

3648
const connectProcessTimeout = 2 * time.Second
3649

3650
// This is invoked for remote LEAF remote connections after processing the INFO
3651
// protocol.
3652
func (s *Server) leafNodeResumeConnectProcess(c *client) {
498✔
3653
        clusterName := s.ClusterName()
498✔
3654

498✔
3655
        c.mu.Lock()
498✔
3656
        if c.isClosed() {
498✔
3657
                c.mu.Unlock()
×
3658
                return
×
3659
        }
×
3660
        if err := c.sendLeafConnect(clusterName, c.headers); err != nil {
500✔
3661
                c.mu.Unlock()
2✔
3662
                c.closeConnection(WriteError)
2✔
3663
                return
2✔
3664
        }
2✔
3665

3666
        // Spin up the write loop.
3667
        s.startGoRoutine(func() { c.writeLoop() })
992✔
3668

3669
        // timeout leafNodeFinishConnectProcess
3670
        c.ping.tmr = time.AfterFunc(connectProcessTimeout, func() {
496✔
3671
                c.mu.Lock()
×
3672
                // check if leafNodeFinishConnectProcess was called and prevent later leafNodeFinishConnectProcess
×
3673
                if !c.flags.setIfNotSet(connectProcessFinished) {
×
3674
                        c.mu.Unlock()
×
3675
                        return
×
3676
                }
×
3677
                clearTimer(&c.ping.tmr)
×
3678
                closed := c.isClosed()
×
3679
                c.mu.Unlock()
×
3680
                if !closed {
×
3681
                        c.sendErrAndDebug("Stale Leaf Node Connection - Closing")
×
3682
                        c.closeConnection(StaleConnection)
×
3683
                }
×
3684
        })
3685
        c.mu.Unlock()
496✔
3686
        c.Debugf("Remote leafnode connect msg sent")
496✔
3687
}
3688

3689
// This is invoked for remote LEAF connections after processing the INFO
3690
// protocol and leafNodeResumeConnectProcess.
3691
// This will send LS+ the CONNECT protocol and register the leaf node.
3692
func (s *Server) leafNodeFinishConnectProcess(c *client) {
461✔
3693
        c.mu.Lock()
461✔
3694
        if !c.flags.setIfNotSet(connectProcessFinished) {
461✔
3695
                c.mu.Unlock()
×
3696
                return
×
3697
        }
×
3698
        if c.isClosed() {
461✔
3699
                c.mu.Unlock()
×
3700
                s.removeLeafNodeConnection(c)
×
3701
                return
×
3702
        }
×
3703
        remote := c.leaf.remote
461✔
3704
        if remote == nil || c.acc == nil {
461✔
3705
                c.mu.Unlock()
×
3706
                c.sendErr("Authorization Violation")
×
3707
                c.closeConnection(ProtocolViolation)
×
3708
                return
×
3709
        }
×
3710
        // Check if we will need to send the system connect event.
3711
        remote.RLock()
461✔
3712
        sendSysConnectEvent := remote.Hub
461✔
3713
        remote.RUnlock()
461✔
3714

461✔
3715
        // Capture account before releasing lock
461✔
3716
        acc := c.acc
461✔
3717
        // cancel connectProcessTimeout
461✔
3718
        clearTimer(&c.ping.tmr)
461✔
3719
        c.mu.Unlock()
461✔
3720

461✔
3721
        // Make sure we register with the account here.
461✔
3722
        if err := c.registerWithAccount(acc); err != nil {
463✔
3723
                if err == ErrTooManyAccountConnections {
2✔
3724
                        c.maxAccountConnExceeded()
×
3725
                        return
×
3726
                } else if err == ErrLeafNodeLoop {
4✔
3727
                        c.handleLeafNodeLoop(true)
2✔
3728
                        return
2✔
3729
                }
2✔
3730
                c.Errorf("Registering leaf with account %s resulted in error: %v", acc.Name, err)
×
3731
                c.closeConnection(ProtocolViolation)
×
3732
                return
×
3733
        }
3734
        if !s.addLeafNodeConnection(c, _EMPTY_, _EMPTY_, false) {
459✔
3735
                // Was not added, could be because the remote configuration has been removed.
×
3736
                c.closeConnection(ClientClosed)
×
3737
                return
×
3738
        }
×
3739
        s.initLeafNodeSmapAndSendSubs(c)
459✔
3740
        if sendSysConnectEvent {
471✔
3741
                s.sendLeafNodeConnect(acc)
12✔
3742
        }
12✔
3743
        s.accountConnectEvent(c)
459✔
3744

459✔
3745
        // The above functions are not running under the client lock, so it is
459✔
3746
        // possible that between the time we have started the read/write loops
459✔
3747
        // and now, that the connection was closed. This would leave the closed
459✔
3748
        // LN connection possibly registered with the account and/or the server's
459✔
3749
        // leafs map. So check if connection is closed, and if so, manually cleanup.
459✔
3750
        c.mu.Lock()
459✔
3751
        closed := c.isClosed()
459✔
3752
        if !closed {
918✔
3753
                c.setFirstPingTimer()
459✔
3754
        }
459✔
3755
        c.mu.Unlock()
459✔
3756
        if closed {
459✔
3757
                s.removeLeafNodeConnection(c)
×
3758
                if prev := acc.removeClient(c); prev == 1 {
×
3759
                        s.decActiveAccounts()
×
3760
                }
×
3761
        }
3762
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc