http.js 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  1. import utils from '../utils.js';
  2. import settle from '../core/settle.js';
  3. import buildFullPath from '../core/buildFullPath.js';
  4. import buildURL from '../helpers/buildURL.js';
  5. import { getProxyForUrl } from 'proxy-from-env';
  6. import HttpsProxyAgent from 'https-proxy-agent';
  7. import http from 'http';
  8. import https from 'https';
  9. import http2 from 'http2';
  10. import util from 'util';
  11. import { resolve as resolvePath } from 'path';
  12. import followRedirects from 'follow-redirects';
  13. import zlib from 'zlib';
  14. import { VERSION } from '../env/data.js';
  15. import transitionalDefaults from '../defaults/transitional.js';
  16. import AxiosError from '../core/AxiosError.js';
  17. import CanceledError from '../cancel/CanceledError.js';
  18. import platform from '../platform/index.js';
  19. import fromDataURI from '../helpers/fromDataURI.js';
  20. import stream from 'stream';
  21. import AxiosHeaders from '../core/AxiosHeaders.js';
  22. import setFormDataHeaders from '../core/setFormDataHeaders.js';
  23. import AxiosTransformStream from '../helpers/AxiosTransformStream.js';
  24. import { EventEmitter } from 'events';
  25. import formDataToStream from '../helpers/formDataToStream.js';
  26. import readBlob from '../helpers/readBlob.js';
  27. import ZlibHeaderTransformStream from '../helpers/ZlibHeaderTransformStream.js';
  28. import Http2Sessions from '../helpers/Http2Sessions.js';
  29. import callbackify from '../helpers/callbackify.js';
  30. import shouldBypassProxy from '../helpers/shouldBypassProxy.js';
  31. import { toByteStringHeaderObject } from '../helpers/sanitizeHeaderValue.js';
  32. import {
  33. progressEventReducer,
  34. progressEventDecorator,
  35. asyncDecorator,
  36. } from '../helpers/progressEventReducer.js';
  37. import { estimateDataURLBufferAllocation } from '../helpers/estimateDataURLDecodedBytes.js';
  38. const zlibOptions = {
  39. flush: zlib.constants.Z_SYNC_FLUSH,
  40. finishFlush: zlib.constants.Z_SYNC_FLUSH,
  41. };
  42. const brotliOptions = {
  43. flush: zlib.constants.BROTLI_OPERATION_FLUSH,
  44. finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH,
  45. };
  46. const zstdOptions = {
  47. flush: zlib.constants.ZSTD_e_flush,
  48. finishFlush: zlib.constants.ZSTD_e_flush,
  49. };
  50. const isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress);
  51. const isZstdSupported = utils.isFunction(zlib.createZstdDecompress);
  52. const ACCEPT_ENCODING = 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : '');
  53. const ACCEPT_ENCODING_WITH_ZSTD = ACCEPT_ENCODING + (isZstdSupported ? ', zstd' : '');
  54. const scheduleProgress =
  55. typeof process !== 'undefined' && process.nextTick ? process.nextTick.bind(process) : utils.asap;
  56. const { http: httpFollow, https: httpsFollow } = followRedirects;
  57. const isHttps = /https:?/;
  58. // Symbols used to bind a single 'error' listener to a pooled socket and track
  59. // the request currently owning that socket across keep-alive reuse (issue #10780).
  60. const kAxiosSocketListener = Symbol('axios.http.socketListener');
  61. const kAxiosCurrentReq = Symbol('axios.http.currentReq');
  62. // Tags HttpsProxyAgent instances installed by setProxy() so the redirect path
  63. // can strip them without clobbering a user-supplied agent that happens to be
  64. // an HttpsProxyAgent.
  65. const kAxiosInstalledTunnel = Symbol('axios.http.installedTunnel');
  66. // Cache of CONNECT-tunneling agents keyed by proxy config so repeat requests
  67. // through the same proxy reuse a single agent (and its socket pool). The
  68. // keyspace is bounded by the set of distinct proxy configs the process uses,
  69. // so unbounded growth is not a concern in practice.
  70. const tunnelingAgentCache = new Map();
  71. const tunnelingAgentCacheUser = new WeakMap();
  72. // Minimum minor versions where Node's HTTP Agent supports native proxyEnv
  73. // handling. Checking the selected agent below also covers startup modes such
  74. // as NODE_OPTIONS=--use-env-proxy and --no-use-env-proxy precedence.
  75. const NODE_NATIVE_ENV_PROXY_SUPPORT = {
  76. 22: 21,
  77. 24: 5,
  78. };
  79. function isNodeNativeEnvProxySupported(nodeVersion = process.versions && process.versions.node) {
  80. if (!nodeVersion) {
  81. return false;
  82. }
  83. const [major, minor] = nodeVersion.split('.').map((part) => Number(part));
  84. if (!Number.isInteger(major) || !Number.isInteger(minor)) {
  85. return false;
  86. }
  87. if (major > 24) {
  88. return true;
  89. }
  90. return (
  91. NODE_NATIVE_ENV_PROXY_SUPPORT[major] != null && minor >= NODE_NATIVE_ENV_PROXY_SUPPORT[major]
  92. );
  93. }
  94. function isNodeEnvProxyEnabled(agent, nodeVersion = process.versions && process.versions.node) {
  95. if (!isNodeNativeEnvProxySupported(nodeVersion)) {
  96. return false;
  97. }
  98. const agentOptions = agent && agent.options;
  99. return Boolean(
  100. agentOptions &&
  101. utils.hasOwnProp(agentOptions, 'proxyEnv') &&
  102. agentOptions.proxyEnv != null
  103. );
  104. }
  105. function getProxyEnvAgent(options, configHttpAgent, configHttpsAgent) {
  106. return isHttps.test(options.protocol)
  107. ? (configHttpsAgent || https.globalAgent)
  108. : (configHttpAgent || http.globalAgent);
  109. }
  110. function getTunnelingAgent(agentOptions, userHttpsAgent) {
  111. const key =
  112. agentOptions.protocol +
  113. '//' +
  114. agentOptions.hostname +
  115. ':' +
  116. (agentOptions.port || '') +
  117. '#' +
  118. (agentOptions.auth || '');
  119. const cache = userHttpsAgent
  120. ? (tunnelingAgentCacheUser.get(userHttpsAgent) ||
  121. tunnelingAgentCacheUser.set(userHttpsAgent, new Map()).get(userHttpsAgent))
  122. : tunnelingAgentCache;
  123. let agent = cache.get(key);
  124. if (agent) return agent;
  125. // Forward the user's TLS options (custom CA, rejectUnauthorized, client cert,
  126. // etc.) into the tunneling agent so they apply to the origin TLS upgrade
  127. // performed after CONNECT. Our proxy fields take precedence on conflict.
  128. const merged = userHttpsAgent && userHttpsAgent.options
  129. ? { ...userHttpsAgent.options, ...agentOptions }
  130. : agentOptions;
  131. agent = new HttpsProxyAgent(merged);
  132. if (userHttpsAgent && userHttpsAgent.options) {
  133. const originTLSOptions = { ...userHttpsAgent.options };
  134. const callback = agent.callback;
  135. agent.callback = function axiosTunnelingAgentCallback(req, opts) {
  136. // HttpsProxyAgent v5 reads callback opts for the post-CONNECT origin TLS upgrade.
  137. return callback.call(this, req, { ...originTLSOptions, ...opts });
  138. };
  139. }
  140. agent[kAxiosInstalledTunnel] = true;
  141. cache.set(key, agent);
  142. return agent;
  143. }
  144. const supportedProtocols = platform.protocols.map((protocol) => {
  145. return protocol + ':';
  146. });
  147. // Node's WHATWG URL parser returns `username` and `password` percent-encoded.
  148. // Decode before composing the `auth` option so credentials such as
  149. // `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
  150. // original value for malformed input so a bad encoding never throws.
  151. const decodeURIComponentSafe = (value) => {
  152. if (!utils.isString(value)) {
  153. return value;
  154. }
  155. try {
  156. return decodeURIComponent(value);
  157. } catch (error) {
  158. return value;
  159. }
  160. };
  161. const flushOnFinish = (stream, [throttled, flush]) => {
  162. stream.on('end', flush).on('error', flush);
  163. return throttled;
  164. };
  165. const http2Sessions = new Http2Sessions();
  166. /**
  167. * If the proxy, auth, sensitive header, or config beforeRedirects functions are defined,
  168. * call them with the options object.
  169. *
  170. * @param {Object<string, any>} options - The options object that was passed to the request.
  171. *
  172. * @returns {Object<string, any>}
  173. */
  174. function dispatchBeforeRedirect(options, responseDetails, requestDetails) {
  175. if (options.beforeRedirects.proxy) {
  176. options.beforeRedirects.proxy(options);
  177. }
  178. if (options.beforeRedirects.auth) {
  179. options.beforeRedirects.auth(options);
  180. }
  181. if (options.beforeRedirects.sensitiveHeaders) {
  182. options.beforeRedirects.sensitiveHeaders(options, requestDetails);
  183. }
  184. if (options.beforeRedirects.config) {
  185. options.beforeRedirects.config(options, responseDetails, requestDetails);
  186. }
  187. }
  188. function stripMatchingHeaders(headers, sensitiveSet) {
  189. if (!headers) {
  190. return;
  191. }
  192. Object.keys(headers).forEach((header) => {
  193. if (sensitiveSet.has(header.toLowerCase())) {
  194. delete headers[header];
  195. }
  196. });
  197. }
  198. function isSameOriginRedirect(redirectOptions, requestDetails) {
  199. if (!requestDetails) {
  200. return false;
  201. }
  202. try {
  203. return new URL(requestDetails.url).origin === new URL(redirectOptions.href).origin;
  204. } catch (e) {
  205. // If origin comparison fails, treat the redirect as unsafe.
  206. return false;
  207. }
  208. }
  209. /**
  210. * If the proxy or config afterRedirects functions are defined, call them with the options
  211. *
  212. * @param {http.ClientRequestArgs} options
  213. * @param {AxiosProxyConfig} configProxy configuration from Axios options object
  214. * @param {string} location
  215. *
  216. * @returns {http.ClientRequestArgs}
  217. */
  218. function setProxy(options, configProxy, location, isRedirect, configHttpsAgent, configHttpAgent) {
  219. let proxy = configProxy;
  220. const proxyEnvAgent = getProxyEnvAgent(options, configHttpAgent, configHttpsAgent);
  221. if (!proxy && proxy !== false && !isNodeEnvProxyEnabled(proxyEnvAgent)) {
  222. const proxyUrl = getProxyForUrl(location);
  223. if (proxyUrl) {
  224. if (!shouldBypassProxy(location)) {
  225. proxy = new URL(proxyUrl);
  226. }
  227. }
  228. }
  229. // On redirect re-invocation, strip any stale Proxy-Authorization header carried
  230. // over from the prior request (e.g. new target no longer uses a proxy, or uses
  231. // a different proxy). Skip on the initial request so user-supplied headers are
  232. // preserved. Header names are case-insensitive, so remove every case variant.
  233. if (isRedirect && options.headers) {
  234. for (const name of Object.keys(options.headers)) {
  235. if (name.toLowerCase() === 'proxy-authorization') {
  236. delete options.headers[name];
  237. }
  238. }
  239. }
  240. // Strip any tunneling agent we installed for the previous hop so a redirect
  241. // that drops the proxy or crosses an HTTPS↔HTTP boundary doesn't reuse a
  242. // stale one. Match on our Symbol marker so a user-supplied HttpsProxyAgent
  243. // (which won't carry the marker) is left alone.
  244. if (isRedirect && options.agent && options.agent[kAxiosInstalledTunnel]) {
  245. options.agent = undefined;
  246. }
  247. if (proxy) {
  248. // Read proxy fields without traversing the prototype chain. URL instances expose
  249. // username/password/hostname/host/port/protocol via getters on URL.prototype (so
  250. // direct reads are shielded), but plain object proxies — and the `auth` field
  251. // (which URL does not expose) — must be guarded so a polluted Object.prototype
  252. // (e.g. Object.prototype.auth = { username, password }) cannot inject
  253. // attacker-controlled credentials into the Proxy-Authorization header or
  254. // redirect proxying to an attacker-controlled host.
  255. const isProxyURL = proxy instanceof URL;
  256. const readProxyField = (key) =>
  257. isProxyURL || utils.hasOwnProp(proxy, key) ? proxy[key] : undefined;
  258. const proxyUsername = readProxyField('username');
  259. const proxyPassword = readProxyField('password');
  260. let proxyAuth = utils.hasOwnProp(proxy, 'auth') ? proxy.auth : undefined;
  261. // Basic proxy authorization
  262. if (proxyUsername) {
  263. proxyAuth = (proxyUsername || '') + ':' + (proxyPassword || '');
  264. }
  265. if (proxyAuth) {
  266. // Support proxy auth object form. Read sub-fields via own-prop checks so a
  267. // plain object inheriting from polluted Object.prototype cannot leak creds.
  268. const authIsObject = typeof proxyAuth === 'object';
  269. const authUsername =
  270. authIsObject && utils.hasOwnProp(proxyAuth, 'username') ? proxyAuth.username : undefined;
  271. const authPassword =
  272. authIsObject && utils.hasOwnProp(proxyAuth, 'password') ? proxyAuth.password : undefined;
  273. const validProxyAuth = Boolean(authUsername || authPassword);
  274. if (validProxyAuth) {
  275. proxyAuth = (authUsername || '') + ':' + (authPassword || '');
  276. } else if (authIsObject) {
  277. throw new AxiosError('Invalid proxy authorization', AxiosError.ERR_BAD_OPTION, { proxy });
  278. }
  279. }
  280. const targetIsHttps = isHttps.test(options.protocol);
  281. if (targetIsHttps) {
  282. // CONNECT-tunneling path for HTTPS targets. Preserves end-to-end TLS to
  283. // the origin so the proxy cannot inspect the URL, headers, or body — the
  284. // behavior already promised by THREATMODEL.md (T-R9). HttpsProxyAgent
  285. // sends Proxy-Authorization on the CONNECT request only, never on the
  286. // wrapped TLS request, which is why we don't stamp it onto
  287. // options.headers here. If the user already supplied an HttpsProxyAgent,
  288. // they own tunneling end-to-end and we leave them alone; otherwise we
  289. // install our own tunneling agent and forward their TLS options (if any)
  290. // so a custom httpsAgent for cert pinning / rejectUnauthorized still
  291. // applies to the origin TLS upgrade.
  292. if (!(configHttpsAgent instanceof HttpsProxyAgent)) {
  293. const proxyHost = readProxyField('hostname') || readProxyField('host');
  294. const proxyPort = readProxyField('port');
  295. const rawProxyProtocol = readProxyField('protocol');
  296. const normalizedProtocol = rawProxyProtocol
  297. ? rawProxyProtocol.includes(':')
  298. ? rawProxyProtocol
  299. : `${rawProxyProtocol}:`
  300. : 'http:';
  301. // Bracket IPv6 literals for URL parsing; URL.hostname strips the
  302. // brackets again on read so the agent receives the raw form.
  303. const proxyHostForURL =
  304. proxyHost && proxyHost.includes(':') && !proxyHost.startsWith('[')
  305. ? `[${proxyHost}]`
  306. : proxyHost;
  307. const proxyURL = new URL(
  308. `${normalizedProtocol}//${proxyHostForURL}${proxyPort ? ':' + proxyPort : ''}`
  309. );
  310. const agentOptions = {
  311. protocol: proxyURL.protocol,
  312. hostname: proxyURL.hostname.replace(/^\[|\]$/g, ''),
  313. port: proxyURL.port,
  314. auth: proxyAuth && typeof proxyAuth === 'string' ? proxyAuth : undefined,
  315. };
  316. if (proxyURL.protocol === 'https:') {
  317. agentOptions.ALPNProtocols = ['http/1.1'];
  318. }
  319. const tunnelingAgent = getTunnelingAgent(agentOptions, configHttpsAgent);
  320. // Set both: `options.agent` is consumed by the native https.request path
  321. // (maxRedirects === 0); `options.agents.https` is consumed by
  322. // follow-redirects, which ignores `options.agent` when `options.agents`
  323. // is present.
  324. options.agent = tunnelingAgent;
  325. if (options.agents) {
  326. options.agents.https = tunnelingAgent;
  327. }
  328. }
  329. } else {
  330. // Forward-proxy mode for plaintext HTTP targets. The request line carries
  331. // the absolute URL and the proxy sees everything — acceptable for plain
  332. // HTTP since the wire was already plaintext.
  333. if (proxyAuth) {
  334. const base64 = Buffer.from(proxyAuth, 'utf8').toString('base64');
  335. options.headers['Proxy-Authorization'] = 'Basic ' + base64;
  336. }
  337. // Preserve a user-supplied Host header (case-insensitive) so callers can override
  338. // the value forwarded to the proxy; otherwise default to the request URL's host.
  339. let hasUserHostHeader = false;
  340. for (const name of Object.keys(options.headers)) {
  341. if (name.toLowerCase() === 'host') {
  342. hasUserHostHeader = true;
  343. break;
  344. }
  345. }
  346. if (!hasUserHostHeader) {
  347. options.headers.host = options.hostname + (options.port ? ':' + options.port : '');
  348. }
  349. const proxyHost = readProxyField('hostname') || readProxyField('host');
  350. options.hostname = proxyHost;
  351. // Replace 'host' since options is not a URL object
  352. options.host = proxyHost;
  353. options.port = readProxyField('port');
  354. options.path = location;
  355. const proxyProtocol = readProxyField('protocol');
  356. if (proxyProtocol) {
  357. options.protocol = proxyProtocol.includes(':') ? proxyProtocol : `${proxyProtocol}:`;
  358. }
  359. }
  360. }
  361. options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
  362. // Configure proxy for redirected request, passing the original config proxy to apply
  363. // the exact same logic as if the redirected request was performed by axios directly.
  364. setProxy(
  365. redirectOptions,
  366. configProxy,
  367. redirectOptions.href,
  368. true,
  369. configHttpsAgent,
  370. configHttpAgent
  371. );
  372. };
  373. }
  374. const isHttpAdapterSupported =
  375. typeof process !== 'undefined' && utils.kindOf(process) === 'process';
  376. // temporary hotfix
  377. const wrapAsync = (asyncExecutor) => {
  378. return new Promise((resolve, reject) => {
  379. let onDone;
  380. let isDone;
  381. const done = (value, isRejected) => {
  382. if (isDone) return;
  383. isDone = true;
  384. onDone && onDone(value, isRejected);
  385. };
  386. const _resolve = (value) => {
  387. done(value);
  388. resolve(value);
  389. };
  390. const _reject = (reason) => {
  391. done(reason, true);
  392. reject(reason);
  393. };
  394. asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject);
  395. });
  396. };
  397. const resolveFamily = ({ address, family }) => {
  398. if (!utils.isString(address)) {
  399. throw TypeError('address must be a string');
  400. }
  401. return {
  402. address,
  403. family: family || (address.indexOf('.') < 0 ? 6 : 4),
  404. };
  405. };
  406. const buildAddressEntry = (address, family) =>
  407. resolveFamily(utils.isObject(address) ? address : { address, family });
  408. const http2Transport = {
  409. request(options, cb) {
  410. const authority =
  411. options.protocol +
  412. '//' +
  413. options.hostname +
  414. ':' +
  415. (options.port || (options.protocol === 'https:' ? 443 : 80));
  416. const { http2Options, headers } = options;
  417. const session = http2Sessions.getSession(authority, http2Options);
  418. const { HTTP2_HEADER_SCHEME, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS } =
  419. http2.constants;
  420. const http2Headers = {
  421. [HTTP2_HEADER_SCHEME]: options.protocol.replace(':', ''),
  422. [HTTP2_HEADER_METHOD]: options.method,
  423. [HTTP2_HEADER_PATH]: options.path,
  424. };
  425. utils.forEach(headers, (header, name) => {
  426. name.charAt(0) !== ':' && (http2Headers[name] = header);
  427. });
  428. const req = session.request(http2Headers);
  429. req.once('response', (responseHeaders) => {
  430. const response = req; //duplex
  431. responseHeaders = Object.assign({}, responseHeaders);
  432. const status = responseHeaders[HTTP2_HEADER_STATUS];
  433. delete responseHeaders[HTTP2_HEADER_STATUS];
  434. response.headers = responseHeaders;
  435. response.statusCode = +status;
  436. cb(response);
  437. });
  438. return req;
  439. },
  440. };
  441. /*eslint consistent-return:0*/
  442. export default isHttpAdapterSupported &&
  443. function httpAdapter(config) {
  444. return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
  445. // Read config pollution-safely: own properties and members inherited from
  446. // a non-Object.prototype source (e.g. an Object.create(defaults) template)
  447. // are honored, but values injected onto a polluted Object.prototype are
  448. // ignored. All behavior-affecting reads in this adapter go through own()
  449. // so the protection boundary stays consistent.
  450. const own = (key) => utils.getSafeProp(config, key);
  451. const transitional = own('transitional') || transitionalDefaults;
  452. let data = own('data');
  453. let lookup = own('lookup');
  454. let family = own('family');
  455. let httpVersion = own('httpVersion');
  456. if (httpVersion === undefined) httpVersion = 1;
  457. let http2Options = own('http2Options');
  458. const httpAgent = own('httpAgent');
  459. const httpsAgent = own('httpsAgent');
  460. const configProxy = own('proxy');
  461. const responseType = own('responseType');
  462. const responseEncoding = own('responseEncoding');
  463. const socketPath = own('socketPath');
  464. const method = own('method').toUpperCase();
  465. const maxRedirects = own('maxRedirects');
  466. const maxBodyLength = own('maxBodyLength');
  467. const maxContentLength = own('maxContentLength');
  468. const decompress = own('decompress');
  469. let isDone;
  470. let rejected = false;
  471. let req;
  472. let connectPhaseTimer;
  473. httpVersion = +httpVersion;
  474. if (Number.isNaN(httpVersion)) {
  475. throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`);
  476. }
  477. if (httpVersion !== 1 && httpVersion !== 2) {
  478. throw TypeError(`Unsupported protocol version '${httpVersion}'`);
  479. }
  480. const isHttp2 = httpVersion === 2;
  481. if (lookup) {
  482. const _lookup = callbackify(lookup, (value) => (utils.isArray(value) ? value : [value]));
  483. // hotfix to support opt.all option which is required for node 20.x
  484. lookup = (hostname, opt, cb) => {
  485. _lookup(hostname, opt, (err, arg0, arg1) => {
  486. if (err) {
  487. return cb(err);
  488. }
  489. const addresses = utils.isArray(arg0)
  490. ? arg0.map((addr) => buildAddressEntry(addr))
  491. : [buildAddressEntry(arg0, arg1)];
  492. opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
  493. });
  494. };
  495. }
  496. const abortEmitter = new EventEmitter();
  497. function abort(reason) {
  498. try {
  499. abortEmitter.emit(
  500. 'abort',
  501. !reason || reason.type ? new CanceledError(null, config, req) : reason
  502. );
  503. } catch (err) {
  504. // ignore emit errors
  505. }
  506. }
  507. function clearConnectPhaseTimer() {
  508. if (connectPhaseTimer) {
  509. clearTimeout(connectPhaseTimer);
  510. connectPhaseTimer = null;
  511. }
  512. }
  513. function createTimeoutError() {
  514. const configTimeout = own('timeout');
  515. let timeoutErrorMessage = configTimeout
  516. ? 'timeout of ' + configTimeout + 'ms exceeded'
  517. : 'timeout exceeded';
  518. const configTimeoutErrorMessage = own('timeoutErrorMessage');
  519. if (configTimeoutErrorMessage) {
  520. timeoutErrorMessage = configTimeoutErrorMessage;
  521. }
  522. return new AxiosError(
  523. timeoutErrorMessage,
  524. transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
  525. config,
  526. req
  527. );
  528. }
  529. abortEmitter.once('abort', reject);
  530. const onFinished = () => {
  531. clearConnectPhaseTimer();
  532. if (config.cancelToken) {
  533. config.cancelToken.unsubscribe(abort);
  534. }
  535. if (config.signal) {
  536. config.signal.removeEventListener('abort', abort);
  537. }
  538. abortEmitter.removeAllListeners();
  539. };
  540. if (config.cancelToken || config.signal) {
  541. config.cancelToken && config.cancelToken.subscribe(abort);
  542. if (config.signal) {
  543. config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
  544. }
  545. }
  546. onDone((response, isRejected) => {
  547. isDone = true;
  548. clearConnectPhaseTimer();
  549. if (isRejected) {
  550. rejected = true;
  551. onFinished();
  552. return;
  553. }
  554. const { data } = response;
  555. if (data instanceof stream.Readable || data instanceof stream.Duplex) {
  556. const offListeners = stream.finished(data, () => {
  557. offListeners();
  558. onFinished();
  559. });
  560. } else {
  561. onFinished();
  562. }
  563. });
  564. // Parse url
  565. const fullPath = buildFullPath(own('baseURL'), own('url'), own('allowAbsoluteUrls'), config);
  566. // Unix-socket requests (own socketPath) commonly pass a path-only url
  567. // like '/foo'; supply a synthetic base so new URL() can still parse it.
  568. // Use the own-property value (not config.socketPath) so a polluted
  569. // prototype cannot influence URL base selection.
  570. const urlBase = socketPath
  571. ? 'http://localhost'
  572. : (platform.hasBrowserEnv ? platform.origin : undefined);
  573. const parsed = new URL(fullPath, urlBase);
  574. const protocol = parsed.protocol || supportedProtocols[0];
  575. if (protocol === 'data:') {
  576. // Apply the same semantics as HTTP: only enforce if a finite, non-negative cap is set.
  577. if (maxContentLength > -1) {
  578. // Use the exact string passed to fromDataURI (the configured url); fall back to fullPath if needed.
  579. const dataUrl = String(own('url') || fullPath || '');
  580. const estimated = estimateDataURLBufferAllocation(dataUrl);
  581. if (estimated > maxContentLength) {
  582. return reject(
  583. new AxiosError(
  584. 'maxContentLength size of ' + maxContentLength + ' exceeded',
  585. AxiosError.ERR_BAD_RESPONSE,
  586. config
  587. )
  588. );
  589. }
  590. }
  591. let convertedData;
  592. if (method !== 'GET') {
  593. return settle(resolve, reject, {
  594. status: 405,
  595. statusText: 'method not allowed',
  596. headers: {},
  597. config,
  598. });
  599. }
  600. try {
  601. convertedData = fromDataURI(own('url'), responseType === 'blob', {
  602. Blob: config.env && config.env.Blob,
  603. });
  604. } catch (err) {
  605. throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);
  606. }
  607. if (responseType === 'text') {
  608. convertedData = convertedData.toString(responseEncoding);
  609. if (!responseEncoding || responseEncoding === 'utf8') {
  610. convertedData = utils.stripBOM(convertedData);
  611. }
  612. } else if (responseType === 'stream') {
  613. convertedData = stream.Readable.from(convertedData);
  614. }
  615. return settle(resolve, reject, {
  616. data: convertedData,
  617. status: 200,
  618. statusText: 'OK',
  619. headers: new AxiosHeaders(),
  620. config,
  621. });
  622. }
  623. if (supportedProtocols.indexOf(protocol) === -1) {
  624. return reject(
  625. new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_BAD_REQUEST, config)
  626. );
  627. }
  628. const headers = AxiosHeaders.from(config.headers).normalize();
  629. // Set User-Agent (required by some servers)
  630. // See https://github.com/axios/axios/issues/69
  631. // User-Agent is specified; handle case where no UA header is desired
  632. // Only set header if it hasn't been set in config
  633. headers.set('User-Agent', 'axios/' + VERSION, false);
  634. const { onUploadProgress, onDownloadProgress } = config;
  635. const maxRate = config.maxRate;
  636. let maxUploadRate = undefined;
  637. let maxDownloadRate = undefined;
  638. // support for spec compliant FormData objects
  639. if (utils.isSpecCompliantForm(data)) {
  640. const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
  641. data = formDataToStream(
  642. data,
  643. (formHeaders) => {
  644. headers.set(formHeaders);
  645. },
  646. {
  647. tag: `axios-${VERSION}-boundary`,
  648. boundary: (userBoundary && userBoundary[1]) || undefined,
  649. }
  650. );
  651. // support for https://www.npmjs.com/package/form-data api
  652. } else if (
  653. utils.isFormData(data) &&
  654. utils.isFunction(data.getHeaders) &&
  655. data.getHeaders !== Object.prototype.getHeaders
  656. ) {
  657. setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy'));
  658. if (!headers.hasContentLength()) {
  659. try {
  660. const knownLength = await util.promisify(data.getLength).call(data);
  661. Number.isFinite(knownLength) &&
  662. knownLength >= 0 &&
  663. headers.setContentLength(knownLength);
  664. /*eslint no-empty:0*/
  665. } catch (e) {}
  666. }
  667. } else if (utils.isBlob(data) || utils.isFile(data)) {
  668. data.size && headers.setContentType(data.type || 'application/octet-stream');
  669. headers.setContentLength(data.size || 0);
  670. data = stream.Readable.from(readBlob(data));
  671. } else if (data && !utils.isStream(data)) {
  672. if (Buffer.isBuffer(data)) {
  673. // Nothing to do...
  674. } else if (utils.isArrayBuffer(data)) {
  675. data = Buffer.from(new Uint8Array(data));
  676. } else if (utils.isString(data)) {
  677. data = Buffer.from(data, 'utf-8');
  678. } else {
  679. return reject(
  680. new AxiosError(
  681. 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
  682. AxiosError.ERR_BAD_REQUEST,
  683. config
  684. )
  685. );
  686. }
  687. // Add Content-Length header if data exists
  688. headers.setContentLength(data.length, false);
  689. if (maxBodyLength > -1 && data.length > maxBodyLength) {
  690. return reject(
  691. new AxiosError(
  692. 'Request body larger than maxBodyLength limit',
  693. AxiosError.ERR_BAD_REQUEST,
  694. config
  695. )
  696. );
  697. }
  698. }
  699. const contentLength = utils.toFiniteNumber(headers.getContentLength());
  700. if (utils.isArray(maxRate)) {
  701. maxUploadRate = maxRate[0];
  702. maxDownloadRate = maxRate[1];
  703. } else {
  704. maxUploadRate = maxDownloadRate = maxRate;
  705. }
  706. if (data && (onUploadProgress || maxUploadRate)) {
  707. if (!utils.isStream(data)) {
  708. data = stream.Readable.from(data, { objectMode: false });
  709. }
  710. data = stream.pipeline(
  711. [
  712. data,
  713. new AxiosTransformStream({
  714. maxRate: utils.toFiniteNumber(maxUploadRate),
  715. }),
  716. ],
  717. utils.noop
  718. );
  719. onUploadProgress &&
  720. data.on(
  721. 'progress',
  722. flushOnFinish(
  723. data,
  724. progressEventDecorator(
  725. contentLength,
  726. progressEventReducer(asyncDecorator(onUploadProgress, scheduleProgress), false, 3)
  727. )
  728. )
  729. );
  730. }
  731. // HTTP basic authentication
  732. let auth = undefined;
  733. const configAuth = own('auth');
  734. if (configAuth) {
  735. const username = utils.getSafeProp(configAuth, 'username') || '';
  736. const password = utils.getSafeProp(configAuth, 'password') || '';
  737. auth = username + ':' + password;
  738. }
  739. if (!auth && (parsed.username || parsed.password)) {
  740. const urlUsername = decodeURIComponentSafe(parsed.username);
  741. const urlPassword = decodeURIComponentSafe(parsed.password);
  742. auth = urlUsername + ':' + urlPassword;
  743. }
  744. auth && headers.delete('authorization');
  745. let path;
  746. try {
  747. path = buildURL(
  748. parsed.pathname + parsed.search,
  749. own('params'),
  750. own('paramsSerializer')
  751. ).replace(/^\?/, '');
  752. } catch (err) {
  753. return reject(
  754. AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config, null, null, {
  755. url: own('url'),
  756. exists: true
  757. })
  758. );
  759. }
  760. headers.set(
  761. 'Accept-Encoding',
  762. utils.hasOwnProp(transitional, 'advertiseZstdAcceptEncoding') &&
  763. transitional.advertiseZstdAcceptEncoding === true ? ACCEPT_ENCODING_WITH_ZSTD : ACCEPT_ENCODING,
  764. false
  765. );
  766. // Null-prototype to block prototype pollution gadgets on properties read
  767. // directly by Node's http.request (e.g. insecureHTTPParser, lookup).
  768. const options = Object.assign(Object.create(null), {
  769. path,
  770. method: method,
  771. headers: toByteStringHeaderObject(headers),
  772. agents: { http: httpAgent, https: httpsAgent },
  773. auth,
  774. protocol,
  775. family,
  776. beforeRedirect: dispatchBeforeRedirect,
  777. beforeRedirects: Object.create(null),
  778. http2Options,
  779. });
  780. // cacheable-lookup integration hotfix
  781. !utils.isUndefined(lookup) && (options.lookup = lookup);
  782. if (socketPath) {
  783. if (typeof socketPath !== 'string') {
  784. return reject(
  785. new AxiosError('socketPath must be a string', AxiosError.ERR_BAD_OPTION_VALUE, config)
  786. );
  787. }
  788. const allowedSocketPaths = own('allowedSocketPaths');
  789. if (allowedSocketPaths != null) {
  790. const allowed = Array.isArray(allowedSocketPaths)
  791. ? allowedSocketPaths
  792. : [allowedSocketPaths];
  793. const resolvedSocket = resolvePath(socketPath);
  794. const isAllowed = allowed.some(
  795. (entry) => typeof entry === 'string' && resolvePath(entry) === resolvedSocket
  796. );
  797. if (!isAllowed) {
  798. return reject(
  799. new AxiosError(
  800. `socketPath "${socketPath}" is not permitted by allowedSocketPaths`,
  801. AxiosError.ERR_BAD_OPTION_VALUE,
  802. config
  803. )
  804. );
  805. }
  806. }
  807. options.socketPath = socketPath;
  808. } else {
  809. options.hostname = parsed.hostname.startsWith('[')
  810. ? parsed.hostname.slice(1, -1)
  811. : parsed.hostname;
  812. options.port = parsed.port;
  813. setProxy(
  814. options,
  815. configProxy,
  816. protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path,
  817. false,
  818. httpsAgent,
  819. httpAgent
  820. );
  821. }
  822. let transport;
  823. let isNativeTransport = false;
  824. // True only for the follow-redirects transport, which applies
  825. // options.maxBodyLength itself. Every other transport (http2, native
  826. // http/https, a user-supplied custom transport) needs the explicit
  827. // byte-counting pipeline below to enforce maxBodyLength on streamed uploads.
  828. let transportEnforcesMaxBodyLength = false;
  829. const isHttpsRequest = isHttps.test(options.protocol);
  830. // Don't clobber a CONNECT-tunneling agent installed by setProxy() for an
  831. // HTTPS target.
  832. if (options.agent == null) {
  833. options.agent = isHttpsRequest ? httpsAgent : httpAgent;
  834. }
  835. if (isHttp2) {
  836. transport = http2Transport;
  837. } else {
  838. const configTransport = own('transport');
  839. if (configTransport) {
  840. transport = configTransport;
  841. } else if (maxRedirects === 0) {
  842. transport = isHttpsRequest ? https : http;
  843. isNativeTransport = true;
  844. } else {
  845. transportEnforcesMaxBodyLength = true;
  846. options.sensitiveHeaders = [];
  847. if (maxRedirects) {
  848. options.maxRedirects = maxRedirects;
  849. }
  850. const configBeforeRedirect = own('beforeRedirect');
  851. if (configBeforeRedirect) {
  852. options.beforeRedirects.config = configBeforeRedirect;
  853. }
  854. if (auth) {
  855. // Restore HTTP Basic credentials on same-origin redirects only.
  856. // follow-redirects >= 1.15.8 strips Authorization on every redirect (see #6929);
  857. // cross-origin stripping is the documented mitigation for T-R2 in THREATMODEL.md
  858. // and is preserved by deliberately not restoring on origin change.
  859. const requestOrigin = parsed.origin;
  860. const authToRestore = auth;
  861. options.beforeRedirects.auth = function beforeRedirectAuth(redirectOptions) {
  862. try {
  863. if (new URL(redirectOptions.href).origin === requestOrigin) {
  864. redirectOptions.auth = authToRestore;
  865. }
  866. } catch (e) {
  867. // ignore malformed URL: leaving auth stripped is fail-safe
  868. }
  869. };
  870. }
  871. const sensitiveHeaders = own('sensitiveHeaders');
  872. if (sensitiveHeaders != null) {
  873. if (!utils.isArray(sensitiveHeaders)) {
  874. return reject(
  875. new AxiosError(
  876. 'sensitiveHeaders must be an array of strings',
  877. AxiosError.ERR_BAD_OPTION_VALUE,
  878. config
  879. )
  880. );
  881. }
  882. const sensitiveSet = new Set();
  883. for (const header of sensitiveHeaders) {
  884. if (!utils.isString(header)) {
  885. return reject(
  886. new AxiosError(
  887. 'sensitiveHeaders must be an array of strings',
  888. AxiosError.ERR_BAD_OPTION_VALUE,
  889. config
  890. )
  891. );
  892. }
  893. sensitiveSet.add(header.toLowerCase());
  894. }
  895. if (sensitiveSet.size) {
  896. options.sensitiveHeaders = Array.from(sensitiveSet);
  897. options.beforeRedirects.sensitiveHeaders = function beforeRedirectSensitiveHeaders(
  898. redirectOptions,
  899. requestDetails
  900. ) {
  901. if (!isSameOriginRedirect(redirectOptions, requestDetails)) {
  902. stripMatchingHeaders(redirectOptions.headers, sensitiveSet);
  903. }
  904. };
  905. }
  906. }
  907. transport = isHttpsRequest ? httpsFollow : httpFollow;
  908. }
  909. }
  910. // Set an explicit maxBodyLength option for transports that inspect it.
  911. // When maxBodyLength is -1 (default/unlimited), use Infinity so
  912. // follow-redirects does not fall back to its own 10MB default.
  913. if (maxBodyLength > -1) {
  914. options.maxBodyLength = maxBodyLength;
  915. } else {
  916. options.maxBodyLength = Infinity;
  917. }
  918. // Always set an explicit own value so a polluted
  919. // Object.prototype.insecureHTTPParser cannot enable the lenient parser
  920. // through Node's internal options copy
  921. options.insecureHTTPParser = Boolean(own('insecureHTTPParser'));
  922. // Create the request
  923. req = transport.request(options, function handleResponse(res) {
  924. clearConnectPhaseTimer();
  925. if (req.destroyed) return;
  926. const streams = [res];
  927. const responseLength = utils.toFiniteNumber(res.headers['content-length']);
  928. if (onDownloadProgress || maxDownloadRate) {
  929. const transformStream = new AxiosTransformStream({
  930. maxRate: utils.toFiniteNumber(maxDownloadRate),
  931. });
  932. onDownloadProgress &&
  933. transformStream.on(
  934. 'progress',
  935. flushOnFinish(
  936. transformStream,
  937. progressEventDecorator(
  938. responseLength,
  939. progressEventReducer(asyncDecorator(onDownloadProgress, scheduleProgress), true, 3)
  940. )
  941. )
  942. );
  943. streams.push(transformStream);
  944. }
  945. // decompress the response body transparently if required
  946. let responseStream = res;
  947. // return the last request in case of redirects
  948. const lastRequest = res.req || req;
  949. // if decompress disabled we should not decompress
  950. if (decompress !== false && res.headers['content-encoding']) {
  951. // if no content, but headers still say that it is encoded,
  952. // remove the header not confuse downstream operations
  953. if (method === 'HEAD' || res.statusCode === 204) {
  954. delete res.headers['content-encoding'];
  955. }
  956. switch ((res.headers['content-encoding'] || '').toLowerCase()) {
  957. /*eslint default-case:0*/
  958. case 'gzip':
  959. case 'x-gzip':
  960. case 'compress':
  961. case 'x-compress':
  962. // add the unzipper to the body stream processing pipeline
  963. streams.push(zlib.createUnzip(zlibOptions));
  964. // remove the content-encoding in order to not confuse downstream operations
  965. delete res.headers['content-encoding'];
  966. break;
  967. case 'deflate':
  968. streams.push(new ZlibHeaderTransformStream());
  969. // add the unzipper to the body stream processing pipeline
  970. streams.push(zlib.createUnzip(zlibOptions));
  971. // remove the content-encoding in order to not confuse downstream operations
  972. delete res.headers['content-encoding'];
  973. break;
  974. case 'br':
  975. if (isBrotliSupported) {
  976. streams.push(zlib.createBrotliDecompress(brotliOptions));
  977. delete res.headers['content-encoding'];
  978. }
  979. break;
  980. case 'zstd':
  981. if (isZstdSupported) {
  982. streams.push(zlib.createZstdDecompress(zstdOptions));
  983. delete res.headers['content-encoding'];
  984. }
  985. break;
  986. }
  987. }
  988. responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0];
  989. const response = {
  990. status: res.statusCode,
  991. statusText: res.statusMessage,
  992. headers: new AxiosHeaders(res.headers),
  993. config,
  994. request: lastRequest,
  995. };
  996. if (responseType === 'stream') {
  997. // Enforce maxContentLength on streamed responses; previously this
  998. // was applied only to buffered responses.
  999. if (maxContentLength > -1) {
  1000. const limit = maxContentLength;
  1001. const source = responseStream;
  1002. async function* enforceMaxContentLength() {
  1003. let totalResponseBytes = 0;
  1004. for await (const chunk of source) {
  1005. totalResponseBytes += chunk.length;
  1006. if (totalResponseBytes > limit) {
  1007. throw new AxiosError(
  1008. 'maxContentLength size of ' + limit + ' exceeded',
  1009. AxiosError.ERR_BAD_RESPONSE,
  1010. config,
  1011. lastRequest
  1012. );
  1013. }
  1014. yield chunk;
  1015. }
  1016. }
  1017. responseStream = stream.Readable.from(enforceMaxContentLength(), {
  1018. objectMode: false,
  1019. });
  1020. }
  1021. response.data = responseStream;
  1022. settle(resolve, reject, response);
  1023. } else {
  1024. const responseBuffer = [];
  1025. let totalResponseBytes = 0;
  1026. responseStream.on('data', function handleStreamData(chunk) {
  1027. responseBuffer.push(chunk);
  1028. totalResponseBytes += chunk.length;
  1029. // make sure the content length is not over the maxContentLength if specified
  1030. if (maxContentLength > -1 && totalResponseBytes > maxContentLength) {
  1031. // stream.destroy() emit aborted event before calling reject() on Node.js v16
  1032. rejected = true;
  1033. responseStream.destroy();
  1034. abort(
  1035. new AxiosError(
  1036. 'maxContentLength size of ' + maxContentLength + ' exceeded',
  1037. AxiosError.ERR_BAD_RESPONSE,
  1038. config,
  1039. lastRequest
  1040. )
  1041. );
  1042. }
  1043. });
  1044. responseStream.on('aborted', function handlerStreamAborted() {
  1045. if (rejected) {
  1046. return;
  1047. }
  1048. const err = new AxiosError(
  1049. 'stream has been aborted',
  1050. AxiosError.ERR_BAD_RESPONSE,
  1051. config,
  1052. lastRequest,
  1053. response
  1054. );
  1055. responseStream.destroy(err);
  1056. reject(err);
  1057. });
  1058. responseStream.on('error', function handleStreamError(err) {
  1059. if (rejected) return;
  1060. reject(AxiosError.from(err, null, config, lastRequest, response));
  1061. });
  1062. responseStream.on('end', function handleStreamEnd() {
  1063. try {
  1064. let responseData =
  1065. responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
  1066. if (responseType !== 'arraybuffer') {
  1067. responseData = responseData.toString(responseEncoding);
  1068. if (!responseEncoding || responseEncoding === 'utf8') {
  1069. responseData = utils.stripBOM(responseData);
  1070. }
  1071. }
  1072. response.data = responseData;
  1073. } catch (err) {
  1074. return reject(AxiosError.from(err, null, config, response.request, response));
  1075. }
  1076. settle(resolve, reject, response);
  1077. });
  1078. }
  1079. abortEmitter.once('abort', (err) => {
  1080. if (!responseStream.destroyed) {
  1081. responseStream.emit('error', err);
  1082. responseStream.destroy();
  1083. }
  1084. });
  1085. });
  1086. abortEmitter.once('abort', (err) => {
  1087. if (req.close) {
  1088. req.close();
  1089. } else {
  1090. req.destroy(err);
  1091. }
  1092. });
  1093. // Handle errors
  1094. req.on('error', function handleRequestError(err) {
  1095. reject(AxiosError.from(err, null, config, req));
  1096. });
  1097. // set tcp keep alive to prevent drop connection by peer
  1098. // Track every socket bound to this outer RedirectableRequest so a single
  1099. // 'close' listener can release ownership on all of them. follow-redirects
  1100. // re-emits the 'socket' event for each hop's native request onto the same
  1101. // outer request, so attaching per-request listeners inside this handler
  1102. // would accumulate across hops and trigger MaxListenersExceededWarning at
  1103. // >= 11 redirects. Clearing only the last-bound socket would leave stale
  1104. // kAxiosCurrentReq refs on earlier hop sockets returned to the keep-alive
  1105. // pool, causing an idle-pool 'error' to be attributed to a closed req.
  1106. const boundSockets = new Set();
  1107. req.on('socket', function handleRequestSocket(socket) {
  1108. // default interval of sending ack packet is 1 minute
  1109. // proxy agents (e.g. agent-base) may return a generic Duplex stream
  1110. // that doesn't have setKeepAlive, so guard before calling
  1111. if (typeof socket.setKeepAlive === 'function') {
  1112. socket.setKeepAlive(true, 1000 * 60);
  1113. }
  1114. // Install a single 'error' listener per socket (not per request) to avoid
  1115. // accumulating listeners on pooled keep-alive sockets that get reassigned
  1116. // to new requests before the previous request's 'close' fires (issue #10780).
  1117. // The listener is bound to the socket's currently-active request via a
  1118. // symbol, which is swapped as the socket is reassigned.
  1119. if (!socket[kAxiosSocketListener]) {
  1120. socket.on('error', function handleSocketError(err) {
  1121. const current = socket[kAxiosCurrentReq];
  1122. if (current && !current.destroyed) {
  1123. current.destroy(err);
  1124. }
  1125. });
  1126. socket[kAxiosSocketListener] = true;
  1127. }
  1128. socket[kAxiosCurrentReq] = req;
  1129. boundSockets.add(socket);
  1130. });
  1131. req.once('close', function clearCurrentReq() {
  1132. clearConnectPhaseTimer();
  1133. for (const socket of boundSockets) {
  1134. if (socket[kAxiosCurrentReq] === req) {
  1135. socket[kAxiosCurrentReq] = null;
  1136. }
  1137. }
  1138. boundSockets.clear();
  1139. });
  1140. // Handle request timeout
  1141. if (own('timeout')) {
  1142. // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
  1143. const timeout = parseInt(own('timeout'), 10);
  1144. if (Number.isNaN(timeout)) {
  1145. abort(
  1146. new AxiosError(
  1147. 'error trying to parse `config.timeout` to int',
  1148. AxiosError.ERR_BAD_OPTION_VALUE,
  1149. config,
  1150. req
  1151. )
  1152. );
  1153. return;
  1154. }
  1155. const handleTimeout = function handleTimeout() {
  1156. if (isDone) return;
  1157. abort(createTimeoutError());
  1158. };
  1159. if (isNativeTransport && timeout > 0) {
  1160. // Native ClientRequest#setTimeout starts from the socket lifecycle and
  1161. // may not fire while TCP connect is still pending. Mirror the
  1162. // follow-redirects wall-clock timer for the maxRedirects === 0 path.
  1163. connectPhaseTimer = setTimeout(handleTimeout, timeout);
  1164. }
  1165. // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
  1166. // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
  1167. // 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.
  1168. // And then these socket which be hang up will devouring CPU little by little.
  1169. // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
  1170. req.setTimeout(timeout, handleTimeout);
  1171. } else {
  1172. // explicitly reset the socket timeout value for a possible `keep-alive` request
  1173. req.setTimeout(0);
  1174. }
  1175. // Send the request
  1176. if (utils.isStream(data)) {
  1177. let ended = false;
  1178. let errored = false;
  1179. data.on('end', () => {
  1180. ended = true;
  1181. });
  1182. data.once('error', (err) => {
  1183. errored = true;
  1184. req.destroy(err);
  1185. });
  1186. data.on('close', () => {
  1187. if (!ended && !errored) {
  1188. abort(new CanceledError('Request stream has been aborted', config, req));
  1189. }
  1190. });
  1191. // Enforce maxBodyLength for streamed uploads on every transport that
  1192. // does not apply options.maxBodyLength itself (native http/https, http2,
  1193. // and user-supplied custom transports). The follow-redirects transport
  1194. // enforces it on the redirected HTTP/1 path.
  1195. let uploadStream = data;
  1196. if (maxBodyLength > -1 && !transportEnforcesMaxBodyLength) {
  1197. const limit = maxBodyLength;
  1198. let bytesSent = 0;
  1199. uploadStream = stream.pipeline(
  1200. [
  1201. data,
  1202. new stream.Transform({
  1203. transform(chunk, _enc, cb) {
  1204. bytesSent += chunk.length;
  1205. if (bytesSent > limit) {
  1206. return cb(
  1207. new AxiosError(
  1208. 'Request body larger than maxBodyLength limit',
  1209. AxiosError.ERR_BAD_REQUEST,
  1210. config,
  1211. req
  1212. )
  1213. );
  1214. }
  1215. cb(null, chunk);
  1216. },
  1217. }),
  1218. ],
  1219. utils.noop
  1220. );
  1221. uploadStream.on('error', (err) => {
  1222. if (!req.destroyed) req.destroy(err);
  1223. });
  1224. }
  1225. uploadStream.pipe(req);
  1226. } else {
  1227. data && req.write(data);
  1228. req.end();
  1229. }
  1230. });
  1231. };
  1232. export const __setProxy = setProxy;
  1233. export const __isNodeEnvProxyEnabled = isNodeEnvProxyEnabled;
  1234. export const __isSameOriginRedirect = isSameOriginRedirect;