Example #1
0
void DialogUsers::on_tableWidget_customContextMenuRequested(const QPoint &pos)
{
    QTableWidgetItem *q = ui->tableWidget->itemAt(pos);
    if ( q == NULL ) return;
    ui->tableWidget->selectRow(q->row()); // fix bug with quick right click

    contextTableMenu->actions().at(2)->setEnabled( ( QVariant(ui->tableWidget->item(q->row(),0)->data(DataRole::deleted)).toInt() == 0 )
                                                   and Act::userPermission(Act::editDirection,currentUserRights));
    contextTableMenu->actions().at(4)->setEnabled( ( QVariant(ui->tableWidget->item(q->row(),0)->data(DataRole::deleted)).toInt() == 1 )
                                                   and Act::userPermission(Act::editDirection,currentUserRights));

    QAction* selectedItem = contextTableMenu->exec(QCursor::pos());
    if ( !selectedItem ) return;
    if ( selectedItem->text() == "Добавить")
    {
        addNewUser();
    } else if ( selectedItem->text() == "Править")
    {
        ui->tableWidget->setCurrentCell(q->row(),q->column());
        editUser();
    } else if ( selectedItem->text() == "Удалить")
    {
        ui->tableWidget->setCurrentCell(q->row(),q->column());
        deleteUser();
    } else if ( selectedItem->text() == "Восстановить")
    {
        ui->tableWidget->setCurrentCell(q->row(),q->column());
        restoreUser();
    }
}
Example #2
0
void Gource::updateUsers(float t, float dt) {
    std::vector<RUser*> inactiveUsers;

    int idle_users = 0;

    //recalc the user bounds
    user_bounds.reset();

    // move users
    for(std::map<std::string,RUser*>::iterator it = users.begin(); it!=users.end(); it++) {
        RUser* u = it->second;

        u->logic(t, dt);

        //deselect user if fading out from inactivity
        if(u->isFading() && selectedUser == u) {
            selectUser(0);
        }

        if(u->isInactive()) {
            inactiveUsers.push_back(u);
        }

        if(u->isIdle()) {
            idle_users++;
        } else {
            user_bounds.update(u->getPos());

            //if nothing is selected, and this user is active and this user is the specified user to follow, select them
            if(selectedUser == 0 && selectedFile == 0) {
                for(std::vector<std::string>::iterator ui = follow_users.begin(); ui != follow_users.end(); ui++) {
                    std::string follow = *ui;

                    if(follow.size() && u->getName() == follow) {
                        selectUser(u);
                    }
                }
            }
        }
    }

    //nothing is moving so increment idle
    if(idle_users==users.size()) {
        idle_time += dt;

        //if stop_on_idle is set and either no stop condition is set or the condition has been reached, exit
        if(stop_on_idle && (stop_position == 0.0f && !stop_at_end || stop_position_reached)) appFinished = true;

    } else {
        idle_time = 0;
    }

    // delete inactive users
    for(std::vector<RUser*>::iterator it = inactiveUsers.begin(); it != inactiveUsers.end(); it++) {
        deleteUser(*it);
    }
}
Example #3
0
void CGameWorld::processUser()
{
	short cmdId;
	CG_TCPSession *session;
	map<long,CUser*>::iterator it;
	CUser *user;
	vector<long> vDeadUser;
	for(it=m_oUsers.begin();it!=m_oUsers.end();)
	{
		user    = it->second;
		GIVER() = user;//user->m_dummy;//(CS_RegionCreature*)
		session = user->m_session;
		if(session)
		{
			session->DefProc();
			//check dead
			if(session->IsDead()/* || GIVER()->m_bClose*/) 
			{
				//user->m_session = NULL;
				user->m_netDeadTime = m_iTime;

				if(session->GetState() == NET_STATE_DEAD)
					CORE("User Disconnect:", "userid=%d",user->getUserId());

				//deleteUser(user->getUserId());
				vDeadUser.push_back(user->getUserId());
				//_DELETE(session);
				//continue;
			}
			else
			{
				bool bQuit = false;
				while(session->GetPacket(m_activeCmd)) 
				{	
					if(!m_activeCmd->ReadShort(&cmdId))
						break;
					m_channelLogin.RecvCmd(cmdId);
				}
				if(session->GetState() == NET_STATE_ERROR)
					CORE("Unknown package format", "%d",user->getUserId());
			}
		}
		it++;
	}

	//ÊͷŵôÏßµÄ
	for (int i=0;i<(int)vDeadUser.size();i++)
	{
		long userid = vDeadUser[i];
		if (userid>0)
		{
			deleteUser(userid);
			CORE("delete user:"******"userid=%d",userid);
		}
	}
}
void searchMain(UserInfo userInfo[], int todo, char mess[], char top[])
{
	int input, menu = 1, num;
	int *ptr = &menu;
	char *menu_num2[MENU_NUM] = {
		{ "1. 회원ID로 검색" },
		{ "2. 이름으로 검색" },
		{ "3. 연락처로 검색" }
	};

	while (1) {
		topMessage(mess, top);
		messageBoxB("검색  ", "방법");
		menuSelectB(menu, 3, menu_num2);
		bottomMessageC();

		input = getch();

		if (input == ARROW_BUFFER)
			input = getch();

		switch (input)
		{
		case UP_ARROW_KEY:
			moveSound();
			if (menu > 1) menu--;
			break;
		case DOWN_ARROW_KEY:
			moveSound();
			if (menu < 3) menu++;
			break;
		case ENTER_KEY:
			inSound();
			num = searchUser(userInfo, menu);

			if (num){
				if (todo == _DELETE)
					deleteUser(userInfo, num);
				else if (todo == MODIFY)
					modifyUser(userInfo, num);
				else
					searchResult(userInfo, num);
			}
			break;
		case ESC_KEY:
			outSound();
			return;
		default:
			warningMessage(input - '0', 3, ptr);
			break;
		}
	}
}
Example #5
0
RegistrationApp::RegistrationApp(QWidget* parent) :
	m_team_table_wnd( new Ui::team_table_wnd ),
	m_user_table_wnd(new Ui::user_table_wnd),
	m_user_edit_wnd(new Ui::user_edit_wnd),
	m_sql(SqlUtil::getInstance())
{
	bool ok;
	QString text = QInputDialog::getText(this, tr("Database Directory"),
										  tr("Database Path:"), QLineEdit::Normal,
										  QDir::home().dirName(), &ok);
	if (!text.isEmpty())
		 m_sql.init(text);
	this->hide();
	m_team_table_w = new QDialog(this);
	m_team_table_wnd->setupUi(m_team_table_w);
	m_team_table_w->show();

	m_user_table_w = new QDialog(this);
	m_user_table_wnd->setupUi(m_user_table_w);
	m_user_table_w->hide();

	m_user_edit_w = new QDialog(this);
	m_user_edit_wnd->setupUi(m_user_edit_w);
	m_user_edit_w->hide();
	//network?

	//connecting stuff

	//connections for the buttons

	//team table
	connect(m_team_table_wnd->add_team_btn, SIGNAL(clicked()), this, SLOT(addTeam()));
	connect(m_team_table_wnd->team_edit_btn, SIGNAL(clicked()), this, SLOT(goToEditTeam()));
	connect(m_team_table_wnd->team_delete_btn, SIGNAL(clicked()), this, SLOT(deleteTeam()));

	//user table
	connect(m_user_table_wnd->edit_school_btn, SIGNAL(clicked()), this, SLOT(editTeamSchool()));
	connect(m_user_table_wnd->add_user_btn, SIGNAL(clicked()), this, SLOT(addUser()));
	connect(m_user_table_wnd->edit_user_btn, SIGNAL(clicked()), this, SLOT(editUser()));
	connect(m_user_table_wnd->delete_user_btn, SIGNAL(clicked()), this, SLOT(deleteUser()));
	connect(m_user_table_wnd->backtoteams_btn, SIGNAL(clicked()), this, SLOT(backToTeam()));

	//user edit
	connect(m_user_edit_wnd->save_userchange_btn, SIGNAL(clicked()), this, SLOT(saveUserEdit()));
	connect(m_user_edit_wnd->backtouser_btn, SIGNAL(clicked()), this, SLOT(backToUser()));

	bool result = SqlUtil::getInstance().init ( text );
		if ( !result ) {
				QMessageBox msg ( this );
				msg.setText ( "Failed to load database" );
				msg.exec();
		}
}
Example #6
0
void Gource::updateUsers(float t, float dt) {
    std::vector<RUser*> inactiveUsers;

    int idle_users = 0;

    //recalc the user bounds
    user_bounds.reset();

    // move users
    for(std::map<std::string,RUser*>::iterator it = users.begin(); it!=users.end(); it++) {
        RUser* u = it->second;

        u->logic(t, dt);

        //deselect user if fading out from inactivity
        if(u->isFading() && selectedUser == u) {
            selectUser(0);
        }

        if(u->isInactive()) {
            inactiveUsers.push_back(u);
        }

        if(u->isIdle()) {
            idle_users++;
        } else {
            user_bounds.update(u->getPos());

            //if nothing is selected, and this user is active and this user is the specified user to follow, select them
            if(selectedUser == 0 && selectedFile == 0) {
                for(std::vector<std::string>::iterator ui = follow_users.begin(); ui != follow_users.end(); ui++) {
                    std::string follow = *ui;

                    if(follow.size() && u->getName() == follow) {
                        selectUser(u);
                    }
                }
            }
        }
    }

    //nothing is moving so increment idle
    if(idle_users==static_cast<int>(users.size())) {
        idle_time += dt;
    } else {
        idle_time = 0.0f;
    }

    // delete inactive users
    for(std::vector<RUser*>::iterator it = inactiveUsers.begin(); it != inactiveUsers.end(); it++) {
        deleteUser(*it);
    }
}
Example #7
0
void clientFree(cli *client){
    serv *server = client->server;
    decrementServerConnections(server);
    if(!(client->nick && client->user)){
        deleteUser(client);
    }
    close(client->socket);
    bdestroy(client->nick);
    bdestroy(client->user);
    bdestroy(client->fullName);
    bdestroy(client->hostName);
    pthread_mutex_destroy(client->clientLock);
    free(client);
}
Example #8
0
void AdminMainWidget::populateList(const QVector<LinQedInUser>& results) const{
    users->clear();
    int height=0;
    foreach(LinQedInUser user,results){
        QListWidgetItem* item=new QListWidgetItem;
        BasicUserViewer* buv=new BasicUserViewer(user,dynamic_cast<QWidget*>(parent()));
        connect(buv,SIGNAL(deleteRequest(QString)),this,SLOT(deleteUser(QString)));
        connect(buv,SIGNAL(changePlanRequest(const QString&,int)),this,SLOT(changePlan(const QString&,int)));
        item->setSizeHint(buv->size());
        buv->setStyleSheet("BasicUserViewer{border-bottom:2px solid black;}");
        users->addItem(item);
        users->setItemWidget(item,buv);
        height+=buv->height();
    }//foreach
UsersManagerDialog::UsersManagerDialog(UserContainer* userContainer, UserDbInterface *userDb, QWidget *parent):QDialog(parent),
    ui(new Ui::UsersManager)
{
    this->userContainer = userContainer;
    this->userDb = userDb;

    ui->setupUi(this);
    this->setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint);
    this->setWindowIcon(QIcon(":/icons/avatar.png"));

    QObject::connect(ui->addBtn,SIGNAL(clicked()),this,SLOT(addUser()));
    QObject::connect(ui->userName,SIGNAL(returnPressed()),this,SLOT(addUser()));
    QObject::connect(ui->deleteBtn,SIGNAL(clicked()),this,SLOT(deleteUser()));
    QObject::connect(this,SIGNAL(rejected()),this,SLOT(dialogClosed()));

    updated = false;
}
NResponse & NTcpServerSocketUserServices::user(const NClientSession & session, NResponse & response)
{
    if (session.request().method() == "POST") {
        return postUser(session, response);
    }

    if (session.request().method() == "PUT") {
        return putUser(session, response);
    }

    if (session.request().method() == "GET") {
        return getUser(session, response);
    }

    if (session.request().method() == "DELETE") {
        return deleteUser(session, response);
    }

    Q_ASSERT(false);
    return response;
}
Example #11
0
int main()
{
	char strUsrName[1024] = {0};
	char strFlag[10] = {0};
	void *zdbhandle = NULL;
	char *userID = NULL;
	int retVal = 0;

	prepareParameter(strUsrName, strFlag);
	if(strlen(strUsrName)==0||strlen(strFlag)==0) {
		response(1, NULL, NULL, NULL);
		return -1;
	}
	
	if(ZDBOpen(Z_UTIL_ZQDEV,DBfile,&zdbhandle) != Z_SUCCESS){
        	fprintf(stderr,"open db error\n");
		response(1, NULL, NULL, NULL);
        	return 0;
    	}

	//090609, JC, add/remove device notification
	if (ZOnlineGetUser(strUsrName, atoi(strFlag), &userID, NULL, NULL, NULL, NULL) < 0) {
		response(1, NULL, NULL, NULL);
        	return 0;
	}

	if ((retVal=deleteUser(zdbhandle,strUsrName,strFlag)) != 0) {
		response(1, NULL, NULL, NULL);
	} else {
		response(0, strUsrName, userID, strFlag);
	}
	//end add/remove device notification

	ZDBClose(zdbhandle);
	free(userID);
	return 0;
}
Example #12
0
UserDialog::UserDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::UserDialog)
{
    ui->setupUi(this);
    //reposition of the widgets
    ui->gridLayout->addWidget(ui->usersLabel, 0, 0, 1, 3);
    ui->gridLayout->addWidget(ui->userName, 1, 1, 1, 3);
    ui->gridLayout->addWidget(ui->cancelButton, 3, 1);
    ui->gridLayout->addWidget(ui->deleteButton, 3, 2);
    ui->gridLayout->addWidget(ui->addButton, 3, 3);
    ui->gridLayout->addWidget(ui->errorLabel,2,0,1,3);

    QSqlQuery query;
    query.exec ("SELECT user FROM user;");
    QString users = QString("Usuarios: ");
    while(query.next())
    {
        users = users + query.value(0).toString() + QString(", ");
    }
    ui->usersLabel->setText(users);

    this->connect(ui->deleteButton, SIGNAL(clicked()), SLOT(deleteUser()));
}
Example #13
0
File: server.c Project: Vuzi/SFSS
/* Programme principal serveur */
void startServer(void) {

    /* Socket du serveur */
    SOCKET sock = startConnection(); /* Fonction de lancement du serveur, ici le serveur passe en écoute */
    int max = sock;

    /* Liste des différents comptes */
    Account *accounts = NULL;

    User *users = NULL;
    User *u_cursor = NULL, *tmp = NULL;

    /* Descripteur */
    fd_set rdfs;

    bool quit = false;


    /* A ajouter : commande permettant de quitter §§§ */
    while(!quit) {

        /* On vide le descripteur */
		FD_ZERO(&rdfs);

		/* On ajoute le socket du serveur */
		FD_SET((u_int)sock, &rdfs);

        u_cursor = getFirstUser(users);

        /* On ajoute le socket de chaque User */
        while(u_cursor) {
            FD_SET((u_int)(u_cursor->sock), &rdfs);
            u_cursor = u_cursor->next;
        }

		/* On effectue le select pour lier le descripteur à la lecture sur le socket */
		if(select(max+1, &rdfs, NULL, NULL, NULL) == SOCKET_ERROR) {
            sock_error("select()");
		} else {
			/* Ici on attends un changement d'un des descripteurs */

			/* Si c'est un nouveau client qui effectue une connexion */
			if(FD_ISSET(sock, &rdfs)) {

				HERROR_WRITE(HERROR_DEBUG, "[Serveur] Nouveau client detecte");

				/* Variables du nouveau client */
				SOCKADDR_IN csin;
				size_t sinsize = sizeof csin;

				/* Socket du nouveau client */
				int csock = accept(sock, (SOCKADDR *)&csin, (socklen_t *)&sinsize);

				/* Si erreur */
				if(csock == SOCKET_ERROR)
                    sock_error("accept()");

				/* On ajoute le client en attente de connexion */
				users = addUser(users, (SOCKET)csock, copy(inet_ntoa(csin.sin_addr)));

				/* Nouveau max : */
				max = csock > max ? csock : max;

				HERROR_WRITE(HERROR_INFO, "[Serveur] Nouveau client ajoute ( ip '%s')", users->ip);
			}
			/* Sinon c'est un client qui effectue une action */
			else {
                u_cursor = getFirstUser(users);

				/* Pour chaque Uset */
                while(u_cursor) {
                    /* S'il a envoyé des données */
                    if(FD_ISSET(u_cursor->sock, &rdfs)){

                        if(u_cursor->state == WAITING_MSG || u_cursor->state == WAITING_END_MSG) {
                            if(u_cursor->acc) {
                                HERROR_WRITE(HERROR_INFO, "[Serveur] Message client (ip '%s' | login '%s')", u_cursor->ip, u_cursor->acc->login);
                            } else {
                                HERROR_WRITE(HERROR_INFO, "[Serveur] Message client (ip '%s' | login '--')", u_cursor->ip);
                            }
                        }

                        /* Ici, fonction qui lit la réception du message */
                        if(rcvMsgFromUser(u_cursor, &accounts) == 0) {
                            /* si == 0, client déconnecté */
                            if(u_cursor->acc) {
                                HERROR_WRITE(HERROR_INFO, "[Serveur] Deconnexion client (ip '%s' | login '%s')", u_cursor->ip, u_cursor->acc->login);
                            } else {
                                HERROR_WRITE(HERROR_INFO, "[Serveur] Deconnexion client (ip '%s' | login '--')", u_cursor->ip);
                            }
                            /* On ferme la connexion */
                            closesocket(u_cursor->sock);

                            /* On l'enleve des Users */
                            tmp = u_cursor->next;
                            removeUserAndAccount(&u_cursor, &accounts);
                            users = u_cursor;
                            u_cursor = tmp;
                        } else
                            u_cursor = u_cursor->next;
                    } else
                        u_cursor = u_cursor->next;
                }
			}

		}
	}

	endConnection();

	deleteUser(users);
	deleteAccount(accounts);
}
Example #14
0
/*
 * @brief method that is utilized by every thread.
 * 			it handles the input sent from every user, so for
 * 			every new user, the server starts an own thread
 * @param currentUser, a struct that contains references to every other user and
 * 			their informations
 */
void clientHandling(void* currentUser)
{
	//Counts the pingreplies of every user, when 0 the thread stops
	int repliedPings = 3;
	uList* user = (uList*) currentUser;
	char* clientMessage = malloc(256*sizeof(char));


	socklen_t currentClientSocketLength = sizeof(user->clientAdress);
	struct timeval timeout;


	while (repliedPings)
	{

		timeout.tv_sec = 5;
		timeout.tv_usec = 0;
		FD_ZERO(&fds);
		FD_SET(user->clientFD, &fds);
		FD_SET(0, &fds);
		if (select((user->clientFD) + 1, &fds, 0, 0, &timeout) < 0)
			printf("Error in select in thread of <%s>.\n", user->userName);

		// if there is a new message incoming...
		if (FD_ISSET(user->clientFD, &fds))
		{
			if (recvfrom(user->clientFD, clientMessage, sizeof(char)*256,
					0, (struct sockaddr*) &(user->clientAdress), &currentClientSocketLength) == -1)
				printf("Error at receiving Message from %s.\n", user->userName);

			//handle it depending on the identifyer
			switch (clientMessage[0])
			{
			//... here a chat method is incoming...
			case CL_MSG:
			{
				uint16_t userNameLength = strlen(user->userName);
				uint16_t userNameLengthToNetwork = htons(userNameLength);
				uint32_t messageLength;
				uint32_t messageLengthToNetwork;
				memcpy(&messageLengthToNetwork, clientMessage + 1,
						sizeof(messageLengthToNetwork));
				messageLength = ntohl(messageLengthToNetwork);

				char* messageToAll = malloc(
						sizeof(uint8_t) + sizeof(uint16_t)
								+ userNameLength * sizeof(char)
								+ sizeof(uint32_t)
								+ messageLength * sizeof(char));

				messageToAll[0] = SV_AMSG;
				memcpy(messageToAll + sizeof(uint8_t), &userNameLengthToNetwork,
						sizeof(userNameLengthToNetwork));
				memcpy(messageToAll + sizeof(uint8_t) + sizeof(uint16_t),
						user->userName, userNameLength * sizeof(char));
				memcpy(
						messageToAll + sizeof(uint8_t) + sizeof(uint16_t)
								+ userNameLength * sizeof(char),
						&messageLengthToNetwork, sizeof(uint32_t));
				memcpy(
						messageToAll + sizeof(uint8_t) + sizeof(uint16_t)
								+ userNameLength * sizeof(char)
								+ sizeof(uint32_t),
						clientMessage + sizeof(uint8_t) + sizeof(uint16_t)
								+ sizeof(userNameLength) * sizeof(char),
						messageLength * sizeof(uint8_t));

				uList* i;

				//...and spread to every other registered client...
				for (i = firstEntry; i != NULL; i = i->next)
				{
					if (sendto(i->clientFD, messageToAll,
							sizeof(uint8_t) + sizeof(uint16_t)
									+ userNameLength * sizeof(char)
									+ sizeof(uint32_t)
									+ messageLength * sizeof(char), 0,
							(struct sockaddr *) &(i->clientAdress),
							sizeof(i->clientAdress)) == -1)
						printf(
								"Error at sending message.(Client Handler)\n");
				}
				free(messageToAll);
				break;
			}
			// In case a user wants to disconnect...
			case CL_DISC_REQ:
			{
				//we reply to him and...
				uint8_t discRep = SV_DISC_REP;
				if (sendto(user->clientFD, &discRep, sizeof(discRep), 0,
						(struct sockaddr *) &(user->clientAdress),
						sizeof(user->clientAdress)) == -1)
					printf("Error sending disconnec reply to <%s>.\n",
							user->userName);
				//... set his pingreply to 0, so loop ends and we delete him
				repliedPings=0;
				break;
			}
			// If the user replies to our pingrequest, his counter is reset to initial value
			case CL_PING_REP:
				repliedPings = 3;
				break;
			default:
				printf("Couldnt compute the incoming message in Thread of User %s\n",
						user->userName);
				break;
			}
		}
		else
		{
			repliedPings--;
			if (repliedPings < 2)
				printf("%s doesn't answer for the %d time\n", user->userName, 3 - repliedPings);
			// send SV_PING_REQ
			uint8_t ping = SV_PING_REQ;
			if (sendto(user->clientFD, &ping, sizeof(uint8_t), 0,
					(struct sockaddr*) &(user->clientAdress),
					sizeof(user->clientAdress)) == -1)
				printf("Error sending ping to <%s>", user->userName);

		}
	}
	printf("<%s> disconnected.\n", user->userName);
	deleteUser((uList*) currentUser);
	pthread_exit(NULL);
}
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;
}
/*!
    Deletes the specified \a account.

    \param account The account to remove.
    \param removeFiles If true all files owned by the user will be removed.
    \return whether the user was deleted successfully.
*/
bool AccountsManager::deleteUser(UserAccount *account, bool removeFiles)
{
    return deleteUser(account->userId(), removeFiles);
}
Example #17
0
/*!
 * This function takes an element of the interprocess buffer passed to it, and
 * handles populating the respective user and contact tables with its contained
 * data.  
 */
static void executeInterprocessBufferCmd(interprocessBuffer_t *currentBuffer) 
{
	int delContactIndex;

	aorToIndexStruct_t *currentUser;

	if (currentBuffer->callbackType == UL_CONTACT_INSERT) 
	{
		/* Add the user if the user doesn't exist, or increment its 
		 * contact index otherwise. */
		updateUser(currentBuffer->stringName);
	}
	else if (currentBuffer->callbackType != UL_CONTACT_EXPIRE)
	{
		/* Currently we only support UL_CONTACT_INSERT and
		 * UL_CONTACT_EXPIRE.  If we receive another callback type, this
		 * is a bug. */
		LM_ERR("found a command on the interprocess buffer that"
				" was not an INSERT or EXPIRE");
		return;
	}

	currentUser =
		findHashRecord(hashTable, currentBuffer->stringName, HASH_SIZE);


	/* This should never happen.  This is more of a sanity check. */
	if (currentUser == NULL) {
		LM_ERR("Received a request for contact: %s for user: %s who doesn't "
				"exists\n", currentBuffer->stringName, 
				currentBuffer->stringContact);
		return;
	} 

	/* This buffer element specified that we need to add a contact.  So lets
	 * add them */
	if (currentBuffer->callbackType == UL_CONTACT_INSERT) {

		/* Increment the contact index, which will be used to generate
		 * our new row.  */  
		currentUser->contactIndex++;

		/* We should do this after we create the row in the snmptable.
		 * Its easier to delete the SNMP Row than the contact record. */
		if(!insertContactRecord(&(currentUser->contactList), 
			currentUser->contactIndex, 
				currentBuffer->stringContact)) {

			LM_ERR("openserSIPRegUserTable was unable to allocate memory for "
					"adding contact: %s to user %s.\n",
					currentBuffer->stringName, currentBuffer->stringContact);

			/* We didn't use the index, so decrement it so we can
			 * use it next time around. */
			currentUser->contactIndex--;
			
			return;
		}
	
		if (!createContactRow(currentUser->userIndex, 
					currentUser->contactIndex,
					currentBuffer->stringContact, 
					currentBuffer->contactInfo)) {
		
			deleteContactRecord(&(currentUser->contactList), 
					currentBuffer->stringContact);

		}

	}
	else {

		delContactIndex = 
			deleteContactRecord(&(currentUser->contactList), 
					currentBuffer->stringContact);

		/* This should never happen.  But its probably wise to check and
		 * to print out debug messages in case there is a hidden bug.  */
		if(delContactIndex == 0) {
			
			LM_ERR("Received a request to delete contact: %s for user: %s"
				"  who doesn't exist\n", currentBuffer->stringName,
				currentBuffer->stringContact);
			return;

		}		

		deleteContactRow(currentUser->userIndex, delContactIndex);

		deleteUser(hashTable, currentBuffer->stringName, HASH_SIZE);
	}
}
Example #18
0
int GetCmd( int argc, char **argv )
{
  int *ret = (int*)malloc( sizeof( int ) ); 
  *ret = 0;
  
  char _tmp_arg[ 11 ]; _tmp_arg[ 0 ] = '\0';
  strlcpy( _tmp_arg, argv[ 1 ], sizeof( _tmp_arg ) );

  if( !valid_comm( argc, argv ) ) return 1;

  if( strcmp( "set", argv[ 1 ] ) == 0 )
  {
    if( argc > 2  )
    {
      char *_argv = argv[ 2 ];
      GList *list = (GList *)GetOptList( argc, argv, ret );
      
      if( strcmp( "default", _argv ) == 0 )
        setDefault( (char*)GetVal( 'c', list ), (char*)GetVal( 'r', list ), (char*)GetVal( 'w', list ), (char*)GetVal( 's', list ) );
      else
        setUser( _argv, (char*)GetVal( 'c', list ), (char*)GetVal( 'r', list ), (char*)GetVal( 'w', list ), (char*)GetVal( 's', list ) );
    }
    else
      return 1;
  }
  else if( strcmp( "ignore", argv[ 1 ] ) == 0 )
  {
    if( argc > 2  )
    {
      ignoreUser( argv[ 2 ] );
    }
    else
      return 1;
  }
  else if( strcmp( "monitor", argv[ 1 ] ) == 0 )
  {
    if( argc > 2  )
    {
      watchUser( argv[ 2 ] );
    }
    else
      return 1;
  }
  else if( strcmp( "delete", argv[ 1 ] ) == 0 )
  {
    if( argc > 2  )
    {
      deleteUser( argv[ 2 ] );
    }
    else
      return 1;
  }
  else if( strcmp( "list", argv[ 1 ] ) == 0 )
  {
    list();
  }
  else if( strcmp( "list-restricted", argv[ 1 ] ) == 0 )
  {
    list_restricted();
  }
  else if( strcmp( "restrict", argv[ 1 ] ) == 0 )
  {
    if( argc > 2  )
    {
      char *_argv = argv[ 2 ];
      GList *list = (GList *)GetOptList( argc, argv, ret );
  
      restrict_user( _argv, (char*)GetVal( 'l', list ) );
    }
    else
      return 1;
  }
  else if( strcmp( "unrestrict", argv[ 1 ] ) == 0 )
  {
    if( argc > 2  )
    {
      unrestrict( argv[ 2 ] );
    }
    else
      return 1;
  }
  else if( strcmp( "unrestrict-all", argv[ 1 ] ) == 0 )
  {
    unrestrict_all();
  }
  else if( strcmp( "--lve-mode", _tmp_arg ) == 0 )
  {
    char *_argv = argv[ 2 ];
    GList *list = (GList *)GetOptList( argc, argv, ret );
    setLveMode( (char*)GetVal( 100, list ) );
  }
  else
  {
    GetOptList( argc, argv, ret );

    int _ret = *ret; free( ret );
    return _ret;
  }
  
  free( ret );  
  return 0;
}
Example #19
0
void DialogUsers::on_pushButtonDelete_clicked()
{
    deleteUser();
}