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