// Destructor BufferedSocket::~BufferedSocket() { if (m_SendBufferHandler != NULL) { delete m_SendBufferHandler; m_SendBufferHandler = NULL; } if (m_ReceiveBufferHandler != NULL) { delete m_ReceiveBufferHandler; m_ReceiveBufferHandler = NULL; } if (m_SendBuffer != NULL) { free(m_SendBuffer); m_SendBuffer = NULL; } if (m_ReceiveBuffer != NULL) { free(m_ReceiveBuffer); m_ReceiveBuffer = NULL; } DestroySocket(); }
void CSocketServer::ReleaseSockets() { CCriticalSection::Owner lock( m_listManipulationSection ); Socket *pSocket = m_activeList.Head(); while ( pSocket ) { Socket *pNext = SocketList::Next( pSocket ); pSocket->Close(); pSocket = pNext; } while ( m_activeList.Head() ) { ReleaseSocket( m_activeList.Head() ); } while ( m_freeList.Head() ) { DestroySocket( m_freeList.PopNode() ); } if ( m_freeList.Count() + m_freeList.Count() != 0 ) { /* * call to unqualified virtual function */ OnError( _T("CSocketServer::ReleaseSockets() - Leaked sockets") ); } }
void CServerConnect::CheckForTimeout() { DWORD dwServerConnectTimeout = CONSERVTIMEOUT; // If we are using a proxy, increase server connection timeout to default connection timeout if (thePrefs.GetProxySettings().UseProxy) dwServerConnectTimeout = max(dwServerConnectTimeout, CONNECTION_TIMEOUT); DWORD dwCurTick = GetTickCount(); DWORD tmpkey; CServerSocket* tmpsock; POSITION pos = connectionattemps.GetStartPosition(); while (pos){ connectionattemps.GetNextAssoc(pos,tmpkey,tmpsock); if (!tmpsock){ if (thePrefs.GetVerbose()) DebugLogError(_T("Error: Socket invalid at timeoutcheck")); connectionattemps.RemoveKey(tmpkey); return; } if (dwCurTick - tmpkey > dwServerConnectTimeout){ LogWarning(GetResString(IDS_ERR_CONTIMEOUT), tmpsock->cur_server->GetListName(), tmpsock->cur_server->GetAddress(), tmpsock->cur_server->GetPort()); connectionattemps.RemoveKey(tmpkey); DestroySocket(tmpsock); if (singleconnecting) StopConnectionTry(); else TryAnotherConnectionRequest(); } } }
void CTcpEpollServer::Destroy(void) { // 关闭SOCKET if(m_hListenSocket != INVALID_SOCKET) { DestroySocket(m_hListenSocket); m_hListenSocket = INVALID_SOCKET; m_ListenContext.m_hSocket = INVALID_SOCKET; } //关闭EPOLL句柄 if (m_hEpollHandle != -1) { DestroyEpoll(m_hEpollHandle); m_hEpollHandle = -1; } // 关闭所有SOCKET //关闭所有已连接SOCKET while (GetTcpContextCount() > 0) { CloseAllContext(); } // 等待线程退出 m_EpollWaitThread.WaitThreadExit(); m_CheckThread.WaitThreadExit(); }
CMuleUDPSocket::~CMuleUDPSocket() { theApp->uploadBandwidthThrottler->RemoveFromAllQueues(this); wxMutexLocker lock(m_mutex); DestroySocket(); }
CServerConnect::~CServerConnect(){ // stop all connections StopConnectionTry(); // close connected socket, if any DestroySocket(connectedsocket); connectedsocket = NULL; // close udp socket if (udpsocket){ udpsocket->Close(); delete udpsocket; } }
void CMuleUDPSocket::OnDisconnected(int WXUNUSED(errorCode)) { /* Due to bugs in wxWidgets, UDP sockets will sometimes * be closed. This is caused by the fact that wx treats * zero-length datagrams as EOF, which is only the case * when dealing with streaming sockets. * * This has been reported as patch #1885472: * http://sourceforge.net/tracker/index.php?func=detail&aid=1885472&group_id=9863&atid=309863 */ AddDebugLogLineC(logMuleUDP, m_name + wxT("Socket died, recreating.")); DestroySocket(); CreateSocket(); }
void CMuleUDPSocket::OnReceive(int errorCode) { AddDebugLogLineN(logMuleUDP, CFormat(wxT("Got UDP callback for read: Error %i Socket state %i")) % errorCode % Ok()); char buffer[UDP_BUFFER_SIZE]; amuleIPV4Address addr; unsigned length = 0; bool error = false; int lastError = 0; { wxMutexLocker lock(m_mutex); if (errorCode || (m_socket == NULL) || !m_socket->IsOk()) { DestroySocket(); CreateSocket(); return; } length = m_socket->RecvFrom(addr, buffer, UDP_BUFFER_SIZE); lastError = m_socket->LastError(); error = lastError != 0; } const uint32 ip = StringIPtoUint32(addr.IPAddress()); const uint16 port = addr.Service(); if (error) { OnReceiveError(lastError, ip, port); } else if (length < 2) { // 2 bytes (protocol and opcode) is the smallets possible packet. AddDebugLogLineN(logMuleUDP, m_name + wxT(": Invalid Packet received")); } else if (!ip) { // wxFAIL; AddLogLineNS(wxT("Unknown ip receiving a UDP packet! Ignoring: '") + addr.IPAddress() + wxT("'")); } else if (!port) { // wxFAIL; AddLogLineNS(wxT("Unknown port receiving a UDP packet! Ignoring")); } else if (theApp->clientlist->IsBannedClient(ip)) { AddDebugLogLineN(logMuleUDP, m_name + wxT(": Dropped packet from banned IP ") + addr.IPAddress()); } else { AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Packet received (")) << addr.IPAddress() << wxT(":") << port << wxT("): ") << length << wxT("b")); OnPacketReceived(ip, port, (byte*)buffer, length); } }
void CTcpIocpServer::Destroy(void) { // 销毁SOCKET套接字 if(INVALID_SOCKET != m_hListenSocket) { DestroySocket(m_hListenSocket); m_hListenSocket = INVALID_SOCKET; } //关闭检查线程 if(INVALID_HANDLE_VALUE != m_hAcceptEvent) { WSASetEvent(m_hAcceptEvent); } //等待Context删除完成 while ((GetTcpContextCount() > 0 || GetAcceptExCount() > 0)) { //关闭所有已连接SOCKET CloseAllContext(); //关闭所有未连接SOCKET CloseAllAcceptExSocket(); Sleep(5); } // 销毁完成端口句柄 if(INVALID_HANDLE_VALUE != m_hIocp) { DestroyCompletePort(m_hIocp); m_hIocp = INVALID_HANDLE_VALUE; } // 销毁ACCEPT事件 if(INVALID_HANDLE_VALUE != m_hAcceptEvent) { DestroyAcceptEvent(m_hAcceptEvent); m_hAcceptEvent = INVALID_HANDLE_VALUE; } // 等待线程退出 m_CheckThread.WaitThreadExit(); // 清空缓存 m_OverloapCache.Clear(); }
void CMuleUDPSocket::CreateSocket() { wxCHECK_RET(!m_socket, wxT("Socket already opened.")); m_socket = new CEncryptedDatagramSocket(m_addr, wxSOCKET_NOWAIT, m_proxy); m_socket->SetClientData(this); m_socket->SetEventHandler(*theApp, m_id); m_socket->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_OUTPUT_FLAG | wxSOCKET_LOST_FLAG); m_socket->Notify(true); if (!m_socket->IsOk()) { AddDebugLogLineC(logMuleUDP, wxT("Failed to create valid ") + m_name); DestroySocket(); } else { AddLogLineN(wxString(wxT("Created ")) << m_name << wxT(" at port ") << m_addr.Service()); } }
bool CServerConnect::Disconnect() { if (connected && connectedsocket) { theApp.sharedfiles->ClearED2KPublishInfo(); connected = false; CServer* pServer = theApp.serverlist->GetServerByAddress(connectedsocket->cur_server->GetAddress(), connectedsocket->cur_server->GetPort()); if (pServer) theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pServer); theApp.SetPublicIP(0); DestroySocket(connectedsocket); connectedsocket = NULL; theApp.emuledlg->ShowConnectionState(); theStats.serverConnectTime = 0; theStats.Add2TotalServerDuration(); return true; } return false; }
void StopSniffer(struct ISlist *iq) { struct tpacket_stats st; int len = sizeof(st); if (!getsockopt(iq -> fd,SOL_PACKET,PACKET_STATISTICS, (char *)&st,(socklen_t *)&len)) fprintf(stderr, "transimited %d packets dropped %d\n", st.tp_packets,st.tp_drops); if ( iq -> ps_hdr_start ) munmap(iq -> ps_hdr_start, iq -> packet_req -> tp_block_size * iq -> packet_req -> tp_block_nr); if ( iq -> fd ) DestroySocket(iq -> fd); pthread_mutex_lock(&m); ISlist_remove(iq); pthread_mutex_unlock(&m); free(iq -> args); }
void CSocketServer::ReleaseSocket( Socket *pSocket ) { if ( !pSocket ) { throw CException( _T("CSocketServer::ReleaseSocket()"), _T("pSocket is null") ); } CCriticalSection::Owner lock( m_listManipulationSection ); pSocket->RemoveFromList(); if ( m_maxFreeSockets == 0 || m_freeList.Count() < m_maxFreeSockets ) { m_freeList.PushNode( pSocket ); } else { DestroySocket( pSocket ); } }
bool BufferedSocket::CreateSocket() { DestroySocket(); m_Socket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if(m_Socket < 0) { CheckError(); return false; } if (connect(m_Socket, (struct sockaddr *)&m_RemoteAddress, sizeof(m_RemoteAddress)) == -1) { CheckError(); return false; } return true; }
void CServerConnect::StopConnectionTry() { connectionattemps.RemoveAll(); connecting = false; singleconnecting = false; theApp.emuledlg->ShowConnectionState(); if (m_idRetryTimer) { KillTimer(NULL, m_idRetryTimer); m_idRetryTimer= 0; } // close all currenty opened sockets except the one which is connected to our current server for( POSITION pos = m_lstOpenSockets.GetHeadPosition(); pos != NULL; ) { CServerSocket* pSck = (CServerSocket*)m_lstOpenSockets.GetNext(pos); if (pSck == connectedsocket) // don't destroy socket which is connected to server continue; if (pSck->m_bIsDeleting == false) // don't destroy socket if it is going to destroy itself later on DestroySocket(pSck); } }
// Write a socket wxInt32 BufferedSocket::SendData(wxInt32 Timeout) { CreateSocket(); // create a transfer buffer, from memory stream to socket wxStopWatch sw; // clear it memset(sData, 0, sizeof(sData)); // copy data wxInt32 actual_size = send_buf->CopyTo(sData, MAX_PAYLOAD); // set the start ping // (Horrible, needs to be improved) SendPing = sw.Time(); // send the data if (!Socket->WaitForWrite(0,Timeout)) { CheckError(); SendPing = 0; RecvPing = 0; DestroySocket(); return 0; } else Socket->SendTo(to_addr, sData, actual_size); CheckError(); // return the amount of bytes sent return Socket->LastCount(); }
U1 NetServer::Destroy(){ //关闭SOCKET DestroySocket(); //关闭SOCKET 停止监听线程 这里才能安全退出 if(!m_ThreadListen.StopThreadWaitForExit()){ } //停止发送线程 if(!m_ThreadSend.StopThreadWaitForExit()){ } m_ReceiveCS.Enter(); std::list<U32> lstSocket; std::list<NetReceiveThread*> lstThread; //获取所有接收线程的ID 和 线程指针 ReceiveThreadMap::iterator i = m_mapReceiveThread.begin(); for(;i!=m_mapReceiveThread.end();i++){ lstSocket.push_back(i->first); lstThread.push_back(i->second); } m_ReceiveCS.Leave(); //关闭SOCKET std::list<U32>::iterator ii = lstSocket.begin(); for(;ii!=lstSocket.end();ii++){ U32 uiSocket = (U32)(*ii); //关闭Socket 这里会使接收线程自动退出 closesocket(uiSocket); } //等待所有线程关闭 std::list<NetReceiveThread*>::iterator it = lstThread.begin(); for(;it!=lstThread.end();it++){ NetReceiveThread* p = (NetReceiveThread*)(*it); while(p->IsRunning()){ p->StopThreadWaitForExit(); } } m_ReceiveCS.Enter(); //清空未使用的线程 ReceiveThreadList::iterator itr = m_lstUnUsedThread.begin(); for(;itr!=m_lstUnUsedThread.end();itr++){ NetReceiveThread* p = (NetReceiveThread*)(*itr); if(p!=NULL){ if(p->IsRunning()){ p->StopThreadWaitForExit(); } } SAFE_DELETE(p); } m_lstUnUsedThread.clear(); m_ReceiveCS.Leave(); return true; }
void StartSniffer(struct ISlist *iq) { struct ifreq newfl; struct iovec packet_ring; struct tpacket_hdr *packet_hdr; struct pollfd pfd; register int i; int size; iq -> fd = CreateSocket(PF_PACKET, SOCK_RAW, iq -> args -> protocol); newfl = GetIndex(iq -> fd, iq -> args -> device); //promiscous mode SetPromisc(iq -> fd, newfl); //calculate packet request for packet_ring iq -> packet_req = CalculatePacket(); RequestPacketRing(iq -> fd, PACKET_RX_RING, *(iq -> packet_req)); size = iq -> packet_req -> tp_block_size * iq -> packet_req -> tp_block_nr; iq -> ps_hdr_start =(unsigned char *) mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, iq -> fd, 0); if ( iq -> ps_hdr_start == MAP_FAILED ) { perror("mmap()"); DestroySocket(iq -> fd); exit(ERROR); } pfd.fd = iq -> fd; pfd.revents = 0; pfd.events = POLLIN|POLLRDNORM|POLLERR; i = 0; while(i < iq->args->packet_num || iq->args->packet_num == 0) { packet_hdr = (struct tpacket_hdr *) (iq -> ps_hdr_start+iq -> packet_req -> tp_frame_size*i); switch(packet_hdr -> tp_status) { case TP_STATUS_KERNEL: if ( poll(&pfd, 1, -1) < 0 ) { perror("poll: "); exit(ERROR); } if ( packet_hdr -> tp_status != TP_STATUS_USER ) packet_hdr -> tp_status = TP_STATUS_USER; break; case TP_STATUS_USER: case 5: case 9: case 13: packet_ring.iov_base = ((unsigned char *)packet_hdr+packet_hdr -> tp_mac); packet_ring.iov_len = iq -> packet_req -> tp_frame_size - packet_hdr -> tp_mac; iq -> args -> FunctionPtr(&packet_ring, iq -> args -> argv); packet_hdr -> tp_status = TP_STATUS_KERNEL; if ( iq -> args->packet_num >= iq -> packet_req -> tp_frame_nr ) iq->args->packet_num--; i = (((unsigned)i) == (unsigned)iq -> packet_req -> tp_frame_nr-1)? 0 : i+1; break; default: if ( poll(&pfd, 1, -1) < 0 ) { perror("poll: "); exit(ERROR); } if ( iq -> args -> packet_num >= iq -> packet_req -> tp_frame_nr ) iq->args->packet_num--; i = (((unsigned)i) == (unsigned)iq -> packet_req -> tp_frame_nr-1)? 0 : i+1; break; } } }
//todo len+sizeof(struct tpacket_hdr) has to be equal with frame void StartInjector(struct ISlist *iq) { struct ifreq newfl; struct iovec packet_ring; struct tpacket_hdr *packet_hdr; struct pollfd pfd; register int i; struct sockaddr_ll sock_ll; int size; int data_off, blocknum; data_off = TPACKET_HDRLEN- sizeof(struct sockaddr_ll); //create socket iq -> fd = CreateSocket(PF_PACKET, SOCK_RAW, iq -> args -> protocol); //get index bind socket newfl = GetIndex(iq -> fd, iq ->args->device); memset((char *)&sock_ll, '\0', sizeof(struct sockaddr_ll)); sock_ll.sll_family = AF_PACKET; sock_ll.sll_protocol = htons(iq->args->protocol); sock_ll.sll_ifindex = newfl.ifr_ifindex; BindSocket(iq -> fd, (struct sockaddr *)&sock_ll, sizeof(struct sockaddr_ll)); iq -> packet_req = CalculatePacket(); RequestPacketRing(iq -> fd, PACKET_TX_RING, *(iq -> packet_req)); //map shared memory size = iq -> packet_req -> tp_block_size * iq -> packet_req -> tp_block_nr; iq -> ps_hdr_start =(unsigned char *) mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, iq -> fd, 0); if ( iq -> ps_hdr_start == MAP_FAILED ) { perror("mmap()"); DestroySocket(iq -> fd); exit(ERROR); } //poll for our fd pfd.fd = iq -> fd; pfd.revents = 0; pfd.events = POLLIN|POLLRDNORM|POLLERR; i = 0; while (i < iq ->args->packet_num || iq->args->packet_num == 0 ) { packet_hdr = (struct tpacket_hdr *)(iq -> ps_hdr_start+iq -> packet_req -> tp_frame_size*i); switch(packet_hdr -> tp_status) { case TP_STATUS_AVAILABLE: packet_ring.iov_base = ((unsigned char *)packet_hdr+data_off); iq -> args -> FunctionPtr(&packet_ring, iq -> args ->argv); packet_hdr -> tp_len = packet_ring.iov_len; if ( packet_hdr -> tp_len == 0 ) break; packet_hdr->tp_status = TP_STATUS_SEND_REQUEST; if ( sendto(iq -> fd, NULL, 0, MSG_DONTWAIT, NULL, 0) == ERROR ) { perror("send:"); exit(ERROR); } if ( iq -> args-> packet_num >= iq -> packet_req -> tp_frame_nr ) iq -> args -> packet_num--; i = (((unsigned)i) == (unsigned)iq -> packet_req -> tp_frame_nr-1)? 0 : i+1; break; case TP_STATUS_SENDING: if ( poll(&pfd, 1, -1) < 0 ) { perror("poll: "); exit(ERROR); } break; case TP_STATUS_WRONG_FORMAT: fprintf(stderr, "An error has occured during" "transfer\n"); exit(ERROR); } } }
int main(int argumentCount, char* arguments[]) { SysCtrlNode server; ClientConnector clientConnector; /*handle connection with client*/ PlNodeConnector plNodeConnector; /*handle connection with plNode*/ BackupSysCtrlNodeController backupSysCtrlNodeController; /*handle backup sys ctrl node*/ MyLog logger; bool recovery = false; char buffer[1024]; bool backup = false; int i; int portIndex = 0; int portToListen; int portToConnect; // char buffer[1024]; // int cmd; // printf("recovery? 0(false) / 1(true) \n"); // gets(buffer); // sscanf(buffer, "%d", &cmd); // if (cmd == 0) // { // recovery = false; // } // else if (cmd == 1) // { // recovery = true; // } for (i = 1; i < argumentCount; ++i) { if (0 == strcmp("recover", arguments[i])) { recovery = true; } if (0 == strcmp("backup", arguments[i])) { backup = true; } if (1 == sscanf(arguments[i], "portIndex%d", &portIndex)) { } } InitializeMemeryHook(); StartSocket(); if (!InitConfig()) { printf("config file cannot be found.\n"); getchar(); return 0; } InitLogSystem(&logger, "SysCtrlNodeLog.txt", recovery); SysCtrlNodeConstruct(&server, &logger, backup, recovery); ClientConnectorConstruct(&clientConnector, &server); ClientConnectorSetListeningPort(&clientConnector, portIndex == 0 ? g_configData.clientListeningPort : g_configData.clientListeningPort2); SysCtrlNodeSetClientConnector(&server, &clientConnector); PlNodeConnectorConstruct(&plNodeConnector, &server); PlNodeConnectorSetListeningPort(&plNodeConnector, portIndex == 0 ? g_configData.plNodeListeningPort : g_configData.plNodeListeningPort2); SysCtrlNodeSetPlNodeConnector(&server, &plNodeConnector); BackupSysCtrlNodeControllerConstruct(&backupSysCtrlNodeController, &server); if (portIndex == 0) { portToListen = g_configData.selfListeningPort; portToConnect = g_configData.selfListeningPort2; } else { portToListen = g_configData.selfListeningPort2; portToConnect = g_configData.selfListeningPort; } // connect to other port BackupSysCtrlNodeControllerSetTargetServerIPAndPort(&backupSysCtrlNodeController, g_configData.szIP, portToListen, portIndex, portToConnect); SysCtrlNodeSetBackupSysCtrlNodeController(&server, &backupSysCtrlNodeController); SysCtrlNodeStart(&server); printf("**** To shutdown the whole system, type 'shutdown' in either SysCtrlNode. ****\n"); do { gets(buffer); } while (strcmp(buffer, "shutdown") != 0); SysCtrlNodeShutdownSystem(&server); PlNodeConnectorDestruct(&plNodeConnector); ClientConnectorDestruct(&clientConnector); SysCtrlNodeDestruct(&server); DestroyLogSystem(&logger); DestroySocket(); if (FinalCheckMemoryAllocation()) { } return 0; }
Server::~Server() { DestroySocket(this->_socket); }
void CServerConnect::ConnectionEstablished(CServerSocket* sender) { if (!connecting) { // we are already connected to another server DestroySocket(sender); return; } InitLocalIP(); if (sender->GetConnectionState() == CS_WAITFORLOGIN) { AddLogLine(false, GetResString(IDS_CONNECTEDTOREQ), sender->cur_server->GetListName(), sender->cur_server->GetAddress(), sender->IsServerCryptEnabledConnection() ? sender->cur_server->GetObfuscationPortTCP() : sender->cur_server->GetPort()); CServer* pServer = theApp.serverlist->GetServerByAddress(sender->cur_server->GetAddress(), sender->cur_server->GetPort()); if (pServer) { pServer->ResetFailedCount(); theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pServer); } // Send login packet CSafeMemFile data(256); data.WriteHash16(thePrefs.GetUserHash()); data.WriteUInt32(GetClientID()); data.WriteUInt16(thePrefs.GetPort()); UINT tagcount = 4; data.WriteUInt32(tagcount); CTag tagName(CT_NAME, thePrefs.GetUserNick()); tagName.WriteTagToFile(&data); CTag tagVersion(CT_VERSION, EDONKEYVERSION); tagVersion.WriteTagToFile(&data); uint32 dwCryptFlags = 0; if (thePrefs.IsClientCryptLayerSupported()) dwCryptFlags |= SRVCAP_SUPPORTCRYPT; if (thePrefs.IsClientCryptLayerRequested()) dwCryptFlags |= SRVCAP_REQUESTCRYPT; if (thePrefs.IsClientCryptLayerRequired()) dwCryptFlags |= SRVCAP_REQUIRECRYPT; CTag tagFlags(CT_SERVER_FLAGS, SRVCAP_ZLIB | SRVCAP_NEWTAGS | SRVCAP_LARGEFILES | SRVCAP_UNICODE | dwCryptFlags); tagFlags.WriteTagToFile(&data); // eMule Version (14-Mar-2004: requested by lugdunummaster (need for LowID clients which have no chance // to send an Hello packet to the server during the callback test)) CTag tagMuleVersion(CT_EMULE_VERSION, //(uCompatibleClientID << 24) | (CemuleApp::m_nVersionMjr << 17) | (CemuleApp::m_nVersionMin << 10) | (CemuleApp::m_nVersionUpd << 7) ); tagMuleVersion.WriteTagToFile(&data); Packet* packet = new Packet(&data); packet->opcode = OP_LOGINREQUEST; if (thePrefs.GetDebugServerTCPLevel() > 0) Debug(_T(">>> Sending OP__LoginRequest\n")); theStats.AddUpDataOverheadServer(packet->size); SendPacket(packet, true, sender); } else if (sender->GetConnectionState() == CS_CONNECTED) { theStats.reconnects++; theStats.serverConnectTime = GetTickCount(); connected = true; CString strMsg; if (sender->IsObfusicating()) strMsg.Format(GetResString(IDS_CONNECTEDTOOBFUSCATED) + _T(" (%s:%u)"), sender->cur_server->GetListName(), sender->cur_server->GetAddress(), sender->cur_server->GetObfuscationPortTCP()); else strMsg.Format(GetResString(IDS_CONNECTEDTO) + _T(" (%s:%u)"), sender->cur_server->GetListName(), sender->cur_server->GetAddress(), sender->cur_server->GetPort()); Log(LOG_SUCCESS | LOG_STATUSBAR, strMsg); theApp.emuledlg->ShowConnectionState(); connectedsocket = sender; StopConnectionTry(); theApp.sharedfiles->ClearED2KPublishInfo(); theApp.sharedfiles->SendListToServer(); theApp.emuledlg->serverwnd->serverlistctrl.RemoveAllDeadServers(); // tecxx 1609 2002 - serverlist update if (thePrefs.GetAddServersFromServer()) { Packet* packet = new Packet(OP_GETSERVERLIST,0); if (thePrefs.GetDebugServerTCPLevel() > 0) Debug(_T(">>> Sending OP__GetServerList\n")); theStats.AddUpDataOverheadServer(packet->size); SendPacket(packet, true); } CServer* pServer = theApp.serverlist->GetServerByAddress(sender->cur_server->GetAddress(), sender->cur_server->GetPort()); if (pServer) theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pServer); } theApp.emuledlg->ShowConnectionState(); }
clSocketBase::~clSocketBase() { DestroySocket(); }
/// 完成端口线程函数 void CTcpEpollServer::EpollWaitFunc(void) { int32_t nEventCount = 0; struct epoll_event EpollEvent[128]; //epoll事件对象 while(-1 != m_hEpollHandle) { nEventCount = epoll_wait(m_hEpollHandle, EpollEvent, 128, 500); if (nEventCount == -1) { continue; } for (uint32_t nIndex = 0; nIndex < nEventCount; ++nIndex) { struct epoll_event* pEpollEvent = &EpollEvent[nIndex]; CTcpContext* lpContext = (CTcpContext*)pEpollEvent->data.ptr; SOCKET hSocket = lpContext->m_hSocket; if (hSocket == m_hListenSocket) { SOCKET hAcceptSocket = INVALID_SOCKET; struct sockaddr_in oAddr; socklen_t nAddrSize = sizeof(sockaddr_in); do { uint32_t nAddrLen = sizeof(sockaddr_in); hAcceptSocket = accept(m_hListenSocket, (sockaddr*)&oAddr, &nAddrSize); if(INVALID_SOCKET == hAcceptSocket) { //当端口是非阻塞时,accept返回-1,并设置errno为EAGAIN,此时应该继续接受连接 //当端口是非阻塞时,非阻塞套接字上不能立即完成的操作返回,设置errno为EWOULDBLOCK,此时应该继续接受连接 if (errno != EAGAIN && errno != EWOULDBLOCK) { } break; } if(!EpollAcceptSocket(hAcceptSocket, oAddr)) { DestroySocket(hAcceptSocket); } }while(hAcceptSocket != INVALID_SOCKET); } else { if (pEpollEvent->events & EPOLLIN) { int32_t nRecvSize = 0; char szRecvBuff[MAX_PACK_BUFFER_SIZE]; do { nRecvSize = recv(hSocket, szRecvBuff, MAX_PACK_BUFFER_SIZE, MSG_NOSIGNAL); if(nRecvSize > 0) { DealRecvData(szRecvBuff, nRecvSize, lpContext); } //接收数据长度为0,说明连接断开了 else if(nRecvSize == 0) { // 关闭连接 RemoveTcpContext(lpContext); break; } else { //当端口是非阻塞时,recv返回-1,并设置errno为EAGAIN,此时应该是数据读完了, //当端口是非阻塞时,非阻塞套接字上不能立即完成的操作返回,设置errno为EWOULDBLOCK,此时应该是数据读完了 if (errno != EAGAIN && errno != EWOULDBLOCK) { // 关闭连接 RemoveTcpContext(lpContext); } } }while(nRecvSize > 0); } if(pEpollEvent->events & EPOLLOUT) { m_SendQueue.SendPacket(hSocket); } } } } }
// Read a socket wxInt32 BufferedSocket::GetData(wxInt32 Timeout) { // temporary address, for comparison wxIPV4address in_addr; wxStopWatch sw; // clear it memset(rData, 0, sizeof(rData)); if (!Socket->WaitForRead(0, Timeout)) { CheckError(); SendPing = 0; RecvPing = 0; DestroySocket(); return 0; } else Socket->RecvFrom(in_addr, rData, MAX_PAYLOAD); CheckError(); // apply the receive ping // (Horrible, needs to be improved) RecvPing = sw.Time(); // get number of bytes received wxInt32 num_recv = Socket->LastCount(); // clear the socket queue Socket->Discard(); // ensure received address is the same as our remote address if (num_recv > 0) if ((in_addr.IPAddress() == to_addr.IPAddress()) && (in_addr.Service() == to_addr.Service())) { // write data to memory stream, if one doesn't already exist if (recv_buf != NULL) { delete recv_buf; recv_buf = new wxMemoryInputStream(rData, num_recv); } else recv_buf = new wxMemoryInputStream(rData, num_recv); DestroySocket(); // return bytes received return num_recv; } SendPing = 0; RecvPing = 0; DestroySocket(); return 0; }
// Read a socket wxInt32 BufferedSocket::GetData(const wxInt32 &Timeout) { wxInt32 res; fd_set readfds; struct timeval tv; wxStopWatch sw; // clear it memset(m_ReceiveBuffer, 0, MAX_PAYLOAD); wxInt32 ReceivedSize = 0; bool DestroyMe = false; // Wait for read with timeout if(Timeout >= 0) { FD_ZERO(&readfds); FD_SET(m_Socket, &readfds); tv.tv_sec = Timeout / 1000; tv.tv_usec = (Timeout % 1000) * 1000; // convert milliseconds to microseconds res = select(m_Socket+1, &readfds, NULL, NULL, &tv); if(res == -1) { CheckError(); DestroyMe = true; } if(res == 0) // Read Timed Out DestroyMe = true; } if (DestroyMe == true) { CheckError(); m_SendPing = 0; m_ReceivePing = 0; DestroySocket(); return 0; } ReceivedSize = recv(m_Socket, (char *)m_ReceiveBuffer, MAX_PAYLOAD, 0); // -1 = Error; 0 = Closed Connection if(ReceivedSize <= 0) { CheckError(); m_SendPing = 0; m_ReceivePing = 0; DestroySocket(); return 0; } CheckError(); // apply the receive ping m_ReceivePing = sw.Time(); if (ReceivedSize > 0) { m_BadRead = false; DestroySocket(); // return bytes received return ReceivedSize; } m_SendPing = 0; m_ReceivePing = 0; DestroySocket(); return 0; }
void ProcessSockets(void) { if (socketpool.length >= events.capacity) { bprintf("Reserving more space for events\n"); vec_reserve(&events, socketpool.length * 2); } bprintf("Entering epoll_wait\n"); int total = epoll_wait(EpollHandle, &vec_first(&events), events.capacity, config->readtimeout * 1000); if (total == -1) { if (errno != EINTR) fprintf(stderr, "Error processing sockets: %s\n", strerror(errno)); return; } for (int i = 0; i < total; ++i) { epoll_t *ev = &(events.data[i]); socket_t s; if (FindSocket(ev->data.fd, &s) == -1) { bfprintf(stderr, "Unknown FD in multiplexer: %d\n", ev->data.fd); // We don't know what socket this is. Someone added something // stupid somewhere so shut this shit down now. // We have to create a temporary socket_t object to remove it // from the multiplexer, then we can close it. socket_t tmp = { ev->data.fd, 0, 0, 0, 0 }; RemoveFromMultiplexer(tmp); close(ev->data.fd); continue; } // Call our event. CallEvent(EV_SOCKETACTIVITY, &s); if (ev->events & (EPOLLHUP | EPOLLERR)) { bprintf("Epoll error reading socket %d, destroying.\n", s.fd); DestroySocket(s, 1); continue; } // Process socket write events if (ev->events & EPOLLOUT && SendPackets(s) == -1) { bprintf("Destorying socket due to send failure!\n"); DestroySocket(s, 1); } // process socket read events. if (ev->events & EPOLLIN && ReceivePackets(s) == -1) { bprintf("Destorying socket due to receive failure!\n"); DestroySocket(s, 1); } } }
void CMuleUDPSocket::Close() { wxMutexLocker lock(m_mutex); DestroySocket(); }