1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) The Exim Maintainers 2020 - 2023 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
8 /* SPDX-License-Identifier: GPL-2.0-or-later */
10 /* Functions for parsing addresses */
16 static const 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. */
27 deliver_make_addr(uschar *address, BOOL copy)
29 address_item *addr = store_get(sizeof(address_item), GET_UNTAINTED);
32 addr->address = address;
37 rewrite_address(uschar *recipient, BOOL dummy1, BOOL dummy2, rewrite_rule
44 rewrite_address_qualify(uschar *recipient, BOOL dummy1)
54 /*************************************************
55 * Find the end of an address *
56 *************************************************/
58 /* Scan over a string looking for the termination of an address at a comma,
59 or end of the string. It's the source-routed addresses which cause much pain
60 here. Although Exim ignores source routes, it must recognize such addresses, so
61 we cannot get rid of this logic.
64 s pointer to the start of an address
65 nl_ends if TRUE, '\n' terminates an address
67 Returns: pointer past the end of the address
68 (i.e. points to null or comma)
72 parse_find_address_end(const uschar * s, BOOL nl_ends)
74 BOOL source_routing = *s == '@';
75 int no_term = source_routing ? 1 : 0;
77 while (*s && (*s != ',' || no_term > 0) && (*s != '\n' || !nl_ends))
79 /* Skip single quoted characters. Strictly these should not occur outside
80 quoted strings in RFC 822 addresses, but they can in RFC 821 addresses. Pity
81 about the lack of consistency, isn't it? */
83 if (*s == '\\' && s[1])
86 /* Skip quoted items that are not inside brackets. Note that
87 quoted pairs are allowed inside quoted strings. */
90 while (*++s && (*s != '\n' || !nl_ends))
92 if (*s == '\\' && s[1])
98 /* Skip comments, which may include nested brackets, but quotes
99 are not recognized inside comments, though quoted pairs are. */
104 while (*++s && (*s != '\n' || !nl_ends))
105 if (*s == '\\' && s[1])
109 else if (*s == ')' && --level <= 0)
113 /* Non-special character; just advance. Passing the colon in a source
114 routed address means that any subsequent comma or colon may terminate unless
115 inside angle brackets. */
121 source_routing = s[1] == '@';
122 no_term = source_routing ? 2 : 1;
126 else if (source_routing && *s == ':')
137 /*************************************************
138 * Find last @ in an address *
139 *************************************************/
141 /* This function is used when we have something that may not qualified. If we
142 know it's qualified, searching for the rightmost '@' is sufficient. Here we
143 have to be a bit more clever than just a plain search, in order to handle
144 unqualified local parts like "thing@thong" correctly. Since quotes may not
145 legally be part of a domain name, we can give up on hitting the first quote
146 when searching from the right. Now that the parsing also permits the RFC 821
147 form of address, where quoted-pairs are allowed in unquoted local parts, we
148 must take care to handle that too.
150 Argument: pointer to an address, possibly unqualified
151 Returns: pointer to the last @ in an address, or NULL if none
155 parse_find_at(const uschar *s)
157 const uschar * t = s + Ustrlen(s);
161 int backslash_count = 0;
162 const uschar *tt = t - 1;
163 while (tt > s && *tt-- == '\\') backslash_count++;
164 if ((backslash_count & 1) == 0) return t;
175 /***************************************************************************
176 * In all the functions below that read a particular object type from *
177 * the input, return the new value of the pointer s (the first argument), *
178 * and put the object into the store pointed to by t (the second argument), *
179 * adding a terminating zero. If no object is found, t will point to zero *
181 ***************************************************************************/
184 /*************************************************
185 * Skip white space and comment *
186 *************************************************/
190 (2) If uschar not '(', return.
191 (3) Skip till matching ')', not counting any characters
193 (4) Move past ')' and goto (1).
195 The start of the last potential comment position is remembered to
196 make it possible to ignore comments at the end of compound items.
198 Argument: current character pointer
199 Returns: new character pointer
202 static const uschar *
203 skip_comment(const uschar *s)
205 last_comment_position = s;
210 if (Uskip_whitespace(&s) != '(') break;
214 if (c == '(') level++;
215 else if (c == ')') { if (--level <= 0) { s++; break; } }
216 else if (c == '\\' && s[1] != 0) s++;
224 /*************************************************
226 *************************************************/
228 /* A domain is a sequence of subdomains, separated by dots. See comments below
229 for detailed syntax of the subdomains.
231 If allow_domain_literals is TRUE, a "domain" may also be an IP address enclosed
232 in []. Make sure the output is set to the null string if there is a syntax
233 error as well as if there is no domain at all.
235 Optionally, msg_id domain literals ( printable-ascii enclosed in [] )
239 s current character pointer
240 t where to put the domain
241 msg_id_literals flag for relaxed domain-literal processing
242 errorptr put error message here on failure (*t will be 0 on exit)
244 Returns: new character pointer
247 static const uschar *
248 read_domain(const uschar *s, uschar *t, BOOL msg_id_literals, uschar **errorptr)
253 /* Handle domain literals if permitted. An RFC 822 domain literal may contain
254 any character except [ ] \, including linear white space, and may contain
255 quoted characters. However, RFC 821 restricts literals to being dot-separated
256 3-digit numbers, and we make the obvious extension for IPv6. Go for a sequence
257 of digits, dots, hex digits, and colons here; later this will be checked for
258 being a syntactically valid IP address if it ever gets to a router.
260 Allow both the formal IPv6 form, with IPV6: at the start, and the informal form
261 without it, and accept IPV4: as well, 'cause someone will use it sooner or
268 if (strncmpic(s, US"IPv6:", 5) == 0 || strncmpic(s, US"IPv4:", 5) == 0)
276 while (*s >= 33 && *s <= 90 || *s >= 94 && *s <= 126) *t++ = *s++;
278 while (*s == '.' || *s == ':' || isxdigit(*s)) *t++ = *s++;
280 if (*s == ']') *t++ = *s++; else
282 *errorptr = US"malformed domain literal";
286 if (!allow_domain_literals && !msg_id_literals)
288 *errorptr = US"domain literals not allowed";
292 return skip_comment(s);
295 /* Handle a proper domain, which is a sequence of dot-separated atoms. Remove
296 trailing dots if strip_trailing_dot is set. A subdomain is an atom.
298 An atom is a sequence of any characters except specials, space, and controls.
299 The specials are ( ) < > @ , ; : \ " . [ and ]. This is the rule for RFC 822
300 and its successor (RFC 2822). However, RFC 821 and its successor (RFC 2821) is
301 tighter, allowing only letters, digits, and hyphens, not starting with a
304 There used to be a global flag that got set when checking addresses that came
305 in over SMTP and which should therefore should be checked according to the
306 stricter rule. However, it seems silly to make the distinction, because I don't
307 suppose anybody ever uses local domains that are 822-compliant and not
308 821-compliant. Furthermore, Exim now has additional data on the spool file line
309 after an address (after "one_time" processing), and it makes use of a #
310 character to delimit it. When I wrote that code, I forgot about this 822-domain
311 stuff, and assumed # could never appear in a domain.
313 So the old code is now cut out for Release 4.11 onwards, on 09-Aug-02. In a few
314 years, when we are sure this isn't actually causing trouble, throw it away.
316 March 2003: the story continues: There is a camp that is arguing for the use of
317 UTF-8 in domain names as the way to internationalization, and other MTAs
318 support this. Therefore, we now have a flag that permits the use of characters
319 with values greater than 127, encoded in UTF-8, in subdomains, so that Exim can
320 be used experimentally in this way. */
326 /*********************
329 if (*s != '-') while (isalnum(*s) || *s == '-') *t++ = *s++;
332 while (!mac_iscntrl_or_special(*s)) *t++ = *s++;
333 *********************/
337 /* Only letters, digits, and hyphens */
339 if (!allow_utf8_domains)
341 while (isalnum(*s) || *s == '-') *t++ = *s++;
344 /* Permit legal UTF-8 characters to be included */
349 if (isalnum(*s) || *s == '-') /* legal ascii characters */
354 if ((*s & 0xc0) != 0xc0) break; /* not start of UTF-8 character */
356 for (i = 1; i < 6; i++) /* i is the number of additional bytes */
358 if ((d & 0x80) == 0) break;
361 if (i == 6) goto BAD_UTF8; /* invalid UTF-8 */
362 *t++ = *s++; /* leading UTF-8 byte */
363 while (i-- > 0) /* copy and check remainder */
365 if ((*s & 0xc0) != 0x80)
368 *errorptr = US"invalid UTF-8 byte sequence";
374 } /* End of loop for UTF-8 character */
375 } /* End of subdomain */
380 if (t == tsave) /* empty component */
382 if (strip_trailing_dot && t > tt && *s != '.') t[-1] = 0; else
384 *errorptr = US"domain missing or malformed";
390 if (*s != '.') break;
400 /*************************************************
401 * Read a local-part *
402 *************************************************/
404 /* A local-part is a sequence of words, separated by periods. A null word
405 between dots is not strictly allowed but apparently many mailers permit it,
406 so, sigh, better be compatible. Even accept a trailing dot...
408 A <word> is either a quoted string, or an <atom>, which is a sequence
409 of any characters except specials, space, and controls. The specials are
410 ( ) < > @ , ; : \ " . [ and ]. In RFC 822, a single quoted character, (a
411 quoted-pair) is not allowed in a word. However, in RFC 821, it is permitted in
412 the local part of an address. Rather than have separate parsing functions for
413 the different cases, take the liberal attitude always. At least one MUA is
414 happy to recognize this case; I don't know how many other programs do.
417 s current character pointer
418 t where to put the local part
419 error where to point error text
420 allow_null TRUE if an empty local part is not an error
422 Returns: new character pointer
425 static const uschar *
426 read_local_part(const uschar *s, uschar *t, uschar **error, BOOL allow_null)
436 /* Handle a quoted string */
441 while ((c = *++s) && c != '\"')
444 if (c == '\\' && s[1]) *t++ = *++s;
453 *error = US"unmatched doublequote in local part";
458 /* Handle an atom, but allow quoted pairs within it. */
460 else while (!mac_iscntrl_or_special(*s) || *s == '\\')
463 if (c == '\\' && *s) *t++ = *s++;
466 /* Terminate the word and skip subsequent comment */
471 /* If we have read a null component at this point, give an error unless it is
472 terminated by a dot - an extension to RFC 822 - or if it is the first
473 component of the local part and an empty local part is permitted, in which
474 case just return normally. */
476 if (t == tsave && *s != '.')
478 if (t == tt && !allow_null)
479 *error = US"missing or malformed local part";
483 /* Anything other than a dot terminates the local part. Treat multiple dots
484 as a single dot, as this seems to be a common extension. */
486 if (*s != '.') break;
487 do { *t++ = *s++; } while (*s == '.');
494 /*************************************************
495 * Read route part of route-addr *
496 *************************************************/
498 /* The pointer is at the initial "@" on entry. Return it following the
499 terminating colon. Exim no longer supports the use of source routes, but it is
500 required to accept the syntax.
503 s current character pointer
504 t where to put the route
505 errorptr where to put an error message
507 Returns: new character pointer
510 static const uschar *
511 read_route(const uschar *s, uschar *t, uschar **errorptr)
519 s = read_domain(s+1, t, FALSE, errorptr);
520 if (*t == 0) return s;
521 t += Ustrlen((const uschar *)t);
522 if (*s != ',') break;
528 if (*s == ':') *t++ = *s++;
530 /* If there is no colon, and there were no commas, the most likely error
531 is in fact a missing local part in the address rather than a missing colon
534 else *errorptr = commas?
535 US"colon expected after route list" :
538 /* Terminate the route and return */
541 return skip_comment(s);
546 /*************************************************
548 *************************************************/
550 /* Addr-spec is local-part@domain. We make the domain optional -
551 the expected terminator for the whole thing is passed to check this.
552 This function is called only when we know we have a route-addr.
555 s current character pointer
556 t where to put the addr-spec
557 term expected terminator (0 or >)
558 errorptr where to put an error message
559 domainptr set to point to the start of the domain
561 Returns: new character pointer
564 static const uschar *
565 read_addr_spec(const uschar *s, uschar *t, int term, uschar **errorptr,
568 s = read_local_part(s, t, errorptr, FALSE);
569 if (*errorptr == NULL)
572 *errorptr = string_sprintf("\"@\" or \".\" expected after \"%s\"", t);
575 t += Ustrlen((const uschar *)t);
578 s = read_domain(s, t, FALSE, errorptr);
585 /*************************************************
586 * Extract operative address *
587 *************************************************/
589 /* This function extracts an operative address from a full RFC822 mailbox and
590 returns it in a piece of dynamic store. We take the easy way and get a piece
591 of store the same size as the input, and then copy into it whatever is
592 necessary. If we cannot find a valid address (syntax error), return NULL, and
593 point the error pointer to the reason. The arguments "start" and "end" are used
594 to return the offsets of the first and one past the last characters in the
595 original mailbox of the address that has been extracted, to aid in re-writing.
596 The argument "domain" is set to point to the first character after "@" in the
597 final part of the returned address, or zero if there is no @.
599 Exim no longer supports the use of source routed addresses (those of the form
600 @domain,...:route_addr). It recognizes the syntax, but collapses such addresses
601 down to their final components. Formerly, collapse_source_routes had to be set
602 to achieve this effect. RFC 1123 allows collapsing with MAY, while the revision
603 of RFC 821 had increased this to SHOULD, so I've gone for it, because it makes
604 a lot of code elsewhere in Exim much simpler.
606 There are some special fudges here for handling RFC 822 group address notation
607 which may appear in certain headers. If the flag parse_allow_group is set
608 TRUE and parse_found_group is FALSE when this function is called, an address
609 which is the start of a group (i.e. preceded by a phrase and a colon) is
610 recognized; the phrase is ignored and the flag parse_found_group is set. If
611 this flag is TRUE at the end of an address, and if an extraneous semicolon is
612 found, it is ignored and the flag is cleared.
614 This logic is used only when scanning through addresses in headers, either to
615 fulfil the -t option, or for rewriting, or for checking header syntax. Because
616 the group "state" has to be remembered between multiple calls of this function,
617 the variables parse_{allow,found}_group are global. It is important to ensure
618 that they are reset to FALSE at the end of scanning a header's list of
622 mailbox points to the RFC822 mailbox
623 errorptr where to point an error message
624 start set to start offset in mailbox
625 end set to end offset in mailbox
626 domain set to domain offset in result, or 0 if no domain present
627 allow_null allow <> if TRUE
629 Returns: points to the extracted address, or NULL on error
632 #define FAILED(s) { *errorptr = s; goto PARSE_FAILED; }
635 parse_extract_address(const uschar *mailbox, uschar **errorptr, int *start, int *end,
636 int *domain, BOOL allow_null)
638 uschar * yield = store_get(Ustrlen(mailbox) + 1, mailbox);
639 const uschar *startptr, *endptr;
640 const uschar *s = US mailbox;
641 uschar *t = US yield;
645 /* At the start of the string we expect either an addr-spec or a phrase
646 preceding a <route-addr>. If groups are allowed, we might also find a phrase
647 preceding a colon and an address. If we find an initial word followed by
648 a dot, strict interpretation of the RFC would cause it to be taken
649 as the start of an addr-spec. However, many mailers break the rules
650 and use addresses of the form "a.n.other <ano@somewhere>" and so we
653 RESTART: /* Come back here after passing a group name */
656 startptr = s; /* In case addr-spec */
657 s = read_local_part(s, t, errorptr, TRUE); /* Dot separated words */
658 if (*errorptr) goto PARSE_FAILED;
660 /* If the terminator is neither < nor @ then the format of the address
661 must either be a bare local-part (we are now at the end), or a phrase
662 followed by a route-addr (more words must follow). */
664 if (*s != '@' && *s != '<')
666 if (!*s || *s == ';')
668 if (!*t) FAILED(US"empty address");
669 endptr = last_comment_position;
670 goto PARSE_SUCCEEDED; /* Bare local part */
673 /* Expect phrase route-addr, or phrase : if groups permitted, but allow
674 dots in the phrase; complete the loop only when '<' or ':' is encountered -
675 end of string will produce a null local_part and therefore fail. We don't
676 need to keep updating t, as the phrase isn't to be kept. */
678 while (*s != '<' && (!f.parse_allow_group || *s != ':'))
680 s = read_local_part(s, t, errorptr, FALSE);
683 *errorptr = string_sprintf("%s (expected word or \"<\")", *errorptr);
690 f.parse_found_group = TRUE;
691 f.parse_allow_group = FALSE;
696 /* Assert *s == '<' */
699 /* At this point the next character is either '@' or '<'. If it is '@', only a
700 single local-part has previously been read. An angle bracket signifies the
701 start of an <addr-spec>. Throw away anything we have saved so far before
702 processing it. Note that this is "if" rather than "else if" because it's also
703 used after reading a preceding phrase.
705 There are a lot of broken sendmails out there that put additional pairs of <>
706 round <route-addr>s. If strip_excess_angle_brackets is set, allow a limited
707 number of them, as long as they match. */
711 uschar *domainptr = yield;
712 BOOL source_routed = FALSE;
713 int bracket_count = 1;
716 if (strip_excess_angle_brackets) while (*s == '<')
718 if(bracket_count++ > 5) FAILED(US"angle-brackets nested too deep");
726 /* Read an optional series of routes, each of which is a domain. They
727 are separated by commas and terminated by a colon. However, we totally ignore
728 such routes (RFC 1123 says we MAY, and the revision of RFC 821 says we
733 s = read_route(s, t, errorptr);
734 if (*errorptr) goto PARSE_FAILED;
735 *t = 0; /* Ensure route is ignored - probably overkill */
736 source_routed = TRUE;
739 /* Now an addr-spec, terminated by '>'. If there is no preceding route,
740 we must allow an empty addr-spec if allow_null is TRUE, to permit the
741 address "<>" in some circumstances. A source-routed address MUST have
742 a domain in the final part. */
744 if (allow_null && !source_routed && *s == '>')
751 s = read_addr_spec(s, t, '>', errorptr, &domainptr);
752 if (*errorptr) goto PARSE_FAILED;
753 *domain = domainptr - yield;
754 if (source_routed && *domain == 0)
755 FAILED(US"domain missing in source-routed address");
759 if (*errorptr) goto PARSE_FAILED;
760 while (bracket_count-- > 0) if (*s++ != '>')
762 *errorptr = s[-1] == 0
763 ? US"'>' missing at end of address"
764 : string_sprintf("malformed address: %.32s may not follow %.*s",
765 s-1, (int)(s - US mailbox - 1), mailbox);
772 /* Hitting '@' after the first local-part means we have definitely got an
773 addr-spec, on a strict reading of the RFC, and the rest of the string
774 should be the domain. However, for flexibility we allow for a route-address
775 not enclosed in <> as well, which is indicated by an empty first local
776 part preceding '@'. The source routing is, however, ignored. */
780 uschar *domainptr = yield;
781 s = read_route(s, t, errorptr);
782 if (*errorptr) goto PARSE_FAILED;
783 *t = 0; /* Ensure route is ignored - probably overkill */
784 s = read_addr_spec(s, t, 0, errorptr, &domainptr);
785 if (*errorptr) goto PARSE_FAILED;
786 *domain = domainptr - yield;
787 endptr = last_comment_position;
788 if (*domain == 0) FAILED(US"domain missing in source-routed address");
791 /* This is the strict case of local-part@domain. */
795 t += Ustrlen((const uschar *)t);
798 s = read_domain(s, t, TRUE, errorptr);
799 if (!*t) goto PARSE_FAILED;
800 endptr = last_comment_position;
803 /* Use goto to get here from the bare local part case. Arrive by falling
804 through for other cases. Endptr may have been moved over whitespace, so
805 move it back past white space if necessary. */
810 if (f.parse_found_group && *s == ';')
812 f.parse_found_group = FALSE;
813 f.parse_allow_group = TRUE;
817 *errorptr = string_sprintf("malformed address: %.32s may not follow %.*s",
818 s, (int)(s - US mailbox), mailbox);
822 *start = startptr - US mailbox; /* Return offsets */
823 while (isspace(endptr[-1])) endptr--;
824 *end = endptr - US mailbox;
826 /* Although this code has no limitation on the length of address extracted,
827 other parts of Exim may have limits, and in any case, RFC 5321 limits email
828 addresses to 256, so we do a check here, giving an error if the address is
829 ridiculously long. */
831 if (*end - *start > EXIM_EMAILADDR_MAX)
833 *errorptr = string_sprintf("address is ridiculously long: %.64s...", yield);
839 /* Use goto (via the macro FAILED) to get to here from a variety of places.
840 We might have an empty address in a group - the caller can choose to ignore
841 this. We must, however, keep the flags correct. */
844 if (f.parse_found_group && *s == ';')
846 f.parse_found_group = FALSE;
847 f.parse_allow_group = TRUE;
856 /*************************************************
857 * Quote according to RFC 2047 *
858 *************************************************/
860 /* This function is used for quoting text in headers according to RFC 2047.
861 If the only characters that strictly need quoting are spaces, we return the
862 original string, unmodified.
864 Hmmph. As always, things get perverted for other uses. This function was
865 originally for the "phrase" part of addresses. Now it is being used for much
866 longer texts in ACLs and via the ${rfc2047: expansion item. This means we have
867 to check for overlong "encoded-word"s and split them. November 2004.
870 string the string to quote - already checked to contain non-printing
872 len the length of the string
873 charset the name of the character set; NULL => iso-8859-1
874 fold if TRUE, a newline is inserted before the separating space when
875 more than one encoded-word is generated
877 Returns: pointer to the original string, if no quoting needed, or
878 pointer to allocated memory containing the quoted string
882 parse_quote_2047(const uschar * string, int len, const uschar * charset,
885 const uschar * s = string;
888 BOOL first_byte = FALSE;
890 string_fmt_append(NULL, "=?%s?Q?%n", charset ? charset : US"iso-8859-1", &hlen);
894 for (s = string; len > 0; s++, len--)
898 if (g->ptr - line_off > 67 && !first_byte)
900 g = fold ? string_catn(g, US"?=\n ", 4) : string_catn(g, US"?= ", 3);
902 g = string_catn(g, g->s, hlen);
905 if ( ch < 33 || ch > 126
906 || Ustrchr("?=()<>@,;:\\\".[]_", ch) != NULL)
910 g = string_catn(g, US"_", 1);
915 g = string_fmt_append(g, "=%02X", ch);
917 first_byte = !first_byte;
921 { g = string_catn(g, s, 1); first_byte = FALSE; }
925 string = string_from_gstring(g = string_catn(g, US"?=", 2));
929 gstring_release_unused(g);
936 /*************************************************
937 * Fix up an RFC 822 "phrase" *
938 *************************************************/
940 /* This function is called to repair any syntactic defects in the "phrase" part
941 of an RFC822 address. In particular, it is applied to the user's name as read
942 from the passwd file when accepting a local message, and to the data from the
945 If the string contains existing quoted strings or comments containing
946 freestanding quotes, then we just quote those bits that need quoting -
947 otherwise it would get awfully messy and probably not look good. If not, we
948 quote the whole thing if necessary. Thus
950 John Q. Smith => "John Q. Smith"
951 John "Jack" Smith => John "Jack" Smith
952 John "Jack" Q. Smith => John "Jack" "Q." Smith
953 John (Jack) Q. Smith => "John (Jack) Q. Smith"
954 John ("Jack") Q. Smith => John ("Jack") "Q." Smith
956 John (\"Jack\") Q. Smith => "John (\"Jack\") Q. Smith"
958 Sheesh! This is tedious code. It is a great pity that the syntax of RFC822 is
961 August 2000: Additional code added:
963 Previously, non-printing characters were turned into question marks, which do
964 not need to be quoted.
966 Now, a different tactic is used if there are any non-printing ASCII
967 characters. The encoding method from RFC 2047 is used, assuming iso-8859-1 as
970 We *could* use this for all cases, getting rid of the messy original code,
971 but leave it for now. It would complicate simple cases like "John Q. Smith".
973 The result is passed back in allocated memory.
976 phrase an RFC822 phrase
977 len the length of the phrase
979 Returns: the fixed RFC822 phrase
983 parse_fix_phrase(const uschar *phrase, int len)
987 const uschar *s, *end;
991 while (len > 0 && isspace(*phrase)) { phrase++; len--; }
993 /* See if there are any non-printing characters, and if so, use the RFC 2047
994 encoding for the whole thing. */
996 for (i = 0, s = phrase; i < len; i++, s++)
997 if ((*s < 32 && *s != '\t') || *s > 126) break;
1000 return parse_quote_2047(phrase, len, headers_charset, FALSE);
1002 /* No non-printers; use the RFC 822 quoting rules */
1004 if (len <= 0 || len >= INT_MAX/4)
1005 return string_copy_taint(CUS"", phrase);
1007 buffer = store_get((len+1)*4, phrase);
1011 yield = t = buffer + 1;
1017 /* Copy over quoted strings, remembering we encountered one */
1022 while (s < end && (ch = *s++) != '\"')
1025 if (ch == '\\' && s < end) *t++ = *s++;
1028 if (s >= end) break;
1032 /* Copy over comments, noting if they contain freestanding quote
1043 if (ch == '(') level++;
1044 else if (ch == ')') { if (--level <= 0) break; }
1045 else if (ch == '\\' && s < end) *t++ = *s++ & 127;
1046 else if (ch == '\"') quoted = TRUE;
1050 while (level--) *t++ = ')';
1055 /* Handle special characters that need to be quoted */
1057 else if (Ustrchr(")<>@,;:\\.[]", ch) != NULL)
1059 /* If hit previous quotes just make one quoted "word" */
1064 while (*(--tt) != ' ' && *tt != '\"' && *tt != ')') tt[1] = *tt;
1070 if (ch == ' ' || ch == '\"') { s--; break; } else *t++ = ch;
1075 /* Else quote the whole string so far, and the rest up to any following
1076 quotes. We must treat anything following a backslash as a literal. */
1080 BOOL escaped = (ch == '\\');
1084 /* Now look for the end or a quote */
1090 /* Handle escaped pairs */
1098 else if (ch == '\\')
1104 /* If hit subsequent quotes, insert our quote before any trailing
1105 spaces and back up to re-handle the quote in the outer loop. */
1107 else if (ch == '\"')
1110 while (t[-1] == ' ') { t--; count++; }
1112 while (count-- > 0) *t++ = ' ';
1117 /* If hit a subsequent comment, check it for unescaped quotes,
1118 and if so, end our quote before it. */
1122 const uschar *ss = s; /* uschar after '(' */
1127 if (ch == '(') level++;
1128 else if (ch == ')') { if (--level <= 0) break; }
1129 else if (ch == '\\' && ss+1 < end) ss++;
1130 else if (ch == '\"') { quoted = TRUE; break; }
1133 /* Comment contains unescaped quotes; end our quote before
1134 the start of the comment. */
1139 while (t[-1] == ' ') { t--; count++; }
1141 while (count-- > 0) *t++ = ' ';
1145 /* Comment does not contain unescaped quotes; include it in
1150 if (ss >= end) ss--;
1154 Ustrncpy(t, s, ss-s);
1161 /* Not a comment or quote; include this character in our quotes. */
1167 /* Add a final quote if we hit the end of the string. */
1169 if (s >= end) *t++ = '\"';
1172 /* Non-special character; just copy it over */
1178 store_release_above(t+1);
1183 /*************************************************
1184 * Extract addresses from a list *
1185 *************************************************/
1187 /* This function is called by the redirect router to scan a string containing a
1188 list of addresses separated by commas (with optional white space) or by
1189 newlines, and to generate a chain of address items from them. In other words,
1190 to unpick data from an alias or .forward file.
1192 The SunOS5 documentation for alias files is not very clear on the syntax; it
1193 does not say that either a comma or a newline can be used for separation.
1194 However, that is the way Smail does it, so we follow suit.
1196 If a # character is encountered in a white space position, then characters from
1197 there to the next newline are skipped.
1199 If an unqualified address begins with '\', just skip that character. This gives
1200 compatibility with Sendmail's use of \ to prevent looping. Exim has its own
1201 loop prevention scheme which handles other cases too - see the code in
1204 An "address" can be a specification of a file or a pipe; the latter may often
1205 need to be quoted because it may contain spaces, but we don't want to retain
1206 the quotes. Quotes may appear in normal addresses too, and should be retained.
1207 We can distinguish between these cases, because in addresses, quotes are used
1208 only for parts of the address, not the whole thing. Therefore, we remove quotes
1209 from items when they entirely enclose them, but not otherwise.
1211 An "address" can also be of the form :include:pathname to include a list of
1212 addresses contained in the specified file.
1214 Any unqualified addresses are qualified with and rewritten if necessary, via
1215 the rewrite_address() function.
1218 s the list of addresses (typically a complete
1219 .forward file or a list of entries in an alias file)
1220 options option bits for permitting or denying various special cases;
1221 not all bits are relevant here - some are for filter
1222 files; those we use here are:
1229 anchor where to hang the chain of newly-created addresses. This
1230 should be initialized to NULL.
1231 error where to return an error text
1232 incoming domain domain of the incoming address; used to qualify unqualified
1233 local parts preceded by \
1234 directory if NULL, no checks are done on :include: files
1235 otherwise, included file names must start with the given
1237 syntax_errors if not NULL, it carries on after syntax errors in addresses,
1238 building up a list of errors as error blocks chained on
1241 Returns: FF_DELIVERED addresses extracted
1242 FF_NOTDELIVERED no addresses extracted, but no errors
1243 FF_BLACKHOLE :blackhole:
1246 FF_INCLUDEFAIL some problem with :include:; *error set
1247 FF_ERROR other problems; *error is set
1251 parse_forward_list(const uschar *s, int options, address_item **anchor,
1252 uschar **error, const uschar *incoming_domain, const uschar *directory,
1253 error_block **syntax_errors)
1257 DEBUG(D_route) debug_printf("parse_forward_list: %s\n", s);
1261 int len, special = 0, specopt = 0, specbit = 0;
1262 const uschar * ss, * nexts;
1263 address_item * addr;
1264 BOOL inquote = FALSE;
1268 while (isspace(*s) || *s == ',') s++;
1269 if (*s == '#') { while (*s && *s != '\n') s++; } else break;
1272 /* When we reach the end of the list, we return FF_DELIVERED if any child
1273 addresses have been generated. If nothing has been generated, there are two
1274 possibilities: either the list is really empty, or there were syntax errors
1275 that are being skipped. (If syntax errors are not being skipped, an FF_ERROR
1276 return is generated on hitting a syntax error and we don't get here.) For a
1277 truly empty list we return FF_NOTDELIVERED so that the router can decline.
1278 However, if the list is empty only because syntax errors were skipped, we
1279 return FF_DELIVERED. */
1283 return (count > 0 || (syntax_errors && *syntax_errors))
1284 ? FF_DELIVERED : FF_NOTDELIVERED;
1286 /* This previous code returns FF_ERROR if nothing is generated but a
1287 syntax error has been skipped. I now think it is the wrong approach, but
1288 have left this here just in case, and for the record. */
1291 if (count > 0) return FF_DELIVERED; /* Something was generated */
1293 if (!syntax_errors || /* Not skipping syntax errors, or */
1294 !*syntax_errors) /* we didn't actually skip any */
1295 return FF_NOTDELIVERED;
1297 *error = string_sprintf("no addresses generated: syntax error in %s: %s",
1298 (*syntax_errors)->text2, (*syntax_errors)->text1);
1303 /* Find the end of the next address. Quoted strings in addresses may contain
1304 escaped characters; I haven't found a proper specification of .forward or
1305 alias files that mentions the quoting properties, but it seems right to do
1306 the escaping thing in all cases, so use the function that finds the end of an
1307 address. However, don't let a quoted string extend over the end of a line. */
1309 ss = parse_find_address_end(s, TRUE);
1311 /* Remember where we finished, for starting the next one. */
1315 /* Remove any trailing spaces; we know there's at least one non-space. */
1317 while (isspace(ss[-1])) ss--;
1319 /* We now have s->start and ss->end of the next address. Remove quotes
1320 if they completely enclose, remembering the address started with a quote
1321 for handling pipes and files. Another round of removal of leading and
1322 trailing spaces is then required. */
1324 if (*s == '\"' && ss[-1] == '\"')
1329 while (s < ss && isspace(*s)) s++;
1330 while (ss > s && isspace(ss[-1])) ss--;
1333 /* Set up the length of the address. */
1337 DEBUG(D_route) debug_printf("extract item: %.*s\n", len, s);
1339 /* Handle special addresses if permitted. If the address is :unknown:
1340 ignore it - this is for backward compatibility with old alias files. You
1341 don't need to use it nowadays - just generate an empty string. For :defer:,
1342 :blackhole:, or :fail: we have to set up the error message and give up right
1345 if (Ustrncmp(s, ":unknown:", len) == 0)
1351 if (Ustrncmp(s, ":defer:", 7) == 0)
1352 { special = FF_DEFER; specopt = RDO_DEFER; } /* specbit is 0 */
1353 else if (Ustrncmp(s, ":blackhole:", 11) == 0)
1354 { special = FF_BLACKHOLE; specopt = specbit = RDO_BLACKHOLE; }
1355 else if (Ustrncmp(s, ":fail:", 6) == 0)
1356 { special = FF_FAIL; specopt = RDO_FAIL; } /* specbit is 0 */
1360 uschar * ss = Ustrchr(s+1, ':') + 1; /* line after the special... */
1361 if ((options & specopt) == specbit)
1363 *error = string_sprintf("\"%.*s\" is not permitted", len, s);
1366 Uskip_whitespace(&ss); /* skip leading whitespace */
1367 if ((len = Ustrlen(ss)) > 0) /* ignore trailing newlines */
1368 for (const uschar * t = ss + len - 1; t >= ss && *t == '\n'; t--) len--;
1369 *error = string_copyn(ss, len); /* becomes the error */
1373 /* If the address is of the form :include:pathname, read the file, and call
1374 this function recursively to extract the addresses from it. If directory is
1375 NULL, do no checks. Otherwise, insist that the file name starts with the
1376 given directory and is a regular file. */
1378 if (Ustrncmp(s, ":include:", 9) == 0)
1381 uschar filename[256];
1382 const uschar * t = s+9;
1385 struct stat statbuf;
1386 address_item * last;
1389 while (flen > 0 && isspace(*t)) { t++; flen--; }
1393 *error = US"file name missing after :include:";
1397 if (flen > sizeof(filename)-1)
1399 *error = string_sprintf("included file name \"%s\" is too long", t);
1403 Ustrncpy(filename, t, flen);
1406 /* Insist on absolute path */
1408 if (filename[0] != '/')
1410 *error = string_sprintf("included file \"%s\" is not an absolute path",
1415 /* Check if include is permitted */
1417 if (options & RDO_INCLUDE)
1419 *error = US"included files not permitted";
1423 if (is_tainted(filename))
1425 *error = string_sprintf("Tainted name '%s' for included file not permitted\n",
1430 /* Check file name if required */
1434 int len = Ustrlen(directory);
1437 while (len > 0 && directory[len-1] == '/') len--; /* ignore trailing '/' */
1439 if (Ustrncmp(filename, directory, len) != 0 || *p != '/')
1441 *error = string_sprintf("included file %s is not in directory %s",
1442 filename, directory);
1446 #ifdef EXIM_HAVE_OPENAT
1447 /* It is necessary to check that every component inside the directory
1448 is NOT a symbolic link, in order to keep the file inside the directory.
1449 This is mighty tedious. We open the directory and openat every component,
1450 with a flag that fails symlinks. */
1453 int fd = exim_open2(CCS directory, O_RDONLY);
1456 *error = string_sprintf("failed to open directory %s", directory);
1463 uschar * q = p + 1; /* skip dividing '/' */
1465 while (*q == '/') q++; /* skip extra '/' */
1466 while (*++p && *p != '/') ; /* end of component */
1470 fd2 = exim_openat(fd, CS q, O_RDONLY|O_NOFOLLOW);
1475 *error = string_sprintf("failed to open %s (component of included "
1476 "file); could be symbolic link", filename);
1481 f = fdopen(fd, "rb");
1484 /* It is necessary to check that every component inside the directory
1485 is NOT a symbolic link, in order to keep the file inside the directory.
1486 This is mighty tedious. It is also not totally foolproof in that it
1487 leaves the possibility of a race attack, but I don't know how to do
1493 while (*++p && *p != '/');
1496 if (Ulstat(filename, &statbuf) != 0)
1498 *error = string_sprintf("failed to stat %s (component of included "
1506 if ((statbuf.st_mode & S_IFMT) == S_IFLNK)
1508 *error = string_sprintf("included file %s in the %s directory "
1509 "involves a symbolic link", filename, directory);
1516 #ifdef EXIM_HAVE_OPENAT
1519 /* Open and stat the file */
1520 f = Ufopen(filename, "rb");
1524 *error = string_open_failed("included file %s", filename);
1525 return FF_INCLUDEFAIL;
1528 if (fstat(fileno(f), &statbuf) != 0)
1530 *error = string_sprintf("failed to stat included file %s: %s",
1531 filename, strerror(errno));
1533 return FF_INCLUDEFAIL;
1536 /* If directory was checked, double check that we opened a regular file */
1538 if (directory && (statbuf.st_mode & S_IFMT) != S_IFREG)
1540 *error = string_sprintf("included file %s is not a regular file in "
1541 "the %s directory", filename, directory);
1545 /* Get a buffer and read the contents */
1547 if (statbuf.st_size > MAX_INCLUDE_SIZE)
1549 *error = string_sprintf("included file %s is too big (max %d)",
1550 filename, MAX_INCLUDE_SIZE);
1554 filebuf = store_get(statbuf.st_size + 1, filename);
1555 if (fread(filebuf, 1, statbuf.st_size, f) != statbuf.st_size)
1557 *error = string_sprintf("error while reading included file %s: %s",
1558 filename, strerror(errno));
1562 filebuf[statbuf.st_size] = 0;
1566 frc = parse_forward_list(filebuf, options, &addr,
1567 error, incoming_domain, directory, syntax_errors);
1568 if (frc != FF_DELIVERED && frc != FF_NOTDELIVERED) return frc;
1572 for (last = addr; last->next; last = last->next) count++;
1573 last->next = *anchor;
1579 /* Else (not :include:) ensure address is syntactically correct and fully
1580 qualified if not a pipe or a file, removing a leading \ if present on an
1581 unqualified address. For pipes and files we must handle quoting. It's
1582 not quite clear exactly what to do for partially quoted things, but the
1583 common case of having the whole thing in quotes is straightforward. If this
1584 was the case, inquote will have been set TRUE above and the quotes removed.
1586 There is a possible ambiguity over addresses whose local parts start with
1587 a vertical bar or a slash, and the latter do in fact occur, thanks to X.400.
1588 Consider a .forward file that contains the line
1590 /X=xxx/Y=xxx/OU=xxx/@some.gate.way
1592 Is this a file or an X.400 address? Does it make any difference if it is in
1593 quotes? On the grounds that file names of this type are rare, Exim treats
1594 something that parses as an RFC 822 address and has a domain as an address
1595 rather than a file or a pipe. This is also how an address such as the above
1596 would be treated if it came in from outside. */
1600 int start, end, domain;
1601 const uschar *recipient = NULL;
1602 uschar * s_ltd = string_copyn(s, len);
1604 /* If it starts with \ and the rest of it parses as a valid mail address
1605 without a domain, carry on with that address, but qualify it with the
1606 incoming domain. Otherwise arrange for the address to fall through,
1607 causing an error message on the re-parse. */
1612 parse_extract_address(s_ltd+1, error, &start, &end, &domain, FALSE);
1614 recipient = domain != 0 ? NULL :
1615 string_sprintf("%s@%s", recipient, incoming_domain);
1618 /* Try parsing the item as an address. */
1620 if (!recipient) recipient =
1621 parse_extract_address(s_ltd, error, &start, &end, &domain, FALSE);
1623 /* If item starts with / or | and is not a valid address, or there
1624 is no domain, treat it as a file or pipe. If it was a quoted item,
1625 remove the quoting occurrences of \ within it. */
1627 if ((*s_ltd == '|' || *s_ltd == '/') && (!recipient || domain == 0))
1629 uschar * t = store_get(Ustrlen(s_ltd) + 1, s_ltd);
1630 uschar * p = t, * q = s_ltd;
1636 *p++ = *q == '\\' ? *++q : *q;
1642 addr = deliver_make_addr(t, TRUE);
1643 setflag(addr, af_pfr); /* indicates pipe/file/reply */
1644 if (*s_ltd != '|') setflag(addr, af_file); /* indicates file */
1647 /* Item must be an address. Complain if not, else qualify, rewrite and set
1648 up the control block. It appears that people are in the habit of using
1649 empty addresses but with comments as a way of putting comments into
1650 alias and forward files. Therefore, ignore the error "empty address".
1651 Mailing lists might want to tolerate syntax errors; there is therefore
1652 an option to do so. */
1658 if (Ustrcmp(*error, "empty address") == 0)
1667 error_block * e = store_get(sizeof(error_block), GET_UNTAINTED);
1668 error_block * last = *syntax_errors;
1671 while (last->next) last = last->next;
1684 *error = string_sprintf("%s in \"%s\"", *error, s_ltd);
1689 /* Address was successfully parsed. Rewrite, and then make an address
1692 recipient = options & RDO_REWRITE
1693 ? rewrite_address(recipient, TRUE, FALSE, global_rewrite_rules,
1695 : rewrite_address_qualify(recipient, TRUE); /*XXX loses track of const */
1696 addr = deliver_make_addr(US recipient, TRUE); /* TRUE => copy recipient, so deconst ok */
1699 /* Add the original data to the output chain. */
1701 addr->next = *anchor;
1706 /* Advance pointer for the next address */
1713 /*************************************************
1714 * Extract a Message-ID *
1715 *************************************************/
1717 /* This function is used to extract message ids from In-Reply-To: and
1718 References: header lines.
1721 str pointer to the start of the message-id
1722 yield put pointer to the message id (in dynamic memory) here
1723 error put error message here on failure
1725 Returns: points after the processed message-id or NULL on error
1729 parse_message_id(const uschar *str, uschar **yield, uschar **error)
1731 uschar *domain = NULL;
1735 str = skip_comment(str);
1738 *error = US"Missing '<' before message-id";
1742 /* Getting a block the size of the input string will definitely be sufficient
1743 for the answer, but it may also be very long if we are processing a header
1744 line. Therefore, take care to release unwanted store afterwards. */
1746 reset_point = store_mark();
1747 id = *yield = store_get(Ustrlen(str) + 1, str);
1750 str = read_addr_spec(str, id, '>', error, &domain);
1754 if (*str != '>') *error = US"Missing '>' after message-id";
1755 else if (domain == NULL) *error = US"domain missing in message-id";
1760 store_reset(reset_point);
1767 store_release_above(id);
1769 return skip_comment(str);
1773 /*************************************************
1774 * Parse a fixed digit number *
1775 *************************************************/
1777 /* Parse a string containing an ASCII encoded fixed digits number
1780 str pointer to the start of the ASCII encoded number
1781 n pointer to the resulting value
1782 digits number of required digits
1784 Returns: points after the processed date or NULL on error
1787 static const uschar *
1788 parse_number(const uschar *str, int *n, int digits)
1793 if (*str<'0' || *str>'9') return NULL;
1794 *n=10*(*n)+(*str++-'0');
1800 /*************************************************
1801 * Parse a RFC 2822 day of week *
1802 *************************************************/
1804 /* Parse the day of the week from a RFC 2822 date, but do not
1805 decode it, because it is only for humans.
1808 str pointer to the start of the day of the week
1810 Returns: points after the parsed day or NULL on error
1813 static const uschar *
1814 parse_day_of_week(const uschar * str)
1817 day-of-week = ([FWS] day-name) / obs-day-of-week
1819 day-name = "Mon" / "Tue" / "Wed" / "Thu" /
1820 "Fri" / "Sat" / "Sun"
1822 obs-day-of-week = [CFWS] day-name [CFWS]
1825 static const uschar *day_name[7]={ US"mon", US"tue", US"wed", US"thu", US"fri", US"sat", US"sun" };
1829 str = skip_comment(str);
1830 for (i = 0; i < 3; ++i)
1832 if ((day[i] = tolower(*str)) == '\0') return NULL;
1836 for (i = 0; i<7; ++i) if (Ustrcmp(day,day_name[i]) == 0) break;
1837 if (i == 7) return NULL;
1838 return skip_comment(str);
1842 /*************************************************
1843 * Parse a RFC 2822 date *
1844 *************************************************/
1846 /* Parse the date part of a RFC 2822 date-time, extracting the
1847 day, month and year.
1850 str pointer to the start of the date
1851 d pointer to the resulting day
1852 m pointer to the resulting month
1853 y pointer to the resulting year
1855 Returns: points after the processed date or NULL on error
1858 static const uschar *
1859 parse_date(const uschar *str, int *d, int *m, int *y)
1862 date = day month year
1864 year = 4*DIGIT / obs-year
1866 obs-year = [CFWS] 2*DIGIT [CFWS]
1868 month = (FWS month-name FWS) / obs-month
1870 month-name = "Jan" / "Feb" / "Mar" / "Apr" /
1871 "May" / "Jun" / "Jul" / "Aug" /
1872 "Sep" / "Oct" / "Nov" / "Dec"
1874 obs-month = CFWS month-name CFWS
1876 day = ([FWS] 1*2DIGIT) / obs-day
1878 obs-day = [CFWS] 1*2DIGIT [CFWS]
1881 const uschar * s, * n;
1882 static const uschar *month_name[]={ US"jan", US"feb", US"mar", US"apr", US"may", US"jun", US"jul", US"aug", US"sep", US"oct", US"nov", US"dec" };
1886 str = skip_comment(str);
1887 if ((str = parse_number(str,d,1)) == NULL) return NULL;
1889 if (*str>='0' && *str<='9') *d = 10*(*d)+(*str++-'0');
1890 s = skip_comment(str);
1891 if (s == str) return NULL;
1894 for (i = 0; i<3; ++i) if ((month[i]=tolower(*(str+i))) == '\0') return NULL;
1896 for (i = 0; i<12; ++i) if (Ustrcmp(month,month_name[i]) == 0) break;
1897 if (i == 12) return NULL;
1900 s = skip_comment(str);
1901 if (s == str) return NULL;
1904 if ((n = parse_number(str,y,4)))
1907 if (*y<1900) return NULL;
1910 else if ((n = parse_number(str,y,2)))
1912 str = skip_comment(n);
1913 while (*(str-1) == ' ' || *(str-1) == '\t') --str; /* match last FWS later */
1921 /*************************************************
1922 * Parse a RFC 2822 Time *
1923 *************************************************/
1925 /* Parse the time part of a RFC 2822 date-time, extracting the
1926 hour, minute, second and timezone.
1929 str pointer to the start of the time
1930 h pointer to the resulting hour
1931 m pointer to the resulting minute
1932 s pointer to the resulting second
1933 z pointer to the resulting timezone (offset in seconds)
1935 Returns: points after the processed time or NULL on error
1938 static const uschar *
1939 parse_time(const uschar *str, int *h, int *m, int *s, int *z)
1942 time = time-of-day FWS zone
1944 time-of-day = hour ":" minute [ ":" second ]
1946 hour = 2DIGIT / obs-hour
1948 obs-hour = [CFWS] 2DIGIT [CFWS]
1950 minute = 2DIGIT / obs-minute
1952 obs-minute = [CFWS] 2DIGIT [CFWS]
1954 second = 2DIGIT / obs-second
1956 obs-second = [CFWS] 2DIGIT [CFWS]
1958 zone = (( "+" / "-" ) 4DIGIT) / obs-zone
1960 obs-zone = "UT" / "GMT" / ; Universal Time
1963 "EST" / "EDT" / ; Eastern: - 5/ - 4
1964 "CST" / "CDT" / ; Central: - 6/ - 5
1965 "MST" / "MDT" / ; Mountain: - 7/ - 6
1966 "PST" / "PDT" / ; Pacific: - 8/ - 7
1968 %d65-73 / ; Military zones - "A"
1969 %d75-90 / ; through "I" and "K"
1970 %d97-105 / ; through "Z", both
1971 %d107-122 ; upper and lower case
1976 str = skip_comment(str);
1977 if ((str = parse_number(str,h,2)) == NULL) return NULL;
1978 str = skip_comment(str);
1979 if (*str!=':') return NULL;
1981 str = skip_comment(str);
1982 if ((str = parse_number(str,m,2)) == NULL) return NULL;
1983 c = skip_comment(str);
1987 str = skip_comment(str);
1988 if ((str = parse_number(str,s,2)) == NULL) return NULL;
1989 c = skip_comment(str);
1991 if (c == str) return NULL;
1993 if (*str == '+' || *str == '-')
1997 neg = (*str == '-');
1999 if ((str = parse_number(str,z,4)) == NULL) return NULL;
2000 *z = (*z/100)*3600+(*z%100)*60;
2006 struct { const char *name; int off; } zone_name[10] =
2007 { {"gmt",0}, {"ut",0}, {"est",-5}, {"edt",-4}, {"cst",-6}, {"cdt",-5}, {"mst",-7}, {"mdt",-6}, {"pst",-8}, {"pdt",-7}};
2010 for (i = 0; i<4; ++i)
2012 zone[i] = tolower(*(str+i));
2013 if (zone[i]<'a' || zone[i]>'z') break;
2016 for (j = 0; j<10 && strcmp(zone,zone_name[j].name); ++j);
2017 /* Besides zones named in the grammar, RFC 2822 says other alphabetic */
2018 /* time zones should be treated as unknown offsets. */
2021 *z = zone_name[j].off*3600;
2024 else if (zone[0]<'a' || zone[1]>'z') return 0;
2027 while ((*str>='a' && *str<='z') || (*str>='A' && *str<='Z')) ++str;
2035 /*************************************************
2036 * Parse a RFC 2822 date-time *
2037 *************************************************/
2039 /* Parse a RFC 2822 date-time and return it in seconds since the epoch.
2042 str pointer to the start of the date-time
2043 t pointer to the parsed time
2045 Returns: points after the processed date-time or NULL on error
2049 parse_date_time(const uschar *str, time_t *t)
2052 date-time = [ day-of-week "," ] date FWS time [CFWS]
2057 extern char **environ;
2059 static char gmt0[]="TZ=GMT0";
2060 static char *gmt_env[]={ gmt0, (char*)0 };
2063 if ((try = parse_day_of_week(str)))
2066 if (*str!=',') return 0;
2069 if ((str = parse_date(str,&tm.tm_mday,&tm.tm_mon,&tm.tm_year)) == NULL) return NULL;
2070 if (*str!=' ' && *str!='\t') return NULL;
2071 while (*str == ' ' || *str == '\t') ++str;
2072 if ((str = parse_time(str,&tm.tm_hour,&tm.tm_min,&tm.tm_sec,&zone)) == NULL) return NULL;
2074 old_environ = environ;
2077 environ = old_environ;
2078 if (*t == -1) return NULL;
2080 return skip_comment(str);
2086 /*************************************************
2087 **************************************************
2088 * Stand-alone test program *
2089 **************************************************
2090 *************************************************/
2092 #if defined STAND_ALONE
2095 int start, end, domain;
2096 uschar buffer[1024];
2099 big_buffer = store_malloc(big_buffer_size);
2101 /* strip_trailing_dot = TRUE; */
2102 allow_domain_literals = TRUE;
2104 printf("Testing parse_fix_phrase\n");
2106 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
2108 buffer[Ustrlen(buffer)-1] = 0;
2109 if (buffer[0] == 0) break;
2110 printf("%s\n", CS parse_fix_phrase(buffer, Ustrlen(buffer)));
2113 printf("Testing parse_extract_address without group syntax and without UTF-8\n");
2115 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
2119 buffer[Ustrlen(buffer) - 1] = 0;
2120 if (buffer[0] == 0) break;
2121 out = parse_extract_address(buffer, &errmess, &start, &end, &domain, FALSE);
2123 printf("*** bad address: %s\n", errmess);
2126 uschar extract[1024];
2127 Ustrncpy(extract, buffer+start, end-start);
2128 extract[end-start] = 0;
2129 printf("%s %d %d %d \"%s\"\n", out, start, end, domain, extract);
2133 printf("Testing parse_extract_address without group syntax but with UTF-8\n");
2135 allow_utf8_domains = TRUE;
2136 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
2140 buffer[Ustrlen(buffer) - 1] = 0;
2141 if (buffer[0] == 0) break;
2142 out = parse_extract_address(buffer, &errmess, &start, &end, &domain, FALSE);
2144 printf("*** bad address: %s\n", errmess);
2147 uschar extract[1024];
2148 Ustrncpy(extract, buffer+start, end-start);
2149 extract[end-start] = 0;
2150 printf("%s %d %d %d \"%s\"\n", out, start, end, domain, extract);
2153 allow_utf8_domains = FALSE;
2155 printf("Testing parse_extract_address with group syntax\n");
2157 f.parse_allow_group = TRUE;
2158 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
2163 buffer[Ustrlen(buffer) - 1] = 0;
2164 if (buffer[0] == 0) break;
2168 uschar *ss = parse_find_address_end(s, FALSE);
2169 int terminator = *ss;
2171 out = parse_extract_address(buffer, &errmess, &start, &end, &domain, FALSE);
2175 printf("*** bad address: %s\n", errmess);
2178 uschar extract[1024];
2179 Ustrncpy(extract, buffer+start, end-start);
2180 extract[end-start] = 0;
2181 printf("%s %d %d %d \"%s\"\n", out, start, end, domain, extract);
2184 s = ss + (terminator? 1:0);
2185 Uskip_whitespace(&s);
2189 printf("Testing parse_find_at\n");
2191 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
2194 buffer[Ustrlen(buffer)-1] = 0;
2195 if (buffer[0] == 0) break;
2196 s = parse_find_at(buffer);
2197 if (s == NULL) printf("no @ found\n");
2198 else printf("offset = %d\n", s - buffer);
2201 printf("Testing parse_extract_addresses\n");
2203 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
2207 address_item *anchor = NULL;
2208 buffer[Ustrlen(buffer) - 1] = 0;
2209 if (buffer[0] == 0) break;
2210 if ((extracted = parse_forward_list(buffer, -1, &anchor,
2211 &errmess, US"incoming.domain", NULL, NULL)) == FF_DELIVERED)
2213 while (anchor != NULL)
2215 address_item *addr = anchor;
2216 anchor = anchor->next;
2217 printf("%d %s\n", testflag(addr, af_pfr), addr->address);
2220 else printf("Failed: %d %s\n", extracted, errmess);
2223 printf("Testing parse_message_id\n");
2225 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
2227 uschar *s, *t, *errmess;
2228 buffer[Ustrlen(buffer) - 1] = 0;
2229 if (buffer[0] == 0) break;
2233 s = parse_message_id(s, &t, &errmess);
2234 if (errmess != NULL)
2236 printf("Failed: %s\n", errmess);
2248 /* End of parse.c */