1 /* $Cambridge: exim/src/src/parse.c,v 1.7 2006/02/07 11:19:00 ph10 Exp $ */
3 /*************************************************
4 * Exim - an Internet mail transport agent *
5 *************************************************/
7 /* Copyright (c) University of Cambridge 1995 - 2006 */
8 /* See the file NOTICE for conditions of use and distribution. */
10 /* Functions for parsing addresses */
16 static uschar *last_comment_position;
20 /* In stand-alone mode, provide a replacement for deliver_make_addr()
21 and rewrite_address[_qualify]() so as to avoid having to drag in too much
22 redundant apparatus. */
26 address_item *deliver_make_addr(uschar *address, BOOL copy)
28 address_item *addr = store_get(sizeof(address_item));
31 addr->address = address;
35 uschar *rewrite_address(uschar *recipient, BOOL dummy1, BOOL dummy2, rewrite_rule
41 uschar *rewrite_address_qualify(uschar *recipient, BOOL dummy1)
51 /*************************************************
52 * Find the end of an address *
53 *************************************************/
55 /* Scan over a string looking for the termination of an address at a comma,
56 or end of the string. It's the source-routed addresses which cause much pain
57 here. Although Exim ignores source routes, it must recognize such addresses, so
58 we cannot get rid of this logic.
61 s pointer to the start of an address
62 nl_ends if TRUE, '\n' terminates an address
64 Returns: pointer past the end of the address
65 (i.e. points to null or comma)
69 parse_find_address_end(uschar *s, BOOL nl_ends)
71 BOOL source_routing = *s == '@';
72 int no_term = source_routing? 1 : 0;
74 while (*s != 0 && (*s != ',' || no_term > 0) && (*s != '\n' || !nl_ends))
76 /* Skip single quoted characters. Strictly these should not occur outside
77 quoted strings in RFC 822 addresses, but they can in RFC 821 addresses. Pity
78 about the lack of consistency, isn't it? */
80 if (*s == '\\' && s[1] != 0) s += 2;
82 /* Skip quoted items that are not inside brackets. Note that
83 quoted pairs are allowed inside quoted strings. */
87 while (*(++s) != 0 && (*s != '\n' || !nl_ends))
89 if (*s == '\\' && s[1] != 0) s++;
90 else if (*s == '\"') { s++; break; }
94 /* Skip comments, which may include nested brackets, but quotes
95 are not recognized inside comments, though quoted pairs are. */
100 while (*(++s) != 0 && (*s != '\n' || !nl_ends))
102 if (*s == '\\' && s[1] != 0) s++;
103 else if (*s == '(') level++;
104 else if (*s == ')' && --level <= 0) { s++; break; }
108 /* Non-special character; just advance. Passing the colon in a source
109 routed address means that any subsequent comma or colon may terminate unless
110 inside angle brackets. */
116 source_routing = s[1] == '@';
117 no_term = source_routing? 2 : 1;
119 else if (*s == '>') no_term--;
120 else if (source_routing && *s == ':') no_term--;
130 /*************************************************
131 * Find last @ in an address *
132 *************************************************/
134 /* This function is used when we have something that may not qualified. If we
135 know it's qualified, searching for the rightmost '@' is sufficient. Here we
136 have to be a bit more clever than just a plain search, in order to handle
137 unqualified local parts like "thing@thong" correctly. Since quotes may not
138 legally be part of a domain name, we can give up on hitting the first quote
139 when searching from the right. Now that the parsing also permits the RFC 821
140 form of address, where quoted-pairs are allowed in unquoted local parts, we
141 must take care to handle that too.
143 Argument: pointer to an address, possibly unqualified
144 Returns: pointer to the last @ in an address, or NULL if none
148 parse_find_at(uschar *s)
150 uschar *t = s + Ustrlen(s);
155 int backslash_count = 0;
157 while (tt > s && *tt-- == '\\') backslash_count++;
158 if ((backslash_count & 1) == 0) return t;
160 else if (*t == '\"') return NULL;
168 /***************************************************************************
169 * In all the functions below that read a particular object type from *
170 * the input, return the new value of the pointer s (the first argument), *
171 * and put the object into the store pointed to by t (the second argument), *
172 * adding a terminating zero. If no object is found, t will point to zero *
174 ***************************************************************************/
177 /*************************************************
178 * Skip white space and comment *
179 *************************************************/
183 (2) If uschar not '(', return.
184 (3) Skip till matching ')', not counting any characters
186 (4) Move past ')' and goto (1).
188 The start of the last potential comment position is remembered to
189 make it possible to ignore comments at the end of compound items.
191 Argument: current character pointer
192 Regurns: new character pointer
196 skip_comment(uschar *s)
198 last_comment_position = s;
202 while (isspace(*s)) s++;
203 if (*s != '(') break;
205 while((c = *(++s)) != 0)
207 if (c == '(') level++;
208 else if (c == ')') { if (--level <= 0) { s++; break; } }
209 else if (c == '\\' && s[1] != 0) s++;
217 /*************************************************
219 *************************************************/
221 /* A domain is a sequence of subdomains, separated by dots. See comments below
222 for detailed syntax of the subdomains.
224 If allow_domain_literals is TRUE, a "domain" may also be an IP address enclosed
225 in []. Make sure the output is set to the null string if there is a syntax
226 error as well as if there is no domain at all.
229 s current character pointer
230 t where to put the domain
231 errorptr put error message here on failure (*t will be 0 on exit)
233 Returns: new character pointer
237 read_domain(uschar *s, uschar *t, uschar **errorptr)
242 /* Handle domain literals if permitted. An RFC 822 domain literal may contain
243 any character except [ ] \, including linear white space, and may contain
244 quoted characters. However, RFC 821 restricts literals to being dot-separated
245 3-digit numbers, and we make the obvious extension for IPv6. Go for a sequence
246 of digits, dots, hex digits, and colons here; later this will be checked for
247 being a syntactically valid IP address if it ever gets to a router.
249 Allow both the formal IPv6 form, with IPV6: at the start, and the informal form
250 without it, and accept IPV4: as well, 'cause someone will use it sooner or
257 if (strncmpic(s, US"IPv6:", 5) == 0 || strncmpic(s, US"IPv4:", 5) == 0)
263 while (*s == '.' || *s == ':' || isxdigit(*s)) *t++ = *s++;
265 if (*s == ']') *t++ = *s++; else
267 *errorptr = US"malformed domain literal";
271 if (!allow_domain_literals)
273 *errorptr = US"domain literals not allowed";
277 return skip_comment(s);
280 /* Handle a proper domain, which is a sequence of dot-separated atoms. Remove
281 trailing dots if strip_trailing_dot is set. A subdomain is an atom.
283 An atom is a sequence of any characters except specials, space, and controls.
284 The specials are ( ) < > @ , ; : \ " . [ and ]. This is the rule for RFC 822
285 and its successor (RFC 2822). However, RFC 821 and its successor (RFC 2821) is
286 tighter, allowing only letters, digits, and hyphens, not starting with a
289 There used to be a global flag that got set when checking addresses that came
290 in over SMTP and which should therefore should be checked according to the
291 stricter rule. However, it seems silly to make the distinction, because I don't
292 suppose anybody ever uses local domains that are 822-compliant and not
293 821-compliant. Furthermore, Exim now has additional data on the spool file line
294 after an address (after "one_time" processing), and it makes use of a #
295 character to delimit it. When I wrote that code, I forgot about this 822-domain
296 stuff, and assumed # could never appear in a domain.
298 So the old code is now cut out for Release 4.11 onwards, on 09-Aug-02. In a few
299 years, when we are sure this isn't actually causing trouble, throw it away.
301 March 2003: the story continues: There is a camp that is arguing for the use of
302 UTF-8 in domain names as the way to internationalization, and other MTAs
303 support this. Therefore, we now have a flag that permits the use of characters
304 with values greater than 127, encoded in UTF-8, in subdomains, so that Exim can
305 be used experimentally in this way. */
311 /*********************
314 if (*s != '-') while (isalnum(*s) || *s == '-') *t++ = *s++;
317 while (!mac_iscntrl_or_special(*s)) *t++ = *s++;
318 *********************/
322 /* Only letters, digits, and hyphens */
324 if (!allow_utf8_domains)
326 while (isalnum(*s) || *s == '-') *t++ = *s++;
329 /* Permit legal UTF-8 characters to be included */
334 if (isalnum(*s) || *s == '-') /* legal ascii characters */
339 if ((*s & 0xc0) != 0xc0) break; /* not start of UTF-8 character */
341 for (i = 1; i < 6; i++) /* i is the number of additional bytes */
343 if ((d & 0x80) == 0) break;
346 if (i == 6) goto BAD_UTF8; /* invalid UTF-8 */
347 *t++ = *s++; /* leading UTF-8 byte */
348 while (i-- > 0) /* copy and check remainder */
350 if ((*s & 0xc0) != 0x80)
353 *errorptr = US"invalid UTF-8 byte sequence";
359 } /* End of loop for UTF-8 character */
360 } /* End of subdomain */
365 if (t == tsave) /* empty component */
367 if (strip_trailing_dot && t > tt && *s != '.') t[-1] = 0; else
369 *errorptr = US"domain missing or malformed";
375 if (*s != '.') break;
385 /*************************************************
386 * Read a local-part *
387 *************************************************/
389 /* A local-part is a sequence of words, separated by periods. A null word
390 between dots is not strictly allowed but apparently many mailers permit it,
391 so, sigh, better be compatible. Even accept a trailing dot...
393 A <word> is either a quoted string, or an <atom>, which is a sequence
394 of any characters except specials, space, and controls. The specials are
395 ( ) < > @ , ; : \ " . [ and ]. In RFC 822, a single quoted character, (a
396 quoted-pair) is not allowed in a word. However, in RFC 821, it is permitted in
397 the local part of an address. Rather than have separate parsing functions for
398 the different cases, take the liberal attitude always. At least one MUA is
399 happy to recognize this case; I don't know how many other programs do.
402 s current character pointer
403 t where to put the local part
404 error where to point error text
405 allow_null TRUE if an empty local part is not an error
407 Returns: new character pointer
411 read_local_part(uschar *s, uschar *t, uschar **error, BOOL allow_null)
421 /* Handle a quoted string */
426 while ((c = *(++s)) != 0 && c != '\"')
429 if (c == '\\' && s[1] != 0) *t++ = *(++s);
438 *error = US"unmatched doublequote in local part";
443 /* Handle an atom, but allow quoted pairs within it. */
445 else while (!mac_iscntrl_or_special(*s) || *s == '\\')
448 if (c == '\\' && *s != 0) *t++ = *s++;
451 /* Terminate the word and skip subsequent comment */
456 /* If we have read a null component at this point, give an error unless it is
457 terminated by a dot - an extension to RFC 822 - or if it is the first
458 component of the local part and an empty local part is permitted, in which
459 case just return normally. */
461 if (t == tsave && *s != '.')
463 if (t == tt && !allow_null)
464 *error = US"missing or malformed local part";
468 /* Anything other than a dot terminates the local part. Treat multiple dots
469 as a single dot, as this seems to be a common extension. */
471 if (*s != '.') break;
472 do { *t++ = *s++; } while (*s == '.');
479 /*************************************************
480 * Read route part of route-addr *
481 *************************************************/
483 /* The pointer is at the initial "@" on entry. Return it following the
484 terminating colon. Exim no longer supports the use of source routes, but it is
485 required to accept the syntax.
488 s current character pointer
489 t where to put the route
490 errorptr where to put an error message
492 Returns: new character pointer
496 read_route(uschar *s, uschar *t, uschar **errorptr)
504 s = read_domain(s+1, t, errorptr);
505 if (*t == 0) return s;
506 t += Ustrlen((const uschar *)t);
507 if (*s != ',') break;
513 if (*s == ':') *t++ = *s++;
515 /* If there is no colon, and there were no commas, the most likely error
516 is in fact a missing local part in the address rather than a missing colon
519 else *errorptr = commas?
520 US"colon expected after route list" :
523 /* Terminate the route and return */
526 return skip_comment(s);
531 /*************************************************
533 *************************************************/
535 /* Addr-spec is local-part@domain. We make the domain optional -
536 the expected terminator for the whole thing is passed to check this.
537 This function is called only when we know we have a route-addr.
540 s current character pointer
541 t where to put the addr-spec
542 term expected terminator (0 or >)
543 errorptr where to put an error message
544 domainptr set to point to the start of the domain
546 Returns: new character pointer
550 read_addr_spec(uschar *s, uschar *t, int term, uschar **errorptr,
553 s = read_local_part(s, t, errorptr, FALSE);
554 if (*errorptr == NULL)
559 *errorptr = string_sprintf("\"@\" or \".\" expected after \"%s\"", t);
562 t += Ustrlen((const uschar *)t);
565 s = read_domain(s, t, errorptr);
574 /*************************************************
575 * Extract operative address *
576 *************************************************/
578 /* This function extracts an operative address from a full RFC822 mailbox and
579 returns it in a piece of dynamic store. We take the easy way and get a piece
580 of store the same size as the input, and then copy into it whatever is
581 necessary. If we cannot find a valid address (syntax error), return NULL, and
582 point the error pointer to the reason. The arguments "start" and "end" are used
583 to return the offsets of the first and one past the last characters in the
584 original mailbox of the address that has been extracted, to aid in re-writing.
585 The argument "domain" is set to point to the first character after "@" in the
586 final part of the returned address, or zero if there is no @.
588 Exim no longer supports the use of source routed addresses (those of the form
589 @domain,...:route_addr). It recognizes the syntax, but collapses such addresses
590 down to their final components. Formerly, collapse_source_routes had to be set
591 to achieve this effect. RFC 1123 allows collapsing with MAY, while the revision
592 of RFC 821 had increased this to SHOULD, so I've gone for it, because it makes
593 a lot of code elsewhere in Exim much simpler.
595 There are some special fudges here for handling RFC 822 group address notation
596 which may appear in certain headers. If the flag parse_allow_group is set
597 TRUE and parse_found_group is FALSE when this function is called, an address
598 which is the start of a group (i.e. preceded by a phrase and a colon) is
599 recognized; the phrase is ignored and the flag parse_found_group is set. If
600 this flag is TRUE at the end of an address, then if an extraneous semicolon is
601 found, it is ignored and the flag is cleared. This logic is used only when
602 scanning through addresses in headers, either to fulfil the -t option or for
603 rewriting or checking header syntax.
606 mailbox points to the RFC822 mailbox
607 errorptr where to point an error message
608 start set to start offset in mailbox
609 end set to end offset in mailbox
610 domain set to domain offset in result, or 0 if no domain present
611 allow_null allow <> if TRUE
613 Returns: points to the extracted address, or NULL on error
616 #define FAILED(s) { *errorptr = s; goto PARSE_FAILED; }
619 parse_extract_address(uschar *mailbox, uschar **errorptr, int *start, int *end,
620 int *domain, BOOL allow_null)
622 uschar *yield = store_get(Ustrlen(mailbox) + 1);
623 uschar *startptr, *endptr;
624 uschar *s = (uschar *)mailbox;
625 uschar *t = (uschar *)yield;
629 /* At the start of the string we expect either an addr-spec or a phrase
630 preceding a <route-addr>. If groups are allowed, we might also find a phrase
631 preceding a colon and an address. If we find an initial word followed by
632 a dot, strict interpretation of the RFC would cause it to be taken
633 as the start of an addr-spec. However, many mailers break the rules
634 and use addresses of the form "a.n.other <ano@somewhere>" and so we
637 RESTART: /* Come back here after passing a group name */
640 startptr = s; /* In case addr-spec */
641 s = read_local_part(s, t, errorptr, TRUE); /* Dot separated words */
642 if (*errorptr != NULL) goto PARSE_FAILED;
644 /* If the terminator is neither < nor @ then the format of the address
645 must either be a bare local-part (we are now at the end), or a phrase
646 followed by a route-addr (more words must follow). */
648 if (*s != '@' && *s != '<')
650 if (*s == 0 || *s == ';')
652 if (*t == 0) FAILED(US"empty address");
653 endptr = last_comment_position;
654 goto PARSE_SUCCEEDED; /* Bare local part */
657 /* Expect phrase route-addr, or phrase : if groups permitted, but allow
658 dots in the phrase; complete the loop only when '<' or ':' is encountered -
659 end of string will produce a null local_part and therefore fail. We don't
660 need to keep updating t, as the phrase isn't to be kept. */
662 while (*s != '<' && (!parse_allow_group || *s != ':'))
664 s = read_local_part(s, t, errorptr, FALSE);
665 if (*errorptr != NULL)
667 *errorptr = string_sprintf("%s (expected word or \"<\")", *errorptr);
674 parse_found_group = TRUE;
675 parse_allow_group = FALSE;
680 /* Assert *s == '<' */
683 /* At this point the next character is either '@' or '<'. If it is '@', only a
684 single local-part has previously been read. An angle bracket signifies the
685 start of an <addr-spec>. Throw away anything we have saved so far before
686 processing it. Note that this is "if" rather than "else if" because it's also
687 used after reading a preceding phrase.
689 There are a lot of broken sendmails out there that put additional pairs of <>
690 round <route-addr>s. If strip_excess_angle_brackets is set, allow any number of
691 them, as long as they match. */
695 uschar *domainptr = yield;
696 BOOL source_routed = FALSE;
697 int bracket_count = 1;
700 if (strip_excess_angle_brackets)
701 while (*s == '<') { bracket_count++; s++; }
707 /* Read an optional series of routes, each of which is a domain. They
708 are separated by commas and terminated by a colon. However, we totally ignore
709 such routes (RFC 1123 says we MAY, and the revision of RFC 821 says we
714 s = read_route(s, t, errorptr);
715 if (*errorptr != NULL) goto PARSE_FAILED;
716 *t = 0; /* Ensure route is ignored - probably overkill */
717 source_routed = TRUE;
720 /* Now an addr-spec, terminated by '>'. If there is no preceding route,
721 we must allow an empty addr-spec if allow_null is TRUE, to permit the
722 address "<>" in some circumstances. A source-routed address MUST have
723 a domain in the final part. */
725 if (allow_null && !source_routed && *s == '>')
732 s = read_addr_spec(s, t, '>', errorptr, &domainptr);
733 if (*errorptr != NULL) goto PARSE_FAILED;
734 *domain = domainptr - yield;
735 if (source_routed && *domain == 0)
736 FAILED(US"domain missing in source-routed address");
740 if (*errorptr != NULL) goto PARSE_FAILED;
741 while (bracket_count-- > 0) if (*s++ != '>')
743 *errorptr = (s[-1] == 0)? US"'>' missing at end of address" :
744 string_sprintf("malformed address: %.32s may not follow %.*s",
745 s-1, s - (uschar *)mailbox - 1, mailbox);
752 /* Hitting '@' after the first local-part means we have definitely got an
753 addr-spec, on a strict reading of the RFC, and the rest of the string
754 should be the domain. However, for flexibility we allow for a route-address
755 not enclosed in <> as well, which is indicated by an empty first local
756 part preceding '@'. The source routing is, however, ignored. */
760 uschar *domainptr = yield;
761 s = read_route(s, t, errorptr);
762 if (*errorptr != NULL) goto PARSE_FAILED;
763 *t = 0; /* Ensure route is ignored - probably overkill */
764 s = read_addr_spec(s, t, 0, errorptr, &domainptr);
765 if (*errorptr != NULL) goto PARSE_FAILED;
766 *domain = domainptr - yield;
767 endptr = last_comment_position;
768 if (*domain == 0) FAILED(US"domain missing in source-routed address");
771 /* This is the strict case of local-part@domain. */
775 t += Ustrlen((const uschar *)t);
778 s = read_domain(s, t, errorptr);
779 if (*t == 0) goto PARSE_FAILED;
780 endptr = last_comment_position;
783 /* Use goto to get here from the bare local part case. Arrive by falling
784 through for other cases. Endptr may have been moved over whitespace, so
785 move it back past white space if necessary. */
790 if (parse_found_group && *s == ';')
792 parse_found_group = FALSE;
793 parse_allow_group = TRUE;
797 *errorptr = string_sprintf("malformed address: %.32s may not follow %.*s",
798 s, s - (uschar *)mailbox, mailbox);
802 *start = startptr - (uschar *)mailbox; /* Return offsets */
803 while (isspace(endptr[-1])) endptr--;
804 *end = endptr - (uschar *)mailbox;
806 /* Although this code has no limitation on the length of address extracted,
807 other parts of Exim may have limits, and in any case, RFC 2821 limits local
808 parts to 64 and domains to 255, so we do a check here, giving an error if the
809 address is ridiculously long. */
811 if (*end - *start > ADDRESS_MAXLENGTH)
813 *errorptr = string_sprintf("address is ridiculously long: %.64s...", yield);
817 return (uschar *)yield;
819 /* Use goto (via the macro FAILED) to get to here from a variety of places.
820 We might have an empty address in a group - the caller can choose to ignore
821 this. We must, however, keep the flags correct. */
824 if (parse_found_group && *s == ';')
826 parse_found_group = FALSE;
827 parse_allow_group = TRUE;
836 /*************************************************
837 * Quote according to RFC 2047 *
838 *************************************************/
840 /* This function is used for quoting text in headers according to RFC 2047.
841 If the only characters that strictly need quoting are spaces, we return the
842 original string, unmodified. If a quoted string is too long for the buffer, it
843 is truncated. (This shouldn't happen: this is normally handling short strings.)
845 Hmmph. As always, things get perverted for other uses. This function was
846 originally for the "phrase" part of addresses. Now it is being used for much
847 longer texts in ACLs and via the ${rfc2047: expansion item. This means we have
848 to check for overlong "encoded-word"s and split them. November 2004.
851 string the string to quote - already checked to contain non-printing
853 len the length of the string
854 charset the name of the character set; NULL => iso-8859-1
855 buffer the buffer to put the answer in
856 buffer_size the size of the buffer
858 Returns: pointer to the original string, if no quoting needed, or
859 pointer to buffer containing the quoted string, or
860 a pointer to "String too long" if the buffer can't even hold
865 parse_quote_2047(uschar *string, int len, uschar *charset, uschar *buffer,
873 if (charset == NULL) charset = US"iso-8859-1";
875 /* We don't expect this to fail! */
877 if (!string_format(buffer, buffer_size, "=?%s?Q?", charset))
878 return US"String too long";
880 hlen = Ustrlen(buffer);
884 for (; len > 0; len--)
887 if (t > buffer + buffer_size - hlen - 8) break;
895 Ustrncpy(p, buffer, hlen);
899 if (ch < 33 || ch > 126 ||
900 Ustrchr("?=()<>@,;:\\\".[]_", ch) != NULL)
902 if (ch == ' ') *t++ = '_'; else
904 sprintf(CS t, "=%02X", ch);
916 return coded? buffer : string;
922 /*************************************************
923 * Fix up an RFC 822 "phrase" *
924 *************************************************/
926 /* This function is called to repair any syntactic defects in the "phrase" part
927 of an RFC822 address. In particular, it is applied to the user's name as read
928 from the passwd file when accepting a local message, and to the data from the
931 If the string contains existing quoted strings or comments containing
932 freestanding quotes, then we just quote those bits that need quoting -
933 otherwise it would get awfully messy and probably not look good. If not, we
934 quote the whole thing if necessary. Thus
936 John Q. Smith => "John Q. Smith"
937 John "Jack" Smith => John "Jack" Smith
938 John "Jack" Q. Smith => John "Jack" "Q." Smith
939 John (Jack) Q. Smith => "John (Jack) Q. Smith"
940 John ("Jack") Q. Smith => John ("Jack") "Q." Smith
942 John (\"Jack\") Q. Smith => "John (\"Jack\") Q. Smith"
944 Sheesh! This is tedious code. It is a great pity that the syntax of RFC822 is
947 August 2000: Additional code added:
949 Previously, non-printing characters were turned into question marks, which do
950 not need to be quoted.
952 Now, a different tactic is used if there are any non-printing ASCII
953 characters. The encoding method from RFC 2047 is used, assuming iso-8859-1 as
956 We *could* use this for all cases, getting rid of the messy original code,
957 but leave it for now. It would complicate simple cases like "John Q. Smith".
959 The result is passed back in the buffer; it is usually going to be added to
960 some other string. In order to be sure there is going to be no overflow,
961 restrict the length of the input to 1/4 of the buffer size - this allows for
962 every single character to be quoted or encoded without overflowing, and that
963 wouldn't happen because of amalgamation. If the phrase is too long, return a
967 phrase an RFC822 phrase
968 len the length of the phrase
969 buffer a buffer to put the result in
970 buffer_size the size of the buffer
972 Returns: the fixed RFC822 phrase
976 parse_fix_phrase(uschar *phrase, int len, uschar *buffer, int buffer_size)
980 uschar *s, *t, *end, *yield;
982 while (len > 0 && isspace(*phrase)) { phrase++; len--; }
983 if (len > buffer_size/4) return US"Name too long";
985 /* See if there are any non-printing characters, and if so, use the RFC 2047
986 encoding for the whole thing. */
988 for (i = 0, s = phrase; i < len; i++, s++)
989 if ((*s < 32 && *s != '\t') || *s > 126) break;
991 if (i < len) return parse_quote_2047(phrase, len, headers_charset, buffer,
994 /* No non-printers; use the RFC 822 quoting rules */
998 yield = t = buffer + 1;
1004 /* Copy over quoted strings, remembering we encountered one */
1009 while (s < end && (ch = *s++) != '\"')
1012 if (ch == '\\' && s < end) *t++ = *s++;
1015 if (s >= end) break;
1019 /* Copy over comments, noting if they contain freestanding quote
1030 if (ch == '(') level++;
1031 else if (ch == ')') { if (--level <= 0) break; }
1032 else if (ch == '\\' && s < end) *t++ = *s++ & 127;
1033 else if (ch == '\"') quoted = TRUE;
1037 while (level--) *t++ = ')';
1042 /* Handle special characters that need to be quoted */
1044 else if (Ustrchr(")<>@,;:\\.[]", ch) != NULL)
1046 /* If hit previous quotes just make one quoted "word" */
1051 while (*(--tt) != ' ' && *tt != '\"' && *tt != ')') tt[1] = *tt;
1057 if (ch == ' ' || ch == '\"') { s--; break; } else *t++ = ch;
1062 /* Else quote the whole string so far, and the rest up to any following
1063 quotes. We must treat anything following a backslash as a literal. */
1067 BOOL escaped = (ch == '\\');
1071 /* Now look for the end or a quote */
1077 /* Handle escaped pairs */
1085 else if (ch == '\\')
1091 /* If hit subsequent quotes, insert our quote before any trailing
1092 spaces and back up to re-handle the quote in the outer loop. */
1094 else if (ch == '\"')
1097 while (t[-1] == ' ') { t--; count++; }
1099 while (count-- > 0) *t++ = ' ';
1104 /* If hit a subsequent comment, check it for unescaped quotes,
1105 and if so, end our quote before it. */
1109 uschar *ss = s; /* uschar after '(' */
1114 if (ch == '(') level++;
1115 else if (ch == ')') { if (--level <= 0) break; }
1116 else if (ch == '\\' && ss+1 < end) ss++;
1117 else if (ch == '\"') { quoted = TRUE; break; }
1120 /* Comment contains unescaped quotes; end our quote before
1121 the start of the comment. */
1126 while (t[-1] == ' ') { t--; count++; }
1128 while (count-- > 0) *t++ = ' ';
1132 /* Comment does not contain unescaped quotes; include it in
1137 if (ss >= end) ss--;
1139 Ustrncpy(t, s, ss-s);
1145 /* Not a comment or quote; include this character in our quotes. */
1151 /* Add a final quote if we hit the end of the string. */
1153 if (s >= end) *t++ = '\"';
1156 /* Non-special character; just copy it over */
1166 /*************************************************
1167 * Extract addresses from a list *
1168 *************************************************/
1170 /* This function is called by the redirect router to scan a string containing a
1171 list of addresses separated by commas (with optional white space) or by
1172 newlines, and to generate a chain of address items from them. In other words,
1173 to unpick data from an alias or .forward file.
1175 The SunOS5 documentation for alias files is not very clear on the syntax; it
1176 does not say that either a comma or a newline can be used for separation.
1177 However, that is the way Smail does it, so we follow suit.
1179 If a # character is encountered in a white space position, then characters from
1180 there to the next newline are skipped.
1182 If an unqualified address begins with '\', just skip that character. This gives
1183 compatibility with Sendmail's use of \ to prevent looping. Exim has its own
1184 loop prevention scheme which handles other cases too - see the code in
1187 An "address" can be a specification of a file or a pipe; the latter may often
1188 need to be quoted because it may contain spaces, but we don't want to retain
1189 the quotes. Quotes may appear in normal addresses too, and should be retained.
1190 We can distinguish between these cases, because in addresses, quotes are used
1191 only for parts of the address, not the whole thing. Therefore, we remove quotes
1192 from items when they entirely enclose them, but not otherwise.
1194 An "address" can also be of the form :include:pathname to include a list of
1195 addresses contained in the specified file.
1197 Any unqualified addresses are qualified with and rewritten if necessary, via
1198 the rewrite_address() function.
1201 s the list of addresses (typically a complete
1202 .forward file or a list of entries in an alias file)
1203 options option bits for permitting or denying various special cases;
1204 not all bits are relevant here - some are for filter
1205 files; those we use here are:
1212 anchor where to hang the chain of newly-created addresses. This
1213 should be initialized to NULL.
1214 error where to return an error text
1215 incoming domain domain of the incoming address; used to qualify unqualified
1216 local parts preceded by \
1217 directory if NULL, no checks are done on :include: files
1218 otherwise, included file names must start with the given
1220 syntax_errors if not NULL, it carries on after syntax errors in addresses,
1221 building up a list of errors as error blocks chained on
1224 Returns: FF_DELIVERED addresses extracted
1225 FF_NOTDELIVERED no addresses extracted, but no errors
1226 FF_BLACKHOLE :blackhole:
1229 FF_INCLUDEFAIL some problem with :include:; *error set
1230 FF_ERROR other problems; *error is set
1234 parse_forward_list(uschar *s, int options, address_item **anchor,
1235 uschar **error, uschar *incoming_domain, uschar *directory,
1236 error_block **syntax_errors)
1240 DEBUG(D_route) debug_printf("parse_forward_list: %s\n", s);
1250 BOOL inquote = FALSE;
1254 while (isspace(*s) || *s == ',') s++;
1255 if (*s == '#') { while (*s != 0 && *s != '\n') s++; } else break;
1258 /* When we reach the end of the list, we return FF_DELIVERED if any child
1259 addresses have been generated. If nothing has been generated, there are two
1260 possibilities: either the list is really empty, or there were syntax errors
1261 that are being skipped. (If syntax errors are not being skipped, an FF_ERROR
1262 return is generated on hitting a syntax error and we don't get here.) For a
1263 truly empty list we return FF_NOTDELIVERED so that the router can decline.
1264 However, if the list is empty only because syntax errors were skipped, we
1265 return FF_DELIVERED. */
1269 return (count > 0 || (syntax_errors != NULL && *syntax_errors != NULL))?
1270 FF_DELIVERED : FF_NOTDELIVERED;
1272 /* This previous code returns FF_ERROR if nothing is generated but a
1273 syntax error has been skipped. I now think it is the wrong approach, but
1274 have left this here just in case, and for the record. */
1277 if (count > 0) return FF_DELIVERED; /* Something was generated */
1279 if (syntax_errors == NULL || /* Not skipping syntax errors, or */
1280 *syntax_errors == NULL) /* we didn't actually skip any */
1281 return FF_NOTDELIVERED;
1283 *error = string_sprintf("no addresses generated: syntax error in %s: %s",
1284 (*syntax_errors)->text2, (*syntax_errors)->text1);
1290 /* Find the end of the next address. Quoted strings in addresses may contain
1291 escaped characters; I haven't found a proper specification of .forward or
1292 alias files that mentions the quoting properties, but it seems right to do
1293 the escaping thing in all cases, so use the function that finds the end of an
1294 address. However, don't let a quoted string extend over the end of a line. */
1296 ss = parse_find_address_end(s, TRUE);
1298 /* Remember where we finished, for starting the next one. */
1302 /* Remove any trailing spaces; we know there's at least one non-space. */
1304 while (isspace((ss[-1]))) ss--;
1306 /* We now have s->start and ss->end of the next address. Remove quotes
1307 if they completely enclose, remembering the address started with a quote
1308 for handling pipes and files. Another round of removal of leading and
1309 trailing spaces is then required. */
1311 if (*s == '\"' && ss[-1] == '\"')
1316 while (s < ss && isspace(*s)) s++;
1317 while (ss > s && isspace((ss[-1]))) ss--;
1320 /* Set up the length of the address. */
1328 debug_printf("extract item: %s\n", s);
1332 /* Handle special addresses if permitted. If the address is :unknown:
1333 ignore it - this is for backward compatibility with old alias files. You
1334 don't need to use it nowadays - just generate an empty string. For :defer:,
1335 :blackhole:, or :fail: we have to set up the error message and give up right
1338 if (Ustrncmp(s, ":unknown:", len) == 0)
1344 if (Ustrncmp(s, ":defer:", 7) == 0)
1345 { special = FF_DEFER; specopt = RDO_DEFER; } /* specbit is 0 */
1346 else if (Ustrncmp(s, ":blackhole:", 11) == 0)
1347 { special = FF_BLACKHOLE; specopt = specbit = RDO_BLACKHOLE; }
1348 else if (Ustrncmp(s, ":fail:", 6) == 0)
1349 { special = FF_FAIL; specopt = RDO_FAIL; } /* specbit is 0 */
1353 uschar *ss = Ustrchr(s+1, ':') + 1;
1354 if ((options & specopt) == specbit)
1356 *error = string_sprintf("\"%.*s\" is not permitted", len, s);
1359 while (*ss != 0 && isspace(*ss)) ss++;
1360 while (s[len] != 0 && s[len] != '\n') len++;
1362 *error = string_copy(ss);
1366 /* If the address is of the form :include:pathname, read the file, and call
1367 this function recursively to extract the addresses from it. If directory is
1368 NULL, do no checks. Otherwise, insist that the file name starts with the
1369 given directory and is a regular file. */
1371 if (Ustrncmp(s, ":include:", 9) == 0)
1374 uschar filename[256];
1378 struct stat statbuf;
1382 while (flen > 0 && isspace(*t)) { t++; flen--; }
1386 *error = string_sprintf("file name missing after :include:");
1392 *error = string_sprintf("included file name \"%s\" is too long", t);
1396 Ustrncpy(filename, t, flen);
1399 /* Insist on absolute path */
1401 if (filename[0]!= '/')
1403 *error = string_sprintf("included file \"%s\" is not an absolute path",
1408 /* Check if include is permitted */
1410 if ((options & RDO_INCLUDE) != 0)
1412 *error = US"included files not permitted";
1416 /* Check file name if required */
1418 if (directory != NULL)
1420 int len = Ustrlen(directory);
1421 uschar *p = filename + len;
1423 if (Ustrncmp(filename, directory, len) != 0 || *p != '/')
1425 *error = string_sprintf("included file %s is not in directory %s",
1426 filename, directory);
1430 /* It is necessary to check that every component inside the directory
1431 is NOT a symbolic link, in order to keep the file inside the directory.
1432 This is mighty tedious. It is also not totally foolproof in that it
1433 leaves the possibility of a race attack, but I don't know how to do
1439 while (*(++p) != 0 && *p != '/');
1442 if (Ulstat(filename, &statbuf) != 0)
1444 *error = string_sprintf("failed to stat %s (component of included "
1452 if ((statbuf.st_mode & S_IFMT) == S_IFLNK)
1454 *error = string_sprintf("included file %s in the %s directory "
1455 "involves a symbolic link", filename, directory);
1461 /* Open and stat the file */
1463 if ((f = Ufopen(filename, "rb")) == NULL)
1465 *error = string_open_failed(errno, "included file %s", filename);
1466 return FF_INCLUDEFAIL;
1469 if (fstat(fileno(f), &statbuf) != 0)
1471 *error = string_sprintf("failed to stat included file %s: %s",
1472 filename, strerror(errno));
1474 return FF_INCLUDEFAIL;
1477 /* If directory was checked, double check that we opened a regular file */
1479 if (directory != NULL && (statbuf.st_mode & S_IFMT) != S_IFREG)
1481 *error = string_sprintf("included file %s is not a regular file in "
1482 "the %s directory", filename, directory);
1486 /* Get a buffer and read the contents */
1488 if (statbuf.st_size > MAX_INCLUDE_SIZE)
1490 *error = string_sprintf("included file %s is too big (max %d)",
1491 filename, MAX_INCLUDE_SIZE);
1495 filebuf = store_get(statbuf.st_size + 1);
1496 if (fread(filebuf, 1, statbuf.st_size, f) != statbuf.st_size)
1498 *error = string_sprintf("error while reading included file %s: %s",
1499 filename, strerror(errno));
1503 filebuf[statbuf.st_size] = 0;
1507 frc = parse_forward_list(filebuf, options, &addr,
1508 error, incoming_domain, directory, syntax_errors);
1509 if (frc != FF_DELIVERED && frc != FF_NOTDELIVERED) return frc;
1514 while (last->next != NULL) { count++; last = last->next; }
1515 last->next = *anchor;
1521 /* Else (not :include:) ensure address is syntactically correct and fully
1522 qualified if not a pipe or a file, removing a leading \ if present on an
1523 unqualified address. For pipes and files we must handle quoting. It's
1524 not quite clear exactly what to do for partially quoted things, but the
1525 common case of having the whole thing in quotes is straightforward. If this
1526 was the case, inquote will have been set TRUE above and the quotes removed.
1528 There is a possible ambiguity over addresses whose local parts start with
1529 a vertical bar or a slash, and the latter do in fact occur, thanks to X.400.
1530 Consider a .forward file that contains the line
1532 /X=xxx/Y=xxx/OU=xxx/@some.gate.way
1534 Is this a file or an X.400 address? Does it make any difference if it is in
1535 quotes? On the grounds that file names of this type are rare, Exim treats
1536 something that parses as an RFC 822 address and has a domain as an address
1537 rather than a file or a pipe. This is also how an address such as the above
1538 would be treated if it came in from outside. */
1542 int start, end, domain;
1543 uschar *recipient = NULL;
1547 /* If it starts with \ and the rest of it parses as a valid mail address
1548 without a domain, carry on with that address, but qualify it with the
1549 incoming domain. Otherwise arrange for the address to fall through,
1550 causing an error message on the re-parse. */
1555 parse_extract_address(s+1, error, &start, &end, &domain, FALSE);
1556 if (recipient != NULL)
1557 recipient = (domain != 0)? NULL :
1558 string_sprintf("%s@%s", recipient, incoming_domain);
1561 /* Try parsing the item as an address. */
1563 if (recipient == NULL) recipient =
1564 parse_extract_address(s, error, &start, &end, &domain, FALSE);
1566 /* If item starts with / or | and is not a valid address, or there
1567 is no domain, treat it as a file or pipe. If it was a quoted item,
1568 remove the quoting occurrences of \ within it. */
1570 if ((*s == '|' || *s == '/') && (recipient == NULL || domain == 0))
1572 uschar *t = store_get(Ustrlen(s) + 1);
1579 *p++ = (*q == '\\')? *(++q) : *q;
1585 addr = deliver_make_addr(t, TRUE);
1586 setflag(addr, af_pfr); /* indicates pipe/file/reply */
1587 if (*s != '|') setflag(addr, af_file); /* indicates file */
1590 /* Item must be an address. Complain if not, else qualify, rewrite and set
1591 up the control block. It appears that people are in the habit of using
1592 empty addresses but with comments as a way of putting comments into
1593 alias and forward files. Therefore, ignore the error "empty address".
1594 Mailing lists might want to tolerate syntax errors; there is therefore
1595 an option to do so. */
1599 if (recipient == NULL)
1601 if (Ustrcmp(*error, "empty address") == 0)
1609 if (syntax_errors != NULL)
1611 error_block *e = store_get(sizeof(error_block));
1612 error_block *last = *syntax_errors;
1613 if (last == NULL) *syntax_errors = e; else
1615 while (last->next != NULL) last = last->next;
1620 e->text2 = string_copy(s);
1627 *error = string_sprintf("%s in \"%s\"", *error, s);
1628 s[len] = save; /* _after_ using it for *error */
1633 /* Address was successfully parsed. Rewrite, and then make an address
1636 recipient = ((options & RDO_REWRITE) != 0)?
1637 rewrite_address(recipient, TRUE, FALSE, global_rewrite_rules,
1638 rewrite_existflags) :
1639 rewrite_address_qualify(recipient, TRUE);
1640 addr = deliver_make_addr(recipient, TRUE); /* TRUE => copy recipient */
1643 /* Restore the final character in the original data, and add to the
1647 addr->next = *anchor;
1652 /* Advance pointer for the next address */
1659 /*************************************************
1660 **************************************************
1661 * Stand-alone test program *
1662 **************************************************
1663 *************************************************/
1665 #if defined STAND_ALONE
1668 int start, end, domain;
1669 uschar buffer[1024];
1670 uschar outbuff[1024];
1672 big_buffer = store_malloc(big_buffer_size);
1674 /* strip_trailing_dot = TRUE; */
1675 allow_domain_literals = TRUE;
1677 printf("Testing parse_fix_phrase\n");
1679 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
1681 buffer[Ustrlen(buffer)-1] = 0;
1682 if (buffer[0] == 0) break;
1683 printf("%s\n", CS parse_fix_phrase(buffer, Ustrlen(buffer), outbuff,
1687 printf("Testing parse_extract_address without group syntax and without UTF-8\n");
1689 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
1693 buffer[Ustrlen(buffer) - 1] = 0;
1694 if (buffer[0] == 0) break;
1695 out = parse_extract_address(buffer, &errmess, &start, &end, &domain, FALSE);
1696 if (out == NULL) printf("*** bad address: %s\n", errmess); else
1698 uschar extract[1024];
1699 Ustrncpy(extract, buffer+start, end-start);
1700 extract[end-start] = 0;
1701 printf("%s %d %d %d \"%s\"\n", out, start, end, domain, extract);
1705 printf("Testing parse_extract_address without group syntax but with UTF-8\n");
1707 allow_utf8_domains = TRUE;
1708 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
1712 buffer[Ustrlen(buffer) - 1] = 0;
1713 if (buffer[0] == 0) break;
1714 out = parse_extract_address(buffer, &errmess, &start, &end, &domain, FALSE);
1715 if (out == NULL) printf("*** bad address: %s\n", errmess); else
1717 uschar extract[1024];
1718 Ustrncpy(extract, buffer+start, end-start);
1719 extract[end-start] = 0;
1720 printf("%s %d %d %d \"%s\"\n", out, start, end, domain, extract);
1723 allow_utf8_domains = FALSE;
1725 printf("Testing parse_extract_address with group syntax\n");
1727 parse_allow_group = TRUE;
1728 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
1733 buffer[Ustrlen(buffer) - 1] = 0;
1734 if (buffer[0] == 0) break;
1738 uschar *ss = parse_find_address_end(s, FALSE);
1739 int terminator = *ss;
1741 out = parse_extract_address(buffer, &errmess, &start, &end, &domain, FALSE);
1744 if (out == NULL) printf("*** bad address: %s\n", errmess); else
1746 uschar extract[1024];
1747 Ustrncpy(extract, buffer+start, end-start);
1748 extract[end-start] = 0;
1749 printf("%s %d %d %d \"%s\"\n", out, start, end, domain, extract);
1752 s = ss + (terminator? 1:0);
1753 while (isspace(*s)) s++;
1757 printf("Testing parse_find_at\n");
1759 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
1762 buffer[Ustrlen(buffer)-1] = 0;
1763 if (buffer[0] == 0) break;
1764 s = parse_find_at(buffer);
1765 if (s == NULL) printf("no @ found\n");
1766 else printf("offset = %d\n", s - buffer);
1769 printf("Testing parse_extract_addresses\n");
1771 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
1775 address_item *anchor = NULL;
1776 buffer[Ustrlen(buffer) - 1] = 0;
1777 if (buffer[0] == 0) break;
1778 if ((extracted = parse_forward_list(buffer, -1, &anchor,
1779 &errmess, US"incoming.domain", NULL, NULL)) == FF_DELIVERED)
1781 while (anchor != NULL)
1783 address_item *addr = anchor;
1784 anchor = anchor->next;
1785 printf("%d %s\n", testflag(addr, af_pfr), addr->address);
1788 else printf("Failed: %d %s\n", extracted, errmess);
1796 /* End of parse.c */