index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. 'use strict'
  2. const { URL } = require('url')
  3. const http = require('http')
  4. const https = require('https')
  5. const zlib = require('minizlib')
  6. const { Minipass } = require('minipass')
  7. const Body = require('./body.js')
  8. const { writeToStream, getTotalBytes } = Body
  9. const Response = require('./response.js')
  10. const Headers = require('./headers.js')
  11. const { createHeadersLenient } = Headers
  12. const Request = require('./request.js')
  13. const { getNodeRequestOptions } = Request
  14. const FetchError = require('./fetch-error.js')
  15. const AbortError = require('./abort-error.js')
  16. // XXX this should really be split up and unit-ized for easier testing
  17. // and better DRY implementation of data/http request aborting
  18. const fetch = async (url, opts) => {
  19. if (/^data:/.test(url)) {
  20. const request = new Request(url, opts)
  21. // delay 1 promise tick so that the consumer can abort right away
  22. return Promise.resolve().then(() => new Promise((resolve, reject) => {
  23. let type, data
  24. try {
  25. const { pathname, search } = new URL(url)
  26. const split = pathname.split(',')
  27. if (split.length < 2) {
  28. throw new Error('invalid data: URI')
  29. }
  30. const mime = split.shift()
  31. const base64 = /;base64$/.test(mime)
  32. type = base64 ? mime.slice(0, -1 * ';base64'.length) : mime
  33. const rawData = decodeURIComponent(split.join(',') + search)
  34. data = base64 ? Buffer.from(rawData, 'base64') : Buffer.from(rawData)
  35. } catch (er) {
  36. return reject(new FetchError(`[${request.method}] ${
  37. request.url} invalid URL, ${er.message}`, 'system', er))
  38. }
  39. const { signal } = request
  40. if (signal && signal.aborted) {
  41. return reject(new AbortError('The user aborted a request.'))
  42. }
  43. const headers = { 'Content-Length': data.length }
  44. if (type) {
  45. headers['Content-Type'] = type
  46. }
  47. return resolve(new Response(data, { headers }))
  48. }))
  49. }
  50. return new Promise((resolve, reject) => {
  51. // build request object
  52. const request = new Request(url, opts)
  53. let options
  54. try {
  55. options = getNodeRequestOptions(request)
  56. } catch (er) {
  57. return reject(er)
  58. }
  59. const send = (options.protocol === 'https:' ? https : http).request
  60. const { signal } = request
  61. let response = null
  62. const abort = () => {
  63. const error = new AbortError('The user aborted a request.')
  64. reject(error)
  65. if (Minipass.isStream(request.body) &&
  66. typeof request.body.destroy === 'function') {
  67. request.body.destroy(error)
  68. }
  69. if (response && response.body) {
  70. response.body.emit('error', error)
  71. }
  72. }
  73. if (signal && signal.aborted) {
  74. return abort()
  75. }
  76. const abortAndFinalize = () => {
  77. abort()
  78. finalize()
  79. }
  80. const finalize = () => {
  81. req.abort()
  82. if (signal) {
  83. signal.removeEventListener('abort', abortAndFinalize)
  84. }
  85. clearTimeout(reqTimeout)
  86. }
  87. // send request
  88. const req = send(options)
  89. if (signal) {
  90. signal.addEventListener('abort', abortAndFinalize)
  91. }
  92. let reqTimeout = null
  93. if (request.timeout) {
  94. req.once('socket', () => {
  95. reqTimeout = setTimeout(() => {
  96. reject(new FetchError(`network timeout at: ${
  97. request.url}`, 'request-timeout'))
  98. finalize()
  99. }, request.timeout)
  100. })
  101. }
  102. req.on('error', er => {
  103. // if a 'response' event is emitted before the 'error' event, then by the
  104. // time this handler is run it's too late to reject the Promise for the
  105. // response. instead, we forward the error event to the response stream
  106. // so that the error will surface to the user when they try to consume
  107. // the body. this is done as a side effect of aborting the request except
  108. // for in windows, where we must forward the event manually, otherwise
  109. // there is no longer a ref'd socket attached to the request and the
  110. // stream never ends so the event loop runs out of work and the process
  111. // exits without warning.
  112. // coverage skipped here due to the difficulty in testing
  113. // istanbul ignore next
  114. if (req.res) {
  115. req.res.emit('error', er)
  116. }
  117. reject(new FetchError(`request to ${request.url} failed, reason: ${
  118. er.message}`, 'system', er))
  119. finalize()
  120. })
  121. req.on('response', res => {
  122. clearTimeout(reqTimeout)
  123. const headers = createHeadersLenient(res.headers)
  124. // HTTP fetch step 5
  125. if (fetch.isRedirect(res.statusCode)) {
  126. // HTTP fetch step 5.2
  127. const location = headers.get('Location')
  128. // HTTP fetch step 5.3
  129. let locationURL = null
  130. try {
  131. locationURL = location === null ? null : new URL(location, request.url).toString()
  132. } catch {
  133. // error here can only be invalid URL in Location: header
  134. // do not throw when options.redirect == manual
  135. // let the user extract the errorneous redirect URL
  136. if (request.redirect !== 'manual') {
  137. /* eslint-disable-next-line max-len */
  138. reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'))
  139. finalize()
  140. return
  141. }
  142. }
  143. // HTTP fetch step 5.5
  144. if (request.redirect === 'error') {
  145. reject(new FetchError('uri requested responds with a redirect, ' +
  146. `redirect mode is set to error: ${request.url}`, 'no-redirect'))
  147. finalize()
  148. return
  149. } else if (request.redirect === 'manual') {
  150. // node-fetch-specific step: make manual redirect a bit easier to
  151. // use by setting the Location header value to the resolved URL.
  152. if (locationURL !== null) {
  153. // handle corrupted header
  154. try {
  155. headers.set('Location', locationURL)
  156. } catch (err) {
  157. /* istanbul ignore next: nodejs server prevent invalid
  158. response headers, we can't test this through normal
  159. request */
  160. reject(err)
  161. }
  162. }
  163. } else if (request.redirect === 'follow' && locationURL !== null) {
  164. // HTTP-redirect fetch step 5
  165. if (request.counter >= request.follow) {
  166. reject(new FetchError(`maximum redirect reached at: ${
  167. request.url}`, 'max-redirect'))
  168. finalize()
  169. return
  170. }
  171. // HTTP-redirect fetch step 9
  172. if (res.statusCode !== 303 &&
  173. request.body &&
  174. getTotalBytes(request) === null) {
  175. reject(new FetchError(
  176. 'Cannot follow redirect with body being a readable stream',
  177. 'unsupported-redirect'
  178. ))
  179. finalize()
  180. return
  181. }
  182. // Update host due to redirection
  183. request.headers.set('host', (new URL(locationURL)).host)
  184. // HTTP-redirect fetch step 6 (counter increment)
  185. // Create a new Request object.
  186. const requestOpts = {
  187. headers: new Headers(request.headers),
  188. follow: request.follow,
  189. counter: request.counter + 1,
  190. agent: request.agent,
  191. compress: request.compress,
  192. method: request.method,
  193. body: request.body,
  194. signal: request.signal,
  195. timeout: request.timeout,
  196. }
  197. // if the redirect is to a new hostname, strip the authorization and cookie headers
  198. const parsedOriginal = new URL(request.url)
  199. const parsedRedirect = new URL(locationURL)
  200. if (parsedOriginal.hostname !== parsedRedirect.hostname) {
  201. requestOpts.headers.delete('authorization')
  202. requestOpts.headers.delete('cookie')
  203. }
  204. // HTTP-redirect fetch step 11
  205. if (res.statusCode === 303 || (
  206. (res.statusCode === 301 || res.statusCode === 302) &&
  207. request.method === 'POST'
  208. )) {
  209. requestOpts.method = 'GET'
  210. requestOpts.body = undefined
  211. requestOpts.headers.delete('content-length')
  212. }
  213. // HTTP-redirect fetch step 15
  214. resolve(fetch(new Request(locationURL, requestOpts)))
  215. finalize()
  216. return
  217. }
  218. } // end if(isRedirect)
  219. // prepare response
  220. res.once('end', () =>
  221. signal && signal.removeEventListener('abort', abortAndFinalize))
  222. const body = new Minipass()
  223. // if an error occurs, either on the response stream itself, on one of the
  224. // decoder streams, or a response length timeout from the Body class, we
  225. // forward the error through to our internal body stream. If we see an
  226. // error event on that, we call finalize to abort the request and ensure
  227. // we don't leave a socket believing a request is in flight.
  228. // this is difficult to test, so lacks specific coverage.
  229. body.on('error', finalize)
  230. // exceedingly rare that the stream would have an error,
  231. // but just in case we proxy it to the stream in use.
  232. res.on('error', /* istanbul ignore next */ er => body.emit('error', er))
  233. res.on('data', (chunk) => body.write(chunk))
  234. res.on('end', () => body.end())
  235. const responseOptions = {
  236. url: request.url,
  237. status: res.statusCode,
  238. statusText: res.statusMessage,
  239. headers: headers,
  240. size: request.size,
  241. timeout: request.timeout,
  242. counter: request.counter,
  243. trailer: new Promise(resolveTrailer =>
  244. res.on('end', () => resolveTrailer(createHeadersLenient(res.trailers)))),
  245. }
  246. // HTTP-network fetch step 12.1.1.3
  247. const codings = headers.get('Content-Encoding')
  248. // HTTP-network fetch step 12.1.1.4: handle content codings
  249. // in following scenarios we ignore compression support
  250. // 1. compression support is disabled
  251. // 2. HEAD request
  252. // 3. no Content-Encoding header
  253. // 4. no content response (204)
  254. // 5. content not modified response (304)
  255. if (!request.compress ||
  256. request.method === 'HEAD' ||
  257. codings === null ||
  258. res.statusCode === 204 ||
  259. res.statusCode === 304) {
  260. response = new Response(body, responseOptions)
  261. resolve(response)
  262. return
  263. }
  264. // Be less strict when decoding compressed responses, since sometimes
  265. // servers send slightly invalid responses that are still accepted
  266. // by common browsers.
  267. // Always using Z_SYNC_FLUSH is what cURL does.
  268. const zlibOptions = {
  269. flush: zlib.constants.Z_SYNC_FLUSH,
  270. finishFlush: zlib.constants.Z_SYNC_FLUSH,
  271. }
  272. // for gzip
  273. if (codings === 'gzip' || codings === 'x-gzip') {
  274. const unzip = new zlib.Gunzip(zlibOptions)
  275. response = new Response(
  276. // exceedingly rare that the stream would have an error,
  277. // but just in case we proxy it to the stream in use.
  278. body.on('error', /* istanbul ignore next */ er => unzip.emit('error', er)).pipe(unzip),
  279. responseOptions
  280. )
  281. resolve(response)
  282. return
  283. }
  284. // for deflate
  285. if (codings === 'deflate' || codings === 'x-deflate') {
  286. // handle the infamous raw deflate response from old servers
  287. // a hack for old IIS and Apache servers
  288. res.once('data', chunk => {
  289. // see http://stackoverflow.com/questions/37519828
  290. const decoder = (chunk[0] & 0x0F) === 0x08
  291. ? new zlib.Inflate()
  292. : new zlib.InflateRaw()
  293. // exceedingly rare that the stream would have an error,
  294. // but just in case we proxy it to the stream in use.
  295. body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder)
  296. response = new Response(decoder, responseOptions)
  297. resolve(response)
  298. })
  299. return
  300. }
  301. // for br
  302. if (codings === 'br') {
  303. // ignoring coverage so tests don't have to fake support (or lack of) for brotli
  304. // istanbul ignore next
  305. try {
  306. var decoder = new zlib.BrotliDecompress()
  307. } catch (err) {
  308. reject(err)
  309. finalize()
  310. return
  311. }
  312. // exceedingly rare that the stream would have an error,
  313. // but just in case we proxy it to the stream in use.
  314. body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder)
  315. response = new Response(decoder, responseOptions)
  316. resolve(response)
  317. return
  318. }
  319. // otherwise, use response as-is
  320. response = new Response(body, responseOptions)
  321. resolve(response)
  322. })
  323. writeToStream(req, request)
  324. })
  325. }
  326. module.exports = fetch
  327. fetch.isRedirect = code =>
  328. code === 301 ||
  329. code === 302 ||
  330. code === 303 ||
  331. code === 307 ||
  332. code === 308
  333. fetch.Headers = Headers
  334. fetch.Request = Request
  335. fetch.Response = Response
  336. fetch.FetchError = FetchError
  337. fetch.AbortError = AbortError