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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright (c) 2018 Peter Tribble.
24  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
25  * Use is subject to license terms.
26  */
27 
28 #include <stdio.h>
29 #include <pwd.h>
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <user_attr.h>
33 #include "getent.h"
34 
35 static int
36 putuserattr(const userattr_t *user, FILE *fp)
37 {
38 	int i;
39 	kva_t *attrs;
40 	kv_t *data;
41 
42 	if (user == NULL)
43 		return (1);
44 
45 	if (fprintf(fp, "%s:%s:%s:%s:",
46 	    user->name != NULL ? user->name : "",
47 	    user->qualifier != NULL ? user->res1 : "",
48 	    user->res1 != NULL ? user->res1 : "",
49 	    user->res2 != NULL ? user->res2 : "") == EOF)
50 		return (1);
51 	attrs = user->attr;
52 	if (attrs != NULL) {
53 		data = attrs->data;
54 		for (i = 0; i < attrs->length; i++) {
55 			if (fprintf(fp, "%s=%s%s",
56 			    data[i].key != NULL ? data[i].key : "",
57 			    data[i].value != NULL ? data[i].value : "",
58 			    i < (attrs->length)-1 ? ";" : "") == EOF)
59 				return (1);
60 		}
61 	}
62 	if (putc('\n', fp) == EOF)
63 		return (1);
64 	return (0);
65 }
66 
67 int
68 dogetuserattr(const char **list)
69 {
70 	struct passwd *pwp;
71 	userattr_t *puser;
72 	int rc = EXC_SUCCESS;
73 	char *ptr;
74 	uid_t uid;
75 
76 	if (list == NULL || *list == NULL) {
77 		setuserattr();
78 		while ((puser = getuserattr()) != NULL)
79 			(void) putuserattr(puser, stdout);
80 		enduserattr();
81 	} else {
82 		for (; *list != NULL; list++) {
83 			uid = strtoul(*list, &ptr, 10);
84 			if (*ptr == '\0' && errno == 0) {
85 				if ((pwp = getpwuid(uid)) == NULL) {
86 					puser = getusernam(*list);
87 				} else {
88 					puser = getusernam(pwp->pw_name);
89 				}
90 			} else {
91 				puser = getusernam(*list);
92 			}
93 			if (puser == NULL)
94 				rc = EXC_NAME_NOT_FOUND;
95 			else
96 				(void) putuserattr(puser, stdout);
97 		}
98 	}
99 
100 	return (rc);
101 }
102