-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_parser.h
More file actions
104 lines (85 loc) · 2.49 KB
/
http_parser.h
File metadata and controls
104 lines (85 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#pragma once
#include <string>
#include <unordered_map>
#include <vector>
#include <optional>
namespace HTTP
{
enum class Method
{
GET,
POST,
PUT,
DELETE_, // DELETE is a reserved keyword, so.
HEAD,
OPTIONS,
PATCH,
CONNECT,
TRACE,
UNKNOWN
};
enum class ParseState
{
REQUEST_LINE,
HEADERS,
BODY,
COMPLETE,
PARSE_ERROR
};
struct Request
{
Method method;
std::string methodStr;
std::string uri;
std::string path;
std::string queryString;
std::string httpVersion;
std::unordered_map<std::string, std::string> headers;
std::vector<char> body;
std::string getHeader(const std::string &name) const;
bool hasHeader(const std::string &name) const;
size_t getContentLength() const;
bool isChunked() const;
bool isKeepAlive() const;
std::string getHost() const;
};
class Parser
{
private:
ParseState state;
std::string buffer;
Request request;
size_t bodyBytesRead;
size_t expectedBodyLength;
std::string errorMessage;
// MAX SIZES FOR HEADERS???
bool parseRequestLine();
bool parseHeaders();
bool parseBody();
Method stringToMethod(const std::string &str);
std::string trim(const std::string &str);
std::string toLower(const std::string &str);
public:
Parser();
void reset();
// feed data to the parser, return true if more data is needed
bool feed(const char *data, size_t len);
// current state of the parser
ParseState getState() const { return state; }
// get the parsed request after state == COMPLETE
const Request &getRequest() const { return request; }
// return error message when state == ERROR
const std::string &getError() const { return errorMessage; }
// check if the request if fully parsed
bool isComplete() const { return state == ParseState::COMPLETE; }
// check for error
bool hasError() const { return state == ParseState::PARSE_ERROR; }
};
// forwarded request with proxy headers
std::string buildForwardedRequest(
const Request &original,
const std::string &clientIP,
bool isTLS);
// error response
std::string buildErrorResponse(int statusCode, const std::string &message);
}