static cmm_error_t cnt_update_dns() { int i; cnt_entry_t *node; for (i=0; i<cnt_table.nb_nodes; i++) { node = cnt_table.nodes[i]; if ( GetHostAddress( node->unix_name, RING_PORT, &(node->net_addr) ) != 1 ) { cm_trace(CM_TRACE_LEVEL_ERROR, "GetHostAddress failed for node %s", node->unix_name ); return( CMM_EOTHER ); } /* Update the addr field */ get_ip_from_hostname( node->unix_name, node->member.addr ); cm_trace(CM_TRACE_LEVEL_DEBUG, "Updated the DNS entry for %s. IP address is %s", node->unix_name, node->member.addr ); } cm_trace(CM_TRACE_LEVEL_DEBUG, "The DNS entries have been found successfully" ); return(CMM_OK); }
//******************************************************************************************************* // SendHTTP: // Main entry point for this code. // url - The URL to GET/POST to/from. // headerSend - Headers to be sent to the server. // post - Data to be posted to the server, NULL if GET. // postLength - Length of data to post. // req - Contains the message and headerSend sent by the server. // // returns 1 on failure, 0 on success. //******************************************************************************************************* int SendHTTP(char* url,HTTPRequest *req) { #ifdef WIN32 WSADATA WsaData; #endif struct sockaddr_in sin; int sock; char buffer[512]; char protocol[20],host[256],request[1024]; int l,port,chars,err; MemBuffer headersBuffer,messageBuffer; char headerSend[1024]; qboolean done; //S4ND_Log("Parse URL\n"); ParseURL(url,protocol,sizeof(protocol),host,sizeof(host), // Parse the URL request,sizeof(request),&port); if(strcmp(protocol,"HTTP")) return 1; #ifdef WIN32 err = WSAStartup (0x0101, &WsaData); // Init Winsock if(err!=0) return 1; #endif //S4ND_Log("Open Socket\n"); sock = socket (AF_INET, SOCK_STREAM, 0); //if (socket == INVALID_SOCKET) if (sock < 0) return 1; sin.sin_family = AF_INET; //Connect to web sever sin.sin_port = htons( (unsigned short)port ); sin.sin_addr.s_addr = GetHostAddress(host); //S4ND_Log("Connect\n"); if( connect (sock,(struct sockaddr*)&sin, sizeof(/*struct sockaddr_in*/sin) ) ) { return 1; } //S4ND_Log("Start Sending\n"); if( !*request ) strcpy(request,"/"); SendString(sock,"GET "); strcpy(headerSend, "GET "); SendString(sock,request); strcat(headerSend, request); SendString(sock," HTTP/1.0\r\n"); strcat(headerSend, " HTTP/1.0\r\n"); SendString(sock,"Accept: image/gif, image/x-xbitmap," " image/jpeg, image/pjpeg, application/vnd.ms-excel," " application/msword, application/vnd.ms-powerpoint," " */*\r\n"); strcat(headerSend, "Accept: image/gif, image/x-xbitmap," " image/jpeg, image/pjpeg, application/vnd.ms-excel," " application/msword, application/vnd.ms-powerpoint," " */*\r\n"); SendString(sock,"Accept-Language: en-us\r\n"); strcat(headerSend, "Accept-Language: en-us\r\n"); SendString(sock,"Accept-Encoding: gzip, deflate\r\n"); strcat(headerSend, "Accept-Encoding: gzip, deflate\r\n"); SendString(sock,"User-Agent: Mozilla/4.0\r\n"); strcat(headerSend, "User-Agent: Mozilla/4.0\r\n"); SendString(sock,"Host: "); strcat(headerSend, "Host: "); SendString(sock,host); strcat(headerSend, host); SendString(sock,"\r\n"); strcat(headerSend, "\r\n"); SendString(sock,"\r\n"); // Send a blank line to signal end of HTTP headerReceive strcat(headerSend, "\r\n"); req->headerSend = (char*) malloc( sizeof(char*) * strlen(headerSend)); strcpy(req->headerSend, (char*) headerSend ); MemBufferCreate(&headersBuffer ); chars = 0; done = qfalse; //S4ND_Log("Start Recv.\n"); while(!done) { l = recv(sock,buffer,1,0); if(l<0) done=qtrue; switch(*buffer) { case '\r': break; case '\n': if(chars==0) done = qtrue; chars=0; break; default: chars++; break; } MemBufferAddByte(&headersBuffer,*buffer); } req->headerReceive = (char*) headersBuffer.buffer; *(headersBuffer.position) = 0; MemBufferCreate(&messageBuffer); // Now read the HTTP body do { l = recv(sock,buffer,sizeof(buffer)-1,0); if(l<0) break; *(buffer+l)=0; MemBufferAddBuffer(&messageBuffer, (unsigned char*)&buffer, l); } while(l>0); *messageBuffer.position = 0; req->message = (char*) messageBuffer.buffer; req->messageLength = (messageBuffer.position - messageBuffer.buffer); //S4ND_Log("Close Socket\n"); closesocket(sock); // Cleanup return 0; }
DWORD ServiceExecutionThread(LPDWORD param) { #if _DEBUG ::OutputDebugString(L"ServiceExecutionThread\n"); #endif if (IntializeSystemInfo() == FALSE) { return IC_NO_INITIALIZE; } WORD wVersionRequested = MAKEWORD(1, 1); WSADATA wsaData; WSAStartup(wVersionRequested, &wsaData); SOCKET udpSocket = INVALID_SOCKET; int result = IC_NOERROR; bool showHelp = false; do { g_killServiceEvent = CreateEvent(0, TRUE, FALSE, 0); if (!g_killServiceEvent) { OutputError(L"CreateEvent fails! (%d)", GetLastError()); result = IC_EVENT_CREATE_FAIL; break; } wstring apiKey; wstring envInfo; vector<int> intervalTimes; ConnectionInfo connection; g_debugMode = GetDebugMode(g_argc, g_argv); if (cmdOptionExists(g_argv, g_argv + g_argc, L"-h") == true || cmdOptionExists(g_argv, g_argv + g_argc, L"/h") == true) { showHelp = true; break; } if (cmdOptionExists(g_argv, g_argv + g_argc, L"-unreg") == true) { DoUnregistration(); break; } if (cmdOptionExists(g_argv, g_argv + g_argc, L"-start") == true) { DoStartService(); break; } if (cmdOptionExists(g_argv, g_argv + g_argc, L"-stop") == true) { DoStopService(); break; } if (cmdOptionExists(g_argv, g_argv + g_argc, L"-update") == true) { ProcessLatestUpdate(); break; } if (cmdOptionExists(g_argv, g_argv + g_argc, L"-restart") == true) { RestartService(); break; } apiKey = GetApiKey(g_argc, g_argv); envInfo = GetEnvInfo(g_argc, g_argv); intervalTimes = GetIntervalTime(g_argc, g_argv); if (apiKey.length() == 0) { OutputError(L"NO ApiKey\n"); result = IC_NO_APIKEY; showHelp = true; break; } if (envInfo.length() == 0) { OutputError(L"NO AgentID Info\n"); result = IC_NO_AGENTIDINFO; showHelp = true; break; } string address = GetHostAddress(g_argc, g_argv, connection); struct hostent *host = gethostbyname(address.c_str()); if (host == nullptr) { OutputError(L"Can't resolve host address: %s\n", address.c_str()); result = IC_NO_RESOLVE_HOSTADDR; break; } SetupHostPort(g_argc, g_argv, connection); if (cmdOptionExists(g_argv, g_argv + g_argc, L"-regservice") == true) { DoRegistration(apiKey, envInfo, address, connection.Getport(), intervalTimes); break; } struct sockaddr_in remoteServAddr; remoteServAddr.sin_family = host->h_addrtype; memcpy((char *)&remoteServAddr.sin_addr.s_addr, host->h_addr_list[0], host->h_length); remoteServAddr.sin_port = htons((u_short)connection.Getport()); /* socket creation */ udpSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (udpSocket == INVALID_SOCKET) { OutputError(L"socket failed with error: %ld\n", WSAGetLastError()); break; } wstring appVersion = GetAppVersion(g_moduleFilePath.c_str(), NULL, NULL, NULL, NULL); OutputConsole(L"(%s) ServiceExecutionThread - data collect thread - start\n", appVersion.c_str()); { thread processCpuMemThread([apiKey, envInfo, udpSocket, remoteServAddr, intervalTimes]() { ProcessCpuMemInfo(apiKey, envInfo, udpSocket, remoteServAddr, intervalTimes[0]); }); thread processDiskThread([apiKey, envInfo, udpSocket, remoteServAddr, intervalTimes]() { ProcessDiskInfo(apiKey, envInfo, udpSocket, remoteServAddr, intervalTimes[1]); }); thread updateThread([]() { DWORD oneday = 1000 * 60 * 60 * 24; while (true) { ProcessLatestUpdate(); if (::WaitForSingleObject(g_killServiceEvent, oneday) == WAIT_TIMEOUT) { continue; } break; } }); if (g_isConsoleApp == TRUE) { printf("Press any key to exit...\n"); getchar(); } else { #if _DEBUG ::OutputDebugString(L"Service thread - WaitForSingleObject...\n"); #endif WaitForSingleObject(g_killServiceEvent, INFINITE); } #if _DEBUG ::OutputDebugString(L"Service thread waiting...\n"); Sleep(1000); #endif if (processCpuMemThread.joinable() == true) { processCpuMemThread.join(); } if (processDiskThread.joinable() == true) { processDiskThread.join(); } if (updateThread.joinable() == true) { updateThread.join(); } #if _DEBUG ::OutputDebugString(L"All Service-threads exited...\n"); #endif } ::SetEvent(g_killSafeExitEvent); #if _DEBUG ::OutputDebugString(L"Service thread detached\n"); #endif } while (false); #if _DEBUG ::OutputDebugString(L"ServiceExecutionThread - data collect thread - ending\n"); #endif if (udpSocket != INVALID_SOCKET) { closesocket(udpSocket); } if (showHelp == true) { ShowHelp(); } WSACleanup(); #if _DEBUG ::OutputDebugString(L"ServiceExecutionThread - data collect thread - ended\n"); #endif return result; }
void SecureChatIOCP::NotifyReceivedPackage(CIOCPBuffer *pOverlapBuff,int nSize,ClientContext *pContext) { // No Context? Why do the work ? if ( pContext==NULL ) { AppendLog("pContext==NULL) in NotifyReceivedPackage"); return; } // No Connection ?? Why do the work ? if ( pContext->m_Socket==INVALID_SOCKET ) { //AppendLog("pContext->m_Socket==INVALID_SOCKET in NotifyReceivedPackage"); return; } BYTE PackageType=pOverlapBuff->GetPackageType(); switch (PackageType) { case PKG_ERRORMSG: OnPKG_ERRORMSG(pOverlapBuff,nSize,pContext); break; case PKG_ENCRYPTED: { //pContext->m_bGotSessionKey=FALSE; if(! pContext->m_bGotSessionKey ) { SendErrorMessageTo(pContext->m_Socket,"Server> Session key Not available, you are not authorized"); CString msg; msg.Format("Client %x (%s) not Authorized",pContext->m_Socket,GetHostAddress(pContext->m_Socket)); AppendLog(msg); break; } CIOCPBuffer *pDecryptedPKG=DeCryptBuffer(pOverlapBuff,pContext); if ( !pDecryptedPKG ) { AppendLog("SECURITY RISK: Warning could not decrypt the clients message.. The remote client may be try to hack your system."); DisconnectClient(pContext->m_Socket); }else { // Process it ProcessPayload(pDecryptedPKG,pDecryptedPKG->GetUsed(),pContext); } if ( pDecryptedPKG ) ReleaseBuffer(pDecryptedPKG); break; } #ifdef _IOCPClientMode_ // Handle the package sent from server case PKG_PUBLIC_KEYA: OnPKG_PUBLIC_KEYA(pOverlapBuff,nSize,pContext); break; case PKG_SIGNATURE: OnPKG_SIGNATURE(pOverlapBuff,nSize,pContext); break; #else // Handle the package sent from clients. case PKG_PUBLIC_KEYP: OnPKG_PUBLIC_KEYP(pOverlapBuff,nSize,pContext); break; case PKG_PUBLIC_KEYB: OnPKG_PUBLIC_KEYB(pOverlapBuff,nSize,pContext); break; #endif }; }
void SecureChatIOCP::NotifyDisconnectedClient(ClientContext *pContext) { if ( pContext!=NULL && pContext->m_Socket!=INVALID_SOCKET ) { pContext->m_ContextLock.Lock(); pContext->m_bGotSessionKey=FALSE; unsigned int *pBuffer= new unsigned int; if(pBuffer!=NULL&&m_hWnd!=NULL) { *pBuffer=pContext->m_Socket; ::PostMessage(m_hWnd, WM_DISCONNECT_CLIENT, 0, (LPARAM) pBuffer); }else { delete pBuffer; pBuffer=NULL; } CString msg; CTime tm= CTime::GetCurrentTime(); msg.Format("[%s] %s Disconnected. (%s)",tm.Format("%H:%M:%S"),pContext->m_sUsername,GetHostAddress(pContext->m_Socket)); AppendLog(msg); TRACE("Client %i is disconnected\r\n",pContext->m_ID); pContext->m_ContextLock.Unlock(); // We can not Lock m_ContextMapLock inside pContext->m_ContextLock lock -> leads do deadlock.. #ifndef _IOCPClientMode_ SendTextMessage(msg); #endif // Clean The memory. NotifyNewClientContext(pContext); } }
//******************************************************************************************************* // SendHTTP: // Main entry point for this code. // url - The URL to GET/POST to/from. // headerSend - Headers to be sent to the server. // post - Data to be posted to the server, NULL if GET. // postLength - Length of data to post. // req - Contains the message and headerSend sent by the server. // // returns 1 on failure, 0 on success. //******************************************************************************************************* int Request::SendHTTP(LPCSTR url,LPCSTR headerReceive,BYTE *post, DWORD postLength,HTTPRequest *req) { WSADATA WsaData; SOCKADDR_IN sin; SOCKET sock; char buffer[512]; char protocol[20],host[256],request[1024]; int l,port,chars,err; MemBuffer headersBuffer,messageBuffer; char headerSend[1024]; BOOL done; ParseURL(url,protocol,sizeof(protocol),host,sizeof(host), // Parse the URL request,sizeof(request),&port); if(strcmp(protocol,"HTTP")) return 1; err = WSAStartup (0x0101, &WsaData); // Init Winsock if(err!=0) return 1; sock = socket (AF_INET, SOCK_STREAM, 0); //if (socket == INVALID_SOCKET) if (sock == INVALID_SOCKET) return 1; sin.sin_family = AF_INET; //Connect to web sever sin.sin_port = htons( (unsigned short)port ); sin.sin_addr.s_addr = GetHostAddress(host); if( connect (sock,(LPSOCKADDR)&sin, sizeof(SOCKADDR_IN) ) ) { return 1; } //printf("\r\n\r\n <<SEND HTTP REQUEST : >> \r\n\r\n"); //Send request if( !*request ) lstrcpyn(request,"/",sizeof(request)); if( post == NULL ) { SendString(sock,"GET "); strcpy(headerSend, "GET "); } else { SendString(sock,"POST "); strcpy(headerSend, "POST "); } SendString(sock,request); strcat(headerSend, request); SendString(sock," HTTP/1.0\r\n"); strcat(headerSend, " HTTP/1.0\r\n"); SendString(sock,"Accept: image/gif, image/x-xbitmap," " image/jpeg, image/pjpeg, application/vnd.ms-excel," " application/msword, application/vnd.ms-powerpoint," " */*\r\n"); strcat(headerSend, "Accept: image/gif, image/x-xbitmap," " image/jpeg, image/pjpeg, application/vnd.ms-excel," " application/msword, application/vnd.ms-powerpoint," " */*\r\n"); SendString(sock,"Accept-Language: en-us\r\n"); strcat(headerSend, "Accept-Language: en-us\r\n"); SendString(sock,"Accept-Encoding: gzip, deflate\r\n"); strcat(headerSend, "Accept-Encoding: gzip, deflate\r\n"); SendString(sock,"User-Agent: Mozilla/4.0\r\n"); strcat(headerSend, "User-Agent: Mozilla/4.0\r\n"); if(postLength) { wsprintf(buffer,"Content-Length: %ld\r\n",postLength); SendString(sock,buffer); strcat(headerSend, buffer); } //SendString(sock,"Cookie: mycookie=blablabla\r\n"); // printf("Cookie: mycookie=blablabla\r\n"); SendString(sock,"Host: "); strcat(headerSend, "Host: "); SendString(sock,host); strcat(headerSend, host); SendString(sock,"\r\n"); strcat(headerSend, "\r\n"); if( (headerReceive!=NULL) && *headerReceive ) { SendString(sock,headerReceive); strcat(headerSend, headerReceive); } SendString(sock,"\r\n"); // Send a blank line to signal end of HTTP headerReceive strcat(headerSend, "\r\n"); if( (post!=NULL) && postLength ) { send(sock,(const char*)post,postLength,0); post[postLength] = '\0'; strcat(headerSend, (const char*)post); } //strcpy(req->headerSend, headerSend); req->headerSend = (char*) malloc( sizeof(char*) * strlen(headerSend)); strcpy(req->headerSend, (char*) headerSend ); // req->headerSend = (char*) headerSend ; // free(req->headerSend); // Read the result //printf("\r\n\r\n <<RECEIVE HTTP REQUEST : >> \r\n\r\n\r\n"); // First read HTTP headerReceive MemBufferCreate(&headersBuffer ); chars = 0; done = FALSE; while(!done) { l = recv(sock,buffer,1,0); if(l<0) done=TRUE; switch(*buffer) { case '\r': break; case '\n': if(chars==0) done = TRUE; chars=0; break; default: chars++; break; } MemBufferAddByte(&headersBuffer,*buffer); } req->headerReceive = (char*) headersBuffer.buffer; *(headersBuffer.position) = 0; MemBufferCreate(&messageBuffer); // Now read the HTTP body do { l = recv(sock,buffer,sizeof(buffer)-1,0); if(l<0) break; *(buffer+l)=0; MemBufferAddBuffer(&messageBuffer, (unsigned char*)&buffer, l); } while(l>0); *messageBuffer.position = 0; req->message = (char*) messageBuffer.buffer; req->messageLength = (messageBuffer.position - messageBuffer.buffer); closesocket(sock); // Cleanup return 0; }