|
| 1 | +#ifdef _WIN32 |
| 2 | + |
| 3 | +#include "firewall_windows.h" |
| 4 | + |
| 5 | +#include <cstdlib> |
| 6 | +#include <sstream> |
| 7 | +#include <string> |
| 8 | + |
| 9 | +namespace { |
| 10 | +std::string escape_ps(const std::string &value) { |
| 11 | + std::string escaped; |
| 12 | + escaped.reserve(value.size()); |
| 13 | + for (char c : value) { |
| 14 | + if (c == '\'') { |
| 15 | + escaped += "''"; |
| 16 | + } else { |
| 17 | + escaped.push_back(c); |
| 18 | + } |
| 19 | + } |
| 20 | + return escaped; |
| 21 | +} |
| 22 | +} // namespace |
| 23 | + |
| 24 | +bool ensureTcpFirewallRule(const char *ruleName, int port) { |
| 25 | + if (port <= 0 || ruleName == nullptr || ruleName[0] == '\0') { |
| 26 | + return false; |
| 27 | + } |
| 28 | + const std::string escapedName = escape_ps(ruleName); |
| 29 | + std::ostringstream ps; |
| 30 | + ps << "powershell -Command \"$ErrorActionPreference='SilentlyContinue'; " |
| 31 | + << "Remove-NetFirewallRule -DisplayName '" << escapedName |
| 32 | + << "' -ErrorAction SilentlyContinue; " |
| 33 | + << "New-NetFirewallRule -DisplayName '" << escapedName |
| 34 | + << "' -Direction Inbound -Action Allow -Protocol TCP -LocalPort " |
| 35 | + << port << " -Enabled True\""; |
| 36 | + return ::system(ps.str().c_str()) == 0; |
| 37 | +} |
| 38 | + |
| 39 | +bool ensureTunFirewallRule(const char *ruleName, const char *interfaceAlias) { |
| 40 | + if (ruleName == nullptr || ruleName[0] == '\0' || interfaceAlias == nullptr || |
| 41 | + interfaceAlias[0] == '\0') { |
| 42 | + return false; |
| 43 | + } |
| 44 | + const std::string escapedName = escape_ps(ruleName); |
| 45 | + const std::string escapedAlias = escape_ps(interfaceAlias); |
| 46 | + std::ostringstream ps; |
| 47 | + ps << "powershell -Command \"$ErrorActionPreference='SilentlyContinue'; " |
| 48 | + << "Remove-NetFirewallRule -DisplayName '" << escapedName |
| 49 | + << "' -ErrorAction SilentlyContinue; " |
| 50 | + << "New-NetFirewallRule -DisplayName '" << escapedName |
| 51 | + << "' -Direction Inbound -Action Allow -Protocol Any " |
| 52 | + << "-InterfaceAlias '" << escapedAlias << "' -Enabled True\""; |
| 53 | + return ::system(ps.str().c_str()) == 0; |
| 54 | +} |
| 55 | + |
| 56 | +#endif |
0 commit comments