xref: /freebsd/usr.bin/who/who.c (revision 7899f917b1c0ea178f1d2be0cfb452086d079d23)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2002 Tim J. Robbins.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/param.h>
30 #include <sys/types.h>
31 #include <sys/ioctl.h>
32 #include <sys/stat.h>
33 
34 #include <err.h>
35 #include <errno.h>
36 #include <langinfo.h>
37 #include <limits.h>
38 #include <locale.h>
39 #include <paths.h>
40 #include <pwd.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <time.h>
45 #include <timeconv.h>
46 #include <unistd.h>
47 #include <utmpx.h>
48 
49 static void	heading(void);
50 static void	process_utmp(void);
51 static void	quick(void);
52 static void	row(const struct utmpx *);
53 static int	ttywidth(void);
54 static void	usage(void);
55 static void	whoami(void);
56 
57 static int	Hflag;			/* Write column headings */
58 static int	aflag;			/* Print all entries */
59 static int	bflag;			/* Show date of the last reboot */
60 static int	mflag;			/* Show info about current terminal */
61 static int	qflag;			/* "Quick" mode */
62 static int	sflag;			/* Show name, line, time */
63 static int	Tflag;			/* Show terminal state */
64 static int	uflag;			/* Show idle time */
65 
66 int
67 main(int argc, char *argv[])
68 {
69 	int ch;
70 
71 	setlocale(LC_TIME, "");
72 
73 	while ((ch = getopt(argc, argv, "HTabmqsu")) != -1) {
74 		switch (ch) {
75 		case 'H':		/* Write column headings */
76 			Hflag = 1;
77 			break;
78 		case 'T':		/* Show terminal state */
79 			Tflag = 1;
80 			break;
81 		case 'a':		/* Same as -bdlprtTu */
82 			aflag = bflag = Tflag = uflag = 1;
83 			break;
84 		case 'b':		/* Show date of the last reboot */
85 			bflag = 1;
86 			break;
87 		case 'm':		/* Show info about current terminal */
88 			mflag = 1;
89 			break;
90 		case 'q':		/* "Quick" mode */
91 			qflag = 1;
92 			break;
93 		case 's':		/* Show name, line, time */
94 			sflag = 1;
95 			break;
96 		case 'u':		/* Show idle time */
97 			uflag = 1;
98 			break;
99 		default:
100 			usage();
101 			/*NOTREACHED*/
102 		}
103 	}
104 	argc -= optind;
105 	argv += optind;
106 
107 	if (argc >= 2 && strcmp(argv[0], "am") == 0 &&
108 	    (strcmp(argv[1], "i") == 0 || strcmp(argv[1], "I") == 0)) {
109 		/* "who am i" or "who am I", equivalent to -m */
110 		mflag = 1;
111 		argc -= 2;
112 		argv += 2;
113 	}
114 	if (argc > 1)
115 		usage();
116 
117 	if (*argv != NULL) {
118 		if (setutxdb(UTXDB_ACTIVE, *argv) != 0)
119 			err(1, "%s", *argv);
120 	}
121 
122 	if (qflag)
123 		quick();
124 	else {
125 		if (sflag)
126 			Tflag = uflag = 0;
127 		if (Hflag)
128 			heading();
129 		if (mflag)
130 			whoami();
131 		else
132 			process_utmp();
133 	}
134 
135 	endutxent();
136 
137 	exit(0);
138 }
139 
140 static void
141 usage(void)
142 {
143 
144 	fprintf(stderr, "usage: who [-abHmqsTu] [am I] [file]\n");
145 	exit(1);
146 }
147 
148 static void
149 heading(void)
150 {
151 
152 	printf("%-16s ", "NAME");
153 	if (Tflag)
154 		printf("S ");
155 	printf("%-12s %-12s ", "LINE", "TIME");
156 	if (uflag)
157 		printf("IDLE  ");
158 	printf("%-16s\n", "FROM");
159 }
160 
161 static void
162 row(const struct utmpx *ut)
163 {
164 	char buf[80], tty[PATH_MAX];
165 	struct stat sb;
166 	time_t idle, t;
167 	static int d_first = -1;
168 	struct tm *tm;
169 	char state;
170 
171 	if (d_first < 0)
172 		d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
173 
174 	state = '?';
175 	idle = 0;
176 	if (Tflag || uflag) {
177 		snprintf(tty, sizeof(tty), "%s%s", _PATH_DEV, ut->ut_line);
178 		if (stat(tty, &sb) == 0) {
179 			state = sb.st_mode & (S_IWOTH|S_IWGRP) ?
180 			    '+' : '-';
181 			idle = time(NULL) - sb.st_mtime;
182 		}
183 	}
184 
185 	printf("%-16s ", ut->ut_user);
186 	if (Tflag)
187 		printf("%c ", state);
188 	if (ut->ut_type == BOOT_TIME)
189 		printf("%-12s ", "system boot");
190 	else
191 		printf("%-12s ", ut->ut_line);
192 	t = ut->ut_tv.tv_sec;
193 	tm = localtime(&t);
194 	strftime(buf, sizeof(buf), d_first ? "%e %b %R" : "%b %e %R", tm);
195 	printf("%-*s ", 12, buf);
196 	if (uflag) {
197 		if (idle < 60)
198 			printf("  .   ");
199 		else if (idle < 24 * 60 * 60)
200 			printf("%02d:%02d ", (int)(idle / 60 / 60),
201 			    (int)(idle / 60 % 60));
202 		else
203 			printf(" old  ");
204 	}
205 	if (*ut->ut_host != '\0')
206 		printf("(%s)", ut->ut_host);
207 	putchar('\n');
208 }
209 
210 static int
211 ttystat(char *line)
212 {
213 	struct stat sb;
214 	char ttybuf[MAXPATHLEN];
215 
216 	if (line == NULL)
217 		return (0);
218 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
219 	if (stat(ttybuf, &sb) == 0) {
220 		return (0);
221 	} else
222 		return (-1);
223 }
224 
225 static void
226 process_utmp(void)
227 {
228 	struct utmpx *utx;
229 
230 	while ((utx = getutxent()) != NULL) {
231 		if ((aflag || !bflag) && utx->ut_type == USER_PROCESS) {
232 			if (ttystat(utx->ut_line) == 0)
233 				row(utx);
234 		} else if (bflag && utx->ut_type == BOOT_TIME)
235 				row(utx);
236 	}
237 }
238 
239 static void
240 quick(void)
241 {
242 	struct utmpx *utx;
243 	int col, ncols, num;
244 
245 	ncols = ttywidth();
246 	col = num = 0;
247 	while ((utx = getutxent()) != NULL) {
248 		if (utx->ut_type != USER_PROCESS)
249 			continue;
250 		printf("%-16s", utx->ut_user);
251 		if (++col < ncols / (16 + 1))
252 			putchar(' ');
253 		else {
254 			col = 0;
255 			putchar('\n');
256 		}
257 		num++;
258 	}
259 	if (col != 0)
260 		putchar('\n');
261 
262 	printf("# users = %d\n", num);
263 }
264 
265 static void
266 whoami(void)
267 {
268 	struct utmpx ut, *utx;
269 	struct passwd *pwd;
270 	const char *name, *tty;
271 
272 	if ((tty = ttyname(STDIN_FILENO)) == NULL)
273 		tty = "tty??";
274 	else if (strncmp(tty, _PATH_DEV, sizeof _PATH_DEV - 1) == 0)
275 		tty += sizeof _PATH_DEV - 1;
276 	strlcpy(ut.ut_line, tty, sizeof ut.ut_line);
277 
278 	/* Search utmp for our tty, dump first matching record. */
279 	if ((utx = getutxline(&ut)) != NULL && utx->ut_type == USER_PROCESS) {
280 		row(utx);
281 		return;
282 	}
283 
284 	/* Not found; fill the utmp structure with the information we have. */
285 	memset(&ut, 0, sizeof(ut));
286 	if ((pwd = getpwuid(getuid())) != NULL)
287 		name = pwd->pw_name;
288 	else
289 		name = "?";
290 	strlcpy(ut.ut_user, name, sizeof ut.ut_user);
291 	gettimeofday(&ut.ut_tv, NULL);
292 	row(&ut);
293 }
294 
295 static int
296 ttywidth(void)
297 {
298 	struct winsize ws;
299 	long width;
300 	char *cols, *ep;
301 
302 	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0') {
303 		errno = 0;
304 		width = strtol(cols, &ep, 10);
305 		if (errno || width <= 0 || width > INT_MAX || ep == cols ||
306 		    *ep != '\0')
307 			warnx("invalid COLUMNS environment variable ignored");
308 		else
309 			return (width);
310 	}
311 	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) != -1)
312 		return (ws.ws_col);
313 
314 	return (80);
315 }
316