| 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496 |
1
1
1
1
1
17
17
17
17
17
17
17
1
1
17
17
17
17
17
17
17
17
17
17
17
17
17
17
17
17
17
1
17
17
17
102
102
153
51
51
51
51
51
1
1
1
1
3
3
1
1
1
14
14
14
14
14
42
42
42
42
42
42
42
42
33
9
9
42
1
1
1
1
1
1
1
4
1
2
2
2
2
2
8
2
2
1
1
1
1
1
1
1
1
4
4
4
1
1
2
2
2
2
2
2
2
6
6
1
15
1
| 'use strict'
var dgram = require('dgram')
, EE = require('events').EventEmitter
, util = require('util')
, ip = require('ip')
, Logger = require('./logger')
, os = require('os')
, async = require('async')
var httpHeader = /HTTP\/\d{1}\.\d{1} \d+ .*/
, ssdpHeader = /^([^:]+):\s*(.*)$/
/* consts */
var c = require('./const')
var nodeVersion = process.version.substr(1)
, moduleVersion = require('../package.json').version
, moduleName = require('../package.json').name
/**
* Options:
*
* @param {Object} opts
* @param {String} opts.ssdpSig SSDP signature
* @param {String} opts.ssdpIp SSDP multicast group
* @param {String} opts.ssdpPort SSDP port
* @param {Number} opts.ssdpTtl Multicast TTL
* @param {Number} opts.adInterval Interval at which to send out advertisement (ms)
* @param {String} opts.description Path to SSDP description file
* @param {String} opts.udn SSDP Unique Device Name
*
* @param {Number} opts.ttl Packet TTL
* @param {Boolean} opts.log Disable/enable logging
* @param {String} opts.logLevel Log level
* @param {Boolean} opts.allowWildcards Allow wildcards in M-SEARCH packets (non-standard)
*
* @returns {SSDP}
* @constructor
*/
function SSDP(opts) {
var self = this
Iif (!(this instanceof SSDP)) return new SSDP(opts)
this._subclass = this._subclass || 'ssdp-base'
opts = opts || {}
EE.call(self)
this._init(opts)
this._createSockets()
}
util.inherits(SSDP, EE)
/**
* Initializes instance properties.
* @param opts
* @private
*/
SSDP.prototype._init = function (opts) {
opts.logger_name = this._subclass
Eif (opts.logJSON === undefined) {
opts.logJSON = true
}
this._logger = Logger(opts)
this._ssdpSig = opts.ssdpSig || getSsdpSignature()
// User shouldn't need to set these
this._ssdpIp = opts.ssdpIp || c.SSDP_DEFAULT_IP
this._ssdpPort = opts.ssdpPort || c.SSDP_DEFAULT_PORT
this._ssdpTtl = opts.ssdpTtl || 1
this._adInterval = opts.adInterval || 10000
this._ttl = opts.ttl || 1800
Iif (typeof opts.location === 'function') {
Object.defineProperty(this, '_location', {
enumerable: true,
get: opts.location
})
} else {
// Probably should specify these
this._location = opts.location || 'http://' + ip.address() + ':' + 10293 + '/upnp/desc.html'
}
this._unicastHost = opts.unicastHost || '0.0.0.0'
this._ssdpServerHost = this._ssdpIp + ':' + this._ssdpPort
this._usns = {}
this._udn = opts.udn || 'uuid:f40c2981-7329-40b7-8b04-27f187aecfb5'
this._allowWildcards = opts.allowWildcards
}
/**
* Creates and returns UDP4 socket.
* Prior to node v0.12.x `dgram.createSocket` did not accept
* an object and socket reuse was not available; this method
* contains a crappy workaround to make version of node before 0.12
* to work correctly. See https://github.com/diversario/node-ssdp/pull/38
*
* @returns {Socket}
* @private
*/
SSDP.prototype._createSockets = function () {
var interfaces = os.networkInterfaces()
, self = this
this.sockets = {}
Object.keys(interfaces).forEach(function (iName) {
self._logger.info('Discovering all IPs from interface %s', iName)
interfaces[iName].forEach(function (ipInfo) {
if (ipInfo.internal == false && ipInfo.family == "IPv4") {
self._logger.info('Will use interface %s', iName)
var socket
Eif (parseFloat(nodeVersion.replace(/\w/, '')) >= 0.12) {
socket = dgram.createSocket({type: 'udp4', reuseAddr: true})
} else {
socket = dgram.createSocket('udp4')
}
self.sockets[ipInfo.address] = socket
}
})
})
}
/**
* Advertise shutdown and close UDP socket.
*/
SSDP.prototype._stop = function () {
var self = this
Iif (!this.sockets) {
this._logger.warn('Already stopped.')
return
}
Object.keys(this.sockets).forEach(function (ipAddress) {
var socket = self.sockets[ipAddress]
socket && socket.close()
})
this.sockets = null
this._socketBound = this._started = false
}
/**
* Configures UDP socket `socket`.
* Binds event listeners.
*/
SSDP.prototype._start = function (cb) {
var self = this
Iif (self._started) {
self._logger.warn('Already started.')
return
}
self._started = true
var interfaces = Object.keys(this.sockets)
async.each(interfaces, function (iface, next) {
var socket = self.sockets[iface]
socket.on('error', function onSocketError(err) {
self._logger.error(err, 'Socker error')
})
socket.on('message', function onSocketMessage(msg, rinfo) {
self._parseMessage(msg, rinfo)
})
socket.on('listening', function onSocketListening() {
var addr = socket.address()
self._logger.info({
address: 'http://' + addr.address + ':' + addr.port,
'interface': iface
}, 'SSDP listening')
try {
socket.addMembership(self._ssdpIp, iface) // TODO: specifying the interface in there might make a difference
socket.setMulticastTTL(self._ssdpTtl)
} catch (e) {
Iif (e.code === 'ENODEV') {
self._logger.warn(e, 'Interface %s is not present to add multicast group membership. Scheduling a retry.', addr)
setTimeout(addMembership, 5000)
} else {
throw e
}
}
})
socket.bind(self._ssdpPort, next) // socket binds on 0.0.0.0
}, cb)
}
/**
* Routes a network message to the appropriate handler.
*
* @param msg
* @param rinfo
*/
SSDP.prototype._parseMessage = function (msg, rinfo) {
msg = msg.toString()
var type = msg.split('\r\n').shift()
// HTTP/#.# ### Response to M-SEARCH
if (httpHeader.test(type)) {
this._parseResponse(msg, rinfo)
} else {
this._parseCommand(msg, rinfo)
}
}
/**
* Parses SSDP command.
*
* @param msg
* @param rinfo
*/
SSDP.prototype._parseCommand = function parseCommand(msg, rinfo) {
var method = this._getMethod(msg)
, headers = this._getHeaders(msg)
switch (method) {
case c.NOTIFY:
this._notify(headers, msg, rinfo)
break
case c.M_SEARCH:
this._msearch(headers, msg, rinfo)
break
default:
this._logger.warn({'message': msg, 'rinfo': rinfo}, 'Unhandled command')
}
}
/**
* Handles NOTIFY command
* Emits `advertise-alive`, `advertise-bye` events.
*
* @param headers
* @param _msg
* @param _rinfo
*/
SSDP.prototype._notify = function (headers, _msg, _rinfo) {
if (!headers.NTS) {
this._logger.trace(headers, 'Missing NTS header')
return
}
switch (headers.NTS.toLowerCase()) {
// Device coming to life.
case c.SSDP_ALIVE:
this.emit(c.ADVERTISE_ALIVE, headers)
break
// Device shutting down.
case c.SSDP_BYE:
this.emit(c.ADVERTISE_BYE, headers)
break
default:
this._logger.trace({'message': _msg, 'rinfo': _rinfo}, 'Unhandled NOTIFY event')
}
}
/**
* Handles M-SEARCH command.
*
* @param headers
* @param msg
* @param rinfo
*/
SSDP.prototype._msearch = function (headers, msg, rinfo) {
this._logger.trace({
'ST': headers.ST,
'address': rinfo.address,
'port': rinfo.port
}, 'SSDP M-SEARCH event')
if (!headers.MAN || !headers.MX || !headers.ST) return
this._respondToSearch(headers.ST, rinfo)
}
/**
* Sends out a response to M-SEARCH commands.
*
* @param {String} serviceType Service type requested by a client
* @param {Object} rinfo Remote client's address
* @private
*/
SSDP.prototype._respondToSearch = function (serviceType, rinfo) {
var self = this
, peer_addr = rinfo.address
, peer_port = rinfo.port
, stRegex
, acceptor
// unwrap quoted string
if (serviceType[0] == '"' && serviceType[serviceType.length - 1] == '"') {
serviceType = serviceType.slice(1, -1)
}
if (self._allowWildcards) {
stRegex = new RegExp(serviceType.replace(/\*/g, '.*') + '$')
acceptor = function (usn, serviceType) {
return serviceType === c.SSDP_ALL || stRegex.test(usn)
}
} else {
acceptor = function (usn, serviceType) {
return serviceType === c.SSDP_ALL || usn === serviceType
}
}
Object.keys(self._usns).forEach(function (usn) {
var udn = self._usns[usn]
if (self._allowWildcards) {
udn = udn.replace(stRegex, serviceType)
}
if (acceptor(usn, serviceType)) {
var pkt = self._getSSDPHeader(
'200 OK', {
'ST': serviceType === c.SSDP_ALL ? usn : serviceType,
'USN': udn,
'LOCATION': self._location,
'CACHE-CONTROL': 'max-age=' + self._ttl,
'DATE': new Date().toUTCString(),
'SERVER': self._ssdpSig,
'EXT': ''
},
true
)
self._logger.trace({
'peer': peer_addr,
'port': peer_port
}, 'Sending a 200 OK for an M-SEARCH')
var message = new Buffer(pkt)
self._send(message, peer_addr, peer_port, function (err, bytes) {
self._logger.trace({'message': pkt}, 'Sent M-SEARCH response')
})
}
})
}
/**
* Parses SSDP response message.
*
* @param msg
* @param rinfo
*/
SSDP.prototype._parseResponse = function parseResponse(msg, rinfo) {
this._logger.info({'message': msg}, 'SSDP response')
var headers = this._getHeaders(msg)
, statusCode = this._getStatusCode(msg)
this.emit('response', headers, statusCode, rinfo)
}
SSDP.prototype.addUSN = function (device) {
this._usns[device] = this._udn + '::' + device
}
SSDP.prototype._getSSDPHeader = function (method, headers, isResponse) {
var message = []
method = method.toUpperCase()
Iif (isResponse) {
message.push('HTTP/1.1 ' + method)
} else {
message.push(method + ' * HTTP/1.1')
}
Object.keys(headers).forEach(function (header) {
message.push(header + ': ' + headers[header])
})
message.push('\r\n')
return message.join('\r\n')
}
SSDP.prototype._getMethod = function _getMethod(msg) {
var lines = msg.split("\r\n")
, type = lines.shift().split(' ')// command, such as "NOTIFY * HTTP/1.1"
, method = (type[0] || '').toLowerCase()
return method
}
SSDP.prototype._getStatusCode = function _getStatusCode(msg) {
var lines = msg.split("\r\n")
, type = lines.shift().split(' ')// command, such as "NOTIFY * HTTP/1.1"
, code = parseInt(type[1], 10)
return code
}
SSDP.prototype._getHeaders = function _getHeaders(msg) {
var lines = msg.split("\r\n")
var headers = {}
lines.forEach(function (line) {
Eif (line.length) {
var pairs = line.match(ssdpHeader)
if (pairs) headers[pairs[1].toUpperCase()] = pairs[2] // e.g. {'HOST': 239.255.255.250:1900}
}
})
return headers
}
SSDP.prototype._send = function (message, host, port, cb) {
var self = this
Eif (typeof host === 'function') {
cb = host
host = this._ssdpIp
port = this._ssdpPort
}
var ipAddresses = Object.keys(this.sockets)
async.each(ipAddresses, function (ipAddress, next) {
var socket = self.sockets[ipAddress]
socket.send(message, 0, message.length, port, host, next)
}, cb)
}
function getSsdpSignature() {
return 'node.js/' + nodeVersion + ' UPnP/1.1 ' + moduleName + '/' + moduleVersion
}
module.exports = SSDP
|