|
| 1 | +#pragma once |
| 2 | +#include "co_future.h" |
| 3 | +#include "read_iterator.h" |
| 4 | +#include "request_data.h" |
| 5 | +#include <optional> |
| 6 | +#include <string> |
| 7 | +#include <string_view> |
| 8 | + |
| 9 | +namespace HTTP { |
| 10 | + |
| 11 | +enum class HttpParseStatus { NeedMoreData, NeedContinue, Complete, Error }; |
| 12 | +enum class RequestReadStatus { Complete, NeedContinue, Closed }; |
| 13 | + |
| 14 | +struct HttpParseResult { |
| 15 | + HttpParseStatus status{HttpParseStatus::NeedMoreData}; |
| 16 | + int errorStatus{0}; |
| 17 | + std::string errorMessage; |
| 18 | +}; |
| 19 | + |
| 20 | +class HttpParserState { |
| 21 | + enum class State { |
| 22 | + StartLine, |
| 23 | + HeaderLine, |
| 24 | + FixedBody, |
| 25 | + ChunkSize, |
| 26 | + ChunkData, |
| 27 | + ChunkDataCrlf, |
| 28 | + TrailerLine, |
| 29 | + Complete, |
| 30 | + Error |
| 31 | + }; |
| 32 | + |
| 33 | + State state_{State::StartLine}; |
| 34 | + RequestData current_; |
| 35 | + std::string line_; |
| 36 | + std::string pending_; |
| 37 | + bool sawCr_{false}; |
| 38 | + bool continueSent_{false}; |
| 39 | + bool waitingForContinue_{false}; |
| 40 | + bool continueCandidate_{false}; |
| 41 | + bool chunkNeedsLf_{false}; |
| 42 | + bool started_{false}; |
| 43 | + bool chunked_{false}; |
| 44 | + bool expectsContinue_{false}; |
| 45 | + bool hostEmpty_{false}; |
| 46 | + bool contentLengthInvalid_{false}; |
| 47 | + bool contentLengthConflict_{false}; |
| 48 | + bool unsupportedTransferEncoding_{false}; |
| 49 | + bool invalidExpect_{false}; |
| 50 | + bool hasContentLength_{false}; |
| 51 | + size_t hostCount_{0}; |
| 52 | + size_t headerBytes_{0}; |
| 53 | + size_t fixedRemaining_{0}; |
| 54 | + size_t chunkRemaining_{0}; |
| 55 | + size_t contentLength_{0}; |
| 56 | + int errorStatus_{0}; |
| 57 | + std::string errorMessage_; |
| 58 | + |
| 59 | + void ResetForNext(); |
| 60 | + size_t ProcessBytes(std::string_view data); |
| 61 | + void SetError(int status, std::string message); |
| 62 | + void CompleteCurrent(); |
| 63 | + void ProcessLine(); |
| 64 | + void AppendLineData(std::string_view data); |
| 65 | + void ProcessLineByte(char ch); |
| 66 | + void FinishHeaders(); |
| 67 | + void TrackHeader(std::string_view name, std::string_view value); |
| 68 | + |
| 69 | +public: |
| 70 | + HttpParserState(); |
| 71 | + void Append(std::string_view data); |
| 72 | + size_t Consume(std::string_view data); |
| 73 | + bool Empty() const; |
| 74 | + void MarkContinueSent(); |
| 75 | + HttpParseResult ParseNext(RequestData &request); |
| 76 | +}; |
| 77 | + |
| 78 | +class HttpRequestParser { |
| 79 | + ReadIterator iterator_; |
| 80 | + HttpParserState state_; |
| 81 | + |
| 82 | +public: |
| 83 | + HttpRequestParser(IOUring &ring, int fd); |
| 84 | + CoFuture<RequestReadStatus> ReadRequest(RequestData &request); |
| 85 | + void MarkContinueSent(); |
| 86 | +}; |
| 87 | + |
| 88 | +} // namespace HTTP |
0 commit comments