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

Annotation of src/usr.bin/at/at.c, Revision 1.47

1.47    ! jmc         1: /*     $OpenBSD: at.c,v 1.46 2006/04/26 03:01:48 cloder Exp $  */
1.1       deraadt     2:
                      3: /*
1.7       millert     4:  *  at.c : Put file into atrun queue
                      5:  *  Copyright (C) 1993, 1994  Thomas Koenig
1.1       deraadt     6:  *
1.7       millert     7:  *  Atrun & Atq modifications
                      8:  *  Copyright (C) 1993  David Parsons
1.1       deraadt     9:  *
1.29      millert    10:  *  Traditional BSD behavior and other significant modifications
1.35      millert    11:  *  Copyright (C) 2002-2003  Todd C. Miller
1.29      millert    12:  *
1.1       deraadt    13:  * Redistribution and use in source and binary forms, with or without
                     14:  * modification, are permitted provided that the following conditions
                     15:  * are met:
                     16:  * 1. Redistributions of source code must retain the above copyright
                     17:  *    notice, this list of conditions and the following disclaimer.
                     18:  * 2. The name of the author(s) may not be used to endorse or promote
                     19:  *    products derived from this software without specific prior written
                     20:  *    permission.
                     21:  *
                     22:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
                     23:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     24:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1.7       millert    25:  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
1.1       deraadt    26:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     27:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     28:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     29:  * THEORY OF LIABILITY, WETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     30:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     31:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                     32:  */
                     33:
1.35      millert    34: #define        MAIN_PROGRAM
1.1       deraadt    35:
1.35      millert    36: #include "cron.h"
1.1       deraadt    37: #include "at.h"
                     38: #include "privs.h"
1.35      millert    39: #include <limits.h>
1.1       deraadt    40:
                     41: #define ALARMC 10              /* Number of seconds to wait for timeout */
1.29      millert    42: #define TIMESIZE 50            /* Size of buffer passed to strftime() */
1.1       deraadt    43:
                     44: #ifndef lint
1.47    ! jmc        45: static const char rcsid[] = "$OpenBSD: at.c,v 1.46 2006/04/26 03:01:48 cloder Exp $";
1.1       deraadt    46: #endif
                     47:
1.29      millert    48: /* Variables to remove from the job's environment. */
1.1       deraadt    49: char *no_export[] =
                     50: {
1.28      millert    51:        "TERM", "TERMCAP", "DISPLAY", "_", "SHELLOPTS", "BASH_VERSINFO",
                     52:        "EUID", "GROUPS", "PPID", "UID", "SSH_AUTH_SOCK", "SSH_AGENT_PID",
1.1       deraadt    53: };
1.7       millert    54:
1.27      millert    55: int program = AT;              /* default program mode */
1.35      millert    56: char atfile[MAX_FNAME];                /* path to the at spool file */
1.29      millert    57: int fcreated;                  /* whether or not we created the file yet */
                     58: char *atinput = NULL;          /* where to get input from */
1.1       deraadt    59: char atqueue = 0;              /* which queue to examine for jobs (atq) */
1.29      millert    60: char vflag = 0;                        /* show completed but unremoved jobs (atq) */
                     61: char force = 0;                        /* suppress errors (atrm) */
                     62: char interactive = 0;          /* interactive mode (atrm) */
                     63: static int send_mail = 0;      /* whether we are sending mail */
1.7       millert    64:
1.21      millert    65: static void sigc(int);
                     66: static void alarmc(int);
1.35      millert    67: static void writefile(const char *, time_t, char);
1.29      millert    68: static void list_jobs(int, char **, int, int);
1.25      millert    69: static time_t ttime(const char *);
1.35      millert    70: static int check_permission(void);
1.46      cloder     71: static __dead void panic(const char *);
1.35      millert    72: static void perr(const char *);
                     73: static void perr2(const char *, const char *);
1.41      millert    74: static __dead void usage(void);
1.35      millert    75: time_t parsetime(int, char **);
                     76:
                     77: /*
                     78:  * Something fatal has happened, print error message and exit.
                     79:  */
                     80: static __dead void
                     81: panic(const char *a)
                     82: {
                     83:        (void)fprintf(stderr, "%s: %s\n", ProgramName, a);
                     84:        if (fcreated) {
                     85:                PRIV_START;
                     86:                unlink(atfile);
                     87:                PRIV_END;
                     88:        }
                     89:
                     90:        exit(ERROR_EXIT);
                     91: }
                     92:
                     93: /*
                     94:  * Two-parameter version of panic().
                     95:  */
1.42      millert    96: static __dead void
1.35      millert    97: panic2(const char *a, const char *b)
                     98: {
                     99:        (void)fprintf(stderr, "%s: %s%s\n", ProgramName, a, b);
                    100:        if (fcreated) {
                    101:                PRIV_START;
                    102:                unlink(atfile);
                    103:                PRIV_END;
                    104:        }
                    105:
                    106:        exit(ERROR_EXIT);
                    107: }
                    108:
                    109: /*
                    110:  * Some operating system error; print error message and exit.
                    111:  */
                    112: static __dead void
                    113: perr(const char *a)
                    114: {
                    115:        if (!force)
                    116:                perror(a);
                    117:        if (fcreated) {
                    118:                PRIV_START;
                    119:                unlink(atfile);
                    120:                PRIV_END;
                    121:        }
                    122:
                    123:        exit(ERROR_EXIT);
                    124: }
                    125:
                    126: /*
                    127:  * Two-parameter version of perr().
                    128:  */
1.42      millert   129: static __dead void
1.35      millert   130: perr2(const char *a, const char *b)
                    131: {
                    132:        if (!force)
                    133:                (void)fputs(a, stderr);
                    134:        perr(b);
                    135: }
1.1       deraadt   136:
1.46      cloder    137: /* ARGSUSED */
1.42      millert   138: static void
1.26      millert   139: sigc(int signo)
1.1       deraadt   140: {
1.7       millert   141:        /* If the user presses ^C, remove the spool file and exit. */
1.1       deraadt   142:        if (fcreated) {
1.26      millert   143:                PRIV_START;
1.7       millert   144:                (void)unlink(atfile);
1.26      millert   145:                PRIV_END;
1.1       deraadt   146:        }
                    147:
1.35      millert   148:        _exit(ERROR_EXIT);
1.1       deraadt   149: }
                    150:
1.46      cloder    151: /* ARGSUSED */
1.42      millert   152: static void
1.26      millert   153: alarmc(int signo)
1.1       deraadt   154: {
1.35      millert   155:        /* just return */
1.1       deraadt   156: }
                    157:
1.29      millert   158: static int
                    159: newjob(time_t runtimer, int queue)
                    160: {
                    161:        int fd, i;
1.1       deraadt   162:
1.7       millert   163:        /*
1.29      millert   164:         * If we have a collision, try shifting the time by up to
                    165:         * two minutes.  Perhaps it would be better to try different
                    166:         * queues instead...
1.7       millert   167:         */
1.29      millert   168:        for (i = 0; i < 120; i++) {
1.35      millert   169:                snprintf(atfile, sizeof(atfile), "%s/%ld.%c", AT_DIR,
                    170:                    (long)runtimer, queue);
1.29      millert   171:                fd = open(atfile, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR);
                    172:                if (fd >= 0)
                    173:                        return (fd);
1.31      millert   174:                runtimer++;
1.29      millert   175:        }
                    176:        return (-1);
1.1       deraadt   177: }
                    178:
1.29      millert   179: /*
                    180:  * This does most of the work if at or batch are invoked for
                    181:  * writing a job.
                    182:  */
1.1       deraadt   183: static void
1.35      millert   184: writefile(const char *cwd, time_t runtimer, char queue)
1.1       deraadt   185: {
1.35      millert   186:        const char *ap;
                    187:        char *mailname, *shell;
1.28      millert   188:        char timestr[TIMESIZE];
1.1       deraadt   189:        struct passwd *pass_entry;
1.28      millert   190:        struct tm runtime;
1.1       deraadt   191:        int fdes, lockdes, fd2;
                    192:        FILE *fp, *fpin;
                    193:        struct sigaction act;
                    194:        char **atenv;
                    195:        int ch;
                    196:        mode_t cmask;
1.29      millert   197:        extern char **environ;
1.1       deraadt   198:
1.7       millert   199:        (void)setlocale(LC_TIME, "");
                    200:
1.1       deraadt   201:        /*
                    202:         * Install the signal handler for SIGINT; terminate after removing the
                    203:         * spool file if necessary
                    204:         */
1.35      millert   205:        bzero(&act, sizeof act);
1.1       deraadt   206:        act.sa_handler = sigc;
1.29      millert   207:        sigemptyset(&act.sa_mask);
1.1       deraadt   208:        act.sa_flags = 0;
                    209:        sigaction(SIGINT, &act, NULL);
                    210:
1.26      millert   211:        PRIV_START;
1.1       deraadt   212:
1.35      millert   213:        if ((lockdes = open(AT_DIR, O_RDONLY, 0)) < 0)
                    214:                perr("Cannot open jobs dir");
                    215:
1.22      millert   216:        /*
1.29      millert   217:         * Lock the jobs dir so we don't have to worry about someone
                    218:         * else grabbing a file name out from under us.
1.22      millert   219:         * Set an alarm so we don't sleep forever waiting on the lock.
                    220:         * If we don't succeed with ALARMC seconds, something is wrong...
                    221:         */
1.35      millert   222:        bzero(&act, sizeof act);
1.1       deraadt   223:        act.sa_handler = alarmc;
1.29      millert   224:        sigemptyset(&act.sa_mask);
1.35      millert   225: #ifdef SA_INTERRUPT
                    226:        act.sa_flags = SA_INTERRUPT;
                    227: #endif
1.1       deraadt   228:        sigaction(SIGALRM, &act, NULL);
                    229:        alarm(ALARMC);
1.35      millert   230:        ch = flock(lockdes, LOCK_EX);
1.1       deraadt   231:        alarm(0);
1.35      millert   232:        if (ch != 0)
                    233:                panic("Unable to lock jobs dir");
1.22      millert   234:
1.1       deraadt   235:        /*
                    236:         * Create the file. The x bit is only going to be set after it has
                    237:         * been completely written out, to make sure it is not executed in
                    238:         * the meantime.  To make sure they do not get deleted, turn off
                    239:         * their r bit.  Yes, this is a kluge.
                    240:         */
                    241:        cmask = umask(S_IRUSR | S_IWUSR | S_IXUSR);
1.29      millert   242:        if ((fdes = newjob(runtimer, queue)) == -1)
1.1       deraadt   243:                perr("Cannot create atjob file");
                    244:
                    245:        if ((fd2 = dup(fdes)) < 0)
                    246:                perr("Error in dup() of job file");
                    247:
1.7       millert   248:        if (fchown(fd2, real_uid, real_gid) != 0)
1.1       deraadt   249:                perr("Cannot give away file");
                    250:
1.26      millert   251:        PRIV_END;
1.1       deraadt   252:
                    253:        /*
                    254:         * We've successfully created the file; let's set the flag so it
                    255:         * gets removed in case of an interrupt or error.
                    256:         */
                    257:        fcreated = 1;
                    258:
                    259:        /* Now we can release the lock, so other people can access it */
1.7       millert   260:        (void)close(lockdes);
1.1       deraadt   261:
                    262:        if ((fp = fdopen(fdes, "w")) == NULL)
                    263:                panic("Cannot reopen atjob file");
                    264:
                    265:        /*
1.18      millert   266:         * Get the userid to mail to, first by trying getlogin(), which asks
                    267:         * the kernel, then from $LOGNAME or $USER, finally from getpwuid().
1.1       deraadt   268:         */
                    269:        mailname = getlogin();
1.5       millert   270:        if (mailname == NULL && (mailname = getenv("LOGNAME")) == NULL)
                    271:                mailname = getenv("USER");
1.1       deraadt   272:
1.7       millert   273:        if ((mailname == NULL) || (mailname[0] == '\0') ||
1.35      millert   274:            (strlen(mailname) > MAX_UNAME) || (getpwnam(mailname) == NULL)) {
1.7       millert   275:                pass_entry = getpwuid(real_uid);
1.1       deraadt   276:                if (pass_entry != NULL)
                    277:                        mailname = pass_entry->pw_name;
                    278:        }
                    279:
1.28      millert   280:        /*
                    281:         * Get the shell to run the job under.  First check $SHELL, falling
                    282:         * back to the user's shell in the password database or, failing
                    283:         * that, /bin/sh.
                    284:         */
                    285:        if ((shell = getenv("SHELL")) == NULL || *shell == '\0') {
                    286:                pass_entry = getpwuid(real_uid);
                    287:                if (pass_entry != NULL && *pass_entry->pw_shell != '\0')
                    288:                        shell = pass_entry->pw_shell;
                    289:                else
                    290:                        shell = _PATH_BSHELL;
                    291:        }
                    292:
1.13      kstailey  293:        if (atinput != NULL) {
1.1       deraadt   294:                fpin = freopen(atinput, "r", stdin);
                    295:                if (fpin == NULL)
                    296:                        perr("Cannot open input file");
                    297:        }
1.42      millert   298:        (void)fprintf(fp, "#!/bin/sh\n# atrun uid=%lu gid=%lu\n# mail %*s %d\n",
                    299:            (unsigned long)real_uid, (unsigned long)real_gid,
                    300:            MAX_UNAME, mailname, send_mail);
1.1       deraadt   301:
                    302:        /* Write out the umask at the time of invocation */
1.7       millert   303:        (void)fprintf(fp, "umask %o\n", cmask);
1.1       deraadt   304:
                    305:        /*
                    306:         * Write out the environment. Anything that may look like a special
                    307:         * character to the shell is quoted, except for \n, which is done
1.44      jmc       308:         * with a pair of "'s.  Don't export the no_export list (such as
1.1       deraadt   309:         * TERM or DISPLAY) because we don't want these.
                    310:         */
                    311:        for (atenv = environ; *atenv != NULL; atenv++) {
                    312:                int export = 1;
                    313:                char *eqp;
                    314:
                    315:                eqp = strchr(*atenv, '=');
1.19      millert   316:                if (eqp == NULL)
1.1       deraadt   317:                        eqp = *atenv;
                    318:                else {
                    319:                        int i;
                    320:
                    321:                        for (i = 0;i < sizeof(no_export) /
                    322:                            sizeof(no_export[0]); i++) {
                    323:                                export = export
                    324:                                    && (strncmp(*atenv, no_export[i],
                    325:                                        (size_t) (eqp - *atenv)) != 0);
                    326:                        }
                    327:                        eqp++;
                    328:                }
                    329:
                    330:                if (export) {
1.7       millert   331:                        (void)fwrite(*atenv, sizeof(char), eqp - *atenv, fp);
1.1       deraadt   332:                        for (ap = eqp; *ap != '\0'; ap++) {
                    333:                                if (*ap == '\n')
1.7       millert   334:                                        (void)fprintf(fp, "\"\n\"");
1.1       deraadt   335:                                else {
1.7       millert   336:                                        if (!isalnum(*ap)) {
                    337:                                                switch (*ap) {
                    338:                                                case '%': case '/': case '{':
                    339:                                                case '[': case ']': case '=':
                    340:                                                case '}': case '@': case '+':
                    341:                                                case '#': case ',': case '.':
                    342:                                                case ':': case '-': case '_':
                    343:                                                        break;
                    344:                                                default:
                    345:                                                        (void)fputc('\\', fp);
                    346:                                                        break;
                    347:                                                }
                    348:                                        }
                    349:                                        (void)fputc(*ap, fp);
1.1       deraadt   350:                                }
                    351:                        }
1.7       millert   352:                        (void)fputs("; export ", fp);
                    353:                        (void)fwrite(*atenv, sizeof(char), eqp - *atenv - 1, fp);
                    354:                        (void)fputc('\n', fp);
                    355:                }
                    356:        }
                    357:        /*
                    358:         * Cd to the directory at the time and write out all the
                    359:         * commands the user supplies from stdin.
                    360:         */
                    361:        (void)fputs("cd ", fp);
1.35      millert   362:        for (ap = cwd; *ap != '\0'; ap++) {
1.7       millert   363:                if (*ap == '\n')
                    364:                        fprintf(fp, "\"\n\"");
                    365:                else {
                    366:                        if (*ap != '/' && !isalnum(*ap))
                    367:                                (void)fputc('\\', fp);
1.1       deraadt   368:
1.7       millert   369:                        (void)fputc(*ap, fp);
1.1       deraadt   370:                }
                    371:        }
                    372:        /*
1.7       millert   373:         * Test cd's exit status: die if the original directory has been
                    374:         * removed, become unreadable or whatever.
1.1       deraadt   375:         */
1.29      millert   376:        (void)fprintf(fp, " || {\n\t echo 'Execution directory inaccessible'"
                    377:            " >&2\n\t exit 1\n}\n");
1.1       deraadt   378:
1.3       millert   379:        if ((ch = getchar()) == EOF)
                    380:                panic("Input error");
                    381:
1.28      millert   382:        /* We want the job to run under the user's shell. */
                    383:        fprintf(fp, "%s << '_END_OF_AT_JOB'\n", shell);
                    384:
1.3       millert   385:        do {
1.7       millert   386:                (void)fputc(ch, fp);
1.3       millert   387:        } while ((ch = getchar()) != EOF);
1.1       deraadt   388:
1.28      millert   389:        (void)fprintf(fp, "\n_END_OF_AT_JOB\n");
1.1       deraadt   390:        if (ferror(fp))
                    391:                panic("Output error");
                    392:
                    393:        if (ferror(stdin))
                    394:                panic("Input error");
                    395:
1.7       millert   396:        (void)fclose(fp);
1.1       deraadt   397:
                    398:        /*
                    399:         * Set the x bit so that we're ready to start executing
                    400:         */
                    401:        if (fchmod(fd2, S_IRUSR | S_IWUSR | S_IXUSR) < 0)
                    402:                perr("Cannot give away file");
                    403:
1.7       millert   404:        (void)close(fd2);
1.28      millert   405:
1.30      millert   406:        /* Poke cron so it knows to reload the at spool. */
1.35      millert   407:        PRIV_START;
                    408:        poke_daemon(AT_DIR, RELOAD_AT);
                    409:        PRIV_END;
1.30      millert   410:
1.28      millert   411:        runtime = *localtime(&runtimer);
                    412:        strftime(timestr, TIMESIZE, "%a %b %e %T %Y", &runtime);
                    413:        (void)fprintf(stderr, "commands will be executed using %s\n", shell);
1.35      millert   414:        (void)fprintf(stderr, "job %s at %s\n", &atfile[sizeof(AT_DIR)],
1.29      millert   415:            timestr);
                    416: }
                    417:
                    418: /* Sort by creation time. */
                    419: static int
                    420: byctime(const void *v1, const void *v2)
                    421: {
1.46      cloder    422:        const struct atjob *j1 = *(const struct atjob **)v1;
                    423:        const struct atjob *j2 = *(const struct atjob **)v2;
1.29      millert   424:
                    425:        return (j1->ctime - j2->ctime);
                    426: }
                    427:
                    428: /* Sort by job number (and thus execution time). */
                    429: static int
                    430: byjobno(const void *v1, const void *v2)
                    431: {
                    432:        const struct atjob *j1 = *(struct atjob **)v1;
                    433:        const struct atjob *j2 = *(struct atjob **)v2;
                    434:
                    435:        if (j1->runtimer == j2->runtimer)
                    436:                return (j1->queue - j2->queue);
                    437:        return (j1->runtimer - j2->runtimer);
                    438: }
                    439:
                    440: static void
1.37      millert   441: print_job(struct atjob *job, int n, int shortformat)
1.29      millert   442: {
                    443:        struct passwd *pw;
                    444:        struct tm runtime;
                    445:        char timestr[TIMESIZE];
                    446:        static char *ranks[] = {
                    447:                "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"
                    448:        };
                    449:
                    450:        runtime = *localtime(&job->runtimer);
                    451:        if (shortformat) {
                    452:                strftime(timestr, TIMESIZE, "%a %b %e %T %Y", &runtime);
                    453:                (void)printf("%ld.%c\t%s\n", (long)job->runtimer,
                    454:                    job->queue, timestr);
                    455:        } else {
1.37      millert   456:                pw = getpwuid(job->uid);
1.29      millert   457:                /* Rank hack shamelessly stolen from lpq */
                    458:                if (n / 10 == 1)
                    459:                        printf("%3d%-5s", n,"th");
                    460:                else
                    461:                        printf("%3d%-5s", n, ranks[n % 10]);
                    462:                strftime(timestr, TIMESIZE, "%b %e, %Y %R", &runtime);
                    463:                (void)printf("%-21.18s%-11.8s%10ld.%c   %c%s\n",
                    464:                    timestr, pw ? pw->pw_name : "???",
                    465:                    (long)job->runtimer, job->queue, job->queue,
1.37      millert   466:                    (S_IXUSR & job->mode) ? "" : " (done)");
1.29      millert   467:        }
1.1       deraadt   468: }
                    469:
1.29      millert   470: /*
                    471:  * List all of a user's jobs in the queue, by looping through
1.35      millert   472:  * AT_DIR, or all jobs if we are root.  If argc is > 0, argv
1.29      millert   473:  * contains the list of users whose jobs shall be displayed. By
                    474:  * default, the list is sorted by execution date and queue.  If
                    475:  * csort is non-zero jobs will be sorted by creation/submission date.
                    476:  */
1.1       deraadt   477: static void
1.29      millert   478: list_jobs(int argc, char **argv, int count_only, int csort)
1.1       deraadt   479: {
                    480:        struct passwd *pw;
                    481:        struct dirent *dirent;
1.40      tedu      482:        struct atjob **atjobs, **newatjobs, *job;
1.29      millert   483:        struct stat stbuf;
1.1       deraadt   484:        time_t runtimer;
1.29      millert   485:        uid_t *uids;
                    486:        long l;
                    487:        char queue, *ep;
                    488:        DIR *spool;
                    489:        int i, shortformat, numjobs, maxjobs;
                    490:
                    491:        if (argc) {
                    492:                if ((uids = malloc(sizeof(uid_t) * argc)) == NULL)
1.35      millert   493:                        panic("Insufficient virtual memory");
1.29      millert   494:
                    495:                for (i = 0; i < argc; i++) {
                    496:                        if ((pw = getpwnam(argv[i])) == NULL)
1.35      millert   497:                                panic2(argv[i], ": invalid user name");
1.29      millert   498:                        if (pw->pw_uid != real_uid && real_uid != 0)
1.35      millert   499:                                panic("Only the superuser may display other users' jobs");
1.29      millert   500:                        uids[i] = pw->pw_uid;
                    501:                }
                    502:        } else
                    503:                uids = NULL;
                    504:
1.35      millert   505:        shortformat = strcmp(ProgramName, "at") == 0;
1.1       deraadt   506:
1.26      millert   507:        PRIV_START;
1.1       deraadt   508:
1.35      millert   509:        if (chdir(AT_DIR) != 0)
                    510:                perr2("Cannot change to ", AT_DIR);
1.1       deraadt   511:
                    512:        if ((spool = opendir(".")) == NULL)
1.35      millert   513:                perr2("Cannot open ", AT_DIR);
1.1       deraadt   514:
1.29      millert   515:        PRIV_END;
                    516:
1.35      millert   517:        if (fstat(spool->dd_fd, &stbuf) != 0)
                    518:                perr2("Cannot stat ", AT_DIR);
1.29      millert   519:
                    520:        /*
                    521:         * The directory's link count should give us a good idea
                    522:         * of how many files are in it.  Fudge things a little just
                    523:         * in case someone adds a job or two.
                    524:         */
                    525:        numjobs = 0;
                    526:        maxjobs = stbuf.st_nlink + 4;
                    527:        atjobs = (struct atjob **)malloc(maxjobs * sizeof(struct atjob *));
                    528:        if (atjobs == NULL)
1.35      millert   529:                panic("Insufficient virtual memory");
1.29      millert   530:
                    531:        /* Loop over every file in the directory. */
1.1       deraadt   532:        while ((dirent = readdir(spool)) != NULL) {
1.29      millert   533:                PRIV_START;
                    534:
                    535:                if (stat(dirent->d_name, &stbuf) != 0)
1.35      millert   536:                        perr2("Cannot stat in ", AT_DIR);
1.1       deraadt   537:
1.29      millert   538:                PRIV_END;
                    539:
1.1       deraadt   540:                /*
                    541:                 * See it's a regular file and has its x bit turned on and
                    542:                 * is the user's
                    543:                 */
1.29      millert   544:                if (!S_ISREG(stbuf.st_mode)
                    545:                    || ((stbuf.st_uid != real_uid) && !(real_uid == 0))
                    546:                    || !(S_IXUSR & stbuf.st_mode || vflag))
1.1       deraadt   547:                        continue;
                    548:
1.29      millert   549:                l = strtol(dirent->d_name, &ep, 10);
                    550:                if (*ep != '.' || !isalpha(*(ep + 1)) || *(ep + 2) != '\0' ||
                    551:                    l < 0 || l >= INT_MAX)
1.1       deraadt   552:                        continue;
1.29      millert   553:                runtimer = (time_t)l;
                    554:                queue = *(ep + 1);
1.1       deraadt   555:
                    556:                if (atqueue && (queue != atqueue))
                    557:                        continue;
                    558:
1.29      millert   559:                /* Check against specified user(s). */
                    560:                if (argc) {
                    561:                        for (i = 0; i < argc; i++) {
                    562:                                if (uids[0] == stbuf.st_uid)
                    563:                                        break;
                    564:                        }
                    565:                        if (i == argc)
                    566:                                continue;       /* user doesn't match */
                    567:                }
                    568:
                    569:                if (count_only) {
                    570:                        numjobs++;
                    571:                        continue;
                    572:                }
                    573:
                    574:                job = (struct atjob *)malloc(sizeof(struct atjob));
                    575:                if (job == NULL)
1.35      millert   576:                        panic("Insufficient virtual memory");
1.29      millert   577:                job->runtimer = runtimer;
                    578:                job->ctime = stbuf.st_ctime;
1.37      millert   579:                job->uid = stbuf.st_uid;
                    580:                job->mode = stbuf.st_mode;
1.29      millert   581:                job->queue = queue;
                    582:                if (numjobs == maxjobs) {
1.40      tedu      583:                        int newjobs = maxjobs * 2;
                    584:                        newatjobs = realloc(atjobs, newjobs * sizeof(job));
                    585:                        if (newatjobs == NULL)
1.35      millert   586:                                panic("Insufficient virtual memory");
1.40      tedu      587:                        atjobs = newatjobs;
                    588:                        maxjobs = newjobs;
1.29      millert   589:                }
                    590:                atjobs[numjobs++] = job;
                    591:        }
                    592:        free(uids);
1.45      robert    593:        closedir(spool);
1.29      millert   594:
                    595:        if (count_only || numjobs == 0) {
                    596:                if (numjobs == 0 && !shortformat)
                    597:                        fprintf(stderr, "no files in queue.\n");
                    598:                else if (count_only)
                    599:                        printf("%d\n", numjobs);
                    600:                free(atjobs);
                    601:                return;
                    602:        }
                    603:
                    604:        /* Sort by job run time or by job creation time. */
                    605:        qsort(atjobs, numjobs, sizeof(struct atjob *),
                    606:            csort ? byctime : byjobno);
                    607:
                    608:        if (!shortformat)
                    609:                (void)puts(" Rank     Execution Date     Owner          "
                    610:                    "Job       Queue");
                    611:
                    612:        for (i = 0; i < numjobs; i++) {
1.37      millert   613:                print_job(atjobs[i], i + 1, shortformat);
1.29      millert   614:                free(atjobs[i]);
1.1       deraadt   615:        }
1.29      millert   616:        free(atjobs);
                    617: }
                    618:
                    619: static int
                    620: rmok(int job)
                    621: {
                    622:        int ch, junk;
                    623:
                    624:        printf("%d: remove it? ", job);
                    625:        ch = getchar();
                    626:        while ((junk = getchar()) != EOF && junk != '\n')
                    627:                ;
                    628:        return (ch == 'y' || ch == 'Y');
1.1       deraadt   629: }
                    630:
1.29      millert   631: /*
1.35      millert   632:  * Loop through all jobs in AT_DIR and display or delete ones
1.29      millert   633:  * that match argv (may be job or username), or all if argc == 0.
                    634:  * Only the superuser may display/delete other people's jobs.
                    635:  */
1.28      millert   636: static int
1.26      millert   637: process_jobs(int argc, char **argv, int what)
1.1       deraadt   638: {
1.29      millert   639:        struct stat stbuf;
                    640:        struct dirent *dirent;
                    641:        struct passwd *pw;
                    642:        time_t runtimer;
                    643:        uid_t *uids;
1.46      cloder    644:        char **jobs, *ep;
1.29      millert   645:        long l;
                    646:        FILE *fp;
1.7       millert   647:        DIR *spool;
1.29      millert   648:        int job_matches, jobs_len, uids_len;
1.30      millert   649:        int error, i, ch, changed;
1.9       millert   650:
1.26      millert   651:        PRIV_START;
1.1       deraadt   652:
1.35      millert   653:        if (chdir(AT_DIR) != 0)
                    654:                perr2("Cannot change to ", AT_DIR);
1.1       deraadt   655:
1.7       millert   656:        if ((spool = opendir(".")) == NULL)
1.35      millert   657:                perr2("Cannot open ", AT_DIR);
1.7       millert   658:
1.26      millert   659:        PRIV_END;
1.7       millert   660:
1.29      millert   661:        /* Convert argv into a list of jobs and uids. */
                    662:        jobs = NULL;
                    663:        uids = NULL;
                    664:        jobs_len = uids_len = 0;
                    665:        if (argc > 0) {
                    666:                if ((jobs = malloc(sizeof(char *) * argc)) == NULL ||
                    667:                    (uids = malloc(sizeof(uid_t) * argc)) == NULL)
1.35      millert   668:                        panic("Insufficient virtual memory");
1.29      millert   669:
                    670:                for (i = 0; i < argc; i++) {
                    671:                        l = strtol(argv[i], &ep, 10);
                    672:                        if (*ep == '.' && isalpha(*(ep + 1)) &&
                    673:                            *(ep + 2) == '\0' && l > 0 && l < INT_MAX)
                    674:                                jobs[jobs_len++] = argv[i];
                    675:                        else if ((pw = getpwnam(argv[i])) != NULL) {
1.35      millert   676:                                if (real_uid != pw->pw_uid && real_uid != 0) {
                    677:                                        fprintf(stderr, "%s: Only the superuser"
1.39      mpech     678:                                            " may %s other users' jobs\n",
1.35      millert   679:                                            ProgramName, what == ATRM
                    680:                                            ? "remove" : "view");
                    681:                                        exit(ERROR_EXIT);
                    682:                                }
1.29      millert   683:                                uids[uids_len++] = pw->pw_uid;
                    684:                        } else
1.35      millert   685:                                panic2(argv[i], ": invalid user name");
1.29      millert   686:                }
                    687:        }
                    688:
1.7       millert   689:        /* Loop over every file in the directory */
1.30      millert   690:        changed = 0;
1.28      millert   691:        while ((dirent = readdir(spool)) != NULL) {
1.7       millert   692:
1.26      millert   693:                PRIV_START;
1.29      millert   694:                if (stat(dirent->d_name, &stbuf) != 0)
1.35      millert   695:                        perr2("Cannot stat in ", AT_DIR);
1.26      millert   696:                PRIV_END;
1.7       millert   697:
1.29      millert   698:                if (stbuf.st_uid != real_uid && real_uid != 0)
1.7       millert   699:                        continue;
                    700:
1.29      millert   701:                l = strtol(dirent->d_name, &ep, 10);
                    702:                if (*ep != '.' || !isalpha(*(ep + 1)) || *(ep + 2) != '\0' ||
                    703:                    l < 0 || l >= INT_MAX)
                    704:                        continue;
                    705:                runtimer = (time_t)l;
1.7       millert   706:
1.29      millert   707:                /* Check runtimer against argv; argc==0 means do all. */
                    708:                job_matches = (argc == 0) ? 1 : 0;
                    709:                if (!job_matches) {
                    710:                        for (i = 0; i < jobs_len; i++) {
1.36      millert   711:                                if (jobs[i] != NULL &&
                    712:                                    strcmp(dirent->d_name, jobs[i]) == 0) {
1.29      millert   713:                                        jobs[i] = NULL;
                    714:                                        job_matches = 1;
                    715:                                        break;
                    716:                                }
                    717:                        }
                    718:                }
                    719:                if (!job_matches) {
                    720:                        for (i = 0; i < uids_len; i++) {
                    721:                                if (uids[i] == stbuf.st_uid) {
                    722:                                        job_matches = 1;
                    723:                                        break;
                    724:                                }
                    725:                        }
                    726:                }
                    727:
                    728:                if (job_matches) {
                    729:                        switch (what) {
                    730:                        case ATRM:
                    731:                                PRIV_START;
                    732:
                    733:                                if (!interactive ||
                    734:                                    (interactive && rmok(runtimer))) {
1.30      millert   735:                                        if (unlink(dirent->d_name) == 0)
                    736:                                                changed = 1;
                    737:                                        else
1.7       millert   738:                                                perr(dirent->d_name);
1.29      millert   739:                                        if (!force && !interactive)
                    740:                                                fprintf(stderr,
                    741:                                                    "%s removed\n",
                    742:                                                    dirent->d_name);
                    743:                                }
1.7       millert   744:
1.29      millert   745:                                PRIV_END;
1.7       millert   746:
1.29      millert   747:                                break;
1.7       millert   748:
1.29      millert   749:                        case CAT:
                    750:                                PRIV_START;
1.7       millert   751:
1.29      millert   752:                                fp = fopen(dirent->d_name, "r");
1.7       millert   753:
1.29      millert   754:                                PRIV_END;
1.7       millert   755:
1.29      millert   756:                                if (!fp)
                    757:                                        perr("Cannot open file");
1.7       millert   758:
1.29      millert   759:                                while ((ch = getc(fp)) != EOF)
                    760:                                        putchar(ch);
1.7       millert   761:
1.45      robert    762:                                fclose(fp);
1.29      millert   763:                                break;
1.7       millert   764:
1.29      millert   765:                        default:
1.35      millert   766:                                panic("Internal error");
1.29      millert   767:                                break;
1.7       millert   768:                        }
1.1       deraadt   769:                }
                    770:        }
1.45      robert    771:        closedir(spool);
                    772:
1.29      millert   773:        for (error = 0, i = 0; i < jobs_len; i++) {
                    774:                if (jobs[i] != NULL) {
                    775:                        if (!force)
1.39      mpech     776:                                fprintf(stderr, "%s: %s: no such job\n",
1.35      millert   777:                                    ProgramName, jobs[i]);
1.28      millert   778:                        error++;
                    779:                }
                    780:        }
1.29      millert   781:        free(jobs);
                    782:        free(uids);
                    783:
1.30      millert   784:        /* If we modied the spool, poke cron so it knows to reload. */
1.35      millert   785:        if (changed) {
                    786:                PRIV_START;
                    787:                if (chdir(CRONDIR) != 0)
                    788:                        perror(CRONDIR);
                    789:                else
                    790:                        poke_daemon(AT_DIR, RELOAD_AT);
                    791:                PRIV_END;
                    792:        }
1.30      millert   793:
1.29      millert   794:        return (error);
1.28      millert   795: }
1.1       deraadt   796:
1.25      millert   797: #define        ATOI2(s)        ((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
                    798:
1.29      millert   799: /*
                    800:  * This is pretty much a copy of stime_arg1() from touch.c.
                    801:  */
1.25      millert   802: static time_t
                    803: ttime(const char *arg)
                    804: {
                    805:        struct timeval tv[2];
                    806:        time_t now;
                    807:        struct tm *t;
                    808:        int yearset;
                    809:        char *p;
1.42      millert   810:
1.25      millert   811:        if (gettimeofday(&tv[0], NULL))
                    812:                panic("Cannot get current time");
1.42      millert   813:
1.25      millert   814:        /* Start with the current time. */
                    815:        now = tv[0].tv_sec;
                    816:        if ((t = localtime(&now)) == NULL)
                    817:                panic("localtime");
                    818:        /* [[CC]YY]MMDDhhmm[.SS] */
                    819:        if ((p = strchr(arg, '.')) == NULL)
                    820:                t->tm_sec = 0;          /* Seconds defaults to 0. */
                    821:        else {
                    822:                if (strlen(p + 1) != 2)
                    823:                        goto terr;
                    824:                *p++ = '\0';
                    825:                t->tm_sec = ATOI2(p);
                    826:        }
1.42      millert   827:
1.25      millert   828:        yearset = 0;
                    829:        switch(strlen(arg)) {
                    830:        case 12:                        /* CCYYMMDDhhmm */
                    831:                t->tm_year = ATOI2(arg);
                    832:                t->tm_year *= 100;
                    833:                yearset = 1;
                    834:                /* FALLTHROUGH */
                    835:        case 10:                        /* YYMMDDhhmm */
                    836:                if (yearset) {
                    837:                        yearset = ATOI2(arg);
                    838:                        t->tm_year += yearset;
                    839:                } else {
                    840:                        yearset = ATOI2(arg);
                    841:                        t->tm_year = yearset + 2000;
                    842:                }
                    843:                t->tm_year -= 1900;     /* Convert to UNIX time. */
                    844:                /* FALLTHROUGH */
                    845:        case 8:                         /* MMDDhhmm */
                    846:                t->tm_mon = ATOI2(arg);
                    847:                --t->tm_mon;            /* Convert from 01-12 to 00-11 */
                    848:                t->tm_mday = ATOI2(arg);
                    849:                t->tm_hour = ATOI2(arg);
                    850:                t->tm_min = ATOI2(arg);
                    851:                break;
                    852:        default:
                    853:                goto terr;
                    854:        }
1.42      millert   855:
1.25      millert   856:        t->tm_isdst = -1;               /* Figure out DST. */
                    857:        tv[0].tv_sec = tv[1].tv_sec = mktime(t);
                    858:        if (tv[0].tv_sec != -1)
                    859:                return (tv[0].tv_sec);
                    860:        else
                    861:     terr:
                    862:                panic("out of range or illegal time specification: "
                    863:                    "[[CC]YY]MMDDhhmm[.SS]");
1.30      millert   864: }
                    865:
1.35      millert   866: static int
                    867: check_permission(void)
                    868: {
                    869:        int ok;
                    870:        uid_t uid = geteuid();
                    871:        struct passwd *pw;
1.30      millert   872:
1.35      millert   873:        if ((pw = getpwuid(uid)) == NULL) {
                    874:                perror("Cannot access password database");
                    875:                exit(ERROR_EXIT);
                    876:        }
1.30      millert   877:
                    878:        PRIV_START;
                    879:
1.35      millert   880:        ok = allowed(pw->pw_name, AT_ALLOW, AT_DENY);
                    881:
                    882:        PRIV_END;
1.30      millert   883:
1.35      millert   884:        return (ok);
                    885: }
1.30      millert   886:
1.41      millert   887: static __dead void
1.35      millert   888: usage(void)
                    889: {
                    890:        /* Print usage and exit.  */
                    891:        switch (program) {
                    892:        case AT:
                    893:        case CAT:
                    894:                (void)fprintf(stderr,
1.47    ! jmc       895:                    "usage: at [-bm] [-f file] [-l [user ...]] [-q queue] "
        !           896:                    "-t time_arg | timespec\n"
        !           897:                    "       at -c | -r job ...\n");
1.35      millert   898:                break;
                    899:        case ATQ:
                    900:                (void)fprintf(stderr,
1.43      jmc       901:                    "usage: atq [-cnv] [-q queue] [name ...]\n");
1.35      millert   902:                break;
                    903:        case ATRM:
                    904:                (void)fprintf(stderr,
                    905:                    "usage: atrm [-afi] [[job] [name] ...]\n");
                    906:                break;
                    907:        case BATCH:
                    908:                (void)fprintf(stderr,
                    909:                    "usage: batch [-m] [-f file] [-q queue] [timespec]\n");
                    910:                break;
                    911:        }
                    912:        exit(ERROR_EXIT);
1.25      millert   913: }
                    914:
1.1       deraadt   915: int
1.26      millert   916: main(int argc, char **argv)
1.1       deraadt   917: {
1.29      millert   918:        time_t timer = -1;
1.7       millert   919:        char queue = DEFAULT_AT_QUEUE;
                    920:        char queue_set = 0;
1.25      millert   921:        char *options = "q:f:t:bcdlmrv";        /* default options for at */
1.38      avsm      922:        char cwd[PATH_MAX];
1.29      millert   923:        int ch;
                    924:        int aflag = 0;
                    925:        int cflag = 0;
                    926:        int nflag = 0;
1.41      millert   927:
                    928:        if (argc < 1)
                    929:                usage();
1.1       deraadt   930:
1.35      millert   931:        if ((ProgramName = strrchr(argv[0], '/')) != NULL)
                    932:                ProgramName++;
                    933:        else
                    934:                ProgramName = argv[0];
                    935:
1.26      millert   936:        RELINQUISH_PRIVS;
1.1       deraadt   937:
                    938:        /* find out what this program is supposed to do */
1.35      millert   939:        if (strcmp(ProgramName, "atq") == 0) {
1.1       deraadt   940:                program = ATQ;
1.29      millert   941:                options = "cnvq:";
1.35      millert   942:        } else if (strcmp(ProgramName, "atrm") == 0) {
1.1       deraadt   943:                program = ATRM;
1.29      millert   944:                options = "afi";
1.35      millert   945:        } else if (strcmp(ProgramName, "batch") == 0) {
1.1       deraadt   946:                program = BATCH;
1.24      millert   947:                options = "f:q:mv";
1.1       deraadt   948:        }
                    949:
                    950:        /* process whatever options we can process */
1.29      millert   951:        while ((ch = getopt(argc, argv, options)) != -1) {
                    952:                switch (ch) {
                    953:                case 'a':
                    954:                        aflag = 1;
                    955:                        break;
                    956:
                    957:                case 'i':
                    958:                        interactive = 1;
                    959:                        force = 0;
                    960:                        break;
                    961:
                    962:                case 'v':       /* show completed but unremoved jobs */
                    963:                        /*
                    964:                         * This option is only useful when we are invoked
                    965:                         * as atq but we accept (and ignore) this flag in
                    966:                         * the other programs for backwards compatibility.
                    967:                         */
                    968:                        vflag = 1;
1.1       deraadt   969:                        break;
                    970:
                    971:                case 'm':       /* send mail when job is complete */
                    972:                        send_mail = 1;
                    973:                        break;
                    974:
                    975:                case 'f':
1.29      millert   976:                        if (program == ATRM) {
                    977:                                force = 1;
                    978:                                interactive = 0;
                    979:                        } else
                    980:                                atinput = optarg;
1.1       deraadt   981:                        break;
                    982:
                    983:                case 'q':       /* specify queue */
                    984:                        if (strlen(optarg) > 1)
                    985:                                usage();
                    986:
                    987:                        atqueue = queue = *optarg;
1.7       millert   988:                        if (!(islower(queue) || isupper(queue)))
1.1       deraadt   989:                                usage();
1.7       millert   990:
                    991:                        queue_set = 1;
                    992:                        break;
                    993:
1.25      millert   994:                case 'd':               /* for backwards compatibility */
                    995:                case 'r':
1.7       millert   996:                        program = ATRM;
1.24      millert   997:                        options = "";
1.7       millert   998:                        break;
                    999:
1.25      millert  1000:                case 't':
                   1001:                        timer = ttime(optarg);
                   1002:                        break;
                   1003:
1.7       millert  1004:                case 'l':
                   1005:                        program = ATQ;
1.29      millert  1006:                        options = "cnvq:";
1.7       millert  1007:                        break;
                   1008:
                   1009:                case 'b':
                   1010:                        program = BATCH;
1.24      millert  1011:                        options = "f:q:mv";
1.7       millert  1012:                        break;
                   1013:
                   1014:                case 'c':
1.29      millert  1015:                        if (program == ATQ) {
                   1016:                                cflag = 1;
                   1017:                        } else {
                   1018:                                program = CAT;
                   1019:                                options = "";
                   1020:                        }
                   1021:                        break;
                   1022:
                   1023:                case 'n':
                   1024:                        nflag = 1;
1.1       deraadt  1025:                        break;
                   1026:
                   1027:                default:
                   1028:                        usage();
                   1029:                        break;
                   1030:                }
1.29      millert  1031:        }
                   1032:        argc -= optind;
                   1033:        argv += optind;
1.7       millert  1034:
1.35      millert  1035:        if (getcwd(cwd, sizeof(cwd)) == NULL)
                   1036:                perr("Cannot get current working directory");
                   1037:
                   1038:        set_cron_cwd();
                   1039:
1.16      mickey   1040:        if (!check_permission())
1.35      millert  1041:                panic("You do not have permission to use at.");
1.7       millert  1042:
1.1       deraadt  1043:        /* select our program */
                   1044:        switch (program) {
                   1045:        case ATQ:
1.29      millert  1046:                list_jobs(argc, argv, nflag, cflag);
1.1       deraadt  1047:                break;
                   1048:
                   1049:        case ATRM:
1.7       millert  1050:        case CAT:
1.29      millert  1051:                if ((aflag && argc) || (!aflag && !argc))
1.10      millert  1052:                        usage();
1.28      millert  1053:                exit(process_jobs(argc, argv, program));
1.1       deraadt  1054:                break;
                   1055:
                   1056:        case AT:
1.25      millert  1057:                /* Time may have been specified via the -t flag. */
1.35      millert  1058:                if (timer == -1) {
                   1059:                        if (argc == 0)
                   1060:                                usage();
                   1061:                        else if ((timer = parsetime(argc, argv)) == -1)
                   1062:                                exit(ERROR_EXIT);
                   1063:                }
                   1064:                writefile(cwd, timer, queue);
1.1       deraadt  1065:                break;
                   1066:
                   1067:        case BATCH:
1.7       millert  1068:                if (queue_set)
                   1069:                        queue = toupper(queue);
                   1070:                else
                   1071:                        queue = DEFAULT_BATCH_QUEUE;
                   1072:
1.35      millert  1073:                if (argc == 0)
1.7       millert  1074:                        timer = time(NULL);
1.35      millert  1075:                else if ((timer = parsetime(argc, argv)) == -1)
                   1076:                        exit(ERROR_EXIT);
1.7       millert  1077:
1.35      millert  1078:                writefile(cwd, timer, queue);
1.1       deraadt  1079:                break;
                   1080:
                   1081:        default:
                   1082:                panic("Internal error");
                   1083:                break;
                   1084:        }
1.35      millert  1085:        exit(OK_EXIT);
1.1       deraadt  1086: }