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