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

nats-io / nats-server / 26271268085

21 May 2026 04:40PM UTC coverage: 81.166% (+3.1%) from 78.111%
26271268085

push

github

web-flow
MQTT: test NATS wildcards in MQTT topics (#8225)

Add coverage to show how NATS wildcards characters '*' and '>' are used
in MQTT topics. The tests fix the following behavior:
1) MQTT literal topic may become a NATS wildcard subject.
   For example, when `foo\>` is converted to `foo.>`, the
   server does not escape the `>` character. And the subject
   gets treated as a regular wildcard subject.
2) ACL permissions on MQTT clients are enforced after topics
   are converted to NATS subjects.

75844 of 93443 relevant lines covered (81.17%)

636054.5 hits per line

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

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

14
package server
15

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

337
        if o.Gateway.Name == _EMPTY_ && o.Gateway.Port == 0 {
7,376✔
338
                return nil
3,350✔
339
        }
3,350✔
340
        // If we are here we have both leaf nodes and gateways defined, make sure there
341
        // is a system account defined.
342
        if o.SystemAccount == _EMPTY_ {
677✔
343
                return fmt.Errorf("leaf nodes and gateways (both being defined) require a system account to also be configured")
1✔
344
        }
1✔
345
        if err := validatePinnedCerts(o.LeafNode.TLSPinnedCerts); err != nil {
675✔
346
                return fmt.Errorf("leafnode: %v", err)
×
347
        }
×
348
        return nil
675✔
349
}
350

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

362
// Used to validate user names in LeafNode configuration.
363
// - rejects mix of single and multiple users.
364
// - rejects duplicate user names.
365
func validateLeafNodeAuthOptions(o *Options) error {
8,213✔
366
        if len(o.LeafNode.Users) == 0 {
16,400✔
367
                return nil
8,187✔
368
        }
8,187✔
369
        if o.LeafNode.Username != _EMPTY_ {
28✔
370
                return fmt.Errorf("can not have a single user/pass and a users array")
2✔
371
        }
2✔
372
        if o.LeafNode.Nkey != _EMPTY_ {
24✔
373
                return fmt.Errorf("can not have a single nkey and a users array")
×
374
        }
×
375
        users := map[string]struct{}{}
24✔
376
        for _, u := range o.LeafNode.Users {
62✔
377
                if _, exists := users[u.Username]; exists {
40✔
378
                        return fmt.Errorf("duplicate user %q detected in leafnode authorization", u.Username)
2✔
379
                }
2✔
380
                users[u.Username] = struct{}{}
36✔
381
        }
382
        return nil
22✔
383
}
384

385
func validateLeafNodeProxyOptions(remote *RemoteLeafOpts) ([]string, error) {
2,066✔
386
        var warnings []string
2,066✔
387

2,066✔
388
        if remote.Proxy.URL == _EMPTY_ {
4,106✔
389
                return warnings, nil
2,040✔
390
        }
2,040✔
391

392
        proxyURL, err := url.Parse(remote.Proxy.URL)
26✔
393
        if err != nil {
27✔
394
                return warnings, fmt.Errorf("invalid proxy URL: %v", err)
1✔
395
        }
1✔
396

397
        if proxyURL.Scheme != "http" && proxyURL.Scheme != "https" {
27✔
398
                return warnings, fmt.Errorf("proxy URL scheme must be http or https, got: %s", proxyURL.Scheme)
2✔
399
        }
2✔
400

401
        if proxyURL.Host == _EMPTY_ {
25✔
402
                return warnings, fmt.Errorf("proxy URL must specify a host")
2✔
403
        }
2✔
404

405
        if remote.Proxy.Timeout < 0 {
22✔
406
                return warnings, fmt.Errorf("proxy timeout must be >= 0")
1✔
407
        }
1✔
408

409
        if (remote.Proxy.Username == _EMPTY_) != (remote.Proxy.Password == _EMPTY_) {
24✔
410
                return warnings, fmt.Errorf("proxy username and password must both be specified or both be empty")
4✔
411
        }
4✔
412

413
        if len(remote.URLs) > 0 {
32✔
414
                hasWebSocketURL := false
16✔
415
                hasNonWebSocketURL := false
16✔
416

16✔
417
                for _, remoteURL := range remote.URLs {
33✔
418
                        if remoteURL.Scheme == wsSchemePrefix || remoteURL.Scheme == wsSchemePrefixTLS {
30✔
419
                                hasWebSocketURL = true
13✔
420
                                if (remoteURL.Scheme == wsSchemePrefixTLS) &&
13✔
421
                                        remote.TLSConfig == nil && !remote.TLS {
14✔
422
                                        return warnings, fmt.Errorf("proxy is configured but remote URL %s requires TLS and no TLS configuration is provided. When using proxy with TLS endpoints, ensure TLS is properly configured for the leafnode remote", remoteURL.String())
1✔
423
                                }
1✔
424
                        } else {
4✔
425
                                hasNonWebSocketURL = true
4✔
426
                        }
4✔
427
                }
428

429
                if !hasWebSocketURL {
18✔
430
                        warnings = append(warnings, "proxy configuration will be ignored: proxy settings only apply to WebSocket connections (ws:// or wss://), but all configured URLs use TCP connections (nats://)")
3✔
431
                } else if hasNonWebSocketURL {
16✔
432
                        warnings = append(warnings, "proxy configuration will only be used for WebSocket URLs: proxy settings do not apply to TCP connections (nats://)")
1✔
433
                }
1✔
434
        }
435

436
        return warnings, nil
15✔
437
}
438

439
// Wait for the configured reconnect interval before attempting to connect
440
// again to the remote leafnode.
441
func (s *Server) reConnectToRemoteLeafNode(remote *leafNodeCfg) {
257✔
442
        clearInProgress := true
257✔
443
        defer func() {
513✔
444
                s.grWG.Done()
256✔
445
                if clearInProgress {
331✔
446
                        remote.setConnectInProgress(false)
75✔
447
                }
75✔
448
        }()
449
        delay := s.getOpts().LeafNode.ReconnectInterval
257✔
450
        select {
257✔
451
        case <-time.After(delay):
191✔
452
        case <-remote.quitCh:
×
453
                return
×
454
        case <-s.quitCh:
66✔
455
                return
66✔
456
        }
457
        clearInProgress = !connectToRemoteLeafNode(s, remote, false)
191✔
458
}
459

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

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

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

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

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

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

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

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

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

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

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

601
const sharedSysAccDelay = 250 * time.Millisecond
602

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

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

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

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

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

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

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

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

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

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

661
        return conn, nil
10✔
662
}
663

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

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

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

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

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

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

715
        var conn net.Conn
1,612✔
716

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

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

1,612✔
727
        // Set default proxy timeout if not specified
1,612✔
728
        if proxyTimeout == 0 {
3,216✔
729
                proxyTimeout = dialTimeout
1,604✔
730
        }
1,604✔
731

732
        attempts := 0
1,612✔
733

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

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

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

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

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

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

813✔
821
                return true
813✔
822
        }
823

824
        return false
12✔
825
}
826

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

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

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

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

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

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

4,402✔
873
        if !shouldMigrate {
8,745✔
874
                return
4,343✔
875
        }
4,343✔
876

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

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

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

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

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

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

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

4,006✔
949
        port := opts.LeafNode.Port
4,006✔
950
        if port == -1 {
7,836✔
951
                port = 0
3,830✔
952
        }
3,830✔
953

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1692
        var resumeConnect bool
1,423✔
1693

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

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

1,422✔
1716
        finishConnect := info.ConnectInfo
1,422✔
1717
        if resumeConnect && s != nil {
2,106✔
1718
                s.leafNodeResumeConnectProcess(c)
684✔
1719
                if !info.InfoOnConnect {
684✔
1720
                        finishConnect = true
×
1721
                }
×
1722
        }
1723
        if finishConnect {
2,070✔
1724
                s.leafNodeFinishConnectProcess(c)
648✔
1725
        }
648✔
1726

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

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

1,244✔
1765
        if !needsCompression(cm) {
1,337✔
1766
                return false, nil
93✔
1767
        }
93✔
1768

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

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

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

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

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

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

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

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

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

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

1971
        srvDecorated := func() string {
1,543✔
1972
                if myClustName == _EMPTY_ {
235✔
1973
                        return mySrvName
26✔
1974
                }
26✔
1975
                return fmt.Sprintf("%s/%s", mySrvName, myClustName)
183✔
1976
        }
1977

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

689✔
2314
        return nil
689✔
2315
}
2316

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

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

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

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

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

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

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

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

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

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

1,334✔
2408
        // To make printing look better when no friendly name present.
1,334✔
2409
        if accNTag != _EMPTY_ {
1,346✔
2410
                accNTag = "/" + accNTag
12✔
2411
        }
12✔
2412

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

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

1,334✔
2423
        // Since leaf nodes only send on interest, if the bound
1,334✔
2424
        // account has import services we need to send those over.
1,334✔
2425
        for isubj := range acc.imports.services {
6,335✔
2426
                if c.isSpokeLeafNode() && !c.canSubscribe(isubj) {
5,304✔
2427
                        c.Debugf("Not permitted to import service %q on behalf of %s%s", isubj, accName, accNTag)
303✔
2428
                        continue
303✔
2429
                }
2430
                ims = append(ims, isubj)
4,698✔
2431
        }
2432
        // Likewise for mappings.
2433
        for _, m := range acc.mappings {
3,821✔
2434
                if c.isSpokeLeafNode() && !c.canSubscribe(m.src) {
2,523✔
2435
                        c.Debugf("Not permitted to import mapping %q on behalf of %s%s", m.src, accName, accNTag)
36✔
2436
                        continue
36✔
2437
                }
2438
                ims = append(ims, m.src)
2,451✔
2439
        }
2440

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

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

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

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

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

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

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

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

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

2577
        acc.mu.RLock()
2,564,996✔
2578
        // First check if we even have leafnodes here.
2,564,996✔
2579
        if acc.nleafs == 0 {
5,058,749✔
2580
                acc.mu.RUnlock()
2,493,753✔
2581
                return
2,493,753✔
2582
        }
2,493,753✔
2583

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

71,243✔
2587
        // Capture the cluster even if its empty.
71,243✔
2588
        var cluster string
71,243✔
2589
        if sub.origin != nil {
121,637✔
2590
                cluster = bytesToString(sub.origin)
50,394✔
2591
        }
50,394✔
2592

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

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

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

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

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

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

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

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

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

2689
        key := keyFromSub(sub)
16,210✔
2690
        n, ok := c.leaf.smap[key]
16,210✔
2691
        if delta < 0 && !ok {
17,400✔
2692
                return
1,190✔
2693
        }
1,190✔
2694

2695
        // We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
2696
        update := sub.queue != nil || (n <= 0 && n+delta > 0) || (n > 0 && n+delta <= 0)
15,020✔
2697
        n += delta
15,020✔
2698
        if n > 0 {
26,259✔
2699
                c.leaf.smap[key] = n
11,239✔
2700
        } else {
15,020✔
2701
                delete(c.leaf.smap, key)
3,781✔
2702
        }
3,781✔
2703
        if update {
25,225✔
2704
                c.sendLeafNodeSubUpdate(key, n)
10,205✔
2705
        }
10,205✔
2706
}
2707

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

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

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

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

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

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

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

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

2828
// Lock should be held.
2829
func (c *client) writeLeafSub(w *bytes.Buffer, key string, n int32) {
37,212✔
2830
        if key == _EMPTY_ {
37,212✔
2831
                return
×
2832
        }
×
2833
        if n > 0 {
70,642✔
2834
                w.WriteString("LS+ " + key)
33,430✔
2835
                // Check for queue semantics, if found write n.
33,430✔
2836
                if strings.Contains(key, " ") {
35,746✔
2837
                        w.WriteString(" ")
2,316✔
2838
                        var b [12]byte
2,316✔
2839
                        var i = len(b)
2,316✔
2840
                        for l := n; l > 0; l /= 10 {
5,540✔
2841
                                i--
3,224✔
2842
                                b[i] = digits[l%10]
3,224✔
2843
                        }
3,224✔
2844
                        w.Write(b[i:])
2,316✔
2845
                        if c.trace {
2,316✔
2846
                                arg := fmt.Sprintf("%s %d", key, n)
×
2847
                                c.traceOutOp("LS+", []byte(arg))
×
2848
                        }
×
2849
                } else if c.trace {
31,317✔
2850
                        c.traceOutOp("LS+", []byte(key))
203✔
2851
                }
203✔
2852
        } else {
3,782✔
2853
                w.WriteString("LS- " + key)
3,782✔
2854
                if c.trace {
3,793✔
2855
                        c.traceOutOp("LS-", []byte(key))
11✔
2856
                }
11✔
2857
        }
2858
        w.WriteString(CR_LF)
37,212✔
2859
}
2860

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

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

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

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

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

33,100✔
2898
        c.mu.Lock()
33,100✔
2899
        if c.isClosed() {
33,110✔
2900
                c.mu.Unlock()
10✔
2901
                return nil
10✔
2902
        }
10✔
2903

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

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

2922
        // Check permissions if applicable. (but exclude the $LDS, $GR and _GR_)
2923
        checkPerms := true
33,085✔
2924
        if sub.subject[0] == '$' || sub.subject[0] == '_' {
63,239✔
2925
                if ldsPrefix ||
30,154✔
2926
                        bytes.HasPrefix(sub.subject, []byte(oldGWReplyPrefix)) ||
30,154✔
2927
                        bytes.HasPrefix(sub.subject, []byte(gwReplyPrefix)) {
32,184✔
2928
                        checkPerms = false
2,030✔
2929
                }
2,030✔
2930
        }
2931

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

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

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

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

32,742✔
2983
        // Only add in shadow subs if a new sub or qsub.
32,742✔
2984
        if osub == nil {
63,972✔
2985
                if err := c.addShadowSubscriptions(acc, sub); err != nil {
31,230✔
2986
                        c.Errorf(err.Error())
×
2987
                }
×
2988
        }
2989

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

32,742✔
3004
        return nil
32,742✔
3005
}
3006

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

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

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

3,392✔
3029
        srv := c.srv
3,392✔
3030

3,392✔
3031
        c.mu.Lock()
3,392✔
3032
        if c.isClosed() {
3,425✔
3033
                c.mu.Unlock()
33✔
3034
                return nil
33✔
3035
        }
33✔
3036

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

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

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

3075
func (c *client) processLeafHeaderMsgArgs(arg []byte) error {
504✔
3076
        // Unroll splitArgs to avoid runtime/heap issues
504✔
3077
        args := c.argsa[:0]
504✔
3078
        start := -1
504✔
3079
        for i, b := range arg {
35,009✔
3080
                switch b {
34,505✔
3081
                case ' ', '\t', '\r', '\n':
1,457✔
3082
                        if start >= 0 {
2,914✔
3083
                                args = append(args, arg[start:i])
1,457✔
3084
                                start = -1
1,457✔
3085
                        }
1,457✔
3086
                default:
33,048✔
3087
                        if start < 0 {
35,009✔
3088
                                start = i
1,961✔
3089
                        }
1,961✔
3090
                }
3091
        }
3092
        if start >= 0 {
1,008✔
3093
                args = append(args, arg[start:])
504✔
3094
        }
504✔
3095

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

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

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

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

504✔
3160
        return nil
504✔
3161
}
3162

3163
func (c *client) processLeafMsgArgs(arg []byte) error {
66,900✔
3164
        // Unroll splitArgs to avoid runtime/heap issues
66,900✔
3165
        args := c.argsa[:0]
66,900✔
3166
        start := -1
66,900✔
3167
        for i, b := range arg {
2,227,200✔
3168
                switch b {
2,160,300✔
3169
                case ' ', '\t', '\r', '\n':
118,476✔
3170
                        if start >= 0 {
236,952✔
3171
                                args = append(args, arg[start:i])
118,476✔
3172
                                start = -1
118,476✔
3173
                        }
118,476✔
3174
                default:
2,041,824✔
3175
                        if start < 0 {
2,227,200✔
3176
                                start = i
185,376✔
3177
                        }
185,376✔
3178
                }
3179
        }
3180
        if start >= 0 {
133,800✔
3181
                args = append(args, arg[start:])
66,900✔
3182
        }
66,900✔
3183

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

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

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

66,900✔
3234
        return nil
66,900✔
3235
}
3236

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

65,437✔
3244
        srv, acc, subject := c.srv, c.acc, string(c.pa.subject)
65,437✔
3245

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

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

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

65,432✔
3262
        genid := atomic.LoadUint64(&c.acc.sl.genid)
65,432✔
3263
        if genid == c.in.genid && c.in.results != nil {
128,489✔
3264
                r, ok = c.in.results[subject]
63,057✔
3265
        } else {
65,432✔
3266
                // Reset our L1 completely.
2,375✔
3267
                c.in.results = make(map[string]*SublistResult)
2,375✔
3268
                c.in.genid = genid
2,375✔
3269
        }
2,375✔
3270

3271
        // Go back to the sublist data structure.
3272
        if !ok {
100,736✔
3273
                r = c.acc.sl.Match(subject)
35,304✔
3274
                // Prune the results cache. Keeps us from unbounded growth. Random delete.
35,304✔
3275
                if len(c.in.results) >= maxResultCacheSize {
36,198✔
3276
                        n := 0
894✔
3277
                        for subj := range c.in.results {
30,396✔
3278
                                delete(c.in.results, subj)
29,502✔
3279
                                if n++; n > pruneSize {
30,396✔
3280
                                        break
894✔
3281
                                }
3282
                        }
3283
                }
3284
                // Then add the new cache entry.
3285
                c.in.results[subject] = r
35,304✔
3286
        }
3287

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

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

3312
        // Now deal with gateways
3313
        if c.srv.gateway.enabled {
78,755✔
3314
                c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, qnames, true)
13,323✔
3315
        }
13,323✔
3316
}
3317

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

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

3340
        c.mu.RLock()
61,618✔
3341
        if c.isSpokeLeafNode() {
90,175✔
3342
                // Gateway routed replies are forwarded without
28,557✔
3343
                // permission checks.
28,557✔
3344
                if isGW || c.leafReceiveAllowed(subjectToCheck) {
57,112✔
3345
                        c.mu.RUnlock()
28,555✔
3346
                        return true
28,555✔
3347
                }
28,555✔
3348
        } else if c.leafSendAllowed(subjectToCheck) {
66,116✔
3349
                c.mu.RUnlock()
33,055✔
3350
                return true
33,055✔
3351
        }
33,055✔
3352

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1,932✔
3508
        tlsRequired := remote.TLS || remote.TLSConfig != nil
1,932✔
3509
        if tlsRequired {
2,012✔
3510
                if remote.TLSConfig != nil {
131✔
3511
                        tlsConfig = remote.TLSConfig.Clone()
51✔
3512
                } else {
80✔
3513
                        tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12}
29✔
3514
                }
29✔
3515
                tlsName = remote.tlsName
80✔
3516
                tlsTimeout = remote.TLSTimeout
80✔
3517
                if tlsTimeout == 0 {
126✔
3518
                        tlsTimeout = float64(TLS_TIMEOUT / time.Second)
46✔
3519
                }
46✔
3520
        }
3521

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

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

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

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

3599
        var resp *http.Response
50✔
3600

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

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

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

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

3648
const connectProcessTimeout = 2 * time.Second
3649

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

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

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

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

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

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

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

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

© 2026 Coveralls, Inc