This repository has been archived on 2024-10-30. You can view files and clone it, but cannot push or open issues or pull requests.
esp-firewall/SourceCode/arduino/lib/Firewall/Firewall.cpp
2022-04-11 17:02:58 +02:00

90 lines
2.6 KiB
C++

#include "Firewall.h"
ESPFirewall::ESPFirewall(int port)
{
log_i("Starting Firewall-API on %i", port);
this->firewall_api = new AsyncWebServer(port);
this->setup_routing();
}
void ESPFirewall::add_rule_to_firewall()
{
firewall_rule_t *temp;
firewall_rule_t *link = (firewall_rule_t *)malloc(sizeof(firewall_rule_t));
link->key = ++amount_of_rules;
if (head == NULL)
{
head = link;
link->next = NULL;
return;
}
temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = link;
link->next = NULL;
return;
}
void ESPFirewall::get_firewall_handler(AsyncWebServerRequest *request)
{
firewall_rule_t *ptr = this->head;
DynamicJsonDocument json(1024);
String response;
json["amount"] = amount_of_rules;
JsonArray rules = json.createNestedArray("rules");
while (ptr != NULL)
{
JsonObject rule = rules.createNestedObject();
rule["key"] = ptr->key;
ptr = ptr->next;
}
serializeJson(json, response);
request->send(200, "application/json", response);
}
void ESPFirewall::post_firewall_handler(AsyncWebServerRequest *request)
{
DynamicJsonDocument json(1024);
String response;
int response_code;
if (request->hasArg("source") || request->hasArg("destination") || request->hasArg("protocol") || request->hasArg("target"))
{
String source = request->arg("source");
String destination = request->arg("destination");
String protocol = request->arg("protocol");
String target = request->arg("target");
json["source"] = source;
json["destination"] = destination;
json["protocol"] = protocol;
json["target"] = target;
add_rule_to_firewall();
response_code = 200;
}
else
{
json["message"] = "not enough parameter provided";
response_code = 400;
}
serializeJson(json, response);
request->send(response_code, "application/json", response);
}
void ESPFirewall::not_found(AsyncWebServerRequest *request)
{
DynamicJsonDocument json(1024);
String response;
json["message"] = "not found";
serializeJson(json, response);
request->send(404, "application/json", response);
}
void ESPFirewall::setup_routing()
{
firewall_api->on("/api/v1/firewall", HTTP_GET, std::bind(&ESPFirewall::get_firewall_handler, this, std::placeholders::_1));
firewall_api->on("/api/v1/firewall", HTTP_POST, std::bind(&ESPFirewall::post_firewall_handler, this, std::placeholders::_1));
firewall_api->onNotFound(std::bind(&ESPFirewall::not_found, this, std::placeholders::_1));
this->firewall_api->begin();
}