-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_parser.cpp
More file actions
475 lines (421 loc) · 14.8 KB
/
http_parser.cpp
File metadata and controls
475 lines (421 loc) · 14.8 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
#include "http_parser.h"
#include <algorithm>
#include <sstream>
#include <cctype>
#include <stdio.h>
#include <iostream>
namespace HTTP
{
std::string Request::getHeader(const std::string &name) const
{
std::string lowerName;
lowerName.reserve(name.size());
for (char c : name)
{
lowerName += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
// we can put the keys as lower case already
for (const auto &pair : headers)
{
std::string lowerKey;
lowerKey.reserve(pair.first.size());
for (char c : pair.first)
{
lowerKey += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
if (lowerKey == lowerName)
{
return pair.second;
}
}
return "";
}
bool Request::hasHeader(const std::string &name) const
{
std::string lowerName;
lowerName.reserve(name.size());
for (char c : name)
{
lowerName += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
// the header could exist and be empty as well
return headers.find(lowerName) != headers.end();
}
size_t Request::getContentLength() const
{
std::string value = getHeader("Content-Length");
if (value.empty())
return 0;
try
{
return std::stoull(value);
}
catch (...)
{
return 0;
}
}
bool Request::isChunked() const
{
std::string te = getHeader("Transfer-Encoding");
std::string lowerName;
for (char c : te)
{
lowerName += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
return lowerName.find("chunked") != std::string::npos;
}
bool Request::isKeepAlive() const
{
std::string connection = getHeader("Connection");
std::string lower;
for (char c : connection)
{
lower += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
// HTTP/1.1 default is keep-alive
if (httpVersion == "HTTP/1.1")
{
return lower != "close";
}
// HTTP/1.0 default is close
return lower == "keep-alive";
}
std::string Request::getHost() const
{
return getHeader("Host");
}
// constructor
Parser::Parser() : state(ParseState::REQUEST_LINE), bodyBytesRead(0), expectedBodyLength(0) {}
void Parser::reset()
{
state = ParseState::REQUEST_LINE;
buffer.clear();
request = Request();
bodyBytesRead = 0;
expectedBodyLength = 0;
errorMessage.clear();
}
std::string Parser::trim(const std::string &str)
{
size_t start = 0;
size_t end = str.size();
while (start < end && std::isspace(static_cast<unsigned char>(str[start])))
{
start++;
}
while (end > start && std::isspace(static_cast<unsigned char>(str[end - 1])))
{
end--;
}
return str.substr(start, end - start);
}
std::string Parser::toLower(const std::string &str)
{
std::string result;
result.reserve(str.size());
for (char c : str)
{
result += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
return result;
}
Method Parser::stringToMethod(const std::string &str)
{
if (str == "GET")
return Method::GET;
if (str == "POST")
return Method::POST;
if (str == "PUT")
return Method::PUT;
if (str == "DELETE")
return Method::DELETE_;
if (str == "HEAD")
return Method::HEAD;
if (str == "OPTIONS")
return Method::OPTIONS;
if (str == "PATCH")
return Method::PATCH;
if (str == "CONNECT")
return Method::CONNECT;
if (str == "TRACE")
return Method::TRACE;
return Method::UNKNOWN;
}
bool Parser::parseRequestLine()
{
size_t lineEnd = buffer.find("\r\n");
std::cout << "DEBUG parseRequestLine: buffer.size()=" << buffer.size() << ", lineEnd=" << lineEnd << std::endl;
if (lineEnd == std::string::npos)
{
// need more data
std::cout << "DEBUG parseRequestLine: No complete line yet, need more data" << std::endl;
return true;
}
std::string line = buffer.substr(0, lineEnd);
std::cout << "DEBUG parseRequestLine: Parsed line=[" << line << "]" << std::endl;
buffer.erase(0, lineEnd + 2);
size_t firstSpace = line.find(' ');
if (firstSpace == std::string::npos)
{
state = ParseState::PARSE_ERROR;
errorMessage = "Invalid request line: missing method";
return false;
}
size_t secondSpace = line.find(' ', firstSpace + 1);
if (secondSpace == std::string::npos)
{
state = ParseState::PARSE_ERROR;
errorMessage = "Invalid request line: missing URI";
return false;
}
request.methodStr = line.substr(0, firstSpace);
request.method = stringToMethod(request.methodStr);
request.uri = line.substr(firstSpace + 1, secondSpace - firstSpace - 1);
request.httpVersion = line.substr(secondSpace + 1);
size_t queryStart = request.uri.find('?');
if (queryStart != std::string::npos)
{
request.path = request.uri.substr(0, queryStart);
request.queryString = request.uri.substr(queryStart + 1);
}
else
{
request.path = request.uri;
request.queryString = "";
}
if (request.httpVersion != "HTTP/1.0" && request.httpVersion != "HTTP/1.1")
{
state = ParseState::PARSE_ERROR;
errorMessage = "Unsupported HTTP version: " + request.httpVersion;
return false;
}
std::cout << "DEBUG parseRequestLine: Transitioning to HEADERS state" << std::endl;
state = ParseState::HEADERS;
return false; // Successfully parsed request line, allow feed loop to continue
}
bool Parser::parseHeaders()
{
while (true)
{
size_t lineEnd = buffer.find("\r\n");
std::cout << "DEBUG parseHeaders: buffer.size()=" << buffer.size() << ", lineEnd=" << lineEnd << std::endl;
if (lineEnd != std::string::npos && lineEnd < 100)
{
std::cout << "DEBUG: First line in buffer: [" << buffer.substr(0, std::min(lineEnd, size_t(100))) << "]" << std::endl;
}
if (lineEnd == std::string::npos)
{
std::cout << "DEBUG: No complete line yet, need more data" << std::endl;
return true;
}
// the headers end with \r\n\r\n, so if the first CRLF is in the beginning, we are done with the headers.
if (lineEnd == 0)
{
std::cout << "DEBUG parseHeaders: Found blank line (end of headers)" << std::endl;
buffer.erase(0, 2);
// check for the body
expectedBodyLength = request.getContentLength();
std::cout << "DEBUG parseHeaders: expectedBodyLength=" << expectedBodyLength << ", isChunked=" << request.isChunked() << std::endl;
if (request.isChunked())
{
// TO be implemented , right now just treating as no body
std::cout << "DEBUG parseHeaders: Transitioning to COMPLETE (chunked)" << std::endl;
state = ParseState::COMPLETE;
return false;
}
else if (expectedBodyLength > 0)
{
std::cout << "DEBUG parseHeaders: Transitioning to BODY state" << std::endl;
state = ParseState::BODY;
request.body.reserve(expectedBodyLength);
return true;
}
else
{
// No body
std::cout << "DEBUG parseHeaders: Transitioning to COMPLETE (no body)" << std::endl;
state = ParseState::COMPLETE;
return false;
}
}
std::string line = buffer.substr(0, lineEnd);
std::cout << "DEBUG parseHeaders: Parsing header line=[" << line << "]" << std::endl;
buffer.erase(0, lineEnd + 2);
size_t colonPos = line.find(':');
if (colonPos == std::string::npos)
{
state = ParseState::PARSE_ERROR;
errorMessage = "Invalid header line: missing colon";
return false;
}
std::string name = trim(line.substr(0, colonPos));
std::string value = trim(line.substr(colonPos + 1));
std::cout << "DEBUG parseHeaders: Header name=[" << name << "], value=[" << value << "]" << std::endl;
if (name.empty())
{
state = ParseState::PARSE_ERROR;
errorMessage = "Invalid header: empty name";
return false;
}
request.headers[name] = value;
}
}
bool Parser::parseBody()
{
size_t bytesNeeded = expectedBodyLength - bodyBytesRead;
size_t bytesAvailable = buffer.size();
size_t bytesToCopy = std::min(bytesNeeded, bytesAvailable);
if (bytesToCopy > 0)
{
request.body.insert(
request.body.end(),
buffer.begin(),
buffer.begin() + bytesToCopy);
buffer.erase(0, bytesToCopy);
bodyBytesRead += bytesToCopy;
}
if (bodyBytesRead >= expectedBodyLength)
{
state = ParseState::COMPLETE;
return false;
}
// incomplete, we need more data
return true;
}
bool Parser::feed(const char *data, size_t len)
{
std::cout << "DEBUG feed(): state=" << (int)state << ", data_len=" << len << ", buffer_size_before=" << buffer.size() << std::endl;
if (state == ParseState::COMPLETE || state == ParseState::PARSE_ERROR)
{
std::cout << "DEBUG feed(): Already complete or error, returning false" << std::endl;
return false;
}
buffer.append(data, len);
std::cout << "DEBUG feed(): buffer_size_after=" << buffer.size() << std::endl;
constexpr size_t MAX_BUFFER_SIZE = 1024 * 1024;
if (buffer.size() > MAX_BUFFER_SIZE)
{
state = ParseState::PARSE_ERROR;
errorMessage = "Request too large";
return false;
}
while (true)
{
bool needMoreData = false;
switch (state)
{
case ParseState::REQUEST_LINE:
needMoreData = parseRequestLine();
break;
case ParseState::HEADERS:
needMoreData = parseHeaders();
break;
case ParseState::BODY:
needMoreData = parseBody();
break;
case ParseState::COMPLETE:
case ParseState::PARSE_ERROR:
return false;
}
if (needMoreData || state == ParseState::COMPLETE)
{
std::cout << "DEBUG feed(): Final state=" << (int)state << ", returning needMoreData=" << needMoreData << std::endl;
return needMoreData;
}
}
}
std::string buildForwardedRequest(const Request &original, const std::string &clientIP, bool isTLS)
{
std::ostringstream oss;
oss << original.methodStr << " " << original.uri << " " << original.httpVersion << "\r\n";
bool hasXForwardedFor = false;
bool hasXForwardedProto = false;
bool hasXRealIP = false;
for (const auto &header : original.headers)
{
std::string lowerName = header.first;
for (char &c : lowerName)
{
c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
if (lowerName == "x-forwarded-for")
{
oss << header.first << ": " << header.second << ", " << clientIP << "\r\n";
hasXForwardedFor = true;
}
else if (lowerName == "x-forwarded-proto")
{
hasXForwardedProto = true;
oss << header.first << ": " << header.second << "\r\n";
}
else if (lowerName == "x-real-ip")
{
hasXRealIP = true;
oss << header.first << ": " << header.second << "\r\n";
}
else if (lowerName == "connection")
{
oss << header.first << ": " << header.second << "\r\n";
}
else
{
oss << header.first << ": " << header.second << "\r\n";
}
}
if (!hasXForwardedFor)
{
oss << "X-Forwarded-For: " << clientIP << "\r\n";
}
if (!hasXForwardedProto)
{
oss << "X-Forwarded-Proto: " << (isTLS ? "https" : "http") << "\r\n";
}
if (!hasXRealIP)
{
oss << "X-Real-IP: " << clientIP << "\r\n";
}
return oss.str();
}
std::string buildErrorResponse(int statusCode, const std::string &message)
{
std::string statusText;
switch (statusCode)
{
case 400:
statusText = "Bad Request";
break;
case 404:
statusText = "Not Found";
break;
case 500:
statusText = "Internal Server Error";
break;
case 502:
statusText = "Bad Gateway";
break;
case 503:
statusText = "Service Unavailable";
break;
case 504:
statusText = "Gateway Timeout";
break;
default:
statusText = "Error";
break;
}
std::ostringstream body;
body << "<html><head><title>" << statusCode << " " << statusText << "</title></head>";
body << "<body><h1>" << statusCode << " " << statusText << "</h1>";
body << "<p>" << message << "</p></body></html>";
std::string bodyStr = body.str();
std::ostringstream response;
response << "HTTP/1.1 " << statusCode << " " << statusText << "\r\n";
response << "Content-Type: text/html\r\n";
response << "Content-Length: " << bodyStr.size() << "\r\n";
response << "Connection: close\r\n";
response << "\r\n";
response << bodyStr;
return response.str();
}
}