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.

684 lines
19 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright (c) 2014, Peter Thorson. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are met:
  6. * * Redistributions of source code must retain the above copyright
  7. * notice, this list of conditions and the following disclaimer.
  8. * * Redistributions in binary form must reproduce the above copyright
  9. * notice, this list of conditions and the following disclaimer in the
  10. * documentation and/or other materials provided with the distribution.
  11. * * Neither the name of the WebSocket++ Project nor the
  12. * names of its contributors may be used to endorse or promote products
  13. * derived from this software without specific prior written permission.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. * ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY
  19. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  20. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  21. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  22. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  24. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. *
  26. */
  27. #ifndef HTTP_PARSER_HPP
  28. #define HTTP_PARSER_HPP
  29. #include <algorithm>
  30. #include <map>
  31. #include <string>
  32. #include <utility>
  33. #include <websocketpp/http/constants.hpp>
  34. #include <websocketpp/utilities.hpp>
  35. namespace websocketpp
  36. {
  37. namespace http
  38. {
  39. namespace parser
  40. {
  41. namespace state
  42. {
  43. enum value
  44. {
  45. method,
  46. resource,
  47. version,
  48. headers
  49. };
  50. }
  51. namespace body_encoding
  52. {
  53. enum value
  54. {
  55. unknown,
  56. plain,
  57. chunked
  58. };
  59. }
  60. typedef std::map<std::string, std::string, utility::ci_less> header_list;
  61. /// Read and return the next token in the stream
  62. /**
  63. * Read until a non-token character is found and then return the token and
  64. * iterator to the next character to read
  65. *
  66. * @param begin An iterator to the beginning of the sequence
  67. * @param end An iterator to the end of the sequence
  68. * @return A pair containing the token and an iterator to the next character in
  69. * the stream
  70. */
  71. template <typename InputIterator> std::pair<std::string, InputIterator> extract_token(InputIterator begin, InputIterator end)
  72. {
  73. InputIterator it = std::find_if(begin, end, &is_not_token_char);
  74. return std::make_pair(std::string(begin, it), it);
  75. }
  76. /// Read and return the next quoted string in the stream
  77. /**
  78. * Read a double quoted string starting at `begin`. The quotes themselves are
  79. * stripped. The quoted value is returned along with an iterator to the next
  80. * character to read
  81. *
  82. * @param begin An iterator to the beginning of the sequence
  83. * @param end An iterator to the end of the sequence
  84. * @return A pair containing the string read and an iterator to the next
  85. * character in the stream
  86. */
  87. template <typename InputIterator> std::pair<std::string, InputIterator> extract_quoted_string(InputIterator begin, InputIterator end)
  88. {
  89. std::string s;
  90. if (end == begin)
  91. {
  92. return std::make_pair(s, begin);
  93. }
  94. if (*begin != '"')
  95. {
  96. return std::make_pair(s, begin);
  97. }
  98. InputIterator cursor = begin + 1;
  99. InputIterator marker = cursor;
  100. cursor = std::find(cursor, end, '"');
  101. while (cursor != end)
  102. {
  103. // either this is the end or a quoted string
  104. if (*(cursor - 1) == '\\')
  105. {
  106. s.append(marker, cursor - 1);
  107. s.append(1, '"');
  108. ++cursor;
  109. marker = cursor;
  110. }
  111. else
  112. {
  113. s.append(marker, cursor);
  114. ++cursor;
  115. return std::make_pair(s, cursor);
  116. }
  117. cursor = std::find(cursor, end, '"');
  118. }
  119. return std::make_pair("", begin);
  120. }
  121. /// Read and discard one unit of linear whitespace
  122. /**
  123. * Read one unit of linear white space and return the iterator to the character
  124. * afterwards. If `begin` is returned, no whitespace was extracted.
  125. *
  126. * @param begin An iterator to the beginning of the sequence
  127. * @param end An iterator to the end of the sequence
  128. * @return An iterator to the character after the linear whitespace read
  129. */
  130. template <typename InputIterator> InputIterator extract_lws(InputIterator begin, InputIterator end)
  131. {
  132. InputIterator it = begin;
  133. // strip leading CRLF
  134. if (end - begin > 2 && *begin == '\r' && *(begin + 1) == '\n' && is_whitespace_char(static_cast<unsigned char>(*(begin + 2))))
  135. {
  136. it += 3;
  137. }
  138. it = std::find_if(it, end, &is_not_whitespace_char);
  139. return it;
  140. }
  141. /// Read and discard linear whitespace
  142. /**
  143. * Read linear white space until a non-lws character is read and return an
  144. * iterator to that character. If `begin` is returned, no whitespace was
  145. * extracted.
  146. *
  147. * @param begin An iterator to the beginning of the sequence
  148. * @param end An iterator to the end of the sequence
  149. * @return An iterator to the character after the linear whitespace read
  150. */
  151. template <typename InputIterator> InputIterator extract_all_lws(InputIterator begin, InputIterator end)
  152. {
  153. InputIterator old_it;
  154. InputIterator new_it = begin;
  155. do
  156. {
  157. // Pull value from previous iteration
  158. old_it = new_it;
  159. // look ahead another pass
  160. new_it = extract_lws(old_it, end);
  161. }
  162. while (new_it != end && old_it != new_it);
  163. return new_it;
  164. }
  165. /// Extract HTTP attributes
  166. /**
  167. * An http attributes list is a semicolon delimited list of key value pairs in
  168. * the format: *( ";" attribute "=" value ) where attribute is a token and value
  169. * is a token or quoted string.
  170. *
  171. * Attributes extracted are appended to the supplied attributes list
  172. * `attributes`.
  173. *
  174. * @param [in] begin An iterator to the beginning of the sequence
  175. * @param [in] end An iterator to the end of the sequence
  176. * @param [out] attributes A reference to the attributes list to append
  177. * attribute/value pairs extracted to
  178. * @return An iterator to the character after the last atribute read
  179. */
  180. template <typename InputIterator> InputIterator extract_attributes(InputIterator begin, InputIterator end, attribute_list & attributes)
  181. {
  182. InputIterator cursor;
  183. bool first = true;
  184. if (begin == end)
  185. {
  186. return begin;
  187. }
  188. cursor = begin;
  189. std::pair<std::string, InputIterator> ret;
  190. while (cursor != end)
  191. {
  192. std::string name;
  193. cursor = http::parser::extract_all_lws(cursor, end);
  194. if (cursor == end)
  195. {
  196. break;
  197. }
  198. if (first)
  199. {
  200. // ignore this check for the very first pass
  201. first = false;
  202. }
  203. else
  204. {
  205. if (*cursor == ';')
  206. {
  207. // advance past the ';'
  208. ++cursor;
  209. }
  210. else
  211. {
  212. // non-semicolon in this position indicates end end of the
  213. // attribute list, break and return.
  214. break;
  215. }
  216. }
  217. cursor = http::parser::extract_all_lws(cursor, end);
  218. ret = http::parser::extract_token(cursor, end);
  219. if (ret.first.empty())
  220. {
  221. // error: expected a token
  222. return begin;
  223. }
  224. else
  225. {
  226. name = ret.first;
  227. cursor = ret.second;
  228. }
  229. cursor = http::parser::extract_all_lws(cursor, end);
  230. if (cursor == end || *cursor != '=')
  231. {
  232. // if there is an equals sign, read the attribute value. Otherwise
  233. // record a blank value and continue
  234. attributes[name].clear();
  235. continue;
  236. }
  237. // advance past the '='
  238. ++cursor;
  239. cursor = http::parser::extract_all_lws(cursor, end);
  240. if (cursor == end)
  241. {
  242. // error: expected a token or quoted string
  243. return begin;
  244. }
  245. ret = http::parser::extract_quoted_string(cursor, end);
  246. if (ret.second != cursor)
  247. {
  248. attributes[name] = ret.first;
  249. cursor = ret.second;
  250. continue;
  251. }
  252. ret = http::parser::extract_token(cursor, end);
  253. if (ret.first.empty())
  254. {
  255. // error : expected token or quoted string
  256. return begin;
  257. }
  258. else
  259. {
  260. attributes[name] = ret.first;
  261. cursor = ret.second;
  262. }
  263. }
  264. return cursor;
  265. }
  266. /// Extract HTTP parameters
  267. /**
  268. * An http parameters list is a comma delimited list of tokens followed by
  269. * optional semicolon delimited attributes lists.
  270. *
  271. * Parameters extracted are appended to the supplied parameters list
  272. * `parameters`.
  273. *
  274. * @param [in] begin An iterator to the beginning of the sequence
  275. * @param [in] end An iterator to the end of the sequence
  276. * @param [out] parameters A reference to the parameters list to append
  277. * paramter values extracted to
  278. * @return An iterator to the character after the last parameter read
  279. */
  280. template <typename InputIterator> InputIterator extract_parameters(InputIterator begin, InputIterator end, parameter_list & parameters)
  281. {
  282. InputIterator cursor;
  283. if (begin == end)
  284. {
  285. // error: expected non-zero length range
  286. return begin;
  287. }
  288. cursor = begin;
  289. std::pair<std::string, InputIterator> ret;
  290. /**
  291. * LWS
  292. * token
  293. * LWS
  294. * *(";" method-param)
  295. * LWS
  296. * ,=loop again
  297. */
  298. while (cursor != end)
  299. {
  300. std::string parameter_name;
  301. attribute_list attributes;
  302. // extract any stray whitespace
  303. cursor = http::parser::extract_all_lws(cursor, end);
  304. if (cursor == end)
  305. {
  306. break;
  307. }
  308. ret = http::parser::extract_token(cursor, end);
  309. if (ret.first.empty())
  310. {
  311. // error: expected a token
  312. return begin;
  313. }
  314. else
  315. {
  316. parameter_name = ret.first;
  317. cursor = ret.second;
  318. }
  319. // Safe break point, insert parameter with blank attributes and exit
  320. cursor = http::parser::extract_all_lws(cursor, end);
  321. if (cursor == end)
  322. {
  323. // parameters[parameter_name] = attributes;
  324. parameters.push_back(std::make_pair(parameter_name, attributes));
  325. break;
  326. }
  327. // If there is an attribute list, read it in
  328. if (*cursor == ';')
  329. {
  330. InputIterator acursor;
  331. ++cursor;
  332. acursor = http::parser::extract_attributes(cursor, end, attributes);
  333. if (acursor == cursor)
  334. {
  335. // attribute extraction ended in syntax error
  336. return begin;
  337. }
  338. cursor = acursor;
  339. }
  340. // insert parameter into output list
  341. // parameters[parameter_name] = attributes;
  342. parameters.push_back(std::make_pair(parameter_name, attributes));
  343. cursor = http::parser::extract_all_lws(cursor, end);
  344. if (cursor == end)
  345. {
  346. break;
  347. }
  348. // if next char is ',' then read another parameter, else stop
  349. if (*cursor != ',')
  350. {
  351. break;
  352. }
  353. // advance past comma
  354. ++cursor;
  355. if (cursor == end)
  356. {
  357. // expected more bytes after a comma
  358. return begin;
  359. }
  360. }
  361. return cursor;
  362. }
  363. inline std::string strip_lws(const std::string & input)
  364. {
  365. std::string::const_iterator begin = extract_all_lws(input.begin(), input.end());
  366. if (begin == input.end())
  367. {
  368. return std::string();
  369. }
  370. std::string::const_reverse_iterator rbegin = extract_all_lws(input.rbegin(), input.rend());
  371. if (rbegin == input.rend())
  372. {
  373. return std::string();
  374. }
  375. return std::string(begin, rbegin.base());
  376. }
  377. /// Base HTTP parser
  378. /**
  379. * Includes methods and data elements common to all types of HTTP messages such
  380. * as headers, versions, bodies, etc.
  381. */
  382. class parser
  383. {
  384. public:
  385. parser() :
  386. m_header_bytes(0),
  387. m_body_bytes_needed(0),
  388. m_body_bytes_max(max_body_size),
  389. m_body_encoding(body_encoding::unknown)
  390. {
  391. }
  392. /// Get the HTTP version string
  393. /**
  394. * @return The version string for this parser
  395. */
  396. const std::string & get_version() const
  397. {
  398. return m_version;
  399. }
  400. /// Set HTTP parser Version
  401. /**
  402. * Input should be in format: HTTP/x.y where x and y are positive integers.
  403. * @todo Does this method need any validation?
  404. *
  405. * @param [in] version The value to set the HTTP version to.
  406. */
  407. void set_version(const std::string & version);
  408. /// Get the value of an HTTP header
  409. /**
  410. * @todo Make this method case insensitive.
  411. *
  412. * @param [in] key The name/key of the header to get.
  413. * @return The value associated with the given HTTP header key.
  414. */
  415. const std::string & get_header(const std::string & key) const;
  416. /// Extract an HTTP parameter list from a parser header.
  417. /**
  418. * If the header requested doesn't exist or exists and is empty the
  419. * parameter list is valid (but empty).
  420. *
  421. * @param [in] key The name/key of the HTTP header to use as input.
  422. * @param [out] out The parameter list to store extracted parameters in.
  423. * @return Whether or not the input was a valid parameter list.
  424. */
  425. bool get_header_as_plist(const std::string & key, parameter_list & out) const;
  426. /// Return a list of all HTTP headers
  427. /**
  428. * Return a list of all HTTP headers
  429. *
  430. * @since 0.8.0
  431. *
  432. * @return A list of all HTTP headers
  433. */
  434. const header_list & get_headers() const;
  435. /// Append a value to an existing HTTP header
  436. /**
  437. * This method will set the value of the HTTP header `key` with the
  438. * indicated value. If a header with the name `key` already exists, `val`
  439. * will be appended to the existing value.
  440. *
  441. * @todo Make this method case insensitive.
  442. * @todo Should there be any restrictions on which keys are allowed?
  443. * @todo Exception free varient
  444. *
  445. * @see replace_header
  446. *
  447. * @param [in] key The name/key of the header to append to.
  448. * @param [in] val The value to append.
  449. */
  450. void append_header(const std::string & key, const std::string & val);
  451. /// Set a value for an HTTP header, replacing an existing value
  452. /**
  453. * This method will set the value of the HTTP header `key` with the
  454. * indicated value. If a header with the name `key` already exists, `val`
  455. * will replace the existing value.
  456. *
  457. * @todo Make this method case insensitive.
  458. * @todo Should there be any restrictions on which keys are allowed?
  459. * @todo Exception free varient
  460. *
  461. * @see append_header
  462. *
  463. * @param [in] key The name/key of the header to append to.
  464. * @param [in] val The value to append.
  465. */
  466. void replace_header(const std::string & key, const std::string & val);
  467. /// Remove a header from the parser
  468. /**
  469. * Removes the header entirely from the parser. This is different than
  470. * setting the value of the header to blank.
  471. *
  472. * @todo Make this method case insensitive.
  473. *
  474. * @param [in] key The name/key of the header to remove.
  475. */
  476. void remove_header(const std::string & key);
  477. /// Get HTTP body
  478. /**
  479. * Gets the body of the HTTP object
  480. *
  481. * @return The body of the HTTP message.
  482. */
  483. const std::string & get_body() const
  484. {
  485. return m_body;
  486. }
  487. /// Set body content
  488. /**
  489. * Set the body content of the HTTP response to the parameter string. Note
  490. * set_body will also set the Content-Length HTTP header to the appropriate
  491. * value. If you want the Content-Length header to be something else, do so
  492. * via replace_header("Content-Length") after calling set_body()
  493. *
  494. * @param value String data to include as the body content.
  495. */
  496. void set_body(const std::string & value);
  497. /// Get body size limit
  498. /**
  499. * Retrieves the maximum number of bytes to parse & buffer before canceling
  500. * a request.
  501. *
  502. * @since 0.5.0
  503. *
  504. * @return The maximum length of a message body.
  505. */
  506. size_t get_max_body_size() const
  507. {
  508. return m_body_bytes_max;
  509. }
  510. /// Set body size limit
  511. /**
  512. * Set the maximum number of bytes to parse and buffer before canceling a
  513. * request.
  514. *
  515. * @since 0.5.0
  516. *
  517. * @param value The size to set the max body length to.
  518. */
  519. void set_max_body_size(size_t value)
  520. {
  521. m_body_bytes_max = value;
  522. }
  523. /// Extract an HTTP parameter list from a string.
  524. /**
  525. * @param [in] in The input string.
  526. * @param [out] out The parameter list to store extracted parameters in.
  527. * @return Whether or not the input was a valid parameter list.
  528. */
  529. bool parse_parameter_list(const std::string & in, parameter_list & out) const;
  530. protected:
  531. /// Process a header line
  532. /**
  533. * @todo Update this method to be exception free.
  534. *
  535. * @param [in] begin An iterator to the beginning of the sequence.
  536. * @param [in] end An iterator to the end of the sequence.
  537. */
  538. void process_header(std::string::iterator begin, std::string::iterator end);
  539. /// Prepare the parser to begin parsing body data
  540. /**
  541. * Inspects headers to determine if the message has a body that needs to be
  542. * read. If so, sets up the necessary state, otherwise returns false. If
  543. * this method returns true and loading the message body is desired call
  544. * `process_body` until it returns zero bytes or an error.
  545. *
  546. * Must not be called until after all headers have been processed.
  547. *
  548. * @since 0.5.0
  549. *
  550. * @return True if more bytes are needed to load the body, false otherwise.
  551. */
  552. bool prepare_body();
  553. /// Process body data
  554. /**
  555. * Parses body data.
  556. *
  557. * @since 0.5.0
  558. *
  559. * @param [in] begin An iterator to the beginning of the sequence.
  560. * @param [in] end An iterator to the end of the sequence.
  561. * @return The number of bytes processed
  562. */
  563. size_t process_body(const char * buf, size_t len);
  564. /// Check if the parser is done parsing the body
  565. /**
  566. * Behavior before a call to `prepare_body` is undefined.
  567. *
  568. * @since 0.5.0
  569. *
  570. * @return True if the message body has been completed loaded.
  571. */
  572. bool body_ready() const
  573. {
  574. return (m_body_bytes_needed == 0);
  575. }
  576. /// Generate and return the HTTP headers as a string
  577. /**
  578. * Each headers will be followed by the \r\n sequence including the last one.
  579. * A second \r\n sequence (blank header) is not appended by this method
  580. *
  581. * @return The HTTP headers as a string.
  582. */
  583. std::string raw_headers() const;
  584. std::string m_version;
  585. header_list m_headers;
  586. size_t m_header_bytes;
  587. std::string m_body;
  588. size_t m_body_bytes_needed;
  589. size_t m_body_bytes_max;
  590. body_encoding::value m_body_encoding;
  591. };
  592. } // namespace parser
  593. } // namespace http
  594. } // namespace websocketpp
  595. #include <websocketpp/http/impl/parser.hpp>
  596. #endif // HTTP_PARSER_HPP