Code coverage report for lib/dgram.js

Statements: 80.37% (217 / 270)      Branches: 69.59% (103 / 148)      Functions: 84.38% (27 / 32)      Lines: 80.67% (217 / 269)      Ignored: none     

All files » lib/ » dgram.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 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    872 872 872 872   872 872   872 872 872     872 872   872 872   872 3329 30   3329       872 3326       872 3       872 53 48 48 48     5 5 5 5 5 5                   872   5   5   5 5 5           5       872 48   48         48 48   48 48 48 48 48     48   48 3   872 872     872 45       872 37   37 37 37 37   37     872     8 8 8 8     8 8     872 42   42   42     42   42 3   42 1 1 1     41 41   41 16 16 16   25 25       41 41           41 30   41 7 7             7       7 7       34 3   31 31     31 31 2 2 2   2     29       41         872           1     1     1       872           3366   3366 14   3366 3   3363 3363 2   3361   3       3358 3358 1   3357 4   3353 3353 3       3350 1589   3350   3350 15       3350     62 21 21   18 55 18     62 62     3288 3288     3288 3287 3287 3287 3287 3287 3287 1746 1746   3287             3287                   872 1746 1   1746 1746 1746         872 33 1 33 33 33 33 33 33   33       872 33       872 14   14 14 14       14       872               872                           872 2       2 2 1     1       872                   872                             872                             872 3439         872 33 6   27 27 27       872 3241 3241     3241 3241       872 1 1   1       872 4 4   4        
(function () { 'use strict';
 
const assert = require('assert');
const util = require('util');
const events = require('events');
const constants = require('constants');
 
const UDP = process.binding('udp_wrap').UDP;
const SendWrap = process.binding('udp_wrap').SendWrap;
 
const BIND_STATE_UNBOUND = 0;
const BIND_STATE_BINDING = 1;
const BIND_STATE_BOUND = 2;
 
// lazily loaded
var cluster = null;
var dns = null;
 
const errnoException = util._errnoException;
const exceptionWithHostPort = util._exceptionWithHostPort;
 
function lookup(address, family, callback) {
  if (!dns)
    dns = require('dns');
 
  return dns.lookup(address, family, callback);
}
 
 
function lookup4(address, callback) {
  return lookup(address || '0.0.0.0', 4, callback);
}
 
 
function lookup6(address, callback) {
  return lookup(address || '::0', 6, callback);
}
 
 
function newHandle(type) {
  if (type == 'udp4') {
    var handle = new UDP();
    handle.lookup = lookup4;
    return handle;
  }
 
  Eif (type == 'udp6') {
    var handle = new UDP();
    handle.lookup = lookup6;
    handle.bind = handle.bind6;
    handle.send = handle.send6;
    return handle;
  }
 
  if (type == 'unix_dgram')
    throw new Error('unix_dgram sockets are not supported any more.');
 
  throw new Error('Bad socket type specified. Valid types are: udp4, udp6');
}
 
 
exports._createSocketHandle = function(address, port, addressType, fd) {
  // Opening an existing fd is not supported for UDP handles.
  assert(typeof fd !== 'number' || fd < 0);
 
  var handle = newHandle(addressType);
 
  Eif (port || address) {
    var err = handle.bind(address, port || 0, 0);
    Iif (err) {
      handle.close();
      return err;
    }
  }
 
  return handle;
};
 
 
function Socket(type, listener) {
  events.EventEmitter.call(this);
 
  Iif (typeof type === 'object') {
    var options = type;
    type = options.type;
  }
 
  var handle = newHandle(type);
  handle.owner = this;
 
  this._handle = handle;
  this._receiving = false;
  this._bindState = BIND_STATE_UNBOUND;
  this.type = type;
  this.fd = null; // compatibility hack
 
  // If true - UV_UDP_REUSEADDR flag will be set
  this._reuseAddr = options && options.reuseAddr;
 
  if (typeof listener === 'function')
    this.on('message', listener);
}
util.inherits(Socket, events.EventEmitter);
exports.Socket = Socket;
 
 
exports.createSocket = function(type, listener) {
  return new Socket(type, listener);
};
 
 
function startListening(socket) {
  socket._handle.onmessage = onMessage;
  // Todo: handle errors
  socket._handle.recvStart();
  socket._receiving = true;
  socket._bindState = BIND_STATE_BOUND;
  socket.fd = -42; // compatibility hack
 
  socket.emit('listening');
}
 
function replaceHandle(self, newHandle) {
 
  // Set up the handle that we got from master.
  newHandle.lookup = self._handle.lookup;
  newHandle.bind = self._handle.bind;
  newHandle.send = self._handle.send;
  newHandle.owner = self;
 
  // Replace the existing handle by the handle we got from master.
  self._handle.close();
  self._handle = newHandle;
}
 
Socket.prototype.bind = function(port /*, address, callback*/) {
  var self = this;
 
  self._healthCheck();
 
  Iif (this._bindState != BIND_STATE_UNBOUND)
    throw new Error('Socket is already bound');
 
  this._bindState = BIND_STATE_BINDING;
 
  if (typeof arguments[arguments.length - 1] === 'function')
    self.once('listening', arguments[arguments.length - 1]);
 
  if (port instanceof UDP) {
    replaceHandle(self, port);
    startListening(self);
    return self;
  }
 
  var address;
  var exclusive;
 
  if (port !== null && typeof port === 'object') {
    address = port.address || '';
    exclusive = !!port.exclusive;
    port = port.port;
  } else {
    address = typeof arguments[1] === 'function' ? '' : arguments[1];
    exclusive = false;
  }
 
  // resolve address first
  self._handle.lookup(address, function(err, ip) {
    Iif (err) {
      self._bindState = BIND_STATE_UNBOUND;
      self.emit('error', err);
      return;
    }
 
    if (!cluster)
      cluster = require('cluster');
 
    if (cluster.isWorker && !exclusive) {
      cluster._getServer(self, ip, port, self.type, -1, function(err, handle) {
        Iif (err) {
          var ex = exceptionWithHostPort(err, 'bind', ip, port);
          self.emit('error', ex);
          self._bindState = BIND_STATE_UNBOUND;
          return;
        }
 
        Iif (!self._handle)
          // handle has been closed in the mean time.
          return handle.close();
 
        replaceHandle(self, handle);
        startListening(self);
      });
 
    } else {
      if (!self._handle)
        return; // handle has been closed in the mean time
 
      var flags = 0;
      Iif (self._reuseAddr)
        flags |= constants.UV_UDP_REUSEADDR;
 
      var err = self._handle.bind(ip, port || 0, flags);
      if (err) {
        var ex = exceptionWithHostPort(err, 'bind', ip, port);
        self.emit('error', ex);
        self._bindState = BIND_STATE_UNBOUND;
        // Todo: close?
        return;
      }
 
      startListening(self);
    }
  });
 
  return self;
};
 
 
// thin wrapper around `send`, here for compatibility with dgram_legacy.js
Socket.prototype.sendto = function(buffer,
                                   offset,
                                   length,
                                   port,
                                   address,
                                   callback) {
  Iif (typeof offset !== 'number' || typeof length !== 'number')
    throw new Error('send takes offset and length as args 2 and 3');
 
  Iif (typeof address !== 'string')
    throw new Error(this.type + ' sockets must send to port, address');
 
  this.send(buffer, offset, length, port, address, callback);
};
 
 
Socket.prototype.send = function(buffer,
                                 offset,
                                 length,
                                 port,
                                 address,
                                 callback) {
  var self = this;
 
  if (typeof buffer === 'string')
    buffer = new Buffer(buffer);
 
  if (!(buffer instanceof Buffer))
    throw new TypeError('First argument must be a buffer or string.');
 
  offset = offset | 0;
  if (offset < 0)
    throw new RangeError('Offset should be >= 0');
 
  if ((length == 0 && offset > buffer.length) ||
      (length > 0 && offset >= buffer.length))
    throw new RangeError('Offset into buffer too large');
 
  // Sending a zero-length datagram is kind of pointless but it _is_
  // allowed, hence check that length >= 0 rather than > 0.
  length = length | 0;
  if (length < 0)
    throw new RangeError('Length should be >= 0');
 
  if (offset + length > buffer.length)
    throw new RangeError('Offset + length beyond buffer length');
 
  port = port | 0;
  if (port <= 0 || port > 65535)
    throw new RangeError('Port should be > 0 and < 65536');
 
  // Normalize callback so it's either a function or undefined but not anything
  // else.
  if (typeof callback !== 'function')
    callback = undefined;
 
  self._healthCheck();
 
  if (self._bindState == BIND_STATE_UNBOUND)
    self.bind({port: 0, exclusive: true}, null);
 
  // If the socket hasn't been bound yet, push the outbound packet onto the
  // send queue and send after binding is complete.
  if (self._bindState != BIND_STATE_BOUND) {
    // If the send queue hasn't been initialized yet, do it, and install an
    // event handler that flushes the send queue after binding is done.
    if (!self._sendQueue) {
      self._sendQueue = [];
      self.once('listening', function() {
        // Flush the send queue.
        for (var i = 0; i < self._sendQueue.length; i++)
          self.send.apply(self, self._sendQueue[i]);
        self._sendQueue = undefined;
      });
    }
    self._sendQueue.push([buffer, offset, length, port, address, callback]);
    return;
  }
 
  self._handle.lookup(address, function(ex, ip) {
    Iif (ex) {
      if (callback) callback(ex);
      self.emit('error', ex);
    } else if (self._handle) {
      var req = new SendWrap();
      req.buffer = buffer;  // Keep reference alive.
      req.length = length;
      req.address = address;
      req.port = port;
      if (callback) {
        req.callback = callback;
        req.oncomplete = afterSend;
      }
      var err = self._handle.send(req,
                                  buffer,
                                  offset,
                                  length,
                                  port,
                                  ip,
                                  !!callback);
      Iif (err && callback) {
        // don't emit as error, dgram_legacy.js compatibility
        var ex = exceptionWithHostPort(err, 'send', address, port);
        process.nextTick(callback, ex);
      }
    }
  });
};
 
 
function afterSend(err) {
  if (err) {
    err = exceptionWithHostPort(err, 'send', this.address, this.port);
  }
  var self = this;
  setImmediate(function() {
    self.callback(err, self.length);
  });
}
 
 
Socket.prototype.close = function(callback) {
  if (typeof callback === 'function')
    this.on('close', callback);
  this._healthCheck();
  this._stopReceiving();
  this._handle.close();
  this._handle = null;
  var self = this;
  process.nextTick(socketCloseNT, self);
 
  return this;
};
 
 
function socketCloseNT(self) {
  self.emit('close');
}
 
 
Socket.prototype.address = function() {
  this._healthCheck();
 
  var out = {};
  var err = this._handle.getsockname(out);
  Iif (err) {
    throw errnoException(err, 'getsockname');
  }
 
  return out;
};
 
 
Socket.prototype.setBroadcast = function(arg) {
  var err = this._handle.setBroadcast(arg ? 1 : 0);
  if (err) {
    throw errnoException(err, 'setBroadcast');
  }
};
 
 
Socket.prototype.setTTL = function(arg) {
  if (typeof arg !== 'number') {
    throw new TypeError('Argument must be a number');
  }
 
  var err = this._handle.setTTL(arg);
  if (err) {
    throw errnoException(err, 'setTTL');
  }
 
  return arg;
};
 
 
Socket.prototype.setMulticastTTL = function(arg) {
  Iif (typeof arg !== 'number') {
    throw new TypeError('Argument must be a number');
  }
 
  var err = this._handle.setMulticastTTL(arg);
  if (err) {
    throw errnoException(err, 'setMulticastTTL');
  }
 
  return arg;
};
 
 
Socket.prototype.setMulticastLoopback = function(arg) {
  var err = this._handle.setMulticastLoopback(arg ? 1 : 0);
  if (err) {
    throw errnoException(err, 'setMulticastLoopback');
  }
 
  return arg; // 0.4 compatibility
};
 
 
Socket.prototype.addMembership = function(multicastAddress,
                                          interfaceAddress) {
  this._healthCheck();
 
  if (!multicastAddress) {
    throw new Error('multicast address must be specified');
  }
 
  var err = this._handle.addMembership(multicastAddress, interfaceAddress);
  if (err) {
    throw errnoException(err, 'addMembership');
  }
};
 
 
Socket.prototype.dropMembership = function(multicastAddress,
                                           interfaceAddress) {
  this._healthCheck();
 
  if (!multicastAddress) {
    throw new Error('multicast address must be specified');
  }
 
  var err = this._handle.dropMembership(multicastAddress, interfaceAddress);
  if (err) {
    throw errnoException(err, 'dropMembership');
  }
};
 
 
Socket.prototype._healthCheck = function() {
  Iif (!this._handle)
    throw new Error('Not running'); // error message from dgram_legacy.js
};
 
 
Socket.prototype._stopReceiving = function() {
  if (!this._receiving)
    return;
 
  this._handle.recvStop();
  this._receiving = false;
  this.fd = null; // compatibility hack
};
 
 
function onMessage(nread, handle, buf, rinfo) {
  var self = handle.owner;
  Iif (nread < 0) {
    return self.emit('error', errnoException(nread, 'recvmsg'));
  }
  rinfo.size = buf.length; // compatibility
  self.emit('message', buf, rinfo);
}
 
 
Socket.prototype.ref = function() {
  Eif (this._handle)
    this._handle.ref();
 
  return this;
};
 
 
Socket.prototype.unref = function() {
  Eif (this._handle)
    this._handle.unref();
 
  return this;
};
 
}());