properties.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. # *******************************************************************
  2. # Copyright (c) 2017, 2019 IBM Corp.
  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. # http://www.eclipse.org/legal/epl-v20.html
  10. # and the Eclipse Distribution License is available at
  11. # http://www.eclipse.org/org/documents/edl-v10.php.
  12. #
  13. # Contributors:
  14. # Ian Craggs - initial implementation and/or documentation
  15. # *******************************************************************
  16. import struct
  17. from .exception import MalformedPacket, MQTTException
  18. from .packettypes import PacketTypes
  19. def writeInt16(length):
  20. # serialize a 16 bit integer to network format
  21. return bytearray(struct.pack("!H", length))
  22. def readInt16(buf):
  23. # deserialize a 16 bit integer from network format
  24. return struct.unpack("!H", buf[:2])[0]
  25. def writeInt32(length):
  26. # serialize a 32 bit integer to network format
  27. return bytearray(struct.pack("!L", length))
  28. def readInt32(buf):
  29. # deserialize a 32 bit integer from network format
  30. return struct.unpack("!L", buf[:4])[0]
  31. def writeUTF(data):
  32. # data could be a string, or bytes. If string, encode into bytes with utf-8
  33. if not isinstance(data, bytes):
  34. data = bytes(data, "utf-8")
  35. return writeInt16(len(data)) + data
  36. def readUTF(buffer, maxlen):
  37. if maxlen >= 2:
  38. length = readInt16(buffer)
  39. else:
  40. raise MalformedPacket("Not enough data to read string length")
  41. maxlen -= 2
  42. if length > maxlen:
  43. raise MalformedPacket("Length delimited string too long")
  44. buf = buffer[2:2+length].decode("utf-8")
  45. # look for chars which are invalid for MQTT
  46. for c in buf: # look for D800-DFFF in the UTF string
  47. ord_c = ord(c)
  48. if ord_c >= 0xD800 and ord_c <= 0xDFFF:
  49. raise MalformedPacket("[MQTT-1.5.4-1] D800-DFFF found in UTF-8 data")
  50. if ord_c == 0x00: # look for null in the UTF string
  51. raise MalformedPacket("[MQTT-1.5.4-2] Null found in UTF-8 data")
  52. if ord_c == 0xFEFF:
  53. raise MalformedPacket("[MQTT-1.5.4-3] U+FEFF in UTF-8 data")
  54. return buf, length+2
  55. def writeBytes(buffer):
  56. return writeInt16(len(buffer)) + buffer
  57. def readBytes(buffer, maxlen):
  58. # Every property is framed by the Property Length field, so a value
  59. # that reaches past the bytes left in that region cannot be parsed and
  60. # is a malformed packet (MQTT v5.0 sections 2.2.2.1, 2.2.2.2 and 1.4).
  61. # This is the same bound readUTF() already enforces for strings.
  62. if maxlen >= 2:
  63. length = readInt16(buffer)
  64. else:
  65. raise MalformedPacket("Not enough data to read binary data length")
  66. maxlen -= 2
  67. if length > maxlen:
  68. raise MalformedPacket("Length delimited binary data too long")
  69. return buffer[2:2+length], length+2
  70. class VariableByteIntegers: # Variable Byte Integer
  71. """
  72. MQTT variable byte integer helper class. Used
  73. in several places in MQTT v5.0 properties.
  74. """
  75. @staticmethod
  76. def encode(x):
  77. """
  78. Convert an integer 0 <= x <= 268435455 into multi-byte format.
  79. Returns the buffer converted from the integer.
  80. """
  81. if not 0 <= x <= 268435455:
  82. raise ValueError(f"Value {x!r} must be in range 0-268435455")
  83. buffer = b''
  84. while 1:
  85. digit = x % 128
  86. x //= 128
  87. if x > 0:
  88. digit |= 0x80
  89. buffer += bytes([digit])
  90. if x == 0:
  91. break
  92. return buffer
  93. @staticmethod
  94. def decode(buffer):
  95. """
  96. Get the value of a multi-byte integer from a buffer
  97. Return the value, and the number of bytes used.
  98. [MQTT-1.5.5-1] the encoded value MUST use the minimum number of bytes necessary to represent the value
  99. """
  100. multiplier = 1
  101. value = 0
  102. bytes = 0
  103. while 1:
  104. # A Variable Byte Integer is at most four bytes long, which also
  105. # caps the value at 268,435,455 (MQTT v5.0 section 1.5.5). A fifth
  106. # byte, or running out of data while a continuation bit is still
  107. # pending, means the packet cannot be parsed, so it is malformed
  108. # (sections 1.4 and 2.2.2.2).
  109. if bytes >= 4:
  110. raise MalformedPacket(
  111. "Variable Byte Integer is more than four bytes long"
  112. )
  113. if len(buffer) == 0:
  114. raise MalformedPacket("Not enough data to decode Variable Byte Integer")
  115. bytes += 1
  116. digit = buffer[0]
  117. buffer = buffer[1:]
  118. value += (digit & 127) * multiplier
  119. if digit & 128 == 0:
  120. break
  121. multiplier *= 128
  122. return (value, bytes)
  123. class Properties:
  124. """MQTT v5.0 properties class.
  125. See Properties.names for a list of accepted property names along with their numeric values.
  126. See Properties.properties for the data type of each property.
  127. Example of use::
  128. publish_properties = Properties(PacketTypes.PUBLISH)
  129. publish_properties.UserProperty = ("a", "2")
  130. publish_properties.UserProperty = ("c", "3")
  131. First the object is created with packet type as argument, no properties will be present at
  132. this point. Then properties are added as attributes, the name of which is the string property
  133. name without the spaces.
  134. """
  135. def __init__(self, packetType):
  136. self.packetType = packetType
  137. self.types = ["Byte", "Two Byte Integer", "Four Byte Integer", "Variable Byte Integer",
  138. "Binary Data", "UTF-8 Encoded String", "UTF-8 String Pair"]
  139. self.names = {
  140. "Payload Format Indicator": 1,
  141. "Message Expiry Interval": 2,
  142. "Content Type": 3,
  143. "Response Topic": 8,
  144. "Correlation Data": 9,
  145. "Subscription Identifier": 11,
  146. "Session Expiry Interval": 17,
  147. "Assigned Client Identifier": 18,
  148. "Server Keep Alive": 19,
  149. "Authentication Method": 21,
  150. "Authentication Data": 22,
  151. "Request Problem Information": 23,
  152. "Will Delay Interval": 24,
  153. "Request Response Information": 25,
  154. "Response Information": 26,
  155. "Server Reference": 28,
  156. "Reason String": 31,
  157. "Receive Maximum": 33,
  158. "Topic Alias Maximum": 34,
  159. "Topic Alias": 35,
  160. "Maximum QoS": 36,
  161. "Retain Available": 37,
  162. "User Property": 38,
  163. "Maximum Packet Size": 39,
  164. "Wildcard Subscription Available": 40,
  165. "Subscription Identifier Available": 41,
  166. "Shared Subscription Available": 42
  167. }
  168. self.properties = {
  169. # id: type, packets
  170. # payload format indicator
  171. 1: (self.types.index("Byte"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]),
  172. 2: (self.types.index("Four Byte Integer"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]),
  173. 3: (self.types.index("UTF-8 Encoded String"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]),
  174. 8: (self.types.index("UTF-8 Encoded String"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]),
  175. 9: (self.types.index("Binary Data"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]),
  176. 11: (self.types.index("Variable Byte Integer"),
  177. [PacketTypes.PUBLISH, PacketTypes.SUBSCRIBE]),
  178. 17: (self.types.index("Four Byte Integer"),
  179. [PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.DISCONNECT]),
  180. 18: (self.types.index("UTF-8 Encoded String"), [PacketTypes.CONNACK]),
  181. 19: (self.types.index("Two Byte Integer"), [PacketTypes.CONNACK]),
  182. 21: (self.types.index("UTF-8 Encoded String"),
  183. [PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.AUTH]),
  184. 22: (self.types.index("Binary Data"),
  185. [PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.AUTH]),
  186. 23: (self.types.index("Byte"),
  187. [PacketTypes.CONNECT]),
  188. 24: (self.types.index("Four Byte Integer"), [PacketTypes.WILLMESSAGE]),
  189. 25: (self.types.index("Byte"), [PacketTypes.CONNECT]),
  190. 26: (self.types.index("UTF-8 Encoded String"), [PacketTypes.CONNACK]),
  191. 28: (self.types.index("UTF-8 Encoded String"),
  192. [PacketTypes.CONNACK, PacketTypes.DISCONNECT]),
  193. 31: (self.types.index("UTF-8 Encoded String"),
  194. [PacketTypes.CONNACK, PacketTypes.PUBACK, PacketTypes.PUBREC,
  195. PacketTypes.PUBREL, PacketTypes.PUBCOMP, PacketTypes.SUBACK,
  196. PacketTypes.UNSUBACK, PacketTypes.DISCONNECT, PacketTypes.AUTH]),
  197. 33: (self.types.index("Two Byte Integer"),
  198. [PacketTypes.CONNECT, PacketTypes.CONNACK]),
  199. 34: (self.types.index("Two Byte Integer"),
  200. [PacketTypes.CONNECT, PacketTypes.CONNACK]),
  201. 35: (self.types.index("Two Byte Integer"), [PacketTypes.PUBLISH]),
  202. 36: (self.types.index("Byte"), [PacketTypes.CONNACK]),
  203. 37: (self.types.index("Byte"), [PacketTypes.CONNACK]),
  204. 38: (self.types.index("UTF-8 String Pair"),
  205. [PacketTypes.CONNECT, PacketTypes.CONNACK,
  206. PacketTypes.PUBLISH, PacketTypes.PUBACK,
  207. PacketTypes.PUBREC, PacketTypes.PUBREL, PacketTypes.PUBCOMP,
  208. PacketTypes.SUBSCRIBE, PacketTypes.SUBACK,
  209. PacketTypes.UNSUBSCRIBE, PacketTypes.UNSUBACK,
  210. PacketTypes.DISCONNECT, PacketTypes.AUTH, PacketTypes.WILLMESSAGE]),
  211. 39: (self.types.index("Four Byte Integer"),
  212. [PacketTypes.CONNECT, PacketTypes.CONNACK]),
  213. 40: (self.types.index("Byte"), [PacketTypes.CONNACK]),
  214. 41: (self.types.index("Byte"), [PacketTypes.CONNACK]),
  215. 42: (self.types.index("Byte"), [PacketTypes.CONNACK]),
  216. }
  217. def allowsMultiple(self, compressedName):
  218. return self.getIdentFromName(compressedName) in [11, 38]
  219. def getIdentFromName(self, compressedName):
  220. # return the identifier corresponding to the property name
  221. result = -1
  222. for name in self.names:
  223. if compressedName == name.replace(' ', ''):
  224. result = self.names[name]
  225. break
  226. return result
  227. def __setattr__(self, name, value):
  228. name = name.replace(' ', '')
  229. privateVars = ["packetType", "types", "names", "properties"]
  230. if name in privateVars:
  231. object.__setattr__(self, name, value)
  232. else:
  233. # the name could have spaces in, or not. Remove spaces before assignment
  234. if name not in [aname.replace(' ', '') for aname in self.names]:
  235. raise MQTTException(
  236. f"Property name must be one of {self.names.keys()}")
  237. # check that this attribute applies to the packet type
  238. if self.packetType not in self.properties[self.getIdentFromName(name)][1]:
  239. raise MQTTException(f"Property {name} does not apply to packet type {PacketTypes.Names[self.packetType]}")
  240. # Check for forbidden values
  241. if not isinstance(value, list):
  242. if name in ["ReceiveMaximum", "TopicAlias"] \
  243. and (value < 1 or value > 65535):
  244. raise MQTTException(f"{name} property value must be in the range 1-65535")
  245. elif name in ["TopicAliasMaximum"] \
  246. and (value < 0 or value > 65535):
  247. raise MQTTException(f"{name} property value must be in the range 0-65535")
  248. elif name in ["MaximumPacketSize", "SubscriptionIdentifier"] \
  249. and (value < 1 or value > 268435455):
  250. raise MQTTException(f"{name} property value must be in the range 1-268435455")
  251. elif name in ["RequestResponseInformation", "RequestProblemInformation", "PayloadFormatIndicator"] \
  252. and (value != 0 and value != 1):
  253. raise MQTTException(
  254. f"{name} property value must be 0 or 1")
  255. if self.allowsMultiple(name):
  256. if not isinstance(value, list):
  257. value = [value]
  258. if hasattr(self, name):
  259. value = object.__getattribute__(self, name) + value
  260. object.__setattr__(self, name, value)
  261. def __str__(self):
  262. buffer = "["
  263. first = True
  264. for name in self.names:
  265. compressedName = name.replace(' ', '')
  266. if hasattr(self, compressedName):
  267. if not first:
  268. buffer += ", "
  269. buffer += f"{compressedName} : {getattr(self, compressedName)}"
  270. first = False
  271. buffer += "]"
  272. return buffer
  273. def json(self):
  274. data = {}
  275. for name in self.names:
  276. compressedName = name.replace(' ', '')
  277. if hasattr(self, compressedName):
  278. val = getattr(self, compressedName)
  279. if compressedName == 'CorrelationData' and isinstance(val, bytes):
  280. data[compressedName] = val.hex()
  281. else:
  282. data[compressedName] = val
  283. return data
  284. def isEmpty(self):
  285. rc = True
  286. for name in self.names:
  287. compressedName = name.replace(' ', '')
  288. if hasattr(self, compressedName):
  289. rc = False
  290. break
  291. return rc
  292. def clear(self):
  293. for name in self.names:
  294. compressedName = name.replace(' ', '')
  295. if hasattr(self, compressedName):
  296. delattr(self, compressedName)
  297. def writeProperty(self, identifier, type, value):
  298. buffer = b""
  299. buffer += VariableByteIntegers.encode(identifier) # identifier
  300. if type == self.types.index("Byte"): # value
  301. buffer += bytes([value])
  302. elif type == self.types.index("Two Byte Integer"):
  303. buffer += writeInt16(value)
  304. elif type == self.types.index("Four Byte Integer"):
  305. buffer += writeInt32(value)
  306. elif type == self.types.index("Variable Byte Integer"):
  307. buffer += VariableByteIntegers.encode(value)
  308. elif type == self.types.index("Binary Data"):
  309. buffer += writeBytes(value)
  310. elif type == self.types.index("UTF-8 Encoded String"):
  311. buffer += writeUTF(value)
  312. elif type == self.types.index("UTF-8 String Pair"):
  313. buffer += writeUTF(value[0]) + writeUTF(value[1])
  314. return buffer
  315. def pack(self):
  316. # serialize properties into buffer for sending over network
  317. buffer = b""
  318. for name in self.names:
  319. compressedName = name.replace(' ', '')
  320. if hasattr(self, compressedName):
  321. identifier = self.getIdentFromName(compressedName)
  322. attr_type = self.properties[identifier][0]
  323. if self.allowsMultiple(compressedName):
  324. for prop in getattr(self, compressedName):
  325. buffer += self.writeProperty(identifier,
  326. attr_type, prop)
  327. else:
  328. buffer += self.writeProperty(identifier, attr_type,
  329. getattr(self, compressedName))
  330. return VariableByteIntegers.encode(len(buffer)) + buffer
  331. def readProperty(self, buffer, type, propslen):
  332. if type == self.types.index("Byte"):
  333. value = buffer[0]
  334. valuelen = 1
  335. elif type == self.types.index("Two Byte Integer"):
  336. value = readInt16(buffer)
  337. valuelen = 2
  338. elif type == self.types.index("Four Byte Integer"):
  339. value = readInt32(buffer)
  340. valuelen = 4
  341. elif type == self.types.index("Variable Byte Integer"):
  342. value, valuelen = VariableByteIntegers.decode(buffer)
  343. elif type == self.types.index("Binary Data"):
  344. value, valuelen = readBytes(buffer, propslen)
  345. elif type == self.types.index("UTF-8 Encoded String"):
  346. value, valuelen = readUTF(buffer, propslen)
  347. elif type == self.types.index("UTF-8 String Pair"):
  348. value, valuelen = readUTF(buffer, propslen)
  349. buffer = buffer[valuelen:] # strip the bytes used by the value
  350. value1, valuelen1 = readUTF(buffer, propslen - valuelen)
  351. value = (value, value1)
  352. valuelen += valuelen1
  353. return value, valuelen
  354. def getNameFromIdent(self, identifier):
  355. rc = None
  356. for name in self.names:
  357. if self.names[name] == identifier:
  358. rc = name
  359. return rc
  360. def unpack(self, buffer):
  361. self.clear()
  362. # deserialize properties into attributes from buffer received from network
  363. propslen, VBIlen = VariableByteIntegers.decode(buffer)
  364. buffer = buffer[VBIlen:] # strip the bytes used by the VBI
  365. propslenleft = propslen
  366. while propslenleft > 0: # properties length is 0 if there are none
  367. identifier, VBIlen2 = VariableByteIntegers.decode(
  368. buffer) # property identifier
  369. buffer = buffer[VBIlen2:] # strip the bytes used by the VBI
  370. propslenleft -= VBIlen2
  371. attr_type = self.properties[identifier][0]
  372. value, valuelen = self.readProperty(
  373. buffer, attr_type, propslenleft)
  374. buffer = buffer[valuelen:] # strip the bytes used by the value
  375. propslenleft -= valuelen
  376. propname = self.getNameFromIdent(identifier)
  377. compressedName = propname.replace(' ', '')
  378. if not self.allowsMultiple(compressedName) and hasattr(self, compressedName):
  379. raise MQTTException(
  380. f"Property '{property}' must not exist more than once")
  381. setattr(self, propname, value)
  382. return self, propslen + VBIlen