1 /* Copyright 1988,1990,1993,1994 by Paul Vixie 2 * All rights reserved 3 * 4 * Distribute freely, except: don't remove my name from the source or 5 * documentation (don't take credit for my work), mark your changes (don't 6 * get me blamed for your possible bugs), don't alter or remove this 7 * notice. May be sold if buildable source is provided to buyer. No 8 * warrantee of any kind, express or implied, is included with this 9 * software; use at your own risk, responsibility for damages (if any) to 10 * anyone resulting from the use of this software rests entirely with the 11 * user. 12 * 13 * Send bug reports, bug fixes, enhancements, requests, flames, etc., and 14 * I'll try to keep a version up to date. I can be reached as follows: 15 * Paul Vixie <paul@vix.com> uunet!decwrl!vixie!paul 16 * From Id: crontab.c,v 2.13 1994/01/17 03:20:37 vixie Exp 17 */ 18 19 #if !defined(lint) && !defined(LINT) 20 static const char rcsid[] = 21 "$FreeBSD$"; 22 #endif 23 24 /* crontab - install and manage per-user crontab files 25 * vix 02may87 [RCS has the rest of the log] 26 * vix 26jan87 [original] 27 */ 28 29 #define MAIN_PROGRAM 30 31 #include "cron.h" 32 #include <errno.h> 33 #include <fcntl.h> 34 #include <md5.h> 35 #include <paths.h> 36 #include <sys/file.h> 37 #include <sys/stat.h> 38 #ifdef USE_UTIMES 39 # include <sys/time.h> 40 #else 41 # include <time.h> 42 # include <utime.h> 43 #endif 44 #if defined(POSIX) 45 # include <locale.h> 46 #endif 47 48 #define MD5_SIZE 33 49 #define NHEADER_LINES 3 50 51 52 enum opt_t { opt_unknown, opt_list, opt_delete, opt_edit, opt_replace }; 53 54 #if DEBUGGING 55 static char *Options[] = { "???", "list", "delete", "edit", "replace" }; 56 #endif 57 58 59 static PID_T Pid; 60 static char User[MAX_UNAME], RealUser[MAX_UNAME]; 61 static char Filename[MAX_FNAME]; 62 static FILE *NewCrontab; 63 static int CheckErrorCount; 64 static enum opt_t Option; 65 static struct passwd *pw; 66 static void list_cmd __P((void)), 67 delete_cmd __P((void)), 68 edit_cmd __P((void)), 69 poke_daemon __P((void)), 70 check_error __P((char *)), 71 parse_args __P((int c, char *v[])); 72 static int replace_cmd __P((void)); 73 74 75 static void 76 usage(msg) 77 char *msg; 78 { 79 fprintf(stderr, "crontab: usage error: %s\n", msg); 80 fprintf(stderr, "%s\n%s\n", 81 "usage: crontab [-u user] file", 82 " crontab [-u user] { -e | -l | -r }"); 83 exit(ERROR_EXIT); 84 } 85 86 87 int 88 main(argc, argv) 89 int argc; 90 char *argv[]; 91 { 92 int exitstatus; 93 94 Pid = getpid(); 95 ProgramName = argv[0]; 96 97 #if defined(POSIX) 98 setlocale(LC_ALL, ""); 99 #endif 100 101 #if defined(BSD) 102 setlinebuf(stderr); 103 #endif 104 parse_args(argc, argv); /* sets many globals, opens a file */ 105 set_cron_uid(); 106 set_cron_cwd(); 107 if (!allowed(User)) { 108 warnx("you (%s) are not allowed to use this program", User); 109 log_it(RealUser, Pid, "AUTH", "crontab command not allowed"); 110 exit(ERROR_EXIT); 111 } 112 exitstatus = OK_EXIT; 113 switch (Option) { 114 case opt_list: list_cmd(); 115 break; 116 case opt_delete: delete_cmd(); 117 break; 118 case opt_edit: edit_cmd(); 119 break; 120 case opt_replace: if (replace_cmd() < 0) 121 exitstatus = ERROR_EXIT; 122 break; 123 case opt_unknown: 124 break; 125 } 126 exit(exitstatus); 127 /*NOTREACHED*/ 128 } 129 130 131 static void 132 parse_args(argc, argv) 133 int argc; 134 char *argv[]; 135 { 136 int argch; 137 138 if (!(pw = getpwuid(getuid()))) 139 errx(ERROR_EXIT, "your UID isn't in the passwd file, bailing out"); 140 (void) strncpy(User, pw->pw_name, (sizeof User)-1); 141 User[(sizeof User)-1] = '\0'; 142 strcpy(RealUser, User); 143 Filename[0] = '\0'; 144 Option = opt_unknown; 145 while ((argch = getopt(argc, argv, "u:lerx:")) != -1) { 146 switch (argch) { 147 case 'x': 148 if (!set_debug_flags(optarg)) 149 usage("bad debug option"); 150 break; 151 case 'u': 152 if (getuid() != ROOT_UID) 153 errx(ERROR_EXIT, "must be privileged to use -u"); 154 if (!(pw = getpwnam(optarg))) 155 errx(ERROR_EXIT, "user `%s' unknown", optarg); 156 (void) strncpy(User, pw->pw_name, (sizeof User)-1); 157 User[(sizeof User)-1] = '\0'; 158 break; 159 case 'l': 160 if (Option != opt_unknown) 161 usage("only one operation permitted"); 162 Option = opt_list; 163 break; 164 case 'r': 165 if (Option != opt_unknown) 166 usage("only one operation permitted"); 167 Option = opt_delete; 168 break; 169 case 'e': 170 if (Option != opt_unknown) 171 usage("only one operation permitted"); 172 Option = opt_edit; 173 break; 174 default: 175 usage("unrecognized option"); 176 } 177 } 178 179 endpwent(); 180 181 if (Option != opt_unknown) { 182 if (argv[optind] != NULL) { 183 usage("no arguments permitted after this option"); 184 } 185 } else { 186 if (argv[optind] != NULL) { 187 Option = opt_replace; 188 (void) strncpy (Filename, argv[optind], (sizeof Filename)-1); 189 Filename[(sizeof Filename)-1] = '\0'; 190 191 } else { 192 usage("file name must be specified for replace"); 193 } 194 } 195 196 if (Option == opt_replace) { 197 /* we have to open the file here because we're going to 198 * chdir(2) into /var/cron before we get around to 199 * reading the file. 200 */ 201 if (!strcmp(Filename, "-")) { 202 NewCrontab = stdin; 203 } else { 204 /* relinquish the setuid status of the binary during 205 * the open, lest nonroot users read files they should 206 * not be able to read. we can't use access() here 207 * since there's a race condition. thanks go out to 208 * Arnt Gulbrandsen <agulbra@pvv.unit.no> for spotting 209 * the race. 210 */ 211 212 if (swap_uids() < OK) 213 err(ERROR_EXIT, "swapping uids"); 214 if (!(NewCrontab = fopen(Filename, "r"))) 215 err(ERROR_EXIT, "%s", Filename); 216 if (swap_uids() < OK) 217 err(ERROR_EXIT, "swapping uids back"); 218 } 219 } 220 221 Debug(DMISC, ("user=%s, file=%s, option=%s\n", 222 User, Filename, Options[(int)Option])) 223 } 224 225 static void 226 copy_file(FILE *in, FILE *out) { 227 int x, ch; 228 229 Set_LineNum(1) 230 /* ignore the top few comments since we probably put them there. 231 */ 232 for (x = 0; x < NHEADER_LINES; x++) { 233 ch = get_char(in); 234 if (EOF == ch) 235 break; 236 if ('#' != ch) { 237 putc(ch, out); 238 break; 239 } 240 while (EOF != (ch = get_char(in))) 241 if (ch == '\n') 242 break; 243 if (EOF == ch) 244 break; 245 } 246 247 /* copy the rest of the crontab (if any) to the output file. 248 */ 249 if (EOF != ch) 250 while (EOF != (ch = get_char(in))) 251 putc(ch, out); 252 } 253 254 static void 255 list_cmd() { 256 char n[MAX_FNAME]; 257 FILE *f; 258 259 log_it(RealUser, Pid, "LIST", User); 260 (void) sprintf(n, CRON_TAB(User)); 261 if (!(f = fopen(n, "r"))) { 262 if (errno == ENOENT) 263 errx(ERROR_EXIT, "no crontab for %s", User); 264 else 265 err(ERROR_EXIT, "%s", n); 266 } 267 268 /* file is open. copy to stdout, close. 269 */ 270 copy_file(f, stdout); 271 fclose(f); 272 } 273 274 275 static void 276 delete_cmd() { 277 char n[MAX_FNAME]; 278 int ch, first; 279 280 if (isatty(STDIN_FILENO)) { 281 (void)fprintf(stderr, "remove crontab for %s? ", User); 282 first = ch = getchar(); 283 while (ch != '\n' && ch != EOF) 284 ch = getchar(); 285 if (first != 'y' && first != 'Y') 286 return; 287 } 288 289 log_it(RealUser, Pid, "DELETE", User); 290 (void) sprintf(n, CRON_TAB(User)); 291 if (unlink(n)) { 292 if (errno == ENOENT) 293 errx(ERROR_EXIT, "no crontab for %s", User); 294 else 295 err(ERROR_EXIT, "%s", n); 296 } 297 poke_daemon(); 298 } 299 300 301 static void 302 check_error(msg) 303 char *msg; 304 { 305 CheckErrorCount++; 306 fprintf(stderr, "\"%s\":%d: %s\n", Filename, LineNumber-1, msg); 307 } 308 309 310 static void 311 edit_cmd() { 312 char n[MAX_FNAME], q[MAX_TEMPSTR], *editor; 313 FILE *f; 314 int t; 315 struct stat statbuf, fsbuf; 316 WAIT_T waiter; 317 PID_T pid, xpid; 318 mode_t um; 319 int syntax_error = 0; 320 char orig_md5[MD5_SIZE]; 321 char new_md5[MD5_SIZE]; 322 323 log_it(RealUser, Pid, "BEGIN EDIT", User); 324 (void) sprintf(n, CRON_TAB(User)); 325 if (!(f = fopen(n, "r"))) { 326 if (errno != ENOENT) 327 err(ERROR_EXIT, "%s", n); 328 warnx("no crontab for %s - using an empty one", User); 329 if (!(f = fopen(_PATH_DEVNULL, "r"))) 330 err(ERROR_EXIT, _PATH_DEVNULL); 331 } 332 333 um = umask(077); 334 (void) sprintf(Filename, "/tmp/crontab.XXXXXXXXXX"); 335 if ((t = mkstemp(Filename)) == -1) { 336 warn("%s", Filename); 337 (void) umask(um); 338 goto fatal; 339 } 340 (void) umask(um); 341 #ifdef HAS_FCHOWN 342 if (fchown(t, getuid(), getgid()) < 0) { 343 #else 344 if (chown(Filename, getuid(), getgid()) < 0) { 345 #endif 346 warn("fchown"); 347 goto fatal; 348 } 349 if (!(NewCrontab = fdopen(t, "r+"))) { 350 warn("fdopen"); 351 goto fatal; 352 } 353 354 copy_file(f, NewCrontab); 355 fclose(f); 356 if (fflush(NewCrontab)) 357 err(ERROR_EXIT, "%s", Filename); 358 if (fstat(t, &fsbuf) < 0) { 359 warn("unable to fstat temp file"); 360 goto fatal; 361 } 362 again: 363 if (stat(Filename, &statbuf) < 0) { 364 warn("stat"); 365 fatal: unlink(Filename); 366 exit(ERROR_EXIT); 367 } 368 if (statbuf.st_dev != fsbuf.st_dev || statbuf.st_ino != fsbuf.st_ino) 369 errx(ERROR_EXIT, "temp file must be edited in place"); 370 if (MD5File(Filename, orig_md5) == NULL) { 371 warn("MD5"); 372 goto fatal; 373 } 374 375 if ((!(editor = getenv("VISUAL"))) 376 && (!(editor = getenv("EDITOR"))) 377 ) { 378 editor = EDITOR; 379 } 380 381 /* we still have the file open. editors will generally rewrite the 382 * original file rather than renaming/unlinking it and starting a 383 * new one; even backup files are supposed to be made by copying 384 * rather than by renaming. if some editor does not support this, 385 * then don't use it. the security problems are more severe if we 386 * close and reopen the file around the edit. 387 */ 388 389 switch (pid = fork()) { 390 case -1: 391 warn("fork"); 392 goto fatal; 393 case 0: 394 /* child */ 395 if (setuid(getuid()) < 0) 396 err(ERROR_EXIT, "setuid(getuid())"); 397 if (chdir("/tmp") < 0) 398 err(ERROR_EXIT, "chdir(/tmp)"); 399 if (strlen(editor) + strlen(Filename) + 2 >= MAX_TEMPSTR) 400 errx(ERROR_EXIT, "editor or filename too long"); 401 execlp(editor, editor, Filename, (char *)NULL); 402 err(ERROR_EXIT, "%s", editor); 403 /*NOTREACHED*/ 404 default: 405 /* parent */ 406 break; 407 } 408 409 /* parent */ 410 { 411 void (*f[4])(); 412 f[0] = signal(SIGHUP, SIG_IGN); 413 f[1] = signal(SIGINT, SIG_IGN); 414 f[2] = signal(SIGTERM, SIG_IGN); 415 xpid = wait(&waiter); 416 signal(SIGHUP, f[0]); 417 signal(SIGINT, f[1]); 418 signal(SIGTERM, f[2]); 419 } 420 if (xpid != pid) { 421 warnx("wrong PID (%d != %d) from \"%s\"", xpid, pid, editor); 422 goto fatal; 423 } 424 if (WIFEXITED(waiter) && WEXITSTATUS(waiter)) { 425 warnx("\"%s\" exited with status %d", editor, WEXITSTATUS(waiter)); 426 goto fatal; 427 } 428 if (WIFSIGNALED(waiter)) { 429 warnx("\"%s\" killed; signal %d (%score dumped)", 430 editor, WTERMSIG(waiter), WCOREDUMP(waiter) ?"" :"no "); 431 goto fatal; 432 } 433 if (stat(Filename, &statbuf) < 0) { 434 warn("stat"); 435 goto fatal; 436 } 437 if (statbuf.st_dev != fsbuf.st_dev || statbuf.st_ino != fsbuf.st_ino) 438 errx(ERROR_EXIT, "temp file must be edited in place"); 439 if (MD5File(Filename, new_md5) == NULL) { 440 warn("MD5"); 441 goto fatal; 442 } 443 if (strcmp(orig_md5, new_md5) == 0 && !syntax_error) { 444 warnx("no changes made to crontab"); 445 goto remove; 446 } 447 warnx("installing new crontab"); 448 switch (replace_cmd()) { 449 case 0: /* Success */ 450 break; 451 case -1: /* Syntax error */ 452 for (;;) { 453 printf("Do you want to retry the same edit? "); 454 fflush(stdout); 455 q[0] = '\0'; 456 (void) fgets(q, sizeof q, stdin); 457 switch (islower(q[0]) ? q[0] : tolower(q[0])) { 458 case 'y': 459 syntax_error = 1; 460 goto again; 461 case 'n': 462 goto abandon; 463 default: 464 fprintf(stderr, "Enter Y or N\n"); 465 } 466 } 467 /*NOTREACHED*/ 468 case -2: /* Install error */ 469 abandon: 470 warnx("edits left in %s", Filename); 471 goto done; 472 default: 473 warnx("panic: bad switch() in replace_cmd()"); 474 goto fatal; 475 } 476 remove: 477 unlink(Filename); 478 done: 479 log_it(RealUser, Pid, "END EDIT", User); 480 } 481 482 483 /* returns 0 on success 484 * -1 on syntax error 485 * -2 on install error 486 */ 487 static int 488 replace_cmd() { 489 char n[MAX_FNAME], envstr[MAX_ENVSTR], tn[MAX_FNAME]; 490 FILE *tmp; 491 int ch, eof; 492 entry *e; 493 time_t now = time(NULL); 494 char **envp = env_init(); 495 496 if (envp == NULL) { 497 warnx("cannot allocate memory"); 498 return (-2); 499 } 500 501 (void) sprintf(n, "tmp.%d", Pid); 502 (void) sprintf(tn, CRON_TAB(n)); 503 if (!(tmp = fopen(tn, "w+"))) { 504 warn("%s", tn); 505 return (-2); 506 } 507 508 /* write a signature at the top of the file. 509 * 510 * VERY IMPORTANT: make sure NHEADER_LINES agrees with this code. 511 */ 512 fprintf(tmp, "# DO NOT EDIT THIS FILE - edit the master and reinstall.\n"); 513 fprintf(tmp, "# (%s installed on %-24.24s)\n", Filename, ctime(&now)); 514 fprintf(tmp, "# (Cron version -- %s)\n", rcsid); 515 516 /* copy the crontab to the tmp 517 */ 518 rewind(NewCrontab); 519 Set_LineNum(1) 520 while (EOF != (ch = get_char(NewCrontab))) 521 putc(ch, tmp); 522 ftruncate(fileno(tmp), ftell(tmp)); 523 fflush(tmp); rewind(tmp); 524 525 if (ferror(tmp)) { 526 warnx("error while writing new crontab to %s", tn); 527 fclose(tmp); unlink(tn); 528 return (-2); 529 } 530 531 /* check the syntax of the file being installed. 532 */ 533 534 /* BUG: was reporting errors after the EOF if there were any errors 535 * in the file proper -- kludged it by stopping after first error. 536 * vix 31mar87 537 */ 538 Set_LineNum(1 - NHEADER_LINES) 539 CheckErrorCount = 0; eof = FALSE; 540 while (!CheckErrorCount && !eof) { 541 switch (load_env(envstr, tmp)) { 542 case ERR: 543 eof = TRUE; 544 break; 545 case FALSE: 546 e = load_entry(tmp, check_error, pw, envp); 547 if (e) 548 free(e); 549 break; 550 case TRUE: 551 break; 552 } 553 } 554 555 if (CheckErrorCount != 0) { 556 warnx("errors in crontab file, can't install"); 557 fclose(tmp); unlink(tn); 558 return (-1); 559 } 560 561 #ifdef HAS_FCHOWN 562 if (fchown(fileno(tmp), ROOT_UID, -1) < OK) 563 #else 564 if (chown(tn, ROOT_UID, -1) < OK) 565 #endif 566 { 567 warn("chown"); 568 fclose(tmp); unlink(tn); 569 return (-2); 570 } 571 572 #ifdef HAS_FCHMOD 573 if (fchmod(fileno(tmp), 0600) < OK) 574 #else 575 if (chmod(tn, 0600) < OK) 576 #endif 577 { 578 warn("chown"); 579 fclose(tmp); unlink(tn); 580 return (-2); 581 } 582 583 if (fclose(tmp) == EOF) { 584 warn("fclose"); 585 unlink(tn); 586 return (-2); 587 } 588 589 (void) sprintf(n, CRON_TAB(User)); 590 if (rename(tn, n)) { 591 warn("error renaming %s to %s", tn, n); 592 unlink(tn); 593 return (-2); 594 } 595 log_it(RealUser, Pid, "REPLACE", User); 596 597 poke_daemon(); 598 599 return (0); 600 } 601 602 603 static void 604 poke_daemon() { 605 #ifdef USE_UTIMES 606 struct timeval tvs[2]; 607 struct timezone tz; 608 609 (void) gettimeofday(&tvs[0], &tz); 610 tvs[1] = tvs[0]; 611 if (utimes(SPOOL_DIR, tvs) < OK) { 612 warn("can't update mtime on spooldir %s", SPOOL_DIR); 613 return; 614 } 615 #else 616 if (utime(SPOOL_DIR, NULL) < OK) { 617 warn("can't update mtime on spooldir %s", SPOOL_DIR); 618 return; 619 } 620 #endif /*USE_UTIMES*/ 621 } 622