asio_webserver to asio_web refactorings

This commit is contained in:
feedc0de committed 2022-07-05 13:07:36 +02:00
1 parent f12c21b41b
commit fdf6e38b14
28 files changed
+43 -42

No files matched your search

+329
View File
@@ -0,0 +1,329 @@
#include "clientconnection.h"
// system includes
#include <cstdio>
#include <utility>
// esp-idf includes
#include <esp_log.h>
// 3rdparty lib includes
#include <numberparsing.h>
#include <strutils.h>
// local includes
#include "webserver.h"
#include "responsehandler.h"
#include "websocketclientconnection.h"
namespace {
constexpr const char * const TAG = "ASIO_WEBSERVER";
} // namespace
ClientConnection::ClientConnection(Webserver &webserver, asio::ip::tcp::socket socket) :
m_webserver{webserver},
m_socket{std::move(socket)},
m_remote_endpoint{m_socket.remote_endpoint()}
{
ESP_LOGI(TAG, "new client (%s:%hi)",
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
m_webserver.m_httpClients++;
}
ClientConnection::~ClientConnection()
{
ESP_LOGI(TAG, "client destroyed (%s:%hi)",
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
m_webserver.m_httpClients--;
}
void ClientConnection::start()
{
doRead();
}
void ClientConnection::responseFinished(std::error_code ec)
{
if (ec)
{
ESP_LOGW(TAG, "error: %i (%s:%hi)", ec.value(),
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
m_socket.close();
return;
}
if (m_webserver.connectionKeepAlive())
{
// ESP_LOGD(TAG, "state changed to RequestLine");
m_state = State::RequestLine;
doRead();
}
else
m_socket.close();
}
void ClientConnection::upgradeWebsocket()
{
// ESP_LOGD(TAG, "state changed to RequestLine");
m_state = State::WebSocket;
std::make_shared<WebsocketClientConnection>(m_webserver, std::move(m_socket), std::move(m_responseHandler))->start();
}
void ClientConnection::doRead()
{
m_socket.async_read_some(asio::buffer(m_receiveBuffer, max_length),
[this, self=shared_from_this()](std::error_code ec, std::size_t length)
{ readyRead(ec, length); });
}
void ClientConnection::readyRead(std::error_code ec, std::size_t length)
{
if (ec)
{
ESP_LOGI(TAG, "error: %i (%s:%hi)", ec.value(),
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
return;
}
if (m_state == State::RequestBody)
{
if (!m_responseHandler)
{
ESP_LOGW(TAG, "invalid response handler (%s:%hi)",
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
m_socket.close();
return;
}
if (!m_requestBodySize)
goto requestFinished;
else
{
if (length <= m_requestBodySize)
{
m_responseHandler->requestBodyReceived({m_receiveBuffer, length});
m_requestBodySize -= length;
length = 0;
if (!m_requestBodySize)
goto requestFinished;
}
else
{
m_responseHandler->requestBodyReceived({m_receiveBuffer, m_requestBodySize});
// TODO how to erase from m_receiveBuffer ?
m_requestBodySize = 0;
goto requestFinished;
}
requestFinished:
// ESP_LOGV(TAG, "state changed to Response");
m_state = State::Response;
m_responseHandler->sendResponse();
}
}
// ESP_LOGV(TAG, "received: %zd \"%.*s\"", length, length, m_receiveBuffer);
m_parsingBuffer.append(m_receiveBuffer, length);
bool shouldDoRead{true};
while (true)
{
constexpr std::string_view newLine{"\r\n"};
const auto index = m_parsingBuffer.find(newLine.data(), 0, newLine.size());
if (index == std::string::npos)
break;
std::string line{m_parsingBuffer.data(), index};
// ESP_LOGD(TAG, "line: %zd \"%.*s\"", line.size(), line.size(), line.data());
m_parsingBuffer.erase(std::begin(m_parsingBuffer), std::next(std::begin(m_parsingBuffer), line.size() + newLine.size()));
if (!readyReadLine(line))
shouldDoRead = false;
}
if (shouldDoRead)
doRead();
}
bool ClientConnection::readyReadLine(std::string_view line)
{
switch (m_state)
{
case State::RequestLine:
// ESP_LOGV(TAG, "case State::RequestLine:");
return parseRequestLine(line);
case State::RequestHeaders:
// ESP_LOGV(TAG, "case State::RequestHeaders:");
return parseRequestHeader(line);
case State::RequestBody:
// ESP_LOGV(TAG, "case State::RequestBody:");
ESP_LOGW(TAG, "unexpected state=RequestBody (%s:%hi)",
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
return true;
case State::Response:
// ESP_LOGV(TAG, "case State::Response:");
ESP_LOGW(TAG, "unexpected state=Response (%s:%hi)",
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
return true;
default:
ESP_LOGW(TAG, "unknown state %i (%s:%hi)", std::to_underlying(m_state),
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
return true;
}
}
bool ClientConnection::parseRequestLine(std::string_view line)
{
// ESP_LOGV(TAG, "%.*s", line.size(), line.data());
if (const auto index = line.find(' '); index == std::string::npos)
{
ESP_LOGW(TAG, "invalid request line (1): \"%.*s\" (%s:%hi)", line.size(), line.data(),
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
m_socket.close();
return false;
}
else
{
const std::string_view method { line.data(), index };
// ESP_LOGV(TAG, "request method: %zd \"%.*s\"", method.size(), method.size(), method.data());
if (const auto index2 = line.find(' ', index + 1); index2 == std::string::npos)
{
ESP_LOGW(TAG, "invalid request line (2): \"%.*s\" (%s:%hi)", line.size(), line.data(),
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
m_socket.close();
return false;
}
else
{
const std::string_view path { line.data() + index + 1, line.data() + index2 };
// ESP_LOGV(TAG, "request path: %zd \"%.*s\"", path.size(), path.size(), path.data());
const std::string_view protocol { line.cbegin() + index2 + 1, line.cend() };
// ESP_LOGV(TAG, "request protocol: %zd \"%.*s\"", protocol.size(), protocol.size(), protocol.data());
m_responseHandler = m_webserver.makeResponseHandler(*this, method, path, protocol);
if (!m_responseHandler)
{
ESP_LOGW(TAG, "invalid response handler method=\"%.*s\" path=\"%.*s\" protocol=\"%.*s\" (%s:%hi)",
method.size(), method.data(), path.size(), path.data(), protocol.size(), protocol.data(),
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
m_socket.close();
return false;
}
// ESP_LOGV(TAG, "state changed to RequestHeaders");
m_state = State::RequestHeaders;
return true;
}
}
}
bool ClientConnection::parseRequestHeader(std::string_view line)
{
// ESP_LOGV(TAG, "%.*s", line.size(), line.data());
if (!line.empty())
{
constexpr std::string_view sep{": "};
if (const auto index = line.find(sep.data(), 0, sep.size()); index == std::string_view::npos)
{
ESP_LOGW(TAG, "invalid request header: %zd \"%.*s\" (%s:%hi)", line.size(), line.size(), line.data(),
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
m_socket.close();
return false;
}
else
{
std::string_view key{line.data(), index};
std::string_view value{std::begin(line) + index + sep.size(), std::end(line)};
// ESP_LOGD(TAG, "header key=\"%.*s\" value=\"%.*s\"", key.size(), key.data(), value.size(), value.data());
if (cpputils::stringEqualsIgnoreCase(key, "Content-Length"))
{
if (const auto parsed = cpputils::fromString<std::size_t>(value); !parsed)
{
ESP_LOGW(TAG, "invalid Content-Length %.*s %.*s", value.size(), value.data(),
parsed.error().size(), parsed.error().data());
m_socket.close();
return false;
}
else
m_requestBodySize = *parsed;
}
if (!m_responseHandler)
{
ESP_LOGW(TAG, "invalid response handler (%s:%hi)",
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
m_socket.close();
return false;
}
m_responseHandler->requestHeaderReceived(key, value);
return true;
}
}
else
{
if (!m_responseHandler)
{
ESP_LOGW(TAG, "invalid response handler (%s:%hi)",
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
m_socket.close();
return false;
}
if (m_requestBodySize)
{
// ESP_LOGV(TAG, "state changed to RequestBody");
m_state = State::RequestBody;
if (!m_parsingBuffer.empty())
{
if (m_parsingBuffer.size() <= m_requestBodySize)
{
m_responseHandler->requestBodyReceived(m_parsingBuffer);
m_requestBodySize -= m_parsingBuffer.size();
m_parsingBuffer.clear();
if (!m_requestBodySize)
goto requestFinished;
return true;
}
else
{
m_responseHandler->requestBodyReceived({m_parsingBuffer.data(), m_requestBodySize});
m_parsingBuffer.erase(std::begin(m_parsingBuffer), std::next(std::begin(m_parsingBuffer), m_requestBodySize));
m_requestBodySize = 0;
goto requestFinished;
}
}
else
return true;
}
else
{
requestFinished:
// ESP_LOGV(TAG, "state changed to Response");
m_state = State::Response;
m_responseHandler->sendResponse();
return false;
}
}
}
+54
View File
@@ -0,0 +1,54 @@
#pragma once
// system includes
#include <memory>
#include <string_view>
#include <string>
// esp-idf includes
#include <asio.hpp>
class Webserver;
class ResponseHandler;
class ClientConnection : public std::enable_shared_from_this<ClientConnection>
{
public:
ClientConnection(Webserver &webserver, asio::ip::tcp::socket socket);
~ClientConnection();
Webserver &webserver() { return m_webserver; }
const Webserver &webserver() const { return m_webserver; }
asio::ip::tcp::socket &socket() { return m_socket; }
const asio::ip::tcp::socket &socket() const { return m_socket; }
const asio::ip::tcp::endpoint &remote_endpoint() const { return m_remote_endpoint; }
void start();
void responseFinished(std::error_code ec);
void upgradeWebsocket();
private:
void doRead();
void readyRead(std::error_code ec, std::size_t length);
bool parseRequestLine(std::string_view line);
bool readyReadLine(std::string_view line);
bool parseRequestHeader(std::string_view line);
Webserver &m_webserver;
asio::ip::tcp::socket m_socket;
const asio::ip::tcp::endpoint m_remote_endpoint;
static constexpr const std::size_t max_length = 1024;
char m_receiveBuffer[max_length];
std::string m_parsingBuffer;
enum class State { RequestLine, RequestHeaders, RequestBody, Response, WebSocket };
State m_state { State::RequestLine };
std::size_t m_requestBodySize{};
std::unique_ptr<ResponseHandler> m_responseHandler;
};
+1
View File
@@ -0,0 +1 @@
#include "responsehandler.h"
+14
View File
@@ -0,0 +1,14 @@
#pragma once
// system includes
#include <string_view>
class ResponseHandler
{
public:
virtual ~ResponseHandler() = default;
virtual void requestHeaderReceived(std::string_view key, std::string_view value) = 0;
virtual void requestBodyReceived(std::string_view body) = 0;
virtual void sendResponse() = 0;
};
+40
View File
@@ -0,0 +1,40 @@
#include "webserver.h"
// esp-idf includes
#include <esp_log.h>
// local includes
#include "clientconnection.h"
namespace {
constexpr const char * const TAG = "ASIO_WEBSERVER";
} // namespace
Webserver::Webserver(asio::io_context &io_context, unsigned short port) :
m_acceptor{io_context, asio::ip::tcp::endpoint{asio::ip::tcp::v4(), port}}
{
ESP_LOGI(TAG, "create webserver on port %hi", port);
doAccept();
}
void Webserver::doAccept()
{
m_acceptor.async_accept(
[this](std::error_code ec, asio::ip::tcp::socket socket)
{ acceptClient(ec, std::move(socket)); });
}
void Webserver::acceptClient(std::error_code ec, asio::ip::tcp::socket socket)
{
if (ec)
{
ESP_LOGI(TAG, "error: %i", ec.value());
doAccept();
return;
}
std::make_shared<ClientConnection>(*this, std::move(socket))->start();
doAccept();
}
+36
View File
@@ -0,0 +1,36 @@
#pragma once
// system includes
#include <memory>
#include <string_view>
#include <atomic>
// esp-idf includes
#include <asio.hpp>
// forward declares
class ResponseHandler;
class ClientConnection;
class Webserver
{
public:
Webserver(asio::io_context& io_context, unsigned short port);
virtual ~Webserver() = default;
virtual bool connectionKeepAlive() const = 0;
virtual std::unique_ptr<ResponseHandler> makeResponseHandler(ClientConnection &clientConnection, std::string_view method, std::string_view path, std::string_view protocol) = 0;
protected:
friend class ClientConnection;
friend class WebsocketClientConnection;
std::atomic<int> m_httpClients;
std::atomic<int> m_websocketClients;
private:
void doAccept();
void acceptClient(std::error_code ec, asio::ip::tcp::socket socket);
asio::ip::tcp::acceptor m_acceptor;
};
+127
View File
@@ -0,0 +1,127 @@
#include "websocketclientconnection.h"
// system includes
// esp-idf includes
#include <esp_log.h>
// 3rdparty lib includes
#include <strutils.h>
// local includes
#include "webserver.h"
#include "responsehandler.h"
namespace {
constexpr const char * const TAG = "ASIO_WEBSERVER";
} // namespace
WebsocketClientConnection::WebsocketClientConnection(Webserver &webserver, asio::ip::tcp::socket socket, std::unique_ptr<ResponseHandler> &&responseHandler) :
m_webserver{webserver},
m_socket{std::move(socket)},
m_remote_endpoint{m_socket.remote_endpoint()},
m_responseHandler{std::move(responseHandler)}
{
ESP_LOGI(TAG, "new client (%s:%hi)",
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
m_webserver.m_websocketClients++;
}
WebsocketClientConnection::~WebsocketClientConnection()
{
ESP_LOGI(TAG, "client destroyed (%s:%hi)",
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
m_webserver.m_websocketClients--;
}
void WebsocketClientConnection::start()
{
doReadWebSocket();
}
void WebsocketClientConnection::doReadWebSocket()
{
m_socket.async_read_some(asio::buffer(m_receiveBuffer, max_length),
[this, self=shared_from_this()](std::error_code ec, std::size_t length)
{ readyReadWebSocket(ec, length); });
}
void WebsocketClientConnection::readyReadWebSocket(std::error_code ec, std::size_t length)
{
if (ec)
{
ESP_LOGI(TAG, "error: %i %s (%s:%hi)", ec.value(), ec.message().c_str(),
m_remote_endpoint.address().to_string().c_str(), m_remote_endpoint.port());
return;
}
// ESP_LOGV(TAG, "received: %zd \"%.*s\"", length, length, m_receiveBuffer);
m_parsingBuffer.append({m_receiveBuffer, length});
again:
ESP_LOGI(TAG, "m_parsingBuffer: %s", cpputils::toHexString(m_parsingBuffer).c_str());
if (m_parsingBuffer.empty())
{
doReadWebSocket();
return;
}
struct WebsocketHeader {
uint8_t opcode:4;
uint8_t reserved:3;
uint8_t fin:1;
uint8_t payloadLength:7;
uint8_t mask:1;
};
if (m_parsingBuffer.size() < sizeof(WebsocketHeader))
{
ESP_LOGW(TAG, "buffer smaller than a websocket header");
doReadWebSocket();
return;
}
ESP_LOGI(TAG, "%s%s%s%s %s%s%s%s %s%s%s%s %s%s%s%s",
m_parsingBuffer.data()[0]&128?"1":".", m_parsingBuffer.data()[0]&64?"1":".", m_parsingBuffer.data()[0]&32?"1":".", m_parsingBuffer.data()[0]&16?"1":".",
m_parsingBuffer.data()[0]&8?"1":".", m_parsingBuffer.data()[0]&4?"1":".", m_parsingBuffer.data()[0]&2?"1":".", m_parsingBuffer.data()[0]&1?"1":".",
m_parsingBuffer.data()[1]&128?"1":".", m_parsingBuffer.data()[1]&64?"1":".", m_parsingBuffer.data()[1]&32?"1":".", m_parsingBuffer.data()[1]&16?"1":".",
m_parsingBuffer.data()[1]&8?"1":".", m_parsingBuffer.data()[1]&4?"1":".", m_parsingBuffer.data()[1]&2?"1":".", m_parsingBuffer.data()[1]&1?"1":".");
const WebsocketHeader *hdr = (const WebsocketHeader *)m_parsingBuffer.data();
ESP_LOGI(TAG, "fin=%i reserved=%i opcode=%i mask=%i payloadLength=%i", hdr->fin, hdr->reserved, hdr->opcode, hdr->mask, hdr->payloadLength);
if (hdr->mask)
{
uint32_t mask;
if (m_parsingBuffer.size() < sizeof(WebsocketHeader) + sizeof(mask) + hdr->payloadLength)
{
ESP_LOGW(TAG, "buffer smaller than payload %zd vs %zd", m_parsingBuffer.size(), sizeof(WebsocketHeader) + hdr->payloadLength);
doReadWebSocket();
return;
}
mask = *(const uint32_t *)(m_parsingBuffer.data() + sizeof(WebsocketHeader));
ESP_LOGI(TAG, "mask=%s", cpputils::toHexString({(const char *)&mask, sizeof(mask)}).c_str());
m_parsingBuffer.erase(std::begin(m_parsingBuffer), std::next(std::begin(m_parsingBuffer), sizeof(WebsocketHeader) + sizeof(mask) + hdr->payloadLength));
}
else
{
if (m_parsingBuffer.size() < sizeof(WebsocketHeader) + hdr->payloadLength)
{
ESP_LOGW(TAG, "buffer smaller than payload %zd vs %zd", m_parsingBuffer.size(), sizeof(WebsocketHeader) + hdr->payloadLength);
doReadWebSocket();
return;
}
m_parsingBuffer.erase(std::begin(m_parsingBuffer), std::next(std::begin(m_parsingBuffer), sizeof(WebsocketHeader) + hdr->payloadLength));
}
goto again;
}
+41
View File
@@ -0,0 +1,41 @@
#pragma once
// system includes
// esp-idf includes
#include <asio.hpp>
class Webserver;
class ResponseHandler;
class WebsocketClientConnection : public std::enable_shared_from_this<WebsocketClientConnection>
{
public:
WebsocketClientConnection(Webserver &webserver, asio::ip::tcp::socket socket, std::unique_ptr<ResponseHandler> &&responseHandler);
~WebsocketClientConnection();
Webserver &webserver() { return m_webserver; }
const Webserver &webserver() const { return m_webserver; }
asio::ip::tcp::socket &socket() { return m_socket; }
const asio::ip::tcp::socket &socket() const { return m_socket; }
const asio::ip::tcp::endpoint &remote_endpoint() const { return m_remote_endpoint; }
void start();
private:
void doReadWebSocket();
void readyReadWebSocket(std::error_code ec, std::size_t length);
Webserver &m_webserver;
asio::ip::tcp::socket m_socket;
const asio::ip::tcp::endpoint m_remote_endpoint;
std::unique_ptr<ResponseHandler> m_responseHandler;
static constexpr const std::size_t max_length = 4;
char m_receiveBuffer[max_length];
std::string m_parsingBuffer;
};