xref: /titanic_50/usr/src/cmd/whodo/whodo.c (revision da2e3ebdc1edfbc5028edf1354e7dd2fa69a7968)
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 /*
23  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T */
28 /*	  All Rights Reserved	*/
29 
30 /*
31  * University Copyright- Copyright (c) 1982, 1986, 1988
32  * The Regents of the University of California
33  * All Rights Reserved
34  *
35  * University Acknowledgment- Portions of this document are derived from
36  * software developed by the University of California, Berkeley, and its
37  * contributors.
38  */
39 
40 #pragma ident	"%Z%%M%	%I%	%E% SMI"
41 
42 /*
43  * This is the new whodo command which takes advantage of
44  * the /proc interface to gain access to the information
45  * of all the processes currently on the system.
46  *
47  * Maintenance note:
48  *
49  * Much of this code is replicated in w.c.  If you're
50  * fixing bugs here, then you should probably fix 'em there too.
51  */
52 
53 #include <stdio.h>
54 #include <string.h>
55 #include <stdlib.h>
56 #include <ctype.h>
57 #include <fcntl.h>
58 #include <time.h>
59 #include <errno.h>
60 #include <sys/types.h>
61 #include <utmpx.h>
62 #include <sys/utsname.h>
63 #include <sys/stat.h>
64 #include <sys/mkdev.h>
65 #include <dirent.h>
66 #include <procfs.h>		/* /proc header file */
67 #include <sys/wait.h>
68 #include <locale.h>
69 #include <unistd.h>
70 #include <limits.h>
71 #include <priv_utils.h>
72 
73 /*
74  * utmpx defines wider fields for user and line.  For compatibility of output,
75  * we are limiting these to the old maximums in utmp. Define UTMPX_NAMELEN
76  * to use the full lengths.
77  */
78 #ifndef UTMPX_NAMELEN
79 /* XXX - utmp - fix name length */
80 #define	NMAX		(_POSIX_LOGIN_NAME_MAX - 1)
81 #define	LMAX		12
82 #else /* UTMPX_NAMELEN */
83 static struct utmpx dummy;
84 #define	NMAX	(sizeof (dummy.ut_user))
85 #define	LMAX	(sizeof (dummy.ut_line))
86 #endif /* UTMPX_NAMELEN */
87 
88 #define	DIV60(t)	((t+30)/60)    /* x/60 rounded */
89 
90 #ifdef ERR
91 #undef ERR
92 #endif
93 #define	ERR		(-1)
94 
95 #define	DEVNAMELEN	14
96 #define	HSIZE		256		/* size of process hash table */
97 #define	PROCDIR		"/proc"
98 #define	INITPROCESS	(pid_t)1	/* init process pid */
99 #define	NONE		'n'		/* no state */
100 #define	RUNNING		'r'		/* runnable process */
101 #define	ZOMBIE		'z'		/* zombie process */
102 #define	VISITED		'v'		/* marked node as visited */
103 
104 static int	ndevs;			/* number of configured devices */
105 static int	maxdev;			/* slots for configured devices */
106 #define	DNINCR	100
107 static struct devl {			/* device list   */
108 	char	dname[DEVNAMELEN];	/* device name   */
109 	dev_t	ddev;			/* device number */
110 } *devl;
111 
112 struct uproc {
113 	pid_t	p_upid;			/* user process id */
114 	char	p_state;		/* numeric value of process state */
115 	dev_t	p_ttyd;			/* controlling tty of process */
116 	time_t	p_time;			/* ticks of user & system time */
117 	time_t	p_ctime;		/* ticks of child user & system time */
118 	int	p_igintr;		/* 1=ignores SIGQUIT and SIGINT */
119 	char	p_comm[PRARGSZ+1];	/* command */
120 	char	p_args[PRARGSZ+1];	/* command line arguments */
121 	struct uproc	*p_child,	/* first child pointer */
122 			*p_sibling,	/* sibling pointer */
123 			*p_pgrplink,	/* pgrp link */
124 			*p_link;	/* hash table chain pointer */
125 };
126 
127 /*
128  *	define	hash table for struct uproc
129  *	Hash function uses process id
130  *	and the size of the hash table(HSIZE)
131  *	to determine process index into the table.
132  */
133 static struct uproc	pr_htbl[HSIZE];
134 
135 static struct	uproc	*findhash(pid_t);
136 static time_t	findidle(char *);
137 static void	clnarglist(char *);
138 static void	showproc(struct uproc *);
139 static void	showtotals(struct uproc *);
140 static void	calctotals(struct uproc *);
141 static char	*getty(dev_t);
142 static void	prttime(time_t, char *);
143 static void	prtat(time_t *);
144 static void	checkampm(char *);
145 
146 static char	*prog;
147 static int	header = 1;	/* true if -h flag: don't print heading */
148 static int	lflag = 0;	/* true if -l flag: w command format */
149 static char 	*sel_user;	/* login of particular user selected */
150 static time_t	now;		/* current time of day */
151 static time_t	uptime;		/* time of last reboot & elapsed time since */
152 static int	nusers;		/* number of users logged in now */
153 static time_t	idle;		/* number of minutes user is idle */
154 static time_t	jobtime;	/* total cpu time visible */
155 static char	doing[520];	/* process attached to terminal */
156 static time_t	proctime;	/* cpu time of process in doing */
157 static int	empty;
158 static pid_t	curpid;
159 
160 #if SIGQUIT > SIGINT
161 #define	ACTSIZE	SIGQUIT
162 #else
163 #define	ACTSIZE	SIGINT
164 #endif
165 
166 int
167 main(int argc, char *argv[])
168 {
169 	struct utmpx	*ut;
170 	struct utmpx	*utmpbegin;
171 	struct utmpx	*utmpend;
172 	struct utmpx 	*utp;
173 	struct tm		*tm;
174 	struct uproc	*up, *parent, *pgrp;
175 	struct psinfo	info;
176 	struct sigaction actinfo[ACTSIZE];
177 	struct pstatus	statinfo;
178 	size_t		size;
179 	struct stat	sbuf;
180 	struct utsname	uts;
181 	DIR		*dirp;
182 	struct	dirent	*dp;
183 	char 		pname[64];
184 	char 		*fname;
185 	int		procfd;
186 	int		i;
187 	int		days, hrs, mins;
188 	int		entries;
189 
190 	/*
191 	 * This program needs the proc_owner privilege
192 	 */
193 	(void) __init_suid_priv(PU_CLEARLIMITSET, PRIV_PROC_OWNER,
194 	    (char *)NULL);
195 
196 	(void) setlocale(LC_ALL, "");
197 #if !defined(TEXT_DOMAIN)
198 #define	TEXT_DOMAIN "SYS_TEST"
199 #endif
200 	(void) textdomain(TEXT_DOMAIN);
201 
202 	prog = argv[0];
203 
204 	while (argc > 1) {
205 		if (argv[1][0] == '-') {
206 			for (i = 1; argv[1][i]; i++) {
207 				switch (argv[1][i]) {
208 
209 				case 'h':
210 					header = 0;
211 					break;
212 
213 				case 'l':
214 					lflag++;
215 					break;
216 
217 				default:
218 					(void) printf(gettext(
219 					    "usage: %s [ -hl ] [ user ]\n"),
220 					    prog);
221 					exit(1);
222 				}
223 			}
224 		} else {
225 			if (!isalnum(argv[1][0]) || argc > 2) {
226 				(void) printf(gettext(
227 				    "usage: %s [ -hl ] [ user ]\n"), prog);
228 				exit(1);
229 			} else
230 				sel_user = argv[1];
231 		}
232 		argc--; argv++;
233 	}
234 
235 	/*
236 	 * read the UTMPX_FILE (contains information about
237 	 * each logged in user)
238 	 */
239 	if (stat(UTMPX_FILE, &sbuf) == ERR) {
240 		(void) fprintf(stderr, gettext("%s: stat error of %s: %s\n"),
241 			prog, UTMPX_FILE, strerror(errno));
242 		exit(1);
243 	}
244 	entries = sbuf.st_size / sizeof (struct futmpx);
245 	size = sizeof (struct utmpx) * entries;
246 
247 	if ((ut = malloc(size)) == NULL) {
248 		(void) fprintf(stderr, gettext("%s: malloc error of %s: %s\n"),
249 			prog, UTMPX_FILE, strerror(errno));
250 		exit(1);
251 	}
252 
253 	(void) utmpxname(UTMPX_FILE);
254 
255 	utmpbegin = ut;
256 	/* LINTED pointer cast may result in improper alignment */
257 	utmpend = (struct utmpx *)((char *)utmpbegin + size);
258 
259 	setutxent();
260 	while ((utp = getutxent()) != NULL)
261 		(void) memcpy(ut++, utp, sizeof (*ut));
262 	endutxent();
263 
264 	(void) time(&now);	/* get current time */
265 
266 	if (header) {	/* print a header */
267 		if (lflag) {	/* w command format header */
268 			prtat(&now);
269 			for (ut = utmpbegin; ut < utmpend; ut++) {
270 				if (ut->ut_type == USER_PROCESS) {
271 					nusers++;
272 				} else if (ut->ut_type == BOOT_TIME) {
273 					uptime = now - ut->ut_xtime;
274 					uptime += 30;
275 					days = uptime / (60*60*24);
276 					uptime %= (60*60*24);
277 					hrs = uptime / (60*60);
278 					uptime %= (60*60);
279 					mins = uptime / 60;
280 
281 					(void) printf(dcgettext(NULL,
282 					    "  up %d day(s), %d hr(s), "
283 					    "%d min(s)", LC_TIME),
284 					    days, hrs, mins);
285 				}
286 			}
287 
288 			ut = utmpbegin; /* rewind utmp data */
289 			(void) printf(dcgettext(NULL,
290 			    "  %d user(s)\n", LC_TIME), nusers);
291 			(void) printf(dcgettext(NULL, "User     tty           "
292 			    "login@  idle   JCPU   PCPU  what\n", LC_TIME));
293 		} else {	/* standard whodo header */
294 			char date_buf[100];
295 
296 			/*
297 			 * print current time and date
298 			 */
299 			(void) strftime(date_buf, sizeof (date_buf),
300 			    dcgettext(NULL, "%C", LC_TIME), localtime(&now));
301 			(void) printf("%s\n", date_buf);
302 
303 			/*
304 			 * print system name
305 			 */
306 			(void) uname(&uts);
307 			(void) printf("%s\n", uts.nodename);
308 		}
309 	}
310 
311 	/*
312 	 * loop through /proc, reading info about each process
313 	 * and build the parent/child tree
314 	 */
315 	if (!(dirp = opendir(PROCDIR))) {
316 		(void) fprintf(stderr, gettext("%s: could not open %s: %s\n"),
317 			prog, PROCDIR, strerror(errno));
318 		exit(1);
319 	}
320 
321 	while ((dp = readdir(dirp)) != NULL) {
322 		if (dp->d_name[0] == '.')
323 			continue;
324 retry:
325 		(void) snprintf(pname, sizeof (pname),
326 			"%s/%s/", PROCDIR, dp->d_name);
327 		fname = pname + strlen(pname);
328 		(void) strcpy(fname, "psinfo");
329 		if ((procfd = open(pname, O_RDONLY)) < 0)
330 			continue;
331 		if (read(procfd, &info, sizeof (info)) != sizeof (info)) {
332 			int err = errno;
333 			(void) close(procfd);
334 			if (err == EAGAIN)
335 				goto retry;
336 			if (err != ENOENT)
337 				(void) fprintf(stderr, gettext(
338 				    "%s: read() failed on %s: %s\n"),
339 				    prog, pname, strerror(err));
340 			continue;
341 		}
342 		(void) close(procfd);
343 
344 		up = findhash(info.pr_pid);
345 		up->p_ttyd = info.pr_ttydev;
346 		up->p_state = (info.pr_nlwp == 0? ZOMBIE : RUNNING);
347 		up->p_time = 0;
348 		up->p_ctime = 0;
349 		up->p_igintr = 0;
350 		(void) strncpy(up->p_comm, info.pr_fname,
351 		    sizeof (info.pr_fname));
352 		up->p_args[0] = 0;
353 
354 		if (up->p_state != NONE && up->p_state != ZOMBIE) {
355 			(void) strcpy(fname, "status");
356 
357 			/* now we need the proc_owner privilege */
358 			(void) __priv_bracket(PRIV_ON);
359 
360 			procfd = open(pname, O_RDONLY);
361 
362 			/* drop proc_owner privilege after open */
363 			(void) __priv_bracket(PRIV_OFF);
364 
365 			if (procfd  < 0)
366 				continue;
367 
368 			if (read(procfd, &statinfo, sizeof (statinfo))
369 			    != sizeof (statinfo)) {
370 				int err = errno;
371 				(void) close(procfd);
372 				if (err == EAGAIN)
373 					goto retry;
374 				if (err != ENOENT)
375 					(void) fprintf(stderr, gettext(
376 					    "%s: read() failed on %s: %s \n"),
377 					    prog, pname, strerror(err));
378 				continue;
379 			}
380 			(void) close(procfd);
381 
382 			up->p_time = statinfo.pr_utime.tv_sec +
383 			    statinfo.pr_stime.tv_sec;
384 			up->p_ctime = statinfo.pr_cutime.tv_sec +
385 			    statinfo.pr_cstime.tv_sec;
386 
387 			(void) strcpy(fname, "sigact");
388 
389 			/* now we need the proc_owner privilege */
390 			(void) __priv_bracket(PRIV_ON);
391 
392 			procfd = open(pname, O_RDONLY);
393 
394 			/* drop proc_owner privilege after open */
395 			(void) __priv_bracket(PRIV_OFF);
396 
397 			if (procfd  < 0)
398 				continue;
399 			if (read(procfd, actinfo, sizeof (actinfo))
400 			    != sizeof (actinfo)) {
401 				int err = errno;
402 				(void) close(procfd);
403 				if (err == EAGAIN)
404 					goto retry;
405 				if (err != ENOENT)
406 					(void) fprintf(stderr, gettext(
407 					    "%s: read() failed on %s: %s \n"),
408 					    prog, pname, strerror(err));
409 				continue;
410 			}
411 			(void) close(procfd);
412 
413 			up->p_igintr =
414 				actinfo[SIGINT-1].sa_handler == SIG_IGN &&
415 				actinfo[SIGQUIT-1].sa_handler == SIG_IGN;
416 
417 			up->p_args[0] = 0;
418 
419 			/*
420 			 * Process args if there's a chance we'll print it.
421 			 */
422 			if (lflag) { /* w command needs args */
423 				clnarglist(info.pr_psargs);
424 				(void) strcpy(up->p_args, info.pr_psargs);
425 				if (up->p_args[0] == 0 ||
426 				    up->p_args[0] == '-' &&
427 				    up->p_args[1] <= ' ' ||
428 				    up->p_args[0] == '?') {
429 					(void) strcat(up->p_args, " (");
430 					(void) strcat(up->p_args, up->p_comm);
431 					(void) strcat(up->p_args, ")");
432 				}
433 			}
434 
435 		}
436 
437 		/*
438 		 * link pgrp together in case parents go away
439 		 * Pgrp chain is a single linked list originating
440 		 * from the pgrp leader to its group member.
441 		 */
442 		if (info.pr_pgid != info.pr_pid) {	/* not pgrp leader */
443 			pgrp = findhash(info.pr_pgid);
444 			up->p_pgrplink = pgrp->p_pgrplink;
445 			pgrp->p_pgrplink = up;
446 		}
447 		parent = findhash(info.pr_ppid);
448 
449 		/* if this is the new member, link it in */
450 		if (parent->p_upid != INITPROCESS) {
451 			if (parent->p_child) {
452 				up->p_sibling = parent->p_child;
453 				up->p_child = 0;
454 			}
455 			parent->p_child = up;
456 		}
457 
458 	}
459 
460 	/* revert to non-privileged user */
461 	(void) __priv_relinquish();
462 
463 	(void) closedir(dirp);
464 	(void) time(&now);	/* get current time */
465 
466 	/*
467 	 * loop through utmpx file, printing process info
468 	 * about each logged in user
469 	 */
470 	for (ut = utmpbegin; ut < utmpend; ut++) {
471 		time_t tim;
472 
473 		if (ut->ut_type != USER_PROCESS)
474 			continue;
475 		if (sel_user && strncmp(ut->ut_name, sel_user, NMAX) != 0)
476 			continue;	/* we're looking for somebody else */
477 		if (lflag) {	/* -l flag format (w command) */
478 			/* print login name of the user */
479 			(void) printf("%-*.*s ", NMAX, NMAX, ut->ut_name);
480 
481 			/* print tty user is on */
482 			(void) printf("%-*.*s", LMAX, LMAX, ut->ut_line);
483 
484 			/* print when the user logged in */
485 			tim = ut->ut_xtime;
486 			(void) prtat(&tim);
487 
488 			/* print idle time */
489 			idle = findidle(ut->ut_line);
490 			if (idle >= 36 * 60)
491 				(void) printf(dcgettext(NULL, "%2ddays ",
492 				    LC_TIME), (idle + 12 * 60) / (24 * 60));
493 			else
494 				prttime(idle, " ");
495 			showtotals(findhash((pid_t)ut->ut_pid));
496 		} else {	/* standard whodo format */
497 			tim = ut->ut_xtime;
498 			tm = localtime(&tim);
499 			(void) printf("\n%-*.*s %-*.*s %2.1d:%2.2d\n",
500 			    LMAX, LMAX, ut->ut_line,
501 			    NMAX, NMAX, ut->ut_name, tm->tm_hour, tm->tm_min);
502 			showproc(findhash((pid_t)ut->ut_pid));
503 		}
504 	}
505 
506 	return (0);
507 }
508 
509 /*
510  * Used for standard whodo format.
511  * This is the recursive routine descending the process
512  * tree starting from the given process pointer(up).
513  * It used depth-first search strategy and also marked
514  * each node as printed as it traversed down the tree.
515  */
516 static void
517 showproc(struct uproc *up)
518 {
519 	struct	uproc	*zp;
520 
521 	if (up->p_state == VISITED) /* we already been here */
522 		return;
523 	/* print the data for this process */
524 	if (up->p_state == ZOMBIE)
525 		(void) printf("    %-*.*s %5d %4.1ld:%2.2ld %s\n",
526 		    LMAX, LMAX, "  ?", (int)up->p_upid, 0L, 0L, "<defunct>");
527 	else if (up->p_state != NONE) {
528 		(void) printf("    %-*.*s %5d %4.1ld:%2.2ld %s\n",
529 		    LMAX, LMAX, getty(up->p_ttyd), (int)up->p_upid,
530 		    up->p_time / 60L, up->p_time % 60L,
531 		    up->p_comm);
532 	}
533 	up->p_state = VISITED;
534 
535 	/* descend for its children */
536 	if (up->p_child) {
537 		showproc(up->p_child);
538 		for (zp = up->p_child->p_sibling; zp; zp = zp->p_sibling) {
539 			showproc(zp);
540 		}
541 	}
542 
543 	/* print the pgrp relation */
544 	if (up->p_pgrplink)
545 		showproc(up->p_pgrplink);
546 }
547 
548 
549 /*
550  * Used for -l flag (w command) format.
551  * Prints the CPU time for all processes & children,
552  * and the cpu time for interesting process,
553  * and what the user is doing.
554  */
555 static void
556 showtotals(struct uproc *up)
557 {
558 	jobtime = 0;
559 	proctime = 0;
560 	empty = 1;
561 	curpid = -1;
562 	(void) strcpy(doing, "-"); /* default act: normally never prints */
563 	calctotals(up);
564 
565 	/* print CPU time for all processes & children */
566 	/* and need to convert clock ticks to seconds first */
567 	prttime((time_t)jobtime, " ");
568 
569 	/* print cpu time for interesting process */
570 	/* and need to convert clock ticks to seconds first */
571 	prttime((time_t)proctime, " ");
572 
573 	/* what user is doing, current process */
574 	(void) printf(" %-.32s\n", doing);
575 }
576 
577 /*
578  *  Used for -l flag (w command) format.
579  *  This recursive routine descends the process
580  *  tree starting from the given process pointer(up).
581  *  It used depth-first search strategy and also marked
582  *  each node as visited as it traversed down the tree.
583  *  It calculates the process time for all processes &
584  *  children.  It also finds the "interesting" process
585  *  and determines its cpu time and command.
586  */
587 static void
588 calctotals(struct uproc *up)
589 {
590 	struct uproc	*zp;
591 
592 	if (up->p_state == VISITED)
593 		return;
594 	up->p_state = VISITED;
595 	if (up->p_state == NONE || up->p_state == ZOMBIE)
596 		return;
597 	jobtime += up->p_time + up->p_ctime;
598 	proctime += up->p_time;
599 
600 	if (empty && !up->p_igintr) {
601 		empty = 0;
602 		curpid = -1;
603 	}
604 
605 	if (up->p_upid > curpid && (!up->p_igintr || empty)) {
606 		curpid = up->p_upid;
607 		(void) strcpy(doing, up->p_args);
608 	}
609 
610 	/* descend for its children */
611 	if (up->p_child) {
612 		calctotals(up->p_child);
613 		for (zp = up->p_child->p_sibling; zp; zp = zp->p_sibling)
614 			calctotals(zp);
615 	}
616 }
617 
618 static char *
619 devadd(char *name, dev_t ddev)
620 {
621 	struct devl *dp;
622 	int leng, start, i;
623 
624 	if (ndevs == maxdev) {
625 		maxdev += DNINCR;
626 		dp = realloc(devl, maxdev * sizeof (struct devl));
627 		if (!dp) {
628 			(void) fprintf(stderr,
629 				gettext("%s: out of memory!: %s\n"),
630 				prog, strerror(errno));
631 			exit(1);
632 		}
633 		devl = dp;
634 	}
635 	dp = &devl[ndevs++];
636 
637 	dp->ddev = ddev;
638 	if (name == NULL) {
639 		(void) strcpy(dp->dname, "  ?  ");
640 		return (dp->dname);
641 	}
642 
643 	leng = strlen(name);
644 	if (leng < DEVNAMELEN + 4) {
645 		/* strip off "/dev/" */
646 		(void) strcpy(dp->dname, &name[5]);
647 	} else {
648 		/* strip enough off the front to fit */
649 		start = leng - DEVNAMELEN - 1;
650 
651 		for (i = start; i < leng && name[i] != '/'; i++)
652 				;
653 		if (i == leng)
654 			(void) strncpy(dp->dname, &name[start], DEVNAMELEN);
655 		else
656 			(void) strncpy(dp->dname, &name[i+1], DEVNAMELEN);
657 	}
658 	return (dp->dname);
659 }
660 
661 static char *
662 devlookup(dev_t ddev)
663 {
664 	struct devl *dp;
665 	int i;
666 
667 	for (dp = devl, i = 0; i < ndevs; dp++, i++) {
668 		if (dp->ddev == ddev)
669 			return (dp->dname);
670 	}
671 	return (NULL);
672 }
673 
674 /*
675  * This routine gives back a corresponding device name
676  * from the device number given.
677  */
678 static char *
679 getty(dev_t dev)
680 {
681 	extern char *_ttyname_dev(dev_t, char *, size_t);
682 	char devname[TTYNAME_MAX];
683 	char *retval;
684 
685 	if (dev == PRNODEV)
686 		return ("  ?  ");
687 
688 	if ((retval = devlookup(dev)) != NULL)
689 		return (retval);
690 
691 	retval = _ttyname_dev(dev, devname, sizeof (devname));
692 	return (devadd(retval, dev));
693 }
694 
695 /*
696  * Findhash  finds the appropriate entry in the process
697  * hash table (pr_htbl) for the given pid in case that
698  * pid exists on the hash chain. It returns back a pointer
699  * to that uproc structure. If this is a new pid, it allocates
700  * a new node, initializes it, links it into the chain (after
701  * head) and returns a structure pointer.
702  */
703 static struct uproc *
704 findhash(pid_t pid)
705 {
706 	struct uproc *up, *tp;
707 
708 	tp = up = &pr_htbl[(int)pid % HSIZE];
709 	if (up->p_upid == 0) {			/* empty slot */
710 		up->p_upid = pid;
711 		up->p_state = NONE;
712 		up->p_child = up->p_sibling = up->p_pgrplink = up->p_link = 0;
713 		return (up);
714 	}
715 	if (up->p_upid == pid) {		/* found in hash table */
716 		return (up);
717 	}
718 	for (tp = up->p_link; tp; tp = tp->p_link) {	/* follow chain */
719 		if (tp->p_upid == pid) {
720 			return (tp);
721 		}
722 	}
723 	tp = malloc(sizeof (*tp));		/* add new node */
724 	if (!tp) {
725 		(void) fprintf(stderr, gettext("%s: out of memory!: %s\n"),
726 			prog, strerror(errno));
727 		exit(1);
728 	}
729 	(void) memset((char *)tp, 0, sizeof (*tp));
730 	tp->p_upid = pid;
731 	tp->p_state = NONE;
732 	tp->p_child = tp->p_sibling = tp->p_pgrplink = (pid_t)0;
733 	tp->p_link = up->p_link;		/* insert after head */
734 	up->p_link = tp;
735 	return (tp);
736 }
737 
738 #define	HR	(60 * 60)
739 #define	DAY	(24 * HR)
740 #define	MON	(30 * DAY)
741 
742 /*
743  * prints a time in hours and minutes or minutes and seconds.
744  * The character string 'tail' is printed at the end, obvious
745  * strings to pass are "", " ", or "am".
746  */
747 static void
748 prttime(time_t tim, char *tail)
749 {
750 	if (tim >= 60)
751 		(void) printf(dcgettext(NULL, "%3d:%02d", LC_TIME),
752 		    (int)tim/60, (int)tim%60);
753 	else if (tim > 0)
754 		(void) printf(dcgettext(NULL, "    %2d", LC_TIME), (int)tim);
755 	else
756 		(void) printf("      ");
757 	(void) printf("%s", tail);
758 }
759 
760 
761 /*
762  * prints a 12 hour time given a pointer to a time of day
763  */
764 static void
765 prtat(time_t *time)
766 {
767 	struct tm *p;
768 
769 	p = localtime(time);
770 	if (now - *time <= 18 * HR) {
771 		char timestr[50];
772 		(void) strftime(timestr, sizeof (timestr),
773 		    dcgettext(NULL, " %l:%M""%p", LC_TIME), p);
774 		checkampm(timestr);
775 		(void) printf("%s", timestr);
776 	} else if (now - *time <= 7 * DAY) {
777 		char weekdaytime[20];
778 
779 		(void) strftime(weekdaytime, sizeof (weekdaytime),
780 		    dcgettext(NULL, "%a%l%p", LC_TIME), p);
781 		checkampm(weekdaytime);
782 		(void) printf(" %s", weekdaytime);
783 	} else {
784 		char monthtime[20];
785 
786 		(void) strftime(monthtime, sizeof (monthtime),
787 		    dcgettext(NULL, "%e%b%y", LC_TIME), p);
788 		(void) printf(" %s", monthtime);
789 	}
790 }
791 
792 /*
793  * find & return number of minutes current tty has been idle
794  */
795 static time_t
796 findidle(char *devname)
797 {
798 	struct stat stbuf;
799 	time_t lastaction, diff;
800 	char ttyname[64];
801 
802 	(void) strcpy(ttyname, "/dev/");
803 	(void) strcat(ttyname, devname);
804 	if (stat(ttyname, &stbuf) != -1) {
805 		lastaction = stbuf.st_atime;
806 		diff = now - lastaction;
807 		diff = DIV60(diff);
808 		if (diff < 0)
809 			diff = 0;
810 	} else
811 		diff = 0;
812 	return (diff);
813 }
814 
815 /*
816  * given a pointer to the argument string clean out unsavory characters.
817  */
818 static void
819 clnarglist(char *arglist)
820 {
821 	char	*c;
822 	int	err = 0;
823 
824 	/* get rid of unsavory characters */
825 	for (c = arglist; *c == NULL; c++) {
826 		if ((*c < ' ') || (*c > 0176)) {
827 			if (err++ > 5) {
828 				*arglist = NULL;
829 				break;
830 			}
831 			*c = '?';
832 		}
833 	}
834 }
835 
836 /* replaces all occurences of AM/PM with am/pm */
837 static void
838 checkampm(char *str)
839 {
840 	char *ampm;
841 	while ((ampm = strstr(str, "AM")) != NULL ||
842 	    (ampm = strstr(str, "PM")) != NULL) {
843 		*ampm = tolower(*ampm);
844 		*(ampm+1) = tolower(*(ampm+1));
845 	}
846 }
847