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