xref: /illumos-gate/usr/src/cmd/logname/logname.c (revision fa4a3e77edc40df6d92e8da6fc4961d275e9896d)
1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright 2019 Robert Mustacchi
14  */
15 
16 #include <unistd.h>
17 #include <err.h>
18 #include <sys/types.h>
19 #include <unistd.h>
20 #include <stdlib.h>
21 #include <pwd.h>
22 #include <libgen.h>
23 #include <locale.h>
24 #include <libintl.h>
25 
26 int
27 main(int argc, char *argv[])
28 {
29 	char *name;
30 	char uidbuf[32];
31 
32 	(void) setlocale(LC_ALL, "");
33 #if !defined(TEXT_DOMAIN)
34 #define	TEXT_DOMAIN "SYS_TEST"
35 #endif
36 	(void) textdomain(TEXT_DOMAIN);
37 
38 	if (argc != 1) {
39 		warnx(gettext("illegal arguments"));
40 		(void) fprintf(stderr, gettext("Usage: %s\n"),
41 		    basename(argv[0]));
42 		return (1);
43 	}
44 
45 	/*
46 	 * In some cases getlogin() can fail. The most common case is due to
47 	 * something like using script(1). Deal with that by falling back to the
48 	 * current user ID, which is as accurate as we can be. This is what the
49 	 * ksh93 version used to do.
50 	 */
51 	name = getlogin();
52 	if (name == NULL) {
53 		uid_t uid;
54 		struct passwd *pass;
55 
56 		uid = getuid();
57 		pass = getpwuid(uid);
58 		if (pass != NULL) {
59 			name = pass->pw_name;
60 		} else {
61 			(void) snprintf(uidbuf, sizeof (uidbuf), "%u", uid);
62 			name = uidbuf;
63 		}
64 	}
65 
66 	if (printf("%s\n", name) == -1) {
67 		err(EXIT_FAILURE, gettext("failed to write out login name"));
68 	}
69 
70 	return (0);
71 }
72