-
-
Notifications
You must be signed in to change notification settings - Fork 232
/
client.js
399 lines (335 loc) · 9.66 KB
/
client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
'use strict'
const mqtt = require('mqtt-packet')
const EventEmitter = require('events')
const util = require('util')
const eos = require('end-of-stream')
const Packet = require('aedes-packet')
const write = require('./write')
const QoSPacket = require('./qos-packet')
const handleSubscribe = require('./handlers/subscribe')
const handleUnsubscribe = require('./handlers/unsubscribe')
const handle = require('./handlers')
const { pipeline } = require('stream')
const { through } = require('./utils')
module.exports = Client
function Client (broker, conn, req) {
const that = this
// metadata
this.closed = false
this.connecting = false
this.connected = false
this.connackSent = false
this.errored = false
// mqtt params
this.id = null
this.clean = true
this.version = null
this.subscriptions = {}
this.duplicates = {}
this.broker = broker
this.conn = conn
conn.client = this
this._disconnected = false
this._authorized = false
this._parsingBatch = 1
this._nextId = Math.ceil(Math.random() * 65535)
this.req = req
this.connDetails = req ? req.connDetails : null
// we use two variables for the will
// because we store in _will while
// we are authenticating
this.will = null
this._will = null
this._parser = mqtt.parser()
this._parser.client = this
this._parser._queue = [] // queue packets received before client fires 'connect' event. Prevents memory leaks on 'connect' event
this._parser.on('packet', enqueue)
this.once('connected', dequeue)
function nextBatch (err) {
if (err) {
that.emit('error', err)
return
}
const client = that
if (client._paused) {
return
}
that._parsingBatch--
if (that._parsingBatch <= 0) {
that._parsingBatch = 0
const buf = client.conn.read(null)
if (buf) {
client._parser.parse(buf)
}
}
}
this._nextBatch = nextBatch
conn.on('readable', nextBatch)
this.on('error', onError)
conn.on('error', this.emit.bind(this, 'error'))
this._parser.on('error', this.emit.bind(this, 'error'))
conn.on('end', this.close.bind(this))
this._eos = eos(this.conn, this.close.bind(this))
const getToForwardPacket = (_packet) => {
// Mqttv5 3.8.3.1: https://docs.oasis-open.org/mqtt/mqtt/v5.0/mqtt-v5.0.html#_Toc3901169
// prevent to forward messages sent by the same client when no-local flag is set
if (_packet.clientId === that.id && _packet.nl) return
const toForward = dedupe(that, _packet) &&
that.broker.authorizeForward(that, _packet)
return toForward
}
this.deliver0 = function deliverQoS0 (_packet, cb) {
const toForward = getToForwardPacket(_packet)
if (toForward) {
// Give nodejs some time to clear stacks, or we will see
// "Maximum call stack size exceeded" in a very high load
setImmediate(() => {
const packet = new Packet(toForward, broker)
packet.qos = 0
write(that, packet, function (err) {
that._onError(err)
cb() // don't pass the error here or it will be thrown by mqemitter
})
})
} else {
setImmediate(cb)
}
}
this.deliverQoS = function deliverQoS (_packet, cb) {
// downgrade to qos0 if requested by publish
if (_packet.qos === 0) {
that.deliver0(_packet, cb)
return
}
const toForward = getToForwardPacket(_packet)
if (toForward) {
setImmediate(() => {
const packet = new QoSPacket(toForward, that)
// Downgrading to client subscription qos if needed
const clientSub = that.subscriptions[packet.topic]
if (clientSub && (clientSub.qos || 0) < packet.qos) {
packet.qos = clientSub.qos
}
packet.writeCallback = cb
if (that.clean || packet.retain) {
writeQoS(null, that, packet)
} else {
broker.persistence.outgoingUpdate(that, packet, writeQoS)
}
})
} else if (that.clean === false) {
that.broker.persistence.outgoingClearMessageId(that, _packet, noop)
// we consider this to be an error, since the packet is undefined
// so there's nothing to send
setImmediate(cb)
} else {
setImmediate(cb)
}
}
this._keepaliveTimer = null
this._keepaliveInterval = -1
this._connectTimer = setTimeout(function () {
that.emit('error', new Error('connect did not arrive in time'))
}, broker.connectTimeout)
}
function dedupe (client, packet) {
const id = packet.brokerId
if (!id) {
return true
}
const duplicates = client.duplicates
const counter = packet.brokerCounter
const result = (duplicates[id] || 0) < counter
if (result) {
duplicates[id] = counter
}
return result
}
function writeQoS (err, client, packet) {
if (err) {
// is this right, or we should ignore thins?
client.emit('error', err)
// don't pass the error here or it will be thrown by mqemitter
packet.writeCallback()
} else {
write(client, packet, function (err) {
if (err) {
client.emit('error', err)
}
// don't pass the error here or it will be thrown by mqemitter
packet.writeCallback()
})
}
}
function drainRequest (req) {
req.callback()
}
function onError (err) {
if (!err) return
this.errored = true
this.conn.removeAllListeners('error')
this.conn.on('error', noop)
// hack to clean up the write callbacks in case of error
const state = this.conn._writableState
const list = typeof state.getBuffer === 'function' ? state.getBuffer() : state.buffer
list.forEach(drainRequest)
this.broker.emit(this.id ? 'clientError' : 'connectionError', this, err)
this.close()
}
util.inherits(Client, EventEmitter)
Client.prototype._onError = onError
Client.prototype.publish = function (message, done) {
const packet = new Packet(message, this.broker)
const that = this
if (packet.qos === 0) {
// skip offline and send it as it is
this.deliver0(packet, done)
return
}
if (!this.clean && this.id) {
this.broker.persistence.outgoingEnqueue({
clientId: this.id
}, packet, function deliver (err) {
if (err) {
return done(err)
}
that.deliverQoS(packet, done)
})
} else {
that.deliverQoS(packet, done)
}
}
Client.prototype.subscribe = function (packet, done) {
if (!packet.subscriptions) {
if (!Array.isArray(packet)) {
packet = [packet]
}
packet = {
subscriptions: packet
}
}
handleSubscribe(this, packet, false, done)
}
Client.prototype.unsubscribe = function (packet, done) {
if (!packet.unsubscriptions) {
if (!Array.isArray(packet)) {
packet = [packet]
}
packet = {
unsubscriptions: packet
}
}
handleUnsubscribe(this, packet, done)
}
Client.prototype.close = function (done) {
if (this.closed) {
if (typeof done === 'function') {
done()
}
return
}
const that = this
const conn = this.conn
this.closed = true
this._parser.removeAllListeners('packet')
conn.removeAllListeners('readable')
this._parser._queue = null
if (this._keepaliveTimer) {
this._keepaliveTimer.clear()
this._keepaliveInterval = -1
this._keepaliveTimer = null
}
if (this._connectTimer) {
clearTimeout(this._connectTimer)
this._connectTimer = null
}
this._eos()
this._eos = noop
handleUnsubscribe(
this,
{
unsubscriptions: Object.keys(this.subscriptions)
},
finish)
function finish () {
const will = that.will
// _disconnected is set only if client is disconnected with a valid disconnect packet
if (!that._disconnected && will) {
that.broker.authorizePublish(that, will, function (err) {
if (err) { return done() }
that.broker.publish(will, that, done)
function done () {
that.broker.persistence.delWill({
id: that.id,
brokerId: that.broker.id
}, noop)
}
})
} else if (will) {
// delete the persisted will even on clean disconnect https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc385349232
that.broker.persistence.delWill({
id: that.id,
brokerId: that.broker.id
}, noop)
}
that.will = null // this function might be called twice
that._will = null
that.connected = false
that.connecting = false
conn.removeAllListeners('error')
conn.on('error', noop)
if (that.broker.clients[that.id] && that._authorized) {
that.broker.unregisterClient(that)
}
// clear up the drain event listeners
that.conn.emit('drain')
that.conn.removeAllListeners('drain')
conn.destroy()
if (typeof done === 'function') {
done()
}
}
}
Client.prototype.pause = function () {
this._paused = true
}
Client.prototype.resume = function () {
this._paused = false
this._nextBatch()
}
function enqueue (packet) {
const client = this.client
client._parsingBatch++
// already connected or it's the first packet
if (client.connackSent || client._parsingBatch === 1) {
handle(client, packet, client._nextBatch)
} else {
if (this._queue.length < client.broker.queueLimit) {
this._queue.push(packet)
} else {
this.emit('error', new Error('Client queue limit reached'))
}
}
}
function dequeue () {
const q = this._parser._queue
if (q) {
for (let i = 0, len = q.length; i < len; i++) {
handle(this, q[i], this._nextBatch)
}
this._parser._queue = null
}
}
Client.prototype.emptyOutgoingQueue = function (done) {
const client = this
const persistence = client.broker.persistence
function filter (packet, enc, next) {
persistence.outgoingClearMessageId(client, packet, next)
}
pipeline(
persistence.outgoingStream(client),
through(filter),
done
)
}
function noop () {}