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