#if !defined(lint) && !defined(LINT)
static const char rcsid[] =
"$FreeBSD: src/usr.sbin/cron/cron/do_command.c,v 1.26 2006/06/11 21:13:49 maxim Exp $";
#endif
#include "cron.h"
#include <sys/signal.h>
#if defined(sequent)
# include <sys/universe.h>
#endif
#if defined(SYSLOG)
# include <syslog.h>
#endif
#if defined(LOGIN_CAP)
# include <login_cap.h>
#endif
#ifdef __APPLE__
#include <stdlib.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/pwr_mgt/IOPMLib.h>
#include <IOKit/pwr_mgt/IOPM.h>
#include <IOKit/IOReturn.h>
#include <CoreFoundation/CFArray.h>
#include <CoreFoundation/CFBase.h>
#include <CoreFoundation/CFNumber.h>
#include <CoreFoundation/CFData.h>
#include <CoreFoundation/CoreFoundation.h>
#include <mach/mach_init.h>
#include <vproc.h>
#include <vproc_priv.h>
#include <bootstrap_priv.h>
#endif
static void child_process __P((entry *, user *)),
do_univ __P((user *));
#ifdef __APPLE__
extern vproc_err_t _vproc_post_fork_ping(void);
#endif
void
do_command(e, u)
entry *e;
user *u;
{
#ifdef __APPLE__
CFArrayRef cfarray;
static mach_port_t master = 0;
static io_connect_t pmcon = 0;
Debug(DPROC, ("[%d] do_command(%s, (%s,%s,%s))\n",
getpid(), e->cmd, u->name, e->uname, e->gname))
if( e->flags & NOT_BATTERY ) {
if( master == 0 ) {
IOMasterPort(bootstrap_port, &master);
pmcon = IOPMFindPowerManagement(master);
}
if( IOPMCopyBatteryInfo(master, &cfarray) == kIOReturnSuccess) {
CFDictionaryRef dict;
CFNumberRef cfnum;
int flags;
dict = CFArrayGetValueAtIndex(cfarray, 0);
cfnum = CFDictionaryGetValue(dict, CFSTR(kIOBatteryFlagsKey));
CFNumberGetValue(cfnum, kCFNumberLongType, &flags);
if( !(flags & kIOBatteryChargerConnect) ) {
return;
}
}
}
#else
Debug(DPROC, ("[%d] do_command(%s, (%s,%d,%d))\n",
getpid(), e->cmd, u->name, e->uid, e->gid))
#endif
switch (fork()) {
case -1:
log_it("CRON",getpid(),"error","can't fork");
break;
case 0:
pidfile_close(pfh);
child_process(e, u);
Debug(DPROC, ("[%d] child process done, exiting\n", getpid()))
_exit(OK_EXIT);
break;
default:
break;
}
Debug(DPROC, ("[%d] main process returning to work\n", getpid()))
}
static void
child_process(e, u)
entry *e;
user *u;
{
int stdin_pipe[2], stdout_pipe[2];
register char *input_data;
char *usernm, *mailto;
#ifdef __APPLE__
uid_t uid = -1;
gid_t gid = -1;
struct passwd *pwd;
#endif
int children = 0;
# if defined(LOGIN_CAP)
struct passwd *pwd;
login_cap_t *lc;
# endif
Debug(DPROC, ("[%d] child_process('%s')\n", getpid(), e->cmd))
#ifdef __APPLE__
setprogname("running job");
#else
setproctitle("running job");
#endif
#ifdef __APPLE__
usernm = e->uname;
#else
usernm = env_get("LOGNAME", e->envp);
#endif
mailto = env_get("MAILTO", e->envp);
#ifdef USE_SIGCHLD
(void) signal(SIGCHLD, SIG_DFL);
#else
(void) signal(SIGCLD, SIG_DFL);
#endif
pipe(stdin_pipe);
pipe(stdout_pipe);
{
register int escaped = FALSE;
register int ch;
register char *p;
for (input_data = p = e->cmd; (ch = *input_data);
input_data++, p++) {
if (p != input_data)
*p = ch;
if (escaped) {
if (ch == '%' || ch == '\\')
*--p = ch;
escaped = FALSE;
continue;
}
if (ch == '\\') {
escaped = TRUE;
continue;
}
if (ch == '%') {
*input_data++ = '\0';
break;
}
}
*p = '\0';
}
#ifdef __APPLE__
switch (fork()) {
#else
switch (vfork()) {
#endif
case -1:
log_it("CRON",getpid(),"error","can't vfork");
exit(ERROR_EXIT);
case 0:
Debug(DPROC, ("[%d] grandchild process Vfork()'ed\n",
getpid()))
#ifndef __APPLE__
if (e->uid == ROOT_UID)
Jitter = RootJitter;
if (Jitter != 0) {
srandom(getpid());
sleep(random() % Jitter);
}
#endif
{
char *x = mkprints((u_char *)e->cmd, strlen(e->cmd));
log_it(usernm, getpid(), "CMD", x);
free(x);
}
#ifdef SYSLOG
closelog();
#endif
(void) setsid();
close(stdin_pipe[WRITE_PIPE]);
close(stdout_pipe[READ_PIPE]);
close(STDIN); dup2(stdin_pipe[READ_PIPE], STDIN);
close(STDOUT); dup2(stdout_pipe[WRITE_PIPE], STDOUT);
close(STDERR); dup2(STDOUT, STDERR);
close(stdin_pipe[READ_PIPE]);
close(stdout_pipe[WRITE_PIPE]);
do_univ(u);
#ifdef __APPLE__
if ((pwd = getpwnam(e->uname))) {
char envstr[MAXPATHLEN + sizeof "HOME="];
uid = pwd->pw_uid;
gid = pwd->pw_gid;
if (pwd->pw_expire && time(NULL) >= pwd->pw_expire) {
warn("user account expired: %s", e->uname);
_exit(ERROR_EXIT);
}
sprintf(envstr, "HOME=%s", pwd->pw_dir);
e->envp = env_set(e->envp, envstr);
if (e->envp == NULL) {
warn("env_set(%s)", envstr);
_exit(ERROR_EXIT);
}
} else {
warn("getpwnam(\"%s\")", e->uname);
_exit(ERROR_EXIT);
}
if (strlen(e->gname) > 0) {
struct group *gr = getgrnam(e->gname);
if (gr) {
gid = gr->gr_gid;
} else {
warn("getgrnam(\"%s\")", e->gname);
_exit(ERROR_EXIT);
}
}
mach_port_t puc = MACH_PORT_NULL;
kern_return_t kr = bootstrap_look_up_per_user(bootstrap_port, NULL, uid, &puc);
if (kr != BOOTSTRAP_SUCCESS) {
warnx("could not look up per-user bootstrap for uid %u", uid);
_exit(ERROR_EXIT);
}
mach_port_mod_refs(mach_task_self(), bootstrap_port, MACH_PORT_RIGHT_SEND, -1);
task_set_bootstrap_port(mach_task_self(), puc);
bootstrap_port = puc;
if (_vproc_post_fork_ping() != NULL) {
warnx("failed to setup exception ports");
_exit(ERROR_EXIT);
}
#endif
# if defined(LOGIN_CAP)
if ((pwd = getpwnam(usernm)) == NULL)
pwd = getpwuid(e->uid);
lc = NULL;
if (pwd != NULL) {
pwd->pw_gid = e->gid;
if (e->class != NULL)
lc = login_getclass(e->class);
}
if (pwd &&
setusercontext(lc, pwd, e->uid,
LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETENV)) == 0)
(void) endpwent();
else {
(void) endpwent();
# endif
#ifdef __APPLE__
if (setgid(gid) != 0) {
#else
if (setgid(e->gid) != 0) {
#endif
log_it(usernm, getpid(),
"error", "setgid failed");
exit(ERROR_EXIT);
}
# if defined(BSD)
#ifdef __APPLE__
if (initgroups(usernm, gid) != 0) {
#else
if (initgroups(usernm, e->gid) != 0) {
#endif
log_it(usernm, getpid(),
"error", "initgroups failed");
exit(ERROR_EXIT);
}
# endif
if (setlogin(usernm) != 0) {
log_it(usernm, getpid(),
"error", "setlogin failed");
exit(ERROR_EXIT);
}
#ifdef __APPLE__
if (setuid(uid) != 0) {
#else
if (setuid(e->uid) != 0) {
#endif
log_it(usernm, getpid(),
"error", "setuid failed");
exit(ERROR_EXIT);
}
#if defined(LOGIN_CAP)
}
if (lc != NULL)
login_close(lc);
#endif
chdir(env_get("HOME", e->envp));
{
char *shell = env_get("SHELL", e->envp);
# if DEBUGGING
if (DebugFlags & DTEST) {
fprintf(stderr,
"debug DTEST is on, not exec'ing command.\n");
fprintf(stderr,
"\tcmd='%s' shell='%s'\n", e->cmd, shell);
_exit(OK_EXIT);
}
# endif
execle(shell, shell, "-c", e->cmd, (char *)0, e->envp);
warn("execl: couldn't exec `%s'", shell);
_exit(ERROR_EXIT);
}
break;
default:
break;
}
children++;
Debug(DPROC, ("[%d] child continues, closing pipes\n", getpid()))
close(stdin_pipe[READ_PIPE]);
close(stdout_pipe[WRITE_PIPE]);
if (*input_data && fork() == 0) {
register FILE *out = fdopen(stdin_pipe[WRITE_PIPE], "w");
register int need_newline = FALSE;
register int escaped = FALSE;
register int ch;
if (out == NULL) {
warn("fdopen failed in child2");
_exit(ERROR_EXIT);
}
Debug(DPROC, ("[%d] child2 sending data to grandchild\n", getpid()))
close(stdout_pipe[READ_PIPE]);
while ((ch = *input_data++)) {
if (escaped) {
if (ch != '%')
putc('\\', out);
} else {
if (ch == '%')
ch = '\n';
}
if (!(escaped = (ch == '\\'))) {
putc(ch, out);
need_newline = (ch != '\n');
}
}
if (escaped)
putc('\\', out);
if (need_newline)
putc('\n', out);
fclose(out);
Debug(DPROC, ("[%d] child2 done sending to grandchild\n", getpid()))
exit(0);
}
close(stdin_pipe[WRITE_PIPE]);
children++;
Debug(DPROC, ("[%d] child reading output from grandchild\n", getpid()))
{
register FILE *in = fdopen(stdout_pipe[READ_PIPE], "r");
register int ch;
if (in == NULL) {
warn("fdopen failed in child");
_exit(ERROR_EXIT);
}
ch = getc(in);
if (ch != EOF) {
register FILE *mail = NULL;
register int bytes = 1;
int status = 0;
Debug(DPROC|DEXT,
("[%d] got data (%x:%c) from grandchild\n",
getpid(), ch, ch))
if (mailto) {
if (!*mailto) {
mailto = NULL;
}
} else {
mailto = usernm;
}
if (mailto) {
register char **env;
auto char mailcmd[MAX_COMMAND];
auto char hostname[MAXHOSTNAMELEN];
(void) gethostname(hostname, MAXHOSTNAMELEN);
(void) snprintf(mailcmd, sizeof(mailcmd),
MAILARGS, MAILCMD);
if (!(mail = cron_popen(mailcmd, "w", e))) {
warn("%s", MAILCMD);
(void) _exit(ERROR_EXIT);
}
fprintf(mail, "From: %s (Cron Daemon)\n", usernm);
fprintf(mail, "To: %s\n", mailto);
fprintf(mail, "Subject: Cron <%s@%s> %s\n",
usernm, first_word(hostname, "."),
e->cmd);
# if defined(MAIL_DATE)
fprintf(mail, "Date: %s\n",
arpadate(&TargetTime));
# endif
for (env = e->envp; *env; env++)
fprintf(mail, "X-Cron-Env: <%s>\n",
*env);
fprintf(mail, "\n");
putc(ch, mail);
}
while (EOF != (ch = getc(in))) {
bytes++;
if (mailto)
putc(ch, mail);
}
if (mailto) {
Debug(DPROC, ("[%d] closing pipe to mail\n",
getpid()))
status = cron_pclose(mail);
}
if (mailto && status) {
char buf[MAX_TEMPSTR];
snprintf(buf, sizeof(buf),
"mailed %d byte%s of output but got status 0x%04x\n",
bytes, (bytes==1)?"":"s",
status);
log_it(usernm, getpid(), "MAIL", buf);
}
}
Debug(DPROC, ("[%d] got EOF from grandchild\n", getpid()))
fclose(in);
}
for (; children > 0; children--)
{
WAIT_T waiter;
PID_T pid;
Debug(DPROC, ("[%d] waiting for grandchild #%d to finish\n",
getpid(), children))
pid = wait(&waiter);
if (pid < OK) {
Debug(DPROC, ("[%d] no more grandchildren--mail written?\n",
getpid()))
break;
}
Debug(DPROC, ("[%d] grandchild #%d finished, status=%04x",
getpid(), pid, WEXITSTATUS(waiter)))
if (WIFSIGNALED(waiter) && WCOREDUMP(waiter))
Debug(DPROC, (", dumped core"))
Debug(DPROC, ("\n"))
}
}
static void
do_univ(u)
user *u;
{
#ifdef __APPLE__
u = u; #endif
#if defined(sequent)
struct passwd *p;
char *s;
int i;
p = getpwuid(u->uid);
(void) endpwent();
if (p == NULL)
return;
s = p->pw_gecos;
for (i = 0; i < 4; i++)
{
if ((s = strchr(s, ',')) == NULL)
return;
s++;
}
if (strcmp(s, "universe(att)"))
return;
(void) universe(U_ATT);
#endif
}