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