xref: /freebsd/usr.bin/at/at.c (revision 953a3198a35204535cc9d450f04da982a4fea59b)
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 #define _USE_BSD 1
30 
31 /* System Headers */
32 
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <sys/wait.h>
36 #include <ctype.h>
37 #include <dirent.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <pwd.h>
41 #include <signal.h>
42 #include <stddef.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <time.h>
47 #include <unistd.h>
48 #ifndef __FreeBSD__
49 #include <getopt.h>
50 #endif
51 
52 /* Local headers */
53 
54 #include "at.h"
55 #include "panic.h"
56 #include "parsetime.h"
57 #include "perm.h"
58 
59 #define MAIN
60 #include "privs.h"
61 
62 /* Macros */
63 
64 #ifndef ATJOB_DIR
65 #define ATJOB_DIR "/usr/spool/atjobs/"
66 #endif
67 
68 #ifndef LFILE
69 #define LFILE ATJOB_DIR ".lockfile"
70 #endif
71 
72 #ifndef ATJOB_MX
73 #define ATJOB_MX 255
74 #endif
75 
76 #define ALARMC 10 /* Number of seconds to wait for timeout */
77 
78 #define SIZE 255
79 #define TIMESIZE 50
80 
81 enum { ATQ, ATRM, AT, BATCH, CAT };	/* what program we want to run */
82 
83 /* File scope variables */
84 
85 static char rcsid[] = "$Id: at.c,v 1.3 1995/08/08 15:24:51 ig25 Exp $";
86 char *no_export[] =
87 {
88     "TERM", "TERMCAP", "DISPLAY", "_"
89 } ;
90 static send_mail = 0;
91 
92 /* External variables */
93 
94 extern char **environ;
95 int fcreated;
96 char *namep;
97 char atfile[] = ATJOB_DIR "12345678901234";
98 
99 char *atinput = (char*)0;	/* where to get input from */
100 char atqueue = 0;		/* which queue to examine for jobs (atq) */
101 char atverify = 0;		/* verify time instead of queuing job */
102 
103 /* Function declarations */
104 
105 static void sigc(int signo);
106 static void alarmc(int signo);
107 static char *cwdname(void);
108 static void writefile(time_t runtimer, char queue);
109 static void list_jobs(void);
110 
111 /* Signal catching functions */
112 
113 static void sigc(int signo)
114 {
115 /* If the user presses ^C, remove the spool file and exit
116  */
117     if (fcreated)
118     {
119 	PRIV_START
120 	    unlink(atfile);
121 	PRIV_END
122     }
123 
124     exit(EXIT_FAILURE);
125 }
126 
127 static void alarmc(int signo)
128 {
129 /* Time out after some seconds
130  */
131     panic("File locking timed out");
132 }
133 
134 /* Local functions */
135 
136 static char *cwdname(void)
137 {
138 /* Read in the current directory; the name will be overwritten on
139  * subsequent calls.
140  */
141     static char *ptr = NULL;
142     static size_t size = SIZE;
143 
144     if (ptr == NULL)
145 	ptr = (char *) mymalloc(size);
146 
147     while (1)
148     {
149 	if (ptr == NULL)
150 	    panic("Out of memory");
151 
152 	if (getcwd(ptr, size-1) != NULL)
153 	    return ptr;
154 
155 	if (errno != ERANGE)
156 	    perr("Cannot get directory");
157 
158 	free (ptr);
159 	size += SIZE;
160 	ptr = (char *) mymalloc(size);
161     }
162 }
163 
164 static long
165 nextjob()
166 {
167     long jobno;
168     FILE *fid;
169 
170     if ((fid = fopen(ATJOB_DIR ".SEQ", "r+")) != (FILE*)0) {
171 	if (fscanf(fid, "%5lx", &jobno) == 1) {
172 	    rewind(fid);
173 	    jobno = (1+jobno) % 0xfffff;	/* 2^20 jobs enough? */
174 	    fprintf(fid, "%05lx\n", jobno);
175 	}
176 	else
177 	    jobno = EOF;
178 	fclose(fid);
179 	return jobno;
180     }
181     else if ((fid = fopen(ATJOB_DIR ".SEQ", "w")) != (FILE*)0) {
182 	fprintf(fid, "%05lx\n", jobno = 1);
183 	fclose(fid);
184 	return 1;
185     }
186     return EOF;
187 }
188 
189 static void
190 writefile(time_t runtimer, char queue)
191 {
192 /* This does most of the work if at or batch are invoked for writing a job.
193  */
194     long jobno;
195     char *ap, *ppos, *mailname;
196     struct passwd *pass_entry;
197     struct stat statbuf;
198     int fdes, lockdes, fd2;
199     FILE *fp, *fpin;
200     struct sigaction act;
201     char **atenv;
202     int ch;
203     mode_t cmask;
204     struct flock lock;
205 
206 /* Install the signal handler for SIGINT; terminate after removing the
207  * spool file if necessary
208  */
209     act.sa_handler = sigc;
210     sigemptyset(&(act.sa_mask));
211     act.sa_flags = 0;
212 
213     sigaction(SIGINT, &act, NULL);
214 
215     ppos = atfile + strlen(ATJOB_DIR);
216 
217     /* Loop over all possible file names for running something at this
218      * particular time, see if a file is there; the first empty slot at any
219      * particular time is used.  Lock the file LFILE first to make sure
220      * we're alone when doing this.
221      */
222 
223     PRIV_START
224 
225     if ((lockdes = open(LFILE, O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR)) < 0)
226 	perr("Cannot open lockfile " LFILE);
227 
228     lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0;
229     lock.l_len = 0;
230 
231     act.sa_handler = alarmc;
232     sigemptyset(&(act.sa_mask));
233     act.sa_flags = 0;
234 
235     /* Set an alarm so a timeout occurs after ALARMC seconds, in case
236      * something is seriously broken.
237      */
238     sigaction(SIGALRM, &act, NULL);
239     alarm(ALARMC);
240     fcntl(lockdes, F_SETLKW, &lock);
241     alarm(0);
242 
243     if ((jobno = nextjob()) == EOF)
244 	perr("Cannot generate job number");
245 
246     sprintf(ppos, "%c%5lx%8lx", queue,
247 	    jobno, (unsigned long) (runtimer/60));
248 
249     for(ap=ppos; *ap != '\0'; ap ++)
250 	if (*ap == ' ')
251 	    *ap = '0';
252 
253     if (stat(atfile, &statbuf) != 0)
254 	if (errno != ENOENT)
255 	    perr("Cannot access " ATJOB_DIR);
256 
257     /* Create the file. The x bit is only going to be set after it has
258      * been completely written out, to make sure it is not executed in the
259      * meantime.  To make sure they do not get deleted, turn off their r
260      * bit.  Yes, this is a kluge.
261      */
262     cmask = umask(S_IRUSR | S_IWUSR | S_IXUSR);
263     if ((fdes = creat(atfile, O_WRONLY)) == -1)
264 	perr("Cannot create atjob file");
265 
266     if ((fd2 = dup(fdes)) <0)
267 	perr("Error in dup() of job file");
268 
269     if(fchown(fd2, real_uid, real_gid) != 0)
270 	perr("Cannot give away file");
271 
272     PRIV_END
273 
274     /* We no longer need suid root; now we just need to be able to write
275      * to the directory, if necessary.
276      */
277 
278     REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
279 
280     /* We've successfully created the file; let's set the flag so it
281      * gets removed in case of an interrupt or error.
282      */
283     fcreated = 1;
284 
285     /* Now we can release the lock, so other people can access it
286      */
287     lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = 0;
288     lock.l_len = 0;
289     fcntl(lockdes, F_SETLKW, &lock);
290     close(lockdes);
291 
292     if((fp = fdopen(fdes, "w")) == NULL)
293 	panic("Cannot reopen atjob file");
294 
295     /* Get the userid to mail to, first by trying getlogin(), which reads
296      * /etc/utmp, then from LOGNAME, finally from getpwuid().
297      */
298     mailname = getlogin();
299     if (mailname == NULL)
300 	mailname = getenv("LOGNAME");
301 
302     if ((mailname == NULL) || (mailname[0] == '\0')
303 	|| (strlen(mailname) > 8) || (getpwnam(mailname)==NULL))
304     {
305 	pass_entry = getpwuid(real_uid);
306 	if (pass_entry != NULL)
307 	    mailname = pass_entry->pw_name;
308     }
309 
310     if (atinput != (char *) NULL)
311     {
312 	fpin = freopen(atinput, "r", stdin);
313 	if (fpin == NULL)
314 	    perr("Cannot open input file");
315     }
316     fprintf(fp, "#!/bin/sh\n# atrun uid=%ld gid=%ld\n# mail %8s %d\n",
317 	(long) real_uid, (long) real_gid, mailname, send_mail);
318 
319     /* Write out the umask at the time of invocation
320      */
321     fprintf(fp, "umask %lo\n", (unsigned long) cmask);
322 
323     /* Write out the environment. Anything that may look like a
324      * special character to the shell is quoted, except for \n, which is
325      * done with a pair of "'s.  Dont't export the no_export list (such
326      * as TERM or DISPLAY) because we don't want these.
327      */
328     for (atenv= environ; *atenv != NULL; atenv++)
329     {
330 	int export = 1;
331 	char *eqp;
332 
333 	eqp = strchr(*atenv, '=');
334 	if (ap == NULL)
335 	    eqp = *atenv;
336 	else
337 	{
338 	    int i;
339 	    for (i=0; i<sizeof(no_export)/sizeof(no_export[0]); i++)
340 	    {
341 		export = export
342 		    && (strncmp(*atenv, no_export[i],
343 				(size_t) (eqp-*atenv)) != 0);
344 	    }
345 	    eqp++;
346 	}
347 
348 	if (export)
349 	{
350 	    fwrite(*atenv, sizeof(char), eqp-*atenv, fp);
351 	    for(ap = eqp;*ap != '\0'; ap++)
352 	    {
353 		if (*ap == '\n')
354 		    fprintf(fp, "\"\n\"");
355 		else
356 		{
357 		    if (!isalnum(*ap)) {
358 			switch (*ap) {
359 			  case '%': case '/': case '{': case '[':
360 			  case ']': case '=': case '}': case '@':
361 			  case '+': case '#': case ',': case '.':
362 			  case ':': case '-': case '_':
363 			    break;
364 			  default:
365 			    fputc('\\', fp);
366 			    break;
367 			}
368 		    }
369 		    fputc(*ap, fp);
370 		}
371 	    }
372 	    fputs("; export ", fp);
373 	    fwrite(*atenv, sizeof(char), eqp-*atenv -1, fp);
374 	    fputc('\n', fp);
375 
376 	}
377     }
378     /* Cd to the directory at the time and write out all the
379      * commands the user supplies from stdin.
380      */
381     fprintf(fp, "cd ");
382     for (ap = cwdname(); *ap != '\0'; ap++)
383     {
384 	if (*ap == '\n')
385 	    fprintf(fp, "\"\n\"");
386 	else
387 	{
388 	    if (*ap != '/' && !isalnum(*ap))
389 		fputc('\\', fp);
390 
391 	    fputc(*ap, fp);
392 	}
393     }
394     /* Test cd's exit status: die if the original directory has been
395      * removed, become unreadable or whatever
396      */
397     fprintf(fp, " || {\n\t echo 'Execution directory "
398 	        "inaccessible' >&2\n\t exit 1\n}\n");
399 
400     while((ch = getchar()) != EOF)
401 	fputc(ch, fp);
402 
403     fprintf(fp, "\n");
404     if (ferror(fp))
405 	panic("Output error");
406 
407     if (ferror(stdin))
408 	panic("Input error");
409 
410     fclose(fp);
411 
412     /* Set the x bit so that we're ready to start executing
413      */
414 
415     if (fchmod(fd2, S_IRUSR | S_IWUSR | S_IXUSR) < 0)
416 	perr("Cannot give away file");
417 
418     close(fd2);
419     fprintf(stderr, "Job %ld will be executed using /bin/sh\n", jobno);
420 }
421 
422 static void
423 list_jobs()
424 {
425     /* List all a user's jobs in the queue, by looping through ATJOB_DIR,
426      * or everybody's if we are root
427      */
428     struct passwd *pw;
429     DIR *spool;
430     struct dirent *dirent;
431     struct stat buf;
432     struct tm runtime;
433     unsigned long ctm;
434     char queue;
435     long jobno;
436     time_t runtimer;
437     char timestr[TIMESIZE];
438     int first=1;
439 
440     PRIV_START
441 
442     if (chdir(ATJOB_DIR) != 0)
443 	perr("Cannot change to " ATJOB_DIR);
444 
445     if ((spool = opendir(".")) == NULL)
446 	perr("Cannot open " ATJOB_DIR);
447 
448     /*	Loop over every file in the directory
449      */
450     while((dirent = readdir(spool)) != NULL) {
451 	if (stat(dirent->d_name, &buf) != 0)
452 	    perr("Cannot stat in " ATJOB_DIR);
453 
454 	/* See it's a regular file and has its x bit turned on and
455          * is the user's
456          */
457 	if (!S_ISREG(buf.st_mode)
458 	    || ((buf.st_uid != real_uid) && ! (real_uid == 0))
459 	    || !(S_IXUSR & buf.st_mode || atverify))
460 	    continue;
461 
462 	if(sscanf(dirent->d_name, "%c%5lx%8lx", &queue, &jobno, &ctm)!=3)
463 	    continue;
464 
465 	if (atqueue && (queue != atqueue))
466 	    continue;
467 
468 	runtimer = 60*(time_t) ctm;
469 	runtime = *localtime(&runtimer);
470 	strftime(timestr, TIMESIZE, "%X %x", &runtime);
471 	if (first) {
472 	    printf("Date\t\t\tOwner\tQueue\tJob#\n");
473 	    first=0;
474 	}
475 	pw = getpwuid(buf.st_uid);
476 
477 	printf("%s\t%s\t%c%s\t%ld\n",
478 	       timestr,
479 	       pw ? pw->pw_name : "???",
480 	       queue,
481 	       (S_IXUSR & buf.st_mode) ? "":"(done)",
482 	       jobno);
483     }
484     PRIV_END
485 }
486 
487 static void
488 process_jobs(int argc, char **argv, int what)
489 {
490     /* Delete every argument (job - ID) given
491      */
492     int i;
493     struct stat buf;
494     DIR *spool;
495     struct dirent *dirent;
496     unsigned long ctm;
497     char queue;
498     long jobno;
499 
500     PRIV_START
501 
502     if (chdir(ATJOB_DIR) != 0)
503 	perr("Cannot change to " ATJOB_DIR);
504 
505     if ((spool = opendir(".")) == NULL)
506 	perr("Cannot open " ATJOB_DIR);
507 
508     PRIV_END
509 
510     /*	Loop over every file in the directory
511      */
512     while((dirent = readdir(spool)) != NULL) {
513 
514 	PRIV_START
515 	if (stat(dirent->d_name, &buf) != 0)
516 	    perr("Cannot stat in " ATJOB_DIR);
517 	PRIV_END
518 
519 	if(sscanf(dirent->d_name, "%c%5lx%8lx", &queue, &jobno, &ctm)!=3)
520 	    continue;
521 
522 	for (i=optind; i < argc; i++) {
523 	    if (atoi(argv[i]) == jobno) {
524 		if ((buf.st_uid != real_uid) && !(real_uid == 0)) {
525 		    fprintf(stderr, "%s: Not owner\n", argv[i]);
526 		    exit(EXIT_FAILURE);
527 		}
528 		switch (what) {
529 		  case ATRM:
530 
531 		    PRIV_START
532 
533 		    if (unlink(dirent->d_name) != 0)
534 		        perr(dirent->d_name);
535 
536 		    PRIV_END
537 
538 		    break;
539 
540 		  case CAT:
541 		    {
542 			FILE *fp;
543 			int ch;
544 
545 			PRIV_START
546 
547 			fp = fopen(dirent->d_name,"r");
548 
549 			PRIV_END
550 
551 			if (!fp) {
552 			    perr("Cannot open file");
553 			}
554 			while((ch = getc(fp)) != EOF) {
555 			    putchar(ch);
556 			}
557 		    }
558 		    break;
559 
560 		  default:
561 		    fprintf(stderr,
562 			    "Internal error, process_jobs = %d\n",what);
563 		    exit(EXIT_FAILURE);
564 		    break;
565 	        }
566 	    }
567 	}
568     }
569 } /* delete_jobs */
570 
571 /* Global functions */
572 
573 void *
574 mymalloc(size_t n)
575 {
576     void *p;
577     if ((p=malloc(n))==(void *)0)
578     {
579 	fprintf(stderr,"Virtual memory exhausted\n");
580 	exit(EXIT_FAILURE);
581     }
582     return p;
583 }
584 
585 int
586 main(int argc, char **argv)
587 {
588     int c;
589     char queue = DEFAULT_AT_QUEUE;
590     char queue_set = 0;
591     char *pgm;
592 
593     enum { ATQ, ATRM, AT, BATCH, CAT };	/* what program we want to run */
594     int program = AT;			/* our default program */
595     char *options = "q:f:mvldbVc";	/* default options for at */
596     int disp_version = 0;
597     time_t timer;
598 
599     RELINQUISH_PRIVS
600 
601     /* Eat any leading paths
602      */
603     if ((pgm = strrchr(argv[0], '/')) == NULL)
604 	pgm = argv[0];
605     else
606         pgm++;
607 
608     namep = pgm;
609 
610     /* find out what this program is supposed to do
611      */
612     if (strcmp(pgm, "atq") == 0) {
613 	program = ATQ;
614 	options = "q:vV";
615     }
616     else if (strcmp(pgm, "atrm") == 0) {
617 	program = ATRM;
618 	options = "V";
619     }
620     else if (strcmp(pgm, "batch") == 0) {
621 	program = BATCH;
622 	options = "f:q:mvV";
623     }
624 
625     /* process whatever options we can process
626      */
627     opterr=1;
628     while ((c=getopt(argc, argv, options)) != EOF)
629 	switch (c) {
630 	case 'v':   /* verify time settings */
631 	    atverify = 1;
632 	    break;
633 
634 	case 'm':   /* send mail when job is complete */
635 	    send_mail = 1;
636 	    break;
637 
638 	case 'f':
639 	    atinput = optarg;
640 	    break;
641 
642 	case 'q':    /* specify queue */
643 	    if (strlen(optarg) > 1)
644 		usage();
645 
646 	    atqueue = queue = *optarg;
647 	    if (!(islower(queue)||isupper(queue)))
648 		usage();
649 
650 	    queue_set = 1;
651 	    break;
652 
653 	case 'd':
654 	    if (program != AT)
655 		usage();
656 
657 	    program = ATRM;
658 	    options = "V";
659 	    break;
660 
661 	case 'l':
662 	    if (program != AT)
663 		usage();
664 
665 	    program = ATQ;
666 	    options = "q:vV";
667 	    break;
668 
669 	case 'b':
670 	    if (program != AT)
671 		usage();
672 
673 	    program = BATCH;
674 	    options = "f:q:mvV";
675 	    break;
676 
677 	case 'V':
678 	    disp_version = 1;
679 	    break;
680 
681 	case 'c':
682 	    program = CAT;
683 	    options = "";
684 	    break;
685 
686 	default:
687 	    usage();
688 	    break;
689 	}
690     /* end of options eating
691      */
692 
693     if (disp_version)
694 	fprintf(stderr, "at version " VERSION "\n"
695 			"Bug reports to: ig25@rz.uni-karlsruhe.de (Thomas Koenig)\n");
696 
697     /* select our program
698      */
699     if(!check_permission())
700     {
701 	fprintf(stderr, "You do not have permission to use %s.\n",namep);
702 	exit(EXIT_FAILURE);
703     }
704     switch (program) {
705     case ATQ:
706 
707 	REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
708 
709 	list_jobs();
710 	break;
711 
712     case ATRM:
713 
714 	REDUCE_PRIV(DAEMON_UID, DAEMON_GID)
715 
716 	process_jobs(argc, argv, ATRM);
717 	break;
718 
719     case CAT:
720 
721 	process_jobs(argc, argv, CAT);
722 	break;
723 
724     case AT:
725 	timer = parsetime(argc, argv);
726 	if (atverify)
727 	{
728 	    struct tm *tm = localtime(&timer);
729 	    fprintf(stderr, "%s\n", asctime(tm));
730 	}
731 	writefile(timer, queue);
732 	break;
733 
734     case BATCH:
735 	if (queue_set)
736 	    queue = toupper(queue);
737 	else
738 	    queue = DEFAULT_BATCH_QUEUE;
739 
740 	if (argc > optind)
741 	    timer = parsetime(argc, argv);
742 	else
743 	    timer = time(NULL);
744 
745 	if (atverify)
746 	{
747 	    struct tm *tm = localtime(&timer);
748 	    fprintf(stderr, "%s\n", asctime(tm));
749 	}
750 
751         writefile(timer, queue);
752 	break;
753 
754     default:
755 	panic("Internal error");
756 	break;
757     }
758     exit(EXIT_SUCCESS);
759 }
760