index.js 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174
  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__(1682324647511, function(require, module, exports) {
  8. /*
  9. * Copyright (c) 2015-2015 MQTT.js contributors.
  10. * Copyright (c) 2011-2014 Adam Rudd.
  11. *
  12. * See LICENSE for more information
  13. */
  14. const MqttClient = require('./lib/client')
  15. const connect = require('./lib/connect')
  16. const Store = require('./lib/store')
  17. const DefaultMessageIdProvider = require('./lib/default-message-id-provider')
  18. const UniqueMessageIdProvider = require('./lib/unique-message-id-provider')
  19. module.exports.connect = connect
  20. // Expose MqttClient
  21. module.exports.MqttClient = MqttClient
  22. module.exports.Client = MqttClient
  23. module.exports.Store = Store
  24. module.exports.DefaultMessageIdProvider = DefaultMessageIdProvider
  25. module.exports.UniqueMessageIdProvider = UniqueMessageIdProvider
  26. }, function(modId) {var map = {"./lib/client":1682324647512,"./lib/connect":1682324647518,"./lib/store":1682324647513,"./lib/default-message-id-provider":1682324647516,"./lib/unique-message-id-provider":1682324647524}; return __REQUIRE__(map[modId], modId); })
  27. __DEFINE__(1682324647512, function(require, module, exports) {
  28. /**
  29. * Module dependencies
  30. */
  31. const EventEmitter = require('events').EventEmitter
  32. const Store = require('./store')
  33. const TopicAliasRecv = require('./topic-alias-recv')
  34. const TopicAliasSend = require('./topic-alias-send')
  35. const mqttPacket = require('mqtt-packet')
  36. const DefaultMessageIdProvider = require('./default-message-id-provider')
  37. const Writable = require('readable-stream').Writable
  38. const inherits = require('inherits')
  39. const reInterval = require('reinterval')
  40. const clone = require('rfdc/default')
  41. const validations = require('./validations')
  42. const xtend = require('xtend')
  43. const debug = require('debug')('mqttjs:client')
  44. const nextTick = process ? process.nextTick : function (callback) { setTimeout(callback, 0) }
  45. const setImmediate = global.setImmediate || function (callback) {
  46. // works in node v0.8
  47. nextTick(callback)
  48. }
  49. const defaultConnectOptions = {
  50. keepalive: 60,
  51. reschedulePings: true,
  52. protocolId: 'MQTT',
  53. protocolVersion: 4,
  54. reconnectPeriod: 1000,
  55. connectTimeout: 30 * 1000,
  56. clean: true,
  57. resubscribe: true
  58. }
  59. const socketErrors = [
  60. 'ECONNREFUSED',
  61. 'EADDRINUSE',
  62. 'ECONNRESET',
  63. 'ENOTFOUND'
  64. ]
  65. // Other Socket Errors: EADDRINUSE, ECONNRESET, ENOTFOUND.
  66. const errors = {
  67. 0: '',
  68. 1: 'Unacceptable protocol version',
  69. 2: 'Identifier rejected',
  70. 3: 'Server unavailable',
  71. 4: 'Bad username or password',
  72. 5: 'Not authorized',
  73. 16: 'No matching subscribers',
  74. 17: 'No subscription existed',
  75. 128: 'Unspecified error',
  76. 129: 'Malformed Packet',
  77. 130: 'Protocol Error',
  78. 131: 'Implementation specific error',
  79. 132: 'Unsupported Protocol Version',
  80. 133: 'Client Identifier not valid',
  81. 134: 'Bad User Name or Password',
  82. 135: 'Not authorized',
  83. 136: 'Server unavailable',
  84. 137: 'Server busy',
  85. 138: 'Banned',
  86. 139: 'Server shutting down',
  87. 140: 'Bad authentication method',
  88. 141: 'Keep Alive timeout',
  89. 142: 'Session taken over',
  90. 143: 'Topic Filter invalid',
  91. 144: 'Topic Name invalid',
  92. 145: 'Packet identifier in use',
  93. 146: 'Packet Identifier not found',
  94. 147: 'Receive Maximum exceeded',
  95. 148: 'Topic Alias invalid',
  96. 149: 'Packet too large',
  97. 150: 'Message rate too high',
  98. 151: 'Quota exceeded',
  99. 152: 'Administrative action',
  100. 153: 'Payload format invalid',
  101. 154: 'Retain not supported',
  102. 155: 'QoS not supported',
  103. 156: 'Use another server',
  104. 157: 'Server moved',
  105. 158: 'Shared Subscriptions not supported',
  106. 159: 'Connection rate exceeded',
  107. 160: 'Maximum connect time',
  108. 161: 'Subscription Identifiers not supported',
  109. 162: 'Wildcard Subscriptions not supported'
  110. }
  111. function defaultId () {
  112. return 'mqttjs_' + Math.random().toString(16).substr(2, 8)
  113. }
  114. function applyTopicAlias (client, packet) {
  115. if (client.options.protocolVersion === 5) {
  116. if (packet.cmd === 'publish') {
  117. let alias
  118. if (packet.properties) {
  119. alias = packet.properties.topicAlias
  120. }
  121. const topic = packet.topic.toString()
  122. if (client.topicAliasSend) {
  123. if (alias) {
  124. if (topic.length !== 0) {
  125. // register topic alias
  126. debug('applyTopicAlias :: register topic: %s - alias: %d', topic, alias)
  127. if (!client.topicAliasSend.put(topic, alias)) {
  128. debug('applyTopicAlias :: error out of range. topic: %s - alias: %d', topic, alias)
  129. return new Error('Sending Topic Alias out of range')
  130. }
  131. }
  132. } else {
  133. if (topic.length !== 0) {
  134. if (client.options.autoAssignTopicAlias) {
  135. alias = client.topicAliasSend.getAliasByTopic(topic)
  136. if (alias) {
  137. packet.topic = ''
  138. packet.properties = { ...(packet.properties), topicAlias: alias }
  139. debug('applyTopicAlias :: auto assign(use) topic: %s - alias: %d', topic, alias)
  140. } else {
  141. alias = client.topicAliasSend.getLruAlias()
  142. client.topicAliasSend.put(topic, alias)
  143. packet.properties = { ...(packet.properties), topicAlias: alias }
  144. debug('applyTopicAlias :: auto assign topic: %s - alias: %d', topic, alias)
  145. }
  146. } else if (client.options.autoUseTopicAlias) {
  147. alias = client.topicAliasSend.getAliasByTopic(topic)
  148. if (alias) {
  149. packet.topic = ''
  150. packet.properties = { ...(packet.properties), topicAlias: alias }
  151. debug('applyTopicAlias :: auto use topic: %s - alias: %d', topic, alias)
  152. }
  153. }
  154. }
  155. }
  156. } else if (alias) {
  157. debug('applyTopicAlias :: error out of range. topic: %s - alias: %d', topic, alias)
  158. return new Error('Sending Topic Alias out of range')
  159. }
  160. }
  161. }
  162. }
  163. function removeTopicAliasAndRecoverTopicName (client, packet) {
  164. let alias
  165. if (packet.properties) {
  166. alias = packet.properties.topicAlias
  167. }
  168. let topic = packet.topic.toString()
  169. if (topic.length === 0) {
  170. // restore topic from alias
  171. if (typeof alias === 'undefined') {
  172. return new Error('Unregistered Topic Alias')
  173. } else {
  174. topic = client.topicAliasSend.getTopicByAlias(alias)
  175. if (typeof topic === 'undefined') {
  176. return new Error('Unregistered Topic Alias')
  177. } else {
  178. packet.topic = topic
  179. }
  180. }
  181. }
  182. if (alias) {
  183. delete packet.properties.topicAlias
  184. }
  185. }
  186. function sendPacket (client, packet, cb) {
  187. debug('sendPacket :: packet: %O', packet)
  188. debug('sendPacket :: emitting `packetsend`')
  189. client.emit('packetsend', packet)
  190. debug('sendPacket :: writing to stream')
  191. const result = mqttPacket.writeToStream(packet, client.stream, client.options)
  192. debug('sendPacket :: writeToStream result %s', result)
  193. if (!result && cb && cb !== nop) {
  194. debug('sendPacket :: handle events on `drain` once through callback.')
  195. client.stream.once('drain', cb)
  196. } else if (cb) {
  197. debug('sendPacket :: invoking cb')
  198. cb()
  199. }
  200. }
  201. function flush (queue) {
  202. if (queue) {
  203. debug('flush: queue exists? %b', !!(queue))
  204. Object.keys(queue).forEach(function (messageId) {
  205. if (typeof queue[messageId].cb === 'function') {
  206. queue[messageId].cb(new Error('Connection closed'))
  207. // This is suspicious. Why do we only delete this if we have a callbck?
  208. // If this is by-design, then adding no as callback would cause this to get deleted unintentionally.
  209. delete queue[messageId]
  210. }
  211. })
  212. }
  213. }
  214. function flushVolatile (queue) {
  215. if (queue) {
  216. debug('flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function')
  217. Object.keys(queue).forEach(function (messageId) {
  218. if (queue[messageId].volatile && typeof queue[messageId].cb === 'function') {
  219. queue[messageId].cb(new Error('Connection closed'))
  220. delete queue[messageId]
  221. }
  222. })
  223. }
  224. }
  225. function storeAndSend (client, packet, cb, cbStorePut) {
  226. debug('storeAndSend :: store packet with cmd %s to outgoingStore', packet.cmd)
  227. let storePacket = packet
  228. let err
  229. if (storePacket.cmd === 'publish') {
  230. // The original packet is for sending.
  231. // The cloned storePacket is for storing to resend on reconnect.
  232. // Topic Alias must not be used after disconnected.
  233. storePacket = clone(packet)
  234. err = removeTopicAliasAndRecoverTopicName(client, storePacket)
  235. if (err) {
  236. return cb && cb(err)
  237. }
  238. }
  239. client.outgoingStore.put(storePacket, function storedPacket (err) {
  240. if (err) {
  241. return cb && cb(err)
  242. }
  243. cbStorePut()
  244. sendPacket(client, packet, cb)
  245. })
  246. }
  247. function nop (error) {
  248. debug('nop ::', error)
  249. }
  250. /**
  251. * MqttClient constructor
  252. *
  253. * @param {Stream} stream - stream
  254. * @param {Object} [options] - connection options
  255. * (see Connection#connect)
  256. */
  257. function MqttClient (streamBuilder, options) {
  258. let k
  259. const that = this
  260. if (!(this instanceof MqttClient)) {
  261. return new MqttClient(streamBuilder, options)
  262. }
  263. this.options = options || {}
  264. // Defaults
  265. for (k in defaultConnectOptions) {
  266. if (typeof this.options[k] === 'undefined') {
  267. this.options[k] = defaultConnectOptions[k]
  268. } else {
  269. this.options[k] = options[k]
  270. }
  271. }
  272. debug('MqttClient :: options.protocol', options.protocol)
  273. debug('MqttClient :: options.protocolVersion', options.protocolVersion)
  274. debug('MqttClient :: options.username', options.username)
  275. debug('MqttClient :: options.keepalive', options.keepalive)
  276. debug('MqttClient :: options.reconnectPeriod', options.reconnectPeriod)
  277. debug('MqttClient :: options.rejectUnauthorized', options.rejectUnauthorized)
  278. debug('MqttClient :: options.topicAliasMaximum', options.topicAliasMaximum)
  279. this.options.clientId = (typeof options.clientId === 'string') ? options.clientId : defaultId()
  280. debug('MqttClient :: clientId', this.options.clientId)
  281. this.options.customHandleAcks = (options.protocolVersion === 5 && options.customHandleAcks) ? options.customHandleAcks : function () { arguments[3](0) }
  282. this.streamBuilder = streamBuilder
  283. this.messageIdProvider = (typeof this.options.messageIdProvider === 'undefined') ? new DefaultMessageIdProvider() : this.options.messageIdProvider
  284. // Inflight message storages
  285. this.outgoingStore = options.outgoingStore || new Store()
  286. this.incomingStore = options.incomingStore || new Store()
  287. // Should QoS zero messages be queued when the connection is broken?
  288. this.queueQoSZero = options.queueQoSZero === undefined ? true : options.queueQoSZero
  289. // map of subscribed topics to support reconnection
  290. this._resubscribeTopics = {}
  291. // map of a subscribe messageId and a topic
  292. this.messageIdToTopic = {}
  293. // Ping timer, setup in _setupPingTimer
  294. this.pingTimer = null
  295. // Is the client connected?
  296. this.connected = false
  297. // Are we disconnecting?
  298. this.disconnecting = false
  299. // Packet queue
  300. this.queue = []
  301. // connack timer
  302. this.connackTimer = null
  303. // Reconnect timer
  304. this.reconnectTimer = null
  305. // Is processing store?
  306. this._storeProcessing = false
  307. // Packet Ids are put into the store during store processing
  308. this._packetIdsDuringStoreProcessing = {}
  309. // Store processing queue
  310. this._storeProcessingQueue = []
  311. // Inflight callbacks
  312. this.outgoing = {}
  313. // True if connection is first time.
  314. this._firstConnection = true
  315. if (options.topicAliasMaximum > 0) {
  316. if (options.topicAliasMaximum > 0xffff) {
  317. debug('MqttClient :: options.topicAliasMaximum is out of range')
  318. } else {
  319. this.topicAliasRecv = new TopicAliasRecv(options.topicAliasMaximum)
  320. }
  321. }
  322. // Send queued packets
  323. this.on('connect', function () {
  324. const queue = this.queue
  325. function deliver () {
  326. const entry = queue.shift()
  327. debug('deliver :: entry %o', entry)
  328. let packet = null
  329. if (!entry) {
  330. that._resubscribe()
  331. return
  332. }
  333. packet = entry.packet
  334. debug('deliver :: call _sendPacket for %o', packet)
  335. let send = true
  336. if (packet.messageId && packet.messageId !== 0) {
  337. if (!that.messageIdProvider.register(packet.messageId)) {
  338. send = false
  339. }
  340. }
  341. if (send) {
  342. that._sendPacket(
  343. packet,
  344. function (err) {
  345. if (entry.cb) {
  346. entry.cb(err)
  347. }
  348. deliver()
  349. }
  350. )
  351. } else {
  352. debug('messageId: %d has already used. The message is skipped and removed.', packet.messageId)
  353. deliver()
  354. }
  355. }
  356. debug('connect :: sending queued packets')
  357. deliver()
  358. })
  359. this.on('close', function () {
  360. debug('close :: connected set to `false`')
  361. this.connected = false
  362. debug('close :: clearing connackTimer')
  363. clearTimeout(this.connackTimer)
  364. debug('close :: clearing ping timer')
  365. if (that.pingTimer !== null) {
  366. that.pingTimer.clear()
  367. that.pingTimer = null
  368. }
  369. if (this.topicAliasRecv) {
  370. this.topicAliasRecv.clear()
  371. }
  372. debug('close :: calling _setupReconnect')
  373. this._setupReconnect()
  374. })
  375. EventEmitter.call(this)
  376. debug('MqttClient :: setting up stream')
  377. this._setupStream()
  378. }
  379. inherits(MqttClient, EventEmitter)
  380. /**
  381. * setup the event handlers in the inner stream.
  382. *
  383. * @api private
  384. */
  385. MqttClient.prototype._setupStream = function () {
  386. const that = this
  387. const writable = new Writable()
  388. const parser = mqttPacket.parser(this.options)
  389. let completeParse = null
  390. const packets = []
  391. debug('_setupStream :: calling method to clear reconnect')
  392. this._clearReconnect()
  393. debug('_setupStream :: using streamBuilder provided to client to create stream')
  394. this.stream = this.streamBuilder(this)
  395. parser.on('packet', function (packet) {
  396. debug('parser :: on packet push to packets array.')
  397. packets.push(packet)
  398. })
  399. function nextTickWork () {
  400. if (packets.length) {
  401. nextTick(work)
  402. } else {
  403. const done = completeParse
  404. completeParse = null
  405. done()
  406. }
  407. }
  408. function work () {
  409. debug('work :: getting next packet in queue')
  410. const packet = packets.shift()
  411. if (packet) {
  412. debug('work :: packet pulled from queue')
  413. that._handlePacket(packet, nextTickWork)
  414. } else {
  415. debug('work :: no packets in queue')
  416. const done = completeParse
  417. completeParse = null
  418. debug('work :: done flag is %s', !!(done))
  419. if (done) done()
  420. }
  421. }
  422. writable._write = function (buf, enc, done) {
  423. completeParse = done
  424. debug('writable stream :: parsing buffer')
  425. parser.parse(buf)
  426. work()
  427. }
  428. function streamErrorHandler (error) {
  429. debug('streamErrorHandler :: error', error.message)
  430. if (socketErrors.includes(error.code)) {
  431. // handle error
  432. debug('streamErrorHandler :: emitting error')
  433. that.emit('error', error)
  434. } else {
  435. nop(error)
  436. }
  437. }
  438. debug('_setupStream :: pipe stream to writable stream')
  439. this.stream.pipe(writable)
  440. // Suppress connection errors
  441. this.stream.on('error', streamErrorHandler)
  442. // Echo stream close
  443. this.stream.on('close', function () {
  444. debug('(%s)stream :: on close', that.options.clientId)
  445. flushVolatile(that.outgoing)
  446. debug('stream: emit close to MqttClient')
  447. that.emit('close')
  448. })
  449. // Send a connect packet
  450. debug('_setupStream: sending packet `connect`')
  451. const connectPacket = Object.create(this.options)
  452. connectPacket.cmd = 'connect'
  453. if (this.topicAliasRecv) {
  454. if (!connectPacket.properties) {
  455. connectPacket.properties = {}
  456. }
  457. if (this.topicAliasRecv) {
  458. connectPacket.properties.topicAliasMaximum = this.topicAliasRecv.max
  459. }
  460. }
  461. // avoid message queue
  462. sendPacket(this, connectPacket)
  463. // Echo connection errors
  464. parser.on('error', this.emit.bind(this, 'error'))
  465. // auth
  466. if (this.options.properties) {
  467. if (!this.options.properties.authenticationMethod && this.options.properties.authenticationData) {
  468. that.end(() =>
  469. this.emit('error', new Error('Packet has no Authentication Method')
  470. ))
  471. return this
  472. }
  473. if (this.options.properties.authenticationMethod && this.options.authPacket && typeof this.options.authPacket === 'object') {
  474. const authPacket = xtend({ cmd: 'auth', reasonCode: 0 }, this.options.authPacket)
  475. sendPacket(this, authPacket)
  476. }
  477. }
  478. // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
  479. this.stream.setMaxListeners(1000)
  480. clearTimeout(this.connackTimer)
  481. this.connackTimer = setTimeout(function () {
  482. debug('!!connectTimeout hit!! Calling _cleanUp with force `true`')
  483. that._cleanUp(true)
  484. }, this.options.connectTimeout)
  485. }
  486. MqttClient.prototype._handlePacket = function (packet, done) {
  487. const options = this.options
  488. if (options.protocolVersion === 5 && options.properties && options.properties.maximumPacketSize && options.properties.maximumPacketSize < packet.length) {
  489. this.emit('error', new Error('exceeding packets size ' + packet.cmd))
  490. this.end({ reasonCode: 149, properties: { reasonString: 'Maximum packet size was exceeded' } })
  491. return this
  492. }
  493. debug('_handlePacket :: emitting packetreceive')
  494. this.emit('packetreceive', packet)
  495. switch (packet.cmd) {
  496. case 'publish':
  497. this._handlePublish(packet, done)
  498. break
  499. case 'puback':
  500. case 'pubrec':
  501. case 'pubcomp':
  502. case 'suback':
  503. case 'unsuback':
  504. this._handleAck(packet)
  505. done()
  506. break
  507. case 'pubrel':
  508. this._handlePubrel(packet, done)
  509. break
  510. case 'connack':
  511. this._handleConnack(packet)
  512. done()
  513. break
  514. case 'auth':
  515. this._handleAuth(packet)
  516. done()
  517. break
  518. case 'pingresp':
  519. this._handlePingresp(packet)
  520. done()
  521. break
  522. case 'disconnect':
  523. this._handleDisconnect(packet)
  524. done()
  525. break
  526. default:
  527. // do nothing
  528. // maybe we should do an error handling
  529. // or just log it
  530. break
  531. }
  532. }
  533. MqttClient.prototype._checkDisconnecting = function (callback) {
  534. if (this.disconnecting) {
  535. if (callback && callback !== nop) {
  536. callback(new Error('client disconnecting'))
  537. } else {
  538. this.emit('error', new Error('client disconnecting'))
  539. }
  540. }
  541. return this.disconnecting
  542. }
  543. /**
  544. * publish - publish <message> to <topic>
  545. *
  546. * @param {String} topic - topic to publish to
  547. * @param {String, Buffer} message - message to publish
  548. * @param {Object} [opts] - publish options, includes:
  549. * {Number} qos - qos level to publish on
  550. * {Boolean} retain - whether or not to retain the message
  551. * {Boolean} dup - whether or not mark a message as duplicate
  552. * {Function} cbStorePut - function(){} called when message is put into `outgoingStore`
  553. * @param {Function} [callback] - function(err){}
  554. * called when publish succeeds or fails
  555. * @returns {MqttClient} this - for chaining
  556. * @api public
  557. *
  558. * @example client.publish('topic', 'message');
  559. * @example
  560. * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
  561. * @example client.publish('topic', 'message', console.log);
  562. */
  563. MqttClient.prototype.publish = function (topic, message, opts, callback) {
  564. debug('publish :: message `%s` to topic `%s`', message, topic)
  565. const options = this.options
  566. // .publish(topic, payload, cb);
  567. if (typeof opts === 'function') {
  568. callback = opts
  569. opts = null
  570. }
  571. // default opts
  572. const defaultOpts = { qos: 0, retain: false, dup: false }
  573. opts = xtend(defaultOpts, opts)
  574. if (this._checkDisconnecting(callback)) {
  575. return this
  576. }
  577. const that = this
  578. const publishProc = function () {
  579. let messageId = 0
  580. if (opts.qos === 1 || opts.qos === 2) {
  581. messageId = that._nextId()
  582. if (messageId === null) {
  583. debug('No messageId left')
  584. return false
  585. }
  586. }
  587. const packet = {
  588. cmd: 'publish',
  589. topic: topic,
  590. payload: message,
  591. qos: opts.qos,
  592. retain: opts.retain,
  593. messageId: messageId,
  594. dup: opts.dup
  595. }
  596. if (options.protocolVersion === 5) {
  597. packet.properties = opts.properties
  598. }
  599. debug('publish :: qos', opts.qos)
  600. switch (opts.qos) {
  601. case 1:
  602. case 2:
  603. // Add to callbacks
  604. that.outgoing[packet.messageId] = {
  605. volatile: false,
  606. cb: callback || nop
  607. }
  608. debug('MqttClient:publish: packet cmd: %s', packet.cmd)
  609. that._sendPacket(packet, undefined, opts.cbStorePut)
  610. break
  611. default:
  612. debug('MqttClient:publish: packet cmd: %s', packet.cmd)
  613. that._sendPacket(packet, callback, opts.cbStorePut)
  614. break
  615. }
  616. return true
  617. }
  618. if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !publishProc()) {
  619. this._storeProcessingQueue.push(
  620. {
  621. invoke: publishProc,
  622. cbStorePut: opts.cbStorePut,
  623. callback: callback
  624. }
  625. )
  626. }
  627. return this
  628. }
  629. /**
  630. * subscribe - subscribe to <topic>
  631. *
  632. * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
  633. * @param {Object} [opts] - optional subscription options, includes:
  634. * {Number} qos - subscribe qos level
  635. * @param {Function} [callback] - function(err, granted){} where:
  636. * {Error} err - subscription error (none at the moment!)
  637. * {Array} granted - array of {topic: 't', qos: 0}
  638. * @returns {MqttClient} this - for chaining
  639. * @api public
  640. * @example client.subscribe('topic');
  641. * @example client.subscribe('topic', {qos: 1});
  642. * @example client.subscribe({'topic': {qos: 0}, 'topic2': {qos: 1}}, console.log);
  643. * @example client.subscribe('topic', console.log);
  644. */
  645. MqttClient.prototype.subscribe = function () {
  646. const that = this
  647. const args = new Array(arguments.length)
  648. for (let i = 0; i < arguments.length; i++) {
  649. args[i] = arguments[i]
  650. }
  651. const subs = []
  652. let obj = args.shift()
  653. const resubscribe = obj.resubscribe
  654. let callback = args.pop() || nop
  655. let opts = args.pop()
  656. const version = this.options.protocolVersion
  657. delete obj.resubscribe
  658. if (typeof obj === 'string') {
  659. obj = [obj]
  660. }
  661. if (typeof callback !== 'function') {
  662. opts = callback
  663. callback = nop
  664. }
  665. const invalidTopic = validations.validateTopics(obj)
  666. if (invalidTopic !== null) {
  667. setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
  668. return this
  669. }
  670. if (this._checkDisconnecting(callback)) {
  671. debug('subscribe: discconecting true')
  672. return this
  673. }
  674. const defaultOpts = {
  675. qos: 0
  676. }
  677. if (version === 5) {
  678. defaultOpts.nl = false
  679. defaultOpts.rap = false
  680. defaultOpts.rh = 0
  681. }
  682. opts = xtend(defaultOpts, opts)
  683. if (Array.isArray(obj)) {
  684. obj.forEach(function (topic) {
  685. debug('subscribe: array topic %s', topic)
  686. if (!Object.prototype.hasOwnProperty.call(that._resubscribeTopics, topic) ||
  687. that._resubscribeTopics[topic].qos < opts.qos ||
  688. resubscribe) {
  689. const currentOpts = {
  690. topic: topic,
  691. qos: opts.qos
  692. }
  693. if (version === 5) {
  694. currentOpts.nl = opts.nl
  695. currentOpts.rap = opts.rap
  696. currentOpts.rh = opts.rh
  697. currentOpts.properties = opts.properties
  698. }
  699. debug('subscribe: pushing topic `%s` and qos `%s` to subs list', currentOpts.topic, currentOpts.qos)
  700. subs.push(currentOpts)
  701. }
  702. })
  703. } else {
  704. Object
  705. .keys(obj)
  706. .forEach(function (k) {
  707. debug('subscribe: object topic %s', k)
  708. if (!Object.prototype.hasOwnProperty.call(that._resubscribeTopics, k) ||
  709. that._resubscribeTopics[k].qos < obj[k].qos ||
  710. resubscribe) {
  711. const currentOpts = {
  712. topic: k,
  713. qos: obj[k].qos
  714. }
  715. if (version === 5) {
  716. currentOpts.nl = obj[k].nl
  717. currentOpts.rap = obj[k].rap
  718. currentOpts.rh = obj[k].rh
  719. currentOpts.properties = opts.properties
  720. }
  721. debug('subscribe: pushing `%s` to subs list', currentOpts)
  722. subs.push(currentOpts)
  723. }
  724. })
  725. }
  726. if (!subs.length) {
  727. callback(null, [])
  728. return this
  729. }
  730. const subscribeProc = function () {
  731. const messageId = that._nextId()
  732. if (messageId === null) {
  733. debug('No messageId left')
  734. return false
  735. }
  736. const packet = {
  737. cmd: 'subscribe',
  738. subscriptions: subs,
  739. qos: 1,
  740. retain: false,
  741. dup: false,
  742. messageId: messageId
  743. }
  744. if (opts.properties) {
  745. packet.properties = opts.properties
  746. }
  747. // subscriptions to resubscribe to in case of disconnect
  748. if (that.options.resubscribe) {
  749. debug('subscribe :: resubscribe true')
  750. const topics = []
  751. subs.forEach(function (sub) {
  752. if (that.options.reconnectPeriod > 0) {
  753. const topic = { qos: sub.qos }
  754. if (version === 5) {
  755. topic.nl = sub.nl || false
  756. topic.rap = sub.rap || false
  757. topic.rh = sub.rh || 0
  758. topic.properties = sub.properties
  759. }
  760. that._resubscribeTopics[sub.topic] = topic
  761. topics.push(sub.topic)
  762. }
  763. })
  764. that.messageIdToTopic[packet.messageId] = topics
  765. }
  766. that.outgoing[packet.messageId] = {
  767. volatile: true,
  768. cb: function (err, packet) {
  769. if (!err) {
  770. const granted = packet.granted
  771. for (let i = 0; i < granted.length; i += 1) {
  772. subs[i].qos = granted[i]
  773. }
  774. }
  775. callback(err, subs)
  776. }
  777. }
  778. debug('subscribe :: call _sendPacket')
  779. that._sendPacket(packet)
  780. return true
  781. }
  782. if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !subscribeProc()) {
  783. this._storeProcessingQueue.push(
  784. {
  785. invoke: subscribeProc,
  786. callback: callback
  787. }
  788. )
  789. }
  790. return this
  791. }
  792. /**
  793. * unsubscribe - unsubscribe from topic(s)
  794. *
  795. * @param {String, Array} topic - topics to unsubscribe from
  796. * @param {Object} [opts] - optional subscription options, includes:
  797. * {Object} properties - properties of unsubscribe packet
  798. * @param {Function} [callback] - callback fired on unsuback
  799. * @returns {MqttClient} this - for chaining
  800. * @api public
  801. * @example client.unsubscribe('topic');
  802. * @example client.unsubscribe('topic', console.log);
  803. */
  804. MqttClient.prototype.unsubscribe = function () {
  805. const that = this
  806. const args = new Array(arguments.length)
  807. for (let i = 0; i < arguments.length; i++) {
  808. args[i] = arguments[i]
  809. }
  810. let topic = args.shift()
  811. let callback = args.pop() || nop
  812. let opts = args.pop()
  813. if (typeof topic === 'string') {
  814. topic = [topic]
  815. }
  816. if (typeof callback !== 'function') {
  817. opts = callback
  818. callback = nop
  819. }
  820. const invalidTopic = validations.validateTopics(topic)
  821. if (invalidTopic !== null) {
  822. setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
  823. return this
  824. }
  825. if (that._checkDisconnecting(callback)) {
  826. return this
  827. }
  828. const unsubscribeProc = function () {
  829. const messageId = that._nextId()
  830. if (messageId === null) {
  831. debug('No messageId left')
  832. return false
  833. }
  834. const packet = {
  835. cmd: 'unsubscribe',
  836. qos: 1,
  837. messageId: messageId
  838. }
  839. if (typeof topic === 'string') {
  840. packet.unsubscriptions = [topic]
  841. } else if (Array.isArray(topic)) {
  842. packet.unsubscriptions = topic
  843. }
  844. if (that.options.resubscribe) {
  845. packet.unsubscriptions.forEach(function (topic) {
  846. delete that._resubscribeTopics[topic]
  847. })
  848. }
  849. if (typeof opts === 'object' && opts.properties) {
  850. packet.properties = opts.properties
  851. }
  852. that.outgoing[packet.messageId] = {
  853. volatile: true,
  854. cb: callback
  855. }
  856. debug('unsubscribe: call _sendPacket')
  857. that._sendPacket(packet)
  858. return true
  859. }
  860. if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !unsubscribeProc()) {
  861. this._storeProcessingQueue.push(
  862. {
  863. invoke: unsubscribeProc,
  864. callback: callback
  865. }
  866. )
  867. }
  868. return this
  869. }
  870. /**
  871. * end - close connection
  872. *
  873. * @returns {MqttClient} this - for chaining
  874. * @param {Boolean} force - do not wait for all in-flight messages to be acked
  875. * @param {Object} opts - added to the disconnect packet
  876. * @param {Function} cb - called when the client has been closed
  877. *
  878. * @api public
  879. */
  880. MqttClient.prototype.end = function (force, opts, cb) {
  881. const that = this
  882. debug('end :: (%s)', this.options.clientId)
  883. if (force == null || typeof force !== 'boolean') {
  884. cb = opts || nop
  885. opts = force
  886. force = false
  887. if (typeof opts !== 'object') {
  888. cb = opts
  889. opts = null
  890. if (typeof cb !== 'function') {
  891. cb = nop
  892. }
  893. }
  894. }
  895. if (typeof opts !== 'object') {
  896. cb = opts
  897. opts = null
  898. }
  899. debug('end :: cb? %s', !!cb)
  900. cb = cb || nop
  901. function closeStores () {
  902. debug('end :: closeStores: closing incoming and outgoing stores')
  903. that.disconnected = true
  904. that.incomingStore.close(function (e1) {
  905. that.outgoingStore.close(function (e2) {
  906. debug('end :: closeStores: emitting end')
  907. that.emit('end')
  908. if (cb) {
  909. const err = e1 || e2
  910. debug('end :: closeStores: invoking callback with args')
  911. cb(err)
  912. }
  913. })
  914. })
  915. if (that._deferredReconnect) {
  916. that._deferredReconnect()
  917. }
  918. }
  919. function finish () {
  920. // defer closesStores of an I/O cycle,
  921. // just to make sure things are
  922. // ok for websockets
  923. debug('end :: (%s) :: finish :: calling _cleanUp with force %s', that.options.clientId, force)
  924. that._cleanUp(force, () => {
  925. debug('end :: finish :: calling process.nextTick on closeStores')
  926. // const boundProcess = nextTick.bind(null, closeStores)
  927. nextTick(closeStores.bind(that))
  928. }, opts)
  929. }
  930. if (this.disconnecting) {
  931. cb()
  932. return this
  933. }
  934. this._clearReconnect()
  935. this.disconnecting = true
  936. if (!force && Object.keys(this.outgoing).length > 0) {
  937. // wait 10ms, just to be sure we received all of it
  938. debug('end :: (%s) :: calling finish in 10ms once outgoing is empty', that.options.clientId)
  939. this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
  940. } else {
  941. debug('end :: (%s) :: immediately calling finish', that.options.clientId)
  942. finish()
  943. }
  944. return this
  945. }
  946. /**
  947. * removeOutgoingMessage - remove a message in outgoing store
  948. * the outgoing callback will be called withe Error('Message removed') if the message is removed
  949. *
  950. * @param {Number} messageId - messageId to remove message
  951. * @returns {MqttClient} this - for chaining
  952. * @api public
  953. *
  954. * @example client.removeOutgoingMessage(client.getLastAllocated());
  955. */
  956. MqttClient.prototype.removeOutgoingMessage = function (messageId) {
  957. const cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null
  958. delete this.outgoing[messageId]
  959. this.outgoingStore.del({ messageId: messageId }, function () {
  960. cb(new Error('Message removed'))
  961. })
  962. return this
  963. }
  964. /**
  965. * reconnect - connect again using the same options as connect()
  966. *
  967. * @param {Object} [opts] - optional reconnect options, includes:
  968. * {Store} incomingStore - a store for the incoming packets
  969. * {Store} outgoingStore - a store for the outgoing packets
  970. * if opts is not given, current stores are used
  971. * @returns {MqttClient} this - for chaining
  972. *
  973. * @api public
  974. */
  975. MqttClient.prototype.reconnect = function (opts) {
  976. debug('client reconnect')
  977. const that = this
  978. const f = function () {
  979. if (opts) {
  980. that.options.incomingStore = opts.incomingStore
  981. that.options.outgoingStore = opts.outgoingStore
  982. } else {
  983. that.options.incomingStore = null
  984. that.options.outgoingStore = null
  985. }
  986. that.incomingStore = that.options.incomingStore || new Store()
  987. that.outgoingStore = that.options.outgoingStore || new Store()
  988. that.disconnecting = false
  989. that.disconnected = false
  990. that._deferredReconnect = null
  991. that._reconnect()
  992. }
  993. if (this.disconnecting && !this.disconnected) {
  994. this._deferredReconnect = f
  995. } else {
  996. f()
  997. }
  998. return this
  999. }
  1000. /**
  1001. * _reconnect - implement reconnection
  1002. * @api privateish
  1003. */
  1004. MqttClient.prototype._reconnect = function () {
  1005. debug('_reconnect: emitting reconnect to client')
  1006. this.emit('reconnect')
  1007. if (this.connected) {
  1008. this.end(() => { this._setupStream() })
  1009. debug('client already connected. disconnecting first.')
  1010. } else {
  1011. debug('_reconnect: calling _setupStream')
  1012. this._setupStream()
  1013. }
  1014. }
  1015. /**
  1016. * _setupReconnect - setup reconnect timer
  1017. */
  1018. MqttClient.prototype._setupReconnect = function () {
  1019. const that = this
  1020. if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {
  1021. if (!this.reconnecting) {
  1022. debug('_setupReconnect :: emit `offline` state')
  1023. this.emit('offline')
  1024. debug('_setupReconnect :: set `reconnecting` to `true`')
  1025. this.reconnecting = true
  1026. }
  1027. debug('_setupReconnect :: setting reconnectTimer for %d ms', that.options.reconnectPeriod)
  1028. that.reconnectTimer = setInterval(function () {
  1029. debug('reconnectTimer :: reconnect triggered!')
  1030. that._reconnect()
  1031. }, that.options.reconnectPeriod)
  1032. } else {
  1033. debug('_setupReconnect :: doing nothing...')
  1034. }
  1035. }
  1036. /**
  1037. * _clearReconnect - clear the reconnect timer
  1038. */
  1039. MqttClient.prototype._clearReconnect = function () {
  1040. debug('_clearReconnect : clearing reconnect timer')
  1041. if (this.reconnectTimer) {
  1042. clearInterval(this.reconnectTimer)
  1043. this.reconnectTimer = null
  1044. }
  1045. }
  1046. /**
  1047. * _cleanUp - clean up on connection end
  1048. * @api private
  1049. */
  1050. MqttClient.prototype._cleanUp = function (forced, done) {
  1051. const opts = arguments[2]
  1052. if (done) {
  1053. debug('_cleanUp :: done callback provided for on stream close')
  1054. this.stream.on('close', done)
  1055. }
  1056. debug('_cleanUp :: forced? %s', forced)
  1057. if (forced) {
  1058. if ((this.options.reconnectPeriod === 0) && this.options.clean) {
  1059. flush(this.outgoing)
  1060. }
  1061. debug('_cleanUp :: (%s) :: destroying stream', this.options.clientId)
  1062. this.stream.destroy()
  1063. } else {
  1064. const packet = xtend({ cmd: 'disconnect' }, opts)
  1065. debug('_cleanUp :: (%s) :: call _sendPacket with disconnect packet', this.options.clientId)
  1066. this._sendPacket(
  1067. packet,
  1068. setImmediate.bind(
  1069. null,
  1070. this.stream.end.bind(this.stream)
  1071. )
  1072. )
  1073. }
  1074. if (!this.disconnecting) {
  1075. debug('_cleanUp :: client not disconnecting. Clearing and resetting reconnect.')
  1076. this._clearReconnect()
  1077. this._setupReconnect()
  1078. }
  1079. if (this.pingTimer !== null) {
  1080. debug('_cleanUp :: clearing pingTimer')
  1081. this.pingTimer.clear()
  1082. this.pingTimer = null
  1083. }
  1084. if (done && !this.connected) {
  1085. debug('_cleanUp :: (%s) :: removing stream `done` callback `close` listener', this.options.clientId)
  1086. this.stream.removeListener('close', done)
  1087. done()
  1088. }
  1089. }
  1090. /**
  1091. * _sendPacket - send or queue a packet
  1092. * @param {Object} packet - packet options
  1093. * @param {Function} cb - callback when the packet is sent
  1094. * @param {Function} cbStorePut - called when message is put into outgoingStore
  1095. * @api private
  1096. */
  1097. MqttClient.prototype._sendPacket = function (packet, cb, cbStorePut) {
  1098. debug('_sendPacket :: (%s) :: start', this.options.clientId)
  1099. cbStorePut = cbStorePut || nop
  1100. cb = cb || nop
  1101. const err = applyTopicAlias(this, packet)
  1102. if (err) {
  1103. cb(err)
  1104. return
  1105. }
  1106. if (!this.connected) {
  1107. // allow auth packets to be sent while authenticating with the broker (mqtt5 enhanced auth)
  1108. if (packet.cmd === 'auth') {
  1109. this._shiftPingInterval()
  1110. sendPacket(this, packet, cb)
  1111. return
  1112. }
  1113. debug('_sendPacket :: client not connected. Storing packet offline.')
  1114. this._storePacket(packet, cb, cbStorePut)
  1115. return
  1116. }
  1117. // When sending a packet, reschedule the ping timer
  1118. this._shiftPingInterval()
  1119. switch (packet.cmd) {
  1120. case 'publish':
  1121. break
  1122. case 'pubrel':
  1123. storeAndSend(this, packet, cb, cbStorePut)
  1124. return
  1125. default:
  1126. sendPacket(this, packet, cb)
  1127. return
  1128. }
  1129. switch (packet.qos) {
  1130. case 2:
  1131. case 1:
  1132. storeAndSend(this, packet, cb, cbStorePut)
  1133. break
  1134. /**
  1135. * no need of case here since it will be caught by default
  1136. * and jshint comply that before default it must be a break
  1137. * anyway it will result in -1 evaluation
  1138. */
  1139. case 0:
  1140. /* falls through */
  1141. default:
  1142. sendPacket(this, packet, cb)
  1143. break
  1144. }
  1145. debug('_sendPacket :: (%s) :: end', this.options.clientId)
  1146. }
  1147. /**
  1148. * _storePacket - queue a packet
  1149. * @param {Object} packet - packet options
  1150. * @param {Function} cb - callback when the packet is sent
  1151. * @param {Function} cbStorePut - called when message is put into outgoingStore
  1152. * @api private
  1153. */
  1154. MqttClient.prototype._storePacket = function (packet, cb, cbStorePut) {
  1155. debug('_storePacket :: packet: %o', packet)
  1156. debug('_storePacket :: cb? %s', !!cb)
  1157. cbStorePut = cbStorePut || nop
  1158. let storePacket = packet
  1159. if (storePacket.cmd === 'publish') {
  1160. // The original packet is for sending.
  1161. // The cloned storePacket is for storing to resend on reconnect.
  1162. // Topic Alias must not be used after disconnected.
  1163. storePacket = clone(packet)
  1164. const err = removeTopicAliasAndRecoverTopicName(this, storePacket)
  1165. if (err) {
  1166. return cb && cb(err)
  1167. }
  1168. }
  1169. // check that the packet is not a qos of 0, or that the command is not a publish
  1170. if (((storePacket.qos || 0) === 0 && this.queueQoSZero) || storePacket.cmd !== 'publish') {
  1171. this.queue.push({ packet: storePacket, cb: cb })
  1172. } else if (storePacket.qos > 0) {
  1173. cb = this.outgoing[storePacket.messageId] ? this.outgoing[storePacket.messageId].cb : null
  1174. this.outgoingStore.put(storePacket, function (err) {
  1175. if (err) {
  1176. return cb && cb(err)
  1177. }
  1178. cbStorePut()
  1179. })
  1180. } else if (cb) {
  1181. cb(new Error('No connection to broker'))
  1182. }
  1183. }
  1184. /**
  1185. * _setupPingTimer - setup the ping timer
  1186. *
  1187. * @api private
  1188. */
  1189. MqttClient.prototype._setupPingTimer = function () {
  1190. debug('_setupPingTimer :: keepalive %d (seconds)', this.options.keepalive)
  1191. const that = this
  1192. if (!this.pingTimer && this.options.keepalive) {
  1193. this.pingResp = true
  1194. this.pingTimer = reInterval(function () {
  1195. that._checkPing()
  1196. }, this.options.keepalive * 1000)
  1197. }
  1198. }
  1199. /**
  1200. * _shiftPingInterval - reschedule the ping interval
  1201. *
  1202. * @api private
  1203. */
  1204. MqttClient.prototype._shiftPingInterval = function () {
  1205. if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {
  1206. this.pingTimer.reschedule(this.options.keepalive * 1000)
  1207. }
  1208. }
  1209. /**
  1210. * _checkPing - check if a pingresp has come back, and ping the server again
  1211. *
  1212. * @api private
  1213. */
  1214. MqttClient.prototype._checkPing = function () {
  1215. debug('_checkPing :: checking ping...')
  1216. if (this.pingResp) {
  1217. debug('_checkPing :: ping response received. Clearing flag and sending `pingreq`')
  1218. this.pingResp = false
  1219. this._sendPacket({ cmd: 'pingreq' })
  1220. } else {
  1221. // do a forced cleanup since socket will be in bad shape
  1222. debug('_checkPing :: calling _cleanUp with force true')
  1223. this._cleanUp(true)
  1224. }
  1225. }
  1226. /**
  1227. * _handlePingresp - handle a pingresp
  1228. *
  1229. * @api private
  1230. */
  1231. MqttClient.prototype._handlePingresp = function () {
  1232. this.pingResp = true
  1233. }
  1234. /**
  1235. * _handleConnack
  1236. *
  1237. * @param {Object} packet
  1238. * @api private
  1239. */
  1240. MqttClient.prototype._handleConnack = function (packet) {
  1241. debug('_handleConnack')
  1242. const options = this.options
  1243. const version = options.protocolVersion
  1244. const rc = version === 5 ? packet.reasonCode : packet.returnCode
  1245. clearTimeout(this.connackTimer)
  1246. delete this.topicAliasSend
  1247. if (packet.properties) {
  1248. if (packet.properties.topicAliasMaximum) {
  1249. if (packet.properties.topicAliasMaximum > 0xffff) {
  1250. this.emit('error', new Error('topicAliasMaximum from broker is out of range'))
  1251. return
  1252. }
  1253. if (packet.properties.topicAliasMaximum > 0) {
  1254. this.topicAliasSend = new TopicAliasSend(packet.properties.topicAliasMaximum)
  1255. }
  1256. }
  1257. if (packet.properties.serverKeepAlive && options.keepalive) {
  1258. options.keepalive = packet.properties.serverKeepAlive
  1259. this._shiftPingInterval()
  1260. }
  1261. if (packet.properties.maximumPacketSize) {
  1262. if (!options.properties) { options.properties = {} }
  1263. options.properties.maximumPacketSize = packet.properties.maximumPacketSize
  1264. }
  1265. }
  1266. if (rc === 0) {
  1267. this.reconnecting = false
  1268. this._onConnect(packet)
  1269. } else if (rc > 0) {
  1270. const err = new Error('Connection refused: ' + errors[rc])
  1271. err.code = rc
  1272. this.emit('error', err)
  1273. }
  1274. }
  1275. MqttClient.prototype._handleAuth = function (packet) {
  1276. const options = this.options
  1277. const version = options.protocolVersion
  1278. const rc = version === 5 ? packet.reasonCode : packet.returnCode
  1279. if (version !== 5) {
  1280. const err = new Error('Protocol error: Auth packets are only supported in MQTT 5. Your version:' + version)
  1281. err.code = rc
  1282. this.emit('error', err)
  1283. return
  1284. }
  1285. const that = this
  1286. this.handleAuth(packet, function (err, packet) {
  1287. if (err) {
  1288. that.emit('error', err)
  1289. return
  1290. }
  1291. if (rc === 24) {
  1292. that.reconnecting = false
  1293. that._sendPacket(packet)
  1294. } else {
  1295. const error = new Error('Connection refused: ' + errors[rc])
  1296. err.code = rc
  1297. that.emit('error', error)
  1298. }
  1299. })
  1300. }
  1301. /**
  1302. * @param packet the packet received by the broker
  1303. * @return the auth packet to be returned to the broker
  1304. * @api public
  1305. */
  1306. MqttClient.prototype.handleAuth = function (packet, callback) {
  1307. callback()
  1308. }
  1309. /**
  1310. * _handlePublish
  1311. *
  1312. * @param {Object} packet
  1313. * @api private
  1314. */
  1315. /*
  1316. those late 2 case should be rewrite to comply with coding style:
  1317. case 1:
  1318. case 0:
  1319. // do not wait sending a puback
  1320. // no callback passed
  1321. if (1 === qos) {
  1322. this._sendPacket({
  1323. cmd: 'puback',
  1324. messageId: messageId
  1325. });
  1326. }
  1327. // emit the message event for both qos 1 and 0
  1328. this.emit('message', topic, message, packet);
  1329. this.handleMessage(packet, done);
  1330. break;
  1331. default:
  1332. // do nothing but every switch mus have a default
  1333. // log or throw an error about unknown qos
  1334. break;
  1335. for now i just suppressed the warnings
  1336. */
  1337. MqttClient.prototype._handlePublish = function (packet, done) {
  1338. debug('_handlePublish: packet %o', packet)
  1339. done = typeof done !== 'undefined' ? done : nop
  1340. let topic = packet.topic.toString()
  1341. const message = packet.payload
  1342. const qos = packet.qos
  1343. const messageId = packet.messageId
  1344. const that = this
  1345. const options = this.options
  1346. const validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]
  1347. if (this.options.protocolVersion === 5) {
  1348. let alias
  1349. if (packet.properties) {
  1350. alias = packet.properties.topicAlias
  1351. }
  1352. if (typeof alias !== 'undefined') {
  1353. if (topic.length === 0) {
  1354. if (alias > 0 && alias <= 0xffff) {
  1355. const gotTopic = this.topicAliasRecv.getTopicByAlias(alias)
  1356. if (gotTopic) {
  1357. topic = gotTopic
  1358. debug('_handlePublish :: topic complemented by alias. topic: %s - alias: %d', topic, alias)
  1359. } else {
  1360. debug('_handlePublish :: unregistered topic alias. alias: %d', alias)
  1361. this.emit('error', new Error('Received unregistered Topic Alias'))
  1362. return
  1363. }
  1364. } else {
  1365. debug('_handlePublish :: topic alias out of range. alias: %d', alias)
  1366. this.emit('error', new Error('Received Topic Alias is out of range'))
  1367. return
  1368. }
  1369. } else {
  1370. if (this.topicAliasRecv.put(topic, alias)) {
  1371. debug('_handlePublish :: registered topic: %s - alias: %d', topic, alias)
  1372. } else {
  1373. debug('_handlePublish :: topic alias out of range. alias: %d', alias)
  1374. this.emit('error', new Error('Received Topic Alias is out of range'))
  1375. return
  1376. }
  1377. }
  1378. }
  1379. }
  1380. debug('_handlePublish: qos %d', qos)
  1381. switch (qos) {
  1382. case 2: {
  1383. options.customHandleAcks(topic, message, packet, function (error, code) {
  1384. if (!(error instanceof Error)) {
  1385. code = error
  1386. error = null
  1387. }
  1388. if (error) { return that.emit('error', error) }
  1389. if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for pubrec')) }
  1390. if (code) {
  1391. that._sendPacket({ cmd: 'pubrec', messageId: messageId, reasonCode: code }, done)
  1392. } else {
  1393. that.incomingStore.put(packet, function () {
  1394. that._sendPacket({ cmd: 'pubrec', messageId: messageId }, done)
  1395. })
  1396. }
  1397. })
  1398. break
  1399. }
  1400. case 1: {
  1401. // emit the message event
  1402. options.customHandleAcks(topic, message, packet, function (error, code) {
  1403. if (!(error instanceof Error)) {
  1404. code = error
  1405. error = null
  1406. }
  1407. if (error) { return that.emit('error', error) }
  1408. if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for puback')) }
  1409. if (!code) { that.emit('message', topic, message, packet) }
  1410. that.handleMessage(packet, function (err) {
  1411. if (err) {
  1412. return done && done(err)
  1413. }
  1414. that._sendPacket({ cmd: 'puback', messageId: messageId, reasonCode: code }, done)
  1415. })
  1416. })
  1417. break
  1418. }
  1419. case 0:
  1420. // emit the message event
  1421. this.emit('message', topic, message, packet)
  1422. this.handleMessage(packet, done)
  1423. break
  1424. default:
  1425. // do nothing
  1426. debug('_handlePublish: unknown QoS. Doing nothing.')
  1427. // log or throw an error about unknown qos
  1428. break
  1429. }
  1430. }
  1431. /**
  1432. * Handle messages with backpressure support, one at a time.
  1433. * Override at will.
  1434. *
  1435. * @param Packet packet the packet
  1436. * @param Function callback call when finished
  1437. * @api public
  1438. */
  1439. MqttClient.prototype.handleMessage = function (packet, callback) {
  1440. callback()
  1441. }
  1442. /**
  1443. * _handleAck
  1444. *
  1445. * @param {Object} packet
  1446. * @api private
  1447. */
  1448. MqttClient.prototype._handleAck = function (packet) {
  1449. /* eslint no-fallthrough: "off" */
  1450. const messageId = packet.messageId
  1451. const type = packet.cmd
  1452. let response = null
  1453. const cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null
  1454. const that = this
  1455. let err
  1456. // Checking `!cb` happens to work, but it's not technically "correct".
  1457. //
  1458. // Why? This code assumes that "no callback" is the same as that "we're not
  1459. // waiting for responses" (puback, pubrec, pubcomp, suback, or unsuback).
  1460. //
  1461. // It would be better to check `if (!this.outgoing[messageId])` here, but
  1462. // there's no reason to change it and risk (another) regression.
  1463. //
  1464. // The only reason this code works is becaues code in MqttClient.publish,
  1465. // MqttClinet.subscribe, and MqttClient.unsubscribe ensures that we will
  1466. // have a callback even if the user doesn't pass one in.)
  1467. if (!cb) {
  1468. debug('_handleAck :: Server sent an ack in error. Ignoring.')
  1469. // Server sent an ack in error, ignore it.
  1470. return
  1471. }
  1472. // Process
  1473. debug('_handleAck :: packet type', type)
  1474. switch (type) {
  1475. case 'pubcomp':
  1476. // same thing as puback for QoS 2
  1477. case 'puback': {
  1478. const pubackRC = packet.reasonCode
  1479. // Callback - we're done
  1480. if (pubackRC && pubackRC > 0 && pubackRC !== 16) {
  1481. err = new Error('Publish error: ' + errors[pubackRC])
  1482. err.code = pubackRC
  1483. cb(err, packet)
  1484. }
  1485. delete this.outgoing[messageId]
  1486. this.outgoingStore.del(packet, cb)
  1487. this.messageIdProvider.deallocate(messageId)
  1488. this._invokeStoreProcessingQueue()
  1489. break
  1490. }
  1491. case 'pubrec': {
  1492. response = {
  1493. cmd: 'pubrel',
  1494. qos: 2,
  1495. messageId: messageId
  1496. }
  1497. const pubrecRC = packet.reasonCode
  1498. if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) {
  1499. err = new Error('Publish error: ' + errors[pubrecRC])
  1500. err.code = pubrecRC
  1501. cb(err, packet)
  1502. } else {
  1503. this._sendPacket(response)
  1504. }
  1505. break
  1506. }
  1507. case 'suback': {
  1508. delete this.outgoing[messageId]
  1509. this.messageIdProvider.deallocate(messageId)
  1510. for (let grantedI = 0; grantedI < packet.granted.length; grantedI++) {
  1511. if ((packet.granted[grantedI] & 0x80) !== 0) {
  1512. // suback with Failure status
  1513. const topics = this.messageIdToTopic[messageId]
  1514. if (topics) {
  1515. topics.forEach(function (topic) {
  1516. delete that._resubscribeTopics[topic]
  1517. })
  1518. }
  1519. }
  1520. }
  1521. this._invokeStoreProcessingQueue()
  1522. cb(null, packet)
  1523. break
  1524. }
  1525. case 'unsuback': {
  1526. delete this.outgoing[messageId]
  1527. this.messageIdProvider.deallocate(messageId)
  1528. this._invokeStoreProcessingQueue()
  1529. cb(null)
  1530. break
  1531. }
  1532. default:
  1533. that.emit('error', new Error('unrecognized packet type'))
  1534. }
  1535. if (this.disconnecting &&
  1536. Object.keys(this.outgoing).length === 0) {
  1537. this.emit('outgoingEmpty')
  1538. }
  1539. }
  1540. /**
  1541. * _handlePubrel
  1542. *
  1543. * @param {Object} packet
  1544. * @api private
  1545. */
  1546. MqttClient.prototype._handlePubrel = function (packet, callback) {
  1547. debug('handling pubrel packet')
  1548. callback = typeof callback !== 'undefined' ? callback : nop
  1549. const messageId = packet.messageId
  1550. const that = this
  1551. const comp = { cmd: 'pubcomp', messageId: messageId }
  1552. that.incomingStore.get(packet, function (err, pub) {
  1553. if (!err) {
  1554. that.emit('message', pub.topic, pub.payload, pub)
  1555. that.handleMessage(pub, function (err) {
  1556. if (err) {
  1557. return callback(err)
  1558. }
  1559. that.incomingStore.del(pub, nop)
  1560. that._sendPacket(comp, callback)
  1561. })
  1562. } else {
  1563. that._sendPacket(comp, callback)
  1564. }
  1565. })
  1566. }
  1567. /**
  1568. * _handleDisconnect
  1569. *
  1570. * @param {Object} packet
  1571. * @api private
  1572. */
  1573. MqttClient.prototype._handleDisconnect = function (packet) {
  1574. this.emit('disconnect', packet)
  1575. }
  1576. /**
  1577. * _nextId
  1578. * @return unsigned int
  1579. */
  1580. MqttClient.prototype._nextId = function () {
  1581. return this.messageIdProvider.allocate()
  1582. }
  1583. /**
  1584. * getLastMessageId
  1585. * @return unsigned int
  1586. */
  1587. MqttClient.prototype.getLastMessageId = function () {
  1588. return this.messageIdProvider.getLastAllocated()
  1589. }
  1590. /**
  1591. * _resubscribe
  1592. * @api private
  1593. */
  1594. MqttClient.prototype._resubscribe = function () {
  1595. debug('_resubscribe')
  1596. const _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics)
  1597. if (!this._firstConnection &&
  1598. (this.options.clean || (this.options.protocolVersion === 5 && !this.connackPacket.sessionPresent)) &&
  1599. _resubscribeTopicsKeys.length > 0) {
  1600. if (this.options.resubscribe) {
  1601. if (this.options.protocolVersion === 5) {
  1602. debug('_resubscribe: protocolVersion 5')
  1603. for (let topicI = 0; topicI < _resubscribeTopicsKeys.length; topicI++) {
  1604. const resubscribeTopic = {}
  1605. resubscribeTopic[_resubscribeTopicsKeys[topicI]] = this._resubscribeTopics[_resubscribeTopicsKeys[topicI]]
  1606. resubscribeTopic.resubscribe = true
  1607. this.subscribe(resubscribeTopic, { properties: resubscribeTopic[_resubscribeTopicsKeys[topicI]].properties })
  1608. }
  1609. } else {
  1610. this._resubscribeTopics.resubscribe = true
  1611. this.subscribe(this._resubscribeTopics)
  1612. }
  1613. } else {
  1614. this._resubscribeTopics = {}
  1615. }
  1616. }
  1617. this._firstConnection = false
  1618. }
  1619. /**
  1620. * _onConnect
  1621. *
  1622. * @api private
  1623. */
  1624. MqttClient.prototype._onConnect = function (packet) {
  1625. if (this.disconnected) {
  1626. this.emit('connect', packet)
  1627. return
  1628. }
  1629. const that = this
  1630. this.connackPacket = packet
  1631. this.messageIdProvider.clear()
  1632. this._setupPingTimer()
  1633. this.connected = true
  1634. function startStreamProcess () {
  1635. let outStore = that.outgoingStore.createStream()
  1636. function clearStoreProcessing () {
  1637. that._storeProcessing = false
  1638. that._packetIdsDuringStoreProcessing = {}
  1639. }
  1640. that.once('close', remove)
  1641. outStore.on('error', function (err) {
  1642. clearStoreProcessing()
  1643. that._flushStoreProcessingQueue()
  1644. that.removeListener('close', remove)
  1645. that.emit('error', err)
  1646. })
  1647. function remove () {
  1648. outStore.destroy()
  1649. outStore = null
  1650. that._flushStoreProcessingQueue()
  1651. clearStoreProcessing()
  1652. }
  1653. function storeDeliver () {
  1654. // edge case, we wrapped this twice
  1655. if (!outStore) {
  1656. return
  1657. }
  1658. that._storeProcessing = true
  1659. const packet = outStore.read(1)
  1660. let cb
  1661. if (!packet) {
  1662. // read when data is available in the future
  1663. outStore.once('readable', storeDeliver)
  1664. return
  1665. }
  1666. // Skip already processed store packets
  1667. if (that._packetIdsDuringStoreProcessing[packet.messageId]) {
  1668. storeDeliver()
  1669. return
  1670. }
  1671. // Avoid unnecessary stream read operations when disconnected
  1672. if (!that.disconnecting && !that.reconnectTimer) {
  1673. cb = that.outgoing[packet.messageId] ? that.outgoing[packet.messageId].cb : null
  1674. that.outgoing[packet.messageId] = {
  1675. volatile: false,
  1676. cb: function (err, status) {
  1677. // Ensure that the original callback passed in to publish gets invoked
  1678. if (cb) {
  1679. cb(err, status)
  1680. }
  1681. storeDeliver()
  1682. }
  1683. }
  1684. that._packetIdsDuringStoreProcessing[packet.messageId] = true
  1685. if (that.messageIdProvider.register(packet.messageId)) {
  1686. that._sendPacket(packet)
  1687. } else {
  1688. debug('messageId: %d has already used.', packet.messageId)
  1689. }
  1690. } else if (outStore.destroy) {
  1691. outStore.destroy()
  1692. }
  1693. }
  1694. outStore.on('end', function () {
  1695. let allProcessed = true
  1696. for (const id in that._packetIdsDuringStoreProcessing) {
  1697. if (!that._packetIdsDuringStoreProcessing[id]) {
  1698. allProcessed = false
  1699. break
  1700. }
  1701. }
  1702. if (allProcessed) {
  1703. clearStoreProcessing()
  1704. that.removeListener('close', remove)
  1705. that._invokeAllStoreProcessingQueue()
  1706. that.emit('connect', packet)
  1707. } else {
  1708. startStreamProcess()
  1709. }
  1710. })
  1711. storeDeliver()
  1712. }
  1713. // start flowing
  1714. startStreamProcess()
  1715. }
  1716. MqttClient.prototype._invokeStoreProcessingQueue = function () {
  1717. if (this._storeProcessingQueue.length > 0) {
  1718. const f = this._storeProcessingQueue[0]
  1719. if (f && f.invoke()) {
  1720. this._storeProcessingQueue.shift()
  1721. return true
  1722. }
  1723. }
  1724. return false
  1725. }
  1726. MqttClient.prototype._invokeAllStoreProcessingQueue = function () {
  1727. while (this._invokeStoreProcessingQueue()) { /* empty */ }
  1728. }
  1729. MqttClient.prototype._flushStoreProcessingQueue = function () {
  1730. for (const f of this._storeProcessingQueue) {
  1731. if (f.cbStorePut) f.cbStorePut(new Error('Connection closed'))
  1732. if (f.callback) f.callback(new Error('Connection closed'))
  1733. }
  1734. this._storeProcessingQueue.splice(0)
  1735. }
  1736. module.exports = MqttClient
  1737. }, function(modId) { var map = {"./store":1682324647513,"./topic-alias-recv":1682324647514,"./topic-alias-send":1682324647515,"./default-message-id-provider":1682324647516,"./validations":1682324647517}; return __REQUIRE__(map[modId], modId); })
  1738. __DEFINE__(1682324647513, function(require, module, exports) {
  1739. /**
  1740. * Module dependencies
  1741. */
  1742. const xtend = require('xtend')
  1743. const Readable = require('readable-stream').Readable
  1744. const streamsOpts = { objectMode: true }
  1745. const defaultStoreOptions = {
  1746. clean: true
  1747. }
  1748. /**
  1749. * In-memory implementation of the message store
  1750. * This can actually be saved into files.
  1751. *
  1752. * @param {Object} [options] - store options
  1753. */
  1754. function Store (options) {
  1755. if (!(this instanceof Store)) {
  1756. return new Store(options)
  1757. }
  1758. this.options = options || {}
  1759. // Defaults
  1760. this.options = xtend(defaultStoreOptions, options)
  1761. this._inflights = new Map()
  1762. }
  1763. /**
  1764. * Adds a packet to the store, a packet is
  1765. * anything that has a messageId property.
  1766. *
  1767. */
  1768. Store.prototype.put = function (packet, cb) {
  1769. this._inflights.set(packet.messageId, packet)
  1770. if (cb) {
  1771. cb()
  1772. }
  1773. return this
  1774. }
  1775. /**
  1776. * Creates a stream with all the packets in the store
  1777. *
  1778. */
  1779. Store.prototype.createStream = function () {
  1780. const stream = new Readable(streamsOpts)
  1781. const values = []
  1782. let destroyed = false
  1783. let i = 0
  1784. this._inflights.forEach(function (value, key) {
  1785. values.push(value)
  1786. })
  1787. stream._read = function () {
  1788. if (!destroyed && i < values.length) {
  1789. this.push(values[i++])
  1790. } else {
  1791. this.push(null)
  1792. }
  1793. }
  1794. stream.destroy = function () {
  1795. if (destroyed) {
  1796. return
  1797. }
  1798. const self = this
  1799. destroyed = true
  1800. setTimeout(function () {
  1801. self.emit('close')
  1802. }, 0)
  1803. }
  1804. return stream
  1805. }
  1806. /**
  1807. * deletes a packet from the store.
  1808. */
  1809. Store.prototype.del = function (packet, cb) {
  1810. packet = this._inflights.get(packet.messageId)
  1811. if (packet) {
  1812. this._inflights.delete(packet.messageId)
  1813. cb(null, packet)
  1814. } else if (cb) {
  1815. cb(new Error('missing packet'))
  1816. }
  1817. return this
  1818. }
  1819. /**
  1820. * get a packet from the store.
  1821. */
  1822. Store.prototype.get = function (packet, cb) {
  1823. packet = this._inflights.get(packet.messageId)
  1824. if (packet) {
  1825. cb(null, packet)
  1826. } else if (cb) {
  1827. cb(new Error('missing packet'))
  1828. }
  1829. return this
  1830. }
  1831. /**
  1832. * Close the store
  1833. */
  1834. Store.prototype.close = function (cb) {
  1835. if (this.options.clean) {
  1836. this._inflights = null
  1837. }
  1838. if (cb) {
  1839. cb()
  1840. }
  1841. }
  1842. module.exports = Store
  1843. }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); })
  1844. __DEFINE__(1682324647514, function(require, module, exports) {
  1845. /**
  1846. * Topic Alias receiving manager
  1847. * This holds alias to topic map
  1848. * @param {Number} [max] - topic alias maximum entries
  1849. */
  1850. function TopicAliasRecv (max) {
  1851. if (!(this instanceof TopicAliasRecv)) {
  1852. return new TopicAliasRecv(max)
  1853. }
  1854. this.aliasToTopic = {}
  1855. this.max = max
  1856. }
  1857. /**
  1858. * Insert or update topic - alias entry.
  1859. * @param {String} [topic] - topic
  1860. * @param {Number} [alias] - topic alias
  1861. * @returns {Boolean} - if success return true otherwise false
  1862. */
  1863. TopicAliasRecv.prototype.put = function (topic, alias) {
  1864. if (alias === 0 || alias > this.max) {
  1865. return false
  1866. }
  1867. this.aliasToTopic[alias] = topic
  1868. this.length = Object.keys(this.aliasToTopic).length
  1869. return true
  1870. }
  1871. /**
  1872. * Get topic by alias
  1873. * @param {String} [topic] - topic
  1874. * @returns {Number} - if mapped topic exists return topic alias, otherwise return undefined
  1875. */
  1876. TopicAliasRecv.prototype.getTopicByAlias = function (alias) {
  1877. return this.aliasToTopic[alias]
  1878. }
  1879. /**
  1880. * Clear all entries
  1881. */
  1882. TopicAliasRecv.prototype.clear = function () {
  1883. this.aliasToTopic = {}
  1884. }
  1885. module.exports = TopicAliasRecv
  1886. }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); })
  1887. __DEFINE__(1682324647515, function(require, module, exports) {
  1888. /**
  1889. * Module dependencies
  1890. */
  1891. const LruMap = require('lru-cache')
  1892. const NumberAllocator = require('number-allocator').NumberAllocator
  1893. /**
  1894. * Topic Alias sending manager
  1895. * This holds both topic to alias and alias to topic map
  1896. * @param {Number} [max] - topic alias maximum entries
  1897. */
  1898. function TopicAliasSend (max) {
  1899. if (!(this instanceof TopicAliasSend)) {
  1900. return new TopicAliasSend(max)
  1901. }
  1902. if (max > 0) {
  1903. this.aliasToTopic = new LruMap({ max: max })
  1904. this.topicToAlias = {}
  1905. this.numberAllocator = new NumberAllocator(1, max)
  1906. this.max = max
  1907. this.length = 0
  1908. }
  1909. }
  1910. /**
  1911. * Insert or update topic - alias entry.
  1912. * @param {String} [topic] - topic
  1913. * @param {Number} [alias] - topic alias
  1914. * @returns {Boolean} - if success return true otherwise false
  1915. */
  1916. TopicAliasSend.prototype.put = function (topic, alias) {
  1917. if (alias === 0 || alias > this.max) {
  1918. return false
  1919. }
  1920. const entry = this.aliasToTopic.get(alias)
  1921. if (entry) {
  1922. delete this.topicToAlias[entry]
  1923. }
  1924. this.aliasToTopic.set(alias, topic)
  1925. this.topicToAlias[topic] = alias
  1926. this.numberAllocator.use(alias)
  1927. this.length = this.aliasToTopic.length
  1928. return true
  1929. }
  1930. /**
  1931. * Get topic by alias
  1932. * @param {Number} [alias] - topic alias
  1933. * @returns {String} - if mapped topic exists return topic, otherwise return undefined
  1934. */
  1935. TopicAliasSend.prototype.getTopicByAlias = function (alias) {
  1936. return this.aliasToTopic.get(alias)
  1937. }
  1938. /**
  1939. * Get topic by alias
  1940. * @param {String} [topic] - topic
  1941. * @returns {Number} - if mapped topic exists return topic alias, otherwise return undefined
  1942. */
  1943. TopicAliasSend.prototype.getAliasByTopic = function (topic) {
  1944. const alias = this.topicToAlias[topic]
  1945. if (typeof alias !== 'undefined') {
  1946. this.aliasToTopic.get(alias) // LRU update
  1947. }
  1948. return alias
  1949. }
  1950. /**
  1951. * Clear all entries
  1952. */
  1953. TopicAliasSend.prototype.clear = function () {
  1954. this.aliasToTopic.reset()
  1955. this.topicToAlias = {}
  1956. this.numberAllocator.clear()
  1957. this.length = 0
  1958. }
  1959. /**
  1960. * Get Least Recently Used (LRU) topic alias
  1961. * @returns {Number} - if vacant alias exists then return it, otherwise then return LRU alias
  1962. */
  1963. TopicAliasSend.prototype.getLruAlias = function () {
  1964. const alias = this.numberAllocator.firstVacant()
  1965. if (alias) return alias
  1966. return this.aliasToTopic.keys()[this.aliasToTopic.length - 1]
  1967. }
  1968. module.exports = TopicAliasSend
  1969. }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); })
  1970. __DEFINE__(1682324647516, function(require, module, exports) {
  1971. /**
  1972. * DefaultMessageAllocator constructor
  1973. * @constructor
  1974. */
  1975. function DefaultMessageIdProvider () {
  1976. if (!(this instanceof DefaultMessageIdProvider)) {
  1977. return new DefaultMessageIdProvider()
  1978. }
  1979. /**
  1980. * MessageIDs starting with 1
  1981. * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
  1982. */
  1983. this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
  1984. }
  1985. /**
  1986. * allocate
  1987. *
  1988. * Get the next messageId.
  1989. * @return unsigned int
  1990. */
  1991. DefaultMessageIdProvider.prototype.allocate = function () {
  1992. // id becomes current state of this.nextId and increments afterwards
  1993. const id = this.nextId++
  1994. // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
  1995. if (this.nextId === 65536) {
  1996. this.nextId = 1
  1997. }
  1998. return id
  1999. }
  2000. /**
  2001. * getLastAllocated
  2002. * Get the last allocated messageId.
  2003. * @return unsigned int
  2004. */
  2005. DefaultMessageIdProvider.prototype.getLastAllocated = function () {
  2006. return (this.nextId === 1) ? 65535 : (this.nextId - 1)
  2007. }
  2008. /**
  2009. * register
  2010. * Register messageId. If success return true, otherwise return false.
  2011. * @param { unsigned int } - messageId to register,
  2012. * @return boolean
  2013. */
  2014. DefaultMessageIdProvider.prototype.register = function (messageId) {
  2015. return true
  2016. }
  2017. /**
  2018. * deallocate
  2019. * Deallocate messageId.
  2020. * @param { unsigned int } - messageId to deallocate,
  2021. */
  2022. DefaultMessageIdProvider.prototype.deallocate = function (messageId) {
  2023. }
  2024. /**
  2025. * clear
  2026. * Deallocate all messageIds.
  2027. */
  2028. DefaultMessageIdProvider.prototype.clear = function () {
  2029. }
  2030. module.exports = DefaultMessageIdProvider
  2031. }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); })
  2032. __DEFINE__(1682324647517, function(require, module, exports) {
  2033. /**
  2034. * Validate a topic to see if it's valid or not.
  2035. * A topic is valid if it follow below rules:
  2036. * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'
  2037. * - Rule #2: Part `#` must be located at the end of the mailbox
  2038. *
  2039. * @param {String} topic - A topic
  2040. * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.
  2041. */
  2042. function validateTopic (topic) {
  2043. const parts = topic.split('/')
  2044. for (let i = 0; i < parts.length; i++) {
  2045. if (parts[i] === '+') {
  2046. continue
  2047. }
  2048. if (parts[i] === '#') {
  2049. // for Rule #2
  2050. return i === parts.length - 1
  2051. }
  2052. if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {
  2053. return false
  2054. }
  2055. }
  2056. return true
  2057. }
  2058. /**
  2059. * Validate an array of topics to see if any of them is valid or not
  2060. * @param {Array} topics - Array of topics
  2061. * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one
  2062. */
  2063. function validateTopics (topics) {
  2064. if (topics.length === 0) {
  2065. return 'empty_topic_list'
  2066. }
  2067. for (let i = 0; i < topics.length; i++) {
  2068. if (!validateTopic(topics[i])) {
  2069. return topics[i]
  2070. }
  2071. }
  2072. return null
  2073. }
  2074. module.exports = {
  2075. validateTopics: validateTopics
  2076. }
  2077. }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); })
  2078. __DEFINE__(1682324647518, function(require, module, exports) {
  2079. const MqttClient = require('../client')
  2080. const Store = require('../store')
  2081. const url = require('url')
  2082. const xtend = require('xtend')
  2083. const debug = require('debug')('mqttjs')
  2084. const protocols = {}
  2085. // eslint-disable-next-line camelcase
  2086. if ((typeof process !== 'undefined' && process.title !== 'browser') || typeof __webpack_require__ !== 'function') {
  2087. protocols.mqtt = require('./tcp')
  2088. protocols.tcp = require('./tcp')
  2089. protocols.ssl = require('./tls')
  2090. protocols.tls = require('./tls')
  2091. protocols.mqtts = require('./tls')
  2092. } else {
  2093. protocols.wx = require('./wx')
  2094. protocols.wxs = require('./wx')
  2095. protocols.ali = require('./ali')
  2096. protocols.alis = require('./ali')
  2097. }
  2098. protocols.ws = require('./ws')
  2099. protocols.wss = require('./ws')
  2100. /**
  2101. * Parse the auth attribute and merge username and password in the options object.
  2102. *
  2103. * @param {Object} [opts] option object
  2104. */
  2105. function parseAuthOptions (opts) {
  2106. let matches
  2107. if (opts.auth) {
  2108. matches = opts.auth.match(/^(.+):(.+)$/)
  2109. if (matches) {
  2110. opts.username = matches[1]
  2111. opts.password = matches[2]
  2112. } else {
  2113. opts.username = opts.auth
  2114. }
  2115. }
  2116. }
  2117. /**
  2118. * connect - connect to an MQTT broker.
  2119. *
  2120. * @param {String} [brokerUrl] - url of the broker, optional
  2121. * @param {Object} opts - see MqttClient#constructor
  2122. */
  2123. function connect (brokerUrl, opts) {
  2124. debug('connecting to an MQTT broker...')
  2125. if ((typeof brokerUrl === 'object') && !opts) {
  2126. opts = brokerUrl
  2127. brokerUrl = null
  2128. }
  2129. opts = opts || {}
  2130. if (brokerUrl) {
  2131. // eslint-disable-next-line
  2132. const parsed = url.parse(brokerUrl, true)
  2133. if (parsed.port != null) {
  2134. parsed.port = Number(parsed.port)
  2135. }
  2136. opts = xtend(parsed, opts)
  2137. if (opts.protocol === null) {
  2138. throw new Error('Missing protocol')
  2139. }
  2140. opts.protocol = opts.protocol.replace(/:$/, '')
  2141. }
  2142. // merge in the auth options if supplied
  2143. parseAuthOptions(opts)
  2144. // support clientId passed in the query string of the url
  2145. if (opts.query && typeof opts.query.clientId === 'string') {
  2146. opts.clientId = opts.query.clientId
  2147. }
  2148. if (opts.cert && opts.key) {
  2149. if (opts.protocol) {
  2150. if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) {
  2151. switch (opts.protocol) {
  2152. case 'mqtt':
  2153. opts.protocol = 'mqtts'
  2154. break
  2155. case 'ws':
  2156. opts.protocol = 'wss'
  2157. break
  2158. case 'wx':
  2159. opts.protocol = 'wxs'
  2160. break
  2161. case 'ali':
  2162. opts.protocol = 'alis'
  2163. break
  2164. default:
  2165. throw new Error('Unknown protocol for secure connection: "' + opts.protocol + '"!')
  2166. }
  2167. }
  2168. } else {
  2169. // A cert and key was provided, however no protocol was specified, so we will throw an error.
  2170. throw new Error('Missing secure protocol key')
  2171. }
  2172. }
  2173. if (!protocols[opts.protocol]) {
  2174. const isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
  2175. opts.protocol = [
  2176. 'mqtt',
  2177. 'mqtts',
  2178. 'ws',
  2179. 'wss',
  2180. 'wx',
  2181. 'wxs',
  2182. 'ali',
  2183. 'alis'
  2184. ].filter(function (key, index) {
  2185. if (isSecure && index % 2 === 0) {
  2186. // Skip insecure protocols when requesting a secure one.
  2187. return false
  2188. }
  2189. return (typeof protocols[key] === 'function')
  2190. })[0]
  2191. }
  2192. if (opts.clean === false && !opts.clientId) {
  2193. throw new Error('Missing clientId for unclean clients')
  2194. }
  2195. if (opts.protocol) {
  2196. opts.defaultProtocol = opts.protocol
  2197. }
  2198. function wrapper (client) {
  2199. if (opts.servers) {
  2200. if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {
  2201. client._reconnectCount = 0
  2202. }
  2203. opts.host = opts.servers[client._reconnectCount].host
  2204. opts.port = opts.servers[client._reconnectCount].port
  2205. opts.protocol = (!opts.servers[client._reconnectCount].protocol ? opts.defaultProtocol : opts.servers[client._reconnectCount].protocol)
  2206. opts.hostname = opts.host
  2207. client._reconnectCount++
  2208. }
  2209. debug('calling streambuilder for', opts.protocol)
  2210. return protocols[opts.protocol](client, opts)
  2211. }
  2212. const client = new MqttClient(wrapper, opts)
  2213. client.on('error', function () { /* Automatically set up client error handling */ })
  2214. return client
  2215. }
  2216. module.exports = connect
  2217. module.exports.connect = connect
  2218. module.exports.MqttClient = MqttClient
  2219. module.exports.Store = Store
  2220. }, function(modId) { var map = {"../client":1682324647512,"../store":1682324647513,"./tcp":1682324647519,"./tls":1682324647520,"./wx":1682324647521,"./ali":1682324647522,"./ws":1682324647523}; return __REQUIRE__(map[modId], modId); })
  2221. __DEFINE__(1682324647519, function(require, module, exports) {
  2222. const net = require('net')
  2223. const debug = require('debug')('mqttjs:tcp')
  2224. /*
  2225. variables port and host can be removed since
  2226. you have all required information in opts object
  2227. */
  2228. function streamBuilder (client, opts) {
  2229. opts.port = opts.port || 1883
  2230. opts.hostname = opts.hostname || opts.host || 'localhost'
  2231. const port = opts.port
  2232. const host = opts.hostname
  2233. debug('port %d and host %s', port, host)
  2234. return net.createConnection(port, host)
  2235. }
  2236. module.exports = streamBuilder
  2237. }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); })
  2238. __DEFINE__(1682324647520, function(require, module, exports) {
  2239. const tls = require('tls')
  2240. const net = require('net')
  2241. const debug = require('debug')('mqttjs:tls')
  2242. function buildBuilder (mqttClient, opts) {
  2243. opts.port = opts.port || 8883
  2244. opts.host = opts.hostname || opts.host || 'localhost'
  2245. if (net.isIP(opts.host) === 0) {
  2246. opts.servername = opts.host
  2247. }
  2248. opts.rejectUnauthorized = opts.rejectUnauthorized !== false
  2249. delete opts.path
  2250. debug('port %d host %s rejectUnauthorized %b', opts.port, opts.host, opts.rejectUnauthorized)
  2251. const connection = tls.connect(opts)
  2252. /* eslint no-use-before-define: [2, "nofunc"] */
  2253. connection.on('secureConnect', function () {
  2254. if (opts.rejectUnauthorized && !connection.authorized) {
  2255. connection.emit('error', new Error('TLS not authorized'))
  2256. } else {
  2257. connection.removeListener('error', handleTLSerrors)
  2258. }
  2259. })
  2260. function handleTLSerrors (err) {
  2261. // How can I get verify this error is a tls error?
  2262. if (opts.rejectUnauthorized) {
  2263. mqttClient.emit('error', err)
  2264. }
  2265. // close this connection to match the behaviour of net
  2266. // otherwise all we get is an error from the connection
  2267. // and close event doesn't fire. This is a work around
  2268. // to enable the reconnect code to work the same as with
  2269. // net.createConnection
  2270. connection.end()
  2271. }
  2272. connection.on('error', handleTLSerrors)
  2273. return connection
  2274. }
  2275. module.exports = buildBuilder
  2276. }, function(modId) { var map = {"tls":1682324647520}; return __REQUIRE__(map[modId], modId); })
  2277. __DEFINE__(1682324647521, function(require, module, exports) {
  2278. const { Buffer } = require('buffer')
  2279. const Transform = require('readable-stream').Transform
  2280. const duplexify = require('duplexify')
  2281. /* global wx */
  2282. let socketTask, proxy, stream
  2283. function buildProxy () {
  2284. const proxy = new Transform()
  2285. proxy._write = function (chunk, encoding, next) {
  2286. socketTask.send({
  2287. data: chunk.buffer,
  2288. success: function () {
  2289. next()
  2290. },
  2291. fail: function (errMsg) {
  2292. next(new Error(errMsg))
  2293. }
  2294. })
  2295. }
  2296. proxy._flush = function socketEnd (done) {
  2297. socketTask.close({
  2298. success: function () {
  2299. done()
  2300. }
  2301. })
  2302. }
  2303. return proxy
  2304. }
  2305. function setDefaultOpts (opts) {
  2306. if (!opts.hostname) {
  2307. opts.hostname = 'localhost'
  2308. }
  2309. if (!opts.path) {
  2310. opts.path = '/'
  2311. }
  2312. if (!opts.wsOptions) {
  2313. opts.wsOptions = {}
  2314. }
  2315. }
  2316. function buildUrl (opts, client) {
  2317. const protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
  2318. let url = protocol + '://' + opts.hostname + opts.path
  2319. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  2320. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  2321. }
  2322. if (typeof (opts.transformWsUrl) === 'function') {
  2323. url = opts.transformWsUrl(url, opts, client)
  2324. }
  2325. return url
  2326. }
  2327. function bindEventHandler () {
  2328. socketTask.onOpen(function () {
  2329. stream.setReadable(proxy)
  2330. stream.setWritable(proxy)
  2331. stream.emit('connect')
  2332. })
  2333. socketTask.onMessage(function (res) {
  2334. let data = res.data
  2335. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  2336. else data = Buffer.from(data, 'utf8')
  2337. proxy.push(data)
  2338. })
  2339. socketTask.onClose(function () {
  2340. stream.end()
  2341. stream.destroy()
  2342. })
  2343. socketTask.onError(function (res) {
  2344. stream.destroy(new Error(res.errMsg))
  2345. })
  2346. }
  2347. function buildStream (client, opts) {
  2348. opts.hostname = opts.hostname || opts.host
  2349. if (!opts.hostname) {
  2350. throw new Error('Could not determine host. Specify host manually.')
  2351. }
  2352. const websocketSubProtocol =
  2353. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  2354. ? 'mqttv3.1'
  2355. : 'mqtt'
  2356. setDefaultOpts(opts)
  2357. const url = buildUrl(opts, client)
  2358. socketTask = wx.connectSocket({
  2359. url: url,
  2360. protocols: [websocketSubProtocol]
  2361. })
  2362. proxy = buildProxy()
  2363. stream = duplexify.obj()
  2364. stream._destroy = function (err, cb) {
  2365. socketTask.close({
  2366. success: function () {
  2367. cb && cb(err)
  2368. }
  2369. })
  2370. }
  2371. const destroyRef = stream.destroy
  2372. stream.destroy = function () {
  2373. stream.destroy = destroyRef
  2374. const self = this
  2375. setTimeout(function () {
  2376. socketTask.close({
  2377. fail: function () {
  2378. self._destroy(new Error())
  2379. }
  2380. })
  2381. }, 0)
  2382. }.bind(stream)
  2383. bindEventHandler()
  2384. return stream
  2385. }
  2386. module.exports = buildStream
  2387. }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); })
  2388. __DEFINE__(1682324647522, function(require, module, exports) {
  2389. const { Buffer } = require('buffer')
  2390. const Transform = require('readable-stream').Transform
  2391. const duplexify = require('duplexify')
  2392. /* global FileReader */
  2393. let my
  2394. let proxy
  2395. let stream
  2396. let isInitialized = false
  2397. function buildProxy () {
  2398. const proxy = new Transform()
  2399. proxy._write = function (chunk, encoding, next) {
  2400. my.sendSocketMessage({
  2401. data: chunk.buffer,
  2402. success: function () {
  2403. next()
  2404. },
  2405. fail: function () {
  2406. next(new Error())
  2407. }
  2408. })
  2409. }
  2410. proxy._flush = function socketEnd (done) {
  2411. my.closeSocket({
  2412. success: function () {
  2413. done()
  2414. }
  2415. })
  2416. }
  2417. return proxy
  2418. }
  2419. function setDefaultOpts (opts) {
  2420. if (!opts.hostname) {
  2421. opts.hostname = 'localhost'
  2422. }
  2423. if (!opts.path) {
  2424. opts.path = '/'
  2425. }
  2426. if (!opts.wsOptions) {
  2427. opts.wsOptions = {}
  2428. }
  2429. }
  2430. function buildUrl (opts, client) {
  2431. const protocol = opts.protocol === 'alis' ? 'wss' : 'ws'
  2432. let url = protocol + '://' + opts.hostname + opts.path
  2433. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  2434. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  2435. }
  2436. if (typeof (opts.transformWsUrl) === 'function') {
  2437. url = opts.transformWsUrl(url, opts, client)
  2438. }
  2439. return url
  2440. }
  2441. function bindEventHandler () {
  2442. if (isInitialized) return
  2443. isInitialized = true
  2444. my.onSocketOpen(function () {
  2445. stream.setReadable(proxy)
  2446. stream.setWritable(proxy)
  2447. stream.emit('connect')
  2448. })
  2449. my.onSocketMessage(function (res) {
  2450. if (typeof res.data === 'string') {
  2451. const buffer = Buffer.from(res.data, 'base64')
  2452. proxy.push(buffer)
  2453. } else {
  2454. const reader = new FileReader()
  2455. reader.addEventListener('load', function () {
  2456. let data = reader.result
  2457. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  2458. else data = Buffer.from(data, 'utf8')
  2459. proxy.push(data)
  2460. })
  2461. reader.readAsArrayBuffer(res.data)
  2462. }
  2463. })
  2464. my.onSocketClose(function () {
  2465. stream.end()
  2466. stream.destroy()
  2467. })
  2468. my.onSocketError(function (res) {
  2469. stream.destroy(res)
  2470. })
  2471. }
  2472. function buildStream (client, opts) {
  2473. opts.hostname = opts.hostname || opts.host
  2474. if (!opts.hostname) {
  2475. throw new Error('Could not determine host. Specify host manually.')
  2476. }
  2477. const websocketSubProtocol =
  2478. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  2479. ? 'mqttv3.1'
  2480. : 'mqtt'
  2481. setDefaultOpts(opts)
  2482. const url = buildUrl(opts, client)
  2483. my = opts.my
  2484. my.connectSocket({
  2485. url: url,
  2486. protocols: websocketSubProtocol
  2487. })
  2488. proxy = buildProxy()
  2489. stream = duplexify.obj()
  2490. bindEventHandler()
  2491. return stream
  2492. }
  2493. module.exports = buildStream
  2494. }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); })
  2495. __DEFINE__(1682324647523, function(require, module, exports) {
  2496. const { Buffer } = require('buffer')
  2497. const WS = require('ws')
  2498. const debug = require('debug')('mqttjs:ws')
  2499. const duplexify = require('duplexify')
  2500. const Transform = require('readable-stream').Transform
  2501. const WSS_OPTIONS = [
  2502. 'rejectUnauthorized',
  2503. 'ca',
  2504. 'cert',
  2505. 'key',
  2506. 'pfx',
  2507. 'passphrase'
  2508. ]
  2509. // eslint-disable-next-line camelcase
  2510. const IS_BROWSER = (typeof process !== 'undefined' && process.title === 'browser') || typeof __webpack_require__ === 'function'
  2511. function buildUrl (opts, client) {
  2512. let url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  2513. if (typeof (opts.transformWsUrl) === 'function') {
  2514. url = opts.transformWsUrl(url, opts, client)
  2515. }
  2516. return url
  2517. }
  2518. function setDefaultOpts (opts) {
  2519. const options = opts
  2520. if (!opts.hostname) {
  2521. options.hostname = 'localhost'
  2522. }
  2523. if (!opts.port) {
  2524. if (opts.protocol === 'wss') {
  2525. options.port = 443
  2526. } else {
  2527. options.port = 80
  2528. }
  2529. }
  2530. if (!opts.path) {
  2531. options.path = '/'
  2532. }
  2533. if (!opts.wsOptions) {
  2534. options.wsOptions = {}
  2535. }
  2536. if (!IS_BROWSER && opts.protocol === 'wss') {
  2537. // Add cert/key/ca etc options
  2538. WSS_OPTIONS.forEach(function (prop) {
  2539. if (Object.prototype.hasOwnProperty.call(opts, prop) && !Object.prototype.hasOwnProperty.call(opts.wsOptions, prop)) {
  2540. options.wsOptions[prop] = opts[prop]
  2541. }
  2542. })
  2543. }
  2544. return options
  2545. }
  2546. function setDefaultBrowserOpts (opts) {
  2547. const options = setDefaultOpts(opts)
  2548. if (!options.hostname) {
  2549. options.hostname = options.host
  2550. }
  2551. if (!options.hostname) {
  2552. // Throwing an error in a Web Worker if no `hostname` is given, because we
  2553. // can not determine the `hostname` automatically. If connecting to
  2554. // localhost, please supply the `hostname` as an argument.
  2555. if (typeof (document) === 'undefined') {
  2556. throw new Error('Could not determine host. Specify host manually.')
  2557. }
  2558. const parsed = new URL(document.URL)
  2559. options.hostname = parsed.hostname
  2560. if (!options.port) {
  2561. options.port = parsed.port
  2562. }
  2563. }
  2564. // objectMode should be defined for logic
  2565. if (options.objectMode === undefined) {
  2566. options.objectMode = !(options.binary === true || options.binary === undefined)
  2567. }
  2568. return options
  2569. }
  2570. function createWebSocket (client, url, opts) {
  2571. debug('createWebSocket')
  2572. debug('protocol: ' + opts.protocolId + ' ' + opts.protocolVersion)
  2573. const websocketSubProtocol =
  2574. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  2575. ? 'mqttv3.1'
  2576. : 'mqtt'
  2577. debug('creating new Websocket for url: ' + url + ' and protocol: ' + websocketSubProtocol)
  2578. const socket = new WS(url, [websocketSubProtocol], opts.wsOptions)
  2579. return socket
  2580. }
  2581. function createBrowserWebSocket (client, opts) {
  2582. const websocketSubProtocol =
  2583. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  2584. ? 'mqttv3.1'
  2585. : 'mqtt'
  2586. const url = buildUrl(opts, client)
  2587. /* global WebSocket */
  2588. const socket = new WebSocket(url, [websocketSubProtocol])
  2589. socket.binaryType = 'arraybuffer'
  2590. return socket
  2591. }
  2592. function streamBuilder (client, opts) {
  2593. debug('streamBuilder')
  2594. const options = setDefaultOpts(opts)
  2595. const url = buildUrl(options, client)
  2596. const socket = createWebSocket(client, url, options)
  2597. const webSocketStream = WS.createWebSocketStream(socket, options.wsOptions)
  2598. webSocketStream.url = url
  2599. socket.on('close', () => { webSocketStream.destroy() })
  2600. return webSocketStream
  2601. }
  2602. function browserStreamBuilder (client, opts) {
  2603. debug('browserStreamBuilder')
  2604. let stream
  2605. const options = setDefaultBrowserOpts(opts)
  2606. // sets the maximum socket buffer size before throttling
  2607. const bufferSize = options.browserBufferSize || 1024 * 512
  2608. const bufferTimeout = opts.browserBufferTimeout || 1000
  2609. const coerceToBuffer = !opts.objectMode
  2610. const socket = createBrowserWebSocket(client, opts)
  2611. const proxy = buildProxy(opts, socketWriteBrowser, socketEndBrowser)
  2612. if (!opts.objectMode) {
  2613. proxy._writev = writev
  2614. }
  2615. proxy.on('close', () => { socket.close() })
  2616. const eventListenerSupport = (typeof socket.addEventListener !== 'undefined')
  2617. // was already open when passed in
  2618. if (socket.readyState === socket.OPEN) {
  2619. stream = proxy
  2620. } else {
  2621. stream = stream = duplexify(undefined, undefined, opts)
  2622. if (!opts.objectMode) {
  2623. stream._writev = writev
  2624. }
  2625. if (eventListenerSupport) {
  2626. socket.addEventListener('open', onopen)
  2627. } else {
  2628. socket.onopen = onopen
  2629. }
  2630. }
  2631. stream.socket = socket
  2632. if (eventListenerSupport) {
  2633. socket.addEventListener('close', onclose)
  2634. socket.addEventListener('error', onerror)
  2635. socket.addEventListener('message', onmessage)
  2636. } else {
  2637. socket.onclose = onclose
  2638. socket.onerror = onerror
  2639. socket.onmessage = onmessage
  2640. }
  2641. // methods for browserStreamBuilder
  2642. function buildProxy (options, socketWrite, socketEnd) {
  2643. const proxy = new Transform({
  2644. objectModeMode: options.objectMode
  2645. })
  2646. proxy._write = socketWrite
  2647. proxy._flush = socketEnd
  2648. return proxy
  2649. }
  2650. function onopen () {
  2651. stream.setReadable(proxy)
  2652. stream.setWritable(proxy)
  2653. stream.emit('connect')
  2654. }
  2655. function onclose () {
  2656. stream.end()
  2657. stream.destroy()
  2658. }
  2659. function onerror (err) {
  2660. stream.destroy(err)
  2661. }
  2662. function onmessage (event) {
  2663. let data = event.data
  2664. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  2665. else data = Buffer.from(data, 'utf8')
  2666. proxy.push(data)
  2667. }
  2668. // this is to be enabled only if objectMode is false
  2669. function writev (chunks, cb) {
  2670. const buffers = new Array(chunks.length)
  2671. for (let i = 0; i < chunks.length; i++) {
  2672. if (typeof chunks[i].chunk === 'string') {
  2673. buffers[i] = Buffer.from(chunks[i], 'utf8')
  2674. } else {
  2675. buffers[i] = chunks[i].chunk
  2676. }
  2677. }
  2678. this._write(Buffer.concat(buffers), 'binary', cb)
  2679. }
  2680. function socketWriteBrowser (chunk, enc, next) {
  2681. if (socket.bufferedAmount > bufferSize) {
  2682. // throttle data until buffered amount is reduced.
  2683. setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)
  2684. }
  2685. if (coerceToBuffer && typeof chunk === 'string') {
  2686. chunk = Buffer.from(chunk, 'utf8')
  2687. }
  2688. try {
  2689. socket.send(chunk)
  2690. } catch (err) {
  2691. return next(err)
  2692. }
  2693. next()
  2694. }
  2695. function socketEndBrowser (done) {
  2696. socket.close()
  2697. done()
  2698. }
  2699. // end methods for browserStreamBuilder
  2700. return stream
  2701. }
  2702. if (IS_BROWSER) {
  2703. module.exports = browserStreamBuilder
  2704. } else {
  2705. module.exports = streamBuilder
  2706. }
  2707. }, function(modId) { var map = {"ws":1682324647523}; return __REQUIRE__(map[modId], modId); })
  2708. __DEFINE__(1682324647524, function(require, module, exports) {
  2709. const NumberAllocator = require('number-allocator').NumberAllocator
  2710. /**
  2711. * UniqueMessageAllocator constructor
  2712. * @constructor
  2713. */
  2714. function UniqueMessageIdProvider () {
  2715. if (!(this instanceof UniqueMessageIdProvider)) {
  2716. return new UniqueMessageIdProvider()
  2717. }
  2718. this.numberAllocator = new NumberAllocator(1, 65535)
  2719. }
  2720. /**
  2721. * allocate
  2722. *
  2723. * Get the next messageId.
  2724. * @return if messageId is fully allocated then return null,
  2725. * otherwise return the smallest usable unsigned int messageId.
  2726. */
  2727. UniqueMessageIdProvider.prototype.allocate = function () {
  2728. this.lastId = this.numberAllocator.alloc()
  2729. return this.lastId
  2730. }
  2731. /**
  2732. * getLastAllocated
  2733. * Get the last allocated messageId.
  2734. * @return unsigned int
  2735. */
  2736. UniqueMessageIdProvider.prototype.getLastAllocated = function () {
  2737. return this.lastId
  2738. }
  2739. /**
  2740. * register
  2741. * Register messageId. If success return true, otherwise return false.
  2742. * @param { unsigned int } - messageId to register,
  2743. * @return boolean
  2744. */
  2745. UniqueMessageIdProvider.prototype.register = function (messageId) {
  2746. return this.numberAllocator.use(messageId)
  2747. }
  2748. /**
  2749. * deallocate
  2750. * Deallocate messageId.
  2751. * @param { unsigned int } - messageId to deallocate,
  2752. */
  2753. UniqueMessageIdProvider.prototype.deallocate = function (messageId) {
  2754. this.numberAllocator.free(messageId)
  2755. }
  2756. /**
  2757. * clear
  2758. * Deallocate all messageIds.
  2759. */
  2760. UniqueMessageIdProvider.prototype.clear = function () {
  2761. this.numberAllocator.clear()
  2762. }
  2763. module.exports = UniqueMessageIdProvider
  2764. }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); })
  2765. return __REQUIRE__(1682324647511);
  2766. })()
  2767. //miniprogram-npm-outsideDeps=["events","mqtt-packet","readable-stream","inherits","reinterval","rfdc/default","xtend","debug","lru-cache","number-allocator","url","net","buffer","duplexify"]
  2768. //# sourceMappingURL=index.js.map