1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) The Exim Maintainers 2021 - 2022 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
9 /* Functions concerned with rewriting headers */
14 /* Names for testing rewriting */
16 static const char *rrname[] = {
27 /* Structure and table for finding source of address for debug printing */
29 typedef struct where_list_block {
34 static where_list_block where_list[] = {
35 { rewrite_sender, CUS"sender:" },
36 { rewrite_from, CUS"from:" },
37 { rewrite_to, CUS"to:" },
38 { rewrite_cc, CUS"cc:" },
39 { rewrite_bcc, CUS"bcc:" },
40 { rewrite_replyto, CUS"reply-to:" },
41 { rewrite_envfrom, CUS"env-from" },
42 { rewrite_envto, CUS"env-to" },
43 { rewrite_smtp, CUS"smtp recipient" },
44 { rewrite_smtp|rewrite_smtp_sender, CUS"smtp sender" }
47 static int where_list_size = sizeof(where_list)/sizeof(where_list_block);
51 /*************************************************
52 * Ensure an address is qualified *
53 *************************************************/
58 is_recipient TRUE if a recipient address; FALSE if a sender address
60 Returns: fully-qualified address
64 rewrite_address_qualify(const uschar *s, BOOL is_recipient)
66 return parse_find_at(s)
67 ? s : string_sprintf("%s@%s", s,
68 is_recipient ? qualify_domain_recipient : qualify_domain_sender);
73 /*************************************************
74 * Rewrite a single address *
75 *************************************************/
77 /* The yield is the input address if there is no rewriting to be done. Assume
78 the input is a valid address, except in the case of SMTP-time rewriting, which
79 is handled specially. When this function is called while processing filter and
80 forward files, the uid may be that of the user. Ensure it is reset while
81 expanding a replacement, in case that involves file lookups.
85 flag indicates where this address comes from; it must match the
86 flags in the rewriting rule
87 whole if not NULL, set TRUE if any rewriting rule contained the
88 "whole" bit and it is a header that is being rewritten
89 add_header if TRUE and rewriting occurs, add an "X-rewrote-xxx" header
90 if headers are in existence; this should be TRUE only when
91 a message is being received, not during delivery
92 name name of header, for use when adding X-rewrote-xxxx
93 rewrite_rules chain of rewriting rules
95 Returns: new address if rewritten; the input address if no change;
96 for a header rewrite, if the "whole" bit is set, the entire
97 rewritten address is returned, not just the active bit.
101 rewrite_one(const uschar *s, int flag, BOOL *whole, BOOL add_header, uschar *name,
102 rewrite_rule *rewrite_rules)
104 const uschar *yield = s;
105 const uschar *subject = s;
106 uschar *domain = NULL;
109 int yield_start = 0, yield_end = 0;
111 if (whole) *whole = FALSE;
113 /* Scan the rewriting rules, ignoring any without matching flag */
115 for (rewrite_rule * rule = rewrite_rules;
117 rule_number++, rule = rule->next) if (rule->flags & flag)
119 int start, end, pdomain;
121 uschar *save_localpart;
122 const uschar *save_domain;
124 const uschar * newparsed;
126 /* Come back here for a repeat after a successful rewrite. We do this
127 only so many times. */
131 /* If this is an SMTP-time rewrite, the pattern must be a regex and
132 the subject may have any structure. No local part or domain variables
133 can be set for the expansion. We expand the pattern in order to be consistent
134 with the other kinds of rewrite, where expansion happens inside
135 match_address_list(). */
137 if (flag & rewrite_smtp)
140 const uschar * key = expand_string_2(rule->key, &textonly_re);
143 if (!f.expand_string_forcedfail)
144 log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand \"%s\" while "
145 "checking for SMTP rewriting: %s", rule->key, expand_string_message);
148 if (match_check_string(subject, key, 0,
149 textonly_re ? MCS_CACHEABLE | MCS_PARTIAL : MCS_PARTIAL, NULL) != OK)
151 new = expand_string(rule->replacement);
154 /* All other rewrites expect the input to be a valid address, so local part
155 and domain variables can be set for expansion. For the first rule, to be
156 applied to this address, domain will be NULL and needs to be set. */
160 if (!domain) domain = Ustrrchr(subject, '@') + 1;
162 /* Use the general function for matching an address against a list (here
163 just one item, so use the "impossible value" separator UCHAR_MAX+1). */
165 if (match_address_list(subject, FALSE, TRUE, CUSS &(rule->key), NULL, 0,
166 UCHAR_MAX + 1, NULL) != OK)
169 /* The source address matches, and numerical variables have been
170 set up. If the replacement string consists of precisely "*" then no
171 rewriting is required for this address - the behaviour is as for "fail"
172 in the replacement expansion, but assuming the quit flag. */
174 if (Ustrcmp(rule->replacement, "*") == 0) break;
176 /* Otherwise, expand the replacement string. Set $local_part and $domain to
177 the appropriate values, restoring whatever value they previously had
180 save_localpart = deliver_localpart;
181 save_domain = deliver_domain;
183 /* We have subject pointing to "localpart@domain" and domain pointing to
184 the domain. Temporarily terminate the local part so that it can be
185 set up as an expansion variable */
188 deliver_localpart = US subject;
189 deliver_domain = domain;
191 new = expand_string(rule->replacement);
194 deliver_localpart = save_localpart;
195 deliver_domain = save_domain;
198 /* If the expansion failed with the "forcedfail" flag, don't generate
199 an error - just give up on this rewriting rule. If the "q" flag is set,
200 give up altogether. For other expansion failures we have a configuration
205 if (f.expand_string_forcedfail)
206 { if (rule->flags & rewrite_quit) break; else continue; }
208 expand_string_message = expand_hide_passwords(expand_string_message);
210 log_write(0, LOG_MAIN|LOG_PANIC, "Expansion of %s failed while rewriting: "
211 "%s", rule->replacement, expand_string_message);
215 /* Check the what has been generated is a valid RFC 2822 address. Only
216 envelope from or SMTP sender is permitted to be rewritten as <>.*/
218 newparsed = parse_extract_address(new, &error, &start, &end, &pdomain,
219 flag == rewrite_envfrom || flag == (rewrite_smtp|rewrite_smtp_sender));
223 log_write(0, LOG_MAIN|LOG_PANIC, "Rewrite of %s yielded unparseable "
224 "address: %s in address %s", subject, error, new);
225 break; /* Give up on this address */
228 /* A non-null unqualified address can be qualified if requested. Otherwise,
229 this is an error unless it's the empty address in circumstances where that is
232 if (pdomain == 0 && (*newparsed != 0 ||
233 (flag != rewrite_envfrom && flag != (rewrite_smtp|rewrite_smtp_sender))))
235 if (rule->flags & rewrite_qualify)
237 newparsed = rewrite_address_qualify(newparsed, TRUE);
238 new = string_sprintf("%.*s%s%.*s", start, new, newparsed,
239 Ustrlen(new) - end, new + end);
240 end = start + Ustrlen(newparsed);
244 log_write(0, LOG_MAIN|LOG_PANIC, "Rewrite of %s yielded unqualified "
245 "address \"%s\"", subject, new);
246 break; /* Give up on this address */
250 /* We have a validly rewritten address */
252 if (LOGGING(address_rewrite) || (debug_selector & D_rewrite) != 0)
254 const uschar *where = CUS"?";
256 for (int i = 0; i < where_list_size; i++)
257 if (flag == where_list[i].bit)
259 where = where_list[i].string;
262 log_write(L_address_rewrite,
263 LOG_MAIN, "\"%s\" from %s rewritten as \"%s\" by rule %d",
264 yield, where, new, rule_number);
267 /* A header will only actually be added if header_last is non-NULL,
268 i.e. during message reception or delivery, but add_header should not
269 be set TRUE during delivery, as otherwise multiple instances of the header
270 can fill up the -H file and make it embarrassingly large. We don't need
271 to set header_rewritten because the -H file always gets written at the end
272 of message reception. */
275 header_add(htype_old, "X-rewrote-%s: %s\n", name, subject);
277 /* Handle the case when replacement of the whole address is possible.
278 This happens only when whole is not NULL and we are rewriting a header.
279 If *whole is already TRUE it means that a previous rule had the w
280 flag set and so we must preserve the non-active portion of the current
281 subject unless the current rule also has the w flag set. */
283 if (whole && (flag & rewrite_all_headers))
285 /* Current rule has the w flag set. We must ensure the phrase parts
286 are syntactically valid if they are present. */
288 if (rule->flags & rewrite_whole)
290 if (start > 0 && new[start-1] == '<')
292 uschar *p1 = new + start - 1;
293 uschar *p2 = new + end + 1;
294 const uschar *pf1, *pf2;
296 while (p1 > new && p1[-1] == ' ') p1--;
297 pf1 = parse_fix_phrase(new, p1 - new);
298 while (*p2 == ' ') p2++;
299 pf2 = parse_fix_phrase(p2, Ustrlen(p2));
301 start = Ustrlen(pf1) + start + new - p1;
302 end = start + Ustrlen(newparsed);
303 new = string_sprintf("%s%.*s%s", pf1, (int)(p2 - p1), p1, pf2);
306 /* Now accept the whole thing */
315 /* Current rule does not have the w flag set; if not previously
316 done any whole rewriting, behave in non-whole manner. */
318 else if (!*whole) goto NEVER_WHOLE;
320 /* Current rule does not have the w flag set, but a previous
321 rule did rewrite the whole address. Thus yield and subject will be
322 different. Preserve the previous non-active part of the address. */
327 new = string_sprintf("%.*s%s%n%s",
328 yield_start, yield, subject, &end, yield + yield_end);
334 /* Rule just rewrites active part, or handling an envelope. This
335 code is obeyed only when all rules so far have not done "whole"
341 subject = yield = newparsed;
344 domain = NULL; /* Reset for next rule */
346 /* If no further rewrites are to be done, set the done flag. This allows
347 repeats of the current rule if configured before breaking the loop. */
349 if (rule->flags & rewrite_quit) done = TRUE;
351 /* Allow the current rule to be applied up to 10 times if
354 if (rule->flags & rewrite_repeat)
356 if (count++ < 10) goto REPEAT_RULE;
357 log_write(0, LOG_MAIN|LOG_PANIC, "rewrite rule repeat ignored after 10 "
362 /* Unset expansion numeric variables, and that's it. */
370 /*************************************************
371 * Ensure qualification and rewrite *
372 *************************************************/
374 /* This function is called for envelope addresses, the boolean specifying
375 whether a recipient or a sender. It must first of all ensure the address is
376 fully qualified, and then apply any relevant re-writing rules. The add-header
377 flag causes a header to be added, recording the old address. This is marked
378 "old", so that it is never transported anywhere; it exists for local checking
379 and debugging purposes.
382 s the address to be considered
383 is_recipient TRUE for recipient addresses; FALSE otherwise
384 add_header add "X-rewrote-xxx" header when rewriting; this is
385 set TRUE only for calls from the reception functions
386 rewrite_rules points to chain of rewrite rules
387 existflags bits indicating which headers there are rewrites for
388 (just an optimisation)
390 Returns: possibly rewritten address
394 rewrite_address(const uschar *s, BOOL is_recipient, BOOL add_header,
395 rewrite_rule *rewrite_rules, int existflags)
397 int flag = is_recipient ? rewrite_envto : rewrite_envfrom;
399 s = rewrite_address_qualify(s, is_recipient);
400 if (existflags & flag)
402 const uschar *new = rewrite_one(s, flag, NULL, add_header, is_recipient?
403 US"original-recipient" : US"sender", rewrite_rules);
404 if (new != s) s = new;
411 /*************************************************
412 * Qualify and possibly rewrite one header *
413 *************************************************/
415 /* This is called only from rewrite_header() below, either when reading a
416 message. or when routing, in order to rewrite addresses that get changed by a
417 router. This is normally the addition of full qualification to a partial
418 domain. The first rewriting rule in this case is "change routed_old into
419 routed_new", and it applies to all header lines that contain addresses. Then
420 header-specific rewriting rules are applied.
422 Before rewriting can be done, addresses without domains have to be qualified.
423 This should only be done for messages from "local" senders. This is a difficult
424 concept to pin down, what with the use of SMTP both as a submission and as a
425 transmission protocol. Exim normally requires incoming SMTP to contain fully-
426 qualified addresses, but there are options to permit unqualified ones from
427 certain hosts. For those hosts only, addresses in headers can also be
428 qualified. For other hosts, unqualified addresses in headers do not get touched
429 in any way. For locally sourced messages, unqualified addresses always get
430 qualified, except when -bnq is used to explicitly suppress this.
433 h pointer to header line block
434 flag indicates which header this is
435 routed_old if not NULL, this is a rewrite caused by a router, changing
436 this domain into routed_new
437 routed_new new routed domain if routed_old is not NULL
438 rewrite_rules points to chain of rewriting rules
439 existflags bits indicating which rewrites exist
440 replace if TRUE, insert the new header in the chain after the old
441 one, and mark the old one "replaced"
443 Returns: NULL if header unchanged; otherwise the rewritten header
447 rewrite_one_header(header_line *h, int flag,
448 const uschar *routed_old, const uschar *routed_new,
449 rewrite_rule *rewrite_rules, int existflags, BOOL replace)
452 header_line *newh = NULL;
453 rmark function_reset_point = store_mark();
454 uschar *s = Ustrchr(h->text, ':') + 1;
456 while (isspace(*s)) s++;
459 debug_printf_indent("rewrite_one_header: type=%c:\n %s", h->type, h->text);
461 f.parse_allow_group = TRUE; /* Allow group syntax */
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. */
473 uschar *ss = parse_find_address_end(s, FALSE);
474 uschar *recipient, *new;
475 rmark loop_reset_point = store_mark();
476 uschar *errmess = NULL;
477 BOOL changed = FALSE;
478 int terminator = *ss;
479 int start, end, domain;
481 /* Temporarily terminate the string at this point, and extract the
482 operative address within. Then put back the terminator and prepare for
483 the next address, saving the start of the old one. */
486 recipient = parse_extract_address(s, &errmess, &start, &end, &domain, FALSE);
489 s = ss + (terminator ? 1 : 0);
490 while (isspace(*s)) s++;
492 /* There isn't much we can do for syntactic disasters at this stage.
493 Pro tem (possibly for ever) ignore them.
494 If we got nothing, then there was any sort of error: non-parsable address,
495 empty address, overlong addres. Sometimes the result matters, sometimes not.
496 It seems this function is called for *any* header we see. */
500 /* Log unparesable addresses in the header. Slightly ugly because a
501 null output from the extract can also result from a header without an
502 address, "To: undisclosed recpients:;" being the classic case. Ignore
503 this one and carry on. */
505 if ((rewrite_rules || routed_old) && Ustrcmp(errmess, "empty address") != 0)
506 log_write(0, LOG_MAIN, "rewrite: %s", errmess);
508 loop_reset_point = store_reset(loop_reset_point);
512 /* If routed_old is not NULL, this is a rewrite caused by a router,
513 consisting of changing routed_old into routed_new, and applying to all
514 headers. If the header address has no domain, it is excluded, since a router
515 rewrite affects domains only. The new value should always be fully qualified,
516 but it may be something that has an explicit re-write rule set, so we need to
517 check the configured rules subsequently as well. (Example: there's an
518 explicit rewrite turning *.foo.com into foo.com, and an address is supplied
519 as abc@xyz, which the DNS lookup turns into abc@xyz.foo.com). However, if no
520 change is made here, don't bother carrying on. */
524 if (domain <= 0 || strcmpic(recipient+domain, routed_old) != 0) continue;
525 recipient[domain-1] = 0;
526 new = string_sprintf("%s@%s", recipient, routed_new);
529 recipient[domain-1] = '@';
530 debug_printf("%s rewritten by router as %s\n", recipient, new);
536 /* This is not a router-inspired rewrite. Ensure the address is fully
537 qualified if that is permitted. If an unqualified address was received
538 from a host that isn't listed, do not continue rewriting this address.
539 Sender, From or Reply-To headers are treated as senders, the rest as
540 recipients. This matters only when there are different qualify strings. */
545 (flag & (rewrite_sender | rewrite_from | rewrite_replyto)) == 0;
546 /* deconst ok as recipient was notconst */
547 new = US rewrite_address_qualify(recipient, is_recipient);
548 changed = (new != recipient);
551 /* Can only qualify if permitted; if not, no rewrite. */
553 if (changed && ((is_recipient && !f.allow_unqualified_recipient) ||
554 (!is_recipient && !f.allow_unqualified_sender)))
556 loop_reset_point = store_reset(loop_reset_point);
561 /* If there are rewrite rules for this type of header, apply
562 them. This test is just for efficiency, to save scanning the rules
563 in cases when nothing is going to change. If any rewrite rule had the
564 "whole" flag set, adjust the pointers so that the whole address gets
565 replaced, except possibly a final \n. */
567 if (existflags & flag)
570 /* deconst ok as recipient was notconst */
571 new = US rewrite_one(recipient, flag, &whole, FALSE, NULL, rewrite_rules);
572 if (new != recipient)
579 if (sprev[end-1] == '\n') end--;
584 /* If nothing has changed, lose all dynamic store obtained in this loop, and
585 move on to the next address. We can't reset to the function start store
586 point, because we may have a rewritten line from a previous time round the
589 if (!changed) loop_reset_point = store_reset(loop_reset_point);
591 /* If the address has changed, create a new header containing the
592 rewritten address. We do not need to set the chain pointers at this
593 stage. We want to avoid using more and more memory if the header is very long
594 and contains lots and lots of rewritten addresses. Therefore, we build the
595 new text string in malloc store, then at the end we reset dynamic store
596 before copying the new header to a new block (and then freeing the malloc
597 block). The header must end up in dynamic store so that it's freed at the end
598 of receiving a message. */
603 int newlen = Ustrlen(new);
604 int oldlen = end - start;
606 header_line * prev = newh ? newh : h;
607 uschar * newt = store_get_perm(prev->slen - oldlen + newlen + 4, GET_TAINTED);
608 uschar * newtstart = newt;
610 int type = prev->type;
611 int slen = prev->slen - oldlen + newlen;
613 /* Build the new header text by copying the old and putting in the
614 replacement. This process may make the header substantially longer
615 than it was before - qualification of a list of bare addresses can
616 often do this - so we stick in a newline after the re-written address
617 if it has increased in length and ends more than 40 characters in. In
618 fact, the code is not perfect, since it does not scan for existing
619 newlines in the header, but it doesn't seem worth going to that
620 amount of trouble. */
622 Ustrncpy(newt, prev->text, sprev - prev->text + start);
623 newt += sprev - prev->text + start;
627 remlen = s - (sprev + end);
630 Ustrncpy(newt, sprev + end, remlen);
635 /* Must check that there isn't a newline here anyway; in particular, there
636 will be one at the very end of the header, where we DON'T want to insert
637 another one! The pointer s has been skipped over white space, so just
638 look back to see if the last non-space-or-tab was a newline. */
640 if (newlen > oldlen && newt - newtstart - lastnewline > 40)
643 while (p >= prev->text && (*p == ' ' || *p == '\t')) p--;
646 lastnewline = newt - newtstart;
647 Ustrcat(newt, US"\n\t");
652 /* Finally, the remaining unprocessed addresses, if any. */
656 DEBUG(D_rewrite) debug_printf("newlen=%d newtype=%c newtext:\n%s",
657 slen, type, newtstart);
659 /* Compute the length of the rest of the header line before we possibly
660 flatten a previously rewritten copy. */
662 remlen = (s - prev->text) - oldlen + newlen;
664 /* We have the new text in a malloc block. That enables us to release all
665 the memory that has been used, back to the point at which the function was
666 entered. Then set up a new header in dynamic store. This will override a
667 rewritten copy from a previous time round this loop. */
669 store_reset(function_reset_point);
670 function_reset_point = store_mark();
671 newh = store_get(sizeof(header_line), GET_UNTAINTED);
674 newh->text = string_copyn(newtstart, slen);
676 /* Set up for scanning the rest of the header */
678 s = newh->text + remlen;
679 DEBUG(D_rewrite) debug_printf("remainder: %s", *s ? s : US"\n");
683 f.parse_allow_group = FALSE; /* Reset group flags */
684 f.parse_found_group = FALSE;
686 /* If a rewrite happened and "replace" is true, put the new header into the
687 chain following the old one, and mark the old one as replaced. */
691 newh->next = h->next;
692 if (!newh->next) header_last = newh;
703 /*************************************************
704 * Rewrite a header line *
705 *************************************************/
707 /* This function may be passed any old header line. It must detect those which
708 contain addresses, then then apply any rewriting rules that apply. If
709 routed_old is NULL, only the configured rewriting rules are consulted.
710 Otherwise, the rewriting rule is "change routed_old into routed_new", and it
711 applies to all header lines that contain addresses. Then header-specific
712 rewriting rules are applied.
714 The old header line is flagged as "old". Old headers are saved on the spool for
715 debugging but are never sent to any recipients.
718 h header line to rewrite
719 routed_old if not NULL, this is a rewrite caused by a router, changing
720 this domain into routed_new
721 routed_new new routed domain if routed_old is not NULL
722 rewrite_rules points to chain of rewrite rules
723 existflags bits indicating which rewrites exist
724 replace if TRUE, the new header is inserted into the header chain
725 after the old one, and the old one is marked replaced
727 Returns: NULL if header unchanged; otherwise the rewritten header
731 rewrite_header(header_line *h,
732 const uschar *routed_old, const uschar *routed_new,
733 rewrite_rule *rewrite_rules, int existflags, BOOL replace)
738 case htype_sender: flag = rewrite_sender; break;
739 case htype_from: flag = rewrite_from; break;
740 case htype_to: flag = rewrite_to; break;
741 case htype_cc: flag = rewrite_cc; break;
742 case htype_bcc: flag = rewrite_bcc; break;
743 case htype_reply_to: flag = rewrite_replyto; break;
744 default: return NULL;
746 return rewrite_one_header(h, flag, routed_old, routed_new,
747 rewrite_rules, existflags, replace);
752 /************************************************
753 * Test rewriting rules *
754 ************************************************/
756 /* Called from the mainline as a result of the -brw option. Test the
757 address for all possible cases.
759 Argument: the address to test
764 rewrite_test(const uschar *s)
766 uschar *recipient, *error;
767 int start, end, domain;
768 BOOL done_smtp = FALSE;
770 if (rewrite_existflags == 0)
772 printf("No rewrite rules are defined\n");
776 /* Do SMTP rewrite only if a rule with the S flag exists. Allow <> by
777 pretending it is a sender. */
779 if ((rewrite_existflags & rewrite_smtp) != 0)
781 const uschar * new = rewrite_one(s, rewrite_smtp|rewrite_smtp_sender, NULL,
782 FALSE, US"", global_rewrite_rules);
786 printf(" SMTP: <>\n");
788 printf(" SMTP: %s\n", new);
793 /* Do the other rewrites only if a rule without the S flag exists */
795 if ((rewrite_existflags & ~rewrite_smtp) == 0) return;
797 /* Qualify if necessary before extracting the address */
799 if (parse_find_at(s) == NULL)
800 s = string_sprintf("%s@%s", s, qualify_domain_recipient);
802 recipient = parse_extract_address(s, &error, &start, &end, &domain, FALSE);
807 printf("Syntax error in %s\n%c%s\n", s, toupper(error[0]), error+1);
811 for (int i = 0; i < 8; i++)
815 const uschar * new = rewrite_one(recipient, flag, &whole, FALSE, US"",
816 global_rewrite_rules);
817 printf("%s: ", rrname[i]);
820 else if (whole || (flag & rewrite_all_headers) == 0)
821 printf("%s\n", CS new);
822 else printf("%.*s%s%s\n", start, s, new, s+end);
826 /* End of rewrite.c */