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

nats-io / nats-server / 27084533270

05 Jun 2026 10:31AM UTC coverage: 77.67% (-3.1%) from 80.787%
27084533270

push

github

web-flow
Apply writer options consistently to s2_fast compression mode (#8047)

Fixes #7037.

## Summary
- include `s2.WriterConcurrency(1)` option for `CompressionS2Fast`
- add regression test `TestS2WriterOptionsForFastCompression`

A maintainer comment on the issue indicated omitting this in fast mode
was an oversight.

## Verification
- `go test ./server -run
''TestS2WriterOptionsForFastCompression|TestRouteCompressionOptions''
-count=1`

72722 of 93630 relevant lines covered (77.67%)

648196.29 hits per line

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

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

14
package server
15

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

227
        // In local config mode, check that leafnode configuration refers to accounts that exist.
228
        if len(o.TrustedOperators) == 0 {
15,272✔
229
                accNames := map[string]struct{}{}
7,495✔
230
                for _, a := range o.Accounts {
16,063✔
231
                        accNames[a.Name] = struct{}{}
8,568✔
232
                }
8,568✔
233
                // global account is always created
234
                accNames[DEFAULT_GLOBAL_ACCOUNT] = struct{}{}
7,495✔
235
                // in the context of leaf nodes, empty account means global account
7,495✔
236
                accNames[_EMPTY_] = struct{}{}
7,495✔
237
                // system account either exists or, if not disabled, will be created
7,495✔
238
                if o.SystemAccount == _EMPTY_ && !o.NoSystemAccount {
13,568✔
239
                        accNames[DEFAULT_SYSTEM_ACCOUNT] = struct{}{}
6,073✔
240
                }
6,073✔
241
                checkAccountExists := func(accName string, cfgType string) error {
15,702✔
242
                        if _, ok := accNames[accName]; !ok {
8,209✔
243
                                return fmt.Errorf("cannot find local account %q specified in leafnode %s", accName, cfgType)
2✔
244
                        }
2✔
245
                        return nil
8,205✔
246
                }
247
                if err := checkAccountExists(o.LeafNode.Account, "authorization"); err != nil {
7,496✔
248
                        return err
1✔
249
                }
1✔
250
                for _, lu := range o.LeafNode.Users {
7,511✔
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,199✔
259
                        if err := checkAccountExists(r.LocalAccount, "remote"); err != nil {
706✔
260
                                return err
1✔
261
                        }
1✔
262
                }
263
        } else {
282✔
264
                if len(o.LeafNode.Users) != 0 {
283✔
265
                        return fmt.Errorf("operator mode does not allow specifying users in leafnode config")
1✔
266
                }
1✔
267
                for _, r := range o.LeafNode.Remotes {
282✔
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) {
281✔
276
                        return fmt.Errorf("operator mode and non account nkeys are incompatible")
1✔
277
                }
1✔
278
        }
279

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

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

294
                if len(rcfg.URLs) >= 2 {
870✔
295
                        firstIsWS, ok := isWSURL(rcfg.URLs[0]), true
172✔
296
                        for i := 1; i < len(rcfg.URLs); i++ {
527✔
297
                                u := rcfg.URLs[i]
355✔
298
                                if isWS := isWSURL(u); isWS && !firstIsWS || !isWS && firstIsWS {
362✔
299
                                        ok = false
7✔
300
                                        break
7✔
301
                                }
302
                        }
303
                        if !ok {
179✔
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() {
691✔
308
                        for _, u := range rcfg.URLs {
×
309
                                if isWSURL(u) {
×
310
                                        return fmt.Errorf("remote leaf node URL %q cannot be used in FIPS-140 mode when built with this Go version, use Go 1.26 or later", redactURLString(u.String()))
×
311
                                }
×
312
                        }
313
                }
314
                // Validate compression settings
315
                if rcfg.Compression.Mode != _EMPTY_ {
1,376✔
316
                        if err := validateAndNormalizeCompressionOption(&rcfg.Compression, CompressionS2Auto); err != nil {
690✔
317
                                return err
5✔
318
                        }
5✔
319
                }
320
        }
321

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

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

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

337
        if o.Gateway.Name == _EMPTY_ && o.Gateway.Port == 0 {
7,347✔
338
                return nil
3,346✔
339
        }
3,346✔
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_ {
656✔
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 {
654✔
346
                return fmt.Errorf("leafnode: %v", err)
×
347
        }
×
348
        return nil
654✔
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,832✔
366
        if len(o.LeafNode.Users) == 0 {
15,638✔
367
                return nil
7,806✔
368
        }
7,806✔
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,254✔
386
        var warnings []string
1,254✔
387

1,254✔
388
        if remote.Proxy.URL == _EMPTY_ {
2,482✔
389
                return warnings, nil
1,228✔
390
        }
1,228✔
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) {
251✔
442
        clearInProgress := true
251✔
443
        defer func() {
501✔
444
                s.grWG.Done()
250✔
445
                if clearInProgress {
320✔
446
                        remote.setConnectInProgress(false)
70✔
447
                }
70✔
448
        }()
449
        delay := s.getOpts().LeafNode.ReconnectInterval
251✔
450
        select {
251✔
451
        case <-time.After(delay):
189✔
452
        case <-remote.quitCh:
×
453
                return
×
454
        case <-s.quitCh:
62✔
455
                return
62✔
456
        }
457
        clearInProgress = !connectToRemoteLeafNode(s, remote, false)
189✔
458
}
459

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

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

510
// Sets the connect-in-progress status for this remote leaf configuration.
511
func (cfg *leafNodeCfg) setConnectInProgress(inProgress bool) {
2,195✔
512
        cfg.Lock()
2,195✔
513
        defer cfg.Unlock()
2,195✔
514
        // In both cases we want to drain the "quit" channel.
2,195✔
515
        select {
2,195✔
516
        case <-cfg.quitCh:
1✔
517
        default:
2,194✔
518
        }
519
        cfg.connInProgress = inProgress
2,195✔
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 {
4,539✔
543
        cfg.RLock()
4,539✔
544
        defer cfg.RUnlock()
4,539✔
545
        return !cfg.Disabled && !cfg.removed
4,539✔
546
}
4,539✔
547

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

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

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

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

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

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

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

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

715
        var conn net.Conn
855✔
716

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

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

855✔
727
        // Set default proxy timeout if not specified
855✔
728
        if proxyTimeout == 0 {
1,702✔
729
                proxyTimeout = dialTimeout
847✔
730
        }
847✔
731

732
        attempts := 0
855✔
733

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

741
        reconnectTimer := time.NewTimer(reconnectDelay)
855✔
742
        reconnectTimer.Stop()
855✔
743
        defer stopAndClearTimer(&reconnectTimer)
855✔
744

855✔
745
        for s.isRunning() && remote.stillValid() {
4,021✔
746
                rURL := remote.pickNextURL()
3,166✔
747
                url, err := s.getRandomIP(resolver, rURL.Host, nil)
3,166✔
748
                if err == nil {
6,327✔
749
                        var ipStr string
3,161✔
750
                        if url != rURL.Host {
3,225✔
751
                                ipStr = fmt.Sprintf(" (%s)", url)
64✔
752
                        }
64✔
753
                        // Some test may want to disable remotes from connecting
754
                        if s.isLeafConnectDisabled() {
3,293✔
755
                                s.Debugf("Will not attempt to connect to remote server on %q%s, leafnodes currently disabled", rURL.Host, ipStr)
132✔
756
                                err = ErrLeafNodeDisabled
132✔
757
                        } else {
3,161✔
758
                                s.Debugf("Trying to connect as leafnode to remote server on %q%s", rURL.Host, ipStr)
3,029✔
759

3,029✔
760
                                // Check if proxy is configured
3,029✔
761
                                if proxyURL != _EMPTY_ {
3,037✔
762
                                        targetHost := rURL.Host
8✔
763
                                        // If URL doesn't include port, add the default port for the scheme
8✔
764
                                        if rURL.Port() == _EMPTY_ {
8✔
765
                                                defaultPort := "80"
×
766
                                                if rURL.Scheme == wsSchemePrefixTLS {
×
767
                                                        defaultPort = "443"
×
768
                                                }
×
769
                                                targetHost = net.JoinHostPort(rURL.Hostname(), defaultPort)
×
770
                                        }
771

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

819
                // We have a connection here to a remote server.
820
                // Go ahead and create our leaf node and return.
821
                s.createLeafNode(conn, rURL, remote, nil)
770✔
822

770✔
823
                // Clear any observer states if we had them.
770✔
824
                s.clearObserverState(remote)
770✔
825

770✔
826
                return true
770✔
827
        }
828

829
        return false
5✔
830
}
831

832
func (cfg *leafNodeCfg) cancelMigrateTimer() {
778✔
833
        cfg.Lock()
778✔
834
        stopAndClearTimer(&cfg.jsMigrateTimer)
778✔
835
        cfg.Unlock()
778✔
836
}
778✔
837

838
// This will clear any observer state such that stream or consumer assets on this server can become leaders again.
839
func (s *Server) clearObserverState(remote *leafNodeCfg) {
770✔
840
        s.mu.RLock()
770✔
841
        accName := remote.LocalAccount
770✔
842
        s.mu.RUnlock()
770✔
843

770✔
844
        acc, err := s.LookupAccount(accName)
770✔
845
        if err != nil {
772✔
846
                s.Warnf("Error looking up account [%s] checking for JetStream clear observer state on a leafnode", accName)
2✔
847
                return
2✔
848
        }
2✔
849

850
        acc.jscmMu.Lock()
768✔
851
        defer acc.jscmMu.Unlock()
768✔
852

768✔
853
        // Walk all streams looking for any clustered stream, skip otherwise.
768✔
854
        for _, mset := range acc.streams() {
787✔
855
                node := mset.raftNode()
19✔
856
                if node == nil {
30✔
857
                        // Not R>1
11✔
858
                        continue
11✔
859
                }
860
                // Check consumers
861
                for _, o := range mset.getConsumers() {
10✔
862
                        if n := o.raftNode(); n != nil {
4✔
863
                                // Ensure we can become a leader again.
2✔
864
                                n.SetObserver(false)
2✔
865
                        }
2✔
866
                }
867
                // Ensure we can not become a leader again.
868
                node.SetObserver(false)
8✔
869
        }
870
}
871

872
// Check to see if we should migrate any assets from this account.
873
func (s *Server) checkJetStreamMigrate(remote *leafNodeCfg) {
2,248✔
874
        s.mu.RLock()
2,248✔
875
        accName, shouldMigrate := remote.LocalAccount, remote.JetStreamClusterMigrate
2,248✔
876
        s.mu.RUnlock()
2,248✔
877

2,248✔
878
        if !shouldMigrate {
4,432✔
879
                return
2,184✔
880
        }
2,184✔
881

882
        acc, err := s.LookupAccount(accName)
64✔
883
        if err != nil {
64✔
884
                s.Warnf("Error looking up account [%s] checking for JetStream migration on a leafnode", accName)
×
885
                return
×
886
        }
×
887

888
        acc.jscmMu.Lock()
64✔
889
        defer acc.jscmMu.Unlock()
64✔
890

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

914
// Helper for checking.
915
func (s *Server) isLeafConnectDisabled() bool {
3,161✔
916
        s.mu.RLock()
3,161✔
917
        defer s.mu.RUnlock()
3,161✔
918
        return s.leafDisableConnect
3,161✔
919
}
3,161✔
920

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

937
// Save off the username/password for when we connect using a bare URL
938
// that we get from the INFO protocol.
939
//
940
// Lock held on entry.
941
func (cfg *leafNodeCfg) saveUserPassword(u *url.URL) {
1,017✔
942
        if cfg.username == _EMPTY_ && u.User != nil {
1,307✔
943
                cfg.username = u.User.Username()
290✔
944
                cfg.password, _ = u.User.Password()
290✔
945
        }
290✔
946
}
947

948
// This starts the leafnode accept loop in a go routine, unless it
949
// is detected that the server has already been shutdown.
950
func (s *Server) startLeafNodeAcceptLoop() {
3,981✔
951
        // Snapshot server options.
3,981✔
952
        opts := s.getOpts()
3,981✔
953

3,981✔
954
        port := opts.LeafNode.Port
3,981✔
955
        if port == -1 {
7,807✔
956
                port = 0
3,826✔
957
        }
3,826✔
958

959
        if s.isShuttingDown() {
3,981✔
960
                return
×
961
        }
×
962

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

973
        s.Noticef("Listening for leafnode connections on %s",
3,981✔
974
                net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
3,981✔
975

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

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

3,981✔
1014
        // Setup state that can enable shutdown
3,981✔
1015
        s.leafNodeListener = l
3,981✔
1016

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

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

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

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

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

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

1156
// Makes a deep copy of the LeafNode Info structure.
1157
// The server lock is held on entry.
1158
func (s *Server) copyLeafNodeInfo() *Info {
2,570✔
1159
        clone := s.leafNodeInfo
2,570✔
1160
        // Copy the array of urls.
2,570✔
1161
        if len(s.leafNodeInfo.LeafNodeURLs) > 0 {
4,690✔
1162
                clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...)
2,120✔
1163
        }
2,120✔
1164
        return &clone
2,570✔
1165
}
1166

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

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

1196
// Server lock is held on entry
1197
func (s *Server) generateLeafNodeInfoJSON() {
15,644✔
1198
        s.leafNodeInfo.Cluster = s.cachedClusterName()
15,644✔
1199
        s.leafNodeInfo.LeafNodeURLs = s.leafURLsMap.getAsStringSlice()
15,644✔
1200
        s.leafNodeInfo.WSConnectURLs = s.websocket.connectURLsMap.getAsStringSlice()
15,644✔
1201
        s.leafNodeInfoJSON = generateInfoJSON(&s.leafNodeInfo)
15,644✔
1202
}
15,644✔
1203

1204
// Sends an async INFO protocol so that the connected servers can update
1205
// their list of LeafNode urls.
1206
func (s *Server) sendAsyncLeafNodeInfo() {
11,663✔
1207
        for _, c := range s.leafs {
11,756✔
1208
                c.mu.Lock()
93✔
1209
                c.enqueueProto(s.leafNodeInfoJSON)
93✔
1210
                c.mu.Unlock()
93✔
1211
        }
93✔
1212
}
1213

1214
// Called when an inbound leafnode connection is accepted or we create one for a solicited leafnode.
1215
func (s *Server) createLeafNode(conn net.Conn, rURL *url.URL, remote *leafNodeCfg, ws *websocket) *client {
1,621✔
1216
        // Snapshot server options.
1,621✔
1217
        opts := s.getOpts()
1,621✔
1218

1,621✔
1219
        maxPay := int32(opts.MaxPayload)
1,621✔
1220
        maxSubs := int32(opts.MaxSubs)
1,621✔
1221
        // For system, maxSubs of 0 means unlimited, so re-adjust here.
1,621✔
1222
        if maxSubs == 0 {
3,241✔
1223
                maxSubs = -1
1,620✔
1224
        }
1,620✔
1225
        now := time.Now().UTC()
1,621✔
1226

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

1,621✔
1231
        // If the leafnode subject interest should be isolated, flag it here.
1,621✔
1232
        s.optsMu.RLock()
1,621✔
1233
        if c.leaf.isolated = s.opts.LeafNode.IsolateLeafnodeInterest; !c.leaf.isolated && remote != nil {
2,391✔
1234
                c.leaf.isolated = remote.LocalIsolation
770✔
1235
        }
770✔
1236
        s.optsMu.RUnlock()
1,621✔
1237

1,621✔
1238
        // For accepted LN connections, ws will be != nil if it was accepted
1,621✔
1239
        // through the Websocket port.
1,621✔
1240
        c.ws = ws
1,621✔
1241

1,621✔
1242
        // For remote, check if the scheme starts with "ws", if so, we will initiate
1,621✔
1243
        // a remote Leaf Node connection as a websocket connection.
1,621✔
1244
        if remote != nil && rURL != nil && isWSURL(rURL) {
1,675✔
1245
                remote.RLock()
54✔
1246
                c.ws = &websocket{compress: remote.Websocket.Compression, maskwrite: !remote.Websocket.NoMasking}
54✔
1247
                remote.RUnlock()
54✔
1248
        }
54✔
1249

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

1272
        c.mu.Lock()
1,619✔
1273
        c.initClient()
1,619✔
1274
        c.Noticef("Leafnode connection created%s %s", remoteSuffix, c.opts.Name)
1,619✔
1275

1,619✔
1276
        var (
1,619✔
1277
                tlsFirst         bool
1,619✔
1278
                tlsFirstFallback time.Duration
1,619✔
1279
                infoTimeout      time.Duration
1,619✔
1280
        )
1,619✔
1281
        if remote != nil {
2,387✔
1282
                solicited = true
768✔
1283
                remote.Lock()
768✔
1284
                c.leaf.remote = remote
768✔
1285
                c.setPermissions(remote.perms)
768✔
1286
                if !c.leaf.remote.Hub {
1,518✔
1287
                        c.leaf.isSpoke = true
750✔
1288
                }
750✔
1289
                tlsFirst = remote.TLSHandshakeFirst
768✔
1290
                infoTimeout = remote.FirstInfoTimeout
768✔
1291
                remote.Unlock()
768✔
1292
                c.acc = acc
768✔
1293
        } else {
851✔
1294
                c.flags.set(expectConnect)
851✔
1295
                if ws != nil {
886✔
1296
                        c.Debugf("Leafnode compression=%v", c.ws.compress)
35✔
1297
                }
35✔
1298
                tlsFirst = opts.LeafNode.TLSHandshakeFirst
851✔
1299
                if f := opts.LeafNode.TLSHandshakeFirstFallback; f > 0 {
852✔
1300
                        tlsFirstFallback = f
1✔
1301
                }
1✔
1302
        }
1303
        c.mu.Unlock()
1,619✔
1304

1,619✔
1305
        var nonce [nonceLen]byte
1,619✔
1306
        var info *Info
1,619✔
1307

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

1327
        // Grab lock
1328
        c.mu.Lock()
1,619✔
1329

1,619✔
1330
        var preBuf []byte
1,619✔
1331
        if solicited {
2,387✔
1332
                // For websocket connection, we need to send an HTTP request,
768✔
1333
                // and get the response before starting the readLoop to get
768✔
1334
                // the INFO, etc..
768✔
1335
                if c.isWebsocket() {
822✔
1336
                        var err error
54✔
1337
                        var closeReason ClosedState
54✔
1338

54✔
1339
                        preBuf, closeReason, err = c.leafNodeSolicitWSConnection(opts, rURL, remote)
54✔
1340
                        if err != nil {
75✔
1341
                                c.Errorf("Error soliciting websocket connection: %v", err)
21✔
1342
                                c.mu.Unlock()
21✔
1343
                                if closeReason != 0 {
38✔
1344
                                        c.closeConnection(closeReason)
17✔
1345
                                }
17✔
1346
                                return nil
21✔
1347
                        }
1348
                } else {
714✔
1349
                        // If configured to do TLS handshake first
714✔
1350
                        if tlsFirst {
718✔
1351
                                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
5✔
1352
                                        c.mu.Unlock()
1✔
1353
                                        return nil
1✔
1354
                                }
1✔
1355
                        }
1356
                        // We need to wait for the info, but not for too long.
1357
                        c.nc.SetReadDeadline(time.Now().Add(infoTimeout))
713✔
1358
                }
1359

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

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

1396
                if !tlsFirst {
1,697✔
1397
                        // We have to send from this go routine because we may
846✔
1398
                        // have to block for TLS handshake before we start our
846✔
1399
                        // writeLoop go routine. The other side needs to receive
846✔
1400
                        // this before it can initiate the TLS handshake..
846✔
1401
                        c.sendProtoNow(proto)
846✔
1402

846✔
1403
                        // The above call could have marked the connection as closed (due to TCP error).
846✔
1404
                        if c.isClosed() {
846✔
1405
                                c.mu.Unlock()
×
1406
                                c.closeConnection(WriteError)
×
1407
                                return nil
×
1408
                        }
×
1409
                }
1410

1411
                // Check to see if we need to spin up TLS.
1412
                if !c.isWebsocket() && info.TLSRequired {
928✔
1413
                        // If we have a prebuffer create a multi-reader.
77✔
1414
                        if len(pre) > 0 {
77✔
1415
                                c.nc = &tlsMixConn{c.nc, bytes.NewBuffer(pre)}
×
1416
                        }
×
1417
                        // Perform server-side TLS handshake.
1418
                        if err := c.doTLSServerHandshake(tlsHandshakeLeaf, opts.LeafNode.TLSConfig, opts.LeafNode.TLSTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
127✔
1419
                                c.mu.Unlock()
50✔
1420
                                return nil
50✔
1421
                        }
50✔
1422
                }
1423

1424
                // If the user wants the TLS handshake to occur first, now that it is
1425
                // done, send the INFO protocol.
1426
                if tlsFirst {
804✔
1427
                        c.flags.set(didTLSFirst)
3✔
1428
                        c.sendProtoNow(proto)
3✔
1429
                        if c.isClosed() {
3✔
1430
                                c.mu.Unlock()
×
1431
                                c.closeConnection(WriteError)
×
1432
                                return nil
×
1433
                        }
×
1434
                }
1435

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

1454
        // Keep track in case server is shutdown before we can successfully register.
1455
        if !s.addToTempClients(c.cid, c) {
1,548✔
1456
                c.mu.Unlock()
1✔
1457
                c.setNoReconnect()
1✔
1458
                c.closeConnection(ServerShutdown)
1✔
1459
                return nil
1✔
1460
        }
1✔
1461

1462
        // Spin up the read loop.
1463
        s.startGoRoutine(func() { c.readLoop(preBuf) })
3,092✔
1464

1465
        // We will spin the write loop for solicited connections only
1466
        // when processing the INFO and after switching to TLS if needed.
1467
        if !solicited {
2,347✔
1468
                s.startGoRoutine(func() { c.writeLoop() })
1,602✔
1469
        }
1470

1471
        c.mu.Unlock()
1,546✔
1472

1,546✔
1473
        return c
1,546✔
1474
}
1475

1476
// Will perform the client-side TLS handshake if needed. Assumes that this
1477
// is called by the solicit side (remote will be non nil). Returns `true`
1478
// if TLS is required, `false` otherwise.
1479
// Lock held on entry.
1480
func (c *client) leafClientHandshakeIfNeeded(remote *leafNodeCfg, opts *Options) (bool, error) {
1,807✔
1481
        // Check if TLS is required and gather TLS config variables.
1,807✔
1482
        tlsRequired, tlsConfig, tlsName, tlsTimeout := c.leafNodeGetTLSConfigForSolicit(remote)
1,807✔
1483
        if !tlsRequired {
3,535✔
1484
                return false, nil
1,728✔
1485
        }
1,728✔
1486

1487
        // If TLS required, peform handshake.
1488
        // Get the URL that was used to connect to the remote server.
1489
        rURL := remote.getCurrentURL()
79✔
1490

79✔
1491
        // Perform the client-side TLS handshake.
79✔
1492
        if resetTLSName, err := c.doTLSClientHandshake(tlsHandshakeLeaf, rURL, tlsConfig, tlsName, tlsTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
117✔
1493
                // Check if we need to reset the remote's TLS name.
38✔
1494
                if resetTLSName {
38✔
1495
                        remote.Lock()
×
1496
                        remote.tlsName = _EMPTY_
×
1497
                        remote.Unlock()
×
1498
                }
×
1499
                return false, err
38✔
1500
        }
1501
        return true, nil
41✔
1502
}
1503

1504
func (c *client) processLeafnodeInfo(info *Info) {
2,505✔
1505
        c.mu.Lock()
2,505✔
1506
        if c.leaf == nil || c.isClosed() {
2,506✔
1507
                c.mu.Unlock()
1✔
1508
                return
1✔
1509
        }
1✔
1510
        s := c.srv
2,504✔
1511
        opts := s.getOpts()
2,504✔
1512
        remote := c.leaf.remote
2,504✔
1513
        didSolicit := remote != nil
2,504✔
1514
        firstINFO := !c.flags.isSet(infoReceived)
2,504✔
1515

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

1539
        // Check for compression, unless already done.
1540
        if firstINFO && !c.flags.isSet(compressionNegotiated) {
3,709✔
1541
                // A solicited leafnode connection must first receive a leafnode INFO.
1,238✔
1542
                // Classify wrong-port connections before any leaf-specific negotiation.
1,238✔
1543
                if didSolicit && (info.CID == 0 || info.LeafNodeURLs == nil) {
1,292✔
1544
                        c.mu.Unlock()
54✔
1545
                        c.Errorf(ErrConnectedToWrongPort.Error())
54✔
1546
                        c.closeConnection(WrongPort)
54✔
1547
                        return
54✔
1548
                }
54✔
1549

1550
                // Prevent from getting back here.
1551
                c.flags.set(compressionNegotiated)
1,184✔
1552

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

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

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

1663
        // For both initial INFO and async INFO protocols, Possibly
1664
        // update our list of remote leafnode URLs we can connect to,
1665
        // unless we are instructed not to.
1666
        if didSolicit && !remote.IgnoreDiscoveredServers &&
1,342✔
1667
                (len(info.LeafNodeURLs) > 0 || len(info.WSConnectURLs) > 0) {
2,599✔
1668
                // Consider the incoming array as the most up-to-date
1,257✔
1669
                // representation of the remote cluster's list of URLs.
1,257✔
1670
                c.updateLeafNodeURLs(info)
1,257✔
1671
        }
1,257✔
1672

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

1697
        var resumeConnect bool
1,342✔
1698

1,342✔
1699
        // If this is a remote connection and this is the first INFO protocol,
1,342✔
1700
        // then we need to finish the connect process by sending CONNECT, etc..
1,342✔
1701
        if firstINFO && didSolicit {
1,985✔
1702
                // Clear deadline that was set in createLeafNode while waiting for the INFO.
643✔
1703
                c.nc.SetDeadline(time.Time{})
643✔
1704
                resumeConnect = true
643✔
1705
        } else if !firstINFO && didSolicit {
1,959✔
1706
                c.leaf.remoteAccName = info.RemoteAccount
617✔
1707
        }
617✔
1708

1709
        // Check if we have the remote account information and if so make sure it's stored.
1710
        if info.RemoteAccount != _EMPTY_ {
1,948✔
1711
                if c.acc == nil {
607✔
1712
                        c.mu.Unlock()
1✔
1713
                        c.sendErr("Authorization Violation")
1✔
1714
                        c.closeConnection(ProtocolViolation)
1✔
1715
                        return
1✔
1716
                }
1✔
1717
                s.leafRemoteAccounts.Store(c.acc.Name, info.RemoteAccount)
605✔
1718
        }
1719
        c.mu.Unlock()
1,341✔
1720

1,341✔
1721
        finishConnect := info.ConnectInfo
1,341✔
1722
        if resumeConnect && s != nil {
1,984✔
1723
                s.leafNodeResumeConnectProcess(c)
643✔
1724
                if !info.InfoOnConnect {
643✔
1725
                        finishConnect = true
×
1726
                }
×
1727
        }
1728
        if finishConnect {
1,947✔
1729
                s.leafNodeFinishConnectProcess(c)
606✔
1730
        }
606✔
1731

1732
        // Check to see if we need to kick any internal source or mirror consumers.
1733
        // This will be a no-op if JetStream not enabled for this server or if the bound account
1734
        // does not have jetstream.
1735
        s.checkInternalSyncConsumers(c.acc)
1,341✔
1736
}
1737

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

1,163✔
1770
        if !needsCompression(cm) {
1,256✔
1771
                return false, nil
93✔
1772
        }
93✔
1773

1774
        // If we end-up doing compression...
1775

1776
        // Generate an INFO with the chosen compression mode.
1777
        s.mu.Lock()
1,070✔
1778
        info := s.copyLeafNodeInfo()
1,070✔
1779
        info.Compression, info.CID, info.Nonce = compressionModeForInfoProtocol(co, cm), cid, nonce
1,070✔
1780
        infoProto := generateInfoJSON(info)
1,070✔
1781
        s.mu.Unlock()
1,070✔
1782

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

1808
// When getting a leaf node INFO protocol, use the provided
1809
// array of urls to update the list of possible endpoints.
1810
func (c *client) updateLeafNodeURLs(info *Info) {
1,257✔
1811
        cfg := c.leaf.remote
1,257✔
1812
        cfg.Lock()
1,257✔
1813
        defer cfg.Unlock()
1,257✔
1814

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

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

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

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

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

1,251✔
1969
        // If applicable, evict the old one.
1,251✔
1970
        if old != nil {
1,253✔
1971
                old.sendErrAndErr(DuplicateRemoteLeafnodeConnection.String())
2✔
1972
                old.closeConnection(DuplicateRemoteLeafnodeConnection)
2✔
1973
                c.Warnf("Replacing connection from same server")
2✔
1974
        }
2✔
1975

1976
        srvDecorated := func() string {
1,442✔
1977
                if myClustName == _EMPTY_ {
217✔
1978
                        return mySrvName
26✔
1979
                }
26✔
1980
                return fmt.Sprintf("%s/%s", mySrvName, myClustName)
165✔
1981
        }
1982

1983
        opts := s.getOpts()
1,251✔
1984
        sysAcc := s.SystemAccount()
1,251✔
1985
        js := s.getJetStream()
1,251✔
1986
        var meta *raft
1,251✔
1987
        if js != nil {
1,740✔
1988
                if mg := js.getMetaGroup(); mg != nil {
859✔
1989
                        meta = mg.(*raft)
370✔
1990
                }
370✔
1991
        }
1992
        blockMappingOutgoing := false
1,251✔
1993
        // Deny (non domain) JetStream API traffic unless system account is shared
1,251✔
1994
        // and domain names are identical and extending is not disabled
1,251✔
1995

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

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

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

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

2148
        // There was an existing field called:
2149
        // >> Comp bool `json:"compression,omitempty"`
2150
        // that has never been used. With support for compression, we now need
2151
        // a field that is a string. So we use a different json tag:
2152
        Compression string `json:"compress_mode,omitempty"`
2153

2154
        // Just used to detect wrong connection attempts.
2155
        Gateway string `json:"gateway,omitempty"`
2156

2157
        // Tells the accept side which account the remote is binding to.
2158
        RemoteAccount string `json:"remote_account,omitempty"`
2159

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

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

2181
        // Unmarshal as a leaf node connect protocol
2182
        proto := &leafConnectInfo{}
653✔
2183
        if err := json.Unmarshal(arg, proto); err != nil {
653✔
2184
                return err
×
2185
        }
×
2186

2187
        // Reject a cluster that contains spaces.
2188
        if proto.Cluster != _EMPTY_ && strings.Contains(proto.Cluster, " ") {
654✔
2189
                c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
2190
                c.closeConnection(ProtocolViolation)
1✔
2191
                return ErrClusterNameHasSpaces
1✔
2192
        }
1✔
2193

2194
        // Check for cluster name collisions.
2195
        if cn := s.cachedClusterName(); cn != _EMPTY_ && proto.Cluster != _EMPTY_ && proto.Cluster == cn {
655✔
2196
                c.sendErrAndErr(ErrLeafNodeHasSameClusterName.Error())
3✔
2197
                c.closeConnection(ClusterNamesIdentical)
3✔
2198
                return ErrLeafNodeHasSameClusterName
3✔
2199
        }
3✔
2200

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

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

2224
        // Check if this server supports headers.
2225
        supportHeaders := c.srv.supportsHeaders()
648✔
2226

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

2247
        // Remember the remote server.
2248
        c.leaf.remoteServer = proto.Name
648✔
2249
        // Remember the remote account name
648✔
2250
        c.leaf.remoteAccName = proto.RemoteAccount
648✔
2251
        // Remember if the leafnode requested isolation.
648✔
2252
        c.leaf.isolated = c.leaf.isolated || proto.Isolate
648✔
2253

648✔
2254
        // If the other side has declared itself a hub, so we will take on the spoke role.
648✔
2255
        if proto.Hub {
666✔
2256
                c.leaf.isSpoke = true
18✔
2257
        }
18✔
2258

2259
        // The soliciting side is part of a cluster.
2260
        if proto.Cluster != _EMPTY_ {
1,139✔
2261
                c.leaf.remoteCluster = proto.Cluster
491✔
2262
        }
491✔
2263

2264
        c.leaf.remoteDomain = proto.Domain
648✔
2265

648✔
2266
        // When a leaf solicits a connection to a hub, the perms that it will use on the soliciting leafnode's
648✔
2267
        // behalf are correct for them, but inside the hub need to be reversed since data is flowing in the opposite direction.
648✔
2268
        if !c.isSolicitedLeafNode() && c.perms != nil {
670✔
2269
                sp, pp := c.perms.sub, c.perms.pub
22✔
2270
                c.perms.sub, c.perms.pub = pp, sp
22✔
2271
                if c.opts.Import != nil {
43✔
2272
                        c.darray = c.opts.Import.Deny
21✔
2273
                } else {
22✔
2274
                        c.darray = nil
1✔
2275
                }
1✔
2276
        }
2277

2278
        // Set the Ping timer
2279
        c.setFirstPingTimer()
648✔
2280

648✔
2281
        // If we received pub deny permissions from the other end, merge with existing ones.
648✔
2282
        c.mergeDenyPermissions(pub, proto.DenyPub)
648✔
2283

648✔
2284
        acc := c.acc
648✔
2285
        c.mu.Unlock()
648✔
2286

648✔
2287
        // If the account is not set (e.g. connection was closed due to auth
648✔
2288
        // timeout while still being processed), bail out to avoid a panic.
648✔
2289
        if acc == nil {
648✔
2290
                c.closeConnection(MissingAccount)
×
2291
                return ErrMissingAccount
×
2292
        }
×
2293

2294
        // Register the cluster, even if empty, as long as we are acting as a hub.
2295
        if !proto.Hub {
1,278✔
2296
                acc.registerLeafNodeCluster(proto.Cluster)
630✔
2297
        }
630✔
2298

2299
        // Add in the leafnode here since we passed through auth at this point.
2300
        s.addLeafNodeConnection(c, proto.Name, proto.Cluster, true)
648✔
2301

648✔
2302
        // If we have permissions bound to this leafnode we need to send then back to the
648✔
2303
        // origin server for local enforcement.
648✔
2304
        s.sendPermsAndAccountInfo(c)
648✔
2305

648✔
2306
        // Create and initialize the smap since we know our bound account now.
648✔
2307
        // This will send all registered subs too.
648✔
2308
        s.initLeafNodeSmapAndSendSubs(c)
648✔
2309

648✔
2310
        // Announce the account connect event for a leaf node.
648✔
2311
        // This will be a no-op as needed.
648✔
2312
        s.sendLeafNodeConnect(c.acc)
648✔
2313

648✔
2314
        // Check to see if we need to kick any internal source or mirror consumers.
648✔
2315
        // This will be a no-op if JetStream not enabled for this server or if the bound account
648✔
2316
        // does not have jetstream.
648✔
2317
        s.checkInternalSyncConsumers(acc)
648✔
2318

648✔
2319
        return nil
648✔
2320
}
2321

2322
// checkInternalSyncConsumers
2323
func (s *Server) checkInternalSyncConsumers(acc *Account) {
1,989✔
2324
        // Grab our js
1,989✔
2325
        js := s.getJetStream()
1,989✔
2326

1,989✔
2327
        // Only applicable if we have JS and the leafnode has JS as well.
1,989✔
2328
        // We check for remote JS outside.
1,989✔
2329
        if !js.isEnabled() || acc == nil {
3,160✔
2330
                return
1,171✔
2331
        }
1,171✔
2332

2333
        // We will check all streams in our local account. They must be a leader and
2334
        // be sourcing or mirroring. We will check the external config on the stream itself
2335
        // if this is cross domain, or if the remote domain is empty, meaning we might be
2336
        // extending the system across this leafnode connection and hence we would be extending
2337
        // our own domain.
2338
        jsa := js.lookupAccount(acc)
818✔
2339
        if jsa == nil {
1,127✔
2340
                return
309✔
2341
        }
309✔
2342

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

509✔
2357
        // Now loop through all candidates and check if we are the leader and have NOT
509✔
2358
        // created the sync up consumer.
509✔
2359
        for _, mset := range streams {
522✔
2360
                mset.retryDisconnectedSyncConsumers()
13✔
2361
        }
13✔
2362
}
2363

2364
// Returns the remote cluster name. This is set only once so does not require a lock.
2365
func (c *client) remoteCluster() string {
150,649✔
2366
        if c.leaf == nil {
150,649✔
2367
                return _EMPTY_
×
2368
        }
×
2369
        return c.leaf.remoteCluster
150,649✔
2370
}
2371

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

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

1,251✔
2405
        // Hold the client lock otherwise there can be a race and miss some subs.
1,251✔
2406
        c.mu.Lock()
1,251✔
2407
        defer c.mu.Unlock()
1,251✔
2408

1,251✔
2409
        acc.mu.RLock()
1,251✔
2410
        accName := acc.Name
1,251✔
2411
        accNTag := acc.nameTag
1,251✔
2412

1,251✔
2413
        // To make printing look better when no friendly name present.
1,251✔
2414
        if accNTag != _EMPTY_ {
1,256✔
2415
                accNTag = "/" + accNTag
5✔
2416
        }
5✔
2417

2418
        // If we are solicited we only send interest for local clients.
2419
        if c.isSpokeLeafNode() {
1,854✔
2420
                acc.sl.localSubs(&subs, true)
603✔
2421
        } else {
1,251✔
2422
                acc.sl.All(&subs)
648✔
2423
        }
648✔
2424

2425
        // Check if we have an existing service import reply.
2426
        siReply := copyBytes(acc.siReply)
1,251✔
2427

1,251✔
2428
        // Since leaf nodes only send on interest, if the bound
1,251✔
2429
        // account has import services we need to send those over.
1,251✔
2430
        for isubj := range acc.imports.services {
5,938✔
2431
                if c.isSpokeLeafNode() && !c.canSubscribe(isubj) {
4,972✔
2432
                        c.Debugf("Not permitted to import service %q on behalf of %s%s", isubj, accName, accNTag)
285✔
2433
                        continue
285✔
2434
                }
2435
                ims = append(ims, isubj)
4,402✔
2436
        }
2437
        // Likewise for mappings.
2438
        for _, m := range acc.mappings {
3,513✔
2439
                if c.isSpokeLeafNode() && !c.canSubscribe(m.src) {
2,280✔
2440
                        c.Debugf("Not permitted to import mapping %q on behalf of %s%s", m.src, accName, accNTag)
18✔
2441
                        continue
18✔
2442
                }
2443
                ims = append(ims, m.src)
2,244✔
2444
        }
2445

2446
        // Create a unique subject that will be used for loop detection.
2447
        lds := acc.lds
1,251✔
2448
        acc.mu.RUnlock()
1,251✔
2449

1,251✔
2450
        // Check if we have to create the LDS.
1,251✔
2451
        if lds == _EMPTY_ {
2,223✔
2452
                lds = leafNodeLoopDetectionSubjectPrefix + nuid.Next()
972✔
2453
                acc.mu.Lock()
972✔
2454
                acc.lds = lds
972✔
2455
                acc.mu.Unlock()
972✔
2456
        }
972✔
2457

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

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

2486
        // Now walk the results and add them to our smap
2487
        rc := c.leaf.remoteCluster
1,251✔
2488
        c.leaf.smap = make(map[string]int32)
1,251✔
2489
        for _, sub := range subs {
35,413✔
2490
                // Check perms regardless of role.
34,162✔
2491
                if c.perms != nil && !c.canSubscribe(string(sub.subject)) {
36,296✔
2492
                        c.Debugf("Not permitted to subscribe to %q on behalf of %s%s", sub.subject, accName, accNTag)
2,134✔
2493
                        continue
2,134✔
2494
                }
2495
                // Don't advertise interest from leafnodes to other isolated leafnodes.
2496
                if sub.client.kind == LEAF && c.isIsolatedLeafNode() {
32,038✔
2497
                        continue
10✔
2498
                }
2499
                // We ignore ourselves here.
2500
                // Also don't add the subscription if it has a origin cluster and the
2501
                // cluster name matches the one of the client we are sending to.
2502
                if c != sub.client && (sub.origin == nil || (bytesToString(sub.origin) != rc)) {
59,164✔
2503
                        count := int32(1)
27,146✔
2504
                        if len(sub.queue) > 0 && sub.qw > 0 {
27,156✔
2505
                                count = sub.qw
10✔
2506
                        }
10✔
2507
                        c.leaf.smap[keyFromSub(sub)] += count
27,146✔
2508
                        if c.leaf.tsub == nil {
28,317✔
2509
                                c.leaf.tsub = make(map[*subscription]struct{})
1,171✔
2510
                        }
1,171✔
2511
                        c.leaf.tsub[sub] = struct{}{}
27,146✔
2512
                }
2513
        }
2514
        // FIXME(dlc) - We need to update appropriately on an account claims update.
2515
        for _, isubj := range ims {
7,897✔
2516
                c.leaf.smap[isubj]++
6,646✔
2517
        }
6,646✔
2518
        // If we have gateways enabled we need to make sure the other side sends us responses
2519
        // that have been augmented from the original subscription.
2520
        // TODO(dlc) - Should we lock this down more?
2521
        if applyGlobalRouting {
1,339✔
2522
                c.leaf.smap[oldGWReplyPrefix+"*.>"]++
88✔
2523
                c.leaf.smap[gwReplyPrefix+">"]++
88✔
2524
        }
88✔
2525
        // Detect loops by subscribing to a specific subject and checking
2526
        // if this sub is coming back to us.
2527
        c.leaf.smap[lds]++
1,251✔
2528

1,251✔
2529
        // Check if we need to add an existing siReply to our map.
1,251✔
2530
        // This will be a prefix so add on the wildcard.
1,251✔
2531
        if siReply != nil {
1,271✔
2532
                wcsub := append(siReply, '>')
20✔
2533
                c.leaf.smap[string(wcsub)]++
20✔
2534
        }
20✔
2535
        // Queue all protocols. There is no max pending limit for LN connection,
2536
        // so we don't need chunking. The writes will happen from the writeLoop.
2537
        var b bytes.Buffer
1,251✔
2538
        for key, n := range c.leaf.smap {
25,819✔
2539
                c.writeLeafSub(&b, key, n)
24,568✔
2540
        }
24,568✔
2541
        if b.Len() > 0 {
2,502✔
2542
                c.enqueueProto(b.Bytes())
1,251✔
2543
        }
1,251✔
2544
        if c.leaf.tsub != nil {
2,423✔
2545
                // Clear the tsub map after 5 seconds.
1,172✔
2546
                c.leaf.tsubt = time.AfterFunc(5*time.Second, func() {
1,209✔
2547
                        c.mu.Lock()
37✔
2548
                        if c.leaf != nil {
74✔
2549
                                c.leaf.tsub = nil
37✔
2550
                                c.leaf.tsubt = nil
37✔
2551
                        }
37✔
2552
                        c.mu.Unlock()
37✔
2553
                })
2554
        }
2555
}
2556

2557
// updateInterestForAccountOnGateway called from gateway code when processing RS+ and RS-.
2558
func (s *Server) updateInterestForAccountOnGateway(accName string, sub *subscription, delta int32) {
195,717✔
2559
        // Since we're in the gateway's readLoop, and we would otherwise block, don't allow fetching.
195,717✔
2560
        acc, err := s.lookupOrFetchAccount(accName, false)
195,717✔
2561
        if acc == nil || err != nil {
196,044✔
2562
                s.Debugf("No or bad account for %q, failed to update interest from gateway", accName)
327✔
2563
                return
327✔
2564
        }
327✔
2565
        acc.updateLeafNodes(sub, delta)
195,390✔
2566
}
2567

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

2577
        // We will do checks for no leafnodes and same cluster here inline and under the
2578
        // general account read lock.
2579
        // If we feel we need to update the leafnodes we will do that out of line to avoid
2580
        // blocking routes or GWs.
2581

2582
        acc.mu.RLock()
2,400,634✔
2583
        // First check if we even have leafnodes here.
2,400,634✔
2584
        if acc.nleafs == 0 {
4,741,080✔
2585
                acc.mu.RUnlock()
2,340,446✔
2586
                return
2,340,446✔
2587
        }
2,340,446✔
2588

2589
        // Is this a loop detection subject.
2590
        isLDS := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
60,188✔
2591

60,188✔
2592
        // Capture the cluster even if its empty.
60,188✔
2593
        var cluster string
60,188✔
2594
        if sub.origin != nil {
103,715✔
2595
                cluster = bytesToString(sub.origin)
43,527✔
2596
        }
43,527✔
2597

2598
        // If we have an isolated cluster we can return early, as long as it is not a loop detection subject.
2599
        // Empty clusters will return false for the check.
2600
        if !isLDS && acc.isLeafNodeClusterIsolated(cluster) {
78,717✔
2601
                acc.mu.RUnlock()
18,529✔
2602
                return
18,529✔
2603
        }
18,529✔
2604

2605
        // We can release the general account lock.
2606
        acc.mu.RUnlock()
41,659✔
2607

41,659✔
2608
        // We can hold the list lock here to avoid having to copy a large slice.
41,659✔
2609
        acc.lmu.RLock()
41,659✔
2610
        defer acc.lmu.RUnlock()
41,659✔
2611

41,659✔
2612
        // Do this once.
41,659✔
2613
        subject := string(sub.subject)
41,659✔
2614

41,659✔
2615
        // Walk the connected leafnodes from a random starting point to avoid
41,659✔
2616
        // concurrent callers all contending over leafs in the same order.
41,659✔
2617
        nleafs := len(acc.lleafs)
41,659✔
2618
        start := 0
41,659✔
2619
        if nleafs > 1 {
48,454✔
2620
                start = rand.Intn(nleafs)
6,795✔
2621
        }
6,795✔
2622
        for i := 0; i < nleafs; i++ {
94,827✔
2623
                ln := acc.lleafs[(start+i)%nleafs]
53,168✔
2624
                if ln == sub.client {
81,765✔
2625
                        continue
28,597✔
2626
                }
2627
                ln.mu.RLock()
24,571✔
2628
                // Don't advertise interest from leafnodes to other isolated leafnodes.
24,571✔
2629
                if sub.client.kind == LEAF && ln.isIsolatedLeafNode() {
24,607✔
2630
                        ln.mu.RUnlock()
36✔
2631
                        continue
36✔
2632
                }
2633
                // If `hubOnly` is true, it means that we want to update only leafnodes
2634
                // that connect to this server (so isHubLeafNode() would return `true`).
2635
                if hubOnly && !ln.isHubLeafNode() {
24,541✔
2636
                        ln.mu.RUnlock()
6✔
2637
                        continue
6✔
2638
                }
2639
                // Check to make sure this sub does not have an origin cluster that matches the leafnode.
2640
                // If skipped, make sure that we still let go the "$LDS." subscription that allows
2641
                // the detection of loops as long as different cluster.
2642
                clusterDifferent := cluster != ln.remoteCluster()
24,529✔
2643
                update := (isLDS && clusterDifferent) ||
24,529✔
2644
                        ((cluster == _EMPTY_ || clusterDifferent) && (delta <= 0 || ln.canSubscribeInternal(subject)))
24,529✔
2645
                ln.mu.RUnlock()
24,529✔
2646
                if update {
46,085✔
2647
                        ln.mu.Lock()
21,556✔
2648
                        // The leaf role, isolation mode, and remote cluster are stable
21,556✔
2649
                        // for the connection. Recheck canSubscribe here since permissions
21,556✔
2650
                        // can change, and to initializes mperms for wildcard subscriptions
21,556✔
2651
                        // that collide with deny rules.
21,556✔
2652
                        if isLDS || delta <= 0 || ln.canSubscribe(subject) {
43,112✔
2653
                                ln.updateSmap(sub, delta, isLDS)
21,556✔
2654
                        }
21,556✔
2655
                        ln.mu.Unlock()
21,556✔
2656
                }
2657
        }
2658
}
2659

2660
// updateLeafNodes will make sure to update the account smap for the subscription.
2661
// Will also forward to all leaf nodes as needed.
2662
func (acc *Account) updateLeafNodes(sub *subscription, delta int32) {
2,400,611✔
2663
        acc.updateLeafNodesEx(sub, delta, false)
2,400,611✔
2664
}
2,400,611✔
2665

2666
// This will make an update to our internal smap and determine if we should send out
2667
// an interest update to the remote side.
2668
// Lock should be held.
2669
func (c *client) updateSmap(sub *subscription, delta int32, isLDS bool) {
21,556✔
2670
        if c.leaf.smap == nil {
21,562✔
2671
                return
6✔
2672
        }
6✔
2673

2674
        // If we are solicited make sure this is a local client or a non-solicited leaf node
2675
        skind := sub.client.kind
21,550✔
2676
        updateClient := skind == CLIENT || skind == SYSTEM || skind == JETSTREAM || skind == ACCOUNT
21,550✔
2677
        if !isLDS && c.isSpokeLeafNode() && !(updateClient || (skind == LEAF && !sub.client.isSpokeLeafNode())) {
28,464✔
2678
                return
6,914✔
2679
        }
6,914✔
2680

2681
        // For additions, check if that sub has just been processed during initLeafNodeSmapAndSendSubs
2682
        if delta > 0 && c.leaf.tsub != nil {
21,779✔
2683
                if _, present := c.leaf.tsub[sub]; present {
7,145✔
2684
                        delete(c.leaf.tsub, sub)
2✔
2685
                        if len(c.leaf.tsub) == 0 {
2✔
2686
                                c.leaf.tsub = nil
×
2687
                                c.leaf.tsubt.Stop()
×
2688
                                c.leaf.tsubt = nil
×
2689
                        }
×
2690
                        return
2✔
2691
                }
2692
        }
2693

2694
        key := keyFromSub(sub)
14,634✔
2695
        n, ok := c.leaf.smap[key]
14,634✔
2696
        if delta < 0 && !ok {
15,365✔
2697
                return
731✔
2698
        }
731✔
2699

2700
        // We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
2701
        update := sub.queue != nil || (n <= 0 && n+delta > 0) || (n > 0 && n+delta <= 0)
13,903✔
2702
        n += delta
13,903✔
2703
        if n > 0 {
24,391✔
2704
                c.leaf.smap[key] = n
10,488✔
2705
        } else {
13,903✔
2706
                delete(c.leaf.smap, key)
3,415✔
2707
        }
3,415✔
2708
        if update {
23,164✔
2709
                c.sendLeafNodeSubUpdate(key, n)
9,261✔
2710
        }
9,261✔
2711
}
2712

2713
// Used to force add subjects to the subject map.
2714
func (c *client) forceAddToSmap(subj string) {
4✔
2715
        c.mu.Lock()
4✔
2716
        defer c.mu.Unlock()
4✔
2717

4✔
2718
        if c.leaf.smap == nil {
4✔
2719
                return
×
2720
        }
×
2721
        n := c.leaf.smap[subj]
4✔
2722
        if n != 0 {
5✔
2723
                return
1✔
2724
        }
1✔
2725
        // Place into the map since it was not there.
2726
        c.leaf.smap[subj] = 1
3✔
2727
        c.sendLeafNodeSubUpdate(subj, 1)
3✔
2728
}
2729

2730
// Used to force remove a subject from the subject map.
2731
func (c *client) forceRemoveFromSmap(subj string) {
1✔
2732
        c.mu.Lock()
1✔
2733
        defer c.mu.Unlock()
1✔
2734

1✔
2735
        if c.leaf.smap == nil {
1✔
2736
                return
×
2737
        }
×
2738
        n := c.leaf.smap[subj]
1✔
2739
        if n == 0 {
1✔
2740
                return
×
2741
        }
×
2742
        n--
1✔
2743
        if n == 0 {
2✔
2744
                // Remove is now zero
1✔
2745
                delete(c.leaf.smap, subj)
1✔
2746
                c.sendLeafNodeSubUpdate(subj, 0)
1✔
2747
        } else {
1✔
2748
                c.leaf.smap[subj] = n
×
2749
        }
×
2750
}
2751

2752
// Send the subscription interest change to the other side.
2753
// Lock should be held.
2754
func (c *client) sendLeafNodeSubUpdate(key string, n int32) {
9,265✔
2755
        // If we are a spoke, we need to check if we are allowed to send this subscription over to the hub.
9,265✔
2756
        if c.isSpokeLeafNode() {
11,372✔
2757
                checkPerms := true
2,107✔
2758
                if len(key) > 0 && (key[0] == '$' || key[0] == '_') {
3,291✔
2759
                        if strings.HasPrefix(key, leafNodeLoopDetectionSubjectPrefix) ||
1,184✔
2760
                                strings.HasPrefix(key, oldGWReplyPrefix) ||
1,184✔
2761
                                strings.HasPrefix(key, gwReplyPrefix) {
1,270✔
2762
                                checkPerms = false
86✔
2763
                        }
86✔
2764
                }
2765
                if checkPerms {
4,128✔
2766
                        var subject string
2,021✔
2767
                        if sep := strings.IndexByte(key, ' '); sep != -1 {
2,504✔
2768
                                subject = key[:sep]
483✔
2769
                        } else {
2,021✔
2770
                                subject = key
1,538✔
2771
                        }
1,538✔
2772
                        if !c.canSubscribe(subject) {
2,021✔
2773
                                return
×
2774
                        }
×
2775
                }
2776
        }
2777
        // If we are here we can send over to the other side.
2778
        _b := [64]byte{}
9,265✔
2779
        b := bytes.NewBuffer(_b[:0])
9,265✔
2780
        c.writeLeafSub(b, key, n)
9,265✔
2781
        c.enqueueProto(b.Bytes())
9,265✔
2782
}
2783

2784
// Helper function to build the key.
2785
func keyFromSub(sub *subscription) string {
42,567✔
2786
        var sb strings.Builder
42,567✔
2787
        sb.Grow(len(sub.subject) + len(sub.queue) + 1)
42,567✔
2788
        sb.Write(sub.subject)
42,567✔
2789
        if sub.queue != nil {
46,163✔
2790
                // Just make the key subject spc group, e.g. 'foo bar'
3,596✔
2791
                sb.WriteByte(' ')
3,596✔
2792
                sb.Write(sub.queue)
3,596✔
2793
        }
3,596✔
2794
        return sb.String()
42,567✔
2795
}
2796

2797
const (
2798
        keyRoutedSub         = "R"
2799
        keyRoutedSubByte     = 'R'
2800
        keyRoutedLeafSub     = "L"
2801
        keyRoutedLeafSubByte = 'L'
2802
)
2803

2804
// Helper function to build the key that prevents collisions between normal
2805
// routed subscriptions and routed subscriptions on behalf of a leafnode.
2806
// Keys will look like this:
2807
// "R foo"          -> plain routed sub on "foo"
2808
// "R foo bar"      -> queue routed sub on "foo", queue "bar"
2809
// "L foo bar"      -> plain routed leaf sub on "foo", leaf "bar"
2810
// "L foo bar baz"  -> queue routed sub on "foo", queue "bar", leaf "baz"
2811
func keyFromSubWithOrigin(sub *subscription) string {
611,891✔
2812
        var sb strings.Builder
611,891✔
2813
        sb.Grow(2 + len(sub.origin) + 1 + len(sub.subject) + 1 + len(sub.queue))
611,891✔
2814
        leaf := len(sub.origin) > 0
611,891✔
2815
        if leaf {
626,523✔
2816
                sb.WriteByte(keyRoutedLeafSubByte)
14,632✔
2817
        } else {
611,891✔
2818
                sb.WriteByte(keyRoutedSubByte)
597,259✔
2819
        }
597,259✔
2820
        sb.WriteByte(' ')
611,891✔
2821
        sb.Write(sub.subject)
611,891✔
2822
        if sub.queue != nil {
638,497✔
2823
                sb.WriteByte(' ')
26,606✔
2824
                sb.Write(sub.queue)
26,606✔
2825
        }
26,606✔
2826
        if leaf {
626,523✔
2827
                sb.WriteByte(' ')
14,632✔
2828
                sb.Write(sub.origin)
14,632✔
2829
        }
14,632✔
2830
        return sb.String()
611,891✔
2831
}
2832

2833
// Lock should be held.
2834
func (c *client) writeLeafSub(w *bytes.Buffer, key string, n int32) {
33,833✔
2835
        if key == _EMPTY_ {
33,833✔
2836
                return
×
2837
        }
×
2838
        if n > 0 {
64,250✔
2839
                w.WriteString("LS+ " + key)
30,417✔
2840
                // Check for queue semantics, if found write n.
30,417✔
2841
                if strings.Contains(key, " ") {
32,751✔
2842
                        w.WriteString(" ")
2,334✔
2843
                        var b [12]byte
2,334✔
2844
                        var i = len(b)
2,334✔
2845
                        for l := n; l > 0; l /= 10 {
5,587✔
2846
                                i--
3,253✔
2847
                                b[i] = digits[l%10]
3,253✔
2848
                        }
3,253✔
2849
                        w.Write(b[i:])
2,334✔
2850
                        if c.trace {
2,334✔
2851
                                arg := fmt.Sprintf("%s %d", key, n)
×
2852
                                c.traceOutOp("LS+", []byte(arg))
×
2853
                        }
×
2854
                } else if c.trace {
28,100✔
2855
                        c.traceOutOp("LS+", []byte(key))
17✔
2856
                }
17✔
2857
        } else {
3,416✔
2858
                w.WriteString("LS- " + key)
3,416✔
2859
                if c.trace {
3,416✔
2860
                        c.traceOutOp("LS-", []byte(key))
×
2861
                }
×
2862
        }
2863
        w.WriteString(CR_LF)
33,833✔
2864
}
2865

2866
// processLeafSub will process an inbound sub request for the remote leaf node.
2867
func (c *client) processLeafSub(argo []byte) (err error) {
30,121✔
2868
        // Indicate activity.
30,121✔
2869
        c.in.subs++
30,121✔
2870

30,121✔
2871
        srv := c.srv
30,121✔
2872
        if srv == nil {
30,121✔
2873
                return nil
×
2874
        }
×
2875

2876
        // Copy so we do not reference a potentially large buffer
2877
        arg := make([]byte, len(argo))
30,121✔
2878
        copy(arg, argo)
30,121✔
2879

30,121✔
2880
        args := splitArg(arg)
30,121✔
2881
        sub := &subscription{client: c}
30,121✔
2882

30,121✔
2883
        delta := int32(1)
30,121✔
2884
        switch len(args) {
30,121✔
2885
        case 1:
27,812✔
2886
                sub.queue = nil
27,812✔
2887
        case 3:
2,309✔
2888
                sub.queue = args[1]
2,309✔
2889
                sub.qw = int32(parseSize(args[2]))
2,309✔
2890
                // TODO: (ik) We should have a non empty queue name and a queue
2,309✔
2891
                // weight >= 1. For 2.11, we may want to return an error if that
2,309✔
2892
                // is not the case, but for now just overwrite `delta` if queue
2,309✔
2893
                // weight is greater than 1 (it is possible after a reconnect/
2,309✔
2894
                // server restart to receive a queue weight > 1 for a new sub).
2,309✔
2895
                if sub.qw > 1 {
4,014✔
2896
                        delta = sub.qw
1,705✔
2897
                }
1,705✔
2898
        default:
×
2899
                return fmt.Errorf("processLeafSub Parse Error: '%s'", arg)
×
2900
        }
2901
        sub.subject = args[0]
30,121✔
2902

30,121✔
2903
        c.mu.Lock()
30,121✔
2904
        if c.isClosed() {
30,145✔
2905
                c.mu.Unlock()
24✔
2906
                return nil
24✔
2907
        }
24✔
2908

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

30,097✔
2921
        if ldsPrefix && bytesToString(sub.subject) == acc.getLDSubject() {
30,104✔
2922
                c.mu.Unlock()
7✔
2923
                c.handleLeafNodeLoop(true)
7✔
2924
                return nil
7✔
2925
        }
7✔
2926

2927
        // Check permissions if applicable. (but exclude the $LDS, $GR and _GR_)
2928
        checkPerms := true
30,090✔
2929
        if sub.subject[0] == '$' || sub.subject[0] == '_' {
57,260✔
2930
                if ldsPrefix ||
27,170✔
2931
                        bytes.HasPrefix(sub.subject, []byte(oldGWReplyPrefix)) ||
27,170✔
2932
                        bytes.HasPrefix(sub.subject, []byte(gwReplyPrefix)) {
29,073✔
2933
                        checkPerms = false
1,903✔
2934
                }
1,903✔
2935
        }
2936

2937
        // If we are a hub check that we can publish to this subject.
2938
        if checkPerms {
58,277✔
2939
                subj := string(sub.subject)
28,187✔
2940
                if subjectIsLiteral(subj) && !c.pubAllowedFullCheck(subj, true, true) {
28,539✔
2941
                        c.mu.Unlock()
352✔
2942
                        c.leafSubPermViolation(sub.subject)
352✔
2943
                        c.Debugf(fmt.Sprintf("Permissions Violation for Subscription to %q", sub.subject))
352✔
2944
                        return nil
352✔
2945
                }
352✔
2946
        }
2947

2948
        // Check if we have a maximum on the number of subscriptions.
2949
        if c.subsAtLimit() {
29,746✔
2950
                c.mu.Unlock()
8✔
2951
                c.maxSubsExceeded()
8✔
2952
                return nil
8✔
2953
        }
8✔
2954

2955
        // If we have an origin cluster associated mark that in the sub.
2956
        if rc := c.remoteCluster(); rc != _EMPTY_ {
55,503✔
2957
                sub.origin = []byte(rc)
25,773✔
2958
        }
25,773✔
2959

2960
        // Like Routes, we store local subs by account and subject and optionally queue name.
2961
        // If we have a queue it will have a trailing weight which we do not want.
2962
        if sub.queue != nil {
31,725✔
2963
                sub.sid = arg[:len(arg)-len(args[2])-1]
1,995✔
2964
        } else {
29,730✔
2965
                sub.sid = arg
27,735✔
2966
        }
27,735✔
2967
        key := bytesToString(sub.sid)
29,730✔
2968
        osub := c.subs[key]
29,730✔
2969
        if osub == nil {
57,917✔
2970
                c.subs[key] = sub
28,187✔
2971
                // Now place into the account sl.
28,187✔
2972
                if err := acc.sl.Insert(sub); err != nil {
28,187✔
2973
                        delete(c.subs, key)
×
2974
                        c.mu.Unlock()
×
2975
                        c.Errorf("Could not insert subscription: %v", err)
×
2976
                        c.sendErr("Invalid Subscription")
×
2977
                        return nil
×
2978
                }
×
2979
        } else if sub.queue != nil {
3,085✔
2980
                // For a queue we need to update the weight.
1,542✔
2981
                delta = sub.qw - atomic.LoadInt32(&osub.qw)
1,542✔
2982
                atomic.StoreInt32(&osub.qw, sub.qw)
1,542✔
2983
                acc.sl.UpdateRemoteQSub(osub)
1,542✔
2984
        }
1,542✔
2985
        spoke := c.isSpokeLeafNode()
29,730✔
2986
        c.mu.Unlock()
29,730✔
2987

29,730✔
2988
        // Only add in shadow subs if a new sub or qsub.
29,730✔
2989
        if osub == nil {
57,917✔
2990
                if err := c.addShadowSubscriptions(acc, sub); err != nil {
28,187✔
2991
                        c.Errorf(err.Error())
×
2992
                }
×
2993
        }
2994

2995
        // If we are not solicited, treat leaf node subscriptions similar to a
2996
        // client subscription, meaning we forward them to routes, gateways and
2997
        // other leaf nodes as needed.
2998
        if !spoke {
40,172✔
2999
                // If we are routing add to the route map for the associated account.
10,442✔
3000
                srv.updateRouteSubscriptionMap(acc, sub, delta)
10,442✔
3001
                if srv.gateway.enabled {
11,598✔
3002
                        srv.gatewayUpdateSubInterest(acc.Name, sub, delta)
1,156✔
3003
                }
1,156✔
3004
        }
3005
        // Now check on leafnode updates for other leaf nodes. We understand solicited
3006
        // and non-solicited state in this call so we will do the right thing.
3007
        acc.updateLeafNodes(sub, delta)
29,730✔
3008

29,730✔
3009
        return nil
29,730✔
3010
}
3011

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

3022
        c.Errorf(errTxt)
17✔
3023
        // If we are here with "sendErr" false, it means that this is the server
17✔
3024
        // that received the error. The other side will have closed the connection,
17✔
3025
        // but does not hurt to close here too.
17✔
3026
        c.closeConnection(ProtocolViolation)
17✔
3027
}
3028

3029
// processLeafUnsub will process an inbound unsub request for the remote leaf node.
3030
func (c *client) processLeafUnsub(arg []byte) error {
3,137✔
3031
        // Indicate any activity, so pub and sub or unsubs.
3,137✔
3032
        c.in.subs++
3,137✔
3033

3,137✔
3034
        srv := c.srv
3,137✔
3035

3,137✔
3036
        c.mu.Lock()
3,137✔
3037
        if c.isClosed() {
3,182✔
3038
                c.mu.Unlock()
45✔
3039
                return nil
45✔
3040
        }
45✔
3041

3042
        acc := c.acc
3,092✔
3043
        // Guard against LS- arriving before CONNECT has been processed.
3,092✔
3044
        if acc == nil {
3,092✔
3045
                c.mu.Unlock()
×
3046
                c.sendErr("Authorization Violation")
×
3047
                c.closeConnection(ProtocolViolation)
×
3048
                return nil
×
3049
        }
×
3050

3051
        spoke := c.isSpokeLeafNode()
3,092✔
3052
        // We store local subs by account and subject and optionally queue name.
3,092✔
3053
        // LS- will have the arg exactly as the key.
3,092✔
3054
        sub, ok := c.subs[string(arg)]
3,092✔
3055
        if !ok {
3,107✔
3056
                // If not found, don't try to update routes/gws/leaf nodes.
15✔
3057
                c.mu.Unlock()
15✔
3058
                return nil
15✔
3059
        }
15✔
3060
        delta := int32(1)
3,077✔
3061
        if len(sub.queue) > 0 {
3,494✔
3062
                delta = sub.qw
417✔
3063
        }
417✔
3064
        c.mu.Unlock()
3,077✔
3065

3,077✔
3066
        c.unsubscribe(acc, sub, true, true)
3,077✔
3067
        if !spoke {
3,972✔
3068
                // If we are routing subtract from the route map for the associated account.
895✔
3069
                srv.updateRouteSubscriptionMap(acc, sub, -delta)
895✔
3070
                // Gateways
895✔
3071
                if srv.gateway.enabled {
1,083✔
3072
                        srv.gatewayUpdateSubInterest(acc.Name, sub, -delta)
188✔
3073
                }
188✔
3074
        }
3075
        // Now check on leafnode updates for other leaf nodes.
3076
        acc.updateLeafNodes(sub, -delta)
3,077✔
3077
        return nil
3,077✔
3078
}
3079

3080
func (c *client) processLeafHeaderMsgArgs(arg []byte) error {
230✔
3081
        // Unroll splitArgs to avoid runtime/heap issues
230✔
3082
        args := c.argsa[:0]
230✔
3083
        start := -1
230✔
3084
        for i, b := range arg {
12,692✔
3085
                switch b {
12,462✔
3086
                case ' ', '\t', '\r', '\n':
674✔
3087
                        if start >= 0 {
1,348✔
3088
                                args = append(args, arg[start:i])
674✔
3089
                                start = -1
674✔
3090
                        }
674✔
3091
                default:
11,788✔
3092
                        if start < 0 {
12,692✔
3093
                                start = i
904✔
3094
                        }
904✔
3095
                }
3096
        }
3097
        if start >= 0 {
460✔
3098
                args = append(args, arg[start:])
230✔
3099
        }
230✔
3100

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

3✔
3136
                // Grab size.
3✔
3137
                c.pa.szb = args[len(args)-1]
3✔
3138
                c.pa.size = parseSize(c.pa.szb)
3✔
3139

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

3162
        // Common ones processed after check for arg length
3163
        c.pa.subject = args[0]
230✔
3164

230✔
3165
        return nil
230✔
3166
}
3167

3168
func (c *client) processLeafMsgArgs(arg []byte) error {
71,255✔
3169
        // Unroll splitArgs to avoid runtime/heap issues
71,255✔
3170
        args := c.argsa[:0]
71,255✔
3171
        start := -1
71,255✔
3172
        for i, b := range arg {
2,351,077✔
3173
                switch b {
2,279,822✔
3174
                case ' ', '\t', '\r', '\n':
122,770✔
3175
                        if start >= 0 {
245,540✔
3176
                                args = append(args, arg[start:i])
122,770✔
3177
                                start = -1
122,770✔
3178
                        }
122,770✔
3179
                default:
2,157,052✔
3180
                        if start < 0 {
2,351,077✔
3181
                                start = i
194,025✔
3182
                        }
194,025✔
3183
                }
3184
        }
3185
        if start >= 0 {
142,510✔
3186
                args = append(args, arg[start:])
71,255✔
3187
        }
71,255✔
3188

3189
        c.pa.arg = arg
71,255✔
3190
        switch len(args) {
71,255✔
3191
        case 0, 1:
×
3192
                return fmt.Errorf("processLeafMsgArgs Parse Error: '%s'", args)
×
3193
        case 2:
42,450✔
3194
                c.pa.reply = nil
42,450✔
3195
                c.pa.queues = nil
42,450✔
3196
                c.pa.szb = args[1]
42,450✔
3197
                c.pa.size = parseSize(args[1])
42,450✔
3198
        case 3:
6,254✔
3199
                c.pa.reply = args[1]
6,254✔
3200
                c.pa.queues = nil
6,254✔
3201
                c.pa.szb = args[2]
6,254✔
3202
                c.pa.size = parseSize(args[2])
6,254✔
3203
        default:
22,551✔
3204
                // args[1] is our reply indicator. Should be + or | normally.
22,551✔
3205
                if len(args[1]) != 1 {
22,551✔
3206
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3207
                }
×
3208
                switch args[1][0] {
22,551✔
3209
                case '+':
159✔
3210
                        c.pa.reply = args[2]
159✔
3211
                case '|':
22,392✔
3212
                        c.pa.reply = nil
22,392✔
3213
                default:
×
3214
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3215
                }
3216
                // Grab size.
3217
                c.pa.szb = args[len(args)-1]
22,551✔
3218
                c.pa.size = parseSize(c.pa.szb)
22,551✔
3219

22,551✔
3220
                // Grab queue names.
22,551✔
3221
                if c.pa.reply != nil {
22,710✔
3222
                        c.pa.queues = args[3 : len(args)-1]
159✔
3223
                } else {
22,551✔
3224
                        c.pa.queues = args[2 : len(args)-1]
22,392✔
3225
                }
22,392✔
3226
        }
3227
        if c.pa.size < 0 {
71,255✔
3228
                return fmt.Errorf("processLeafMsgArgs Bad or Missing Size: '%s'", args)
×
3229
        }
×
3230
        maxPayload := atomic.LoadInt32(&c.mpay)
71,255✔
3231
        if maxPayload != jwt.NoLimit && int64(c.pa.size) > int64(maxPayload) {
71,255✔
3232
                c.maxPayloadViolation(c.pa.size, maxPayload)
×
3233
                return ErrMaxPayload
×
3234
        }
×
3235

3236
        // Common ones processed after check for arg length
3237
        c.pa.subject = args[0]
71,255✔
3238

71,255✔
3239
        return nil
71,255✔
3240
}
3241

3242
// processInboundLeafMsg is called to process an inbound msg from a leaf node.
3243
func (c *client) processInboundLeafMsg(msg []byte) {
70,116✔
3244
        // Update statistics
70,116✔
3245
        // The msg includes the CR_LF, so pull back out for accounting.
70,116✔
3246
        c.in.msgs++
70,116✔
3247
        c.in.bytes += int32(len(msg) - LEN_CR_LF)
70,116✔
3248

70,116✔
3249
        srv, acc, subject := c.srv, c.acc, string(c.pa.subject)
70,116✔
3250

70,116✔
3251
        // Mostly under testing scenarios.
70,116✔
3252
        if srv == nil || acc == nil {
70,116✔
3253
                return
×
3254
        }
×
3255

3256
        // Check that leaf messages respect the subject permissions.
3257
        if c.perms != nil && !c.leafMsgAllowed() {
70,121✔
3258
                c.leafPubPermViolation(c.pa.subject)
5✔
3259
                return
5✔
3260
        }
5✔
3261

3262
        // Match the subscriptions. We will use our own L1 map if
3263
        // it's still valid, avoiding contention on the shared sublist.
3264
        var r *SublistResult
70,111✔
3265
        var ok bool
70,111✔
3266

70,111✔
3267
        genid := atomic.LoadUint64(&c.acc.sl.genid)
70,111✔
3268
        if genid == c.in.genid && c.in.results != nil {
138,189✔
3269
                r, ok = c.in.results[subject]
68,078✔
3270
        } else {
70,111✔
3271
                // Reset our L1 completely.
2,033✔
3272
                c.in.results = make(map[string]*SublistResult)
2,033✔
3273
                c.in.genid = genid
2,033✔
3274
        }
2,033✔
3275

3276
        // Go back to the sublist data structure.
3277
        if !ok {
110,476✔
3278
                r = c.acc.sl.Match(subject)
40,365✔
3279
                // Prune the results cache. Keeps us from unbounded growth. Random delete.
40,365✔
3280
                if len(c.in.results) >= maxResultCacheSize {
41,433✔
3281
                        n := 0
1,068✔
3282
                        for subj := range c.in.results {
36,312✔
3283
                                delete(c.in.results, subj)
35,244✔
3284
                                if n++; n > pruneSize {
36,312✔
3285
                                        break
1,068✔
3286
                                }
3287
                        }
3288
                }
3289
                // Then add the new cache entry.
3290
                c.in.results[subject] = r
40,365✔
3291
        }
3292

3293
        // Collect queue names if needed.
3294
        var qnames [][]byte
70,111✔
3295

70,111✔
3296
        // Check for no interest, short circuit if so.
70,111✔
3297
        // This is the fanout scale.
70,111✔
3298
        if len(r.psubs)+len(r.qsubs) > 0 {
139,947✔
3299
                flag := pmrNoFlag
69,836✔
3300
                // If we have queue subs in this cluster, then if we run in gateway
69,836✔
3301
                // mode and the remote gateways have queue subs, then we need to
69,836✔
3302
                // collect the queue groups this message was sent to so that we
69,836✔
3303
                // exclude them when sending to gateways.
69,836✔
3304
                if len(r.qsubs) > 0 && c.srv.gateway.enabled &&
69,836✔
3305
                        atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 {
82,180✔
3306
                        flag |= pmrCollectQueueNames
12,344✔
3307
                }
12,344✔
3308
                // If this is a mapped subject that means the mapped interest
3309
                // is what got us here, but this might not have a queue designation
3310
                // If that is the case, make sure we ignore to process local queue subscribers.
3311
                if len(c.pa.mapped) > 0 && len(c.pa.queues) == 0 {
70,086✔
3312
                        flag |= pmrIgnoreEmptyQueueFilter
250✔
3313
                }
250✔
3314
                _, qnames = c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, flag)
69,836✔
3315
        }
3316

3317
        // Now deal with gateways
3318
        if c.srv.gateway.enabled {
83,240✔
3319
                c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, qnames, true)
13,129✔
3320
        }
13,129✔
3321
}
3322

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

66,516✔
3338
        // Service-import replies (_R_), JS ack subjects ($JS.ACK.)
66,516✔
3339
        // are internal routing subjects forwarded via LS+ without
66,516✔
3340
        // permission checks.
66,516✔
3341
        if isServiceReply(subjectToCheck) || isJSAckSubject(subjectToCheck) {
66,546✔
3342
                return true
30✔
3343
        }
30✔
3344

3345
        c.mu.RLock()
66,486✔
3346
        if c.isSpokeLeafNode() {
97,552✔
3347
                // Gateway routed replies are forwarded without
31,066✔
3348
                // permission checks.
31,066✔
3349
                if isGW || c.leafReceiveAllowed(subjectToCheck) {
62,130✔
3350
                        c.mu.RUnlock()
31,064✔
3351
                        return true
31,064✔
3352
                }
31,064✔
3353
        } else if c.leafSendAllowed(subjectToCheck) {
70,834✔
3354
                c.mu.RUnlock()
35,414✔
3355
                return true
35,414✔
3356
        }
35,414✔
3357

3358
        // If allow_responses is not configured, or there is no tracked reply for
3359
        // this subject, the answer is "denied" and we can return it while still
3360
        // holding only the read lock.
3361
        replySubject := bytesToString(wireSubject)
8✔
3362
        if c.perms == nil || c.perms.resp == nil || c.replies[replySubject] == nil {
13✔
3363
                c.mu.RUnlock()
5✔
3364
                return false
5✔
3365
        }
5✔
3366
        c.mu.RUnlock()
3✔
3367

3✔
3368
        // Check tracked reply permissions (allow_responses).
3✔
3369
        // Use the pre-strip subject since deliverMsg tracks
3✔
3370
        // replies under the original form, which includes
3✔
3371
        // the GW routing prefix for routed requests.
3✔
3372
        c.mu.Lock()
3✔
3373
        defer c.mu.Unlock()
3✔
3374
        return c.responseAllowed(replySubject)
3✔
3375
}
3376

3377
// Returns true if the leaf side ACLs allow importing this subject,
3378
// based on the permissions received over INFO and any local deny_imports.
3379
// At least a read lock must be held.
3380
func (c *client) leafReceiveAllowed(subject []byte) bool {
31,066✔
3381
        return c.canSubscribeInternal(bytesToString(subject))
31,066✔
3382
}
31,066✔
3383

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

3398
        allowed := true
25✔
3399
        if perms.Allow != nil && !strings.HasPrefix(subject, mqttPrefix) {
36✔
3400
                allowed = false
11✔
3401
                for _, allowSubj := range perms.Allow {
21✔
3402
                        if matchLiteral(subject, allowSubj) {
16✔
3403
                                allowed = true
6✔
3404
                                break
6✔
3405
                        }
3406
                }
3407
        }
3408

3409
        if allowed && len(perms.Deny) > 0 {
39✔
3410
                for _, denySubj := range perms.Deny {
40✔
3411
                        if matchLiteral(subject, denySubj) {
27✔
3412
                                allowed = false
1✔
3413
                                break
1✔
3414
                        }
3415
                }
3416
        }
3417
        return allowed
25✔
3418
}
3419

3420
// Handles a subscription permission violation.
3421
// See leafPermViolation() for details.
3422
func (c *client) leafSubPermViolation(subj []byte) {
352✔
3423
        c.leafPermViolation(false, subj)
352✔
3424
}
352✔
3425

3426
// Handles a publish permission violation.
3427
// See leafPermViolation() for details.
3428
func (c *client) leafPubPermViolation(subj []byte) {
5✔
3429
        c.leafPermViolation(true, subj)
5✔
3430
}
5✔
3431

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

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

3470
        // We will look for Loop detected error coming from the other side.
3471
        // If we solicit, set the connect delay.
3472
        if !strings.Contains(errStr, "Loop detected") {
80✔
3473
                return
36✔
3474
        }
36✔
3475
        c.handleLeafNodeLoop(false)
8✔
3476
}
3477

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

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

1,807✔
3510
        remote.RLock()
1,807✔
3511
        defer remote.RUnlock()
1,807✔
3512

1,807✔
3513
        tlsRequired := remote.TLS || remote.TLSConfig != nil
1,807✔
3514
        if tlsRequired {
1,886✔
3515
                if remote.TLSConfig != nil {
130✔
3516
                        tlsConfig = remote.TLSConfig.Clone()
51✔
3517
                } else {
79✔
3518
                        tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}
28✔
3519
                }
28✔
3520
                tlsName = remote.tlsName
79✔
3521
                tlsTimeout = remote.TLSTimeout
79✔
3522
                if tlsTimeout == 0 {
124✔
3523
                        tlsTimeout = float64(TLS_TIMEOUT / time.Second)
45✔
3524
                }
45✔
3525
        }
3526

3527
        return tlsRequired, tlsConfig, tlsName, tlsTimeout
1,807✔
3528
}
3529

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

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

3589
        req.Header["Upgrade"] = []string{"websocket"}
50✔
3590
        req.Header["Connection"] = []string{"Upgrade"}
50✔
3591
        req.Header["Sec-WebSocket-Key"] = []string{wsKey}
50✔
3592
        req.Header["Sec-WebSocket-Version"] = []string{"13"}
50✔
3593
        if compress {
61✔
3594
                req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue)
11✔
3595
        }
11✔
3596
        if noMasking {
60✔
3597
                req.Header.Add(wsNoMaskingHeader, wsNoMaskingValue)
10✔
3598
        }
10✔
3599
        c.nc.SetDeadline(time.Now().Add(infoTimeout))
50✔
3600
        if err := req.Write(c.nc); err != nil {
50✔
3601
                return nil, WriteError, err
×
3602
        }
×
3603

3604
        var resp *http.Response
50✔
3605

50✔
3606
        br := bufio.NewReaderSize(c.nc, MAX_CONTROL_LINE_SIZE)
50✔
3607
        resp, err = http.ReadResponse(br, req)
50✔
3608
        if err == nil &&
50✔
3609
                (resp.StatusCode != 101 ||
50✔
3610
                        !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
50✔
3611
                        !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
50✔
3612
                        resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) {
51✔
3613

1✔
3614
                err = fmt.Errorf("invalid websocket connection")
1✔
3615
        }
1✔
3616
        // Check compression extension...
3617
        if err == nil && c.ws.compress {
61✔
3618
                // Check that not only permessage-deflate extension is present, but that
11✔
3619
                // we also have server and client no context take over.
11✔
3620
                srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header, false)
11✔
3621

11✔
3622
                // If server does not support compression, then simply disable it in our side.
11✔
3623
                if !srvCompress {
16✔
3624
                        c.ws.compress = false
5✔
3625
                } else if !noCtxTakeover {
11✔
3626
                        err = fmt.Errorf("compression negotiation error")
×
3627
                }
×
3628
        }
3629
        // Same for no masking...
3630
        if err == nil && noMasking {
60✔
3631
                // Check if server accepts no masking
10✔
3632
                if resp.Header.Get(wsNoMaskingHeader) != wsNoMaskingValue {
11✔
3633
                        // Nope, need to mask our writes as any client would do.
1✔
3634
                        c.ws.maskwrite = true
1✔
3635
                }
1✔
3636
        }
3637
        if resp != nil {
84✔
3638
                resp.Body.Close()
34✔
3639
        }
34✔
3640
        if err != nil {
67✔
3641
                return nil, ReadError, err
17✔
3642
        }
17✔
3643
        c.Debugf("Leafnode compression=%v masking=%v", c.ws.compress, c.ws.maskwrite)
33✔
3644

33✔
3645
        var preBuf []byte
33✔
3646
        // We have to slurp whatever is in the bufio reader and pass that to the readloop.
33✔
3647
        if n := br.Buffered(); n != 0 {
35✔
3648
                preBuf, _ = br.Peek(n)
2✔
3649
        }
2✔
3650
        return preBuf, 0, nil
33✔
3651
}
3652

3653
const connectProcessTimeout = 2 * time.Second
3654

3655
// This is invoked for remote LEAF remote connections after processing the INFO
3656
// protocol.
3657
func (s *Server) leafNodeResumeConnectProcess(c *client) {
643✔
3658
        clusterName := s.ClusterName()
643✔
3659

643✔
3660
        c.mu.Lock()
643✔
3661
        if c.isClosed() {
643✔
3662
                c.mu.Unlock()
×
3663
                return
×
3664
        }
×
3665
        if err := c.sendLeafConnect(clusterName, c.headers); err != nil {
645✔
3666
                c.mu.Unlock()
2✔
3667
                c.closeConnection(WriteError)
2✔
3668
                return
2✔
3669
        }
2✔
3670

3671
        // Spin up the write loop.
3672
        s.startGoRoutine(func() { c.writeLoop() })
1,282✔
3673

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

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

605✔
3720
        // Capture account before releasing lock
605✔
3721
        acc := c.acc
605✔
3722
        // cancel connectProcessTimeout
605✔
3723
        clearTimer(&c.ping.tmr)
605✔
3724
        c.mu.Unlock()
605✔
3725

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

603✔
3750
        // The above functions are not running under the client lock, so it is
603✔
3751
        // possible that between the time we have started the read/write loops
603✔
3752
        // and now, that the connection was closed. This would leave the closed
603✔
3753
        // LN connection possibly registered with the account and/or the server's
603✔
3754
        // leafs map. So check if connection is closed, and if so, manually cleanup.
603✔
3755
        c.mu.Lock()
603✔
3756
        closed := c.isClosed()
603✔
3757
        if !closed {
1,206✔
3758
                c.setFirstPingTimer()
603✔
3759
        }
603✔
3760
        c.mu.Unlock()
603✔
3761
        if closed {
603✔
3762
                s.removeLeafNodeConnection(c)
×
3763
                if prev := acc.removeClient(c); prev == 1 {
×
3764
                        s.decActiveAccounts()
×
3765
                }
×
3766
        }
3767
}
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