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