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