Debug: pass ACL-initiated debug through execs
[exim.git] / src / src / child.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2015 */
6 /* Copyright (c) The Exim Maintainers 2020 - 2021 */
7 /* See the file NOTICE for conditions of use and distribution. */
8
9
10 #include "exim.h"
11
12 static void (*oldsignal)(int);
13
14
15 /*************************************************
16 *          Ensure an fd has a given value        *
17 *************************************************/
18
19 /* This function is called when we want to ensure that a certain fd has a
20 specific value (one of 0, 1, 2). If it hasn't got it already, close the value
21 we want, duplicate the fd, then close the old one.
22
23 Arguments:
24   oldfd        original fd
25   newfd        the fd we want
26
27 Returns:       nothing
28 */
29
30 void
31 force_fd(int oldfd, int newfd)
32 {
33 if (oldfd == newfd) return;
34 (void)close(newfd);
35 (void)dup2(oldfd, newfd);
36 (void)close(oldfd);
37 }
38
39
40 #ifndef STAND_ALONE
41 /*************************************************
42 *   Build argv list and optionally re-exec Exim  *
43 *************************************************/
44
45 /* This function is called when Exim wants to re-exec (overlay) itself in the
46 current process. This is different to child_open_exim(), which runs another
47 Exim process in parallel (but it then calls this function). The function's
48 basic job is to build the argv list according to the values of current options
49 settings. There is a basic list that all calls require, and an additional list
50 that some do not require. Further additions can be given as additional
51 arguments. An option specifies whether the exec() is actually to happen, and if
52 so, what is to be done if it fails.
53
54 Arguments:
55   exec_type      CEE_RETURN_ARGV => don't exec; return the argv list
56                  CEE_EXEC_EXIT   => just exit() on exec failure
57                  CEE_EXEC_PANIC  => panic-die on exec failure
58   kill_v         if TRUE, don't pass on the D_v flag
59   pcount         if not NULL, points to extra size of argv required, and if
60                    CEE_RETURN_ARGV is specified, it is updated to give the
61                    number of slots used
62   minimal        TRUE if only minimal argv is required
63   acount         number of additional arguments
64   ...            further values to add to argv
65
66 Returns:         if CEE_RETURN_ARGV is given, returns a pointer to argv;
67                  otherwise, does not return
68 */
69
70 uschar **
71 child_exec_exim(int exec_type, BOOL kill_v, int *pcount, BOOL minimal,
72   int acount, ...)
73 {
74 int first_special = -1;
75 int n = 0;
76 int extra = pcount ? *pcount : 0;
77 uschar **argv;
78
79 argv = store_get((extra + acount + MAX_CLMACROS + 21) * sizeof(char *), FALSE);
80
81 /* In all case, the list starts out with the path, any macros, and a changed
82 config file. */
83
84 argv[n++] = exim_path;
85 if (clmacro_count > 0)
86   {
87   memcpy(argv + n, clmacros, clmacro_count * sizeof(uschar *));
88   n += clmacro_count;
89   }
90 if (f.config_changed)
91   {
92   argv[n++] = US"-C";
93   argv[n++] = config_main_filename;
94   }
95
96 /* These values are added only for non-minimal cases. If debug_selector is
97 precisely D_v, we have to assume this was started by a non-admin user, and
98 we suppress the flag when requested. (This happens when passing on an SMTP
99 connection, and after ETRN.) If there's more debugging going on, an admin user
100 was involved, so we do pass it on. */
101
102 if (!minimal)
103   {
104   if (debug_selector == D_v)
105     {
106     if (!kill_v) argv[n++] = US"-v";
107     }
108   else
109     {
110     if (debug_selector != 0)
111       {
112       argv[n++] = string_sprintf("-d=0x%x", debug_selector);
113       if (debug_fd > 2)
114         {
115         int flags = fcntl(debug_fd, F_GETFD);
116         if (flags != -1) (void)fcntl(debug_fd, F_SETFD, flags & ~FD_CLOEXEC);
117         close(2);
118         dup2(debug_fd, 2);
119         close(debug_fd);
120         }
121       }
122     }
123   DEBUG(D_any)
124     {
125     argv[n++] = US"-MCd";
126     argv[n++] = US process_purpose;
127     }
128   if (!f.testsuite_delays) argv[n++] = US"-odd";
129   if (f.dont_deliver) argv[n++] = US"-N";
130   if (f.queue_smtp) argv[n++] = US"-odqs";
131   if (f.synchronous_delivery) argv[n++] = US"-odi";
132   if (connection_max_messages >= 0)
133     argv[n++] = string_sprintf("-oB%d", connection_max_messages);
134   if (*queue_name)
135     {
136     argv[n++] = US"-MCG";
137     argv[n++] = queue_name;
138     }
139   }
140
141 /* Now add in any others that are in the call. Remember which they were,
142 for more helpful diagnosis on failure. */
143
144 if (acount > 0)
145   {
146   va_list ap;
147   va_start(ap, acount);
148   first_special = n;
149   while (acount-- > 0)
150     argv[n++] = va_arg(ap, uschar *);
151   va_end(ap);
152   }
153
154 /* Terminate the list, and return it, if that is what is wanted. */
155
156 argv[n] = NULL;
157 if (exec_type == CEE_RETURN_ARGV)
158   {
159   if (pcount) *pcount = n;
160   return argv;
161   }
162
163 /* Otherwise, do the exec() here, and handle the consequences of an unexpected
164 failure. We know that there will always be at least one extra option in the
165 call when exec() is done here, so it can be used to add to the panic data. */
166
167 DEBUG(D_exec) debug_print_argv(CUSS argv);
168 exim_nullstd();                            /* Make sure std{in,out,err} exist */
169 execv(CS argv[0], (char *const *)argv);
170
171 log_write(0,
172   LOG_MAIN | ((exec_type == CEE_EXEC_EXIT)? LOG_PANIC : LOG_PANIC_DIE),
173   "re-exec of exim (%s) with %s failed: %s", exim_path, argv[first_special],
174   strerror(errno));
175
176 /* Get here if exec_type == CEE_EXEC_EXIT.
177 Note: this must be _exit(), not exit(). */
178
179 _exit(EX_EXECFAILED);
180
181 return NULL;   /* To keep compilers happy */
182 }
183
184
185
186
187 /*************************************************
188 *          Create a child Exim process           *
189 *************************************************/
190
191 /* This function is called when Exim wants to run a parallel instance of itself
192 in order to inject a message via the standard input. The function creates a
193 child process and runs Exim in it. It sets up a pipe to the standard input of
194 the new process, and returns that to the caller via fdptr. The function returns
195 the pid of the new process, or -1 if things go wrong. If debug_fd is
196 non-negative, it is passed as stderr.
197
198 This interface is now a just wrapper for the more complicated function
199 child_open_exim2(), which has additional arguments. The wrapper must continue
200 to exist, even if all calls from within Exim are changed, because it is
201 documented for use from local_scan().
202
203 Argument: fdptr   pointer to int for the stdin fd
204           purpose of the child process, for debug
205 Returns:          pid of the created process or -1 if anything has gone wrong
206 */
207
208 pid_t
209 child_open_exim_function(int * fdptr, const uschar * purpose)
210 {
211 return child_open_exim2_function(fdptr, US"<>", bounce_sender_authentication,
212   purpose);
213 }
214
215
216 /* This is a more complicated function for creating a child Exim process, with
217 more arguments.
218
219 Arguments:
220   fdptr                   pointer to int for the stdin fd
221   sender                  for a sender address (data for -f)
222   sender_authentication   authenticated sender address or NULL
223   purpose                 of the child process, for debug
224
225 Returns:          pid of the created process or -1 if anything has gone wrong
226 */
227
228 pid_t
229 child_open_exim2_function(int * fdptr, uschar * sender,
230   uschar * sender_authentication, const uschar * purpose)
231 {
232 int pfd[2];
233 int save_errno;
234 pid_t pid;
235
236 /* Create the pipe and fork the process. Ensure that SIGCHLD is set to
237 SIG_DFL before forking, so that the child process can be waited for. We
238 sometimes get here with it set otherwise. Save the old state for resetting
239 on the wait. */
240
241 if (pipe(pfd) != 0) return (pid_t)(-1);
242 oldsignal = signal(SIGCHLD, SIG_DFL);
243 pid = exim_fork(purpose);
244
245 /* Child process: make the reading end of the pipe into the standard input and
246 close the writing end. If debugging, pass debug_fd as stderr. Then re-exec
247 Exim with appropriate options. In the test harness, use -odi unless queue_only
248 is set, so that the bounce is fully delivered before returning. Failure is
249 signalled with EX_EXECFAILED (specified by CEE_EXEC_EXIT), but this shouldn't
250 occur. */
251
252 if (pid == 0)
253   {
254   force_fd(pfd[pipe_read], 0);
255   (void)close(pfd[pipe_write]);
256   if (debug_fd > 0) force_fd(debug_fd, 2);
257   if (f.running_in_test_harness && !queue_only)
258     {
259     if (sender_authentication)
260       child_exec_exim(CEE_EXEC_EXIT, FALSE, NULL, FALSE, 9,
261         US "-odi", US"-t", US"-oem", US"-oi", US"-f", sender, US"-oMas",
262         sender_authentication, message_id_option);
263     else
264       child_exec_exim(CEE_EXEC_EXIT, FALSE, NULL, FALSE, 7,
265         US "-odi", US"-t", US"-oem", US"-oi", US"-f", sender,
266         message_id_option);
267     /* Control does not return here. */
268     }
269   else   /* Not test harness */
270     {
271     if (sender_authentication)
272       child_exec_exim(CEE_EXEC_EXIT, FALSE, NULL, FALSE, 8,
273         US"-t", US"-oem", US"-oi", US"-f", sender, US"-oMas",
274         sender_authentication, message_id_option);
275     else
276       child_exec_exim(CEE_EXEC_EXIT, FALSE, NULL, FALSE, 6,
277         US"-t", US"-oem", US"-oi", US"-f", sender, message_id_option);
278     /* Control does not return here. */
279     }
280   }
281
282 testharness_pause_ms(100); /* let child work even longer, for exec */
283
284 /* Parent process. Save fork() errno and close the reading end of the stdin
285 pipe. */
286
287 save_errno = errno;
288 (void)close(pfd[pipe_read]);
289
290 /* Fork succeeded */
291
292 if (pid > 0)
293   {
294   *fdptr = pfd[pipe_write];   /* return writing end of stdin pipe */
295   return pid;                 /* and pid of new process */
296   }
297
298 /* Fork failed */
299
300 (void)close(pfd[pipe_write]);
301 errno = save_errno;
302 return (pid_t)(-1);
303 }
304 #endif   /* STAND_ALONE */
305
306
307
308 /*************************************************
309 *         Create a non-Exim child process        *
310 *************************************************/
311
312 /* This function creates a child process and runs the given command in it. It
313 sets up pipes to the standard input and output of the new process, and returns
314 them to the caller. The standard error is cloned to the output. If there are
315 any file descriptors "in the way" in the new process, they are closed. A new
316 umask is supplied for the process, and an optional new uid and gid are also
317 available. These are used by the queryprogram router to set an unprivileged id.
318 SIGUSR1 is always disabled in the new process, as it is not going to be running
319 Exim (the function child_open_exim() is provided for that). This function
320 returns the pid of the new process, or -1 if things go wrong.
321
322 Arguments:
323   argv        the argv for exec in the new process
324   envp        the envp for exec in the new process
325   newumask    umask to set in the new process
326   newuid      point to uid for the new process or NULL for no change
327   newgid      point to gid for the new process or NULL for no change
328   infdptr     pointer to int into which the fd of the stdin of the new process
329                 is placed
330   outfdptr    pointer to int into which the fd of the stdout/stderr of the new
331                 process is placed
332   wd          if not NULL, a path to be handed to chdir() in the new process
333   make_leader if TRUE, make the new process a process group leader
334   purpose     for debug: reason for running the task
335
336 Returns:      the pid of the created process or -1 if anything has gone wrong
337 */
338
339 pid_t
340 child_open_uid(const uschar **argv, const uschar **envp, int newumask,
341   uid_t *newuid, gid_t *newgid, int *infdptr, int *outfdptr, uschar *wd,
342   BOOL make_leader, const uschar * purpose)
343 {
344 int save_errno;
345 int inpfd[2], outpfd[2];
346 pid_t pid;
347
348 /* Create the pipes. */
349
350 if (pipe(inpfd) != 0) return (pid_t)(-1);
351 if (pipe(outpfd) != 0)
352   {
353   (void)close(inpfd[pipe_read]);
354   (void)close(inpfd[pipe_write]);
355   return (pid_t)(-1);
356   }
357
358 /* Fork the process. Ensure that SIGCHLD is set to SIG_DFL before forking, so
359 that the child process can be waited for. We sometimes get here with it set
360 otherwise. Save the old state for resetting on the wait. */
361
362 oldsignal = signal(SIGCHLD, SIG_DFL);
363 pid = exim_fork(purpose);
364
365 /* Handle the child process. First, set the required environment. We must do
366 this before messing with the pipes, in order to be able to write debugging
367 output when things go wrong. */
368
369 if (pid == 0)
370   {
371   signal(SIGUSR1, SIG_IGN);
372   signal(SIGPIPE, SIG_DFL);
373
374   if (newgid && setgid(*newgid) < 0)
375     {
376     DEBUG(D_any) debug_printf("failed to set gid=%ld in subprocess: %s\n",
377       (long int)(*newgid), strerror(errno));
378     goto CHILD_FAILED;
379     }
380
381   if (newuid && setuid(*newuid) < 0)
382     {
383     DEBUG(D_any) debug_printf("failed to set uid=%ld in subprocess: %s\n",
384       (long int)(*newuid), strerror(errno));
385     goto CHILD_FAILED;
386     }
387
388   (void)umask(newumask);
389
390   if (wd && Uchdir(wd) < 0)
391     {
392     DEBUG(D_any) debug_printf("failed to chdir to %s: %s\n", wd,
393       strerror(errno));
394     goto CHILD_FAILED;
395     }
396
397   /* Becomes a process group leader if requested, and then organize the pipes.
398   Any unexpected failure is signalled with EX_EXECFAILED; these are all "should
399   never occur" failures, except for exec failing because the command doesn't
400   exist. */
401
402   if (make_leader && setpgid(0,0) < 0)
403     {
404     DEBUG(D_any) debug_printf("failed to set group leader in subprocess: %s\n",
405       strerror(errno));
406     goto CHILD_FAILED;
407     }
408
409   (void)close(inpfd[pipe_write]);
410   force_fd(inpfd[pipe_read], 0);
411
412   (void)close(outpfd[pipe_read]);
413   force_fd(outpfd[pipe_write], 1);
414
415   (void)close(2);
416   (void)dup2(1, 2);
417
418   /* Now do the exec */
419
420   if (envp) execve(CS argv[0], (char *const *)argv, (char *const *)envp);
421   else execv(CS argv[0], (char *const *)argv);
422
423   /* Failed to execv. Signal this failure using EX_EXECFAILED. We are
424   losing the actual errno we got back, because there is no way to return
425   this information. */
426
427   CHILD_FAILED:
428   _exit(EX_EXECFAILED);      /* Note: must be _exit(), NOT exit() */
429   }
430
431 /* Parent process. Save any fork failure code, and close the reading end of the
432 stdin pipe, and the writing end of the stdout pipe. */
433
434 save_errno = errno;
435 (void)close(inpfd[pipe_read]);
436 (void)close(outpfd[pipe_write]);
437
438 /* Fork succeeded; return the input/output pipes and the pid */
439
440 if (pid > 0)
441   {
442   *infdptr = inpfd[pipe_write];
443   *outfdptr = outpfd[pipe_read];
444   return pid;
445   }
446
447 /* Fork failed; reset fork errno before returning */
448
449 (void)close(inpfd[pipe_write]);
450 (void)close(outpfd[pipe_read]);
451 errno = save_errno;
452 return (pid_t)(-1);
453 }
454
455
456
457
458 /*************************************************
459 *    Create child process without uid change     *
460 *************************************************/
461
462 /* This function is a wrapper for child_open_uid() that doesn't have the uid,
463 gid and working directory changing arguments. The function is provided so as to
464 have a clean interface for use from local_scan(), but also saves writing NULL
465 arguments several calls that would otherwise use child_open_uid().
466
467 Arguments:
468   argv        the argv for exec in the new process
469   envp        the envp for exec in the new process
470   newumask    umask to set in the new process
471   infdptr     pointer to int into which the fd of the stdin of the new process
472                 is placed
473   outfdptr    pointer to int into which the fd of the stdout/stderr of the new
474                 process is placed
475   make_leader if TRUE, make the new process a process group leader
476   purpose     for debug: reason for running the task
477
478 Returns:      the pid of the created process or -1 if anything has gone wrong
479 */
480
481 pid_t
482 child_open_function(uschar **argv, uschar **envp, int newumask, int *infdptr,
483   int *outfdptr, BOOL make_leader, const uschar * purpose)
484 {
485 return child_open_uid(CUSS argv, CUSS envp, newumask, NULL, NULL,
486   infdptr, outfdptr, NULL, make_leader, purpose);
487 }
488
489
490
491
492 /*************************************************
493 *           Close down child process             *
494 *************************************************/
495
496 /* Wait for the given process to finish, with optional timeout.
497
498 Arguments
499   pid:      the pid to wait for
500   timeout:  maximum time to wait; 0 means for as long as it takes
501
502 Returns:    >= 0          process terminated by exiting; value is process
503                             ending status; if an execve() failed, the value
504                             is typically 127 (defined as EX_EXECFAILED)
505             < 0 & > -256  process was terminated by a signal; value is the
506                             negation of the signal number
507             -256          timed out
508             -257          other error in wait(); errno still set
509 */
510
511 int
512 child_close(pid_t pid, int timeout)
513 {
514 int yield;
515
516 if (timeout > 0)
517   {
518   sigalrm_seen = FALSE;
519   ALARM(timeout);
520   }
521
522 for(;;)
523   {
524   int status;
525   pid_t rc = waitpid(pid, &status, 0);
526   if (rc == pid)
527     {
528     int lowbyte = status & 255;
529     yield = lowbyte == 0 ? (status >> 8) & 255 : -lowbyte;
530     break;
531     }
532   if (rc < 0)
533     {
534     /* This "shouldn't happen" test does happen on MacOS: for some reason
535     I do not understand we seems to get an alarm signal despite not having
536     an active alarm set. There seems to be only one, so just go round again. */
537
538     if (errno == EINTR && sigalrm_seen && timeout <= 0) continue;
539
540     yield = (errno == EINTR && sigalrm_seen) ? -256 : -257;
541     break;
542     }
543   }
544
545 if (timeout > 0) ALARM_CLR(0);
546
547 signal(SIGCHLD, oldsignal);   /* restore */
548 return yield;
549 }
550
551 /* End of child.c */