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