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

nats-io / nats-server / 19658562439

24 Nov 2025 12:55PM UTC coverage: 69.106% (-17.0%) from 86.129%
19658562439

push

github

web-flow
NRG: Don't reset WAL when failing to load last snapshot (#7580)

In most cases we can either install a new snapshot before shutting down,
or if not, we can better detect the situation on the next startup.

ref: #7556

Signed-off-by: Neil Twigg <neil@nats.io>

60221 of 87143 relevant lines covered (69.11%)

271294.87 hits per line

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

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

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

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

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

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

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

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

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

66
        // This is the time the server will wait, when receiving a CONNECT,
67
        // before closing the connection if the required minimum version is not met.
68
        leafNodeWaitBeforeClose = 5 * time.Second
69
)
70

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

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

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

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

131
func (c *client) isHubLeafNode() bool {
9,800✔
132
        return c.kind == LEAF && !c.leaf.isSpoke
9,800✔
133
}
9,800✔
134

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

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

200
func (s *Server) remoteLeafNodeStillValid(remote *leafNodeCfg) bool {
901✔
201
        if remote.Disabled {
901✔
202
                return false
×
203
        }
×
204
        for _, ri := range s.getOpts().LeafNode.Remotes {
1,976✔
205
                // FIXME(dlc) - What about auth changes?
1,075✔
206
                if reflect.DeepEqual(ri.URLs, remote.URLs) {
1,976✔
207
                        return true
901✔
208
                }
901✔
209
        }
210
        return false
×
211
}
212

213
// Ensure that leafnode is properly configured.
214
func validateLeafNode(o *Options) error {
4,642✔
215
        if err := validateLeafNodeAuthOptions(o); err != nil {
4,642✔
216
                return err
×
217
        }
×
218

219
        // Users can bind to any local account, if its empty we will assume the $G account.
220
        for _, r := range o.LeafNode.Remotes {
4,958✔
221
                if r.LocalAccount == _EMPTY_ {
463✔
222
                        r.LocalAccount = globalAccountName
147✔
223
                }
147✔
224
        }
225

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

279
        // Validate compression settings
280
        if o.LeafNode.Compression.Mode != _EMPTY_ {
7,405✔
281
                if err := validateAndNormalizeCompressionOption(&o.LeafNode.Compression, CompressionS2Auto); err != nil {
2,763✔
282
                        return err
×
283
                }
×
284
        }
285

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

293
                if len(rcfg.URLs) >= 2 {
441✔
294
                        firstIsWS, ok := isWSURL(rcfg.URLs[0]), true
125✔
295
                        for i := 1; i < len(rcfg.URLs); i++ {
345✔
296
                                u := rcfg.URLs[i]
220✔
297
                                if isWS := isWSURL(u); isWS && !firstIsWS || !isWS && firstIsWS {
220✔
298
                                        ok = false
×
299
                                        break
×
300
                                }
301
                        }
302
                        if !ok {
125✔
303
                                return fmt.Errorf("remote leaf node configuration cannot have a mix of websocket and non-websocket urls: %q", redactURLList(rcfg.URLs))
×
304
                        }
×
305
                }
306
                // Validate compression settings
307
                if rcfg.Compression.Mode != _EMPTY_ {
632✔
308
                        if err := validateAndNormalizeCompressionOption(&rcfg.Compression, CompressionS2Auto); err != nil {
316✔
309
                                return err
×
310
                        }
×
311
                }
312
        }
313

314
        if o.LeafNode.Port == 0 {
7,109✔
315
                return nil
2,467✔
316
        }
2,467✔
317

318
        // If MinVersion is defined, check that it is valid.
319
        if mv := o.LeafNode.MinVersion; mv != _EMPTY_ {
2,175✔
320
                if err := checkLeafMinVersionConfig(mv); err != nil {
×
321
                        return err
×
322
                }
×
323
        }
324

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

329
        if o.Gateway.Name == _EMPTY_ && o.Gateway.Port == 0 {
4,125✔
330
                return nil
1,950✔
331
        }
1,950✔
332
        // If we are here we have both leaf nodes and gateways defined, make sure there
333
        // is a system account defined.
334
        if o.SystemAccount == _EMPTY_ {
226✔
335
                return fmt.Errorf("leaf nodes and gateways (both being defined) require a system account to also be configured")
1✔
336
        }
1✔
337
        if err := validatePinnedCerts(o.LeafNode.TLSPinnedCerts); err != nil {
224✔
338
                return fmt.Errorf("leafnode: %v", err)
×
339
        }
×
340
        return nil
224✔
341
}
342

343
func checkLeafMinVersionConfig(mv string) error {
2✔
344
        if ok, err := versionAtLeastCheckError(mv, 2, 8, 0); !ok || err != nil {
4✔
345
                if err != nil {
3✔
346
                        return fmt.Errorf("invalid leafnode's minimum version: %v", err)
1✔
347
                } else {
2✔
348
                        return fmt.Errorf("the minimum version should be at least 2.8.0")
1✔
349
                }
1✔
350
        }
351
        return nil
×
352
}
353

354
// Used to validate user names in LeafNode configuration.
355
// - rejects mix of single and multiple users.
356
// - rejects duplicate user names.
357
func validateLeafNodeAuthOptions(o *Options) error {
4,655✔
358
        if len(o.LeafNode.Users) == 0 {
9,300✔
359
                return nil
4,645✔
360
        }
4,645✔
361
        if o.LeafNode.Username != _EMPTY_ {
11✔
362
                return fmt.Errorf("can not have a single user/pass and a users array")
1✔
363
        }
1✔
364
        if o.LeafNode.Nkey != _EMPTY_ {
9✔
365
                return fmt.Errorf("can not have a single nkey and a users array")
×
366
        }
×
367
        users := map[string]struct{}{}
9✔
368
        for _, u := range o.LeafNode.Users {
27✔
369
                if _, exists := users[u.Username]; exists {
19✔
370
                        return fmt.Errorf("duplicate user %q detected in leafnode authorization", u.Username)
1✔
371
                }
1✔
372
                users[u.Username] = struct{}{}
17✔
373
        }
374
        return nil
8✔
375
}
376

377
func validateLeafNodeProxyOptions(remote *RemoteLeafOpts) ([]string, error) {
529✔
378
        var warnings []string
529✔
379

529✔
380
        if remote.Proxy.URL == _EMPTY_ {
1,053✔
381
                return warnings, nil
524✔
382
        }
524✔
383

384
        proxyURL, err := url.Parse(remote.Proxy.URL)
5✔
385
        if err != nil {
5✔
386
                return warnings, fmt.Errorf("invalid proxy URL: %v", err)
×
387
        }
×
388

389
        if proxyURL.Scheme != "http" && proxyURL.Scheme != "https" {
6✔
390
                return warnings, fmt.Errorf("proxy URL scheme must be http or https, got: %s", proxyURL.Scheme)
1✔
391
        }
1✔
392

393
        if proxyURL.Host == _EMPTY_ {
5✔
394
                return warnings, fmt.Errorf("proxy URL must specify a host")
1✔
395
        }
1✔
396

397
        if remote.Proxy.Timeout < 0 {
3✔
398
                return warnings, fmt.Errorf("proxy timeout must be >= 0")
×
399
        }
×
400

401
        if (remote.Proxy.Username == _EMPTY_) != (remote.Proxy.Password == _EMPTY_) {
5✔
402
                return warnings, fmt.Errorf("proxy username and password must both be specified or both be empty")
2✔
403
        }
2✔
404

405
        if len(remote.URLs) > 0 {
2✔
406
                hasWebSocketURL := false
1✔
407
                hasNonWebSocketURL := false
1✔
408

1✔
409
                for _, remoteURL := range remote.URLs {
2✔
410
                        if remoteURL.Scheme == wsSchemePrefix || remoteURL.Scheme == wsSchemePrefixTLS {
2✔
411
                                hasWebSocketURL = true
1✔
412
                                if (remoteURL.Scheme == wsSchemePrefixTLS) &&
1✔
413
                                        remote.TLSConfig == nil && !remote.TLS {
2✔
414
                                        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✔
415
                                }
1✔
416
                        } else {
×
417
                                hasNonWebSocketURL = true
×
418
                        }
×
419
                }
420

421
                if !hasWebSocketURL {
×
422
                        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://)")
×
423
                } else if hasNonWebSocketURL {
×
424
                        warnings = append(warnings, "proxy configuration will only be used for WebSocket URLs: proxy settings do not apply to TCP connections (nats://)")
×
425
                }
×
426
        }
427

428
        return warnings, nil
×
429
}
430

431
// Update remote LeafNode TLS configurations after a config reload.
432
func (s *Server) updateRemoteLeafNodesTLSConfig(opts *Options) {
×
433
        max := len(opts.LeafNode.Remotes)
×
434
        if max == 0 {
×
435
                return
×
436
        }
×
437

438
        s.mu.RLock()
×
439
        defer s.mu.RUnlock()
×
440

×
441
        // Changes in the list of remote leaf nodes is not supported.
×
442
        // However, make sure that we don't go over the arrays.
×
443
        if len(s.leafRemoteCfgs) < max {
×
444
                max = len(s.leafRemoteCfgs)
×
445
        }
×
446
        for i := 0; i < max; i++ {
×
447
                ro := opts.LeafNode.Remotes[i]
×
448
                cfg := s.leafRemoteCfgs[i]
×
449
                if ro.TLSConfig != nil {
×
450
                        cfg.Lock()
×
451
                        cfg.TLSConfig = ro.TLSConfig.Clone()
×
452
                        cfg.TLSHandshakeFirst = ro.TLSHandshakeFirst
×
453
                        cfg.Unlock()
×
454
                }
×
455
        }
456
}
457

458
func (s *Server) reConnectToRemoteLeafNode(remote *leafNodeCfg) {
50✔
459
        delay := s.getOpts().LeafNode.ReconnectInterval
50✔
460
        select {
50✔
461
        case <-time.After(delay):
30✔
462
        case <-s.quitCh:
20✔
463
                s.grWG.Done()
20✔
464
                return
20✔
465
        }
466
        s.connectToRemoteLeafNode(remote, false)
30✔
467
}
468

469
// Creates a leafNodeCfg object that wraps the RemoteLeafOpts.
470
func newLeafNodeCfg(remote *RemoteLeafOpts) *leafNodeCfg {
316✔
471
        cfg := &leafNodeCfg{
316✔
472
                RemoteLeafOpts: remote,
316✔
473
                urls:           make([]*url.URL, 0, len(remote.URLs)),
316✔
474
        }
316✔
475
        if len(remote.DenyExports) > 0 || len(remote.DenyImports) > 0 {
317✔
476
                perms := &Permissions{}
1✔
477
                if len(remote.DenyExports) > 0 {
2✔
478
                        perms.Publish = &SubjectPermission{Deny: remote.DenyExports}
1✔
479
                }
1✔
480
                if len(remote.DenyImports) > 0 {
2✔
481
                        perms.Subscribe = &SubjectPermission{Deny: remote.DenyImports}
1✔
482
                }
1✔
483
                cfg.perms = perms
1✔
484
        }
485
        // Start with the one that is configured. We will add to this
486
        // array when receiving async leafnode INFOs.
487
        cfg.urls = append(cfg.urls, cfg.URLs...)
316✔
488
        // If allowed to randomize, do it on our copy of URLs
316✔
489
        if !remote.NoRandomize {
632✔
490
                rand.Shuffle(len(cfg.urls), func(i, j int) {
536✔
491
                        cfg.urls[i], cfg.urls[j] = cfg.urls[j], cfg.urls[i]
220✔
492
                })
220✔
493
        }
494
        // If we are TLS make sure we save off a proper servername if possible.
495
        // Do same for user/password since we may need them to connect to
496
        // a bare URL that we get from INFO protocol.
497
        for _, u := range cfg.urls {
852✔
498
                cfg.saveTLSHostname(u)
536✔
499
                cfg.saveUserPassword(u)
536✔
500
                // If the url(s) have the "wss://" scheme, and we don't have a TLS
536✔
501
                // config, mark that we should be using TLS anyway.
536✔
502
                if !cfg.TLS && isWSSURL(u) {
536✔
503
                        cfg.TLS = true
×
504
                }
×
505
        }
506
        return cfg
316✔
507
}
508

509
// Will pick an URL from the list of available URLs.
510
func (cfg *leafNodeCfg) pickNextURL() *url.URL {
650✔
511
        cfg.Lock()
650✔
512
        defer cfg.Unlock()
650✔
513
        // If the current URL is the first in the list and we have more than
650✔
514
        // one URL, then move that one to end of the list.
650✔
515
        if cfg.curURL != nil && len(cfg.urls) > 1 && urlsAreEqual(cfg.curURL, cfg.urls[0]) {
746✔
516
                first := cfg.urls[0]
96✔
517
                copy(cfg.urls, cfg.urls[1:])
96✔
518
                cfg.urls[len(cfg.urls)-1] = first
96✔
519
        }
96✔
520
        cfg.curURL = cfg.urls[0]
650✔
521
        return cfg.curURL
650✔
522
}
523

524
// Returns the current URL
525
func (cfg *leafNodeCfg) getCurrentURL() *url.URL {
24✔
526
        cfg.RLock()
24✔
527
        defer cfg.RUnlock()
24✔
528
        return cfg.curURL
24✔
529
}
24✔
530

531
// Returns how long the server should wait before attempting
532
// to solicit a remote leafnode connection.
533
func (cfg *leafNodeCfg) getConnectDelay() time.Duration {
346✔
534
        cfg.RLock()
346✔
535
        delay := cfg.connDelay
346✔
536
        cfg.RUnlock()
346✔
537
        return delay
346✔
538
}
346✔
539

540
// Sets the connect delay.
541
func (cfg *leafNodeCfg) setConnectDelay(delay time.Duration) {
86✔
542
        cfg.Lock()
86✔
543
        cfg.connDelay = delay
86✔
544
        cfg.Unlock()
86✔
545
}
86✔
546

547
// Ensure that non-exported options (used in tests) have
548
// been properly set.
549
func (s *Server) setLeafNodeNonExportedOptions() {
3,544✔
550
        opts := s.getOpts()
3,544✔
551
        s.leafNodeOpts.dialTimeout = opts.LeafNode.dialTimeout
3,544✔
552
        if s.leafNodeOpts.dialTimeout == 0 {
7,088✔
553
                // Use same timeouts as routes for now.
3,544✔
554
                s.leafNodeOpts.dialTimeout = DEFAULT_ROUTE_DIAL
3,544✔
555
        }
3,544✔
556
        s.leafNodeOpts.resolver = opts.LeafNode.resolver
3,544✔
557
        if s.leafNodeOpts.resolver == nil {
7,088✔
558
                s.leafNodeOpts.resolver = net.DefaultResolver
3,544✔
559
        }
3,544✔
560
}
561

562
const sharedSysAccDelay = 250 * time.Millisecond
563

564
// establishHTTPProxyTunnel establishes an HTTP CONNECT tunnel through a proxy server
565
func establishHTTPProxyTunnel(proxyURL, targetHost string, timeout time.Duration, username, password string) (net.Conn, error) {
×
566
        proxyAddr, err := url.Parse(proxyURL)
×
567
        if err != nil {
×
568
                // This should not happen since proxy URL is validated during configuration parsing
×
569
                return nil, fmt.Errorf("unexpected proxy URL parse error (URL was pre-validated): %v", err)
×
570
        }
×
571

572
        // Connect to the proxy server
573
        conn, err := natsDialTimeout("tcp", proxyAddr.Host, timeout)
×
574
        if err != nil {
×
575
                return nil, fmt.Errorf("failed to connect to proxy: %v", err)
×
576
        }
×
577

578
        // Set deadline for the entire proxy handshake
579
        if err := conn.SetDeadline(time.Now().Add(timeout)); err != nil {
×
580
                conn.Close()
×
581
                return nil, fmt.Errorf("failed to set deadline: %v", err)
×
582
        }
×
583

584
        req := &http.Request{
×
585
                Method: http.MethodConnect,
×
586
                URL:    &url.URL{Opaque: targetHost}, // Opaque is required for CONNECT
×
587
                Host:   targetHost,
×
588
                Header: make(http.Header),
×
589
        }
×
590

×
591
        // Add proxy authentication if provided
×
592
        if username != "" && password != "" {
×
593
                req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password)))
×
594
        }
×
595

596
        if err := req.Write(conn); err != nil {
×
597
                conn.Close()
×
598
                return nil, fmt.Errorf("failed to write CONNECT request: %v", err)
×
599
        }
×
600

601
        resp, err := http.ReadResponse(bufio.NewReader(conn), req)
×
602
        if err != nil {
×
603
                conn.Close()
×
604
                return nil, fmt.Errorf("failed to read proxy response: %v", err)
×
605
        }
×
606

607
        if resp.StatusCode != http.StatusOK {
×
608
                resp.Body.Close()
×
609
                conn.Close()
×
610
                return nil, fmt.Errorf("proxy CONNECT failed: %s", resp.Status)
×
611
        }
×
612

613
        // Close the response body
614
        resp.Body.Close()
×
615

×
616
        // Clear the deadline now that we've finished the proxy handshake
×
617
        if err := conn.SetDeadline(time.Time{}); err != nil {
×
618
                conn.Close()
×
619
                return nil, fmt.Errorf("failed to clear deadline: %v", err)
×
620
        }
×
621

622
        return conn, nil
×
623
}
624

625
func (s *Server) connectToRemoteLeafNode(remote *leafNodeCfg, firstConnect bool) {
346✔
626
        defer s.grWG.Done()
346✔
627

346✔
628
        if remote == nil || len(remote.URLs) == 0 {
346✔
629
                s.Debugf("Empty remote leafnode definition, nothing to connect")
×
630
                return
×
631
        }
×
632

633
        opts := s.getOpts()
346✔
634
        reconnectDelay := opts.LeafNode.ReconnectInterval
346✔
635
        s.mu.RLock()
346✔
636
        dialTimeout := s.leafNodeOpts.dialTimeout
346✔
637
        resolver := s.leafNodeOpts.resolver
346✔
638
        var isSysAcc bool
346✔
639
        if s.eventsEnabled() {
665✔
640
                isSysAcc = remote.LocalAccount == s.sys.account.Name
319✔
641
        }
319✔
642
        jetstreamMigrateDelay := remote.JetStreamClusterMigrateDelay
346✔
643
        s.mu.RUnlock()
346✔
644

346✔
645
        // If we are sharing a system account and we are not standalone delay to gather some info prior.
346✔
646
        if firstConnect && isSysAcc && !s.standAloneMode() {
390✔
647
                s.Debugf("Will delay first leafnode connect to shared system account due to clustering")
44✔
648
                remote.setConnectDelay(sharedSysAccDelay)
44✔
649
        }
44✔
650

651
        if connDelay := remote.getConnectDelay(); connDelay > 0 {
390✔
652
                select {
44✔
653
                case <-time.After(connDelay):
39✔
654
                case <-s.quitCh:
5✔
655
                        return
5✔
656
                }
657
                remote.setConnectDelay(0)
39✔
658
        }
659

660
        var conn net.Conn
341✔
661

341✔
662
        const connErrFmt = "Error trying to connect as leafnode to remote server %q (attempt %v): %v"
341✔
663

341✔
664
        // Capture proxy configuration once before the loop with proper locking
341✔
665
        remote.RLock()
341✔
666
        proxyURL := remote.Proxy.URL
341✔
667
        proxyUsername := remote.Proxy.Username
341✔
668
        proxyPassword := remote.Proxy.Password
341✔
669
        proxyTimeout := remote.Proxy.Timeout
341✔
670
        remote.RUnlock()
341✔
671

341✔
672
        // Set default proxy timeout if not specified
341✔
673
        if proxyTimeout == 0 {
682✔
674
                proxyTimeout = dialTimeout
341✔
675
        }
341✔
676

677
        attempts := 0
341✔
678

341✔
679
        for s.isRunning() && s.remoteLeafNodeStillValid(remote) {
991✔
680
                rURL := remote.pickNextURL()
650✔
681
                url, err := s.getRandomIP(resolver, rURL.Host, nil)
650✔
682
                if err == nil {
1,297✔
683
                        var ipStr string
647✔
684
                        if url != rURL.Host {
649✔
685
                                ipStr = fmt.Sprintf(" (%s)", url)
2✔
686
                        }
2✔
687
                        // Some test may want to disable remotes from connecting
688
                        if s.isLeafConnectDisabled() {
734✔
689
                                s.Debugf("Will not attempt to connect to remote server on %q%s, leafnodes currently disabled", rURL.Host, ipStr)
87✔
690
                                err = ErrLeafNodeDisabled
87✔
691
                        } else {
647✔
692
                                s.Debugf("Trying to connect as leafnode to remote server on %q%s", rURL.Host, ipStr)
560✔
693

560✔
694
                                // Check if proxy is configured first, then check if URL supports it
560✔
695
                                if proxyURL != _EMPTY_ && isWSURL(rURL) {
560✔
696
                                        // Use proxy for WebSocket connections - use original hostname, resolved IP for connection
×
697
                                        targetHost := rURL.Host
×
698
                                        // If URL doesn't include port, add the default port for the scheme
×
699
                                        if rURL.Port() == _EMPTY_ {
×
700
                                                defaultPort := "80"
×
701
                                                if rURL.Scheme == wsSchemePrefixTLS {
×
702
                                                        defaultPort = "443"
×
703
                                                }
×
704
                                                targetHost = net.JoinHostPort(rURL.Hostname(), defaultPort)
×
705
                                        }
706

707
                                        conn, err = establishHTTPProxyTunnel(proxyURL, targetHost, proxyTimeout, proxyUsername, proxyPassword)
×
708
                                } else {
560✔
709
                                        // Direct connection
560✔
710
                                        conn, err = natsDialTimeout("tcp", url, dialTimeout)
560✔
711
                                }
560✔
712
                        }
713
                }
714
                if err != nil {
1,049✔
715
                        jitter := time.Duration(rand.Int63n(int64(reconnectDelay)))
399✔
716
                        delay := reconnectDelay + jitter
399✔
717
                        attempts++
399✔
718
                        if s.shouldReportConnectErr(firstConnect, attempts) {
577✔
719
                                s.Errorf(connErrFmt, rURL.Host, attempts, err)
178✔
720
                        } else {
399✔
721
                                s.Debugf(connErrFmt, rURL.Host, attempts, err)
221✔
722
                        }
221✔
723
                        remote.Lock()
399✔
724
                        // if we are using a delay to start migrating assets, kick off a migrate timer.
399✔
725
                        if remote.jsMigrateTimer == nil && jetstreamMigrateDelay > 0 {
401✔
726
                                remote.jsMigrateTimer = time.AfterFunc(jetstreamMigrateDelay, func() {
4✔
727
                                        s.checkJetStreamMigrate(remote)
2✔
728
                                })
2✔
729
                        }
730
                        remote.Unlock()
399✔
731
                        select {
399✔
732
                        case <-s.quitCh:
90✔
733
                                remote.cancelMigrateTimer()
90✔
734
                                return
90✔
735
                        case <-time.After(delay):
309✔
736
                                // Check if we should migrate any JetStream assets immediately while this remote is down.
309✔
737
                                // This will be used if JetStreamClusterMigrateDelay was not set
309✔
738
                                if jetstreamMigrateDelay == 0 {
570✔
739
                                        s.checkJetStreamMigrate(remote)
261✔
740
                                }
261✔
741
                                continue
309✔
742
                        }
743
                }
744
                remote.cancelMigrateTimer()
251✔
745
                if !s.remoteLeafNodeStillValid(remote) {
251✔
746
                        conn.Close()
×
747
                        return
×
748
                }
×
749

750
                // We have a connection here to a remote server.
751
                // Go ahead and create our leaf node and return.
752
                s.createLeafNode(conn, rURL, remote, nil)
251✔
753

251✔
754
                // Clear any observer states if we had them.
251✔
755
                s.clearObserverState(remote)
251✔
756

251✔
757
                return
251✔
758
        }
759
}
760

761
func (cfg *leafNodeCfg) cancelMigrateTimer() {
341✔
762
        cfg.Lock()
341✔
763
        stopAndClearTimer(&cfg.jsMigrateTimer)
341✔
764
        cfg.Unlock()
341✔
765
}
341✔
766

767
// This will clear any observer state such that stream or consumer assets on this server can become leaders again.
768
func (s *Server) clearObserverState(remote *leafNodeCfg) {
251✔
769
        s.mu.RLock()
251✔
770
        accName := remote.LocalAccount
251✔
771
        s.mu.RUnlock()
251✔
772

251✔
773
        acc, err := s.LookupAccount(accName)
251✔
774
        if err != nil {
251✔
775
                s.Warnf("Error looking up account [%s] checking for JetStream clear observer state on a leafnode", accName)
×
776
                return
×
777
        }
×
778

779
        acc.jscmMu.Lock()
251✔
780
        defer acc.jscmMu.Unlock()
251✔
781

251✔
782
        // Walk all streams looking for any clustered stream, skip otherwise.
251✔
783
        for _, mset := range acc.streams() {
256✔
784
                node := mset.raftNode()
5✔
785
                if node == nil {
8✔
786
                        // Not R>1
3✔
787
                        continue
3✔
788
                }
789
                // Check consumers
790
                for _, o := range mset.getConsumers() {
4✔
791
                        if n := o.raftNode(); n != nil {
4✔
792
                                // Ensure we can become a leader again.
2✔
793
                                n.SetObserver(false)
2✔
794
                        }
2✔
795
                }
796
                // Ensure we can not become a leader again.
797
                node.SetObserver(false)
2✔
798
        }
799
}
800

801
// Check to see if we should migrate any assets from this account.
802
func (s *Server) checkJetStreamMigrate(remote *leafNodeCfg) {
263✔
803
        s.mu.RLock()
263✔
804
        accName, shouldMigrate := remote.LocalAccount, remote.JetStreamClusterMigrate
263✔
805
        s.mu.RUnlock()
263✔
806

263✔
807
        if !shouldMigrate {
485✔
808
                return
222✔
809
        }
222✔
810

811
        acc, err := s.LookupAccount(accName)
41✔
812
        if err != nil {
41✔
813
                s.Warnf("Error looking up account [%s] checking for JetStream migration on a leafnode", accName)
×
814
                return
×
815
        }
×
816

817
        acc.jscmMu.Lock()
41✔
818
        defer acc.jscmMu.Unlock()
41✔
819

41✔
820
        // Walk all streams looking for any clustered stream, skip otherwise.
41✔
821
        // If we are the leader force stepdown.
41✔
822
        for _, mset := range acc.streams() {
61✔
823
                node := mset.raftNode()
20✔
824
                if node == nil {
20✔
825
                        // Not R>1
×
826
                        continue
×
827
                }
828
                // Collect any consumers
829
                for _, o := range mset.getConsumers() {
40✔
830
                        if n := o.raftNode(); n != nil {
40✔
831
                                n.StepDown()
20✔
832
                                // Ensure we can not become a leader while in this state.
20✔
833
                                n.SetObserver(true)
20✔
834
                        }
20✔
835
                }
836
                // Stepdown if this stream was leader.
837
                node.StepDown()
20✔
838
                // Ensure we can not become a leader while in this state.
20✔
839
                node.SetObserver(true)
20✔
840
        }
841
}
842

843
// Helper for checking.
844
func (s *Server) isLeafConnectDisabled() bool {
647✔
845
        s.mu.RLock()
647✔
846
        defer s.mu.RUnlock()
647✔
847
        return s.leafDisableConnect
647✔
848
}
647✔
849

850
// Save off the tlsName for when we use TLS and mix hostnames and IPs. IPs usually
851
// come from the server we connect to.
852
//
853
// We used to save the name only if there was a TLSConfig or scheme equal to "tls".
854
// However, this was causing failures for users that did not set the scheme (and
855
// their remote connections did not have a tls{} block).
856
// We now save the host name regardless in case the remote returns an INFO indicating
857
// that TLS is required.
858
func (cfg *leafNodeCfg) saveTLSHostname(u *url.URL) {
691✔
859
        if cfg.tlsName == _EMPTY_ && net.ParseIP(u.Hostname()) == nil {
696✔
860
                cfg.tlsName = u.Hostname()
5✔
861
        }
5✔
862
}
863

864
// Save off the username/password for when we connect using a bare URL
865
// that we get from the INFO protocol.
866
func (cfg *leafNodeCfg) saveUserPassword(u *url.URL) {
536✔
867
        if cfg.username == _EMPTY_ && u.User != nil {
638✔
868
                cfg.username = u.User.Username()
102✔
869
                cfg.password, _ = u.User.Password()
102✔
870
        }
102✔
871
}
872

873
// This starts the leafnode accept loop in a go routine, unless it
874
// is detected that the server has already been shutdown.
875
func (s *Server) startLeafNodeAcceptLoop() {
2,168✔
876
        // Snapshot server options.
2,168✔
877
        opts := s.getOpts()
2,168✔
878

2,168✔
879
        port := opts.LeafNode.Port
2,168✔
880
        if port == -1 {
4,289✔
881
                port = 0
2,121✔
882
        }
2,121✔
883

884
        if s.isShuttingDown() {
2,168✔
885
                return
×
886
        }
×
887

888
        s.mu.Lock()
2,168✔
889
        hp := net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(port))
2,168✔
890
        l, e := natsListen("tcp", hp)
2,168✔
891
        s.leafNodeListenerErr = e
2,168✔
892
        if e != nil {
2,168✔
893
                s.mu.Unlock()
×
894
                s.Fatalf("Error listening on leafnode port: %d - %v", opts.LeafNode.Port, e)
×
895
                return
×
896
        }
×
897

898
        s.Noticef("Listening for leafnode connections on %s",
2,168✔
899
                net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
2,168✔
900

2,168✔
901
        tlsRequired := opts.LeafNode.TLSConfig != nil
2,168✔
902
        tlsVerify := tlsRequired && opts.LeafNode.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert
2,168✔
903
        // Do not set compression in this Info object, it would possibly cause
2,168✔
904
        // issues when sending asynchronous INFO to the remote.
2,168✔
905
        info := Info{
2,168✔
906
                ID:            s.info.ID,
2,168✔
907
                Name:          s.info.Name,
2,168✔
908
                Version:       s.info.Version,
2,168✔
909
                GitCommit:     gitCommit,
2,168✔
910
                GoVersion:     runtime.Version(),
2,168✔
911
                AuthRequired:  true,
2,168✔
912
                TLSRequired:   tlsRequired,
2,168✔
913
                TLSVerify:     tlsVerify,
2,168✔
914
                MaxPayload:    s.info.MaxPayload, // TODO(dlc) - Allow override?
2,168✔
915
                Headers:       s.supportsHeaders(),
2,168✔
916
                JetStream:     opts.JetStream,
2,168✔
917
                Domain:        opts.JetStreamDomain,
2,168✔
918
                Proto:         s.getServerProto(),
2,168✔
919
                InfoOnConnect: true,
2,168✔
920
                JSApiLevel:    JSApiLevel,
2,168✔
921
        }
2,168✔
922
        // If we have selected a random port...
2,168✔
923
        if port == 0 {
4,289✔
924
                // Write resolved port back to options.
2,121✔
925
                opts.LeafNode.Port = l.Addr().(*net.TCPAddr).Port
2,121✔
926
        }
2,121✔
927

928
        s.leafNodeInfo = info
2,168✔
929
        // Possibly override Host/Port and set IP based on Cluster.Advertise
2,168✔
930
        if err := s.setLeafNodeInfoHostPortAndIP(); err != nil {
2,168✔
931
                s.Fatalf("Error setting leafnode INFO with LeafNode.Advertise value of %s, err=%v", opts.LeafNode.Advertise, err)
×
932
                l.Close()
×
933
                s.mu.Unlock()
×
934
                return
×
935
        }
×
936
        s.leafURLsMap[s.leafNodeInfo.IP]++
2,168✔
937
        s.generateLeafNodeInfoJSON()
2,168✔
938

2,168✔
939
        // Setup state that can enable shutdown
2,168✔
940
        s.leafNodeListener = l
2,168✔
941

2,168✔
942
        // As of now, a server that does not have remotes configured would
2,168✔
943
        // never solicit a connection, so we should not have to warn if
2,168✔
944
        // InsecureSkipVerify is set in main LeafNodes config (since
2,168✔
945
        // this TLS setting matters only when soliciting a connection).
2,168✔
946
        // Still, warn if insecure is set in any of LeafNode block.
2,168✔
947
        // We need to check remotes, even if tls is not required on accept.
2,168✔
948
        warn := tlsRequired && opts.LeafNode.TLSConfig.InsecureSkipVerify
2,168✔
949
        if !warn {
4,336✔
950
                for _, r := range opts.LeafNode.Remotes {
2,212✔
951
                        if r.TLSConfig != nil && r.TLSConfig.InsecureSkipVerify {
44✔
952
                                warn = true
×
953
                                break
×
954
                        }
955
                }
956
        }
957
        if warn {
2,168✔
958
                s.Warnf(leafnodeTLSInsecureWarning)
×
959
        }
×
960
        go s.acceptConnections(l, "Leafnode", func(conn net.Conn) { s.createLeafNode(conn, nil, nil, nil) }, nil)
2,549✔
961
        s.mu.Unlock()
2,168✔
962
}
963

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

967
// clusterName is provided as argument to avoid lock ordering issues with the locked client c
968
// Lock should be held entering here.
969
func (c *client) sendLeafConnect(clusterName string, headers bool) error {
244✔
970
        // We support basic user/pass and operator based user JWT with signatures.
244✔
971
        cinfo := leafConnectInfo{
244✔
972
                Version:       VERSION,
244✔
973
                ID:            c.srv.info.ID,
244✔
974
                Domain:        c.srv.info.Domain,
244✔
975
                Name:          c.srv.info.Name,
244✔
976
                Hub:           c.leaf.remote.Hub,
244✔
977
                Cluster:       clusterName,
244✔
978
                Headers:       headers,
244✔
979
                JetStream:     c.acc.jetStreamConfigured(),
244✔
980
                DenyPub:       c.leaf.remote.DenyImports,
244✔
981
                Compression:   c.leaf.compression,
244✔
982
                RemoteAccount: c.acc.GetName(),
244✔
983
                Proto:         c.srv.getServerProto(),
244✔
984
                Isolate:       c.leaf.remote.RequestIsolation,
244✔
985
        }
244✔
986

244✔
987
        // If a signature callback is specified, this takes precedence over anything else.
244✔
988
        if cb := c.leaf.remote.SignatureCB; cb != nil {
246✔
989
                nonce := c.nonce
2✔
990
                c.mu.Unlock()
2✔
991
                jwt, sigraw, err := cb(nonce)
2✔
992
                c.mu.Lock()
2✔
993
                if err == nil && c.isClosed() {
2✔
994
                        err = ErrConnectionClosed
×
995
                }
×
996
                if err != nil {
2✔
997
                        c.Errorf("Error signing the nonce: %v", err)
×
998
                        return err
×
999
                }
×
1000
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
2✔
1001
                cinfo.JWT, cinfo.Sig = jwt, sig
2✔
1002

1003
        } else if creds := c.leaf.remote.Credentials; creds != _EMPTY_ {
274✔
1004
                // Check for credentials first, that will take precedence..
32✔
1005
                c.Debugf("Authenticating with credentials file %q", c.leaf.remote.Credentials)
32✔
1006
                contents, err := os.ReadFile(creds)
32✔
1007
                if err != nil {
32✔
1008
                        c.Errorf("%v", err)
×
1009
                        return err
×
1010
                }
×
1011
                defer wipeSlice(contents)
32✔
1012
                items := credsRe.FindAllSubmatch(contents, -1)
32✔
1013
                if len(items) < 2 {
32✔
1014
                        c.Errorf("Credentials file malformed")
×
1015
                        return err
×
1016
                }
×
1017
                // First result should be the user JWT.
1018
                // We copy here so that the file containing the seed will be wiped appropriately.
1019
                raw := items[0][1]
32✔
1020
                tmp := make([]byte, len(raw))
32✔
1021
                copy(tmp, raw)
32✔
1022
                // Seed is second item.
32✔
1023
                kp, err := nkeys.FromSeed(items[1][1])
32✔
1024
                if err != nil {
32✔
1025
                        c.Errorf("Credentials file has malformed seed")
×
1026
                        return err
×
1027
                }
×
1028
                // Wipe our key on exit.
1029
                defer kp.Wipe()
32✔
1030

32✔
1031
                sigraw, _ := kp.Sign(c.nonce)
32✔
1032
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
32✔
1033
                cinfo.JWT = bytesToString(tmp)
32✔
1034
                cinfo.Sig = sig
32✔
1035
        } else if nkey := c.leaf.remote.Nkey; nkey != _EMPTY_ {
213✔
1036
                kp, err := nkeys.FromSeed([]byte(nkey))
3✔
1037
                if err != nil {
3✔
1038
                        c.Errorf("Remote nkey has malformed seed")
×
1039
                        return err
×
1040
                }
×
1041
                // Wipe our key on exit.
1042
                defer kp.Wipe()
3✔
1043
                sigraw, _ := kp.Sign(c.nonce)
3✔
1044
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
3✔
1045
                pkey, _ := kp.PublicKey()
3✔
1046
                cinfo.Nkey = pkey
3✔
1047
                cinfo.Sig = sig
3✔
1048
        }
1049
        // In addition, and this is to allow auth callout, set user/password or
1050
        // token if applicable.
1051
        if userInfo := c.leaf.remote.curURL.User; userInfo != nil {
346✔
1052
                cinfo.User = userInfo.Username()
102✔
1053
                var ok bool
102✔
1054
                cinfo.Pass, ok = userInfo.Password()
102✔
1055
                // For backward compatibility, if only username is provided, set both
102✔
1056
                // Token and User, not just Token.
102✔
1057
                if !ok {
106✔
1058
                        cinfo.Token = cinfo.User
4✔
1059
                }
4✔
1060
        } else if c.leaf.remote.username != _EMPTY_ {
144✔
1061
                cinfo.User = c.leaf.remote.username
2✔
1062
                cinfo.Pass = c.leaf.remote.password
2✔
1063
                // For backward compatibility, if only username is provided, set both
2✔
1064
                // Token and User, not just Token.
2✔
1065
                if cinfo.Pass == _EMPTY_ {
2✔
1066
                        cinfo.Token = cinfo.User
×
1067
                }
×
1068
        }
1069
        b, err := json.Marshal(cinfo)
244✔
1070
        if err != nil {
244✔
1071
                c.Errorf("Error marshaling CONNECT to remote leafnode: %v\n", err)
×
1072
                return err
×
1073
        }
×
1074
        // Although this call is made before the writeLoop is created,
1075
        // we don't really need to send in place. The protocol will be
1076
        // sent out by the writeLoop.
1077
        c.enqueueProto([]byte(fmt.Sprintf(ConProto, b)))
244✔
1078
        return nil
244✔
1079
}
1080

1081
// Makes a deep copy of the LeafNode Info structure.
1082
// The server lock is held on entry.
1083
func (s *Server) copyLeafNodeInfo() *Info {
953✔
1084
        clone := s.leafNodeInfo
953✔
1085
        // Copy the array of urls.
953✔
1086
        if len(s.leafNodeInfo.LeafNodeURLs) > 0 {
1,764✔
1087
                clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...)
811✔
1088
        }
811✔
1089
        return &clone
953✔
1090
}
1091

1092
// Adds a LeafNode URL that we get when a route connects to the Info structure.
1093
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
1094
// Returns a boolean indicating if the URL was added or not.
1095
// Server lock is held on entry
1096
func (s *Server) addLeafNodeURL(urlStr string) bool {
4,910✔
1097
        if s.leafURLsMap.addUrl(urlStr) {
9,815✔
1098
                s.generateLeafNodeInfoJSON()
4,905✔
1099
                return true
4,905✔
1100
        }
4,905✔
1101
        return false
5✔
1102
}
1103

1104
// Removes a LeafNode URL of the route that is disconnecting from the Info structure.
1105
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
1106
// Returns a boolean indicating if the URL was removed or not.
1107
// Server lock is held on entry.
1108
func (s *Server) removeLeafNodeURL(urlStr string) bool {
4,904✔
1109
        // Don't need to do this if we are removing the route connection because
4,904✔
1110
        // we are shuting down...
4,904✔
1111
        if s.isShuttingDown() {
7,474✔
1112
                return false
2,570✔
1113
        }
2,570✔
1114
        if s.leafURLsMap.removeUrl(urlStr) {
4,664✔
1115
                s.generateLeafNodeInfoJSON()
2,330✔
1116
                return true
2,330✔
1117
        }
2,330✔
1118
        return false
4✔
1119
}
1120

1121
// Server lock is held on entry
1122
func (s *Server) generateLeafNodeInfoJSON() {
9,403✔
1123
        s.leafNodeInfo.Cluster = s.cachedClusterName()
9,403✔
1124
        s.leafNodeInfo.LeafNodeURLs = s.leafURLsMap.getAsStringSlice()
9,403✔
1125
        s.leafNodeInfo.WSConnectURLs = s.websocket.connectURLsMap.getAsStringSlice()
9,403✔
1126
        s.leafNodeInfoJSON = generateInfoJSON(&s.leafNodeInfo)
9,403✔
1127
}
9,403✔
1128

1129
// Sends an async INFO protocol so that the connected servers can update
1130
// their list of LeafNode urls.
1131
func (s *Server) sendAsyncLeafNodeInfo() {
7,235✔
1132
        for _, c := range s.leafs {
7,274✔
1133
                c.mu.Lock()
39✔
1134
                c.enqueueProto(s.leafNodeInfoJSON)
39✔
1135
                c.mu.Unlock()
39✔
1136
        }
39✔
1137
}
1138

1139
// Called when an inbound leafnode connection is accepted or we create one for a solicited leafnode.
1140
func (s *Server) createLeafNode(conn net.Conn, rURL *url.URL, remote *leafNodeCfg, ws *websocket) *client {
632✔
1141
        // Snapshot server options.
632✔
1142
        opts := s.getOpts()
632✔
1143

632✔
1144
        maxPay := int32(opts.MaxPayload)
632✔
1145
        maxSubs := int32(opts.MaxSubs)
632✔
1146
        // For system, maxSubs of 0 means unlimited, so re-adjust here.
632✔
1147
        if maxSubs == 0 {
1,263✔
1148
                maxSubs = -1
631✔
1149
        }
631✔
1150
        now := time.Now().UTC()
632✔
1151

632✔
1152
        c := &client{srv: s, nc: conn, kind: LEAF, opts: defaultOpts, mpay: maxPay, msubs: maxSubs, start: now, last: now}
632✔
1153
        // Do not update the smap here, we need to do it in initLeafNodeSmapAndSendSubs
632✔
1154
        c.leaf = &leaf{}
632✔
1155

632✔
1156
        // If the leafnode subject interest should be isolated, flag it here.
632✔
1157
        s.optsMu.RLock()
632✔
1158
        if c.leaf.isolated = s.opts.LeafNode.IsolateLeafnodeInterest; !c.leaf.isolated && remote != nil {
883✔
1159
                c.leaf.isolated = remote.LocalIsolation
251✔
1160
        }
251✔
1161
        s.optsMu.RUnlock()
632✔
1162

632✔
1163
        // For accepted LN connections, ws will be != nil if it was accepted
632✔
1164
        // through the Websocket port.
632✔
1165
        c.ws = ws
632✔
1166

632✔
1167
        // For remote, check if the scheme starts with "ws", if so, we will initiate
632✔
1168
        // a remote Leaf Node connection as a websocket connection.
632✔
1169
        if remote != nil && rURL != nil && isWSURL(rURL) {
632✔
1170
                remote.RLock()
×
1171
                c.ws = &websocket{compress: remote.Websocket.Compression, maskwrite: !remote.Websocket.NoMasking}
×
1172
                remote.RUnlock()
×
1173
        }
×
1174

1175
        // Determines if we are soliciting the connection or not.
1176
        var solicited bool
632✔
1177
        var acc *Account
632✔
1178
        var remoteSuffix string
632✔
1179
        if remote != nil {
883✔
1180
                // For now, if lookup fails, we will constantly try
251✔
1181
                // to recreate this LN connection.
251✔
1182
                lacc := remote.LocalAccount
251✔
1183
                var err error
251✔
1184
                acc, err = s.LookupAccount(lacc)
251✔
1185
                if err != nil {
251✔
1186
                        // An account not existing is something that can happen with nats/http account resolver and the account
×
1187
                        // has not yet been pushed, or the request failed for other reasons.
×
1188
                        // remote needs to be set or retry won't happen
×
1189
                        c.leaf.remote = remote
×
1190
                        c.closeConnection(MissingAccount)
×
1191
                        s.Errorf("Unable to lookup account %s for solicited leafnode connection: %v", lacc, err)
×
1192
                        return nil
×
1193
                }
×
1194
                remoteSuffix = fmt.Sprintf(" for account: %s", acc.traceLabel())
251✔
1195
        }
1196

1197
        c.mu.Lock()
632✔
1198
        c.initClient()
632✔
1199
        c.Noticef("Leafnode connection created%s %s", remoteSuffix, c.opts.Name)
632✔
1200

632✔
1201
        var (
632✔
1202
                tlsFirst         bool
632✔
1203
                tlsFirstFallback time.Duration
632✔
1204
                infoTimeout      time.Duration
632✔
1205
        )
632✔
1206
        if remote != nil {
883✔
1207
                solicited = true
251✔
1208
                remote.Lock()
251✔
1209
                c.leaf.remote = remote
251✔
1210
                c.setPermissions(remote.perms)
251✔
1211
                if !c.leaf.remote.Hub {
502✔
1212
                        c.leaf.isSpoke = true
251✔
1213
                }
251✔
1214
                tlsFirst = remote.TLSHandshakeFirst
251✔
1215
                infoTimeout = remote.FirstInfoTimeout
251✔
1216
                remote.Unlock()
251✔
1217
                c.acc = acc
251✔
1218
        } else {
381✔
1219
                c.flags.set(expectConnect)
381✔
1220
                if ws != nil {
381✔
1221
                        c.Debugf("Leafnode compression=%v", c.ws.compress)
×
1222
                }
×
1223
                tlsFirst = opts.LeafNode.TLSHandshakeFirst
381✔
1224
                if f := opts.LeafNode.TLSHandshakeFirstFallback; f > 0 {
381✔
1225
                        tlsFirstFallback = f
×
1226
                }
×
1227
        }
1228
        c.mu.Unlock()
632✔
1229

632✔
1230
        var nonce [nonceLen]byte
632✔
1231
        var info *Info
632✔
1232

632✔
1233
        // Grab this before the client lock below.
632✔
1234
        if !solicited {
1,013✔
1235
                // Grab server variables
381✔
1236
                s.mu.Lock()
381✔
1237
                info = s.copyLeafNodeInfo()
381✔
1238
                // For tests that want to simulate old servers, do not set the compression
381✔
1239
                // on the INFO protocol if configured with CompressionNotSupported.
381✔
1240
                if cm := opts.LeafNode.Compression.Mode; cm != CompressionNotSupported {
762✔
1241
                        info.Compression = cm
381✔
1242
                }
381✔
1243
                // We always send a nonce for LEAF connections. Do not change that without
1244
                // taking into account presence of proxy trusted keys.
1245
                s.generateNonce(nonce[:])
381✔
1246
                s.mu.Unlock()
381✔
1247
        }
1248

1249
        // Grab lock
1250
        c.mu.Lock()
632✔
1251

632✔
1252
        var preBuf []byte
632✔
1253
        if solicited {
883✔
1254
                // For websocket connection, we need to send an HTTP request,
251✔
1255
                // and get the response before starting the readLoop to get
251✔
1256
                // the INFO, etc..
251✔
1257
                if c.isWebsocket() {
251✔
1258
                        var err error
×
1259
                        var closeReason ClosedState
×
1260

×
1261
                        preBuf, closeReason, err = c.leafNodeSolicitWSConnection(opts, rURL, remote)
×
1262
                        if err != nil {
×
1263
                                c.Errorf("Error soliciting websocket connection: %v", err)
×
1264
                                c.mu.Unlock()
×
1265
                                if closeReason != 0 {
×
1266
                                        c.closeConnection(closeReason)
×
1267
                                }
×
1268
                                return nil
×
1269
                        }
1270
                } else {
251✔
1271
                        // If configured to do TLS handshake first
251✔
1272
                        if tlsFirst {
251✔
1273
                                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
×
1274
                                        c.mu.Unlock()
×
1275
                                        return nil
×
1276
                                }
×
1277
                        }
1278
                        // We need to wait for the info, but not for too long.
1279
                        c.nc.SetReadDeadline(time.Now().Add(infoTimeout))
251✔
1280
                }
1281

1282
                // We will process the INFO from the readloop and finish by
1283
                // sending the CONNECT and finish registration later.
1284
        } else {
381✔
1285
                // Send our info to the other side.
381✔
1286
                // Remember the nonce we sent here for signatures, etc.
381✔
1287
                c.nonce = make([]byte, nonceLen)
381✔
1288
                copy(c.nonce, nonce[:])
381✔
1289
                info.Nonce = bytesToString(c.nonce)
381✔
1290
                info.CID = c.cid
381✔
1291
                proto := generateInfoJSON(info)
381✔
1292

381✔
1293
                var pre []byte
381✔
1294
                // We need first to check for "TLS First" fallback delay.
381✔
1295
                if tlsFirstFallback > 0 {
381✔
1296
                        // We wait and see if we are getting any data. Since we did not send
×
1297
                        // the INFO protocol yet, only clients that use TLS first should be
×
1298
                        // sending data (the TLS handshake). We don't really check the content:
×
1299
                        // if it is a rogue agent and not an actual client performing the
×
1300
                        // TLS handshake, the error will be detected when performing the
×
1301
                        // handshake on our side.
×
1302
                        pre = make([]byte, 4)
×
1303
                        c.nc.SetReadDeadline(time.Now().Add(tlsFirstFallback))
×
1304
                        n, _ := io.ReadFull(c.nc, pre[:])
×
1305
                        c.nc.SetReadDeadline(time.Time{})
×
1306
                        // If we get any data (regardless of possible timeout), we will proceed
×
1307
                        // with the TLS handshake.
×
1308
                        if n > 0 {
×
1309
                                pre = pre[:n]
×
1310
                        } else {
×
1311
                                // We did not get anything so we will send the INFO protocol.
×
1312
                                pre = nil
×
1313
                                // Set the boolean to false for the rest of the function.
×
1314
                                tlsFirst = false
×
1315
                        }
×
1316
                }
1317

1318
                if !tlsFirst {
762✔
1319
                        // We have to send from this go routine because we may
381✔
1320
                        // have to block for TLS handshake before we start our
381✔
1321
                        // writeLoop go routine. The other side needs to receive
381✔
1322
                        // this before it can initiate the TLS handshake..
381✔
1323
                        c.sendProtoNow(proto)
381✔
1324

381✔
1325
                        // The above call could have marked the connection as closed (due to TCP error).
381✔
1326
                        if c.isClosed() {
381✔
1327
                                c.mu.Unlock()
×
1328
                                c.closeConnection(WriteError)
×
1329
                                return nil
×
1330
                        }
×
1331
                }
1332

1333
                // Check to see if we need to spin up TLS.
1334
                if !c.isWebsocket() && info.TLSRequired {
407✔
1335
                        // If we have a prebuffer create a multi-reader.
26✔
1336
                        if len(pre) > 0 {
26✔
1337
                                c.nc = &tlsMixConn{c.nc, bytes.NewBuffer(pre)}
×
1338
                        }
×
1339
                        // Perform server-side TLS handshake.
1340
                        if err := c.doTLSServerHandshake(tlsHandshakeLeaf, opts.LeafNode.TLSConfig, opts.LeafNode.TLSTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
38✔
1341
                                c.mu.Unlock()
12✔
1342
                                return nil
12✔
1343
                        }
12✔
1344
                }
1345

1346
                // If the user wants the TLS handshake to occur first, now that it is
1347
                // done, send the INFO protocol.
1348
                if tlsFirst {
369✔
1349
                        c.flags.set(didTLSFirst)
×
1350
                        c.sendProtoNow(proto)
×
1351
                        if c.isClosed() {
×
1352
                                c.mu.Unlock()
×
1353
                                c.closeConnection(WriteError)
×
1354
                                return nil
×
1355
                        }
×
1356
                }
1357

1358
                // Leaf nodes will always require a CONNECT to let us know
1359
                // when we are properly bound to an account.
1360
                //
1361
                // If compression is configured, we can't set the authTimer here because
1362
                // it would cause the parser to fail any incoming protocol that is not a
1363
                // CONNECT (and we need to exchange INFO protocols for compression
1364
                // negotiation). So instead, use the ping timer until we are done with
1365
                // negotiation and can set the auth timer.
1366
                timeout := secondsToDuration(opts.LeafNode.AuthTimeout)
369✔
1367
                if needsCompression(opts.LeafNode.Compression.Mode) {
531✔
1368
                        c.ping.tmr = time.AfterFunc(timeout, func() {
162✔
1369
                                c.authTimeout()
×
1370
                        })
×
1371
                } else {
207✔
1372
                        c.setAuthTimer(timeout)
207✔
1373
                }
207✔
1374
        }
1375

1376
        // Keep track in case server is shutdown before we can successfully register.
1377
        if !s.addToTempClients(c.cid, c) {
620✔
1378
                c.mu.Unlock()
×
1379
                c.setNoReconnect()
×
1380
                c.closeConnection(ServerShutdown)
×
1381
                return nil
×
1382
        }
×
1383

1384
        // Spin up the read loop.
1385
        s.startGoRoutine(func() { c.readLoop(preBuf) })
1,240✔
1386

1387
        // We will spin the write loop for solicited connections only
1388
        // when processing the INFO and after switching to TLS if needed.
1389
        if !solicited {
989✔
1390
                s.startGoRoutine(func() { c.writeLoop() })
738✔
1391
        }
1392

1393
        c.mu.Unlock()
620✔
1394

620✔
1395
        return c
620✔
1396
}
1397

1398
// Will perform the client-side TLS handshake if needed. Assumes that this
1399
// is called by the solicit side (remote will be non nil). Returns `true`
1400
// if TLS is required, `false` otherwise.
1401
// Lock held on entry.
1402
func (c *client) leafClientHandshakeIfNeeded(remote *leafNodeCfg, opts *Options) (bool, error) {
611✔
1403
        // Check if TLS is required and gather TLS config variables.
611✔
1404
        tlsRequired, tlsConfig, tlsName, tlsTimeout := c.leafNodeGetTLSConfigForSolicit(remote)
611✔
1405
        if !tlsRequired {
1,198✔
1406
                return false, nil
587✔
1407
        }
587✔
1408

1409
        // If TLS required, peform handshake.
1410
        // Get the URL that was used to connect to the remote server.
1411
        rURL := remote.getCurrentURL()
24✔
1412

24✔
1413
        // Perform the client-side TLS handshake.
24✔
1414
        if resetTLSName, err := c.doTLSClientHandshake(tlsHandshakeLeaf, rURL, tlsConfig, tlsName, tlsTimeout, opts.LeafNode.TLSPinnedCerts); err != nil {
30✔
1415
                // Check if we need to reset the remote's TLS name.
6✔
1416
                if resetTLSName {
6✔
1417
                        remote.Lock()
×
1418
                        remote.tlsName = _EMPTY_
×
1419
                        remote.Unlock()
×
1420
                }
×
1421
                return false, err
6✔
1422
        }
1423
        return true, nil
18✔
1424
}
1425

1426
func (c *client) processLeafnodeInfo(info *Info) {
825✔
1427
        c.mu.Lock()
825✔
1428
        if c.leaf == nil || c.isClosed() {
825✔
1429
                c.mu.Unlock()
×
1430
                return
×
1431
        }
×
1432
        s := c.srv
825✔
1433
        opts := s.getOpts()
825✔
1434
        remote := c.leaf.remote
825✔
1435
        didSolicit := remote != nil
825✔
1436
        firstINFO := !c.flags.isSet(infoReceived)
825✔
1437

825✔
1438
        // In case of websocket, the TLS handshake has been already done.
825✔
1439
        // So check only for non websocket connections and for configurations
825✔
1440
        // where the TLS Handshake was not done first.
825✔
1441
        if didSolicit && !c.flags.isSet(handshakeComplete) && !c.isWebsocket() && !remote.TLSHandshakeFirst {
1,436✔
1442
                // If the server requires TLS, we need to set this in the remote
611✔
1443
                // otherwise if there is no TLS configuration block for the remote,
611✔
1444
                // the solicit side will not attempt to perform the TLS handshake.
611✔
1445
                if firstINFO && info.TLSRequired {
635✔
1446
                        // Check for TLS/proxy configuration mismatch
24✔
1447
                        if remote.Proxy.URL != _EMPTY_ && !remote.TLS && remote.TLSConfig == nil {
24✔
1448
                                c.mu.Unlock()
×
1449
                                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.")
×
1450
                                c.closeConnection(TLSHandshakeError)
×
1451
                                return
×
1452
                        }
×
1453
                        remote.TLS = true
24✔
1454
                }
1455
                if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil {
617✔
1456
                        c.mu.Unlock()
6✔
1457
                        return
6✔
1458
                }
6✔
1459
        }
1460

1461
        // Check for compression, unless already done.
1462
        if firstINFO && !c.flags.isSet(compressionNegotiated) {
1,224✔
1463
                // Prevent from getting back here.
405✔
1464
                c.flags.set(compressionNegotiated)
405✔
1465

405✔
1466
                var co *CompressionOpts
405✔
1467
                if !didSolicit {
566✔
1468
                        co = &opts.LeafNode.Compression
161✔
1469
                } else {
405✔
1470
                        co = &remote.Compression
244✔
1471
                }
244✔
1472
                if needsCompression(co.Mode) {
808✔
1473
                        // Release client lock since following function will need server lock.
403✔
1474
                        c.mu.Unlock()
403✔
1475
                        compress, err := s.negotiateLeafCompression(c, didSolicit, info.Compression, co)
403✔
1476
                        if err != nil {
403✔
1477
                                c.sendErrAndErr(err.Error())
×
1478
                                c.closeConnection(ProtocolViolation)
×
1479
                                return
×
1480
                        }
×
1481
                        if compress {
723✔
1482
                                // Done for now, will get back another INFO protocol...
320✔
1483
                                return
320✔
1484
                        }
320✔
1485
                        // No compression because one side does not want/can't, so proceed.
1486
                        c.mu.Lock()
83✔
1487
                        // Check that the connection did not close if the lock was released.
83✔
1488
                        if c.isClosed() {
83✔
1489
                                c.mu.Unlock()
×
1490
                                return
×
1491
                        }
×
1492
                } else {
2✔
1493
                        // Coming from an old server, the Compression field would be the empty
2✔
1494
                        // string. For servers that are configured with CompressionNotSupported,
2✔
1495
                        // this makes them behave as old servers.
2✔
1496
                        if info.Compression == _EMPTY_ || co.Mode == CompressionNotSupported {
3✔
1497
                                c.leaf.compression = CompressionNotSupported
1✔
1498
                        } else {
2✔
1499
                                c.leaf.compression = CompressionOff
1✔
1500
                        }
1✔
1501
                }
1502
                // Accepting side does not normally process an INFO protocol during
1503
                // initial connection handshake. So we keep it consistent by returning
1504
                // if we are not soliciting.
1505
                if !didSolicit {
86✔
1506
                        // If we had created the ping timer instead of the auth timer, we will
1✔
1507
                        // clear the ping timer and set the auth timer now that the compression
1✔
1508
                        // negotiation is done.
1✔
1509
                        if info.Compression != _EMPTY_ && c.ping.tmr != nil {
1✔
1510
                                clearTimer(&c.ping.tmr)
×
1511
                                c.setAuthTimer(secondsToDuration(opts.LeafNode.AuthTimeout))
×
1512
                        }
×
1513
                        c.mu.Unlock()
1✔
1514
                        return
1✔
1515
                }
1516
                // Fall through and process the INFO protocol as usual.
1517
        }
1518

1519
        // Note: For now, only the initial INFO has a nonce. We
1520
        // will probably do auto key rotation at some point.
1521
        if firstINFO {
761✔
1522
                // Mark that the INFO protocol has been received.
263✔
1523
                c.flags.set(infoReceived)
263✔
1524
                // Prevent connecting to non leafnode port. Need to do this only for
263✔
1525
                // the first INFO, not for async INFO updates...
263✔
1526
                //
263✔
1527
                // Content of INFO sent by the server when accepting a tcp connection.
263✔
1528
                // -------------------------------------------------------------------
263✔
1529
                // Listen Port Of | CID | ClientConnectURLs | LeafNodeURLs | Gateway |
263✔
1530
                // -------------------------------------------------------------------
263✔
1531
                //      CLIENT    |  X* |        X**        |              |         |
263✔
1532
                //      ROUTE     |     |        X**        |      X***    |         |
263✔
1533
                //     GATEWAY    |     |                   |              |    X    |
263✔
1534
                //     LEAFNODE   |  X  |                   |       X      |         |
263✔
1535
                // -------------------------------------------------------------------
263✔
1536
                // *   Not on older servers.
263✔
1537
                // **  Not if "no advertise" is enabled.
263✔
1538
                // *** Not if leafnode's "no advertise" is enabled.
263✔
1539
                //
263✔
1540
                // As seen from above, a solicited LeafNode connection should receive
263✔
1541
                // from the remote server an INFO with CID and LeafNodeURLs. Anything
263✔
1542
                // else should be considered an attempt to connect to a wrong port.
263✔
1543
                if didSolicit && (info.CID == 0 || info.LeafNodeURLs == nil) {
263✔
1544
                        c.mu.Unlock()
×
1545
                        c.Errorf(ErrConnectedToWrongPort.Error())
×
1546
                        c.closeConnection(WrongPort)
×
1547
                        return
×
1548
                }
×
1549
                // Reject a cluster that contains spaces.
1550
                if info.Cluster != _EMPTY_ && strings.Contains(info.Cluster, " ") {
264✔
1551
                        c.mu.Unlock()
1✔
1552
                        c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
1553
                        c.closeConnection(ProtocolViolation)
1✔
1554
                        return
1✔
1555
                }
1✔
1556
                // Capture a nonce here.
1557
                c.nonce = []byte(info.Nonce)
262✔
1558
                if info.TLSRequired && didSolicit {
280✔
1559
                        remote.TLS = true
18✔
1560
                }
18✔
1561
                supportsHeaders := c.srv.supportsHeaders()
262✔
1562
                c.headers = supportsHeaders && info.Headers
262✔
1563

262✔
1564
                // Remember the remote server.
262✔
1565
                // Pre 2.2.0 servers are not sending their server name.
262✔
1566
                // In that case, use info.ID, which, for those servers, matches
262✔
1567
                // the content of the field `Name` in the leafnode CONNECT protocol.
262✔
1568
                if info.Name == _EMPTY_ {
262✔
1569
                        c.leaf.remoteServer = info.ID
×
1570
                } else {
262✔
1571
                        c.leaf.remoteServer = info.Name
262✔
1572
                }
262✔
1573
                c.leaf.remoteDomain = info.Domain
262✔
1574
                c.leaf.remoteCluster = info.Cluster
262✔
1575
                // We send the protocol version in the INFO protocol.
262✔
1576
                // Keep track of it, so we know if this connection supports message
262✔
1577
                // tracing for instance.
262✔
1578
                c.opts.Protocol = info.Proto
262✔
1579
        }
1580

1581
        // For both initial INFO and async INFO protocols, Possibly
1582
        // update our list of remote leafnode URLs we can connect to.
1583
        if didSolicit && (len(info.LeafNodeURLs) > 0 || len(info.WSConnectURLs) > 0) {
957✔
1584
                // Consider the incoming array as the most up-to-date
460✔
1585
                // representation of the remote cluster's list of URLs.
460✔
1586
                c.updateLeafNodeURLs(info)
460✔
1587
        }
460✔
1588

1589
        // Check to see if we have permissions updates here.
1590
        if info.Import != nil || info.Export != nil {
499✔
1591
                perms := &Permissions{
2✔
1592
                        Publish:   info.Export,
2✔
1593
                        Subscribe: info.Import,
2✔
1594
                }
2✔
1595
                // Check if we have local deny clauses that we need to merge.
2✔
1596
                if remote := c.leaf.remote; remote != nil {
4✔
1597
                        if len(remote.DenyExports) > 0 {
3✔
1598
                                if perms.Publish == nil {
1✔
1599
                                        perms.Publish = &SubjectPermission{}
×
1600
                                }
×
1601
                                perms.Publish.Deny = append(perms.Publish.Deny, remote.DenyExports...)
1✔
1602
                        }
1603
                        if len(remote.DenyImports) > 0 {
3✔
1604
                                if perms.Subscribe == nil {
1✔
1605
                                        perms.Subscribe = &SubjectPermission{}
×
1606
                                }
×
1607
                                perms.Subscribe.Deny = append(perms.Subscribe.Deny, remote.DenyImports...)
1✔
1608
                        }
1609
                }
1610
                c.setPermissions(perms)
2✔
1611
        }
1612

1613
        var resumeConnect bool
497✔
1614

497✔
1615
        // If this is a remote connection and this is the first INFO protocol,
497✔
1616
        // then we need to finish the connect process by sending CONNECT, etc..
497✔
1617
        if firstINFO && didSolicit {
741✔
1618
                // Clear deadline that was set in createLeafNode while waiting for the INFO.
244✔
1619
                c.nc.SetDeadline(time.Time{})
244✔
1620
                resumeConnect = true
244✔
1621
        } else if !firstINFO && didSolicit {
713✔
1622
                c.leaf.remoteAccName = info.RemoteAccount
216✔
1623
        }
216✔
1624

1625
        // Check if we have the remote account information and if so make sure it's stored.
1626
        if info.RemoteAccount != _EMPTY_ {
712✔
1627
                s.leafRemoteAccounts.Store(c.acc.Name, info.RemoteAccount)
215✔
1628
        }
215✔
1629
        c.mu.Unlock()
497✔
1630

497✔
1631
        finishConnect := info.ConnectInfo
497✔
1632
        if resumeConnect && s != nil {
741✔
1633
                s.leafNodeResumeConnectProcess(c)
244✔
1634
                if !info.InfoOnConnect {
244✔
1635
                        finishConnect = true
×
1636
                }
×
1637
        }
1638
        if finishConnect {
712✔
1639
                s.leafNodeFinishConnectProcess(c)
215✔
1640
        }
215✔
1641

1642
        // Check to see if we need to kick any internal source or mirror consumers.
1643
        // This will be a no-op if JetStream not enabled for this server or if the bound account
1644
        // does not have jetstream.
1645
        s.checkInternalSyncConsumers(c.acc)
497✔
1646
}
1647

1648
func (s *Server) negotiateLeafCompression(c *client, didSolicit bool, infoCompression string, co *CompressionOpts) (bool, error) {
403✔
1649
        // Negotiate the appropriate compression mode (or no compression)
403✔
1650
        cm, err := selectCompressionMode(co.Mode, infoCompression)
403✔
1651
        if err != nil {
403✔
1652
                return false, err
×
1653
        }
×
1654
        c.mu.Lock()
403✔
1655
        // For "auto" mode, set the initial compression mode based on RTT
403✔
1656
        if cm == CompressionS2Auto {
723✔
1657
                if c.rttStart.IsZero() {
640✔
1658
                        c.rtt = computeRTT(c.start)
320✔
1659
                }
320✔
1660
                cm = selectS2AutoModeBasedOnRTT(c.rtt, co.RTTThresholds)
320✔
1661
        }
1662
        // Keep track of the negotiated compression mode.
1663
        c.leaf.compression = cm
403✔
1664
        cid := c.cid
403✔
1665
        var nonce string
403✔
1666
        if !didSolicit {
563✔
1667
                nonce = bytesToString(c.nonce)
160✔
1668
        }
160✔
1669
        c.mu.Unlock()
403✔
1670

403✔
1671
        if !needsCompression(cm) {
486✔
1672
                return false, nil
83✔
1673
        }
83✔
1674

1675
        // If we end-up doing compression...
1676

1677
        // Generate an INFO with the chosen compression mode.
1678
        s.mu.Lock()
320✔
1679
        info := s.copyLeafNodeInfo()
320✔
1680
        info.Compression, info.CID, info.Nonce = compressionModeForInfoProtocol(co, cm), cid, nonce
320✔
1681
        infoProto := generateInfoJSON(info)
320✔
1682
        s.mu.Unlock()
320✔
1683

320✔
1684
        // If we solicited, then send this INFO protocol BEFORE switching
320✔
1685
        // to compression writer. However, if we did not, we send it after.
320✔
1686
        c.mu.Lock()
320✔
1687
        if didSolicit {
480✔
1688
                c.enqueueProto(infoProto)
160✔
1689
                // Make sure it is completely flushed (the pending bytes goes to
160✔
1690
                // 0) before proceeding.
160✔
1691
                for c.out.pb > 0 && !c.isClosed() {
320✔
1692
                        c.flushOutbound()
160✔
1693
                }
160✔
1694
        }
1695
        // This is to notify the readLoop that it should switch to a
1696
        // (de)compression reader.
1697
        c.in.flags.set(switchToCompression)
320✔
1698
        // Create the compress writer before queueing the INFO protocol for
320✔
1699
        // a route that did not solicit. It will make sure that that proto
320✔
1700
        // is sent with compression on.
320✔
1701
        c.out.cw = s2.NewWriter(nil, s2WriterOptions(cm)...)
320✔
1702
        if !didSolicit {
480✔
1703
                c.enqueueProto(infoProto)
160✔
1704
        }
160✔
1705
        c.mu.Unlock()
320✔
1706
        return true, nil
320✔
1707
}
1708

1709
// When getting a leaf node INFO protocol, use the provided
1710
// array of urls to update the list of possible endpoints.
1711
func (c *client) updateLeafNodeURLs(info *Info) {
460✔
1712
        cfg := c.leaf.remote
460✔
1713
        cfg.Lock()
460✔
1714
        defer cfg.Unlock()
460✔
1715

460✔
1716
        // We have ensured that if a remote has a WS scheme, then all are.
460✔
1717
        // So check if first is WS, then add WS URLs, otherwise, add non WS ones.
460✔
1718
        if len(cfg.URLs) > 0 && isWSURL(cfg.URLs[0]) {
460✔
1719
                // It does not really matter if we use "ws://" or "wss://" here since
×
1720
                // we will have already marked that the remote should use TLS anyway.
×
1721
                // But use proper scheme for log statements, etc...
×
1722
                proto := wsSchemePrefix
×
1723
                if cfg.TLS {
×
1724
                        proto = wsSchemePrefixTLS
×
1725
                }
×
1726
                c.doUpdateLNURLs(cfg, proto, info.WSConnectURLs)
×
1727
                return
×
1728
        }
1729
        c.doUpdateLNURLs(cfg, "nats-leaf", info.LeafNodeURLs)
460✔
1730
}
1731

1732
func (c *client) doUpdateLNURLs(cfg *leafNodeCfg, scheme string, URLs []string) {
460✔
1733
        cfg.urls = make([]*url.URL, 0, 1+len(URLs))
460✔
1734
        // Add the ones we receive in the protocol
460✔
1735
        for _, surl := range URLs {
1,485✔
1736
                url, err := url.Parse(fmt.Sprintf("%s://%s", scheme, surl))
1,025✔
1737
                if err != nil {
1,025✔
1738
                        // As per below, the URLs we receive should not have contained URL info, so this should be safe to log.
×
1739
                        c.Errorf("Error parsing url %q: %v", surl, err)
×
1740
                        continue
×
1741
                }
1742
                // Do not add if it's the same as what we already have configured.
1743
                var dup bool
1,025✔
1744
                for _, u := range cfg.URLs {
2,677✔
1745
                        // URLs that we receive never have user info, but the
1,652✔
1746
                        // ones that were configured may have. Simply compare
1,652✔
1747
                        // host and port to decide if they are equal or not.
1,652✔
1748
                        if url.Host == u.Host && url.Port() == u.Port() {
2,522✔
1749
                                dup = true
870✔
1750
                                break
870✔
1751
                        }
1752
                }
1753
                if !dup {
1,180✔
1754
                        cfg.urls = append(cfg.urls, url)
155✔
1755
                        cfg.saveTLSHostname(url)
155✔
1756
                }
155✔
1757
        }
1758
        // Add the configured one
1759
        cfg.urls = append(cfg.urls, cfg.URLs...)
460✔
1760
}
1761

1762
// Similar to setInfoHostPortAndGenerateJSON, but for leafNodeInfo.
1763
func (s *Server) setLeafNodeInfoHostPortAndIP() error {
2,168✔
1764
        opts := s.getOpts()
2,168✔
1765
        if opts.LeafNode.Advertise != _EMPTY_ {
2,179✔
1766
                advHost, advPort, err := parseHostPort(opts.LeafNode.Advertise, opts.LeafNode.Port)
11✔
1767
                if err != nil {
11✔
1768
                        return err
×
1769
                }
×
1770
                s.leafNodeInfo.Host = advHost
11✔
1771
                s.leafNodeInfo.Port = advPort
11✔
1772
        } else {
2,157✔
1773
                s.leafNodeInfo.Host = opts.LeafNode.Host
2,157✔
1774
                s.leafNodeInfo.Port = opts.LeafNode.Port
2,157✔
1775
                // If the host is "0.0.0.0" or "::" we need to resolve to a public IP.
2,157✔
1776
                // This will return at most 1 IP.
2,157✔
1777
                hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(s.leafNodeInfo.Host, false)
2,157✔
1778
                if err != nil {
2,157✔
1779
                        return err
×
1780
                }
×
1781
                if hostIsIPAny {
2,169✔
1782
                        if len(ips) == 0 {
12✔
1783
                                s.Errorf("Could not find any non-local IP for leafnode's listen specification %q",
×
1784
                                        s.leafNodeInfo.Host)
×
1785
                        } else {
12✔
1786
                                // Take the first from the list...
12✔
1787
                                s.leafNodeInfo.Host = ips[0]
12✔
1788
                        }
12✔
1789
                }
1790
        }
1791
        // Use just host:port for the IP
1792
        s.leafNodeInfo.IP = net.JoinHostPort(s.leafNodeInfo.Host, strconv.Itoa(s.leafNodeInfo.Port))
2,168✔
1793
        if opts.LeafNode.Advertise != _EMPTY_ {
2,179✔
1794
                s.Noticef("Advertise address for leafnode is set to %s", s.leafNodeInfo.IP)
11✔
1795
        }
11✔
1796
        return nil
2,168✔
1797
}
1798

1799
// Add the connection to the map of leaf nodes.
1800
// If `checkForDup` is true (invoked when a leafnode is accepted), then we check
1801
// if a connection already exists for the same server name and account.
1802
// That can happen when the remote is attempting to reconnect while the accepting
1803
// side did not detect the connection as broken yet.
1804
// But it can also happen when there is a misconfiguration and the remote is
1805
// creating two (or more) connections that bind to the same account on the accept
1806
// side.
1807
// When a duplicate is found, the new connection is accepted and the old is closed
1808
// (this solves the stale connection situation). An error is returned to help the
1809
// remote detect the misconfiguration when the duplicate is the result of that
1810
// misconfiguration.
1811
func (s *Server) addLeafNodeConnection(c *client, srvName, clusterName string, checkForDup bool) {
467✔
1812
        var accName string
467✔
1813
        c.mu.Lock()
467✔
1814
        cid := c.cid
467✔
1815
        acc := c.acc
467✔
1816
        if acc != nil {
934✔
1817
                accName = acc.Name
467✔
1818
        }
467✔
1819
        myRemoteDomain := c.leaf.remoteDomain
467✔
1820
        mySrvName := c.leaf.remoteServer
467✔
1821
        remoteAccName := c.leaf.remoteAccName
467✔
1822
        myClustName := c.leaf.remoteCluster
467✔
1823
        solicited := c.leaf.remote != nil
467✔
1824
        c.mu.Unlock()
467✔
1825

467✔
1826
        var old *client
467✔
1827
        s.mu.Lock()
467✔
1828
        // We check for empty because in some test we may send empty CONNECT{}
467✔
1829
        if checkForDup && srvName != _EMPTY_ {
682✔
1830
                for _, ol := range s.leafs {
460✔
1831
                        ol.mu.Lock()
245✔
1832
                        // We care here only about non solicited Leafnode. This function
245✔
1833
                        // is more about replacing stale connections than detecting loops.
245✔
1834
                        // We have code for the loop detection elsewhere, which also delays
245✔
1835
                        // attempt to reconnect.
245✔
1836
                        if !ol.isSolicitedLeafNode() && ol.leaf.remoteServer == srvName &&
245✔
1837
                                ol.leaf.remoteCluster == clusterName && ol.acc.Name == accName &&
245✔
1838
                                remoteAccName != _EMPTY_ && ol.leaf.remoteAccName == remoteAccName {
245✔
1839
                                old = ol
×
1840
                        }
×
1841
                        ol.mu.Unlock()
245✔
1842
                        if old != nil {
245✔
1843
                                break
×
1844
                        }
1845
                }
1846
        }
1847
        // Store new connection in the map
1848
        s.leafs[cid] = c
467✔
1849
        s.mu.Unlock()
467✔
1850
        s.removeFromTempClients(cid)
467✔
1851

467✔
1852
        // If applicable, evict the old one.
467✔
1853
        if old != nil {
467✔
1854
                old.sendErrAndErr(DuplicateRemoteLeafnodeConnection.String())
×
1855
                old.closeConnection(DuplicateRemoteLeafnodeConnection)
×
1856
                c.Warnf("Replacing connection from same server")
×
1857
        }
×
1858

1859
        srvDecorated := func() string {
572✔
1860
                if myClustName == _EMPTY_ {
111✔
1861
                        return mySrvName
6✔
1862
                }
6✔
1863
                return fmt.Sprintf("%s/%s", mySrvName, myClustName)
99✔
1864
        }
1865

1866
        opts := s.getOpts()
467✔
1867
        sysAcc := s.SystemAccount()
467✔
1868
        js := s.getJetStream()
467✔
1869
        var meta *raft
467✔
1870
        if js != nil {
713✔
1871
                if mg := js.getMetaGroup(); mg != nil {
464✔
1872
                        meta = mg.(*raft)
218✔
1873
                }
218✔
1874
        }
1875
        blockMappingOutgoing := false
467✔
1876
        // Deny (non domain) JetStream API traffic unless system account is shared
467✔
1877
        // and domain names are identical and extending is not disabled
467✔
1878

467✔
1879
        // Check if backwards compatibility has been enabled and needs to be acted on
467✔
1880
        forceSysAccDeny := false
467✔
1881
        if len(opts.JsAccDefaultDomain) > 0 {
467✔
1882
                if acc == sysAcc {
×
1883
                        for _, d := range opts.JsAccDefaultDomain {
×
1884
                                if d == _EMPTY_ {
×
1885
                                        // Extending JetStream via leaf node is mutually exclusive with a domain mapping to the empty/default domain.
×
1886
                                        // As soon as one mapping to "" is found, disable the ability to extend JS via a leaf node.
×
1887
                                        c.Noticef("Not extending remote JetStream domain %q due to presence of empty default domain", myRemoteDomain)
×
1888
                                        forceSysAccDeny = true
×
1889
                                        break
×
1890
                                }
1891
                        }
1892
                } else if domain, ok := opts.JsAccDefaultDomain[accName]; ok && domain == _EMPTY_ {
×
1893
                        // for backwards compatibility with old setups that do not have a domain name set
×
1894
                        c.Debugf("Skipping deny %q for account %q due to default domain", jsAllAPI, accName)
×
1895
                        return
×
1896
                }
×
1897
        }
1898

1899
        // If the server has JS disabled, it may still be part of a JetStream that could be extended.
1900
        // This is either signaled by js being disabled and a domain set,
1901
        // or in cases where no domain name exists, an extension hint is set.
1902
        // However, this is only relevant in mixed setups.
1903
        //
1904
        // If the system account connects but default domains are present, JetStream can't be extended.
1905
        if opts.JetStreamDomain != myRemoteDomain || (!opts.JetStream && (opts.JetStreamDomain == _EMPTY_ && opts.JetStreamExtHint != jsWillExtend)) ||
467✔
1906
                sysAcc == nil || acc == nil || forceSysAccDeny {
861✔
1907
                // If domain names mismatch always deny. This applies to system accounts as well as non system accounts.
394✔
1908
                // Not having a system account, account or JetStream disabled is considered a mismatch as well.
394✔
1909
                if acc != nil && acc == sysAcc {
463✔
1910
                        c.Noticef("System account connected from %s", srvDecorated())
69✔
1911
                        c.Noticef("JetStream not extended, domains differ")
69✔
1912
                        c.mergeDenyPermissionsLocked(both, denyAllJs)
69✔
1913
                        // When a remote with a system account is present in a server, unless otherwise disabled, the server will be
69✔
1914
                        // started in observer mode. Now that it is clear that this not used, turn the observer mode off.
69✔
1915
                        if solicited && meta != nil && meta.IsObserver() {
83✔
1916
                                meta.setObserver(false, extNotExtended)
14✔
1917
                                c.Debugf("Turning JetStream metadata controller Observer Mode off")
14✔
1918
                                // Take note that the domain was not extended to avoid this state from startup.
14✔
1919
                                writePeerState(js.config.StoreDir, meta.currentPeerState())
14✔
1920
                                // Meta controller can't be leader yet.
14✔
1921
                                // Yet it is possible that due to observer mode every server already stopped campaigning.
14✔
1922
                                // Therefore this server needs to be kicked into campaigning gear explicitly.
14✔
1923
                                meta.Campaign()
14✔
1924
                        }
14✔
1925
                } else {
325✔
1926
                        c.Noticef("JetStream using domains: local %q, remote %q", opts.JetStreamDomain, myRemoteDomain)
325✔
1927
                        c.mergeDenyPermissionsLocked(both, denyAllClientJs)
325✔
1928
                }
325✔
1929
                blockMappingOutgoing = true
394✔
1930
        } else if acc == sysAcc {
109✔
1931
                // system account and same domain
36✔
1932
                s.sys.client.Noticef("Extending JetStream domain %q as System Account connected from server %s",
36✔
1933
                        myRemoteDomain, srvDecorated())
36✔
1934
                // In an extension use case, pin leadership to server remotes connect to.
36✔
1935
                // Therefore, server with a remote that are not already in observer mode, need to be put into it.
36✔
1936
                if solicited && meta != nil && !meta.IsObserver() {
36✔
1937
                        meta.setObserver(true, extExtended)
×
1938
                        c.Debugf("Turning JetStream metadata controller Observer Mode on - System Account Connected")
×
1939
                        // Take note that the domain was not extended to avoid this state next startup.
×
1940
                        writePeerState(js.config.StoreDir, meta.currentPeerState())
×
1941
                        // If this server is the leader already, step down so a new leader can be elected (that is not an observer)
×
1942
                        meta.StepDown()
×
1943
                }
×
1944
        } else {
37✔
1945
                // This deny is needed in all cases (system account shared or not)
37✔
1946
                // If the system account is shared, jsAllAPI traffic will go through the system account.
37✔
1947
                // So in order to prevent duplicate delivery (from system and actual account) suppress it on the account.
37✔
1948
                // If the system account is NOT shared, jsAllAPI traffic has no business
37✔
1949
                c.Debugf("Adding deny %+v for account %q", denyAllClientJs, accName)
37✔
1950
                c.mergeDenyPermissionsLocked(both, denyAllClientJs)
37✔
1951
        }
37✔
1952
        // If we have a specified JetStream domain we will want to add a mapping to
1953
        // allow access cross domain for each non-system account.
1954
        if opts.JetStreamDomain != _EMPTY_ && opts.JetStream && acc != nil && acc != sysAcc {
577✔
1955
                for src, dest := range generateJSMappingTable(opts.JetStreamDomain) {
1,100✔
1956
                        if err := acc.AddMapping(src, dest); err != nil {
990✔
1957
                                c.Debugf("Error adding JetStream domain mapping: %s", err.Error())
×
1958
                        } else {
990✔
1959
                                c.Debugf("Adding JetStream Domain Mapping %q -> %s to account %q", src, dest, accName)
990✔
1960
                        }
990✔
1961
                }
1962
                if blockMappingOutgoing {
212✔
1963
                        src := fmt.Sprintf(jsDomainAPI, opts.JetStreamDomain)
102✔
1964
                        // make sure that messages intended for this domain, do not leave the cluster via this leaf node connection
102✔
1965
                        // This is a guard against a miss-config with two identical domain names and will only cover some forms
102✔
1966
                        // of this issue, not all of them.
102✔
1967
                        // This guards against a hub and a spoke having the same domain name.
102✔
1968
                        // But not two spokes having the same one and the request coming from the hub.
102✔
1969
                        c.mergeDenyPermissionsLocked(pub, []string{src})
102✔
1970
                        c.Debugf("Adding deny %q for outgoing messages to account %q", src, accName)
102✔
1971
                }
102✔
1972
        }
1973
}
1974

1975
func (s *Server) removeLeafNodeConnection(c *client) {
632✔
1976
        c.mu.Lock()
632✔
1977
        cid := c.cid
632✔
1978
        if c.leaf != nil {
1,264✔
1979
                if c.leaf.tsubt != nil {
1,027✔
1980
                        c.leaf.tsubt.Stop()
395✔
1981
                        c.leaf.tsubt = nil
395✔
1982
                }
395✔
1983
                if c.leaf.gwSub != nil {
847✔
1984
                        s.gwLeafSubs.Remove(c.leaf.gwSub)
215✔
1985
                        // We need to set this to nil for GC to release the connection
215✔
1986
                        c.leaf.gwSub = nil
215✔
1987
                }
215✔
1988
        }
1989
        proxyKey := c.proxyKey
632✔
1990
        c.mu.Unlock()
632✔
1991
        s.mu.Lock()
632✔
1992
        delete(s.leafs, cid)
632✔
1993
        if proxyKey != _EMPTY_ {
636✔
1994
                s.removeProxiedConn(proxyKey, cid)
4✔
1995
        }
4✔
1996
        s.mu.Unlock()
632✔
1997
        s.removeFromTempClients(cid)
632✔
1998
}
1999

2000
// Connect information for solicited leafnodes.
2001
type leafConnectInfo struct {
2002
        Version   string   `json:"version,omitempty"`
2003
        Nkey      string   `json:"nkey,omitempty"`
2004
        JWT       string   `json:"jwt,omitempty"`
2005
        Sig       string   `json:"sig,omitempty"`
2006
        User      string   `json:"user,omitempty"`
2007
        Pass      string   `json:"pass,omitempty"`
2008
        Token     string   `json:"auth_token,omitempty"`
2009
        ID        string   `json:"server_id,omitempty"`
2010
        Domain    string   `json:"domain,omitempty"`
2011
        Name      string   `json:"name,omitempty"`
2012
        Hub       bool     `json:"is_hub,omitempty"`
2013
        Cluster   string   `json:"cluster,omitempty"`
2014
        Headers   bool     `json:"headers,omitempty"`
2015
        JetStream bool     `json:"jetstream,omitempty"`
2016
        DenyPub   []string `json:"deny_pub,omitempty"`
2017
        Isolate   bool     `json:"isolate,omitempty"`
2018

2019
        // There was an existing field called:
2020
        // >> Comp bool `json:"compression,omitempty"`
2021
        // that has never been used. With support for compression, we now need
2022
        // a field that is a string. So we use a different json tag:
2023
        Compression string `json:"compress_mode,omitempty"`
2024

2025
        // Just used to detect wrong connection attempts.
2026
        Gateway string `json:"gateway,omitempty"`
2027

2028
        // Tells the accept side which account the remote is binding to.
2029
        RemoteAccount string `json:"remote_account,omitempty"`
2030

2031
        // The accept side of a LEAF connection, unlike ROUTER and GATEWAY, receives
2032
        // only the CONNECT protocol, and no INFO. So we need to send the protocol
2033
        // version as part of the CONNECT. It will indicate if a connection supports
2034
        // some features, such as message tracing.
2035
        // We use `protocol` as the JSON tag, so this is automatically unmarshal'ed
2036
        // in the low level process CONNECT.
2037
        Proto int `json:"protocol,omitempty"`
2038
}
2039

2040
// processLeafNodeConnect will process the inbound connect args.
2041
// Once we are here we are bound to an account, so can send any interest that
2042
// we would have to the other side.
2043
func (c *client) processLeafNodeConnect(s *Server, arg []byte, lang string) error {
256✔
2044
        // Way to detect clients that incorrectly connect to the route listen
256✔
2045
        // port. Client provided "lang" in the CONNECT protocol while LEAFNODEs don't.
256✔
2046
        if lang != _EMPTY_ {
256✔
2047
                c.sendErrAndErr(ErrClientConnectedToLeafNodePort.Error())
×
2048
                c.closeConnection(WrongPort)
×
2049
                return ErrClientConnectedToLeafNodePort
×
2050
        }
×
2051

2052
        // Unmarshal as a leaf node connect protocol
2053
        proto := &leafConnectInfo{}
256✔
2054
        if err := json.Unmarshal(arg, proto); err != nil {
256✔
2055
                return err
×
2056
        }
×
2057

2058
        // Reject a cluster that contains spaces.
2059
        if proto.Cluster != _EMPTY_ && strings.Contains(proto.Cluster, " ") {
257✔
2060
                c.sendErrAndErr(ErrClusterNameHasSpaces.Error())
1✔
2061
                c.closeConnection(ProtocolViolation)
1✔
2062
                return ErrClusterNameHasSpaces
1✔
2063
        }
1✔
2064

2065
        // Check for cluster name collisions.
2066
        if cn := s.cachedClusterName(); cn != _EMPTY_ && proto.Cluster != _EMPTY_ && proto.Cluster == cn {
258✔
2067
                c.sendErrAndErr(ErrLeafNodeHasSameClusterName.Error())
3✔
2068
                c.closeConnection(ClusterNamesIdentical)
3✔
2069
                return ErrLeafNodeHasSameClusterName
3✔
2070
        }
3✔
2071

2072
        // Reject if this has Gateway which means that it would be from a gateway
2073
        // connection that incorrectly connects to the leafnode port.
2074
        if proto.Gateway != _EMPTY_ {
252✔
2075
                errTxt := fmt.Sprintf("Rejecting connection from gateway %q on the leafnode port", proto.Gateway)
×
2076
                c.Errorf(errTxt)
×
2077
                c.sendErr(errTxt)
×
2078
                c.closeConnection(WrongGateway)
×
2079
                return ErrWrongGateway
×
2080
        }
×
2081

2082
        if mv := s.getOpts().LeafNode.MinVersion; mv != _EMPTY_ {
252✔
2083
                major, minor, update, _ := versionComponents(mv)
×
2084
                if !versionAtLeast(proto.Version, major, minor, update) {
×
2085
                        // We are going to send back an INFO because otherwise recent
×
2086
                        // versions of the remote server would simply break the connection
×
2087
                        // after 2 seconds if not receiving it. Instead, we want the
×
2088
                        // other side to just "stall" until we finish waiting for the holding
×
2089
                        // period and close the connection below.
×
2090
                        s.sendPermsAndAccountInfo(c)
×
2091
                        c.sendErrAndErr(fmt.Sprintf("connection rejected since minimum version required is %q", mv))
×
2092
                        select {
×
2093
                        case <-c.srv.quitCh:
×
2094
                        case <-time.After(leafNodeWaitBeforeClose):
×
2095
                        }
2096
                        c.closeConnection(MinimumVersionRequired)
×
2097
                        return ErrMinimumVersionRequired
×
2098
                }
2099
        }
2100

2101
        // Check if this server supports headers.
2102
        supportHeaders := c.srv.supportsHeaders()
252✔
2103

252✔
2104
        c.mu.Lock()
252✔
2105
        // Leaf Nodes do not do echo or verbose or pedantic.
252✔
2106
        c.opts.Verbose = false
252✔
2107
        c.opts.Echo = false
252✔
2108
        c.opts.Pedantic = false
252✔
2109
        // This inbound connection will be marked as supporting headers if this server
252✔
2110
        // support headers and the remote has sent in the CONNECT protocol that it does
252✔
2111
        // support headers too.
252✔
2112
        c.headers = supportHeaders && proto.Headers
252✔
2113
        // If the compression level is still not set, set it based on what has been
252✔
2114
        // given to us in the CONNECT protocol.
252✔
2115
        if c.leaf.compression == _EMPTY_ {
364✔
2116
                // But if proto.Compression is _EMPTY_, set it to CompressionNotSupported
112✔
2117
                if proto.Compression == _EMPTY_ {
148✔
2118
                        c.leaf.compression = CompressionNotSupported
36✔
2119
                } else {
112✔
2120
                        c.leaf.compression = proto.Compression
76✔
2121
                }
76✔
2122
        }
2123

2124
        // Remember the remote server.
2125
        c.leaf.remoteServer = proto.Name
252✔
2126
        // Remember the remote account name
252✔
2127
        c.leaf.remoteAccName = proto.RemoteAccount
252✔
2128
        // Remember if the leafnode requested isolation.
252✔
2129
        c.leaf.isolated = c.leaf.isolated || proto.Isolate
252✔
2130

252✔
2131
        // If the other side has declared itself a hub, so we will take on the spoke role.
252✔
2132
        if proto.Hub {
252✔
2133
                c.leaf.isSpoke = true
×
2134
        }
×
2135

2136
        // The soliciting side is part of a cluster.
2137
        if proto.Cluster != _EMPTY_ {
405✔
2138
                c.leaf.remoteCluster = proto.Cluster
153✔
2139
        }
153✔
2140

2141
        c.leaf.remoteDomain = proto.Domain
252✔
2142

252✔
2143
        // When a leaf solicits a connection to a hub, the perms that it will use on the soliciting leafnode's
252✔
2144
        // behalf are correct for them, but inside the hub need to be reversed since data is flowing in the opposite direction.
252✔
2145
        if !c.isSolicitedLeafNode() && c.perms != nil {
255✔
2146
                sp, pp := c.perms.sub, c.perms.pub
3✔
2147
                c.perms.sub, c.perms.pub = pp, sp
3✔
2148
                if c.opts.Import != nil {
5✔
2149
                        c.darray = c.opts.Import.Deny
2✔
2150
                } else {
3✔
2151
                        c.darray = nil
1✔
2152
                }
1✔
2153
        }
2154

2155
        // Set the Ping timer
2156
        c.setFirstPingTimer()
252✔
2157

252✔
2158
        // If we received pub deny permissions from the other end, merge with existing ones.
252✔
2159
        c.mergeDenyPermissions(pub, proto.DenyPub)
252✔
2160

252✔
2161
        acc := c.acc
252✔
2162
        c.mu.Unlock()
252✔
2163

252✔
2164
        // Register the cluster, even if empty, as long as we are acting as a hub.
252✔
2165
        if !proto.Hub {
504✔
2166
                acc.registerLeafNodeCluster(proto.Cluster)
252✔
2167
        }
252✔
2168

2169
        // Add in the leafnode here since we passed through auth at this point.
2170
        s.addLeafNodeConnection(c, proto.Name, proto.Cluster, true)
252✔
2171

252✔
2172
        // If we have permissions bound to this leafnode we need to send then back to the
252✔
2173
        // origin server for local enforcement.
252✔
2174
        s.sendPermsAndAccountInfo(c)
252✔
2175

252✔
2176
        // Create and initialize the smap since we know our bound account now.
252✔
2177
        // This will send all registered subs too.
252✔
2178
        s.initLeafNodeSmapAndSendSubs(c)
252✔
2179

252✔
2180
        // Announce the account connect event for a leaf node.
252✔
2181
        // This will be a no-op as needed.
252✔
2182
        s.sendLeafNodeConnect(c.acc)
252✔
2183

252✔
2184
        // Check to see if we need to kick any internal source or mirror consumers.
252✔
2185
        // This will be a no-op if JetStream not enabled for this server or if the bound account
252✔
2186
        // does not have jetstream.
252✔
2187
        s.checkInternalSyncConsumers(acc)
252✔
2188

252✔
2189
        return nil
252✔
2190
}
2191

2192
// checkInternalSyncConsumers
2193
func (s *Server) checkInternalSyncConsumers(acc *Account) {
749✔
2194
        // Grab our js
749✔
2195
        js := s.getJetStream()
749✔
2196

749✔
2197
        // Only applicable if we have JS and the leafnode has JS as well.
749✔
2198
        // We check for remote JS outside.
749✔
2199
        if !js.isEnabled() || acc == nil {
1,094✔
2200
                return
345✔
2201
        }
345✔
2202

2203
        // We will check all streams in our local account. They must be a leader and
2204
        // be sourcing or mirroring. We will check the external config on the stream itself
2205
        // if this is cross domain, or if the remote domain is empty, meaning we might be
2206
        // extending the system across this leafnode connection and hence we would be extending
2207
        // our own domain.
2208
        jsa := js.lookupAccount(acc)
404✔
2209
        if jsa == nil {
549✔
2210
                return
145✔
2211
        }
145✔
2212

2213
        var streams []*stream
259✔
2214
        jsa.mu.RLock()
259✔
2215
        for _, mset := range jsa.streams {
275✔
2216
                mset.cfgMu.RLock()
16✔
2217
                // We need to have a mirror or source defined.
16✔
2218
                // We do not want to force another lock here to look for leader status,
16✔
2219
                // so collect and after we release jsa will make sure.
16✔
2220
                if mset.cfg.Mirror != nil || len(mset.cfg.Sources) > 0 {
16✔
2221
                        streams = append(streams, mset)
×
2222
                }
×
2223
                mset.cfgMu.RUnlock()
16✔
2224
        }
2225
        jsa.mu.RUnlock()
259✔
2226

259✔
2227
        // Now loop through all candidates and check if we are the leader and have NOT
259✔
2228
        // created the sync up consumer.
259✔
2229
        for _, mset := range streams {
259✔
2230
                mset.retryDisconnectedSyncConsumers()
×
2231
        }
×
2232
}
2233

2234
// Returns the remote cluster name. This is set only once so does not require a lock.
2235
func (c *client) remoteCluster() string {
37,875✔
2236
        if c.leaf == nil {
37,875✔
2237
                return _EMPTY_
×
2238
        }
×
2239
        return c.leaf.remoteCluster
37,875✔
2240
}
2241

2242
// Sends back an info block to the soliciting leafnode to let it know about
2243
// its permission settings for local enforcement.
2244
func (s *Server) sendPermsAndAccountInfo(c *client) {
252✔
2245
        // Copy
252✔
2246
        s.mu.Lock()
252✔
2247
        info := s.copyLeafNodeInfo()
252✔
2248
        s.mu.Unlock()
252✔
2249
        c.mu.Lock()
252✔
2250
        info.CID = c.cid
252✔
2251
        info.Import = c.opts.Import
252✔
2252
        info.Export = c.opts.Export
252✔
2253
        info.RemoteAccount = c.acc.Name
252✔
2254
        // s.SystemAccount() uses an atomic operation and does not get the server lock, so this is safe.
252✔
2255
        info.IsSystemAccount = c.acc == s.SystemAccount()
252✔
2256
        info.ConnectInfo = true
252✔
2257
        c.enqueueProto(generateInfoJSON(info))
252✔
2258
        c.mu.Unlock()
252✔
2259
}
252✔
2260

2261
// Snapshot the current subscriptions from the sublist into our smap which
2262
// we will keep updated from now on.
2263
// Also send the registered subscriptions.
2264
func (s *Server) initLeafNodeSmapAndSendSubs(c *client) {
467✔
2265
        acc := c.acc
467✔
2266
        if acc == nil {
467✔
2267
                c.Debugf("Leafnode does not have an account bound")
×
2268
                return
×
2269
        }
×
2270
        // Collect all account subs here.
2271
        _subs := [1024]*subscription{}
467✔
2272
        subs := _subs[:0]
467✔
2273
        ims := []string{}
467✔
2274

467✔
2275
        // Hold the client lock otherwise there can be a race and miss some subs.
467✔
2276
        c.mu.Lock()
467✔
2277
        defer c.mu.Unlock()
467✔
2278

467✔
2279
        acc.mu.RLock()
467✔
2280
        accName := acc.Name
467✔
2281
        accNTag := acc.nameTag
467✔
2282

467✔
2283
        // To make printing look better when no friendly name present.
467✔
2284
        if accNTag != _EMPTY_ {
469✔
2285
                accNTag = "/" + accNTag
2✔
2286
        }
2✔
2287

2288
        // If we are solicited we only send interest for local clients.
2289
        if c.isSpokeLeafNode() {
682✔
2290
                acc.sl.localSubs(&subs, true)
215✔
2291
        } else {
467✔
2292
                acc.sl.All(&subs)
252✔
2293
        }
252✔
2294

2295
        // Check if we have an existing service import reply.
2296
        siReply := copyBytes(acc.siReply)
467✔
2297

467✔
2298
        // Since leaf nodes only send on interest, if the bound
467✔
2299
        // account has import services we need to send those over.
467✔
2300
        for isubj := range acc.imports.services {
1,955✔
2301
                if c.isSpokeLeafNode() && !c.canSubscribe(isubj) {
1,585✔
2302
                        c.Debugf("Not permitted to import service %q on behalf of %s%s", isubj, accName, accNTag)
97✔
2303
                        continue
97✔
2304
                }
2305
                ims = append(ims, isubj)
1,391✔
2306
        }
2307
        // Likewise for mappings.
2308
        for _, m := range acc.mappings {
1,475✔
2309
                if c.isSpokeLeafNode() && !c.canSubscribe(m.src) {
1,008✔
2310
                        c.Debugf("Not permitted to import mapping %q on behalf of %s%s", m.src, accName, accNTag)
×
2311
                        continue
×
2312
                }
2313
                ims = append(ims, m.src)
1,008✔
2314
        }
2315

2316
        // Create a unique subject that will be used for loop detection.
2317
        lds := acc.lds
467✔
2318
        acc.mu.RUnlock()
467✔
2319

467✔
2320
        // Check if we have to create the LDS.
467✔
2321
        if lds == _EMPTY_ {
822✔
2322
                lds = leafNodeLoopDetectionSubjectPrefix + nuid.Next()
355✔
2323
                acc.mu.Lock()
355✔
2324
                acc.lds = lds
355✔
2325
                acc.mu.Unlock()
355✔
2326
        }
355✔
2327

2328
        // Now check for gateway interest. Leafnodes will put this into
2329
        // the proper mode to propagate, but they are not held in the account.
2330
        gwsa := [16]*client{}
467✔
2331
        gws := gwsa[:0]
467✔
2332
        s.getOutboundGatewayConnections(&gws)
467✔
2333
        for _, cgw := range gws {
496✔
2334
                cgw.mu.Lock()
29✔
2335
                gw := cgw.gw
29✔
2336
                cgw.mu.Unlock()
29✔
2337
                if gw != nil {
58✔
2338
                        if ei, _ := gw.outsim.Load(accName); ei != nil {
58✔
2339
                                if e := ei.(*outsie); e != nil && e.sl != nil {
58✔
2340
                                        e.sl.All(&subs)
29✔
2341
                                }
29✔
2342
                        }
2343
                }
2344
        }
2345

2346
        applyGlobalRouting := s.gateway.enabled
467✔
2347
        if c.isSpokeLeafNode() {
682✔
2348
                // Add a fake subscription for this solicited leafnode connection
215✔
2349
                // so that we can send back directly for mapped GW replies.
215✔
2350
                // We need to keep track of this subscription so it can be removed
215✔
2351
                // when the connection is closed so that the GC can release it.
215✔
2352
                c.leaf.gwSub = &subscription{client: c, subject: []byte(gwReplyPrefix + ">")}
215✔
2353
                c.srv.gwLeafSubs.Insert(c.leaf.gwSub)
215✔
2354
        }
215✔
2355

2356
        // Now walk the results and add them to our smap
2357
        rc := c.leaf.remoteCluster
467✔
2358
        c.leaf.smap = make(map[string]int32)
467✔
2359
        for _, sub := range subs {
20,882✔
2360
                // Check perms regardless of role.
20,415✔
2361
                if c.perms != nil && !c.canSubscribe(string(sub.subject)) {
21,559✔
2362
                        c.Debugf("Not permitted to subscribe to %q on behalf of %s%s", sub.subject, accName, accNTag)
1,144✔
2363
                        continue
1,144✔
2364
                }
2365
                // Don't advertise interest from leafnodes to other isolated leafnodes.
2366
                if sub.client.kind == LEAF && c.isIsolatedLeafNode() {
19,271✔
2367
                        continue
×
2368
                }
2369
                // We ignore ourselves here.
2370
                // Also don't add the subscription if it has a origin cluster and the
2371
                // cluster name matches the one of the client we are sending to.
2372
                if c != sub.client && (sub.origin == nil || (bytesToString(sub.origin) != rc)) {
35,207✔
2373
                        count := int32(1)
15,936✔
2374
                        if len(sub.queue) > 0 && sub.qw > 0 {
15,943✔
2375
                                count = sub.qw
7✔
2376
                        }
7✔
2377
                        c.leaf.smap[keyFromSub(sub)] += count
15,936✔
2378
                        if c.leaf.tsub == nil {
16,345✔
2379
                                c.leaf.tsub = make(map[*subscription]struct{})
409✔
2380
                        }
409✔
2381
                        c.leaf.tsub[sub] = struct{}{}
15,936✔
2382
                }
2383
        }
2384
        // FIXME(dlc) - We need to update appropriately on an account claims update.
2385
        for _, isubj := range ims {
2,866✔
2386
                c.leaf.smap[isubj]++
2,399✔
2387
        }
2,399✔
2388
        // If we have gateways enabled we need to make sure the other side sends us responses
2389
        // that have been augmented from the original subscription.
2390
        // TODO(dlc) - Should we lock this down more?
2391
        if applyGlobalRouting {
497✔
2392
                c.leaf.smap[oldGWReplyPrefix+"*.>"]++
30✔
2393
                c.leaf.smap[gwReplyPrefix+">"]++
30✔
2394
        }
30✔
2395
        // Detect loops by subscribing to a specific subject and checking
2396
        // if this sub is coming back to us.
2397
        c.leaf.smap[lds]++
467✔
2398

467✔
2399
        // Check if we need to add an existing siReply to our map.
467✔
2400
        // This will be a prefix so add on the wildcard.
467✔
2401
        if siReply != nil {
473✔
2402
                wcsub := append(siReply, '>')
6✔
2403
                c.leaf.smap[string(wcsub)]++
6✔
2404
        }
6✔
2405
        // Queue all protocols. There is no max pending limit for LN connection,
2406
        // so we don't need chunking. The writes will happen from the writeLoop.
2407
        var b bytes.Buffer
467✔
2408
        for key, n := range c.leaf.smap {
13,154✔
2409
                c.writeLeafSub(&b, key, n)
12,687✔
2410
        }
12,687✔
2411
        if b.Len() > 0 {
934✔
2412
                c.enqueueProto(b.Bytes())
467✔
2413
        }
467✔
2414
        if c.leaf.tsub != nil {
877✔
2415
                // Clear the tsub map after 5 seconds.
410✔
2416
                c.leaf.tsubt = time.AfterFunc(5*time.Second, func() {
425✔
2417
                        c.mu.Lock()
15✔
2418
                        if c.leaf != nil {
30✔
2419
                                c.leaf.tsub = nil
15✔
2420
                                c.leaf.tsubt = nil
15✔
2421
                        }
15✔
2422
                        c.mu.Unlock()
15✔
2423
                })
2424
        }
2425
}
2426

2427
// updateInterestForAccountOnGateway called from gateway code when processing RS+ and RS-.
2428
func (s *Server) updateInterestForAccountOnGateway(accName string, sub *subscription, delta int32) {
65,974✔
2429
        // Since we're in the gateway's readLoop, and we would otherwise block, don't allow fetching.
65,974✔
2430
        acc, err := s.lookupOrFetchAccount(accName, false)
65,974✔
2431
        if acc == nil || err != nil {
66,135✔
2432
                s.Debugf("No or bad account for %q, failed to update interest from gateway", accName)
161✔
2433
                return
161✔
2434
        }
161✔
2435
        acc.updateLeafNodes(sub, delta)
65,813✔
2436
}
2437

2438
// updateLeafNodesEx will make sure to update the account smap for the subscription.
2439
// Will also forward to all leaf nodes as needed.
2440
// If `hubOnly` is true, then will update only leaf nodes that connect to this server
2441
// (that is, for which this server acts as a hub to them).
2442
func (acc *Account) updateLeafNodesEx(sub *subscription, delta int32, hubOnly bool) {
1,577,298✔
2443
        if acc == nil || sub == nil {
1,577,298✔
2444
                return
×
2445
        }
×
2446

2447
        // We will do checks for no leafnodes and same cluster here inline and under the
2448
        // general account read lock.
2449
        // If we feel we need to update the leafnodes we will do that out of line to avoid
2450
        // blocking routes or GWs.
2451

2452
        acc.mu.RLock()
1,577,298✔
2453
        // First check if we even have leafnodes here.
1,577,298✔
2454
        if acc.nleafs == 0 {
3,124,514✔
2455
                acc.mu.RUnlock()
1,547,216✔
2456
                return
1,547,216✔
2457
        }
1,547,216✔
2458

2459
        // Is this a loop detection subject.
2460
        isLDS := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
30,082✔
2461

30,082✔
2462
        // Capture the cluster even if its empty.
30,082✔
2463
        var cluster string
30,082✔
2464
        if sub.origin != nil {
53,604✔
2465
                cluster = bytesToString(sub.origin)
23,522✔
2466
        }
23,522✔
2467

2468
        // If we have an isolated cluster we can return early, as long as it is not a loop detection subject.
2469
        // Empty clusters will return false for the check.
2470
        if !isLDS && acc.isLeafNodeClusterIsolated(cluster) {
38,167✔
2471
                acc.mu.RUnlock()
8,085✔
2472
                return
8,085✔
2473
        }
8,085✔
2474

2475
        // We can release the general account lock.
2476
        acc.mu.RUnlock()
21,997✔
2477

21,997✔
2478
        // We can hold the list lock here to avoid having to copy a large slice.
21,997✔
2479
        acc.lmu.RLock()
21,997✔
2480
        defer acc.lmu.RUnlock()
21,997✔
2481

21,997✔
2482
        // Do this once.
21,997✔
2483
        subject := string(sub.subject)
21,997✔
2484

21,997✔
2485
        // Walk the connected leafnodes.
21,997✔
2486
        for _, ln := range acc.lleafs {
50,969✔
2487
                if ln == sub.client {
43,431✔
2488
                        continue
14,459✔
2489
                }
2490
                ln.mu.Lock()
14,513✔
2491
                // Don't advertise interest from leafnodes to other isolated leafnodes.
14,513✔
2492
                if sub.client.kind == LEAF && ln.isIsolatedLeafNode() {
14,513✔
2493
                        ln.mu.Unlock()
×
2494
                        continue
×
2495
                }
2496
                // If `hubOnly` is true, it means that we want to update only leafnodes
2497
                // that connect to this server (so isHubLeafNode() would return `true`).
2498
                if hubOnly && !ln.isHubLeafNode() {
14,519✔
2499
                        ln.mu.Unlock()
6✔
2500
                        continue
6✔
2501
                }
2502
                // Check to make sure this sub does not have an origin cluster that matches the leafnode.
2503
                // If skipped, make sure that we still let go the "$LDS." subscription that allows
2504
                // the detection of loops as long as different cluster.
2505
                clusterDifferent := cluster != ln.remoteCluster()
14,507✔
2506
                if (isLDS && clusterDifferent) || ((cluster == _EMPTY_ || clusterDifferent) && (delta <= 0 || ln.canSubscribe(subject))) {
26,761✔
2507
                        ln.updateSmap(sub, delta, isLDS)
12,254✔
2508
                }
12,254✔
2509
                ln.mu.Unlock()
14,507✔
2510
        }
2511
}
2512

2513
// updateLeafNodes will make sure to update the account smap for the subscription.
2514
// Will also forward to all leaf nodes as needed.
2515
func (acc *Account) updateLeafNodes(sub *subscription, delta int32) {
1,577,291✔
2516
        acc.updateLeafNodesEx(sub, delta, false)
1,577,291✔
2517
}
1,577,291✔
2518

2519
// This will make an update to our internal smap and determine if we should send out
2520
// an interest update to the remote side.
2521
// Lock should be held.
2522
func (c *client) updateSmap(sub *subscription, delta int32, isLDS bool) {
12,254✔
2523
        if c.leaf.smap == nil {
12,270✔
2524
                return
16✔
2525
        }
16✔
2526

2527
        // If we are solicited make sure this is a local client or a non-solicited leaf node
2528
        skind := sub.client.kind
12,238✔
2529
        updateClient := skind == CLIENT || skind == SYSTEM || skind == JETSTREAM || skind == ACCOUNT
12,238✔
2530
        if !isLDS && c.isSpokeLeafNode() && !(updateClient || (skind == LEAF && !sub.client.isSpokeLeafNode())) {
16,065✔
2531
                return
3,827✔
2532
        }
3,827✔
2533

2534
        // For additions, check if that sub has just been processed during initLeafNodeSmapAndSendSubs
2535
        if delta > 0 && c.leaf.tsub != nil {
12,443✔
2536
                if _, present := c.leaf.tsub[sub]; present {
4,033✔
2537
                        delete(c.leaf.tsub, sub)
1✔
2538
                        if len(c.leaf.tsub) == 0 {
1✔
2539
                                c.leaf.tsub = nil
×
2540
                                c.leaf.tsubt.Stop()
×
2541
                                c.leaf.tsubt = nil
×
2542
                        }
×
2543
                        return
1✔
2544
                }
2545
        }
2546

2547
        key := keyFromSub(sub)
8,410✔
2548
        n, ok := c.leaf.smap[key]
8,410✔
2549
        if delta < 0 && !ok {
8,784✔
2550
                return
374✔
2551
        }
374✔
2552

2553
        // We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
2554
        update := sub.queue != nil || (n <= 0 && n+delta > 0) || (n > 0 && n+delta <= 0)
8,036✔
2555
        n += delta
8,036✔
2556
        if n > 0 {
14,161✔
2557
                c.leaf.smap[key] = n
6,125✔
2558
        } else {
8,036✔
2559
                delete(c.leaf.smap, key)
1,911✔
2560
        }
1,911✔
2561
        if update {
12,021✔
2562
                c.sendLeafNodeSubUpdate(key, n)
3,985✔
2563
        }
3,985✔
2564
}
2565

2566
// Used to force add subjects to the subject map.
2567
func (c *client) forceAddToSmap(subj string) {
2✔
2568
        c.mu.Lock()
2✔
2569
        defer c.mu.Unlock()
2✔
2570

2✔
2571
        if c.leaf.smap == nil {
2✔
2572
                return
×
2573
        }
×
2574
        n := c.leaf.smap[subj]
2✔
2575
        if n != 0 {
2✔
2576
                return
×
2577
        }
×
2578
        // Place into the map since it was not there.
2579
        c.leaf.smap[subj] = 1
2✔
2580
        c.sendLeafNodeSubUpdate(subj, 1)
2✔
2581
}
2582

2583
// Used to force remove a subject from the subject map.
2584
func (c *client) forceRemoveFromSmap(subj string) {
×
2585
        c.mu.Lock()
×
2586
        defer c.mu.Unlock()
×
2587

×
2588
        if c.leaf.smap == nil {
×
2589
                return
×
2590
        }
×
2591
        n := c.leaf.smap[subj]
×
2592
        if n == 0 {
×
2593
                return
×
2594
        }
×
2595
        n--
×
2596
        if n == 0 {
×
2597
                // Remove is now zero
×
2598
                delete(c.leaf.smap, subj)
×
2599
                c.sendLeafNodeSubUpdate(subj, 0)
×
2600
        } else {
×
2601
                c.leaf.smap[subj] = n
×
2602
        }
×
2603
}
2604

2605
// Send the subscription interest change to the other side.
2606
// Lock should be held.
2607
func (c *client) sendLeafNodeSubUpdate(key string, n int32) {
3,987✔
2608
        // If we are a spoke, we need to check if we are allowed to send this subscription over to the hub.
3,987✔
2609
        if c.isSpokeLeafNode() {
4,575✔
2610
                checkPerms := true
588✔
2611
                if len(key) > 0 && (key[0] == '$' || key[0] == '_') {
1,079✔
2612
                        if strings.HasPrefix(key, leafNodeLoopDetectionSubjectPrefix) ||
491✔
2613
                                strings.HasPrefix(key, oldGWReplyPrefix) ||
491✔
2614
                                strings.HasPrefix(key, gwReplyPrefix) {
529✔
2615
                                checkPerms = false
38✔
2616
                        }
38✔
2617
                }
2618
                if checkPerms {
1,138✔
2619
                        var subject string
550✔
2620
                        if sep := strings.IndexByte(key, ' '); sep != -1 {
564✔
2621
                                subject = key[:sep]
14✔
2622
                        } else {
550✔
2623
                                subject = key
536✔
2624
                        }
536✔
2625
                        if !c.canSubscribe(subject) {
550✔
2626
                                return
×
2627
                        }
×
2628
                }
2629
        }
2630
        // If we are here we can send over to the other side.
2631
        _b := [64]byte{}
3,987✔
2632
        b := bytes.NewBuffer(_b[:0])
3,987✔
2633
        c.writeLeafSub(b, key, n)
3,987✔
2634
        c.enqueueProto(b.Bytes())
3,987✔
2635
}
2636

2637
// Helper function to build the key.
2638
func keyFromSub(sub *subscription) string {
25,121✔
2639
        var sb strings.Builder
25,121✔
2640
        sb.Grow(len(sub.subject) + len(sub.queue) + 1)
25,121✔
2641
        sb.Write(sub.subject)
25,121✔
2642
        if sub.queue != nil {
25,956✔
2643
                // Just make the key subject spc group, e.g. 'foo bar'
835✔
2644
                sb.WriteByte(' ')
835✔
2645
                sb.Write(sub.queue)
835✔
2646
        }
835✔
2647
        return sb.String()
25,121✔
2648
}
2649

2650
const (
2651
        keyRoutedSub         = "R"
2652
        keyRoutedSubByte     = 'R'
2653
        keyRoutedLeafSub     = "L"
2654
        keyRoutedLeafSubByte = 'L'
2655
)
2656

2657
// Helper function to build the key that prevents collisions between normal
2658
// routed subscriptions and routed subscriptions on behalf of a leafnode.
2659
// Keys will look like this:
2660
// "R foo"          -> plain routed sub on "foo"
2661
// "R foo bar"      -> queue routed sub on "foo", queue "bar"
2662
// "L foo bar"      -> plain routed leaf sub on "foo", leaf "bar"
2663
// "L foo bar baz"  -> queue routed sub on "foo", queue "bar", leaf "baz"
2664
func keyFromSubWithOrigin(sub *subscription) string {
529,113✔
2665
        var sb strings.Builder
529,113✔
2666
        sb.Grow(2 + len(sub.origin) + 1 + len(sub.subject) + 1 + len(sub.queue))
529,113✔
2667
        leaf := len(sub.origin) > 0
529,113✔
2668
        if leaf {
537,116✔
2669
                sb.WriteByte(keyRoutedLeafSubByte)
8,003✔
2670
        } else {
529,113✔
2671
                sb.WriteByte(keyRoutedSubByte)
521,110✔
2672
        }
521,110✔
2673
        sb.WriteByte(' ')
529,113✔
2674
        sb.Write(sub.subject)
529,113✔
2675
        if sub.queue != nil {
549,670✔
2676
                sb.WriteByte(' ')
20,557✔
2677
                sb.Write(sub.queue)
20,557✔
2678
        }
20,557✔
2679
        if leaf {
537,116✔
2680
                sb.WriteByte(' ')
8,003✔
2681
                sb.Write(sub.origin)
8,003✔
2682
        }
8,003✔
2683
        return sb.String()
529,113✔
2684
}
2685

2686
// Lock should be held.
2687
func (c *client) writeLeafSub(w *bytes.Buffer, key string, n int32) {
16,674✔
2688
        if key == _EMPTY_ {
16,674✔
2689
                return
×
2690
        }
×
2691
        if n > 0 {
31,437✔
2692
                w.WriteString("LS+ " + key)
14,763✔
2693
                // Check for queue semantics, if found write n.
14,763✔
2694
                if strings.Contains(key, " ") {
14,805✔
2695
                        w.WriteString(" ")
42✔
2696
                        var b [12]byte
42✔
2697
                        var i = len(b)
42✔
2698
                        for l := n; l > 0; l /= 10 {
84✔
2699
                                i--
42✔
2700
                                b[i] = digits[l%10]
42✔
2701
                        }
42✔
2702
                        w.Write(b[i:])
42✔
2703
                        if c.trace {
42✔
2704
                                arg := fmt.Sprintf("%s %d", key, n)
×
2705
                                c.traceOutOp("LS+", []byte(arg))
×
2706
                        }
×
2707
                } else if c.trace {
14,721✔
2708
                        c.traceOutOp("LS+", []byte(key))
×
2709
                }
×
2710
        } else {
1,911✔
2711
                w.WriteString("LS- " + key)
1,911✔
2712
                if c.trace {
1,911✔
2713
                        c.traceOutOp("LS-", []byte(key))
×
2714
                }
×
2715
        }
2716
        w.WriteString(CR_LF)
16,674✔
2717
}
2718

2719
// processLeafSub will process an inbound sub request for the remote leaf node.
2720
func (c *client) processLeafSub(argo []byte) (err error) {
14,537✔
2721
        // Indicate activity.
14,537✔
2722
        c.in.subs++
14,537✔
2723

14,537✔
2724
        srv := c.srv
14,537✔
2725
        if srv == nil {
14,537✔
2726
                return nil
×
2727
        }
×
2728

2729
        // Copy so we do not reference a potentially large buffer
2730
        arg := make([]byte, len(argo))
14,537✔
2731
        copy(arg, argo)
14,537✔
2732

14,537✔
2733
        args := splitArg(arg)
14,537✔
2734
        sub := &subscription{client: c}
14,537✔
2735

14,537✔
2736
        delta := int32(1)
14,537✔
2737
        switch len(args) {
14,537✔
2738
        case 1:
14,506✔
2739
                sub.queue = nil
14,506✔
2740
        case 3:
31✔
2741
                sub.queue = args[1]
31✔
2742
                sub.qw = int32(parseSize(args[2]))
31✔
2743
                // TODO: (ik) We should have a non empty queue name and a queue
31✔
2744
                // weight >= 1. For 2.11, we may want to return an error if that
31✔
2745
                // is not the case, but for now just overwrite `delta` if queue
31✔
2746
                // weight is greater than 1 (it is possible after a reconnect/
31✔
2747
                // server restart to receive a queue weight > 1 for a new sub).
31✔
2748
                if sub.qw > 1 {
52✔
2749
                        delta = sub.qw
21✔
2750
                }
21✔
2751
        default:
×
2752
                return fmt.Errorf("processLeafSub Parse Error: '%s'", arg)
×
2753
        }
2754
        sub.subject = args[0]
14,537✔
2755

14,537✔
2756
        c.mu.Lock()
14,537✔
2757
        if c.isClosed() {
14,537✔
2758
                c.mu.Unlock()
×
2759
                return nil
×
2760
        }
×
2761

2762
        acc := c.acc
14,537✔
2763
        // Check if we have a loop.
14,537✔
2764
        ldsPrefix := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix))
14,537✔
2765

14,537✔
2766
        if ldsPrefix && bytesToString(sub.subject) == acc.getLDSubject() {
14,537✔
2767
                c.mu.Unlock()
×
2768
                c.handleLeafNodeLoop(true)
×
2769
                return nil
×
2770
        }
×
2771

2772
        // Check permissions if applicable. (but exclude the $LDS, $GR and _GR_)
2773
        checkPerms := true
14,537✔
2774
        if sub.subject[0] == '$' || sub.subject[0] == '_' {
28,895✔
2775
                if ldsPrefix ||
14,358✔
2776
                        bytes.HasPrefix(sub.subject, []byte(oldGWReplyPrefix)) ||
14,358✔
2777
                        bytes.HasPrefix(sub.subject, []byte(gwReplyPrefix)) {
15,232✔
2778
                        checkPerms = false
874✔
2779
                }
874✔
2780
        }
2781

2782
        // If we are a hub check that we can publish to this subject.
2783
        if checkPerms {
28,200✔
2784
                subj := string(sub.subject)
13,663✔
2785
                if subjectIsLiteral(subj) && !c.pubAllowedFullCheck(subj, true, true) {
13,663✔
2786
                        c.mu.Unlock()
×
2787
                        c.leafSubPermViolation(sub.subject)
×
2788
                        c.Debugf(fmt.Sprintf("Permissions Violation for Subscription to %q", sub.subject))
×
2789
                        return nil
×
2790
                }
×
2791
        }
2792

2793
        // Check if we have a maximum on the number of subscriptions.
2794
        if c.subsAtLimit() {
14,545✔
2795
                c.mu.Unlock()
8✔
2796
                c.maxSubsExceeded()
8✔
2797
                return nil
8✔
2798
        }
8✔
2799

2800
        // If we have an origin cluster associated mark that in the sub.
2801
        if rc := c.remoteCluster(); rc != _EMPTY_ {
28,199✔
2802
                sub.origin = []byte(rc)
13,670✔
2803
        }
13,670✔
2804

2805
        // Like Routes, we store local subs by account and subject and optionally queue name.
2806
        // If we have a queue it will have a trailing weight which we do not want.
2807
        if sub.queue != nil {
14,560✔
2808
                sub.sid = arg[:len(arg)-len(args[2])-1]
31✔
2809
        } else {
14,529✔
2810
                sub.sid = arg
14,498✔
2811
        }
14,498✔
2812
        key := bytesToString(sub.sid)
14,529✔
2813
        osub := c.subs[key]
14,529✔
2814
        if osub == nil {
29,042✔
2815
                c.subs[key] = sub
14,513✔
2816
                // Now place into the account sl.
14,513✔
2817
                if err := acc.sl.Insert(sub); err != nil {
14,513✔
2818
                        delete(c.subs, key)
×
2819
                        c.mu.Unlock()
×
2820
                        c.Errorf("Could not insert subscription: %v", err)
×
2821
                        c.sendErr("Invalid Subscription")
×
2822
                        return nil
×
2823
                }
×
2824
        } else if sub.queue != nil {
31✔
2825
                // For a queue we need to update the weight.
15✔
2826
                delta = sub.qw - atomic.LoadInt32(&osub.qw)
15✔
2827
                atomic.StoreInt32(&osub.qw, sub.qw)
15✔
2828
                acc.sl.UpdateRemoteQSub(osub)
15✔
2829
        }
15✔
2830
        spoke := c.isSpokeLeafNode()
14,529✔
2831
        c.mu.Unlock()
14,529✔
2832

14,529✔
2833
        // Only add in shadow subs if a new sub or qsub.
14,529✔
2834
        if osub == nil {
29,042✔
2835
                if err := c.addShadowSubscriptions(acc, sub, true); err != nil {
14,513✔
2836
                        c.Errorf(err.Error())
×
2837
                }
×
2838
        }
2839

2840
        // If we are not solicited, treat leaf node subscriptions similar to a
2841
        // client subscription, meaning we forward them to routes, gateways and
2842
        // other leaf nodes as needed.
2843
        if !spoke {
19,107✔
2844
                // If we are routing add to the route map for the associated account.
4,578✔
2845
                srv.updateRouteSubscriptionMap(acc, sub, delta)
4,578✔
2846
                if srv.gateway.enabled {
4,713✔
2847
                        srv.gatewayUpdateSubInterest(acc.Name, sub, delta)
135✔
2848
                }
135✔
2849
        }
2850
        // Now check on leafnode updates for other leaf nodes. We understand solicited
2851
        // and non-solicited state in this call so we will do the right thing.
2852
        acc.updateLeafNodes(sub, delta)
14,529✔
2853

14,529✔
2854
        return nil
14,529✔
2855
}
2856

2857
// If the leafnode is a solicited, set the connect delay based on default
2858
// or private option (for tests). Sends the error to the other side, log and
2859
// close the connection.
2860
func (c *client) handleLeafNodeLoop(sendErr bool) {
×
2861
        accName, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterLoopDetected)
×
2862
        errTxt := fmt.Sprintf("Loop detected for leafnode account=%q. Delaying attempt to reconnect for %v", accName, delay)
×
2863
        if sendErr {
×
2864
                c.sendErr(errTxt)
×
2865
        }
×
2866

2867
        c.Errorf(errTxt)
×
2868
        // If we are here with "sendErr" false, it means that this is the server
×
2869
        // that received the error. The other side will have closed the connection,
×
2870
        // but does not hurt to close here too.
×
2871
        c.closeConnection(ProtocolViolation)
×
2872
}
2873

2874
// processLeafUnsub will process an inbound unsub request for the remote leaf node.
2875
func (c *client) processLeafUnsub(arg []byte) error {
1,783✔
2876
        // Indicate any activity, so pub and sub or unsubs.
1,783✔
2877
        c.in.subs++
1,783✔
2878

1,783✔
2879
        acc := c.acc
1,783✔
2880
        srv := c.srv
1,783✔
2881

1,783✔
2882
        c.mu.Lock()
1,783✔
2883
        if c.isClosed() {
1,802✔
2884
                c.mu.Unlock()
19✔
2885
                return nil
19✔
2886
        }
19✔
2887

2888
        spoke := c.isSpokeLeafNode()
1,764✔
2889
        // We store local subs by account and subject and optionally queue name.
1,764✔
2890
        // LS- will have the arg exactly as the key.
1,764✔
2891
        sub, ok := c.subs[string(arg)]
1,764✔
2892
        if !ok {
1,768✔
2893
                // If not found, don't try to update routes/gws/leaf nodes.
4✔
2894
                c.mu.Unlock()
4✔
2895
                return nil
4✔
2896
        }
4✔
2897
        delta := int32(1)
1,760✔
2898
        if len(sub.queue) > 0 {
1,766✔
2899
                delta = sub.qw
6✔
2900
        }
6✔
2901
        c.mu.Unlock()
1,760✔
2902

1,760✔
2903
        c.unsubscribe(acc, sub, true, true)
1,760✔
2904
        if !spoke {
2,040✔
2905
                // If we are routing subtract from the route map for the associated account.
280✔
2906
                srv.updateRouteSubscriptionMap(acc, sub, -delta)
280✔
2907
                // Gateways
280✔
2908
                if srv.gateway.enabled {
292✔
2909
                        srv.gatewayUpdateSubInterest(acc.Name, sub, -delta)
12✔
2910
                }
12✔
2911
        }
2912
        // Now check on leafnode updates for other leaf nodes.
2913
        acc.updateLeafNodes(sub, -delta)
1,760✔
2914
        return nil
1,760✔
2915
}
2916

2917
func (c *client) processLeafHeaderMsgArgs(arg []byte) error {
34✔
2918
        // Unroll splitArgs to avoid runtime/heap issues
34✔
2919
        a := [MAX_MSG_ARGS][]byte{}
34✔
2920
        args := a[:0]
34✔
2921
        start := -1
34✔
2922
        for i, b := range arg {
1,532✔
2923
                switch b {
1,498✔
2924
                case ' ', '\t', '\r', '\n':
103✔
2925
                        if start >= 0 {
206✔
2926
                                args = append(args, arg[start:i])
103✔
2927
                                start = -1
103✔
2928
                        }
103✔
2929
                default:
1,395✔
2930
                        if start < 0 {
1,532✔
2931
                                start = i
137✔
2932
                        }
137✔
2933
                }
2934
        }
2935
        if start >= 0 {
68✔
2936
                args = append(args, arg[start:])
34✔
2937
        }
34✔
2938

2939
        c.pa.arg = arg
34✔
2940
        switch len(args) {
34✔
2941
        case 0, 1, 2:
×
2942
                return fmt.Errorf("processLeafHeaderMsgArgs Parse Error: '%s'", args)
×
2943
        case 3:
4✔
2944
                c.pa.reply = nil
4✔
2945
                c.pa.queues = nil
4✔
2946
                c.pa.hdb = args[1]
4✔
2947
                c.pa.hdr = parseSize(args[1])
4✔
2948
                c.pa.szb = args[2]
4✔
2949
                c.pa.size = parseSize(args[2])
4✔
2950
        case 4:
27✔
2951
                c.pa.reply = args[1]
27✔
2952
                c.pa.queues = nil
27✔
2953
                c.pa.hdb = args[2]
27✔
2954
                c.pa.hdr = parseSize(args[2])
27✔
2955
                c.pa.szb = args[3]
27✔
2956
                c.pa.size = parseSize(args[3])
27✔
2957
        default:
3✔
2958
                // args[1] is our reply indicator. Should be + or | normally.
3✔
2959
                if len(args[1]) != 1 {
3✔
2960
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2961
                }
×
2962
                switch args[1][0] {
3✔
2963
                case '+':
2✔
2964
                        c.pa.reply = args[2]
2✔
2965
                case '|':
1✔
2966
                        c.pa.reply = nil
1✔
2967
                default:
×
2968
                        return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
2969
                }
2970
                // Grab header size.
2971
                c.pa.hdb = args[len(args)-2]
3✔
2972
                c.pa.hdr = parseSize(c.pa.hdb)
3✔
2973

3✔
2974
                // Grab size.
3✔
2975
                c.pa.szb = args[len(args)-1]
3✔
2976
                c.pa.size = parseSize(c.pa.szb)
3✔
2977

3✔
2978
                // Grab queue names.
3✔
2979
                if c.pa.reply != nil {
5✔
2980
                        c.pa.queues = args[3 : len(args)-2]
2✔
2981
                } else {
3✔
2982
                        c.pa.queues = args[2 : len(args)-2]
1✔
2983
                }
1✔
2984
        }
2985
        if c.pa.hdr < 0 {
34✔
2986
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Header Size: '%s'", arg)
×
2987
        }
×
2988
        if c.pa.size < 0 {
34✔
2989
                return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Size: '%s'", args)
×
2990
        }
×
2991
        if c.pa.hdr > c.pa.size {
34✔
2992
                return fmt.Errorf("processLeafHeaderMsgArgs Header Size larger then TotalSize: '%s'", arg)
×
2993
        }
×
2994

2995
        // Common ones processed after check for arg length
2996
        c.pa.subject = args[0]
34✔
2997

34✔
2998
        return nil
34✔
2999
}
3000

3001
func (c *client) processLeafMsgArgs(arg []byte) error {
4,660✔
3002
        // Unroll splitArgs to avoid runtime/heap issues
4,660✔
3003
        a := [MAX_MSG_ARGS][]byte{}
4,660✔
3004
        args := a[:0]
4,660✔
3005
        start := -1
4,660✔
3006
        for i, b := range arg {
262,789✔
3007
                switch b {
258,129✔
3008
                case ' ', '\t', '\r', '\n':
5,763✔
3009
                        if start >= 0 {
11,526✔
3010
                                args = append(args, arg[start:i])
5,763✔
3011
                                start = -1
5,763✔
3012
                        }
5,763✔
3013
                default:
252,366✔
3014
                        if start < 0 {
262,789✔
3015
                                start = i
10,423✔
3016
                        }
10,423✔
3017
                }
3018
        }
3019
        if start >= 0 {
9,320✔
3020
                args = append(args, arg[start:])
4,660✔
3021
        }
4,660✔
3022

3023
        c.pa.arg = arg
4,660✔
3024
        switch len(args) {
4,660✔
3025
        case 0, 1:
×
3026
                return fmt.Errorf("processLeafMsgArgs Parse Error: '%s'", args)
×
3027
        case 2:
3,570✔
3028
                c.pa.reply = nil
3,570✔
3029
                c.pa.queues = nil
3,570✔
3030
                c.pa.szb = args[1]
3,570✔
3031
                c.pa.size = parseSize(args[1])
3,570✔
3032
        case 3:
1,083✔
3033
                c.pa.reply = args[1]
1,083✔
3034
                c.pa.queues = nil
1,083✔
3035
                c.pa.szb = args[2]
1,083✔
3036
                c.pa.size = parseSize(args[2])
1,083✔
3037
        default:
7✔
3038
                // args[1] is our reply indicator. Should be + or | normally.
7✔
3039
                if len(args[1]) != 1 {
7✔
3040
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3041
                }
×
3042
                switch args[1][0] {
7✔
3043
                case '+':
6✔
3044
                        c.pa.reply = args[2]
6✔
3045
                case '|':
1✔
3046
                        c.pa.reply = nil
1✔
3047
                default:
×
3048
                        return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1])
×
3049
                }
3050
                // Grab size.
3051
                c.pa.szb = args[len(args)-1]
7✔
3052
                c.pa.size = parseSize(c.pa.szb)
7✔
3053

7✔
3054
                // Grab queue names.
7✔
3055
                if c.pa.reply != nil {
13✔
3056
                        c.pa.queues = args[3 : len(args)-1]
6✔
3057
                } else {
7✔
3058
                        c.pa.queues = args[2 : len(args)-1]
1✔
3059
                }
1✔
3060
        }
3061
        if c.pa.size < 0 {
4,660✔
3062
                return fmt.Errorf("processLeafMsgArgs Bad or Missing Size: '%s'", args)
×
3063
        }
×
3064

3065
        // Common ones processed after check for arg length
3066
        c.pa.subject = args[0]
4,660✔
3067

4,660✔
3068
        return nil
4,660✔
3069
}
3070

3071
// processInboundLeafMsg is called to process an inbound msg from a leaf node.
3072
func (c *client) processInboundLeafMsg(msg []byte) {
4,134✔
3073
        // Update statistics
4,134✔
3074
        // The msg includes the CR_LF, so pull back out for accounting.
4,134✔
3075
        c.in.msgs++
4,134✔
3076
        c.in.bytes += int32(len(msg) - LEN_CR_LF)
4,134✔
3077

4,134✔
3078
        srv, acc, subject := c.srv, c.acc, string(c.pa.subject)
4,134✔
3079

4,134✔
3080
        // Mostly under testing scenarios.
4,134✔
3081
        if srv == nil || acc == nil {
4,134✔
3082
                return
×
3083
        }
×
3084

3085
        // Match the subscriptions. We will use our own L1 map if
3086
        // it's still valid, avoiding contention on the shared sublist.
3087
        var r *SublistResult
4,134✔
3088
        var ok bool
4,134✔
3089

4,134✔
3090
        genid := atomic.LoadUint64(&c.acc.sl.genid)
4,134✔
3091
        if genid == c.in.genid && c.in.results != nil {
7,346✔
3092
                r, ok = c.in.results[subject]
3,212✔
3093
        } else {
4,134✔
3094
                // Reset our L1 completely.
922✔
3095
                c.in.results = make(map[string]*SublistResult)
922✔
3096
                c.in.genid = genid
922✔
3097
        }
922✔
3098

3099
        // Go back to the sublist data structure.
3100
        if !ok {
6,295✔
3101
                r = c.acc.sl.Match(subject)
2,161✔
3102
                // Prune the results cache. Keeps us from unbounded growth. Random delete.
2,161✔
3103
                if len(c.in.results) >= maxResultCacheSize {
2,161✔
3104
                        n := 0
×
3105
                        for subj := range c.in.results {
×
3106
                                delete(c.in.results, subj)
×
3107
                                if n++; n > pruneSize {
×
3108
                                        break
×
3109
                                }
3110
                        }
3111
                }
3112
                // Then add the new cache entry.
3113
                c.in.results[subject] = r
2,161✔
3114
        }
3115

3116
        // Collect queue names if needed.
3117
        var qnames [][]byte
4,134✔
3118

4,134✔
3119
        // Check for no interest, short circuit if so.
4,134✔
3120
        // This is the fanout scale.
4,134✔
3121
        if len(r.psubs)+len(r.qsubs) > 0 {
8,255✔
3122
                flag := pmrNoFlag
4,121✔
3123
                // If we have queue subs in this cluster, then if we run in gateway
4,121✔
3124
                // mode and the remote gateways have queue subs, then we need to
4,121✔
3125
                // collect the queue groups this message was sent to so that we
4,121✔
3126
                // exclude them when sending to gateways.
4,121✔
3127
                if len(r.qsubs) > 0 && c.srv.gateway.enabled &&
4,121✔
3128
                        atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 {
4,123✔
3129
                        flag |= pmrCollectQueueNames
2✔
3130
                }
2✔
3131
                // If this is a mapped subject that means the mapped interest
3132
                // is what got us here, but this might not have a queue designation
3133
                // If that is the case, make sure we ignore to process local queue subscribers.
3134
                if len(c.pa.mapped) > 0 && len(c.pa.queues) == 0 {
4,197✔
3135
                        flag |= pmrIgnoreEmptyQueueFilter
76✔
3136
                }
76✔
3137
                _, qnames = c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, flag)
4,121✔
3138
        }
3139

3140
        // Now deal with gateways
3141
        if c.srv.gateway.enabled {
4,558✔
3142
                c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, qnames, true)
424✔
3143
        }
424✔
3144
}
3145

3146
// Handles a subscription permission violation.
3147
// See leafPermViolation() for details.
3148
func (c *client) leafSubPermViolation(subj []byte) {
×
3149
        c.leafPermViolation(false, subj)
×
3150
}
×
3151

3152
// Common function to process publish or subscribe leafnode permission violation.
3153
// Sends the permission violation error to the remote, logs it and closes the connection.
3154
// If this is from a server soliciting, the reconnection will be delayed.
3155
func (c *client) leafPermViolation(pub bool, subj []byte) {
×
3156
        if c.isSpokeLeafNode() {
×
3157
                // For spokes these are no-ops since the hub server told us our permissions.
×
3158
                // We just need to not send these over to the other side since we will get cutoff.
×
3159
                return
×
3160
        }
×
3161
        // FIXME(dlc) ?
3162
        c.setLeafConnectDelayIfSoliciting(leafNodeReconnectAfterPermViolation)
×
3163
        var action string
×
3164
        if pub {
×
3165
                c.sendErr(fmt.Sprintf("Permissions Violation for Publish to %q", subj))
×
3166
                action = "Publish"
×
3167
        } else {
×
3168
                c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q", subj))
×
3169
                action = "Subscription"
×
3170
        }
×
3171
        c.Errorf("%s Violation on %q - Check other side configuration", action, subj)
×
3172
        // TODO: add a new close reason that is more appropriate?
×
3173
        c.closeConnection(ProtocolViolation)
×
3174
}
3175

3176
// Invoked from generic processErr() for LEAF connections.
3177
func (c *client) leafProcessErr(errStr string) {
33✔
3178
        // Check if we got a cluster name collision.
33✔
3179
        if strings.Contains(errStr, ErrLeafNodeHasSameClusterName.Error()) {
36✔
3180
                _, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterClusterNameSame)
3✔
3181
                c.Errorf("Leafnode connection dropped with same cluster name error. Delaying attempt to reconnect for %v", delay)
3✔
3182
                return
3✔
3183
        }
3✔
3184

3185
        // We will look for Loop detected error coming from the other side.
3186
        // If we solicit, set the connect delay.
3187
        if !strings.Contains(errStr, "Loop detected") {
60✔
3188
                return
30✔
3189
        }
30✔
3190
        c.handleLeafNodeLoop(false)
×
3191
}
3192

3193
// If this leaf connection solicits, sets the connect delay to the given value,
3194
// or the one from the server option's LeafNode.connDelay if one is set (for tests).
3195
// Returns the connection's account name and delay.
3196
func (c *client) setLeafConnectDelayIfSoliciting(delay time.Duration) (string, time.Duration) {
3✔
3197
        c.mu.Lock()
3✔
3198
        if c.isSolicitedLeafNode() {
6✔
3199
                if s := c.srv; s != nil {
6✔
3200
                        if srvdelay := s.getOpts().LeafNode.connDelay; srvdelay != 0 {
3✔
3201
                                delay = srvdelay
×
3202
                        }
×
3203
                }
3204
                c.leaf.remote.setConnectDelay(delay)
3✔
3205
        }
3206
        accName := c.acc.Name
3✔
3207
        c.mu.Unlock()
3✔
3208
        return accName, delay
3✔
3209
}
3210

3211
// For the given remote Leafnode configuration, this function returns
3212
// if TLS is required, and if so, will return a clone of the TLS Config
3213
// (since some fields will be changed during handshake), the TLS server
3214
// name that is remembered, and the TLS timeout.
3215
func (c *client) leafNodeGetTLSConfigForSolicit(remote *leafNodeCfg) (bool, *tls.Config, string, float64) {
611✔
3216
        var (
611✔
3217
                tlsConfig  *tls.Config
611✔
3218
                tlsName    string
611✔
3219
                tlsTimeout float64
611✔
3220
        )
611✔
3221

611✔
3222
        remote.RLock()
611✔
3223
        defer remote.RUnlock()
611✔
3224

611✔
3225
        tlsRequired := remote.TLS || remote.TLSConfig != nil
611✔
3226
        if tlsRequired {
635✔
3227
                if remote.TLSConfig != nil {
48✔
3228
                        tlsConfig = remote.TLSConfig.Clone()
24✔
3229
                } else {
24✔
3230
                        tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}
×
3231
                }
×
3232
                tlsName = remote.tlsName
24✔
3233
                tlsTimeout = remote.TLSTimeout
24✔
3234
                if tlsTimeout == 0 {
27✔
3235
                        tlsTimeout = float64(TLS_TIMEOUT / time.Second)
3✔
3236
                }
3✔
3237
        }
3238

3239
        return tlsRequired, tlsConfig, tlsName, tlsTimeout
611✔
3240
}
3241

3242
// Initiates the LeafNode Websocket connection by:
3243
// - doing the TLS handshake if needed
3244
// - sending the HTTP request
3245
// - waiting for the HTTP response
3246
//
3247
// Since some bufio reader is used to consume the HTTP response, this function
3248
// returns the slice of buffered bytes (if any) so that the readLoop that will
3249
// be started after that consume those first before reading from the socket.
3250
// The boolean
3251
//
3252
// Lock held on entry.
3253
func (c *client) leafNodeSolicitWSConnection(opts *Options, rURL *url.URL, remote *leafNodeCfg) ([]byte, ClosedState, error) {
×
3254
        remote.RLock()
×
3255
        compress := remote.Websocket.Compression
×
3256
        // By default the server will mask outbound frames, but it can be disabled with this option.
×
3257
        noMasking := remote.Websocket.NoMasking
×
3258
        infoTimeout := remote.FirstInfoTimeout
×
3259
        remote.RUnlock()
×
3260
        // Will do the client-side TLS handshake if needed.
×
3261
        tlsRequired, err := c.leafClientHandshakeIfNeeded(remote, opts)
×
3262
        if err != nil {
×
3263
                // 0 will indicate that the connection was already closed
×
3264
                return nil, 0, err
×
3265
        }
×
3266

3267
        // For http request, we need the passed URL to contain either http or https scheme.
3268
        scheme := "http"
×
3269
        if tlsRequired {
×
3270
                scheme = "https"
×
3271
        }
×
3272
        // We will use the `/leafnode` path to tell the accepting WS server that it should
3273
        // create a LEAF connection, not a CLIENT.
3274
        // In case we use the user's URL path in the future, make sure we append the user's
3275
        // path to our `/leafnode` path.
3276
        lpath := leafNodeWSPath
×
3277
        if curPath := rURL.EscapedPath(); curPath != _EMPTY_ {
×
3278
                if curPath[0] == '/' {
×
3279
                        curPath = curPath[1:]
×
3280
                }
×
3281
                lpath = path.Join(curPath, lpath)
×
3282
        } else {
×
3283
                lpath = lpath[1:]
×
3284
        }
×
3285
        ustr := fmt.Sprintf("%s://%s/%s", scheme, rURL.Host, lpath)
×
3286
        u, _ := url.Parse(ustr)
×
3287
        req := &http.Request{
×
3288
                Method:     "GET",
×
3289
                URL:        u,
×
3290
                Proto:      "HTTP/1.1",
×
3291
                ProtoMajor: 1,
×
3292
                ProtoMinor: 1,
×
3293
                Header:     make(http.Header),
×
3294
                Host:       u.Host,
×
3295
        }
×
3296
        wsKey, err := wsMakeChallengeKey()
×
3297
        if err != nil {
×
3298
                return nil, WriteError, err
×
3299
        }
×
3300

3301
        req.Header["Upgrade"] = []string{"websocket"}
×
3302
        req.Header["Connection"] = []string{"Upgrade"}
×
3303
        req.Header["Sec-WebSocket-Key"] = []string{wsKey}
×
3304
        req.Header["Sec-WebSocket-Version"] = []string{"13"}
×
3305
        if compress {
×
3306
                req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue)
×
3307
        }
×
3308
        if noMasking {
×
3309
                req.Header.Add(wsNoMaskingHeader, wsNoMaskingValue)
×
3310
        }
×
3311
        c.nc.SetDeadline(time.Now().Add(infoTimeout))
×
3312
        if err := req.Write(c.nc); err != nil {
×
3313
                return nil, WriteError, err
×
3314
        }
×
3315

3316
        var resp *http.Response
×
3317

×
3318
        br := bufio.NewReaderSize(c.nc, MAX_CONTROL_LINE_SIZE)
×
3319
        resp, err = http.ReadResponse(br, req)
×
3320
        if err == nil &&
×
3321
                (resp.StatusCode != 101 ||
×
3322
                        !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
×
3323
                        !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
×
3324
                        resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) {
×
3325

×
3326
                err = fmt.Errorf("invalid websocket connection")
×
3327
        }
×
3328
        // Check compression extension...
3329
        if err == nil && c.ws.compress {
×
3330
                // Check that not only permessage-deflate extension is present, but that
×
3331
                // we also have server and client no context take over.
×
3332
                srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header, false)
×
3333

×
3334
                // If server does not support compression, then simply disable it in our side.
×
3335
                if !srvCompress {
×
3336
                        c.ws.compress = false
×
3337
                } else if !noCtxTakeover {
×
3338
                        err = fmt.Errorf("compression negotiation error")
×
3339
                }
×
3340
        }
3341
        // Same for no masking...
3342
        if err == nil && noMasking {
×
3343
                // Check if server accepts no masking
×
3344
                if resp.Header.Get(wsNoMaskingHeader) != wsNoMaskingValue {
×
3345
                        // Nope, need to mask our writes as any client would do.
×
3346
                        c.ws.maskwrite = true
×
3347
                }
×
3348
        }
3349
        if resp != nil {
×
3350
                resp.Body.Close()
×
3351
        }
×
3352
        if err != nil {
×
3353
                return nil, ReadError, err
×
3354
        }
×
3355
        c.Debugf("Leafnode compression=%v masking=%v", c.ws.compress, c.ws.maskwrite)
×
3356

×
3357
        var preBuf []byte
×
3358
        // We have to slurp whatever is in the bufio reader and pass that to the readloop.
×
3359
        if n := br.Buffered(); n != 0 {
×
3360
                preBuf, _ = br.Peek(n)
×
3361
        }
×
3362
        return preBuf, 0, nil
×
3363
}
3364

3365
const connectProcessTimeout = 2 * time.Second
3366

3367
// This is invoked for remote LEAF remote connections after processing the INFO
3368
// protocol.
3369
func (s *Server) leafNodeResumeConnectProcess(c *client) {
244✔
3370
        clusterName := s.ClusterName()
244✔
3371

244✔
3372
        c.mu.Lock()
244✔
3373
        if c.isClosed() {
244✔
3374
                c.mu.Unlock()
×
3375
                return
×
3376
        }
×
3377
        if err := c.sendLeafConnect(clusterName, c.headers); err != nil {
244✔
3378
                c.mu.Unlock()
×
3379
                c.closeConnection(WriteError)
×
3380
                return
×
3381
        }
×
3382

3383
        // Spin up the write loop.
3384
        s.startGoRoutine(func() { c.writeLoop() })
488✔
3385

3386
        // timeout leafNodeFinishConnectProcess
3387
        c.ping.tmr = time.AfterFunc(connectProcessTimeout, func() {
244✔
3388
                c.mu.Lock()
×
3389
                // check if leafNodeFinishConnectProcess was called and prevent later leafNodeFinishConnectProcess
×
3390
                if !c.flags.setIfNotSet(connectProcessFinished) {
×
3391
                        c.mu.Unlock()
×
3392
                        return
×
3393
                }
×
3394
                clearTimer(&c.ping.tmr)
×
3395
                closed := c.isClosed()
×
3396
                c.mu.Unlock()
×
3397
                if !closed {
×
3398
                        c.sendErrAndDebug("Stale Leaf Node Connection - Closing")
×
3399
                        c.closeConnection(StaleConnection)
×
3400
                }
×
3401
        })
3402
        c.mu.Unlock()
244✔
3403
        c.Debugf("Remote leafnode connect msg sent")
244✔
3404
}
3405

3406
// This is invoked for remote LEAF connections after processing the INFO
3407
// protocol and leafNodeResumeConnectProcess.
3408
// This will send LS+ the CONNECT protocol and register the leaf node.
3409
func (s *Server) leafNodeFinishConnectProcess(c *client) {
215✔
3410
        c.mu.Lock()
215✔
3411
        if !c.flags.setIfNotSet(connectProcessFinished) {
215✔
3412
                c.mu.Unlock()
×
3413
                return
×
3414
        }
×
3415
        if c.isClosed() {
215✔
3416
                c.mu.Unlock()
×
3417
                s.removeLeafNodeConnection(c)
×
3418
                return
×
3419
        }
×
3420
        remote := c.leaf.remote
215✔
3421
        // Check if we will need to send the system connect event.
215✔
3422
        remote.RLock()
215✔
3423
        sendSysConnectEvent := remote.Hub
215✔
3424
        remote.RUnlock()
215✔
3425

215✔
3426
        // Capture account before releasing lock
215✔
3427
        acc := c.acc
215✔
3428
        // cancel connectProcessTimeout
215✔
3429
        clearTimer(&c.ping.tmr)
215✔
3430
        c.mu.Unlock()
215✔
3431

215✔
3432
        // Make sure we register with the account here.
215✔
3433
        if err := c.registerWithAccount(acc); err != nil {
215✔
3434
                if err == ErrTooManyAccountConnections {
×
3435
                        c.maxAccountConnExceeded()
×
3436
                        return
×
3437
                } else if err == ErrLeafNodeLoop {
×
3438
                        c.handleLeafNodeLoop(true)
×
3439
                        return
×
3440
                }
×
3441
                c.Errorf("Registering leaf with account %s resulted in error: %v", acc.Name, err)
×
3442
                c.closeConnection(ProtocolViolation)
×
3443
                return
×
3444
        }
3445
        s.addLeafNodeConnection(c, _EMPTY_, _EMPTY_, false)
215✔
3446
        s.initLeafNodeSmapAndSendSubs(c)
215✔
3447
        if sendSysConnectEvent {
215✔
3448
                s.sendLeafNodeConnect(acc)
×
3449
        }
×
3450

3451
        // The above functions are not atomically under the client
3452
        // lock doing those operations. It is possible - since we
3453
        // have started the read/write loops - that the connection
3454
        // is closed before or in between. This would leave the
3455
        // closed LN connection possible registered with the account
3456
        // and/or the server's leafs map. So check if connection
3457
        // is closed, and if so, manually cleanup.
3458
        c.mu.Lock()
215✔
3459
        closed := c.isClosed()
215✔
3460
        if !closed {
430✔
3461
                c.setFirstPingTimer()
215✔
3462
        }
215✔
3463
        c.mu.Unlock()
215✔
3464
        if closed {
215✔
3465
                s.removeLeafNodeConnection(c)
×
3466
                if prev := acc.removeClient(c); prev == 1 {
×
3467
                        s.decActiveAccounts()
×
3468
                }
×
3469
        }
3470
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc