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