TLA Line data Source code
1 : //
2 : // Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
3 : // Copyright (c) 2024 Mohammad Nejati
4 : //
5 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
6 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7 : //
8 : // Official repository: https://github.com/cppalliance/http
9 : //
10 :
11 : #ifndef BOOST_HTTP_PARSER_HPP
12 : #define BOOST_HTTP_PARSER_HPP
13 :
14 : #include <boost/http/config.hpp>
15 : #include <boost/http/detail/header.hpp>
16 : #include <boost/http/detail/type_traits.hpp>
17 : #include <boost/http/error.hpp>
18 :
19 : #include <boost/capy/buffers/buffer_copy.hpp>
20 : #include <boost/capy/concept/read_stream.hpp>
21 : #include <boost/http/concept/write_sink.hpp>
22 : #include <boost/http/io/buffer_param.hpp>
23 : #include <boost/capy/cond.hpp>
24 : #include <boost/capy/error.hpp>
25 : #include <boost/capy/results.hpp>
26 : #include <boost/capy/task.hpp>
27 : #include <boost/core/span.hpp>
28 :
29 : #include <array>
30 : #include <cstddef>
31 : #include <cstdint>
32 : #include <memory>
33 :
34 : namespace boost {
35 : namespace http {
36 :
37 : // Forward declaration
38 : class request_parser;
39 : class response_parser;
40 : class static_request;
41 : class static_response;
42 :
43 : //------------------------------------------------
44 :
45 : /** A parser for HTTP/1 messages.
46 :
47 : This parser uses a single block of memory allocated
48 : during construction and guarantees it will never
49 : exceed the specified size. This space is reused for
50 : parsing multiple HTTP messages ( one at a time ).
51 :
52 : The allocated space is used for:
53 :
54 : @li Buffering raw input from a socket
55 : @li Storing HTTP headers with O(1) access to
56 : method, target, and status code
57 : @li Storing all or part of an HTTP message body
58 : @li Storing state for inflate algorithms
59 :
60 : The parser is strict. Any malformed input according
61 : to the HTTP ABNFs is treated as an unrecoverable
62 : error.
63 :
64 : @see
65 : @ref response_parser,
66 : @ref request_parser.
67 : */
68 : class parser
69 : {
70 : public:
71 : template<capy::ReadStream Stream>
72 : class source;
73 :
74 : /// Buffer type returned from @ref prepare.
75 : using mutable_buffers_type =
76 : boost::span<capy::mutable_buffer const>;
77 :
78 : /// Buffer type returned from @ref pull_body.
79 : using const_buffers_type =
80 : boost::span<capy::const_buffer const>;
81 :
82 : //--------------------------------------------
83 : //
84 : // Observers
85 : //
86 : //--------------------------------------------
87 :
88 : /// Check if a complete header has been parsed.
89 : BOOST_HTTP_DECL
90 : bool
91 : got_header() const noexcept;
92 :
93 : /// Check if a complete message has been parsed.
94 : BOOST_HTTP_DECL
95 : bool
96 : is_complete() const noexcept;
97 :
98 : //--------------------------------------------
99 : //
100 : // Modifiers
101 : //
102 : //--------------------------------------------
103 :
104 : /// Prepare for a new stream.
105 : BOOST_HTTP_DECL
106 : void
107 : reset() noexcept;
108 :
109 : /** Prepare for a new message.
110 :
111 : @par Preconditions
112 : Either this is the first message in the stream,
113 : or the previous message has been fully parsed.
114 : */
115 : BOOST_HTTP_DECL
116 : void
117 : start();
118 :
119 : /** Return a buffer for reading input.
120 :
121 : After writing to the buffer, call @ref commit
122 : with the number of bytes written.
123 :
124 : @par Preconditions
125 : @ref parse returned @ref condition::need_more_input.
126 :
127 : @par Postconditions
128 : A call to @ref commit or @ref commit_eof is
129 : required before calling @ref prepare again.
130 :
131 : @par Exception Safety
132 : Strong guarantee.
133 :
134 : @return A non-empty mutable buffer.
135 :
136 : @see @ref commit, @ref commit_eof.
137 : */
138 : BOOST_HTTP_DECL
139 : mutable_buffers_type
140 : prepare();
141 :
142 : /** Commit bytes to the input buffer.
143 :
144 : @par Preconditions
145 : @li `n <= capy::buffer_size( this->prepare() )`
146 : @li No prior call to @ref commit or @ref commit_eof
147 : since the last @ref prepare
148 :
149 : @par Postconditions
150 : Buffers from @ref prepare are invalidated.
151 :
152 : @par Exception Safety
153 : Strong guarantee.
154 :
155 : @param n The number of bytes written.
156 :
157 : @see @ref parse, @ref prepare.
158 : */
159 : BOOST_HTTP_DECL
160 : void
161 : commit(
162 : std::size_t n);
163 :
164 : /** Indicate end of input.
165 :
166 : Call this when the underlying stream has closed
167 : and no more data will arrive.
168 :
169 : @par Postconditions
170 : Buffers from @ref prepare are invalidated.
171 :
172 : @par Exception Safety
173 : Strong guarantee.
174 :
175 : @see @ref parse, @ref prepare.
176 : */
177 : BOOST_HTTP_DECL
178 : void
179 : commit_eof();
180 :
181 : /** Parse pending input data.
182 :
183 : Returns immediately after the header is fully
184 : parsed to allow @ref set_body_limit to be called
185 : before body parsing begins. If an error occurs
186 : during body parsing, the parsed header remains
187 : valid and accessible.
188 :
189 : When `ec == condition::need_more_input`, read
190 : more data and call @ref commit before calling
191 : this function again.
192 :
193 : When `ec == error::end_of_stream`, the stream
194 : closed cleanly. Call @ref reset to reuse the
195 : parser for a new stream.
196 :
197 : @param ec Set to the error, if any occurred.
198 :
199 : @see @ref start, @ref prepare, @ref commit.
200 : */
201 : BOOST_HTTP_DECL
202 : void
203 : parse(
204 : std::error_code& ec);
205 :
206 : /** Set maximum body size for the current message.
207 :
208 : Overrides @ref parser_config::body_limit for this
209 : message only. The limit resets to the default
210 : for subsequent messages.
211 :
212 : @par Preconditions
213 : `this->got_header() == true` and body parsing
214 : has not started.
215 :
216 : @par Exception Safety
217 : Strong guarantee.
218 :
219 : @param n The body size limit in bytes.
220 :
221 : @see @ref parser_config::body_limit.
222 : */
223 : BOOST_HTTP_DECL
224 : void
225 : set_body_limit(std::uint64_t n);
226 :
227 : /** Return available body data.
228 :
229 : Use this to incrementally process body data.
230 : Call @ref consume_body after processing to
231 : release the buffer space.
232 :
233 : @par Example
234 : @code
235 : request_parser pr( ctx );
236 : pr.start();
237 : co_await pr.read_header( stream );
238 :
239 : while( ! pr.is_complete() )
240 : {
241 : co_await read_some( stream, pr );
242 : auto cbs = pr.pull_body();
243 : // process cbs ...
244 : pr.consume_body( capy::buffer_size( cbs ) );
245 : }
246 : @endcode
247 :
248 : @par Preconditions
249 : `this->got_header() == true`
250 :
251 : @par Postconditions
252 : The returned buffer is invalidated by any
253 : modifying member function.
254 :
255 : @par Exception Safety
256 : Strong guarantee.
257 :
258 : @return Buffers containing available body data.
259 :
260 : @see @ref consume_body.
261 : */
262 : BOOST_HTTP_DECL
263 : const_buffers_type
264 : pull_body();
265 :
266 : /** Consume bytes from available body data.
267 :
268 : @par Preconditions
269 : `n <= capy::buffer_size( this->pull_body() )`
270 :
271 : @par Exception Safety
272 : Strong guarantee.
273 :
274 : @param n The number of bytes to consume.
275 :
276 : @see @ref pull_body.
277 : */
278 : BOOST_HTTP_DECL
279 : void
280 : consume_body(std::size_t n);
281 :
282 : /** Return the complete body.
283 :
284 : Use this when the entire message fits within
285 : the parser's internal buffer.
286 :
287 : @par Example
288 : @code
289 : request_parser pr( ctx );
290 : pr.start();
291 : co_await pr.read_header( stream );
292 : // ... read entire body ...
293 : core::string_view body = pr.body();
294 : @endcode
295 :
296 : @par Preconditions
297 : @li `this->is_complete() == true`
298 : @li No previous call to @ref consume_body
299 :
300 : @par Exception Safety
301 : Strong guarantee.
302 :
303 : @return A string view of the complete body.
304 :
305 : @see @ref is_complete.
306 : */
307 : BOOST_HTTP_DECL
308 : core::string_view
309 : body() const;
310 :
311 : /** Return true if data is buffered past the message.
312 :
313 : After a complete message, returns true when the
314 : parser's buffer still holds octets that lie
315 : beyond it, such as the start of a pipelined
316 : message or data the peer sent past the message
317 : framing. Returns false before the message is
318 : complete.
319 :
320 : This does not include the message body, which is
321 : retrieved separately via @ref body or
322 : @ref pull_body.
323 :
324 : @return true if octets remain buffered past the
325 : completed message.
326 :
327 : @see @ref is_complete, @ref release_buffered_data.
328 : */
329 : BOOST_HTTP_DECL
330 : bool
331 : has_buffered_data() const noexcept;
332 :
333 : /** Return unconsumed data past the last message.
334 :
335 : Use this after an upgrade or CONNECT request
336 : to retrieve protocol-dependent data that
337 : follows the HTTP message.
338 :
339 : @return A string view of leftover data.
340 :
341 : @see @ref metadata::upgrade, @ref metadata::connection.
342 : */
343 : BOOST_HTTP_DECL
344 : core::string_view
345 : release_buffered_data() noexcept;
346 :
347 : /** Asynchronously read the HTTP headers.
348 :
349 : Reads from the stream until the headers are
350 : complete or an error occurs.
351 :
352 : @par Preconditions
353 : @li @ref reset has been called
354 : @li @ref start has been called
355 :
356 : @param stream The stream to read from.
357 :
358 : @return An awaitable yielding `(error_code)`.
359 :
360 : @see @ref read.
361 : */
362 : template<capy::ReadStream Stream>
363 : capy::task<capy::results<>>
364 : read_header(Stream& stream);
365 :
366 : /** Asynchronously read a complete HTTP message.
367 :
368 : Reads from the stream until the message is fully
369 : parsed or an error occurs. The body is accumulated
370 : in the parser's internal buffer and can be retrieved
371 : via @ref body after completion.
372 :
373 : If the parser's internal buffer fills before the
374 : message is complete, the operation completes with
375 : @ref error::in_place_overflow.
376 :
377 : @par Preconditions
378 : @li @ref reset has been called
379 : @li @ref start has been called
380 :
381 : @param stream The stream to read from.
382 :
383 : @return An awaitable yielding `(error_code)`.
384 :
385 : @see @ref body, @ref read_header.
386 : */
387 : template<capy::ReadStream Stream>
388 : capy::task<capy::results<>>
389 : read(Stream& stream);
390 :
391 : /** Asynchronously read body data into buffers.
392 :
393 : Reads from the stream and copies body data into
394 : the provided buffers with complete-fill semantics.
395 : Returns `capy::error::eof` when the body is complete.
396 :
397 : @par Preconditions
398 : @li @ref reset has been called
399 : @li @ref start has been called
400 :
401 : @param stream The stream to read from.
402 :
403 : @param buffers The buffers to read into.
404 :
405 : @return An awaitable yielding `(error_code,std::size_t)`.
406 :
407 : @see @ref read_header.
408 : */
409 : template<capy::ReadStream Stream, capy::MutableBufferSequence MB>
410 : capy::task<capy::results<std::size_t>>
411 : read(Stream& stream, MB buffers);
412 :
413 : /** Return a source for reading body data.
414 :
415 : The returned source satisfies @ref http::BufferSource.
416 : On first pull, headers are automatically parsed if
417 : not yet received.
418 :
419 : @par Example
420 : @code
421 : request_parser pr( ctx );
422 : pr.start();
423 : auto body = pr.source_for( socket );
424 :
425 : capy::const_buffer arr[16];
426 : auto [ec, bufs] = co_await body.pull( arr );
427 : body.consume( buffer_size( bufs ) );
428 : @endcode
429 :
430 : @param stream The stream to read from.
431 :
432 : @return A source satisfying @ref http::BufferSource.
433 :
434 : @see @ref read_header, @ref http::BufferSource.
435 : */
436 : template<capy::ReadStream Stream>
437 : source<Stream>
438 : source_for(Stream& stream) noexcept;
439 :
440 : /** Read body from stream and push to a WriteSink.
441 :
442 : Reads body data from the stream and pushes each chunk to
443 : the sink. The sink must consume all bytes from each write.
444 :
445 : @param stream The stream to read body data from.
446 :
447 : @param sink The sink to receive body data.
448 :
449 : @return An awaitable yielding `(error_code)`.
450 :
451 : @see WriteSink.
452 : */
453 : template<http::WriteSink Sink>
454 : capy::task<capy::results<>>
455 : read(capy::ReadStream auto& stream, Sink&& sink);
456 :
457 : private:
458 : friend class request_parser;
459 : friend class response_parser;
460 : class impl;
461 :
462 : BOOST_HTTP_DECL ~parser();
463 : BOOST_HTTP_DECL parser() noexcept;
464 : BOOST_HTTP_DECL parser(parser&& other) noexcept;
465 : BOOST_HTTP_DECL parser(
466 : std::shared_ptr<parser_config_impl const> cfg,
467 : detail::kind k);
468 : BOOST_HTTP_DECL void assign(parser&& other) noexcept;
469 :
470 : BOOST_HTTP_DECL
471 : void
472 : start_impl(bool);
473 :
474 : static_request const&
475 : safe_get_request() const;
476 :
477 : static_response const&
478 : safe_get_response() const;
479 :
480 : impl* impl_;
481 : };
482 :
483 : /** A source for reading the message body.
484 :
485 : This type satisfies @ref http::BufferSource. It can be
486 : constructed immediately after parser construction; on
487 : first pull, headers are automatically parsed if not
488 : yet received.
489 :
490 : @tparam Stream A type satisfying @ref capy::ReadStream.
491 :
492 : @see @ref parser::source_for.
493 : */
494 : template<capy::ReadStream Stream>
495 : class parser::source
496 : {
497 : Stream* stream_;
498 : parser* pr_;
499 :
500 : public:
501 : /// Default constructor.
502 : source() noexcept
503 : : stream_(nullptr)
504 : , pr_(nullptr)
505 : {
506 : }
507 :
508 : /// Construct a source for reading body data.
509 HIT 355 : source(Stream& stream, parser& pr) noexcept
510 355 : : stream_(&stream)
511 355 : , pr_(&pr)
512 : {
513 355 : }
514 :
515 : /** Pull buffer data from the body.
516 :
517 : On first invocation, reads headers if not yet parsed.
518 : Returns buffer descriptors pointing to internal parser
519 : memory. When the body is complete, returns an empty span.
520 :
521 : @param dest Span of const_buffer to fill.
522 :
523 : @return An awaitable yielding `(error_code,std::span<const_buffer>)`.
524 : */
525 : capy::task<capy::results<std::span<capy::const_buffer>>>
526 : pull(std::span<capy::const_buffer> dest);
527 :
528 : /** Consume bytes from pulled body data.
529 :
530 : Advances the read position by the specified number of
531 : bytes. The next pull returns data starting after the
532 : consumed bytes.
533 :
534 : @param n The number of bytes to consume.
535 : */
536 : void
537 : consume(std::size_t n) noexcept;
538 : };
539 :
540 : template<capy::ReadStream Stream>
541 : capy::task<capy::results<>>
542 749 : parser::
543 : read_header(Stream& stream)
544 : {
545 : std::error_code ec;
546 : for(;;)
547 : {
548 : parse(ec);
549 :
550 : if(got_header())
551 : co_return {};
552 :
553 : if(ec != condition::need_more_input)
554 : co_return {std::error_code(ec)};
555 :
556 : auto mbs = prepare();
557 :
558 : auto [read_ec, n] = co_await stream.read_some(mbs);
559 : if(read_ec == capy::cond::eof)
560 : commit_eof();
561 : else if(!read_ec)
562 : commit(n);
563 : else
564 : co_return {read_ec};
565 : }
566 1498 : }
567 :
568 : template<capy::ReadStream Stream>
569 : capy::task<capy::results<>>
570 274 : parser::
571 : read(Stream& stream)
572 : {
573 : std::error_code ec;
574 : for(;;)
575 : {
576 : parse(ec);
577 :
578 : if(is_complete())
579 : co_return {};
580 :
581 : if(ec && ec != condition::need_more_input)
582 : co_return {std::error_code(ec)};
583 :
584 : if(ec == condition::need_more_input)
585 : {
586 : auto mbs = prepare();
587 :
588 : auto [read_ec, n] = co_await stream.read_some(mbs);
589 : if(read_ec == capy::cond::eof)
590 : commit_eof();
591 : else if(!read_ec)
592 : commit(n);
593 : else
594 : co_return {read_ec};
595 : }
596 : }
597 548 : }
598 :
599 : template<capy::ReadStream Stream, capy::MutableBufferSequence MB>
600 : capy::task<capy::results<std::size_t>>
601 114 : parser::
602 : read(Stream& stream, MB buffers)
603 : {
604 : if(capy::buffers_empty(buffers))
605 : co_return {std::error_code(), 0};
606 :
607 : std::size_t total = 0;
608 : buffer_param dest(buffers);
609 :
610 : for(;;)
611 : {
612 : std::error_code ec;
613 : parse(ec);
614 :
615 : if(got_header())
616 : {
617 : // dest.data() is one window, so drain the body over several copies
618 : for(auto body_data = pull_body();
619 : capy::buffer_size(body_data) > 0;
620 : body_data = pull_body())
621 : {
622 : std::size_t copied = capy::buffer_copy(dest.data(), body_data);
623 : consume_body(copied);
624 : total += copied;
625 : dest.consume(copied);
626 :
627 : if(capy::buffers_empty(dest.data()))
628 : co_return {std::error_code(), total};
629 : }
630 :
631 : if(is_complete())
632 : co_return {capy::error::eof, total};
633 : }
634 :
635 : if(ec == condition::need_more_input)
636 : {
637 : auto mbs = prepare();
638 : auto [read_ec, n] = co_await stream.read_some(mbs);
639 :
640 : if(read_ec == capy::cond::eof)
641 : commit_eof();
642 : else if(!read_ec)
643 : commit(n);
644 : else
645 : co_return {read_ec, total};
646 :
647 : continue;
648 : }
649 :
650 : if(ec)
651 : co_return {ec, total};
652 : }
653 228 : }
654 :
655 : template<capy::ReadStream Stream>
656 : parser::source<Stream>
657 355 : parser::
658 : source_for(Stream& stream) noexcept
659 : {
660 355 : return source<Stream>(stream, *this);
661 : }
662 :
663 : template<capy::ReadStream Stream>
664 : capy::task<capy::results<std::span<capy::const_buffer>>>
665 922 : parser::source<Stream>::
666 : pull(std::span<capy::const_buffer> dest)
667 : {
668 : // Read headers if not yet parsed
669 : if(!pr_->got_header())
670 : {
671 : auto [ec] = co_await pr_->read_header(*stream_);
672 : if(ec)
673 : co_return {ec, {}};
674 : }
675 :
676 : for(;;)
677 : {
678 : std::error_code ec;
679 : pr_->parse(ec);
680 :
681 : auto body_data = pr_->pull_body();
682 : if(capy::buffer_size(body_data) > 0)
683 : {
684 : std::size_t count = (std::min)(body_data.size(), dest.size());
685 : for(std::size_t i = 0; i < count; ++i)
686 : dest[i] = body_data[i];
687 : co_return {std::error_code(), dest.first(count)};
688 : }
689 :
690 : if(pr_->is_complete())
691 : co_return {capy::error::eof, {}};
692 :
693 : if(ec == condition::need_more_input)
694 : {
695 : auto mbs = pr_->prepare();
696 : auto [read_ec, n] = co_await stream_->read_some(mbs);
697 :
698 : if(read_ec == capy::cond::eof)
699 : pr_->commit_eof();
700 : else if(!read_ec)
701 : pr_->commit(n);
702 : else
703 : co_return {read_ec, {}};
704 :
705 : continue;
706 : }
707 :
708 : if(ec)
709 : co_return {ec, {}};
710 : }
711 1844 : }
712 :
713 : template<capy::ReadStream Stream>
714 : void
715 568 : parser::source<Stream>::
716 : consume(std::size_t n) noexcept
717 : {
718 568 : pr_->consume_body(n);
719 568 : }
720 :
721 : template<http::WriteSink Sink>
722 : capy::task<capy::results<>>
723 138 : parser::
724 : read(capy::ReadStream auto& stream, Sink&& sink)
725 : {
726 : for(;;)
727 : {
728 : std::error_code ec;
729 : parse(ec);
730 :
731 : if(got_header())
732 : {
733 : auto body_data = pull_body();
734 : if(capy::buffer_size(body_data) > 0)
735 : {
736 : auto [write_ec, n] = co_await sink.write(body_data);
737 : if(write_ec)
738 : co_return {write_ec};
739 : consume_body(n);
740 : }
741 :
742 : if(is_complete())
743 : {
744 : auto [eof_ec] = co_await sink.write_eof();
745 : co_return {eof_ec};
746 : }
747 : }
748 :
749 : if(ec == condition::need_more_input)
750 : {
751 : auto mbs = prepare();
752 : auto [read_ec, n] = co_await stream.read_some(mbs);
753 :
754 : if(read_ec == capy::cond::eof)
755 : commit_eof();
756 : else if(!read_ec)
757 : commit(n);
758 : else
759 : co_return {read_ec};
760 :
761 : continue;
762 : }
763 :
764 : if(ec)
765 : co_return {std::error_code(ec)};
766 : }
767 276 : }
768 :
769 : } // http
770 : } // boost
771 :
772 : #endif
|