2 * at.c : Put file into atrun queue
3 * Copyright (C) 1993, 1994 Thomas Koenig
5 * Atrun & Atq modifications
6 * Copyright (C) 1993 David Parsons
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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
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.
28 * $FreeBSD: src/usr.bin/at/at.c,v 1.30 2007/09/21 01:55:11 kevlo Exp $
35 #include <sys/param.h>
59 #include "parsetime.h"
68 #define ATJOB_DIR "/usr/spool/atjobs/"
72 #define LFILE ATJOB_DIR ".lockfile"
79 #define ALARMC 10 /* Number of seconds to wait for timeout */
84 enum { ATQ, ATRM, AT, BATCH, CAT }; /* what program we want to run */
86 /* File scope variables */
88 const char *no_export[] =
90 "TERM", "TERMCAP", "DISPLAY", "_"
92 static int send_mail = 0;
94 /* External variables */
95 uid_t real_uid, effective_uid;
96 gid_t real_gid, effective_gid;
98 extern char **environ;
100 char atfile[sizeof(ATJOB_DIR) + 14] = ATJOB_DIR;
102 char *atinput = NULL; /* where to get input from */
103 char atqueue = 0; /* which queue to examine for jobs (atq) */
104 char atverify = 0; /* verify time instead of queuing job */
107 /* Function declarations */
109 static void sigc(int signo);
110 static void alarmc(int signo);
111 static char *cwdname(void);
112 static void writefile(time_t runtimer, char queue);
113 static void list_jobs(long *, int);
114 static long nextjob(void);
115 static time_t ttime(const char *arg);
116 static char * timer2str(time_t runtimer);
117 static int in_job_list(long, long *, int);
118 static long *get_job_list(int, char *[], int *);
120 /* Signal catching functions */
123 sigc(int signo __unused)
125 /* If the user presses ^C, remove the spool file and exit
138 alarmc(int signo __unused)
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));
149 /* Local functions */
154 /* Read in the current directory; the name will be overwritten on
157 static char *ptr = NULL;
158 static size_t size = SIZE;
161 if ((ptr = malloc(size)) == NULL)
162 errx(EXIT_FAILURE, "virtual memory exhausted");
167 panic("out of memory");
169 if (getcwd(ptr, size-1) != NULL)
173 perr("cannot get directory");
177 if ((ptr = malloc(size)) == NULL)
178 errx(EXIT_FAILURE, "virtual memory exhausted");
188 if ((fid = fopen(ATJOB_DIR ".SEQ", "r+")) != NULL) {
189 if (fscanf(fid, "%5lx", &jobno) == 1) {
191 jobno = (1+jobno) % 0xfffff; /* 2^20 jobs enough? */
192 fprintf(fid, "%05lx\n", jobno);
199 else if ((fid = fopen(ATJOB_DIR ".SEQ", "w")) != NULL) {
200 fprintf(fid, "%05lx\n", jobno = 1);
208 writefile(time_t runtimer, char queue)
210 /* This does most of the work if at or batch are invoked for writing a job.
213 char *ap, *ppos, *mailname;
214 struct passwd *pass_entry;
216 int fdes, lockdes, fd2;
218 struct sigaction act;
224 setlocale(LC_TIME, "");
226 /* Install the signal handler for SIGINT; terminate after removing the
227 * spool file if necessary
229 act.sa_handler = sigc;
230 sigemptyset(&(act.sa_mask));
233 sigaction(SIGINT, &act, NULL);
235 /* Loop over all possible file names for running something at this
236 * particular time, see if a file is there; the first empty slot at any
237 * particular time is used. Lock the file LFILE first to make sure
238 * we're alone when doing this.
243 if ((lockdes = open(LFILE, O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR)) < 0)
244 perr("cannot open lockfile " LFILE);
246 lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0;
249 act.sa_handler = alarmc;
250 sigemptyset(&(act.sa_mask));
253 /* Set an alarm so a timeout occurs after ALARMC seconds, in case
254 * something is seriously broken.
256 sigaction(SIGALRM, &act, NULL);
258 fcntl(lockdes, F_SETLKW, &lock);
261 if ((jobno = nextjob()) == EOF)
262 perr("cannot generate job number");
264 ppos = atfile + strlen(atfile);
265 snprintf(ppos, sizeof(atfile) - strlen(atfile), "%c%5lx%8lx", queue,
266 jobno, (unsigned long) (runtimer/60));
268 for(ap=ppos; *ap != '\0'; ap ++)
272 if (stat(atfile, &statbuf) != 0)
274 perr("cannot access " ATJOB_DIR);
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.
281 cmask = umask(S_IRUSR | S_IWUSR | S_IXUSR);
282 if ((fdes = creat(atfile, O_WRONLY)) == -1)
283 perr("cannot create atjob file");
285 if ((fd2 = dup(fdes)) <0)
286 perr("error in dup() of job file");
288 if(fchown(fd2, real_uid, real_gid) != 0)
289 perr("cannot give away file");
293 /* We no longer need suid root; now we just need to be able to write
294 * to the directory, if necessary.
297 REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
299 /* We've successfully created the file; let's set the flag so it
300 * gets removed in case of an interrupt or error.
304 /* Now we can release the lock, so other people can access it
306 lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = 0;
308 fcntl(lockdes, F_SETLKW, &lock);
311 if((fp = fdopen(fdes, "w")) == NULL)
312 panic("cannot reopen atjob file");
314 /* Get the userid to mail to, first by trying getlogin(),
315 * then from LOGNAME, finally from getpwuid().
317 mailname = getlogin();
318 if (mailname == NULL)
319 mailname = getenv("LOGNAME");
321 if ((mailname == NULL) || (mailname[0] == '\0')
322 || (strlen(mailname) >= MAXLOGNAME) || (getpwnam(mailname)==NULL))
324 pass_entry = getpwuid(real_uid);
325 if (pass_entry != NULL)
326 mailname = pass_entry->pw_name;
331 fpin = freopen(atinput, "r", stdin);
333 perr("cannot open input file");
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,
339 /* Write out the umask at the time of invocation
341 fprintf(fp, "umask %lo\n", (unsigned long) cmask);
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.
348 for (atenv= environ; *atenv != NULL; atenv++)
353 eqp = strchr(*atenv, '=');
359 for (i=0; i<NELEM(no_export); i++)
362 && (strncmp(*atenv, no_export[i],
363 (size_t) (eqp-*atenv)) != 0);
370 fwrite(*atenv, sizeof(char), eqp-*atenv, fp);
371 for(ap = eqp;*ap != '\0'; ap++)
374 fprintf(fp, "\"\n\"");
379 case '%': case '/': case '{': case '[':
380 case ']': case '=': case '}': case '@':
381 case '+': case '#': case ',': case '.':
382 case ':': case '-': case '_':
392 fputs("; export ", fp);
393 fwrite(*atenv, sizeof(char), eqp-*atenv -1, fp);
398 /* Cd to the directory at the time and write out all the
399 * commands the user supplies from stdin.
402 for (ap = cwdname(); *ap != '\0'; ap++)
405 fprintf(fp, "\"\n\"");
408 if (*ap != '/' && !isalnum(*ap))
414 /* Test cd's exit status: die if the original directory has been
415 * removed, become unreadable or whatever
417 fprintf(fp, " || {\n\t echo 'Execution directory "
418 "inaccessible' >&2\n\t exit 1\n}\n");
420 while((ch = getchar()) != EOF)
425 panic("output error");
428 panic("input error");
432 /* Set the x bit so that we're ready to start executing
435 if (fchmod(fd2, S_IRUSR | S_IWUSR | S_IXUSR) < 0)
436 perr("cannot give away file");
441 char *timestr = timer2str(runtimer);
443 fprintf(stderr, "Job %ld will be executed using /bin/sh\n", jobno);
444 fprintf(stderr, "Job %ld at %s\n", jobno, timestr);
449 in_job_list(long job, long *joblist, int len)
453 for (i = 0; i < len; i++)
454 if (job == joblist[i])
461 list_jobs(long *joblist, int len)
463 /* List all a user's jobs in the queue, by looping through ATJOB_DIR,
464 * or everybody's if we are root
468 struct dirent *dirent;
477 setlocale(LC_TIME, "");
481 if (chdir(ATJOB_DIR) != 0)
482 perr("cannot change to " ATJOB_DIR);
484 if ((spool = opendir(".")) == NULL)
485 perr("cannot open " ATJOB_DIR);
487 /* Loop over every file in the directory
489 while((dirent = readdir(spool)) != NULL) {
490 if (stat(dirent->d_name, &buf) != 0)
491 perr("cannot stat in " ATJOB_DIR);
493 /* See it's a regular file and has its x bit turned on and
496 if (!S_ISREG(buf.st_mode)
497 || ((buf.st_uid != real_uid) && ! (real_uid == 0))
498 || !(S_IXUSR & buf.st_mode || atverify))
501 if(sscanf(dirent->d_name, "%c%5lx%8lx", &queue, &jobno, &ctm)!=3)
504 /* If jobs are given, only list those jobs */
505 if (joblist && !in_job_list(jobno, joblist, len))
508 if (atqueue && (queue != atqueue))
512 runtimer = 60*(time_t) ctm;
513 timestr = timer2str(runtimer);
515 /* Look up owner's uid in password database file */
516 pw = getpwuid(buf.st_uid);
519 printf("Date\t\t\t\tOwner\t\tQueue\tJob#\n");
522 printf("%s\t%-16s%c%s\t%ld\n",
524 pw ? pw->pw_name : "???",
526 (S_IXUSR & buf.st_mode) ? "":"(done)",
536 process_jobs(int argc, char **argv, int what)
538 /* Delete every argument (job - ID) given
543 struct dirent *dirent;
550 if (chdir(ATJOB_DIR) != 0)
551 perr("cannot change to " ATJOB_DIR);
553 if ((spool = opendir(".")) == NULL)
554 perr("cannot open " ATJOB_DIR);
558 /* Loop over every file in the directory
560 while((dirent = readdir(spool)) != NULL) {
563 if (stat(dirent->d_name, &buf) != 0)
564 perr("cannot stat in " ATJOB_DIR);
567 if(sscanf(dirent->d_name, "%c%5lx%8lx", &queue, &jobno, &ctm)!=3)
570 for (i=optind; i < argc; i++) {
571 if (atoi(argv[i]) == jobno) {
572 if ((buf.st_uid != real_uid) && !(real_uid == 0))
573 errx(EXIT_FAILURE, "%s: not owner", argv[i]);
579 if (unlink(dirent->d_name) != 0)
580 perr(dirent->d_name);
593 fp = fopen(dirent->d_name,"r");
598 perr("cannot open file");
600 while((ch = getc(fp)) != EOF) {
608 errx(EXIT_FAILURE, "internal error, process_jobs = %d",
617 #define ATOI2(ar) ((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
620 ttime(const char *arg)
623 * This is pretty much a copy of stime_arg1() from touch.c. I changed
624 * the return value and the argument list because it's more convenient
625 * (IMO) to do everything in one place. - Joe Halpin
627 struct timeval tv[2];
633 if (gettimeofday(&tv[0], NULL))
634 panic("Cannot get current time");
636 /* Start with the current time. */
638 if ((t = localtime(&now)) == NULL)
640 /* [[CC]YY]MMDDhhmm[.SS] */
641 if ((p = strchr(arg, '.')) == NULL)
642 t->tm_sec = 0; /* Seconds defaults to 0. */
644 if (strlen(p + 1) != 2)
647 t->tm_sec = ATOI2(p);
651 switch(strlen(arg)) {
652 case 12: /* CCYYMMDDhhmm */
653 t->tm_year = ATOI2(arg);
657 case 10: /* YYMMDDhhmm */
659 yearset = ATOI2(arg);
660 t->tm_year += yearset;
662 yearset = ATOI2(arg);
663 t->tm_year = yearset + 2000;
665 t->tm_year -= 1900; /* Convert to UNIX time. */
667 case 8: /* MMDDhhmm */
668 t->tm_mon = ATOI2(arg);
669 --t->tm_mon; /* Convert from 01-12 to 00-11 */
670 t->tm_mday = ATOI2(arg);
671 t->tm_hour = ATOI2(arg);
672 t->tm_min = ATOI2(arg);
678 t->tm_isdst = -1; /* Figure out DST. */
679 tv[0].tv_sec = tv[1].tv_sec = mktime(t);
680 if (tv[0].tv_sec != -1)
685 "out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
688 /* The caller must free up the memory. */
690 timer2str(time_t runtimer)
696 timestr = malloc(TIMESIZE);
698 panic("out of memory");
700 runtime = *localtime(&runtimer);
701 rv = strftime(timestr, TIMESIZE, nl_langinfo(D_T_FMT), &runtime);
703 panic("TIMESIZE too low");
709 get_job_list(int argc, char *argv[], int *joblen)
718 if ((joblist = malloc(len * sizeof(*joblist))) == NULL)
719 panic("out of memory");
721 for (i = 0; i < argc; i++) {
723 if ((joblist[i] = strtol(argv[i], &ep, 10)) < 0 ||
724 ep == argv[i] || *ep != '\0' || errno)
725 panic("invalid job number");
734 main(int argc, char **argv)
737 char queue = DEFAULT_AT_QUEUE;
741 int program = AT; /* our default program */
742 const char *options = "q:f:t:rmvldbc"; /* default options for at */
752 /* Eat any leading paths
754 if ((pgm = strrchr(argv[0], '/')) == NULL)
761 /* find out what this program is supposed to do
763 if (strcmp(pgm, "atq") == 0) {
767 else if (strcmp(pgm, "atrm") == 0) {
771 else if (strcmp(pgm, "batch") == 0) {
776 /* process whatever options we can process
779 while ((c=getopt(argc, argv, options)) != -1)
781 case 'v': /* verify time settings */
785 case 'm': /* send mail when job is complete */
793 case 'q': /* specify queue */
794 if (strlen(optarg) > 1)
797 atqueue = queue = *optarg;
798 if (!(islower(queue)||isupper(queue)))
805 warnx("-d is deprecated; use -r instead");
819 timer = ttime(optarg);
847 /* end of options eating
850 /* select our program
852 if(!check_permission())
853 errx(EXIT_FAILURE, "you do not have permission to use this program");
857 REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
860 joblist = get_job_list(argc - optind, argv + optind, &joblen);
861 list_jobs(joblist, joblen);
866 REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
868 process_jobs(argc, argv, ATRM);
873 process_jobs(argc, argv, CAT);
878 * If timer is > -1, then the user gave the time with -t. In that
879 * case, it's already been set. If not, set it now.
882 timer = parsetime(argc, argv);
886 struct tm *tm = localtime(&timer);
887 fprintf(stderr, "%s\n", asctime(tm));
889 writefile(timer, queue);
894 queue = toupper(queue);
896 queue = DEFAULT_BATCH_QUEUE;
899 timer = parsetime(argc, argv);
905 struct tm *tm = localtime(&timer);
906 fprintf(stderr, "%s\n", asctime(tm));
909 writefile(timer, queue);
913 panic("internal error");