void ChatServer::processMessage(ChannelCreateRequest *msg) { ChannelCreateResult *result = new ChannelCreateResult(); switch (m_clientList.createChannel(msg->channelName, msg->channelDescription, msg->channelTopic)) { case GeneralClientList::ccrTooManyChannels: { result->answer = false; result->denialReason = "Too many channels already created on server."; } case GeneralClientList::ccrBadName: { result->answer = false; result->denialReason = "Name of channel is already reserved"; } case GeneralClientList::ccrSuccess: { result->answer = true; } } sendMessageToClient(msg->username, result); if (result->answer) { m_clientList.joinChannel(msg->username, msg->channelName); ChannelListMessage *userListUpdate = new ChannelListMessage(); userListUpdate->listType = ChannelListMessage::listOfJoined; userListUpdate->channelList = m_clientList.getChannelsForClient(msg->username); sendMessageToClient(msg->username, userListUpdate); delete userListUpdate; ChannelListMessage *listUpdate = new ChannelListMessage(); listUpdate->listType = ChannelListMessage::listOfAll; listUpdate->channelList = m_clientList.getAllChanells(); sendMessageToChannel("main", listUpdate); delete listUpdate; ChannelUserList *list = new ChannelUserList(); list->channelName = msg->channelName; ChatChannel tempChannel = m_clientList.getChannel(msg->channelName); for(int i = 0; i < tempChannel.userList.count(); i++) { //FIXME: GOVNOKOD list->userList.insert(tempChannel.userList[i], getSendableState(tempChannel.userList[i])); } sendMessageToChannel(msg->channelName, list); delete list; ChannelThemeChanged *theme = new ChannelThemeChanged(); theme->channel = msg->channelName; theme->theme = m_clientList.getChannel(msg->channelName).topic(); sendMessageToClient(msg->username, theme); delete theme; emit updateTable("channels"); emit updateTable("membership"); } delete result; }
bool ServerPage::mouseReleased(sf::Mouse::Button button, int x, int y) { if(backButton.mouseReleased(button, x, y)) { *pageNum = 1; sendMessageToClient("logoutOfOwnServer"); } if(startButton.mouseReleased(button, x, y)) { sendMessageToClient("startGame"); } return true; }
void ChatServer::processMessage(ChannelListRequest *msg, QTcpSocket *socket) //new processMessage for ChannelListRequest { if (!msg) { QString log = "Error processing authorization request- message is empty"; emit serverLog(esMinor, log); return; } ChannelListMessage *chanListMsg = new ChannelListMessage(); if(msg->listType == ChannelListRequest::listOfAll) { chanListMsg->listType = ChannelListMessage::listOfAll; chanListMsg->channelList = m_clientList.getAllChanells(); sendMessageToClient(socket, chanListMsg); } else { chanListMsg->listType = ChannelListMessage::listOfJoined; chanListMsg->channelList = m_clientList.getChannelsForClient(msg->nick); sendMessageToClient(socket, chanListMsg); ChannelUserList *userListMsg = new ChannelUserList(); ChannelThemeChanged *theme = new ChannelThemeChanged(); QMap<QString, QString>::iterator channel = chanListMsg->channelList.begin(); for(;channel != chanListMsg->channelList.end(); ++channel) { QString channelName = channel.key(); ChatChannel tempChannel = m_clientList.getChannel(channelName); userListMsg->channelName = channel.key(); for(int i = 0; i < tempChannel.userList.count(); i++) { //FIXME: GOVNOKOD userListMsg->userList.insert(tempChannel.userList[i], getSendableState(tempChannel.userList[i])); } theme->channel = channel.key(); theme->theme = m_clientList.getChannel(userListMsg->channelName).topic(); sendMessageToChannel(channel.key(), userListMsg); sendMessageToClient(msg->nick, theme); } delete userListMsg; delete theme; UserInfoMessage *userInfo = new UserInfoMessage(); userInfo->username = msg->nick; userInfo->info = m_clientList.getClient(msg->nick).userInfo(); sendMessageToClient(msg->nick, userInfo); delete userInfo; } delete chanListMsg; }
/* * Executes the traceroute command and sends output * to client. */ void traceRoute(char *command,int clientSocketDes) { char message[1024]; strcpy(message, SEPERATOR); sendMessageToClient(message, clientSocketDes); FILE *fp = popen(command, "r"); char line[1024]; char reply[1024]; while (fgets(line, sizeof(line), fp)) { cout<<line<<"\n"; strcpy(reply, line); strcat(reply, "\n"); sendMessageToClient(reply, clientSocketDes); } pclose(fp); sendMessageToClient(message, clientSocketDes); }
void ChatServer::processMessage(UserInfoRequest *msg, QTcpSocket *socket) { UserInfoMessage *answer = new UserInfoMessage(); answer->username = msg->username; answer->info = m_clientList.getClient(msg->username).userInfo(); sendMessageToClient(socket, answer); delete answer; }
/* * Starts server execution. */ void Socket::startServerProcess() { remCon = this->maximum_users; maxCon = this->maximum_users; if(this->bindSocket() == YES) { //Log server started serverStartedLog(); while((listen(this->sock_fd, this->maximum_users))==0) { struct sockaddr_in tempAddress; memset(&tempAddress,0, sizeof(tempAddress)); params details; socklen_t sockAddrLen = sizeof(tempAddress); int connFD = accept(this->sock_fd, (struct sockaddr*)&tempAddress,&sockAddrLen); if(connFD!=-1 && remCon>0) { sem_wait(&mutex); remCon--; cout<<"\n REMAINING CONNECTIONS : "<<remCon; sem_post(&mutex); details.connFD = connFD; details.maxRate = this->reqPerMinPerUser; details.kTimeUnit = this->timeUnit; details.clientAddress = tempAddress; details.isStrictOn = this->strictDestination; pthread_create(&pids[totalThreads], NULL, handleRequest,(void*)&details); } else if(connFD!=-1 && remCon<=0) { char mess[16]; strcpy(mess, "terminate"); sendMessageToClient(mess, connFD); //LOG simultaneousConnectionLimitExccededLog(inet_ntoa(details.clientAddress.sin_addr),details.clientAddress.sin_port); close(connFD); } } for (int i=0; i<totalThreads; i++) { pthread_join(pids[i], NULL); } } }
void ChatServer::processMessage(ChannelJoinRequest *msg, QTcpSocket *socket) { ChannelJoinResult *answer = new ChannelJoinResult(); if(m_clientList.hasChannel(msg->channelName) && !m_clientList.getChannel(msg->channelName).hasClient(msg->nick)) { m_clientList.joinChannel(msg->nick, msg->channelName); answer->result = true; ChannelListMessage *listUpdate = new ChannelListMessage(); listUpdate->listType = ChannelListMessage::listOfJoined; listUpdate->channelList = m_clientList.getChannelsForClient(msg->nick); sendMessageToClient(msg->nick, listUpdate); delete listUpdate; ChannelSystemMessage *newmsg = new ChannelSystemMessage(); newmsg->message = msg->nick + " joined channel"; newmsg->channelName = msg->channelName; sendMessageToChannel(msg->channelName, newmsg); delete newmsg; emit updateTable("membership"); ChannelUserList *list = new ChannelUserList(); list->channelName = msg->channelName; ChatChannel tempChannel = m_clientList.getChannel(msg->channelName); for(int i = 0; i < tempChannel.userList.count(); i++) { //FIXME: GOVNOKOD list->userList.insert(tempChannel.userList[i], getSendableState(tempChannel.userList[i])); } sendMessageToChannel(msg->channelName, list); delete list; ChannelThemeChanged *theme = new ChannelThemeChanged(); theme->channel = msg->channelName; theme->theme = m_clientList.getChannel(msg->channelName).topic(); sendMessageToClient(msg->nick, theme); delete theme; } else { answer->result = false; } answer->channelName = msg->channelName; sendMessageToClient(socket, answer); delete answer; }
bool MultiplayerPage::mouseReleased(sf::Mouse::Button button, int x, int y) { if(backButton.mouseReleased(button, x, y)) *pageNum = 0; if(serverButton.mouseReleased(button, x, y)) { *pageNum = 2; sendMessageToClient("loginToOwnServer"); } if(clientButton.mouseReleased(button, x, y)) *pageNum = 3; return true; }
int startServer(){ /* server start */ AllGameInfo agi; char clientMsg[MAX_MESSAGE+1]; char *cmd[20]; int n; ServerMessage sm; int clientId; /* 1 or 2 */ int fd; int res; #if defined TEST #endif /* Create fifo file */ if((mkfifo(FIFO_SERVER, 0777)) < 0) printf("Cannot create fifoServe : %s\n", FIFO_SERVER); /* iit all info */ initAllGameInfo(&agi); while(1){ /* receive client msg */ receiveClientMsg(FIFO_SERVER, clientMsg); n = splitStrByChar(clientMsg, cmd, ' '); if(n < 1 || n > 3){ printf("******************************\n"); printf("%s clientMsg error: %s %s %s\n", cmd[0], cmd[0], cmd[1], cmd[2]); printf("******************************\n"); } if(n >= 3){ if(!strcmp(cmd[2],"TJ")) strcpy(cmd[2],"XT"); if(!strcmp(cmd[2],"WJ")) strcpy(cmd[2],"XW"); } clientId = getClientId(cmd[0]); updateAllGameInfo(&agi, cmd); printf("gameInfoToServerMessage for %d\n", clientId); sendMessageToClient(agi, clientId); } #if defined TEST #endif return 0; }
void ChatServer::stopServer(const QString &shutdownReason) //stops server //we need to send disconnect messages to all channels { GeneralClientList::userSocketsList_t *userList = m_clientList.getAllSockets(); GeneralClientList::userSocketsListIterator_t itr(*userList); ServerShutdownMessage msg; msg.shutdownReason = shutdownReason; while(itr.hasNext()) sendMessageToClient(itr.next(), &msg); delete userList; m_clientList.disconnectAll(); QString log = tr("Server stopped."); m_tcpServer->close(); disconnect(m_tcpServer, SIGNAL(newConnection()), this, SLOT(serverGotNewConnection())); disconnect(&m_clientList, SIGNAL(logMessage(ErrorStatus, QString&)), this, SLOT(replyLog(ErrorStatus, QString&))); emit serverLog(esNotify, log); delete m_tcpServer; }
void ChatServer::processMessage(RegistrationRequest *msg, QTcpSocket *socket) //processing regisration message //registration logic stored in clientList, //we just call it and use results to send registration answer { if (!msg) { QString log = "Error processing registration request - message is empty"; emit serverLog(esMinor, log); return; } RegistrationAnswer *answer = new RegistrationAnswer(); switch (m_clientList.registrate(msg->username, msg->password)) { case GeneralClientList::rrOccupiedUsername: { answer->registrationResult = false; answer->denialReason = "Username allready reserved, please choose another"; break; } case GeneralClientList::rrBadUsername: { answer->registrationResult = false; answer->denialReason = "Your username isn't allowed"; break; } case GeneralClientList::rrRegSuccess: { answer->registrationResult = true; emit updateTable("clients"); emit updateTable("membership"); break; } } sendMessageToClient(socket, answer); // QString log = msg->username + ((answer->registrationResult) ? " was registered." : "wasn't registered"); emit serverLog(esNotify, log); // delete answer; }
void ChatServer::processMessage(PasswordChangeRequest *msg) { PasswordChangeResult *answer = new PasswordChangeResult; ChatClient client = m_clientList.getClient(msg->username); QString log; if(client.password() == msg->oldPassword) { client.setPassword(msg->newPassword); m_clientList.updateClient(client); answer->result = "Password changed!\nDon't forget to use new password in the next authorization."; log = "User " + msg->username + " changed his password"; emit updateTable("clients"); } else { answer->result = "Given old password is incorrect!"; log = "User " + msg->username + " tried to change his password. Unfortunately, unsuccessfull."; } emit serverLog(esNotify, log); sendMessageToClient(msg->username, answer); }
void ChatServer::sendMessageToChannel(QString channelName, ChatMessageBody *msgBody) //send message *msgBody to all clients, which are in channel <channelName> //needed for replying channel and other messages for all channel { if (!m_clientList.hasChannel(channelName)) return; /*QByteArray arrBlock; QDataStream output(&arrBlock, QIODevice::WriteOnly); output.setVersion(QDataStream::Qt_4_7); output << quint16(0); ChatMessageHeader *header = new ChatMessageHeader(msgBody); header->pack(output); msgBody->pack(output); delete header; output << quint16(arrBlock.size() - sizeof(quint16));*/ ChatChannel channel = m_clientList.getChannel(channelName); for (int i = 0; i < channel.userList.count(); i++) { sendMessageToClient(channel.userList[i], msgBody); /*channel.userList[i]->userSocket()->write(arrBlock);*/ } }
//Countdown to time out and then kill the parent thread void *countdown(void *arg) { countdownParams details = *(countdownParams*)arg; double diff = difftime(time(NULL), details.startTime); while (diff<TIMEOUT_INTERVAL) { diff = difftime(time(NULL), details.startTime); //cout<<"\n Diff..... "<<diff<<"...."<<details.socketDescriptor; } //client timeout and disconnection logic if(diff>=TIMEOUT_INTERVAL) { char mess[1024]; strcpy(mess, "\nConnection Time Out"); sendMessageToClient(mess, details.socketDescriptor); close(details.socketDescriptor); sem_wait(&mutex); if(remCon<maxCon) remCon++; cout<<"\n REMAINING CONNECTIONS : "<<remCon; sem_post(&mutex); int result = pthread_cancel(details.parentThread); if(result==0) automaticTimeOutLog(details.ipAddress, details.port_no); } pthread_exit(NULL); //countdown till 30 if the thread is not killed the it will terminate the client connection and the thread return NULL; }
/* Process user command * * userInput : char* - the user input * return : void */ void processUserInput(ClientManager* clientManager, char* userInput, int i){ Client* currentClient = &(clientManager->clients[i]); char* respondMessage = "(And this is the respond message)"; sendMessageToClient(currentClient, respondMessage, 33, NOT_FREE_STRING); printf(FMT_OUTPUT, userInput, respondMessage); }
void ChatServer::processMessage(AuthorizationRequest *msg, QTcpSocket *socket) //processing authorization request //here we need to check whether user exists in table or not //YOBA ETO YA, PSHH-PSSHHH //and we need to form authorization answer and send it to client { if (!msg) { QString log = "Error processing authprization request- message is empty"; emit serverLog(esMinor, log); return; } AuthorizationAnswer *answer = new AuthorizationAnswer(); switch (m_clientList.authorize(msg->username, msg->password, socket)) { case GeneralClientList::arAllreadyAuthorized: { answer->authorizationResult = false; answer->denialReason = "User allready authorized"; break; } case GeneralClientList::arWrongAuthData: { answer->authorizationResult = false; answer->denialReason = "Wrong username or password"; break; } case GeneralClientList::arAuthSuccess: { answer->authorizationResult = true; break; } } sendMessageToClient(socket, answer); if (answer->authorizationResult) { ChatClient client = m_clientList.getClient(msg->username); client.setUserState("Online"); m_clientList.updateClient(client); emit updateTable("clients"); QStringList channels = m_clientList.getChannelsForClient(msg->username).keys(); ChannelSystemMessage *informMsg = new ChannelSystemMessage(); ChannelUserList *updateListMsg = new ChannelUserList(); informMsg->message = msg->username + " entered chat."; for (int i = 0; i < channels.count(); ++i) { informMsg->channelName = channels[i]; updateListMsg->channelName = channels[i]; ChatChannel channel = m_clientList.getChannel(channels[i]); for(int k = 0; k < channel.userList.count(); k++) { //FIXME: GOVNOKOD updateListMsg->userList.insert(channel.userList[k], getSendableState(channel.userList[k])); } for (int j = 0; j < channel.userList.count(); j++) { QString username = channel.userList[j]; if (username != msg->username) { sendMessageToClient(username, informMsg); sendMessageToClient(username, updateListMsg); } } } delete updateListMsg; delete informMsg; } delete answer; }
void ClientPage::submitForm() { sendMessageToClient(ipTextBox.getString() + ":" + portTextBox.getString()); }
/* * Creates a new thread for each client and handles all client requests. */ void * handleRequest(void *arg) { params details = *(params*)arg; int connFD = details.connFD; int numberOfTraceroutes = 0; char *ipaddress =new char[15](); int isStrictOn = details.isStrictOn; ipaddress = inet_ntoa(details.clientAddress.sin_addr); //LOG clientConnectedLog(ipaddress,details.clientAddress.sin_port); time_t startTime = NULL; char mess[1024]; strcpy(mess,PROMPT); sendMessageToClient(mess, connFD); pthread_t countThread; countdownParams connDetails; strcpy(connDetails.ipAddress, ipaddress); connDetails.port_no = details.clientAddress.sin_port; connDetails.socketDescriptor = connFD; connDetails.parentThread = pthread_self(); connDetails.startTime = time(NULL); pthread_create(&countThread, NULL, countdown,(void*)&connDetails); //continuously run the server while (1) { char buff[1024]; size_t buffSize = (size_t)sizeof(buff); memset(&buff, 0,buffSize); recv(connFD, &buff, buffSize,0); cout<<"\n Client "<<connFD<<" : "<<buff; if(buff==NULL || strlen(buff)<=0){ continue;} Command *cmd = new Command(buff); //help command if(strcmp(cmd->command, "help")==0) { //kill previous timer if((pthread_cancel(countThread))!=0) cout<<"\n Cannot kill thread"; /* //Send help file FILE *fp = fopen(HELP_FILE, "r"); char line[1024];*/ ifstream infile; infile.open("help.txt"); string line, message_to_send; if (infile.is_open()) { while (!infile.eof()) { getline(infile, line); cout<<"line " <<line<<endl; message_to_send = message_to_send + line + "\n"; } } cout<<"message_to_send "<<message_to_send<<endl; strcpy(mess, message_to_send.c_str()); sendMessageToClient(mess, connFD); /*while (fgets(line, sizeof(line), fp)) { //cout<<line<<"\n"; strcpy(mess, line); strcat(mess, "\n"); sendMessageToClient(mess, connFD); }*/ //start new timer connDetails.startTime = time(NULL); pthread_create(&countThread, NULL, countdown, (void*)&connDetails); } else if(strcmp(cmd->command, "traceroute")==0 && cmd->total_args==1) { //kill previous timer if((pthread_cancel(countThread))!=0) cout<<"\n Cannot kill thread"; char *tracerouteCommands[100]; int totalTracerouteCommands=0; /*determine command type*/ if(strcmp(cmd->args[0], "me")==0) { //This is traceroute me command char *command = new char[1024](); strcat(command, cmd->command); strcat(command, " "); strcat(command, ipaddress); tracerouteCommands[totalTracerouteCommands++]=command; }else { //normal traceroute //check if argument is a file FILE *batchFile = fopen(cmd->args[0], "r"); //arg[0] contains the value of argument to traceroute. //read commands from file if(batchFile!=NULL) { char line[1024]; while (fgets(line, sizeof(line), batchFile)) { Command *c = new Command(line); char *command = new char[1024](); strcat(command, c->command); strcat(command, " "); strcat(command, c->args[0]); bool isArgumentValid = validateTarget(c->args[0]); if(isArgumentValid) tracerouteCommands[totalTracerouteCommands++]=command; else { strcpy(mess, "\nInvalid parameter to traceroute command."); sendMessageToClient(mess, connFD); } } fclose(batchFile); } else { //read command from user input char *command = new char[1024](); strcat(command, cmd->command); strcat(command, " "); bool isArgumentValid = validateTarget(cmd->args[0]); if(isArgumentValid==true) { cout<<"Valid IP"; strcat(command, cmd->args[0]); int res = strcmp(cmd->args[0],ipaddress); cout<<" "<<ipaddress<<" "<<cmd->args[0]; cout<<"IP ADDR COMP"<<res; if((isStrictOn &&(strcmp(cmd->args[0],ipaddress)!=0))) { //LOG strictviolatedLog(ipaddress, details.clientAddress.sin_port, command); char mess[1024]; strcpy(mess, "\nCannot traceroute to host other than yourself\n"); sendMessageToClient(mess, connFD); } else tracerouteCommands[totalTracerouteCommands++]=command; } else { cout<<"Invalid IP"; strcpy(mess, "Invalid parameter to traceroute command."); sendMessageToClient(mess, connFD); } } } int index=0; while(totalTracerouteCommands>0) { if(numberOfTraceroutes==0) { startTime = time(NULL); } double diffInSec = difftime(time(NULL), startTime); if((numberOfTraceroutes+1<=details.maxRate) && (diffInSec<=details.kTimeUnit)) { numberOfTraceroutes++; cout<<"\n Executing "<<numberOfTraceroutes<<" "<<diffInSec/details.kTimeUnit<<":"<<(int)diffInSec%details.kTimeUnit; //LOG simpleTrtLog(ipaddress,cmd->args[0],details.clientAddress.sin_port); traceRoute(tracerouteCommands[index++], connFD); } else if ((numberOfTraceroutes+1>details.maxRate) && (diffInSec<=details.kTimeUnit)) { totalTracerouteCommands=1; strcpy(mess, "Rate limit excedded"); sendMessageToClient(mess, connFD); rateLimitExceededLog(ipaddress, details.clientAddress.sin_port, tracerouteCommands[index]); } else if((numberOfTraceroutes+1>details.maxRate) && (diffInSec>details.kTimeUnit)) { numberOfTraceroutes=0; startTime=time(NULL); cout<<"\n Executing "<<numberOfTraceroutes<<" "<<diffInSec/details.kTimeUnit<<":"<<(int)diffInSec%details.kTimeUnit; //LOG simpleTrtLog(ipaddress,cmd->args[0],details.clientAddress.sin_port); traceRoute(tracerouteCommands[index++], connFD); } else if((numberOfTraceroutes+1<=details.maxRate) && (diffInSec>details.kTimeUnit)) { numberOfTraceroutes=0; startTime=time(NULL); cout<<"\n Executing "<<numberOfTraceroutes<<" "<<diffInSec/details.kTimeUnit<<":"<<(int)diffInSec%details.kTimeUnit; //LOG simpleTrtLog(ipaddress,cmd->args[0],details.clientAddress.sin_port); traceRoute(tracerouteCommands[index++], connFD); } else{ } totalTracerouteCommands--; } //start new timer connDetails.startTime = time(NULL); pthread_create(&countThread, NULL, countdown, (void*)&connDetails); } else if(strcmp(cmd->command, "quit")==0) { //kill previous timer if((pthread_cancel(countThread))!=0) cout<<"\n Cannot kill thread"; //close connection strcpy(mess, "terminate"); sendMessageToClient(mess, connFD); //LOG clientDisconnetedLog(ipaddress,details.clientAddress.sin_port); if(close(connFD)==0) cout<<"\nClient "<<connFD<<" closed"; else cout<<"\n Error closing client"<<connFD; //modify global remaining connections using semaphore sem_wait(&mutex); remCon = (remCon+1>=maxCon)?maxCon:++remCon; cout<<"\n REMAINING CONNECTIONS : "<<remCon; sem_post(&mutex); pthread_exit((void*)&connFD); } else { //kill previous timer if((pthread_cancel(countThread))!=0) cout<<"\n Cannot kill thread"; strcpy(mess, "\nInvalid Command\n"); sendMessageToClient(mess, connFD); //start new timer connDetails.startTime = time(NULL); pthread_create(&countThread, NULL, countdown, (void*)&connDetails); } strcpy(mess,PROMPT); sendMessageToClient(mess, connFD); cmd->~Command(); } return NULL; }