net-client-request.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. import * as url from 'url';
  2. import { Readable, Writable } from 'stream';
  3. import type {
  4. ClientRequestConstructorOptions,
  5. UploadProgress
  6. } from 'electron/common';
  7. const {
  8. isValidHeaderName,
  9. isValidHeaderValue,
  10. createURLLoader
  11. } = process._linkedBinding('electron_common_net');
  12. const kHttpProtocols = new Set(['http:', 'https:']);
  13. // set of headers that Node.js discards duplicates for
  14. // see https://nodejs.org/api/http.html#http_message_headers
  15. const discardableDuplicateHeaders = new Set([
  16. 'content-type',
  17. 'content-length',
  18. 'user-agent',
  19. 'referer',
  20. 'host',
  21. 'authorization',
  22. 'proxy-authorization',
  23. 'if-modified-since',
  24. 'if-unmodified-since',
  25. 'from',
  26. 'location',
  27. 'max-forwards',
  28. 'retry-after',
  29. 'etag',
  30. 'last-modified',
  31. 'server',
  32. 'age',
  33. 'expires'
  34. ]);
  35. class IncomingMessage extends Readable {
  36. _shouldPush: boolean = false;
  37. _data: (Buffer | null)[] = [];
  38. _responseHead: NodeJS.ResponseHead;
  39. _resume: (() => void) | null = null;
  40. constructor (responseHead: NodeJS.ResponseHead) {
  41. super();
  42. this._responseHead = responseHead;
  43. }
  44. get statusCode () {
  45. return this._responseHead.statusCode;
  46. }
  47. get statusMessage () {
  48. return this._responseHead.statusMessage;
  49. }
  50. get headers () {
  51. const filteredHeaders: Record<string, string | string[]> = {};
  52. const { headers, rawHeaders } = this._responseHead;
  53. for (const [name, values] of Object.entries(headers)) {
  54. filteredHeaders[name] = discardableDuplicateHeaders.has(name) ? values[0] : values.join(', ');
  55. }
  56. const cookies = rawHeaders.filter(({ key }) => key.toLowerCase() === 'set-cookie').map(({ value }) => value);
  57. // keep set-cookie as an array per Node.js rules
  58. // see https://nodejs.org/api/http.html#http_message_headers
  59. if (cookies.length) { filteredHeaders['set-cookie'] = cookies; }
  60. return filteredHeaders;
  61. }
  62. get rawHeaders () {
  63. const rawHeadersArr: string[] = [];
  64. const { rawHeaders } = this._responseHead;
  65. for (const header of rawHeaders) {
  66. rawHeadersArr.push(header.key, header.value);
  67. }
  68. return rawHeadersArr;
  69. }
  70. get httpVersion () {
  71. return `${this.httpVersionMajor}.${this.httpVersionMinor}`;
  72. }
  73. get httpVersionMajor () {
  74. return this._responseHead.httpVersion.major;
  75. }
  76. get httpVersionMinor () {
  77. return this._responseHead.httpVersion.minor;
  78. }
  79. get rawTrailers () {
  80. throw new Error('HTTP trailers are not supported');
  81. }
  82. get trailers () {
  83. throw new Error('HTTP trailers are not supported');
  84. }
  85. _storeInternalData (chunk: Buffer | null, resume: (() => void) | null) {
  86. // save the network callback for use in _pushInternalData
  87. this._resume = resume;
  88. this._data.push(chunk);
  89. this._pushInternalData();
  90. }
  91. _pushInternalData () {
  92. while (this._shouldPush && this._data.length > 0) {
  93. const chunk = this._data.shift();
  94. this._shouldPush = this.push(chunk);
  95. }
  96. if (this._shouldPush && this._resume) {
  97. // Reset the callback, so that a new one is used for each
  98. // batch of throttled data. Do this before calling resume to avoid a
  99. // potential race-condition
  100. const resume = this._resume;
  101. this._resume = null;
  102. resume();
  103. }
  104. }
  105. _read () {
  106. this._shouldPush = true;
  107. this._pushInternalData();
  108. }
  109. }
  110. /** Writable stream that buffers up everything written to it. */
  111. class SlurpStream extends Writable {
  112. _data: Buffer;
  113. constructor () {
  114. super();
  115. this._data = Buffer.alloc(0);
  116. }
  117. _write (chunk: Buffer, encoding: string, callback: () => void) {
  118. this._data = Buffer.concat([this._data, chunk]);
  119. callback();
  120. }
  121. data () { return this._data; }
  122. }
  123. class ChunkedBodyStream extends Writable {
  124. _pendingChunk: Buffer | undefined;
  125. _downstream?: NodeJS.DataPipe;
  126. _pendingCallback?: (error?: Error) => void;
  127. _clientRequest: ClientRequest;
  128. constructor (clientRequest: ClientRequest) {
  129. super();
  130. this._clientRequest = clientRequest;
  131. }
  132. _write (chunk: Buffer, encoding: string, callback: () => void) {
  133. if (this._downstream) {
  134. this._downstream.write(chunk).then(callback, callback);
  135. } else {
  136. // the contract of _write is that we won't be called again until we call
  137. // the callback, so we're good to just save a single chunk.
  138. this._pendingChunk = chunk;
  139. this._pendingCallback = callback;
  140. // The first write to a chunked body stream begins the request.
  141. this._clientRequest._startRequest();
  142. }
  143. }
  144. _final (callback: () => void) {
  145. this._downstream!.done();
  146. callback();
  147. }
  148. startReading (pipe: NodeJS.DataPipe) {
  149. if (this._downstream) {
  150. throw new Error('two startReading calls???');
  151. }
  152. this._downstream = pipe;
  153. if (this._pendingChunk) {
  154. const doneWriting = (maybeError: Error | void) => {
  155. // If the underlying request has been aborted, we honestly don't care about the error
  156. // all work should cease as soon as we abort anyway, this error is probably a
  157. // "mojo pipe disconnected" error (code=9)
  158. if (this._clientRequest._aborted) return;
  159. const cb = this._pendingCallback!;
  160. delete this._pendingCallback;
  161. delete this._pendingChunk;
  162. cb(maybeError || undefined);
  163. };
  164. this._downstream.write(this._pendingChunk).then(doneWriting, doneWriting);
  165. }
  166. }
  167. }
  168. type RedirectPolicy = 'manual' | 'follow' | 'error';
  169. const kAllowNonHttpProtocols = Symbol('kAllowNonHttpProtocols');
  170. export function allowAnyProtocol (opts: ClientRequestConstructorOptions): ClientRequestConstructorOptions {
  171. return {
  172. ...opts,
  173. [kAllowNonHttpProtocols]: true
  174. } as any;
  175. }
  176. type ExtraURLLoaderOptions = {
  177. redirectPolicy: RedirectPolicy;
  178. headers: Record<string, { name: string, value: string | string[] }>;
  179. allowNonHttpProtocols: boolean;
  180. }
  181. function parseOptions (optionsIn: ClientRequestConstructorOptions | string): NodeJS.CreateURLLoaderOptions & ExtraURLLoaderOptions {
  182. // eslint-disable-next-line node/no-deprecated-api
  183. const options: any = typeof optionsIn === 'string' ? url.parse(optionsIn) : { ...optionsIn };
  184. let urlStr: string = options.url;
  185. if (!urlStr) {
  186. const urlObj: url.UrlObject = {};
  187. const protocol = options.protocol || 'http:';
  188. urlObj.protocol = protocol;
  189. if (options.host) {
  190. urlObj.host = options.host;
  191. } else {
  192. if (options.hostname) {
  193. urlObj.hostname = options.hostname;
  194. } else {
  195. urlObj.hostname = 'localhost';
  196. }
  197. if (options.port) {
  198. urlObj.port = options.port;
  199. }
  200. }
  201. if (options.path && / /.test(options.path)) {
  202. // The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/
  203. // with an additional rule for ignoring percentage-escaped characters
  204. // but that's a) hard to capture in a regular expression that performs
  205. // well, and b) possibly too restrictive for real-world usage. That's
  206. // why it only scans for spaces because those are guaranteed to create
  207. // an invalid request.
  208. throw new TypeError('Request path contains unescaped characters');
  209. }
  210. // eslint-disable-next-line node/no-deprecated-api
  211. const pathObj = url.parse(options.path || '/');
  212. urlObj.pathname = pathObj.pathname;
  213. urlObj.search = pathObj.search;
  214. urlObj.hash = pathObj.hash;
  215. urlStr = url.format(urlObj);
  216. }
  217. const redirectPolicy = options.redirect || 'follow';
  218. if (!['follow', 'error', 'manual'].includes(redirectPolicy)) {
  219. throw new Error('redirect mode should be one of follow, error or manual');
  220. }
  221. if (options.headers != null && typeof options.headers !== 'object') {
  222. throw new TypeError('headers must be an object');
  223. }
  224. const urlLoaderOptions: NodeJS.CreateURLLoaderOptions & { redirectPolicy: RedirectPolicy, headers: Record<string, { name: string, value: string | string[] }>, allowNonHttpProtocols: boolean } = {
  225. method: (options.method || 'GET').toUpperCase(),
  226. url: urlStr,
  227. redirectPolicy,
  228. headers: {},
  229. body: null as any,
  230. useSessionCookies: options.useSessionCookies,
  231. credentials: options.credentials,
  232. origin: options.origin,
  233. referrerPolicy: options.referrerPolicy,
  234. cache: options.cache,
  235. allowNonHttpProtocols: Object.hasOwn(options, kAllowNonHttpProtocols)
  236. };
  237. const headers: Record<string, string | string[]> = options.headers || {};
  238. for (const [name, value] of Object.entries(headers)) {
  239. if (!isValidHeaderName(name)) {
  240. throw new Error(`Invalid header name: '${name}'`);
  241. }
  242. if (!isValidHeaderValue(value.toString())) {
  243. throw new Error(`Invalid value for header '${name}': '${value}'`);
  244. }
  245. const key = name.toLowerCase();
  246. urlLoaderOptions.headers[key] = { name, value };
  247. }
  248. if (process.type !== 'utility') {
  249. const { Session } = process._linkedBinding('electron_browser_session');
  250. if (options.session) {
  251. if (!(options.session instanceof Session)) { throw new TypeError('`session` should be an instance of the Session class'); }
  252. urlLoaderOptions.session = options.session;
  253. } else if (options.partition) {
  254. if (typeof options.partition === 'string') {
  255. urlLoaderOptions.partition = options.partition;
  256. } else {
  257. throw new TypeError('`partition` should be a string');
  258. }
  259. }
  260. }
  261. return urlLoaderOptions;
  262. }
  263. export class ClientRequest extends Writable implements Electron.ClientRequest {
  264. _started: boolean = false;
  265. _firstWrite: boolean = false;
  266. _aborted: boolean = false;
  267. _chunkedEncoding: boolean | undefined;
  268. _body: Writable | undefined;
  269. _urlLoaderOptions: NodeJS.CreateURLLoaderOptions & { headers: Record<string, { name: string, value: string | string[] }> };
  270. _redirectPolicy: RedirectPolicy;
  271. _followRedirectCb?: () => void;
  272. _uploadProgress?: { active: boolean, started: boolean, current: number, total: number };
  273. _urlLoader?: NodeJS.URLLoader;
  274. _response?: IncomingMessage;
  275. constructor (options: ClientRequestConstructorOptions | string, callback?: (message: IncomingMessage) => void) {
  276. super({ autoDestroy: true });
  277. if (callback) {
  278. this.once('response', callback);
  279. }
  280. const { redirectPolicy, ...urlLoaderOptions } = parseOptions(options);
  281. const urlObj = new URL(urlLoaderOptions.url);
  282. if (!urlLoaderOptions.allowNonHttpProtocols && !kHttpProtocols.has(urlObj.protocol)) {
  283. throw new Error('ClientRequest only supports http: and https: protocols');
  284. }
  285. if (urlLoaderOptions.credentials === 'same-origin' && !urlLoaderOptions.origin) { throw new Error('credentials: same-origin requires origin to be set'); }
  286. this._urlLoaderOptions = urlLoaderOptions;
  287. this._redirectPolicy = redirectPolicy;
  288. }
  289. get chunkedEncoding () {
  290. return this._chunkedEncoding || false;
  291. }
  292. set chunkedEncoding (value: boolean) {
  293. if (this._started) {
  294. throw new Error('chunkedEncoding can only be set before the request is started');
  295. }
  296. if (typeof this._chunkedEncoding !== 'undefined') {
  297. throw new Error('chunkedEncoding can only be set once');
  298. }
  299. this._chunkedEncoding = !!value;
  300. if (this._chunkedEncoding) {
  301. this._body = new ChunkedBodyStream(this);
  302. this._urlLoaderOptions.body = (pipe: NodeJS.DataPipe) => {
  303. (this._body! as ChunkedBodyStream).startReading(pipe);
  304. };
  305. }
  306. }
  307. setHeader (name: string, value: string) {
  308. if (typeof name !== 'string') {
  309. throw new TypeError('`name` should be a string in setHeader(name, value)');
  310. }
  311. if (value == null) {
  312. throw new Error('`value` required in setHeader("' + name + '", value)');
  313. }
  314. if (this._started || this._firstWrite) {
  315. throw new Error('Can\'t set headers after they are sent');
  316. }
  317. if (!isValidHeaderName(name)) {
  318. throw new Error(`Invalid header name: '${name}'`);
  319. }
  320. if (!isValidHeaderValue(value.toString())) {
  321. throw new Error(`Invalid value for header '${name}': '${value}'`);
  322. }
  323. const key = name.toLowerCase();
  324. this._urlLoaderOptions.headers[key] = { name, value };
  325. }
  326. getHeader (name: string) {
  327. if (name == null) {
  328. throw new Error('`name` is required for getHeader(name)');
  329. }
  330. const key = name.toLowerCase();
  331. const header = this._urlLoaderOptions.headers[key];
  332. return header && header.value as any;
  333. }
  334. removeHeader (name: string) {
  335. if (name == null) {
  336. throw new Error('`name` is required for removeHeader(name)');
  337. }
  338. if (this._started || this._firstWrite) {
  339. throw new Error('Can\'t remove headers after they are sent');
  340. }
  341. const key = name.toLowerCase();
  342. delete this._urlLoaderOptions.headers[key];
  343. }
  344. _write (chunk: Buffer, encoding: BufferEncoding, callback: () => void) {
  345. this._firstWrite = true;
  346. if (!this._body) {
  347. this._body = new SlurpStream();
  348. this._body.on('finish', () => {
  349. this._urlLoaderOptions.body = (this._body as SlurpStream).data();
  350. this._startRequest();
  351. });
  352. }
  353. // TODO: is this the right way to forward to another stream?
  354. this._body.write(chunk, encoding, callback);
  355. }
  356. _final (callback: () => void) {
  357. if (this._body) {
  358. // TODO: is this the right way to forward to another stream?
  359. this._body.end(callback);
  360. } else {
  361. // end() called without a body, go ahead and start the request
  362. this._startRequest();
  363. callback();
  364. }
  365. }
  366. _startRequest () {
  367. this._started = true;
  368. const stringifyValues = (obj: Record<string, { name: string, value: string | string[] }>) => {
  369. const ret: Record<string, string> = {};
  370. for (const k of Object.keys(obj)) {
  371. const kv = obj[k];
  372. ret[kv.name] = kv.value.toString();
  373. }
  374. return ret;
  375. };
  376. this._urlLoaderOptions.referrer = this.getHeader('referer') || '';
  377. this._urlLoaderOptions.origin = this._urlLoaderOptions.origin || this.getHeader('origin') || '';
  378. this._urlLoaderOptions.hasUserActivation = this.getHeader('sec-fetch-user') === '?1';
  379. this._urlLoaderOptions.mode = this.getHeader('sec-fetch-mode') || '';
  380. this._urlLoaderOptions.destination = this.getHeader('sec-fetch-dest') || '';
  381. const opts = { ...this._urlLoaderOptions, extraHeaders: stringifyValues(this._urlLoaderOptions.headers) };
  382. this._urlLoader = createURLLoader(opts);
  383. this._urlLoader.on('response-started', (event, finalUrl, responseHead) => {
  384. const response = this._response = new IncomingMessage(responseHead);
  385. this.emit('response', response);
  386. });
  387. this._urlLoader.on('data', (event, data, resume) => {
  388. this._response!._storeInternalData(Buffer.from(data), resume);
  389. });
  390. this._urlLoader.on('complete', () => {
  391. if (this._response) { this._response._storeInternalData(null, null); }
  392. });
  393. this._urlLoader.on('error', (event, netErrorString) => {
  394. const error = new Error(netErrorString);
  395. if (this._response) this._response.destroy(error);
  396. this._die(error);
  397. });
  398. this._urlLoader.on('login', (event, authInfo, callback) => {
  399. const handled = this.emit('login', authInfo, callback);
  400. if (!handled) {
  401. // If there were no listeners, cancel the authentication request.
  402. callback();
  403. }
  404. });
  405. this._urlLoader.on('redirect', (event, redirectInfo, headers) => {
  406. const { statusCode, newMethod, newUrl } = redirectInfo;
  407. if (this._redirectPolicy === 'error') {
  408. this._die(new Error('Attempted to redirect, but redirect policy was \'error\''));
  409. } else if (this._redirectPolicy === 'manual') {
  410. let _followRedirect = false;
  411. this._followRedirectCb = () => { _followRedirect = true; };
  412. try {
  413. this.emit('redirect', statusCode, newMethod, newUrl, headers);
  414. } finally {
  415. this._followRedirectCb = undefined;
  416. if (!_followRedirect && !this._aborted) {
  417. this._die(new Error('Redirect was cancelled'));
  418. }
  419. }
  420. } else if (this._redirectPolicy === 'follow') {
  421. // Calling followRedirect() when the redirect policy is 'follow' is
  422. // allowed but does nothing. (Perhaps it should throw an error
  423. // though...? Since the redirect will happen regardless.)
  424. try {
  425. this._followRedirectCb = () => {};
  426. this.emit('redirect', statusCode, newMethod, newUrl, headers);
  427. } finally {
  428. this._followRedirectCb = undefined;
  429. }
  430. } else {
  431. this._die(new Error(`Unexpected redirect policy '${this._redirectPolicy}'`));
  432. }
  433. });
  434. this._urlLoader.on('upload-progress', (event, position, total) => {
  435. this._uploadProgress = { active: true, started: true, current: position, total };
  436. this.emit('upload-progress', position, total); // Undocumented, for now
  437. });
  438. this._urlLoader.on('download-progress', (event, current) => {
  439. if (this._response) {
  440. this._response.emit('download-progress', current); // Undocumented, for now
  441. }
  442. });
  443. }
  444. followRedirect () {
  445. if (this._followRedirectCb) {
  446. this._followRedirectCb();
  447. } else {
  448. throw new Error('followRedirect() called, but was not waiting for a redirect');
  449. }
  450. }
  451. abort () {
  452. if (!this._aborted) {
  453. process.nextTick(() => { this.emit('abort'); });
  454. }
  455. this._aborted = true;
  456. this._die();
  457. }
  458. _die (err?: Error) {
  459. // Node.js assumes that any stream which is ended is no longer capable of emitted events
  460. // which is a faulty assumption for the case of an object that is acting like a stream
  461. // (our urlRequest). If we don't emit here, this causes errors since we *do* expect
  462. // that error events can be emitted after urlRequest.end().
  463. if ((this as any)._writableState.destroyed && err) {
  464. this.emit('error', err);
  465. }
  466. this.destroy(err);
  467. if (this._urlLoader) {
  468. this._urlLoader.cancel();
  469. if (this._response) this._response.destroy(err);
  470. }
  471. }
  472. getUploadProgress (): UploadProgress {
  473. return this._uploadProgress ? { ...this._uploadProgress } : { active: false, started: false, current: 0, total: 0 };
  474. }
  475. }