2020-04-19 13:14:21 +00:00
|
|
|
#ifdef CONF_UPNP
|
|
|
|
|
2020-09-26 19:41:58 +00:00
|
|
|
#include "upnp.h"
|
|
|
|
#include <base/system.h>
|
|
|
|
#include <engine/shared/config.h>
|
|
|
|
#include <game/version.h>
|
2020-04-19 13:14:21 +00:00
|
|
|
#include <miniupnpc/miniupnpc.h>
|
|
|
|
#include <miniupnpc/upnpcommands.h>
|
|
|
|
#include <miniupnpc/upnperrors.h>
|
|
|
|
|
2022-06-24 12:16:29 +00:00
|
|
|
#include <cstdlib>
|
|
|
|
|
2020-04-19 13:14:21 +00:00
|
|
|
void CUPnP::Open(NETADDR Address)
|
|
|
|
{
|
|
|
|
if(g_Config.m_SvUseUPnP)
|
|
|
|
{
|
|
|
|
m_Enabled = false;
|
|
|
|
m_Addr = Address;
|
2022-06-30 22:36:32 +00:00
|
|
|
m_pUPnPUrls = (struct UPNPUrls *)malloc(sizeof(struct UPNPUrls));
|
|
|
|
m_pUPnPData = (struct IGDdatas *)malloc(sizeof(struct IGDdatas));
|
2020-04-19 13:14:21 +00:00
|
|
|
|
|
|
|
char aLanAddr[64];
|
|
|
|
char aPort[6];
|
|
|
|
int Error;
|
|
|
|
|
2022-06-30 22:36:32 +00:00
|
|
|
m_pUPnPDevice = upnpDiscover(2000, NULL, NULL, 0, 0, 2, &Error);
|
2020-04-19 13:14:21 +00:00
|
|
|
|
2022-06-30 22:36:32 +00:00
|
|
|
int Status = UPNP_GetValidIGD(m_pUPnPDevice, m_pUPnPUrls, m_pUPnPData, aLanAddr, sizeof(aLanAddr));
|
2020-04-19 13:14:21 +00:00
|
|
|
dbg_msg("upnp", "status=%d, lan_addr=%s", Status, aLanAddr);
|
|
|
|
|
|
|
|
if(Status == 1)
|
|
|
|
{
|
|
|
|
m_Enabled = true;
|
2022-06-30 22:36:32 +00:00
|
|
|
dbg_msg("upnp", "found valid IGD: %s", m_pUPnPUrls->controlURL);
|
2020-04-19 13:14:21 +00:00
|
|
|
str_format(aPort, sizeof(aPort), "%d", m_Addr.port);
|
2022-06-30 22:36:32 +00:00
|
|
|
Error = UPNP_AddPortMapping(m_pUPnPUrls->controlURL, m_pUPnPData->first.servicetype,
|
2020-09-26 19:41:58 +00:00
|
|
|
aPort, aPort, aLanAddr,
|
|
|
|
"DDNet Server " GAME_RELEASE_VERSION,
|
|
|
|
"UDP", NULL, "0");
|
2020-04-19 13:14:21 +00:00
|
|
|
|
|
|
|
if(Error)
|
|
|
|
dbg_msg("upnp", "failed to map port, error: %s", strupnperror(Error));
|
|
|
|
else
|
|
|
|
dbg_msg("upnp", "successfully mapped port");
|
|
|
|
}
|
|
|
|
else
|
|
|
|
dbg_msg("upnp", "no valid IGD found, disabled");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void CUPnP::Shutdown()
|
|
|
|
{
|
|
|
|
if(g_Config.m_SvUseUPnP)
|
|
|
|
{
|
|
|
|
if(m_Enabled)
|
|
|
|
{
|
|
|
|
char aPort[6];
|
|
|
|
str_format(aPort, sizeof(aPort), "%d", m_Addr.port);
|
2022-06-30 22:36:32 +00:00
|
|
|
int Error = UPNP_DeletePortMapping(m_pUPnPUrls->controlURL, m_pUPnPData->first.servicetype, aPort, "UDP", NULL);
|
2020-04-19 13:14:21 +00:00
|
|
|
|
|
|
|
if(Error != 0)
|
|
|
|
{
|
|
|
|
dbg_msg("upnp", "failed to delete port mapping on shutdown: %s", strupnperror(Error));
|
|
|
|
}
|
2022-06-30 22:36:32 +00:00
|
|
|
FreeUPNPUrls(m_pUPnPUrls);
|
|
|
|
freeUPNPDevlist(m_pUPnPDevice);
|
2020-04-19 13:14:21 +00:00
|
|
|
}
|
2022-06-30 22:36:32 +00:00
|
|
|
free(m_pUPnPUrls);
|
|
|
|
free(m_pUPnPData);
|
|
|
|
m_pUPnPUrls = NULL;
|
|
|
|
m_pUPnPData = NULL;
|
2020-04-19 13:14:21 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-19 16:57:49 +00:00
|
|
|
#endif
|