-
Notifications
You must be signed in to change notification settings - Fork 0
/
FlowHttp3.h
101 lines (87 loc) · 3.68 KB
/
FlowHttp3.h
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
#pragma once
#include "FlowAsio.h"
#include <FlowUtils/ThreadPool.h>
#include "routes/Router.h"
#include <memory>
#include <FlowUtils/Semaphore.h>
#include <set>
class FlowHttp3 {
public:
FlowHttp3(const std::string &address, const std::string &port, Router router,
size_t threads = std::thread::hardware_concurrency(),
const std::string &dh = "", const std::string &key = "", const std::string &cert = "") :
threadPool(threads),
router(std::move(router)) {
boost::asio::ip::tcp::resolver::query query(address, port);
boost::asio::ip::tcp::resolver resolver(io_context);
const auto resolverResult = resolver.resolve(query);
acceptor = std::make_unique<boost::asio::ip::tcp::acceptor>(io_context, resolverResult.begin()->endpoint());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
if (!dh.empty() && !key.empty() && !cert.empty()) {
useSSL = true;
ssl_context = std::make_unique<boost::asio::ssl::context>(boost::asio::ssl::context::sslv23_server);
ssl_context->set_options(
boost::asio::ssl::context::default_workarounds
| boost::asio::ssl::context::no_sslv2);
ssl_context->use_certificate_chain_file(cert);
ssl_context->use_private_key_file(key,
boost::asio::ssl::context::pem);
ssl_context->use_tmp_dh_file(dh);
}
}
void Stop() {
io_context.stop();
}
void Start() {
acceptor->async_accept([&](
const boost::system::error_code &error, boost::asio::ip::tcp::socket socket) {
if (error) {
return;
}
Start();
Socket iSocket(std::move(socket));
threadPool.addFunction(std::make_shared<std::function<void()>>(
[&, iSocket]() mutable { // Threadfunction
if (useSSL) {
boost::system::error_code error;
iSocket.SetSSL(*ssl_context);
iSocket.GetSSLSocket()->handshake(boost::asio::ssl::stream_base::server, error);
if (error) {
LOG_WARNING << "Bad Request";
return;
}
}
bool continue_connection = true;
while (continue_connection) {
continue_connection = false;
++threadPool.threadLimit;
Request request = FlowAsio::readRequest(iSocket);
--threadPool.threadLimit;
Response response(iSocket.IsSSL());
router.execRoute(request, response, iSocket);
if (response.StatusCode == HttpStatusCode::BadRequest) {
break;
}
if (request.Header("Connection") == "keep-alive") {
continue_connection = true;
}
}
})); // Threadfunction
threadPool.start();
});
}
void Run() {
Start();
Join();
}
void Join() {
io_context.run();
}
private:
boost::asio::io_context io_context;
std::unique_ptr<boost::asio::ssl::context> ssl_context;
std::unique_ptr<boost::asio::ip::tcp::acceptor> acceptor;
Router router;
ThreadPool threadPool;
bool useSSL = false;
};