Imported Upstream version 1.72.0
[platform/upstream/boost.git] / boost / beast / http / basic_file_body.hpp
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
10 #ifndef BOOST_BEAST_HTTP_BASIC_FILE_BODY_HPP
11 #define BOOST_BEAST_HTTP_BASIC_FILE_BODY_HPP
12
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>
19 #include <algorithm>
20 #include <cstdio>
21 #include <cstdint>
22 #include <utility>
23
24 namespace boost {
25 namespace beast {
26 namespace http {
27
28 //[example_http_file_body_1
29
30 /** A message body represented by a file on the filesystem.
31
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.
39
40     @tparam File The implementation to use for accessing files.
41     This type must meet the requirements of <em>File</em>.
42 */
43 template<class File>
44 struct basic_file_body
45 {
46     // Make sure the type meets the requirements
47     static_assert(is_file<File>::value,
48         "File type requirements not met");
49
50     /// The type of File this body uses
51     using file_type = File;
52
53     // Algorithm for storing buffers when parsing.
54     class reader;
55
56     // Algorithm for retrieving buffers when serializing.
57     class writer;
58
59     // The type of the @ref message::body member.
60     class value_type;
61
62     /** Returns the size of the body
63
64         @param body The file body to use
65     */
66     static
67     std::uint64_t
68     size(value_type const& body);
69 };
70
71 //]
72
73 //[example_http_file_body_2
74
75 /** The type of the @ref message::body member.
76
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.
81 */
82 template<class File>
83 class basic_file_body<File>::value_type
84 {
85     // This body container holds a handle to the file
86     // when it is open, and also caches the size when set.
87
88     friend class reader;
89     friend class writer;
90     friend struct basic_file_body;
91
92     // This represents the open file
93     File file_;
94
95     // The cached file size
96     std::uint64_t file_size_ = 0;
97
98 public:
99     /** Destructor.
100
101         If the file is open, it is closed first.
102     */
103     ~value_type() = default;
104
105     /// Constructor
106     value_type() = default;
107
108     /// Constructor
109     value_type(value_type&& other) = default;
110
111     /// Move assignment
112     value_type& operator=(value_type&& other) = default;
113
114     /// Returns `true` if the file is open
115     bool
116     is_open() const
117     {
118         return file_.is_open();
119     }
120
121     /// Returns the size of the file if open
122     std::uint64_t
123     size() const
124     {
125         return file_size_;
126     }
127
128     /// Close the file if open
129     void
130     close();
131
132     /** Open a file at the given path with the specified mode
133
134         @param path The utf-8 encoded path to the file
135
136         @param mode The file mode to use
137
138         @param ec Set to the error, if any occurred
139     */
140     void
141     open(char const* path, file_mode mode, error_code& ec);
142
143     /** Set the open file
144
145         This function is used to set the open file. Any previously
146         set file will be closed.
147
148         @param file The file to set. The file must be open or else
149         an error occurs
150
151         @param ec Set to the error, if any occurred
152     */
153     void
154     reset(File&& file, error_code& ec);
155 };
156
157 template<class File>
158 void
159 basic_file_body<File>::
160 value_type::
161 close()
162 {
163     error_code ignored;
164     file_.close(ignored);
165 }
166
167 template<class File>
168 void
169 basic_file_body<File>::
170 value_type::
171 open(char const* path, file_mode mode, error_code& ec)
172 {
173     // Open the file
174     file_.open(path, mode, ec);
175     if(ec)
176         return;
177
178     // Cache the size
179     file_size_ = file_.size(ec);
180     if(ec)
181     {
182         close();
183         return;
184     }
185 }
186
187 template<class File>
188 void
189 basic_file_body<File>::
190 value_type::
191 reset(File&& file, error_code& ec)
192 {
193     // First close the file if open
194     if(file_.is_open())
195     {
196         error_code ignored;
197         file_.close(ignored);
198     }
199
200     // Take ownership of the new file
201     file_ = std::move(file);
202
203     // Cache the size
204     file_size_ = file_.size(ec);
205 }
206
207 // This is called from message::payload_size
208 template<class File>
209 std::uint64_t
210 basic_file_body<File>::
211 size(value_type const& body)
212 {
213     // Forward the call to the body
214     return body.size();
215 }
216
217 //]
218
219 //[example_http_file_body_3
220
221 /** Algorithm for retrieving buffers when serializing.
222
223     Objects of this type are created during serialization
224     to extract the buffers representing the body.
225 */
226 template<class File>
227 class basic_file_body<File>::writer
228 {
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
232
233 public:
234     // The type of buffer sequence returned by `get`.
235     //
236     using const_buffers_type =
237         net::const_buffer;
238
239     // Constructor.
240     //
241     // `h` holds the headers of the message we are
242     // serializing, while `b` holds the body.
243     //
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
248     // const).
249     //
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
255     // construct.
256     //
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
261     // a time.
262     //
263     template<bool isRequest, class Fields>
264     writer(header<isRequest, Fields>& h, value_type& b);
265
266     // Initializer
267     //
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.
271     //
272     void
273     init(error_code& ec);
274
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>>
282     get(error_code& ec);
283 };
284
285 //]
286
287 //[example_http_file_body_4
288
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`.
292 //
293 template<class File>
294 template<bool isRequest, class Fields>
295 basic_file_body<File>::
296 writer::
297 writer(header<isRequest, Fields>& h, value_type& b)
298     : body_(b)
299 {
300     boost::ignore_unused(h);
301
302     // The file must already be open
303     BOOST_ASSERT(body_.file_.is_open());
304
305     // Get the size of the file
306     remain_ = body_.file_size_;
307 }
308
309 // Initializer
310 template<class File>
311 void
312 basic_file_body<File>::
313 writer::
314 init(error_code& ec)
315 {
316     // The error_code specification requires that we
317     // either set the error to some value, or set it
318     // to indicate no error.
319     //
320     // We don't do anything fancy so set "no error"
321     ec = {};
322 }
323
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.
328 //
329 template<class File>
330 auto
331 basic_file_body<File>::
332 writer::
333 get(error_code& ec) ->
334     boost::optional<std::pair<const_buffers_type, bool>>
335 {
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_);
340
341     // Handle the case where the file is zero length
342     if(amount == 0)
343     {
344         // Modify the error code to indicate success
345         // This is required by the error_code specification.
346         //
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.
350         //
351         ec = {};
352         return boost::none;
353     }
354
355     // Now read the next buffer
356     auto const nread = body_.file_.read(buf_, amount, ec);
357     if(ec)
358         return boost::none;
359
360     // Make sure there is forward progress
361     BOOST_ASSERT(nread != 0);
362     BOOST_ASSERT(nread <= remain_);
363
364     // Update the amount remaining based on what we got
365     remain_ -= nread;
366
367     // Return the buffer to the caller.
368     //
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
373     // again.
374     //
375     ec = {};
376     return {{
377         const_buffers_type{buf_, nread},    // buffer to return.
378         remain_ > 0                         // `true` if there are more buffers.
379         }};
380 }
381
382 //]
383
384 //[example_http_file_body_5
385
386 /** Algorithm for storing buffers when parsing.
387
388     Objects of this type are created during parsing
389     to store incoming buffers representing the body.
390 */
391 template<class File>
392 class basic_file_body<File>::reader
393 {
394     value_type& body_;  // The body we are writing to
395
396 public:
397     // Constructor.
398     //
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`.
403     //
404     template<bool isRequest, class Fields>
405     explicit
406     reader(header<isRequest, Fields>&h, value_type& b);
407
408     // Initializer
409     //
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.
415     //
416     void
417     init(boost::optional<std::uint64_t> const&, error_code& ec);
418
419     // This function is called one or more times to store
420     // buffer sequences corresponding to the incoming body.
421     //
422     template<class ConstBufferSequence>
423     std::size_t
424     put(ConstBufferSequence const& buffers,
425         error_code& ec);
426
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.
433     //
434     void
435     finish(error_code& ec);
436 };
437
438 //]
439
440 //[example_http_file_body_6
441
442 // We don't do much in the reader constructor since the
443 // file is already open.
444 //
445 template<class File>
446 template<bool isRequest, class Fields>
447 basic_file_body<File>::
448 reader::
449 reader(header<isRequest, Fields>& h, value_type& body)
450     : body_(body)
451 {
452     boost::ignore_unused(h);
453 }
454
455 template<class File>
456 void
457 basic_file_body<File>::
458 reader::
459 init(
460     boost::optional<std::uint64_t> const& content_length,
461     error_code& ec)
462 {
463     // The file must already be open for writing
464     BOOST_ASSERT(body_.file_.is_open());
465
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);
470
471     // The error_code specification requires that we
472     // either set the error to some value, or set it
473     // to indicate no error.
474     //
475     // We don't do anything fancy so set "no error"
476     ec = {};
477 }
478
479 // This will get called one or more times with body buffers
480 //
481 template<class File>
482 template<class ConstBufferSequence>
483 std::size_t
484 basic_file_body<File>::
485 reader::
486 put(ConstBufferSequence const& buffers, error_code& ec)
487 {
488     // This function must return the total number of
489     // bytes transferred from the input buffers.
490     std::size_t nwritten = 0;
491
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)
496     {
497         // Write this buffer to the file
498         net::const_buffer buffer = *it;
499         nwritten += body_.file_.write(
500             buffer.data(), buffer.size(), ec);
501         if(ec)
502             return nwritten;
503     }
504
505     // Indicate success
506     // This is required by the error_code specification
507     ec = {};
508
509     return nwritten;
510 }
511
512 // Called after writing is done when there's no error.
513 template<class File>
514 void
515 basic_file_body<File>::
516 reader::
517 finish(error_code& ec)
518 {
519     // This has to be cleared before returning, to
520     // indicate no error. The specification requires it.
521     ec = {};
522 }
523
524 //]
525
526 #if ! BOOST_BEAST_DOXYGEN
527 // operator<< is not supported for file_body
528 template<bool isRequest, class File, class Fields>
529 std::ostream&
530 operator<<(std::ostream&, message<
531     isRequest, basic_file_body<File>, Fields> const&) = delete;
532 #endif
533
534 } // http
535 } // beast
536 } // boost
537
538 #endif