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

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