| 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 { |
| 124 |
return c.kind == LEAF && c.leaf != nil && c.leaf.remote != nil |
| 125 |
} |
| 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 { |
| 130 |
return c.kind == LEAF && c.leaf != nil && c.leaf.isSpoke |
| 131 |
} |
| 132 |
|
| 133 |
func (c *client) isHubLeafNode() bool { |
| 134 |
return c.kind == LEAF && c.leaf != nil && !c.leaf.isSpoke |
| 135 |
} |
| 136 |
|
| 137 |
func (c *client) isIsolatedLeafNode() bool { |
| 138 |
// TODO(nat): In future we may want to pass in and consider an isolation |
| 139 |
// group name here, which the hub and/or leaf could provide, so that we |
| 140 |
// can isolate away certain LNs but not others on an opt-in basis. For |
| 141 |
// now we will just isolate all LN interest until then. |
| 142 |
return c.kind == LEAF && c.leaf != nil && c.leaf.isolated |
| 143 |
} |
| 144 |
|
| 145 |
// This will spin up go routines to solicit the remote leaf node connections. |
| 146 |
func (s *Server) solicitLeafNodeRemotes(remotes []*RemoteLeafOpts) { |
| 147 |
sysAccName := _EMPTY_ |
| 148 |
sAcc := s.SystemAccount() |
| 149 |
if sAcc != nil { |
| 150 |
sysAccName = sAcc.Name |
| 151 |
} |
| 152 |
addRemote := func(r *RemoteLeafOpts, isSysAccRemote bool) *leafNodeCfg { |
| 153 |
s.mu.Lock() |
| 154 |
remote := newLeafNodeCfg(r) |
| 155 |
creds := remote.Credentials |
| 156 |
accName := remote.LocalAccount |
| 157 |
if s.leafRemoteCfgs == nil { |
| 158 |
s.leafRemoteCfgs = make(map[*leafNodeCfg]struct{}) |
| 159 |
} |
| 160 |
s.leafRemoteCfgs[remote] = struct{}{} |
| 161 |
// Print notice if |
| 162 |
if isSysAccRemote { |
| 163 |
if len(remote.DenyExports) > 0 { |
| 164 |
s.Noticef("Remote for System Account uses restricted export permissions") |
| 165 |
} |
| 166 |
if len(remote.DenyImports) > 0 { |
| 167 |
s.Noticef("Remote for System Account uses restricted import permissions") |
| 168 |
} |
| 169 |
} |
| 170 |
s.mu.Unlock() |
| 171 |
if creds != _EMPTY_ { |
| 172 |
contents, err := os.ReadFile(creds) |
| 173 |
defer wipeSlice(contents) |
| 174 |
if err != nil { |
| 175 |
s.Errorf("Error reading LeafNode Remote Credentials file %q: %v", creds, err) |
| 176 |
} else if items := credsRe.FindAllSubmatch(contents, -1); len(items) < 2 { |
| 177 |
s.Errorf("LeafNode Remote Credentials file %q malformed", creds) |
| 178 |
} else if _, err := nkeys.FromSeed(items[1][1]); err != nil { |
| 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 { |
| 181 |
s.Errorf("LeafNode Remote Credentials file %q has malformed user jwt", creds) |
| 182 |
} else if isSysAccRemote { |
| 183 |
if !uc.Permissions.Pub.Empty() || !uc.Permissions.Sub.Empty() || uc.Permissions.Resp != nil { |
| 184 |
s.Noticef("LeafNode Remote for System Account uses credentials file %q with restricted permissions", creds) |
| 185 |
} |
| 186 |
} else { |
| 187 |
if !uc.Permissions.Pub.Empty() || !uc.Permissions.Sub.Empty() || uc.Permissions.Resp != nil { |
| 188 |
s.Noticef("LeafNode Remote for Account %s uses credentials file %q with restricted permissions", accName, creds) |
| 189 |
} |
| 190 |
} |
| 191 |
} |
| 192 |
return remote |
| 193 |
} |
| 194 |
for _, r := range remotes { |
| 195 |
// We need to call this, even if the leaf is disabled. This is so that |
| 196 |
// the number of internal configuration matches the options' remote leaf |
| 197 |
// configuration required for configuration reload. |
| 198 |
remote := addRemote(r, r.LocalAccount == sysAccName) |
| 199 |
if !r.Disabled { |
| 200 |
s.connectToRemoteLeafNodeAsynchronously(remote, true) |
| 201 |
} |
| 202 |
} |
| 203 |
} |
| 204 |
|
| 205 |
// Ensure that leafnode is properly configured. |
| 206 |
func validateLeafNode(o *Options) error { |
| 207 |
if err := validateLeafNodeAuthOptions(o); err != nil { |
| 208 |
return err |
| 209 |
} |
| 210 |
|
| 211 |
if len(o.LeafNode.Remotes) > 0 { |
| 212 |
names := make(map[string]struct{}) |
| 213 |
// Check for duplicate remotes, also, users can bind to any local account, |
| 214 |
// if its empty we will assume the $G account. |
| 215 |
for _, r := range o.LeafNode.Remotes { |
| 216 |
if r.LocalAccount == _EMPTY_ { |
| 217 |
r.LocalAccount = globalAccountName |
| 218 |
} |
| 219 |
if err := checkPermSubjectArray(r.DenyImports, false); err != nil { |
| 220 |
return fmt.Errorf("invalid deny_imports for remote %s: %w", r.safeName(), err) |
| 221 |
} |
| 222 |
if err := checkPermSubjectArray(r.DenyExports, false); err != nil { |
| 223 |
return fmt.Errorf("invalid deny_exports for remote %s: %w", r.safeName(), err) |
| 224 |
} |
| 225 |
rn := r.name() |
| 226 |
if _, dup := names[rn]; dup { |
| 227 |
return fmt.Errorf("duplicate remote %s", r.safeName()) |
| 228 |
} |
| 229 |
names[rn] = struct{}{} |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
// In local config mode, check that leafnode configuration refers to accounts that exist. |
| 234 |
if len(o.TrustedOperators) == 0 { |
| 235 |
accNames := map[string]struct{}{} |
| 236 |
for _, a := range o.Accounts { |
| 237 |
accNames[a.Name] = struct{}{} |
| 238 |
} |
| 239 |
// global account is always created |
| 240 |
accNames[DEFAULT_GLOBAL_ACCOUNT] = struct{}{} |
| 241 |
// in the context of leaf nodes, empty account means global account |
| 242 |
accNames[_EMPTY_] = struct{}{} |
| 243 |
// system account either exists or, if not disabled, will be created |
| 244 |
if o.SystemAccount == _EMPTY_ && !o.NoSystemAccount { |
| 245 |
accNames[DEFAULT_SYSTEM_ACCOUNT] = struct{}{} |
| 246 |
} |
| 247 |
checkAccountExists := func(accName string, cfgType string) error { |
| 248 |
if _, ok := accNames[accName]; !ok { |
| 249 |
return fmt.Errorf("cannot find local account %q specified in leafnode %s", accName, cfgType) |
| 250 |
} |
| 251 |
return nil |
| 252 |
} |
| 253 |
if err := checkAccountExists(o.LeafNode.Account, "authorization"); err != nil { |
| 254 |
return err |
| 255 |
} |
| 256 |
for _, lu := range o.LeafNode.Users { |
| 257 |
if lu.Account == nil { // means global account |
| 258 |
continue |
| 259 |
} |
| 260 |
if err := checkAccountExists(lu.Account.Name, "authorization"); err != nil { |
| 261 |
return err |
| 262 |
} |
| 263 |
} |
| 264 |
for _, r := range o.LeafNode.Remotes { |
| 265 |
if err := checkAccountExists(r.LocalAccount, "remote"); err != nil { |
| 266 |
return err |
| 267 |
} |
| 268 |
} |
| 269 |
} else { |
| 270 |
if len(o.LeafNode.Users) != 0 { |
| 271 |
return fmt.Errorf("operator mode does not allow specifying users in leafnode config") |
| 272 |
} |
| 273 |
for _, r := range o.LeafNode.Remotes { |
| 274 |
if !nkeys.IsValidPublicAccountKey(r.LocalAccount) { |
| 275 |
return fmt.Errorf( |
| 276 |
"operator mode requires account nkeys in remotes. " + |
| 277 |
"Please add an `account` key to each remote in your `leafnodes` section, to assign it to an account. " + |
| 278 |
"Each account value should be a 56 character public key, starting with the letter 'A'") |
| 279 |
} |
| 280 |
} |
| 281 |
if o.LeafNode.Port != 0 && o.LeafNode.Account != "" && !nkeys.IsValidPublicAccountKey(o.LeafNode.Account) { |
| 282 |
return fmt.Errorf("operator mode and non account nkeys are incompatible") |
| 283 |
} |
| 284 |
} |
| 285 |
|
| 286 |
// Validate compression settings |
| 287 |
if o.LeafNode.Compression.Mode != _EMPTY_ { |
| 288 |
if err := validateAndNormalizeCompressionOption(&o.LeafNode.Compression, CompressionS2Auto); err != nil { |
| 289 |
return err |
| 290 |
} |
| 291 |
} |
| 292 |
|
| 293 |
// If a remote has a websocket scheme, all need to have it. |
| 294 |
for _, rcfg := range o.LeafNode.Remotes { |
| 295 |
// Validate proxy configuration |
| 296 |
if _, err := validateLeafNodeProxyOptions(rcfg); err != nil { |
| 297 |
return err |
| 298 |
} |
| 299 |
|
| 300 |
if len(rcfg.URLs) >= 2 { |
| 301 |
firstIsWS, ok := isWSURL(rcfg.URLs[0]), true |
| 302 |
for i := 1; i < len(rcfg.URLs); i++ { |
| 303 |
u := rcfg.URLs[i] |
| 304 |
if isWS := isWSURL(u); isWS && !firstIsWS || !isWS && firstIsWS { |
| 305 |
ok = false |
| 306 |
break |
| 307 |
} |
| 308 |
} |
| 309 |
if !ok { |
| 310 |
return fmt.Errorf("remote leaf node configuration cannot have a mix of websocket and non-websocket urls: %q", redactURLList(rcfg.URLs)) |
| 311 |
} |
| 312 |
} |
| 313 |
if !wsAllowedFIPS() { |
| 314 |
for _, u := range rcfg.URLs { |
| 315 |
if isWSURL(u) { |
| 316 |
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())) |
| 317 |
} |
| 318 |
} |
| 319 |
} |
| 320 |
// Validate compression settings |
| 321 |
if rcfg.Compression.Mode != _EMPTY_ { |
| 322 |
if err := validateAndNormalizeCompressionOption(&rcfg.Compression, CompressionS2Auto); err != nil { |
| 323 |
return err |
| 324 |
} |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
if o.LeafNode.Port == 0 { |
| 329 |
return nil |
| 330 |
} |
| 331 |
|
| 332 |
// If MinVersion is defined, check that it is valid. |
| 333 |
if mv := o.LeafNode.MinVersion; mv != _EMPTY_ { |
| 334 |
if err := checkLeafMinVersionConfig(mv); err != nil { |
| 335 |
return err |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
// The checks below will be done only when detecting that we are configured |
| 340 |
// with gateways. So if an option validation needs to be done regardless, |
| 341 |
// it MUST be done before this point! |
| 342 |
|
| 343 |
if o.Gateway.Name == _EMPTY_ && o.Gateway.Port == 0 { |
| 344 |
return nil |
| 345 |
} |
| 346 |
// If we are here we have both leaf nodes and gateways defined, make sure there |
| 347 |
// is a system account defined. |
| 348 |
if o.SystemAccount == _EMPTY_ { |
| 349 |
return fmt.Errorf("leaf nodes and gateways (both being defined) require a system account to also be configured") |
| 350 |
} |
| 351 |
if err := validatePinnedCerts(o.LeafNode.TLSPinnedCerts); err != nil { |
| 352 |
return fmt.Errorf("leafnode: %v", err) |
| 353 |
} |
| 354 |
return nil |
| 355 |
} |
| 356 |
|
| 357 |
func checkLeafMinVersionConfig(mv string) error { |
| 358 |
if ok, err := versionAtLeastCheckError(mv, 2, 8, 0); !ok || err != nil { |
| 359 |
if err != nil { |
| 360 |
return fmt.Errorf("invalid leafnode's minimum version: %v", err) |
| 361 |
} else { |
| 362 |
return fmt.Errorf("the minimum version should be at least 2.8.0") |
| 363 |
} |
| 364 |
} |
| 365 |
return nil |
| 366 |
} |
| 367 |
|
| 368 |
// Used to validate user names in LeafNode configuration. |
| 369 |
// - rejects mix of single and multiple users. |
| 370 |
// - rejects duplicate user names. |
| 371 |
func validateLeafNodeAuthOptions(o *Options) error { |
| 372 |
if len(o.LeafNode.Users) == 0 { |
| 373 |
return nil |
| 374 |
} |
| 375 |
if o.LeafNode.Username != _EMPTY_ { |
| 376 |
return fmt.Errorf("can not have a single user/pass and a users array") |
| 377 |
} |
| 378 |
if o.LeafNode.Nkey != _EMPTY_ { |
| 379 |
return fmt.Errorf("can not have a single nkey and a users array") |
| 380 |
} |
| 381 |
users := map[string]struct{}{} |
| 382 |
for _, u := range o.LeafNode.Users { |
| 383 |
if _, exists := users[u.Username]; exists { |
| 384 |
return fmt.Errorf("duplicate user %q detected in leafnode authorization", u.Username) |
| 385 |
} |
| 386 |
users[u.Username] = struct{}{} |
| 387 |
} |
| 388 |
return nil |
| 389 |
} |
| 390 |
|
| 391 |
func validateLeafNodeProxyOptions(remote *RemoteLeafOpts) ([]string, error) { |
| 392 |
var warnings []string |
| 393 |
|
| 394 |
if remote.Proxy.URL == _EMPTY_ { |
| 395 |
return warnings, nil |
| 396 |
} |
| 397 |
|
| 398 |
proxyURL, err := url.Parse(remote.Proxy.URL) |
| 399 |
if err != nil { |
| 400 |
return warnings, fmt.Errorf("invalid proxy URL: %v", err) |
| 401 |
} |
| 402 |
|
| 403 |
if proxyURL.Scheme != "http" && proxyURL.Scheme != "https" { |
| 404 |
return warnings, fmt.Errorf("proxy URL scheme must be http or https, got: %s", proxyURL.Scheme) |
| 405 |
} |
| 406 |
|
| 407 |
if proxyURL.Host == _EMPTY_ { |
| 408 |
return warnings, fmt.Errorf("proxy URL must specify a host") |
| 409 |
} |
| 410 |
|
| 411 |
if remote.Proxy.Timeout < 0 { |
| 412 |
return warnings, fmt.Errorf("proxy timeout must be >= 0") |
| 413 |
} |
| 414 |
|
| 415 |
if (remote.Proxy.Username == _EMPTY_) != (remote.Proxy.Password == _EMPTY_) { |
| 416 |
return warnings, fmt.Errorf("proxy username and password must both be specified or both be empty") |
| 417 |
} |
| 418 |
|
| 419 |
if len(remote.URLs) > 0 { |
| 420 |
hasWebSocketURL := false |
| 421 |
hasNonWebSocketURL := false |
| 422 |
|
| 423 |
for _, remoteURL := range remote.URLs { |
| 424 |
if remoteURL.Scheme == wsSchemePrefix || remoteURL.Scheme == wsSchemePrefixTLS { |
| 425 |
hasWebSocketURL = true |
| 426 |
if (remoteURL.Scheme == wsSchemePrefixTLS) && |
| 427 |
remote.TLSConfig == nil && !remote.TLS { |
| 428 |
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()) |
| 429 |
} |
| 430 |
} else { |
| 431 |
hasNonWebSocketURL = true |
| 432 |
} |
| 433 |
} |
| 434 |
|
| 435 |
if !hasWebSocketURL { |
| 436 |
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://)") |
| 437 |
} else if hasNonWebSocketURL { |
| 438 |
warnings = append(warnings, "proxy configuration will only be used for WebSocket URLs: proxy settings do not apply to TCP connections (nats://)") |
| 439 |
} |
| 440 |
} |
| 441 |
|
| 442 |
return warnings, nil |
| 443 |
} |
| 444 |
|
| 445 |
// Wait for the configured reconnect interval before attempting to connect |
| 446 |
// again to the remote leafnode. |
| 447 |
func (s *Server) reConnectToRemoteLeafNode(remote *leafNodeCfg) { |
| 448 |
clearInProgress := true |
| 449 |
defer func() { |
| 450 |
s.grWG.Done() |
| 451 |
if clearInProgress { |
| 452 |
remote.setConnectInProgress(false) |
| 453 |
} |
| 454 |
}() |
| 455 |
delay := s.getOpts().LeafNode.ReconnectInterval |
| 456 |
select { |
| 457 |
case <-time.After(delay): |
| 458 |
case <-remote.quitCh: |
| 459 |
return |
| 460 |
case <-s.quitCh: |
| 461 |
return |
| 462 |
} |
| 463 |
clearInProgress = !connectToRemoteLeafNode(s, remote, false) |
| 464 |
} |
| 465 |
|
| 466 |
// Creates a leafNodeCfg object that wraps the RemoteLeafOpts. |
| 467 |
func newLeafNodeCfg(remote *RemoteLeafOpts) *leafNodeCfg { |
| 468 |
cfg := &leafNodeCfg{ |
| 469 |
RemoteLeafOpts: remote, |
| 470 |
urls: make([]*url.URL, 0, len(remote.URLs)), |
| 471 |
quitCh: make(chan struct{}, 1), |
| 472 |
} |
| 473 |
if len(remote.DenyExports) > 0 || len(remote.DenyImports) > 0 { |
| 474 |
perms := &Permissions{} |
| 475 |
if len(remote.DenyExports) > 0 { |
| 476 |
perms.Publish = &SubjectPermission{Deny: remote.DenyExports} |
| 477 |
} |
| 478 |
if len(remote.DenyImports) > 0 { |
| 479 |
perms.Subscribe = &SubjectPermission{Deny: remote.DenyImports} |
| 480 |
} |
| 481 |
cfg.perms = perms |
| 482 |
} |
| 483 |
// Start with the one that is configured. We will add to this |
| 484 |
// array when receiving async leafnode INFOs. |
| 485 |
cfg.urls = append(cfg.urls, cfg.URLs...) |
| 486 |
// If allowed to randomize, do it on our copy of URLs |
| 487 |
if !remote.NoRandomize { |
| 488 |
rand.Shuffle(len(cfg.urls), func(i, j int) { |
| 489 |
cfg.urls[i], cfg.urls[j] = cfg.urls[j], cfg.urls[i] |
| 490 |
}) |
| 491 |
} |
| 492 |
// If we are TLS make sure we save off a proper servername if possible. |
| 493 |
// Do same for user/password since we may need them to connect to |
| 494 |
// a bare URL that we get from INFO protocol. |
| 495 |
for _, u := range cfg.urls { |
| 496 |
cfg.saveTLSHostname(u) |
| 497 |
cfg.saveUserPassword(u) |
| 498 |
// If the url(s) have the "wss://" scheme, and we don't have a TLS |
| 499 |
// config, mark that we should be using TLS anyway. |
| 500 |
if !cfg.TLS && isWSSURL(u) { |
| 501 |
cfg.TLS = true |
| 502 |
} |
| 503 |
} |
| 504 |
return cfg |
| 505 |
} |
| 506 |
|
| 507 |
// Notifies the quit channel without blocking. |
| 508 |
// No lock is needed to invoke this function. |
| 509 |
func (cfg *leafNodeCfg) notifyQuitChannel() { |
| 510 |
select { |
| 511 |
case cfg.quitCh <- struct{}{}: |
| 512 |
default: |
| 513 |
} |
| 514 |
} |
| 515 |
|
| 516 |
// Sets the connect-in-progress status for this remote leaf configuration. |
| 517 |
func (cfg *leafNodeCfg) setConnectInProgress(inProgress bool) { |
| 518 |
cfg.Lock() |
| 519 |
defer cfg.Unlock() |
| 520 |
// In both cases we want to drain the "quit" channel. |
| 521 |
select { |
| 522 |
case <-cfg.quitCh: |
| 523 |
default: |
| 524 |
} |
| 525 |
cfg.connInProgress = inProgress |
| 526 |
} |
| 527 |
|
| 528 |
// Returns `true` if this remote is in the middle of a connect, `false` otherwise. |
| 529 |
func (cfg *leafNodeCfg) isConnectInProgress() bool { |
| 530 |
cfg.RLock() |
| 531 |
defer cfg.RUnlock() |
| 532 |
return cfg.connInProgress |
| 533 |
} |
| 534 |
|
| 535 |
// Mark that this remote is being removed from the configuration. |
| 536 |
func (cfg *leafNodeCfg) markAsRemoved() { |
| 537 |
cfg.Lock() |
| 538 |
defer cfg.Unlock() |
| 539 |
// This function should be invoked only once, but protect. |
| 540 |
if cfg.removed { |
| 541 |
return |
| 542 |
} |
| 543 |
cfg.removed = true |
| 544 |
cfg.notifyQuitChannel() |
| 545 |
} |
| 546 |
|
| 547 |
// Returns false if it has been disabled or removed. |
| 548 |
func (cfg *leafNodeCfg) stillValid() bool { |
| 549 |
cfg.RLock() |
| 550 |
defer cfg.RUnlock() |
| 551 |
return !cfg.Disabled && !cfg.removed |
| 552 |
} |
| 553 |
|
| 554 |
// Will pick an URL from the list of available URLs. |
| 555 |
func (cfg *leafNodeCfg) pickNextURL() *url.URL { |
| 556 |
cfg.Lock() |
| 557 |
defer cfg.Unlock() |
| 558 |
// If the current URL is the first in the list and we have more than |
| 559 |
// one URL, then move that one to end of the list. |
| 560 |
if cfg.curURL != nil && len(cfg.urls) > 1 && urlsAreEqual(cfg.curURL, cfg.urls[0]) { |
| 561 |
first := cfg.urls[0] |
| 562 |
copy(cfg.urls, cfg.urls[1:]) |
| 563 |
cfg.urls[len(cfg.urls)-1] = first |
| 564 |
} |
| 565 |
cfg.curURL = cfg.urls[0] |
| 566 |
return cfg.curURL |
| 567 |
} |
| 568 |
|
| 569 |
// Returns the current URL |
| 570 |
func (cfg *leafNodeCfg) getCurrentURL() *url.URL { |
| 571 |
cfg.RLock() |
| 572 |
defer cfg.RUnlock() |
| 573 |
return cfg.curURL |
| 574 |
} |
| 575 |
|
| 576 |
// Returns how long the server should wait before attempting |
| 577 |
// to solicit a remote leafnode connection. |
| 578 |
func (cfg *leafNodeCfg) getConnectDelay() time.Duration { |
| 579 |
cfg.RLock() |
| 580 |
delay := cfg.connDelay |
| 581 |
cfg.RUnlock() |
| 582 |
return delay |
| 583 |
} |
| 584 |
|
| 585 |
// Sets the connect delay. |
| 586 |
func (cfg *leafNodeCfg) setConnectDelay(delay time.Duration) { |
| 587 |
cfg.Lock() |
| 588 |
cfg.connDelay = delay |
| 589 |
cfg.Unlock() |
| 590 |
} |
| 591 |
|
| 592 |
// leafNodeDialer establishes the TCP connection to a remote leafnode server. |
| 593 |
// It has the same signature as natsDialTimeout(), which is what is used in |
| 594 |
// production. Tests can substitute their own implementation via |
| 595 |
// LeafNodeOpts.dialer in order to observe the resolved dial timeout, or to |
| 596 |
// simulate a slow/unreachable remote, without needing to manipulate the |
| 597 |
// network stack. |
| 598 |
type leafNodeDialer func(network, address string, timeout time.Duration) (net.Conn, error) |
| 599 |
|
| 600 |
// Ensure that non-exported options (used in tests) have |
| 601 |
// been properly set. |
| 602 |
func (s *Server) setLeafNodeNonExportedOptions() { |
| 603 |
opts := s.getOpts() |
| 604 |
s.leafNodeOpts.dialTimeout = opts.LeafNode.DialTimeout |
| 605 |
if s.leafNodeOpts.dialTimeout <= 0 { |
| 606 |
// Use same timeouts as routes for now. |
| 607 |
s.leafNodeOpts.dialTimeout = DEFAULT_ROUTE_DIAL |
| 608 |
} |
| 609 |
s.leafNodeOpts.resolver = opts.LeafNode.resolver |
| 610 |
if s.leafNodeOpts.resolver == nil { |
| 611 |
s.leafNodeOpts.resolver = net.DefaultResolver |
| 612 |
} |
| 613 |
s.leafNodeOpts.dialer = opts.LeafNode.dialer |
| 614 |
if s.leafNodeOpts.dialer == nil { |
| 615 |
s.leafNodeOpts.dialer = natsDialTimeout |
| 616 |
} |
| 617 |
} |
| 618 |
|
| 619 |
const sharedSysAccDelay = 250 * time.Millisecond |
| 620 |
|
| 621 |
// establishHTTPProxyTunnel establishes an HTTP CONNECT tunnel through a proxy server |
| 622 |
func establishHTTPProxyTunnel(proxyURL, targetHost string, timeout time.Duration, username, password string) (net.Conn, error) { |
| 623 |
proxyAddr, err := url.Parse(proxyURL) |
| 624 |
if err != nil { |
| 625 |
// This should not happen since proxy URL is validated during configuration parsing |
| 626 |
return nil, fmt.Errorf("unexpected proxy URL parse error (URL was pre-validated): %v", err) |
| 627 |
} |
| 628 |
|
| 629 |
// Connect to the proxy server |
| 630 |
conn, err := natsDialTimeout("tcp", proxyAddr.Host, timeout) |
| 631 |
if err != nil { |
| 632 |
return nil, fmt.Errorf("failed to connect to proxy: %v", err) |
| 633 |
} |
| 634 |
|
| 635 |
// Set deadline for the entire proxy handshake |
| 636 |
if err := conn.SetDeadline(time.Now().Add(timeout)); err != nil { |
| 637 |
conn.Close() |
| 638 |
return nil, fmt.Errorf("failed to set deadline: %v", err) |
| 639 |
} |
| 640 |
|
| 641 |
req := &http.Request{ |
| 642 |
Method: http.MethodConnect, |
| 643 |
URL: &url.URL{Opaque: targetHost}, // Opaque is required for CONNECT |
| 644 |
Host: targetHost, |
| 645 |
Header: make(http.Header), |
| 646 |
} |
| 647 |
|
| 648 |
// Add proxy authentication if provided |
| 649 |
if username != "" && password != "" { |
| 650 |
req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password))) |
| 651 |
} |
| 652 |
|
| 653 |
if err := req.Write(conn); err != nil { |
| 654 |
conn.Close() |
| 655 |
return nil, fmt.Errorf("failed to write CONNECT request: %v", err) |
| 656 |
} |
| 657 |
|
| 658 |
resp, err := http.ReadResponse(bufio.NewReader(conn), req) |
| 659 |
if err != nil { |
| 660 |
conn.Close() |
| 661 |
return nil, fmt.Errorf("failed to read proxy response: %v", err) |
| 662 |
} |
| 663 |
|
| 664 |
if resp.StatusCode != http.StatusOK { |
| 665 |
resp.Body.Close() |
| 666 |
conn.Close() |
| 667 |
return nil, fmt.Errorf("proxy CONNECT failed: %s", resp.Status) |
| 668 |
} |
| 669 |
|
| 670 |
// Close the response body |
| 671 |
resp.Body.Close() |
| 672 |
|
| 673 |
// Clear the deadline now that we've finished the proxy handshake |
| 674 |
if err := conn.SetDeadline(time.Time{}); err != nil { |
| 675 |
conn.Close() |
| 676 |
return nil, fmt.Errorf("failed to clear deadline: %v", err) |
| 677 |
} |
| 678 |
|
| 679 |
return conn, nil |
| 680 |
} |
| 681 |
|
| 682 |
// Connect to a remote leaf node asynchronously (that is, this function will do |
| 683 |
// the connect in a go routine). |
| 684 |
func (s *Server) connectToRemoteLeafNodeAsynchronously(remote *leafNodeCfg, firstConnect bool) { |
| 685 |
remote.setConnectInProgress(true) |
| 686 |
s.startGoRoutine(func() { |
| 687 |
defer s.grWG.Done() |
| 688 |
if !connectToRemoteLeafNode(s, remote, firstConnect) { |
| 689 |
remote.setConnectInProgress(false) |
| 690 |
} |
| 691 |
}) |
| 692 |
} |
| 693 |
|
| 694 |
// Connect to a remote leaf node. Should only be invoked from |
| 695 |
// `s.connectToRemoteLeafNodeAsynchronously()` or `s.reConnectToRemoteLeafNode()`. |
| 696 |
// Returns `true` if this function invoked `s.createLeafNode()`, false otherwise. |
| 697 |
func connectToRemoteLeafNode(s *Server, remote *leafNodeCfg, firstConnect bool) bool { |
| 698 |
|
| 699 |
if remote == nil || len(remote.URLs) == 0 { |
| 700 |
s.Debugf("Empty remote leafnode definition, nothing to connect") |
| 701 |
return false |
| 702 |
} |
| 703 |
|
| 704 |
// If this remote is no longer valid by the time we return (e.g. it was |
| 705 |
// removed or disabled through a configuration reload), we will never |
| 706 |
// reconnect, so clear any JetStream observer state. Otherwise, the raft |
| 707 |
// nodes of this account's assets would remain observers. |
| 708 |
defer func() { |
| 709 |
if remote.stillValid() { |
| 710 |
return |
| 711 |
} |
| 712 |
s.mu.RLock() |
| 713 |
shouldMigrate := remote.JetStreamClusterMigrate |
| 714 |
s.mu.RUnlock() |
| 715 |
if shouldMigrate { |
| 716 |
s.clearObserverState(remote) |
| 717 |
} |
| 718 |
}() |
| 719 |
|
| 720 |
opts := s.getOpts() |
| 721 |
reconnectDelay := opts.LeafNode.ReconnectInterval |
| 722 |
s.mu.RLock() |
| 723 |
dialTimeout := s.leafNodeOpts.dialTimeout |
| 724 |
resolver := s.leafNodeOpts.resolver |
| 725 |
dialer := s.leafNodeOpts.dialer |
| 726 |
var isSysAcc bool |
| 727 |
if s.eventsEnabled() { |
| 728 |
isSysAcc = remote.LocalAccount == s.sys.account.Name |
| 729 |
} |
| 730 |
jetstreamMigrateDelay := remote.JetStreamClusterMigrateDelay |
| 731 |
s.mu.RUnlock() |
| 732 |
|
| 733 |
// If we are sharing a system account and we are not standalone delay to gather some info prior. |
| 734 |
if firstConnect && isSysAcc && !s.standAloneMode() { |
| 735 |
s.Debugf("Will delay first leafnode connect to shared system account due to clustering") |
| 736 |
remote.setConnectDelay(sharedSysAccDelay) |
| 737 |
} |
| 738 |
|
| 739 |
if connDelay := remote.getConnectDelay(); connDelay > 0 { |
| 740 |
select { |
| 741 |
case <-time.After(connDelay): |
| 742 |
case <-remote.quitCh: |
| 743 |
return false |
| 744 |
case <-s.quitCh: |
| 745 |
return false |
| 746 |
} |
| 747 |
remote.setConnectDelay(0) |
| 748 |
} |
| 749 |
|
| 750 |
var conn net.Conn |
| 751 |
|
| 752 |
const connErrFmt = "Error trying to connect as leafnode to remote server %q (attempt %v): %v" |
| 753 |
|
| 754 |
// Capture proxy configuration once before the loop with proper locking |
| 755 |
remote.RLock() |
| 756 |
proxyURL := remote.Proxy.URL |
| 757 |
proxyUsername := remote.Proxy.Username |
| 758 |
proxyPassword := remote.Proxy.Password |
| 759 |
proxyTimeout := remote.Proxy.Timeout |
| 760 |
// A remote can override the server-wide dial timeout. This is useful on |
| 761 |
// high latency links where the default is too short for the TCP handshake |
| 762 |
// to complete. |
| 763 |
if remote.DialTimeout > 0 { |
| 764 |
dialTimeout = remote.DialTimeout |
| 765 |
} |
| 766 |
remote.RUnlock() |
| 767 |
|
| 768 |
// Set default proxy timeout if not specified |
| 769 |
if proxyTimeout == 0 { |
| 770 |
proxyTimeout = dialTimeout |
| 771 |
} |
| 772 |
|
| 773 |
attempts := 0 |
| 774 |
|
| 775 |
// In case the migrate timer was created but not canceled, do it when |
| 776 |
// this function exits. Note that the timer would not be created if |
| 777 |
// `jetstreamMigrateDelay == 0`. |
| 778 |
if jetstreamMigrateDelay > 0 { |
| 779 |
defer remote.cancelMigrateTimer() |
| 780 |
} |
| 781 |
|
| 782 |
reconnectTimer := time.NewTimer(reconnectDelay) |
| 783 |
reconnectTimer.Stop() |
| 784 |
defer stopAndClearTimer(&reconnectTimer) |
| 785 |
|
| 786 |
for s.isRunning() && remote.stillValid() { |
| 787 |
rURL := remote.pickNextURL() |
| 788 |
url, err := s.getRandomIP(resolver, rURL.Host, nil) |
| 789 |
if err == nil { |
| 790 |
var ipStr string |
| 791 |
if url != rURL.Host { |
| 792 |
ipStr = fmt.Sprintf(" (%s)", url) |
| 793 |
} |
| 794 |
// Some test may want to disable remotes from connecting |
| 795 |
if s.isLeafConnectDisabled() { |
| 796 |
s.Debugf("Will not attempt to connect to remote server on %q%s, leafnodes currently disabled", rURL.Host, ipStr) |
| 797 |
err = ErrLeafNodeDisabled |
| 798 |
} else { |
| 799 |
s.Debugf("Trying to connect as leafnode to remote server on %q%s", rURL.Host, ipStr) |
| 800 |
|
| 801 |
// Check if proxy is configured |
| 802 |
if proxyURL != _EMPTY_ { |
| 803 |
targetHost := rURL.Host |
| 804 |
// If URL doesn't include port, add the default port for the scheme |
| 805 |
if rURL.Port() == _EMPTY_ { |
| 806 |
defaultPort := "80" |
| 807 |
if rURL.Scheme == wsSchemePrefixTLS { |
| 808 |
defaultPort = "443" |
| 809 |
} |
| 810 |
targetHost = net.JoinHostPort(rURL.Hostname(), defaultPort) |
| 811 |
} |
| 812 |
|
| 813 |
conn, err = establishHTTPProxyTunnel(proxyURL, targetHost, proxyTimeout, proxyUsername, proxyPassword) |
| 814 |
} else { |
| 815 |
// Direct connection |
| 816 |
conn, err = dialer("tcp", url, dialTimeout) |
| 817 |
} |
| 818 |
} |
| 819 |
} |
| 820 |
if err != nil { |
| 821 |
jitter := time.Duration(rand.Int63n(int64(reconnectDelay))) |
| 822 |
delay := reconnectDelay + jitter |
| 823 |
attempts++ |
| 824 |
if s.shouldReportConnectErr(firstConnect, attempts) { |
| 825 |
s.Errorf(connErrFmt, rURL.Host, attempts, err) |
| 826 |
} else { |
| 827 |
s.Debugf(connErrFmt, rURL.Host, attempts, err) |
| 828 |
} |
| 829 |
remote.Lock() |
| 830 |
// if we are using a delay to start migrating assets, kick off a migrate timer. |
| 831 |
if remote.jsMigrateTimer == nil && jetstreamMigrateDelay > 0 { |
| 832 |
remote.jsMigrateTimer = time.AfterFunc(jetstreamMigrateDelay, func() { |
| 833 |
s.checkJetStreamMigrate(remote) |
| 834 |
}) |
| 835 |
} |
| 836 |
remote.Unlock() |
| 837 |
reconnectTimer.Reset(delay) |
| 838 |
select { |
| 839 |
case <-s.quitCh: |
| 840 |
return false |
| 841 |
case <-remote.quitCh: |
| 842 |
return false |
| 843 |
case <-reconnectTimer.C: |
| 844 |
// Check if we should migrate any JetStream assets immediately while this remote is down. |
| 845 |
// This will be used if JetStreamClusterMigrateDelay was not set |
| 846 |
if jetstreamMigrateDelay == 0 { |
| 847 |
s.checkJetStreamMigrate(remote) |
| 848 |
} |
| 849 |
continue |
| 850 |
} |
| 851 |
} |
| 852 |
remote.cancelMigrateTimer() |
| 853 |
// We can check here, but really we will have to check again when the server |
| 854 |
// is about to add to the `s.leafs` map later in the process. |
| 855 |
if !remote.stillValid() { |
| 856 |
conn.Close() |
| 857 |
return false |
| 858 |
} |
| 859 |
|
| 860 |
// We have a connection here to a remote server. |
| 861 |
// Go ahead and create our leaf node and return. |
| 862 |
s.createLeafNode(conn, rURL, remote, nil) |
| 863 |
|
| 864 |
// Clear any observer states if we had them. |
| 865 |
s.clearObserverState(remote) |
| 866 |
|
| 867 |
return true |
| 868 |
} |
| 869 |
|
| 870 |
return false |
| 871 |
} |
| 872 |
|
| 873 |
func (cfg *leafNodeCfg) cancelMigrateTimer() { |
| 874 |
cfg.Lock() |
| 875 |
stopAndClearTimer(&cfg.jsMigrateTimer) |
| 876 |
cfg.Unlock() |
| 877 |
} |
| 878 |
|
| 879 |
// This will clear any observer state such that stream or consumer assets on this server can become leaders again. |
| 880 |
func (s *Server) clearObserverState(remote *leafNodeCfg) { |
| 881 |
s.mu.RLock() |
| 882 |
accName := remote.LocalAccount |
| 883 |
s.mu.RUnlock() |
| 884 |
|
| 885 |
acc, err := s.LookupAccount(accName) |
| 886 |
if err != nil { |
| 887 |
s.Warnf("Error looking up account [%s] checking for JetStream clear observer state on a leafnode", accName) |
| 888 |
return |
| 889 |
} |
| 890 |
|
| 891 |
acc.jscmMu.Lock() |
| 892 |
defer acc.jscmMu.Unlock() |
| 893 |
|
| 894 |
// Walk all streams looking for any clustered stream, skip otherwise. |
| 895 |
for _, mset := range acc.streams() { |
| 896 |
node := mset.raftNode() |
| 897 |
if node == nil { |
| 898 |
// Not R>1 |
| 899 |
continue |
| 900 |
} |
| 901 |
// Check consumers |
| 902 |
for _, o := range mset.getConsumers() { |
| 903 |
if n := o.raftNode(); n != nil { |
| 904 |
// Ensure we can become a leader again. |
| 905 |
n.SetObserver(false) |
| 906 |
} |
| 907 |
} |
| 908 |
// Ensure we can not become a leader again. |
| 909 |
node.SetObserver(false) |
| 910 |
} |
| 911 |
} |
| 912 |
|
| 913 |
// Check to see if we should migrate any assets from this account. |
| 914 |
func (s *Server) checkJetStreamMigrate(remote *leafNodeCfg) { |
| 915 |
s.mu.RLock() |
| 916 |
accName, shouldMigrate := remote.LocalAccount, remote.JetStreamClusterMigrate |
| 917 |
s.mu.RUnlock() |
| 918 |
|
| 919 |
if !shouldMigrate { |
| 920 |
return |
| 921 |
} |
| 922 |
|
| 923 |
acc, err := s.LookupAccount(accName) |
| 924 |
if err != nil { |
| 925 |
s.Warnf("Error looking up account [%s] checking for JetStream migration on a leafnode", accName) |
| 926 |
return |
| 927 |
} |
| 928 |
|
| 929 |
acc.jscmMu.Lock() |
| 930 |
defer acc.jscmMu.Unlock() |
| 931 |
|
| 932 |
// Walk all streams looking for any clustered stream, skip otherwise. |
| 933 |
// If we are the leader force stepdown. |
| 934 |
for _, mset := range acc.streams() { |
| 935 |
node := mset.raftNode() |
| 936 |
if node == nil { |
| 937 |
// Not R>1 |
| 938 |
continue |
| 939 |
} |
| 940 |
// Collect any consumers |
| 941 |
for _, o := range mset.getConsumers() { |
| 942 |
if n := o.raftNode(); n != nil { |
| 943 |
n.StepDown() |
| 944 |
// Ensure we can not become a leader while in this state. |
| 945 |
n.SetObserver(true) |
| 946 |
} |
| 947 |
} |
| 948 |
// Stepdown if this stream was leader. |
| 949 |
node.StepDown() |
| 950 |
// Ensure we can not become a leader while in this state. |
| 951 |
node.SetObserver(true) |
| 952 |
} |
| 953 |
} |
| 954 |
|
| 955 |
// Helper for checking. |
| 956 |
func (s *Server) isLeafConnectDisabled() bool { |
| 957 |
s.mu.RLock() |
| 958 |
defer s.mu.RUnlock() |
| 959 |
return s.leafDisableConnect |
| 960 |
} |
| 961 |
|
| 962 |
// Save off the tlsName for when we use TLS and mix hostnames and IPs. IPs usually |
| 963 |
// come from the server we connect to. |
| 964 |
// |
| 965 |
// We used to save the name only if there was a TLSConfig or scheme equal to "tls". |
| 966 |
// However, this was causing failures for users that did not set the scheme (and |
| 967 |
// their remote connections did not have a tls{} block). |
| 968 |
// We now save the host name regardless in case the remote returns an INFO indicating |
| 969 |
// that TLS is required. |
| 970 |
// |
| 971 |
// Lock held on entry. |
| 972 |
func (cfg *leafNodeCfg) saveTLSHostname(u *url.URL) { |
| 973 |
if cfg.tlsName == _EMPTY_ && net.ParseIP(u.Hostname()) == nil { |
| 974 |
cfg.tlsName = u.Hostname() |
| 975 |
} |
| 976 |
} |
| 977 |
|
| 978 |
// Save off the username/password for when we connect using a bare URL |
| 979 |
// that we get from the INFO protocol. |
| 980 |
// |
| 981 |
// Lock held on entry. |
| 982 |
func (cfg *leafNodeCfg) saveUserPassword(u *url.URL) { |
| 983 |
if cfg.username == _EMPTY_ && u.User != nil { |
| 984 |
cfg.username = u.User.Username() |
| 985 |
cfg.password, _ = u.User.Password() |
| 986 |
} |
| 987 |
} |
| 988 |
|
| 989 |
// This starts the leafnode accept loop in a go routine, unless it |
| 990 |
// is detected that the server has already been shutdown. |
| 991 |
func (s *Server) startLeafNodeAcceptLoop() { |
| 992 |
// Snapshot server options. |
| 993 |
opts := s.getOpts() |
| 994 |
|
| 995 |
port := opts.LeafNode.Port |
| 996 |
if port == -1 { |
| 997 |
port = 0 |
| 998 |
} |
| 999 |
|
| 1000 |
if s.isShuttingDown() { |
| 1001 |
return |
| 1002 |
} |
| 1003 |
|
| 1004 |
s.mu.Lock() |
| 1005 |
hp := net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(port)) |
| 1006 |
l, e := natsListen("tcp", hp) |
| 1007 |
s.leafNodeListenerErr = e |
| 1008 |
if e != nil { |
| 1009 |
s.mu.Unlock() |
| 1010 |
s.Fatalf("Error listening on leafnode port: %d - %v", opts.LeafNode.Port, e) |
| 1011 |
return |
| 1012 |
} |
| 1013 |
|
| 1014 |
s.Noticef("Listening for leafnode connections on %s", |
| 1015 |
net.JoinHostPort(opts.LeafNode.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port))) |
| 1016 |
|
| 1017 |
tlsRequired := opts.LeafNode.TLSConfig != nil |
| 1018 |
tlsVerify := tlsRequired && opts.LeafNode.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert |
| 1019 |
// Do not set compression in this Info object, it would possibly cause |
| 1020 |
// issues when sending asynchronous INFO to the remote. |
| 1021 |
info := Info{ |
| 1022 |
ID: s.info.ID, |
| 1023 |
Name: s.info.Name, |
| 1024 |
Version: s.info.Version, |
| 1025 |
GitCommit: gitCommit, |
| 1026 |
GoVersion: runtime.Version(), |
| 1027 |
AuthRequired: true, |
| 1028 |
TLSRequired: tlsRequired, |
| 1029 |
TLSVerify: tlsVerify, |
| 1030 |
MaxPayload: s.info.MaxPayload, // TODO(dlc) - Allow override? |
| 1031 |
Headers: s.supportsHeaders(), |
| 1032 |
JetStream: opts.JetStream, |
| 1033 |
Domain: opts.JetStreamDomain, |
| 1034 |
Proto: s.getServerProto(), |
| 1035 |
InfoOnConnect: true, |
| 1036 |
JSApiLevel: JSApiLevel, |
| 1037 |
} |
| 1038 |
// If we have selected a random port... |
| 1039 |
if port == 0 { |
| 1040 |
// Write resolved port back to options. |
| 1041 |
opts.LeafNode.Port = l.Addr().(*net.TCPAddr).Port |
| 1042 |
} |
| 1043 |
|
| 1044 |
s.leafNodeInfo = info |
| 1045 |
// Possibly override Host/Port and set IP based on Cluster.Advertise |
| 1046 |
if err := s.setLeafNodeInfoHostPortAndIP(); err != nil { |
| 1047 |
s.Fatalf("Error setting leafnode INFO with LeafNode.Advertise value of %s, err=%v", opts.LeafNode.Advertise, err) |
| 1048 |
l.Close() |
| 1049 |
s.mu.Unlock() |
| 1050 |
return |
| 1051 |
} |
| 1052 |
s.leafURLsMap[s.leafNodeInfo.IP]++ |
| 1053 |
s.generateLeafNodeInfoJSON() |
| 1054 |
|
| 1055 |
// Setup state that can enable shutdown |
| 1056 |
s.leafNodeListener = l |
| 1057 |
|
| 1058 |
// As of now, a server that does not have remotes configured would |
| 1059 |
// never solicit a connection, so we should not have to warn if |
| 1060 |
// InsecureSkipVerify is set in main LeafNodes config (since |
| 1061 |
// this TLS setting matters only when soliciting a connection). |
| 1062 |
// Still, warn if insecure is set in any of LeafNode block. |
| 1063 |
// We need to check remotes, even if tls is not required on accept. |
| 1064 |
warn := tlsRequired && opts.LeafNode.TLSConfig.InsecureSkipVerify |
| 1065 |
if !warn { |
| 1066 |
for _, r := range opts.LeafNode.Remotes { |
| 1067 |
if r.TLSConfig != nil && r.TLSConfig.InsecureSkipVerify { |
| 1068 |
warn = true |
| 1069 |
break |
| 1070 |
} |
| 1071 |
} |
| 1072 |
} |
| 1073 |
if warn { |
| 1074 |
s.Warnf(leafnodeTLSInsecureWarning) |
| 1075 |
} |
| 1076 |
go s.acceptConnections(l, "Leafnode", func(conn net.Conn) { s.createLeafNode(conn, nil, nil, nil) }, nil) |
| 1077 |
s.mu.Unlock() |
| 1078 |
} |
| 1079 |
|
| 1080 |
// RegEx to match a creds file with user JWT and Seed. |
| 1081 |
var credsRe = regexp.MustCompile(`\s*(?:(?:[-]{3,}.*[-]{3,}\r?\n)([\w\-.=]+)(?:\r?\n[-]{3,}.*[-]{3,}(\r?\n|\z)))`) |
| 1082 |
|
| 1083 |
// clusterName is provided as argument to avoid lock ordering issues with the locked client c |
| 1084 |
// Lock should be held entering here. |
| 1085 |
func (c *client) sendLeafConnect(clusterName string, headers bool) error { |
| 1086 |
// We support basic user/pass and operator based user JWT with signatures. |
| 1087 |
cinfo := leafConnectInfo{ |
| 1088 |
Version: VERSION, |
| 1089 |
ID: c.srv.info.ID, |
| 1090 |
Domain: c.srv.info.Domain, |
| 1091 |
Name: c.srv.info.Name, |
| 1092 |
Hub: c.leaf.remote.Hub, |
| 1093 |
Cluster: clusterName, |
| 1094 |
Headers: headers, |
| 1095 |
JetStream: c.acc.jetStreamConfigured(), |
| 1096 |
DenyPub: c.leaf.remote.DenyImports, |
| 1097 |
Compression: c.leaf.compression, |
| 1098 |
RemoteAccount: c.acc.GetName(), |
| 1099 |
Proto: c.srv.getServerProto(), |
| 1100 |
Isolate: c.leaf.remote.RequestIsolation, |
| 1101 |
} |
| 1102 |
|
| 1103 |
// If a signature callback is specified, this takes precedence over anything else. |
| 1104 |
if cb := c.leaf.remote.SignatureCB; cb != nil { |
| 1105 |
nonce := c.nonce |
| 1106 |
c.mu.Unlock() |
| 1107 |
jwt, sigraw, err := cb(nonce) |
| 1108 |
c.mu.Lock() |
| 1109 |
if err == nil && c.isClosed() { |
| 1110 |
err = ErrConnectionClosed |
| 1111 |
} |
| 1112 |
if err != nil { |
| 1113 |
c.Errorf("Error signing the nonce: %v", err) |
| 1114 |
return err |
| 1115 |
} |
| 1116 |
sig := base64.RawURLEncoding.EncodeToString(sigraw) |
| 1117 |
cinfo.JWT, cinfo.Sig = jwt, sig |
| 1118 |
|
| 1119 |
} else if creds := c.leaf.remote.Credentials; creds != _EMPTY_ { |
| 1120 |
// Check for credentials first, that will take precedence.. |
| 1121 |
c.Debugf("Authenticating with credentials file %q", c.leaf.remote.Credentials) |
| 1122 |
contents, err := os.ReadFile(creds) |
| 1123 |
if err != nil { |
| 1124 |
c.Errorf("%v", err) |
| 1125 |
return err |
| 1126 |
} |
| 1127 |
defer wipeSlice(contents) |
| 1128 |
items := credsRe.FindAllSubmatch(contents, -1) |
| 1129 |
if len(items) < 2 { |
| 1130 |
c.Errorf("Credentials file malformed") |
| 1131 |
return err |
| 1132 |
} |
| 1133 |
// First result should be the user JWT. |
| 1134 |
// We copy here so that the file containing the seed will be wiped appropriately. |
| 1135 |
raw := items[0][1] |
| 1136 |
tmp := make([]byte, len(raw)) |
| 1137 |
copy(tmp, raw) |
| 1138 |
// Seed is second item. |
| 1139 |
kp, err := nkeys.FromSeed(items[1][1]) |
| 1140 |
if err != nil { |
| 1141 |
c.Errorf("Credentials file has malformed seed") |
| 1142 |
return err |
| 1143 |
} |
| 1144 |
// Wipe our key on exit. |
| 1145 |
defer kp.Wipe() |
| 1146 |
|
| 1147 |
sigraw, _ := kp.Sign(c.nonce) |
| 1148 |
sig := base64.RawURLEncoding.EncodeToString(sigraw) |
| 1149 |
cinfo.JWT = bytesToString(tmp) |
| 1150 |
cinfo.Sig = sig |
| 1151 |
} else if nkey := c.leaf.remote.Nkey; nkey != _EMPTY_ { |
| 1152 |
kp, err := nkeys.FromSeed([]byte(nkey)) |
| 1153 |
if err != nil { |
| 1154 |
c.Errorf("Remote nkey has malformed seed") |
| 1155 |
return err |
| 1156 |
} |
| 1157 |
// Wipe our key on exit. |
| 1158 |
defer kp.Wipe() |
| 1159 |
sigraw, _ := kp.Sign(c.nonce) |
| 1160 |
sig := base64.RawURLEncoding.EncodeToString(sigraw) |
| 1161 |
pkey, _ := kp.PublicKey() |
| 1162 |
cinfo.Nkey = pkey |
| 1163 |
cinfo.Sig = sig |
| 1164 |
} |
| 1165 |
// In addition, and this is to allow auth callout, set user/password or |
| 1166 |
// token if applicable. |
| 1167 |
if userInfo := c.leaf.remote.curURL.User; userInfo != nil { |
| 1168 |
cinfo.User = userInfo.Username() |
| 1169 |
var ok bool |
| 1170 |
cinfo.Pass, ok = userInfo.Password() |
| 1171 |
// For backward compatibility, if only username is provided, set both |
| 1172 |
// Token and User, not just Token. |
| 1173 |
if !ok { |
| 1174 |
cinfo.Token = cinfo.User |
| 1175 |
} |
| 1176 |
} else if c.leaf.remote.username != _EMPTY_ { |
| 1177 |
cinfo.User = c.leaf.remote.username |
| 1178 |
cinfo.Pass = c.leaf.remote.password |
| 1179 |
// For backward compatibility, if only username is provided, set both |
| 1180 |
// Token and User, not just Token. |
| 1181 |
if cinfo.Pass == _EMPTY_ { |
| 1182 |
cinfo.Token = cinfo.User |
| 1183 |
} |
| 1184 |
} |
| 1185 |
b, err := json.Marshal(cinfo) |
| 1186 |
if err != nil { |
| 1187 |
c.Errorf("Error marshaling CONNECT to remote leafnode: %v\n", err) |
| 1188 |
return err |
| 1189 |
} |
| 1190 |
// Although this call is made before the writeLoop is created, |
| 1191 |
// we don't really need to send in place. The protocol will be |
| 1192 |
// sent out by the writeLoop. |
| 1193 |
c.enqueueProto([]byte(fmt.Sprintf(ConProto, b))) |
| 1194 |
return nil |
| 1195 |
} |
| 1196 |
|
| 1197 |
// Makes a deep copy of the LeafNode Info structure. |
| 1198 |
// The server lock is held on entry. |
| 1199 |
func (s *Server) copyLeafNodeInfo() *Info { |
| 1200 |
clone := s.leafNodeInfo |
| 1201 |
// Copy the array of urls. |
| 1202 |
if len(s.leafNodeInfo.LeafNodeURLs) > 0 { |
| 1203 |
clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...) |
| 1204 |
} |
| 1205 |
return &clone |
| 1206 |
} |
| 1207 |
|
| 1208 |
// Adds a LeafNode URL that we get when a route connects to the Info structure. |
| 1209 |
// Regenerates the JSON byte array so that it can be sent to LeafNode connections. |
| 1210 |
// Returns a boolean indicating if the URL was added or not. |
| 1211 |
// Server lock is held on entry |
| 1212 |
func (s *Server) addLeafNodeURL(urlStr string) bool { |
| 1213 |
if s.leafURLsMap.addUrl(urlStr) { |
| 1214 |
s.generateLeafNodeInfoJSON() |
| 1215 |
return true |
| 1216 |
} |
| 1217 |
return false |
| 1218 |
} |
| 1219 |
|
| 1220 |
// Removes a LeafNode URL of the route that is disconnecting from the Info structure. |
| 1221 |
// Regenerates the JSON byte array so that it can be sent to LeafNode connections. |
| 1222 |
// Returns a boolean indicating if the URL was removed or not. |
| 1223 |
// Server lock is held on entry. |
| 1224 |
func (s *Server) removeLeafNodeURL(urlStr string) bool { |
| 1225 |
// Don't need to do this if we are removing the route connection because |
| 1226 |
// we are shuting down... |
| 1227 |
if s.isShuttingDown() { |
| 1228 |
return false |
| 1229 |
} |
| 1230 |
if s.leafURLsMap.removeUrl(urlStr) { |
| 1231 |
s.generateLeafNodeInfoJSON() |
| 1232 |
return true |
| 1233 |
} |
| 1234 |
return false |
| 1235 |
} |
| 1236 |
|
| 1237 |
// Server lock is held on entry |
| 1238 |
func (s *Server) generateLeafNodeInfoJSON() { |
| 1239 |
s.leafNodeInfo.Cluster = s.cachedClusterName() |
| 1240 |
s.leafNodeInfo.LeafNodeURLs = s.leafURLsMap.getAsStringSlice() |
| 1241 |
s.leafNodeInfo.WSConnectURLs = s.websocket.connectURLsMap.getAsStringSlice() |
| 1242 |
s.leafNodeInfoJSON = generateInfoJSON(&s.leafNodeInfo) |
| 1243 |
} |
| 1244 |
|
| 1245 |
// Sends an async INFO protocol so that the connected servers can update |
| 1246 |
// their list of LeafNode urls. |
| 1247 |
func (s *Server) sendAsyncLeafNodeInfo() { |
| 1248 |
for _, c := range s.leafs { |
| 1249 |
c.mu.Lock() |
| 1250 |
c.enqueueProto(s.leafNodeInfoJSON) |
| 1251 |
c.mu.Unlock() |
| 1252 |
} |
| 1253 |
} |
| 1254 |
|
| 1255 |
// Called when an inbound leafnode connection is accepted or we create one for a solicited leafnode. |
| 1256 |
func (s *Server) createLeafNode(conn net.Conn, rURL *url.URL, remote *leafNodeCfg, ws *websocket) *client { |
| 1257 |
// Snapshot server options. |
| 1258 |
opts := s.getOpts() |
| 1259 |
|
| 1260 |
maxPay := int32(opts.MaxPayload) |
| 1261 |
maxSubs := int32(opts.MaxSubs) |
| 1262 |
// For system, maxSubs of 0 means unlimited, so re-adjust here. |
| 1263 |
if maxSubs == 0 { |
| 1264 |
maxSubs = -1 |
| 1265 |
} |
| 1266 |
now := time.Now().UTC() |
| 1267 |
|
| 1268 |
c := &client{srv: s, nc: conn, kind: LEAF, opts: defaultOpts, mpay: maxPay, msubs: maxSubs, start: now, last: now} |
| 1269 |
// Do not update the smap here, we need to do it in initLeafNodeSmapAndSendSubs |
| 1270 |
c.leaf = &leaf{} |
| 1271 |
|
| 1272 |
// If the leafnode subject interest should be isolated, flag it here. |
| 1273 |
s.optsMu.RLock() |
| 1274 |
if c.leaf.isolated = s.opts.LeafNode.IsolateLeafnodeInterest; !c.leaf.isolated && remote != nil { |
| 1275 |
c.leaf.isolated = remote.LocalIsolation |
| 1276 |
} |
| 1277 |
s.optsMu.RUnlock() |
| 1278 |
|
| 1279 |
// For accepted LN connections, ws will be != nil if it was accepted |
| 1280 |
// through the Websocket port. |
| 1281 |
c.ws = ws |
| 1282 |
|
| 1283 |
// For remote, check if the scheme starts with "ws", if so, we will initiate |
| 1284 |
// a remote Leaf Node connection as a websocket connection. |
| 1285 |
if remote != nil && rURL != nil && isWSURL(rURL) { |
| 1286 |
remote.RLock() |
| 1287 |
c.ws = &websocket{compress: remote.Websocket.Compression, maskwrite: !remote.Websocket.NoMasking} |
| 1288 |
remote.RUnlock() |
| 1289 |
} |
| 1290 |
|
| 1291 |
// Determines if we are soliciting the connection or not. |
| 1292 |
var solicited bool |
| 1293 |
var acc *Account |
| 1294 |
var remoteSuffix string |
| 1295 |
if remote != nil { |
| 1296 |
// For now, if lookup fails, we will constantly try |
| 1297 |
// to recreate this LN connection. |
| 1298 |
lacc := remote.LocalAccount |
| 1299 |
var err error |
| 1300 |
acc, err = s.LookupAccount(lacc) |
| 1301 |
if err != nil { |
| 1302 |
// An account not existing is something that can happen with nats/http account resolver and the account |
| 1303 |
// has not yet been pushed, or the request failed for other reasons. |
| 1304 |
// remote needs to be set or retry won't happen |
| 1305 |
c.leaf.remote = remote |
| 1306 |
c.closeConnection(MissingAccount) |
| 1307 |
s.Errorf("Unable to lookup account %s for solicited leafnode connection: %v", lacc, err) |
| 1308 |
return nil |
| 1309 |
} |
| 1310 |
remoteSuffix = fmt.Sprintf(" for account: %s", acc.traceLabel()) |
| 1311 |
} |
| 1312 |
|
| 1313 |
c.mu.Lock() |
| 1314 |
c.initClient() |
| 1315 |
c.Noticef("Leafnode connection created%s %s", remoteSuffix, c.opts.Name) |
| 1316 |
|
| 1317 |
var ( |
| 1318 |
tlsFirst bool |
| 1319 |
tlsFirstFallback time.Duration |
| 1320 |
infoTimeout time.Duration |
| 1321 |
) |
| 1322 |
if remote != nil { |
| 1323 |
solicited = true |
| 1324 |
remote.Lock() |
| 1325 |
c.leaf.remote = remote |
| 1326 |
c.setPermissions(remote.perms) |
| 1327 |
if !c.leaf.remote.Hub { |
| 1328 |
c.leaf.isSpoke = true |
| 1329 |
} |
| 1330 |
tlsFirst = remote.TLSHandshakeFirst |
| 1331 |
infoTimeout = remote.FirstInfoTimeout |
| 1332 |
remote.Unlock() |
| 1333 |
c.acc = acc |
| 1334 |
} else { |
| 1335 |
c.flags.set(expectConnect) |
| 1336 |
if ws != nil { |
| 1337 |
c.Debugf("Leafnode compression=%v", c.ws.compress) |
| 1338 |
} |
| 1339 |
tlsFirst = opts.LeafNode.TLSHandshakeFirst |
| 1340 |
if f := opts.LeafNode.TLSHandshakeFirstFallback; f > 0 { |
| 1341 |
tlsFirstFallback = f |
| 1342 |
} |
| 1343 |
} |
| 1344 |
c.mu.Unlock() |
| 1345 |
|
| 1346 |
var nonce [nonceLen]byte |
| 1347 |
var info *Info |
| 1348 |
|
| 1349 |
// Grab this before the client lock below. |
| 1350 |
if !solicited { |
| 1351 |
// Grab server variables |
| 1352 |
s.mu.Lock() |
| 1353 |
info = s.copyLeafNodeInfo() |
| 1354 |
// For tests that want to simulate old servers, do not set the compression |
| 1355 |
// on the INFO protocol if configured with CompressionNotSupported. |
| 1356 |
// Also suppress it if WebSocket compression is already in use, otherwise |
| 1357 |
// an old soliciting peer would honor the advertised mode, switch to S2, |
| 1358 |
// and then wait forever for a compressed INFO response from us. |
| 1359 |
if cm := opts.LeafNode.Compression.Mode; cm != CompressionNotSupported && (ws == nil || !ws.compress) { |
| 1360 |
info.Compression = cm |
| 1361 |
} |
| 1362 |
// We always send a nonce for LEAF connections. Do not change that without |
| 1363 |
// taking into account presence of proxy trusted keys. |
| 1364 |
s.generateNonce(nonce[:]) |
| 1365 |
s.mu.Unlock() |
| 1366 |
} |
| 1367 |
|
| 1368 |
// Grab lock |
| 1369 |
c.mu.Lock() |
| 1370 |
|
| 1371 |
var preBuf []byte |
| 1372 |
if solicited { |
| 1373 |
// For websocket connection, we need to send an HTTP request, |
| 1374 |
// and get the response before starting the readLoop to get |
| 1375 |
// the INFO, etc.. |
| 1376 |
if c.isWebsocket() { |
| 1377 |
var err error |
| 1378 |
var closeReason ClosedState |
| 1379 |
|
| 1380 |
preBuf, closeReason, err = c.leafNodeSolicitWSConnection(opts, rURL, remote) |
| 1381 |
if err != nil { |
| 1382 |
c.Errorf("Error soliciting websocket connection: %v", err) |
| 1383 |
c.mu.Unlock() |
| 1384 |
if closeReason != 0 { |
| 1385 |
c.closeConnection(closeReason) |
| 1386 |
} |
| 1387 |
return nil |
| 1388 |
} |
| 1389 |
} else { |
| 1390 |
// If configured to do TLS handshake first |
| 1391 |
if tlsFirst { |
| 1392 |
if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil { |
| 1393 |
c.mu.Unlock() |
| 1394 |
return nil |
| 1395 |
} |
| 1396 |
} |
| 1397 |
// We need to wait for the info, but not for too long. |
| 1398 |
c.nc.SetReadDeadline(time.Now().Add(infoTimeout)) |
| 1399 |
} |
| 1400 |
|
| 1401 |
// We will process the INFO from the readloop and finish by |
| 1402 |
// sending the CONNECT and finish registration later. |
| 1403 |
} else { |
| 1404 |
// Send our info to the other side. |
| 1405 |
// Remember the nonce we sent here for signatures, etc. |
| 1406 |
c.nonce = make([]byte, nonceLen) |
| 1407 |
copy(c.nonce, nonce[:]) |
| 1408 |
info.Nonce = bytesToString(c.nonce) |
| 1409 |
info.CID = c.cid |
| 1410 |
proto := generateInfoJSON(info) |
| 1411 |
|
| 1412 |
var pre []byte |
| 1413 |
// We need first to check for "TLS First" fallback delay. |
| 1414 |
if tlsFirstFallback > 0 { |
| 1415 |
// We wait and see if we are getting any data. Since we did not send |
| 1416 |
// the INFO protocol yet, only clients that use TLS first should be |
| 1417 |
// sending data (the TLS handshake). We don't really check the content: |
| 1418 |
// if it is a rogue agent and not an actual client performing the |
| 1419 |
// TLS handshake, the error will be detected when performing the |
| 1420 |
// handshake on our side. |
| 1421 |
pre = make([]byte, 4) |
| 1422 |
c.nc.SetReadDeadline(time.Now().Add(tlsFirstFallback)) |
| 1423 |
n, _ := io.ReadFull(c.nc, pre[:]) |
| 1424 |
c.nc.SetReadDeadline(time.Time{}) |
| 1425 |
// If we get any data (regardless of possible timeout), we will proceed |
| 1426 |
// with the TLS handshake. |
| 1427 |
if n > 0 { |
| 1428 |
pre = pre[:n] |
| 1429 |
} else { |
| 1430 |
// We did not get anything so we will send the INFO protocol. |
| 1431 |
pre = nil |
| 1432 |
// Set the boolean to false for the rest of the function. |
| 1433 |
tlsFirst = false |
| 1434 |
} |
| 1435 |
} |
| 1436 |
|
| 1437 |
if !tlsFirst { |
| 1438 |
// We have to send from this go routine because we may |
| 1439 |
// have to block for TLS handshake before we start our |
| 1440 |
// writeLoop go routine. The other side needs to receive |
| 1441 |
// this before it can initiate the TLS handshake.. |
| 1442 |
c.sendProtoNow(proto) |
| 1443 |
|
| 1444 |
// The above call could have marked the connection as closed (due to TCP error). |
| 1445 |
if c.isClosed() { |
| 1446 |
c.mu.Unlock() |
| 1447 |
c.closeConnection(WriteError) |
| 1448 |
return nil |
| 1449 |
} |
| 1450 |
} |
| 1451 |
|
| 1452 |
// Check to see if we need to spin up TLS. |
| 1453 |
if !c.isWebsocket() && info.TLSRequired { |
| 1454 |
// If we have a prebuffer create a multi-reader. |
| 1455 |
if len(pre) > 0 { |
| 1456 |
c.nc = &tlsMixConn{c.nc, bytes.NewBuffer(pre)} |
| 1457 |
} |
| 1458 |
// Perform server-side TLS handshake. |
| 1459 |
if err := c.doTLSServerHandshake(tlsHandshakeLeaf, opts.LeafNode.TLSConfig, opts.LeafNode.TLSTimeout, opts.LeafNode.TLSPinnedCerts); err != nil { |
| 1460 |
c.mu.Unlock() |
| 1461 |
return nil |
| 1462 |
} |
| 1463 |
} |
| 1464 |
|
| 1465 |
// If the user wants the TLS handshake to occur first, now that it is |
| 1466 |
// done, send the INFO protocol. |
| 1467 |
if tlsFirst { |
| 1468 |
c.flags.set(didTLSFirst) |
| 1469 |
c.sendProtoNow(proto) |
| 1470 |
if c.isClosed() { |
| 1471 |
c.mu.Unlock() |
| 1472 |
c.closeConnection(WriteError) |
| 1473 |
return nil |
| 1474 |
} |
| 1475 |
} |
| 1476 |
|
| 1477 |
// Leaf nodes will always require a CONNECT to let us know |
| 1478 |
// when we are properly bound to an account. |
| 1479 |
// |
| 1480 |
// If compression is configured, we can't set the authTimer here because |
| 1481 |
// it would cause the parser to fail any incoming protocol that is not a |
| 1482 |
// CONNECT (and we need to exchange INFO protocols for compression |
| 1483 |
// negotiation). So instead, use the ping timer until we are done with |
| 1484 |
// negotiation and can set the auth timer. |
| 1485 |
timeout := secondsToDuration(opts.LeafNode.AuthTimeout) |
| 1486 |
if needsCompression(opts.LeafNode.Compression.Mode) { |
| 1487 |
c.ping.tmr = time.AfterFunc(timeout, func() { |
| 1488 |
c.authTimeout() |
| 1489 |
}) |
| 1490 |
} else { |
| 1491 |
c.setAuthTimer(timeout) |
| 1492 |
} |
| 1493 |
} |
| 1494 |
|
| 1495 |
// Keep track in case server is shutdown before we can successfully register. |
| 1496 |
if !s.addToTempClients(c.cid, c) { |
| 1497 |
c.mu.Unlock() |
| 1498 |
c.setNoReconnect() |
| 1499 |
c.closeConnection(ServerShutdown) |
| 1500 |
return nil |
| 1501 |
} |
| 1502 |
|
| 1503 |
// Spin up the read loop. |
| 1504 |
s.startGoRoutine(func() { c.readLoop(preBuf) }) |
| 1505 |
|
| 1506 |
// We will spin the write loop for solicited connections only |
| 1507 |
// when processing the INFO and after switching to TLS if needed. |
| 1508 |
if !solicited { |
| 1509 |
s.startGoRoutine(func() { c.writeLoop() }) |
| 1510 |
} |
| 1511 |
|
| 1512 |
c.mu.Unlock() |
| 1513 |
|
| 1514 |
return c |
| 1515 |
} |
| 1516 |
|
| 1517 |
// Will perform the client-side TLS handshake if needed. Assumes that this |
| 1518 |
// is called by the solicit side (remote will be non nil). Returns `true` |
| 1519 |
// if TLS is required, `false` otherwise. |
| 1520 |
// Lock held on entry. |
| 1521 |
func (c *client) leafClientHandshakeIfNeeded(remote *leafNodeCfg, opts *Options) (bool, error) { |
| 1522 |
// Check if TLS is required and gather TLS config variables. |
| 1523 |
tlsRequired, tlsConfig, tlsName, tlsTimeout := c.leafNodeGetTLSConfigForSolicit(remote) |
| 1524 |
if !tlsRequired { |
| 1525 |
return false, nil |
| 1526 |
} |
| 1527 |
|
| 1528 |
// If TLS required, peform handshake. |
| 1529 |
// Get the URL that was used to connect to the remote server. |
| 1530 |
rURL := remote.getCurrentURL() |
| 1531 |
|
| 1532 |
// Perform the client-side TLS handshake. |
| 1533 |
if resetTLSName, err := c.doTLSClientHandshake(tlsHandshakeLeaf, rURL, tlsConfig, tlsName, tlsTimeout, opts.LeafNode.TLSPinnedCerts); err != nil { |
| 1534 |
// Check if we need to reset the remote's TLS name. |
| 1535 |
if resetTLSName { |
| 1536 |
remote.Lock() |
| 1537 |
remote.tlsName = _EMPTY_ |
| 1538 |
remote.Unlock() |
| 1539 |
} |
| 1540 |
return false, err |
| 1541 |
} |
| 1542 |
return true, nil |
| 1543 |
} |
| 1544 |
|
| 1545 |
func (c *client) processLeafnodeInfo(info *Info) { |
| 1546 |
c.mu.Lock() |
| 1547 |
if c.leaf == nil || c.isClosed() { |
| 1548 |
c.mu.Unlock() |
| 1549 |
return |
| 1550 |
} |
| 1551 |
s := c.srv |
| 1552 |
opts := s.getOpts() |
| 1553 |
remote := c.leaf.remote |
| 1554 |
didSolicit := remote != nil |
| 1555 |
firstINFO := !c.flags.isSet(infoReceived) |
| 1556 |
|
| 1557 |
// In case of websocket, the TLS handshake has been already done. |
| 1558 |
// So check only for non websocket connections and for configurations |
| 1559 |
// where the TLS Handshake was not done first. |
| 1560 |
if didSolicit && !c.flags.isSet(handshakeComplete) && !c.isWebsocket() && !remote.TLSHandshakeFirst { |
| 1561 |
// If the server requires TLS, we need to set this in the remote |
| 1562 |
// otherwise if there is no TLS configuration block for the remote, |
| 1563 |
// the solicit side will not attempt to perform the TLS handshake. |
| 1564 |
if firstINFO && info.TLSRequired { |
| 1565 |
// Check for TLS/proxy configuration mismatch |
| 1566 |
if remote.Proxy.URL != _EMPTY_ && !remote.TLS && remote.TLSConfig == nil { |
| 1567 |
c.mu.Unlock() |
| 1568 |
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.") |
| 1569 |
c.closeConnection(TLSHandshakeError) |
| 1570 |
return |
| 1571 |
} |
| 1572 |
remote.TLS = true |
| 1573 |
} |
| 1574 |
if _, err := c.leafClientHandshakeIfNeeded(remote, opts); err != nil { |
| 1575 |
c.mu.Unlock() |
| 1576 |
return |
| 1577 |
} |
| 1578 |
} |
| 1579 |
|
| 1580 |
// Check for compression, unless already done. |
| 1581 |
if firstINFO && !c.flags.isSet(compressionNegotiated) { |
| 1582 |
// A solicited leafnode connection must first receive a leafnode INFO. |
| 1583 |
// Classify wrong-port connections before any leaf-specific negotiation. |
| 1584 |
if didSolicit && (info.CID == 0 || info.LeafNodeURLs == nil) { |
| 1585 |
c.mu.Unlock() |
| 1586 |
c.Errorf(ErrConnectedToWrongPort.Error()) |
| 1587 |
c.closeConnection(WrongPort) |
| 1588 |
return |
| 1589 |
} |
| 1590 |
|
| 1591 |
// Prevent from getting back here. |
| 1592 |
c.flags.set(compressionNegotiated) |
| 1593 |
|
| 1594 |
var co *CompressionOpts |
| 1595 |
if !didSolicit { |
| 1596 |
co = &opts.LeafNode.Compression |
| 1597 |
} else { |
| 1598 |
co = &remote.Compression |
| 1599 |
} |
| 1600 |
if needsCompression(co.Mode) { |
| 1601 |
// Release client lock since following function will need server lock. |
| 1602 |
c.mu.Unlock() |
| 1603 |
compress, err := s.negotiateLeafCompression(c, didSolicit, info.Compression, co) |
| 1604 |
if err != nil { |
| 1605 |
c.sendErrAndErr(err.Error()) |
| 1606 |
c.closeConnection(ProtocolViolation) |
| 1607 |
return |
| 1608 |
} |
| 1609 |
if compress { |
| 1610 |
// Done for now, will get back another INFO protocol... |
| 1611 |
return |
| 1612 |
} |
| 1613 |
// No compression because one side does not want/can't, so proceed. |
| 1614 |
c.mu.Lock() |
| 1615 |
// Check that the connection did not close if the lock was released. |
| 1616 |
if c.isClosed() { |
| 1617 |
c.mu.Unlock() |
| 1618 |
return |
| 1619 |
} |
| 1620 |
} else { |
| 1621 |
// Coming from an old server, the Compression field would be the empty |
| 1622 |
// string. For servers that are configured with CompressionNotSupported, |
| 1623 |
// this makes them behave as old servers. |
| 1624 |
if info.Compression == _EMPTY_ || co.Mode == CompressionNotSupported { |
| 1625 |
c.leaf.compression = CompressionNotSupported |
| 1626 |
} else { |
| 1627 |
c.leaf.compression = CompressionOff |
| 1628 |
} |
| 1629 |
} |
| 1630 |
// Accepting side does not normally process an INFO protocol during |
| 1631 |
// initial connection handshake. So we keep it consistent by returning |
| 1632 |
// if we are not soliciting. |
| 1633 |
if !didSolicit { |
| 1634 |
// If we had created the ping timer instead of the auth timer, we will |
| 1635 |
// clear the ping timer and set the auth timer now that the compression |
| 1636 |
// negotiation is done. |
| 1637 |
if info.Compression != _EMPTY_ && c.ping.tmr != nil { |
| 1638 |
clearTimer(&c.ping.tmr) |
| 1639 |
c.setAuthTimer(secondsToDuration(opts.LeafNode.AuthTimeout)) |
| 1640 |
} |
| 1641 |
c.mu.Unlock() |
| 1642 |
return |
| 1643 |
} |
| 1644 |
// Fall through and process the INFO protocol as usual. |
| 1645 |
} |
| 1646 |
|
| 1647 |
// Note: For now, only the initial INFO has a nonce. We |
| 1648 |
// will probably do auto key rotation at some point. |
| 1649 |
if firstINFO { |
| 1650 |
// Mark that the INFO protocol has been received. |
| 1651 |
c.flags.set(infoReceived) |
| 1652 |
// Prevent connecting to non leafnode port. Need to do this only for |
| 1653 |
// the first INFO, not for async INFO updates... |
| 1654 |
// |
| 1655 |
// Content of INFO sent by the server when accepting a tcp connection. |
| 1656 |
// ------------------------------------------------------------------- |
| 1657 |
// Listen Port Of | CID | ClientConnectURLs | LeafNodeURLs | Gateway | |
| 1658 |
// ------------------------------------------------------------------- |
| 1659 |
// CLIENT | X* | X** | | | |
| 1660 |
// ROUTE | | X** | X*** | | |
| 1661 |
// GATEWAY | | | | X | |
| 1662 |
// LEAFNODE | X | | X | | |
| 1663 |
// ------------------------------------------------------------------- |
| 1664 |
// * Not on older servers. |
| 1665 |
// ** Not if "no advertise" is enabled. |
| 1666 |
// *** Not if leafnode's "no advertise" is enabled. |
| 1667 |
// |
| 1668 |
// Reject a cluster that contains spaces. |
| 1669 |
if info.Cluster != _EMPTY_ && strings.Contains(info.Cluster, " ") { |
| 1670 |
c.mu.Unlock() |
| 1671 |
c.sendErrAndErr(ErrClusterNameHasSpaces.Error()) |
| 1672 |
c.closeConnection(ProtocolViolation) |
| 1673 |
return |
| 1674 |
} |
| 1675 |
// For solicited outbound leaf connections, capture the remote's nonce. |
| 1676 |
// For inbound leaf connections, keep using the server-issued nonce that |
| 1677 |
// was sent in our initial INFO and must be signed in CONNECT. |
| 1678 |
if didSolicit { |
| 1679 |
c.nonce = []byte(info.Nonce) |
| 1680 |
} |
| 1681 |
if info.TLSRequired && didSolicit { |
| 1682 |
remote.TLS = true |
| 1683 |
} |
| 1684 |
supportsHeaders := c.srv.supportsHeaders() |
| 1685 |
c.headers = supportsHeaders && info.Headers |
| 1686 |
|
| 1687 |
// Remember the remote server. |
| 1688 |
// Pre 2.2.0 servers are not sending their server name. |
| 1689 |
// In that case, use info.ID, which, for those servers, matches |
| 1690 |
// the content of the field `Name` in the leafnode CONNECT protocol. |
| 1691 |
if info.Name == _EMPTY_ { |
| 1692 |
c.leaf.remoteServer = info.ID |
| 1693 |
} else { |
| 1694 |
c.leaf.remoteServer = info.Name |
| 1695 |
} |
| 1696 |
c.leaf.remoteDomain = info.Domain |
| 1697 |
c.leaf.remoteCluster = info.Cluster |
| 1698 |
// We send the protocol version in the INFO protocol. |
| 1699 |
// Keep track of it, so we know if this connection supports message |
| 1700 |
// tracing for instance. |
| 1701 |
c.opts.Protocol = info.Proto |
| 1702 |
} |
| 1703 |
|
| 1704 |
// For both initial INFO and async INFO protocols, Possibly |
| 1705 |
// update our list of remote leafnode URLs we can connect to, |
| 1706 |
// unless we are instructed not to. |
| 1707 |
if didSolicit && !remote.IgnoreDiscoveredServers && |
| 1708 |
(len(info.LeafNodeURLs) > 0 || len(info.WSConnectURLs) > 0) { |
| 1709 |
// Consider the incoming array as the most up-to-date |
| 1710 |
// representation of the remote cluster's list of URLs. |
| 1711 |
c.updateLeafNodeURLs(info) |
| 1712 |
} |
| 1713 |
|
| 1714 |
// Only solicited leafnode connections trust permission updates from INFO. |
| 1715 |
if didSolicit && (info.Import != nil || info.Export != nil) { |
| 1716 |
perms := &Permissions{ |
| 1717 |
Publish: info.Export, |
| 1718 |
Subscribe: info.Import, |
| 1719 |
} |
| 1720 |
// Check if we have local deny clauses that we need to merge. |
| 1721 |
if remote := c.leaf.remote; remote != nil { |
| 1722 |
if len(remote.DenyExports) > 0 { |
| 1723 |
if perms.Publish == nil { |
| 1724 |
perms.Publish = &SubjectPermission{} |
| 1725 |
} |
| 1726 |
perms.Publish.Deny = append(perms.Publish.Deny, remote.DenyExports...) |
| 1727 |
} |
| 1728 |
if len(remote.DenyImports) > 0 { |
| 1729 |
if perms.Subscribe == nil { |
| 1730 |
perms.Subscribe = &SubjectPermission{} |
| 1731 |
} |
| 1732 |
perms.Subscribe.Deny = append(perms.Subscribe.Deny, remote.DenyImports...) |
| 1733 |
} |
| 1734 |
} |
| 1735 |
c.setPermissions(perms) |
| 1736 |
} |
| 1737 |
|
| 1738 |
var resumeConnect bool |
| 1739 |
|
| 1740 |
// If this is a remote connection and this is the first INFO protocol, |
| 1741 |
// then we need to finish the connect process by sending CONNECT, etc.. |
| 1742 |
if firstINFO && didSolicit { |
| 1743 |
// Clear deadline that was set in createLeafNode while waiting for the INFO. |
| 1744 |
c.nc.SetDeadline(time.Time{}) |
| 1745 |
resumeConnect = true |
| 1746 |
} else if !firstINFO && didSolicit { |
| 1747 |
c.leaf.remoteAccName = info.RemoteAccount |
| 1748 |
} |
| 1749 |
|
| 1750 |
// Check if we have the remote account information and if so make sure it's stored. |
| 1751 |
if info.RemoteAccount != _EMPTY_ { |
| 1752 |
if c.acc == nil { |
| 1753 |
c.mu.Unlock() |
| 1754 |
c.sendErr("Authorization Violation") |
| 1755 |
c.closeConnection(ProtocolViolation) |
| 1756 |
return |
| 1757 |
} |
| 1758 |
s.leafRemoteAccounts.Store(c.acc.Name, info.RemoteAccount) |
| 1759 |
} |
| 1760 |
c.mu.Unlock() |
| 1761 |
|
| 1762 |
finishConnect := info.ConnectInfo |
| 1763 |
if resumeConnect && s != nil { |
| 1764 |
s.leafNodeResumeConnectProcess(c) |
| 1765 |
if !info.InfoOnConnect { |
| 1766 |
finishConnect = true |
| 1767 |
} |
| 1768 |
} |
| 1769 |
if finishConnect { |
| 1770 |
s.leafNodeFinishConnectProcess(c) |
| 1771 |
} |
| 1772 |
|
| 1773 |
// Check to see if we need to kick any internal source or mirror consumers. |
| 1774 |
// This will be a no-op if JetStream not enabled for this server or if the bound account |
| 1775 |
// does not have jetstream. |
| 1776 |
s.checkInternalSyncConsumers(c.acc) |
| 1777 |
} |
| 1778 |
|
| 1779 |
func (s *Server) negotiateLeafCompression(c *client, didSolicit bool, infoCompression string, co *CompressionOpts) (bool, error) { |
| 1780 |
// If WebSocket compression is already negotiated on this connection then |
| 1781 |
// we shouldn't layer S2 compression on top of it. |
| 1782 |
c.mu.Lock() |
| 1783 |
if c.ws != nil && c.ws.compress { |
| 1784 |
c.leaf.compression = CompressionOff |
| 1785 |
c.mu.Unlock() |
| 1786 |
return false, nil |
| 1787 |
} |
| 1788 |
c.mu.Unlock() |
| 1789 |
// Negotiate the appropriate compression mode (or no compression) |
| 1790 |
cm, err := selectCompressionMode(co.Mode, infoCompression) |
| 1791 |
if err != nil { |
| 1792 |
return false, err |
| 1793 |
} |
| 1794 |
c.mu.Lock() |
| 1795 |
// For "auto" mode, set the initial compression mode based on RTT |
| 1796 |
if cm == CompressionS2Auto { |
| 1797 |
if c.rttStart.IsZero() { |
| 1798 |
c.rtt = computeRTT(c.start) |
| 1799 |
} |
| 1800 |
cm = selectS2AutoModeBasedOnRTT(c.rtt, co.RTTThresholds) |
| 1801 |
} |
| 1802 |
// Keep track of the negotiated compression mode. |
| 1803 |
c.leaf.compression = cm |
| 1804 |
cid := c.cid |
| 1805 |
var nonce string |
| 1806 |
if !didSolicit { |
| 1807 |
nonce = bytesToString(c.nonce) |
| 1808 |
} |
| 1809 |
c.mu.Unlock() |
| 1810 |
|
| 1811 |
if !needsCompression(cm) { |
| 1812 |
return false, nil |
| 1813 |
} |
| 1814 |
|
| 1815 |
// If we end-up doing compression... |
| 1816 |
|
| 1817 |
// Generate an INFO with the chosen compression mode. |
| 1818 |
s.mu.Lock() |
| 1819 |
info := s.copyLeafNodeInfo() |
| 1820 |
info.Compression, info.CID, info.Nonce = compressionModeForInfoProtocol(co, cm), cid, nonce |
| 1821 |
infoProto := generateInfoJSON(info) |
| 1822 |
s.mu.Unlock() |
| 1823 |
|
| 1824 |
// If we solicited, then send this INFO protocol BEFORE switching |
| 1825 |
// to compression writer. However, if we did not, we send it after. |
| 1826 |
c.mu.Lock() |
| 1827 |
if didSolicit { |
| 1828 |
c.enqueueProto(infoProto) |
| 1829 |
// Make sure it is completely flushed (the pending bytes goes to |
| 1830 |
// 0) before proceeding. |
| 1831 |
for c.out.pb > 0 && !c.isClosed() { |
| 1832 |
c.flushOutbound() |
| 1833 |
} |
| 1834 |
} |
| 1835 |
// This is to notify the readLoop that it should switch to a |
| 1836 |
// (de)compression reader. |
| 1837 |
c.in.flags.set(switchToCompression) |
| 1838 |
// Create the compress writer before queueing the INFO protocol for |
| 1839 |
// a route that did not solicit. It will make sure that that proto |
| 1840 |
// is sent with compression on. |
| 1841 |
c.out.cw = s2.NewWriter(nil, s2WriterOptions(cm)...) |
| 1842 |
if !didSolicit { |
| 1843 |
c.enqueueProto(infoProto) |
| 1844 |
} |
| 1845 |
c.mu.Unlock() |
| 1846 |
return true, nil |
| 1847 |
} |
| 1848 |
|
| 1849 |
// When getting a leaf node INFO protocol, use the provided |
| 1850 |
// array of urls to update the list of possible endpoints. |
| 1851 |
func (c *client) updateLeafNodeURLs(info *Info) { |
| 1852 |
cfg := c.leaf.remote |
| 1853 |
cfg.Lock() |
| 1854 |
defer cfg.Unlock() |
| 1855 |
|
| 1856 |
// We have ensured that if a remote has a WS scheme, then all are. |
| 1857 |
// So check if first is WS, then add WS URLs, otherwise, add non WS ones. |
| 1858 |
if len(cfg.URLs) > 0 && isWSURL(cfg.URLs[0]) { |
| 1859 |
// It does not really matter if we use "ws://" or "wss://" here since |
| 1860 |
// we will have already marked that the remote should use TLS anyway. |
| 1861 |
// But use proper scheme for log statements, etc... |
| 1862 |
proto := wsSchemePrefix |
| 1863 |
if cfg.TLS { |
| 1864 |
proto = wsSchemePrefixTLS |
| 1865 |
} |
| 1866 |
c.doUpdateLNURLs(cfg, proto, info.WSConnectURLs) |
| 1867 |
return |
| 1868 |
} |
| 1869 |
c.doUpdateLNURLs(cfg, "nats-leaf", info.LeafNodeURLs) |
| 1870 |
} |
| 1871 |
|
| 1872 |
func (c *client) doUpdateLNURLs(cfg *leafNodeCfg, scheme string, URLs []string) { |
| 1873 |
cfg.urls = make([]*url.URL, 0, 1+len(URLs)) |
| 1874 |
// Add the ones we receive in the protocol |
| 1875 |
for _, surl := range URLs { |
| 1876 |
url, err := url.Parse(fmt.Sprintf("%s://%s", scheme, surl)) |
| 1877 |
if err != nil { |
| 1878 |
// As per below, the URLs we receive should not have contained URL info, so this should be safe to log. |
| 1879 |
c.Errorf("Error parsing url %q: %v", surl, err) |
| 1880 |
continue |
| 1881 |
} |
| 1882 |
// Do not add if it's the same as what we already have configured. |
| 1883 |
var dup bool |
| 1884 |
for _, u := range cfg.URLs { |
| 1885 |
// URLs that we receive never have user info, but the |
| 1886 |
// ones that were configured may have. Simply compare |
| 1887 |
// host and port to decide if they are equal or not. |
| 1888 |
if url.Host == u.Host && url.Port() == u.Port() { |
| 1889 |
dup = true |
| 1890 |
break |
| 1891 |
} |
| 1892 |
} |
| 1893 |
if !dup { |
| 1894 |
cfg.urls = append(cfg.urls, url) |
| 1895 |
cfg.saveTLSHostname(url) |
| 1896 |
} |
| 1897 |
} |
| 1898 |
// Add the configured one |
| 1899 |
cfg.urls = append(cfg.urls, cfg.URLs...) |
| 1900 |
} |
| 1901 |
|
| 1902 |
// Similar to setInfoHostPortAndGenerateJSON, but for leafNodeInfo. |
| 1903 |
func (s *Server) setLeafNodeInfoHostPortAndIP() error { |
| 1904 |
opts := s.getOpts() |
| 1905 |
if opts.LeafNode.Advertise != _EMPTY_ { |
| 1906 |
advHost, advPort, err := parseHostPort(opts.LeafNode.Advertise, opts.LeafNode.Port) |
| 1907 |
if err != nil { |
| 1908 |
return err |
| 1909 |
} |
| 1910 |
s.leafNodeInfo.Host = advHost |
| 1911 |
s.leafNodeInfo.Port = advPort |
| 1912 |
} else { |
| 1913 |
s.leafNodeInfo.Host = opts.LeafNode.Host |
| 1914 |
s.leafNodeInfo.Port = opts.LeafNode.Port |
| 1915 |
// If the host is "0.0.0.0" or "::" we need to resolve to a public IP. |
| 1916 |
// This will return at most 1 IP. |
| 1917 |
hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(s.leafNodeInfo.Host, false) |
| 1918 |
if err != nil { |
| 1919 |
return err |
| 1920 |
} |
| 1921 |
if hostIsIPAny { |
| 1922 |
if len(ips) == 0 { |
| 1923 |
s.Errorf("Could not find any non-local IP for leafnode's listen specification %q", |
| 1924 |
s.leafNodeInfo.Host) |
| 1925 |
} else { |
| 1926 |
// Take the first from the list... |
| 1927 |
s.leafNodeInfo.Host = ips[0] |
| 1928 |
} |
| 1929 |
} |
| 1930 |
} |
| 1931 |
// Use just host:port for the IP |
| 1932 |
s.leafNodeInfo.IP = net.JoinHostPort(s.leafNodeInfo.Host, strconv.Itoa(s.leafNodeInfo.Port)) |
| 1933 |
if opts.LeafNode.Advertise != _EMPTY_ { |
| 1934 |
s.Noticef("Advertise address for leafnode is set to %s", s.leafNodeInfo.IP) |
| 1935 |
} |
| 1936 |
return nil |
| 1937 |
} |
| 1938 |
|
| 1939 |
// Add the connection to the map of leaf nodes. |
| 1940 |
// If `checkForDup` is true (invoked when a leafnode is accepted), then we check |
| 1941 |
// if a connection already exists for the same server name and account. |
| 1942 |
// That can happen when the remote is attempting to reconnect while the accepting |
| 1943 |
// side did not detect the connection as broken yet. |
| 1944 |
// But it can also happen when there is a misconfiguration and the remote is |
| 1945 |
// creating two (or more) connections that bind to the same account on the accept |
| 1946 |
// side. |
| 1947 |
// When a duplicate is found, the new connection is accepted and the old is closed |
| 1948 |
// (this solves the stale connection situation). An error is returned to help the |
| 1949 |
// remote detect the misconfiguration when the duplicate is the result of that |
| 1950 |
// misconfiguration. |
| 1951 |
func (s *Server) addLeafNodeConnection(c *client, srvName, clusterName string, checkForDup bool) bool { |
| 1952 |
var accName string |
| 1953 |
c.mu.Lock() |
| 1954 |
cid := c.cid |
| 1955 |
acc := c.acc |
| 1956 |
if acc != nil { |
| 1957 |
accName = acc.Name |
| 1958 |
} |
| 1959 |
myRemoteDomain := c.leaf.remoteDomain |
| 1960 |
mySrvName := c.leaf.remoteServer |
| 1961 |
remoteAccName := c.leaf.remoteAccName |
| 1962 |
myClustName := c.leaf.remoteCluster |
| 1963 |
remote := c.leaf.remote |
| 1964 |
solicited := remote != nil |
| 1965 |
c.mu.Unlock() |
| 1966 |
|
| 1967 |
var old *client |
| 1968 |
s.mu.Lock() |
| 1969 |
// We check for empty because in some test we may send empty CONNECT{} |
| 1970 |
if checkForDup && srvName != _EMPTY_ { |
| 1971 |
for _, ol := range s.leafs { |
| 1972 |
ol.mu.Lock() |
| 1973 |
// We care here only about non solicited Leafnode. This function |
| 1974 |
// is more about replacing stale connections than detecting loops. |
| 1975 |
// We have code for the loop detection elsewhere, which also delays |
| 1976 |
// attempt to reconnect. |
| 1977 |
if !ol.isSolicitedLeafNode() && ol.leaf.remoteServer == srvName && |
| 1978 |
ol.leaf.remoteCluster == clusterName && ol.acc.Name == accName && |
| 1979 |
remoteAccName != _EMPTY_ && ol.leaf.remoteAccName == remoteAccName { |
| 1980 |
old = ol |
| 1981 |
} |
| 1982 |
ol.mu.Unlock() |
| 1983 |
if old != nil { |
| 1984 |
break |
| 1985 |
} |
| 1986 |
} |
| 1987 |
} |
| 1988 |
// Now that we are under the server lock and before adding it to the map, |
| 1989 |
// for a solicited leaf, we need to make sure that it has not been removed |
| 1990 |
// from the config or disabled. |
| 1991 |
if solicited { |
| 1992 |
// If no longer valid, do not add to the server map. The connection |
| 1993 |
// should have been marked so that it can't reconnect. When the caller |
| 1994 |
// calls closeConnection(), cleanup (including clearing the connect- |
| 1995 |
// in-progress flag) will occur at the appropriate time. |
| 1996 |
if !remote.stillValid() { |
| 1997 |
// Prevent reconnect in case it was not yet done. |
| 1998 |
c.setNoReconnect() |
| 1999 |
s.mu.Unlock() |
| 2000 |
s.removeFromTempClients(cid) |
| 2001 |
return false |
| 2002 |
} |
| 2003 |
remote.setConnectInProgress(false) |
| 2004 |
} |
| 2005 |
// Store new connection in the map |
| 2006 |
s.leafs[cid] = c |
| 2007 |
s.mu.Unlock() |
| 2008 |
s.removeFromTempClients(cid) |
| 2009 |
|
| 2010 |
// If applicable, evict the old one. |
| 2011 |
if old != nil { |
| 2012 |
old.sendErrAndErr(DuplicateRemoteLeafnodeConnection.String()) |
| 2013 |
old.closeConnection(DuplicateRemoteLeafnodeConnection) |
| 2014 |
c.Warnf("Replacing connection from same server") |
| 2015 |
} |
| 2016 |
|
| 2017 |
srvDecorated := func() string { |
| 2018 |
if myClustName == _EMPTY_ { |
| 2019 |
return mySrvName |
| 2020 |
} |
| 2021 |
return fmt.Sprintf("%s/%s", mySrvName, myClustName) |
| 2022 |
} |
| 2023 |
|
| 2024 |
opts := s.getOpts() |
| 2025 |
sysAcc := s.SystemAccount() |
| 2026 |
js := s.getJetStream() |
| 2027 |
var meta *raft |
| 2028 |
if js != nil { |
| 2029 |
if mg := js.getMetaGroup(); mg != nil { |
| 2030 |
meta = mg.(*raft) |
| 2031 |
} |
| 2032 |
} |
| 2033 |
blockMappingOutgoing := false |
| 2034 |
// Deny (non domain) JetStream API traffic unless system account is shared |
| 2035 |
// and domain names are identical and extending is not disabled |
| 2036 |
|
| 2037 |
// Check if backwards compatibility has been enabled and needs to be acted on |
| 2038 |
forceSysAccDeny := false |
| 2039 |
if len(opts.JsAccDefaultDomain) > 0 { |
| 2040 |
if acc == sysAcc { |
| 2041 |
for _, d := range opts.JsAccDefaultDomain { |
| 2042 |
if d == _EMPTY_ { |
| 2043 |
// Extending JetStream via leaf node is mutually exclusive with a domain mapping to the empty/default domain. |
| 2044 |
// As soon as one mapping to "" is found, disable the ability to extend JS via a leaf node. |
| 2045 |
c.Noticef("Not extending remote JetStream domain %q due to presence of empty default domain", myRemoteDomain) |
| 2046 |
forceSysAccDeny = true |
| 2047 |
break |
| 2048 |
} |
| 2049 |
} |
| 2050 |
} else if domain, ok := opts.JsAccDefaultDomain[accName]; ok && domain == _EMPTY_ { |
| 2051 |
// for backwards compatibility with old setups that do not have a domain name set |
| 2052 |
c.Debugf("Skipping deny %q for account %q due to default domain", jsAllAPI, accName) |
| 2053 |
return true |
| 2054 |
} |
| 2055 |
} |
| 2056 |
|
| 2057 |
// If the server has JS disabled, it may still be part of a JetStream that could be extended. |
| 2058 |
// This is either signaled by js being disabled and a domain set, |
| 2059 |
// or in cases where no domain name exists, an extension hint is set. |
| 2060 |
// However, this is only relevant in mixed setups. |
| 2061 |
// |
| 2062 |
// If the system account connects but default domains are present, JetStream can't be extended. |
| 2063 |
if opts.JetStreamDomain != myRemoteDomain || (!opts.JetStream && (opts.JetStreamDomain == _EMPTY_ && opts.JetStreamExtHint != jsWillExtend)) || |
| 2064 |
sysAcc == nil || acc == nil || forceSysAccDeny { |
| 2065 |
// If domain names mismatch always deny. This applies to system accounts as well as non system accounts. |
| 2066 |
// Not having a system account, account or JetStream disabled is considered a mismatch as well. |
| 2067 |
if acc != nil && acc == sysAcc { |
| 2068 |
c.Noticef("System account connected from %s", srvDecorated()) |
| 2069 |
c.Noticef("JetStream not extended, domains differ") |
| 2070 |
c.mergeDenyPermissionsLocked(both, denyAllJs) |
| 2071 |
// When a remote with a system account is present in a server, unless otherwise disabled, the server will be |
| 2072 |
// started in observer mode. Now that it is clear that this not used, turn the observer mode off. |
| 2073 |
if solicited && meta != nil && meta.IsObserver() { |
| 2074 |
meta.setObserver(false, extNotExtended) |
| 2075 |
c.Debugf("Turning JetStream metadata controller Observer Mode off") |
| 2076 |
// Take note that the domain was not extended to avoid this state from startup. |
| 2077 |
writePeerState(c.srv.diskIOSemaphore(), js.config.StoreDir, meta.currentPeerState()) |
| 2078 |
// Meta controller can't be leader yet. |
| 2079 |
// Yet it is possible that due to observer mode every server already stopped campaigning. |
| 2080 |
// Therefore this server needs to be kicked into campaigning gear explicitly. |
| 2081 |
meta.Campaign() |
| 2082 |
} |
| 2083 |
} else { |
| 2084 |
c.Noticef("JetStream using domains: local %q, remote %q", opts.JetStreamDomain, myRemoteDomain) |
| 2085 |
c.mergeDenyPermissionsLocked(both, denyAllClientJs) |
| 2086 |
} |
| 2087 |
blockMappingOutgoing = true |
| 2088 |
} else if acc == sysAcc { |
| 2089 |
// system account and same domain |
| 2090 |
s.sys.client.Noticef("Extending JetStream domain %q as System Account connected from server %s", |
| 2091 |
myRemoteDomain, srvDecorated()) |
| 2092 |
// In an extension use case, pin leadership to server remotes connect to. |
| 2093 |
// Therefore, server with a remote that are not already in observer mode, need to be put into it. |
| 2094 |
if solicited && meta != nil && !meta.IsObserver() { |
| 2095 |
c.Debugf("Turning JetStream metadata controller Observer Mode on - System Account Connected") |
| 2096 |
// Discard any local metagroup state accumulated before the SYS-account |
| 2097 |
// leaf came up (e.g. the wrong-hint case where this server bootstrapped |
| 2098 |
// its own metagroup). The parent's view is now authoritative; without |
| 2099 |
// this reset the two raft logs stay forked because the standalone log's |
| 2100 |
// commit prefix short-circuits the follower's AE handling. |
| 2101 |
meta.setObserver(true, extExtended) |
| 2102 |
meta.Reset() |
| 2103 |
} |
| 2104 |
} else { |
| 2105 |
// This deny is needed in all cases (system account shared or not) |
| 2106 |
// If the system account is shared, jsAllAPI traffic will go through the system account. |
| 2107 |
// So in order to prevent duplicate delivery (from system and actual account) suppress it on the account. |
| 2108 |
// If the system account is NOT shared, jsAllAPI traffic has no business |
| 2109 |
c.Debugf("Adding deny %+v for account %q", denyAllClientJs, accName) |
| 2110 |
c.mergeDenyPermissionsLocked(both, denyAllClientJs) |
| 2111 |
} |
| 2112 |
// If we have a specified JetStream domain we will want to add a mapping to |
| 2113 |
// allow access cross domain for each non-system account. |
| 2114 |
if opts.JetStreamDomain != _EMPTY_ && opts.JetStream && acc != nil && acc != sysAcc { |
| 2115 |
for src, dest := range generateJSMappingTable(opts.JetStreamDomain) { |
| 2116 |
if err := acc.AddMapping(src, dest); err != nil { |
| 2117 |
c.Debugf("Error adding JetStream domain mapping: %s", err.Error()) |
| 2118 |
} else { |
| 2119 |
c.Debugf("Adding JetStream Domain Mapping %q -> %s to account %q", src, dest, accName) |
| 2120 |
} |
| 2121 |
} |
| 2122 |
if blockMappingOutgoing { |
| 2123 |
src := fmt.Sprintf(jsDomainAPI, opts.JetStreamDomain) |
| 2124 |
// make sure that messages intended for this domain, do not leave the cluster via this leaf node connection |
| 2125 |
// This is a guard against a miss-config with two identical domain names and will only cover some forms |
| 2126 |
// of this issue, not all of them. |
| 2127 |
// This guards against a hub and a spoke having the same domain name. |
| 2128 |
// But not two spokes having the same one and the request coming from the hub. |
| 2129 |
c.mergeDenyPermissionsLocked(pub, []string{src}) |
| 2130 |
c.Debugf("Adding deny %q for outgoing messages to account %q", src, accName) |
| 2131 |
} |
| 2132 |
} |
| 2133 |
return true |
| 2134 |
} |
| 2135 |
|
| 2136 |
func (s *Server) removeLeafNodeConnection(c *client) { |
| 2137 |
s.mu.Lock() |
| 2138 |
c.mu.Lock() |
| 2139 |
cid := c.cid |
| 2140 |
if c.leaf != nil { |
| 2141 |
if c.leaf.tsubt != nil { |
| 2142 |
c.leaf.tsubt.Stop() |
| 2143 |
c.leaf.tsubt = nil |
| 2144 |
} |
| 2145 |
if c.leaf.gwSub != nil { |
| 2146 |
s.gwLeafSubs.Remove(c.leaf.gwSub) |
| 2147 |
// We need to set this to nil for GC to release the connection |
| 2148 |
c.leaf.gwSub = nil |
| 2149 |
} |
| 2150 |
if remote := c.leaf.remote; remote != nil { |
| 2151 |
// If "noReconnect" is true, then we won't attempt to reconnect, so |
| 2152 |
// we will clear the "connect-in-progress" flag. However, if we can |
| 2153 |
// reconnect, then we should set "connect-in-progress" to true while |
| 2154 |
// we are under the server/client lock. The go routine that performs |
| 2155 |
// the reconnect will be started later and there would be a gap with |
| 2156 |
// the wrong flag value otherwise. |
| 2157 |
remote.setConnectInProgress(!c.flags.isSet(noReconnect)) |
| 2158 |
} |
| 2159 |
} |
| 2160 |
proxyKey := c.proxyKey |
| 2161 |
c.mu.Unlock() |
| 2162 |
delete(s.leafs, cid) |
| 2163 |
if proxyKey != _EMPTY_ { |
| 2164 |
s.removeProxiedConn(proxyKey, cid) |
| 2165 |
} |
| 2166 |
s.mu.Unlock() |
| 2167 |
s.removeFromTempClients(cid) |
| 2168 |
} |
| 2169 |
|
| 2170 |
// Connect information for solicited leafnodes. |
| 2171 |
type leafConnectInfo struct { |
| 2172 |
Version string `json:"version,omitempty"` |
| 2173 |
Nkey string `json:"nkey,omitempty"` |
| 2174 |
JWT string `json:"jwt,omitempty"` |
| 2175 |
Sig string `json:"sig,omitempty"` |
| 2176 |
User string `json:"user,omitempty"` |
| 2177 |
Pass string `json:"pass,omitempty"` |
| 2178 |
Token string `json:"auth_token,omitempty"` |
| 2179 |
ID string `json:"server_id,omitempty"` |
| 2180 |
Domain string `json:"domain,omitempty"` |
| 2181 |
Name string `json:"name,omitempty"` |
| 2182 |
Hub bool `json:"is_hub,omitempty"` |
| 2183 |
Cluster string `json:"cluster,omitempty"` |
| 2184 |
Headers bool `json:"headers,omitempty"` |
| 2185 |
JetStream bool `json:"jetstream,omitempty"` |
| 2186 |
DenyPub []string `json:"deny_pub,omitempty"` |
| 2187 |
Isolate bool `json:"isolate,omitempty"` |
| 2188 |
|
| 2189 |
// There was an existing field called: |
| 2190 |
// >> Comp bool `json:"compression,omitempty"` |
| 2191 |
// that has never been used. With support for compression, we now need |
| 2192 |
// a field that is a string. So we use a different json tag: |
| 2193 |
Compression string `json:"compress_mode,omitempty"` |
| 2194 |
|
| 2195 |
// Just used to detect wrong connection attempts. |
| 2196 |
Gateway string `json:"gateway,omitempty"` |
| 2197 |
|
| 2198 |
// Tells the accept side which account the remote is binding to. |
| 2199 |
RemoteAccount string `json:"remote_account,omitempty"` |
| 2200 |
|
| 2201 |
// The accept side of a LEAF connection, unlike ROUTER and GATEWAY, receives |
| 2202 |
// only the CONNECT protocol, and no INFO. So we need to send the protocol |
| 2203 |
// version as part of the CONNECT. It will indicate if a connection supports |
| 2204 |
// some features, such as message tracing. |
| 2205 |
// We use `protocol` as the JSON tag, so this is automatically unmarshal'ed |
| 2206 |
// in the low level process CONNECT. |
| 2207 |
Proto int `json:"protocol,omitempty"` |
| 2208 |
} |
| 2209 |
|
| 2210 |
// processLeafNodeConnect will process the inbound connect args. |
| 2211 |
// Once we are here we are bound to an account, so can send any interest that |
| 2212 |
// we would have to the other side. |
| 2213 |
func (c *client) processLeafNodeConnect(s *Server, arg []byte, lang string) error { |
| 2214 |
// Way to detect clients that incorrectly connect to the route listen |
| 2215 |
// port. Client provided "lang" in the CONNECT protocol while LEAFNODEs don't. |
| 2216 |
if lang != _EMPTY_ { |
| 2217 |
c.sendErrAndErr(ErrClientConnectedToLeafNodePort.Error()) |
| 2218 |
c.closeConnection(WrongPort) |
| 2219 |
return ErrClientConnectedToLeafNodePort |
| 2220 |
} |
| 2221 |
|
| 2222 |
// Unmarshal as a leaf node connect protocol |
| 2223 |
proto := &leafConnectInfo{} |
| 2224 |
if err := json.Unmarshal(arg, proto); err != nil { |
| 2225 |
return err |
| 2226 |
} |
| 2227 |
|
| 2228 |
// Reject a cluster that contains spaces. |
| 2229 |
if proto.Cluster != _EMPTY_ && strings.Contains(proto.Cluster, " ") { |
| 2230 |
c.sendErrAndErr(ErrClusterNameHasSpaces.Error()) |
| 2231 |
c.closeConnection(ProtocolViolation) |
| 2232 |
return ErrClusterNameHasSpaces |
| 2233 |
} |
| 2234 |
|
| 2235 |
// Check for cluster name collisions. |
| 2236 |
if cn := s.cachedClusterName(); cn != _EMPTY_ && proto.Cluster != _EMPTY_ && proto.Cluster == cn { |
| 2237 |
c.sendErrAndErr(ErrLeafNodeHasSameClusterName.Error()) |
| 2238 |
c.closeConnection(ClusterNamesIdentical) |
| 2239 |
return ErrLeafNodeHasSameClusterName |
| 2240 |
} |
| 2241 |
|
| 2242 |
// Reject if this has Gateway which means that it would be from a gateway |
| 2243 |
// connection that incorrectly connects to the leafnode port. |
| 2244 |
if proto.Gateway != _EMPTY_ { |
| 2245 |
errTxt := fmt.Sprintf("Rejecting connection from gateway %q on the leafnode port", proto.Gateway) |
| 2246 |
c.Errorf(errTxt) |
| 2247 |
c.sendErr(errTxt) |
| 2248 |
c.closeConnection(WrongGateway) |
| 2249 |
return ErrWrongGateway |
| 2250 |
} |
| 2251 |
|
| 2252 |
if mv := s.getOpts().LeafNode.MinVersion; mv != _EMPTY_ { |
| 2253 |
major, minor, update, _ := versionComponents(mv) |
| 2254 |
if !versionAtLeast(proto.Version, major, minor, update) { |
| 2255 |
// Send back an INFO so recent remote servers process the rejection |
| 2256 |
// cleanly, then close immediately. The soliciting side applies the |
| 2257 |
// reconnect delay when it processes the error. |
| 2258 |
s.sendPermsAndAccountInfo(c) |
| 2259 |
c.sendErrAndErr(fmt.Sprintf("%s %q", ErrLeafNodeMinVersionRejected, mv)) |
| 2260 |
c.closeConnection(MinimumVersionRequired) |
| 2261 |
return ErrMinimumVersionRequired |
| 2262 |
} |
| 2263 |
} |
| 2264 |
|
| 2265 |
// Check if this server supports headers. |
| 2266 |
supportHeaders := c.srv.supportsHeaders() |
| 2267 |
|
| 2268 |
c.mu.Lock() |
| 2269 |
// Leaf Nodes do not do echo or verbose or pedantic. |
| 2270 |
c.opts.Verbose = false |
| 2271 |
c.opts.Echo = false |
| 2272 |
c.opts.Pedantic = false |
| 2273 |
// This inbound connection will be marked as supporting headers if this server |
| 2274 |
// support headers and the remote has sent in the CONNECT protocol that it does |
| 2275 |
// support headers too. |
| 2276 |
c.headers = supportHeaders && proto.Headers |
| 2277 |
// If the compression level is still not set, set it based on what has been |
| 2278 |
// given to us in the CONNECT protocol. |
| 2279 |
if c.leaf.compression == _EMPTY_ { |
| 2280 |
// But if proto.Compression is _EMPTY_, set it to CompressionNotSupported |
| 2281 |
if proto.Compression == _EMPTY_ { |
| 2282 |
c.leaf.compression = CompressionNotSupported |
| 2283 |
} else { |
| 2284 |
c.leaf.compression = proto.Compression |
| 2285 |
} |
| 2286 |
} |
| 2287 |
|
| 2288 |
// Remember the remote server. |
| 2289 |
c.leaf.remoteServer = proto.Name |
| 2290 |
// Remember the remote account name |
| 2291 |
c.leaf.remoteAccName = proto.RemoteAccount |
| 2292 |
// Remember if the leafnode requested isolation. |
| 2293 |
c.leaf.isolated = c.leaf.isolated || proto.Isolate |
| 2294 |
|
| 2295 |
// If the other side has declared itself a hub, so we will take on the spoke role. |
| 2296 |
if proto.Hub { |
| 2297 |
c.leaf.isSpoke = true |
| 2298 |
} |
| 2299 |
|
| 2300 |
// The soliciting side is part of a cluster. |
| 2301 |
if proto.Cluster != _EMPTY_ { |
| 2302 |
c.leaf.remoteCluster = proto.Cluster |
| 2303 |
} |
| 2304 |
|
| 2305 |
c.leaf.remoteDomain = proto.Domain |
| 2306 |
|
| 2307 |
// When a leaf solicits a connection to a hub, the perms that it will use on the soliciting leafnode's |
| 2308 |
// behalf are correct for them, but inside the hub need to be reversed since data is flowing in the opposite direction. |
| 2309 |
if !c.isSolicitedLeafNode() && c.perms != nil { |
| 2310 |
sp, pp := c.perms.sub, c.perms.pub |
| 2311 |
c.perms.sub, c.perms.pub = pp, sp |
| 2312 |
// setPermissions populated darray from the subscribe permissions, |
| 2313 |
// which are the import permissions advertised to the spoke. Keep |
| 2314 |
// those parsed denies after reversing the live permission directions. |
| 2315 |
if c.opts.Import == nil { |
| 2316 |
c.darray = nil |
| 2317 |
} |
| 2318 |
} |
| 2319 |
|
| 2320 |
// Set the Ping timer |
| 2321 |
c.setFirstPingTimer() |
| 2322 |
|
| 2323 |
// If we received pub deny permissions from the other end, merge with existing ones. |
| 2324 |
c.mergeDenyPermissions(pub, proto.DenyPub) |
| 2325 |
|
| 2326 |
acc := c.acc |
| 2327 |
c.mu.Unlock() |
| 2328 |
|
| 2329 |
// If the account is not set (e.g. connection was closed due to auth |
| 2330 |
// timeout while still being processed), bail out to avoid a panic. |
| 2331 |
if acc == nil { |
| 2332 |
c.closeConnection(MissingAccount) |
| 2333 |
return ErrMissingAccount |
| 2334 |
} |
| 2335 |
|
| 2336 |
// Register the cluster, even if empty, as long as we are acting as a hub. |
| 2337 |
if !proto.Hub { |
| 2338 |
acc.registerLeafNodeCluster(proto.Cluster) |
| 2339 |
} |
| 2340 |
|
| 2341 |
// Add in the leafnode here since we passed through auth at this point. |
| 2342 |
s.addLeafNodeConnection(c, proto.Name, proto.Cluster, true) |
| 2343 |
|
| 2344 |
// If we have permissions bound to this leafnode we need to send then back to the |
| 2345 |
// origin server for local enforcement. |
| 2346 |
s.sendPermsAndAccountInfo(c) |
| 2347 |
|
| 2348 |
// Create and initialize the smap since we know our bound account now. |
| 2349 |
// This will send all registered subs too. |
| 2350 |
s.initLeafNodeSmapAndSendSubs(c) |
| 2351 |
|
| 2352 |
// Announce the account connect event for a leaf node. |
| 2353 |
// This will be a no-op as needed. |
| 2354 |
s.sendLeafNodeConnect(c.acc) |
| 2355 |
|
| 2356 |
// Check to see if we need to kick any internal source or mirror consumers. |
| 2357 |
// This will be a no-op if JetStream not enabled for this server or if the bound account |
| 2358 |
// does not have jetstream. |
| 2359 |
s.checkInternalSyncConsumers(acc) |
| 2360 |
|
| 2361 |
return nil |
| 2362 |
} |
| 2363 |
|
| 2364 |
// checkInternalSyncConsumers |
| 2365 |
func (s *Server) checkInternalSyncConsumers(acc *Account) { |
| 2366 |
// Grab our js |
| 2367 |
js := s.getJetStream() |
| 2368 |
|
| 2369 |
// Only applicable if we have JS and the leafnode has JS as well. |
| 2370 |
// We check for remote JS outside. |
| 2371 |
if !js.isEnabled() || acc == nil { |
| 2372 |
return |
| 2373 |
} |
| 2374 |
|
| 2375 |
// We will check all streams in our local account. They must be a leader and |
| 2376 |
// be sourcing or mirroring. We will check the external config on the stream itself |
| 2377 |
// if this is cross domain, or if the remote domain is empty, meaning we might be |
| 2378 |
// extending the system across this leafnode connection and hence we would be extending |
| 2379 |
// our own domain. |
| 2380 |
jsa := js.lookupAccount(acc) |
| 2381 |
if jsa == nil { |
| 2382 |
return |
| 2383 |
} |
| 2384 |
|
| 2385 |
var streams []*stream |
| 2386 |
jsa.mu.RLock() |
| 2387 |
for _, mset := range jsa.streams { |
| 2388 |
mset.cfgMu.RLock() |
| 2389 |
// We need to have a mirror or source defined. |
| 2390 |
// We do not want to force another lock here to look for leader status, |
| 2391 |
// so collect and after we release jsa will make sure. |
| 2392 |
if mset.cfg.Mirror != nil || len(mset.cfg.Sources) > 0 { |
| 2393 |
streams = append(streams, mset) |
| 2394 |
} |
| 2395 |
mset.cfgMu.RUnlock() |
| 2396 |
} |
| 2397 |
jsa.mu.RUnlock() |
| 2398 |
|
| 2399 |
// Now loop through all candidates and check if we are the leader and have NOT |
| 2400 |
// created the sync up consumer. |
| 2401 |
for _, mset := range streams { |
| 2402 |
mset.retryDisconnectedSyncConsumers() |
| 2403 |
} |
| 2404 |
} |
| 2405 |
|
| 2406 |
// Returns the remote cluster name. This is set only once so does not require a lock. |
| 2407 |
func (c *client) remoteCluster() string { |
| 2408 |
if c.leaf == nil { |
| 2409 |
return _EMPTY_ |
| 2410 |
} |
| 2411 |
return c.leaf.remoteCluster |
| 2412 |
} |
| 2413 |
|
| 2414 |
// Sends back an info block to the soliciting leafnode to let it know about |
| 2415 |
// its permission settings for local enforcement. |
| 2416 |
func (s *Server) sendPermsAndAccountInfo(c *client) { |
| 2417 |
// Copy |
| 2418 |
s.mu.Lock() |
| 2419 |
info := s.copyLeafNodeInfo() |
| 2420 |
s.mu.Unlock() |
| 2421 |
c.mu.Lock() |
| 2422 |
info.CID = c.cid |
| 2423 |
info.Import = c.opts.Import |
| 2424 |
info.Export = c.opts.Export |
| 2425 |
info.RemoteAccount = c.acc.Name |
| 2426 |
// s.SystemAccount() uses an atomic operation and does not get the server lock, so this is safe. |
| 2427 |
info.IsSystemAccount = c.acc == s.SystemAccount() |
| 2428 |
info.ConnectInfo = true |
| 2429 |
c.enqueueProto(generateInfoJSON(info)) |
| 2430 |
c.mu.Unlock() |
| 2431 |
} |
| 2432 |
|
| 2433 |
// Snapshot the current subscriptions from the sublist into our smap which |
| 2434 |
// we will keep updated from now on. |
| 2435 |
// Also send the registered subscriptions. |
| 2436 |
func (s *Server) initLeafNodeSmapAndSendSubs(c *client) { |
| 2437 |
acc := c.acc |
| 2438 |
if acc == nil { |
| 2439 |
c.Debugf("Leafnode does not have an account bound") |
| 2440 |
return |
| 2441 |
} |
| 2442 |
// Collect all account subs here. |
| 2443 |
_subs := [1024]*subscription{} |
| 2444 |
subs := _subs[:0] |
| 2445 |
ims := []string{} |
| 2446 |
|
| 2447 |
// Hold the client lock otherwise there can be a race and miss some subs. |
| 2448 |
c.mu.Lock() |
| 2449 |
defer c.mu.Unlock() |
| 2450 |
|
| 2451 |
acc.mu.RLock() |
| 2452 |
accName := acc.Name |
| 2453 |
accNTag := acc.nameTag |
| 2454 |
|
| 2455 |
// To make printing look better when no friendly name present. |
| 2456 |
if accNTag != _EMPTY_ { |
| 2457 |
accNTag = "/" + accNTag |
| 2458 |
} |
| 2459 |
|
| 2460 |
// If we are solicited we only send interest for local clients. |
| 2461 |
if c.isSpokeLeafNode() { |
| 2462 |
acc.sl.localSubs(&subs, true) |
| 2463 |
} else { |
| 2464 |
acc.sl.All(&subs) |
| 2465 |
} |
| 2466 |
|
| 2467 |
// Check if we have an existing service import reply. |
| 2468 |
siReply := copyBytes(acc.siReply) |
| 2469 |
|
| 2470 |
// Since leaf nodes only send on interest, if the bound |
| 2471 |
// account has import services we need to send those over. |
| 2472 |
for isubj := range acc.imports.services { |
| 2473 |
if c.isSpokeLeafNode() && !c.canSubscribe(isubj) { |
| 2474 |
c.Debugf("Not permitted to import service %q on behalf of %s%s", isubj, accName, accNTag) |
| 2475 |
continue |
| 2476 |
} |
| 2477 |
ims = append(ims, isubj) |
| 2478 |
} |
| 2479 |
// Likewise for mappings. |
| 2480 |
for _, m := range acc.mappings { |
| 2481 |
if c.isSpokeLeafNode() && !c.canSubscribe(m.src) { |
| 2482 |
c.Debugf("Not permitted to import mapping %q on behalf of %s%s", m.src, accName, accNTag) |
| 2483 |
continue |
| 2484 |
} |
| 2485 |
ims = append(ims, m.src) |
| 2486 |
} |
| 2487 |
|
| 2488 |
// Create a unique subject that will be used for loop detection. |
| 2489 |
lds := acc.lds |
| 2490 |
acc.mu.RUnlock() |
| 2491 |
|
| 2492 |
// Check if we have to create the LDS. |
| 2493 |
if lds == _EMPTY_ { |
| 2494 |
lds = leafNodeLoopDetectionSubjectPrefix + nuid.Next() |
| 2495 |
acc.mu.Lock() |
| 2496 |
acc.lds = lds |
| 2497 |
acc.mu.Unlock() |
| 2498 |
} |
| 2499 |
|
| 2500 |
// Now check for gateway interest. Leafnodes will put this into |
| 2501 |
// the proper mode to propagate, but they are not held in the account. |
| 2502 |
gwsa := [16]*client{} |
| 2503 |
gws := gwsa[:0] |
| 2504 |
s.getOutboundGatewayConnections(&gws) |
| 2505 |
for _, cgw := range gws { |
| 2506 |
cgw.mu.Lock() |
| 2507 |
gw := cgw.gw |
| 2508 |
cgw.mu.Unlock() |
| 2509 |
if gw != nil { |
| 2510 |
if ei, _ := gw.outsim.Load(accName); ei != nil { |
| 2511 |
if e := ei.(*outsie); e != nil && e.sl != nil { |
| 2512 |
e.sl.All(&subs) |
| 2513 |
} |
| 2514 |
} |
| 2515 |
} |
| 2516 |
} |
| 2517 |
|
| 2518 |
applyGlobalRouting := s.gateway.enabled |
| 2519 |
if c.isSpokeLeafNode() { |
| 2520 |
// Add a fake subscription for this solicited leafnode connection |
| 2521 |
// so that we can send back directly for mapped GW replies. |
| 2522 |
// We need to keep track of this subscription so it can be removed |
| 2523 |
// when the connection is closed so that the GC can release it. |
| 2524 |
c.leaf.gwSub = &subscription{client: c, subject: []byte(gwReplyPrefix + ">")} |
| 2525 |
c.srv.gwLeafSubs.Insert(c.leaf.gwSub) |
| 2526 |
} |
| 2527 |
|
| 2528 |
// Now walk the results and add them to our smap |
| 2529 |
rc := c.leaf.remoteCluster |
| 2530 |
c.leaf.smap = make(map[string]int32) |
| 2531 |
for _, sub := range subs { |
| 2532 |
// Check perms regardless of role. |
| 2533 |
if c.perms != nil && !c.canSubscribe(string(sub.subject)) { |
| 2534 |
c.Debugf("Not permitted to subscribe to %q on behalf of %s%s", sub.subject, accName, accNTag) |
| 2535 |
continue |
| 2536 |
} |
| 2537 |
// Don't advertise interest from leafnodes to other isolated leafnodes. |
| 2538 |
if sub.client.kind == LEAF && c.isIsolatedLeafNode() { |
| 2539 |
continue |
| 2540 |
} |
| 2541 |
// We ignore ourselves here. |
| 2542 |
// Also don't add the subscription if it has a origin cluster and the |
| 2543 |
// cluster name matches the one of the client we are sending to. |
| 2544 |
if c != sub.client && (sub.origin == nil || (bytesToString(sub.origin) != rc)) { |
| 2545 |
count := int32(1) |
| 2546 |
if len(sub.queue) > 0 && sub.qw > 0 { |
| 2547 |
count = sub.qw |
| 2548 |
} |
| 2549 |
c.leaf.smap[keyFromSub(sub)] += count |
| 2550 |
if c.leaf.tsub == nil { |
| 2551 |
c.leaf.tsub = make(map[*subscription]struct{}) |
| 2552 |
} |
| 2553 |
c.leaf.tsub[sub] = struct{}{} |
| 2554 |
} |
| 2555 |
} |
| 2556 |
// FIXME(dlc) - We need to update appropriately on an account claims update. |
| 2557 |
for _, isubj := range ims { |
| 2558 |
c.leaf.smap[isubj]++ |
| 2559 |
} |
| 2560 |
// If we have gateways enabled we need to make sure the other side sends us responses |
| 2561 |
// that have been augmented from the original subscription. |
| 2562 |
// TODO(dlc) - Should we lock this down more? |
| 2563 |
if applyGlobalRouting { |
| 2564 |
c.leaf.smap[oldGWReplyPrefix+"*.>"]++ |
| 2565 |
c.leaf.smap[gwReplyPrefix+">"]++ |
| 2566 |
} |
| 2567 |
// Detect loops by subscribing to a specific subject and checking |
| 2568 |
// if this sub is coming back to us. |
| 2569 |
c.leaf.smap[lds]++ |
| 2570 |
|
| 2571 |
// Check if we need to add an existing siReply to our map. |
| 2572 |
// This will be a prefix so add on the wildcard. |
| 2573 |
if siReply != nil { |
| 2574 |
wcsub := append(siReply, '>') |
| 2575 |
c.leaf.smap[string(wcsub)]++ |
| 2576 |
} |
| 2577 |
// Queue all protocols. There is no max pending limit for LN connection, |
| 2578 |
// so we don't need chunking. The writes will happen from the writeLoop. |
| 2579 |
var b bytes.Buffer |
| 2580 |
for key, n := range c.leaf.smap { |
| 2581 |
c.writeLeafSub(&b, key, n) |
| 2582 |
} |
| 2583 |
if b.Len() > 0 { |
| 2584 |
c.enqueueProto(b.Bytes()) |
| 2585 |
} |
| 2586 |
if c.leaf.tsub != nil { |
| 2587 |
// Clear the tsub map after 5 seconds. |
| 2588 |
c.leaf.tsubt = time.AfterFunc(5*time.Second, func() { |
| 2589 |
c.mu.Lock() |
| 2590 |
if c.leaf != nil { |
| 2591 |
c.leaf.tsub = nil |
| 2592 |
c.leaf.tsubt = nil |
| 2593 |
} |
| 2594 |
c.mu.Unlock() |
| 2595 |
}) |
| 2596 |
} |
| 2597 |
} |
| 2598 |
|
| 2599 |
// updateInterestForAccountOnGateway called from gateway code when processing RS+ and RS-. |
| 2600 |
func (s *Server) updateInterestForAccountOnGateway(accName string, sub *subscription, delta int32) { |
| 2601 |
// Since we're in the gateway's readLoop, and we would otherwise block, don't allow fetching. |
| 2602 |
acc, err := s.lookupOrFetchAccount(accName, false) |
| 2603 |
if acc == nil || err != nil { |
| 2604 |
s.Debugf("No or bad account for %q, failed to update interest from gateway", accName) |
| 2605 |
return |
| 2606 |
} |
| 2607 |
acc.updateLeafNodes(sub, delta) |
| 2608 |
} |
| 2609 |
|
| 2610 |
// updateLeafNodesEx will make sure to update the account smap for the subscription. |
| 2611 |
// Will also forward to all leaf nodes as needed. |
| 2612 |
// If `hubOnly` is true, then will update only leaf nodes that connect to this server |
| 2613 |
// (that is, for which this server acts as a hub to them). |
| 2614 |
func (acc *Account) updateLeafNodesEx(sub *subscription, delta int32, hubOnly bool) { |
| 2615 |
if acc == nil || sub == nil { |
| 2616 |
return |
| 2617 |
} |
| 2618 |
|
| 2619 |
// We will do checks for no leafnodes and same cluster here inline and under the |
| 2620 |
// general account read lock. |
| 2621 |
// If we feel we need to update the leafnodes we will do that out of line to avoid |
| 2622 |
// blocking routes or GWs. |
| 2623 |
|
| 2624 |
acc.mu.RLock() |
| 2625 |
// First check if we even have leafnodes here. |
| 2626 |
if acc.nleafs == 0 { |
| 2627 |
acc.mu.RUnlock() |
| 2628 |
return |
| 2629 |
} |
| 2630 |
|
| 2631 |
// Is this a loop detection subject. |
| 2632 |
isLDS := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix)) |
| 2633 |
|
| 2634 |
// Capture the cluster even if its empty. |
| 2635 |
var cluster string |
| 2636 |
if sub.origin != nil { |
| 2637 |
cluster = bytesToString(sub.origin) |
| 2638 |
} |
| 2639 |
|
| 2640 |
// If we have an isolated cluster we can return early, as long as it is not a loop detection subject. |
| 2641 |
// Empty clusters will return false for the check. |
| 2642 |
if !isLDS && acc.isLeafNodeClusterIsolated(cluster) { |
| 2643 |
acc.mu.RUnlock() |
| 2644 |
return |
| 2645 |
} |
| 2646 |
|
| 2647 |
// We can release the general account lock. |
| 2648 |
acc.mu.RUnlock() |
| 2649 |
|
| 2650 |
// We can hold the list lock here to avoid having to copy a large slice. |
| 2651 |
acc.lmu.RLock() |
| 2652 |
defer acc.lmu.RUnlock() |
| 2653 |
|
| 2654 |
// Do this once. |
| 2655 |
subject := string(sub.subject) |
| 2656 |
|
| 2657 |
// Walk the connected leafnodes from a random starting point to avoid |
| 2658 |
// concurrent callers all contending over leafs in the same order. |
| 2659 |
nleafs := len(acc.lleafs) |
| 2660 |
start := 0 |
| 2661 |
if nleafs > 1 { |
| 2662 |
start = rand.Intn(nleafs) |
| 2663 |
} |
| 2664 |
for i := 0; i < nleafs; i++ { |
| 2665 |
ln := acc.lleafs[(start+i)%nleafs] |
| 2666 |
if ln == sub.client { |
| 2667 |
continue |
| 2668 |
} |
| 2669 |
ln.mu.RLock() |
| 2670 |
// Don't advertise interest from leafnodes to other isolated leafnodes. |
| 2671 |
if sub.client.kind == LEAF && ln.isIsolatedLeafNode() { |
| 2672 |
ln.mu.RUnlock() |
| 2673 |
continue |
| 2674 |
} |
| 2675 |
// If `hubOnly` is true, it means that we want to update only leafnodes |
| 2676 |
// that connect to this server (so isHubLeafNode() would return `true`). |
| 2677 |
if hubOnly && !ln.isHubLeafNode() { |
| 2678 |
ln.mu.RUnlock() |
| 2679 |
continue |
| 2680 |
} |
| 2681 |
// Check to make sure this sub does not have an origin cluster that matches the leafnode. |
| 2682 |
// If skipped, make sure that we still let go the "$LDS." subscription that allows |
| 2683 |
// the detection of loops as long as different cluster. |
| 2684 |
clusterDifferent := cluster != ln.remoteCluster() |
| 2685 |
update := (isLDS && clusterDifferent) || |
| 2686 |
((cluster == _EMPTY_ || clusterDifferent) && (delta <= 0 || ln.canSubscribeInternal(subject))) |
| 2687 |
ln.mu.RUnlock() |
| 2688 |
if update { |
| 2689 |
ln.mu.Lock() |
| 2690 |
// The leaf role, isolation mode, and remote cluster are stable |
| 2691 |
// for the connection. Recheck canSubscribe here since permissions |
| 2692 |
// can change, and to initializes mperms for wildcard subscriptions |
| 2693 |
// that collide with deny rules. |
| 2694 |
if isLDS || delta <= 0 || ln.canSubscribe(subject) { |
| 2695 |
ln.updateSmap(sub, delta, isLDS) |
| 2696 |
} |
| 2697 |
ln.mu.Unlock() |
| 2698 |
} |
| 2699 |
} |
| 2700 |
} |
| 2701 |
|
| 2702 |
// updateLeafNodes will make sure to update the account smap for the subscription. |
| 2703 |
// Will also forward to all leaf nodes as needed. |
| 2704 |
func (acc *Account) updateLeafNodes(sub *subscription, delta int32) { |
| 2705 |
acc.updateLeafNodesEx(sub, delta, false) |
| 2706 |
} |
| 2707 |
|
| 2708 |
// This will make an update to our internal smap and determine if we should send out |
| 2709 |
// an interest update to the remote side. |
| 2710 |
// Lock should be held. |
| 2711 |
func (c *client) updateSmap(sub *subscription, delta int32, isLDS bool) { |
| 2712 |
if c.leaf.smap == nil { |
| 2713 |
return |
| 2714 |
} |
| 2715 |
|
| 2716 |
// If we are solicited make sure this is a local client or a non-solicited leaf node |
| 2717 |
skind := sub.client.kind |
| 2718 |
updateClient := skind == CLIENT || skind == SYSTEM || skind == JETSTREAM || skind == ACCOUNT |
| 2719 |
if !isLDS && c.isSpokeLeafNode() && !(updateClient || (skind == LEAF && !sub.client.isSpokeLeafNode())) { |
| 2720 |
return |
| 2721 |
} |
| 2722 |
|
| 2723 |
// For additions, check if that sub has just been processed during initLeafNodeSmapAndSendSubs |
| 2724 |
if delta > 0 && c.leaf.tsub != nil { |
| 2725 |
if _, present := c.leaf.tsub[sub]; present { |
| 2726 |
delete(c.leaf.tsub, sub) |
| 2727 |
if len(c.leaf.tsub) == 0 { |
| 2728 |
c.leaf.tsub = nil |
| 2729 |
c.leaf.tsubt.Stop() |
| 2730 |
c.leaf.tsubt = nil |
| 2731 |
} |
| 2732 |
return |
| 2733 |
} |
| 2734 |
} |
| 2735 |
|
| 2736 |
key := keyFromSub(sub) |
| 2737 |
n, ok := c.leaf.smap[key] |
| 2738 |
if delta < 0 && !ok { |
| 2739 |
return |
| 2740 |
} |
| 2741 |
|
| 2742 |
// We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0. |
| 2743 |
update := sub.queue != nil || (n <= 0 && n+delta > 0) || (n > 0 && n+delta <= 0) |
| 2744 |
n += delta |
| 2745 |
if n > 0 { |
| 2746 |
c.leaf.smap[key] = n |
| 2747 |
} else { |
| 2748 |
delete(c.leaf.smap, key) |
| 2749 |
} |
| 2750 |
if update { |
| 2751 |
c.sendLeafNodeSubUpdate(key, n) |
| 2752 |
} |
| 2753 |
} |
| 2754 |
|
| 2755 |
// Used to force add subjects to the subject map. |
| 2756 |
func (c *client) forceAddToSmap(subj string) { |
| 2757 |
c.mu.Lock() |
| 2758 |
defer c.mu.Unlock() |
| 2759 |
|
| 2760 |
if c.leaf.smap == nil { |
| 2761 |
return |
| 2762 |
} |
| 2763 |
n := c.leaf.smap[subj] |
| 2764 |
if n != 0 { |
| 2765 |
return |
| 2766 |
} |
| 2767 |
// Place into the map since it was not there. |
| 2768 |
c.leaf.smap[subj] = 1 |
| 2769 |
c.sendLeafNodeSubUpdate(subj, 1) |
| 2770 |
} |
| 2771 |
|
| 2772 |
// Used to force remove a subject from the subject map. |
| 2773 |
func (c *client) forceRemoveFromSmap(subj string) { |
| 2774 |
c.mu.Lock() |
| 2775 |
defer c.mu.Unlock() |
| 2776 |
|
| 2777 |
if c.leaf.smap == nil { |
| 2778 |
return |
| 2779 |
} |
| 2780 |
n := c.leaf.smap[subj] |
| 2781 |
if n == 0 { |
| 2782 |
return |
| 2783 |
} |
| 2784 |
n-- |
| 2785 |
if n == 0 { |
| 2786 |
// Remove is now zero |
| 2787 |
delete(c.leaf.smap, subj) |
| 2788 |
c.sendLeafNodeSubUpdate(subj, 0) |
| 2789 |
} else { |
| 2790 |
c.leaf.smap[subj] = n |
| 2791 |
} |
| 2792 |
} |
| 2793 |
|
| 2794 |
// Send the subscription interest change to the other side. |
| 2795 |
// Lock should be held. |
| 2796 |
func (c *client) sendLeafNodeSubUpdate(key string, n int32) { |
| 2797 |
// If we are a spoke, we need to check if we are allowed to send this subscription over to the hub. |
| 2798 |
if c.isSpokeLeafNode() { |
| 2799 |
checkPerms := true |
| 2800 |
if len(key) > 0 && (key[0] == '$' || key[0] == '_') { |
| 2801 |
if strings.HasPrefix(key, leafNodeLoopDetectionSubjectPrefix) || |
| 2802 |
strings.HasPrefix(key, oldGWReplyPrefix) || |
| 2803 |
strings.HasPrefix(key, gwReplyPrefix) { |
| 2804 |
checkPerms = false |
| 2805 |
} |
| 2806 |
} |
| 2807 |
if checkPerms { |
| 2808 |
var subject string |
| 2809 |
if sep := strings.IndexByte(key, ' '); sep != -1 { |
| 2810 |
subject = key[:sep] |
| 2811 |
} else { |
| 2812 |
subject = key |
| 2813 |
} |
| 2814 |
if !c.canSubscribe(subject) { |
| 2815 |
return |
| 2816 |
} |
| 2817 |
} |
| 2818 |
} |
| 2819 |
// If we are here we can send over to the other side. |
| 2820 |
_b := [64]byte{} |
| 2821 |
b := bytes.NewBuffer(_b[:0]) |
| 2822 |
c.writeLeafSub(b, key, n) |
| 2823 |
c.enqueueProto(b.Bytes()) |
| 2824 |
} |
| 2825 |
|
| 2826 |
// Helper function to build the key. |
| 2827 |
func keyFromSub(sub *subscription) string { |
| 2828 |
var sb strings.Builder |
| 2829 |
sb.Grow(len(sub.subject) + len(sub.queue) + 1) |
| 2830 |
sb.Write(sub.subject) |
| 2831 |
if sub.queue != nil { |
| 2832 |
// Just make the key subject spc group, e.g. 'foo bar' |
| 2833 |
sb.WriteByte(' ') |
| 2834 |
sb.Write(sub.queue) |
| 2835 |
} |
| 2836 |
return sb.String() |
| 2837 |
} |
| 2838 |
|
| 2839 |
const ( |
| 2840 |
keyRoutedSub = "R" |
| 2841 |
keyRoutedSubByte = 'R' |
| 2842 |
keyRoutedLeafSub = "L" |
| 2843 |
keyRoutedLeafSubByte = 'L' |
| 2844 |
) |
| 2845 |
|
| 2846 |
// Helper function to build the key that prevents collisions between normal |
| 2847 |
// routed subscriptions and routed subscriptions on behalf of a leafnode. |
| 2848 |
// Keys will look like this: |
| 2849 |
// "R foo" -> plain routed sub on "foo" |
| 2850 |
// "R foo bar" -> queue routed sub on "foo", queue "bar" |
| 2851 |
// "L foo bar" -> plain routed leaf sub on "foo", leaf "bar" |
| 2852 |
// "L foo bar baz" -> queue routed sub on "foo", queue "bar", leaf "baz" |
| 2853 |
func keyFromSubWithOrigin(sub *subscription) string { |
| 2854 |
var sb strings.Builder |
| 2855 |
sb.Grow(2 + len(sub.origin) + 1 + len(sub.subject) + 1 + len(sub.queue)) |
| 2856 |
leaf := len(sub.origin) > 0 |
| 2857 |
if leaf { |
| 2858 |
sb.WriteByte(keyRoutedLeafSubByte) |
| 2859 |
} else { |
| 2860 |
sb.WriteByte(keyRoutedSubByte) |
| 2861 |
} |
| 2862 |
sb.WriteByte(' ') |
| 2863 |
sb.Write(sub.subject) |
| 2864 |
if sub.queue != nil { |
| 2865 |
sb.WriteByte(' ') |
| 2866 |
sb.Write(sub.queue) |
| 2867 |
} |
| 2868 |
if leaf { |
| 2869 |
sb.WriteByte(' ') |
| 2870 |
sb.Write(sub.origin) |
| 2871 |
} |
| 2872 |
return sb.String() |
| 2873 |
} |
| 2874 |
|
| 2875 |
// Lock should be held. |
| 2876 |
func (c *client) writeLeafSub(w *bytes.Buffer, key string, n int32) { |
| 2877 |
if key == _EMPTY_ { |
| 2878 |
return |
| 2879 |
} |
| 2880 |
if n > 0 { |
| 2881 |
w.WriteString("LS+ " + key) |
| 2882 |
// Check for queue semantics, if found write n. |
| 2883 |
if strings.Contains(key, " ") { |
| 2884 |
w.WriteString(" ") |
| 2885 |
var b [12]byte |
| 2886 |
var i = len(b) |
| 2887 |
for l := n; l > 0; l /= 10 { |
| 2888 |
i-- |
| 2889 |
b[i] = digits[l%10] |
| 2890 |
} |
| 2891 |
w.Write(b[i:]) |
| 2892 |
if c.trace { |
| 2893 |
arg := fmt.Sprintf("%s %d", key, n) |
| 2894 |
c.traceOutOp("LS+", []byte(arg)) |
| 2895 |
} |
| 2896 |
} else if c.trace { |
| 2897 |
c.traceOutOp("LS+", []byte(key)) |
| 2898 |
} |
| 2899 |
} else { |
| 2900 |
w.WriteString("LS- " + key) |
| 2901 |
if c.trace { |
| 2902 |
c.traceOutOp("LS-", []byte(key)) |
| 2903 |
} |
| 2904 |
} |
| 2905 |
w.WriteString(CR_LF) |
| 2906 |
} |
| 2907 |
|
| 2908 |
// processLeafSub will process an inbound sub request for the remote leaf node. |
| 2909 |
func (c *client) processLeafSub(argo []byte) (err error) { |
| 2910 |
// Indicate activity. |
| 2911 |
c.in.subs++ |
| 2912 |
|
| 2913 |
srv := c.srv |
| 2914 |
if srv == nil { |
| 2915 |
return nil |
| 2916 |
} |
| 2917 |
|
| 2918 |
// Copy so we do not reference a potentially large buffer |
| 2919 |
arg := make([]byte, len(argo)) |
| 2920 |
copy(arg, argo) |
| 2921 |
|
| 2922 |
args := splitArg(arg) |
| 2923 |
sub := &subscription{client: c} |
| 2924 |
|
| 2925 |
delta := int32(1) |
| 2926 |
switch len(args) { |
| 2927 |
case 1: |
| 2928 |
sub.queue = nil |
| 2929 |
case 3: |
| 2930 |
sub.queue = args[1] |
| 2931 |
sub.qw = int32(parseSize(args[2])) |
| 2932 |
// TODO: (ik) We should have a non empty queue name and a queue |
| 2933 |
// weight >= 1. For 2.11, we may want to return an error if that |
| 2934 |
// is not the case, but for now just overwrite `delta` if queue |
| 2935 |
// weight is greater than 1 (it is possible after a reconnect/ |
| 2936 |
// server restart to receive a queue weight > 1 for a new sub). |
| 2937 |
if sub.qw > 1 { |
| 2938 |
delta = sub.qw |
| 2939 |
} |
| 2940 |
default: |
| 2941 |
return fmt.Errorf("processLeafSub Parse Error: '%s'", arg) |
| 2942 |
} |
| 2943 |
sub.subject = args[0] |
| 2944 |
|
| 2945 |
c.mu.Lock() |
| 2946 |
if c.isClosed() { |
| 2947 |
c.mu.Unlock() |
| 2948 |
return nil |
| 2949 |
} |
| 2950 |
|
| 2951 |
acc := c.acc |
| 2952 |
// Guard against LS+ arriving before CONNECT has been processed, which |
| 2953 |
// can happen when compression is enabled. |
| 2954 |
if acc == nil { |
| 2955 |
c.mu.Unlock() |
| 2956 |
c.sendErr("Authorization Violation") |
| 2957 |
c.closeConnection(ProtocolViolation) |
| 2958 |
return nil |
| 2959 |
} |
| 2960 |
// Check if we have a loop. |
| 2961 |
ldsPrefix := bytes.HasPrefix(sub.subject, []byte(leafNodeLoopDetectionSubjectPrefix)) |
| 2962 |
|
| 2963 |
if ldsPrefix && bytesToString(sub.subject) == acc.getLDSubject() { |
| 2964 |
c.mu.Unlock() |
| 2965 |
c.handleLeafNodeLoop(true) |
| 2966 |
return nil |
| 2967 |
} |
| 2968 |
|
| 2969 |
// Check permissions if applicable. (but exclude the $LDS, $GR and _GR_) |
| 2970 |
checkPerms := true |
| 2971 |
if sub.subject[0] == '$' || sub.subject[0] == '_' { |
| 2972 |
if ldsPrefix || |
| 2973 |
bytes.HasPrefix(sub.subject, []byte(oldGWReplyPrefix)) || |
| 2974 |
bytes.HasPrefix(sub.subject, []byte(gwReplyPrefix)) { |
| 2975 |
checkPerms = false |
| 2976 |
} |
| 2977 |
} |
| 2978 |
|
| 2979 |
// If we are a hub check that we can publish to this subject. |
| 2980 |
if checkPerms { |
| 2981 |
subj := string(sub.subject) |
| 2982 |
if subjectIsLiteral(subj) && !c.pubAllowedFullCheck(subj, true, true) { |
| 2983 |
c.mu.Unlock() |
| 2984 |
c.leafSubPermViolation(sub.subject) |
| 2985 |
c.Debugf(fmt.Sprintf("Permissions Violation for Subscription to %q", sub.subject)) |
| 2986 |
return nil |
| 2987 |
} |
| 2988 |
c.loadMsgDenyFilterIfNeeded(subj, len(sub.queue) > 0) |
| 2989 |
} |
| 2990 |
|
| 2991 |
// Check if we have a maximum on the number of subscriptions. |
| 2992 |
if c.subsAtLimit() { |
| 2993 |
c.mu.Unlock() |
| 2994 |
c.maxSubsExceeded() |
| 2995 |
return nil |
| 2996 |
} |
| 2997 |
|
| 2998 |
// If we have an origin cluster associated mark that in the sub. |
| 2999 |
if rc := c.remoteCluster(); rc != _EMPTY_ { |
| 3000 |
sub.origin = []byte(rc) |
| 3001 |
} |
| 3002 |
|
| 3003 |
// Like Routes, we store local subs by account and subject and optionally queue name. |
| 3004 |
// If we have a queue it will have a trailing weight which we do not want. |
| 3005 |
if sub.queue != nil { |
| 3006 |
sub.sid = arg[:len(arg)-len(args[2])-1] |
| 3007 |
} else { |
| 3008 |
sub.sid = arg |
| 3009 |
} |
| 3010 |
key := bytesToString(sub.sid) |
| 3011 |
osub := c.subs[key] |
| 3012 |
if osub == nil { |
| 3013 |
c.subs[key] = sub |
| 3014 |
// Now place into the account sl. |
| 3015 |
if err := acc.sl.Insert(sub); err != nil { |
| 3016 |
delete(c.subs, key) |
| 3017 |
c.mu.Unlock() |
| 3018 |
c.Errorf("Could not insert subscription: %v", err) |
| 3019 |
c.sendErr("Invalid Subscription") |
| 3020 |
return nil |
| 3021 |
} |
| 3022 |
} else if sub.queue != nil { |
| 3023 |
// For a queue we need to update the weight. |
| 3024 |
delta = sub.qw - atomic.LoadInt32(&osub.qw) |
| 3025 |
atomic.StoreInt32(&osub.qw, sub.qw) |
| 3026 |
acc.sl.UpdateRemoteQSub(osub) |
| 3027 |
} |
| 3028 |
spoke := c.isSpokeLeafNode() |
| 3029 |
c.mu.Unlock() |
| 3030 |
|
| 3031 |
// Only add in shadow subs if a new sub or qsub. |
| 3032 |
if osub == nil { |
| 3033 |
if err := c.addShadowSubscriptions(acc, sub); err != nil { |
| 3034 |
c.Errorf(err.Error()) |
| 3035 |
} |
| 3036 |
} |
| 3037 |
|
| 3038 |
// If we are not solicited, treat leaf node subscriptions similar to a |
| 3039 |
// client subscription, meaning we forward them to routes, gateways and |
| 3040 |
// other leaf nodes as needed. |
| 3041 |
if !spoke { |
| 3042 |
// If we are routing add to the route map for the associated account. |
| 3043 |
srv.updateRouteSubscriptionMap(acc, sub, delta) |
| 3044 |
if srv.gateway.enabled { |
| 3045 |
srv.gatewayUpdateSubInterest(acc.Name, sub, delta) |
| 3046 |
} |
| 3047 |
} |
| 3048 |
// Now check on leafnode updates for other leaf nodes. We understand solicited |
| 3049 |
// and non-solicited state in this call so we will do the right thing. |
| 3050 |
acc.updateLeafNodes(sub, delta) |
| 3051 |
|
| 3052 |
return nil |
| 3053 |
} |
| 3054 |
|
| 3055 |
// If the leafnode is a solicited, set the connect delay based on default |
| 3056 |
// or private option (for tests). Sends the error to the other side, log and |
| 3057 |
// close the connection. |
| 3058 |
func (c *client) handleLeafNodeLoop(sendErr bool) { |
| 3059 |
accName, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterLoopDetected) |
| 3060 |
errTxt := fmt.Sprintf("Loop detected for leafnode account=%q. Delaying attempt to reconnect for %v", accName, delay) |
| 3061 |
if sendErr { |
| 3062 |
c.sendErr(errTxt) |
| 3063 |
} |
| 3064 |
|
| 3065 |
c.Errorf(errTxt) |
| 3066 |
// If we are here with "sendErr" false, it means that this is the server |
| 3067 |
// that received the error. The other side will have closed the connection, |
| 3068 |
// but does not hurt to close here too. |
| 3069 |
c.closeConnection(ProtocolViolation) |
| 3070 |
} |
| 3071 |
|
| 3072 |
// processLeafUnsub will process an inbound unsub request for the remote leaf node. |
| 3073 |
func (c *client) processLeafUnsub(arg []byte) error { |
| 3074 |
// Indicate any activity, so pub and sub or unsubs. |
| 3075 |
c.in.subs++ |
| 3076 |
|
| 3077 |
srv := c.srv |
| 3078 |
|
| 3079 |
c.mu.Lock() |
| 3080 |
if c.isClosed() { |
| 3081 |
c.mu.Unlock() |
| 3082 |
return nil |
| 3083 |
} |
| 3084 |
|
| 3085 |
acc := c.acc |
| 3086 |
// Guard against LS- arriving before CONNECT has been processed. |
| 3087 |
if acc == nil { |
| 3088 |
c.mu.Unlock() |
| 3089 |
c.sendErr("Authorization Violation") |
| 3090 |
c.closeConnection(ProtocolViolation) |
| 3091 |
return nil |
| 3092 |
} |
| 3093 |
|
| 3094 |
spoke := c.isSpokeLeafNode() |
| 3095 |
// We store local subs by account and subject and optionally queue name. |
| 3096 |
// LS- will have the arg exactly as the key. |
| 3097 |
sub, ok := c.subs[string(arg)] |
| 3098 |
if !ok { |
| 3099 |
// If not found, don't try to update routes/gws/leaf nodes. |
| 3100 |
c.mu.Unlock() |
| 3101 |
return nil |
| 3102 |
} |
| 3103 |
delta := int32(1) |
| 3104 |
if len(sub.queue) > 0 { |
| 3105 |
delta = sub.qw |
| 3106 |
} |
| 3107 |
c.mu.Unlock() |
| 3108 |
|
| 3109 |
c.unsubscribe(acc, sub, true, true) |
| 3110 |
if !spoke { |
| 3111 |
// If we are routing subtract from the route map for the associated account. |
| 3112 |
srv.updateRouteSubscriptionMap(acc, sub, -delta) |
| 3113 |
// Gateways |
| 3114 |
if srv.gateway.enabled { |
| 3115 |
srv.gatewayUpdateSubInterest(acc.Name, sub, -delta) |
| 3116 |
} |
| 3117 |
} |
| 3118 |
// Now check on leafnode updates for other leaf nodes. |
| 3119 |
acc.updateLeafNodes(sub, -delta) |
| 3120 |
return nil |
| 3121 |
} |
| 3122 |
|
| 3123 |
func (c *client) processLeafHeaderMsgArgs(arg []byte) error { |
| 3124 |
// Unroll splitArgs to avoid runtime/heap issues |
| 3125 |
args := c.argsa[:0] |
| 3126 |
start := -1 |
| 3127 |
for i, b := range arg { |
| 3128 |
switch b { |
| 3129 |
case ' ', '\t', '\r', '\n': |
| 3130 |
if start >= 0 { |
| 3131 |
args = append(args, arg[start:i]) |
| 3132 |
start = -1 |
| 3133 |
} |
| 3134 |
default: |
| 3135 |
if start < 0 { |
| 3136 |
start = i |
| 3137 |
} |
| 3138 |
} |
| 3139 |
} |
| 3140 |
if start >= 0 { |
| 3141 |
args = append(args, arg[start:]) |
| 3142 |
} |
| 3143 |
|
| 3144 |
c.pa.arg = arg |
| 3145 |
switch len(args) { |
| 3146 |
case 0, 1, 2: |
| 3147 |
return fmt.Errorf("processLeafHeaderMsgArgs Parse Error: '%s'", args) |
| 3148 |
case 3: |
| 3149 |
c.pa.reply = nil |
| 3150 |
c.pa.queues = nil |
| 3151 |
c.pa.hdb = args[1] |
| 3152 |
c.pa.hdr = parseSize(args[1]) |
| 3153 |
c.pa.szb = args[2] |
| 3154 |
c.pa.size = parseSize(args[2]) |
| 3155 |
case 4: |
| 3156 |
c.pa.reply = args[1] |
| 3157 |
c.pa.queues = nil |
| 3158 |
c.pa.hdb = args[2] |
| 3159 |
c.pa.hdr = parseSize(args[2]) |
| 3160 |
c.pa.szb = args[3] |
| 3161 |
c.pa.size = parseSize(args[3]) |
| 3162 |
default: |
| 3163 |
// args[1] is our reply indicator. Should be + or | normally. |
| 3164 |
if len(args[1]) != 1 { |
| 3165 |
return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1]) |
| 3166 |
} |
| 3167 |
switch args[1][0] { |
| 3168 |
case '+': |
| 3169 |
c.pa.reply = args[2] |
| 3170 |
case '|': |
| 3171 |
c.pa.reply = nil |
| 3172 |
default: |
| 3173 |
return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Reply Indicator: '%s'", args[1]) |
| 3174 |
} |
| 3175 |
// Grab header size. |
| 3176 |
c.pa.hdb = args[len(args)-2] |
| 3177 |
c.pa.hdr = parseSize(c.pa.hdb) |
| 3178 |
|
| 3179 |
// Grab size. |
| 3180 |
c.pa.szb = args[len(args)-1] |
| 3181 |
c.pa.size = parseSize(c.pa.szb) |
| 3182 |
|
| 3183 |
// Grab queue names. |
| 3184 |
if c.pa.reply != nil { |
| 3185 |
c.pa.queues = args[3 : len(args)-2] |
| 3186 |
} else { |
| 3187 |
c.pa.queues = args[2 : len(args)-2] |
| 3188 |
} |
| 3189 |
} |
| 3190 |
if c.pa.hdr < 0 { |
| 3191 |
return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Header Size: '%s'", arg) |
| 3192 |
} |
| 3193 |
if c.pa.size < 0 { |
| 3194 |
return fmt.Errorf("processLeafHeaderMsgArgs Bad or Missing Size: '%s'", args) |
| 3195 |
} |
| 3196 |
if c.pa.hdr > c.pa.size { |
| 3197 |
return fmt.Errorf("processLeafHeaderMsgArgs Header Size larger then TotalSize: '%s'", arg) |
| 3198 |
} |
| 3199 |
maxPayload := atomic.LoadInt32(&c.mpay) |
| 3200 |
if maxPayload != jwt.NoLimit && int64(c.pa.size) > int64(maxPayload) { |
| 3201 |
c.maxPayloadViolation(c.pa.size, maxPayload) |
| 3202 |
return ErrMaxPayload |
| 3203 |
} |
| 3204 |
|
| 3205 |
// Common ones processed after check for arg length |
| 3206 |
c.pa.subject = args[0] |
| 3207 |
|
| 3208 |
return nil |
| 3209 |
} |
| 3210 |
|
| 3211 |
func (c *client) processLeafMsgArgs(arg []byte) error { |
| 3212 |
// Unroll splitArgs to avoid runtime/heap issues |
| 3213 |
args := c.argsa[:0] |
| 3214 |
start := -1 |
| 3215 |
for i, b := range arg { |
| 3216 |
switch b { |
| 3217 |
case ' ', '\t', '\r', '\n': |
| 3218 |
if start >= 0 { |
| 3219 |
args = append(args, arg[start:i]) |
| 3220 |
start = -1 |
| 3221 |
} |
| 3222 |
default: |
| 3223 |
if start < 0 { |
| 3224 |
start = i |
| 3225 |
} |
| 3226 |
} |
| 3227 |
} |
| 3228 |
if start >= 0 { |
| 3229 |
args = append(args, arg[start:]) |
| 3230 |
} |
| 3231 |
|
| 3232 |
c.pa.arg = arg |
| 3233 |
switch len(args) { |
| 3234 |
case 0, 1: |
| 3235 |
return fmt.Errorf("processLeafMsgArgs Parse Error: '%s'", args) |
| 3236 |
case 2: |
| 3237 |
c.pa.reply = nil |
| 3238 |
c.pa.queues = nil |
| 3239 |
c.pa.szb = args[1] |
| 3240 |
c.pa.size = parseSize(args[1]) |
| 3241 |
case 3: |
| 3242 |
c.pa.reply = args[1] |
| 3243 |
c.pa.queues = nil |
| 3244 |
c.pa.szb = args[2] |
| 3245 |
c.pa.size = parseSize(args[2]) |
| 3246 |
default: |
| 3247 |
// args[1] is our reply indicator. Should be + or | normally. |
| 3248 |
if len(args[1]) != 1 { |
| 3249 |
return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1]) |
| 3250 |
} |
| 3251 |
switch args[1][0] { |
| 3252 |
case '+': |
| 3253 |
c.pa.reply = args[2] |
| 3254 |
case '|': |
| 3255 |
c.pa.reply = nil |
| 3256 |
default: |
| 3257 |
return fmt.Errorf("processLeafMsgArgs Bad or Missing Reply Indicator: '%s'", args[1]) |
| 3258 |
} |
| 3259 |
// Grab size. |
| 3260 |
c.pa.szb = args[len(args)-1] |
| 3261 |
c.pa.size = parseSize(c.pa.szb) |
| 3262 |
|
| 3263 |
// Grab queue names. |
| 3264 |
if c.pa.reply != nil { |
| 3265 |
c.pa.queues = args[3 : len(args)-1] |
| 3266 |
} else { |
| 3267 |
c.pa.queues = args[2 : len(args)-1] |
| 3268 |
} |
| 3269 |
} |
| 3270 |
if c.pa.size < 0 { |
| 3271 |
return fmt.Errorf("processLeafMsgArgs Bad or Missing Size: '%s'", args) |
| 3272 |
} |
| 3273 |
maxPayload := atomic.LoadInt32(&c.mpay) |
| 3274 |
if maxPayload != jwt.NoLimit && int64(c.pa.size) > int64(maxPayload) { |
| 3275 |
c.maxPayloadViolation(c.pa.size, maxPayload) |
| 3276 |
return ErrMaxPayload |
| 3277 |
} |
| 3278 |
|
| 3279 |
// Common ones processed after check for arg length |
| 3280 |
c.pa.subject = args[0] |
| 3281 |
|
| 3282 |
return nil |
| 3283 |
} |
| 3284 |
|
| 3285 |
// processInboundLeafMsg is called to process an inbound msg from a leaf node. |
| 3286 |
func (c *client) processInboundLeafMsg(msg []byte) { |
| 3287 |
// Update statistics |
| 3288 |
// The msg includes the CR_LF, so pull back out for accounting. |
| 3289 |
c.in.msgs++ |
| 3290 |
c.in.bytes += int32(len(msg) - LEN_CR_LF) |
| 3291 |
|
| 3292 |
srv, acc, subject := c.srv, c.acc, string(c.pa.subject) |
| 3293 |
|
| 3294 |
// Mostly under testing scenarios. |
| 3295 |
if srv == nil || acc == nil { |
| 3296 |
return |
| 3297 |
} |
| 3298 |
|
| 3299 |
// Check that leaf messages respect the subject permissions. |
| 3300 |
if c.perms != nil && !c.leafMsgAllowed() { |
| 3301 |
c.leafPubPermViolation(c.pa.subject) |
| 3302 |
return |
| 3303 |
} |
| 3304 |
|
| 3305 |
// Match the subscriptions. We will use our own L1 map if |
| 3306 |
// it's still valid, avoiding contention on the shared sublist. |
| 3307 |
var r *SublistResult |
| 3308 |
var ok bool |
| 3309 |
|
| 3310 |
genid := atomic.LoadUint64(&c.acc.sl.genid) |
| 3311 |
if genid == c.in.genid && c.in.results != nil { |
| 3312 |
r, ok = c.in.results[subject] |
| 3313 |
} else { |
| 3314 |
// Reset our L1 completely. |
| 3315 |
c.in.results = make(map[string]*SublistResult) |
| 3316 |
c.in.genid = genid |
| 3317 |
} |
| 3318 |
|
| 3319 |
// Go back to the sublist data structure. |
| 3320 |
if !ok { |
| 3321 |
r = c.acc.sl.Match(subject) |
| 3322 |
// Prune the results cache. Keeps us from unbounded growth. Random delete. |
| 3323 |
if len(c.in.results) >= maxResultCacheSize { |
| 3324 |
n := 0 |
| 3325 |
for subj := range c.in.results { |
| 3326 |
delete(c.in.results, subj) |
| 3327 |
if n++; n > pruneSize { |
| 3328 |
break |
| 3329 |
} |
| 3330 |
} |
| 3331 |
} |
| 3332 |
// Then add the new cache entry. |
| 3333 |
c.in.results[subject] = r |
| 3334 |
} |
| 3335 |
|
| 3336 |
// Collect queue names if needed. |
| 3337 |
var qnames [][]byte |
| 3338 |
|
| 3339 |
// Check for no interest, short circuit if so. |
| 3340 |
// This is the fanout scale. |
| 3341 |
if len(r.psubs)+len(r.qsubs) > 0 { |
| 3342 |
flag := pmrNoFlag |
| 3343 |
// If we have queue subs in this cluster, then if we run in gateway |
| 3344 |
// mode and the remote gateways have queue subs, then we need to |
| 3345 |
// collect the queue groups this message was sent to so that we |
| 3346 |
// exclude them when sending to gateways. |
| 3347 |
if len(r.qsubs) > 0 && c.srv.gateway.enabled && |
| 3348 |
atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 { |
| 3349 |
flag |= pmrCollectQueueNames |
| 3350 |
} |
| 3351 |
// If this is a mapped subject that means the mapped interest |
| 3352 |
// is what got us here, but this might not have a queue designation |
| 3353 |
// If that is the case, make sure we ignore to process local queue subscribers. |
| 3354 |
if len(c.pa.mapped) > 0 && len(c.pa.queues) == 0 { |
| 3355 |
flag |= pmrIgnoreEmptyQueueFilter |
| 3356 |
} |
| 3357 |
_, qnames = c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, flag) |
| 3358 |
} |
| 3359 |
|
| 3360 |
// Now deal with gateways |
| 3361 |
if c.srv.gateway.enabled { |
| 3362 |
c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, qnames, true) |
| 3363 |
} |
| 3364 |
} |
| 3365 |
|
| 3366 |
// Checks whether the inbound leaf message is allowed by the |
| 3367 |
// connection's permissions. On the hub side this enforces what |
| 3368 |
// the remote leaf may publish. On the spoke side this enforces |
| 3369 |
// import restrictions such as deny_imports. |
| 3370 |
func (c *client) leafMsgAllowed() bool { |
| 3371 |
wireSubject := c.pa.subject |
| 3372 |
if len(c.pa.mapped) > 0 { |
| 3373 |
// Mappings rewrite c.pa.subject to the internal |
| 3374 |
// destination. For leaf ACLs, need to check |
| 3375 |
// the original wire subject from the remote side. |
| 3376 |
wireSubject = c.pa.mapped |
| 3377 |
} |
| 3378 |
// Strip any gateway routing prefix for the permission check. |
| 3379 |
subjectToCheck, isGW := getGWRoutedSubjectOrSelf(wireSubject) |
| 3380 |
|
| 3381 |
// Service-import replies (_R_), JS ack subjects ($JS.ACK.) |
| 3382 |
// are internal routing subjects forwarded via LS+ without |
| 3383 |
// permission checks. |
| 3384 |
if isServiceReply(subjectToCheck) || isJSAckSubject(subjectToCheck) { |
| 3385 |
return true |
| 3386 |
} |
| 3387 |
|
| 3388 |
c.mu.RLock() |
| 3389 |
if c.isSpokeLeafNode() { |
| 3390 |
// Gateway routed replies are forwarded without |
| 3391 |
// permission checks. |
| 3392 |
if isGW || c.leafReceiveAllowed(subjectToCheck) { |
| 3393 |
c.mu.RUnlock() |
| 3394 |
return true |
| 3395 |
} |
| 3396 |
} else if c.leafSendAllowed(subjectToCheck) { |
| 3397 |
c.mu.RUnlock() |
| 3398 |
return true |
| 3399 |
} |
| 3400 |
|
| 3401 |
// If allow_responses is not configured, or there is no tracked reply for |
| 3402 |
// this subject, the answer is "denied" and we can return it while still |
| 3403 |
// holding only the read lock. |
| 3404 |
replySubject := bytesToString(wireSubject) |
| 3405 |
if c.perms == nil || c.perms.resp == nil || c.replies[replySubject] == nil { |
| 3406 |
c.mu.RUnlock() |
| 3407 |
return false |
| 3408 |
} |
| 3409 |
c.mu.RUnlock() |
| 3410 |
|
| 3411 |
// Check tracked reply permissions (allow_responses). |
| 3412 |
// Use the pre-strip subject since deliverMsg tracks |
| 3413 |
// replies under the original form, which includes |
| 3414 |
// the GW routing prefix for routed requests. |
| 3415 |
c.mu.Lock() |
| 3416 |
defer c.mu.Unlock() |
| 3417 |
return c.responseAllowed(replySubject) |
| 3418 |
} |
| 3419 |
|
| 3420 |
// Returns true if the leaf side ACLs allow importing this subject, |
| 3421 |
// based on the permissions received over INFO and any local deny_imports. |
| 3422 |
// At least a read lock must be held. |
| 3423 |
func (c *client) leafReceiveAllowed(subject []byte) bool { |
| 3424 |
return c.canSubscribeInternal(bytesToString(subject)) |
| 3425 |
} |
| 3426 |
|
| 3427 |
// Returns true if the hub side ACLs allow the remote leaf to send |
| 3428 |
// this subject. |
| 3429 |
// At least a read lock must be held. |
| 3430 |
func (c *client) leafSendAllowed(bsubject []byte) bool { |
| 3431 |
// Use the original export ACL captured for this accepted leaf. |
| 3432 |
// The live perms also contain additional JetStream denies used by |
| 3433 |
// the normal forwarding path, and applying them here would reject |
| 3434 |
// legitimate inbound JS API requests. |
| 3435 |
subject := bytesToString(bsubject) |
| 3436 |
perms := c.opts.Export |
| 3437 |
if perms == nil || (perms.Allow == nil && perms.Deny == nil) { |
| 3438 |
return true |
| 3439 |
} |
| 3440 |
|
| 3441 |
allowed := true |
| 3442 |
if perms.Allow != nil && !strings.HasPrefix(subject, mqttPrefix) { |
| 3443 |
allowed = false |
| 3444 |
for _, allowSubj := range perms.Allow { |
| 3445 |
if matchLiteral(subject, allowSubj) { |
| 3446 |
allowed = true |
| 3447 |
break |
| 3448 |
} |
| 3449 |
} |
| 3450 |
} |
| 3451 |
|
| 3452 |
if allowed && len(perms.Deny) > 0 { |
| 3453 |
for _, denySubj := range perms.Deny { |
| 3454 |
if matchLiteral(subject, denySubj) { |
| 3455 |
allowed = false |
| 3456 |
break |
| 3457 |
} |
| 3458 |
} |
| 3459 |
} |
| 3460 |
return allowed |
| 3461 |
} |
| 3462 |
|
| 3463 |
// Handles a subscription permission violation. |
| 3464 |
// See leafPermViolation() for details. |
| 3465 |
func (c *client) leafSubPermViolation(subj []byte) { |
| 3466 |
c.leafPermViolation(false, subj) |
| 3467 |
} |
| 3468 |
|
| 3469 |
// Handles a publish permission violation. |
| 3470 |
// See leafPermViolation() for details. |
| 3471 |
func (c *client) leafPubPermViolation(subj []byte) { |
| 3472 |
c.leafPermViolation(true, subj) |
| 3473 |
} |
| 3474 |
|
| 3475 |
// Common function to process publish or subscribe leafnode permission violation. |
| 3476 |
// Sends the permission violation error to the remote, logs it and closes the connection. |
| 3477 |
// If this is from a server soliciting, the reconnection will be delayed. |
| 3478 |
func (c *client) leafPermViolation(pub bool, subj []byte) { |
| 3479 |
if c.isSpokeLeafNode() { |
| 3480 |
// For spokes these are no-ops since the hub server told us our permissions. |
| 3481 |
// We just need to not send these over to the other side since we will get cutoff. |
| 3482 |
return |
| 3483 |
} |
| 3484 |
// FIXME(dlc) ? |
| 3485 |
c.setLeafConnectDelayIfSoliciting(leafNodeReconnectAfterPermViolation) |
| 3486 |
var action string |
| 3487 |
if pub { |
| 3488 |
c.sendErr(fmt.Sprintf("Permissions Violation for Publish to %q", subj)) |
| 3489 |
action = "Publish" |
| 3490 |
} else { |
| 3491 |
c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q", subj)) |
| 3492 |
action = "Subscription" |
| 3493 |
} |
| 3494 |
c.Errorf("%s Violation on %q - Check other side configuration", action, subj) |
| 3495 |
// TODO: add a new close reason that is more appropriate? |
| 3496 |
c.closeConnection(ProtocolViolation) |
| 3497 |
} |
| 3498 |
|
| 3499 |
// Invoked from generic processErr() for LEAF connections. |
| 3500 |
func (c *client) leafProcessErr(errStr string) { |
| 3501 |
// Check if we got a cluster name collision. |
| 3502 |
if strings.Contains(errStr, ErrLeafNodeHasSameClusterName.Error()) { |
| 3503 |
_, delay := c.setLeafConnectDelayIfSoliciting(leafNodeReconnectDelayAfterClusterNameSame) |
| 3504 |
c.Errorf("Leafnode connection dropped with same cluster name error. Delaying attempt to reconnect for %v", delay) |
| 3505 |
return |
| 3506 |
} |
| 3507 |
if strings.Contains(errStr, ErrLeafNodeMinVersionRejected.Error()) { |
| 3508 |
_, delay := c.setLeafConnectDelayIfSoliciting(leafNodeMinVersionReconnectDelay) |
| 3509 |
c.Errorf("Leafnode connection dropped due to minimum version requirement. Delaying attempt to reconnect for %v", delay) |
| 3510 |
return |
| 3511 |
} |
| 3512 |
|
| 3513 |
// We will look for Loop detected error coming from the other side. |
| 3514 |
// If we solicit, set the connect delay. |
| 3515 |
if !strings.Contains(errStr, "Loop detected") { |
| 3516 |
return |
| 3517 |
} |
| 3518 |
c.handleLeafNodeLoop(false) |
| 3519 |
} |
| 3520 |
|
| 3521 |
// If this leaf connection solicits, sets the connect delay to the given value, |
| 3522 |
// or the one from the server option's LeafNode.connDelay if one is set (for tests). |
| 3523 |
// Returns the connection's account name and delay. |
| 3524 |
func (c *client) setLeafConnectDelayIfSoliciting(delay time.Duration) (string, time.Duration) { |
| 3525 |
c.mu.Lock() |
| 3526 |
if c.isSolicitedLeafNode() { |
| 3527 |
if s := c.srv; s != nil { |
| 3528 |
if srvdelay := s.getOpts().LeafNode.connDelay; srvdelay != 0 { |
| 3529 |
delay = srvdelay |
| 3530 |
} |
| 3531 |
} |
| 3532 |
c.leaf.remote.setConnectDelay(delay) |
| 3533 |
} |
| 3534 |
var accName string |
| 3535 |
if c.acc != nil { |
| 3536 |
accName = c.acc.Name |
| 3537 |
} |
| 3538 |
c.mu.Unlock() |
| 3539 |
return accName, delay |
| 3540 |
} |
| 3541 |
|
| 3542 |
// For the given remote Leafnode configuration, this function returns |
| 3543 |
// if TLS is required, and if so, will return a clone of the TLS Config |
| 3544 |
// (since some fields will be changed during handshake), the TLS server |
| 3545 |
// name that is remembered, and the TLS timeout. |
| 3546 |
func (c *client) leafNodeGetTLSConfigForSolicit(remote *leafNodeCfg) (bool, *tls.Config, string, float64) { |
| 3547 |
var ( |
| 3548 |
tlsConfig *tls.Config |
| 3549 |
tlsName string |
| 3550 |
tlsTimeout float64 |
| 3551 |
) |
| 3552 |
|
| 3553 |
remote.RLock() |
| 3554 |
defer remote.RUnlock() |
| 3555 |
|
| 3556 |
tlsRequired := remote.TLS || remote.TLSConfig != nil |
| 3557 |
if tlsRequired { |
| 3558 |
if remote.TLSConfig != nil { |
| 3559 |
tlsConfig = remote.TLSConfig.Clone() |
| 3560 |
} else { |
| 3561 |
tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12} |
| 3562 |
} |
| 3563 |
tlsName = remote.tlsName |
| 3564 |
tlsTimeout = remote.TLSTimeout |
| 3565 |
if tlsTimeout == 0 { |
| 3566 |
tlsTimeout = float64(TLS_TIMEOUT / time.Second) |
| 3567 |
} |
| 3568 |
} |
| 3569 |
|
| 3570 |
return tlsRequired, tlsConfig, tlsName, tlsTimeout |
| 3571 |
} |
| 3572 |
|
| 3573 |
// Initiates the LeafNode Websocket connection by: |
| 3574 |
// - doing the TLS handshake if needed |
| 3575 |
// - sending the HTTP request |
| 3576 |
// - waiting for the HTTP response |
| 3577 |
// |
| 3578 |
// Since some bufio reader is used to consume the HTTP response, this function |
| 3579 |
// returns the slice of buffered bytes (if any) so that the readLoop that will |
| 3580 |
// be started after that consume those first before reading from the socket. |
| 3581 |
// The boolean |
| 3582 |
// |
| 3583 |
// Lock held on entry. |
| 3584 |
func (c *client) leafNodeSolicitWSConnection(opts *Options, rURL *url.URL, remote *leafNodeCfg) ([]byte, ClosedState, error) { |
| 3585 |
remote.RLock() |
| 3586 |
compress := remote.Websocket.Compression |
| 3587 |
// By default the server will mask outbound frames, but it can be disabled with this option. |
| 3588 |
noMasking := remote.Websocket.NoMasking |
| 3589 |
infoTimeout := remote.FirstInfoTimeout |
| 3590 |
remote.RUnlock() |
| 3591 |
// Will do the client-side TLS handshake if needed. |
| 3592 |
tlsRequired, err := c.leafClientHandshakeIfNeeded(remote, opts) |
| 3593 |
if err != nil { |
| 3594 |
// 0 will indicate that the connection was already closed |
| 3595 |
return nil, 0, err |
| 3596 |
} |
| 3597 |
|
| 3598 |
// For http request, we need the passed URL to contain either http or https scheme. |
| 3599 |
scheme := "http" |
| 3600 |
if tlsRequired { |
| 3601 |
scheme = "https" |
| 3602 |
} |
| 3603 |
// We will use the `/leafnode` path to tell the accepting WS server that it should |
| 3604 |
// create a LEAF connection, not a CLIENT. |
| 3605 |
// In case we use the user's URL path in the future, make sure we append the user's |
| 3606 |
// path to our `/leafnode` path. |
| 3607 |
lpath := leafNodeWSPath |
| 3608 |
if curPath := rURL.EscapedPath(); curPath != _EMPTY_ { |
| 3609 |
if curPath[0] == '/' { |
| 3610 |
curPath = curPath[1:] |
| 3611 |
} |
| 3612 |
lpath = path.Join(curPath, lpath) |
| 3613 |
} else { |
| 3614 |
lpath = lpath[1:] |
| 3615 |
} |
| 3616 |
ustr := fmt.Sprintf("%s://%s/%s", scheme, rURL.Host, lpath) |
| 3617 |
u, _ := url.Parse(ustr) |
| 3618 |
req := &http.Request{ |
| 3619 |
Method: "GET", |
| 3620 |
URL: u, |
| 3621 |
Proto: "HTTP/1.1", |
| 3622 |
ProtoMajor: 1, |
| 3623 |
ProtoMinor: 1, |
| 3624 |
Header: make(http.Header), |
| 3625 |
Host: u.Host, |
| 3626 |
} |
| 3627 |
wsKey, err := wsMakeChallengeKey() |
| 3628 |
if err != nil { |
| 3629 |
return nil, WriteError, err |
| 3630 |
} |
| 3631 |
|
| 3632 |
req.Header["Upgrade"] = []string{"websocket"} |
| 3633 |
req.Header["Connection"] = []string{"Upgrade"} |
| 3634 |
req.Header["Sec-WebSocket-Key"] = []string{wsKey} |
| 3635 |
req.Header["Sec-WebSocket-Version"] = []string{"13"} |
| 3636 |
if compress { |
| 3637 |
req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue) |
| 3638 |
} |
| 3639 |
if noMasking { |
| 3640 |
req.Header.Add(wsNoMaskingHeader, wsNoMaskingValue) |
| 3641 |
} |
| 3642 |
c.nc.SetDeadline(time.Now().Add(infoTimeout)) |
| 3643 |
if err := req.Write(c.nc); err != nil { |
| 3644 |
return nil, WriteError, err |
| 3645 |
} |
| 3646 |
|
| 3647 |
var resp *http.Response |
| 3648 |
|
| 3649 |
br := bufio.NewReaderSize(c.nc, MAX_CONTROL_LINE_SIZE) |
| 3650 |
resp, err = http.ReadResponse(br, req) |
| 3651 |
if err == nil && |
| 3652 |
(resp.StatusCode != 101 || |
| 3653 |
!strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") || |
| 3654 |
!strings.EqualFold(resp.Header.Get("Connection"), "upgrade") || |
| 3655 |
resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) { |
| 3656 |
|
| 3657 |
err = fmt.Errorf("invalid websocket connection") |
| 3658 |
} |
| 3659 |
// Check compression extension... |
| 3660 |
if err == nil && c.ws.compress { |
| 3661 |
// Check that not only permessage-deflate extension is present, but that |
| 3662 |
// we also have server and client no context take over. |
| 3663 |
srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header, false) |
| 3664 |
|
| 3665 |
// If server does not support compression, then simply disable it in our side. |
| 3666 |
if !srvCompress { |
| 3667 |
c.ws.compress = false |
| 3668 |
} else if !noCtxTakeover { |
| 3669 |
err = fmt.Errorf("compression negotiation error") |
| 3670 |
} |
| 3671 |
} |
| 3672 |
// Same for no masking... |
| 3673 |
if err == nil && noMasking { |
| 3674 |
// Check if server accepts no masking |
| 3675 |
if resp.Header.Get(wsNoMaskingHeader) != wsNoMaskingValue { |
| 3676 |
// Nope, need to mask our writes as any client would do. |
| 3677 |
c.ws.maskwrite = true |
| 3678 |
} |
| 3679 |
} |
| 3680 |
if resp != nil { |
| 3681 |
resp.Body.Close() |
| 3682 |
} |
| 3683 |
if err != nil { |
| 3684 |
return nil, ReadError, err |
| 3685 |
} |
| 3686 |
c.Debugf("Leafnode compression=%v masking=%v", c.ws.compress, c.ws.maskwrite) |
| 3687 |
|
| 3688 |
var preBuf []byte |
| 3689 |
// We have to slurp whatever is in the bufio reader and pass that to the readloop. |
| 3690 |
if n := br.Buffered(); n != 0 { |
| 3691 |
preBuf, _ = br.Peek(n) |
| 3692 |
} |
| 3693 |
return preBuf, 0, nil |
| 3694 |
} |
| 3695 |
|
| 3696 |
const connectProcessTimeout = 2 * time.Second |
| 3697 |
|
| 3698 |
// This is invoked for remote LEAF remote connections after processing the INFO |
| 3699 |
// protocol. |
| 3700 |
func (s *Server) leafNodeResumeConnectProcess(c *client) { |
| 3701 |
clusterName := s.ClusterName() |
| 3702 |
|
| 3703 |
c.mu.Lock() |
| 3704 |
if c.isClosed() { |
| 3705 |
c.mu.Unlock() |
| 3706 |
return |
| 3707 |
} |
| 3708 |
if err := c.sendLeafConnect(clusterName, c.headers); err != nil { |
| 3709 |
c.mu.Unlock() |
| 3710 |
c.closeConnection(WriteError) |
| 3711 |
return |
| 3712 |
} |
| 3713 |
|
| 3714 |
// Spin up the write loop. |
| 3715 |
s.startGoRoutine(func() { c.writeLoop() }) |
| 3716 |
|
| 3717 |
// timeout leafNodeFinishConnectProcess |
| 3718 |
c.ping.tmr = time.AfterFunc(connectProcessTimeout, func() { |
| 3719 |
c.mu.Lock() |
| 3720 |
// check if leafNodeFinishConnectProcess was called and prevent later leafNodeFinishConnectProcess |
| 3721 |
if !c.flags.setIfNotSet(connectProcessFinished) { |
| 3722 |
c.mu.Unlock() |
| 3723 |
return |
| 3724 |
} |
| 3725 |
clearTimer(&c.ping.tmr) |
| 3726 |
closed := c.isClosed() |
| 3727 |
c.mu.Unlock() |
| 3728 |
if !closed { |
| 3729 |
c.sendErrAndDebug("Stale Leaf Node Connection - Closing") |
| 3730 |
c.closeConnection(StaleConnection) |
| 3731 |
} |
| 3732 |
}) |
| 3733 |
c.mu.Unlock() |
| 3734 |
c.Debugf("Remote leafnode connect msg sent") |
| 3735 |
} |
| 3736 |
|
| 3737 |
// This is invoked for remote LEAF connections after processing the INFO |
| 3738 |
// protocol and leafNodeResumeConnectProcess. |
| 3739 |
// This will send LS+ the CONNECT protocol and register the leaf node. |
| 3740 |
func (s *Server) leafNodeFinishConnectProcess(c *client) { |
| 3741 |
c.mu.Lock() |
| 3742 |
if !c.flags.setIfNotSet(connectProcessFinished) { |
| 3743 |
c.mu.Unlock() |
| 3744 |
return |
| 3745 |
} |
| 3746 |
if c.isClosed() { |
| 3747 |
c.mu.Unlock() |
| 3748 |
s.removeLeafNodeConnection(c) |
| 3749 |
return |
| 3750 |
} |
| 3751 |
remote := c.leaf.remote |
| 3752 |
if remote == nil || c.acc == nil { |
| 3753 |
c.mu.Unlock() |
| 3754 |
c.sendErr("Authorization Violation") |
| 3755 |
c.closeConnection(ProtocolViolation) |
| 3756 |
return |
| 3757 |
} |
| 3758 |
// Check if we will need to send the system connect event. |
| 3759 |
remote.RLock() |
| 3760 |
sendSysConnectEvent := remote.Hub |
| 3761 |
remote.RUnlock() |
| 3762 |
|
| 3763 |
// Capture account before releasing lock |
| 3764 |
acc := c.acc |
| 3765 |
// cancel connectProcessTimeout |
| 3766 |
clearTimer(&c.ping.tmr) |
| 3767 |
c.mu.Unlock() |
| 3768 |
|
| 3769 |
// Make sure we register with the account here. |
| 3770 |
if err := c.registerWithAccount(acc); err != nil { |
| 3771 |
if err == ErrTooManyAccountConnections { |
| 3772 |
c.maxAccountConnExceeded() |
| 3773 |
return |
| 3774 |
} else if err == ErrLeafNodeLoop { |
| 3775 |
c.handleLeafNodeLoop(true) |
| 3776 |
return |
| 3777 |
} |
| 3778 |
c.Errorf("Registering leaf with account %s resulted in error: %v", acc.Name, err) |
| 3779 |
c.closeConnection(ProtocolViolation) |
| 3780 |
return |
| 3781 |
} |
| 3782 |
if !s.addLeafNodeConnection(c, _EMPTY_, _EMPTY_, false) { |
| 3783 |
// Was not added, could be because the remote configuration has been removed. |
| 3784 |
c.closeConnection(ClientClosed) |
| 3785 |
return |
| 3786 |
} |
| 3787 |
s.initLeafNodeSmapAndSendSubs(c) |
| 3788 |
if sendSysConnectEvent { |
| 3789 |
s.sendLeafNodeConnect(acc) |
| 3790 |
} |
| 3791 |
s.accountConnectEvent(c) |
| 3792 |
|
| 3793 |
// The above functions are not running under the client lock, so it is |
| 3794 |
// possible that between the time we have started the read/write loops |
| 3795 |
// and now, that the connection was closed. This would leave the closed |
| 3796 |
// LN connection possibly registered with the account and/or the server's |
| 3797 |
// leafs map. So check if connection is closed, and if so, manually cleanup. |
| 3798 |
c.mu.Lock() |
| 3799 |
closed := c.isClosed() |
| 3800 |
if !closed { |
| 3801 |
c.setFirstPingTimer() |
| 3802 |
} |
| 3803 |
c.mu.Unlock() |
| 3804 |
if closed { |
| 3805 |
s.removeLeafNodeConnection(c) |
| 3806 |
if prev := acc.removeClient(c); prev == 1 { |
| 3807 |
s.decActiveAccounts() |
| 3808 |
} |
| 3809 |
} |
| 3810 |
} |