mirror of
https://git.neolegacy.dev/neoStudiosLCE/neoLegacy.git
synced 2026-12-02 22:18:09 +01:00
+Discord account connection +Friends List +UPnP Connection +Cosmetics (Iggy menus need to be fixed up a little)
641 lines
21 KiB
C++
641 lines
21 KiB
C++
#include "stdafx.h"
|
|
#include "UPnPMapper.h"
|
|
#include <WinSock2.h>
|
|
#include <WS2tcpip.h>
|
|
#include <iphlpapi.h>
|
|
#include <winhttp.h>
|
|
#include <atomic>
|
|
#include <mutex>
|
|
#include <thread>
|
|
#include <string>
|
|
#include <vector>
|
|
#include <algorithm>
|
|
#include <cstdarg>
|
|
|
|
#pragma comment(lib, "iphlpapi.lib")
|
|
#pragma comment(lib, "winhttp.lib")
|
|
#pragma comment(lib, "ws2_32.lib")
|
|
|
|
namespace UPnPMapper
|
|
{
|
|
namespace
|
|
{
|
|
const char *kDescription = "neoLegacy";
|
|
const unsigned int kLeaseSeconds = 7200;
|
|
const unsigned int kNatPmpLifetime = 7200;
|
|
|
|
enum EMethod
|
|
{
|
|
eMethod_None,
|
|
eMethod_UPnP,
|
|
eMethod_NatPmp,
|
|
};
|
|
|
|
struct Mapping
|
|
{
|
|
EMethod method = eMethod_None;
|
|
int internalPort = 0;
|
|
int externalPort = 0;
|
|
unsigned int lease = 0;
|
|
std::string controlUrl;
|
|
std::string serviceType;
|
|
std::string localIp;
|
|
std::string gateway;
|
|
};
|
|
|
|
std::mutex s_mutex;
|
|
std::atomic<int> s_state{ eState_Idle };
|
|
std::atomic<int> s_externalPort{ 0 };
|
|
Mapping s_mapping;
|
|
unsigned int s_generation = 0;
|
|
|
|
void Log(const char *format, ...)
|
|
{
|
|
char line[1024] = {};
|
|
va_list args;
|
|
va_start(args, format);
|
|
vsnprintf(line, sizeof(line), format, args);
|
|
va_end(args);
|
|
app.DebugPrintf("UPnP: %s\n", line);
|
|
|
|
char exePath[MAX_PATH] = {};
|
|
GetModuleFileNameA(nullptr, exePath, MAX_PATH);
|
|
char *slash = strrchr(exePath, '\\');
|
|
if (slash)
|
|
*(slash + 1) = 0;
|
|
std::string path = std::string(exePath) + "upnp.log";
|
|
FILE *f = nullptr;
|
|
if (fopen_s(&f, path.c_str(), "a") == 0 && f)
|
|
{
|
|
SYSTEMTIME t;
|
|
GetLocalTime(&t);
|
|
fprintf(f, "%04d-%02d-%02d %02d:%02d:%02d %s\n", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, line);
|
|
fclose(f);
|
|
}
|
|
}
|
|
|
|
std::string Lower(std::string value)
|
|
{
|
|
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) { return static_cast<char>(tolower(c)); });
|
|
return value;
|
|
}
|
|
|
|
std::wstring Widen(const std::string &value)
|
|
{
|
|
return std::wstring(value.begin(), value.end());
|
|
}
|
|
|
|
bool LocalAddress(std::string &out)
|
|
{
|
|
SOCKET probe = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
|
if (probe == INVALID_SOCKET)
|
|
return false;
|
|
sockaddr_in target = {};
|
|
target.sin_family = AF_INET;
|
|
target.sin_port = htons(53);
|
|
inet_pton(AF_INET, "8.8.8.8", &target.sin_addr);
|
|
bool ok = false;
|
|
if (connect(probe, reinterpret_cast<sockaddr *>(&target), sizeof(target)) == 0)
|
|
{
|
|
sockaddr_in local = {};
|
|
int length = sizeof(local);
|
|
char text[64] = {};
|
|
if (getsockname(probe, reinterpret_cast<sockaddr *>(&local), &length) == 0 && inet_ntop(AF_INET, &local.sin_addr, text, sizeof(text)) != nullptr)
|
|
{
|
|
out = text;
|
|
ok = local.sin_addr.s_addr != 0;
|
|
}
|
|
}
|
|
closesocket(probe);
|
|
return ok;
|
|
}
|
|
|
|
bool GatewayAddress(std::string &out)
|
|
{
|
|
MIB_IPFORWARDROW row = {};
|
|
IN_ADDR target = {};
|
|
inet_pton(AF_INET, "8.8.8.8", &target);
|
|
if (GetBestRoute(target.s_addr, 0, &row) != NO_ERROR || row.dwForwardNextHop == 0)
|
|
return false;
|
|
IN_ADDR hop = {};
|
|
hop.s_addr = row.dwForwardNextHop;
|
|
char text[64] = {};
|
|
if (inet_ntop(AF_INET, &hop, text, sizeof(text)) == nullptr)
|
|
return false;
|
|
out = text;
|
|
return true;
|
|
}
|
|
|
|
bool HttpRequest(const std::string &url, const wchar_t *verb, const std::string &headers, const std::string &body, int &status, std::string &response)
|
|
{
|
|
status = 0;
|
|
response.clear();
|
|
std::wstring wideUrl = Widen(url);
|
|
URL_COMPONENTS parts = {};
|
|
parts.dwStructSize = sizeof(parts);
|
|
wchar_t host[256] = {};
|
|
wchar_t path[2048] = {};
|
|
wchar_t extra[1024] = {};
|
|
parts.lpszHostName = host;
|
|
parts.dwHostNameLength = 256;
|
|
parts.lpszUrlPath = path;
|
|
parts.dwUrlPathLength = 2048;
|
|
parts.lpszExtraInfo = extra;
|
|
parts.dwExtraInfoLength = 1024;
|
|
if (!WinHttpCrackUrl(wideUrl.c_str(), 0, 0, &parts) || host[0] == 0)
|
|
return false;
|
|
std::wstring fullPath = std::wstring(path) + extra;
|
|
if (fullPath.empty())
|
|
fullPath = L"/";
|
|
|
|
HINTERNET session = WinHttpOpen(L"neoLegacy UPnP/1.0", WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
|
|
if (session == nullptr)
|
|
return false;
|
|
WinHttpSetTimeouts(session, 3000, 3000, 4000, 4000);
|
|
bool ok = false;
|
|
HINTERNET connection = WinHttpConnect(session, host, parts.nPort, 0);
|
|
if (connection != nullptr)
|
|
{
|
|
HINTERNET request = WinHttpOpenRequest(connection, verb, fullPath.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, parts.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0);
|
|
if (request != nullptr)
|
|
{
|
|
std::wstring wideHeaders = Widen(headers);
|
|
DWORD length = static_cast<DWORD>(body.size());
|
|
LPVOID data = length > 0 ? const_cast<char *>(body.data()) : WINHTTP_NO_REQUEST_DATA;
|
|
if (WinHttpSendRequest(request, wideHeaders.empty() ? WINHTTP_NO_ADDITIONAL_HEADERS : wideHeaders.c_str(), wideHeaders.empty() ? 0 : static_cast<DWORD>(-1), data, length, length, 0) && WinHttpReceiveResponse(request, nullptr))
|
|
{
|
|
DWORD code = 0;
|
|
DWORD size = sizeof(code);
|
|
WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &code, &size, WINHTTP_NO_HEADER_INDEX);
|
|
status = static_cast<int>(code);
|
|
while (response.size() < 262144)
|
|
{
|
|
DWORD available = 0;
|
|
if (!WinHttpQueryDataAvailable(request, &available) || available == 0)
|
|
break;
|
|
std::string chunk(available, '\0');
|
|
DWORD read = 0;
|
|
if (!WinHttpReadData(request, &chunk[0], available, &read))
|
|
break;
|
|
chunk.resize(read);
|
|
response += chunk;
|
|
}
|
|
ok = true;
|
|
}
|
|
WinHttpCloseHandle(request);
|
|
}
|
|
WinHttpCloseHandle(connection);
|
|
}
|
|
WinHttpCloseHandle(session);
|
|
return ok;
|
|
}
|
|
|
|
std::string TagValue(const std::string &xml, const std::string &lowerXml, const std::string &tag, size_t from = 0, size_t until = std::string::npos)
|
|
{
|
|
std::string open = "<" + tag;
|
|
size_t pos = from;
|
|
while (true)
|
|
{
|
|
pos = lowerXml.find(open, pos);
|
|
if (pos == std::string::npos || pos >= until)
|
|
return std::string();
|
|
char next = pos + open.size() < lowerXml.size() ? lowerXml[pos + open.size()] : 0;
|
|
if (next == '>' || next == ' ')
|
|
break;
|
|
pos += open.size();
|
|
}
|
|
size_t start = lowerXml.find('>', pos);
|
|
if (start == std::string::npos)
|
|
return std::string();
|
|
++start;
|
|
size_t end = lowerXml.find("</" + tag, start);
|
|
if (end == std::string::npos || end > until)
|
|
return std::string();
|
|
std::string value = xml.substr(start, end - start);
|
|
size_t first = value.find_first_not_of(" \t\r\n");
|
|
size_t last = value.find_last_not_of(" \t\r\n");
|
|
return first == std::string::npos ? std::string() : value.substr(first, last - first + 1);
|
|
}
|
|
|
|
std::string ResolveUrl(const std::string &base, const std::string &relative)
|
|
{
|
|
if (relative.find("://") != std::string::npos)
|
|
return relative;
|
|
size_t scheme = base.find("://");
|
|
if (scheme == std::string::npos)
|
|
return relative;
|
|
size_t hostEnd = base.find('/', scheme + 3);
|
|
std::string root = hostEnd == std::string::npos ? base : base.substr(0, hostEnd);
|
|
if (!relative.empty() && relative[0] == '/')
|
|
return root + relative;
|
|
std::string dir = hostEnd == std::string::npos ? root + "/" : base.substr(0, base.rfind('/') + 1);
|
|
return dir + relative;
|
|
}
|
|
|
|
std::vector<std::string> DiscoverLocations(const std::string &localIp)
|
|
{
|
|
std::vector<std::string> locations;
|
|
SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
|
if (sock == INVALID_SOCKET)
|
|
{
|
|
Log("could not open a discovery socket (%d)", WSAGetLastError());
|
|
return locations;
|
|
}
|
|
sockaddr_in bindAddr = {};
|
|
bindAddr.sin_family = AF_INET;
|
|
inet_pton(AF_INET, localIp.c_str(), &bindAddr.sin_addr);
|
|
if (::bind(sock, reinterpret_cast<sockaddr *>(&bindAddr), sizeof(bindAddr)) != 0)
|
|
{
|
|
bindAddr.sin_addr.s_addr = INADDR_ANY;
|
|
::bind(sock, reinterpret_cast<sockaddr *>(&bindAddr), sizeof(bindAddr));
|
|
}
|
|
DWORD ttl = 2;
|
|
setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, reinterpret_cast<const char *>(&ttl), sizeof(ttl));
|
|
IN_ADDR iface = {};
|
|
inet_pton(AF_INET, localIp.c_str(), &iface);
|
|
setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, reinterpret_cast<const char *>(&iface), sizeof(iface));
|
|
DWORD timeout = 500;
|
|
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char *>(&timeout), sizeof(timeout));
|
|
|
|
sockaddr_in group = {};
|
|
group.sin_family = AF_INET;
|
|
group.sin_port = htons(1900);
|
|
inet_pton(AF_INET, "239.255.255.250", &group.sin_addr);
|
|
|
|
const char *targets[] = {
|
|
"urn:schemas-upnp-org:device:InternetGatewayDevice:1",
|
|
"urn:schemas-upnp-org:device:InternetGatewayDevice:2",
|
|
"urn:schemas-upnp-org:service:WANIPConnection:1",
|
|
"urn:schemas-upnp-org:service:WANIPConnection:2",
|
|
"urn:schemas-upnp-org:service:WANPPPConnection:1",
|
|
};
|
|
for (int round = 0; round < 2 && locations.empty(); ++round)
|
|
{
|
|
for (const char *target : targets)
|
|
{
|
|
std::string message = std::string("M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: 2\r\nST: ") + target + "\r\n\r\n";
|
|
sendto(sock, message.c_str(), static_cast<int>(message.size()), 0, reinterpret_cast<sockaddr *>(&group), sizeof(group));
|
|
}
|
|
ULONGLONG until = GetTickCount64() + 3000;
|
|
while (GetTickCount64() < until)
|
|
{
|
|
char buffer[2048] = {};
|
|
int received = recv(sock, buffer, sizeof(buffer) - 1, 0);
|
|
if (received <= 0)
|
|
continue;
|
|
std::string reply(buffer, received);
|
|
std::string lowerReply = Lower(reply);
|
|
if (lowerReply.find("internetgatewaydevice") == std::string::npos && lowerReply.find("wanipconnection") == std::string::npos && lowerReply.find("wanpppconnection") == std::string::npos)
|
|
continue;
|
|
size_t pos = lowerReply.find("\nlocation:");
|
|
if (pos == std::string::npos)
|
|
continue;
|
|
pos += 10;
|
|
size_t end = reply.find("\r", pos);
|
|
std::string location = reply.substr(pos, end == std::string::npos ? std::string::npos : end - pos);
|
|
location.erase(0, location.find_first_not_of(" \t"));
|
|
if (!location.empty() && std::find(locations.begin(), locations.end(), location) == locations.end())
|
|
locations.push_back(location);
|
|
}
|
|
}
|
|
closesocket(sock);
|
|
return locations;
|
|
}
|
|
|
|
bool FindControl(const std::string &location, std::string &controlUrl, std::string &serviceType)
|
|
{
|
|
int status = 0;
|
|
std::string xml;
|
|
if (!HttpRequest(location, L"GET", std::string(), std::string(), status, xml) || status != 200)
|
|
{
|
|
Log("could not read router description from %s (status %d)", location.c_str(), status);
|
|
return false;
|
|
}
|
|
std::string lowerXml = Lower(xml);
|
|
std::string base = TagValue(xml, lowerXml, "urlbase");
|
|
if (base.empty())
|
|
base = location;
|
|
const char *wanted[] = { "wanipconnection:2", "wanipconnection:1", "wanpppconnection:1" };
|
|
for (const char *want : wanted)
|
|
{
|
|
size_t pos = 0;
|
|
while ((pos = lowerXml.find("<service>", pos)) != std::string::npos)
|
|
{
|
|
size_t end = lowerXml.find("</service>", pos);
|
|
if (end == std::string::npos)
|
|
break;
|
|
std::string type = TagValue(xml, lowerXml, "servicetype", pos, end);
|
|
if (Lower(type).find(want) != std::string::npos)
|
|
{
|
|
std::string control = TagValue(xml, lowerXml, "controlurl", pos, end);
|
|
if (!control.empty())
|
|
{
|
|
controlUrl = ResolveUrl(base, control);
|
|
serviceType = type;
|
|
return true;
|
|
}
|
|
}
|
|
pos = end;
|
|
}
|
|
}
|
|
Log("router at %s has no WAN connection service", location.c_str());
|
|
return false;
|
|
}
|
|
|
|
bool Soap(const std::string &controlUrl, const std::string &serviceType, const std::string &action, const std::string &args, int &status, std::string &response)
|
|
{
|
|
std::string body =
|
|
"<?xml version=\"1.0\"?>\r\n"
|
|
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
|
|
"<s:Body><u:" + action + " xmlns:u=\"" + serviceType + "\">" + args + "</u:" + action + "></s:Body></s:Envelope>\r\n";
|
|
std::string headers = "Content-Type: text/xml; charset=\"utf-8\"\r\nSOAPAction: \"" + serviceType + "#" + action + "\"\r\n";
|
|
return HttpRequest(controlUrl, L"POST", headers, body, status, response);
|
|
}
|
|
|
|
std::string SoapError(const std::string &response)
|
|
{
|
|
std::string lower = Lower(response);
|
|
std::string code = TagValue(response, lower, "errorcode");
|
|
std::string text = TagValue(response, lower, "errordescription");
|
|
return code.empty() ? std::string("unknown") : code + (text.empty() ? std::string() : " " + text);
|
|
}
|
|
|
|
std::string AddArgs(int port, const std::string &localIp, unsigned int lease)
|
|
{
|
|
return "<NewRemoteHost></NewRemoteHost>"
|
|
"<NewExternalPort>" + std::to_string(port) + "</NewExternalPort>"
|
|
"<NewProtocol>TCP</NewProtocol>"
|
|
"<NewInternalPort>" + std::to_string(port) + "</NewInternalPort>"
|
|
"<NewInternalClient>" + localIp + "</NewInternalClient>"
|
|
"<NewEnabled>1</NewEnabled>"
|
|
"<NewPortMappingDescription>" + kDescription + "</NewPortMappingDescription>"
|
|
"<NewLeaseDuration>" + std::to_string(lease) + "</NewLeaseDuration>";
|
|
}
|
|
|
|
std::string DeleteArgs(int port)
|
|
{
|
|
return "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + std::to_string(port) + "</NewExternalPort><NewProtocol>TCP</NewProtocol>";
|
|
}
|
|
|
|
bool TryUPnP(int port, const std::string &localIp, Mapping &out)
|
|
{
|
|
std::vector<std::string> locations = DiscoverLocations(localIp);
|
|
if (locations.empty())
|
|
{
|
|
Log("no UPnP router answered on the local network");
|
|
return false;
|
|
}
|
|
for (const std::string &location : locations)
|
|
{
|
|
std::string controlUrl;
|
|
std::string serviceType;
|
|
if (!FindControl(location, controlUrl, serviceType))
|
|
continue;
|
|
Log("found router service %s", serviceType.c_str());
|
|
const unsigned int leases[] = { kLeaseSeconds, 0 };
|
|
for (unsigned int lease : leases)
|
|
{
|
|
int status = 0;
|
|
std::string response;
|
|
bool sent = Soap(controlUrl, serviceType, "AddPortMapping", AddArgs(port, localIp, lease), status, response);
|
|
if (sent && status == 200)
|
|
{
|
|
out.method = eMethod_UPnP;
|
|
out.internalPort = port;
|
|
out.externalPort = port;
|
|
out.lease = lease;
|
|
out.controlUrl = controlUrl;
|
|
out.serviceType = serviceType;
|
|
out.localIp = localIp;
|
|
return true;
|
|
}
|
|
std::string error = sent ? SoapError(response) : std::string("no response");
|
|
Log("router refused the mapping (lease %u): %s", lease, error.c_str());
|
|
if (error.compare(0, 3, "718") == 0)
|
|
{
|
|
Log("port %d is already mapped on the router, possibly to another device", port);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
bool NatPmpRequest(const std::string &gateway, const unsigned char *request, int requestLength, unsigned char *reply, int replyLength)
|
|
{
|
|
SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
|
if (sock == INVALID_SOCKET)
|
|
return false;
|
|
sockaddr_in target = {};
|
|
target.sin_family = AF_INET;
|
|
target.sin_port = htons(5351);
|
|
inet_pton(AF_INET, gateway.c_str(), &target.sin_addr);
|
|
bool ok = false;
|
|
DWORD wait = 250;
|
|
for (int attempt = 0; attempt < 5 && !ok; ++attempt)
|
|
{
|
|
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char *>(&wait), sizeof(wait));
|
|
sendto(sock, reinterpret_cast<const char *>(request), requestLength, 0, reinterpret_cast<sockaddr *>(&target), sizeof(target));
|
|
sockaddr_in from = {};
|
|
int fromLength = sizeof(from);
|
|
int received = recvfrom(sock, reinterpret_cast<char *>(reply), replyLength, 0, reinterpret_cast<sockaddr *>(&from), &fromLength);
|
|
if (received >= replyLength && from.sin_addr.s_addr == target.sin_addr.s_addr)
|
|
ok = true;
|
|
wait *= 2;
|
|
}
|
|
closesocket(sock);
|
|
return ok;
|
|
}
|
|
|
|
bool NatPmpMap(const std::string &gateway, int internalPort, int requestedPort, unsigned int lifetime, int &mappedPort, int &resultCode)
|
|
{
|
|
unsigned char request[12] = {};
|
|
request[0] = 0;
|
|
request[1] = 2;
|
|
request[4] = static_cast<unsigned char>(internalPort >> 8);
|
|
request[5] = static_cast<unsigned char>(internalPort & 0xff);
|
|
request[6] = static_cast<unsigned char>(requestedPort >> 8);
|
|
request[7] = static_cast<unsigned char>(requestedPort & 0xff);
|
|
request[8] = static_cast<unsigned char>(lifetime >> 24);
|
|
request[9] = static_cast<unsigned char>(lifetime >> 16);
|
|
request[10] = static_cast<unsigned char>(lifetime >> 8);
|
|
request[11] = static_cast<unsigned char>(lifetime & 0xff);
|
|
unsigned char reply[16] = {};
|
|
resultCode = -1;
|
|
if (!NatPmpRequest(gateway, request, sizeof(request), reply, sizeof(reply)))
|
|
return false;
|
|
resultCode = (reply[2] << 8) | reply[3];
|
|
if (reply[1] != 130 || resultCode != 0)
|
|
return false;
|
|
mappedPort = (reply[10] << 8) | reply[11];
|
|
return true;
|
|
}
|
|
|
|
bool TryNatPmp(int port, Mapping &out)
|
|
{
|
|
std::string gateway;
|
|
if (!GatewayAddress(gateway))
|
|
{
|
|
Log("could not find the default gateway for NAT-PMP");
|
|
return false;
|
|
}
|
|
int mapped = 0;
|
|
int result = 0;
|
|
if (!NatPmpMap(gateway, port, port, kNatPmpLifetime, mapped, result))
|
|
{
|
|
if (result < 0)
|
|
Log("router did not answer NAT-PMP");
|
|
else
|
|
Log("router refused NAT-PMP mapping (result %d)", result);
|
|
return false;
|
|
}
|
|
out.method = eMethod_NatPmp;
|
|
out.internalPort = port;
|
|
out.externalPort = mapped;
|
|
out.lease = kNatPmpLifetime;
|
|
out.gateway = gateway;
|
|
return true;
|
|
}
|
|
|
|
bool Refresh(Mapping &mapping)
|
|
{
|
|
if (mapping.method == eMethod_UPnP)
|
|
{
|
|
int status = 0;
|
|
std::string response;
|
|
return Soap(mapping.controlUrl, mapping.serviceType, "AddPortMapping", AddArgs(mapping.internalPort, mapping.localIp, mapping.lease), status, response) && status == 200;
|
|
}
|
|
if (mapping.method == eMethod_NatPmp)
|
|
{
|
|
int mapped = 0;
|
|
int result = 0;
|
|
if (!NatPmpMap(mapping.gateway, mapping.internalPort, mapping.externalPort, mapping.lease, mapped, result))
|
|
return false;
|
|
mapping.externalPort = mapped;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
void Remove(const Mapping &mapping)
|
|
{
|
|
if (mapping.method == eMethod_UPnP)
|
|
{
|
|
int status = 0;
|
|
std::string response;
|
|
Soap(mapping.controlUrl, mapping.serviceType, "DeletePortMapping", DeleteArgs(mapping.externalPort), status, response);
|
|
Log("removed UPnP mapping for port %d (status %d)", mapping.externalPort, status);
|
|
}
|
|
else if (mapping.method == eMethod_NatPmp)
|
|
{
|
|
int mapped = 0;
|
|
int result = 0;
|
|
NatPmpMap(mapping.gateway, mapping.internalPort, 0, 0, mapped, result);
|
|
Log("removed NAT-PMP mapping for port %d", mapping.internalPort);
|
|
}
|
|
}
|
|
|
|
bool IsCurrent(unsigned int generation)
|
|
{
|
|
std::lock_guard<std::mutex> lock(s_mutex);
|
|
return generation == s_generation;
|
|
}
|
|
|
|
void MapWorker(int port, unsigned int generation)
|
|
{
|
|
std::string localIp;
|
|
Mapping mapping;
|
|
bool mapped = false;
|
|
if (!LocalAddress(localIp))
|
|
{
|
|
Log("could not find this computer's local address");
|
|
}
|
|
else
|
|
{
|
|
Log("trying to open port %d for %s", port, localIp.c_str());
|
|
mapped = TryUPnP(port, localIp, mapping);
|
|
if (!mapped)
|
|
mapped = TryNatPmp(port, mapping);
|
|
}
|
|
|
|
{
|
|
std::lock_guard<std::mutex> lock(s_mutex);
|
|
if (generation == s_generation)
|
|
{
|
|
s_mapping = mapped ? mapping : Mapping();
|
|
s_externalPort = mapped ? mapping.externalPort : 0;
|
|
s_state = mapped ? eState_Mapped : eState_Failed;
|
|
}
|
|
}
|
|
if (!IsCurrent(generation))
|
|
{
|
|
if (mapped)
|
|
Remove(mapping);
|
|
return;
|
|
}
|
|
if (!mapped)
|
|
{
|
|
Log("port %d could not be mapped; friends can only join if it is forwarded by hand", port);
|
|
return;
|
|
}
|
|
Log("port %d mapped with %s (external port %d)", port, mapping.method == eMethod_UPnP ? "UPnP" : "NAT-PMP", mapping.externalPort);
|
|
|
|
if (mapping.lease == 0)
|
|
return;
|
|
ULONGLONG nextRefresh = GetTickCount64() + (mapping.lease * 1000ULL) / 2;
|
|
while (IsCurrent(generation))
|
|
{
|
|
Sleep(1000);
|
|
if (GetTickCount64() < nextRefresh)
|
|
continue;
|
|
bool ok = Refresh(mapping);
|
|
nextRefresh = GetTickCount64() + (ok ? (mapping.lease * 1000ULL) / 2 : 60000ULL);
|
|
if (!ok)
|
|
Log("could not renew the port mapping, retrying in a minute");
|
|
std::lock_guard<std::mutex> lock(s_mutex);
|
|
if (generation == s_generation)
|
|
{
|
|
s_mapping = mapping;
|
|
s_externalPort = mapping.externalPort;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void Map(int port)
|
|
{
|
|
std::lock_guard<std::mutex> lock(s_mutex);
|
|
if (s_state == eState_Working || (s_state == eState_Mapped && s_mapping.internalPort == port))
|
|
return;
|
|
++s_generation;
|
|
s_state = eState_Working;
|
|
s_externalPort = 0;
|
|
std::thread(MapWorker, port, s_generation).detach();
|
|
}
|
|
|
|
void Unmap()
|
|
{
|
|
Mapping mapping;
|
|
{
|
|
std::lock_guard<std::mutex> lock(s_mutex);
|
|
++s_generation;
|
|
mapping = s_mapping;
|
|
s_mapping = Mapping();
|
|
s_externalPort = 0;
|
|
s_state = eState_Idle;
|
|
}
|
|
if (mapping.method != eMethod_None)
|
|
std::thread([mapping]() { Remove(mapping); }).detach();
|
|
}
|
|
|
|
EState GetState()
|
|
{
|
|
return static_cast<EState>(s_state.load());
|
|
}
|
|
|
|
int GetExternalPort()
|
|
{
|
|
return s_externalPort.load();
|
|
}
|
|
}
|