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

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