summaryrefslogtreecommitdiff
path: root/school/node_modules/jsdom/lib/jsdom/living/helpers/http-request.js
blob: 616a806758e6971953419c16c6829f56c3a8fac3 (plain)
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
"use strict";
const http = require("http");
const https = require("https");
const { Writable } = require("stream");
const zlib = require("zlib");

const ver = process.version.replace("v", "").split(".");
const majorNodeVersion = Number.parseInt(ver[0]);

function abortRequest(clientRequest) {
  // clientRequest.destroy breaks the test suite for versions 10 and 12,
  // hence the version check
  if (majorNodeVersion > 13) {
    clientRequest.destroy();
  } else {
    clientRequest.abort();
  }
  clientRequest.removeAllListeners();
  clientRequest.on("error", () => {});
}

module.exports = class Request extends Writable {
  constructor(url, clientOptions, requestOptions) {
    super();
    Object.assign(this, clientOptions);
    this.currentURL = url;
    this._requestOptions = requestOptions;
    this.headers = requestOptions.headers;
    this._ended = false;
    this._redirectCount = 0;
    this._requestBodyBuffers = [];
    this._bufferIndex = 0;
    this._performRequest();
  }

  abort() {
    abortRequest(this._currentRequest);
    this.emit("abort");
    this.removeAllListeners();
  }

  pipeRequest(form) {
    form.pipe(this._currentRequest);
  }

  write(data, encoding) {
    if (data.length > 0) {
      this._requestBodyBuffers.push({ data, encoding });
      this._currentRequest.write(data, encoding);
    }
  }

  end() {
    this.emit("request", this._currentRequest);
    this._ended = true;
    this._currentRequest.end();
  }

  setHeader(name, value) {
    this.headers[name] = value;
    this._currentRequest.setHeader(name, value);
  }

  removeHeader(name) {
    delete this.headers[name];
    this._currentRequest.removeHeader(name);
  }

  // Without this method, the test send-redirect-infinite-sync will halt the test suite
  // TODO: investigate this further and ideally remove
  toJSON() {
    const { method, headers } = this._requestOptions;
    return { uri: new URL(this.currentURL), method, headers };
  }

  _writeNext(error) {
    if (this._currentRequest) {
      if (error) {
        this.emit("error", error);
      } else if (this._bufferIndex < this._requestBodyBuffers.length) {
        const buffer = this._requestBodyBuffers[this._bufferIndex++];
        if (!this._currentRequest.writableEnded) {
          this._currentRequest.write(
            buffer.data,
            buffer.encoding,
            this._writeNext.bind(this)
          );
        }
      } else if (this._ended) {
        this._currentRequest.end();
      }
    }
  }

  _performRequest() {
    const urlOptions = new URL(this.currentURL);
    const scheme = urlOptions.protocol;
    this._requestOptions.agent = this.agents[scheme.substring(0, scheme.length - 1)];
    const { request } = scheme === "https:" ? https : http;
    this._currentRequest = request(this.currentURL, this._requestOptions, response => {
      this._processResponse(response);
    });

    let cookies;
    if (this._redirectCount === 0) {
      this.originalCookieHeader = this.getHeader("Cookie");
    }
    if (this.cookieJar) {
      cookies = this.cookieJar.getCookieStringSync(this.currentURL);
    }
    if (cookies && cookies.length) {
      if (this.originalCookieHeader) {
        this.setHeader("Cookie", this.originalCookieHeader + "; " + cookies);
      } else {
        this.setHeader("Cookie", cookies);
      }
    }

    for (const event of ["connect", "error", "socket", "timeout"]) {
      this._currentRequest.on(event, (...args) => {
        this.emit(event, ...args);
      });
    }
    if (this._isRedirect) {
      this._bufferIndex = 0;
      this._writeNext();
    }
  }

  _processResponse(response) {
    const cookies = response.headers["set-cookie"];
    if (this.cookieJar && Array.isArray(cookies)) {
      try {
        cookies.forEach(cookie => {
          this.cookieJar.setCookieSync(cookie, this.currentURL, { ignoreError: true });
        });
      } catch (e) {
        this.emit("error", e);
      }
    }

    const { statusCode } = response;
    const { location } = response.headers;
    // In Node v15, aborting a message with remaining data causes an error to be thrown,
    // hence the version check
    const catchResErrors = err => {
      if (!(majorNodeVersion >= 15 && err.message === "aborted")) {
        this.emit("error", err);
      }
    };
    response.on("error", catchResErrors);
    let redirectAddress = null;
    let resendWithAuth = false;
    if (typeof location === "string" &&
      location.length &&
      this.followRedirects &&
      statusCode >= 300 &&
      statusCode < 400) {
      redirectAddress = location;
    } else if (statusCode === 401 &&
      /^Basic /i.test(response.headers["www-authenticate"] || "") &&
      (this.user && this.user.length)) {
      this._requestOptions.auth = `${this.user}:${this.pass}`;
      resendWithAuth = true;
    }
    if (redirectAddress || resendWithAuth) {
      if (++this._redirectCount > 21) {
        const redirectError = new Error("Maximum number of redirects exceeded");
        redirectError.code = "ERR_TOO_MANY_REDIRECTS";
        this.emit("error", redirectError);
        return;
      }
      abortRequest(this._currentRequest);
      response.destroy();
      this._isRedirect = true;
      if (((statusCode === 301 || statusCode === 302) && this._requestOptions.method === "POST") ||
        (statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._requestOptions.method))) {
        this._requestOptions.method = "GET";
        this._requestBodyBuffers = [];
      }
      let previousHostName = this._removeMatchingHeaders(/^host$/i);
      if (!previousHostName) {
        previousHostName = new URL(this.currentURL).hostname;
      }
      const previousURL = this.currentURL;
      if (!resendWithAuth) {
        const nextURL = redirectAddress.startsWith("https:") ?
          new URL(redirectAddress) :
          new URL(redirectAddress, this.currentURL);
        if (nextURL.hostname !== previousHostName) {
          this._removeMatchingHeaders(/^authorization$/i);
        }
        this.currentURL = nextURL.toString();
      }
      this.headers.Referer = previousURL;
      this.emit("redirect", response, this.headers, this.currentURL);
      try {
        this._performRequest();
      } catch (cause) {
        this.emit("error", cause);
      }
    } else {
      let pipeline = response;
      const acceptEncoding = this.headers["Accept-Encoding"];
      const requestCompressed = typeof acceptEncoding === "string" &&
        (acceptEncoding.includes("gzip") || acceptEncoding.includes("deflate"));
      if (
        requestCompressed &&
        this._requestOptions.method !== "HEAD" &&
        statusCode >= 200 &&
        statusCode !== 204 &&
        statusCode !== 304
      ) {
        const zlibOptions = {
          flush: zlib.constants.Z_SYNC_FLUSH,
          finishFlush: zlib.constants.Z_SYNC_FLUSH
        };
        const contentEncoding = (response.headers["content-encoding"] || "identity").trim().toLowerCase();
        if (contentEncoding === "gzip") {
          pipeline = zlib.createGunzip(zlibOptions);
          response.pipe(pipeline);
        } else if (contentEncoding === "deflate") {
          pipeline = zlib.createInflate(zlibOptions);
          response.pipe(pipeline);
        }
      }
      pipeline.removeAllListeners("error");
      this.emit("response", response, this.currentURL);
      pipeline.on("data", bytes => this.emit("data", bytes));
      pipeline.once("end", bytes => this.emit("end", bytes));
      pipeline.on("error", catchResErrors);
      pipeline.on("close", () => this.emit("close"));
      this._requestBodyBuffers = [];
    }
  }

  getHeader(key, value) {
    if (this._currentRequest) {
      return this._currentRequest.getHeader(key, value);
    }
    return null;
  }

  _removeMatchingHeaders(regex) {
    let lastValue;
    for (const header in this.headers) {
      if (regex.test(header)) {
        lastValue = this.headers[header];
        delete this.headers[header];
      }
    }
    return lastValue;
  }
};