basic_parser.hpp 23 KB

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