All files / lib _http_agent.js

99.11% Statements 443/447
97.48% Branches 116/119
100% Functions 22/22
99.11% Lines 443/447

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 44810x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 10x 10x 793x 793x 793x 789x 789x 789x 789x 789x 789x 789x 789x 789x 789x 789x 789x 789x 793x 793x 793x 793x 793x 793x 336x 336x 336x 336x 336x 162x 162x 162x 21x 21x 21x 331x 174x 174x 174x 174x 174x 174x 174x 108x 108x 108x 108x 108x 108x 108x 6x 108x 100x 100x 100x 100x 100x 100x 100x 100x 77x 77x 100x 100x 102x 2x 2x 2x 174x 66x 66x 174x 793x 793x 793x 793x 793x 10x 10x 10x 9x 9x 1x 1x 1x 1x 10x 1x 1x 1x     1x 9x 10x 10x 10x 10x 10x 10x 10x 6546x 6546x 6546x 6546x 6546x 6546x 6546x 6546x 6546x 6546x 6546x 6546x 6546x 6546x 6546x 6546x 6546x 6546x 6546x 10x 10x 10x 2157x 2157x 2157x 1x 1x 1x 1x 1x 1x 2157x 2157x 2157x 2157x 2157x 2157x 2157x 2156x 2156x 2156x 436x 436x 2156x 2156x 2156x 2156x 34x 2x 2x 34x 34x 34x 34x 2156x 2157x 2157x 2157x 2157x 32x 32x 32x 30x 30x 30x 30x 32x 32x 32x 32x 2148x 1960x 1960x 1960x 2106x 164x 164x 164x 22x 22x 164x 164x 10x 10x 10x 1976x 1976x 1976x 1976x 1976x 1976x 1976x 1976x 1976x 1976x 1976x 1976x 1976x 1976x 1976x 3777x 3777x 1976x 1976x 3777x 3777x 12x 12x 1960x 1960x 1960x 1960x 1976x 1976x 1976x 1976x 1976x 10x 10x 2131x 2131x 2131x 2131x 2118x 1x 1x 1x 2117x 2117x 2117x 2117x 2117x 2117x 1x 1x     1x 1x 1x 2117x 2116x 2116x 2118x 2130x 2130x 2130x 2130x 2131x 10x 1960x 1960x 336x 336x 336x 1960x 1960x 1960x 1914x 1914x 1914x 1914x 1914x 1914x 1960x 1960x 1960x 504x 504x 504x 504x 504x 504x 1x 1x 1x 1x 504x 1960x 1960x 1960x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 1960x 1960x 1960x 2x 2x 1960x 10x 10x 2049x 2049x 2049x 2049x 2049x 2049x 2049x 2049x 2049x 3964x 2055x 2055x 2047x 2047x 2047x 2047x 2047x 2055x 3964x 2049x 2049x 16x 16x 16x 16x 16x 16x 10x 10x 10x 100x 100x 100x 100x 10x 10x 10x 32x 32x 32x 10x 10x 10x 23x 46x 29x 80x 80x 29x 46x 10x 10x 1976x 1976x 1976x 16x 16x 16x 1960x 1960x 16x 16x 1976x 1976x 10x 2138x 2138x 2138x 2138x 2132x 2132x 6x 2138x 10x 16x 16x 16x 10x 10x 10x 10x 10x  
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
'use strict';
 
const {
  ObjectKeys,
  ObjectSetPrototypeOf,
  ObjectValues,
  Symbol,
} = primordials;
 
const net = require('net');
const EventEmitter = require('events');
const debug = require('internal/util/debuglog').debuglog('http');
const { async_id_symbol } = require('internal/async_hooks').symbols;
const {
  codes: {
    ERR_INVALID_ARG_TYPE,
  },
} = require('internal/errors');
const kOnKeylog = Symbol('onkeylog');
// New Agent code.
 
// The largest departure from the previous implementation is that
// an Agent instance holds connections for a variable number of host:ports.
// Surprisingly, this is still API compatible as far as third parties are
// concerned. The only code that really notices the difference is the
// request object.
 
// Another departure is that all code related to HTTP parsing is in
// ClientRequest.onSocket(). The Agent is now *strictly*
// concerned with managing a connection pool.
 
const kReusedHandle = Symbol('kReusedHandle');
class ReusedHandle {
  constructor(type, handle) {
    this.type = type;
    this.handle = handle;
    // We need keep the resource object alive from this object, because
    // domains rely on GC of the resource object for lifetime tracking.
    // TODO(addaleax): This should really apply to all uses of
    // AsyncWrap::AsyncReset() when the resource is not the AsyncWrap object
    // itself. However, HTTPClientAsyncResource and HTTPServerAsyncResource
    // hold on to other objects, inhibiting GC.
    handle[kReusedHandle] = this;
  }
}
 
function Agent(options) {
  if (!(this instanceof Agent))
    return new Agent(options);
 
  EventEmitter.call(this);
 
  this.defaultPort = 80;
  this.protocol = 'http:';
 
  this.options = { ...options };
 
  // Don't confuse net and make it think that we're connecting to a pipe
  this.options.path = null;
  this.requests = {};
  this.sockets = {};
  this.freeSockets = {};
  this.keepAliveMsecs = this.options.keepAliveMsecs || 1000;
  this.keepAlive = this.options.keepAlive || false;
  this.maxSockets = this.options.maxSockets || Agent.defaultMaxSockets;
  this.maxFreeSockets = this.options.maxFreeSockets || 256;
 
  this.on('free', (socket, options) => {
    const name = this.getName(options);
    debug('agent.on(free)', name);
 
    if (socket.writable &&
        this.requests[name] && this.requests[name].length) {
      const req = this.requests[name].shift();
      setRequestSocket(this, req, socket);
      if (this.requests[name].length === 0) {
        // don't leak
        delete this.requests[name];
      }
    } else {
      // If there are no pending requests, then put it in
      // the freeSockets pool, but only if we're allowed to do so.
      const req = socket._httpMessage;
      if (req &&
          req.shouldKeepAlive &&
          socket.writable &&
          this.keepAlive) {
        let freeSockets = this.freeSockets[name];
        const freeLen = freeSockets ? freeSockets.length : 0;
        let count = freeLen;
        if (this.sockets[name])
          count += this.sockets[name].length;
 
        if (count > this.maxSockets || freeLen >= this.maxFreeSockets) {
          socket.destroy();
        } else if (this.keepSocketAlive(socket)) {
          freeSockets = freeSockets || [];
          this.freeSockets[name] = freeSockets;
          socket[async_id_symbol] = -1;
          socket._httpMessage = null;
          this.removeSocket(socket, options);
 
          const agentTimeout = this.options.timeout || 0;
          if (socket.timeout !== agentTimeout) {
            socket.setTimeout(agentTimeout);
          }
 
          freeSockets.push(socket);
        } else {
          // Implementation doesn't want to keep socket alive
          socket.destroy();
        }
      } else {
        socket.destroy();
      }
    }
  });
 
  // Don't emit keylog events unless there is a listener for them.
  this.on('newListener', maybeEnableKeylog);
}
ObjectSetPrototypeOf(Agent.prototype, EventEmitter.prototype);
ObjectSetPrototypeOf(Agent, EventEmitter);
 
function maybeEnableKeylog(eventName) {
  if (eventName === 'keylog') {
    this.removeListener('newListener', maybeEnableKeylog);
    // Future sockets will listen on keylog at creation.
    const agent = this;
    this[kOnKeylog] = function onkeylog(keylog) {
      agent.emit('keylog', keylog, this);
    };
    // Existing sockets will start listening on keylog now.
    for (const socket of ObjectValues(this.sockets)) {
      socket.on('keylog', this[kOnKeylog]);
    }
  }
}
 
Agent.defaultMaxSockets = Infinity;
 
Agent.prototype.createConnection = net.createConnection;
 
// Get the key for a given set of request options
Agent.prototype.getName = function getName(options) {
  let name = options.host || 'localhost';
 
  name += ':';
  if (options.port)
    name += options.port;
 
  name += ':';
  if (options.localAddress)
    name += options.localAddress;
 
  // Pacify parallel/test-http-agent-getname by only appending
  // the ':' when options.family is set.
  if (options.family === 4 || options.family === 6)
    name += `:${options.family}`;
 
  if (options.socketPath)
    name += `:${options.socketPath}`;
 
  return name;
};
 
Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */,
                                                 localAddress/* legacy */) {
  // Legacy API: addRequest(req, host, port, localAddress)
  if (typeof options === 'string') {
    options = {
      host: options,
      port,
      localAddress
    };
  }
 
  options = { ...options, ...this.options };
  if (options.socketPath)
    options.path = options.socketPath;
 
  if (!options.servername && options.servername !== '')
    options.servername = calculateServerName(options, req);
 
  const name = this.getName(options);
  if (!this.sockets[name]) {
    this.sockets[name] = [];
  }
 
  const freeSockets = this.freeSockets[name];
  let socket;
  if (freeSockets) {
    while (freeSockets.length && freeSockets[0].destroyed) {
      freeSockets.shift();
    }
    socket = freeSockets.shift();
    if (!freeSockets.length)
      delete this.freeSockets[name];
  }
 
  const freeLen = freeSockets ? freeSockets.length : 0;
  const sockLen = freeLen + this.sockets[name].length;
 
  if (socket) {
    // Guard against an uninitialized or user supplied Socket.
    const handle = socket._handle;
    if (handle && typeof handle.asyncReset === 'function') {
      // Assign the handle a new asyncId and run any destroy()/init() hooks.
      handle.asyncReset(new ReusedHandle(handle.getProviderType(), handle));
      socket[async_id_symbol] = handle.getAsyncId();
    }
 
    this.reuseSocket(socket, req);
    setRequestSocket(this, req, socket);
    this.sockets[name].push(socket);
  } else if (sockLen < this.maxSockets) {
    debug('call onSocket', sockLen, freeLen);
    // If we are under maxSockets create a new one.
    this.createSocket(req, options, handleSocketCreation(this, req, true));
  } else {
    debug('wait for socket');
    // We are over limit so we'll add it to the queue.
    if (!this.requests[name]) {
      this.requests[name] = [];
    }
    this.requests[name].push(req);
  }
};
 
Agent.prototype.createSocket = function createSocket(req, options, cb) {
  options = { ...options, ...this.options };
  if (options.socketPath)
    options.path = options.socketPath;
 
  if (!options.servername && options.servername !== '')
    options.servername = calculateServerName(options, req);
 
  const name = this.getName(options);
  options._agentKey = name;
 
  debug('createConnection', name, options);
  options.encoding = null;
  let called = false;
 
  const oncreate = (err, s) => {
    if (called)
      return;
    called = true;
    if (err)
      return cb(err);
    if (!this.sockets[name]) {
      this.sockets[name] = [];
    }
    this.sockets[name].push(s);
    debug('sockets', name, this.sockets[name].length);
    installListeners(this, s, options);
    cb(null, s);
  };
 
  const newSocket = this.createConnection(options, oncreate);
  if (newSocket)
    oncreate(null, newSocket);
};
 
function calculateServerName(options, req) {
  let servername = options.host;
  const hostHeader = req.getHeader('host');
  if (hostHeader) {
    if (typeof hostHeader !== 'string') {
      throw new ERR_INVALID_ARG_TYPE('options.headers.host',
                                     'String', hostHeader);
    }
 
    // abc => abc
    // abc:123 => abc
    // [::1] => ::1
    // [::1]:123 => ::1
    if (hostHeader.startsWith('[')) {
      const index = hostHeader.indexOf(']');
      if (index === -1) {
        // Leading '[', but no ']'. Need to do something...
        servername = hostHeader;
      } else {
        servername = hostHeader.substr(1, index - 1);
      }
    } else {
      servername = hostHeader.split(':', 1)[0];
    }
  }
  // Don't implicitly set invalid (IP) servernames.
  if (net.isIP(servername))
    servername = '';
  return servername;
}
 
function installListeners(agent, s, options) {
  function onFree() {
    debug('CLIENT socket onFree');
    agent.emit('free', s, options);
  }
  s.on('free', onFree);
 
  function onClose(err) {
    debug('CLIENT socket onClose');
    // This is the only place where sockets get removed from the Agent.
    // If you want to remove a socket from the pool, just close it.
    // All socket errors end in a close event anyway.
    agent.removeSocket(s, options);
  }
  s.on('close', onClose);
 
  function onTimeout() {
    debug('CLIENT socket onTimeout');
 
    // Destroy if in free list.
    // TODO(ronag): Always destroy, even if not in free list.
    const sockets = agent.freeSockets;
    for (const name of ObjectKeys(sockets)) {
      if (sockets[name].includes(s)) {
        return s.destroy();
      }
    }
  }
  s.on('timeout', onTimeout);
 
  function onRemove() {
    // We need this function for cases like HTTP 'upgrade'
    // (defined by WebSockets) where we need to remove a socket from the
    // pool because it'll be locked up indefinitely
    debug('CLIENT socket onRemove');
    agent.removeSocket(s, options);
    s.removeListener('close', onClose);
    s.removeListener('free', onFree);
    s.removeListener('timeout', onTimeout);
    s.removeListener('agentRemove', onRemove);
  }
  s.on('agentRemove', onRemove);
 
  if (agent[kOnKeylog]) {
    s.on('keylog', agent[kOnKeylog]);
  }
}
 
Agent.prototype.removeSocket = function removeSocket(s, options) {
  const name = this.getName(options);
  debug('removeSocket', name, 'writable:', s.writable);
  const sets = [this.sockets];
 
  // If the socket was destroyed, remove it from the free buffers too.
  if (!s.writable)
    sets.push(this.freeSockets);
 
  for (const sockets of sets) {
    if (sockets[name]) {
      const index = sockets[name].indexOf(s);
      if (index !== -1) {
        sockets[name].splice(index, 1);
        // Don't leak
        if (sockets[name].length === 0)
          delete sockets[name];
      }
    }
  }
 
  if (this.requests[name] && this.requests[name].length) {
    debug('removeSocket, have a request, make a socket');
    const req = this.requests[name][0];
    // If we have pending requests and a socket gets closed make a new one
    const socketCreationHandler = handleSocketCreation(this, req, false);
    this.createSocket(req, options, socketCreationHandler);
  }
};
 
Agent.prototype.keepSocketAlive = function keepSocketAlive(socket) {
  socket.setKeepAlive(true, this.keepAliveMsecs);
  socket.unref();
 
  return true;
};
 
Agent.prototype.reuseSocket = function reuseSocket(socket, req) {
  debug('have free socket');
  req.reusedSocket = true;
  socket.ref();
};
 
Agent.prototype.destroy = function destroy() {
  for (const set of [this.freeSockets, this.sockets]) {
    for (const key of ObjectKeys(set)) {
      for (const setName of set[key]) {
        setName.destroy();
      }
    }
  }
};
 
function handleSocketCreation(agent, request, informRequest) {
  return function handleSocketCreation_Inner(err, socket) {
    if (err) {
      process.nextTick(emitErrorNT, request, err);
      return;
    }
    if (informRequest)
      setRequestSocket(agent, request, socket);
    else
      socket.emit('free');
  };
}
 
function setRequestSocket(agent, req, socket) {
  req.onSocket(socket);
  const agentTimeout = agent.options.timeout || 0;
  if (req.timeout === undefined || req.timeout === agentTimeout) {
    return;
  }
  socket.setTimeout(req.timeout);
}
 
function emitErrorNT(emitter, err) {
  emitter.emit('error', err);
}
 
module.exports = {
  Agent,
  globalAgent: new Agent()
};