[BACK]Return to w.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / w

Annotation of src/usr.bin/w/w.c, Revision 1.31

1.31    ! deraadt     1: /*     $OpenBSD: w.c,v 1.30 2000/07/07 21:09:02 deraadt Exp $  */
1.4       deraadt     2:
1.1       deraadt     3: /*-
                      4:  * Copyright (c) 1980, 1991, 1993, 1994
                      5:  *     The Regents of the University of California.  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:  * 3. All advertising materials mentioning features or use of this software
                     16:  *    must display the following acknowledgement:
                     17:  *     This product includes software developed by the University of
                     18:  *     California, Berkeley and its contributors.
                     19:  * 4. Neither the name of the University nor the names of its contributors
                     20:  *    may be used to endorse or promote products derived from this software
                     21:  *    without specific prior written permission.
                     22:  *
                     23:  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
                     24:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     25:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     26:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
                     27:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     28:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
                     29:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     30:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     31:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     32:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     33:  * SUCH DAMAGE.
                     34:  */
                     35:
                     36: #ifndef lint
                     37: static char copyright[] =
                     38: "@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
                     39:        The Regents of the University of California.  All rights reserved.\n";
                     40: #endif /* not lint */
                     41:
                     42: #ifndef lint
1.23      millert    43: #if 0
1.1       deraadt    44: static char sccsid[] = "@(#)w.c        8.4 (Berkeley) 4/16/94";
1.23      millert    45: #else
1.31    ! deraadt    46: static char *rcsid = "$OpenBSD: w.c,v 1.30 2000/07/07 21:09:02 deraadt Exp $";
1.23      millert    47: #endif
1.1       deraadt    48: #endif /* not lint */
                     49:
                     50: /*
                     51:  * w - print system status (who and what)
                     52:  *
                     53:  * This program is similar to the systat command on Tenex/Tops 10/20
                     54:  *
                     55:  */
                     56: #include <sys/param.h>
                     57: #include <sys/time.h>
                     58: #include <sys/stat.h>
                     59: #include <sys/sysctl.h>
                     60: #include <sys/proc.h>
                     61: #include <sys/user.h>
                     62: #include <sys/ioctl.h>
                     63: #include <sys/socket.h>
                     64: #include <sys/tty.h>
                     65:
                     66: #include <machine/cpu.h>
                     67: #include <netinet/in.h>
                     68: #include <arpa/inet.h>
                     69:
                     70: #include <ctype.h>
                     71: #include <err.h>
                     72: #include <errno.h>
                     73: #include <fcntl.h>
                     74: #include <kvm.h>
                     75: #include <netdb.h>
                     76: #include <nlist.h>
                     77: #include <paths.h>
                     78: #include <stdio.h>
                     79: #include <stdlib.h>
                     80: #include <string.h>
                     81: #include <tzfile.h>
                     82: #include <unistd.h>
1.5       deraadt    83: #include <limits.h>
1.1       deraadt    84: #include <utmp.h>
                     85: #include <vis.h>
                     86:
                     87: #include "extern.h"
                     88:
                     89: struct timeval boottime;
                     90: struct utmp    utmp;
                     91: struct winsize ws;
                     92: kvm_t         *kd;
                     93: time_t         now;            /* the current time of day */
                     94: time_t         uptime;         /* time of last reboot & elapsed time since */
                     95: int            ttywidth;       /* width of tty */
                     96: int            argwidth;       /* width of tty */
                     97: int            header = 1;     /* true if -h flag: don't print heading */
1.6       deraadt    98: int            nflag = 1;      /* true if -n flag: don't convert addrs */
1.1       deraadt    99: int            sortidle;       /* sort bu idle time */
                    100: char          *sel_user;       /* login of particular user selected */
                    101: char           domain[MAXHOSTNAMELEN];
                    102:
                    103: /*
                    104:  * One of these per active utmp entry.
                    105:  */
                    106: struct entry {
                    107:        struct  entry *next;
                    108:        struct  utmp utmp;
                    109:        dev_t   tdev;           /* dev_t of terminal */
                    110:        time_t  idle;           /* idle time of terminal in seconds */
                    111:        struct  kinfo_proc *kp; /* `most interesting' proc */
                    112: } *ep, *ehead = NULL, **nextp = &ehead;
                    113:
                    114: static void     pr_args __P((struct kinfo_proc *));
                    115: static void     pr_header __P((time_t *, int));
                    116: static struct stat
                    117:                *ttystat __P((char *));
                    118: static void     usage __P((int));
                    119:
                    120: int
                    121: main(argc, argv)
                    122:        int argc;
                    123:        char **argv;
                    124: {
                    125:        extern char *__progname;
                    126:        struct kinfo_proc *kp;
                    127:        struct hostent *hp;
                    128:        struct stat *stp;
                    129:        FILE *ut;
1.27      deraadt   130:        struct in_addr addr;
1.1       deraadt   131:        int ch, i, nentries, nusers, wcmd;
                    132:        char *memf, *nlistf, *p, *x;
1.5       deraadt   133:        char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
1.1       deraadt   134:
                    135:        /* Are we w(1) or uptime(1)? */
                    136:        p = __progname;
                    137:        if (*p == '-')
                    138:                p++;
1.19      mickey    139:        if (p[0] == 'w' && p[1] == '\0') {
                    140:                wcmd = 1;
                    141:                p = "hiflM:N:asuw";
                    142:        } else if (!strcmp(p, "uptime")) {
1.1       deraadt   143:                wcmd = 0;
1.28      millert   144:                p = "M:N:";
1.19      mickey    145:        } else
1.20      kstailey  146:                errx(1,
                    147:                 "this program should be invoked only as \"w\" or \"uptime\"");
1.1       deraadt   148:
                    149:        memf = nlistf = NULL;
1.12      millert   150:        while ((ch = getopt(argc, argv, p)) != -1)
1.1       deraadt   151:                switch (ch) {
                    152:                case 'h':
                    153:                        header = 0;
                    154:                        break;
                    155:                case 'i':
                    156:                        sortidle = 1;
                    157:                        break;
                    158:                case 'M':
                    159:                        header = 0;
                    160:                        memf = optarg;
                    161:                        break;
                    162:                case 'N':
                    163:                        nlistf = optarg;
                    164:                        break;
1.6       deraadt   165:                case 'a':
                    166:                        nflag = 0;
1.1       deraadt   167:                        break;
                    168:                case 'f': case 'l': case 's': case 'u': case 'w':
                    169:                        warnx("[-flsuw] no longer supported");
                    170:                        /* FALLTHROUGH */
                    171:                case '?':
                    172:                default:
                    173:                        usage(wcmd);
                    174:                }
                    175:        argc -= optind;
                    176:        argv += optind;
                    177:
1.3       deraadt   178:        /*
                    179:         * Discard setgid privileges if not the running kernel so that bad
                    180:         * guys can't print interesting stuff from kernel memory.
                    181:         */
1.11      tholo     182:        if (nlistf != NULL || memf != NULL) {
                    183:                setegid(getgid());
1.3       deraadt   184:                setgid(getgid());
1.11      tholo     185:        }
1.3       deraadt   186:
1.1       deraadt   187:        if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
                    188:                errx(1, "%s", errbuf);
1.25      deraadt   189:
                    190:        setegid(getgid());
                    191:        setgid(getgid());
1.1       deraadt   192:
                    193:        (void)time(&now);
                    194:        if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
                    195:                err(1, "%s", _PATH_UTMP);
                    196:
                    197:        if (*argv)
                    198:                sel_user = *argv;
                    199:
                    200:        for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
                    201:                if (utmp.ut_name[0] == '\0')
                    202:                        continue;
                    203:                ++nusers;
                    204:                if (wcmd == 0 || (sel_user &&
                    205:                    strncmp(utmp.ut_name, sel_user, UT_NAMESIZE) != 0))
                    206:                        continue;
                    207:                if ((ep = calloc(1, sizeof(struct entry))) == NULL)
                    208:                        err(1, NULL);
                    209:                *nextp = ep;
                    210:                nextp = &(ep->next);
1.26      millert   211:                memcpy(&(ep->utmp), &utmp, sizeof(struct utmp));
1.1       deraadt   212:                if (!(stp = ttystat(ep->utmp.ut_line)))
                    213:                        continue;
                    214:                ep->tdev = stp->st_rdev;
                    215: #ifdef CPU_CONSDEV
                    216:                /*
                    217:                 * If this is the console device, attempt to ascertain
                    218:                 * the true console device dev_t.
                    219:                 */
                    220:                if (ep->tdev == 0) {
                    221:                        int mib[2];
                    222:                        size_t size;
                    223:
                    224:                        mib[0] = CTL_MACHDEP;
                    225:                        mib[1] = CPU_CONSDEV;
                    226:                        size = sizeof(dev_t);
                    227:                        (void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
                    228:                }
                    229: #endif
                    230:                if ((ep->idle = now - stp->st_atime) < 0)
                    231:                        ep->idle = 0;
                    232:        }
                    233:        (void)fclose(ut);
                    234:
                    235:        if (header || wcmd == 0) {
                    236:                pr_header(&now, nusers);
                    237:                if (wcmd == 0)
                    238:                        exit (0);
                    239:        }
                    240:
1.30      deraadt   241: #define HEADER "USER    TTY FROM              LOGIN@  IDLE WHAT"
                    242: #define WUSED  (sizeof (HEADER) - sizeof ("WHAT"))
                    243:        (void)puts(HEADER);
1.1       deraadt   244:
                    245:        if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
1.2       deraadt   246:                errx(1, "%s", kvm_geterr(kd));
1.1       deraadt   247:        for (i = 0; i < nentries; i++, kp++) {
                    248:                struct proc *p = &kp->kp_proc;
                    249:                struct eproc *e;
                    250:
                    251:                if (p->p_stat == SIDL || p->p_stat == SZOMB)
                    252:                        continue;
                    253:                e = &kp->kp_eproc;
                    254:                for (ep = ehead; ep != NULL; ep = ep->next) {
1.7       downsj    255:                        /* ftp is a special case. */
                    256:                        if (strncmp(ep->utmp.ut_line, "ftp", 3) == 0) {
1.26      millert   257:                                char pidstr[UT_LINESIZE-2];
                    258:                                pid_t fp;
                    259:
                    260:                                (void)strncpy(pidstr, &ep->utmp.ut_line[3],
                    261:                                    sizeof(pidstr) - 1);
                    262:                                pidstr[sizeof(pidstr) - 1] = '\0';
                    263:                                fp = (pid_t)strtol(pidstr, NULL, 10);
1.7       downsj    264:                                if (p->p_pid == fp) {
                    265:                                        ep->kp = kp;
                    266:                                        break;
                    267:                                }
                    268:                        } else if (ep->tdev == e->e_tdev
                    269:                                   && e->e_pgid == e->e_tpgid) {
1.1       deraadt   270:                                /*
                    271:                                 * Proc is in foreground of this terminal
                    272:                                 */
                    273:                                if (proc_compare(&ep->kp->kp_proc, p))
                    274:                                        ep->kp = kp;
                    275:                                break;
                    276:                        }
                    277:                }
                    278:        }
                    279:        if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
                    280:             ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
                    281:             ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
                    282:               ttywidth = 79;
                    283:         else
                    284:               ttywidth = ws.ws_col - 1;
                    285:        argwidth = ttywidth - WUSED;
                    286:        if (argwidth < 4)
                    287:                argwidth = 8;
                    288:        /* sort by idle time */
                    289:        if (sortidle && ehead != NULL) {
                    290:                struct entry *from = ehead, *save;
                    291:
                    292:                ehead = NULL;
                    293:                while (from != NULL) {
                    294:                        for (nextp = &ehead;
                    295:                            (*nextp) && from->idle >= (*nextp)->idle;
                    296:                            nextp = &(*nextp)->next)
                    297:                                continue;
                    298:                        save = from;
                    299:                        from = from->next;
                    300:                        save->next = *nextp;
                    301:                        *nextp = save;
                    302:                }
                    303:        }
                    304:
                    305:        if (!nflag)
                    306:                if (gethostname(domain, sizeof(domain) - 1) < 0 ||
                    307:                    (p = strchr(domain, '.')) == 0)
                    308:                        domain[0] = '\0';
                    309:                else {
                    310:                        domain[sizeof(domain) - 1] = '\0';
                    311:                        memmove(domain, p, strlen(p) + 1);
                    312:                }
                    313:
                    314:        for (ep = ehead; ep != NULL; ep = ep->next) {
                    315:                p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
1.16      millert   316:                for (x = NULL, i = 0; p[i] != '\0' && i < UT_HOSTSIZE; i++)
                    317:                        if (p[i] == ':') {
                    318:                                x = &p[i];
                    319:                                *x++ = '\0';
                    320:                                break;
                    321:                        }
1.27      deraadt   322:                if (!nflag && inet_aton(p, &addr) &&
                    323:                    (hp = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET))) {
1.1       deraadt   324:                        if (domain[0] != '\0') {
                    325:                                p = hp->h_name;
                    326:                                p += strlen(hp->h_name);
                    327:                                p -= strlen(domain);
1.31    ! deraadt   328:                                if (p > hp->h_name &&
        !           329:                                    strcasecmp(p, domain) == 0)
1.1       deraadt   330:                                        *p = '\0';
                    331:                        }
                    332:                        p = hp->h_name;
                    333:                }
                    334:                if (x) {
                    335:                        (void)snprintf(buf, sizeof(buf), "%s:%.*s", p,
                    336:                            ep->utmp.ut_host + UT_HOSTSIZE - x, x);
                    337:                        p = buf;
                    338:                }
1.22      deraadt   339:                (void)printf("%-*.*s %-2.2s %-*.*s ",
1.1       deraadt   340:                    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
                    341:                    strncmp(ep->utmp.ut_line, "tty", 3) ?
                    342:                    ep->utmp.ut_line : ep->utmp.ut_line + 3,
                    343:                    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
                    344:                pr_attime(&ep->utmp.ut_time, &now);
                    345:                pr_idle(ep->idle);
                    346:                pr_args(ep->kp);
                    347:                printf("\n");
                    348:        }
                    349:        exit(0);
                    350: }
                    351:
                    352: static void
                    353: pr_args(kp)
                    354:        struct kinfo_proc *kp;
                    355: {
1.7       downsj    356:        char **argv, *str;
1.1       deraadt   357:        int left;
                    358:
1.23      millert   359:        if (kp == NULL)
1.1       deraadt   360:                goto nothing;
                    361:        left = argwidth;
1.26      millert   362:        argv = kvm_getargv(kd, kp, argwidth+60);  /* +60 for ftpd snip */
1.23      millert   363:        if (argv == NULL)
1.1       deraadt   364:                goto nothing;
1.7       downsj    365:
1.23      millert   366:        if (*argv == NULL || **argv == '\0') {
                    367:                /* Process has zeroed argv[0], display executable name. */
                    368:                fmt_putc('(', &left);
                    369:                fmt_puts(kp->kp_proc.p_comm, &left);
                    370:                fmt_putc(')', &left);
                    371:        }
1.1       deraadt   372:        while (*argv) {
1.7       downsj    373:                /* ftp is a special case... */
                    374:                if (strncmp(*argv, "ftpd:", 5) == 0) {
                    375:                        str = strrchr(*argv, ':');
                    376:                        if (str != (char *)NULL) {
1.8       downsj    377:                                if ((str[0] == ':') && isspace(str[1]))
1.7       downsj    378:                                        str += 2;
                    379:                                fmt_puts(str, &left);
                    380:                        } else
                    381:                                fmt_puts(*argv, &left);
                    382:                } else
                    383:                        fmt_puts(*argv, &left);
1.1       deraadt   384:                argv++;
                    385:                fmt_putc(' ', &left);
                    386:        }
                    387:        return;
                    388: nothing:
                    389:        putchar('-');
                    390: }
                    391:
                    392: static void
                    393: pr_header(nowp, nusers)
                    394:        time_t *nowp;
                    395:        int nusers;
                    396: {
                    397:        double avenrun[3];
                    398:        time_t uptime;
                    399:        int days, hrs, i, mins;
                    400:        int mib[2];
                    401:        size_t size;
                    402:        char buf[256];
                    403:
                    404:        /*
                    405:         * Print time of day.
                    406:         *
                    407:         * SCCS forces the string manipulation below, as it replaces
                    408:         * %, M, and % in a character string with the file name.
                    409:         */
1.14      deraadt   410:        (void)strftime(buf, sizeof(buf) - 1,
1.1       deraadt   411:            __CONCAT("%l:%","M%p"), localtime(nowp));
1.14      deraadt   412:        buf[sizeof buf -1] = '\0';
1.1       deraadt   413:        (void)printf("%s ", buf);
                    414:
                    415:        /*
                    416:         * Print how long system has been up.
                    417:         * (Found by looking getting "boottime" from the kernel)
                    418:         */
                    419:        mib[0] = CTL_KERN;
                    420:        mib[1] = KERN_BOOTTIME;
                    421:        size = sizeof(boottime);
1.17      deraadt   422:        if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1) {
1.1       deraadt   423:                uptime = now - boottime.tv_sec;
1.19      mickey    424:                if (uptime > 59) {
1.17      deraadt   425:                        uptime += 30;
                    426:                        days = uptime / SECSPERDAY;
                    427:                        uptime %= SECSPERDAY;
                    428:                        hrs = uptime / SECSPERHOUR;
                    429:                        uptime %= SECSPERHOUR;
                    430:                        mins = uptime / SECSPERMIN;
                    431:                        (void)printf(" up");
                    432:                        if (days > 0)
                    433:                                (void)printf(" %d day%s,", days,
                    434:                                    days > 1 ? "s" : "");
                    435:                        if (hrs > 0 && mins > 0)
                    436:                                (void)printf(" %2d:%02d,", hrs, mins);
                    437:                        else {
                    438:                                if (hrs > 0)
                    439:                                        (void)printf(" %d hr%s,",
                    440:                                            hrs, hrs > 1 ? "s" : "");
                    441:                                if (mins > 0 || (days == 0 && hrs == 0))
                    442:                                        (void)printf(" %d min%s,",
                    443:                                            mins, mins != 1 ? "s" : "");
                    444:                        }
                    445:                } else
1.18      deraadt   446:                        printf(" %d secs,", uptime);
1.1       deraadt   447:        }
                    448:
                    449:        /* Print number of users logged in to system */
                    450:        (void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
                    451:
                    452:        /*
                    453:         * Print 1, 5, and 15 minute load averages.
                    454:         */
                    455:        if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
                    456:                (void)printf(", no load average information available\n");
                    457:        else {
                    458:                (void)printf(", load averages:");
                    459:                for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
                    460:                        if (i > 0)
                    461:                                (void)printf(",");
                    462:                        (void)printf(" %.2f", avenrun[i]);
                    463:                }
                    464:                (void)printf("\n");
                    465:        }
                    466: }
                    467:
                    468: static struct stat *
                    469: ttystat(line)
                    470:        char *line;
                    471: {
                    472:        static struct stat sb;
1.26      millert   473:        char ttybuf[sizeof(_PATH_DEV) + UT_LINESIZE];
1.1       deraadt   474:
1.26      millert   475:        /* Note, line may not be NUL-terminated */
                    476:        (void)strcpy(ttybuf, _PATH_DEV);
                    477:        (void)strncpy(ttybuf + sizeof(_PATH_DEV) - 1, line, UT_LINESIZE);
                    478:        ttybuf[sizeof(ttybuf) - 1] = '\0';
1.1       deraadt   479:        if (stat(ttybuf, &sb))
                    480:                return (NULL);
                    481:        return (&sb);
                    482: }
                    483:
                    484: static void
                    485: usage(wcmd)
                    486:        int wcmd;
                    487: {
                    488:        if (wcmd)
                    489:                (void)fprintf(stderr,
1.13      angelos   490:                    "usage: w: [-hia] [-M core] [-N system] [user]\n");
1.1       deraadt   491:        else
1.24      deraadt   492:                (void)fprintf(stderr, "usage: uptime\n");
1.1       deraadt   493:        exit (1);
                    494: }