CVE-2020-28009: Integer overflow in get_stdinput()
[exim.git] / src / src / rewrite.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8 /* Functions concerned with rewriting headers */
9
10
11 #include "exim.h"
12
13 /* Names for testing rewriting */
14
15 static const char *rrname[] = {
16   "  sender",
17   "    from",
18   "      to",
19   "      cc",
20   "     bcc",
21   "reply-to",
22   "env-from",
23   "  env-to"
24 };
25
26 /* Structure and table for finding source of address for debug printing */
27
28 typedef struct where_list_block {
29   int bit;
30   const uschar *string;
31 } where_list_block;
32
33 static where_list_block where_list[] = {
34   { rewrite_sender,  CUS"sender:" },
35   { rewrite_from,    CUS"from:" },
36   { rewrite_to,      CUS"to:" },
37   { rewrite_cc,      CUS"cc:" },
38   { rewrite_bcc,     CUS"bcc:" },
39   { rewrite_replyto, CUS"reply-to:" },
40   { rewrite_envfrom, CUS"env-from" },
41   { rewrite_envto,   CUS"env-to" },
42   { rewrite_smtp,    CUS"smtp recipient" },
43   { rewrite_smtp|rewrite_smtp_sender, CUS"smtp sender" }
44 };
45
46 static int where_list_size = sizeof(where_list)/sizeof(where_list_block);
47
48
49
50 /*************************************************
51 *            Ensure an address is qualified      *
52 *************************************************/
53
54 /*
55 Arguments:
56   s              address to check
57   is_recipient   TRUE if a recipient address; FALSE if a sender address
58
59 Returns:         fully-qualified address
60 */
61
62 const uschar *
63 rewrite_address_qualify(const uschar *s, BOOL is_recipient)
64 {
65 return parse_find_at(s)
66   ? s : string_sprintf("%s@%s", s,
67           is_recipient ? qualify_domain_recipient : qualify_domain_sender);
68 }
69
70
71
72 /*************************************************
73 *               Rewrite a single address         *
74 *************************************************/
75
76 /* The yield is the input address if there is no rewriting to be done. Assume
77 the input is a valid address, except in the case of SMTP-time rewriting, which
78 is handled specially. When this function is called while processing filter and
79 forward files, the uid may be that of the user. Ensure it is reset while
80 expanding a replacement, in case that involves file lookups.
81
82 Arguments:
83   s              address to rewrite
84   flag           indicates where this address comes from; it must match the
85                    flags in the rewriting rule
86   whole          if not NULL, set TRUE if any rewriting rule contained the
87                    "whole" bit and it is a header that is being rewritten
88   add_header     if TRUE and rewriting occurs, add an "X-rewrote-xxx" header
89                    if headers are in existence; this should be TRUE only when
90                    a message is being received, not during delivery
91   name           name of header, for use when adding X-rewrote-xxxx
92   rewrite_rules  chain of rewriting rules
93
94 Returns:         new address if rewritten; the input address if no change;
95                  for a header rewrite, if the "whole" bit is set, the entire
96                  rewritten address is returned, not just the active bit.
97 */
98
99 const uschar *
100 rewrite_one(const uschar *s, int flag, BOOL *whole, BOOL add_header, uschar *name,
101   rewrite_rule *rewrite_rules)
102 {
103 const uschar *yield = s;
104 const uschar *subject = s;
105 uschar *domain = NULL;
106 BOOL done = FALSE;
107 int rule_number = 1;
108 int yield_start = 0, yield_end = 0;
109
110 if (whole) *whole = FALSE;
111
112 /* Scan the rewriting rules */
113
114 for (rewrite_rule * rule = rewrite_rules;
115      rule && !done;
116      rule_number++, rule = rule->next)
117   {
118   int start, end, pdomain;
119   int count = 0;
120   uschar *save_localpart;
121   const uschar *save_domain;
122   uschar *error, *new;
123   const uschar * newparsed;
124
125   /* Ensure that the flag matches the flags in the rule. */
126
127   if (!(rule->flags & flag)) continue;
128
129   /* Come back here for a repeat after a successful rewrite. We do this
130   only so many times. */
131
132   REPEAT_RULE:
133
134   /* If this is an SMTP-time rewrite, the pattern must be a regex and
135   the subject may have any structure. No local part or domain variables
136   can be set for the expansion. We expand the pattern in order to be consistent
137   with the other kinds of rewrite, where expansion happens inside
138   match_address_list(). */
139
140   if (flag & rewrite_smtp)
141     {
142     uschar *key = expand_string(rule->key);
143     if (!key)
144       {
145       if (!f.expand_string_forcedfail)
146         log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand \"%s\" while "
147           "checking for SMTP rewriting: %s", rule->key, expand_string_message);
148       continue;
149       }
150     if (match_check_string(subject, key, 0, TRUE, FALSE, FALSE, NULL) != OK)
151       continue;
152     new = expand_string(rule->replacement);
153     }
154
155   /* All other rewrites expect the input to be a valid address, so local part
156   and domain variables can be set for expansion. For the first rule, to be
157   applied to this address, domain will be NULL and needs to be set. */
158
159   else
160     {
161     if (!domain) domain = Ustrrchr(subject, '@') + 1;
162
163     /* Use the general function for matching an address against a list (here
164     just one item, so use the "impossible value" separator UCHAR_MAX+1). */
165
166     if (match_address_list(subject, FALSE, TRUE, CUSS &(rule->key), NULL, 0,
167         UCHAR_MAX + 1, NULL) != OK)
168       continue;
169
170     /* The source address matches, and numerical variables have been
171     set up. If the replacement string consists of precisely "*" then no
172     rewriting is required for this address - the behaviour is as for "fail"
173     in the replacement expansion, but assuming the quit flag. */
174
175     if (Ustrcmp(rule->replacement, "*") == 0) break;
176
177     /* Otherwise, expand the replacement string. Set $local_part and $domain to
178     the appropriate values, restoring whatever value they previously had
179     afterwards. */
180
181     save_localpart = deliver_localpart;
182     save_domain = deliver_domain;
183
184     /* We have subject pointing to "localpart@domain" and domain pointing to
185     the domain. Temporarily terminate the local part so that it can be
186     set up as an expansion variable */
187
188     domain[-1] = 0;
189     deliver_localpart = US subject;
190     deliver_domain = domain;
191
192     new = expand_string(rule->replacement);
193
194     domain[-1] = '@';
195     deliver_localpart = save_localpart;
196     deliver_domain = save_domain;
197     }
198
199   /* If the expansion failed with the "forcedfail" flag, don't generate
200   an error - just give up on this rewriting rule. If the "q" flag is set,
201   give up altogether. For other expansion failures we have a configuration
202   error. */
203
204   if (!new)
205     {
206     if (f.expand_string_forcedfail)
207       { if (rule->flags & rewrite_quit) break; else continue; }
208
209     expand_string_message = expand_hide_passwords(expand_string_message);
210
211     log_write(0, LOG_MAIN|LOG_PANIC, "Expansion of %s failed while rewriting: "
212       "%s", rule->replacement, expand_string_message);
213     break;
214     }
215
216   /* Check the what has been generated is a valid RFC 2822 address. Only
217   envelope from or SMTP sender is permitted to be rewritten as <>.*/
218
219   newparsed = parse_extract_address(new, &error, &start, &end, &pdomain,
220     flag == rewrite_envfrom || flag == (rewrite_smtp|rewrite_smtp_sender));
221
222   if (!newparsed)
223     {
224     log_write(0, LOG_MAIN|LOG_PANIC, "Rewrite of %s yielded unparseable "
225       "address: %s in address %s", subject, error, new);
226     break;   /* Give up on this address */
227     }
228
229   /* A non-null unqualified address can be qualified if requested. Otherwise,
230   this is an error unless it's the empty address in circumstances where that is
231   permitted. */
232
233   if (pdomain == 0 && (*newparsed != 0 ||
234       (flag != rewrite_envfrom && flag != (rewrite_smtp|rewrite_smtp_sender))))
235     {
236     if (rule->flags & rewrite_qualify)
237       {
238       newparsed = rewrite_address_qualify(newparsed, TRUE);
239       new = string_sprintf("%.*s%s%.*s", start, new, newparsed,
240         Ustrlen(new) - end, new + end);
241       end = start + Ustrlen(newparsed);
242       }
243     else
244       {
245       log_write(0, LOG_MAIN|LOG_PANIC, "Rewrite of %s yielded unqualified "
246         "address \"%s\"", subject, new);
247       break;   /* Give up on this address */
248       }
249     }
250
251   /* We have a validly rewritten address */
252
253   if (LOGGING(address_rewrite) || (debug_selector & D_rewrite) != 0)
254     {
255     const uschar *where = CUS"?";
256
257     for (int i = 0; i < where_list_size; i++)
258       if (flag == where_list[i].bit)
259         {
260         where = where_list[i].string;
261         break;
262         }
263     log_write(L_address_rewrite,
264            LOG_MAIN, "\"%s\" from %s rewritten as \"%s\" by rule %d",
265            yield, where, new, rule_number);
266     }
267
268   /* A header will only actually be added if header_last is non-NULL,
269   i.e. during message reception or delivery, but add_header should not
270   be set TRUE during delivery, as otherwise multiple instances of the header
271   can fill up the -H file and make it embarrassingly large. We don't need
272   to set header_rewritten because the -H file always gets written at the end
273   of message reception. */
274
275   if (add_header)
276     header_add(htype_old, "X-rewrote-%s: %s\n", name, subject);
277
278   /* Handle the case when replacement of the whole address is possible.
279   This happens only when whole is not NULL and we are rewriting a header.
280   If *whole is already TRUE it means that a previous rule had the w
281   flag set and so we must preserve the non-active portion of the current
282   subject unless the current rule also has the w flag set. */
283
284   if (whole && (flag & rewrite_all_headers))
285     {
286     /* Current rule has the w flag set. We must ensure the phrase parts
287     are syntactically valid if they are present. */
288
289     if (rule->flags & rewrite_whole)
290       {
291       if (start > 0 && new[start-1] == '<')
292         {
293         uschar *p1 = new + start - 1;
294         uschar *p2 = new + end + 1;
295         const uschar *pf1, *pf2;
296
297         while (p1 > new && p1[-1] == ' ') p1--;
298         pf1 = parse_fix_phrase(new, p1 - new);
299         while (*p2 == ' ') p2++;
300         pf2 = parse_fix_phrase(p2, Ustrlen(p2));
301
302         start = Ustrlen(pf1) + start + new - p1;
303         end = start + Ustrlen(newparsed);
304         new = string_sprintf("%s%.*s%s", pf1, (int)(p2 - p1), p1, pf2);
305         }
306
307       /* Now accept the whole thing */
308
309       yield = new;
310       yield_start = start;
311       yield_end = end;
312       subject = newparsed;
313       *whole = TRUE;
314       }
315
316     /* Current rule does not have the w flag set; if not previously
317     done any whole rewriting, behave in non-whole manner. */
318
319     else if (!*whole) goto NEVER_WHOLE;
320
321     /* Current rule does not have the w flag set, but a previous
322     rule did rewrite the whole address. Thus yield and subject will be
323     different. Preserve the previous non-active part of the address. */
324
325     else
326       {
327       subject = newparsed;
328       new = string_sprintf("%.*s%s%n%s",
329          yield_start, yield, subject, &end, yield + yield_end);
330       yield_end = end;
331       yield = new;
332       }
333     }
334
335   /* Rule just rewrites active part, or handling an envelope. This
336   code is obeyed only when all rules so far have not done "whole"
337   replacement. */
338
339   else
340     {
341     NEVER_WHOLE:
342     subject = yield = newparsed;
343     }
344
345   domain = NULL;    /* Reset for next rule */
346
347   /* If no further rewrites are to be done, set the done flag. This allows
348   repeats of the current rule if configured before breaking the loop. */
349
350   if (rule->flags & rewrite_quit) done = TRUE;
351
352   /* Allow the current rule to be applied up to 10 times if
353   requested. */
354
355   if (rule->flags & rewrite_repeat)
356     {
357     if (count++ < 10) goto REPEAT_RULE;
358     log_write(0, LOG_MAIN|LOG_PANIC, "rewrite rule repeat ignored after 10 "
359       "times");
360     }
361   }
362
363 /* Unset expansion numeric variables, and that's it. */
364
365 expand_nmax = -1;
366 return yield;
367 }
368
369
370
371 /*************************************************
372 *         Ensure qualification and rewrite       *
373 *************************************************/
374
375 /* This function is called for envelope addresses, the boolean specifying
376 whether a recipient or a sender. It must first of all ensure the address is
377 fully qualified, and then apply any relevant re-writing rules. The add-header
378 flag causes a header to be added, recording the old address. This is marked
379 "old", so that it is never transported anywhere; it exists for local checking
380 and debugging purposes.
381
382 Arguments:
383   s              the address to be considered
384   is_recipient   TRUE for recipient addresses; FALSE otherwise
385   add_header     add "X-rewrote-xxx" header when rewriting; this is
386                    set TRUE only for calls from the reception functions
387   rewrite_rules  points to chain of rewrite rules
388   existflags     bits indicating which headers there are rewrites for
389                  (just an optimisation)
390
391 Returns:         possibly rewritten address
392 */
393
394 const uschar *
395 rewrite_address(const uschar *s, BOOL is_recipient, BOOL add_header,
396   rewrite_rule *rewrite_rules, int existflags)
397 {
398 int flag = is_recipient ? rewrite_envto : rewrite_envfrom;
399
400 s = rewrite_address_qualify(s, is_recipient);
401 if (existflags & flag)
402   {
403   const uschar *new = rewrite_one(s, flag, NULL, add_header, is_recipient?
404     US"original-recipient" : US"sender", rewrite_rules);
405   if (new != s) s = new;
406   }
407 return s;
408 }
409
410
411
412 /*************************************************
413 *    Qualify and possibly rewrite one header     *
414 *************************************************/
415
416 /* This is called only from rewrite_header() below, either when reading a
417 message. or when routing, in order to rewrite addresses that get changed by a
418 router. This is normally the addition of full qualification to a partial
419 domain. The first rewriting rule in this case is "change routed_old into
420 routed_new", and it applies to all header lines that contain addresses. Then
421 header-specific rewriting rules are applied.
422
423 Before rewriting can be done, addresses without domains have to be qualified.
424 This should only be done for messages from "local" senders. This is a difficult
425 concept to pin down, what with the use of SMTP both as a submission and as a
426 transmission protocol. Exim normally requires incoming SMTP to contain fully-
427 qualified addresses, but there are options to permit unqualified ones from
428 certain hosts. For those hosts only, addresses in headers can also be
429 qualified. For other hosts, unqualified addresses in headers do not get touched
430 in any way. For locally sourced messages, unqualified addresses always get
431 qualified, except when -bnq is used to explicitly suppress this.
432
433 Arguments:
434   h              pointer to header line block
435   flag           indicates which header this is
436   routed_old     if not NULL, this is a rewrite caused by a router, changing
437                    this domain into routed_new
438   routed_new     new routed domain if routed_old is not NULL
439   rewrite_rules  points to chain of rewriting rules
440   existflags     bits indicating which rewrites exist
441   replace        if TRUE, insert the new header in the chain after the old
442                    one, and mark the old one "replaced"
443
444 Returns:         NULL if header unchanged; otherwise the rewritten header
445 */
446
447 static header_line *
448 rewrite_one_header(header_line *h, int flag,
449   const uschar *routed_old, const uschar *routed_new,
450   rewrite_rule *rewrite_rules, int existflags, BOOL replace)
451 {
452 int lastnewline = 0;
453 header_line *newh = NULL;
454 rmark function_reset_point = store_mark();
455 uschar *s = Ustrchr(h->text, ':') + 1;
456 while (isspace(*s)) s++;
457
458 DEBUG(D_rewrite)
459   debug_printf("rewrite_one_header: type=%c:\n  %s", h->type, h->text);
460
461 f.parse_allow_group = TRUE;     /* Allow group syntax */
462
463 /* Loop for multiple addresses in the header. We have to go through them all
464 in case any need qualifying, even if there's no rewriting. Pathological headers
465 may have thousands of addresses in them, so cause the store to be reset for
466 any that don't actually get rewritten. We also play silly games for those that
467 _are_ rewritten so as to avoid runaway store usage for these kinds of header.
468 We want to avoid keeping store for any intermediate versions. */
469
470 while (*s)
471   {
472   uschar *sprev;
473   uschar *ss = parse_find_address_end(s, FALSE);
474   uschar *recipient, *new, *errmess;
475   rmark loop_reset_point = store_mark();
476   BOOL changed = FALSE;
477   int terminator = *ss;
478   int start, end, domain;
479
480   /* Temporarily terminate the string at this point, and extract the
481   operative address within. Then put back the terminator and prepare for
482   the next address, saving the start of the old one. */
483
484   *ss = 0;
485   recipient = parse_extract_address(s,&errmess,&start,&end,&domain,FALSE);
486   *ss = terminator;
487   sprev = s;
488   s = ss + (terminator? 1:0);
489   while (isspace(*s)) s++;
490
491   /* There isn't much we can do for syntactic disasters at this stage.
492   Pro tem (possibly for ever) ignore them. */
493
494   if (!recipient)
495     {
496     loop_reset_point = store_reset(loop_reset_point);
497     continue;
498     }
499
500   /* If routed_old is not NULL, this is a rewrite caused by a router,
501   consisting of changing routed_old into routed_new, and applying to all
502   headers. If the header address has no domain, it is excluded, since a router
503   rewrite affects domains only. The new value should always be fully qualified,
504   but it may be something that has an explicit re-write rule set, so we need to
505   check the configured rules subsequently as well. (Example: there's an
506   explicit rewrite turning *.foo.com into foo.com, and an address is supplied
507   as abc@xyz, which the DNS lookup turns into abc@xyz.foo.com). However, if no
508   change is made here, don't bother carrying on. */
509
510   if (routed_old != NULL)
511     {
512     if (domain <= 0 || strcmpic(recipient+domain, routed_old) != 0) continue;
513     recipient[domain-1] = 0;
514     new = string_sprintf("%s@%s", recipient, routed_new);
515     DEBUG(D_rewrite)
516       {
517       recipient[domain-1] = '@';
518       debug_printf("%s rewritten by router as %s\n", recipient, new);
519       }
520     recipient = new;
521     changed = TRUE;
522     }
523
524   /* This is not a router-inspired rewrite. Ensure the address is fully
525   qualified if that is permitted. If an unqualified address was received
526   from a host that isn't listed, do not continue rewriting this address.
527   Sender, From or Reply-To headers are treated as senders, the rest as
528   recipients. This matters only when there are different qualify strings. */
529
530   else
531     {
532     BOOL is_recipient =
533       (flag & (rewrite_sender | rewrite_from | rewrite_replyto)) == 0;
534     /* deconst ok as recipient was notconst */
535     new = US rewrite_address_qualify(recipient, is_recipient);
536     changed = (new != recipient);
537     recipient = new;
538
539     /* Can only qualify if permitted; if not, no rewrite. */
540
541     if (changed && ((is_recipient && !f.allow_unqualified_recipient) ||
542                     (!is_recipient && !f.allow_unqualified_sender)))
543       {
544       loop_reset_point = store_reset(loop_reset_point);
545       continue;
546       }
547     }
548
549   /* If there are rewrite rules for this type of header, apply
550   them. This test is just for efficiency, to save scanning the rules
551   in cases when nothing is going to change. If any rewrite rule had the
552   "whole" flag set, adjust the pointers so that the whole address gets
553   replaced, except possibly a final \n. */
554
555   if ((existflags & flag) != 0)
556     {
557     BOOL whole;
558     /* deconst ok as recipient was notconst */
559     new = US rewrite_one(recipient, flag, &whole, FALSE, NULL, rewrite_rules);
560     if (new != recipient)
561       {
562       changed = TRUE;
563       if (whole)
564         {
565         start = 0;
566         end = ss - sprev;
567         if (sprev[end-1] == '\n') end--;
568         }
569       }
570     }
571
572   /* If nothing has changed, lose all dynamic store obtained in this loop, and
573   move on to the next address. We can't reset to the function start store
574   point, because we may have a rewritten line from a previous time round the
575   loop. */
576
577   if (!changed) loop_reset_point = store_reset(loop_reset_point);
578
579   /* If the address has changed, create a new header containing the
580   rewritten address. We do not need to set the chain pointers at this
581   stage. We want to avoid using more and more memory if the header is very long
582   and contains lots and lots of rewritten addresses. Therefore, we build the
583   new text string in malloc store, then at the end we reset dynamic store
584   before copying the new header to a new block (and then freeing the malloc
585   block). The header must end up in dynamic store so that it's freed at the end
586   of receiving a message. */
587
588   else
589     {
590     int remlen;
591     int newlen = Ustrlen(new);
592     int oldlen = end - start;
593
594     header_line * prev = newh ? newh : h;
595     uschar * newt = store_get_perm(prev->slen - oldlen + newlen + 4, TRUE);
596     uschar * newtstart = newt;
597
598     int type = prev->type;
599     int slen = prev->slen - oldlen + newlen;
600
601     /* Build the new header text by copying the old and putting in the
602     replacement. This process may make the header substantially longer
603     than it was before - qualification of a list of bare addresses can
604     often do this - so we stick in a newline after the re-written address
605     if it has increased in length and ends more than 40 characters in. In
606     fact, the code is not perfect, since it does not scan for existing
607     newlines in the header, but it doesn't seem worth going to that
608     amount of trouble. */
609
610     Ustrncpy(newt, prev->text, sprev - prev->text + start);
611     newt += sprev - prev->text + start;
612     *newt = 0;
613     Ustrcat(newt, new);
614     newt += newlen;
615     remlen = s - (sprev + end);
616     if (remlen > 0)
617       {
618       Ustrncpy(newt, sprev + end, remlen);
619       newt += remlen;
620       *newt = 0;
621       }
622
623     /* Must check that there isn't a newline here anyway; in particular, there
624     will be one at the very end of the header, where we DON'T want to insert
625     another one! The pointer s has been skipped over white space, so just
626     look back to see if the last non-space-or-tab was a newline. */
627
628     if (newlen > oldlen && newt - newtstart - lastnewline > 40)
629       {
630       uschar *p = s - 1;
631       while (p >= prev->text && (*p == ' ' || *p == '\t')) p--;
632       if (*p != '\n')
633         {
634         lastnewline = newt - newtstart;
635         Ustrcat(newt, US"\n\t");
636         slen += 2;
637         }
638       }
639
640     /* Finally, the remaining unprocessed addresses, if any. */
641
642     Ustrcat(newt, s);
643
644     DEBUG(D_rewrite) debug_printf("newlen=%d newtype=%c newtext:\n%s",
645       slen, type, newtstart);
646
647     /* Compute the length of the rest of the header line before we possibly
648     flatten a previously rewritten copy. */
649
650     remlen = (s - prev->text) - oldlen + newlen;
651
652     /* We have the new text in a malloc block. That enables us to release all
653     the memory that has been used, back to the point at which the function was
654     entered. Then set up a new header in dynamic store. This will override a
655     rewritten copy from a previous time round this loop. */
656
657     store_reset(function_reset_point);
658     function_reset_point = store_mark();
659     newh = store_get(sizeof(header_line), FALSE);
660     newh->type = type;
661     newh->slen = slen;
662     newh->text = string_copyn(newtstart, slen);
663
664     /* Set up for scanning the rest of the header */
665
666     s = newh->text + remlen;
667     DEBUG(D_rewrite) debug_printf("remainder: %s", (*s == 0)? US"\n" : s);
668     }
669   }
670
671 f.parse_allow_group = FALSE;  /* Reset group flags */
672 f.parse_found_group = FALSE;
673
674 /* If a rewrite happened and "replace" is true, put the new header into the
675 chain following the old one, and mark the old one as replaced. */
676
677 if (newh != NULL && replace)
678   {
679   newh->next = h->next;
680   if (newh->next == NULL) header_last = newh;
681   h->type = htype_old;
682   h->next = newh;
683   }
684
685 return newh;
686 }
687
688
689
690
691 /*************************************************
692 *              Rewrite a header line             *
693 *************************************************/
694
695 /* This function may be passed any old header line. It must detect those which
696 contain addresses, then then apply any rewriting rules that apply. If
697 routed_old is NULL, only the configured rewriting rules are consulted.
698 Otherwise, the rewriting rule is "change routed_old into routed_new", and it
699 applies to all header lines that contain addresses. Then header-specific
700 rewriting rules are applied.
701
702 The old header line is flagged as "old". Old headers are saved on the spool for
703 debugging but are never sent to any recipients.
704
705 Arguments:
706   h              header line to rewrite
707   routed_old     if not NULL, this is a rewrite caused by a router, changing
708                    this domain into routed_new
709   routed_new     new routed domain if routed_old is not NULL
710   rewrite_rules  points to chain of rewrite rules
711   existflags     bits indicating which rewrites exist
712   replace        if TRUE, the new header is inserted into the header chain
713                     after the old one, and the old one is marked replaced
714
715 Returns:         NULL if header unchanged; otherwise the rewritten header
716 */
717
718 header_line *
719 rewrite_header(header_line *h,
720   const uschar *routed_old, const uschar *routed_new,
721   rewrite_rule *rewrite_rules, int existflags, BOOL replace)
722 {
723 int flag;
724 switch (h->type)
725   {
726   case htype_sender:    flag = rewrite_sender;  break;
727   case htype_from:      flag = rewrite_from;    break;
728   case htype_to:        flag = rewrite_to;      break;
729   case htype_cc:        flag = rewrite_cc;      break;
730   case htype_bcc:       flag = rewrite_bcc;     break;
731   case htype_reply_to:  flag = rewrite_replyto; break;
732   default:              return NULL;
733   }
734 return rewrite_one_header(h, flag, routed_old, routed_new,
735   rewrite_rules, existflags, replace);
736 }
737
738
739
740 /************************************************
741 *            Test rewriting rules               *
742 ************************************************/
743
744 /* Called from the mainline as a result of the -brw option. Test the
745 address for all possible cases.
746
747 Argument: the address to test
748 Returns:  nothing
749 */
750
751 void
752 rewrite_test(const uschar *s)
753 {
754 uschar *recipient, *error;
755 int start, end, domain;
756 BOOL done_smtp = FALSE;
757
758 if (rewrite_existflags == 0)
759   {
760   printf("No rewrite rules are defined\n");
761   return;
762   }
763
764 /* Do SMTP rewrite only if a rule with the S flag exists. Allow <> by
765 pretending it is a sender. */
766
767 if ((rewrite_existflags & rewrite_smtp) != 0)
768   {
769   const uschar * new = rewrite_one(s, rewrite_smtp|rewrite_smtp_sender, NULL,
770     FALSE, US"", global_rewrite_rules);
771   if (new != s)
772     {
773     if (*new == 0)
774       printf("    SMTP: <>\n");
775     else
776       printf("    SMTP: %s\n", new);
777     done_smtp = TRUE;
778     }
779   }
780
781 /* Do the other rewrites only if a rule without the S flag exists */
782
783 if ((rewrite_existflags & ~rewrite_smtp) == 0) return;
784
785 /* Qualify if necessary before extracting the address */
786
787 if (parse_find_at(s) == NULL)
788   s = string_sprintf("%s@%s", s, qualify_domain_recipient);
789
790 recipient = parse_extract_address(s, &error, &start, &end, &domain, FALSE);
791
792 if (!recipient)
793   {
794   if (!done_smtp)
795     printf("Syntax error in %s\n%c%s\n", s, toupper(error[0]), error+1);
796   return;
797   }
798
799 for (int i = 0; i < 8; i++)
800   {
801   BOOL whole = FALSE;
802   int flag = 1 << i;
803   const uschar * new = rewrite_one(recipient, flag, &whole, FALSE, US"",
804     global_rewrite_rules);
805   printf("%s: ", rrname[i]);
806   if (*new == 0)
807     printf("<>\n");
808   else if (whole || (flag & rewrite_all_headers) == 0)
809     printf("%s\n", CS new);
810   else printf("%.*s%s%s\n", start, s, new, s+end);
811   }
812 }
813
814 /* End of rewrite.c */