w.c 16.8 KB
Newer Older
1 2 3 4 5 6 7
/*
 * w - show what logged in users are doing.
 *
 * Almost entirely rewritten from scratch by Charles Blake circa
 * June 1996. Some vestigal traces of the original may exist.
 * That was done in 1993 by Larry Greenfield with some fixes by
 * Michael K. Johnson.
8 9
 *
 * Changes by Albert Cahalan, 2002.
10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
csmall's avatar
csmall committed
24
 */
Sami Kerola's avatar
Sami Kerola committed
25 26

#include "c.h"
27
#include "fileutils.h"
Sami Kerola's avatar
Sami Kerola committed
28
#include "nls.h"
csmall's avatar
csmall committed
29
#include "proc/devname.h"
30
#include "proc/escape.h"
csmall's avatar
csmall committed
31
#include "proc/procps.h"
32
#include "proc/readproc.h"
csmall's avatar
csmall committed
33
#include "proc/sysinfo.h"
34 35
#include "proc/version.h"
#include "proc/whattime.h"
Sami Kerola's avatar
Sami Kerola committed
36

csmall's avatar
csmall committed
37 38 39
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
40 41 42 43 44 45
#include <getopt.h>
#include <limits.h>
#include <locale.h>
#include <locale.h>
#include <pwd.h>
#include <pwd.h>
46
#include <signal.h>
csmall's avatar
csmall committed
47 48 49 50 51 52 53
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
54
#include <termios.h>
csmall's avatar
csmall committed
55 56 57
#include <time.h>
#include <unistd.h>
#include <utmp.h>
Jaromir Capik's avatar
Jaromir Capik committed
58
#include <arpa/inet.h>
csmall's avatar
csmall committed
59 60

static int ignoreuser = 0;	/* for '-u' */
61
static int oldstyle = 0;	/* for '-o' */
csmall's avatar
csmall committed
62 63 64 65 66
static proc_t **procs;		/* our snapshot of the process table */

typedef struct utmp utmp_t;

#ifdef W_SHOWFROM
67
# define FROM_STRING "on"
csmall's avatar
csmall committed
68
#else
69
# define FROM_STRING "off"
csmall's avatar
csmall committed
70 71
#endif

72
#define MAX_CMD_WIDTH	512
Craig Small's avatar
Craig Small committed
73
#define MIN_CMD_WIDTH   7
74

75 76 77 78
/*
 * This routine is careful since some programs leave utmp strings
 * unprintable. Always outputs at least 16 chars padded with
 * spaces on the right if necessary.
csmall's avatar
csmall committed
79
 */
80 81 82 83 84 85 86 87 88
static void print_host(const char *restrict host, int len, const int fromlen)
{
	const char *last;
	int width = 0;

	if (len > fromlen)
		len = fromlen;
	last = host + len;
	for (; host < last; host++) {
Jaromir Capik's avatar
Jaromir Capik committed
89
		if (*host == '\0') break;
90 91 92 93
		if (isprint(*host) && *host != ' ') {
			fputc(*host, stdout);
			++width;
		} else {
94 95
			fputc('-', stdout);
			++width;
96 97
			break;
		}
csmall's avatar
csmall committed
98 99
	}

100 101 102 103
	/*
	 * space-fill, and a '-' too if needed to ensure the
	 * column exists
	 */
104 105 106 107
	if (!width) {
		fputc('-', stdout);
		++width;
	}
108 109
	while (width++ < fromlen)
		fputc(' ', stdout);
csmall's avatar
csmall committed
110 111
}

Jaromir Capik's avatar
Jaromir Capik committed
112

Jaromir Capik's avatar
Jaromir Capik committed
113 114
/* This routine prints the display part of the host or IPv6 link address interface */
static void print_display_or_interface(const char *restrict host, int len, int restlen)
Jaromir Capik's avatar
Jaromir Capik committed
115
{
116 117
	const char *const end = host + (len > 0 ? len : 0);
	const char *disp, *tmp;
Jaromir Capik's avatar
Jaromir Capik committed
118

Jaromir Capik's avatar
Jaromir Capik committed
119
	if (restlen <= 0) return; /* not enough space for printing anything */
Jaromir Capik's avatar
Jaromir Capik committed
120

Jaromir Capik's avatar
Jaromir Capik committed
121
	/* search for a collon (might be a display) */
122 123
	disp = host;
	while ( (disp < end) && (*disp != ':') && isprint(*disp) ) disp++;
Jaromir Capik's avatar
Jaromir Capik committed
124

Jaromir Capik's avatar
Jaromir Capik committed
125
	/* colon found */
126
	if (disp < end && *disp == ':') {
Jaromir Capik's avatar
Jaromir Capik committed
127 128
		/* detect multiple colons -> IPv6 in the host (not a display) */
		tmp = disp+1;
129
		while ( (tmp < end) && (*tmp != ':') && isprint(*tmp) ) tmp++;
Jaromir Capik's avatar
Jaromir Capik committed
130

131
		if (tmp >= end || *tmp != ':') { /* multiple colons not found - it's a display */
Jaromir Capik's avatar
Jaromir Capik committed
132

Jaromir Capik's avatar
Jaromir Capik committed
133 134 135 136 137 138 139 140 141
			/* number of chars till the end of the input field */
			len -= (disp - host);

			/* if it is still longer than the rest of the output field, then cut it */
			if (len > restlen) len = restlen;

			/* print the display */
			while ((len > 0) && isprint(*disp) && (*disp != ' ')) {
				len--; restlen--;
Jaromir Capik's avatar
Jaromir Capik committed
142 143
				fputc(*disp, stdout);
				disp++;
Jaromir Capik's avatar
Jaromir Capik committed
144 145 146 147
			}

			if ((len > 0) && (*disp != '\0')) { /* space or nonprintable found - replace with dash and stop printing */
				restlen--;
Jaromir Capik's avatar
Jaromir Capik committed
148 149
				fputc('-', stdout);
			}
Jaromir Capik's avatar
Jaromir Capik committed
150
		} else { /* multiple colons found - it's an IPv6 address */
151

Jaromir Capik's avatar
Jaromir Capik committed
152
			/* search for % (interface separator in case of IPv6 link address) */
153
			while ( (tmp < end) && (*tmp != '%') && isprint(*tmp) ) tmp++;
Jaromir Capik's avatar
Jaromir Capik committed
154

155
			if (tmp < end && *tmp == '%') { /* interface separator found */
156

Jaromir Capik's avatar
Jaromir Capik committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
				/* number of chars till the end of the input field */
				len -= (tmp - host);

				/* if it is still longer than the rest of the output field, then cut it */
				if (len > restlen) len = restlen;

				/* print the interface */
				while ((len > 0) && isprint(*tmp) && (*tmp != ' ')) {
					len--; restlen--;
					fputc(*tmp, stdout);
					tmp++;
				}
				if ((len > 0) && (*tmp != '\0')) {  /* space or nonprintable found - replace with dash and stop printing */
					restlen--;
					fputc('-', stdout);
				}
			}
Jaromir Capik's avatar
Jaromir Capik committed
174 175 176 177 178 179 180 181 182 183 184 185 186 187
		}
	}

	/* padding with spaces */
	while (restlen > 0) {
		fputc(' ', stdout);
		restlen--;
	}
}


/* This routine prints either the hostname or the IP address of the remote */
static void print_from(const utmp_t *restrict const u, const int ip_addresses, const int fromlen) {
	char buf[fromlen + 1];
188
	char buf_ipv6[INET6_ADDRSTRLEN];
Jaromir Capik's avatar
Jaromir Capik committed
189
	int len;
190
#ifndef __CYGWIN__
Jaromir Capik's avatar
Jaromir Capik committed
191 192 193 194 195 196 197 198 199 200 201 202 203
	int32_t ut_addr_v6[4];      /* IP address of the remote host */

	if (ip_addresses) { /* -i switch used */
		memcpy(&ut_addr_v6, &u->ut_addr_v6, sizeof(ut_addr_v6));
		if (IN6_IS_ADDR_V4MAPPED(&ut_addr_v6)) {
			/* map back */
			ut_addr_v6[0] = ut_addr_v6[3];
			ut_addr_v6[1] = 0;
			ut_addr_v6[2] = 0;
			ut_addr_v6[3] = 0;
		}
		if (ut_addr_v6[1] || ut_addr_v6[2] || ut_addr_v6[3]) {
			/* IPv6 */
204
			if (!inet_ntop(AF_INET6, &ut_addr_v6, buf_ipv6, sizeof(buf_ipv6))) {
Jaromir Capik's avatar
Jaromir Capik committed
205
				strcpy(buf, ""); /* invalid address, clean the buffer */
206
			} else {
207
				strncpy(buf, buf_ipv6, fromlen); /* address valid, copy to buffer */
Jaromir Capik's avatar
Jaromir Capik committed
208 209 210 211 212 213 214 215 216 217 218 219
			}
		} else {
			/* IPv4 */
			if (!(ut_addr_v6[0] && inet_ntop(AF_INET, &ut_addr_v6[0], buf, sizeof(buf)))) {
				strcpy(buf, ""); /* invalid address, clean the buffer */
			}
		}
		buf[fromlen] = '\0';

		len = strlen(buf);
		if (len) { /* IP address is non-empty, print it (and concatenate with display, if present) */
			fputs(buf, stdout);
Jaromir Capik's avatar
Jaromir Capik committed
220 221
			/* show the display part of the host or IPv6 link addr. interface, if present */
			print_display_or_interface(u->ut_host, UT_HOSTSIZE, fromlen - len);
Jaromir Capik's avatar
Jaromir Capik committed
222 223 224 225 226 227
		} else { /* IP address is empty, print the host instead */
			print_host(u->ut_host, UT_HOSTSIZE, fromlen);
		}
	} else {  /* -i switch NOT used */
		print_host(u->ut_host, UT_HOSTSIZE, fromlen);
	}
228 229 230
#else
	print_host(u->ut_host, UT_HOSTSIZE, fromlen);
#endif
Jaromir Capik's avatar
Jaromir Capik committed
231 232 233
}


234 235 236 237 238
/* compact 7 char format for time intervals (belongs in libproc?) */
static void print_time_ival7(time_t t, int centi_sec, FILE * fout)
{
	if ((long)t < (long)0) {
		/* system clock changed? */
239
		fprintf(fout, "   ?   ");
240 241 242 243 244
		return;
	}
	if (oldstyle) {
		if (t >= 48 * 60 * 60)
			/* > 2 days */
Sami Kerola's avatar
Sami Kerola committed
245
			fprintf(fout, _(" %2ludays"), t / (24 * 60 * 60));
246 247
		else if (t >= 60 * 60)
			/* > 1 hour */
248
		        /* Translation Hint: Hours:Minutes */
249 250 251 252
			fprintf(fout, " %2lu:%02u ", t / (60 * 60),
				(unsigned)((t / 60) % 60));
		else if (t > 60)
			/* > 1 minute */
253
		        /* Translation Hint: Minutes:Seconds */
Sami Kerola's avatar
Sami Kerola committed
254
			fprintf(fout, _(" %2lu:%02um"), t / 60, (unsigned)t % 60);
255 256 257 258 259
		else
			fprintf(fout, "       ");
	} else {
		if (t >= 48 * 60 * 60)
			/* 2 days or more */
Sami Kerola's avatar
Sami Kerola committed
260
			fprintf(fout, _(" %2ludays"), t / (24 * 60 * 60));
261 262
		else if (t >= 60 * 60)
			/* 1 hour or more */
263
		        /* Translation Hint: Hours:Minutes */
Sami Kerola's avatar
Sami Kerola committed
264
			fprintf(fout, _(" %2lu:%02um"), t / (60 * 60),
265 266 267
				(unsigned)((t / 60) % 60));
		else if (t > 60)
			/* 1 minute or more */
268
		        /* Translation Hint: Minutes:Seconds */
269 270
			fprintf(fout, " %2lu:%02u ", t / 60, (unsigned)t % 60);
		else
271
		        /* Translation Hint: Seconds:Centiseconds */
Sami Kerola's avatar
Sami Kerola committed
272
			fprintf(fout, _(" %2lu.%02us"), t, centi_sec);
273
	}
csmall's avatar
csmall committed
274 275
}

276 277 278 279 280 281 282
/* stat the device file to get an idle time */
static time_t idletime(const char *restrict const tty)
{
	struct stat sbuf;
	if (stat(tty, &sbuf) != 0)
		return 0;
	return time(NULL) - sbuf.st_atime;
csmall's avatar
csmall committed
283 284
}

285 286 287
/* 7 character formatted login time */
static void print_logintime(time_t logt, FILE * fout)
{
288 289 290 291
	/* Abbreviated of weekday can be longer than 3 characters,
	 * see for instance hu_HU.  Using 16 is few bytes more than
	 * enough.  */
	char time_str[16];
292 293 294
	time_t curt;
	struct tm *logtm, *curtm;
	int today;
csmall's avatar
csmall committed
295

296
	curt = time(NULL);
297
	if (curt == (time_t)(-1)) goto error;
298
	curtm = localtime(&curt);
299
	if (!curtm) goto error;
300 301 302
	/* localtime returns a pointer to static memory */
	today = curtm->tm_yday;
	logtm = localtime(&logt);
303
	if (!logtm) goto error;
304
	if (curt - logt > 12 * 60 * 60 && logtm->tm_yday != today) {
305
		if (curt - logt > 6 * 24 * 60 * 60) {
306
			if (!strftime(time_str, sizeof(time_str), "%b", logtm)) goto error;
307
			fprintf(fout, " %02d%3s%02d", logtm->tm_mday,
308 309
				time_str, logtm->tm_year % 100);
		} else {
310
			if (!strftime(time_str, sizeof(time_str), "%a", logtm)) goto error;
311
			fprintf(fout, " %3s%02d  ", time_str,
312
				logtm->tm_hour);
313
		}
314 315 316
	} else {
		fprintf(fout, " %02d:%02d  ", logtm->tm_hour, logtm->tm_min);
	}
317 318 319
	return;
error:
	fprintf(fout, " ???????");
320 321 322 323 324 325 326 327
}

/*
 * This function scans the process table accumulating total cpu
 * times for any processes "associated" with this login session.
 * It also searches for the "best" process to report as "(w)hat"
 * the user for that login session is doing currently. This the
 * essential core of 'w'.
csmall's avatar
csmall committed
328
 */
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
static const proc_t *getproc(const utmp_t * restrict const u,
			     const char *restrict const tty,
			     unsigned long long *restrict const jcpu,
			     int *restrict const found_utpid)
{
	int line;
	proc_t **pptr = procs;
	const proc_t *best = NULL;
	const proc_t *secondbest = NULL;
	unsigned uid = ~0U;

	*found_utpid = 0;
	if (!ignoreuser) {
		char buf[UT_NAMESIZE + 1];
		/* pointer to static data */
		struct passwd *passwd_data;
		strncpy(buf, u->ut_user, UT_NAMESIZE);
		buf[UT_NAMESIZE] = '\0';
		passwd_data = getpwnam(buf);
		if (!passwd_data)
			return NULL;
		uid = passwd_data->pw_uid;
		/* OK to have passwd_data go out of scope here */
352
	}
353 354 355 356 357 358
	line = tty_to_dev(tty);
	*jcpu = 0;
	for (; *pptr; pptr++) {
		const proc_t *restrict const tmp = *pptr;
		if (unlikely(tmp->tgid == u->ut_pid)) {
			*found_utpid = 1;
359 360
            if (!best)
                best = tmp;
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
		}
		if (tmp->tty != line)
			continue;
		(*jcpu) += tmp->utime + tmp->stime;
		secondbest = tmp;
		/* same time-logic here as for "best" below */
		if (!(secondbest && tmp->start_time <= secondbest->start_time)) {
			secondbest = tmp;
		}
		if (!ignoreuser && uid != tmp->euid && uid != tmp->ruid)
			continue;
		if (tmp->pgrp != tmp->tpgid)
			continue;
		if (best && tmp->start_time <= best->start_time)
			continue;
		best = tmp;
377
	}
378
	return best ? best : secondbest;
csmall's avatar
csmall committed
379 380
}

381
static void showinfo(utmp_t * u, int formtype, int maxcmd, int from,
Jaromir Capik's avatar
Jaromir Capik committed
382
		     const int userlen, const int fromlen, const int ip_addresses)
383 384 385 386
{
	unsigned long long jcpu;
	int ut_pid_found;
	unsigned i;
387
	char uname[UT_NAMESIZE + 1] = "", tty[5 + UT_LINESIZE + 1] = "/dev/";
388
	const proc_t *best;
csmall's avatar
csmall committed
389

390
	for (i = 0; i < UT_LINESIZE; i++)
391 392 393 394 395
		/* clean up tty if garbled */
		if (isalnum(u->ut_line[i]) || (u->ut_line[i] == '/'))
			tty[i + 5] = u->ut_line[i];
		else
			tty[i + 5] = '\0';
csmall's avatar
csmall committed
396

397 398 399 400 401 402 403 404 405 406 407 408
	best = getproc(u, tty + 5, &jcpu, &ut_pid_found);

	/*
	 * just skip if stale utmp entry (i.e. login proc doesn't
	 * exist). If there is a desire a cmdline flag could be
	 * added to optionally show it with a prefix of (stale)
	 * in front of cmd or something like that.
	 */
	if (!ut_pid_found)
		return;

	/* force NUL term for printf */
409
	strncpy(uname, u->ut_user, UT_NAMESIZE);
410 411 412 413

	if (formtype) {
		printf("%-*.*s%-9.8s", userlen + 1, userlen, uname, u->ut_line);
		if (from)
Jaromir Capik's avatar
Jaromir Capik committed
414
			print_from(u, ip_addresses, fromlen);
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
		print_logintime(u->ut_time, stdout);
		if (*u->ut_line == ':')
			/* idle unknown for xdm logins */
			printf(" ?xdm? ");
		else
			print_time_ival7(idletime(tty), 0, stdout);
		print_time_ival7(jcpu / Hertz, (jcpu % Hertz) * (100. / Hertz),
				 stdout);
		if (best) {
			unsigned long long pcpu = best->utime + best->stime;
			print_time_ival7(pcpu / Hertz,
					 (pcpu % Hertz) * (100. / Hertz),
					 stdout);
		} else
			printf("   ?   ");
	} else {
		printf("%-*.*s%-9.8s", userlen + 1, userlen, u->ut_user,
		       u->ut_line);
		if (from)
Jaromir Capik's avatar
Jaromir Capik committed
434
			print_from(u, ip_addresses, fromlen);
435 436 437 438 439 440 441 442
		if (*u->ut_line == ':')
			/* idle unknown for xdm logins */
			printf(" ?xdm? ");
		else
			print_time_ival7(idletime(tty), 0, stdout);
	}
	fputs(" ", stdout);
	if (likely(best)) {
443
		char cmdbuf[MAX_CMD_WIDTH];
444 445 446 447 448 449 450 451 452 453 454
		escape_command(cmdbuf, best, sizeof cmdbuf, &maxcmd, ESC_ARGS);
		fputs(cmdbuf, stdout);
	} else {
		printf("-");
	}
	fputc('\n', stdout);
}

static void __attribute__ ((__noreturn__))
    usage(FILE * out)
{
Sami Kerola's avatar
Sami Kerola committed
455
	fputs(USAGE_HEADER, out);
456
	fprintf(out,
457
              _(" %s [options]\n"), program_invocation_short_name);
Sami Kerola's avatar
Sami Kerola committed
458
	fputs(USAGE_OPTIONS, out);
459 460 461 462 463 464
	fputs(_(" -h, --no-header     do not print header\n"),out);
	fputs(_(" -u, --no-current    ignore current process username\n"),out);
	fputs(_(" -s, --short         short format\n"),out);
	fputs(_(" -f, --from          show remote hostname field\n"),out);
	fputs(_(" -o, --old-style     old style output\n"),out);
	fputs(_(" -i, --ip-addr       display IP address instead of hostname (if possible)\n"), out);
Sami Kerola's avatar
Sami Kerola committed
465 466 467 468
	fputs(USAGE_SEPARATOR, out);
	fputs(_("     --help     display this help and exit\n"), out);
	fputs(USAGE_VERSION, out);
	fprintf(out, USAGE_MAN_TAIL("w(1)"));
469 470

	exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
csmall's avatar
csmall committed
471 472
}

473 474 475 476 477
int main(int argc, char **argv)
{
	char *user = NULL, *p;
	utmp_t *u;
	struct winsize win;
Jaromir Capik's avatar
Jaromir Capik committed
478 479
	int ch;
	int maxcmd = 80;
480 481 482 483
	int userlen = 8;
	int fromlen = 16;
	char *env_var;

Jaromir Capik's avatar
Jaromir Capik committed
484 485 486 487 488 489
	/* switches (defaults) */
	int header = 1;
	int longform = 1;
	int from = 1;
	int ip_addresses = 0;

490 491 492 493 494 495 496
	enum {
		HELP_OPTION = CHAR_MAX + 1
	};

	static const struct option longopts[] = {
		{"no-header", no_argument, NULL, 'h'},
		{"no-current", no_argument, NULL, 'u'},
497
		{"short", no_argument, NULL, 's'},
498 499
		{"from", no_argument, NULL, 'f'},
		{"old-style", no_argument, NULL, 'o'},
500
		{"ip-addr", no_argument, NULL, 'i'},
501 502 503 504
		{"help", no_argument, NULL, HELP_OPTION},
		{"version", no_argument, NULL, 'V'},
		{NULL, 0, NULL, 0}
	};
csmall's avatar
csmall committed
505

506
#ifdef HAVE_PROGRAM_INVOCATION_NAME
507
	program_invocation_name = program_invocation_short_name;
508
#endif
509 510 511
	setlocale (LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
512
	atexit(close_stdout);
513

csmall's avatar
csmall committed
514
#ifndef W_SHOWFROM
515
	from = 0;
csmall's avatar
csmall committed
516 517
#endif

518
	while ((ch =
Jaromir Capik's avatar
Jaromir Capik committed
519
		getopt_long(argc, argv, "husfoVi", longopts, NULL)) != -1)
520 521 522 523 524 525 526 527 528 529 530 531 532 533
		switch (ch) {
		case 'h':
			header = 0;
			break;
		case 'l':
			longform = 1;
			break;
		case 's':
			longform = 0;
			break;
		case 'f':
			from = !from;
			break;
		case 'V':
Sami Kerola's avatar
Sami Kerola committed
534
			printf(PROCPS_NG_VERSION);
535 536 537 538 539 540 541
			exit(0);
		case 'u':
			ignoreuser = 1;
			break;
		case 'o':
			oldstyle = 1;
			break;
Jaromir Capik's avatar
Jaromir Capik committed
542 543 544 545
		case 'i':
			ip_addresses = 1;
			from = 1;
			break;
546 547 548 549 550
		case HELP_OPTION:
			usage(stdout);
		default:
			usage(stderr);
		}
csmall's avatar
csmall committed
551

552 553
	if ((argv[optind]))
		user = (argv[optind]);
csmall's avatar
csmall committed
554

555
	/* Get user field length from environment */
556
	if ((env_var = getenv("PROCPS_USERLEN")) != NULL) {
557
		int ut_namesize = UT_NAMESIZE;
558
		userlen = atoi(env_var);
559
		if (userlen < 8 || ut_namesize < userlen) {
560
			xwarnx
561 562
			    (_("User length environment PROCPS_USERLEN must be between 8 and %i, ignoring.\n"),
			     ut_namesize);
563 564
			userlen = 8;
		}
565 566
	}
	/* Get from field length from environment */
567 568
	if ((env_var = getenv("PROCPS_FROMLEN")) != NULL) {
		fromlen = atoi(env_var);
569
		if (fromlen < 8 || UT_HOSTSIZE < fromlen) {
570
			xwarnx
571
			    (_("from length environment PROCPS_FROMLEN must be between 8 and %d, ignoring\n"),
572
			     UT_HOSTSIZE);
573 574
			fromlen = 16;
		}
575
	}
576 577
	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 && win.ws_col > 0)
		maxcmd = win.ws_col;
Sami Kerola's avatar
Sami Kerola committed
578
	else if ((p = getenv("COLUMNS")))
579
		maxcmd = atoi(p);
csmall's avatar
csmall committed
580
	else
581
		maxcmd = MAX_CMD_WIDTH;
582 583 584 585 586
#define CLAMP_CMD_WIDTH(cw) do { \
	if ((cw) < MIN_CMD_WIDTH) (cw) = MIN_CMD_WIDTH; \
	if ((cw) > MAX_CMD_WIDTH) (cw) = MAX_CMD_WIDTH; \
} while (0)
	CLAMP_CMD_WIDTH(maxcmd);
587
	maxcmd -= 21 + userlen + (from ? fromlen : 0) + (longform ? 20 : 0);
588 589
	CLAMP_CMD_WIDTH(maxcmd);
#undef CLAMP_CMD_WIDTH
590 591 592 593 594

	procs = readproctab(PROC_FILLCOM | PROC_FILLUSR | PROC_FILLSTAT);

	if (header) {
		/* print uptime and headers */
595
		print_uptime(0);
596 597 598
		/* Translation Hint: Following five uppercase messages are
		 * headers. Try to keep alignment intact.  */
		printf(_("%-*s TTY      "), userlen, _("USER"));
599
		if (from)
600
			printf("%-*s", fromlen - 1, _("FROM"));
601
		if (longform)
602
			printf(_("  LOGIN@   IDLE   JCPU   PCPU WHAT\n"));
603
		else
604
			printf(_("   IDLE WHAT\n"));
albert's avatar
albert committed
605
	}
606 607 608 609 610 611 612 613 614 615

	utmpname(UTMP_FILE);
	setutent();
	if (user) {
		for (;;) {
			u = getutent();
			if (unlikely(!u))
				break;
			if (u->ut_type != USER_PROCESS)
				continue;
616
			if (!strncmp(u->ut_user, user, UT_NAMESIZE))
617
				showinfo(u, longform, maxcmd, from, userlen,
Jaromir Capik's avatar
Jaromir Capik committed
618
					 fromlen, ip_addresses);
619 620 621 622 623 624 625 626 627 628
		}
	} else {
		for (;;) {
			u = getutent();
			if (unlikely(!u))
				break;
			if (u->ut_type != USER_PROCESS)
				continue;
			if (*u->ut_user)
				showinfo(u, longform, maxcmd, from, userlen,
Jaromir Capik's avatar
Jaromir Capik committed
629
					 fromlen, ip_addresses);
630
		}
albert's avatar
albert committed
631
	}
632
	endutent();
csmall's avatar
csmall committed
633

634
	return EXIT_SUCCESS;
csmall's avatar
csmall committed
635
}