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