Dieses Repository beinhaltet HTML- und Javascript Code zur einer NotizenWebApp auf Basis von Web Storage. Zudem sind Mocha/Chai Tests im Browser enthalten. https://meinenotizen.netlify.app/
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.

http-parser.js 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /*jshint node:true */
  2. var assert = require('assert');
  3. exports.HTTPParser = HTTPParser;
  4. function HTTPParser(type) {
  5. assert.ok(type === HTTPParser.REQUEST || type === HTTPParser.RESPONSE || type === undefined);
  6. if (type === undefined) {
  7. // Node v12+
  8. } else {
  9. this.initialize(type);
  10. }
  11. }
  12. HTTPParser.prototype.initialize = function (type, async_resource) {
  13. assert.ok(type === HTTPParser.REQUEST || type === HTTPParser.RESPONSE);
  14. this.type = type;
  15. this.state = type + '_LINE';
  16. this.info = {
  17. headers: [],
  18. upgrade: false
  19. };
  20. this.trailers = [];
  21. this.line = '';
  22. this.isChunked = false;
  23. this.connection = '';
  24. this.headerSize = 0; // for preventing too big headers
  25. this.body_bytes = null;
  26. this.isUserCall = false;
  27. this.hadError = false;
  28. };
  29. HTTPParser.encoding = 'ascii';
  30. HTTPParser.maxHeaderSize = 80 * 1024; // maxHeaderSize (in bytes) is configurable, but 80kb by default;
  31. HTTPParser.REQUEST = 'REQUEST';
  32. HTTPParser.RESPONSE = 'RESPONSE';
  33. var kOnHeaders = HTTPParser.kOnHeaders = 0;
  34. var kOnHeadersComplete = HTTPParser.kOnHeadersComplete = 1;
  35. var kOnBody = HTTPParser.kOnBody = 2;
  36. var kOnMessageComplete = HTTPParser.kOnMessageComplete = 3;
  37. // Some handler stubs, needed for compatibility
  38. HTTPParser.prototype[kOnHeaders] =
  39. HTTPParser.prototype[kOnHeadersComplete] =
  40. HTTPParser.prototype[kOnBody] =
  41. HTTPParser.prototype[kOnMessageComplete] = function () {};
  42. var compatMode0_12 = true;
  43. Object.defineProperty(HTTPParser, 'kOnExecute', {
  44. get: function () {
  45. // hack for backward compatibility
  46. compatMode0_12 = false;
  47. return 4;
  48. }
  49. });
  50. var methods = exports.methods = HTTPParser.methods = [
  51. 'DELETE',
  52. 'GET',
  53. 'HEAD',
  54. 'POST',
  55. 'PUT',
  56. 'CONNECT',
  57. 'OPTIONS',
  58. 'TRACE',
  59. 'COPY',
  60. 'LOCK',
  61. 'MKCOL',
  62. 'MOVE',
  63. 'PROPFIND',
  64. 'PROPPATCH',
  65. 'SEARCH',
  66. 'UNLOCK',
  67. 'BIND',
  68. 'REBIND',
  69. 'UNBIND',
  70. 'ACL',
  71. 'REPORT',
  72. 'MKACTIVITY',
  73. 'CHECKOUT',
  74. 'MERGE',
  75. 'M-SEARCH',
  76. 'NOTIFY',
  77. 'SUBSCRIBE',
  78. 'UNSUBSCRIBE',
  79. 'PATCH',
  80. 'PURGE',
  81. 'MKCALENDAR',
  82. 'LINK',
  83. 'UNLINK'
  84. ];
  85. var method_connect = methods.indexOf('CONNECT');
  86. HTTPParser.prototype.reinitialize = HTTPParser;
  87. HTTPParser.prototype.close =
  88. HTTPParser.prototype.pause =
  89. HTTPParser.prototype.resume =
  90. HTTPParser.prototype.free = function () {};
  91. HTTPParser.prototype._compatMode0_11 = false;
  92. HTTPParser.prototype.getAsyncId = function() { return 0; };
  93. var headerState = {
  94. REQUEST_LINE: true,
  95. RESPONSE_LINE: true,
  96. HEADER: true
  97. };
  98. HTTPParser.prototype.execute = function (chunk, start, length) {
  99. if (!(this instanceof HTTPParser)) {
  100. throw new TypeError('not a HTTPParser');
  101. }
  102. // backward compat to node < 0.11.4
  103. // Note: the start and length params were removed in newer version
  104. start = start || 0;
  105. length = typeof length === 'number' ? length : chunk.length;
  106. this.chunk = chunk;
  107. this.offset = start;
  108. var end = this.end = start + length;
  109. try {
  110. while (this.offset < end) {
  111. if (this[this.state]()) {
  112. break;
  113. }
  114. }
  115. } catch (err) {
  116. if (this.isUserCall) {
  117. throw err;
  118. }
  119. this.hadError = true;
  120. return err;
  121. }
  122. this.chunk = null;
  123. length = this.offset - start;
  124. if (headerState[this.state]) {
  125. this.headerSize += length;
  126. if (this.headerSize > HTTPParser.maxHeaderSize) {
  127. return new Error('max header size exceeded');
  128. }
  129. }
  130. return length;
  131. };
  132. var stateFinishAllowed = {
  133. REQUEST_LINE: true,
  134. RESPONSE_LINE: true,
  135. BODY_RAW: true
  136. };
  137. HTTPParser.prototype.finish = function () {
  138. if (this.hadError) {
  139. return;
  140. }
  141. if (!stateFinishAllowed[this.state]) {
  142. return new Error('invalid state for EOF');
  143. }
  144. if (this.state === 'BODY_RAW') {
  145. this.userCall()(this[kOnMessageComplete]());
  146. }
  147. };
  148. // These three methods are used for an internal speed optimization, and it also
  149. // works if theses are noops. Basically consume() asks us to read the bytes
  150. // ourselves, but if we don't do it we get them through execute().
  151. HTTPParser.prototype.consume =
  152. HTTPParser.prototype.unconsume =
  153. HTTPParser.prototype.getCurrentBuffer = function () {};
  154. //For correct error handling - see HTTPParser#execute
  155. //Usage: this.userCall()(userFunction('arg'));
  156. HTTPParser.prototype.userCall = function () {
  157. this.isUserCall = true;
  158. var self = this;
  159. return function (ret) {
  160. self.isUserCall = false;
  161. return ret;
  162. };
  163. };
  164. HTTPParser.prototype.nextRequest = function () {
  165. this.userCall()(this[kOnMessageComplete]());
  166. this.reinitialize(this.type);
  167. };
  168. HTTPParser.prototype.consumeLine = function () {
  169. var end = this.end,
  170. chunk = this.chunk;
  171. for (var i = this.offset; i < end; i++) {
  172. if (chunk[i] === 0x0a) { // \n
  173. var line = this.line + chunk.toString(HTTPParser.encoding, this.offset, i);
  174. if (line.charAt(line.length - 1) === '\r') {
  175. line = line.substr(0, line.length - 1);
  176. }
  177. this.line = '';
  178. this.offset = i + 1;
  179. return line;
  180. }
  181. }
  182. //line split over multiple chunks
  183. this.line += chunk.toString(HTTPParser.encoding, this.offset, this.end);
  184. this.offset = this.end;
  185. };
  186. var headerExp = /^([^: \t]+):[ \t]*((?:.*[^ \t])|)/;
  187. var headerContinueExp = /^[ \t]+(.*[^ \t])/;
  188. HTTPParser.prototype.parseHeader = function (line, headers) {
  189. if (line.indexOf('\r') !== -1) {
  190. throw parseErrorCode('HPE_LF_EXPECTED');
  191. }
  192. var match = headerExp.exec(line);
  193. var k = match && match[1];
  194. if (k) { // skip empty string (malformed header)
  195. headers.push(k);
  196. headers.push(match[2]);
  197. } else {
  198. var matchContinue = headerContinueExp.exec(line);
  199. if (matchContinue && headers.length) {
  200. if (headers[headers.length - 1]) {
  201. headers[headers.length - 1] += ' ';
  202. }
  203. headers[headers.length - 1] += matchContinue[1];
  204. }
  205. }
  206. };
  207. var requestExp = /^([A-Z-]+) ([^ ]+) HTTP\/(\d)\.(\d)$/;
  208. HTTPParser.prototype.REQUEST_LINE = function () {
  209. var line = this.consumeLine();
  210. if (!line) {
  211. return;
  212. }
  213. var match = requestExp.exec(line);
  214. if (match === null) {
  215. throw parseErrorCode('HPE_INVALID_CONSTANT');
  216. }
  217. this.info.method = this._compatMode0_11 ? match[1] : methods.indexOf(match[1]);
  218. if (this.info.method === -1) {
  219. throw new Error('invalid request method');
  220. }
  221. this.info.url = match[2];
  222. this.info.versionMajor = +match[3];
  223. this.info.versionMinor = +match[4];
  224. this.body_bytes = 0;
  225. this.state = 'HEADER';
  226. };
  227. var responseExp = /^HTTP\/(\d)\.(\d) (\d{3}) ?(.*)$/;
  228. HTTPParser.prototype.RESPONSE_LINE = function () {
  229. var line = this.consumeLine();
  230. if (!line) {
  231. return;
  232. }
  233. var match = responseExp.exec(line);
  234. if (match === null) {
  235. throw parseErrorCode('HPE_INVALID_CONSTANT');
  236. }
  237. this.info.versionMajor = +match[1];
  238. this.info.versionMinor = +match[2];
  239. var statusCode = this.info.statusCode = +match[3];
  240. this.info.statusMessage = match[4];
  241. // Implied zero length.
  242. if ((statusCode / 100 | 0) === 1 || statusCode === 204 || statusCode === 304) {
  243. this.body_bytes = 0;
  244. }
  245. this.state = 'HEADER';
  246. };
  247. HTTPParser.prototype.shouldKeepAlive = function () {
  248. if (this.info.versionMajor > 0 && this.info.versionMinor > 0) {
  249. if (this.connection.indexOf('close') !== -1) {
  250. return false;
  251. }
  252. } else if (this.connection.indexOf('keep-alive') === -1) {
  253. return false;
  254. }
  255. if (this.body_bytes !== null || this.isChunked) { // || skipBody
  256. return true;
  257. }
  258. return false;
  259. };
  260. HTTPParser.prototype.HEADER = function () {
  261. var line = this.consumeLine();
  262. if (line === undefined) {
  263. return;
  264. }
  265. var info = this.info;
  266. if (line) {
  267. this.parseHeader(line, info.headers);
  268. } else {
  269. var headers = info.headers;
  270. var hasContentLength = false;
  271. var currentContentLengthValue;
  272. var hasUpgradeHeader = false;
  273. for (var i = 0; i < headers.length; i += 2) {
  274. switch (headers[i].toLowerCase()) {
  275. case 'transfer-encoding':
  276. this.isChunked = headers[i + 1].toLowerCase() === 'chunked';
  277. break;
  278. case 'content-length':
  279. currentContentLengthValue = +headers[i + 1];
  280. if (hasContentLength) {
  281. // Fix duplicate Content-Length header with same values.
  282. // Throw error only if values are different.
  283. // Known issues:
  284. // https://github.com/request/request/issues/2091#issuecomment-328715113
  285. // https://github.com/nodejs/node/issues/6517#issuecomment-216263771
  286. if (currentContentLengthValue !== this.body_bytes) {
  287. throw parseErrorCode('HPE_UNEXPECTED_CONTENT_LENGTH');
  288. }
  289. } else {
  290. hasContentLength = true;
  291. this.body_bytes = currentContentLengthValue;
  292. }
  293. break;
  294. case 'connection':
  295. this.connection += headers[i + 1].toLowerCase();
  296. break;
  297. case 'upgrade':
  298. hasUpgradeHeader = true;
  299. break;
  300. }
  301. }
  302. // if both isChunked and hasContentLength, isChunked wins
  303. // This is required so the body is parsed using the chunked method, and matches
  304. // Chrome's behavior. We could, maybe, ignore them both (would get chunked
  305. // encoding into the body), and/or disable shouldKeepAlive to be more
  306. // resilient.
  307. if (this.isChunked && hasContentLength) {
  308. hasContentLength = false;
  309. this.body_bytes = null;
  310. }
  311. // Logic from https://github.com/nodejs/http-parser/blob/921d5585515a153fa00e411cf144280c59b41f90/http_parser.c#L1727-L1737
  312. // "For responses, "Upgrade: foo" and "Connection: upgrade" are
  313. // mandatory only when it is a 101 Switching Protocols response,
  314. // otherwise it is purely informational, to announce support.
  315. if (hasUpgradeHeader && this.connection.indexOf('upgrade') != -1) {
  316. info.upgrade = this.type === HTTPParser.REQUEST || info.statusCode === 101;
  317. } else {
  318. info.upgrade = info.method === method_connect;
  319. }
  320. if (this.isChunked && info.upgrade) {
  321. this.isChunked = false;
  322. }
  323. info.shouldKeepAlive = this.shouldKeepAlive();
  324. //problem which also exists in original node: we should know skipBody before calling onHeadersComplete
  325. var skipBody;
  326. if (compatMode0_12) {
  327. skipBody = this.userCall()(this[kOnHeadersComplete](info));
  328. } else {
  329. skipBody = this.userCall()(this[kOnHeadersComplete](info.versionMajor,
  330. info.versionMinor, info.headers, info.method, info.url, info.statusCode,
  331. info.statusMessage, info.upgrade, info.shouldKeepAlive));
  332. }
  333. if (skipBody === 2) {
  334. this.nextRequest();
  335. return true;
  336. } else if (this.isChunked && !skipBody) {
  337. this.state = 'BODY_CHUNKHEAD';
  338. } else if (skipBody || this.body_bytes === 0) {
  339. this.nextRequest();
  340. // For older versions of node (v6.x and older?), that return skipBody=1 or skipBody=true,
  341. // need this "return true;" if it's an upgrade request.
  342. return info.upgrade;
  343. } else if (this.body_bytes === null) {
  344. this.state = 'BODY_RAW';
  345. } else {
  346. this.state = 'BODY_SIZED';
  347. }
  348. }
  349. };
  350. HTTPParser.prototype.BODY_CHUNKHEAD = function () {
  351. var line = this.consumeLine();
  352. if (line === undefined) {
  353. return;
  354. }
  355. this.body_bytes = parseInt(line, 16);
  356. if (!this.body_bytes) {
  357. this.state = 'BODY_CHUNKTRAILERS';
  358. } else {
  359. this.state = 'BODY_CHUNK';
  360. }
  361. };
  362. HTTPParser.prototype.BODY_CHUNK = function () {
  363. var length = Math.min(this.end - this.offset, this.body_bytes);
  364. this.userCall()(this[kOnBody](this.chunk, this.offset, length));
  365. this.offset += length;
  366. this.body_bytes -= length;
  367. if (!this.body_bytes) {
  368. this.state = 'BODY_CHUNKEMPTYLINE';
  369. }
  370. };
  371. HTTPParser.prototype.BODY_CHUNKEMPTYLINE = function () {
  372. var line = this.consumeLine();
  373. if (line === undefined) {
  374. return;
  375. }
  376. assert.equal(line, '');
  377. this.state = 'BODY_CHUNKHEAD';
  378. };
  379. HTTPParser.prototype.BODY_CHUNKTRAILERS = function () {
  380. var line = this.consumeLine();
  381. if (line === undefined) {
  382. return;
  383. }
  384. if (line) {
  385. this.parseHeader(line, this.trailers);
  386. } else {
  387. if (this.trailers.length) {
  388. this.userCall()(this[kOnHeaders](this.trailers, ''));
  389. }
  390. this.nextRequest();
  391. }
  392. };
  393. HTTPParser.prototype.BODY_RAW = function () {
  394. var length = this.end - this.offset;
  395. this.userCall()(this[kOnBody](this.chunk, this.offset, length));
  396. this.offset = this.end;
  397. };
  398. HTTPParser.prototype.BODY_SIZED = function () {
  399. var length = Math.min(this.end - this.offset, this.body_bytes);
  400. this.userCall()(this[kOnBody](this.chunk, this.offset, length));
  401. this.offset += length;
  402. this.body_bytes -= length;
  403. if (!this.body_bytes) {
  404. this.nextRequest();
  405. }
  406. };
  407. // backward compat to node < 0.11.6
  408. ['Headers', 'HeadersComplete', 'Body', 'MessageComplete'].forEach(function (name) {
  409. var k = HTTPParser['kOn' + name];
  410. Object.defineProperty(HTTPParser.prototype, 'on' + name, {
  411. get: function () {
  412. return this[k];
  413. },
  414. set: function (to) {
  415. // hack for backward compatibility
  416. this._compatMode0_11 = true;
  417. method_connect = 'CONNECT';
  418. return (this[k] = to);
  419. }
  420. });
  421. });
  422. function parseErrorCode(code) {
  423. var err = new Error('Parse Error');
  424. err.code = code;
  425. return err;
  426. }