parser.hpp 14 KB

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