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