basic_file_body.hpp 14 KB

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