3 const assert = require('assert');
4 const Buffer = require('buffer').Buffer;
5 const util = require('util');
6 const EventEmitter = require('events');
7 const constants = require('constants');
9 const UDP = process.binding('udp_wrap').UDP;
10 const SendWrap = process.binding('udp_wrap').SendWrap;
12 const BIND_STATE_UNBOUND = 0;
13 const BIND_STATE_BINDING = 1;
14 const BIND_STATE_BOUND = 2;
20 const errnoException = util._errnoException;
21 const exceptionWithHostPort = util._exceptionWithHostPort;
23 function lookup(address, family, callback) {
27 return dns.lookup(address, family, callback);
31 function lookup4(address, callback) {
32 return lookup(address || '0.0.0.0', 4, callback);
36 function lookup6(address, callback) {
37 return lookup(address || '::0', 6, callback);
41 function newHandle(type) {
43 var handle = new UDP();
44 handle.lookup = lookup4;
49 var handle = new UDP();
50 handle.lookup = lookup6;
51 handle.bind = handle.bind6;
52 handle.send = handle.send6;
56 if (type == 'unix_dgram')
57 throw new Error('unix_dgram sockets are not supported any more.');
59 throw new Error('Bad socket type specified. Valid types are: udp4, udp6');
63 exports._createSocketHandle = function(address, port, addressType, fd, flags) {
64 // Opening an existing fd is not supported for UDP handles.
65 assert(typeof fd !== 'number' || fd < 0);
67 var handle = newHandle(addressType);
69 if (port || address) {
70 var err = handle.bind(address, port || 0, flags);
81 function Socket(type, listener) {
82 EventEmitter.call(this);
84 if (typeof type === 'object') {
89 var handle = newHandle(type);
92 this._handle = handle;
93 this._receiving = false;
94 this._bindState = BIND_STATE_UNBOUND;
96 this.fd = null; // compatibility hack
98 // If true - UV_UDP_REUSEADDR flag will be set
99 this._reuseAddr = options && options.reuseAddr;
101 if (typeof listener === 'function')
102 this.on('message', listener);
104 util.inherits(Socket, EventEmitter);
105 exports.Socket = Socket;
108 exports.createSocket = function(type, listener) {
109 return new Socket(type, listener);
113 function startListening(socket) {
114 socket._handle.onmessage = onMessage;
115 // Todo: handle errors
116 socket._handle.recvStart();
117 socket._receiving = true;
118 socket._bindState = BIND_STATE_BOUND;
119 socket.fd = -42; // compatibility hack
121 socket.emit('listening');
124 function replaceHandle(self, newHandle) {
126 // Set up the handle that we got from master.
127 newHandle.lookup = self._handle.lookup;
128 newHandle.bind = self._handle.bind;
129 newHandle.send = self._handle.send;
130 newHandle.owner = self;
132 // Replace the existing handle by the handle we got from master.
133 self._handle.close();
134 self._handle = newHandle;
137 Socket.prototype.bind = function(port /*, address, callback*/) {
142 if (this._bindState != BIND_STATE_UNBOUND)
143 throw new Error('Socket is already bound');
145 this._bindState = BIND_STATE_BINDING;
147 if (typeof arguments[arguments.length - 1] === 'function')
148 self.once('listening', arguments[arguments.length - 1]);
150 if (port instanceof UDP) {
151 replaceHandle(self, port);
152 startListening(self);
159 if (port !== null && typeof port === 'object') {
160 address = port.address || '';
161 exclusive = !!port.exclusive;
164 address = typeof arguments[1] === 'function' ? '' : arguments[1];
168 // resolve address first
169 self._handle.lookup(address, function(err, ip) {
171 self._bindState = BIND_STATE_UNBOUND;
172 self.emit('error', err);
177 cluster = require('cluster');
181 flags |= constants.UV_UDP_REUSEADDR;
183 if (cluster.isWorker && !exclusive) {
184 function onHandle(err, handle) {
186 var ex = exceptionWithHostPort(err, 'bind', ip, port);
187 self.emit('error', ex);
188 self._bindState = BIND_STATE_UNBOUND;
193 // handle has been closed in the mean time.
194 return handle.close();
196 replaceHandle(self, handle);
197 startListening(self);
199 cluster._getServer(self, {
202 addressType: self.type,
209 return; // handle has been closed in the mean time
211 var err = self._handle.bind(ip, port || 0, flags);
213 var ex = exceptionWithHostPort(err, 'bind', ip, port);
214 self.emit('error', ex);
215 self._bindState = BIND_STATE_UNBOUND;
220 startListening(self);
228 // thin wrapper around `send`, here for compatibility with dgram_legacy.js
229 Socket.prototype.sendto = function(buffer,
235 if (typeof offset !== 'number' || typeof length !== 'number')
236 throw new Error('send takes offset and length as args 2 and 3');
238 if (typeof address !== 'string')
239 throw new Error(this.type + ' sockets must send to port, address');
241 this.send(buffer, offset, length, port, address, callback);
245 Socket.prototype.send = function(buffer,
253 if (typeof buffer === 'string')
254 buffer = new Buffer(buffer);
255 else if (!(buffer instanceof Buffer))
256 throw new TypeError('First argument must be a buffer or string.');
260 throw new RangeError('Offset should be >= 0');
262 if ((length == 0 && offset > buffer.length) ||
263 (length > 0 && offset >= buffer.length))
264 throw new RangeError('Offset into buffer too large');
266 // Sending a zero-length datagram is kind of pointless but it _is_
267 // allowed, hence check that length >= 0 rather than > 0.
270 throw new RangeError('Length should be >= 0');
272 if (offset + length > buffer.length)
273 throw new RangeError('Offset + length beyond buffer length');
276 if (port <= 0 || port > 65535)
277 throw new RangeError('Port should be > 0 and < 65536');
279 // Normalize callback so it's either a function or undefined but not anything
281 if (typeof callback !== 'function')
282 callback = undefined;
286 if (self._bindState == BIND_STATE_UNBOUND)
287 self.bind({port: 0, exclusive: true}, null);
289 // If the socket hasn't been bound yet, push the outbound packet onto the
290 // send queue and send after binding is complete.
291 if (self._bindState != BIND_STATE_BOUND) {
292 // If the send queue hasn't been initialized yet, do it, and install an
293 // event handler that flushes the send queue after binding is done.
294 if (!self._sendQueue) {
295 self._sendQueue = [];
296 self.once('listening', function() {
297 // Flush the send queue.
298 for (var i = 0; i < self._sendQueue.length; i++)
299 self.send.apply(self, self._sendQueue[i]);
300 self._sendQueue = undefined;
303 self._sendQueue.push([buffer, offset, length, port, address, callback]);
307 self._handle.lookup(address, function(ex, ip) {
309 if (typeof callback === 'function') {
314 self.emit('error', ex);
315 } else if (self._handle) {
316 var req = new SendWrap();
317 req.buffer = buffer; // Keep reference alive.
319 req.address = address;
322 req.callback = callback;
323 req.oncomplete = afterSend;
325 var err = self._handle.send(req,
332 if (err && callback) {
333 // don't emit as error, dgram_legacy.js compatibility
334 var ex = exceptionWithHostPort(err, 'send', address, port);
335 process.nextTick(callback, ex);
342 function afterSend(err) {
344 err = exceptionWithHostPort(err, 'send', this.address, this.port);
346 this.callback(err, this.length);
350 Socket.prototype.close = function(callback) {
351 if (typeof callback === 'function')
352 this.on('close', callback);
354 this._stopReceiving();
355 this._handle.close();
358 process.nextTick(socketCloseNT, self);
364 function socketCloseNT(self) {
369 Socket.prototype.address = function() {
373 var err = this._handle.getsockname(out);
375 throw errnoException(err, 'getsockname');
382 Socket.prototype.setBroadcast = function(arg) {
383 var err = this._handle.setBroadcast(arg ? 1 : 0);
385 throw errnoException(err, 'setBroadcast');
390 Socket.prototype.setTTL = function(arg) {
391 if (typeof arg !== 'number') {
392 throw new TypeError('Argument must be a number');
395 var err = this._handle.setTTL(arg);
397 throw errnoException(err, 'setTTL');
404 Socket.prototype.setMulticastTTL = function(arg) {
405 if (typeof arg !== 'number') {
406 throw new TypeError('Argument must be a number');
409 var err = this._handle.setMulticastTTL(arg);
411 throw errnoException(err, 'setMulticastTTL');
418 Socket.prototype.setMulticastLoopback = function(arg) {
419 var err = this._handle.setMulticastLoopback(arg ? 1 : 0);
421 throw errnoException(err, 'setMulticastLoopback');
424 return arg; // 0.4 compatibility
428 Socket.prototype.addMembership = function(multicastAddress,
432 if (!multicastAddress) {
433 throw new Error('multicast address must be specified');
436 var err = this._handle.addMembership(multicastAddress, interfaceAddress);
438 throw errnoException(err, 'addMembership');
443 Socket.prototype.dropMembership = function(multicastAddress,
447 if (!multicastAddress) {
448 throw new Error('multicast address must be specified');
451 var err = this._handle.dropMembership(multicastAddress, interfaceAddress);
453 throw errnoException(err, 'dropMembership');
458 Socket.prototype._healthCheck = function() {
460 throw new Error('Not running'); // error message from dgram_legacy.js
464 Socket.prototype._stopReceiving = function() {
465 if (!this._receiving)
468 this._handle.recvStop();
469 this._receiving = false;
470 this.fd = null; // compatibility hack
474 function onMessage(nread, handle, buf, rinfo) {
475 var self = handle.owner;
477 return self.emit('error', errnoException(nread, 'recvmsg'));
479 rinfo.size = buf.length; // compatibility
480 self.emit('message', buf, rinfo);
484 Socket.prototype.ref = function() {
492 Socket.prototype.unref = function() {
494 this._handle.unref();