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

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