- plenty of code cleanup (some refactoring of socket / UPNP code)

- FTP console output now only shows when --verbose used
This commit is contained in:
Mark Vejvoda 2010-12-31 08:21:26 +00:00
parent bd12b10e29
commit d176053da9
12 changed files with 198 additions and 291 deletions

View File

@ -1034,7 +1034,7 @@ int glestMain(int argc, char** argv) {
// Set some statics based on ini entries
SystemFlags::ENABLE_THREADED_LOGGING = config.getBool("ThreadedLogging","true");
FontGl::setDefault_fontType(config.getString("DefaultFont",FontGl::getDefault_fontType().c_str()));
Socket::isUPNP = !config.getBool("DisableUPNP","false");
UPNP_Tools::isUPNP = !config.getBool("DisableUPNP","false");
Texture::useTextureCompression = config.getBool("EnableTextureCompression","false");
// 256 for English
// 30000 for Chinese

View File

@ -62,7 +62,6 @@ typedef struct
char rxBuf[LEN_RXBUF]; ///< receive buffer for ftp commands
char workingDir[MAX_PATH_LEN]; ///< current working directory (absolute path which is relative to the root-path of the user account)
ip_t remoteIp; ///< IP of connected ftp client
//ip_t remoteFTPServerIp; ///< IP of the FTP Server from the clients perspective
port_t remoteFTPServerPassivePort; ///< Port of the FTP Server from the clients perspective related to Passive connection
port_t remotePort; ///< Port of connected ftp client for control connection
port_t remoteDataPort; ///< Port of connected ftp client for data connection

View File

@ -25,22 +25,22 @@
/**
* @brief max. possible simultaneous FTP client connections
*/
#define MAX_CONNECTIONS 10
#define MAX_CONNECTIONS 16
/**
* @brief max. possible user accounts
*/
#define MAX_USERS 10
#define MAX_USERS 16
/**
* @brief max. length of a user account name
*/
#define MAXLEN_USERNAME 10
#define MAXLEN_USERNAME 25
/**
* @brief max. length of a user account password
*/
#define MAXLEN_PASSWORD 10
#define MAXLEN_PASSWORD 25
/**
* @brief session timeout in seconds
@ -76,7 +76,7 @@
/**
* @brief set to 1 to activate debug messages on stdout
*/
#define DBG_LOG 1
//#define DBG_LOG 1
/**
* @brief set to 1 if target-plattform supports ANSI-C file-IO functions

View File

@ -63,6 +63,6 @@ typedef uint16_t port_t;
ip_t (*ftpFindExternalFTPServerIp)(ip_t clientIp);
void (*ftpAddUPNPPortForward)(int internalPort, int externalPort);
void (*ftpRemoveUPNPPortForward)(int internalPort, int externalPort);
int VERBOSE_MODE_ENABLED;
#endif

View File

@ -51,8 +51,11 @@ using namespace Shared::PlatformCommon;
namespace Shared{ namespace Platform {
void AddUPNPPortForward(int internalPort, int externalPort);
void RemoveUPNPPortForward(int internalPort, int externalPort);
// The callback Interface used by the UPNP discovery process
class UPNPInitInterface {
public:
virtual void UPNPInitStatus(bool result) = 0;
};
//
// This interface describes the methods a callback object must implement
@ -157,8 +160,6 @@ public:
uint32 getConnectedIPAddress(string IP="");
static bool isUPNP;
protected:
static void throwException(string str);
};
@ -204,7 +205,21 @@ public:
// =====================================================
// class ServerSocket
// =====================================================
class ServerSocket: public Socket{
class ServerSocket: public Socket, public UPNPInitInterface {
protected:
bool portBound;
int boundPort;
static int externalPort;
static int ftpServerPort;
SDL_Thread *upnpdiscoverThread;
virtual void UPNPInitStatus(bool result);
BroadCastSocketThread *broadCastThread;
void startBroadCastThread();
bool isBroadCastThreadRunning();
public:
ServerSocket();
virtual ~ServerSocket();
@ -226,27 +241,28 @@ public:
virtual void disconnectSocket();
void NETdiscoverUPnPDevices();
};
// =====================================================
// class UPNP_Tools
// =====================================================
class UPNP_Tools {
public:
static bool isUPNP;
static bool enabledUPNP;
static bool upnp_add_redirect(int ports[2]);
static void upnp_rem_redirect(int ext_port);
protected:
bool portBound;
int boundPort;
static int externalPort;
static int ftpServerPort;
BroadCastSocketThread *broadCastThread;
void startBroadCastThread();
bool isBroadCastThreadRunning();
static int upnp_init(void *param);
void NETaddRedirects(int ports[4]);
void NETremRedirects(int ext_port);
static bool upnp_add_redirect(int ports[2]);
static void upnp_rem_redirect(int ext_port);
static void NETaddRedirects(int ports[4]);
static void NETremRedirects(int ext_port);
static void AddUPNPPortForward(int internalPort, int externalPort);
static void RemoveUPNPPortForward(int internalPort, int externalPort);
};
}}//end namespace

View File

@ -78,9 +78,7 @@ int ftpSendMsg(msgmode_E mode, int sessionId, int ret, const char* msg)
sentlen += ftpSend(ftpGetSession(sessionId)->ctrlSocket, "\r\n", 2);
}
#if DBG_LOG
printf("%02d <-- %s%s\n", sessionId, buf, msg);
#endif
if(VERBOSE_MODE_ENABLED) printf("%02d <-- %s%s\n", sessionId, buf, msg);
return sentlen;
}
@ -282,18 +280,15 @@ LOCAL int sendListing(socket_t dataSocket, int sessionId, const char* path, int
ftpGetLocalTime(&currTime);
ftpSendMsg(MSG_NORMAL, sessionId, 150, ftpMsg010);
#if DBG_LOG
printf("about to read dir contents [%s]\n", path);
#endif
if(VERBOSE_MODE_ENABLED) printf("about to read dir contents [%s]\n", path);
haveAnySuccessfulFiles = 0;
while((dirEntry = ftpReadDir(dir)) != NULL)
{
const char * realPath = ftpGetRealPath(sessionId, dirEntry, FALSE);
int statResult = ftpStat(realPath, &fileInfo);
#if DBG_LOG
printf("ftpGetRealPath() returned [%s] stat() = %d\n", realPath, statResult);
#endif
if(VERBOSE_MODE_ENABLED) printf("ftpGetRealPath() returned [%s] stat() = %d\n", realPath, statResult);
if(statResult == 0)
{
@ -401,9 +396,7 @@ LOCAL int sendListing(socket_t dataSocket, int sessionId, const char* path, int
}
else
{
#if DBG_LOG
printf("opendir [%s] returned errno: %#x\n", path,errno);
#endif
if(VERBOSE_MODE_ENABLED) printf("opendir [%s] returned errno: %#x\n", path,errno);
ftpSendMsg(MSG_NORMAL, sessionId, 451, ftpMsg038);
}
@ -491,14 +484,10 @@ LOCAL int ftpCmdRetr(int sessionId, const char* args, int len)
void *fp;
int statResult = 0;
#if DBG_LOG
printf("ftpCmdRetr args [%s] realPath [%s]\n", args, realPath);
#endif
if(VERBOSE_MODE_ENABLED) printf("ftpCmdRetr args [%s] realPath [%s]\n", args, realPath);
statResult = ftpStat(realPath, &fileInfo);
#if DBG_LOG
printf("stat() = %d fileInfo.type = %d\n", statResult,fileInfo.type);
#endif
if(VERBOSE_MODE_ENABLED) printf("stat() = %d fileInfo.type = %d\n", statResult,fileInfo.type);
if(statResult || (fileInfo.type != TYPE_FILE)) // file accessible?
{
@ -682,18 +671,14 @@ LOCAL int ftpCmdPasv(int sessionId, const char* args, int len)
}
ftpGetSession(sessionId)->passiveDataSocket = s;
#if DBG_LOG
printf("In ftpCmdPasv sessionId = %d, client IP = %u, remote IP = %u, port = %d, ftpAddUPNPPortForward = %p, ftpRemoveUPNPPortForward = %p\n",
if(VERBOSE_MODE_ENABLED) printf("In ftpCmdPasv sessionId = %d, client IP = %u, remote IP = %u, port = %d, ftpAddUPNPPortForward = %p, ftpRemoveUPNPPortForward = %p\n",
sessionId, ftpGetSession(sessionId)->remoteIp, ftpFindExternalFTPServerIp(ftpGetSession(sessionId)->remoteIp), port,ftpAddUPNPPortForward,ftpRemoveUPNPPortForward);
#endif
if(ftpFindExternalFTPServerIp(ftpGetSession(sessionId)->remoteIp) != 0)
{
ftpGetSession(sessionId)->remoteFTPServerPassivePort = port;
if(ftpAddUPNPPortForward) {
#if DBG_LOG
printf("In ftpCmdPasv sessionId = %d, adding UPNP port forward\n", sessionId);
#endif
if(VERBOSE_MODE_ENABLED) printf("In ftpCmdPasv sessionId = %d, adding UPNP port forward\n", sessionId);
ftpAddUPNPPortForward(port, port);
}
@ -709,9 +694,7 @@ LOCAL int ftpCmdPasv(int sessionId, const char* args, int len)
(port >> 8) & 0xFF,
port & 0xFF);
#if DBG_LOG
printf("In ftpCmdPasv sessionId = %d, str [%s]\n", sessionId, str);
#endif
if(VERBOSE_MODE_ENABLED) printf("In ftpCmdPasv sessionId = %d, str [%s]\n", sessionId, str);
}
else
@ -965,9 +948,7 @@ void ftpParseCmd(int sessionId)
pSession->rxBuf[c] = toupper(pSession->rxBuf[c]);
}
#if DBG_LOG
printf("%02d --> %s\n", sessionId, pSession->rxBuf);
#endif
if(VERBOSE_MODE_ENABLED) printf("%02d --> %s\n", sessionId, pSession->rxBuf);
if(execFtpCmd(sessionId, pSession->rxBuf, len - 2) == -1)
{
@ -980,9 +961,8 @@ void ftpParseCmd(int sessionId)
{
pSession->rxBufWriteIdx = 0;
ftpSendMsg(MSG_NORMAL, sessionId, 500, ftpMsg035);
#if DBG_LOG
printf("Receive buffer overflow. Received data discarded.\n");
#endif
if(VERBOSE_MODE_ENABLED) printf("Receive buffer overflow. Received data discarded.\n");
}
}

View File

@ -48,28 +48,23 @@ int ftpStart(int portNumber)
{
server = -1; // set server socket to invalid value
#if DBG_LOG
printf("Feathery FTP-Server\n");
#endif
if(VERBOSE_MODE_ENABLED) printf("Feathery FTP-Server\n");
ftpArchInit();
#if DBG_LOG
printf(". Creating server socket");
#endif
if(VERBOSE_MODE_ENABLED) printf("Creating server socket");
server = ftpCreateServerSocket(portNumber); // create main listener socket
if(server < 0)
{
#if DBG_LOG
printf("\t\terror\n");
#endif
if(VERBOSE_MODE_ENABLED) printf("\t\terror\n");
return -1;
}
#if DBG_LOG
printf("\t\tok\n");
printf("Server successfully startet\n");
#endif
if(VERBOSE_MODE_ENABLED) printf("\t\tok\n");
if(VERBOSE_MODE_ENABLED) printf("Server successfully started\n");
ftpTrackSocket(server); // add socket to "watchlist"
return 0;
@ -143,9 +138,8 @@ void ftpExecute(void)
}
else
{
#if DBG_LOG
printf("Connection refused; Session limit reached.\n");
#endif
if(VERBOSE_MODE_ENABLED) printf("Connection refused; Session limit reached.\n");
ftpCloseSocket(clientSocket);
}
}

View File

@ -119,18 +119,14 @@ int ftpAuthSession(int id)
*/
int ftpCloseSession(int id)
{
#if DBG_LOG
printf("In ftpCloseSession sessionId = %d, remote IP = %u, port = %d\n",
if(VERBOSE_MODE_ENABLED) printf("In ftpCloseSession sessionId = %d, remote IP = %u, port = %d\n",
id, sessions[id].remoteIp, sessions[id].remoteFTPServerPassivePort);
#endif
if(ftpFindExternalFTPServerIp != NULL && ftpFindExternalFTPServerIp(sessions[id].remoteIp) != 0)
{
if(ftpRemoveUPNPPortForward)
{
#if DBG_LOG
printf("In ftpCmdPasv sessionId = %d, removing UPNP port forward [%d]\n", id,sessions[id].remoteFTPServerPassivePort);
#endif
if(VERBOSE_MODE_ENABLED) printf("In ftpCmdPasv sessionId = %d, removing UPNP port forward [%d]\n", id,sessions[id].remoteFTPServerPassivePort);
ftpRemoveUPNPPortForward(sessions[id].remoteFTPServerPassivePort, sessions[id].remoteFTPServerPassivePort);
}
@ -140,9 +136,7 @@ int ftpCloseSession(int id)
sessions[id].open = FALSE;
#if DBG_LOG
printf("Session %d closed\n", id);
#endif
if(VERBOSE_MODE_ENABLED) printf("Session %d closed\n", id);
return 0;
}
@ -248,9 +242,7 @@ const char* ftpGetRealPath(int id, const char* path, int normalize)
ftpRoot = ftpGetRoot(sessions[id].userId, &len);
#if DBG_LOG
printf("#1 ftpGetRealPath id = %d path [%s] ftpRoot [%s] sessions[id].workingDir [%s] normalize = %d\n", id, path, ftpRoot, sessions[id].workingDir,normalize);
#endif
if(VERBOSE_MODE_ENABLED) printf("#1 ftpGetRealPath id = %d path [%s] ftpRoot [%s] sessions[id].workingDir [%s] normalize = %d\n", id, path, ftpRoot, sessions[id].workingDir,normalize);
pathScratchBuf[0]='\0';
if(path[0] == '/' || strcmp(path,sessions[id].workingDir) == 0) // absolute path?
@ -263,9 +255,7 @@ const char* ftpGetRealPath(int id, const char* path, int normalize)
//ftpMergePaths(pathScratchBuf, ftpRoot, path, NULL);
}
#if DBG_LOG
printf("#2 ftpGetRealPath path [%s] ftpRoot [%s] pathScratchBuf [%s]\n", path, ftpRoot, pathScratchBuf);
#endif
if(VERBOSE_MODE_ENABLED) printf("#2 ftpGetRealPath path [%s] ftpRoot [%s] pathScratchBuf [%s]\n", path, ftpRoot, pathScratchBuf);
ftpRemoveDoubleSlash(pathScratchBuf);
if(normalize) {
@ -273,9 +263,7 @@ const char* ftpGetRealPath(int id, const char* path, int normalize)
}
ftpRemoveTrailingSlash(pathScratchBuf);
#if DBG_LOG
printf("#2 ftpGetRealPath path [%s] ftpRoot [%s] pathScratchBuf [%s]\n", path, ftpRoot, pathScratchBuf);
#endif
if(VERBOSE_MODE_ENABLED) printf("#2 ftpGetRealPath path [%s] ftpRoot [%s] pathScratchBuf [%s]\n", path, ftpRoot, pathScratchBuf);
return pathScratchBuf;
}
@ -299,9 +287,7 @@ int ftpChangeDir(int id, const char* path)
if(len == 1) // if len == 1 root-path == '/'
len = 0;
#if DBG_LOG
printf("ftpChangeDir path [%s] realPath [%s] sessions[id].workingDir [%s]\n", path, realPath, sessions[id].workingDir);
#endif
if(VERBOSE_MODE_ENABLED) printf("ftpChangeDir path [%s] realPath [%s] sessions[id].workingDir [%s]\n", path, realPath, sessions[id].workingDir);
if(ftpStat(realPath, &fileInfo) || (fileInfo.type != TYPE_DIR)) // directory accessible?
return -2;
@ -310,9 +296,7 @@ int ftpChangeDir(int id, const char* path)
if(sessions[id].workingDir[0] == '\0')
strcpy(sessions[id].workingDir, "/");
#if DBG_LOG
printf("ftpChangeDir path [%s] realPath [%s] NEW sessions[id].workingDir [%s]\n", path, realPath, sessions[id].workingDir);
#endif
if(VERBOSE_MODE_ENABLED) printf("ftpChangeDir path [%s] realPath [%s] NEW sessions[id].workingDir [%s]\n", path, realPath, sessions[id].workingDir);
return 0;
}

View File

@ -38,7 +38,6 @@
#include "ftp.h"
ip_t ownIp;
//ip_t ownExternalIp;
LOCAL fd_set watchedSockets;
LOCAL fd_set signaledSockets;
@ -48,7 +47,6 @@ LOCAL int maxSockNr;
void ftpArchInit()
{
ownIp = 0;
//ownExternalIp = externalIp;
maxSockNr = 0;
FD_ZERO(&watchedSockets);
FD_ZERO(&signaledSockets);
@ -263,9 +261,6 @@ socket_t ftpEstablishDataConnection(int passive, ip_t *ip, port_t *port)
*port = ntohs(myAddr.sin_port);
*ip = ownIp;
//if(ownExternalIp > 0) {
// *ip = ownExternalIp;
//}
if(listen(dataSocket, 1))
{
@ -339,16 +334,14 @@ socket_t ftpAcceptServerConnection(socket_t server, ip_t *remoteIP, port_t *remo
len = sizeof(sockinfo);
if(getsockname(clientSocket, (struct sockaddr *)&sockinfo, &len))
{
#if DBG_LOG
printf("getsockname error\n");
#endif
if(VERBOSE_MODE_ENABLED) printf("getsockname error\n");
}
ownIp = ntohl(sockinfo.sin_addr.s_addr); // eigene IP-Adresse abspeichern (wird dir PASV benätigt)
}
#if DBG_LOG
printf("Verbindung mit %s auf Port %d akzeptiert.\n", inet_ntoa(sockinfo.sin_addr), *remotePort);
#endif
if(VERBOSE_MODE_ENABLED) printf("Connection with %s on Port %d accepted.\n", inet_ntoa(sockinfo.sin_addr), *remotePort);
return clientSocket;
}

View File

@ -33,7 +33,6 @@
#pragma comment(lib, "MSWSOCK")
ip_t ownIp;
//ip_t ownExternalIp;
LOCAL fd_set watchedSockets;
LOCAL fd_set signaledSockets;
@ -43,7 +42,6 @@ void ftpArchInit()
{
WSADATA wsaData;
ownIp = 0;
//ownExternalIp = externalIp;
maxSockNr = 0;
FD_ZERO(&watchedSockets);
WSAStartup(MAKEWORD(2, 0),&wsaData);
@ -293,9 +291,6 @@ socket_t ftpEstablishDataConnection(int passive, ip_t *ip, port_t *port)
*port = ntohs(myAddr.sin_port);
*ip = ownIp;
//if(ownExternalIp > 0) {
// *ip = ownExternalIp;
//}
if(listen(dataSocket, 1))
{
@ -376,16 +371,14 @@ socket_t ftpAcceptServerConnection(socket_t server, ip_t *remoteIP, port_t *remo
len = sizeof(sockinfo);
if(getsockname(clientSocket, (struct sockaddr *)&sockinfo, &len))
{
#if DBG_LOG
printf("getsockname error\n");
#endif
if(VERBOSE_MODE_ENABLED) printf("getsockname error\n");
}
ownIp = ntohl(sockinfo.sin_addr.s_addr); // eigene IP-Adresse abspeichern (wird dir PASV benätigt)
}
#if DBG_LOG
printf("Verbindung mit %s auf Port %d akzeptiert.\n", inet_ntoa(sockinfo.sin_addr), *remotePort);
#endif
if(VERBOSE_MODE_ENABLED) printf("Connection with %s on Port %d accepted.\n", inet_ntoa(sockinfo.sin_addr), *remotePort);
return clientSocket;
}

View File

@ -39,17 +39,15 @@ uint32 FindExternalFTPServerIp(uint32 clientIp) {
FTPServerThread::FTPServerThread(std::pair<string,string> mapsPath,int portNumber) : BaseThread() {
this->mapsPath = mapsPath;
this->portNumber = portNumber;
//this->externalIp = externalIp;
//void (*ftpAddUPNPPortForward)(int internalPort, int externalPort) = NULL;
//void (*ftpRemoveUPNPPortForward)(int internalPort, int externalPort) = NULL;
ftpAddUPNPPortForward = &AddUPNPPortForward;
ftpRemoveUPNPPortForward = &RemoveUPNPPortForward;
ftpAddUPNPPortForward = &UPNP_Tools::AddUPNPPortForward;
ftpRemoveUPNPPortForward = &UPNP_Tools::RemoveUPNPPortForward;
ftpFindExternalFTPServerIp = &FindExternalFTPServerIp;
VERBOSE_MODE_ENABLED = SystemFlags::VERBOSE_MODE_ENABLED;
}
FTPServerThread::~FTPServerThread() {
ServerSocket::upnp_rem_redirect(ServerSocket::getFTPServerPort());
UPNP_Tools::upnp_rem_redirect(ServerSocket::getFTPServerPort());
}
void FTPServerThread::signalQuit() {
@ -67,9 +65,7 @@ bool FTPServerThread::shutdownAndWait() {
}
void FTPServerThread::addClientToServerIPAddress(uint32 clientIp,uint32 ServerIp) {
//ftpSetSessionRemoteServerIp(clientIp, ServerIp);
clientToFTPServerList[clientIp] = ServerIp;
if(SystemFlags::VERBOSE_MODE_ENABLED) printf ("===> FTP Server thread clientIp = %u, ServerIp = %u\n",clientIp,ServerIp);
}
@ -125,10 +121,6 @@ void FTPServerThread::execute() {
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] FTP Server thread is exiting\n",__FILE__,__FUNCTION__,__LINE__);
}
// Delete ourself when the thread is done (no other actions can happen after this
// such as the mutex which modifies the running status of this method
//delete this;
}
}}//end namespace

View File

@ -43,7 +43,6 @@
#include <netdb.h>
#include <netinet/in.h>
#include <net/if.h>
//#include <sys/ioctl.h>
#endif
@ -64,20 +63,18 @@ namespace Shared{ namespace Platform{
int Socket::broadcast_portno = 61357;
int ServerSocket::ftpServerPort = 61358;
int ServerSocket::externalPort = Socket::broadcast_portno;
BroadCastClientSocketThread *ClientSocket::broadCastClientThread = NULL;
//
// UPnP - Start
//
SDL_Thread *upnpdiscover = NULL;
static struct UPNPUrls urls;
static struct IGDdatas data;
// local ip address
static char lanaddr[16] = "";
bool Socket::isUPNP = true;
int ServerSocket::externalPort = Socket::broadcast_portno;
bool ServerSocket::enabledUPNP = false;
bool UPNP_Tools::isUPNP = true;
bool UPNP_Tools::enabledUPNP = false;
// UPnP - End
#ifdef WIN32
@ -1671,6 +1668,7 @@ void BroadCastClientSocketThread::execute() {
ServerSocket::ServerSocket() : Socket() {
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
upnpdiscoverThread = NULL;
portBound = false;
broadCastThread = NULL;
@ -1681,10 +1679,15 @@ ServerSocket::~ServerSocket() {
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
stopBroadCastThread();
if (ServerSocket::enabledUPNP) {
ServerSocket::enabledUPNP = false;
NETremRedirects(ServerSocket::externalPort);
if(upnpdiscoverThread != NULL) {
SDL_WaitThread(upnpdiscoverThread, NULL);
upnpdiscoverThread = NULL;
}
if (UPNP_Tools::enabledUPNP) {
UPNP_Tools::NETremRedirects(ServerSocket::externalPort);
UPNP_Tools::enabledUPNP = false;
}
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
@ -1852,106 +1855,70 @@ Socket *ServerSocket::accept() {
return result;
}
void AddUPNPPortForward(int internalPort, int externalPort) {
struct UPNPDev *devlist=NULL;
struct UPNPDev *dev=NULL;
char *descXML=NULL;
int descXMLsize = 0;
char buf[255]="";
//int *externalPort = (int *)asdf;
void ServerSocket::NETdiscoverUPnPDevices() {
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] UPNP - Start\n",__FILE__,__FUNCTION__,__LINE__);
memset(&urls, 0, sizeof(struct UPNPUrls));
memset(&data, 0, sizeof(struct IGDdatas));
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"Socket::isUPNP = %d\n", Socket::isUPNP);
if(Socket::isUPNP) {
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"Searching for UPnP devices for automatic port forwarding...\n");
devlist = upnpDiscover(2000, NULL, NULL, 0);
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"UPnP device search finished.\n");
if (devlist) {
dev = devlist;
while (dev) {
if (strstr(dev->st, "InternetGatewayDevice"))
break;
dev = dev->pNext;
}
if (!dev) {
dev = devlist; /* defaulting to first device */
if(upnpdiscoverThread != NULL) {
SDL_WaitThread(upnpdiscoverThread, NULL);
upnpdiscoverThread = NULL;
}
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"UPnP device found: %s %s\n", dev->descURL, dev->st);
descXML = (char *)miniwget_getaddr(dev->descURL, &descXMLsize, lanaddr, sizeof(lanaddr));
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"LAN address: %s\n", lanaddr);
if (descXML) {
parserootdesc (descXML, descXMLsize, &data);
free (descXML); descXML = 0;
GetUPNPUrls (&urls, &data, dev->descURL);
}
sprintf(buf, "UPnP device found: %s %s LAN address %s", dev->descURL, dev->st, lanaddr);
//addDumpInfo(buf);
freeUPNPDevlist(devlist);
if (!urls.controlURL || urls.controlURL[0] == '\0') {
sprintf(buf, "controlURL not available, UPnP disabled");
//addDumpInfo(buf);
//obj->DiscoveredServers();
//return false;
return;
// WATCH OUT! Because the thread takes void * as a parameter we MUST cast to the pointer type
// used on the other side (inside the thread)
upnpdiscoverThread = SDL_CreateThread(&UPNP_Tools::upnp_init, dynamic_cast<UPNPInitInterface *>(this));
}
//obj->DiscoveredServers();
void ServerSocket::UPNPInitStatus(bool result) {
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] result = %d\n",__FILE__,__FUNCTION__,__LINE__,result);
if(result == true) {
int ports[4] = { this->getExternalPort(), this->getBindPort(), this->getFTPServerPort(), this->getFTPServerPort() };
UPNP_Tools::NETaddRedirects(ports);
}
}
//
// UPNP Tools Start
//
void UPNP_Tools::AddUPNPPortForward(int internalPort, int externalPort) {
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] internalPort = %d, externalPort = %d\n",__FILE__,__FUNCTION__,__LINE__,internalPort,externalPort);
bool addPorts = (UPNP_Tools::enabledUPNP == true);
if(addPorts == false) {
int result = UPNP_Tools::upnp_init(NULL);
addPorts = (result != 0);
}
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] internalPort = %d, externalPort = %d, addPorts = %d\n",__FILE__,__FUNCTION__,__LINE__,internalPort,externalPort,addPorts);
if(addPorts == true) {
int ports[2] = { externalPort, internalPort };
ServerSocket::upnp_add_redirect(ports);
ServerSocket::enabledUPNP = true;
//return true;
return;
}
sprintf(buf, "UPnP device not found.");
//addDumpInfo(buf);
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"No UPnP devices found.\n");
//obj->DiscoveredServers();
//return false;
return;
}
else {
sprintf(buf, "UPnP detection routine disabled by user.");
//addDumpInfo(buf);
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"UPnP detection routine disabled by user.\n");
//obj->DiscoveredServers();
//return false;
return;
UPNP_Tools::upnp_add_redirect(ports);
}
}
void RemoveUPNPPortForward(int internalPort, int externalPort) {
ServerSocket::upnp_rem_redirect(externalPort);
void UPNP_Tools::RemoveUPNPPortForward(int internalPort, int externalPort) {
UPNP_Tools::upnp_rem_redirect(externalPort);
}
//
// This code below handles Universal Plug and Play Router Port Forwarding
// This code below handles Universal Plug and Play Router Discovery
//
int ServerSocket::upnp_init(void *param) {
int UPNP_Tools::upnp_init(void *param) {
struct UPNPDev *devlist = NULL;
struct UPNPDev *dev = NULL;
char *descXML = NULL;
int descXMLsize = 0;
char buf[255] = "";
//int *externalPort = (int *)asdf;
ServerSocket *srv = (ServerSocket *)param;
int ports[4] = { externalPort, srv->getBindPort(), ftpServerPort, ftpServerPort };
// Callers MUST pass in NULL or a UPNPInitInterface *
UPNPInitInterface *callback = (UPNPInitInterface *)(param);
memset(&urls, 0, sizeof(struct UPNPUrls));
memset(&data, 0, sizeof(struct IGDdatas));
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"Socket::isUPNP = %d\n", Socket::isUPNP);
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] isUPNP = %d callback = %p\n",__FILE__,__FUNCTION__,__LINE__,UPNP_Tools::isUPNP,callback);
if(Socket::isUPNP) {
if(UPNP_Tools::isUPNP) {
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"Searching for UPnP devices for automatic port forwarding...\n");
devlist = upnpDiscover(2000, NULL, NULL, 0);
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"UPnP device search finished.\n");
@ -1959,8 +1926,9 @@ int ServerSocket::upnp_init(void *param) {
if (devlist) {
dev = devlist;
while (dev) {
if (strstr(dev->st, "InternetGatewayDevice"))
if (strstr(dev->st, "InternetGatewayDevice")) {
break;
}
dev = dev->pNext;
}
if (!dev) {
@ -1977,109 +1945,97 @@ int ServerSocket::upnp_init(void *param) {
GetUPNPUrls (&urls, &data, dev->descURL);
}
sprintf(buf, "UPnP device found: %s %s LAN address %s", dev->descURL, dev->st, lanaddr);
//addDumpInfo(buf);
freeUPNPDevlist(devlist);
if (!urls.controlURL || urls.controlURL[0] == '\0') {
sprintf(buf, "controlURL not available, UPnP disabled");
//addDumpInfo(buf);
//obj->DiscoveredServers();
if(callback) {
callback->UPNPInitStatus(false);
}
return false;
}
//obj->DiscoveredServers();
srv->NETaddRedirects(ports);
ServerSocket::enabledUPNP = true;
char externalIP[16] = "";
UPNP_GetExternalIPAddress(urls.controlURL, data.servicetype, externalIP);
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"UPnP device found at: [%s] callback [%p]\n",externalIP,callback);
//UPNP_Tools::NETaddRedirects(ports);
UPNP_Tools::enabledUPNP = true;
if(callback) {
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
callback->UPNPInitStatus(true);
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
}
return true;
}
sprintf(buf, "UPnP device not found.");
//addDumpInfo(buf);
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"No UPnP devices found.\n");
//obj->DiscoveredServers();
if(callback) {
callback->UPNPInitStatus(false);
}
return false;
}
else {
sprintf(buf, "UPnP detection routine disabled by user.");
//addDumpInfo(buf);
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"UPnP detection routine disabled by user.\n");
//obj->DiscoveredServers();
if(callback) {
callback->UPNPInitStatus(false);
}
return false;
}
}
bool ServerSocket::upnp_add_redirect(int ports[2]) {
bool UPNP_Tools::upnp_add_redirect(int ports[2]) {
char externalIP[16] = "";
char ext_port_str[16] = "";
char int_port_str[16] = "";
int r = 0;
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"upnp_add_redir(%d : %d) (%d : %d)\n", ports[0],ports[1],ports[2],ports[3]);
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] upnp_add_redir(%d : %d)\n",__FILE__,__FUNCTION__,__LINE__,ports[0],ports[1]);
UPNP_GetExternalIPAddress(urls.controlURL, data.servicetype, externalIP);
sprintf(ext_port_str, "%d", ports[0]);
sprintf(int_port_str, "%d", ports[1]);
r = UPNP_AddPortMapping(urls.controlURL, data.servicetype,
ext_port_str, int_port_str, lanaddr, "MegaGlest - www.megaglest.org", "TCP", 0);
r = UPNP_AddPortMapping(urls.controlURL, data.servicetype,ext_port_str, int_port_str, lanaddr, "MegaGlest - www.megaglest.org", "TCP", 0);
if (r != UPNPCOMMAND_SUCCESS) {
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"AddPortMapping(%s, %s, %s) failed\n", ext_port_str, int_port_str, lanaddr);
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] AddPortMapping(%s, %s, %s) failed\n",__FILE__,__FUNCTION__,__LINE__,ext_port_str, int_port_str, lanaddr);
return false;
}
//sprintf(ext_port_str, "%d", ports[2]);
//sprintf(int_port_str, "%d", ports[3]);
//r = UPNP_AddPortMapping(urls.controlURL, data.servicetype,
// ext_port_str, int_port_str, lanaddr, "MegaGlest (FTP) - www.megaglest.org", "TCP", 0);
//if (r != UPNPCOMMAND_SUCCESS) {
// SystemFlags::OutputDebug(SystemFlags::debugNetwork,"AddPortMapping(%s, %s, %s) failed\n", ext_port_str, int_port_str, lanaddr);
//return false;
//}
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] AddPortMapping(%s, %s, %s) success\n",__FILE__,__FUNCTION__,__LINE__,ext_port_str, int_port_str, lanaddr);
return true;
}
void ServerSocket::upnp_rem_redirect(int ext_port) {
void UPNP_Tools::upnp_rem_redirect(int ext_port) {
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] upnp_rem_redir(%d)\n",__FILE__,__FUNCTION__,__LINE__,ext_port);
char ext_port_str[16]="";
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"upnp_rem_redir(%d)\n", ext_port);
sprintf(ext_port_str, "%d", ext_port);
UPNP_DeletePortMapping(urls.controlURL, data.servicetype, ext_port_str, "TCP", 0);
}
void ServerSocket::NETaddRedirects(int ports[4]) {
SystemFlags::OutputDebug(SystemFlags::debugNetwork, "%s\n", __FUNCTION__);
//if (!upnp_done)
//{
// SDL_WaitThread(upnpdiscover, &upnp);
// upnp_done = true;
//}
//if (upnp) {
void UPNP_Tools::NETaddRedirects(int ports[4]) {
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] upnp_rem_redir(%d)\n",__FILE__,__FUNCTION__,__LINE__);
int portsA[2] = { ports[0], ports[1] };
upnp_add_redirect(portsA);
int portsB[2] = { ports[2], ports[3] };
upnp_add_redirect(portsB);
//}
}
void ServerSocket::NETremRedirects(int ext_port) {
SystemFlags::OutputDebug(SystemFlags::debugNetwork, "%s\n", __FUNCTION__);
//if (ServerSocket::enabledUPNP) {
//ServerSocket::enabledUPNP = false;
void UPNP_Tools::NETremRedirects(int ext_port) {
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] upnp_rem_redir(%d)\n",__FILE__,__FUNCTION__,__LINE__);
upnp_rem_redirect(ext_port);
//}
}
void ServerSocket::NETdiscoverUPnPDevices() {
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] UPNP - Start\n",__FILE__,__FUNCTION__,__LINE__);
upnpdiscover = SDL_CreateThread(&upnp_init, this);
}
// END UPNP
//
// UPNP Tools END
//
//=======================================================================
// Function : broadcast_thread