Allow for linefold when generating more than one RFC 2047 encoded-word.
[exim.git] / src / src / parse.c
1 /* $Cambridge: exim/src/src/parse.c,v 1.9 2006/03/08 11:13:07 ph10 Exp $ */
2
3 /*************************************************
4 *     Exim - an Internet mail transport agent    *
5 *************************************************/
6
7 /* Copyright (c) University of Cambridge 1995 - 2006 */
8 /* See the file NOTICE for conditions of use and distribution. */
9
10 /* Functions for parsing addresses */
11
12
13 #include "exim.h"
14
15
16 static 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 *deliver_make_addr(uschar *address, BOOL copy)
27 {
28 address_item *addr = store_get(sizeof(address_item));
29 addr->next = NULL;
30 addr->parent = NULL;
31 addr->address = address;
32 return addr;
33 }
34
35 uschar *rewrite_address(uschar *recipient, BOOL dummy1, BOOL dummy2, rewrite_rule
36   *dummy3, int dummy4)
37 {
38 return recipient;
39 }
40
41 uschar *rewrite_address_qualify(uschar *recipient, BOOL dummy1)
42 {
43 return recipient;
44 }
45
46 #endif
47
48
49
50
51 /*************************************************
52 *             Find the end of an address         *
53 *************************************************/
54
55 /* Scan over a string looking for the termination of an address at a comma,
56 or end of the string. It's the source-routed addresses which cause much pain
57 here. Although Exim ignores source routes, it must recognize such addresses, so
58 we cannot get rid of this logic.
59
60 Argument:
61   s        pointer to the start of an address
62   nl_ends  if TRUE, '\n' terminates an address
63
64 Returns:   pointer past the end of the address
65            (i.e. points to null or comma)
66 */
67
68 uschar *
69 parse_find_address_end(uschar *s, BOOL nl_ends)
70 {
71 BOOL source_routing = *s == '@';
72 int no_term = source_routing? 1 : 0;
73
74 while (*s != 0 && (*s != ',' || no_term > 0) && (*s != '\n' || !nl_ends))
75   {
76   /* Skip single quoted characters. Strictly these should not occur outside
77   quoted strings in RFC 822 addresses, but they can in RFC 821 addresses. Pity
78   about the lack of consistency, isn't it? */
79
80   if (*s == '\\' && s[1] != 0) s += 2;
81
82   /* Skip quoted items that are not inside brackets. Note that
83   quoted pairs are allowed inside quoted strings. */
84
85   else if (*s == '\"')
86     {
87     while (*(++s) != 0 && (*s != '\n' || !nl_ends))
88       {
89       if (*s == '\\' && s[1] != 0) s++;
90         else if (*s == '\"') { s++; break; }
91       }
92     }
93
94   /* Skip comments, which may include nested brackets, but quotes
95   are not recognized inside comments, though quoted pairs are. */
96
97   else if (*s == '(')
98     {
99     int level = 1;
100     while (*(++s) != 0 && (*s != '\n' || !nl_ends))
101       {
102       if (*s == '\\' && s[1] != 0) s++;
103         else if (*s == '(') level++;
104           else if (*s == ')' && --level <= 0) { s++; break; }
105       }
106     }
107
108   /* Non-special character; just advance. Passing the colon in a source
109   routed address means that any subsequent comma or colon may terminate unless
110   inside angle brackets. */
111
112   else
113     {
114     if (*s == '<')
115       {
116       source_routing = s[1] == '@';
117       no_term = source_routing? 2 : 1;
118       }
119     else if (*s == '>') no_term--;
120     else if (source_routing && *s == ':') no_term--;
121     s++;
122     }
123   }
124
125 return s;
126 }
127
128
129
130 /*************************************************
131 *            Find last @ in an address           *
132 *************************************************/
133
134 /* This function is used when we have something that may not qualified. If we
135 know it's qualified, searching for the rightmost '@' is sufficient. Here we
136 have to be a bit more clever than just a plain search, in order to handle
137 unqualified local parts like "thing@thong" correctly. Since quotes may not
138 legally be part of a domain name, we can give up on hitting the first quote
139 when searching from the right. Now that the parsing also permits the RFC 821
140 form of address, where quoted-pairs are allowed in unquoted local parts, we
141 must take care to handle that too.
142
143 Argument:  pointer to an address, possibly unqualified
144 Returns:   pointer to the last @ in an address, or NULL if none
145 */
146
147 uschar *
148 parse_find_at(uschar *s)
149 {
150 uschar *t = s + Ustrlen(s);
151 while (--t >= s)
152   {
153   if (*t == '@')
154     {
155     int backslash_count = 0;
156     uschar *tt = t - 1;
157     while (tt > s && *tt-- == '\\') backslash_count++;
158     if ((backslash_count & 1) == 0) return t;
159     }
160   else if (*t == '\"') return NULL;
161   }
162 return NULL;
163 }
164
165
166
167
168 /***************************************************************************
169 * In all the functions below that read a particular object type from       *
170 * the input, return the new value of the pointer s (the first argument),   *
171 * and put the object into the store pointed to by t (the second argument), *
172 * adding a terminating zero. If no object is found, t will point to zero   *
173 * on return.                                                               *
174 ***************************************************************************/
175
176
177 /*************************************************
178 *          Skip white space and comment          *
179 *************************************************/
180
181 /* Algorithm:
182   (1) Skip spaces.
183   (2) If uschar not '(', return.
184   (3) Skip till matching ')', not counting any characters
185       escaped with '\'.
186   (4) Move past ')' and goto (1).
187
188 The start of the last potential comment position is remembered to
189 make it possible to ignore comments at the end of compound items.
190
191 Argument: current character pointer
192 Regurns:  new character pointer
193 */
194
195 static uschar *
196 skip_comment(uschar *s)
197 {
198 last_comment_position = s;
199 while (*s)
200   {
201   int c, level;
202   while (isspace(*s)) s++;
203   if (*s != '(') break;
204   level = 1;
205   while((c = *(++s)) != 0)
206     {
207     if (c == '(') level++;
208     else if (c == ')') { if (--level <= 0) { s++; break; } }
209     else if (c == '\\' && s[1] != 0) s++;
210     }
211   }
212 return s;
213 }
214
215
216
217 /*************************************************
218 *             Read a domain                      *
219 *************************************************/
220
221 /* A domain is a sequence of subdomains, separated by dots. See comments below
222 for detailed syntax of the subdomains.
223
224 If allow_domain_literals is TRUE, a "domain" may also be an IP address enclosed
225 in []. Make sure the output is set to the null string if there is a syntax
226 error as well as if there is no domain at all.
227
228 Arguments:
229   s          current character pointer
230   t          where to put the domain
231   errorptr   put error message here on failure (*t will be 0 on exit)
232
233 Returns:     new character pointer
234 */
235
236 static uschar *
237 read_domain(uschar *s, uschar *t, uschar **errorptr)
238 {
239 uschar *tt = t;
240 s = skip_comment(s);
241
242 /* Handle domain literals if permitted. An RFC 822 domain literal may contain
243 any character except [ ] \, including linear white space, and may contain
244 quoted characters. However, RFC 821 restricts literals to being dot-separated
245 3-digit numbers, and we make the obvious extension for IPv6. Go for a sequence
246 of digits, dots, hex digits, and colons here; later this will be checked for
247 being a syntactically valid IP address if it ever gets to a router.
248
249 Allow both the formal IPv6 form, with IPV6: at the start, and the informal form
250 without it, and accept IPV4: as well, 'cause someone will use it sooner or
251 later. */
252
253 if (*s == '[')
254   {
255   *t++ = *s++;
256
257   if (strncmpic(s, US"IPv6:", 5) == 0 || strncmpic(s, US"IPv4:", 5) == 0)
258     {
259     memcpy(t, s, 5);
260     t += 5;
261     s += 5;
262     }
263   while (*s == '.' || *s == ':' || isxdigit(*s)) *t++ = *s++;
264
265   if (*s == ']') *t++ = *s++; else
266     {
267     *errorptr = US"malformed domain literal";
268     *tt = 0;
269     }
270
271   if (!allow_domain_literals)
272     {
273     *errorptr = US"domain literals not allowed";
274     *tt = 0;
275     }
276   *t = 0;
277   return skip_comment(s);
278   }
279
280 /* Handle a proper domain, which is a sequence of dot-separated atoms. Remove
281 trailing dots if strip_trailing_dot is set. A subdomain is an atom.
282
283 An atom is a sequence of any characters except specials, space, and controls.
284 The specials are ( ) < > @ , ; : \ " . [ and ]. This is the rule for RFC 822
285 and its successor (RFC 2822). However, RFC 821 and its successor (RFC 2821) is
286 tighter, allowing only letters, digits, and hyphens, not starting with a
287 hyphen.
288
289 There used to be a global flag that got set when checking addresses that came
290 in over SMTP and which should therefore should be checked according to the
291 stricter rule. However, it seems silly to make the distinction, because I don't
292 suppose anybody ever uses local domains that are 822-compliant and not
293 821-compliant. Furthermore, Exim now has additional data on the spool file line
294 after an address (after "one_time" processing), and it makes use of a #
295 character to delimit it. When I wrote that code, I forgot about this 822-domain
296 stuff, and assumed # could never appear in a domain.
297
298 So the old code is now cut out for Release 4.11 onwards, on 09-Aug-02. In a few
299 years, when we are sure this isn't actually causing trouble, throw it away.
300
301 March 2003: the story continues: There is a camp that is arguing for the use of
302 UTF-8 in domain names as the way to internationalization, and other MTAs
303 support this. Therefore, we now have a flag that permits the use of characters
304 with values greater than 127, encoded in UTF-8, in subdomains, so that Exim can
305 be used experimentally in this way. */
306
307 for (;;)
308   {
309   uschar *tsave = t;
310
311 /*********************
312   if (rfc821_domains)
313     {
314     if (*s != '-') while (isalnum(*s) || *s == '-') *t++ = *s++;
315     }
316   else
317     while (!mac_iscntrl_or_special(*s)) *t++ = *s++;
318 *********************/
319
320   if (*s != '-')
321     {
322     /* Only letters, digits, and hyphens */
323
324     if (!allow_utf8_domains)
325       {
326       while (isalnum(*s) || *s == '-') *t++ = *s++;
327       }
328
329     /* Permit legal UTF-8 characters to be included */
330
331     else for(;;)
332       {
333       int i, d;
334       if (isalnum(*s) || *s == '-')    /* legal ascii characters */
335         {
336         *t++ = *s++;
337         continue;
338         }
339       if ((*s & 0xc0) != 0xc0) break;  /* not start of UTF-8 character */
340       d = *s << 2;
341       for (i = 1; i < 6; i++)          /* i is the number of additional bytes */
342         {
343         if ((d & 0x80) == 0) break;
344         d <<= 1;
345         }
346       if (i == 6) goto BAD_UTF8;       /* invalid UTF-8 */
347       *t++ = *s++;                     /* leading UTF-8 byte */
348       while (i-- > 0)                  /* copy and check remainder */
349         {
350         if ((*s & 0xc0) != 0x80)
351           {
352           BAD_UTF8:
353           *errorptr = US"invalid UTF-8 byte sequence";
354           *tt = 0;
355           return s;
356           }
357         *t++ = *s++;
358         }
359       }    /* End of loop for UTF-8 character */
360     }      /* End of subdomain */
361
362   s = skip_comment(s);
363   *t = 0;
364
365   if (t == tsave)   /* empty component */
366     {
367     if (strip_trailing_dot && t > tt && *s != '.') t[-1] = 0; else
368       {
369       *errorptr = US"domain missing or malformed";
370       *tt = 0;
371       }
372     return s;
373     }
374
375   if (*s != '.') break;
376   *t++ = *s++;
377   s = skip_comment(s);
378   }
379
380 return s;
381 }
382
383
384
385 /*************************************************
386 *            Read a local-part                   *
387 *************************************************/
388
389 /* A local-part is a sequence of words, separated by periods. A null word
390 between dots is not strictly allowed but apparently many mailers permit it,
391 so, sigh, better be compatible. Even accept a trailing dot...
392
393 A <word> is either a quoted string, or an <atom>, which is a sequence
394 of any characters except specials, space, and controls. The specials are
395 ( ) < > @ , ; : \ " . [ and ]. In RFC 822, a single quoted character, (a
396 quoted-pair) is not allowed in a word. However, in RFC 821, it is permitted in
397 the local part of an address. Rather than have separate parsing functions for
398 the different cases, take the liberal attitude always. At least one MUA is
399 happy to recognize this case; I don't know how many other programs do.
400
401 Arguments:
402   s           current character pointer
403   t           where to put the local part
404   error       where to point error text
405   allow_null  TRUE if an empty local part is not an error
406
407 Returns:   new character pointer
408 */
409
410 static uschar *
411 read_local_part(uschar *s, uschar *t, uschar **error, BOOL allow_null)
412 {
413 uschar *tt = t;
414 *error = NULL;
415 for (;;)
416   {
417   int c;
418   uschar *tsave = t;
419   s = skip_comment(s);
420
421   /* Handle a quoted string */
422
423   if (*s == '\"')
424     {
425     *t++ = '\"';
426     while ((c = *(++s)) != 0 && c != '\"')
427       {
428       *t++ = c;
429       if (c == '\\' && s[1] != 0) *t++ = *(++s);
430       }
431     if (c == '\"')
432       {
433       s++;
434       *t++ = '\"';
435       }
436     else
437       {
438       *error = US"unmatched doublequote in local part";
439       return s;
440       }
441     }
442
443   /* Handle an atom, but allow quoted pairs within it. */
444
445   else while (!mac_iscntrl_or_special(*s) || *s == '\\')
446     {
447     c = *t++ = *s++;
448     if (c == '\\' && *s != 0) *t++ = *s++;
449     }
450
451   /* Terminate the word and skip subsequent comment */
452
453   *t = 0;
454   s = skip_comment(s);
455
456   /* If we have read a null component at this point, give an error unless it is
457   terminated by a dot - an extension to RFC 822 - or if it is the first
458   component of the local part and an empty local part is permitted, in which
459   case just return normally. */
460
461   if (t == tsave && *s != '.')
462     {
463     if (t == tt && !allow_null)
464       *error = US"missing or malformed local part";
465     return s;
466     }
467
468   /* Anything other than a dot terminates the local part. Treat multiple dots
469   as a single dot, as this seems to be a common extension. */
470
471   if (*s != '.') break;
472   do { *t++ = *s++; } while (*s == '.');
473   }
474
475 return s;
476 }
477
478
479 /*************************************************
480 *            Read route part of route-addr       *
481 *************************************************/
482
483 /* The pointer is at the initial "@" on entry. Return it following the
484 terminating colon. Exim no longer supports the use of source routes, but it is
485 required to accept the syntax.
486
487 Arguments:
488   s          current character pointer
489   t          where to put the route
490   errorptr   where to put an error message
491
492 Returns:     new character pointer
493 */
494
495 static uschar *
496 read_route(uschar *s, uschar *t, uschar **errorptr)
497 {
498 BOOL commas = FALSE;
499 *errorptr = NULL;
500
501 while (*s == '@')
502   {
503   *t++ = '@';
504   s = read_domain(s+1, t, errorptr);
505   if (*t == 0) return s;
506   t += Ustrlen((const uschar *)t);
507   if (*s != ',') break;
508   *t++ = *s++;
509   commas = TRUE;
510   s = skip_comment(s);
511   }
512
513 if (*s == ':') *t++ = *s++;
514
515 /* If there is no colon, and there were no commas, the most likely error
516 is in fact a missing local part in the address rather than a missing colon
517 after the route. */
518
519 else *errorptr = commas?
520   US"colon expected after route list" :
521   US"no local part";
522
523 /* Terminate the route and return */
524
525 *t = 0;
526 return skip_comment(s);
527 }
528
529
530
531 /*************************************************
532 *                Read addr-spec                  *
533 *************************************************/
534
535 /* Addr-spec is local-part@domain. We make the domain optional -
536 the expected terminator for the whole thing is passed to check this.
537 This function is called only when we know we have a route-addr.
538
539 Arguments:
540   s          current character pointer
541   t          where to put the addr-spec
542   term       expected terminator (0 or >)
543   errorptr   where to put an error message
544   domainptr  set to point to the start of the domain
545
546 Returns:     new character pointer
547 */
548
549 static uschar *
550 read_addr_spec(uschar *s, uschar *t, int term, uschar **errorptr,
551   uschar **domainptr)
552 {
553 s = read_local_part(s, t, errorptr, FALSE);
554 if (*errorptr == NULL)
555   {
556   if (*s != term)
557     {
558     if (*s != '@')
559       *errorptr = string_sprintf("\"@\" or \".\" expected after \"%s\"", t);
560     else
561       {
562       t += Ustrlen((const uschar *)t);
563       *t++ = *s++;
564       *domainptr = t;
565       s = read_domain(s, t, errorptr);
566       }
567     }
568   }
569 return s;
570 }
571
572
573
574 /*************************************************
575 *         Extract operative address              *
576 *************************************************/
577
578 /* This function extracts an operative address from a full RFC822 mailbox and
579 returns it in a piece of dynamic store. We take the easy way and get a piece
580 of store the same size as the input, and then copy into it whatever is
581 necessary. If we cannot find a valid address (syntax error), return NULL, and
582 point the error pointer to the reason. The arguments "start" and "end" are used
583 to return the offsets of the first and one past the last characters in the
584 original mailbox of the address that has been extracted, to aid in re-writing.
585 The argument "domain" is set to point to the first character after "@" in the
586 final part of the returned address, or zero if there is no @.
587
588 Exim no longer supports the use of source routed addresses (those of the form
589 @domain,...:route_addr). It recognizes the syntax, but collapses such addresses
590 down to their final components. Formerly, collapse_source_routes had to be set
591 to achieve this effect. RFC 1123 allows collapsing with MAY, while the revision
592 of RFC 821 had increased this to SHOULD, so I've gone for it, because it makes
593 a lot of code elsewhere in Exim much simpler.
594
595 There are some special fudges here for handling RFC 822 group address notation
596 which may appear in certain headers. If the flag parse_allow_group is set
597 TRUE and parse_found_group is FALSE when this function is called, an address
598 which is the start of a group (i.e. preceded by a phrase and a colon) is
599 recognized; the phrase is ignored and the flag parse_found_group is set. If
600 this flag is TRUE at the end of an address, then if an extraneous semicolon is
601 found, it is ignored and the flag is cleared. This logic is used only when
602 scanning through addresses in headers, either to fulfil the -t option or for
603 rewriting or checking header syntax.
604
605 Arguments:
606   mailbox     points to the RFC822 mailbox
607   errorptr    where to point an error message
608   start       set to start offset in mailbox
609   end         set to end offset in mailbox
610   domain      set to domain offset in result, or 0 if no domain present
611   allow_null  allow <> if TRUE
612
613 Returns:      points to the extracted address, or NULL on error
614 */
615
616 #define FAILED(s) { *errorptr = s; goto PARSE_FAILED; }
617
618 uschar *
619 parse_extract_address(uschar *mailbox, uschar **errorptr, int *start, int *end,
620   int *domain, BOOL allow_null)
621 {
622 uschar *yield = store_get(Ustrlen(mailbox) + 1);
623 uschar *startptr, *endptr;
624 uschar *s = (uschar *)mailbox;
625 uschar *t = (uschar *)yield;
626
627 *domain = 0;
628
629 /* At the start of the string we expect either an addr-spec or a phrase
630 preceding a <route-addr>. If groups are allowed, we might also find a phrase
631 preceding a colon and an address. If we find an initial word followed by
632 a dot, strict interpretation of the RFC would cause it to be taken
633 as the start of an addr-spec. However, many mailers break the rules
634 and use addresses of the form "a.n.other <ano@somewhere>" and so we
635 allow this case. */
636
637 RESTART:   /* Come back here after passing a group name */
638
639 s = skip_comment(s);
640 startptr = s;                                 /* In case addr-spec */
641 s = read_local_part(s, t, errorptr, TRUE);    /* Dot separated words */
642 if (*errorptr != NULL) goto PARSE_FAILED;
643
644 /* If the terminator is neither < nor @ then the format of the address
645 must either be a bare local-part (we are now at the end), or a phrase
646 followed by a route-addr (more words must follow). */
647
648 if (*s != '@' && *s != '<')
649   {
650   if (*s == 0 || *s == ';')
651     {
652     if (*t == 0) FAILED(US"empty address");
653     endptr = last_comment_position;
654     goto PARSE_SUCCEEDED;              /* Bare local part */
655     }
656
657   /* Expect phrase route-addr, or phrase : if groups permitted, but allow
658   dots in the phrase; complete the loop only when '<' or ':' is encountered -
659   end of string will produce a null local_part and therefore fail. We don't
660   need to keep updating t, as the phrase isn't to be kept. */
661
662   while (*s != '<' && (!parse_allow_group || *s != ':'))
663     {
664     s = read_local_part(s, t, errorptr, FALSE);
665     if (*errorptr != NULL)
666       {
667       *errorptr = string_sprintf("%s (expected word or \"<\")", *errorptr);
668       goto PARSE_FAILED;
669       }
670     }
671
672   if (*s == ':')
673     {
674     parse_found_group = TRUE;
675     parse_allow_group = FALSE;
676     s++;
677     goto RESTART;
678     }
679
680   /* Assert *s == '<' */
681   }
682
683 /* At this point the next character is either '@' or '<'. If it is '@', only a
684 single local-part has previously been read. An angle bracket signifies the
685 start of an <addr-spec>. Throw away anything we have saved so far before
686 processing it. Note that this is "if" rather than "else if" because it's also
687 used after reading a preceding phrase.
688
689 There are a lot of broken sendmails out there that put additional pairs of <>
690 round <route-addr>s. If strip_excess_angle_brackets is set, allow any number of
691 them, as long as they match. */
692
693 if (*s == '<')
694   {
695   uschar *domainptr = yield;
696   BOOL source_routed = FALSE;
697   int bracket_count = 1;
698
699   s++;
700   if (strip_excess_angle_brackets)
701     while (*s == '<') { bracket_count++; s++; }
702
703   t = yield;
704   startptr = s;
705   s = skip_comment(s);
706
707   /* Read an optional series of routes, each of which is a domain. They
708   are separated by commas and terminated by a colon. However, we totally ignore
709   such routes (RFC 1123 says we MAY, and the revision of RFC 821 says we
710   SHOULD). */
711
712   if (*s == '@')
713     {
714     s = read_route(s, t, errorptr);
715     if (*errorptr != NULL) goto PARSE_FAILED;
716     *t = 0;                  /* Ensure route is ignored - probably overkill */
717     source_routed = TRUE;
718     }
719
720   /* Now an addr-spec, terminated by '>'. If there is no preceding route,
721   we must allow an empty addr-spec if allow_null is TRUE, to permit the
722   address "<>" in some circumstances. A source-routed address MUST have
723   a domain in the final part. */
724
725   if (allow_null && !source_routed && *s == '>')
726     {
727     *t = 0;
728     *errorptr = NULL;
729     }
730   else
731     {
732     s = read_addr_spec(s, t, '>', errorptr, &domainptr);
733     if (*errorptr != NULL) goto PARSE_FAILED;
734     *domain = domainptr - yield;
735     if (source_routed && *domain == 0)
736       FAILED(US"domain missing in source-routed address");
737     }
738
739   endptr = s;
740   if (*errorptr != NULL) goto PARSE_FAILED;
741   while (bracket_count-- > 0) if (*s++ != '>')
742     {
743     *errorptr = (s[-1] == 0)? US"'>' missing at end of address" :
744       string_sprintf("malformed address: %.32s may not follow %.*s",
745         s-1, s - (uschar *)mailbox - 1, mailbox);
746     goto PARSE_FAILED;
747     }
748
749   s = skip_comment(s);
750   }
751
752 /* Hitting '@' after the first local-part means we have definitely got an
753 addr-spec, on a strict reading of the RFC, and the rest of the string
754 should be the domain. However, for flexibility we allow for a route-address
755 not enclosed in <> as well, which is indicated by an empty first local
756 part preceding '@'. The source routing is, however, ignored. */
757
758 else if (*t == 0)
759   {
760   uschar *domainptr = yield;
761   s = read_route(s, t, errorptr);
762   if (*errorptr != NULL) goto PARSE_FAILED;
763   *t = 0;         /* Ensure route is ignored - probably overkill */
764   s = read_addr_spec(s, t, 0, errorptr, &domainptr);
765   if (*errorptr != NULL) goto PARSE_FAILED;
766   *domain = domainptr - yield;
767   endptr = last_comment_position;
768   if (*domain == 0) FAILED(US"domain missing in source-routed address");
769   }
770
771 /* This is the strict case of local-part@domain. */
772
773 else
774   {
775   t += Ustrlen((const uschar *)t);
776   *t++ = *s++;
777   *domain = t - yield;
778   s = read_domain(s, t, errorptr);
779   if (*t == 0) goto PARSE_FAILED;
780   endptr = last_comment_position;
781   }
782
783 /* Use goto to get here from the bare local part case. Arrive by falling
784 through for other cases. Endptr may have been moved over whitespace, so
785 move it back past white space if necessary. */
786
787 PARSE_SUCCEEDED:
788 if (*s != 0)
789   {
790   if (parse_found_group && *s == ';')
791     {
792     parse_found_group = FALSE;
793     parse_allow_group = TRUE;
794     }
795   else
796     {
797     *errorptr = string_sprintf("malformed address: %.32s may not follow %.*s",
798       s, s - (uschar *)mailbox, mailbox);
799     goto PARSE_FAILED;
800     }
801   }
802 *start = startptr - (uschar *)mailbox;      /* Return offsets */
803 while (isspace(endptr[-1])) endptr--;
804 *end = endptr - (uschar *)mailbox;
805
806 /* Although this code has no limitation on the length of address extracted,
807 other parts of Exim may have limits, and in any case, RFC 2821 limits local
808 parts to 64 and domains to 255, so we do a check here, giving an error if the
809 address is ridiculously long. */
810
811 if (*end - *start > ADDRESS_MAXLENGTH)
812   {
813   *errorptr = string_sprintf("address is ridiculously long: %.64s...", yield);
814   return NULL;
815   }
816
817 return (uschar *)yield;
818
819 /* Use goto (via the macro FAILED) to get to here from a variety of places.
820 We might have an empty address in a group - the caller can choose to ignore
821 this. We must, however, keep the flags correct. */
822
823 PARSE_FAILED:
824 if (parse_found_group && *s == ';')
825   {
826   parse_found_group = FALSE;
827   parse_allow_group = TRUE;
828   }
829 return NULL;
830 }
831
832 #undef FAILED
833
834
835
836 /*************************************************
837 *        Quote according to RFC 2047             *
838 *************************************************/
839
840 /* This function is used for quoting text in headers according to RFC 2047.
841 If the only characters that strictly need quoting are spaces, we return the
842 original string, unmodified. If a quoted string is too long for the buffer, it
843 is truncated. (This shouldn't happen: this is normally handling short strings.)
844
845 Hmmph. As always, things get perverted for other uses. This function was
846 originally for the "phrase" part of addresses. Now it is being used for much
847 longer texts in ACLs and via the ${rfc2047: expansion item. This means we have
848 to check for overlong "encoded-word"s and split them. November 2004.
849
850 Arguments:
851   string       the string to quote - already checked to contain non-printing
852                  chars
853   len          the length of the string
854   charset      the name of the character set; NULL => iso-8859-1
855   buffer       the buffer to put the answer in
856   buffer_size  the size of the buffer
857   fold         if TRUE, a newline is inserted before the separating space when
858                  more than one encoded-word is generated
859
860 Returns:       pointer to the original string, if no quoting needed, or
861                pointer to buffer containing the quoted string, or
862                a pointer to "String too long" if the buffer can't even hold
863                the introduction
864 */
865
866 uschar *
867 parse_quote_2047(uschar *string, int len, uschar *charset, uschar *buffer,
868   int buffer_size, BOOL fold)
869 {
870 uschar *s = string;
871 uschar *p, *t;
872 int hlen;
873 BOOL coded = FALSE;
874
875 if (charset == NULL) charset = US"iso-8859-1";
876
877 /* We don't expect this to fail! */
878
879 if (!string_format(buffer, buffer_size, "=?%s?Q?", charset))
880   return US"String too long";
881
882 hlen = Ustrlen(buffer);
883 t = buffer + hlen;
884 p = buffer;
885
886 for (; len > 0; len--)
887   {
888   int ch = *s++;
889   if (t > buffer + buffer_size - hlen - 8) break;
890
891   if (t - p > 70)
892     {
893     *t++ = '?';
894     *t++ = '=';
895     if (fold) *t++ = '\n';
896     *t++ = ' ';
897     p = t;
898     Ustrncpy(p, buffer, hlen);
899     t += hlen;
900     }
901
902   if (ch < 33 || ch > 126 ||
903       Ustrchr("?=()<>@,;:\\\".[]_", ch) != NULL)
904     {
905     if (ch == ' ') *t++ = '_'; else
906       {
907       sprintf(CS t, "=%02X", ch);
908       while (*t != 0) t++;
909       coded = TRUE;
910       }
911     }
912   else *t++ = ch;
913   }
914
915 *t++ = '?';
916 *t++ = '=';
917 *t = 0;
918
919 return coded? buffer : string;
920 }
921
922
923
924
925 /*************************************************
926 *            Fix up an RFC 822 "phrase"          *
927 *************************************************/
928
929 /* This function is called to repair any syntactic defects in the "phrase" part
930 of an RFC822 address. In particular, it is applied to the user's name as read
931 from the passwd file when accepting a local message, and to the data from the
932 -F option.
933
934 If the string contains existing quoted strings or comments containing
935 freestanding quotes, then we just quote those bits that need quoting -
936 otherwise it would get awfully messy and probably not look good. If not, we
937 quote the whole thing if necessary. Thus
938
939    John Q. Smith            =>  "John Q. Smith"
940    John "Jack" Smith        =>  John "Jack" Smith
941    John "Jack" Q. Smith     =>  John "Jack" "Q." Smith
942    John (Jack) Q. Smith     =>  "John (Jack) Q. Smith"
943    John ("Jack") Q. Smith   =>  John ("Jack") "Q." Smith
944 but
945    John (\"Jack\") Q. Smith =>  "John (\"Jack\") Q. Smith"
946
947 Sheesh! This is tedious code. It is a great pity that the syntax of RFC822 is
948 the way it is...
949
950 August 2000: Additional code added:
951
952   Previously, non-printing characters were turned into question marks, which do
953   not need to be quoted.
954
955   Now, a different tactic is used if there are any non-printing ASCII
956   characters. The encoding method from RFC 2047 is used, assuming iso-8859-1 as
957   the character set.
958
959   We *could* use this for all cases, getting rid of the messy original code,
960   but leave it for now. It would complicate simple cases like "John Q. Smith".
961
962 The result is passed back in the buffer; it is usually going to be added to
963 some other string. In order to be sure there is going to be no overflow,
964 restrict the length of the input to 1/4 of the buffer size - this allows for
965 every single character to be quoted or encoded without overflowing, and that
966 wouldn't happen because of amalgamation. If the phrase is too long, return a
967 fixed string.
968
969 Arguments:
970   phrase       an RFC822 phrase
971   len          the length of the phrase
972   buffer       a buffer to put the result in
973   buffer_size  the size of the buffer
974
975 Returns:       the fixed RFC822 phrase
976 */
977
978 uschar *
979 parse_fix_phrase(uschar *phrase, int len, uschar *buffer, int buffer_size)
980 {
981 int ch, i;
982 BOOL quoted = FALSE;
983 uschar *s, *t, *end, *yield;
984
985 while (len > 0 && isspace(*phrase)) { phrase++; len--; }
986 if (len > buffer_size/4) return US"Name too long";
987
988 /* See if there are any non-printing characters, and if so, use the RFC 2047
989 encoding for the whole thing. */
990
991 for (i = 0, s = phrase; i < len; i++, s++)
992   if ((*s < 32 && *s != '\t') || *s > 126) break;
993
994 if (i < len) return parse_quote_2047(phrase, len, headers_charset, buffer,
995   buffer_size, FALSE);
996
997 /* No non-printers; use the RFC 822 quoting rules */
998
999 s = phrase;
1000 end = s + len;
1001 yield = t = buffer + 1;
1002
1003 while (s < end)
1004   {
1005   ch = *s++;
1006
1007   /* Copy over quoted strings, remembering we encountered one */
1008
1009   if (ch == '\"')
1010     {
1011     *t++ = '\"';
1012     while (s < end && (ch = *s++) != '\"')
1013       {
1014       *t++ = ch;
1015       if (ch == '\\' && s < end) *t++ = *s++;
1016       }
1017     *t++ = '\"';
1018     if (s >= end) break;
1019     quoted = TRUE;
1020     }
1021
1022   /* Copy over comments, noting if they contain freestanding quote
1023   characters */
1024
1025   else if (ch == '(')
1026     {
1027     int level = 1;
1028     *t++ = '(';
1029     while (s < end)
1030       {
1031       ch = *s++;
1032       *t++ = ch;
1033       if (ch == '(') level++;
1034       else if (ch == ')') { if (--level <= 0) break; }
1035       else if (ch == '\\' && s < end) *t++ = *s++ & 127;
1036       else if (ch == '\"') quoted = TRUE;
1037       }
1038     if (ch == 0)
1039       {
1040       while (level--) *t++ = ')';
1041       break;
1042       }
1043     }
1044
1045   /* Handle special characters that need to be quoted */
1046
1047   else if (Ustrchr(")<>@,;:\\.[]", ch) != NULL)
1048     {
1049     /* If hit previous quotes just make one quoted "word" */
1050
1051     if (quoted)
1052       {
1053       uschar *tt = t++;
1054       while (*(--tt) != ' ' && *tt != '\"' && *tt != ')') tt[1] = *tt;
1055       tt[1] = '\"';
1056       *t++ = ch;
1057       while (s < end)
1058         {
1059         ch = *s++;
1060         if (ch == ' ' || ch == '\"') { s--; break; } else *t++ = ch;
1061         }
1062       *t++ = '\"';
1063       }
1064
1065     /* Else quote the whole string so far, and the rest up to any following
1066     quotes. We must treat anything following a backslash as a literal. */
1067
1068     else
1069       {
1070       BOOL escaped = (ch == '\\');
1071       *(--yield) = '\"';
1072       *t++ = ch;
1073
1074       /* Now look for the end or a quote */
1075
1076       while (s < end)
1077         {
1078         ch = *s++;
1079
1080         /* Handle escaped pairs */
1081
1082         if (escaped)
1083           {
1084           *t++ = ch;
1085           escaped = FALSE;
1086           }
1087
1088         else if (ch == '\\')
1089           {
1090           *t++ = ch;
1091           escaped = TRUE;
1092           }
1093
1094         /* If hit subsequent quotes, insert our quote before any trailing
1095         spaces and back up to re-handle the quote in the outer loop. */
1096
1097         else if (ch == '\"')
1098           {
1099           int count = 0;
1100           while (t[-1] == ' ') { t--; count++; }
1101           *t++ = '\"';
1102           while (count-- > 0) *t++ = ' ';
1103           s--;
1104           break;
1105           }
1106
1107         /* If hit a subsequent comment, check it for unescaped quotes,
1108         and if so, end our quote before it. */
1109
1110         else if (ch == '(')
1111           {
1112           uschar *ss = s;     /* uschar after '(' */
1113           int level = 1;
1114           while(ss < end)
1115             {
1116             ch = *ss++;
1117             if (ch == '(') level++;
1118             else if (ch == ')') { if (--level <= 0) break; }
1119             else if (ch == '\\' && ss+1 < end) ss++;
1120             else if (ch == '\"') { quoted = TRUE; break; }
1121             }
1122
1123           /* Comment contains unescaped quotes; end our quote before
1124           the start of the comment. */
1125
1126           if (quoted)
1127             {
1128             int count = 0;
1129             while (t[-1] == ' ') { t--; count++; }
1130             *t++ = '\"';
1131             while (count-- > 0) *t++ = ' ';
1132             break;
1133             }
1134
1135           /* Comment does not contain unescaped quotes; include it in
1136           our quote. */
1137
1138           else
1139             {
1140             if (ss >= end) ss--;
1141             *t++ = '(';
1142             Ustrncpy(t, s, ss-s);
1143             t += ss-s;
1144             s = ss;
1145             }
1146           }
1147
1148         /* Not a comment or quote; include this character in our quotes. */
1149
1150         else *t++ = ch;
1151         }
1152       }
1153
1154     /* Add a final quote if we hit the end of the string. */
1155
1156     if (s >= end) *t++ = '\"';
1157     }
1158
1159   /* Non-special character; just copy it over */
1160
1161   else *t++ = ch;
1162   }
1163
1164 *t = 0;
1165 return yield;
1166 }
1167
1168
1169 /*************************************************
1170 *          Extract addresses from a list         *
1171 *************************************************/
1172
1173 /* This function is called by the redirect router to scan a string containing a
1174 list of addresses separated by commas (with optional white space) or by
1175 newlines, and to generate a chain of address items from them. In other words,
1176 to unpick data from an alias or .forward file.
1177
1178 The SunOS5 documentation for alias files is not very clear on the syntax; it
1179 does not say that either a comma or a newline can be used for separation.
1180 However, that is the way Smail does it, so we follow suit.
1181
1182 If a # character is encountered in a white space position, then characters from
1183 there to the next newline are skipped.
1184
1185 If an unqualified address begins with '\', just skip that character. This gives
1186 compatibility with Sendmail's use of \ to prevent looping. Exim has its own
1187 loop prevention scheme which handles other cases too - see the code in
1188 route_address().
1189
1190 An "address" can be a specification of a file or a pipe; the latter may often
1191 need to be quoted because it may contain spaces, but we don't want to retain
1192 the quotes. Quotes may appear in normal addresses too, and should be retained.
1193 We can distinguish between these cases, because in addresses, quotes are used
1194 only for parts of the address, not the whole thing. Therefore, we remove quotes
1195 from items when they entirely enclose them, but not otherwise.
1196
1197 An "address" can also be of the form :include:pathname to include a list of
1198 addresses contained in the specified file.
1199
1200 Any unqualified addresses are qualified with and rewritten if necessary, via
1201 the rewrite_address() function.
1202
1203 Arguments:
1204   s                the list of addresses (typically a complete
1205                      .forward file or a list of entries in an alias file)
1206   options          option bits for permitting or denying various special cases;
1207                      not all bits are relevant here - some are for filter
1208                      files; those we use here are:
1209                        RDO_DEFER
1210                        RDO_FREEZE
1211                        RDO_FAIL
1212                        RDO_BLACKHOLE
1213                        RDO_REWRITE
1214                        RDO_INCLUDE
1215   anchor           where to hang the chain of newly-created addresses. This
1216                      should be initialized to NULL.
1217   error            where to return an error text
1218   incoming domain  domain of the incoming address; used to qualify unqualified
1219                      local parts preceded by \
1220   directory        if NULL, no checks are done on :include: files
1221                    otherwise, included file names must start with the given
1222                      directory
1223   syntax_errors    if not NULL, it carries on after syntax errors in addresses,
1224                      building up a list of errors as error blocks chained on
1225                      here.
1226
1227 Returns:      FF_DELIVERED      addresses extracted
1228               FF_NOTDELIVERED   no addresses extracted, but no errors
1229               FF_BLACKHOLE      :blackhole:
1230               FF_DEFER          :defer:
1231               FF_FAIL           :fail:
1232               FF_INCLUDEFAIL    some problem with :include:; *error set
1233               FF_ERROR          other problems; *error is set
1234 */
1235
1236 int
1237 parse_forward_list(uschar *s, int options, address_item **anchor,
1238   uschar **error, uschar *incoming_domain, uschar *directory,
1239   error_block **syntax_errors)
1240 {
1241 int count = 0;
1242
1243 DEBUG(D_route) debug_printf("parse_forward_list: %s\n", s);
1244
1245 for (;;)
1246   {
1247   int len;
1248   int special = 0;
1249   int specopt = 0;
1250   int specbit = 0;
1251   uschar *ss, *nexts;
1252   address_item *addr;
1253   BOOL inquote = FALSE;
1254
1255   for (;;)
1256     {
1257     while (isspace(*s) || *s == ',') s++;
1258     if (*s == '#') { while (*s != 0 && *s != '\n') s++; } else break;
1259     }
1260
1261   /* When we reach the end of the list, we return FF_DELIVERED if any child
1262   addresses have been generated. If nothing has been generated, there are two
1263   possibilities: either the list is really empty, or there were syntax errors
1264   that are being skipped. (If syntax errors are not being skipped, an FF_ERROR
1265   return is generated on hitting a syntax error and we don't get here.) For a
1266   truly empty list we return FF_NOTDELIVERED so that the router can decline.
1267   However, if the list is empty only because syntax errors were skipped, we
1268   return FF_DELIVERED. */
1269
1270   if (*s == 0)
1271     {
1272     return (count > 0 || (syntax_errors != NULL && *syntax_errors != NULL))?
1273       FF_DELIVERED : FF_NOTDELIVERED;
1274
1275     /* This previous code returns FF_ERROR if nothing is generated but a
1276     syntax error has been skipped. I now think it is the wrong approach, but
1277     have left this here just in case, and for the record. */
1278
1279     #ifdef NEVER
1280     if (count > 0) return FF_DELIVERED;   /* Something was generated */
1281
1282     if (syntax_errors == NULL ||          /* Not skipping syntax errors, or */
1283        *syntax_errors == NULL)            /*   we didn't actually skip any */
1284       return FF_NOTDELIVERED;
1285
1286     *error = string_sprintf("no addresses generated: syntax error in %s: %s",
1287        (*syntax_errors)->text2, (*syntax_errors)->text1);
1288     return FF_ERROR;
1289     #endif
1290
1291     }
1292
1293   /* Find the end of the next address. Quoted strings in addresses may contain
1294   escaped characters; I haven't found a proper specification of .forward or
1295   alias files that mentions the quoting properties, but it seems right to do
1296   the escaping thing in all cases, so use the function that finds the end of an
1297   address. However, don't let a quoted string extend over the end of a line. */
1298
1299   ss = parse_find_address_end(s, TRUE);
1300
1301   /* Remember where we finished, for starting the next one. */
1302
1303   nexts = ss;
1304
1305   /* Remove any trailing spaces; we know there's at least one non-space. */
1306
1307   while (isspace((ss[-1]))) ss--;
1308
1309   /* We now have s->start and ss->end of the next address. Remove quotes
1310   if they completely enclose, remembering the address started with a quote
1311   for handling pipes and files. Another round of removal of leading and
1312   trailing spaces is then required. */
1313
1314   if (*s == '\"' && ss[-1] == '\"')
1315     {
1316     s++;
1317     ss--;
1318     inquote = TRUE;
1319     while (s < ss && isspace(*s)) s++;
1320     while (ss > s && isspace((ss[-1]))) ss--;
1321     }
1322
1323   /* Set up the length of the address. */
1324
1325   len = ss - s;
1326
1327   DEBUG(D_route)
1328     {
1329     int save = s[len];
1330     s[len] = 0;
1331     debug_printf("extract item: %s\n", s);
1332     s[len] = save;
1333     }
1334
1335   /* Handle special addresses if permitted. If the address is :unknown:
1336   ignore it - this is for backward compatibility with old alias files. You
1337   don't need to use it nowadays - just generate an empty string. For :defer:,
1338   :blackhole:, or :fail: we have to set up the error message and give up right
1339   away. */
1340
1341   if (Ustrncmp(s, ":unknown:", len) == 0)
1342     {
1343     s = nexts;
1344     continue;
1345     }
1346
1347   if      (Ustrncmp(s, ":defer:", 7) == 0)
1348     { special = FF_DEFER; specopt = RDO_DEFER; }  /* specbit is 0 */
1349   else if (Ustrncmp(s, ":blackhole:", 11) == 0)
1350     { special = FF_BLACKHOLE; specopt = specbit = RDO_BLACKHOLE; }
1351   else if (Ustrncmp(s, ":fail:", 6) == 0)
1352     { special = FF_FAIL; specopt = RDO_FAIL; }  /* specbit is 0 */
1353
1354   if (special != 0)
1355     {
1356     uschar *ss = Ustrchr(s+1, ':') + 1;
1357     if ((options & specopt) == specbit)
1358       {
1359       *error = string_sprintf("\"%.*s\" is not permitted", len, s);
1360       return FF_ERROR;
1361       }
1362     while (*ss != 0 && isspace(*ss)) ss++;
1363     while (s[len] != 0 && s[len] != '\n') len++;
1364     s[len] = 0;
1365     *error = string_copy(ss);
1366     return special;
1367     }
1368
1369   /* If the address is of the form :include:pathname, read the file, and call
1370   this function recursively to extract the addresses from it. If directory is
1371   NULL, do no checks. Otherwise, insist that the file name starts with the
1372   given directory and is a regular file. */
1373
1374   if (Ustrncmp(s, ":include:", 9) == 0)
1375     {
1376     uschar *filebuf;
1377     uschar filename[256];
1378     uschar *t = s+9;
1379     int flen = len - 9;
1380     int frc;
1381     struct stat statbuf;
1382     address_item *last;
1383     FILE *f;
1384
1385     while (flen > 0 && isspace(*t)) { t++; flen--; }
1386
1387     if (flen <= 0)
1388       {
1389       *error = string_sprintf("file name missing after :include:");
1390       return FF_ERROR;
1391       }
1392
1393     if (flen > 255)
1394       {
1395       *error = string_sprintf("included file name \"%s\" is too long", t);
1396       return FF_ERROR;
1397       }
1398
1399     Ustrncpy(filename, t, flen);
1400     filename[flen] = 0;
1401
1402     /* Insist on absolute path */
1403
1404     if (filename[0]!= '/')
1405       {
1406       *error = string_sprintf("included file \"%s\" is not an absolute path",
1407         filename);
1408       return FF_ERROR;
1409       }
1410
1411     /* Check if include is permitted */
1412
1413     if ((options & RDO_INCLUDE) != 0)
1414       {
1415       *error = US"included files not permitted";
1416       return FF_ERROR;
1417       }
1418
1419     /* Check file name if required */
1420
1421     if (directory != NULL)
1422       {
1423       int len = Ustrlen(directory);
1424       uschar *p = filename + len;
1425
1426       if (Ustrncmp(filename, directory, len) != 0 || *p != '/')
1427         {
1428         *error = string_sprintf("included file %s is not in directory %s",
1429           filename, directory);
1430         return FF_ERROR;
1431         }
1432
1433       /* It is necessary to check that every component inside the directory
1434       is NOT a symbolic link, in order to keep the file inside the directory.
1435       This is mighty tedious. It is also not totally foolproof in that it
1436       leaves the possibility of a race attack, but I don't know how to do
1437       any better. */
1438
1439       while (*p != 0)
1440         {
1441         int temp;
1442         while (*(++p) != 0 && *p != '/');
1443         temp = *p;
1444         *p = 0;
1445         if (Ulstat(filename, &statbuf) != 0)
1446           {
1447           *error = string_sprintf("failed to stat %s (component of included "
1448             "file)", filename);
1449           *p = temp;
1450           return FF_ERROR;
1451           }
1452
1453         *p = temp;
1454
1455         if ((statbuf.st_mode & S_IFMT) == S_IFLNK)
1456           {
1457           *error = string_sprintf("included file %s in the %s directory "
1458             "involves a symbolic link", filename, directory);
1459           return FF_ERROR;
1460           }
1461         }
1462       }
1463
1464     /* Open and stat the file */
1465
1466     if ((f = Ufopen(filename, "rb")) == NULL)
1467       {
1468       *error = string_open_failed(errno, "included file %s", filename);
1469       return FF_INCLUDEFAIL;
1470       }
1471
1472     if (fstat(fileno(f), &statbuf) != 0)
1473       {
1474       *error = string_sprintf("failed to stat included file %s: %s",
1475         filename, strerror(errno));
1476       (void)fclose(f);
1477       return FF_INCLUDEFAIL;
1478       }
1479
1480     /* If directory was checked, double check that we opened a regular file */
1481
1482     if (directory != NULL && (statbuf.st_mode & S_IFMT) != S_IFREG)
1483       {
1484       *error = string_sprintf("included file %s is not a regular file in "
1485         "the %s directory", filename, directory);
1486       return FF_ERROR;
1487       }
1488
1489     /* Get a buffer and read the contents */
1490
1491     if (statbuf.st_size > MAX_INCLUDE_SIZE)
1492       {
1493       *error = string_sprintf("included file %s is too big (max %d)",
1494         filename, MAX_INCLUDE_SIZE);
1495       return FF_ERROR;
1496       }
1497
1498     filebuf = store_get(statbuf.st_size + 1);
1499     if (fread(filebuf, 1, statbuf.st_size, f) != statbuf.st_size)
1500       {
1501       *error = string_sprintf("error while reading included file %s: %s",
1502         filename, strerror(errno));
1503       (void)fclose(f);
1504       return FF_ERROR;
1505       }
1506     filebuf[statbuf.st_size] = 0;
1507     (void)fclose(f);
1508
1509     addr = NULL;
1510     frc = parse_forward_list(filebuf, options, &addr,
1511       error, incoming_domain, directory, syntax_errors);
1512     if (frc != FF_DELIVERED && frc != FF_NOTDELIVERED) return frc;
1513
1514     if (addr != NULL)
1515       {
1516       last = addr;
1517       while (last->next != NULL) { count++; last = last->next; }
1518       last->next = *anchor;
1519       *anchor = addr;
1520       count++;
1521       }
1522     }
1523
1524   /* Else (not :include:) ensure address is syntactically correct and fully
1525   qualified if not a pipe or a file, removing a leading \ if present on an
1526   unqualified address. For pipes and files we must handle quoting. It's
1527   not quite clear exactly what to do for partially quoted things, but the
1528   common case of having the whole thing in quotes is straightforward. If this
1529   was the case, inquote will have been set TRUE above and the quotes removed.
1530
1531   There is a possible ambiguity over addresses whose local parts start with
1532   a vertical bar or a slash, and the latter do in fact occur, thanks to X.400.
1533   Consider a .forward file that contains the line
1534
1535      /X=xxx/Y=xxx/OU=xxx/@some.gate.way
1536
1537   Is this a file or an X.400 address? Does it make any difference if it is in
1538   quotes? On the grounds that file names of this type are rare, Exim treats
1539   something that parses as an RFC 822 address and has a domain as an address
1540   rather than a file or a pipe. This is also how an address such as the above
1541   would be treated if it came in from outside. */
1542
1543   else
1544     {
1545     int start, end, domain;
1546     uschar *recipient = NULL;
1547     int save = s[len];
1548     s[len] = 0;
1549
1550     /* If it starts with \ and the rest of it parses as a valid mail address
1551     without a domain, carry on with that address, but qualify it with the
1552     incoming domain. Otherwise arrange for the address to fall through,
1553     causing an error message on the re-parse. */
1554
1555     if (*s == '\\')
1556       {
1557       recipient =
1558         parse_extract_address(s+1, error, &start, &end, &domain, FALSE);
1559       if (recipient != NULL)
1560         recipient = (domain != 0)? NULL :
1561           string_sprintf("%s@%s", recipient, incoming_domain);
1562       }
1563
1564     /* Try parsing the item as an address. */
1565
1566     if (recipient == NULL) recipient =
1567       parse_extract_address(s, error, &start, &end, &domain, FALSE);
1568
1569     /* If item starts with / or | and is not a valid address, or there
1570     is no domain, treat it as a file or pipe. If it was a quoted item,
1571     remove the quoting occurrences of \ within it. */
1572
1573     if ((*s == '|' || *s == '/') && (recipient == NULL || domain == 0))
1574       {
1575       uschar *t = store_get(Ustrlen(s) + 1);
1576       uschar *p = t;
1577       uschar *q = s;
1578       while (*q != 0)
1579         {
1580         if (inquote)
1581           {
1582           *p++ = (*q == '\\')? *(++q) : *q;
1583           q++;
1584           }
1585         else *p++ = *q++;
1586         }
1587       *p = 0;
1588       addr = deliver_make_addr(t, TRUE);
1589       setflag(addr, af_pfr);                   /* indicates pipe/file/reply */
1590       if (*s != '|') setflag(addr, af_file);   /* indicates file */
1591       }
1592
1593     /* Item must be an address. Complain if not, else qualify, rewrite and set
1594     up the control block. It appears that people are in the habit of using
1595     empty addresses but with comments as a way of putting comments into
1596     alias and forward files. Therefore, ignore the error "empty address".
1597     Mailing lists might want to tolerate syntax errors; there is therefore
1598     an option to do so. */
1599
1600     else
1601       {
1602       if (recipient == NULL)
1603         {
1604         if (Ustrcmp(*error, "empty address") == 0)
1605           {
1606           *error = NULL;
1607           s[len] = save;
1608           s = nexts;
1609           continue;
1610           }
1611
1612         if (syntax_errors != NULL)
1613           {
1614           error_block *e = store_get(sizeof(error_block));
1615           error_block *last = *syntax_errors;
1616           if (last == NULL) *syntax_errors = e; else
1617             {
1618             while (last->next != NULL) last = last->next;
1619             last->next = e;
1620             }
1621           e->next = NULL;
1622           e->text1 = *error;
1623           e->text2 = string_copy(s);
1624           s[len] = save;
1625           s = nexts;
1626           continue;
1627           }
1628         else
1629           {
1630           *error = string_sprintf("%s in \"%s\"", *error, s);
1631           s[len] = save;   /* _after_ using it for *error */
1632           return FF_ERROR;
1633           }
1634         }
1635
1636       /* Address was successfully parsed. Rewrite, and then make an address
1637       block. */
1638
1639       recipient = ((options & RDO_REWRITE) != 0)?
1640         rewrite_address(recipient, TRUE, FALSE, global_rewrite_rules,
1641           rewrite_existflags) :
1642         rewrite_address_qualify(recipient, TRUE);
1643       addr = deliver_make_addr(recipient, TRUE);  /* TRUE => copy recipient */
1644       }
1645
1646     /* Restore the final character in the original data, and add to the
1647     output chain. */
1648
1649     s[len] = save;
1650     addr->next = *anchor;
1651     *anchor = addr;
1652     count++;
1653     }
1654
1655   /* Advance pointer for the next address */
1656
1657   s = nexts;
1658   }
1659 }
1660
1661
1662
1663 /*************************************************
1664 *            Extract a Message-ID                *
1665 *************************************************/
1666
1667 /* This function is used to extract message ids from In-Reply-To: and
1668 References: header lines.
1669
1670 Arguments:
1671   str          pointer to the start of the message-id
1672   yield        put pointer to the message id (in dynamic memory) here
1673   error        put error message here on failure
1674
1675 Returns:       points after the processed message-id or NULL on error
1676 */
1677
1678 uschar *
1679 parse_message_id(uschar *str, uschar **yield, uschar **error)
1680 {
1681 uschar *domain = NULL;
1682 uschar *id;
1683
1684 str = skip_comment(str);
1685 if (*str != '<')
1686   {
1687   *error = US"Missing '<' before message-id";
1688   return NULL;
1689   }
1690
1691 /* Getting a block the size of the input string will definitely be sufficient
1692 for the answer, but it may also be very long if we are processing a header
1693 line. Therefore, take care to release unwanted store afterwards. */
1694
1695 id = *yield = store_get(Ustrlen(str) + 1);
1696 *id++ = *str++;
1697
1698 str = read_addr_spec(str, id, '>', error, &domain);
1699
1700 if (*error == NULL)
1701   {
1702   if (*str != '>') *error = US"Missing '>' after message-id";
1703     else if (domain == NULL) *error = US"domain missing in message-id";
1704   }
1705
1706 if (*error != NULL)
1707   {
1708   store_reset(*yield);
1709   return NULL;
1710   }
1711
1712 while (*id != 0) id++;
1713 *id++ = *str++;
1714 *id++ = 0;
1715 store_reset(id);
1716
1717 str = skip_comment(str);
1718 return str;
1719 }
1720
1721
1722
1723
1724 /*************************************************
1725 **************************************************
1726 *             Stand-alone test program           *
1727 **************************************************
1728 *************************************************/
1729
1730 #if defined STAND_ALONE
1731 int main(void)
1732 {
1733 int start, end, domain;
1734 uschar buffer[1024];
1735 uschar outbuff[1024];
1736
1737 big_buffer = store_malloc(big_buffer_size);
1738
1739 /* strip_trailing_dot = TRUE; */
1740 allow_domain_literals = TRUE;
1741
1742 printf("Testing parse_fix_phrase\n");
1743
1744 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
1745   {
1746   buffer[Ustrlen(buffer)-1] = 0;
1747   if (buffer[0] == 0) break;
1748   printf("%s\n", CS parse_fix_phrase(buffer, Ustrlen(buffer), outbuff,
1749     sizeof(outbuff)));
1750   }
1751
1752 printf("Testing parse_extract_address without group syntax and without UTF-8\n");
1753
1754 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
1755   {
1756   uschar *out;
1757   uschar *errmess;
1758   buffer[Ustrlen(buffer) - 1] = 0;
1759   if (buffer[0] == 0) break;
1760   out = parse_extract_address(buffer, &errmess, &start, &end, &domain, FALSE);
1761   if (out == NULL) printf("*** bad address: %s\n", errmess); else
1762     {
1763     uschar extract[1024];
1764     Ustrncpy(extract, buffer+start, end-start);
1765     extract[end-start] = 0;
1766     printf("%s %d %d %d \"%s\"\n", out, start, end, domain, extract);
1767     }
1768   }
1769
1770 printf("Testing parse_extract_address without group syntax but with UTF-8\n");
1771
1772 allow_utf8_domains = TRUE;
1773 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
1774   {
1775   uschar *out;
1776   uschar *errmess;
1777   buffer[Ustrlen(buffer) - 1] = 0;
1778   if (buffer[0] == 0) break;
1779   out = parse_extract_address(buffer, &errmess, &start, &end, &domain, FALSE);
1780   if (out == NULL) printf("*** bad address: %s\n", errmess); else
1781     {
1782     uschar extract[1024];
1783     Ustrncpy(extract, buffer+start, end-start);
1784     extract[end-start] = 0;
1785     printf("%s %d %d %d \"%s\"\n", out, start, end, domain, extract);
1786     }
1787   }
1788 allow_utf8_domains = FALSE;
1789
1790 printf("Testing parse_extract_address with group syntax\n");
1791
1792 parse_allow_group = TRUE;
1793 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
1794   {
1795   uschar *out;
1796   uschar *errmess;
1797   uschar *s;
1798   buffer[Ustrlen(buffer) - 1] = 0;
1799   if (buffer[0] == 0) break;
1800   s = buffer;
1801   while (*s != 0)
1802     {
1803     uschar *ss = parse_find_address_end(s, FALSE);
1804     int terminator = *ss;
1805     *ss = 0;
1806     out = parse_extract_address(buffer, &errmess, &start, &end, &domain, FALSE);
1807     *ss = terminator;
1808
1809     if (out == NULL) printf("*** bad address: %s\n", errmess); else
1810       {
1811       uschar extract[1024];
1812       Ustrncpy(extract, buffer+start, end-start);
1813       extract[end-start] = 0;
1814       printf("%s %d %d %d \"%s\"\n", out, start, end, domain, extract);
1815       }
1816
1817     s = ss + (terminator? 1:0);
1818     while (isspace(*s)) s++;
1819     }
1820   }
1821
1822 printf("Testing parse_find_at\n");
1823
1824 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
1825   {
1826   uschar *s;
1827   buffer[Ustrlen(buffer)-1] = 0;
1828   if (buffer[0] == 0) break;
1829   s = parse_find_at(buffer);
1830   if (s == NULL) printf("no @ found\n");
1831     else printf("offset = %d\n", s - buffer);
1832   }
1833
1834 printf("Testing parse_extract_addresses\n");
1835
1836 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
1837   {
1838   uschar *errmess;
1839   int extracted;
1840   address_item *anchor = NULL;
1841   buffer[Ustrlen(buffer) - 1] = 0;
1842   if (buffer[0] == 0) break;
1843   if ((extracted = parse_forward_list(buffer, -1, &anchor,
1844       &errmess, US"incoming.domain", NULL, NULL)) == FF_DELIVERED)
1845     {
1846     while (anchor != NULL)
1847       {
1848       address_item *addr = anchor;
1849       anchor = anchor->next;
1850       printf("%d %s\n", testflag(addr, af_pfr), addr->address);
1851       }
1852     }
1853   else printf("Failed: %d %s\n", extracted, errmess);
1854   }
1855
1856 printf("Testing parse_message_id\n");
1857
1858 while (Ufgets(buffer, sizeof(buffer), stdin) != NULL)
1859   {
1860   uschar *s, *t, *errmess;
1861   buffer[Ustrlen(buffer) - 1] = 0;
1862   if (buffer[0] == 0) break;
1863   s = buffer;
1864   while (*s != 0)
1865     {
1866     s = parse_message_id(s, &t, &errmess);
1867     if (errmess != NULL)
1868       {
1869       printf("Failed: %s\n", errmess);
1870       break;
1871       }
1872     printf("%s\n", t);
1873     }
1874   }
1875
1876 return 0;
1877 }
1878
1879 #endif
1880
1881 /* End of parse.c */