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