xref: /freebsd/usr.bin/at/at.c (revision 1d386b48)
1 /*-
2  *  at.c : Put file into atrun queue
3  *
4  * SPDX-License-Identifier: BSD-2-Clause
5  *
6  *  Copyright (C) 1993, 1994 Thomas Koenig
7  *
8  *  Atrun & Atq modifications
9  *  Copyright (C) 1993  David Parsons
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. The name of the author(s) may not be used to endorse or promote
17  *    products derived from this software without specific prior written
18  *    permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
21  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #define _USE_BSD 1
34 
35 /* System Headers */
36 
37 #include <sys/param.h>
38 #include <sys/stat.h>
39 #include <sys/time.h>
40 #include <sys/wait.h>
41 #include <ctype.h>
42 #include <dirent.h>
43 #include <err.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #ifndef __FreeBSD__
47 #include <getopt.h>
48 #endif
49 #ifdef __FreeBSD__
50 #include <locale.h>
51 #endif
52 #include <pwd.h>
53 #include <signal.h>
54 #include <stddef.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <time.h>
59 #include <unistd.h>
60 
61 /* Local headers */
62 
63 #include "at.h"
64 #include "panic.h"
65 #include "parsetime.h"
66 #include "perm.h"
67 
68 #define MAIN
69 #include "privs.h"
70 
71 /* Macros */
72 
73 #ifndef ATJOB_DIR
74 #define ATJOB_DIR "/usr/spool/atjobs/"
75 #endif
76 
77 #ifndef LFILE
78 #define LFILE ATJOB_DIR ".lockfile"
79 #endif
80 
81 #ifndef ATJOB_MX
82 #define ATJOB_MX 255
83 #endif
84 
85 #define ALARMC 10 /* Number of seconds to wait for timeout */
86 
87 #define SIZE 255
88 #define TIMESIZE 50
89 
90 enum { ATQ, ATRM, AT, BATCH, CAT };	/* what program we want to run */
91 
92 /* File scope variables */
93 
94 static const char *no_export[] = {
95     "TERM", "TERMCAP", "DISPLAY", "_"
96 };
97 static int send_mail = 0;
98 static char *atinput = NULL;	/* where to get input from */
99 static char atqueue = 0;	/* which queue to examine for jobs (atq) */
100 
101 /* External variables */
102 
103 extern char **environ;
104 int fcreated;
105 char atfile[] = ATJOB_DIR "12345678901234";
106 char atverify = 0;		/* verify time instead of queuing job */
107 char *namep;
108 
109 /* Function declarations */
110 
111 static void sigc(int signo);
112 static void alarmc(int signo);
113 static char *cwdname(void);
114 static void writefile(time_t runtimer, char queue);
115 static void list_jobs(long *, int);
116 static long nextjob(void);
117 static time_t ttime(const char *arg);
118 static int in_job_list(long, long *, int);
119 static long *get_job_list(int, char *[], int *);
120 
121 /* Signal catching functions */
122 
sigc(int signo __unused)123 static void sigc(int signo __unused)
124 {
125 /* If the user presses ^C, remove the spool file and exit
126  */
127     if (fcreated)
128     {
129 	PRIV_START
130 	    unlink(atfile);
131 	PRIV_END
132     }
133 
134     _exit(EXIT_FAILURE);
135 }
136 
alarmc(int signo __unused)137 static void alarmc(int signo __unused)
138 {
139     char buf[1024];
140 
141     /* Time out after some seconds. */
142     strlcpy(buf, namep, sizeof(buf));
143     strlcat(buf, ": file locking timed out\n", sizeof(buf));
144     write(STDERR_FILENO, buf, strlen(buf));
145     sigc(0);
146 }
147 
148 /* Local functions */
149 
cwdname(void)150 static char *cwdname(void)
151 {
152 /* Read in the current directory; the name will be overwritten on
153  * subsequent calls.
154  */
155     static char *ptr = NULL;
156     static size_t size = SIZE;
157 
158     if (ptr == NULL)
159 	if ((ptr = malloc(size)) == NULL)
160 	    errx(EXIT_FAILURE, "virtual memory exhausted");
161 
162     while (1)
163     {
164 	if (ptr == NULL)
165 	    panic("out of memory");
166 
167 	if (getcwd(ptr, size-1) != NULL)
168 	    return ptr;
169 
170 	if (errno != ERANGE)
171 	    perr("cannot get directory");
172 
173 	free (ptr);
174 	size += SIZE;
175 	if ((ptr = malloc(size)) == NULL)
176 	    errx(EXIT_FAILURE, "virtual memory exhausted");
177     }
178 }
179 
180 static long
nextjob(void)181 nextjob(void)
182 {
183     long jobno;
184     FILE *fid;
185 
186     if ((fid = fopen(ATJOB_DIR ".SEQ", "r+")) != NULL) {
187 	if (fscanf(fid, "%5lx", &jobno) == 1) {
188 	    rewind(fid);
189 	    jobno = (1+jobno) % 0xfffff;	/* 2^20 jobs enough? */
190 	    fprintf(fid, "%05lx\n", jobno);
191 	}
192 	else
193 	    jobno = EOF;
194 	fclose(fid);
195 	return jobno;
196     }
197     else if ((fid = fopen(ATJOB_DIR ".SEQ", "w")) != NULL) {
198 	fprintf(fid, "%05lx\n", jobno = 1);
199 	fclose(fid);
200 	return 1;
201     }
202     return EOF;
203 }
204 
205 static void
writefile(time_t runtimer,char queue)206 writefile(time_t runtimer, char queue)
207 {
208 /* This does most of the work if at or batch are invoked for writing a job.
209  */
210     long jobno;
211     char *ap, *ppos, *mailname;
212     struct passwd *pass_entry;
213     struct stat statbuf;
214     int fdes, lockdes, fd2;
215     FILE *fp, *fpin;
216     struct sigaction act;
217     char **atenv;
218     int ch;
219     mode_t cmask;
220     struct flock lock;
221 
222 #ifdef __FreeBSD__
223     (void) setlocale(LC_TIME, "");
224 #endif
225 
226 /* Install the signal handler for SIGINT; terminate after removing the
227  * spool file if necessary
228  */
229     act.sa_handler = sigc;
230     sigemptyset(&(act.sa_mask));
231     act.sa_flags = 0;
232 
233     sigaction(SIGINT, &act, NULL);
234 
235     ppos = atfile + strlen(ATJOB_DIR);
236 
237     /* Loop over all possible file names for running something at this
238      * particular time, see if a file is there; the first empty slot at any
239      * particular time is used.  Lock the file LFILE first to make sure
240      * we're alone when doing this.
241      */
242 
243     PRIV_START
244 
245     if ((lockdes = open(LFILE, O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR)) < 0)
246 	perr("cannot open lockfile " LFILE);
247 
248     lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0;
249     lock.l_len = 0;
250 
251     act.sa_handler = alarmc;
252     sigemptyset(&(act.sa_mask));
253     act.sa_flags = 0;
254 
255     /* Set an alarm so a timeout occurs after ALARMC seconds, in case
256      * something is seriously broken.
257      */
258     sigaction(SIGALRM, &act, NULL);
259     alarm(ALARMC);
260     fcntl(lockdes, F_SETLKW, &lock);
261     alarm(0);
262 
263     if ((jobno = nextjob()) == EOF)
264 	perr("cannot generate job number");
265 
266     sprintf(ppos, "%c%5lx%8lx", queue,
267 	    jobno, (unsigned long) (runtimer/60));
268 
269     for(ap=ppos; *ap != '\0'; ap ++)
270 	if (*ap == ' ')
271 	    *ap = '0';
272 
273     if (stat(atfile, &statbuf) != 0)
274 	if (errno != ENOENT)
275 	    perr("cannot access " ATJOB_DIR);
276 
277     /* Create the file. The x bit is only going to be set after it has
278      * been completely written out, to make sure it is not executed in the
279      * meantime.  To make sure they do not get deleted, turn off their r
280      * bit.  Yes, this is a kluge.
281      */
282     cmask = umask(S_IRUSR | S_IWUSR | S_IXUSR);
283     if ((fdes = creat(atfile, O_WRONLY)) == -1)
284 	perr("cannot create atjob file");
285 
286     if ((fd2 = dup(fdes)) <0)
287 	perr("error in dup() of job file");
288 
289     if(fchown(fd2, real_uid, real_gid) != 0)
290 	perr("cannot give away file");
291 
292     PRIV_END
293 
294     /* We no longer need suid root; now we just need to be able to write
295      * to the directory, if necessary.
296      */
297 
298     REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
299 
300     /* We've successfully created the file; let's set the flag so it
301      * gets removed in case of an interrupt or error.
302      */
303     fcreated = 1;
304 
305     /* Now we can release the lock, so other people can access it
306      */
307     lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = 0;
308     lock.l_len = 0;
309     fcntl(lockdes, F_SETLKW, &lock);
310     close(lockdes);
311 
312     if((fp = fdopen(fdes, "w")) == NULL)
313 	panic("cannot reopen atjob file");
314 
315     /* Get the userid to mail to, first by trying getlogin(),
316      * then from LOGNAME, finally from getpwuid().
317      */
318     mailname = getlogin();
319     if (mailname == NULL)
320 	mailname = getenv("LOGNAME");
321 
322     if ((mailname == NULL) || (mailname[0] == '\0')
323 	|| (strlen(mailname) >= MAXLOGNAME) || (getpwnam(mailname)==NULL))
324     {
325 	pass_entry = getpwuid(real_uid);
326 	if (pass_entry != NULL)
327 	    mailname = pass_entry->pw_name;
328     }
329 
330     if (atinput != (char *) NULL)
331     {
332 	fpin = freopen(atinput, "r", stdin);
333 	if (fpin == NULL)
334 	    perr("cannot open input file");
335     }
336     fprintf(fp, "#!/bin/sh\n# atrun uid=%ld gid=%ld\n# mail %*s %d\n",
337 	(long) real_uid, (long) real_gid, MAXLOGNAME - 1, mailname,
338 	send_mail);
339 
340     /* Write out the umask at the time of invocation
341      */
342     fprintf(fp, "umask %lo\n", (unsigned long) cmask);
343 
344     /* Write out the environment. Anything that may look like a
345      * special character to the shell is quoted, except for \n, which is
346      * done with a pair of "'s.  Don't export the no_export list (such
347      * as TERM or DISPLAY) because we don't want these.
348      */
349     for (atenv= environ; *atenv != NULL; atenv++)
350     {
351 	int export = 1;
352 	char *eqp;
353 
354 	eqp = strchr(*atenv, '=');
355 	if (eqp == NULL)
356 	    eqp = *atenv;
357 	else
358 	{
359 	    size_t i;
360 	    for (i = 0; i < nitems(no_export); i++)
361 	    {
362 		export = export
363 		    && (strncmp(*atenv, no_export[i],
364 				(size_t) (eqp-*atenv)) != 0);
365 	    }
366 	    eqp++;
367 	}
368 
369 	if (export)
370 	{
371 	    (void)fputs("export ", fp);
372 	    fwrite(*atenv, sizeof(char), eqp-*atenv, fp);
373 	    for(ap = eqp;*ap != '\0'; ap++)
374 	    {
375 		if (*ap == '\n')
376 		    fprintf(fp, "\"\n\"");
377 		else
378 		{
379 		    if (!isalnum(*ap)) {
380 			switch (*ap) {
381 			  case '%': case '/': case '{': case '[':
382 			  case ']': case '=': case '}': case '@':
383 			  case '+': case '#': case ',': case '.':
384 			  case ':': case '-': case '_':
385 			    break;
386 			  default:
387 			    fputc('\\', fp);
388 			    break;
389 			}
390 		    }
391 		    fputc(*ap, fp);
392 		}
393 	    }
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
in_job_list(long job,long * joblist,int len)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
list_jobs(long * joblist,int len)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
process_jobs(int argc,char ** argv,int what)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
ttime(const char * arg)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 *
get_job_list(int argc,char * argv[],int * joblen)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
main(int argc,char ** argv)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