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 */ 17 18 #if !defined(lint) && !defined(LINT) 19 static const char rcsid[] = 20 "$FreeBSD$"; 21 #endif 22 23 24 #include "cron.h" 25 #include <sys/signal.h> 26 #if defined(sequent) 27 # include <sys/universe.h> 28 #endif 29 #if defined(SYSLOG) 30 # include <syslog.h> 31 #endif 32 #if defined(LOGIN_CAP) 33 # include <login_cap.h> 34 #endif 35 #ifdef PAM 36 # include <security/pam_appl.h> 37 # include <security/openpam.h> 38 #endif 39 40 41 static void child_process(entry *, user *), 42 do_univ(user *); 43 44 static WAIT_T wait_on_child(PID_T, const char *); 45 46 void 47 do_command(e, u) 48 entry *e; 49 user *u; 50 { 51 pid_t pid; 52 53 Debug(DPROC, ("[%d] do_command(%s, (%s,%d,%d))\n", 54 getpid(), e->cmd, u->name, e->uid, e->gid)) 55 56 /* fork to become asynchronous -- parent process is done immediately, 57 * and continues to run the normal cron code, which means return to 58 * tick(). the child and grandchild don't leave this function, alive. 59 * 60 * vfork() is unsuitable, since we have much to do, and the parent 61 * needs to be able to run off and fork other processes. 62 */ 63 switch ((pid = fork())) { 64 case -1: 65 log_it("CRON",getpid(),"error","can't fork"); 66 if (e->flags & INTERVAL) 67 e->lastexit = time(NULL); 68 break; 69 case 0: 70 /* child process */ 71 pidfile_close(pfh); 72 child_process(e, u); 73 Debug(DPROC, ("[%d] child process done, exiting\n", getpid())) 74 _exit(OK_EXIT); 75 break; 76 default: 77 /* parent process */ 78 Debug(DPROC, ("[%d] main process forked child #%d, " 79 "returning to work\n", getpid(), pid)) 80 if (e->flags & INTERVAL) { 81 e->lastexit = 0; 82 e->child = pid; 83 } 84 break; 85 } 86 Debug(DPROC, ("[%d] main process returning to work\n", getpid())) 87 } 88 89 90 static void 91 child_process(e, u) 92 entry *e; 93 user *u; 94 { 95 int stdin_pipe[2], stdout_pipe[2]; 96 register char *input_data; 97 char *usernm, *mailto, *mailfrom; 98 PID_T jobpid, stdinjob, mailpid; 99 register FILE *mail; 100 register int bytes = 1; 101 int status = 0; 102 # if defined(LOGIN_CAP) 103 struct passwd *pwd; 104 login_cap_t *lc; 105 # endif 106 107 Debug(DPROC, ("[%d] child_process('%s')\n", getpid(), e->cmd)) 108 109 /* mark ourselves as different to PS command watchers by upshifting 110 * our program name. This has no effect on some kernels. 111 */ 112 setproctitle("running job"); 113 114 /* discover some useful and important environment settings 115 */ 116 usernm = env_get("LOGNAME", e->envp); 117 mailto = env_get("MAILTO", e->envp); 118 mailfrom = env_get("MAILFROM", e->envp); 119 120 #ifdef PAM 121 /* use PAM to see if the user's account is available, 122 * i.e., not locked or expired or whatever. skip this 123 * for system tasks from /etc/crontab -- they can run 124 * as any user. 125 */ 126 if (strcmp(u->name, SYS_NAME)) { /* not equal */ 127 pam_handle_t *pamh = NULL; 128 int pam_err; 129 struct pam_conv pamc = { 130 .conv = openpam_nullconv, 131 .appdata_ptr = NULL 132 }; 133 134 Debug(DPROC, ("[%d] checking account with PAM\n", getpid())) 135 136 /* u->name keeps crontab owner name while LOGNAME is the name 137 * of user to run command on behalf of. they should be the 138 * same for a task from a per-user crontab. 139 */ 140 if (strcmp(u->name, usernm)) { 141 log_it(usernm, getpid(), "username ambiguity", u->name); 142 exit(ERROR_EXIT); 143 } 144 145 pam_err = pam_start("cron", usernm, &pamc, &pamh); 146 if (pam_err != PAM_SUCCESS) { 147 log_it("CRON", getpid(), "error", "can't start PAM"); 148 exit(ERROR_EXIT); 149 } 150 151 pam_err = pam_acct_mgmt(pamh, PAM_SILENT); 152 /* Expired password shouldn't prevent the job from running. */ 153 if (pam_err != PAM_SUCCESS && pam_err != PAM_NEW_AUTHTOK_REQD) { 154 log_it(usernm, getpid(), "USER", "account unavailable"); 155 exit(ERROR_EXIT); 156 } 157 158 pam_end(pamh, pam_err); 159 } 160 #endif 161 162 #ifdef USE_SIGCHLD 163 /* our parent is watching for our death by catching SIGCHLD. we 164 * do not care to watch for our children's deaths this way -- we 165 * use wait() explicitly. so we have to disable the signal (which 166 * was inherited from the parent). 167 */ 168 (void) signal(SIGCHLD, SIG_DFL); 169 #else 170 /* on system-V systems, we are ignoring SIGCLD. we have to stop 171 * ignoring it now or the wait() in cron_pclose() won't work. 172 * because of this, we have to wait() for our children here, as well. 173 */ 174 (void) signal(SIGCLD, SIG_DFL); 175 #endif /*BSD*/ 176 177 /* create some pipes to talk to our future child 178 */ 179 if (pipe(stdin_pipe) != 0 || pipe(stdout_pipe) != 0) { 180 log_it("CRON", getpid(), "error", "can't pipe"); 181 exit(ERROR_EXIT); 182 } 183 184 /* since we are a forked process, we can diddle the command string 185 * we were passed -- nobody else is going to use it again, right? 186 * 187 * if a % is present in the command, previous characters are the 188 * command, and subsequent characters are the additional input to 189 * the command. Subsequent %'s will be transformed into newlines, 190 * but that happens later. 191 * 192 * If there are escaped %'s, remove the escape character. 193 */ 194 /*local*/{ 195 register int escaped = FALSE; 196 register int ch; 197 register char *p; 198 199 for (input_data = p = e->cmd; (ch = *input_data); 200 input_data++, p++) { 201 if (p != input_data) 202 *p = ch; 203 if (escaped) { 204 if (ch == '%' || ch == '\\') 205 *--p = ch; 206 escaped = FALSE; 207 continue; 208 } 209 if (ch == '\\') { 210 escaped = TRUE; 211 continue; 212 } 213 if (ch == '%') { 214 *input_data++ = '\0'; 215 break; 216 } 217 } 218 *p = '\0'; 219 } 220 221 /* fork again, this time so we can exec the user's command. 222 */ 223 switch (jobpid = vfork()) { 224 case -1: 225 log_it("CRON",getpid(),"error","can't vfork"); 226 exit(ERROR_EXIT); 227 /*NOTREACHED*/ 228 case 0: 229 Debug(DPROC, ("[%d] grandchild process Vfork()'ed\n", 230 getpid())) 231 232 if (e->uid == ROOT_UID) 233 Jitter = RootJitter; 234 if (Jitter != 0) { 235 srandom(getpid()); 236 sleep(random() % Jitter); 237 } 238 239 /* write a log message. we've waited this long to do it 240 * because it was not until now that we knew the PID that 241 * the actual user command shell was going to get and the 242 * PID is part of the log message. 243 */ 244 if ((e->flags & DONT_LOG) == 0) { 245 char *x = mkprints((u_char *)e->cmd, strlen(e->cmd)); 246 247 log_it(usernm, getpid(), "CMD", x); 248 free(x); 249 } 250 251 /* that's the last thing we'll log. close the log files. 252 */ 253 #ifdef SYSLOG 254 closelog(); 255 #endif 256 257 /* get new pgrp, void tty, etc. 258 */ 259 (void) setsid(); 260 261 /* close the pipe ends that we won't use. this doesn't affect 262 * the parent, who has to read and write them; it keeps the 263 * kernel from recording us as a potential client TWICE -- 264 * which would keep it from sending SIGPIPE in otherwise 265 * appropriate circumstances. 266 */ 267 close(stdin_pipe[WRITE_PIPE]); 268 close(stdout_pipe[READ_PIPE]); 269 270 /* grandchild process. make std{in,out} be the ends of 271 * pipes opened by our daddy; make stderr go to stdout. 272 */ 273 close(STDIN); dup2(stdin_pipe[READ_PIPE], STDIN); 274 close(STDOUT); dup2(stdout_pipe[WRITE_PIPE], STDOUT); 275 close(STDERR); dup2(STDOUT, STDERR); 276 277 /* close the pipes we just dup'ed. The resources will remain. 278 */ 279 close(stdin_pipe[READ_PIPE]); 280 close(stdout_pipe[WRITE_PIPE]); 281 282 /* set our login universe. Do this in the grandchild 283 * so that the child can invoke /usr/lib/sendmail 284 * without surprises. 285 */ 286 do_univ(u); 287 288 # if defined(LOGIN_CAP) 289 /* Set user's entire context, but skip the environment 290 * as cron provides a separate interface for this 291 */ 292 if ((pwd = getpwnam(usernm)) == NULL) 293 pwd = getpwuid(e->uid); 294 lc = NULL; 295 if (pwd != NULL) { 296 pwd->pw_gid = e->gid; 297 if (e->class != NULL) 298 lc = login_getclass(e->class); 299 } 300 if (pwd && 301 setusercontext(lc, pwd, e->uid, 302 LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETENV)) == 0) 303 (void) endpwent(); 304 else { 305 /* fall back to the old method */ 306 (void) endpwent(); 307 # endif 308 /* set our directory, uid and gid. Set gid first, 309 * since once we set uid, we've lost root privileges. 310 */ 311 if (setgid(e->gid) != 0) { 312 log_it(usernm, getpid(), 313 "error", "setgid failed"); 314 exit(ERROR_EXIT); 315 } 316 # if defined(BSD) 317 if (initgroups(usernm, e->gid) != 0) { 318 log_it(usernm, getpid(), 319 "error", "initgroups failed"); 320 exit(ERROR_EXIT); 321 } 322 # endif 323 if (setlogin(usernm) != 0) { 324 log_it(usernm, getpid(), 325 "error", "setlogin failed"); 326 exit(ERROR_EXIT); 327 } 328 if (setuid(e->uid) != 0) { 329 log_it(usernm, getpid(), 330 "error", "setuid failed"); 331 exit(ERROR_EXIT); 332 } 333 /* we aren't root after this..*/ 334 #if defined(LOGIN_CAP) 335 } 336 if (lc != NULL) 337 login_close(lc); 338 #endif 339 chdir(env_get("HOME", e->envp)); 340 341 /* exec the command. 342 */ 343 { 344 char *shell = env_get("SHELL", e->envp); 345 346 # if DEBUGGING 347 if (DebugFlags & DTEST) { 348 fprintf(stderr, 349 "debug DTEST is on, not exec'ing command.\n"); 350 fprintf(stderr, 351 "\tcmd='%s' shell='%s'\n", e->cmd, shell); 352 _exit(OK_EXIT); 353 } 354 # endif /*DEBUGGING*/ 355 execle(shell, shell, "-c", e->cmd, (char *)NULL, 356 e->envp); 357 warn("execle: couldn't exec `%s'", shell); 358 _exit(ERROR_EXIT); 359 } 360 break; 361 default: 362 /* parent process */ 363 break; 364 } 365 366 /* middle process, child of original cron, parent of process running 367 * the user's command. 368 */ 369 370 Debug(DPROC, ("[%d] child continues, closing pipes\n", getpid())) 371 372 /* close the ends of the pipe that will only be referenced in the 373 * grandchild process... 374 */ 375 close(stdin_pipe[READ_PIPE]); 376 close(stdout_pipe[WRITE_PIPE]); 377 378 /* 379 * write, to the pipe connected to child's stdin, any input specified 380 * after a % in the crontab entry. while we copy, convert any 381 * additional %'s to newlines. when done, if some characters were 382 * written and the last one wasn't a newline, write a newline. 383 * 384 * Note that if the input data won't fit into one pipe buffer (2K 385 * or 4K on most BSD systems), and the child doesn't read its stdin, 386 * we would block here. thus we must fork again. 387 */ 388 389 if (*input_data && (stdinjob = fork()) == 0) { 390 register FILE *out = fdopen(stdin_pipe[WRITE_PIPE], "w"); 391 register int need_newline = FALSE; 392 register int escaped = FALSE; 393 register int ch; 394 395 if (out == NULL) { 396 warn("fdopen failed in child2"); 397 _exit(ERROR_EXIT); 398 } 399 400 Debug(DPROC, ("[%d] child2 sending data to grandchild\n", getpid())) 401 402 /* close the pipe we don't use, since we inherited it and 403 * are part of its reference count now. 404 */ 405 close(stdout_pipe[READ_PIPE]); 406 407 /* translation: 408 * \% -> % 409 * % -> \n 410 * \x -> \x for all x != % 411 */ 412 while ((ch = *input_data++)) { 413 if (escaped) { 414 if (ch != '%') 415 putc('\\', out); 416 } else { 417 if (ch == '%') 418 ch = '\n'; 419 } 420 421 if (!(escaped = (ch == '\\'))) { 422 putc(ch, out); 423 need_newline = (ch != '\n'); 424 } 425 } 426 if (escaped) 427 putc('\\', out); 428 if (need_newline) 429 putc('\n', out); 430 431 /* close the pipe, causing an EOF condition. fclose causes 432 * stdin_pipe[WRITE_PIPE] to be closed, too. 433 */ 434 fclose(out); 435 436 Debug(DPROC, ("[%d] child2 done sending to grandchild\n", getpid())) 437 exit(0); 438 } 439 440 /* close the pipe to the grandkiddie's stdin, since its wicked uncle 441 * ernie back there has it open and will close it when he's done. 442 */ 443 close(stdin_pipe[WRITE_PIPE]); 444 445 /* 446 * read output from the grandchild. it's stderr has been redirected to 447 * it's stdout, which has been redirected to our pipe. if there is any 448 * output, we'll be mailing it to the user whose crontab this is... 449 * when the grandchild exits, we'll get EOF. 450 */ 451 452 Debug(DPROC, ("[%d] child reading output from grandchild\n", getpid())) 453 454 /*local*/{ 455 register FILE *in = fdopen(stdout_pipe[READ_PIPE], "r"); 456 register int ch; 457 458 if (in == NULL) { 459 warn("fdopen failed in child"); 460 _exit(ERROR_EXIT); 461 } 462 463 mail = NULL; 464 465 ch = getc(in); 466 if (ch != EOF) { 467 Debug(DPROC|DEXT, 468 ("[%d] got data (%x:%c) from grandchild\n", 469 getpid(), ch, ch)) 470 471 /* get name of recipient. this is MAILTO if set to a 472 * valid local username; USER otherwise. 473 */ 474 if (mailto == NULL) { 475 /* MAILTO not present, set to USER, 476 * unless globally overriden. 477 */ 478 if (defmailto) 479 mailto = defmailto; 480 else 481 mailto = usernm; 482 } 483 if (mailto && *mailto == '\0') 484 mailto = NULL; 485 486 /* if we are supposed to be mailing, MAILTO will 487 * be non-NULL. only in this case should we set 488 * up the mail command and subjects and stuff... 489 */ 490 491 if (mailto) { 492 register char **env; 493 auto char mailcmd[MAX_COMMAND]; 494 auto char hostname[MAXHOSTNAMELEN]; 495 496 if (gethostname(hostname, MAXHOSTNAMELEN) == -1) 497 hostname[0] = '\0'; 498 hostname[sizeof(hostname) - 1] = '\0'; 499 (void) snprintf(mailcmd, sizeof(mailcmd), 500 MAILARGS, MAILCMD); 501 if (!(mail = cron_popen(mailcmd, "w", e, &mailpid))) { 502 warn("%s", MAILCMD); 503 (void) _exit(ERROR_EXIT); 504 } 505 if (mailfrom == NULL || *mailfrom == '\0') 506 fprintf(mail, "From: Cron Daemon <%s@%s>\n", 507 usernm, hostname); 508 else 509 fprintf(mail, "From: Cron Daemon <%s>\n", 510 mailfrom); 511 fprintf(mail, "To: %s\n", mailto); 512 fprintf(mail, "Subject: Cron <%s@%s> %s\n", 513 usernm, first_word(hostname, "."), 514 e->cmd); 515 # if defined(MAIL_DATE) 516 fprintf(mail, "Date: %s\n", 517 arpadate(&TargetTime)); 518 # endif /* MAIL_DATE */ 519 for (env = e->envp; *env; env++) 520 fprintf(mail, "X-Cron-Env: <%s>\n", 521 *env); 522 fprintf(mail, "\n"); 523 524 /* this was the first char from the pipe 525 */ 526 putc(ch, mail); 527 } 528 529 /* we have to read the input pipe no matter whether 530 * we mail or not, but obviously we only write to 531 * mail pipe if we ARE mailing. 532 */ 533 534 while (EOF != (ch = getc(in))) { 535 bytes++; 536 if (mail) 537 putc(ch, mail); 538 } 539 } 540 /*if data from grandchild*/ 541 542 Debug(DPROC, ("[%d] got EOF from grandchild\n", getpid())) 543 544 /* also closes stdout_pipe[READ_PIPE] */ 545 fclose(in); 546 } 547 548 /* wait for children to die. 549 */ 550 if (jobpid > 0) { 551 WAIT_T waiter; 552 553 waiter = wait_on_child(jobpid, "grandchild command job"); 554 555 /* If everything went well, and -n was set, _and_ we have mail, 556 * we won't be mailing... so shoot the messenger! 557 */ 558 if (WIFEXITED(waiter) && WEXITSTATUS(waiter) == 0 559 && (e->flags & MAIL_WHEN_ERR) == MAIL_WHEN_ERR 560 && mail) { 561 Debug(DPROC, ("[%d] %s executed successfully, mail suppressed\n", 562 getpid(), "grandchild command job")) 563 kill(mailpid, SIGKILL); 564 (void)fclose(mail); 565 mail = NULL; 566 } 567 568 569 /* only close pipe if we opened it -- i.e., we're 570 * mailing... 571 */ 572 573 if (mail) { 574 Debug(DPROC, ("[%d] closing pipe to mail\n", 575 getpid())) 576 /* Note: the pclose will probably see 577 * the termination of the grandchild 578 * in addition to the mail process, since 579 * it (the grandchild) is likely to exit 580 * after closing its stdout. 581 */ 582 status = cron_pclose(mail); 583 584 /* if there was output and we could not mail it, 585 * log the facts so the poor user can figure out 586 * what's going on. 587 */ 588 if (status) { 589 char buf[MAX_TEMPSTR]; 590 591 snprintf(buf, sizeof(buf), 592 "mailed %d byte%s of output but got status 0x%04x\n", 593 bytes, (bytes==1)?"":"s", 594 status); 595 log_it(usernm, getpid(), "MAIL", buf); 596 } 597 } 598 } 599 600 if (*input_data && stdinjob > 0) 601 wait_on_child(stdinjob, "grandchild stdinjob"); 602 } 603 604 static WAIT_T 605 wait_on_child(PID_T childpid, const char *name) { 606 WAIT_T waiter; 607 PID_T pid; 608 609 Debug(DPROC, ("[%d] waiting for %s (%d) to finish\n", 610 getpid(), name, childpid)) 611 612 #ifdef POSIX 613 while ((pid = waitpid(childpid, &waiter, 0)) < 0 && errno == EINTR) 614 #else 615 while ((pid = wait4(childpid, &waiter, 0, NULL)) < 0 && errno == EINTR) 616 #endif 617 ; 618 619 if (pid < OK) 620 return waiter; 621 622 Debug(DPROC, ("[%d] %s (%d) finished, status=%04x", 623 getpid(), name, pid, WEXITSTATUS(waiter))) 624 if (WIFSIGNALED(waiter) && WCOREDUMP(waiter)) 625 Debug(DPROC, (", dumped core")) 626 Debug(DPROC, ("\n")) 627 628 return waiter; 629 } 630 631 632 static void 633 do_univ(u) 634 user *u; 635 { 636 #if defined(sequent) 637 /* Dynix (Sequent) hack to put the user associated with 638 * the passed user structure into the ATT universe if 639 * necessary. We have to dig the gecos info out of 640 * the user's password entry to see if the magic 641 * "universe(att)" string is present. 642 */ 643 644 struct passwd *p; 645 char *s; 646 int i; 647 648 p = getpwuid(u->uid); 649 (void) endpwent(); 650 651 if (p == NULL) 652 return; 653 654 s = p->pw_gecos; 655 656 for (i = 0; i < 4; i++) 657 { 658 if ((s = strchr(s, ',')) == NULL) 659 return; 660 s++; 661 } 662 if (strcmp(s, "universe(att)")) 663 return; 664 665 (void) universe(U_ATT); 666 #endif 667 } 668