#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(const char *source, const char *destination, const char *protocol, const char *target) { firewall_rule_t *temp; firewall_rule_t *link = (firewall_rule_t *)malloc(sizeof(firewall_rule_t)); link->key = ++amount_of_rules; strcpy(link->source, source); strcpy(link->destination, destination); strcpy(link->protocol, protocol); strcpy(link->target, target); 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; rule["source"] = ptr->source; rule["destination"] = ptr->destination; rule["protocol"] = ptr->protocol; rule["target"] = ptr->target; 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")) { const char *source = request->arg("source").c_str(); const char *destination = request->arg("destination").c_str(); const char *protocol = request->arg("protocol").c_str(); const char *target = request->arg("target").c_str(); json["source"] = source; json["destination"] = destination; json["protocol"] = protocol; json["target"] = target; add_rule_to_firewall(source, destination, protocol, target); 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(); }