3 const EventEmitter = require('events');
4 const stream = require('stream');
5 const timers = require('timers');
6 const util = require('util');
7 const internalUtil = require('internal/util');
8 const internalNet = require('internal/net');
9 const assert = require('assert');
10 const cares = process.binding('cares_wrap');
11 const uv = process.binding('uv');
13 const Buffer = require('buffer').Buffer;
14 const TTYWrap = process.binding('tty_wrap');
15 const TCP = process.binding('tcp_wrap').TCP;
16 const Pipe = process.binding('pipe_wrap').Pipe;
17 const TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap;
18 const PipeConnectWrap = process.binding('pipe_wrap').PipeConnectWrap;
19 const ShutdownWrap = process.binding('stream_wrap').ShutdownWrap;
20 const WriteWrap = process.binding('stream_wrap').WriteWrap;
24 const errnoException = util._errnoException;
25 const exceptionWithHostPort = util._exceptionWithHostPort;
26 const isLegalPort = internalNet.isLegalPort;
30 function createHandle(fd) {
31 var type = TTYWrap.guessHandleType(fd);
32 if (type === 'PIPE') return new Pipe();
33 if (type === 'TCP') return new TCP();
34 throw new TypeError('Unsupported fd type: ' + type);
38 const debug = util.debuglog('net');
40 function isPipeName(s) {
41 return typeof s === 'string' && toNumber(s) === false;
44 exports.createServer = function(options, connectionListener) {
45 return new Server(options, connectionListener);
51 // var s = net.connect({port: 80, host: 'google.com'}, function() {
55 // There are various forms:
57 // connect(options, [cb])
58 // connect(port, [host], [cb])
59 // connect(path, [cb]);
61 exports.connect = exports.createConnection = function() {
62 var args = normalizeConnectArgs(arguments);
63 debug('createConnection', args);
64 var s = new Socket(args[0]);
65 return Socket.prototype.connect.apply(s, args);
68 // Returns an array [options] or [options, cb]
69 // It is the same as the argument of Socket.prototype.connect().
70 function normalizeConnectArgs(args) {
73 if (args[0] !== null && typeof args[0] === 'object') {
74 // connect(options, [cb])
76 } else if (isPipeName(args[0])) {
77 // connect(path, [cb]);
78 options.path = args[0];
80 // connect(port, [host], [cb])
81 options.port = args[0];
82 if (typeof args[1] === 'string') {
83 options.host = args[1];
87 var cb = args[args.length - 1];
88 return typeof cb === 'function' ? [options, cb] : [options];
90 exports._normalizeConnectArgs = normalizeConnectArgs;
93 // called when creating new Socket, or when re-using a closed Socket
94 function initSocketHandle(self) {
95 self.destroyed = false;
97 self._bytesDispatched = 0;
98 self._sockname = null;
100 // Handle creation may be deferred to bind() or connect() time.
102 self._handle.owner = self;
103 self._handle.onread = onread;
105 // If handle doesn't support writev - neither do we
106 if (!self._handle.writev)
111 function Socket(options) {
112 if (!(this instanceof Socket)) return new Socket(options);
114 this._connecting = false;
115 this._hadError = false;
120 if (typeof options === 'number')
121 options = { fd: options }; // Legacy interface.
122 else if (options === undefined)
125 stream.Duplex.call(this, options);
127 if (options.handle) {
128 this._handle = options.handle; // private
129 } else if (options.fd !== undefined) {
130 this._handle = createHandle(options.fd);
131 this._handle.open(options.fd);
132 if ((options.fd == 1 || options.fd == 2) &&
133 (this._handle instanceof Pipe) &&
134 process.platform === 'win32') {
135 // Make stdout and stderr blocking on Windows
136 var err = this._handle.setBlocking(true);
138 throw errnoException(err, 'setBlocking');
140 this.readable = options.readable !== false;
141 this.writable = options.writable !== false;
143 // these will be set once there is a connection
144 this.readable = this.writable = false;
147 // shut down the socket when we're finished with it.
148 this.on('finish', onSocketFinish);
149 this.on('_socketEnd', onSocketEnd);
151 initSocketHandle(this);
153 this._pendingData = null;
154 this._pendingEncoding = '';
156 // handle strings directly
157 this._writableState.decodeStrings = false;
159 // default to *not* allowing half open sockets
160 this.allowHalfOpen = options && options.allowHalfOpen || false;
162 // if we have a handle, then start the flow of data into the
163 // buffer. if not, then this will happen when we connect
164 if (this._handle && options.readable !== false) {
165 if (options.pauseOnCreate) {
166 // stop the handle from reading and pause the stream
167 this._handle.reading = false;
168 this._handle.readStop();
169 this._readableState.flowing = false;
175 // Reserve properties
179 util.inherits(Socket, stream.Duplex);
181 Socket.prototype._unrefTimer = function unrefTimer() {
182 for (var s = this; s !== null; s = s._parent)
183 timers._unrefActive(s);
186 // the user has called .end(), and all the bytes have been
187 // sent out to the other side.
188 // If allowHalfOpen is false, or if the readable side has
189 // ended already, then destroy.
190 // If allowHalfOpen is true, then we need to do a shutdown,
191 // so that only the writable side will be cleaned up.
192 function onSocketFinish() {
193 // If still connecting - defer handling 'finish' until 'connect' will happen
194 if (this._connecting) {
195 debug('osF: not yet connected');
196 return this.once('connect', onSocketFinish);
199 debug('onSocketFinish');
200 if (!this.readable || this._readableState.ended) {
201 debug('oSF: ended, destroy', this._readableState);
202 return this.destroy();
205 debug('oSF: not ended, call shutdown()');
207 // otherwise, just shutdown, or destroy() if not possible
208 if (!this._handle || !this._handle.shutdown)
209 return this.destroy();
211 var req = new ShutdownWrap();
212 req.oncomplete = afterShutdown;
213 req.handle = this._handle;
214 var err = this._handle.shutdown(req);
217 return this._destroy(errnoException(err, 'shutdown'));
221 function afterShutdown(status, handle, req) {
222 var self = handle.owner;
224 debug('afterShutdown destroyed=%j', self.destroyed,
225 self._readableState);
227 // callback may come after call to destroy.
231 if (self._readableState.ended) {
232 debug('readableState ended, destroying');
235 self.once('_socketEnd', self.destroy);
239 // the EOF has been received, and no more bytes are coming.
240 // if the writable side has ended already, then clean everything
242 function onSocketEnd() {
243 // XXX Should not have to do as much crap in this function.
244 // ended should already be true, since this is called *after*
245 // the EOF errno and onread has eof'ed
246 debug('onSocketEnd', this._readableState);
247 this._readableState.ended = true;
248 if (this._readableState.endEmitted) {
249 this.readable = false;
252 this.once('end', function() {
253 this.readable = false;
259 if (!this.allowHalfOpen) {
260 this.write = writeAfterFIN;
265 // Provide a better error message when we call end() as a result
266 // of the other side sending a FIN. The standard 'write after end'
267 // is overly vague, and makes it seem like the user's code is to blame.
268 function writeAfterFIN(chunk, encoding, cb) {
269 if (typeof encoding === 'function') {
274 var er = new Error('This socket has been ended by the other party');
277 // TODO: defer error events consistently everywhere, not just the cb
278 self.emit('error', er);
279 if (typeof cb === 'function') {
280 process.nextTick(cb, er);
284 exports.Socket = Socket;
285 exports.Stream = Socket; // Legacy naming.
287 Socket.prototype.read = function(n) {
289 return stream.Readable.prototype.read.call(this, n);
291 this.read = stream.Readable.prototype.read;
292 this._consuming = true;
297 Socket.prototype.listen = function() {
298 debug('socket.listen');
300 self.on('connection', arguments[0]);
301 listen(self, null, null, null);
305 Socket.prototype.setTimeout = function(msecs, callback) {
307 timers.unenroll(this);
309 this.removeListener('timeout', callback);
312 timers.enroll(this, msecs);
313 timers._unrefActive(this);
315 this.once('timeout', callback);
322 Socket.prototype._onTimeout = function() {
324 this.emit('timeout');
328 Socket.prototype.setNoDelay = function(enable) {
331 enable ? this.setNoDelay : () => this.setNoDelay(enable));
335 // backwards compatibility: assume true when `enable` is omitted
336 if (this._handle.setNoDelay)
337 this._handle.setNoDelay(enable === undefined ? true : !!enable);
343 Socket.prototype.setKeepAlive = function(setting, msecs) {
345 this.once('connect', () => this.setKeepAlive(setting, msecs));
349 if (this._handle.setKeepAlive)
350 this._handle.setKeepAlive(setting, ~~(msecs / 1000));
356 Socket.prototype.address = function() {
357 return this._getsockname();
361 Object.defineProperty(Socket.prototype, 'readyState', {
363 if (this._connecting) {
365 } else if (this.readable && this.writable) {
367 } else if (this.readable && !this.writable) {
369 } else if (!this.readable && this.writable) {
378 Object.defineProperty(Socket.prototype, 'bufferSize', {
381 return this._handle.writeQueueSize + this._writableState.length;
387 // Just call handle.readStart until we have enough in the buffer
388 Socket.prototype._read = function(n) {
391 if (this._connecting || !this._handle) {
392 debug('_read wait for connection');
393 this.once('connect', () => this._read(n));
394 } else if (!this._handle.reading) {
395 // not already reading, start the flow
396 debug('Socket._read readStart');
397 this._handle.reading = true;
398 var err = this._handle.readStart();
400 this._destroy(errnoException(err, 'read'));
405 Socket.prototype.end = function(data, encoding) {
406 stream.Duplex.prototype.end.call(this, data, encoding);
407 this.writable = false;
408 DTRACE_NET_STREAM_END(this);
409 LTTNG_NET_STREAM_END(this);
411 // just in case we're waiting for an EOF.
412 if (this.readable && !this._readableState.endEmitted)
419 // Call whenever we set writable=false or readable=false
420 function maybeDestroy(socket) {
421 if (!socket.readable &&
424 !socket._connecting &&
425 !socket._writableState.length) {
431 Socket.prototype.destroySoon = function() {
435 if (this._writableState.finished)
438 this.once('finish', this.destroy);
442 Socket.prototype._destroy = function(exception, cb) {
447 function fireErrorCallbacks() {
448 if (cb) cb(exception);
449 if (exception && !self._writableState.errorEmitted) {
450 process.nextTick(emitErrorNT, self, exception);
451 self._writableState.errorEmitted = true;
455 if (this.destroyed) {
456 debug('already destroyed, fire error callbacks');
457 fireErrorCallbacks();
461 self._connecting = false;
463 this.readable = this.writable = false;
465 for (var s = this; s !== null; s = s._parent)
470 if (this !== process.stderr)
471 debug('close handle');
472 var isException = exception ? true : false;
473 this._handle.close(function() {
475 self.emit('close', isException);
477 this._handle.onread = noop;
479 this._sockname = null;
482 // we set destroyed to true before firing error callbacks in order
483 // to make it re-entrance safe in case Socket.prototype.destroy()
484 // is called within callbacks
485 this.destroyed = true;
486 fireErrorCallbacks();
489 COUNTER_NET_SERVER_CONNECTION_CLOSE(this);
491 this._server._connections--;
492 if (this._server._emitCloseIfDrained) {
493 this._server._emitCloseIfDrained();
499 Socket.prototype.destroy = function(exception) {
500 debug('destroy', exception);
501 this._destroy(exception);
505 // This function is called whenever the handle gets a
506 // buffer, or when there's an error reading.
507 function onread(nread, buffer) {
509 var self = handle.owner;
510 assert(handle === self._handle, 'handle != self._handle');
514 debug('onread', nread);
520 // In theory (and in practice) calling readStop right now
521 // will prevent this from being called again until _read() gets
524 // if it's not enough data, we'll just call handle.readStart()
526 self.bytesRead += nread;
528 // Optimization: emit the original buffer with end points
529 var ret = self.push(buffer);
531 if (handle.reading && !ret) {
532 handle.reading = false;
534 var err = handle.readStop();
536 self._destroy(errnoException(err, 'read'));
541 // if we didn't get any bytes, that doesn't necessarily mean EOF.
542 // wait for the next one.
544 debug('not any data, keep waiting');
548 // Error, possibly EOF.
549 if (nread !== uv.UV_EOF) {
550 return self._destroy(errnoException(nread, 'read'));
555 if (self._readableState.length === 0) {
556 self.readable = false;
560 // push a null to signal the end of data.
563 // internal end event so that we know that the actual socket
564 // is no longer readable, and we can start the shutdown
565 // procedure. No need to wait for all the data to be consumed.
566 self.emit('_socketEnd');
570 Socket.prototype._getpeername = function() {
571 if (!this._peername) {
572 if (!this._handle || !this._handle.getpeername) {
576 var err = this._handle.getpeername(out);
577 if (err) return {}; // FIXME(bnoordhuis) Throw?
578 this._peername = out;
580 return this._peername;
584 Socket.prototype.__defineGetter__('remoteAddress', function() {
585 return this._getpeername().address;
588 Socket.prototype.__defineGetter__('remoteFamily', function() {
589 return this._getpeername().family;
592 Socket.prototype.__defineGetter__('remotePort', function() {
593 return this._getpeername().port;
597 Socket.prototype._getsockname = function() {
598 if (!this._handle || !this._handle.getsockname) {
601 if (!this._sockname) {
603 var err = this._handle.getsockname(out);
604 if (err) return {}; // FIXME(bnoordhuis) Throw?
605 this._sockname = out;
607 return this._sockname;
611 Socket.prototype.__defineGetter__('localAddress', function() {
612 return this._getsockname().address;
616 Socket.prototype.__defineGetter__('localPort', function() {
617 return this._getsockname().port;
621 Socket.prototype.write = function(chunk, encoding, cb) {
622 if (typeof chunk !== 'string' && !(chunk instanceof Buffer))
623 throw new TypeError('invalid data');
624 return stream.Duplex.prototype.write.apply(this, arguments);
628 Socket.prototype._writeGeneric = function(writev, data, encoding, cb) {
629 // If we are still connecting, then buffer this for later.
630 // The Writable logic will buffer up any more writes while
631 // waiting for this one to be done.
632 if (this._connecting) {
633 this._pendingData = data;
634 this._pendingEncoding = encoding;
635 this.once('connect', function() {
636 this._writeGeneric(writev, data, encoding, cb);
640 this._pendingData = null;
641 this._pendingEncoding = '';
646 this._destroy(new Error('This socket is closed.'), cb);
650 var req = new WriteWrap();
651 req.handle = this._handle;
652 req.oncomplete = afterWrite;
657 var chunks = new Array(data.length << 1);
658 for (var i = 0; i < data.length; i++) {
660 chunks[i * 2] = entry.chunk;
661 chunks[i * 2 + 1] = entry.encoding;
663 err = this._handle.writev(req, chunks);
666 if (err === 0) req._chunks = chunks;
669 if (data instanceof Buffer) {
670 req.buffer = data; // Keep reference alive.
675 err = createWriteReq(req, this._handle, data, enc);
679 return this._destroy(errnoException(err, 'write', req.error), cb);
681 this._bytesDispatched += req.bytes;
683 // If it was entirely flushed, we can write some more right now.
684 // However, if more is left in the queue, then wait until that clears.
685 if (req.async && this._handle.writeQueueSize != 0)
692 Socket.prototype._writev = function(chunks, cb) {
693 this._writeGeneric(true, chunks, '', cb);
697 Socket.prototype._write = function(data, encoding, cb) {
698 this._writeGeneric(false, data, encoding, cb);
701 function createWriteReq(req, handle, data, encoding) {
704 return handle.writeBinaryString(req, data);
707 return handle.writeBuffer(req, data);
711 return handle.writeUtf8String(req, data);
714 return handle.writeAsciiString(req, data);
720 return handle.writeUcs2String(req, data);
723 return handle.writeBuffer(req, new Buffer(data, encoding));
728 Socket.prototype.__defineGetter__('bytesWritten', function() {
729 var bytes = this._bytesDispatched;
730 const state = this._writableState;
731 const data = this._pendingData;
732 const encoding = this._pendingEncoding;
737 state.getBuffer().forEach(function(el) {
738 if (el.chunk instanceof Buffer)
739 bytes += el.chunk.length;
741 bytes += Buffer.byteLength(el.chunk, el.encoding);
745 if (data instanceof Buffer)
746 bytes += data.length;
748 bytes += Buffer.byteLength(data, encoding);
755 function afterWrite(status, handle, req, err) {
756 var self = handle.owner;
757 if (self !== process.stderr && self !== process.stdout)
758 debug('afterWrite', status);
760 // callback may come after call to destroy.
761 if (self.destroyed) {
762 debug('afterWrite destroyed');
767 var ex = errnoException(status, 'write', req.error);
768 debug('write failure', ex);
769 self._destroy(ex, req.cb);
775 if (self !== process.stderr && self !== process.stdout)
776 debug('afterWrite call cb');
783 function connect(self, address, port, addressType, localAddress, localPort) {
784 // TODO return promise from Socket.prototype.connect which
785 // wraps _connectReq.
787 assert.ok(self._connecting);
791 if (localAddress || localPort) {
794 if (addressType === 4) {
795 localAddress = localAddress || '0.0.0.0';
796 bind = self._handle.bind;
797 } else if (addressType === 6) {
798 localAddress = localAddress || '::';
799 bind = self._handle.bind6;
801 self._destroy(new TypeError('Invalid addressType: ' + addressType));
805 debug('binding to localAddress: %s and localPort: %d',
809 bind = bind.bind(self._handle);
810 err = bind(localAddress, localPort);
813 const ex = exceptionWithHostPort(err, 'bind', localAddress, localPort);
819 if (addressType === 6 || addressType === 4) {
820 const req = new TCPConnectWrap();
821 req.oncomplete = afterConnect;
822 req.address = address;
824 req.localAddress = localAddress;
825 req.localPort = localPort;
827 if (addressType === 4)
828 err = self._handle.connect(req, address, port);
830 err = self._handle.connect6(req, address, port);
833 const req = new PipeConnectWrap();
834 req.address = address;
835 req.oncomplete = afterConnect;
836 err = self._handle.connect(req, address, afterConnect);
840 var sockname = self._getsockname();
844 details = sockname.address + ':' + sockname.port;
847 const ex = exceptionWithHostPort(err, 'connect', address, port, details);
853 Socket.prototype.connect = function(options, cb) {
854 if (this.write !== Socket.prototype.write)
855 this.write = Socket.prototype.write;
857 if (options === null || typeof options !== 'object') {
859 // connect(port, [host], [cb])
860 // connect(path, [cb]);
861 var args = normalizeConnectArgs(arguments);
862 return Socket.prototype.connect.apply(this, args);
865 if (this.destroyed) {
866 this._readableState.reading = false;
867 this._readableState.ended = false;
868 this._readableState.endEmitted = false;
869 this._writableState.ended = false;
870 this._writableState.ending = false;
871 this._writableState.finished = false;
872 this._writableState.errorEmitted = false;
873 this.destroyed = false;
875 this._peername = null;
876 this._sockname = null;
880 var pipe = !!options.path;
881 debug('pipe', pipe, options.path);
884 this._handle = pipe ? new Pipe() : new TCP();
885 initSocketHandle(this);
888 if (typeof cb === 'function') {
889 self.once('connect', cb);
894 self._connecting = true;
895 self.writable = true;
898 connect(self, options.path);
901 lookupAndConnect(self, options);
907 function lookupAndConnect(self, options) {
908 const dns = require('dns');
909 var host = options.host || 'localhost';
910 var port = options.port;
911 var localAddress = options.localAddress;
912 var localPort = options.localPort;
914 if (localAddress && !exports.isIP(localAddress))
915 throw new TypeError('localAddress must be a valid IP: ' + localAddress);
917 if (localPort && typeof localPort !== 'number')
918 throw new TypeError('localPort should be a number: ' + localPort);
920 if (typeof port !== 'undefined') {
921 if (typeof port !== 'number' && typeof port !== 'string')
922 throw new TypeError('port should be a number or string: ' + port);
923 if (!isLegalPort(port))
924 throw new RangeError('port should be >= 0 and < 65536: ' + port);
928 // If host is an IP, skip performing a lookup
929 var addressType = exports.isIP(host);
931 process.nextTick(function() {
932 if (self._connecting)
933 connect(self, host, port, addressType, localAddress, localPort);
938 if (options.lookup && typeof options.lookup !== 'function')
939 throw new TypeError('options.lookup should be a function.');
942 family: options.family,
946 if (dnsopts.family !== 4 && dnsopts.family !== 6) {
947 dnsopts.hints = dns.ADDRCONFIG;
948 // The AI_V4MAPPED hint is not supported on FreeBSD or Android,
949 // and getaddrinfo returns EAI_BADFLAGS. However, it seems to be
950 // supported on most other systems. See
951 // http://lists.freebsd.org/pipermail/freebsd-bugs/2008-February/028260.html
952 // for more information on the lack of support for FreeBSD.
953 if (process.platform !== 'freebsd' && process.platform !== 'android')
954 dnsopts.hints |= dns.V4MAPPED;
957 debug('connect: find host ' + host);
958 debug('connect: dns options', dnsopts);
960 var lookup = options.lookup || dns.lookup;
961 lookup(host, dnsopts, function(err, ip, addressType) {
962 self.emit('lookup', err, ip, addressType);
964 // It's possible we were destroyed while looking this up.
965 // XXX it would be great if we could cancel the promise returned by
967 if (!self._connecting) return;
970 // net.createConnection() creates a net.Socket object and
971 // immediately calls net.Socket.connect() on it (that's us).
972 // There are no event listeners registered yet so defer the
973 // error event to the next tick.
974 err.host = options.host;
975 err.port = options.port;
976 err.message = err.message + ' ' + options.host + ':' + options.port;
977 process.nextTick(connectErrorNT, self, err);
991 function connectErrorNT(self, err) {
992 self.emit('error', err);
997 Socket.prototype.ref = function() {
999 this.once('connect', this.ref);
1009 Socket.prototype.unref = function() {
1010 if (!this._handle) {
1011 this.once('connect', this.unref);
1015 this._handle.unref();
1021 function afterConnect(status, handle, req, readable, writable) {
1022 var self = handle.owner;
1024 // callback may come after call to destroy
1025 if (self.destroyed) {
1029 // Update handle if it was wrapped
1030 // TODO(indutny): assert that the handle is actually an ancestor of old one
1031 handle = self._handle;
1033 debug('afterConnect');
1035 assert.ok(self._connecting);
1036 self._connecting = false;
1037 self._sockname = null;
1040 self.readable = readable;
1041 self.writable = writable;
1044 self.emit('connect');
1046 // start the first read, or get an immediate EOF.
1047 // this doesn't actually consume any bytes, because len=0.
1048 if (readable && !self.isPaused())
1052 self._connecting = false;
1054 if (req.localAddress && req.localPort) {
1055 details = req.localAddress + ':' + req.localPort;
1057 var ex = exceptionWithHostPort(status,
1063 ex.localAddress = req.localAddress;
1064 ex.localPort = req.localPort;
1071 function Server(options, connectionListener) {
1072 if (!(this instanceof Server))
1073 return new Server(options, connectionListener);
1075 EventEmitter.call(this);
1079 if (typeof options === 'function') {
1080 connectionListener = options;
1082 self.on('connection', connectionListener);
1084 options = options || {};
1086 if (typeof connectionListener === 'function') {
1087 self.on('connection', connectionListener);
1091 this._connections = 0;
1093 Object.defineProperty(this, 'connections', {
1094 get: internalUtil.deprecate(function() {
1096 if (self._usingSlaves) {
1099 return self._connections;
1100 }, 'Server.connections property is deprecated. ' +
1101 'Use Server.getConnections method instead.'),
1102 set: internalUtil.deprecate(function(val) {
1103 return (self._connections = val);
1104 }, 'Server.connections property is deprecated.'),
1105 configurable: true, enumerable: false
1108 this._handle = null;
1109 this._usingSlaves = false;
1111 this._unref = false;
1113 this.allowHalfOpen = options.allowHalfOpen || false;
1114 this.pauseOnConnect = !!options.pauseOnConnect;
1116 util.inherits(Server, EventEmitter);
1117 exports.Server = Server;
1120 function toNumber(x) { return (x = Number(x)) >= 0 ? x : false; }
1122 function _listen(handle, backlog) {
1123 // Use a backlog of 512 entries. We pass 511 to the listen() call because
1124 // the kernel does: backlogsize = roundup_pow_of_two(backlogsize + 1);
1125 // which will thus give us a backlog of 512 entries.
1126 return handle.listen(backlog || 511);
1129 function createServerHandle(address, port, addressType, fd) {
1131 // assign handle in listen, and clean up if bind or listen fails
1135 if (typeof fd === 'number' && fd >= 0) {
1137 handle = createHandle(fd);
1140 // Not a fd we can listen on. This will trigger an error.
1141 debug('listen invalid fd=' + fd + ': ' + e.message);
1142 return uv.UV_EINVAL;
1145 handle.readable = true;
1146 handle.writable = true;
1147 assert(!address && !port);
1148 } else if (port === -1 && addressType === -1) {
1149 handle = new Pipe();
1150 if (process.platform === 'win32') {
1151 var instances = parseInt(process.env.NODE_PENDING_PIPE_INSTANCES);
1152 if (!isNaN(instances)) {
1153 handle.setPendingInstances(instances);
1161 if (address || port || isTCP) {
1162 debug('bind to ' + (address || 'anycast'));
1164 // Try binding to ipv6 first
1165 err = handle.bind6('::', port);
1169 return createServerHandle('0.0.0.0', port);
1171 } else if (addressType === 6) {
1172 err = handle.bind6(address, port);
1174 err = handle.bind(address, port);
1185 exports._createServerHandle = createServerHandle;
1188 Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
1189 debug('listen2', address, port, addressType, backlog, fd);
1192 // If there is not yet a handle, we need to create one and bind.
1193 // In the case of a server sent via IPC, we don't need to do this.
1195 debug('_listen2: have a handle already');
1197 debug('_listen2: create a handle');
1201 if (!address && typeof fd !== 'number') {
1202 rval = createServerHandle('::', port, 6, fd);
1204 if (typeof rval === 'number') {
1206 address = '0.0.0.0';
1215 rval = createServerHandle(address, port, addressType, fd);
1217 if (typeof rval === 'number') {
1218 var error = exceptionWithHostPort(rval, 'listen', address, port);
1219 process.nextTick(emitErrorNT, self, error);
1222 self._handle = rval;
1225 self._handle.onconnection = onconnection;
1226 self._handle.owner = self;
1228 var err = _listen(self._handle, backlog);
1231 var ex = exceptionWithHostPort(err, 'listen', address, port);
1232 self._handle.close();
1233 self._handle = null;
1234 process.nextTick(emitErrorNT, self, ex);
1238 // generate connection key, this should be unique to the connection
1239 this._connectionKey = addressType + ':' + address + ':' + port;
1241 // unref the handle if the server was unref'ed prior to listening
1245 process.nextTick(emitListeningNT, self);
1249 function emitErrorNT(self, err) {
1250 self.emit('error', err);
1254 function emitListeningNT(self) {
1255 // ensure handle hasn't closed
1257 self.emit('listening');
1261 function listen(self, address, port, addressType, backlog, fd, exclusive) {
1262 exclusive = !!exclusive;
1264 if (!cluster) cluster = require('cluster');
1266 if (cluster.isMaster || exclusive) {
1267 self._listen2(address, port, addressType, backlog, fd);
1271 cluster._getServer(self, {
1274 addressType: addressType,
1279 function cb(err, handle) {
1280 // EADDRINUSE may not be reported until we call listen(). To complicate
1281 // matters, a failed bind() followed by listen() will implicitly bind to
1282 // a random port. Ergo, check that the socket is bound to the expected
1283 // port before calling listen().
1285 // FIXME(bnoordhuis) Doesn't work for pipe handles, they don't have a
1286 // getsockname() method. Non-issue for now, the cluster module doesn't
1287 // really support pipes anyway.
1288 if (err === 0 && port > 0 && handle.getsockname) {
1290 err = handle.getsockname(out);
1291 if (err === 0 && port !== out.port)
1292 err = uv.UV_EADDRINUSE;
1296 var ex = exceptionWithHostPort(err, 'bind', address, port);
1297 return self.emit('error', ex);
1300 self._handle = handle;
1301 self._listen2(address, port, addressType, backlog, fd);
1306 Server.prototype.listen = function() {
1309 var lastArg = arguments[arguments.length - 1];
1310 if (typeof lastArg === 'function') {
1311 self.once('listening', lastArg);
1314 var port = toNumber(arguments[0]);
1316 // The third optional argument is the backlog size.
1317 // When the ip is omitted it can be the second argument.
1318 var backlog = toNumber(arguments[1]) || toNumber(arguments[2]);
1320 if (arguments.length === 0 || typeof arguments[0] === 'function') {
1321 // Bind to a random port.
1322 listen(self, null, 0, null, backlog);
1323 } else if (arguments[0] !== null && typeof arguments[0] === 'object') {
1324 var h = arguments[0];
1325 h = h._handle || h.handle || h;
1327 if (h instanceof TCP) {
1329 listen(self, null, -1, -1, backlog);
1330 } else if (typeof h.fd === 'number' && h.fd >= 0) {
1331 listen(self, null, null, null, backlog, h.fd);
1333 // The first argument is a configuration object
1335 backlog = h.backlog;
1337 if (typeof h.port === 'number' || typeof h.port === 'string' ||
1338 (typeof h.port === 'undefined' && 'port' in h)) {
1339 // Undefined is interpreted as zero (random port) for consistency
1340 // with net.connect().
1341 if (typeof h.port !== 'undefined' && !isLegalPort(h.port))
1342 throw new RangeError('port should be >= 0 and < 65536: ' + h.port);
1344 listenAfterLookup(h.port | 0, h.host, backlog, h.exclusive);
1346 listen(self, null, h.port | 0, 4, backlog, undefined, h.exclusive);
1347 } else if (h.path && isPipeName(h.path)) {
1348 const pipeName = self._pipeName = h.path;
1349 listen(self, pipeName, -1, -1, backlog, undefined, h.exclusive);
1351 throw new Error('Invalid listen argument: ' + h);
1354 } else if (isPipeName(arguments[0])) {
1355 // UNIX socket or Windows pipe.
1356 const pipeName = self._pipeName = arguments[0];
1357 listen(self, pipeName, -1, -1, backlog);
1359 } else if (arguments[1] === undefined ||
1360 typeof arguments[1] === 'function' ||
1361 typeof arguments[1] === 'number') {
1362 // The first argument is the port, no IP given.
1363 listen(self, null, port, 4, backlog);
1366 // The first argument is the port, the second an IP.
1367 listenAfterLookup(port, arguments[1], backlog);
1370 function listenAfterLookup(port, address, backlog, exclusive) {
1371 require('dns').lookup(address, function(err, ip, addressType) {
1373 self.emit('error', err);
1375 addressType = ip ? addressType : 4;
1376 listen(self, ip, port, addressType, backlog, undefined, exclusive);
1384 Server.prototype.address = function() {
1385 if (this._handle && this._handle.getsockname) {
1387 this._handle.getsockname(out);
1388 // TODO(bnoordhuis) Check err and throw?
1390 } else if (this._pipeName) {
1391 return this._pipeName;
1397 function onconnection(err, clientHandle) {
1399 var self = handle.owner;
1401 debug('onconnection');
1404 self.emit('error', errnoException(err, 'accept'));
1408 if (self.maxConnections && self._connections >= self.maxConnections) {
1409 clientHandle.close();
1413 var socket = new Socket({
1414 handle: clientHandle,
1415 allowHalfOpen: self.allowHalfOpen,
1416 pauseOnCreate: self.pauseOnConnect
1418 socket.readable = socket.writable = true;
1421 self._connections++;
1422 socket.server = self;
1423 socket._server = self;
1425 DTRACE_NET_SERVER_CONNECTION(socket);
1426 LTTNG_NET_SERVER_CONNECTION(socket);
1427 COUNTER_NET_SERVER_CONNECTION(socket);
1428 self.emit('connection', socket);
1432 Server.prototype.getConnections = function(cb) {
1433 function end(err, connections) {
1434 process.nextTick(cb, err, connections);
1437 if (!this._usingSlaves) {
1438 return end(null, this._connections);
1442 var left = this._slaves.length;
1443 var total = this._connections;
1445 function oncount(err, count) {
1452 if (--left === 0) return end(null, total);
1455 this._slaves.forEach(function(slave) {
1456 slave.getConnections(oncount);
1461 Server.prototype.close = function(cb) {
1462 function onSlaveClose() {
1463 if (--left !== 0) return;
1465 self._connections = 0;
1466 self._emitCloseIfDrained();
1469 if (typeof cb === 'function') {
1470 if (!this._handle) {
1471 this.once('close', function() {
1472 cb(new Error('Not running'));
1475 this.once('close', cb);
1480 this._handle.close();
1481 this._handle = null;
1484 if (this._usingSlaves) {
1486 var left = this._slaves.length;
1488 // Increment connections to be sure that, even if all sockets will be closed
1489 // during polling of slaves, `close` event will be emitted only once.
1490 this._connections++;
1493 this._slaves.forEach(function(slave) {
1494 slave.close(onSlaveClose);
1497 this._emitCloseIfDrained();
1503 Server.prototype._emitCloseIfDrained = function() {
1504 debug('SERVER _emitCloseIfDrained');
1507 if (self._handle || self._connections) {
1508 debug('SERVER handle? %j connections? %d',
1509 !!self._handle, self._connections);
1513 process.nextTick(emitCloseNT, self);
1517 function emitCloseNT(self) {
1518 debug('SERVER: emit close');
1523 Server.prototype.listenFD = internalUtil.deprecate(function(fd, type) {
1524 return this.listen({ fd: fd });
1525 }, 'Server.listenFD is deprecated. Use Server.listen({fd: <number>}) instead.');
1527 Server.prototype._setupSlave = function(socketList) {
1528 this._usingSlaves = true;
1529 this._slaves.push(socketList);
1532 Server.prototype.ref = function() {
1533 this._unref = false;
1541 Server.prototype.unref = function() {
1545 this._handle.unref();
1551 exports.isIP = cares.isIP;
1554 exports.isIPv4 = function(input) {
1555 return exports.isIP(input) === 4;
1559 exports.isIPv6 = function(input) {
1560 return exports.isIP(input) === 6;
1564 if (process.platform === 'win32') {
1565 var simultaneousAccepts;
1567 exports._setSimultaneousAccepts = function(handle) {
1568 if (handle === undefined) {
1572 if (simultaneousAccepts === undefined) {
1573 simultaneousAccepts = (process.env.NODE_MANY_ACCEPTS &&
1574 process.env.NODE_MANY_ACCEPTS !== '0');
1577 if (handle._simultaneousAccepts !== simultaneousAccepts) {
1578 handle.setSimultaneousAccepts(simultaneousAccepts);
1579 handle._simultaneousAccepts = simultaneousAccepts;
1583 exports._setSimultaneousAccepts = function(handle) {};