xref: /illumos-gate/usr/src/cmd/lp/lib/lp/getname.c (revision 2a8bcb4e)
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 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
23 /*	  All Rights Reserved  	*/
24 
25 /*
26  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
27  * Use is subject to license terms.
28  */
29 
30 /*
31  *	getname(name)  --  get logname
32  *
33  *		getname tries to find the user's logname from:
34  *			${LOGNAME}, if set and if it is telling the truth
35  *			/etc/passwd, otherwise
36  *
37  *		The logname is returned as the value of the function.
38  *
39  *		Getname returns the user's user id converted to ASCII
40  *		for unknown lognames.
41  *
42  */
43 
44 #include "string.h"
45 #include "pwd.h"
46 #include "errno.h"
47 #include "sys/types.h"
48 #include "stdlib.h"
49 #include "unistd.h"
50 
51 #include "lp.h"
52 
53 char *
54 #if	defined(__STDC__)
getname(void)55 getname (
56 	void
57 )
58 #else
59 getname ()
60 #endif
61 {
62 	uid_t			uid;
63 	struct passwd		*p;
64 	static char		*logname	= 0;
65 	char			*l;
66 
67 	if (logname)
68 		return (logname);
69 
70 	uid = getuid();
71 
72 	setpwent ();
73 	if (
74 		!(l = getenv("LOGNAME"))
75 	     || !(p = getpwnam(l))
76 	     || p->pw_uid != uid
77 	)
78 		if ((p = getpwuid(uid)))
79 			l = p->pw_name;
80 		else
81 			l = 0;
82 	endpwent ();
83 
84 	if (l)
85 		logname = Strdup(l);
86 	else {
87 		if (uid > 0) {
88 			logname = Malloc(10 + 1);
89 			if (logname)
90 				sprintf (logname, "%d", uid);
91 		}
92 	}
93 
94 	if (!logname)
95 	{
96 		errno = ENOMEM;
97 	}
98 	else
99 	{
100 		errno = 0;
101 	}
102 
103 	return (logname);
104 }
105