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