Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

client-request.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. 'use strict';
  2. const http2 = require('http2');
  3. const {Writable} = require('stream');
  4. const {Agent, globalAgent} = require('./agent');
  5. const IncomingMessage = require('./incoming-message');
  6. const urlToOptions = require('./utils/url-to-options');
  7. const proxyEvents = require('./utils/proxy-events');
  8. const isRequestPseudoHeader = require('./utils/is-request-pseudo-header');
  9. const {
  10. ERR_INVALID_ARG_TYPE,
  11. ERR_INVALID_PROTOCOL,
  12. ERR_HTTP_HEADERS_SENT,
  13. ERR_INVALID_HTTP_TOKEN,
  14. ERR_HTTP_INVALID_HEADER_VALUE,
  15. ERR_INVALID_CHAR
  16. } = require('./utils/errors');
  17. const {
  18. HTTP2_HEADER_STATUS,
  19. HTTP2_HEADER_METHOD,
  20. HTTP2_HEADER_PATH,
  21. HTTP2_METHOD_CONNECT
  22. } = http2.constants;
  23. const kHeaders = Symbol('headers');
  24. const kOrigin = Symbol('origin');
  25. const kSession = Symbol('session');
  26. const kOptions = Symbol('options');
  27. const kFlushedHeaders = Symbol('flushedHeaders');
  28. const kJobs = Symbol('jobs');
  29. const isValidHttpToken = /^[\^`\-\w!#$%&*+.|~]+$/;
  30. const isInvalidHeaderValue = /[^\t\u0020-\u007E\u0080-\u00FF]/;
  31. class ClientRequest extends Writable {
  32. constructor(input, options, callback) {
  33. super({
  34. autoDestroy: false
  35. });
  36. const hasInput = typeof input === 'string' || input instanceof URL;
  37. if (hasInput) {
  38. input = urlToOptions(input instanceof URL ? input : new URL(input));
  39. }
  40. if (typeof options === 'function' || options === undefined) {
  41. // (options, callback)
  42. callback = options;
  43. options = hasInput ? input : {...input};
  44. } else {
  45. // (input, options, callback)
  46. options = {...input, ...options};
  47. }
  48. if (options.h2session) {
  49. this[kSession] = options.h2session;
  50. } else if (options.agent === false) {
  51. this.agent = new Agent({maxFreeSessions: 0});
  52. } else if (typeof options.agent === 'undefined' || options.agent === null) {
  53. if (typeof options.createConnection === 'function') {
  54. // This is a workaround - we don't have to create the session on our own.
  55. this.agent = new Agent({maxFreeSessions: 0});
  56. this.agent.createConnection = options.createConnection;
  57. } else {
  58. this.agent = globalAgent;
  59. }
  60. } else if (typeof options.agent.request === 'function') {
  61. this.agent = options.agent;
  62. } else {
  63. throw new ERR_INVALID_ARG_TYPE('options.agent', ['Agent-like Object', 'undefined', 'false'], options.agent);
  64. }
  65. if (options.protocol && options.protocol !== 'https:') {
  66. throw new ERR_INVALID_PROTOCOL(options.protocol, 'https:');
  67. }
  68. const port = options.port || options.defaultPort || (this.agent && this.agent.defaultPort) || 443;
  69. const host = options.hostname || options.host || 'localhost';
  70. // Don't enforce the origin via options. It may be changed in an Agent.
  71. delete options.hostname;
  72. delete options.host;
  73. delete options.port;
  74. const {timeout} = options;
  75. options.timeout = undefined;
  76. this[kHeaders] = Object.create(null);
  77. this[kJobs] = [];
  78. this.socket = null;
  79. this.connection = null;
  80. this.method = options.method || 'GET';
  81. this.path = options.path;
  82. this.res = null;
  83. this.aborted = false;
  84. this.reusedSocket = false;
  85. if (options.headers) {
  86. for (const [header, value] of Object.entries(options.headers)) {
  87. this.setHeader(header, value);
  88. }
  89. }
  90. if (options.auth && !('authorization' in this[kHeaders])) {
  91. this[kHeaders].authorization = 'Basic ' + Buffer.from(options.auth).toString('base64');
  92. }
  93. options.session = options.tlsSession;
  94. options.path = options.socketPath;
  95. this[kOptions] = options;
  96. // Clients that generate HTTP/2 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field.
  97. if (port === 443) {
  98. this[kOrigin] = `https://${host}`;
  99. if (!(':authority' in this[kHeaders])) {
  100. this[kHeaders][':authority'] = host;
  101. }
  102. } else {
  103. this[kOrigin] = `https://${host}:${port}`;
  104. if (!(':authority' in this[kHeaders])) {
  105. this[kHeaders][':authority'] = `${host}:${port}`;
  106. }
  107. }
  108. if (timeout) {
  109. this.setTimeout(timeout);
  110. }
  111. if (callback) {
  112. this.once('response', callback);
  113. }
  114. this[kFlushedHeaders] = false;
  115. }
  116. get method() {
  117. return this[kHeaders][HTTP2_HEADER_METHOD];
  118. }
  119. set method(value) {
  120. if (value) {
  121. this[kHeaders][HTTP2_HEADER_METHOD] = value.toUpperCase();
  122. }
  123. }
  124. get path() {
  125. return this[kHeaders][HTTP2_HEADER_PATH];
  126. }
  127. set path(value) {
  128. if (value) {
  129. this[kHeaders][HTTP2_HEADER_PATH] = value;
  130. }
  131. }
  132. get _mustNotHaveABody() {
  133. return this.method === 'GET' || this.method === 'HEAD' || this.method === 'DELETE';
  134. }
  135. _write(chunk, encoding, callback) {
  136. // https://github.com/nodejs/node/blob/654df09ae0c5e17d1b52a900a545f0664d8c7627/lib/internal/http2/util.js#L148-L156
  137. if (this._mustNotHaveABody) {
  138. callback(new Error('The GET, HEAD and DELETE methods must NOT have a body'));
  139. /* istanbul ignore next: Node.js 12 throws directly */
  140. return;
  141. }
  142. this.flushHeaders();
  143. const callWrite = () => this._request.write(chunk, encoding, callback);
  144. if (this._request) {
  145. callWrite();
  146. } else {
  147. this[kJobs].push(callWrite);
  148. }
  149. }
  150. _final(callback) {
  151. if (this.destroyed) {
  152. return;
  153. }
  154. this.flushHeaders();
  155. const callEnd = () => {
  156. // For GET, HEAD and DELETE
  157. if (this._mustNotHaveABody) {
  158. callback();
  159. return;
  160. }
  161. this._request.end(callback);
  162. };
  163. if (this._request) {
  164. callEnd();
  165. } else {
  166. this[kJobs].push(callEnd);
  167. }
  168. }
  169. abort() {
  170. if (this.res && this.res.complete) {
  171. return;
  172. }
  173. if (!this.aborted) {
  174. process.nextTick(() => this.emit('abort'));
  175. }
  176. this.aborted = true;
  177. this.destroy();
  178. }
  179. _destroy(error, callback) {
  180. if (this.res) {
  181. this.res._dump();
  182. }
  183. if (this._request) {
  184. this._request.destroy();
  185. }
  186. callback(error);
  187. }
  188. async flushHeaders() {
  189. if (this[kFlushedHeaders] || this.destroyed) {
  190. return;
  191. }
  192. this[kFlushedHeaders] = true;
  193. const isConnectMethod = this.method === HTTP2_METHOD_CONNECT;
  194. // The real magic is here
  195. const onStream = stream => {
  196. this._request = stream;
  197. if (this.destroyed) {
  198. stream.destroy();
  199. return;
  200. }
  201. // Forwards `timeout`, `continue`, `close` and `error` events to this instance.
  202. if (!isConnectMethod) {
  203. proxyEvents(stream, this, ['timeout', 'continue', 'close', 'error']);
  204. }
  205. // Wait for the `finish` event. We don't want to emit the `response` event
  206. // before `request.end()` is called.
  207. const waitForEnd = fn => {
  208. return (...args) => {
  209. if (!this.writable && !this.destroyed) {
  210. fn(...args);
  211. } else {
  212. this.once('finish', () => {
  213. fn(...args);
  214. });
  215. }
  216. };
  217. };
  218. // This event tells we are ready to listen for the data.
  219. stream.once('response', waitForEnd((headers, flags, rawHeaders) => {
  220. // If we were to emit raw request stream, it would be as fast as the native approach.
  221. // Note that wrapping the raw stream in a Proxy instance won't improve the performance (already tested it).
  222. const response = new IncomingMessage(this.socket, stream.readableHighWaterMark);
  223. this.res = response;
  224. response.req = this;
  225. response.statusCode = headers[HTTP2_HEADER_STATUS];
  226. response.headers = headers;
  227. response.rawHeaders = rawHeaders;
  228. response.once('end', () => {
  229. if (this.aborted) {
  230. response.aborted = true;
  231. response.emit('aborted');
  232. } else {
  233. response.complete = true;
  234. // Has no effect, just be consistent with the Node.js behavior
  235. response.socket = null;
  236. response.connection = null;
  237. }
  238. });
  239. if (isConnectMethod) {
  240. response.upgrade = true;
  241. // The HTTP1 API says the socket is detached here,
  242. // but we can't do that so we pass the original HTTP2 request.
  243. if (this.emit('connect', response, stream, Buffer.alloc(0))) {
  244. this.emit('close');
  245. } else {
  246. // No listeners attached, destroy the original request.
  247. stream.destroy();
  248. }
  249. } else {
  250. // Forwards data
  251. stream.on('data', chunk => {
  252. if (!response._dumped && !response.push(chunk)) {
  253. stream.pause();
  254. }
  255. });
  256. stream.once('end', () => {
  257. response.push(null);
  258. });
  259. if (!this.emit('response', response)) {
  260. // No listeners attached, dump the response.
  261. response._dump();
  262. }
  263. }
  264. }));
  265. // Emits `information` event
  266. stream.once('headers', waitForEnd(
  267. headers => this.emit('information', {statusCode: headers[HTTP2_HEADER_STATUS]})
  268. ));
  269. stream.once('trailers', waitForEnd((trailers, flags, rawTrailers) => {
  270. const {res} = this;
  271. // Assigns trailers to the response object.
  272. res.trailers = trailers;
  273. res.rawTrailers = rawTrailers;
  274. }));
  275. const {socket} = stream.session;
  276. this.socket = socket;
  277. this.connection = socket;
  278. for (const job of this[kJobs]) {
  279. job();
  280. }
  281. this.emit('socket', this.socket);
  282. };
  283. // Makes a HTTP2 request
  284. if (this[kSession]) {
  285. try {
  286. onStream(this[kSession].request(this[kHeaders]));
  287. } catch (error) {
  288. this.emit('error', error);
  289. }
  290. } else {
  291. this.reusedSocket = true;
  292. try {
  293. onStream(await this.agent.request(this[kOrigin], this[kOptions], this[kHeaders]));
  294. } catch (error) {
  295. this.emit('error', error);
  296. }
  297. }
  298. }
  299. getHeader(name) {
  300. if (typeof name !== 'string') {
  301. throw new ERR_INVALID_ARG_TYPE('name', 'string', name);
  302. }
  303. return this[kHeaders][name.toLowerCase()];
  304. }
  305. get headersSent() {
  306. return this[kFlushedHeaders];
  307. }
  308. removeHeader(name) {
  309. if (typeof name !== 'string') {
  310. throw new ERR_INVALID_ARG_TYPE('name', 'string', name);
  311. }
  312. if (this.headersSent) {
  313. throw new ERR_HTTP_HEADERS_SENT('remove');
  314. }
  315. delete this[kHeaders][name.toLowerCase()];
  316. }
  317. setHeader(name, value) {
  318. if (this.headersSent) {
  319. throw new ERR_HTTP_HEADERS_SENT('set');
  320. }
  321. if (typeof name !== 'string' || (!isValidHttpToken.test(name) && !isRequestPseudoHeader(name))) {
  322. throw new ERR_INVALID_HTTP_TOKEN('Header name', name);
  323. }
  324. if (typeof value === 'undefined') {
  325. throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name);
  326. }
  327. if (isInvalidHeaderValue.test(value)) {
  328. throw new ERR_INVALID_CHAR('header content', name);
  329. }
  330. this[kHeaders][name.toLowerCase()] = value;
  331. }
  332. setNoDelay() {
  333. // HTTP2 sockets cannot be malformed, do nothing.
  334. }
  335. setSocketKeepAlive() {
  336. // HTTP2 sockets cannot be malformed, do nothing.
  337. }
  338. setTimeout(ms, callback) {
  339. const applyTimeout = () => this._request.setTimeout(ms, callback);
  340. if (this._request) {
  341. applyTimeout();
  342. } else {
  343. this[kJobs].push(applyTimeout);
  344. }
  345. return this;
  346. }
  347. get maxHeadersCount() {
  348. if (!this.destroyed && this._request) {
  349. return this._request.session.localSettings.maxHeaderListSize;
  350. }
  351. return undefined;
  352. }
  353. set maxHeadersCount(_value) {
  354. // Updating HTTP2 settings would affect all requests, do nothing.
  355. }
  356. }
  357. module.exports = ClientRequest;