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.
30 static const char rcsid[] =
31 "$FreeBSD: src/usr.bin/at/at.c,v 1.18.2.1 2001/08/02 00:55:58 obrien Exp $";
38 #include <sys/types.h>
41 #include <sys/param.h>
62 #if (MAXLOGNAME-1) > UT_NAMESIZE
63 #define LOGNAMESIZE UT_NAMESIZE
65 #define LOGNAMESIZE (MAXLOGNAME-1)
72 #include "parsetime.h"
81 #define ATJOB_DIR "/usr/spool/atjobs/"
85 #define LFILE ATJOB_DIR ".lockfile"
92 #define ALARMC 10 /* Number of seconds to wait for timeout */
97 enum { ATQ, ATRM, AT, BATCH, CAT }; /* what program we want to run */
99 /* File scope variables */
103 "TERM", "TERMCAP", "DISPLAY", "_"
105 static int send_mail = 0;
107 /* External variables */
109 extern char **environ;
111 char atfile[] = ATJOB_DIR "12345678901234";
113 char *atinput = (char*)0; /* where to get input from */
114 char atqueue = 0; /* which queue to examine for jobs (atq) */
115 char atverify = 0; /* verify time instead of queuing job */
117 /* Function declarations */
119 static void sigc(int signo);
120 static void alarmc(int signo);
121 static char *cwdname(void);
122 static void writefile(time_t runtimer, char queue);
123 static void list_jobs(void);
125 /* Signal catching functions */
127 static void sigc(int signo)
129 /* If the user presses ^C, remove the spool file and exit
141 static void alarmc(int signo)
143 /* Time out after some seconds
145 panic("file locking timed out");
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+")) != (FILE*)0) {
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")) != (FILE*)0) {
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(), which reads
316 * /etc/utmp, 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) > LOGNAMESIZE) || (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, LOGNAMESIZE, mailname, send_mail);
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<sizeof(no_export)/sizeof(no_export[0]); 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");
439 fprintf(stderr, "Job %ld will be executed using /bin/sh\n", jobno);
445 /* List all a user's jobs in the queue, by looping through ATJOB_DIR,
446 * or everybody's if we are root
450 struct dirent *dirent;
457 char timestr[TIMESIZE];
461 (void) setlocale(LC_TIME, "");
466 if (chdir(ATJOB_DIR) != 0)
467 perr("cannot change to " ATJOB_DIR);
469 if ((spool = opendir(".")) == NULL)
470 perr("cannot open " ATJOB_DIR);
472 /* Loop over every file in the directory
474 while((dirent = readdir(spool)) != NULL) {
475 if (stat(dirent->d_name, &buf) != 0)
476 perr("cannot stat in " ATJOB_DIR);
478 /* See it's a regular file and has its x bit turned on and
481 if (!S_ISREG(buf.st_mode)
482 || ((buf.st_uid != real_uid) && ! (real_uid == 0))
483 || !(S_IXUSR & buf.st_mode || atverify))
486 if(sscanf(dirent->d_name, "%c%5lx%8lx", &queue, &jobno, &ctm)!=3)
489 if (atqueue && (queue != atqueue))
492 runtimer = 60*(time_t) ctm;
493 runtime = *localtime(&runtimer);
494 strftime(timestr, TIMESIZE, "%X %x", &runtime);
496 printf("Date\t\t\tOwner\tQueue\tJob#\n");
499 pw = getpwuid(buf.st_uid);
501 printf("%s\t%s\t%c%s\t%ld\n",
503 pw ? pw->pw_name : "???",
505 (S_IXUSR & buf.st_mode) ? "":"(done)",
512 process_jobs(int argc, char **argv, int what)
514 /* Delete every argument (job - ID) given
519 struct dirent *dirent;
526 if (chdir(ATJOB_DIR) != 0)
527 perr("cannot change to " ATJOB_DIR);
529 if ((spool = opendir(".")) == NULL)
530 perr("cannot open " ATJOB_DIR);
534 /* Loop over every file in the directory
536 while((dirent = readdir(spool)) != NULL) {
539 if (stat(dirent->d_name, &buf) != 0)
540 perr("cannot stat in " ATJOB_DIR);
543 if(sscanf(dirent->d_name, "%c%5lx%8lx", &queue, &jobno, &ctm)!=3)
546 for (i=optind; i < argc; i++) {
547 if (atoi(argv[i]) == jobno) {
548 if ((buf.st_uid != real_uid) && !(real_uid == 0))
549 errx(EXIT_FAILURE, "%s: not owner", argv[i]);
555 if (unlink(dirent->d_name) != 0)
556 perr(dirent->d_name);
569 fp = fopen(dirent->d_name,"r");
574 perr("cannot open file");
576 while((ch = getc(fp)) != EOF) {
583 errx(EXIT_FAILURE, "internal error, process_jobs = %d",
592 main(int argc, char **argv)
595 char queue = DEFAULT_AT_QUEUE;
599 enum { ATQ, ATRM, AT, BATCH, CAT }; /* what program we want to run */
600 int program = AT; /* our default program */
601 char *options = "q:f:mvldbVc"; /* default options for at */
602 int disp_version = 0;
607 /* Eat any leading paths
609 if ((pgm = strrchr(argv[0], '/')) == NULL)
614 /* find out what this program is supposed to do
616 if (strcmp(pgm, "atq") == 0) {
620 else if (strcmp(pgm, "atrm") == 0) {
624 else if (strcmp(pgm, "batch") == 0) {
629 /* process whatever options we can process
632 while ((c=getopt(argc, argv, options)) != -1)
634 case 'v': /* verify time settings */
638 case 'm': /* send mail when job is complete */
646 case 'q': /* specify queue */
647 if (strlen(optarg) > 1)
650 atqueue = queue = *optarg;
651 if (!(islower(queue)||isupper(queue)))
694 /* end of options eating
698 fprintf(stderr, "at version " VERSION "\n"
699 "Bug reports to: ig25@rz.uni-karlsruhe.de (Thomas Koenig)\n");
701 /* select our program
703 if(!check_permission())
704 errx(EXIT_FAILURE, "you do not have permission to use this program");
708 REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
715 REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
717 process_jobs(argc, argv, ATRM);
722 process_jobs(argc, argv, CAT);
726 timer = parsetime(argc, argv);
729 struct tm *tm = localtime(&timer);
730 fprintf(stderr, "%s\n", asctime(tm));
732 writefile(timer, queue);
737 queue = toupper(queue);
739 queue = DEFAULT_BATCH_QUEUE;
742 timer = parsetime(argc, argv);
748 struct tm *tm = localtime(&timer);
749 fprintf(stderr, "%s\n", asctime(tm));
752 writefile(timer, queue);
756 panic("internal error");