net.ts 18 KB

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