Message Expiry Interval deletes a QoS 2 exchange that has already passed PUBREC, so the owed PUBREL is never resent
Summary
Hello, our team @AIS2Lab found that a Message Expiry Interval deletes a QoS 2 exchange that has
already begun, so the PUBREL the broker owes is never resent when the session is resumed.
A QoS 2 message published with a Message Expiry Interval is delivered to a subscriber, the
subscriber answers PUBREC, and the connection is then cut. After the expiry interval passes, the
session is resumed and the PUBREL the broker owes is never sent. The same cut on a message
published without a Message Expiry Interval recovers correctly, which isolates the expiry as the
cause.
Specification
Section 3.3.2.3.3 scopes the Message Expiry Interval to an Application Message the Server is holding:
The PUBLISH packet sent to a Client by the Server MUST contain a Message Expiry Interval set to the received value minus the time that the Application Message has been waiting in the Server
Once PUBREC has been answered the message is no longer waiting: the delivery is under way and what
remains outstanding is an acknowledgement, not a message. Section 4.4 then requires:
When a Client reconnects with Clean Start set to 0 and a session is present, both the Client and Server MUST resend any unacknowledged PUBLISH packets (where QoS > 0) and PUBREL packets using their original Packet Identifiers.
Section 4.1 lists "QoS 2 messages which have been received from the Client, but have not been completely acknowledged" as Session State, so the exchange belongs to the Session and not to the expiry sweep.
Steps to reproduce
- Subscribe at QoS 2 on a Session with
Clean Start 0and Session Expiry Interval 300. - From another client, publish a QoS 2 message to that topic with Message Expiry Interval 5.
- When the
PUBLISHarrives, answerPUBRECand then cut the TCP connection. - Wait 12 seconds, past the expiry interval.
- Reconnect with
Clean Start 0.
Expected
The PUBREL for the original Packet Identifier is resent on the resumed Session.
Actual
Nothing is resent. Session Present is 1, so the Session itself survived.
Observed on Mosquitto 2.1.2:
control (message published with NO Message Expiry Interval)
resume: session_present=1 PUBREL resent = True
arm (same flow, Message Expiry Interval = 5)
resume: session_present=1 PUBREL resent = False PUBLISH restarted = FalseControl
Both arms run in the same process against the same broker and differ only in whether the publication carried a Message Expiry Interval. The control arm recovers, so this is not a general [MQTT-4.4.0-1] problem; the expiry is deleting an exchange that had already started.
Environment
- Mosquitto 2.1.2, image
eclipse-mosquitto:2.1.2-alpine, digestsha256:6dba0f1b2795ddcbe0d41bdfb8b8d56a423acca23ccde4342a4652be54639b11 - Configuration:
listener 1883,allow_anonymous true,persistence false - MQTT v5.0 over plain TCP
- Reproduced 3 out of 3 runs, each with a fresh random Client Identifier and topic namespace
Reproducer
Standard library only, no dependencies. Exit code 1 means the behaviour was reproduced; the script prints every frame it sends and receives, so its output can be pasted back here as-is.
python3 x02_qos2_inflight_expiry.py <host> <port>#!/usr/bin/env python3
"""Self-contained MQTT v5 reproducer. Standard library only, no dependencies.
Usage: python3 <script>.py [host] [port]
"""
import socket, struct, sys, time, uuid
CONNECT, CONNACK, PUBLISH, PUBACK, PUBREC, PUBREL, PUBCOMP = 1, 2, 3, 4, 5, 6, 7
SUBSCRIBE, SUBACK, UNSUBSCRIBE, UNSUBACK, PINGREQ, PINGRESP, DISCONNECT = 8, 9, 10, 11, 12, 13, 14
NAMES = {1:"CONNECT",2:"CONNACK",3:"PUBLISH",4:"PUBACK",5:"PUBREC",6:"PUBREL",7:"PUBCOMP",
8:"SUBSCRIBE",9:"SUBACK",10:"UNSUBSCRIBE",11:"UNSUBACK",12:"PINGREQ",13:"PINGRESP",14:"DISCONNECT"}
P_MSG_EXPIRY, P_SESSION_EXPIRY, P_WILL_DELAY, P_RECV_MAX, P_MAX_PKT = 0x02, 0x11, 0x18, 0x21, 0x27
P_SUB_ID, P_TOPIC_ALIAS_MAX, P_TOPIC_ALIAS, P_USER = 0x0B, 0x22, 0x23, 0x26
_U8 = {0x01,0x17,0x19,0x24,0x25,0x28,0x29,0x2A}
_U16 = {0x13,0x21,0x22,0x23}
_U32 = {0x02,0x11,0x18,0x27}
_STR = {0x03,0x08,0x12,0x15,0x1A,0x1C,0x1F}
_BIN = {0x09,0x16}
_VAR = {0x0B}
def vbi(n):
out = bytearray()
while True:
b = n % 128; n //= 128
if n: b |= 0x80
out.append(b)
if not n: return bytes(out)
def rvbi(buf, i):
mult, val = 1, 0
for _ in range(4):
b = buf[i]; i += 1
val += (b & 0x7F) * mult
if not b & 0x80: return val, i
mult *= 128
raise ValueError("bad varint")
def s(t):
r = t.encode(); return len(r).to_bytes(2, "big") + r
def rs(buf, i):
n = int.from_bytes(buf[i:i+2], "big"); i += 2
return buf[i:i+n].decode("utf-8", "replace"), i + n
def props(items):
b = bytearray()
for k, v in items:
b.append(k)
if k in _U8: b.append(int(v) & 0xFF)
elif k in _U16: b += int(v).to_bytes(2, "big")
elif k in _U32: b += int(v).to_bytes(4, "big")
elif k in _STR: b += s(str(v))
elif k in _BIN: b += len(v).to_bytes(2, "big") + v
elif k in _VAR: b += vbi(int(v))
elif k == P_USER: b += s(v[0]) + s(v[1])
else: raise ValueError("prop 0x%02x" % k)
return vbi(len(b)) + bytes(b)
def rprops(buf, i):
n, i = rvbi(buf, i); end = i + n; out = {}; users = []
while i < end:
k = buf[i]; i += 1
if k in _U8: v = buf[i]; i += 1
elif k in _U16: v = int.from_bytes(buf[i:i+2], "big"); i += 2
elif k in _U32: v = int.from_bytes(buf[i:i+4], "big"); i += 4
elif k in _STR: v, i = rs(buf, i)
elif k in _BIN:
m = int.from_bytes(buf[i:i+2], "big"); i += 2; v = buf[i:i+m]; i += m
elif k in _VAR: v, i = rvbi(buf, i)
elif k == P_USER:
a, i = rs(buf, i); b2, i = rs(buf, i); v = (a, b2); users.append(v)
else: raise ValueError("unknown prop 0x%02x" % k)
out[k] = v
out["users"] = users
return out, i
class C:
"""One MQTT v5 connection. Every frame is printed so the log IS the evidence."""
def __init__(self, host, port, tag, verbose=True):
self.sk = socket.create_connection((host, port), timeout=15)
self.sk.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.buf = bytearray(); self.tag = tag; self.v = verbose; self.closed = False
self.log("tcp connect %s:%d" % (host, port))
def log(self, m):
if self.v: print(" [%s] %s" % (self.tag, m))
def send(self, raw, what):
self.log("--> %-46s %s" % (what, raw[:40].hex()))
self.sk.sendall(raw)
def _fill(self, n, deadline):
while len(self.buf) < n:
left = deadline - time.monotonic()
if left <= 0: raise TimeoutError
self.sk.settimeout(max(0.01, left))
try: c = self.sk.recv(65536)
except socket.timeout: raise TimeoutError
except ConnectionResetError: self.closed = True; raise EOFError
if not c: self.closed = True; raise EOFError
self.buf += c
def read(self, timeout):
d = time.monotonic() + timeout
self._fill(1, d); first = self.buf[0]
n, mult, i = 0, 1, 1
while True:
self._fill(i + 1, d); b = self.buf[i]; n += (b & 0x7F) * mult; i += 1
if not b & 0x80: break
mult *= 128
self._fill(i + n, d)
raw = bytes(self.buf[:i+n]); del self.buf[:i+n]
p = parse(first, raw[i:]); p["raw"] = raw
self.log("<-- %-46s %s" % (p["desc"], raw[:40].hex()))
return p
def drain(self, seconds):
d = time.monotonic() + seconds; out = []
while True:
left = d - time.monotonic()
if left <= 0: return out
try: out.append(self.read(left))
except (TimeoutError, EOFError, ValueError): return out
def connect(self, cid, clean=True, se=None, will=None, keepalive=60, extra=None, timeout=20):
pr = []
if se is not None: pr.append((P_SESSION_EXPIRY, se))
pr += (extra or [])
flags = 0x02 if clean else 0x00
payload = s(cid)
if will:
flags |= 0x04 | ((will.get("qos", 1) & 3) << 3)
if will.get("retain"): flags |= 0x20
payload += props(will.get("props", [])) + s(will["topic"])
payload += len(will["payload"]).to_bytes(2, "big") + will["payload"]
vh = s("MQTT") + bytes([5, flags]) + keepalive.to_bytes(2, "big") + props(pr)
body = vh + payload
self.send(bytes([CONNECT << 4]) + vbi(len(body)) + body,
"CONNECT id=%s clean=%d" % (cid, clean))
p = self.read(timeout)
assert p["t"] == CONNACK, "expected CONNACK, got %s" % p["desc"]
return p
def subscribe(self, filt, opts=1, pid=1, subid=None, timeout=20):
pr = [(P_SUB_ID, subid)] if subid else []
body = pid.to_bytes(2, "big") + props(pr) + s(filt) + bytes([opts])
self.send(bytes([(SUBSCRIBE << 4) | 2]) + vbi(len(body)) + body, "SUBSCRIBE %s" % filt)
d = time.monotonic() + timeout
while True:
p = self.read(d - time.monotonic())
if p["t"] == SUBACK: return p
def publish(self, topic, payload, qos=0, pid=None, retain=False, dup=False, pr=None):
f = (qos & 3) << 1
if retain: f |= 1
if dup: f |= 8
body = s(topic) + (pid.to_bytes(2, "big") if qos else b"") + props(pr or []) + payload
self.send(bytes([(PUBLISH << 4) | f]) + vbi(len(body)) + body,
"PUBLISH %s qos=%d retain=%d dup=%d" % (topic, qos, retain, dup))
def ack(self, t, pid, reason=0):
f = 2 if t == PUBREL else 0
body = pid.to_bytes(2, "big") + (bytes([reason]) + props([]) if reason else b"")
self.send(bytes([(t << 4) | f]) + vbi(len(body)) + body,
"%s pid=%d rc=0x%02x" % (NAMES[t], pid, reason))
def pub_qos1(self, topic, payload, pid=1, timeout=20, **kw):
self.publish(topic, payload, qos=1, pid=pid, **kw)
d = time.monotonic() + timeout
while True:
try: p = self.read(d - time.monotonic())
except (TimeoutError, EOFError): return None
if p["t"] == PUBACK and p["pid"] == pid: return p
def pub_qos2(self, topic, payload, pid=1, timeout=20, **kw):
self.publish(topic, payload, qos=2, pid=pid, **kw)
d = time.monotonic() + timeout
rec = None
while rec is None:
try: p = self.read(d - time.monotonic())
except (TimeoutError, EOFError): return None
if p["t"] == PUBREC and p["pid"] == pid: rec = p
self.ack(PUBREL, pid)
while True:
try: p = self.read(d - time.monotonic())
except (TimeoutError, EOFError): return rec
if p["t"] == PUBCOMP and p["pid"] == pid: return p
def disconnect(self, reason=0):
body = bytes([reason]) + props([])
try: self.send(bytes([DISCONNECT << 4]) + vbi(len(body)) + body, "DISCONNECT rc=0x%02x" % reason)
except OSError: pass
self.close()
def kill(self):
"""Abnormal close: TCP RST, which section 3.1.2.5 treats as not a normal disconnection."""
try: self.sk.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
except OSError: pass
self.log("--- abrupt close (TCP RST)")
self.close()
def close(self):
self.closed = True
try: self.sk.close()
except OSError: pass
def parse(first, body):
t = first >> 4; f = first & 0x0F
o = {"t": t, "flags": f, "pid": None, "rc": None, "props": {}, "desc": NAMES.get(t, str(t))}
if t == CONNACK:
o["sp"] = bool(body[0] & 1); o["rc"] = body[1]
o["props"], _ = rprops(body, 2)
o["desc"] = "CONNACK session_present=%d rc=0x%02x" % (o["sp"], o["rc"])
elif t == PUBLISH:
o["dup"] = bool(f & 8); o["qos"] = (f & 6) >> 1; o["retain"] = bool(f & 1)
o["topic"], i = rs(body, 0)
if o["qos"]: o["pid"] = int.from_bytes(body[i:i+2], "big"); i += 2
o["props"], i = rprops(body, i); o["payload"] = body[i:]
o["desc"] = "PUBLISH %r qos=%d dup=%d retain=%d pid=%s payload=%r" % (
o["topic"], o["qos"], o["dup"], o["retain"], o["pid"], o["payload"][:24])
elif t in (PUBACK, PUBREC, PUBREL, PUBCOMP):
o["pid"] = int.from_bytes(body[0:2], "big"); o["rc"] = body[2] if len(body) > 2 else 0
o["desc"] = "%s pid=%d rc=0x%02x" % (NAMES[t], o["pid"], o["rc"])
elif t in (SUBACK, UNSUBACK):
o["pid"] = int.from_bytes(body[0:2], "big")
o["props"], i = rprops(body, 2); o["codes"] = list(body[i:])
o["desc"] = "%s pid=%d codes=%s" % (NAMES[t], o["pid"], [hex(c) for c in o["codes"]])
elif t == DISCONNECT:
o["rc"] = body[0] if body else 0
o["desc"] = "DISCONNECT rc=0x%02x" % o["rc"]
return o
def endpoint(default_port):
host = sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1"
port = int(sys.argv[2]) if len(sys.argv) > 2 else default_port
return host, port
def nid(p): return "%s-%s" % (p, uuid.uuid4().hex[:10])
def ns(): return "repro/%s" % uuid.uuid4().hex[:12]
def verdict(name, failed, detail):
print("\n" + "=" * 72)
print("%s: %s" % (name, "REPRODUCED (spec violation observed)" if failed else "not reproduced"))
print(detail)
print("=" * 72)
return 1 if failed else 0
# ---------------------------------------------------------------------------
# X-02: a QoS 2 delivery that has already begun is deleted by Message Expiry
# ---------------------------------------------------------------------------
# Section 3.3.2.3.3 applies the Message Expiry Interval to an Application
# Message the Server is HOLDING. Once the receiver has answered PUBREC the
# delivery is under way and the Server owes a PUBREL, which section 4.4
# [MQTT-4.4.0-1] requires it to resend on the resumed Session using the
# original Packet Identifier.
#
# ARM subscribe QoS 2 on a persistent Session, receive the PUBLISH, answer
# PUBREC, cut abruptly, wait past the Message Expiry Interval, resume.
# The owed PUBREL MUST arrive.
# CONTROL the identical cut on a message published with NO Message Expiry
# Interval. If the PUBREL comes back there and not in the arm, the
# expiry is what deleted an exchange that had already started.
EXPIRY = 5
WAIT = 12
def one_arm(host, port, label, expiry):
topic = ns() + "/" + label
cid = nid(label)
c = C(host, port, label)
c.connect(cid, clean=False, se=300)
sub = c.subscribe(topic, opts=2)
if any(x >= 0x80 for x in sub["codes"]):
return {"ok": False, "why": "QoS 2 subscribe refused: %s" % sub["desc"]}
p = C(host, port, label + "-pub")
p.connect(nid("pub"), clean=True)
pr = [(P_MSG_EXPIRY, expiry)] if expiry else []
p.pub_qos2(topic, b"inflight", pid=1, pr=pr)
p.disconnect(0)
got = None
for m in c.drain(12):
if m["t"] == PUBLISH and m["payload"] == b"inflight":
got = m; break
if got is None or got["qos"] != 2:
c.kill()
return {"ok": False, "why": "no QoS 2 delivery reached the subscriber"}
pid = got["pid"]
c.ack(PUBREC, pid)
c.kill()
return {"ok": True, "cid": cid, "pid": pid}
def resume(host, port, label, st):
c = C(host, port, label + "-resumed")
ack = c.connect(st["cid"], clean=False, se=300)
pubrel = restarted = False
for m in c.drain(12):
if m["t"] == PUBREL and m["pid"] == st["pid"]:
pubrel = True; c.ack(PUBCOMP, st["pid"])
if m["t"] == PUBLISH and m["payload"] == b"inflight":
restarted = True
c.disconnect(0)
return ack["sp"], pubrel, restarted
def main():
host, port = endpoint(1883)
print("target %s:%d\n" % (host, port))
print("-- start both exchanges and cut them after PUBREC")
ctl = one_arm(host, port, "control", None)
arm = one_arm(host, port, "arm", EXPIRY)
for st, n in ((ctl, "control"), (arm, "arm")):
if not st["ok"]:
return verdict("X-02", False, "Precondition failed for the %s arm: %s" % (n, st["why"]))
print("\n both arms answered PUBREC; waiting %ds, past the %ds Message Expiry ..." % (WAIT, EXPIRY))
time.sleep(WAIT)
print("\n-- CONTROL resume (message had NO Message Expiry Interval)")
c_sp, c_rel, c_re = resume(host, port, "control", ctl)
print("\n-- ARM resume (message had Message Expiry Interval = %d)" % EXPIRY)
a_sp, a_rel, a_re = resume(host, port, "arm", arm)
if not (c_rel or c_re):
return verdict("X-02", False,
"Control failed: the in-flight QoS 2 exchange was not recovered even WITHOUT a "
"Message Expiry Interval, so the loss is not attributable to expiry. That is a "
"separate [MQTT-4.4.0-1] problem.")
return verdict("X-02", not (a_rel or a_re),
"control (no expiry): session_present=%d PUBREL resent=%s PUBLISH restarted=%s\n"
"arm (expiry=%ds) : session_present=%d PUBREL resent=%s PUBLISH restarted=%s\n"
"The exchange had already passed PUBREC when the connection was cut, so it was no longer "
"a message being held." % (
int(c_sp), c_rel, c_re, EXPIRY, int(a_sp), a_rel, a_re))
if __name__ == "__main__":
sys.exit(main())Source: eclipse-mosquitto/mosquitto