Debian Codegraph @

server/mqtt.go

raw
1 // Copyright 2020-2026 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "bytes"
18 "crypto/tls"
19 "encoding/binary"
20 "encoding/json"
21 "errors"
22 "fmt"
23 "io"
24 "net"
25 "net/http"
26 "slices"
27 "strconv"
28 "strings"
29 "sync"
30 "sync/atomic"
31 "time"
32 "unicode/utf8"
33
34 "github.com/nats-io/jwt/v2"
35 "github.com/nats-io/nats-server/v2/server/gsl"
36 "github.com/nats-io/nats-server/v2/server/stree"
37 "github.com/nats-io/nuid"
38 )
39
40 // References to "spec" here is from https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.pdf
41
42 const (
43 mqttPacketConnect = byte(0x10)
44 mqttPacketConnectAck = byte(0x20)
45 mqttPacketPub = byte(0x30)
46 mqttPacketPubAck = byte(0x40)
47 mqttPacketPubRec = byte(0x50)
48 mqttPacketPubRel = byte(0x60)
49 mqttPacketPubComp = byte(0x70)
50 mqttPacketSub = byte(0x80)
51 mqttPacketSubAck = byte(0x90)
52 mqttPacketUnsub = byte(0xa0)
53 mqttPacketUnsubAck = byte(0xb0)
54 mqttPacketPing = byte(0xc0)
55 mqttPacketPingResp = byte(0xd0)
56 mqttPacketDisconnect = byte(0xe0)
57 mqttPacketMask = byte(0xf0)
58 mqttPacketFlagMask = byte(0x0f)
59
60 mqttProtoLevel = byte(0x4)
61
62 // Connect flags
63 mqttConnFlagReserved = byte(0x1)
64 mqttConnFlagCleanSession = byte(0x2)
65 mqttConnFlagWillFlag = byte(0x04)
66 mqttConnFlagWillQoS = byte(0x18)
67 mqttConnFlagWillRetain = byte(0x20)
68 mqttConnFlagPasswordFlag = byte(0x40)
69 mqttConnFlagUsernameFlag = byte(0x80)
70
71 // Publish flags
72 mqttPubFlagRetain = byte(0x01)
73 mqttPubFlagQoS = byte(0x06)
74 mqttPubFlagDup = byte(0x08)
75 mqttPubFlags = mqttPubFlagRetain | mqttPubFlagQoS | mqttPubFlagDup // 0x0f, the fixed-header flags nibble
76 mqttPubQos1 = byte(0x1 << 1)
77 mqttPubQoS2 = byte(0x2 << 1)
78
79 // Subscribe flags
80 mqttSubscribeFlags = byte(0x2)
81 mqttSubAckFailure = byte(0x80)
82
83 // Unsubscribe flags
84 mqttUnsubscribeFlags = byte(0x2)
85
86 // ConnAck returned codes
87 mqttConnAckRCConnectionAccepted = byte(0x0)
88 mqttConnAckRCUnacceptableProtocolVersion = byte(0x1)
89 mqttConnAckRCIdentifierRejected = byte(0x2)
90 mqttConnAckRCServerUnavailable = byte(0x3)
91 mqttConnAckRCBadUserOrPassword = byte(0x4)
92 mqttConnAckRCNotAuthorized = byte(0x5)
93 mqttConnAckRCQoS2WillRejected = byte(0x10)
94
95 // Maximum payload size of a control packet
96 mqttMaxPayloadSize = 0xFFFFFFF
97
98 // Topic/Filter characters
99 mqttTopicLevelSep = '/'
100 mqttSingleLevelWC = '+'
101 mqttMultiLevelWC = '#'
102 mqttReservedPre = '$'
103
104 // This is appended to the sid of a subscription that is
105 // created on the upper level subject because of the MQTT
106 // wildcard '#' semantic.
107 mqttMultiLevelSidSuffix = " fwc"
108
109 // This is the prefix used for all subjects used by MQTT code.
110 mqttPrefix = "$MQTT."
111
112 // This is the prefix for NATS subscriptions subjects associated as delivery
113 // subject of JS consumer. We want to make them unique so will prevent users
114 // MQTT subscriptions to start with this.
115 mqttSubPrefix = mqttPrefix + "sub."
116
117 // Stream name for MQTT messages on a given account
118 mqttStreamName = "$MQTT_msgs"
119 mqttStreamSubjectPrefix = mqttPrefix + "msgs."
120
121 // Stream name for MQTT retained messages on a given account
122 mqttRetainedMsgsStreamName = "$MQTT_rmsgs"
123 mqttRetainedMsgsStreamSubject = mqttPrefix + "rmsgs."
124
125 // Stream name for MQTT sessions on a given account
126 mqttSessStreamName = "$MQTT_sess"
127 mqttSessStreamSubjectPrefix = mqttPrefix + "sess."
128
129 // Stream name prefix for MQTT sessions on a given account
130 mqttSessionsStreamNamePrefix = "$MQTT_sess_"
131
132 // Stream name and subject for incoming MQTT QoS2 messages
133 mqttQoS2IncomingMsgsStreamName = "$MQTT_qos2in"
134 mqttQoS2IncomingMsgsStreamSubjectPrefix = mqttPrefix + "qos2.in."
135
136 // Stream name and subjects for outgoing MQTT QoS (PUBREL) messages
137 mqttOutStreamName = "$MQTT_out"
138 mqttOutSubjectPrefix = mqttPrefix + "out."
139 mqttPubRelSubjectPrefix = mqttPrefix + "out.pubrel."
140 mqttPubRelDeliverySubjectPrefix = mqttPrefix + "deliver.pubrel."
141 mqttPubRelConsumerDurablePrefix = "$MQTT_PUBREL_"
142
143 // As per spec, MQTT server may not redeliver QoS 1 and 2 messages to
144 // clients, except after client reconnects. However, NATS Server will
145 // redeliver unacknowledged messages after this default interval. This can
146 // be changed with the server.Options.MQTT.AckWait option.
147 mqttDefaultAckWait = 30 * time.Second
148
149 // This is the default for the outstanding number of pending QoS 1
150 // messages sent to a session with QoS 1 subscriptions.
151 mqttDefaultMaxAckPending = 1024
152
153 // A session's list of subscriptions cannot have a cumulative MaxAckPending
154 // of more than this limit.
155 mqttMaxAckTotalLimit = 0xFFFF
156
157 // Prefix of the reply subject for JS API requests.
158 mqttJSARepliesPrefix = mqttPrefix + "JSA."
159
160 // Those are tokens that are used for the reply subject of JS API requests.
161 // For instance "$MQTT.JSA.<node id>.SC.<number>" is the reply subject
162 // for a request to create a stream (where <node id> is the server name hash),
163 // while "$MQTT.JSA.<node id>.SL.<number>" is for a stream lookup, etc...
164 mqttJSAIdTokenPos = 3
165 mqttJSATokenPos = 4
166 mqttJSAClientIDPos = 5
167 mqttJSAStreamCreate = "SC"
168 mqttJSAStreamUpdate = "SU"
169 mqttJSAStreamLookup = "SL"
170 mqttJSAStreamDel = "SD"
171 mqttJSAConsumerCreate = "CC"
172 mqttJSAConsumerLookup = "CL"
173 mqttJSAConsumerDel = "CD"
174 mqttJSAMsgStore = "MS"
175 mqttJSAMsgLoad = "ML"
176 mqttJSAMsgDelete = "MD"
177 mqttJSASessPersist = "SP"
178 mqttJSARetainedMsgDel = "RD"
179 mqttJSAStreamNames = "SN"
180
181 // This is how long to keep a client in the flappers map before closing the
182 // connection. This prevent quick reconnect from those clients that keep
183 // wanting to connect with a client ID already in use.
184 mqttSessFlappingJailDur = time.Second
185
186 // This is how frequently the timer to cleanup the sessions flappers map is firing.
187 mqttSessFlappingCleanupInterval = 5 * time.Second
188
189 // Default retry delay if transfer of old session streams to new one fails
190 mqttDefaultTransferRetry = 5 * time.Second
191
192 // For Websocket URLs
193 mqttWSPath = "/mqtt"
194
195 mqttInitialPubHeader = 16 // An overkill, should need 7 bytes max
196 mqttProcessSubTooLong = 100 * time.Millisecond
197 mqttDefaultRetainedCacheTTL = 2 * time.Minute
198 mqttRetainedTransferTimeout = 10 * time.Second
199 mqttDefaultJSAPITimeout = 5 * time.Second
200 mqttRetainedFlagDelMarker = '-'
201 )
202
203 const (
204 sparkbNBIRTH = "NBIRTH"
205 sparkbDBIRTH = "DBIRTH"
206 sparkbNDEATH = "NDEATH"
207 sparkbDDEATH = "DDEATH"
208 )
209
210 var (
211 sparkbNamespaceTopicPrefix = []byte("spBv1.0/")
212 sparkbCertificatesTopicPrefix = []byte("$sparkplug/certificates/")
213 )
214
215 var (
216 mqttPingResponse = []byte{mqttPacketPingResp, 0x0}
217 mqttProtoName = []byte("MQTT")
218 mqttOldProtoName = []byte("MQIsdp")
219 mqttSessJailDur = mqttSessFlappingJailDur
220 mqttFlapCleanItvl = mqttSessFlappingCleanupInterval
221 mqttRetainedCacheTTL = mqttDefaultRetainedCacheTTL
222 )
223
224 var (
225 errMQTTNotWebsocketPort = errors.New("MQTT clients over websocket must connect to the Websocket port, not the MQTT port")
226 errMQTTTopicFilterCannotBeEmpty = errors.New("topic filter cannot be empty")
227 errMQTTMalformedVarInt = errors.New("malformed variable int")
228 errMQTTSecondConnectPacket = errors.New("received a second CONNECT packet")
229 errMQTTServerNameMustBeSet = errors.New("mqtt requires server name to be explicitly set")
230 errMQTTUserMixWithUsersNKeys = errors.New("mqtt authentication username not compatible with presence of users/nkeys")
231 errMQTTTokenMixWIthUsersNKeys = errors.New("mqtt authentication token not compatible with presence of users/nkeys")
232 errMQTTAckWaitMustBePositive = errors.New("ack wait must be a positive value")
233 errMQTTJSAPITimeoutMustBePositive = errors.New("JS API timeout must be a positive value")
234 errMQTTStandaloneNeedsJetStream = errors.New("mqtt requires JetStream to be enabled if running in standalone mode")
235 errMQTTConnFlagReserved = errors.New("connect flags reserved bit not set to 0")
236 errMQTTWillAndRetainFlag = errors.New("if Will flag is set to 0, Will Retain flag must be 0 too")
237 errMQTTPasswordFlagAndNoUser = errors.New("password flag set but username flag is not")
238 errMQTTCIDEmptyNeedsCleanFlag = errors.New("when client ID is empty, clean session flag must be set to 1")
239 errMQTTEmptyWillTopic = errors.New("empty Will topic not allowed")
240 errMQTTEmptyUsername = errors.New("empty user name not allowed")
241 errMQTTTopicIsEmpty = errors.New("topic cannot be empty")
242 errMQTTPacketIdentifierIsZero = errors.New("packet identifier cannot be 0")
243 errMQTTUnsupportedCharacters = errors.New("character not supported for MQTT topics")
244 errMQTTInvalidSession = errors.New("invalid MQTT session")
245 errMQTTInvalidRetainFlags = errors.New("invalid retained message flags")
246 errMQTTInvalidRetainedMessage = errors.New("invalid retained message")
247 errMQTTSessionCollision = errors.New("stored session does not match client ID")
248 )
249
250 type srvMQTT struct {
251 listener net.Listener
252 listenerErr error
253 authOverride bool
254 sessmgr mqttSessionManager
255 }
256
257 type mqttSessionManager struct {
258 mu sync.RWMutex
259 sessions map[string]*mqttAccountSessionManager // key is account name
260 }
261
262 type mqttAccountSessionManager struct {
263 mu sync.RWMutex
264 sessions map[string]*mqttSession // key is MQTT client ID
265 sessByHash map[string]*mqttSession // key is MQTT client ID hash
266 sessLocked map[string]struct{} // key is MQTT client ID and indicate that a session can not be taken by a new client at this time
267 flappers map[string]time.Time // When connection connects with client ID already in use
268 flapTimer *time.Timer // Timer to perform some cleanup of the flappers map
269 retmsgs *stree.SubjectTree[mqttRetainedMsgRef] // retained message metadata
270 rmsCache *sync.Map // map[subject]mqttRetainedMsg
271 jsa mqttJSA
272 domainTk string // Domain (with trailing "."), or possibly empty. This is added to session subject.
273 }
274
275 type mqttJSAResponse struct {
276 reply string // will be used to map to the original request in jsa.NewRequestExMulti
277 value any
278 }
279
280 type mqttJSA struct {
281 mu sync.Mutex
282 id string
283 c *client
284 sendq *ipQueue[*mqttJSPubMsg]
285 rplyr string
286 replies sync.Map // [string]chan *mqttJSAResponse
287 nuid *nuid.NUID
288 quitCh chan struct{}
289 domain string // Domain or possibly empty. This is added to session subject.
290 domainSet bool // covers if domain was set, even to empty
291 timeout time.Duration
292 }
293
294 type mqttJSPubMsg struct {
295 subj string
296 reply string
297 hdr int
298 msg []byte
299 }
300
301 type mqttRetMsgDel struct {
302 Subject string `json:"subject"`
303 Seq uint64 `json:"seq"`
304 }
305
306 type mqttSession struct {
307 // subsMu is a "quick" version of the session lock, sufficient for the QoS0
308 // callback. It only guarantees that a new subscription is initialized, and
309 // its retained messages if any have been queued up for delivery. The QoS12
310 // callback uses the session lock.
311 mu sync.Mutex
312 subsMu sync.RWMutex
313
314 id string // client ID
315 idHash string // client ID hash
316 c *client
317 jsa *mqttJSA
318 subs map[string]byte // Key is MQTT SUBSCRIBE filter, value is the subscription QoS
319 cons map[string]*ConsumerConfig
320 pubRelConsumer *ConsumerConfig
321 pubRelSubscribed bool
322 pubRelDeliverySubject string
323 pubRelDeliverySubjectB []byte
324 pubRelSubject string
325 seq uint64
326
327 // pendingPublish maps packet identifiers (PI) to JetStream ACK subjects for
328 // QoS1 and 2 PUBLISH messages pending delivery to the session's client.
329 pendingPublish map[uint16]*mqttPending
330
331 // pendingPubRel maps PIs to JetStream ACK subjects for QoS2 PUBREL
332 // messages pending delivery to the session's client.
333 pendingPubRel map[uint16]*mqttPending
334
335 // cpending maps delivery attempts (that come with a JS ACK subject) to
336 // existing PIs.
337 cpending map[string]map[uint64]uint16 // composite key: jsDur, sseq
338
339 // "Last used" publish packet identifier (PI). starting point searching for the next available.
340 last_pi uint16
341
342 // Maximum number of pending acks for this session.
343 maxp uint16
344 tmaxack int
345 clean bool
346 domainTk string
347 }
348
349 type mqttPersistedSession struct {
350 Origin string `json:"origin,omitempty"`
351 ID string `json:"id,omitempty"`
352 Clean bool `json:"clean,omitempty"`
353 Subs map[string]byte `json:"subs,omitempty"`
354 Cons map[string]*ConsumerConfig `json:"cons,omitempty"`
355 PubRel *ConsumerConfig `json:"pubrel,omitempty"`
356 }
357
358 type mqttRetainedMsg struct {
359 Origin string `json:"origin,omitempty"`
360 Subject string `json:"subject,omitempty"`
361 Topic string `json:"topic,omitempty"`
362 Msg []byte `json:"msg,omitempty"`
363 Flags byte `json:"flags,omitempty"`
364 Source string `json:"source,omitempty"`
365
366 expiresFromCache time.Time
367 }
368
369 type mqttRetainedMsgRef struct {
370 sseq uint64
371 }
372
373 // mqttSub contains fields associated with a MQTT subscription, and is added to
374 // the main subscription struct for MQTT message delivery subscriptions. The
375 // delivery callbacks may get invoked before sub.mqtt is set up, so they should
376 // acquire either sess.mu or sess.subsMu before accessing it.
377 type mqttSub struct {
378 // The sub's QOS and the JS durable name. They can change when
379 // re-subscribing, and are used in the delivery callbacks. They can be
380 // quickly accessed using sess.subsMu.RLock, or under the main session lock.
381 qos byte
382 jsDur string
383
384 // closed marks the subscription as torn down (QoS downgrade to 0, or
385 // unsubscribe) so QoS 1/2 delivery callbacks stop tracking new messages for
386 // it. Guarded like qos/jsDur (sess.mu or sess.subsMu). Unlike clearing
387 // sub.mqtt, this keeps the struct valid for an in-flight enqueue.
388 closed bool
389
390 // Pending serialization of retained messages to be sent when subscription
391 // is registered. The sub's delivery callbacks must wait until `prm` is
392 // ready (can block on sess.mu for that, too).
393 prm [][]byte
394
395 // If this subscription needs to be checked for being reserved. E.g. '#' or
396 // '*' or '*/'. It is set up at the time of subscription and is immutable
397 // after that.
398 reserved bool
399 }
400
401 type mqtt struct {
402 r *mqttReader
403 cp *mqttConnectProto
404 pp *mqttPublish
405 asm *mqttAccountSessionManager // quick reference to account session manager, immutable after processConnect()
406 sess *mqttSession // quick reference to session, immutable after processConnect()
407 cid string // client ID
408
409 // rejectQoS2Pub tells the MQTT client to not accept QoS2 PUBLISH, instead
410 // error and terminate the connection.
411 rejectQoS2Pub bool
412
413 // downgradeQOS2Sub tells the MQTT client to downgrade QoS2 SUBSCRIBE
414 // requests to QoS1.
415 downgradeQoS2Sub bool
416 }
417
418 type mqttPending struct {
419 sseq uint64 // stream sequence
420 jsAckSubject string // the ACK subject to send the ack to
421 jsDur string // JS durable name
422 }
423
424 type mqttConnectProto struct {
425 rd time.Duration
426 will *mqttWill
427 flags byte
428 }
429
430 type mqttIOReader interface {
431 io.Reader
432 SetReadDeadline(time.Time) error
433 }
434
435 type mqttReader struct {
436 reader mqttIOReader
437 buf []byte
438 pos int
439 pstart int
440 pbuf []byte
441 }
442
443 type mqttWriter struct {
444 bytes.Buffer
445 }
446
447 type mqttWill struct {
448 topic []byte
449 subject []byte
450 mapped []byte
451 message []byte
452 qos byte
453 retain bool
454 }
455
456 type mqttFilter struct {
457 filter string
458 qos byte
459 // Used only for tracing and should not be used after parsing of (un)sub protocols.
460 ttopic []byte
461 }
462
463 type mqttPublish struct {
464 topic []byte
465 subject []byte
466 mapped []byte
467 msg []byte
468 sz int
469 pi uint16
470 flags byte
471 }
472
473 // When we re-encode incoming MQTT PUBLISH messages for NATS delivery, we add
474 // the following headers:
475 // - "Nmqtt-Pub" (*always) indicates that the message originated from MQTT, and
476 // contains the original message QoS.
477 // - "Nmqtt-Subject" contains the original MQTT subject from mqttParsePub.
478 // - "Nmqtt-Mapped" contains the mapping during mqttParsePub.
479 //
480 // When we submit a PUBREL for delivery, we add a "Nmqtt-PubRel" header that
481 // contains the PI.
482 const (
483 // NATS header that indicates that the message originated from MQTT and
484 // stores the published message QOS.
485 mqttNatsHeader = "Nmqtt-Pub"
486 // A staged QoS2 message's mqttNatsHeader value carries a second byte after
487 // the QoS: the MQTT PUBLISH flags nibble (mqttPubFlags) as one hex char,
488 // e.g. "25" for a retained QoS2 message (0x5 = retain|QoS2). The value is a
489 // persisted, cross-version contract: byte 0 stays the bare QoS forever
490 // (older servers read only it), a missing flags byte reads as no flags, and
491 // extensions may only append bytes (a second hex char = a full private
492 // byte), never change the meaning of existing ones.
493
494 // NATS headers to store retained message metadata (along with the original
495 // message as binary).
496 mqttNatsRetainedMessageTopic = "Nmqtt-RTopic"
497 mqttNatsRetainedMessageOrigin = "Nmqtt-ROrigin"
498 mqttNatsRetainedMessageFlags = "Nmqtt-RFlags"
499 mqttNatsRetainedMessageSource = "Nmqtt-RSource"
500
501 // NATS header that indicates that the message is an MQTT PubRel and stores
502 // the PI.
503 mqttNatsPubRelHeader = "Nmqtt-PubRel"
504
505 // NATS headers to store the original MQTT subject and the subject mapping.
506 mqttNatsHeaderSubject = "Nmqtt-Subject"
507 mqttNatsHeaderMapped = "Nmqtt-Mapped"
508 )
509
510 type mqttParsedPublishNATSHeader struct {
511 qos byte
512 retained bool
513 subject []byte
514 mapped []byte
515 }
516
517 func (s *Server) startMQTT() {
518 if s.isShuttingDown() {
519 return
520 }
521
522 sopts := s.getOpts()
523 o := &sopts.MQTT
524
525 var hl net.Listener
526 var err error
527
528 port := o.Port
529 if port == -1 {
530 port = 0
531 }
532 hp := net.JoinHostPort(o.Host, strconv.Itoa(port))
533 s.mu.Lock()
534 s.mqtt.sessmgr.sessions = make(map[string]*mqttAccountSessionManager)
535 hl, err = natsListen("tcp", hp)
536 s.mqtt.listenerErr = err
537 if err != nil {
538 s.mu.Unlock()
539 s.Fatalf("Unable to listen for MQTT connections: %v", err)
540 return
541 }
542 if port == 0 {
543 o.Port = hl.Addr().(*net.TCPAddr).Port
544 }
545 s.mqtt.listener = hl
546 scheme := "mqtt"
547 if o.TLSConfig != nil {
548 scheme = "tls"
549 }
550 s.Noticef("Listening for MQTT clients on %s://%s:%d", scheme, o.Host, o.Port)
551 go s.acceptConnections(hl, "MQTT", func(conn net.Conn) { s.createMQTTClient(conn, nil) }, nil)
552 s.mu.Unlock()
553 }
554
555 // This is similar to createClient() but has some modifications specifi to MQTT clients.
556 // The comments have been kept to minimum to reduce code size. Check createClient() for
557 // more details.
558 func (s *Server) createMQTTClient(conn net.Conn, ws *websocket) *client {
559 opts := s.getOpts()
560
561 maxPay := int32(opts.MaxPayload)
562 maxSubs := int32(opts.MaxSubs)
563 if maxSubs == 0 {
564 maxSubs = -1
565 }
566 now := time.Now()
567
568 mqtt := &mqtt{
569 rejectQoS2Pub: opts.MQTT.rejectQoS2Pub,
570 downgradeQoS2Sub: opts.MQTT.downgradeQoS2Sub,
571 }
572 c := &client{srv: s, nc: conn, mpay: maxPay, msubs: maxSubs, start: now, last: now, mqtt: mqtt, ws: ws}
573 c.headers = true
574 c.mqtt.pp = &mqttPublish{}
575 // MQTT clients don't send NATS CONNECT protocols. So make it an "echo"
576 // client, but disable verbose and pedantic (by not setting them).
577 c.opts.Echo = true
578
579 c.registerWithAccount(s.globalAccount())
580
581 s.mu.Lock()
582 // Check auth, override if applicable.
583 authRequired := s.info.AuthRequired || s.mqtt.authOverride
584 s.totalClients++
585 s.mu.Unlock()
586
587 c.mu.Lock()
588 if authRequired {
589 c.flags.set(expectConnect)
590 }
591 c.initClient()
592 c.Debugf("Client connection created")
593 c.mu.Unlock()
594
595 s.mu.Lock()
596 if !s.isRunning() || s.ldm {
597 if s.isShuttingDown() {
598 conn.Close()
599 }
600 s.mu.Unlock()
601 return c
602 }
603
604 if opts.MaxConn < 0 || (opts.MaxConn > 0 && len(s.clients) >= opts.MaxConn) {
605 s.mu.Unlock()
606 c.maxConnExceeded()
607 return nil
608 }
609 s.clients[c.cid] = c
610
611 // Websocket TLS handshake is already done when getting to this function.
612 tlsRequired := opts.MQTT.TLSConfig != nil && ws == nil
613 s.mu.Unlock()
614
615 c.mu.Lock()
616
617 // In case connection has already been closed
618 if c.isClosed() {
619 c.mu.Unlock()
620 c.closeConnection(WriteError)
621 return nil
622 }
623
624 var pre []byte
625 if tlsRequired && opts.AllowNonTLS {
626 pre = make([]byte, 4)
627 c.nc.SetReadDeadline(time.Now().Add(secondsToDuration(opts.MQTT.TLSTimeout)))
628 n, _ := io.ReadFull(c.nc, pre[:])
629 c.nc.SetReadDeadline(time.Time{})
630 pre = pre[:n]
631 if n > 0 && pre[0] == 0x16 {
632 tlsRequired = true
633 } else {
634 tlsRequired = false
635 }
636 }
637
638 if tlsRequired {
639 if len(pre) > 0 {
640 c.nc = &tlsMixConn{c.nc, bytes.NewBuffer(pre)}
641 pre = nil
642 }
643
644 // Perform server-side TLS handshake.
645 if err := c.doTLSServerHandshake(tlsHandshakeMQTT, opts.MQTT.TLSConfig, opts.MQTT.TLSTimeout, opts.MQTT.TLSPinnedCerts); err != nil {
646 c.mu.Unlock()
647 return nil
648 }
649 }
650
651 if authRequired {
652 timeout := opts.AuthTimeout
653 // Possibly override with MQTT specific value.
654 if opts.MQTT.AuthTimeout != 0 {
655 timeout = opts.MQTT.AuthTimeout
656 }
657 c.setAuthTimer(secondsToDuration(timeout))
658 }
659
660 // No Ping timer for MQTT clients...
661
662 s.startGoRoutine(func() { c.readLoop(pre) })
663 s.startGoRoutine(func() { c.writeLoop() })
664
665 if tlsRequired {
666 c.Debugf("TLS handshake complete")
667 cs := c.nc.(*tls.Conn).ConnectionState()
668 c.Debugf("TLS version %s, cipher suite %s", tlsVersion(cs.Version), tls.CipherSuiteName(cs.CipherSuite))
669 }
670
671 c.mu.Unlock()
672
673 return c
674 }
675
676 // Given the mqtt options, we check if any auth configuration
677 // has been provided. If so, possibly create users/nkey users and
678 // store them in s.mqtt.users/nkeys.
679 // Also update a boolean that indicates if auth is required for
680 // mqtt clients.
681 // Server lock is held on entry.
682 func (s *Server) mqttConfigAuth(opts *MQTTOpts) {
683 mqtt := &s.mqtt
684 // If any of those is specified, we consider that there is an override.
685 mqtt.authOverride = opts.Username != _EMPTY_ || opts.Token != _EMPTY_ || opts.NoAuthUser != _EMPTY_
686 }
687
688 // Validate the mqtt related options.
689 func validateMQTTOptions(o *Options) error {
690 mo := &o.MQTT
691 // If no port is defined, we don't care about other options
692 if mo.Port == 0 {
693 return nil
694 }
695 // We have to force the server name to be explicitly set and be unique when
696 // in cluster mode.
697 if o.ServerName == _EMPTY_ && (o.Cluster.Port != 0 || o.Gateway.Port != 0) {
698 return errMQTTServerNameMustBeSet
699 }
700 // If there is a NoAuthUser, we need to have Users defined and
701 // the user to be present.
702 if mo.NoAuthUser != _EMPTY_ {
703 if err := validateNoAuthUser(o, mo.NoAuthUser); err != nil {
704 return err
705 }
706 }
707 // Token/Username not possible if there are users/nkeys
708 if len(o.Users) > 0 || len(o.Nkeys) > 0 {
709 if mo.Username != _EMPTY_ {
710 return errMQTTUserMixWithUsersNKeys
711 }
712 if mo.Token != _EMPTY_ {
713 return errMQTTTokenMixWIthUsersNKeys
714 }
715 }
716 if mo.AckWait < 0 {
717 return errMQTTAckWaitMustBePositive
718 }
719 if mo.JSAPITimeout < 0 {
720 return errMQTTJSAPITimeoutMustBePositive
721 }
722 // If strictly standalone and there is no JS enabled, then it won't work...
723 // For leafnodes, we could either have remote(s) and it would be ok, or no
724 // remote but accept from a remote side that has "hub" property set, which
725 // then would ok too. So we fail only if we have no leafnode config at all.
726 if !o.JetStream && o.Cluster.Port == 0 && o.Gateway.Port == 0 &&
727 o.LeafNode.Port == 0 && len(o.LeafNode.Remotes) == 0 {
728 return errMQTTStandaloneNeedsJetStream
729 }
730 if err := validatePinnedCerts(mo.TLSPinnedCerts); err != nil {
731 return fmt.Errorf("mqtt: %v", err)
732 }
733 if mo.ConsumerReplicas > 0 && mo.StreamReplicas > 0 && mo.ConsumerReplicas > mo.StreamReplicas {
734 return fmt.Errorf("mqtt: consumer_replicas (%v) cannot be higher than stream_replicas (%v)",
735 mo.ConsumerReplicas, mo.StreamReplicas)
736 }
737 return nil
738 }
739
740 // Returns true if this connection is from a MQTT client.
741 // Lock held on entry.
742 func (c *client) isMqtt() bool {
743 return c.mqtt != nil
744 }
745
746 // If this is an MQTT client, returns the session client ID,
747 // otherwise returns the empty string.
748 // Lock held on entry
749 func (c *client) getMQTTClientID() string {
750 if !c.isMqtt() {
751 return _EMPTY_
752 }
753 return c.mqtt.cid
754 }
755
756 // Parse protocols inside the given buffer.
757 // This is invoked from the readLoop.
758 func (c *client) mqttParse(buf []byte) error {
759 c.mu.Lock()
760 s := c.srv
761 trace := c.trace
762 connected := c.flags.isSet(connectReceived)
763 mqtt := c.mqtt
764 r := mqtt.r
765 var rd time.Duration
766 if mqtt.cp != nil {
767 rd = mqtt.cp.rd
768 if rd > 0 {
769 r.reader.SetReadDeadline(time.Time{})
770 }
771 }
772 hasMappings := c.in.flags.isSet(hasMappings)
773 c.mu.Unlock()
774
775 r.reset(buf)
776
777 var err error
778 var b byte
779 var pl int
780 var complete bool
781
782 for err == nil && r.hasMore() {
783
784 // Keep track of the starting of the packet, in case we have a partial
785 r.pstart = r.pos
786
787 // Read packet type and flags
788 if b, err = r.readByte("packet type"); err != nil {
789 break
790 }
791
792 // Packet type
793 pt := b & mqttPacketMask
794
795 // If client was not connected yet, the first packet must be
796 // a mqttPacketConnect otherwise we fail the connection.
797 if !connected && pt != mqttPacketConnect {
798 // If the buffer indicates that it may be a websocket handshake
799 // but the client is not websocket, it means that the client
800 // connected to the MQTT port instead of the Websocket port.
801 if bytes.HasPrefix(buf, []byte("GET ")) && !c.isWebsocket() {
802 err = errMQTTNotWebsocketPort
803 } else {
804 err = fmt.Errorf("the first packet should be a CONNECT (%v), got %v", mqttPacketConnect, pt)
805 }
806 break
807 }
808 if err = mqttCheckFixedHeaderFlags(pt, b&mqttPacketFlagMask); err != nil {
809 break
810 }
811
812 maxLen := int32(jwt.NoLimit)
813 if !connected {
814 maxLen = atomic.LoadInt32(&c.mpay)
815 }
816 pl, complete, err = r.readPacketLen(maxLen)
817 if err != nil || !complete {
818 if err == ErrMaxPayload {
819 c.maxPayloadViolation(pl, maxLen)
820 }
821 break
822 }
823 if err = mqttCheckRemainingLength(pt, pl); err != nil {
824 break
825 }
826
827 switch pt {
828 // Packets that we receive back when we act as the "sender": PUBACK,
829 // PUBREC, PUBCOMP.
830 case mqttPacketPubAck:
831 var pi uint16
832 pi, err = mqttParsePIPacket(r)
833 if trace {
834 c.traceInOp("PUBACK", errOrTrace(err, fmt.Sprintf("pi=%v", pi)))
835 }
836 if err == nil {
837 err = c.mqttProcessPubAck(pi)
838 }
839
840 case mqttPacketPubRec:
841 var pi uint16
842 pi, err = mqttParsePIPacket(r)
843 if trace {
844 c.traceInOp("PUBREC", errOrTrace(err, fmt.Sprintf("pi=%v", pi)))
845 }
846 if err == nil {
847 err = c.mqttProcessPubRec(pi)
848 }
849
850 case mqttPacketPubComp:
851 var pi uint16
852 pi, err = mqttParsePIPacket(r)
853 if trace {
854 c.traceInOp("PUBCOMP", errOrTrace(err, fmt.Sprintf("pi=%v", pi)))
855 }
856 if err == nil {
857 c.mqttProcessPubComp(pi)
858 }
859
860 // Packets where we act as the "receiver": PUBLISH, PUBREL, SUBSCRIBE, UNSUBSCRIBE.
861 case mqttPacketPub:
862 pp := c.mqtt.pp
863 pp.flags = b & mqttPacketFlagMask
864 err = c.mqttParsePub(r, pl, pp, hasMappings)
865 if trace {
866 c.traceInOp("PUBLISH", errOrTrace(err, mqttPubTrace(pp)))
867 if err == nil {
868 c.mqttTraceMsg(pp.msg)
869 }
870 }
871 if err == nil {
872 err = s.mqttProcessPub(c, pp, trace)
873 }
874
875 case mqttPacketPubRel:
876 var pi uint16
877 pi, err = mqttParsePIPacket(r)
878 if trace {
879 c.traceInOp("PUBREL", errOrTrace(err, fmt.Sprintf("pi=%v", pi)))
880 }
881 if err == nil {
882 err = s.mqttProcessPubRel(c, pi, trace)
883 }
884
885 case mqttPacketSub:
886 var pi uint16 // packet identifier
887 var filters []*mqttFilter
888 var subs []*subscription
889 pi, filters, err = c.mqttParseSubs(r, b, pl)
890 if trace {
891 c.traceInOp("SUBSCRIBE", errOrTrace(err, mqttSubscribeTrace(pi, filters)))
892 }
893 if err == nil {
894 subs, err = c.mqttProcessSubs(filters)
895 if err == nil && trace {
896 c.traceOutOp("SUBACK", []byte(fmt.Sprintf("pi=%v", pi)))
897 }
898 }
899 if err == nil {
900 c.mqttEnqueueSubAck(pi, filters)
901 c.mqttSendRetainedMsgsToNewSubs(subs)
902 }
903
904 case mqttPacketUnsub:
905 var pi uint16 // packet identifier
906 var filters []*mqttFilter
907 pi, filters, err = c.mqttParseUnsubs(r, b, pl)
908 if trace {
909 c.traceInOp("UNSUBSCRIBE", errOrTrace(err, mqttUnsubscribeTrace(pi, filters)))
910 }
911 if err == nil {
912 err = c.mqttProcessUnsubs(filters)
913 if err == nil && trace {
914 c.traceOutOp("UNSUBACK", []byte(fmt.Sprintf("pi=%v", pi)))
915 }
916 }
917 if err == nil {
918 c.mqttEnqueueUnsubAck(pi)
919 }
920
921 // Packets that we get both as a receiver and sender: PING, CONNECT, DISCONNECT
922 case mqttPacketPing:
923 if trace {
924 c.traceInOp("PINGREQ", nil)
925 }
926 c.mqttEnqueuePingResp()
927 if trace {
928 c.traceOutOp("PINGRESP", nil)
929 }
930
931 case mqttPacketConnect:
932 // It is an error to receive a second connect packet
933 if connected {
934 err = errMQTTSecondConnectPacket
935 break
936 }
937 var rc byte
938 var cp *mqttConnectProto
939 var sessp bool
940 rc, cp, err = c.mqttParseConnect(r, hasMappings)
941 // Add the client id to the client's string, regardless of error.
942 // We may still get the client_id if the call above fails somewhere
943 // after parsing the client ID itself.
944 c.ncs.Store(fmt.Sprintf("%s - %q", c, c.mqtt.cid))
945 if trace && cp != nil {
946 c.traceInOp("CONNECT", errOrTrace(err, c.mqttConnectTrace(cp)))
947 }
948 if rc != 0 {
949 c.mqttEnqueueConnAck(rc, sessp)
950 if trace {
951 c.traceOutOp("CONNACK", []byte(fmt.Sprintf("sp=%v rc=%v", sessp, rc)))
952 }
953 } else if err == nil {
954 if err = s.mqttProcessConnect(c, cp, trace); err != nil {
955 err = fmt.Errorf("unable to connect: %v", err)
956 } else {
957 // Add this debug statement so users running in Debug mode
958 // will have the client id printed here for the first time.
959 c.Debugf("Client connected")
960 connected = true
961 rd = cp.rd
962 }
963 }
964
965 case mqttPacketDisconnect:
966 if trace {
967 c.traceInOp("DISCONNECT", nil)
968 }
969 // Normal disconnect, we need to discard the will.
970 // Spec [MQTT-3.1.2-8]
971 c.mu.Lock()
972 if c.mqtt.cp != nil {
973 c.mqtt.cp.will = nil
974 }
975 c.mu.Unlock()
976 s.mqttHandleClosedClient(c)
977 c.closeConnection(ClientClosed)
978 return nil
979
980 default:
981 err = fmt.Errorf("received unknown packet type %d", pt>>4)
982 }
983 }
984 if err == nil && rd > 0 {
985 r.reader.SetReadDeadline(time.Now().Add(rd))
986 }
987 return err
988 }
989
990 func mqttCheckFixedHeaderFlags(packetType, flags byte) error {
991 var expected byte
992 switch packetType {
993 case mqttPacketConnect, mqttPacketPubAck, mqttPacketPubRec, mqttPacketPubComp,
994 mqttPacketPing, mqttPacketDisconnect:
995 expected = 0
996 case mqttPacketPubRel, mqttPacketSub, mqttPacketUnsub:
997 expected = 0x2
998 case mqttPacketPub:
999 return nil
1000 default:
1001 return nil
1002 }
1003 if flags != expected {
1004 return fmt.Errorf("invalid fixed header flags %x for packet type %x", flags, packetType)
1005 }
1006 return nil
1007 }
1008
1009 func mqttCheckRemainingLength(packetType byte, pl int) error {
1010 var expected int
1011 switch packetType {
1012 case mqttPacketConnect, mqttPacketPub, mqttPacketSub, mqttPacketUnsub:
1013 return nil
1014 case mqttPacketPubAck, mqttPacketPubRec, mqttPacketPubRel, mqttPacketPubComp:
1015 expected = 2
1016 case mqttPacketPing, mqttPacketDisconnect:
1017 expected = 0
1018 default:
1019 return nil
1020 }
1021 if pl != expected {
1022 return fmt.Errorf("invalid remaining length %d for packet type %x", pl, packetType)
1023 }
1024 return nil
1025 }
1026
1027 func (c *client) mqttTraceMsg(msg []byte) {
1028 maxTrace := c.srv.getOpts().MaxTracedMsgLen
1029 if maxTrace > 0 && len(msg) > maxTrace {
1030 c.Tracef("<<- MSG_PAYLOAD: [\"%s...\"]", msg[:maxTrace])
1031 } else {
1032 c.Tracef("<<- MSG_PAYLOAD: [%q]", msg)
1033 }
1034 }
1035
1036 // The MQTT client connection has been closed, or the DISCONNECT packet was received.
1037 // For a "clean" session, we will delete the session, otherwise, simply removing
1038 // the binding. We will also send the "will" message if applicable.
1039 //
1040 // Runs from the client's readLoop.
1041 // No lock held on entry.
1042 func (s *Server) mqttHandleClosedClient(c *client) {
1043 c.mu.Lock()
1044 asm := c.mqtt.asm
1045 sess := c.mqtt.sess
1046 c.mu.Unlock()
1047
1048 // If asm or sess are nil, it means that we have failed a client
1049 // before it was associated with a session, so nothing more to do.
1050 if asm == nil || sess == nil {
1051 return
1052 }
1053
1054 // Add this session to the locked map for the rest of the execution.
1055 if err := asm.lockSession(sess, c); err != nil {
1056 return
1057 }
1058 defer asm.unlockSession(sess)
1059
1060 asm.mu.Lock()
1061 // Clear the client from the session, but session may stay.
1062 sess.mu.Lock()
1063 sess.c = nil
1064 doClean := sess.clean
1065 sess.mu.Unlock()
1066 // If it was a clean session, then we remove from the account manager,
1067 // and we will call clear() outside of any lock.
1068 if doClean {
1069 asm.removeSession(sess, false)
1070 }
1071 // Remove in case it was in the flappers map.
1072 asm.removeSessFromFlappers(sess.id)
1073 asm.mu.Unlock()
1074
1075 // This needs to be done outside of any lock.
1076 if doClean {
1077 if err := sess.clear(true); err != nil {
1078 c.Errorf(err.Error())
1079 }
1080 }
1081
1082 // Now handle the "will". This function will be a no-op if there is no "will" to send.
1083 s.mqttHandleWill(c)
1084 }
1085
1086 // Updates the MaxAckPending for all MQTT sessions, updating the
1087 // JetStream consumers and updating their max ack pending and forcing
1088 // a expiration of pending messages.
1089 //
1090 // Runs from a server configuration reload routine.
1091 // No lock held on entry.
1092 func (s *Server) mqttUpdateMaxAckPending(newmaxp uint16) {
1093 msm := &s.mqtt.sessmgr
1094 s.accounts.Range(func(k, _ any) bool {
1095 accName := k.(string)
1096 msm.mu.RLock()
1097 asm := msm.sessions[accName]
1098 msm.mu.RUnlock()
1099 if asm == nil {
1100 // Move to next account
1101 return true
1102 }
1103 asm.mu.RLock()
1104 for _, sess := range asm.sessions {
1105 sess.mu.Lock()
1106 sess.maxp = newmaxp
1107 sess.mu.Unlock()
1108 }
1109 asm.mu.RUnlock()
1110 return true
1111 })
1112 }
1113
1114 func (s *Server) mqttGetJSAForAccount(acc string) *mqttJSA {
1115 sm := &s.mqtt.sessmgr
1116
1117 sm.mu.RLock()
1118 asm := sm.sessions[acc]
1119 sm.mu.RUnlock()
1120
1121 if asm == nil {
1122 return nil
1123 }
1124
1125 asm.mu.RLock()
1126 jsa := &asm.jsa
1127 asm.mu.RUnlock()
1128 return jsa
1129 }
1130
1131 func (s *Server) mqttStoreQoSMsgForAccountOnNewSubject(hdr int, msg []byte, acc, subject string) {
1132 if s == nil || hdr <= 0 {
1133 return
1134 }
1135 h := mqttParsePublishNATSHeader(msg[:hdr])
1136 if h == nil || h.qos == 0 {
1137 return
1138 }
1139 jsa := s.mqttGetJSAForAccount(acc)
1140 if jsa == nil {
1141 return
1142 }
1143 jsa.storeMsg(mqttStreamSubjectPrefix+subject, hdr, msg)
1144 }
1145
1146 // Encodes the MQTT PUBLISH flags nibble (mqttPubFlags) as one hex char, the
1147 // flags byte that follows the QoS in a mqttNatsHeader value.
1148 func mqttNatsHeaderEncodeFlags(ppFlags byte) byte {
1149 return "0123456789abcdef"[ppFlags&mqttPubFlags]
1150 }
1151
1152 // Decodes the MQTT flags nibble carried after the QoS in a mqttNatsHeader
1153 // value; values without the flags byte read as no flags set. Callers test the
1154 // result with the mqttPubFlag* bits.
1155 func mqttNatsHeaderDecodeFlags(value []byte) byte {
1156 if len(value) < 2 {
1157 return 0
1158 }
1159 switch c := value[1]; {
1160 case c >= '0' && c <= '9':
1161 return c - '0'
1162 case c >= 'a' && c <= 'f':
1163 return c - 'a' + 10
1164 }
1165 return 0
1166 }
1167
1168 func mqttParsePublishNATSHeader(headerBytes []byte) *mqttParsedPublishNATSHeader {
1169 if len(headerBytes) == 0 {
1170 return nil
1171 }
1172
1173 pubValue := getHeader(mqttNatsHeader, headerBytes)
1174 if len(pubValue) == 0 {
1175 return nil
1176 }
1177 return &mqttParsedPublishNATSHeader{
1178 qos: pubValue[0] - '0',
1179 retained: mqttIsRetained(mqttNatsHeaderDecodeFlags(pubValue)),
1180 subject: getHeader(mqttNatsHeaderSubject, headerBytes),
1181 mapped: getHeader(mqttNatsHeaderMapped, headerBytes),
1182 }
1183 }
1184
1185 func mqttParsePubRelNATSHeader(headerBytes []byte) uint16 {
1186 if len(headerBytes) == 0 {
1187 return 0
1188 }
1189
1190 pubrelValue := getHeader(mqttNatsPubRelHeader, headerBytes)
1191 if len(pubrelValue) == 0 {
1192 return 0
1193 }
1194 pi, _ := strconv.ParseUint(string(pubrelValue), 10, 16)
1195 return uint16(pi)
1196 }
1197
1198 // Returns the MQTT sessions manager for a given account.
1199 // If new, creates the required JetStream streams/consumers
1200 // for handling of sessions and messages.
1201 func (s *Server) getOrCreateMQTTAccountSessionManager(c *client) (*mqttAccountSessionManager, error) {
1202 sm := &s.mqtt.sessmgr
1203
1204 c.mu.Lock()
1205 acc := c.acc
1206 c.mu.Unlock()
1207 accName := acc.GetName()
1208
1209 sm.mu.RLock()
1210 asm, ok := sm.sessions[accName]
1211 sm.mu.RUnlock()
1212
1213 if ok {
1214 return asm, nil
1215 }
1216
1217 // We will pass the quitCh to the account session manager if we happen to create it.
1218 s.mu.Lock()
1219 quitCh := s.quitCh
1220 s.mu.Unlock()
1221
1222 // Not found, now take the write lock and check again
1223 sm.mu.Lock()
1224 defer sm.mu.Unlock()
1225 asm, ok = sm.sessions[accName]
1226 if ok {
1227 return asm, nil
1228 }
1229 // Need to create one here.
1230 asm, err := s.mqttCreateAccountSessionManager(acc, quitCh)
1231 if err != nil {
1232 return nil, err
1233 }
1234 sm.sessions[accName] = asm
1235 return asm, nil
1236 }
1237
1238 // Creates JS streams/consumers for handling of sessions and messages for this account.
1239 //
1240 // Global session manager lock is held on entry.
1241 func (s *Server) mqttCreateAccountSessionManager(acc *Account, quitCh chan struct{}) (*mqttAccountSessionManager, error) {
1242 var err error
1243
1244 accName := acc.GetName()
1245
1246 opts := s.getOpts()
1247 c := s.createInternalAccountClient()
1248 c.acc = acc
1249
1250 id := s.NodeName()
1251
1252 mqttJSAPITimeout := opts.MQTT.JSAPITimeout
1253 if mqttJSAPITimeout == 0 {
1254 mqttJSAPITimeout = mqttDefaultJSAPITimeout
1255 }
1256
1257 replicas := opts.MQTT.StreamReplicas
1258 if replicas <= 0 {
1259 replicas = s.mqttDetermineReplicas()
1260 }
1261 qname := fmt.Sprintf("[ACC:%s] MQTT ", accName)
1262 as := &mqttAccountSessionManager{
1263 sessions: make(map[string]*mqttSession),
1264 sessByHash: make(map[string]*mqttSession),
1265 sessLocked: make(map[string]struct{}),
1266 flappers: make(map[string]time.Time),
1267 jsa: mqttJSA{
1268 id: id,
1269 c: c,
1270 rplyr: mqttJSARepliesPrefix + id + ".",
1271 sendq: newIPQueue[*mqttJSPubMsg](s, qname+"send"),
1272 nuid: nuid.New(),
1273 quitCh: quitCh,
1274 timeout: mqttJSAPITimeout,
1275 },
1276 rmsCache: &sync.Map{},
1277 }
1278 // TODO record domain name in as here
1279
1280 // The domain to communicate with may be required for JS calls.
1281 // Search from specific (per account setting) to generic (mqtt setting)
1282 if opts.JsAccDefaultDomain != nil {
1283 if d, ok := opts.JsAccDefaultDomain[accName]; ok {
1284 if d != _EMPTY_ {
1285 as.jsa.domain = d
1286 }
1287 as.jsa.domainSet = true
1288 }
1289 // in case domain was set to empty, check if there are more generic domain overwrites
1290 }
1291 if as.jsa.domain == _EMPTY_ {
1292 if d := opts.MQTT.JsDomain; d != _EMPTY_ {
1293 as.jsa.domain = d
1294 as.jsa.domainSet = true
1295 }
1296 }
1297 // We need to include the domain in the subject prefix used to store sessions in the $MQTT_sess stream.
1298 if as.jsa.domainSet {
1299 if as.jsa.domain != _EMPTY_ {
1300 as.domainTk = as.jsa.domain + "."
1301 }
1302 } else if d := s.getOpts().JetStreamDomain; d != _EMPTY_ {
1303 as.domainTk = d + "."
1304 }
1305 if as.jsa.domainSet {
1306 s.Noticef("Creating MQTT streams/consumers with replicas %v for account %q in domain %q", replicas, accName, as.jsa.domain)
1307 } else {
1308 s.Noticef("Creating MQTT streams/consumers with replicas %v for account %q", replicas, accName)
1309 }
1310
1311 var subs []*subscription
1312 var success bool
1313 closeCh := make(chan struct{})
1314
1315 defer func() {
1316 if success {
1317 return
1318 }
1319 for _, sub := range subs {
1320 c.processUnsub(sub.sid)
1321 }
1322 close(closeCh)
1323 }()
1324
1325 // We create all subscriptions before starting the go routine that will do
1326 // sends otherwise we could get races.
1327 // Note that using two different clients (one for the subs, one for the
1328 // sends) would cause other issues such as registration of recent subs in
1329 // the "sub" client would be invisible to the check for GW routed replies
1330 // (shouldMapReplyForGatewaySend) since the client there would be the "sender".
1331
1332 jsa := &as.jsa
1333 sid := int64(1)
1334 // This is a subscription that will process all JS API replies. We could split to
1335 // individual subscriptions if needed, but since there is a bit of common code,
1336 // that seemed like a good idea to be all in one place.
1337 if err := as.createSubscription(jsa.rplyr+">",
1338 as.processJSAPIReplies, &sid, &subs); err != nil {
1339 return nil, err
1340 }
1341
1342 // We will listen for replies to session persist requests so that we can
1343 // detect the use of a session with the same client ID anywhere in the cluster.
1344 // `$MQTT.JSA.{js-id}.SP.{client-id-hash}.{uuid}`
1345 if err := as.createSubscription(mqttJSARepliesPrefix+"*."+mqttJSASessPersist+".*.*",
1346 as.processSessionPersist, &sid, &subs); err != nil {
1347 return nil, err
1348 }
1349
1350 // We create the subscription on "$MQTT.sub.<nuid>" to limit the subjects
1351 // that a user would allow permissions on.
1352 rmsubj := mqttSubPrefix + nuid.Next()
1353 if err := as.createSubscription(rmsubj, as.processRetainedMsg, &sid, &subs); err != nil {
1354 return nil, err
1355 }
1356
1357 // Create a subscription to be notified of retained messages delete requests.
1358 rmdelsubj := mqttJSARepliesPrefix + "*." + mqttJSARetainedMsgDel
1359 if err := as.createSubscription(rmdelsubj, as.processRetainedMsgDel, &sid, &subs); err != nil {
1360 return nil, err
1361 }
1362
1363 // No more creation of subscriptions past this point otherwise RACEs may happen.
1364
1365 // Start the go routine that will send JS API requests.
1366 s.startGoRoutine(func() {
1367 defer s.grWG.Done()
1368 as.sendJSAPIrequests(s, c, accName, closeCh)
1369 })
1370
1371 // Start the go routine that will clean up cached retained messages that expired.
1372 s.startGoRoutine(func() {
1373 defer s.grWG.Done()
1374 as.cleanupRetainedMessageCache(s, closeCh)
1375 })
1376
1377 lookupStream := func(stream, txt string) (*StreamInfo, error) {
1378 si, err := jsa.lookupStream(stream)
1379 if err != nil {
1380 if IsNatsErr(err, JSStreamNotFoundErr) {
1381 return nil, nil
1382 }
1383 return nil, fmt.Errorf("lookup %s stream for account %q: %v", txt, accName, err)
1384 }
1385 if opts.MQTT.StreamReplicas == 0 {
1386 return si, nil
1387 }
1388 sr := 1
1389 if si.Cluster != nil {
1390 sr += len(si.Cluster.Replicas)
1391 }
1392 if replicas != sr {
1393 s.Warnf("MQTT %s stream replicas mismatch: current is %v but configuration is %v for '%s > %s'",
1394 txt, sr, replicas, accName, stream)
1395 }
1396 return si, nil
1397 }
1398
1399 if si, err := lookupStream(mqttSessStreamName, "sessions"); err != nil {
1400 return nil, err
1401 } else if si == nil {
1402 // Create the stream for the sessions.
1403 cfg := &StreamConfig{
1404 Name: mqttSessStreamName,
1405 Subjects: []string{mqttSessStreamSubjectPrefix + as.domainTk + ">"},
1406 Storage: FileStorage,
1407 Retention: LimitsPolicy,
1408 Replicas: replicas,
1409 MaxMsgsPer: 1,
1410 }
1411 if _, created, err := jsa.createStream(cfg); err == nil && created {
1412 as.transferUniqueSessStreamsToMuxed(s)
1413 } else if isErrorOtherThan(err, JSStreamNameExistErr) {
1414 return nil, fmt.Errorf("create sessions stream for account %q: %v", accName, err)
1415 }
1416 }
1417
1418 if si, err := lookupStream(mqttStreamName, "messages"); err != nil {
1419 return nil, err
1420 } else if si == nil {
1421 // Create the stream for the messages.
1422 cfg := &StreamConfig{
1423 Name: mqttStreamName,
1424 Subjects: []string{mqttStreamSubjectPrefix + ">"},
1425 Storage: FileStorage,
1426 Retention: InterestPolicy,
1427 Replicas: replicas,
1428 }
1429 if _, _, err := jsa.createStream(cfg); isErrorOtherThan(err, JSStreamNameExistErr) {
1430 return nil, fmt.Errorf("create messages stream for account %q: %v", accName, err)
1431 }
1432 }
1433
1434 if si, err := lookupStream(mqttQoS2IncomingMsgsStreamName, "QoS2 incoming messages"); err != nil {
1435 return nil, err
1436 } else if si == nil {
1437 // Create the stream for the incoming QoS2 messages that have not been
1438 // PUBREL-ed by the sender. Subject is
1439 // "$MQTT.qos2.<session>.<PI>", the .PI is to achieve exactly
1440 // once for each PI.
1441 cfg := &StreamConfig{
1442 Name: mqttQoS2IncomingMsgsStreamName,
1443 Subjects: []string{mqttQoS2IncomingMsgsStreamSubjectPrefix + ">"},
1444 Storage: FileStorage,
1445 Retention: LimitsPolicy,
1446 Discard: DiscardNew,
1447 MaxMsgsPer: 1,
1448 DiscardNewPer: true,
1449 Replicas: replicas,
1450 }
1451 if _, _, err := jsa.createStream(cfg); isErrorOtherThan(err, JSStreamNameExistErr) {
1452 return nil, fmt.Errorf("create QoS2 incoming messages stream for account %q: %v", accName, err)
1453 }
1454 }
1455
1456 if si, err := lookupStream(mqttOutStreamName, "QoS2 outgoing PUBREL"); err != nil {
1457 return nil, err
1458 } else if si == nil {
1459 // Create the stream for the incoming QoS2 messages that have not been
1460 // PUBREL-ed by the sender. NATS messages are submitted as
1461 // "$MQTT.pubrel.<session hash>"
1462 cfg := &StreamConfig{
1463 Name: mqttOutStreamName,
1464 Subjects: []string{mqttOutSubjectPrefix + ">"},
1465 Storage: FileStorage,
1466 Retention: InterestPolicy,
1467 Replicas: replicas,
1468 }
1469 if _, _, err := jsa.createStream(cfg); isErrorOtherThan(err, JSStreamNameExistErr) {
1470 return nil, fmt.Errorf("create QoS2 outgoing PUBREL stream for account %q: %v", accName, err)
1471 }
1472 }
1473
1474 // This is the only case where we need "si" after lookup/create
1475 needToTransfer := true
1476 si, err := lookupStream(mqttRetainedMsgsStreamName, "retained messages")
1477 switch {
1478 case err != nil:
1479 return nil, err
1480
1481 case si == nil:
1482 // Create the stream for retained messages.
1483 cfg := &StreamConfig{
1484 Name: mqttRetainedMsgsStreamName,
1485 Subjects: []string{mqttRetainedMsgsStreamSubject + ">"},
1486 Storage: FileStorage,
1487 Retention: LimitsPolicy,
1488 Replicas: replicas,
1489 MaxMsgsPer: 1,
1490 }
1491 // We will need "si" outside of this block.
1492 si, _, err = jsa.createStream(cfg)
1493 if err != nil {
1494 if isErrorOtherThan(err, JSStreamNameExistErr) {
1495 return nil, fmt.Errorf("create retained messages stream for account %q: %v", accName, err)
1496 }
1497 // Suppose we had a race and the stream was actually created by another
1498 // node, we really need "si" after that, so lookup the stream again here.
1499 si, err = lookupStream(mqttRetainedMsgsStreamName, "retained messages")
1500 if err != nil {
1501 return nil, err
1502 }
1503 }
1504 needToTransfer = false
1505
1506 default:
1507 needToTransfer = si.Config.MaxMsgsPer != 1
1508 }
1509 // Guard before dereferencing si.Config below.
1510 if si == nil {
1511 return nil, fmt.Errorf("could not look up or create the retained messages stream for account %q", accName)
1512 }
1513
1514 // Doing this check outside of above if/else due to possible race when
1515 // creating the stream.
1516 wantedSubj := mqttRetainedMsgsStreamSubject + ">"
1517 if len(si.Config.Subjects) != 1 || si.Config.Subjects[0] != wantedSubj {
1518 // Update only the Subjects at this stage, not MaxMsgsPer yet.
1519 si.Config.Subjects = []string{wantedSubj}
1520 if si, err = jsa.updateStream(&si.Config); err != nil {
1521 return nil, fmt.Errorf("failed to update stream config: %w", err)
1522 }
1523 }
1524
1525 transferRMS := func() error {
1526 if !needToTransfer {
1527 return nil
1528 }
1529
1530 as.transferRetainedToPerKeySubjectStream(s)
1531
1532 // We need another lookup to have up-to-date si.State values in order
1533 // to load all retained messages.
1534 si, err = lookupStream(mqttRetainedMsgsStreamName, "retained messages")
1535 if err != nil {
1536 return err
1537 }
1538 needToTransfer = false
1539 return nil
1540 }
1541
1542 // Attempt to transfer all "single subject" retained messages to new
1543 // subjects. It may fail, will log its own error; ignore it the first time
1544 // and proceed to updating MaxMsgsPer. Then we invoke transferRMS() again,
1545 // which will get another chance to resolve the error; if not we bail there.
1546 if err = transferRMS(); err != nil {
1547 return nil, err
1548 }
1549 // Guard before dereferencing si.Config below.
1550 if si == nil {
1551 return nil, fmt.Errorf("could not look up the retained messages stream for account %q", accName)
1552 }
1553
1554 // Now, if the stream does not have MaxMsgsPer set to 1, and there are no
1555 // more messages on the single $MQTT.rmsgs subject, update the stream again.
1556 if si.Config.MaxMsgsPer != 1 {
1557 si.Config.MaxMsgsPer = 1
1558 // We will need an up-to-date si, so don't use local variable here.
1559 if si, err = jsa.updateStream(&si.Config); err != nil {
1560 return nil, fmt.Errorf("failed to update stream config: %w", err)
1561 }
1562 }
1563
1564 // If we failed the first time, there is now at most one lingering message
1565 // in the old subject. Try again (it will be a NO-OP if succeeded the first
1566 // time).
1567 if err = transferRMS(); err != nil {
1568 return nil, err
1569 }
1570
1571 // Opportunistically delete the old (legacy) consumer, from v2.10.10 and
1572 // before. Ignore any errors that might arise.
1573 rmLegacyDurName := mqttRetainedMsgsStreamName + "_" + jsa.id
1574 jsa.deleteConsumer(mqttRetainedMsgsStreamName, rmLegacyDurName, true)
1575
1576 // Create a new, uniquely names consumer for retained messages for this
1577 // server. The prior one will expire eventually.
1578 ccfg := &CreateConsumerRequest{
1579 Stream: mqttRetainedMsgsStreamName,
1580 Config: ConsumerConfig{
1581 Name: mqttRetainedMsgsStreamName + "_" + nuid.Next(),
1582 FilterSubject: mqttRetainedMsgsStreamSubject + ">",
1583 DeliverSubject: rmsubj,
1584 ReplayPolicy: ReplayInstant,
1585 AckPolicy: AckNone,
1586 InactiveThreshold: 5 * time.Minute,
1587 },
1588 }
1589 if _, err := jsa.createEphemeralConsumer(ccfg); err != nil {
1590 return nil, fmt.Errorf("create retained messages consumer for account %q: %v", accName, err)
1591 }
1592
1593 // Set this so that on defer we don't cleanup.
1594 success = true
1595
1596 return as, nil
1597 }
1598
1599 func (s *Server) mqttDetermineReplicas() int {
1600 // If not clustered, then replica will be 1.
1601 if !s.JetStreamIsClustered() {
1602 return 1
1603 }
1604 opts := s.getOpts()
1605 replicas := 0
1606 for _, u := range opts.Routes {
1607 host := u.Hostname()
1608 // If this is an IP just add one.
1609 if net.ParseIP(host) != nil {
1610 replicas++
1611 } else {
1612 addrs, _ := net.LookupHost(host)
1613 replicas += len(addrs)
1614 }
1615 }
1616 if replicas < 1 {
1617 replicas = 1
1618 } else if replicas > 3 {
1619 replicas = 3
1620 }
1621 return replicas
1622 }
1623
1624 //////////////////////////////////////////////////////////////////////////////
1625 //
1626 // JS APIs related functions
1627 //
1628 //////////////////////////////////////////////////////////////////////////////
1629
1630 func (jsa *mqttJSA) newRequest(kind, subject string, hdr int, msg []byte) (any, error) {
1631 return jsa.newRequestEx(kind, subject, _EMPTY_, hdr, msg)
1632 }
1633
1634 func (jsa *mqttJSA) prefixDomain(subject string) string {
1635 if jsa.domain != _EMPTY_ {
1636 // rewrite js api prefix with domain
1637 if sub := strings.TrimPrefix(subject, JSApiPrefix+"."); sub != subject {
1638 subject = fmt.Sprintf("$JS.%s.API.%s", jsa.domain, sub)
1639 }
1640 }
1641 return subject
1642 }
1643
1644 func (jsa *mqttJSA) newRequestEx(kind, subject, cidHash string, hdr int, msg []byte) (any, error) {
1645 responses, err := jsa.newRequestExMulti(kind, subject, cidHash, []int{hdr}, [][]byte{msg})
1646 if err != nil {
1647 return nil, err
1648 }
1649 if len(responses) != 1 {
1650 return nil, fmt.Errorf("unreachable: invalid number of responses (%d)", len(responses))
1651 }
1652 return responses[0].value, nil
1653 }
1654
1655 // newRequestExMulti sends multiple messages on the same subject and waits for
1656 // all responses. It returns the same number of responses in the same order as
1657 // msgs parameter. In case of a timeout it returns an error as well as all
1658 // responses received as a sparsely populated array, matching msgs, with nils
1659 // for the values that have not yet been received.
1660 //
1661 // Note that each response may represent an error and should be inspected as
1662 // such by the caller.
1663 func (jsa *mqttJSA) newRequestExMulti(kind, subject, cidHash string, hdrs []int, msgs [][]byte) ([]*mqttJSAResponse, error) {
1664 if len(hdrs) != len(msgs) {
1665 return nil, fmt.Errorf("unreachable: invalid number of messages (%d) or header offsets (%d)", len(msgs), len(hdrs))
1666 }
1667 responseCh := make(chan *mqttJSAResponse, len(msgs))
1668
1669 // Generate and queue all outgoing requests, have all results reported to
1670 // responseCh, and store a map of reply subjects to the original subjects'
1671 // indices.
1672 r2i := map[string]int{}
1673 for i, msg := range msgs {
1674 hdr := hdrs[i]
1675 var sb strings.Builder
1676 // Either we use nuid.Next() which uses a global lock, or our own nuid object, but
1677 // then it needs to be "write" protected. This approach will reduce across account
1678 // contention since we won't use the global nuid's lock.
1679 jsa.mu.Lock()
1680 uid := jsa.nuid.Next()
1681 sb.WriteString(jsa.rplyr)
1682 jsa.mu.Unlock()
1683
1684 sb.WriteString(kind)
1685 sb.WriteByte(btsep)
1686 if cidHash != _EMPTY_ {
1687 sb.WriteString(cidHash)
1688 sb.WriteByte(btsep)
1689 }
1690 sb.WriteString(uid)
1691 reply := sb.String()
1692
1693 // Add responseCh to the reply channel map. It will be cleaned out on
1694 // timeout (see below), or in processJSAPIReplies upon receiving the
1695 // response.
1696 jsa.replies.Store(reply, responseCh)
1697
1698 subject = jsa.prefixDomain(subject)
1699 jsa.sendq.push(&mqttJSPubMsg{
1700 subj: subject,
1701 reply: reply,
1702 hdr: hdr,
1703 msg: msg,
1704 })
1705 r2i[reply] = i
1706 }
1707
1708 // Wait for all responses to come back, or for the timeout to expire. We
1709 // don't want to use time.After() which causes memory growth because the
1710 // timer can't be stopped and will need to expire to then be garbage
1711 // collected.
1712 c := 0
1713 responses := make([]*mqttJSAResponse, len(msgs))
1714 start := time.Now()
1715 t := time.NewTimer(jsa.timeout)
1716 defer t.Stop()
1717 for {
1718 select {
1719 case r := <-responseCh:
1720 i := r2i[r.reply]
1721 responses[i] = r
1722 c++
1723 if c == len(msgs) {
1724 return responses, nil
1725 }
1726
1727 case <-jsa.quitCh:
1728 return nil, ErrServerNotRunning
1729
1730 case <-t.C:
1731 var reply string
1732 now := time.Now()
1733 for reply = range r2i { // preserve the last value for Errorf
1734 jsa.replies.Delete(reply)
1735 }
1736
1737 if len(msgs) == 1 {
1738 return responses, fmt.Errorf("timeout after %v: request type %q on %q (reply=%q)", now.Sub(start), kind, subject, reply)
1739 } else {
1740 return responses, fmt.Errorf("timeout after %v: request type %q on %q: got %d out of %d", now.Sub(start), kind, subject, c, len(msgs))
1741 }
1742 }
1743 }
1744 }
1745
1746 func (jsa *mqttJSA) sendAck(ackSubject string) {
1747 // Send to the ack subject with no payload.
1748 jsa.sendMsg(ackSubject, nil)
1749 }
1750
1751 func (jsa *mqttJSA) sendMsg(subj string, msg []byte) {
1752 if subj == _EMPTY_ {
1753 return
1754 }
1755 // We pass -1 for the hdr so that the send loop does not need to
1756 // add the "client info" header. This is not a JS API request per se.
1757 jsa.sendq.push(&mqttJSPubMsg{subj: subj, msg: msg, hdr: -1})
1758 }
1759
1760 func (jsa *mqttJSA) createEphemeralConsumer(cfg *CreateConsumerRequest) (*JSApiConsumerCreateResponse, error) {
1761 cfgb, err := json.Marshal(cfg)
1762 if err != nil {
1763 return nil, err
1764 }
1765 subj := fmt.Sprintf(JSApiConsumerCreateT, cfg.Stream)
1766 ccri, err := jsa.newRequest(mqttJSAConsumerCreate, subj, 0, cfgb)
1767 if err != nil {
1768 return nil, err
1769 }
1770 ccr := ccri.(*JSApiConsumerCreateResponse)
1771 return ccr, ccr.ToError()
1772 }
1773
1774 func (jsa *mqttJSA) createDurableConsumer(cfg *CreateConsumerRequest) (*JSApiConsumerCreateResponse, error) {
1775 cfgb, err := json.Marshal(cfg)
1776 if err != nil {
1777 return nil, err
1778 }
1779 subj := fmt.Sprintf(JSApiDurableCreateT, cfg.Stream, cfg.Config.Durable)
1780 ccri, err := jsa.newRequest(mqttJSAConsumerCreate, subj, 0, cfgb)
1781 if err != nil {
1782 return nil, err
1783 }
1784 ccr := ccri.(*JSApiConsumerCreateResponse)
1785 return ccr, ccr.ToError()
1786 }
1787
1788 // if noWait is specified, does not wait for the JS response, returns nil
1789 func (jsa *mqttJSA) deleteConsumer(streamName, consName string, noWait bool) (*JSApiConsumerDeleteResponse, error) {
1790 subj := fmt.Sprintf(JSApiConsumerDeleteT, streamName, consName)
1791 if noWait {
1792 jsa.sendMsg(subj, nil)
1793 return nil, nil
1794 }
1795
1796 cdri, err := jsa.newRequest(mqttJSAConsumerDel, subj, 0, nil)
1797 if err != nil {
1798 return nil, err
1799 }
1800 cdr := cdri.(*JSApiConsumerDeleteResponse)
1801 return cdr, cdr.ToError()
1802 }
1803
1804 func (jsa *mqttJSA) createStream(cfg *StreamConfig) (*StreamInfo, bool, error) {
1805 cfgb, err := json.Marshal(cfg)
1806 if err != nil {
1807 return nil, false, err
1808 }
1809 scri, err := jsa.newRequest(mqttJSAStreamCreate, fmt.Sprintf(JSApiStreamCreateT, cfg.Name), 0, cfgb)
1810 if err != nil {
1811 return nil, false, err
1812 }
1813 scr := scri.(*JSApiStreamCreateResponse)
1814 if err = scr.ToError(); err != nil {
1815 return nil, false, err
1816 }
1817 if scr.StreamInfo == nil {
1818 return nil, false, fmt.Errorf("invalid stream create response: missing stream info")
1819 }
1820 return scr.StreamInfo, scr.DidCreate, nil
1821 }
1822
1823 func (jsa *mqttJSA) updateStream(cfg *StreamConfig) (*StreamInfo, error) {
1824 cfgb, err := json.Marshal(cfg)
1825 if err != nil {
1826 return nil, err
1827 }
1828 scri, err := jsa.newRequest(mqttJSAStreamUpdate, fmt.Sprintf(JSApiStreamUpdateT, cfg.Name), 0, cfgb)
1829 if err != nil {
1830 return nil, err
1831 }
1832 scr := scri.(*JSApiStreamUpdateResponse)
1833 if err = scr.ToError(); err != nil {
1834 return nil, err
1835 }
1836 if scr.StreamInfo == nil {
1837 return nil, fmt.Errorf("invalid stream update response: missing stream info")
1838 }
1839 return scr.StreamInfo, nil
1840 }
1841
1842 func (jsa *mqttJSA) lookupStream(name string) (*StreamInfo, error) {
1843 slri, err := jsa.newRequest(mqttJSAStreamLookup, fmt.Sprintf(JSApiStreamInfoT, name), 0, nil)
1844 if err != nil {
1845 return nil, err
1846 }
1847 slr := slri.(*JSApiStreamInfoResponse)
1848 if err = slr.ToError(); err != nil {
1849 return nil, err
1850 }
1851 if slr.StreamInfo == nil {
1852 return nil, NewJSStreamNotFoundError()
1853 }
1854 return slr.StreamInfo, nil
1855 }
1856
1857 func (jsa *mqttJSA) deleteStream(name string) (bool, error) {
1858 sdri, err := jsa.newRequest(mqttJSAStreamDel, fmt.Sprintf(JSApiStreamDeleteT, name), 0, nil)
1859 if err != nil {
1860 return false, err
1861 }
1862 sdr := sdri.(*JSApiStreamDeleteResponse)
1863 return sdr.Success, sdr.ToError()
1864 }
1865
1866 func (jsa *mqttJSA) loadLastMsgFor(streamName string, subject string) (*StoredMsg, error) {
1867 mreq := &JSApiMsgGetRequest{LastFor: subject}
1868 req, err := json.Marshal(mreq)
1869 if err != nil {
1870 return nil, err
1871 }
1872 lmri, err := jsa.newRequest(mqttJSAMsgLoad, fmt.Sprintf(JSApiMsgGetT, streamName), 0, req)
1873 if err != nil {
1874 return nil, err
1875 }
1876 lmr := lmri.(*JSApiMsgGetResponse)
1877 if err = lmr.ToError(); err != nil {
1878 return nil, err
1879 }
1880 if lmr.Message == nil {
1881 return nil, NewJSNoMessageFoundError()
1882 }
1883 return lmr.Message, nil
1884 }
1885
1886 func (jsa *mqttJSA) loadLastMsgForMulti(streamName string, subjects []string) ([]*JSApiMsgGetResponse, error) {
1887 marshaled := make([][]byte, 0, len(subjects))
1888 headerBytes := make([]int, 0, len(subjects))
1889 for _, subject := range subjects {
1890 mreq := &JSApiMsgGetRequest{LastFor: subject}
1891 bb, err := json.Marshal(mreq)
1892 if err != nil {
1893 return nil, err
1894 }
1895 marshaled = append(marshaled, bb)
1896 headerBytes = append(headerBytes, 0)
1897 }
1898
1899 all, err := jsa.newRequestExMulti(mqttJSAMsgLoad, fmt.Sprintf(JSApiMsgGetT, streamName), _EMPTY_, headerBytes, marshaled)
1900 // all has the same order as subjects, preserve it as we unmarshal
1901 responses := make([]*JSApiMsgGetResponse, len(all))
1902 for i, v := range all {
1903 if v != nil {
1904 responses[i] = v.value.(*JSApiMsgGetResponse)
1905 }
1906 }
1907 return responses, err
1908 }
1909
1910 func (jsa *mqttJSA) loadNextMsgFor(streamName string, subject string) (*StoredMsg, error) {
1911 mreq := &JSApiMsgGetRequest{NextFor: subject}
1912 req, err := json.Marshal(mreq)
1913 if err != nil {
1914 return nil, err
1915 }
1916 lmri, err := jsa.newRequest(mqttJSAMsgLoad, fmt.Sprintf(JSApiMsgGetT, streamName), 0, req)
1917 if err != nil {
1918 return nil, err
1919 }
1920 lmr := lmri.(*JSApiMsgGetResponse)
1921 if err = lmr.ToError(); err != nil {
1922 return nil, err
1923 }
1924 if lmr.Message == nil {
1925 return nil, NewJSNoMessageFoundError()
1926 }
1927 return lmr.Message, nil
1928 }
1929
1930 func (jsa *mqttJSA) loadMsg(streamName string, seq uint64) (*StoredMsg, error) {
1931 mreq := &JSApiMsgGetRequest{Seq: seq}
1932 req, err := json.Marshal(mreq)
1933 if err != nil {
1934 return nil, err
1935 }
1936 lmri, err := jsa.newRequest(mqttJSAMsgLoad, fmt.Sprintf(JSApiMsgGetT, streamName), 0, req)
1937 if err != nil {
1938 return nil, err
1939 }
1940 lmr := lmri.(*JSApiMsgGetResponse)
1941 if err := lmr.ToError(); err != nil {
1942 return nil, err
1943 }
1944 if lmr.Message == nil {
1945 return nil, NewJSNoMessageFoundError()
1946 }
1947 return lmr.Message, nil
1948 }
1949
1950 func (jsa *mqttJSA) storeMsgNoWait(subject string, hdrLen int, msg []byte) {
1951 jsa.sendq.push(&mqttJSPubMsg{
1952 subj: subject,
1953 msg: msg,
1954 hdr: hdrLen,
1955 })
1956 }
1957
1958 func (jsa *mqttJSA) storeMsg(subject string, headers int, msg []byte) (*JSPubAckResponse, error) {
1959 smri, err := jsa.newRequest(mqttJSAMsgStore, subject, headers, msg)
1960 if err != nil {
1961 return nil, err
1962 }
1963 smr := smri.(*JSPubAckResponse)
1964 return smr, smr.ToError()
1965 }
1966
1967 func (jsa *mqttJSA) storeSessionMsg(domainTk, cidHash string, hdr int, msg []byte) (*JSPubAckResponse, error) {
1968 // Compute subject where the session is being stored
1969 subject := mqttSessStreamSubjectPrefix + domainTk + cidHash
1970
1971 // Passing cidHash will add it to the JS reply subject, so that we can use
1972 // it in processSessionPersist.
1973 smri, err := jsa.newRequestEx(mqttJSASessPersist, subject, cidHash, hdr, msg)
1974 if err != nil {
1975 return nil, err
1976 }
1977 smr := smri.(*JSPubAckResponse)
1978 return smr, smr.ToError()
1979 }
1980
1981 func (jsa *mqttJSA) loadSessionMsg(domainTk, cidHash string) (*StoredMsg, error) {
1982 subject := mqttSessStreamSubjectPrefix + domainTk + cidHash
1983 return jsa.loadLastMsgFor(mqttSessStreamName, subject)
1984 }
1985
1986 func (jsa *mqttJSA) deleteMsg(stream string, seq uint64, wait bool) error {
1987 dreq := JSApiMsgDeleteRequest{Seq: seq, NoErase: true}
1988 req, _ := json.Marshal(dreq)
1989 subj := jsa.prefixDomain(fmt.Sprintf(JSApiMsgDeleteT, stream))
1990 if !wait {
1991 jsa.sendq.push(&mqttJSPubMsg{
1992 subj: subj,
1993 msg: req,
1994 })
1995 return nil
1996 }
1997 dmi, err := jsa.newRequest(mqttJSAMsgDelete, subj, 0, req)
1998 if err != nil {
1999 return err
2000 }
2001 dm := dmi.(*JSApiMsgDeleteResponse)
2002 return dm.ToError()
2003 }
2004
2005 //////////////////////////////////////////////////////////////////////////////
2006 //
2007 // Account Sessions Manager related functions
2008 //
2009 //////////////////////////////////////////////////////////////////////////////
2010
2011 // Returns true if `err` is not nil and does not match the api error with ErrorIdentifier id
2012 func isErrorOtherThan(err error, id ErrorIdentifier) bool {
2013 return err != nil && !IsNatsErr(err, id)
2014 }
2015
2016 // Process JS API replies.
2017 //
2018 // Can run from various go routines (consumer's loop, system send loop, etc..).
2019 func (as *mqttAccountSessionManager) processJSAPIReplies(_ *subscription, pc *client, _ *Account, subject, _ string, msg []byte) {
2020 token := tokenAt(subject, mqttJSATokenPos)
2021 if token == _EMPTY_ {
2022 return
2023 }
2024 jsa := &as.jsa
2025 chi, ok := jsa.replies.Load(subject)
2026 if !ok {
2027 return
2028 }
2029 jsa.replies.Delete(subject)
2030 ch := chi.(chan *mqttJSAResponse)
2031 out := func(value any) {
2032 ch <- &mqttJSAResponse{reply: subject, value: value}
2033 }
2034 switch token {
2035 case mqttJSAStreamCreate:
2036 var resp = &JSApiStreamCreateResponse{}
2037 if err := json.Unmarshal(msg, resp); err != nil {
2038 resp.Error = NewJSInvalidJSONError(err)
2039 }
2040 out(resp)
2041 case mqttJSAStreamUpdate:
2042 var resp = &JSApiStreamUpdateResponse{}
2043 if err := json.Unmarshal(msg, resp); err != nil {
2044 resp.Error = NewJSInvalidJSONError(err)
2045 }
2046 out(resp)
2047 case mqttJSAStreamLookup:
2048 var resp = &JSApiStreamInfoResponse{}
2049 if err := json.Unmarshal(msg, resp); err != nil {
2050 resp.Error = NewJSInvalidJSONError(err)
2051 }
2052 out(resp)
2053 case mqttJSAStreamDel:
2054 var resp = &JSApiStreamDeleteResponse{}
2055 if err := json.Unmarshal(msg, resp); err != nil {
2056 resp.Error = NewJSInvalidJSONError(err)
2057 }
2058 out(resp)
2059 case mqttJSAConsumerCreate:
2060 var resp = &JSApiConsumerCreateResponse{}
2061 if err := json.Unmarshal(msg, resp); err != nil {
2062 resp.Error = NewJSInvalidJSONError(err)
2063 }
2064 out(resp)
2065 case mqttJSAConsumerDel:
2066 var resp = &JSApiConsumerDeleteResponse{}
2067 if err := json.Unmarshal(msg, resp); err != nil {
2068 resp.Error = NewJSInvalidJSONError(err)
2069 }
2070 out(resp)
2071 case mqttJSAMsgStore, mqttJSASessPersist:
2072 var resp = &JSPubAckResponse{}
2073 if err := json.Unmarshal(msg, resp); err != nil {
2074 resp.Error = NewJSInvalidJSONError(err)
2075 }
2076 out(resp)
2077 case mqttJSAMsgLoad:
2078 var resp = &JSApiMsgGetResponse{}
2079 if err := json.Unmarshal(msg, resp); err != nil {
2080 resp.Error = NewJSInvalidJSONError(err)
2081 }
2082 out(resp)
2083 case mqttJSAStreamNames:
2084 var resp = &JSApiStreamNamesResponse{}
2085 if err := json.Unmarshal(msg, resp); err != nil {
2086 resp.Error = NewJSInvalidJSONError(err)
2087 }
2088 out(resp)
2089 case mqttJSAMsgDelete:
2090 var resp = &JSApiMsgDeleteResponse{}
2091 if err := json.Unmarshal(msg, resp); err != nil {
2092 resp.Error = NewJSInvalidJSONError(err)
2093 }
2094 out(resp)
2095 default:
2096 pc.Warnf("Unknown reply code %q", token)
2097 }
2098 }
2099
2100 // This will both load all retained messages and process updates from the cluster.
2101 //
2102 // Run from various go routines (JS consumer, etc..).
2103 // No lock held on entry.
2104 func (as *mqttAccountSessionManager) processRetainedMsg(_ *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) {
2105 h, m := c.msgParts(rmsg)
2106 // We need to strip the trailing "\r\n".
2107 if l := len(m); l >= LEN_CR_LF {
2108 m = m[:l-LEN_CR_LF]
2109 }
2110 rm, err := mqttDecodeRetainedMessage(subject, h, m)
2111 if err != nil {
2112 return
2113 }
2114 if strings.IndexByte(rm.Subject, 0x7f) >= 0 {
2115 c.Warnf("Skipping retained message for subject %q: unsupported character 0x7f", rm.Subject)
2116 return
2117 }
2118 // The as.jsa.id is immutable, so no need to have a rlock here.
2119 local := rm.Origin == as.jsa.id
2120 // Get the stream sequence for this message.
2121 seq, _, _, _, _ := ackReplyInfo(reply)
2122 if len(m) == 0 {
2123 // An empty payload means that we need to remove the retained message.
2124 rmSeq := as.removeRetainedMsg(rm.Subject, 0)
2125 if local {
2126 if rmSeq > 0 {
2127 // This is for backward compatibility reasons.
2128 // Should be removed in a future release.
2129 as.notifyRetainedMsgDeleted(rm.Subject, rmSeq)
2130 }
2131 // Delete this very message we just processed, we don't need it anymore.
2132 as.deleteRetainedMsg(seq)
2133 }
2134 } else {
2135 // Add this retained message. The `rm.Msg` references some buffer that we
2136 // don't own. But addRetainedMsg() will take care of making a copy of
2137 // `rm.Msg` it `rm` ends-up being stored in the cache.
2138 as.addRetainedMsg(rm.Subject, seq, rm)
2139 }
2140 }
2141
2142 // NOTE: This is maintained for backward compatibility reasons. Should be removed in 2.14/2.15?
2143 func (as *mqttAccountSessionManager) processRetainedMsgDel(_ *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) {
2144 idHash := tokenAt(subject, 3)
2145 if idHash == _EMPTY_ || idHash == as.jsa.id {
2146 return
2147 }
2148 _, msg := c.msgParts(rmsg)
2149 if len(msg) < LEN_CR_LF {
2150 return
2151 }
2152 var drm mqttRetMsgDel
2153 if err := json.Unmarshal(msg, &drm); err != nil {
2154 return
2155 }
2156 as.removeRetainedMsg(drm.Subject, drm.Seq)
2157 }
2158
2159 // This will receive all JS API replies for a request to store a session record,
2160 // including the reply for our own server, which we will ignore.
2161 // This allows us to detect that some application somewhere else in the cluster
2162 // is connecting with the same client ID, and therefore we need to close the
2163 // connection that is currently using this client ID.
2164 //
2165 // Can run from various go routines (system send loop, etc..).
2166 // No lock held on entry.
2167 func (as *mqttAccountSessionManager) processSessionPersist(_ *subscription, pc *client, _ *Account, subject, _ string, rmsg []byte) {
2168 // Ignore our own responses here (they are handled elsewhere)
2169 if tokenAt(subject, mqttJSAIdTokenPos) == as.jsa.id {
2170 return
2171 }
2172 cIDHash := tokenAt(subject, mqttJSAClientIDPos)
2173 _, msg := pc.msgParts(rmsg)
2174 if len(msg) < LEN_CR_LF {
2175 return
2176 }
2177 var par = &JSPubAckResponse{}
2178 if err := json.Unmarshal(msg, par); err != nil {
2179 return
2180 }
2181 if err := par.Error; err != nil {
2182 return
2183 }
2184 if par.PubAck == nil {
2185 return
2186 }
2187 as.mu.RLock()
2188 // Note that as.domainTk includes a terminal '.', so strip to compare to PubAck.Domain.
2189 dl := len(as.domainTk)
2190 if dl > 0 {
2191 dl--
2192 }
2193 ignore := par.Domain != as.domainTk[:dl]
2194 as.mu.RUnlock()
2195 if ignore {
2196 return
2197 }
2198
2199 as.mu.Lock()
2200 defer as.mu.Unlock()
2201 sess, ok := as.sessByHash[cIDHash]
2202 if !ok {
2203 return
2204 }
2205 // If our current session's stream sequence is higher, it means that this
2206 // update is stale, so we don't do anything here.
2207 sess.mu.Lock()
2208 ignore = par.Sequence < sess.seq
2209 sess.mu.Unlock()
2210 if ignore {
2211 return
2212 }
2213 as.removeSession(sess, false)
2214 sess.mu.Lock()
2215 if ec := sess.c; ec != nil {
2216 as.addSessToFlappers(sess.id)
2217 ec.Warnf("Closing because a remote connection has started with the same client ID: %q", sess.id)
2218 // Disassociate the client from the session so that on client close,
2219 // nothing will be done with regards to cleaning up the session,
2220 // such as deleting stream, etc..
2221 sess.c = nil
2222 // Remove in separate go routine.
2223 go ec.closeConnection(DuplicateClientID)
2224 }
2225 sess.mu.Unlock()
2226 }
2227
2228 // Adds this client ID to the flappers map, and if needed start the timer
2229 // for map cleanup.
2230 //
2231 // Lock held on entry.
2232 func (as *mqttAccountSessionManager) addSessToFlappers(clientID string) {
2233 as.flappers[clientID] = time.Now()
2234 if as.flapTimer == nil {
2235 as.flapTimer = time.AfterFunc(mqttFlapCleanItvl, func() {
2236 as.mu.Lock()
2237 defer as.mu.Unlock()
2238 // In case of shutdown, this will be nil
2239 if as.flapTimer == nil {
2240 return
2241 }
2242 now := time.Now()
2243 for cID, tm := range as.flappers {
2244 if now.Sub(tm) > mqttSessJailDur {
2245 delete(as.flappers, cID)
2246 }
2247 }
2248 as.flapTimer.Reset(mqttFlapCleanItvl)
2249 })
2250 }
2251 }
2252
2253 // Remove this client ID from the flappers map.
2254 //
2255 // Lock held on entry.
2256 func (as *mqttAccountSessionManager) removeSessFromFlappers(clientID string) {
2257 delete(as.flappers, clientID)
2258 // Do not stop/set timer to nil here. Better leave the timer run at its
2259 // regular interval and detect that there is nothing to do. The timer
2260 // will be stopped on shutdown.
2261 }
2262
2263 // Helper to create a subscription. It updates the sid and array of subscriptions.
2264 func (as *mqttAccountSessionManager) createSubscription(subject string, cb msgHandler, sid *int64, subs *[]*subscription) error {
2265 sub, err := as.jsa.c.processSub([]byte(subject), nil, []byte(strconv.FormatInt(*sid, 10)), cb, false)
2266 if err != nil {
2267 return err
2268 }
2269 *sid++
2270 *subs = append(*subs, sub)
2271 return nil
2272 }
2273
2274 // A timer loop to cleanup up expired cached retained messages for a given MQTT account.
2275 // The closeCh is used by the caller to be able to interrupt this routine
2276 // if the rest of the initialization fails, since the quitCh is really
2277 // only used when the server shutdown.
2278 //
2279 // No lock held on entry.
2280 func (as *mqttAccountSessionManager) cleanupRetainedMessageCache(s *Server, closeCh chan struct{}) {
2281 tt := time.NewTicker(mqttRetainedCacheTTL)
2282 defer tt.Stop()
2283 for {
2284 select {
2285 case <-tt.C:
2286 // Set a limit to the number of retained messages to scan since we
2287 // lock as for it. Since the map enumeration gives random order we
2288 // should eventually clean up everything.
2289 i, maxScan := 0, 10*1000
2290 now := time.Now()
2291 as.rmsCache.Range(func(key, value any) bool {
2292 rm := value.(*mqttRetainedMsg)
2293 if now.After(rm.expiresFromCache) {
2294 as.rmsCache.Delete(key)
2295 }
2296 i++
2297 return i < maxScan
2298 })
2299
2300 case <-closeCh:
2301 return
2302 case <-s.quitCh:
2303 return
2304 }
2305 }
2306 }
2307
2308 // Loop to send JS API requests for a given MQTT account.
2309 // The closeCh is used by the caller to be able to interrupt this routine
2310 // if the rest of the initialization fails, since the quitCh is really
2311 // only used when the server shutdown.
2312 //
2313 // No lock held on entry.
2314 func (as *mqttAccountSessionManager) sendJSAPIrequests(s *Server, c *client, accName string, closeCh chan struct{}) {
2315 var cluster string
2316 if s.JetStreamEnabled() && !as.jsa.domainSet {
2317 // Only request the own cluster when it is clear that
2318 cluster = s.cachedClusterName()
2319 }
2320 as.mu.RLock()
2321 sendq := as.jsa.sendq
2322 quitCh := as.jsa.quitCh
2323 ci := ClientInfo{Account: accName, Cluster: cluster}
2324 acc := c.acc
2325 as.mu.RUnlock()
2326
2327 // The account session manager does not have a suhtdown API per-se, instead,
2328 // we will cleanup things when this go routine exits after detecting that the
2329 // server is shutdown or the initialization of the account manager failed.
2330 defer func() {
2331 as.mu.Lock()
2332 if as.flapTimer != nil {
2333 as.flapTimer.Stop()
2334 as.flapTimer = nil
2335 }
2336 as.mu.Unlock()
2337 }()
2338
2339 b, _ := json.Marshal(ci)
2340 hdrStart := bytes.Buffer{}
2341 hdrStart.WriteString(hdrLine)
2342 http.Header{ClientInfoHdr: []string{string(b)}}.Write(&hdrStart)
2343 hdrStart.WriteString(CR_LF)
2344 hdrStart.WriteString(CR_LF)
2345 hdrb := hdrStart.Bytes()
2346
2347 for {
2348 select {
2349 case <-sendq.ch:
2350 pmis := sendq.pop()
2351 for _, r := range pmis {
2352 var nsize int
2353
2354 msg := r.msg
2355 // If r.hdr is set to -1, it means that there is no need for any header.
2356 if r.hdr != -1 {
2357 bb := bytes.Buffer{}
2358 if r.hdr > 0 {
2359 // This means that the header has been set by the caller and is
2360 // already part of `msg`, so simply set c.pa.hdr to the given value.
2361 c.pa.hdr = r.hdr
2362 nsize = len(msg)
2363 msg = append(msg, _CRLF_...)
2364 } else {
2365 // We need the ClientInfo header, so add it here.
2366 bb.Write(hdrb)
2367 c.pa.hdr = bb.Len()
2368 bb.Write(r.msg)
2369 nsize = bb.Len()
2370 bb.WriteString(_CRLF_)
2371 msg = bb.Bytes()
2372 }
2373 c.pa.hdb = []byte(strconv.Itoa(c.pa.hdr))
2374 } else {
2375 c.pa.hdr = -1
2376 c.pa.hdb = nil
2377 nsize = len(msg)
2378 msg = append(msg, _CRLF_...)
2379 }
2380
2381 c.pa.subject = []byte(r.subj)
2382 c.pa.reply = []byte(r.reply)
2383 c.pa.size = nsize
2384 c.pa.szb = []byte(strconv.Itoa(nsize))
2385 c.pa.mapped = nil
2386
2387 if acc.hasMappings() {
2388 if changed := c.selectMappedSubject(); changed {
2389 c.traceOutOp("MAPPINGS", fmt.Appendf(nil, "%s -> %s", c.pa.mapped, c.pa.subject))
2390 }
2391 }
2392 c.processInboundClientMsg(msg)
2393 c.flushClients(0)
2394 }
2395 sendq.recycle(&pmis)
2396
2397 case <-closeCh:
2398 return
2399 case <-quitCh:
2400 return
2401 }
2402 }
2403 }
2404
2405 // Add/Replace this message from the retained messages map.
2406 // If a message for this topic already existed, the existing record is updated
2407 // with the provided information.
2408 // Lock not held on entry.
2409 func (as *mqttAccountSessionManager) addRetainedMsg(key string, sseq uint64, rm *mqttRetainedMsg) {
2410 as.mu.Lock()
2411 defer as.mu.Unlock()
2412 if as.retmsgs == nil {
2413 as.retmsgs = stree.NewSubjectTree[mqttRetainedMsgRef]()
2414 } else {
2415 // Check if we already had one retained message. If so, update the existing one.
2416 if erf, exists := as.retmsgs.Find(stringToBytes(key)); exists {
2417 // Update the stream sequence with the new value.
2418 erf.sseq = sseq
2419 // Update the in-memory retained message cache but only for messages
2420 // that are already in the cache, i.e. have been (recently) used.
2421 // If that is the case, we ask setCachedRetainedMsg() to make a copy
2422 // of rm.Msg bytes slice.
2423 as.setCachedRetainedMsg(key, rm, true, true)
2424 return
2425 }
2426 }
2427 as.retmsgs.Insert([]byte(key), mqttRetainedMsgRef{sseq: sseq})
2428 }
2429
2430 // Remove the retained message stored with the `subject` key from the map/cache.
2431 // When invoked from the retained message stream's consumer, this function will
2432 // be called with `seq == 0`, this is because add/remove are serialized in this
2433 // stream and so the request is to remove the current retained message.
2434 // But in some conditions, we will invoke this function from some other places
2435 // with `seq > 0` which means that the retained message will be removed only if
2436 // its sequence is the same than the provided one.
2437 // This function returns the sequence associated with the existing retained
2438 // message that is being removed (used with `seq == 0`) and returns 0 if the
2439 // retained message was not removed from the map (not found or sequence did not
2440 // match).
2441 func (as *mqttAccountSessionManager) removeRetainedMsg(subject string, seq uint64) uint64 {
2442 as.mu.Lock()
2443 defer as.mu.Unlock()
2444 rm, ok := as.retmsgs.Find(stringToBytes(subject))
2445 if !ok || (seq > 0 && rm.sseq != seq) {
2446 return 0
2447 }
2448 rm, _ = as.retmsgs.Delete(stringToBytes(subject))
2449 as.rmsCache.Delete(subject)
2450 return rm.sseq
2451 }
2452
2453 // First check if this session's client ID is already in the "locked" map,
2454 // which if it is the case means that another client is now bound to this
2455 // session and this should return an error.
2456 // If not in the "locked" map, but the client is not bound with this session,
2457 // then same error is returned.
2458 // Finally, if all checks ok, then the session's ID is added to the "locked" map.
2459 //
2460 // No lock held on entry.
2461 func (as *mqttAccountSessionManager) lockSession(sess *mqttSession, c *client) error {
2462 as.mu.Lock()
2463 defer as.mu.Unlock()
2464 var fail bool
2465 if _, fail = as.sessLocked[sess.id]; !fail {
2466 sess.mu.Lock()
2467 fail = sess.c != c
2468 sess.mu.Unlock()
2469 }
2470 if fail {
2471 return fmt.Errorf("another session is in use with client ID %q", sess.id)
2472 }
2473 as.sessLocked[sess.id] = struct{}{}
2474 return nil
2475 }
2476
2477 // Remove the session from the "locked" map.
2478 //
2479 // No lock held on entry.
2480 func (as *mqttAccountSessionManager) unlockSession(sess *mqttSession) {
2481 as.mu.Lock()
2482 delete(as.sessLocked, sess.id)
2483 as.mu.Unlock()
2484 }
2485
2486 // Simply adds the session to the various sessions maps.
2487 // The boolean `lock` indicates if this function should acquire the lock
2488 // prior to adding to the maps.
2489 //
2490 // No lock held on entry.
2491 func (as *mqttAccountSessionManager) addSession(sess *mqttSession, lock bool) {
2492 if lock {
2493 as.mu.Lock()
2494 }
2495 as.sessions[sess.id] = sess
2496 as.sessByHash[sess.idHash] = sess
2497 if lock {
2498 as.mu.Unlock()
2499 }
2500 }
2501
2502 // Simply removes the session from the various sessions maps.
2503 // The boolean `lock` indicates if this function should acquire the lock
2504 // prior to removing from the maps.
2505 //
2506 // No lock held on entry.
2507 func (as *mqttAccountSessionManager) removeSession(sess *mqttSession, lock bool) {
2508 if lock {
2509 as.mu.Lock()
2510 }
2511 delete(as.sessions, sess.id)
2512 delete(as.sessByHash, sess.idHash)
2513 if lock {
2514 as.mu.Unlock()
2515 }
2516 }
2517
2518 // Helper to set the sub's mqtt fields and possibly serialize (pre-loaded)
2519 // retained messages.
2520 //
2521 // Session lock held on entry. Acquires the subs lock and holds it for
2522 // the duration. Non-MQTT messages coming into mqttDeliverMsgCbQoS0 will be
2523 // waiting.
2524 func (sess *mqttSession) processQOS12Sub(
2525 c *client, // subscribing client.
2526 subject, sid []byte, isReserved bool, qos byte, jsDurName string, h msgHandler, // subscription parameters.
2527 ) (*subscription, error) {
2528 return sess.processSub(c, subject, sid, isReserved, qos, jsDurName, h, false, nil, false, nil)
2529 }
2530
2531 func (sess *mqttSession) processSub(
2532 c *client, // subscribing client.
2533 subject, sid []byte, isReserved bool, qos byte, jsDurName string, h msgHandler, // subscription parameters.
2534 initShadow bool, // do we need to scan for shadow subscriptions? (not for QOS1+)
2535 rms map[string]*mqttRetainedMsg, // preloaded rms (can be empty, or missing items if errors)
2536 trace bool, // trace serialized retained messages in the log?
2537 as *mqttAccountSessionManager, // needed only for rms serialization.
2538 ) (*subscription, error) {
2539 start := time.Now()
2540 defer func() {
2541 elapsed := time.Since(start)
2542 if elapsed > mqttProcessSubTooLong {
2543 c.Warnf("Took too long to process subscription for %q: %v", subject, elapsed)
2544 }
2545 }()
2546
2547 // Hold subsMu to prevent QOS0 messages callback from doing anything until
2548 // the (MQTT) sub is initialized.
2549 sess.subsMu.Lock()
2550 defer sess.subsMu.Unlock()
2551
2552 sub, err := c.processSub(subject, nil, sid, h, false)
2553 if err != nil {
2554 // c.processSub already called c.Errorf(), so no need here.
2555 return nil, err
2556 }
2557 subs := []*subscription{sub}
2558 if initShadow {
2559 subs = append(subs, sub.shadow...)
2560 }
2561 for _, ss := range subs {
2562 if ss.mqtt == nil {
2563 // reserved is set only once and once the subscription has been
2564 // created it can be considered immutable.
2565 ss.mqtt = &mqttSub{
2566 reserved: isReserved,
2567 }
2568 }
2569 // QOS and jsDurName can be changed on an existing subscription, so
2570 // accessing it later requires a lock.
2571 ss.mqtt.qos = qos
2572 ss.mqtt.jsDur = jsDurName
2573 // A (re)configured subscription is live; clear any prior teardown mark.
2574 ss.mqtt.closed = false
2575 }
2576
2577 if len(rms) > 0 {
2578 // Only deal with retained messages for the normal subscription,
2579 // not the shadow one (which is for a different account and subject).
2580 as.serializeRetainedMsgsForSub(rms, sess, c, sub, trace)
2581 }
2582
2583 return sub, nil
2584 }
2585
2586 // Process subscriptions for the given session/client.
2587 //
2588 // When `fromSubProto` is false, it means that this is invoked from the CONNECT
2589 // protocol, when restoring subscriptions that were saved for this session.
2590 // In that case, there is no need to update the session record.
2591 //
2592 // When `fromSubProto` is true, it means that this call is invoked from the
2593 // processing of the SUBSCRIBE protocol, which means that the session needs to
2594 // be updated. It also means that if a subscription on same subject with same
2595 // QoS already exist, we should not be recreating the subscription/JS durable,
2596 // since it was already done when processing the CONNECT protocol.
2597 //
2598 // Runs from the client's readLoop.
2599 // Lock not held on entry, but session is in the locked map.
2600 func (as *mqttAccountSessionManager) processSubs(sess *mqttSession, c *client,
2601 filters []*mqttFilter, fromSubProto, trace bool) ([]*subscription, error) {
2602
2603 // Helper to determine if we need to create a separate top-level
2604 // subscription for a wildcard.
2605 fwc := func(subject string) (bool, string, string) {
2606 if !mqttNeedSubForLevelUp(subject) {
2607 return false, _EMPTY_, _EMPTY_
2608 }
2609 // Say subject is "foo.>", remove the ".>" so that it becomes "foo"
2610 fwcsubject := subject[:len(subject)-2]
2611 // Change the sid to "foo fwc"
2612 fwcsid := fwcsubject + mqttMultiLevelSidSuffix
2613
2614 return true, fwcsubject, fwcsid
2615 }
2616
2617 rmSubjects := map[string]uint64{}
2618 // Preload retained messages for all requested subscriptions. Also, since
2619 // it's the first iteration over the filter list, do some cleanup.
2620 for _, f := range filters {
2621 if f.qos > 2 {
2622 f.qos = 2
2623 }
2624 if c.mqtt.downgradeQoS2Sub && f.qos == 2 {
2625 c.Warnf("Downgrading subscription QoS2 to QoS1 for %q, as configured", f.filter)
2626 f.qos = 1
2627 }
2628
2629 // Do not allow MQTT clients to subscribe directly to internal subjects.
2630 // Otherwise, subjects such as "$MQTT.msgs.*" could be used to bypass
2631 // MQTT subscription permissions.
2632 if strings.HasPrefix(f.filter, mqttPrefix) {
2633 f.qos = mqttSubAckFailure
2634 continue
2635 }
2636
2637 if f.qos == 2 {
2638 if err := sess.ensurePubRelConsumerSubscription(c); err != nil {
2639 c.Errorf("failed to initialize PUBREL processing: %v", err)
2640 f.qos = mqttSubAckFailure
2641 continue
2642 }
2643 }
2644
2645 // Find retained messages.
2646 if fromSubProto {
2647 as.addRetainedSubjectsForSubject(rmSubjects, f.filter)
2648 if need, subject, _ := fwc(f.filter); need {
2649 as.addRetainedSubjectsForSubject(rmSubjects, subject)
2650 }
2651 }
2652 }
2653
2654 var rms map[string]*mqttRetainedMsg
2655 if len(rmSubjects) > 0 {
2656 // Make the best effort to load retained messages.
2657 rms = as.loadRetainedMessages(rmSubjects, c)
2658 }
2659
2660 // Small helper to add the consumer config to the session.
2661 addJSConsToSess := func(sid string, cc *ConsumerConfig) {
2662 if cc == nil {
2663 return
2664 }
2665 if sess.cons == nil {
2666 sess.cons = make(map[string]*ConsumerConfig)
2667 }
2668 sess.cons[sid] = cc
2669 }
2670
2671 var err error
2672 subs := make([]*subscription, 0, len(filters))
2673 for _, f := range filters {
2674 // Skip what's already been identified as a failure.
2675 if f.qos == mqttSubAckFailure {
2676 continue
2677 }
2678 subject := f.filter
2679 bsubject := []byte(subject)
2680 sid := subject
2681 bsid := bsubject
2682 isReserved := isMQTTReservedSubscription(subject)
2683
2684 var jscons *ConsumerConfig
2685 var jssub *subscription
2686
2687 // Note that if a subscription already exists on this subject, the
2688 // existing sub is returned. Need to update the qos.
2689 var sub *subscription
2690 var err error
2691
2692 const processShadowSubs = true
2693
2694 as.mu.Lock()
2695 sess.mu.Lock()
2696 sub, err = sess.processSub(c,
2697 bsubject, bsid, isReserved, f.qos, // main subject
2698 _EMPTY_, mqttDeliverMsgCbQoS0, // no jsDur for QOS0
2699 processShadowSubs,
2700 rms, trace, as)
2701 sess.mu.Unlock()
2702 as.mu.Unlock()
2703
2704 if err != nil {
2705 f.qos = mqttSubAckFailure
2706 sess.cleanupFailedSub(c, sub, jscons, jssub)
2707 continue
2708 }
2709
2710 // This will create (if not already exist) a JS consumer for
2711 // subscriptions of QoS >= 1. But if a JS consumer already exists and
2712 // the subscription for same subject is now a QoS==0, then the JS
2713 // consumer will be deleted.
2714 jscons, jssub, err = sess.processJSConsumer(c, subject, sid, f.qos, fromSubProto)
2715 if err != nil {
2716 f.qos = mqttSubAckFailure
2717 sess.cleanupFailedSub(c, sub, jscons, jssub)
2718 continue
2719 }
2720
2721 // Process the wildcard subject if needed.
2722 if need, fwcsubject, fwcsid := fwc(subject); need {
2723 var fwjscons *ConsumerConfig
2724 var fwjssub *subscription
2725 var fwcsub *subscription
2726
2727 // See note above about existing subscription.
2728 as.mu.Lock()
2729 sess.mu.Lock()
2730 fwcsub, err = sess.processSub(c,
2731 []byte(fwcsubject), []byte(fwcsid), isReserved, f.qos, // FWC (top-level wildcard) subject
2732 _EMPTY_, mqttDeliverMsgCbQoS0, // no jsDur for QOS0
2733 processShadowSubs,
2734 rms, trace, as)
2735 sess.mu.Unlock()
2736 as.mu.Unlock()
2737 if err != nil {
2738 // c.processSub already called c.Errorf(), so no need here.
2739 f.qos = mqttSubAckFailure
2740 sess.cleanupFailedSub(c, sub, jscons, jssub)
2741 continue
2742 }
2743
2744 fwjscons, fwjssub, err = sess.processJSConsumer(c, fwcsubject, fwcsid, f.qos, fromSubProto)
2745 if err != nil {
2746 // c.processSub already called c.Errorf(), so no need here.
2747 f.qos = mqttSubAckFailure
2748 sess.cleanupFailedSub(c, sub, jscons, jssub)
2749 sess.cleanupFailedSub(c, fwcsub, fwjscons, fwjssub)
2750 continue
2751 }
2752
2753 subs = append(subs, fwcsub)
2754 addJSConsToSess(fwcsid, fwjscons)
2755 }
2756
2757 subs = append(subs, sub)
2758 addJSConsToSess(sid, jscons)
2759 }
2760
2761 if fromSubProto {
2762 err = sess.update(filters, true)
2763 }
2764
2765 return subs, err
2766 }
2767
2768 // Retained publish messages matching this subscription are serialized in the
2769 // subscription's `prm` mqtt writer. This buffer will be queued for outbound
2770 // after the subscription is processed and SUBACK is sent or possibly when
2771 // server processes an incoming published message matching the newly
2772 // registered subscription.
2773 //
2774 // Runs from the client's readLoop.
2775 // Account session manager lock held on entry.
2776 // Session lock held on entry.
2777 func (as *mqttAccountSessionManager) serializeRetainedMsgsForSub(rms map[string]*mqttRetainedMsg, sess *mqttSession, c *client, sub *subscription, trace bool) {
2778 if as.retmsgs.Size() == 0 || len(rms) == 0 {
2779 return
2780 }
2781 toTrace := []mqttPublish{}
2782 as.retmsgs.Match(sub.subject, func(subj []byte, _ *mqttRetainedMsgRef) {
2783 rm := rms[string(subj)]
2784 if rm == nil {
2785 // This should not happen since we pre-load messages into rms before
2786 // calling serialize.
2787 return
2788 }
2789 // A broad wildcard subscription can overlap a subscribe deny clause.
2790 c.mu.Lock()
2791 denied := c.mperms != nil && c.checkDenySub(string(subj), bytesToString(sub.queue))
2792 c.mu.Unlock()
2793 if denied {
2794 return
2795 }
2796 var pi uint16
2797 qos := min(mqttGetQoS(rm.Flags), sub.mqtt.qos)
2798 if c.mqtt.rejectQoS2Pub && qos == 2 {
2799 c.Warnf("Rejecting retained message with QoS2 for subscription %q, as configured", sub.subject)
2800 return
2801 }
2802 if qos > 0 {
2803 pi = sess.trackPublishRetained(string(sub.sid))
2804
2805 // If we failed to get a PI for this message, send it as a QoS0, the
2806 // best we can do?
2807 if pi == 0 {
2808 qos = 0
2809 }
2810 }
2811
2812 // Need to use the subject for the retained message, not the `sub` subject.
2813 // We can find the published retained message in rm.sub.subject.
2814 // Set the RETAIN flag: [MQTT-3.3.1-8].
2815 flags, headerBytes := mqttMakePublishHeader(pi, qos, false, true, []byte(rm.Topic), len(rm.Msg))
2816 c.mu.Lock()
2817 sub.mqtt.prm = append(sub.mqtt.prm, headerBytes, rm.Msg)
2818 c.mu.Unlock()
2819 if trace {
2820 toTrace = append(toTrace, mqttPublish{
2821 topic: []byte(rm.Topic),
2822 flags: flags,
2823 pi: pi,
2824 sz: len(rm.Msg),
2825 })
2826 }
2827 })
2828 for _, pp := range toTrace {
2829 c.traceOutOp("PUBLISH", []byte(mqttPubTrace(&pp)))
2830 }
2831 }
2832
2833 // Appends the stored message subjects for all retained message records that
2834 // match the given subscription's `subject` (which could have wildcards).
2835 //
2836 // Account session manager NOT lock held on entry.
2837 func (as *mqttAccountSessionManager) addRetainedSubjectsForSubject(list map[string]uint64, topSubject string) {
2838 as.mu.RLock()
2839 defer as.mu.RUnlock()
2840
2841 if as.retmsgs.Size() == 0 {
2842 return
2843 }
2844
2845 as.retmsgs.Match(stringToBytes(topSubject), func(subj []byte, ret *mqttRetainedMsgRef) {
2846 subject := string(subj)
2847 if _, ok := list[subject]; ok {
2848 return
2849 }
2850 if seq := ret.sseq; seq > 0 {
2851 list[subject] = seq
2852 }
2853 })
2854 }
2855
2856 type warner interface {
2857 Warnf(format string, v ...any)
2858 }
2859
2860 // Loads a list of retained messages given a list of stored message subjects.
2861 func (as *mqttAccountSessionManager) loadRetainedMessages(subjects map[string]uint64, w warner) map[string]*mqttRetainedMsg {
2862 rms := make(map[string]*mqttRetainedMsg, len(subjects))
2863 ss := []string{}
2864 for s := range subjects {
2865 if rm := as.getCachedRetainedMsg(s); rm != nil {
2866 rms[s] = rm
2867 } else {
2868 ss = append(ss, mqttRetainedMsgsStreamSubject+s)
2869 }
2870 }
2871
2872 if len(ss) == 0 {
2873 return rms
2874 }
2875
2876 // Although we have the stream sequence for a given subject, we still use
2877 // the load with "last for subject" because it will cover the cases where a
2878 // new retained message has arrived since we collected the subject/seq pair.
2879 // If we were doing a load "by seq" and the message is not found, we would
2880 // incorrectly remove the retained message from our map.
2881 results, err := as.jsa.loadLastMsgForMulti(mqttRetainedMsgsStreamName, ss)
2882 // If an error occurred, warn, but then proceed with what we got.
2883 if err != nil {
2884 w.Warnf("error loading retained messages: %v", err)
2885 }
2886 for i, result := range results {
2887 if result == nil {
2888 continue // skip requests that timed out
2889 }
2890 if err := result.ToError(); err != nil {
2891 // Skip the "$MQTT.rmsgs." prefix...
2892 subj := ss[i][len(mqttRetainedMsgsStreamSubject):]
2893 if IsNatsErr(err, JSNoMessageFoundErr) {
2894 // If there is no message for that subject, delete from our map.
2895 // The good thing here is that we handle the race where a retained
2896 // message may just arrive and be replacing it in the map. The
2897 // removeRetainedMsg() function below will not remove if the sequence
2898 // does not match.
2899 seq := subjects[subj]
2900 as.removeRetainedMsg(subj, seq)
2901 }
2902 w.Warnf("failed to load retained message for subject %q: %v", subj, err)
2903 continue
2904 }
2905 // Guard before dereferencing below.
2906 if result.Message == nil {
2907 continue
2908 }
2909 rm, err := mqttDecodeRetainedMessage(result.Message.Subject, result.Message.Header, result.Message.Data)
2910 if err != nil {
2911 // Unlikely that we can recover from that, so remove the message.
2912 // (see comment above if failing to load the message).
2913 subj := ss[i][len(mqttRetainedMsgsStreamSubject):]
2914 seq := subjects[subj]
2915 as.removeRetainedMsg(subj, seq)
2916 w.Warnf("failed to decode retained message for subject %q: %v", subj, err)
2917 continue
2918 }
2919
2920 // Add the loaded retained message to the cache, and to the results map.
2921 // We don't need setCachedRetainedMsg() to clone the `rm.Msg` bytes slice
2922 // since we own it.
2923 as.setCachedRetainedMsg(rm.Subject, rm, false, false)
2924 rms[rm.Subject] = rm
2925 }
2926 return rms
2927 }
2928
2929 // Composes a NATS message for a storeable mqttRetainedMsg.
2930 // If the body is empty, the flags are encoded in a way that will cause older
2931 // servers to fail to decode the message in processRetainedMsg callback and
2932 // will simply ignore it, which is what we want.
2933 func mqttEncodeRetainedMessage(rm *mqttRetainedMsg) (natsMsg []byte, headerLen int) {
2934 delRM := len(rm.Msg) == 0
2935
2936 // No need to encode the subject, we can restore it from topic.
2937 l := len(hdrLine)
2938 l += len(mqttNatsRetainedMessageTopic) + 1 + len(rm.Topic) + 2 // 1 byte for ':', 2 bytes for CRLF
2939 if rm.Origin != _EMPTY_ {
2940 l += len(mqttNatsRetainedMessageOrigin) + 1 + len(rm.Origin) + 2 // 1 byte for ':', 2 bytes for CRLF
2941 }
2942 if rm.Source != _EMPTY_ {
2943 l += len(mqttNatsRetainedMessageSource) + 1 + len(rm.Source) + 2 // 1 byte for ':', 2 bytes for CRLF
2944 }
2945 l += len(mqttNatsRetainedMessageFlags) + 1 + 2 + 2 // 1 byte for ':', 2 bytes for the flags, 2 bytes for CRLF
2946 l += 2 // 2 bytes for the extra CRLF after the header
2947 if delRM {
2948 l++ // Will add the delete marker before the flag
2949 } else {
2950 l += len(rm.Msg)
2951 }
2952
2953 buf := bytes.NewBuffer(make([]byte, 0, l))
2954
2955 buf.WriteString(hdrLine)
2956
2957 buf.WriteString(mqttNatsRetainedMessageTopic)
2958 buf.WriteByte(':')
2959 buf.WriteString(rm.Topic)
2960 buf.WriteString(_CRLF_)
2961
2962 buf.WriteString(mqttNatsRetainedMessageFlags)
2963 buf.WriteByte(':')
2964 if delRM {
2965 buf.WriteByte(mqttRetainedFlagDelMarker)
2966 }
2967 buf.WriteString(strconv.FormatUint(uint64(rm.Flags), 16))
2968 buf.WriteString(_CRLF_)
2969
2970 if rm.Origin != _EMPTY_ {
2971 buf.WriteString(mqttNatsRetainedMessageOrigin)
2972 buf.WriteByte(':')
2973 buf.WriteString(rm.Origin)
2974 buf.WriteString(_CRLF_)
2975 }
2976 if rm.Source != _EMPTY_ {
2977 buf.WriteString(mqttNatsRetainedMessageSource)
2978 buf.WriteByte(':')
2979 buf.WriteString(rm.Source)
2980 buf.WriteString(_CRLF_)
2981 }
2982
2983 // End of header, finalize
2984 buf.WriteString(_CRLF_)
2985 headerLen = buf.Len()
2986 buf.Write(rm.Msg)
2987 return buf.Bytes(), headerLen
2988 }
2989
2990 func mqttSliceHeaders(headers map[string][]byte, hdr []byte) {
2991 // Skip the hdrLine
2992 if !bytes.HasPrefix(hdr, stringToBytes(hdrLine)) {
2993 return
2994 }
2995 crLFAsBytes := stringToBytes(CR_LF)
2996 for i := len(hdrLine); i < len(hdr); {
2997 // Search for key/val delimiter.
2998 del := bytes.IndexByte(hdr[i:], ':')
2999 // Not found or key is length 0, we stop.
3000 if del < 0 || del == i {
3001 break
3002 }
3003 keyStart := i
3004 // Walk back to remove spaces between the key and ':' if applicable.
3005 index := keyStart + del - 1
3006 for index > keyStart && hdr[index] == ' ' {
3007 index--
3008 }
3009 key := hdr[keyStart : index+1]
3010 // If what we had is only spaces, we stop.
3011 if len(key) == 0 {
3012 break
3013 }
3014 i += del + 1
3015 valStart := i
3016 // Search for `\r\n`.
3017 nl := bytes.Index(hdr[valStart:], crLFAsBytes)
3018 // If we don't find, we stop.
3019 if nl < 0 {
3020 break
3021 }
3022 // Look if the caller is interested in this key.
3023 if _, ok := headers[bytesToString(key)]; ok {
3024 index := valStart
3025 // Remove possible spaces between the ':' and the value.
3026 for index < valStart+nl && hdr[index] == ' ' {
3027 index++
3028 }
3029 // Create a slice and limit capacity to the value range.
3030 val := hdr[index : valStart+nl : valStart+nl]
3031 // Record in the caller's map the value for this key.
3032 headers[bytesToString(key)] = val
3033 }
3034 // Reposition to past the `\r\n`.
3035 i += nl + 2
3036 }
3037 }
3038
3039 // Decodes a retained message based on the content of the header `h`.
3040 // The returned `*mqttRetainedMsg` object will hold a reference to `m`.
3041 // If the buffer `m` is not owned by the caller, it is the caller
3042 // responsibility to make a copy of the byte slice.
3043 func mqttDecodeRetainedMessage(subject string, h, m []byte) (*mqttRetainedMsg, error) {
3044 headers := map[string][]byte{
3045 mqttNatsRetainedMessageOrigin: nil,
3046 mqttNatsRetainedMessageFlags: nil,
3047 mqttNatsRetainedMessageSource: nil,
3048 }
3049 var rm *mqttRetainedMsg
3050 // Retrieve the values for the above headers.
3051 mqttSliceHeaders(headers, h)
3052 // Get the flag header.
3053 fHeader := headers[mqttNatsRetainedMessageFlags]
3054 // If we don't, it could be that this is an old retained message that
3055 // was JSON encoded.
3056 if len(fHeader) > 0 {
3057 if len(fHeader) > 1 && fHeader[0] == mqttRetainedFlagDelMarker {
3058 fHeader = fHeader[1:]
3059 }
3060 flagsUint, err := strconv.ParseUint(bytesToString(fHeader), 16, 8)
3061 if err != nil {
3062 // Since the error is currently not reported in the server, we
3063 // will simply replace with this one.
3064 return nil, errMQTTInvalidRetainFlags
3065 }
3066 rm = &mqttRetainedMsg{
3067 Flags: byte(flagsUint),
3068 Origin: string(headers[mqttNatsRetainedMessageOrigin]),
3069 Source: string(headers[mqttNatsRetainedMessageSource]),
3070 Msg: m,
3071 }
3072 } else {
3073 if err := json.Unmarshal(m, &rm); err != nil {
3074 return nil, err
3075 }
3076 if rm == nil {
3077 return nil, errMQTTInvalidRetainedMessage
3078 }
3079 }
3080 // Now check that the values are correct.
3081 //
3082 // For "Flags", anything at or above binary (1111) is too big.
3083 if rm.Flags >= mqttPacketFlagMask {
3084 return nil, errMQTTInvalidRetainFlags
3085 }
3086 if qos := mqttGetQoS(rm.Flags); qos > 2 {
3087 return nil, errMQTTInvalidRetainFlags
3088 }
3089 // We store `Topic` in the retained message because we used to store
3090 // all retained messages under the same subject `$MQTT_rmsgs` in
3091 // the retained messages stream. That is no longer the case, and to
3092 // cover setups where the retained message stream is sourced from another
3093 // account and has some subject transforms, simply reconstruct the
3094 // topic/subject based on the `subject` passed to this function.
3095 rm.Subject = strings.TrimPrefix(subject, mqttRetainedMsgsStreamSubject)
3096 rm.Topic = bytesToString(natsSubjectStrToMQTTTopic(rm.Subject))
3097 return rm, nil
3098 }
3099
3100 // Creates the session stream (limit msgs of 1) for this client ID if it does
3101 // not already exist. If it exists, recover the single record to rebuild the
3102 // state of the session. If there is a session record but this session is not
3103 // registered in the runtime of this server, then a request is made to the
3104 // owner to close the client associated with this session since specification
3105 // [MQTT-3.1.4-2] specifies that if the ClientId represents a Client already
3106 // connected to the Server then the Server MUST disconnect the existing client.
3107 //
3108 // Runs from the client's readLoop.
3109 // Lock not held on entry, but session is in the locked map.
3110 func (as *mqttAccountSessionManager) createOrRestoreSession(clientID string, opts *Options) (*mqttSession, bool, error) {
3111 jsa := &as.jsa
3112
3113 hash := getHash(clientID)
3114 smsg, err := jsa.loadSessionMsg(as.domainTk, hash)
3115 if err != nil {
3116 if isErrorOtherThan(err, JSNoMessageFoundErr) {
3117 return nil, false, fmt.Errorf("loading session record: %w", err)
3118 }
3119 // Message not found, so reate the session...
3120 // Create a session and indicate that this session did not exist.
3121 sess := mqttSessionCreate(jsa, clientID, hash, 0, opts)
3122 sess.domainTk = as.domainTk
3123 return sess, false, nil
3124 }
3125 // We need to recover the existing record now.
3126 ps := &mqttPersistedSession{}
3127 if err := json.Unmarshal(smsg.Data, ps); err != nil {
3128 return nil, false, fmt.Errorf("unmarshal of session record at sequence %v: %w", smsg.Sequence, err)
3129 }
3130 if ps.ID != clientID {
3131 return nil, false, errMQTTSessionCollision
3132 }
3133 for sid, cc := range ps.Cons {
3134 if cc == nil {
3135 delete(ps.Cons, sid)
3136 }
3137 }
3138
3139 // Restore this session (even if we don't own it), the caller will do the right thing.
3140 sess := mqttSessionCreate(jsa, clientID, hash, smsg.Sequence, opts)
3141 sess.domainTk = as.domainTk
3142 sess.clean = ps.Clean
3143 sess.subs = ps.Subs
3144 sess.cons = ps.Cons
3145 sess.pubRelConsumer = ps.PubRel
3146 as.addSession(sess, true)
3147 return sess, true, nil
3148 }
3149
3150 // Sends a request to delete a message, but does not wait for the response.
3151 //
3152 // No lock held on entry.
3153 func (as *mqttAccountSessionManager) deleteRetainedMsg(seq uint64) {
3154 as.jsa.deleteMsg(mqttRetainedMsgsStreamName, seq, false)
3155 }
3156
3157 // Sends a message indicating that a retained message on a given subject and stream sequence
3158 // is being removed.
3159 // NOTE: This is maintained for backward compatibility reasons. Should be removed in 2.14/2.15?
3160 func (as *mqttAccountSessionManager) notifyRetainedMsgDeleted(subject string, seq uint64) {
3161 req := mqttRetMsgDel{
3162 Subject: subject,
3163 Seq: seq,
3164 }
3165 b, _ := json.Marshal(&req)
3166 jsa := &as.jsa
3167 jsa.sendq.push(&mqttJSPubMsg{
3168 subj: jsa.rplyr + mqttJSARetainedMsgDel,
3169 msg: b,
3170 })
3171 }
3172
3173 func (as *mqttAccountSessionManager) transferUniqueSessStreamsToMuxed(log *Server) {
3174 // Set retry to true, will be set to false on success.
3175 retry := true
3176 defer func() {
3177 if retry {
3178 next := mqttDefaultTransferRetry
3179 log.Warnf("Failed to transfer all MQTT session streams, will try again in %v", next)
3180 time.AfterFunc(next, func() { as.transferUniqueSessStreamsToMuxed(log) })
3181 }
3182 }()
3183
3184 jsa := &as.jsa
3185 sni, err := jsa.newRequestEx(mqttJSAStreamNames, JSApiStreams, _EMPTY_, 0, nil)
3186 if err != nil {
3187 log.Errorf("Unable to transfer MQTT session streams: %v", err)
3188 return
3189 }
3190 snames := sni.(*JSApiStreamNamesResponse)
3191 if snames.Error != nil {
3192 log.Errorf("Unable to transfer MQTT session streams: %v", snames.ToError())
3193 return
3194 }
3195 var oldMQTTSessStreams []string
3196 for _, sn := range snames.Streams {
3197 if strings.HasPrefix(sn, mqttSessionsStreamNamePrefix) {
3198 oldMQTTSessStreams = append(oldMQTTSessStreams, sn)
3199 }
3200 }
3201 ns := len(oldMQTTSessStreams)
3202 if ns == 0 {
3203 // Nothing to do
3204 retry = false
3205 return
3206 }
3207 log.Noticef("Transferring %v MQTT session streams...", ns)
3208 for _, sn := range oldMQTTSessStreams {
3209 log.Noticef(" Transferring stream %q to %q", sn, mqttSessStreamName)
3210 smsg, err := jsa.loadLastMsgFor(sn, sn)
3211 if err != nil {
3212 log.Errorf(" Unable to load session record: %v", err)
3213 return
3214 }
3215 ps := &mqttPersistedSession{}
3216 if err := json.Unmarshal(smsg.Data, ps); err != nil {
3217 log.Warnf(" Unable to unmarshal the content of this stream, may not be a legitimate MQTT session stream, skipping")
3218 continue
3219 }
3220 // Store record to MQTT session stream
3221 if _, err := jsa.storeSessionMsg(as.domainTk, getHash(ps.ID), 0, smsg.Data); err != nil {
3222 log.Errorf(" Unable to transfer the session record: %v", err)
3223 return
3224 }
3225 jsa.deleteStream(sn)
3226 }
3227 log.Noticef("Transfer of %v MQTT session streams done!", ns)
3228 retry = false
3229 }
3230
3231 func (as *mqttAccountSessionManager) transferRetainedToPerKeySubjectStream(log *Server) error {
3232 jsa := &as.jsa
3233 var processed int
3234 var transferred int
3235
3236 start := time.Now()
3237 deadline := start.Add(mqttRetainedTransferTimeout)
3238 for {
3239 // Try and look up messages on the original undivided "$MQTT.rmsgs" subject.
3240 // If nothing is returned here, we assume to have migrated all old messages.
3241 smsg, err := jsa.loadNextMsgFor(mqttRetainedMsgsStreamName, "$MQTT.rmsgs")
3242 if IsNatsErr(err, JSNoMessageFoundErr) {
3243 // We've ran out of messages to transfer, done.
3244 break
3245 }
3246 if err != nil {
3247 log.Warnf(" Unable to transfer a retained message: failed to load from '$MQTT.rmsgs': %s", err)
3248 return err
3249 }
3250
3251 // Unmarshal the message so that we can obtain the subject name. Do not
3252 // use mqttDecodeRetainedMessage() here because these messages are from
3253 // older versions, and contain the full JSON encoding in payload.
3254 var rmsg mqttRetainedMsg
3255 if err = json.Unmarshal(smsg.Data, &rmsg); err == nil {
3256 // Store the message again, this time with the new per-key subject.
3257 subject := mqttRetainedMsgsStreamSubject + rmsg.Subject
3258 if _, err = jsa.storeMsg(subject, 0, smsg.Data); err != nil {
3259 log.Errorf(" Unable to transfer the retained message with sequence %d: %v", smsg.Sequence, err)
3260 }
3261 transferred++
3262 } else {
3263 log.Warnf(" Unable to unmarshal retained message with sequence %d, skipping", smsg.Sequence)
3264 }
3265
3266 // Delete the original message.
3267 if err := jsa.deleteMsg(mqttRetainedMsgsStreamName, smsg.Sequence, true); err != nil {
3268 log.Errorf(" Unable to clean up the retained message with sequence %d: %v", smsg.Sequence, err)
3269 return err
3270 }
3271 processed++
3272
3273 now := time.Now()
3274 if now.After(deadline) {
3275 err := fmt.Errorf("timed out while transferring retained messages from '$MQTT.rmsgs' after %v, %d processed, %d successfully transferred", now.Sub(start), processed, transferred)
3276 log.Noticef(err.Error())
3277 return err
3278 }
3279 }
3280 if processed > 0 {
3281 log.Noticef("Processed %d messages from '$MQTT.rmsgs', successfully transferred %d in %v", processed, transferred, time.Since(start))
3282 } else {
3283 log.Debugf("No messages found to transfer from '$MQTT.rmsgs'")
3284 }
3285 return nil
3286 }
3287
3288 func (as *mqttAccountSessionManager) getCachedRetainedMsg(subject string) *mqttRetainedMsg {
3289 v, ok := as.rmsCache.Load(subject)
3290 if !ok {
3291 return nil
3292 }
3293 rm := v.(*mqttRetainedMsg)
3294 if rm.expiresFromCache.Before(time.Now()) {
3295 as.rmsCache.Delete(subject)
3296 return nil
3297 }
3298 return rm
3299 }
3300
3301 // If cache is enabled, the expiration for the `rm` is bumped by
3302 // `mqttRetainedCacheTTL` seconds.
3303 // If `onlyReplace` is true, then the `rm` object is stored in the cache using
3304 // the `subject` key only if there was already an object stored under that key.
3305 // If `copyMsgBytes` is true, then the `rm.Msg` bytes are copied (because it
3306 // references some buffer that is not owned by the caller).
3307 //
3308 // Note: currently `onlyReplace` and `cloneMsgBytes` always have the same
3309 // value (all `true` or all `false`) however we use different booleans to
3310 // better express the intent.
3311 func (as *mqttAccountSessionManager) setCachedRetainedMsg(subject string, rm *mqttRetainedMsg, onlyReplace, copyMsgBytes bool) {
3312 if rm == nil {
3313 return
3314 }
3315 rm.expiresFromCache = time.Now().Add(mqttRetainedCacheTTL)
3316 if onlyReplace {
3317 if _, ok := as.rmsCache.Load(subject); !ok {
3318 return
3319 }
3320 }
3321 if copyMsgBytes {
3322 rm.Msg = copyBytes(rm.Msg)
3323 }
3324 as.rmsCache.Store(subject, rm)
3325 }
3326
3327 //////////////////////////////////////////////////////////////////////////////
3328 //
3329 // MQTT session related functions
3330 //
3331 //////////////////////////////////////////////////////////////////////////////
3332
3333 // Returns a new mqttSession object with max ack pending set based on
3334 // option or use mqttDefaultMaxAckPending if no option set.
3335 func mqttSessionCreate(jsa *mqttJSA, id, idHash string, seq uint64, opts *Options) *mqttSession {
3336 maxp := opts.MQTT.MaxAckPending
3337 if maxp == 0 {
3338 maxp = mqttDefaultMaxAckPending
3339 }
3340
3341 return &mqttSession{
3342 jsa: jsa,
3343 id: id,
3344 idHash: idHash,
3345 seq: seq,
3346 maxp: maxp,
3347 pubRelSubject: mqttPubRelSubjectPrefix + idHash,
3348 pubRelDeliverySubject: mqttPubRelDeliverySubjectPrefix + idHash,
3349 pubRelDeliverySubjectB: []byte(mqttPubRelDeliverySubjectPrefix + idHash),
3350 }
3351 }
3352
3353 // Persists a session. Note that if the session's current client does not match
3354 // the given client, nothing is done.
3355 //
3356 // Lock not held on entry.
3357 func (sess *mqttSession) save() error {
3358 sess.mu.Lock()
3359 ps := mqttPersistedSession{
3360 Origin: sess.jsa.id,
3361 ID: sess.id,
3362 Clean: sess.clean,
3363 Subs: sess.subs,
3364 Cons: sess.cons,
3365 PubRel: sess.pubRelConsumer,
3366 }
3367 b, _ := json.Marshal(&ps)
3368
3369 domainTk, cidHash := sess.domainTk, sess.idHash
3370 seq := sess.seq
3371 sess.mu.Unlock()
3372
3373 var hdr int
3374 if seq != 0 {
3375 bb := bytes.Buffer{}
3376 bb.WriteString(hdrLine)
3377 bb.WriteString(JSExpectedLastSubjSeq)
3378 bb.WriteString(":")
3379 bb.WriteString(strconv.FormatInt(int64(seq), 10))
3380 bb.WriteString(CR_LF)
3381 bb.WriteString(CR_LF)
3382 hdr = bb.Len()
3383 bb.Write(b)
3384 b = bb.Bytes()
3385 }
3386
3387 resp, err := sess.jsa.storeSessionMsg(domainTk, cidHash, hdr, b)
3388 if err != nil {
3389 return fmt.Errorf("unable to persist session %q (seq=%v): %v", ps.ID, seq, err)
3390 }
3391 // Guard before dereferencing below.
3392 if resp == nil || resp.PubAck == nil {
3393 return fmt.Errorf("unable to persist session %q (seq=%v): invalid pub ack response", ps.ID, seq)
3394 }
3395 sess.mu.Lock()
3396 sess.seq = resp.Sequence
3397 sess.mu.Unlock()
3398 return nil
3399 }
3400
3401 // Clear the session.
3402 //
3403 // Runs from the client's readLoop.
3404 // Lock not held on entry, but session is in the locked map.
3405 func (sess *mqttSession) clear(noWait bool) error {
3406 var durs []string
3407 var pubRelDur string
3408
3409 sess.mu.Lock()
3410 id := sess.id
3411 seq := sess.seq
3412 if l := len(sess.cons); l > 0 {
3413 durs = make([]string, 0, l)
3414 }
3415 for sid, cc := range sess.cons {
3416 delete(sess.cons, sid)
3417 durs = append(durs, cc.Durable)
3418 }
3419 if sess.pubRelConsumer != nil {
3420 pubRelDur = sess.pubRelConsumer.Durable
3421 }
3422
3423 sess.subs = nil
3424 sess.pendingPublish = nil
3425 sess.pendingPubRel = nil
3426 sess.cpending = nil
3427 sess.pubRelConsumer = nil
3428 sess.seq = 0
3429 sess.tmaxack = 0
3430 // Discarded session: reset the PI counter too so a reused session object
3431 // does not inherit the previous session's identifiers. Spec [MQTT-3.1.2-6].
3432 sess.last_pi = 0
3433 sess.mu.Unlock()
3434
3435 for _, dur := range durs {
3436 if _, err := sess.jsa.deleteConsumer(mqttStreamName, dur, noWait); isErrorOtherThan(err, JSConsumerNotFoundErr) {
3437 return fmt.Errorf("unable to delete consumer %q for session %q: %v", dur, sess.id, err)
3438 }
3439 }
3440 if pubRelDur != _EMPTY_ {
3441 _, err := sess.jsa.deleteConsumer(mqttOutStreamName, pubRelDur, noWait)
3442 if isErrorOtherThan(err, JSConsumerNotFoundErr) {
3443 return fmt.Errorf("unable to delete consumer %q for session %q: %v", pubRelDur, sess.id, err)
3444 }
3445 }
3446
3447 if seq > 0 {
3448 err := sess.jsa.deleteMsg(mqttSessStreamName, seq, !noWait)
3449 // Ignore the various errors indicating that the message (or sequence)
3450 // is already deleted, can happen in a cluster.
3451 if isErrorOtherThan(err, JSSequenceNotFoundErrF) {
3452 if isErrorOtherThan(err, JSStreamMsgDeleteFailedF) || !strings.Contains(err.Error(), ErrStoreMsgNotFound.Error()) {
3453 return fmt.Errorf("unable to delete session %q record at sequence %v: %v", id, seq, err)
3454 }
3455 }
3456 }
3457 return nil
3458 }
3459
3460 // This will update the session record for this client in the account's MQTT
3461 // sessions stream if the session had any change in the subscriptions.
3462 //
3463 // Runs from the client's readLoop.
3464 // Lock not held on entry, but session is in the locked map.
3465 func (sess *mqttSession) update(filters []*mqttFilter, add bool) error {
3466 // Evaluate if we need to persist anything.
3467 var needUpdate bool
3468 for _, f := range filters {
3469 if add {
3470 if f.qos == mqttSubAckFailure {
3471 continue
3472 }
3473 if qos, ok := sess.subs[f.filter]; !ok || qos != f.qos {
3474 if sess.subs == nil {
3475 sess.subs = make(map[string]byte)
3476 }
3477 sess.subs[f.filter] = f.qos
3478 needUpdate = true
3479 }
3480 } else {
3481 if _, ok := sess.subs[f.filter]; ok {
3482 delete(sess.subs, f.filter)
3483 needUpdate = true
3484 }
3485 }
3486 }
3487 var err error
3488 if needUpdate {
3489 err = sess.save()
3490 }
3491 return err
3492 }
3493
3494 func (sess *mqttSession) bumpPI() uint16 {
3495 var avail bool
3496 next := sess.last_pi
3497 for i := 0; i < 0xFFFF; i++ {
3498 next++
3499 if next == 0 {
3500 next = 1
3501 }
3502
3503 _, usedInPublish := sess.pendingPublish[next]
3504 _, usedInPubRel := sess.pendingPubRel[next]
3505 if !usedInPublish && !usedInPubRel {
3506 sess.last_pi = next
3507 avail = true
3508 break
3509 }
3510 }
3511 if !avail {
3512 return 0
3513 }
3514 return sess.last_pi
3515 }
3516
3517 // mqttRetainedPendingDur returns the pseudo consumer-durable key under which a
3518 // subscription's in-flight retained QoS deliveries are tracked in cpending.
3519 // Retained deliveries have no JS consumer, but keying them per subscription
3520 // lets unsubscribe/downgrade teardown purge them like consumer deliveries.
3521 // Cannot collide with real durables (idHash+"_"+nuid, $MQTT_PUBREL_ prefix).
3522 func mqttRetainedPendingDur(sid string) string {
3523 return mqttRetainedMsgsStreamName + "/" + sid
3524 }
3525
3526 // trackPublishRetained is invoked when a retained (QoS) message is published.
3527 // It needs a new PI to be allocated, so we add it to the pendingPublish map,
3528 // and serialize it in cpending under the subscription's pseudo-durable key
3529 // (with the PI as the sequence) so consumer teardown purges it; an ack removes
3530 // both entries via untrackPublish.
3531 //
3532 // Lock held on entry
3533 func (sess *mqttSession) trackPublishRetained(sid string) uint16 {
3534 // Make sure we initialize the tracking maps.
3535 if sess.pendingPublish == nil {
3536 sess.pendingPublish = make(map[uint16]*mqttPending)
3537 }
3538 if sess.cpending == nil {
3539 sess.cpending = make(map[string]map[uint64]uint16)
3540 }
3541
3542 pi := sess.bumpPI()
3543 if pi == 0 {
3544 return 0
3545 }
3546 dur := mqttRetainedPendingDur(sid)
3547 sseqToPi := sess.cpending[dur]
3548 if sseqToPi == nil {
3549 sseqToPi = make(map[uint64]uint16)
3550 sess.cpending[dur] = sseqToPi
3551 }
3552 sseqToPi[uint64(pi)] = pi
3553 sess.pendingPublish[pi] = &mqttPending{jsDur: dur, sseq: uint64(pi)}
3554
3555 return pi
3556 }
3557
3558 // trackPublish is invoked when a (QoS) PUBLISH message is to be delivered. It
3559 // detects an untracked (new) message based on its sequence extracted from its
3560 // delivery-time jsAckSubject, and adds it to the tracking maps. Returns a PI to
3561 // use for the message (new, or previously used), and whether this is a
3562 // duplicate delivery attempt.
3563 //
3564 // Lock held on entry
3565 func (sess *mqttSession) trackPublish(jsDur, jsAckSubject string) (uint16, bool) {
3566 var dup bool
3567 var pi uint16
3568
3569 if jsAckSubject == _EMPTY_ || jsDur == _EMPTY_ {
3570 return 0, false
3571 }
3572
3573 // Make sure we initialize the tracking maps.
3574 if sess.pendingPublish == nil {
3575 sess.pendingPublish = make(map[uint16]*mqttPending)
3576 }
3577 if sess.cpending == nil {
3578 sess.cpending = make(map[string]map[uint64]uint16)
3579 }
3580
3581 // Get the stream sequence and duplicate flag from the ack reply subject.
3582 sseq, _, dcount, _, _ := ackReplyInfo(jsAckSubject)
3583 if dcount > 1 {
3584 dup = true
3585 }
3586
3587 var ack *mqttPending
3588 sseqToPi, ok := sess.cpending[jsDur]
3589 if !ok {
3590 sseqToPi = make(map[uint64]uint16)
3591 sess.cpending[jsDur] = sseqToPi
3592 } else {
3593 pi = sseqToPi[sseq]
3594 }
3595
3596 if pi != 0 {
3597 // There is a possible race between a PUBLISH re-delivery calling us,
3598 // and a PUBREC received already having submitting a PUBREL into JS . If
3599 // so, indicate no need for (re-)delivery by returning a PI of 0.
3600 _, usedForPubRel := sess.pendingPubRel[pi]
3601 if /*dup && */ usedForPubRel {
3602 return 0, false
3603 }
3604
3605 // We should have a pending JS ACK for this PI.
3606 ack = sess.pendingPublish[pi]
3607 } else {
3608 // sess.maxp will always have a value > 0.
3609 if len(sess.pendingPublish) >= int(sess.maxp) {
3610 // Indicate that we did not assign a packet identifier.
3611 // The caller will not send the message to the subscription
3612 // and JS will redeliver later, based on consumer's AckWait.
3613 return 0, false
3614 }
3615
3616 pi = sess.bumpPI()
3617 if pi == 0 {
3618 return 0, false
3619 }
3620
3621 sseqToPi[sseq] = pi
3622 }
3623
3624 if ack == nil {
3625 sess.pendingPublish[pi] = &mqttPending{
3626 jsDur: jsDur,
3627 sseq: sseq,
3628 jsAckSubject: jsAckSubject,
3629 }
3630 } else {
3631 ack.jsAckSubject = jsAckSubject
3632 ack.sseq = sseq
3633 ack.jsDur = jsDur
3634 }
3635
3636 return pi, dup
3637 }
3638
3639 // Stops a PI from being tracked as a PUBLISH. It can still be in use for a
3640 // pending PUBREL.
3641 //
3642 // Lock held on entry
3643 func (sess *mqttSession) untrackPublish(pi uint16) (jsAckSubject string) {
3644 ack, ok := sess.pendingPublish[pi]
3645 if !ok {
3646 return _EMPTY_
3647 }
3648
3649 delete(sess.pendingPublish, pi)
3650 // Do NOT reset last_pi here: it is a monotonic rolling counter (see bumpPI) so
3651 // a just-freed id is not reused within a delivery burst, which a client would
3652 // read as a duplicate. Spec [MQTT-2.3.1-4].
3653
3654 if len(sess.cpending) != 0 && ack.jsDur != _EMPTY_ {
3655 if sseqToPi := sess.cpending[ack.jsDur]; sseqToPi != nil {
3656 delete(sseqToPi, ack.sseq)
3657 }
3658 }
3659
3660 return ack.jsAckSubject
3661 }
3662
3663 // trackAsPubRel is invoked in 2 cases: (a) when we receive a PUBREC and we need
3664 // to change from tracking the PI as a PUBLISH to a PUBREL; and (b) when we
3665 // attempt to deliver the PUBREL to record the JS ack subject for it.
3666 //
3667 // Lock held on entry
3668 func (sess *mqttSession) trackAsPubRel(pi uint16, jsAckSubject string) {
3669 if sess.pubRelConsumer == nil {
3670 // The cosumer MUST be set up already.
3671 return
3672 }
3673 jsDur := sess.pubRelConsumer.Durable
3674
3675 if sess.pendingPubRel == nil {
3676 sess.pendingPubRel = make(map[uint16]*mqttPending)
3677 }
3678
3679 if jsAckSubject == _EMPTY_ {
3680 sess.pendingPubRel[pi] = &mqttPending{
3681 jsDur: jsDur,
3682 }
3683 return
3684 }
3685
3686 sseq, _, _, _, _ := ackReplyInfo(jsAckSubject)
3687
3688 if sess.cpending == nil {
3689 sess.cpending = make(map[string]map[uint64]uint16)
3690 }
3691 sseqToPi := sess.cpending[jsDur]
3692 if sseqToPi == nil {
3693 sseqToPi = make(map[uint64]uint16)
3694 sess.cpending[jsDur] = sseqToPi
3695 }
3696 sseqToPi[sseq] = pi
3697 sess.pendingPubRel[pi] = &mqttPending{
3698 jsDur: sess.pubRelConsumer.Durable,
3699 sseq: sseq,
3700 jsAckSubject: jsAckSubject,
3701 }
3702 }
3703
3704 // Stops a PI from being tracked as a PUBREL.
3705 //
3706 // Lock held on entry
3707 func (sess *mqttSession) untrackPubRel(pi uint16) (jsAckSubject string) {
3708 ack, ok := sess.pendingPubRel[pi]
3709 if !ok {
3710 return _EMPTY_
3711 }
3712
3713 delete(sess.pendingPubRel, pi)
3714
3715 if sess.pubRelConsumer != nil && len(sess.cpending) > 0 {
3716 if sseqToPi := sess.cpending[ack.jsDur]; sseqToPi != nil {
3717 delete(sseqToPi, ack.sseq)
3718 }
3719 }
3720
3721 return ack.jsAckSubject
3722 }
3723
3724 // Sends a consumer delete request, but does not wait for response.
3725 //
3726 // Lock not held on entry.
3727 func (sess *mqttSession) deleteConsumer(cc *ConsumerConfig) {
3728 sess.mu.Lock()
3729 sess.tmaxack -= cc.MaxAckPending
3730 sess.jsa.deleteConsumer(mqttStreamName, cc.Durable, true)
3731 sess.mu.Unlock()
3732 }
3733
3734 //////////////////////////////////////////////////////////////////////////////
3735 //
3736 // CONNECT protocol related functions
3737 //
3738 //////////////////////////////////////////////////////////////////////////////
3739
3740 // Parse the MQTT connect protocol
3741 func (c *client) mqttParseConnect(r *mqttReader, hasMappings bool) (byte, *mqttConnectProto, error) {
3742 // Protocol name
3743 proto, err := r.readBytes("protocol name", false)
3744 if err != nil {
3745 return 0, nil, err
3746 }
3747
3748 // Spec [MQTT-3.1.2-1]
3749 if !bytes.Equal(proto, mqttProtoName) {
3750 // Check proto name against v3.1 to report better error
3751 if bytes.Equal(proto, mqttOldProtoName) {
3752 return 0, nil, fmt.Errorf("older protocol %q not supported", proto)
3753 }
3754 return 0, nil, fmt.Errorf("expected connect packet with protocol name %q, got %q", mqttProtoName, proto)
3755 }
3756
3757 // Protocol level
3758 level, err := r.readByte("protocol level")
3759 if err != nil {
3760 return 0, nil, err
3761 }
3762 // Spec [MQTT-3.1.2-2]
3763 if level != mqttProtoLevel {
3764 return mqttConnAckRCUnacceptableProtocolVersion, nil, fmt.Errorf("unacceptable protocol version of %v", level)
3765 }
3766
3767 cp := &mqttConnectProto{}
3768 // Connect flags
3769 cp.flags, err = r.readByte("flags")
3770 if err != nil {
3771 return 0, nil, err
3772 }
3773
3774 // Spec [MQTT-3.1.2-3]
3775 if cp.flags&mqttConnFlagReserved != 0 {
3776 return 0, nil, errMQTTConnFlagReserved
3777 }
3778
3779 var hasWill bool
3780 wqos := (cp.flags & mqttConnFlagWillQoS) >> 3
3781 wretain := cp.flags&mqttConnFlagWillRetain != 0
3782 // Spec [MQTT-3.1.2-11]
3783 if cp.flags&mqttConnFlagWillFlag == 0 {
3784 // Spec [MQTT-3.1.2-13]
3785 if wqos != 0 {
3786 return 0, nil, fmt.Errorf("if Will flag is set to 0, Will QoS must be 0 too, got %v", wqos)
3787 }
3788 // Spec [MQTT-3.1.2-15]
3789 if wretain {
3790 return 0, nil, errMQTTWillAndRetainFlag
3791 }
3792 } else {
3793 // Spec [MQTT-3.1.2-14]
3794 if wqos == 3 {
3795 return 0, nil, fmt.Errorf("if Will flag is set to 1, Will QoS can be 0, 1 or 2, got %v", wqos)
3796 }
3797 hasWill = true
3798 }
3799
3800 if c.mqtt.rejectQoS2Pub && hasWill && wqos == 2 {
3801 return mqttConnAckRCQoS2WillRejected, nil, fmt.Errorf("server does not accept QoS2 for Will messages")
3802 }
3803
3804 // Spec [MQTT-3.1.2-19]
3805 hasUser := cp.flags&mqttConnFlagUsernameFlag != 0
3806 // Spec [MQTT-3.1.2-21]
3807 hasPassword := cp.flags&mqttConnFlagPasswordFlag != 0
3808 // Spec [MQTT-3.1.2-22]
3809 if !hasUser && hasPassword {
3810 return 0, nil, errMQTTPasswordFlagAndNoUser
3811 }
3812
3813 // Keep alive
3814 var ka uint16
3815 ka, err = r.readUint16("keep alive")
3816 if err != nil {
3817 return 0, nil, err
3818 }
3819 // Spec [MQTT-3.1.2-24]
3820 if ka > 0 {
3821 cp.rd = time.Duration(float64(ka)*1.5) * time.Second
3822 }
3823
3824 // Payload starts here and order is mandated by:
3825 // Spec [MQTT-3.1.3-1]: client ID, will topic, will message, username, password
3826
3827 // Client ID
3828 c.mqtt.cid, err = r.readString("client ID")
3829 if err != nil {
3830 return 0, nil, err
3831 }
3832 // Spec [MQTT-3.1.3-7]
3833 if c.mqtt.cid == _EMPTY_ {
3834 if cp.flags&mqttConnFlagCleanSession == 0 {
3835 return mqttConnAckRCIdentifierRejected, nil, errMQTTCIDEmptyNeedsCleanFlag
3836 }
3837 // Spec [MQTT-3.1.3-6]
3838 c.mqtt.cid = nuid.Next()
3839 }
3840 // Spec [MQTT-3.1.3-4] and [MQTT-3.1.3-9]
3841 if err := mqttValidateString(c.mqtt.cid, "client ID"); err != nil {
3842 return mqttConnAckRCIdentifierRejected, nil, err
3843 } else if !isValidName(c.mqtt.cid) {
3844 // Should not contain characters that make it an invalid name for NATS subjects, etc.
3845 err = fmt.Errorf("invalid character in %s %q", "client ID", c.mqtt.cid)
3846 return mqttConnAckRCIdentifierRejected, nil, err
3847 }
3848
3849 if hasWill {
3850 cp.will = &mqttWill{
3851 qos: wqos,
3852 retain: wretain,
3853 }
3854 var topic []byte
3855 // Need to make a copy since we need to hold to this topic after the
3856 // parsing of this protocol.
3857 topic, err = r.readBytes("Will topic", true)
3858 if err != nil {
3859 return 0, nil, err
3860 }
3861 if len(topic) == 0 {
3862 return 0, nil, errMQTTEmptyWillTopic
3863 }
3864 if err := mqttValidateTopic(topic, "Will topic"); err != nil {
3865 return 0, nil, err
3866 }
3867 // Convert MQTT topic to NATS subject
3868 cp.will.subject, err = mqttTopicToNATSPubSubject(topic)
3869 if err != nil {
3870 return 0, nil, err
3871 }
3872 // Check for subject mapping.
3873 if hasMappings {
3874 // For selectMappedSubject to work, we need to have c.pa.subject set.
3875 // If there is a change, c.pa.mapped will be set after the call.
3876 c.pa.subject = cp.will.subject
3877 if changed := c.selectMappedSubject(); changed {
3878 // We need to keep track of the NATS subject/mapped in the `cp` structure.
3879 cp.will.subject = c.pa.subject
3880 cp.will.mapped = c.pa.mapped
3881 // We also now need to map the original MQTT topic to the new topic
3882 // based on the new subject.
3883 topic = natsSubjectToMQTTTopic(cp.will.subject)
3884 }
3885 // Reset those now.
3886 c.pa.subject, c.pa.mapped = nil, nil
3887 }
3888 cp.will.topic = topic
3889 // Now "will" message.
3890 // Ask for a copy since we need to hold to this after parsing of this protocol.
3891 cp.will.message, err = r.readBytes("Will message", true)
3892 if err != nil {
3893 return 0, nil, err
3894 }
3895 }
3896
3897 if hasUser {
3898 c.opts.Username, err = r.readString("user name")
3899 if err != nil {
3900 return 0, nil, err
3901 }
3902 if c.opts.Username == _EMPTY_ {
3903 return mqttConnAckRCBadUserOrPassword, nil, errMQTTEmptyUsername
3904 }
3905 // Spec [MQTT-3.1.3-11]
3906 if err := mqttValidateString(c.opts.Username, "user name"); err != nil {
3907 return mqttConnAckRCBadUserOrPassword, nil, err
3908 }
3909 }
3910
3911 if hasPassword {
3912 c.opts.Password, err = r.readString("password")
3913 if err != nil {
3914 return 0, nil, err
3915 }
3916 c.opts.Token = c.opts.Password
3917 }
3918 return 0, cp, nil
3919 }
3920
3921 func (c *client) mqttConnectTrace(cp *mqttConnectProto) string {
3922 trace := fmt.Sprintf("clientID=%s", c.mqtt.cid)
3923 if cp.rd > 0 {
3924 trace += fmt.Sprintf(" keepAlive=%v", cp.rd)
3925 }
3926 if cp.will != nil {
3927 trace += fmt.Sprintf(" will=(topic=%s QoS=%v retain=%v)",
3928 cp.will.topic, cp.will.qos, cp.will.retain)
3929 }
3930 if cp.flags&mqttConnFlagCleanSession != 0 {
3931 trace += " clean"
3932 }
3933 if c.opts.Username != _EMPTY_ {
3934 trace += fmt.Sprintf(" username=%s", c.opts.Username)
3935 }
3936 if c.opts.Password != _EMPTY_ {
3937 trace += " password=****"
3938 }
3939 return trace
3940 }
3941
3942 // Process the CONNECT packet.
3943 //
3944 // For the first session on the account, an account session manager will be created,
3945 // along with the JetStream streams/consumer necessary for the working of MQTT.
3946 //
3947 // The session, identified by a client ID, will be registered, or if already existing,
3948 // will be resumed. If the session exists but is associated with an existing client,
3949 // the old client is evicted, as per the specifications.
3950 //
3951 // Due to specific locking requirements around JS API requests, we cannot hold some
3952 // locks for the entire duration of processing of some protocols, therefore, we use
3953 // a map that registers the client ID in a "locked" state. If a different client tries
3954 // to connect and the server detects that the client ID is in that map, it will try
3955 // a little bit until it is not, or fail the new client, since we can't protect
3956 // processing of protocols in the original client. This is not expected to happen often.
3957 //
3958 // Runs from the client's readLoop.
3959 // No lock held on entry.
3960 func (s *Server) mqttProcessConnect(c *client, cp *mqttConnectProto, trace bool) error {
3961 sendConnAck := func(rc byte, sessp bool) {
3962 c.mqttEnqueueConnAck(rc, sessp)
3963 if trace {
3964 c.traceOutOp("CONNACK", []byte(fmt.Sprintf("sp=%v rc=%v", sessp, rc)))
3965 }
3966 }
3967
3968 c.mu.Lock()
3969 cid := c.mqtt.cid
3970 c.clearAuthTimer()
3971 c.mu.Unlock()
3972 if !s.isClientAuthorized(c) {
3973 if trace {
3974 c.traceOutOp("CONNACK", []byte(fmt.Sprintf("sp=%v rc=%v", false, mqttConnAckRCNotAuthorized)))
3975 }
3976 c.authViolation()
3977 return ErrAuthentication
3978 }
3979 // Now that we are authenticated, we have the client bound to the account.
3980 // Get the account's level MQTT sessions manager. If it does not exists yet,
3981 // this will create it along with the streams where sessions and messages
3982 // are stored.
3983 asm, err := s.getOrCreateMQTTAccountSessionManager(c)
3984 if err != nil {
3985 return err
3986 }
3987
3988 // Most of the session state is altered only in the readLoop so does not
3989 // need locking. For things that can be access in the readLoop and in
3990 // callbacks, we will use explicit locking.
3991 // To prevent other clients to connect with the same client ID, we will
3992 // add the client ID to a "locked" map so that the connect somewhere else
3993 // is put on hold.
3994 // This keep track of how many times this client is detecting that its
3995 // client ID is in the locked map. After a short amount, the server will
3996 // fail this inbound client.
3997 locked := 0
3998
3999 CHECK:
4000 asm.mu.Lock()
4001 // Check if different applications keep trying to connect with the same
4002 // client ID at the same time.
4003 if tm, ok := asm.flappers[cid]; ok {
4004 // If the last time it tried to connect was more than 1 sec ago,
4005 // then accept and remove from flappers map.
4006 if time.Since(tm) > mqttSessJailDur {
4007 asm.removeSessFromFlappers(cid)
4008 } else {
4009 // Will hold this client for a second and then close it. We
4010 // do this so that if the client has a reconnect feature we
4011 // don't end-up with very rapid flapping between apps.
4012 // We need to wait in place and not schedule the connection
4013 // close because if this is a misbehaved client that does
4014 // not wait for the CONNACK and sends other protocols, the
4015 // server would not have a fully setup client and may panic.
4016 asm.mu.Unlock()
4017 select {
4018 case <-s.quitCh:
4019 case <-time.After(mqttSessJailDur):
4020 }
4021 c.closeConnection(DuplicateClientID)
4022 return ErrConnectionClosed
4023 }
4024 }
4025 // If an existing session is in the process of processing some packet, we can't
4026 // evict the old client just yet. So try again to see if the state clears, but
4027 // if it does not, then we have no choice but to fail the new client instead of
4028 // the old one.
4029 if _, ok := asm.sessLocked[cid]; ok {
4030 asm.mu.Unlock()
4031 if locked++; locked == 10 {
4032 return fmt.Errorf("other session with client ID %q is in the process of connecting", cid)
4033 }
4034 time.Sleep(100 * time.Millisecond)
4035 goto CHECK
4036 }
4037
4038 // Register this client ID the "locked" map for the duration if this function.
4039 asm.sessLocked[cid] = struct{}{}
4040 // And remove it on exit, regardless of error or not.
4041 defer func() {
4042 asm.mu.Lock()
4043 delete(asm.sessLocked, cid)
4044 asm.mu.Unlock()
4045 }()
4046
4047 // Is the client requesting a clean session or not.
4048 cleanSess := cp.flags&mqttConnFlagCleanSession != 0
4049 // Session present? Assume false, will be set to true only when applicable.
4050 sessp := false
4051 // Do we have an existing session for this client ID
4052 es, exists := asm.sessions[cid]
4053 asm.mu.Unlock()
4054 formatError := func(err error) error {
4055 return fmt.Errorf("%v for account %q, session %q", err, c.acc.GetName(), cid)
4056 }
4057
4058 // The session is not in the map, but may be on disk, so try to recover
4059 // or create the stream if not.
4060 if !exists {
4061 es, exists, err = asm.createOrRestoreSession(cid, s.getOpts())
4062 if err != nil {
4063 if err == errMQTTSessionCollision {
4064 sendConnAck(mqttConnAckRCIdentifierRejected, false)
4065 }
4066 return formatError(err)
4067 }
4068 }
4069 if exists {
4070 // Clear the session if client wants a clean session.
4071 // Also, Spec [MQTT-3.2.2-1]: don't report session present
4072 if cleanSess || es.clean {
4073 // Spec [MQTT-3.1.2-6]: If CleanSession is set to 1, the Client and
4074 // Server MUST discard any previous Session and start a new one.
4075 // This Session lasts as long as the Network Connection. State data
4076 // associated with this Session MUST NOT be reused in any subsequent
4077 // Session.
4078 if err := es.clear(false); err != nil {
4079 asm.removeSession(es, true)
4080 return err
4081 }
4082 } else {
4083 // Report to the client that the session was present
4084 sessp = true
4085 }
4086 // Spec [MQTT-3.1.4-2]. If the ClientId represents a Client already
4087 // connected to the Server then the Server MUST disconnect the existing
4088 // client.
4089 // Bind with the new client. This needs to be protected because can be
4090 // accessed outside of the readLoop.
4091 es.mu.Lock()
4092 ec := es.c
4093 es.c = c
4094 es.clean = cleanSess
4095 // Clear this flag so we resubscribe to PUBREL subject is needed.
4096 es.pubRelSubscribed = false
4097 es.mu.Unlock()
4098 if ec != nil {
4099 // Remove "will" of existing client before closing
4100 ec.mu.Lock()
4101 ec.mqtt.cp.will = nil
4102 ec.mu.Unlock()
4103 // Add to the map of the flappers
4104 asm.mu.Lock()
4105 asm.addSessToFlappers(cid)
4106 asm.mu.Unlock()
4107 c.Warnf("Replacing old client %q since both have the same client ID %q", ec, cid)
4108 // Close old client in separate go routine
4109 go ec.closeConnection(DuplicateClientID)
4110 }
4111 } else {
4112 // Spec [MQTT-3.2.2-3]: if the Server does not have stored Session state,
4113 // it MUST set Session Present to 0 in the CONNACK packet.
4114 es.mu.Lock()
4115 es.c, es.clean = c, cleanSess
4116 es.mu.Unlock()
4117 // Now add this new session into the account sessions
4118 asm.addSession(es, true)
4119 }
4120 // We would need to save only if it did not exist previously, but we save
4121 // always in case we are running in cluster mode. This will notify other
4122 // running servers that this session is being used.
4123 if err := es.save(); err != nil {
4124 asm.removeSession(es, true)
4125 return err
4126 }
4127 c.mu.Lock()
4128 c.flags.set(connectReceived)
4129 c.mqtt.cp = cp
4130 c.mqtt.asm = asm
4131 c.mqtt.sess = es
4132 c.mu.Unlock()
4133
4134 // Spec [MQTT-3.2.0-1]: CONNACK must be the first protocol sent to the session.
4135 sendConnAck(mqttConnAckRCConnectionAccepted, sessp)
4136
4137 // Process possible saved subscriptions.
4138 if l := len(es.subs); l > 0 {
4139 filters := make([]*mqttFilter, 0, l)
4140 for subject, qos := range es.subs {
4141 filters = append(filters, &mqttFilter{filter: subject, qos: qos})
4142 }
4143 if _, err := asm.processSubs(es, c, filters, false, trace); err != nil {
4144 return err
4145 }
4146 }
4147 return nil
4148 }
4149
4150 func (c *client) mqttEnqueueConnAck(rc byte, sessionPresent bool) {
4151 proto := [4]byte{mqttPacketConnectAck, 2, 0, rc}
4152 c.mu.Lock()
4153 // Spec [MQTT-3.2.2-4]. If return code is different from 0, then
4154 // session present flag must be set to 0.
4155 if rc == 0 {
4156 if sessionPresent {
4157 proto[2] = 1
4158 }
4159 }
4160 c.enqueueProto(proto[:])
4161 c.mu.Unlock()
4162 }
4163
4164 func (s *Server) mqttHandleWill(c *client) {
4165 c.mu.Lock()
4166 if c.mqtt.cp == nil {
4167 c.mu.Unlock()
4168 return
4169 }
4170 will := c.mqtt.cp.will
4171 if will == nil {
4172 c.mu.Unlock()
4173 return
4174 }
4175 // Create a synthetic PUBLISH packet to be delivered to the session's
4176 // subscriptions, regardless of what is currently in c.mqtt.pp.
4177 pp := &mqttPublish{
4178 topic: will.topic,
4179 subject: will.subject,
4180 mapped: will.mapped,
4181 msg: will.message,
4182 sz: len(will.message),
4183 flags: will.qos << 1,
4184 }
4185 if will.retain {
4186 pp.flags |= mqttPubFlagRetain
4187 }
4188 c.mu.Unlock()
4189 s.mqttInitiateMsgDelivery(c, pp)
4190 c.flushClients(0)
4191 }
4192
4193 //////////////////////////////////////////////////////////////////////////////
4194 //
4195 // PUBLISH protocol related functions
4196 //
4197 //////////////////////////////////////////////////////////////////////////////
4198
4199 func (c *client) mqttParsePub(r *mqttReader, pl int, pp *mqttPublish, hasMappings bool) error {
4200 qos := mqttGetQoS(pp.flags)
4201 if qos > 2 {
4202 return fmt.Errorf("QoS=%v is invalid in MQTT", qos)
4203 }
4204
4205 if c.mqtt.rejectQoS2Pub && qos == 2 {
4206 return fmt.Errorf("QoS=2 is disabled for PUBLISH messages")
4207 }
4208
4209 // Keep track of where we are when starting to read the variable header
4210 start := r.pos
4211
4212 var err error
4213 pp.topic, err = r.readBytes("topic", false)
4214 if err != nil {
4215 return err
4216 }
4217 if len(pp.topic) == 0 {
4218 return errMQTTTopicIsEmpty
4219 }
4220 if err := mqttValidateTopic(pp.topic, "topic"); err != nil {
4221 return err
4222 }
4223 // Convert the topic to a NATS subject. This call will also check that
4224 // there is no MQTT wildcards (Spec [MQTT-3.3.2-2] and [MQTT-4.7.1-1])
4225 // Note that this may not result in a copy if there is no conversion.
4226 // It is good because after the message is processed we won't have a
4227 // reference to the buffer and we save a copy.
4228 pp.subject, err = mqttTopicToNATSPubSubject(pp.topic)
4229 if err != nil {
4230 return err
4231 }
4232
4233 // Check for subject mapping.
4234 if hasMappings {
4235 // For selectMappedSubject to work, we need to have c.pa.subject set.
4236 // If there is a change, c.pa.mapped will be set after the call.
4237 c.pa.subject = pp.subject
4238 if changed := c.selectMappedSubject(); changed {
4239 // We need to keep track of the NATS subject/mapped in the `pp` structure.
4240 pp.subject = c.pa.subject
4241 pp.mapped = c.pa.mapped
4242 // We also now need to map the original MQTT topic to the new topic
4243 // based on the new subject.
4244 pp.topic = natsSubjectToMQTTTopic(pp.subject)
4245 }
4246 // Reset those now.
4247 c.pa.subject, c.pa.mapped = nil, nil
4248 }
4249
4250 if qos > 0 {
4251 pp.pi, err = r.readUint16("packet identifier")
4252 if err != nil {
4253 return err
4254 }
4255 if pp.pi == 0 {
4256 return fmt.Errorf("with QoS=%v, packet identifier cannot be 0", qos)
4257 }
4258 } else {
4259 pp.pi = 0
4260 }
4261
4262 // The message payload will be the total packet length minus
4263 // what we have consumed for the variable header
4264 payloadSize := pl - (r.pos - start)
4265 if payloadSize < 0 {
4266 return fmt.Errorf("invalid remaining length %d for PUBLISH packet", pl)
4267 }
4268 pp.sz = payloadSize
4269 if pp.sz > 0 {
4270 start = r.pos
4271 r.pos += pp.sz
4272 pp.msg = r.buf[start:r.pos]
4273 } else {
4274 pp.msg = nil
4275 }
4276 return nil
4277 }
4278
4279 func mqttValidateTopic(topic []byte, field string) error {
4280 if !utf8.Valid(topic) {
4281 return fmt.Errorf("invalid utf8 for %s %q", field, topic)
4282 }
4283 if bytes.IndexByte(topic, 0) >= 0 {
4284 return fmt.Errorf("invalid null character in %s %q", field, topic)
4285 }
4286 return nil
4287 }
4288
4289 func mqttValidateString(value string, field string) error {
4290 if !utf8.ValidString(value) {
4291 return fmt.Errorf("invalid utf8 for %s %q", field, value)
4292 }
4293 if strings.IndexByte(value, 0) >= 0 {
4294 return fmt.Errorf("invalid null character in %s %q", field, value)
4295 }
4296 return nil
4297 }
4298
4299 func mqttPubTrace(pp *mqttPublish) string {
4300 dup := pp.flags&mqttPubFlagDup != 0
4301 qos := mqttGetQoS(pp.flags)
4302 retain := mqttIsRetained(pp.flags)
4303 var piStr string
4304 if pp.pi > 0 {
4305 piStr = fmt.Sprintf(" pi=%v", pp.pi)
4306 }
4307 return fmt.Sprintf("%s dup=%v QoS=%v retain=%v size=%v%s",
4308 pp.topic, dup, qos, retain, pp.sz, piStr)
4309 }
4310
4311 // mqttComputeNatsMsgSize computes the size the NATS message to be delivered
4312 // based on a MQTT PUBLISH packet.
4313 // encodePP: whether to encode complete MQTT PUBLISH packet header information
4314 // - false: initial delivery (QoS 0/1) needs only base header
4315 // - true: QoS2 storage needs to encode Nmqtt-Subject and Nmqtt-Mapped
4316 func mqttComputeNatsMsgSize(pp *mqttPublish, encodePP bool) int {
4317 size := len(hdrLine) +
4318 len(mqttNatsHeader) + 2 + 2 + // 2 for ':<qos>', and 2 for CRLF
4319 2 + // end-of-header CRLF
4320 pp.sz
4321 if encodePP {
4322 size++ // for the flags byte
4323 size += len(mqttNatsHeaderSubject) + 1 + // +1 for ':'
4324 len(pp.subject) + 2 // 2 for CRLF
4325
4326 if len(pp.mapped) > 0 {
4327 size += len(mqttNatsHeaderMapped) + 1 + // +1 for ':'
4328 len(pp.mapped) + 2 // 2 for CRLF
4329 }
4330 }
4331 return size
4332 }
4333
4334 // Composes a NATS message from a MQTT PUBLISH packet. The message includes an
4335 // internal header containint the original packet's QoS, and for QoS2 packets
4336 // the original subject.
4337 //
4338 // Example (QoS2, subject: "foo.bar"):
4339 //
4340 // NATS/1.0\r\n
4341 // Nmqtt-Pub:2foo.bar\r\n
4342 // \r\n
4343 func mqttNewDeliverableMessage(pp *mqttPublish, encodePP bool) (natsMsg []byte, headerLen int) {
4344 size := mqttComputeNatsMsgSize(pp, encodePP)
4345
4346 buf := bytes.NewBuffer(make([]byte, 0, size))
4347
4348 qos := mqttGetQoS(pp.flags)
4349
4350 buf.WriteString(hdrLine)
4351 buf.WriteString(mqttNatsHeader)
4352 buf.WriteByte(':')
4353 buf.WriteByte(qos + '0')
4354 if encodePP {
4355 buf.WriteByte(mqttNatsHeaderEncodeFlags(pp.flags))
4356 }
4357 buf.WriteString(_CRLF_)
4358
4359 if encodePP {
4360 buf.WriteString(mqttNatsHeaderSubject)
4361 buf.WriteByte(':')
4362 buf.Write(pp.subject)
4363 buf.WriteString(_CRLF_)
4364
4365 if len(pp.mapped) > 0 {
4366 buf.WriteString(mqttNatsHeaderMapped)
4367 buf.WriteByte(':')
4368 buf.Write(pp.mapped)
4369 buf.WriteString(_CRLF_)
4370 }
4371 }
4372
4373 // End of header
4374 buf.WriteString(_CRLF_)
4375
4376 headerLen = buf.Len()
4377
4378 buf.Write(pp.msg)
4379 return buf.Bytes(), headerLen
4380 }
4381
4382 // Composes a NATS message for a pending PUBREL packet. The message includes an
4383 // internal header containing the PI for PUBREL/PUBCOMP.
4384 //
4385 // Example (PI:123):
4386 //
4387 // NATS/1.0\r\n
4388 // Nmqtt-PubRel:123\r\n
4389 // \r\n
4390 func mqttNewDeliverablePubRel(pi uint16) (natsMsg []byte, headerLen int) {
4391 size := len(hdrLine) +
4392 len(mqttNatsPubRelHeader) + 6 + 2 + // 6 for ':65535', and 2 for CRLF
4393 2 // end-of-header CRLF
4394 buf := bytes.NewBuffer(make([]byte, 0, size))
4395 buf.WriteString(hdrLine)
4396 buf.WriteString(mqttNatsPubRelHeader)
4397 buf.WriteByte(':')
4398 buf.WriteString(strconv.FormatInt(int64(pi), 10))
4399 buf.WriteString(_CRLF_)
4400 buf.WriteString(_CRLF_)
4401 return buf.Bytes(), buf.Len()
4402 }
4403
4404 // Process the PUBLISH packet.
4405 //
4406 // Runs from the client's readLoop.
4407 // No lock held on entry.
4408 func (s *Server) mqttProcessPub(c *client, pp *mqttPublish, trace bool) error {
4409 qos := mqttGetQoS(pp.flags)
4410
4411 // Enforce max_payload using existing client max payload logic (mpay) by
4412 // checking the total NATS message size that would be processed.
4413 if maxPayload := atomic.LoadInt32(&c.mpay); maxPayload != jwt.NoLimit {
4414 if total := mqttComputeNatsMsgSize(pp, qos == 2); total > int(maxPayload) {
4415 c.maxPayloadViolation(total, maxPayload)
4416 return ErrMaxPayload
4417 }
4418 }
4419
4420 switch qos {
4421 case 0:
4422 return s.mqttInitiateMsgDelivery(c, pp)
4423
4424 case 1:
4425 // [MQTT-4.3.2-2]. Initiate onward delivery of the Application Message,
4426 // Send PUBACK.
4427 //
4428 // The receiver is not required to complete delivery of the Application
4429 // Message before sending the PUBACK. When its original sender receives
4430 // the PUBACK packet, ownership of the Application Message is
4431 // transferred to the receiver.
4432 err := s.mqttInitiateMsgDelivery(c, pp)
4433 if err == nil {
4434 c.mqttEnqueuePubResponse(mqttPacketPubAck, pp.pi, trace)
4435 }
4436 return err
4437
4438 case 2:
4439 // [MQTT-4.3.3-2]. Method A, Store message, send PUBREC.
4440 //
4441 // The receiver is not required to complete delivery of the Application
4442 // Message before sending the PUBREC or PUBCOMP. When its original
4443 // sender receives the PUBREC packet, ownership of the Application
4444 // Message is transferred to the receiver.
4445 err := s.mqttStoreQoS2MsgOnce(c, pp)
4446 if err == nil {
4447 c.mqttEnqueuePubResponse(mqttPacketPubRec, pp.pi, trace)
4448 }
4449 return err
4450
4451 default:
4452 return fmt.Errorf("unreachable: invalid QoS in mqttProcessPub: %v", qos)
4453 }
4454 }
4455
4456 func (s *Server) mqttInitiateMsgDelivery(c *client, pp *mqttPublish) error {
4457 natsMsg, headerLen := mqttNewDeliverableMessage(pp, false)
4458
4459 // The delivered message becomes the client's current publish (it is not
4460 // the last PARSED packet for a PUBREL- or will-initiated delivery), and
4461 // c.pa carries its pubargs; one defer restores both. c.mqtt.pp is
4462 // readLoop-owned, like c.pa.
4463 prevPP := c.mqtt.pp
4464 c.mqtt.pp = pp
4465
4466 c.pa.subject = pp.subject
4467 c.pa.mapped = pp.mapped
4468 c.pa.reply = nil
4469 c.pa.hdr = headerLen
4470 c.pa.hdb = []byte(strconv.FormatInt(int64(c.pa.hdr), 10))
4471 c.pa.size = len(natsMsg)
4472 c.pa.szb = []byte(strconv.FormatInt(int64(c.pa.size), 10))
4473 defer func() {
4474 c.mqtt.pp = prevPP
4475 c.pa.subject = nil
4476 c.pa.mapped = nil
4477 c.pa.reply = nil
4478 c.pa.hdr = -1
4479 c.pa.hdb = nil
4480 c.pa.size = 0
4481 c.pa.szb = nil
4482 }()
4483
4484 _, permIssue := c.processInboundClientMsg(natsMsg)
4485 if permIssue {
4486 return nil
4487 }
4488
4489 // If QoS 0 messages don't need to be stored, other (1 and 2) do. Store them
4490 // JetStream under "$MQTT.msgs.<delivery-subject>"
4491 if qos := mqttGetQoS(pp.flags); qos == 0 {
4492 return nil
4493 }
4494
4495 // We need to call flushClients now since this we may have called c.addToPCD
4496 // with destination clients (possibly a route). Without calling flushClients
4497 // the following call may then be stuck waiting for a reply that may never
4498 // come because the destination is not flushed (due to c.out.fsp > 0,
4499 // see addToPCD and writeLoop for details).
4500 c.flushClients(0)
4501
4502 _, err := c.mqtt.sess.jsa.storeMsg(mqttStreamSubjectPrefix+string(c.pa.subject), headerLen, natsMsg)
4503
4504 return err
4505 }
4506
4507 var mqttMaxMsgErrPattern = fmt.Sprintf("%s (%v)", ErrMaxMsgsPerSubject.Error(), JSStreamStoreFailedF)
4508
4509 func (s *Server) mqttStoreQoS2MsgOnce(c *client, pp *mqttPublish) error {
4510 // `true` means encode the MQTT PUBLISH packet in the NATS message header.
4511 natsMsg, headerLen := mqttNewDeliverableMessage(pp, true)
4512
4513 // Do not broadcast the message until it has been deduplicated and released
4514 // by the sender. Instead store this QoS2 message as
4515 // "$MQTT.qos2.<client-id>.<PI>". If the message is a duplicate, we get back
4516 // a ErrMaxMsgsPerSubject, otherwise it does not change the flow, still need
4517 // to send a PUBREC back to the client. The original subject (translated
4518 // from MQTT topic) is included in the NATS header of the stored message to
4519 // use for latter delivery.
4520 _, err := c.mqtt.sess.jsa.storeMsg(c.mqttQoS2InternalSubject(pp.pi), headerLen, natsMsg)
4521
4522 // TODO: would prefer a more robust and performant way of checking the
4523 // error, but it comes back wrapped as an API result.
4524 if err != nil &&
4525 (isErrorOtherThan(err, JSStreamStoreFailedF) || err.Error() != mqttMaxMsgErrPattern) {
4526 return err
4527 }
4528
4529 return nil
4530 }
4531
4532 func (c *client) mqttQoS2InternalSubject(pi uint16) string {
4533 return mqttQoS2IncomingMsgsStreamSubjectPrefix + c.mqtt.cid + "." + strconv.FormatUint(uint64(pi), 10)
4534 }
4535
4536 // Process a PUBREL packet (QoS2, acting as Receiver).
4537 //
4538 // Runs from the client's readLoop.
4539 // No lock held on entry.
4540 func (s *Server) mqttProcessPubRel(c *client, pi uint16, trace bool) error {
4541 // Once done with the processing, send a PUBCOMP back to the client.
4542 defer c.mqttEnqueuePubResponse(mqttPacketPubComp, pi, trace)
4543
4544 // See if there is a message pending for this pi. All failures are treated
4545 // as "not found".
4546 asm := c.mqtt.asm
4547 stored, _ := asm.jsa.loadLastMsgFor(mqttQoS2IncomingMsgsStreamName, c.mqttQoS2InternalSubject(pi))
4548
4549 if stored == nil {
4550 // No message found, nothing to do.
4551 return nil
4552 }
4553 // Best attempt to delete the message from the QoS2 stream.
4554 asm.jsa.deleteMsg(mqttQoS2IncomingMsgsStreamName, stored.Sequence, true)
4555
4556 // only MQTT QoS2 messages should be here, and they must have a subject.
4557 h := mqttParsePublishNATSHeader(stored.Header)
4558 if h == nil || h.qos != 2 || len(h.subject) == 0 {
4559 return errors.New("invalid message in QoS2 PUBREL stream")
4560 }
4561
4562 flags := h.qos << 1
4563 if h.retained {
4564 flags |= mqttPubFlagRetain
4565 }
4566 pp := &mqttPublish{
4567 topic: natsSubjectToMQTTTopic(h.subject),
4568 subject: h.subject,
4569 mapped: h.mapped,
4570 msg: stored.Data,
4571 sz: len(stored.Data),
4572 pi: pi,
4573 flags: flags,
4574 }
4575
4576 return s.mqttInitiateMsgDelivery(c, pp)
4577 }
4578
4579 // Invoked when processing an inbound client message. If the "retain" flag is
4580 // set, the message is stored so it can be later resent to (re)starting
4581 // subscriptions that match the subject.
4582 //
4583 // Invoked from the MQTT publisher's readLoop. No client lock is held on entry.
4584 func (c *client) mqttHandlePubRetain() {
4585 pp := c.mqtt.pp
4586 retainMQTT := mqttIsRetained(pp.flags)
4587 isBirth, _, isCertificate := sparkbParseBirthDeathTopic(pp.topic)
4588 retainSparkbBirth := isBirth && !isCertificate
4589
4590 // [tck-id-topics-nbirth-mqtt] NBIRTH messages MUST be published with MQTT
4591 // QoS equal to 0 and retain equal to false.
4592 //
4593 // [tck-id-conformance-mqtt-aware-nbirth-mqtt-retain] A Sparkplug Aware MQTT
4594 // Server MUST make NBIRTH messages available on the topic:
4595 // $sparkplug/certificates/namespace/group_id/NBIRTH/edge_node_id with the
4596 // MQTT retain flag set to true.
4597 if retainMQTT == retainSparkbBirth {
4598 // (retainSparkbBirth && retainMQTT) : not valid, so ignore altogether.
4599 // (!retainSparkbBirth && !retainMQTT) : nothing to do.
4600 return
4601 }
4602
4603 asm := c.mqtt.asm
4604 key := string(pp.subject)
4605
4606 // Always clear the retain flag to deliver a normal published message.
4607 defer func() {
4608 pp.flags &= ^mqttPubFlagRetain
4609 }()
4610
4611 // Spec [MQTT-3.3.1-11]. Payload of size 0 removes the retained message, but
4612 // should still be delivered as a normal message.
4613 //
4614 // We used to delete the message here from our map, the stream, and notify
4615 // the network about the delete. We no longer do that. Instead, we store
4616 // the message with an empty body. When servers will get the empty body
4617 // in processRetainedMsg, then will remove the message from their map. This
4618 // effectively serializes all add/remove of retained messages without the
4619 // need for "network" notifications about deletes (we still support that
4620 // for backward compatibility but will be pulled in future releases).
4621
4622 rm := &mqttRetainedMsg{
4623 Origin: asm.jsa.id,
4624 Msg: pp.msg, // will copy these bytes later as we process rm.
4625 Flags: pp.flags,
4626 Source: c.opts.Username,
4627 }
4628
4629 if retainSparkbBirth {
4630 // [tck-id-conformance-mqtt-aware-store] A Sparkplug Aware MQTT Server
4631 // MUST store NBIRTH and DBIRTH messages as they pass through the MQTT
4632 // Server.
4633 //
4634 // [tck-id-conformance-mqtt-aware-nbirth-mqtt-topic]. A Sparkplug Aware
4635 // MQTT Server MUST make NBIRTH messages available on a topic of the
4636 // form: $sparkplug/certificates/namespace/group_id/NBIRTH/edge_node_id
4637 //
4638 // [tck-id-conformance-mqtt-aware-dbirth-mqtt-topic] A Sparkplug Aware
4639 // MQTT Server MUST make DBIRTH messages available on a topic of the
4640 // form:
4641 // $sparkplug/certificates/namespace/group_id/DBIRTH/edge_node_id/device_id
4642 topic := append(sparkbCertificatesTopicPrefix, pp.topic...)
4643 subject, _ := mqttTopicToNATSPubSubject(topic)
4644 rm.Topic = string(topic)
4645 rm.Subject = string(subject)
4646
4647 // will use to save the retained message.
4648 key = string(subject)
4649
4650 // Store the retained message with the RETAIN flag set.
4651 rm.Flags |= mqttPubFlagRetain
4652
4653 if pp.sz > 0 {
4654 // Copy the payload out of pp since we will be sending the message
4655 // asynchronously.
4656 msg := make([]byte, pp.sz)
4657 copy(msg, pp.msg[:pp.sz])
4658 asm.jsa.sendMsg(key, msg)
4659 }
4660
4661 } else { // isRetained
4662 // Spec [MQTT-3.3.1-5]. Store the retained message with its QoS.
4663 //
4664 // When coming from a publish protocol, `pp` is referencing a stack
4665 // variable that itself possibly references the read buffer.
4666 rm.Topic = string(pp.topic)
4667 }
4668
4669 // Set the key to the subject of the message for retained, or the composed
4670 // $sparkplug subject for sparkB.
4671 rm.Subject = key
4672 rmBytes, hdr := mqttEncodeRetainedMessage(rm) // will copy the payload bytes
4673 _, err := asm.jsa.storeMsg(mqttRetainedMsgsStreamSubject+key, hdr, rmBytes)
4674 if err != nil {
4675 c.mu.Lock()
4676 acc := c.acc
4677 c.mu.Unlock()
4678 c.Errorf("unable to store retained message for account %q, subject %q: %v",
4679 acc.GetName(), key, err)
4680 }
4681 }
4682
4683 // After a config reload, it is possible that the source of a publish retained
4684 // message is no longer allowed to publish on the given topic. If that is the
4685 // case, the retained message is removed from the map and will no longer be
4686 // sent to (re)starting subscriptions.
4687 //
4688 // Server lock MUST NOT be held on entry.
4689 func (s *Server) mqttCheckPubRetainedPerms() {
4690 sm := &s.mqtt.sessmgr
4691 sm.mu.RLock()
4692 done := len(sm.sessions) == 0
4693 sm.mu.RUnlock()
4694
4695 if done {
4696 return
4697 }
4698
4699 s.mu.Lock()
4700 users := make(map[string]*User, len(s.users))
4701 for un, u := range s.users {
4702 users[un] = u
4703 }
4704 s.mu.Unlock()
4705
4706 // First get a list of all of the sessions.
4707 sm.mu.RLock()
4708 asms := make([]*mqttAccountSessionManager, 0, len(sm.sessions))
4709 for _, asm := range sm.sessions {
4710 asms = append(asms, asm)
4711 }
4712 sm.mu.RUnlock()
4713
4714 // For each session we will obtain a list of retained messages.
4715 var _rms [128]uint64
4716 rms := _rms[:0]
4717 for _, asm := range asms {
4718 // Get all of the retained messages. Then we will sort them so
4719 // that they are in sequence order, which should help the file
4720 // store to not have to load out-of-order blocks so often.
4721 asm.mu.RLock()
4722 rms = rms[:0] // reuse slice
4723 // Copy the sequence out of the tree. The tree entry itself can be
4724 // updated concurrently by addRetainedMsg() after we release the lock,
4725 // so keeping a pointer here would race with the later sort.
4726 asm.retmsgs.IterOrdered(func(_ []byte, rm *mqttRetainedMsgRef) bool {
4727 rms = append(rms, rm.sseq)
4728 return true
4729 })
4730 jsaID := asm.jsa.id
4731 asm.mu.RUnlock()
4732 slices.Sort(rms)
4733
4734 perms := map[string]*mqttPerm{}
4735 for _, rf := range rms {
4736 jsm, err := asm.jsa.loadMsg(mqttRetainedMsgsStreamName, rf)
4737 if err != nil || jsm == nil {
4738 continue
4739 }
4740 rm, err := mqttDecodeRetainedMessage(jsm.Subject, jsm.Header, jsm.Data)
4741 if err != nil {
4742 continue
4743 }
4744 // We deal only with messages that have a source (the username that produced
4745 // this message) and were produced on this server.
4746 if rm.Source == _EMPTY_ || rm.Origin != jsaID {
4747 continue
4748 }
4749 // Lookup source from global users.
4750 u := users[rm.Source]
4751 if u != nil {
4752 p, ok := perms[rm.Source]
4753 if !ok {
4754 p = generatePubPerms(u.Permissions)
4755 perms[rm.Source] = p // possibly nil
4756 }
4757 // If there is permission and no longer allowed to publish in
4758 // the subject, remove the publish retained message from the map.
4759 if p != nil && !pubAllowed(p, rm.Subject) {
4760 u = nil
4761 }
4762 }
4763
4764 // Not present or permissions have changed such that the source can't
4765 // publish on that subject anymore: delete this retained message.
4766 if u == nil {
4767 // Set the payload to empty to notify that we are deleting this
4768 // retained message. We will send this message async.
4769 rm.Msg = nil
4770 rmBytes, hdrLen := mqttEncodeRetainedMessage(rm)
4771 asm.jsa.storeMsgNoWait(mqttRetainedMsgsStreamSubject+rm.Subject, hdrLen, rmBytes)
4772 }
4773 }
4774 }
4775 }
4776
4777 // Helper to generate only pub permissions from a Permissions object
4778 type mqttPerm struct {
4779 allow *gsl.SimpleSublist
4780 deny *gsl.SimpleSublist
4781 }
4782
4783 func generatePubPerms(perms *Permissions) *mqttPerm {
4784 // If given permissions is `nil`, then it means that permissions block
4785 // has been removed (so the user is now allowed to publish on everything)
4786 // or was never there in the first place. Returning `nil` will let the
4787 // caller know that there are no permissions to enforce.
4788 if perms == nil {
4789 return nil
4790 }
4791 var p *mqttPerm
4792 if perms.Publish.Allow != nil {
4793 p = &mqttPerm{}
4794 p.allow = gsl.NewSimpleSublist()
4795 for _, pubSubject := range perms.Publish.Allow {
4796 _ = p.allow.Insert(pubSubject, struct{}{})
4797 }
4798 }
4799 if len(perms.Publish.Deny) > 0 {
4800 if p == nil {
4801 p = &mqttPerm{}
4802 }
4803 p.deny = gsl.NewSimpleSublist()
4804 for _, pubSubject := range perms.Publish.Deny {
4805 _ = p.deny.Insert(pubSubject, struct{}{})
4806 }
4807 }
4808 return p
4809 }
4810
4811 // Helper that checks if given `perms` allow to publish on the given `subject`
4812 func pubAllowed(perms *mqttPerm, subject string) bool {
4813 if perms == nil {
4814 return true
4815 }
4816 allowed := true
4817 if perms.allow != nil {
4818 allowed = perms.allow.HasInterest(subject)
4819 }
4820 // If we have a deny list and are currently allowed, check that as well.
4821 if allowed && perms.deny != nil {
4822 allowed = !perms.deny.HasInterest(subject)
4823 }
4824 return allowed
4825 }
4826
4827 func (c *client) mqttEnqueuePubResponse(packetType byte, pi uint16, trace bool) {
4828 proto := [4]byte{packetType, 0x2, 0, 0}
4829 proto[2] = byte(pi >> 8)
4830 proto[3] = byte(pi)
4831
4832 // Bits 3,2,1 and 0 of the fixed header in the PUBREL Control Packet are
4833 // reserved and MUST be set to 0,0,1 and 0 respectively. The Server MUST treat
4834 // any other value as malformed and close the Network Connection [MQTT-3.6.1-1].
4835 if packetType == mqttPacketPubRel {
4836 proto[0] |= 0x2
4837 }
4838
4839 c.mu.Lock()
4840 c.enqueueProto(proto[:4])
4841 c.mu.Unlock()
4842
4843 if trace {
4844 name := "(???)"
4845 switch packetType {
4846 case mqttPacketPubAck:
4847 name = "PUBACK"
4848 case mqttPacketPubRec:
4849 name = "PUBREC"
4850 case mqttPacketPubRel:
4851 name = "PUBREL"
4852 case mqttPacketPubComp:
4853 name = "PUBCOMP"
4854 }
4855 c.traceOutOp(name, []byte(fmt.Sprintf("pi=%v", pi)))
4856 }
4857 }
4858
4859 func mqttParsePIPacket(r *mqttReader) (uint16, error) {
4860 pi, err := r.readUint16("packet identifier")
4861 if err != nil {
4862 return 0, err
4863 }
4864 if pi == 0 {
4865 return 0, errMQTTPacketIdentifierIsZero
4866 }
4867 return pi, nil
4868 }
4869
4870 // Process a PUBACK (QoS1) or a PUBREC (QoS2) packet, acting as Sender. Set
4871 // isPubRec to false to process as a PUBACK.
4872 //
4873 // Runs from the client's readLoop. No lock held on entry.
4874 func (c *client) mqttProcessPublishReceived(pi uint16, isPubRec bool) (err error) {
4875 sess := c.mqtt.sess
4876 if sess == nil {
4877 return errMQTTInvalidSession
4878 }
4879
4880 var jsAckSubject string
4881 sess.mu.Lock()
4882 // Must be the same client, and the session must have been setup for QoS2.
4883 if sess.c != c {
4884 sess.mu.Unlock()
4885 return errMQTTInvalidSession
4886 }
4887 if isPubRec {
4888 // The JS ACK subject for the PUBREL will be filled in at the delivery
4889 // attempt.
4890 sess.trackAsPubRel(pi, _EMPTY_)
4891 }
4892 jsAckSubject = sess.untrackPublish(pi)
4893 sess.mu.Unlock()
4894
4895 if isPubRec {
4896 natsMsg, headerLen := mqttNewDeliverablePubRel(pi)
4897 _, err = sess.jsa.storeMsg(sess.pubRelSubject, headerLen, natsMsg)
4898 if err != nil {
4899 // Failure to send out PUBREL will terminate the connection.
4900 return err
4901 }
4902 }
4903
4904 // Send the ack to JS to remove the pending message from the consumer.
4905 sess.jsa.sendAck(jsAckSubject)
4906 return nil
4907 }
4908
4909 func (c *client) mqttProcessPubAck(pi uint16) error {
4910 return c.mqttProcessPublishReceived(pi, false)
4911 }
4912
4913 func (c *client) mqttProcessPubRec(pi uint16) error {
4914 return c.mqttProcessPublishReceived(pi, true)
4915 }
4916
4917 // Runs from the client's readLoop. No lock held on entry.
4918 func (c *client) mqttProcessPubComp(pi uint16) {
4919 sess := c.mqtt.sess
4920 if sess == nil {
4921 return
4922 }
4923
4924 var jsAckSubject string
4925 sess.mu.Lock()
4926 if sess.c != c {
4927 sess.mu.Unlock()
4928 return
4929 }
4930 jsAckSubject = sess.untrackPubRel(pi)
4931 sess.mu.Unlock()
4932
4933 // Send the ack to JS to remove the pending message from the consumer.
4934 sess.jsa.sendAck(jsAckSubject)
4935 }
4936
4937 // Return the QoS from the given PUBLISH protocol's flags
4938 func mqttGetQoS(flags byte) byte {
4939 return flags & mqttPubFlagQoS >> 1
4940 }
4941
4942 func mqttIsRetained(flags byte) bool {
4943 return flags&mqttPubFlagRetain != 0
4944 }
4945
4946 func sparkbParseBirthDeathTopic(topic []byte) (isBirth, isDeath, isCertificate bool) {
4947 if bytes.HasPrefix(topic, sparkbCertificatesTopicPrefix) {
4948 isCertificate = true
4949 topic = topic[len(sparkbCertificatesTopicPrefix):]
4950 }
4951 if !bytes.HasPrefix(topic, sparkbNamespaceTopicPrefix) {
4952 return false, false, false
4953 }
4954 topic = topic[len(sparkbNamespaceTopicPrefix):]
4955
4956 parts := bytes.Split(topic, []byte{'/'})
4957 if len(parts) < 3 || len(parts) > 4 {
4958 return false, false, false
4959 }
4960 typ := bytesToString(parts[1])
4961 switch typ {
4962 case sparkbNBIRTH, sparkbDBIRTH:
4963 isBirth = true
4964 case sparkbNDEATH, sparkbDDEATH:
4965 isDeath = true
4966 default:
4967 return false, false, false
4968 }
4969 return isBirth, isDeath, isCertificate
4970 }
4971
4972 //////////////////////////////////////////////////////////////////////////////
4973 //
4974 // SUBSCRIBE related functions
4975 //
4976 //////////////////////////////////////////////////////////////////////////////
4977
4978 func (c *client) mqttParseSubs(r *mqttReader, b byte, pl int) (uint16, []*mqttFilter, error) {
4979 return c.mqttParseSubsOrUnsubs(r, b, pl, true)
4980 }
4981
4982 func (c *client) mqttParseSubsOrUnsubs(r *mqttReader, b byte, pl int, sub bool) (uint16, []*mqttFilter, error) {
4983 var expectedFlag byte
4984 var action string
4985 if sub {
4986 expectedFlag = mqttSubscribeFlags
4987 } else {
4988 expectedFlag = mqttUnsubscribeFlags
4989 action = "un"
4990 }
4991 // Spec [MQTT-3.8.1-1], [MQTT-3.10.1-1]
4992 if rf := b & 0xf; rf != expectedFlag {
4993 return 0, nil, fmt.Errorf("wrong %ssubscribe reserved flags: %x", action, rf)
4994 }
4995 pi, err := mqttParsePIPacket(r)
4996 if err != nil {
4997 return 0, nil, err
4998 }
4999 end := r.pos + (pl - 2)
5000 var filters []*mqttFilter
5001 for r.pos < end {
5002 // Don't make a copy now because, this will happen during conversion
5003 // or when processing the sub.
5004 topic, err := r.readBytes("topic filter", false)
5005 if err != nil {
5006 return 0, nil, err
5007 }
5008 if len(topic) == 0 {
5009 return 0, nil, errMQTTTopicFilterCannotBeEmpty
5010 }
5011 // Spec [MQTT-3.8.3-1], [MQTT-3.10.3-1]
5012 if err := mqttValidateTopic(topic, "topic filter"); err != nil {
5013 return 0, nil, err
5014 }
5015 var qos byte
5016 // We are going to report if we had an error during the conversion,
5017 // but we don't fail the parsing. When processing the sub, we will
5018 // have an error then, and the processing of subs code will send
5019 // the proper mqttSubAckFailure flag for this given subscription.
5020 filter, err := mqttFilterToNATSSubject(topic)
5021 if err != nil {
5022 c.Errorf("invalid topic %q: %v", topic, err)
5023 }
5024 if sub {
5025 qos, err = r.readByte("QoS")
5026 if err != nil {
5027 return 0, nil, err
5028 }
5029 // Spec [MQTT-3-8.3-4].
5030 if qos > 2 {
5031 return 0, nil, fmt.Errorf("subscribe QoS value must be 0, 1 or 2, got %v", qos)
5032 }
5033 }
5034 f := &mqttFilter{ttopic: topic, filter: string(filter), qos: qos}
5035 filters = append(filters, f)
5036 }
5037 // Spec [MQTT-3.8.3-3], [MQTT-3.10.3-2]
5038 if len(filters) == 0 {
5039 return 0, nil, fmt.Errorf("%ssubscribe protocol must contain at least 1 topic filter", action)
5040 }
5041 return pi, filters, nil
5042 }
5043
5044 func mqttSubscribeTrace(pi uint16, filters []*mqttFilter) string {
5045 var sep string
5046 sb := &strings.Builder{}
5047 sb.WriteString("[")
5048 for i, f := range filters {
5049 sb.WriteString(sep)
5050 sb.Write(f.ttopic)
5051 sb.WriteString(" (")
5052 sb.WriteString(f.filter)
5053 sb.WriteString(") QoS=")
5054 sb.WriteString(fmt.Sprintf("%v", f.qos))
5055 if i == 0 {
5056 sep = ", "
5057 }
5058 }
5059 sb.WriteString(fmt.Sprintf("] pi=%v", pi))
5060 return sb.String()
5061 }
5062
5063 // For a MQTT QoS0 subscription, we create a single NATS subscription on the
5064 // actual subject, for instance "foo.bar".
5065 //
5066 // For a MQTT QoS1+ subscription, we create 2 subscriptions, one on "foo.bar"
5067 // (as for QoS0, but sub.mqtt.qos will be 1 or 2), and one on the subject
5068 // "$MQTT.sub.<uid>" which is the delivery subject of the JS durable consumer
5069 // with the filter subject "$MQTT.msgs.foo.bar".
5070 //
5071 // This callback delivers messages to the client as QoS0 messages, either
5072 // because: (a) they have been produced as MQTT QoS0 messages (and therefore
5073 // only this callback can receive them); (b) they are MQTT QoS1+ published
5074 // messages but this callback is for a subscription that is QoS0; or (c) the
5075 // published messages come from (other) NATS publishers on the subject.
5076 //
5077 // This callback must reject a message if it is known to be a QoS1+ published
5078 // message and this is the callback for a QoS1+ subscription because in that
5079 // case, it will be handled by the other callback. This avoid getting duplicate
5080 // deliveries.
5081 func mqttDeliverMsgCbQoS0(sub *subscription, pc *client, _ *Account, subject, reply string, rmsg []byte) {
5082 if pc.kind == JETSTREAM && len(reply) > 0 && strings.HasPrefix(reply, jsAckPre) {
5083 return
5084 }
5085
5086 // This is the client associated with the subscription.
5087 cc := sub.client
5088
5089 // This is immutable
5090 sess := cc.mqtt.sess
5091
5092 // Lock here, otherwise we may be called with sub.mqtt == nil. Ignore
5093 // wildcard subscriptions if this subject starts with '$', per Spec
5094 // [MQTT-4.7.2-1].
5095 sess.subsMu.RLock()
5096 subQoS := sub.mqtt.qos
5097 ignore := mqttMustIgnoreForReservedSub(sub, subject)
5098 sess.subsMu.RUnlock()
5099
5100 if ignore {
5101 return
5102 }
5103
5104 hdr, msg := pc.msgParts(rmsg)
5105 var topic []byte
5106 if pc.isMqtt() {
5107 // This is an MQTT publisher directly connected to this server.
5108
5109 // Check the subscription's QoS. If the message was published with a
5110 // QoS>0 and the sub has the QoS>0 then the message will be delivered by
5111 // mqttDeliverMsgCbQoS12.
5112 msgQoS := mqttGetQoS(pc.mqtt.pp.flags)
5113 if subQoS > 0 && msgQoS > 0 {
5114 return
5115 }
5116 topic = pc.mqtt.pp.topic
5117 // If the subject is different than the one in pp.subject, then some
5118 // mapping/transform occurred and we need to recreate the topic.
5119 if subject != bytesToString(pc.mqtt.pp.subject) {
5120 topic = natsSubjectStrToMQTTTopic(subject)
5121 }
5122
5123 } else {
5124 // Non MQTT client, could be NATS publisher, or ROUTER, etc..
5125 h := mqttParsePublishNATSHeader(hdr)
5126
5127 // Check the subscription's QoS. If the message was published with a
5128 // QoS>0 (in the header) and the sub has the QoS>0 then the message will
5129 // be delivered by mqttDeliverMsgCbQoS12.
5130 if subQoS > 0 && h != nil && h.qos > 0 {
5131 return
5132 }
5133
5134 // If size is more than what a MQTT client can handle, we should probably reject,
5135 // for now just truncate.
5136 if len(msg) > mqttMaxPayloadSize {
5137 msg = msg[:mqttMaxPayloadSize]
5138 }
5139 topic = natsSubjectStrToMQTTTopic(subject)
5140 }
5141
5142 // Message never has a packet identifier nor is marked as duplicate.
5143 pc.mqttEnqueuePublishMsgTo(cc, sub, 0, 0, false, topic, msg)
5144 }
5145
5146 // This is the callback attached to a JS durable subscription for a MQTT QoS 1+
5147 // sub. Only JETSTREAM should be sending a message to this subject (the delivery
5148 // subject associated with the JS durable consumer), but in cluster mode, this
5149 // can be coming from a route, gw, etc... We make sure that if this is the case,
5150 // the message contains a NATS/MQTT header that indicates that this is a
5151 // published QoS1+ message.
5152 func mqttDeliverMsgCbQoS12(sub *subscription, pc *client, _ *Account, subject, reply string, rmsg []byte) {
5153 // Message on foo.bar is stored under $MQTT.msgs.foo.bar, so the subject has to be
5154 // at least as long as the stream subject prefix "$MQTT.msgs.", and after removing
5155 // the prefix, has to be at least 1 character long.
5156 if len(subject) < len(mqttStreamSubjectPrefix)+1 {
5157 return
5158 }
5159
5160 hdr, msg := pc.msgParts(rmsg)
5161 h := mqttParsePublishNATSHeader(hdr)
5162 if pc.kind != JETSTREAM && (h == nil || h.qos == 0) {
5163 // MQTT QoS 0 messages must be ignored, they will be delivered by the
5164 // other callback, the direct NATS subscription. All JETSTREAM messages
5165 // will have the header.
5166 return
5167 }
5168
5169 // This is the client associated with the subscription.
5170 cc := sub.client
5171
5172 // This is immutable
5173 sess := cc.mqtt.sess
5174
5175 // We lock to check some of the subscription's fields and if we need to keep
5176 // track of pending acks, etc. There is no need to acquire the subsMu RLock
5177 // since sess.Lock is overarching for modifying subscriptions.
5178 sess.mu.Lock()
5179 if sess.c != cc || sub.mqtt == nil || sub.mqtt.closed {
5180 sess.mu.Unlock()
5181 return
5182 }
5183
5184 // In this callback we handle only QoS-published messages to QoS
5185 // subscriptions. Ignore if either is 0, will be delivered by the other
5186 // callback, mqttDeliverMsgCbQos1.
5187 var qos byte
5188 if h != nil {
5189 qos = h.qos
5190 }
5191 if qos > sub.mqtt.qos {
5192 qos = sub.mqtt.qos
5193 }
5194 if qos == 0 {
5195 sess.mu.Unlock()
5196 return
5197 }
5198
5199 // Check for reserved subject violation. If so, we will send the ack to
5200 // remove the message, and do nothing else.
5201 strippedSubj := subject[len(mqttStreamSubjectPrefix):]
5202 if mqttMustIgnoreForReservedSub(sub, strippedSubj) {
5203 sess.mu.Unlock()
5204 sess.jsa.sendAck(reply)
5205 return
5206 }
5207
5208 // A broad wildcard subscription can overlap a subscribe deny clause.
5209 cc.mu.Lock()
5210 denied := cc.mperms != nil && cc.checkDenySub(strippedSubj, bytesToString(sub.queue))
5211 cc.mu.Unlock()
5212 if denied {
5213 sess.mu.Unlock()
5214 sess.jsa.sendAck(reply)
5215 return
5216 }
5217
5218 pi, dup := sess.trackPublish(sub.mqtt.jsDur, reply)
5219 sess.mu.Unlock()
5220
5221 if pi == 0 {
5222 // We have reached max pending, don't send the message now.
5223 // JS will cause a redelivery and if by then the number of pending
5224 // messages has fallen below threshold, the message will be resent.
5225 return
5226 }
5227
5228 originalTopic := natsSubjectStrToMQTTTopic(strippedSubj)
5229 pc.mqttEnqueuePublishMsgTo(cc, sub, pi, qos, dup, originalTopic, msg)
5230 }
5231
5232 func mqttDeliverPubRelCb(sub *subscription, pc *client, _ *Account, subject, reply string, rmsg []byte) {
5233 if sub.client.mqtt == nil || sub.client.mqtt.sess == nil || reply == _EMPTY_ {
5234 return
5235 }
5236
5237 hdr, _ := pc.msgParts(rmsg)
5238 pi := mqttParsePubRelNATSHeader(hdr)
5239 if pi == 0 {
5240 return
5241 }
5242
5243 // This is the client associated with the subscription.
5244 cc := sub.client
5245
5246 // This is immutable
5247 sess := cc.mqtt.sess
5248
5249 sess.mu.Lock()
5250 if sess.c != cc || sess.pubRelConsumer == nil {
5251 sess.mu.Unlock()
5252 return
5253 }
5254 sess.trackAsPubRel(pi, reply)
5255 trace := cc.trace
5256 sess.mu.Unlock()
5257
5258 cc.mqttEnqueuePubResponse(mqttPacketPubRel, pi, trace)
5259 }
5260
5261 // The MQTT Server MUST NOT match Topic Filters starting with a wildcard
5262 // character (# or +) with Topic Names beginning with a $ character, Spec
5263 // [MQTT-4.7.2-1]. We will return true if there is a violation.
5264 //
5265 // Session or subMu lock must be held on entry to protect access to sub.mqtt.
5266 func mqttMustIgnoreForReservedSub(sub *subscription, subject string) bool {
5267 // If the subject does not start with $ nothing to do here.
5268 if !sub.mqtt.reserved || len(subject) == 0 || subject[0] != mqttReservedPre {
5269 return false
5270 }
5271 return true
5272 }
5273
5274 // Check if a sub is a reserved wildcard. E.g. '#', '*', or '*/" prefix.
5275 func isMQTTReservedSubscription(subject string) bool {
5276 if len(subject) == 1 && (subject[0] == fwc || subject[0] == pwc) {
5277 return true
5278 }
5279 // Match "*.<>"
5280 if len(subject) > 1 && (subject[0] == pwc && subject[1] == btsep) {
5281 return true
5282 }
5283 return false
5284 }
5285
5286 func sparkbReplaceDeathTimestamp(msg []byte) []byte {
5287 const VARINT = 0
5288 const TIMESTAMP = 1
5289
5290 orig := msg
5291 buf := bytes.NewBuffer(make([]byte, 0, len(msg)+16)) // 16 bytes should be enough if we need to add a timestamp
5292 writeDeathTimestamp := func() {
5293 // [tck-id-conformance-mqtt-aware-ndeath-timestamp] A Sparkplug Aware
5294 // MQTT Server MAY replace the timestamp of NDEATH messages. If it does,
5295 // it MUST set the timestamp to the UTC time at which it attempts to
5296 // deliver the NDEATH to subscribed clients
5297 //
5298 // sparkB spec: 6.4.1. Google Protocol Buffer Schema
5299 // optional uint64 timestamp = 1; // Timestamp at message sending time
5300 //
5301 // SparkplugB timestamps are milliseconds since epoch, represented as
5302 // uint64 in go, transmitted as protobuf varint.
5303 ts := uint64(time.Now().UnixMilli())
5304 buf.Write(protoEncodeVarint(TIMESTAMP<<3 | VARINT))
5305 buf.Write(protoEncodeVarint(ts))
5306 }
5307
5308 for len(msg) > 0 {
5309 fieldNumericID, fieldType, size, err := protoScanField(msg)
5310 if err != nil {
5311 return orig
5312 }
5313 if fieldType != VARINT || fieldNumericID != TIMESTAMP {
5314 // Add the field as is
5315 buf.Write(msg[:size])
5316 msg = msg[size:]
5317 continue
5318 }
5319
5320 writeDeathTimestamp()
5321
5322 // Add the rest of the message as is, we are done
5323 buf.Write(msg[size:])
5324 return buf.Bytes()
5325 }
5326
5327 // Add timestamp if we did not find one.
5328 writeDeathTimestamp()
5329
5330 return buf.Bytes()
5331 }
5332
5333 // Common function to mqtt delivery callbacks to serialize and send the message
5334 // to the `cc` client.
5335 func (c *client) mqttEnqueuePublishMsgTo(cc *client, sub *subscription, pi uint16, qos byte, dup bool, topic, msg []byte) {
5336 // [tck-id-conformance-mqtt-aware-nbirth-mqtt-retain] A Sparkplug Aware
5337 // MQTT Server MUST make NBIRTH messages available on the topic:
5338 // $sparkplug/certificates/namespace/group_id/NBIRTH/edge_node_id with
5339 // the MQTT retain flag set to true
5340 //
5341 // [tck-id-conformance-mqtt-aware-dbirth-mqtt-retain] A Sparkplug Aware
5342 // MQTT Server MUST make DBIRTH messages available on the topic:
5343 // $sparkplug/certificates/namespace/group_id/DBIRTH/edge_node_id/device_id
5344 // with the MQTT retain flag set to true
5345 //
5346 // $sparkplug/certificates messages are sent as NATS messages, so we
5347 // need to add the retain flag when sending them to MQTT clients.
5348
5349 retain := false
5350 isBirth, isDeath, isCertificate := sparkbParseBirthDeathTopic(topic)
5351 if isBirth && qos == 0 {
5352 retain = isCertificate
5353 } else if isDeath && !isCertificate {
5354 msg = sparkbReplaceDeathTimestamp(msg)
5355 }
5356
5357 flags, headerBytes := mqttMakePublishHeader(pi, qos, dup, retain, topic, len(msg))
5358
5359 cc.mu.Lock()
5360 if sub.mqtt.prm != nil {
5361 for _, data := range sub.mqtt.prm {
5362 cc.queueOutbound(data)
5363 }
5364 sub.mqtt.prm = nil
5365 }
5366 cc.queueOutbound(headerBytes)
5367 cc.queueOutbound(msg)
5368 c.addToPCD(cc)
5369 trace := cc.trace
5370 cc.mu.Unlock()
5371
5372 if trace {
5373 pp := mqttPublish{
5374 topic: topic,
5375 flags: flags,
5376 pi: pi,
5377 sz: len(msg),
5378 }
5379 cc.traceOutOp("PUBLISH", []byte(mqttPubTrace(&pp)))
5380 }
5381 }
5382
5383 // Serializes to the given writer the message for the given subject.
5384 func (w *mqttWriter) WritePublishHeader(pi uint16, qos byte, dup, retained bool, topic []byte, msgLen int) byte {
5385 // Compute len (will have to add packet id if message is sent as QoS>=1)
5386 pkLen := 2 + len(topic) + msgLen
5387 var flags byte
5388
5389 // Set flags for dup/retained/qos1
5390 if dup {
5391 flags |= mqttPubFlagDup
5392 }
5393 if retained {
5394 flags |= mqttPubFlagRetain
5395 }
5396 if qos > 0 {
5397 pkLen += 2
5398 flags |= qos << 1
5399 }
5400
5401 w.WriteByte(mqttPacketPub | flags)
5402 w.WriteVarInt(pkLen)
5403 w.WriteBytes(topic)
5404 if qos > 0 {
5405 w.WriteUint16(pi)
5406 }
5407
5408 return flags
5409 }
5410
5411 // Serializes to the given writer the message for the given subject.
5412 func mqttMakePublishHeader(pi uint16, qos byte, dup, retained bool, topic []byte, msgLen int) (byte, []byte) {
5413 headerBuf := newMQTTWriter(mqttInitialPubHeader + len(topic))
5414 flags := headerBuf.WritePublishHeader(pi, qos, dup, retained, topic, msgLen)
5415 return flags, headerBuf.Bytes()
5416 }
5417
5418 // Process the SUBSCRIBE packet.
5419 //
5420 // Process the list of subscriptions and update the given filter
5421 // with the QoS that has been accepted (or failure).
5422 //
5423 // Spec [MQTT-3.8.4-3] says that if an exact same subscription is
5424 // found, it needs to be replaced with the new one (possibly updating
5425 // the qos) and that the flow of publications must not be interrupted,
5426 // which I read as the replacement cannot be a "remove then add" if there
5427 // is a chance that in between the 2 actions, published messages
5428 // would be "lost" because there would not be any matching subscription.
5429 //
5430 // Run from client's readLoop.
5431 // No lock held on entry.
5432 func (c *client) mqttProcessSubs(filters []*mqttFilter) ([]*subscription, error) {
5433 // Those things are immutable, but since processing subs is not
5434 // really in the fast path, let's get them under the client lock.
5435 c.mu.Lock()
5436 asm := c.mqtt.asm
5437 sess := c.mqtt.sess
5438 trace := c.trace
5439 c.mu.Unlock()
5440
5441 if err := asm.lockSession(sess, c); err != nil {
5442 return nil, err
5443 }
5444 defer asm.unlockSession(sess)
5445 return asm.processSubs(sess, c, filters, true, trace)
5446 }
5447
5448 // Cleanup that is performed in processSubs if there was an error.
5449 //
5450 // Runs from client's readLoop.
5451 // Lock not held on entry, but session is in the locked map.
5452 func (sess *mqttSession) cleanupFailedSub(c *client, sub *subscription, cc *ConsumerConfig, jssub *subscription) {
5453 if sub != nil {
5454 c.processUnsub(sub.sid)
5455 }
5456 if jssub != nil {
5457 c.processUnsub(jssub.sid)
5458 }
5459 if cc != nil {
5460 sess.deleteConsumer(cc)
5461 }
5462 }
5463
5464 // Make sure we are set up to deliver PUBREL messages to this QoS2-subscribed
5465 // session.
5466 func (sess *mqttSession) ensurePubRelConsumerSubscription(c *client) error {
5467
5468 sess.mu.Lock()
5469 pubRelSubscribed := sess.pubRelSubscribed
5470 pubRelDeliverySubjectB := sess.pubRelDeliverySubjectB
5471 pubRelDeliverySubject := sess.pubRelDeliverySubject
5472 pubRelConsumer := sess.pubRelConsumer
5473 sess.mu.Unlock()
5474
5475 // Subscribe before the consumer is created so we don't loose any messages.
5476 if !pubRelSubscribed {
5477 _, err := c.processSub(pubRelDeliverySubjectB, nil, pubRelDeliverySubjectB, mqttDeliverPubRelCb, false)
5478 if err != nil {
5479 c.Errorf("Unable to create subscription for JetStream consumer on %q: %v", pubRelDeliverySubject, err)
5480 return err
5481 }
5482 sess.mu.Lock()
5483 sess.pubRelSubscribed = true
5484 sess.mu.Unlock()
5485 }
5486
5487 // If the JS consumer already exists, we are done.
5488 if pubRelConsumer != nil {
5489 return nil
5490 }
5491
5492 opts := c.srv.getOpts()
5493 ackWait := opts.MQTT.AckWait
5494 if ackWait == 0 {
5495 ackWait = mqttDefaultAckWait
5496 }
5497 maxAckPending := int(opts.MQTT.MaxAckPending)
5498 if maxAckPending == 0 {
5499 maxAckPending = mqttDefaultMaxAckPending
5500 }
5501
5502 sess.mu.Lock()
5503 pubRelSubject := sess.pubRelSubject
5504 tmaxack := sess.tmaxack
5505 idHash := sess.idHash
5506 id := sess.id
5507 sess.mu.Unlock()
5508
5509 // Check that the limit of subs' maxAckPending are not going over the limit
5510 if after := tmaxack + maxAckPending; after > mqttMaxAckTotalLimit {
5511 return fmt.Errorf("max_ack_pending for all consumers would be %v which exceeds the limit of %v",
5512 after, mqttMaxAckTotalLimit)
5513 }
5514
5515 ccr := &CreateConsumerRequest{
5516 Stream: mqttOutStreamName,
5517 Config: ConsumerConfig{
5518 DeliverSubject: pubRelDeliverySubject,
5519 Durable: mqttPubRelConsumerDurablePrefix + idHash,
5520 AckPolicy: AckExplicit,
5521 DeliverPolicy: DeliverNew,
5522 FilterSubject: pubRelSubject,
5523 AckWait: ackWait,
5524 MaxAckPending: maxAckPending,
5525 MemoryStorage: opts.MQTT.ConsumerMemoryStorage,
5526 },
5527 }
5528 if opts.MQTT.ConsumerInactiveThreshold > 0 {
5529 ccr.Config.InactiveThreshold = opts.MQTT.ConsumerInactiveThreshold
5530 }
5531 if _, err := sess.jsa.createDurableConsumer(ccr); err != nil {
5532 c.Errorf("Unable to add JetStream consumer for PUBREL for client %q: err=%v", id, err)
5533 return err
5534 }
5535 pubRelConsumer = &ccr.Config
5536 tmaxack += maxAckPending
5537
5538 sess.mu.Lock()
5539 sess.pubRelConsumer = pubRelConsumer
5540 sess.tmaxack = tmaxack
5541 sess.mu.Unlock()
5542
5543 return nil
5544 }
5545
5546 // When invoked with a QoS of 0, looks for an existing JS durable consumer for
5547 // the given sid and if one is found, delete the JS durable consumer and unsub
5548 // the NATS subscription on the delivery subject.
5549 //
5550 // With a QoS > 0, creates or update the existing JS durable consumer along with
5551 // its NATS subscription on a delivery subject.
5552 //
5553 // Session lock is acquired and released as needed. Session is in the locked
5554 // map.
5555 func (sess *mqttSession) processJSConsumer(c *client, subject, sid string,
5556 qos byte, fromSubProto bool) (*ConsumerConfig, *subscription, error) {
5557
5558 sess.mu.Lock()
5559 cc, exists := sess.cons[sid]
5560 tmaxack := sess.tmaxack
5561 idHash := sess.idHash
5562 sess.mu.Unlock()
5563
5564 // Check if we are already a JS consumer for this SID.
5565 if exists {
5566 // If current QoS is 0, it means that we need to delete the existing
5567 // one (that was QoS > 0)
5568 if qos == 0 {
5569 // The JS durable consumer's delivery subject is on a NUID of
5570 // the form: mqttSubPrefix + <nuid>. It is also used as the sid
5571 // for the NATS subscription, so use that for the lookup.
5572 c.mu.Lock()
5573 sub := c.subs[cc.DeliverSubject]
5574 c.mu.Unlock()
5575
5576 // Delete the consumer entry, mark its delivery subscription closed,
5577 // and purge its pending QoS 1/2 deliveries — all under the session
5578 // lock. Otherwise those packet identifiers leak and count against the
5579 // in-flight cap for the life of the session (as mqttProcessUnsubs
5580 // purges on unsubscribe). deleteConsumer is asynchronous, so an
5581 // in-flight delivery callback could re-populate the maps after the
5582 // purge; marking sub.mqtt.closed (guarded by sess.mu and sess.subsMu,
5583 // same as delivery) makes mqttDeliverMsgCbQoS12 skip instead. The flag
5584 // leaves sub.mqtt valid so an already-committed enqueue does not panic.
5585 sess.mu.Lock()
5586 delete(sess.cons, sid)
5587 if sub != nil && sub.mqtt != nil {
5588 sess.subsMu.Lock()
5589 sub.mqtt.closed = true
5590 sess.subsMu.Unlock()
5591 }
5592 // Also purge this sid's in-flight retained deliveries, tracked
5593 // under a pseudo-durable key (no JS consumer, no redelivery).
5594 for _, dur := range [...]string{cc.Durable, mqttRetainedPendingDur(sid)} {
5595 if seqPis, ok := sess.cpending[dur]; ok {
5596 delete(sess.cpending, dur)
5597 for _, pi := range seqPis {
5598 delete(sess.pendingPublish, pi)
5599 }
5600 }
5601 }
5602 sess.mu.Unlock()
5603
5604 sess.deleteConsumer(cc)
5605 if sub != nil {
5606 c.processUnsub(sub.sid)
5607 }
5608 return nil, nil, nil
5609 }
5610 // If this is called when processing SUBSCRIBE protocol, then if
5611 // the JS consumer already exists, we are done (it was created
5612 // during the processing of CONNECT).
5613 if fromSubProto {
5614 return nil, nil, nil
5615 }
5616 }
5617 // Here it means we don't have a JS consumer and if we are QoS 0,
5618 // we have nothing to do.
5619 if qos == 0 {
5620 return nil, nil, nil
5621 }
5622 var err error
5623 var inbox string
5624 if exists {
5625 inbox = cc.DeliverSubject
5626 } else {
5627 inbox = mqttSubPrefix + nuid.Next()
5628 opts := c.srv.getOpts()
5629 ackWait := opts.MQTT.AckWait
5630 if ackWait == 0 {
5631 ackWait = mqttDefaultAckWait
5632 }
5633 maxAckPending := int(opts.MQTT.MaxAckPending)
5634 if maxAckPending == 0 {
5635 maxAckPending = mqttDefaultMaxAckPending
5636 }
5637
5638 // Check that the limit of subs' maxAckPending are not going over the limit
5639 if after := tmaxack + maxAckPending; after > mqttMaxAckTotalLimit {
5640 return nil, nil, fmt.Errorf("max_ack_pending for all consumers would be %v which exceeds the limit of %v",
5641 after, mqttMaxAckTotalLimit)
5642 }
5643
5644 durName := idHash + "_" + nuid.Next()
5645 ccr := &CreateConsumerRequest{
5646 Stream: mqttStreamName,
5647 Config: ConsumerConfig{
5648 DeliverSubject: inbox,
5649 Durable: durName,
5650 AckPolicy: AckExplicit,
5651 DeliverPolicy: DeliverNew,
5652 FilterSubject: mqttStreamSubjectPrefix + subject,
5653 AckWait: ackWait,
5654 MaxAckPending: maxAckPending,
5655 MemoryStorage: opts.MQTT.ConsumerMemoryStorage,
5656 },
5657 }
5658 if opts.MQTT.ConsumerInactiveThreshold > 0 {
5659 ccr.Config.InactiveThreshold = opts.MQTT.ConsumerInactiveThreshold
5660 }
5661 if _, err := sess.jsa.createDurableConsumer(ccr); err != nil {
5662 c.Errorf("Unable to add JetStream consumer for subscription on %q: err=%v", subject, err)
5663 return nil, nil, err
5664 }
5665 cc = &ccr.Config
5666 tmaxack += maxAckPending
5667 }
5668
5669 // This is an internal subscription on subject like "$MQTT.sub.<nuid>" that is setup
5670 // for the JS durable's deliver subject.
5671 sess.mu.Lock()
5672 sess.tmaxack = tmaxack
5673 sub, err := sess.processQOS12Sub(c, []byte(inbox), []byte(inbox),
5674 isMQTTReservedSubscription(subject), qos, cc.Durable, mqttDeliverMsgCbQoS12)
5675 sess.mu.Unlock()
5676
5677 if err != nil {
5678 sess.deleteConsumer(cc)
5679 c.Errorf("Unable to create subscription for JetStream consumer on %q: %v", subject, err)
5680 return nil, nil, err
5681 }
5682 return cc, sub, nil
5683 }
5684
5685 // Queues the published retained messages for each subscription and signals
5686 // the writeLoop.
5687 func (c *client) mqttSendRetainedMsgsToNewSubs(subs []*subscription) {
5688 c.mu.Lock()
5689 for _, sub := range subs {
5690 if sub.mqtt != nil && sub.mqtt.prm != nil {
5691 for _, data := range sub.mqtt.prm {
5692 c.queueOutbound(data)
5693 }
5694 sub.mqtt.prm = nil
5695 }
5696 }
5697 c.flushSignal()
5698 c.mu.Unlock()
5699 }
5700
5701 func (c *client) mqttEnqueueSubAck(pi uint16, filters []*mqttFilter) {
5702 w := newMQTTWriter(7 + len(filters))
5703 w.WriteByte(mqttPacketSubAck)
5704 // packet length is 2 (for packet identifier) and 1 byte per filter.
5705 w.WriteVarInt(2 + len(filters))
5706 w.WriteUint16(pi)
5707 for _, f := range filters {
5708 w.WriteByte(f.qos)
5709 }
5710 c.mu.Lock()
5711 c.enqueueProto(w.Bytes())
5712 c.mu.Unlock()
5713 }
5714
5715 //////////////////////////////////////////////////////////////////////////////
5716 //
5717 // UNSUBSCRIBE related functions
5718 //
5719 //////////////////////////////////////////////////////////////////////////////
5720
5721 func (c *client) mqttParseUnsubs(r *mqttReader, b byte, pl int) (uint16, []*mqttFilter, error) {
5722 return c.mqttParseSubsOrUnsubs(r, b, pl, false)
5723 }
5724
5725 // Process the UNSUBSCRIBE packet.
5726 //
5727 // Given the list of topics, this is going to unsubscribe the low level NATS subscriptions
5728 // and delete the JS durable consumers when applicable.
5729 //
5730 // Runs from the client's readLoop.
5731 // No lock held on entry.
5732 func (c *client) mqttProcessUnsubs(filters []*mqttFilter) error {
5733 // Those things are immutable, but since processing unsubs is not
5734 // really in the fast path, let's get them under the client lock.
5735 c.mu.Lock()
5736 asm := c.mqtt.asm
5737 sess := c.mqtt.sess
5738 c.mu.Unlock()
5739
5740 if err := asm.lockSession(sess, c); err != nil {
5741 return err
5742 }
5743 defer asm.unlockSession(sess)
5744
5745 removeJSCons := func(sid string) {
5746 cc, ok := sess.cons[sid]
5747 if ok {
5748 delete(sess.cons, sid)
5749 sess.deleteConsumer(cc)
5750
5751 c.mu.Lock()
5752 sub := c.subs[cc.DeliverSubject]
5753 c.mu.Unlock()
5754
5755 // Need lock here since these are accessed by callbacks
5756 sess.mu.Lock()
5757 // Mark the delivery sub closed so an in-flight QoS 1/2 callback stops
5758 // tracking new messages after the purge (deleteConsumer is async);
5759 // same barrier as the QoS 0 downgrade path in processJSConsumer.
5760 if sub != nil && sub.mqtt != nil {
5761 sess.subsMu.Lock()
5762 sub.mqtt.closed = true
5763 sess.subsMu.Unlock()
5764 }
5765 // Purge both the consumer's deliveries and this sid's in-flight
5766 // retained deliveries (tracked under a pseudo-durable key).
5767 for _, dur := range [...]string{cc.Durable, mqttRetainedPendingDur(sid)} {
5768 if seqPis, ok := sess.cpending[dur]; ok {
5769 delete(sess.cpending, dur)
5770 for _, pi := range seqPis {
5771 delete(sess.pendingPublish, pi)
5772 }
5773 // last_pi stays monotonic (see untrackPublish); do not reset here.
5774 }
5775 }
5776 sess.mu.Unlock()
5777 }
5778 }
5779 for _, f := range filters {
5780 sid := f.filter
5781 // Remove JS Consumer if one exists for this sid
5782 removeJSCons(sid)
5783 if err := c.processUnsub([]byte(sid)); err != nil {
5784 c.Errorf("error unsubscribing from %q: %v", sid, err)
5785 }
5786 if mqttNeedSubForLevelUp(sid) {
5787 subject := sid[:len(sid)-2]
5788 sid = subject + mqttMultiLevelSidSuffix
5789 removeJSCons(sid)
5790 if err := c.processUnsub([]byte(sid)); err != nil {
5791 c.Errorf("error unsubscribing from %q: %v", subject, err)
5792 }
5793 }
5794 }
5795 return sess.update(filters, false)
5796 }
5797
5798 func (c *client) mqttEnqueueUnsubAck(pi uint16) {
5799 w := newMQTTWriter(4)
5800 w.WriteByte(mqttPacketUnsubAck)
5801 w.WriteVarInt(2)
5802 w.WriteUint16(pi)
5803 c.mu.Lock()
5804 c.enqueueProto(w.Bytes())
5805 c.mu.Unlock()
5806 }
5807
5808 func mqttUnsubscribeTrace(pi uint16, filters []*mqttFilter) string {
5809 var sep string
5810 sb := strings.Builder{}
5811 sb.WriteString("[")
5812 for i, f := range filters {
5813 sb.WriteString(sep)
5814 sb.Write(f.ttopic)
5815 sb.WriteString(" (")
5816 sb.WriteString(f.filter)
5817 sb.WriteString(")")
5818 if i == 0 {
5819 sep = ", "
5820 }
5821 }
5822 sb.WriteString(fmt.Sprintf("] pi=%v", pi))
5823 return sb.String()
5824 }
5825
5826 //////////////////////////////////////////////////////////////////////////////
5827 //
5828 // PINGREQ/PINGRESP related functions
5829 //
5830 //////////////////////////////////////////////////////////////////////////////
5831
5832 func (c *client) mqttEnqueuePingResp() {
5833 c.mu.Lock()
5834 c.enqueueProto(mqttPingResponse)
5835 c.mu.Unlock()
5836 }
5837
5838 //////////////////////////////////////////////////////////////////////////////
5839 //
5840 // Trace functions
5841 //
5842 //////////////////////////////////////////////////////////////////////////////
5843
5844 func errOrTrace(err error, trace string) []byte {
5845 if err != nil {
5846 return []byte(err.Error())
5847 }
5848 return []byte(trace)
5849 }
5850
5851 //////////////////////////////////////////////////////////////////////////////
5852 //
5853 // Subject/Topic conversion functions
5854 //
5855 //////////////////////////////////////////////////////////////////////////////
5856
5857 // Converts an MQTT Topic Name to a NATS Subject (used by PUBLISH)
5858 // See mqttToNATSSubjectConversion() for details.
5859 func mqttTopicToNATSPubSubject(mt []byte) ([]byte, error) {
5860 return mqttToNATSSubjectConversion(mt, false)
5861 }
5862
5863 // Converts an MQTT Topic Filter to a NATS Subject (used by SUBSCRIBE)
5864 // See mqttToNATSSubjectConversion() for details.
5865 func mqttFilterToNATSSubject(filter []byte) ([]byte, error) {
5866 return mqttToNATSSubjectConversion(filter, true)
5867 }
5868
5869 // Converts an MQTT Topic Name or Filter to a NATS Subject.
5870 // In MQTT:
5871 // - a Topic Name does not have wildcard (PUBLISH uses only topic names).
5872 // - a Topic Filter can include wildcards (SUBSCRIBE uses those).
5873 // - '+' and '#' are wildcard characters (single and multiple levels respectively)
5874 // - '/' is the topic level separator.
5875 //
5876 // Conversion that occurs:
5877 // - '/' is replaced with '/.' if it is the first character in mt
5878 // - '/' is replaced with './' if the last or next character in mt is '/'
5879 // For instance, foo//bar would become foo./.bar
5880 // - '/' is replaced with '.' for all other conditions (foo/bar -> foo.bar)
5881 // - '.' is replaced with '//'.
5882 // - ' ' cause an error to be returned.
5883 //
5884 // If there is no need to convert anything (say "foo" remains "foo"), then
5885 // the no memory is allocated and the returned slice is the original `mt`.
5886 func mqttToNATSSubjectConversion(mt []byte, wcOk bool) ([]byte, error) {
5887 var cp bool
5888 var j int
5889 res := mt
5890
5891 makeCopy := func(i int) {
5892 cp = true
5893 res = make([]byte, 0, len(mt)+10)
5894 if i > 0 {
5895 res = append(res, mt[:i]...)
5896 }
5897 }
5898
5899 end := len(mt) - 1
5900 for i := 0; i < len(mt); i++ {
5901 switch mt[i] {
5902 case mqttTopicLevelSep:
5903 if i == 0 || res[j-1] == btsep {
5904 if !cp {
5905 makeCopy(0)
5906 }
5907 res = append(res, mqttTopicLevelSep, btsep)
5908 j++
5909 } else if i == end || mt[i+1] == mqttTopicLevelSep {
5910 if !cp {
5911 makeCopy(i)
5912 }
5913 res = append(res, btsep, mqttTopicLevelSep)
5914 j++
5915 } else {
5916 if !cp {
5917 makeCopy(i)
5918 }
5919 res = append(res, btsep)
5920 }
5921 case ' ', '\t', '\n', '\r', '\f':
5922 // We cannot support whitespace in the MQTT topic/filter — these
5923 // characters would also corrupt the NATS wire protocol when the
5924 // subject is forwarded to other connection types (e.g. leaf
5925 // nodes) where the resulting control line could be split.
5926 return nil, errMQTTUnsupportedCharacters
5927 case 0x7f:
5928 // SubjectTree uses DEL as an internal pivot marker, so retained
5929 // subjects containing it cannot be indexed safely, including
5930 // legacy retained messages recovered from the retained-message
5931 // stream.
5932 return nil, errMQTTUnsupportedCharacters
5933 case btsep:
5934 if !cp {
5935 makeCopy(i)
5936 }
5937 res = append(res, mqttTopicLevelSep, mqttTopicLevelSep)
5938 j++
5939 case mqttSingleLevelWC, mqttMultiLevelWC:
5940 if !wcOk {
5941 // Spec [MQTT-3.3.2-2] and [MQTT-4.7.1-1]
5942 // The wildcard characters can be used in Topic Filters, but MUST NOT be used within a Topic Name
5943 return nil, fmt.Errorf("wildcards not allowed in publish's topic: %q", mt)
5944 }
5945 if !cp {
5946 makeCopy(i)
5947 }
5948 if mt[i] == mqttSingleLevelWC {
5949 res = append(res, pwc)
5950 } else {
5951 res = append(res, fwc)
5952 }
5953 default:
5954 if cp {
5955 res = append(res, mt[i])
5956 }
5957 }
5958 j++
5959 }
5960 if cp && res[j-1] == btsep {
5961 res = append(res, mqttTopicLevelSep)
5962 j++
5963 }
5964 return res[:j], nil
5965 }
5966
5967 // Converts a NATS subject to MQTT topic. This is for publish
5968 // messages only, so there is no checking for wildcards.
5969 // Rules are reversed of mqttToNATSSubjectConversion.
5970 func natsSubjectStrToMQTTTopic(subject string) []byte {
5971 return natsSubjectToMQTTTopic(stringToBytes(subject))
5972 }
5973
5974 func natsSubjectToMQTTTopic(subject []byte) []byte {
5975 topic := make([]byte, len(subject))
5976 end := len(subject) - 1
5977 var j int
5978 for i := 0; i < len(subject); i++ {
5979 switch subject[i] {
5980 case mqttTopicLevelSep:
5981 if i < end {
5982 switch c := subject[i+1]; c {
5983 case btsep, mqttTopicLevelSep:
5984 if c == btsep {
5985 topic[j] = mqttTopicLevelSep
5986 } else {
5987 topic[j] = btsep
5988 }
5989 j++
5990 i++
5991 default:
5992 }
5993 }
5994 case btsep:
5995 topic[j] = mqttTopicLevelSep
5996 j++
5997 default:
5998 topic[j] = subject[i]
5999 j++
6000 }
6001 }
6002 return topic[:j]
6003 }
6004
6005 // Returns true if the subject has more than 1 token and ends with ".>"
6006 func mqttNeedSubForLevelUp(subject string) bool {
6007 if len(subject) < 3 {
6008 return false
6009 }
6010 end := len(subject)
6011 if subject[end-2] == '.' && subject[end-1] == fwc {
6012 return true
6013 }
6014 return false
6015 }
6016
6017 //////////////////////////////////////////////////////////////////////////////
6018 //
6019 // MQTT Reader functions
6020 //
6021 //////////////////////////////////////////////////////////////////////////////
6022
6023 func (r *mqttReader) reset(buf []byte) {
6024 if l := len(r.pbuf); l > 0 {
6025 tmp := make([]byte, l+len(buf))
6026 copy(tmp, r.pbuf)
6027 copy(tmp[l:], buf)
6028 buf = tmp
6029 r.pbuf = nil
6030 }
6031 r.buf = buf
6032 r.pos = 0
6033 r.pstart = 0
6034 }
6035
6036 func (r *mqttReader) hasMore() bool {
6037 return r.pos != len(r.buf)
6038 }
6039
6040 func (r *mqttReader) readByte(field string) (byte, error) {
6041 if r.pos == len(r.buf) {
6042 return 0, fmt.Errorf("error reading %s: %v", field, io.EOF)
6043 }
6044 b := r.buf[r.pos]
6045 r.pos++
6046 return b, nil
6047 }
6048
6049 func (r *mqttReader) readPacketLen(maxLen int32) (int, bool, error) {
6050 v, complete, err := r.readVarInt()
6051 if err != nil {
6052 return 0, false, err
6053 }
6054 if complete {
6055 packetEnd := r.pos + v
6056 packetLen := packetEnd - r.pstart
6057 if maxLen != jwt.NoLimit && int64(packetLen) > int64(maxLen) {
6058 return packetLen, false, ErrMaxPayload
6059 }
6060 if packetEnd <= len(r.buf) {
6061 return v, true, nil
6062 }
6063 }
6064 r.pbuf = make([]byte, len(r.buf)-r.pstart)
6065 copy(r.pbuf, r.buf[r.pstart:])
6066 return 0, false, nil
6067 }
6068
6069 func (r *mqttReader) readVarInt() (int, bool, error) {
6070 m := 1
6071 v := 0
6072 for {
6073 var b byte
6074 if r.pos != len(r.buf) {
6075 b = r.buf[r.pos]
6076 r.pos++
6077 } else {
6078 break
6079 }
6080 v += int(b&0x7f) * m
6081 if (b & 0x80) == 0 {
6082 return v, true, nil
6083 }
6084 m *= 0x80
6085 if m > 0x200000 {
6086 return 0, false, errMQTTMalformedVarInt
6087 }
6088 }
6089 return 0, false, nil
6090 }
6091
6092 func (r *mqttReader) readString(field string) (string, error) {
6093 var s string
6094 bs, err := r.readBytes(field, false)
6095 if err == nil {
6096 s = string(bs)
6097 }
6098 return s, err
6099 }
6100
6101 func (r *mqttReader) readBytes(field string, cp bool) ([]byte, error) {
6102 luint, err := r.readUint16(field)
6103 if err != nil {
6104 return nil, err
6105 }
6106 l := int(luint)
6107 if l == 0 {
6108 return nil, nil
6109 }
6110 start := r.pos
6111 if start+l > len(r.buf) {
6112 return nil, fmt.Errorf("error reading %s: %v", field, io.ErrUnexpectedEOF)
6113 }
6114 r.pos += l
6115 b := r.buf[start:r.pos]
6116 if cp {
6117 b = copyBytes(b)
6118 }
6119 return b, nil
6120 }
6121
6122 func (r *mqttReader) readUint16(field string) (uint16, error) {
6123 if len(r.buf)-r.pos < 2 {
6124 return 0, fmt.Errorf("error reading %s: %v", field, io.ErrUnexpectedEOF)
6125 }
6126 start := r.pos
6127 r.pos += 2
6128 return binary.BigEndian.Uint16(r.buf[start:r.pos]), nil
6129 }
6130
6131 //////////////////////////////////////////////////////////////////////////////
6132 //
6133 // MQTT Writer functions
6134 //
6135 //////////////////////////////////////////////////////////////////////////////
6136
6137 func (w *mqttWriter) WriteUint16(i uint16) {
6138 w.WriteByte(byte(i >> 8))
6139 w.WriteByte(byte(i))
6140 }
6141
6142 func (w *mqttWriter) WriteString(s string) {
6143 w.WriteBytes([]byte(s))
6144 }
6145
6146 func (w *mqttWriter) WriteBytes(bs []byte) {
6147 w.WriteUint16(uint16(len(bs)))
6148 w.Write(bs)
6149 }
6150
6151 func (w *mqttWriter) WriteVarInt(value int) {
6152 for {
6153 b := byte(value & 0x7f)
6154 value >>= 7
6155 if value > 0 {
6156 b |= 0x80
6157 }
6158 w.WriteByte(b)
6159 if value == 0 {
6160 break
6161 }
6162 }
6163 }
6164
6165 func newMQTTWriter(cap int) *mqttWriter {
6166 w := &mqttWriter{}
6167 w.Grow(cap)
6168 return w
6169 }