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