PageRenderTime 70ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/net.js

https://gitlab.com/GeekSir/node
JavaScript | 1482 lines | 1029 code | 296 blank | 157 comment | 271 complexity | e2617b2e9e242eeb6ff08cdb0685d84b MD5 | raw file
Possible License(s): 0BSD, Apache-2.0, MPL-2.0-no-copyleft-exception, JSON, WTFPL, CC-BY-SA-3.0, Unlicense, ISC, BSD-3-Clause, MIT, AGPL-3.0
  1. // Copyright Joyent, Inc. and other Node contributors.
  2. //
  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:
  10. //
  11. // The above copyright notice and this permission notice shall be included
  12. // in all copies or substantial portions of the Software.
  13. //
  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.
  21. 'use strict';
  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');
  29. var Pipe = process.binding('pipe_wrap').Pipe;
  30. var TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap;
  31. var PipeConnectWrap = process.binding('pipe_wrap').PipeConnectWrap;
  32. var ShutdownWrap = process.binding('stream_wrap').ShutdownWrap;
  33. var WriteWrap = process.binding('stream_wrap').WriteWrap;
  34. var Buffer = require('buffer').Buffer;
  35. var cluster;
  36. var errnoException = util._errnoException;
  37. function noop() {}
  38. // constructor for lazy loading
  39. function createPipe() {
  40. return new Pipe();
  41. }
  42. // constructor for lazy loading
  43. function createTCP() {
  44. var TCP = process.binding('tcp_wrap').TCP;
  45. return new TCP();
  46. }
  47. function createHandle(fd) {
  48. var tty = process.binding('tty_wrap');
  49. var type = tty.guessHandleType(fd);
  50. if (type === 'PIPE') return createPipe();
  51. if (type === 'TCP') return createTCP();
  52. throw new TypeError('Unsupported fd type: ' + type);
  53. }
  54. var debug = util.debuglog('net');
  55. function isPipeName(s) {
  56. return util.isString(s) && toNumber(s) === false;
  57. }
  58. exports.createServer = function(options, connectionListener) {
  59. return new Server(options, connectionListener);
  60. };
  61. // Target API:
  62. //
  63. // var s = net.connect({port: 80, host: 'google.com'}, function() {
  64. // ...
  65. // });
  66. //
  67. // There are various forms:
  68. //
  69. // connect(options, [cb])
  70. // connect(port, [host], [cb])
  71. // connect(path, [cb]);
  72. //
  73. exports.connect = exports.createConnection = function() {
  74. var args = normalizeConnectArgs(arguments);
  75. debug('createConnection', args);
  76. var s = new Socket(args[0]);
  77. return Socket.prototype.connect.apply(s, args);
  78. };
  79. // Returns an array [options] or [options, cb]
  80. // It is the same as the argument of Socket.prototype.connect().
  81. function normalizeConnectArgs(args) {
  82. var options = {};
  83. if (util.isObject(args[0])) {
  84. // connect(options, [cb])
  85. options = args[0];
  86. } else if (isPipeName(args[0])) {
  87. // connect(path, [cb]);
  88. options.path = args[0];
  89. } else {
  90. // connect(port, [host], [cb])
  91. options.port = args[0];
  92. if (util.isString(args[1])) {
  93. options.host = args[1];
  94. }
  95. }
  96. var cb = args[args.length - 1];
  97. return util.isFunction(cb) ? [options, cb] : [options];
  98. }
  99. exports._normalizeConnectArgs = normalizeConnectArgs;
  100. // called when creating new Socket, or when re-using a closed Socket
  101. function initSocketHandle(self) {
  102. self.destroyed = false;
  103. self.bytesRead = 0;
  104. self._bytesDispatched = 0;
  105. // Handle creation may be deferred to bind() or connect() time.
  106. if (self._handle) {
  107. self._handle.owner = self;
  108. self._handle.onread = onread;
  109. // If handle doesn't support writev - neither do we
  110. if (!self._handle.writev)
  111. self._writev = null;
  112. }
  113. }
  114. function Socket(options) {
  115. if (!(this instanceof Socket)) return new Socket(options);
  116. this._connecting = false;
  117. this._hadError = false;
  118. this._handle = null;
  119. this._parent = null;
  120. this._host = null;
  121. if (util.isNumber(options))
  122. options = { fd: options }; // Legacy interface.
  123. else if (util.isUndefined(options))
  124. options = {};
  125. stream.Duplex.call(this, options);
  126. if (options.handle) {
  127. this._handle = options.handle; // private
  128. } else if (!util.isUndefined(options.fd)) {
  129. this._handle = createHandle(options.fd);
  130. this._handle.open(options.fd);
  131. // this._handle.open() puts the file descriptor in non-blocking
  132. // mode but it must be synchronous for backwards compatibility.
  133. if ((options.fd == 1 || options.fd == 2) && this._handle instanceof Pipe) {
  134. // Make stdout and stderr blocking on Windows
  135. var err = this._handle.setBlocking(true);
  136. if (err)
  137. throw errnoException(err, 'setBlocking');
  138. }
  139. this.readable = options.readable !== false;
  140. this.writable = options.writable !== false;
  141. } else {
  142. // these will be set once there is a connection
  143. this.readable = this.writable = false;
  144. }
  145. // shut down the socket when we're finished with it.
  146. this.on('finish', onSocketFinish);
  147. this.on('_socketEnd', onSocketEnd);
  148. initSocketHandle(this);
  149. this._pendingData = null;
  150. this._pendingEncoding = '';
  151. // handle strings directly
  152. this._writableState.decodeStrings = false;
  153. // default to *not* allowing half open sockets
  154. this.allowHalfOpen = options && options.allowHalfOpen || false;
  155. // if we have a handle, then start the flow of data into the
  156. // buffer. if not, then this will happen when we connect
  157. if (this._handle && options.readable !== false) {
  158. if (options.pauseOnCreate) {
  159. // stop the handle from reading and pause the stream
  160. this._handle.reading = false;
  161. this._handle.readStop();
  162. this._readableState.flowing = false;
  163. } else {
  164. this.read(0);
  165. }
  166. }
  167. }
  168. util.inherits(Socket, stream.Duplex);
  169. Socket.prototype._unrefTimer = function unrefTimer() {
  170. for (var s = this; s !== null; s = s._parent)
  171. timers._unrefActive(s);
  172. };
  173. // the user has called .end(), and all the bytes have been
  174. // sent out to the other side.
  175. // If allowHalfOpen is false, or if the readable side has
  176. // ended already, then destroy.
  177. // If allowHalfOpen is true, then we need to do a shutdown,
  178. // so that only the writable side will be cleaned up.
  179. function onSocketFinish() {
  180. // If still connecting - defer handling 'finish' until 'connect' will happen
  181. if (this._connecting) {
  182. debug('osF: not yet connected');
  183. return this.once('connect', onSocketFinish);
  184. }
  185. debug('onSocketFinish');
  186. if (!this.readable || this._readableState.ended) {
  187. debug('oSF: ended, destroy', this._readableState);
  188. return this.destroy();
  189. }
  190. debug('oSF: not ended, call shutdown()');
  191. // otherwise, just shutdown, or destroy() if not possible
  192. if (!this._handle || !this._handle.shutdown)
  193. return this.destroy();
  194. var req = new ShutdownWrap();
  195. req.oncomplete = afterShutdown;
  196. var err = this._handle.shutdown(req);
  197. if (err)
  198. return this._destroy(errnoException(err, 'shutdown'));
  199. }
  200. function afterShutdown(status, handle, req) {
  201. var self = handle.owner;
  202. debug('afterShutdown destroyed=%j', self.destroyed,
  203. self._readableState);
  204. // callback may come after call to destroy.
  205. if (self.destroyed)
  206. return;
  207. if (self._readableState.ended) {
  208. debug('readableState ended, destroying');
  209. self.destroy();
  210. } else {
  211. self.once('_socketEnd', self.destroy);
  212. }
  213. }
  214. // the EOF has been received, and no more bytes are coming.
  215. // if the writable side has ended already, then clean everything
  216. // up.
  217. function onSocketEnd() {
  218. // XXX Should not have to do as much crap in this function.
  219. // ended should already be true, since this is called *after*
  220. // the EOF errno and onread has eof'ed
  221. debug('onSocketEnd', this._readableState);
  222. this._readableState.ended = true;
  223. if (this._readableState.endEmitted) {
  224. this.readable = false;
  225. maybeDestroy(this);
  226. } else {
  227. this.once('end', function() {
  228. this.readable = false;
  229. maybeDestroy(this);
  230. });
  231. this.read(0);
  232. }
  233. if (!this.allowHalfOpen) {
  234. this.write = writeAfterFIN;
  235. this.destroySoon();
  236. }
  237. }
  238. // Provide a better error message when we call end() as a result
  239. // of the other side sending a FIN. The standard 'write after end'
  240. // is overly vague, and makes it seem like the user's code is to blame.
  241. function writeAfterFIN(chunk, encoding, cb) {
  242. if (util.isFunction(encoding)) {
  243. cb = encoding;
  244. encoding = null;
  245. }
  246. var er = new Error('This socket has been ended by the other party');
  247. er.code = 'EPIPE';
  248. var self = this;
  249. // TODO: defer error events consistently everywhere, not just the cb
  250. self.emit('error', er);
  251. if (util.isFunction(cb)) {
  252. process.nextTick(function() {
  253. cb(er);
  254. });
  255. }
  256. }
  257. exports.Socket = Socket;
  258. exports.Stream = Socket; // Legacy naming.
  259. Socket.prototype.read = function(n) {
  260. if (n === 0)
  261. return stream.Readable.prototype.read.call(this, n);
  262. this.read = stream.Readable.prototype.read;
  263. this._consuming = true;
  264. return this.read(n);
  265. };
  266. Socket.prototype.listen = function() {
  267. debug('socket.listen');
  268. var self = this;
  269. self.on('connection', arguments[0]);
  270. listen(self, null, null, null);
  271. };
  272. Socket.prototype.setTimeout = function(msecs, callback) {
  273. if (msecs === 0) {
  274. timers.unenroll(this);
  275. if (callback) {
  276. this.removeListener('timeout', callback);
  277. }
  278. } else {
  279. timers.enroll(this, msecs);
  280. timers._unrefActive(this);
  281. if (callback) {
  282. this.once('timeout', callback);
  283. }
  284. }
  285. };
  286. Socket.prototype._onTimeout = function() {
  287. debug('_onTimeout');
  288. this.emit('timeout');
  289. };
  290. Socket.prototype.setNoDelay = function(enable) {
  291. // backwards compatibility: assume true when `enable` is omitted
  292. if (this._handle && this._handle.setNoDelay)
  293. this._handle.setNoDelay(util.isUndefined(enable) ? true : !!enable);
  294. };
  295. Socket.prototype.setKeepAlive = function(setting, msecs) {
  296. if (this._handle && this._handle.setKeepAlive)
  297. this._handle.setKeepAlive(setting, ~~(msecs / 1000));
  298. };
  299. Socket.prototype.address = function() {
  300. return this._getsockname();
  301. };
  302. Object.defineProperty(Socket.prototype, 'readyState', {
  303. get: function() {
  304. if (this._connecting) {
  305. return 'opening';
  306. } else if (this.readable && this.writable) {
  307. return 'open';
  308. } else if (this.readable && !this.writable) {
  309. return 'readOnly';
  310. } else if (!this.readable && this.writable) {
  311. return 'writeOnly';
  312. } else {
  313. return 'closed';
  314. }
  315. }
  316. });
  317. Object.defineProperty(Socket.prototype, 'bufferSize', {
  318. get: function() {
  319. if (this._handle) {
  320. return this._handle.writeQueueSize + this._writableState.length;
  321. }
  322. }
  323. });
  324. // Just call handle.readStart until we have enough in the buffer
  325. Socket.prototype._read = function(n) {
  326. debug('_read');
  327. if (this._connecting || !this._handle) {
  328. debug('_read wait for connection');
  329. this.once('connect', this._read.bind(this, n));
  330. } else if (!this._handle.reading) {
  331. // not already reading, start the flow
  332. debug('Socket._read readStart');
  333. this._handle.reading = true;
  334. var err = this._handle.readStart();
  335. if (err)
  336. this._destroy(errnoException(err, 'read'));
  337. }
  338. };
  339. Socket.prototype.end = function(data, encoding) {
  340. stream.Duplex.prototype.end.call(this, data, encoding);
  341. this.writable = false;
  342. DTRACE_NET_STREAM_END(this);
  343. // just in case we're waiting for an EOF.
  344. if (this.readable && !this._readableState.endEmitted)
  345. this.read(0);
  346. else
  347. maybeDestroy(this);
  348. };
  349. // Call whenever we set writable=false or readable=false
  350. function maybeDestroy(socket) {
  351. if (!socket.readable &&
  352. !socket.writable &&
  353. !socket.destroyed &&
  354. !socket._connecting &&
  355. !socket._writableState.length) {
  356. socket.destroy();
  357. }
  358. }
  359. Socket.prototype.destroySoon = function() {
  360. if (this.writable)
  361. this.end();
  362. if (this._writableState.finished)
  363. this.destroy();
  364. else
  365. this.once('finish', this.destroy);
  366. };
  367. Socket.prototype._destroy = function(exception, cb) {
  368. debug('destroy');
  369. var self = this;
  370. function fireErrorCallbacks() {
  371. if (cb) cb(exception);
  372. if (exception && !self._writableState.errorEmitted) {
  373. process.nextTick(function() {
  374. self.emit('error', exception);
  375. });
  376. self._writableState.errorEmitted = true;
  377. }
  378. };
  379. if (this.destroyed) {
  380. debug('already destroyed, fire error callbacks');
  381. fireErrorCallbacks();
  382. return;
  383. }
  384. self._connecting = false;
  385. this.readable = this.writable = false;
  386. for (var s = this; s !== null; s = s._parent)
  387. timers.unenroll(s);
  388. debug('close');
  389. if (this._handle) {
  390. if (this !== process.stderr)
  391. debug('close handle');
  392. var isException = exception ? true : false;
  393. this._handle.close(function() {
  394. debug('emit close');
  395. self.emit('close', isException);
  396. });
  397. this._handle.onread = noop;
  398. this._handle = null;
  399. }
  400. // we set destroyed to true before firing error callbacks in order
  401. // to make it re-entrance safe in case Socket.prototype.destroy()
  402. // is called within callbacks
  403. this.destroyed = true;
  404. fireErrorCallbacks();
  405. if (this.server) {
  406. COUNTER_NET_SERVER_CONNECTION_CLOSE(this);
  407. debug('has server');
  408. this.server._connections--;
  409. if (this.server._emitCloseIfDrained) {
  410. this.server._emitCloseIfDrained();
  411. }
  412. }
  413. };
  414. Socket.prototype.destroy = function(exception) {
  415. debug('destroy', exception);
  416. this._destroy(exception);
  417. };
  418. // This function is called whenever the handle gets a
  419. // buffer, or when there's an error reading.
  420. function onread(nread, buffer) {
  421. var handle = this;
  422. var self = handle.owner;
  423. assert(handle === self._handle, 'handle != self._handle');
  424. self._unrefTimer();
  425. debug('onread', nread);
  426. if (nread > 0) {
  427. debug('got data');
  428. // read success.
  429. // In theory (and in practice) calling readStop right now
  430. // will prevent this from being called again until _read() gets
  431. // called again.
  432. // if it's not enough data, we'll just call handle.readStart()
  433. // again right away.
  434. self.bytesRead += nread;
  435. // Optimization: emit the original buffer with end points
  436. var ret = self.push(buffer);
  437. if (handle.reading && !ret) {
  438. handle.reading = false;
  439. debug('readStop');
  440. var err = handle.readStop();
  441. if (err)
  442. self._destroy(errnoException(err, 'read'));
  443. }
  444. return;
  445. }
  446. // if we didn't get any bytes, that doesn't necessarily mean EOF.
  447. // wait for the next one.
  448. if (nread === 0) {
  449. debug('not any data, keep waiting');
  450. return;
  451. }
  452. // Error, possibly EOF.
  453. if (nread !== uv.UV_EOF) {
  454. return self._destroy(errnoException(nread, 'read'));
  455. }
  456. debug('EOF');
  457. if (self._readableState.length === 0) {
  458. self.readable = false;
  459. maybeDestroy(self);
  460. }
  461. // push a null to signal the end of data.
  462. self.push(null);
  463. // internal end event so that we know that the actual socket
  464. // is no longer readable, and we can start the shutdown
  465. // procedure. No need to wait for all the data to be consumed.
  466. self.emit('_socketEnd');
  467. }
  468. Socket.prototype._getpeername = function() {
  469. if (!this._peername) {
  470. if (!this._handle || !this._handle.getpeername) {
  471. return {};
  472. }
  473. var out = {};
  474. var err = this._handle.getpeername(out);
  475. if (err) return {}; // FIXME(bnoordhuis) Throw?
  476. this._peername = out;
  477. }
  478. return this._peername;
  479. };
  480. Socket.prototype.__defineGetter__('remoteAddress', function() {
  481. return this._getpeername().address;
  482. });
  483. Socket.prototype.__defineGetter__('remoteFamily', function() {
  484. return this._getpeername().family;
  485. });
  486. Socket.prototype.__defineGetter__('remotePort', function() {
  487. return this._getpeername().port;
  488. });
  489. Socket.prototype._getsockname = function() {
  490. if (!this._handle || !this._handle.getsockname) {
  491. return {};
  492. }
  493. if (!this._sockname) {
  494. var out = {};
  495. var err = this._handle.getsockname(out);
  496. if (err) return {}; // FIXME(bnoordhuis) Throw?
  497. this._sockname = out;
  498. }
  499. return this._sockname;
  500. };
  501. Socket.prototype.__defineGetter__('localAddress', function() {
  502. return this._getsockname().address;
  503. });
  504. Socket.prototype.__defineGetter__('localPort', function() {
  505. return this._getsockname().port;
  506. });
  507. Socket.prototype.write = function(chunk, encoding, cb) {
  508. 'use strict';
  509. if (!util.isString(chunk) && !util.isBuffer(chunk))
  510. throw new TypeError('invalid data');
  511. return stream.Duplex.prototype.write.apply(this, arguments);
  512. };
  513. Socket.prototype._writeGeneric = function(writev, data, encoding, cb) {
  514. // If we are still connecting, then buffer this for later.
  515. // The Writable logic will buffer up any more writes while
  516. // waiting for this one to be done.
  517. if (this._connecting) {
  518. this._pendingData = data;
  519. this._pendingEncoding = encoding;
  520. this.once('connect', function() {
  521. this._writeGeneric(writev, data, encoding, cb);
  522. });
  523. return;
  524. }
  525. this._pendingData = null;
  526. this._pendingEncoding = '';
  527. this._unrefTimer();
  528. if (!this._handle) {
  529. this._destroy(new Error('This socket is closed.'), cb);
  530. return false;
  531. }
  532. var req = new WriteWrap();
  533. req.oncomplete = afterWrite;
  534. req.async = false;
  535. var err;
  536. if (writev) {
  537. var chunks = new Array(data.length << 1);
  538. for (var i = 0; i < data.length; i++) {
  539. var entry = data[i];
  540. var chunk = entry.chunk;
  541. var enc = entry.encoding;
  542. chunks[i * 2] = chunk;
  543. chunks[i * 2 + 1] = enc;
  544. }
  545. err = this._handle.writev(req, chunks);
  546. // Retain chunks
  547. if (err === 0) req._chunks = chunks;
  548. } else {
  549. var enc;
  550. if (util.isBuffer(data)) {
  551. req.buffer = data; // Keep reference alive.
  552. enc = 'buffer';
  553. } else {
  554. enc = encoding;
  555. }
  556. err = createWriteReq(req, this._handle, data, enc);
  557. }
  558. if (err)
  559. return this._destroy(errnoException(err, 'write', req.error), cb);
  560. this._bytesDispatched += req.bytes;
  561. // If it was entirely flushed, we can write some more right now.
  562. // However, if more is left in the queue, then wait until that clears.
  563. if (req.async && this._handle.writeQueueSize != 0)
  564. req.cb = cb;
  565. else
  566. cb();
  567. };
  568. Socket.prototype._writev = function(chunks, cb) {
  569. this._writeGeneric(true, chunks, '', cb);
  570. };
  571. Socket.prototype._write = function(data, encoding, cb) {
  572. this._writeGeneric(false, data, encoding, cb);
  573. };
  574. function createWriteReq(req, handle, data, encoding) {
  575. switch (encoding) {
  576. case 'binary':
  577. return handle.writeBinaryString(req, data);
  578. case 'buffer':
  579. return handle.writeBuffer(req, data);
  580. case 'utf8':
  581. case 'utf-8':
  582. return handle.writeUtf8String(req, data);
  583. case 'ascii':
  584. return handle.writeAsciiString(req, data);
  585. case 'ucs2':
  586. case 'ucs-2':
  587. case 'utf16le':
  588. case 'utf-16le':
  589. return handle.writeUcs2String(req, data);
  590. default:
  591. return handle.writeBuffer(req, new Buffer(data, encoding));
  592. }
  593. }
  594. Socket.prototype.__defineGetter__('bytesWritten', function() {
  595. var bytes = this._bytesDispatched,
  596. state = this._writableState,
  597. data = this._pendingData,
  598. encoding = this._pendingEncoding;
  599. state.getBuffer().forEach(function(el) {
  600. if (util.isBuffer(el.chunk))
  601. bytes += el.chunk.length;
  602. else
  603. bytes += Buffer.byteLength(el.chunk, el.encoding);
  604. });
  605. if (data) {
  606. if (util.isBuffer(data))
  607. bytes += data.length;
  608. else
  609. bytes += Buffer.byteLength(data, encoding);
  610. }
  611. return bytes;
  612. });
  613. function afterWrite(status, handle, req, err) {
  614. var self = handle.owner;
  615. if (self !== process.stderr && self !== process.stdout)
  616. debug('afterWrite', status);
  617. // callback may come after call to destroy.
  618. if (self.destroyed) {
  619. debug('afterWrite destroyed');
  620. return;
  621. }
  622. if (status < 0) {
  623. var ex = errnoException(status, 'write', err);
  624. debug('write failure', ex);
  625. self._destroy(ex, req.cb);
  626. return;
  627. }
  628. self._unrefTimer();
  629. if (self !== process.stderr && self !== process.stdout)
  630. debug('afterWrite call cb');
  631. if (req.cb)
  632. req.cb.call(self);
  633. }
  634. function connect(self, address, port, addressType, localAddress, localPort) {
  635. // TODO return promise from Socket.prototype.connect which
  636. // wraps _connectReq.
  637. assert.ok(self._connecting);
  638. var err;
  639. if (localAddress || localPort) {
  640. var bind;
  641. if (addressType === 4) {
  642. localAddress = localAddress || '0.0.0.0';
  643. bind = self._handle.bind;
  644. } else if (addressType === 6) {
  645. localAddress = localAddress || '::';
  646. bind = self._handle.bind6;
  647. } else {
  648. self._destroy(new TypeError('Invalid addressType: ' + addressType));
  649. return;
  650. }
  651. debug('binding to localAddress: %s and localPort: %d',
  652. localAddress,
  653. localPort);
  654. bind = bind.bind(self._handle);
  655. err = bind(localAddress, localPort);
  656. if (err) {
  657. self._destroy(errnoException(err, 'bind'));
  658. return;
  659. }
  660. }
  661. if (addressType === 6 || addressType === 4) {
  662. var req = new TCPConnectWrap();
  663. req.oncomplete = afterConnect;
  664. if (addressType === 4)
  665. err = self._handle.connect(req, address, port);
  666. else
  667. err = self._handle.connect6(req, address, port);
  668. } else {
  669. var req = new PipeConnectWrap();
  670. req.oncomplete = afterConnect;
  671. err = self._handle.connect(req, address, afterConnect);
  672. }
  673. if (err) {
  674. self._destroy(errnoException(err, 'connect'));
  675. }
  676. }
  677. Socket.prototype.connect = function(options, cb) {
  678. if (this.write !== Socket.prototype.write)
  679. this.write = Socket.prototype.write;
  680. if (!util.isObject(options)) {
  681. // Old API:
  682. // connect(port, [host], [cb])
  683. // connect(path, [cb]);
  684. var args = normalizeConnectArgs(arguments);
  685. return Socket.prototype.connect.apply(this, args);
  686. }
  687. if (this.destroyed) {
  688. this._readableState.reading = false;
  689. this._readableState.ended = false;
  690. this._readableState.endEmitted = false;
  691. this._writableState.ended = false;
  692. this._writableState.ending = false;
  693. this._writableState.finished = false;
  694. this._writableState.errorEmitted = false;
  695. this.destroyed = false;
  696. this._handle = null;
  697. this._peername = null;
  698. }
  699. var self = this;
  700. var pipe = !!options.path;
  701. debug('pipe', pipe, options.path);
  702. if (!this._handle) {
  703. this._handle = pipe ? createPipe() : createTCP();
  704. initSocketHandle(this);
  705. }
  706. if (util.isFunction(cb)) {
  707. self.once('connect', cb);
  708. }
  709. this._unrefTimer();
  710. self._connecting = true;
  711. self.writable = true;
  712. if (pipe) {
  713. connect(self, options.path);
  714. } else {
  715. var dns = require('dns');
  716. var host = options.host || 'localhost';
  717. var port = 0;
  718. var localAddress = options.localAddress;
  719. var localPort = options.localPort;
  720. var dnsopts = {
  721. family: options.family,
  722. hints: 0
  723. };
  724. if (localAddress && !exports.isIP(localAddress))
  725. throw new TypeError('localAddress must be a valid IP: ' + localAddress);
  726. if (localPort && !util.isNumber(localPort))
  727. throw new TypeError('localPort should be a number: ' + localPort);
  728. if (typeof options.port === 'number')
  729. port = options.port;
  730. else if (typeof options.port === 'string')
  731. port = options.port.trim() === '' ? -1 : +options.port;
  732. else if (options.port !== undefined)
  733. throw new TypeError('port should be a number or string: ' + options.port);
  734. if (port < 0 || port > 65535 || isNaN(port))
  735. throw new RangeError('port should be >= 0 and < 65536: ' +
  736. options.port);
  737. if (dnsopts.family !== 4 && dnsopts.family !== 6) {
  738. dnsopts.hints = dns.ADDRCONFIG;
  739. // The AI_V4MAPPED hint is not supported on FreeBSD, and getaddrinfo
  740. // returns EAI_BADFLAGS. However, it seems to be supported on most other
  741. // systems. See
  742. // http://lists.freebsd.org/pipermail/freebsd-bugs/2008-February/028260.html
  743. // and
  744. // https://svnweb.freebsd.org/base/head/lib/libc/net/getaddrinfo.c?r1=172052&r2=175955
  745. // for more information on the lack of support for FreeBSD.
  746. if (process.platform !== 'freebsd')
  747. dnsopts.hints |= dns.V4MAPPED;
  748. }
  749. debug('connect: find host ' + host);
  750. debug('connect: dns options ' + dnsopts);
  751. self._host = host;
  752. dns.lookup(host, dnsopts, function(err, ip, addressType) {
  753. self.emit('lookup', err, ip, addressType);
  754. // It's possible we were destroyed while looking this up.
  755. // XXX it would be great if we could cancel the promise returned by
  756. // the look up.
  757. if (!self._connecting) return;
  758. if (err) {
  759. // net.createConnection() creates a net.Socket object and
  760. // immediately calls net.Socket.connect() on it (that's us).
  761. // There are no event listeners registered yet so defer the
  762. // error event to the next tick.
  763. process.nextTick(function() {
  764. self.emit('error', err);
  765. self._destroy();
  766. });
  767. } else {
  768. self._unrefTimer();
  769. connect(self,
  770. ip,
  771. port,
  772. addressType,
  773. localAddress,
  774. localPort);
  775. }
  776. });
  777. }
  778. return self;
  779. };
  780. Socket.prototype.ref = function() {
  781. if (this._handle)
  782. this._handle.ref();
  783. };
  784. Socket.prototype.unref = function() {
  785. if (this._handle)
  786. this._handle.unref();
  787. };
  788. function afterConnect(status, handle, req, readable, writable) {
  789. var self = handle.owner;
  790. // callback may come after call to destroy
  791. if (self.destroyed) {
  792. return;
  793. }
  794. assert(handle === self._handle, 'handle != self._handle');
  795. debug('afterConnect');
  796. assert.ok(self._connecting);
  797. self._connecting = false;
  798. if (status == 0) {
  799. self.readable = readable;
  800. self.writable = writable;
  801. self._unrefTimer();
  802. self.emit('connect');
  803. // start the first read, or get an immediate EOF.
  804. // this doesn't actually consume any bytes, because len=0.
  805. if (readable && !self.isPaused())
  806. self.read(0);
  807. } else {
  808. self._connecting = false;
  809. self._destroy(errnoException(status, 'connect'));
  810. }
  811. }
  812. function Server(options, connectionListener) {
  813. if (!(this instanceof Server))
  814. return new Server(options, connectionListener);
  815. events.EventEmitter.call(this);
  816. var self = this;
  817. if (util.isFunction(options)) {
  818. connectionListener = options;
  819. options = {};
  820. self.on('connection', connectionListener);
  821. } else {
  822. options = options || {};
  823. if (util.isFunction(connectionListener))
  824. self.on('connection', connectionListener);
  825. }
  826. this._connections = 0;
  827. Object.defineProperty(this, 'connections', {
  828. get: util.deprecate(function() {
  829. if (self._usingSlaves) {
  830. return null;
  831. }
  832. return self._connections;
  833. }, 'connections property is deprecated. Use getConnections() method'),
  834. set: util.deprecate(function(val) {
  835. return (self._connections = val);
  836. }, 'connections property is deprecated. Use getConnections() method'),
  837. configurable: true, enumerable: false
  838. });
  839. this._handle = null;
  840. this._usingSlaves = false;
  841. this._slaves = [];
  842. this.allowHalfOpen = options.allowHalfOpen || false;
  843. this.pauseOnConnect = !!options.pauseOnConnect;
  844. }
  845. util.inherits(Server, events.EventEmitter);
  846. exports.Server = Server;
  847. function toNumber(x) { return (x = Number(x)) >= 0 ? x : false; }
  848. function _listen(handle, backlog) {
  849. // Use a backlog of 512 entries. We pass 511 to the listen() call because
  850. // the kernel does: backlogsize = roundup_pow_of_two(backlogsize + 1);
  851. // which will thus give us a backlog of 512 entries.
  852. return handle.listen(backlog || 511);
  853. }
  854. var createServerHandle = exports._createServerHandle =
  855. function(address, port, addressType, fd) {
  856. var err = 0;
  857. // assign handle in listen, and clean up if bind or listen fails
  858. var handle;
  859. var isTCP = false;
  860. if (util.isNumber(fd) && fd >= 0) {
  861. try {
  862. handle = createHandle(fd);
  863. }
  864. catch (e) {
  865. // Not a fd we can listen on. This will trigger an error.
  866. debug('listen invalid fd=' + fd + ': ' + e.message);
  867. return uv.UV_EINVAL;
  868. }
  869. handle.open(fd);
  870. handle.readable = true;
  871. handle.writable = true;
  872. assert(!address && !port);
  873. } else if (port === -1 && addressType === -1) {
  874. handle = createPipe();
  875. if (process.platform === 'win32') {
  876. var instances = parseInt(process.env.NODE_PENDING_PIPE_INSTANCES);
  877. if (!isNaN(instances)) {
  878. handle.setPendingInstances(instances);
  879. }
  880. }
  881. } else {
  882. handle = createTCP();
  883. isTCP = true;
  884. }
  885. if (address || port || isTCP) {
  886. debug('bind to ' + (address || 'anycast'));
  887. if (!address) {
  888. // Try binding to ipv6 first
  889. err = handle.bind6('::', port);
  890. if (err) {
  891. handle.close();
  892. // Fallback to ipv4
  893. return createServerHandle('0.0.0.0', port);
  894. }
  895. } else if (addressType === 6) {
  896. err = handle.bind6(address, port);
  897. } else {
  898. err = handle.bind(address, port);
  899. }
  900. }
  901. if (err) {
  902. handle.close();
  903. return err;
  904. }
  905. return handle;
  906. };
  907. Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
  908. debug('listen2', address, port, addressType, backlog);
  909. var self = this;
  910. // If there is not yet a handle, we need to create one and bind.
  911. // In the case of a server sent via IPC, we don't need to do this.
  912. if (!self._handle) {
  913. debug('_listen2: create a handle');
  914. var rval = createServerHandle(address, port, addressType, fd);
  915. if (util.isNumber(rval)) {
  916. var error = errnoException(rval, 'listen');
  917. process.nextTick(function() {
  918. self.emit('error', error);
  919. });
  920. return;
  921. }
  922. self._handle = rval;
  923. } else {
  924. debug('_listen2: have a handle already');
  925. }
  926. self._handle.onconnection = onconnection;
  927. self._handle.owner = self;
  928. var err = _listen(self._handle, backlog);
  929. if (err) {
  930. var ex = errnoException(err, 'listen');
  931. self._handle.close();
  932. self._handle = null;
  933. process.nextTick(function() {
  934. self.emit('error', ex);
  935. });
  936. return;
  937. }
  938. // generate connection key, this should be unique to the connection
  939. this._connectionKey = addressType + ':' + address + ':' + port;
  940. process.nextTick(function() {
  941. // ensure handle hasn't closed
  942. if (self._handle)
  943. self.emit('listening');
  944. });
  945. };
  946. function listen(self, address, port, addressType, backlog, fd, exclusive) {
  947. exclusive = !!exclusive;
  948. if (!cluster) cluster = require('cluster');
  949. if (cluster.isMaster || exclusive) {
  950. self._listen2(address, port, addressType, backlog, fd);
  951. return;
  952. }
  953. cluster._getServer(self, address, port, addressType, fd, cb);
  954. function cb(err, handle) {
  955. // EADDRINUSE may not be reported until we call listen(). To complicate
  956. // matters, a failed bind() followed by listen() will implicitly bind to
  957. // a random port. Ergo, check that the socket is bound to the expected
  958. // port before calling listen().
  959. //
  960. // FIXME(bnoordhuis) Doesn't work for pipe handles, they don't have a
  961. // getsockname() method. Non-issue for now, the cluster module doesn't
  962. // really support pipes anyway.
  963. if (err === 0 && port > 0 && handle.getsockname) {
  964. var out = {};
  965. err = handle.getsockname(out);
  966. if (err === 0 && port !== out.port)
  967. err = uv.UV_EADDRINUSE;
  968. }
  969. if (err)
  970. return self.emit('error', errnoException(err, 'bind'));
  971. self._handle = handle;
  972. self._listen2(address, port, addressType, backlog, fd);
  973. }
  974. }
  975. Server.prototype.listen = function() {
  976. var self = this;
  977. var lastArg = arguments[arguments.length - 1];
  978. if (util.isFunction(lastArg)) {
  979. self.once('listening', lastArg);
  980. }
  981. var port = toNumber(arguments[0]);
  982. // The third optional argument is the backlog size.
  983. // When the ip is omitted it can be the second argument.
  984. var backlog = toNumber(arguments[1]) || toNumber(arguments[2]);
  985. var TCP = process.binding('tcp_wrap').TCP;
  986. if (arguments.length === 0 || util.isFunction(arguments[0])) {
  987. // Bind to a random port.
  988. listen(self, null, 0, null, backlog);
  989. } else if (util.isObject(arguments[0])) {
  990. var h = arguments[0];
  991. h = h._handle || h.handle || h;
  992. if (h instanceof TCP) {
  993. self._handle = h;
  994. listen(self, null, -1, -1, backlog);
  995. } else if (util.isNumber(h.fd) && h.fd >= 0) {
  996. listen(self, null, null, null, backlog, h.fd);
  997. } else {
  998. // The first argument is a configuration object
  999. if (h.backlog)
  1000. backlog = h.backlog;
  1001. if (util.isNumber(h.port)) {
  1002. if (h.host)
  1003. listenAfterLookup(h.port, h.host, backlog, h.exclusive);
  1004. else
  1005. listen(self, null, h.port, 4, backlog, undefined, h.exclusive);
  1006. } else if (h.path && isPipeName(h.path)) {
  1007. var pipeName = self._pipeName = h.path;
  1008. listen(self, pipeName, -1, -1, backlog, undefined, h.exclusive);
  1009. } else {
  1010. throw new Error('Invalid listen argument: ' + h);
  1011. }
  1012. }
  1013. } else if (isPipeName(arguments[0])) {
  1014. // UNIX socket or Windows pipe.
  1015. var pipeName = self._pipeName = arguments[0];
  1016. listen(self, pipeName, -1, -1, backlog);
  1017. } else if (util.isUndefined(arguments[1]) ||
  1018. util.isFunction(arguments[1]) ||
  1019. util.isNumber(arguments[1])) {
  1020. // The first argument is the port, no IP given.
  1021. listen(self, null, port, 4, backlog);
  1022. } else {
  1023. // The first argument is the port, the second an IP.
  1024. listenAfterLookup(port, arguments[1], backlog);
  1025. }
  1026. function listenAfterLookup(port, address, backlog, exclusive) {
  1027. require('dns').lookup(address, function(err, ip, addressType) {
  1028. if (err) {
  1029. self.emit('error', err);
  1030. } else {
  1031. addressType = ip ? addressType : 4;
  1032. listen(self, ip, port, addressType, backlog, undefined, exclusive);
  1033. }
  1034. });
  1035. }
  1036. return self;
  1037. };
  1038. Server.prototype.address = function() {
  1039. if (this._handle && this._handle.getsockname) {
  1040. var out = {};
  1041. var err = this._handle.getsockname(out);
  1042. // TODO(bnoordhuis) Check err and throw?
  1043. return out;
  1044. } else if (this._pipeName) {
  1045. return this._pipeName;
  1046. } else {
  1047. return null;
  1048. }
  1049. };
  1050. function onconnection(err, clientHandle) {
  1051. var handle = this;
  1052. var self = handle.owner;
  1053. debug('onconnection');
  1054. if (err) {
  1055. self.emit('error', errnoException(err, 'accept'));
  1056. return;
  1057. }
  1058. if (self.maxConnections && self._connections >= self.maxConnections) {
  1059. clientHandle.close();
  1060. return;
  1061. }
  1062. var socket = new Socket({
  1063. handle: clientHandle,
  1064. allowHalfOpen: self.allowHalfOpen,
  1065. pauseOnCreate: self.pauseOnConnect
  1066. });
  1067. socket.readable = socket.writable = true;
  1068. self._connections++;
  1069. socket.server = self;
  1070. DTRACE_NET_SERVER_CONNECTION(socket);
  1071. COUNTER_NET_SERVER_CONNECTION(socket);
  1072. self.emit('connection', socket);
  1073. }
  1074. Server.prototype.getConnections = function(cb) {
  1075. function end(err, connections) {
  1076. process.nextTick(function() {
  1077. cb(err, connections);
  1078. });
  1079. }
  1080. if (!this._usingSlaves) {
  1081. return end(null, this._connections);
  1082. }
  1083. // Poll slaves
  1084. var left = this._slaves.length,
  1085. total = this._connections;
  1086. function oncount(err, count) {
  1087. if (err) {
  1088. left = -1;
  1089. return end(err);
  1090. }
  1091. total += count;
  1092. if (--left === 0) return end(null, total);
  1093. }
  1094. this._slaves.forEach(function(slave) {
  1095. slave.getConnections(oncount);
  1096. });
  1097. };
  1098. Server.prototype.close = function(cb) {
  1099. function onSlaveClose() {
  1100. if (--left !== 0) return;
  1101. self._connections = 0;
  1102. self._emitCloseIfDrained();
  1103. }
  1104. if (cb) {
  1105. if (!this._handle) {
  1106. this.once('close', function() {
  1107. cb(new Error('Not running'));
  1108. });
  1109. } else {
  1110. this.once('close', cb);
  1111. }
  1112. }
  1113. if (this._handle) {
  1114. this._handle.close();
  1115. this._handle = null;
  1116. }
  1117. if (this._usingSlaves) {
  1118. var self = this,
  1119. left = this._slaves.length;
  1120. // Increment connections to be sure that, even if all sockets will be closed
  1121. // during polling of slaves, `close` event will be emitted only once.
  1122. this._connections++;
  1123. // Poll slaves
  1124. this._slaves.forEach(function(slave) {
  1125. slave.close(onSlaveClose);
  1126. });
  1127. } else {
  1128. this._emitCloseIfDrained();
  1129. }
  1130. return this;
  1131. };
  1132. Server.prototype._emitCloseIfDrained = function() {
  1133. debug('SERVER _emitCloseIfDrained');
  1134. var self = this;
  1135. if (self._handle || self._connections) {
  1136. debug('SERVER handle? %j connections? %d',
  1137. !!self._handle, self._connections);
  1138. return;
  1139. }
  1140. process.nextTick(function() {
  1141. debug('SERVER: emit close');
  1142. self.emit('close');
  1143. });
  1144. };
  1145. Server.prototype.listenFD = util.deprecate(function(fd, type) {
  1146. return this.listen({ fd: fd });
  1147. }, 'listenFD is deprecated. Use listen({fd: <number>}).');
  1148. Server.prototype._setupSlave = function(socketList) {
  1149. this._usingSlaves = true;
  1150. this._slaves.push(socketList);
  1151. };
  1152. Server.prototype.ref = function() {
  1153. if (this._handle)
  1154. this._handle.ref();
  1155. };
  1156. Server.prototype.unref = function() {
  1157. if (this._handle)
  1158. this._handle.unref();
  1159. };
  1160. // TODO: isIP should be moved to the DNS code. Putting it here now because
  1161. // this is what the legacy system did.
  1162. exports.isIP = cares.isIP;
  1163. exports.isIPv4 = function(input) {
  1164. return exports.isIP(input) === 4;
  1165. };
  1166. exports.isIPv6 = function(input) {
  1167. return exports.isIP(input) === 6;
  1168. };
  1169. if (process.platform === 'win32') {
  1170. var simultaneousAccepts;
  1171. exports._setSimultaneousAccepts = function(handle) {
  1172. if (util.isUndefined(handle)) {
  1173. return;
  1174. }
  1175. if (util.isUndefined(simultaneousAccepts)) {
  1176. simultaneousAccepts = (process.env.NODE_MANY_ACCEPTS &&
  1177. process.env.NODE_MANY_ACCEPTS !== '0');
  1178. }
  1179. if (handle._simultaneousAccepts !== simultaneousAccepts) {
  1180. handle.setSimultaneousAccepts(simultaneousAccepts);
  1181. handle._simultaneousAccepts = simultaneousAccepts;
  1182. }
  1183. };
  1184. } else {
  1185. exports._setSimultaneousAccepts = function(handle) {};
  1186. }