2 * at.c : Put file into atrun queue
4 * SPDX-License-Identifier: BSD-2-Clause
6 * Copyright (C) 1993, 1994 Thomas Koenig
8 * Atrun & Atq modifications
9 * Copyright (C) 1993 David Parsons
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
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
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.
32 #include <sys/cdefs.h>
37 #include <sys/param.h>
65 #include "parsetime.h"
74 #define ATJOB_DIR "/usr/spool/atjobs/"
78 #define LFILE ATJOB_DIR ".lockfile"
85 #define ALARMC 10 /* Number of seconds to wait for timeout */
90 enum { ATQ, ATRM, AT, BATCH, CAT }; /* what program we want to run */
92 /* File scope variables */
94 static const char *no_export[] = {
95 "TERM", "TERMCAP", "DISPLAY", "_"
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) */
101 /* External variables */
103 extern char **environ;
105 char atfile[] = ATJOB_DIR "12345678901234";
106 char atverify = 0; /* verify time instead of queuing job */
109 /* Function declarations */
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 *);
121 /* Signal catching functions */
123 static void sigc(int signo __unused)
125 /* If the user presses ^C, remove the spool file and exit
137 static void alarmc(int signo __unused)
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));
148 /* Local functions */
150 static char *cwdname(void)
152 /* Read in the current directory; the name will be overwritten on
155 static char *ptr = NULL;
156 static size_t size = SIZE;
159 if ((ptr = malloc(size)) == NULL)
160 errx(EXIT_FAILURE, "virtual memory exhausted");
165 panic("out of memory");
167 if (getcwd(ptr, size-1) != NULL)
171 perr("cannot get directory");
175 if ((ptr = malloc(size)) == NULL)
176 errx(EXIT_FAILURE, "virtual memory exhausted");
186 if ((fid = fopen(ATJOB_DIR ".SEQ", "r+")) != NULL) {
187 if (fscanf(fid, "%5lx", &jobno) == 1) {
189 jobno = (1+jobno) % 0xfffff; /* 2^20 jobs enough? */
190 fprintf(fid, "%05lx\n", jobno);
197 else if ((fid = fopen(ATJOB_DIR ".SEQ", "w")) != NULL) {
198 fprintf(fid, "%05lx\n", jobno = 1);
206 writefile(time_t runtimer, char queue)
208 /* This does most of the work if at or batch are invoked for writing a job.
211 char *ap, *ppos, *mailname;
212 struct passwd *pass_entry;
214 int fdes, lockdes, fd2;
216 struct sigaction act;
223 (void) 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 ppos = atfile + strlen(ATJOB_DIR);
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.
245 if ((lockdes = open(LFILE, O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR)) < 0)
246 perr("cannot open lockfile " LFILE);
248 lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0;
251 act.sa_handler = alarmc;
252 sigemptyset(&(act.sa_mask));
255 /* Set an alarm so a timeout occurs after ALARMC seconds, in case
256 * something is seriously broken.
258 sigaction(SIGALRM, &act, NULL);
260 fcntl(lockdes, F_SETLKW, &lock);
263 if ((jobno = nextjob()) == EOF)
264 perr("cannot generate job number");
266 sprintf(ppos, "%c%5lx%8lx", queue,
267 jobno, (unsigned long) (runtimer/60));
269 for(ap=ppos; *ap != '\0'; ap ++)
273 if (stat(atfile, &statbuf) != 0)
275 perr("cannot access " ATJOB_DIR);
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.
282 cmask = umask(S_IRUSR | S_IWUSR | S_IXUSR);
283 if ((fdes = creat(atfile, O_WRONLY)) == -1)
284 perr("cannot create atjob file");
286 if ((fd2 = dup(fdes)) <0)
287 perr("error in dup() of job file");
289 if(fchown(fd2, real_uid, real_gid) != 0)
290 perr("cannot give away file");
294 /* We no longer need suid root; now we just need to be able to write
295 * to the directory, if necessary.
298 REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
300 /* We've successfully created the file; let's set the flag so it
301 * gets removed in case of an interrupt or error.
305 /* Now we can release the lock, so other people can access it
307 lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = 0;
309 fcntl(lockdes, F_SETLKW, &lock);
312 if((fp = fdopen(fdes, "w")) == NULL)
313 panic("cannot reopen atjob file");
315 /* Get the userid to mail to, first by trying getlogin(),
316 * then from LOGNAME, finally from getpwuid().
318 mailname = getlogin();
319 if (mailname == NULL)
320 mailname = getenv("LOGNAME");
322 if ((mailname == NULL) || (mailname[0] == '\0')
323 || (strlen(mailname) >= MAXLOGNAME) || (getpwnam(mailname)==NULL))
325 pass_entry = getpwuid(real_uid);
326 if (pass_entry != NULL)
327 mailname = pass_entry->pw_name;
330 if (atinput != (char *) NULL)
332 fpin = freopen(atinput, "r", stdin);
334 perr("cannot open input file");
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,
340 /* Write out the umask at the time of invocation
342 fprintf(fp, "umask %lo\n", (unsigned long) cmask);
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.
349 for (atenv= environ; *atenv != NULL; atenv++)
354 eqp = strchr(*atenv, '=');
360 for (i = 0; i < nitems(no_export); i++)
363 && (strncmp(*atenv, no_export[i],
364 (size_t) (eqp-*atenv)) != 0);
371 (void)fputs("export ", fp);
372 fwrite(*atenv, sizeof(char), eqp-*atenv, fp);
373 for(ap = eqp;*ap != '\0'; ap++)
376 fprintf(fp, "\"\n\"");
381 case '%': case '/': case '{': case '[':
382 case ']': case '=': case '}': case '@':
383 case '+': case '#': case ',': case '.':
384 case ':': case '-': case '_':
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");
439 fprintf(stderr, "Job %ld will be executed using /bin/sh\n", jobno);
443 in_job_list(long job, long *joblist, int len)
447 for (i = 0; i < len; i++)
448 if (job == joblist[i])
455 list_jobs(long *joblist, int len)
457 /* List all a user's jobs in the queue, by looping through ATJOB_DIR,
458 * or everybody's if we are root
462 struct dirent *dirent;
469 char timestr[TIMESIZE];
473 (void) setlocale(LC_TIME, "");
478 if (chdir(ATJOB_DIR) != 0)
479 perr("cannot change to " ATJOB_DIR);
481 if ((spool = opendir(".")) == NULL)
482 perr("cannot open " ATJOB_DIR);
484 /* Loop over every file in the directory
486 while((dirent = readdir(spool)) != NULL) {
487 if (stat(dirent->d_name, &buf) != 0)
488 perr("cannot stat in " ATJOB_DIR);
490 /* See it's a regular file and has its x bit turned on and
493 if (!S_ISREG(buf.st_mode)
494 || ((buf.st_uid != real_uid) && ! (real_uid == 0))
495 || !(S_IXUSR & buf.st_mode || atverify))
498 if(sscanf(dirent->d_name, "%c%5lx%8lx", &queue, &jobno, &ctm)!=3)
501 /* If jobs are given, only list those jobs */
502 if (joblist && !in_job_list(jobno, joblist, len))
505 if (atqueue && (queue != atqueue))
508 runtimer = 60*(time_t) ctm;
509 runtime = *localtime(&runtimer);
510 strftime(timestr, TIMESIZE, "%+", &runtime);
512 printf("Date\t\t\t\tOwner\t\tQueue\tJob#\n");
515 pw = getpwuid(buf.st_uid);
517 printf("%s\t%-16s%c%s\t%ld\n",
519 pw ? pw->pw_name : "???",
521 (S_IXUSR & buf.st_mode) ? "":"(done)",
529 process_jobs(int argc, char **argv, int what)
531 /* Delete every argument (job - ID) given
540 struct dirent *dirent;
545 nofJobs = argc - optind;
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 rc = stat(dirent->d_name, &buf);
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.
572 if (statErrno == ENOENT)
575 perr("cannot stat in " ATJOB_DIR);
578 if(sscanf(dirent->d_name, "%c%5lx%8lx", &queue, &jobno, &ctm)!=3)
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]);
590 if (unlink(dirent->d_name) != 0)
591 perr(dirent->d_name);
604 fp = fopen(dirent->d_name,"r");
609 perr("cannot open file");
611 while((ch = getc(fp)) != EOF) {
619 errx(EXIT_FAILURE, "internal error, process_jobs = %d",
623 /* All arguments have been processed
625 if (++nofDone == nofJobs)
634 #define ATOI2(ar) ((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
637 ttime(const char *arg)
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
644 struct timeval tv[2];
650 if (gettimeofday(&tv[0], NULL))
651 panic("Cannot get current time");
653 /* Start with the current time. */
655 if ((t = localtime(&now)) == NULL)
657 /* [[CC]YY]MMDDhhmm[.SS] */
658 if ((p = strchr(arg, '.')) == NULL)
659 t->tm_sec = 0; /* Seconds defaults to 0. */
661 if (strlen(p + 1) != 2)
664 t->tm_sec = ATOI2(p);
668 switch(strlen(arg)) {
669 case 12: /* CCYYMMDDhhmm */
670 t->tm_year = ATOI2(arg);
674 case 10: /* YYMMDDhhmm */
676 yearset = ATOI2(arg);
677 t->tm_year += yearset;
679 yearset = ATOI2(arg);
680 t->tm_year = yearset + 2000;
682 t->tm_year -= 1900; /* Convert to UNIX time. */
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);
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)
702 "out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
706 get_job_list(int argc, char *argv[], int *joblen)
715 if ((joblist = malloc(len * sizeof(*joblist))) == NULL)
716 panic("out of memory");
718 for (i = 0; i < argc; i++) {
720 if ((joblist[i] = strtol(argv[i], &ep, 10)) < 0 ||
721 ep == argv[i] || *ep != '\0' || errno)
722 panic("invalid job number");
731 main(int argc, char **argv)
734 char queue = DEFAULT_AT_QUEUE;
738 int program = AT; /* our default program */
739 const char *options = "q:f:t:rmvldbc"; /* default options for at */
749 /* Eat any leading paths
751 if ((pgm = strrchr(argv[0], '/')) == NULL)
758 /* find out what this program is supposed to do
760 if (strcmp(pgm, "atq") == 0) {
764 else if (strcmp(pgm, "atrm") == 0) {
768 else if (strcmp(pgm, "batch") == 0) {
773 /* process whatever options we can process
776 while ((c=getopt(argc, argv, options)) != -1)
778 case 'v': /* verify time settings */
782 case 'm': /* send mail when job is complete */
790 case 'q': /* specify queue */
791 if (strlen(optarg) > 1)
794 atqueue = queue = *optarg;
795 if (!(islower(queue)||isupper(queue)))
802 warnx("-d is deprecated; use -r instead");
803 /* fall through to 'r' */
816 timer = ttime(optarg);
844 /* end of options eating
847 /* select our program
849 if(!check_permission())
850 errx(EXIT_FAILURE, "you do not have permission to use this program");
854 REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
857 joblist = get_job_list(argc - optind, argv + optind, &joblen);
858 list_jobs(joblist, joblen);
863 REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
865 process_jobs(argc, argv, ATRM);
870 process_jobs(argc, argv, CAT);
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.
879 timer = parsetime(argc, argv);
883 struct tm *tm = localtime(&timer);
884 fprintf(stderr, "%s\n", asctime(tm));
886 writefile(timer, queue);
891 queue = toupper(queue);
893 queue = DEFAULT_BATCH_QUEUE;
896 timer = parsetime(argc, argv);
902 struct tm *tm = localtime(&timer);
903 fprintf(stderr, "%s\n", asctime(tm));
906 writefile(timer, queue);
910 panic("internal error");