-
Notifications
You must be signed in to change notification settings - Fork 11
/
Proxy.cpp
72 lines (53 loc) · 2.17 KB
/
Proxy.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
71
72
#include "Proxy.hpp"
#include <map>
#include <iostream>
#include <algorithm>
#include <sstream>
#include "net/HTTP.hpp"
std::vector<std::string> Proxy::modifyableTypes = {"/html", "/css", "/javascript", "/x-javascript"};
Proxy::Proxy(net::TCPSocket &&socket, std::shared_ptr<HTTPTransform> transformations) :
client(std::move(socket)), transformations(transformations) {
}
void Proxy::run() {
try {
std::string host;
for (;;) {
net::HTTP request, response;
request.read(client);
// Client could close connection in the meantime
if (request.getRequestLine().empty())
return;
request.getHeaders()["accept-encoding"] = "identity";
if (host.empty()) {
host = request.getHeaders()["host"];
server.connect(host, "80");
}
transformations->transformRequest(request);
request.write(server);
response.readRequestLine(server);
// Server could close connection in the meantime
if (response.getRequestLine().empty())
return;
response.readHeaders(server);
auto contentTypeIt = response.getHeaders().find("content-type");
if (contentTypeIt != response.getHeaders().end() && std::any_of(modifyableTypes.begin(),
modifyableTypes.end(),
[&contentTypeIt] (std::string type) {return contentTypeIt->second.find(type) != std::string::npos;})) {
response.readContent(server);
transformations->transformResponse(response);
response.fixContentLength();
response.write(client);
} else {
response.writeRequestLine(client);
response.writeHeaders(client);
response.streamContent(server, client);
}
if (response.getHeaders()["connection"] == "close" ||
request.getHeaders()["connection"] == "close" ||
!server.canWrite())
break;
}
} catch (std::runtime_error er) {
std::cerr << er.what() << std::endl;
}
}