Michael Haardt's patch for support for :user and :subaddress in Sieve
[exim.git] / src / src / rda.c
1 /* $Cambridge: exim/src/src/rda.c,v 1.5 2005/04/06 14:40:24 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 /* 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 != 0; s++, tag++)
47   {
48   if (*tag == ' ')
49     {
50     while (*s == ' ' || *s == '\t') s++;
51     s--;
52     }
53   else 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 while (isspace(*s)) 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 uschar *slash;
102 struct stat statbuf;
103
104 if ((rc = Ustat(filename, &statbuf)) >= 0) return FILE_EXIST;
105 saved_errno = errno;
106
107 Ustrncpy(big_buffer, filename, big_buffer_size - 3);
108 sigalrm_seen = FALSE;
109
110 if (saved_errno == ENOENT)
111   {
112   slash = Ustrrchr(big_buffer, '/');
113   Ustrcpy(slash+1, ".");
114
115   alarm(30);
116   rc = Ustat(big_buffer, &statbuf);
117   if (rc != 0 && errno == EACCES && !sigalrm_seen)
118     {
119     *slash = 0;
120     rc = Ustat(big_buffer, &statbuf);
121     }
122   saved_errno = errno;
123   alarm(0);
124
125   DEBUG(D_route) debug_printf("stat(%s)=%d\n", big_buffer, rc);
126   }
127
128 if (sigalrm_seen || rc != 0)
129   {
130   *error = string_sprintf("failed to stat %s (%s)", big_buffer,
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(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 /* Attempt to open the file. If it appears not to exist, check up on the
181 containing directory by statting it. If the directory does not exist, we treat
182 this situation as an error (which will cause delivery to defer); otherwise we
183 pass back FF_NONEXIST, which causes the redirect router to decline.
184
185 However, if the ignore_enotdir option is set (to ignore "something on the
186 path is not a directory" errors), the right behaviour seems to be not to do the
187 directory test. */
188
189 fwd = Ufopen(filename, "rb");
190 if (fwd == NULL)
191   {
192   switch(errno)
193     {
194     case ENOENT:          /* File does not exist */
195     DEBUG(D_route) debug_printf("%s does not exist\n%schecking parent directory\n",
196       filename,
197       ((options & RDO_ENOTDIR) != 0)? "ignore_enotdir set => skip " : "");
198     *yield = (((options & RDO_ENOTDIR) != 0) ||
199               rda_exists(filename, error) == FILE_NOT_EXIST)?
200       FF_NONEXIST : FF_ERROR;
201     return NULL;
202
203     case ENOTDIR:         /* Something on the path isn't a directory */
204     if ((options & RDO_ENOTDIR) == 0) goto DEFAULT_ERROR;
205     DEBUG(D_route) debug_printf("non-directory on path %s: file assumed not to "
206       "exist\n", filename);
207     *yield = FF_NONEXIST;
208     return NULL;
209
210     case EACCES:           /* Permission denied */
211     if ((options & RDO_EACCES) == 0) goto DEFAULT_ERROR;
212     DEBUG(D_route) debug_printf("permission denied for %s: file assumed not to "
213       "exist\n", filename);
214     *yield = FF_NONEXIST;
215     return NULL;
216
217     DEFAULT_ERROR:
218     default:
219     *error = string_open_failed(errno, "%s", filename);
220     *yield = FF_ERROR;
221     return NULL;
222     }
223   }
224
225 /* Check that we have a regular file. */
226
227 if (fstat(fileno(fwd), &statbuf) != 0)
228   {
229   *error = string_sprintf("failed to stat %s: %s", filename, strerror(errno));
230   goto ERROR_RETURN;
231   }
232
233 if ((statbuf.st_mode & S_IFMT) != S_IFREG)
234   {
235   *error = string_sprintf("%s is not a regular file", filename);
236   goto ERROR_RETURN;
237   }
238
239 /* Check for unwanted mode bits */
240
241 if ((statbuf.st_mode & rdata->modemask) != 0)
242   {
243   *error = string_sprintf("bad mode (0%o) for %s: 0%o bit(s) unexpected",
244     statbuf.st_mode, filename, statbuf.st_mode & rdata->modemask);
245   goto ERROR_RETURN;
246   }
247
248 /* Check the file owner and file group if required to do so. */
249
250 if (!uid_ok)
251   {
252   if (rdata->pw != NULL && statbuf.st_uid == rdata->pw->pw_uid)
253     uid_ok = TRUE;
254   else if (rdata->owners != NULL)
255     {
256     int i;
257     for (i = 1; i <= (int)(rdata->owners[0]); i++)
258       if (rdata->owners[i] == statbuf.st_uid) { uid_ok = TRUE; break; }
259     }
260   }
261
262 if (!gid_ok)
263   {
264   if (rdata->pw != NULL && statbuf.st_gid == rdata->pw->pw_gid)
265     gid_ok = TRUE;
266   else if (rdata->owngroups != NULL)
267     {
268     int i;
269     for (i = 1; i <= (int)(rdata->owngroups[0]); i++)
270       if (rdata->owngroups[i] == statbuf.st_gid) { gid_ok = TRUE; break; }
271     }
272   }
273
274 if (!uid_ok || !gid_ok)
275   {
276   *error = string_sprintf("bad %s for %s", uid_ok? "group" : "owner", filename);
277   goto ERROR_RETURN;
278   }
279
280 /* Put an upper limit on the size of the file, just to stop silly people
281 feeding in ridiculously large files, which can easily be created by making
282 files that have holes in them. */
283
284 if (statbuf.st_size > MAX_FILTER_SIZE)
285   {
286   *error = string_sprintf("%s is too big (max %d)", filename, MAX_FILTER_SIZE);
287   goto ERROR_RETURN;
288   }
289
290 /* Read the file in one go in order to minimize the time we have it open. */
291
292 filebuf = store_get(statbuf.st_size + 1);
293
294 if (fread(filebuf, 1, statbuf.st_size, fwd) != statbuf.st_size)
295   {
296   *error = string_sprintf("error while reading %s: %s",
297     filename, strerror(errno));
298   goto ERROR_RETURN;
299   }
300 filebuf[statbuf.st_size] = 0;
301
302 /* Don't pass statbuf.st_size directly to debug_printf. On some systems it
303 is a long, which may not be the same as an int. */
304
305 DEBUG(D_route)
306   {
307   int size = (int)statbuf.st_size;
308   debug_printf("%d bytes read from %s\n", size, filename);
309   }
310
311 fclose(fwd);
312 return filebuf;
313
314 /* Return an error: the string is already set up. */
315
316 ERROR_RETURN:
317 *yield = FF_ERROR;
318 fclose(fwd);
319 return NULL;
320 }
321
322
323
324 /*************************************************
325 *      Extract info from list or filter          *
326 *************************************************/
327
328 /* This function calls the appropriate function to extract addresses from a
329 forwarding list, or to run a filter file and get addresses from there.
330
331 Arguments:
332   rdata                     the redirection block
333   options                   the options bits
334   include_directory         restrain to this directory
335   sieve_vacation_directory  passed to sieve_interpret
336   sieve_useraddress         passed to sieve_interpret
337   sieve_subaddress          passed to sieve_interpret
338   generated                 where to hang generated addresses
339   error                     for error messages
340   eblockp                   for details of skipped syntax errors
341                               (NULL => no skip)
342   filtertype                set to the filter type:
343                               FILTER_FORWARD => a traditional .forward file
344                               FILTER_EXIM    => an Exim filter file
345                               FILTER_SIEVE   => a Sieve filter file
346                             a system filter is always forced to be FILTER_EXIM
347
348 Returns:                    a suitable return for rda_interpret()
349 */
350
351 static int
352 rda_extract(redirect_block *rdata, int options, uschar *include_directory,
353   uschar *sieve_vacation_directory, uschar *sieve_useraddress,
354   uschar *sieve_subaddress, address_item **generated, uschar **error,
355   error_block **eblockp, int *filtertype)
356 {
357 uschar *data;
358
359 if (rdata->isfile)
360   {
361   int yield;
362   data = rda_get_file_contents(rdata, options, error, &yield);
363   if (data == NULL) return yield;
364   }
365 else data = rdata->string;
366
367 *filtertype = system_filtering? FILTER_EXIM : rda_is_filter(data);
368
369 /* Filter interpretation is done by a general function that is also called from
370 the filter testing option (-bf). There are two versions: one for Exim filtering
371 and one for Sieve filtering. Several features of string expansion may be locked
372 out at sites that don't trust users. This is done by setting flags in
373 expand_forbid that the expander inspects. */
374
375 if (*filtertype != FILTER_FORWARD)
376   {
377   int frc;
378   int old_expand_forbid = expand_forbid;
379
380   DEBUG(D_route) debug_printf("data is %s filter program\n",
381     (*filtertype == FILTER_EXIM)? "an Exim" : "a Sieve");
382
383   /* RDO_FILTER is an "allow" bit */
384
385   if ((options & RDO_FILTER) == 0)
386     {
387     *error = US"filtering not enabled";
388     return FF_ERROR;
389     }
390
391   expand_forbid =
392     (expand_forbid & ~RDO_FILTER_EXPANSIONS) |
393     (options & RDO_FILTER_EXPANSIONS);
394
395   /* RDO_{EXIM,SIEVE}_FILTER are forbid bits */
396
397   if (*filtertype == FILTER_EXIM)
398     {
399     if ((options & RDO_EXIM_FILTER) != 0)
400       {
401       *error = US"Exim filtering not enabled";
402       return FF_ERROR;
403       }
404     frc = filter_interpret(data, options, generated, error);
405     }
406   else
407     {
408     if ((options & RDO_SIEVE_FILTER) != 0)
409       {
410       *error = US"Sieve filtering not enabled";
411       return FF_ERROR;
412       }
413     frc = sieve_interpret(data, options, sieve_vacation_directory,
414       sieve_useraddress, sieve_subaddress, generated, error);
415     }
416
417   expand_forbid = old_expand_forbid;
418   return frc;
419   }
420
421 /* Not a filter script */
422
423 DEBUG(D_route) debug_printf("file is not a filter file\n");
424
425 return parse_forward_list(data,
426   options,                           /* specials that are allowed */
427   generated,                         /* where to hang them */
428   error,                             /* for errors */
429   deliver_domain,                    /* to qualify \name */
430   include_directory,                 /* restrain to directory */
431   eblockp);                          /* for skipped syntax errors */
432 }
433
434
435
436
437 /*************************************************
438 *         Write string down pipe                 *
439 *************************************************/
440
441 /* This function is used for tranferring a string down a pipe between
442 processes. If the pointer is NULL, a length of zero is written.
443
444 Arguments:
445   fd         the pipe
446   s          the string
447
448 Returns:     nothing
449 */
450
451 static void
452 rda_write_string(int fd, uschar *s)
453 {
454 int len = (s == NULL)? 0 : Ustrlen(s) + 1;
455 write(fd, &len, sizeof(int));
456 if (s != NULL) write(fd, s, len);
457 }
458
459
460
461 /*************************************************
462 *          Read string from pipe                 *
463 *************************************************/
464
465 /* This function is used for receiving a string from a pipe.
466
467 Arguments:
468   fd         the pipe
469   sp         where to put the string
470
471 Returns:     FALSE if data missing
472 */
473
474 static BOOL
475 rda_read_string(int fd, uschar **sp)
476 {
477 int len;
478
479 if (read(fd, &len, sizeof(int)) != sizeof(int)) return FALSE;
480 if (len == 0) *sp = NULL; else
481   {
482   *sp = store_get(len);
483   if (read(fd, *sp, len) != len) return FALSE;
484   }
485 return TRUE;
486 }
487
488
489
490 /*************************************************
491 *         Interpret forward list or filter       *
492 *************************************************/
493
494 /* This function is passed a forward list string (unexpanded) or the name of a
495 file (unexpanded) whose contents are the forwarding list. The list may in fact
496 be a filter program if it starts with "#Exim filter" or "#Sieve filter". Other
497 types of filter, with different inital tag strings, may be introduced in due
498 course.
499
500 The job of the function is to process the forwarding list or filter. It is
501 pulled out into this separate function, because it is used for system filter
502 files as well as from the redirect router.
503
504 If the function is given a uid/gid, it runs a subprocess that passes the
505 results back via a pipe. This provides security for things like :include:s in
506 users' .forward files, and "logwrite" calls in users' filter files. A
507 sub-process is NOT used when:
508
509   . No uid/gid is provided
510   . The input is a string which is not a filter string, and does not contain
511     :include:
512   . The input is a file whose non-existence can be detected in the main
513     process (which is usually running as root).
514
515 Arguments:
516   rdata                     redirect data (file + constraints, or data string)
517   options                   options to pass to the extraction functions,
518                               plus ENOTDIR and EACCES handling bits
519   include_directory         restrain :include: to this directory
520   sieve_vacation_directory  directory passed to sieve_interpret()
521   sieve_useraddress         passed to sieve_interpret
522   sieve_subaddress          passed to sieve_interpret
523   ugid                      uid/gid to run under - if NULL, no change
524   generated                 where to hang generated addresses, initially NULL
525   error                     pointer for error message
526   eblockp                   for skipped syntax errors; NULL if no skipping
527   filtertype                set to the type of file:
528                               FILTER_FORWARD => traditional .forward file
529                               FILTER_EXIM    => an Exim filter file
530                               FILTER_SIEVE   => a Sieve filter file
531                             a system filter is always forced to be FILTER_EXIM
532   rname                     router name for error messages in the format
533                               "xxx router" or "system filter"
534
535 Returns:        values from extraction function, or FF_NONEXIST:
536                   FF_DELIVERED     success, a significant action was taken
537                   FF_NOTDELIVERED  success, no significant action
538                   FF_BLACKHOLE     :blackhole:
539                   FF_DEFER         defer requested
540                   FF_FAIL          fail requested
541                   FF_INCLUDEFAIL   some problem with :include:
542                   FF_FREEZE        freeze requested
543                   FF_ERROR         there was a problem
544                   FF_NONEXIST      the file does not exist
545 */
546
547 int
548 rda_interpret(redirect_block *rdata, int options, uschar *include_directory,
549   uschar *sieve_vacation_directory, uschar *sieve_useraddress,
550   uschar *sieve_subaddress, ugid_block *ugid, address_item **generated,
551   uschar **error, error_block **eblockp, 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_useraddress, sieve_subaddress,
596     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. */
617
618 oldsignal = signal(SIGCHLD, SIG_DFL);
619 if ((pid = fork()) == 0)
620   {
621   header_line *waslast = header_last;   /* Save last header */
622
623   fd = pfd[pipe_write];
624   close(pfd[pipe_read]);
625   exim_setugid(ugid->uid, ugid->gid, FALSE, rname);
626
627   /* Addresses can get rewritten in filters; if we are not root or the exim
628   user (and we probably are not), turn off rewrite logging, because we cannot
629   write to the log now. */
630
631   if (ugid->uid != root_uid && ugid->uid != exim_uid)
632     {
633     DEBUG(D_rewrite) debug_printf("turned off address rewrite logging (not "
634       "root or exim in this process)\n");
635     log_write_selector &= ~L_address_rewrite;
636     }
637
638   /* Now do the business */
639
640   yield = rda_extract(rdata, options, include_directory,
641     sieve_vacation_directory, sieve_useraddress, sieve_subaddress, generated,
642     error, eblockp, filtertype);
643
644   /* Pass back whether it was a filter, and the return code and any overall
645   error text via the pipe. */
646
647   write(fd, filtertype, sizeof(int));
648   write(fd, &yield, sizeof(int));
649   rda_write_string(fd, *error);
650
651   /* Pass back the contents of any syntax error blocks if we have a pointer */
652
653   if (eblockp != NULL)
654     {
655     error_block *ep;
656     for (ep = *eblockp; ep != NULL; ep = ep->next)
657       {
658       rda_write_string(fd, ep->text1);
659       rda_write_string(fd, ep->text2);
660       }
661     rda_write_string(fd, NULL);    /* Indicates end of eblocks */
662     }
663
664   /* If this is a system filter, we have to pass back the numbers of any
665   original header lines that were removed, and then any header lines that were
666   added but not subsequently removed. */
667
668   if (system_filtering)
669     {
670     int i = 0;
671     header_line *h;
672     for (h = header_list; h != waslast->next; i++, h = h->next)
673       {
674       if (h->type == htype_old) write(fd, &i, sizeof(i));
675       }
676     i = -1;
677     write(fd, &i, sizeof(i));
678
679     while (waslast != header_last)
680       {
681       waslast = waslast->next;
682       if (waslast->type != htype_old)
683         {
684         rda_write_string(fd, waslast->text);
685         write(fd, &(waslast->type), sizeof(waslast->type));
686         }
687       }
688     rda_write_string(fd, NULL);    /* Indicates end of added headers */
689     }
690
691   /* Write the contents of the $n variables */
692
693   write(fd, filter_n, sizeof(filter_n));
694
695   /* If the result was DELIVERED or NOTDELIVERED, we pass back the generated
696   addresses, and their associated information, through the pipe. This is
697   just tedious, but it seems to be the only safe way. We do this also for
698   FAIL and FREEZE, because a filter is allowed to set up deliveries that
699   are honoured before freezing or failing. */
700
701   if (yield == FF_DELIVERED || yield == FF_NOTDELIVERED ||
702       yield == FF_FAIL || yield == FF_FREEZE)
703     {
704     address_item *addr;
705     for (addr = *generated; addr != NULL; addr = addr->next)
706       {
707       int reply_options = 0;
708
709       rda_write_string(fd, addr->address);
710       write(fd, &(addr->mode), sizeof(addr->mode));
711       write(fd, &(addr->flags), sizeof(addr->flags));
712       rda_write_string(fd, addr->p.errors_address);
713
714       if (addr->pipe_expandn != NULL)
715         {
716         uschar **pp;
717         for (pp = addr->pipe_expandn; *pp != NULL; pp++)
718           rda_write_string(fd, *pp);
719         }
720       rda_write_string(fd, NULL);
721
722       if (addr->reply == NULL)
723         write(fd, &reply_options, sizeof(int));    /* 0 means no reply */
724       else
725         {
726         reply_options |= REPLY_EXISTS;
727         if (addr->reply->file_expand) reply_options |= REPLY_EXPAND;
728         if (addr->reply->return_message) reply_options |= REPLY_RETURN;
729         write(fd, &reply_options, sizeof(int));
730         write(fd, &(addr->reply->expand_forbid), sizeof(int));
731         write(fd, &(addr->reply->once_repeat), sizeof(time_t));
732         rda_write_string(fd, addr->reply->to);
733         rda_write_string(fd, addr->reply->cc);
734         rda_write_string(fd, addr->reply->bcc);
735         rda_write_string(fd, addr->reply->from);
736         rda_write_string(fd, addr->reply->reply_to);
737         rda_write_string(fd, addr->reply->subject);
738         rda_write_string(fd, addr->reply->headers);
739         rda_write_string(fd, addr->reply->text);
740         rda_write_string(fd, addr->reply->file);
741         rda_write_string(fd, addr->reply->logfile);
742         rda_write_string(fd, addr->reply->oncelog);
743         }
744       }
745
746     rda_write_string(fd, NULL);   /* Marks end of addresses */
747     }
748
749   /* OK, this process is now done. Must use _exit() and not exit() !! */
750
751   close(fd);
752   _exit(0);
753   }
754
755 /* Back in the main process: panic if the fork did not succeed. */
756
757 if (pid < 0)
758   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "fork failed for %s", rname);
759
760 /* Read the pipe to get the data from the filter/forward. Our copy of the
761 writing end must be closed first, as otherwise read() won't return zero on an
762 empty pipe. Afterwards, close the reading end. */
763
764 close(pfd[pipe_write]);
765
766 /* Read initial data, including yield and contents of *error */
767
768 fd = pfd[pipe_read];
769 if (read(fd, filtertype, sizeof(int)) != sizeof(int) ||
770     read(fd, &yield, sizeof(int)) != sizeof(int) ||
771     !rda_read_string(fd, error)) goto DISASTER;
772
773 DEBUG(D_route)
774   debug_printf("rda_interpret: subprocess yield=%d error=%s\n", yield, *error);
775
776 /* Read the contents of any syntax error blocks if we have a pointer */
777
778 if (eblockp != NULL)
779   {
780   uschar *s;
781   error_block *e;
782   error_block **p = eblockp;
783   for (;;)
784     {
785     if (!rda_read_string(fd, &s)) goto DISASTER;
786     if (s == NULL) break;
787     e = store_get(sizeof(error_block));
788     e->next = NULL;
789     e->text1 = s;
790     if (!rda_read_string(fd, &s)) goto DISASTER;
791     e->text2 = s;
792     *p = e;
793     p = &(e->next);
794     }
795   }
796
797 /* If this is a system filter, read the identify of any original header lines
798 that were removed, and then read data for any new ones that were added. */
799
800 if (system_filtering)
801   {
802   int hn = 0;
803   header_line *h = header_list;
804
805   for (;;)
806     {
807     int n;
808     if (read(fd, &n, sizeof(int)) != sizeof(int)) goto DISASTER;
809     if (n < 0) break;
810     while (hn < n)
811       {
812       hn++;
813       h = h->next;
814       if (h == NULL) goto DISASTER_NO_HEADER;
815       }
816     h->type = htype_old;
817     }
818
819   for (;;)
820     {
821     uschar *s;
822     int type;
823     if (!rda_read_string(fd, &s)) goto DISASTER;
824     if (s == NULL) break;
825     if (read(fd, &type, sizeof(type)) != sizeof(type)) goto DISASTER;
826     header_add(type, "%s", s);
827     }
828   }
829
830 /* Read the values of the $n variables */
831
832 if (read(fd, filter_n, sizeof(filter_n)) != sizeof(filter_n)) goto DISASTER;
833
834 /* If the yield is DELIVERED, NOTDELIVERED, FAIL, or FREEZE there may follow
835 addresses and data to go with them. Keep them in the same order in the
836 generated chain. */
837
838 if (yield == FF_DELIVERED || yield == FF_NOTDELIVERED ||
839     yield == FF_FAIL || yield == FF_FREEZE)
840   {
841   address_item **nextp = generated;
842
843   for (;;)
844     {
845     int i, reply_options;
846     address_item *addr;
847     uschar *recipient;
848     uschar *expandn[EXPAND_MAXN + 2];
849
850     /* First string is the address; NULL => end of addresses */
851
852     if (!rda_read_string(fd, &recipient)) goto DISASTER;
853     if (recipient == NULL) break;
854
855     /* Hang on the end of the chain */
856
857     addr = deliver_make_addr(recipient, FALSE);
858     *nextp = addr;
859     nextp = &(addr->next);
860
861     /* Next comes the mode and the flags fields */
862
863     if (read(fd, &(addr->mode), sizeof(addr->mode)) != sizeof(addr->mode) ||
864         read(fd, &(addr->flags), sizeof(addr->flags)) != sizeof(addr->flags) ||
865         !rda_read_string(fd, &(addr->p.errors_address))) goto DISASTER;
866
867     /* Next comes a possible setting for $thisaddress and any numerical
868     variables for pipe expansion, terminated by a NULL string. The maximum
869     number of numericals is EXPAND_MAXN. Note that we put filter_thisaddress
870     into the zeroth item in the vector - this is sorted out inside the pipe
871     transport. */
872
873     for (i = 0; i < EXPAND_MAXN + 1; i++)
874       {
875       uschar *temp;
876       if (!rda_read_string(fd, &temp)) goto DISASTER;
877       if (i == 0) filter_thisaddress = temp;           /* Just in case */
878       expandn[i] = temp;
879       if (temp == NULL) break;
880       }
881
882     if (i > 0)
883       {
884       addr->pipe_expandn = store_get((i+1) * sizeof(uschar **));
885       addr->pipe_expandn[i] = NULL;
886       while (--i >= 0) addr->pipe_expandn[i] = expandn[i];
887       }
888
889     /* Then an int containing reply options; zero => no reply data. */
890
891     if (read(fd, &reply_options, sizeof(int)) != sizeof(int)) goto DISASTER;
892     if ((reply_options & REPLY_EXISTS) != 0)
893       {
894       addr->reply = store_get(sizeof(reply_item));
895
896       addr->reply->file_expand = (reply_options & REPLY_EXPAND) != 0;
897       addr->reply->return_message = (reply_options & REPLY_RETURN) != 0;
898
899       if (read(fd,&(addr->reply->expand_forbid),sizeof(int)) !=
900             sizeof(int) ||
901           read(fd,&(addr->reply->once_repeat),sizeof(time_t)) !=
902             sizeof(time_t) ||
903           !rda_read_string(fd, &(addr->reply->to)) ||
904           !rda_read_string(fd, &(addr->reply->cc)) ||
905           !rda_read_string(fd, &(addr->reply->bcc)) ||
906           !rda_read_string(fd, &(addr->reply->from)) ||
907           !rda_read_string(fd, &(addr->reply->reply_to)) ||
908           !rda_read_string(fd, &(addr->reply->subject)) ||
909           !rda_read_string(fd, &(addr->reply->headers)) ||
910           !rda_read_string(fd, &(addr->reply->text)) ||
911           !rda_read_string(fd, &(addr->reply->file)) ||
912           !rda_read_string(fd, &(addr->reply->logfile)) ||
913           !rda_read_string(fd, &(addr->reply->oncelog)))
914         goto DISASTER;
915       }
916     }
917   }
918
919 /* All data has been transferred from the sub-process. Reap it, close the
920 reading end of the pipe, and we are done. */
921
922 WAIT_EXIT:
923 while ((rc = wait(&status)) != pid)
924   {
925   if (rc < 0 && errno == ECHILD)      /* Process has vanished */
926     {
927     log_write(0, LOG_MAIN, "redirection process %d vanished unexpectedly", pid);
928     goto FINAL_EXIT;
929     }
930   }
931
932 if (had_disaster)
933   {
934   *error = string_sprintf("internal problem in %s: failure to transfer "
935     "data from subprocess: status=%04x%s%s%s", rname,
936     status, readerror,
937     (*error == NULL)? US"" : US": error=",
938     (*error == NULL)? US"" : *error);
939   log_write(0, LOG_MAIN|LOG_PANIC, "%s", *error);
940   }
941 else if (status != 0)
942   {
943   log_write(0, LOG_MAIN|LOG_PANIC, "internal problem in %s: unexpected status "
944     "%04x from redirect subprocess (but data correctly received)", rname,
945     status);
946   }
947
948 FINAL_EXIT:
949 close(fd);
950 signal(SIGCHLD, oldsignal);   /* restore */
951 return yield;
952
953
954 /* Come here if the data indicates removal of a header that we can't find */
955
956 DISASTER_NO_HEADER:
957 readerror = US" readerror=bad header identifier";
958 had_disaster = TRUE;
959 yield = FF_ERROR;
960 goto WAIT_EXIT;
961
962 /* Come here is there's a shambles in transferring the data over the pipe. The
963 value of errno should still be set. */
964
965 DISASTER:
966 readerror = string_sprintf(" readerror='%s'", strerror(errno));
967 had_disaster = TRUE;
968 yield = FF_ERROR;
969 goto WAIT_EXIT;
970 }
971
972 /* End of rda.c */