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

1.15    ! millert     1: /*     $OpenBSD: w.c,v 1.14 1997/03/25 21:24:12 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
                     43: static char sccsid[] = "@(#)w.c        8.4 (Berkeley) 4/16/94";
                     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:
                     99: /*
                    100:  * One of these per active utmp entry.
                    101:  */
                    102: struct entry {
                    103:        struct  entry *next;
                    104:        struct  utmp utmp;
                    105:        dev_t   tdev;           /* dev_t of terminal */
                    106:        time_t  idle;           /* idle time of terminal in seconds */
                    107:        struct  kinfo_proc *kp; /* `most interesting' proc */
                    108: } *ep, *ehead = NULL, **nextp = &ehead;
                    109:
                    110: static void     pr_args __P((struct kinfo_proc *));
                    111: static void     pr_header __P((time_t *, int));
                    112: static struct stat
                    113:                *ttystat __P((char *));
                    114: static void     usage __P((int));
                    115:
                    116: int
                    117: main(argc, argv)
                    118:        int argc;
                    119:        char **argv;
                    120: {
                    121:        extern char *__progname;
                    122:        struct kinfo_proc *kp;
                    123:        struct hostent *hp;
                    124:        struct stat *stp;
                    125:        FILE *ut;
                    126:        u_long l;
                    127:        int ch, i, nentries, nusers, wcmd;
                    128:        char *memf, *nlistf, *p, *x;
1.5       deraadt   129:        char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
1.1       deraadt   130:
                    131:        /* Are we w(1) or uptime(1)? */
                    132:        p = __progname;
                    133:        if (*p == '-')
                    134:                p++;
                    135:        if (*p == 'u') {
                    136:                wcmd = 0;
                    137:                p = "";
                    138:        } else {
                    139:                wcmd = 1;
1.6       deraadt   140:                p = "hiflM:N:asuw";
1.1       deraadt   141:        }
                    142:
                    143:        memf = nlistf = NULL;
1.12      millert   144:        while ((ch = getopt(argc, argv, p)) != -1)
1.1       deraadt   145:                switch (ch) {
                    146:                case 'h':
                    147:                        header = 0;
                    148:                        break;
                    149:                case 'i':
                    150:                        sortidle = 1;
                    151:                        break;
                    152:                case 'M':
                    153:                        header = 0;
                    154:                        memf = optarg;
                    155:                        break;
                    156:                case 'N':
                    157:                        nlistf = optarg;
                    158:                        break;
1.6       deraadt   159:                case 'a':
                    160:                        nflag = 0;
1.1       deraadt   161:                        break;
                    162:                case 'f': case 'l': case 's': case 'u': case 'w':
                    163:                        warnx("[-flsuw] no longer supported");
                    164:                        /* FALLTHROUGH */
                    165:                case '?':
                    166:                default:
                    167:                        usage(wcmd);
                    168:                }
                    169:        argc -= optind;
                    170:        argv += optind;
                    171:
1.3       deraadt   172:        /*
                    173:         * Discard setgid privileges if not the running kernel so that bad
                    174:         * guys can't print interesting stuff from kernel memory.
                    175:         */
1.11      tholo     176:        if (nlistf != NULL || memf != NULL) {
                    177:                setegid(getgid());
1.3       deraadt   178:                setgid(getgid());
1.11      tholo     179:        }
1.3       deraadt   180:
1.1       deraadt   181:        if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
                    182:                errx(1, "%s", errbuf);
                    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;
                    198:                if ((ep = calloc(1, sizeof(struct entry))) == NULL)
                    199:                        err(1, NULL);
                    200:                *nextp = ep;
                    201:                nextp = &(ep->next);
                    202:                memmove(&(ep->utmp), &utmp, sizeof(struct utmp));
                    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:
                    232: #define HEADER "USER    TTY FROM              LOGIN@  IDLE WHAT\n"
                    233: #define WUSED  (sizeof (HEADER) - sizeof ("WHAT\n"))
                    234:        (void)printf(HEADER);
                    235:
                    236:        if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
1.2       deraadt   237:                errx(1, "%s", kvm_geterr(kd));
1.1       deraadt   238:        for (i = 0; i < nentries; i++, kp++) {
                    239:                struct proc *p = &kp->kp_proc;
                    240:                struct eproc *e;
                    241:
                    242:                if (p->p_stat == SIDL || p->p_stat == SZOMB)
                    243:                        continue;
                    244:                e = &kp->kp_eproc;
                    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) {
                    248:                                pid_t fp = (pid_t)strtol(&ep->utmp.ut_line[3],
                    249:                                                         NULL, 10);
                    250:                                if (p->p_pid == fp) {
                    251:                                        ep->kp = kp;
                    252:
                    253:                                        break;
                    254:                                }
                    255:                        } else if (ep->tdev == e->e_tdev
                    256:                                   && e->e_pgid == e->e_tpgid) {
1.1       deraadt   257:                                /*
                    258:                                 * Proc is in foreground of this terminal
                    259:                                 */
                    260:                                if (proc_compare(&ep->kp->kp_proc, p))
                    261:                                        ep->kp = kp;
                    262:                                break;
                    263:                        }
                    264:                }
                    265:        }
                    266:        if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
                    267:             ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
                    268:             ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
                    269:               ttywidth = 79;
                    270:         else
                    271:               ttywidth = ws.ws_col - 1;
                    272:        argwidth = ttywidth - WUSED;
                    273:        if (argwidth < 4)
                    274:                argwidth = 8;
                    275:        /* sort by idle time */
                    276:        if (sortidle && ehead != NULL) {
                    277:                struct entry *from = ehead, *save;
                    278:
                    279:                ehead = NULL;
                    280:                while (from != NULL) {
                    281:                        for (nextp = &ehead;
                    282:                            (*nextp) && from->idle >= (*nextp)->idle;
                    283:                            nextp = &(*nextp)->next)
                    284:                                continue;
                    285:                        save = from;
                    286:                        from = from->next;
                    287:                        save->next = *nextp;
                    288:                        *nextp = save;
                    289:                }
                    290:        }
                    291:
                    292:        if (!nflag)
                    293:                if (gethostname(domain, sizeof(domain) - 1) < 0 ||
                    294:                    (p = strchr(domain, '.')) == 0)
                    295:                        domain[0] = '\0';
                    296:                else {
                    297:                        domain[sizeof(domain) - 1] = '\0';
                    298:                        memmove(domain, p, strlen(p) + 1);
                    299:                }
                    300:
                    301:        for (ep = ehead; ep != NULL; ep = ep->next) {
                    302:                p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
1.15    ! millert   303:                if ((x = strchr(p, ':')) != NULL && x - p <= UT_HOSTSIZE)
1.1       deraadt   304:                        *x++ = '\0';
1.15    ! millert   305:                else
        !           306:                        x = NULL;
1.1       deraadt   307:                if (!nflag && isdigit(*p) &&
                    308:                    (long)(l = inet_addr(p)) != -1 &&
                    309:                    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
                    310:                        if (domain[0] != '\0') {
                    311:                                p = hp->h_name;
                    312:                                p += strlen(hp->h_name);
                    313:                                p -= strlen(domain);
                    314:                                if (p > hp->h_name && strcmp(p, domain) == 0)
                    315:                                        *p = '\0';
                    316:                        }
                    317:                        p = hp->h_name;
                    318:                }
                    319:                if (x) {
                    320:                        (void)snprintf(buf, sizeof(buf), "%s:%.*s", p,
                    321:                            ep->utmp.ut_host + UT_HOSTSIZE - x, x);
                    322:                        p = buf;
                    323:                }
                    324:                (void)printf("%-*.*s %-2.2s %-*.*s ",
                    325:                    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
                    326:                    strncmp(ep->utmp.ut_line, "tty", 3) ?
                    327:                    ep->utmp.ut_line : ep->utmp.ut_line + 3,
                    328:                    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
                    329:                pr_attime(&ep->utmp.ut_time, &now);
                    330:                pr_idle(ep->idle);
                    331:                pr_args(ep->kp);
                    332:                printf("\n");
                    333:        }
                    334:        exit(0);
                    335: }
                    336:
                    337: static void
                    338: pr_args(kp)
                    339:        struct kinfo_proc *kp;
                    340: {
1.7       downsj    341:        char **argv, *str;
1.1       deraadt   342:        int left;
                    343:
                    344:        if (kp == 0)
                    345:                goto nothing;
                    346:        left = argwidth;
1.9       deraadt   347:        argv = kvm_getargv(kd, kp, argwidth+60);  /*+60 for ftpd snip */
1.1       deraadt   348:        if (argv == 0)
                    349:                goto nothing;
1.7       downsj    350:
1.1       deraadt   351:        while (*argv) {
1.7       downsj    352:                /* ftp is a special case... */
                    353:                if (strncmp(*argv, "ftpd:", 5) == 0) {
                    354:                        str = strrchr(*argv, ':');
                    355:                        if (str != (char *)NULL) {
1.8       downsj    356:                                if ((str[0] == ':') && isspace(str[1]))
1.7       downsj    357:                                        str += 2;
                    358:                                fmt_puts(str, &left);
                    359:                        } else
                    360:                                fmt_puts(*argv, &left);
                    361:                } else
                    362:                        fmt_puts(*argv, &left);
1.1       deraadt   363:                argv++;
                    364:                fmt_putc(' ', &left);
                    365:        }
                    366:        return;
                    367: nothing:
                    368:        putchar('-');
                    369: }
                    370:
                    371: static void
                    372: pr_header(nowp, nusers)
                    373:        time_t *nowp;
                    374:        int nusers;
                    375: {
                    376:        double avenrun[3];
                    377:        time_t uptime;
                    378:        int days, hrs, i, mins;
                    379:        int mib[2];
                    380:        size_t size;
                    381:        char buf[256];
                    382:
                    383:        /*
                    384:         * Print time of day.
                    385:         *
                    386:         * SCCS forces the string manipulation below, as it replaces
                    387:         * %, M, and % in a character string with the file name.
                    388:         */
1.14      deraadt   389:        (void)strftime(buf, sizeof(buf) - 1,
1.1       deraadt   390:            __CONCAT("%l:%","M%p"), localtime(nowp));
1.14      deraadt   391:        buf[sizeof buf -1] = '\0';
1.1       deraadt   392:        (void)printf("%s ", buf);
                    393:
                    394:        /*
                    395:         * Print how long system has been up.
                    396:         * (Found by looking getting "boottime" from the kernel)
                    397:         */
                    398:        mib[0] = CTL_KERN;
                    399:        mib[1] = KERN_BOOTTIME;
                    400:        size = sizeof(boottime);
                    401:        if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
                    402:            boottime.tv_sec != 0) {
                    403:                uptime = now - boottime.tv_sec;
                    404:                uptime += 30;
                    405:                days = uptime / SECSPERDAY;
                    406:                uptime %= SECSPERDAY;
                    407:                hrs = uptime / SECSPERHOUR;
                    408:                uptime %= SECSPERHOUR;
                    409:                mins = uptime / SECSPERMIN;
                    410:                (void)printf(" up");
                    411:                if (days > 0)
                    412:                        (void)printf(" %d day%s,", days, days > 1 ? "s" : "");
                    413:                if (hrs > 0 && mins > 0)
                    414:                        (void)printf(" %2d:%02d,", hrs, mins);
                    415:                else {
                    416:                        if (hrs > 0)
                    417:                                (void)printf(" %d hr%s,",
                    418:                                    hrs, hrs > 1 ? "s" : "");
1.10      deraadt   419:                        if (mins > 0 || (days == 0 && hrs == 0))
1.1       deraadt   420:                                (void)printf(" %d min%s,",
1.10      deraadt   421:                                    mins, mins != 1 ? "s" : "");
1.1       deraadt   422:                }
                    423:        }
                    424:
                    425:        /* Print number of users logged in to system */
                    426:        (void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
                    427:
                    428:        /*
                    429:         * Print 1, 5, and 15 minute load averages.
                    430:         */
                    431:        if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
                    432:                (void)printf(", no load average information available\n");
                    433:        else {
                    434:                (void)printf(", load averages:");
                    435:                for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
                    436:                        if (i > 0)
                    437:                                (void)printf(",");
                    438:                        (void)printf(" %.2f", avenrun[i]);
                    439:                }
                    440:                (void)printf("\n");
                    441:        }
                    442: }
                    443:
                    444: static struct stat *
                    445: ttystat(line)
                    446:        char *line;
                    447: {
                    448:        static struct stat sb;
                    449:        char ttybuf[MAXPATHLEN];
                    450:
                    451:        (void)snprintf(ttybuf, sizeof(ttybuf), "%s/%s", _PATH_DEV, line);
                    452:        if (stat(ttybuf, &sb))
                    453:                return (NULL);
                    454:        return (&sb);
                    455: }
                    456:
                    457: static void
                    458: usage(wcmd)
                    459:        int wcmd;
                    460: {
                    461:        if (wcmd)
                    462:                (void)fprintf(stderr,
1.13      angelos   463:                    "usage: w: [-hia] [-M core] [-N system] [user]\n");
1.1       deraadt   464:        else
                    465:                (void)fprintf(stderr, "uptime\n");
                    466:        exit (1);
                    467: }