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.

425 lines
11 KiB

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