index.js 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177
  1. module.exports = (function() {
  2. var __MODS__ = {};
  3. var __DEFINE__ = function(modId, func, req) { var m = { exports: {}, _tempexports: {} }; __MODS__[modId] = { status: 0, func: func, req: req, m: m }; };
  4. var __REQUIRE__ = function(modId, source) { if(!__MODS__[modId]) return require(source); if(!__MODS__[modId].status) { var m = __MODS__[modId].m; m._exports = m._tempexports; var desp = Object.getOwnPropertyDescriptor(m, "exports"); if (desp && desp.configurable) Object.defineProperty(m, "exports", { set: function (val) { if(typeof val === "object" && val !== m._exports) { m._exports.__proto__ = val.__proto__; Object.keys(val).forEach(function (k) { m._exports[k] = val[k]; }); } m._tempexports = val }, get: function () { return m._tempexports; } }); __MODS__[modId].status = 1; __MODS__[modId].func(__MODS__[modId].req, m, m.exports); } return __MODS__[modId].m.exports; };
  5. var __REQUIRE_WILDCARD__ = function(obj) { if(obj && obj.__esModule) { return obj; } else { var newObj = {}; if(obj != null) { for(var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) newObj[k] = obj[k]; } } newObj.default = obj; return newObj; } };
  6. var __REQUIRE_DEFAULT__ = function(obj) { return obj && obj.__esModule ? obj.default : obj; };
  7. __DEFINE__(1682324647504, function(require, module, exports) {
  8. exports.parser = require('./parser').parser
  9. exports.generate = require('./generate')
  10. exports.writeToStream = require('./writeToStream')
  11. }, function(modId) {var map = {"./parser":1682324647505,"./generate":1682324647508,"./writeToStream":1682324647509}; return __REQUIRE__(map[modId], modId); })
  12. __DEFINE__(1682324647505, function(require, module, exports) {
  13. const bl = require('bl')
  14. const EventEmitter = require('events')
  15. const Packet = require('./packet')
  16. const constants = require('./constants')
  17. const debug = require('debug')('mqtt-packet:parser')
  18. class Parser extends EventEmitter {
  19. constructor () {
  20. super()
  21. this.parser = this.constructor.parser
  22. }
  23. static parser (opt) {
  24. if (!(this instanceof Parser)) return (new Parser()).parser(opt)
  25. this.settings = opt || {}
  26. this._states = [
  27. '_parseHeader',
  28. '_parseLength',
  29. '_parsePayload',
  30. '_newPacket'
  31. ]
  32. this._resetState()
  33. return this
  34. }
  35. _resetState () {
  36. debug('_resetState: resetting packet, error, _list, and _stateCounter')
  37. this.packet = new Packet()
  38. this.error = null
  39. this._list = bl()
  40. this._stateCounter = 0
  41. }
  42. parse (buf) {
  43. if (this.error) this._resetState()
  44. this._list.append(buf)
  45. debug('parse: current state: %s', this._states[this._stateCounter])
  46. while ((this.packet.length !== -1 || this._list.length > 0) &&
  47. this[this._states[this._stateCounter]]() &&
  48. !this.error) {
  49. this._stateCounter++
  50. debug('parse: state complete. _stateCounter is now: %d', this._stateCounter)
  51. debug('parse: packet.length: %d, buffer list length: %d', this.packet.length, this._list.length)
  52. if (this._stateCounter >= this._states.length) this._stateCounter = 0
  53. }
  54. debug('parse: exited while loop. packet: %d, buffer list length: %d', this.packet.length, this._list.length)
  55. return this._list.length
  56. }
  57. _parseHeader () {
  58. // There is at least one byte in the buffer
  59. const zero = this._list.readUInt8(0)
  60. this.packet.cmd = constants.types[zero >> constants.CMD_SHIFT]
  61. this.packet.retain = (zero & constants.RETAIN_MASK) !== 0
  62. this.packet.qos = (zero >> constants.QOS_SHIFT) & constants.QOS_MASK
  63. this.packet.dup = (zero & constants.DUP_MASK) !== 0
  64. debug('_parseHeader: packet: %o', this.packet)
  65. this._list.consume(1)
  66. return true
  67. }
  68. _parseLength () {
  69. // There is at least one byte in the list
  70. const result = this._parseVarByteNum(true)
  71. if (result) {
  72. this.packet.length = result.value
  73. this._list.consume(result.bytes)
  74. }
  75. debug('_parseLength %d', result.value)
  76. return !!result
  77. }
  78. _parsePayload () {
  79. debug('_parsePayload: payload %O', this._list)
  80. let result = false
  81. // Do we have a payload? Do we have enough data to complete the payload?
  82. // PINGs have no payload
  83. if (this.packet.length === 0 || this._list.length >= this.packet.length) {
  84. this._pos = 0
  85. switch (this.packet.cmd) {
  86. case 'connect':
  87. this._parseConnect()
  88. break
  89. case 'connack':
  90. this._parseConnack()
  91. break
  92. case 'publish':
  93. this._parsePublish()
  94. break
  95. case 'puback':
  96. case 'pubrec':
  97. case 'pubrel':
  98. case 'pubcomp':
  99. this._parseConfirmation()
  100. break
  101. case 'subscribe':
  102. this._parseSubscribe()
  103. break
  104. case 'suback':
  105. this._parseSuback()
  106. break
  107. case 'unsubscribe':
  108. this._parseUnsubscribe()
  109. break
  110. case 'unsuback':
  111. this._parseUnsuback()
  112. break
  113. case 'pingreq':
  114. case 'pingresp':
  115. // These are empty, nothing to do
  116. break
  117. case 'disconnect':
  118. this._parseDisconnect()
  119. break
  120. case 'auth':
  121. this._parseAuth()
  122. break
  123. default:
  124. this._emitError(new Error('Not supported'))
  125. }
  126. result = true
  127. }
  128. debug('_parsePayload complete result: %s', result)
  129. return result
  130. }
  131. _parseConnect () {
  132. debug('_parseConnect')
  133. let topic // Will topic
  134. let payload // Will payload
  135. let password // Password
  136. let username // Username
  137. const flags = {}
  138. const packet = this.packet
  139. // Parse protocolId
  140. const protocolId = this._parseString()
  141. if (protocolId === null) return this._emitError(new Error('Cannot parse protocolId'))
  142. if (protocolId !== 'MQTT' && protocolId !== 'MQIsdp') {
  143. return this._emitError(new Error('Invalid protocolId'))
  144. }
  145. packet.protocolId = protocolId
  146. // Parse constants version number
  147. if (this._pos >= this._list.length) return this._emitError(new Error('Packet too short'))
  148. packet.protocolVersion = this._list.readUInt8(this._pos)
  149. if (packet.protocolVersion >= 128) {
  150. packet.bridgeMode = true
  151. packet.protocolVersion = packet.protocolVersion - 128
  152. }
  153. if (packet.protocolVersion !== 3 && packet.protocolVersion !== 4 && packet.protocolVersion !== 5) {
  154. return this._emitError(new Error('Invalid protocol version'))
  155. }
  156. this._pos++
  157. if (this._pos >= this._list.length) {
  158. return this._emitError(new Error('Packet too short'))
  159. }
  160. // Parse connect flags
  161. flags.username = (this._list.readUInt8(this._pos) & constants.USERNAME_MASK)
  162. flags.password = (this._list.readUInt8(this._pos) & constants.PASSWORD_MASK)
  163. flags.will = (this._list.readUInt8(this._pos) & constants.WILL_FLAG_MASK)
  164. if (flags.will) {
  165. packet.will = {}
  166. packet.will.retain = (this._list.readUInt8(this._pos) & constants.WILL_RETAIN_MASK) !== 0
  167. packet.will.qos = (this._list.readUInt8(this._pos) &
  168. constants.WILL_QOS_MASK) >> constants.WILL_QOS_SHIFT
  169. }
  170. packet.clean = (this._list.readUInt8(this._pos) & constants.CLEAN_SESSION_MASK) !== 0
  171. this._pos++
  172. // Parse keepalive
  173. packet.keepalive = this._parseNum()
  174. if (packet.keepalive === -1) return this._emitError(new Error('Packet too short'))
  175. // parse properties
  176. if (packet.protocolVersion === 5) {
  177. const properties = this._parseProperties()
  178. if (Object.getOwnPropertyNames(properties).length) {
  179. packet.properties = properties
  180. }
  181. }
  182. // Parse clientId
  183. const clientId = this._parseString()
  184. if (clientId === null) return this._emitError(new Error('Packet too short'))
  185. packet.clientId = clientId
  186. debug('_parseConnect: packet.clientId: %s', packet.clientId)
  187. if (flags.will) {
  188. if (packet.protocolVersion === 5) {
  189. const willProperties = this._parseProperties()
  190. if (Object.getOwnPropertyNames(willProperties).length) {
  191. packet.will.properties = willProperties
  192. }
  193. }
  194. // Parse will topic
  195. topic = this._parseString()
  196. if (topic === null) return this._emitError(new Error('Cannot parse will topic'))
  197. packet.will.topic = topic
  198. debug('_parseConnect: packet.will.topic: %s', packet.will.topic)
  199. // Parse will payload
  200. payload = this._parseBuffer()
  201. if (payload === null) return this._emitError(new Error('Cannot parse will payload'))
  202. packet.will.payload = payload
  203. debug('_parseConnect: packet.will.paylaod: %s', packet.will.payload)
  204. }
  205. // Parse username
  206. if (flags.username) {
  207. username = this._parseString()
  208. if (username === null) return this._emitError(new Error('Cannot parse username'))
  209. packet.username = username
  210. debug('_parseConnect: packet.username: %s', packet.username)
  211. }
  212. // Parse password
  213. if (flags.password) {
  214. password = this._parseBuffer()
  215. if (password === null) return this._emitError(new Error('Cannot parse password'))
  216. packet.password = password
  217. }
  218. // need for right parse auth packet and self set up
  219. this.settings = packet
  220. debug('_parseConnect: complete')
  221. return packet
  222. }
  223. _parseConnack () {
  224. debug('_parseConnack')
  225. const packet = this.packet
  226. if (this._list.length < 1) return null
  227. packet.sessionPresent = !!(this._list.readUInt8(this._pos++) & constants.SESSIONPRESENT_MASK)
  228. if (this.settings.protocolVersion === 5) {
  229. if (this._list.length >= 2) {
  230. packet.reasonCode = this._list.readUInt8(this._pos++)
  231. } else {
  232. packet.reasonCode = 0
  233. }
  234. } else {
  235. if (this._list.length < 2) return null
  236. packet.returnCode = this._list.readUInt8(this._pos++)
  237. }
  238. if (packet.returnCode === -1 || packet.reasonCode === -1) return this._emitError(new Error('Cannot parse return code'))
  239. // mqtt 5 properties
  240. if (this.settings.protocolVersion === 5) {
  241. const properties = this._parseProperties()
  242. if (Object.getOwnPropertyNames(properties).length) {
  243. packet.properties = properties
  244. }
  245. }
  246. debug('_parseConnack: complete')
  247. }
  248. _parsePublish () {
  249. debug('_parsePublish')
  250. const packet = this.packet
  251. packet.topic = this._parseString()
  252. if (packet.topic === null) return this._emitError(new Error('Cannot parse topic'))
  253. // Parse messageId
  254. if (packet.qos > 0) if (!this._parseMessageId()) { return }
  255. // Properties mqtt 5
  256. if (this.settings.protocolVersion === 5) {
  257. const properties = this._parseProperties()
  258. if (Object.getOwnPropertyNames(properties).length) {
  259. packet.properties = properties
  260. }
  261. }
  262. packet.payload = this._list.slice(this._pos, packet.length)
  263. debug('_parsePublish: payload from buffer list: %o', packet.payload)
  264. }
  265. _parseSubscribe () {
  266. debug('_parseSubscribe')
  267. const packet = this.packet
  268. let topic
  269. let options
  270. let qos
  271. let rh
  272. let rap
  273. let nl
  274. let subscription
  275. if (packet.qos !== 1) {
  276. return this._emitError(new Error('Wrong subscribe header'))
  277. }
  278. packet.subscriptions = []
  279. if (!this._parseMessageId()) { return }
  280. // Properties mqtt 5
  281. if (this.settings.protocolVersion === 5) {
  282. const properties = this._parseProperties()
  283. if (Object.getOwnPropertyNames(properties).length) {
  284. packet.properties = properties
  285. }
  286. }
  287. while (this._pos < packet.length) {
  288. // Parse topic
  289. topic = this._parseString()
  290. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  291. if (this._pos >= packet.length) return this._emitError(new Error('Malformed Subscribe Payload'))
  292. options = this._parseByte()
  293. qos = options & constants.SUBSCRIBE_OPTIONS_QOS_MASK
  294. nl = ((options >> constants.SUBSCRIBE_OPTIONS_NL_SHIFT) & constants.SUBSCRIBE_OPTIONS_NL_MASK) !== 0
  295. rap = ((options >> constants.SUBSCRIBE_OPTIONS_RAP_SHIFT) & constants.SUBSCRIBE_OPTIONS_RAP_MASK) !== 0
  296. rh = (options >> constants.SUBSCRIBE_OPTIONS_RH_SHIFT) & constants.SUBSCRIBE_OPTIONS_RH_MASK
  297. subscription = { topic, qos }
  298. // mqtt 5 options
  299. if (this.settings.protocolVersion === 5) {
  300. subscription.nl = nl
  301. subscription.rap = rap
  302. subscription.rh = rh
  303. } else if (this.settings.bridgeMode) {
  304. subscription.rh = 0
  305. subscription.rap = true
  306. subscription.nl = true
  307. }
  308. // Push pair to subscriptions
  309. debug('_parseSubscribe: push subscription `%s` to subscription', subscription)
  310. packet.subscriptions.push(subscription)
  311. }
  312. }
  313. _parseSuback () {
  314. debug('_parseSuback')
  315. const packet = this.packet
  316. this.packet.granted = []
  317. if (!this._parseMessageId()) { return }
  318. // Properties mqtt 5
  319. if (this.settings.protocolVersion === 5) {
  320. const properties = this._parseProperties()
  321. if (Object.getOwnPropertyNames(properties).length) {
  322. packet.properties = properties
  323. }
  324. }
  325. // Parse granted QoSes
  326. while (this._pos < this.packet.length) {
  327. this.packet.granted.push(this._list.readUInt8(this._pos++))
  328. }
  329. }
  330. _parseUnsubscribe () {
  331. debug('_parseUnsubscribe')
  332. const packet = this.packet
  333. packet.unsubscriptions = []
  334. // Parse messageId
  335. if (!this._parseMessageId()) { return }
  336. // Properties mqtt 5
  337. if (this.settings.protocolVersion === 5) {
  338. const properties = this._parseProperties()
  339. if (Object.getOwnPropertyNames(properties).length) {
  340. packet.properties = properties
  341. }
  342. }
  343. while (this._pos < packet.length) {
  344. // Parse topic
  345. const topic = this._parseString()
  346. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  347. // Push topic to unsubscriptions
  348. debug('_parseUnsubscribe: push topic `%s` to unsubscriptions', topic)
  349. packet.unsubscriptions.push(topic)
  350. }
  351. }
  352. _parseUnsuback () {
  353. debug('_parseUnsuback')
  354. const packet = this.packet
  355. if (!this._parseMessageId()) return this._emitError(new Error('Cannot parse messageId'))
  356. // Properties mqtt 5
  357. if (this.settings.protocolVersion === 5) {
  358. const properties = this._parseProperties()
  359. if (Object.getOwnPropertyNames(properties).length) {
  360. packet.properties = properties
  361. }
  362. // Parse granted QoSes
  363. packet.granted = []
  364. while (this._pos < this.packet.length) {
  365. this.packet.granted.push(this._list.readUInt8(this._pos++))
  366. }
  367. }
  368. }
  369. // parse packets like puback, pubrec, pubrel, pubcomp
  370. _parseConfirmation () {
  371. debug('_parseConfirmation: packet.cmd: `%s`', this.packet.cmd)
  372. const packet = this.packet
  373. this._parseMessageId()
  374. if (this.settings.protocolVersion === 5) {
  375. if (packet.length > 2) {
  376. // response code
  377. packet.reasonCode = this._parseByte()
  378. debug('_parseConfirmation: packet.reasonCode `%d`', packet.reasonCode)
  379. } else {
  380. packet.reasonCode = 0
  381. }
  382. if (packet.length > 3) {
  383. // properies mqtt 5
  384. const properties = this._parseProperties()
  385. if (Object.getOwnPropertyNames(properties).length) {
  386. packet.properties = properties
  387. }
  388. }
  389. }
  390. return true
  391. }
  392. // parse disconnect packet
  393. _parseDisconnect () {
  394. const packet = this.packet
  395. debug('_parseDisconnect')
  396. if (this.settings.protocolVersion === 5) {
  397. // response code
  398. if (this._list.length > 0) {
  399. packet.reasonCode = this._parseByte()
  400. } else {
  401. packet.reasonCode = 0
  402. }
  403. // properies mqtt 5
  404. const properties = this._parseProperties()
  405. if (Object.getOwnPropertyNames(properties).length) {
  406. packet.properties = properties
  407. }
  408. }
  409. debug('_parseDisconnect result: true')
  410. return true
  411. }
  412. // parse auth packet
  413. _parseAuth () {
  414. debug('_parseAuth')
  415. const packet = this.packet
  416. if (this.settings.protocolVersion !== 5) {
  417. return this._emitError(new Error('Not supported auth packet for this version MQTT'))
  418. }
  419. // response code
  420. packet.reasonCode = this._parseByte()
  421. // properies mqtt 5
  422. const properties = this._parseProperties()
  423. if (Object.getOwnPropertyNames(properties).length) {
  424. packet.properties = properties
  425. }
  426. debug('_parseAuth: result: true')
  427. return true
  428. }
  429. _parseMessageId () {
  430. const packet = this.packet
  431. packet.messageId = this._parseNum()
  432. if (packet.messageId === null) {
  433. this._emitError(new Error('Cannot parse messageId'))
  434. return false
  435. }
  436. debug('_parseMessageId: packet.messageId %d', packet.messageId)
  437. return true
  438. }
  439. _parseString (maybeBuffer) {
  440. const length = this._parseNum()
  441. const end = length + this._pos
  442. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  443. const result = this._list.toString('utf8', this._pos, end)
  444. this._pos += length
  445. debug('_parseString: result: %s', result)
  446. return result
  447. }
  448. _parseStringPair () {
  449. debug('_parseStringPair')
  450. return {
  451. name: this._parseString(),
  452. value: this._parseString()
  453. }
  454. }
  455. _parseBuffer () {
  456. const length = this._parseNum()
  457. const end = length + this._pos
  458. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  459. const result = this._list.slice(this._pos, end)
  460. this._pos += length
  461. debug('_parseBuffer: result: %o', result)
  462. return result
  463. }
  464. _parseNum () {
  465. if (this._list.length - this._pos < 2) return -1
  466. const result = this._list.readUInt16BE(this._pos)
  467. this._pos += 2
  468. debug('_parseNum: result: %s', result)
  469. return result
  470. }
  471. _parse4ByteNum () {
  472. if (this._list.length - this._pos < 4) return -1
  473. const result = this._list.readUInt32BE(this._pos)
  474. this._pos += 4
  475. debug('_parse4ByteNum: result: %s', result)
  476. return result
  477. }
  478. _parseVarByteNum (fullInfoFlag) {
  479. debug('_parseVarByteNum')
  480. const maxBytes = 4
  481. let bytes = 0
  482. let mul = 1
  483. let value = 0
  484. let result = false
  485. let current
  486. const padding = this._pos ? this._pos : 0
  487. while (bytes < maxBytes && (padding + bytes) < this._list.length) {
  488. current = this._list.readUInt8(padding + bytes++)
  489. value += mul * (current & constants.VARBYTEINT_MASK)
  490. mul *= 0x80
  491. if ((current & constants.VARBYTEINT_FIN_MASK) === 0) {
  492. result = true
  493. break
  494. }
  495. if (this._list.length <= bytes) {
  496. break
  497. }
  498. }
  499. if (!result && bytes === maxBytes && this._list.length >= bytes) {
  500. this._emitError(new Error('Invalid variable byte integer'))
  501. }
  502. if (padding) {
  503. this._pos += bytes
  504. }
  505. result = result
  506. ? fullInfoFlag ? {
  507. bytes,
  508. value
  509. } : value
  510. : false
  511. debug('_parseVarByteNum: result: %o', result)
  512. return result
  513. }
  514. _parseByte () {
  515. let result
  516. if (this._pos < this._list.length) {
  517. result = this._list.readUInt8(this._pos)
  518. this._pos++
  519. }
  520. debug('_parseByte: result: %o', result)
  521. return result
  522. }
  523. _parseByType (type) {
  524. debug('_parseByType: type: %s', type)
  525. switch (type) {
  526. case 'byte': {
  527. return this._parseByte() !== 0
  528. }
  529. case 'int8': {
  530. return this._parseByte()
  531. }
  532. case 'int16': {
  533. return this._parseNum()
  534. }
  535. case 'int32': {
  536. return this._parse4ByteNum()
  537. }
  538. case 'var': {
  539. return this._parseVarByteNum()
  540. }
  541. case 'string': {
  542. return this._parseString()
  543. }
  544. case 'pair': {
  545. return this._parseStringPair()
  546. }
  547. case 'binary': {
  548. return this._parseBuffer()
  549. }
  550. }
  551. }
  552. _parseProperties () {
  553. debug('_parseProperties')
  554. const length = this._parseVarByteNum()
  555. const start = this._pos
  556. const end = start + length
  557. const result = {}
  558. while (this._pos < end) {
  559. const type = this._parseByte()
  560. if (!type) {
  561. this._emitError(new Error('Cannot parse property code type'))
  562. return false
  563. }
  564. const name = constants.propertiesCodes[type]
  565. if (!name) {
  566. this._emitError(new Error('Unknown property'))
  567. return false
  568. }
  569. // user properties process
  570. if (name === 'userProperties') {
  571. if (!result[name]) {
  572. result[name] = Object.create(null)
  573. }
  574. const currentUserProperty = this._parseByType(constants.propertiesTypes[name])
  575. if (result[name][currentUserProperty.name]) {
  576. if (Array.isArray(result[name][currentUserProperty.name])) {
  577. result[name][currentUserProperty.name].push(currentUserProperty.value)
  578. } else {
  579. const currentValue = result[name][currentUserProperty.name]
  580. result[name][currentUserProperty.name] = [currentValue]
  581. result[name][currentUserProperty.name].push(currentUserProperty.value)
  582. }
  583. } else {
  584. result[name][currentUserProperty.name] = currentUserProperty.value
  585. }
  586. continue
  587. }
  588. if (result[name]) {
  589. if (Array.isArray(result[name])) {
  590. result[name].push(this._parseByType(constants.propertiesTypes[name]))
  591. } else {
  592. result[name] = [result[name]]
  593. result[name].push(this._parseByType(constants.propertiesTypes[name]))
  594. }
  595. } else {
  596. result[name] = this._parseByType(constants.propertiesTypes[name])
  597. }
  598. }
  599. return result
  600. }
  601. _newPacket () {
  602. debug('_newPacket')
  603. if (this.packet) {
  604. this._list.consume(this.packet.length)
  605. debug('_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d', this.packet.cmd, this.packet.payload, this.packet.length)
  606. this.emit('packet', this.packet)
  607. }
  608. debug('_newPacket: new packet')
  609. this.packet = new Packet()
  610. this._pos = 0
  611. return true
  612. }
  613. _emitError (err) {
  614. debug('_emitError')
  615. this.error = err
  616. this.emit('error', err)
  617. }
  618. }
  619. module.exports = Parser
  620. }, function(modId) { var map = {"./packet":1682324647506,"./constants":1682324647507}; return __REQUIRE__(map[modId], modId); })
  621. __DEFINE__(1682324647506, function(require, module, exports) {
  622. class Packet {
  623. constructor () {
  624. this.cmd = null
  625. this.retain = false
  626. this.qos = 0
  627. this.dup = false
  628. this.length = -1
  629. this.topic = null
  630. this.payload = null
  631. }
  632. }
  633. module.exports = Packet
  634. }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); })
  635. __DEFINE__(1682324647507, function(require, module, exports) {
  636. /* Protocol - protocol constants */
  637. const protocol = module.exports
  638. /* Command code => mnemonic */
  639. protocol.types = {
  640. 0: 'reserved',
  641. 1: 'connect',
  642. 2: 'connack',
  643. 3: 'publish',
  644. 4: 'puback',
  645. 5: 'pubrec',
  646. 6: 'pubrel',
  647. 7: 'pubcomp',
  648. 8: 'subscribe',
  649. 9: 'suback',
  650. 10: 'unsubscribe',
  651. 11: 'unsuback',
  652. 12: 'pingreq',
  653. 13: 'pingresp',
  654. 14: 'disconnect',
  655. 15: 'auth'
  656. }
  657. /* Mnemonic => Command code */
  658. protocol.codes = {}
  659. for (const k in protocol.types) {
  660. const v = protocol.types[k]
  661. protocol.codes[v] = k
  662. }
  663. /* Header */
  664. protocol.CMD_SHIFT = 4
  665. protocol.CMD_MASK = 0xF0
  666. protocol.DUP_MASK = 0x08
  667. protocol.QOS_MASK = 0x03
  668. protocol.QOS_SHIFT = 1
  669. protocol.RETAIN_MASK = 0x01
  670. /* Length */
  671. protocol.VARBYTEINT_MASK = 0x7F
  672. protocol.VARBYTEINT_FIN_MASK = 0x80
  673. protocol.VARBYTEINT_MAX = 268435455
  674. /* Connack */
  675. protocol.SESSIONPRESENT_MASK = 0x01
  676. protocol.SESSIONPRESENT_HEADER = Buffer.from([protocol.SESSIONPRESENT_MASK])
  677. protocol.CONNACK_HEADER = Buffer.from([protocol.codes.connack << protocol.CMD_SHIFT])
  678. /* Connect */
  679. protocol.USERNAME_MASK = 0x80
  680. protocol.PASSWORD_MASK = 0x40
  681. protocol.WILL_RETAIN_MASK = 0x20
  682. protocol.WILL_QOS_MASK = 0x18
  683. protocol.WILL_QOS_SHIFT = 3
  684. protocol.WILL_FLAG_MASK = 0x04
  685. protocol.CLEAN_SESSION_MASK = 0x02
  686. protocol.CONNECT_HEADER = Buffer.from([protocol.codes.connect << protocol.CMD_SHIFT])
  687. /* Properties */
  688. protocol.properties = {
  689. sessionExpiryInterval: 17,
  690. willDelayInterval: 24,
  691. receiveMaximum: 33,
  692. maximumPacketSize: 39,
  693. topicAliasMaximum: 34,
  694. requestResponseInformation: 25,
  695. requestProblemInformation: 23,
  696. userProperties: 38,
  697. authenticationMethod: 21,
  698. authenticationData: 22,
  699. payloadFormatIndicator: 1,
  700. messageExpiryInterval: 2,
  701. contentType: 3,
  702. responseTopic: 8,
  703. correlationData: 9,
  704. maximumQoS: 36,
  705. retainAvailable: 37,
  706. assignedClientIdentifier: 18,
  707. reasonString: 31,
  708. wildcardSubscriptionAvailable: 40,
  709. subscriptionIdentifiersAvailable: 41,
  710. sharedSubscriptionAvailable: 42,
  711. serverKeepAlive: 19,
  712. responseInformation: 26,
  713. serverReference: 28,
  714. topicAlias: 35,
  715. subscriptionIdentifier: 11
  716. }
  717. protocol.propertiesCodes = {}
  718. for (const prop in protocol.properties) {
  719. const id = protocol.properties[prop]
  720. protocol.propertiesCodes[id] = prop
  721. }
  722. protocol.propertiesTypes = {
  723. sessionExpiryInterval: 'int32',
  724. willDelayInterval: 'int32',
  725. receiveMaximum: 'int16',
  726. maximumPacketSize: 'int32',
  727. topicAliasMaximum: 'int16',
  728. requestResponseInformation: 'byte',
  729. requestProblemInformation: 'byte',
  730. userProperties: 'pair',
  731. authenticationMethod: 'string',
  732. authenticationData: 'binary',
  733. payloadFormatIndicator: 'byte',
  734. messageExpiryInterval: 'int32',
  735. contentType: 'string',
  736. responseTopic: 'string',
  737. correlationData: 'binary',
  738. maximumQoS: 'int8',
  739. retainAvailable: 'byte',
  740. assignedClientIdentifier: 'string',
  741. reasonString: 'string',
  742. wildcardSubscriptionAvailable: 'byte',
  743. subscriptionIdentifiersAvailable: 'byte',
  744. sharedSubscriptionAvailable: 'byte',
  745. serverKeepAlive: 'int16',
  746. responseInformation: 'string',
  747. serverReference: 'string',
  748. topicAlias: 'int16',
  749. subscriptionIdentifier: 'var'
  750. }
  751. function genHeader (type) {
  752. return [0, 1, 2].map(qos => {
  753. return [0, 1].map(dup => {
  754. return [0, 1].map(retain => {
  755. const buf = Buffer.alloc(1)
  756. buf.writeUInt8(
  757. protocol.codes[type] << protocol.CMD_SHIFT |
  758. (dup ? protocol.DUP_MASK : 0) |
  759. qos << protocol.QOS_SHIFT | retain, 0, true)
  760. return buf
  761. })
  762. })
  763. })
  764. }
  765. /* Publish */
  766. protocol.PUBLISH_HEADER = genHeader('publish')
  767. /* Subscribe */
  768. protocol.SUBSCRIBE_HEADER = genHeader('subscribe')
  769. protocol.SUBSCRIBE_OPTIONS_QOS_MASK = 0x03
  770. protocol.SUBSCRIBE_OPTIONS_NL_MASK = 0x01
  771. protocol.SUBSCRIBE_OPTIONS_NL_SHIFT = 2
  772. protocol.SUBSCRIBE_OPTIONS_RAP_MASK = 0x01
  773. protocol.SUBSCRIBE_OPTIONS_RAP_SHIFT = 3
  774. protocol.SUBSCRIBE_OPTIONS_RH_MASK = 0x03
  775. protocol.SUBSCRIBE_OPTIONS_RH_SHIFT = 4
  776. protocol.SUBSCRIBE_OPTIONS_RH = [0x00, 0x10, 0x20]
  777. protocol.SUBSCRIBE_OPTIONS_NL = 0x04
  778. protocol.SUBSCRIBE_OPTIONS_RAP = 0x08
  779. protocol.SUBSCRIBE_OPTIONS_QOS = [0x00, 0x01, 0x02]
  780. /* Unsubscribe */
  781. protocol.UNSUBSCRIBE_HEADER = genHeader('unsubscribe')
  782. /* Confirmations */
  783. protocol.ACKS = {
  784. unsuback: genHeader('unsuback'),
  785. puback: genHeader('puback'),
  786. pubcomp: genHeader('pubcomp'),
  787. pubrel: genHeader('pubrel'),
  788. pubrec: genHeader('pubrec')
  789. }
  790. protocol.SUBACK_HEADER = Buffer.from([protocol.codes.suback << protocol.CMD_SHIFT])
  791. /* Protocol versions */
  792. protocol.VERSION3 = Buffer.from([3])
  793. protocol.VERSION4 = Buffer.from([4])
  794. protocol.VERSION5 = Buffer.from([5])
  795. protocol.VERSION131 = Buffer.from([131])
  796. protocol.VERSION132 = Buffer.from([132])
  797. /* QoS */
  798. protocol.QOS = [0, 1, 2].map(qos => {
  799. return Buffer.from([qos])
  800. })
  801. /* Empty packets */
  802. protocol.EMPTY = {
  803. pingreq: Buffer.from([protocol.codes.pingreq << 4, 0]),
  804. pingresp: Buffer.from([protocol.codes.pingresp << 4, 0]),
  805. disconnect: Buffer.from([protocol.codes.disconnect << 4, 0])
  806. }
  807. }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); })
  808. __DEFINE__(1682324647508, function(require, module, exports) {
  809. const writeToStream = require('./writeToStream')
  810. const EventEmitter = require('events')
  811. function generate (packet, opts) {
  812. const stream = new Accumulator()
  813. writeToStream(packet, stream, opts)
  814. return stream.concat()
  815. }
  816. class Accumulator extends EventEmitter {
  817. constructor () {
  818. super()
  819. this._array = new Array(20)
  820. this._i = 0
  821. }
  822. write (chunk) {
  823. this._array[this._i++] = chunk
  824. return true
  825. }
  826. concat () {
  827. let length = 0
  828. const lengths = new Array(this._array.length)
  829. const list = this._array
  830. let pos = 0
  831. let i
  832. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  833. if (typeof list[i] !== 'string') lengths[i] = list[i].length
  834. else lengths[i] = Buffer.byteLength(list[i])
  835. length += lengths[i]
  836. }
  837. const result = Buffer.allocUnsafe(length)
  838. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  839. if (typeof list[i] !== 'string') {
  840. list[i].copy(result, pos)
  841. pos += lengths[i]
  842. } else {
  843. result.write(list[i], pos)
  844. pos += lengths[i]
  845. }
  846. }
  847. return result
  848. }
  849. }
  850. module.exports = generate
  851. }, function(modId) { var map = {"./writeToStream":1682324647509}; return __REQUIRE__(map[modId], modId); })
  852. __DEFINE__(1682324647509, function(require, module, exports) {
  853. const protocol = require('./constants')
  854. const empty = Buffer.allocUnsafe(0)
  855. const zeroBuf = Buffer.from([0])
  856. const numbers = require('./numbers')
  857. const nextTick = require('process-nextick-args').nextTick
  858. const debug = require('debug')('mqtt-packet:writeToStream')
  859. const numCache = numbers.cache
  860. const generateNumber = numbers.generateNumber
  861. const generateCache = numbers.generateCache
  862. const genBufVariableByteInt = numbers.genBufVariableByteInt
  863. const generate4ByteBuffer = numbers.generate4ByteBuffer
  864. let writeNumber = writeNumberCached
  865. let toGenerate = true
  866. function generate (packet, stream, opts) {
  867. debug('generate called')
  868. if (stream.cork) {
  869. stream.cork()
  870. nextTick(uncork, stream)
  871. }
  872. if (toGenerate) {
  873. toGenerate = false
  874. generateCache()
  875. }
  876. debug('generate: packet.cmd: %s', packet.cmd)
  877. switch (packet.cmd) {
  878. case 'connect':
  879. return connect(packet, stream, opts)
  880. case 'connack':
  881. return connack(packet, stream, opts)
  882. case 'publish':
  883. return publish(packet, stream, opts)
  884. case 'puback':
  885. case 'pubrec':
  886. case 'pubrel':
  887. case 'pubcomp':
  888. return confirmation(packet, stream, opts)
  889. case 'subscribe':
  890. return subscribe(packet, stream, opts)
  891. case 'suback':
  892. return suback(packet, stream, opts)
  893. case 'unsubscribe':
  894. return unsubscribe(packet, stream, opts)
  895. case 'unsuback':
  896. return unsuback(packet, stream, opts)
  897. case 'pingreq':
  898. case 'pingresp':
  899. return emptyPacket(packet, stream, opts)
  900. case 'disconnect':
  901. return disconnect(packet, stream, opts)
  902. case 'auth':
  903. return auth(packet, stream, opts)
  904. default:
  905. stream.emit('error', new Error('Unknown command'))
  906. return false
  907. }
  908. }
  909. /**
  910. * Controls numbers cache.
  911. * Set to "false" to allocate buffers on-the-flight instead of pre-generated cache
  912. */
  913. Object.defineProperty(generate, 'cacheNumbers', {
  914. get () {
  915. return writeNumber === writeNumberCached
  916. },
  917. set (value) {
  918. if (value) {
  919. if (!numCache || Object.keys(numCache).length === 0) toGenerate = true
  920. writeNumber = writeNumberCached
  921. } else {
  922. toGenerate = false
  923. writeNumber = writeNumberGenerated
  924. }
  925. }
  926. })
  927. function uncork (stream) {
  928. stream.uncork()
  929. }
  930. function connect (packet, stream, opts) {
  931. const settings = packet || {}
  932. const protocolId = settings.protocolId || 'MQTT'
  933. let protocolVersion = settings.protocolVersion || 4
  934. const will = settings.will
  935. let clean = settings.clean
  936. const keepalive = settings.keepalive || 0
  937. const clientId = settings.clientId || ''
  938. const username = settings.username
  939. const password = settings.password
  940. /* mqtt5 new oprions */
  941. const properties = settings.properties
  942. if (clean === undefined) clean = true
  943. let length = 0
  944. // Must be a string and non-falsy
  945. if (!protocolId ||
  946. (typeof protocolId !== 'string' && !Buffer.isBuffer(protocolId))) {
  947. stream.emit('error', new Error('Invalid protocolId'))
  948. return false
  949. } else length += protocolId.length + 2
  950. // Must be 3 or 4 or 5
  951. if (protocolVersion !== 3 && protocolVersion !== 4 && protocolVersion !== 5) {
  952. stream.emit('error', new Error('Invalid protocol version'))
  953. return false
  954. } else length += 1
  955. // ClientId might be omitted in 3.1.1 and 5, but only if cleanSession is set to 1
  956. if ((typeof clientId === 'string' || Buffer.isBuffer(clientId)) &&
  957. (clientId || protocolVersion >= 4) && (clientId || clean)) {
  958. length += Buffer.byteLength(clientId) + 2
  959. } else {
  960. if (protocolVersion < 4) {
  961. stream.emit('error', new Error('clientId must be supplied before 3.1.1'))
  962. return false
  963. }
  964. if ((clean * 1) === 0) {
  965. stream.emit('error', new Error('clientId must be given if cleanSession set to 0'))
  966. return false
  967. }
  968. }
  969. // Must be a two byte number
  970. if (typeof keepalive !== 'number' ||
  971. keepalive < 0 ||
  972. keepalive > 65535 ||
  973. keepalive % 1 !== 0) {
  974. stream.emit('error', new Error('Invalid keepalive'))
  975. return false
  976. } else length += 2
  977. // Connect flags
  978. length += 1
  979. // Properties
  980. if (protocolVersion === 5) {
  981. var propertiesData = getProperties(stream, properties)
  982. if (!propertiesData) { return false }
  983. length += propertiesData.length
  984. }
  985. // If will exists...
  986. if (will) {
  987. // It must be an object
  988. if (typeof will !== 'object') {
  989. stream.emit('error', new Error('Invalid will'))
  990. return false
  991. }
  992. // It must have topic typeof string
  993. if (!will.topic || typeof will.topic !== 'string') {
  994. stream.emit('error', new Error('Invalid will topic'))
  995. return false
  996. } else {
  997. length += Buffer.byteLength(will.topic) + 2
  998. }
  999. // Payload
  1000. length += 2 // payload length
  1001. if (will.payload) {
  1002. if (will.payload.length >= 0) {
  1003. if (typeof will.payload === 'string') {
  1004. length += Buffer.byteLength(will.payload)
  1005. } else {
  1006. length += will.payload.length
  1007. }
  1008. } else {
  1009. stream.emit('error', new Error('Invalid will payload'))
  1010. return false
  1011. }
  1012. }
  1013. // will properties
  1014. var willProperties = {}
  1015. if (protocolVersion === 5) {
  1016. willProperties = getProperties(stream, will.properties)
  1017. if (!willProperties) { return false }
  1018. length += willProperties.length
  1019. }
  1020. }
  1021. // Username
  1022. let providedUsername = false
  1023. if (username != null) {
  1024. if (isStringOrBuffer(username)) {
  1025. providedUsername = true
  1026. length += Buffer.byteLength(username) + 2
  1027. } else {
  1028. stream.emit('error', new Error('Invalid username'))
  1029. return false
  1030. }
  1031. }
  1032. // Password
  1033. if (password != null) {
  1034. if (!providedUsername) {
  1035. stream.emit('error', new Error('Username is required to use password'))
  1036. return false
  1037. }
  1038. if (isStringOrBuffer(password)) {
  1039. length += byteLength(password) + 2
  1040. } else {
  1041. stream.emit('error', new Error('Invalid password'))
  1042. return false
  1043. }
  1044. }
  1045. // Generate header
  1046. stream.write(protocol.CONNECT_HEADER)
  1047. // Generate length
  1048. writeVarByteInt(stream, length)
  1049. // Generate protocol ID
  1050. writeStringOrBuffer(stream, protocolId)
  1051. if (settings.bridgeMode) {
  1052. protocolVersion += 128
  1053. }
  1054. stream.write(
  1055. protocolVersion === 131
  1056. ? protocol.VERSION131
  1057. : protocolVersion === 132
  1058. ? protocol.VERSION132
  1059. : protocolVersion === 4
  1060. ? protocol.VERSION4
  1061. : protocolVersion === 5
  1062. ? protocol.VERSION5
  1063. : protocol.VERSION3
  1064. )
  1065. // Connect flags
  1066. let flags = 0
  1067. flags |= (username != null) ? protocol.USERNAME_MASK : 0
  1068. flags |= (password != null) ? protocol.PASSWORD_MASK : 0
  1069. flags |= (will && will.retain) ? protocol.WILL_RETAIN_MASK : 0
  1070. flags |= (will && will.qos) ? will.qos << protocol.WILL_QOS_SHIFT : 0
  1071. flags |= will ? protocol.WILL_FLAG_MASK : 0
  1072. flags |= clean ? protocol.CLEAN_SESSION_MASK : 0
  1073. stream.write(Buffer.from([flags]))
  1074. // Keepalive
  1075. writeNumber(stream, keepalive)
  1076. // Properties
  1077. if (protocolVersion === 5) {
  1078. propertiesData.write()
  1079. }
  1080. // Client ID
  1081. writeStringOrBuffer(stream, clientId)
  1082. // Will
  1083. if (will) {
  1084. if (protocolVersion === 5) {
  1085. willProperties.write()
  1086. }
  1087. writeString(stream, will.topic)
  1088. writeStringOrBuffer(stream, will.payload)
  1089. }
  1090. // Username and password
  1091. if (username != null) {
  1092. writeStringOrBuffer(stream, username)
  1093. }
  1094. if (password != null) {
  1095. writeStringOrBuffer(stream, password)
  1096. }
  1097. // This is a small packet that happens only once on a stream
  1098. // We assume the stream is always free to receive more data after this
  1099. return true
  1100. }
  1101. function connack (packet, stream, opts) {
  1102. const version = opts ? opts.protocolVersion : 4
  1103. const settings = packet || {}
  1104. const rc = version === 5 ? settings.reasonCode : settings.returnCode
  1105. const properties = settings.properties
  1106. let length = 2 // length of rc and sessionHeader
  1107. // Check return code
  1108. if (typeof rc !== 'number') {
  1109. stream.emit('error', new Error('Invalid return code'))
  1110. return false
  1111. }
  1112. // mqtt5 properties
  1113. let propertiesData = null
  1114. if (version === 5) {
  1115. propertiesData = getProperties(stream, properties)
  1116. if (!propertiesData) { return false }
  1117. length += propertiesData.length
  1118. }
  1119. stream.write(protocol.CONNACK_HEADER)
  1120. // length
  1121. writeVarByteInt(stream, length)
  1122. stream.write(settings.sessionPresent ? protocol.SESSIONPRESENT_HEADER : zeroBuf)
  1123. stream.write(Buffer.from([rc]))
  1124. if (propertiesData != null) {
  1125. propertiesData.write()
  1126. }
  1127. return true
  1128. }
  1129. function publish (packet, stream, opts) {
  1130. debug('publish: packet: %o', packet)
  1131. const version = opts ? opts.protocolVersion : 4
  1132. const settings = packet || {}
  1133. const qos = settings.qos || 0
  1134. const retain = settings.retain ? protocol.RETAIN_MASK : 0
  1135. const topic = settings.topic
  1136. const payload = settings.payload || empty
  1137. const id = settings.messageId
  1138. const properties = settings.properties
  1139. let length = 0
  1140. // Topic must be a non-empty string or Buffer
  1141. if (typeof topic === 'string') length += Buffer.byteLength(topic) + 2
  1142. else if (Buffer.isBuffer(topic)) length += topic.length + 2
  1143. else {
  1144. stream.emit('error', new Error('Invalid topic'))
  1145. return false
  1146. }
  1147. // Get the payload length
  1148. if (!Buffer.isBuffer(payload)) length += Buffer.byteLength(payload)
  1149. else length += payload.length
  1150. // Message ID must a number if qos > 0
  1151. if (qos && typeof id !== 'number') {
  1152. stream.emit('error', new Error('Invalid messageId'))
  1153. return false
  1154. } else if (qos) length += 2
  1155. // mqtt5 properties
  1156. let propertiesData = null
  1157. if (version === 5) {
  1158. propertiesData = getProperties(stream, properties)
  1159. if (!propertiesData) { return false }
  1160. length += propertiesData.length
  1161. }
  1162. // Header
  1163. stream.write(protocol.PUBLISH_HEADER[qos][settings.dup ? 1 : 0][retain ? 1 : 0])
  1164. // Remaining length
  1165. writeVarByteInt(stream, length)
  1166. // Topic
  1167. writeNumber(stream, byteLength(topic))
  1168. stream.write(topic)
  1169. // Message ID
  1170. if (qos > 0) writeNumber(stream, id)
  1171. // Properties
  1172. if (propertiesData != null) {
  1173. propertiesData.write()
  1174. }
  1175. // Payload
  1176. debug('publish: payload: %o', payload)
  1177. return stream.write(payload)
  1178. }
  1179. /* Puback, pubrec, pubrel and pubcomp */
  1180. function confirmation (packet, stream, opts) {
  1181. const version = opts ? opts.protocolVersion : 4
  1182. const settings = packet || {}
  1183. const type = settings.cmd || 'puback'
  1184. const id = settings.messageId
  1185. const dup = (settings.dup && type === 'pubrel') ? protocol.DUP_MASK : 0
  1186. let qos = 0
  1187. const reasonCode = settings.reasonCode
  1188. const properties = settings.properties
  1189. let length = version === 5 ? 3 : 2
  1190. if (type === 'pubrel') qos = 1
  1191. // Check message ID
  1192. if (typeof id !== 'number') {
  1193. stream.emit('error', new Error('Invalid messageId'))
  1194. return false
  1195. }
  1196. // properies mqtt 5
  1197. let propertiesData = null
  1198. if (version === 5) {
  1199. // Confirm should not add empty property length with no properties (rfc 3.4.2.2.1)
  1200. if (typeof properties === 'object') {
  1201. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  1202. if (!propertiesData) { return false }
  1203. length += propertiesData.length
  1204. }
  1205. }
  1206. // Header
  1207. stream.write(protocol.ACKS[type][qos][dup][0])
  1208. // Length
  1209. writeVarByteInt(stream, length)
  1210. // Message ID
  1211. writeNumber(stream, id)
  1212. // reason code in header
  1213. if (version === 5) {
  1214. stream.write(Buffer.from([reasonCode]))
  1215. }
  1216. // properies mqtt 5
  1217. if (propertiesData !== null) {
  1218. propertiesData.write()
  1219. }
  1220. return true
  1221. }
  1222. function subscribe (packet, stream, opts) {
  1223. debug('subscribe: packet: ')
  1224. const version = opts ? opts.protocolVersion : 4
  1225. const settings = packet || {}
  1226. const dup = settings.dup ? protocol.DUP_MASK : 0
  1227. const id = settings.messageId
  1228. const subs = settings.subscriptions
  1229. const properties = settings.properties
  1230. let length = 0
  1231. // Check message ID
  1232. if (typeof id !== 'number') {
  1233. stream.emit('error', new Error('Invalid messageId'))
  1234. return false
  1235. } else length += 2
  1236. // properies mqtt 5
  1237. let propertiesData = null
  1238. if (version === 5) {
  1239. propertiesData = getProperties(stream, properties)
  1240. if (!propertiesData) { return false }
  1241. length += propertiesData.length
  1242. }
  1243. // Check subscriptions
  1244. if (typeof subs === 'object' && subs.length) {
  1245. for (let i = 0; i < subs.length; i += 1) {
  1246. const itopic = subs[i].topic
  1247. const iqos = subs[i].qos
  1248. if (typeof itopic !== 'string') {
  1249. stream.emit('error', new Error('Invalid subscriptions - invalid topic'))
  1250. return false
  1251. }
  1252. if (typeof iqos !== 'number') {
  1253. stream.emit('error', new Error('Invalid subscriptions - invalid qos'))
  1254. return false
  1255. }
  1256. if (version === 5) {
  1257. const nl = subs[i].nl || false
  1258. if (typeof nl !== 'boolean') {
  1259. stream.emit('error', new Error('Invalid subscriptions - invalid No Local'))
  1260. return false
  1261. }
  1262. const rap = subs[i].rap || false
  1263. if (typeof rap !== 'boolean') {
  1264. stream.emit('error', new Error('Invalid subscriptions - invalid Retain as Published'))
  1265. return false
  1266. }
  1267. const rh = subs[i].rh || 0
  1268. if (typeof rh !== 'number' || rh > 2) {
  1269. stream.emit('error', new Error('Invalid subscriptions - invalid Retain Handling'))
  1270. return false
  1271. }
  1272. }
  1273. length += Buffer.byteLength(itopic) + 2 + 1
  1274. }
  1275. } else {
  1276. stream.emit('error', new Error('Invalid subscriptions'))
  1277. return false
  1278. }
  1279. // Generate header
  1280. debug('subscribe: writing to stream: %o', protocol.SUBSCRIBE_HEADER)
  1281. stream.write(protocol.SUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  1282. // Generate length
  1283. writeVarByteInt(stream, length)
  1284. // Generate message ID
  1285. writeNumber(stream, id)
  1286. // properies mqtt 5
  1287. if (propertiesData !== null) {
  1288. propertiesData.write()
  1289. }
  1290. let result = true
  1291. // Generate subs
  1292. for (const sub of subs) {
  1293. const jtopic = sub.topic
  1294. const jqos = sub.qos
  1295. const jnl = +sub.nl
  1296. const jrap = +sub.rap
  1297. const jrh = sub.rh
  1298. let joptions
  1299. // Write topic string
  1300. writeString(stream, jtopic)
  1301. // options process
  1302. joptions = protocol.SUBSCRIBE_OPTIONS_QOS[jqos]
  1303. if (version === 5) {
  1304. joptions |= jnl ? protocol.SUBSCRIBE_OPTIONS_NL : 0
  1305. joptions |= jrap ? protocol.SUBSCRIBE_OPTIONS_RAP : 0
  1306. joptions |= jrh ? protocol.SUBSCRIBE_OPTIONS_RH[jrh] : 0
  1307. }
  1308. // Write options
  1309. result = stream.write(Buffer.from([joptions]))
  1310. }
  1311. return result
  1312. }
  1313. function suback (packet, stream, opts) {
  1314. const version = opts ? opts.protocolVersion : 4
  1315. const settings = packet || {}
  1316. const id = settings.messageId
  1317. const granted = settings.granted
  1318. const properties = settings.properties
  1319. let length = 0
  1320. // Check message ID
  1321. if (typeof id !== 'number') {
  1322. stream.emit('error', new Error('Invalid messageId'))
  1323. return false
  1324. } else length += 2
  1325. // Check granted qos vector
  1326. if (typeof granted === 'object' && granted.length) {
  1327. for (let i = 0; i < granted.length; i += 1) {
  1328. if (typeof granted[i] !== 'number') {
  1329. stream.emit('error', new Error('Invalid qos vector'))
  1330. return false
  1331. }
  1332. length += 1
  1333. }
  1334. } else {
  1335. stream.emit('error', new Error('Invalid qos vector'))
  1336. return false
  1337. }
  1338. // properies mqtt 5
  1339. let propertiesData = null
  1340. if (version === 5) {
  1341. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  1342. if (!propertiesData) { return false }
  1343. length += propertiesData.length
  1344. }
  1345. // header
  1346. stream.write(protocol.SUBACK_HEADER)
  1347. // Length
  1348. writeVarByteInt(stream, length)
  1349. // Message ID
  1350. writeNumber(stream, id)
  1351. // properies mqtt 5
  1352. if (propertiesData !== null) {
  1353. propertiesData.write()
  1354. }
  1355. return stream.write(Buffer.from(granted))
  1356. }
  1357. function unsubscribe (packet, stream, opts) {
  1358. const version = opts ? opts.protocolVersion : 4
  1359. const settings = packet || {}
  1360. const id = settings.messageId
  1361. const dup = settings.dup ? protocol.DUP_MASK : 0
  1362. const unsubs = settings.unsubscriptions
  1363. const properties = settings.properties
  1364. let length = 0
  1365. // Check message ID
  1366. if (typeof id !== 'number') {
  1367. stream.emit('error', new Error('Invalid messageId'))
  1368. return false
  1369. } else {
  1370. length += 2
  1371. }
  1372. // Check unsubs
  1373. if (typeof unsubs === 'object' && unsubs.length) {
  1374. for (let i = 0; i < unsubs.length; i += 1) {
  1375. if (typeof unsubs[i] !== 'string') {
  1376. stream.emit('error', new Error('Invalid unsubscriptions'))
  1377. return false
  1378. }
  1379. length += Buffer.byteLength(unsubs[i]) + 2
  1380. }
  1381. } else {
  1382. stream.emit('error', new Error('Invalid unsubscriptions'))
  1383. return false
  1384. }
  1385. // properies mqtt 5
  1386. let propertiesData = null
  1387. if (version === 5) {
  1388. propertiesData = getProperties(stream, properties)
  1389. if (!propertiesData) { return false }
  1390. length += propertiesData.length
  1391. }
  1392. // Header
  1393. stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  1394. // Length
  1395. writeVarByteInt(stream, length)
  1396. // Message ID
  1397. writeNumber(stream, id)
  1398. // properies mqtt 5
  1399. if (propertiesData !== null) {
  1400. propertiesData.write()
  1401. }
  1402. // Unsubs
  1403. let result = true
  1404. for (let j = 0; j < unsubs.length; j++) {
  1405. result = writeString(stream, unsubs[j])
  1406. }
  1407. return result
  1408. }
  1409. function unsuback (packet, stream, opts) {
  1410. const version = opts ? opts.protocolVersion : 4
  1411. const settings = packet || {}
  1412. const id = settings.messageId
  1413. const dup = settings.dup ? protocol.DUP_MASK : 0
  1414. const granted = settings.granted
  1415. const properties = settings.properties
  1416. const type = settings.cmd
  1417. const qos = 0
  1418. let length = 2
  1419. // Check message ID
  1420. if (typeof id !== 'number') {
  1421. stream.emit('error', new Error('Invalid messageId'))
  1422. return false
  1423. }
  1424. // Check granted
  1425. if (version === 5) {
  1426. if (typeof granted === 'object' && granted.length) {
  1427. for (let i = 0; i < granted.length; i += 1) {
  1428. if (typeof granted[i] !== 'number') {
  1429. stream.emit('error', new Error('Invalid qos vector'))
  1430. return false
  1431. }
  1432. length += 1
  1433. }
  1434. } else {
  1435. stream.emit('error', new Error('Invalid qos vector'))
  1436. return false
  1437. }
  1438. }
  1439. // properies mqtt 5
  1440. let propertiesData = null
  1441. if (version === 5) {
  1442. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  1443. if (!propertiesData) { return false }
  1444. length += propertiesData.length
  1445. }
  1446. // Header
  1447. stream.write(protocol.ACKS[type][qos][dup][0])
  1448. // Length
  1449. writeVarByteInt(stream, length)
  1450. // Message ID
  1451. writeNumber(stream, id)
  1452. // properies mqtt 5
  1453. if (propertiesData !== null) {
  1454. propertiesData.write()
  1455. }
  1456. // payload
  1457. if (version === 5) {
  1458. stream.write(Buffer.from(granted))
  1459. }
  1460. return true
  1461. }
  1462. function emptyPacket (packet, stream, opts) {
  1463. return stream.write(protocol.EMPTY[packet.cmd])
  1464. }
  1465. function disconnect (packet, stream, opts) {
  1466. const version = opts ? opts.protocolVersion : 4
  1467. const settings = packet || {}
  1468. const reasonCode = settings.reasonCode
  1469. const properties = settings.properties
  1470. let length = version === 5 ? 1 : 0
  1471. // properies mqtt 5
  1472. let propertiesData = null
  1473. if (version === 5) {
  1474. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  1475. if (!propertiesData) { return false }
  1476. length += propertiesData.length
  1477. }
  1478. // Header
  1479. stream.write(Buffer.from([protocol.codes.disconnect << 4]))
  1480. // Length
  1481. writeVarByteInt(stream, length)
  1482. // reason code in header
  1483. if (version === 5) {
  1484. stream.write(Buffer.from([reasonCode]))
  1485. }
  1486. // properies mqtt 5
  1487. if (propertiesData !== null) {
  1488. propertiesData.write()
  1489. }
  1490. return true
  1491. }
  1492. function auth (packet, stream, opts) {
  1493. const version = opts ? opts.protocolVersion : 4
  1494. const settings = packet || {}
  1495. const reasonCode = settings.reasonCode
  1496. const properties = settings.properties
  1497. let length = version === 5 ? 1 : 0
  1498. if (version !== 5) stream.emit('error', new Error('Invalid mqtt version for auth packet'))
  1499. // properies mqtt 5
  1500. const propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  1501. if (!propertiesData) { return false }
  1502. length += propertiesData.length
  1503. // Header
  1504. stream.write(Buffer.from([protocol.codes.auth << 4]))
  1505. // Length
  1506. writeVarByteInt(stream, length)
  1507. // reason code in header
  1508. stream.write(Buffer.from([reasonCode]))
  1509. // properies mqtt 5
  1510. if (propertiesData !== null) {
  1511. propertiesData.write()
  1512. }
  1513. return true
  1514. }
  1515. /**
  1516. * writeVarByteInt - write an MQTT style variable byte integer to the buffer
  1517. *
  1518. * @param <Buffer> buffer - destination
  1519. * @param <Number> pos - offset
  1520. * @param <Number> length - length (>0)
  1521. * @returns <Number> number of bytes written
  1522. *
  1523. * @api private
  1524. */
  1525. const varByteIntCache = {}
  1526. function writeVarByteInt (stream, num) {
  1527. if (num > protocol.VARBYTEINT_MAX) {
  1528. stream.emit('error', new Error(`Invalid variable byte integer: ${num}`))
  1529. return false
  1530. }
  1531. let buffer = varByteIntCache[num]
  1532. if (!buffer) {
  1533. buffer = genBufVariableByteInt(num)
  1534. if (num < 16384) varByteIntCache[num] = buffer
  1535. }
  1536. debug('writeVarByteInt: writing to stream: %o', buffer)
  1537. return stream.write(buffer)
  1538. }
  1539. /**
  1540. * writeString - write a utf8 string to the buffer
  1541. *
  1542. * @param <Buffer> buffer - destination
  1543. * @param <Number> pos - offset
  1544. * @param <String> string - string to write
  1545. * @return <Number> number of bytes written
  1546. *
  1547. * @api private
  1548. */
  1549. function writeString (stream, string) {
  1550. const strlen = Buffer.byteLength(string)
  1551. writeNumber(stream, strlen)
  1552. debug('writeString: %s', string)
  1553. return stream.write(string, 'utf8')
  1554. }
  1555. /**
  1556. * writeStringPair - write a utf8 string pairs to the buffer
  1557. *
  1558. * @param <Buffer> buffer - destination
  1559. * @param <String> name - string name to write
  1560. * @param <String> value - string value to write
  1561. * @return <Number> number of bytes written
  1562. *
  1563. * @api private
  1564. */
  1565. function writeStringPair (stream, name, value) {
  1566. writeString(stream, name)
  1567. writeString(stream, value)
  1568. }
  1569. /**
  1570. * writeNumber - write a two byte number to the buffer
  1571. *
  1572. * @param <Buffer> buffer - destination
  1573. * @param <Number> pos - offset
  1574. * @param <String> number - number to write
  1575. * @return <Number> number of bytes written
  1576. *
  1577. * @api private
  1578. */
  1579. function writeNumberCached (stream, number) {
  1580. debug('writeNumberCached: number: %d', number)
  1581. debug('writeNumberCached: %o', numCache[number])
  1582. return stream.write(numCache[number])
  1583. }
  1584. function writeNumberGenerated (stream, number) {
  1585. const generatedNumber = generateNumber(number)
  1586. debug('writeNumberGenerated: %o', generatedNumber)
  1587. return stream.write(generatedNumber)
  1588. }
  1589. function write4ByteNumber (stream, number) {
  1590. const generated4ByteBuffer = generate4ByteBuffer(number)
  1591. debug('write4ByteNumber: %o', generated4ByteBuffer)
  1592. return stream.write(generated4ByteBuffer)
  1593. }
  1594. /**
  1595. * writeStringOrBuffer - write a String or Buffer with the its length prefix
  1596. *
  1597. * @param <Buffer> buffer - destination
  1598. * @param <Number> pos - offset
  1599. * @param <String> toWrite - String or Buffer
  1600. * @return <Number> number of bytes written
  1601. */
  1602. function writeStringOrBuffer (stream, toWrite) {
  1603. if (typeof toWrite === 'string') {
  1604. writeString(stream, toWrite)
  1605. } else if (toWrite) {
  1606. writeNumber(stream, toWrite.length)
  1607. stream.write(toWrite)
  1608. } else writeNumber(stream, 0)
  1609. }
  1610. function getProperties (stream, properties) {
  1611. /* connect properties */
  1612. if (typeof properties !== 'object' || properties.length != null) {
  1613. return {
  1614. length: 1,
  1615. write () {
  1616. writeProperties(stream, {}, 0)
  1617. }
  1618. }
  1619. }
  1620. let propertiesLength = 0
  1621. function getLengthProperty (name, value) {
  1622. const type = protocol.propertiesTypes[name]
  1623. let length = 0
  1624. switch (type) {
  1625. case 'byte': {
  1626. if (typeof value !== 'boolean') {
  1627. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  1628. return false
  1629. }
  1630. length += 1 + 1
  1631. break
  1632. }
  1633. case 'int8': {
  1634. if (typeof value !== 'number' || value < 0 || value > 0xff) {
  1635. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  1636. return false
  1637. }
  1638. length += 1 + 1
  1639. break
  1640. }
  1641. case 'binary': {
  1642. if (value && value === null) {
  1643. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  1644. return false
  1645. }
  1646. length += 1 + Buffer.byteLength(value) + 2
  1647. break
  1648. }
  1649. case 'int16': {
  1650. if (typeof value !== 'number' || value < 0 || value > 0xffff) {
  1651. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  1652. return false
  1653. }
  1654. length += 1 + 2
  1655. break
  1656. }
  1657. case 'int32': {
  1658. if (typeof value !== 'number' || value < 0 || value > 0xffffffff) {
  1659. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  1660. return false
  1661. }
  1662. length += 1 + 4
  1663. break
  1664. }
  1665. case 'var': {
  1666. // var byte integer is max 24 bits packed in 32 bits
  1667. if (typeof value !== 'number' || value < 0 || value > 0x0fffffff) {
  1668. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  1669. return false
  1670. }
  1671. length += 1 + Buffer.byteLength(genBufVariableByteInt(value))
  1672. break
  1673. }
  1674. case 'string': {
  1675. if (typeof value !== 'string') {
  1676. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  1677. return false
  1678. }
  1679. length += 1 + 2 + Buffer.byteLength(value.toString())
  1680. break
  1681. }
  1682. case 'pair': {
  1683. if (typeof value !== 'object') {
  1684. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  1685. return false
  1686. }
  1687. length += Object.getOwnPropertyNames(value).reduce((result, name) => {
  1688. const currentValue = value[name]
  1689. if (Array.isArray(currentValue)) {
  1690. result += currentValue.reduce((currentLength, value) => {
  1691. currentLength += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value.toString())
  1692. return currentLength
  1693. }, 0)
  1694. } else {
  1695. result += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value[name].toString())
  1696. }
  1697. return result
  1698. }, 0)
  1699. break
  1700. }
  1701. default: {
  1702. stream.emit('error', new Error(`Invalid property ${name}: ${value}`))
  1703. return false
  1704. }
  1705. }
  1706. return length
  1707. }
  1708. if (properties) {
  1709. for (const propName in properties) {
  1710. let propLength = 0
  1711. let propValueLength = 0
  1712. const propValue = properties[propName]
  1713. if (Array.isArray(propValue)) {
  1714. for (let valueIndex = 0; valueIndex < propValue.length; valueIndex++) {
  1715. propValueLength = getLengthProperty(propName, propValue[valueIndex])
  1716. if (!propValueLength) { return false }
  1717. propLength += propValueLength
  1718. }
  1719. } else {
  1720. propValueLength = getLengthProperty(propName, propValue)
  1721. if (!propValueLength) { return false }
  1722. propLength = propValueLength
  1723. }
  1724. if (!propLength) return false
  1725. propertiesLength += propLength
  1726. }
  1727. }
  1728. const propertiesLengthLength = Buffer.byteLength(genBufVariableByteInt(propertiesLength))
  1729. return {
  1730. length: propertiesLengthLength + propertiesLength,
  1731. write () {
  1732. writeProperties(stream, properties, propertiesLength)
  1733. }
  1734. }
  1735. }
  1736. function getPropertiesByMaximumPacketSize (stream, properties, opts, length) {
  1737. const mayEmptyProps = ['reasonString', 'userProperties']
  1738. const maximumPacketSize = opts && opts.properties && opts.properties.maximumPacketSize ? opts.properties.maximumPacketSize : 0
  1739. let propertiesData = getProperties(stream, properties)
  1740. if (maximumPacketSize) {
  1741. while (length + propertiesData.length > maximumPacketSize) {
  1742. const currentMayEmptyProp = mayEmptyProps.shift()
  1743. if (currentMayEmptyProp && properties[currentMayEmptyProp]) {
  1744. delete properties[currentMayEmptyProp]
  1745. propertiesData = getProperties(stream, properties)
  1746. } else {
  1747. return false
  1748. }
  1749. }
  1750. }
  1751. return propertiesData
  1752. }
  1753. function writeProperty (stream, propName, value) {
  1754. const type = protocol.propertiesTypes[propName]
  1755. switch (type) {
  1756. case 'byte': {
  1757. stream.write(Buffer.from([protocol.properties[propName]]))
  1758. stream.write(Buffer.from([+value]))
  1759. break
  1760. }
  1761. case 'int8': {
  1762. stream.write(Buffer.from([protocol.properties[propName]]))
  1763. stream.write(Buffer.from([value]))
  1764. break
  1765. }
  1766. case 'binary': {
  1767. stream.write(Buffer.from([protocol.properties[propName]]))
  1768. writeStringOrBuffer(stream, value)
  1769. break
  1770. }
  1771. case 'int16': {
  1772. stream.write(Buffer.from([protocol.properties[propName]]))
  1773. writeNumber(stream, value)
  1774. break
  1775. }
  1776. case 'int32': {
  1777. stream.write(Buffer.from([protocol.properties[propName]]))
  1778. write4ByteNumber(stream, value)
  1779. break
  1780. }
  1781. case 'var': {
  1782. stream.write(Buffer.from([protocol.properties[propName]]))
  1783. writeVarByteInt(stream, value)
  1784. break
  1785. }
  1786. case 'string': {
  1787. stream.write(Buffer.from([protocol.properties[propName]]))
  1788. writeString(stream, value)
  1789. break
  1790. }
  1791. case 'pair': {
  1792. Object.getOwnPropertyNames(value).forEach(name => {
  1793. const currentValue = value[name]
  1794. if (Array.isArray(currentValue)) {
  1795. currentValue.forEach(value => {
  1796. stream.write(Buffer.from([protocol.properties[propName]]))
  1797. writeStringPair(stream, name.toString(), value.toString())
  1798. })
  1799. } else {
  1800. stream.write(Buffer.from([protocol.properties[propName]]))
  1801. writeStringPair(stream, name.toString(), currentValue.toString())
  1802. }
  1803. })
  1804. break
  1805. }
  1806. default: {
  1807. stream.emit('error', new Error(`Invalid property ${propName} value: ${value}`))
  1808. return false
  1809. }
  1810. }
  1811. }
  1812. function writeProperties (stream, properties, propertiesLength) {
  1813. /* write properties to stream */
  1814. writeVarByteInt(stream, propertiesLength)
  1815. for (const propName in properties) {
  1816. if (Object.prototype.hasOwnProperty.call(properties, propName) && properties[propName] !== null) {
  1817. const value = properties[propName]
  1818. if (Array.isArray(value)) {
  1819. for (let valueIndex = 0; valueIndex < value.length; valueIndex++) {
  1820. writeProperty(stream, propName, value[valueIndex])
  1821. }
  1822. } else {
  1823. writeProperty(stream, propName, value)
  1824. }
  1825. }
  1826. }
  1827. }
  1828. function byteLength (bufOrString) {
  1829. if (!bufOrString) return 0
  1830. else if (bufOrString instanceof Buffer) return bufOrString.length
  1831. else return Buffer.byteLength(bufOrString)
  1832. }
  1833. function isStringOrBuffer (field) {
  1834. return typeof field === 'string' || field instanceof Buffer
  1835. }
  1836. module.exports = generate
  1837. }, function(modId) { var map = {"./constants":1682324647507,"./numbers":1682324647510}; return __REQUIRE__(map[modId], modId); })
  1838. __DEFINE__(1682324647510, function(require, module, exports) {
  1839. const max = 65536
  1840. const cache = {}
  1841. // in node 6 Buffer.subarray returns a Uint8Array instead of a Buffer
  1842. // later versions return a Buffer
  1843. // alternative is Buffer.slice but that creates a new buffer
  1844. // creating new buffers takes time
  1845. // SubOk is only false on node < 8
  1846. const SubOk = Buffer.isBuffer(Buffer.from([1, 2]).subarray(0, 1))
  1847. function generateBuffer (i) {
  1848. const buffer = Buffer.allocUnsafe(2)
  1849. buffer.writeUInt8(i >> 8, 0)
  1850. buffer.writeUInt8(i & 0x00FF, 0 + 1)
  1851. return buffer
  1852. }
  1853. function generateCache () {
  1854. for (let i = 0; i < max; i++) {
  1855. cache[i] = generateBuffer(i)
  1856. }
  1857. }
  1858. function genBufVariableByteInt (num) {
  1859. const maxLength = 4 // max 4 bytes
  1860. let digit = 0
  1861. let pos = 0
  1862. const buffer = Buffer.allocUnsafe(maxLength)
  1863. do {
  1864. digit = num % 128 | 0
  1865. num = num / 128 | 0
  1866. if (num > 0) digit = digit | 0x80
  1867. buffer.writeUInt8(digit, pos++)
  1868. } while (num > 0 && pos < maxLength)
  1869. if (num > 0) {
  1870. pos = 0
  1871. }
  1872. return SubOk ? buffer.subarray(0, pos) : buffer.slice(0, pos)
  1873. }
  1874. function generate4ByteBuffer (num) {
  1875. const buffer = Buffer.allocUnsafe(4)
  1876. buffer.writeUInt32BE(num, 0)
  1877. return buffer
  1878. }
  1879. module.exports = {
  1880. cache,
  1881. generateCache,
  1882. generateNumber: generateBuffer,
  1883. genBufVariableByteInt,
  1884. generate4ByteBuffer
  1885. }
  1886. }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); })
  1887. return __REQUIRE__(1682324647504);
  1888. })()
  1889. //miniprogram-npm-outsideDeps=["bl","events","debug","process-nextick-args"]
  1890. //# sourceMappingURL=index.js.map