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