parse-proxy-response.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. const debug_1 = __importDefault(require("debug"));
  7. const debug = debug_1.default('https-proxy-agent:parse-proxy-response');
  8. function parseProxyResponse(socket) {
  9. return new Promise((resolve, reject) => {
  10. // we need to buffer any HTTP traffic that happens with the proxy before we get
  11. // the CONNECT response, so that if the response is anything other than an "200"
  12. // response code, then we can re-play the "data" events on the socket once the
  13. // HTTP parser is hooked up...
  14. let buffersLength = 0;
  15. const buffers = [];
  16. function read() {
  17. const b = socket.read();
  18. if (b)
  19. ondata(b);
  20. else
  21. socket.once('readable', read);
  22. }
  23. function cleanup() {
  24. socket.removeListener('end', onend);
  25. socket.removeListener('error', onerror);
  26. socket.removeListener('close', onclose);
  27. socket.removeListener('readable', read);
  28. }
  29. function onclose(err) {
  30. debug('onclose had error %o', err);
  31. }
  32. function onend() {
  33. debug('onend');
  34. }
  35. function onerror(err) {
  36. cleanup();
  37. debug('onerror %o', err);
  38. reject(err);
  39. }
  40. function ondata(b) {
  41. buffers.push(b);
  42. buffersLength += b.length;
  43. const buffered = Buffer.concat(buffers, buffersLength);
  44. const endOfHeaders = buffered.indexOf('\r\n\r\n');
  45. if (endOfHeaders === -1) {
  46. // keep buffering
  47. debug('have not received end of HTTP headers yet...');
  48. read();
  49. return;
  50. }
  51. const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n'));
  52. const statusCode = +firstLine.split(' ')[1];
  53. debug('got proxy server response: %o', firstLine);
  54. resolve({
  55. statusCode,
  56. buffered
  57. });
  58. }
  59. socket.on('error', onerror);
  60. socket.on('close', onclose);
  61. socket.on('end', onend);
  62. read();
  63. });
  64. }
  65. exports.default = parseProxyResponse;
  66. //# sourceMappingURL=parse-proxy-response.js.map