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