Testsuite: munge for non-WITH_CONTENT_SCAN builds
[exim.git] / src / src / parse.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
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 */
9
10 /* Functions for parsing addresses */
11
12
13 #include "exim.h"
14
15
16 static const uschar *last_comment_position;
17
18
19
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. */
23
24 #ifdef STAND_ALONE
25
26 address_item *
27 deliver_make_addr(uschar *address, BOOL copy)
28 {
29 address_item *addr = store_get(sizeof(address_item), GET_UNTAINTED);
30 addr->next = NULL;
31 addr->parent = NULL;
32 addr->address = address;
33 return addr;
34 }
35
36 uschar *
37 rewrite_address(uschar *recipient, BOOL dummy1, BOOL dummy2, rewrite_rule
38   *dummy3, int dummy4)
39 {
40 return recipient;
41 }
42
43 uschar *
44 rewrite_address_qualify(uschar *recipient, BOOL dummy1)
45 {
46 return recipient;
47 }
48
49 #endif
50
51
52
53
54 /*************************************************
55 *             Find the end of an address         *
56 *************************************************/
57
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.
62
63 Argument:
64   s        pointer to the start of an address
65   nl_ends  if TRUE, '\n' terminates an address
66
67 Returns:   pointer past the end of the address
68            (i.e. points to null or comma)
69 */
70
71 uschar *
72 parse_find_address_end(const uschar * s, BOOL nl_ends)
73 {
74 BOOL source_routing = *s == '@';
75 int no_term = source_routing ? 1 : 0;
76
77 while (*s && (*s != ',' || no_term > 0) && (*s != '\n' || !nl_ends))
78   {
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? */
82
83   if (*s == '\\' && s[1])
84     s += 2;
85
86   /* Skip quoted items that are not inside brackets. Note that
87   quoted pairs are allowed inside quoted strings. */
88
89   else if (*s == '\"')
90     while (*++s && (*s != '\n' || !nl_ends))
91       {
92       if (*s == '\\' && s[1])
93         s++;
94       else if (*s == '\"')
95         { s++; break; }
96       }
97
98   /* Skip comments, which may include nested brackets, but quotes
99   are not recognized inside comments, though quoted pairs are. */
100
101   else if (*s == '(')
102     {
103     int level = 1;
104     while (*++s && (*s != '\n' || !nl_ends))
105       if (*s == '\\' && s[1])
106         s++;
107       else if (*s == '(')
108         level++;
109       else if (*s == ')' && --level <= 0)
110         { s++; break; }
111     }
112
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. */
116
117   else
118     {
119     if (*s == '<')
120       {
121       source_routing = s[1] == '@';
122       no_term = source_routing ? 2 : 1;
123       }
124     else if (*s == '>')
125       no_term--;
126     else if (source_routing && *s == ':')
127       no_term--;
128     s++;
129     }
130   }
131
132 return US s;
133 }
134
135
136
137 /*************************************************
138 *            Find last @ in an address           *
139 *************************************************/
140
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.
149
150 Argument:  pointer to an address, possibly unqualified
151 Returns:   pointer to the last @ in an address, or NULL if none
152 */
153
154 const uschar *
155 parse_find_at(const uschar *s)
156 {
157 const uschar * t = s + Ustrlen(s);
158 while (--t >= s)
159   if (*t == '@')
160     {
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;
165     }
166   else if (*t == '\"')
167     return NULL;
168
169 return NULL;
170 }
171
172
173
174
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   *
180 * on return.                                                               *
181 ***************************************************************************/
182
183
184 /*************************************************
185 *          Skip white space and comment          *
186 *************************************************/
187
188 /* Algorithm:
189   (1) Skip spaces.
190   (2) If uschar not '(', return.
191   (3) Skip till matching ')', not counting any characters
192       escaped with '\'.
193   (4) Move past ')' and goto (1).
194
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.
197
198 Argument: current character pointer
199 Returns:  new character pointer
200 */
201
202 static const uschar *
203 skip_comment(const uschar *s)
204 {
205 last_comment_position = s;
206 while (*s)
207   {
208   int c, level;
209
210   if (Uskip_whitespace(&s) != '(') break;
211   level = 1;
212   while((c = *(++s)))
213     {
214     if (c == '(') level++;
215     else if (c == ')') { if (--level <= 0) { s++; break; } }
216     else if (c == '\\' && s[1] != 0) s++;
217     }
218   }
219 return s;
220 }
221
222
223
224 /*************************************************
225 *             Read a domain                      *
226 *************************************************/
227
228 /* A domain is a sequence of subdomains, separated by dots. See comments below
229 for detailed syntax of the subdomains.
230
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.
234
235 Optionally, msg_id domain literals ( printable-ascii enclosed in [] )
236 are permitted.
237
238 Arguments:
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)
243
244 Returns:     new character pointer
245 */
246
247 static const uschar *
248 read_domain(const uschar *s, uschar *t, BOOL msg_id_literals, uschar **errorptr)
249 {
250 uschar *tt = t;
251 s = skip_comment(s);
252
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.
259
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
262 later. */
263
264 if (*s == '[')
265   {
266   *t++ = *s++;
267
268   if (strncmpic(s, US"IPv6:", 5) == 0 || strncmpic(s, US"IPv4:", 5) == 0)
269     {
270     memcpy(t, s, 5);
271     t += 5;
272     s += 5;
273     }
274
275   if (msg_id_literals)
276     while (*s >= 33 && *s <= 90 || *s >= 94 && *s <= 126) *t++ = *s++;
277   else
278     while (*s == '.' || *s == ':' || isxdigit(*s)) *t++ = *s++;
279
280   if (*s == ']') *t++ = *s++; else
281     {
282     *errorptr = US"malformed domain literal";
283     *tt = 0;
284     }
285
286   if (!allow_domain_literals && !msg_id_literals)
287     {
288     *errorptr = US"domain literals not allowed";
289     *tt = 0;
290     }
291   *t = 0;
292   return skip_comment(s);
293   }
294
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.
297
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
302 hyphen.
303
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.
312
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.
315
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. */
321
322 for (;;)
323   {
324   uschar *tsave = t;
325
326 /*********************
327   if (rfc821_domains)
328     {
329     if (*s != '-') while (isalnum(*s) || *s == '-') *t++ = *s++;
330     }
331   else
332     while (!mac_iscntrl_or_special(*s)) *t++ = *s++;
333 *********************/
334
335   if (*s != '-')
336     {
337     /* Only letters, digits, and hyphens */
338
339     if (!allow_utf8_domains)
340       {
341       while (isalnum(*s) || *s == '-') *t++ = *s++;
342       }
343
344     /* Permit legal UTF-8 characters to be included */
345
346     else for(;;)
347       {
348       int i, d;
349       if (isalnum(*s) || *s == '-')    /* legal ascii characters */
350         {
351         *t++ = *s++;
352         continue;
353         }
354       if ((*s & 0xc0) != 0xc0) break;  /* not start of UTF-8 character */
355       d = *s << 2;
356       for (i = 1; i < 6; i++)          /* i is the number of additional bytes */
357         {
358         if ((d & 0x80) == 0) break;
359         d <<= 1;
360         }
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 */
364         {
365         if ((*s & 0xc0) != 0x80)
366           {
367           BAD_UTF8:
368           *errorptr = US"invalid UTF-8 byte sequence";
369           *tt = 0;
370           return s;
371           }
372         *t++ = *s++;
373         }
374       }    /* End of loop for UTF-8 character */
375     }      /* End of subdomain */
376
377   s = skip_comment(s);
378   *t = 0;
379
380   if (t == tsave)   /* empty component */
381     {
382     if (strip_trailing_dot && t > tt && *s != '.') t[-1] = 0; else
383       {
384       *errorptr = US"domain missing or malformed";
385       *tt = 0;
386       }
387     return s;
388     }
389
390   if (*s != '.') break;
391   *t++ = *s++;
392   s = skip_comment(s);
393   }
394
395 return s;
396 }
397
398
399
400 /*************************************************
401 *            Read a local-part                   *
402 *************************************************/
403
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...
407
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.
415
416 Arguments:
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
421
422 Returns:   new character pointer
423 */
424
425 static const uschar *
426 read_local_part(const uschar *s, uschar *t, uschar **error, BOOL allow_null)
427 {
428 uschar *tt = t;
429 *error = NULL;
430 for (;;)
431   {
432   int c;
433   uschar *tsave = t;
434   s = skip_comment(s);
435
436   /* Handle a quoted string */
437
438   if (*s == '\"')
439     {
440     *t++ = '\"';
441     while ((c = *++s) && c != '\"')
442       {
443       *t++ = c;
444       if (c == '\\' && s[1]) *t++ = *++s;
445       }
446     if (c == '\"')
447       {
448       s++;
449       *t++ = '\"';
450       }
451     else
452       {
453       *error = US"unmatched doublequote in local part";
454       return s;
455       }
456     }
457
458   /* Handle an atom, but allow quoted pairs within it. */
459
460   else while (!mac_iscntrl_or_special(*s) || *s == '\\')
461     {
462     c = *t++ = *s++;
463     if (c == '\\' && *s) *t++ = *s++;
464     }
465
466   /* Terminate the word and skip subsequent comment */
467
468   *t = 0;
469   s = skip_comment(s);
470
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. */
475
476   if (t == tsave && *s != '.')
477     {
478     if (t == tt && !allow_null)
479       *error = US"missing or malformed local part";
480     return s;
481     }
482
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. */
485
486   if (*s != '.') break;
487   do { *t++ = *s++; } while (*s == '.');
488   }
489
490 return s;
491 }
492
493
494 /*************************************************
495 *            Read route part of route-addr       *
496 *************************************************/
497
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.
501
502 Arguments:
503   s          current character pointer
504   t          where to put the route
505   errorptr   where to put an error message
506
507 Returns:     new character pointer
508 */
509
510 static const uschar *
511 read_route(const uschar *s, uschar *t, uschar **errorptr)
512 {
513 BOOL commas = FALSE;
514 *errorptr = NULL;
515
516 while (*s == '@')
517   {
518   *t++ = '@';
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;
523   *t++ = *s++;
524   commas = TRUE;
525   s = skip_comment(s);
526   }
527
528 if (*s == ':') *t++ = *s++;
529
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
532 after the route. */
533
534 else *errorptr = commas?
535   US"colon expected after route list" :
536   US"no local part";
537
538 /* Terminate the route and return */
539
540 *t = 0;
541 return skip_comment(s);
542 }
543
544
545
546 /*************************************************
547 *                Read addr-spec                  *
548 *************************************************/
549
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.
553
554 Arguments:
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
560
561 Returns:     new character pointer
562 */
563
564 static const uschar *
565 read_addr_spec(const uschar *s, uschar *t, int term, uschar **errorptr,
566   uschar **domainptr)
567 {
568 s = read_local_part(s, t, errorptr, FALSE);
569 if (*errorptr == NULL)
570   if (*s != term)
571     if (*s != '@')
572       *errorptr = string_sprintf("\"@\" or \".\" expected after \"%s\"", t);
573     else
574       {
575       t += Ustrlen((const uschar *)t);
576       *t++ = *s++;
577       *domainptr = t;
578       s = read_domain(s, t, FALSE, errorptr);
579       }
580 return s;
581 }
582
583
584
585 /*************************************************
586 *         Extract operative address              *
587 *************************************************/
588
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 @.
598
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.
605
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.
613
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
619 addresses.
620
621 Arguments:
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
628
629 Returns:      points to the extracted address, or NULL on error
630 */
631
632 #define FAILED(s) { *errorptr = s; goto PARSE_FAILED; }
633
634 uschar *
635 parse_extract_address(const uschar *mailbox, uschar **errorptr, int *start, int *end,
636   int *domain, BOOL allow_null)
637 {
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;
642
643 *domain = 0;
644
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
651 allow this case. */
652
653 RESTART:   /* Come back here after passing a group name */
654
655 s = skip_comment(s);
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;
659
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). */
663
664 if (*s != '@' && *s != '<')
665   {
666   if (!*s || *s == ';')
667     {
668     if (!*t) FAILED(US"empty address");
669     endptr = last_comment_position;
670     goto PARSE_SUCCEEDED;              /* Bare local part */
671     }
672
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. */
677
678   while (*s != '<' && (!f.parse_allow_group || *s != ':'))
679     {
680     s = read_local_part(s, t, errorptr, FALSE);
681     if (*errorptr)
682       {
683       *errorptr = string_sprintf("%s (expected word or \"<\")", *errorptr);
684       goto PARSE_FAILED;
685       }
686     }
687
688   if (*s == ':')
689     {
690     f.parse_found_group = TRUE;
691     f.parse_allow_group = FALSE;
692     s++;
693     goto RESTART;
694     }
695
696   /* Assert *s == '<' */
697   }
698
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.
704
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. */
708
709 if (*s == '<')
710   {
711   uschar *domainptr = yield;
712   BOOL source_routed = FALSE;
713   int bracket_count = 1;
714
715   s++;
716   if (strip_excess_angle_brackets) while (*s == '<')
717    {
718    if(bracket_count++ > 5) FAILED(US"angle-brackets nested too deep");
719    s++;
720    }
721
722   t = yield;
723   startptr = s;
724   s = skip_comment(s);
725
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
729   SHOULD). */
730
731   if (*s == '@')
732     {
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;
737     }
738
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. */
743
744   if (allow_null && !source_routed && *s == '>')
745     {
746     *t = 0;
747     *errorptr = NULL;
748     }
749   else
750     {
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");
756     }
757
758   endptr = s;
759   if (*errorptr) goto PARSE_FAILED;
760   while (bracket_count-- > 0) if (*s++ != '>')
761     {
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);
766     goto PARSE_FAILED;
767     }
768
769   s = skip_comment(s);
770   }
771
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. */
777
778 else if (!*t)
779   {
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");
789   }
790
791 /* This is the strict case of local-part@domain. */
792
793 else
794   {
795   t += Ustrlen((const uschar *)t);
796   *t++ = *s++;
797   *domain = t - yield;
798   s = read_domain(s, t, TRUE, errorptr);
799   if (!*t) goto PARSE_FAILED;
800   endptr = last_comment_position;
801   }
802
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. */
806
807 PARSE_SUCCEEDED:
808 if (*s)
809   {
810   if (f.parse_found_group && *s == ';')
811     {
812     f.parse_found_group = FALSE;
813     f.parse_allow_group = TRUE;
814     }
815   else
816     {
817     *errorptr = string_sprintf("malformed address: %.32s may not follow %.*s",
818       s, (int)(s - US mailbox), mailbox);
819     goto PARSE_FAILED;
820     }
821   }
822 *start = startptr - US mailbox;      /* Return offsets */
823 while (isspace(endptr[-1])) endptr--;
824 *end = endptr - US mailbox;
825
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. */
830
831 if (*end - *start > EXIM_EMAILADDR_MAX)
832   {
833   *errorptr = string_sprintf("address is ridiculously long: %.64s...", yield);
834   return NULL;
835   }
836
837 return yield;
838
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. */
842
843 PARSE_FAILED:
844 if (f.parse_found_group && *s == ';')
845   {
846   f.parse_found_group = FALSE;
847   f.parse_allow_group = TRUE;
848   }
849 return NULL;
850 }
851
852 #undef FAILED
853
854
855
856 /*************************************************
857 *        Quote according to RFC 2047             *
858 *************************************************/
859
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.
863
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.
868
869 Arguments:
870   string       the string to quote - already checked to contain non-printing
871                  chars
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
876
877 Returns:       pointer to the original string, if no quoting needed, or
878                pointer to allocated memory containing the quoted string
879 */
880
881 const uschar *
882 parse_quote_2047(const uschar * string, int len, const uschar * charset,
883   BOOL fold)
884 {
885 const uschar * s = string;
886 int hlen, line_off;
887 BOOL coded = FALSE;
888 BOOL first_byte = FALSE;
889 gstring * g =
890   string_fmt_append(NULL, "=?%s?Q?%n", charset ? charset : US"iso-8859-1", &hlen);
891
892 line_off = hlen;
893
894 for (s = string; len > 0; s++, len--)
895   {
896   int ch = *s;
897
898   if (g->ptr - line_off > 67 && !first_byte)
899     {
900     g = fold ? string_catn(g, US"?=\n ", 4) : string_catn(g, US"?= ", 3);
901     line_off = g->ptr;
902     g = string_catn(g, g->s, hlen);
903     }
904
905   if (  ch < 33 || ch > 126
906      || Ustrchr("?=()<>@,;:\\\".[]_", ch) != NULL)
907     {
908     if (ch == ' ')
909       {
910       g = string_catn(g, US"_", 1);
911       first_byte = FALSE;
912       }
913     else
914       {
915       g = string_fmt_append(g, "=%02X", ch);
916       coded = TRUE;
917       first_byte = !first_byte;
918       }
919     }
920   else
921     { g = string_catn(g, s, 1); first_byte = FALSE; }
922   }
923
924 if (coded)
925   string = string_from_gstring(g = string_catn(g, US"?=", 2));
926 else
927   g->ptr = -1;
928
929 gstring_release_unused(g);
930 return string;
931 }
932
933
934
935
936 /*************************************************
937 *            Fix up an RFC 822 "phrase"          *
938 *************************************************/
939
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
943 -F option.
944
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
949
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
955 but
956    John (\"Jack\") Q. Smith =>  "John (\"Jack\") Q. Smith"
957
958 Sheesh! This is tedious code. It is a great pity that the syntax of RFC822 is
959 the way it is...
960
961 August 2000: Additional code added:
962
963   Previously, non-printing characters were turned into question marks, which do
964   not need to be quoted.
965
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
968   the character set.
969
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".
972
973 The result is passed back in allocated memory.
974
975 Arguments:
976   phrase       an RFC822 phrase
977   len          the length of the phrase
978
979 Returns:       the fixed RFC822 phrase
980 */
981
982 const uschar *
983 parse_fix_phrase(const uschar *phrase, int len)
984 {
985 int ch, i;
986 BOOL quoted = FALSE;
987 const uschar *s, *end;
988 uschar * buffer;
989 uschar *t, *yield;
990
991 while (len > 0 && isspace(*phrase)) { phrase++; len--; }
992
993 /* See if there are any non-printing characters, and if so, use the RFC 2047
994 encoding for the whole thing. */
995
996 for (i = 0, s = phrase; i < len; i++, s++)
997   if ((*s < 32 && *s != '\t') || *s > 126) break;
998
999 if (i < len)
1000   return parse_quote_2047(phrase, len, headers_charset, FALSE);
1001
1002 /* No non-printers; use the RFC 822 quoting rules */
1003
1004 if (len <= 0 || len >= INT_MAX/4)
1005   return string_copy_taint(CUS"", phrase);
1006
1007 buffer = store_get((len+1)*4, phrase);
1008
1009 s = phrase;
1010 end = s + len;
1011 yield = t = buffer + 1;
1012
1013 while (s < end)
1014   {
1015   ch = *s++;
1016
1017   /* Copy over quoted strings, remembering we encountered one */
1018
1019   if (ch == '\"')
1020     {
1021     *t++ = '\"';
1022     while (s < end && (ch = *s++) != '\"')
1023       {
1024       *t++ = ch;
1025       if (ch == '\\' && s < end) *t++ = *s++;
1026       }
1027     *t++ = '\"';
1028     if (s >= end) break;
1029     quoted = TRUE;
1030     }
1031
1032   /* Copy over comments, noting if they contain freestanding quote
1033   characters */
1034
1035   else if (ch == '(')
1036     {
1037     int level = 1;
1038     *t++ = '(';
1039     while (s < end)
1040       {
1041       ch = *s++;
1042       *t++ = ch;
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;
1047       }
1048     if (ch == 0)
1049       {
1050       while (level--) *t++ = ')';
1051       break;
1052       }
1053     }
1054
1055   /* Handle special characters that need to be quoted */
1056
1057   else if (Ustrchr(")<>@,;:\\.[]", ch) != NULL)
1058     {
1059     /* If hit previous quotes just make one quoted "word" */
1060
1061     if (quoted)
1062       {
1063       uschar *tt = t++;
1064       while (*(--tt) != ' ' && *tt != '\"' && *tt != ')') tt[1] = *tt;
1065       tt[1] = '\"';
1066       *t++ = ch;
1067       while (s < end)
1068         {
1069         ch = *s++;
1070         if (ch == ' ' || ch == '\"') { s--; break; } else *t++ = ch;
1071         }
1072       *t++ = '\"';
1073       }
1074
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. */
1077
1078     else
1079       {
1080       BOOL escaped = (ch == '\\');
1081       *(--yield) = '\"';
1082       *t++ = ch;
1083
1084       /* Now look for the end or a quote */
1085
1086       while (s < end)
1087         {
1088         ch = *s++;
1089
1090         /* Handle escaped pairs */
1091
1092         if (escaped)
1093           {
1094           *t++ = ch;
1095           escaped = FALSE;
1096           }
1097
1098         else if (ch == '\\')
1099           {
1100           *t++ = ch;
1101           escaped = TRUE;
1102           }
1103
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. */
1106
1107         else if (ch == '\"')
1108           {
1109           int count = 0;
1110           while (t[-1] == ' ') { t--; count++; }
1111           *t++ = '\"';
1112           while (count-- > 0) *t++ = ' ';
1113           s--;
1114           break;
1115           }
1116
1117         /* If hit a subsequent comment, check it for unescaped quotes,
1118         and if so, end our quote before it. */
1119
1120         else if (ch == '(')
1121           {
1122           const uschar *ss = s;     /* uschar after '(' */
1123           int level = 1;
1124           while(ss < end)
1125             {
1126             ch = *ss++;
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; }
1131             }
1132
1133           /* Comment contains unescaped quotes; end our quote before
1134           the start of the comment. */
1135
1136           if (quoted)
1137             {
1138             int count = 0;
1139             while (t[-1] == ' ') { t--; count++; }
1140             *t++ = '\"';
1141             while (count-- > 0) *t++ = ' ';
1142             break;
1143             }
1144
1145           /* Comment does not contain unescaped quotes; include it in
1146           our quote. */
1147
1148           else
1149             {
1150             if (ss >= end) ss--;
1151             *t++ = '(';
1152             if (ss > s)
1153               {
1154               Ustrncpy(t, s, ss-s);
1155               t += ss-s;
1156               s = ss;
1157               }
1158             }
1159           }
1160
1161         /* Not a comment or quote; include this character in our quotes. */
1162
1163         else *t++ = ch;
1164         }
1165       }
1166
1167     /* Add a final quote if we hit the end of the string. */
1168
1169     if (s >= end) *t++ = '\"';
1170     }
1171
1172   /* Non-special character; just copy it over */
1173
1174   else *t++ = ch;
1175   }
1176
1177 *t = 0;
1178 store_release_above(t+1);
1179 return yield;
1180 }
1181
1182
1183 /*************************************************
1184 *          Extract addresses from a list         *
1185 *************************************************/
1186
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.
1191
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.
1195
1196 If a # character is encountered in a white space position, then characters from
1197 there to the next newline are skipped.
1198
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
1202 route_address().
1203
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.
1210
1211 An "address" can also be of the form :include:pathname to include a list of
1212 addresses contained in the specified file.
1213
1214 Any unqualified addresses are qualified with and rewritten if necessary, via
1215 the rewrite_address() function.
1216
1217 Arguments:
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:
1223                        RDO_DEFER
1224                        RDO_FREEZE
1225                        RDO_FAIL
1226                        RDO_BLACKHOLE
1227                        RDO_REWRITE
1228                        RDO_INCLUDE
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
1236                      directory
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
1239                      here.
1240
1241 Returns:      FF_DELIVERED      addresses extracted
1242               FF_NOTDELIVERED   no addresses extracted, but no errors
1243               FF_BLACKHOLE      :blackhole:
1244               FF_DEFER          :defer:
1245               FF_FAIL           :fail:
1246               FF_INCLUDEFAIL    some problem with :include:; *error set
1247               FF_ERROR          other problems; *error is set
1248 */
1249
1250 int
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)
1254 {
1255 int count = 0;
1256
1257 DEBUG(D_route) debug_printf("parse_forward_list: %s\n", s);
1258
1259 for (;;)
1260   {
1261   int len, special = 0, specopt = 0, specbit = 0;
1262   const uschar * ss, * nexts;
1263   address_item * addr;
1264   BOOL inquote = FALSE;
1265
1266   for (;;)
1267     {
1268     while (isspace(*s) || *s == ',') s++;
1269     if (*s == '#') { while (*s && *s != '\n') s++; } else break;
1270     }
1271
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. */
1280
1281   if (!*s)
1282     {
1283     return (count > 0 || (syntax_errors && *syntax_errors))
1284       ?  FF_DELIVERED : FF_NOTDELIVERED;
1285
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. */
1289
1290 #ifdef NEVER
1291     if (count > 0) return FF_DELIVERED;   /* Something was generated */
1292
1293     if (!syntax_errors ||          /* Not skipping syntax errors, or */
1294        !*syntax_errors)            /*   we didn't actually skip any */
1295       return FF_NOTDELIVERED;
1296
1297     *error = string_sprintf("no addresses generated: syntax error in %s: %s",
1298        (*syntax_errors)->text2, (*syntax_errors)->text1);
1299     return FF_ERROR;
1300 #endif
1301     }
1302
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. */
1308
1309   ss = parse_find_address_end(s, TRUE);
1310
1311   /* Remember where we finished, for starting the next one. */
1312
1313   nexts = ss;
1314
1315   /* Remove any trailing spaces; we know there's at least one non-space. */
1316
1317   while (isspace(ss[-1])) ss--;
1318
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. */
1323
1324   if (*s == '\"' && ss[-1] == '\"')
1325     {
1326     s++;
1327     ss--;
1328     inquote = TRUE;
1329     while (s < ss && isspace(*s)) s++;
1330     while (ss > s && isspace(ss[-1])) ss--;
1331     }
1332
1333   /* Set up the length of the address. */
1334
1335   len = ss - s;
1336
1337   DEBUG(D_route) debug_printf("extract item: %.*s\n", len, s);
1338
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
1343   away. */
1344
1345   if (Ustrncmp(s, ":unknown:", len) == 0)
1346     {
1347     s = nexts;
1348     continue;
1349     }
1350
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 */
1357
1358   if (special)
1359     {
1360     uschar * ss = Ustrchr(s+1, ':') + 1; /* line after the special... */
1361     if ((options & specopt) == specbit)
1362       {
1363       *error = string_sprintf("\"%.*s\" is not permitted", len, s);
1364       return FF_ERROR;
1365       }
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 */
1370     return special;
1371     }
1372
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. */
1377
1378   if (Ustrncmp(s, ":include:", 9) == 0)
1379     {
1380     uschar * filebuf;
1381     uschar filename[256];
1382     const uschar * t = s+9;
1383     int flen = len - 9;
1384     int frc;
1385     struct stat statbuf;
1386     address_item * last;
1387     FILE * f;
1388
1389     while (flen > 0 && isspace(*t)) { t++; flen--; }
1390
1391     if (flen <= 0)
1392       {
1393       *error = US"file name missing after :include:";
1394       return FF_ERROR;
1395       }
1396
1397     if (flen > sizeof(filename)-1)
1398       {
1399       *error = string_sprintf("included file name \"%s\" is too long", t);
1400       return FF_ERROR;
1401       }
1402
1403     Ustrncpy(filename, t, flen);
1404     filename[flen] = 0;
1405
1406     /* Insist on absolute path */
1407
1408     if (filename[0] != '/')
1409       {
1410       *error = string_sprintf("included file \"%s\" is not an absolute path",
1411         filename);
1412       return FF_ERROR;
1413       }
1414
1415     /* Check if include is permitted */
1416
1417     if (options & RDO_INCLUDE)
1418       {
1419       *error = US"included files not permitted";
1420       return FF_ERROR;
1421       }
1422
1423     if (is_tainted(filename))
1424       {
1425       *error = string_sprintf("Tainted name '%s' for included file  not permitted\n",
1426        filename);
1427       return FF_ERROR;
1428       }
1429
1430     /* Check file name if required */
1431
1432     if (directory)
1433       {
1434       int len = Ustrlen(directory);
1435       uschar * p;
1436
1437       while (len > 0 && directory[len-1] == '/') len--;         /* ignore trailing '/' */
1438       p = filename + len;
1439       if (Ustrncmp(filename, directory, len) != 0 || *p != '/')
1440         {
1441         *error = string_sprintf("included file %s is not in directory %s",
1442           filename, directory);
1443         return FF_ERROR;
1444         }
1445
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. */
1451
1452       {
1453       int fd = exim_open2(CCS directory, O_RDONLY);
1454       if (fd < 0)
1455         {
1456         *error = string_sprintf("failed to open directory %s", directory);
1457         return FF_ERROR;
1458         }
1459       while (*p)
1460         {
1461         uschar temp;
1462         int fd2;
1463         uschar * q = p + 1;             /* skip dividing '/' */
1464
1465         while (*q == '/') q++;          /* skip extra '/' */
1466         while (*++p && *p != '/') ;     /* end of component */
1467         temp = *p;
1468         *p = '\0';
1469
1470         fd2 = exim_openat(fd, CS q, O_RDONLY|O_NOFOLLOW);
1471         close(fd);
1472         *p = temp;
1473         if (fd2 < 0)
1474           {
1475           *error = string_sprintf("failed to open %s (component of included "
1476             "file); could be symbolic link", filename);
1477           return FF_ERROR;
1478           }
1479         fd = fd2;
1480         }
1481       f = fdopen(fd, "rb");
1482       }
1483 #else
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
1488       any better. */
1489
1490       while (*p)
1491         {
1492         int temp;
1493         while (*++p && *p != '/');
1494         temp = *p;
1495         *p = 0;
1496         if (Ulstat(filename, &statbuf) != 0)
1497           {
1498           *error = string_sprintf("failed to stat %s (component of included "
1499             "file)", filename);
1500           *p = temp;
1501           return FF_ERROR;
1502           }
1503
1504         *p = temp;
1505
1506         if ((statbuf.st_mode & S_IFMT) == S_IFLNK)
1507           {
1508           *error = string_sprintf("included file %s in the %s directory "
1509             "involves a symbolic link", filename, directory);
1510           return FF_ERROR;
1511           }
1512         }
1513 #endif
1514       }
1515
1516 #ifdef EXIM_HAVE_OPENAT
1517     else
1518 #endif
1519       /* Open and stat the file */
1520       f = Ufopen(filename, "rb");
1521
1522     if (!f)
1523       {
1524       *error = string_open_failed("included file %s", filename);
1525       return FF_INCLUDEFAIL;
1526       }
1527
1528     if (fstat(fileno(f), &statbuf) != 0)
1529       {
1530       *error = string_sprintf("failed to stat included file %s: %s",
1531         filename, strerror(errno));
1532       (void)fclose(f);
1533       return FF_INCLUDEFAIL;
1534       }
1535
1536     /* If directory was checked, double check that we opened a regular file */
1537
1538     if (directory && (statbuf.st_mode & S_IFMT) != S_IFREG)
1539       {
1540       *error = string_sprintf("included file %s is not a regular file in "
1541         "the %s directory", filename, directory);
1542       return FF_ERROR;
1543       }
1544
1545     /* Get a buffer and read the contents */
1546
1547     if (statbuf.st_size > MAX_INCLUDE_SIZE)
1548       {
1549       *error = string_sprintf("included file %s is too big (max %d)",
1550         filename, MAX_INCLUDE_SIZE);
1551       return FF_ERROR;
1552       }
1553
1554     filebuf = store_get(statbuf.st_size + 1, filename);
1555     if (fread(filebuf, 1, statbuf.st_size, f) != statbuf.st_size)
1556       {
1557       *error = string_sprintf("error while reading included file %s: %s",
1558         filename, strerror(errno));
1559       (void)fclose(f);
1560       return FF_ERROR;
1561       }
1562     filebuf[statbuf.st_size] = 0;
1563     (void)fclose(f);
1564
1565     addr = NULL;
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;
1569
1570     if (addr)
1571       {
1572       for (last = addr; last->next; last = last->next) count++;
1573       last->next = *anchor;
1574       *anchor = addr;
1575       count++;
1576       }
1577     }
1578
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.
1585
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
1589
1590      /X=xxx/Y=xxx/OU=xxx/@some.gate.way
1591
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. */
1597
1598   else
1599     {
1600     int start, end, domain;
1601     const uschar *recipient = NULL;
1602     uschar * s_ltd = string_copyn(s, len);
1603
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. */
1608
1609     if (*s_ltd == '\\')
1610       {
1611       recipient =
1612         parse_extract_address(s_ltd+1, error, &start, &end, &domain, FALSE);
1613       if (recipient)
1614         recipient = domain != 0 ? NULL :
1615           string_sprintf("%s@%s", recipient, incoming_domain);
1616       }
1617
1618     /* Try parsing the item as an address. */
1619
1620     if (!recipient) recipient =
1621       parse_extract_address(s_ltd, error, &start, &end, &domain, FALSE);
1622
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. */
1626
1627     if ((*s_ltd == '|' || *s_ltd == '/') && (!recipient || domain == 0))
1628       {
1629       uschar * t = store_get(Ustrlen(s_ltd) + 1, s_ltd);
1630       uschar * p = t, * q = s_ltd;
1631
1632       while (*q)
1633         {
1634         if (inquote)
1635           {
1636           *p++ = *q == '\\' ? *++q : *q;
1637           q++;
1638           }
1639         else *p++ = *q++;
1640         }
1641       *p = 0;
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 */
1645       }
1646
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. */
1653
1654     else
1655       {
1656       if (!recipient)
1657         {
1658         if (Ustrcmp(*error, "empty address") == 0)
1659           {
1660           *error = NULL;
1661           s = nexts;
1662           continue;
1663           }
1664
1665         if (syntax_errors)
1666           {
1667           error_block * e = store_get(sizeof(error_block), GET_UNTAINTED);
1668           error_block * last = *syntax_errors;
1669           if (last)
1670             {
1671             while (last->next) last = last->next;
1672             last->next = e;
1673             }
1674           else
1675             *syntax_errors = e;
1676           e->next = NULL;
1677           e->text1 = *error;
1678           e->text2 = s_ltd;
1679           s = nexts;
1680           continue;
1681           }
1682         else
1683           {
1684           *error = string_sprintf("%s in \"%s\"", *error, s_ltd);
1685           return FF_ERROR;
1686           }
1687         }
1688
1689       /* Address was successfully parsed. Rewrite, and then make an address
1690       block. */
1691
1692       recipient = options & RDO_REWRITE
1693         ? rewrite_address(recipient, TRUE, FALSE, global_rewrite_rules,
1694                           rewrite_existflags)
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 */
1697       }
1698
1699     /* Add the original data to the output chain. */
1700
1701     addr->next = *anchor;
1702     *anchor = addr;
1703     count++;
1704     }
1705
1706   /* Advance pointer for the next address */
1707
1708   s = nexts;
1709   }
1710 }
1711
1712
1713 /*************************************************
1714 *            Extract a Message-ID                *
1715 *************************************************/
1716
1717 /* This function is used to extract message ids from In-Reply-To: and
1718 References: header lines.
1719
1720 Arguments:
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
1724
1725 Returns:       points after the processed message-id or NULL on error
1726 */
1727
1728 const uschar *
1729 parse_message_id(const uschar *str, uschar **yield, uschar **error)
1730 {
1731 uschar *domain = NULL;
1732 uschar *id;
1733 rmark reset_point;
1734
1735 str = skip_comment(str);
1736 if (*str != '<')
1737   {
1738   *error = US"Missing '<' before message-id";
1739   return NULL;
1740   }
1741
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. */
1745
1746 reset_point = store_mark();
1747 id = *yield = store_get(Ustrlen(str) + 1, str);
1748 *id++ = *str++;
1749
1750 str = read_addr_spec(str, id, '>', error, &domain);
1751
1752 if (!*error)
1753   {
1754   if (*str != '>') *error = US"Missing '>' after message-id";
1755     else if (domain == NULL) *error = US"domain missing in message-id";
1756   }
1757
1758 if (*error)
1759   {
1760   store_reset(reset_point);
1761   return NULL;
1762   }
1763
1764 while (*id) id++;
1765 *id++ = *str++;
1766 *id++ = 0;
1767 store_release_above(id);
1768
1769 return skip_comment(str);
1770 }
1771
1772
1773 /*************************************************
1774 *        Parse a fixed digit number              *
1775 *************************************************/
1776
1777 /* Parse a string containing an ASCII encoded fixed digits number
1778
1779 Arguments:
1780   str          pointer to the start of the ASCII encoded number
1781   n            pointer to the resulting value
1782   digits       number of required digits
1783
1784 Returns:       points after the processed date or NULL on error
1785 */
1786
1787 static const uschar *
1788 parse_number(const uschar *str, int *n, int digits)
1789 {
1790 *n=0;
1791 while (digits--)
1792   {
1793   if (*str<'0' || *str>'9') return NULL;
1794   *n=10*(*n)+(*str++-'0');
1795   }
1796 return str;
1797 }
1798
1799
1800 /*************************************************
1801 *        Parse a RFC 2822 day of week            *
1802 *************************************************/
1803
1804 /* Parse the day of the week from a RFC 2822 date, but do not
1805    decode it, because it is only for humans.
1806
1807 Arguments:
1808   str          pointer to the start of the day of the week
1809
1810 Returns:       points after the parsed day or NULL on error
1811 */
1812
1813 static const uschar *
1814 parse_day_of_week(const uschar * str)
1815 {
1816 /*
1817 day-of-week     =       ([FWS] day-name) / obs-day-of-week
1818
1819 day-name        =       "Mon" / "Tue" / "Wed" / "Thu" /
1820                         "Fri" / "Sat" / "Sun"
1821
1822 obs-day-of-week =       [CFWS] day-name [CFWS]
1823 */
1824
1825 static const uschar *day_name[7]={ US"mon", US"tue", US"wed", US"thu", US"fri", US"sat", US"sun" };
1826 int i;
1827 uschar day[4];
1828
1829 str = skip_comment(str);
1830 for (i = 0; i < 3; ++i)
1831   {
1832   if ((day[i] = tolower(*str)) == '\0') return NULL;
1833   ++str;
1834   }
1835 day[3] = '\0';
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);
1839 }
1840
1841
1842 /*************************************************
1843 *            Parse a RFC 2822 date               *
1844 *************************************************/
1845
1846 /* Parse the date part of a RFC 2822 date-time, extracting the
1847    day, month and year.
1848
1849 Arguments:
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
1854
1855 Returns:       points after the processed date or NULL on error
1856 */
1857
1858 static const uschar *
1859 parse_date(const uschar *str, int *d, int *m, int *y)
1860 {
1861 /*
1862 date            =       day month year
1863
1864 year            =       4*DIGIT / obs-year
1865
1866 obs-year        =       [CFWS] 2*DIGIT [CFWS]
1867
1868 month           =       (FWS month-name FWS) / obs-month
1869
1870 month-name      =       "Jan" / "Feb" / "Mar" / "Apr" /
1871                         "May" / "Jun" / "Jul" / "Aug" /
1872                         "Sep" / "Oct" / "Nov" / "Dec"
1873
1874 obs-month       =       CFWS month-name CFWS
1875
1876 day             =       ([FWS] 1*2DIGIT) / obs-day
1877
1878 obs-day         =       [CFWS] 1*2DIGIT [CFWS]
1879 */
1880
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" };
1883 int i;
1884 uschar month[4];
1885
1886 str = skip_comment(str);
1887 if ((str = parse_number(str,d,1)) == NULL) return NULL;
1888
1889 if (*str>='0' && *str<='9') *d = 10*(*d)+(*str++-'0');
1890 s = skip_comment(str);
1891 if (s == str) return NULL;
1892 str = s;
1893
1894 for (i = 0; i<3; ++i) if ((month[i]=tolower(*(str+i))) == '\0') return NULL;
1895 month[3] = '\0';
1896 for (i = 0; i<12; ++i) if (Ustrcmp(month,month_name[i]) == 0) break;
1897 if (i == 12) return NULL;
1898 str+=3;
1899 *m = i;
1900 s = skip_comment(str);
1901 if (s == str) return NULL;
1902 str=s;
1903
1904 if ((n = parse_number(str,y,4)))
1905   {
1906   str = n;
1907   if (*y<1900) return NULL;
1908   *y = *y-1900;
1909   }
1910 else if ((n = parse_number(str,y,2)))
1911   {
1912   str = skip_comment(n);
1913   while (*(str-1) == ' ' || *(str-1) == '\t') --str; /* match last FWS later */
1914   if (*y<50) *y+=100;
1915   }
1916 else return NULL;
1917 return str;
1918 }
1919
1920
1921 /*************************************************
1922 *            Parse a RFC 2822 Time               *
1923 *************************************************/
1924
1925 /* Parse the time part of a RFC 2822 date-time, extracting the
1926    hour, minute, second and timezone.
1927
1928 Arguments:
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)
1934
1935 Returns:       points after the processed time or NULL on error
1936 */
1937
1938 static const uschar *
1939 parse_time(const uschar *str, int *h, int *m, int *s, int *z)
1940 {
1941 /*
1942 time            =       time-of-day FWS zone
1943
1944 time-of-day     =       hour ":" minute [ ":" second ]
1945
1946 hour            =       2DIGIT / obs-hour
1947
1948 obs-hour        =       [CFWS] 2DIGIT [CFWS]
1949
1950 minute          =       2DIGIT / obs-minute
1951
1952 obs-minute      =       [CFWS] 2DIGIT [CFWS]
1953
1954 second          =       2DIGIT / obs-second
1955
1956 obs-second      =       [CFWS] 2DIGIT [CFWS]
1957
1958 zone            =       (( "+" / "-" ) 4DIGIT) / obs-zone
1959
1960 obs-zone        =       "UT" / "GMT" /          ; Universal Time
1961                                                 ; North American UT
1962                                                 ; offsets
1963                         "EST" / "EDT" /         ; Eastern:  - 5/ - 4
1964                         "CST" / "CDT" /         ; Central:  - 6/ - 5
1965                         "MST" / "MDT" /         ; Mountain: - 7/ - 6
1966                         "PST" / "PDT" /         ; Pacific:  - 8/ - 7
1967
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
1972 */
1973
1974 const uschar * c;
1975
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;
1980 ++str;
1981 str = skip_comment(str);
1982 if ((str = parse_number(str,m,2)) == NULL) return NULL;
1983 c = skip_comment(str);
1984 if (*str == ':')
1985   {
1986   ++str;
1987   str = skip_comment(str);
1988   if ((str = parse_number(str,s,2)) == NULL) return NULL;
1989   c = skip_comment(str);
1990   }
1991 if (c == str) return NULL;
1992 else str=c;
1993 if (*str == '+' || *str == '-')
1994   {
1995   int neg;
1996
1997   neg = (*str == '-');
1998   ++str;
1999   if ((str = parse_number(str,z,4)) == NULL) return NULL;
2000   *z = (*z/100)*3600+(*z%100)*60;
2001   if (neg) *z = -*z;
2002   }
2003 else
2004   {
2005   char zone[5];
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}};
2008   int i,j;
2009
2010   for (i = 0; i<4; ++i)
2011     {
2012     zone[i] = tolower(*(str+i));
2013     if (zone[i]<'a' || zone[i]>'z') break;
2014     }
2015   zone[i] = '\0';
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. */
2019   if (j<10)
2020     {
2021     *z = zone_name[j].off*3600;
2022     str+=i;
2023     }
2024   else if (zone[0]<'a' || zone[1]>'z') return 0;
2025   else
2026     {
2027     while ((*str>='a' && *str<='z') || (*str>='A' && *str<='Z')) ++str;
2028     *z = 0;
2029     }
2030   }
2031 return str;
2032 }
2033
2034
2035 /*************************************************
2036 *          Parse a RFC 2822 date-time            *
2037 *************************************************/
2038
2039 /* Parse a RFC 2822 date-time and return it in seconds since the epoch.
2040
2041 Arguments:
2042   str          pointer to the start of the date-time
2043   t            pointer to the parsed time
2044
2045 Returns:       points after the processed date-time or NULL on error
2046 */
2047
2048 const uschar *
2049 parse_date_time(const uschar *str, time_t *t)
2050 {
2051 /*
2052 date-time       =       [ day-of-week "," ] date FWS time [CFWS]
2053 */
2054
2055 struct tm tm;
2056 int zone;
2057 extern char **environ;
2058 char **old_environ;
2059 static char gmt0[]="TZ=GMT0";
2060 static char *gmt_env[]={ gmt0, (char*)0 };
2061 const uschar * try;
2062
2063 if ((try = parse_day_of_week(str)))
2064   {
2065   str = try;
2066   if (*str!=',') return 0;
2067   ++str;
2068   }
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;
2073 tm.tm_isdst = 0;
2074 old_environ = environ;
2075 environ = gmt_env;
2076 *t = mktime(&tm);
2077 environ = old_environ;
2078 if (*t == -1) return NULL;
2079 *t-=zone;
2080 return skip_comment(str);
2081 }
2082
2083
2084
2085
2086 /*************************************************
2087 **************************************************
2088 *             Stand-alone test program           *
2089 **************************************************
2090 *************************************************/
2091
2092 #if defined STAND_ALONE
2093 int main(void)
2094 {
2095 int start, end, domain;
2096 uschar buffer[1024];
2097
2098 store_init();
2099 big_buffer = store_malloc(big_buffer_size);
2100
2101 /* strip_trailing_dot = TRUE; */
2102 allow_domain_literals = TRUE;
2103
2104 printf("Testing parse_fix_phrase\n");
2105
2106 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
2107   {
2108   buffer[Ustrlen(buffer)-1] = 0;
2109   if (buffer[0] == 0) break;
2110   printf("%s\n", CS parse_fix_phrase(buffer, Ustrlen(buffer)));
2111   }
2112
2113 printf("Testing parse_extract_address without group syntax and without UTF-8\n");
2114
2115 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
2116   {
2117   uschar *out;
2118   uschar *errmess;
2119   buffer[Ustrlen(buffer) - 1] = 0;
2120   if (buffer[0] == 0) break;
2121   out = parse_extract_address(buffer, &errmess, &start, &end, &domain, FALSE);
2122   if (!out)
2123     printf("*** bad address: %s\n", errmess);
2124   else
2125     {
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);
2130     }
2131   }
2132
2133 printf("Testing parse_extract_address without group syntax but with UTF-8\n");
2134
2135 allow_utf8_domains = TRUE;
2136 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
2137   {
2138   uschar *out;
2139   uschar *errmess;
2140   buffer[Ustrlen(buffer) - 1] = 0;
2141   if (buffer[0] == 0) break;
2142   out = parse_extract_address(buffer, &errmess, &start, &end, &domain, FALSE);
2143   if (!out)
2144     printf("*** bad address: %s\n", errmess);
2145   else
2146     {
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);
2151     }
2152   }
2153 allow_utf8_domains = FALSE;
2154
2155 printf("Testing parse_extract_address with group syntax\n");
2156
2157 f.parse_allow_group = TRUE;
2158 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
2159   {
2160   uschar *out;
2161   uschar *errmess;
2162   uschar *s;
2163   buffer[Ustrlen(buffer) - 1] = 0;
2164   if (buffer[0] == 0) break;
2165   s = buffer;
2166   while (*s)
2167     {
2168     uschar *ss = parse_find_address_end(s, FALSE);
2169     int terminator = *ss;
2170     *ss = 0;
2171     out = parse_extract_address(buffer, &errmess, &start, &end, &domain, FALSE);
2172     *ss = terminator;
2173
2174     if (!out)
2175       printf("*** bad address: %s\n", errmess);
2176     else
2177       {
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);
2182       }
2183
2184     s = ss + (terminator? 1:0);
2185     Uskip_whitespace(&s);
2186     }
2187   }
2188
2189 printf("Testing parse_find_at\n");
2190
2191 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
2192   {
2193   uschar *s;
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);
2199   }
2200
2201 printf("Testing parse_extract_addresses\n");
2202
2203 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
2204   {
2205   uschar *errmess;
2206   int extracted;
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)
2212     {
2213     while (anchor != NULL)
2214       {
2215       address_item *addr = anchor;
2216       anchor = anchor->next;
2217       printf("%d %s\n", testflag(addr, af_pfr), addr->address);
2218       }
2219     }
2220   else printf("Failed: %d %s\n", extracted, errmess);
2221   }
2222
2223 printf("Testing parse_message_id\n");
2224
2225 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
2226   {
2227   uschar *s, *t, *errmess;
2228   buffer[Ustrlen(buffer) - 1] = 0;
2229   if (buffer[0] == 0) break;
2230   s = buffer;
2231   while (*s != 0)
2232     {
2233     s = parse_message_id(s, &t, &errmess);
2234     if (errmess != NULL)
2235       {
2236       printf("Failed: %s\n", errmess);
2237       break;
2238       }
2239     printf("%s\n", t);
2240     }
2241   }
2242
2243 return 0;
2244 }
2245
2246 #endif
2247
2248 /* End of parse.c */