properties.py 16 KB

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