-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.cpp
More file actions
81 lines (69 loc) · 1.89 KB
/
utils.cpp
File metadata and controls
81 lines (69 loc) · 1.89 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
#include "utils.h"
std::string getLine(int fd) {
std::string line;
char c;
while (read(fd, &c, 1) > 0) {
line.push_back(c);
if (c == '\n')
break;
}
return line;
}
std::string lower(std::string str) {
for (char &c : str) {
if (c >= 'A' && c <= 'Z')
c += 'a' - 'A';
}
return str;
}
std::size_t from_hexadecimal(std::string str) {
std::size_t r = 0;
for (char c : lower(str)) {
if (c == '\r' or c == '\n')
break;
r = r * 16 + (c <= '9' ? c - '0' : c - 'a');
}
return r;
}
std::string to_10_digit_string(std::size_t size) {
std::stringstream ss;
ss << std::setfill('0') << std::setw(10);
ss << size;
return ss.str();
}
std::string httpRead(int socket) {
std::string content, line;
std::size_t contentLength = 0;
bool chunked = false;
do {
line = getLine(socket);
content += line;
std::size_t colon = line.find(':');
if (colon != line.size()) {
std::string header = line.substr(0, colon);
if (lower(header) == "content-length") {
std::stringstream ss(line.substr(colon + 1));
ss >> contentLength;
} else if (lower(header) == "transfer-encoding") {
chunked = true;
}
}
} while (line != "\n" and line != "\r\n");
if (contentLength > 0) {
line.resize(contentLength);
read(socket, &line[0], contentLength);
content += line;
} else if (chunked) {
while (true) {
line = getLine(socket);
content += line;
contentLength = from_hexadecimal(line);
if (contentLength == 0)
break;
line.resize(contentLength);
read(socket, &line[0], contentLength);
content += line;
}
}
return content;
}