123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143 |
- #include "abstractServer.hpp"
- namespace cpr {
- void AbstractServer::SetUp() {
- Start();
- }
- void AbstractServer::TearDown() {
- Stop();
- }
- void AbstractServer::Start() {
- should_run = true;
- serverThread = std::make_shared<std::thread>(&AbstractServer::Run, this);
- serverThread->detach();
- std::unique_lock<std::mutex> server_lock(server_mutex);
- server_start_cv.wait(server_lock);
- }
- void AbstractServer::Stop() {
- should_run = false;
- std::unique_lock<std::mutex> server_lock(server_mutex);
- server_stop_cv.wait(server_lock);
- }
- static void EventHandler(mg_connection* conn, int event, void* event_data, void* context) {
- switch (event) {
- case MG_EV_READ:
- case MG_EV_WRITE:
-
- break;
- case MG_EV_POLL:
-
- break;
- case MG_EV_CLOSE:
-
- break;
- case MG_EV_ACCEPT:
-
- static_cast<AbstractServer*>(context)->acceptConnection(conn);
- break;
- case MG_EV_CONNECT:
-
- break;
- case MG_EV_HTTP_CHUNK: {
-
- } break;
- case MG_EV_HTTP_MSG: {
- AbstractServer* server = static_cast<AbstractServer*>(context);
- server->OnRequest(conn, static_cast<mg_http_message*>(event_data));
- } break;
- default:
- break;
- }
- }
- void AbstractServer::Run() {
-
- memset(&mgr, 0, sizeof(mg_mgr));
- initServer(&mgr, EventHandler);
-
- server_start_cv.notify_all();
-
- while (should_run) {
-
- mg_mgr_poll(&mgr, 100);
- }
-
- timer_args.clear();
- mg_mgr_free(&mgr);
-
- server_stop_cv.notify_all();
- }
- static const std::string base64_chars =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- "abcdefghijklmnopqrstuvwxyz"
- "0123456789+/";
- std::string AbstractServer::Base64Decode(const std::string& in) {
- std::string out;
- std::vector<int> T(256, -1);
- for (size_t i = 0; i < 64; i++)
- T[base64_chars[i]] = static_cast<int>(i);
- int val = 0;
- int valb = -8;
- for (unsigned char c : in) {
- if (T[c] == -1) {
- break;
- }
- val = (val << 6) + T[c];
- valb += 6;
- if (valb >= 0) {
- out.push_back(char((val >> valb) & 0xFF));
- valb -= 8;
- }
- }
- return out;
- }
- void AbstractServer::SendError(mg_connection* conn, int code, std::string& reason) {
- std::string headers{"Content-Type: text/plain\r\nConnection: close\r\n"};
- mg_http_reply(conn, code, headers.c_str(), reason.c_str());
- }
- bool AbstractServer::IsConnectionActive(mg_mgr* mgr, mg_connection* conn) {
- mg_connection* c{mgr->conns};
- while (c) {
- if (c == conn) {
- return true;
- }
- c = c->next;
- }
- return false;
- }
- uint16_t AbstractServer::GetRemotePort(const mg_connection* conn) {
- return (conn->rem.port >> 8) | (conn->rem.port << 8);
- }
- uint16_t AbstractServer::GetLocalPort(const mg_connection* conn) {
- return (conn->loc.port >> 8) | (conn->loc.port << 8);
- }
- }
|