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