You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
513 lines
17 KiB
513 lines
17 KiB
#ifndef _SERVER_CORE_SERVER_MODULE_
|
|
#define _SERVER_CORE_SERVER_MODULE_
|
|
|
|
|
|
#include <stdio.h>
|
|
#include <signal.h>
|
|
#ifndef __linux__
|
|
#ifndef WIN32_LEAN_AND_MEAN
|
|
#define WIN32_LEAN_AND_MEAN
|
|
// #include <WinSock2.h>
|
|
#include <windows.h>
|
|
#include <winsock2.h>
|
|
#include <ws2tcpip.h>
|
|
#endif
|
|
#else
|
|
#include <sys/socket.h>
|
|
#include <netinet/in.h>
|
|
#include <netinet/ip.h>
|
|
#include <netdb.h>
|
|
#include <sys/un.h>
|
|
#include <sys/types.h>
|
|
#include <fcntl.h>
|
|
#include <sys/ioctl.h>
|
|
#include <unistd.h>
|
|
#include <errno.h>
|
|
#endif
|
|
|
|
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <vector>
|
|
|
|
#include "../../components/base/basicTypes.h"
|
|
#include "../../components/base/basicThread.h"
|
|
#include "../../components/base/basicLogCollection.h"
|
|
#include "../../components/base/basicLogCollection.h"
|
|
#include "../../components/base/basicSettingsProvider.h"
|
|
#include "../../components/base/basicEngine.h"
|
|
#include "../../components/base/basicEventHeap.h"
|
|
#include "../protocol/protocol.h"
|
|
#include "netClientHandler.h"
|
|
|
|
|
|
#define NWS_SETTINGS_HOST "NW_HOSTNAME_IP"
|
|
#define NWS_SETTINGS_PORT "NW_LISTEN_PORT"
|
|
|
|
//typedef _Primitive_Ring<_Core_Channel> ChannelsRing;
|
|
//typedef std::vector<networkClientHandler *> vectorNetHandlers;
|
|
|
|
#define UNIX_PATH_MAX 108
|
|
|
|
//void signal_void_handler( int SIG );
|
|
|
|
template <class HANDLER, class ENGINE> class networkServer : public basicThread, public basicEventHandler{
|
|
private:
|
|
basicLogCollection * m_pLog;
|
|
//vectorNetHandlers m_vHandlersPool;
|
|
std::vector<HANDLER *> m_vHandlersPool;
|
|
//basicEngine *m_pEngine;
|
|
ENGINE * m_pEngine;
|
|
config_setting_t * m_pSettings;
|
|
struct sockaddr * MainSocketAddress;
|
|
CSTR m_pHostName;
|
|
uint16_t m_nPortNumber;
|
|
#ifdef __linux__
|
|
int MainSocket;
|
|
#else
|
|
SOCKET MainSocket;
|
|
#endif
|
|
U8 m_bConnectionType;
|
|
protected:
|
|
void m_fThreadProc( void );
|
|
public:
|
|
explicit networkServer( config_setting_t *Settings = NULL );
|
|
virtual ~networkServer();
|
|
bool BootUp( void ); // Config By Settings provided in constructor, on fail uses next BootUp
|
|
bool BootUp( U16 Port ); // Uses Default Hostname and Port as parameter, on fail (getlocalhost) uses next Bootup
|
|
bool BootUp( CSTR HOST_NAME, U16 Port ); // Uses parameters
|
|
#ifdef __linux__
|
|
bool BootUp( CSTR UNIX_SOCKET_NAME );
|
|
#endif
|
|
bool attachEngine(ENGINE *ptr);
|
|
void dispatchEvent( basicEvent *Evt );
|
|
};
|
|
|
|
#define LOG( X ) m_pLog->Log( "networkServer", this, X )
|
|
#define LOG_ERROR( X ) m_pLog->Log( "networkServer", this, _LOG_ERROR, X )
|
|
|
|
//void signal_void_handler(int SIG){
|
|
//};
|
|
|
|
template <class HANDLER, class ENGINE> networkServer<HANDLER, ENGINE>::networkServer(config_setting_t *Settings) : basicThread(), basicEventHandler() {
|
|
m_pLog = basicLogCollection::getInstance();
|
|
m_bConnectionType = 0;
|
|
m_vHandlersPool.clear();
|
|
MainSocketAddress = NULL;
|
|
if (Settings != NULL) {
|
|
m_pSettings = Settings;
|
|
} else {
|
|
m_pSettings = basicSettingsProvider::getInstance()->getSubNode(NULL, "NETWORK_SERVER");
|
|
};
|
|
};
|
|
|
|
template <class HANDLER, class ENGINE> networkServer<HANDLER, ENGINE>::~networkServer(){
|
|
m_bThreadStatus = TH_ENDED;
|
|
if (m_pHostName != NULL) free(m_pHostName);
|
|
};
|
|
|
|
template <class HANDLER, class ENGINE> bool networkServer<HANDLER, ENGINE>::BootUp(void){
|
|
config_setting_t *pSetting;
|
|
int tVal;
|
|
char tBuffer[CTEXT];
|
|
m_pHostName = NULL;
|
|
if (m_pSettings != NULL) {
|
|
LOG("NetServer Getting Settings ...");
|
|
if (!config_setting_lookup_string(m_pSettings, NWS_SETTINGS_HOST, (const char**)&m_pHostName)){
|
|
m_pHostName = (CSTR)malloc(CTEXT);
|
|
sprintf(m_pHostName, "localhost");
|
|
pSetting = config_setting_add(m_pSettings, NWS_SETTINGS_HOST, CONFIG_TYPE_STRING);
|
|
config_setting_set_string(pSetting, m_pHostName);
|
|
basicSettingsProvider::getInstance()->compromise();
|
|
LOG("No Host defined");
|
|
}
|
|
else {
|
|
sprintf(tBuffer, "1 Read From Settings: %s", m_pHostName);
|
|
LOG(tBuffer);
|
|
};
|
|
if (!config_setting_lookup_int(m_pSettings, NWS_SETTINGS_PORT, &tVal)){
|
|
m_nPortNumber = 2222;
|
|
pSetting = config_setting_add(m_pSettings, NWS_SETTINGS_PORT, CONFIG_TYPE_INT);
|
|
config_setting_set_int(pSetting, m_nPortNumber);
|
|
basicSettingsProvider::getInstance()->compromise();
|
|
LOG("No Port defined");
|
|
}
|
|
else {
|
|
m_nPortNumber = tVal;
|
|
sprintf(tBuffer, "2 Read From Settings: %d", m_nPortNumber);
|
|
LOG(tBuffer);
|
|
};
|
|
if (basicSettingsProvider::getInstance()->isCompromised()) basicSettingsProvider::getInstance()->validate();
|
|
return BootUp(m_pHostName, m_nPortNumber);
|
|
} else {
|
|
// Last try to bootup by detecting host and default port 2222
|
|
return BootUp(2222);
|
|
};
|
|
};
|
|
|
|
template <class HANDLER, class ENGINE> bool networkServer<HANDLER, ENGINE>::BootUp(CSTR HOST_NAME, U16 PORT){
|
|
char temp[CTEXT];
|
|
#ifdef __linux__
|
|
int RetCode;
|
|
struct hostent *h_info;
|
|
|
|
LOG("Core BootUp");
|
|
|
|
MainSocket = socket(AF_INET, SOCK_STREAM, 0);
|
|
if (MainSocket == -1){
|
|
LOG_ERROR("Some throuble with networking on this machine (Socket Error)!");
|
|
return false;
|
|
};
|
|
MainSocketAddress = NULL;
|
|
MainSocketAddress = (struct sockaddr *) malloc(sizeof(struct sockaddr_in));
|
|
if (MainSocketAddress == NULL){
|
|
LOG_ERROR("Some throuble with networking on this machine (Cannot Alloc Sockaddr Struct)!");
|
|
return false;
|
|
};
|
|
bzero(MainSocketAddress, sizeof(struct sockaddr_in));
|
|
h_info = gethostbyname(HOST_NAME);
|
|
if (h_info == NULL){
|
|
LOG_ERROR("Some throuble with networking on this machine (Cannot Get Hostname)!");
|
|
return false;
|
|
};
|
|
|
|
//*****************************************
|
|
//* there we building our network address *
|
|
//*****************************************
|
|
bcopy(h_info->h_addr, &(((struct sockaddr_in *)MainSocketAddress)->sin_addr), h_info->h_length);
|
|
((struct sockaddr_in *)MainSocketAddress)->sin_family = h_info->h_addrtype;
|
|
((struct sockaddr_in *)MainSocketAddress)->sin_port = htons(PORT);
|
|
|
|
RetCode = bind(MainSocket, MainSocketAddress, sizeof(struct sockaddr_in));
|
|
if (RetCode != 0){
|
|
LOG_ERROR("Error Binding to Port/Address");
|
|
return false;
|
|
};
|
|
RetCode = listen(MainSocket, 128);
|
|
if (RetCode != 0){
|
|
LOG_ERROR("Cannot Listen Port/Address");
|
|
return false;
|
|
};
|
|
|
|
U8 dontblock;
|
|
dontblock = fcntl(MainSocket, F_GETFL, NULL);
|
|
dontblock |= O_NONBLOCK | O_NDELAY;
|
|
RetCode = ioctl(MainSocket, FIONBIO, (char *)&dontblock);
|
|
if (RetCode == 0){
|
|
LOG("Set N-Blocking Mode of Accepting Socket");
|
|
}
|
|
else {
|
|
LOG("Can't set N-Blocking Mode of Accepting Socket");
|
|
};
|
|
#else
|
|
WSADATA wsaData;
|
|
int iResult;
|
|
// Initialize Winsock
|
|
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
|
|
if (iResult != 0){
|
|
sprintf(temp, "WSAStartup failed with error: %d\n", iResult);
|
|
LOG_ERROR(temp);
|
|
return false;
|
|
};
|
|
|
|
MainSocket = INVALID_SOCKET;
|
|
SOCKET ClientSocket = INVALID_SOCKET;
|
|
|
|
struct addrinfo *result = NULL;
|
|
struct addrinfo hints;
|
|
|
|
//int iSendResult;
|
|
//char recvbuf[512];
|
|
//int recvbuflen = 512;
|
|
|
|
ZeroMemory(&hints, sizeof(hints));
|
|
hints.ai_family = AF_INET;
|
|
hints.ai_socktype = SOCK_STREAM;
|
|
hints.ai_protocol = IPPROTO_TCP;
|
|
hints.ai_flags = AI_PASSIVE;
|
|
|
|
// Resolve the server address and port
|
|
sprintf(temp, "%d", PORT);
|
|
iResult = getaddrinfo(NULL, temp, &hints, &result);
|
|
if (iResult != 0) {
|
|
sprintf(temp, "getaddrinfo failed with error: %d\n", iResult);
|
|
LOG_ERROR(temp);
|
|
WSACleanup();
|
|
return false;
|
|
};
|
|
|
|
// Create a SOCKET for connecting to server
|
|
MainSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
|
|
if (MainSocket == INVALID_SOCKET) {
|
|
sprintf(temp, "socket failed with error: %ld\n", WSAGetLastError());
|
|
LOG_ERROR(temp);
|
|
freeaddrinfo(result);
|
|
WSACleanup();
|
|
return false;
|
|
};
|
|
|
|
// Setup the TCP listening socket
|
|
iResult = bind(MainSocket, result->ai_addr, (int)result->ai_addrlen);
|
|
if (iResult == SOCKET_ERROR) {
|
|
sprintf(temp, "bind failed with error: %d\n", WSAGetLastError());
|
|
LOG_ERROR(temp);
|
|
freeaddrinfo(result);
|
|
closesocket(MainSocket);
|
|
WSACleanup();
|
|
return false;
|
|
};
|
|
|
|
freeaddrinfo(result);
|
|
|
|
iResult = listen(MainSocket, SOMAXCONN);
|
|
if (iResult == SOCKET_ERROR) {
|
|
sprintf(temp, "listen failed with error: %d\n", WSAGetLastError());
|
|
LOG_ERROR(temp);
|
|
closesocket(MainSocket);
|
|
WSACleanup();
|
|
return false;
|
|
};
|
|
/*
|
|
u_long iMode = 1;
|
|
iResult = ioctlsocket(MainSocket, FIONBIO, &iMode);
|
|
if (iResult != NO_ERROR){
|
|
sprintf(temp, "ioctlsocket failed with error: %ld\n", iResult);
|
|
LOG_ERROR(temp);
|
|
};
|
|
*/
|
|
#endif
|
|
m_bConnectionType = 1;
|
|
return init();
|
|
};
|
|
|
|
template <class HANDLER, class ENGINE> bool networkServer<HANDLER, ENGINE>::BootUp(U16 Port){
|
|
m_nPortNumber = Port;
|
|
#ifdef __linux__
|
|
int RetCode;
|
|
size_t S_NAMLEN = CTEXT;
|
|
RetCode = gethostname(m_pHostName, S_NAMLEN);
|
|
char temp[CTEXT];
|
|
sprintf(temp, "Running on host: %s:%d", m_pHostName, m_nPortNumber);
|
|
LOG(temp);
|
|
#else
|
|
sprintf(m_pHostName, "");
|
|
#endif
|
|
return BootUp(m_pHostName, m_nPortNumber);
|
|
};
|
|
|
|
template <class HANDLER, class ENGINE> bool networkServer<HANDLER, ENGINE>::attachEngine(ENGINE *ptr){
|
|
m_pEngine = ptr;
|
|
if (m_vHandlersPool.size()) {
|
|
// Pass Kernel to all already connected nodes
|
|
for (std::vector<HANDLER *>::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++) {
|
|
((networkClientHandler *)(*index))->attachEngine((basicEngine *)m_pEngine);
|
|
};
|
|
};
|
|
return true;
|
|
};
|
|
|
|
#ifdef __linux__
|
|
bool networkServer::BootUp(CSTR SOCKET_NAME){
|
|
struct sockaddr_un MainPort;
|
|
size_t S_NAMLEN = CTEXT;
|
|
int RetCode;
|
|
char localhost[S_NAMLEN];
|
|
char temp[CTEXT];
|
|
|
|
LOG("Core BootUp");
|
|
|
|
MainSocket = socket(PF_UNIX, SOCK_STREAM, 0);
|
|
if (MainSocket == -1){
|
|
LOG_ERROR("Some throuble with Kernel on this machine (UnixSocket Error)!");
|
|
return false;
|
|
};
|
|
|
|
if (unlink(SOCKET_NAME) == -1){
|
|
LOG("Old Socket File was not deleted!");
|
|
};
|
|
localhost[0] = 0;
|
|
//RetCode = gethostname( localhost, S_NAMLEN );
|
|
sprintf(temp, "Running Unix Socket: %s::%s", localhost, SOCKET_NAME);
|
|
LOG(temp);
|
|
MainSocketAddress = (sockaddr *)malloc(sizeof(struct sockaddr_un));
|
|
bzero(MainSocketAddress, sizeof(struct sockaddr_un));
|
|
|
|
//*****************************************
|
|
//* there we building our network address *
|
|
//*****************************************
|
|
((struct sockaddr_un *) MainSocketAddress)->sun_family = AF_UNIX;
|
|
snprintf(((struct sockaddr_un *) MainSocketAddress)->sun_path, UNIX_PATH_MAX, SOCKET_NAME);
|
|
|
|
|
|
RetCode = bind(MainSocket, MainSocketAddress, sizeof(struct sockaddr_un));
|
|
if (RetCode != 0){
|
|
LOG_ERROR("Error Binding to Port/Address");
|
|
return false;
|
|
};
|
|
RetCode = listen(MainSocket, 128);
|
|
if (RetCode != 0){
|
|
LOG_ERROR("Cannot Listen UNIX SOCKET");
|
|
return false;
|
|
};
|
|
U8 dontblock;
|
|
// Set Socket permitions 666
|
|
fchmod(MainSocket, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
|
|
dontblock = fcntl(MainSocket, F_GETFL, NULL);
|
|
dontblock |= O_NONBLOCK | O_NDELAY;
|
|
RetCode = ioctl(MainSocket, FIONBIO, (char *)&dontblock);
|
|
if (RetCode == 0){
|
|
LOG("Set N-Blocking Mode of Accepting Socket");
|
|
}
|
|
else {
|
|
LOG("Can't set N-Blocking Mode of Accepting Socket");
|
|
};
|
|
m_bConnectionType = 2;
|
|
return init();
|
|
};
|
|
|
|
#endif
|
|
|
|
template <class HANDLER, class ENGINE> void networkServer<HANDLER, ENGINE>::m_fThreadProc(void){
|
|
//struct sockaddr ClientAddress;
|
|
//socklen_t size;
|
|
#ifdef __linux__
|
|
int ClientSocket;
|
|
if (m_bConnectionType == 1){
|
|
size = (socklen_t) sizeof(struct sockaddr_in);
|
|
}
|
|
else {
|
|
size = (socklen_t) sizeof(struct sockaddr_un);
|
|
};
|
|
#else
|
|
SOCKET ClientSocket;
|
|
#endif
|
|
LOG("Core Worker Thread Started");
|
|
LOG("Ready to Accept Connections");
|
|
m_bThreadStatus = TH_WORKING;
|
|
while (m_bThreadStatus < TH_ENDED){
|
|
#ifdef __linux__
|
|
ClientSocket = accept( MainSocket, &ClientAddress, &size);
|
|
if (ClientSocket == -1) {
|
|
#else
|
|
ClientSocket = accept( MainSocket, NULL, NULL);
|
|
if (ClientSocket == INVALID_SOCKET) {
|
|
#endif
|
|
switch (errno){
|
|
case EAGAIN:{
|
|
// Checkup client disconnection
|
|
if (m_vHandlersPool.size()) {
|
|
for (std::vector<HANDLER *>::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++) {
|
|
networkClientHandler *tClient = (networkClientHandler *)(*index);
|
|
if (tClient->getConnectionStatus() == CS_DISCONNECTED){
|
|
// Remove Client Handler
|
|
LOG("Remove Client");
|
|
delete(tClient);
|
|
m_vHandlersPool.erase(index);
|
|
LOG("Client Stoped");
|
|
LOG("Remove Client Done");
|
|
};
|
|
};
|
|
};
|
|
SLEEP(10);
|
|
continue;
|
|
};
|
|
case EWOULDBLOCK: LOG_ERROR("The socket is marked non-blocking and no connections are present to be accepted."); break;
|
|
case EBADF: LOG_ERROR("The descriptor is invalid."); break;
|
|
case ECONNABORTED: LOG_ERROR("A connection has been aborted."); break;
|
|
case EINTR: LOG_ERROR("The system call was interrupted by a signal that was caught before a valid connection arrived."); break;
|
|
case EINVAL: LOG_ERROR("Socket is not listening for connections, or addrlen is invalid (e.g., is negative)."); break;
|
|
case EMFILE: LOG_ERROR("The per-process limit of open file descriptors has been reached."); break;
|
|
case ENFILE: LOG_ERROR("The system limit on the total number of open files has been reached."); break;
|
|
case ENOTSOCK: LOG_ERROR("The descriptor references a file, not a socket."); break;
|
|
case EOPNOTSUPP: LOG_ERROR("The referenced socket is not of type SOCK_STREAM."); break;
|
|
case EFAULT: LOG_ERROR("The addr argument is not in a writable part of the user address space."); break;
|
|
case ENOBUFS:
|
|
case ENOMEM: LOG_ERROR("Not enough free memory. This often means that the memory allocation is limited by the socket buffer limits, not by the system memory."); break;
|
|
case EPROTO: LOG_ERROR("Protocol error."); break;
|
|
case EPERM: LOG_ERROR("Firewall rules forbid connection."); break;
|
|
case ENOSR:
|
|
#ifdef __linux__
|
|
case ESOCKTNOSUPPORT:
|
|
#endif
|
|
case EPROTONOSUPPORT:
|
|
case ETIMEDOUT: LOG_ERROR("Unusual error in Kernel (Timeout, No Socket Support in Kernel, Unsupported Protocol)"); break;
|
|
#ifdef __linux__
|
|
case ERESTARTSYS: LOG_ERROR("Unusual error by Kernel"); break;
|
|
#endif
|
|
default: LOG_ERROR("Unhandled error in Kernel"); break;
|
|
};
|
|
m_bThreadStatus = TH_ENDED;
|
|
} else {
|
|
if (ClientSocket >= 0) {
|
|
if (m_bConnectionType == 1){
|
|
//char tstr[CQUERY];
|
|
#ifdef __linux__
|
|
inet_ntop(AF_INET, &(((struct sockaddr_in*) &(ClientAddress))->sin_addr), tstr, size);
|
|
#else
|
|
//strcpy(tstr, inet_ntoa(((struct sockaddr_in*)&ClientAddress)->sin_addr));
|
|
//InetNtop(AF_INET, &(((struct sockaddr_in*) &(ClientAddress ))->sin_addr ), (PWSTR)tstr, size );
|
|
#endif
|
|
};
|
|
LOG("Client Connection Accepted");
|
|
HANDLER *tHandle;
|
|
tHandle = new HANDLER(ClientSocket, m_pSettings);//networkClientHandler(ClientSocket);
|
|
if (tHandle != NULL) {
|
|
tHandle->attachEngine(m_pEngine);
|
|
m_vHandlersPool.push_back(tHandle);
|
|
};
|
|
} else {
|
|
LOG_ERROR("Client Socket Error");
|
|
switch (errno){
|
|
//case EAGAIN: continue;
|
|
case EWOULDBLOCK: LOG_ERROR(" The socket is marked non-blocking and no connections are present to be accepted."); break;
|
|
case EBADF: LOG_ERROR(" The descriptor is invalid."); break;
|
|
case ECONNABORTED: LOG_ERROR(" A connection has been aborted."); break;
|
|
case EINTR:{// If Interrupted by Signal - No Harm was done
|
|
LOG_ERROR(" The system call was interrupted by a signal that was caught before a valid connection arrived.");
|
|
continue;
|
|
};
|
|
case EINVAL: LOG_ERROR(" Socket is not listening for connections, or addrlen is invalid (e.g., is negative)."); break;
|
|
case EMFILE: LOG_ERROR(" The per-process limit of open file descriptors has been reached."); break;
|
|
case ENFILE: LOG_ERROR(" The system limit on the total number of open files has been reached."); break;
|
|
case ENOTSOCK: LOG_ERROR(" The descriptor references a file, not a socket."); break;
|
|
case EOPNOTSUPP: LOG_ERROR(" The referenced socket is not of type SOCK_STREAM."); break;
|
|
case EFAULT: LOG_ERROR(" The addr argument is not in a writable part of the user address space."); break;
|
|
case ENOBUFS:
|
|
case ENOMEM: LOG_ERROR(" Not enough free memory. This often means that the memory allocation is limited by the socket buffer limits, not by the system memory."); break;
|
|
case EPROTO: LOG_ERROR(" Protocol error."); break;
|
|
case EPERM: LOG_ERROR(" Firewall rules forbid connection."); break;
|
|
case ENOSR:
|
|
#ifdef __linux__
|
|
case ESOCKTNOSUPPORT:
|
|
#endif
|
|
case EPROTONOSUPPORT:
|
|
case ETIMEDOUT: LOG_ERROR(" Unusual error in Kernel (Timeout, No Socket Support in Kernel, Unsupported Protocol)"); break;
|
|
#ifdef __linux__
|
|
case ERESTARTSYS: LOG_ERROR(" Unusual error by Kernel"); break;
|
|
#endif
|
|
default: LOG_ERROR(" Unhandled error in Kernel"); break;
|
|
};
|
|
m_bThreadStatus = TH_ENDED;
|
|
};
|
|
};
|
|
};
|
|
LOG("Core Worker Thread Ended");
|
|
};
|
|
|
|
template <class HANDLER, class ENGINE> void networkServer<HANDLER, ENGINE>::dispatchEvent(basicEvent *Evt){
|
|
if (Evt == NULL) return;
|
|
if (Evt->m_eClass == EVT_CLASS_SYSTEM) {
|
|
// Handle System Events
|
|
};
|
|
};
|
|
|
|
|
|
#undef LOG
|
|
#undef LOG_ERROR
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#endif
|