xref: /csrg-svn/lib/libc/gen/initgroups.c (revision 38787)
121346Sdist /*
221346Sdist  * Copyright (c) 1983 Regents of the University of California.
335091Sbostic  * All rights reserved.
435091Sbostic  *
535091Sbostic  * Redistribution and use in source and binary forms are permitted
635091Sbostic  * provided that the above copyright notice and this paragraph are
735091Sbostic  * duplicated in all such forms and that any documentation,
835091Sbostic  * advertising materials, and other materials related to such
935091Sbostic  * distribution and use acknowledge that the software was developed
1035091Sbostic  * by the University of California, Berkeley.  The name of the
1135091Sbostic  * University may not be used to endorse or promote products derived
1235091Sbostic  * from this software without specific prior written permission.
1335091Sbostic  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
1435091Sbostic  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
1535091Sbostic  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
1621346Sdist  */
179110Ssam 
1826567Sdonn #if defined(LIBC_SCCS) && !defined(lint)
19*38787Skarels static char sccsid[] = "@(#)initgroups.c	5.5 (Berkeley) 08/26/89";
2035091Sbostic #endif /* LIBC_SCCS and not lint */
2121346Sdist 
229110Ssam /*
239110Ssam  * initgroups
249110Ssam  */
259110Ssam #include <stdio.h>
269110Ssam #include <sys/param.h>
279110Ssam #include <grp.h>
289110Ssam 
299110Ssam struct group *getgrent();
309110Ssam 
319110Ssam initgroups(uname, agroup)
329110Ssam 	char *uname;
339110Ssam 	int agroup;
349110Ssam {
359110Ssam 	int groups[NGROUPS], ngroups = 0;
369110Ssam 	register struct group *grp;
379110Ssam 	register int i;
389110Ssam 
39*38787Skarels 	/*
40*38787Skarels 	 * If installing primary group, duplicate it;
41*38787Skarels 	 * the first element of groups is the effective gid
42*38787Skarels 	 * and will be overwritten when a setgid file is executed.
43*38787Skarels 	 */
44*38787Skarels 	if (agroup >= 0) {
459110Ssam 		groups[ngroups++] = agroup;
46*38787Skarels 		groups[ngroups++] = agroup;
47*38787Skarels 	}
489110Ssam 	setgrent();
4912168Ssam 	while (grp = getgrent()) {
5012168Ssam 		if (grp->gr_gid == agroup)
5112168Ssam 			continue;
529110Ssam 		for (i = 0; grp->gr_mem[i]; i++)
539110Ssam 			if (!strcmp(grp->gr_mem[i], uname)) {
549110Ssam 				if (ngroups == NGROUPS) {
5512168Ssam fprintf(stderr, "initgroups: %s is in too many groups\n", uname);
569110Ssam 					goto toomany;
579110Ssam 				}
5811073Smckusick 				groups[ngroups++] = grp->gr_gid;
599110Ssam 			}
6012168Ssam 	}
619110Ssam toomany:
6213176Ssam 	endgrent();
639110Ssam 	if (setgroups(ngroups, groups) < 0) {
6412168Ssam 		perror("setgroups");
6527457Sdonn 		return (-1);
669110Ssam 	}
679110Ssam 	return (0);
689110Ssam }
69