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