xref: /titanic_50/usr/src/cmd/getent/dogetgr.c (revision 843e19887f64dde75055cf8842fc4db2171eff45)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <stdio.h>
30 #include <grp.h>
31 #include <stdlib.h>
32 #include <errno.h>
33 #include "getent.h"
34 
35 
36 static int
37 putgrent(const struct group *grp, FILE *fp)
38 {
39 	char **mem;
40 	int rc = 0;
41 
42 	if (grp == NULL) {
43 		return (1);
44 	}
45 
46 	if (fprintf(fp, "%s:%s:%d:",
47 		    grp->gr_name != NULL ? grp->gr_name : "",
48 		    grp->gr_passwd != NULL ? grp->gr_passwd : "",
49 		    grp->gr_gid) == EOF)
50 		rc = 1;
51 
52 	mem = grp ->gr_mem;
53 
54 	if (mem != NULL) {
55 		if (*mem != NULL)
56 			if (fputs(*mem++, fp) == EOF)
57 				rc = 1;
58 
59 		while (*mem != NULL)
60 			if (fprintf(fp, ",%s", *mem++) == EOF)
61 				rc = 1;
62 	}
63 	if (putc('\n', fp) == EOF)
64 		rc = 1;
65 	return (rc);
66 }
67 
68 int
69 dogetgr(const char **list)
70 {
71 	struct group *grp;
72 	int rc = EXC_SUCCESS;
73 	char *ptr;
74 	gid_t gid;
75 
76 	if (list == NULL || *list == NULL) {
77 		while ((grp = getgrent()) != NULL)
78 			(void) putgrent(grp, stdout);
79 	} else {
80 		for (; *list != NULL; list++) {
81 			errno = 0;
82 
83 			/*
84 			 * Here we assume that the argument passed is
85 			 * a gid, if it can be completely transformed
86 			 * to a long integer. So we check for gid in
87 			 * the database and if we fail then we check
88 			 * for the group name.
89 			 * If the argument passed is not numeric, then
90 			 * we take it as the group name and proceed.
91 			 */
92 			gid = strtol(*list, &ptr, 10);
93 			if (!(*ptr == '\0' && errno == 0) ||
94 			    ((grp = getgrgid(gid)) == NULL)) {
95 				grp = getgrnam(*list);
96 			}
97 			if (grp == NULL)
98 				rc = EXC_NAME_NOT_FOUND;
99 			else
100 				(void) putgrent(grp, stdout);
101 		}
102 	}
103 
104 	return (rc);
105 }
106