示例#1
0
/*
Creates a list of length 'len' and fills it with value 'value'.
Returns the 'len' if everything went ok , and -1 if
there was a problem allocating memory.
*/
int fill_list(int len, TYPE_ value, NODE **Head) {
  NODE *p;
  int i;

  if (!del_list(Head))
    return -1;
  if (len < 1)
    return -1;

  *Head = malloc(sizeof(NODE));
  if (*Head == NULL)
    return -1;
  (*Head)->num = value;
  (*Head)->next = NULL;

  p = *Head;
  for (i = 0; i < len - 1; i++) {
    p->next = malloc(sizeof(NODE));
    if (p->next == NULL)
      return -1;
    p = p->next;
    p->num = value;
  }
  p->next = NULL;
  return len;
}
示例#2
0
bool_t flush_fonts(void)
{
    font_node_t *fontnode;
    hash_search_t  sptr;
    list_t delete_list;
    list_elem_t elem;
    char *key;
    bool_t result;

    delete_list = create_list();
  
    begin_hash_scan(font_table, &sptr);
    while ( next_hash_entry(sptr, &key, (hash_entry_t*)(&fontnode)) ) {
	if (fontnode->ref_count == 0) {
	    elem = insert_list_elem(delete_list, NULL, (list_elem_data_t)key);
	}
    }
    end_hash_scan(sptr);

    elem = get_list_head(delete_list);
    while (elem != NULL) {
	key = (char*)get_list_elem_data(elem);

	result = del_font( key );
	check_assertion(result, "Attempt to flush non-existant font");

	elem = get_next_list_elem(delete_list, elem);
    }

    del_list(delete_list);

    return True;

}
void creat(stud** h)
{stud *head,*p1,*p2;
 head=NULL;
 p1=p2=(stud *)malloc(sizeof(stud));
 if(p1==NULL)
   {printf("no space.\n");
    *h=NULL;
    return;
   }
 scanf("%d,%d",&p1->n,&p1->score);
 while(p1->n!=0)
    {if(head==NULL)
       head=p1;
     else
       p2->next=p1;
     p2=p1;
     p2->next=NULL;
     p1=(stud*)malloc(sizeof(stud));
     if(p1==NULL)
       {printf("no space.\n");
        del_list(head);
        *h=NULL;
        return;
       }
     scanf("%d,%d",&p1->n,&p1->score);
    }
 free(p1);
 *h=head;
}
示例#4
0
/*
Takes the array pointed to by arr and saves its values in a linked list.
It can be used to simulate the Python's syntax : my_list = [1,2,3,4]
WARNING: arr MUST have as a last value the character '\0' !!! .
*/
int set_list(TYPE_ arr[], NODE **Head) {
  if (!del_list(Head))
    return -1;

  if (!arr[0]) {
    *Head = NULL;
    return 1;
  }

  *Head = malloc(sizeof(NODE));
  if (*Head == NULL)
    return -1;

  (*Head)->num = arr[0];
  (*Head)->next = NULL;

  NODE *p = *Head;
  int i;
  for (i = 1; arr[i]; i++) {
    p->next = malloc(sizeof(NODE));
    if (p->next == NULL)
      return -1;
    p = p->next;
    p->num = arr[i];
  }
  p->next = NULL;
  return 1;
}
示例#5
0
// меню работы с выписками
void ref_menu(refferal **ref_head, refferal **ref_tail, node *doc, hash_tab *pat)
{
	bool end(false); // флаг остановки работы(возврат в главное меню)
	svector_ref search; // вектор найденных записей направлений
	svector_doc search_doc; // вектор найденных данных врачей
	int choice; // выбор критерия

	while(!end) 
	{
		system("cls");
		cout<<"======== Работа с направлениями ========\n"
			<<" 1. Добавить новое направление\n"
			<<" 2. Возврат направления\n"
			<<" 3. Список всех направлений\n"
			<<" 4. Удаление данных всех направлений\n"
			<<" 0. Назад в меню\n"
			<<"========================================\n"
			<<"\nВведите команду: ";
		choice = input_control(4, 0);
		if (!(*ref_head) && (choice >= 2 && choice <= 4))
		{
			cout << "\nБД направлений пуста! Пункты #2 - #4 недоступны.\n";
			system("pause");
			choice = -1;
		}
		switch(choice)
		{
		case 1:
			cout<<" Регистрация направления:\n";
			add_to_list(ref_head, ref_tail, doc, pat, search_doc);
			cout << "\n=== Направление добавлено ===\n";
			system("pause");
			break;
		case 2:
			del_ref_menu(ref_head, ref_tail);
			system("pause");
			break;
		case 3:
			cout<<" Список всех направлений:\n";
			print_list(*ref_head, pat);
			system("pause");
			break;
		case 4:
			del_list(ref_head, ref_tail);
			cout<<" Записи удалены.\n";
			system("pause");
			break;
		case 0:
			end = true;
			break;
		default:
			break;
		}
		search.clear();
		search.shrink_to_fit();
		search_doc.clear();
		search_doc.shrink_to_fit();
	}
}
示例#6
0
文件: graph.c 项目: gatlin/markov
void del_vertex(Vertex *v) {
    del_list(v->edges ); /* Free the adjacency list */
    if (v->payload != NULL) { /* Don't free NULL pointers */
        free(v->payload);
    }
    free (v);
    return;
}
示例#7
0
int main(void) {
	struct item *ptr = NULL;
	ptr = main_menu(ptr);
	if(ptr != NULL) {
		ptr = del_list(ptr);
	}
	return 0;
}
int main(int argc,char *argv[])
{
	int total,m;
	struct monkey *head;
	printf("Input the monkey numbe you want:\n");
	scanf("%d",&total);
	printf("Input the monkey you want to get out:\n"); 
	scanf("%d",&m);
	head=del_list(create_list(total),m,total);
	print(head);
	return 0;
}
示例#9
0
文件: ft_hdel.c 项目: JeanMax/fillit
void			ft_hdel(t_htable **table)
{
	t_hnode	**bucket;

	bucket = (*table)->bucket;
	while ((*table)->bucket_size--)
	{
		if (*bucket)
			del_list(*table, *bucket);
		bucket++;
	}
	ft_memdel((void *)&(*table)->bucket);
	ft_memdel((void *)table);
}
示例#10
0
void		ft_lstdel(t_list **begin, t_list *elem)
{
	t_list		*cur;

	if (elem == NULL || *begin == NULL)
		return ;
	cur = *begin;
	if (cur == elem)
	{
		*begin = NULL;
		del_list(elem);
		return ;
	}
}
示例#11
0
void del_dir(void)
{	system("cls");
	int num,m=0,*v;//用一个m来数到底有多少个数据 
	char choice;
	FILE *fout,*fin;
	team *fp,*head;
	v=&m;
	fp=head=find_list();
	if((fout=fopen("F:\\lol_info_table.dat","ab+"))==NULL)
	{
		printf("open the file error");
		exit(-1);
	}
	while(!feof(fout))
	{
		if(fread(fp,sizeof(team),1,fout)==1)
		m++;
		fp=fp->next;
	}
	fclose(fout);//fp没用了 
	while(TRUE)
	{
	printf("Input the number you want to delete:\n");
	scanf("%d",&num);
	getchar();
	head=del_list(head,num,m,v);
	printf("If you want to continue delete?(y/n)\n");
	scanf("%c",&choice);
	getchar();
	if(choice=='y'||choice=='Y')
	;
	else 
		break;
	}
	if((fin=fopen("F:\\lol_info_table.dat","wb"))==NULL)
	{
		printf("Open the file failed!\n");
		exit(-1);	
	}
	for(fp=head;m>0;m--)
	{
		if(fwrite(fp,sizeof(team)-4,1,fin)!=1)
		{
		printf("can not save");
		exit(-1);
		}
		fp=fp->next;
	}
	fclose(fin);
}
示例#12
0
/*
    clear_table
        frees the memory allocated for the lists array in the hash table
    param:  
        hash_table_t* hash_table (the hash table whose lists array must be freed)
    return:
        void
*/
int clear_table(hash_table_t* hash_table)
{
    if(!hash_table || !(hash_table->lists))return -1;
    
    //for each list in the hashtable's lists array,
    //free the list
    uint64_t size = hash_table->table_size;
    uint64_t i = 0;
    for(; i < size; ++i)
    {
        del_list(&(hash_table->lists[i]));
    }
    //free the memory allocated for the now-cleared table
    free(hash_table->lists);
    hash_table->lists = NULL;

    return 0;
}
示例#13
0
t_listp			*init_path(t_listp *env)
{
  int			i;
  int			j;
  t_listp		*path;
  t_listp		*tmp;

  i = 0;
  j = 0;
  tmp = search_lchar_elem(env, "PATH=", 5);
  while (tmp->beg->data && tmp->beg->data[i - 1] != '=')
    i++;
  while (tmp->beg->data && tmp->beg->data[i])
    tmp->beg->data[j++] = tmp->beg->data[i++];
  tmp->beg->data[j++] = 0;
  tmp->beg->data[j] = 0;
  path = cut_the_path(tmp->beg->data);
  del_list(tmp);
  return (path);
}
示例#14
0
文件: trade.c 项目: Hooman3/minix
/*
 *	This routine does a switch from one player to another
 */
static void
move_em(TRADE *from, TRADE *to)
{
	PLAY *pl_fr, *pl_to;
	OWN *op;

	pl_fr = &play[from->trader];
	pl_to = &play[to->trader];

	pl_fr->money -= from->cash;
	pl_to->money += from->cash;
	pl_fr->num_gojf -= from->gojf;
	pl_to->num_gojf += from->gojf;
	for (op = from->prop_list; op; op = op->next) {
		add_list(to->trader, &(pl_to->own_list), sqnum(op->sqr));
		op->sqr->owner = to->trader;
		del_list(from->trader, &(pl_fr->own_list), sqnum(op->sqr));
	}
	set_ownlist(to->trader);
}
示例#15
0
void		replay_directory(t_item *items, t_args *args)
{
	t_item 	*start;
	int		i;
	
	start = NULL;
	start = get_start(items);
	i = 0;
	while (items)
	{
		if (items->child)
		{
			if (i == 1)
				ft_putchar('\n');
			ft_get_items(args, items->name, 1);
			i = 1;
		}
		items = items->next;
	}
	del_list(&start, 0);
}
示例#16
0
文件: list_test.c 项目: antontest/c
/*********************************************************
 ******************    Main Function    ******************
 *********************************************************/
int main(int agrc, char *agrv[])
{
    int rt = 0; /* return value of function main */
    plist h = NULL;
    int num = 99;

    h = list_add(h, &num, sizeof(int));
    num = 100;
    h = list_add(h, &num, sizeof(int));
    num = 102;
    h = list_add(h, &num, sizeof(int));
    num = 101;
    h = list_add(h, &num, sizeof(int));
    printf("sort before:\n");
    print_list(h);
    h = bubble_sort(h);
    printf("sort after:\n");
    print_list(h);
    del_list(h);

    return rt;
}
示例#17
0
文件: ll19.c 项目: jleffler/soq
int main(void)
{
    value *node1;

    prt_forwards("Empty");

    node1 = new_node(23);
    ins_tail(node1);
    prt_backwards("Tail 23");

    node1 = new_node(29);
    ins_head(node1);
    prt_forwards("Head 29");

    value *node2 = new_node(31);
    ins_head(node2);
    prt_forwards("Head 31");

    node1 = new_node(37);
    ins_after(node2, node1);
    prt_backwards("37 after 31");

    node1 = new_node(41);
    ins_after(node2, node1);
    prt_forwards("41 after 31");

    node1 = new_node(43);
    ins_before(node2, node1);
    prt_forwards("43 before 31");

    node1 = new_node(47);
    ins_before(node2, node1);
    prt_forwards("47 before 31");

    del_list();
    prt_backwards("Empty");

    return 0;
}
示例#18
0
文件: list_ub.c 项目: kkzinger/SWE
int main()
{
	HEAD *head;
	int a=15,b=10, c=23;
	int *ptra, *ptrb, *ptrc;

	ptra = &a;
	ptrb = &b;
	ptrc = &c;


	if((head=init_list()) == NULL)
	{
		fprintf(stdout,"Error at list_init()");
		return EXIT_FAILURE;
	}


//	print_list(head);
	append_front(head,ptra);
	print_list(head);
	append_back(head,ptrb);
	print_list(head);
	insert_node(head,head->first,ptrc);
	print_list(head);
	insert_node(head,head->last,ptrc);
	print_list(head);

	printf("DATA: %d\n",*((int*)head->first->data));

	del_node(head, head->first->next);
	print_list(head);

	del_list(head);
	return 0;
}
示例#19
0
int main(int argc, char **argv)
{
	int i, modus=0;
	char *filepath_source = NULL,*filepath_result = NULL;
	HEAD *list_pt;
	//Read programm parameters

	if(argc <= 1)
        {
                fprintf(stderr,"To few options for function!");
                return EXIT_FAILURE;
        }

	for(i=1;i<argc;i++)
        {
                if(strcmp(argv[i],"-f") == 0) //Sourcefile path
                {
			filepath_source = (char*) malloc(strlen(argv[i]));

                        if(i+1 < argc)
			{
				i++;
				filepath_source = argv[i];
			}else
			{
		                fprintf(stderr,"To few arguments for option '-f'!");
			}

                }else if(strcmp(argv[i],"-o") == 0) //Option if Output should be stored in File
                {
                        filepath_result = (char*) malloc(strlen(argv[i]));
                        modus = 1;

                        if(i+1 < argc)
			{
				i++;
				filepath_result = argv[i];
			}else
			{
				strcpy(filepath_result,"output.txt");
			}

                }else if(strcmp(argv[i],"--help") == 0) //Option that show help text
                {
                        printf("\n\n-- txt_analyse -- \n  is designed to provide a List of the words contained in a Text and how often they appear.\n");
			printf("\n\nOPTIONS\n");
			printf("   -f path of textfile wich should be analysed\n");
			printf("   -o path of the output file where results will be stored\n");
			printf("\n\n   if there is no name present after -o the standard output file is 'output.txt'\n");
			printf("   if option '-o' is not provided output will be on 'stdout'\n");
			printf("\nEXAMPLE\n");
			printf("   ./txt_analyse -f input_text.txt -o result.txt\n\n\n");
			return EXIT_SUCCESS;
                }

        }

	if((list_pt = init_list()) == NULL) 
	{
		fprintf(stderr,"Failed to init List Header\n");
		return EXIT_FAILURE;
	}
	if(txt_analyse(list_pt,filepath_source) == EXIT_FAILURE)
	{
		fprintf(stderr,"Failed to analyse text\n");
		return EXIT_FAILURE;
	}

//	print_list(list_pt);

	print_result(list_pt,modus,filepath_result);

	del_list(list_pt);
	return EXIT_SUCCESS;
}
	/********************************************************************
	 Copyright (C), 2015-2016,
	 FunctonName:Chose
	 Description:选项
	 Parameter: void
	 Returns: void
	 Access: nullnullnull
	 Author: jackwu
	 Created: 2015/09/14
	 history: 14:9:2015 11:43 byjackwu
	*********************************************************************/
void Chose()
{
	int i;
	char key='#';
	scanf_s("%d",&i);
	switch(i)
	{
	case 0:
		{
		 //创建
			//_head=Create_Student_List();//创建链表成功
			_head=Create_Student_List();
			//_head->name=NULL;
			//_head->num=NULL;
			system("cls");
			gotoxy(18,10);
			printf("创建成功!");
			gotoxy(18,11);
			printf("按esc键返回");
			fflush(stdin);
			while(1)
			{    ////
				if(_kbhit())
				{
					key=_getch();
					if(key==27)
					{
						Func_Esc();
					}
					else
					{  
						system("cls");
						MainMenu();
						break;
					}
				}
				///
			}
			break;
		
		}
	case 1:
		{
			//加载学生的信息
			FILE *fp;
			//char name[10];
			//char num[10];
			char xiaofei[30];
		    
			if((fp=fopen("student.txt","r"))!=NULL)
				while(feof(fp)!=EOF)
				{
				   // fscanf_s(fp,"%s,%s,%s\n",name,num,xiaofei);
					//fwrite(p,sizeof(struct _student_),1,fp);
					//fscanf_s(fp,"姓名:%s",p->name);
					fgets(xiaofei,1,fp);
					//printf("%s\n%s\n%s\n",name,num,xiaofei);
					printf("%s\n",xiaofei);


				}
			fclose(fp);
			break;
	
		}
	case 2:
		{
			//查找
			char num[10];
			int tag;
			memset(num,'\0',sizeof(num));
		
			printf("输入学生的学号:");
			//scanf_s("%s",num);
			fflush(stdin);
			gets(num);
			system("cls");
			tag=find_element(_head,num);
			if(tag)
			{   
				//system("cls");
		        printf("查找成功!\n");
				gotoxy(18,9);
				printf("按esc键返回");
				fflush(stdin);
				while(1)
				{
					if(_kbhit())
					{
						key=_getch();
						if(key==27)
						{
							Func_Esc();
						}
						else
						{  
							system("cls");
							MainMenu();
							break;
						}
					}
				}
			}
			break;

		}
	case 3:
		{
			//删除
			char num[10];
			int tag;
			memset(num,'\0',sizeof(num));

			printf("输入学生的学号:");
			//scanf_s("%s",num);
			fflush(stdin);
			gets(num);
			system("cls");
			if(del_list(_head,num))
			{
		          printf("删除成功!\n");
				  gotoxy(18,9);
				  printf("按esc键返回");
				  fflush(stdin);
				  while(1)
				  {
					  if(_kbhit())
					  {
						  key=_getch();
						  if(key==27)
						  {
							  Func_Esc();
						  }
						  else
						  {  
							  system("cls");
							  MainMenu();
							  break;
						  }
					  }
				  }
			}
			break;
		}
	case 4:
		{
			//增加学生的信息
			pzstudent p=Create_Student();

			if(Add(_head,*p))
			{  
                system("cls");
				gotoxy(18,8);
				printf("添加学生的信息成功!");
				gotoxy(18,9);
				printf("按esc键返回");
				fflush(stdin);
				while(1)
				{
					if(_kbhit())
					{
						key=_getch();
						if(key==27)
						{
							Func_Esc();
						}
						else
						{  
							system("cls");
							MainMenu();
							break;
						}
					}
				}

			}
			break;
		}
	case 5:
		{
			//遍历信息
			system("cls");
			Printf_StudentInfo(_head);
			gotoxy(18,11);
			printf("按esc键返回");
			fflush(stdin);
			while(1)
			{
				if(_kbhit())
				{
					key=_getch();
					if(key==27)
					{
						Func_Esc();
					}
					else
					{  
						system("cls");
						MainMenu();
						break;
					}
				}
			}
		}
	case 6:
		{
			//保存学生的信息
			FILE *fp;
			pzstudent p,q;
			p=_head->next;
			if(!(fp=fopen("student.txt","w+")))
			{
			 printf("cant open file");
			 exit(0);
			}
			while(p->next)
			{
			        fprintf(fp,"姓名:%s,学号:%s,消费:%d\n",p->name,p->num,p->xiaofei);
					p=p->next;
			}
			fprintf(fp,"姓名:%s,学号:%s,消费:%d\n",p->name,p->num,p->xiaofei);

			fclose(fp);
			system("cls");
			printf("保存学生的信息成功!");
			gotoxy(18,9);
			printf("按esc键返回");
			fflush(stdin);
			while(1)
			{
				if(_kbhit())
				{
					key=_getch();
					if(key==27)
					{
						Func_Esc();
					}
					else
					{  
						system("cls");
						MainMenu();
						break;
					}
				}
			}
			break;

		}
	case 7:
		{
			Func_Esc();
			break;
		}
	default:
		{
			break;
		}
		

	}
}
示例#21
0
文件: userdel.c 项目: bfeeny/shadow
/*
 * update_groups - delete user from secondary group set
 *
 *	update_groups() takes the user name that was given and searches
 *	the group files for membership in any group.
 *
 *	we also check to see if they have any groups they own (the same
 *	name is their user name) and delete them too (only if USERGROUPS_ENAB
 *	is enabled).
 */
static void update_groups (void)
{
	const struct group *grp;
	struct group *ngrp;

#ifdef	SHADOWGRP
	const struct sgrp *sgrp;
	struct sgrp *nsgrp;
#endif				/* SHADOWGRP */

	/*
	 * Scan through the entire group file looking for the groups that
	 * the user is a member of.
	 */
	for (gr_rewind (), grp = gr_next (); NULL != grp; grp = gr_next ()) {

		/*
		 * See if the user specified this group as one of their
		 * concurrent groups.
		 */
		if (!is_on_list (grp->gr_mem, user_name)) {
			continue;
		}

		/*
		 * Delete the username from the list of group members and
		 * update the group entry to reflect the change.
		 */
		ngrp = __gr_dup (grp);
		if (NULL == ngrp) {
			fprintf (stderr,
			         _("%s: Out of memory. Cannot update %s.\n"),
			         Prog, gr_dbname ());
			exit (13);	/* XXX */
		}
		ngrp->gr_mem = del_list (ngrp->gr_mem, user_name);
		if (gr_update (ngrp) == 0) {
			fprintf (stderr,
			         _("%s: failed to prepare the new %s entry '%s'\n"),
			         Prog, gr_dbname (), ngrp->gr_name);
			exit (E_GRP_UPDATE);
		}

		/*
		 * Update the DBM group file with the new entry as well.
		 */
#ifdef WITH_AUDIT
		audit_logger (AUDIT_DEL_USER, Prog,
		              "deleting user from group",
		              user_name, (unsigned int) user_id,
		              SHADOW_AUDIT_SUCCESS);
#endif				/* WITH_AUDIT */
		SYSLOG ((LOG_INFO, "delete '%s' from group '%s'\n",
			 user_name, ngrp->gr_name));
	}

	if (getdef_bool ("USERGROUPS_ENAB")) {
		remove_usergroup ();
	}

#ifdef	SHADOWGRP
	if (!is_shadow_grp) {
		return;
	}

	/*
	 * Scan through the entire shadow group file looking for the groups
	 * that the user is a member of. Both the administrative list and
	 * the ordinary membership list is checked.
	 */
	for (sgr_rewind (), sgrp = sgr_next ();
	     NULL != sgrp;
	     sgrp = sgr_next ()) {
		bool was_member, was_admin;

		/*
		 * See if the user specified this group as one of their
		 * concurrent groups.
		 */
		was_member = is_on_list (sgrp->sg_mem, user_name);
		was_admin = is_on_list (sgrp->sg_adm, user_name);

		if (!was_member && !was_admin) {
			continue;
		}

		nsgrp = __sgr_dup (sgrp);
		if (NULL == nsgrp) {
			fprintf (stderr,
			         _("%s: Out of memory. Cannot update %s.\n"),
			         Prog, sgr_dbname ());
			exit (13);	/* XXX */
		}

		if (was_member) {
			nsgrp->sg_mem = del_list (nsgrp->sg_mem, user_name);
		}

		if (was_admin) {
			nsgrp->sg_adm = del_list (nsgrp->sg_adm, user_name);
		}

		if (sgr_update (nsgrp) == 0) {
			fprintf (stderr,
			         _("%s: failed to prepare the new %s entry '%s'\n"),
			         Prog, sgr_dbname (), nsgrp->sg_name);
			exit (E_GRP_UPDATE);
		}
#ifdef WITH_AUDIT
		audit_logger (AUDIT_DEL_USER, Prog,
		              "deleting user from shadow group",
		              user_name, (unsigned int) user_id,
		              SHADOW_AUDIT_SUCCESS);
#endif				/* WITH_AUDIT */
		SYSLOG ((LOG_INFO, "delete '%s' from shadow group '%s'\n",
		         user_name, nsgrp->sg_name));
	}
#endif				/* SHADOWGRP */
}
示例#22
0
/*
 * gpasswd - administer the /etc/group file
 */
int main (int argc, char **argv)
{
	struct group grent;
#ifdef SHADOWGRP
	struct sgrp sgent;
#endif
	struct passwd *pw = NULL;

#ifdef WITH_AUDIT
	audit_help_open ();
#endif

	sanitize_env ();
	(void) setlocale (LC_ALL, "");
	(void) bindtextdomain (PACKAGE, LOCALEDIR);
	(void) textdomain (PACKAGE);

	/*
	 * Make a note of whether or not this command was invoked by root.
	 * This will be used to bypass certain checks later on. Also, set
	 * the real user ID to match the effective user ID. This will
	 * prevent the invoker from issuing signals which would interfere
	 * with this command.
	 */
	bywho = getuid ();
	Prog = Basename (argv[0]);

	OPENLOG ("gpasswd");
	setbuf (stdout, NULL);
	setbuf (stderr, NULL);

#ifdef SHADOWGRP
	is_shadowgrp = sgr_file_present ();
#endif

	/*
	 * Determine the name of the user that invoked this command. This
	 * is really hit or miss because there are so many ways that command
	 * can be executed and so many ways to trip up the routines that
	 * report the user name.
	 */
	pw = get_my_pwent ();
	if (NULL == pw) {
		fprintf (stderr, _("%s: Cannot determine your user name.\n"),
		         Prog);
		SYSLOG ((LOG_WARN,
		         "Cannot determine the user name of the caller (UID %lu)",
		         (unsigned long) getuid ()));
		exit (E_NOPERM);
	}
	myname = xstrdup (pw->pw_name);

	/*
	 * Register an exit function to warn for any inconsistency that we
	 * could create.
	 */
	if (atexit (do_cleanups) != 0) {
		fprintf(stderr, "%s: cannot set exit function\n", Prog);
		exit (1);
	}

	/* Parse the options */
	process_flags (argc, argv);

	/*
	 * Replicate the group so it can be modified later on.
	 */
#ifdef SHADOWGRP
	get_group (&grent, &sgent);
#else
	get_group (&grent);
#endif

	/*
	 * Check if the user is allowed to change the password of this group.
	 */
#ifdef SHADOWGRP
	check_perms (&grent, &sgent);
#else
	check_perms (&grent);
#endif

	/*
	 * Removing a password is straight forward. Just set the password
	 * field to a "".
	 */
	if (rflg) {
		grent.gr_passwd = "";	/* XXX warning: const */
#ifdef SHADOWGRP
		sgent.sg_passwd = "";	/* XXX warning: const */
#endif
		goto output;
	} else if (Rflg) {
		/*
		 * Same thing for restricting the group. Set the password
		 * field to "!".
		 */
		grent.gr_passwd = "!";	/* XXX warning: const */
#ifdef SHADOWGRP
		sgent.sg_passwd = "!";	/* XXX warning: const */
#endif
		goto output;
	}

	/*
	 * Adding a member to a member list is pretty straightforward as
	 * well. Call the appropriate routine and split.
	 */
	if (aflg) {
		printf (_("Adding user %s to group %s\n"), user, group);
		grent.gr_mem = add_list (grent.gr_mem, user);
#ifdef SHADOWGRP
		if (is_shadowgrp) {
			sgent.sg_mem = add_list (sgent.sg_mem, user);
		}
#endif
		goto output;
	}

	/*
	 * Removing a member from the member list is the same deal as adding
	 * one, except the routine is different.
	 */
	if (dflg) {
		bool removed = false;

		printf (_("Removing user %s from group %s\n"), user, group);

		if (is_on_list (grent.gr_mem, user)) {
			removed = true;
			grent.gr_mem = del_list (grent.gr_mem, user);
		}
#ifdef SHADOWGRP
		if (is_shadowgrp) {
			if (is_on_list (sgent.sg_mem, user)) {
				removed = true;
				sgent.sg_mem = del_list (sgent.sg_mem, user);
			}
		}
#endif
		if (!removed) {
			fprintf (stderr,
			         _("%s: user '%s' is not a member of '%s'\n"),
			         Prog, user, group);
			exit (E_BAD_ARG);
		}
		goto output;
	}
#ifdef SHADOWGRP
	/*
	 * Replacing the entire list of administrators is simple. Check the
	 * list to make sure everyone is a real user. Then slap the new list
	 * in place.
	 */
	if (Aflg) {
		sgent.sg_adm = comma_to_list (admins);
		if (!Mflg) {
			goto output;
		}
	}
#endif				/* SHADOWGRP */

	/*
	 * Replacing the entire list of members is simple. Check the list to
	 * make sure everyone is a real user. Then slap the new list in
	 * place.
	 */
	if (Mflg) {
#ifdef SHADOWGRP
		sgent.sg_mem = comma_to_list (members);
#endif
		grent.gr_mem = comma_to_list (members);
		goto output;
	}

	/*
	 * If the password is being changed, the input and output must both
	 * be a tty. The typical keyboard signals are caught so the termio
	 * modes can be restored.
	 */
	if ((isatty (0) == 0) || (isatty (1) == 0)) {
		fprintf (stderr, _("%s: Not a tty\n"), Prog);
		exit (E_NOPERM);
	}

	catch_signals (0);	/* save tty modes */

	(void) signal (SIGHUP, catch_signals);
	(void) signal (SIGINT, catch_signals);
	(void) signal (SIGQUIT, catch_signals);
	(void) signal (SIGTERM, catch_signals);
#ifdef SIGTSTP
	(void) signal (SIGTSTP, catch_signals);
#endif

	/* Prompt for the new password */
#ifdef SHADOWGRP
	change_passwd (&grent, &sgent);
#else
	change_passwd (&grent);
#endif

	/*
	 * This is the common arrival point to output the new group file.
	 * The freshly crafted entry is in allocated space. The group file
	 * will be locked and opened for writing. The new entry will be
	 * output, etc.
	 */
      output:
	if (setuid (0) != 0) {
		fputs (_("Cannot change ID to root.\n"), stderr);
		SYSLOG ((LOG_ERR, "can't setuid(0)"));
		closelog ();
		exit (E_NOPERM);
	}
	pwd_init ();

	open_files ();

#ifdef SHADOWGRP
	update_group (&grent, &sgent);
#else
	update_group (&grent);
#endif

	close_files ();

	nscd_flush_cache ("group");

	exit (E_SUCCESS);
}
示例#23
0
/*!
 Creates a cup_data_t object from a Tcl string.
 \return  New cup_data_t object if successful, or NULL if error
 \author  jfpatry
 \date    Created:  2000-09-19
 \date    Modified: 2000-09-19
 */
static
cup_data_t* create_cup_data( Tcl_Interp *ip, const char *string, char **err_msg )
{
    const char **argv = NULL;
    const char **orig_argv = NULL;
    int argc = 0;

    char *name = NULL;
    char *icon = NULL;
    list_t race_list = NULL;
    list_elem_t last_race = NULL;
    const char **races = NULL;
    int num_races = 0;
    int i;

    cup_data_t *cup_data = NULL;

    if ( Tcl_SplitList( ip, string, &argc, &argv ) == TCL_ERROR ) {
        *err_msg = "cup data is not a list";
        goto bail_cup_data;
    }

    orig_argv = argv;

    while ( *argv != NULL ) {
        if ( strcmp( *argv, "-name" ) == 0 ) {
            NEXT_ARG;

            if ( *argv == NULL ) {
                *err_msg = "No data supplied for -name in cup data";
                goto bail_cup_data;
            }

            name = string_copy( *argv );
        } else if ( strcmp( *argv, "-icon" ) == 0 ) {
            NEXT_ARG;

            if ( *argv == NULL ) {
                *err_msg = "No data supplied for -icon in cup data";
                goto bail_cup_data;
            }

            icon = string_copy( *argv );
        } else if ( strcmp( *argv, "-races" ) == 0 ) {
            NEXT_ARG;

            if ( *argv == NULL ) {
                *err_msg= "No data supplied for -races in cup data";
                goto bail_cup_data;
            }

            race_list = create_list();
            last_race = NULL;

            if ( Tcl_SplitList( ip, *argv, &num_races, &races ) == TCL_ERROR ) {
                *err_msg = "Race data is not a list in event data";
                goto bail_cup_data;
            }

            for ( i=0; i<num_races; i++) {
                race_data_t *race_data;
                race_data = create_race_data( ip, races[i], err_msg );
                if ( race_data == NULL ) {
                    goto bail_cup_data;
                }

                last_race = insert_list_elem( race_list, last_race,
                                              (list_elem_data_t) race_data );
            }

            Tcl_Free( (char*) races );
            races = NULL;
        } else {
            sprintf( err_buff, "Unrecognized argument `%s'", *argv );
            *err_msg = err_buff;
            goto bail_cup_data;
        }

        NEXT_ARG;
    }

    /* Make sure mandatory fields have been specified */
    if ( name == NULL ) {
        *err_msg = "Must specify a name in cup data";
        goto bail_cup_data;
    }

    if ( icon == NULL ) {
        *err_msg = "Must specify an icon texture in cup data";
        goto bail_cup_data;
    }

    if ( race_list == NULL ) {
        *err_msg = "Must specify a race list in cup data";
        goto bail_cup_data;
    }

    /* Create a new cup data object */
    cup_data = (cup_data_t*) malloc( sizeof( cup_data_t ) );
    check_assertion( cup_data != NULL, "out of memory" );

    cup_data->name = name;
    cup_data->race_list = race_list;

    bind_texture( name, icon );

    Tcl_Free( (char*) orig_argv );
    argv = NULL;

    free( icon );

    return cup_data;

bail_cup_data:

    if ( orig_argv ) {
        Tcl_Free( (char*) orig_argv );
    }

    if ( name ) {
        free( name );
    }

    if ( icon ) {
        free( icon );
    }

    if ( races ) {
        Tcl_Free( (char*) races );
    }

    /* Clean out race list */
    if ( race_list ) {
        last_race = get_list_tail( race_list );
        while ( last_race != NULL ) {
            race_data_t *data;
            data = (race_data_t*) delete_list_elem( race_list, last_race );
            free( data );
            last_race = get_list_tail( race_list );
        }

        del_list( race_list );
    }

    if ( cup_data ) {
        free( cup_data );
    }

    return NULL;
}
示例#24
0
// меню работы с врачами
void doc_menu(node **doc, hash_tab *tab, refferal **ref_head, refferal **ref_tail)
{
	bool end(false); // флаг остановки работы(возврат в главное меню)
	svector_doc search; // вектор найденных данных врачей
	int choice; // выбор критерия
	string answer; // ответ на вопрос д\н

	while(!end) 
	{
		system("cls");
		cout<<"======= Работа с докторами =======\n"
			<<" 1. Добавить нового врача\n"
			<<" 2. Удаление сведений о враче\n"
			<<" 3. Список всех врачей\n"
			<<" 4. Удаление данных о всех врачах\n"
			<<" 5. Поиск\n"
			<<" 0. Назад в меню\n"
			<<"==================================\n"
			<<"\nВведите команду: ";
		choice = input_control(5, 0);
		if (!(*doc) && (choice >= 2 && choice <= 5))
		{
			cout << "\nБД докторов пуста! Пункты #2 - #4 недоступны.\n";
			system("pause");
			choice = -1;
		}
		switch(choice)
		{
		case 1:
			cout<<" Регистрация врача:\n";
			*doc = add_node(*doc, doc_init());
			cout << "\n=== Специалист добавлен ===\n";
			system("pause");
			break; 
		case 2:
			doc_del_menu(doc, search, ref_head, ref_tail);
			system("pause");
			break;
		case 3:
			//debug_out(*doc, 0);
			doc_out(*doc);
			system("pause");
			break;
		case 4:
			cout << " Удалить данные о всех врачах? \n(Также удалится вся информация о выданных направлениях на прием) д/н ";
			answer_control(answer);
			if (answer[0] == 'д')
			{
				remove_all_doc(doc);
				del_list(ref_head, ref_tail);
				cout << " Записи удалены.\n";
				system("pause");
			}
			else
			{
				cout << " Записи НЕ удалены.\n";
				system("pause");
			}
			break;
		case 5:
			doc_search_menu(*doc, tab, *ref_head, search);
			system("pause");
			break;
		case 0:
			end = true;
			break;
		default:
			break;
		}
		search.clear();
		search.shrink_to_fit();
	}
}
示例#25
0
// меню работы с пациентами
void pat_menu(hash_tab **pat, node *doc, refferal **ref_head, refferal **ref_tail)
{
	bool end(false); // флаг остановки работы(возврат в главное меню)
	svector_pat search; // вектор найденных данных врачей
	int choice; // выбор критерия
	string answer; // ответ на вопрос д\н

	while(!end) 
	{
		system("cls");
		cout<<"======= Работа с клиентурой =======\n"
			<<" 1. Регистрация нового больного\n"
			<<" 2. Удаление данных о больном\n"
			<<" 3. Список всех больных\n"
			<<" 4. Удаление данных о всех больных\n"
			<<" 5. Поиск\n"
			<<" 0. Назад в меню\n"
			<<"===================================\n"
			<<"\nВведите команду: ";
		choice = input_control(5, 0);
		if ((choice >= 2 && choice <= 5) && !(have_pat(*pat)))
		{
			cout << "\nБД пациентов пуста! Пункты #2 - #5 недоступны.\n";
			system("pause");
			choice = -1;
		}
		switch(choice)
		{
		case 1:
			cout<<" Регистрация больного:\n";
			add_to_tab(*pat, pat_init());
			system("pause");
			break;
		case 2:
			del_pat(*pat, ref_head, ref_tail);
			system("pause");
			break;
		case 3:
			pat_out(*pat);
			system("pause");
			break;
		case 4:
			cout << " Удалить данные о всех больных? \n(Также удалится вся информация о выданных направлениях на прием) д/н ";
			answer_control(answer);
			if (answer[0] == 'д')
			{
				htab_init(*pat);
				del_list(ref_head, ref_tail);
				cout << " Записи удалены.\n";
				system("pause");
			}
			else
			{
				cout << " Записи НЕ удалены.\n";
				system("pause");
			}
			break;
		case 5:
			pat_search_menu(search, *pat, doc, *ref_head);
			system("pause");
			break;
		case 0:
			end = true;
			break;
		default:
			break;
		}
		search.clear();
		search.shrink_to_fit();
	}
}
示例#26
0
// главное меню 
void menu()
{
	bool end(false); // флаг остановки работы
	int choice; // критерий выбора
	/* =============== Обявления ============== */
	node *doc = NULL; // АВЛ-дерево данных врачей
	refferal *ref_head = NULL, *ref_tail = NULL; // циклический список направлений 
	hash_tab *pat = new hash_tab[TAB_SIZE]; // хэш-таблица данных пациентов
	/* ============ Чтение из файлов ========== */
	read_pat_base(pat);
	read_doc_base(&doc);
	read_ref_base(&ref_head, &ref_tail);

	while(!end) 
	{
		system("cls");
		cout<<"=========== Меню ============\n"
			<<" 1. Работа с клиентурой \n"
			<<" 2. Работа с направлениями\n"
			<<" 3. Работа с докторами\n"
			<<" 4. Сохранить изменения\n"
			<<" 0. Выход\n"
			<<"=============================\n"
			<<"\nВведите команду: ";
		choice = input_control(4, 0);
		if (choice == 2 && !(doc || have_pat(pat)))
		{
			if (have_pat(pat)) cout << "\nБД врачей пуста! Пункт #2 недоступен.\n";
			else cout << "\nБД пациентов пуста! Пункт #2 недоступен.\n";
			system("pause");
			choice = -1;
		}
		switch(choice)
		{
		case 1:
			pat_menu(&pat, doc, &ref_head, &ref_tail);
			break;
		case 2:
			ref_menu(&ref_head, &ref_tail, doc, pat);
			break;
		case 3:
			doc_menu(&doc, pat, &ref_head, &ref_tail);
			break;
		case 4:
			fill_pat_base(pat);
			fill_doc_base(doc);
			fill_ref_base(ref_head);
			break;
		case 0:
			end = true;
			break;
		default:
			break;
		}
	}
	cout<<"Завершаю работу...\n";
	/* ============ Запись в файлы ============ */
	fill_pat_base(pat);
	fill_doc_base(doc);
	fill_ref_base(ref_head);/**/
	/* ==== Удаление динамических структур ==== */
	del_list(&ref_head, &ref_tail);
	remove_all_doc(&doc);
	delete [] pat;
}
示例#27
0
int 
main(int argc, char **argv)
{
	FILE *fp;
	char buf[MAX_LINE];
	int count=0;
	int serv_port;
	int max_sending_window_size;
	const int on=1;
	struct socket_descripts sock_desc[10];
	int sock_count = 0;
	struct ifi_info *ifi, *ifihead;
	int sockfd;
	struct sockaddr_in *sa;
	int i = 0;
	fp=fopen("server.in","r");

	if(fp == NULL)
	{
		printf("ERROR MSG: No server.in file!\n");
		exit(1);
	}

	while(fgets(buf, MAX_LINE -1, fp) != NULL)
	{
		if(count == 0)
			serv_port = atoi(buf);
		else if(count == 1)
			max_sending_window_size = atoi(buf);
		count++;
	}
	fclose(fp);

	for (ifihead = ifi = Get_ifi_info_plus( AF_INET, 1);
                ifi != NULL; 
		ifi = ifi->ifi_next) {

		/* bind unicast adress */
		sockfd = Socket(AF_INET, SOCK_DGRAM, 0);
		Setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,&on, sizeof(on));

		sa = (struct sockaddr_in *) ifi->ifi_addr;
		sa->sin_family = AF_INET;
		sa->sin_port = htons(serv_port);

		Bind(sockfd, (SA *) sa, sizeof(*sa));

		sock_desc[sock_count].sockfd = sockfd;
		sock_desc[sock_count].ip_addr = sa;
		sock_desc[sock_count].net_mask = (struct sockaddr_in *)ifi->ifi_ntmaddr;

		//printf("SERVER: sockdesc[%d]\n", sock_count);
		printf("SERVER: IP: %s\n", Sock_ntop_host(sock_desc[sock_count].ip_addr, sizeof(struct in_addr)));
		printf("SERVER: Network mask: %s\n", Sock_ntop_host(sock_desc[sock_count].net_mask, sizeof(struct in_addr)));
		//printf("SERVER: sockdesc[%d]\n", sock_count); 
		sock_count++;
	}
	
	int maxfd;
	fd_set rset;
	int nready;
	int len;
	char recvline[MAXLINE];	
	struct sockaddr_in cliaddr, child_server_addr, server_addr, sock_store;
	
	int n;
	int server_len;
	char IPserver[MAXLINE];
	int pid;
	socklen_t serv_len, store_len;
	struct list_ips* r = NULL;

	maxfd=sock_desc[0].sockfd;
	for(i=0;i < sock_count; i++)
	{
		if(maxfd < sock_desc[i].sockfd)
			maxfd = sock_desc[i].sockfd;
	}

	for( ; ; )
	{
		FD_ZERO(&rset);
		for(i = 0; i < sock_count; i++)
			FD_SET(sock_desc[i].sockfd, &rset);

		//printf("SERVER: waiting using select()\n");
		
		if( (nready=select(maxfd+1, &rset, NULL, NULL, NULL)) < 0 )
		{
			if (errno == EINTR){
				continue;
			}else{
				printf("ERROR MSG: server select error\n");
				exit(0);
			}
		}


		
		for(i=0; i < sock_count; i++)
		{
			if(FD_ISSET(sock_desc[i].sockfd, &rset))
			{
				char filename[MAXLINE];
				int client_window_size;
				len = sizeof(cliaddr);
				
				//printf("SERVER: before revefrom func()\n");	
				n = recvfrom(sock_desc[i].sockfd, recvline, MAXLINE, 0, (SA *) &cliaddr, &len);
				sscanf(recvline, "%s %d", filename, &client_window_size);
				//printf("%s %d\n", filename, client_window_size);
				//printf("SERVER: first message is recevied: %s\n", recvline);
				
				r = search_list(cliaddr, NULL);
				if( r != NULL)
					continue;

				server_len = sizeof(server_addr);	
				if( getsockname( sock_desc[ i ].sockfd, (SA *)&server_addr, &server_len ) < 0 )
				{
					printf( "SERVER: getsockname error\n" );
					exit(1);
				}      
				inet_ntop( AF_INET, &(server_addr.sin_addr), IPserver, MAXLINE);
				//printf("SERVER: IPserver after receving filename: %s\n", IPserver);

				
				inet_pton( AF_INET, IPserver, &child_server_addr.sin_addr );	
				child_server_addr.sin_family = AF_INET;
				child_server_addr.sin_port = htonl(0);
			
				add_list(cliaddr);

				if ( (pid = fork() ) == 0)
				{
					int j;
					for(j=0; j < sock_count; j++)
					{
						if(i!=j)
							close(sock_desc[j].sockfd);
					}
					//printf("%d %d\n", max_sending_window_size, client_window_size);
					max_sending_window_size = min(max_sending_window_size, client_window_size);
					handshake(sock_desc[i].sockfd,&child_server_addr, sizeof(child_server_addr), &cliaddr, sizeof(cliaddr),  filename, max_sending_window_size );
					del_list(cliaddr);
					exit(0);
				}
			}
		}
	}
}
示例#28
0
static int update_gshadow (void)
{
	int is_member;
	int was_member;
	int was_admin;
	int changed;
	const struct sgrp *sgrp;
	struct sgrp *nsgrp;

	if (!sgr_lock ()) {
		fprintf (stderr,
			 _("%s: error locking shadow group file\n"), Prog);
		SYSLOG ((LOG_ERR, "error locking shadow group file"));
		return -1;
	}
	if (!sgr_open (O_RDWR)) {
		fprintf (stderr,
			 _("%s: error opening shadow group file\n"), Prog);
		SYSLOG ((LOG_ERR, "error opening shadow group file"));
		sgr_unlock ();
		return -1;
	}

	changed = 0;

	/*
	 * Scan through the entire shadow group file looking for the groups
	 * that the user is a member of.
	 */
	while ((sgrp = sgr_next ())) {

		/*
		 * See if the user was a member of this group
		 */
		was_member = is_on_list (sgrp->sg_mem, user_name);

		/*
		 * See if the user was an administrator of this group
		 */
		was_admin = is_on_list (sgrp->sg_adm, user_name);

		/*
		 * See if the user specified this group as one of their
		 * concurrent groups.
		 */
		is_member = Gflg
		    && is_on_list (user_groups, sgrp->sg_name);

		if (!was_member && !was_admin && !is_member)
			continue;

		nsgrp = __sgr_dup (sgrp);
		if (!nsgrp) {
			fprintf (stderr,
				 _
				 ("%s: out of memory in update_gshadow\n"),
				 Prog);
			sgr_unlock ();
			return -1;
		}

		if (was_admin && lflg) {
			nsgrp->sg_adm =
			    del_list (nsgrp->sg_adm, user_name);
			nsgrp->sg_adm =
			    add_list (nsgrp->sg_adm, user_newname);
			changed = 1;
			SYSLOG ((LOG_INFO,
				 "change admin `%s' to `%s' in shadow group `%s'",
				 user_name, user_newname, nsgrp->sg_name));
		}
		if (was_member && (!Gflg || is_member)) {
			if (lflg) {
				nsgrp->sg_mem = del_list (nsgrp->sg_mem,
							  user_name);
				nsgrp->sg_mem = add_list (nsgrp->sg_mem,
							  user_newname);
				changed = 1;
				SYSLOG ((LOG_INFO,
					 "change `%s' to `%s' in shadow group `%s'",
					 user_name, user_newname,
					 nsgrp->sg_name));
			}
		} else if (was_member && Gflg && !is_member) {
			nsgrp->sg_mem =
			    del_list (nsgrp->sg_mem, user_name);
			changed = 1;
			SYSLOG ((LOG_INFO,
				 "delete `%s' from shadow group `%s'",
				 user_name, nsgrp->sg_name));
		} else if (!was_member && Gflg && is_member) {
			nsgrp->sg_mem = add_list (nsgrp->sg_mem,
						  lflg ? user_newname :
						  user_name);
			changed = 1;
			SYSLOG ((LOG_INFO, "add `%s' to shadow group `%s'",
				 lflg ? user_newname : user_name,
				 nsgrp->sg_name));
		}
		if (!changed)
			continue;

		changed = 0;

		/* 
		 * Update the group entry to reflect the changes.
		 */
		if (!sgr_update (nsgrp)) {
			fprintf (stderr,
				 _("%s: error adding new group entry\n"),
				 Prog);
			SYSLOG ((LOG_ERR,
				 "error adding shadow group entry"));
			sgr_unlock ();
			return -1;
		}
#ifdef	NDBM
		/*
		 * Update the DBM group file with the new entry as well.
		 */
		if (!sg_dbm_update (nsgrp)) {
			fprintf (stderr,
				 _("%s: cannot add new dbm group entry\n"),
				 Prog);
			SYSLOG ((LOG_ERR,
				 "error adding dbm shadow group entry"));
			sgr_unlock ();
			return -1;
		}
#endif				/* NDBM */
	}
#ifdef NDBM
	endsgent ();
#endif				/* NDBM */
	if (!sgr_close ()) {
		fprintf (stderr,
			 _("%s: cannot rewrite shadow group file\n"),
			 Prog);
		sgr_unlock ();
		return -1;
	}
	sgr_unlock ();
	return 0;
}
示例#29
0
static int update_group (void)
{
	int is_member;
	int was_member;
	int changed;
	const struct group *grp;
	struct group *ngrp;

	/*
	 * Lock and open the group file. This will load all of the group
	 * entries.
	 */
	if (!gr_lock ()) {
		fprintf (stderr, _("%s: error locking group file\n"),
			 Prog);
		SYSLOG ((LOG_ERR, "error locking group file"));
		return -1;
	}
	if (!gr_open (O_RDWR)) {
		fprintf (stderr, _("%s: error opening group file\n"),
			 Prog);
		SYSLOG ((LOG_ERR, "error opening group file"));
		gr_unlock ();
		return -1;
	}

	changed = 0;

	/*
	 * Scan through the entire group file looking for the groups that
	 * the user is a member of.
	 */
	while ((grp = gr_next ())) {

		/*
		 * See if the user specified this group as one of their
		 * concurrent groups.
		 */
		was_member = is_on_list (grp->gr_mem, user_name);
		is_member = Gflg && is_on_list (user_groups, grp->gr_name);

		if (!was_member && !is_member)
			continue;

		ngrp = __gr_dup (grp);
		if (!ngrp) {
			fprintf (stderr,
				 _("%s: out of memory in update_group\n"),
				 Prog);
			gr_unlock ();
			return -1;
		}

		if (was_member && (!Gflg || is_member)) {
			if (lflg) {
				ngrp->gr_mem = del_list (ngrp->gr_mem,
							 user_name);
				ngrp->gr_mem = add_list (ngrp->gr_mem,
							 user_newname);
				changed = 1;
				SYSLOG ((LOG_INFO,
					 "change `%s' to `%s' in group `%s'",
					 user_name, user_newname,
					 ngrp->gr_name));
			}
		} else if (was_member && Gflg && !is_member) {
			ngrp->gr_mem = del_list (ngrp->gr_mem, user_name);
			changed = 1;
			SYSLOG ((LOG_INFO, "delete `%s' from group `%s'",
				 user_name, ngrp->gr_name));
		} else if (!was_member && Gflg && is_member) {
			ngrp->gr_mem = add_list (ngrp->gr_mem,
						 lflg ? user_newname :
						 user_name);
			changed = 1;
			SYSLOG ((LOG_INFO, "add `%s' to group `%s'",
				 lflg ? user_newname : user_name,
				 ngrp->gr_name));
		}
		if (!changed)
			continue;

		changed = 0;
		if (!gr_update (ngrp)) {
			fprintf (stderr,
				 _("%s: error adding new group entry\n"),
				 Prog);
			SYSLOG ((LOG_ERR, "error adding group entry"));
			gr_unlock ();
			return -1;
		}
#ifdef	NDBM
		/*
		 * Update the DBM group file with the new entry as well.
		 */
		if (!gr_dbm_update (ngrp)) {
			fprintf (stderr,
				 _("%s: cannot add new dbm group entry\n"),
				 Prog);
			SYSLOG ((LOG_ERR, "error adding dbm group entry"));
			gr_unlock ();
			return -1;
		}
#endif				/* NDBM */
	}
#ifdef NDBM
	endgrent ();
#endif				/* NDBM */
	if (!gr_close ()) {
		fprintf (stderr, _("%s: cannot rewrite group file\n"),
			 Prog);
		gr_unlock ();
		return -1;
	}
	gr_unlock ();
	return 0;
}
示例#30
0
static void
update_groups(void)
{
	const struct group *grp;
	struct group *ngrp;
#ifdef	SHADOWGRP
	const struct sgrp *sgrp;
	struct sgrp *nsgrp;
#endif	/* SHADOWGRP */

	/*
	 * Scan through the entire group file looking for the groups that
	 * the user is a member of.
	 */

	for (gr_rewind (), grp = gr_next ();grp;grp = gr_next ()) {

		/*
		 * See if the user specified this group as one of their
		 * concurrent groups.
		 */

		if (!is_on_list(grp->gr_mem, user_name))
			continue;

		/* 
		 * Delete the username from the list of group members and
		 * update the group entry to reflect the change.
		 */

		ngrp = __gr_dup(grp);
		if (!ngrp) {
			exit(13);  /* XXX */
		}
		ngrp->gr_mem = del_list (ngrp->gr_mem, user_name);
		if (!gr_update(ngrp))
			fprintf(stderr, _("%s: error updating group entry\n"),
				Prog);

		/*
		 * Update the DBM group file with the new entry as well.
		 */

#ifdef	NDBM
		if (!gr_dbm_update(ngrp))
			fprintf(stderr,
				_("%s: cannot update dbm group entry\n"),
				Prog);
#endif	/* NDBM */
		SYSLOG((LOG_INFO, "delete `%s' from group `%s'\n",
			user_name, ngrp->gr_name));
	}
#ifdef	NDBM
	endgrent ();
#endif	/* NDBM */
#ifdef	SHADOWGRP
	if (!is_shadow_grp)
		return;

	/*
	 * Scan through the entire shadow group file looking for the groups
	 * that the user is a member of.  Both the administrative list and
	 * the ordinary membership list is checked.
	 */

	for (sgr_rewind (), sgrp = sgr_next ();sgrp;sgrp = sgr_next ()) {
		int was_member, was_admin;

		/*
		 * See if the user specified this group as one of their
		 * concurrent groups.
		 */

		was_member = is_on_list(sgrp->sg_mem, user_name);
		was_admin = is_on_list(sgrp->sg_adm, user_name);

		if (!was_member && !was_admin)
			continue;

		nsgrp = __sgr_dup(sgrp);
		if (!nsgrp) {
			exit(13);  /* XXX */
		}

		if (was_member)
			nsgrp->sg_mem = del_list (nsgrp->sg_mem, user_name);

		if (was_admin)
			nsgrp->sg_adm = del_list (nsgrp->sg_adm, user_name);

		if (!sgr_update(nsgrp))
			fprintf(stderr, _("%s: error updating group entry\n"),
				Prog);
#ifdef	NDBM
		/*
		 * Update the DBM group file with the new entry as well.
		 */

		if (!sg_dbm_update(nsgrp))
			fprintf(stderr,
				_("%s: cannot update dbm group entry\n"),
				Prog);
#endif	/* NDBM */
		SYSLOG((LOG_INFO, "delete `%s' from shadow group `%s'\n",
			user_name, nsgrp->sg_name));
	}
#ifdef	NDBM
	endsgent ();
#endif	/* NDBM */
#endif	/* SHADOWGRP */
}