1 /* $NetBSD: at.c,v 1.28 2010/11/24 17:40:41 christos 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.28 2010/11/24 17:40:41 christos 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 (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 (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 (void)closedir(spool); 488 PRIV_END; 489 } 490 491 static void 492 process_jobs(int argc, char **argv, int what) 493 { 494 /* Delete every argument (job - ID) given */ 495 int i; 496 struct stat buf; 497 DIR *spool; 498 struct dirent *dirent; 499 unsigned long ctm; 500 unsigned char queue; 501 int jobno; 502 503 PRIV_START; 504 505 if (chdir(_PATH_ATJOBS) == -1) 506 perr("Cannot change to " _PATH_ATJOBS); 507 508 if ((spool = opendir(".")) == NULL) 509 perr("Cannot open " _PATH_ATJOBS); 510 511 PRIV_END; 512 513 /* Loop over every file in the directory */ 514 while((dirent = readdir(spool)) != NULL) { 515 516 PRIV_START; 517 if (stat(dirent->d_name, &buf) == -1) 518 perr("Cannot stat in " _PATH_ATJOBS); 519 PRIV_END; 520 521 if (sscanf(dirent->d_name, "%c%5x%8lx", &queue, &jobno, &ctm) !=3) 522 continue; 523 524 for (i = optind; i < argc; i++) { 525 if (atoi(argv[i]) == jobno) { 526 if (buf.st_uid != real_uid && real_uid != 0) 527 errx(EXIT_FAILURE, 528 "%s: Not owner", argv[i]); 529 530 switch (what) { 531 case ATRM: 532 PRIV_START; 533 534 if (unlink(dirent->d_name) == -1) 535 perr(dirent->d_name); 536 537 PRIV_END; 538 break; 539 540 case CAT: { 541 FILE *fp; 542 int ch; 543 544 PRIV_START; 545 546 fp = fopen(dirent->d_name, "r"); 547 548 PRIV_END; 549 550 if (!fp) 551 perr("Cannot open file"); 552 else { 553 while((ch = getc(fp)) != EOF) 554 (void)putchar(ch); 555 (void)fclose(fp); 556 } 557 } 558 break; 559 560 default: 561 errx(EXIT_FAILURE, 562 "Internal error, process_jobs = %d", 563 what); 564 break; 565 } 566 } 567 } 568 } 569 (void)closedir(spool); 570 } 571 572 /* Global functions */ 573 574 int 575 main(int argc, char **argv) 576 { 577 int c; 578 unsigned char queue = DEFAULT_AT_QUEUE; 579 char queue_set = 0; 580 char time_set = 0; 581 char *pgm; 582 583 int program = AT; /* our default program */ 584 const char *options = "q:f:t:mvldbrVc"; /* default options for at */ 585 int disp_version = 0; 586 time_t timer; 587 588 RELINQUISH_PRIVS; 589 590 /* Eat any leading paths */ 591 if ((pgm = strrchr(argv[0], '/')) == NULL) 592 pgm = argv[0]; 593 else 594 pgm++; 595 596 /* find out what this program is supposed to do */ 597 if (strcmp(pgm, "atq") == 0) { 598 program = ATQ; 599 options = "q:vV"; 600 } else if (strcmp(pgm, "atrm") == 0) { 601 program = ATRM; 602 options = "V"; 603 } else if (strcmp(pgm, "batch") == 0) { 604 program = BATCH; 605 options = "f:q:t:mvV"; 606 } 607 608 /* process whatever options we can process */ 609 opterr = 1; 610 while ((c = getopt(argc, argv, options)) != -1) { 611 switch (c) { 612 case 'v': /* verify time settings */ 613 atverify = 1; 614 break; 615 616 case 'm': /* send mail when job is complete */ 617 send_mail = 1; 618 break; 619 620 case 'f': 621 atinput = optarg; 622 break; 623 624 case 'q': /* specify queue */ 625 if (strlen(optarg) > 1) 626 usage(); 627 628 atqueue = queue = *optarg; 629 if (!(islower(queue) || isupper(queue))) 630 usage(); 631 632 queue_set = 1; 633 break; 634 case 't': /* touch(1) date format */ 635 timer = stime(optarg); 636 time_set = 1; 637 break; 638 639 case 'd': 640 case 'r': 641 if (program != AT) 642 usage(); 643 644 program = ATRM; 645 options = "V"; 646 break; 647 648 case 'l': 649 if (program != AT) 650 usage(); 651 652 program = ATQ; 653 options = "q:vV"; 654 break; 655 656 case 'b': 657 if (program != AT) 658 usage(); 659 660 program = BATCH; 661 options = "f:q:mvV"; 662 break; 663 664 case 'V': 665 disp_version = 1; 666 break; 667 668 case 'c': 669 program = CAT; 670 options = ""; 671 break; 672 673 default: 674 usage(); 675 break; 676 } 677 } /* end of options eating */ 678 679 if (disp_version) 680 (void)fprintf(stderr, "%s version %.1f\n", pgm, AT_VERSION); 681 682 if (!check_permission()) 683 errx(EXIT_FAILURE, 684 "You do not have permission to use %s.", pgm); 685 686 /* select our program */ 687 switch (program) { 688 case ATQ: 689 if (optind != argc) 690 usage(); 691 list_jobs(); 692 break; 693 694 case ATRM: 695 case CAT: 696 if (optind == argc) 697 usage(); 698 process_jobs(argc, argv, program); 699 break; 700 701 case AT: 702 if (argc > optind) { 703 /* -t and timespec argument are mutually exclusive */ 704 if (time_set) { 705 usage(); 706 exit(EXIT_FAILURE); 707 } else { 708 timer = parsetime(argc, argv); 709 time_set = 1; 710 } 711 } 712 713 if (atverify) { 714 struct tm *tm = localtime(&timer); 715 (void)fprintf(stderr, "%s\n", asctime(tm)); 716 } 717 writefile(timer, queue); 718 break; 719 720 case BATCH: 721 if (queue_set) 722 queue = toupper(queue); 723 else 724 queue = DEFAULT_BATCH_QUEUE; 725 726 if (argc > optind) { 727 /* -t and timespec argument are mutually exclusive */ 728 if (time_set) { 729 usage(); 730 exit(EXIT_FAILURE); 731 } else { 732 timer = parsetime(argc, argv); 733 time_set = 1; 734 } 735 } else if (!time_set) 736 timer = time(NULL); 737 738 if (atverify) { 739 struct tm *tm = localtime(&timer); 740 (void)fprintf(stderr, "%s\n", asctime(tm)); 741 } 742 743 writefile(timer, queue); 744 break; 745 746 default: 747 panic("Internal error"); 748 break; 749 } 750 return EXIT_SUCCESS; 751 } 752