xref: /titanic_41/usr/src/ucbcmd/groups/groups.c (revision bafec74292ca6805e5acb387856f4e60a5314b37)
1 /*
2  * Copyright 2007 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/types.h>
23 #include <sys/param.h>
24 #include <grp.h>
25 #include <pwd.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <string.h>
30 
31 static void showgroups(char *user);
32 
33 int
34 main(int argc, char *argv[])
35 {
36 	int ngroups, i;
37 	char *sep = "";
38 	struct group *gr;
39 	gid_t groups[NGROUPS_UMAX];
40 
41 	if (argc > 1) {
42 		for (i = 1; i < argc; i++)
43 			showgroups(argv[i]);
44 		exit(0);
45 	}
46 
47 	ngroups = getgroups(NGROUPS_UMAX, groups);
48 	if (getpwuid(getuid()) == NULL) {
49 		(void) fprintf(stderr, "groups: could not find passwd entry\n");
50 		exit(1);
51 	}
52 
53 	for (i = 0; i < ngroups; i++) {
54 		gr = getgrgid(groups[i]);
55 		if (gr == NULL) {
56 			(void) printf("%s%u", sep, groups[i]);
57 			sep = " ";
58 			continue;
59 		}
60 		(void) printf("%s%s", sep, gr->gr_name);
61 		sep = " ";
62 	}
63 
64 	(void) printf("\n");
65 	return (0);
66 }
67 
68 static void
69 showgroups(char *user)
70 {
71 	struct group *gr;
72 	struct passwd *pw;
73 	char **cp;
74 	char *sep = "";
75 	int pwgid_printed = 0;
76 
77 	if ((pw = getpwnam(user)) == NULL) {
78 		(void) fprintf(stderr, "groups: %s : No such user\n", user);
79 		return;
80 	}
81 	setgrent();
82 	(void) printf("%s : ", user);
83 	while (gr = getgrent()) {
84 		if (pw->pw_gid == gr->gr_gid) {
85 			/*
86 			 * To avoid duplicate group entries
87 			 */
88 			if (pwgid_printed == 0) {
89 			    (void) printf("%s%s", sep, gr->gr_name);
90 			    sep = " ";
91 			    pwgid_printed = 1;
92 			}
93 			continue;
94 		}
95 		for (cp = gr->gr_mem; cp && *cp; cp++)
96 			if (strcmp(*cp, user) == 0) {
97 				(void) printf("%s%s", sep, gr->gr_name);
98 				sep = " ";
99 				break;
100 			}
101 	}
102 	(void) printf("\n");
103 	endgrent();
104 }
105