Пример #1
0
ssize_t sys_llistxattr (const char *path, char *list, size_t size)
{
#if defined(HAVE_LLISTXATTR)
	ssize_t ret;

	ret = llistxattr(path, list, size);
	return remove_user(ret, list, size);
#elif defined(HAVE_LISTXATTR) && defined(XATTR_ADD_OPT)
	ssize_t ret;
	int options = XATTR_NOFOLLOW;

	ret = listxattr(path, list, size, options);
	return remove_user(ret, list, size);

#elif defined(HAVE_LLISTEA)
	return llistea(path, list, size);
#elif defined(HAVE_EXTATTR_LIST_LINK)
	extattr_arg arg;
	arg.path = path;
	return bsd_attr_list(1, arg, list, size);
#elif defined(HAVE_ATTR_LIST) && defined(HAVE_SYS_ATTRIBUTES_H)
	return irix_attr_list(path, 0, list, size, ATTR_DONTFOLLOW);
#elif defined(HAVE_ATTROPEN)
	ssize_t ret = -1;
	int attrdirfd = solaris_attropen(path, ".", O_RDONLY | O_NOFOLLOW, 0);
	if (attrdirfd >= 0) {
		ret = solaris_list_xattr(attrdirfd, list, size);
		close(attrdirfd);
	}
	return ret;
#else
	errno = ENOSYS;
	return -1;
#endif
}
Пример #2
0
static boolean process_request(SSL *ssl_client)
{
	char buffer[BUFFER_LENGTH + 1];
	char token_name[TOKEN_NAME_LENGTH + 1];
	char request[REQUEST_TYPE_LENGTH + 1];
	
	// Receive request information
	if(SSL_recv_buffer(ssl_client, buffer, NULL) == 0)
	{
		fprintf(stderr, "Receiving request information failed\n");
		goto ERROR;
	}

	// Get a request information token from buffer
	if(read_token_from_buffer(buffer, 1, token_name, request) != READ_TOKEN_SUCCESS || strcmp(token_name, "request") != 0)
		int_error("Extracting the request failed");

	if(strcmp(request, USER_REGISTRATION) == 0)
	{
		return register_user(ssl_client, false);
	}
	else if(strcmp(request, USER_EMAIL_ADDRESS_EDITING) == 0)
	{
		return edit_user_email_address(ssl_client, false);
	}
	else if(strcmp(request, USER_PASSWD_RESETTING) == 0)
	{
		return reset_user_passwd(ssl_client, false);
	}
	else if(strcmp(request, USER_REMOVAL) == 0)
	{
		return remove_user(ssl_client, false);
	}
	else if(strcmp(request, ADMIN_REGISTRATION) == 0)
	{
		return register_user(ssl_client, true);
	}
	else if(strcmp(request, ADMIN_EMAIL_ADDRESS_EDITING) == 0)
	{
		return edit_user_email_address(ssl_client, true);
	}
	else if(strcmp(request, ADMIN_PASSWD_RESETTING) == 0)
	{
		return reset_user_passwd(ssl_client, true);
	}
	else if(strcmp(request, ADMIN_REMOVAL) == 0)
	{
		return remove_user(ssl_client, true);
	}
	else
	{
		fprintf(stderr, "Invalid request type\n");
		goto ERROR;
	}

ERROR:

	return false;
}
Пример #3
0
static void rmuser_command(ostream &out, istream &in)
{
   if (get_access_level() < ADMIN_ACCESS_LEVEL)
      {
      cout << "You must be logged in with administrator privileges\n"
	      "(access level " << ADMIN_ACCESS_LEVEL
	    << " or higher) to add users." << endl ;
      return ;
      }
   char username[200] ;

   out << "Name of user to remove: " << flush ;
   in.ignore(1000,'\n') ;
   in.getline(username,sizeof(username)) ;
   if (!retrieve_userinfo(username))
      {
      cout << "No such user!" ;
      return ;
      }
   if (remove_user(username))
      cout << "User information file updated." << endl ;
   else
      cout << "User information file update failed!" << endl ;
   return ;
}
Пример #4
0
// 客户端退出过程
static void client_logout(user_client* client)
{
    // 从客户端列表中删除
    if (client->already_login())
        remove_user(client);

    // 如果该客户端的读协程还在工作,则通知该读协程退出
    if (client->is_reading())
    {
        printf("%s(%d): user: %s, kill_reader\r\n",
               __FUNCTION__, __LINE__, client->get_name());
        client->kill_reader();
    }

    // 如果该客户端的写协程还在工作,则通知该写协程退出
    if (client->is_waiting())
    {
        printf("fiber-%d: %s(%d): user: %s, notify logout\r\n",
               acl_fiber_self(), __FUNCTION__, __LINE__,
               client->get_name());
        client->notify(MT_LOGOUT);
    }

    // 如果该客户端的读、写协程都已经退出,则通知该客户端退出
    if (!client->is_reading() && !client->is_waiting())
        client->notify_exit();
}
Пример #5
0
ssize_t sys_flistxattr (int filedes, const char *path, char *list, size_t size)
{
#if defined(HAVE_LISTXATTR)
	ssize_t ret;

#ifndef XATTR_ADD_OPT
	ret = listxattr(path, list, size);
#else
	int options = 0;
	ret = listxattr(path, list, size, options);
#endif
	return remove_user(ret, list, size);

#elif defined(HAVE_LISTEA)
	return listea(path, list, size);
#elif defined(HAVE_EXTATTR_LIST_FILE)
	extattr_arg arg;
	arg.path = path;
	return bsd_attr_list(0, arg, list, size);
#elif defined(HAVE_ATTR_LIST) && defined(HAVE_SYS_ATTRIBUTES_H)
	return irix_attr_list(path, 0, list, size, 0);
#elif defined(SOLARIS)
	ssize_t ret = -1;
	int attrdirfd = solaris_attropenat(filedes, path, ".", O_RDONLY, 0);
	if (attrdirfd >= 0) {
		ret = solaris_list_xattr(attrdirfd, list, size);
		close(attrdirfd);
	}
	return ret;
#else
	errno = ENOSYS;
	return -1;
#endif
}
Пример #6
0
void mutt_set_followup_to (ENVELOPE *e)
{
  ADDRESS *t = NULL;
  ADDRESS *from;

  /* 
   * Only generate the Mail-Followup-To if the user has requested it, and
   * it hasn't already been set
   */

  if (option (OPTFOLLOWUPTO) && !e->mail_followup_to)
  {
    if (mutt_is_list_cc (0, e->to, e->cc))
    {
      /* 
       * this message goes to known mailing lists, so create a proper
       * mail-followup-to header
       */

      t = rfc822_append (&e->mail_followup_to, e->to, 0);
      rfc822_append (&t, e->cc, 1);
    }

    /* remove ourselves from the mail-followup-to header */
    e->mail_followup_to = remove_user (e->mail_followup_to, 0);

    /*
     * If we are not subscribed to any of the lists in question,
     * re-add ourselves to the mail-followup-to header.  The 
     * mail-followup-to header generated is a no-op with group-reply,
     * but makes sure list-reply has the desired effect.
     */

    if (e->mail_followup_to && !mutt_is_list_recipient (0, e->to, e->cc))
    {
      if (e->reply_to)
	from = rfc822_cpy_adr (e->reply_to, 0);
      else if (e->from)
	from = rfc822_cpy_adr (e->from, 0);
      else
	from = mutt_default_from ();
      
      if (from)
      {
	/* Normally, this loop will not even be entered. */
	for (t = from; t && t->next; t = t->next)
	  ;
	
	t->next = e->mail_followup_to; 	/* t cannot be NULL at this point. */
	e->mail_followup_to = from;
      }
    }
    
    e->mail_followup_to = mutt_remove_duplicates (e->mail_followup_to);
    
  }
}
Пример #7
0
void			close_client(t_user *tmp, t_user **list)
{
  char			*buff;

  if ((buff = malloc(4096 * sizeof(char))) == NULL)
    return ;
  close(tmp->socket);
  sprintf(buff, DECO_CLI, tmp->name);
  send_msg(*list, tmp, buff, 2);
  remove_user(list, tmp->name);
  return ;
}
Пример #8
0
void mutt_fix_reply_recipients (ENVELOPE *env)
{
  if (! option (OPTMETOO))
  {
    /* the order is important here.  do the CC: first so that if the
     * the user is the only recipient, it ends up on the TO: field
     */
    env->cc = remove_user (env->cc, (env->to == NULL));
    env->to = remove_user (env->to, (env->cc == NULL));
  }
  
  /* the CC field can get cluttered, especially with lists */
  env->to = mutt_remove_duplicates (env->to);
  env->cc = mutt_remove_duplicates (env->cc);
  env->cc = mutt_remove_xrefs (env->to, env->cc);
  
  if (env->cc && !env->to)
  {
    env->to = env->cc;
    env->cc = NULL;
  }
}
Пример #9
0
int remove_user_from_room (user u, char *room_name) {
   
    // On récupère la liste des salons du haché du nom de salon
    int index = hash_room_name (room_name);
    room_list l = rooms[index];
    room_list t;

    // On parcourt la liste
    for (t = l; t != NULL; t = t->next) {
        if (strcmp (t->current->name, room_name) == 0) {
            remove_user (u, t->current->users);
            break;
        }
    }

    return 0;
}
Пример #10
0
void	make_leave(t_env *e, int cs, char *line)
{
	t_chan	*tmp;

	(void)line;
	tmp = e->users[cs]->chan;
	if (tmp != NULL)
	{
		send_msg(e, cs, tmp);
		if (tmp->co->after == NULL)
			free_chan(e, tmp);
		else
			tmp->co = remove_user(tmp, cs);
		e->users[cs]->chan = NULL;
	}
	else
		send(cs, "You can't leave what you didn't joined\0", 39, 0);
}
Пример #11
0
int main(int argc, char *argv[]) {
	adduser();
	showusers(argc, argv);
	show_bill();
	fcloseall();
	lightbill obj;
	obj = find_bill(1	);
	if(obj.id) {
		printf("\n\n");
		printf("%d\n\n", obj.prev_unit);
	}
	generate_bill(2, 250);
	show_bill();
	user h;
	h = finduser(1);
	remove_user(5);
	printf("%s", h.id);
	return 0;
}
Пример #12
0
void parse_msg(char tokens[MAX_MSG_TOKENS][MAX_MSG_LEN+1],
              int length, char *sendbuf, int fd)
{
    // app_error("Not Implemented");
    // int i = ERR_UNKNOWNCOMMAND; 
    if(!strcmp(tokens[0],"ADDUSER"))
    {
        add_user(fd, tokens[1], sendbuf);
    } else
    if(!strcmp(tokens[0],"ADDCHAN"))
    {
    	add_channel(fd, tokens[1], sendbuf);
    } else
    if(!strcmp(tokens[0],"REMOVEUSER"))
    {
    	remove_user(fd, tokens[1], sendbuf);
    } else
    if(!strcmp(tokens[0],"REMOVECHAN"))
    {
    	remove_channel(fd, tokens[1], sendbuf);
    } else
    if(!strcmp(tokens[0],"NEXTHOP"))
    {
    	next_hop(fd, tokens[1], sendbuf);
    } else
    if(!strcmp(tokens[0],"NEXTHOPS"))
    {
    	next_hops(fd, atol(tokens[1]), tokens[2], sendbuf);
    } else
    if(!strcmp(tokens[0],"USERTABLE"))
    {
    	user_table(fd, sendbuf);
    } else
    if(!strcmp(tokens[0],"CHANTABLE"))
    {
    	channel_table(fd, sendbuf);
    } else {

    }
    return;
}
void suh::clean_up() {
	// Remove users that have not logged in for user_expiration_ days:
	// Check if the last login of this user exceeds the
	// expiration limit

	//The expiration time set to 0 means no expiration limit
	if(!user_expiration_) {
		return;
	}

	time_t now = time(NULL);

	//A minute has 60 seconds, an hour 60 minutes and
	//a day 24 hours.
	time_t limit = user_expiration_ * 60 * 60 * 24;

	std::vector<std::string> us = users();
	for(std::vector<std::string>::const_iterator u = us.begin(); u != us.end(); ++u) {
		if((now - get_lastlogin(*u)) > limit) {
			std::cout << "User '" << *u << "' exceeds expiration limit.\n";
			remove_user(*u);
		}
	}
}
Пример #14
0
void *srv_thread_function(void *arg) {
	printf("server thread started!\n"); // hooray
	
	
// initializing variables
	ptsrv_thread_args targs = (ptsrv_thread_args) arg;
	sim = targs->sim;
	int PORT = targs->port;
	
	
	
	
	int socketfd;                       /* Socket file descriptor  */
	struct sockaddr_in server_name;     /* server socket's address */
	struct sockaddr_in client_name;     /* client socket's address */

	fd_set active_fd_set, read_fd_set;  /* Array of file descriptors */

	int nbytes;
	char buffer[BUFFER_SIZE];
	
	int socketdest;
	char* pacote;
	char str_aux[80];
	FILE* motd;
	char name[150]; //robot name buffer

	table = start_table();
 /* Create the socket. 

    socket (NAMESPACE, STYLE, PROTOCOL)

      - namespace: local, other, internet: PF_INET || PF_INET6 

      - style: SOCK_STREAM, SOCK_DGRAM

      - protocol: 0 means 'auto' */

	socketfd = socket (PF_INET, SOCK_STREAM, 0); 

	if (socketfd < 0)
   	fatal ();

	/* Give the socket a name. */

	server_name.sin_family = AF_INET;                   /* Ineternet family */
	server_name.sin_port = htons (PORT);                /* set port  */
	server_name.sin_addr.s_addr = htonl (INADDR_ANY);   /* Any internetface */

	/* Bind the socket to the port. */

	if (bind (socketfd, (struct sockaddr *) &server_name, sizeof (server_name)) < 0)
		fatal ();
	
     // 23 apr 2010 - Disabling Nagle algorithm	in the protocol stack, so it sends packages
     // immeadiately, without waiting for more bytes to be available to send, which is more
     // appropriate for this real-time program,
     char flag = 1;
     setsockopt(socketfd, IPPROTO_TCP, 1, (char *) &flag, sizeof(int)); 

	/* Tell the OS to start to listen to the socket. */

	if (listen (socketfd, 1) < 0)
		fatal ();

	/* Initialize the set of active sockets. */

	FD_ZERO (&active_fd_set);
	FD_SET (socketfd, &active_fd_set);

	for (;;) {
		int i,j;

		/* Block until there is activity in the socket. */
		read_fd_set = active_fd_set;

		if (select (FD_SETSIZE, &read_fd_set, NULL, NULL, NULL) < 0)
        fatal ();
	
	
	
	

     
     
     /* Service all the sockets with input pending. */

		for (i = 0; i < FD_SETSIZE; ++i) {
			if (FD_ISSET (i, &read_fd_set)) {
				if (i == socketfd) { /* Connection request on original socket. */
					int new_socket;
					socklen_t size;

					/* Accept the the connection and associate it
					with a new socket. */

					size = sizeof (client_name);
					new_socket = accept (socketfd, (struct sockaddr *) &client_name, &size);
					if (new_socket < 0)
						fatal ();
					fprintf (stderr, "Server: connect from host %s, port %hd.\n", inet_ntoa (client_name.sin_addr), ntohs (client_name.sin_port));
					FD_SET (new_socket, &active_fd_set);      /* Add the new socket to the set of active fd */
					
					// adding new user to the table
					//add_user (table, inet_ntoa (client_name.sin_addr), new_socket);
					add_user (table, new_socket);
				}
				else {                                 /* Data arriving on an already-connected socket. */
					nbytes = read (i, buffer, BUFFER_SIZE);
					buffer[nbytes-1] = 0;
					if (nbytes ==0) {                  /* Cient ended the transmission */ 
						printf ("Client disconnected.\n");
						remove_user (table, i);
						print_table (table);
						close (i);
						FD_CLR (i, &active_fd_set);
					}
					else if (nbytes < 0) {            /* Read error */ 
						fprintf (stderr, "Read error, client disconnected.\n");
						remove_user (table, i);
						print_table (table);
						close (i);
						FD_CLR (i, &active_fd_set);
					}
					else {                            // client message
						//debug
						//printf("%s\n", buffer);
						if (IsPackageValid(buffer, nbytes)) {
							if (NewRobot(buffer, name)) { //new robot connected, get name
								printf("New robot added: %s\n", name);
								set_id(table, i, name); //add the new name to the table
								strcpy(sim->robotnames[sim->num_available_clients], name);
								sim->num_available_clients++;
								print_table (table);
								sim->clientlist_update = true;
								//CreateUpdate(buffer, &nbytes, sim->GetRobot(get_id(table, i)));
								//write(i, buffer, nbytes);
							} else {
								//update settings for this robot
								if (GetUpdate(buffer, nbytes, sim->GetRobot(get_id(table, i))) ) {
									//printf("got update from %s\n", sim->GetRobot(get_id(table, i))->robot_name);
									CreateUpdate(buffer, &nbytes, sim->GetRobot(get_id(table, i)));
									write(i, buffer, nbytes);
								} else {
								    //printf("pacote de ok\n");
								    CreateUpdate(buffer, &nbytes, sim->GetRobot(get_id(table, i)));
								    write(i, buffer, nbytes);
								}
							}
						}
						//nbytes = write (i, buffer, strlen(buffer) + 1);
						
					
						/*switch (get_tipo(buffer)) {
						case 2:                       // mensagem privada;
							nome = get_dest(buffer);
							socketdest = busca_usuario(tabela, nome);
							if (socketdest) {
								nbytes = write (socketdest, buffer, strlen(buffer) + 1);
								nbytes = write (i, buffer, strlen(buffer) + 1);
							}
							free(nome);
						break;
						case 3:                      //mensagem de sauda��o de novo usuario
							nome = get_rem(buffer);
							adiciona_usuario(tabela, nome, i);
							imprime_tabela(tabela);
							free(nome);
							if ((motd = fopen("motd", "r")) != NULL) {   // abre o Message Of The Day
								while (fgets(str_aux,79, motd)) {
									pacote = monta_pacote_sis(str_aux, nome);
									nbytes = write (i, pacote, pacote[0]);
									usleep(2000);
								}
								fclose(motd);
							}
						default: // mensagem comum (tambem repassa para todos os usuarios a mensagem de saudacao - case 3 nao tem break)
							for (j = 3; j < FD_SETSIZE; ++j) {
								if (j != socketfd) nbytes = write (j, buffer, strlen(buffer) + 1);
    						}	
						break;
						case 4:                   // mensagens do sistema
							switch (get_sis(buffer)) {
							case 'l':             // cliente requisitando a listagem de usuarios conectados
								reset_iterator(tabela);
								nome = get_rem(buffer);
								strcpy(str_aux, "Usuarios conectados:\n");
								pacote = monta_pacote_sis(str_aux, nome);
								nbytes = write (i, pacote, pacote[0]);
								free(pacote);
								do {
									usleep(2000);
									strcpy(str_aux, get_next_nome(tabela));
									strcat(str_aux, "\n");
									pacote = monta_pacote_sis(str_aux, nome);
									nbytes = write (i, pacote, pacote[0]);
									free(pacote);
								} while (! iterator_finished(tabela));
								usleep(2000);
								strcpy(str_aux, "Fim da listagem.\n");
								pacote = monta_pacote_sis(str_aux, nome);
								nbytes = write (i, pacote, pacote[0]);
								free(pacote);
							break;
							}
						break;
						
						}*/
					}
				}
			}
		}
	}	
	
}
Пример #15
0
int main(int argc, char* argv[]) { 
	user_list* servant_users;
	FILE* test_file = fopen(SERVANT_ACCOUNTS_FILE, "w");

	servant_user* u1 = (servant_user*) malloc(sizeof(servant_user));
	servant_user* u2 = (servant_user*) malloc(sizeof(servant_user));
	servant_user* u3 = (servant_user*) malloc(sizeof(servant_user));
	servant_user* u4 = (servant_user*) malloc(sizeof(servant_user));
	servant_user* u5 = (servant_user*) malloc(sizeof(servant_user));

	printf("Testing user management. Using ORDERED_LIST behavior.\n");

	write_line(test_file, "user0:3d517fe6ebab7b8cfcf98db6259c8a59");
	write_line(test_file, "user1:24c9e15e52afc47c225b757e7bee1f9d");
	write_line(test_file, "user8:7e58d63b60197ceb55a1c487989a3720");
	write_line(test_file, "user3:92877af70a45fd6a2ed7fe81e1236b78");
	write_line(test_file, "user2:3f02ebe3d7929b091e3d8ccfde2f3bc6");
	write_line(test_file, "user5:0a791842f52a0acfbb3a783378c066b8");

	fclose(test_file);

	printf("Parsing test accounts file...\t");
	parse_accounts_file(&servant_users, ORDERED_LIST);
	printf("done.\n");

	print_users(servant_users);
	
	printf("Building some users...\n");

	strncpy(u1->username, "user4", sizeof(u1->username) -1);
	u1->username[31] = '\0';
	strncpy(u1->password, "7668f673d5669995175ef91b5d171945", sizeof(u1->password) - 1);
	u1->password[31] = '\0';

	strncpy(u2->username, "user6", sizeof(u2->username) -1);
	u2->username[31] = '\0';
	strncpy(u2->password, "affec3b64cf90492377a8114c86fc093", sizeof(u2->password) - 1);
	u2->password[31] = '\0';

	strncpy(u3->username, "user10", sizeof(u3->username) -1);
	u3->username[31] = '\0';
	strncpy(u3->password, "990d67a9f94696b1abe2dccf06900322", sizeof(u3->password) - 1);
	u3->password[31] = '\0';

	strncpy(u4->username, "user7", sizeof(u4->username) -1);
	u4->username[31] = '\0';
	strncpy(u4->password, "990d67a9f94696b1abe2dccf06900322", sizeof(u4->password) - 1);
	u4->password[31] = '\0';

	strncpy(u5->username, "user9", sizeof(u5->username) -1);
	u5->username[31] = '\0';
	strncpy(u5->password, "8808a13b854c2563da1a5f6cb2130868", sizeof(u5->password) - 1);
	u5->password[31] = '\0';

	printf("Adding them...\n");

	add(servant_users, u1);
	add(servant_users, u2);
	add(servant_users, u5); 

	print_users(servant_users);

	print_if_has_user(servant_users, *u1);
	print_if_has_user(servant_users, *u2);
	print_if_has_user(servant_users, *u3);
	print_if_has_user(servant_users, *u4);
	print_if_has_user(servant_users, *u5);
	print_if_has_user_by_username(servant_users, "user0");
	print_if_has_user_by_username(servant_users, "user1");
	print_if_has_user_by_username(servant_users, "user8");
	print_if_has_user_by_username(servant_users, "user2");
	print_if_has_user_by_username(servant_users, "user3");
	print_if_has_user_by_username(servant_users, "user5");

	printf("\nRemoving some users...\n");
	remove_user(servant_users, u1);
	remove_user(servant_users, u5);
	remove_user(servant_users, u3);

	print_users(servant_users);

	printf("\n\nUpdating accounts file...\t");
	update_accounts_file(servant_users);
	printf("done.\n");

	free(servant_users); 
	remove(SERVANT_ACCOUNTS_FILE);

	printf("\n\nNow using UNORDERED_LIST behavior.\n");

	test_file = fopen(SERVANT_ACCOUNTS_FILE, "w");

	write_line(test_file, "user0:3d517fe6ebab7b8cfcf98db6259c8a59");
	write_line(test_file, "user1:24c9e15e52afc47c225b757e7bee1f9d");
	write_line(test_file, "user8:7e58d63b60197ceb55a1c487989a3720");
	write_line(test_file, "user3:92877af70a45fd6a2ed7fe81e1236b78");
	write_line(test_file, "user2:3f02ebe3d7929b091e3d8ccfde2f3bc6");
	write_line(test_file, "user5:0a791842f52a0acfbb3a783378c066b8");

	fclose(test_file);
	
	printf("Parsing test accounts file...\t");
	parse_accounts_file(&servant_users, UNORDERED_LIST);
	printf("done.\n");
	
	printf("Building some users...\n");

	strncpy(u1->username, "user4", sizeof(u1->username) -1);
	u1->username[31] = '\0';
	strncpy(u1->password, "7668f673d5669995175ef91b5d171945", sizeof(u1->password) - 1);
	u1->password[31] = '\0';

	strncpy(u2->username, "user6", sizeof(u2->username) -1);
	u2->username[31] = '\0';
	strncpy(u2->password, "affec3b64cf90492377a8114c86fc093", sizeof(u2->password) - 1);
	u2->password[31] = '\0';

	strncpy(u3->username, "user10", sizeof(u3->username) -1);
	u3->username[31] = '\0';
	strncpy(u3->password, "990d67a9f94696b1abe2dccf06900322", sizeof(u3->password) - 1);
	u3->password[31] = '\0';

	strncpy(u4->username, "user7", sizeof(u4->username) -1);
	u4->username[31] = '\0';
	strncpy(u4->password, "990d67a9f94696b1abe2dccf06900322", sizeof(u4->password) - 1);
	u4->password[31] = '\0';

	strncpy(u5->username, "user9", sizeof(u5->username) -1);
	u5->username[31] = '\0';
	strncpy(u5->password, "8808a13b854c2563da1a5f6cb2130868", sizeof(u5->password) - 1);
	u5->password[31] = '\0';

	printf("Adding them...\n");

	add(servant_users, u1);
	add(servant_users, u2);
	add(servant_users, u5); 

	print_users(servant_users);

	print_if_has_user(servant_users, *u1);
	print_if_has_user(servant_users, *u2);
	print_if_has_user(servant_users, *u3);
	print_if_has_user(servant_users, *u4);
	print_if_has_user(servant_users, *u5);
	print_if_has_user_by_username(servant_users, "user0");
	print_if_has_user_by_username(servant_users, "user1");
	print_if_has_user_by_username(servant_users, "user8");
	print_if_has_user_by_username(servant_users, "user2");
	print_if_has_user_by_username(servant_users, "user3");
	print_if_has_user_by_username(servant_users, "user5");

	printf("\nRemoving some users...\n");
	remove_user(servant_users, u1);
	remove_user(servant_users, u5);
	remove_user(servant_users, u3);

	print_users(servant_users); 

	printf("\n\nUpdating accounts file...\t");
	update_accounts_file(servant_users);
	printf("done.\n");

	free(servant_users); 
	remove(SERVANT_ACCOUNTS_FILE); 


	printf("\n\nTests are done. No errors.\n");

	return 0;
}
Пример #16
0
//-----------------------------------------------------------------------------
void *connection(void *user) {
  //struct timeval curTime;
  struct User *_user = (struct User *)user;
  int e;
  int rc = 1;
  int sockfd = _user->sockfd;
  pthread_detach(pthread_self()); //automatically clears the threads memory on exit
  fd_set rdset, wrset;
  int s = -1;
  int max_fd = sockfd + 1;
  struct timeval selectTimeout;
  
  selectTimeout.tv_sec = TIMEOUT / 1000;
  selectTimeout.tv_usec = (TIMEOUT % 1000) * 1000;
  FD_ZERO(&rdset);
  FD_ZERO(&wrset);
  
  char *buf = calloc(100,1);
  for (;;) {
    // start monitoring for reads or timeout
    if (s <= 0) {
      FD_SET(sockfd, &rdset);
    }

    s = select(max_fd, &rdset, &wrset, NULL, &selectTimeout); 

    if (s == -1) { printf("ERROR: Socket error. Exiting.\n"); exit(1); }

    /*
     * Here we handle all of the incoming text from a particular client.
     */
    if(s > 0) {
      bzero(buf,100);
      rc = recv(sockfd,buf,99,0);
      if (rc > 0)
      {
        char *cmd = malloc(24);
        cmd = strtok(buf," ");
 
        // which command are we processing? 
        if (strcmp(cmd,GET_CMD) == 0) {
          char *filename = calloc(FILENAME_LEN,1);
          filename = strtok(NULL,"\0");
          send_file_info(sockfd, filename);
        }
        else if (strcmp(cmd,LIST_CMD) == 0) {
          send_file_list(sockfd);
        }
        else if (strcmp(cmd,USERS_CMD) == 0) {
          send_user_list(sockfd);
        }
        else if (strcmp(cmd,SEND_LIST_CMD) == 0) {
          receive_file_list(sockfd,_user);
        }
        else if (strcmp(cmd,EXIT_CMD) == 0) {
          //if I received an 'exit' message from this client
	        pthread_mutex_lock(&mutex);
	        remove_user(_user);
	        pthread_mutex_unlock(&mutex);
	        pthread_exit(NULL);
	        printf("Shouldn't see this!\n");
          //loop through global client list and
	        //e =write(..); 
	        if (e == -1) //broken pipe.. someone has left the room
	        {
	          pthread_mutex_lock(&mutex);
	          //so remove them from our list
	          pthread_mutex_unlock(&mutex);
	        }
        }
        else {
          printf("Unknown command received: %s\n",cmd);
        }
        fflush(stdout);
      }
    }
  }	
	//A requirement for 5273 students:
  //if I received a new files list from this client, the
	//server must “Push”/send the new updated hash table to all clients it is connected to.

  //should probably never get here
  return 0;
}
Пример #17
0
// main
int
main(int argc, char** argv)
{
	BApplication app("application/x-vnd.antares-netfs_server_prefs");

	// parse first argument
	int argi = 1;
	const char* arg = next_arg(argc, argv, argi);
	if (strcmp(arg, "-h") == 0 || strcmp(arg, "--help") == 0)
		print_usage_and_exit(false);

	if (strcmp(arg, "launch") == 0) {
		// launch
		no_more_args(argc, argi);
		launch_server();
	} else if (strcmp(arg, "terminate") == 0) {
		// terminate
		no_more_args(argc, argi);
		terminate_server();
	} else if (strcmp(arg, "save") == 0) {
		// save
		no_more_args(argc, argi);
		save_server_setttings();
	} else if (strcmp(arg, "l") == 0 || strcmp(arg, "list") == 0) {
		// list
		no_more_args(argc, argi);
		list();
	} else if (strcmp(arg, "add") == 0) {
		// add
		arg = next_arg(argc, argv, argi);
		if (strcmp(arg, "share") == 0) {
			// share
			const char* name = next_arg(argc, argv, argi);
			const char* path = next_arg(argc, argv, argi);
			no_more_args(argc, argi);
			add_share(name, path);
		} else if (strcmp(arg, "user") == 0) {
			// user
			const char* name = next_arg(argc, argv, argi);
			const char* password = next_arg(argc, argv, argi, true);
			no_more_args(argc, argi);
			add_user(name, password);
		} else
			print_usage_and_exit(true);
	} else if (strcmp(arg, "remove") == 0) {
		// remove
		arg = next_arg(argc, argv, argi);
		if (strcmp(arg, "share") == 0) {
			// share
			const char* name = next_arg(argc, argv, argi);
			no_more_args(argc, argi);
			remove_share(name);
		} else if (strcmp(arg, "user") == 0) {
			// user
			const char* name = next_arg(argc, argv, argi);
			no_more_args(argc, argi);
			remove_user(name);
		} else
			print_usage_and_exit(true);
	} else if (strcmp(arg, "permissions") == 0) {
		// permissions
		const char* user = next_arg(argc, argv, argi);
		const char* share = next_arg(argc, argv, argi);
		uint32 permissions = 0;
		while (argi < argc) {
			uint32 perms = 0;
			arg = next_arg(argc, argv, argi);
			if (!get_permissions(arg, &perms))
				print_usage_and_exit(true);
			permissions |= perms;
		}
		set_user_permissions(user, share, permissions);
	} else {
		print_usage_and_exit(true);
	}

	return 0;
}
Пример #18
0
int sh( int argc, char **argv, char **envp ) {
	signal(SIGINT, sig_handle);
	signal(SIGTERM, SIG_IGN);
	signal(SIGTSTP, SIG_IGN);
	char *prompt = calloc(PROMPTMAX, sizeof(char));
	char *commandline = calloc(MAX_CANON, sizeof(char));
	char *command, *arg, *aliashelp, *commandpath, *p, *pwd, *owd;
	/* Use these two save chars for strtok_r on command and alias commands*/
	char *command_save, *alias_save;
	char **args = calloc(MAXARGS, sizeof(char*));
	int uid, i, status, argsct, a, go = 1;
	int background, bg_pid = 0;
	struct passwd *password_entry;
	char *homedir;
	struct pathelement *pathlist, *history;
	struct aliaselement *aliases;
	const char sp[2] = " ";
	extern char **environ;
	glob_t globbuf;
	size_t glc;
	char **gl;
	pthread_t pt_warnload, pt_watchuser;
	
	/* for use with warnload */
	float load = 0.0;
	int load_thread = 1;
	
	/* for use with watchuser */
	static pthread_mutex_t user_lock = PTHREAD_MUTEX_INITIALIZER;
	int user_thread = 1;
	struct userarg *userargs;

	/* for use with file redirection */
	int fid;
	int file_redirect, error_redirect, input_redirect = 0;
	int noclobber = 0;

	/* for use with pipe */
	int ipc = 0;
	int ipc_err = 0;
	int pipefd[2];
	char **pipeargs = calloc(5, sizeof(char*));

	uid = getuid();
	password_entry = getpwuid(uid);               /* get passwd info */
	homedir = getenv("HOME");						/* get homedir */
     
	if ( (pwd = getcwd(NULL, PATH_MAX+1)) == NULL ) {
    	perror("getcwd");
    	exit(2);
	}
	
	owd = calloc(strlen(pwd) + 1, sizeof(char));
	memcpy(owd, pwd, strlen(pwd));
	prompt[0] = ' '; prompt[1] = '\0';

	/* Put PATH into a linked list */
	pathlist = get_path();

	/* By default, we have no history or aliases or users */
	history = NULL;
	aliases = NULL;
	userargs = NULL;

	while ( go ) {

		/* wait on background processes */
		bg_pid = waitpid(-1, &status, WNOHANG);
		if(bg_pid > 0) {
        	printf("Background child [%d] exited with status: %d\n", bg_pid, WEXITSTATUS(status));
		}

		/* print prompt */
		printf("\n");
    	printf(prompt);
    	printf(" [");
    	printf(pwd);
    	printf("]> ");

    	i = 0;

		/* get command line and process */
    	while (fgets(commandline, MAX_CANON, stdin) != NULL) {

			/* wait on background processes */
            bg_pid = waitpid(-1, &status, WNOHANG);
            if(bg_pid > 0) {
                printf("Background child [%d] exited with status: %d\n", bg_pid, WEXITSTATUS(status));
            }

			if (commandline[strlen(commandline) - 1] == '\n') {
				commandline[strlen(commandline) - 1] = 0;
			}

			/* Add the command to history */
			history = add_last(history, commandline);

			/* Get the command */	
			command = strtok_r(commandline, sp, &command_save);
			if(command == NULL) {
				break;
			}

			/* Search for aliases */
			a = 0;	
			struct aliaselement *alias = aliases;
			while(alias != NULL) {
				if(strcmp(command, alias->name) == 0) {
					a = 1;
					break;
				}
				alias = alias->next;
			}

			/* If we have an alias */
			i = 0;
			if(a) {
				/* parse alias command */
				arg = calloc(strlen(alias->command) + 1, sizeof(char));
				strcpy(arg, alias->command);
				aliashelp = strtok_r(arg, sp, &alias_save);
				while(aliashelp != NULL) {
					if(i == MAXARGS) {
						strcpy(args[0], "maxargs");
						break;
					}
					args[i] = calloc(strlen(aliashelp) + 1, sizeof(char));
					strcpy(args[i], aliashelp);
					aliashelp = strtok_r(NULL, sp, &alias_save);
					i++;
				}
				command = strtok_r(NULL, sp, &command_save);
				free(arg);
			} 

			/* parse command line or remainder of command line if we have an alias */
			while (command != NULL) {
	    		if(i == MAXARGS) {
					strcpy(args[0], "maxargs");
					break;
				}
	    		args[i] =  calloc(strlen(command) + 1, sizeof(char));
	   			strcpy(args[i], command);
	    		command = strtok_r(NULL, sp, &command_save);
	    		i++;
			}
			
			/* SANITY CHECK: make sure the user passed in something */
			if(args[0] == NULL) {
				break;
			}

			/* Expand wildcard characters */
			glob(args[0], GLOB_NOCHECK, NULL, &globbuf);
			i = 1;	
			while(args[i] != NULL) {
 				glob(args[i], GLOB_APPEND | GLOB_NOCHECK, NULL, &globbuf);
				i++;
			}
		
			/* gl becomes our arguments, it is the expanded version of args */
			gl = globbuf.gl_pathv;
			/* glc is the number of arguments. Use it for checking built in commands */
			glc = globbuf.gl_pathc;

			/* Check for background & at end of last argument */
			char* last_arg = gl[glc - 1];
			char last_char = last_arg[(strlen(last_arg) - 1)];
			if(strcmp(&last_char, "&") == 0) {
				last_arg[(strlen(last_arg) - 1)] = '\0';
				background = 1;
			}

			/* Check for file output redirection (without appending) */
			if(glc > 2 && (strcmp(gl[glc-2], ">") == 0 || strcmp(gl[glc-2], ">&") == 0)) {

				/* Don't overwrite an existing file if noclobber is set */
				if(noclobber) {
					if(access(gl[glc-1], F_OK) == 0) {
						fprintf(stderr, "%s: File exists.\n", gl[glc-1]);
						free_args(args);
						break;
					}
				}

				/* Redirect the output to given file */
				fid = open(gl[glc-1], O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP);
				if(fid == -1) {
					perror(gl[glc-1]);
					free_args(args);
					break;
				}
				close(1);
				dup(fid);
				
				/* Redirect error output to the given file */
				if(strcmp(gl[glc-2], ">&") == 0) {
					close(2);
					dup(fid);
					error_redirect = 1;
				}
				close(fid);
				file_redirect = 1;

				/* Hide redirection character and filename */
				gl[glc-2] = '\0';
				gl[glc-1] = '\0';
				glc = glc - 2;
			}

			/* Check for file output redirection (with appending) */
			if(glc > 2 && (strcmp(gl[glc-2], ">>") == 0 || strcmp(gl[glc-2], ">>&") == 0)) {
				
				/* Don't append to a file that doesn't exist */
				if(noclobber) {
					if(access(gl[glc-1], F_OK) != 0) {
						fprintf(stderr, "%s: No such file or directory.\n", gl[glc-1]);
						free_args(args);
						break;
					}
				}

				/* Redirect the output to given file */
				fid = open(gl[glc-1], O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR|S_IRGRP);
				if(fid == -1) {
					perror(gl[glc-1]);
					free_args(args);
					break;
				}
				close(1);
				dup(fid);
		
				/* Redirect error output to the given file */
				if(strcmp(gl[glc-2], ">>&") == 0) {
					close(2);
					dup(fid);
					error_redirect = 1;
				}
				close(fid);
				file_redirect = 1;
			
				/* Hide redirection character and filename */
				gl[glc-2] = '\0';
				gl[glc-1] = '\0';
				glc = glc - 2;
			}

			/* Check for file input redirection */
			if(glc > 2 && strcmp(gl[glc-2], "<") == 0) {

				/* Can't take input from a nonexisistent file */
				if(access(gl[glc-1], F_OK) != 0) {
					fprintf(stderr, "%s: No such file or directory.\n", gl[glc-1]);
					free_args(args);
					break;
				}

				/* Open the file to read from */
				fid = open(gl[glc-1], O_RDONLY);
				if(fid == -1) {
					perror(gl[glc-1]);
					free_args(args);
					break;
				}
				close(0);
				dup(fid);
				close(fid);
				input_redirect = 1;

				/* Hide redirection character and filename */
				gl[glc-2] = '\0';
				gl[glc-1] = '\0';
				glc = glc - 2;
			}

			/* Check for inter-process communication */
			if(glc > 2 && (strcmp(gl[1], "|") == 0 || strcmp(gl[1], "|&") == 0)) {
				ipc = 1;
				if(strcmp(gl[1], "|&") == 0) {
					ipc_err = 1;
				}

				/* Create our pipe */
				if(pipe(pipefd) == -1) {
					perror("pipe");
					free_args(args);
					break;
				}

				/* Put the command to the right of the pipe in a second arguments list */
				i = 2;
				int p = 0;
				while(gl[i] != NULL) {
					pipeargs[p] = malloc(strlen(gl[i]) + 1 * sizeof(char));
					pipeargs[p] = gl[i];
					i++; p++;
				}
				gl[1] = '\0';
				glc = 1;
			}

    		/* check for each built in command and implement */

			/* Built in warnload */
			if(strcmp(gl[0], "warnload") == 0) {
	    		printf("Executing built-in [%s]\n", gl[0]);
				char *end;
				if(glc != 2) {
					printf("Usage: warnload LOAD\n");
				} else if (strcmp(gl[1], "0.0") != 0 && (strtof(gl[1], &end) == 0 || strtof(gl[1], &end) < 0)) {
					printf("LOAD must be a positive floating point number\n");
				} else if (strcmp(gl[1], "0.0") == 0) {
					load = 0.0;
					load_thread = 1;
				} else {
					load = strtof(gl[1], &end);
					if(load_thread != 0) {
						load_thread = 0;
						pthread_create(&pt_warnload, NULL, warnload, &load);
					}
				}
			}

			/* Built in watchuser */
			else if(strcmp(gl[0], "watchuser") == 0) {
	    		printf("Executing built-in [%s]\n", gl[0]);
				if(glc < 2) {
					fprintf(stderr, "watchuser: Too few arguements.\n");
				} else if(glc > 3) {
					fprintf(stderr, "watchuser: Too many arguments.\n");
				} else if (glc == 3 && strcmp(gl[2], "off") != 0) {
					printf("Usage: watchuser USERNAME [off]\n");
				} else if (glc == 3 && strcmp(gl[2], "off") == 0 ){

					/* remove the given username from watched users list */
					if(user_thread == 0) {
						pthread_mutex_lock(&user_lock);
						userargs->users = remove_user(userargs->users, gl[1]);
						pthread_mutex_unlock(&user_lock);
					} else {
						printf("No watched users have been added yet\n");
					}
				} else {
					
					/* Add the user to the list. Create the watchuser thread if it isn't already created */
					if(user_thread == 1) {
						user_thread = 0;
						userargs = calloc(1, sizeof(struct userarg));	
						userargs->lock = user_lock;
						userargs->users = add_user(NULL, gl[1]);
						pthread_create(&pt_watchuser, NULL, watchuser, userargs);
					} else {
						pthread_mutex_lock(&user_lock);
						userargs->users = add_user(userargs->users, gl[1]);
						pthread_mutex_unlock(&user_lock);
					}
				}
			}

			/* WATCHMAIL NOT IMPLEMENTED */
			else if(strcmp(gl[0], "watchmail") == 0) {
				printf("We were not able to implement watchmail as we could not figure out\nhow to correctly use pthread_cancel(3) to cancel threads\n");
			}

			/* Build in fg */
			else if(strcmp(gl[0], "fg") == 0) {
				printf("Executing build-in [%s]\n", gl[0]);
				/* No arguments, bring a default process into foreground */
				if(glc == 1) {
					kill(0, SIGCONT);
					wait(NULL);
				}
				/* One argument, bring the process with pid into foreground */
				else if(glc == 2) {
					if(atoi(gl[1])) {
						kill(atoi(gl[1]), SIGCONT);
						waitpid(atoi(gl[1]), NULL, 0);
					} else {
						fprintf(stderr, "pid must be an integer\n");
					}
				} else {
					fprintf(stderr, "Usage: fg [pid]\n");
				}
			}

			/* Built in list */
			else if(strcmp(gl[0], "list") == 0) {
	    		printf("Executing built-in [%s]\n", gl[0]);
	    		i = 1;
				/* No arguments, print the current working directory */
	    		if(glc < 2) {
	    			list(pwd);
	    		} else {
					/* list each of the arguments passed in */
	        		while(i < glc) {
	            		list(gl[i]);
		    			printf("\n");
		    			i++;
	        		}
	    		}
    		} 

			/* Built in exit */
			else if (strcmp(gl[0], "exit") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
	    		go = 0;
	    		break;
			} 

			/* Built in prompt */
			else if (strcmp(gl[0], "prompt") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
	    		if(glc < 2) {
					/* user didn't enter a prompt so request one */
					printf("input prompt prefix:");
					fgets(prompt, PROMPTMAX, stdin);
					if(prompt[strlen(prompt) - 1] == '\n') {
		    			prompt[strlen(prompt) - 1] = 0;
					}
	    		} else {
					/* set the prompt to be the first argument */
					strncpy(prompt, gl[1], PROMPTMAX);
	    		}
			} 

			/* Built in pwd */
			else if (strcmp(gl[0], "pwd") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
	    		printf(pwd);
	    		printf("\n");
			} 
			
			/* Built in noclobber */
			else if (strcmp(gl[0], "noclobber") == 0){
				if(noclobber == 0) {
					noclobber = 1;
				} else {
					noclobber = 0;
				}
				printf("noclobber is set to %d\n", noclobber);
			}
			/* Built in pid */
			else if (strcmp(gl[0], "pid") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
	    		printf("%d\n", getpid());
			} 

			/* Built in which */
			else if (strcmp(gl[0], "which") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
				if(glc < 2) {
					fprintf(stderr, "which: Too few arguments.\n");
				} else {
					i = 1;
					while(i < glc) {
						char *wh;
						/* call the which function which will check for the command in the path */
	    				wh = which(gl[i], pathlist);
						if(wh == NULL) { 
							fprintf(stderr, "%s: Command not found.\n", gl[i]);
						} else {
							printf("%s\n", wh);
						}
						free(wh);
						i++;
					}
				}	   
			} 

			/* Built in where */
			else if (strcmp(gl[0], "where") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
				if(glc < 2) {
					fprintf(stderr, "where: Too few arguments.\n");
				} else {
					i = 1;
					while(i < glc) {
						where(gl[i], pathlist);
						i++;
					}	
				} 
			}

			/* Built in cd */
			else if (strcmp(gl[0], "cd") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
				if(glc > 2) {
					printf("cd: Too many arguments.\n");
				} else {
	    			char *tmp;	    
					/* tmp will be the new directory or NULL on failure */
	    			tmp = cd(gl[1], homedir, owd);
	    			if(tmp == NULL) {
						break;
	    			} else { 
						free(owd);
						/* set owd to be the old (previous) working directory */
						owd = pwd;
						/* set the new working directory */
						pwd = tmp;
	    			}    
	    			tmp = NULL;
				}
			} 

			/* Built in printenv */
			else if (strcmp(gl[0], "printenv") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
	    		if(glc > 2) {
					fprintf(stderr, "%s: Too many arguments.\n", gl[0]);
	    		} else if (glc > 1) { 
					/* print a particular environmental variable */
					char *tmp;
					tmp = getenv(gl[1]);
					if(tmp == NULL) {
						fprintf(stderr, "%s: Environmental variable not found.\n", gl[1]);
					} else {
						printf("%s\n", tmp);
					}
					tmp = NULL;
	    		} else {
					/* print all environmental variables */
	        		i = 0;
	        		while(environ[i] != NULL) {
		    			printf("%s\n", environ[i]);
		    			i++;
					}
	    		}
			} 

			/* Built in setenv */
			else if (strcmp(gl[0], "setenv") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
				if(glc > 3) {
					fprintf(stderr, "%s: Too many arguments.\n", gl[0]);
				} else if (glc > 2) {
					/* set an environmental variable to the given value */
					setenv(gl[1], gl[2], 1);
				} else if (glc > 1) {
					/* set an environmental variable to an empty value */
					setenv(gl[1], "", 1);
				} else {
					/* print all environmental variables */
					i = 0;
					while(environ[i] != NULL) {
						printf("%s\n", environ[i]);
						i++;
					}
				}
				/* in case we update the home directory */
				homedir = getenv("HOME");
			} 

			/* Built in history */
			else if (strcmp(gl[0], "history") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
				int n = 10;
				/* set how many history records to print */
				if(glc > 1 && atoi(gl[1]) != 0) {
					n = atoi(gl[1]);
				}
				struct pathelement *curr = history;
				/* loop and print past commands */
				while(curr != NULL && n > 0) {
					printf("%s\n", curr->element);
					curr = curr->next;
					n--;
				}
			} 

			/* Built in alias */
			else if (strcmp(gl[0], "alias") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
				if(glc < 2) {
					/* list all aliases */
					struct aliaselement *curr = aliases;
					while(curr != NULL) {
						printf("%s     %s\n", curr->name, curr->command);
						curr = curr->next;
					}
				} else if(glc < 3) {
					/* list a specific alias */
					struct aliaselement *curr = aliases;
					while(curr != NULL) {
						if(strcmp(gl[1], curr->name) == 0) {
							printf("%s\n", curr->command);
						}
						curr = curr->next;
					}
				} else {
					/* add an alias */
					char buf[MAX_CANON];
					snprintf(buf, MAX_CANON, "%s", gl[2]);
					i = 3;
					while(gl[i] != NULL && i < MAXARGS) {
						strcat(buf, " ");
						strcat(buf, gl[i]);
						i++;
					}
					aliases = add_alias(aliases, gl[1], buf);
				}
			} 

			/* Built in kill */
			else if (strcmp(gl[0], "kill") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
				if(glc < 2) {
					fprintf(stderr, "kill: Too few arguments.\n");
				} else if(glc < 3 || strchr(gl[1], '-') == NULL) {
					/* default kill with SIGINT */
					i = 1;
					while(gl[i] != NULL) {
						kill_process(gl[i]);
						i++;
					}
				} else {
					/* kill with the given signal number */
					char *signal;
					signal = strtok(gl[1], "-");
					i = 2;
					while(gl[i] != NULL) {
						kill_process_signal(gl[i], signal);	
						i++;
					}
				}
			} 

			/* MAXARGS handler */
			else if (strcmp(gl[0], "maxargs") == 0) {
	    		fprintf(stderr, "Error: Too many arguments.\n");
			} 

			/* Absolute/Relative paths */
			else if (strncmp(gl[0], "/", 1) == 0 || strncmp(gl[0], "./", 2) == 0 || strncmp(gl[0], "../", 3) == 0) {
				if(access(gl[0], X_OK) == 0) {
					pid_t pid = fork();
					if(pid == -1) {
						perror("fork");
					} else if(pid == 0) {
						/* print what child is executing and execve it */
 	    				printf("Executing [%s]\n", gl[0]);
						
						/* If we are piping this is the command on the left, set standard output to the pipe output */
						if(ipc) {
							close(1);
							dup(pipefd[1]);
							if(ipc_err) {
								close(2);
								dup(pipefd[1]);
							}
							close(pipefd[0]);
							close(pipefd[1]);
						}

						execve(gl[0], gl, environ);
						/* on exec error */
						perror(gl[0]);
						exit(127);
					} else {
						/* if not a background process, wait */
						if(!background) {
							/* If we are piping this is the command on the right. Wait for the first command to finish */
							if(ipc) {
								waitpid(pid, &status, 0);
								pid_t pid2 = fork();
								if(pid2 == -1) {
									perror("fork");
								} else if (pid2 == 0) {
									/* Set stdin to be the pipe input */
									close(0);
									dup(pipefd[0]);
									close(pipefd[1]);
									close(pipefd[0]);
									
									/* Which command should we run */
									char* wh;
									wh = which(pipeargs[0], pathlist);
									if(wh == NULL) {
										fprintf(stderr, "%s: Command not found", pipeargs[0]);
									} else {
										execve(wh, pipeargs, environ);
									}
								} else {
									close(pipefd[0]);
									close(pipefd[1]);
								}
							} else {
								/* wait for chil process */
								waitpid(pid, &status, 0);
								/* if child exits with non-zero status print it */
								if(WEXITSTATUS(status) != 0) {
									printf("Exit: %d\n", WEXITSTATUS(status));
								}
							}
						}
					}
				} else {
					/* path doens't exist */
					fprintf(stderr,"%s: Command not found.\n", gl[0]);
				}
			} 

			/* Executable */
			else {
				char* wh;
				char* wh2;
				/* figure out which executable to execute */
				wh = which(gl[0], pathlist);
				if(wh == NULL) {
					fprintf(stderr, "%s: Command not found.\n", gl[0]);   
				} else {
					pid_t pid = fork();
					if(pid == -1) {
						perror("fork");
					} else if (pid == 0) {
						/* what we are executing */
 	    				printf("Executing [%s]\n", wh);

						/* If we are piping this is the command on the left, set standard output to be the pipe output*/
                        if(ipc) {
                            close(1);
                            dup(pipefd[1]);
							if(ipc_err) {
								close(2);
								dup(pipefd[1]);
							}
                            close(pipefd[0]);
                            close(pipefd[1]);
                        }

						execve(wh, gl, environ);
						/* on execve error */
						perror(wh);
						exit(127);
					} else {
						/* if not a background process, wait */
						if(!background) {

							/* If we are piping this is the command on the right, wait for command on left to finish */
							if(ipc) {
                                waitpid(pid, &status, 0);
                                pid_t pid2 = fork();
                                if(pid2 == -1) {
                                    perror("fork");
                                } else if (pid2 == 0) {
									/* Set standard input to be pipe input */
                                    close(0);
                                    dup(pipefd[0]);
                                    close(pipefd[1]);
                                    close(pipefd[0]);
									/* Which command should we run */
                                    wh2 = which(pipeargs[0], pathlist);
                                    if(wh2 == NULL) {
                                        fprintf(stderr, "%s: Command not found", pipeargs[0]);
                                    } else {
                                        execve(wh2, pipeargs, environ);
                                    }
                                } else {
                                    close(pipefd[0]);
                                    close(pipefd[1]);
                                }
							} else {
								/* wait for child */
								waitpid(pid, &status, 0);
								/* if child exits with nonzero value print it */
								if(WEXITSTATUS(status) != 0){
									printf("Exit: %d\n", WEXITSTATUS(status));
								}
							}
						}
					}
					free(wh);
				} 
    		}
		
			/* reset background */
			background = 0;

			/* reset glob */
			globfree(&globbuf);

			/* reset args */
			free_args(args);
			free_args(pipeargs);

			/* if we redirected file output, reset it to the screen */
			if(file_redirect == 1) {
				file_redirect = 0;
				fid = open("/dev/tty", O_WRONLY);
				close(1);
				dup(fid);
				if(error_redirect == 1) {
					error_redirect = 0;
					close(2);
					dup(fid);
				}
				close(fid);
			}

			/* if we redirected file input, reset it to the keyboard */
			if(input_redirect == 1) {
				input_redirect = 0;
				fid = open("/dev/tty", O_RDONLY);
				close(0);
				dup(fid);
				close(fid);
			}

			ipc = 0;
			ipc_err = 0;

			sleep(1);

			/* Print prompt again */
			printf(prompt);
			printf(" [");
			printf(pwd);
			printf("]> ");
    	}
	}

	/* free allocated memory */
	free(prompt);
	free(commandline);
	free_args(args);
	free_args(pipeargs);
	free(args);
	free(pipeargs);
	free(owd);
	free(pwd);
	struct pathelement *tmp;
	while(pathlist != NULL) {
    	tmp = pathlist->next;
    	free(pathlist);
    	pathlist = tmp;
	}
	while(history != NULL) {
		tmp = history->next;
		free(history->element);
		free(history);
		history = tmp;
	}
	struct aliaselement *temp;
	while(aliases != NULL) {
		temp = aliases->next;
		free(aliases->name);
		free(aliases->command);
		free(aliases);
		aliases = temp;
	}
	struct userelement *tem;
	while(userargs != NULL && userargs->users != NULL) {
		tem = userargs->users->next;
		free(userargs->users->username);
		free(userargs->users);
		userargs->users = tem;
	}
	if(userargs != NULL) {
		pthread_mutex_destroy(&userargs->lock);
		free(userargs);
	}
	globfree(&globbuf);

	return 0;
} /* sh() */
Пример #19
0
void main_loop(pDataStruct workingData){
	char *commandList[] = {"set", "get", "add", "delete","exit","help","ls","cat","cd"};
	char *setList[] = {"date", "user", "group","help"};
	char *getList[] = {"date", "user", "group", "workingDir","help", "userlist", "grouplist", "usersingroup"};
	char *addList[] = {"user", "group", "file", "directory", "usertogroup","perm", "appendfile","help"};
	char *deleteList[] = {"user", "group", "file", "directory", "usertogroup","perm", "filebytes","help"};
	char arg[16][MAXCOMMAND];
	char command[MAXCOMMAND];
	int argnum, i, j, tempNum, cmd, size;
	char *c;
	char temp[MAXPATH];
	char *tempBuf;
	unsigned char *rcvBuf;
	pNode tempNode = NULL;
	pUser tempUser = NULL;
	pGroup tempGroup = NULL;
	pFile tempFile = NULL;
	pPerms tempPerms = NULL;
	pFileChunk tempFileChunk = NULL;
	pGroupUserList tempGroupUserList = NULL;

	while(1){
		argnum = i = j = tempNum = cmd = 0;
		c = 0;
		bzero(temp, sizeof(temp));
		tempBuf = NULL;
		tempNode = NULL;
		tempUser = NULL;
		tempGroup = NULL;
		tempFile = NULL;
		tempPerms = NULL;
		tempFileChunk = NULL;
		tempGroupUserList = NULL;		
		bzero(command, sizeof(command));
		print_prompt(workingData);
		get_string(command, MAXCOMMAND-1, "");
		for (j = 0;j<16;j++){
			bzero(arg[j],MAXCOMMAND);
		}
		argnum = parse_arg(arg, command);
		tempNum = 0;
		cmd = 100;

		for (i=0;i<sizeof(commandList)/4;i++){
			if (strcmp(commandList[i],arg[0]) == 0 ){
				cmd = i;
			}
		}
		switch(cmd)
		{
			case 0x0 : //set
				cmd = 100;
				for (i=0;i<sizeof(setList)/4;i++){
					if (strcmp(setList[i],arg[1]) == 0){
						cmd = i;
					}
				}
				switch(cmd)
				{

					case 0 : //set date
						workingData->date = get_time();
						break;//end set date

					case 1 : //set user

						if ( strcmp(arg[2],"") == 0){
							puts("missing user name or number");
							break;
						}
						tempUser = find_user(arg[2],workingData);
						if ( tempUser != NULL ){
							workingData->currentUser = tempUser;
						} else { 
							printf("unknown user: @s\n",arg[2]);
						}
						break;//end set user

					case 2 : //set group

						if ( strcmp(arg[2], "") == 0){
							puts("missing group name or number");
							break;
						}
						tempGroup = find_group(arg[2], workingData);
						if ( tempGroup != NULL){
							workingData->currentGroup = tempGroup;
						} else {
							printf("unknown group: @s\n",arg[2]);
						}
						break;

					case 3 : //set help
						print_help(setList,(sizeof(setList)/4));
						break;//end set help

					default :
						printf("Invalid command: @s\n",arg[1]);

				}

				break;//end set 

			case 1 ://get
				cmd = 100;
				for (i=0;i<sizeof(getList)/4;i++){
					if (strcmp(getList[i],arg[1]) == 0){
						cmd = i;
					}
				}
				switch(cmd)
				{

					case 0 : //get date
						strofdate( workingData->date);
						break;//end get date

					case 1 : //get user
						printf("@s\n",workingData->currentUser->name);
						break;//end get user

					case 2 : //get group
						printf("@s\n",workingData->currentGroup->name);
						break;//end get group

					case 3 : //get workingDir
						bzero(temp,MAXPATH);
						str_of_path( temp, workingData, workingData->workingDir);
						printf("@s/\n",temp);
						break;//end get workingDir

					case 4 : //get help
						print_help(getList,(sizeof(getList)/4));
						break;//end get help

					case 5 : //get userlist
						print_user_list(workingData);

						break;//end get userlist

					case 6 : //get grouplist
						print_group_list(workingData);
						break;//end get grouplist

					case 7 : //get usersingroup
						if ( strcmp(arg[2], "") == 0){
							puts("missing group name or number");
							break;
						}
						tempGroup = find_group(arg[2], workingData);
						if ( tempGroup != NULL ){
							print_users_in_group(tempGroup);
							break;
						}
						printf("unknown group: @s\n",arg[2]);
						break;//end get useringroup						

					default :
						printf("Invalid command: @s\n",arg[1]);
				}

				break;//end get

			case 2 ://add
				cmd = 100;
				for (i=0;i<sizeof(addList)/4;i++){
					if ( strcmp(addList[i],arg[1]) == 0 ){
						cmd = i;
					}
				}
				switch(cmd)
				{
					case 0 : //add user

						if ( strcmp(arg[2],"") == 0 ){
							bzero(temp,MAXPATH);
							get_string(temp, 128, "UserName");
							strcpy(arg[2],temp);
						}
						tempUser = find_user( arg[2], workingData);
						if ( tempUser == NULL ){
							add_user( arg[2], workingData );
						} else {
							puts("Username already in use");
						}
						break;//end add user

					case 1 : //add group
						if ( strcmp(arg[2],"") == 0 ){
							bzero(temp,MAXPATH);
							get_string(temp, 128, "GroupName");
							strcpy(arg[2], temp);
						}
						tempGroup = find_group( arg[2], workingData);
						if ( tempGroup == NULL ){
							add_group( arg[2], workingData );
						} else {
							puts("Groupname already in use");
						}
						break;//end add group

					case 2 : //add file
						//add file name size
						tempNum = atoi(arg[3]);
						if (strcmp(arg[2],"") == 0){
							puts("Filename required");
							break;
						}
						if ( tempNum > MAXUPLOAD ){
							puts("Too big");
							break;
						}
						if ( find_node_by_name(arg[2],workingData->workingDir->directoryHeadNode) != NULL ){
							puts("There is another file or directory with that name");
							break;
						}
						if ( tempNum > 0){
							rcvBuf = mallocOrDie(tempNum,"Failed to allocate tempBuf");
							puts("-----Begin File-----");//five - 
							if ( tempNum != receive_bytes(rcvBuf,tempNum) ){
								die("Failed to reveive file");
								break;
							}
						} else {rcvBuf = NULL;}
						tempNode = add_file( workingData->workingDir, workingData->date, tempNum, arg[2], (char *)rcvBuf, workingData->currentUser );
						break;//end add file

					case 3 : //add directory

						if (strcmp(arg[2],"") == 0){
							puts("Directory name required");
							break;
						}
						if ( find_node_by_name(arg[2],workingData->workingDir->directoryHeadNode) != NULL ){
							puts("There is another file or directory with that name");
							break;
						}
						tempNode = add_directory( workingData->date, arg[2], workingData->workingDir, workingData->currentUser );
						break;//end add directory

					case 4 : //add useringroup
						if (strcmp(arg[2],"") == 0){
							puts("username or number required");
							break;
						}
						tempUser = find_user( arg[2], workingData);
						if ( tempUser != NULL ){//user exists
							tempGroupUserList = is_user_in_group( tempUser, workingData->currentGroup );
							if ( tempGroupUserList == NULL ){//user is not already in group	
								add_user_to_group( tempUser, workingData->currentGroup );
							} else {printf("@s is already in @s\n",arg[2], workingData->currentGroup->name);}
						} else {
							puts("User does not exist, add user first");
						}

						break;//end add useringroup
						
					case 5 : //add perm
						if (  ( strcmp(arg[2],"") == 0 )||( strcmp(arg[2]," ") == 0 )  ){//arg[2] name of file or dir
							puts("name of file or directory required");
							break;
						}
						if (!(  (strcmp(arg[3],"user") == 0) ^ (strcmp(arg[3],"group") == 0) )) {//arg[3] user, group
							puts("'user' or 'group'");
							break;
						}
						if (strcmp(arg[4],"") == 0){
							puts("user name, group name, or number required");//arg[4] name or number of user or group
							break;
						}
						tempNode = find_node_by_name(arg[2],workingData->workingDir->directoryHeadNode );//validate file or dir
						if (tempNode == NULL){
							puts("Invalid file or directory");
							break;
						}
						if (tempNode->type == LINK){
							tempNode = tempNode->directoryHeadNode;
							break;
						}
						if (strcmp(arg[3],"user") == 0){
							tempUser = find_user(arg[4],workingData);
							tempGroup = NULL;
							if (tempUser == NULL){
								printf("user @s not found\n",arg[4]);
								break;
							}
						} else {
							tempGroup = find_group(arg[4],workingData);
							tempUser = NULL;
							if (tempGroup == NULL){
								printf("group @s not found\n",arg[4]);
								break;
							}
						}

						validate_current_perms(tempNode, workingData);
						tempPerms = add_perm(tempUser, tempGroup, tempNode ); 
						break;//end add perm

					case 6 : //add appendfile
						tempNum = atoi(arg[3]);
						if (strcmp(arg[2],"") == 0){
							puts("Filename required");
							break;
						}
						if ( tempNum > MAXUPLOAD ){
							puts("Too big");
							break;
						}
						tempFile = find_file_by_name(arg[2],workingData->workingDir);
						if (  tempFile == NULL ){
							puts("No file in working directory by that name");
							break;
						}
						if ( tempNum > 0){
							tempBuf = mallocOrDie(tempNum,"Failed to allocate tempBuf");
							puts("-----Begin File-----");//five - 
							if ( tempNum != receive_bytes((unsigned char *)tempBuf,tempNum) ){
								die("Failed to reveive file");
								break;
							}
						} else {
							tempBuf = NULL;
							puts("Can not add 0 bytes to file");
							break;
						}
						tempFileChunk = add_file_chunk( tempBuf, tempFile, tempNum );
						break;//end add appendfile

					case 7 : //add help
						print_help(addList, (sizeof(addList)/4));	
						break;//end add help

					default :
						printf("Invalid command: @s\n",arg[1]);
				}

				break;//end add
			case 3 ://delete 	
				cmd = 100;
				for (i=0;i<sizeof(deleteList)/4;i++){
					if ( strcmp(deleteList[i],arg[1]) == 0 ){
						cmd = i;
					}
				}
				switch(cmd)
				{

					case 0 : //delete user
						bzero(temp,MAXPATH);
						if ( strcmp(arg[2],"") == 0 ){
							get_string(temp, 128, "User Name or number");
							strcpy(arg[2],temp);
						}
						tempUser = find_user( arg[2], workingData);
						if ( tempUser != NULL ){
							remove_user(tempUser , workingData );
						} else {
							puts("No such user found");
						}
						break;//end delete user

					case 1 : //delete group
						bzero(temp,MAXPATH);
						if ( strcmp(arg[2],"") == 0 ){
							get_string(temp, 128, "Group Name or number");
							strcpy(arg[2],temp);
						}
						tempGroup = find_group( arg[2], workingData);
						if ( tempGroup != NULL ){
							remove_group(tempGroup , workingData );
						} else {
							puts("no such group found");
						}
						break;//end delete group 

					case 2 : //delete file 
						if (strcmp(arg[2],"") == 0){
							puts("Filename required");
							break;
						}
						tempNode = find_file_node_by_name(arg[2],workingData->workingDir);
						if (tempNode == NULL){
							puts("No such file");
							break;
						}
						delete_node(tempNode, workingData);
						break;//end delete file 

					case 3 : //delete directory
						if (strcmp(arg[2],"") == 0){
							puts("Directory name required");
							break;
						}
						tempNode = find_directory_by_name(arg[2],workingData->workingDir);
						if (tempNode == NULL){
							puts("No such directory");
							break;
						}
						delete_node(tempNode, workingData);
						break;//end delete directory

					case 4 : //delete usertogroup
						if (strcmp(arg[2],"") == 0){
							puts("User name required");
							break;
						}
						if (strcmp(arg[3],"") == 0){
							puts("group name required");
							break;
						}
						tempUser = find_user(arg[2],workingData);
						if (tempUser == NULL){
							puts("No such user");
							break;
						}
						tempGroup = find_group(arg[3],workingData);
						if (tempGroup == NULL){
							puts("No such group");
							break;
						}
						tempGroupUserList = is_user_in_group(tempUser, tempGroup);
						if (tempGroupUserList == NULL){
							puts("User is not in group");
							break;
						}
						remove_user_from_group(tempUser, tempGroup);
						break;//end delete usertogroup

					case 5 : //delete perm
						if (strcmp(arg[3],"") == 0){
							puts("User or group name required");
							break;
						}
						if (strcmp(arg[2],"") == 0){
							puts("file name required");
							break;
						}
						tempNode = find_node_by_name(arg[2],workingData->workingDir->directoryHeadNode);
						if (tempNode == NULL){
							puts("No such file");
							break;
						}
						tempPerms = find_perm_by_name(arg[3],tempNode,workingData);
						if (tempPerms != NULL){
							delete_perms(tempNode, tempPerms);
						} else {
							puts("No such user permission on file");
						}
						break;//end delete perm

					case 6 : //delete filebytes [file] [numbytes]
						if (strcmp(arg[2],"") == 0){
							puts("Filename required");
							break;
						}
						size = strict_atoi(arg[3]);
						if (size == 0){
							puts("zero bytes deleted");
							break;
						}
						//validate file						
						tempNode = find_file_node_by_name(arg[2],workingData->workingDir);
						tempFile = tempNode->file;
						if (tempNode == NULL){
							puts("No such file");
							printf("@s\n",arg[2]);
							break;
						}
						tempNum = get_file_size(tempFile);
						if (size > tempNum){
							puts("Too many bytes");
						} 
						//tempNum is new file size
						tempNum = tempNum - size;
						delete_file_bytes(tempFile, tempNum);
						break;//end delete file 

					case 7 : //delete help
						print_help(deleteList, (sizeof(deleteList)/4));	
						break;//end delete help

					default:
						print_help(deleteList, (sizeof(deleteList)/4));	
						//break;//end delete help

				}
				break;//end delete
				

			case 4 ://cgc_exit
				puts("exiting");
				goto cgc_exit;
				break;

			case 5 ://help
				print_help(commandList, (sizeof(commandList)/4));
				break;
			case 6 ://ls
				print_working_dir(workingData);
				break;
			case 7 ://cat
				if (strcmp(arg[1],"") == 0){
					puts("Filename required");
					break;
				}
				tempFile = find_file_by_name(arg[1], workingData->workingDir);							
				if ( tempFile != NULL ){
					tempFileChunk = tempFile->head;
					puts("-----Begin File-----");//five - 
					while ( tempFileChunk != NULL ){
						if (tempFileChunk->chunkSize != cgc_write(tempFileChunk,tempFileChunk->chunkSize)){
							puts("file write failed");
						}
/*
						c = tempFileChunk->chunk;
						for ( i = 0; i < tempFileChunk->chunkSize; i++ ){//putc each byte of every chunk
							putc( *c);
							c++;
						}
*/						
						tempFileChunk = tempFileChunk->next;	
					}
					puts("-----END File-----");//five - 
				}
				break;
			case 8 ://cd
				if (strcmp(arg[1],"") == 0){
					puts("directory required");
					break;
				}
				if (strcmp(arg[1],"..") == 0){
					if (workingData->workingDir->parent != NULL){
						workingData->workingDir = workingData->workingDir->parent;
					}
					break;
				}
				tempNode = find_directory_by_name(arg[1],workingData->workingDir);
				if ( tempNode != NULL ){
					workingData->workingDir = tempNode;
					break;
				}
				puts("No such directory in working directory");
				break;//end cd

			default :
				printf("Invalid command @s\n",arg[0]);
				print_help(commandList, (sizeof(commandList)/4));
				
		}
	}
	cgc_exit:
	return;
}
void main(){
	ul *list = (ul *) malloc (sizeof(ul));
	make_user_list(list);
	printf("\n\n");
	printf("------------------------Seja bem-vindo---------------------------------- \n\n\n");
	int run = 1;
	int op;
	char name[50] ;
	char name1[50] ;
	user *u = NULL;

	while (run == 1){

		printf("Escolha sua opção: \n");
		printf("1 - Cadastrar novo usuário.\n");
		printf("2 - Remover um contato.\n");
		printf("3 - Criar amizade.\n"); 
		printf("4 - Desfazer amizade.\n"); 
		printf("5 - Imprimir dados de um usuário.\n");
		printf("6 - Imprimir dados de todos os usuários.\n");
		printf("7 - Sair.\n\n");
		printf("Opção: ");

		scanf ("%d", &op);


		switch (op){	
			case 1:
				printf("\n\n");
				u = make_user();
				add_user(list,u);
				free(u);
				u = NULL;
				break;
			case 2:
				printf("Informe o nome do usuário que quer remover: ");
				scanf("%s",&name);
				remove_user(list, name);
				break;
			case 3:
				printf("Informe o nome de uma das pessoas: ");
				scanf("%s",&name);
				printf("Informe o nome de uma outra pessoa: ");
				scanf("%s",&name1);
				add_contact(list, name, name1);
				break;
			case 4: 
				printf("Informe o nome de uma das pessoas: ");
				scanf("%s",&name);
				printf("Informe o nome de uma outra pessoa: ");
				scanf("%s",&name1);
				remove_contact(list, name, name1);
				break;
			case 5:
				printf("Informe o nome do usuário que quer imprimir os dados: ");
				scanf("%s",&name);
				print_info(list, name);
				break;
			case 6:
				print_list_user(list);
			case 7:
				run = 2;
				printf("\n\n\n");
				printf("Até logo.\n");
				// exit(0);
				break;
		}
	}
	exit(0);
}