2 // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
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)
7 // Official repository: https://github.com/boostorg/beast
10 #ifndef BOOST_BEAST_HTTP_BASIC_FILE_BODY_HPP
11 #define BOOST_BEAST_HTTP_BASIC_FILE_BODY_HPP
13 #include <boost/beast/core/detail/config.hpp>
14 #include <boost/beast/core/error.hpp>
15 #include <boost/beast/core/file_base.hpp>
16 #include <boost/beast/http/message.hpp>
17 #include <boost/assert.hpp>
18 #include <boost/optional.hpp>
28 //[example_http_file_body_1
30 /** A message body represented by a file on the filesystem.
32 Messages with this type have bodies represented by a
33 file on the file system. When parsing a message using
34 this body type, the data is stored in the file pointed
35 to by the path, which must be writable. When serializing,
36 the implementation will read the file and present those
37 octets as the body content. This may be used to serve
38 content from a directory as part of a web service.
40 @tparam File The implementation to use for accessing files.
41 This type must meet the requirements of <em>File</em>.
44 struct basic_file_body
46 // Make sure the type meets the requirements
47 static_assert(is_file<File>::value,
48 "File type requirements not met");
50 /// The type of File this body uses
51 using file_type = File;
53 // Algorithm for storing buffers when parsing.
56 // Algorithm for retrieving buffers when serializing.
59 // The type of the @ref message::body member.
62 /** Returns the size of the body
64 @param body The file body to use
68 size(value_type const& body);
73 //[example_http_file_body_2
75 /** The type of the @ref message::body member.
77 Messages declared using `basic_file_body` will have this type for
78 the body member. This rich class interface allow the file to be
79 opened with the file handle maintained directly in the object,
80 which is attached to the message.
83 class basic_file_body<File>::value_type
85 // This body container holds a handle to the file
86 // when it is open, and also caches the size when set.
90 friend struct basic_file_body;
92 // This represents the open file
95 // The cached file size
96 std::uint64_t file_size_ = 0;
101 If the file is open, it is closed first.
103 ~value_type() = default;
106 value_type() = default;
109 value_type(value_type&& other) = default;
112 value_type& operator=(value_type&& other) = default;
114 /// Returns `true` if the file is open
118 return file_.is_open();
121 /// Returns the size of the file if open
128 /// Close the file if open
132 /** Open a file at the given path with the specified mode
134 @param path The utf-8 encoded path to the file
136 @param mode The file mode to use
138 @param ec Set to the error, if any occurred
141 open(char const* path, file_mode mode, error_code& ec);
143 /** Set the open file
145 This function is used to set the open file. Any previously
146 set file will be closed.
148 @param file The file to set. The file must be open or else
151 @param ec Set to the error, if any occurred
154 reset(File&& file, error_code& ec);
159 basic_file_body<File>::
164 file_.close(ignored);
169 basic_file_body<File>::
171 open(char const* path, file_mode mode, error_code& ec)
174 file_.open(path, mode, ec);
179 file_size_ = file_.size(ec);
189 basic_file_body<File>::
191 reset(File&& file, error_code& ec)
193 // First close the file if open
197 file_.close(ignored);
200 // Take ownership of the new file
201 file_ = std::move(file);
204 file_size_ = file_.size(ec);
207 // This is called from message::payload_size
210 basic_file_body<File>::
211 size(value_type const& body)
213 // Forward the call to the body
219 //[example_http_file_body_3
221 /** Algorithm for retrieving buffers when serializing.
223 Objects of this type are created during serialization
224 to extract the buffers representing the body.
227 class basic_file_body<File>::writer
229 value_type& body_; // The body we are reading from
230 std::uint64_t remain_; // The number of unread bytes
231 char buf_[4096]; // Small buffer for reading
234 // The type of buffer sequence returned by `get`.
236 using const_buffers_type =
241 // `h` holds the headers of the message we are
242 // serializing, while `b` holds the body.
244 // Note that the message is passed by non-const reference.
245 // This is intentional, because reading from the file
246 // changes its "current position" which counts makes the
247 // operation logically not-const (although it is bitwise
250 // The BodyWriter concept allows the writer to choose
251 // whether to take the message by const reference or
252 // non-const reference. Depending on the choice, a
253 // serializer constructed using that body type will
254 // require the same const or non-const reference to
257 // Readers which accept const messages usually allow
258 // the same body to be serialized by multiple threads
259 // concurrently, while readers accepting non-const
260 // messages may only be serialized by one thread at
263 template<bool isRequest, class Fields>
264 writer(header<isRequest, Fields>& h, value_type& b);
268 // This is called before the body is serialized and
269 // gives the writer a chance to do something that might
270 // need to return an error code.
273 init(error_code& ec);
275 // This function is called zero or more times to
276 // retrieve buffers. A return value of `boost::none`
277 // means there are no more buffers. Otherwise,
278 // the contained pair will have the next buffer
279 // to serialize, and a `bool` indicating whether
280 // or not there may be additional buffers.
281 boost::optional<std::pair<const_buffers_type, bool>>
287 //[example_http_file_body_4
289 // Here we just stash a reference to the path for later.
290 // Rather than dealing with messy constructor exceptions,
291 // we save the things that might fail for the call to `init`.
294 template<bool isRequest, class Fields>
295 basic_file_body<File>::
297 writer(header<isRequest, Fields>& h, value_type& b)
300 boost::ignore_unused(h);
302 // The file must already be open
303 BOOST_ASSERT(body_.file_.is_open());
305 // Get the size of the file
306 remain_ = body_.file_size_;
312 basic_file_body<File>::
316 // The error_code specification requires that we
317 // either set the error to some value, or set it
318 // to indicate no error.
320 // We don't do anything fancy so set "no error"
324 // This function is called repeatedly by the serializer to
325 // retrieve the buffers representing the body. Our strategy
326 // is to read into our buffer and return it until we have
327 // read through the whole file.
331 basic_file_body<File>::
333 get(error_code& ec) ->
334 boost::optional<std::pair<const_buffers_type, bool>>
336 // Calculate the smaller of our buffer size,
337 // or the amount of unread data in the file.
338 auto const amount = remain_ > sizeof(buf_) ?
339 sizeof(buf_) : static_cast<std::size_t>(remain_);
341 // Handle the case where the file is zero length
344 // Modify the error code to indicate success
345 // This is required by the error_code specification.
347 // NOTE We use the existing category instead of calling
348 // into the library to get the generic category because
349 // that saves us a possibly expensive atomic operation.
355 // Now read the next buffer
356 auto const nread = body_.file_.read(buf_, amount, ec);
360 // Make sure there is forward progress
361 BOOST_ASSERT(nread != 0);
362 BOOST_ASSERT(nread <= remain_);
364 // Update the amount remaining based on what we got
367 // Return the buffer to the caller.
369 // The second element of the pair indicates whether or
370 // not there is more data. As long as there is some
371 // unread bytes, there will be more data. Otherwise,
372 // we set this bool to `false` so we will not be called
377 const_buffers_type{buf_, nread}, // buffer to return.
378 remain_ > 0 // `true` if there are more buffers.
384 //[example_http_file_body_5
386 /** Algorithm for storing buffers when parsing.
388 Objects of this type are created during parsing
389 to store incoming buffers representing the body.
392 class basic_file_body<File>::reader
394 value_type& body_; // The body we are writing to
399 // This is called after the header is parsed and
400 // indicates that a non-zero sized body may be present.
401 // `h` holds the received message headers.
402 // `b` is an instance of `basic_file_body`.
404 template<bool isRequest, class Fields>
406 reader(header<isRequest, Fields>&h, value_type& b);
410 // This is called before the body is parsed and
411 // gives the reader a chance to do something that might
412 // need to return an error code. It informs us of
413 // the payload size (`content_length`) which we can
414 // optionally use for optimization.
417 init(boost::optional<std::uint64_t> const&, error_code& ec);
419 // This function is called one or more times to store
420 // buffer sequences corresponding to the incoming body.
422 template<class ConstBufferSequence>
424 put(ConstBufferSequence const& buffers,
427 // This function is called when writing is complete.
428 // It is an opportunity to perform any final actions
429 // which might fail, in order to return an error code.
430 // Operations that might fail should not be attempted in
431 // destructors, since an exception thrown from there
432 // would terminate the program.
435 finish(error_code& ec);
440 //[example_http_file_body_6
442 // We don't do much in the reader constructor since the
443 // file is already open.
446 template<bool isRequest, class Fields>
447 basic_file_body<File>::
449 reader(header<isRequest, Fields>& h, value_type& body)
452 boost::ignore_unused(h);
457 basic_file_body<File>::
460 boost::optional<std::uint64_t> const& content_length,
463 // The file must already be open for writing
464 BOOST_ASSERT(body_.file_.is_open());
466 // We don't do anything with this but a sophisticated
467 // application might check available space on the device
468 // to see if there is enough room to store the body.
469 boost::ignore_unused(content_length);
471 // The error_code specification requires that we
472 // either set the error to some value, or set it
473 // to indicate no error.
475 // We don't do anything fancy so set "no error"
479 // This will get called one or more times with body buffers
482 template<class ConstBufferSequence>
484 basic_file_body<File>::
486 put(ConstBufferSequence const& buffers, error_code& ec)
488 // This function must return the total number of
489 // bytes transferred from the input buffers.
490 std::size_t nwritten = 0;
492 // Loop over all the buffers in the sequence,
493 // and write each one to the file.
494 for(auto it = net::buffer_sequence_begin(buffers);
495 it != net::buffer_sequence_end(buffers); ++it)
497 // Write this buffer to the file
498 net::const_buffer buffer = *it;
499 nwritten += body_.file_.write(
500 buffer.data(), buffer.size(), ec);
506 // This is required by the error_code specification
512 // Called after writing is done when there's no error.
515 basic_file_body<File>::
517 finish(error_code& ec)
519 // This has to be cleared before returning, to
520 // indicate no error. The specification requires it.
526 #if ! BOOST_BEAST_DOXYGEN
527 // operator<< is not supported for file_body
528 template<bool isRequest, class File, class Fields>
530 operator<<(std::ostream&, message<
531 isRequest, basic_file_body<File>, Fields> const&) = delete;