Front end of the Slack clone application.

http-parser.js 12KB

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