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