net.ts 16 KB

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