basic_parser.hpp 23 KB

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