xref: /original-bsd/lib/libc/gen/initgroups.c (revision 18f6d767)
1 /*	initgroups.c	4.4	83/06/17	*/
2 
3 /*
4  * initgroups
5  */
6 #include <stdio.h>
7 #include <sys/param.h>
8 #include <grp.h>
9 
10 struct group *getgrent();
11 
12 initgroups(uname, agroup)
13 	char *uname;
14 	int agroup;
15 {
16 	int groups[NGROUPS], ngroups = 0;
17 	register struct group *grp;
18 	register int i;
19 
20 	if (agroup >= 0)
21 		groups[ngroups++] = agroup;
22 	setgrent();
23 	while (grp = getgrent()) {
24 		if (grp->gr_gid == agroup)
25 			continue;
26 		for (i = 0; grp->gr_mem[i]; i++)
27 			if (!strcmp(grp->gr_mem[i], uname)) {
28 				if (ngroups == NGROUPS) {
29 fprintf(stderr, "initgroups: %s is in too many groups\n", uname);
30 					goto toomany;
31 				}
32 				groups[ngroups++] = grp->gr_gid;
33 			}
34 	}
35 toomany:
36 	endgrent();
37 	if (setgroups(ngroups, groups) < 0) {
38 		perror("setgroups");
39 		return (1);
40 	}
41 	return (0);
42 }
43