BOOL InitCommClient( SOCK *clnt, const char *address, unsigned short serverPortNr, unsigned short clientPortNr, int timeOutMS ) { BOOL fatal, ret = FALSE; int err; if( InitIP() && CreateClient( clnt, clientPortNr, TRUE ) ){ QTils_LogMsgEx( "Client socket opened on port %hu", clientPortNr ); if( ConnectToServer( *clnt, serverPortNr, "", address, timeOutMS, &fatal ) ){ QTils_LogMsgEx( "Connected to server \"%s:%hu\"", address, serverPortNr ); if( !SendMutex ){ SendMutex = new CritSectEx(4000); } if( !ReceiveMutex ){ ReceiveMutex = new CritSectEx(4000); } ret = TRUE; } else{ err = errSock; QTils_LogMsgEx( "Failure connecting to server \"%s:%hu\" (err=%d \"%s\")", address, serverPortNr, err, errSockText(err) ); CloseClient(clnt); } } else{ QTils_LogMsgEx( "Failure opening client socket on port %hu (err=%d \"%s\")", clientPortNr, errSock, errSockText(errSock) ); } return ret; }
void GetClient() { int new_socket; char hello[256]; new_socket = accept(server_socket, 0, 0); #ifdef _WIN32 if (new_socket == INVALID_SOCKET) return; #else if (new_socket == -1) return; #endif if (client_socket) CloseClient(); client_socket = new_socket; #ifndef _WIN32 { int flags; flags = fcntl(client_socket, F_GETFL, 0); fcntl(client_socket, F_SETFL, flags | O_NONBLOCK); } #endif sprintf(hello, "000 PCSXR Version %s - Debug console\r\n", PACKAGE_VERSION); WriteSocket(hello, strlen(hello)); ptr = 0; }
void ServerSocket::Close() { CloseClient(); #ifdef _WIN32 closesocket(my_socket); #else close(my_socket); #endif }
DWORD WINAPI CEgTcpDriver::Stop() { CAutoLock lock(&m_InitLock); if (!m_bInited) return ERROR_SERVICE_NOT_ACTIVE; m_bInited = FALSE; WSASetEvent(m_hWsaEvents[WSASHUTDOWN_EVENT]); WaitForSingleObject(m_hWSAEventThread, INFINITE); CloseHandle(m_hWSAEventThread); for (DWORD i = 0; i < m_dwThreadCount; i++) PostQueuedCompletionStatus(m_hIocp, 0, 0, NULL); HANDLE * ThreadHandles = new HANDLE[m_dwThreadCount]; for (i = 0; i < m_dwThreadCount; i++) ThreadHandles[i] = m_hThreads[i]; WaitForMultipleObjects(m_dwThreadCount, ThreadHandles, TRUE, INFINITE); delete [] ThreadHandles; for (i = 0; i < m_dwThreadCount; i++) CloseHandle(m_hThreads[i]); m_hThreads.clear(); if (m_usServerPort != CLIENT_ONLY) { closesocket(m_ListenSocket); closesocket(m_ListenSocketContext.m_pIOContext.m_SocketAccept); while (!HasOverlappedIoCompleted((LPOVERLAPPED)&m_ListenSocketContext.m_pIOContext.m_SendOverlapped)) Sleep(0); while (!HasOverlappedIoCompleted((LPOVERLAPPED)&m_ListenSocketContext.m_pIOContext.m_ReceiveOverlapped)) Sleep(0); } CloseHandle(m_hIocp); for(i = 0; i < WSATOTAL_EVENTS; i++) WSACloseEvent(m_hWsaEvents[i]); for(set<PER_SOCKET_CONTEXT>::iterator it = m_SocketContexts.begin(); it != m_SocketContexts.end(); ) { set<PER_SOCKET_CONTEXT>::iterator DelIt = it; it++; CloseClient(*DelIt); } return 0; }
void CheatGuard::Disconnect(int aIndex) { if( this->m_UseDisconnect ) { #if defined __BEREZNUK__ || __MIX__ || __REEDLAN__ || __MUANGEL__ || __WHITE__ || __MEGAMU__ || __VIRNET__ g_ConnectEx.SendClose(aIndex); #endif CloseClient(aIndex); } }
void CHacktoolBlockEx::OnRequestUserHacktoolUseInfo(LPOBJ lpObj, DWORD dwHacktoolIndex, BYTE btResult) { HACKTOOL_DATA * lpHacktoolData; // ---- for( int i = 0; i < HACKTOOL_DATA_SIZE; i++ ) { if( lpObj->m_HacktoolUseInfo[i].btCheckType == 1 && lpObj->m_HacktoolUseInfo[i].wHacktoolIndex == dwHacktoolIndex ) { if( btResult == 1 ) { lpObj->m_HacktoolUseInfo[i].btUseType = 2; // ---- if( this->SetHacktoolUseDisadvantage(lpObj, 2) ) { GCServerMsgStringSend(lMsg.Get(3461), lpObj->m_Index, 1); CloseClient(lpObj->m_Index); } else if( this->SetHacktoolUseDisadvantage(lpObj, 4) ) { GCServerMsgStringSend(lMsg.Get(3462), lpObj->m_Index, 1); this->SetUseForceMove2Town(lpObj); } else if( !this->SetHacktoolUseDisadvantage(lpObj, 8) && !this->SetHacktoolUseDisadvantage(lpObj, 16) ) { if( this->SetHacktoolUseDisadvantage(lpObj, 32) ) //GM event? { GCServerMsgStringSend(lMsg.Get(3460), lpObj->m_Index, 1); gObjAddBuffEffect(lpObj, 120, 0, 0, 0, 0, g_iHacktoolUsePenaltyDuration); } else if( this->SetHacktoolUseDisadvantage(lpObj, 1) ) { GCServerMsgStringSend(lMsg.Get(3463), lpObj->m_Index, 1); } } // ---- lpHacktoolData = this->SearchHacktoolData(dwHacktoolIndex); // ---- if( lpHacktoolData ) { LogAddTD("[HackBlockEx][SetHackUseInfo] Use Hacktool User Id : %s(%d), Name : %s, Hacktool Name : %s, Index : %d, BlockType : %d", lpObj->AccountID, lpObj->DBNumber, lpObj->Name, lpHacktoolData->chFilename, dwHacktoolIndex, lpHacktoolData->btHackBlockType); } } else { lpObj->m_HacktoolUseInfo[i].btUseType = 1; lpHacktoolData = this->SearchHacktoolData(dwHacktoolIndex); } break; } } }
void WriteClient (struct a_client *theClients, int fd, int *nbClient, long dataLen, void *buf, int buflen, long dur) { if (theClients[fd].writeLen >= dataLen) { CloseClient (theClients, fd, nbClient, dur, dataLen); } else { int len = buflen; if (len > (dataLen - theClients[fd].writeLen)) { len = (dataLen - theClients[fd].writeLen); } if (len > 0) { if (0 == fd) { int a = 100 / fd; } int e = write (fd, buf, len); printf ("Write -> %d\n",e); if (e > 0) { theClients[fd].writeLen += e; /* if (theClients[fd].writeLen >= dataLen) { CloseClient (theClients, fd, nbClient, duration); } */ } if (e < 0) { CloseClient (theClients, fd, nbClient, dur, dataLen); } } } }
int IoSendSecond(LPPER_SOCKET_CONTEXT lpPerSocketContext) { DWORD SendBytes; int aIndex; EnterCriticalSection(&criti); aIndex = lpPerSocketContext->nIndex; LPPER_IO_CONTEXT lpIoCtxt = (LPPER_IO_CONTEXT)&lpPerSocketContext->IOContext[1]; if ( lpIoCtxt->nWaitIO > 0 ) { LeaveCriticalSection(&criti); return false; } lpIoCtxt->nTotalBytes = 0; if ( lpIoCtxt->nSecondOfs > 0 ) { memcpy(lpIoCtxt->Buffer, lpIoCtxt->BufferSecond, lpIoCtxt->nSecondOfs); lpIoCtxt->nTotalBytes = lpIoCtxt->nSecondOfs; lpIoCtxt->nSecondOfs = 0; } else { LeaveCriticalSection(&criti); return false; } lpIoCtxt->wsabuf.buf = (char*)&lpIoCtxt->Buffer; lpIoCtxt->wsabuf.len = lpIoCtxt->nTotalBytes; lpIoCtxt->nSentBytes = 0; lpIoCtxt->IOOperation = SEND_IO; if ( WSASend(gObj[aIndex].m_socket, &lpIoCtxt->wsabuf, 1, &SendBytes, 0, &lpIoCtxt->Overlapped, NULL) == -1 ) { if ( WSAGetLastError() != WSA_IO_PENDING ) { LogAdd("WSASend(%d) failed with error %d %s ", __LINE__, WSAGetLastError(), gObj[aIndex].Ip_addr); CloseClient(aIndex); LeaveCriticalSection(&criti); return false; } } else { lpPerSocketContext->dwIOCount ++; } lpIoCtxt->nWaitIO = 1; LeaveCriticalSection(&criti); return true; }
TInt DMemModelAlignedShPool::Close(TAny* aPtr) { __KTRACE_OPT(KMMU, Kern::Printf(">DMemModelAlignedShPool::Close(0x%08x)", aPtr)); if (aPtr) { DProcess* pP = reinterpret_cast<DProcess*>(aPtr); CloseClient(pP); } __KTRACE_OPT(KMMU, Kern::Printf("<DMemModelAlignedShPool::Close(0x%08x)", aPtr)); return DShPool::Close(aPtr); }
//======================================================================================================================== void COFFTrade::CreateOfflineTrade(int aIndex) { int OfftradeMapN = GetPrivateProfileInt("OffTrade","OfftradeMap",0,".\\Config\\OffTrade.cfg"); int OfftradeSendAll = GetPrivateProfileInt("OffTrade","OfftradeSendAll",0,".\\Config\\OffTrade.cfg"); char OfftradeShopM[50]; OBJECTSTRUCT *gObj = (OBJECTSTRUCT*)OBJECT_POINTER(aIndex); if(gObj->m_bPShopOpen == false) { MsgNormal(aIndex,"First Open you Store!"); return; } if(gObj->MapNumber != OfftradeMapN) { MsgNormal(aIndex,"OffTrade can be only in %s",GetMapName(OfftradeMapN)); return; } if (gObj->OffTradeCoin == 1) { char TextShop[36] = "<<COIN SHOP>>"; PMSG_ANS_PSHOP_TEXT_CHANGED pMsg; PHeadSubSetB((LPBYTE)&pMsg, 0x3F, 0x10, sizeof(pMsg)); pMsg.NumberH = SET_NUMBERH(aIndex); pMsg.NumberL = SET_NUMBERL(aIndex); memcpy(gObj->m_szPShopText, TextShop, sizeof(pMsg.btPShopText)); memcpy(pMsg.btPShopText, TextShop, sizeof(pMsg.btPShopText)); memcpy(pMsg.btName, gObj->Name, sizeof(pMsg.btName)); DataSendB(aIndex, (char*)&pMsg, pMsg.h.size); MsgAll("[OffTrade] %s now state in %s X:%d Y:%d Exchange:COIN",gObj->Name,GetMapName(gObj->MapNumber),gObj->X,gObj->Y); } if (gObj->OffTradeZen == 1) { char TextShop[36] = "<<ZEN SHOP>>"; PMSG_ANS_PSHOP_TEXT_CHANGED pMsg; PHeadSubSetB((LPBYTE)&pMsg, 0x3F, 0x10, sizeof(pMsg)); pMsg.NumberH = SET_NUMBERH(aIndex); pMsg.NumberL = SET_NUMBERL(aIndex); memcpy(gObj->m_szPShopText, TextShop, sizeof(pMsg.btPShopText)); memcpy(pMsg.btPShopText, TextShop, sizeof(pMsg.btPShopText)); memcpy(pMsg.btName, gObj->Name, sizeof(pMsg.btName)); DataSendB(aIndex, (char*)&pMsg, pMsg.h.size); MsgAll("[OffTrade] %s now state in %s:X %d Y:%d Exchange:COIN",gObj->Name,GetMapName(gObj->MapNumber),gObj->X,gObj->Y); } OfflineShop[aIndex].IsOffTrade=1; CloseClient(aIndex); }
bool cIpBlock::CheckIp(DWORD aIndex) { OBJECTSTRUCT *gObj = (OBJECTSTRUCT*)OBJECT_POINTER(aIndex); for(int x=1;x < IPBlockCount;x++) { if(!CheckIp2(IPBlockInfo[x].IP, gObj->Ip_addr)) { Log.ConsoleOutPut(1, c_Red, t_IPBLOCK,"[Anti-Hack] Blocked %s try to connect!!!",gObj->Ip_addr); CloseClient(aIndex); return false; } } return true; }
// Write a number of bytes if we can, returning true if we wrote anything bool Webserver::WriteBytes() { Network *net = platform->GetNetwork(); uint8_t i; for (i = 0; i < 50 && writing && net->CanWrite(); ) { ++i; if(jsonPointer >= 0) { if(jsonResponse[jsonPointer]) { net->Write(jsonResponse[jsonPointer++]); } else { jsonPointer = -1; jsonResponse[0] = 0; CloseClient(); break; } } else { char b; if(fileBeingSent->Read(b)) { net->Write(b); } else { fileBeingSent->Close(); CloseClient(); break; } } } return i != 0; }
//________________________________________________________________________ void TMidiClient::RcvPacket (GenericPacketPtr p, short len) { if (TPacket::Check (&p->header)) { // check the packet header switch (p->header.type) { case kTCPBye: CloseClient ((TCPByePacketPtr)p); break; case kMidi: fControler->DispatchTCP (fAddr->GetIP(), p, len); break; case kTCPCnxRefused: Disconnect (kTCPCnxRefused); break; default: ; } } }
// ------------------------------------------------------------------------------------------------------------------------------------------------------- bool IOCP::IoSendSecond(_PER_SOCKET_CONTEXT * lpPerSocketContext) { OBJECTSTRUCT * lpObj = & m_Server[lpPerSocketContext->nIndex]; ULONG SendBytes = NULL; _PER_IO_CONTEXT * lpIoCtxt = &lpPerSocketContext->IOContext[1]; // ----- if(lpIoCtxt->nWaitIO > 0) return false; // ----- lpIoCtxt->nTotalBytes = 0; // ----- if(lpIoCtxt->nSecondOfs > 0) { // ----- memcpy(lpIoCtxt->Buffer, lpIoCtxt->BufferSecond, lpIoCtxt->nSecondOfs); // ----- lpIoCtxt->nTotalBytes = lpIoCtxt->nSecondOfs; lpIoCtxt->nSecondOfs = 0; } else { return false; } // ----- lpIoCtxt->wsabuf.buf = (char*)&lpIoCtxt->Buffer; lpIoCtxt->wsabuf.len = lpIoCtxt->nTotalBytes; lpIoCtxt->nSentBytes = 0; lpIoCtxt->IOOperation = OP_RECV; // ----- if(WSASend(lpObj->m_Socket, &lpIoCtxt->wsabuf, 1, &SendBytes, 0, &lpIoCtxt->Overlapped, NULL) == SOCKET_ERROR) { if(WSAGetLastError() != WSA_IO_PENDING) { CLog.Error("[IOCP] WSASend [%s] Failed: [%d].", lpObj->m_ServerIp, WSAGetLastError()); // ----- CloseClient(lpObj->m_Index); // ----- return false; } } else { lpPerSocketContext->dwIOCount++; } // ----- lpIoCtxt->nWaitIO = 1; // ----- return true; }
bool cChat::DiskCommand(LPOBJ gObj, int Index) { if(CheckCommand(gObj, 1, GmSystem.cDisconnect, 0, 0, 0, Index, "DC", "[Name] /disconnect", "")) return true; OBJECTSTRUCT *tObj = (OBJECTSTRUCT*)OBJECT_POINTER(Index); TNotice.SendNotice(Index,1,"[Disconnect] %s was disconnected.", tObj->Name); if(GmSystem.IsAdmin(gObj->Name) == 1) TNotice.SendNotice(Index,1,"[Disconnect] You was disconnected by [Admin] %s", gObj->Name); else if(GmSystem.IsAdmin(gObj->Name) == 2) TNotice.SendNotice(Index,1,"[Disconnect] You was disconnected by [GM] %s", gObj->Name); CloseClient(Index); return true; }
void CloseCommClient( SOCK *clnt ) { if( *clnt != NULLSOCKET ){ CloseConnectionToServer(clnt); CloseClient(clnt); delete SendMutex; SendMutex = NULL; delete ReceiveMutex; ReceiveMutex = NULL; #ifdef COMMTIMING if( sendRcvDelays > 0 ){ QTils_LogMsgEx( "Average communications delay over %lu messages: %gs", sendRcvDelays, cumSendRcvDelay/sendRcvDelays ); sendRcvDelays = 0; cumSendRcvDelay = 0.0; } #endif } }
void CPlayer::Disconnect() { OBJECTSTRUCT *gObj = (OBJECTSTRUCT*)OBJECT_POINTER(aIndex); //------------------------------------------------------ char Nickn[11]; //------------------------------------------------------ if(gObj->PetActived = true) { gObj->PetActived = false; } //------------------------------------------------------ CloseClient(aIndex); //------------------------------------------------------ this->GetName(Nickn); //------------------------------------------------------ Console.Write("[Disconnect][Index: %d][Nick: %s] Player Disconnected",this->aIndex,Nickn); }
void GJPUserDisconnectRecv( SDHP_BILLKILLUSER * lpMsg) { char szId[11]; szId[10]=0; int number; memcpy( szId, lpMsg->Id , sizeof( lpMsg->Id ) ); number = lpMsg->Number; if ( gObjIsAccontConnect(number, szId ) == 0 ) { return; } GCServerMsgStringSend(lMsg.Get( MSGGET(6, 67) ), number, 0 ); //gObjUserKill(number); CloseClient(number); }
//======================================================================================================================== void CSPJoinIdPassRequest(LPBYTE aRecv,int aIndex) { char id[11]; int isOff = 0; PMSG_IDPASS *lpMsg = (PMSG_IDPASS *)aRecv; id[10]=0; memcpy(id, lpMsg->Id, sizeof(lpMsg->Id)); BuxConvert(id, MAX_ACCOUNT_LEN); for(int i=OBJECT_MIN;i<OBJECT_MAX;i++) { OBJECTSTRUCT *gObj = (OBJECTSTRUCT*)OBJECT_POINTER(i); if(gObj->Connected == 3) { if(_tcsstr(gObj->AccountID, id)) { if(OfflineShop[i].IsOffTrade != 0) { OfflineShop[i].IsOffTrade = 1; ObjGameClose(i); CloseClient(i); isOff=1; } // Log.outError("Already here[%d]",i); } } } if(isOff) { OfflineLogin[aIndex].aRecv = aRecv; OfflineLogin[aIndex].aIndex = aIndex; _beginthread( Login_Timer, 0, NULL ); } else { GCSPJoinIdPassRequest(lpMsg,aIndex); } }
void UvTcpServerStream::Close() { // keep a reference in scope fwRefContainer<UvTcpServerStream> selfRef = this; CloseClient(); SetReadCallback(TReadCallback()); // get it locally as we may recurse auto closeCallback = GetCloseCallback(); if (closeCallback) { SetCloseCallback(TCloseCallback()); closeCallback(); } m_server->RemoveStream(this); }
void Server::writeData(int client, char* data) { if(!FD_ISSET(clients[client], &fd)) return; //cout << "writeData clients[" << client << "]\n"; int dataLen = strlen(data); int rc = write(clients[client], data, dataLen); if(rc != dataLen) { cout << "write returns: " << rc << endl; perror("Server-write() error"); char temp = 0; rc = getsockopt(clients[client], SOL_SOCKET, SO_ERROR, &temp, (socklen_t *)&length); if(rc < 1) { errno = temp; perror("SO_ERROR was: "); } CloseClient(client); } }
bool acceptNewClient(server_t* server) { client_t* client = malloc(sizeof(client_t)); client->infoLength = sizeof(client->info); client->socket = accept(server->socket, (struct sockaddr*)&client->info, &client->infoLength); if (client->socket < 0) { free(client); perror("accept"); return false; } if (!setBlocking(client->socket, false)) { free(client); return false; } // Now put the client into our server for (int i = 0; i < kMaxClients; i++) { // Found a spot if (server->clients[i] == NULL) { server->clients[i] = client; client->server = server; break; } } if (!client->server) { printf("Could not accept client %s. We're full.\n", ""); const char* msg = "Server full\n"; send(client->socket, msg, strlen(msg), 0); CloseClient(client); return false; } printf("Accept client %s...\n", stringFromSockaddrIn(&client->info)); return true; }
int gObjAdd(SOCKET aSocket, char *ip) { int n; int total; n = gObjCount; total = 0; while( TRUE ) { if( gObj[n].Connected == 0 ) { gObj[n].m_Index = n; gObj[n].m_socket = aSocket; gObj[n].Connected = 1; gObjSetTime(n); strcpy(gObj[n].m_Ip, ip); gObjCount++; if( gObjCount >= MAX_CONNECTOBJECT ) gObjCount = 0; return n; } else { if( GetTickCount() > gObj[n].Time ) { CloseClient( n ); } } n++; if( n >= MAX_CONNECTOBJECT ) n = 0; total ++; if( total >= MAX_CONNECTOBJECT ) break; } return -1; }
void cOffExp::OffExpStart(int aIndex) { if(!this->Enable) return; LPOBJ lpObj = &gObj[aIndex]; if(!lpObj->DbOffExp) { return; } if (this->CheckTerrain(lpObj)) { CloseClient(aIndex); lpObj->OffExp = true; if(this->EnableTime) lpObj->OffExpTick = 0; } else { GCServerMsgStringSend("[OffExp] Works just outside of town", aIndex, 1); } }
int Server::readData(char* data) { read_fd = fd; long int rc = select(FD_SETSIZE, &read_fd, NULL, NULL, &timeout); if (rc == -1) { perror("Server-select() error"); close(sd); return -1; } if(checkNewClient() < 0) return -1; for(int client = 0; client < numsocks; ++client) { if(FD_ISSET(clients[client], &read_fd)) { char recc[BYTES2READ + 1]; rc = read(clients[client], recc, BYTES2READ); if(rc < 1) { if(rc) perror("Server-read() error"); else perror("Client program has issued a close()"); CloseClient(client); return 0; }else{ recc[rc + 1] = '\0'; memcpy(data, recc, BYTES2READ + 1); memset(recc, 1, BYTES2READ + 1); return rc; } } } return 0; }
void Ccloseplayer::Load(char* filename) { int Token; int aIndex; char closeplayerid[50]; SMDFile=fopen(filename, "r"); if (SMDFile == 0) { LogAdd(lMsg.Get(MSGGET(1, 213)), filename); } else { aIndex=0; while ( true ) { Token=GetToken(); if (Token == 2) { break; } memset(closeplayerid, 0, sizeof(closeplayerid) ); strcpy(&closeplayerid[0], TokenString); if ( strlen(closeplayerid) > 0 ) { aIndex=gObjGetIndex(closeplayerid); if ( aIndex >= 0 ) { LogAdd(lMsg.Get(MSGGET(1, 191)), closeplayerid); CloseClient(aIndex); } } } fclose(SMDFile); } }
void JGPAccountRequest(SDHP_IDPASSRESULT * lpMsg) { char szId[11]; int aIndex; char szJN[20]=""; memset(szId, 0, sizeof(szId)); memcpy(szId, lpMsg->Id , sizeof(lpMsg->Id)); memcpy(szJN, lpMsg->JoominNumber , sizeof(lpMsg->JoominNumber)); aIndex = lpMsg->Number ; switch ( lpMsg->result ) { case 1: case 15: if (gObjSetAccountLogin(aIndex, szId, lpMsg->UserNumber , lpMsg->DBNumber, szJN ) == 0 ) { GJPAccountFail(aIndex, szId, lpMsg->DBNumber , lpMsg->UserNumber ); lpMsg->result = 4; } else { LogAddTD(lMsg.Get(MSGGET(1, 211)), gObj[aIndex].Ip_addr, szId, lpMsg->UserNumber , lpMsg->DBNumber ); } if ( lpMsg->UserNumber == 0 && lpMsg->DBNumber == 0) { LogAddTD(lMsg.Get(MSGGET(1, 212)), szId, lpMsg->UserNumber , lpMsg->DBNumber ); } } #if (ENABLE_CUSTOM_OFFLINETRADE==1) if( lpMsg->result == 6 ) { for (int n=OBJ_STARTUSERINDEX;n<OBJMAX; n++) { if ( gObj[n].Connected >= PLAYER_PLAYING) { if ( gObj[n].AccountID[0] == *szId ) { if ( strcmp(&gObj[n].AccountID[0] , szId) == 0) { if( gObj[n].bOffTrade ) { gObjDel(n); } break; } } } } lpMsg->result = 3; } #else if( lpMsg->result == 6 ) lpMsg->result = 3; #endif if ( lpMsg->result == 0 ) lpMsg->result = 2; if ( lpMsg->result == 15 ) { lpMsg->result = 1; gObj[aIndex].m_cAccountItemBlock = 1; } gObj[aIndex].LoginMsgSnd = 0; if (gObj[aIndex].LoginMsgCount >= 3 ) { lpMsg->result = 8; } GCJoinResult(lpMsg->result , aIndex); if ( lpMsg->result != 1 ) { if ( gObj[aIndex].LoginMsgCount > 3 ) { CloseClient(aIndex); } } }
int DataSend(int aIndex, LPBYTE lpMsg, DWORD dwSize) { DWORD SendBytes; LPPER_SOCKET_CONTEXT lpPerSocketContext; LPBYTE SendBuf; if ( aIndex < OBJ_STARTUSERINDEX ) { return true; } EnterCriticalSection(&criti); if(aIndex < 0 && aIndex > (OBJMAX-1)) { LogAdd("error-L2 : Index(%d) %x %x %x ", dwSize, lpMsg[0], lpMsg[1], lpMsg[2]); LeaveCriticalSection(&criti); return false; } if ( lpMsg[0] == 0xC3 || lpMsg[0] == 0xC4 ) { int ret; BYTE btsize; if ( lpMsg[0] == 0xC3 ) { btsize = lpMsg[1]; lpMsg[1]=gNSerialCheck[aIndex].GetSendSerial(); ret = g_SimpleModulusSC.Encrypt(&ExSendBuf[2], &lpMsg[1], dwSize-1); ExSendBuf[0] = 0xC3; ExSendBuf[1] = ret + 2; SendBuf = ExSendBuf; dwSize = ret + 2; lpMsg[1] = btsize; } else { btsize = lpMsg[2]; lpMsg[2] = gNSerialCheck[aIndex].GetSendSerial(); ret = g_SimpleModulusSC.Encrypt(&ExSendBuf[3], &lpMsg[2], dwSize-2); ExSendBuf[0] = 0xC4; ExSendBuf[1] = SET_NUMBERH(ret +3 ); ExSendBuf[2] = SET_NUMBERL(ret+3); SendBuf = ExSendBuf; dwSize = ret + 3; lpMsg[2] = btsize; } } else { SendBuf = lpMsg; } if ( gObj[aIndex].Connected < PLAYER_CONNECTED ) { LeaveCriticalSection(&criti); return FALSE; } lpPerSocketContext= gObj[aIndex].PerSocketContext; if ( dwSize > sizeof(lpPerSocketContext->IOContext[0].Buffer)) { LogAdd("Error : Max msg(%d) %s %d", dwSize, __FILE__, __LINE__); CloseClient(aIndex); LeaveCriticalSection(&criti); return false; } LPPER_IO_CONTEXT lpIoCtxt = (LPPER_IO_CONTEXT)&lpPerSocketContext->IOContext[1]; if ( lpIoCtxt->nWaitIO > 0 ) { if ( ( lpIoCtxt->nSecondOfs + dwSize ) > MAX_IO_BUFFER_SIZE-1 ) { LogAdd("(%d)error-L2 MAX BUFFER OVER %d %d %d [%s][%s]", aIndex, lpIoCtxt->nTotalBytes, lpIoCtxt->nSecondOfs, dwSize, gObj[aIndex].AccountID, gObj[aIndex].Name); lpIoCtxt->nWaitIO = 0; CloseClient(aIndex); LeaveCriticalSection(&criti); return true; } memcpy( &lpIoCtxt->BufferSecond[lpIoCtxt->nSecondOfs], SendBuf, dwSize); lpIoCtxt->nSecondOfs += dwSize; LeaveCriticalSection(&criti); return true; } lpIoCtxt->nTotalBytes = 0; if ( lpIoCtxt->nSecondOfs > 0 ) { memcpy(lpIoCtxt->Buffer, lpIoCtxt->BufferSecond, lpIoCtxt->nSecondOfs); lpIoCtxt->nTotalBytes = lpIoCtxt->nSecondOfs; lpIoCtxt->nSecondOfs = 0; } if ( (lpIoCtxt->nTotalBytes+dwSize) > MAX_IO_BUFFER_SIZE-1 ) { LogAdd("(%d)error-L2 MAX BUFFER OVER %d %d [%s][%s]", aIndex, lpIoCtxt->nTotalBytes, dwSize, gObj[aIndex].AccountID, gObj[aIndex].Name); lpIoCtxt->nWaitIO = 0; CloseClient(aIndex); LeaveCriticalSection(&criti); return FALSE; } memcpy( &lpIoCtxt->Buffer[lpIoCtxt->nTotalBytes], SendBuf, dwSize); lpIoCtxt->nTotalBytes += dwSize; lpIoCtxt->wsabuf.buf = (char*)&lpIoCtxt->Buffer; lpIoCtxt->wsabuf.len = lpIoCtxt->nTotalBytes; lpIoCtxt->nSentBytes = 0; lpIoCtxt->IOOperation = SEND_IO; if ( WSASend( gObj[aIndex].m_socket, &lpIoCtxt->wsabuf , 1, &SendBytes, 0, &lpIoCtxt->Overlapped, NULL) == -1 ) { if ( WSAGetLastError() != WSA_IO_PENDING ) { lpIoCtxt->nWaitIO = 0; if ( lpIoCtxt->wsabuf.buf[0] == 0xC1 ) { LogAdd("(%d)WSASend(%d) failed with error [%x][%x] %d %s ", __LINE__, aIndex, (BYTE)lpIoCtxt->wsabuf.buf[0], (BYTE)lpIoCtxt->wsabuf.buf[2], WSAGetLastError(), gObj[aIndex].Ip_addr); } else if ( lpIoCtxt->wsabuf.buf[0] == 0xC2 ) { LogAdd("(%d)WSASend(%d) failed with error [%x][%x] %d %s ", __LINE__, aIndex, (BYTE)lpIoCtxt->wsabuf.buf[0], (BYTE)lpIoCtxt->wsabuf.buf[3], WSAGetLastError(), gObj[aIndex].Ip_addr); } CloseClient(aIndex); LeaveCriticalSection(&criti); return false; } } else { lpPerSocketContext->dwIOCount ++; } lpIoCtxt->nWaitIO = 1; LeaveCriticalSection(&criti); return true; }
DWORD WINAPI ServerWorkerThread(LPVOID CompletionPortID) { HANDLE CompletionPort = (HANDLE) CompletionPortID; DWORD dwIoSize; DWORD RecvBytes; DWORD Flags; DWORD dwSendNumBytes = 0; BOOL bSuccess = FALSE; int nRet; int ClientIndex; LPPER_SOCKET_CONTEXT lpPerSocketContext = NULL; LPOVERLAPPED lpOverlapped = NULL; LPPER_IO_CONTEXT lpIOContext = NULL; while(TRUE) { bSuccess = GetQueuedCompletionStatus( CompletionPort, &dwIoSize, (LPDWORD)&ClientIndex, &lpOverlapped, INFINITE ); if( !bSuccess ) { if( lpOverlapped != NULL ) { int aError = GetLastError(); if ( (aError != ERROR_NETNAME_DELETED) && (aError != ERROR_CONNECTION_ABORTED) && (aError != ERROR_OPERATION_ABORTED) && (aError != ERROR_SEM_TIMEOUT)) { EnterCriticalSection(&criti); LogAdd("Error Thread : GetQueueCompletionStatus( %d )", GetLastError()); LeaveCriticalSection(&criti); return 0; } } } EnterCriticalSection(&criti); lpPerSocketContext = gObj[ClientIndex].PerSocketContext; lpPerSocketContext->dwIOCount--; if( dwIoSize == 0 ) { LogAdd("Connection Closed, dwIoSize == 0 (Index:%d)", lpPerSocketContext->nIndex); CloseClient(lpPerSocketContext, 0); LeaveCriticalSection(&criti); continue; } lpIOContext = (LPPER_IO_CONTEXT)lpOverlapped; if( lpIOContext == NULL ) continue; if( lpIOContext->IOOperation == SEND_IO ) { lpIOContext->nSentBytes += dwIoSize; if( lpIOContext->nSentBytes >= lpIOContext->nTotalBytes ) { lpIOContext->nWaitIO = 0; if( lpIOContext->nSecondOfs > 0 ) { IoSendSecond(lpPerSocketContext); } } else { IoMoreSend(lpPerSocketContext); } } else if( lpIOContext->IOOperation == RECV_IO ) { RecvBytes = 0; lpIOContext->nSentBytes += dwIoSize; if( RecvDataParse(lpIOContext, lpPerSocketContext->nIndex) == FALSE ) { LogAdd("error-L1 : Socket Header error %d, %d", WSAGetLastError(), lpPerSocketContext->nIndex); CloseClient(lpPerSocketContext, 0); LeaveCriticalSection(&criti); continue; } lpIOContext->nWaitIO = 0; Flags = 0; ZeroMemory(&(lpIOContext->Overlapped), sizeof(OVERLAPPED)); lpIOContext->wsabuf.len = MAX_IO_BUFFER_SIZE-lpIOContext->nSentBytes; lpIOContext->wsabuf.buf = lpIOContext->Buffer+lpIOContext->nSentBytes; lpIOContext->IOOperation = RECV_IO; nRet = WSARecv(lpPerSocketContext->m_socket, &(lpIOContext->wsabuf), 1, &RecvBytes, &Flags, &(lpIOContext->Overlapped), NULL); if( nRet == SOCKET_ERROR && (WSAGetLastError() != ERROR_IO_PENDING) ) { LogAdd("WSARecv() failed with error %d", WSAGetLastError()); //lpIOContext->nWaitIO = 2; CloseClient( lpPerSocketContext, FALSE); LeaveCriticalSection(&criti); continue; } lpPerSocketContext->dwIOCount++; lpIOContext->nWaitIO = 1; } LeaveCriticalSection(&criti); } return TRUE; }
DWORD WINAPI IocpServerWorker(LPVOID p) { SYSTEM_INFO SystemInfo; DWORD ThreadID; SOCKET Accept; int nRet; int ClientIndex; SOCKADDR_IN cAddr; IN_ADDR cInAddr; int cAddrlen = sizeof( cAddr ); LPPER_SOCKET_CONTEXT lpPerSocketContext = NULL; DWORD RecvBytes; DWORD Flags=0; InitializeCriticalSection(&criti); GetSystemInfo(&SystemInfo); g_dwThreadCount = SystemInfo.dwNumberOfProcessors * 2; __try { g_CompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0); if ( g_CompletionPort == NULL) { LogAdd("CreateIoCompletionPort failed with error: %d", GetLastError()); __leave; } for(DWORD dwCPU = 0; dwCPU < g_dwThreadCount; dwCPU++) { HANDLE ThreadHandle; // Create a server worker thread and pass the completion port to the thread. ThreadHandle = CreateThread(NULL, 0, ServerWorkerThread, g_CompletionPort, 0, &ThreadID); if ( ThreadHandle == NULL) { LogAdd("CreateThread() failed with error %d", GetLastError()); __leave; } g_ThreadHandles[dwCPU] = ThreadHandle; CloseHandle(ThreadHandle); } if (!CreateListenSocket() ) __leave; while(TRUE) { Accept = WSAAccept(g_Listen, (LPSOCKADDR)&cAddr, &cAddrlen, NULL, 0); if (Accept==SOCKET_ERROR) { EnterCriticalSection(&criti); LogAdd("WSAAccept() failed with error %d", WSAGetLastError()); LeaveCriticalSection(&criti); continue; } EnterCriticalSection(&criti); memcpy( &cInAddr, &cAddr.sin_addr.s_addr, 4 ); ClientIndex = gObjAddSearch(Accept, inet_ntoa(cInAddr) ); if ( ClientIndex == -1 ) { LogAddL("error-L2 : ClientIndex = -1"); closesocket(Accept); LeaveCriticalSection(&criti); continue; } if (UpdateCompletionPort(Accept, ClientIndex, 1) == 0 ) { LogAddL("error-L1 : %d %d CreateIoCompletionPort failed with error %d", Accept, ClientIndex, GetLastError() ); closesocket(Accept); LeaveCriticalSection(&criti); continue; } if (gObjAdd(Accept, inet_ntoa(cInAddr), ClientIndex) == -1 ) { LogAddL("error-L1 : %d %d gObjAdd() failed with error %d", Accept, ClientIndex, GetLastError() ); LeaveCriticalSection(&criti); closesocket(Accept); continue; } memset(&gObj[ClientIndex].PerSocketContext->IOContext[0].Overlapped, 0, sizeof(OVERLAPPED)); memset(&gObj[ClientIndex].PerSocketContext->IOContext[1].Overlapped, 0, sizeof(OVERLAPPED)); gObj[ClientIndex].PerSocketContext->IOContext[0].wsabuf.buf = gObj[ClientIndex].PerSocketContext->IOContext[0].Buffer; gObj[ClientIndex].PerSocketContext->IOContext[0].wsabuf.len = MAX_IO_BUFFER_SIZE; gObj[ClientIndex].PerSocketContext->IOContext[0].nTotalBytes = 0; gObj[ClientIndex].PerSocketContext->IOContext[0].nSentBytes = 0; gObj[ClientIndex].PerSocketContext->IOContext[0].nWaitIO = 0; gObj[ClientIndex].PerSocketContext->IOContext[0].nSecondOfs = 0; gObj[ClientIndex].PerSocketContext->IOContext[0].IOOperation = RECV_IO; gObj[ClientIndex].PerSocketContext->IOContext[1].wsabuf.buf = gObj[ClientIndex].PerSocketContext->IOContext[0].Buffer; gObj[ClientIndex].PerSocketContext->IOContext[1].wsabuf.len = MAX_IO_BUFFER_SIZE; gObj[ClientIndex].PerSocketContext->IOContext[1].nTotalBytes= 0; gObj[ClientIndex].PerSocketContext->IOContext[1].nSentBytes = 0; gObj[ClientIndex].PerSocketContext->IOContext[1].nWaitIO = 0; gObj[ClientIndex].PerSocketContext->IOContext[1].nSecondOfs = 0; gObj[ClientIndex].PerSocketContext->IOContext[1].IOOperation = SEND_IO; gObj[ClientIndex].PerSocketContext->m_socket = Accept; gObj[ClientIndex].PerSocketContext->nIndex = ClientIndex; nRet = WSARecv(Accept, &(gObj[ClientIndex].PerSocketContext->IOContext[0].wsabuf), 1, &RecvBytes, &Flags, &(gObj[ClientIndex].PerSocketContext->IOContext[0].Overlapped), NULL); if( nRet == SOCKET_ERROR && WSAGetLastError() != ERROR_IO_PENDING ) { LogAdd("error-L1 : WSARecv() failed with error %d", WSAGetLastError()); gObj[ClientIndex].PerSocketContext->IOContext[0].nWaitIO = 4; CloseClient(gObj[ClientIndex].PerSocketContext, FALSE); LeaveCriticalSection(&criti); continue; } gObj[ClientIndex].PerSocketContext->IOContext[0].nWaitIO = 1; gObj[ClientIndex].PerSocketContext->dwIOCount++; LeaveCriticalSection(&criti); SCPJoinResultSend(ClientIndex, 1); } } __finally { if( g_CompletionPort ) { for (DWORD i = 0; i < g_dwThreadCount; i++) PostQueuedCompletionStatus(g_CompletionPort, 0, 0, NULL); } if( g_CompletionPort ) { CloseHandle(g_CompletionPort); g_CompletionPort = NULL; } if (g_Listen != INVALID_SOCKET) { closesocket(g_Listen); g_Listen = INVALID_SOCKET; } } return TRUE; }