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.18.2.1 2001/08/02 00:55:58 obrien Exp $
29 * $DragonFly: src/usr.bin/at/at.c,v 1.4 2004/01/22 03:22:52 rob Exp $
36 #include <sys/types.h>
39 #include <sys/param.h>
60 #if (MAXLOGNAME-1) > UT_NAMESIZE
61 #define LOGNAMESIZE UT_NAMESIZE
63 #define LOGNAMESIZE (MAXLOGNAME-1)
70 #include "parsetime.h"
79 #define ATJOB_DIR "/usr/spool/atjobs/"
83 #define LFILE ATJOB_DIR ".lockfile"
90 #define ALARMC 10 /* Number of seconds to wait for timeout */
95 enum { ATQ, ATRM, AT, BATCH, CAT }; /* what program we want to run */
97 /* File scope variables */
101 "TERM", "TERMCAP", "DISPLAY", "_"
103 static int send_mail = 0;
105 /* External variables */
107 extern char **environ;
109 char atfile[] = ATJOB_DIR "12345678901234";
111 char *atinput = (char*)0; /* where to get input from */
112 char atqueue = 0; /* which queue to examine for jobs (atq) */
113 char atverify = 0; /* verify time instead of queuing job */
115 /* Function declarations */
117 static void sigc(int signo);
118 static void alarmc(int signo);
119 static char *cwdname(void);
120 static void writefile(time_t runtimer, char queue);
121 static void list_jobs(void);
123 /* Signal catching functions */
125 static void sigc(int signo)
127 /* If the user presses ^C, remove the spool file and exit
139 static void alarmc(int signo)
141 /* Time out after some seconds
143 panic("file locking timed out");
146 /* Local functions */
148 static char *cwdname(void)
150 /* Read in the current directory; the name will be overwritten on
153 static char *ptr = NULL;
154 static size_t size = SIZE;
157 if ((ptr = malloc(size)) == NULL)
158 errx(EXIT_FAILURE, "virtual memory exhausted");
163 panic("out of memory");
165 if (getcwd(ptr, size-1) != NULL)
169 perr("cannot get directory");
173 if ((ptr = malloc(size)) == NULL)
174 errx(EXIT_FAILURE, "virtual memory exhausted");
184 if ((fid = fopen(ATJOB_DIR ".SEQ", "r+")) != (FILE*)0) {
185 if (fscanf(fid, "%5lx", &jobno) == 1) {
187 jobno = (1+jobno) % 0xfffff; /* 2^20 jobs enough? */
188 fprintf(fid, "%05lx\n", jobno);
195 else if ((fid = fopen(ATJOB_DIR ".SEQ", "w")) != (FILE*)0) {
196 fprintf(fid, "%05lx\n", jobno = 1);
204 writefile(time_t runtimer, char queue)
206 /* This does most of the work if at or batch are invoked for writing a job.
209 char *ap, *ppos, *mailname;
210 struct passwd *pass_entry;
212 int fdes, lockdes, fd2;
214 struct sigaction act;
221 (void) setlocale(LC_TIME, "");
224 /* Install the signal handler for SIGINT; terminate after removing the
225 * spool file if necessary
227 act.sa_handler = sigc;
228 sigemptyset(&(act.sa_mask));
231 sigaction(SIGINT, &act, NULL);
233 ppos = atfile + strlen(ATJOB_DIR);
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 sprintf(ppos, "%c%5lx%8lx", queue,
265 jobno, (unsigned long) (runtimer/60));
267 for(ap=ppos; *ap != '\0'; ap ++)
271 if (stat(atfile, &statbuf) != 0)
273 perr("cannot access " ATJOB_DIR);
275 /* Create the file. The x bit is only going to be set after it has
276 * been completely written out, to make sure it is not executed in the
277 * meantime. To make sure they do not get deleted, turn off their r
278 * bit. Yes, this is a kluge.
280 cmask = umask(S_IRUSR | S_IWUSR | S_IXUSR);
281 if ((fdes = creat(atfile, O_WRONLY)) == -1)
282 perr("cannot create atjob file");
284 if ((fd2 = dup(fdes)) <0)
285 perr("error in dup() of job file");
287 if(fchown(fd2, real_uid, real_gid) != 0)
288 perr("cannot give away file");
292 /* We no longer need suid root; now we just need to be able to write
293 * to the directory, if necessary.
296 REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
298 /* We've successfully created the file; let's set the flag so it
299 * gets removed in case of an interrupt or error.
303 /* Now we can release the lock, so other people can access it
305 lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = 0;
307 fcntl(lockdes, F_SETLKW, &lock);
310 if((fp = fdopen(fdes, "w")) == NULL)
311 panic("cannot reopen atjob file");
313 /* Get the userid to mail to, first by trying getlogin(), which reads
314 * /etc/utmp, then from LOGNAME, finally from getpwuid().
316 mailname = getlogin();
317 if (mailname == NULL)
318 mailname = getenv("LOGNAME");
320 if ((mailname == NULL) || (mailname[0] == '\0')
321 || (strlen(mailname) > LOGNAMESIZE) || (getpwnam(mailname)==NULL))
323 pass_entry = getpwuid(real_uid);
324 if (pass_entry != NULL)
325 mailname = pass_entry->pw_name;
328 if (atinput != (char *) NULL)
330 fpin = freopen(atinput, "r", stdin);
332 perr("cannot open input file");
334 fprintf(fp, "#!/bin/sh\n# atrun uid=%ld gid=%ld\n# mail %*s %d\n",
335 (long) real_uid, (long) real_gid, LOGNAMESIZE, mailname, send_mail);
337 /* Write out the umask at the time of invocation
339 fprintf(fp, "umask %lo\n", (unsigned long) cmask);
341 /* Write out the environment. Anything that may look like a
342 * special character to the shell is quoted, except for \n, which is
343 * done with a pair of "'s. Don't export the no_export list (such
344 * as TERM or DISPLAY) because we don't want these.
346 for (atenv= environ; *atenv != NULL; atenv++)
351 eqp = strchr(*atenv, '=');
357 for (i=0; i<sizeof(no_export)/sizeof(no_export[0]); i++)
360 && (strncmp(*atenv, no_export[i],
361 (size_t) (eqp-*atenv)) != 0);
368 fwrite(*atenv, sizeof(char), eqp-*atenv, fp);
369 for(ap = eqp;*ap != '\0'; ap++)
372 fprintf(fp, "\"\n\"");
377 case '%': case '/': case '{': case '[':
378 case ']': case '=': case '}': case '@':
379 case '+': case '#': case ',': case '.':
380 case ':': case '-': case '_':
390 fputs("; export ", fp);
391 fwrite(*atenv, sizeof(char), eqp-*atenv -1, fp);
396 /* Cd to the directory at the time and write out all the
397 * commands the user supplies from stdin.
400 for (ap = cwdname(); *ap != '\0'; ap++)
403 fprintf(fp, "\"\n\"");
406 if (*ap != '/' && !isalnum(*ap))
412 /* Test cd's exit status: die if the original directory has been
413 * removed, become unreadable or whatever
415 fprintf(fp, " || {\n\t echo 'Execution directory "
416 "inaccessible' >&2\n\t exit 1\n}\n");
418 while((ch = getchar()) != EOF)
423 panic("output error");
426 panic("input error");
430 /* Set the x bit so that we're ready to start executing
433 if (fchmod(fd2, S_IRUSR | S_IWUSR | S_IXUSR) < 0)
434 perr("cannot give away file");
437 fprintf(stderr, "Job %ld will be executed using /bin/sh\n", jobno);
443 /* List all a user's jobs in the queue, by looping through ATJOB_DIR,
444 * or everybody's if we are root
448 struct dirent *dirent;
455 char timestr[TIMESIZE];
459 (void) setlocale(LC_TIME, "");
464 if (chdir(ATJOB_DIR) != 0)
465 perr("cannot change to " ATJOB_DIR);
467 if ((spool = opendir(".")) == NULL)
468 perr("cannot open " ATJOB_DIR);
470 /* Loop over every file in the directory
472 while((dirent = readdir(spool)) != NULL) {
473 if (stat(dirent->d_name, &buf) != 0)
474 perr("cannot stat in " ATJOB_DIR);
476 /* See it's a regular file and has its x bit turned on and
479 if (!S_ISREG(buf.st_mode)
480 || ((buf.st_uid != real_uid) && ! (real_uid == 0))
481 || !(S_IXUSR & buf.st_mode || atverify))
484 if(sscanf(dirent->d_name, "%c%5lx%8lx", &queue, &jobno, &ctm)!=3)
487 if (atqueue && (queue != atqueue))
490 runtimer = 60*(time_t) ctm;
491 runtime = *localtime(&runtimer);
492 strftime(timestr, TIMESIZE, "%X %x", &runtime);
494 printf("Date\t\t\tOwner\tQueue\tJob#\n");
497 pw = getpwuid(buf.st_uid);
499 printf("%s\t%s\t%c%s\t%ld\n",
501 pw ? pw->pw_name : "???",
503 (S_IXUSR & buf.st_mode) ? "":"(done)",
510 process_jobs(int argc, char **argv, int what)
512 /* Delete every argument (job - ID) given
517 struct dirent *dirent;
524 if (chdir(ATJOB_DIR) != 0)
525 perr("cannot change to " ATJOB_DIR);
527 if ((spool = opendir(".")) == NULL)
528 perr("cannot open " ATJOB_DIR);
532 /* Loop over every file in the directory
534 while((dirent = readdir(spool)) != NULL) {
537 if (stat(dirent->d_name, &buf) != 0)
538 perr("cannot stat in " ATJOB_DIR);
541 if(sscanf(dirent->d_name, "%c%5lx%8lx", &queue, &jobno, &ctm)!=3)
544 for (i=optind; i < argc; i++) {
545 if (atoi(argv[i]) == jobno) {
546 if ((buf.st_uid != real_uid) && !(real_uid == 0))
547 errx(EXIT_FAILURE, "%s: not owner", argv[i]);
553 if (unlink(dirent->d_name) != 0)
554 perr(dirent->d_name);
567 fp = fopen(dirent->d_name,"r");
572 perr("cannot open file");
574 while((ch = getc(fp)) != EOF) {
581 errx(EXIT_FAILURE, "internal error, process_jobs = %d",
590 main(int argc, char **argv)
593 char queue = DEFAULT_AT_QUEUE;
597 enum { ATQ, ATRM, AT, BATCH, CAT }; /* what program we want to run */
598 int program = AT; /* our default program */
599 char *options = "q:f:mvldbVc"; /* default options for at */
600 int disp_version = 0;
605 /* Eat any leading paths
607 if ((pgm = strrchr(argv[0], '/')) == NULL)
612 /* find out what this program is supposed to do
614 if (strcmp(pgm, "atq") == 0) {
618 else if (strcmp(pgm, "atrm") == 0) {
622 else if (strcmp(pgm, "batch") == 0) {
627 /* process whatever options we can process
630 while ((c=getopt(argc, argv, options)) != -1)
632 case 'v': /* verify time settings */
636 case 'm': /* send mail when job is complete */
644 case 'q': /* specify queue */
645 if (strlen(optarg) > 1)
648 atqueue = queue = *optarg;
649 if (!(islower(queue)||isupper(queue)))
692 /* end of options eating
696 fprintf(stderr, "at version " VERSION "\n"
697 "Bug reports to: ig25@rz.uni-karlsruhe.de (Thomas Koenig)\n");
699 /* select our program
701 if(!check_permission())
702 errx(EXIT_FAILURE, "you do not have permission to use this program");
706 REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
713 REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
715 process_jobs(argc, argv, ATRM);
720 process_jobs(argc, argv, CAT);
724 timer = parsetime(argc, argv);
727 struct tm *tm = localtime(&timer);
728 fprintf(stderr, "%s\n", asctime(tm));
730 writefile(timer, queue);
735 queue = toupper(queue);
737 queue = DEFAULT_BATCH_QUEUE;
740 timer = parsetime(argc, argv);
746 struct tm *tm = localtime(&timer);
747 fprintf(stderr, "%s\n", asctime(tm));
750 writefile(timer, queue);
754 panic("internal error");