Debian Codegraph @

paho/session/state/state.go

raw
1 /*
2 * Copyright (c) 2024 Contributors to the Eclipse Foundation
3 *
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v2.0
6 * and Eclipse Distribution License v1.0 which accompany this distribution.
7 *
8 * The Eclipse Public License is available at
9 * https://www.eclipse.org/legal/epl-2.0/
10 * and the Eclipse Distribution License is available at
11 * http://www.eclipse.org/org/documents/edl-v10.php.
12 *
13 * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
14 */
15
16 package state
17
18 import (
19 "context"
20 "errors"
21 "fmt"
22 "io"
23 "sync"
24 "time"
25
26 "github.com/eclipse/paho.golang/packets"
27 paholog "github.com/eclipse/paho.golang/paho/log"
28 "github.com/eclipse/paho.golang/paho/session"
29 "github.com/eclipse/paho.golang/paho/store/memory"
30 )
31
32 // The Session State, as per the MQTT spec, contains:
33 //
34 // > QoS 1 and QoS 2 messages which have been sent to the Server, but have not been completely acknowledged.
35 // > QoS 2 messages which have been received from the Server, but have not been completely acknowledged.
36 //
37 // and, importantly, is used when resending as follows:
38 //
39 // > When a Client reconnects with Clean Start set to 0 and a session is present, both the Client and Server MUST resend
40 // > any unacknowledged PUBLISH packets (where QoS > 0) and PUBREL packets using their original Packet Identifiers. This
41 // > is the only circumstance where a Client or Server is REQUIRED to resend messages. Clients and Servers MUST NOT
42 // > resend messages at any other time
43 //
44 // There are a few other areas where the State is important:
45 // * When allocating a new packet identifier we need to know what Id's are already in the session state.
46 // * If a QOS2 Publish with `DUP=TRUE` is received then we should not pass it to the client if we have previously
47 // sent a `PUBREC` (indicating that the message has already been processed).
48 // * Some subscribers may need a transaction (i.e. commit transaction when `PUBREL` received), this is not implemented
49 // here, but the option is left open.
50 //
51 // This means that the following information may need to be retained after the connection is lost:
52 // * The IDs of any transactions initiated by the client (so that we don't reuse IDs and can notify the requester (if
53 // known) when a response is received or the request is removed from the state).
54 // * For client initiated publish:
55 // * Outgoing `PUBLISH` packets to allow resend.
56 // * Outgoing `PUBREL` packets to allow resend.
57 // * For server initiated publish:
58 // * Outgoing `PUBREL` packets. The fact that this has been sent indicates that the user app has acknowledged the
59 // message, and it should not be re-presented (doing so would breach the "exactly once" requirement).
60 // * In memory only - the fact that a QOS2 PUBLISH has been received and sent to the handler, but not acknowledged.
61 // This allows us to avoid presenting the message a second time (if the application is restarted, we have no option
62 // but to re-present it because we have no way of knowing if the application completed handling it).
63 //
64 // It is important to note that there are packets with identifiers that do not form part of the session state
65 // (SUBSCRIBE, SUBACK, UNSUBSCRIBE, UNSUBACK). Whilst these will never be stored to disk, it is important to track
66 // the packet IDs to ensure we don't reuse them.
67 // For packets relating to client-initiated transactions sent during a `session.State` lifetime we also want to link
68 // a channel to the message ID so that we can notify our user when the transaction is complete (allowing a call to, for
69 // instance `Publish()` to block until the message is fully acknowledged even if we disconnect/reconnect in the interim.
70
71 const (
72 midMin uint16 = 1
73 midMax uint16 = 65535
74 )
75
76 type (
77 // clientGenerated holds information on client-generated packets (e.g. an outgoing SUBSCRIBE request)
78 clientGenerated struct {
79 packetType byte // The type of the last packet sent (i.e. PUBLISH, SUBSCRIBE or UNSUBSCRIBE) - 0 means unknown until loaded from the store
80
81 // When a message is fully acknowledged, we need to let the requester know by sending the final response to this
82 // channel. One and only one message will be sent (the channel will then be closed to ensure this!).
83 // We also guarantee to always send to the channel (assuming there is a clean shutdown) so that the end user knows
84 // the status of the request.
85 responseChan chan<- packets.ControlPacket
86 }
87 )
88
89 // State manages the session state. The client will send messages that may impact the state via
90 // us, and we will maintain the session state
91 type State struct {
92 mu sync.Mutex // protects whole struct (operations should be quick, so the impact of multiple mutexes is likely to be low)
93 connectionLostAt time.Time // Time that the connection was lost
94 sessionExpiryInterval uint32 // The session expiry interval sent with the most recent CONNECT packet
95
96 conn io.Writer // current connection or nil if we are not connected
97 connCtx context.Context // Context will be closed if the connection is lost (only valid when conn != nil)
98 connCtxCancel func() // Cancels the above context
99
100 // client store - holds packets where the message ID was generated on the client (i.e. by paho.golang)
101 clientPackets map[uint16]clientGenerated // Store relating to messages sent TO the server
102 clientStore storer // Used to store session state that survives connection loss
103 lastMid uint16 // The message ID most recently issued
104
105 // server store - holds packets where the message ID was generated on the server
106 serverPackets map[uint16]byte // The last packet received from the server with this ID (cleared when the transaction is complete)
107 serverStore storer // Used to store session state that survives connection loss
108
109 // The number of messages in flight needs to be limited, as per receive maximum received from the server.
110 inflight *sendQuota
111
112 debug paholog.Logger
113 errors paholog.Logger
114 }
115
116 // New creates a new state which will persist information using the passed in storer's.
117 func New(client storer, server storer) *State {
118 return &State{
119 clientStore: client,
120 serverStore: server,
121 debug: paholog.NOOPLogger{},
122 errors: paholog.NOOPLogger{},
123 }
124 }
125
126 // NewInMemory returns a default State that stores all information in memory
127 func NewInMemory() *State {
128 return &State{
129 clientStore: memory.New(),
130 serverStore: memory.New(),
131 debug: paholog.NOOPLogger{},
132 errors: paholog.NOOPLogger{},
133 }
134 }
135
136 // Close closes the session state
137 func (s *State) Close() error {
138 s.mu.Lock()
139 defer s.mu.Unlock()
140 s.connectionLost(nil) // Connection may be up in which case we need to cleanup.
141 for packetID, cg := range s.clientPackets {
142 cg.responseChan <- packets.ControlPacket{} // Default control packet indicates that we are shutting down (TODO: better solution?)
143 delete(s.clientPackets, packetID)
144 }
145 return nil
146 }
147
148 // ConAckReceived will be called when the client receives a CONACK that indicates the connection has been successfully
149 // established. This indicates that a new connection is live and the passed in connection should be used going forward.
150 // It is also the trigger to resend any queued messages. Note that this function should not be called concurrently with
151 // others (we should not begin sending/receiving packets until after the CONACK has been processed).
152 // TODO: Add errors() function so we can notify the client of errors whilst transmitting the session stuff?
153 func (s *State) ConAckReceived(conn io.Writer, cp *packets.Connect, ca *packets.Connack) error {
154 // We could use cp.Properties.SessionExpiryInterval / ca.Properties.SessionExpiryInterval to clear the session
155 // after the specified time period (if the Session Expiry Interval is absent the value in the CONNECT Packet used)
156 // however, this is not something the generic client can really accomplish (forks may wish to do this!).
157 s.mu.Lock()
158 defer s.mu.Unlock()
159 if s.conn != nil {
160 s.errors.Println("ConAckReceived called whilst connection active (you MUST call ConnectionLost before starting a new connection")
161 _ = s.connectionLost(nil) // assume the connection dropped
162 }
163 s.conn = conn
164 s.connCtx, s.connCtxCancel = context.WithCancel(context.Background())
165
166 // If the Server accepts a connection with Clean Start set to 1, the Server MUST set Session Present to 0 in the
167 // CONNACK packet in addition to setting a 0x00 (Success) Reason Code in the CONNACK packet [MQTT-3.2.2-2].
168 // If the Server accepts a connection with Clean Start set to 0 and the Server has Session State for the ClientID,
169 // it MUST set Session Present to 1 in the CONNACK packet, otherwise it MUST set Session Present to 0 in the CONNACK
170 // packet. In both cases, it MUST set a 0x00 (Success) Reason Code in the CONNACK packet [MQTT-3.2.2-3].
171 if !ca.SessionPresent {
172 s.debug.Println("no session present - cleaning session state")
173 s.clean()
174 }
175 inFlight := uint16(len(s.clientPackets))
176 s.debug.Printf("%d inflight transactions upon connection", inFlight)
177
178 // "If the Session Expiry Interval is absent, the Session Expiry Interval in the CONNECT packet is used."
179 // If the Session Expiry Interval is absent the value 0 is used. If it is set to 0, or is absent, the Session ends
180 // when the Network Connection is closed (3.1.2.11.2).
181 if ca.Properties != nil && ca.Properties.SessionExpiryInterval != nil {
182 s.sessionExpiryInterval = *ca.Properties.SessionExpiryInterval
183 } else if cp.Properties != nil && cp.Properties.SessionExpiryInterval != nil {
184 s.sessionExpiryInterval = *cp.Properties.SessionExpiryInterval
185 } else {
186 s.sessionExpiryInterval = 0
187 }
188
189 // If clientPackets already exists, we re-use it so that the responseChan survives the reconnection
190 // the map will be populated/repopulated when we retransmit the messages.
191 if s.clientPackets == nil {
192 s.clientPackets = make(map[uint16]clientGenerated) // This will be populated whilst packets are resent
193 }
194
195 if s.serverPackets == nil {
196 if err := s.loadServerSession(ca); err != nil {
197 return fmt.Errorf("failed to server session: %w", err)
198 }
199 }
200
201 // As per section 4.9 "The send quota and Receive Maximum value are not preserved across Network Connections"
202 recvMax := uint16(65535) // Default as per MQTT spec
203 if ca.Properties != nil && ca.Properties.ReceiveMaximum != nil {
204 recvMax = *ca.Properties.ReceiveMaximum
205 }
206 s.inflight = newSendQuota(recvMax)
207
208 // Now we need to resend any packets in the store; this must happen in order, the simplest approach is to complete
209 // the sending them before returning.
210 toResend, err := s.clientStore.List()
211 if err != nil {
212 return fmt.Errorf("failed to load stored message ids: %w", err)
213 }
214 s.debug.Printf("retransmitting %d messages", len(toResend))
215 for _, id := range toResend {
216 s.debug.Printf("resending message ID %d", id)
217 r, err := s.clientStore.Get(id)
218 if err != nil {
219 s.errors.Printf("failed to load packet %d from client store: %s", id, err)
220 continue
221 }
222
223 // DUP needs to be set when resending PUBLISH
224 // Read/parse the full packet, so we can detect corruption (e.g. 0 byte file)
225 p, err := packets.ReadPacket(r)
226 if cErr := r.Close(); cErr != nil {
227 s.errors.Printf("failed to close stored client packet %d: %s", id, cErr)
228 }
229 if err != nil { // If the packet cannot be read, we quarantine it; otherwise we may retry infinitely.
230 if err := s.clientStore.Quarantine(id); err != nil {
231 s.errors.Printf("failed to quarantine packet %d from client store: %s", id, err)
232 }
233 s.errors.Printf("failed to retrieve/parse packet %d from client store: %s", id, err)
234 continue
235 }
236
237 switch p.Type {
238 case packets.PUBLISH:
239 pub := p.Content.(*packets.Publish)
240 pub.Duplicate = true
241 case packets.PUBREL:
242 default:
243 if err := s.clientStore.Quarantine(id); err != nil {
244 s.errors.Printf("failed to quarantine packet %d from client store: %s", id, err)
245 }
246 s.errors.Printf("unexpected packet type %d (for packet identifier %d) in client store", p.Type, id)
247 continue
248 }
249
250 // The messages being retransmitted form part of the "send quota"; however, as per the V5 spec,
251 // the limit does not apply to messages being resent (the quota can go under 0)
252 s.inflight.Retransmit() // This will never block (but is needed to block new messages)
253
254 // Any failure from this point should result in loss of connection (so fatal)
255 if _, err := p.WriteTo(conn); err != nil {
256 s.debug.Printf("retransmitting of identifier %d failed: %s", id, err)
257 return fmt.Errorf("failed to retransmit message (%d): %w", id, err)
258 }
259 s.debug.Printf("retransmitted message with identifier %d", id)
260 // On initial connection, the packet needs to be added to our record of client-generated packets.
261 if _, ok := s.clientPackets[id]; !ok {
262 s.clientPackets[id] = clientGenerated{
263 packetType: p.Type,
264 responseChan: make(chan packets.ControlPacket, 1), // Nothing will wait on this
265 }
266 }
267 }
268 return nil
269 }
270
271 // loadServerSession should be called once, when the first connection is established.
272 // It loads the server session state from the store.
273 // The caller must hold a lock on s.mu
274 func (s *State) loadServerSession(ca *packets.Connack) error {
275 s.serverPackets = make(map[uint16]byte)
276 ids, err := s.serverStore.List()
277 if err != nil {
278 return fmt.Errorf("failed to load stored server message ids: %w", err)
279 }
280 for _, id := range ids {
281 r, err := s.serverStore.Get(id)
282 if err != nil {
283 s.errors.Printf("failed to load packet %d from server store: %s", id, err)
284 continue
285 }
286 // We only need to know the packet type so there is no need to process the entire packet
287 byte1 := make([]byte, 1)
288 _, err = r.Read(byte1)
289 _ = r.Close()
290 if err != nil {
291 if err := s.serverStore.Quarantine(id); err != nil {
292 s.errors.Printf("failed to quarantine packet %d from server store (failed to read): %s", id, err)
293 }
294 s.errors.Printf("packet %d from server store could not be read: %s", id, err)
295 continue // don't want to fail so quarantine and continue is the best we can do
296 }
297 packetType := byte1[0] >> 4
298 switch packetType {
299 case packets.PUBLISH:
300 s.serverPackets[id] = packets.PUBLISH
301 case packets.PUBREC:
302 s.serverPackets[id] = packets.PUBREC
303 default:
304 if err := s.serverStore.Quarantine(id); err != nil {
305 s.errors.Printf("failed to quarantine packet %d from server store: %s", id, err)
306 }
307 s.errors.Printf("packet %d from server store had unexpected type %d", id, packetType)
308 continue // don't want to fail so quarantine and continue is the best we can do
309 }
310 }
311 return nil
312 }
313
314 // ConnectionLost will be called when the connection is lost; either because we received a DISCONNECT packet or due
315 // to a network error (`nil` will be passed in)
316 func (s *State) ConnectionLost(dp *packets.Disconnect) error {
317 s.mu.Lock()
318 defer s.mu.Unlock()
319 return s.connectionLost(dp)
320 }
321
322 // connectionLost process loss of connection
323 // Caller MUST have locked c.Mu
324 func (s *State) connectionLost(dp *packets.Disconnect) error {
325 if s.conn == nil {
326 return nil // ConnectionLost may be called multiple times (but call ref Disconnect packet should be first)
327 }
328 s.connCtxCancel()
329 s.conn, s.connCtx, s.connCtxCancel = nil, nil, nil
330 s.connectionLostAt = time.Now()
331
332 if dp != nil && dp.Properties != nil && dp.Properties.SessionExpiryInterval != nil {
333 s.sessionExpiryInterval = *dp.Properties.SessionExpiryInterval
334 }
335 // The Client and Server MUST store the Session State after the Network Connection is closed if the Session Expiry
336 // Interval is greater than 0 [MQTT-3.1.2-23]
337 if s.sessionExpiryInterval == 0 {
338 s.debug.Println("sessionExpiryInterval is 0 and connection lost - cleaning session state")
339 s.clean()
340 }
341 return nil
342 }
343
344 // AddToSession adds a packet to the session state (including allocation of a Message Identifier).
345 // If this function returns a nil then:
346 // - A slot has been allocated if the packet is a PUBLISH (function will block if RECEIVE MAXIMUM messages are inflight)
347 // - A message Identifier has been added to the passed in packet
348 // - Publish messages will have been written to the store (and will be automatically transmitted if a new connection
349 // is established before the message is fully acknowledged - subject to state rules in the MQTTv5 spec)
350 // - Something will be sent to `resp` when either the message is fully acknowledged or the packet is removed from
351 // the session (in which case nil will be sent).
352 //
353 // If the function returns an error, then any actions taken will be rewound prior to return.
354 func (s *State) AddToSession(ctx context.Context, packet session.Packet, resp chan<- packets.ControlPacket) error {
355 ctx, cancel := context.WithCancel(ctx)
356 defer cancel()
357 s.mu.Lock() // There may be a delay waiting for semaphore so check for connection before and after
358 if s.conn == nil {
359 s.mu.Unlock()
360 return session.ErrNoConnection
361 }
362 // If the connection is lost whilst we are waiting, then in Acquire should terminate.
363 connCtx := s.connCtx
364 s.mu.Unlock()
365
366 // If the connection drops while waiting we should abort
367 go func() {
368 select {
369 case <-connCtx.Done():
370 cancel()
371 case <-ctx.Done():
372 }
373 }()
374
375 pt := packet.Type()
376
377 // Ensure only "RECEIVE MAXIMUM" PUBLISH transactions are in flight at any time
378 if pt == packets.PUBLISH {
379 if err := s.inflight.Acquire(ctx); err != nil {
380 if connCtx.Err() != nil {
381 return session.ErrNoConnection
382 }
383 return err // Allow user to confirm if it was their context that led to termination
384 }
385 }
386
387 // We have a slot, so acquire a Message ID
388 // Need to look at what to do if this fails. Should be infrequent as:
389 // its a lot of messages
390 // receive max often defaults to a fairly low value
391 // Maximum recieve max is 65535 which matches the number of slots (so would also need a SUB/UNSUB in flight).
392 packetID, err := s.allocateNextPacketId(pt, resp)
393 if err != nil {
394 if pt == packets.PUBLISH {
395 if qErr := s.inflight.Release(); qErr != nil {
396 s.errors.Printf("quota release due to packet id issue: %s", qErr)
397 }
398 }
399 return err
400 }
401 packet.SetIdentifier(packetID)
402 if pt == packets.PUBLISH {
403 if err = s.clientStore.Put(packetID, pt, packet); err != nil {
404 s.mu.Lock()
405 delete(s.clientPackets, packetID)
406 s.mu.Unlock()
407 if qErr := s.inflight.Release(); qErr != nil {
408 s.errors.Printf("quota release due to store issue: %s", qErr)
409 }
410 packet.SetIdentifier(0) // ensure the Message identifier is not used
411 return err
412 }
413 }
414 return nil
415 }
416
417 // endClientGenerated should be called when a client-generated transaction has been fully acknowledged
418 // (or if, due to connection loss, it will never be acknowledged).
419 func (s *State) endClientGenerated(packetID uint16, recv *packets.ControlPacket) error {
420 s.mu.Lock()
421 defer s.mu.Unlock()
422 if cg, ok := s.clientPackets[packetID]; ok {
423 cg.responseChan <- *recv
424 delete(s.clientPackets, packetID)
425 // Outgoing publish messages will be in the store (replaced with PUBREL that is sent)
426 if cg.packetType == packets.PUBLISH || cg.packetType == packets.PUBREL {
427 if qErr := s.inflight.Release(); qErr != nil {
428 s.errors.Printf("quota release due to %s: %s", recv.PacketType(), qErr)
429 }
430 if err := s.clientStore.Delete(packetID); err != nil {
431 s.errors.Printf("failed to remove message %d from store: %s", packetID, err)
432 }
433 }
434 } else {
435 s.debug.Println("received a response for a message ID we don't know:", recv.PacketID())
436 }
437 return nil // TODO: Should we return errors here (not much that could be done with them)
438 }
439
440 // Ack is called when the client message handlers have completed (or, if manual acknowledgements are enabled, when
441 // `client.ACK()` has been called - this may happen some time after the message was received and it is conceivable that
442 // the connection may have been dropped and reestablished in the interim).
443 // See issue 160 re issues when the State is called after the connection is dropped. We assume that the
444 // user will ensure that all ACK's are completed before the State is applied to a new connection (not doing
445 // this may have unpredictable results).
446 func (s *State) Ack(pb *packets.Publish) error {
447 return s.ack(pb)
448 }
449
450 // ack sends an acknowledgment of the `PUBLISH` (which will have been received from the server)
451 // `s.mu` must NOT be locked when this is called.
452 // Note: Adding properties to the response is not currently supported. If this functionality is added, then it is
453 // important to note that QOS2 PUBREC's may be resent if a duplicate `PUBLISH` is received.
454 // This function will only return comms related errors (so caller can assume connection has been lost).
455 func (s *State) ack(pb *packets.Publish) error {
456 s.mu.Lock()
457 defer s.mu.Unlock()
458 var err error
459 switch pb.QoS {
460 case 1:
461 pa := packets.Puback{
462 Properties: &packets.Properties{},
463 PacketID: pb.PacketID,
464 }
465 if s.conn != nil {
466 s.debug.Println("sending PUBACK")
467 _, err = pa.WriteTo(s.conn)
468 if err != nil {
469 s.errors.Printf("failed to send PUBACK for %d: %s", pb.PacketID, err)
470 }
471 } else {
472 s.debug.Println("PUBACK not send because connection down")
473 }
474 // We don't store outbound PUBACK. The server will retransmit the PUBLISH if the connection is reestablished
475 // before it receives the ACK. Unfortunately, there is no definitive way to determine if
476 // such messages are duplicates or not (so we are forced to treat them all as if they are new).
477 case 2:
478 pr := packets.Pubrec{
479 Properties: &packets.Properties{},
480 PacketID: pb.PacketID,
481 }
482 if s.conn != nil {
483 s.debug.Printf("sending PUBREC")
484 _, err = pr.WriteTo(s.conn)
485 if err != nil {
486 s.errors.Printf("failed to send PUBREC for %d: %s", pb.PacketID, err)
487 }
488 } else {
489 s.debug.Println("PUBREC not send because connection down")
490 }
491
492 // We need to record the fact that a PUBREC has been sent so we can detect receipt of a duplicate `PUBLISH`
493 // (which should not be passed to the client app)
494 cp := pr.ToControlPacket()
495 s.serverStore.Put(pb.PacketID, packets.PUBREC, cp)
496 s.serverPackets[pb.PacketID] = cp.Type
497 default:
498 err = errors.New("ack called but publish not QOS 1 or 2")
499 }
500 return err
501 }
502
503 // PacketReceived should be called whenever one of the following is received:
504 // `PUBLISH` (QOS1+ only), `PUBACK`, `PUBREC`, `PUBREL`, `PUBCOMP`, `SUBACK`, `UNSUBACK`
505 // It will handle sending any neccessary response or passing the message to the client.
506 // pubChan will be sent a `PUBLISH` if applicable (and a receiver must be active whilst this function runs)
507 func (s *State) PacketReceived(recv *packets.ControlPacket, pubChan chan<- *packets.Publish) error {
508 // Note: we do a type switch rather than using the packet type because it's safer and easier to understand
509 switch rp := recv.Content.(type) {
510 //
511 // Packets in response to client-generated transactions
512 //
513 case *packets.Suback: // Not in store, just need to advise client and free Message Identifier
514 s.debug.Println("received SUBACK packet with id ", rp.PacketID)
515 s.endClientGenerated(rp.PacketID, recv)
516 return nil
517 case *packets.Unsuback: // Not in store, just need to advise client and free Message Identifier
518 s.debug.Println("received UNSUBACK packet with id ", rp.PacketID)
519 s.endClientGenerated(rp.PacketID, recv)
520 return nil
521 case *packets.Puback: // QOS 1 initial (and final) response
522 s.debug.Println("received PUBACK packet with id ", rp.PacketID)
523 s.endClientGenerated(rp.PacketID, recv)
524 return nil
525 case *packets.Pubrec: // Initial response to a QOS2 Publish
526 s.debug.Println("received PUBREC packet with id ", rp.PacketID)
527 s.mu.Lock()
528 _, ok := s.clientPackets[rp.PacketID]
529 s.mu.Unlock()
530 if !ok {
531 pl := packets.Pubrel{ // Respond with "Packet Identifier not found"
532 PacketID: recv.Content.(*packets.Pubrec).PacketID,
533 ReasonCode: 0x92,
534 }
535 s.debug.Println("sending PUBREL (unknown ID) for ", pl.PacketID)
536 _, err := pl.WriteTo(s.conn)
537 if err != nil {
538 s.errors.Printf("failed to send PUBREL for %d: %s", pl.PacketID, err)
539 }
540 } else {
541 if rp.ReasonCode >= 0x80 {
542 s.endClientGenerated(rp.PacketID, recv)
543 } else {
544 pl := packets.Pubrel{
545 PacketID: rp.PacketID,
546 }
547 s.debug.Println("sending PUBREL for", rp.PacketID)
548 // Update the store (we should never resend the PUBLISH after receiving a PUBREL)
549 if err := s.clientStore.Put(rp.PacketID, packets.PUBREL, &pl); err != nil {
550 s.errors.Printf("failed to write PUBREL to store for %d: %s", rp.PacketID, err)
551 }
552 if _, err := pl.WriteTo(s.conn); err != nil {
553 s.errors.Printf("failed to send PUBREL for %d: %s", rp.PacketID, err)
554 }
555 }
556 }
557 return nil
558 case *packets.Pubcomp: // QOS 2 final response
559 s.debug.Printf("received PUBCOMP packet with id %d", rp.PacketID)
560 s.endClientGenerated(rp.PacketID, recv)
561 return nil
562 //
563 // Packets relating to server generated PUBLISH
564 //
565 case *packets.Publish:
566 s.debug.Printf("received QoS%d PUBLISH", rp.QoS)
567 // There is no need to store the packet because it will be resent if not acknowledged before the connection is
568 // reestablished.
569 if rp.QoS > 0 {
570 if rp.PacketID == 0 { // Invalid
571 return fmt.Errorf("received QOS %d PUBLISH with 0 PacketID", rp.QoS)
572 }
573 if rp.QoS == 2 {
574 s.mu.Lock()
575 if lastSent, ok := s.serverPackets[rp.PacketID]; ok {
576 // If we have sent a PUBREC, that means that the client has already seen this message, so we can
577 // simply resend the acknowledgment.
578 if lastSent == packets.PUBREC {
579 // If the message is not flagged as a duplicate, then something is wrong; to avoid message loss,
580 // we will treat this as a new message (because it appears there is a session mismatch, and we
581 // have not actually seen this message).
582 if rp.Duplicate {
583 // The client has already seen this message meaning we do not want to resend it and, instead
584 // immediately acknowledge it.
585 s.mu.Unlock() // mu must be unlocked to call ack
586 return s.ack(rp)
587 }
588 s.errors.Printf("received duplicate PUBLISH (%d) but dup flag not set (will assume this overwrites old publish)", rp.PacketID)
589 } else {
590 s.errors.Printf("received PUBLISH (%d) but lastSent type is %d (unexpected!)", lastSent)
591 }
592 }
593 s.mu.Unlock()
594 }
595 }
596 pubChan <- rp // the message will be passed to router (and thus the end user app)
597 return nil
598 case *packets.Pubrel:
599 s.debug.Println("received PUBREL for", recv.PacketID())
600 // Auto respond to pubrels unless failure code
601 pr := recv.Content.(*packets.Pubrel)
602 if pr.ReasonCode >= 0x80 {
603 // Received a failure code meaning the server does not know about the message (so all we can do is to remove
604 // it from our store).
605 s.errors.Printf("received PUBREL with reason code %d ", pr.ReasonCode)
606 return nil
607 } else {
608 pc := packets.Pubcomp{
609 PacketID: pr.PacketID,
610 }
611 s.mu.Lock()
612 defer s.mu.Unlock()
613 s.debug.Println("sending PUBCOMP for", pr.PacketID)
614 var err error
615 if s.conn != nil {
616 _, err = pc.WriteTo(s.conn)
617 if err != nil {
618 s.errors.Printf("failed to send PUBCOMP for %d: %s", pc.PacketID, err)
619 }
620 // Note: If connection is down we do not clear store (because the server will resend PUBREL upon reconnect)
621 delete(s.serverPackets, pr.PacketID)
622 if sErr := s.serverStore.Delete(pr.PacketID); sErr != nil {
623 s.errors.Printf("failed to remove message %d from server store: %s", pr.PacketID, sErr)
624 }
625 }
626 return err
627 }
628 default:
629 s.errors.Printf("State.PacketReceived received unexpected packet: %#v ", rp)
630 return nil
631 }
632 }
633
634 // allocateNextPacketId assigns the next available packet ID
635 // Callers must NOT hold lock on s.mu
636 func (s *State) allocateNextPacketId(forPacketType byte, resp chan<- packets.ControlPacket) (uint16, error) {
637 s.mu.Lock() // There may be a delay waiting for semaphore so check for connection before and after
638 defer s.mu.Unlock()
639
640 cg := clientGenerated{
641 packetType: forPacketType,
642 responseChan: resp,
643 }
644
645 // Scan from lastMid to end of range.
646 for i := s.lastMid + 1; i != 0; i++ {
647 if _, ok := s.clientPackets[i]; ok {
648 continue
649 }
650 s.clientPackets[i] = cg
651 s.lastMid = i
652 return i, nil
653 }
654
655 // Default struct will set s.lastMid=0 meaning we have already scanned all mids
656 if s.lastMid == 0 {
657 s.lastMid = 1
658 return 0, session.ErrPacketIdentifiersExhausted
659 }
660
661 // Scan from start of range to lastMid (use +1 to avoid rolling over when s.lastMid = 65535)
662 for i := uint16(0); i < s.lastMid; i++ {
663 if _, ok := s.clientPackets[i+1]; ok {
664 continue
665 }
666 s.clientPackets[i+1] = cg
667 s.lastMid = i + 1
668 return i + 1, nil
669 }
670 return 0, session.ErrPacketIdentifiersExhausted
671 }
672
673 // clean deletes any existing stored session information
674 // does not touch inflight because this is not part of the session state (so is reset separately)
675 // caller is responsible for locking s.mu
676 func (s *State) clean() {
677 s.debug.Println("State.clean() called")
678 s.serverPackets = make(map[uint16]byte)
679 s.clientPackets = make(map[uint16]clientGenerated)
680
681 s.serverStore.Reset()
682 s.clientStore.Reset()
683 }
684
685 // clean deletes any existing stored session information
686 // as per section 4.1 in the spec; The Session State in the Client consists of:
687 // > · QoS 1 and QoS 2 messages which have been sent to the Server, but have not been completely acknowledged.
688 // > · QoS 2 messages which have been received from the Server, but have not been completely acknowledged.
689 // This means that we keep PUBLISH, PUBREC and PUBREL packets. PUBACK and PUBCOMP will not be stored (the MID
690 // will be free once they have been sent). PUBREC is retained so we can check newly received PUBLISH messages (and
691 // confirm if they have already been processed).
692 // We only resend PUBLISH (where QoS > 0) and PUBREL packets (as per spec section 4.4)
693 // caller is responsible for locking s.mu
694 func (s *State) tidy(trigger *packets.ControlPacket) {
695 s.debug.Println("State.tidy() called")
696 for id, p := range s.serverPackets {
697 switch p {
698 case packets.PUBREC:
699 // For inbound messages, we only retain `PUBREC` messages so that we can determine if a PUBLISH received has
700 // already been processed (the `PUBREL` will be sent when the message has been processed by our user).
701 // The broker will resend any `PUBLISH` and `PUBREL` messages, so there is no need to retain those.
702 default:
703 delete(s.serverPackets, id)
704 s.serverStore.Delete(id)
705 }
706 }
707
708 for id, p := range s.clientPackets {
709 // We only need to remember `PUBLISH` and `PUBREL` messages (both originating from a PUBLISH)
710 if p.packetType != packets.PUBLISH {
711 delete(s.clientPackets, id)
712 s.clientStore.Delete(id)
713 p.responseChan <- packets.ControlPacket{}
714 }
715 }
716 }
717
718 // SetDebugLogger takes an instance of the paho Logger interface
719 // and sets it to be used by the debug log endpoint
720 func (s *State) SetDebugLogger(l paholog.Logger) {
721 s.debug = l
722 }
723
724 // SetErrorLogger takes an instance of the paho Logger interface
725 // and sets it to be used by the error log endpoint
726 func (s *State) SetErrorLogger(l paholog.Logger) {
727 s.errors = l
728 }
729
730 // AllocateClientPacketIDForTest is intended for use in tests only. It allocates a packet ID in the client session state
731 // This feels like a hack but makes it easier to test packet identifier exhaustion
732 func (s *State) AllocateClientPacketIDForTest(packetID uint16, forPacketType byte, resp chan<- packets.ControlPacket) {
733 s.mu.Lock()
734 defer s.mu.Unlock()
735 s.clientPackets[packetID] = clientGenerated{
736 packetType: forPacketType,
737 responseChan: resp,
738 }
739 }