All files / lib/internal/inspector inspect_client.js

89.29% Statements 325/364
78.69% Branches 48/61
100% Functions 15/15
89.29% Lines 325/364

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 36530x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 1x 1x 1x 1x 1x 1x 30x 435x 435x 435x 435x 435x 435x 435x 435x               435x 21x 21x 21x 21x 435x 414x 414x 414x 435x 435x 435x 435x 435x 435x 435x 435x 435x 28995x 28995x 435x 435x 435x 30x 3663x 3663x 3663x 3663x 3663x 3663x 3663x 3663x 3663x 3663x 3663x 3663x 3663x 3663x 3663x 3663x 3663x     3663x     3663x 3663x     3663x 3663x 3663x 3663x     3663x 3663x 3663x   3663x 3663x 3663x 3663x 3663x 3184x 3184x 3184x 3663x 3663x 60x 60x 60x 480x 480x 480x 60x 3663x 3663x 3663x 3663x 3663x 3633x 3633x 3633x 3633x 3633x 3633x 3633x 3663x 30x 30x 30x 27x 27x 27x 27x 27x 27x 27x 27x 30x 30x 702x 702x 702x 3663x 3663x 3663x 3663x 3663x 3663x 3663x 3663x       3663x 3633x 3633x 3633x 3633x 3663x     3633x 3633x 3633x 3663x       3633x 3633x 3663x 429x 429x 429x 429x 429x 3663x 3204x 3204x 3204x     3663x 702x 30x 30x 122x 32x 32x 122x 32x 32x 122x 122x 122x 122x 122x 122x 30x 30x 437x 437x 2x 2x 2x 435x 435x 429x 428x 435x 435x 435x 435x 437x 437x 30x 30x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 32x 32x 32x       32x 32x 32x       32x 32x 32x 32x 32x 32x 37x 37x 37x 37x 37x 30x 30x 37x 37x 37x 32x 37x 30x 30x 37x 32x 37x 30x 30x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x   32x 32x             32x 32x 32x 32x 32x 32x 32x 32x 32x 7x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 30x 30x 30x  
/*
 * Copyright Node.js contributors. All rights reserved.
 *
 * 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.
 */
 
// TODO(aduh95): use errors exported by the internal/errors module
/* eslint-disable no-restricted-syntax */
 
'use strict';
 
const {
  ArrayPrototypePush,
  Error,
  ErrorCaptureStackTrace,
  FunctionPrototypeBind,
  JSONParse,
  JSONStringify,
  ObjectKeys,
  Promise,
} = primordials;
 
const Buffer = require('buffer').Buffer;
const { EventEmitter } = require('events');
const http = require('http');
const URL = require('url');
 
const debuglog = require('internal/util/debuglog').debuglog('inspect');
 
const kOpCodeText = 0x1;
const kOpCodeClose = 0x8;
 
const kFinalBit = 0x80;
const kReserved1Bit = 0x40;
const kReserved2Bit = 0x20;
const kReserved3Bit = 0x10;
const kOpCodeMask = 0xF;
const kMaskBit = 0x80;
const kPayloadLengthMask = 0x7F;
 
const kMaxSingleBytePayloadLength = 125;
const kMaxTwoBytePayloadLength = 0xFFFF;
const kTwoBytePayloadLengthField = 126;
const kEightBytePayloadLengthField = 127;
const kMaskingKeyWidthInBytes = 4;
 
function unpackError({ code, message, data }) {
  const err = new Error(`${message} - ${data}`);
  err.code = code;
  ErrorCaptureStackTrace(err, unpackError);
  return err;
}
 
function encodeFrameHybi17(payload) {
  var i;
 
  const dataLength = payload.length;
 
  let singleByteLength;
  let additionalLength;
  if (dataLength > kMaxTwoBytePayloadLength) {
    singleByteLength = kEightBytePayloadLengthField;
    additionalLength = Buffer.alloc(8);
    let remaining = dataLength;
    for (i = 0; i < 8; ++i) {
      additionalLength[7 - i] = remaining & 0xFF;
      remaining >>= 8;
    }
  } else if (dataLength > kMaxSingleBytePayloadLength) {
    singleByteLength = kTwoBytePayloadLengthField;
    additionalLength = Buffer.alloc(2);
    additionalLength[0] = (dataLength & 0xFF00) >> 8;
    additionalLength[1] = dataLength & 0xFF;
  } else {
    additionalLength = Buffer.alloc(0);
    singleByteLength = dataLength;
  }
 
  const header = Buffer.from([
    kFinalBit | kOpCodeText,
    kMaskBit | singleByteLength,
  ]);
 
  const mask = Buffer.alloc(4);
  const masked = Buffer.alloc(dataLength);
  for (i = 0; i < dataLength; ++i) {
    masked[i] = payload[i] ^ mask[i % kMaskingKeyWidthInBytes];
  }
 
  return Buffer.concat([header, additionalLength, mask, masked]);
}
 
function decodeFrameHybi17(data) {
  const dataAvailable = data.length;
  const notComplete = { closed: false, payload: null, rest: data };
  let payloadOffset = 2;
  if ((dataAvailable - payloadOffset) < 0) return notComplete;
 
  const firstByte = data[0];
  const secondByte = data[1];
 
  const final = (firstByte & kFinalBit) !== 0;
  const reserved1 = (firstByte & kReserved1Bit) !== 0;
  const reserved2 = (firstByte & kReserved2Bit) !== 0;
  const reserved3 = (firstByte & kReserved3Bit) !== 0;
  const opCode = firstByte & kOpCodeMask;
  const masked = (secondByte & kMaskBit) !== 0;
  const compressed = reserved1;
  if (compressed) {
    throw new Error('Compressed frames not supported');
  }
  if (!final || reserved2 || reserved3) {
    throw new Error('Only compression extension is supported');
  }
 
  if (masked) {
    throw new Error('Masked server frame - not supported');
  }
 
  let closed = false;
  switch (opCode) {
    case kOpCodeClose:
      closed = true;
      break;
    case kOpCodeText:
      break;
    default:
      throw new Error(`Unsupported op code ${opCode}`);
  }
 
  let payloadLength = secondByte & kPayloadLengthMask;
  switch (payloadLength) {
    case kTwoBytePayloadLengthField:
      payloadOffset += 2;
      payloadLength = (data[2] << 8) + data[3];
      break;
 
    case kEightBytePayloadLengthField:
      payloadOffset += 8;
      payloadLength = 0;
      for (var i = 0; i < 8; ++i) {
        payloadLength <<= 8;
        payloadLength |= data[2 + i];
      }
      break;
 
    default:
      // Nothing. We already have the right size.
  }
  if ((dataAvailable - payloadOffset - payloadLength) < 0) return notComplete;
 
  const payloadEnd = payloadOffset + payloadLength;
  return {
    payload: data.slice(payloadOffset, payloadEnd),
    rest: data.slice(payloadEnd),
    closed,
  };
}
 
class Client extends EventEmitter {
  constructor() {
    super();
    this.handleChunk = FunctionPrototypeBind(this._handleChunk, this);
 
    this._port = undefined;
    this._host = undefined;
 
    this.reset();
  }
 
  _handleChunk(chunk) {
    this._unprocessed = Buffer.concat([this._unprocessed, chunk]);
 
    while (this._unprocessed.length > 2) {
      const {
        closed,
        payload: payloadBuffer,
        rest
      } = decodeFrameHybi17(this._unprocessed);
      this._unprocessed = rest;
 
      if (closed) {
        this.reset();
        return;
      }
      if (payloadBuffer === null || payloadBuffer.length === 0) break;
 
      const payloadStr = payloadBuffer.toString();
      debuglog('< %s', payloadStr);
      const lastChar = payloadStr[payloadStr.length - 1];
      if (payloadStr[0] !== '{' || lastChar !== '}') {
        throw new Error(`Payload does not look like JSON: ${payloadStr}`);
      }
      let payload;
      try {
        payload = JSONParse(payloadStr);
      } catch (parseError) {
        parseError.string = payloadStr;
        throw parseError;
      }
 
      const { id, method, params, result, error } = payload;
      if (id) {
        const handler = this._pending[id];
        if (handler) {
          delete this._pending[id];
          handler(error, result);
        }
      } else if (method) {
        this.emit('debugEvent', method, params);
        this.emit(method, params);
      } else {
        throw new Error(`Unsupported response: ${payloadStr}`);
      }
    }
  }
 
  reset() {
    if (this._http) {
      this._http.destroy();
    }
    if (this._socket) {
      this._socket.destroy();
    }
    this._http = null;
    this._lastId = 0;
    this._socket = null;
    this._pending = {};
    this._unprocessed = Buffer.alloc(0);
  }
 
  callMethod(method, params) {
    return new Promise((resolve, reject) => {
      if (!this._socket) {
        reject(new Error('Use `run` to start the app again.'));
        return;
      }
      const data = { id: ++this._lastId, method, params };
      this._pending[data.id] = (error, result) => {
        if (error) reject(unpackError(error));
        else resolve(ObjectKeys(result).length ? result : undefined);
      };
      const json = JSONStringify(data);
      debuglog('> %s', json);
      this._socket.write(encodeFrameHybi17(Buffer.from(json)));
    });
  }
 
  _fetchJSON(urlPath) {
    return new Promise((resolve, reject) => {
      const httpReq = http.get({
        host: this._host,
        port: this._port,
        path: urlPath,
      });
 
      const chunks = [];
 
      function onResponse(httpRes) {
        function parseChunks() {
          const resBody = Buffer.concat(chunks).toString();
          if (httpRes.statusCode !== 200) {
            reject(new Error(`Unexpected ${httpRes.statusCode}: ${resBody}`));
            return;
          }
          try {
            resolve(JSONParse(resBody));
          } catch {
            reject(new Error(`Response didn't contain JSON: ${resBody}`));

          }
        }
 
        httpRes.on('error', reject);
        httpRes.on('data', (chunk) => ArrayPrototypePush(chunks, chunk));
        httpRes.on('end', parseChunks);
      }
 
      httpReq.on('error', reject);
      httpReq.on('response', onResponse);
    });
  }
 
  async connect(port, host) {
    this._port = port;
    this._host = host;
    const urlPath = await this._discoverWebsocketPath();
    return this._connectWebsocket(urlPath);
  }
 
  async _discoverWebsocketPath() {
    const { 0: { webSocketDebuggerUrl } } = await this._fetchJSON('/json');
    return URL.parse(webSocketDebuggerUrl).path;
  }
 
  _connectWebsocket(urlPath) {
    this.reset();
 
    const key1 = require('crypto').randomBytes(16).toString('base64');
    debuglog('request websocket', key1);
 
    const httpReq = this._http = http.request({
      host: this._host,
      port: this._port,
      path: urlPath,
      headers: {
        'Connection': 'Upgrade',
        'Upgrade': 'websocket',
        'Sec-WebSocket-Key': key1,
        'Sec-WebSocket-Version': '13',
      },
    });
    httpReq.on('error', (e) => {
      this.emit('error', e);
    });
    httpReq.on('response', (httpRes) => {
      if (httpRes.statusCode >= 400) {
        process.stderr.write(`Unexpected HTTP code: ${httpRes.statusCode}\n`);
        httpRes.pipe(process.stderr);
      } else {
        httpRes.pipe(process.stderr);
      }
    });
 
    const handshakeListener = (res, socket) => {
      // TODO: we *could* validate res.headers[sec-websocket-accept]
      debuglog('websocket upgrade');
 
      this._socket = socket;
      socket.on('data', this.handleChunk);
      socket.on('close', () => {
        this.emit('close');
      });
 
      this.emit('ready');
    };
 
    return new Promise((resolve, reject) => {
      this.once('error', reject);
      this.once('ready', resolve);
 
      httpReq.on('upgrade', handshakeListener);
      httpReq.end();
    });
  }
}
 
module.exports = Client;