net.js 14 KB

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