_packet.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. """ internal module to (de)serialize packet.
  2. """
  3. from __future__ import annotations
  4. import functools
  5. import struct
  6. from typing import TYPE_CHECKING, Callable, NamedTuple, TypeVar
  7. from paho.mqtt.enums import ConnackCode, MQTTProtocolVersion
  8. from paho.mqtt.exception import MalformedPacket, MQTTException
  9. from paho.mqtt.packettypes import PacketTypes
  10. from paho.mqtt.properties import Properties
  11. from paho.mqtt.reasoncodes import ReasonCode
  12. class PublishPacket(NamedTuple):
  13. dup: bool
  14. qos: int
  15. retain: bool
  16. topic: bytes
  17. mid: int
  18. properties: Properties|None
  19. payload: bytes|bytearray
  20. class ConnackPacket(NamedTuple):
  21. flags: int
  22. reason: ReasonCode
  23. properties: Properties|None
  24. rc: ConnackCode
  25. class DisconnectPacket(NamedTuple):
  26. reason: ReasonCode|None
  27. properties: Properties|None
  28. class SubackPacket(NamedTuple):
  29. mid: int
  30. reason_codes: list[ReasonCode]
  31. granted_qos: tuple[int, ...]
  32. properties: Properties
  33. class UnsubackPacket(NamedTuple):
  34. mid: int
  35. reason_codes: list[ReasonCode]
  36. properties: Properties
  37. class PubrelPacket(NamedTuple):
  38. mid: int
  39. reason: ReasonCode
  40. properties: Properties
  41. class PubrecPacket(NamedTuple):
  42. mid: int
  43. reason: ReasonCode
  44. properties: Properties
  45. class PubackPacket(NamedTuple):
  46. mid: int
  47. reason: ReasonCode
  48. properties: Properties
  49. class PubcompPacket(NamedTuple):
  50. mid: int
  51. reason: ReasonCode
  52. properties: Properties
  53. # Also catch MQTTException, because Properties decoding could yield MQTTException.
  54. # It's expected that such decoding yield MQTTException because it could equally occur
  55. # during decoding (here a MalformedPacket would be better), but also when user try to
  56. # encode a property (here a MalformedPacket wouldn't fit).
  57. DECODE_ERRORS = (struct.error, IndexError, KeyError, ValueError, MQTTException)
  58. if TYPE_CHECKING:
  59. from typing_extensions import ParamSpec
  60. P = ParamSpec("P")
  61. R = TypeVar("R")
  62. def convert_exception(func: Callable[P, R]) -> Callable[P, R]:
  63. @functools.wraps(func)
  64. def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
  65. try:
  66. return func(*args, **kwargs)
  67. except MalformedPacket:
  68. raise
  69. except DECODE_ERRORS as err:
  70. raise MalformedPacket(str(err)) from err
  71. return wrapper
  72. @convert_exception
  73. def decode_publish(header: int, packet: bytes|bytearray, protocol: MQTTProtocolVersion) -> PublishPacket:
  74. """ Decode a PUBLISH packet.
  75. header is the first bytes of fixed header. packet is everything after
  76. the fixed header (e.g. after the remaining length byte(s)).
  77. """
  78. dup = ((header & 0x08) >> 3) != 0
  79. qos = (header & 0x06) >> 1
  80. retain = (header & 0x01) != 0
  81. pack_format = f"!H{len(packet) - 2}s"
  82. (slen, packet) = struct.unpack(pack_format, packet)
  83. pack_format = f"!{slen}s{len(packet) - slen}s"
  84. (topic, packet) = struct.unpack(pack_format, packet)
  85. if protocol != MQTTProtocolVersion.MQTTv5 and len(topic) == 0:
  86. raise MalformedPacket("topic can't be empty in MQTTv3")
  87. mid = 0
  88. if qos > 0:
  89. pack_format = f"!H{len(packet) - 2}s"
  90. (mid, packet) = struct.unpack(pack_format, packet)
  91. properties = None
  92. if protocol == MQTTProtocolVersion.MQTTv5:
  93. properties = Properties(PacketTypes.PUBLISH)
  94. _props, props_len = properties.unpack(packet)
  95. packet = packet[props_len:]
  96. payload = packet
  97. return PublishPacket(
  98. dup=dup,
  99. qos=qos,
  100. retain=retain,
  101. topic=topic,
  102. mid=mid,
  103. properties=properties,
  104. payload=payload,
  105. )
  106. def convert_connack_rc_to_reason_code(connack_code: ConnackCode) -> ReasonCode:
  107. """Convert a MQTTv3 / MQTTv3.1.1 connack result to `ReasonCode`.
  108. This is used in `on_connect` callback to have a consistent API.
  109. Be careful that the numeric value isn't the same, for example:
  110. >>> ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE == 3
  111. >>> convert_connack_rc_to_reason_code(ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE) == 136
  112. It's recommended to compare by names
  113. >>> code_to_test = ReasonCode(PacketTypes.CONNACK, "Server unavailable")
  114. >>> convert_connack_rc_to_reason_code(ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE) == code_to_test
  115. """
  116. if connack_code == ConnackCode.CONNACK_ACCEPTED:
  117. return ReasonCode(PacketTypes.CONNACK, "Success")
  118. if connack_code == ConnackCode.CONNACK_REFUSED_PROTOCOL_VERSION:
  119. return ReasonCode(PacketTypes.CONNACK, "Unsupported protocol version")
  120. if connack_code == ConnackCode.CONNACK_REFUSED_IDENTIFIER_REJECTED:
  121. return ReasonCode(PacketTypes.CONNACK, "Client identifier not valid")
  122. if connack_code == ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE:
  123. return ReasonCode(PacketTypes.CONNACK, "Server unavailable")
  124. if connack_code == ConnackCode.CONNACK_REFUSED_BAD_USERNAME_PASSWORD:
  125. return ReasonCode(PacketTypes.CONNACK, "Bad user name or password")
  126. if connack_code == ConnackCode.CONNACK_REFUSED_NOT_AUTHORIZED:
  127. return ReasonCode(PacketTypes.CONNACK, "Not authorized")
  128. return ReasonCode(PacketTypes.CONNACK, "Unspecified error")
  129. @convert_exception
  130. def decode_connack(header: int, packet: bytes|bytearray, protocol: MQTTProtocolVersion) -> ConnackPacket:
  131. """ Decode a CONNACK packet.
  132. header is the first bytes of fixed header. packet is everything after
  133. the fixed header (e.g. after the remaining length byte(s)).
  134. """
  135. if protocol == MQTTProtocolVersion.MQTTv5:
  136. if len(packet) < 2:
  137. raise MalformedPacket("CONNACK packet is too small")
  138. elif len(packet) != 2:
  139. raise MalformedPacket("CONNACK packet size is wrong")
  140. if protocol == MQTTProtocolVersion.MQTTv5:
  141. (flags, result) = struct.unpack(
  142. "!BB", packet[:2])
  143. if result == 1:
  144. # This is probably a failure from a broker that doesn't support
  145. # MQTT v5.
  146. reason = ReasonCode(PacketTypes.CONNACK, aName="Unsupported protocol version")
  147. properties = None
  148. else:
  149. reason = ReasonCode(PacketTypes.CONNACK, identifier=result)
  150. properties = Properties(PacketTypes.CONNACK)
  151. properties.unpack(packet[2:])
  152. else:
  153. (flags, result) = struct.unpack("!BB", packet)
  154. reason = convert_connack_rc_to_reason_code(result)
  155. properties = None
  156. return ConnackPacket(
  157. flags=flags,
  158. reason=reason,
  159. properties=properties,
  160. rc=result,
  161. )
  162. @convert_exception
  163. def decode_disconnect(header: int, packet: bytes|bytearray, protocol: MQTTProtocolVersion) -> DisconnectPacket:
  164. """ Decode a DISCONNECT packet.
  165. header is the first bytes of fixed header. packet is everything after
  166. the fixed header (e.g. after the remaining length byte(s)).
  167. """
  168. packet_type = PacketTypes.DISCONNECT
  169. reasonCode = properties = None
  170. if len(packet) > 0:
  171. reasonCode = ReasonCode(packet_type)
  172. reasonCode.unpack(packet)
  173. if len(packet) > 1:
  174. properties = Properties(packet_type)
  175. _props, _props_len = properties.unpack(packet[1:])
  176. return DisconnectPacket(
  177. reason=reasonCode,
  178. properties=properties,
  179. )
  180. @convert_exception
  181. def decode_suback(header: int, packet: bytes|bytearray, protocol: MQTTProtocolVersion) -> SubackPacket:
  182. """ Decode a SUBACK packet.
  183. header is the first bytes of fixed header. packet is everything after
  184. the fixed header (e.g. after the remaining length byte(s)).
  185. """
  186. pack_format = f"!H{len(packet) - 2}s"
  187. (mid, packet) = struct.unpack(pack_format, packet)
  188. if protocol == MQTTProtocolVersion.MQTTv5:
  189. granted_qos: tuple[int, ...] = ()
  190. properties = Properties(PacketTypes.SUBACK)
  191. _props, props_len = properties.unpack(packet)
  192. reasoncodes = [ReasonCode(PacketTypes.SUBACK, identifier=c) for c in packet[props_len:]]
  193. else:
  194. pack_format = f"!{'B' * len(packet)}"
  195. granted_qos = struct.unpack(pack_format, packet)
  196. reasoncodes = [ReasonCode(PacketTypes.SUBACK, identifier=c) for c in granted_qos]
  197. properties = Properties(PacketTypes.SUBACK)
  198. return SubackPacket(
  199. mid=mid,
  200. reason_codes=reasoncodes,
  201. granted_qos=granted_qos,
  202. properties=properties,
  203. )
  204. @convert_exception
  205. def decode_unsuback(header: int, packet: bytes|bytearray, protocol: MQTTProtocolVersion) -> UnsubackPacket:
  206. """ Decode a UNSUBACK packet.
  207. header is the first bytes of fixed header. packet is everything after
  208. the fixed header (e.g. after the remaining length byte(s)).
  209. """
  210. if protocol == MQTTProtocolVersion.MQTTv5:
  211. if len(packet) < 4:
  212. raise MalformedPacket("wrong size of packet")
  213. elif len(packet) != 2:
  214. raise MalformedPacket("wrong size of packet")
  215. mid, = struct.unpack("!H", packet[:2])
  216. if protocol == MQTTProtocolVersion.MQTTv5:
  217. packet = packet[2:]
  218. properties = Properties(PacketTypes.UNSUBACK)
  219. _props, props_len = properties.unpack(packet)
  220. reasoncodes_list = [
  221. ReasonCode(PacketTypes.UNSUBACK, identifier=c)
  222. for c in packet[props_len:]
  223. ]
  224. else:
  225. reasoncodes_list = []
  226. properties = Properties(PacketTypes.UNSUBACK)
  227. return UnsubackPacket(
  228. mid=mid,
  229. reason_codes=reasoncodes_list,
  230. properties=properties,
  231. )
  232. def _decode_mid_reason_prop(packet_type: int, packet: bytes|bytearray, protocol: MQTTProtocolVersion) -> tuple[int, ReasonCode, Properties]:
  233. if protocol == MQTTProtocolVersion.MQTTv5:
  234. if len(packet) < 2:
  235. raise MalformedPacket("wrong size of packet")
  236. elif len(packet) != 2:
  237. raise MalformedPacket("wrong size of packet")
  238. mid, = struct.unpack("!H", packet[:2])
  239. reasonCode = ReasonCode(packet_type)
  240. properties = Properties(packet_type)
  241. if protocol == MQTTProtocolVersion.MQTTv5 and len(packet) > 2:
  242. reasonCode = ReasonCode(packet_type)
  243. reasonCode.unpack(packet[2:])
  244. if len(packet) > 3:
  245. properties = Properties(packet_type)
  246. _props, _props_len = properties.unpack(
  247. packet[3:])
  248. return mid, reasonCode, properties
  249. @convert_exception
  250. def decode_pubrel(header: int, packet: bytes|bytearray, protocol: MQTTProtocolVersion) -> PubrelPacket:
  251. """ Decode a PUBREL packet.
  252. header is the first bytes of fixed header. packet is everything after
  253. the fixed header (e.g. after the remaining length byte(s)).
  254. """
  255. (mid, reasonCode, properties) = _decode_mid_reason_prop(PacketTypes.PUBREL, packet, protocol)
  256. return PubrelPacket(
  257. mid=mid,
  258. reason=reasonCode,
  259. properties=properties,
  260. )
  261. @convert_exception
  262. def decode_pubrec(header: int, packet: bytes|bytearray, protocol: MQTTProtocolVersion) -> PubrecPacket:
  263. """ Decode a PUBREC packet.
  264. header is the first bytes of fixed header. packet is everything after
  265. the fixed header (e.g. after the remaining length byte(s)).
  266. """
  267. (mid, reasonCode, properties) = _decode_mid_reason_prop(PacketTypes.PUBREC, packet, protocol)
  268. return PubrecPacket(
  269. mid=mid,
  270. reason=reasonCode,
  271. properties=properties,
  272. )
  273. @convert_exception
  274. def decode_puback(header: int, packet: bytes|bytearray, protocol: MQTTProtocolVersion) -> PubackPacket:
  275. """ Decode a PUBACK packet.
  276. header is the first bytes of fixed header. packet is everything after
  277. the fixed header (e.g. after the remaining length byte(s)).
  278. """
  279. (mid, reasonCode, properties) = _decode_mid_reason_prop(PacketTypes.PUBACK, packet, protocol)
  280. return PubackPacket(
  281. mid=mid,
  282. reason=reasonCode,
  283. properties=properties,
  284. )
  285. @convert_exception
  286. def decode_pubcomp(header: int, packet: bytes|bytearray, protocol: MQTTProtocolVersion) -> PubcompPacket:
  287. """ Decode a PUBCOMP packet.
  288. header is the first bytes of fixed header. packet is everything after
  289. the fixed header (e.g. after the remaining length byte(s)).
  290. """
  291. (mid, reasonCode, properties) = _decode_mid_reason_prop(PacketTypes.PUBCOMP, packet, protocol)
  292. return PubcompPacket(
  293. mid=mid,
  294. reason=reasonCode,
  295. properties=properties,
  296. )