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

nats-io / nats-server / 18830161409

24 Oct 2025 09:58AM UTC coverage: 84.784% (-1.3%) from 86.052%
18830161409

push

github

web-flow
[FIXED] Consumer send 404 No Messages on EOS (#7466)

Requests using `NoWait` but no expiry would not receive `404 No
Messages` if the stream was empty and no messages were delivered. `408
Request Timeout` would only be returned if messages were delivered or
the request expired.

This PR fixes that by sending a `404 No Messages` for `NoWait` requests
without expiry (same response when doing a pull request on a consumer
with no pending messages) when reaching the end of the stream.

Resolves https://github.com/nats-io/nats-server/issues/7457,
https://github.com/nats-io/nats-server/issues/5373

Signed-off-by: Maurice van Veen <github@mauricevanveen.com>

73664 of 86884 relevant lines covered (84.78%)

343678.39 hits per line

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

90.19
/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 {
2,134✔
122
        return c.kind == LEAF && c.leaf.remote != nil
2,134✔
123
}
2,134✔
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,990,856✔
128
        return c.kind == LEAF && c.leaf.isSpoke
5,990,856✔
129
}
5,990,856✔
130

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

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

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

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

213
// Ensure that leafnode is properly configured.
214
func validateLeafNode(o *Options) error {
8,722✔
215
        if err := validateLeafNodeAuthOptions(o); err != nil {
8,724✔
216
                return err
2✔
217
        }
2✔
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 {
10,115✔
221
                if r.LocalAccount == _EMPTY_ {
1,848✔
222
                        r.LocalAccount = globalAccountName
453✔
223
                }
453✔
224
        }
225

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

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

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

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

314
        if o.LeafNode.Port == 0 {
13,728✔
315
                return nil
5,036✔
316
        }
5,036✔
317

318
        // If MinVersion is defined, check that it is valid.
319
        if mv := o.LeafNode.MinVersion; mv != _EMPTY_ {
3,660✔
320
                if err := checkLeafMinVersionConfig(mv); err != nil {
6✔
321
                        return err
2✔
322
                }
2✔
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 {
6,625✔
330
                return nil
2,971✔
331
        }
2,971✔
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_ {
684✔
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 {
682✔
338
                return fmt.Errorf("leafnode: %v", err)
×
339
        }
×
340
        return nil
682✔
341
}
342

343
func checkLeafMinVersionConfig(mv string) error {
8✔
344
        if ok, err := versionAtLeastCheckError(mv, 2, 8, 0); !ok || err != nil {
12✔
345
                if err != nil {
6✔
346
                        return fmt.Errorf("invalid leafnode's minimum version: %v", err)
2✔
347
                } else {
4✔
348
                        return fmt.Errorf("the minimum version should be at least 2.8.0")
2✔
349
                }
2✔
350
        }
351
        return nil
4✔
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 {
8,781✔
358
        if len(o.LeafNode.Users) == 0 {
17,535✔
359
                return nil
8,754✔
360
        }
8,754✔
361
        if o.LeafNode.Username != _EMPTY_ {
29✔
362
                return fmt.Errorf("can not have a single user/pass and a users array")
2✔
363
        }
2✔
364
        if o.LeafNode.Nkey != _EMPTY_ {
25✔
365
                return fmt.Errorf("can not have a single nkey and a users array")
×
366
        }
×
367
        users := map[string]struct{}{}
25✔
368
        for _, u := range o.LeafNode.Users {
66✔
369
                if _, exists := users[u.Username]; exists {
43✔
370
                        return fmt.Errorf("duplicate user %q detected in leafnode authorization", u.Username)
2✔
371
                }
2✔
372
                users[u.Username] = struct{}{}
39✔
373
        }
374
        return nil
23✔
375
}
376

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

1,998✔
380
        if remote.Proxy.URL == _EMPTY_ {
3,972✔
381
                return warnings, nil
1,974✔
382
        }
1,974✔
383

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

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

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

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

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

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

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

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

428
        return warnings, nil
13✔
429
}
430

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

438
        s.mu.RLock()
15✔
439
        defer s.mu.RUnlock()
15✔
440

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

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

469
// Creates a leafNodeCfg object that wraps the RemoteLeafOpts.
470
func newLeafNodeCfg(remote *RemoteLeafOpts) *leafNodeCfg {
1,344✔
471
        cfg := &leafNodeCfg{
1,344✔
472
                RemoteLeafOpts: remote,
1,344✔
473
                urls:           make([]*url.URL, 0, len(remote.URLs)),
1,344✔
474
        }
1,344✔
475
        if len(remote.DenyExports) > 0 || len(remote.DenyImports) > 0 {
1,352✔
476
                perms := &Permissions{}
8✔
477
                if len(remote.DenyExports) > 0 {
16✔
478
                        perms.Publish = &SubjectPermission{Deny: remote.DenyExports}
8✔
479
                }
8✔
480
                if len(remote.DenyImports) > 0 {
15✔
481
                        perms.Subscribe = &SubjectPermission{Deny: remote.DenyImports}
7✔
482
                }
7✔
483
                cfg.perms = perms
8✔
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...)
1,344✔
488
        // If allowed to randomize, do it on our copy of URLs
1,344✔
489
        if !remote.NoRandomize {
2,686✔
490
                rand.Shuffle(len(cfg.urls), func(i, j int) {
1,756✔
491
                        cfg.urls[i], cfg.urls[j] = cfg.urls[j], cfg.urls[i]
414✔
492
                })
414✔
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 {
3,132✔
498
                cfg.saveTLSHostname(u)
1,788✔
499
                cfg.saveUserPassword(u)
1,788✔
500
                // If the url(s) have the "wss://" scheme, and we don't have a TLS
1,788✔
501
                // config, mark that we should be using TLS anyway.
1,788✔
502
                if !cfg.TLS && isWSSURL(u) {
1,789✔
503
                        cfg.TLS = true
1✔
504
                }
1✔
505
        }
506
        return cfg
1,344✔
507
}
508

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

524
// Returns the current URL
525
func (cfg *leafNodeCfg) getCurrentURL() *url.URL {
78✔
526
        cfg.RLock()
78✔
527
        defer cfg.RUnlock()
78✔
528
        return cfg.curURL
78✔
529
}
78✔
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 {
1,535✔
534
        cfg.RLock()
1,535✔
535
        delay := cfg.connDelay
1,535✔
536
        cfg.RUnlock()
1,535✔
537
        return delay
1,535✔
538
}
1,535✔
539

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

547
// Ensure that non-exported options (used in tests) have
548
// been properly set.
549
func (s *Server) setLeafNodeNonExportedOptions() {
7,194✔
550
        opts := s.getOpts()
7,194✔
551
        s.leafNodeOpts.dialTimeout = opts.LeafNode.dialTimeout
7,194✔
552
        if s.leafNodeOpts.dialTimeout == 0 {
14,387✔
553
                // Use same timeouts as routes for now.
7,193✔
554
                s.leafNodeOpts.dialTimeout = DEFAULT_ROUTE_DIAL
7,193✔
555
        }
7,193✔
556
        s.leafNodeOpts.resolver = opts.LeafNode.resolver
7,194✔
557
        if s.leafNodeOpts.resolver == nil {
14,384✔
558
                s.leafNodeOpts.resolver = net.DefaultResolver
7,190✔
559
        }
7,190✔
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) {
10✔
566
        proxyAddr, err := url.Parse(proxyURL)
10✔
567
        if err != nil {
10✔
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)
10✔
574
        if err != nil {
10✔
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 {
10✔
580
                conn.Close()
×
581
                return nil, fmt.Errorf("failed to set deadline: %v", err)
×
582
        }
×
583

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

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

596
        if err := req.Write(conn); err != nil {
10✔
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)
10✔
602
        if err != nil {
10✔
603
                conn.Close()
×
604
                return nil, fmt.Errorf("failed to read proxy response: %v", err)
×
605
        }
×
606

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

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

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

622
        return conn, nil
9✔
623
}
624

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

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

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

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

651
        if connDelay := remote.getConnectDelay(); connDelay > 0 {
1,615✔
652
                select {
80✔
653
                case <-time.After(connDelay):
70✔
654
                case <-s.quitCh:
10✔
655
                        return
10✔
656
                }
657
                remote.setConnectDelay(0)
70✔
658
        }
659

660
        var conn net.Conn
1,525✔
661

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

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

1,525✔
672
        // Set default proxy timeout if not specified
1,525✔
673
        if proxyTimeout == 0 {
3,043✔
674
                proxyTimeout = dialTimeout
1,518✔
675
        }
1,518✔
676

677
        attempts := 0
1,525✔
678

1,525✔
679
        for s.isRunning() && s.remoteLeafNodeStillValid(remote) {
8,608✔
680
                rURL := remote.pickNextURL()
7,083✔
681
                url, err := s.getRandomIP(resolver, rURL.Host, nil)
7,083✔
682
                if err == nil {
14,159✔
683
                        var ipStr string
7,076✔
684
                        if url != rURL.Host {
7,157✔
685
                                ipStr = fmt.Sprintf(" (%s)", url)
81✔
686
                        }
81✔
687
                        // Some test may want to disable remotes from connecting
688
                        if s.isLeafConnectDisabled() {
7,205✔
689
                                s.Debugf("Will not attempt to connect to remote server on %q%s, leafnodes currently disabled", rURL.Host, ipStr)
129✔
690
                                err = ErrLeafNodeDisabled
129✔
691
                        } else {
7,076✔
692
                                s.Debugf("Trying to connect as leafnode to remote server on %q%s", rURL.Host, ipStr)
6,947✔
693

6,947✔
694
                                // Check if proxy is configured first, then check if URL supports it
6,947✔
695
                                if proxyURL != _EMPTY_ && isWSURL(rURL) {
6,954✔
696
                                        // Use proxy for WebSocket connections - use original hostname, resolved IP for connection
7✔
697
                                        targetHost := rURL.Host
7✔
698
                                        // If URL doesn't include port, add the default port for the scheme
7✔
699
                                        if rURL.Port() == _EMPTY_ {
7✔
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)
7✔
708
                                } else {
6,940✔
709
                                        // Direct connection
6,940✔
710
                                        conn, err = natsDialTimeout("tcp", url, dialTimeout)
6,940✔
711
                                }
6,940✔
712
                        }
713
                }
714
                if err != nil {
13,353✔
715
                        jitter := time.Duration(rand.Int63n(int64(reconnectDelay)))
6,270✔
716
                        delay := reconnectDelay + jitter
6,270✔
717
                        attempts++
6,270✔
718
                        if s.shouldReportConnectErr(firstConnect, attempts) {
10,652✔
719
                                s.Errorf(connErrFmt, rURL.Host, attempts, err)
4,382✔
720
                        } else {
6,270✔
721
                                s.Debugf(connErrFmt, rURL.Host, attempts, err)
1,888✔
722
                        }
1,888✔
723
                        remote.Lock()
6,270✔
724
                        // if we are using a delay to start migrating assets, kick off a migrate timer.
6,270✔
725
                        if remote.jsMigrateTimer == nil && jetstreamMigrateDelay > 0 {
6,278✔
726
                                remote.jsMigrateTimer = time.AfterFunc(jetstreamMigrateDelay, func() {
16✔
727
                                        s.checkJetStreamMigrate(remote)
8✔
728
                                })
8✔
729
                        }
730
                        remote.Unlock()
6,270✔
731
                        select {
6,270✔
732
                        case <-s.quitCh:
702✔
733
                                remote.cancelMigrateTimer()
702✔
734
                                return
702✔
735
                        case <-time.After(delay):
5,567✔
736
                                // Check if we should migrate any JetStream assets immediately while this remote is down.
5,567✔
737
                                // This will be used if JetStreamClusterMigrateDelay was not set
5,567✔
738
                                if jetstreamMigrateDelay == 0 {
11,063✔
739
                                        s.checkJetStreamMigrate(remote)
5,496✔
740
                                }
5,496✔
741
                                continue
5,567✔
742
                        }
743
                }
744
                remote.cancelMigrateTimer()
813✔
745
                if !s.remoteLeafNodeStillValid(remote) {
813✔
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)
813✔
753

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

813✔
757
                return
813✔
758
        }
759
}
760

761
func (cfg *leafNodeCfg) cancelMigrateTimer() {
1,515✔
762
        cfg.Lock()
1,515✔
763
        stopAndClearTimer(&cfg.jsMigrateTimer)
1,515✔
764
        cfg.Unlock()
1,515✔
765
}
1,515✔
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) {
813✔
769
        s.mu.RLock()
813✔
770
        accName := remote.LocalAccount
813✔
771
        s.mu.RUnlock()
813✔
772

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

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

811✔
782
        // Walk all streams looking for any clustered stream, skip otherwise.
811✔
783
        for _, mset := range acc.streams() {
829✔
784
                node := mset.raftNode()
18✔
785
                if node == nil {
28✔
786
                        // Not R>1
10✔
787
                        continue
10✔
788
                }
789
                // Check consumers
790
                for _, o := range mset.getConsumers() {
10✔
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)
8✔
798
        }
799
}
800

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

5,504✔
807
        if !shouldMigrate {
10,942✔
808
                return
5,438✔
809
        }
5,438✔
810

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

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

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

843
// Helper for checking.
844
func (s *Server) isLeafConnectDisabled() bool {
7,076✔
845
        s.mu.RLock()
7,076✔
846
        defer s.mu.RUnlock()
7,076✔
847
        return s.leafDisableConnect
7,076✔
848
}
7,076✔
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) {
2,466✔
859
        if cfg.tlsName == _EMPTY_ && net.ParseIP(u.Hostname()) == nil {
2,487✔
860
                cfg.tlsName = u.Hostname()
21✔
861
        }
21✔
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) {
1,788✔
867
        if cfg.username == _EMPTY_ && u.User != nil {
2,092✔
868
                cfg.username = u.User.Username()
304✔
869
                cfg.password, _ = u.User.Password()
304✔
870
        }
304✔
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() {
3,622✔
876
        // Snapshot server options.
3,622✔
877
        opts := s.getOpts()
3,622✔
878

3,622✔
879
        port := opts.LeafNode.Port
3,622✔
880
        if port == -1 {
7,069✔
881
                port = 0
3,447✔
882
        }
3,447✔
883

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

888
        s.mu.Lock()
3,622✔
889
        hp := net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(port))
3,622✔
890
        l, e := natsListen("tcp", hp)
3,622✔
891
        s.leafNodeListenerErr = e
3,622✔
892
        if e != nil {
3,622✔
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",
3,622✔
899
                net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
3,622✔
900

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

928
        s.leafNodeInfo = info
3,622✔
929
        // Possibly override Host/Port and set IP based on Cluster.Advertise
3,622✔
930
        if err := s.setLeafNodeInfoHostPortAndIP(); err != nil {
3,622✔
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]++
3,622✔
937
        s.generateLeafNodeInfoJSON()
3,622✔
938

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

3,622✔
942
        // As of now, a server that does not have remotes configured would
3,622✔
943
        // never solicit a connection, so we should not have to warn if
3,622✔
944
        // InsecureSkipVerify is set in main LeafNodes config (since
3,622✔
945
        // this TLS setting matters only when soliciting a connection).
3,622✔
946
        // Still, warn if insecure is set in any of LeafNode block.
3,622✔
947
        // We need to check remotes, even if tls is not required on accept.
3,622✔
948
        warn := tlsRequired && opts.LeafNode.TLSConfig.InsecureSkipVerify
3,622✔
949
        if !warn {
7,242✔
950
                for _, r := range opts.LeafNode.Remotes {
3,813✔
951
                        if r.TLSConfig != nil && r.TLSConfig.InsecureSkipVerify {
193✔
952
                                warn = true
×
953
                                break
×
954
                        }
955
                }
956
        }
957
        if warn {
3,624✔
958
                s.Warnf(leafnodeTLSInsecureWarning)
2✔
959
        }
2✔
960
        go s.acceptConnections(l, "Leafnode", func(conn net.Conn) { s.createLeafNode(conn, nil, nil, nil) }, nil)
4,474✔
961
        s.mu.Unlock()
3,622✔
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 {
688✔
970
        // We support basic user/pass and operator based user JWT with signatures.
688✔
971
        cinfo := leafConnectInfo{
688✔
972
                Version:       VERSION,
688✔
973
                ID:            c.srv.info.ID,
688✔
974
                Domain:        c.srv.info.Domain,
688✔
975
                Name:          c.srv.info.Name,
688✔
976
                Hub:           c.leaf.remote.Hub,
688✔
977
                Cluster:       clusterName,
688✔
978
                Headers:       headers,
688✔
979
                JetStream:     c.acc.jetStreamConfigured(),
688✔
980
                DenyPub:       c.leaf.remote.DenyImports,
688✔
981
                Compression:   c.leaf.compression,
688✔
982
                RemoteAccount: c.acc.GetName(),
688✔
983
                Proto:         c.srv.getServerProto(),
688✔
984
                Isolate:       c.leaf.remote.RequestIsolation,
688✔
985
        }
688✔
986

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

1003
        } else if creds := c.leaf.remote.Credentials; creds != _EMPTY_ {
737✔
1004
                // Check for credentials first, that will take precedence..
54✔
1005
                c.Debugf("Authenticating with credentials file %q", c.leaf.remote.Credentials)
54✔
1006
                contents, err := os.ReadFile(creds)
54✔
1007
                if err != nil {
54✔
1008
                        c.Errorf("%v", err)
×
1009
                        return err
×
1010
                }
×
1011
                defer wipeSlice(contents)
54✔
1012
                items := credsRe.FindAllSubmatch(contents, -1)
54✔
1013
                if len(items) < 2 {
54✔
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]
54✔
1020
                tmp := make([]byte, len(raw))
54✔
1021
                copy(tmp, raw)
54✔
1022
                // Seed is second item.
54✔
1023
                kp, err := nkeys.FromSeed(items[1][1])
54✔
1024
                if err != nil {
54✔
1025
                        c.Errorf("Credentials file has malformed seed")
×
1026
                        return err
×
1027
                }
×
1028
                // Wipe our key on exit.
1029
                defer kp.Wipe()
54✔
1030

54✔
1031
                sigraw, _ := kp.Sign(c.nonce)
54✔
1032
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
54✔
1033
                cinfo.JWT = bytesToString(tmp)
54✔
1034
                cinfo.Sig = sig
54✔
1035
        } else if nkey := c.leaf.remote.Nkey; nkey != _EMPTY_ {
634✔
1036
                kp, err := nkeys.FromSeed([]byte(nkey))
5✔
1037
                if err != nil {
5✔
1038
                        c.Errorf("Remote nkey has malformed seed")
×
1039
                        return err
×
1040
                }
×
1041
                // Wipe our key on exit.
1042
                defer kp.Wipe()
5✔
1043
                sigraw, _ := kp.Sign(c.nonce)
5✔
1044
                sig := base64.RawURLEncoding.EncodeToString(sigraw)
5✔
1045
                pkey, _ := kp.PublicKey()
5✔
1046
                cinfo.Nkey = pkey
5✔
1047
                cinfo.Sig = sig
5✔
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 {
1,010✔
1052
                cinfo.User = userInfo.Username()
324✔
1053
                var ok bool
324✔
1054
                cinfo.Pass, ok = userInfo.Password()
324✔
1055
                // For backward compatibility, if only username is provided, set both
324✔
1056
                // Token and User, not just Token.
324✔
1057
                if !ok {
331✔
1058
                        cinfo.Token = cinfo.User
7✔
1059
                }
7✔
1060
        } else if c.leaf.remote.username != _EMPTY_ {
368✔
1061
                cinfo.User = c.leaf.remote.username
6✔
1062
                cinfo.Pass = c.leaf.remote.password
6✔
1063
                // For backward compatibility, if only username is provided, set both
6✔
1064
                // Token and User, not just Token.
6✔
1065
                if cinfo.Pass == _EMPTY_ {
6✔
1066
                        cinfo.Token = cinfo.User
×
1067
                }
×
1068
        }
1069
        b, err := json.Marshal(cinfo)
686✔
1070
        if err != nil {
686✔
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)))
686✔
1078
        return nil
686✔
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 {
2,765✔
1084
        clone := s.leafNodeInfo
2,765✔
1085
        // Copy the array of urls.
2,765✔
1086
        if len(s.leafNodeInfo.LeafNodeURLs) > 0 {
5,016✔
1087
                clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...)
2,251✔
1088
        }
2,251✔
1089
        return &clone
2,765✔
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 {
7,204✔
1097
        if s.leafURLsMap.addUrl(urlStr) {
14,403✔
1098
                s.generateLeafNodeInfoJSON()
7,199✔
1099
                return true
7,199✔
1100
        }
7,199✔
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 {
7,204✔
1109
        // Don't need to do this if we are removing the route connection because
7,204✔
1110
        // we are shuting down...
7,204✔
1111
        if s.isShuttingDown() {
10,954✔
1112
                return false
3,750✔
1113
        }
3,750✔
1114
        if s.leafURLsMap.removeUrl(urlStr) {
6,904✔
1115
                s.generateLeafNodeInfoJSON()
3,450✔
1116
                return true
3,450✔
1117
        }
3,450✔
1118
        return false
4✔
1119
}
1120

1121
// Server lock is held on entry
1122
func (s *Server) generateLeafNodeInfoJSON() {
14,271✔
1123
        s.leafNodeInfo.Cluster = s.cachedClusterName()
14,271✔
1124
        s.leafNodeInfo.LeafNodeURLs = s.leafURLsMap.getAsStringSlice()
14,271✔
1125
        s.leafNodeInfo.WSConnectURLs = s.websocket.connectURLsMap.getAsStringSlice()
14,271✔
1126
        s.leafNodeInfoJSON = generateInfoJSON(&s.leafNodeInfo)
14,271✔
1127
}
14,271✔
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() {
10,649✔
1132
        for _, c := range s.leafs {
10,766✔
1133
                c.mu.Lock()
117✔
1134
                c.enqueueProto(s.leafNodeInfoJSON)
117✔
1135
                c.mu.Unlock()
117✔
1136
        }
117✔
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 {
1,694✔
1141
        // Snapshot server options.
1,694✔
1142
        opts := s.getOpts()
1,694✔
1143

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

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

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

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

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

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

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

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

1,692✔
1230
        var nonce [nonceLen]byte
1,692✔
1231
        var info *Info
1,692✔
1232

1,692✔
1233
        // Grab this before the client lock below.
1,692✔
1234
        if !solicited {
2,573✔
1235
                // Grab server variables
881✔
1236
                s.mu.Lock()
881✔
1237
                info = s.copyLeafNodeInfo()
881✔
1238
                // For tests that want to simulate old servers, do not set the compression
881✔
1239
                // on the INFO protocol if configured with CompressionNotSupported.
881✔
1240
                if cm := opts.LeafNode.Compression.Mode; cm != CompressionNotSupported {
1,761✔
1241
                        info.Compression = cm
880✔
1242
                }
880✔
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[:])
881✔
1246
                s.mu.Unlock()
881✔
1247
        }
1248

1249
        // Grab lock
1250
        c.mu.Lock()
1,692✔
1251

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

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

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

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

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

876✔
1325
                        // The above call could have marked the connection as closed (due to TCP error).
876✔
1326
                        if c.isClosed() {
876✔
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 {
957✔
1335
                        // If we have a prebuffer create a multi-reader.
76✔
1336
                        if len(pre) > 0 {
76✔
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 {
125✔
1341
                                c.mu.Unlock()
49✔
1342
                                return nil
49✔
1343
                        }
49✔
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 {
835✔
1349
                        c.flags.set(didTLSFirst)
3✔
1350
                        c.sendProtoNow(proto)
3✔
1351
                        if c.isClosed() {
3✔
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)
832✔
1367
                if needsCompression(opts.LeafNode.Compression.Mode) {
1,447✔
1368
                        c.ping.tmr = time.AfterFunc(timeout, func() {
625✔
1369
                                c.authTimeout()
10✔
1370
                        })
10✔
1371
                } else {
217✔
1372
                        c.setAuthTimer(timeout)
217✔
1373
                }
217✔
1374
        }
1375

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

1384
        // Spin up the read loop.
1385
        s.startGoRoutine(func() { c.readLoop(preBuf) })
3,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 {
2,452✔
1390
                s.startGoRoutine(func() { c.writeLoop() })
1,664✔
1391
        }
1392

1393
        c.mu.Unlock()
1,620✔
1394

1,620✔
1395
        return c
1,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) {
1,966✔
1403
        // Check if TLS is required and gather TLS config variables.
1,966✔
1404
        tlsRequired, tlsConfig, tlsName, tlsTimeout := c.leafNodeGetTLSConfigForSolicit(remote)
1,966✔
1405
        if !tlsRequired {
3,854✔
1406
                return false, nil
1,888✔
1407
        }
1,888✔
1408

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

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

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

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

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

1,330✔
1466
                var co *CompressionOpts
1,330✔
1467
                if !didSolicit {
1,917✔
1468
                        co = &opts.LeafNode.Compression
587✔
1469
                } else {
1,330✔
1470
                        co = &remote.Compression
743✔
1471
                }
743✔
1472
                if needsCompression(co.Mode) {
2,649✔
1473
                        // Release client lock since following function will need server lock.
1,319✔
1474
                        c.mu.Unlock()
1,319✔
1475
                        compress, err := s.negotiateLeafCompression(c, didSolicit, info.Compression, co)
1,319✔
1476
                        if err != nil {
1,319✔
1477
                                c.sendErrAndErr(err.Error())
×
1478
                                c.closeConnection(ProtocolViolation)
×
1479
                                return
×
1480
                        }
×
1481
                        if compress {
2,510✔
1482
                                // Done for now, will get back another INFO protocol...
1,191✔
1483
                                return
1,191✔
1484
                        }
1,191✔
1485
                        // No compression because one side does not want/can't, so proceed.
1486
                        c.mu.Lock()
128✔
1487
                        // Check that the connection did not close if the lock was released.
128✔
1488
                        if c.isClosed() {
128✔
1489
                                c.mu.Unlock()
×
1490
                                return
×
1491
                        }
×
1492
                } else {
11✔
1493
                        // Coming from an old server, the Compression field would be the empty
11✔
1494
                        // string. For servers that are configured with CompressionNotSupported,
11✔
1495
                        // this makes them behave as old servers.
11✔
1496
                        if info.Compression == _EMPTY_ || co.Mode == CompressionNotSupported {
14✔
1497
                                c.leaf.compression = CompressionNotSupported
3✔
1498
                        } else {
11✔
1499
                                c.leaf.compression = CompressionOff
8✔
1500
                        }
8✔
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 {
140✔
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 {
2,291✔
1522
                // Mark that the INFO protocol has been received.
784✔
1523
                c.flags.set(infoReceived)
784✔
1524
                // Prevent connecting to non leafnode port. Need to do this only for
784✔
1525
                // the first INFO, not for async INFO updates...
784✔
1526
                //
784✔
1527
                // Content of INFO sent by the server when accepting a tcp connection.
784✔
1528
                // -------------------------------------------------------------------
784✔
1529
                // Listen Port Of | CID | ClientConnectURLs | LeafNodeURLs | Gateway |
784✔
1530
                // -------------------------------------------------------------------
784✔
1531
                //      CLIENT    |  X* |        X**        |              |         |
784✔
1532
                //      ROUTE     |     |        X**        |      X***    |         |
784✔
1533
                //     GATEWAY    |     |                   |              |    X    |
784✔
1534
                //     LEAFNODE   |  X  |                   |       X      |         |
784✔
1535
                // -------------------------------------------------------------------
784✔
1536
                // *   Not on older servers.
784✔
1537
                // **  Not if "no advertise" is enabled.
784✔
1538
                // *** Not if leafnode's "no advertise" is enabled.
784✔
1539
                //
784✔
1540
                // As seen from above, a solicited LeafNode connection should receive
784✔
1541
                // from the remote server an INFO with CID and LeafNodeURLs. Anything
784✔
1542
                // else should be considered an attempt to connect to a wrong port.
784✔
1543
                if didSolicit && (info.CID == 0 || info.LeafNodeURLs == nil) {
836✔
1544
                        c.mu.Unlock()
52✔
1545
                        c.Errorf(ErrConnectedToWrongPort.Error())
52✔
1546
                        c.closeConnection(WrongPort)
52✔
1547
                        return
52✔
1548
                }
52✔
1549
                // Reject a cluster that contains spaces.
1550
                if info.Cluster != _EMPTY_ && strings.Contains(info.Cluster, " ") {
733✔
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)
731✔
1558
                if info.TLSRequired && didSolicit {
761✔
1559
                        remote.TLS = true
30✔
1560
                }
30✔
1561
                supportsHeaders := c.srv.supportsHeaders()
731✔
1562
                c.headers = supportsHeaders && info.Headers
731✔
1563

731✔
1564
                // Remember the remote server.
731✔
1565
                // Pre 2.2.0 servers are not sending their server name.
731✔
1566
                // In that case, use info.ID, which, for those servers, matches
731✔
1567
                // the content of the field `Name` in the leafnode CONNECT protocol.
731✔
1568
                if info.Name == _EMPTY_ {
731✔
1569
                        c.leaf.remoteServer = info.ID
×
1570
                } else {
731✔
1571
                        c.leaf.remoteServer = info.Name
731✔
1572
                }
731✔
1573
                c.leaf.remoteDomain = info.Domain
731✔
1574
                c.leaf.remoteCluster = info.Cluster
731✔
1575
                // We send the protocol version in the INFO protocol.
731✔
1576
                // Keep track of it, so we know if this connection supports message
731✔
1577
                // tracing for instance.
731✔
1578
                c.opts.Protocol = info.Proto
731✔
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) {
2,807✔
1584
                // Consider the incoming array as the most up-to-date
1,353✔
1585
                // representation of the remote cluster's list of URLs.
1,353✔
1586
                c.updateLeafNodeURLs(info)
1,353✔
1587
        }
1,353✔
1588

1589
        // Check to see if we have permissions updates here.
1590
        if info.Import != nil || info.Export != nil {
1,469✔
1591
                perms := &Permissions{
15✔
1592
                        Publish:   info.Export,
15✔
1593
                        Subscribe: info.Import,
15✔
1594
                }
15✔
1595
                // Check if we have local deny clauses that we need to merge.
15✔
1596
                if remote := c.leaf.remote; remote != nil {
30✔
1597
                        if len(remote.DenyExports) > 0 {
16✔
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 {
16✔
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)
15✔
1611
        }
1612

1613
        var resumeConnect bool
1,454✔
1614

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

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

1,454✔
1631
        finishConnect := info.ConnectInfo
1,454✔
1632
        if resumeConnect && s != nil {
2,142✔
1633
                s.leafNodeResumeConnectProcess(c)
688✔
1634
                if !info.InfoOnConnect {
688✔
1635
                        finishConnect = true
×
1636
                }
×
1637
        }
1638
        if finishConnect {
2,105✔
1639
                s.leafNodeFinishConnectProcess(c)
651✔
1640
        }
651✔
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)
1,454✔
1646
}
1647

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

1,319✔
1671
        if !needsCompression(cm) {
1,447✔
1672
                return false, nil
128✔
1673
        }
128✔
1674

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

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

1,191✔
1684
        // If we solicited, then send this INFO protocol BEFORE switching
1,191✔
1685
        // to compression writer. However, if we did not, we send it after.
1,191✔
1686
        c.mu.Lock()
1,191✔
1687
        if didSolicit {
1,796✔
1688
                c.enqueueProto(infoProto)
605✔
1689
                // Make sure it is completely flushed (the pending bytes goes to
605✔
1690
                // 0) before proceeding.
605✔
1691
                for c.out.pb > 0 && !c.isClosed() {
1,210✔
1692
                        c.flushOutbound()
605✔
1693
                }
605✔
1694
        }
1695
        // This is to notify the readLoop that it should switch to a
1696
        // (de)compression reader.
1697
        c.in.flags.set(switchToCompression)
1,191✔
1698
        // Create the compress writer before queueing the INFO protocol for
1,191✔
1699
        // a route that did not solicit. It will make sure that that proto
1,191✔
1700
        // is sent with compression on.
1,191✔
1701
        c.out.cw = s2.NewWriter(nil, s2WriterOptions(cm)...)
1,191✔
1702
        if !didSolicit {
1,777✔
1703
                c.enqueueProto(infoProto)
586✔
1704
        }
586✔
1705
        c.mu.Unlock()
1,191✔
1706
        return true, nil
1,191✔
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) {
1,353✔
1712
        cfg := c.leaf.remote
1,353✔
1713
        cfg.Lock()
1,353✔
1714
        defer cfg.Unlock()
1,353✔
1715

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

1732
func (c *client) doUpdateLNURLs(cfg *leafNodeCfg, scheme string, URLs []string) {
1,353✔
1733
        cfg.urls = make([]*url.URL, 0, 1+len(URLs))
1,353✔
1734
        // Add the ones we receive in the protocol
1,353✔
1735
        for _, surl := range URLs {
3,739✔
1736
                url, err := url.Parse(fmt.Sprintf("%s://%s", scheme, surl))
2,386✔
1737
                if err != nil {
2,386✔
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
2,386✔
1744
                for _, u := range cfg.URLs {
6,031✔
1745
                        // URLs that we receive never have user info, but the
3,645✔
1746
                        // ones that were configured may have. Simply compare
3,645✔
1747
                        // host and port to decide if they are equal or not.
3,645✔
1748
                        if url.Host == u.Host && url.Port() == u.Port() {
5,353✔
1749
                                dup = true
1,708✔
1750
                                break
1,708✔
1751
                        }
1752
                }
1753
                if !dup {
3,064✔
1754
                        cfg.urls = append(cfg.urls, url)
678✔
1755
                        cfg.saveTLSHostname(url)
678✔
1756
                }
678✔
1757
        }
1758
        // Add the configured one
1759
        cfg.urls = append(cfg.urls, cfg.URLs...)
1,353✔
1760
}
1761

1762
// Similar to setInfoHostPortAndGenerateJSON, but for leafNodeInfo.
1763
func (s *Server) setLeafNodeInfoHostPortAndIP() error {
3,622✔
1764
        opts := s.getOpts()
3,622✔
1765
        if opts.LeafNode.Advertise != _EMPTY_ {
3,633✔
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 {
3,611✔
1773
                s.leafNodeInfo.Host = opts.LeafNode.Host
3,611✔
1774
                s.leafNodeInfo.Port = opts.LeafNode.Port
3,611✔
1775
                // If the host is "0.0.0.0" or "::" we need to resolve to a public IP.
3,611✔
1776
                // This will return at most 1 IP.
3,611✔
1777
                hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(s.leafNodeInfo.Host, false)
3,611✔
1778
                if err != nil {
3,611✔
1779
                        return err
×
1780
                }
×
1781
                if hostIsIPAny {
3,914✔
1782
                        if len(ips) == 0 {
303✔
1783
                                s.Errorf("Could not find any non-local IP for leafnode's listen specification %q",
×
1784
                                        s.leafNodeInfo.Host)
×
1785
                        } else {
303✔
1786
                                // Take the first from the list...
303✔
1787
                                s.leafNodeInfo.Host = ips[0]
303✔
1788
                        }
303✔
1789
                }
1790
        }
1791
        // Use just host:port for the IP
1792
        s.leafNodeInfo.IP = net.JoinHostPort(s.leafNodeInfo.Host, strconv.Itoa(s.leafNodeInfo.Port))
3,622✔
1793
        if opts.LeafNode.Advertise != _EMPTY_ {
3,633✔
1794
                s.Noticef("Advertise address for leafnode is set to %s", s.leafNodeInfo.IP)
11✔
1795
        }
11✔
1796
        return nil
3,622✔
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) {
1,341✔
1812
        var accName string
1,341✔
1813
        c.mu.Lock()
1,341✔
1814
        cid := c.cid
1,341✔
1815
        acc := c.acc
1,341✔
1816
        if acc != nil {
2,682✔
1817
                accName = acc.Name
1,341✔
1818
        }
1,341✔
1819
        myRemoteDomain := c.leaf.remoteDomain
1,341✔
1820
        mySrvName := c.leaf.remoteServer
1,341✔
1821
        remoteAccName := c.leaf.remoteAccName
1,341✔
1822
        myClustName := c.leaf.remoteCluster
1,341✔
1823
        solicited := c.leaf.remote != nil
1,341✔
1824
        c.mu.Unlock()
1,341✔
1825

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

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

1859
        srvDecorated := func() string {
1,547✔
1860
                if myClustName == _EMPTY_ {
227✔
1861
                        return mySrvName
21✔
1862
                }
21✔
1863
                return fmt.Sprintf("%s/%s", mySrvName, myClustName)
185✔
1864
        }
1865

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

1,341✔
1879
        // Check if backwards compatibility has been enabled and needs to be acted on
1,341✔
1880
        forceSysAccDeny := false
1,341✔
1881
        if len(opts.JsAccDefaultDomain) > 0 {
1,378✔
1882
                if acc == sysAcc {
48✔
1883
                        for _, d := range opts.JsAccDefaultDomain {
22✔
1884
                                if d == _EMPTY_ {
19✔
1885
                                        // Extending JetStream via leaf node is mutually exclusive with a domain mapping to the empty/default domain.
8✔
1886
                                        // As soon as one mapping to "" is found, disable the ability to extend JS via a leaf node.
8✔
1887
                                        c.Noticef("Not extending remote JetStream domain %q due to presence of empty default domain", myRemoteDomain)
8✔
1888
                                        forceSysAccDeny = true
8✔
1889
                                        break
8✔
1890
                                }
1891
                        }
1892
                } else if domain, ok := opts.JsAccDefaultDomain[accName]; ok && domain == _EMPTY_ {
41✔
1893
                        // for backwards compatibility with old setups that do not have a domain name set
15✔
1894
                        c.Debugf("Skipping deny %q for account %q due to default domain", jsAllAPI, accName)
15✔
1895
                        return
15✔
1896
                }
15✔
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)) ||
1,326✔
1906
                sysAcc == nil || acc == nil || forceSysAccDeny {
2,494✔
1907
                // If domain names mismatch always deny. This applies to system accounts as well as non system accounts.
1,168✔
1908
                // Not having a system account, account or JetStream disabled is considered a mismatch as well.
1,168✔
1909
                if acc != nil && acc == sysAcc {
1,302✔
1910
                        c.Noticef("System account connected from %s", srvDecorated())
134✔
1911
                        c.Noticef("JetStream not extended, domains differ")
134✔
1912
                        c.mergeDenyPermissionsLocked(both, denyAllJs)
134✔
1913
                        // When a remote with a system account is present in a server, unless otherwise disabled, the server will be
134✔
1914
                        // started in observer mode. Now that it is clear that this not used, turn the observer mode off.
134✔
1915
                        if solicited && meta != nil && meta.IsObserver() {
163✔
1916
                                meta.setObserver(false, extNotExtended)
29✔
1917
                                c.Debugf("Turning JetStream metadata controller Observer Mode off")
29✔
1918
                                // Take note that the domain was not extended to avoid this state from startup.
29✔
1919
                                writePeerState(js.config.StoreDir, meta.currentPeerState())
29✔
1920
                                // Meta controller can't be leader yet.
29✔
1921
                                // Yet it is possible that due to observer mode every server already stopped campaigning.
29✔
1922
                                // Therefore this server needs to be kicked into campaigning gear explicitly.
29✔
1923
                                meta.Campaign()
29✔
1924
                        }
29✔
1925
                } else {
1,034✔
1926
                        c.Noticef("JetStream using domains: local %q, remote %q", opts.JetStreamDomain, myRemoteDomain)
1,034✔
1927
                        c.mergeDenyPermissionsLocked(both, denyAllClientJs)
1,034✔
1928
                }
1,034✔
1929
                blockMappingOutgoing = true
1,168✔
1930
        } else if acc == sysAcc {
230✔
1931
                // system account and same domain
72✔
1932
                s.sys.client.Noticef("Extending JetStream domain %q as System Account connected from server %s",
72✔
1933
                        myRemoteDomain, srvDecorated())
72✔
1934
                // In an extension use case, pin leadership to server remotes connect to.
72✔
1935
                // Therefore, server with a remote that are not already in observer mode, need to be put into it.
72✔
1936
                if solicited && meta != nil && !meta.IsObserver() {
76✔
1937
                        meta.setObserver(true, extExtended)
4✔
1938
                        c.Debugf("Turning JetStream metadata controller Observer Mode on - System Account Connected")
4✔
1939
                        // Take note that the domain was not extended to avoid this state next startup.
4✔
1940
                        writePeerState(js.config.StoreDir, meta.currentPeerState())
4✔
1941
                        // If this server is the leader already, step down so a new leader can be elected (that is not an observer)
4✔
1942
                        meta.StepDown()
4✔
1943
                }
4✔
1944
        } else {
86✔
1945
                // This deny is needed in all cases (system account shared or not)
86✔
1946
                // If the system account is shared, jsAllAPI traffic will go through the system account.
86✔
1947
                // So in order to prevent duplicate delivery (from system and actual account) suppress it on the account.
86✔
1948
                // If the system account is NOT shared, jsAllAPI traffic has no business
86✔
1949
                c.Debugf("Adding deny %+v for account %q", denyAllClientJs, accName)
86✔
1950
                c.mergeDenyPermissionsLocked(both, denyAllClientJs)
86✔
1951
        }
86✔
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 {
1,579✔
1955
                for src, dest := range generateJSMappingTable(opts.JetStreamDomain) {
2,530✔
1956
                        if err := acc.AddMapping(src, dest); err != nil {
2,277✔
1957
                                c.Debugf("Error adding JetStream domain mapping: %s", err.Error())
×
1958
                        } else {
2,277✔
1959
                                c.Debugf("Adding JetStream Domain Mapping %q -> %s to account %q", src, dest, accName)
2,277✔
1960
                        }
2,277✔
1961
                }
1962
                if blockMappingOutgoing {
475✔
1963
                        src := fmt.Sprintf(jsDomainAPI, opts.JetStreamDomain)
222✔
1964
                        // make sure that messages intended for this domain, do not leave the cluster via this leaf node connection
222✔
1965
                        // This is a guard against a miss-config with two identical domain names and will only cover some forms
222✔
1966
                        // of this issue, not all of them.
222✔
1967
                        // This guards against a hub and a spoke having the same domain name.
222✔
1968
                        // But not two spokes having the same one and the request coming from the hub.
222✔
1969
                        c.mergeDenyPermissionsLocked(pub, []string{src})
222✔
1970
                        c.Debugf("Adding deny %q for outgoing messages to account %q", src, accName)
222✔
1971
                }
222✔
1972
        }
1973
}
1974

1975
func (s *Server) removeLeafNodeConnection(c *client) {
1,694✔
1976
        c.mu.Lock()
1,694✔
1977
        cid := c.cid
1,694✔
1978
        if c.leaf != nil {
3,388✔
1979
                if c.leaf.tsubt != nil {
2,929✔
1980
                        c.leaf.tsubt.Stop()
1,235✔
1981
                        c.leaf.tsubt = nil
1,235✔
1982
                }
1,235✔
1983
                if c.leaf.gwSub != nil {
2,343✔
1984
                        s.gwLeafSubs.Remove(c.leaf.gwSub)
649✔
1985
                        // We need to set this to nil for GC to release the connection
649✔
1986
                        c.leaf.gwSub = nil
649✔
1987
                }
649✔
1988
        }
1989
        proxyKey := c.proxyKey
1,694✔
1990
        c.mu.Unlock()
1,694✔
1991
        s.mu.Lock()
1,694✔
1992
        delete(s.leafs, cid)
1,694✔
1993
        if proxyKey != _EMPTY_ {
1,698✔
1994
                s.removeProxiedConn(proxyKey, cid)
4✔
1995
        }
4✔
1996
        s.mu.Unlock()
1,694✔
1997
        s.removeFromTempClients(cid)
1,694✔
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 {
697✔
2044
        // Way to detect clients that incorrectly connect to the route listen
697✔
2045
        // port. Client provided "lang" in the CONNECT protocol while LEAFNODEs don't.
697✔
2046
        if lang != _EMPTY_ {
697✔
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{}
697✔
2054
        if err := json.Unmarshal(arg, proto); err != nil {
697✔
2055
                return err
×
2056
        }
×
2057

2058
        // Reject a cluster that contains spaces.
2059
        if proto.Cluster != _EMPTY_ && strings.Contains(proto.Cluster, " ") {
698✔
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 {
699✔
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_ {
693✔
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_ {
695✔
2083
                major, minor, update, _ := versionComponents(mv)
2✔
2084
                if !versionAtLeast(proto.Version, major, minor, update) {
3✔
2085
                        // We are going to send back an INFO because otherwise recent
1✔
2086
                        // versions of the remote server would simply break the connection
1✔
2087
                        // after 2 seconds if not receiving it. Instead, we want the
1✔
2088
                        // other side to just "stall" until we finish waiting for the holding
1✔
2089
                        // period and close the connection below.
1✔
2090
                        s.sendPermsAndAccountInfo(c)
1✔
2091
                        c.sendErrAndErr(fmt.Sprintf("connection rejected since minimum version required is %q", mv))
1✔
2092
                        select {
1✔
2093
                        case <-c.srv.quitCh:
1✔
2094
                        case <-time.After(leafNodeWaitBeforeClose):
×
2095
                        }
2096
                        c.closeConnection(MinimumVersionRequired)
1✔
2097
                        return ErrMinimumVersionRequired
1✔
2098
                }
2099
        }
2100

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

692✔
2189
        return nil
692✔
2190
}
2191

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

2,146✔
2197
        // Only applicable if we have JS and the leafnode has JS as well.
2,146✔
2198
        // We check for remote JS outside.
2,146✔
2199
        if !js.isEnabled() || acc == nil {
3,379✔
2200
                return
1,233✔
2201
        }
1,233✔
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)
913✔
2209
        if jsa == nil {
1,266✔
2210
                return
353✔
2211
        }
353✔
2212

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

560✔
2227
        // Now loop through all candidates and check if we are the leader and have NOT
560✔
2228
        // created the sync up consumer.
560✔
2229
        for _, mset := range streams {
572✔
2230
                mset.retryDisconnectedSyncConsumers()
12✔
2231
        }
12✔
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 {
200,098✔
2236
        if c.leaf == nil {
200,098✔
2237
                return _EMPTY_
×
2238
        }
×
2239
        return c.leaf.remoteCluster
200,098✔
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) {
693✔
2245
        // Copy
693✔
2246
        s.mu.Lock()
693✔
2247
        info := s.copyLeafNodeInfo()
693✔
2248
        s.mu.Unlock()
693✔
2249
        c.mu.Lock()
693✔
2250
        info.CID = c.cid
693✔
2251
        info.Import = c.opts.Import
693✔
2252
        info.Export = c.opts.Export
693✔
2253
        info.RemoteAccount = c.acc.Name
693✔
2254
        // s.SystemAccount() uses an atomic operation and does not get the server lock, so this is safe.
693✔
2255
        info.IsSystemAccount = c.acc == s.SystemAccount()
693✔
2256
        info.ConnectInfo = true
693✔
2257
        c.enqueueProto(generateInfoJSON(info))
693✔
2258
        c.mu.Unlock()
693✔
2259
}
693✔
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) {
1,341✔
2265
        acc := c.acc
1,341✔
2266
        if acc == nil {
1,341✔
2267
                c.Debugf("Leafnode does not have an account bound")
×
2268
                return
×
2269
        }
×
2270
        // Collect all account subs here.
2271
        _subs := [1024]*subscription{}
1,341✔
2272
        subs := _subs[:0]
1,341✔
2273
        ims := []string{}
1,341✔
2274

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

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

1,341✔
2283
        // To make printing look better when no friendly name present.
1,341✔
2284
        if accNTag != _EMPTY_ {
1,352✔
2285
                accNTag = "/" + accNTag
11✔
2286
        }
11✔
2287

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

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

1,341✔
2298
        // Since leaf nodes only send on interest, if the bound
1,341✔
2299
        // account has import services we need to send those over.
1,341✔
2300
        for isubj := range acc.imports.services {
6,371✔
2301
                if c.isSpokeLeafNode() && !c.canSubscribe(isubj) {
5,319✔
2302
                        c.Debugf("Not permitted to import service %q on behalf of %s%s", isubj, accName, accNTag)
289✔
2303
                        continue
289✔
2304
                }
2305
                ims = append(ims, isubj)
4,741✔
2306
        }
2307
        // Likewise for mappings.
2308
        for _, m := range acc.mappings {
3,738✔
2309
                if c.isSpokeLeafNode() && !c.canSubscribe(m.src) {
2,433✔
2310
                        c.Debugf("Not permitted to import mapping %q on behalf of %s%s", m.src, accName, accNTag)
36✔
2311
                        continue
36✔
2312
                }
2313
                ims = append(ims, m.src)
2,361✔
2314
        }
2315

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

1,341✔
2320
        // Check if we have to create the LDS.
1,341✔
2321
        if lds == _EMPTY_ {
2,375✔
2322
                lds = leafNodeLoopDetectionSubjectPrefix + nuid.Next()
1,034✔
2323
                acc.mu.Lock()
1,034✔
2324
                acc.lds = lds
1,034✔
2325
                acc.mu.Unlock()
1,034✔
2326
        }
1,034✔
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{}
1,341✔
2331
        gws := gwsa[:0]
1,341✔
2332
        s.getOutboundGatewayConnections(&gws)
1,341✔
2333
        for _, cgw := range gws {
1,423✔
2334
                cgw.mu.Lock()
82✔
2335
                gw := cgw.gw
82✔
2336
                cgw.mu.Unlock()
82✔
2337
                if gw != nil {
164✔
2338
                        if ei, _ := gw.outsim.Load(accName); ei != nil {
164✔
2339
                                if e := ei.(*outsie); e != nil && e.sl != nil {
164✔
2340
                                        e.sl.All(&subs)
82✔
2341
                                }
82✔
2342
                        }
2343
                }
2344
        }
2345

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

2356
        // Now walk the results and add them to our smap
2357
        rc := c.leaf.remoteCluster
1,341✔
2358
        c.leaf.smap = make(map[string]int32)
1,341✔
2359
        for _, sub := range subs {
39,278✔
2360
                // Check perms regardless of role.
37,937✔
2361
                if c.perms != nil && !c.canSubscribe(string(sub.subject)) {
40,283✔
2362
                        c.Debugf("Not permitted to subscribe to %q on behalf of %s%s", sub.subject, accName, accNTag)
2,346✔
2363
                        continue
2,346✔
2364
                }
2365
                // Don't advertise interest from leafnodes to other isolated leafnodes.
2366
                if sub.client.kind == LEAF && c.isIsolatedLeafNode() {
35,606✔
2367
                        continue
15✔
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)) {
65,685✔
2373
                        count := int32(1)
30,109✔
2374
                        if len(sub.queue) > 0 && sub.qw > 0 {
30,119✔
2375
                                count = sub.qw
10✔
2376
                        }
10✔
2377
                        c.leaf.smap[keyFromSub(sub)] += count
30,109✔
2378
                        if c.leaf.tsub == nil {
31,374✔
2379
                                c.leaf.tsub = make(map[*subscription]struct{})
1,265✔
2380
                        }
1,265✔
2381
                        c.leaf.tsub[sub] = struct{}{}
30,109✔
2382
                }
2383
        }
2384
        // FIXME(dlc) - We need to update appropriately on an account claims update.
2385
        for _, isubj := range ims {
8,443✔
2386
                c.leaf.smap[isubj]++
7,102✔
2387
        }
7,102✔
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 {
1,444✔
2392
                c.leaf.smap[oldGWReplyPrefix+"*.>"]++
103✔
2393
                c.leaf.smap[gwReplyPrefix+">"]++
103✔
2394
        }
103✔
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]++
1,341✔
2398

1,341✔
2399
        // Check if we need to add an existing siReply to our map.
1,341✔
2400
        // This will be a prefix so add on the wildcard.
1,341✔
2401
        if siReply != nil {
1,361✔
2402
                wcsub := append(siReply, '>')
20✔
2403
                c.leaf.smap[string(wcsub)]++
20✔
2404
        }
20✔
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
1,341✔
2408
        for key, n := range c.leaf.smap {
28,054✔
2409
                c.writeLeafSub(&b, key, n)
26,713✔
2410
        }
26,713✔
2411
        if b.Len() > 0 {
2,682✔
2412
                c.enqueueProto(b.Bytes())
1,341✔
2413
        }
1,341✔
2414
        if c.leaf.tsub != nil {
2,607✔
2415
                // Clear the tsub map after 5 seconds.
1,266✔
2416
                c.leaf.tsubt = time.AfterFunc(5*time.Second, func() {
1,297✔
2417
                        c.mu.Lock()
31✔
2418
                        if c.leaf != nil {
62✔
2419
                                c.leaf.tsub = nil
31✔
2420
                                c.leaf.tsubt = nil
31✔
2421
                        }
31✔
2422
                        c.mu.Unlock()
31✔
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) {
197,931✔
2429
        acc, err := s.LookupAccount(accName)
197,931✔
2430
        if acc == nil || err != nil {
198,090✔
2431
                s.Debugf("No or bad account for %q, failed to update interest from gateway", accName)
159✔
2432
                return
159✔
2433
        }
159✔
2434
        acc.updateLeafNodes(sub, delta)
197,772✔
2435
}
2436

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

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

2451
        acc.mu.RLock()
2,371,675✔
2452
        // First check if we even have leafnodes here.
2,371,675✔
2453
        if acc.nleafs == 0 {
4,675,751✔
2454
                acc.mu.RUnlock()
2,304,076✔
2455
                return
2,304,076✔
2456
        }
2,304,076✔
2457

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

67,599✔
2461
        // Capture the cluster even if its empty.
67,599✔
2462
        var cluster string
67,599✔
2463
        if sub.origin != nil {
115,999✔
2464
                cluster = bytesToString(sub.origin)
48,400✔
2465
        }
48,400✔
2466

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

2474
        // We can release the general account lock.
2475
        acc.mu.RUnlock()
47,486✔
2476

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

47,486✔
2481
        // Do this once.
47,486✔
2482
        subject := string(sub.subject)
47,486✔
2483

47,486✔
2484
        // Walk the connected leafnodes.
47,486✔
2485
        for _, ln := range acc.lleafs {
106,743✔
2486
                if ln == sub.client {
89,965✔
2487
                        continue
30,708✔
2488
                }
2489
                ln.mu.Lock()
28,549✔
2490
                // Don't advertise interest from leafnodes to other isolated leafnodes.
28,549✔
2491
                if sub.client.kind == LEAF && ln.isIsolatedLeafNode() {
28,580✔
2492
                        ln.mu.Unlock()
31✔
2493
                        continue
31✔
2494
                }
2495
                // If `hubOnly` is true, it means that we want to update only leafnodes
2496
                // that connect to this server (so isHubLeafNode() would return `true`).
2497
                if hubOnly && !ln.isHubLeafNode() {
28,524✔
2498
                        ln.mu.Unlock()
6✔
2499
                        continue
6✔
2500
                }
2501
                // Check to make sure this sub does not have an origin cluster that matches the leafnode.
2502
                // If skipped, make sure that we still let go the "$LDS." subscription that allows
2503
                // the detection of loops as long as different cluster.
2504
                clusterDifferent := cluster != ln.remoteCluster()
28,512✔
2505
                if (isLDS && clusterDifferent) || ((cluster == _EMPTY_ || clusterDifferent) && (delta <= 0 || ln.canSubscribe(subject))) {
52,611✔
2506
                        ln.updateSmap(sub, delta, isLDS)
24,099✔
2507
                }
24,099✔
2508
                ln.mu.Unlock()
28,512✔
2509
        }
2510
}
2511

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

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

2526
        // If we are solicited make sure this is a local client or a non-solicited leaf node
2527
        skind := sub.client.kind
24,084✔
2528
        updateClient := skind == CLIENT || skind == SYSTEM || skind == JETSTREAM || skind == ACCOUNT
24,084✔
2529
        if !isLDS && c.isSpokeLeafNode() && !(updateClient || (skind == LEAF && !sub.client.isSpokeLeafNode())) {
32,877✔
2530
                return
8,793✔
2531
        }
8,793✔
2532

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

2546
        key := keyFromSub(sub)
15,288✔
2547
        n, ok := c.leaf.smap[key]
15,288✔
2548
        if delta < 0 && !ok {
16,177✔
2549
                return
889✔
2550
        }
889✔
2551

2552
        // We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
2553
        update := sub.queue != nil || (n <= 0 && n+delta > 0) || (n > 0 && n+delta <= 0)
14,399✔
2554
        n += delta
14,399✔
2555
        if n > 0 {
25,075✔
2556
                c.leaf.smap[key] = n
10,676✔
2557
        } else {
14,399✔
2558
                delete(c.leaf.smap, key)
3,723✔
2559
        }
3,723✔
2560
        if update {
24,366✔
2561
                c.sendLeafNodeSubUpdate(key, n)
9,967✔
2562
        }
9,967✔
2563
}
2564

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

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

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

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

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

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

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

2656
// Helper function to build the key that prevents collisions between normal
2657
// routed subscriptions and routed subscriptions on behalf of a leafnode.
2658
// Keys will look like this:
2659
// "R foo"          -> plain routed sub on "foo"
2660
// "R foo bar"      -> queue routed sub on "foo", queue "bar"
2661
// "L foo bar"      -> plain routed leaf sub on "foo", leaf "bar"
2662
// "L foo bar baz"  -> queue routed sub on "foo", queue "bar", leaf "baz"
2663
func keyFromSubWithOrigin(sub *subscription) string {
585,541✔
2664
        var sb strings.Builder
585,541✔
2665
        sb.Grow(2 + len(sub.origin) + 1 + len(sub.subject) + 1 + len(sub.queue))
585,541✔
2666
        leaf := len(sub.origin) > 0
585,541✔
2667
        if leaf {
602,240✔
2668
                sb.WriteByte(keyRoutedLeafSubByte)
16,699✔
2669
        } else {
585,541✔
2670
                sb.WriteByte(keyRoutedSubByte)
568,842✔
2671
        }
568,842✔
2672
        sb.WriteByte(' ')
585,541✔
2673
        sb.Write(sub.subject)
585,541✔
2674
        if sub.queue != nil {
608,016✔
2675
                sb.WriteByte(' ')
22,475✔
2676
                sb.Write(sub.queue)
22,475✔
2677
        }
22,475✔
2678
        if leaf {
602,240✔
2679
                sb.WriteByte(' ')
16,699✔
2680
                sb.Write(sub.origin)
16,699✔
2681
        }
16,699✔
2682
        return sb.String()
585,541✔
2683
}
2684

2685
// Lock should be held.
2686
func (c *client) writeLeafSub(w *bytes.Buffer, key string, n int32) {
36,684✔
2687
        if key == _EMPTY_ {
36,684✔
2688
                return
×
2689
        }
×
2690
        if n > 0 {
69,644✔
2691
                w.WriteString("LS+ " + key)
32,960✔
2692
                // Check for queue semantics, if found write n.
32,960✔
2693
                if strings.Contains(key, " ") {
35,243✔
2694
                        w.WriteString(" ")
2,283✔
2695
                        var b [12]byte
2,283✔
2696
                        var i = len(b)
2,283✔
2697
                        for l := n; l > 0; l /= 10 {
5,459✔
2698
                                i--
3,176✔
2699
                                b[i] = digits[l%10]
3,176✔
2700
                        }
3,176✔
2701
                        w.Write(b[i:])
2,283✔
2702
                        if c.trace {
2,283✔
2703
                                arg := fmt.Sprintf("%s %d", key, n)
×
2704
                                c.traceOutOp("LS+", []byte(arg))
×
2705
                        }
×
2706
                } else if c.trace {
30,868✔
2707
                        c.traceOutOp("LS+", []byte(key))
191✔
2708
                }
191✔
2709
        } else {
3,724✔
2710
                w.WriteString("LS- " + key)
3,724✔
2711
                if c.trace {
3,737✔
2712
                        c.traceOutOp("LS-", []byte(key))
13✔
2713
                }
13✔
2714
        }
2715
        w.WriteString(CR_LF)
36,684✔
2716
}
2717

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

32,592✔
2723
        srv := c.srv
32,592✔
2724
        if srv == nil {
32,592✔
2725
                return nil
×
2726
        }
×
2727

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

32,592✔
2732
        args := splitArg(arg)
32,592✔
2733
        sub := &subscription{client: c}
32,592✔
2734

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

32,592✔
2755
        c.mu.Lock()
32,592✔
2756
        if c.isClosed() {
32,610✔
2757
                c.mu.Unlock()
18✔
2758
                return nil
18✔
2759
        }
18✔
2760

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

32,574✔
2765
        if ldsPrefix && bytesToString(sub.subject) == acc.getLDSubject() {
32,580✔
2766
                c.mu.Unlock()
6✔
2767
                c.handleLeafNodeLoop(true)
6✔
2768
                return nil
6✔
2769
        }
6✔
2770

2771
        // Check permissions if applicable. (but exclude the $LDS, $GR and _GR_)
2772
        checkPerms := true
32,568✔
2773
        if sub.subject[0] == '$' || sub.subject[0] == '_' {
62,212✔
2774
                if ldsPrefix ||
29,644✔
2775
                        bytes.HasPrefix(sub.subject, []byte(oldGWReplyPrefix)) ||
29,644✔
2776
                        bytes.HasPrefix(sub.subject, []byte(gwReplyPrefix)) {
31,710✔
2777
                        checkPerms = false
2,066✔
2778
                }
2,066✔
2779
        }
2780

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

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

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

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

32,246✔
2832
        // Only add in shadow subs if a new sub or qsub.
32,246✔
2833
        if osub == nil {
63,002✔
2834
                if err := c.addShadowSubscriptions(acc, sub, true); err != nil {
30,756✔
2835
                        c.Errorf(err.Error())
×
2836
                }
×
2837
        }
2838

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

32,246✔
2853
        return nil
32,246✔
2854
}
2855

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

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

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

3,434✔
2878
        acc := c.acc
3,434✔
2879
        srv := c.srv
3,434✔
2880

3,434✔
2881
        c.mu.Lock()
3,434✔
2882
        if c.isClosed() {
3,461✔
2883
                c.mu.Unlock()
27✔
2884
                return nil
27✔
2885
        }
27✔
2886

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

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

2916
func (c *client) processLeafHeaderMsgArgs(arg []byte) error {
476✔
2917
        // Unroll splitArgs to avoid runtime/heap issues
476✔
2918
        a := [MAX_MSG_ARGS][]byte{}
476✔
2919
        args := a[:0]
476✔
2920
        start := -1
476✔
2921
        for i, b := range arg {
31,594✔
2922
                switch b {
31,118✔
2923
                case ' ', '\t', '\r', '\n':
1,367✔
2924
                        if start >= 0 {
2,734✔
2925
                                args = append(args, arg[start:i])
1,367✔
2926
                                start = -1
1,367✔
2927
                        }
1,367✔
2928
                default:
29,751✔
2929
                        if start < 0 {
31,594✔
2930
                                start = i
1,843✔
2931
                        }
1,843✔
2932
                }
2933
        }
2934
        if start >= 0 {
952✔
2935
                args = append(args, arg[start:])
476✔
2936
        }
476✔
2937

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

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

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

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

476✔
2997
        return nil
476✔
2998
}
2999

3000
func (c *client) processLeafMsgArgs(arg []byte) error {
117,134✔
3001
        // Unroll splitArgs to avoid runtime/heap issues
117,134✔
3002
        a := [MAX_MSG_ARGS][]byte{}
117,134✔
3003
        args := a[:0]
117,134✔
3004
        start := -1
117,134✔
3005
        for i, b := range arg {
3,770,444✔
3006
                switch b {
3,653,310✔
3007
                case ' ', '\t', '\r', '\n':
168,697✔
3008
                        if start >= 0 {
337,394✔
3009
                                args = append(args, arg[start:i])
168,697✔
3010
                                start = -1
168,697✔
3011
                        }
168,697✔
3012
                default:
3,484,613✔
3013
                        if start < 0 {
3,770,444✔
3014
                                start = i
285,831✔
3015
                        }
285,831✔
3016
                }
3017
        }
3018
        if start >= 0 {
234,268✔
3019
                args = append(args, arg[start:])
117,134✔
3020
        }
117,134✔
3021

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

22,556✔
3053
                // Grab queue names.
22,556✔
3054
                if c.pa.reply != nil {
22,715✔
3055
                        c.pa.queues = args[3 : len(args)-1]
159✔
3056
                } else {
22,556✔
3057
                        c.pa.queues = args[2 : len(args)-1]
22,397✔
3058
                }
22,397✔
3059
        }
3060
        if c.pa.size < 0 {
117,134✔
3061
                return fmt.Errorf("processLeafMsgArgs Bad or Missing Size: '%s'", args)
×
3062
        }
×
3063

3064
        // Common ones processed after check for arg length
3065
        c.pa.subject = args[0]
117,134✔
3066

117,134✔
3067
        return nil
117,134✔
3068
}
3069

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

115,433✔
3077
        srv, acc, subject := c.srv, c.acc, string(c.pa.subject)
115,433✔
3078

115,433✔
3079
        // Mostly under testing scenarios.
115,433✔
3080
        if srv == nil || acc == nil {
115,434✔
3081
                return
1✔
3082
        }
1✔
3083

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

115,432✔
3089
        genid := atomic.LoadUint64(&c.acc.sl.genid)
115,432✔
3090
        if genid == c.in.genid && c.in.results != nil {
228,505✔
3091
                r, ok = c.in.results[subject]
113,073✔
3092
        } else {
115,432✔
3093
                // Reset our L1 completely.
2,359✔
3094
                c.in.results = make(map[string]*SublistResult)
2,359✔
3095
                c.in.genid = genid
2,359✔
3096
        }
2,359✔
3097

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

3115
        // Collect queue names if needed.
3116
        var qnames [][]byte
115,432✔
3117

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

3139
        // Now deal with gateways
3140
        if c.srv.gateway.enabled {
128,801✔
3141
                c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, qnames, true)
13,369✔
3142
        }
13,369✔
3143
}
3144

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

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

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

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

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

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

1,966✔
3221
        remote.RLock()
1,966✔
3222
        defer remote.RUnlock()
1,966✔
3223

1,966✔
3224
        tlsRequired := remote.TLS || remote.TLSConfig != nil
1,966✔
3225
        if tlsRequired {
2,044✔
3226
                if remote.TLSConfig != nil {
129✔
3227
                        tlsConfig = remote.TLSConfig.Clone()
51✔
3228
                } else {
78✔
3229
                        tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}
27✔
3230
                }
27✔
3231
                tlsName = remote.tlsName
78✔
3232
                tlsTimeout = remote.TLSTimeout
78✔
3233
                if tlsTimeout == 0 {
122✔
3234
                        tlsTimeout = float64(TLS_TIMEOUT / time.Second)
44✔
3235
                }
44✔
3236
        }
3237

3238
        return tlsRequired, tlsConfig, tlsName, tlsTimeout
1,966✔
3239
}
3240

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

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

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

3315
        var resp *http.Response
46✔
3316

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

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

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

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

3364
const connectProcessTimeout = 2 * time.Second
3365

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

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

3382
        // Spin up the write loop.
3383
        s.startGoRoutine(func() { c.writeLoop() })
1,371✔
3384

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

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

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

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

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

© 2026 Coveralls, Inc