parser.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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_PARSER_HPP
  10. #define BOOST_BEAST_HTTP_PARSER_HPP
  11. #include <boost/beast/core/detail/config.hpp>
  12. #include <boost/beast/http/basic_parser.hpp>
  13. #include <boost/beast/http/message.hpp>
  14. #include <boost/beast/http/type_traits.hpp>
  15. #include <boost/optional.hpp>
  16. #include <boost/throw_exception.hpp>
  17. #include <cstdint>
  18. #include <functional>
  19. #include <memory>
  20. #include <type_traits>
  21. #include <utility>
  22. namespace boost {
  23. namespace beast {
  24. namespace http {
  25. /** An HTTP/1 parser for producing a message.
  26. This class uses the basic HTTP/1 wire format parser to convert
  27. a series of octets into a @ref message using the @ref basic_fields
  28. container to represent the fields.
  29. @tparam isRequest Indicates whether a request or response
  30. will be parsed.
  31. @tparam Body The type used to represent the body. This must
  32. meet the requirements of <em>Body</em>.
  33. @tparam Allocator The type of allocator used with the
  34. @ref basic_fields container.
  35. @note A new instance of the parser is required for each message.
  36. */
  37. template<
  38. bool isRequest,
  39. class Body,
  40. class Allocator = std::allocator<char>>
  41. class parser
  42. : public basic_parser<isRequest>
  43. {
  44. static_assert(is_body<Body>::value,
  45. "Body type requirements not met");
  46. static_assert(is_body_reader<Body>::value,
  47. "BodyReader type requirements not met");
  48. template<bool, class, class>
  49. friend class parser;
  50. message<isRequest, Body, basic_fields<Allocator>> m_;
  51. typename Body::reader rd_;
  52. bool rd_inited_ = false;
  53. bool used_ = false;
  54. std::function<void(
  55. std::uint64_t,
  56. string_view,
  57. error_code&)> cb_h_;
  58. std::function<std::size_t(
  59. std::uint64_t,
  60. string_view,
  61. error_code&)> cb_b_;
  62. public:
  63. /// The type of message returned by the parser
  64. using value_type =
  65. message<isRequest, Body, basic_fields<Allocator>>;
  66. /// Destructor
  67. ~parser() = default;
  68. /// Constructor (disallowed)
  69. parser(parser const&) = delete;
  70. /// Assignment (disallowed)
  71. parser& operator=(parser const&) = delete;
  72. /// Constructor (disallowed)
  73. parser(parser&& other) = delete;
  74. /// Constructor
  75. parser();
  76. /** Constructor
  77. @param args Optional arguments forwarded to the
  78. @ref http::message constructor.
  79. @note This function participates in overload
  80. resolution only if the first argument is not a
  81. @ref parser.
  82. */
  83. #if BOOST_BEAST_DOXYGEN
  84. template<class... Args>
  85. explicit
  86. parser(Args&&... args);
  87. #else
  88. template<class Arg1, class... ArgN,
  89. class = typename std::enable_if<
  90. ! detail::is_parser<typename
  91. std::decay<Arg1>::type>::value>::type>
  92. explicit
  93. parser(Arg1&& arg1, ArgN&&... argn);
  94. #endif
  95. /** Construct a parser from another parser, changing the Body type.
  96. This constructs a new parser by move constructing the
  97. header from another parser with a different body type. The
  98. constructed-from parser must not have any parsed body octets or
  99. initialized <em>BodyReader</em>, otherwise an exception is generated.
  100. @par Example
  101. @code
  102. // Deferred body type commitment
  103. request_parser<empty_body> req0;
  104. ...
  105. request_parser<string_body> req{std::move(req0)};
  106. @endcode
  107. If an exception is thrown, the state of the constructed-from
  108. parser is undefined.
  109. @param parser The other parser to construct from. After
  110. this call returns, the constructed-from parser may only
  111. be destroyed.
  112. @param args Optional arguments forwarded to the message
  113. constructor.
  114. @throws std::invalid_argument Thrown when the constructed-from
  115. parser has already initialized a body reader.
  116. @note This function participates in overload resolution only
  117. if the other parser uses a different body type.
  118. */
  119. #if BOOST_BEAST_DOXYGEN
  120. template<class OtherBody, class... Args>
  121. #else
  122. template<class OtherBody, class... Args,
  123. class = typename std::enable_if<
  124. ! std::is_same<Body, OtherBody>::value>::type>
  125. #endif
  126. explicit
  127. parser(parser<isRequest, OtherBody,
  128. Allocator>&& parser, Args&&... args);
  129. /** Returns the parsed message.
  130. Depending on the parser's progress,
  131. parts of this object may be incomplete.
  132. */
  133. value_type const&
  134. get() const
  135. {
  136. return m_;
  137. }
  138. /** Returns the parsed message.
  139. Depending on the parser's progress,
  140. parts of this object may be incomplete.
  141. */
  142. value_type&
  143. get()
  144. {
  145. return m_;
  146. }
  147. /** Returns ownership of the parsed message.
  148. Ownership is transferred to the caller.
  149. Depending on the parser's progress,
  150. parts of this object may be incomplete.
  151. @par Requires
  152. @ref value_type is @b MoveConstructible
  153. */
  154. value_type
  155. release()
  156. {
  157. static_assert(std::is_move_constructible<decltype(m_)>::value,
  158. "MoveConstructible requirements not met");
  159. return std::move(m_);
  160. }
  161. /** Set a callback to be invoked on each chunk header.
  162. The callback will be invoked once for every chunk in the message
  163. payload, as well as once for the last chunk. The invocation
  164. happens after the chunk header is available but before any body
  165. octets have been parsed.
  166. The extensions are provided in raw, validated form, use
  167. @ref chunk_extensions::parse to parse the extensions into a
  168. structured container for easier access.
  169. The implementation type-erases the callback without requiring
  170. a dynamic allocation. For this reason, the callback object is
  171. passed by a non-constant reference.
  172. @par Example
  173. @code
  174. auto callback =
  175. [](std::uint64_t size, string_view extensions, error_code& ec)
  176. {
  177. //...
  178. };
  179. parser.on_chunk_header(callback);
  180. @endcode
  181. @param cb The function to set, which must be invocable with
  182. this equivalent signature:
  183. @code
  184. void
  185. on_chunk_header(
  186. std::uint64_t size, // Size of the chunk, zero for the last chunk
  187. string_view extensions, // The chunk-extensions in raw form
  188. error_code& ec); // May be set by the callback to indicate an error
  189. @endcode
  190. */
  191. template<class Callback>
  192. void
  193. on_chunk_header(Callback& cb)
  194. {
  195. // Callback may not be constant, caller is responsible for
  196. // managing the lifetime of the callback. Copies are not made.
  197. BOOST_STATIC_ASSERT(! std::is_const<Callback>::value);
  198. // Can't set the callback after receiving any chunk data!
  199. BOOST_ASSERT(! rd_inited_);
  200. cb_h_ = std::ref(cb);
  201. }
  202. /** Set a callback to be invoked on chunk body data
  203. The provided function object will be invoked one or more times
  204. to provide buffers corresponding to the chunk body for the current
  205. chunk. The callback receives the number of octets remaining in this
  206. chunk body including the octets in the buffer provided.
  207. The callback must return the number of octets actually consumed.
  208. Any octets not consumed will be presented again in a subsequent
  209. invocation of the callback.
  210. The implementation type-erases the callback without requiring
  211. a dynamic allocation. For this reason, the callback object is
  212. passed by a non-constant reference.
  213. @par Example
  214. @code
  215. auto callback =
  216. [](std::uint64_t remain, string_view body, error_code& ec)
  217. {
  218. //...
  219. };
  220. parser.on_chunk_body(callback);
  221. @endcode
  222. @param cb The function to set, which must be invocable with
  223. this equivalent signature:
  224. @code
  225. std::size_t
  226. on_chunk_header(
  227. std::uint64_t remain, // Octets remaining in this chunk, includes `body`
  228. string_view body, // A buffer holding some or all of the remainder of the chunk body
  229. error_code& ec); // May be set by the callback to indicate an error
  230. @endcode
  231. */
  232. template<class Callback>
  233. void
  234. on_chunk_body(Callback& cb)
  235. {
  236. // Callback may not be constant, caller is responsible for
  237. // managing the lifetime of the callback. Copies are not made.
  238. BOOST_STATIC_ASSERT(! std::is_const<Callback>::value);
  239. // Can't set the callback after receiving any chunk data!
  240. BOOST_ASSERT(! rd_inited_);
  241. cb_b_ = std::ref(cb);
  242. }
  243. private:
  244. parser(std::true_type);
  245. parser(std::false_type);
  246. template<class OtherBody, class... Args,
  247. class = typename std::enable_if<
  248. ! std::is_same<Body, OtherBody>::value>::type>
  249. parser(
  250. std::true_type,
  251. parser<isRequest, OtherBody, Allocator>&& parser,
  252. Args&&... args);
  253. template<class OtherBody, class... Args,
  254. class = typename std::enable_if<
  255. ! std::is_same<Body, OtherBody>::value>::type>
  256. parser(
  257. std::false_type,
  258. parser<isRequest, OtherBody, Allocator>&& parser,
  259. Args&&... args);
  260. template<class Arg1, class... ArgN,
  261. class = typename std::enable_if<
  262. ! detail::is_parser<typename
  263. std::decay<Arg1>::type>::value>::type>
  264. explicit
  265. parser(Arg1&& arg1, std::true_type, ArgN&&... argn);
  266. template<class Arg1, class... ArgN,
  267. class = typename std::enable_if<
  268. ! detail::is_parser<typename
  269. std::decay<Arg1>::type>::value>::type>
  270. explicit
  271. parser(Arg1&& arg1, std::false_type, ArgN&&... argn);
  272. void
  273. on_request_impl(
  274. verb method,
  275. string_view method_str,
  276. string_view target,
  277. int version,
  278. error_code& ec,
  279. std::true_type)
  280. {
  281. // If this assert goes off, it means you tried to re-use a
  282. // parser after it was done reading a message. This is not
  283. // allowed, you need to create a new parser for each message.
  284. // The easiest way to do that is to store the parser in
  285. // an optional object.
  286. BOOST_ASSERT(! used_);
  287. if(used_)
  288. {
  289. BOOST_BEAST_ASSIGN_EC(ec, error::stale_parser);
  290. return;
  291. }
  292. used_ = true;
  293. m_.target(target);
  294. if(method != verb::unknown)
  295. m_.method(method);
  296. else
  297. m_.method_string(method_str);
  298. m_.version(version);
  299. }
  300. void
  301. on_request_impl(
  302. verb, string_view, string_view,
  303. int, error_code&, std::false_type)
  304. {
  305. }
  306. void
  307. on_request_impl(
  308. verb method,
  309. string_view method_str,
  310. string_view target,
  311. int version,
  312. error_code& ec) override
  313. {
  314. this->on_request_impl(
  315. method, method_str, target, version, ec,
  316. std::integral_constant<bool, isRequest>{});
  317. }
  318. void
  319. on_response_impl(
  320. int code,
  321. string_view reason,
  322. int version,
  323. error_code& ec,
  324. std::true_type)
  325. {
  326. // If this assert goes off, it means you tried to re-use a
  327. // parser after it was done reading a message. This is not
  328. // allowed, you need to create a new parser for each message.
  329. // The easiest way to do that is to store the parser in
  330. // an optional object.
  331. BOOST_ASSERT(! used_);
  332. if(used_)
  333. {
  334. BOOST_BEAST_ASSIGN_EC(ec, error::stale_parser);
  335. return;
  336. }
  337. used_ = true;
  338. m_.result(code);
  339. m_.version(version);
  340. m_.reason(reason);
  341. }
  342. void
  343. on_response_impl(
  344. int, string_view, int,
  345. error_code&, std::false_type)
  346. {
  347. }
  348. void
  349. on_response_impl(
  350. int code,
  351. string_view reason,
  352. int version,
  353. error_code& ec) override
  354. {
  355. this->on_response_impl(
  356. code, reason, version, ec,
  357. std::integral_constant<bool, ! isRequest>{});
  358. }
  359. void
  360. on_field_impl(
  361. field name,
  362. string_view name_string,
  363. string_view value,
  364. error_code&) override
  365. {
  366. m_.insert(name, name_string, value);
  367. }
  368. void
  369. on_header_impl(error_code& ec) override
  370. {
  371. ec = {};
  372. }
  373. void
  374. on_body_init_impl(
  375. boost::optional<std::uint64_t> const& content_length,
  376. error_code& ec) override
  377. {
  378. rd_.init(content_length, ec);
  379. rd_inited_ = true;
  380. }
  381. std::size_t
  382. on_body_impl(
  383. string_view body,
  384. error_code& ec) override
  385. {
  386. return rd_.put(net::buffer(
  387. body.data(), body.size()), ec);
  388. }
  389. void
  390. on_chunk_header_impl(
  391. std::uint64_t size,
  392. string_view extensions,
  393. error_code& ec) override
  394. {
  395. if(cb_h_)
  396. return cb_h_(size, extensions, ec);
  397. }
  398. std::size_t
  399. on_chunk_body_impl(
  400. std::uint64_t remain,
  401. string_view body,
  402. error_code& ec) override
  403. {
  404. if(cb_b_)
  405. return cb_b_(remain, body, ec);
  406. return rd_.put(net::buffer(
  407. body.data(), body.size()), ec);
  408. }
  409. void
  410. on_finish_impl(
  411. error_code& ec) override
  412. {
  413. rd_.finish(ec);
  414. }
  415. };
  416. /// An HTTP/1 parser for producing a request message.
  417. template<class Body, class Allocator = std::allocator<char>>
  418. using request_parser = parser<true, Body, Allocator>;
  419. /// An HTTP/1 parser for producing a response message.
  420. template<class Body, class Allocator = std::allocator<char>>
  421. using response_parser = parser<false, Body, Allocator>;
  422. } // http
  423. } // beast
  424. } // boost
  425. #include <boost/beast/http/impl/parser.hpp>
  426. #endif