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.
 
 
 
 
 
 

402 lines
14 KiB

#include "netServer.h"
#include "../../App/3dSERVER/LRF_ClientHandler.h"
#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 ){
};
networkServer::networkServer( config_setting_t *Settings ) : basicThread(){
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" );
};
};
networkServer::~networkServer(){
m_bThreadStatus = TH_ENDED;
if( m_pHostName != NULL ) free( m_pHostName );
};
bool networkServer::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 );
};
};
bool networkServer::BootUp( CSTR HOST_NAME, U16 PORT ){
char temp[CTEXT];
int RetCode;
#ifdef __linux__
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;
};
#endif
m_bConnectionType = 1;
return init();
};
bool networkServer::BootUp( U16 Port ){
char temp[CTEXT];
m_nPortNumber = Port;
#ifdef __linux__
int RetCode;
size_t S_NAMLEN = CTEXT;
RetCode = gethostname( m_pHostName, S_NAMLEN );
sprintf( temp, "Running on host: %s:%d", m_pHostName, m_nPortNumber );
LOG( temp );
#else
sprintf( m_pHostName, "" );
#endif
return BootUp( m_pHostName, m_nPortNumber );
};
bool networkServer::attachEngine( basicEngine *ptr ){
m_pDetectorKernel = ptr;
if( m_vHandlersPool.size()) {
// Pass Kernel to all already connected nodes
for( vectorNetHandlers::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++ ) {
((LRF_ClientHandler *)(*index))->attachEngine(m_pDetectorKernel);
};
};
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
void networkServer::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 ){
ClientSocket = accept ( MainSocket, &ClientAddress, &size );
if ( ClientSocket == -1 ) {
switch( errno ){
case EAGAIN:{
// Checkup client disconnection
if( m_vHandlersPool.size()) {
for( vectorNetHandlers::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++ ) {
LRF_ClientHandler *tClient = (LRF_ClientHandler *)(*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: me->Log(" 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;
//case ERESTARTSYS: me->Log(" Unusual error by Kernel"); break;
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 ), tstr, size );
#endif
};
LOG( "Client Connection Accepted" );
LRF_ClientHandler *tHandle;
tHandle = new LRF_ClientHandler( ClientSocket );
if( tHandle != NULL ) {
tHandle->attachEngine( m_pDetectorKernel );
m_vHandlersPool.push_back( (networkClientHandler *) 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;
//case ERESTARTSYS: me->Log(" Unusual error by Kernel"); break;
default: LOG_ERROR( " Unhandled error in Kernel" ); break;
};
m_bThreadStatus = TH_ENDED;
};
};
};
LOG( "Core Worker Thread Ended" );
};
void networkServer::dispatchEvent( basicEvent *Evt ){
if( Evt == NULL ) return;
if( Evt->m_eClass == EVT_CLASS_SYSTEM ) {
// Handle System Events
};
};
#undef LOG
#undef LOG_ERROR