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