// *************************************************************** // Function: NetServer.cpp // *************************************************************** #include "NetServer.h" #include #include #include #include "GWLPLog.h" #include "Utility.h" #include "timer.h" //Set up logging for this class #undef DEBUG_TEXT #undef WARNING_TEXT #undef NOTICE_TEXT #undef ERROR_TEXT #undef ALWAYS_TEXT #define DEBUG_TEXT OPT_DEBUG_LEVEL | OPT_HEAD_DEBUG #define WARNING_TEXT OPT_WARNING_LEVEL | OPT_C3 | OPT_HEAD_WARNING | OPT_APP_TIME | OPT_APP_LOCATION | OPT_CCSEMICOLON #define NOTICE_TEXT OPT_NOTICE_LEVEL | OPT_C4 | OPT_HEAD_NOTICE | OPT_APP_TIME | OPT_CCSEMICOLON #define ERROR_TEXT OPT_ERROR_LEVEL | OPT_C5 | OPT_HEAD_ERROR | OPT_APP_TIME | OPT_APP_LOCATION | OPT_CCSEMICOLON #define ALWAYS_TEXT OPT_ALWAYS_LEVEL | OPT_APP_TIME #define SETLOCN SetLocation(__FILE__, __FUNCTION__, __LINE__, mName) //Change if (true) to if (false) to disable logging #define MYLOG if (true){((GWLPLog*)mpMyLog)->SETLOCN;((GWLPLog*)mpMyLog) #define ENDLOG } int byteCounter=0; //************************************ // Name: IsLan // // Is the specified client network id connected via LAN // // Parameters: // id - Client network id // // Return: // true - Client is connected via LAN // false - Client not connected via LAN //************************************ bool Server::IsLan(short id) { assert(id>0); SOCKETINFO *socket_info=GetClientByPid(id); if (socket_info!=NULL) { //Check for LAN IP if ((socket_info->ip[0]==LAN10) || ((socket_info->ip[0]==LAN172) && ((socket_info->ip[1]>=LAN16) && (socket_info->ip[1]<=LAN31))) || ((socket_info->ip[0]==LAN192) && (socket_info->ip[1]==LAN168)) || ((socket_info->ip[0]==LAN169) && (socket_info->ip[1]==LAN254)) || socket_info->ip[0]==127) { return true; } } return false; } //************************************ // Name: Update // // Updates the server. Processes control messages, reads data from clients, and sends queued data. // // Parameters: // // Return: // //************************************ void Server::Update() { if (!mIsClient) { if (Listen()<0) { mFatalError=true; } } //------------------------------------------------------------ //Processes the server control messages. These messages tell //the server to do something. Such as terminate a connection //after ten seconds. //------------------------------------------------------------ if (true) { list::iterator itr; for (itr=mControlMessages.begin(); itr!=mControlMessages.end(); itr++) { NetMessage d=*itr; this->ProcessControlMessage(d); } if (mControlMessages.size()>0){mControlMessages.clear();} } //Process event messages if (true) { stupidRepeat: list::iterator itr; for (itr=mEventQueue.begin(); itr!=mEventQueue.end(); itr++) { if (ProcessEventMessage(&(*itr))) { mEventQueue.erase(itr); goto stupidRepeat; } } } //------------------------------------------------------------------- //Check for data on all client connections //------------------------------------------------------------------- hash_map::iterator hitr; for (hitr=mClients.begin(); hitr!=mClients.end(); hitr++) { hitr->second.haltSend=false; //poll each socket to see if it has any data fd_set read; fd_set write; FD_ZERO(&read); FD_ZERO(&write); FD_SET(hitr->second.client, &read); FD_SET(hitr->second.client, &write); timeval t; t.tv_sec=0; t.tv_usec=0; if (select((int)hitr->second.client+1, &read, &write, NULL, &t)==SOCKET_ERROR_N) { #ifdef WIN32 int err=WSAGetLastError(); if (err!=WSAENOTSOCK) { MYLOG->error("An error has occurred with select()");ENDLOG mReport.numErrors++; } #else MYLOG->error("An error has occured with select()");ENDLOG mReport.numErrors++; #endif } //----------------------------------------------------------------------- //there is data to be read from the socket //----------------------------------------------------------------------- if (FD_ISSET(hitr->second.client, &read)) { //Read in the packet unsigned char buffer[2921]; int err=recv(hitr->second.client, (char*)buffer, 2920, 0); if (CheckRecvError(err, hitr->second.id)!=0) { return; } else { unsigned char *pBuf=new unsigned char[err]; assert(pBuf!=NULL); memcpy(pBuf, buffer, err); if (hitr->second.useEncryption) { if (Crypto!=NULL) { (*Crypto)(pBuf, pBuf, err, &hitr->second.eState); } } //Package the data with info for the processor NetMessage d; d.extra1=(int)TimerGetTime(); d.pData=pBuf; d.dataSize=err; d.networkId=hitr->second.id; mIncoming.push_back(d); mReport.inByteCounter+=err; mReport.outNumPackets++; } } } //-------------------------------------------------------------------------- //Go through and send all data that must be sent. If the data should not be //sent yet then add that NetMessage to the holdover list. //-------------------------------------------------------------------------- list sendHoldOver; //cycle through the outgoing list and send what needs be list::iterator itr; for (itr=mOutgoing.begin(); itr!=mOutgoing.end(); itr++) { SOCKETINFO *socket_info=GetClientByPid(itr->networkId); if (socket_info!=NULL) { //poll each socket to see if it has any data fd_set read; fd_set write; FD_ZERO(&read); FD_ZERO(&write); FD_SET(socket_info->client, &read); FD_SET(socket_info->client, &write); timeval t; t.tv_sec=0; t.tv_usec=0; if (select((int)socket_info->client+1, &read, &write, NULL, &t)==SOCKET_ERROR_N) { #ifdef WIN32 int err=WSAGetLastError(); if (err!=WSAENOTSOCK) { MYLOG->error("An error has occured with select()");ENDLOG mReport.numErrors++; } #else MYLOG->error("An error has occured with select()");ENDLOG mReport.numErrors++; #endif } //------------------------------------------------------------------------- //we can send data to this client //------------------------------------------------------------------------- if (FD_ISSET(socket_info->client, &write) && itr->dataSize>0 && !socket_info->haltSend) { //-------------------------------------------------------------------------------- //check for time wait(used to prevent packets from bunching up at the client end) //-------------------------------------------------------------------------------- bool send_packet=true; if (BIT_TEST(itr->flags, NETMESS_BOOL_DELAYEDSEND)) { if (TimerGetTime()-(unsigned long)itr->extra1<=(unsigned long)itr->unused) { sendHoldOver.push_back(*itr); send_packet=false; } } //----------------------------------------------------------------------------- //If we must send the packet now //----------------------------------------------------------------------------- if (send_packet) { if (socket_info->useEncryption) { if (Crypto!=NULL) { (*Crypto)(itr->pData, itr->pData, itr->dataSize, &socket_info->eState); } } //MYLOG->notice("BC: %u", byteCounter);ENDLOG if(itr->dataSize==4) { //MYLOG->debug("Serv Pck: %02X %02X - %u", itr->pData[0], itr->pData[1], itr->dataSize);ENDLOG } int ret=send(socket_info->client, (char*)itr->pData, itr->dataSize, 0); if (ret==0) { MYLOG->error("ZERO bytes sent!");ENDLOG mReport.numErrors++; } if (BIT_TEST(itr->flags, NETMESS_BOOL_TIMERECV)) { NetMessage r(0, EVENT_TIME_SENT, itr->networkId); r.extra1=(int)TimerGetTime(); r.extra2=itr->extra2; r.pData=NULL; this->AddIncoming(&r); } if (BIT_TEST(itr->flags, NETMESS_BOOL_DEL) && itr->pData!=0) { delete [] itr->pData; } mReport.outByteCounter+=itr->dataSize; mReport.outNumPackets++; } else { //MYLOG->error("Delaying");ENDLOG } } else if (itr->dataSize==TOGGLE_CLIENT_ENCRYPTION) { if (socket_info->useEncryption) { socket_info->useEncryption=false; } else { socket_info->useEncryption=true; } } else if (itr->dataSize==KICK_CLIENT) { Kick(itr->networkId); } else { sendHoldOver.push_back(*itr); socket_info->haltSend=true; } } else { if (BIT_TEST(itr->flags, NETMESS_BOOL_DEL) && itr->pData!=0) { delete [] itr->pData; } MYLOG->debug("Failed to send packet: Client does not exist!");ENDLOG mReport.numWarnings++; } } if (mOutgoing.size()>0) mOutgoing.clear(); //------------------------------------------------------------------------- //copy the sendHoldOver to the outgoing list to be processed next time //------------------------------------------------------------------------- for (itr=sendHoldOver.begin(); itr!=sendHoldOver.end(); itr++) { mOutgoing.push_back(*itr); } if (sendHoldOver.size()>0) sendHoldOver.clear(); mTotalIncomingAtEnd=(unsigned long)mIncoming.size(); //Calculate the report if (TimerGetTime()-mReport.timer>=1000) { mReport.avgBytesPerSecIn+=(mReport.inByteCounter/1+(mReport.inNumPackets)); mReport.avgBytesPerSecIn/=2; mReport.avgBytesPerSecOut+=(mReport.outByteCounter/1+(mReport.outNumPackets)); mReport.avgBytesPerSecOut/=2; if (mReport.avgBytesPerSecIn>mReport.peakAvgBytesPerSecIn){mReport.peakAvgBytesPerSecIn=mReport.avgBytesPerSecIn;} if (mReport.avgBytesPerSecOut>mReport.peakAvgBytesPerSecOut){mReport.peakAvgBytesPerSecOut=mReport.avgBytesPerSecOut;} mReport.bytesPerSecIn=mReport.inByteCounter; mReport.bytesPerSecOut=mReport.outByteCounter; if (mReport.bytesPerSecIn>mReport.peakBytesPerSecIn){mReport.peakBytesPerSecIn=mReport.bytesPerSecIn;} if (mReport.bytesPerSecOut>mReport.peakBytesPerSecOut){mReport.peakBytesPerSecOut=mReport.bytesPerSecOut;} mReport.packetsPerSecIn+=mReport.inNumPackets; mReport.packetsPerSecIn/=2; mReport.packetsPerSecOut+=mReport.outNumPackets; mReport.packetsPerSecOut/=2; mReport.inByteCounter=0; mReport.outByteCounter=0; mReport.inNumPackets=0; mReport.outNumPackets=0; mReport.timer=(unsigned long)TimerGetTime(); } } //###################################################################################3 //#Returns the next NetMessage in the incoming queue //#Currently this must be modified if NetMessage changes //################################################################################### int Server::GetNextNetMessage(NetMessage* pData) { assert(pData!=NULL); if (mIncoming.size()==0 || mTotalIncomingAtEnd<=0) { pData->dataSize=-9999; return -1; } //Blast...can't replace this nasty code, anyway update this if NetMessage changes pData->pData=mIncoming.front().pData; pData->dataSize=mIncoming.front().dataSize; pData->networkId=mIncoming.front().networkId; pData->flags=mIncoming.front().flags; pData->extra1=mIncoming.front().extra1; pData->extra2=mIncoming.front().extra2; mIncoming.pop_front(); mTotalIncomingAtEnd--; return 0; } //************************************ // Name: GetReport // // Access the network server network report. // // Parameters: // // Return: // - Pointer to the network server's network report data //************************************ NET_REPORT* Server::GetReport() { return &mReport; } //************************************ // Name: SendData // // Adds a network message to the outgoing queue // // Parameters: // pData - Network message // // Return: // - zero //************************************ int Server::SendData(NetMessage* pData) { assert(pData!=NULL); assert(pData->networkId>0); if (pData->pData!=NULL) { //Make a copy of the data unsigned char *pDest=new unsigned char[pData->dataSize]; memcpy(pDest, pData->pData, pData->dataSize); pData->pData=pDest; BIT_SET(pData->flags, NETMESS_BOOL_DEL); } mOutgoing.push_back(*pData); return 0; } //TODO: wtf is this? int Server::ForwardData(NetMessage* pData) { assert(pData!=NULL); pData->pData[0] = 0x09; //0x08; // header meaning for the login server to forward the data pData->pData[1] =(unsigned char)(pData->dataSize - 2); mOutgoing.push_back(*pData); return 0; } //################################################################################### //#Is used to add a NetMessage to the outgoing queue //#timeWait is how many ms to delay before sending the packet //#thus preventing the bunching up of packets on the client end //################################################################################### //************************************ // Name: SendData // // Adds a network message to the outgoing queue. But waits before sending it. // // Parameters: // pData - Network message // timeWait - Timewait in ms // // Return: // - zero //************************************ int Server::SendData(NetMessage* pData, int timeWait) { assert(pData!=NULL); assert(pData->networkId>0); BIT_SET(pData->flags, NETMESS_BOOL_DELAYEDSEND); BIT_SET(pData->flags, NETMESS_BOOL_DEL); pData->extra1=(int)TimerGetTime(); pData->unused=timeWait; if (pData->pData!=NULL) { //Make a copy of the data unsigned char *pDest=new unsigned char[pData->dataSize]; memcpy(pDest, pData->pData, pData->dataSize); pData->pData=pDest; } mOutgoing.push_back(*pData); return 0; } //************************************ // Name: AddIncoming // // Adds a network message to the back of incoming packets queue. // // Parameters: // pData - Network message // // Return: // - zero //************************************ int Server::AddIncoming(NetMessage* pData) { assert(pData!=NULL); //Make a copy of the data if (pData->dataSize>0 && pData->pData!=NULL) { unsigned char *pDest=new unsigned char[pData->dataSize]; memcpy(pDest, pData->pData, pData->dataSize); pData->pData=pDest; BIT_SET(pData->flags, NETMESS_NOT_ENCRYPTED); } mIncoming.push_back(*pData); pData->pData=NULL; return 0; } //************************************ // Name: AddIncomingFront // // Adds a network message to the front of the incoming packets queue. // // Parameters: // pData - Network message // // Return: // - zero //************************************ int Server::AddIncomingFront(NetMessage* pData) { assert(pData!=NULL); mTotalIncomingAtEnd++; //Make a copy of the data if (pData->dataSize>0 && pData->pData!=NULL) { unsigned char *pDest=new unsigned char[pData->dataSize]; memcpy(pDest, pData->pData, pData->dataSize); pData->pData=pDest; BIT_SET(pData->flags, NETMESS_NOT_ENCRYPTED); } mIncoming.push_front(*pData); pData->pData=NULL; return 0; } //************************************ // Name: SendControl // // Don't use will probably be removed. // // Parameters: // pData - Document // // Return: // //************************************ int Server::SendControl(NetMessage* pData) { assert(pData!=NULL); mControlMessages.push_back(*pData); return 0; } //************************************ // Name: SetEncryptionState // // Sets the encryption state of the network client. This is used for automatically processing cryptography. // // Parameters: // id - Client network id // pEncryptionState - Pointer to your encryption state data. // // Return: // //************************************ void Server::SetEncryptionState(short id, ENCRYPTION_STATE* pEncryptionState) { SOCKETINFO *socket_info=GetClientByPid(id); if (socket_info==NULL) { MYLOG->error("Failed to set encryption state!");ENDLOG mReport.numErrors++; return; } memcpy(&socket_info->eState, pEncryptionState, sizeof(ENCRYPTION_STATE)); //Tell the server to turn on encryption for this client NetMessage s; s.networkId=id; s.dataSize=TOGGLE_CLIENT_ENCRYPTION; s.pData=NULL; this->SendData(&s); return; } //************************************ // Name: GetClientById // // Get a copy of the client who owns the specified network id. // // Parameters: // networkId - Client network id // // Return: // //************************************ SOCKETINFO Server::GetClientById(short networkId) { assert(networkId>0); hash_map::iterator hitr=mClients.find(networkId); SOCKETINFO *socket_info=&hitr->second; return *socket_info; } //************************************ // Name: GetClientByPid // // Access the specified client's network data. // // Parameters: // networkId - Client's network id // // Return: // - Pointer to the client's socket info //************************************ SOCKETINFO *Server::GetClientByPid(short networkId) { assert(networkId>0); hash_map::iterator hitr=mClients.find(networkId); if (hitr!=mClients.end()) { SOCKETINFO *socket_info=&hitr->second; return socket_info; } return NULL; } //************************************ // Name: IssueBan // // Bans an IP // // Parameters: // pIpByteRange - 8 byte buffer hold the low and high ip addresses of the range // durationSeconds - How many seconds to ban for. 0=infinite // pReason - Reason for banning // // Return: // //************************************ void Server::IssueBan(unsigned char* pIpByteRange, unsigned long durationSeconds, char* pReason) { _IPBAN ban; ban.addedOn=time(NULL); ban.duration=durationSeconds; memcpy(ban.start, pIpByteRange, 4); memcpy(ban.end, pIpByteRange+4, 4); if (strlen(pReason)<100){strcpy(ban.reason, pReason);} typedef pair bpair; unsigned long temp1=0; memcpy(&temp1, pIpByteRange, sizeof(unsigned long)); mBans.insert(bpair(temp1, ban)); if (durationSeconds>0) { MYLOG->notice("Issued %f minute IP Ban for %d.%d.%d.%d -> %d.%d.%d.%d Reason: %s", durationSeconds/60.0, pIpByteRange[0], pIpByteRange[1], pIpByteRange[2], pIpByteRange[3], pIpByteRange[4], pIpByteRange[5], pIpByteRange[6], pIpByteRange[7], pReason);ENDLOG } else { MYLOG->notice("Issued infinite IP Ban for %d.%d.%d.%d -> %d.%d.%d.%d Reason: %s", pIpByteRange[0], pIpByteRange[1], pIpByteRange[2], pIpByteRange[3], pIpByteRange[4], pIpByteRange[5], pIpByteRange[6], pIpByteRange[7], pReason);ENDLOG } } //************************************ // Name: IssueBan // // Wrapper function for IssueBan // // Parameters: // networkId - Client's network id // durationSeconds - Duration of ban in seconds. // pReason - Reason for banning. // // Return: // //************************************ void Server::IssueBan(short networkId, unsigned long durationSeconds, char *pReason) { unsigned char ipb[8]; memcpy(ipb, GetClientById(networkId).ip, 4); memcpy(ipb+4, GetClientById(networkId).ip, 4); IssueBan(ipb, durationSeconds, pReason); KillClient(networkId); } //############################################################################### //#Called to check if a call to Recv() has returned an error //#This will process both the, lost connection to client terminated gracefully //#and connections terminated abnormally. //############################################################################### //************************************ // Name: CheckRecvError // // Check for recv() errors on a socket. // // Parameters: // err - Result returned from recv() // networkId - Client's network id // // Return: // 0 - No errors // -1 - Connection terminated gracefully // -2 - Connection terminated abnormally //************************************ int Server::CheckRecvError(int err, int networkId) { assert(networkId>0); //----------------------------------------------------------------------- //the connection has ended gracefully //----------------------------------------------------------------------- if (err==0) { MYLOG->debug("Lost connection to: %d.%d.%d.%d - Terminated Gracefully.", mClients[networkId].ip[0], mClients[networkId].ip[1], mClients[networkId].ip[2], mClients[networkId].ip[3]);ENDLOG KillClient(networkId); return -1; } //------------------------------------------------------------------------ //The connection ended abnormally //------------------------------------------------------------------------ else if (err==SOCKET_ERROR_N) { #ifdef WIN32 err=WSAGetLastError(); #endif MYLOG->debug("Lost connection to: %d.%d.%d.%d Terminated Abnormally! Code #%d", mClients[networkId].ip[0], mClients[networkId].ip[1], mClients[networkId].ip[2], mClients[networkId].ip[3], err);ENDLOG KillClient(networkId); return -2; } return 0; } //Default constructor for the Server class Server::Server() { mConfig.maxConnections=10; mIsClient=false; mFatalError=false; mpMyLog=0; srand((unsigned int)TimerGetTime()); } //Constructor with arguments //************************************ // Name: Server // // Server constructor. // // Parameters: // port - Port to run the server on or connect on if using the client. // pName - Name of the server/client. // pIp - IP address to bind to. // isClient - Is this network code being used a server or client? // pMyLog - Pointer to a GWLPLog (Required) // // Return: // //************************************ Server::Server(int port, char* pName, unsigned char* pIp, bool isClient, void* pMyLog) { assert(pName!=NULL); mConfig.maxConnections=10; mIsClient=isClient; mFatalError=false; Init(port, pName, pIp, isClient, pMyLog); mShutdownOK=false; } //************************************ // Name: Shutdown // // Prepares to shutdown the server/client. Must be called before the deconstructor. // // Parameters: // isLastServer - If this is the last network server in-use. // // Notes: // o If /isLastServer/ is true Winsock will be shutdown. // // Return: // - zero //************************************ int Server::Shutdown(bool isLastServer) { hash_map::iterator hitr; for (hitr=mClients.begin(); hitr!=mClients.end(); hitr++) { closesocket(hitr->second.client); } if (!mIsClient) closesocket(mMySocket); #ifdef WIN32 if (isLastServer) { WSACleanup(); } #endif if (mClients.size()>0){mClients.clear();} mShutdownOK=true; return 0; } //************************************ // Name: GetName // // Gets the name of the server. // // Parameters: // // Return: // - Pointer to the server name. //************************************ char* Server::GetName() { return mName; } //Deconstructor: Cleans up everything we have allocated Server::~Server() { if (!mShutdownOK) { MYLOG->error("Shutdown not called on NetServer!");ENDLOG mReport.numErrors++; } list::iterator itr; for (itr=mIncoming.begin(); itr!=mIncoming.end(); itr++) { if (itr->pData!=0) delete [] itr->pData; } for (itr=mOutgoing.begin(); itr!=mOutgoing.end(); itr++) { if (BIT_TEST(itr->flags, NETMESS_BOOL_DEL)) delete [] itr->pData; } if (mIncoming.size()>0) mIncoming.clear(); if (mOutgoing.size()>0) mOutgoing.clear(); if (mControlMessages.size()>0) mControlMessages.clear(); if (mEventQueue.size()>0) mEventQueue.clear(); //Attempt to save the bans list for this server char ban_file_name[80]; strcpy(ban_file_name, "System/"); strcat(ban_file_name, mName); strcat(ban_file_name, ".ban"); std::ofstream fout(ban_file_name, std::ios::binary); unsigned long num_bans=(unsigned long)mBans.size(); fout.write((char*)&num_bans, sizeof(unsigned long)); hash_map::iterator it; for (it=mBans.begin(); it!=mBans.end(); it++) { fout.write((char*)&it->second.addedOn, sizeof(time_t)); fout.write((char*)&it->second.duration, sizeof(unsigned long)); fout.write((char*)it->second.end, 4); fout.write((char*)it->second.start, 4); } fout.close(); mBans.clear(); } //************************************ // Name: Bind // // Binds the server to a port and sets the socket options. // // Notes: // o Turns off Nagle algorithm // o Sets socket to non-blocking mode // // Return: // - zero //************************************ int Server::Bind() { //Binds our socket to the specified port if (bind(mMySocket, (struct sockaddr *)&my_address, sizeof(my_address))==SOCKET_ERROR_N) { MYLOG->error("An error has occurred with bind()");ENDLOG mReport.numErrors++; #ifdef WIN32 WSACleanup(); #endif return 0; } #ifdef WIN32 //Set our socket to not block int int_no_block=1; if (ioctlsocket(mMySocket, FIONBIO, (u_long FAR*) &int_no_block)==-1) { MYLOG->error("ioctlsocket has failed!");ENDLOG mReport.numErrors++; } #else // linux equivalent to set non-blocking int flags; if ((flags = fcntl(mMySocket, F_GETFL, 0)) < 0) { MYLOG->error("Error setting non-blocking");ENDLOG mReport.numErrors++; } flags |= O_NONBLOCK|O_NDELAY; if (fcntl(mMySocket, F_SETFL, flags) < 0) { MYLOG->error("setting non-blocking");ENDLOG mReport.numErrors++; } #endif MYLOG->notice("Success: Server: %s", inet_ntoa(my_address.sin_addr));ENDLOG MYLOG->notice("Success: Port: %d", ntohs(my_address.sin_port));ENDLOG return 0; } //************************************ // Name: GetIp // // Gets the IP address of the server in byte form. (Maybe client as well.) // // Parameters: // pIpDest - Byte buffer of size >=4 // // Return: // //************************************ void Server::GetIp(char* pIpDest) { char temp[50]; strcpy(temp, inet_ntoa(my_address.sin_addr)); char *pToken=strtok(temp, "."); for (int i=0; i<4; i++) { pIpDest[i]=(char)atoi(pToken); pToken=strtok(0, "."); } } //************************************ // Name: GetIpString // // Gets the server IP address as a string. // // Parameters: // pBuffer - Destination string buffer. 16 characters minimum. // // Return: // //************************************ void Server::GetIpString(char* pBuffer) { strcpy(pBuffer, inet_ntoa(my_address.sin_addr)); } //************************************ // Name: GetClientModeId // // Retrieves the client network id used for addressing network messages. // // Parameters: // // Return: // >-1 - Network id of client // -1 - This cannot be used in server mode. //************************************ int Server::GetClientModeId() { assert(mClients.size()>0); hash_map::iterator itr=mClients.begin(); if (mIsClient) return itr->second.id; else return -1; } //************************************ // Name: IsBanned // // Checks if specified IP address is banned. // // Parameters: // pIp - Ip address (byte form) // // Return: // true - IP address is banned. // false - IP address is not banned. //************************************ bool Server::IsBanned(char* pIp) { unsigned long check_this_ip; unsigned long start_range; unsigned long end_range; memcpy(&check_this_ip, pIp, 4); hash_map::iterator itr=mBans.find(check_this_ip); if (itr!=mBans.end()) { memcpy(&start_range, itr->second.start, 4); memcpy(&end_range, itr->second.end, 4); if (check_this_ip>=start_range && check_this_ip<=end_range) { if (itr->second.duration>0) { time_t ct=time(NULL); if (difftime(ct, itr->second.addedOn)>itr->second.duration) { mBans.erase(itr); return false; } else { return true; } } else { return true; } } } return false; } //************************************ // Name: Listen // // Listens for new network connections. // // Notes: // o There is no notifications of blocking a banned client by IP. // // Return: // 0 - no errors // -1 - listen failed //************************************ int Server::Listen() { //--------------------------------------------------------------- //If an error occurred then clean-up //--------------------------------------------------------------- if (listen(mMySocket, 10)==SOCKET_ERROR_N) { MYLOG->error("Error in Listening");ENDLOG mReport.numErrors++; closesocket(mMySocket); mFatalError=true; #ifdef WIN32 WSACleanup(); #endif return -1; } //--------------------------------------------------------------- //We have a client wanting to connect. //--------------------------------------------------------------- else { struct sockaddr client_address; #ifdef WIN32 int sin_size = sizeof(struct sockaddr_in); #else socklen_t sin_size = sizeof(struct sockaddr_in); #endif //--------------------------------------------------------- //If we have enough room to allow said client to connect //then accept the connection. //--------------------------------------------------------- if (mClients.size()<(unsigned int)mConfig.maxConnections) { SOCKETINFO socket_info; if ((socket_info.client=accept(mMySocket, &client_address, &sin_size))!=INVALID_SOCKET) { socket_info.inUse=true; socket_info.id=NewId(); socket_info.haltSend=false; //Disable the Nagle algorithm bool disable_nagle=true; int boolean_bytes=sizeof(bool); if (setsockopt(socket_info.client, SOL_SOCKET, TCP_NODELAY, (char*)&disable_nagle, boolean_bytes)==SOCKET_ERROR_N) { MYLOG->error("Could not turn off Nagle algorithm.");ENDLOG }//*/ //convert addr to an IP address, because windows is TOO fucking stupid! unsigned char ip[5]; memset(ip, 0, 5); memcpy(&ip, &client_address.sa_data[2], 4); memcpy((char*)socket_info.ip, (char*)ip, 5); if (IsBanned((char*)socket_info.ip)) { closesocket(socket_info.client); return 0; } socket_info.useEncryption=false; //This may cause problems on Linux...fucking Microsoft... typedef pair tpair; mClients.insert(tpair(socket_info.id, socket_info)); //----------------------------------------------------------------------------- //If notify on connect is enabled we send a message to the calling application //----------------------------------------------------------------------------- if (mConfig.notifyOnConnect) { NetMessage d; d.networkId=socket_info.id; d.dataSize=-3; mIncoming.push_back(d); } MYLOG->debug("Client Connection From: %d.%d.%d.%d Received", ip[0], ip[1], ip[2], ip[3]);ENDLOG MYLOG->debug("I have %d/%d slots connected.", mClients.size(), mConfig.maxConnections);ENDLOG return 0; } } //--------------------------------------------------------------- //There are too many connections to the server already. I can't //handle any more. //--------------------------------------------------------------- else { //prevents spamming of the log if (TimerGetTime()-this->mSrvFullSpamStop>60000) { MYLOG->warning("Server is full!");ENDLOG mReport.numWarnings++; this->mSrvFullSpamStop=(int)TimerGetTime(); } } } return 0; } //************************************ // Name: Kick // // Kicks any client using the specified network id from the server. // // Parameters: // networkId - Client's network id // // Return: // //************************************ void Server::Kick(short networkId) { MYLOG->notice("Kicked!");ENDLOG KillClient(networkId); } //************************************ // Name: GetNumClients // // Retrieves the current number of clients on the server. // // Parameters: // pNumConnections - Buffer for numConnections // // Return: // //************************************ void Server::GetNumClients(int* pNumConnections) { int size=(int)mClients.size(); *pNumConnections=size; } //************************************ // Name: NewId // // Generates a unique network id for a client. (Used internally) // // Parameters: // // Return: // - Unique network id //************************************ short Server::NewId() { short Id=mNetIdMan.GetFreeID(); return Id; } //************************************ // Name: ClientExists // // Check if a client with /id/ exists on the server. // // Parameters: // id - Client's network id // // Return: // true - Client found with network id // false - No client found with network id //************************************ bool Server::ClientExists(short id) { assert(id>0); hash_map::iterator itr; itr=mClients.find(id); if (itr!=mClients.end()) { return true; } return false; } //************************************ // Name: KillClient // // Closes and client connection and/or cleans up data after connection close. // // Parameters: // id - Client's network id // // Notes: // o Adds CLIENT_DISCONNECTED message to the incoming queue // // Return: // - zero //************************************ int Server::KillClient(short id) { assert(id>0); //---------------------------------------------------------------------- //Cycle through all the incoming messages and delete ones that are for //this client. //---------------------------------------------------------------------- SOCKETINFO *sock_info=GetClientByPid(id); if (sock_info!=NULL) { ContinueCycle: std::list::iterator itr2; for (itr2=mIncoming.begin(); itr2!=mIncoming.end(); itr2++) { if (itr2->networkId==id) { if (itr2->dataSize>0 && itr2->pData!=NULL) { delete [] itr2->pData; } mIncoming.erase(itr2); goto ContinueCycle; } } //---------------------------------------------------------------------- //Close the connection and store the IP of the client we disconnected or //one that was terminated remotely. //---------------------------------------------------------------------- unsigned char ip[5]={0, 0, 0, 0, 0}; closesocket(sock_info->client); memcpy(ip, sock_info->ip, 4); mClients.erase(id); //Log the connection close MYLOG->debug("Closed Connection To: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);ENDLOG MYLOG->debug("I have: %d/%d slots connected.", mClients.size(), mConfig.maxConnections);ENDLOG //Add a NetMessage telling the calling application to deallocate local data for the client NetMessage d; d.networkId=id; d.dataSize=-2; mIncoming.push_back(d); } mNetIdMan.FreeID(id); return 0; } //************************************ // Name: UpdateServerConfig // // Updates the server configuration. // // Parameters: // sc - Server config structure // // Return: // - zero //************************************ int Server::UpdateServerConfig(SERVERCONFIG sc) { memcpy(&mConfig, &sc, sizeof(SERVERCONFIG)); return 0; } //************************************ // Name: Init // // Initializes the server. // // Parameters: // port - Port to bind or connect to. // pName - Server name // pIp - Server IP // isClient - If true the code is being used in client mode. // pMyLog - Pointer to a GWLPLog // // Return: // 0 - no errors // -55 - No logging class specified // -1 - Starting winsock failed // -2 - Unable to create socket // -3 - Hostname lookup error // -4 - Hostname lookup failed //************************************ int Server::Init(int port, char* pName, unsigned char* pIp, bool isClient, void* pMyLog) { mNetIdMan.Init(); if (pMyLog==0) { cout << "Error! NetServer does not have a logging class specified! Aborting..." << endl; return -55; } this->Crypto=NULL; this->mpMyLog=pMyLog; assert(pName!=NULL); memset(&mReport, 0, sizeof(NET_REPORT)); //Variables that must be initialized mIsClient=isClient; this->mSrvFullSpamStop=0; strcpy(mName, pName); this->mPort=port; //Attempt to load the bans list for this server char ban_file_name[80]; strcpy(ban_file_name, "System/"); strcat(ban_file_name, mName); strcat(ban_file_name, ".ban"); std::ifstream fin(ban_file_name, std::ios::binary); if (!fin.fail()) { unsigned long num_bans=0; fin.read((char*)&num_bans, sizeof(unsigned long)); for (unsigned int i=0; i bpair; unsigned long temp2=0; memcpy(&temp2, b.start, sizeof(unsigned long)); mBans.insert(bpair(temp2, b)); } fin.close(); } //----------------------------------------------------------------- //Start-up Winsock //----------------------------------------------------------------- #ifdef WIN32 { WSADATA w; // used to store information about WinSock version int error = WSAStartup (0x0202, &w); if (error) { MYLOG->error("Error in WSAStartup()");ENDLOG mReport.numErrors++; return -1; } if (w.wVersion != 0x0202) { // wrong WinSock version! MYLOG->error("Wrong WinSock version");ENDLOG mReport.numErrors++; WSACleanup (); // unload ws2_32.dll } } #endif //------------------------------------------------------------------------------- //Create my socket. Same for both server mode and client mode //------------------------------------------------------------------------------- mMySocket=socket(AF_INET, SOCK_STREAM, 0); if (mMySocket==-1) { MYLOG->error("An error has occured with socket()");ENDLOG mReport.numErrors++; #ifdef WIN32 WSACleanup(); #endif return -2; } //------------------------------------------------------------------------------ //If server is running in server mode //------------------------------------------------------------------------------ if (!mIsClient) { //grab the local IP, modified from some other code. =/ char ac[80]; if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR_N) { #ifdef WIN32 MYLOG->error("Error #%d", WSAGetLastError());ENDLOG MYLOG->error(" when getting local host name.");ENDLOG mReport.numErrors++; #endif return -3; } MYLOG->notice("Success: Host name is: %s", ac);ENDLOG struct hostent *phe = gethostbyname(ac); if (phe==0) { MYLOG->error("Host lookup failed.");ENDLOG mReport.numErrors++; return -4; } struct in_addr addr; for (int i = 0; phe->h_addr_list[i] != 0; ++i) { memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr)); } memset(my_address.sin_zero, 0 , 8); my_address.sin_family=AF_INET; my_address.sin_port=htons(port); //----------------------------------------------------- //We are using automatic IP address detection //----------------------------------------------------- if (pIp==0) { my_address.sin_addr.s_addr=inet_addr(inet_ntoa(addr)); } //----------------------------------------------------- //An IP address is specified so we use that and do not //use the automatically detected one. //----------------------------------------------------- else { char ipaddr[17]; sprintf(ipaddr, "%d.%d.%d.%d", pIp[0], pIp[1], pIp[2], pIp[3]); my_address.sin_addr.s_addr=inet_addr(ipaddr); } //Bind our server to the port specified Bind(); } //------------------------------------------------------------------------- //The server is running in client mode //------------------------------------------------------------------------- else { my_address.sin_family=AF_INET; my_address.sin_port=htons(port); my_address.sin_addr.s_addr=INADDR_ANY; memset(my_address.sin_zero, '\0', 8); } return 0; } //************************************ // Name: Connect // // Connects to a server. // // Parameters: // pIpBytes - IP address of server (byte form) // // Return: // 0 - no errors // -1 - connect() failed // -2 - Could not set non-blocking // -5 - Connect cannot be used in server mode. //************************************ int Server::Connect(unsigned char* pIpBytes) { assert(pIpBytes!=NULL); //-------------------------------------------------------------------------- //Running in client mode //-------------------------------------------------------------------------- if (mIsClient) { char converted[4][20]; for (int i=0; i<4; i++) sprintf(converted[i], "%d", pIpBytes[i]); char final_ip[17]; memset(final_ip, 0, 16); for (int i=0; i<4; i++) { strcat(final_ip, converted[i]); if (i<3) strcat(final_ip, "."); } char *ip=final_ip; SOCKETINFO s; my_address.sin_addr.s_addr=inet_addr(ip); if (connect(mMySocket, (struct sockaddr *)&my_address, sizeof(struct sockaddr))==-1) { #ifdef WIN32 MYLOG->error("Error #%d", WSAGetLastError());ENDLOG MYLOG->error("Could not connect to server");ENDLOG mReport.numErrors++; closesocket(mMySocket); WSACleanup(); #endif return -1; } int int_no_block=1; #ifdef WIN32 //Disable the Nagle algorithm bool disable_nagle=true; int boolean_bytes=sizeof(bool); if (setsockopt(mMySocket, SOL_SOCKET, TCP_NODELAY, (char*)&disable_nagle, boolean_bytes)==SOCKET_ERROR_N) { MYLOG->error("Could not turn off Nagle algorithm.");ENDLOG } if (ioctlsocket(mMySocket, FIONBIO, (u_long FAR*) &int_no_block)==-1) { MYLOG->error("Error #%d", WSAGetLastError());ENDLOG MYLOG->error("Changing to non-blocking socket failed!");ENDLOG mReport.numErrors++; return -2; } #else // linux equivalent to set non-blocking int flags; if ((flags = fcntl(mMySocket, F_GETFL, 0)) < 0) { MYLOG->error("Error setting non-blocking");ENDLOG mReport.numErrors++; return -1; } flags |= O_NONBLOCK|O_NDELAY; if (fcntl(mMySocket, F_SETFL, flags) == -1) { MYLOG->error("Error setting non-blocking");ENDLOG mReport.numErrors++; return -1; } #endif s.client=mMySocket; s.inUse=true; s.id=NewId(); memcpy((char*)s.ip, (char*)pIpBytes, 4); //Add the client to the hash map typedef pair tpair; mClients.insert(tpair(s.id, s)); MYLOG->notice("Connected To: %d.%d.%d.%d", s.ip[0], s.ip[1], s.ip[2], s.ip[3]);ENDLOG } //----------------------------------------------------------------------------------- //Running in server mode //----------------------------------------------------------------------------------- else { MYLOG->error("Connect() cannot be called on servers with IsClient not enabled!");ENDLOG mReport.numErrors++; return -5; } return 0; }