xref: /csrg-svn/lib/libc/gen/initgroups.c (revision 46597)
121346Sdist /*
221346Sdist  * Copyright (c) 1983 Regents of the University of California.
335091Sbostic  * All rights reserved.
435091Sbostic  *
542625Sbostic  * %sccs.include.redist.c%
621346Sdist  */
79110Ssam 
826567Sdonn #if defined(LIBC_SCCS) && !defined(lint)
9*46597Sdonn static char sccsid[] = "@(#)initgroups.c	5.7 (Berkeley) 02/23/91";
1035091Sbostic #endif /* LIBC_SCCS and not lint */
1121346Sdist 
129110Ssam /*
139110Ssam  * initgroups
149110Ssam  */
15*46597Sdonn #include <sys/param.h>
169110Ssam #include <stdio.h>
17*46597Sdonn #include <string.h>
18*46597Sdonn #include <unistd.h>
199110Ssam #include <grp.h>
209110Ssam 
219110Ssam struct group *getgrent();
229110Ssam 
23*46597Sdonn int
249110Ssam initgroups(uname, agroup)
25*46597Sdonn 	const char *uname;
269110Ssam 	int agroup;
279110Ssam {
289110Ssam 	int groups[NGROUPS], ngroups = 0;
299110Ssam 	register struct group *grp;
309110Ssam 	register int i;
319110Ssam 
3238787Skarels 	/*
3338787Skarels 	 * If installing primary group, duplicate it;
3438787Skarels 	 * the first element of groups is the effective gid
3538787Skarels 	 * and will be overwritten when a setgid file is executed.
3638787Skarels 	 */
3738787Skarels 	if (agroup >= 0) {
389110Ssam 		groups[ngroups++] = agroup;
3938787Skarels 		groups[ngroups++] = agroup;
4038787Skarels 	}
419110Ssam 	setgrent();
4212168Ssam 	while (grp = getgrent()) {
4312168Ssam 		if (grp->gr_gid == agroup)
4412168Ssam 			continue;
459110Ssam 		for (i = 0; grp->gr_mem[i]; i++)
469110Ssam 			if (!strcmp(grp->gr_mem[i], uname)) {
479110Ssam 				if (ngroups == NGROUPS) {
4812168Ssam fprintf(stderr, "initgroups: %s is in too many groups\n", uname);
499110Ssam 					goto toomany;
509110Ssam 				}
5111073Smckusick 				groups[ngroups++] = grp->gr_gid;
529110Ssam 			}
5312168Ssam 	}
549110Ssam toomany:
5513176Ssam 	endgrent();
569110Ssam 	if (setgroups(ngroups, groups) < 0) {
5712168Ssam 		perror("setgroups");
5827457Sdonn 		return (-1);
599110Ssam 	}
609110Ssam 	return (0);
619110Ssam }
62