basic_file_body.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. //
  2. // Copyright (c) 2016-2017 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_FILE_BODY_HPP
  10. #define BOOST_BEAST_HTTP_BASIC_FILE_BODY_HPP
  11. #include <boost/beast/core/detail/config.hpp>
  12. #include <boost/beast/core/error.hpp>
  13. #include <boost/beast/core/file_base.hpp>
  14. #include <boost/beast/core/type_traits.hpp>
  15. #include <boost/beast/http/message.hpp>
  16. #include <boost/assert.hpp>
  17. #include <boost/optional.hpp>
  18. #include <algorithm>
  19. #include <cstdio>
  20. #include <cstdint>
  21. #include <utility>
  22. namespace boost {
  23. namespace beast {
  24. namespace http {
  25. //[example_http_file_body_1
  26. /** A message body represented by a file on the filesystem.
  27. Messages with this type have bodies represented by a
  28. file on the file system. When parsing a message using
  29. this body type, the data is stored in the file pointed
  30. to by the path, which must be writable. When serializing,
  31. the implementation will read the file and present those
  32. octets as the body content. This may be used to serve
  33. content from a directory as part of a web service.
  34. @tparam File The implementation to use for accessing files.
  35. This type must meet the requirements of @b File.
  36. */
  37. template<class File>
  38. struct basic_file_body
  39. {
  40. // Make sure the type meets the requirements
  41. static_assert(is_file<File>::value,
  42. "File requirements not met");
  43. /// The type of File this body uses
  44. using file_type = File;
  45. // Algorithm for storing buffers when parsing.
  46. class reader;
  47. // Algorithm for retrieving buffers when serializing.
  48. class writer;
  49. // The type of the @ref message::body member.
  50. class value_type;
  51. /** Returns the size of the body
  52. @param body The file body to use
  53. */
  54. static
  55. std::uint64_t
  56. size(value_type const& body);
  57. };
  58. //]
  59. //[example_http_file_body_2
  60. /** The type of the @ref message::body member.
  61. Messages declared using `basic_file_body` will have this type for
  62. the body member. This rich class interface allow the file to be
  63. opened with the file handle maintained directly in the object,
  64. which is attached to the message.
  65. */
  66. template<class File>
  67. class basic_file_body<File>::value_type
  68. {
  69. // This body container holds a handle to the file
  70. // when it is open, and also caches the size when set.
  71. friend class reader;
  72. friend class writer;
  73. friend struct basic_file_body;
  74. // This represents the open file
  75. File file_;
  76. // The cached file size
  77. std::uint64_t file_size_ = 0;
  78. public:
  79. /** Destructor.
  80. If the file is open, it is closed first.
  81. */
  82. ~value_type() = default;
  83. /// Constructor
  84. value_type() = default;
  85. /// Constructor
  86. value_type(value_type&& other) = default;
  87. /// Move assignment
  88. value_type& operator=(value_type&& other) = default;
  89. /// Returns `true` if the file is open
  90. bool
  91. is_open() const
  92. {
  93. return file_.is_open();
  94. }
  95. /// Returns the size of the file if open
  96. std::uint64_t
  97. size() const
  98. {
  99. return file_size_;
  100. }
  101. /// Close the file if open
  102. void
  103. close();
  104. /** Open a file at the given path with the specified mode
  105. @param path The utf-8 encoded path to the file
  106. @param mode The file mode to use
  107. @param ec Set to the error, if any occurred
  108. */
  109. void
  110. open(char const* path, file_mode mode, error_code& ec);
  111. /** Set the open file
  112. This function is used to set the open file. Any previously
  113. set file will be closed.
  114. @param file The file to set. The file must be open or else
  115. an error occurs
  116. @param ec Set to the error, if any occurred
  117. */
  118. void
  119. reset(File&& file, error_code& ec);
  120. };
  121. template<class File>
  122. void
  123. basic_file_body<File>::
  124. value_type::
  125. close()
  126. {
  127. error_code ignored;
  128. file_.close(ignored);
  129. }
  130. template<class File>
  131. void
  132. basic_file_body<File>::
  133. value_type::
  134. open(char const* path, file_mode mode, error_code& ec)
  135. {
  136. // Open the file
  137. file_.open(path, mode, ec);
  138. if(ec)
  139. return;
  140. // Cache the size
  141. file_size_ = file_.size(ec);
  142. if(ec)
  143. {
  144. close();
  145. return;
  146. }
  147. }
  148. template<class File>
  149. void
  150. basic_file_body<File>::
  151. value_type::
  152. reset(File&& file, error_code& ec)
  153. {
  154. // First close the file if open
  155. if(file_.is_open())
  156. {
  157. error_code ignored;
  158. file_.close(ignored);
  159. }
  160. // Take ownership of the new file
  161. file_ = std::move(file);
  162. // Cache the size
  163. file_size_ = file_.size(ec);
  164. }
  165. // This is called from message::payload_size
  166. template<class File>
  167. std::uint64_t
  168. basic_file_body<File>::
  169. size(value_type const& body)
  170. {
  171. // Forward the call to the body
  172. return body.size();
  173. }
  174. //]
  175. //[example_http_file_body_3
  176. /** Algorithm for retrieving buffers when serializing.
  177. Objects of this type are created during serialization
  178. to extract the buffers representing the body.
  179. */
  180. template<class File>
  181. class basic_file_body<File>::writer
  182. {
  183. value_type& body_; // The body we are reading from
  184. std::uint64_t remain_; // The number of unread bytes
  185. char buf_[4096]; // Small buffer for reading
  186. public:
  187. // The type of buffer sequence returned by `get`.
  188. //
  189. using const_buffers_type =
  190. boost::asio::const_buffer;
  191. // Constructor.
  192. //
  193. // `h` holds the headers of the message we are
  194. // serializing, while `b` holds the body.
  195. //
  196. // Note that the message is passed by non-const reference.
  197. // This is intentional, because reading from the file
  198. // changes its "current position" which counts makes the
  199. // operation logically not-const (although it is bitwise
  200. // const).
  201. //
  202. // The BodyWriter concept allows the writer to choose
  203. // whether to take the message by const reference or
  204. // non-const reference. Depending on the choice, a
  205. // serializer constructed using that body type will
  206. // require the same const or non-const reference to
  207. // construct.
  208. //
  209. // Readers which accept const messages usually allow
  210. // the same body to be serialized by multiple threads
  211. // concurrently, while readers accepting non-const
  212. // messages may only be serialized by one thread at
  213. // a time.
  214. //
  215. template<bool isRequest, class Fields>
  216. writer(header<isRequest, Fields>& h, value_type& b);
  217. // Initializer
  218. //
  219. // This is called before the body is serialized and
  220. // gives the writer a chance to do something that might
  221. // need to return an error code.
  222. //
  223. void
  224. init(error_code& ec);
  225. // This function is called zero or more times to
  226. // retrieve buffers. A return value of `boost::none`
  227. // means there are no more buffers. Otherwise,
  228. // the contained pair will have the next buffer
  229. // to serialize, and a `bool` indicating whether
  230. // or not there may be additional buffers.
  231. boost::optional<std::pair<const_buffers_type, bool>>
  232. get(error_code& ec);
  233. };
  234. //]
  235. //[example_http_file_body_4
  236. // Here we just stash a reference to the path for later.
  237. // Rather than dealing with messy constructor exceptions,
  238. // we save the things that might fail for the call to `init`.
  239. //
  240. template<class File>
  241. template<bool isRequest, class Fields>
  242. basic_file_body<File>::
  243. writer::
  244. writer(header<isRequest, Fields>& h, value_type& b)
  245. : body_(b)
  246. {
  247. boost::ignore_unused(h);
  248. // The file must already be open
  249. BOOST_ASSERT(body_.file_.is_open());
  250. // Get the size of the file
  251. remain_ = body_.file_size_;
  252. }
  253. // Initializer
  254. template<class File>
  255. void
  256. basic_file_body<File>::
  257. writer::
  258. init(error_code& ec)
  259. {
  260. // The error_code specification requires that we
  261. // either set the error to some value, or set it
  262. // to indicate no error.
  263. //
  264. // We don't do anything fancy so set "no error"
  265. ec.assign(0, ec.category());
  266. }
  267. // This function is called repeatedly by the serializer to
  268. // retrieve the buffers representing the body. Our strategy
  269. // is to read into our buffer and return it until we have
  270. // read through the whole file.
  271. //
  272. template<class File>
  273. auto
  274. basic_file_body<File>::
  275. writer::
  276. get(error_code& ec) ->
  277. boost::optional<std::pair<const_buffers_type, bool>>
  278. {
  279. // Calculate the smaller of our buffer size,
  280. // or the amount of unread data in the file.
  281. auto const amount = remain_ > sizeof(buf_) ?
  282. sizeof(buf_) : static_cast<std::size_t>(remain_);
  283. // Handle the case where the file is zero length
  284. if(amount == 0)
  285. {
  286. // Modify the error code to indicate success
  287. // This is required by the error_code specification.
  288. //
  289. // NOTE We use the existing category instead of calling
  290. // into the library to get the generic category because
  291. // that saves us a possibly expensive atomic operation.
  292. //
  293. ec.assign(0, ec.category());
  294. return boost::none;
  295. }
  296. // Now read the next buffer
  297. auto const nread = body_.file_.read(buf_, amount, ec);
  298. if(ec)
  299. return boost::none;
  300. // Make sure there is forward progress
  301. BOOST_ASSERT(nread != 0);
  302. BOOST_ASSERT(nread <= remain_);
  303. // Update the amount remaining based on what we got
  304. remain_ -= nread;
  305. // Return the buffer to the caller.
  306. //
  307. // The second element of the pair indicates whether or
  308. // not there is more data. As long as there is some
  309. // unread bytes, there will be more data. Otherwise,
  310. // we set this bool to `false` so we will not be called
  311. // again.
  312. //
  313. ec.assign(0, ec.category());
  314. return {{
  315. const_buffers_type{buf_, nread}, // buffer to return.
  316. remain_ > 0 // `true` if there are more buffers.
  317. }};
  318. }
  319. //]
  320. //[example_http_file_body_5
  321. /** Algorithm for storing buffers when parsing.
  322. Objects of this type are created during parsing
  323. to store incoming buffers representing the body.
  324. */
  325. template<class File>
  326. class basic_file_body<File>::reader
  327. {
  328. value_type& body_; // The body we are writing to
  329. public:
  330. // Constructor.
  331. //
  332. // This is called after the header is parsed and
  333. // indicates that a non-zero sized body may be present.
  334. // `h` holds the received message headers.
  335. // `b` is an instance of `basic_file_body`.
  336. //
  337. template<bool isRequest, class Fields>
  338. explicit
  339. reader(header<isRequest, Fields>&h, value_type& b);
  340. // Initializer
  341. //
  342. // This is called before the body is parsed and
  343. // gives the reader a chance to do something that might
  344. // need to return an error code. It informs us of
  345. // the payload size (`content_length`) which we can
  346. // optionally use for optimization.
  347. //
  348. void
  349. init(boost::optional<std::uint64_t> const&, error_code& ec);
  350. // This function is called one or more times to store
  351. // buffer sequences corresponding to the incoming body.
  352. //
  353. template<class ConstBufferSequence>
  354. std::size_t
  355. put(ConstBufferSequence const& buffers,
  356. error_code& ec);
  357. // This function is called when writing is complete.
  358. // It is an opportunity to perform any final actions
  359. // which might fail, in order to return an error code.
  360. // Operations that might fail should not be attemped in
  361. // destructors, since an exception thrown from there
  362. // would terminate the program.
  363. //
  364. void
  365. finish(error_code& ec);
  366. };
  367. //]
  368. //[example_http_file_body_6
  369. // We don't do much in the reader constructor since the
  370. // file is already open.
  371. //
  372. template<class File>
  373. template<bool isRequest, class Fields>
  374. basic_file_body<File>::
  375. reader::
  376. reader(header<isRequest, Fields>& h, value_type& body)
  377. : body_(body)
  378. {
  379. boost::ignore_unused(h);
  380. }
  381. template<class File>
  382. void
  383. basic_file_body<File>::
  384. reader::
  385. init(
  386. boost::optional<std::uint64_t> const& content_length,
  387. error_code& ec)
  388. {
  389. // The file must already be open for writing
  390. BOOST_ASSERT(body_.file_.is_open());
  391. // We don't do anything with this but a sophisticated
  392. // application might check available space on the device
  393. // to see if there is enough room to store the body.
  394. boost::ignore_unused(content_length);
  395. // The error_code specification requires that we
  396. // either set the error to some value, or set it
  397. // to indicate no error.
  398. //
  399. // We don't do anything fancy so set "no error"
  400. ec.assign(0, ec.category());
  401. }
  402. // This will get called one or more times with body buffers
  403. //
  404. template<class File>
  405. template<class ConstBufferSequence>
  406. std::size_t
  407. basic_file_body<File>::
  408. reader::
  409. put(ConstBufferSequence const& buffers, error_code& ec)
  410. {
  411. // This function must return the total number of
  412. // bytes transferred from the input buffers.
  413. std::size_t nwritten = 0;
  414. // Loop over all the buffers in the sequence,
  415. // and write each one to the file.
  416. for(auto it = boost::asio::buffer_sequence_begin(buffers);
  417. it != boost::asio::buffer_sequence_end(buffers); ++it)
  418. {
  419. // Write this buffer to the file
  420. boost::asio::const_buffer buffer = *it;
  421. nwritten += body_.file_.write(
  422. buffer.data(), buffer.size(), ec);
  423. if(ec)
  424. return nwritten;
  425. }
  426. // Indicate success
  427. // This is required by the error_code specification
  428. ec.assign(0, ec.category());
  429. return nwritten;
  430. }
  431. // Called after writing is done when there's no error.
  432. template<class File>
  433. void
  434. basic_file_body<File>::
  435. reader::
  436. finish(error_code& ec)
  437. {
  438. // This has to be cleared before returning, to
  439. // indicate no error. The specification requires it.
  440. ec.assign(0, ec.category());
  441. }
  442. //]
  443. #if ! BOOST_BEAST_DOXYGEN
  444. // operator<< is not supported for file_body
  445. template<bool isRequest, class File, class Fields>
  446. std::ostream&
  447. operator<<(std::ostream& os, message<
  448. isRequest, basic_file_body<File>, Fields> const& msg) = delete;
  449. #endif
  450. } // http
  451. } // beast
  452. } // boost
  453. #endif