예제 #1
0
void ram(void) {
    struct NRF_CFG config;
    uint8_t buf[16];
    
    // Space to save signal strength and username.
    uint8_t count = 0;
    char usernames[8][16];
    uint8_t strength[8];

    config.nrmacs=1;
    config.maclen[0] = 16;
    config.channel = 81;
    memcpy(config.mac0, "\x01\x02\x03\x02\x01", 5);
    nrf_config_set(&config);
    lcdClear();
    lcdPrintln("Track it:");
    lcdPrintln("---------");
    lcdRefresh();
    do{
        if( nrf_rcv_pkt_time(64,sizeof(buf),buf) == 16 ){
            buf[14] = 0;
            // TODO: allow last package parameter 0x25
            if( buf[1] == 0x23 || buf[1] == 0x24){
                if(0==insertUser(usernames, strength, (char *)buf+6, buf[3],
                  count)) {
                  if(count<8) ++count;
                  printNames(usernames, strength, count);
                }
            }
        }
    }while ((getInputRaw())==BTN_NONE);
}
예제 #2
0
void IrcUserModelPrivate::promoteUser(IrcUser* user)
{
    Q_Q(IrcUserModel);
    if (sortMethod == Irc::SortByActivity) {
        const bool notify = false;
        removeUser(user, notify);
        insertUser(0, user, notify);
        if (updateTitles())
            emit q->titlesChanged(titles);
        emit q->usersChanged(userList);
    }
}
예제 #3
0
/*
 *Register
 */
int register_user(packet *in_pkt, int fd) {
   int i = 0;
   char *args[16];
   char cpy[BUFFERSIZE];
   char *tmp = cpy;
   strcpy(tmp, in_pkt->buf);

   args[i] = strsep(&tmp, " \t");
   while ((i < sizeof(args) - 1) && (args[i] != '\0')) {
       args[++i] = strsep(&tmp, " \t");
   }
   // Check there are enough arguements to safely inspect them
   if (i > 3) {
      // Ensure requested username is valid
      if (!validUsername(args[1], fd)) { return 0; }
      // Check if the requested username is unique
      if(strcmp(get_real_name(&registered_users_list, args[1], registered_users_mutex), "ERROR") !=0 || \
                              !(strcmp(SERVER_NAME, args[1])) || \
                              strcmp(args[2], args[3]) != 0) {
         sendError("Username unavailable.", fd);
         return 0;
      }
      // Ensure password requested is valid
      if (!validPassword(args[2], args[3], fd)) { return 0; }

      // Allocate memory space for new user node, populate node with new user data
      User *user = (User *)malloc(sizeof(User));
      strcpy(user->username, args[1]);
      strcpy(user->real_name, args[1]);
      // Hash password
      SHA256_CTX sha256;
      SHA256_Init(&sha256);
      SHA256_Update(&sha256, args[2], strlen(args[2]));
      SHA256_Final(user->password, &sha256);
      user->sock = fd;
      user->next = NULL;
      
      // Insert user as registered user, write new user data to file
      insertUser(&registered_users_list, user, registered_users_mutex);
      writeUserFile(&registered_users_list, USERS_FILE, registered_users_mutex);

      // Reform packet as valid login, pass new user data to login
      memset(&in_pkt->buf, 0, sizeof(in_pkt->buf));
      sprintf(in_pkt->buf, "/login %s %s", args[1], args[2]);
      return login(in_pkt, fd);
   }
   // There were not enough arguements received to correctly read them
   else {
      printf("%s --- %sError:%s Malformed reg packet received from %s on %d, ignoring.\n", \
             WHITE, RED, NORMAL, args[1], fd);
   }
   return 0;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Add account Dialog
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void MainWindow::registerAccount()
{
    QDialog dialog(this);
    // Use a layout allowing to have a label next to each field
    QFormLayout form(&dialog);

    // Add the lineEdits with their respective labels
    QLineEdit *userEdit = new QLineEdit(&dialog);
    QString userString = QString("Username:"******"Password:"******"Confirm Password:"******"Ok");
    cancelButton->setText("Cancel");

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(okButton);
    layout->addWidget(cancelButton);

    form.addRow(layout);
    QObject::connect(okButton, SIGNAL(clicked()), &dialog, SLOT(accept()));
    QObject::connect(cancelButton, SIGNAL(clicked()), &dialog, SLOT(close()));

    if (dialog.exec() == QDialog::Accepted) {
        //add the user to the database

        //check passwords are equivalent
        if (passEdit->text() == conPassEdit->text() && userEdit->text() != "")
        {
            std::string usr = userEdit->text().toStdString();
            std::string pss = passEdit->text().toStdString();
            insertUser(usr, pss);
        }
        else
        {
            invalidDialog("Please make sure the username field isn't empty\n and ensure Passwords fields match");
            registerAccount();
        }
    }
}
예제 #5
0
void ChatChannel::connectAll()
{
  connect(_conn, SIGNAL(chatUsersRecv(QString,QMap<QString,shared_ptr<ChatUser> >)),
          this, SLOT(updateUsers(QString,QMap<QString,shared_ptr<ChatUser> >)));
  connect(_conn, SIGNAL(chatUserEnter(QString,shared_ptr<ChatUser>)),
          this, SLOT(insertUser(QString,shared_ptr<ChatUser>)));
  connect(_conn, SIGNAL(chatUserLeave(QString,QString)),
          this, SLOT(removeUser(QString,QString)));
  connect(this, SIGNAL(sendPublicReady(QString,QString)),
          _conn, SLOT(chatSendPublic(QString,QString)));
  connect(_conn, SIGNAL(chatPublicMessage(QString,QString,QString)),
          this, SLOT(publicMessageRecv(QString,QString,QString)));
}
예제 #6
0
void IrcUserModelPrivate::renameUser(IrcUser* user)
{
    Q_Q(IrcUserModel);
    if (updateUser(user) && sortMethod != Irc::SortByHand) {
        QList<IrcUser*> users = userList;
        const bool notify = false;
        removeUser(user, notify);
        insertUser(-1, user, notify);
        if (updateTitles())
            emit q->titlesChanged(titles);
        if (users != userList)
            emit q->usersChanged(userList);
    }
}
예제 #7
0
파일: login.c 프로젝트: younghedong/chat
void on_button_signup_clicked(GtkWidget *button, gpointer data)
{
	gint type;
	const gchar *username = gtk_entry_get_text(GTK_ENTRY(entry1));
	const gchar *password = gtk_entry_get_text(GTK_ENTRY(entry2));
	if(strlen(password) < 6)
	{
		informationdialog(-6);
	}
	else
	{
		type = insertUser((char *)username, (char *)password);
		informationdialog(type);
	}
	gtk_entry_set_text(GTK_ENTRY(entry1), "");
	gtk_entry_set_text(GTK_ENTRY(entry2), "");
}
예제 #8
0
void IrcUserModelPrivate::addUser(IrcUser* user, bool notify)
{
    insertUser(-1, user, notify);
}
int insertUser(string ID, string pw){
	return insertUser(Account(ID, pw));
}
void *run(void *arg){
	pthread_detach(pthread_self());
	vector<string>tok;
	Account currentUser;
	int n;
	char  mesg[MAXLINE], sendline[MAXLINE], recvline[MAXLINE];
	ClientSock clientSock=*(ClientSock*)arg;
	int connfd=clientSock.connfd;
	struct sockaddr_in cliaddr=clientSock.addr;
	free(arg);

	while((n=receive(connfd, recvline)) >0) {

		recvline[n]=0; /* null terminate */
		printf("from client IP %s port %d\n", getIP(cliaddr), getPort(cliaddr));
		printf("connfd = %d\n", connfd);
		tok.clear();
		tok=parse(recvline);
		

		if(userAccount.find(User(getIP(cliaddr), getPort(cliaddr), cliaddr))==userAccount.end()){
			if(tok[0][0]=='R'){
				writeRecv(connfd, recvline, strlen(recvline));// send to client
				//register
				currentUser=Account(tok[1], tok[2]);
				currentUser.state=Normal;
				userAccount[User(getIP(cliaddr), getPort(cliaddr), cliaddr, connfd)]=currentUser;
				accountUser[currentUser]=User(getIP(cliaddr), getPort(cliaddr), cliaddr, connfd);
				
				if(insertUser(currentUser)){
					puts("register sucess");
					write(connfd, SUCCESS, strlen(SUCCESS));

					// update filelist
					recvFilelist(connfd, currentUser.ID);


				}
				else{
					puts("register fail");

					write(connfd, FAIL, strlen(FAIL));
				}
			}
			else if(tok[0][0]=='L'){
				writeRecv(connfd, recvline, strlen(recvline));// send to client
				if(login(Account(tok[1], tok[2]))){
					currentUser=Account(tok[1], tok[2]);
					currentUser.state=Normal;
					userAccount[User(getIP(cliaddr), getPort(cliaddr), cliaddr, connfd)]=currentUser;
					accountUser[currentUser]=User(getIP(cliaddr), getPort(cliaddr), cliaddr, connfd);
					puts("login sucess");
					write(connfd, SUCCESS, strlen(SUCCESS));	
					// update filelist
					recvFilelist(connfd, currentUser.ID);

				}
				else{
					puts("login fail");
					write(connfd, FAIL, strlen(FAIL));
				}
			}
		}
		else{ // login already
			currentUser=userAccount[User(getIP(cliaddr), getPort(cliaddr), cliaddr)];
			accountUser[currentUser]=User(getIP(cliaddr), getPort(cliaddr), cliaddr);
			if(currentUser.state==Normal){
				if(tok[0]=="Del"){// delete account
					writeRecv(connfd, recvline, strlen(recvline));// send to client
					puts("Delete account");
					deleteUser(currentUser);// delete in db
					userAccount.erase(User(getIP(cliaddr), getPort(cliaddr), cliaddr));
					accountUser.erase(currentUser);
					
					write(connfd, SUCCESS, strlen(SUCCESS));
				}
				else if(tok[0]=="L"){// logout
					writeRecv(connfd, recvline, strlen(recvline));// send to client
					puts("Logout");
					userAccount.erase(User(getIP(cliaddr), getPort(cliaddr), cliaddr));
					accountUser.erase(currentUser);
					deleteFile(currentUser.ID);
					write(connfd, SUCCESS, strlen(SUCCESS));
				}
			
				//------------------------------------------------
				// show filelist/ show user
				else if(tok[0]=="SU"){// show user
					writeRecv(connfd, recvline, strlen(recvline));// send to client
					writeRecv(connfd, SUCCESS, strlen(SUCCESS));
					sendUser(connfd);
				}
				else if(tok[0]=="SF"){// show filelist
					writeRecv(connfd, recvline, strlen(recvline));// send to client
					writeRecv(connfd, SUCCESS, strlen(SUCCESS));
					showFilelist();
					sendResult(connfd, 2, result);
				}
				//------------------------------------------------
				// upload download
				else if(tok[0]=="D"){// download
					writeRecv(connfd, recvline, strlen(recvline));// send to client
					int numFile=existNumFile(tok[1]);
					printf("number of file = %d\n", numFile);
					
					// total authors
					if(numFile){
						vector<string>author=getFileAuthor();
						writeRecv(connfd, SUCCESS, strlen(SUCCESS));
						string str=toString((int)author.size());
						// how many author
						write(connfd, str.c_str(), str.length());
						// to user A
						recvWrite(connfd, recvline);// tell B connect to "port"
						// to user A
						User userA=accountUser[currentUser];
						for(int i=0;i<author.size();i++){
							cout<<author[i]<<endl;

							
							User userB=accountUser[Account(author[i])];
							
							// user B
							str=string(DOWNLOAD)+" "+userA.IP+" "+recvline+" "+tok[1]+" "+toString(i)+" "+toString((int)author.size());
							write(userB.connfd, str.c_str(), str.length());// tell B :(A's) IP port path idx total

						}

						// update filelist
						puts("update filelist");
						addFile(currentUser.ID, tok[1]);
					}
					else{
						write(connfd, FAIL, strlen(FAIL));
					}
					


				}
				else if(tok[0]=="U"){// upload
					writeRecv(connfd, recvline, strlen(recvline));// send to client
					if(accountUser.find(Account(tok[1]))!=accountUser.end()){
						// to user A
						write(connfd, SUCCESS, strlen(SUCCESS));
						User userA=accountUser[currentUser];
						User userB=accountUser[Account(tok[1])];
						string str;
						// to user A
						recvWrite(connfd, recvline);// tell B connect to "port"
						// user B
						str=string(UPLOAD)+" "+userA.IP+" "+recvline+" "+tok[2];
						write(userB.connfd, str.c_str(), str.length());// tell B :(A's) IP port

						// update B's filelist
						addFile(tok[1], tok[2]);
					}
					else{
						write(connfd, FAIL, strlen(FAIL));
					}
					
				}
				//------------------------------------------------
				else if(tok[0]=="T"){// A tell B
					writeRecv(connfd, recvline, strlen(recvline));// send to client
					if(accountUser.find(Account(tok[1]))!=accountUser.end()){
						currentUser.state=Tell;
						userAccount[User(getIP(cliaddr), getPort(cliaddr), cliaddr, connfd)]=currentUser;
						// to user A
						write(connfd, SUCCESS, strlen(SUCCESS));
						User userA=accountUser[currentUser];
						User userB=accountUser[Account(tok[1])];
						Account accountB=userAccount[userB];
						accountB.state=Tell;
						userAccount[userB]=accountB;
						
						string str;
						// to user A
						recvWrite(connfd, recvline);// tell B connect to "port"
						// user B
						printf("user B connfd = %d\n", userB.connfd);
						str=string(TALK)+" "+userA.IP+" "+recvline;
						// write(userB.connfd, TALK, strlen(TALK));
						
						
						write(userB.connfd, str.c_str(), str.length());// tell B :(A's) IP port

						// string str=userB.IP+" "+toString(userB.port);
						// writeWithSleep(connfd, str.c_str(), str.length());

					}
					else{
						write(connfd, FAIL, strlen(FAIL));
					}
					
				}
			
			}
			else if(currentUser.state==Tell){
				if(tok[0]=="EXIT"){
					printf("%s EXIT~\n", currentUser.ID.c_str());
					currentUser.state=Normal;
					userAccount[User(getIP(cliaddr), getPort(cliaddr), cliaddr, connfd)]=currentUser;
				}
				else{
					printf("%s tell~\n", currentUser.ID.c_str());
				}
			}		
		}
		puts(recvline);
		
		
		// write(connfd, recvline, strlen(recvline));
	}
	close(connfd);

	return NULL;
}
예제 #11
0
int phoneOperatorUserInfo(struct bufferevent *bev, client_t *client, char *packet, int length) {
	char u8PhoneId[LEN_PHONE_ID*2+1] = {0};
	char u8UserName[LEN_PHONE_USERNAME+1] = {0};
	//phone id hex to string				
	hextostring(u8PhoneId ,packet+IDX_PHONE_ID, LEN_PHONE_ID);
	memcpy(u8UserName, packet+IDX_PHONE_USERNAME, LEN_PHONE_USERNAME);
			
	switch (packet[IDX_PHONE_COMMAND]) {
		case CMD_PHONE_REGISTER_USER: {
			int u32UserId = 0;
			char u8Password[LEN_PHONE_PASSWORD+1] = {0};
			char retBuf[LEN_DEVICE_RETURN_BUFFER*2] = {0};
			retBuf[0] = 'R';
			retBuf[1] = 'E';
			retBuf[2] = 'T';
			retBuf[3] = 'O';
			retBuf[4] = 'K';
			retBuf[5] = ':';
			
			memcpy(u8Password, packet+IDX_PHONE_PASSWORD, LEN_PHONE_PASSWORD);
			
			if (OK == insertUser(u8UserName, u8Password)) {
				//return userid			
				if (OK == selectUserId(u8UserName, u8Password, &u32UserId)) {					
					memcpy(retBuf+IDX_PHONE_RETURN_USERID, &u32UserId, LEN_PHONE_ID);
					apolloReturnPacket(bev, client, retBuf, LEN_DEVICE_RETURN_BUFFER*2);
				} else {					
					retBuf[3] = 'N';
					retBuf[4] = 'O';
					retBuf[IDX_PHONE_RETURN_USERID] = RET_PHONE_GETUSERID_FAILED;
					apolloReturnPacket(bev, client, retBuf, LEN_DEVICE_RETURN_BUFFER*2);
				}
			} else {
				//return sign in failed
				retBuf[3] = 'N';
				retBuf[4] = 'O';
				retBuf[IDX_PHONE_RETURN_USERID] = RET_PHONE_SIGNIN_FAILED;
				apolloReturnPacket(bev, client, retBuf, LEN_DEVICE_RETURN_BUFFER*2);
			}
			break;
		}
		case CMD_PHONE_SIGNIN_USER: {
			int u32UserId = 0;
			char u8Password[LEN_PHONE_PASSWORD+1] = {0};
			char retBuf[LEN_DEVICE_RETURN_BUFFER*2] = {0};
			retBuf[0] = 'R';
			retBuf[1] = 'E';
			retBuf[2] = 'T';
			retBuf[3] = 'O';
			retBuf[4] = 'K';
			retBuf[5] = ':';

			memcpy(u8Password, packet+IDX_PHONE_PASSWORD, LEN_PHONE_PASSWORD);
			if (OK == selectUserId(u8UserName, u8Password, &u32UserId)) {					
				memcpy(retBuf+IDX_PHONE_RETURN_USERID, &u32UserId, LEN_PHONE_ID);
				apolloReturnPacket(bev, client, retBuf, LEN_DEVICE_RETURN_BUFFER*2);
			} else {					
				retBuf[3] = 'N';
				retBuf[4] = 'O';
				retBuf[IDX_PHONE_RETURN_USERID] = RET_PHONE_USERID_NOEXIST;
				apolloReturnPacket(bev, client, retBuf, LEN_DEVICE_RETURN_BUFFER*2);
			}
			
			break;
		}
		case CMD_PHONE_UPDATE_PWD: {
			char u8Password[LEN_PHONE_PASSWORD+1] = {0};
			char retBuf[LEN_DEVICE_RETURN_BUFFER*2] = {0};
			retBuf[0] = 'R';
			retBuf[1] = 'E';
			retBuf[2] = 'T';
			retBuf[3] = 'O';
			retBuf[4] = 'K';
			retBuf[5] = ':';

			memcpy(u8Password, packet+IDX_PHONE_PASSWORD, LEN_PHONE_PASSWORD);

			if (OK == updatePassword(u8Password, u8UserName)) {	
				retBuf[IDX_PHONE_RETURN_USERID] = RET_PHONE_SUCCESS;
				apolloReturnPacket(bev, client, retBuf, LEN_DEVICE_RETURN_BUFFER*2);
			} else {					
				retBuf[3] = 'N';
				retBuf[4] = 'O';
				retBuf[IDX_PHONE_RETURN_USERID] = RET_PHONE_UPDATE_PWD_FAILED;
				apolloReturnPacket(bev, client, retBuf, LEN_DEVICE_RETURN_BUFFER*2);
			}
			
			break;
		}
		case CMD_PHONE_BIND_DEVICE: {
			break;
		}
		case CMD_PHONE_UNBIND_DEVICE: {
			//delete mysql

			//delete redis key
			break;
		}
	}
	return 0;
}
예제 #12
0
파일: server.c 프로젝트: correiajoao/chat
int main(){
	pid_t pid;
	int fluxo, msgKind;
	char userName[50];
	char *bufferRcv, *_bufferRcv, *msgContent;	
	
	struct userList _users;
	struct messageList _messages;
	
	int localSocket,remoteSocket,structSize;
	struct sockaddr_in local;
	struct sockaddr_in remote;
		
	//Inicio da execução
	
	system("clear");
	//Apagando todos os dados de seções passadas
	deleteFile();
	//Criando diretórios necessários
	makeDirectory();
	//Mensagem de inicio
	printf("Servidor iniciado\n");
	
	//Configurações do socket local
	//Mais detalhes consulte as manpages
	localSocket = socket(AF_INET, SOCK_STREAM, 0);
	if(localSocket == -1)
		errorSocket();
		
	//Configuração do socket local
	//Mais detalhes consulte as manpages
	local.sin_family = AF_INET; 
	local.sin_port = htons(31337);  	
	local.sin_addr.s_addr = INADDR_ANY;
	memset(local.sin_zero,0,8);

	//Associação da porta
	if(bind(localSocket, (struct sockaddr *)&local, sizeof(local)) == -1)
		errorBind();
	
	//Inicio da escuta
	if(listen (localSocket, BACKLOG) == -1)
		errorListen();
	
	structSize = sizeof(struct sockaddr_in);
	
	while(1){
		//Agurda um processo conectars-se
		remoteSocket = accept(localSocket, (struct sockaddr *)&remote, &structSize);
		
		//Após a conxão ser aceita, o processo servidor é duplicado
		pid = fork();
		if(pid == 0){
			
				//Alocação de memória necessária
				bufferRcv = (char*) calloc (MAXALLOC, sizeof(char));
				_bufferRcv = (char*) calloc (MAXALLOC, sizeof(char));	
				msgContent = (char*) calloc (MAXALLOC, sizeof(char));			
			
				fluxo = 0;
				while(!fluxo){	
					recv(remoteSocket, bufferRcv, MAXDATASIZE,  0);
					strcpy(_bufferRcv, bufferRcv);
					
					//Após a conexão de um cliente, a primeira mensagem que o servidor espera é do tipo USERNAME,
					//caso contrário o processo servidor é finalizado
					if(checkKindMessage(_bufferRcv,1) == USERNAME){
						//Resgata o conteudo da mensagem
						strcpy(_bufferRcv, bufferRcv);  		
						msgContent = checkMessage(_bufferRcv);
						
						//Verifica se o userName é válido
						if(!checkUserName(msgContent)){
							
								//Se o userName é válido o servidor guarda esse nome para o processo corrente identificar a qual usuário está associado
								strcpy(userName,msgContent);
							
								//Insere o usuário na lista de usuários ativos passando como parâmetros o seu nome e endereço
								insertUser(msgContent,inet_ntoa(remote.sin_addr));
								
								//Informa ao cliente que ele foi conectado		   
								send(remoteSocket,generateMessage("",CONNECTED,1),MAXDATASIZE,0);	
								fluxo = 1;
							}else{
							
								//Sinaliza que o nome de usuário é inválido
								send(remoteSocket,generateMessage("",INVALIDUSERNAME,1),MAXDATASIZE,0);
								fluxo = 0;
							}
					}else{
						close(remoteSocket);
						return 0;
					}
				}
			
			fluxo = 0;	
			while(!fluxo){
				
				//Recebe uma mensagem e guarda o estado de atividade do cliente
				int isActive = recv(remoteSocket, bufferRcv, MAXDATASIZE,  0);
				strcpy(_bufferRcv, bufferRcv); 		
				
				//Verifica o tipo da mensagem
				msgKind = checkKindMessage(_bufferRcv,1);
				strcpy(_bufferRcv, bufferRcv);  		
				msgContent = checkMessage(_bufferRcv);
				
				//Se o estado de conexão é ativo
				if(isActive){
					//Trata as mensagem de acordo com o seu tipo
					switch(msgKind){
						//ACTIVEUSERS: O servidor envia para o cliente a lista de usuários ativos
						case ACTIVEUSERS:{
							int i = 0;
							_users = checkActiveUsers();	
							for(i=0;i<_users.size;i++){
								send(remoteSocket,generateMessage(_users.name[i],USERNAME,1),MAXDATASIZE,0);
							}
							send(remoteSocket,generateMessage("",FINISHED,1),MAXDATASIZE,0);
							break;
						}
						//MESSAGECHAT: O servidor armazena a mensagem enviada pelo cliente	
						case MESSAGECHAT:{
							putMessageChatInLog(userName, msgContent);
							break;
						//UPDATECHAT: O servidor retorna as mensagens direcionadas ao cliente 	
						}case UPDATECHAT:{
							int i = 0;
							_messages = checkLog(userName);
							for(i=0;i<_messages.size;i++){
								send(remoteSocket,generateMessage(_messages.content[i],MESSAGECHAT,1),MAXDATASIZE,0);
							}
							send(remoteSocket,generateMessage("",FINISHED,1),MAXDATASIZE,0);
							break;
						//CLOSE: O servidor fecha a conexão 	
						}case CLOSE:{
							removeUser(userName);
							deleteUserFiles(userName);
							close(remoteSocket);
							
							free(bufferRcv);
							free(_bufferRcv);
							free(msgContent);
							return 0;
						}
					
					}
				}else{
					removeUser(userName);
					deleteUserFiles(userName);
					close(remoteSocket);
					break;
				}
				
				
			}
			
		free(bufferRcv);
		free(_bufferRcv);
		free(msgContent);	
		break;
		}		
	}
	
	return 0;
}
예제 #13
0
/* Remove a user from their current room and move them to lobby */
void leave(packet *pkt, int fd) {
   int i = 0, roomNum;
   char *args[16];
   char *tmp = pkt->buf;
   packet ret;

   // Split command args
   args[i] = strsep(&tmp, " \t");
   while ((i < sizeof(args) - 1) && (args[i] != '\0')) {
      args[++i] = strsep(&tmp, " \t");
   }
   if (i > 1) {
      roomNum = atoi(args[1]);
      // If user is not in the lobby
      if (roomNum != DEFAULT_ROOM) {
         // Get current room information
         Room *currRoom = Rget_roomFID(&room_list, roomNum, rooms_mutex);
         if (currRoom != NULL) {
            // Find users node in room
            User *currUser = get_user(&(currRoom->user_list), pkt->username, currRoom->user_list_mutex);
            if (currUser != NULL) {
               // Remove user from their current room
               removeUser(&(currRoom->user_list), currUser, currRoom->user_list_mutex);

               //Create node to add user back to lobby
               Node *new_node = (Node *)malloc(sizeof(Node));
               new_node->data = currUser;

               // Place user in lobby room
               Room *defaultRoom = Rget_roomFID(&room_list, DEFAULT_ROOM, rooms_mutex);
               currUser->roomID = 1000;
               insertUser(&(defaultRoom->user_list), currUser, defaultRoom->user_list_mutex);

               // Send user leave message to room
               ret.options = roomNum;
               strcpy(ret.realname, SERVER_NAME);
               strcpy(ret.username, SERVER_NAME);
               strncpy(ret.buf, currUser->real_name, sizeof(currUser->real_name));
               strcat(ret.buf, " has left the room.");
               ret.timestamp = time(NULL);
               send_message(&ret, -1);
               memset(&ret, 0, sizeof(ret));

               // Send join success to client
               ret.options = JOINSUC;
               strcpy(ret.realname, SERVER_NAME);
               strcpy(ret.username, SERVER_NAME);
               sprintf(ret.buf, "%s %d", defaultRoom->name, defaultRoom->ID);
               strcat(ret.buf, " has joined the room.");
               ret.timestamp = time(NULL);
               send(fd, (void *)&ret, sizeof(packet), MSG_NOSIGNAL);
               memset(&ret, 0, sizeof(ret));

               // Send join notification to lobby room
               ret.options = defaultRoom->ID;
               strcpy(ret.realname, SERVER_NAME);
               strcpy(ret.username, SERVER_NAME);
               strncpy(ret.buf, currUser->real_name, sizeof(currUser->real_name));
               strcat(ret.buf, " has joined the room.");
               ret.timestamp = time(NULL);
               send_message(&ret, -1);
            }
         }
      }
   }
}
예제 #14
0
/*
 *Join a chat room
 */
void join(packet *pkt, int fd) {
   int i = 0;
   char *args[16];
   char *tmp = pkt->buf;
   packet ret;

   // Split command args
   args[i] = strsep(&tmp, " \t");
   while ((i < sizeof(args) - 1) && (args[i] != '\0')) {
      args[++i] = strsep(&tmp, " \t");
   }
   if (i > 1 && validRoomname(args[0], fd)) {
      // check if room exists
      printf("Checking if room exists . . .\n");
      if (Rget_ID(&room_list, args[0], rooms_mutex) == -1) {
         // create if it does not exist
         createRoom(&room_list, numRooms, args[0], rooms_mutex);
      }
      RprintList(&room_list, rooms_mutex);
      printf("Receiving room node for requested room.\n");
      Room *newRoom = Rget_roomFNAME(&room_list, args[0], rooms_mutex);

      int currRoomNum = atoi(args[1]);
      // Should check if current room exists
      printf("Receiving room node for users current room.\n");
      Room *currentRoom = Rget_roomFID(&room_list, currRoomNum, rooms_mutex);//pkt->options);
      printf("Getting user node from current room user list.\n");
      if(currentRoom == NULL) {
         printf("Could not remove user: current room is NULL\n");
      }
      else {
         User *currUser = get_user(&(currentRoom->user_list), pkt->username, currentRoom->user_list_mutex);
         printf("Removing user from his current rooms user list\n");
         removeUser(&(currentRoom->user_list), currUser, currentRoom->user_list_mutex);
         printf("User removed from current room\n");
         
         //Create node to add user to other room list.
         Node *new_node = (Node *)malloc(sizeof(Node));
         new_node->data = currUser;
         currUser->roomID = newRoom->ID;
         printf("Inserting user into new rooms user list\n");
         insertUser(&(newRoom->user_list), currUser, newRoom->user_list_mutex);

         RprintList(&room_list, rooms_mutex);

         ret.options = JOINSUC;
         strcpy(ret.realname, SERVER_NAME);
         strcpy(ret.username, SERVER_NAME);
         ret.timestamp = time(NULL);
         sprintf(ret.buf, "%s %d", args[0], newRoom->ID);
         send(fd, (void *)&ret, sizeof(packet), MSG_NOSIGNAL);
         memset(&ret, 0, sizeof(ret));

         ret.options = currRoomNum;
         strcpy(ret.realname, SERVER_NAME);
         strcpy(ret.username, SERVER_NAME);
         strncpy(ret.buf, currUser->real_name, sizeof(currUser->real_name));
         strcat(ret.buf, " has left the room.");
         ret.timestamp = time(NULL);
         send_message(&ret, -1);
         memset(&ret, 0, sizeof(ret));

         ret.options = newRoom->ID;
         strcpy(ret.realname, SERVER_NAME);
         strcpy(ret.username, SERVER_NAME);
         strncpy(ret.buf, currUser->real_name, sizeof(currUser->real_name));
         strcat(ret.buf, " has joined the room.");
         ret.timestamp = time(NULL);
         send_message(&ret, -1);
      }
   }
   else {
      printf("Problem in join.\n");
      sendError("We were unable to put you in that room, sorry.", fd);
   }
}
예제 #15
0
/*
 *Login
 */
int login(packet *pkt, int fd) {
   int i = 0;
   char *args[16];
   char cpy[BUFFERSIZE];
   char *tmp = cpy;
   unsigned char *arg_pass_hash = (unsigned char *)malloc(SHA256_DIGEST);
   strcpy(tmp, pkt->buf);

   args[i] = strsep(&tmp, " \t");
   while ((i < sizeof(args) - 1) && (args[i] != '\0')) {
       args[++i] = strsep(&tmp, " \t");
   }
   // Check there are enough arguements to safely inspect them
   if (i > 2) {
      packet ret;
      // Check if user exists as registered user
      if (strcmp(get_real_name(&registered_users_list, args[1], registered_users_mutex), "ERROR") == 0) {
         sendError("Username not found.", fd);
         return 0;
      }
      // Retreive password for requested user
      unsigned char *password = get_password(&registered_users_list, args[1], registered_users_mutex);
      // Hash login password arg
      SHA256_CTX sha256;
      SHA256_Init(&sha256);
      SHA256_Update(&sha256, args[2], strlen(args[2]));
      SHA256_Final(arg_pass_hash, &sha256);

      // Compare pass arg and stored pass
      if (comparePasswords(password, arg_pass_hash, 32) != 0) {
         sendError("Incorrect password.", fd);
         free(arg_pass_hash);
         return 0;
      }
      free(arg_pass_hash);

      // Login input is valid, read user data from registered users
      User *user = get_user(&registered_users_list, args[1], registered_users_mutex);

      //Create node for active users list
      Node *new_usr_act = (Node *)malloc(sizeof(Node));
      new_usr_act->data = (void *)user;
      new_usr_act->next = NULL;

      //Create node for room list
      Node *new_usr_rm = (Node *)malloc(sizeof(Node));
      new_usr_rm->data = (void *)user;
      new_usr_rm->next = NULL;

      // Check if the user is already logged in
      if(insertUser(&active_users_list, user, active_users_mutex) == 1) {
         user->sock = fd;
         user->roomID = 1000;

         // Login successful, add user to default room
         Room *defaultRoom = Rget_roomFID(&room_list, DEFAULT_ROOM, rooms_mutex);
         insertNode(&(defaultRoom->user_list), new_usr_rm, defaultRoom->user_list_mutex);

         // Inform client of successful login
         strcpy(ret.realname, get_real_name(&registered_users_list, args[1], registered_users_mutex));
         strcpy(ret.username, args[1]);
         ret.options = LOGSUC;
         //printf("%s logged in\n", ret.username);
         ret.timestamp = time(NULL);
         send(fd, &ret, sizeof(packet), MSG_NOSIGNAL);

         // Inform lobby of successful login
         memset(&ret, 0, sizeof(packet));
         ret.options = DEFAULT_ROOM;
         strcpy(ret.realname, SERVER_NAME);
         strcpy(ret.username, SERVER_NAME);
         sprintf(ret.buf, "%s has joined the lobby.", user->real_name);
         ret.timestamp = time(NULL);
         send_message(&ret, -1);

         // Send MOTD to client
         sendMOTD(fd);
         return 1;
      }
      // Valid login data received, but user is already in active users
      else {
         sendError("User already logged in.", fd);
         printf("%s log in failed: already logged in", args[1]);
         free(user);
         return 0;
      }
   }
   // Not enough arguements received to properly parse input, ignore it
   else {
      printf("%s --- %sError:%s Malformed login packet received from %s on %d, ignoring.\n", \
             WHITE, RED, NORMAL, args[1], fd);
   }
   return 0;
}