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