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

nats-io / nats-server / 25902955617

14 May 2026 01:11PM UTC coverage: 82.2% (+2.0%) from 80.18%
25902955617

push

github

web-flow
Fix message block corruption on filestore cipher conversion with cache clear (#8166)

This ensures that using an old `mb.bek` doesn't corrupt the block by
maintaining an old offset from before the cache clear.

76650 of 93248 relevant lines covered (82.2%)

556972.55 hits per line

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

89.9
/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,212✔
124
        return c.kind == LEAF && c.leaf != nil && c.leaf.remote != nil
2,212✔
125
}
2,212✔
126

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

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

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

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

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

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

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

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

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

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

326
        // If MinVersion is defined, check that it is valid.
327
        if mv := o.LeafNode.MinVersion; mv != _EMPTY_ {
4,004✔
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,311✔
338
                return nil
3,313✔
339
        }
3,313✔
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_ {
686✔
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 {
684✔
346
                return fmt.Errorf("leafnode: %v", err)
×
347
        }
×
348
        return nil
684✔
349
}
350

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

362
// Used to validate user names in LeafNode configuration.
363
// - rejects mix of single and multiple users.
364
// - rejects duplicate user names.
365
func validateLeafNodeAuthOptions(o *Options) error {
8,276✔
366
        if len(o.LeafNode.Users) == 0 {
16,526✔
367
                return nil
8,250✔
368
        }
8,250✔
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) {
2,082✔
386
        var warnings []string
2,082✔
387

2,082✔
388
        if remote.Proxy.URL == _EMPTY_ {
4,138✔
389
                return warnings, nil
2,056✔
390
        }
2,056✔
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 {
316✔
446
                        remote.setConnectInProgress(false)
66✔
447
                }
66✔
448
        }()
449
        delay := s.getOpts().LeafNode.ReconnectInterval
251✔
450
        select {
251✔
451
        case <-time.After(delay):
192✔
452
        case <-remote.quitCh:
×
453
                return
×
454
        case <-s.quitCh:
59✔
455
                return
59✔
456
        }
457
        clearInProgress = !connectToRemoteLeafNode(s, remote, false)
192✔
458
}
459

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

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

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

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

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

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

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

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

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

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

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

601
const sharedSysAccDelay = 250 * time.Millisecond
602

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

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

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

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

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

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

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

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

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

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

661
        return conn, nil
10✔
662
}
663

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

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

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

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

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

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

715
        var conn net.Conn
1,621✔
716

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

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

1,621✔
727
        // Set default proxy timeout if not specified
1,621✔
728
        if proxyTimeout == 0 {
3,234✔
729
                proxyTimeout = dialTimeout
1,613✔
730
        }
1,613✔
731

732
        attempts := 0
1,621✔
733

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

741
        for s.isRunning() && remote.stillValid() {
7,999✔
742
                rURL := remote.pickNextURL()
6,378✔
743
                url, err := s.getRandomIP(resolver, rURL.Host, nil)
6,378✔
744
                if err == nil {
12,751✔
745
                        var ipStr string
6,373✔
746
                        if url != rURL.Host {
6,446✔
747
                                ipStr = fmt.Sprintf(" (%s)", url)
73✔
748
                        }
73✔
749
                        // Some test may want to disable remotes from connecting
750
                        if s.isLeafConnectDisabled() {
6,500✔
751
                                s.Debugf("Will not attempt to connect to remote server on %q%s, leafnodes currently disabled", rURL.Host, ipStr)
127✔
752
                                err = ErrLeafNodeDisabled
127✔
753
                        } else {
6,373✔
754
                                s.Debugf("Trying to connect as leafnode to remote server on %q%s", rURL.Host, ipStr)
6,246✔
755

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

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

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

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

827✔
821
                return true
827✔
822
        }
823

824
        return false
9✔
825
}
826

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

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

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

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

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

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

4,704✔
873
        if !shouldMigrate {
9,343✔
874
                return
4,639✔
875
        }
4,639✔
876

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

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

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

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

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

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

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

3,978✔
949
        port := opts.LeafNode.Port
3,978✔
950
        if port == -1 {
7,780✔
951
                port = 0
3,802✔
952
        }
3,802✔
953

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2,735✔
1508
        // In case of websocket, the TLS handshake has been already done.
2,735✔
1509
        // So check only for non websocket connections and for configurations
2,735✔
1510
        // where the TLS Handshake was not done first.
2,735✔
1511
        if didSolicit && !c.flags.isSet(handshakeComplete) && !c.isWebsocket() && !remote.TLSHandshakeFirst {
4,662✔
1512
                // If the server requires TLS, we need to set this in the remote
1,927✔
1513
                // otherwise if there is no TLS configuration block for the remote,
1,927✔
1514
                // the solicit side will not attempt to perform the TLS handshake.
1,927✔
1515
                if firstINFO && info.TLSRequired {
1,994✔
1516
                        // Check for TLS/proxy configuration mismatch
67✔
1517
                        if remote.Proxy.URL != _EMPTY_ && !remote.TLS && remote.TLSConfig == nil {
67✔
1518
                                c.mu.Unlock()
×
1519
                                c.Errorf("TLS configuration mismatch: Hub requires TLS but leafnode remote is not configured for TLS. When using a proxy, ensure TLS leafnode configuration matches the Hub requirements.")
×
1520
                                c.closeConnection(TLSHandshakeError)
×
1521
                                return
×
1522
                        }
×
1523
                        remote.TLS = true
67✔
1524
                }
1525
                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
1,964✔
1526
                        c.mu.Unlock()
37✔
1527
                        return
37✔
1528
                }
37✔
1529
        }
1530

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

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

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

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

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

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

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

1689
        var resumeConnect bool
1,451✔
1690

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

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

1,450✔
1713
        finishConnect := info.ConnectInfo
1,450✔
1714
        if resumeConnect && s != nil {
2,146✔
1715
                s.leafNodeResumeConnectProcess(c)
696✔
1716
                if !info.InfoOnConnect {
696✔
1717
                        finishConnect = true
×
1718
                }
×
1719
        }
1720
        if finishConnect {
2,109✔
1721
                s.leafNodeFinishConnectProcess(c)
659✔
1722
        }
659✔
1723

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

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

1,281✔
1753
        if !needsCompression(cm) {
1,374✔
1754
                return false, nil
93✔
1755
        }
93✔
1756

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

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

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

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

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

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

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

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

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

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

1959
        srvDecorated := func() string {
1,568✔
1960
                if myClustName == _EMPTY_ {
238✔
1961
                        return mySrvName
27✔
1962
                }
27✔
1963
                return fmt.Sprintf("%s/%s", mySrvName, myClustName)
184✔
1964
        }
1965

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

701✔
2300
        return nil
701✔
2301
}
2302

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2563
        acc.mu.RLock()
2,551,974✔
2564
        // First check if we even have leafnodes here.
2,551,974✔
2565
        if acc.nleafs == 0 {
5,032,945✔
2566
                acc.mu.RUnlock()
2,480,971✔
2567
                return
2,480,971✔
2568
        }
2,480,971✔
2569

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

71,003✔
2573
        // Capture the cluster even if its empty.
71,003✔
2574
        var cluster string
71,003✔
2575
        if sub.origin != nil {
121,033✔
2576
                cluster = bytesToString(sub.origin)
50,030✔
2577
        }
50,030✔
2578

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

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

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

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

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

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

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

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

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

2675
        key := keyFromSub(sub)
16,345✔
2676
        n, ok := c.leaf.smap[key]
16,345✔
2677
        if delta < 0 && !ok {
17,597✔
2678
                return
1,252✔
2679
        }
1,252✔
2680

2681
        // We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
2682
        update := sub.queue != nil || (n <= 0 && n+delta > 0) || (n > 0 && n+delta <= 0)
15,093✔
2683
        n += delta
15,093✔
2684
        if n > 0 {
26,288✔
2685
                c.leaf.smap[key] = n
11,195✔
2686
        } else {
15,093✔
2687
                delete(c.leaf.smap, key)
3,898✔
2688
        }
3,898✔
2689
        if update {
25,436✔
2690
                c.sendLeafNodeSubUpdate(key, n)
10,343✔
2691
        }
10,343✔
2692
}
2693

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

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

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

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

2733
// Send the subscription interest change to the other side.
2734
// Lock should be held.
2735
func (c *client) sendLeafNodeSubUpdate(key string, n int32) {
10,356✔
2736
        // If we are a spoke, we need to check if we are allowed to send this subscription over to the hub.
10,356✔
2737
        if c.isSpokeLeafNode() {
12,947✔
2738
                checkPerms := true
2,591✔
2739
                if len(key) > 0 && (key[0] == '$' || key[0] == '_') {
4,183✔
2740
                        if strings.HasPrefix(key, leafNodeLoopDetectionSubjectPrefix) ||
1,592✔
2741
                                strings.HasPrefix(key, oldGWReplyPrefix) ||
1,592✔
2742
                                strings.HasPrefix(key, gwReplyPrefix) {
1,682✔
2743
                                checkPerms = false
90✔
2744
                        }
90✔
2745
                }
2746
                if checkPerms {
5,092✔
2747
                        var subject string
2,501✔
2748
                        if sep := strings.IndexByte(key, ' '); sep != -1 {
2,992✔
2749
                                subject = key[:sep]
491✔
2750
                        } else {
2,501✔
2751
                                subject = key
2,010✔
2752
                        }
2,010✔
2753
                        if !c.canSubscribe(subject) {
2,510✔
2754
                                return
9✔
2755
                        }
9✔
2756
                }
2757
        }
2758
        // If we are here we can send over to the other side.
2759
        _b := [64]byte{}
10,347✔
2760
        b := bytes.NewBuffer(_b[:0])
10,347✔
2761
        c.writeLeafSub(b, key, n)
10,347✔
2762
        c.enqueueProto(b.Bytes())
10,347✔
2763
}
2764

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

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

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

2814
// Lock should be held.
2815
func (c *client) writeLeafSub(w *bytes.Buffer, key string, n int32) {
37,580✔
2816
        if key == _EMPTY_ {
37,580✔
2817
                return
×
2818
        }
×
2819
        if n > 0 {
71,261✔
2820
                w.WriteString("LS+ " + key)
33,681✔
2821
                // Check for queue semantics, if found write n.
33,681✔
2822
                if strings.Contains(key, " ") {
35,984✔
2823
                        w.WriteString(" ")
2,303✔
2824
                        var b [12]byte
2,303✔
2825
                        var i = len(b)
2,303✔
2826
                        for l := n; l > 0; l /= 10 {
5,522✔
2827
                                i--
3,219✔
2828
                                b[i] = digits[l%10]
3,219✔
2829
                        }
3,219✔
2830
                        w.Write(b[i:])
2,303✔
2831
                        if c.trace {
2,303✔
2832
                                arg := fmt.Sprintf("%s %d", key, n)
×
2833
                                c.traceOutOp("LS+", []byte(arg))
×
2834
                        }
×
2835
                } else if c.trace {
31,581✔
2836
                        c.traceOutOp("LS+", []byte(key))
203✔
2837
                }
203✔
2838
        } else {
3,899✔
2839
                w.WriteString("LS- " + key)
3,899✔
2840
                if c.trace {
3,915✔
2841
                        c.traceOutOp("LS-", []byte(key))
16✔
2842
                }
16✔
2843
        }
2844
        w.WriteString(CR_LF)
37,580✔
2845
}
2846

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

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

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

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

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

33,341✔
2884
        c.mu.Lock()
33,341✔
2885
        if c.isClosed() {
33,357✔
2886
                c.mu.Unlock()
16✔
2887
                return nil
16✔
2888
        }
16✔
2889

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

33,325✔
2902
        if ldsPrefix && bytesToString(sub.subject) == acc.getLDSubject() {
33,330✔
2903
                c.mu.Unlock()
5✔
2904
                c.handleLeafNodeLoop(true)
5✔
2905
                return nil
5✔
2906
        }
5✔
2907

2908
        // Check permissions if applicable. (but exclude the $LDS, $GR and _GR_)
2909
        checkPerms := true
33,320✔
2910
        if sub.subject[0] == '$' || sub.subject[0] == '_' {
63,679✔
2911
                if ldsPrefix ||
30,359✔
2912
                        bytes.HasPrefix(sub.subject, []byte(oldGWReplyPrefix)) ||
30,359✔
2913
                        bytes.HasPrefix(sub.subject, []byte(gwReplyPrefix)) {
32,436✔
2914
                        checkPerms = false
2,077✔
2915
                }
2,077✔
2916
        }
2917

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

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

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

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

32,995✔
2969
        // Only add in shadow subs if a new sub or qsub.
32,995✔
2970
        if osub == nil {
64,488✔
2971
                if err := c.addShadowSubscriptions(acc, sub); err != nil {
31,493✔
2972
                        c.Errorf(err.Error())
×
2973
                }
×
2974
        }
2975

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

32,995✔
2990
        return nil
32,995✔
2991
}
2992

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

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

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

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

3,530✔
3017
        c.mu.Lock()
3,530✔
3018
        if c.isClosed() {
3,557✔
3019
                c.mu.Unlock()
27✔
3020
                return nil
27✔
3021
        }
27✔
3022

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

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

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

3061
func (c *client) processLeafHeaderMsgArgs(arg []byte) error {
569✔
3062
        // Unroll splitArgs to avoid runtime/heap issues
569✔
3063
        args := c.argsa[:0]
569✔
3064
        start := -1
569✔
3065
        for i, b := range arg {
103,100✔
3066
                switch b {
102,531✔
3067
                case ' ', '\t', '\r', '\n':
1,633✔
3068
                        if start >= 0 {
3,266✔
3069
                                args = append(args, arg[start:i])
1,633✔
3070
                                start = -1
1,633✔
3071
                        }
1,633✔
3072
                default:
100,898✔
3073
                        if start < 0 {
103,100✔
3074
                                start = i
2,202✔
3075
                        }
2,202✔
3076
                }
3077
        }
3078
        if start >= 0 {
1,138✔
3079
                args = append(args, arg[start:])
569✔
3080
        }
569✔
3081

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

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

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

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

569✔
3146
        return nil
569✔
3147
}
3148

3149
func (c *client) processLeafMsgArgs(arg []byte) error {
67,738✔
3150
        // Unroll splitArgs to avoid runtime/heap issues
67,738✔
3151
        args := c.argsa[:0]
67,738✔
3152
        start := -1
67,738✔
3153
        for i, b := range arg {
2,255,136✔
3154
                switch b {
2,187,398✔
3155
                case ' ', '\t', '\r', '\n':
119,510✔
3156
                        if start >= 0 {
239,020✔
3157
                                args = append(args, arg[start:i])
119,510✔
3158
                                start = -1
119,510✔
3159
                        }
119,510✔
3160
                default:
2,067,888✔
3161
                        if start < 0 {
2,255,136✔
3162
                                start = i
187,248✔
3163
                        }
187,248✔
3164
                }
3165
        }
3166
        if start >= 0 {
135,476✔
3167
                args = append(args, arg[start:])
67,738✔
3168
        }
67,738✔
3169

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

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

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

67,738✔
3220
        return nil
67,738✔
3221
}
3222

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

66,605✔
3230
        srv, acc, subject := c.srv, c.acc, string(c.pa.subject)
66,605✔
3231

66,605✔
3232
        // Mostly under testing scenarios.
66,605✔
3233
        if srv == nil || acc == nil {
66,606✔
3234
                return
1✔
3235
        }
1✔
3236

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

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

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

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

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

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

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

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

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

3326
        c.mu.RLock()
62,310✔
3327
        if c.isSpokeLeafNode() {
91,723✔
3328
                // Gateway routed replies are forwarded without
29,413✔
3329
                // permission checks.
29,413✔
3330
                if isGW || c.leafReceiveAllowed(subjectToCheck) {
58,824✔
3331
                        c.mu.RUnlock()
29,411✔
3332
                        return true
29,411✔
3333
                }
29,411✔
3334
        } else if c.leafSendAllowed(subjectToCheck) {
65,788✔
3335
                c.mu.RUnlock()
32,891✔
3336
                return true
32,891✔
3337
        }
32,891✔
3338

3339
        // If allow_responses is not configured, or there is no tracked reply for
3340
        // this subject, the answer is "denied" and we can return it while still
3341
        // holding only the read lock.
3342
        replySubject := bytesToString(wireSubject)
8✔
3343
        if c.perms == nil || c.perms.resp == nil || c.replies[replySubject] == nil {
13✔
3344
                c.mu.RUnlock()
5✔
3345
                return false
5✔
3346
        }
5✔
3347
        c.mu.RUnlock()
3✔
3348

3✔
3349
        // Check tracked reply permissions (allow_responses).
3✔
3350
        // Use the pre-strip subject since deliverMsg tracks
3✔
3351
        // replies under the original form, which includes
3✔
3352
        // the GW routing prefix for routed requests.
3✔
3353
        c.mu.Lock()
3✔
3354
        defer c.mu.Unlock()
3✔
3355
        return c.responseAllowed(replySubject)
3✔
3356
}
3357

3358
// Returns true if the leaf side ACLs allow importing this subject,
3359
// based on the permissions received over INFO and any local deny_imports.
3360
// At least a read lock must be held.
3361
func (c *client) leafReceiveAllowed(subject []byte) bool {
29,413✔
3362
        return c.canSubscribeInternal(bytesToString(subject))
29,413✔
3363
}
29,413✔
3364

3365
// Returns true if the hub side ACLs allow the remote leaf to send
3366
// this subject.
3367
// At least a read lock must be held.
3368
func (c *client) leafSendAllowed(bsubject []byte) bool {
32,897✔
3369
        // Use the original export ACL captured for this accepted leaf.
32,897✔
3370
        // The live perms also contain additional JetStream denies used by
32,897✔
3371
        // the normal forwarding path, and applying them here would reject
32,897✔
3372
        // legitimate inbound JS API requests.
32,897✔
3373
        subject := bytesToString(bsubject)
32,897✔
3374
        perms := c.opts.Export
32,897✔
3375
        if perms == nil || (perms.Allow == nil && perms.Deny == nil) {
65,769✔
3376
                return true
32,872✔
3377
        }
32,872✔
3378

3379
        allowed := true
25✔
3380
        if perms.Allow != nil && !strings.HasPrefix(subject, mqttPrefix) {
36✔
3381
                allowed = false
11✔
3382
                for _, allowSubj := range perms.Allow {
21✔
3383
                        if matchLiteral(subject, allowSubj) {
16✔
3384
                                allowed = true
6✔
3385
                                break
6✔
3386
                        }
3387
                }
3388
        }
3389

3390
        if allowed && len(perms.Deny) > 0 {
39✔
3391
                for _, denySubj := range perms.Deny {
40✔
3392
                        if matchLiteral(subject, denySubj) {
27✔
3393
                                allowed = false
1✔
3394
                                break
1✔
3395
                        }
3396
                }
3397
        }
3398
        return allowed
25✔
3399
}
3400

3401
// Handles a subscription permission violation.
3402
// See leafPermViolation() for details.
3403
func (c *client) leafSubPermViolation(subj []byte) {
317✔
3404
        c.leafPermViolation(false, subj)
317✔
3405
}
317✔
3406

3407
// Handles a publish permission violation.
3408
// See leafPermViolation() for details.
3409
func (c *client) leafPubPermViolation(subj []byte) {
5✔
3410
        c.leafPermViolation(true, subj)
5✔
3411
}
5✔
3412

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

3437
// Invoked from generic processErr() for LEAF connections.
3438
func (c *client) leafProcessErr(errStr string) {
47✔
3439
        // Check if we got a cluster name collision.
47✔
3440
        if strings.Contains(errStr, ErrLeafNodeHasSameClusterName.Error()) {
50✔
3441
                _, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterClusterNameSame)
3✔
3442
                c.Errorf("Leafnode connection dropped with same cluster name error. Delaying attempt to reconnect for %v", delay)
3✔
3443
                return
3✔
3444
        }
3✔
3445
        if strings.Contains(errStr, ErrLeafNodeMinVersionRejected.Error()) {
45✔
3446
                _, delay := c.setLeafConnectDelayIfSoliciting(leafNodeMinVersionReconnectDelay)
1✔
3447
                c.Errorf("Leafnode connection dropped due to minimum version requirement. Delaying attempt to reconnect for %v", delay)
1✔
3448
                return
1✔
3449
        }
1✔
3450

3451
        // We will look for Loop detected error coming from the other side.
3452
        // If we solicit, set the connect delay.
3453
        if !strings.Contains(errStr, "Loop detected") {
79✔
3454
                return
36✔
3455
        }
36✔
3456
        c.handleLeafNodeLoop(false)
7✔
3457
}
3458

3459
// If this leaf connection solicits, sets the connect delay to the given value,
3460
// or the one from the server option's LeafNode.connDelay if one is set (for tests).
3461
// Returns the connection's account name and delay.
3462
func (c *client) setLeafConnectDelayIfSoliciting(delay time.Duration) (string, time.Duration) {
21✔
3463
        c.mu.Lock()
21✔
3464
        if c.isSolicitedLeafNode() {
33✔
3465
                if s := c.srv; s != nil {
24✔
3466
                        if srvdelay := s.getOpts().LeafNode.connDelay; srvdelay != 0 {
16✔
3467
                                delay = srvdelay
4✔
3468
                        }
4✔
3469
                }
3470
                c.leaf.remote.setConnectDelay(delay)
12✔
3471
        }
3472
        var accName string
21✔
3473
        if c.acc != nil {
42✔
3474
                accName = c.acc.Name
21✔
3475
        }
21✔
3476
        c.mu.Unlock()
21✔
3477
        return accName, delay
21✔
3478
}
3479

3480
// For the given remote Leafnode configuration, this function returns
3481
// if TLS is required, and if so, will return a clone of the TLS Config
3482
// (since some fields will be changed during handshake), the TLS server
3483
// name that is remembered, and the TLS timeout.
3484
func (c *client) leafNodeGetTLSConfigForSolicit(remote *leafNodeCfg) (bool, *tls.Config, string, float64) {
1,981✔
3485
        var (
1,981✔
3486
                tlsConfig  *tls.Config
1,981✔
3487
                tlsName    string
1,981✔
3488
                tlsTimeout float64
1,981✔
3489
        )
1,981✔
3490

1,981✔
3491
        remote.RLock()
1,981✔
3492
        defer remote.RUnlock()
1,981✔
3493

1,981✔
3494
        tlsRequired := remote.TLS || remote.TLSConfig != nil
1,981✔
3495
        if tlsRequired {
2,064✔
3496
                if remote.TLSConfig != nil {
134✔
3497
                        tlsConfig = remote.TLSConfig.Clone()
51✔
3498
                } else {
83✔
3499
                        tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}
32✔
3500
                }
32✔
3501
                tlsName = remote.tlsName
83✔
3502
                tlsTimeout = remote.TLSTimeout
83✔
3503
                if tlsTimeout == 0 {
132✔
3504
                        tlsTimeout = float64(TLS_TIMEOUT / time.Second)
49✔
3505
                }
49✔
3506
        }
3507

3508
        return tlsRequired, tlsConfig, tlsName, tlsTimeout
1,981✔
3509
}
3510

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

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

3570
        req.Header["Upgrade"] = []string{"websocket"}
46✔
3571
        req.Header["Connection"] = []string{"Upgrade"}
46✔
3572
        req.Header["Sec-WebSocket-Key"] = []string{wsKey}
46✔
3573
        req.Header["Sec-WebSocket-Version"] = []string{"13"}
46✔
3574
        if compress {
55✔
3575
                req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue)
9✔
3576
        }
9✔
3577
        if noMasking {
56✔
3578
                req.Header.Add(wsNoMaskingHeader, wsNoMaskingValue)
10✔
3579
        }
10✔
3580
        c.nc.SetDeadline(time.Now().Add(infoTimeout))
46✔
3581
        if err := req.Write(c.nc); err != nil {
46✔
3582
                return nil, WriteError, err
×
3583
        }
×
3584

3585
        var resp *http.Response
46✔
3586

46✔
3587
        br := bufio.NewReaderSize(c.nc, MAX_CONTROL_LINE_SIZE)
46✔
3588
        resp, err = http.ReadResponse(br, req)
46✔
3589
        if err == nil &&
46✔
3590
                (resp.StatusCode != 101 ||
46✔
3591
                        !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
46✔
3592
                        !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
46✔
3593
                        resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) {
47✔
3594

1✔
3595
                err = fmt.Errorf("invalid websocket connection")
1✔
3596
        }
1✔
3597
        // Check compression extension...
3598
        if err == nil && c.ws.compress {
55✔
3599
                // Check that not only permessage-deflate extension is present, but that
9✔
3600
                // we also have server and client no context take over.
9✔
3601
                srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header, false)
9✔
3602

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

29✔
3626
        var preBuf []byte
29✔
3627
        // We have to slurp whatever is in the bufio reader and pass that to the readloop.
29✔
3628
        if n := br.Buffered(); n != 0 {
30✔
3629
                preBuf, _ = br.Peek(n)
1✔
3630
        }
1✔
3631
        return preBuf, 0, nil
29✔
3632
}
3633

3634
const connectProcessTimeout = 2 * time.Second
3635

3636
// This is invoked for remote LEAF remote connections after processing the INFO
3637
// protocol.
3638
func (s *Server) leafNodeResumeConnectProcess(c *client) {
696✔
3639
        clusterName := s.ClusterName()
696✔
3640

696✔
3641
        c.mu.Lock()
696✔
3642
        if c.isClosed() {
696✔
3643
                c.mu.Unlock()
×
3644
                return
×
3645
        }
×
3646
        if err := c.sendLeafConnect(clusterName, c.headers); err != nil {
698✔
3647
                c.mu.Unlock()
2✔
3648
                c.closeConnection(WriteError)
2✔
3649
                return
2✔
3650
        }
2✔
3651

3652
        // Spin up the write loop.
3653
        s.startGoRoutine(func() { c.writeLoop() })
1,388✔
3654

3655
        // timeout leafNodeFinishConnectProcess
3656
        c.ping.tmr = time.AfterFunc(connectProcessTimeout, func() {
694✔
3657
                c.mu.Lock()
×
3658
                // check if leafNodeFinishConnectProcess was called and prevent later leafNodeFinishConnectProcess
×
3659
                if !c.flags.setIfNotSet(connectProcessFinished) {
×
3660
                        c.mu.Unlock()
×
3661
                        return
×
3662
                }
×
3663
                clearTimer(&c.ping.tmr)
×
3664
                closed := c.isClosed()
×
3665
                c.mu.Unlock()
×
3666
                if !closed {
×
3667
                        c.sendErrAndDebug("Stale Leaf Node Connection - Closing")
×
3668
                        c.closeConnection(StaleConnection)
×
3669
                }
×
3670
        })
3671
        c.mu.Unlock()
694✔
3672
        c.Debugf("Remote leafnode connect msg sent")
694✔
3673
}
3674

3675
// This is invoked for remote LEAF connections after processing the INFO
3676
// protocol and leafNodeResumeConnectProcess.
3677
// This will send LS+ the CONNECT protocol and register the leaf node.
3678
func (s *Server) leafNodeFinishConnectProcess(c *client) {
659✔
3679
        c.mu.Lock()
659✔
3680
        if !c.flags.setIfNotSet(connectProcessFinished) {
659✔
3681
                c.mu.Unlock()
×
3682
                return
×
3683
        }
×
3684
        if c.isClosed() {
659✔
3685
                c.mu.Unlock()
×
3686
                s.removeLeafNodeConnection(c)
×
3687
                return
×
3688
        }
×
3689
        remote := c.leaf.remote
659✔
3690
        if remote == nil || c.acc == nil {
660✔
3691
                c.mu.Unlock()
1✔
3692
                c.sendErr("Authorization Violation")
1✔
3693
                c.closeConnection(ProtocolViolation)
1✔
3694
                return
1✔
3695
        }
1✔
3696
        // Check if we will need to send the system connect event.
3697
        remote.RLock()
658✔
3698
        sendSysConnectEvent := remote.Hub
658✔
3699
        remote.RUnlock()
658✔
3700

658✔
3701
        // Capture account before releasing lock
658✔
3702
        acc := c.acc
658✔
3703
        // cancel connectProcessTimeout
658✔
3704
        clearTimer(&c.ping.tmr)
658✔
3705
        c.mu.Unlock()
658✔
3706

658✔
3707
        // Make sure we register with the account here.
658✔
3708
        if err := c.registerWithAccount(acc); err != nil {
660✔
3709
                if err == ErrTooManyAccountConnections {
2✔
3710
                        c.maxAccountConnExceeded()
×
3711
                        return
×
3712
                } else if err == ErrLeafNodeLoop {
4✔
3713
                        c.handleLeafNodeLoop(true)
2✔
3714
                        return
2✔
3715
                }
2✔
3716
                c.Errorf("Registering leaf with account %s resulted in error: %v", acc.Name, err)
×
3717
                c.closeConnection(ProtocolViolation)
×
3718
                return
×
3719
        }
3720
        if !s.addLeafNodeConnection(c, _EMPTY_, _EMPTY_, false) {
656✔
3721
                // Was not added, could be because the remote configuration has been removed.
×
3722
                c.closeConnection(ClientClosed)
×
3723
                return
×
3724
        }
×
3725
        s.initLeafNodeSmapAndSendSubs(c)
656✔
3726
        if sendSysConnectEvent {
674✔
3727
                s.sendLeafNodeConnect(acc)
18✔
3728
        }
18✔
3729
        s.accountConnectEvent(c)
656✔
3730

656✔
3731
        // The above functions are not running under the client lock, so it is
656✔
3732
        // possible that between the time we have started the read/write loops
656✔
3733
        // and now, that the connection was closed. This would leave the closed
656✔
3734
        // LN connection possibly registered with the account and/or the server's
656✔
3735
        // leafs map. So check if connection is closed, and if so, manually cleanup.
656✔
3736
        c.mu.Lock()
656✔
3737
        closed := c.isClosed()
656✔
3738
        if !closed {
1,312✔
3739
                c.setFirstPingTimer()
656✔
3740
        }
656✔
3741
        c.mu.Unlock()
656✔
3742
        if closed {
656✔
3743
                s.removeLeafNodeConnection(c)
×
3744
                if prev := acc.removeClient(c); prev == 1 {
×
3745
                        s.decActiveAccounts()
×
3746
                }
×
3747
        }
3748
}
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