#include "netServer.h" // #include "../../App/3dSERVER/LRF_ClientHandler.h" #include "netClientHandler.h" #define LOG(X) m_pLog->Log("NS", this, X) #ifdef DEBUG #define LOG_ERROR(X) \ { \ char _tBfrErrMSG234[256]; \ sprintf(_tBfrErrMSG234, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \ m_pLog->Log("NS", this, _LOG_ERROR, _tBfrErrMSG234); \ } #else #define LOG_ERROR(X) m_pLog->Log("NS", this, _LOG_ERROR, X); #endif void signal_void_handler(int SIG) { if ( SIG ) SIG = 121; // dummy to prevent Warnings } networkServer::networkServer(config_setting_t * Settings, networkServiceEngine * ptr) : basicThread() { m_pLog = basicLogCollection::getInstance(); m_bConnectionType = 0; m_pHostName = NULL; // always owned (malloc/strdup) once set m_nPortNumber = 0; m_vHandlersPool.clear(); MainSocketAddress = NULL; m_pKernelEngine = ptr; MainSocket = INVALID_SOCKET; 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 ..."); #ifdef AUTOMATIC_IP_DETECTION struct ifaddrs * ifaddr = NULL; struct ifaddrs * ifa; m_pHostName = (CSTR) malloc(CTEXT); if (-1 == getifaddrs(&ifaddr)) { LOG_ERROR("Cannot get Net Integfaces!"); return false; } else { bool regs = false; char ip[16]; struct sockaddr_in * inn; unsigned char A, B, C, D; #ifdef DEBUG LOG("Gotta check some IFs"); #endif for (ifa = ifaddr; ifa; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) { // Can Bus LOG("IFA->ifa_addr is NULL"); continue; }; if (ifa->ifa_addr->sa_family != AF_INET) { continue; } inn = (struct sockaddr_in *) ifa->ifa_addr; D = (inn->sin_addr.s_addr >> 24) & 0xFF; C = (inn->sin_addr.s_addr >> 16) & 0xFF; B = (inn->sin_addr.s_addr >> 8) & 0xFF; A = (inn->sin_addr.s_addr >> 0) & 0xFF; sprintf(ip, "%d.%d.%d.%d", A, B, C, D); sprintf(tBuffer, "Network Interface: %s [%s]", ifa->ifa_name, ip); if (strncmp(ifa->ifa_name, "eth", 3) == 0 || strncmp(ifa->ifa_name, "enp", 3) == 0) { regs = true; sprintf(m_pHostName, ip); }; LOG(tBuffer); }; if (! regs) { free(m_pHostName); m_pHostName = NULL; LOG_ERROR("Ethernet IP address Not Detected! Using Settings"); const char * tCfgHost = NULL; if (! config_setting_lookup_string(m_pSettings, NWS_SETTINGS_HOST, &tCfgHost)) { 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 { m_pHostName = strdup(tCfgHost); // libconfig owns tCfgHost: ~networkServer frees m_pHostName sprintf(tBuffer, "Host Address Read From Settings: %s", m_pHostName); LOG(tBuffer); }; }; freeifaddrs(ifaddr); }; #else const char * tCfgHost = NULL; if (! config_setting_lookup_string(m_pSettings, NWS_SETTINGS_HOST, &tCfgHost)) { 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 { m_pHostName = strdup(tCfgHost); // libconfig owns tCfgHost: ~networkServer frees m_pHostName sprintf(tBuffer, "Host Address Read From Settings: %s", m_pHostName); LOG(tBuffer); }; #endif 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, "Port Read From Settings: %d", m_nPortNumber); LOG(tBuffer); }; sprintf(tBuffer, "Final Network Config is: %s:%d", m_pHostName, 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) { #ifdef __linux__ int RetCode; struct hostent * h_info; #ifdef DEBUG LOG("BootUp"); #endif MainSocket = socket(AF_INET, SOCK_STREAM, 0); if (MainSocket == -1) { LOG_ERROR("Some throuble with networking on this machine (Socket Error)!"); return false; }; const int enable = 1; if (setsockopt(MainSocket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) { LOG_ERROR("setsockopt(SO_REUSEADDR) failed"); }; 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; }; int flags; flags = fcntl(MainSocket, F_GETFL, NULL); flags |= O_NONBLOCK | O_NDELAY; // RetCode = ioctl( MainSocket, FIONBIO, (char *) &dontblock ); RetCode = fcntl(MainSocket, F_SETFL, flags); if (RetCode == 0) { LOG("Set N-Blocking Mode of Accepting Socket"); } else { LOG("Can't set N-Blocking Mode of Accepting Socket"); }; #else char temp[CTEXT]; 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; if (m_pHostName == NULL) { m_pHostName = (CSTR) malloc(CTEXT); if (m_pHostName == NULL) { return false; } m_pHostName[0] = (char) 0; } RetCode = gethostname(m_pHostName, S_NAMLEN); if ( RetCode < 0 ) { LOG_ERROR("Can't Get Hostname!"); }; 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(networkServiceEngine * ptr) { m_pKernelEngine = 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); (*index)->attachEngine(m_pKernelEngine); }; }; return true; } #ifdef __linux__ bool networkServer::BootUp(CSTR SOCKET_NAME) { //struct sockaddr_un MainPort; //size_t S_NAMLEN = CTEXT; int RetCode; char localhost[CTEXT]; char temp[512]; 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 Master Socket"); } else { LOG("Can't set N-Blocking Mode of Master Socket"); }; m_bConnectionType = 2; return init(); } #endif void networkServer::m_fThreadProc(void) { struct sockaddr ClientAddress; socklen_t size; int RetCode; #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 #ifdef DEBUG LOG("Core Worker Thread Started"); LOG("Ready to Accept Connections"); #endif pthread_setname_np(pthread_self(), "networkServer"); m_bThreadStatus = TH_WORKING; while (m_bThreadStatus < TH_ENDED) { ClientSocket = accept(MainSocket, &ClientAddress, &size); if (ClientSocket < 0) { switch (errno) { case EAGAIN: { // No new connection: remove the clients that disconnected cleanupClients(); SLEEP(10); continue; }; // Transient: a full descriptor table (EMFILE/ENFILE) or memory shortage clears up once // disconnected clients are removed, an aborted handshake / signal only affects that attempt. // Before, every error ended the accept thread: the server stopped accepting for good. case EMFILE : case ENFILE : case ENOBUFS : case ENOMEM : case ECONNABORTED: case EINTR : case EPROTO : case EPERM : { char tB[96]; snprintf(tB, sizeof(tB), "accept() failed temporarily (errno %d), retrying", errno); LOG_ERROR(tB); cleanupClients(); SLEEP(100); 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 EINVAL : LOG_ERROR("Socket is not listening for connections, or addrlen is invalid (e.g., is negative)."); 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 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( m_bConnectionType == 1 ){ char tstr[CQUERY]; #ifdef __linux__ inet_ntop( AF_INET, &(((struct sockaddr_in*) &(ClientAddress ))->sin_addr ), tstr, CQUERY );//size ); #else strcpy( tstr, inet_ntoa( ((struct sockaddr_in*)&ClientAddress)->sin_addr ) ); //InetNtop(AF_INET, &(((struct sockaddr_in*) &(ClientAddress ))->sin_addr ), tstr, size ); #endif }; */ int flags; flags = fcntl(ClientSocket, F_GETFL, NULL); flags |= O_NONBLOCK | O_NDELAY; // RetCode = ioctl( MainSocket, FIONBIO, (char *) &dontblock ); RetCode = fcntl(ClientSocket, F_SETFL, flags); // Detect dead peers (module powered off, cable/VPN down): without keepalive a half-open // connection is never reported and its handler (threads, 8 MB buffers, descriptor) stays forever. if (m_bConnectionType == 1) { int tOn = 1, tIdle = NWS_KEEPALIVE_IDLE_S, tIntvl = NWS_KEEPALIVE_INTERVAL_S, tCnt = NWS_KEEPALIVE_PROBES; setsockopt(ClientSocket, SOL_SOCKET, SO_KEEPALIVE, &tOn, sizeof(tOn)); setsockopt(ClientSocket, IPPROTO_TCP, TCP_KEEPIDLE, &tIdle, sizeof(tIdle)); setsockopt(ClientSocket, IPPROTO_TCP, TCP_KEEPINTVL, &tIntvl, sizeof(tIntvl)); setsockopt(ClientSocket, IPPROTO_TCP, TCP_KEEPCNT, &tCnt, sizeof(tCnt)); } #ifdef DEBUG if (RetCode == 0) { LOG("Set N-Blocking Mode of Client Socket"); } else { LOG("Can't set N-Blocking Mode of Client Socket"); }; LOG("Client Connection Accepted"); #endif if (m_pKernelEngine) { networkClientHandler * tHandle; #ifdef DEBUG LOG("Before New Handler"); #endif tHandle = m_pKernelEngine->attachNewClient(ClientSocket, &ClientAddress); #ifdef DEBUG LOG("After New Handler"); #endif if (tHandle != NULL) { #ifdef DEBUG_EXTRA LOG("Handle Not NULL"); #endif // tHandle->attachEngine( m_pKernelEngine ); m_vHandlersPool.push_back(tHandle); } else { #ifdef DEBUG LOG_ERROR("No Client Handler Created!"); #endif shutdown(ClientSocket, 2); close(ClientSocket); }; } else { #ifdef DEBUG LOG_ERROR("No Kernel Attached!"); #endif shutdown(ClientSocket, 2); close(ClientSocket); }; }; }; #ifdef DEBUG LOG("Core Worker Thread Ended"); #endif } // Removes the handlers whose connection is gone (called from the accept thread) void networkServer::cleanupClients(void) { for (vectorNetHandlers::iterator index = m_vHandlersPool.begin(); index != m_vHandlersPool.end();) { if ((*index)->getStatus() == false) { if (m_pKernelEngine == NULL) { LOG_ERROR("No Kernel Attached!"); return; } if (m_pKernelEngine->detachClient(*index)) { index = m_vHandlersPool.erase(index); // erase() invalidates the iterator: continue with the returned one continue; } LOG_ERROR("Client detach from Kernel Failure!"); }; index++; }; } bool networkServer::dispatchEvent(EVENT_CONTAINER * Evt) { if (Evt == NULL) { return false; } return true; } #undef LOG #undef LOG_ERROR