-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.cpp
70 lines (65 loc) · 2.84 KB
/
utils.cpp
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
#include "utils.h"
#include <iostream>
#include "picohttpparser/picohttpparser.h"
RequestParseStatus httpParseRequest(std::string &req, RequestInfo* info) {
const char* path;
const char* method;
int pret, minor_version;
struct phr_header headers[100];
size_t prevbuflen = 0, method_len, path_len, num_headers;
num_headers = sizeof(headers) / sizeof(headers[0]);
pret = phr_parse_request(req.c_str(), req.size(), &method, &method_len, &path, &path_len,
&minor_version, headers, &num_headers, prevbuflen);
if (pret == -1)
return REQ_ERROR;
if (pret == -2)
return REQ_NOT_FULL;
info->method = method;
info->method.erase(info->method.begin() + method_len, info->method.end());
info->path = path;
info->path.erase(info->path.begin() + path_len, info->path.end());
for (int i = 0; i != num_headers; ++i) {
std::string headerName = headers[i].name;
headerName.erase(headerName.begin() + headers[i].name_len, headerName.end());
if (headerName != "Connection") {
info->otherHeaders[headerName] = headers[i].value;
info->otherHeaders[headerName].erase(info->otherHeaders[headerName].begin() + headers[i].value_len,
info->otherHeaders[headerName].end());
}
if (headerName == "Host")
info->host = info->otherHeaders[headerName];
}
req = info->method + " " + info->path + " " + "HTTP/1.0\r\n";
for (std::map<std::string, std::string>::iterator it = info->otherHeaders.begin();
it != info->otherHeaders.end(); ++it) {
req += it->first;
req += ": ";
req += it->second;
req += "\r\n";
}
req += "\r\n";
return REQ_OK;
}
ResponseParseStatus httpParseResponse(const char* response, size_t responseLen, RequestInfo* info) {
const char* message;
int pret, minor_version, status;
struct phr_header headers[100];
size_t prevbuflen = 0, message_len, num_headers;
num_headers = sizeof(headers) / sizeof(headers[0]);
pret = phr_parse_response(response, responseLen, &minor_version, &status, &message, &message_len,
headers, &num_headers, prevbuflen);
if (pret == -1 or minor_version < 0)
return Error;
std::cout << "VERSION " << minor_version << " STATUS " << status << std::endl;
if (NULL != info) {
for (int i = 0; i != num_headers; ++i) {
std::string headerName = headers[i].name;
headerName.erase(headerName.begin() + headers[i].name_len, headerName.end());
if (headerName == "Content-Length") {
info->host = headers[i].value;
info->host.erase(info->host.begin() + headers[i].value_len, info->host.end());
}
}
}
return (status == 200) ? OK : NoCache;
}