DWORD WINAPI DaytimeHandler(VOID* Sock_) { struct tm *localTime; time_t aclock; CHAR *pszTime; DWORD retVal = 0; SOCKET Sock = (SOCKET)Sock_; time(&aclock); localTime = localtime(&aclock); if (localTime) { pszTime = asctime(localTime); if (!SendTime(Sock, pszTime)) retVal = 1; } LogEvent(L"DayTime: Shutting connection down", 0, 0, LOG_FILE); if (ShutdownConnection(Sock, FALSE)) LogEvent(L"DayTime: Connection is down", 0, 0, LOG_FILE); else { LogEvent(L"DayTime: Connection shutdown failed", 0, 0, LOG_FILE); retVal = 1; } LogEvent(L"DayTime: Terminating thread", 0, 0, LOG_FILE); ExitThread(retVal); }
DWORD WINAPI QotdHandler(VOID* sock_) { SOCKET sock = (SOCKET)sock_; DWORD retVal = 0; if (!RetrieveQuote(sock)) { LogEvent(L"QOTD: Error retrieving quote", 0, 0, LOG_FILE); retVal = 1; } LogEvent(L"QOTD: Shutting connection down", 0, 0, LOG_FILE); if (ShutdownConnection(sock, FALSE)) { LogEvent(L"QOTD: Connection is down", 0, 0, LOG_FILE); } else { LogEvent(L"QOTD: Connection shutdown failed", 0, 0, LOG_FILE); LogEvent(L"QOTD: Terminating thread", 0, 0, LOG_FILE); retVal = 1; } LogEvent(L"QOTD: Terminating thread", 0, 0, LOG_FILE); ExitThread(retVal); }
DWORD WINAPI DiscardHandler(VOID* sock_) { DWORD retVal = 0; SOCKET sock = (SOCKET)sock_; if (!RecieveIncomingPackets(sock)) { LogEvent(L"Discard: RecieveIncomingPackets failed", 0, 0, LOG_FILE); retVal = 1; } LogEvent(L"Discard: Shutting connection down", 0, 0, LOG_FILE); if (ShutdownConnection(sock, TRUE)) { LogEvent(L"Discard: Connection is down.", 0, 0, LOG_FILE); } else { LogEvent(L"Discard: Connection shutdown failed", 0, 0, LOG_FILE); retVal = 1; } LogEvent(L"Discard: Terminating thread", 0, 0, LOG_FILE); ExitThread(retVal); }
/////////////////////////////////////////////////////////////////////////////// // CloseComm /////////////////////////////////////////////////////////////////////////////// // DESCRIPTION: // Close Socket Communication // PARAMETERS: // None /////////////////////////////////////////////////////////////////////////////// void CSocketComm::CloseComm() { if (IsOpen()) { ShutdownConnection((SOCKET)m_hComm); m_hComm = INVALID_HANDLE_VALUE; m_bBroadcast = false; } }
void PopSession::Reconnect() { // re-establish the connection m_reconnect = true; if (m_syncSession.get()) { m_syncSession->RequestStop(); } m_commandManager->Pause(); ShutdownConnection(); }
bool FWinInetConnection::InitConnection() { // Make sure previous connection is closed ShutdownConnection(); UE_LOG(LogHttp, Log, TEXT("Initializing WinInet connection")); // Check and log the connected state so we can report early errors. ::DWORD ConnectedFlags; BOOL bConnected = InternetGetConnectedState(&ConnectedFlags, 0); FString ConnectionType; ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_CONFIGURED) ? TEXT("Configured ") : TEXT(""); ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_LAN) ? TEXT("LAN ") : TEXT(""); ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_MODEM) ? TEXT("Modem ") : TEXT(""); ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_MODEM_BUSY) ? TEXT("Modem Busy ") : TEXT(""); ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_OFFLINE) ? TEXT("Offline ") : TEXT(""); ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_PROXY) ? TEXT("Proxy Server ") : TEXT(""); ConnectionType += (ConnectedFlags & INTERNET_RAS_INSTALLED) ? TEXT("RAS Installed ") : TEXT(""); UE_LOG(LogHttp, Log, TEXT("Connected State: %s. Flags: (%s)"), bConnected ? TEXT("Good") : TEXT("Bad"), *ConnectionType); if (InternetAttemptConnect(0) != ERROR_SUCCESS) { UE_LOG(LogHttp, Warning, TEXT("InternetAttemptConnect failed: %s\n"), *InternetTranslateError(GetLastError())); return false; } // setup net connection InternetHandle = InternetOpen( *FString::Printf(TEXT("game=%s, engine=UE4, version=%d"), FApp::GetGameName(), GEngineNetVersion), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, INTERNET_FLAG_ASYNC); if (InternetHandle == NULL) { UE_LOG(LogHttp, Warning, TEXT("Failed WinHttpOpen: %s"), *InternetTranslateError(GetLastError())); return false; } { FScopeLock ScopeLock(&FHttpManager::RequestLock); bStaticConnectionInitialized = true; } // Register callback to update based on WinInet connection state InternetSetStatusCallback(InternetHandle, InternetStatusCallbackWinInet); return true; }
void CNet::CloseWinsock() { if ( m_bInitialized ) { if ( m_bConnected ) { ShutdownConnection(); } #ifdef ARCHDEF_PLATFORM_WIN32 int res = WSACleanup(); if ( res == 0 ) { // CLog::Error("Winsock shut down", __FUNCTION__); m_bInitialized = false; return; } CLog::Error(GetError(res).c_str(), __FUNCTION__); #endif } }
/** The main entry point. */ int main(int argc, char *argv[]) { char *temp; int x; enum { ACTION_RUN, ACTION_RESTART, ACTION_EXIT, ACTION_RELOAD, ACTION_PARSE } action; StartDebug(); /* Get the name of the user's local configuration file. */ temp = getenv("HOME"); if(temp) { const size_t temp_len = strlen(temp); const size_t config_len = sizeof(CONFIG_FILE); configPath = Allocate(temp_len + config_len); memcpy(configPath, temp, temp_len); memcpy(&configPath[temp_len], CONFIG_FILE, config_len); } else { configPath = CopyString(CONFIG_FILE); } /* Parse command line options. */ action = ACTION_RUN; for(x = 1; x < argc; x++) { if(!strcmp(argv[x], "-v")) { DisplayAbout(); DoExit(0); } else if(!strcmp(argv[x], "-h")) { DisplayHelp(); DoExit(0); } else if(!strcmp(argv[x], "-p")) { action = ACTION_PARSE; } else if(!strcmp(argv[x], "-restart")) { action = ACTION_RESTART; } else if(!strcmp(argv[x], "-exit")) { action = ACTION_EXIT; } else if(!strcmp(argv[x], "-reload")) { action = ACTION_RELOAD; } else if(!strcmp(argv[x], "-display") && x + 1 < argc) { displayString = argv[++x]; } else if(!strcmp(argv[x], "-f") && x + 1 < argc) { Release(configPath); configPath = CopyString(argv[++x]); } else { printf("unrecognized option: %s\n", argv[x]); DisplayHelp(); DoExit(1); } } switch(action) { case ACTION_PARSE: Initialize(); ParseConfig(configPath); DoExit(0); case ACTION_RESTART: SendRestart(); DoExit(0); case ACTION_EXIT: SendExit(); DoExit(0); case ACTION_RELOAD: SendReload(); DoExit(0); default: break; } #if defined(HAVE_SETLOCALE) && defined(ENABLE_NLS) setlocale(LC_ALL, ""); #endif #ifdef HAVE_GETTEXT bindtextdomain("jwm", LOCALEDIR); textdomain("jwm"); #endif /* The main loop. */ StartupConnection(); do { isRestarting = shouldRestart; shouldExit = 0; shouldRestart = 0; shouldReload = 0; /* Prepare JWM components. */ Initialize(); /* Parse the configuration file. */ ParseConfig(configPath); /* Start up the JWM components. */ Startup(); /* The main event loop. */ EventLoop(); /* Shutdown JWM components. */ Shutdown(); /* Perform any extra cleanup. */ Destroy(); } while(shouldRestart); ShutdownConnection(); /* If we have a command to execute on shutdown, run it now. */ if(exitCommand) { execl(SHELL_NAME, SHELL_NAME, "-c", exitCommand, NULL); Warning(_("exec failed: (%s) %s"), SHELL_NAME, exitCommand); DoExit(1); } else { DoExit(0); } /* Control shoud never get here. */ return -1; }
/////////////////////////////////////////////////////////////////////////////// // Run /////////////////////////////////////////////////////////////////////////////// // DESCRIPTION: // This function runs the main thread loop // this implementation can be overloaded. // This function calls CSocketComm::OnDataReceived() (Virtual Function) // PARAMETERS: // NOTES: // You should not wait on the thread to end in this function or overloads /////////////////////////////////////////////////////////////////////////////// void CSocketComm::Run() { stMessageProxy stMsgProxy; DWORD dwBytes = 0L; DWORD dwTimeout = INFINITE; LPBYTE lpData = (LPBYTE)&stMsgProxy; DWORD dwSize = sizeof(stMsgProxy); bool bSmartAddressing = IsSmartAddressing(); if ( !bSmartAddressing ) { lpData = stMsgProxy.byData; dwSize = sizeof(stMsgProxy.byData); } // Should we run as server mode if (IsServer() && !bSmartAddressing) { if (!IsBroadcast()) { SOCKET sock = (SOCKET) m_hComm; sock = WaitForConnection( sock ); // Get new connection socket if (sock != INVALID_SOCKET) { ShutdownConnection( (SOCKET) m_hComm); m_hComm = (HANDLE) sock; OnEvent( EVT_CONSUCCESS, NULL ); // connect } else { // Do not send event if we are closing if (IsOpen()) OnEvent( EVT_CONFAILURE, NULL ); // wait fail return; } } } else { GetPeerName( stMsgProxy.address ); } while( IsOpen() ) { // Blocking mode: Wait for event dwBytes = ReadComm(lpData, dwSize, dwTimeout); // Error? - need to signal error if (dwBytes == (DWORD)-1L) { // Do not send event if we are closing if (IsOpen()) { if ( bSmartAddressing ) { RemoveFromList( stMsgProxy.address ); } OnEvent( EVT_CONDROP, &stMsgProxy.address ); // lost connection } // special case for UDP, alert about the event but do not stop if ( bSmartAddressing ) continue; else break; } // Chars received? if ( bSmartAddressing && dwBytes == sizeof(SOCKADDR_IN)) { OnEvent( EVT_ZEROLENGTH, NULL ); } else if (dwBytes > 0L) { OnDataReceived( lpData, dwBytes); } //Sleep(0); } }
void PopSession::LogoutDone() { // disconnect the connection MojLogInfo(m_log, "Shutting down connection after successful log out"); ShutdownConnection(); }
int _tmain(int argc, _TCHAR* argv[]) { const std::string Pop3Server = "pop3.lolipop.jp"; const bool UseSSL = false; const unsigned short Pop3Port = UseSSL ? 995 : 110; const std::string Pop3User = "******"; const std::string Pop3Pass = "******"; UseWinSock ws(2, 2); if( !ws ) return -1; u_long srvr_bin_addr = GetBinAddr(Pop3Server.c_str()); if( INADDR_NONE==srvr_bin_addr ) { return -1; } sockaddr_in ssock_addr; ssock_addr.sin_family = AF_INET; ssock_addr.sin_port = htons(Pop3Port); ssock_addr.sin_addr.s_addr = srvr_bin_addr; SOCKET hServerSock = socket(AF_INET, SOCK_STREAM, 0); if( INVALID_SOCKET == hServerSock ) return -1; AutoCloseSocket CloseSocket(hServerSock); int ws_ret = connect(hServerSock, (sockaddr *)&ssock_addr, sizeof(ssock_addr)); if( SOCKET_ERROR != ws_ret ) { AutoShutdownConnection ShutdownConnection(hServerSock, SD_BOTH); std::cout<<"Connected to: "<<Pop3Server<<" port:"<<Pop3Port<<std::endl; try { LSockByteStream ss(hServerSock); LSSLContext SSLCtx;//in case we will need SSL LSSLByteStream ssls(&ss);//in case we will need SSL if( UseSSL ) { SSLCtx.AcquireCredentials(); SSLCtx.Handshake(&ss, to_wstring(Pop3Server).c_str() ); ssls.SetSSLContext(&SSLCtx); } //POP3 protocol conversation LPop3 pop3( UseSSL ? (LByteStream*)&ssls : (LByteStream*)&ss ); pop3.Greeting(); std::cout<<"Server greeting: "<<pop3.GetResponse(); if( pop3.USER(Pop3User) && pop3.PASS(Pop3Pass) ) { std::cout<<"User name: "<<Pop3User<<std::endl; unsigned int MessagesCount; pop3.STAT(&MessagesCount); std::cout<<"Total messages: "<<MessagesCount<<std::endl<<std::endl; std::vector<char> msg_body; for( unsigned int i=1; i<MessagesCount+1; ++i) { pop3.TOP(i, 100, &msg_body); msg_body.push_back('\0'); std::cout<<"Message #"<<i<<" headers:"<<std::endl; std::cout<<&msg_body[0]; CStringA aa = &msg_body[0]; } } pop3.QUIT(); } catch(LPop3::BAD_POP3_PROTOCOL&){//some problem with POP3 return -1; } catch(LBS_EOF&){//connection closed. return -1; } catch(LSSL_SEC_E&){//some problems with ssl. return -1; } catch(int){//some problem with socket io. return -1; } } else return -1; return 0; }
void SocketListener::AcceptConnections() { sockaddr_in endpoint; int endpointSize = sizeof(endpoint); while (this->listening) { fd_set readFDs, writeFDs, exceptFDs; this->SetupFileDescriptorSets(readFDs, writeFDs, exceptFDs, this->listener); if (select(0, &readFDs, &writeFDs, &exceptFDs, 0) > 0) { // Listener socket? if (FD_ISSET(this->listener, &readFDs)) { SOCKET sd = accept(this->listener, (sockaddr*)&endpoint, &endpointSize); if (sd != INVALID_SOCKET) { // Connection accepted connections.push_back(Connection(sd)); // Set "no block" mode on socket u_long noBlock = 1; ioctlsocket(sd, FIONBIO, &noBlock); } else { // "accept() failed" } } // Exception on listener socket else if (FD_ISSET(this->listener, &exceptFDs)) { // Exception on listening socket } // Or one of clients? auto i = connections.begin(); while (i != connections.end()) { bool ok = true; const char* error = nullptr; if (FD_ISSET(i->socket, &exceptFDs)) { ok = false; error = "General socket error"; FD_CLR(i->socket, &exceptFDs); } else { if (FD_ISSET(i->socket, &readFDs)) { ok = this->ReadData(*i); error = "Read error"; FD_CLR(i->socket, &readFDs); } if (FD_ISSET(i->socket, &writeFDs)) { // Writing not implemented... FD_CLR(i->socket, &writeFDs); } } if (!ok) { // Something bad happened on the socket, or the // client closed its half of the connection. Shut // the conn down and remove it from the list. int err; int errlen = sizeof(err); getsockopt(i->socket, SOL_SOCKET, SO_ERROR, (char*)&err, &errlen); if (err != NO_ERROR) { //std::cout << WSAGetLastErrorMessage(error, err) << std::endl; //std::cout << "Error"; } ShutdownConnection(*i); connections.erase(i); i = connections.begin(); } else { ++i; } } } else { // select() failed } } }