Sync 4.next from master
[exim.git] / src / src / rda.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2016 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8 /* This module contains code for extracting addresses from a forwarding list
9 (from an alias or forward file) or by running the filter interpreter. It may do
10 this in a sub-process if a uid/gid are supplied. */
11
12
13 #include "exim.h"
14
15 enum { FILE_EXIST, FILE_NOT_EXIST, FILE_EXIST_UNCLEAR };
16
17 #define REPLY_EXISTS    0x01
18 #define REPLY_EXPAND    0x02
19 #define REPLY_RETURN    0x04
20
21
22 /*************************************************
23 *         Check string for filter program        *
24 *************************************************/
25
26 /* This function checks whether a string is actually a filter program. The rule
27 is that it must start with "# Exim filter ..." (any capitalization, spaces
28 optional). It is envisaged that in future, other kinds of filter may be
29 implemented. That's why it is implemented the way it is. The function is global
30 because it is also called from filter.c when checking filters.
31
32 Argument:  the string
33
34 Returns:   FILTER_EXIM    if it starts with "# Exim filter"
35            FILTER_SIEVE   if it starts with "# Sieve filter"
36            FILTER_FORWARD otherwise
37 */
38
39 /* This is an auxiliary function for matching a tag. */
40
41 static BOOL
42 match_tag(const uschar *s, const uschar *tag)
43 {
44 for (; *tag != 0; s++, tag++)
45   {
46   if (*tag == ' ')
47     {
48     while (*s == ' ' || *s == '\t') s++;
49     s--;
50     }
51   else if (tolower(*s) != tolower(*tag)) break;
52   }
53 return (*tag == 0);
54 }
55
56 /* This is the real function. It should be easy to add checking different
57 tags for other types of filter. */
58
59 int
60 rda_is_filter(const uschar *s)
61 {
62 while (isspace(*s)) s++;     /* Skips initial blank lines */
63 if (match_tag(s, CUS"# exim filter")) return FILTER_EXIM;
64   else if (match_tag(s, CUS"# sieve filter")) return FILTER_SIEVE;
65     else return FILTER_FORWARD;
66 }
67
68
69
70
71 /*************************************************
72 *         Check for existence of file            *
73 *************************************************/
74
75 /* First of all, we stat the file. If this fails, we try to stat the enclosing
76 directory, because a file in an unmounted NFS directory will look the same as a
77 non-existent file. It seems that in Solaris 2.6, statting an entry in an
78 indirect map that is currently unmounted does not cause the mount to happen.
79 Instead, dummy data is returned, which defeats the whole point of this test.
80 However, if a stat() is done on some object inside the directory, such as the
81 "." back reference to itself, then the mount does occur. If an NFS host is
82 taken offline, it is possible for the stat() to get stuck until it comes back.
83 To guard against this, stick a timer round it. If we can't access the "."
84 inside the directory, try the plain directory, just in case that helps.
85
86 Argument:
87   filename   the file name
88   error      for message on error
89
90 Returns:     FILE_EXIST          the file exists
91              FILE_NOT_EXIST      the file does not exist
92              FILE_EXIST_UNCLEAR  cannot determine existence
93 */
94
95 static int
96 rda_exists(uschar *filename, uschar **error)
97 {
98 int rc, saved_errno;
99 uschar *slash;
100 struct stat statbuf;
101
102 if ((rc = Ustat(filename, &statbuf)) >= 0) return FILE_EXIST;
103 saved_errno = errno;
104
105 Ustrncpy(big_buffer, filename, big_buffer_size - 3);
106 sigalrm_seen = FALSE;
107
108 if (saved_errno == ENOENT)
109   {
110   slash = Ustrrchr(big_buffer, '/');
111   Ustrcpy(slash+1, ".");
112
113   alarm(30);
114   rc = Ustat(big_buffer, &statbuf);
115   if (rc != 0 && errno == EACCES && !sigalrm_seen)
116     {
117     *slash = 0;
118     rc = Ustat(big_buffer, &statbuf);
119     }
120   saved_errno = errno;
121   alarm(0);
122
123   DEBUG(D_route) debug_printf("stat(%s)=%d\n", big_buffer, rc);
124   }
125
126 if (sigalrm_seen || rc != 0)
127   {
128   *error = string_sprintf("failed to stat %s (%s)", big_buffer,
129     sigalrm_seen? "timeout" : strerror(saved_errno));
130   return FILE_EXIST_UNCLEAR;
131   }
132
133 *error = string_sprintf("%s does not exist", filename);
134 DEBUG(D_route) debug_printf("%s\n", *error);
135 return FILE_NOT_EXIST;
136 }
137
138
139
140 /*************************************************
141 *     Get forwarding list from a file            *
142 *************************************************/
143
144 /* Open a file and read its entire contents into a block of memory. Certain
145 opening errors are optionally treated the same as "file does not exist".
146
147 ENOTDIR means that something along the line is not a directory: there are
148 installations that set home directories to be /dev/null for non-login accounts
149 but in normal circumstances this indicates some kind of configuration error.
150
151 EACCES means there's a permissions failure. Some users turn off read permission
152 on a .forward file to suspend forwarding, but this is probably an error in any
153 kind of mailing list processing.
154
155 The redirect block that contains the file name also contains constraints such
156 as who may own the file, and mode bits that must not be set. This function is
157
158 Arguments:
159   rdata       rdirect block, containing file name and constraints
160   options     for the RDO_ENOTDIR and RDO_EACCES options
161   error       where to put an error message
162   yield       what to return from rda_interpret on error
163
164 Returns:      pointer to string in store; NULL on error
165 */
166
167 static uschar *
168 rda_get_file_contents(redirect_block *rdata, int options, uschar **error,
169   int *yield)
170 {
171 FILE *fwd;
172 uschar *filebuf;
173 uschar *filename = rdata->string;
174 BOOL uid_ok = !rdata->check_owner;
175 BOOL gid_ok = !rdata->check_group;
176 struct stat statbuf;
177
178 /* Attempt to open the file. If it appears not to exist, check up on the
179 containing directory by statting it. If the directory does not exist, we treat
180 this situation as an error (which will cause delivery to defer); otherwise we
181 pass back FF_NONEXIST, which causes the redirect router to decline.
182
183 However, if the ignore_enotdir option is set (to ignore "something on the
184 path is not a directory" errors), the right behaviour seems to be not to do the
185 directory test. */
186
187 fwd = Ufopen(filename, "rb");
188 if (fwd == NULL)
189   {
190   switch(errno)
191     {
192     case ENOENT:          /* File does not exist */
193     DEBUG(D_route) debug_printf("%s does not exist\n%schecking parent directory\n",
194       filename,
195       ((options & RDO_ENOTDIR) != 0)? "ignore_enotdir set => skip " : "");
196     *yield = (((options & RDO_ENOTDIR) != 0) ||
197               rda_exists(filename, error) == FILE_NOT_EXIST)?
198       FF_NONEXIST : FF_ERROR;
199     return NULL;
200
201     case ENOTDIR:         /* Something on the path isn't a directory */
202     if ((options & RDO_ENOTDIR) == 0) goto DEFAULT_ERROR;
203     DEBUG(D_route) debug_printf("non-directory on path %s: file assumed not to "
204       "exist\n", filename);
205     *yield = FF_NONEXIST;
206     return NULL;
207
208     case EACCES:           /* Permission denied */
209     if ((options & RDO_EACCES) == 0) goto DEFAULT_ERROR;
210     DEBUG(D_route) debug_printf("permission denied for %s: file assumed not to "
211       "exist\n", filename);
212     *yield = FF_NONEXIST;
213     return NULL;
214
215     DEFAULT_ERROR:
216     default:
217     *error = string_open_failed(errno, "%s", filename);
218     *yield = FF_ERROR;
219     return NULL;
220     }
221   }
222
223 /* Check that we have a regular file. */
224
225 if (fstat(fileno(fwd), &statbuf) != 0)
226   {
227   *error = string_sprintf("failed to stat %s: %s", filename, strerror(errno));
228   goto ERROR_RETURN;
229   }
230
231 if ((statbuf.st_mode & S_IFMT) != S_IFREG)
232   {
233   *error = string_sprintf("%s is not a regular file", filename);
234   goto ERROR_RETURN;
235   }
236
237 /* Check for unwanted mode bits */
238
239 if ((statbuf.st_mode & rdata->modemask) != 0)
240   {
241   *error = string_sprintf("bad mode (0%o) for %s: 0%o bit(s) unexpected",
242     statbuf.st_mode, filename, statbuf.st_mode & rdata->modemask);
243   goto ERROR_RETURN;
244   }
245
246 /* Check the file owner and file group if required to do so. */
247
248 if (!uid_ok)
249   {
250   if (rdata->pw != NULL && statbuf.st_uid == rdata->pw->pw_uid)
251     uid_ok = TRUE;
252   else if (rdata->owners != NULL)
253     {
254     int i;
255     for (i = 1; i <= (int)(rdata->owners[0]); i++)
256       if (rdata->owners[i] == statbuf.st_uid) { uid_ok = TRUE; break; }
257     }
258   }
259
260 if (!gid_ok)
261   {
262   if (rdata->pw != NULL && statbuf.st_gid == rdata->pw->pw_gid)
263     gid_ok = TRUE;
264   else if (rdata->owngroups != NULL)
265     {
266     int i;
267     for (i = 1; i <= (int)(rdata->owngroups[0]); i++)
268       if (rdata->owngroups[i] == statbuf.st_gid) { gid_ok = TRUE; break; }
269     }
270   }
271
272 if (!uid_ok || !gid_ok)
273   {
274   *error = string_sprintf("bad %s for %s", uid_ok? "group" : "owner", filename);
275   goto ERROR_RETURN;
276   }
277
278 /* Put an upper limit on the size of the file, just to stop silly people
279 feeding in ridiculously large files, which can easily be created by making
280 files that have holes in them. */
281
282 if (statbuf.st_size > MAX_FILTER_SIZE)
283   {
284   *error = string_sprintf("%s is too big (max %d)", filename, MAX_FILTER_SIZE);
285   goto ERROR_RETURN;
286   }
287
288 /* Read the file in one go in order to minimize the time we have it open. */
289
290 filebuf = store_get(statbuf.st_size + 1);
291
292 if (fread(filebuf, 1, statbuf.st_size, fwd) != statbuf.st_size)
293   {
294   *error = string_sprintf("error while reading %s: %s",
295     filename, strerror(errno));
296   goto ERROR_RETURN;
297   }
298 filebuf[statbuf.st_size] = 0;
299
300 DEBUG(D_route)
301   debug_printf(OFF_T_FMT " bytes read from %s\n", statbuf.st_size, filename);
302
303 (void)fclose(fwd);
304 return filebuf;
305
306 /* Return an error: the string is already set up. */
307
308 ERROR_RETURN:
309 *yield = FF_ERROR;
310 (void)fclose(fwd);
311 return NULL;
312 }
313
314
315
316 /*************************************************
317 *      Extract info from list or filter          *
318 *************************************************/
319
320 /* This function calls the appropriate function to extract addresses from a
321 forwarding list, or to run a filter file and get addresses from there.
322
323 Arguments:
324   rdata                     the redirection block
325   options                   the options bits
326   include_directory         restrain to this directory
327   sieve_vacation_directory  passed to sieve_interpret
328   sieve_enotify_mailto_owner passed to sieve_interpret
329   sieve_useraddress         passed to sieve_interpret
330   sieve_subaddress          passed to sieve_interpret
331   generated                 where to hang generated addresses
332   error                     for error messages
333   eblockp                   for details of skipped syntax errors
334                               (NULL => no skip)
335   filtertype                set to the filter type:
336                               FILTER_FORWARD => a traditional .forward file
337                               FILTER_EXIM    => an Exim filter file
338                               FILTER_SIEVE   => a Sieve filter file
339                             a system filter is always forced to be FILTER_EXIM
340
341 Returns:                    a suitable return for rda_interpret()
342 */
343
344 static int
345 rda_extract(redirect_block *rdata, int options, uschar *include_directory,
346   uschar *sieve_vacation_directory, uschar *sieve_enotify_mailto_owner,
347   uschar *sieve_useraddress, uschar *sieve_subaddress,
348   address_item **generated, uschar **error, error_block **eblockp,
349   int *filtertype)
350 {
351 uschar *data;
352
353 if (rdata->isfile)
354   {
355   int yield = 0;
356   data = rda_get_file_contents(rdata, options, error, &yield);
357   if (data == NULL) return yield;
358   }
359 else data = rdata->string;
360
361 *filtertype = system_filtering? FILTER_EXIM : rda_is_filter(data);
362
363 /* Filter interpretation is done by a general function that is also called from
364 the filter testing option (-bf). There are two versions: one for Exim filtering
365 and one for Sieve filtering. Several features of string expansion may be locked
366 out at sites that don't trust users. This is done by setting flags in
367 expand_forbid that the expander inspects. */
368
369 if (*filtertype != FILTER_FORWARD)
370   {
371   int frc;
372   int old_expand_forbid = expand_forbid;
373
374   DEBUG(D_route) debug_printf("data is %s filter program\n",
375     (*filtertype == FILTER_EXIM)? "an Exim" : "a Sieve");
376
377   /* RDO_FILTER is an "allow" bit */
378
379   if ((options & RDO_FILTER) == 0)
380     {
381     *error = US"filtering not enabled";
382     return FF_ERROR;
383     }
384
385   expand_forbid =
386     (expand_forbid & ~RDO_FILTER_EXPANSIONS) |
387     (options & RDO_FILTER_EXPANSIONS);
388
389   /* RDO_{EXIM,SIEVE}_FILTER are forbid bits */
390
391   if (*filtertype == FILTER_EXIM)
392     {
393     if ((options & RDO_EXIM_FILTER) != 0)
394       {
395       *error = US"Exim filtering not enabled";
396       return FF_ERROR;
397       }
398     frc = filter_interpret(data, options, generated, error);
399     }
400   else
401     {
402     if ((options & RDO_SIEVE_FILTER) != 0)
403       {
404       *error = US"Sieve filtering not enabled";
405       return FF_ERROR;
406       }
407     frc = sieve_interpret(data, options, sieve_vacation_directory,
408       sieve_enotify_mailto_owner, sieve_useraddress, sieve_subaddress,
409       generated, error);
410     }
411
412   expand_forbid = old_expand_forbid;
413   return frc;
414   }
415
416 /* Not a filter script */
417
418 DEBUG(D_route) debug_printf("file is not a filter file\n");
419
420 return parse_forward_list(data,
421   options,                           /* specials that are allowed */
422   generated,                         /* where to hang them */
423   error,                             /* for errors */
424   deliver_domain,                    /* to qualify \name */
425   include_directory,                 /* restrain to directory */
426   eblockp);                          /* for skipped syntax errors */
427 }
428
429
430
431
432 /*************************************************
433 *         Write string down pipe                 *
434 *************************************************/
435
436 /* This function is used for transferring a string down a pipe between
437 processes. If the pointer is NULL, a length of zero is written.
438
439 Arguments:
440   fd         the pipe
441   s          the string
442
443 Returns:     -1 on error, else 0
444 */
445
446 static int
447 rda_write_string(int fd, const uschar *s)
448 {
449 int len = (s == NULL)? 0 : Ustrlen(s) + 1;
450 return (  write(fd, &len, sizeof(int)) != sizeof(int)
451        || (s != NULL  &&  write(fd, s, len) != len)
452        )
453        ? -1 : 0;
454 }
455
456
457
458 /*************************************************
459 *          Read string from pipe                 *
460 *************************************************/
461
462 /* This function is used for receiving a string from a pipe.
463
464 Arguments:
465   fd         the pipe
466   sp         where to put the string
467
468 Returns:     FALSE if data missing
469 */
470
471 static BOOL
472 rda_read_string(int fd, uschar **sp)
473 {
474 int len;
475
476 if (read(fd, &len, sizeof(int)) != sizeof(int)) return FALSE;
477 if (len == 0)
478   *sp = NULL;
479 else
480   /* We know we have enough memory so disable the error on "len" */
481   /* coverity[tainted_data] */
482   if (read(fd, *sp = store_get(len), len) != len) return FALSE;
483 return TRUE;
484 }
485
486
487
488 /*************************************************
489 *         Interpret forward list or filter       *
490 *************************************************/
491
492 /* This function is passed a forward list string (unexpanded) or the name of a
493 file (unexpanded) whose contents are the forwarding list. The list may in fact
494 be a filter program if it starts with "#Exim filter" or "#Sieve filter". Other
495 types of filter, with different inital tag strings, may be introduced in due
496 course.
497
498 The job of the function is to process the forwarding list or filter. It is
499 pulled out into this separate function, because it is used for system filter
500 files as well as from the redirect router.
501
502 If the function is given a uid/gid, it runs a subprocess that passes the
503 results back via a pipe. This provides security for things like :include:s in
504 users' .forward files, and "logwrite" calls in users' filter files. A
505 sub-process is NOT used when:
506
507   . No uid/gid is provided
508   . The input is a string which is not a filter string, and does not contain
509     :include:
510   . The input is a file whose non-existence can be detected in the main
511     process (which is usually running as root).
512
513 Arguments:
514   rdata                     redirect data (file + constraints, or data string)
515   options                   options to pass to the extraction functions,
516                               plus ENOTDIR and EACCES handling bits
517   include_directory         restrain :include: to this directory
518   sieve_vacation_directory  directory passed to sieve_interpret
519   sieve_enotify_mailto_owner passed to sieve_interpret
520   sieve_useraddress         passed to sieve_interpret
521   sieve_subaddress          passed to sieve_interpret
522   ugid                      uid/gid to run under - if NULL, no change
523   generated                 where to hang generated addresses, initially NULL
524   error                     pointer for error message
525   eblockp                   for skipped syntax errors; NULL if no skipping
526   filtertype                set to the type of file:
527                               FILTER_FORWARD => traditional .forward file
528                               FILTER_EXIM    => an Exim filter file
529                               FILTER_SIEVE   => a Sieve filter file
530                             a system filter is always forced to be FILTER_EXIM
531   rname                     router name for error messages in the format
532                               "xxx router" or "system filter"
533
534 Returns:        values from extraction function, or FF_NONEXIST:
535                   FF_DELIVERED     success, a significant action was taken
536                   FF_NOTDELIVERED  success, no significant action
537                   FF_BLACKHOLE     :blackhole:
538                   FF_DEFER         defer requested
539                   FF_FAIL          fail requested
540                   FF_INCLUDEFAIL   some problem with :include:
541                   FF_FREEZE        freeze requested
542                   FF_ERROR         there was a problem
543                   FF_NONEXIST      the file does not exist
544 */
545
546 int
547 rda_interpret(redirect_block *rdata, int options, uschar *include_directory,
548   uschar *sieve_vacation_directory, uschar *sieve_enotify_mailto_owner,
549   uschar *sieve_useraddress, uschar *sieve_subaddress, ugid_block *ugid,
550   address_item **generated, uschar **error, error_block **eblockp,
551   int *filtertype, uschar *rname)
552 {
553 int fd, rc, pfd[2];
554 int yield, status;
555 BOOL had_disaster = FALSE;
556 pid_t pid;
557 uschar *data;
558 uschar *readerror = US"";
559 void (*oldsignal)(int);
560
561 DEBUG(D_route) debug_printf("rda_interpret (%s): %s\n",
562   (rdata->isfile)? "file" : "string", rdata->string);
563
564 /* Do the expansions of the file name or data first, while still privileged. */
565
566 data = expand_string(rdata->string);
567 if (data == NULL)
568   {
569   if (expand_string_forcedfail) return FF_NOTDELIVERED;
570   *error = string_sprintf("failed to expand \"%s\": %s", rdata->string,
571     expand_string_message);
572   return FF_ERROR;
573   }
574 rdata->string = data;
575
576 DEBUG(D_route) debug_printf("expanded: %s\n", data);
577
578 if (rdata->isfile && data[0] != '/')
579   {
580   *error = string_sprintf("\"%s\" is not an absolute path", data);
581   return FF_ERROR;
582   }
583
584 /* If no uid/gid are supplied, or if we have a data string which does not start
585 with #Exim filter or #Sieve filter, and does not contain :include:, do all the
586 work in this process. Note that for a system filter, we always have a file, so
587 the work is done in this process only if no user is supplied. */
588
589 if (!ugid->uid_set ||                         /* Either there's no uid, or */
590     (!rdata->isfile &&                        /* We've got the data, and */
591      rda_is_filter(data) == FILTER_FORWARD && /* It's not a filter script, */
592      Ustrstr(data, ":include:") == NULL))     /* and there's no :include: */
593   {
594   return rda_extract(rdata, options, include_directory,
595     sieve_vacation_directory, sieve_enotify_mailto_owner, sieve_useraddress,
596     sieve_subaddress, generated, error, eblockp, filtertype);
597   }
598
599 /* We need to run the processing code in a sub-process. However, if we can
600 determine the non-existence of a file first, we can decline without having to
601 create the sub-process. */
602
603 if (rdata->isfile && rda_exists(data, error) == FILE_NOT_EXIST)
604   return FF_NONEXIST;
605
606 /* If the file does exist, or we can't tell (non-root mounted NFS directory)
607 we have to create the subprocess to do everything as the given user. The
608 results of processing are passed back via a pipe. */
609
610 if (pipe(pfd) != 0)
611   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "creation of pipe for filter or "
612     ":include: failed for %s: %s", rname, strerror(errno));
613
614 /* Ensure that SIGCHLD is set to SIG_DFL before forking, so that the child
615 process can be waited for. We sometimes get here with it set otherwise. Save
616 the old state for resetting on the wait. Ensure that all cached resources are
617 freed so that the subprocess starts with a clean slate and doesn't interfere
618 with the parent process. */
619
620 oldsignal = signal(SIGCHLD, SIG_DFL);
621 search_tidyup();
622
623 if ((pid = fork()) == 0)
624   {
625   header_line *waslast = header_last;   /* Save last header */
626
627   fd = pfd[pipe_write];
628   (void)close(pfd[pipe_read]);
629   exim_setugid(ugid->uid, ugid->gid, FALSE, rname);
630
631   /* Addresses can get rewritten in filters; if we are not root or the exim
632   user (and we probably are not), turn off rewrite logging, because we cannot
633   write to the log now. */
634
635   if (ugid->uid != root_uid && ugid->uid != exim_uid)
636     {
637     DEBUG(D_rewrite) debug_printf("turned off address rewrite logging (not "
638       "root or exim in this process)\n");
639     BIT_CLEAR(log_selector, log_selector_size, Li_address_rewrite);
640     }
641
642   /* Now do the business */
643
644   yield = rda_extract(rdata, options, include_directory,
645     sieve_vacation_directory, sieve_enotify_mailto_owner, sieve_useraddress,
646     sieve_subaddress, generated, error, eblockp, filtertype);
647
648   /* Pass back whether it was a filter, and the return code and any overall
649   error text via the pipe. */
650
651   if (  write(fd, filtertype, sizeof(int)) != sizeof(int)
652      || write(fd, &yield, sizeof(int)) != sizeof(int)
653      || rda_write_string(fd, *error) != 0
654      )
655     goto bad;
656
657   /* Pass back the contents of any syntax error blocks if we have a pointer */
658
659   if (eblockp != NULL)
660     {
661     error_block *ep;
662     for (ep = *eblockp; ep != NULL; ep = ep->next)
663       if (  rda_write_string(fd, ep->text1) != 0
664          || rda_write_string(fd, ep->text2) != 0
665          )
666         goto bad;
667     if (rda_write_string(fd, NULL) != 0)    /* Indicates end of eblocks */
668       goto bad;
669     }
670
671   /* If this is a system filter, we have to pass back the numbers of any
672   original header lines that were removed, and then any header lines that were
673   added but not subsequently removed. */
674
675   if (system_filtering)
676     {
677     int i = 0;
678     header_line *h;
679     for (h = header_list; h != waslast->next; i++, h = h->next)
680       if (  h->type == htype_old
681          && write(fd, &i, sizeof(i)) != sizeof(i)
682          )
683         goto bad;
684
685     i = -1;
686     if (write(fd, &i, sizeof(i)) != sizeof(i))
687         goto bad;
688
689     while (waslast != header_last)
690       {
691       waslast = waslast->next;
692       if (waslast->type != htype_old)
693         if (  rda_write_string(fd, waslast->text) != 0
694            || write(fd, &(waslast->type), sizeof(waslast->type))
695               != sizeof(waslast->type)
696            )
697           goto bad;
698       }
699     if (rda_write_string(fd, NULL) != 0)    /* Indicates end of added headers */
700       goto bad;
701     }
702
703   /* Write the contents of the $n variables */
704
705   if (write(fd, filter_n, sizeof(filter_n)) != sizeof(filter_n))
706     goto bad;
707
708   /* If the result was DELIVERED or NOTDELIVERED, we pass back the generated
709   addresses, and their associated information, through the pipe. This is
710   just tedious, but it seems to be the only safe way. We do this also for
711   FAIL and FREEZE, because a filter is allowed to set up deliveries that
712   are honoured before freezing or failing. */
713
714   if (yield == FF_DELIVERED || yield == FF_NOTDELIVERED ||
715       yield == FF_FAIL || yield == FF_FREEZE)
716     {
717     address_item *addr;
718     for (addr = *generated; addr != NULL; addr = addr->next)
719       {
720       int reply_options = 0;
721
722       if (  rda_write_string(fd, addr->address) != 0
723          || write(fd, &(addr->mode), sizeof(addr->mode))
724             != sizeof(addr->mode)
725          || write(fd, &(addr->flags), sizeof(addr->flags))
726             != sizeof(addr->flags)
727          || rda_write_string(fd, addr->prop.errors_address) != 0
728          )
729         goto bad;
730
731       if (addr->pipe_expandn != NULL)
732         {
733         uschar **pp;
734         for (pp = addr->pipe_expandn; *pp != NULL; pp++)
735           if (rda_write_string(fd, *pp) != 0)
736             goto bad;
737         }
738       if (rda_write_string(fd, NULL) != 0)
739         goto bad;
740
741       if (addr->reply == NULL)
742         {
743         if (write(fd, &reply_options, sizeof(int)) != sizeof(int))    /* 0 means no reply */
744           goto bad;
745         }
746       else
747         {
748         reply_options |= REPLY_EXISTS;
749         if (addr->reply->file_expand) reply_options |= REPLY_EXPAND;
750         if (addr->reply->return_message) reply_options |= REPLY_RETURN;
751         if (  write(fd, &reply_options, sizeof(int)) != sizeof(int)
752            || write(fd, &(addr->reply->expand_forbid), sizeof(int))
753               != sizeof(int)
754            || write(fd, &(addr->reply->once_repeat), sizeof(time_t))
755               != sizeof(time_t)
756            || rda_write_string(fd, addr->reply->to) != 0
757            || rda_write_string(fd, addr->reply->cc) != 0
758            || rda_write_string(fd, addr->reply->bcc) != 0
759            || rda_write_string(fd, addr->reply->from) != 0
760            || rda_write_string(fd, addr->reply->reply_to) != 0
761            || rda_write_string(fd, addr->reply->subject) != 0
762            || rda_write_string(fd, addr->reply->headers) != 0
763            || rda_write_string(fd, addr->reply->text) != 0
764            || rda_write_string(fd, addr->reply->file) != 0
765            || rda_write_string(fd, addr->reply->logfile) != 0
766            || rda_write_string(fd, addr->reply->oncelog) != 0
767            )
768           goto bad;
769         }
770       }
771
772     if (rda_write_string(fd, NULL) != 0)   /* Marks end of addresses */
773       goto bad;
774     }
775
776   /* OK, this process is now done. Free any cached resources. Must use _exit()
777   and not exit() !! */
778
779 out:
780   (void)close(fd);
781   search_tidyup();
782   _exit(0);
783
784 bad:
785   DEBUG(D_rewrite) debug_printf("rda_interpret: failed write to pipe\n");
786   goto out;
787   }
788
789 /* Back in the main process: panic if the fork did not succeed. */
790
791 if (pid < 0)
792   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "fork failed for %s", rname);
793
794 /* Read the pipe to get the data from the filter/forward. Our copy of the
795 writing end must be closed first, as otherwise read() won't return zero on an
796 empty pipe. Afterwards, close the reading end. */
797
798 (void)close(pfd[pipe_write]);
799
800 /* Read initial data, including yield and contents of *error */
801
802 fd = pfd[pipe_read];
803 if (read(fd, filtertype, sizeof(int)) != sizeof(int) ||
804     read(fd, &yield, sizeof(int)) != sizeof(int) ||
805     !rda_read_string(fd, error)) goto DISASTER;
806
807 /* Read the contents of any syntax error blocks if we have a pointer */
808
809 if (eblockp)
810   {
811   error_block *e;
812   error_block **p;
813   for (p = eblockp; ; p = &e->next)
814     {
815     uschar *s;
816     if (!rda_read_string(fd, &s)) goto DISASTER;
817     if (!s) break;
818     e = store_get(sizeof(error_block));
819     e->next = NULL;
820     e->text1 = s;
821     if (!rda_read_string(fd, &s)) goto DISASTER;
822     e->text2 = s;
823     *p = e;
824     }
825   }
826
827 /* If this is a system filter, read the identify of any original header lines
828 that were removed, and then read data for any new ones that were added. */
829
830 if (system_filtering)
831   {
832   int hn = 0;
833   header_line *h = header_list;
834
835   for (;;)
836     {
837     int n;
838     if (read(fd, &n, sizeof(int)) != sizeof(int)) goto DISASTER;
839     if (n < 0) break;
840     while (hn < n)
841       {
842       hn++;
843       if (!(h = h->next)) goto DISASTER_NO_HEADER;
844       }
845     h->type = htype_old;
846     }
847
848   for (;;)
849     {
850     uschar *s;
851     int type;
852     if (!rda_read_string(fd, &s)) goto DISASTER;
853     if (!s) break;
854     if (read(fd, &type, sizeof(type)) != sizeof(type)) goto DISASTER;
855     header_add(type, "%s", s);
856     }
857   }
858
859 /* Read the values of the $n variables */
860
861 if (read(fd, filter_n, sizeof(filter_n)) != sizeof(filter_n)) goto DISASTER;
862
863 /* If the yield is DELIVERED, NOTDELIVERED, FAIL, or FREEZE there may follow
864 addresses and data to go with them. Keep them in the same order in the
865 generated chain. */
866
867 if (yield == FF_DELIVERED || yield == FF_NOTDELIVERED ||
868     yield == FF_FAIL || yield == FF_FREEZE)
869   {
870   address_item **nextp = generated;
871
872   for (;;)
873     {
874     int i, reply_options;
875     address_item *addr;
876     uschar *recipient;
877     uschar *expandn[EXPAND_MAXN + 2];
878
879     /* First string is the address; NULL => end of addresses */
880
881     if (!rda_read_string(fd, &recipient)) goto DISASTER;
882     if (recipient == NULL) break;
883
884     /* Hang on the end of the chain */
885
886     addr = deliver_make_addr(recipient, FALSE);
887     *nextp = addr;
888     nextp = &(addr->next);
889
890     /* Next comes the mode and the flags fields */
891
892     if (read(fd, &(addr->mode), sizeof(addr->mode)) != sizeof(addr->mode) ||
893         read(fd, &(addr->flags), sizeof(addr->flags)) != sizeof(addr->flags) ||
894         !rda_read_string(fd, &(addr->prop.errors_address))) goto DISASTER;
895
896     /* Next comes a possible setting for $thisaddress and any numerical
897     variables for pipe expansion, terminated by a NULL string. The maximum
898     number of numericals is EXPAND_MAXN. Note that we put filter_thisaddress
899     into the zeroth item in the vector - this is sorted out inside the pipe
900     transport. */
901
902     for (i = 0; i < EXPAND_MAXN + 1; i++)
903       {
904       uschar *temp;
905       if (!rda_read_string(fd, &temp)) goto DISASTER;
906       if (i == 0) filter_thisaddress = temp;           /* Just in case */
907       expandn[i] = temp;
908       if (temp == NULL) break;
909       }
910
911     if (i > 0)
912       {
913       addr->pipe_expandn = store_get((i+1) * sizeof(uschar *));
914       addr->pipe_expandn[i] = NULL;
915       while (--i >= 0) addr->pipe_expandn[i] = expandn[i];
916       }
917
918     /* Then an int containing reply options; zero => no reply data. */
919
920     if (read(fd, &reply_options, sizeof(int)) != sizeof(int)) goto DISASTER;
921     if ((reply_options & REPLY_EXISTS) != 0)
922       {
923       addr->reply = store_get(sizeof(reply_item));
924
925       addr->reply->file_expand = (reply_options & REPLY_EXPAND) != 0;
926       addr->reply->return_message = (reply_options & REPLY_RETURN) != 0;
927
928       if (read(fd,&(addr->reply->expand_forbid),sizeof(int)) !=
929             sizeof(int) ||
930           read(fd,&(addr->reply->once_repeat),sizeof(time_t)) !=
931             sizeof(time_t) ||
932           !rda_read_string(fd, &(addr->reply->to)) ||
933           !rda_read_string(fd, &(addr->reply->cc)) ||
934           !rda_read_string(fd, &(addr->reply->bcc)) ||
935           !rda_read_string(fd, &(addr->reply->from)) ||
936           !rda_read_string(fd, &(addr->reply->reply_to)) ||
937           !rda_read_string(fd, &(addr->reply->subject)) ||
938           !rda_read_string(fd, &(addr->reply->headers)) ||
939           !rda_read_string(fd, &(addr->reply->text)) ||
940           !rda_read_string(fd, &(addr->reply->file)) ||
941           !rda_read_string(fd, &(addr->reply->logfile)) ||
942           !rda_read_string(fd, &(addr->reply->oncelog)))
943         goto DISASTER;
944       }
945     }
946   }
947
948 /* All data has been transferred from the sub-process. Reap it, close the
949 reading end of the pipe, and we are done. */
950
951 WAIT_EXIT:
952 while ((rc = wait(&status)) != pid)
953   {
954   if (rc < 0 && errno == ECHILD)      /* Process has vanished */
955     {
956     log_write(0, LOG_MAIN, "redirection process %d vanished unexpectedly", pid);
957     goto FINAL_EXIT;
958     }
959   }
960
961 DEBUG(D_route)
962   debug_printf("rda_interpret: subprocess yield=%d error=%s\n", yield, *error);
963
964 if (had_disaster)
965   {
966   *error = string_sprintf("internal problem in %s: failure to transfer "
967     "data from subprocess: status=%04x%s%s%s", rname,
968     status, readerror,
969     (*error == NULL)? US"" : US": error=",
970     (*error == NULL)? US"" : *error);
971   log_write(0, LOG_MAIN|LOG_PANIC, "%s", *error);
972   }
973 else if (status != 0)
974   {
975   log_write(0, LOG_MAIN|LOG_PANIC, "internal problem in %s: unexpected status "
976     "%04x from redirect subprocess (but data correctly received)", rname,
977     status);
978   }
979
980 FINAL_EXIT:
981 (void)close(fd);
982 signal(SIGCHLD, oldsignal);   /* restore */
983 return yield;
984
985
986 /* Come here if the data indicates removal of a header that we can't find */
987
988 DISASTER_NO_HEADER:
989 readerror = US" readerror=bad header identifier";
990 had_disaster = TRUE;
991 yield = FF_ERROR;
992 goto WAIT_EXIT;
993
994 /* Come here is there's a shambles in transferring the data over the pipe. The
995 value of errno should still be set. */
996
997 DISASTER:
998 readerror = string_sprintf(" readerror='%s'", strerror(errno));
999 had_disaster = TRUE;
1000 yield = FF_ERROR;
1001 goto WAIT_EXIT;
1002 }
1003
1004 /* End of rda.c */