Files
stvpn/srvconfig.cpp
2026-05-15 15:30:29 +02:00

98 lines
3.2 KiB
C++

#include <expected>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include <srvconfig.hpp>
#include <stringaux.hpp>
#include <networkaux.hpp>
int ServConfig::Listenport(void) {
return listenport;
}
std::vector<std::string> ServConfig::Localnets(void) {
return localnets;
}
std::string ServConfig::Tunnelnet(void) {
return tunnelnet;
}
std::expected<void, std::string> ServConfig::Read(std::string filename) {
std::ifstream file;
file.open(filename);
if (file.fail()) {
auto state = file.rdstate();
if (state & std::ios_base::badbit) {
return std::unexpected("Read/writing error on i/o operation");
} else if (state & std::ios_base::failbit) {
return std::unexpected("Logical error on i/o operation");
}
}
std::string line;
while (std::getline(file, line)) {
auto tokens = split(line, "#;");
auto keyval = trim(tokens[0]);
if (keyval.size() == 0) continue;
tokens = split(keyval, "=");
if (tokens.size() < 2) continue;
auto key = trim(tokens[0]);
auto val = trim(tokens[1]);
kvmap[key] = val;
if (key == "localnet") {
localnets.push_back(val);
} else if (key == "tunnelnet") {
tunnelnet = val;
} else if (key == "listenport") {
auto convRes = strtoint(val);
if (!convRes) {
auto msg = std::format("listenport: {}", convRes.error());
return std::unexpected(msg);
}
listenport = convRes.value();
}
}
file.close();
return {};
}
std::expected<void, std::string> ServConfig::Validate(void) {
if (tunnelnet.size() == 0) {
return std::unexpected("Empty tunnel network");
}
if (listenport == 0) {
return std::unexpected("Zero listen port");
}
auto netprefixRes = netprefix(tunnelnet);
if (!netprefixRes) {
return std::unexpected("Incorrect tunnel network:" + netprefixRes.error());
}
auto networkRes = network(tunnelnet);
if (!networkRes) {
return std::unexpected("Incorrect tunnel network:" + networkRes.error());
}
for (const auto& val : localnets) {
auto netprefixRes = netprefix(val);
if (!netprefixRes) {
return std::unexpected("Incorrect local network " + val + ":" + netprefixRes.error());
}
auto networkRes = network(val);
if (!networkRes) {
return std::unexpected("Incorrect local network " + val + ":" + networkRes.error());
}
}
return {};
}