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