http.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. 'use strict';
  2. import utils from './../utils.js';
  3. import settle from './../core/settle.js';
  4. import buildFullPath from '../core/buildFullPath.js';
  5. import buildURL from './../helpers/buildURL.js';
  6. import {getProxyForUrl} from 'proxy-from-env';
  7. import http from 'http';
  8. import https from 'https';
  9. import util from 'util';
  10. import followRedirects from 'follow-redirects';
  11. import zlib from 'zlib';
  12. import {VERSION} from '../env/data.js';
  13. import transitionalDefaults from '../defaults/transitional.js';
  14. import AxiosError from '../core/AxiosError.js';
  15. import CanceledError from '../cancel/CanceledError.js';
  16. import platform from '../platform/index.js';
  17. import fromDataURI from '../helpers/fromDataURI.js';
  18. import stream from 'stream';
  19. import AxiosHeaders from '../core/AxiosHeaders.js';
  20. import AxiosTransformStream from '../helpers/AxiosTransformStream.js';
  21. import EventEmitter from 'events';
  22. import formDataToStream from "../helpers/formDataToStream.js";
  23. import readBlob from "../helpers/readBlob.js";
  24. import ZlibHeaderTransformStream from '../helpers/ZlibHeaderTransformStream.js';
  25. const zlibOptions = {
  26. flush: zlib.constants.Z_SYNC_FLUSH,
  27. finishFlush: zlib.constants.Z_SYNC_FLUSH
  28. };
  29. const brotliOptions = {
  30. flush: zlib.constants.BROTLI_OPERATION_FLUSH,
  31. finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
  32. }
  33. const isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress);
  34. const {http: httpFollow, https: httpsFollow} = followRedirects;
  35. const isHttps = /https:?/;
  36. const supportedProtocols = platform.protocols.map(protocol => {
  37. return protocol + ':';
  38. });
  39. /**
  40. * If the proxy or config beforeRedirects functions are defined, call them with the options
  41. * object.
  42. *
  43. * @param {Object<string, any>} options - The options object that was passed to the request.
  44. *
  45. * @returns {Object<string, any>}
  46. */
  47. function dispatchBeforeRedirect(options) {
  48. if (options.beforeRedirects.proxy) {
  49. options.beforeRedirects.proxy(options);
  50. }
  51. if (options.beforeRedirects.config) {
  52. options.beforeRedirects.config(options);
  53. }
  54. }
  55. /**
  56. * If the proxy or config afterRedirects functions are defined, call them with the options
  57. *
  58. * @param {http.ClientRequestArgs} options
  59. * @param {AxiosProxyConfig} configProxy configuration from Axios options object
  60. * @param {string} location
  61. *
  62. * @returns {http.ClientRequestArgs}
  63. */
  64. function setProxy(options, configProxy, location) {
  65. let proxy = configProxy;
  66. if (!proxy && proxy !== false) {
  67. const proxyUrl = getProxyForUrl(location);
  68. if (proxyUrl) {
  69. proxy = new URL(proxyUrl);
  70. }
  71. }
  72. if (proxy) {
  73. // Basic proxy authorization
  74. if (proxy.username) {
  75. proxy.auth = (proxy.username || '') + ':' + (proxy.password || '');
  76. }
  77. if (proxy.auth) {
  78. // Support proxy auth object form
  79. if (proxy.auth.username || proxy.auth.password) {
  80. proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || '');
  81. }
  82. const base64 = Buffer
  83. .from(proxy.auth, 'utf8')
  84. .toString('base64');
  85. options.headers['Proxy-Authorization'] = 'Basic ' + base64;
  86. }
  87. options.headers.host = options.hostname + (options.port ? ':' + options.port : '');
  88. const proxyHost = proxy.hostname || proxy.host;
  89. options.hostname = proxyHost;
  90. // Replace 'host' since options is not a URL object
  91. options.host = proxyHost;
  92. options.port = proxy.port;
  93. options.path = location;
  94. if (proxy.protocol) {
  95. options.protocol = proxy.protocol.includes(':') ? proxy.protocol : `${proxy.protocol}:`;
  96. }
  97. }
  98. options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
  99. // Configure proxy for redirected request, passing the original config proxy to apply
  100. // the exact same logic as if the redirected request was performed by axios directly.
  101. setProxy(redirectOptions, configProxy, redirectOptions.href);
  102. };
  103. }
  104. const isHttpAdapterSupported = typeof process !== 'undefined' && utils.kindOf(process) === 'process';
  105. // temporary hotfix
  106. const wrapAsync = (asyncExecutor) => {
  107. return new Promise((resolve, reject) => {
  108. let onDone;
  109. let isDone;
  110. const done = (value, isRejected) => {
  111. if (isDone) return;
  112. isDone = true;
  113. onDone && onDone(value, isRejected);
  114. }
  115. const _resolve = (value) => {
  116. done(value);
  117. resolve(value);
  118. };
  119. const _reject = (reason) => {
  120. done(reason, true);
  121. reject(reason);
  122. }
  123. asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject);
  124. })
  125. };
  126. /*eslint consistent-return:0*/
  127. export default isHttpAdapterSupported && function httpAdapter(config) {
  128. return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
  129. let {data} = config;
  130. const {responseType, responseEncoding} = config;
  131. const method = config.method.toUpperCase();
  132. let isDone;
  133. let rejected = false;
  134. let req;
  135. // temporary internal emitter until the AxiosRequest class will be implemented
  136. const emitter = new EventEmitter();
  137. const onFinished = () => {
  138. if (config.cancelToken) {
  139. config.cancelToken.unsubscribe(abort);
  140. }
  141. if (config.signal) {
  142. config.signal.removeEventListener('abort', abort);
  143. }
  144. emitter.removeAllListeners();
  145. }
  146. onDone((value, isRejected) => {
  147. isDone = true;
  148. if (isRejected) {
  149. rejected = true;
  150. onFinished();
  151. }
  152. });
  153. function abort(reason) {
  154. emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
  155. }
  156. emitter.once('abort', reject);
  157. if (config.cancelToken || config.signal) {
  158. config.cancelToken && config.cancelToken.subscribe(abort);
  159. if (config.signal) {
  160. config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
  161. }
  162. }
  163. // Parse url
  164. const fullPath = buildFullPath(config.baseURL, config.url);
  165. const parsed = new URL(fullPath, 'http://localhost');
  166. const protocol = parsed.protocol || supportedProtocols[0];
  167. if (protocol === 'data:') {
  168. let convertedData;
  169. if (method !== 'GET') {
  170. return settle(resolve, reject, {
  171. status: 405,
  172. statusText: 'method not allowed',
  173. headers: {},
  174. config
  175. });
  176. }
  177. try {
  178. convertedData = fromDataURI(config.url, responseType === 'blob', {
  179. Blob: config.env && config.env.Blob
  180. });
  181. } catch (err) {
  182. throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);
  183. }
  184. if (responseType === 'text') {
  185. convertedData = convertedData.toString(responseEncoding);
  186. if (!responseEncoding || responseEncoding === 'utf8') {
  187. convertedData = utils.stripBOM(convertedData);
  188. }
  189. } else if (responseType === 'stream') {
  190. convertedData = stream.Readable.from(convertedData);
  191. }
  192. return settle(resolve, reject, {
  193. data: convertedData,
  194. status: 200,
  195. statusText: 'OK',
  196. headers: new AxiosHeaders(),
  197. config
  198. });
  199. }
  200. if (supportedProtocols.indexOf(protocol) === -1) {
  201. return reject(new AxiosError(
  202. 'Unsupported protocol ' + protocol,
  203. AxiosError.ERR_BAD_REQUEST,
  204. config
  205. ));
  206. }
  207. const headers = AxiosHeaders.from(config.headers).normalize();
  208. // Set User-Agent (required by some servers)
  209. // See https://github.com/axios/axios/issues/69
  210. // User-Agent is specified; handle case where no UA header is desired
  211. // Only set header if it hasn't been set in config
  212. headers.set('User-Agent', 'axios/' + VERSION, false);
  213. const onDownloadProgress = config.onDownloadProgress;
  214. const onUploadProgress = config.onUploadProgress;
  215. const maxRate = config.maxRate;
  216. let maxUploadRate = undefined;
  217. let maxDownloadRate = undefined;
  218. // support for spec compliant FormData objects
  219. if (utils.isSpecCompliantForm(data)) {
  220. const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
  221. data = formDataToStream(data, (formHeaders) => {
  222. headers.set(formHeaders);
  223. }, {
  224. tag: `axios-${VERSION}-boundary`,
  225. boundary: userBoundary && userBoundary[1] || undefined
  226. });
  227. // support for https://www.npmjs.com/package/form-data api
  228. } else if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {
  229. headers.set(data.getHeaders());
  230. if (!headers.hasContentLength()) {
  231. try {
  232. const knownLength = await util.promisify(data.getLength).call(data);
  233. Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);
  234. /*eslint no-empty:0*/
  235. } catch (e) {
  236. }
  237. }
  238. } else if (utils.isBlob(data)) {
  239. data.size && headers.setContentType(data.type || 'application/octet-stream');
  240. headers.setContentLength(data.size || 0);
  241. data = stream.Readable.from(readBlob(data));
  242. } else if (data && !utils.isStream(data)) {
  243. if (Buffer.isBuffer(data)) {
  244. // Nothing to do...
  245. } else if (utils.isArrayBuffer(data)) {
  246. data = Buffer.from(new Uint8Array(data));
  247. } else if (utils.isString(data)) {
  248. data = Buffer.from(data, 'utf-8');
  249. } else {
  250. return reject(new AxiosError(
  251. 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
  252. AxiosError.ERR_BAD_REQUEST,
  253. config
  254. ));
  255. }
  256. // Add Content-Length header if data exists
  257. headers.setContentLength(data.length, false);
  258. if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) {
  259. return reject(new AxiosError(
  260. 'Request body larger than maxBodyLength limit',
  261. AxiosError.ERR_BAD_REQUEST,
  262. config
  263. ));
  264. }
  265. }
  266. const contentLength = utils.toFiniteNumber(headers.getContentLength());
  267. if (utils.isArray(maxRate)) {
  268. maxUploadRate = maxRate[0];
  269. maxDownloadRate = maxRate[1];
  270. } else {
  271. maxUploadRate = maxDownloadRate = maxRate;
  272. }
  273. if (data && (onUploadProgress || maxUploadRate)) {
  274. if (!utils.isStream(data)) {
  275. data = stream.Readable.from(data, {objectMode: false});
  276. }
  277. data = stream.pipeline([data, new AxiosTransformStream({
  278. length: contentLength,
  279. maxRate: utils.toFiniteNumber(maxUploadRate)
  280. })], utils.noop);
  281. onUploadProgress && data.on('progress', progress => {
  282. onUploadProgress(Object.assign(progress, {
  283. upload: true
  284. }));
  285. });
  286. }
  287. // HTTP basic authentication
  288. let auth = undefined;
  289. if (config.auth) {
  290. const username = config.auth.username || '';
  291. const password = config.auth.password || '';
  292. auth = username + ':' + password;
  293. }
  294. if (!auth && parsed.username) {
  295. const urlUsername = parsed.username;
  296. const urlPassword = parsed.password;
  297. auth = urlUsername + ':' + urlPassword;
  298. }
  299. auth && headers.delete('authorization');
  300. let path;
  301. try {
  302. path = buildURL(
  303. parsed.pathname + parsed.search,
  304. config.params,
  305. config.paramsSerializer
  306. ).replace(/^\?/, '');
  307. } catch (err) {
  308. const customErr = new Error(err.message);
  309. customErr.config = config;
  310. customErr.url = config.url;
  311. customErr.exists = true;
  312. return reject(customErr);
  313. }
  314. headers.set(
  315. 'Accept-Encoding',
  316. 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), false
  317. );
  318. const options = {
  319. path,
  320. method: method,
  321. headers: headers.toJSON(),
  322. agents: { http: config.httpAgent, https: config.httpsAgent },
  323. auth,
  324. protocol,
  325. beforeRedirect: dispatchBeforeRedirect,
  326. beforeRedirects: {}
  327. };
  328. if (config.socketPath) {
  329. options.socketPath = config.socketPath;
  330. } else {
  331. options.hostname = parsed.hostname;
  332. options.port = parsed.port;
  333. setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
  334. }
  335. let transport;
  336. const isHttpsRequest = isHttps.test(options.protocol);
  337. options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
  338. if (config.transport) {
  339. transport = config.transport;
  340. } else if (config.maxRedirects === 0) {
  341. transport = isHttpsRequest ? https : http;
  342. } else {
  343. if (config.maxRedirects) {
  344. options.maxRedirects = config.maxRedirects;
  345. }
  346. if (config.beforeRedirect) {
  347. options.beforeRedirects.config = config.beforeRedirect;
  348. }
  349. transport = isHttpsRequest ? httpsFollow : httpFollow;
  350. }
  351. if (config.maxBodyLength > -1) {
  352. options.maxBodyLength = config.maxBodyLength;
  353. } else {
  354. // follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited
  355. options.maxBodyLength = Infinity;
  356. }
  357. if (config.insecureHTTPParser) {
  358. options.insecureHTTPParser = config.insecureHTTPParser;
  359. }
  360. // Create the request
  361. req = transport.request(options, function handleResponse(res) {
  362. if (req.destroyed) return;
  363. const streams = [res];
  364. const responseLength = +res.headers['content-length'];
  365. if (onDownloadProgress) {
  366. const transformStream = new AxiosTransformStream({
  367. length: utils.toFiniteNumber(responseLength),
  368. maxRate: utils.toFiniteNumber(maxDownloadRate)
  369. });
  370. onDownloadProgress && transformStream.on('progress', progress => {
  371. onDownloadProgress(Object.assign(progress, {
  372. download: true
  373. }));
  374. });
  375. streams.push(transformStream);
  376. }
  377. // decompress the response body transparently if required
  378. let responseStream = res;
  379. // return the last request in case of redirects
  380. const lastRequest = res.req || req;
  381. // if decompress disabled we should not decompress
  382. if (config.decompress !== false && res.headers['content-encoding']) {
  383. // if no content, but headers still say that it is encoded,
  384. // remove the header not confuse downstream operations
  385. if (method === 'HEAD' || res.statusCode === 204) {
  386. delete res.headers['content-encoding'];
  387. }
  388. switch (res.headers['content-encoding']) {
  389. /*eslint default-case:0*/
  390. case 'gzip':
  391. case 'x-gzip':
  392. case 'compress':
  393. case 'x-compress':
  394. // add the unzipper to the body stream processing pipeline
  395. streams.push(zlib.createUnzip(zlibOptions));
  396. // remove the content-encoding in order to not confuse downstream operations
  397. delete res.headers['content-encoding'];
  398. break;
  399. case 'deflate':
  400. streams.push(new ZlibHeaderTransformStream());
  401. // add the unzipper to the body stream processing pipeline
  402. streams.push(zlib.createUnzip(zlibOptions));
  403. // remove the content-encoding in order to not confuse downstream operations
  404. delete res.headers['content-encoding'];
  405. break;
  406. case 'br':
  407. if (isBrotliSupported) {
  408. streams.push(zlib.createBrotliDecompress(brotliOptions));
  409. delete res.headers['content-encoding'];
  410. }
  411. }
  412. }
  413. responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0];
  414. const offListeners = stream.finished(responseStream, () => {
  415. offListeners();
  416. onFinished();
  417. });
  418. const response = {
  419. status: res.statusCode,
  420. statusText: res.statusMessage,
  421. headers: new AxiosHeaders(res.headers),
  422. config,
  423. request: lastRequest
  424. };
  425. if (responseType === 'stream') {
  426. response.data = responseStream;
  427. settle(resolve, reject, response);
  428. } else {
  429. const responseBuffer = [];
  430. let totalResponseBytes = 0;
  431. responseStream.on('data', function handleStreamData(chunk) {
  432. responseBuffer.push(chunk);
  433. totalResponseBytes += chunk.length;
  434. // make sure the content length is not over the maxContentLength if specified
  435. if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) {
  436. // stream.destroy() emit aborted event before calling reject() on Node.js v16
  437. rejected = true;
  438. responseStream.destroy();
  439. reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
  440. AxiosError.ERR_BAD_RESPONSE, config, lastRequest));
  441. }
  442. });
  443. responseStream.on('aborted', function handlerStreamAborted() {
  444. if (rejected) {
  445. return;
  446. }
  447. const err = new AxiosError(
  448. 'maxContentLength size of ' + config.maxContentLength + ' exceeded',
  449. AxiosError.ERR_BAD_RESPONSE,
  450. config,
  451. lastRequest
  452. );
  453. responseStream.destroy(err);
  454. reject(err);
  455. });
  456. responseStream.on('error', function handleStreamError(err) {
  457. if (req.destroyed) return;
  458. reject(AxiosError.from(err, null, config, lastRequest));
  459. });
  460. responseStream.on('end', function handleStreamEnd() {
  461. try {
  462. let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
  463. if (responseType !== 'arraybuffer') {
  464. responseData = responseData.toString(responseEncoding);
  465. if (!responseEncoding || responseEncoding === 'utf8') {
  466. responseData = utils.stripBOM(responseData);
  467. }
  468. }
  469. response.data = responseData;
  470. } catch (err) {
  471. reject(AxiosError.from(err, null, config, response.request, response));
  472. }
  473. settle(resolve, reject, response);
  474. });
  475. }
  476. emitter.once('abort', err => {
  477. if (!responseStream.destroyed) {
  478. responseStream.emit('error', err);
  479. responseStream.destroy();
  480. }
  481. });
  482. });
  483. emitter.once('abort', err => {
  484. reject(err);
  485. req.destroy(err);
  486. });
  487. // Handle errors
  488. req.on('error', function handleRequestError(err) {
  489. // @todo remove
  490. // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return;
  491. reject(AxiosError.from(err, null, config, req));
  492. });
  493. // set tcp keep alive to prevent drop connection by peer
  494. req.on('socket', function handleRequestSocket(socket) {
  495. // default interval of sending ack packet is 1 minute
  496. socket.setKeepAlive(true, 1000 * 60);
  497. });
  498. // Handle request timeout
  499. if (config.timeout) {
  500. // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
  501. const timeout = parseInt(config.timeout, 10);
  502. if (isNaN(timeout)) {
  503. reject(new AxiosError(
  504. 'error trying to parse `config.timeout` to int',
  505. AxiosError.ERR_BAD_OPTION_VALUE,
  506. config,
  507. req
  508. ));
  509. return;
  510. }
  511. // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
  512. // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
  513. // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
  514. // And then these socket which be hang up will devouring CPU little by little.
  515. // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
  516. req.setTimeout(timeout, function handleRequestTimeout() {
  517. if (isDone) return;
  518. let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
  519. const transitional = config.transitional || transitionalDefaults;
  520. if (config.timeoutErrorMessage) {
  521. timeoutErrorMessage = config.timeoutErrorMessage;
  522. }
  523. reject(new AxiosError(
  524. timeoutErrorMessage,
  525. transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
  526. config,
  527. req
  528. ));
  529. abort();
  530. });
  531. }
  532. // Send the request
  533. if (utils.isStream(data)) {
  534. let ended = false;
  535. let errored = false;
  536. data.on('end', () => {
  537. ended = true;
  538. });
  539. data.once('error', err => {
  540. errored = true;
  541. req.destroy(err);
  542. });
  543. data.on('close', () => {
  544. if (!ended && !errored) {
  545. abort(new CanceledError('Request stream has been aborted', config, req));
  546. }
  547. });
  548. data.pipe(req);
  549. } else {
  550. req.end(data);
  551. }
  552. });
  553. }
  554. export const __setProxy = setProxy;