xref: /titanic_51/usr/src/ucbcmd/groups/groups.c (revision 43a291055ab3951f6372241323fd4e2486098fff)
1 /*
2  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
7 /*	  All Rights Reserved  	*/
8 
9 
10 /*
11  * Copyright (c) 1980 Regents of the University of California.
12  * All rights reserved. The Berkeley software License Agreement
13  * specifies the terms and conditions for redistribution.
14  */
15 
16 #pragma ident	"%Z%%M%	%I%	%E% SMI"
17 
18 /*
19  * groups
20  */
21 
22 #include <sys/param.h>
23 #include <grp.h>
24 #include <pwd.h>
25 #include <stdio.h>
26 
27 static void showgroups(char *);
28 
29 int	groups[NGROUPS_UMAX];
30 
31 int
32 main(int argc, char *argv[])
33 {
34 	int ngroups, i, j;
35 	char *sep = "";
36 	struct group *gr;
37 	struct passwd *pw;
38 
39 	if (argc > 1) {
40 		for (i=1; i < argc ; i++)
41         		showgroups(argv[i]);
42 		exit(0) ;
43 	}
44 
45 	ngroups = getgroups(NGROUPS_UMAX, groups);
46 	if ((pw = getpwuid(getuid())) == NULL) {
47 		fprintf(stderr, "groups: could not find passwd entry\n");
48 		exit(1);
49 	}
50 
51 	for (i = 0; i < ngroups; i++) {
52 		gr = getgrgid(groups[i]);
53 		if (gr == NULL) {
54 			printf("%s%d", sep, groups[i]);
55 			sep = " ";
56 			continue;
57 		}
58 		printf("%s%s", sep, gr->gr_name);
59 		sep = " ";
60 	}
61 	printf("\n");
62 	return (0);
63 }
64 
65 void
66 showgroups(char *user)
67 {
68 	struct group *gr;
69 	struct passwd *pw;
70 	char **cp;
71 	char *sep = "";
72 	int pwgid_printed = 0 ;
73 
74 	if ((pw = getpwnam(user)) == NULL) {
75 		fprintf(stderr, "groups: %s : No such user\n", user);
76 		return;
77 	}
78 	setgrent() ;
79 	printf("%s : ", user) ;
80 	while (gr = getgrent()) {
81 		if (pw->pw_gid == gr->gr_gid) {
82 			/*
83 			 * To avoid duplicate group entries
84 			 */
85 			if (pwgid_printed==0) {
86 			    printf("%s%s", sep, gr->gr_name);
87 			    sep = " ";
88 			    pwgid_printed = 1 ;
89 			}
90 			continue ;
91 		}
92 		for (cp = gr->gr_mem; cp && *cp; cp++)
93 			if (strcmp(*cp, user) == 0) {
94 				printf("%s%s", sep, gr->gr_name);
95 				sep = " ";
96 				break;
97 			}
98 	}
99 	printf("\n");
100 	endgrent() ;
101 }
102