void Cleanup(int index) { closesocket(g_CliSocketArr[index]); WSACloseEvent(g_CliEventArr[index]); if (index < g_iTotalConn-1) { g_CliSocketArr[index] = g_CliSocketArr[g_iTotalConn-1]; g_CliEventArr[index] = g_CliEventArr[g_iTotalConn-1]; } g_iTotalConn--; }
UINT __stdcall CSvrSyncPlug::UdpThread(LPVOID lpVoid) { CSvrSyncPlug* pThis = reinterpret_cast<CSvrSyncPlug*>(lpVoid); SOCKET sck = socket(AF_INET, SOCK_DGRAM, 0); if (sck == INVALID_SOCKET) return 0; sockaddr_in addr = {0}; addr.sin_family = AF_INET; addr.sin_port = htons(5000); addr.sin_addr.s_addr = ADDR_ANY; if (SOCKET_ERROR == bind(sck, (PSOCKADDR)&addr, sizeof(addr))) { closesocket(sck); return 0; } int RecvBufSize = 0x10000; setsockopt(sck,SOL_SOCKET, SO_RCVBUF, (char*)&RecvBufSize, sizeof(int) ); setsockopt(sck,SOL_SOCKET, SO_SNDBUF, (char*)&RecvBufSize, sizeof(int) ); WSAEVENT hNetEvent = WSACreateEvent(); if (hNetEvent == NULL || SOCKET_ERROR == WSAEventSelect(sck, hNetEvent, FD_READ)) { closesocket(sck); return 0; } HANDLE hEvents[2] = {pThis->m_hExited, hNetEvent}; while (1) { DWORD ret = WSAWaitForMultipleEvents(_countof(hEvents), hEvents, FALSE,WSA_INFINITE, FALSE); if (ret == WAIT_OBJECT_0) break; else if (ret == WAIT_OBJECT_0 + 1) { WSANETWORKEVENTS NetworkEvents; WSAEnumNetworkEvents(sck, hNetEvent, &NetworkEvents); if(NetworkEvents.lNetworkEvents == FD_READ && NetworkEvents.iErrorCode[FD_READ_BIT] == 0) { char data[4096] = {0}; pkgheader* pheader = (pkgheader*)data; int len = recvfrom(sck, data, sizeof(data), 0, NULL, NULL); if (len > 0 && pheader->Length == len) { data[len] = 0; try { pThis->UdpProcess(data, len); } catch (...) {} } } } else break; } closesocket(sck); WSACloseEvent(hNetEvent); return 0; }
void eloop_wait_for_read_sock(int sock) { WSAEVENT event; event = WSACreateEvent(); if (event == WSA_INVALID_EVENT) { printf("WSACreateEvent() failed: %d\n", WSAGetLastError()); return; } if (WSAEventSelect(sock, event, FD_READ)) { printf("WSAEventSelect() failed: %d\n", WSAGetLastError()); WSACloseEvent(event); return ; } WaitForSingleObject(event, INFINITE); WSAEventSelect(sock, event, 0); WSACloseEvent(event); }
void ListenerImpl::stopListening() { ::SetEvent(hKillEvent); WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); CloseHandle(hKillEvent); closesocket(hSocket); WSACloseEvent(hSocketEvent); }
S32 tcp_open_channel(LLHost host) { // Open a TCP channel // Jump through some hoops to ensure that if the request hosts is down // or not reachable connect() does not block S32 handle; handle = socket(AF_INET, SOCK_STREAM, 0); if (!handle) { llwarns << "Error opening TCP control socket, socket() returned " << handle << llendl; return -1; } struct sockaddr_in address; address.sin_port = htons(host.getPort()); address.sin_family = AF_INET; address.sin_addr.s_addr = host.getAddress(); // Non blocking WSAEVENT hEvent=WSACreateEvent(); WSAEventSelect(handle, hEvent, FD_CONNECT) ; connect(handle, (struct sockaddr*)&address, sizeof(address)) ; // Wait fot 5 seconds, if we can't get a TCP channel open in this // time frame then there is something badly wrong. WaitForSingleObject(hEvent, 1000*5); // 5 seconds time out WSANETWORKEVENTS netevents; WSAEnumNetworkEvents(handle,hEvent,&netevents); // Check the async event status to see if we connected if ((netevents.lNetworkEvents & FD_CONNECT) == FD_CONNECT) { if (netevents.iErrorCode[FD_CONNECT_BIT] != 0) { llwarns << "Unable to open TCP channel, WSA returned an error code of " << netevents.iErrorCode[FD_CONNECT_BIT] << llendl; WSACloseEvent(hEvent); return -1; } // Now we are connected disable non blocking // we don't need support an async interface as // currently our only consumer (socks5) will make one round // of packets then just hold the connection open WSAEventSelect(handle, hEvent, NULL) ; unsigned long NonBlock = 0; ioctlsocket(handle, FIONBIO, &NonBlock); return handle; } llwarns << "Unable to open TCP channel, Timeout is the host up?" << netevents.iErrorCode[FD_CONNECT_BIT] << llendl; return -1; }
int32_t OsNetworkReceiveFrom(THandle aHandle, uint8_t* aBuffer, uint32_t aBytes, TIpAddress* aAddress, uint16_t* aPort) { int32_t received; OsNetworkHandle* handle = (OsNetworkHandle*)aHandle; struct sockaddr_in addr; int len = sizeof(addr); WSAEVENT event; HANDLE handles[2]; DWORD ret; if (SocketInterrupted(handle)) { return -1; } sockaddrFromEndpoint(&addr, 0, 0); event = WSACreateEvent(); if (NULL == event) { return -1; } if (0 != WSAEventSelect(handle->iSocket, event, FD_READ|FD_CLOSE)) { WSACloseEvent(event); return -1; } received = recvfrom(handle->iSocket, (char*)aBuffer, aBytes, 0, (struct sockaddr*)&addr, &len); if (SOCKET_ERROR==received && WSAEWOULDBLOCK==WSAGetLastError()) { handles[0] = event; handles[1] = handle->iEvent; ret = WSAWaitForMultipleEvents(2, &handles[0], FALSE, INFINITE, FALSE); if (WAIT_OBJECT_0 == ret) { received = recvfrom(handle->iSocket, (char*)aBuffer, aBytes, 0, (struct sockaddr*)&addr, &len); } } SetSocketBlocking(handle->iSocket); WSACloseEvent(event); *aAddress = addr.sin_addr.s_addr; *aPort = SwapEndian16(addr.sin_port); return received; }
int eloop_register_read_sock(int sock, eloop_sock_handler handler, void *eloop_data, void *user_data) { WSAEVENT event; struct eloop_sock *tmp; if (eloop_prepare_handles()) return -1; event = WSACreateEvent(); if (event == WSA_INVALID_EVENT) { printf("WSACreateEvent() failed: %d\n", WSAGetLastError()); return -1; } if (WSAEventSelect(sock, event, FD_READ)) { printf("WSAEventSelect() failed: %d\n", WSAGetLastError()); WSACloseEvent(event); return -1; } tmp = os_realloc_array(eloop.readers, eloop.reader_count + 1, sizeof(struct eloop_sock)); if (tmp == NULL) { WSAEventSelect(sock, event, 0); WSACloseEvent(event); return -1; } tmp[eloop.reader_count].sock = sock; tmp[eloop.reader_count].eloop_data = eloop_data; tmp[eloop.reader_count].user_data = user_data; tmp[eloop.reader_count].handler = handler; tmp[eloop.reader_count].event = event; eloop.reader_count++; eloop.readers = tmp; if (sock > eloop.max_sock) eloop.max_sock = sock; eloop.reader_table_changed = 1; return 0; }
//--------------------------------------- void TCPSocket::Close() { if(m_xSock!=INVALID_SOCKET) { shutdown(m_xSock,SD_BOTH); closesocket(m_xSock); m_xSock=INVALID_SOCKET; if(m_hClose!=WSA_INVALID_EVENT) WSACloseEvent(m_hClose); m_hClose=WSA_INVALID_EVENT; } }
void RemoteDesktop::GatewayServer::_Run(){ std::vector<WSAEVENT> EventArray; auto socketarray = std::vector<std::shared_ptr<Gateway_Socket>>(); EventArray.reserve(WSA_MAXIMUM_WAIT_EVENTS); socketarray.reserve(WSA_MAXIMUM_WAIT_EVENTS); SOCKET listensocket = RemoteDesktop::Listen(_Port, _Host); if (listensocket == INVALID_SOCKET) return; auto newevent = WSACreateEvent(); WSAEventSelect(listensocket, newevent, FD_ACCEPT | FD_CLOSE); EventArray.push_back(newevent); socketarray.push_back(std::make_shared<Gateway_Socket>(listensocket)); WSANETWORKEVENTS NetworkEvents; auto timer = std::chrono::high_resolution_clock::now(); while (_Running && !EventArray.empty()) { auto Index = WSAWaitForMultipleEvents(EventArray.size(), EventArray.data(), FALSE, 1000, FALSE); if ((Index != WSA_WAIT_FAILED) && (Index != WSA_WAIT_TIMEOUT) && _Running) { WSAEnumNetworkEvents(socketarray[Index]->ThisSocket->socket, EventArray[Index], &NetworkEvents); if (((NetworkEvents.lNetworkEvents & FD_ACCEPT) == FD_ACCEPT) && NetworkEvents.iErrorCode[FD_ACCEPT_BIT] == ERROR_SUCCESS){ if (EventArray.size() >= WSA_MAXIMUM_WAIT_EVENTS - 1) continue;// ignore this event too many connections _HandleNewConnect(listensocket, EventArray, socketarray); } else if (((NetworkEvents.lNetworkEvents & FD_READ) == FD_READ) && NetworkEvents.iErrorCode[FD_READ_BIT] == ERROR_SUCCESS){ socketarray[Index]->Receive(); } else if (((NetworkEvents.lNetworkEvents & FD_CLOSE) == FD_CLOSE) && NetworkEvents.iErrorCode[FD_CLOSE_BIT] == ERROR_SUCCESS){ if (Index == 0) {//stop all processing, set running to false and next loop will fail and cleanup _Running = false; continue; } } } //once every second send a keep alive. this will trigger disconnects if (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - timer).count() > 1000){ _CheckForDisconnects(EventArray, socketarray); timer = std::chrono::high_resolution_clock::now(); } } for (size_t beg = 1; beg < socketarray.size(); beg++){ //OnDisconnect(sharedrockarray->at(beg));//let all callers know about the disconnect, skip slot 0 which is the listen socket } //cleanup code here for (auto x : EventArray) WSACloseEvent(x); DEBUG_MSG("_Listen Exiting"); }
static void clean(nfds_t nfds, SOCKET *fds, HANDLE *hEvents) { nfds_t i; for (i = 0; i < nfds; i++) { if (fds[i] != INVALID_SOCKET) { WSAEventSelect(fds[i], NULL, 0); } if (hEvents[i] != NULL) { WSACloseEvent(hEvents[i]); } } }
void AJ_Net_Disconnect(AJ_NetSocket* netSock) { AJ_InfoPrintf(("AJ_Net_Disconnect(nexSock=0x%p)\n", netSock)); if (netContext.tcpSock != INVALID_SOCKET) { shutdown(netContext.tcpSock, 0); closesocket(netContext.tcpSock); netContext.tcpSock = INVALID_SOCKET; } else if (netContext.udpSock != INVALID_SOCKET) { #ifdef AJ_ARDP AJ_ARDP_Disconnect(FALSE); #endif shutdown(netContext.udpSock, 0); closesocket(netContext.udpSock); netContext.udpSock = INVALID_SOCKET; } memset(netSock, 0, sizeof(AJ_NetSocket)); WSACloseEvent(recvEvent); WSACloseEvent(sendEvent); WSACloseEvent(interruptEvent); }
void tube_delete(struct tube* tube) { if(!tube) return; tube_remove_bg_listen(tube); tube_remove_bg_write(tube); tube_close_read(tube); tube_close_write(tube); if(!WSACloseEvent(tube->event)) log_err("WSACloseEvent: %s", wsa_strerror(WSAGetLastError())); lock_basic_destroy(&tube->res_lock); verbose(VERB_ALGO, "tube deleted"); free(tube); }
void DeleteOverlappedTransferBuffer(OverlappedTransferBuffer *buffer) { if (!buffer) return; delete[] buffer->buffer.buf; #ifdef WIN32 BOOL success = WSACloseEvent(buffer->overlapped.hEvent); if (success == FALSE) LOG(LogError, "Socket.cpp:DeleteOverlappedTransferBuffer: WSACloseEvent failed!"); buffer->overlapped.hEvent = WSA_INVALID_EVENT; #endif delete buffer; }
void WSA_Async::Event_Proc(){ enum{NETWORK_EVENT=0,SYSTEM_EVENT,SIZE}; wstring res; WSANETWORKEVENTS events; DWORD dwResult; m_hWSAEvent=WSACreateEvent(); WSAEventSelect(m_socket->GetSocket(),m_hWSAEvent,FD_READ|FD_CLOSE); HANDLE hWSAEvents[SIZE]; hWSAEvents[NETWORK_EVENT]=m_hWSAEvent; hWSAEvents[SYSTEM_EVENT]=m_hEvent; while(running){ dwResult=WSAWaitForMultipleEvents(SIZE,hWSAEvents,FALSE,WSA_INFINITE,FALSE); if(dwResult==WSA_WAIT_FAILED){ break; } dwResult-=WSA_WAIT_EVENT_0; WSAResetEvent(hWSAEvents[dwResult]); if(dwResult==SYSTEM_EVENT){ while(pause&&running){ if(WSAWaitForMultipleEvents(1,&m_hEvent,FALSE,WSA_INFINITE,FALSE)==WSA_WAIT_FAILED){ break; } WSAResetEvent(m_hEvent); } }else{ wstring read; read.clear(); WSAEnumNetworkEvents(m_socket->GetSocket(),m_hWSAEvent,&events); switch(events.lNetworkEvents){ case FD_READ: m_socket->Recv(&read); m_call(events.lNetworkEvents,(wchar_t*)read.c_str()); break; case FD_CLOSE: m_socket->Reset(); m_call(events.lNetworkEvents,TEXT("")); running=false; break; } } } END: running=false; pause=false; WSAResetEvent(m_hEvent); WSACloseEvent(m_hWSAEvent); }
void OsDestroy(OsContext* aContext) { if (aContext == NULL) { return; } (void)SymCleanup(aContext->iDebugSymbolHandle); if (NULL != aContext->iInterfaceChangeObserver) { aContext->iInterfaceChangeObserver->iShutdown = 1; (void)WSASetEvent(aContext->iInterfaceChangeObserver->iShutdownEvent); (void)WaitForSingleObject(aContext->iInterfaceChangeObserver->iSem, INFINITE); CloseHandle(aContext->iInterfaceChangeObserver->iSem); WSACloseEvent(aContext->iInterfaceChangeObserver->iEvent); WSACloseEvent(aContext->iInterfaceChangeObserver->iShutdownEvent); (void)closesocket(aContext->iInterfaceChangeObserver->iSocket); free(aContext->iInterfaceChangeObserver); aContext->iInterfaceChangeObserver = NULL; } (void)WSACleanup(); OsMutexDestroy(aContext->iMutex); aContext->iMutex = kHandleNull; TlsFree(aContext->iTlsIndex); free(aContext); }
void CW32SocketServer::Shutdown() { if ( m_hListenThrd ) { m_bRun = false; SetEvent( m_hListenEvent ); WaitForSingleObject( m_hListenThrd, INFINITE ); WSACloseEvent(m_hListenEvent); CloseHandle(m_hListenThrd); m_hListenEvent = m_hListenThrd = 0; } delete this; }
LWS_VISIBLE void lws_plat_context_early_destroy(struct lws_context *context) { struct lws_context_per_thread *pt = &context->pt[0]; int n = context->count_threads; while (n--) { if (pt->events) { WSACloseEvent(pt->events[0]); lws_free(pt->events); } pt++; } }
void AsyncEventPoller::CleanUp() { for (auto iter = eventFds_.begin(); iter != eventFds_.end();++iter) { WSAEVENT hEvent = iter->first; FdEntry* entry = iter->second; WSAEventSelect(entry->fd, NULL, 0); WSACloseEvent(hEvent); closesocket(entry->fd); delete entry; } eventFds_.clear(); fdEvents_.clear(); }
static void globus_l_xio_win32_blocking_destroy( globus_l_xio_win32_blocking_info_t * blocking_info) { GlobusXIOName(globus_l_xio_win32_blocking_destroy); GlobusXIOSystemDebugEnter(); WSACloseEvent(blocking_info->event); globus_free(blocking_info); GlobusXIOSystemDebugExit(); }
//--------------------------------------- void TCPAcceptSocket::Close() { if(m_xSock!=INVALID_SOCKET) { shutdown(m_xSock,SD_BOTH); closesocket(m_xSock); m_xSock=INVALID_SOCKET; } if(m_hEvent) { WSACloseEvent(m_hEvent); m_hEvent=WSA_INVALID_EVENT; } }
static void Close( VoodooLink *link ) { Link *l = link->priv; D_INFO( "Voodoo/Link: Closing connection.\n" ); // FIXME: how to close socket? direct_mutex_deinit( &l->lock ); WSACloseEvent( l->event ); D_FREE( l ); }
void UnInitSock() { if (g_wsaEvent != WSA_INVALID_EVENT) { WSACloseEvent(g_wsaEvent); } if (g_socketServer != INVALID_SOCKET) { closesocket(g_socketServer); g_socketServer = INVALID_SOCKET; } WSACleanup(); }
// // GetHostByName // struct hostent *Xbox::GetHostByName(const char *name) { static struct hostent *he = NULL; unsigned long addr = INADDR_NONE; WSAEVENT hEvent; XNDNS *pDns = NULL; INT err; if(!name) return NULL; // This data is static and it should not be freed. if(!he) { he = (struct hostent *)malloc(sizeof(struct hostent)); if(!he) { // Failed to allocate! return NULL; } he->h_addr_list = (char **)malloc(sizeof(char*)); he->h_addr_list[0] = (char *)malloc(sizeof(struct in_addr)); } if(isdigit(name[0])) addr = inet_addr(name); if(addr != INADDR_NONE) *(int *)he->h_addr_list[0] = addr; else { hEvent = WSACreateEvent(); err = XNetDnsLookup(name, hEvent, &pDns); WaitForSingleObject( (HANDLE)hEvent, INFINITE); if(!pDns || pDns->iStatus != 0) return NULL; memcpy(he->h_addr_list[0], pDns->aina, sizeof(struct in_addr)); XNetDnsRelease(pDns); WSACloseEvent(hEvent); } return he; }
void AsyncEventPoller::RemoveFd(SOCKET fd) { auto iter = fdEvents_.find(fd); if (iter == fdEvents_.end()) { return; // not found } WSAEVENT hEvent = iter->second; //clear the event record associated with socket WSAEventSelect(fd, NULL, 0); WSACloseEvent(hEvent); eventFds_.erase(hEvent); fdEvents_.erase(fd); }
/* Disconnect on the TCP layer */ void tcp_disconnect(rdpTcp * tcp) { if (tcp->sock != -1) { TCP_CLOSE(tcp->sock); tcp->sock = -1; } #ifdef _WIN32 if (tcp->wsa_event) { WSACloseEvent(tcp->wsa_event); tcp->wsa_event = 0; } #endif }
int is_socket_closed(int sock) { int nRet; HANDLE hCloseEvent = WSACreateEvent(); WSAEventSelect(sock, hCloseEvent, FD_CLOSE); DWORD dwRet = WaitForSingleObject(hCloseEvent, 1); if(dwRet == WSA_WAIT_EVENT_0) nRet = 1; else if(dwRet == WSA_WAIT_TIMEOUT) nRet = 0; WSACloseEvent(hCloseEvent); return nRet; }
ConnectionSockets::~ConnectionSockets() { int num_reserved_events=ReturnNumberOfReservedEvents(); // Close the reserved events for(int i=0;i<num_reserved_events;i++) { if(WSACloseEvent(m_events[i])==FALSE) { char msg[1024]; strcpy(msg,"Could not close reserved event "); _itoa(i,&msg[strlen(msg)],10); ::MessageBox(NULL,msg,"Error",MB_OK); } } }
int epoll_close(int epfd) { GUARD(); if(epfd < 1 || ep_data.find(epfd) == ep_data.end()) return ENOENT; ep_internal& epi = ep_data[epfd]; for(ep_internal::size_type i = 0; i < epi.size(); ++i) { // now unset the event notifications WSAEventSelect(epi[i].fd, 0, 0); // clean up event WSACloseEvent(epi[i].wsa_event); } ep_data.erase(epfd); return 0; }
/* * Performs an alertable wait for the specified event (FD_ACCEPT_BIT, * FD_CONNECT_BIT, FD_READ_BIT, FD_WRITE_BIT) on the specified socket. * Returns TRUE if the event is fired without errors. Calls WSASetLastError() * with WSAEINTR and returns FALSE if the thread is alerted. If the event is * fired but with an error WSASetLastError() is called to set the error and the * function returns FALSE. */ static gboolean alertable_socket_wait (SOCKET sock, int event_bit) { static char *EVENT_NAMES[] = { "FD_READ", "FD_WRITE", NULL /*FD_OOB*/, "FD_ACCEPT", "FD_CONNECT", "FD_CLOSE" }; gboolean success = FALSE; int error = -1; DWORD timeout = WSA_INFINITE; if (event_bit == FD_READ_BIT || event_bit == FD_WRITE_BIT) { timeout = get_socket_timeout (sock, event_bit == FD_READ_BIT ? SO_RCVTIMEO : SO_SNDTIMEO); } WSASetLastError (0); WSAEVENT event = WSACreateEvent (); if (event != WSA_INVALID_EVENT) { if (WSAEventSelect (sock, event, (1 << event_bit) | FD_CLOSE) != SOCKET_ERROR) { LOGDEBUG (g_message ("%06d - Calling WSAWaitForMultipleEvents () on socket %d", GetCurrentThreadId (), sock)); DWORD ret = WSAWaitForMultipleEvents (1, &event, TRUE, timeout, TRUE); if (ret == WSA_WAIT_IO_COMPLETION) { LOGDEBUG (g_message ("%06d - WSAWaitForMultipleEvents () returned WSA_WAIT_IO_COMPLETION for socket %d", GetCurrentThreadId (), sock)); error = WSAEINTR; } else if (ret == WSA_WAIT_TIMEOUT) { error = WSAETIMEDOUT; } else { g_assert (ret == WSA_WAIT_EVENT_0); WSANETWORKEVENTS ne = { 0 }; if (WSAEnumNetworkEvents (sock, event, &ne) != SOCKET_ERROR) { if (ne.lNetworkEvents & (1 << event_bit) && ne.iErrorCode[event_bit]) { LOGDEBUG (g_message ("%06d - %s error %d on socket %d", GetCurrentThreadId (), EVENT_NAMES[event_bit], ne.iErrorCode[event_bit], sock)); error = ne.iErrorCode[event_bit]; } else if (ne.lNetworkEvents & FD_CLOSE_BIT && ne.iErrorCode[FD_CLOSE_BIT]) { LOGDEBUG (g_message ("%06d - FD_CLOSE error %d on socket %d", GetCurrentThreadId (), ne.iErrorCode[FD_CLOSE_BIT], sock)); error = ne.iErrorCode[FD_CLOSE_BIT]; } else { LOGDEBUG (g_message ("%06d - WSAEnumNetworkEvents () finished successfully on socket %d", GetCurrentThreadId (), sock)); success = TRUE; error = 0; } } } WSAEventSelect (sock, NULL, 0); } WSACloseEvent (event); } if (error != -1) { WSASetLastError (error); } return success; }
// 소켓 정보 삭제 void RemoveSocketInfo(int nIndex) { EnterCriticalSection(&cs); SOCKETINFO *ptr = SocketInfoArray[nIndex]; closesocket(ptr->sock); delete ptr; WSACloseEvent(EventArray[nIndex]); if(nIndex != (nTotalSockets-1)){ SocketInfoArray[nIndex] = SocketInfoArray[nTotalSockets-1]; EventArray[nIndex] = EventArray[nTotalSockets-1]; } --nTotalSockets; LeaveCriticalSection(&cs); }