xref: /illumos-gate/usr/src/lib/libc/port/gen/getpw.c (revision 4b22b9337f359bfd063322244f5336cc7c6ffcfa)
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  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*	Copyright (c) 1988 AT&T	*/
29 /*	  All Rights Reserved  	*/
30 
31 
32 /*	3.0 SID #	1.2	*/
33 #pragma weak getpw = _getpw
34 
35 #include "synonyms.h"
36 #include "file64.h"
37 #include <sys/types.h>
38 #include <mtlib.h>
39 #include <ctype.h>
40 #include <thread.h>
41 #include <synch.h>
42 #include <stdio.h>
43 #include "stdiom.h"
44 #include "libc.h"
45 
46 static FILE *pwf;
47 static mutex_t _pwlock = DEFAULTMUTEX;
48 const char *PASSWD = "/etc/passwd";
49 
50 int
51 getpw(uid_t uid, char buf[])
52 {
53 	int n, c;
54 	char *bp;
55 	FILE *fp;
56 	rmutex_t *lk;
57 
58 	if (pwf == NULL) {
59 		fp = fopen(PASSWD, "rF");
60 		lmutex_lock(&_pwlock);
61 		if (pwf == NULL) {
62 			if ((pwf = fp) == NULL) {
63 				lmutex_unlock(&_pwlock);
64 				return (1);
65 			}
66 			fp = NULL;
67 		}
68 		lmutex_unlock(&_pwlock);
69 		if (fp != NULL)		/* someone beat us to it */
70 			(void) fclose(fp);
71 	}
72 
73 	FLOCKFILE(lk, pwf);
74 	_rewind_unlocked(pwf);
75 
76 	for (;;) {
77 		bp = buf;
78 		while ((c = GETC(pwf)) != '\n') {
79 			if (c == EOF) {
80 				FUNLOCKFILE(lk);
81 				return (1);
82 			}
83 			*bp++ = (char)c;
84 		}
85 		*bp = '\0';
86 		bp = buf;
87 		n = 3;
88 		while (--n)
89 			while ((c = *bp++) != ':')
90 				if (c == '\n') {
91 					FUNLOCKFILE(lk);
92 					return (1);
93 				}
94 		while ((c = *bp++) != ':')
95 			if (isdigit(c))
96 				n = n*10+c-'0';
97 			else
98 				continue;
99 		if (n == uid) {
100 			FUNLOCKFILE(lk);
101 			return (0);
102 		}
103 	}
104 }
105