Convert more cases of list-walking to use self-assigned memory for the list-item
[exim.git] / src / src / route.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* Copyright (c) The Exim Maintainers 2020 */
7 /* See the file NOTICE for conditions of use and distribution. */
8
9 /* Functions concerned with routing, and the list of generic router options. */
10
11
12 #include "exim.h"
13
14
15
16 /* Generic options for routers, all of which live inside router_instance
17 data blocks and which therefore have the opt_public flag set. */
18 #define LOFF(field) OPT_OFF(router_instance, field)
19
20 optionlist optionlist_routers[] = {
21   { "*expand_group",      opt_stringptr | opt_hidden | opt_public,
22                  LOFF(expand_gid) },
23   { "*expand_more",       opt_stringptr | opt_hidden | opt_public,
24                  LOFF(expand_more) },
25   { "*expand_unseen",     opt_stringptr | opt_hidden | opt_public,
26                  LOFF(expand_unseen) },
27   { "*expand_user",       opt_stringptr | opt_hidden | opt_public,
28                  LOFF(expand_uid) },
29   { "*set_group",         opt_bool | opt_hidden | opt_public,
30                  LOFF(gid_set) },
31   { "*set_user",          opt_bool | opt_hidden | opt_public,
32                  LOFF(uid_set) },
33   { "address_data",       opt_stringptr|opt_public,
34                  LOFF(address_data) },
35   { "address_test",       opt_bool|opt_public,
36                  LOFF(address_test) },
37 #ifdef EXPERIMENTAL_BRIGHTMAIL
38   { "bmi_deliver_alternate",   opt_bool | opt_public,
39                  LOFF(bmi_deliver_alternate) },
40   { "bmi_deliver_default",   opt_bool | opt_public,
41                  LOFF(bmi_deliver_default) },
42   { "bmi_dont_deliver",   opt_bool | opt_public,
43                  LOFF(bmi_dont_deliver) },
44   { "bmi_rule",           opt_stringptr|opt_public,
45                  LOFF(bmi_rule) },
46 #endif
47   { "cannot_route_message", opt_stringptr | opt_public,
48                  LOFF(cannot_route_message) },
49   { "caseful_local_part", opt_bool | opt_public,
50                  LOFF(caseful_local_part) },
51   { "check_local_user",   opt_bool | opt_public,
52                  LOFF(check_local_user) },
53   { "condition",          opt_stringptr|opt_public|opt_rep_con,
54                  LOFF(condition) },
55   { "debug_print",        opt_stringptr | opt_public,
56                  LOFF(debug_string) },
57   { "disable_logging",    opt_bool | opt_public,
58                  LOFF(disable_logging) },
59   { "dnssec_request_domains",            opt_stringptr|opt_public,
60                  LOFF(dnssec.request) },
61   { "dnssec_require_domains",            opt_stringptr|opt_public,
62                  LOFF(dnssec.require) },
63   { "domains",            opt_stringptr|opt_public,
64                  LOFF(domains) },
65   { "driver",             opt_stringptr|opt_public,
66                  LOFF(driver_name) },
67   { "dsn_lasthop",        opt_bool|opt_public,
68                  LOFF(dsn_lasthop) },
69   { "errors_to",          opt_stringptr|opt_public,
70                  LOFF(errors_to) },
71   { "expn",               opt_bool|opt_public,
72                  LOFF(expn) },
73   { "fail_verify",        opt_bool_verify|opt_hidden|opt_public,
74                  LOFF(fail_verify_sender) },
75   { "fail_verify_recipient", opt_bool|opt_public,
76                  LOFF(fail_verify_recipient) },
77   { "fail_verify_sender", opt_bool|opt_public,
78                  LOFF(fail_verify_sender) },
79   { "fallback_hosts",     opt_stringptr|opt_public,
80                  LOFF(fallback_hosts) },
81   { "group",              opt_expand_gid | opt_public,
82                  LOFF(gid) },
83   { "headers_add",        opt_stringptr|opt_public|opt_rep_str,
84                  LOFF(extra_headers) },
85   { "headers_remove",     opt_stringptr|opt_public|opt_rep_str,
86                  LOFF(remove_headers) },
87   { "ignore_target_hosts",opt_stringptr|opt_public,
88                  LOFF(ignore_target_hosts) },
89   { "initgroups",         opt_bool | opt_public,
90                  LOFF(initgroups) },
91   { "local_part_prefix",  opt_stringptr|opt_public,
92                  LOFF(prefix) },
93   { "local_part_prefix_optional",opt_bool|opt_public,
94                  LOFF(prefix_optional) },
95   { "local_part_suffix",  opt_stringptr|opt_public,
96                  LOFF(suffix) },
97   { "local_part_suffix_optional",opt_bool|opt_public,
98                  LOFF(suffix_optional) },
99   { "local_parts",        opt_stringptr|opt_public,
100                  LOFF(local_parts) },
101   { "log_as_local",       opt_bool|opt_public,
102                  LOFF(log_as_local) },
103   { "more",               opt_expand_bool|opt_public,
104                  LOFF(more) },
105   { "pass_on_timeout",    opt_bool|opt_public,
106                  LOFF(pass_on_timeout) },
107   { "pass_router",       opt_stringptr|opt_public,
108                  LOFF(pass_router_name) },
109   { "redirect_router",    opt_stringptr|opt_public,
110                  LOFF(redirect_router_name) },
111   { "require_files",      opt_stringptr|opt_public,
112                  LOFF(require_files) },
113   { "retry_use_local_part", opt_bool|opt_public,
114                  LOFF(retry_use_local_part) },
115   { "router_home_directory", opt_stringptr|opt_public,
116                  LOFF(router_home_directory) },
117   { "self",               opt_stringptr|opt_public,
118                  LOFF(self) },
119   { "senders",            opt_stringptr|opt_public,
120                  LOFF(senders) },
121   { "set",                opt_stringptr|opt_public|opt_rep_str,
122                  LOFF(set) },
123   #ifdef SUPPORT_TRANSLATE_IP_ADDRESS
124   { "translate_ip_address", opt_stringptr|opt_public,
125                  LOFF(translate_ip_address) },
126   #endif
127   { "transport",          opt_stringptr|opt_public,
128                  LOFF(transport_name) },
129   { "transport_current_directory", opt_stringptr|opt_public,
130                  LOFF(current_directory) },
131   { "transport_home_directory", opt_stringptr|opt_public,
132                  LOFF(home_directory) },
133   { "unseen",             opt_expand_bool|opt_public,
134                  LOFF(unseen) },
135   { "user",               opt_expand_uid | opt_public,
136                  LOFF(uid) },
137   { "verify",             opt_bool_verify|opt_hidden|opt_public,
138                  LOFF(verify_sender) },
139   { "verify_only",        opt_bool|opt_public,
140                  LOFF(verify_only) },
141   { "verify_recipient",   opt_bool|opt_public,
142                  LOFF(verify_recipient) },
143   { "verify_sender",      opt_bool|opt_public,
144                  LOFF(verify_sender) }
145 };
146
147 int optionlist_routers_size = nelem(optionlist_routers);
148
149
150 #ifdef MACRO_PREDEF
151
152 # include "macro_predef.h"
153
154 void
155 options_routers(void)
156 {
157 uschar buf[64];
158
159 options_from_list(optionlist_routers, nelem(optionlist_routers), US"ROUTERS", NULL);
160
161 for (router_info * ri = routers_available; ri->driver_name[0]; ri++)
162   {
163   spf(buf, sizeof(buf), US"_DRIVER_ROUTER_%T", ri->driver_name);
164   builtin_macro_create(buf);
165   options_from_list(ri->options, (unsigned)*ri->options_count, US"ROUTER", ri->driver_name);
166   }
167 }
168
169 #else   /*!MACRO_PREDEF*/
170
171 /*************************************************
172 *          Set router pointer from name          *
173 *************************************************/
174
175 /* This function is used for the redirect_router and pass_router options and
176 called from route_init() below.
177
178 Arguments:
179   r           the current router
180   name        new router name
181   ptr         where to put the pointer
182   after       TRUE if router must follow this one
183
184 Returns:      nothing.
185 */
186
187 static void
188 set_router(router_instance *r, uschar *name, router_instance **ptr, BOOL after)
189 {
190 BOOL afterthis = FALSE;
191 router_instance *rr;
192
193 for (rr = routers; rr; rr = rr->next)
194   {
195   if (Ustrcmp(name, rr->name) == 0)
196     {
197     *ptr = rr;
198     break;
199     }
200   if (rr == r) afterthis = TRUE;
201   }
202
203 if (!rr)
204   log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
205     "new_router \"%s\" not found for \"%s\" router", name, r->name);
206
207 if (after && !afterthis)
208   log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
209     "new_router \"%s\" does not follow \"%s\" router", name, r->name);
210 }
211
212
213
214 /*************************************************
215 *             Initialize router list             *
216 *************************************************/
217
218 /* Read the routers section of the configuration file, and set up a chain of
219 router instances according to its contents. Each router has generic options and
220 may also have its own private options. This function is only ever called when
221 routers == NULL. We use generic code in readconf to do the work. It will set
222 values from the configuration file, and then call the driver's initialization
223 function. */
224
225 void
226 route_init(void)
227 {
228 readconf_driver_init(US"router",
229   (driver_instance **)(&routers),     /* chain anchor */
230   (driver_info *)routers_available,   /* available drivers */
231   sizeof(router_info),                /* size of info blocks */
232   &router_defaults,                   /* default values for generic options */
233   sizeof(router_instance),            /* size of instance block */
234   optionlist_routers,                 /* generic options */
235   optionlist_routers_size);
236
237 for (router_instance * r = routers; r; r = r->next)
238   {
239   uschar *s = r->self;
240
241   /* If log_as_local is unset, its overall default is FALSE. (The accept
242   router defaults it to TRUE.) */
243
244   if (r->log_as_local == TRUE_UNSET) r->log_as_local = FALSE;
245
246   /* Check for transport or no transport on certain routers */
247
248   if (  (r->info->ri_flags & ri_yestransport)
249      && !r->transport_name && !r->verify_only)
250     log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "%s router:\n  "
251       "a transport is required for this router", r->name);
252
253   if ((r->info->ri_flags & ri_notransport) && r->transport_name)
254     log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "%s router:\n  "
255       "a transport must not be defined for this router", r->name);
256
257   /* The "self" option needs to be decoded into a code value and possibly a
258   new domain string and a rewrite boolean. */
259
260   if      (Ustrcmp(s, "freeze") == 0)    r->self_code = self_freeze;
261   else if (Ustrcmp(s, "defer") == 0)     r->self_code = self_defer;
262   else if (Ustrcmp(s, "send") == 0)      r->self_code = self_send;
263   else if (Ustrcmp(s, "pass") == 0)      r->self_code = self_pass;
264   else if (Ustrcmp(s, "fail") == 0)      r->self_code = self_fail;
265   else if (Ustrncmp(s, "reroute:", 8) == 0)
266     {
267     s += 8;
268     while (isspace(*s)) s++;
269     if (Ustrncmp(s, "rewrite:", 8) == 0)
270       {
271       r->self_rewrite = TRUE;
272       s += 8;
273       while (isspace(*s)) s++;
274       }
275     r->self = s;
276     r->self_code = self_reroute;
277     }
278
279   else log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s router:\n  "
280       "%s is not valid for the self option", r->name, s);
281
282   /* If any router has check_local_user set, default retry_use_local_part
283   TRUE; otherwise its default is FALSE. */
284
285   if (r->retry_use_local_part == TRUE_UNSET)
286     r->retry_use_local_part =
287       r->check_local_user || r->local_parts || r->condition || r->prefix || r->suffix || r->senders || r->require_files;
288
289   /* Build a host list if fallback hosts is set. */
290
291   host_build_hostlist(&(r->fallback_hostlist), r->fallback_hosts, FALSE);
292
293   /* Check redirect_router and pass_router are valid */
294
295   if (r->redirect_router_name)
296     set_router(r, r->redirect_router_name, &(r->redirect_router), FALSE);
297
298   if (r->pass_router_name)
299     set_router(r, r->pass_router_name, &(r->pass_router), TRUE);
300
301 #ifdef notdef
302   DEBUG(D_route) debug_printf("DSN: %s %s\n", r->name,
303         r->dsn_lasthop ? "lasthop set" : "propagating DSN");
304 #endif
305   }
306 }
307
308
309
310 /*************************************************
311 *             Tidy up after routing              *
312 *************************************************/
313
314 /* Routers are entitled to keep hold of certain resources in their instance
315 blocks so as to save setting them up each time. An example is an open file.
316 Such routers must provide a tidyup entry point which is called when all routing
317 is finished, via this function. */
318
319 void
320 route_tidyup(void)
321 {
322 for (router_instance * r = routers; r; r = r->next)
323   if (r->info->tidyup) (r->info->tidyup)(r);
324 }
325
326
327
328 /*************************************************
329 *         Check local part for prefix            *
330 *************************************************/
331
332 /* This function is handed a local part and a list of possible prefixes; if any
333 one matches, return the prefix length. A prefix beginning with '*' is a
334 wildcard.
335
336 Arguments:
337   local_part    the local part to check
338   prefixes      the list of prefixes
339   vp            if set, pointer to place for size of wildcard portion
340
341 Returns:        length of matching prefix or zero
342 */
343
344 int
345 route_check_prefix(const uschar * local_part, const uschar * prefixes,
346   unsigned * vp)
347 {
348 int sep = 0;
349 uschar *prefix;
350 const uschar *listptr = prefixes;
351
352 while ((prefix = string_nextinlist(&listptr, &sep, NULL, 0)))
353   {
354   int plen = Ustrlen(prefix);
355   if (prefix[0] == '*')
356     {
357     prefix++;
358     for (const uschar * p = local_part + Ustrlen(local_part) - (--plen);
359          p >= local_part; p--)
360       if (strncmpic(prefix, p, plen) == 0)
361         {
362         unsigned vlen = p - local_part;
363         if (vp) *vp = vlen;
364         return plen + vlen;
365         }
366     }
367   else
368     if (strncmpic(prefix, local_part, plen) == 0)
369       {
370       if (vp) *vp = 0;
371       return plen;
372       }
373   }
374
375 return 0;
376 }
377
378
379
380 /*************************************************
381 *         Check local part for suffix            *
382 *************************************************/
383
384 /* This function is handed a local part and a list of possible suffixes;
385 if any one matches, return the suffix length. A suffix ending with '*'
386 is a wildcard.
387
388 Arguments:
389   local_part    the local part to check
390   suffixes      the list of suffixes
391   vp            if set, pointer to place for size of wildcard portion
392
393 Returns:        length of matching suffix or zero
394 */
395
396 int
397 route_check_suffix(const uschar * local_part, const uschar * suffixes,
398   unsigned * vp)
399 {
400 int sep = 0;
401 int alen = Ustrlen(local_part);
402 uschar *suffix;
403 const uschar *listptr = suffixes;
404
405 while ((suffix = string_nextinlist(&listptr, &sep, NULL, 0)))
406   {
407   int slen = Ustrlen(suffix);
408   if (suffix[slen-1] == '*')
409     {
410     const uschar * pend = local_part + alen - (--slen) + 1;
411     for (const uschar * p = local_part; p < pend; p++)
412       if (strncmpic(suffix, p, slen) == 0)
413         {
414         int tlen = alen - (p - local_part);
415         if (vp) *vp = tlen - slen;
416         return tlen;
417         }
418     }
419   else
420     if (alen > slen && strncmpic(suffix, local_part + alen - slen, slen) == 0)
421       {
422       if (vp) *vp = 0;
423       return slen;
424       }
425   }
426
427 return 0;
428 }
429
430
431
432
433 /*************************************************
434 *     Check local part, domain, or sender        *
435 *************************************************/
436
437 /* The checks in check_router_conditions() require similar code, so we use
438 this function to save repetition.
439
440 Arguments:
441   rname          router name for error messages
442   type           type of check, for error message
443   list           domains, local_parts, or senders list
444   anchorptr      -> tree for possibly cached items (domains)
445   cache_bits     cached bits pointer
446   listtype       MCL_DOMAIN for domain check
447                  MCL_LOCALPART for local part check
448                  MCL_ADDRESS for sender check
449   domloc         current domain, current local part, or NULL for sender check
450   ldata          where to put lookup data
451   caseless       passed on to match_isinlist()
452   perror         where to put an error message
453
454 Returns:         OK     item is in list
455                  SKIP   item is not in list, router is to be skipped
456                  DEFER  lookup or other defer
457 */
458
459 static int
460 route_check_dls(uschar *rname, uschar *type, const uschar *list,
461   tree_node **anchorptr, unsigned int *cache_bits, int listtype,
462   const uschar *domloc, const uschar **ldata, BOOL caseless, uschar **perror)
463 {
464 if (!list) return OK;   /* Empty list always succeeds */
465
466 DEBUG(D_route) debug_printf("checking %s\n", type);
467
468 /* The domain and local part use the same matching function, whereas sender
469 has its own code. */
470
471 switch(domloc
472   ? match_isinlist(domloc, &list, 0, anchorptr, cache_bits, listtype,
473     caseless, ldata)
474   : match_address_list(sender_address ? sender_address : US"",
475     TRUE, TRUE, &list, cache_bits, -1, 0, CUSS &sender_data)
476       )
477   {
478   case OK:
479     return OK;
480
481   case FAIL:
482     *perror = string_sprintf("%s router skipped: %s mismatch", rname, type);
483     DEBUG(D_route) debug_printf("%s\n", *perror);
484     return SKIP;
485
486   default:      /* Paranoia, and keeps compilers happy */
487   case DEFER:
488     *perror = string_sprintf("%s check lookup or other defer", type);
489     DEBUG(D_route) debug_printf("%s\n", *perror);
490     return DEFER;
491   }
492 }
493
494
495
496 /*************************************************
497 *        Check access by a given uid/gid         *
498 *************************************************/
499
500 /* This function checks whether a given uid/gid has access to a given file or
501 directory. It is called only from check_files() below. This is hopefully a
502 cheapish check that does the job most of the time. Exim does *not* rely on this
503 test when actually accessing any file. The test is used when routing to make it
504 possible to take actions such as "if user x can access file y then run this
505 router".
506
507 During routing, Exim is normally running as root, and so the test will work
508 except for NFS non-root mounts. When verifying during message reception, Exim
509 is running as "exim", so the test may not work. This is a limitation of the
510 Exim design.
511
512 Code in check_files() below detects the case when it cannot stat() the file (as
513 root), and in that situation it uses a setuid subprocess in which to run this
514 test.
515
516 Arguments:
517   path          the path to check
518   uid           the user
519   gid           the group
520   bits          the bits required in the final component
521
522 Returns:        TRUE
523                 FALSE errno=EACCES or ENOENT (or others from realpath or stat)
524 */
525
526 static BOOL
527 route_check_access(uschar *path, uid_t uid, gid_t gid, int bits)
528 {
529 struct stat statbuf;
530 uschar *slash;
531 uschar *rp = US realpath(CS path, CS big_buffer);
532 uschar *sp = rp + 1;
533
534 DEBUG(D_route) debug_printf("route_check_access(%s,%d,%d,%o)\n", path,
535   (int)uid, (int)gid, bits);
536
537 if (!rp) return FALSE;
538
539 while ((slash = Ustrchr(sp, '/')))
540   {
541   *slash = 0;
542   DEBUG(D_route) debug_printf("stat %s\n", rp);
543   if (Ustat(rp, &statbuf) < 0) return FALSE;
544   if ((statbuf.st_mode &
545        ((statbuf.st_uid == uid)? 0100 : (statbuf.st_gid == gid)? 0010 : 001)
546       ) == 0)
547     {
548     errno = EACCES;
549     return FALSE;
550     }
551   *slash = '/';
552   sp = slash + 1;
553   }
554
555 /* Down to the final component */
556
557 DEBUG(D_route) debug_printf("stat %s\n", rp);
558
559 if (Ustat(rp, &statbuf) < 0) return FALSE;
560
561 if (statbuf.st_uid == uid) bits = bits << 6;
562   else if (statbuf.st_gid == gid) bits = bits << 3;
563 if ((statbuf.st_mode & bits) != bits)
564   {
565   errno = EACCES;
566   return FALSE;
567   }
568
569 DEBUG(D_route) debug_printf("route_check_access() succeeded\n");
570 return TRUE;
571 }
572
573
574
575 /*************************************************
576 *           Do file existence tests              *
577 *************************************************/
578
579 /* This function is given a colon-separated list of file tests, each of which
580 is expanded before use. A test consists of a file name, optionally preceded by
581 ! (require non-existence) and/or + for handling permission denied (+ means
582 treat as non-existing).
583
584 An item that contains no slashes is interpreted as a username or id, with an
585 optional group id, for checking access to the file. This cannot be done
586 "perfectly", but it is good enough for a number of applications.
587
588 Arguments:
589   s        a colon-separated list of file tests or NULL
590   perror   a pointer to an anchor for an error text in the case of a DEFER
591
592 Returns:   OK if s == NULL or all tests are as required
593            DEFER if the existence of at least one of the files is
594              unclear (an error other than non-existence occurred);
595            DEFER if an expansion failed
596            DEFER if a name is not absolute
597            DEFER if problems with user/group
598            SKIP otherwise
599 */
600
601 static int
602 check_files(const uschar *s, uschar **perror)
603 {
604 int sep = 0;              /* List has default separators */
605 uid_t uid = 0;            /* For picky compilers */
606 gid_t gid = 0;            /* For picky compilers */
607 BOOL ugid_set = FALSE;
608 const uschar *listptr;
609 uschar *check;
610
611 if (!s) return OK;
612
613 DEBUG(D_route) debug_printf("checking require_files\n");
614
615 listptr = s;
616 while ((check = string_nextinlist(&listptr, &sep, NULL, 0)))
617   {
618   int rc;
619   int eacces_code = 0;
620   BOOL invert = FALSE;
621   struct stat statbuf;
622   uschar *ss = expand_string(check);
623
624   if (!ss)
625     {
626     if (f.expand_string_forcedfail) continue;
627     *perror = string_sprintf("failed to expand \"%s\" for require_files: %s",
628       check, expand_string_message);
629     goto RETURN_DEFER;
630     }
631
632   /* Empty items are just skipped */
633
634   if (*ss == 0) continue;
635
636   /* If there are no slashes in the string, we have a user name or uid, with
637   optional group/gid. */
638
639   if (Ustrchr(ss, '/') == NULL)
640     {
641     BOOL ok;
642     struct passwd *pw;
643     uschar *comma = Ustrchr(ss, ',');
644
645     /* If there's a comma, temporarily terminate the user name/number
646     at that point. Then set the uid. */
647
648     if (comma != NULL) *comma = 0;
649     ok = route_finduser(ss, &pw, &uid);
650     if (comma != NULL) *comma = ',';
651
652     if (!ok)
653       {
654       *perror = string_sprintf("user \"%s\" for require_files not found", ss);
655       goto RETURN_DEFER;
656       }
657
658     /* If there was no comma, the gid is that associated with the user. */
659
660     if (comma == NULL)
661       {
662       if (pw != NULL) gid = pw->pw_gid; else
663         {
664         *perror = string_sprintf("group missing after numerical uid %d for "
665           "require_files", (int)uid);
666         goto RETURN_DEFER;
667         }
668       }
669     else
670       {
671       if (!route_findgroup(comma + 1, &gid))
672         {
673         *perror = string_sprintf("group \"%s\" for require_files not found\n",
674           comma + 1);
675         goto RETURN_DEFER;
676         }
677       }
678
679     /* Note that we have values set, and proceed to next item */
680
681     DEBUG(D_route)
682       debug_printf("check subsequent files for access by %s\n", ss);
683     ugid_set = TRUE;
684     continue;
685     }
686
687   /* Path, possibly preceded by + and ! */
688
689   if (*ss == '+')
690     {
691     eacces_code = 1;
692     while (isspace((*(++ss))));
693     }
694
695   if (*ss == '!')
696     {
697     invert = TRUE;
698     while (isspace((*(++ss))));
699     }
700
701   if (*ss != '/')
702     {
703     *perror = string_sprintf("require_files: \"%s\" is not absolute", ss);
704     goto RETURN_DEFER;
705     }
706
707   /* Stat the file, either as root (while routing) or as exim (while verifying
708   during message reception). */
709
710   rc = Ustat(ss, &statbuf);
711
712   DEBUG(D_route)
713     {
714     debug_printf("file check: %s\n", check);
715     if (ss != check) debug_printf("expanded file: %s\n", ss);
716     debug_printf("stat() yielded %d\n", rc);
717     }
718
719   /* If permission is denied, and we are running as root (i.e. routing for
720   delivery rather than verifying), and the requirement is to test for access by
721   a particular uid/gid, it must mean that the file is on a non-root-mounted NFS
722   system. In this case, we have to use a subprocess that runs as the relevant
723   uid in order to do the test. */
724
725   if (rc != 0 && errno == EACCES && ugid_set && getuid() == root_uid)
726     {
727     int status;
728     pid_t pid;
729     void (*oldsignal)(int);
730
731     DEBUG(D_route) debug_printf("root is denied access: forking to check "
732       "in subprocess\n");
733
734     /* Before forking, ensure that SIGCHLD is set to SIG_DFL before forking, so
735     that the child process can be waited for, just in case get here with it set
736     otherwise. Save the old state for resetting on the wait. */
737
738     oldsignal = signal(SIGCHLD, SIG_DFL);
739     pid = exim_fork(US"require-files");
740
741     /* If fork() fails, reinstate the original error and behave as if
742     this block of code were not present. This is the same behaviour as happens
743     when Exim is not running as root at this point. */
744
745     if (pid < 0)
746       {
747       DEBUG(D_route)
748        debug_printf("require_files: fork failed: %s\n", strerror(errno));
749       errno = EACCES;
750       goto HANDLE_ERROR;
751       }
752
753     /* In the child process, change uid and gid, and then do the check using
754     the route_check_access() function. This does more than just stat the file;
755     it tests permissions as well. Return 0 for OK and 1 for failure. */
756
757     if (pid == 0)
758       {
759       exim_setugid(uid, gid, TRUE,
760         string_sprintf("require_files check, file=%s", ss));
761       if (route_check_access(ss, uid, gid, 4))
762         exim_underbar_exit(EXIT_SUCCESS);
763       DEBUG(D_route) debug_printf("route_check_access() failed\n");
764       exim_underbar_exit(EXIT_FAILURE);
765       }
766
767     /* In the parent, wait for the child to finish */
768
769     while (waitpid(pid, &status, 0) < 0)
770      if (errno != EINTR)  /* unexpected error, interpret as failure */
771        {
772        status = 1;
773        break;
774        }
775
776     signal(SIGCHLD, oldsignal);   /* restore */
777     if ((status == 0) == invert) return SKIP;
778     continue;   /* to test the next file */
779     }
780
781   /* Control reaches here if the initial stat() succeeds, or fails with an
782   error other than EACCES, or no uid/gid is set, or we are not running as root.
783   If we know the file exists and uid/gid are set, try to check read access for
784   that uid/gid as best we can. */
785
786   if (rc == 0 && ugid_set && !route_check_access(ss, uid, gid, 4))
787     {
788     DEBUG(D_route) debug_printf("route_check_access() failed\n");
789     rc = -1;
790     }
791
792   /* Handle error returns from stat() or route_check_access(). The EACCES error
793   is handled specially. At present, we can force it to be treated as
794   non-existence. Write the code so that it will be easy to add forcing for
795   existence if required later. */
796
797   HANDLE_ERROR:
798   if (rc < 0)
799     {
800     DEBUG(D_route) debug_printf("errno = %d\n", errno);
801     if (errno == EACCES)
802       {
803       if (eacces_code == 1)
804         {
805         DEBUG(D_route) debug_printf("EACCES => ENOENT\n");
806         errno = ENOENT;   /* Treat as non-existent */
807         }
808       }
809     if (errno != ENOENT)
810       {
811       *perror = string_sprintf("require_files: error for %s: %s", ss,
812         strerror(errno));
813       goto RETURN_DEFER;
814       }
815     }
816
817   /* At this point, rc < 0 => non-existence; rc >= 0 => existence */
818
819   if ((rc >= 0) == invert) return SKIP;
820   }
821
822 return OK;
823
824 /* Come here on any of the errors that return DEFER. */
825
826 RETURN_DEFER:
827 DEBUG(D_route) debug_printf("%s\n", *perror);
828 return DEFER;
829 }
830
831
832
833
834
835 /*************************************************
836 *             Check for router skipping          *
837 *************************************************/
838
839 /* This function performs various checks to see whether a router should be
840 skipped. The order in which they are performed is important.
841
842 Arguments:
843   r            pointer to router instance block
844   addr         address that is being handled
845   verify       the verification type
846   pw           ptr to ptr to passwd structure for local user
847   perror       for lookup errors
848
849 Returns:       OK if all the tests succeed
850                SKIP if router is to be skipped
851                DEFER for a lookup defer
852                FAIL for address to be failed
853 */
854
855 static BOOL
856 check_router_conditions(router_instance *r, address_item *addr, int verify,
857   struct passwd **pw, uschar **perror)
858 {
859 int rc;
860 uschar *check_local_part;
861 unsigned int *localpart_cache;
862
863 /* Reset variables to hold a home directory and data from lookup of a domain or
864 local part, and ensure search_find_defer is unset, in case there aren't any
865 actual lookups. */
866
867 deliver_home = NULL;
868 deliver_domain_data = NULL;
869 deliver_localpart_data = NULL;
870 sender_data = NULL;
871 local_user_gid = (gid_t)(-1);
872 local_user_uid = (uid_t)(-1);
873 f.search_find_defer = FALSE;
874
875 /* Skip this router if not verifying and it has verify_only set */
876
877 if ((verify == v_none || verify == v_expn) && r->verify_only)
878   {
879   DEBUG(D_route) debug_printf("%s router skipped: verify_only set\n", r->name);
880   return SKIP;
881   }
882
883 /* Skip this router if testing an address (-bt) and address_test is not set */
884
885 if (f.address_test_mode && !r->address_test)
886   {
887   DEBUG(D_route) debug_printf("%s router skipped: address_test is unset\n",
888     r->name);
889   return SKIP;
890   }
891
892 /* Skip this router if verifying and it hasn't got the appropriate verify flag
893 set. */
894
895 if ((verify == v_sender && !r->verify_sender) ||
896     (verify == v_recipient && !r->verify_recipient))
897   {
898   DEBUG(D_route) debug_printf("%s router skipped: verify %d %d %d\n",
899     r->name, verify, r->verify_sender, r->verify_recipient);
900   return SKIP;
901   }
902
903 /* Skip this router if processing EXPN and it doesn't have expn set */
904
905 if (verify == v_expn && !r->expn)
906   {
907   DEBUG(D_route) debug_printf("%s router skipped: no_expn set\n", r->name);
908   return SKIP;
909   }
910
911 /* Skip this router if there's a domain mismatch. */
912
913 if ((rc = route_check_dls(r->name, US"domains", r->domains, &domainlist_anchor,
914      addr->domain_cache, TRUE, addr->domain, CUSS &deliver_domain_data,
915      MCL_DOMAIN, perror)) != OK)
916   return rc;
917
918 /* Skip this router if there's a local part mismatch. We want to pass over the
919 caseful local part, so that +caseful can restore it, even if this router is
920 handling local parts caselessly. However, we can't just pass cc_local_part,
921 because that doesn't have the prefix or suffix stripped. A bit of massaging is
922 required. Also, we only use the match cache for local parts that have not had
923 a prefix or suffix stripped. */
924
925 if (!addr->prefix && !addr->suffix)
926   {
927   localpart_cache = addr->localpart_cache;
928   check_local_part = addr->cc_local_part;
929   }
930 else
931   {
932   localpart_cache = NULL;
933   check_local_part = string_copy(addr->cc_local_part);
934   if (addr->prefix)
935     check_local_part += Ustrlen(addr->prefix);
936   if (addr->suffix)
937     check_local_part[Ustrlen(check_local_part) - Ustrlen(addr->suffix)] = 0;
938   }
939
940 if ((rc = route_check_dls(r->name, US"local_parts", r->local_parts,
941        &localpartlist_anchor, localpart_cache, MCL_LOCALPART,
942        check_local_part, CUSS &deliver_localpart_data,
943        !r->caseful_local_part, perror)) != OK)
944   return rc;
945
946 /* If the check_local_user option is set, check that the local_part is the
947 login of a local user. Note: the third argument to route_finduser() must be
948 NULL here, to prevent a numeric string being taken as a numeric uid. If the
949 user is found, set deliver_home to the home directory, and also set
950 local_user_{uid,gid} and local_part_data.  */
951
952 if (r->check_local_user)
953   {
954   DEBUG(D_route) debug_printf("checking for local user\n");
955   if (!route_finduser(addr->local_part, pw, NULL))
956     {
957     DEBUG(D_route) debug_printf("%s router skipped: %s is not a local user\n",
958       r->name, addr->local_part);
959     return SKIP;
960     }
961   addr->prop.localpart_data =
962     deliver_localpart_data = string_copy(US (*pw)->pw_name);
963   deliver_home = string_copy(US (*pw)->pw_dir);
964   local_user_gid = (*pw)->pw_gid;
965   local_user_uid = (*pw)->pw_uid;
966   }
967
968 /* Set (or override in the case of check_local_user) the home directory if
969 router_home_directory is set. This is done here so that it overrides $home from
970 check_local_user before any subsequent expansions are done. Otherwise, $home
971 could mean different things for different options, which would be extremely
972 confusing. */
973
974 if (r->router_home_directory)
975   {
976   uschar * router_home = expand_string(r->router_home_directory);
977   if (router_home)
978     {
979     setflag(addr, af_home_expanded); /* Note set from router_home_directory */
980     deliver_home = router_home;
981     }
982   else if (!f.expand_string_forcedfail)
983     {
984     *perror = string_sprintf("failed to expand \"%s\" for "
985       "router_home_directory: %s", r->router_home_directory,
986       expand_string_message);
987     return DEFER;
988     }
989   }
990
991 /* Skip if the sender condition is not met. We leave this one till after the
992 local user check so that $home is set - enabling the possibility of letting
993 individual recipients specify lists of acceptable/unacceptable senders. */
994
995 if ((rc = route_check_dls(r->name, US"senders", r->senders, NULL,
996      sender_address_cache, MCL_ADDRESS, NULL, NULL, FALSE, perror)) != OK)
997   return rc;
998
999 /* This is the point at which we print out the router's debugging string if it
1000 is set. We wait till here so as to have $home available for local users (and
1001 anyway, we don't want too much stuff for skipped routers). */
1002
1003 debug_print_string(r->debug_string);
1004
1005 /* Perform file existence tests. */
1006
1007 if ((rc = check_files(r->require_files, perror)) != OK)
1008   {
1009   DEBUG(D_route) debug_printf("%s router %s: file check\n", r->name,
1010     (rc == SKIP)? "skipped" : "deferred");
1011   return rc;
1012   }
1013
1014 /* Now the general condition test. */
1015
1016 if (r->condition)
1017   {
1018   DEBUG(D_route) debug_printf("checking \"condition\" \"%.80s\"...\n", r->condition);
1019   if (!expand_check_condition(r->condition, r->name, US"router"))
1020     {
1021     if (f.search_find_defer)
1022       {
1023       *perror = US"condition check lookup defer";
1024       DEBUG(D_route) debug_printf("%s\n", *perror);
1025       return DEFER;
1026       }
1027     DEBUG(D_route)
1028       debug_printf("%s router skipped: condition failure\n", r->name);
1029     return SKIP;
1030     }
1031   }
1032
1033 #ifdef EXPERIMENTAL_BRIGHTMAIL
1034 /* check if a specific Brightmail AntiSpam rule fired on the message */
1035 if (r->bmi_rule)
1036   {
1037   DEBUG(D_route) debug_printf("checking bmi_rule\n");
1038   if (bmi_check_rule(bmi_base64_verdict, r->bmi_rule) == 0)
1039     {    /* none of the rules fired */
1040     DEBUG(D_route)
1041       debug_printf("%s router skipped: none of bmi_rule rules fired\n", r->name);
1042     return SKIP;
1043     }
1044   }
1045
1046 /* check if message should not be delivered */
1047 if (r->bmi_dont_deliver && bmi_deliver == 1)
1048   {
1049   DEBUG(D_route)
1050     debug_printf("%s router skipped: bmi_dont_deliver is FALSE\n", r->name);
1051   return SKIP;
1052   }
1053
1054 /* check if message should go to an alternate location */
1055 if (  r->bmi_deliver_alternate
1056    && (bmi_deliver == 0 || !bmi_alt_location)
1057    )
1058   {
1059   DEBUG(D_route)
1060     debug_printf("%s router skipped: bmi_deliver_alternate is FALSE\n", r->name);
1061   return SKIP;
1062   }
1063
1064 /* check if message should go to default location */
1065 if (  r->bmi_deliver_default
1066    && (bmi_deliver == 0 || bmi_alt_location)
1067    )
1068   {
1069   DEBUG(D_route)
1070     debug_printf("%s router skipped: bmi_deliver_default is FALSE\n", r->name);
1071   return SKIP;
1072   }
1073 #endif
1074
1075 /* All the checks passed. */
1076
1077 return OK;
1078 }
1079
1080
1081
1082
1083 /*************************************************
1084 *           Find a local user                    *
1085 *************************************************/
1086
1087 /* Try several times (if configured) to find a local user, in case delays in
1088 NIS or NFS whatever cause an incorrect refusal. It's a pity that getpwnam()
1089 doesn't have some kind of indication as to why it has failed. If the string
1090 given consists entirely of digits, and the third argument is not NULL, assume
1091 the string is the numerical value of the uid. Otherwise it is looked up using
1092 getpwnam(). The uid is passed back via return_uid, if not NULL, and the
1093 pointer to a passwd structure, if found, is passed back via pw, if not NULL.
1094
1095 Because this may be called several times in succession for the same user for
1096 different routers, cache the result of the previous getpwnam call so that it
1097 can be re-used. Note that we can't just copy the structure, as the store it
1098 points to can get trashed.
1099
1100 Arguments:
1101   s           the login name or textual form of the numerical uid of the user
1102   pw          if not NULL, return the result of getpwnam here, or set NULL
1103                 if no call to getpwnam is made (s numeric, return_uid != NULL)
1104   return_uid  if not NULL, return the uid via this address
1105
1106 Returns:      TRUE if s is numerical or was looked up successfully
1107
1108 */
1109
1110 static struct passwd pwcopy;
1111 static struct passwd *lastpw = NULL;
1112 static uschar lastname[48] = { 0 };
1113 static uschar lastdir[128];
1114 static uschar lastgecos[128];
1115 static uschar lastshell[128];
1116
1117 BOOL
1118 route_finduser(const uschar *s, struct passwd **pw, uid_t *return_uid)
1119 {
1120 BOOL cache_set = (Ustrcmp(lastname, s) == 0);
1121
1122 DEBUG(D_uid) debug_printf("seeking password data for user \"%s\": %s\n", s,
1123   cache_set ? "using cached result" : "cache not available");
1124
1125 if (!cache_set)
1126   {
1127   int i = 0;
1128
1129   if (return_uid && (isdigit(*s) || *s == '-') &&
1130        s[Ustrspn(s+1, "0123456789")+1] == 0)
1131     {
1132     *return_uid = (uid_t)Uatoi(s);
1133     if (pw) *pw = NULL;
1134     return TRUE;
1135     }
1136
1137   string_format_nt(lastname, sizeof(lastname), "%s", s);
1138
1139   /* Force failure if string length is greater than given maximum */
1140
1141   if (max_username_length > 0 && Ustrlen(lastname) > max_username_length)
1142     {
1143     DEBUG(D_uid) debug_printf("forced failure of finduser(): string "
1144       "length of %s is greater than %d\n", lastname, max_username_length);
1145     lastpw = NULL;
1146     }
1147
1148   /* Try a few times if so configured; this handles delays in NIS etc. */
1149
1150   else for (;;)
1151     {
1152     errno = 0;
1153     if ((lastpw = getpwnam(CS s))) break;
1154     if (++i > finduser_retries) break;
1155     sleep(1);
1156     }
1157
1158   if (lastpw)
1159     {
1160     pwcopy.pw_uid = lastpw->pw_uid;
1161     pwcopy.pw_gid = lastpw->pw_gid;
1162     (void)string_format(lastdir, sizeof(lastdir), "%s", lastpw->pw_dir);
1163     (void)string_format(lastgecos, sizeof(lastgecos), "%s", lastpw->pw_gecos);
1164     (void)string_format(lastshell, sizeof(lastshell), "%s", lastpw->pw_shell);
1165     pwcopy.pw_name = CS lastname;
1166     pwcopy.pw_dir = CS lastdir;
1167     pwcopy.pw_gecos = CS lastgecos;
1168     pwcopy.pw_shell = CS lastshell;
1169     lastpw = &pwcopy;
1170     }
1171
1172   else DEBUG(D_uid) if (errno != 0)
1173     debug_printf("getpwnam(%s) failed: %s\n", s, strerror(errno));
1174   }
1175
1176 if (!lastpw)
1177   {
1178   DEBUG(D_uid) debug_printf("getpwnam() returned NULL (user not found)\n");
1179   return FALSE;
1180   }
1181
1182 DEBUG(D_uid) debug_printf("getpwnam() succeeded uid=%d gid=%d\n",
1183     lastpw->pw_uid, lastpw->pw_gid);
1184
1185 if (return_uid) *return_uid = lastpw->pw_uid;
1186 if (pw) *pw = lastpw;
1187
1188 return TRUE;
1189 }
1190
1191
1192
1193
1194 /*************************************************
1195 *           Find a local group                   *
1196 *************************************************/
1197
1198 /* Try several times (if configured) to find a local group, in case delays in
1199 NIS or NFS whatever cause an incorrect refusal. It's a pity that getgrnam()
1200 doesn't have some kind of indication as to why it has failed.
1201
1202 Arguments:
1203   s           the group name or textual form of the numerical gid
1204   return_gid  return the gid via this address
1205
1206 Returns:      TRUE if the group was found; FALSE otherwise
1207
1208 */
1209
1210 BOOL
1211 route_findgroup(uschar *s, gid_t *return_gid)
1212 {
1213 int i = 0;
1214 struct group *gr;
1215
1216 if ((isdigit(*s) || *s == '-') && s[Ustrspn(s+1, "0123456789")+1] == 0)
1217   {
1218   *return_gid = (gid_t)Uatoi(s);
1219   return TRUE;
1220   }
1221
1222 for (;;)
1223   {
1224   if ((gr = getgrnam(CS s)))
1225     {
1226     *return_gid = gr->gr_gid;
1227     return TRUE;
1228     }
1229   if (++i > finduser_retries) break;
1230   sleep(1);
1231   }
1232
1233 return FALSE;
1234 }
1235
1236
1237
1238
1239 /*************************************************
1240 *          Find user by expanding string         *
1241 *************************************************/
1242
1243 /* Expands a string, and then looks up the result in the passwd file.
1244
1245 Arguments:
1246   string       the string to be expanded, yielding a login name or a numerical
1247                  uid value (to be passed to route_finduser())
1248   driver_name  caller name for panic error message (only)
1249   driver_type  caller type for panic error message (only)
1250   pw           return passwd entry via this pointer
1251   uid          return uid via this pointer
1252   errmsg       where to point a message on failure
1253
1254 Returns:       TRUE if user found, FALSE otherwise
1255 */
1256
1257 BOOL
1258 route_find_expanded_user(uschar *string, uschar *driver_name,
1259   uschar *driver_type, struct passwd **pw, uid_t *uid, uschar **errmsg)
1260 {
1261 uschar *user = expand_string(string);
1262
1263 if (!user)
1264   {
1265   *errmsg = string_sprintf("Failed to expand user string \"%s\" for the "
1266     "%s %s: %s", string, driver_name, driver_type, expand_string_message);
1267   log_write(0, LOG_MAIN|LOG_PANIC, "%s", *errmsg);
1268   return FALSE;
1269   }
1270
1271 if (route_finduser(user, pw, uid)) return TRUE;
1272
1273 *errmsg = string_sprintf("Failed to find user \"%s\" from expanded string "
1274   "\"%s\" for the %s %s", user, string, driver_name, driver_type);
1275 log_write(0, LOG_MAIN|LOG_PANIC, "%s", *errmsg);
1276 return FALSE;
1277 }
1278
1279
1280
1281 /*************************************************
1282 *          Find group by expanding string        *
1283 *************************************************/
1284
1285 /* Expands a string and then looks up the result in the group file.
1286
1287 Arguments:
1288   string       the string to be expanded, yielding a group name or a numerical
1289                  gid value (to be passed to route_findgroup())
1290   driver_name  caller name for panic error message (only)
1291   driver_type  caller type for panic error message (only)
1292   gid          return gid via this pointer
1293   errmsg       return error message via this pointer
1294
1295 Returns:       TRUE if found group, FALSE otherwise
1296 */
1297
1298 BOOL
1299 route_find_expanded_group(uschar *string, uschar *driver_name, uschar *driver_type,
1300   gid_t *gid, uschar **errmsg)
1301 {
1302 BOOL yield = TRUE;
1303 uschar *group = expand_string(string);
1304
1305 if (!group)
1306   {
1307   *errmsg = string_sprintf("Failed to expand group string \"%s\" for the "
1308     "%s %s: %s", string, driver_name, driver_type, expand_string_message);
1309   log_write(0, LOG_MAIN|LOG_PANIC, "%s", *errmsg);
1310   return FALSE;
1311   }
1312
1313 if (!route_findgroup(group, gid))
1314   {
1315   *errmsg = string_sprintf("Failed to find group \"%s\" from expanded string "
1316     "\"%s\" for the %s %s", group, string, driver_name, driver_type);
1317   log_write(0, LOG_MAIN|LOG_PANIC, "%s", *errmsg);
1318   yield = FALSE;
1319   }
1320
1321 return yield;
1322 }
1323
1324
1325
1326 /*************************************************
1327 *            Handle an unseen routing            *
1328 *************************************************/
1329
1330 /* This function is called when an address is routed by a router with "unseen"
1331 set. It must make a clone of the address, for handling by subsequent drivers.
1332 The clone is set to start routing at the next router.
1333
1334 The original address must be replaced by an invented "parent" which has the
1335 routed address plus the clone as its children. This is necessary in case the
1336 address is at the top level - we don't want to mark it complete until both
1337 deliveries have been done.
1338
1339 A new unique field must be made, so that the record of the delivery isn't a
1340 record of the original address, and checking for already delivered has
1341 therefore to be done here. If the delivery has happened, then take the base
1342 address off whichever delivery queue it is on - it will always be the top item.
1343
1344 Arguments:
1345   name          router name
1346   addr          address that was routed
1347   paddr_local   chain of local-delivery addresses
1348   paddr_remote  chain of remote-delivery addresses
1349   addr_new      chain for newly created addresses
1350
1351 Returns:        nothing
1352 */
1353
1354 static void
1355 route_unseen(uschar *name, address_item *addr, address_item **paddr_local,
1356   address_item **paddr_remote, address_item **addr_new)
1357 {
1358 address_item *parent = deliver_make_addr(addr->address, TRUE);
1359 address_item *new = deliver_make_addr(addr->address, TRUE);
1360
1361 /* The invented parent is a copy that replaces the original; note that
1362 this copies its parent pointer. It has two children, and its errors_address is
1363 from the original address' parent, if present, otherwise unset. */
1364
1365 *parent = *addr;
1366 parent->child_count = 2;
1367 parent->prop.errors_address =
1368   addr->parent ? addr->parent->prop.errors_address : NULL;
1369
1370 /* The routed address gets a new parent. */
1371
1372 addr->parent = parent;
1373
1374 /* The clone has this parent too. Set its errors address from the parent. This
1375 was set from the original parent (or to NULL) - see above. We do NOT want to
1376 take the errors address from the unseen router. */
1377
1378 new->parent = parent;
1379 new->prop.errors_address = parent->prop.errors_address;
1380
1381 /* Copy the propagated flags and address_data from the original. */
1382
1383 new->prop.ignore_error = addr->prop.ignore_error;
1384 new->prop.address_data = addr->prop.address_data;
1385 new->prop.variables = NULL;
1386 tree_dup((tree_node **)&new->prop.variables, addr->prop.variables);
1387 new->dsn_flags = addr->dsn_flags;
1388 new->dsn_orcpt = addr->dsn_orcpt;
1389
1390
1391 /* As it has turned out, we haven't set headers_add or headers_remove for the
1392  * clone. Thinking about it, it isn't entirely clear whether they should be
1393  * copied from the original parent, like errors_address, or taken from the
1394  * unseen router, like address_data and the flags. Until somebody brings this
1395  * up, I propose to leave the code as it is.
1396  */
1397
1398
1399 /* Set the cloned address to start at the next router, and put it onto the
1400 chain of new addresses. */
1401
1402 new->start_router = addr->router->next;
1403 new->next = *addr_new;
1404 *addr_new = new;
1405
1406 DEBUG(D_route) debug_printf("\"unseen\" set: replicated %s\n", addr->address);
1407
1408 /* Make a new unique field, to distinguish from the normal one. */
1409
1410 addr->unique = string_sprintf("%s/%s", addr->unique, name);
1411
1412 /* If the address has been routed to a transport, see if it was previously
1413 delivered. If so, we take it off the relevant queue so that it isn't delivered
1414 again. Otherwise, it was an alias or something, and the addresses it generated
1415 are handled in the normal way. */
1416
1417 if (addr->transport && tree_search(tree_nonrecipients, addr->unique))
1418   {
1419   DEBUG(D_route)
1420     debug_printf("\"unseen\" delivery previously done - discarded\n");
1421   parent->child_count--;
1422   if (*paddr_remote == addr) *paddr_remote = addr->next;
1423   if (*paddr_local == addr) *paddr_local = addr->next;
1424   }
1425 }
1426
1427
1428
1429 /************************************************/
1430 /* Add router-assigned variables
1431 Return OK/DEFER/FAIL/PASS */
1432
1433 static int
1434 set_router_vars(address_item * addr, const router_instance * r)
1435 {
1436 const uschar * varlist = r->set;
1437 tree_node ** root = (tree_node **) &addr->prop.variables;
1438 int sep = ';';
1439
1440 if (!varlist) return OK;
1441
1442 /* Walk the varlist, creating variables */
1443
1444 for (uschar * ele; (ele = string_nextinlist(&varlist, &sep, NULL, 0)); )
1445   {
1446   const uschar * assignment = ele;
1447   int esep = '=';
1448   uschar * name = string_nextinlist(&assignment, &esep, NULL, 0);
1449   uschar * val;
1450   tree_node * node;
1451
1452   /* Variable name must exist and start "r_". */
1453
1454   if (!name || name[0] != 'r' || name[1] != '_' || !name[2])
1455     {
1456     log_write(0, LOG_MAIN|LOG_PANIC,
1457         "bad router variable name '%s' in router '%s'\n", name, r->name);
1458     return FAIL;
1459     }
1460   name += 2;
1461
1462   while (isspace(*assignment)) assignment++;
1463
1464   if (!(val = expand_string(US assignment)))
1465     if (f.expand_string_forcedfail)
1466       {
1467       int yield;
1468       BOOL more;
1469       DEBUG(D_route) debug_printf("forced failure in expansion of \"%s\" "
1470           "(router variable): decline action taken\n", ele);
1471
1472       /* Expand "more" if necessary; DEFER => an expansion failed */
1473
1474       yield = exp_bool(addr, US"router", r->name, D_route,
1475                       US"more", r->more, r->expand_more, &more);
1476       if (yield != OK) return yield;
1477
1478       if (!more)
1479         {
1480         DEBUG(D_route)
1481           debug_printf("\"more\"=false: skipping remaining routers\n");
1482         router_name = NULL;
1483         r = NULL;
1484         return FAIL;
1485         }
1486       return PASS;
1487       }
1488     else
1489       {
1490       addr->message = string_sprintf("expansion of \"%s\" failed "
1491         "in %s router: %s", ele, r->name, expand_string_message);
1492       return DEFER;
1493       }
1494
1495   if (!(node = tree_search(*root, name)))
1496     {                           /* name should never be tainted */
1497     node = store_get(sizeof(tree_node) + Ustrlen(name), FALSE);
1498     Ustrcpy(node->name, name);
1499     (void)tree_insertnode(root, node);
1500     }
1501   node->data.ptr = US val;
1502   DEBUG(D_route) debug_printf("set r_%s%s = '%s'%s\n",
1503                     name, is_tainted(name)?" (tainted)":"",
1504                     val, is_tainted(val)?" (tainted)":"");
1505
1506   /* All expansions after this point need visibility of that variable */
1507   router_var = *root;
1508   }
1509 return OK;
1510 }
1511
1512
1513 /*************************************************
1514 *                 Route one address              *
1515 *************************************************/
1516
1517 /* This function is passed in one address item, for processing by the routers.
1518 The verify flag is set if this is being called for verification rather than
1519 delivery. If the router doesn't have its "verify" flag set, it is skipped.
1520
1521 Arguments:
1522   addr           address to route
1523   paddr_local    chain of local-delivery addresses
1524   paddr_remote   chain of remote-delivery addresses
1525   addr_new       chain for newly created addresses
1526   addr_succeed   chain for completed addresses
1527   verify         v_none if not verifying
1528                  v_sender if verifying a sender address
1529                  v_recipient if verifying a recipient address
1530                  v_expn if processing an EXPN address
1531
1532 Returns:         OK      => address successfully routed
1533                  DISCARD => address was discarded
1534                  FAIL    => address could not be routed
1535                  DEFER   => some temporary problem
1536                  ERROR   => some major internal or configuration failure
1537 */
1538
1539 int
1540 route_address(address_item *addr, address_item **paddr_local,
1541   address_item **paddr_remote, address_item **addr_new,
1542   address_item **addr_succeed, int verify)
1543 {
1544 int yield = OK;
1545 BOOL unseen;
1546 router_instance *r, *nextr;
1547 const uschar *old_domain = addr->domain;
1548
1549 HDEBUG(D_route)
1550   {
1551   debug_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1552   debug_printf("routing %s\n", addr->address);
1553   }
1554
1555 /* Loop through all router instances until a router succeeds, fails, defers, or
1556 encounters an error. If the address has start_router set, we begin from there
1557 instead of at the first router. */
1558
1559 for (r = addr->start_router ? addr->start_router : routers; r; r = nextr)
1560   {
1561   uschar *error;
1562   struct passwd *pw = NULL;
1563   struct passwd pwcopy;
1564   BOOL loop_detected = FALSE;
1565   BOOL more;
1566   int loopcount = 0;
1567   int rc;
1568
1569   DEBUG(D_route) debug_printf("--------> %s router <--------\n", r->name);
1570
1571   /* Reset any search error message from the previous router. */
1572
1573   search_error_message = NULL;
1574
1575   /* There are some weird cases where logging is disabled */
1576
1577   f.disable_logging = r->disable_logging;
1578
1579   /* Record the last router to handle the address, and set the default
1580   next router. */
1581
1582   addr->router = r;
1583   nextr = r->next;
1584
1585   /* Loop protection: If this address has an ancestor with the same address,
1586   and that ancestor was routed by this router, we skip this router. This
1587   prevents a variety of looping states when a new address is created by
1588   redirection or by the use of "unseen" on a router.
1589
1590   If no_repeat_use is set on the router, we skip if _any_ ancestor was routed
1591   by  this router, even if it was different to the current address.
1592
1593   Just in case someone does put it into a loop (possible with redirection
1594   continually adding to an address, for example), put a long stop counter on
1595   the number of parents. */
1596
1597   for (address_item * parent = addr->parent; parent; parent = parent->parent)
1598     {
1599     if (parent->router == r)
1600       {
1601       BOOL break_loop = !r->repeat_use;
1602
1603       /* When repeat_use is set, first check the active addresses caselessly.
1604       If they match, we have to do a further caseful check of the local parts
1605       when caseful_local_part is set. This is assumed to be rare, which is why
1606       the code is written this way. */
1607
1608       if (!break_loop)
1609         {
1610         break_loop = strcmpic(parent->address, addr->address) == 0;
1611         if (break_loop && r->caseful_local_part)
1612           break_loop = Ustrncmp(parent->address, addr->address,
1613              Ustrrchr(addr->address, '@') - addr->address) == 0;
1614         }
1615
1616       if (break_loop)
1617         {
1618         DEBUG(D_route) debug_printf("%s router skipped: previously routed %s\n",
1619           r->name, parent->address);
1620         loop_detected = TRUE;
1621         break;
1622         }
1623       }
1624
1625     /* Continue with parents, limiting the size of the dynasty. */
1626
1627     if (loopcount++ > 100)
1628       {
1629       log_write(0, LOG_MAIN|LOG_PANIC, "routing loop for %s", addr->address);
1630       yield = DEFER;
1631       goto ROUTE_EXIT;
1632       }
1633     }
1634
1635   if (loop_detected) continue;
1636
1637   /* Default no affixes and select whether to use a caseful or caseless local
1638   part in this router. */
1639
1640   addr->prefix = addr->prefix_v = addr->suffix = addr->suffix_v = NULL;
1641   addr->local_part = r->caseful_local_part
1642     ? addr->cc_local_part : addr->lc_local_part;
1643
1644   DEBUG(D_route) debug_printf("local_part=%s domain=%s\n", addr->local_part,
1645     addr->domain);
1646
1647   /* Handle any configured prefix by replacing the local_part address,
1648   and setting the prefix. Skip the router if the prefix doesn't match,
1649   unless the prefix is optional. */
1650
1651   if (r->prefix)
1652     {
1653     unsigned vlen;
1654     int plen = route_check_prefix(addr->local_part, r->prefix, &vlen);
1655     if (plen > 0)
1656       {
1657       /* If the variable-part is zero-length then the prefix was not
1658       wildcarded and we can detaint-copy it since it matches the
1659       (non-expandable) router option.  Otherwise copy the (likely) tainted match
1660       and the variable-part of the match from the local_part. */
1661
1662       if (vlen)
1663         {
1664         addr->prefix = string_copyn(addr->local_part, plen);
1665         addr->prefix_v = string_copyn(addr->local_part, vlen);
1666         }
1667       else
1668         addr->prefix = string_copyn_taint(addr->local_part, plen, FALSE);
1669       addr->local_part += plen;
1670       DEBUG(D_route) debug_printf("stripped prefix %s\n", addr->prefix);
1671       }
1672     else if (!r->prefix_optional)
1673       {
1674       DEBUG(D_route) debug_printf("%s router skipped: prefix mismatch\n",
1675         r->name);
1676       continue;
1677       }
1678     }
1679
1680   /* Handle any configured suffix likewise. */
1681
1682   if (r->suffix)
1683     {
1684     unsigned vlen;
1685     int slen = route_check_suffix(addr->local_part, r->suffix, &vlen);
1686     if (slen > 0)
1687       {
1688       int lplen = Ustrlen(addr->local_part) - slen;
1689       addr->suffix = vlen
1690         ? addr->local_part + lplen
1691         : string_copy_taint(addr->local_part + lplen, slen);
1692       addr->suffix_v = addr->suffix + Ustrlen(addr->suffix) - vlen;
1693       addr->local_part = string_copyn(addr->local_part, lplen);
1694       DEBUG(D_route) debug_printf("stripped suffix %s\n", addr->suffix);
1695       }
1696     else if (!r->suffix_optional)
1697       {
1698       DEBUG(D_route) debug_printf("%s router skipped: suffix mismatch\n",
1699         r->name);
1700       continue;
1701       }
1702     }
1703
1704   /* Set the expansion variables now that we have the affixes and the case of
1705   the local part sorted. */
1706
1707   router_name = r->name;
1708   deliver_set_expansions(addr);
1709
1710   /* For convenience, the pre-router checks are in a separate function, which
1711   returns OK, SKIP, FAIL, or DEFER. */
1712
1713   if ((rc = check_router_conditions(r, addr, verify, &pw, &error)) != OK)
1714     {
1715     router_name = NULL;
1716     if (rc == SKIP) continue;
1717     addr->message = error;
1718     yield = rc;
1719     goto ROUTE_EXIT;
1720     }
1721
1722   /* All pre-conditions have been met. Reset any search error message from
1723   pre-condition tests. These can arise in negated tests where the failure of
1724   the lookup leads to a TRUE pre-condition. */
1725
1726   search_error_message = NULL;
1727
1728   /* Add any variable-settings that are on the router, to the set on the
1729   addr. Expansion is done here and not later when the addr is used.  There may
1730   be multiple settings, gathered during readconf; this code gathers them during
1731   router traversal.  On the addr string they are held as a variable tree, so
1732   as to maintain the post-expansion taints separate. */
1733
1734   switch (set_router_vars(addr, r))
1735     {
1736     case OK:    break;
1737     case PASS:  continue;               /* with next router */
1738     default:     goto ROUTE_EXIT;
1739     }
1740
1741   /* Finally, expand the address_data field in the router. Forced failure
1742   behaves as if the router declined. Any other failure is more serious. On
1743   success, the string is attached to the address for all subsequent processing.
1744   */
1745
1746   if (r->address_data)
1747     {
1748     DEBUG(D_route) debug_printf("processing address_data\n");
1749     if (!(deliver_address_data = expand_string(r->address_data)))
1750       {
1751       if (f.expand_string_forcedfail)
1752         {
1753         DEBUG(D_route) debug_printf("forced failure in expansion of \"%s\" "
1754             "(address_data): decline action taken\n", r->address_data);
1755
1756         /* Expand "more" if necessary; DEFER => an expansion failed */
1757
1758         yield = exp_bool(addr, US"router", r->name, D_route,
1759                         US"more", r->more, r->expand_more, &more);
1760         if (yield != OK) goto ROUTE_EXIT;
1761
1762         if (!more)
1763           {
1764           DEBUG(D_route)
1765             debug_printf("\"more\"=false: skipping remaining routers\n");
1766           router_name = NULL;
1767           r = NULL;
1768           break;
1769           }
1770         else continue;    /* With next router */
1771         }
1772
1773       else
1774         {
1775         addr->message = string_sprintf("expansion of \"%s\" failed "
1776           "in %s router: %s", r->address_data, r->name, expand_string_message);
1777         yield = DEFER;
1778         goto ROUTE_EXIT;
1779         }
1780       }
1781     addr->prop.address_data = deliver_address_data;
1782     }
1783
1784   /* We are finally cleared for take-off with this router. Clear the the flag
1785   that records that a local host was removed from a routed host list. Make a
1786   copy of relevant fields in the password information from check_local_user,
1787   because it will be overwritten if check_local_user is invoked again while
1788   verifying an errors_address setting. */
1789
1790   clearflag(addr, af_local_host_removed);
1791
1792   if (pw)
1793     {
1794     pwcopy.pw_name = CS string_copy(US pw->pw_name);
1795     pwcopy.pw_uid = pw->pw_uid;
1796     pwcopy.pw_gid = pw->pw_gid;
1797     pwcopy.pw_gecos = CS string_copy(US pw->pw_gecos);
1798     pwcopy.pw_dir = CS string_copy(US pw->pw_dir);
1799     pwcopy.pw_shell = CS string_copy(US pw->pw_shell);
1800     pw = &pwcopy;
1801     }
1802
1803   /* If this should be the last hop for DSN flag the addr. */
1804
1805   if (r->dsn_lasthop && !(addr->dsn_flags & rf_dsnlasthop))
1806     {
1807     addr->dsn_flags |= rf_dsnlasthop;
1808     HDEBUG(D_route) debug_printf("DSN: last hop for %s\n", addr->address);
1809     }
1810
1811   /* Run the router, and handle the consequences. */
1812
1813   HDEBUG(D_route) debug_printf("calling %s router\n", r->name);
1814
1815   yield = (r->info->code)(r, addr, pw, verify, paddr_local, paddr_remote,
1816     addr_new, addr_succeed);
1817
1818   router_name = NULL;
1819
1820   if (yield == FAIL)
1821     {
1822     HDEBUG(D_route) debug_printf("%s router forced address failure\n", r->name);
1823     goto ROUTE_EXIT;
1824     }
1825
1826   /* If succeeded while verifying but fail_verify is set, convert into
1827   a failure, and take it off the local or remote delivery list. */
1828
1829   if (  (  verify == v_sender && r->fail_verify_sender
1830         || verify == v_recipient && r->fail_verify_recipient
1831         )
1832      && (yield == OK || yield == PASS))
1833     {
1834     addr->message = string_sprintf("%s router forced verify failure", r->name);
1835     if (*paddr_remote == addr) *paddr_remote = addr->next;
1836     if (*paddr_local == addr) *paddr_local = addr->next;
1837     yield = FAIL;
1838     goto ROUTE_EXIT;
1839     }
1840
1841   /* PASS and DECLINE are the only two cases where the loop continues. For all
1842   other returns, we break the loop and handle the result below. */
1843
1844   if (yield != PASS && yield != DECLINE) break;
1845
1846   HDEBUG(D_route)
1847     {
1848     debug_printf("%s router %s for %s\n", r->name,
1849       yield == PASS ? "passed" : "declined", addr->address);
1850     if (Ustrcmp(old_domain, addr->domain) != 0)
1851       debug_printf("domain %s rewritten\n", old_domain);
1852     }
1853
1854   /* PASS always continues to another router; DECLINE does so if "more"
1855   is true. Initialization insists that pass_router is always a following
1856   router. Otherwise, break the loop as if at the end of the routers. */
1857
1858   if (yield == PASS)
1859     {
1860     if (r->pass_router != NULL) nextr = r->pass_router;
1861     }
1862   else
1863     {
1864     /* Expand "more" if necessary */
1865
1866     yield = exp_bool(addr, US"router", r->name, D_route,
1867                         US"more", r->more, r->expand_more, &more);
1868     if (yield != OK) goto ROUTE_EXIT;
1869
1870     if (!more)
1871       {
1872       HDEBUG(D_route)
1873         debug_printf("\"more\" is false: skipping remaining routers\n");
1874       r = NULL;
1875       break;
1876       }
1877     }
1878   }                                      /* Loop for all routers */
1879
1880 /* On exit from the routers loop, if r == NULL we have run out of routers,
1881 either genuinely, or as a result of no_more. Otherwise, the loop ended
1882 prematurely, either because a router succeeded, or because of some special
1883 router response. Note that FAIL errors and errors detected before actually
1884 running a router go direct to ROUTE_EXIT from code above. */
1885
1886 if (!r)
1887   {
1888   HDEBUG(D_route) debug_printf("no more routers\n");
1889   if (!addr->message)
1890     {
1891     uschar *message = US"Unrouteable address";
1892     if (addr->router && addr->router->cannot_route_message)
1893       {
1894       uschar *expmessage = expand_string(addr->router->cannot_route_message);
1895       if (!expmessage)
1896         {
1897         if (!f.expand_string_forcedfail)
1898           log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand "
1899             "cannot_route_message in %s router: %s", addr->router->name,
1900             expand_string_message);
1901         }
1902       else message = expmessage;
1903       }
1904     addr->user_message = addr->message = message;
1905     }
1906   addr->router = NULL;         /* For logging */
1907   yield = FAIL;
1908   goto ROUTE_EXIT;
1909   }
1910
1911 if (yield == DEFER)
1912   {
1913   HDEBUG(D_route) debug_printf("%s router: defer for %s\n  message: %s\n",
1914       r->name, addr->address, addr->message ? addr->message : US"<none>");
1915   goto ROUTE_EXIT;
1916   }
1917
1918 if (yield == DISCARD) goto ROUTE_EXIT;
1919
1920 /* The yield must be either OK or REROUTED. */
1921
1922 if (yield != OK && yield != REROUTED)
1923   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s router returned unknown value %d",
1924     r->name, yield);
1925
1926 /* If the yield was REROUTED, the router put a child address on the new chain
1927 as a result of a domain change of some sort (widening, typically). */
1928
1929 if (yield == REROUTED)
1930   {
1931   HDEBUG(D_route) debug_printf("re-routed to %s\n", addr->address);
1932   yield = OK;
1933   goto ROUTE_EXIT;
1934   }
1935
1936 /* The only remaining possibility is that the router succeeded. If the
1937 translate_ip_address options is set and host addresses were associated with the
1938 address, run them through the translation. This feature is for weird and
1939 wonderful situations (the amateur packet radio people need it) or very broken
1940 networking, so it is included in the binary only if requested. */
1941
1942 #ifdef SUPPORT_TRANSLATE_IP_ADDRESS
1943
1944 if (r->translate_ip_address)
1945   {
1946   int rc;
1947   int old_pool = store_pool;
1948   for (host_item * h = addr->host_list; h; h = h->next)
1949     {
1950     uschar *newaddress;
1951     uschar *oldaddress, *oldname;
1952
1953     if (!h->address) continue;
1954
1955     deliver_host_address = h->address;
1956     newaddress = expand_string(r->translate_ip_address);
1957     deliver_host_address = NULL;
1958
1959     if (!newaddress)
1960       {
1961       if (f.expand_string_forcedfail) continue;
1962       addr->basic_errno = ERRNO_EXPANDFAIL;
1963       addr->message = string_sprintf("translate_ip_address expansion "
1964         "failed: %s", expand_string_message);
1965       yield = DEFER;
1966       goto ROUTE_EXIT;
1967       }
1968
1969     DEBUG(D_route) debug_printf("%s [%s] translated to %s\n",
1970       h->name, h->address, newaddress);
1971     if (string_is_ip_address(newaddress, NULL) != 0)
1972       {
1973       h->address = newaddress;
1974       continue;
1975       }
1976
1977     oldname = h->name;
1978     oldaddress = h->address;
1979     h->name = newaddress;
1980     h->address = NULL;
1981     h->mx = MX_NONE;
1982
1983     store_pool = POOL_PERM;
1984     rc = host_find_byname(h, NULL, HOST_FIND_QUALIFY_SINGLE, NULL, TRUE);
1985     store_pool = old_pool;
1986
1987     if (rc == HOST_FIND_FAILED || rc == HOST_FIND_AGAIN)
1988       {
1989       addr->basic_errno = ERRNO_UNKNOWNHOST;
1990       addr->message = string_sprintf("host %s not found when "
1991         "translating %s [%s]", h->name, oldname, oldaddress);
1992       yield = DEFER;
1993       goto ROUTE_EXIT;
1994       }
1995     }
1996   }
1997 #endif  /* SUPPORT_TRANSLATE_IP_ADDRESS */
1998
1999 /* See if this is an unseen routing; first expand the option if necessary.
2000 DEFER can be given if the expansion fails */
2001
2002 yield = exp_bool(addr, US"router", r->name, D_route,
2003                 US"unseen", r->unseen, r->expand_unseen, &unseen);
2004 if (yield != OK) goto ROUTE_EXIT;
2005
2006 /* Debugging output recording a successful routing */
2007
2008 HDEBUG(D_route) debug_printf("routed by %s router%s\n", r->name,
2009     unseen? " (unseen)" : "");
2010
2011 DEBUG(D_route)
2012   {
2013   debug_printf("  envelope to: %s\n", addr->address);
2014   debug_printf("  transport: %s\n", addr->transport
2015     ? addr->transport->name : US"<none>");
2016
2017   if (addr->prop.errors_address)
2018     debug_printf("  errors to %s\n", addr->prop.errors_address);
2019
2020   for (host_item * h = addr->host_list; h; h = h->next)
2021     {
2022     debug_printf("  host %s", h->name);
2023     if (h->address) debug_printf(" [%s]", h->address);
2024     if (h->mx >= 0) debug_printf(" MX=%d", h->mx);
2025       else if (h->mx != MX_NONE) debug_printf(" rgroup=%d", h->mx);
2026     if (h->port != PORT_NONE) debug_printf(" port=%d", h->port);
2027     if (h->dnssec != DS_UNK) debug_printf(" dnssec=%s", h->dnssec==DS_YES ? "yes" : "no");
2028     debug_printf("\n");
2029     }
2030   }
2031
2032 /* Clear any temporary error message set by a router that declined, and handle
2033 the "unseen" option (ignore if there are no further routers). */
2034
2035 addr->message = NULL;
2036 if (unseen && r->next)
2037   route_unseen(r->name, addr, paddr_local, paddr_remote, addr_new);
2038
2039 /* Unset the address expansions, and return the final result. */
2040
2041 ROUTE_EXIT:
2042 if (yield == DEFER && addr->message)
2043   addr->message = expand_hide_passwords(addr->message);
2044
2045 deliver_set_expansions(NULL);
2046 router_name = NULL;
2047 f.disable_logging = FALSE;
2048 return yield;
2049 }
2050
2051 #endif  /*!MACRO_PREDEF*/
2052 /* End of route.c */