[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.67

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