1 // Copyright Joyent, Inc. and other Node contributors.
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
22 var events = require('events');
23 var stream = require('stream');
24 var timers = require('timers');
25 var util = require('util');
26 var assert = require('assert');
27 var cares = process.binding('cares_wrap');
28 var uv = process.binding('uv');
31 var errnoException = util._errnoException;
35 // constructor for lazy loading
36 function createPipe() {
37 var Pipe = process.binding('pipe_wrap').Pipe;
41 // constructor for lazy loading
42 function createTCP() {
43 var TCP = process.binding('tcp_wrap').TCP;
48 function createHandle(fd) {
49 var tty = process.binding('tty_wrap');
50 var type = tty.guessHandleType(fd);
51 if (type === 'PIPE') return createPipe();
52 if (type === 'TCP') return createTCP();
53 throw new TypeError('Unsupported fd type: ' + type);
57 var debug = util.debuglog('net');
59 function isPipeName(s) {
60 return util.isString(s) && toNumber(s) === false;
64 exports.createServer = function() {
65 return new Server(arguments[0], arguments[1]);
71 // var s = net.connect({port: 80, host: 'google.com'}, function() {
75 // There are various forms:
77 // connect(options, [cb])
78 // connect(port, [host], [cb])
79 // connect(path, [cb]);
81 exports.connect = exports.createConnection = function() {
82 var args = normalizeConnectArgs(arguments);
83 debug('createConnection', args);
84 var s = new Socket(args[0]);
85 return Socket.prototype.connect.apply(s, args);
88 // Returns an array [options] or [options, cb]
89 // It is the same as the argument of Socket.prototype.connect().
90 function normalizeConnectArgs(args) {
93 if (util.isObject(args[0])) {
94 // connect(options, [cb])
96 } else if (isPipeName(args[0])) {
97 // connect(path, [cb]);
98 options.path = args[0];
100 // connect(port, [host], [cb])
101 options.port = args[0];
102 if (util.isString(args[1])) {
103 options.host = args[1];
107 var cb = args[args.length - 1];
108 return util.isFunction(cb) ? [options, cb] : [options];
110 exports._normalizeConnectArgs = normalizeConnectArgs;
113 // called when creating new Socket, or when re-using a closed Socket
114 function initSocketHandle(self) {
115 self.destroyed = false;
116 self.errorEmitted = false;
118 self._bytesDispatched = 0;
120 // Handle creation may be deferred to bind() or connect() time.
122 self._handle.owner = self;
123 self._handle.onread = onread;
125 // If handle doesn't support writev - neither do we
126 if (!self._handle.writev)
131 function Socket(options) {
132 if (!(this instanceof Socket)) return new Socket(options);
134 this._connecting = false;
135 this._hadError = false;
138 if (util.isNumber(options))
139 options = { fd: options }; // Legacy interface.
140 else if (util.isUndefined(options))
143 stream.Duplex.call(this, options);
145 if (options.handle) {
146 this._handle = options.handle; // private
147 } else if (!util.isUndefined(options.fd)) {
148 this._handle = createHandle(options.fd);
149 this._handle.open(options.fd);
150 this.readable = options.readable !== false;
151 this.writable = options.writable !== false;
153 // these will be set once there is a connection
154 this.readable = this.writable = false;
157 // shut down the socket when we're finished with it.
158 this.on('finish', onSocketFinish);
159 this.on('_socketEnd', onSocketEnd);
161 initSocketHandle(this);
163 this._pendingData = null;
164 this._pendingEncoding = '';
166 // handle strings directly
167 this._writableState.decodeStrings = false;
169 // default to *not* allowing half open sockets
170 this.allowHalfOpen = options && options.allowHalfOpen || false;
172 // if we have a handle, then start the flow of data into the
173 // buffer. if not, then this will happen when we connect
174 if (this._handle && options.readable !== false)
177 util.inherits(Socket, stream.Duplex);
179 // the user has called .end(), and all the bytes have been
180 // sent out to the other side.
181 // If allowHalfOpen is false, or if the readable side has
182 // ended already, then destroy.
183 // If allowHalfOpen is true, then we need to do a shutdown,
184 // so that only the writable side will be cleaned up.
185 function onSocketFinish() {
186 // If still connecting - defer handling 'finish' until 'connect' will happen
187 if (this._connecting) {
188 debug('osF: not yet connected');
189 return this.once('connect', onSocketFinish);
192 debug('onSocketFinish');
193 if (!this.readable || this._readableState.ended) {
194 debug('oSF: ended, destroy', this._readableState);
195 return this.destroy();
198 debug('oSF: not ended, call shutdown()');
200 // otherwise, just shutdown, or destroy() if not possible
201 if (!this._handle || !this._handle.shutdown)
202 return this.destroy();
204 var req = { oncomplete: afterShutdown };
205 var err = this._handle.shutdown(req);
208 return this._destroy(errnoException(err, 'shutdown'));
212 function afterShutdown(status, handle, req) {
213 var self = handle.owner;
215 debug('afterShutdown destroyed=%j', self.destroyed,
216 self._readableState);
218 // callback may come after call to destroy.
222 if (self._readableState.ended) {
223 debug('readableState ended, destroying');
226 self.once('_socketEnd', self.destroy);
230 // the EOF has been received, and no more bytes are coming.
231 // if the writable side has ended already, then clean everything
233 function onSocketEnd() {
234 // XXX Should not have to do as much crap in this function.
235 // ended should already be true, since this is called *after*
236 // the EOF errno and onread has eof'ed
237 debug('onSocketEnd', this._readableState);
238 this._readableState.ended = true;
239 if (this._readableState.endEmitted) {
240 this.readable = false;
243 this.once('end', function() {
244 this.readable = false;
250 if (!this.allowHalfOpen) {
251 this.write = writeAfterFIN;
256 // Provide a better error message when we call end() as a result
257 // of the other side sending a FIN. The standard 'write after end'
258 // is overly vague, and makes it seem like the user's code is to blame.
259 function writeAfterFIN(chunk, encoding, cb) {
260 if (util.isFunction(encoding)) {
265 var er = new Error('This socket has been ended by the other party');
268 // TODO: defer error events consistently everywhere, not just the cb
269 self.emit('error', er);
270 if (util.isFunction(cb)) {
271 process.nextTick(function() {
277 exports.Socket = Socket;
278 exports.Stream = Socket; // Legacy naming.
280 Socket.prototype.read = function(n) {
282 return stream.Readable.prototype.read.call(this, n);
284 this.read = stream.Readable.prototype.read;
285 this._consuming = true;
290 Socket.prototype.listen = function() {
291 debug('socket.listen');
293 self.on('connection', arguments[0]);
294 listen(self, null, null, null);
298 Socket.prototype.setTimeout = function(msecs, callback) {
299 if (msecs > 0 && !isNaN(msecs) && isFinite(msecs)) {
300 timers.enroll(this, msecs);
301 timers._unrefActive(this);
303 this.once('timeout', callback);
305 } else if (msecs === 0) {
306 timers.unenroll(this);
308 this.removeListener('timeout', callback);
314 Socket.prototype._onTimeout = function() {
316 this.emit('timeout');
320 Socket.prototype.setNoDelay = function(enable) {
321 // backwards compatibility: assume true when `enable` is omitted
322 if (this._handle && this._handle.setNoDelay)
323 this._handle.setNoDelay(util.isUndefined(enable) ? true : !!enable);
327 Socket.prototype.setKeepAlive = function(setting, msecs) {
328 if (this._handle && this._handle.setKeepAlive)
329 this._handle.setKeepAlive(setting, ~~(msecs / 1000));
333 Socket.prototype.address = function() {
334 if (this._handle && this._handle.getsockname) {
336 var err = this._handle.getsockname(out);
337 // TODO(bnoordhuis) Check err and throw?
344 Object.defineProperty(Socket.prototype, 'readyState', {
346 if (this._connecting) {
348 } else if (this.readable && this.writable) {
350 } else if (this.readable && !this.writable) {
352 } else if (!this.readable && this.writable) {
361 Object.defineProperty(Socket.prototype, 'bufferSize', {
364 return this._handle.writeQueueSize + this._writableState.length;
370 // Just call handle.readStart until we have enough in the buffer
371 Socket.prototype._read = function(n) {
374 if (this._connecting || !this._handle) {
375 debug('_read wait for connection');
376 this.once('connect', this._read.bind(this, n));
377 } else if (!this._handle.reading) {
378 // not already reading, start the flow
379 debug('Socket._read readStart');
380 this._handle.reading = true;
381 var err = this._handle.readStart();
383 this._destroy(errnoException(err, 'read'));
388 Socket.prototype.end = function(data, encoding) {
389 stream.Duplex.prototype.end.call(this, data, encoding);
390 this.writable = false;
391 DTRACE_NET_STREAM_END(this);
393 // just in case we're waiting for an EOF.
394 if (this.readable && !this._readableState.endEmitted)
401 // Call whenever we set writable=false or readable=false
402 function maybeDestroy(socket) {
403 if (!socket.readable &&
406 !socket._connecting &&
407 !socket._writableState.length) {
413 Socket.prototype.destroySoon = function() {
417 if (this._writableState.finished)
420 this.once('finish', this.destroy);
424 Socket.prototype._destroy = function(exception, cb) {
429 function fireErrorCallbacks() {
430 if (cb) cb(exception);
431 if (exception && !self.errorEmitted) {
432 process.nextTick(function() {
433 self.emit('error', exception);
435 self.errorEmitted = true;
439 if (this.destroyed) {
440 debug('already destroyed, fire error callbacks');
441 fireErrorCallbacks();
445 self._connecting = false;
447 this.readable = this.writable = false;
449 timers.unenroll(this);
453 if (this !== process.stderr)
454 debug('close handle');
455 var isException = exception ? true : false;
456 this._handle.close(function() {
458 self.emit('close', isException);
460 this._handle.onread = noop;
464 fireErrorCallbacks();
465 this.destroyed = true;
468 COUNTER_NET_SERVER_CONNECTION_CLOSE(this);
470 this.server._connections--;
471 if (this.server._emitCloseIfDrained) {
472 this.server._emitCloseIfDrained();
478 Socket.prototype.destroy = function(exception) {
479 debug('destroy', exception);
480 this._destroy(exception);
484 // This function is called whenever the handle gets a
485 // buffer, or when there's an error reading.
486 function onread(nread, buffer) {
488 var self = handle.owner;
489 assert(handle === self._handle, 'handle != self._handle');
491 timers._unrefActive(self);
493 debug('onread', nread);
499 // In theory (and in practice) calling readStop right now
500 // will prevent this from being called again until _read() gets
503 // if it's not enough data, we'll just call handle.readStart()
505 self.bytesRead += nread;
507 // Optimization: emit the original buffer with end points
508 var ret = self.push(buffer);
510 if (handle.reading && !ret) {
511 handle.reading = false;
513 var err = handle.readStop();
515 self._destroy(errnoException(err, 'read'));
520 // if we didn't get any bytes, that doesn't necessarily mean EOF.
521 // wait for the next one.
523 debug('not any data, keep waiting');
527 // Error, possibly EOF.
528 if (nread !== uv.UV_EOF) {
529 return self._destroy(errnoException(nread, 'read'));
534 if (self._readableState.length === 0) {
535 self.readable = false;
539 // push a null to signal the end of data.
542 // internal end event so that we know that the actual socket
543 // is no longer readable, and we can start the shutdown
544 // procedure. No need to wait for all the data to be consumed.
545 self.emit('_socketEnd');
549 Socket.prototype._getpeername = function() {
550 if (!this._handle || !this._handle.getpeername) {
553 if (!this._peername) {
555 var err = this._handle.getpeername(out);
556 if (err) return {}; // FIXME(bnoordhuis) Throw?
557 this._peername = out;
559 return this._peername;
563 Socket.prototype.__defineGetter__('remoteAddress', function() {
564 return this._getpeername().address;
568 Socket.prototype.__defineGetter__('remotePort', function() {
569 return this._getpeername().port;
573 Socket.prototype._getsockname = function() {
574 if (!this._handle || !this._handle.getsockname) {
577 if (!this._sockname) {
579 var err = this._handle.getsockname(out);
580 if (err) return {}; // FIXME(bnoordhuis) Throw?
581 this._sockname = out;
583 return this._sockname;
587 Socket.prototype.__defineGetter__('localAddress', function() {
588 return this._getsockname().address;
592 Socket.prototype.__defineGetter__('localPort', function() {
593 return this._getsockname().port;
597 Socket.prototype.write = function(chunk, encoding, cb) {
598 if (!util.isString(chunk) && !util.isBuffer(chunk))
599 throw new TypeError('invalid data');
600 return stream.Duplex.prototype.write.apply(this, arguments);
604 Socket.prototype._writeGeneric = function(writev, data, encoding, cb) {
605 // If we are still connecting, then buffer this for later.
606 // The Writable logic will buffer up any more writes while
607 // waiting for this one to be done.
608 if (this._connecting) {
609 this._pendingData = data;
610 this._pendingEncoding = encoding;
611 this.once('connect', function() {
612 this._writeGeneric(writev, data, encoding, cb);
616 this._pendingData = null;
617 this._pendingEncoding = '';
619 timers._unrefActive(this);
622 this._destroy(new Error('This socket is closed.'), cb);
626 var req = { oncomplete: afterWrite };
630 var chunks = new Array(data.length << 1);
631 for (var i = 0; i < data.length; i++) {
633 var chunk = entry.chunk;
634 var enc = entry.encoding;
635 chunks[i * 2] = chunk;
636 chunks[i * 2 + 1] = enc;
638 err = this._handle.writev(req, chunks);
641 if (err === 0) req._chunks = chunks;
644 if (util.isBuffer(data)) {
645 req.buffer = data; // Keep reference alive.
650 err = createWriteReq(req, this._handle, data, enc);
654 return this._destroy(errnoException(err, 'write'), cb);
656 this._bytesDispatched += req.bytes;
658 // If it was entirely flushed, we can write some more right now.
659 // However, if more is left in the queue, then wait until that clears.
660 if (this._handle.writeQueueSize === 0)
667 Socket.prototype._writev = function(chunks, cb) {
668 this._writeGeneric(true, chunks, '', cb);
672 Socket.prototype._write = function(data, encoding, cb) {
673 this._writeGeneric(false, data, encoding, cb);
676 // Important: this should have the same values as in src/stream_wrap.h
677 function getEncodingId(encoding) {
700 function createWriteReq(req, handle, data, encoding) {
703 return handle.writeBuffer(req, data);
707 return handle.writeUtf8String(req, data);
710 return handle.writeAsciiString(req, data);
716 return handle.writeUcs2String(req, data);
719 return handle.writeBuffer(req, new Buffer(data, encoding));
724 Socket.prototype.__defineGetter__('bytesWritten', function() {
725 var bytes = this._bytesDispatched,
726 state = this._writableState,
727 data = this._pendingData,
728 encoding = this._pendingEncoding;
730 state.buffer.forEach(function(el) {
731 if (util.isBuffer(el.chunk))
732 bytes += el.chunk.length;
734 bytes += Buffer.byteLength(el.chunk, el.encoding);
738 if (util.isBuffer(data))
739 bytes += data.length;
741 bytes += Buffer.byteLength(data, encoding);
748 function afterWrite(status, handle, req) {
749 var self = handle.owner;
750 if (self !== process.stderr && self !== process.stdout)
751 debug('afterWrite', status);
753 // callback may come after call to destroy.
754 if (self.destroyed) {
755 debug('afterWrite destroyed');
760 var ex = errnoException(status, 'write');
761 debug('write failure', ex);
762 self._destroy(ex, req.cb);
766 timers._unrefActive(self);
768 if (self !== process.stderr && self !== process.stdout)
769 debug('afterWrite call cb');
776 function connect(self, address, port, addressType, localAddress) {
777 // TODO return promise from Socket.prototype.connect which
778 // wraps _connectReq.
780 assert.ok(self._connecting);
784 if (addressType == 6) {
785 err = self._handle.bind6(localAddress);
787 err = self._handle.bind(localAddress);
791 self._destroy(errnoException(err, 'bind'));
796 var req = { oncomplete: afterConnect };
797 if (addressType == 6) {
798 err = self._handle.connect6(req, address, port);
799 } else if (addressType == 4) {
800 err = self._handle.connect(req, address, port);
802 err = self._handle.connect(req, address, afterConnect);
806 self._destroy(errnoException(err, 'connect'));
811 Socket.prototype.connect = function(options, cb) {
812 if (this.write !== Socket.prototype.write)
813 this.write = Socket.prototype.write;
815 if (!util.isObject(options)) {
817 // connect(port, [host], [cb])
818 // connect(path, [cb]);
819 var args = normalizeConnectArgs(arguments);
820 return Socket.prototype.connect.apply(this, args);
823 if (this.destroyed) {
824 this._readableState.reading = false;
825 this._readableState.ended = false;
826 this._writableState.ended = false;
827 this._writableState.ending = false;
828 this._writableState.finished = false;
829 this.destroyed = false;
834 var pipe = !!options.path;
835 debug('pipe', pipe, options.path);
838 this._handle = pipe ? createPipe() : createTCP();
839 initSocketHandle(this);
842 if (util.isFunction(cb)) {
843 self.once('connect', cb);
846 timers._unrefActive(this);
848 self._connecting = true;
849 self.writable = true;
852 connect(self, options.path);
854 } else if (!options.host) {
855 debug('connect: missing host');
856 connect(self, '127.0.0.1', options.port, 4);
859 var host = options.host;
860 var family = options.family || 4;
861 debug('connect: find host ' + host);
862 require('dns').lookup(host, family, function(err, ip, addressType) {
863 self.emit('lookup', err, ip, addressType);
865 // It's possible we were destroyed while looking this up.
866 // XXX it would be great if we could cancel the promise returned by
868 if (!self._connecting) return;
871 // net.createConnection() creates a net.Socket object and
872 // immediately calls net.Socket.connect() on it (that's us).
873 // There are no event listeners registered yet so defer the
874 // error event to the next tick.
875 process.nextTick(function() {
876 self.emit('error', err);
880 timers._unrefActive(self);
882 addressType = addressType || 4;
884 // node_net.cc handles null host names graciously but user land
885 // expects remoteAddress to have a meaningful value
886 ip = ip || (addressType === 4 ? '127.0.0.1' : '0:0:0:0:0:0:0:1');
888 connect(self, ip, options.port, addressType, options.localAddress);
896 Socket.prototype.ref = function() {
902 Socket.prototype.unref = function() {
904 this._handle.unref();
909 function afterConnect(status, handle, req, readable, writable) {
910 var self = handle.owner;
912 // callback may come after call to destroy
913 if (self.destroyed) {
917 assert(handle === self._handle, 'handle != self._handle');
919 debug('afterConnect');
921 assert.ok(self._connecting);
922 self._connecting = false;
925 self.readable = readable;
926 self.writable = writable;
927 timers._unrefActive(self);
929 self.emit('connect');
931 // start the first read, or get an immediate EOF.
932 // this doesn't actually consume any bytes, because len=0.
937 self._connecting = false;
938 self._destroy(errnoException(status, 'connect'));
943 function Server(/* [ options, ] listener */) {
944 if (!(this instanceof Server)) return new Server(arguments[0], arguments[1]);
945 events.EventEmitter.call(this);
951 if (util.isFunction(arguments[0])) {
953 self.on('connection', arguments[0]);
955 options = arguments[0] || {};
957 if (util.isFunction(arguments[1])) {
958 self.on('connection', arguments[1]);
962 this._connections = 0;
964 Object.defineProperty(this, 'connections', {
965 get: util.deprecate(function() {
967 if (self._usingSlaves) {
970 return self._connections;
971 }, 'connections property is deprecated. Use getConnections() method'),
972 set: util.deprecate(function(val) {
973 return (self._connections = val);
974 }, 'connections property is deprecated. Use getConnections() method'),
975 configurable: true, enumerable: true
979 this._usingSlaves = false;
982 this.allowHalfOpen = options.allowHalfOpen || false;
984 util.inherits(Server, events.EventEmitter);
985 exports.Server = Server;
988 function toNumber(x) { return (x = Number(x)) >= 0 ? x : false; }
991 var createServerHandle = exports._createServerHandle =
992 function(address, port, addressType, fd) {
994 // assign handle in listen, and clean up if bind or listen fails
997 if (util.isNumber(fd) && fd >= 0) {
999 handle = createHandle(fd);
1002 // Not a fd we can listen on. This will trigger an error.
1003 debug('listen invalid fd=' + fd + ': ' + e.message);
1004 return uv.UV_EINVAL;
1007 handle.readable = true;
1008 handle.writable = true;
1011 } else if (port == -1 && addressType == -1) {
1012 handle = createPipe();
1013 if (process.platform === 'win32') {
1014 var instances = parseInt(process.env.NODE_PENDING_PIPE_INSTANCES);
1015 if (!isNaN(instances)) {
1016 handle.setPendingInstances(instances);
1020 handle = createTCP();
1023 if (address || port) {
1024 debug('bind to ' + address);
1025 if (addressType == 6) {
1026 err = handle.bind6(address, port);
1028 err = handle.bind(address, port);
1041 Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
1042 debug('listen2', address, port, addressType, backlog);
1045 // If there is not yet a handle, we need to create one and bind.
1046 // In the case of a server sent via IPC, we don't need to do this.
1047 if (!self._handle) {
1048 debug('_listen2: create a handle');
1049 var rval = createServerHandle(address, port, addressType, fd);
1050 if (util.isNumber(rval)) {
1051 var error = errnoException(rval, 'listen');
1052 process.nextTick(function() {
1053 self.emit('error', error);
1057 self._handle = rval;
1059 debug('_listen2: have a handle already');
1062 self._handle.onconnection = onconnection;
1063 self._handle.owner = self;
1065 // Use a backlog of 512 entries. We pass 511 to the listen() call because
1066 // the kernel does: backlogsize = roundup_pow_of_two(backlogsize + 1);
1067 // which will thus give us a backlog of 512 entries.
1068 var err = self._handle.listen(backlog || 511);
1071 var ex = errnoException(err, 'listen');
1072 self._handle.close();
1073 self._handle = null;
1074 process.nextTick(function() {
1075 self.emit('error', ex);
1080 // generate connection key, this should be unique to the connection
1081 this._connectionKey = addressType + ':' + address + ':' + port;
1083 process.nextTick(function() {
1084 self.emit('listening');
1089 function listen(self, address, port, addressType, backlog, fd) {
1090 if (!cluster) cluster = require('cluster');
1092 if (cluster.isMaster) {
1093 self._listen2(address, port, addressType, backlog, fd);
1097 cluster._getServer(self, address, port, addressType, fd, cb);
1099 function cb(err, handle) {
1100 // EADDRINUSE may not be reported until we call listen(). To complicate
1101 // matters, a failed bind() followed by listen() will implicitly bind to
1102 // a random port. Ergo, check that the socket is bound to the expected
1103 // port before calling listen().
1105 // FIXME(bnoordhuis) Doesn't work for pipe handles, they don't have a
1106 // getsockname() method. Non-issue for now, the cluster module doesn't
1107 // really support pipes anyway.
1108 if (err === 0 && port > 0 && handle.getsockname) {
1110 err = handle.getsockname(out);
1111 if (err === 0 && port !== out.port)
1112 err = uv.UV_EADDRINUSE;
1116 return self.emit('error', errnoException(err, 'bind'));
1118 self._handle = handle;
1119 self._listen2(address, port, addressType, backlog, fd);
1124 Server.prototype.listen = function() {
1127 var lastArg = arguments[arguments.length - 1];
1128 if (util.isFunction(lastArg)) {
1129 self.once('listening', lastArg);
1132 var port = toNumber(arguments[0]);
1134 // The third optional argument is the backlog size.
1135 // When the ip is omitted it can be the second argument.
1136 var backlog = toNumber(arguments[1]) || toNumber(arguments[2]);
1138 var TCP = process.binding('tcp_wrap').TCP;
1140 if (arguments.length == 0 || util.isFunction(arguments[0])) {
1141 // Bind to a random port.
1142 listen(self, '0.0.0.0', 0, null, backlog);
1144 } else if (arguments[0] && util.isObject(arguments[0])) {
1145 var h = arguments[0];
1148 } else if (h.handle) {
1151 if (h instanceof TCP) {
1153 listen(self, null, -1, -1, backlog);
1154 } else if (util.isNumber(h.fd) && h.fd >= 0) {
1155 listen(self, null, null, null, backlog, h.fd);
1157 throw new Error('Invalid listen argument: ' + h);
1159 } else if (isPipeName(arguments[0])) {
1160 // UNIX socket or Windows pipe.
1161 var pipeName = self._pipeName = arguments[0];
1162 listen(self, pipeName, -1, -1, backlog);
1164 } else if (util.isUndefined(arguments[1]) ||
1165 util.isFunction(arguments[1]) ||
1166 util.isNumber(arguments[1])) {
1167 // The first argument is the port, no IP given.
1168 listen(self, '0.0.0.0', port, 4, backlog);
1171 // The first argument is the port, the second an IP.
1172 require('dns').lookup(arguments[1], function(err, ip, addressType) {
1174 self.emit('error', err);
1176 listen(self, ip || '0.0.0.0', port, ip ? addressType : 4, backlog);
1183 Server.prototype.address = function() {
1184 if (this._handle && this._handle.getsockname) {
1186 var err = this._handle.getsockname(out);
1187 // TODO(bnoordhuis) Check err and throw?
1189 } else if (this._pipeName) {
1190 return this._pipeName;
1196 function onconnection(err, clientHandle) {
1198 var self = handle.owner;
1200 debug('onconnection');
1203 self.emit('error', errnoException(err, 'accept'));
1207 if (self.maxConnections && self._connections >= self.maxConnections) {
1208 clientHandle.close();
1212 var socket = new Socket({
1213 handle: clientHandle,
1214 allowHalfOpen: self.allowHalfOpen
1216 socket.readable = socket.writable = true;
1219 self._connections++;
1220 socket.server = self;
1222 DTRACE_NET_SERVER_CONNECTION(socket);
1223 COUNTER_NET_SERVER_CONNECTION(socket);
1224 self.emit('connection', socket);
1228 Server.prototype.getConnections = function(cb) {
1229 function end(err, connections) {
1230 process.nextTick(function() {
1231 cb(err, connections);
1235 if (!this._usingSlaves) {
1236 return end(null, this._connections);
1240 var left = this._slaves.length,
1241 total = this._connections;
1243 function oncount(err, count) {
1250 if (--left === 0) return end(null, total);
1253 this._slaves.forEach(function(slave) {
1254 slave.getConnections(oncount);
1259 Server.prototype.close = function(cb) {
1260 function onSlaveClose() {
1261 if (--left !== 0) return;
1263 self._connections = 0;
1264 self._emitCloseIfDrained();
1267 if (!this._handle) {
1268 // Throw error. Follows net_legacy behaviour.
1269 throw new Error('Not running');
1273 this.once('close', cb);
1275 this._handle.close();
1276 this._handle = null;
1278 if (this._usingSlaves) {
1280 left = this._slaves.length;
1282 // Increment connections to be sure that, even if all sockets will be closed
1283 // during polling of slaves, `close` event will be emitted only once.
1284 this._connections++;
1287 this._slaves.forEach(function(slave) {
1288 slave.close(onSlaveClose);
1291 this._emitCloseIfDrained();
1297 Server.prototype._emitCloseIfDrained = function() {
1298 debug('SERVER _emitCloseIfDrained');
1301 if (self._handle || self._connections) {
1302 debug('SERVER handle? %j connections? %d',
1303 !!self._handle, self._connections);
1307 process.nextTick(function() {
1308 debug('SERVER: emit close');
1314 Server.prototype.listenFD = util.deprecate(function(fd, type) {
1315 return this.listen({ fd: fd });
1316 }, 'listenFD is deprecated. Use listen({fd: <number>}).');
1318 Server.prototype._setupSlave = function(socketList) {
1319 this._usingSlaves = true;
1320 this._slaves.push(socketList);
1323 Server.prototype.ref = function() {
1328 Server.prototype.unref = function() {
1330 this._handle.unref();
1334 // TODO: isIP should be moved to the DNS code. Putting it here now because
1335 // this is what the legacy system did.
1336 exports.isIP = cares.isIP;
1339 exports.isIPv4 = function(input) {
1340 return exports.isIP(input) === 4;
1344 exports.isIPv6 = function(input) {
1345 return exports.isIP(input) === 6;
1349 if (process.platform === 'win32') {
1350 var simultaneousAccepts;
1352 exports._setSimultaneousAccepts = function(handle) {
1353 if (util.isUndefined(handle)) {
1357 if (util.isUndefined(simultaneousAccepts)) {
1358 simultaneousAccepts = (process.env.NODE_MANY_ACCEPTS &&
1359 process.env.NODE_MANY_ACCEPTS !== '0');
1362 if (handle._simultaneousAccepts !== simultaneousAccepts) {
1363 handle.setSimultaneousAccepts(simultaneousAccepts);
1364 handle._simultaneousAccepts = simultaneousAccepts;
1368 exports._setSimultaneousAccepts = function(handle) {};