xref: /freebsd/usr.bin/who/who.c (revision 9a14aa017b21c292740c00ee098195cd46642730)
1 /*-
2  * Copyright (c) 2002 Tim J. Robbins.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 #include <sys/types.h>
32 #include <sys/ioctl.h>
33 #include <sys/stat.h>
34 
35 #include <err.h>
36 #include <errno.h>
37 #include <langinfo.h>
38 #include <limits.h>
39 #include <locale.h>
40 #include <paths.h>
41 #include <pwd.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <time.h>
46 #include <timeconv.h>
47 #include <unistd.h>
48 #include <utmpx.h>
49 
50 static void	heading(void);
51 static void	boottime(void);
52 static void	process_utmp(void);
53 static void	quick(void);
54 static void	row(const struct utmpx *);
55 static int	ttywidth(void);
56 static void	usage(void);
57 static void	whoami(void);
58 
59 static int	Hflag;			/* Write column headings */
60 static int	bflag;			/* Show date of the last reboot */
61 static int	mflag;			/* Show info about current terminal */
62 static int	qflag;			/* "Quick" mode */
63 static int	sflag;			/* Show name, line, time */
64 static int	Tflag;			/* Show terminal state */
65 static int	uflag;			/* Show idle time */
66 
67 int
68 main(int argc, char *argv[])
69 {
70 	int ch;
71 
72 	setlocale(LC_TIME, "");
73 
74 	while ((ch = getopt(argc, argv, "HTbmqsu")) != -1) {
75 		switch (ch) {
76 		case 'H':		/* Write column headings */
77 			Hflag = 1;
78 			break;
79 		case 'T':		/* Show terminal state */
80 			Tflag = 1;
81 			break;
82 		case 'b':		/* Show date of the last reboot */
83 			bflag = 1;
84 			break;
85 		case 'm':		/* Show info about current terminal */
86 			mflag = 1;
87 			break;
88 		case 'q':		/* "Quick" mode */
89 			qflag = 1;
90 			break;
91 		case 's':		/* Show name, line, time */
92 			sflag = 1;
93 			break;
94 		case 'u':		/* Show idle time */
95 			uflag = 1;
96 			break;
97 		default:
98 			usage();
99 			/*NOTREACHED*/
100 		}
101 	}
102 	argc -= optind;
103 	argv += optind;
104 
105 	if (argc >= 2 && strcmp(argv[0], "am") == 0 &&
106 	    (strcmp(argv[1], "i") == 0 || strcmp(argv[1], "I") == 0)) {
107 		/* "who am i" or "who am I", equivalent to -m */
108 		mflag = 1;
109 		argc -= 2;
110 		argv += 2;
111 	}
112 	if (argc > 1)
113 		usage();
114 
115 	if (*argv != NULL) {
116 		if (setutxdb(UTXDB_ACTIVE, *argv) != 0)
117 			err(1, "%s", *argv);
118 	}
119 
120 	if (qflag)
121 		quick();
122 	else {
123 		if (sflag)
124 			Tflag = uflag = 0;
125 		if (Hflag)
126 			heading();
127 		if (mflag)
128 			whoami();
129 		else if (bflag)
130 			boottime();
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 [-bHmqsTu] [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 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
217 	if (stat(ttybuf, &sb) == 0) {
218 		return (0);
219 	} else
220 		return (-1);
221 }
222 
223 static void
224 process_utmp(void)
225 {
226 	struct utmpx *utx;
227 
228 	while ((utx = getutxent()) != NULL) {
229 		if (utx->ut_type != USER_PROCESS)
230 			continue;
231 		if (ttystat(utx->ut_line) != 0)
232 			continue;
233 		row(utx);
234 	}
235 }
236 
237 static void
238 boottime(void)
239 {
240 	struct utmpx u1, *u2;
241 
242 	u1.ut_type = BOOT_TIME;
243 	if ((u2 = getutxid(&u1)) == NULL)
244 		return;
245 	row(u2);
246 }
247 
248 static void
249 quick(void)
250 {
251 	struct utmpx *utx;
252 	int col, ncols, num;
253 
254 	ncols = ttywidth();
255 	col = num = 0;
256 	while ((utx = getutxent()) != NULL) {
257 		if (utx->ut_type != USER_PROCESS)
258 			continue;
259 		printf("%-16s", utx->ut_user);
260 		if (++col < ncols / (16 + 1))
261 			putchar(' ');
262 		else {
263 			col = 0;
264 			putchar('\n');
265 		}
266 		num++;
267 	}
268 	if (col != 0)
269 		putchar('\n');
270 
271 	printf("# users = %d\n", num);
272 }
273 
274 static void
275 whoami(void)
276 {
277 	struct utmpx ut, *utx;
278 	struct passwd *pwd;
279 	const char *name, *tty;
280 
281 	if ((tty = ttyname(STDIN_FILENO)) == NULL)
282 		tty = "tty??";
283 	else if (strncmp(tty, _PATH_DEV, sizeof _PATH_DEV - 1) == 0)
284 		tty += sizeof _PATH_DEV - 1;
285 	strlcpy(ut.ut_line, tty, sizeof ut.ut_line);
286 
287 	/* Search utmp for our tty, dump first matching record. */
288 	if ((utx = getutxline(&ut)) != NULL && utx->ut_type == USER_PROCESS) {
289 		row(utx);
290 		return;
291 	}
292 
293 	/* Not found; fill the utmp structure with the information we have. */
294 	memset(&ut, 0, sizeof(ut));
295 	if ((pwd = getpwuid(getuid())) != NULL)
296 		name = pwd->pw_name;
297 	else
298 		name = "?";
299 	strlcpy(ut.ut_user, name, sizeof ut.ut_user);
300 	gettimeofday(&ut.ut_tv, NULL);
301 	row(&ut);
302 }
303 
304 static int
305 ttywidth(void)
306 {
307 	struct winsize ws;
308 	long width;
309 	char *cols, *ep;
310 
311 	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0') {
312 		errno = 0;
313 		width = strtol(cols, &ep, 10);
314 		if (errno || width <= 0 || width > INT_MAX || ep == cols ||
315 		    *ep != '\0')
316 			warnx("invalid COLUMNS environment variable ignored");
317 		else
318 			return (width);
319 	}
320 	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) != -1)
321 		return (ws.ws_col);
322 
323 	return (80);
324 }
325