WebFramework v3.0.12
Web framework for C++.
Loading...
Searching...
No Matches
ProxyServer.cpp
1#include "ProxyServer.h"
2
3#include "JSONArrayWrapper.h"
4#include "HTTPSNetwork.h"
5
6#include "Exceptions/SSLException.h"
7
8using namespace std;
9
10namespace framework
11{
12 namespace proxy
13 {
14 ProxyServer::ProxyData::ProxyData(string_view ip, string_view port, DWORD timeout, bool isHTTPS) :
15 BaseConnectionData(ip, port, timeout),
16 isHTTPS(isHTTPS)
17 {
18
19 }
20
21 void ProxyServer::clientConnection(const string& ip, SOCKET clientSocket, sockaddr addr, function<void()>& cleanup) //-V688
22 {
23 SSL* ssl = nullptr;
24
25 if (useHTTPS)
26 {
27 ssl = SSL_new(context);
28
29 if (!ssl)
30 {
31 throw web::exceptions::SSLException(__LINE__, __FILE__);
32 }
33
34 if (!SSL_set_fd(ssl, static_cast<int>(clientSocket)))
35 {
36 SSL_free(ssl);
37
38 throw web::exceptions::SSLException(__LINE__, __FILE__);
39 }
40
41 if (int errorCode = SSL_accept(ssl); errorCode != 1)
42 {
43 throw web::exceptions::SSLException(__LINE__, __FILE__, ssl, errorCode);
44 }
45 }
46
47 streams::IOSocketStream clientStream
48 (
49 ssl ?
50 make_unique<web::HTTPSNetwork>(clientSocket, ssl, context) :
51 make_unique<web::HTTPNetwork>(clientSocket)
52 );
53
54 string request;
55 string response;
56
57 clientStream >> request;
58
59 web::HTTPParser parser(request);
60
61 string route = parser.getParameters();
62
63 if (route.find('?') != string::npos)
64 {
65 route.resize(route.find('?'));
66 }
67
68 const ProxyData& proxyData = *routes.at(route);
69
70 streams::IOSocketStream serverStream
71 (
72 proxyData.isHTTPS ?
73 make_unique<web::HTTPSNetwork>(proxyData.ip, proxyData.port, proxyData.timeout) :
74 make_unique<web::HTTPNetwork>(proxyData.ip, proxyData.port, proxyData.timeout)
75 );
76
77 serverStream << request;
78
79 serverStream >> response;
80
81 clientStream << response;
82 }
83
84 ProxyServer::ProxyServer(string_view ip, string_view port, DWORD timeout, const json::utility::jsonObject& proxySettings) :
85 BaseTCPServer
86 (
87 port,
88 ip,
89 timeout,
90 true,
91 0,
92 false
93 )
94 {
95 vector<json::utility::jsonObject> servers = json::utility::JSONArrayWrapper(proxySettings.getArray("proxiedServers")).getAsObjectArray();
96
97 proxyData.reserve(servers.size());
98
99 for (const json::utility::jsonObject& proxiedServer : servers)
100 {
101 const string& ip = proxiedServer.getString("ip"); //-V688
102 int64_t port = proxiedServer.getInt("port"); //-V688
103 uint64_t timeout = proxiedServer.getUnsignedInt("timeout"); //-V688
104 bool isHTTPS = proxiedServer.getBool("isHTTPS");
105 vector<string> serverRoutes = json::utility::JSONArrayWrapper(proxiedServer.getArray("routes")).getAsStringArray();
106
107 const ProxyData& data = proxyData.emplace_back(ip, to_string(port), static_cast<DWORD>(timeout), isHTTPS); //-V688
108
109 for (const string& route : serverRoutes)
110 {
111 routes[route] = &data;
112 }
113 }
114 }
115 }
116}