basic_parser.hpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/beast
  8. //
  9. #ifndef BOOST_BEAST_HTTP_BASIC_PARSER_HPP
  10. #define BOOST_BEAST_HTTP_BASIC_PARSER_HPP
  11. #include <boost/beast/core/detail/config.hpp>
  12. #include <boost/beast/core/error.hpp>
  13. #include <boost/beast/core/string.hpp>
  14. #include <boost/beast/http/field.hpp>
  15. #include <boost/beast/http/verb.hpp>
  16. #include <boost/beast/http/detail/basic_parser.hpp>
  17. #include <boost/asio/buffer.hpp>
  18. #include <boost/optional.hpp>
  19. #include <boost/assert.hpp>
  20. #include <limits>
  21. #include <memory>
  22. #include <type_traits>
  23. #include <utility>
  24. namespace boost {
  25. namespace beast {
  26. namespace http {
  27. /** A parser for decoding HTTP/1 wire format messages.
  28. This parser is designed to efficiently parse messages in the
  29. HTTP/1 wire format. It allocates no memory when input is
  30. presented as a single contiguous buffer, and uses minimal
  31. state. It will handle chunked encoding and it understands
  32. the semantics of the Connection, Content-Length, and Upgrade
  33. fields.
  34. The parser is optimized for the case where the input buffer
  35. sequence consists of a single contiguous buffer. The
  36. @ref beast::basic_flat_buffer class is provided, which guarantees
  37. that the input sequence of the stream buffer will be represented
  38. by exactly one contiguous buffer. To ensure the optimum performance
  39. of the parser, use @ref beast::basic_flat_buffer with HTTP algorithms
  40. such as @ref read, @ref read_some, @ref async_read, and @ref async_read_some.
  41. Alternatively, the caller may use custom techniques to ensure that
  42. the structured portion of the HTTP message (header or chunk header)
  43. is contained in a linear buffer.
  44. The interface to the parser uses virtual member functions.
  45. To use this class, derive your type from @ref basic_parser. When
  46. bytes are presented, the implementation will make a series of zero
  47. or more calls to virtual functions, which the derived class must
  48. implement.
  49. Every virtual function must be provided by the derived class,
  50. or else a compilation error will be generated. The implementation
  51. will make sure that `ec` is clear before each virtual function
  52. is invoked. If a virtual function sets an error, it is propagated
  53. out of the parser to the caller.
  54. @tparam isRequest A `bool` indicating whether the parser will be
  55. presented with request or response message.
  56. @note If the parser encounters a field value with obs-fold
  57. longer than 4 kilobytes in length, an error is generated.
  58. */
  59. template<bool isRequest>
  60. class basic_parser
  61. : private detail::basic_parser_base
  62. {
  63. std::uint64_t body_limit_ =
  64. default_body_limit(is_request{}); // max payload body
  65. std::uint64_t len_ = 0; // size of chunk or body
  66. std::uint64_t len0_ = 0; // content length if known
  67. std::unique_ptr<char[]> buf_; // temp storage
  68. std::size_t buf_len_ = 0; // size of buf_
  69. std::size_t skip_ = 0; // resume search here
  70. std::uint32_t header_limit_ = 8192; // max header size
  71. unsigned short status_ = 0; // response status
  72. state state_ = state::nothing_yet; // initial state
  73. unsigned f_ = 0; // flags
  74. // limit on the size of the stack flat buffer
  75. static std::size_t constexpr max_stack_buffer = 8192;
  76. // Message will be complete after reading header
  77. static unsigned constexpr flagSkipBody = 1<< 0;
  78. // Consume input buffers across semantic boundaries
  79. static unsigned constexpr flagEager = 1<< 1;
  80. // The parser has read at least one byte
  81. static unsigned constexpr flagGotSome = 1<< 2;
  82. // Message semantics indicate a body is expected.
  83. // cleared if flagSkipBody set
  84. //
  85. static unsigned constexpr flagHasBody = 1<< 3;
  86. static unsigned constexpr flagHTTP11 = 1<< 4;
  87. static unsigned constexpr flagNeedEOF = 1<< 5;
  88. static unsigned constexpr flagExpectCRLF = 1<< 6;
  89. static unsigned constexpr flagConnectionClose = 1<< 7;
  90. static unsigned constexpr flagConnectionUpgrade = 1<< 8;
  91. static unsigned constexpr flagConnectionKeepAlive = 1<< 9;
  92. static unsigned constexpr flagContentLength = 1<< 10;
  93. static unsigned constexpr flagChunked = 1<< 11;
  94. static unsigned constexpr flagUpgrade = 1<< 12;
  95. static unsigned constexpr flagFinalChunk = 1<< 13;
  96. static constexpr
  97. std::uint64_t
  98. default_body_limit(std::true_type)
  99. {
  100. // limit for requests
  101. return 1 * 1024 * 1024; // 1MB
  102. }
  103. static constexpr
  104. std::uint64_t
  105. default_body_limit(std::false_type)
  106. {
  107. // limit for responses
  108. return 8 * 1024 * 1024; // 8MB
  109. }
  110. template<bool OtherIsRequest>
  111. friend class basic_parser;
  112. friend class basic_parser_test;
  113. protected:
  114. /// Default constructor
  115. basic_parser() = default;
  116. /** Move constructor
  117. @note
  118. After the move, the only valid operation on the
  119. moved-from object is destruction.
  120. */
  121. basic_parser(basic_parser &&) = default;
  122. /// Move assignment
  123. basic_parser& operator=(basic_parser &&) = default;
  124. public:
  125. /// `true` if this parser parses requests, `false` for responses.
  126. using is_request =
  127. std::integral_constant<bool, isRequest>;
  128. /// Destructor
  129. virtual ~basic_parser() = default;
  130. /// Copy constructor
  131. basic_parser(basic_parser const&) = delete;
  132. /// Copy assignment
  133. basic_parser& operator=(basic_parser const&) = delete;
  134. /// Returns `true` if the parser has received at least one byte of input.
  135. bool
  136. got_some() const
  137. {
  138. return state_ != state::nothing_yet;
  139. }
  140. /** Returns `true` if the message is complete.
  141. The message is complete after the full header is prduced
  142. and one of the following is true:
  143. @li The skip body option was set.
  144. @li The semantics of the message indicate there is no body.
  145. @li The semantics of the message indicate a body is expected,
  146. and the entire body was parsed.
  147. */
  148. bool
  149. is_done() const
  150. {
  151. return state_ == state::complete;
  152. }
  153. /** Returns `true` if a the parser has produced the full header.
  154. */
  155. bool
  156. is_header_done() const
  157. {
  158. return state_ > state::fields;
  159. }
  160. /** Returns `true` if the message is an upgrade message.
  161. @note The return value is undefined unless
  162. @ref is_header_done would return `true`.
  163. */
  164. bool
  165. upgrade() const
  166. {
  167. return (f_ & flagConnectionUpgrade) != 0;
  168. }
  169. /** Returns `true` if the last value for Transfer-Encoding is "chunked".
  170. @note The return value is undefined unless
  171. @ref is_header_done would return `true`.
  172. */
  173. bool
  174. chunked() const
  175. {
  176. return (f_ & flagChunked) != 0;
  177. }
  178. /** Returns `true` if the message has keep-alive connection semantics.
  179. This function always returns `false` if @ref need_eof would return
  180. `false`.
  181. @note The return value is undefined unless
  182. @ref is_header_done would return `true`.
  183. */
  184. bool
  185. keep_alive() const;
  186. /** Returns the optional value of Content-Length if known.
  187. @note The return value is undefined unless
  188. @ref is_header_done would return `true`.
  189. */
  190. boost::optional<std::uint64_t>
  191. content_length() const;
  192. /** Returns the remaining content length if known
  193. If the message header specifies a Content-Length,
  194. the return value will be the number of bytes remaining
  195. in the payload body have not yet been parsed.
  196. @note The return value is undefined unless
  197. @ref is_header_done would return `true`.
  198. */
  199. boost::optional<std::uint64_t>
  200. content_length_remaining() const;
  201. /** Returns `true` if the message semantics require an end of file.
  202. Depending on the contents of the header, the parser may
  203. require and end of file notification to know where the end
  204. of the body lies. If this function returns `true` it will be
  205. necessary to call @ref put_eof when there will never be additional
  206. data from the input.
  207. */
  208. bool
  209. need_eof() const
  210. {
  211. return (f_ & flagNeedEOF) != 0;
  212. }
  213. /** Set the limit on the payload body.
  214. This function sets the maximum allowed size of the payload body,
  215. before any encodings except chunked have been removed. Depending
  216. on the message semantics, one of these cases will apply:
  217. @li The Content-Length is specified and exceeds the limit. In
  218. this case the result @ref error::body_limit is returned
  219. immediately after the header is parsed.
  220. @li The Content-Length is unspecified and the chunked encoding
  221. is not specified as the last encoding. In this case the end of
  222. message is determined by the end of file indicator on the
  223. associated stream or input source. If a sufficient number of
  224. body payload octets are presented to the parser to exceed the
  225. configured limit, the parse fails with the result
  226. @ref error::body_limit
  227. @li The Transfer-Encoding specifies the chunked encoding as the
  228. last encoding. In this case, when the number of payload body
  229. octets produced by removing the chunked encoding exceeds
  230. the configured limit, the parse fails with the result
  231. @ref error::body_limit.
  232. Setting the limit after any body octets have been parsed
  233. results in undefined behavior.
  234. The default limit is 1MB for requests and 8MB for responses.
  235. @param v The payload body limit to set
  236. */
  237. void
  238. body_limit(std::uint64_t v)
  239. {
  240. body_limit_ = v;
  241. }
  242. /** Set a limit on the total size of the header.
  243. This function sets the maximum allowed size of the header
  244. including all field name, value, and delimiter characters
  245. and also including the CRLF sequences in the serialized
  246. input. If the end of the header is not found within the
  247. limit of the header size, the error @ref error::header_limit
  248. is returned by @ref put.
  249. Setting the limit after any header octets have been parsed
  250. results in undefined behavior.
  251. */
  252. void
  253. header_limit(std::uint32_t v)
  254. {
  255. header_limit_ = v;
  256. }
  257. /// Returns `true` if the eager parse option is set.
  258. bool
  259. eager() const
  260. {
  261. return (f_ & flagEager) != 0;
  262. }
  263. /** Set the eager parse option.
  264. Normally the parser returns after successfully parsing a structured
  265. element (header, chunk header, or chunk body) even if there are octets
  266. remaining in the input. This is necessary when attempting to parse the
  267. header first, or when the caller wants to inspect information which may
  268. be invalidated by subsequent parsing, such as a chunk extension. The
  269. `eager` option controls whether the parser keeps going after parsing
  270. structured element if there are octets remaining in the buffer and no
  271. error occurs. This option is automatically set or cleared during certain
  272. stream operations to improve performance with no change in functionality.
  273. The default setting is `false`.
  274. @param v `true` to set the eager parse option or `false` to disable it.
  275. */
  276. void
  277. eager(bool v)
  278. {
  279. if(v)
  280. f_ |= flagEager;
  281. else
  282. f_ &= ~flagEager;
  283. }
  284. /// Returns `true` if the skip parse option is set.
  285. bool
  286. skip() const
  287. {
  288. return (f_ & flagSkipBody) != 0;
  289. }
  290. /** Set the skip parse option.
  291. This option controls whether or not the parser expects to see an HTTP
  292. body, regardless of the presence or absence of certain fields such as
  293. Content-Length or a chunked Transfer-Encoding. Depending on the request,
  294. some responses do not carry a body. For example, a 200 response to a
  295. CONNECT request from a tunneling proxy, or a response to a HEAD request.
  296. In these cases, callers may use this function inform the parser that
  297. no body is expected. The parser will consider the message complete
  298. after the header has been received.
  299. @param v `true` to set the skip body option or `false` to disable it.
  300. @note This function must called before any bytes are processed.
  301. */
  302. void
  303. skip(bool v);
  304. /** Write a buffer sequence to the parser.
  305. This function attempts to incrementally parse the HTTP
  306. message data stored in the caller provided buffers. Upon
  307. success, a positive return value indicates that the parser
  308. made forward progress, consuming that number of
  309. bytes.
  310. In some cases there may be an insufficient number of octets
  311. in the input buffer in order to make forward progress. This
  312. is indicated by the code @ref error::need_more. When
  313. this happens, the caller should place additional bytes into
  314. the buffer sequence and call @ref put again.
  315. The error code @ref error::need_more is special. When this
  316. error is returned, a subsequent call to @ref put may succeed
  317. if the buffers have been updated. Otherwise, upon error
  318. the parser may not be restarted.
  319. @param buffers An object meeting the requirements of
  320. <em>ConstBufferSequence</em> that represents the next chunk of
  321. message data. If the length of this buffer sequence is
  322. one, the implementation will not allocate additional memory.
  323. The class @ref beast::basic_flat_buffer is provided as one way to
  324. meet this requirement
  325. @param ec Set to the error, if any occurred.
  326. @return The number of octets consumed in the buffer
  327. sequence. The caller should remove these octets even if the
  328. error is set.
  329. */
  330. template<class ConstBufferSequence>
  331. std::size_t
  332. put(ConstBufferSequence const& buffers, error_code& ec);
  333. #if ! BOOST_BEAST_DOXYGEN
  334. std::size_t
  335. put(net::const_buffer buffer,
  336. error_code& ec);
  337. #endif
  338. /** Inform the parser that the end of stream was reached.
  339. In certain cases, HTTP needs to know where the end of
  340. the stream is. For example, sometimes servers send
  341. responses without Content-Length and expect the client
  342. to consume input (for the body) until EOF. Callbacks
  343. and errors will still be processed as usual.
  344. This is typically called when a read from the
  345. underlying stream object sets the error code to
  346. `net::error::eof`.
  347. @note Only valid after parsing a complete header.
  348. @param ec Set to the error, if any occurred.
  349. */
  350. void
  351. put_eof(error_code& ec);
  352. protected:
  353. /** Called after receiving the request-line.
  354. This virtual function is invoked after receiving a request-line
  355. when parsing HTTP requests.
  356. It can only be called when `isRequest == true`.
  357. @param method The verb enumeration. If the method string is not
  358. one of the predefined strings, this value will be @ref verb::unknown.
  359. @param method_str The unmodified string representing the verb.
  360. @param target The request-target.
  361. @param version The HTTP-version. This will be 10 for HTTP/1.0,
  362. and 11 for HTTP/1.1.
  363. @param ec An output parameter which the function may set to indicate
  364. an error. The error will be clear before this function is invoked.
  365. */
  366. virtual
  367. void
  368. on_request_impl(
  369. verb method,
  370. string_view method_str,
  371. string_view target,
  372. int version,
  373. error_code& ec) = 0;
  374. /** Called after receiving the status-line.
  375. This virtual function is invoked after receiving a status-line
  376. when parsing HTTP responses.
  377. It can only be called when `isRequest == false`.
  378. @param code The numeric status code.
  379. @param reason The reason-phrase. Note that this value is
  380. now obsolete, and only provided for historical or diagnostic
  381. purposes.
  382. @param version The HTTP-version. This will be 10 for HTTP/1.0,
  383. and 11 for HTTP/1.1.
  384. @param ec An output parameter which the function may set to indicate
  385. an error. The error will be clear before this function is invoked.
  386. */
  387. virtual
  388. void
  389. on_response_impl(
  390. int code,
  391. string_view reason,
  392. int version,
  393. error_code& ec) = 0;
  394. /** Called once for each complete field in the HTTP header.
  395. This virtual function is invoked for each field that is received
  396. while parsing an HTTP message.
  397. @param name The known field enum value. If the name of the field
  398. is not recognized, this value will be @ref field::unknown.
  399. @param name_string The exact name of the field as received from
  400. the input, represented as a string.
  401. @param value A string holding the value of the field.
  402. @param ec An output parameter which the function may set to indicate
  403. an error. The error will be clear before this function is invoked.
  404. */
  405. virtual
  406. void
  407. on_field_impl(
  408. field name,
  409. string_view name_string,
  410. string_view value,
  411. error_code& ec) = 0;
  412. /** Called once after the complete HTTP header is received.
  413. This virtual function is invoked once, after the complete HTTP
  414. header is received while parsing a message.
  415. @param ec An output parameter which the function may set to indicate
  416. an error. The error will be clear before this function is invoked.
  417. */
  418. virtual
  419. void
  420. on_header_impl(error_code& ec) = 0;
  421. /** Called once before the body is processed.
  422. This virtual function is invoked once, before the content body is
  423. processed (but after the complete header is received).
  424. @param content_length A value representing the content length in
  425. bytes if the length is known (this can include a zero length).
  426. Otherwise, the value will be `boost::none`.
  427. @param ec An output parameter which the function may set to indicate
  428. an error. The error will be clear before this function is invoked.
  429. */
  430. virtual
  431. void
  432. on_body_init_impl(
  433. boost::optional<std::uint64_t> const& content_length,
  434. error_code& ec) = 0;
  435. /** Called each time additional data is received representing the content body.
  436. This virtual function is invoked for each piece of the body which is
  437. received while parsing of a message. This function is only used when
  438. no chunked transfer encoding is present.
  439. @param body A string holding the additional body contents. This may
  440. contain nulls or unprintable characters.
  441. @param ec An output parameter which the function may set to indicate
  442. an error. The error will be clear before this function is invoked.
  443. @see on_chunk_body_impl
  444. */
  445. virtual
  446. std::size_t
  447. on_body_impl(
  448. string_view body,
  449. error_code& ec) = 0;
  450. /** Called each time a new chunk header of a chunk encoded body is received.
  451. This function is invoked each time a new chunk header is received.
  452. The function is only used when the chunked transfer encoding is present.
  453. @param size The size of this chunk, in bytes.
  454. @param extensions A string containing the entire chunk extensions.
  455. This may be empty, indicating no extensions are present.
  456. @param ec An output parameter which the function may set to indicate
  457. an error. The error will be clear before this function is invoked.
  458. */
  459. virtual
  460. void
  461. on_chunk_header_impl(
  462. std::uint64_t size,
  463. string_view extensions,
  464. error_code& ec) = 0;
  465. /** Called each time additional data is received representing part of a body chunk.
  466. This virtual function is invoked for each piece of the body which is
  467. received while parsing of a message. This function is only used when
  468. no chunked transfer encoding is present.
  469. @param remain The number of bytes remaining in this chunk. This includes
  470. the contents of passed `body`. If this value is zero, then this represents
  471. the final chunk.
  472. @param body A string holding the additional body contents. This may
  473. contain nulls or unprintable characters.
  474. @param ec An output parameter which the function may set to indicate
  475. an error. The error will be clear before this function is invoked.
  476. @return This function should return the number of bytes actually consumed
  477. from the `body` value. Any bytes that are not consumed on this call
  478. will be presented in a subsequent call.
  479. @see on_body_impl
  480. */
  481. virtual
  482. std::size_t
  483. on_chunk_body_impl(
  484. std::uint64_t remain,
  485. string_view body,
  486. error_code& ec) = 0;
  487. /** Called once when the complete message is received.
  488. This virtual function is invoked once, after successfully parsing
  489. a complete HTTP message.
  490. @param ec An output parameter which the function may set to indicate
  491. an error. The error will be clear before this function is invoked.
  492. */
  493. virtual
  494. void
  495. on_finish_impl(error_code& ec) = 0;
  496. private:
  497. template<class ConstBufferSequence>
  498. std::size_t
  499. put_from_stack(
  500. std::size_t size,
  501. ConstBufferSequence const& buffers,
  502. error_code& ec);
  503. void
  504. maybe_need_more(
  505. char const* p, std::size_t n,
  506. error_code& ec);
  507. void
  508. parse_start_line(
  509. char const*& p, char const* last,
  510. error_code& ec, std::true_type);
  511. void
  512. parse_start_line(
  513. char const*& p, char const* last,
  514. error_code& ec, std::false_type);
  515. void
  516. parse_fields(
  517. char const*& p, char const* last,
  518. error_code& ec);
  519. void
  520. finish_header(
  521. error_code& ec, std::true_type);
  522. void
  523. finish_header(
  524. error_code& ec, std::false_type);
  525. void
  526. parse_body(char const*& p,
  527. std::size_t n, error_code& ec);
  528. void
  529. parse_body_to_eof(char const*& p,
  530. std::size_t n, error_code& ec);
  531. void
  532. parse_chunk_header(char const*& p,
  533. std::size_t n, error_code& ec);
  534. void
  535. parse_chunk_body(char const*& p,
  536. std::size_t n, error_code& ec);
  537. void
  538. do_field(field f,
  539. string_view value, error_code& ec);
  540. };
  541. } // http
  542. } // beast
  543. } // boost
  544. #include <boost/beast/http/impl/basic_parser.hpp>
  545. #ifdef BOOST_BEAST_HEADER_ONLY
  546. #include <boost/beast/http/impl/basic_parser.ipp>
  547. #endif
  548. #endif