Debian Codegraph @

server/gateway.go

raw
1 // Copyright 2018-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "bytes"
18 "cmp"
19 "crypto/sha256"
20 "crypto/tls"
21 "encoding/json"
22 "errors"
23 "fmt"
24 "math/rand"
25 "net"
26 "net/url"
27 "slices"
28 "strconv"
29 "strings"
30 "sync"
31 "sync/atomic"
32 "time"
33 )
34
35 const (
36 defaultSolicitGatewaysDelay = time.Second
37 defaultGatewayConnectDelay = time.Second
38 defaultGatewayConnectMaxDelay = 30 * time.Second
39 defaultGatewayReconnectDelay = time.Second
40 defaultGatewayRecentSubExpiration = 2 * time.Second
41 defaultGatewayMaxRUnsubBeforeSwitch = 1000
42
43 oldGWReplyPrefix = "$GR."
44 oldGWReplyPrefixLen = len(oldGWReplyPrefix)
45 oldGWReplyStart = oldGWReplyPrefixLen + 5 // len of prefix above + len of hash (4) + "."
46
47 // The new prefix is "_GR_.<cluster>.<server>." where <cluster> is 6 characters
48 // hash of origin cluster name and <server> is 6 characters hash of origin server pub key.
49 gwReplyPrefix = "_GR_."
50 gwReplyPrefixLen = len(gwReplyPrefix)
51 gwHashLen = 6
52 gwClusterOffset = gwReplyPrefixLen
53 gwServerOffset = gwClusterOffset + gwHashLen + 1
54 gwSubjectOffset = gwServerOffset + gwHashLen + 1
55
56 // Gateway connections send PINGs regardless of traffic. The interval is
57 // either Options.PingInterval or this value, whichever is the smallest.
58 gwMaxPingInterval = 15 * time.Second
59 )
60
61 var (
62 gatewayConnectDelay = defaultGatewayConnectDelay
63 gatewayConnectMaxDelay = defaultGatewayConnectMaxDelay
64 gatewayReconnectDelay = defaultGatewayReconnectDelay
65 gatewayMaxRUnsubBeforeSwitch = defaultGatewayMaxRUnsubBeforeSwitch
66 gatewaySolicitDelay = int64(defaultSolicitGatewaysDelay)
67 gatewayMaxPingInterval = gwMaxPingInterval
68 )
69
70 // Warning when user configures gateway TLS insecure
71 const gatewayTLSInsecureWarning = "TLS certificate chain and hostname of solicited gateways will not be verified. DO NOT USE IN PRODUCTION!"
72
73 // SetGatewaysSolicitDelay sets the initial delay before gateways
74 // connections are initiated.
75 // Used by tests.
76 func SetGatewaysSolicitDelay(delay time.Duration) {
77 atomic.StoreInt64(&gatewaySolicitDelay, int64(delay))
78 }
79
80 // ResetGatewaysSolicitDelay resets the initial delay before gateways
81 // connections are initiated to its default values.
82 // Used by tests.
83 func ResetGatewaysSolicitDelay() {
84 atomic.StoreInt64(&gatewaySolicitDelay, int64(defaultSolicitGatewaysDelay))
85 }
86
87 const (
88 gatewayCmdGossip byte = 1
89 gatewayCmdAllSubsStart byte = 2
90 gatewayCmdAllSubsComplete byte = 3
91 )
92
93 // GatewayInterestMode represents an account interest mode for a gateway connection
94 type GatewayInterestMode byte
95
96 // GatewayInterestMode values
97 const (
98 // optimistic is the default mode where a cluster will send
99 // to a gateway unless it is been told that there is no interest
100 // (this is for plain subscribers only).
101 Optimistic GatewayInterestMode = iota
102 // transitioning is when a gateway has to send too many
103 // no interest on subjects to the remote and decides that it is
104 // now time to move to modeInterestOnly (this is on a per account
105 // basis).
106 Transitioning
107 // interestOnly means that a cluster sends all it subscriptions
108 // interest to the gateway, which in return does not send a message
109 // unless it knows that there is explicit interest.
110 InterestOnly
111 )
112
113 func (im GatewayInterestMode) String() string {
114 switch im {
115 case Optimistic:
116 return "Optimistic"
117 case InterestOnly:
118 return "Interest-Only"
119 case Transitioning:
120 return "Transitioning"
121 default:
122 return "Unknown"
123 }
124 }
125
126 var gwDoNotForceInterestOnlyMode bool
127
128 // GatewayDoNotForceInterestOnlyMode is used ONLY in tests.
129 // DO NOT USE in normal code or if you embed the NATS Server.
130 func GatewayDoNotForceInterestOnlyMode(doNotForce bool) {
131 gwDoNotForceInterestOnlyMode = doNotForce
132 }
133
134 type srvGateway struct {
135 totalQSubs int64 //total number of queue subs in all remote gateways (used with atomic operations)
136 sync.RWMutex
137 enabled bool // Immutable, true if both a name and port are configured
138 name string // Name of the Gateway on this server
139 out map[string]*client // outbound gateways
140 outo []*client // outbound gateways maintained in an order suitable for sending msgs (currently based on RTT)
141 in map[uint64]*client // inbound gateways
142 remotes map[string]*gatewayCfg // Config of remote gateways
143 URLs refCountedUrlSet // Set of all Gateway URLs in the cluster
144 URL string // This server gateway URL (after possible random port is resolved)
145 info *Info // Gateway Info protocol
146 infoJSON []byte // Marshal'ed Info protocol
147 runknown bool // Rejects unknown (not configured) gateway connections
148 replyPfx []byte // Will be "$GNR.<1:reserved>.<8:cluster hash>.<8:server hash>."
149
150 // For backward compatibility
151 oldReplyPfx []byte
152 oldHash []byte
153
154 // We maintain the interest of subjects and queues per account.
155 // For a given account, entries in the map could be something like this:
156 // foo.bar {n: 3} // 3 subs on foo.bar
157 // foo.> {n: 6} // 6 subs on foo.>
158 // foo bar {n: 1, q: true} // 1 qsub on foo, queue bar
159 // foo baz {n: 3, q: true} // 3 qsubs on foo, queue baz
160 pasi struct {
161 // Protect map since accessed from different go-routine and avoid
162 // possible race resulting in RS+ being sent before RS- resulting
163 // in incorrect interest suppression.
164 // Will use while sending QSubs (on GW connection accept) and when
165 // switching to the send-all-subs mode.
166 sync.Mutex
167 m map[string]map[string]*sitally
168 }
169
170 // This is to track recent subscriptions for a given account
171 rsubs sync.Map
172
173 resolver netResolver // Used to resolve host name before calling net.Dial()
174 sqbsz int // Max buffer size to send queue subs protocol. Used for testing.
175 recSubExp time.Duration // For how long do we check if there is a subscription match for a message with reply
176
177 // These are used for routing of mapped replies.
178 sIDHash []byte // Server ID hash (6 bytes)
179 routesIDByHash sync.Map // Route's server ID is hashed (6 bytes) and stored in this map.
180
181 // If a server has its own configuration in the "Gateways" remotes configuration
182 // we will keep track of the URLs that are defined in the config so they can
183 // be reported in monitoring.
184 ownCfgURLs []string
185 }
186
187 // Subject interest tally. Also indicates if the key in the map is a
188 // queue or not.
189 type sitally struct {
190 n int32 // number of subscriptions directly matching
191 q bool // indicate that this is a queue
192 }
193
194 type gatewayCfg struct {
195 sync.RWMutex
196 *RemoteGatewayOpts
197 hash []byte
198 oldHash []byte
199 urls map[string]*url.URL
200 connAttempts int
201 tlsName string
202 implicit bool
203 varzUpdateURLs bool // Tells monitoring code to update URLs when varz is inspected.
204 }
205
206 // Struct for client's gateway related fields
207 type gateway struct {
208 name string
209 cfg *gatewayCfg
210 connectURL *url.URL // Needed when sending CONNECT after receiving INFO from remote
211 outsim *sync.Map // Per-account subject interest (or no-interest) (outbound conn)
212 insim map[string]*insie // Per-account subject no-interest sent or modeInterestOnly mode (inbound conn)
213
214 // This is an outbound GW connection
215 outbound bool
216 // Set/check in readLoop without lock. This is to know that an inbound has sent the CONNECT protocol first
217 connected bool
218 // Set to true if outbound is to a server that only knows about $GR, not $GNR
219 useOldPrefix bool
220 // If true, it indicates that the inbound side will switch any account to
221 // interest-only mode "immediately", so the outbound should disregard
222 // the optimistic mode when checking for interest.
223 interestOnlyMode bool
224 // Name of the remote server
225 remoteName string
226 }
227
228 // Outbound subject interest entry.
229 type outsie struct {
230 sync.RWMutex
231 // Indicate that all subs should be stored. This is
232 // set to true when receiving the command from the
233 // remote that we are about to receive all its subs.
234 mode GatewayInterestMode
235 // If not nil, used for no-interest for plain subs.
236 // If a subject is present in this map, it means that
237 // the remote is not interested in that subject.
238 // When we have received the command that says that
239 // the remote has sent all its subs, this is set to nil.
240 ni map[string]struct{}
241 // Contains queue subscriptions when in optimistic mode,
242 // and all subs when pk is > 0.
243 sl *Sublist
244 // Number of queue subs
245 qsubs int
246 }
247
248 // Inbound subject interest entry.
249 // If `ni` is not nil, it stores the subjects for which an
250 // RS- was sent to the remote gateway. When a subscription
251 // is created, this is used to know if we need to send
252 // an RS+ to clear the no-interest in the remote.
253 // When an account is switched to modeInterestOnly (we send
254 // all subs of an account to the remote), then `ni` is nil and
255 // when all subs have been sent, mode is set to modeInterestOnly
256 type insie struct {
257 ni map[string]struct{} // Record if RS- was sent for given subject
258 mode GatewayInterestMode
259 }
260
261 type gwReplyMap struct {
262 ms string
263 exp int64
264 }
265
266 type gwReplyMapping struct {
267 // Indicate if we should check the map or not. Since checking the map is done
268 // when processing inbound messages and requires the lock we want to
269 // check only when needed. This is set/get using atomic, so needs to
270 // be memory aligned.
271 check int32
272 // To keep track of gateway replies mapping
273 mapping map[string]*gwReplyMap
274 }
275
276 // Returns the corresponding gw routed subject, and `true` to indicate that a
277 // mapping was found. If no entry is found, the passed subject is returned
278 // as-is and `false` is returned to indicate that no mapping was found.
279 // Caller is responsible to ensure the locking.
280 func (g *gwReplyMapping) get(subject []byte) ([]byte, bool) {
281 rm, ok := g.mapping[string(subject)]
282 if !ok {
283 return subject, false
284 }
285 subj := []byte(rm.ms)
286 return subj, true
287 }
288
289 // clone returns a deep copy of the RemoteGatewayOpts object
290 func (r *RemoteGatewayOpts) clone() *RemoteGatewayOpts {
291 if r == nil {
292 return nil
293 }
294 clone := &RemoteGatewayOpts{
295 Name: r.Name,
296 URLs: deepCopyURLs(r.URLs),
297 }
298 if r.TLSConfig != nil {
299 clone.TLSConfig = r.TLSConfig.Clone()
300 clone.TLSTimeout = r.TLSTimeout
301 }
302 return clone
303 }
304
305 // Ensure that gateway is properly configured.
306 func validateGatewayOptions(o *Options) error {
307 if o.Gateway.Name == _EMPTY_ && o.Gateway.Port == 0 {
308 return nil
309 }
310 if o.Gateway.Name == _EMPTY_ {
311 return errors.New("gateway has no name")
312 }
313 if strings.Contains(o.Gateway.Name, " ") {
314 return ErrGatewayNameHasSpaces
315 }
316 if o.Gateway.Port == 0 {
317 return fmt.Errorf("gateway %q has no port specified (select -1 for random port)", o.Gateway.Name)
318 }
319 for i, g := range o.Gateway.Gateways {
320 if g.Name == _EMPTY_ {
321 return fmt.Errorf("gateway in the list %d has no name", i)
322 }
323 if len(g.URLs) == 0 {
324 return fmt.Errorf("gateway %q has no URL", g.Name)
325 }
326 }
327 if err := validatePinnedCerts(o.Gateway.TLSPinnedCerts); err != nil {
328 return fmt.Errorf("gateway %q: %v", o.Gateway.Name, err)
329 }
330 return nil
331 }
332
333 // Computes a hash of 6 characters for the name.
334 // This will be used for routing of replies.
335 func getGWHash(name string) []byte {
336 return []byte(getHashSize(name, gwHashLen))
337 }
338
339 func getOldHash(name string) []byte {
340 sha := sha256.New()
341 sha.Write([]byte(name))
342 fullHash := []byte(fmt.Sprintf("%x", sha.Sum(nil)))
343 return fullHash[:4]
344 }
345
346 // Initialize the s.gateway structure. We do this even if the server
347 // does not have a gateway configured. In some part of the code, the
348 // server will check the number of outbound gateways, etc.. and so
349 // we don't have to check if s.gateway is nil or not.
350 func (s *Server) newGateway(opts *Options) error {
351 gateway := &srvGateway{
352 name: opts.Gateway.Name,
353 out: make(map[string]*client),
354 outo: make([]*client, 0, 4),
355 in: make(map[uint64]*client),
356 remotes: make(map[string]*gatewayCfg),
357 URLs: make(refCountedUrlSet),
358 resolver: opts.Gateway.resolver,
359 runknown: opts.Gateway.RejectUnknown,
360 oldHash: getOldHash(opts.Gateway.Name),
361 }
362 gateway.Lock()
363 defer gateway.Unlock()
364
365 gateway.sIDHash = getGWHash(s.info.ID)
366 clusterHash := getGWHash(opts.Gateway.Name)
367 prefix := make([]byte, 0, gwSubjectOffset)
368 prefix = append(prefix, gwReplyPrefix...)
369 prefix = append(prefix, clusterHash...)
370 prefix = append(prefix, '.')
371 prefix = append(prefix, gateway.sIDHash...)
372 prefix = append(prefix, '.')
373 gateway.replyPfx = prefix
374
375 prefix = make([]byte, 0, oldGWReplyStart)
376 prefix = append(prefix, oldGWReplyPrefix...)
377 prefix = append(prefix, gateway.oldHash...)
378 prefix = append(prefix, '.')
379 gateway.oldReplyPfx = prefix
380
381 gateway.pasi.m = make(map[string]map[string]*sitally)
382
383 if gateway.resolver == nil {
384 gateway.resolver = netResolver(net.DefaultResolver)
385 }
386
387 // Create remote gateways
388 for _, rgo := range opts.Gateway.Gateways {
389 // Ignore if there is a remote gateway with our name.
390 if rgo.Name == gateway.name {
391 gateway.ownCfgURLs = getURLsAsString(rgo.URLs)
392 continue
393 }
394 cfg := &gatewayCfg{
395 RemoteGatewayOpts: rgo.clone(),
396 hash: getGWHash(rgo.Name),
397 oldHash: getOldHash(rgo.Name),
398 urls: make(map[string]*url.URL, len(rgo.URLs)),
399 }
400 if opts.Gateway.TLSConfig != nil && cfg.TLSConfig == nil {
401 cfg.TLSConfig = opts.Gateway.TLSConfig.Clone()
402 }
403 if cfg.TLSTimeout == 0 {
404 cfg.TLSTimeout = opts.Gateway.TLSTimeout
405 }
406 for _, u := range rgo.URLs {
407 // For TLS, look for a hostname that we can use for TLSConfig.ServerName
408 cfg.saveTLSHostname(u)
409 cfg.urls[u.Host] = u
410 }
411 gateway.remotes[cfg.Name] = cfg
412 }
413
414 gateway.sqbsz = opts.Gateway.sendQSubsBufSize
415 if gateway.sqbsz == 0 {
416 gateway.sqbsz = maxBufSize
417 }
418 gateway.recSubExp = defaultGatewayRecentSubExpiration
419
420 gateway.enabled = opts.Gateway.Name != "" && opts.Gateway.Port != 0
421 s.gateway = gateway
422 return nil
423 }
424
425 // Update remote gateways TLS configurations after a config reload.
426 func (g *srvGateway) updateRemotesTLSConfig(opts *Options) {
427 g.Lock()
428 defer g.Unlock()
429 // Instead of going over opts.Gateway.Gateways, which would include only
430 // explicit remotes, we are going to go through g.remotes.
431 for name, cfg := range g.remotes {
432 if name == g.name {
433 continue
434 }
435 var ro *RemoteGatewayOpts
436 // We now need to go back and find the RemoteGatewayOpts but only if
437 // this remote is explicit (otherwise it won't be found).
438 if !cfg.isImplicit() {
439 for _, r := range opts.Gateway.Gateways {
440 if r.Name == name {
441 ro = r
442 break
443 }
444 }
445 }
446 cfg.Lock()
447 // If we have an `ro` (that means an explicitly defined remote gateway)
448 // and it has an explicit TLS config, use that one, otherwise (no explicit
449 // TLS config in the remote, or implicit remote), use the TLS config from
450 // the main block.
451 if ro != nil && ro.TLSConfig != nil {
452 cfg.TLSConfig = ro.TLSConfig.Clone()
453 } else if opts.Gateway.TLSConfig != nil {
454 cfg.TLSConfig = opts.Gateway.TLSConfig.Clone()
455 }
456 // Ensure that OCSP callbacks are always setup after a reload if needed.
457 mustStaple := opts.OCSPConfig != nil && opts.OCSPConfig.Mode == OCSPModeAlways
458 if mustStaple && opts.Gateway.TLSConfig != nil {
459 clientCB := opts.Gateway.TLSConfig.GetClientCertificate
460 verifyCB := opts.Gateway.TLSConfig.VerifyConnection
461 if mustStaple && cfg.TLSConfig != nil {
462 if clientCB != nil && cfg.TLSConfig.GetClientCertificate == nil {
463 cfg.TLSConfig.GetClientCertificate = clientCB
464 }
465 if verifyCB != nil && cfg.TLSConfig.VerifyConnection == nil {
466 cfg.TLSConfig.VerifyConnection = verifyCB
467 }
468 }
469 }
470 cfg.Unlock()
471 }
472 }
473
474 // Returns if this server rejects connections from gateways that are not
475 // explicitly configured.
476 func (g *srvGateway) rejectUnknown() bool {
477 g.RLock()
478 reject := g.runknown
479 g.RUnlock()
480 return reject
481 }
482
483 // Starts the gateways accept loop and solicit explicit gateways
484 // after an initial delay. This delay is meant to give a chance to
485 // the cluster to form and this server gathers gateway URLs for this
486 // cluster in order to send that as part of the connect/info process.
487 func (s *Server) startGateways() {
488 s.startGatewayAcceptLoop()
489
490 // Delay start of creation of gateways to give a chance
491 // to the local cluster to form.
492 s.startGoRoutine(func() {
493 defer s.grWG.Done()
494
495 dur := s.getOpts().gatewaysSolicitDelay
496 if dur == 0 {
497 dur = time.Duration(atomic.LoadInt64(&gatewaySolicitDelay))
498 }
499
500 select {
501 case <-time.After(dur):
502 s.solicitGateways()
503 case <-s.quitCh:
504 return
505 }
506 })
507 }
508
509 // This starts the gateway accept loop in a go routine, unless it
510 // is detected that the server has already been shutdown.
511 func (s *Server) startGatewayAcceptLoop() {
512 if s.isShuttingDown() {
513 return
514 }
515
516 // Snapshot server options.
517 opts := s.getOpts()
518
519 port := opts.Gateway.Port
520 if port == -1 {
521 port = 0
522 }
523
524 s.mu.Lock()
525 hp := net.JoinHostPort(opts.Gateway.Host, strconv.Itoa(port))
526 l, e := natsListen("tcp", hp)
527 s.gatewayListenerErr = e
528 if e != nil {
529 s.mu.Unlock()
530 s.Fatalf("Error listening on gateway port: %d - %v", opts.Gateway.Port, e)
531 return
532 }
533 s.Noticef("Gateway name is %s", s.getGatewayName())
534 s.Noticef("Listening for gateways connections on %s",
535 net.JoinHostPort(opts.Gateway.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
536
537 tlsReq := opts.Gateway.TLSConfig != nil
538 authRequired := opts.Gateway.Username != ""
539 info := &Info{
540 ID: s.info.ID,
541 Name: opts.ServerName,
542 Version: s.info.Version,
543 AuthRequired: authRequired,
544 TLSRequired: tlsReq,
545 TLSVerify: tlsReq,
546 MaxPayload: s.info.MaxPayload,
547 Gateway: opts.Gateway.Name,
548 GatewayNRP: true,
549 Headers: s.supportsHeaders(),
550 Proto: s.getServerProto(),
551 }
552 // Unless in some tests we want to keep the old behavior, we are now
553 // (since v2.9.0) indicate that this server will switch all accounts
554 // to InterestOnly mode when accepting an inbound or when a new
555 // account is fetched.
556 if !gwDoNotForceInterestOnlyMode {
557 info.GatewayIOM = true
558 }
559
560 // If we have selected a random port...
561 if port == 0 {
562 // Write resolved port back to options.
563 opts.Gateway.Port = l.Addr().(*net.TCPAddr).Port
564 }
565 // Possibly override Host/Port based on Gateway.Advertise
566 if err := s.setGatewayInfoHostPort(info, opts); err != nil {
567 s.Fatalf("Error setting gateway INFO with Gateway.Advertise value of %s, err=%v", opts.Gateway.Advertise, err)
568 l.Close()
569 s.mu.Unlock()
570 return
571 }
572 // Setup state that can enable shutdown
573 s.gatewayListener = l
574
575 // Warn if insecure is configured in the main Gateway configuration
576 // or any of the RemoteGateway's. This means that we need to check
577 // remotes even if TLS would not be configured for the accept.
578 warn := tlsReq && opts.Gateway.TLSConfig.InsecureSkipVerify
579 if !warn {
580 for _, g := range opts.Gateway.Gateways {
581 if g.TLSConfig != nil && g.TLSConfig.InsecureSkipVerify {
582 warn = true
583 break
584 }
585 }
586 }
587 if warn {
588 s.Warnf(gatewayTLSInsecureWarning)
589 }
590 go s.acceptConnections(l, "Gateway", func(conn net.Conn) { s.createGateway(nil, nil, conn) }, nil)
591 s.mu.Unlock()
592 }
593
594 // Similar to setInfoHostPortAndGenerateJSON, but for gatewayInfo.
595 func (s *Server) setGatewayInfoHostPort(info *Info, o *Options) error {
596 gw := s.gateway
597 gw.Lock()
598 defer gw.Unlock()
599 gw.URLs.removeUrl(gw.URL)
600 if o.Gateway.Advertise != "" {
601 advHost, advPort, err := parseHostPort(o.Gateway.Advertise, o.Gateway.Port)
602 if err != nil {
603 return err
604 }
605 info.Host = advHost
606 info.Port = advPort
607 } else {
608 info.Host = o.Gateway.Host
609 info.Port = o.Gateway.Port
610 // If the host is "0.0.0.0" or "::" we need to resolve to a public IP.
611 // This will return at most 1 IP.
612 hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(info.Host, false)
613 if err != nil {
614 return err
615 }
616 if hostIsIPAny {
617 if len(ips) == 0 {
618 // TODO(ik): Should we fail here (prevent starting)? If not, we
619 // are going to "advertise" the 0.0.0.0:<port> url, which means
620 // that remote are going to try to connect to 0.0.0.0:<port>,
621 // which means a connect to loopback address, which is going
622 // to fail with either TLS error, conn refused if the remote
623 // is using different gateway port than this one, or error
624 // saying that it tried to connect to itself.
625 s.Errorf("Could not find any non-local IP for gateway %q with listen specification %q",
626 gw.name, info.Host)
627 } else {
628 // Take the first from the list...
629 info.Host = ips[0]
630 }
631 }
632 }
633 gw.URL = net.JoinHostPort(info.Host, strconv.Itoa(info.Port))
634 if o.Gateway.Advertise != "" {
635 s.Noticef("Advertise address for gateway %q is set to %s", gw.name, gw.URL)
636 } else {
637 s.Noticef("Address for gateway %q is %s", gw.name, gw.URL)
638 }
639 gw.URLs[gw.URL]++
640 gw.info = info
641 info.GatewayURL = gw.URL
642 // (re)generate the gatewayInfoJSON byte array
643 gw.generateInfoJSON()
644 return nil
645 }
646
647 // Generates the Gateway INFO protocol.
648 // The gateway lock is held on entry
649 func (g *srvGateway) generateInfoJSON() {
650 // We could be here when processing a route INFO that has a gateway URL,
651 // but this server is not configured for gateways, so simply ignore here.
652 // The configuration mismatch is reported somewhere else.
653 if !g.enabled || g.info == nil {
654 return
655 }
656 g.info.GatewayURLs = g.URLs.getAsStringSlice()
657 b, err := json.Marshal(g.info)
658 if err != nil {
659 panic(err)
660 }
661 g.infoJSON = []byte(fmt.Sprintf(InfoProto, b))
662 }
663
664 // Goes through the list of registered gateways and try to connect to those.
665 // The list (remotes) is initially containing the explicit remote gateways,
666 // but the list is augmented with any implicit (discovered) gateway. Therefore,
667 // this function only solicit explicit ones.
668 func (s *Server) solicitGateways() {
669 gw := s.gateway
670 gw.RLock()
671 defer gw.RUnlock()
672 for _, cfg := range gw.remotes {
673 // Since we delay the creation of gateways, it is
674 // possible that server starts to receive inbound from
675 // other clusters and in turn create outbounds. So here
676 // we create only the ones that are configured.
677 if !cfg.isImplicit() {
678 cfg := cfg // Create new instance for the goroutine.
679 s.startGoRoutine(func() {
680 s.solicitGateway(cfg, true)
681 s.grWG.Done()
682 })
683 }
684 }
685 }
686
687 // Reconnect to the gateway after a little wait period. For explicit
688 // gateways, we also wait for the default reconnect time.
689 func (s *Server) reconnectGateway(cfg *gatewayCfg) {
690 defer s.grWG.Done()
691
692 delay := time.Duration(rand.Intn(100)) * time.Millisecond
693 if !cfg.isImplicit() {
694 delay += gatewayReconnectDelay
695 }
696 select {
697 case <-time.After(delay):
698 case <-s.quitCh:
699 return
700 }
701 s.solicitGateway(cfg, false)
702 }
703
704 // This function will loop trying to connect to any URL attached
705 // to the given Gateway. It will return once a connection has been created.
706 func (s *Server) solicitGateway(cfg *gatewayCfg, firstConnect bool) {
707 var (
708 opts = s.getOpts()
709 isImplicit = cfg.isImplicit()
710 attemptDelay = gatewayConnectDelay
711 attempts int
712 typeStr string
713 )
714 if isImplicit {
715 typeStr = "implicit"
716 } else {
717 typeStr = "explicit"
718 }
719
720 const connFmt = "Connecting to %s gateway %q (%s) at %s (attempt %v)"
721 const connErrFmt = "Error connecting to %s gateway %q (%s) at %s (attempt %v): %v"
722
723 for s.isRunning() {
724 urls := cfg.getURLs()
725 if len(urls) == 0 {
726 break
727 }
728 attempts++
729 report := s.shouldReportConnectErr(firstConnect, attempts)
730 // Iteration is random
731 for _, u := range urls {
732 address, err := s.getRandomIP(s.gateway.resolver, u.Host, nil)
733 if err != nil {
734 s.Errorf("Error getting IP for %s gateway %q (%s): %v", typeStr, cfg.Name, u.Host, err)
735 continue
736 }
737 if report {
738 s.Noticef(connFmt, typeStr, cfg.Name, u.Host, address, attempts)
739 } else {
740 s.Debugf(connFmt, typeStr, cfg.Name, u.Host, address, attempts)
741 }
742 conn, err := natsDialTimeout("tcp", address, DEFAULT_ROUTE_DIAL)
743 if err == nil {
744 // We could connect, create the gateway connection and return.
745 s.createGateway(cfg, u, conn)
746 return
747 }
748 if report {
749 s.Errorf(connErrFmt, typeStr, cfg.Name, u.Host, address, attempts, err)
750 } else {
751 s.Debugf(connErrFmt, typeStr, cfg.Name, u.Host, address, attempts, err)
752 }
753 // Break this loop if server is being shutdown...
754 if !s.isRunning() {
755 break
756 }
757 }
758 if isImplicit {
759 if opts.Gateway.ConnectRetries == 0 || attempts > opts.Gateway.ConnectRetries {
760 s.gateway.Lock()
761 // We could have just accepted an inbound for this remote gateway.
762 // So if there is an inbound, let's try again to connect.
763 if s.gateway.hasInbound(cfg.Name) {
764 s.gateway.Unlock()
765 continue
766 }
767 delete(s.gateway.remotes, cfg.Name)
768 s.gateway.Unlock()
769 return
770 }
771 }
772 select {
773 case <-s.quitCh:
774 return
775 case <-time.After(attemptDelay):
776 if opts.Gateway.ConnectBackoff {
777 // Use exponential backoff for connection attempts.
778 attemptDelay *= 2
779 if attemptDelay > gatewayConnectMaxDelay {
780 attemptDelay = gatewayConnectMaxDelay
781 }
782 }
783 continue
784 }
785 }
786 }
787
788 // Returns true if there is an inbound for the given `name`.
789 // Lock held on entry.
790 func (g *srvGateway) hasInbound(name string) bool {
791 for _, ig := range g.in {
792 ig.mu.Lock()
793 igname := ig.gw.name
794 ig.mu.Unlock()
795 if igname == name {
796 return true
797 }
798 }
799 return false
800 }
801
802 // Called when a gateway connection is either accepted or solicited.
803 // If accepted, the gateway is marked as inbound.
804 // If solicited, the gateway is marked as outbound.
805 func (s *Server) createGateway(cfg *gatewayCfg, url *url.URL, conn net.Conn) {
806 // Snapshot server options.
807 opts := s.getOpts()
808
809 now := time.Now()
810 c := &client{srv: s, nc: conn, start: now, last: now, kind: GATEWAY}
811
812 // Are we creating the gateway based on the configuration
813 solicit := cfg != nil
814 var tlsRequired bool
815
816 s.gateway.RLock()
817 infoJSON := s.gateway.infoJSON
818 s.gateway.RUnlock()
819
820 // Perform some initialization under the client lock
821 c.mu.Lock()
822 c.initClient()
823 c.gw = &gateway{}
824 if solicit {
825 // This is an outbound gateway connection
826 cfg.RLock()
827 tlsRequired = cfg.TLSConfig != nil
828 cfgName := cfg.Name
829 cfg.RUnlock()
830 c.gw.outbound = true
831 c.gw.name = cfgName
832 c.gw.cfg = cfg
833 cfg.bumpConnAttempts()
834 // Since we are delaying the connect until after receiving
835 // the remote's INFO protocol, save the URL we need to connect to.
836 c.gw.connectURL = url
837
838 c.Noticef("Creating outbound gateway connection to %q", cfgName)
839 } else {
840 c.flags.set(expectConnect)
841 // Inbound gateway connection
842 c.Noticef("Processing inbound gateway connection")
843 // Check if TLS is required for inbound GW connections.
844 tlsRequired = opts.Gateway.TLSConfig != nil
845 // We expect a CONNECT from the accepted connection.
846 c.setAuthTimer(secondsToDuration(opts.Gateway.AuthTimeout))
847 }
848
849 // Check for TLS
850 if tlsRequired {
851 var tlsConfig *tls.Config
852 var tlsName string
853 var timeout float64
854
855 if solicit {
856 var (
857 mustStaple = opts.OCSPConfig != nil && opts.OCSPConfig.Mode == OCSPModeAlways
858 clientCB func(*tls.CertificateRequestInfo) (*tls.Certificate, error)
859 verifyCB func(tls.ConnectionState) error
860 )
861 // Snapshot callbacks for OCSP outside an ongoing reload which might be happening.
862 if mustStaple {
863 s.reloadMu.RLock()
864 s.optsMu.RLock()
865 clientCB = s.opts.Gateway.TLSConfig.GetClientCertificate
866 verifyCB = s.opts.Gateway.TLSConfig.VerifyConnection
867 s.optsMu.RUnlock()
868 s.reloadMu.RUnlock()
869 }
870
871 cfg.RLock()
872 tlsName = cfg.tlsName
873 tlsConfig = cfg.TLSConfig.Clone()
874 timeout = cfg.TLSTimeout
875
876 // Ensure that OCSP callbacks are always setup on gateway reconnect when OCSP policy is set to always.
877 if mustStaple {
878 if clientCB != nil && tlsConfig.GetClientCertificate == nil {
879 tlsConfig.GetClientCertificate = clientCB
880 }
881 if verifyCB != nil && tlsConfig.VerifyConnection == nil {
882 tlsConfig.VerifyConnection = verifyCB
883 }
884 }
885 cfg.RUnlock()
886 } else {
887 tlsConfig = opts.Gateway.TLSConfig
888 timeout = opts.Gateway.TLSTimeout
889 }
890
891 // Perform (either server or client side) TLS handshake.
892 if resetTLSName, err := c.doTLSHandshake("gateway", solicit, url, tlsConfig, tlsName, timeout, opts.Gateway.TLSPinnedCerts); err != nil {
893 if resetTLSName {
894 cfg.Lock()
895 cfg.tlsName = _EMPTY_
896 cfg.Unlock()
897 }
898 c.mu.Unlock()
899 return
900 }
901 }
902
903 // Do final client initialization
904 c.in.pacache = make(map[string]*perAccountCache)
905 if solicit {
906 // This is an outbound gateway connection
907 c.gw.outsim = &sync.Map{}
908 } else {
909 // Inbound gateway connection
910 c.gw.insim = make(map[string]*insie)
911 }
912
913 // Register in temp map for now until gateway properly registered
914 // in out or in gateways.
915 if !s.addToTempClients(c.cid, c) {
916 c.mu.Unlock()
917 c.closeConnection(ServerShutdown)
918 return
919 }
920
921 // Only send if we accept a connection. Will send CONNECT+INFO as an
922 // outbound only after processing peer's INFO protocol.
923 if !solicit {
924 c.enqueueProto(infoJSON)
925 }
926
927 // Spin up the read loop.
928 s.startGoRoutine(func() { c.readLoop(nil) })
929
930 // Spin up the write loop.
931 s.startGoRoutine(func() { c.writeLoop() })
932
933 if tlsRequired {
934 c.Debugf("TLS handshake complete")
935 cs := c.nc.(*tls.Conn).ConnectionState()
936 c.Debugf("TLS version %s, cipher suite %s", tlsVersion(cs.Version), tls.CipherSuiteName(cs.CipherSuite))
937 }
938
939 // For outbound, we can't set the normal ping timer yet since the other
940 // side would fail with a parse error should it receive anything but the
941 // CONNECT protocol as the first protocol. We still want to make sure
942 // that the connection is not stale until the first INFO from the remote
943 // is received.
944 if solicit {
945 c.watchForStaleConnection(adjustPingInterval(GATEWAY, opts.PingInterval), opts.MaxPingsOut)
946 }
947
948 c.mu.Unlock()
949
950 // Announce ourselves again to new connections.
951 if solicit && s.EventsEnabled() {
952 s.sendStatszUpdate()
953 }
954 }
955
956 // Builds and sends the CONNECT protocol for a gateway.
957 // Client lock held on entry.
958 func (c *client) sendGatewayConnect(opts *Options) {
959 c.gw.cfg.RLock()
960 tlsRequired := c.gw.cfg.TLSConfig != nil
961 c.gw.cfg.RUnlock()
962 url := c.gw.connectURL
963 c.gw.connectURL = nil
964 var user, pass string
965 if userInfo := url.User; userInfo != nil {
966 user = userInfo.Username()
967 pass, _ = userInfo.Password()
968 } else if opts != nil {
969 user = opts.Gateway.Username
970 pass = opts.Gateway.Password
971 }
972 cinfo := connectInfo{
973 Verbose: false,
974 Pedantic: false,
975 User: user,
976 Pass: pass,
977 TLS: tlsRequired,
978 Name: c.srv.info.ID,
979 Gateway: c.srv.gateway.name,
980 }
981 b, err := json.Marshal(cinfo)
982 if err != nil {
983 panic(err)
984 }
985 c.enqueueProto([]byte(fmt.Sprintf(ConProto, b)))
986 }
987
988 // Process the CONNECT protocol from a gateway connection.
989 // Returns an error to the connection if the CONNECT is not from a gateway
990 // (for instance a client or route connecting to the gateway port), or
991 // if the destination does not match the gateway name of this server.
992 //
993 // <Invoked from inbound connection's readLoop>
994 func (c *client) processGatewayConnect(arg []byte) error {
995 connect := &connectInfo{}
996 if err := json.Unmarshal(arg, connect); err != nil {
997 return err
998 }
999
1000 // Coming from a client or a route, reject
1001 if connect.Gateway == "" {
1002 c.sendErrAndErr(ErrClientOrRouteConnectedToGatewayPort.Error())
1003 c.closeConnection(WrongPort)
1004 return ErrClientOrRouteConnectedToGatewayPort
1005 }
1006
1007 c.mu.Lock()
1008 s := c.srv
1009 c.mu.Unlock()
1010
1011 // If we reject unknown gateways, make sure we have it configured,
1012 // otherwise return an error.
1013 if s.gateway.rejectUnknown() && s.getRemoteGateway(connect.Gateway) == nil {
1014 c.Errorf("Rejecting connection from gateway %q", connect.Gateway)
1015 c.sendErr(fmt.Sprintf("Connection to gateway %q rejected", s.getGatewayName()))
1016 c.closeConnection(WrongGateway)
1017 return ErrWrongGateway
1018 }
1019
1020 c.mu.Lock()
1021 c.gw.connected = true
1022 // Set the Ping timer after sending connect and info.
1023 c.setFirstPingTimer()
1024 c.mu.Unlock()
1025
1026 return nil
1027 }
1028
1029 // Process the INFO protocol from a gateway connection.
1030 //
1031 // If the gateway connection is an outbound (this server initiated the connection),
1032 // this function checks that the incoming INFO contains the Gateway field. If empty,
1033 // it means that this is a response from an older server or that this server connected
1034 // to the wrong port.
1035 // The outbound gateway may also receive a gossip INFO protocol from the remote gateway,
1036 // indicating other gateways that the remote knows about. This server will try to connect
1037 // to those gateways (if not explicitly configured or already implicitly connected).
1038 // In both cases (explicit or implicit), the local cluster is notified about the existence
1039 // of this new gateway. This allows servers in the cluster to ensure that they have an
1040 // outbound connection to this gateway.
1041 //
1042 // For an inbound gateway, the gateway is simply registered and the info protocol
1043 // is saved to be used after processing the CONNECT.
1044 //
1045 // <Invoked from both inbound/outbound readLoop's connection>
1046 func (c *client) processGatewayInfo(info *Info) {
1047 var (
1048 gwName string
1049 cfg *gatewayCfg
1050 )
1051 c.mu.Lock()
1052 s := c.srv
1053 cid := c.cid
1054
1055 // Check if this is the first INFO. (this call sets the flag if not already set).
1056 isFirstINFO := c.flags.setIfNotSet(infoReceived)
1057
1058 isOutbound := c.gw.outbound
1059 if isOutbound {
1060 gwName = c.gw.name
1061 cfg = c.gw.cfg
1062 } else if isFirstINFO {
1063 c.gw.name = info.Gateway
1064 }
1065 if isFirstINFO {
1066 c.opts.Name = info.ID
1067 // Get the protocol version from the INFO protocol. This will be checked
1068 // to see if this connection supports message tracing for instance.
1069 c.opts.Protocol = info.Proto
1070 c.gw.remoteName = info.Name
1071 }
1072 c.mu.Unlock()
1073
1074 // For an outbound connection...
1075 if isOutbound {
1076 // Check content of INFO for fields indicating that it comes from a gateway.
1077 // If we incorrectly connect to the wrong port (client or route), we won't
1078 // have the Gateway field set.
1079 if info.Gateway == "" {
1080 c.sendErrAndErr(fmt.Sprintf("Attempt to connect to gateway %q using wrong port", gwName))
1081 c.closeConnection(WrongPort)
1082 return
1083 }
1084 // Check that the gateway name we got is what we expect
1085 if info.Gateway != gwName {
1086 // Unless this is the very first INFO, it may be ok if this is
1087 // a gossip request to connect to other gateways.
1088 if !isFirstINFO && info.GatewayCmd == gatewayCmdGossip {
1089 // If we are configured to reject unknown, do not attempt to
1090 // connect to one that we don't have configured.
1091 if s.gateway.rejectUnknown() && s.getRemoteGateway(info.Gateway) == nil {
1092 return
1093 }
1094 s.processImplicitGateway(info)
1095 return
1096 }
1097 // Otherwise, this is a failure...
1098 // We are reporting this error in the log...
1099 c.Errorf("Failing connection to gateway %q, remote gateway name is %q",
1100 gwName, info.Gateway)
1101 // ...and sending this back to the remote so that the error
1102 // makes more sense in the remote server's log.
1103 c.sendErr(fmt.Sprintf("Connection from %q rejected, wanted to connect to %q, this is %q",
1104 s.getGatewayName(), gwName, info.Gateway))
1105 c.closeConnection(WrongGateway)
1106 return
1107 }
1108
1109 // Check for duplicate server name with servers in our cluster
1110 if s.isDuplicateServerName(info.Name) {
1111 c.Errorf("Remote server has a duplicate name: %q", info.Name)
1112 c.closeConnection(DuplicateServerName)
1113 return
1114 }
1115
1116 // Possibly add URLs that we get from the INFO protocol.
1117 if len(info.GatewayURLs) > 0 {
1118 cfg.updateURLs(info.GatewayURLs)
1119 }
1120
1121 // If this is the first INFO, send our connect
1122 if isFirstINFO {
1123 s.gateway.RLock()
1124 infoJSON := s.gateway.infoJSON
1125 s.gateway.RUnlock()
1126
1127 supportsHeaders := s.supportsHeaders()
1128 opts := s.getOpts()
1129
1130 // Note, if we want to support NKeys, then we would get the nonce
1131 // from this INFO protocol and can sign it in the CONNECT we are
1132 // going to send now.
1133 c.mu.Lock()
1134 c.gw.interestOnlyMode = info.GatewayIOM
1135 c.sendGatewayConnect(opts)
1136 c.Debugf("Gateway connect protocol sent to %q", gwName)
1137 // Send INFO too
1138 c.enqueueProto(infoJSON)
1139 c.gw.useOldPrefix = !info.GatewayNRP
1140 c.headers = supportsHeaders && info.Headers
1141 c.mu.Unlock()
1142
1143 // Register as an outbound gateway.. if we had a protocol to ack our connect,
1144 // then we should do that when process that ack.
1145 if s.registerOutboundGatewayConnection(gwName, c) {
1146 c.Noticef("Outbound gateway connection to %q (%s) registered", gwName, info.ID)
1147 // Now that the outbound gateway is registered, we can remove from temp map.
1148 s.removeFromTempClients(cid)
1149 // Set the Ping timer after sending connect and info.
1150 c.mu.Lock()
1151 c.setFirstPingTimer()
1152 c.mu.Unlock()
1153 } else {
1154 // There was a bug that would cause a connection to possibly
1155 // be called twice resulting in reconnection of twice the
1156 // same outbound connection. The issue is fixed, but adding
1157 // defensive code above that if we did not register this connection
1158 // because we already have an outbound for this name, then
1159 // close this connection (and make sure it does not try to reconnect)
1160 c.setNoReconnect()
1161 c.closeConnection(WrongGateway)
1162 return
1163 }
1164 } else if info.GatewayCmd > 0 {
1165 switch info.GatewayCmd {
1166 case gatewayCmdAllSubsStart:
1167 c.gatewayAllSubsReceiveStart(info)
1168 return
1169 case gatewayCmdAllSubsComplete:
1170 c.gatewayAllSubsReceiveComplete(info)
1171 return
1172 default:
1173 s.Warnf("Received unknown command %v from gateway %q", info.GatewayCmd, gwName)
1174 return
1175 }
1176 }
1177
1178 // Flood local cluster with information about this gateway.
1179 // Servers in this cluster will ensure that they have (or otherwise create)
1180 // an outbound connection to this gateway.
1181 s.forwardNewGatewayToLocalCluster(info)
1182
1183 } else if isFirstINFO {
1184 // This is the first INFO of an inbound connection...
1185
1186 // Check for duplicate server name with servers in our cluster
1187 if s.isDuplicateServerName(info.Name) {
1188 c.Errorf("Remote server has a duplicate name: %q", info.Name)
1189 c.closeConnection(DuplicateServerName)
1190 return
1191 }
1192
1193 s.registerInboundGatewayConnection(cid, c)
1194 c.Noticef("Inbound gateway connection from %q (%s) registered", info.Gateway, info.ID)
1195
1196 // Now that it is registered, we can remove from temp map.
1197 s.removeFromTempClients(cid)
1198
1199 // Send our QSubs.
1200 s.sendQueueSubsToGateway(c)
1201
1202 // Initiate outbound connection. This function will behave correctly if
1203 // we have already one.
1204 s.processImplicitGateway(info)
1205
1206 // Send back to the server that initiated this gateway connection the
1207 // list of all remote gateways known on this server.
1208 s.gossipGatewaysToInboundGateway(info.Gateway, c)
1209
1210 // Now make sure if we have any knowledge of connected leafnodes that we resend the
1211 // connect events to switch those accounts into interest only mode.
1212 s.mu.Lock()
1213 s.ensureGWsInterestOnlyForLeafNodes()
1214 s.mu.Unlock()
1215 js := s.js.Load()
1216
1217 // If running in some tests, maintain the original behavior.
1218 if gwDoNotForceInterestOnlyMode && js != nil {
1219 // Switch JetStream accounts to interest-only mode.
1220 var accounts []string
1221 js.mu.Lock()
1222 if len(js.accounts) > 0 {
1223 accounts = make([]string, 0, len(js.accounts))
1224 for accName := range js.accounts {
1225 accounts = append(accounts, accName)
1226 }
1227 }
1228 js.mu.Unlock()
1229 for _, accName := range accounts {
1230 if acc, err := s.LookupAccount(accName); err == nil && acc != nil {
1231 if acc.JetStreamEnabled() {
1232 s.switchAccountToInterestMode(acc.GetName())
1233 }
1234 }
1235 }
1236 } else if !gwDoNotForceInterestOnlyMode {
1237 // Starting 2.9.0, we are phasing out the optimistic mode, so change
1238 // all accounts to interest-only mode, unless instructed not to do so
1239 // in some tests.
1240 s.accounts.Range(func(_, v any) bool {
1241 acc := v.(*Account)
1242 s.switchAccountToInterestMode(acc.GetName())
1243 return true
1244 })
1245 }
1246 }
1247 }
1248
1249 // Sends to the given inbound gateway connection a gossip INFO protocol
1250 // for each gateway known by this server. This allows for a "full mesh"
1251 // of gateways.
1252 func (s *Server) gossipGatewaysToInboundGateway(gwName string, c *client) {
1253 gw := s.gateway
1254 gw.RLock()
1255 defer gw.RUnlock()
1256 for gwCfgName, cfg := range gw.remotes {
1257 // Skip the gateway that we just created
1258 if gwCfgName == gwName {
1259 continue
1260 }
1261 info := Info{
1262 ID: s.info.ID,
1263 GatewayCmd: gatewayCmdGossip,
1264 }
1265 urls := cfg.getURLsAsStrings()
1266 if len(urls) > 0 {
1267 info.Gateway = gwCfgName
1268 info.GatewayURLs = urls
1269 b, _ := json.Marshal(&info)
1270 c.mu.Lock()
1271 c.enqueueProto([]byte(fmt.Sprintf(InfoProto, b)))
1272 c.mu.Unlock()
1273 }
1274 }
1275 }
1276
1277 // Sends the INFO protocol of a gateway to all routes known by this server.
1278 func (s *Server) forwardNewGatewayToLocalCluster(oinfo *Info) {
1279 // Need to protect s.routes here, so use server's lock
1280 s.mu.Lock()
1281 defer s.mu.Unlock()
1282
1283 // We don't really need the ID to be set, but, we need to make sure
1284 // that it is not set to the server ID so that if we were to connect
1285 // to an older server that does not expect a "gateway" INFO, it
1286 // would think that it needs to create an implicit route (since info.ID
1287 // would not match the route's remoteID), but will fail to do so because
1288 // the sent protocol will not have host/port defined.
1289 info := &Info{
1290 ID: "GW" + s.info.ID,
1291 Name: s.getOpts().ServerName,
1292 Gateway: oinfo.Gateway,
1293 GatewayURLs: oinfo.GatewayURLs,
1294 GatewayCmd: gatewayCmdGossip,
1295 }
1296 b, _ := json.Marshal(info)
1297 infoJSON := []byte(fmt.Sprintf(InfoProto, b))
1298
1299 s.forEachRemote(func(r *client) {
1300 r.mu.Lock()
1301 r.enqueueProto(infoJSON)
1302 r.mu.Unlock()
1303 })
1304 }
1305
1306 // Sends queue subscriptions interest to remote gateway.
1307 // This is sent from the inbound side, that is, the side that receives
1308 // messages from the remote's outbound connection. This side is
1309 // the one sending the subscription interest.
1310 func (s *Server) sendQueueSubsToGateway(c *client) {
1311 s.sendSubsToGateway(c, _EMPTY_)
1312 }
1313
1314 // Sends all subscriptions for the given account to the remove gateway
1315 // This is sent from the inbound side, that is, the side that receives
1316 // messages from the remote's outbound connection. This side is
1317 // the one sending the subscription interest.
1318 func (s *Server) sendAccountSubsToGateway(c *client, accName string) {
1319 s.sendSubsToGateway(c, accName)
1320 }
1321
1322 func gwBuildSubProto(buf *bytes.Buffer, accName string, acc map[string]*sitally, doQueues bool) {
1323 for saq, si := range acc {
1324 if doQueues && si.q || !doQueues && !si.q {
1325 buf.Write(rSubBytes)
1326 buf.WriteString(accName)
1327 buf.WriteByte(' ')
1328 // For queue subs (si.q is true), saq will be
1329 // subject + ' ' + queue, for plain subs, this is
1330 // just the subject.
1331 buf.WriteString(saq)
1332 if doQueues {
1333 buf.WriteString(" 1")
1334 }
1335 buf.WriteString(CR_LF)
1336 }
1337 }
1338 }
1339
1340 // Sends subscriptions to remote gateway.
1341 func (s *Server) sendSubsToGateway(c *client, accountName string) {
1342 var (
1343 bufa = [32 * 1024]byte{}
1344 bbuf = bytes.NewBuffer(bufa[:0])
1345 )
1346
1347 gw := s.gateway
1348
1349 // This needs to run under this lock for the whole duration
1350 gw.pasi.Lock()
1351 defer gw.pasi.Unlock()
1352
1353 // If account is specified...
1354 if accountName != _EMPTY_ {
1355 // Simply send all plain subs (no queues) for this specific account
1356 gwBuildSubProto(bbuf, accountName, gw.pasi.m[accountName], false)
1357 // Instruct to send all subs (RS+/-) for this account from now on.
1358 c.mu.Lock()
1359 e := c.gw.insim[accountName]
1360 if e == nil {
1361 e = &insie{}
1362 c.gw.insim[accountName] = e
1363 }
1364 e.mode = InterestOnly
1365 c.mu.Unlock()
1366 } else {
1367 // Send queues for all accounts
1368 for accName, acc := range gw.pasi.m {
1369 gwBuildSubProto(bbuf, accName, acc, true)
1370 }
1371 }
1372
1373 buf := bbuf.Bytes()
1374
1375 // Nothing to send.
1376 if len(buf) == 0 {
1377 return
1378 }
1379 if len(buf) > cap(bufa) {
1380 s.Debugf("Sending subscriptions to %q, buffer size: %v", c.gw.name, len(buf))
1381 }
1382 // Send
1383 c.mu.Lock()
1384 c.enqueueProto(buf)
1385 c.Debugf("Sent queue subscriptions to gateway")
1386 c.mu.Unlock()
1387 }
1388
1389 // This is invoked when getting an INFO protocol for gateway on the ROUTER port.
1390 // This function will then execute appropriate function based on the command
1391 // contained in the protocol.
1392 // <Invoked from a route connection's readLoop>
1393 func (s *Server) processGatewayInfoFromRoute(info *Info, routeSrvID string) {
1394 switch info.GatewayCmd {
1395 case gatewayCmdGossip:
1396 s.processImplicitGateway(info)
1397 default:
1398 s.Errorf("Unknown command %d from server %v", info.GatewayCmd, routeSrvID)
1399 }
1400 }
1401
1402 // Sends INFO protocols to the given route connection for each known Gateway.
1403 // These will be processed by the route and delegated to the gateway code to
1404 // invoke processImplicitGateway.
1405 func (s *Server) sendGatewayConfigsToRoute(route *client) {
1406 gw := s.gateway
1407 gw.RLock()
1408 // Send only to gateways for which we have actual outbound connection to.
1409 if len(gw.out) == 0 {
1410 gw.RUnlock()
1411 return
1412 }
1413 // Collect gateway configs for which we have an outbound connection.
1414 gwCfgsa := [16]*gatewayCfg{}
1415 gwCfgs := gwCfgsa[:0]
1416 for _, c := range gw.out {
1417 c.mu.Lock()
1418 if c.gw.cfg != nil {
1419 gwCfgs = append(gwCfgs, c.gw.cfg)
1420 }
1421 c.mu.Unlock()
1422 }
1423 gw.RUnlock()
1424 if len(gwCfgs) == 0 {
1425 return
1426 }
1427
1428 // Check forwardNewGatewayToLocalCluster() as to why we set ID this way.
1429 info := Info{
1430 ID: "GW" + s.info.ID,
1431 GatewayCmd: gatewayCmdGossip,
1432 }
1433 for _, cfg := range gwCfgs {
1434 urls := cfg.getURLsAsStrings()
1435 if len(urls) > 0 {
1436 info.Gateway = cfg.Name
1437 info.GatewayURLs = urls
1438 b, _ := json.Marshal(&info)
1439 route.mu.Lock()
1440 route.enqueueProto([]byte(fmt.Sprintf(InfoProto, b)))
1441 route.mu.Unlock()
1442 }
1443 }
1444 }
1445
1446 // Initiates a gateway connection using the info contained in the INFO protocol.
1447 // If a gateway with the same name is already registered (either because explicitly
1448 // configured, or already implicitly connected), this function will augmment the
1449 // remote URLs with URLs present in the info protocol and return.
1450 // Otherwise, this function will register this remote (to prevent multiple connections
1451 // to the same remote) and call solicitGateway (which will run in a different go-routine).
1452 func (s *Server) processImplicitGateway(info *Info) {
1453 s.gateway.Lock()
1454 defer s.gateway.Unlock()
1455 // Name of the gateway to connect to is the Info.Gateway field.
1456 gwName := info.Gateway
1457 // If this is our name, bail.
1458 if gwName == s.gateway.name {
1459 return
1460 }
1461 // Check if we already have this config, and if so, we are done
1462 cfg := s.gateway.remotes[gwName]
1463 if cfg != nil {
1464 // However, possibly augment the list of URLs with the given
1465 // info.GatewayURLs content.
1466 cfg.Lock()
1467 cfg.addURLs(info.GatewayURLs)
1468 cfg.Unlock()
1469 return
1470 }
1471 opts := s.getOpts()
1472 cfg = &gatewayCfg{
1473 RemoteGatewayOpts: &RemoteGatewayOpts{Name: gwName},
1474 hash: getGWHash(gwName),
1475 oldHash: getOldHash(gwName),
1476 urls: make(map[string]*url.URL, len(info.GatewayURLs)),
1477 implicit: true,
1478 }
1479 if opts.Gateway.TLSConfig != nil {
1480 cfg.TLSConfig = opts.Gateway.TLSConfig.Clone()
1481 cfg.TLSTimeout = opts.Gateway.TLSTimeout
1482 }
1483
1484 // Since we know we don't have URLs (no config, so just based on what we
1485 // get from INFO), directly call addURLs(). We don't need locking since
1486 // we just created that structure and no one else has access to it yet.
1487 cfg.addURLs(info.GatewayURLs)
1488 // If there is no URL, we can't proceed.
1489 if len(cfg.urls) == 0 {
1490 return
1491 }
1492 s.gateway.remotes[gwName] = cfg
1493 s.startGoRoutine(func() {
1494 s.solicitGateway(cfg, true)
1495 s.grWG.Done()
1496 })
1497 }
1498
1499 // NumOutboundGateways is public here mostly for testing.
1500 func (s *Server) NumOutboundGateways() int {
1501 return s.numOutboundGateways()
1502 }
1503
1504 // Returns the number of outbound gateway connections
1505 func (s *Server) numOutboundGateways() int {
1506 s.gateway.RLock()
1507 n := len(s.gateway.out)
1508 s.gateway.RUnlock()
1509 return n
1510 }
1511
1512 // Returns the number of inbound gateway connections
1513 func (s *Server) numInboundGateways() int {
1514 s.gateway.RLock()
1515 n := len(s.gateway.in)
1516 s.gateway.RUnlock()
1517 return n
1518 }
1519
1520 // Returns the remoteGateway (if any) that has the given `name`
1521 func (s *Server) getRemoteGateway(name string) *gatewayCfg {
1522 s.gateway.RLock()
1523 cfg := s.gateway.remotes[name]
1524 s.gateway.RUnlock()
1525 return cfg
1526 }
1527
1528 // Used in tests
1529 func (g *gatewayCfg) bumpConnAttempts() {
1530 g.Lock()
1531 g.connAttempts++
1532 g.Unlock()
1533 }
1534
1535 // Used in tests
1536 func (g *gatewayCfg) getConnAttempts() int {
1537 g.Lock()
1538 ca := g.connAttempts
1539 g.Unlock()
1540 return ca
1541 }
1542
1543 // Used in tests
1544 func (g *gatewayCfg) resetConnAttempts() {
1545 g.Lock()
1546 g.connAttempts = 0
1547 g.Unlock()
1548 }
1549
1550 // Returns if this remote gateway is implicit or not.
1551 func (g *gatewayCfg) isImplicit() bool {
1552 g.RLock()
1553 ii := g.implicit
1554 g.RUnlock()
1555 return ii
1556 }
1557
1558 // getURLs returns an array of URLs in random order suitable for
1559 // an iteration to try to connect.
1560 func (g *gatewayCfg) getURLs() []*url.URL {
1561 g.RLock()
1562 a := make([]*url.URL, 0, len(g.urls))
1563 for _, u := range g.urls {
1564 a = append(a, u)
1565 }
1566 g.RUnlock()
1567 // Map iteration is random, but not that good with small maps.
1568 rand.Shuffle(len(a), func(i, j int) {
1569 a[i], a[j] = a[j], a[i]
1570 })
1571 return a
1572 }
1573
1574 // Similar to getURLs but returns the urls as an array of strings.
1575 func (g *gatewayCfg) getURLsAsStrings() []string {
1576 g.RLock()
1577 a := make([]string, 0, len(g.urls))
1578 for _, u := range g.urls {
1579 a = append(a, u.Host)
1580 }
1581 g.RUnlock()
1582 return a
1583 }
1584
1585 // updateURLs creates the urls map with the content of the config's URLs array
1586 // and the given array that we get from the INFO protocol.
1587 func (g *gatewayCfg) updateURLs(infoURLs []string) {
1588 g.Lock()
1589 // Clear the map...
1590 g.urls = make(map[string]*url.URL, len(g.URLs)+len(infoURLs))
1591 // Add the urls from the config URLs array.
1592 for _, u := range g.URLs {
1593 g.urls[u.Host] = u
1594 }
1595 // Then add the ones from the infoURLs array we got.
1596 g.addURLs(infoURLs)
1597 // The call above will set varzUpdateURLs only when finding ULRs in infoURLs
1598 // that are not present in the config. That does not cover the case where
1599 // previously "discovered" URLs are now gone. We could check "before" size
1600 // of g.urls and if bigger than current size, set the boolean to true.
1601 // Not worth it... simply set this to true to allow a refresh of gateway
1602 // URLs in varz.
1603 g.varzUpdateURLs = true
1604 g.Unlock()
1605 }
1606
1607 // Saves the hostname of the given URL (if not already done).
1608 // This may be used as the ServerName of the TLSConfig when initiating a
1609 // TLS connection.
1610 // Write lock held on entry.
1611 func (g *gatewayCfg) saveTLSHostname(u *url.URL) {
1612 if g.TLSConfig != nil && g.tlsName == "" && net.ParseIP(u.Hostname()) == nil {
1613 g.tlsName = u.Hostname()
1614 }
1615 }
1616
1617 // add URLs from the given array to the urls map only if not already present.
1618 // remoteGateway write lock is assumed to be held on entry.
1619 // Write lock is held on entry.
1620 func (g *gatewayCfg) addURLs(infoURLs []string) {
1621 var scheme string
1622 if g.TLSConfig != nil {
1623 scheme = "tls"
1624 } else {
1625 scheme = "nats"
1626 }
1627 for _, iu := range infoURLs {
1628 if _, present := g.urls[iu]; !present {
1629 // Urls in Info.GatewayURLs come without scheme. Add it to parse
1630 // the url (otherwise it fails).
1631 if u, err := url.Parse(fmt.Sprintf("%s://%s", scheme, iu)); err == nil {
1632 // Also, if a tlsName has not been set yet and we are dealing
1633 // with a hostname and not a bare IP, save the hostname.
1634 g.saveTLSHostname(u)
1635 // Use u.Host for the key.
1636 g.urls[u.Host] = u
1637 // Signal that we have updated the list. Used by monitoring code.
1638 g.varzUpdateURLs = true
1639 }
1640 }
1641 }
1642 }
1643
1644 // Adds this URL to the set of Gateway URLs.
1645 // Returns true if the URL has been added, false otherwise.
1646 // Server lock held on entry
1647 func (s *Server) addGatewayURL(urlStr string) bool {
1648 s.gateway.Lock()
1649 added := s.gateway.URLs.addUrl(urlStr)
1650 if added {
1651 s.gateway.generateInfoJSON()
1652 }
1653 s.gateway.Unlock()
1654 return added
1655 }
1656
1657 // Removes this URL from the set of gateway URLs.
1658 // Returns true if the URL has been removed, false otherwise.
1659 // Server lock held on entry
1660 func (s *Server) removeGatewayURL(urlStr string) bool {
1661 if s.isShuttingDown() {
1662 return false
1663 }
1664 s.gateway.Lock()
1665 removed := s.gateway.URLs.removeUrl(urlStr)
1666 if removed {
1667 s.gateway.generateInfoJSON()
1668 }
1669 s.gateway.Unlock()
1670 return removed
1671 }
1672
1673 // Sends a Gateway's INFO to all inbound GW connections.
1674 // Server lock is held on entry
1675 func (s *Server) sendAsyncGatewayInfo() {
1676 s.gateway.RLock()
1677 for _, ig := range s.gateway.in {
1678 ig.mu.Lock()
1679 ig.enqueueProto(s.gateway.infoJSON)
1680 ig.mu.Unlock()
1681 }
1682 s.gateway.RUnlock()
1683 }
1684
1685 // This returns the URL of the Gateway listen spec, or empty string
1686 // if the server has no gateway configured.
1687 func (s *Server) getGatewayURL() string {
1688 s.gateway.RLock()
1689 url := s.gateway.URL
1690 s.gateway.RUnlock()
1691 return url
1692 }
1693
1694 // Returns this server gateway name.
1695 // Same than calling s.gateway.getName()
1696 func (s *Server) getGatewayName() string {
1697 // This is immutable
1698 return s.gateway.name
1699 }
1700
1701 // All gateway connections (outbound and inbound) are put in the given map.
1702 func (s *Server) getAllGatewayConnections(conns map[uint64]*client) {
1703 gw := s.gateway
1704 gw.RLock()
1705 for _, c := range gw.out {
1706 c.mu.Lock()
1707 cid := c.cid
1708 c.mu.Unlock()
1709 conns[cid] = c
1710 }
1711 for cid, c := range gw.in {
1712 conns[cid] = c
1713 }
1714 gw.RUnlock()
1715 }
1716
1717 // Register the given gateway connection (*client) in the inbound gateways
1718 // map. The key is the connection ID (like for clients and routes).
1719 func (s *Server) registerInboundGatewayConnection(cid uint64, gwc *client) {
1720 s.gateway.Lock()
1721 s.gateway.in[cid] = gwc
1722 s.gateway.Unlock()
1723 }
1724
1725 // Register the given gateway connection (*client) in the outbound gateways
1726 // map with the given name as the key.
1727 func (s *Server) registerOutboundGatewayConnection(name string, gwc *client) bool {
1728 s.gateway.Lock()
1729 if _, exist := s.gateway.out[name]; exist {
1730 s.gateway.Unlock()
1731 return false
1732 }
1733 s.gateway.out[name] = gwc
1734 s.gateway.outo = append(s.gateway.outo, gwc)
1735 s.gateway.orderOutboundConnectionsLocked()
1736 s.gateway.Unlock()
1737 return true
1738 }
1739
1740 // Returns the outbound gateway connection (*client) with the given name,
1741 // or nil if not found
1742 func (s *Server) getOutboundGatewayConnection(name string) *client {
1743 s.gateway.RLock()
1744 gwc := s.gateway.out[name]
1745 s.gateway.RUnlock()
1746 return gwc
1747 }
1748
1749 // Returns all outbound gateway connections in the provided array.
1750 // The order of the gateways is suited for the sending of a message.
1751 // Current ordering is based on individual gateway's RTT value.
1752 func (s *Server) getOutboundGatewayConnections(a *[]*client) {
1753 s.gateway.RLock()
1754 for i := 0; i < len(s.gateway.outo); i++ {
1755 *a = append(*a, s.gateway.outo[i])
1756 }
1757 s.gateway.RUnlock()
1758 }
1759
1760 // Orders the array of outbound connections.
1761 // Current ordering is by lowest RTT.
1762 // Gateway write lock is held on entry
1763 func (g *srvGateway) orderOutboundConnectionsLocked() {
1764 // Order the gateways by lowest RTT
1765 slices.SortFunc(g.outo, func(i, j *client) int { return cmp.Compare(i.getRTTValue(), j.getRTTValue()) })
1766 }
1767
1768 // Orders the array of outbound connections.
1769 // Current ordering is by lowest RTT.
1770 func (g *srvGateway) orderOutboundConnections() {
1771 g.Lock()
1772 g.orderOutboundConnectionsLocked()
1773 g.Unlock()
1774 }
1775
1776 // Returns all inbound gateway connections in the provided array
1777 func (s *Server) getInboundGatewayConnections(a *[]*client) {
1778 s.gateway.RLock()
1779 for _, gwc := range s.gateway.in {
1780 *a = append(*a, gwc)
1781 }
1782 s.gateway.RUnlock()
1783 }
1784
1785 // This is invoked when a gateway connection is closed and the server
1786 // is removing this connection from its state.
1787 func (s *Server) removeRemoteGatewayConnection(c *client) {
1788 c.mu.Lock()
1789 cid := c.cid
1790 isOutbound := c.gw.outbound
1791 gwName := c.gw.name
1792 if isOutbound && c.gw.outsim != nil {
1793 // We do this to allow the GC to release this connection.
1794 // Since the map is used by the rest of the code without client lock,
1795 // we can't simply set it to nil, instead, just make sure we empty it.
1796 c.gw.outsim.Range(func(k, _ any) bool {
1797 c.gw.outsim.Delete(k)
1798 return true
1799 })
1800 }
1801 c.mu.Unlock()
1802
1803 gw := s.gateway
1804 gw.Lock()
1805 if isOutbound {
1806 delete(gw.out, gwName)
1807 louto := len(gw.outo)
1808 reorder := false
1809 for i := 0; i < len(gw.outo); i++ {
1810 if gw.outo[i] == c {
1811 // If last, simply remove and no need to reorder
1812 if i != louto-1 {
1813 gw.outo[i] = gw.outo[louto-1]
1814 reorder = true
1815 }
1816 gw.outo = gw.outo[:louto-1]
1817 }
1818 }
1819 if reorder {
1820 gw.orderOutboundConnectionsLocked()
1821 }
1822 } else {
1823 delete(gw.in, cid)
1824 }
1825 gw.Unlock()
1826 s.removeFromTempClients(cid)
1827
1828 if isOutbound {
1829 // Update number of totalQSubs for this gateway
1830 qSubsRemoved := int64(0)
1831 c.mu.Lock()
1832 for _, sub := range c.subs {
1833 if sub.queue != nil {
1834 qSubsRemoved++
1835 }
1836 }
1837 c.subs = nil
1838 c.mu.Unlock()
1839 // Update total count of qsubs in remote gateways.
1840 atomic.AddInt64(&c.srv.gateway.totalQSubs, -qSubsRemoved)
1841
1842 } else {
1843 var subsa [1024]*subscription
1844 var subs = subsa[:0]
1845
1846 // For inbound GW connection, if we have subs, those are
1847 // local subs on "_R_." subjects.
1848 c.mu.Lock()
1849 for _, sub := range c.subs {
1850 subs = append(subs, sub)
1851 }
1852 c.subs = nil
1853 c.mu.Unlock()
1854 for _, sub := range subs {
1855 c.removeReplySub(sub)
1856 }
1857 }
1858 }
1859
1860 // GatewayAddr returns the net.Addr object for the gateway listener.
1861 func (s *Server) GatewayAddr() *net.TCPAddr {
1862 s.mu.Lock()
1863 defer s.mu.Unlock()
1864 if s.gatewayListener == nil {
1865 return nil
1866 }
1867 return s.gatewayListener.Addr().(*net.TCPAddr)
1868 }
1869
1870 // A- protocol received from the remote after sending messages
1871 // on an account that it has no interest in. Mark this account
1872 // with a "no interest" marker to prevent further messages send.
1873 // <Invoked from outbound connection's readLoop>
1874 func (c *client) processGatewayAccountUnsub(accName string) {
1875 // Just to indicate activity around "subscriptions" events.
1876 c.in.subs++
1877 // This account may have an entry because of queue subs.
1878 // If that's the case, we can reset the no-interest map,
1879 // but not set the entry to nil.
1880 setToNil := true
1881 if ei, ok := c.gw.outsim.Load(accName); ei != nil {
1882 e := ei.(*outsie)
1883 e.Lock()
1884 // Reset the no-interest map if we have queue subs
1885 // and don't set the entry to nil.
1886 if e.qsubs > 0 {
1887 e.ni = make(map[string]struct{})
1888 setToNil = false
1889 }
1890 e.Unlock()
1891 } else if ok {
1892 // Already set to nil, so skip
1893 setToNil = false
1894 }
1895 if setToNil {
1896 c.gw.outsim.Store(accName, nil)
1897 }
1898 }
1899
1900 // A+ protocol received from remote gateway if it had previously
1901 // sent an A-. Clear the "no interest" marker for this account.
1902 // <Invoked from outbound connection's readLoop>
1903 func (c *client) processGatewayAccountSub(accName string) error {
1904 // Just to indicate activity around "subscriptions" events.
1905 c.in.subs++
1906 // If this account has an entry because of queue subs, we
1907 // can't delete the entry.
1908 remove := true
1909 if ei, ok := c.gw.outsim.Load(accName); ei != nil {
1910 e := ei.(*outsie)
1911 e.Lock()
1912 if e.qsubs > 0 {
1913 remove = false
1914 }
1915 e.Unlock()
1916 } else if !ok {
1917 // There is no entry, so skip
1918 remove = false
1919 }
1920 if remove {
1921 c.gw.outsim.Delete(accName)
1922 }
1923 return nil
1924 }
1925
1926 // RS- protocol received from the remote after sending messages
1927 // on a subject that it has no interest in (but knows about the
1928 // account). Mark this subject with a "no interest" marker to
1929 // prevent further messages being sent.
1930 // If in modeInterestOnly or for a queue sub, remove from
1931 // the sublist if present.
1932 // <Invoked from outbound connection's readLoop>
1933 func (c *client) processGatewayRUnsub(arg []byte) error {
1934 _, accName, subject, queue, err := c.parseUnsubProto(arg, true, false)
1935 if err != nil {
1936 return fmt.Errorf("processGatewaySubjectUnsub %s", err.Error())
1937 }
1938
1939 var (
1940 e *outsie
1941 useSl bool
1942 newe bool
1943 callUpdate bool
1944 srv *Server
1945 sub *subscription
1946 )
1947
1948 // Possibly execute this on exit after all locks have been released.
1949 // If callUpdate is true, srv and sub will be not nil.
1950 defer func() {
1951 if callUpdate {
1952 srv.updateInterestForAccountOnGateway(accName, sub, -1)
1953 }
1954 }()
1955
1956 c.mu.Lock()
1957 if c.gw.outsim == nil {
1958 c.Errorf("Received RS- from gateway on inbound connection")
1959 c.mu.Unlock()
1960 c.closeConnection(ProtocolViolation)
1961 return nil
1962 }
1963 defer c.mu.Unlock()
1964 // If closed, c.subs map will be nil, so bail out.
1965 if c.isClosed() {
1966 return nil
1967 }
1968
1969 ei, _ := c.gw.outsim.Load(accName)
1970 if ei != nil {
1971 e = ei.(*outsie)
1972 e.Lock()
1973 defer e.Unlock()
1974 // If there is an entry, for plain sub we need
1975 // to know if we should store the sub
1976 useSl = queue != nil || e.mode != Optimistic
1977 } else if queue != nil {
1978 // should not even happen...
1979 c.Debugf("Received RS- without prior RS+ for subject %q, queue %q", subject, queue)
1980 return nil
1981 } else {
1982 // Plain sub, assume optimistic sends, create entry.
1983 e = &outsie{ni: make(map[string]struct{}), sl: NewSublistForServer(c.srv)}
1984 newe = true
1985 }
1986 // This is when a sub or queue sub is supposed to be in
1987 // the sublist. Look for it and remove.
1988 if useSl {
1989 var ok bool
1990 key := arg
1991 // m[string()] does not cause mem allocation
1992 sub, ok = c.subs[string(key)]
1993 // if RS- for a sub that we don't have, just ignore.
1994 if !ok {
1995 return nil
1996 }
1997 if e.sl.Remove(sub) == nil {
1998 delete(c.subs, bytesToString(key))
1999 if queue != nil {
2000 e.qsubs--
2001 atomic.AddInt64(&c.srv.gateway.totalQSubs, -1)
2002 }
2003 // If last, we can remove the whole entry only
2004 // when in optimistic mode and there is no element
2005 // in the `ni` map.
2006 if e.sl.Count() == 0 && e.mode == Optimistic && len(e.ni) == 0 {
2007 c.gw.outsim.Delete(accName)
2008 }
2009 }
2010 // We are going to call updateInterestForAccountOnGateway on exit.
2011 srv = c.srv
2012 callUpdate = true
2013 } else {
2014 e.ni[string(subject)] = struct{}{}
2015 if newe {
2016 c.gw.outsim.Store(accName, e)
2017 }
2018 }
2019 return nil
2020 }
2021
2022 // For plain subs, RS+ protocol received from remote gateway if it
2023 // had previously sent a RS-. Clear the "no interest" marker for
2024 // this subject (under this account).
2025 // For queue subs, or if in modeInterestOnly, register interest
2026 // from remote gateway.
2027 // <Invoked from outbound connection's readLoop>
2028 func (c *client) processGatewayRSub(arg []byte) error {
2029 // Indicate activity.
2030 c.in.subs++
2031
2032 var (
2033 queue []byte
2034 qw int32
2035 )
2036
2037 args := splitArg(arg)
2038 switch len(args) {
2039 case 2:
2040 case 4:
2041 queue = args[2]
2042 qw = int32(parseSize(args[3]))
2043 default:
2044 return fmt.Errorf("processGatewaySubjectSub Parse Error: '%s'", arg)
2045 }
2046 accName := args[0]
2047 subject := args[1]
2048
2049 var (
2050 e *outsie
2051 useSl bool
2052 newe bool
2053 callUpdate bool
2054 srv *Server
2055 sub *subscription
2056 )
2057
2058 // Possibly execute this on exit after all locks have been released.
2059 // If callUpdate is true, srv and sub will be not nil.
2060 defer func() {
2061 if callUpdate {
2062 srv.updateInterestForAccountOnGateway(string(accName), sub, 1)
2063 }
2064 }()
2065
2066 c.mu.Lock()
2067 if c.gw.outsim == nil {
2068 c.Errorf("Received RS+ from gateway on inbound connection")
2069 c.mu.Unlock()
2070 c.closeConnection(ProtocolViolation)
2071 return nil
2072 }
2073 defer c.mu.Unlock()
2074 // If closed, c.subs map will be nil, so bail out.
2075 if c.isClosed() {
2076 return nil
2077 }
2078
2079 ei, _ := c.gw.outsim.Load(bytesToString(accName))
2080 // We should always have an existing entry for plain subs because
2081 // in optimistic mode we would have received RS- first, and
2082 // in full knowledge, we are receiving RS+ for an account after
2083 // getting many RS- from the remote..
2084 if ei != nil {
2085 e = ei.(*outsie)
2086 e.Lock()
2087 defer e.Unlock()
2088 useSl = queue != nil || e.mode != Optimistic
2089 } else if queue == nil {
2090 return nil
2091 } else {
2092 e = &outsie{ni: make(map[string]struct{}), sl: NewSublistForServer(c.srv)}
2093 newe = true
2094 useSl = true
2095 }
2096 if useSl {
2097 var key []byte
2098 // We store remote subs by account/subject[/queue].
2099 // For queue, remove the trailing weight
2100 if queue != nil {
2101 key = arg[:len(arg)-len(args[3])-1]
2102 } else {
2103 key = arg
2104 }
2105 // If RS+ for a sub that we already have, ignore.
2106 // (m[string()] does not allocate memory)
2107 if _, ok := c.subs[string(key)]; ok {
2108 return nil
2109 }
2110 // new subscription. copy subject (and queue) to
2111 // not reference the underlying possibly big buffer.
2112 var csubject []byte
2113 var cqueue []byte
2114 if queue != nil {
2115 // make single allocation and use different slices
2116 // to point to subject and queue name.
2117 cbuf := make([]byte, len(subject)+1+len(queue))
2118 copy(cbuf, key[len(accName)+1:])
2119 csubject = cbuf[:len(subject)]
2120 cqueue = cbuf[len(subject)+1:]
2121 } else {
2122 csubject = make([]byte, len(subject))
2123 copy(csubject, subject)
2124 }
2125 sub = &subscription{client: c, subject: csubject, queue: cqueue, qw: qw}
2126 // If no error inserting in sublist...
2127 if e.sl.Insert(sub) == nil {
2128 c.subs[string(key)] = sub
2129 if queue != nil {
2130 e.qsubs++
2131 atomic.AddInt64(&c.srv.gateway.totalQSubs, 1)
2132 }
2133 if newe {
2134 c.gw.outsim.Store(string(accName), e)
2135 }
2136 }
2137 // We are going to call updateInterestForAccountOnGateway on exit.
2138 srv = c.srv
2139 callUpdate = true
2140 } else {
2141 subj := bytesToString(subject)
2142 // If this is an RS+ for a wc subject, then
2143 // remove from the no interest map all subjects
2144 // that are a subset of this wc subject.
2145 if subjectHasWildcard(subj) {
2146 for k := range e.ni {
2147 if subjectIsSubsetMatch(k, subj) {
2148 delete(e.ni, k)
2149 }
2150 }
2151 } else {
2152 delete(e.ni, subj)
2153 }
2154 }
2155 return nil
2156 }
2157
2158 // Returns true if this gateway has possible interest in the
2159 // given account/subject (which means, it does not have a registered
2160 // no-interest on the account and/or subject) and the sublist result
2161 // for queue subscriptions.
2162 // <Outbound connection: invoked when client message is published,
2163 // so from any client connection's readLoop>
2164 func (c *client) gatewayInterest(acc string, subj []byte) (bool, *SublistResult) {
2165 ei, accountInMap := c.gw.outsim.Load(acc)
2166 // If there is an entry for this account and ei is nil,
2167 // it means that the remote is not interested at all in
2168 // this account and we could not possibly have queue subs.
2169 if accountInMap && ei == nil {
2170 return false, nil
2171 }
2172 // Assume interest if account not in map, unless we support
2173 // only interest-only mode.
2174 psi := !accountInMap && !c.gw.interestOnlyMode
2175 var r *SublistResult
2176 if accountInMap {
2177 // If in map, check for subs interest with sublist.
2178 e := ei.(*outsie)
2179 e.RLock()
2180 // Unless each side has agreed on interest-only mode,
2181 // we may be in transition to modeInterestOnly
2182 // but until e.ni is nil, use it to know if we
2183 // should suppress interest or not.
2184 if !c.gw.interestOnlyMode && e.ni != nil {
2185 if _, inMap := e.ni[string(subj)]; !inMap {
2186 psi = true
2187 }
2188 }
2189 // If we are in modeInterestOnly (e.ni will be nil)
2190 // or if we have queue subs, we also need to check sl.Match.
2191 if e.ni == nil || e.qsubs > 0 {
2192 r = e.sl.MatchBytes(subj)
2193 if len(r.psubs) > 0 {
2194 psi = true
2195 }
2196 }
2197 e.RUnlock()
2198 // Since callers may just check if the sublist result is nil or not,
2199 // make sure that if what is returned by sl.Match() is the emptyResult, then
2200 // we return nil to the caller.
2201 if r == emptyResult {
2202 r = nil
2203 }
2204 }
2205 return psi, r
2206 }
2207
2208 // switchAccountToInterestMode will switch an account over to interestMode.
2209 // Lock should NOT be held.
2210 func (s *Server) switchAccountToInterestMode(accName string) {
2211 gwsa := [16]*client{}
2212 gws := gwsa[:0]
2213 s.getInboundGatewayConnections(&gws)
2214
2215 for _, gin := range gws {
2216 var e *insie
2217 var ok bool
2218
2219 gin.mu.Lock()
2220 if e, ok = gin.gw.insim[accName]; !ok || e == nil {
2221 e = &insie{}
2222 gin.gw.insim[accName] = e
2223 }
2224 // Do it only if we are in Optimistic mode
2225 if e.mode == Optimistic {
2226 gin.gatewaySwitchAccountToSendAllSubs(e, accName)
2227 }
2228 gin.mu.Unlock()
2229 }
2230 }
2231
2232 // This is invoked when registering (or unregistering) the first
2233 // (or last) subscription on a given account/subject. For each
2234 // GWs inbound connections, we will check if we need to send an RS+ or A+
2235 // protocol.
2236 func (s *Server) maybeSendSubOrUnsubToGateways(accName string, sub *subscription, added bool) {
2237 if sub.queue != nil {
2238 return
2239 }
2240 gwsa := [16]*client{}
2241 gws := gwsa[:0]
2242 s.getInboundGatewayConnections(&gws)
2243 if len(gws) == 0 {
2244 return
2245 }
2246 var (
2247 rsProtoa [512]byte
2248 rsProto []byte
2249 accProtoa [256]byte
2250 accProto []byte
2251 proto []byte
2252 subject = bytesToString(sub.subject)
2253 hasWC = subjectHasWildcard(subject)
2254 )
2255 for _, c := range gws {
2256 proto = nil
2257 c.mu.Lock()
2258 e, inMap := c.gw.insim[accName]
2259 // If there is a inbound subject interest entry...
2260 if e != nil {
2261 sendProto := false
2262 // In optimistic mode, we care only about possibly sending RS+ (or A+)
2263 // so if e.ni is not nil we do things only when adding a new subscription.
2264 if e.ni != nil && added {
2265 // For wildcard subjects, we will remove from our no-interest
2266 // map, all subjects that are a subset of this wc subject, but we
2267 // still send the wc subject and let the remote do its own cleanup.
2268 if hasWC {
2269 for enis := range e.ni {
2270 if subjectIsSubsetMatch(enis, subject) {
2271 delete(e.ni, enis)
2272 sendProto = true
2273 }
2274 }
2275 } else if _, noInterest := e.ni[subject]; noInterest {
2276 delete(e.ni, subject)
2277 sendProto = true
2278 }
2279 } else if e.mode == InterestOnly {
2280 // We are in the mode where we always send RS+/- protocols.
2281 sendProto = true
2282 }
2283 if sendProto {
2284 if rsProto == nil {
2285 // Construct the RS+/- only once
2286 proto = rsProtoa[:0]
2287 if added {
2288 proto = append(proto, rSubBytes...)
2289 } else {
2290 proto = append(proto, rUnsubBytes...)
2291 }
2292 proto = append(proto, accName...)
2293 proto = append(proto, ' ')
2294 proto = append(proto, sub.subject...)
2295 proto = append(proto, CR_LF...)
2296 rsProto = proto
2297 } else {
2298 // Point to the already constructed RS+/-
2299 proto = rsProto
2300 }
2301 }
2302 } else if added && inMap {
2303 // Here, we have a `nil` entry for this account in
2304 // the map, which means that we have previously sent
2305 // an A-. We have a new subscription, so we need to
2306 // send an A+ and delete the entry from the map so
2307 // that we do this only once.
2308 delete(c.gw.insim, accName)
2309 if accProto == nil {
2310 // Construct the A+ only once
2311 proto = accProtoa[:0]
2312 proto = append(proto, aSubBytes...)
2313 proto = append(proto, accName...)
2314 proto = append(proto, CR_LF...)
2315 accProto = proto
2316 } else {
2317 // Point to the already constructed A+
2318 proto = accProto
2319 }
2320 }
2321 if proto != nil {
2322 c.enqueueProto(proto)
2323 if c.trace {
2324 c.traceOutOp("", proto[:len(proto)-LEN_CR_LF])
2325 }
2326 }
2327 c.mu.Unlock()
2328 }
2329 }
2330
2331 // This is invoked when the first (or last) queue subscription on a
2332 // given subject/group is registered (or unregistered). Sent to all
2333 // inbound gateways.
2334 func (s *Server) sendQueueSubOrUnsubToGateways(accName string, qsub *subscription, added bool) {
2335 if qsub.queue == nil {
2336 return
2337 }
2338
2339 gwsa := [16]*client{}
2340 gws := gwsa[:0]
2341 s.getInboundGatewayConnections(&gws)
2342 if len(gws) == 0 {
2343 return
2344 }
2345
2346 var protoa [512]byte
2347 var proto []byte
2348 for _, c := range gws {
2349 if proto == nil {
2350 proto = protoa[:0]
2351 if added {
2352 proto = append(proto, rSubBytes...)
2353 } else {
2354 proto = append(proto, rUnsubBytes...)
2355 }
2356 proto = append(proto, accName...)
2357 proto = append(proto, ' ')
2358 proto = append(proto, qsub.subject...)
2359 proto = append(proto, ' ')
2360 proto = append(proto, qsub.queue...)
2361 if added {
2362 // For now, just use 1 for the weight
2363 proto = append(proto, ' ', '1')
2364 }
2365 proto = append(proto, CR_LF...)
2366 }
2367 c.mu.Lock()
2368 // If we add a queue sub, and we had previously sent an A-,
2369 // we don't need to send an A+ here, but we need to clear
2370 // the fact that we did sent the A- so that we don't send
2371 // an A+ when we will get the first non-queue sub registered.
2372 if added {
2373 if ei, ok := c.gw.insim[accName]; ok && ei == nil {
2374 delete(c.gw.insim, accName)
2375 }
2376 }
2377 c.enqueueProto(proto)
2378 if c.trace {
2379 c.traceOutOp("", proto[:len(proto)-LEN_CR_LF])
2380 }
2381 c.mu.Unlock()
2382 }
2383 }
2384
2385 // This is invoked when a subscription (plain or queue) is
2386 // added/removed locally or in our cluster. We use ref counting
2387 // to know when to update the inbound gateways.
2388 // <Invoked from client or route connection's readLoop or when such
2389 // connection is closed>
2390 func (s *Server) gatewayUpdateSubInterest(accName string, sub *subscription, change int32) {
2391 if sub.si {
2392 return
2393 }
2394
2395 var (
2396 keya [1024]byte
2397 key = keya[:0]
2398 entry *sitally
2399 isNew bool
2400 )
2401
2402 s.gateway.pasi.Lock()
2403 defer s.gateway.pasi.Unlock()
2404
2405 accMap := s.gateway.pasi.m
2406
2407 // First see if we have the account
2408 st := accMap[accName]
2409 if st == nil {
2410 // Ignore remove of something we don't have
2411 if change < 0 {
2412 return
2413 }
2414 st = make(map[string]*sitally)
2415 accMap[accName] = st
2416 isNew = true
2417 }
2418 // Lookup: build the key as subject[+' '+queue]
2419 key = append(key, sub.subject...)
2420 if sub.queue != nil {
2421 key = append(key, ' ')
2422 key = append(key, sub.queue...)
2423 }
2424 if !isNew {
2425 entry = st[string(key)]
2426 }
2427 first := false
2428 last := false
2429 if entry == nil {
2430 // Ignore remove of something we don't have
2431 if change < 0 {
2432 return
2433 }
2434 entry = &sitally{n: change, q: sub.queue != nil}
2435 st[string(key)] = entry
2436 first = true
2437 } else {
2438 entry.n += change
2439 if entry.n <= 0 {
2440 delete(st, bytesToString(key))
2441 last = true
2442 if len(st) == 0 {
2443 delete(accMap, accName)
2444 }
2445 }
2446 }
2447 if sub.client != nil {
2448 rsubs := &s.gateway.rsubs
2449 acc := sub.client.acc
2450 sli, _ := rsubs.Load(acc)
2451 if change > 0 {
2452 var sl *Sublist
2453 if sli == nil {
2454 sl = NewSublistNoCache()
2455 rsubs.Store(acc, sl)
2456 } else {
2457 sl = sli.(*Sublist)
2458 }
2459 sl.Insert(sub)
2460 time.AfterFunc(s.gateway.recSubExp, func() {
2461 sl.Remove(sub)
2462 })
2463 } else if sli != nil {
2464 sl := sli.(*Sublist)
2465 sl.Remove(sub)
2466 if sl.Count() == 0 {
2467 rsubs.Delete(acc)
2468 }
2469 }
2470 }
2471 if first || last {
2472 if entry.q {
2473 s.sendQueueSubOrUnsubToGateways(accName, sub, first)
2474 } else {
2475 s.maybeSendSubOrUnsubToGateways(accName, sub, first)
2476 }
2477 }
2478 }
2479
2480 // Returns true if the given subject is a GW routed reply subject,
2481 // that is, starts with $GNR and is long enough to contain cluster/server hash
2482 // and subject.
2483 func isGWRoutedReply(subj []byte) bool {
2484 return len(subj) > gwSubjectOffset && bytesToString(subj[:gwReplyPrefixLen]) == gwReplyPrefix
2485 }
2486
2487 // Same than isGWRoutedReply but accepts the old prefix $GR and returns
2488 // a boolean indicating if this is the old prefix
2489 func isGWRoutedSubjectAndIsOldPrefix(subj []byte) (bool, bool) {
2490 if isGWRoutedReply(subj) {
2491 return true, false
2492 }
2493 if len(subj) > oldGWReplyStart && bytesToString(subj[:oldGWReplyPrefixLen]) == oldGWReplyPrefix {
2494 return true, true
2495 }
2496 return false, false
2497 }
2498
2499 // Returns true if subject starts with "$GNR.". This is to check that
2500 // clients can't publish on this subject.
2501 func hasGWRoutedReplyPrefix(subj []byte) bool {
2502 return len(subj) > gwReplyPrefixLen && bytesToString(subj[:gwReplyPrefixLen]) == gwReplyPrefix
2503 }
2504
2505 // Evaluates if the given reply should be mapped or not.
2506 func (g *srvGateway) shouldMapReplyForGatewaySend(acc *Account, reply []byte) bool {
2507 // If for this account there is a recent matching subscription interest
2508 // then we will map.
2509 sli, _ := g.rsubs.Load(acc)
2510 if sli == nil {
2511 return false
2512 }
2513 sl := sli.(*Sublist)
2514 if sl.Count() > 0 {
2515 if sl.HasInterest(string(reply)) {
2516 return true
2517 }
2518 }
2519
2520 return false
2521 }
2522
2523 var subPool = &sync.Pool{
2524 New: func() any {
2525 return &subscription{}
2526 },
2527 }
2528
2529 // May send a message to all outbound gateways. It is possible
2530 // that the message is not sent to a given gateway if for instance
2531 // it is known that this gateway has no interest in the account or
2532 // subject, etc..
2533 // When invoked from a LEAF connection, `checkLeafQF` should be passed as `true`
2534 // so that we skip any queue subscription interest that is not part of the
2535 // `c.pa.queues` filter (similar to what we do in `processMsgResults`). However,
2536 // when processing service imports, then this boolean should be passes as `false`,
2537 // regardless if it is a LEAF connection or not.
2538 // <Invoked from any client connection's readLoop>
2539 func (c *client) sendMsgToGateways(acc *Account, msg, subject, reply []byte, qgroups [][]byte, checkLeafQF bool) bool {
2540 // We had some times when we were sending across a GW with no subject, and the other side would break
2541 // due to parser error. These need to be fixed upstream but also double check here.
2542 if len(subject) == 0 {
2543 return false
2544 }
2545 gwsa := [16]*client{}
2546 gws := gwsa[:0]
2547 // This is in fast path, so avoid calling functions when possible.
2548 // Get the outbound connections in place instead of calling
2549 // getOutboundGatewayConnections().
2550 srv := c.srv
2551 gw := srv.gateway
2552 gw.RLock()
2553 for i := 0; i < len(gw.outo); i++ {
2554 gws = append(gws, gw.outo[i])
2555 }
2556 thisClusterReplyPrefix := gw.replyPfx
2557 thisClusterOldReplyPrefix := gw.oldReplyPfx
2558 gw.RUnlock()
2559 if len(gws) == 0 {
2560 return false
2561 }
2562
2563 // Copy off original pa in case it changes.
2564 pa := c.pa
2565
2566 mt, _ := c.isMsgTraceEnabled()
2567
2568 var (
2569 queuesa = [512]byte{}
2570 queues = queuesa[:0]
2571 accName = acc.Name
2572 mreplya [256]byte
2573 mreply []byte
2574 dstHash []byte
2575 checkReply = len(reply) > 0
2576 didDeliver bool
2577 prodIsMQTT = c.isMqtt()
2578 dlvMsgs int64
2579 dlvExtraSz int64
2580 )
2581
2582 // Get a subscription from the pool
2583 sub := subPool.Get().(*subscription)
2584
2585 // Check if the subject is on the reply prefix, if so, we
2586 // need to send that message directly to the origin cluster.
2587 directSend, old := isGWRoutedSubjectAndIsOldPrefix(subject)
2588 if directSend {
2589 if old {
2590 dstHash = subject[oldGWReplyPrefixLen : oldGWReplyStart-1]
2591 } else {
2592 dstHash = subject[gwClusterOffset : gwClusterOffset+gwHashLen]
2593 }
2594 }
2595 for i := 0; i < len(gws); i++ {
2596 gwc := gws[i]
2597 if directSend {
2598 gwc.mu.Lock()
2599 var ok bool
2600 if gwc.gw.cfg != nil {
2601 if old {
2602 ok = bytes.Equal(dstHash, gwc.gw.cfg.oldHash)
2603 } else {
2604 ok = bytes.Equal(dstHash, gwc.gw.cfg.hash)
2605 }
2606 }
2607 gwc.mu.Unlock()
2608 if !ok {
2609 continue
2610 }
2611 } else {
2612 // Plain sub interest and queue sub results for this account/subject
2613 psi, qr := gwc.gatewayInterest(accName, subject)
2614 if !psi && qr == nil {
2615 continue
2616 }
2617 queues = queuesa[:0]
2618 if qr != nil {
2619 for i := 0; i < len(qr.qsubs); i++ {
2620 qsubs := qr.qsubs[i]
2621 if len(qsubs) > 0 {
2622 queue := qsubs[0].queue
2623 if checkLeafQF {
2624 // Skip any queue that is not in the leaf's queue filter.
2625 skip := true
2626 for _, qn := range c.pa.queues {
2627 if bytes.Equal(queue, qn) {
2628 skip = false
2629 break
2630 }
2631 }
2632 if skip {
2633 continue
2634 }
2635 // Now we still need to check that it was not delivered
2636 // locally by checking the given `qgroups`.
2637 }
2638 add := true
2639 for _, qn := range qgroups {
2640 if bytes.Equal(queue, qn) {
2641 add = false
2642 break
2643 }
2644 }
2645 if add {
2646 qgroups = append(qgroups, queue)
2647 queues = append(queues, queue...)
2648 queues = append(queues, ' ')
2649 }
2650 }
2651 }
2652 }
2653 if !psi && len(queues) == 0 {
2654 continue
2655 }
2656 }
2657 if checkReply {
2658 // Check/map only once
2659 checkReply = false
2660 // Assume we will use original
2661 mreply = reply
2662 // Decide if we should map.
2663 if gw.shouldMapReplyForGatewaySend(acc, reply) {
2664 mreply = mreplya[:0]
2665 gwc.mu.Lock()
2666 useOldPrefix := gwc.gw.useOldPrefix
2667 gwc.mu.Unlock()
2668 if useOldPrefix {
2669 mreply = append(mreply, thisClusterOldReplyPrefix...)
2670 } else {
2671 mreply = append(mreply, thisClusterReplyPrefix...)
2672 }
2673 mreply = append(mreply, reply...)
2674 }
2675 }
2676
2677 // Assume original message
2678 dmsg := msg
2679 if mt != nil {
2680 // If trace is enabled, we need to set the hop header per gateway.
2681 dmsg = mt.setHopHeader(c, dmsg)
2682 }
2683
2684 // Setup the message header.
2685 // Make sure we are an 'R' proto by default
2686 c.msgb[0] = 'R'
2687 mh := c.msgb[:msgHeadProtoLen]
2688 mh = append(mh, accName...)
2689 mh = append(mh, ' ')
2690 mh = append(mh, subject...)
2691 mh = append(mh, ' ')
2692 if len(queues) > 0 {
2693 if len(reply) > 0 {
2694 mh = append(mh, "+ "...) // Signal that there is a reply.
2695 mh = append(mh, mreply...)
2696 mh = append(mh, ' ')
2697 } else {
2698 mh = append(mh, "| "...) // Only queues
2699 }
2700 mh = append(mh, queues...)
2701 } else if len(reply) > 0 {
2702 mh = append(mh, mreply...)
2703 mh = append(mh, ' ')
2704 }
2705 // Headers
2706 hasHeader := c.pa.hdr > 0
2707 canReceiveHeader := gwc.headers
2708
2709 if hasHeader {
2710 if canReceiveHeader {
2711 mh[0] = 'H'
2712 mh = append(mh, c.pa.hdb...)
2713 mh = append(mh, ' ')
2714 mh = append(mh, c.pa.szb...)
2715 } else {
2716 // If we are here we need to truncate the payload size
2717 nsz := strconv.Itoa(c.pa.size - c.pa.hdr)
2718 mh = append(mh, nsz...)
2719 }
2720 } else {
2721 mh = append(mh, c.pa.szb...)
2722 }
2723
2724 mh = append(mh, CR_LF...)
2725
2726 // We reuse the subscription object that we pass to deliverMsg.
2727 // So set/reset important fields.
2728 sub.nm, sub.max = 0, 0
2729 sub.client = gwc
2730 sub.subject = subject
2731 if c.deliverMsg(prodIsMQTT, sub, acc, subject, mreply, mh, dmsg, false) {
2732 // We don't count internal deliveries so count only if sub.icb is nil
2733 if sub.icb == nil {
2734 dlvMsgs++
2735 dlvExtraSz += int64(len(dmsg) - len(msg))
2736 }
2737 didDeliver = true
2738 }
2739
2740 // If we set the header reset the origin pub args.
2741 if mt != nil {
2742 c.pa = pa
2743 }
2744 }
2745 if dlvMsgs > 0 {
2746 totalBytes := dlvMsgs*int64(len(msg)) + dlvExtraSz
2747 // For non MQTT producers, remove the CR_LF * number of messages
2748 if !prodIsMQTT {
2749 totalBytes -= dlvMsgs * int64(LEN_CR_LF)
2750 }
2751 if acc != nil {
2752 acc.stats.Lock()
2753 acc.stats.outMsgs += dlvMsgs
2754 acc.stats.outBytes += totalBytes
2755 acc.stats.gw.outMsgs += dlvMsgs
2756 acc.stats.gw.outBytes += totalBytes
2757 acc.stats.Unlock()
2758 }
2759 atomic.AddInt64(&srv.outMsgs, dlvMsgs)
2760 atomic.AddInt64(&srv.outBytes, totalBytes)
2761 }
2762 // Done with subscription, put back to pool. We don't need
2763 // to reset content since we explicitly set when using it.
2764 // However, make sure to not hold a reference to a connection.
2765 sub.client = nil
2766 subPool.Put(sub)
2767 return didDeliver
2768 }
2769
2770 // Possibly sends an A- to the remote gateway `c`.
2771 // Invoked when processing an inbound message and the account is not found.
2772 // A check under a lock that protects processing of SUBs and UNSUBs is
2773 // done to make sure that we don't send the A- if a subscription has just
2774 // been created at the same time, which would otherwise results in the
2775 // remote never sending messages on this account until a new subscription
2776 // is created.
2777 func (s *Server) gatewayHandleAccountNoInterest(c *client, accName []byte) {
2778 // Check and possibly send the A- under this lock.
2779 s.gateway.pasi.Lock()
2780 defer s.gateway.pasi.Unlock()
2781
2782 si, inMap := s.gateway.pasi.m[string(accName)]
2783 if inMap && si != nil && len(si) > 0 {
2784 return
2785 }
2786 c.sendAccountUnsubToGateway(accName)
2787 }
2788
2789 // Helper that sends an A- to this remote gateway if not already done.
2790 // This function should not be invoked directly but instead be invoked
2791 // by functions holding the gateway.pasi's Lock.
2792 func (c *client) sendAccountUnsubToGateway(accName []byte) {
2793 // Check if we have sent the A- or not.
2794 c.mu.Lock()
2795 e, sent := c.gw.insim[string(accName)]
2796 if e != nil || !sent {
2797 // Add a nil value to indicate that we have sent an A-
2798 // so that we know to send A+ when needed.
2799 c.gw.insim[string(accName)] = nil
2800 var protoa [256]byte
2801 proto := protoa[:0]
2802 proto = append(proto, aUnsubBytes...)
2803 proto = append(proto, accName...)
2804 proto = append(proto, CR_LF...)
2805 c.enqueueProto(proto)
2806 if c.trace {
2807 c.traceOutOp("", proto[:len(proto)-LEN_CR_LF])
2808 }
2809 }
2810 c.mu.Unlock()
2811 }
2812
2813 // Possibly sends an A- for this account or RS- for this subject.
2814 // Invoked when processing an inbound message and the account is found
2815 // but there is no interest on this subject.
2816 // A test is done under a lock that protects processing of SUBs and UNSUBs
2817 // and if there is no subscription at this time, we send an A-. If there
2818 // is at least a subscription, but no interest on this subject, we send
2819 // an RS- for this subject (if not already done).
2820 func (s *Server) gatewayHandleSubjectNoInterest(c *client, acc *Account, accName, subject []byte) {
2821 s.gateway.pasi.Lock()
2822 defer s.gateway.pasi.Unlock()
2823
2824 // If there is no subscription for this account, we would normally
2825 // send an A-, however, if this account has the internal subscription
2826 // for service reply, send a specific RS- for the subject instead.
2827 // Need to grab the lock here since sublist can change during reload.
2828 acc.mu.RLock()
2829 hasSubs := acc.sl.Count() > 0 || acc.siReply != nil
2830 acc.mu.RUnlock()
2831
2832 // If there is at least a subscription, possibly send RS-
2833 if hasSubs {
2834 sendProto := false
2835 c.mu.Lock()
2836 // Send an RS- protocol if not already done and only if
2837 // not in the modeInterestOnly.
2838 e := c.gw.insim[string(accName)]
2839 if e == nil {
2840 e = &insie{ni: make(map[string]struct{})}
2841 e.ni[string(subject)] = struct{}{}
2842 c.gw.insim[string(accName)] = e
2843 sendProto = true
2844 } else if e.ni != nil {
2845 // If we are not in modeInterestOnly, check if we
2846 // have already sent an RS-
2847 if _, alreadySent := e.ni[string(subject)]; !alreadySent {
2848 // TODO(ik): pick some threshold as to when
2849 // we need to switch mode
2850 if len(e.ni) >= gatewayMaxRUnsubBeforeSwitch {
2851 // If too many RS-, switch to all-subs-mode.
2852 c.gatewaySwitchAccountToSendAllSubs(e, string(accName))
2853 } else {
2854 e.ni[string(subject)] = struct{}{}
2855 sendProto = true
2856 }
2857 }
2858 }
2859 if sendProto {
2860 var (
2861 protoa = [512]byte{}
2862 proto = protoa[:0]
2863 )
2864 proto = append(proto, rUnsubBytes...)
2865 proto = append(proto, accName...)
2866 proto = append(proto, ' ')
2867 proto = append(proto, subject...)
2868 proto = append(proto, CR_LF...)
2869 c.enqueueProto(proto)
2870 if c.trace {
2871 c.traceOutOp("", proto[:len(proto)-LEN_CR_LF])
2872 }
2873 }
2874 c.mu.Unlock()
2875 } else {
2876 // There is not a single subscription, send an A- (if not already done).
2877 c.sendAccountUnsubToGateway([]byte(acc.Name))
2878 }
2879 }
2880
2881 // Returns the cluster hash from the gateway reply prefix
2882 func (g *srvGateway) getClusterHash() []byte {
2883 g.RLock()
2884 clusterHash := g.replyPfx[gwClusterOffset : gwClusterOffset+gwHashLen]
2885 g.RUnlock()
2886 return clusterHash
2887 }
2888
2889 // Store this route in map with the key being the remote server's name hash
2890 // and the remote server's ID hash used by gateway replies mapping routing.
2891 func (s *Server) storeRouteByHash(srvIDHash string, c *client) {
2892 if !s.gateway.enabled {
2893 return
2894 }
2895 s.gateway.routesIDByHash.Store(srvIDHash, c)
2896 }
2897
2898 // Remove the route with the given keys from the map.
2899 func (s *Server) removeRouteByHash(srvIDHash string) {
2900 if !s.gateway.enabled {
2901 return
2902 }
2903 s.gateway.routesIDByHash.Delete(srvIDHash)
2904 }
2905
2906 // Returns the route with given hash or nil if not found.
2907 // This is for gateways only.
2908 func (s *Server) getRouteByHash(hash, accName []byte) (*client, bool) {
2909 id := bytesToString(hash)
2910 var perAccount bool
2911 if v, ok := s.accRouteByHash.Load(bytesToString(accName)); ok {
2912 if v == nil {
2913 id += bytesToString(accName)
2914 perAccount = true
2915 } else {
2916 id += strconv.Itoa(v.(int))
2917 }
2918 }
2919 if v, ok := s.gateway.routesIDByHash.Load(id); ok {
2920 return v.(*client), perAccount
2921 } else if !perAccount {
2922 // Check if we have a "no pool" connection at index 0.
2923 if v, ok := s.gateway.routesIDByHash.Load(bytesToString(hash) + "0"); ok {
2924 if r := v.(*client); r != nil {
2925 r.mu.Lock()
2926 noPool := r.route.noPool
2927 r.mu.Unlock()
2928 if noPool {
2929 return r, false
2930 }
2931 }
2932 }
2933 }
2934 return nil, perAccount
2935 }
2936
2937 // Returns the subject from the routed reply
2938 func getSubjectFromGWRoutedReply(reply []byte, isOldPrefix bool) []byte {
2939 if isOldPrefix {
2940 return reply[oldGWReplyStart:]
2941 }
2942 return reply[gwSubjectOffset:]
2943 }
2944
2945 // Returns the subject embedded in the given routed
2946 // reply subject and whether the prefix was stripped.
2947 // If the subject is not routed, returns it unchanged.
2948 func getGWRoutedSubjectOrSelf(subject []byte) ([]byte, bool) {
2949 if isGWPrefix, oldPrefix := isGWRoutedSubjectAndIsOldPrefix(subject); isGWPrefix {
2950 return getSubjectFromGWRoutedReply(subject, oldPrefix), true
2951 }
2952 return subject, false
2953 }
2954
2955 // This should be invoked only from processInboundGatewayMsg() or
2956 // processInboundRoutedMsg() and is checking if the subject
2957 // (c.pa.subject) has the _GR_ prefix. If so, this is processed
2958 // as a GW reply and `true` is returned to indicate to the caller
2959 // that it should stop processing.
2960 // If gateway is not enabled on this server or if the subject
2961 // does not start with _GR_, `false` is returned and caller should
2962 // process message as usual.
2963 func (c *client) handleGatewayReply(msg []byte) (processed bool) {
2964 // Do not handle GW prefixed messages if this server does not have
2965 // gateway enabled or if the subject does not start with the previx.
2966 if !c.srv.gateway.enabled {
2967 return false
2968 }
2969 isGWPrefix, oldPrefix := isGWRoutedSubjectAndIsOldPrefix(c.pa.subject)
2970 if !isGWPrefix {
2971 return false
2972 }
2973 // Save original subject (in case we have to forward)
2974 orgSubject := c.pa.subject
2975
2976 var clusterHash []byte
2977 var srvHash []byte
2978 var subject []byte
2979
2980 if oldPrefix {
2981 clusterHash = c.pa.subject[oldGWReplyPrefixLen : oldGWReplyStart-1]
2982 // Check if this reply is intended for our cluster.
2983 if !bytes.Equal(clusterHash, c.srv.gateway.oldHash) {
2984 // We could report, for now, just drop.
2985 return true
2986 }
2987 subject = c.pa.subject[oldGWReplyStart:]
2988 } else {
2989 clusterHash = c.pa.subject[gwClusterOffset : gwClusterOffset+gwHashLen]
2990 // Check if this reply is intended for our cluster.
2991 if !bytes.Equal(clusterHash, c.srv.gateway.getClusterHash()) {
2992 // We could report, for now, just drop.
2993 return true
2994 }
2995 srvHash = c.pa.subject[gwServerOffset : gwServerOffset+gwHashLen]
2996 subject = c.pa.subject[gwSubjectOffset:]
2997 }
2998
2999 var route *client
3000 var perAccount bool
3001
3002 // If the origin is not this server, get the route this should be sent to.
3003 if c.kind == GATEWAY && srvHash != nil && !bytes.Equal(srvHash, c.srv.gateway.sIDHash) {
3004 route, perAccount = c.srv.getRouteByHash(srvHash, c.pa.account)
3005 // This will be possibly nil, and in this case we will try to process
3006 // the interest from this server.
3007 }
3008
3009 // Adjust the subject
3010 c.pa.subject = subject
3011
3012 // Use a stack buffer to rewrite c.pa.cache since we only need it for
3013 // getAccAndResultFromCache()
3014 var _pacache [256]byte
3015 pacache := _pacache[:0]
3016 // For routes that are dedicated to an account, do not put the account
3017 // name in the pacache.
3018 if c.kind == GATEWAY || (c.kind == ROUTER && c.route != nil && len(c.route.accName) == 0) {
3019 pacache = append(pacache, c.pa.account...)
3020 pacache = append(pacache, ' ')
3021 }
3022 pacache = append(pacache, c.pa.subject...)
3023 c.pa.pacache = pacache
3024
3025 acc, r := c.getAccAndResultFromCache()
3026 if acc == nil {
3027 typeConn := "routed"
3028 if c.kind == GATEWAY {
3029 typeConn = "gateway"
3030 }
3031 c.Debugf("Unknown account %q for %s message on subject: %q", c.pa.account, typeConn, c.pa.subject)
3032 if c.kind == GATEWAY {
3033 c.srv.gatewayHandleAccountNoInterest(c, c.pa.account)
3034 }
3035 return true
3036 }
3037
3038 // If route is nil, we will process the incoming message locally.
3039 if route == nil {
3040 // Check if this is a service reply subject (_R_)
3041 isServiceReply := isServiceReply(c.pa.subject)
3042
3043 var queues [][]byte
3044 if len(r.psubs)+len(r.qsubs) > 0 {
3045 flags := pmrCollectQueueNames | pmrIgnoreEmptyQueueFilter
3046 // If this message came from a ROUTE, allow to pick queue subs
3047 // only if the message was directly sent by the "gateway" server
3048 // in our cluster that received it.
3049 if c.kind == ROUTER {
3050 flags |= pmrAllowSendFromRouteToRoute
3051 }
3052 _, queues = c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, flags)
3053 }
3054 // Since this was a reply that made it to the origin cluster,
3055 // we now need to send the message with the real subject to
3056 // gateways in case they have interest on that reply subject.
3057 if !isServiceReply {
3058 c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, queues, false)
3059 }
3060 } else if c.kind == GATEWAY {
3061 // Only if we are a gateway connection should we try to route
3062 // to the server where the request originated.
3063 var bufa [256]byte
3064 var buf = bufa[:0]
3065 buf = append(buf, msgHeadProto...)
3066 if !perAccount {
3067 buf = append(buf, acc.Name...)
3068 buf = append(buf, ' ')
3069 }
3070 buf = append(buf, orgSubject...)
3071 buf = append(buf, ' ')
3072 if len(c.pa.reply) > 0 {
3073 buf = append(buf, c.pa.reply...)
3074 buf = append(buf, ' ')
3075 }
3076 szb := c.pa.szb
3077 if c.pa.hdr >= 0 {
3078 if route.headers {
3079 buf[0] = 'H'
3080 buf = append(buf, c.pa.hdb...)
3081 buf = append(buf, ' ')
3082 } else {
3083 szb = []byte(strconv.Itoa(c.pa.size - c.pa.hdr))
3084 msg = msg[c.pa.hdr:]
3085 }
3086 }
3087 buf = append(buf, szb...)
3088 mhEnd := len(buf)
3089 buf = append(buf, _CRLF_...)
3090 buf = append(buf, msg...)
3091
3092 route.mu.Lock()
3093 route.enqueueProto(buf)
3094 if route.trace {
3095 route.traceOutOp("", buf[:mhEnd])
3096 }
3097 route.mu.Unlock()
3098 }
3099 return true
3100 }
3101
3102 // Process a message coming from a remote gateway. Send to any sub/qsub
3103 // in our cluster that is matching. When receiving a message for an
3104 // account or subject for which there is no interest in this cluster
3105 // an A-/RS- protocol may be send back.
3106 // <Invoked from inbound connection's readLoop>
3107 func (c *client) processInboundGatewayMsg(msg []byte) {
3108 // Update statistics
3109 c.in.msgs++
3110 // The msg includes the CR_LF, so pull back out for accounting.
3111 size := len(msg) - LEN_CR_LF
3112 c.in.bytes += int32(size)
3113
3114 if c.opts.Verbose {
3115 c.sendOK()
3116 }
3117
3118 // Mostly under testing scenarios.
3119 if c.srv == nil {
3120 return
3121 }
3122
3123 // If the subject (c.pa.subject) has the gateway prefix, this function will
3124 // handle it.
3125 if c.handleGatewayReply(msg) {
3126 // We are done here.
3127 return
3128 }
3129
3130 acc, r := c.getAccAndResultFromCache()
3131 if acc == nil {
3132 c.Debugf("Unknown account %q for gateway message on subject: %q", c.pa.account, c.pa.subject)
3133 c.srv.gatewayHandleAccountNoInterest(c, c.pa.account)
3134 return
3135 }
3136
3137 acc.stats.Lock()
3138 acc.stats.inMsgs++
3139 acc.stats.inBytes += int64(size)
3140 acc.stats.gw.inMsgs++
3141 acc.stats.gw.inBytes += int64(size)
3142 acc.stats.Unlock()
3143
3144 // Check if this is a service reply subject (_R_)
3145 noInterest := len(r.psubs) == 0
3146 checkNoInterest := true
3147 if acc.NumServiceImports() > 0 {
3148 if isServiceReply(c.pa.subject) {
3149 checkNoInterest = false
3150 } else {
3151 // We need to eliminate the subject interest from the service imports here to
3152 // make sure we send the proper no interest if the service import is the only interest.
3153 noInterest = true
3154 for _, sub := range r.psubs {
3155 // sub.si indicates that this is a subscription for service import, and is immutable.
3156 // So sub.si is false, then this is a subscription for something else, so there is
3157 // actually proper interest.
3158 if !sub.si {
3159 noInterest = false
3160 break
3161 }
3162 }
3163 }
3164 }
3165 if checkNoInterest && noInterest {
3166 // If there is no interest on plain subs, possibly send an RS-,
3167 // even if there is qsubs interest.
3168 c.srv.gatewayHandleSubjectNoInterest(c, acc, c.pa.account, c.pa.subject)
3169
3170 // If there is also no queue filter, then no point in continuing
3171 // (even if r.qsubs i > 0).
3172 if len(c.pa.queues) == 0 {
3173 return
3174 }
3175 }
3176 c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, pmrNoFlag)
3177 }
3178
3179 // Indicates that the remote which we are sending messages to
3180 // has decided to send us all its subs interest so that we
3181 // stop doing optimistic sends.
3182 // <Invoked from outbound connection's readLoop>
3183 func (c *client) gatewayAllSubsReceiveStart(info *Info) {
3184 account := getAccountFromGatewayCommand(c, info, "start")
3185 if account == "" {
3186 return
3187 }
3188
3189 c.Debugf("Gateway %q: switching account %q to %s mode",
3190 info.Gateway, account, InterestOnly)
3191
3192 // Since the remote would send us this start command
3193 // only after sending us too many RS- for this account,
3194 // we should always have an entry here.
3195 // TODO(ik): Should we close connection with protocol violation
3196 // error if that happens?
3197 ei, _ := c.gw.outsim.Load(account)
3198 if ei != nil {
3199 e := ei.(*outsie)
3200 e.Lock()
3201 e.mode = Transitioning
3202 e.Unlock()
3203 } else {
3204 e := &outsie{sl: NewSublistForServer(c.srv)}
3205 e.mode = Transitioning
3206 c.mu.Lock()
3207 c.gw.outsim.Store(account, e)
3208 c.mu.Unlock()
3209 }
3210 }
3211
3212 // Indicates that the remote has finished sending all its
3213 // subscriptions and we should now not send unless we know
3214 // there is explicit interest.
3215 // <Invoked from outbound connection's readLoop>
3216 func (c *client) gatewayAllSubsReceiveComplete(info *Info) {
3217 account := getAccountFromGatewayCommand(c, info, "complete")
3218 if account == _EMPTY_ {
3219 return
3220 }
3221 // Done receiving all subs from remote. Set the `ni`
3222 // map to nil so that gatewayInterest() no longer
3223 // uses it.
3224 ei, _ := c.gw.outsim.Load(account)
3225 if ei != nil {
3226 e := ei.(*outsie)
3227 // Needs locking here since `ni` is checked by
3228 // many go-routines calling gatewayInterest()
3229 e.Lock()
3230 e.ni = nil
3231 e.mode = InterestOnly
3232 e.Unlock()
3233
3234 c.Debugf("Gateway %q: switching account %q to %s mode complete",
3235 info.Gateway, account, InterestOnly)
3236 }
3237 }
3238
3239 // small helper to get the account name from the INFO command.
3240 func getAccountFromGatewayCommand(c *client, info *Info, cmd string) string {
3241 if info.GatewayCmdPayload == nil {
3242 c.sendErrAndErr(fmt.Sprintf("Account absent from receive-all-subscriptions-%s command", cmd))
3243 c.closeConnection(ProtocolViolation)
3244 return _EMPTY_
3245 }
3246 return string(info.GatewayCmdPayload)
3247 }
3248
3249 // Switch to send-all-subs mode for the given gateway and account.
3250 // This is invoked when processing an inbound message and we
3251 // reach a point where we had to send a lot of RS- for this
3252 // account. We will send an INFO protocol to indicate that we
3253 // start sending all our subs (for this account), followed by
3254 // all subs (RS+) and finally an INFO to indicate the end of it.
3255 // The remote will then send messages only if it finds explicit
3256 // interest in the sublist created based on all RS+ that we just
3257 // sent.
3258 // The client's lock is held on entry.
3259 // <Invoked from inbound connection's readLoop>
3260 func (c *client) gatewaySwitchAccountToSendAllSubs(e *insie, accName string) {
3261 // Set this map to nil so that the no-interest is no longer checked.
3262 e.ni = nil
3263 // Switch mode to transitioning to prevent switchAccountToInterestMode
3264 // to possibly call this function multiple times.
3265 e.mode = Transitioning
3266 s := c.srv
3267
3268 remoteGWName := c.gw.name
3269 c.Debugf("Gateway %q: switching account %q to %s mode",
3270 remoteGWName, accName, InterestOnly)
3271
3272 // Function that will create an INFO protocol
3273 // and set proper command.
3274 sendCmd := func(cmd byte, useLock bool) {
3275 // Use bare server info and simply set the
3276 // gateway name and command
3277 info := Info{
3278 Gateway: s.gateway.name,
3279 GatewayCmd: cmd,
3280 GatewayCmdPayload: stringToBytes(accName),
3281 }
3282
3283 b, _ := json.Marshal(&info)
3284 infoJSON := []byte(fmt.Sprintf(InfoProto, b))
3285 if useLock {
3286 c.mu.Lock()
3287 }
3288 c.enqueueProto(infoJSON)
3289 if useLock {
3290 c.mu.Unlock()
3291 }
3292 }
3293 // Send the start command. When remote receives this,
3294 // it may continue to send optimistic messages, but
3295 // it will start to register RS+/RS- in sublist instead
3296 // of noInterest map.
3297 sendCmd(gatewayCmdAllSubsStart, false)
3298
3299 // Execute this in separate go-routine as to not block
3300 // the readLoop (which may cause the otherside to close
3301 // the connection due to slow consumer)
3302 s.startGoRoutine(func() {
3303 defer s.grWG.Done()
3304
3305 s.sendAccountSubsToGateway(c, accName)
3306 // Send the complete command. When the remote receives
3307 // this, it will not send a message unless it has a
3308 // matching sub from us.
3309 sendCmd(gatewayCmdAllSubsComplete, true)
3310
3311 c.Debugf("Gateway %q: switching account %q to %s mode complete",
3312 remoteGWName, accName, InterestOnly)
3313 })
3314 }
3315
3316 // Keeps track of the routed reply to be used when/if application sends back a
3317 // message on the reply without the prefix.
3318 // If `client` is not nil, it will be stored in the client gwReplyMapping structure,
3319 // and client lock is held on entry.
3320 // If `client` is nil, the mapping is stored in the client's account's gwReplyMapping
3321 // structure. Account lock will be explicitly acquired.
3322 // This is a server receiver because we use a timer interval that is avail in
3323 // Server.gateway object.
3324 func (s *Server) trackGWReply(c *client, acc *Account, reply, routedReply []byte) {
3325 var l sync.Locker
3326 var g *gwReplyMapping
3327 if acc != nil {
3328 acc.mu.Lock()
3329 defer acc.mu.Unlock()
3330 g = &acc.gwReplyMapping
3331 l = &acc.mu
3332 } else {
3333 g = &c.gwReplyMapping
3334 l = &c.mu
3335 }
3336 ttl := s.gateway.recSubExp
3337 wasEmpty := len(g.mapping) == 0
3338 if g.mapping == nil {
3339 g.mapping = make(map[string]*gwReplyMap)
3340 }
3341 // The reason we pass both `reply` and `routedReply`, is that in some cases,
3342 // `routedReply` may have a deliver subject appended, something look like:
3343 // "_GR_.xxx.yyy.$JS.ACK.$MQTT_msgs.someid.1.1.1.1620086713306484000.0@$MQTT.msgs.foo"
3344 // but `reply` has already been cleaned up (delivery subject removed from tail):
3345 // "$JS.ACK.$MQTT_msgs.someid.1.1.1.1620086713306484000.0"
3346 // So we will use that knowledge so we don't have to make any cleaning here.
3347 routedReply = routedReply[:gwSubjectOffset+len(reply)]
3348 // We need to make a copy so that we don't reference the underlying
3349 // read buffer.
3350 ms := string(routedReply)
3351 grm := &gwReplyMap{ms: ms, exp: time.Now().Add(ttl).UnixNano()}
3352 // If we are here with the same key but different mapped replies
3353 // (say $GNR._.A.srv1.bar and then $GNR._.B.srv2.bar), we need to
3354 // store it otherwise we would take the risk of the reply not
3355 // making it back.
3356 g.mapping[ms[gwSubjectOffset:]] = grm
3357 if wasEmpty {
3358 atomic.StoreInt32(&g.check, 1)
3359 s.gwrm.m.Store(g, l)
3360 if atomic.CompareAndSwapInt32(&s.gwrm.w, 0, 1) {
3361 select {
3362 case s.gwrm.ch <- ttl:
3363 default:
3364 }
3365 }
3366 }
3367 }
3368
3369 // Starts a long lived go routine that is responsible to
3370 // remove GW reply mapping that have expired.
3371 func (s *Server) startGWReplyMapExpiration() {
3372 s.mu.Lock()
3373 s.gwrm.ch = make(chan time.Duration, 1)
3374 s.mu.Unlock()
3375 s.startGoRoutine(func() {
3376 defer s.grWG.Done()
3377
3378 t := time.NewTimer(time.Hour)
3379 var ttl time.Duration
3380 for {
3381 select {
3382 case <-t.C:
3383 if ttl == 0 {
3384 t.Reset(time.Hour)
3385 continue
3386 }
3387 now := time.Now().UnixNano()
3388 mapEmpty := true
3389 s.gwrm.m.Range(func(k, v any) bool {
3390 g := k.(*gwReplyMapping)
3391 l := v.(sync.Locker)
3392 l.Lock()
3393 for k, grm := range g.mapping {
3394 if grm.exp <= now {
3395 delete(g.mapping, k)
3396 if len(g.mapping) == 0 {
3397 atomic.StoreInt32(&g.check, 0)
3398 s.gwrm.m.Delete(g)
3399 }
3400 }
3401 }
3402 l.Unlock()
3403 mapEmpty = false
3404 return true
3405 })
3406 if mapEmpty && atomic.CompareAndSwapInt32(&s.gwrm.w, 1, 0) {
3407 ttl = 0
3408 t.Reset(time.Hour)
3409 } else {
3410 t.Reset(ttl)
3411 }
3412 case cttl := <-s.gwrm.ch:
3413 ttl = cttl
3414 if !t.Stop() {
3415 select {
3416 case <-t.C:
3417 default:
3418 }
3419 }
3420 t.Reset(ttl)
3421 case <-s.quitCh:
3422 return
3423 }
3424 }
3425 })
3426 }