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