]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - usr.bin/at/at.c
MFC r272288,272289:
[FreeBSD/stable/8.git] / usr.bin / at / at.c
1 /* 
2  *  at.c : Put file into atrun queue
3  *  Copyright (C) 1993, 1994 Thomas Koenig
4  *
5  *  Atrun & Atq modifications
6  *  Copyright (C) 1993  David Parsons
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. The name of the author(s) may not be used to endorse or promote
14  *    products derived from this software without specific prior written
15  *    permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #define _USE_BSD 1
33
34 /* System Headers */
35
36 #include <sys/param.h>
37 #include <sys/stat.h>
38 #include <sys/time.h>
39 #include <sys/wait.h>
40 #include <ctype.h>
41 #include <dirent.h>
42 #include <err.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #ifndef __FreeBSD__
46 #include <getopt.h>
47 #endif
48 #ifdef __FreeBSD__
49 #include <locale.h>
50 #endif
51 #include <pwd.h>
52 #include <signal.h>
53 #include <stddef.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <time.h>
58 #include <unistd.h>
59
60 /* Local headers */
61
62 #include "at.h"
63 #include "panic.h"
64 #include "parsetime.h"
65 #include "perm.h"
66
67 #define MAIN
68 #include "privs.h"
69
70 /* Macros */
71
72 #ifndef ATJOB_DIR 
73 #define ATJOB_DIR "/usr/spool/atjobs/"
74 #endif
75
76 #ifndef LFILE
77 #define LFILE ATJOB_DIR ".lockfile"
78 #endif
79
80 #ifndef ATJOB_MX
81 #define ATJOB_MX 255
82 #endif
83
84 #define ALARMC 10 /* Number of seconds to wait for timeout */
85
86 #define SIZE 255
87 #define TIMESIZE 50
88
89 enum { ATQ, ATRM, AT, BATCH, CAT };     /* what program we want to run */
90
91 /* File scope variables */
92
93 const char *no_export[] =
94 {
95     "TERM", "TERMCAP", "DISPLAY", "_"
96 } ;
97 static int send_mail = 0;
98
99 /* External variables */
100
101 extern char **environ;
102 int fcreated;
103 char atfile[] = ATJOB_DIR "12345678901234";
104
105 char *atinput = (char*)0;       /* where to get input from */
106 char atqueue = 0;               /* which queue to examine for jobs (atq) */
107 char atverify = 0;              /* verify time instead of queuing job */
108 char *namep;
109
110 /* Function declarations */
111
112 static void sigc(int signo);
113 static void alarmc(int signo);
114 static char *cwdname(void);
115 static void writefile(time_t runtimer, char queue);
116 static void list_jobs(long *, int);
117 static long nextjob(void);
118 static time_t ttime(const char *arg);
119 static int in_job_list(long, long *, int);
120 static long *get_job_list(int, char *[], int *);
121
122 /* Signal catching functions */
123
124 static void sigc(int signo __unused)
125 {
126 /* If the user presses ^C, remove the spool file and exit 
127  */
128     if (fcreated)
129     {
130         PRIV_START
131             unlink(atfile);
132         PRIV_END
133     }
134
135     _exit(EXIT_FAILURE);
136 }
137
138 static void alarmc(int signo __unused)
139 {
140     char buf[1024];
141
142     /* Time out after some seconds. */
143     strlcpy(buf, namep, sizeof(buf));
144     strlcat(buf, ": file locking timed out\n", sizeof(buf));
145     write(STDERR_FILENO, buf, strlen(buf));
146     sigc(0);
147 }
148
149 /* Local functions */
150
151 static char *cwdname(void)
152 {
153 /* Read in the current directory; the name will be overwritten on
154  * subsequent calls.
155  */
156     static char *ptr = NULL;
157     static size_t size = SIZE;
158
159     if (ptr == NULL)
160         if ((ptr = malloc(size)) == NULL)
161             errx(EXIT_FAILURE, "virtual memory exhausted");
162
163     while (1)
164     {
165         if (ptr == NULL)
166             panic("out of memory");
167
168         if (getcwd(ptr, size-1) != NULL)
169             return ptr;
170         
171         if (errno != ERANGE)
172             perr("cannot get directory");
173         
174         free (ptr);
175         size += SIZE;
176         if ((ptr = malloc(size)) == NULL)
177             errx(EXIT_FAILURE, "virtual memory exhausted");
178     }
179 }
180
181 static long
182 nextjob()
183 {
184     long jobno;
185     FILE *fid;
186
187     if ((fid = fopen(ATJOB_DIR ".SEQ", "r+")) != NULL) {
188         if (fscanf(fid, "%5lx", &jobno) == 1) {
189             rewind(fid);
190             jobno = (1+jobno) % 0xfffff;        /* 2^20 jobs enough? */
191             fprintf(fid, "%05lx\n", jobno);
192         }
193         else
194             jobno = EOF;
195         fclose(fid);
196         return jobno;
197     }
198     else if ((fid = fopen(ATJOB_DIR ".SEQ", "w")) != NULL) {
199         fprintf(fid, "%05lx\n", jobno = 1);
200         fclose(fid);
201         return 1;
202     }
203     return EOF;
204 }
205
206 static void
207 writefile(time_t runtimer, char queue)
208 {
209 /* This does most of the work if at or batch are invoked for writing a job.
210  */
211     long jobno;
212     char *ap, *ppos, *mailname;
213     struct passwd *pass_entry;
214     struct stat statbuf;
215     int fdes, lockdes, fd2;
216     FILE *fp, *fpin;
217     struct sigaction act;
218     char **atenv;
219     int ch;
220     mode_t cmask;
221     struct flock lock;
222     
223 #ifdef __FreeBSD__
224     (void) setlocale(LC_TIME, "");
225 #endif
226
227 /* Install the signal handler for SIGINT; terminate after removing the
228  * spool file if necessary
229  */
230     act.sa_handler = sigc;
231     sigemptyset(&(act.sa_mask));
232     act.sa_flags = 0;
233
234     sigaction(SIGINT, &act, NULL);
235
236     ppos = atfile + strlen(ATJOB_DIR);
237
238     /* Loop over all possible file names for running something at this
239      * particular time, see if a file is there; the first empty slot at any
240      * particular time is used.  Lock the file LFILE first to make sure
241      * we're alone when doing this.
242      */
243
244     PRIV_START
245
246     if ((lockdes = open(LFILE, O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR)) < 0)
247         perr("cannot open lockfile " LFILE);
248
249     lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0;
250     lock.l_len = 0;
251
252     act.sa_handler = alarmc;
253     sigemptyset(&(act.sa_mask));
254     act.sa_flags = 0;
255
256     /* Set an alarm so a timeout occurs after ALARMC seconds, in case
257      * something is seriously broken.
258      */
259     sigaction(SIGALRM, &act, NULL);
260     alarm(ALARMC);
261     fcntl(lockdes, F_SETLKW, &lock);
262     alarm(0);
263
264     if ((jobno = nextjob()) == EOF)
265         perr("cannot generate job number");
266
267     sprintf(ppos, "%c%5lx%8lx", queue, 
268             jobno, (unsigned long) (runtimer/60));
269
270     for(ap=ppos; *ap != '\0'; ap ++)
271         if (*ap == ' ')
272             *ap = '0';
273
274     if (stat(atfile, &statbuf) != 0)
275         if (errno != ENOENT)
276             perr("cannot access " ATJOB_DIR);
277
278     /* Create the file. The x bit is only going to be set after it has
279      * been completely written out, to make sure it is not executed in the
280      * meantime.  To make sure they do not get deleted, turn off their r
281      * bit.  Yes, this is a kluge.
282      */
283     cmask = umask(S_IRUSR | S_IWUSR | S_IXUSR);
284     if ((fdes = creat(atfile, O_WRONLY)) == -1)
285         perr("cannot create atjob file"); 
286
287     if ((fd2 = dup(fdes)) <0)
288         perr("error in dup() of job file");
289
290     if(fchown(fd2, real_uid, real_gid) != 0)
291         perr("cannot give away file");
292
293     PRIV_END
294
295     /* We no longer need suid root; now we just need to be able to write
296      * to the directory, if necessary.
297      */
298
299     REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
300
301     /* We've successfully created the file; let's set the flag so it 
302      * gets removed in case of an interrupt or error.
303      */
304     fcreated = 1;
305
306     /* Now we can release the lock, so other people can access it
307      */
308     lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = 0;
309     lock.l_len = 0;
310     fcntl(lockdes, F_SETLKW, &lock);
311     close(lockdes);
312
313     if((fp = fdopen(fdes, "w")) == NULL)
314         panic("cannot reopen atjob file");
315
316     /* Get the userid to mail to, first by trying getlogin(),
317      * then from LOGNAME, finally from getpwuid().
318      */
319     mailname = getlogin();
320     if (mailname == NULL)
321         mailname = getenv("LOGNAME");
322
323     if ((mailname == NULL) || (mailname[0] == '\0') 
324         || (strlen(mailname) >= MAXLOGNAME) || (getpwnam(mailname)==NULL))
325     {
326         pass_entry = getpwuid(real_uid);
327         if (pass_entry != NULL)
328             mailname = pass_entry->pw_name;
329     }
330
331     if (atinput != (char *) NULL)
332     {
333         fpin = freopen(atinput, "r", stdin);
334         if (fpin == NULL)
335             perr("cannot open input file");
336     }
337     fprintf(fp, "#!/bin/sh\n# atrun uid=%ld gid=%ld\n# mail %*s %d\n",
338         (long) real_uid, (long) real_gid, MAXLOGNAME - 1, mailname,
339         send_mail);
340
341     /* Write out the umask at the time of invocation
342      */
343     fprintf(fp, "umask %lo\n", (unsigned long) cmask);
344
345     /* Write out the environment. Anything that may look like a
346      * special character to the shell is quoted, except for \n, which is
347      * done with a pair of "'s.  Don't export the no_export list (such
348      * as TERM or DISPLAY) because we don't want these.
349      */
350     for (atenv= environ; *atenv != NULL; atenv++)
351     {
352         int export = 1;
353         char *eqp;
354
355         eqp = strchr(*atenv, '=');
356         if (ap == NULL)
357             eqp = *atenv;
358         else
359         {
360             size_t i;
361             for (i=0; i<sizeof(no_export)/sizeof(no_export[0]); i++)
362             {
363                 export = export
364                     && (strncmp(*atenv, no_export[i], 
365                                 (size_t) (eqp-*atenv)) != 0);
366             }
367             eqp++;
368         }
369
370         if (export)
371         {
372             (void)fputs("export ", fp);
373             fwrite(*atenv, sizeof(char), eqp-*atenv, fp);
374             for(ap = eqp;*ap != '\0'; ap++)
375             {
376                 if (*ap == '\n')
377                     fprintf(fp, "\"\n\"");
378                 else
379                 {
380                     if (!isalnum(*ap)) {
381                         switch (*ap) {
382                           case '%': case '/': case '{': case '[':
383                           case ']': case '=': case '}': case '@':
384                           case '+': case '#': case ',': case '.':
385                           case ':': case '-': case '_':
386                             break;
387                           default:
388                             fputc('\\', fp);
389                             break;
390                         }
391                     }
392                     fputc(*ap, fp);
393                 }
394             }
395             fputc('\n', fp);
396             
397         }
398     }   
399     /* Cd to the directory at the time and write out all the
400      * commands the user supplies from stdin.
401      */
402     fprintf(fp, "cd ");
403     for (ap = cwdname(); *ap != '\0'; ap++)
404     {
405         if (*ap == '\n')
406             fprintf(fp, "\"\n\"");
407         else
408         {
409             if (*ap != '/' && !isalnum(*ap))
410                 fputc('\\', fp);
411             
412             fputc(*ap, fp);
413         }
414     }
415     /* Test cd's exit status: die if the original directory has been
416      * removed, become unreadable or whatever
417      */
418     fprintf(fp, " || {\n\t echo 'Execution directory "
419                 "inaccessible' >&2\n\t exit 1\n}\n");
420
421     while((ch = getchar()) != EOF)
422         fputc(ch, fp);
423
424     fprintf(fp, "\n");
425     if (ferror(fp))
426         panic("output error");
427         
428     if (ferror(stdin))
429         panic("input error");
430
431     fclose(fp);
432
433     /* Set the x bit so that we're ready to start executing
434      */
435
436     if (fchmod(fd2, S_IRUSR | S_IWUSR | S_IXUSR) < 0)
437         perr("cannot give away file");
438
439     close(fd2);
440     fprintf(stderr, "Job %ld will be executed using /bin/sh\n", jobno);
441 }
442
443 static int 
444 in_job_list(long job, long *joblist, int len)
445 {
446     int i;
447
448     for (i = 0; i < len; i++)
449         if (job == joblist[i])
450             return 1;
451
452     return 0;
453 }
454
455 static void
456 list_jobs(long *joblist, int len)
457 {
458     /* List all a user's jobs in the queue, by looping through ATJOB_DIR, 
459      * or everybody's if we are root
460      */
461     struct passwd *pw;
462     DIR *spool;
463     struct dirent *dirent;
464     struct stat buf;
465     struct tm runtime;
466     unsigned long ctm;
467     char queue;
468     long jobno;
469     time_t runtimer;
470     char timestr[TIMESIZE];
471     int first=1;
472     
473 #ifdef __FreeBSD__
474     (void) setlocale(LC_TIME, "");
475 #endif
476
477     PRIV_START
478
479     if (chdir(ATJOB_DIR) != 0)
480         perr("cannot change to " ATJOB_DIR);
481
482     if ((spool = opendir(".")) == NULL)
483         perr("cannot open " ATJOB_DIR);
484
485     /*  Loop over every file in the directory 
486      */
487     while((dirent = readdir(spool)) != NULL) {
488         if (stat(dirent->d_name, &buf) != 0)
489             perr("cannot stat in " ATJOB_DIR);
490         
491         /* See it's a regular file and has its x bit turned on and
492          * is the user's
493          */
494         if (!S_ISREG(buf.st_mode)
495             || ((buf.st_uid != real_uid) && ! (real_uid == 0))
496             || !(S_IXUSR & buf.st_mode || atverify))
497             continue;
498
499         if(sscanf(dirent->d_name, "%c%5lx%8lx", &queue, &jobno, &ctm)!=3)
500             continue;
501
502         /* If jobs are given, only list those jobs */
503         if (joblist && !in_job_list(jobno, joblist, len))
504             continue;
505
506         if (atqueue && (queue != atqueue))
507             continue;
508
509         runtimer = 60*(time_t) ctm;
510         runtime = *localtime(&runtimer);
511         strftime(timestr, TIMESIZE, "%+", &runtime);
512         if (first) {
513             printf("Date\t\t\t\tOwner\t\tQueue\tJob#\n");
514             first=0;
515         }
516         pw = getpwuid(buf.st_uid);
517
518         printf("%s\t%-16s%c%s\t%ld\n", 
519                timestr, 
520                pw ? pw->pw_name : "???", 
521                queue, 
522                (S_IXUSR & buf.st_mode) ? "":"(done)", 
523                jobno);
524     }
525     PRIV_END
526     closedir(spool);
527 }
528
529 static void
530 process_jobs(int argc, char **argv, int what)
531 {
532     /* Delete every argument (job - ID) given
533      */
534     int i;
535     int rc;
536     int nofJobs;
537     int nofDone;
538     int statErrno;
539     struct stat buf;
540     DIR *spool;
541     struct dirent *dirent;
542     unsigned long ctm;
543     char queue;
544     long jobno;
545
546     nofJobs = argc - optind;
547     nofDone = 0;
548
549     PRIV_START
550
551     if (chdir(ATJOB_DIR) != 0)
552         perr("cannot change to " ATJOB_DIR);
553
554     if ((spool = opendir(".")) == NULL)
555         perr("cannot open " ATJOB_DIR);
556
557     PRIV_END
558
559     /*  Loop over every file in the directory 
560      */
561     while((dirent = readdir(spool)) != NULL) {
562
563         PRIV_START
564         rc = stat(dirent->d_name, &buf);
565         statErrno = errno;
566         PRIV_END
567         /* There's a race condition between readdir above and stat here:
568          * another atrm process could have removed the file from the spool
569          * directory under our nose. If this happens, stat will set errno to
570          * ENOENT, which we shouldn't treat as fatal.
571          */
572         if (rc != 0) {
573             if (statErrno == ENOENT)
574                 continue;
575             else
576                 perr("cannot stat in " ATJOB_DIR);
577         }
578
579         if(sscanf(dirent->d_name, "%c%5lx%8lx", &queue, &jobno, &ctm)!=3)
580             continue;
581
582         for (i=optind; i < argc; i++) {
583             if (atoi(argv[i]) == jobno) {
584                 if ((buf.st_uid != real_uid) && !(real_uid == 0))
585                     errx(EXIT_FAILURE, "%s: not owner", argv[i]);
586                 switch (what) {
587                   case ATRM:
588
589                     PRIV_START
590
591                     if (unlink(dirent->d_name) != 0)
592                         perr(dirent->d_name);
593
594                     PRIV_END
595
596                     break;
597
598                   case CAT:
599                     {
600                         FILE *fp;
601                         int ch;
602
603                         PRIV_START
604
605                         fp = fopen(dirent->d_name,"r");
606
607                         PRIV_END
608
609                         if (!fp) {
610                             perr("cannot open file");
611                         }
612                         while((ch = getc(fp)) != EOF) {
613                             putchar(ch);
614                         }
615                         fclose(fp);
616                     }
617                     break;
618
619                   default:
620                     errx(EXIT_FAILURE, "internal error, process_jobs = %d",
621                         what);
622                 }
623
624                 /* All arguments have been processed
625                  */
626                 if (++nofDone == nofJobs)
627                     goto end;
628             }
629         }
630     }
631 end:
632     closedir(spool);
633 } /* delete_jobs */
634
635 #define ATOI2(ar)       ((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
636
637 static time_t
638 ttime(const char *arg)
639 {
640     /*
641      * This is pretty much a copy of stime_arg1() from touch.c.  I changed
642      * the return value and the argument list because it's more convenient
643      * (IMO) to do everything in one place. - Joe Halpin
644      */
645     struct timeval tv[2];
646     time_t now;
647     struct tm *t;
648     int yearset;
649     char *p;
650     
651     if (gettimeofday(&tv[0], NULL))
652         panic("Cannot get current time");
653     
654     /* Start with the current time. */
655     now = tv[0].tv_sec;
656     if ((t = localtime(&now)) == NULL)
657         panic("localtime");
658     /* [[CC]YY]MMDDhhmm[.SS] */
659     if ((p = strchr(arg, '.')) == NULL)
660         t->tm_sec = 0;          /* Seconds defaults to 0. */
661     else {
662         if (strlen(p + 1) != 2)
663             goto terr;
664         *p++ = '\0';
665         t->tm_sec = ATOI2(p);
666     }
667     
668     yearset = 0;
669     switch(strlen(arg)) {
670     case 12:                    /* CCYYMMDDhhmm */
671         t->tm_year = ATOI2(arg);
672         t->tm_year *= 100;
673         yearset = 1;
674         /* FALLTHROUGH */
675     case 10:                    /* YYMMDDhhmm */
676         if (yearset) {
677             yearset = ATOI2(arg);
678             t->tm_year += yearset;
679         } else {
680             yearset = ATOI2(arg);
681             t->tm_year = yearset + 2000;
682         }
683         t->tm_year -= 1900;     /* Convert to UNIX time. */
684         /* FALLTHROUGH */
685     case 8:                             /* MMDDhhmm */
686         t->tm_mon = ATOI2(arg);
687         --t->tm_mon;            /* Convert from 01-12 to 00-11 */
688         t->tm_mday = ATOI2(arg);
689         t->tm_hour = ATOI2(arg);
690         t->tm_min = ATOI2(arg);
691         break;
692     default:
693         goto terr;
694     }
695     
696     t->tm_isdst = -1;           /* Figure out DST. */
697     tv[0].tv_sec = tv[1].tv_sec = mktime(t);
698     if (tv[0].tv_sec != -1)
699         return tv[0].tv_sec;
700     else
701 terr:
702         panic(
703            "out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
704 }
705
706 static long *
707 get_job_list(int argc, char *argv[], int *joblen)
708 {
709     int i, len;
710     long *joblist;
711     char *ep;
712
713     joblist = NULL;
714     len = argc;
715     if (len > 0) {
716         if ((joblist = malloc(len * sizeof(*joblist))) == NULL)
717             panic("out of memory");
718
719         for (i = 0; i < argc; i++) {
720             errno = 0;
721             if ((joblist[i] = strtol(argv[i], &ep, 10)) < 0 ||
722                 ep == argv[i] || *ep != '\0' || errno)
723                 panic("invalid job number");
724         }
725     }
726
727     *joblen = len;
728     return joblist;
729 }
730
731 int
732 main(int argc, char **argv)
733 {
734     int c;
735     char queue = DEFAULT_AT_QUEUE;
736     char queue_set = 0;
737     char *pgm;
738
739     int program = AT;                   /* our default program */
740     const char *options = "q:f:t:rmvldbc"; /* default options for at */
741     time_t timer;
742     long *joblist;
743     int joblen;
744
745     joblist = NULL;
746     joblen = 0;
747     timer = -1;
748     RELINQUISH_PRIVS
749
750     /* Eat any leading paths
751      */
752     if ((pgm = strrchr(argv[0], '/')) == NULL)
753         pgm = argv[0];
754     else
755         pgm++;
756
757     namep = pgm;
758
759     /* find out what this program is supposed to do
760      */
761     if (strcmp(pgm, "atq") == 0) {
762         program = ATQ;
763         options = "q:v";
764     }
765     else if (strcmp(pgm, "atrm") == 0) {
766         program = ATRM;
767         options = "";
768     }
769     else if (strcmp(pgm, "batch") == 0) {
770         program = BATCH;
771         options = "f:q:mv";
772     }
773
774     /* process whatever options we can process
775      */
776     opterr=1;
777     while ((c=getopt(argc, argv, options)) != -1)
778         switch (c) {
779         case 'v':   /* verify time settings */
780             atverify = 1;
781             break;
782
783         case 'm':   /* send mail when job is complete */
784             send_mail = 1;
785             break;
786
787         case 'f':
788             atinput = optarg;
789             break;
790             
791         case 'q':    /* specify queue */
792             if (strlen(optarg) > 1)
793                 usage();
794
795             atqueue = queue = *optarg;
796             if (!(islower(queue)||isupper(queue)))
797                 usage();
798
799             queue_set = 1;
800             break;
801
802         case 'd':
803             warnx("-d is deprecated; use -r instead");
804             /* fall through to 'r' */
805
806         case 'r':
807             if (program != AT)
808                 usage();
809
810             program = ATRM;
811             options = "";
812             break;
813
814         case 't':
815             if (program != AT)
816                 usage();
817             timer = ttime(optarg);
818             break;
819
820         case 'l':
821             if (program != AT)
822                 usage();
823
824             program = ATQ;
825             options = "q:";
826             break;
827
828         case 'b':
829             if (program != AT)
830                 usage();
831
832             program = BATCH;
833             options = "f:q:mv";
834             break;
835
836         case 'c':
837             program = CAT;
838             options = "";
839             break;
840
841         default:
842             usage();
843             break;
844         }
845     /* end of options eating
846      */
847
848     /* select our program
849      */
850     if(!check_permission())
851         errx(EXIT_FAILURE, "you do not have permission to use this program");
852     switch (program) {
853     case ATQ:
854
855         REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
856
857         if (queue_set == 0)
858             joblist = get_job_list(argc - optind, argv + optind, &joblen);
859         list_jobs(joblist, joblen);
860         break;
861
862     case ATRM:
863
864         REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
865
866         process_jobs(argc, argv, ATRM);
867         break;
868
869     case CAT:
870
871         process_jobs(argc, argv, CAT);
872         break;
873
874     case AT:
875         /*
876          * If timer is > -1, then the user gave the time with -t.  In that
877          * case, it's already been set. If not, set it now.  
878          */
879         if (timer == -1) 
880             timer = parsetime(argc, argv);
881
882         if (atverify)
883         {
884             struct tm *tm = localtime(&timer);
885             fprintf(stderr, "%s\n", asctime(tm));
886         }
887         writefile(timer, queue);
888         break;
889
890     case BATCH:
891         if (queue_set)
892             queue = toupper(queue);
893         else
894             queue = DEFAULT_BATCH_QUEUE;
895
896         if (argc > optind)
897             timer = parsetime(argc, argv);
898         else
899             timer = time(NULL);
900         
901         if (atverify)
902         {
903             struct tm *tm = localtime(&timer);
904             fprintf(stderr, "%s\n", asctime(tm));
905         }
906
907         writefile(timer, queue);
908         break;
909
910     default:
911         panic("internal error");
912         break;
913     }
914     exit(EXIT_SUCCESS);
915 }