net.ts 18 KB

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