Code coverage report for lib/index.js

Statements: 89.73% (131 / 146)      Branches: 85.71% (60 / 70)      Functions: 92.31% (24 / 26)      Lines: 91.55% (130 / 142)      Ignored: none     

All files » lib/ » index.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 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420    1           1                                           1 16   16     16 11 9 9       16   16 14   2     16   16   16       1               1 16     16 16 16   16   16   16             16     16 16   16 16                     1 2             1 2         2 2   2               1 13   13         13   13       13 7     13 1   1   1   1 1 1 1                       13                     1 7   7   7     7 1   6                     1 6     6   3 3   2 2   1                           1 3   3     1 1       1 1     1                         1 2   2   2                       1 2         2       2 2   2 1                           1   1   1                             1 1   1     1         1 3         1 23   23 1   22     23 113     23   23         1 10       10         1 1       1         1 11   11   11 75 69 69       11         1 23   23 22 22 22     23         1 14       14         1  
'use strict'
 
var dgram = require('dgram')
  , EE = require('events').EventEmitter
  , util = require('util')
  , ip = require('ip')
  , Logger = require('./logger')
 
var httpHeader = /HTTP\/\d{1}\.\d{1} \d+ .*/
  , ssdpHeader = /^([^:]+):\s*(.*)$/
 
/**
 * 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
 *
 * @returns {SSDP}
 * @constructor
 */
function SSDP(opts, sock) {
  var self = this
 
  Iif (!(this instanceof SSDP)) return new SSDP(opts)
 
  // we didn't get options, only socket
  if (!sock) {
    if (opts && /^udp\d$/.test(opts.type) && typeof opts.addMembership == 'function') {
      sock = opts
      opts = null
    }
  }
 
  opts = opts || {}
 
  if (sock) {
    this.sock = sock
  } else {
    this.sock = this._createSocket()
  }
 
  EE.call(self)
 
  this._logger = Logger(opts)
 
  this._init(opts)
}
 
 
util.inherits(SSDP, EE)
 
 
/**
 * Initializes instance properties.
 * @param opts
 * @private
 */
SSDP.prototype._init = function (opts) {
  this._ssdpSig = opts.ssdpSig || getSsdpSignature()
 
  // User shouldn't need to set these
  this._ssdpIp = opts.ssdpIp || '239.255.255.250'
  this._ssdpPort = opts.ssdpPort || 1900
  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'
}
 
 
 
/**
 * Creates and returns UDP4 socket
 *
 * @returns {Socket}
 * @private
 */
SSDP.prototype._createSocket = function () {
  return dgram.createSocket('udp4')
}
 
 
/**
 * Advertise shutdown and close UDP socket.
 */
SSDP.prototype._stop = function () {
  Iif (!this.sock) {
    this._logger.warn('Already stopped.')
    return;
  }
 
  this.sock.close()
  this.sock = null
 
  this._socketBound = this._started = false;
}
 
 
/**
 * Configures UDP socket `socket`.
 * Binds event listeners.
 */
SSDP.prototype._start = function (port, host, cb) {
  var self = this
 
  Iif (self._started) {
    self._logger.warn('Already started.')
    return
  }
 
  self._started = true
 
  this.sock.on('error', function onSocketError(err) {
    self._logger.error(err, 'Socker error')
  })
 
  this.sock.on('message', function onSocketMessage(msg, rinfo) {
    self._parseMessage(msg, rinfo)
  })
 
  this.sock.on('listening', function onSocketListening() {
    var addr = self.sock.address()
 
    self._logger.info('SSDP listening on ' + 'http://' + addr.address + ':' + addr.port)
 
    addMembership();
 
    function addMembership() {
      try {
        self.sock.addMembership(self._ssdpIp)
        self.sock.setMulticastTTL(self._ssdpTtl)
      } catch (e) {
        if (e.code === 'ENODEV') {
          self._logger.warn({err: e}, 'No interface present to add multicast group membership. Scheduling a retry.')
          setTimeout(addMembership, 5000)
        } else {
          throw e;
        }
      }
    }
  })
 
  this.sock.bind(port, host, cb)
}
 
 
 
/**
 * Routes a network message to the appropriate handler.
 *
 * @param msg
 * @param rinfo
 */
SSDP.prototype._parseMessage = function (msg, rinfo) {
  msg = msg.toString()
 
  this._logger.trace({message: '\n' + msg}, 'Multicast message')
 
  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 'NOTIFY':
      this._notify(headers, msg, rinfo)
      break
    case 'M-SEARCH':
      this._msearch(headers, msg, rinfo)
      break
    default:
      this._logger.warn({'message': '\n' + 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) {
  Iif (!headers.NTS) this._logger.trace(headers, 'Missing NTS header')
 
  switch (headers.NTS.toLowerCase()) {
    // Device coming to life.
    case 'ssdp:alive':
      this.emit('advertise-alive', headers)
      break
 
    // Device shutting down.
    case 'ssdp:byebye':
      this.emit('advertise-bye', headers)
      break
 
    default:
      this._logger.trace({'message': '\n' + _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')
 
  Iif (!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 = rinfo.address
    , port = rinfo.port
 
  // unwrap quoted string
  Iif (serviceType[0] == '"' && serviceType[serviceType.length-1] == '"') {
    serviceType = serviceType.slice(1, -1)
  }
 
  Object.keys(self._usns).forEach(function (usn) {
    var udn = self._usns[usn]
 
    if (serviceType === 'ssdp:all' || usn === serviceType) {
      var pkt = self._getSSDPHeader(
        '200 OK',
        {
          'ST': usn,
          '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, 'port': port}, 'Sending a 200 OK for an M-SEARCH')
 
      var message = new Buffer(pkt)
 
      self._send(message, 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': '\n' + 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 = []
 
  if (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]
 
  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) {
    if (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
 
  if (typeof host === 'function') {
    cb = host
    host = this._ssdpIp
    port = this._ssdpPort
  }
 
  self.sock.send(message, 0, message.length, port, host, cb)
}
 
 
 
function getSsdpSignature() {
  var nodeVersion = process.version.substr(1)
    , moduleVersion = require('../package.json').version
    , moduleName = require('../package.json').name
 
  return 'node.js/' + nodeVersion + ' UPnP/1.1 ' + moduleName + '/' + moduleVersion
}
 
 
 
module.exports = SSDP