http.js 21 KB

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