7a612096ab45d03f6d775ec503f13bf4bdc3fe48
[platform/upstream/nodejs.git] / lib / net.js
1 'use strict';
2
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 assert = require('assert');
9 const cares = process.binding('cares_wrap');
10 const uv = process.binding('uv');
11
12 const Buffer = require('buffer').Buffer;
13 const TTYWrap = process.binding('tty_wrap');
14 const TCP = process.binding('tcp_wrap').TCP;
15 const Pipe = process.binding('pipe_wrap').Pipe;
16 const TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap;
17 const PipeConnectWrap = process.binding('pipe_wrap').PipeConnectWrap;
18 const ShutdownWrap = process.binding('stream_wrap').ShutdownWrap;
19 const WriteWrap = process.binding('stream_wrap').WriteWrap;
20
21
22 var cluster;
23 const errnoException = util._errnoException;
24 const exceptionWithHostPort = util._exceptionWithHostPort;
25
26 function noop() {}
27
28 function createHandle(fd) {
29   var type = TTYWrap.guessHandleType(fd);
30   if (type === 'PIPE') return new Pipe();
31   if (type === 'TCP') return new TCP();
32   throw new TypeError('Unsupported fd type: ' + type);
33 }
34
35
36 const debug = util.debuglog('net');
37
38 function isPipeName(s) {
39   return typeof s === 'string' && toNumber(s) === false;
40 }
41
42 exports.createServer = function(options, connectionListener) {
43   return new Server(options, connectionListener);
44 };
45
46
47 // Target API:
48 //
49 // var s = net.connect({port: 80, host: 'google.com'}, function() {
50 //   ...
51 // });
52 //
53 // There are various forms:
54 //
55 // connect(options, [cb])
56 // connect(port, [host], [cb])
57 // connect(path, [cb]);
58 //
59 exports.connect = exports.createConnection = function() {
60   var args = normalizeConnectArgs(arguments);
61   debug('createConnection', args);
62   var s = new Socket(args[0]);
63   return Socket.prototype.connect.apply(s, args);
64 };
65
66 // Returns an array [options] or [options, cb]
67 // It is the same as the argument of Socket.prototype.connect().
68 function normalizeConnectArgs(args) {
69   var options = {};
70
71   if (args[0] !== null && typeof args[0] === 'object') {
72     // connect(options, [cb])
73     options = args[0];
74   } else if (isPipeName(args[0])) {
75     // connect(path, [cb]);
76     options.path = args[0];
77   } else {
78     // connect(port, [host], [cb])
79     options.port = args[0];
80     if (typeof args[1] === 'string') {
81       options.host = args[1];
82     }
83   }
84
85   var cb = args[args.length - 1];
86   return typeof cb === 'function' ? [options, cb] : [options];
87 }
88 exports._normalizeConnectArgs = normalizeConnectArgs;
89
90
91 // called when creating new Socket, or when re-using a closed Socket
92 function initSocketHandle(self) {
93   self.destroyed = false;
94   self.bytesRead = 0;
95   self._bytesDispatched = 0;
96   self._sockname = null;
97
98   // Handle creation may be deferred to bind() or connect() time.
99   if (self._handle) {
100     self._handle.owner = self;
101     self._handle.onread = onread;
102
103     // If handle doesn't support writev - neither do we
104     if (!self._handle.writev)
105       self._writev = null;
106   }
107 }
108
109 function Socket(options) {
110   if (!(this instanceof Socket)) return new Socket(options);
111
112   this._connecting = false;
113   this._hadError = false;
114   this._handle = null;
115   this._parent = null;
116   this._host = null;
117
118   if (typeof options === 'number')
119     options = { fd: options }; // Legacy interface.
120   else if (options === undefined)
121     options = {};
122
123   stream.Duplex.call(this, options);
124
125   if (options.handle) {
126     this._handle = options.handle; // private
127   } else if (options.fd !== undefined) {
128     this._handle = createHandle(options.fd);
129     this._handle.open(options.fd);
130     if ((options.fd == 1 || options.fd == 2) &&
131         (this._handle instanceof Pipe) &&
132         process.platform === 'win32') {
133       // Make stdout and stderr blocking on Windows
134       var err = this._handle.setBlocking(true);
135       if (err)
136         throw errnoException(err, 'setBlocking');
137     }
138     this.readable = options.readable !== false;
139     this.writable = options.writable !== false;
140   } else {
141     // these will be set once there is a connection
142     this.readable = this.writable = false;
143   }
144
145   // shut down the socket when we're finished with it.
146   this.on('finish', onSocketFinish);
147   this.on('_socketEnd', onSocketEnd);
148
149   initSocketHandle(this);
150
151   this._pendingData = null;
152   this._pendingEncoding = '';
153
154   // handle strings directly
155   this._writableState.decodeStrings = false;
156
157   // default to *not* allowing half open sockets
158   this.allowHalfOpen = options && options.allowHalfOpen || false;
159
160   // if we have a handle, then start the flow of data into the
161   // buffer.  if not, then this will happen when we connect
162   if (this._handle && options.readable !== false) {
163     if (options.pauseOnCreate) {
164       // stop the handle from reading and pause the stream
165       this._handle.reading = false;
166       this._handle.readStop();
167       this._readableState.flowing = false;
168     } else {
169       this.read(0);
170     }
171   }
172 }
173 util.inherits(Socket, stream.Duplex);
174
175 Socket.prototype._unrefTimer = function unrefTimer() {
176   for (var s = this; s !== null; s = s._parent)
177     timers._unrefActive(s);
178 };
179
180 // the user has called .end(), and all the bytes have been
181 // sent out to the other side.
182 // If allowHalfOpen is false, or if the readable side has
183 // ended already, then destroy.
184 // If allowHalfOpen is true, then we need to do a shutdown,
185 // so that only the writable side will be cleaned up.
186 function onSocketFinish() {
187   // If still connecting - defer handling 'finish' until 'connect' will happen
188   if (this._connecting) {
189     debug('osF: not yet connected');
190     return this.once('connect', onSocketFinish);
191   }
192
193   debug('onSocketFinish');
194   if (!this.readable || this._readableState.ended) {
195     debug('oSF: ended, destroy', this._readableState);
196     return this.destroy();
197   }
198
199   debug('oSF: not ended, call shutdown()');
200
201   // otherwise, just shutdown, or destroy() if not possible
202   if (!this._handle || !this._handle.shutdown)
203     return this.destroy();
204
205   var req = new ShutdownWrap();
206   req.oncomplete = afterShutdown;
207   req.handle = this._handle;
208   var err = this._handle.shutdown(req);
209
210   if (err)
211     return this._destroy(errnoException(err, 'shutdown'));
212 }
213
214
215 function afterShutdown(status, handle, req) {
216   var self = handle.owner;
217
218   debug('afterShutdown destroyed=%j', self.destroyed,
219         self._readableState);
220
221   // callback may come after call to destroy.
222   if (self.destroyed)
223     return;
224
225   if (self._readableState.ended) {
226     debug('readableState ended, destroying');
227     self.destroy();
228   } else {
229     self.once('_socketEnd', self.destroy);
230   }
231 }
232
233 // the EOF has been received, and no more bytes are coming.
234 // if the writable side has ended already, then clean everything
235 // up.
236 function onSocketEnd() {
237   // XXX Should not have to do as much crap in this function.
238   // ended should already be true, since this is called *after*
239   // the EOF errno and onread has eof'ed
240   debug('onSocketEnd', this._readableState);
241   this._readableState.ended = true;
242   if (this._readableState.endEmitted) {
243     this.readable = false;
244     maybeDestroy(this);
245   } else {
246     this.once('end', function() {
247       this.readable = false;
248       maybeDestroy(this);
249     });
250     this.read(0);
251   }
252
253   if (!this.allowHalfOpen) {
254     this.write = writeAfterFIN;
255     this.destroySoon();
256   }
257 }
258
259 // Provide a better error message when we call end() as a result
260 // of the other side sending a FIN.  The standard 'write after end'
261 // is overly vague, and makes it seem like the user's code is to blame.
262 function writeAfterFIN(chunk, encoding, cb) {
263   if (typeof encoding === 'function') {
264     cb = encoding;
265     encoding = null;
266   }
267
268   var er = new Error('This socket has been ended by the other party');
269   er.code = 'EPIPE';
270   var self = this;
271   // TODO: defer error events consistently everywhere, not just the cb
272   self.emit('error', er);
273   if (typeof cb === 'function') {
274     process.nextTick(cb, er);
275   }
276 }
277
278 exports.Socket = Socket;
279 exports.Stream = Socket; // Legacy naming.
280
281 Socket.prototype.read = function(n) {
282   if (n === 0)
283     return stream.Readable.prototype.read.call(this, n);
284
285   this.read = stream.Readable.prototype.read;
286   this._consuming = true;
287   return this.read(n);
288 };
289
290
291 Socket.prototype.listen = function() {
292   debug('socket.listen');
293   var self = this;
294   self.on('connection', arguments[0]);
295   listen(self, null, null, null);
296 };
297
298
299 Socket.prototype.setTimeout = function(msecs, callback) {
300   if (msecs === 0) {
301     timers.unenroll(this);
302     if (callback) {
303       this.removeListener('timeout', callback);
304     }
305   } else {
306     timers.enroll(this, msecs);
307     timers._unrefActive(this);
308     if (callback) {
309       this.once('timeout', callback);
310     }
311   }
312   return this;
313 };
314
315
316 Socket.prototype._onTimeout = function() {
317   debug('_onTimeout');
318   this.emit('timeout');
319 };
320
321
322 Socket.prototype.setNoDelay = function(enable) {
323   if (!this._handle) {
324     this.once('connect',
325               enable ? this.setNoDelay : () => this.setNoDelay(enable));
326     return this;
327   }
328
329   // backwards compatibility: assume true when `enable` is omitted
330   if (this._handle.setNoDelay)
331     this._handle.setNoDelay(enable === undefined ? true : !!enable);
332
333   return this;
334 };
335
336
337 Socket.prototype.setKeepAlive = function(setting, msecs) {
338   if (!this._handle) {
339     this.once('connect', () => this.setKeepAlive(setting, msecs));
340     return this;
341   }
342
343   if (this._handle.setKeepAlive)
344     this._handle.setKeepAlive(setting, ~~(msecs / 1000));
345
346   return this;
347 };
348
349
350 Socket.prototype.address = function() {
351   return this._getsockname();
352 };
353
354
355 Object.defineProperty(Socket.prototype, 'readyState', {
356   get: function() {
357     if (this._connecting) {
358       return 'opening';
359     } else if (this.readable && this.writable) {
360       return 'open';
361     } else if (this.readable && !this.writable) {
362       return 'readOnly';
363     } else if (!this.readable && this.writable) {
364       return 'writeOnly';
365     } else {
366       return 'closed';
367     }
368   }
369 });
370
371
372 Object.defineProperty(Socket.prototype, 'bufferSize', {
373   get: function() {
374     if (this._handle) {
375       return this._handle.writeQueueSize + this._writableState.length;
376     }
377   }
378 });
379
380
381 // Just call handle.readStart until we have enough in the buffer
382 Socket.prototype._read = function(n) {
383   debug('_read');
384
385   if (this._connecting || !this._handle) {
386     debug('_read wait for connection');
387     this.once('connect', () => this._read(n));
388   } else if (!this._handle.reading) {
389     // not already reading, start the flow
390     debug('Socket._read readStart');
391     this._handle.reading = true;
392     var err = this._handle.readStart();
393     if (err)
394       this._destroy(errnoException(err, 'read'));
395   }
396 };
397
398
399 Socket.prototype.end = function(data, encoding) {
400   stream.Duplex.prototype.end.call(this, data, encoding);
401   this.writable = false;
402   DTRACE_NET_STREAM_END(this);
403   LTTNG_NET_STREAM_END(this);
404
405   // just in case we're waiting for an EOF.
406   if (this.readable && !this._readableState.endEmitted)
407     this.read(0);
408   else
409     maybeDestroy(this);
410 };
411
412
413 // Call whenever we set writable=false or readable=false
414 function maybeDestroy(socket) {
415   if (!socket.readable &&
416       !socket.writable &&
417       !socket.destroyed &&
418       !socket._connecting &&
419       !socket._writableState.length) {
420     socket.destroy();
421   }
422 }
423
424
425 Socket.prototype.destroySoon = function() {
426   if (this.writable)
427     this.end();
428
429   if (this._writableState.finished)
430     this.destroy();
431   else
432     this.once('finish', this.destroy);
433 };
434
435
436 Socket.prototype._destroy = function(exception, cb) {
437   debug('destroy');
438
439   var self = this;
440
441   function fireErrorCallbacks() {
442     if (cb) cb(exception);
443     if (exception && !self._writableState.errorEmitted) {
444       process.nextTick(emitErrorNT, self, exception);
445       self._writableState.errorEmitted = true;
446     }
447   }
448
449   if (this.destroyed) {
450     debug('already destroyed, fire error callbacks');
451     fireErrorCallbacks();
452     return;
453   }
454
455   self._connecting = false;
456
457   this.readable = this.writable = false;
458
459   for (var s = this; s !== null; s = s._parent)
460     timers.unenroll(s);
461
462   debug('close');
463   if (this._handle) {
464     if (this !== process.stderr)
465       debug('close handle');
466     var isException = exception ? true : false;
467     this._handle.close(function() {
468       debug('emit close');
469       self.emit('close', isException);
470     });
471     this._handle.onread = noop;
472     this._handle = null;
473     this._sockname = null;
474   }
475
476   // we set destroyed to true before firing error callbacks in order
477   // to make it re-entrance safe in case Socket.prototype.destroy()
478   // is called within callbacks
479   this.destroyed = true;
480   fireErrorCallbacks();
481
482   if (this.server) {
483     COUNTER_NET_SERVER_CONNECTION_CLOSE(this);
484     debug('has server');
485     this.server._connections--;
486     if (this.server._emitCloseIfDrained) {
487       this.server._emitCloseIfDrained();
488     }
489   }
490 };
491
492
493 Socket.prototype.destroy = function(exception) {
494   debug('destroy', exception);
495   this._destroy(exception);
496 };
497
498
499 // This function is called whenever the handle gets a
500 // buffer, or when there's an error reading.
501 function onread(nread, buffer) {
502   var handle = this;
503   var self = handle.owner;
504   assert(handle === self._handle, 'handle != self._handle');
505
506   self._unrefTimer();
507
508   debug('onread', nread);
509
510   if (nread > 0) {
511     debug('got data');
512
513     // read success.
514     // In theory (and in practice) calling readStop right now
515     // will prevent this from being called again until _read() gets
516     // called again.
517
518     // if it's not enough data, we'll just call handle.readStart()
519     // again right away.
520     self.bytesRead += nread;
521
522     // Optimization: emit the original buffer with end points
523     var ret = self.push(buffer);
524
525     if (handle.reading && !ret) {
526       handle.reading = false;
527       debug('readStop');
528       var err = handle.readStop();
529       if (err)
530         self._destroy(errnoException(err, 'read'));
531     }
532     return;
533   }
534
535   // if we didn't get any bytes, that doesn't necessarily mean EOF.
536   // wait for the next one.
537   if (nread === 0) {
538     debug('not any data, keep waiting');
539     return;
540   }
541
542   // Error, possibly EOF.
543   if (nread !== uv.UV_EOF) {
544     return self._destroy(errnoException(nread, 'read'));
545   }
546
547   debug('EOF');
548
549   if (self._readableState.length === 0) {
550     self.readable = false;
551     maybeDestroy(self);
552   }
553
554   // push a null to signal the end of data.
555   self.push(null);
556
557   // internal end event so that we know that the actual socket
558   // is no longer readable, and we can start the shutdown
559   // procedure. No need to wait for all the data to be consumed.
560   self.emit('_socketEnd');
561 }
562
563
564 Socket.prototype._getpeername = function() {
565   if (!this._peername) {
566     if (!this._handle || !this._handle.getpeername) {
567       return {};
568     }
569     var out = {};
570     var err = this._handle.getpeername(out);
571     if (err) return {};  // FIXME(bnoordhuis) Throw?
572     this._peername = out;
573   }
574   return this._peername;
575 };
576
577
578 Socket.prototype.__defineGetter__('remoteAddress', function() {
579   return this._getpeername().address;
580 });
581
582 Socket.prototype.__defineGetter__('remoteFamily', function() {
583   return this._getpeername().family;
584 });
585
586 Socket.prototype.__defineGetter__('remotePort', function() {
587   return this._getpeername().port;
588 });
589
590
591 Socket.prototype._getsockname = function() {
592   if (!this._handle || !this._handle.getsockname) {
593     return {};
594   }
595   if (!this._sockname) {
596     var out = {};
597     var err = this._handle.getsockname(out);
598     if (err) return {};  // FIXME(bnoordhuis) Throw?
599     this._sockname = out;
600   }
601   return this._sockname;
602 };
603
604
605 Socket.prototype.__defineGetter__('localAddress', function() {
606   return this._getsockname().address;
607 });
608
609
610 Socket.prototype.__defineGetter__('localPort', function() {
611   return this._getsockname().port;
612 });
613
614
615 Socket.prototype.write = function(chunk, encoding, cb) {
616   if (typeof chunk !== 'string' && !(chunk instanceof Buffer))
617     throw new TypeError('invalid data');
618   return stream.Duplex.prototype.write.apply(this, arguments);
619 };
620
621
622 Socket.prototype._writeGeneric = function(writev, data, encoding, cb) {
623   // If we are still connecting, then buffer this for later.
624   // The Writable logic will buffer up any more writes while
625   // waiting for this one to be done.
626   if (this._connecting) {
627     this._pendingData = data;
628     this._pendingEncoding = encoding;
629     this.once('connect', function() {
630       this._writeGeneric(writev, data, encoding, cb);
631     });
632     return;
633   }
634   this._pendingData = null;
635   this._pendingEncoding = '';
636
637   this._unrefTimer();
638
639   if (!this._handle) {
640     this._destroy(new Error('This socket is closed.'), cb);
641     return false;
642   }
643
644   var req = new WriteWrap();
645   req.handle = this._handle;
646   req.oncomplete = afterWrite;
647   req.async = false;
648   var err;
649
650   if (writev) {
651     var chunks = new Array(data.length << 1);
652     for (var i = 0; i < data.length; i++) {
653       var entry = data[i];
654       var chunk = entry.chunk;
655       var enc = entry.encoding;
656       chunks[i * 2] = chunk;
657       chunks[i * 2 + 1] = enc;
658     }
659     err = this._handle.writev(req, chunks);
660
661     // Retain chunks
662     if (err === 0) req._chunks = chunks;
663   } else {
664     var enc;
665     if (data instanceof Buffer) {
666       req.buffer = data;  // Keep reference alive.
667       enc = 'buffer';
668     } else {
669       enc = encoding;
670     }
671     err = createWriteReq(req, this._handle, data, enc);
672   }
673
674   if (err)
675     return this._destroy(errnoException(err, 'write', req.error), cb);
676
677   this._bytesDispatched += req.bytes;
678
679   // If it was entirely flushed, we can write some more right now.
680   // However, if more is left in the queue, then wait until that clears.
681   if (req.async && this._handle.writeQueueSize != 0)
682     req.cb = cb;
683   else
684     cb();
685 };
686
687
688 Socket.prototype._writev = function(chunks, cb) {
689   this._writeGeneric(true, chunks, '', cb);
690 };
691
692
693 Socket.prototype._write = function(data, encoding, cb) {
694   this._writeGeneric(false, data, encoding, cb);
695 };
696
697 function createWriteReq(req, handle, data, encoding) {
698   switch (encoding) {
699     case 'binary':
700       return handle.writeBinaryString(req, data);
701
702     case 'buffer':
703       return handle.writeBuffer(req, data);
704
705     case 'utf8':
706     case 'utf-8':
707       return handle.writeUtf8String(req, data);
708
709     case 'ascii':
710       return handle.writeAsciiString(req, data);
711
712     case 'ucs2':
713     case 'ucs-2':
714     case 'utf16le':
715     case 'utf-16le':
716       return handle.writeUcs2String(req, data);
717
718     default:
719       return handle.writeBuffer(req, new Buffer(data, encoding));
720   }
721 }
722
723
724 Socket.prototype.__defineGetter__('bytesWritten', function() {
725   var bytes = this._bytesDispatched;
726   const state = this._writableState;
727   const data = this._pendingData;
728   const encoding = this._pendingEncoding;
729
730   if (!state)
731     return undefined;
732
733   state.getBuffer().forEach(function(el) {
734     if (el.chunk instanceof Buffer)
735       bytes += el.chunk.length;
736     else
737       bytes += Buffer.byteLength(el.chunk, el.encoding);
738   });
739
740   if (data) {
741     if (data instanceof Buffer)
742       bytes += data.length;
743     else
744       bytes += Buffer.byteLength(data, encoding);
745   }
746
747   return bytes;
748 });
749
750
751 function afterWrite(status, handle, req, err) {
752   var self = handle.owner;
753   if (self !== process.stderr && self !== process.stdout)
754     debug('afterWrite', status);
755
756   // callback may come after call to destroy.
757   if (self.destroyed) {
758     debug('afterWrite destroyed');
759     return;
760   }
761
762   if (status < 0) {
763     var ex = exceptionWithHostPort(status, 'write', req.address, req.port);
764     debug('write failure', ex);
765     self._destroy(ex, req.cb);
766     return;
767   }
768
769   self._unrefTimer();
770
771   if (self !== process.stderr && self !== process.stdout)
772     debug('afterWrite call cb');
773
774   if (req.cb)
775     req.cb.call(self);
776 }
777
778
779 function connect(self, address, port, addressType, localAddress, localPort) {
780   // TODO return promise from Socket.prototype.connect which
781   // wraps _connectReq.
782
783   assert.ok(self._connecting);
784
785   var err;
786
787   if (localAddress || localPort) {
788     var bind;
789
790     if (addressType === 4) {
791       localAddress = localAddress || '0.0.0.0';
792       bind = self._handle.bind;
793     } else if (addressType === 6) {
794       localAddress = localAddress || '::';
795       bind = self._handle.bind6;
796     } else {
797       self._destroy(new TypeError('Invalid addressType: ' + addressType));
798       return;
799     }
800
801     debug('binding to localAddress: %s and localPort: %d',
802           localAddress,
803           localPort);
804
805     bind = bind.bind(self._handle);
806     err = bind(localAddress, localPort);
807
808     if (err) {
809       var ex = exceptionWithHostPort(err, 'bind', localAddress, localPort);
810       self._destroy(ex);
811       return;
812     }
813   }
814
815   if (addressType === 6 || addressType === 4) {
816     var req = new TCPConnectWrap();
817     req.oncomplete = afterConnect;
818     req.address = address;
819     req.port = port;
820     req.localAddress = localAddress;
821     req.localPort = localPort;
822
823     if (addressType === 4)
824       err = self._handle.connect(req, address, port);
825     else
826       err = self._handle.connect6(req, address, port);
827
828   } else {
829     var req = new PipeConnectWrap();
830     req.address = address;
831     req.oncomplete = afterConnect;
832     err = self._handle.connect(req, address, afterConnect);
833   }
834
835   if (err) {
836     var sockname = self._getsockname();
837     var details;
838
839     if (sockname) {
840       details = sockname.address + ':' + sockname.port;
841     }
842
843     var ex = exceptionWithHostPort(err, 'connect', address, port, details);
844     self._destroy(ex);
845   }
846 }
847
848
849 // Check that the port number is not NaN when coerced to a number,
850 // is an integer and that it falls within the legal range of port numbers.
851 function isLegalPort(port) {
852   if (typeof port === 'string' && port.trim() === '')
853     return false;
854   return +port === (port >>> 0) && port >= 0 && port <= 0xFFFF;
855 }
856
857
858 Socket.prototype.connect = function(options, cb) {
859   if (this.write !== Socket.prototype.write)
860     this.write = Socket.prototype.write;
861
862   if (options === null || typeof options !== 'object') {
863     // Old API:
864     // connect(port, [host], [cb])
865     // connect(path, [cb]);
866     var args = normalizeConnectArgs(arguments);
867     return Socket.prototype.connect.apply(this, args);
868   }
869
870   if (this.destroyed) {
871     this._readableState.reading = false;
872     this._readableState.ended = false;
873     this._readableState.endEmitted = false;
874     this._writableState.ended = false;
875     this._writableState.ending = false;
876     this._writableState.finished = false;
877     this._writableState.errorEmitted = false;
878     this.destroyed = false;
879     this._handle = null;
880     this._peername = null;
881     this._sockname = null;
882   }
883
884   var self = this;
885   var pipe = !!options.path;
886   debug('pipe', pipe, options.path);
887
888   if (!this._handle) {
889     this._handle = pipe ? new Pipe() : new TCP();
890     initSocketHandle(this);
891   }
892
893   if (typeof cb === 'function') {
894     self.once('connect', cb);
895   }
896
897   this._unrefTimer();
898
899   self._connecting = true;
900   self.writable = true;
901
902   if (pipe) {
903     connect(self, options.path);
904
905   } else {
906     lookupAndConnect(self, options);
907   }
908   return self;
909 };
910
911
912 function lookupAndConnect(self, options) {
913   const dns = require('dns');
914   var host = options.host || 'localhost';
915   var port = options.port;
916   var localAddress = options.localAddress;
917   var localPort = options.localPort;
918
919   if (localAddress && !exports.isIP(localAddress))
920     throw new TypeError('localAddress must be a valid IP: ' + localAddress);
921
922   if (localPort && typeof localPort !== 'number')
923     throw new TypeError('localPort should be a number: ' + localPort);
924
925   if (typeof port !== 'undefined') {
926     if (typeof port !== 'number' && typeof port !== 'string')
927       throw new TypeError('port should be a number or string: ' + port);
928     if (!isLegalPort(port))
929       throw new RangeError('port should be >= 0 and < 65536: ' + port);
930   }
931   port |= 0;
932
933   // If host is an IP, skip performing a lookup
934   var addressType = exports.isIP(host);
935   if (addressType) {
936     process.nextTick(function() {
937       if (self._connecting)
938         connect(self, host, port, addressType, localAddress, localPort);
939     });
940     return;
941   }
942
943   if (options.lookup && typeof options.lookup !== 'function')
944     throw new TypeError('options.lookup should be a function.');
945
946   var dnsopts = {
947     family: options.family,
948     hints: 0
949   };
950
951   if (dnsopts.family !== 4 && dnsopts.family !== 6) {
952     dnsopts.hints = dns.ADDRCONFIG;
953     // The AI_V4MAPPED hint is not supported on FreeBSD or Android,
954     // and getaddrinfo returns EAI_BADFLAGS. However, it seems to be
955     // supported on most other systems. See
956     // http://lists.freebsd.org/pipermail/freebsd-bugs/2008-February/028260.html
957     // for more information on the lack of support for FreeBSD.
958     if (process.platform !== 'freebsd' && process.platform !== 'android')
959       dnsopts.hints |= dns.V4MAPPED;
960   }
961
962   debug('connect: find host ' + host);
963   debug('connect: dns options', dnsopts);
964   self._host = host;
965   var lookup = options.lookup || dns.lookup;
966   lookup(host, dnsopts, function(err, ip, addressType) {
967     self.emit('lookup', err, ip, addressType);
968
969     // It's possible we were destroyed while looking this up.
970     // XXX it would be great if we could cancel the promise returned by
971     // the look up.
972     if (!self._connecting) return;
973
974     if (err) {
975       // net.createConnection() creates a net.Socket object and
976       // immediately calls net.Socket.connect() on it (that's us).
977       // There are no event listeners registered yet so defer the
978       // error event to the next tick.
979       err.host = options.host;
980       err.port = options.port;
981       err.message = err.message + ' ' + options.host + ':' + options.port;
982       process.nextTick(connectErrorNT, self, err);
983     } else {
984       self._unrefTimer();
985       connect(self,
986               ip,
987               port,
988               addressType,
989               localAddress,
990               localPort);
991     }
992   });
993 }
994
995
996 function connectErrorNT(self, err) {
997   self.emit('error', err);
998   self._destroy();
999 }
1000
1001
1002 Socket.prototype.ref = function() {
1003   if (!this._handle) {
1004     this.once('connect', this.ref);
1005     return this;
1006   }
1007
1008   this._handle.ref();
1009
1010   return this;
1011 };
1012
1013
1014 Socket.prototype.unref = function() {
1015   if (!this._handle) {
1016     this.once('connect', this.unref);
1017     return this;
1018   }
1019
1020   this._handle.unref();
1021
1022   return this;
1023 };
1024
1025
1026 function afterConnect(status, handle, req, readable, writable) {
1027   var self = handle.owner;
1028
1029   // callback may come after call to destroy
1030   if (self.destroyed) {
1031     return;
1032   }
1033
1034   // Update handle if it was wrapped
1035   // TODO(indutny): assert that the handle is actually an ancestor of old one
1036   handle = self._handle;
1037
1038   debug('afterConnect');
1039
1040   assert.ok(self._connecting);
1041   self._connecting = false;
1042   self._sockname = null;
1043
1044   if (status == 0) {
1045     self.readable = readable;
1046     self.writable = writable;
1047     self._unrefTimer();
1048
1049     self.emit('connect');
1050
1051     // start the first read, or get an immediate EOF.
1052     // this doesn't actually consume any bytes, because len=0.
1053     if (readable && !self.isPaused())
1054       self.read(0);
1055
1056   } else {
1057     self._connecting = false;
1058     var details;
1059     if (req.localAddress && req.localPort) {
1060       details = req.localAddress + ':' + req.localPort;
1061     }
1062     var ex = exceptionWithHostPort(status,
1063                                    'connect',
1064                                    req.address,
1065                                    req.port,
1066                                    details);
1067     if (details) {
1068       ex.localAddress = req.localAddress;
1069       ex.localPort = req.localPort;
1070     }
1071     self._destroy(ex);
1072   }
1073 }
1074
1075
1076 function Server(options, connectionListener) {
1077   if (!(this instanceof Server))
1078     return new Server(options, connectionListener);
1079
1080   EventEmitter.call(this);
1081
1082   var self = this;
1083
1084   if (typeof options === 'function') {
1085     connectionListener = options;
1086     options = {};
1087     self.on('connection', connectionListener);
1088   } else {
1089     options = options || {};
1090
1091     if (typeof connectionListener === 'function') {
1092       self.on('connection', connectionListener);
1093     }
1094   }
1095
1096   this._connections = 0;
1097
1098   Object.defineProperty(this, 'connections', {
1099     get: internalUtil.deprecate(function() {
1100
1101       if (self._usingSlaves) {
1102         return null;
1103       }
1104       return self._connections;
1105     }, 'Server.connections property is deprecated. ' +
1106        'Use Server.getConnections method instead.'),
1107     set: internalUtil.deprecate(function(val) {
1108       return (self._connections = val);
1109     }, 'Server.connections property is deprecated.'),
1110     configurable: true, enumerable: false
1111   });
1112
1113   this._handle = null;
1114   this._usingSlaves = false;
1115   this._slaves = [];
1116   this._unref = false;
1117
1118   this.allowHalfOpen = options.allowHalfOpen || false;
1119   this.pauseOnConnect = !!options.pauseOnConnect;
1120 }
1121 util.inherits(Server, EventEmitter);
1122 exports.Server = Server;
1123
1124
1125 function toNumber(x) { return (x = Number(x)) >= 0 ? x : false; }
1126
1127 function _listen(handle, backlog) {
1128   // Use a backlog of 512 entries. We pass 511 to the listen() call because
1129   // the kernel does: backlogsize = roundup_pow_of_two(backlogsize + 1);
1130   // which will thus give us a backlog of 512 entries.
1131   return handle.listen(backlog || 511);
1132 }
1133
1134 function createServerHandle(address, port, addressType, fd) {
1135   var err = 0;
1136   // assign handle in listen, and clean up if bind or listen fails
1137   var handle;
1138
1139   var isTCP = false;
1140   if (typeof fd === 'number' && fd >= 0) {
1141     try {
1142       handle = createHandle(fd);
1143     }
1144     catch (e) {
1145       // Not a fd we can listen on.  This will trigger an error.
1146       debug('listen invalid fd=' + fd + ': ' + e.message);
1147       return uv.UV_EINVAL;
1148     }
1149     handle.open(fd);
1150     handle.readable = true;
1151     handle.writable = true;
1152     assert(!address && !port);
1153   } else if (port === -1 && addressType === -1) {
1154     handle = new Pipe();
1155     if (process.platform === 'win32') {
1156       var instances = parseInt(process.env.NODE_PENDING_PIPE_INSTANCES);
1157       if (!isNaN(instances)) {
1158         handle.setPendingInstances(instances);
1159       }
1160     }
1161   } else {
1162     handle = new TCP();
1163     isTCP = true;
1164   }
1165
1166   if (address || port || isTCP) {
1167     debug('bind to ' + (address || 'anycast'));
1168     if (!address) {
1169       // Try binding to ipv6 first
1170       err = handle.bind6('::', port);
1171       if (err) {
1172         handle.close();
1173         // Fallback to ipv4
1174         return createServerHandle('0.0.0.0', port);
1175       }
1176     } else if (addressType === 6) {
1177       err = handle.bind6(address, port);
1178     } else {
1179       err = handle.bind(address, port);
1180     }
1181   }
1182
1183   if (err) {
1184     handle.close();
1185     return err;
1186   }
1187
1188   return handle;
1189 }
1190 exports._createServerHandle = createServerHandle;
1191
1192
1193 Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
1194   debug('listen2', address, port, addressType, backlog, fd);
1195   var self = this;
1196
1197   // If there is not yet a handle, we need to create one and bind.
1198   // In the case of a server sent via IPC, we don't need to do this.
1199   if (self._handle) {
1200     debug('_listen2: have a handle already');
1201   } else {
1202     debug('_listen2: create a handle');
1203
1204     var rval = null;
1205
1206     if (!address && typeof fd !== 'number') {
1207       rval = createServerHandle('::', port, 6, fd);
1208
1209       if (typeof rval === 'number') {
1210         rval = null;
1211         address = '0.0.0.0';
1212         addressType = 4;
1213       } else {
1214         address = '::';
1215         addressType = 6;
1216       }
1217     }
1218
1219     if (rval === null)
1220       rval = createServerHandle(address, port, addressType, fd);
1221
1222     if (typeof rval === 'number') {
1223       var error = exceptionWithHostPort(rval, 'listen', address, port);
1224       process.nextTick(emitErrorNT, self, error);
1225       return;
1226     }
1227     self._handle = rval;
1228   }
1229
1230   self._handle.onconnection = onconnection;
1231   self._handle.owner = self;
1232
1233   var err = _listen(self._handle, backlog);
1234
1235   if (err) {
1236     var ex = exceptionWithHostPort(err, 'listen', address, port);
1237     self._handle.close();
1238     self._handle = null;
1239     process.nextTick(emitErrorNT, self, ex);
1240     return;
1241   }
1242
1243   // generate connection key, this should be unique to the connection
1244   this._connectionKey = addressType + ':' + address + ':' + port;
1245
1246   // unref the handle if the server was unref'ed prior to listening
1247   if (this._unref)
1248     this.unref();
1249
1250   process.nextTick(emitListeningNT, self);
1251 };
1252
1253
1254 function emitErrorNT(self, err) {
1255   self.emit('error', err);
1256 }
1257
1258
1259 function emitListeningNT(self) {
1260   // ensure handle hasn't closed
1261   if (self._handle)
1262     self.emit('listening');
1263 }
1264
1265
1266 function listen(self, address, port, addressType, backlog, fd, exclusive) {
1267   exclusive = !!exclusive;
1268
1269   if (!cluster) cluster = require('cluster');
1270
1271   if (cluster.isMaster || exclusive) {
1272     self._listen2(address, port, addressType, backlog, fd);
1273     return;
1274   }
1275
1276   cluster._getServer(self, {
1277     address: address,
1278     port: port,
1279     addressType: addressType,
1280     fd: fd,
1281     flags: 0
1282   }, cb);
1283
1284   function cb(err, handle) {
1285     // EADDRINUSE may not be reported until we call listen(). To complicate
1286     // matters, a failed bind() followed by listen() will implicitly bind to
1287     // a random port. Ergo, check that the socket is bound to the expected
1288     // port before calling listen().
1289     //
1290     // FIXME(bnoordhuis) Doesn't work for pipe handles, they don't have a
1291     // getsockname() method. Non-issue for now, the cluster module doesn't
1292     // really support pipes anyway.
1293     if (err === 0 && port > 0 && handle.getsockname) {
1294       var out = {};
1295       err = handle.getsockname(out);
1296       if (err === 0 && port !== out.port)
1297         err = uv.UV_EADDRINUSE;
1298     }
1299
1300     if (err) {
1301       var ex = exceptionWithHostPort(err, 'bind', address, port);
1302       return self.emit('error', ex);
1303     }
1304
1305     self._handle = handle;
1306     self._listen2(address, port, addressType, backlog, fd);
1307   }
1308 }
1309
1310
1311 Server.prototype.listen = function() {
1312   var self = this;
1313
1314   var lastArg = arguments[arguments.length - 1];
1315   if (typeof lastArg === 'function') {
1316     self.once('listening', lastArg);
1317   }
1318
1319   var port = toNumber(arguments[0]);
1320
1321   // The third optional argument is the backlog size.
1322   // When the ip is omitted it can be the second argument.
1323   var backlog = toNumber(arguments[1]) || toNumber(arguments[2]);
1324
1325   if (arguments.length === 0 || typeof arguments[0] === 'function') {
1326     // Bind to a random port.
1327     listen(self, null, 0, null, backlog);
1328   } else if (arguments[0] !== null && typeof arguments[0] === 'object') {
1329     var h = arguments[0];
1330     h = h._handle || h.handle || h;
1331
1332     if (h instanceof TCP) {
1333       self._handle = h;
1334       listen(self, null, -1, -1, backlog);
1335     } else if (typeof h.fd === 'number' && h.fd >= 0) {
1336       listen(self, null, null, null, backlog, h.fd);
1337     } else {
1338       // The first argument is a configuration object
1339       if (h.backlog)
1340         backlog = h.backlog;
1341
1342       if (typeof h.port === 'number' || typeof h.port === 'string' ||
1343           (typeof h.port === 'undefined' && 'port' in h)) {
1344         // Undefined is interpreted as zero (random port) for consistency
1345         // with net.connect().
1346         if (typeof h.port !== 'undefined' && !isLegalPort(h.port))
1347           throw new RangeError('port should be >= 0 and < 65536: ' + h.port);
1348         if (h.host)
1349           listenAfterLookup(h.port | 0, h.host, backlog, h.exclusive);
1350         else
1351           listen(self, null, h.port | 0, 4, backlog, undefined, h.exclusive);
1352       } else if (h.path && isPipeName(h.path)) {
1353         var pipeName = self._pipeName = h.path;
1354         listen(self, pipeName, -1, -1, backlog, undefined, h.exclusive);
1355       } else {
1356         throw new Error('Invalid listen argument: ' + h);
1357       }
1358     }
1359   } else if (isPipeName(arguments[0])) {
1360     // UNIX socket or Windows pipe.
1361     var pipeName = self._pipeName = arguments[0];
1362     listen(self, pipeName, -1, -1, backlog);
1363
1364   } else if (arguments[1] === undefined ||
1365              typeof arguments[1] === 'function' ||
1366              typeof arguments[1] === 'number') {
1367     // The first argument is the port, no IP given.
1368     listen(self, null, port, 4, backlog);
1369
1370   } else {
1371     // The first argument is the port, the second an IP.
1372     listenAfterLookup(port, arguments[1], backlog);
1373   }
1374
1375   function listenAfterLookup(port, address, backlog, exclusive) {
1376     require('dns').lookup(address, function(err, ip, addressType) {
1377       if (err) {
1378         self.emit('error', err);
1379       } else {
1380         addressType = ip ? addressType : 4;
1381         listen(self, ip, port, addressType, backlog, undefined, exclusive);
1382       }
1383     });
1384   }
1385
1386   return self;
1387 };
1388
1389 Server.prototype.address = function() {
1390   if (this._handle && this._handle.getsockname) {
1391     var out = {};
1392     this._handle.getsockname(out);
1393     // TODO(bnoordhuis) Check err and throw?
1394     return out;
1395   } else if (this._pipeName) {
1396     return this._pipeName;
1397   } else {
1398     return null;
1399   }
1400 };
1401
1402 function onconnection(err, clientHandle) {
1403   var handle = this;
1404   var self = handle.owner;
1405
1406   debug('onconnection');
1407
1408   if (err) {
1409     self.emit('error', errnoException(err, 'accept'));
1410     return;
1411   }
1412
1413   if (self.maxConnections && self._connections >= self.maxConnections) {
1414     clientHandle.close();
1415     return;
1416   }
1417
1418   var socket = new Socket({
1419     handle: clientHandle,
1420     allowHalfOpen: self.allowHalfOpen,
1421     pauseOnCreate: self.pauseOnConnect
1422   });
1423   socket.readable = socket.writable = true;
1424
1425
1426   self._connections++;
1427   socket.server = self;
1428
1429   DTRACE_NET_SERVER_CONNECTION(socket);
1430   LTTNG_NET_SERVER_CONNECTION(socket);
1431   COUNTER_NET_SERVER_CONNECTION(socket);
1432   self.emit('connection', socket);
1433 }
1434
1435
1436 Server.prototype.getConnections = function(cb) {
1437   function end(err, connections) {
1438     process.nextTick(cb, err, connections);
1439   }
1440
1441   if (!this._usingSlaves) {
1442     return end(null, this._connections);
1443   }
1444
1445   // Poll slaves
1446   var left = this._slaves.length;
1447   var total = this._connections;
1448
1449   function oncount(err, count) {
1450     if (err) {
1451       left = -1;
1452       return end(err);
1453     }
1454
1455     total += count;
1456     if (--left === 0) return end(null, total);
1457   }
1458
1459   this._slaves.forEach(function(slave) {
1460     slave.getConnections(oncount);
1461   });
1462 };
1463
1464
1465 Server.prototype.close = function(cb) {
1466   function onSlaveClose() {
1467     if (--left !== 0) return;
1468
1469     self._connections = 0;
1470     self._emitCloseIfDrained();
1471   }
1472
1473   if (typeof cb === 'function') {
1474     if (!this._handle) {
1475       this.once('close', function() {
1476         cb(new Error('Not running'));
1477       });
1478     } else {
1479       this.once('close', cb);
1480     }
1481   }
1482
1483   if (this._handle) {
1484     this._handle.close();
1485     this._handle = null;
1486   }
1487
1488   if (this._usingSlaves) {
1489     var self = this;
1490     var left = this._slaves.length;
1491
1492     // Increment connections to be sure that, even if all sockets will be closed
1493     // during polling of slaves, `close` event will be emitted only once.
1494     this._connections++;
1495
1496     // Poll slaves
1497     this._slaves.forEach(function(slave) {
1498       slave.close(onSlaveClose);
1499     });
1500   } else {
1501     this._emitCloseIfDrained();
1502   }
1503
1504   return this;
1505 };
1506
1507 Server.prototype._emitCloseIfDrained = function() {
1508   debug('SERVER _emitCloseIfDrained');
1509   var self = this;
1510
1511   if (self._handle || self._connections) {
1512     debug('SERVER handle? %j   connections? %d',
1513           !!self._handle, self._connections);
1514     return;
1515   }
1516
1517   process.nextTick(emitCloseNT, self);
1518 };
1519
1520
1521 function emitCloseNT(self) {
1522   debug('SERVER: emit close');
1523   self.emit('close');
1524 }
1525
1526
1527 Server.prototype.listenFD = internalUtil.deprecate(function(fd, type) {
1528   return this.listen({ fd: fd });
1529 }, 'Server.listenFD is deprecated. Use Server.listen({fd: <number>}) instead.');
1530
1531 Server.prototype._setupSlave = function(socketList) {
1532   this._usingSlaves = true;
1533   this._slaves.push(socketList);
1534 };
1535
1536 Server.prototype.ref = function() {
1537   this._unref = false;
1538
1539   if (this._handle)
1540     this._handle.ref();
1541
1542   return this;
1543 };
1544
1545 Server.prototype.unref = function() {
1546   this._unref = true;
1547
1548   if (this._handle)
1549     this._handle.unref();
1550
1551   return this;
1552 };
1553
1554
1555 exports.isIP = cares.isIP;
1556
1557
1558 exports.isIPv4 = function(input) {
1559   return exports.isIP(input) === 4;
1560 };
1561
1562
1563 exports.isIPv6 = function(input) {
1564   return exports.isIP(input) === 6;
1565 };
1566
1567
1568 if (process.platform === 'win32') {
1569   var simultaneousAccepts;
1570
1571   exports._setSimultaneousAccepts = function(handle) {
1572     if (handle === undefined) {
1573       return;
1574     }
1575
1576     if (simultaneousAccepts === undefined) {
1577       simultaneousAccepts = (process.env.NODE_MANY_ACCEPTS &&
1578                              process.env.NODE_MANY_ACCEPTS !== '0');
1579     }
1580
1581     if (handle._simultaneousAccepts !== simultaneousAccepts) {
1582       handle.setSimultaneousAccepts(simultaneousAccepts);
1583       handle._simultaneousAccepts = simultaneousAccepts;
1584     }
1585   };
1586 } else {
1587   exports._setSimultaneousAccepts = function(handle) {};
1588 }