91 lines
3 KiB
C++
91 lines
3 KiB
C++
#include "relayconf.h"
|
|
|
|
#include <algorithm>
|
|
#include <cstdlib>
|
|
#include <fstream>
|
|
#include <sstream>
|
|
#include <string>
|
|
|
|
namespace wg {
|
|
|
|
static std::string trim(const std::string &s) {
|
|
const char *ws = " \t\r\n";
|
|
size_t start = s.find_first_not_of(ws);
|
|
if (start == std::string::npos) return {};
|
|
size_t end = s.find_last_not_of(ws);
|
|
return s.substr(start, end - start + 1);
|
|
}
|
|
|
|
bool parseRelayConf(const std::string &path, RelayConf &conf, std::string &errOut) {
|
|
std::ifstream file(path);
|
|
if (!file.is_open()) {
|
|
errOut = "Cannot open relay.conf: " + path;
|
|
return false;
|
|
}
|
|
|
|
std::string line;
|
|
int lineNum = 0;
|
|
|
|
while (std::getline(file, line)) {
|
|
++lineNum;
|
|
std::string trimmed = trim(line);
|
|
|
|
// Skip blank lines and comments
|
|
if (trimmed.empty() || trimmed[0] == '#') continue;
|
|
|
|
size_t eq = trimmed.find('=');
|
|
if (eq == std::string::npos) {
|
|
errOut = "relay.conf line " + std::to_string(lineNum) + ": missing '='";
|
|
return false;
|
|
}
|
|
|
|
std::string key = trim(trimmed.substr(0, eq));
|
|
std::string value = trim(trimmed.substr(eq + 1));
|
|
|
|
if (key == "server_address") conf.server_address = value;
|
|
else if (key == "private_key") conf.private_key = value;
|
|
else if (key == "server_public_key") conf.server_public_key = value;
|
|
else if (key == "relay_token") conf.relay_token = value;
|
|
else if (key == "relay_host") conf.relay_host = value;
|
|
else if (key == "server_port") {
|
|
try { conf.server_port = std::stoi(value); }
|
|
catch (...) {
|
|
errOut = "relay.conf line " + std::to_string(lineNum) + ": invalid server_port";
|
|
return false;
|
|
}
|
|
}
|
|
else if (key == "relay_port") {
|
|
try { conf.relay_port = std::stoi(value); }
|
|
catch (...) {
|
|
errOut = "relay.conf line " + std::to_string(lineNum) + ": invalid relay_port";
|
|
return false;
|
|
}
|
|
}
|
|
// Unknown keys are silently ignored for forward compatibility
|
|
}
|
|
|
|
// Validate required fields
|
|
if (conf.server_address.empty()) { errOut = "relay.conf: missing server_address"; return false; }
|
|
if (conf.private_key.empty()) { errOut = "relay.conf: missing private_key"; return false; }
|
|
if (conf.server_public_key.empty()) { errOut = "relay.conf: missing server_public_key"; return false; }
|
|
if (conf.relay_token.empty()) { errOut = "relay.conf: missing relay_token"; return false; }
|
|
|
|
// Default relay_host from server_address if not set
|
|
if (conf.relay_host.empty()) {
|
|
conf.relay_host = "https://" + conf.server_address;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
std::string defaultRelayConfPath() {
|
|
#ifdef _WIN32
|
|
const char *pd = std::getenv("PROGRAMDATA");
|
|
std::string base = pd ? pd : "C:\\ProgramData";
|
|
return base + "\\Artemis\\relay.conf";
|
|
#else
|
|
return "/etc/artemis/relay.conf";
|
|
#endif
|
|
}
|
|
|
|
} // namespace wg
|