-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathleafnode.go
3111 lines (2840 loc) · 96 KB
/
leafnode.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019-2025 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"bufio"
"bytes"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"path"
"reflect"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"github.com/klauspost/compress/s2"
"github.com/nats-io/jwt/v2"
"github.com/nats-io/nkeys"
"github.com/nats-io/nuid"
)
const (
// Warning when user configures leafnode TLS insecure
leafnodeTLSInsecureWarning = "TLS certificate chain and hostname of solicited leafnodes will not be verified. DO NOT USE IN PRODUCTION!"
// When a loop is detected, delay the reconnect of solicited connection.
leafNodeReconnectDelayAfterLoopDetected = 30 * time.Second
// When a server receives a message causing a permission violation, the
// connection is closed and it won't attempt to reconnect for that long.
leafNodeReconnectAfterPermViolation = 30 * time.Second
// When we have the same cluster name as the hub.
leafNodeReconnectDelayAfterClusterNameSame = 30 * time.Second
// Prefix for loop detection subject
leafNodeLoopDetectionSubjectPrefix = "$LDS."
// Path added to URL to indicate to WS server that the connection is a
// LEAF connection as opposed to a CLIENT.
leafNodeWSPath = "/leafnode"
// This is the time the server will wait, when receiving a CONNECT,
// before closing the connection if the required minimum version is not met.
leafNodeWaitBeforeClose = 5 * time.Second
)
type leaf struct {
// We have any auth stuff here for solicited connections.
remote *leafNodeCfg
// isSpoke tells us what role we are playing.
// Used when we receive a connection but otherside tells us they are a hub.
isSpoke bool
// remoteCluster is when we are a hub but the spoke leafnode is part of a cluster.
remoteCluster string
// remoteServer holds onto the remove server's name or ID.
remoteServer string
// domain name of remote server
remoteDomain string
// account name of remote server
remoteAccName string
// Used to suppress sub and unsub interest. Same as routes but our audience
// here is tied to this leaf node. This will hold all subscriptions except this
// leaf nodes. This represents all the interest we want to send to the other side.
smap map[string]int32
// This map will contain all the subscriptions that have been added to the smap
// during initLeafNodeSmapAndSendSubs. It is short lived and is there to avoid
// race between processing of a sub where sub is added to account sublist but
// updateSmap has not be called on that "thread", while in the LN readloop,
// when processing CONNECT, initLeafNodeSmapAndSendSubs is invoked and add
// this subscription to smap. When processing of the sub then calls updateSmap,
// we would add it a second time in the smap causing later unsub to suppress the LS-.
tsub map[*subscription]struct{}
tsubt *time.Timer
// Selected compression mode, which may be different from the server configured mode.
compression string
// This is for GW map replies.
gwSub *subscription
}
// Used for remote (solicited) leafnodes.
type leafNodeCfg struct {
sync.RWMutex
*RemoteLeafOpts
urls []*url.URL
curURL *url.URL
tlsName string
username string
password string
perms *Permissions
connDelay time.Duration // Delay before a connect, could be used while detecting loop condition, etc..
}
// Check to see if this is a solicited leafnode. We do special processing for solicited.
func (c *client) isSolicitedLeafNode() bool {
return c.kind == LEAF && c.leaf.remote != nil
}
// Returns true if this is a solicited leafnode and is not configured to be treated as a hub or a receiving
// connection leafnode where the otherside has declared itself to be the hub.
func (c *client) isSpokeLeafNode() bool {
return c.kind == LEAF && c.leaf.isSpoke
}
func (c *client) isHubLeafNode() bool {
return c.kind == LEAF && !c.leaf.isSpoke
}
// This will spin up go routines to solicit the remote leaf node connections.
func (s *Server) solicitLeafNodeRemotes(remotes []*RemoteLeafOpts) {
sysAccName := _EMPTY_
sAcc := s.SystemAccount()
if sAcc != nil {
sysAccName = sAcc.Name
}
addRemote := func(r *RemoteLeafOpts, isSysAccRemote bool) *leafNodeCfg {
s.mu.Lock()
remote := newLeafNodeCfg(r)
creds := remote.Credentials
accName := remote.LocalAccount
s.leafRemoteCfgs = append(s.leafRemoteCfgs, remote)
// Print notice if
if isSysAccRemote {
if len(remote.DenyExports) > 0 {
s.Noticef("Remote for System Account uses restricted export permissions")
}
if len(remote.DenyImports) > 0 {
s.Noticef("Remote for System Account uses restricted import permissions")
}
}
s.mu.Unlock()
if creds != _EMPTY_ {
contents, err := os.ReadFile(creds)
defer wipeSlice(contents)
if err != nil {
s.Errorf("Error reading LeafNode Remote Credentials file %q: %v", creds, err)
} else if items := credsRe.FindAllSubmatch(contents, -1); len(items) < 2 {
s.Errorf("LeafNode Remote Credentials file %q malformed", creds)
} else if _, err := nkeys.FromSeed(items[1][1]); err != nil {
s.Errorf("LeafNode Remote Credentials file %q has malformed seed", creds)
} else if uc, err := jwt.DecodeUserClaims(string(items[0][1])); err != nil {
s.Errorf("LeafNode Remote Credentials file %q has malformed user jwt", creds)
} else if isSysAccRemote {
if !uc.Permissions.Pub.Empty() || !uc.Permissions.Sub.Empty() || uc.Permissions.Resp != nil {
s.Noticef("LeafNode Remote for System Account uses credentials file %q with restricted permissions", creds)
}
} else {
if !uc.Permissions.Pub.Empty() || !uc.Permissions.Sub.Empty() || uc.Permissions.Resp != nil {
s.Noticef("LeafNode Remote for Account %s uses credentials file %q with restricted permissions", accName, creds)
}
}
}
return remote
}
for _, r := range remotes {
remote := addRemote(r, r.LocalAccount == sysAccName)
s.startGoRoutine(func() { s.connectToRemoteLeafNode(remote, true) })
}
}
func (s *Server) remoteLeafNodeStillValid(remote *leafNodeCfg) bool {
for _, ri := range s.getOpts().LeafNode.Remotes {
// FIXME(dlc) - What about auth changes?
if reflect.DeepEqual(ri.URLs, remote.URLs) {
return true
}
}
return false
}
// Ensure that leafnode is properly configured.
func validateLeafNode(o *Options) error {
if err := validateLeafNodeAuthOptions(o); err != nil {
return err
}
// Users can bind to any local account, if its empty we will assume the $G account.
for _, r := range o.LeafNode.Remotes {
if r.LocalAccount == _EMPTY_ {
r.LocalAccount = globalAccountName
}
}
// In local config mode, check that leafnode configuration refers to accounts that exist.
if len(o.TrustedOperators) == 0 {
accNames := map[string]struct{}{}
for _, a := range o.Accounts {
accNames[a.Name] = struct{}{}
}
// global account is always created
accNames[DEFAULT_GLOBAL_ACCOUNT] = struct{}{}
// in the context of leaf nodes, empty account means global account
accNames[_EMPTY_] = struct{}{}
// system account either exists or, if not disabled, will be created
if o.SystemAccount == _EMPTY_ && !o.NoSystemAccount {
accNames[DEFAULT_SYSTEM_ACCOUNT] = struct{}{}
}
checkAccountExists := func(accName string, cfgType string) error {
if _, ok := accNames[accName]; !ok {
return fmt.Errorf("cannot find local account %q specified in leafnode %s", accName, cfgType)
}
return nil
}
if err := checkAccountExists(o.LeafNode.Account, "authorization"); err != nil {
return err
}
for _, lu := range o.LeafNode.Users {
if lu.Account == nil { // means global account
continue
}
if err := checkAccountExists(lu.Account.Name, "authorization"); err != nil {
return err
}
}
for _, r := range o.LeafNode.Remotes {
if err := checkAccountExists(r.LocalAccount, "remote"); err != nil {
return err
}
}
} else {
if len(o.LeafNode.Users) != 0 {
return fmt.Errorf("operator mode does not allow specifying users in leafnode config")
}
for _, r := range o.LeafNode.Remotes {
if !nkeys.IsValidPublicAccountKey(r.LocalAccount) {
return fmt.Errorf(
"operator mode requires account nkeys in remotes. " +
"Please add an `account` key to each remote in your `leafnodes` section, to assign it to an account. " +
"Each account value should be a 56 character public key, starting with the letter 'A'")
}
}
if o.LeafNode.Port != 0 && o.LeafNode.Account != "" && !nkeys.IsValidPublicAccountKey(o.LeafNode.Account) {
return fmt.Errorf("operator mode and non account nkeys are incompatible")
}
}
// Validate compression settings
if o.LeafNode.Compression.Mode != _EMPTY_ {
if err := validateAndNormalizeCompressionOption(&o.LeafNode.Compression, CompressionS2Auto); err != nil {
return err
}
}
// If a remote has a websocket scheme, all need to have it.
for _, rcfg := range o.LeafNode.Remotes {
if len(rcfg.URLs) >= 2 {
firstIsWS, ok := isWSURL(rcfg.URLs[0]), true
for i := 1; i < len(rcfg.URLs); i++ {
u := rcfg.URLs[i]
if isWS := isWSURL(u); isWS && !firstIsWS || !isWS && firstIsWS {
ok = false
break
}
}
if !ok {
return fmt.Errorf("remote leaf node configuration cannot have a mix of websocket and non-websocket urls: %q", redactURLList(rcfg.URLs))
}
}
// Validate compression settings
if rcfg.Compression.Mode != _EMPTY_ {
if err := validateAndNormalizeCompressionOption(&rcfg.Compression, CompressionS2Auto); err != nil {
return err
}
}
}
if o.LeafNode.Port == 0 {
return nil
}
// If MinVersion is defined, check that it is valid.
if mv := o.LeafNode.MinVersion; mv != _EMPTY_ {
if err := checkLeafMinVersionConfig(mv); err != nil {
return err
}
}
// The checks below will be done only when detecting that we are configured
// with gateways. So if an option validation needs to be done regardless,
// it MUST be done before this point!
if o.Gateway.Name == _EMPTY_ && o.Gateway.Port == 0 {
return nil
}
// If we are here we have both leaf nodes and gateways defined, make sure there
// is a system account defined.
if o.SystemAccount == _EMPTY_ {
return fmt.Errorf("leaf nodes and gateways (both being defined) require a system account to also be configured")
}
if err := validatePinnedCerts(o.LeafNode.TLSPinnedCerts); err != nil {
return fmt.Errorf("leafnode: %v", err)
}
return nil
}
func checkLeafMinVersionConfig(mv string) error {
if ok, err := versionAtLeastCheckError(mv, 2, 8, 0); !ok || err != nil {
if err != nil {
return fmt.Errorf("invalid leafnode's minimum version: %v", err)
} else {
return fmt.Errorf("the minimum version should be at least 2.8.0")
}
}
return nil
}
// Used to validate user names in LeafNode configuration.
// - rejects mix of single and multiple users.
// - rejects duplicate user names.
func validateLeafNodeAuthOptions(o *Options) error {
if len(o.LeafNode.Users) == 0 {
return nil
}
if o.LeafNode.Username != _EMPTY_ {
return fmt.Errorf("can not have a single user/pass and a users array")
}
if o.LeafNode.Nkey != _EMPTY_ {
return fmt.Errorf("can not have a single nkey and a users array")
}
users := map[string]struct{}{}
for _, u := range o.LeafNode.Users {
if _, exists := users[u.Username]; exists {
return fmt.Errorf("duplicate user %q detected in leafnode authorization", u.Username)
}
users[u.Username] = struct{}{}
}
return nil
}
// Update remote LeafNode TLS configurations after a config reload.
func (s *Server) updateRemoteLeafNodesTLSConfig(opts *Options) {
max := len(opts.LeafNode.Remotes)
if max == 0 {
return
}
s.mu.RLock()
defer s.mu.RUnlock()
// Changes in the list of remote leaf nodes is not supported.
// However, make sure that we don't go over the arrays.
if len(s.leafRemoteCfgs) < max {
max = len(s.leafRemoteCfgs)
}
for i := 0; i < max; i++ {
ro := opts.LeafNode.Remotes[i]
cfg := s.leafRemoteCfgs[i]
if ro.TLSConfig != nil {
cfg.Lock()
cfg.TLSConfig = ro.TLSConfig.Clone()
cfg.TLSHandshakeFirst = ro.TLSHandshakeFirst
cfg.Unlock()
}
}
}
func (s *Server) reConnectToRemoteLeafNode(remote *leafNodeCfg) {
delay := s.getOpts().LeafNode.ReconnectInterval
select {
case <-time.After(delay):
case <-s.quitCh:
s.grWG.Done()
return
}
s.connectToRemoteLeafNode(remote, false)
}
// Creates a leafNodeCfg object that wraps the RemoteLeafOpts.
func newLeafNodeCfg(remote *RemoteLeafOpts) *leafNodeCfg {
cfg := &leafNodeCfg{
RemoteLeafOpts: remote,
urls: make([]*url.URL, 0, len(remote.URLs)),
}
if len(remote.DenyExports) > 0 || len(remote.DenyImports) > 0 {
perms := &Permissions{}
if len(remote.DenyExports) > 0 {
perms.Publish = &SubjectPermission{Deny: remote.DenyExports}
}
if len(remote.DenyImports) > 0 {
perms.Subscribe = &SubjectPermission{Deny: remote.DenyImports}
}
cfg.perms = perms
}
// Start with the one that is configured. We will add to this
// array when receiving async leafnode INFOs.
cfg.urls = append(cfg.urls, cfg.URLs...)
// If allowed to randomize, do it on our copy of URLs
if !remote.NoRandomize {
rand.Shuffle(len(cfg.urls), func(i, j int) {
cfg.urls[i], cfg.urls[j] = cfg.urls[j], cfg.urls[i]
})
}
// If we are TLS make sure we save off a proper servername if possible.
// Do same for user/password since we may need them to connect to
// a bare URL that we get from INFO protocol.
for _, u := range cfg.urls {
cfg.saveTLSHostname(u)
cfg.saveUserPassword(u)
// If the url(s) have the "wss://" scheme, and we don't have a TLS
// config, mark that we should be using TLS anyway.
if !cfg.TLS && isWSSURL(u) {
cfg.TLS = true
}
}
return cfg
}
// Will pick an URL from the list of available URLs.
func (cfg *leafNodeCfg) pickNextURL() *url.URL {
cfg.Lock()
defer cfg.Unlock()
// If the current URL is the first in the list and we have more than
// one URL, then move that one to end of the list.
if cfg.curURL != nil && len(cfg.urls) > 1 && urlsAreEqual(cfg.curURL, cfg.urls[0]) {
first := cfg.urls[0]
copy(cfg.urls, cfg.urls[1:])
cfg.urls[len(cfg.urls)-1] = first
}
cfg.curURL = cfg.urls[0]
return cfg.curURL
}
// Returns the current URL
func (cfg *leafNodeCfg) getCurrentURL() *url.URL {
cfg.RLock()
defer cfg.RUnlock()
return cfg.curURL
}
// Returns how long the server should wait before attempting
// to solicit a remote leafnode connection.
func (cfg *leafNodeCfg) getConnectDelay() time.Duration {
cfg.RLock()
delay := cfg.connDelay
cfg.RUnlock()
return delay
}
// Sets the connect delay.
func (cfg *leafNodeCfg) setConnectDelay(delay time.Duration) {
cfg.Lock()
cfg.connDelay = delay
cfg.Unlock()
}
// Ensure that non-exported options (used in tests) have
// been properly set.
func (s *Server) setLeafNodeNonExportedOptions() {
opts := s.getOpts()
s.leafNodeOpts.dialTimeout = opts.LeafNode.dialTimeout
if s.leafNodeOpts.dialTimeout == 0 {
// Use same timeouts as routes for now.
s.leafNodeOpts.dialTimeout = DEFAULT_ROUTE_DIAL
}
s.leafNodeOpts.resolver = opts.LeafNode.resolver
if s.leafNodeOpts.resolver == nil {
s.leafNodeOpts.resolver = net.DefaultResolver
}
}
const sharedSysAccDelay = 250 * time.Millisecond
func (s *Server) connectToRemoteLeafNode(remote *leafNodeCfg, firstConnect bool) {
defer s.grWG.Done()
if remote == nil || len(remote.URLs) == 0 {
s.Debugf("Empty remote leafnode definition, nothing to connect")
return
}
opts := s.getOpts()
reconnectDelay := opts.LeafNode.ReconnectInterval
s.mu.Lock()
dialTimeout := s.leafNodeOpts.dialTimeout
resolver := s.leafNodeOpts.resolver
var isSysAcc bool
if s.eventsEnabled() {
isSysAcc = remote.LocalAccount == s.sys.account.Name
}
s.mu.Unlock()
// If we are sharing a system account and we are not standalone delay to gather some info prior.
if firstConnect && isSysAcc && !s.standAloneMode() {
s.Debugf("Will delay first leafnode connect to shared system account due to clustering")
remote.setConnectDelay(sharedSysAccDelay)
}
if connDelay := remote.getConnectDelay(); connDelay > 0 {
select {
case <-time.After(connDelay):
case <-s.quitCh:
return
}
remote.setConnectDelay(0)
}
var conn net.Conn
const connErrFmt = "Error trying to connect as leafnode to remote server %q (attempt %v): %v"
attempts := 0
for s.isRunning() && s.remoteLeafNodeStillValid(remote) {
rURL := remote.pickNextURL()
url, err := s.getRandomIP(resolver, rURL.Host, nil)
if err == nil {
var ipStr string
if url != rURL.Host {
ipStr = fmt.Sprintf(" (%s)", url)
}
// Some test may want to disable remotes from connecting
if s.isLeafConnectDisabled() {
s.Debugf("Will not attempt to connect to remote server on %q%s, leafnodes currently disabled", rURL.Host, ipStr)
err = ErrLeafNodeDisabled
} else {
s.Debugf("Trying to connect as leafnode to remote server on %q%s", rURL.Host, ipStr)
conn, err = natsDialTimeout("tcp", url, dialTimeout)
}
}
if err != nil {
jitter := time.Duration(rand.Int63n(int64(reconnectDelay)))
delay := reconnectDelay + jitter
attempts++
if s.shouldReportConnectErr(firstConnect, attempts) {
s.Errorf(connErrFmt, rURL.Host, attempts, err)
} else {
s.Debugf(connErrFmt, rURL.Host, attempts, err)
}
select {
case <-s.quitCh:
return
case <-time.After(delay):
// Check if we should migrate any JetStream assets while this remote is down.
s.checkJetStreamMigrate(remote)
continue
}
}
if !s.remoteLeafNodeStillValid(remote) {
conn.Close()
return
}
// We have a connection here to a remote server.
// Go ahead and create our leaf node and return.
s.createLeafNode(conn, rURL, remote, nil)
// Clear any observer states if we had them.
s.clearObserverState(remote)
return
}
}
// This will clear any observer state such that stream or consumer assets on this server can become leaders again.
func (s *Server) clearObserverState(remote *leafNodeCfg) {
s.mu.RLock()
accName := remote.LocalAccount
s.mu.RUnlock()
acc, err := s.LookupAccount(accName)
if err != nil {
s.Warnf("Error looking up account [%s] checking for JetStream clear observer state on a leafnode", accName)
return
}
acc.jscmMu.Lock()
defer acc.jscmMu.Unlock()
// Walk all streams looking for any clustered stream, skip otherwise.
for _, mset := range acc.streams() {
node := mset.raftNode()
if node == nil {
// Not R>1
continue
}
// Check consumers
for _, o := range mset.getConsumers() {
if n := o.raftNode(); n != nil {
// Ensure we can become a leader again.
n.SetObserver(false)
}
}
// Ensure we can not become a leader again.
node.SetObserver(false)
}
}
// Check to see if we should migrate any assets from this account.
func (s *Server) checkJetStreamMigrate(remote *leafNodeCfg) {
s.mu.RLock()
accName, shouldMigrate := remote.LocalAccount, remote.JetStreamClusterMigrate
s.mu.RUnlock()
if !shouldMigrate {
return
}
acc, err := s.LookupAccount(accName)
if err != nil {
s.Warnf("Error looking up account [%s] checking for JetStream migration on a leafnode", accName)
return
}
acc.jscmMu.Lock()
defer acc.jscmMu.Unlock()
// Walk all streams looking for any clustered stream, skip otherwise.
// If we are the leader force stepdown.
for _, mset := range acc.streams() {
node := mset.raftNode()
if node == nil {
// Not R>1
continue
}
// Collect any consumers
for _, o := range mset.getConsumers() {
if n := o.raftNode(); n != nil {
if n.Leader() {
n.StepDown()
}
// Ensure we can not become a leader while in this state.
n.SetObserver(true)
}
}
// Stepdown if this stream was leader.
if node.Leader() {
node.StepDown()
}
// Ensure we can not become a leader while in this state.
node.SetObserver(true)
}
}
// Helper for checking.
func (s *Server) isLeafConnectDisabled() bool {
s.mu.RLock()
defer s.mu.RUnlock()
return s.leafDisableConnect
}
// Save off the tlsName for when we use TLS and mix hostnames and IPs. IPs usually
// come from the server we connect to.
//
// We used to save the name only if there was a TLSConfig or scheme equal to "tls".
// However, this was causing failures for users that did not set the scheme (and
// their remote connections did not have a tls{} block).
// We now save the host name regardless in case the remote returns an INFO indicating
// that TLS is required.
func (cfg *leafNodeCfg) saveTLSHostname(u *url.URL) {
if cfg.tlsName == _EMPTY_ && net.ParseIP(u.Hostname()) == nil {
cfg.tlsName = u.Hostname()
}
}
// Save off the username/password for when we connect using a bare URL
// that we get from the INFO protocol.
func (cfg *leafNodeCfg) saveUserPassword(u *url.URL) {
if cfg.username == _EMPTY_ && u.User != nil {
cfg.username = u.User.Username()
cfg.password, _ = u.User.Password()
}
}
// This starts the leafnode accept loop in a go routine, unless it
// is detected that the server has already been shutdown.
func (s *Server) startLeafNodeAcceptLoop() {
// Snapshot server options.
opts := s.getOpts()
port := opts.LeafNode.Port
if port == -1 {
port = 0
}
if s.isShuttingDown() {
return
}
s.mu.Lock()
hp := net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(port))
l, e := natsListen("tcp", hp)
s.leafNodeListenerErr = e
if e != nil {
s.mu.Unlock()
s.Fatalf("Error listening on leafnode port: %d - %v", opts.LeafNode.Port, e)
return
}
s.Noticef("Listening for leafnode connections on %s",
net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
tlsRequired := opts.LeafNode.TLSConfig != nil
tlsVerify := tlsRequired && opts.LeafNode.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert
// Do not set compression in this Info object, it would possibly cause
// issues when sending asynchronous INFO to the remote.
info := Info{
ID: s.info.ID,
Name: s.info.Name,
Version: s.info.Version,
GitCommit: gitCommit,
GoVersion: runtime.Version(),
AuthRequired: true,
TLSRequired: tlsRequired,
TLSVerify: tlsVerify,
MaxPayload: s.info.MaxPayload, // TODO(dlc) - Allow override?
Headers: s.supportsHeaders(),
JetStream: opts.JetStream,
Domain: opts.JetStreamDomain,
Proto: 1, // Fixed for now.
InfoOnConnect: true,
}
// If we have selected a random port...
if port == 0 {
// Write resolved port back to options.
opts.LeafNode.Port = l.Addr().(*net.TCPAddr).Port
}
s.leafNodeInfo = info
// Possibly override Host/Port and set IP based on Cluster.Advertise
if err := s.setLeafNodeInfoHostPortAndIP(); err != nil {
s.Fatalf("Error setting leafnode INFO with LeafNode.Advertise value of %s, err=%v", opts.LeafNode.Advertise, err)
l.Close()
s.mu.Unlock()
return
}
s.leafURLsMap[s.leafNodeInfo.IP]++
s.generateLeafNodeInfoJSON()
// Setup state that can enable shutdown
s.leafNodeListener = l
// As of now, a server that does not have remotes configured would
// never solicit a connection, so we should not have to warn if
// InsecureSkipVerify is set in main LeafNodes config (since
// this TLS setting matters only when soliciting a connection).
// Still, warn if insecure is set in any of LeafNode block.
// We need to check remotes, even if tls is not required on accept.
warn := tlsRequired && opts.LeafNode.TLSConfig.InsecureSkipVerify
if !warn {
for _, r := range opts.LeafNode.Remotes {
if r.TLSConfig != nil && r.TLSConfig.InsecureSkipVerify {
warn = true
break
}
}
}
if warn {
s.Warnf(leafnodeTLSInsecureWarning)
}
go s.acceptConnections(l, "Leafnode", func(conn net.Conn) { s.createLeafNode(conn, nil, nil, nil) }, nil)
s.mu.Unlock()
}
// RegEx to match a creds file with user JWT and Seed.
var credsRe = regexp.MustCompile(`\s*(?:(?:[-]{3,}.*[-]{3,}\r?\n)([\w\-.=]+)(?:\r?\n[-]{3,}.*[-]{3,}(\r?\n|\z)))`)
// clusterName is provided as argument to avoid lock ordering issues with the locked client c
// Lock should be held entering here.
func (c *client) sendLeafConnect(clusterName string, headers bool) error {
// We support basic user/pass and operator based user JWT with signatures.
cinfo := leafConnectInfo{
Version: VERSION,
ID: c.srv.info.ID,
Domain: c.srv.info.Domain,
Name: c.srv.info.Name,
Hub: c.leaf.remote.Hub,
Cluster: clusterName,
Headers: headers,
JetStream: c.acc.jetStreamConfigured(),
DenyPub: c.leaf.remote.DenyImports,
Compression: c.leaf.compression,
RemoteAccount: c.acc.GetName(),
}
// If a signature callback is specified, this takes precedence over anything else.
if cb := c.leaf.remote.SignatureCB; cb != nil {
nonce := c.nonce
c.mu.Unlock()
jwt, sigraw, err := cb(nonce)
c.mu.Lock()
if err == nil && c.isClosed() {
err = ErrConnectionClosed
}
if err != nil {
c.Errorf("Error signing the nonce: %v", err)
return err
}
sig := base64.RawURLEncoding.EncodeToString(sigraw)
cinfo.JWT, cinfo.Sig = jwt, sig
} else if creds := c.leaf.remote.Credentials; creds != _EMPTY_ {
// Check for credentials first, that will take precedence..
c.Debugf("Authenticating with credentials file %q", c.leaf.remote.Credentials)
contents, err := os.ReadFile(creds)
if err != nil {
c.Errorf("%v", err)
return err
}
defer wipeSlice(contents)
items := credsRe.FindAllSubmatch(contents, -1)
if len(items) < 2 {
c.Errorf("Credentials file malformed")
return err
}
// First result should be the user JWT.
// We copy here so that the file containing the seed will be wiped appropriately.
raw := items[0][1]
tmp := make([]byte, len(raw))
copy(tmp, raw)
// Seed is second item.
kp, err := nkeys.FromSeed(items[1][1])
if err != nil {
c.Errorf("Credentials file has malformed seed")
return err
}
// Wipe our key on exit.
defer kp.Wipe()
sigraw, _ := kp.Sign(c.nonce)
sig := base64.RawURLEncoding.EncodeToString(sigraw)
cinfo.JWT = bytesToString(tmp)
cinfo.Sig = sig
} else if nkey := c.leaf.remote.Nkey; nkey != _EMPTY_ {
kp, err := nkeys.FromSeed([]byte(nkey))
if err != nil {
c.Errorf("Remote nkey has malformed seed")
return err
}
// Wipe our key on exit.
defer kp.Wipe()
sigraw, _ := kp.Sign(c.nonce)
sig := base64.RawURLEncoding.EncodeToString(sigraw)
pkey, _ := kp.PublicKey()
cinfo.Nkey = pkey
cinfo.Sig = sig
}
// In addition, and this is to allow auth callout, set user/password or
// token if applicable.
if userInfo := c.leaf.remote.curURL.User; userInfo != nil {
// For backward compatibility, if only username is provided, set both
// Token and User, not just Token.
cinfo.User = userInfo.Username()
var ok bool
cinfo.Pass, ok = userInfo.Password()
if !ok {
cinfo.Token = cinfo.User
}
} else if c.leaf.remote.username != _EMPTY_ {
cinfo.User = c.leaf.remote.username
cinfo.Pass = c.leaf.remote.password
}
b, err := json.Marshal(cinfo)
if err != nil {
c.Errorf("Error marshaling CONNECT to remote leafnode: %v\n", err)
return err
}
// Although this call is made before the writeLoop is created,
// we don't really need to send in place. The protocol will be
// sent out by the writeLoop.
c.enqueueProto([]byte(fmt.Sprintf(ConProto, b)))
return nil
}
// Makes a deep copy of the LeafNode Info structure.
// The server lock is held on entry.
func (s *Server) copyLeafNodeInfo() *Info {
clone := s.leafNodeInfo
// Copy the array of urls.
if len(s.leafNodeInfo.LeafNodeURLs) > 0 {
clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...)
}
return &clone
}
// Adds a LeafNode URL that we get when a route connects to the Info structure.
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
// Returns a boolean indicating if the URL was added or not.
// Server lock is held on entry
func (s *Server) addLeafNodeURL(urlStr string) bool {
if s.leafURLsMap.addUrl(urlStr) {
s.generateLeafNodeInfoJSON()
return true
}
return false
}
// Removes a LeafNode URL of the route that is disconnecting from the Info structure.
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
// Returns a boolean indicating if the URL was removed or not.
// Server lock is held on entry.
func (s *Server) removeLeafNodeURL(urlStr string) bool {
// Don't need to do this if we are removing the route connection because
// we are shuting down...
if s.isShuttingDown() {
return false
}
if s.leafURLsMap.removeUrl(urlStr) {
s.generateLeafNodeInfoJSON()
return true
}
return false
}
// Server lock is held on entry
func (s *Server) generateLeafNodeInfoJSON() {
s.leafNodeInfo.Cluster = s.cachedClusterName()
s.leafNodeInfo.LeafNodeURLs = s.leafURLsMap.getAsStringSlice()
s.leafNodeInfo.WSConnectURLs = s.websocket.connectURLsMap.getAsStringSlice()
s.leafNodeInfoJSON = generateInfoJSON(&s.leafNodeInfo)
}
// Sends an async INFO protocol so that the connected servers can update
// their list of LeafNode urls.
func (s *Server) sendAsyncLeafNodeInfo() {
for _, c := range s.leafs {
c.mu.Lock()
c.enqueueProto(s.leafNodeInfoJSON)
c.mu.Unlock()
}
}
// Called when an inbound leafnode connection is accepted or we create one for a solicited leafnode.
func (s *Server) createLeafNode(conn net.Conn, rURL *url.URL, remote *leafNodeCfg, ws *websocket) *client {
// Snapshot server options.
opts := s.getOpts()
maxPay := int32(opts.MaxPayload)
maxSubs := int32(opts.MaxSubs)
// For system, maxSubs of 0 means unlimited, so re-adjust here.
if maxSubs == 0 {
maxSubs = -1
}
now := time.Now().UTC()
c := &client{srv: s, nc: conn, kind: LEAF, opts: defaultOpts, mpay: maxPay, msubs: maxSubs, start: now, last: now}
// Do not update the smap here, we need to do it in initLeafNodeSmapAndSendSubs
c.leaf = &leaf{}
// For accepted LN connections, ws will be != nil if it was accepted
// through the Websocket port.
c.ws = ws
// For remote, check if the scheme starts with "ws", if so, we will initiate
// a remote Leaf Node connection as a websocket connection.
if remote != nil && rURL != nil && isWSURL(rURL) {
remote.RLock()
c.ws = &websocket{compress: remote.Websocket.Compression, maskwrite: !remote.Websocket.NoMasking}
remote.RUnlock()
}
// Determines if we are soliciting the connection or not.
var solicited bool
var acc *Account
var remoteSuffix string
if remote != nil {
// For now, if lookup fails, we will constantly try
// to recreate this LN connection.
lacc := remote.LocalAccount
var err error
acc, err = s.LookupAccount(lacc)
if err != nil {
// An account not existing is something that can happen with nats/http account resolver and the account
// has not yet been pushed, or the request failed for other reasons.
// remote needs to be set or retry won't happen
c.leaf.remote = remote
c.closeConnection(MissingAccount)
s.Errorf("Unable to lookup account %s for solicited leafnode connection: %v", lacc, err)
return nil
}
remoteSuffix = fmt.Sprintf(" for account: %s", acc.traceLabel())
}
c.mu.Lock()
c.initClient()
c.Noticef("Leafnode connection created%s %s", remoteSuffix, c.opts.Name)
var tlsFirst bool
if remote != nil {