http-parser.js 14 KB

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