1 /* $NetBSD: at.c,v 1.27 2009/01/18 01:02:41 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 <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.27 2009/01/18 01:02:41 lukem 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 static void sigc (int); 95 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 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 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 (void)strftime(timestr, TIMESIZE, "%X %x", &runtime); 470 if (first) { 471 (void)printf("%-*s %-*s %-*s %s\n", 472 (int)strlen(timestr), "Date", 473 LOGIN_NAME_MAX, "Owner", 474 7, "Queue", 475 "Job"); 476 first = 0; 477 } 478 pw = getpwuid(buf.st_uid); 479 480 (void)printf("%s %-*s %c%-*s %d\n", 481 timestr, 482 LOGIN_NAME_MAX, pw ? pw->pw_name : "???", 483 queue, 484 6, (S_IXUSR & buf.st_mode) ? "" : "(done)", 485 jobno); 486 } 487 PRIV_END; 488 } 489 490 static void 491 process_jobs(int argc, char **argv, int what) 492 { 493 /* Delete every argument (job - ID) given */ 494 int i; 495 struct stat buf; 496 DIR *spool; 497 struct dirent *dirent; 498 unsigned long ctm; 499 unsigned char queue; 500 int jobno; 501 502 PRIV_START; 503 504 if (chdir(_PATH_ATJOBS) == -1) 505 perr("Cannot change to " _PATH_ATJOBS); 506 507 if ((spool = opendir(".")) == NULL) 508 perr("Cannot open " _PATH_ATJOBS); 509 510 PRIV_END; 511 512 /* Loop over every file in the directory */ 513 while((dirent = readdir(spool)) != NULL) { 514 515 PRIV_START; 516 if (stat(dirent->d_name, &buf) == -1) 517 perr("Cannot stat in " _PATH_ATJOBS); 518 PRIV_END; 519 520 if (sscanf(dirent->d_name, "%c%5x%8lx", &queue, &jobno, &ctm) !=3) 521 continue; 522 523 for (i = optind; i < argc; i++) { 524 if (atoi(argv[i]) == jobno) { 525 if (buf.st_uid != real_uid && real_uid != 0) 526 errx(EXIT_FAILURE, 527 "%s: Not owner", argv[i]); 528 529 switch (what) { 530 case ATRM: 531 PRIV_START; 532 533 if (unlink(dirent->d_name) == -1) 534 perr(dirent->d_name); 535 536 PRIV_END; 537 break; 538 539 case CAT: { 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 else { 552 while((ch = getc(fp)) != EOF) 553 (void)putchar(ch); 554 (void)fclose(fp); 555 } 556 } 557 break; 558 559 default: 560 errx(EXIT_FAILURE, 561 "Internal error, process_jobs = %d", 562 what); 563 break; 564 } 565 } 566 } 567 } 568 } 569 570 /* Global functions */ 571 572 int 573 main(int argc, char **argv) 574 { 575 int c; 576 unsigned char queue = DEFAULT_AT_QUEUE; 577 char queue_set = 0; 578 char time_set = 0; 579 char *pgm; 580 581 int program = AT; /* our default program */ 582 const char *options = "q:f:t:mvldbrVc"; /* default options for at */ 583 int disp_version = 0; 584 time_t timer; 585 586 RELINQUISH_PRIVS; 587 588 /* Eat any leading paths */ 589 if ((pgm = strrchr(argv[0], '/')) == NULL) 590 pgm = argv[0]; 591 else 592 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:t: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 case 't': /* touch(1) date format */ 633 timer = stime(optarg); 634 time_set = 1; 635 break; 636 637 case 'd': 638 case 'r': 639 if (program != AT) 640 usage(); 641 642 program = ATRM; 643 options = "V"; 644 break; 645 646 case 'l': 647 if (program != AT) 648 usage(); 649 650 program = ATQ; 651 options = "q:vV"; 652 break; 653 654 case 'b': 655 if (program != AT) 656 usage(); 657 658 program = BATCH; 659 options = "f:q:mvV"; 660 break; 661 662 case 'V': 663 disp_version = 1; 664 break; 665 666 case 'c': 667 program = CAT; 668 options = ""; 669 break; 670 671 default: 672 usage(); 673 break; 674 } 675 } /* end of options eating */ 676 677 if (disp_version) 678 (void)fprintf(stderr, "%s version %.1f\n", pgm, AT_VERSION); 679 680 if (!check_permission()) 681 errx(EXIT_FAILURE, 682 "You do not have permission to use %s.", pgm); 683 684 /* select our program */ 685 switch (program) { 686 case ATQ: 687 if (optind != argc) 688 usage(); 689 list_jobs(); 690 break; 691 692 case ATRM: 693 case CAT: 694 if (optind == argc) 695 usage(); 696 process_jobs(argc, argv, program); 697 break; 698 699 case AT: 700 if (argc > optind) { 701 /* -t and timespec argument are mutually exclusive */ 702 if (time_set) { 703 usage(); 704 exit(EXIT_FAILURE); 705 } else { 706 timer = parsetime(argc, argv); 707 time_set = 1; 708 } 709 } 710 711 if (atverify) { 712 struct tm *tm = localtime(&timer); 713 (void)fprintf(stderr, "%s\n", asctime(tm)); 714 } 715 writefile(timer, queue); 716 break; 717 718 case BATCH: 719 if (queue_set) 720 queue = toupper(queue); 721 else 722 queue = DEFAULT_BATCH_QUEUE; 723 724 if (argc > optind) { 725 /* -t and timespec argument are mutually exclusive */ 726 if (time_set) { 727 usage(); 728 exit(EXIT_FAILURE); 729 } else { 730 timer = parsetime(argc, argv); 731 time_set = 1; 732 } 733 } else if (!time_set) 734 timer = time(NULL); 735 736 if (atverify) { 737 struct tm *tm = localtime(&timer); 738 (void)fprintf(stderr, "%s\n", asctime(tm)); 739 } 740 741 writefile(timer, queue); 742 break; 743 744 default: 745 panic("Internal error"); 746 break; 747 } 748 return EXIT_SUCCESS; 749 } 750