Changed "legit" to "legitimate" in the fakereject message (blame Tony
[exim.git] / src / src / acl.c
1 /* $Cambridge: exim/src/src/acl.c,v 1.16 2005/01/12 14:41:12 ph10 Exp $ */
2
3 /*************************************************
4 *     Exim - an Internet mail transport agent    *
5 *************************************************/
6
7 /* Copyright (c) University of Cambridge 1995 - 2005 */
8 /* See the file NOTICE for conditions of use and distribution. */
9
10 /* Code for handling Access Control Lists (ACLs) */
11
12 #include "exim.h"
13
14
15 /* Default callout timeout */
16
17 #define CALLOUT_TIMEOUT_DEFAULT 30
18
19 /* ACL verb codes - keep in step with the table of verbs that follows */
20
21 enum { ACL_ACCEPT, ACL_DEFER, ACL_DENY, ACL_DISCARD, ACL_DROP, ACL_REQUIRE,
22        ACL_WARN };
23
24 /* ACL verbs */
25
26 static uschar *verbs[] =
27   { US"accept", US"defer", US"deny", US"discard", US"drop", US"require",
28     US"warn" };
29
30 /* For each verb, the condition for which "message" is used */
31
32 static int msgcond[] = { FAIL, OK, OK, FAIL, OK, FAIL, OK };
33
34 /* ACL condition and modifier codes - keep in step with the table that
35 follows. */
36
37 enum { ACLC_ACL, ACLC_AUTHENTICATED,
38 #ifdef EXPERIMENTAL_BRIGHTMAIL
39        ACLC_BMI_OPTIN,
40 #endif
41 ACLC_CONDITION, ACLC_CONTROL,
42 #ifdef WITH_CONTENT_SCAN
43        ACLC_DECODE,
44 #endif
45        ACLC_DELAY,
46 #ifdef WITH_OLD_DEMIME
47        ACLC_DEMIME,
48 #endif        
49        ACLC_DNSLISTS, ACLC_DOMAINS, ACLC_ENCRYPTED, ACLC_ENDPASS,
50        ACLC_HOSTS, ACLC_LOCAL_PARTS, ACLC_LOG_MESSAGE, ACLC_LOGWRITE,
51 #ifdef WITH_CONTENT_SCAN
52        ACLC_MALWARE,
53 #endif
54        ACLC_MESSAGE,
55 #ifdef WITH_CONTENT_SCAN
56        ACLC_MIME_REGEX,
57 #endif
58        ACLC_RECIPIENTS,
59 #ifdef WITH_CONTENT_SCAN
60        ACLC_REGEX,
61 #endif
62        ACLC_SENDER_DOMAINS, ACLC_SENDERS, ACLC_SET,
63 #ifdef WITH_CONTENT_SCAN
64        ACLC_SPAM,       
65 #endif
66 #ifdef EXPERIMENTAL_SPF
67        ACLC_SPF,
68 #endif
69        ACLC_VERIFY };
70
71 /* ACL conditions/modifiers: "delay", "control", "endpass", "message",
72 "log_message", "logwrite", and "set" are modifiers that look like conditions
73 but always return TRUE. They are used for their side effects. */
74
75 static uschar *conditions[] = { US"acl", US"authenticated",
76 #ifdef EXPERIMENTAL_BRIGHTMAIL
77   US"bmi_optin",
78 #endif
79   US"condition",
80   US"control", 
81 #ifdef WITH_CONTENT_SCAN
82   US"decode",
83 #endif
84   US"delay",
85 #ifdef WITH_OLD_DEMIME
86   US"demime",
87 #endif
88   US"dnslists", US"domains", US"encrypted",
89   US"endpass", US"hosts", US"local_parts", US"log_message", US"logwrite",
90 #ifdef WITH_CONTENT_SCAN
91   US"malware",
92 #endif
93   US"message",
94 #ifdef WITH_CONTENT_SCAN
95   US"mime_regex",
96 #endif
97   US"recipients",
98 #ifdef WITH_CONTENT_SCAN
99   US"regex",
100 #endif
101   US"sender_domains", US"senders", US"set",
102 #ifdef WITH_CONTENT_SCAN
103   US"spam",
104 #endif
105 #ifdef EXPERIMENTAL_SPF
106   US"spf",
107 #endif
108   US"verify" };
109   
110 /* ACL control names */
111
112 static uschar *controls[] = { US"error", US"caseful_local_part",
113   US"caselower_local_part", US"enforce_sync", US"no_enforce_sync", US"freeze",
114   US"queue_only", US"submission", US"no_multiline"}; 
115
116 /* Flags to indicate for which conditions /modifiers a string expansion is done
117 at the outer level. In the other cases, expansion already occurs in the
118 checking functions. */
119
120 static uschar cond_expand_at_top[] = {
121   TRUE,    /* acl */
122   FALSE,   /* authenticated */
123 #ifdef EXPERIMENTAL_BRIGHTMAIL
124   TRUE,    /* bmi_optin */
125 #endif  
126   TRUE,    /* condition */
127   TRUE,    /* control */
128 #ifdef WITH_CONTENT_SCAN
129   TRUE,    /* decode */
130 #endif
131   TRUE,    /* delay */
132 #ifdef WITH_OLD_DEMIME
133   TRUE,    /* demime */
134 #endif
135   TRUE,    /* dnslists */
136   FALSE,   /* domains */
137   FALSE,   /* encrypted */
138   TRUE,    /* endpass */
139   FALSE,   /* hosts */
140   FALSE,   /* local_parts */
141   TRUE,    /* log_message */
142   TRUE,    /* logwrite */
143 #ifdef WITH_CONTENT_SCAN
144   TRUE,    /* malware */
145 #endif
146   TRUE,    /* message */
147 #ifdef WITH_CONTENT_SCAN
148   TRUE,    /* mime_regex */
149 #endif
150   FALSE,   /* recipients */
151 #ifdef WITH_CONTENT_SCAN
152   TRUE,    /* regex */
153 #endif
154   FALSE,   /* sender_domains */
155   FALSE,   /* senders */
156   TRUE,    /* set */
157 #ifdef WITH_CONTENT_SCAN
158   TRUE,    /* spam */
159 #endif
160 #ifdef EXPERIMENTAL_SPF
161   TRUE,    /* spf */
162 #endif
163   TRUE     /* verify */
164 };
165
166 /* Flags to identify the modifiers */
167
168 static uschar cond_modifiers[] = {
169   FALSE,   /* acl */
170   FALSE,   /* authenticated */
171 #ifdef EXPERIMENTAL_BRIGHTMAIL
172   TRUE,    /* bmi_optin */
173 #endif  
174   FALSE,   /* condition */
175   TRUE,    /* control */
176 #ifdef WITH_CONTENT_SCAN
177   FALSE,   /* decode */
178 #endif
179   TRUE,    /* delay */
180 #ifdef WITH_OLD_DEMIME
181   FALSE,   /* demime */
182 #endif
183   FALSE,   /* dnslists */
184   FALSE,   /* domains */
185   FALSE,   /* encrypted */
186   TRUE,    /* endpass */
187   FALSE,   /* hosts */
188   FALSE,   /* local_parts */
189   TRUE,    /* log_message */
190   TRUE,    /* logwrite */
191 #ifdef WITH_CONTENT_SCAN
192   FALSE,   /* malware */
193 #endif
194   TRUE,    /* message */
195 #ifdef WITH_CONTENT_SCAN
196   FALSE,   /* mime_regex */
197 #endif
198   FALSE,   /* recipients */
199 #ifdef WITH_CONTENT_SCAN
200   FALSE,   /* regex */
201 #endif
202   FALSE,   /* sender_domains */
203   FALSE,   /* senders */
204   TRUE,    /* set */
205 #ifdef WITH_CONTENT_SCAN
206   FALSE,   /* spam */
207 #endif
208 #ifdef EXPERIMENTAL_SPF
209   FALSE,   /* spf */
210 #endif
211   FALSE    /* verify */
212 };
213
214 /* Bit map vector of which conditions are not allowed at certain times. For
215 each condition, there's a bitmap of dis-allowed times. */
216
217 static unsigned int cond_forbids[] = {
218   0,                                               /* acl */
219    
220   (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_CONNECT)|   /* authenticated */
221     (1<<ACL_WHERE_HELO),
222   
223 #ifdef EXPERIMENTAL_BRIGHTMAIL
224   (1<<ACL_WHERE_AUTH)|                             /* bmi_optin */
225     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
226     (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_MIME)|
227     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|                                       
228     (1<<ACL_WHERE_MAILAUTH)|
229     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
230     (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_PREDATA),
231 #endif
232   
233   0,                                               /* condition */
234   
235   /* Certain types of control are always allowed, so we let it through
236   always and check in the control processing itself */
237   
238   0,                                               /* control */
239   
240 #ifdef WITH_CONTENT_SCAN
241   (1<<ACL_WHERE_AUTH)|                             /* decode */
242     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
243     (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_PREDATA)|
244     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
245     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
246     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
247     (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_RCPT),
248 #endif
249
250   0,                                               /* delay */
251   
252 #ifdef WITH_OLD_DEMIME
253   (1<<ACL_WHERE_AUTH)|                             /* demime */
254     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
255     (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
256     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
257     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
258     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
259     (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_MIME),
260 #endif
261   
262   (1<<ACL_WHERE_NOTSMTP),                          /* dnslists */
263
264   (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_AUTH)|      /* domains */
265     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
266     (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_PREDATA)|
267     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
268     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
269     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
270     (1<<ACL_WHERE_VRFY),
271
272   (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_CONNECT)|   /* encrypted */
273     (1<<ACL_WHERE_HELO),
274      
275   0,                                               /* endpass */
276    
277   (1<<ACL_WHERE_NOTSMTP),                          /* hosts */
278
279   (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_AUTH)|      /* local_parts */
280     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
281     (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_PREDATA)|
282     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
283     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
284     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
285     (1<<ACL_WHERE_VRFY),
286
287   0,                                               /* log_message */
288    
289   0,                                               /* logwrite */
290   
291 #ifdef WITH_CONTENT_SCAN
292   (1<<ACL_WHERE_AUTH)|                             /* malware */
293     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
294     (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
295     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
296     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
297     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
298     (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_MIME),
299 #endif
300
301   0,                                               /* message */
302
303 #ifdef WITH_CONTENT_SCAN
304   (1<<ACL_WHERE_AUTH)|                             /* mime_regex */
305     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
306     (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_PREDATA)|
307     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
308     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
309     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
310     (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_RCPT),
311 #endif
312
313   (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_AUTH)|      /* recipients */
314     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
315     (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_PREDATA)|
316     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
317     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
318     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
319     (1<<ACL_WHERE_VRFY),
320
321 #ifdef WITH_CONTENT_SCAN
322   (1<<ACL_WHERE_AUTH)|                             /* regex */
323     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
324     (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
325     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
326     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
327     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
328     (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_MIME),
329 #endif
330
331   (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)|      /* sender_domains */
332     (1<<ACL_WHERE_HELO)|
333     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
334     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
335     (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY),
336
337   (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)|      /* senders */
338     (1<<ACL_WHERE_HELO)|
339     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
340     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
341     (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY),
342
343   0,                                               /* set */
344
345 #ifdef WITH_CONTENT_SCAN
346   (1<<ACL_WHERE_AUTH)|                             /* spam */
347     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
348     (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
349     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
350     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
351     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
352     (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_MIME),
353 #endif
354
355 #ifdef EXPERIMENTAL_SPF
356   (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)|      /* spf */
357     (1<<ACL_WHERE_HELO)|
358     (1<<ACL_WHERE_MAILAUTH)|
359     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
360     (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY),
361 #endif
362
363   /* Certain types of verify are always allowed, so we let it through
364   always and check in the verify function itself */
365
366   0                                                /* verify */
367 };
368
369
370 /* Return values from decode_control() */
371
372 enum { 
373 #ifdef EXPERIMENTAL_BRIGHTMAIL
374   CONTROL_BMI_RUN,
375 #endif  
376   CONTROL_ERROR, CONTROL_CASEFUL_LOCAL_PART, CONTROL_CASELOWER_LOCAL_PART,
377   CONTROL_ENFORCE_SYNC, CONTROL_NO_ENFORCE_SYNC, CONTROL_FREEZE,
378   CONTROL_QUEUE_ONLY, CONTROL_SUBMISSION,
379 #ifdef WITH_CONTENT_SCAN
380   CONTROL_NO_MBOX_UNSPOOL, 
381 #endif
382   CONTROL_FAKEREJECT, CONTROL_NO_MULTILINE };
383
384 /* Bit map vector of which controls are not allowed at certain times. For
385 each control, there's a bitmap of dis-allowed times. For some, it is easier to
386 specify the negation of a small number of allowed times. */
387
388 static unsigned int control_forbids[] = {
389 #ifdef EXPERIMENTAL_BRIGHTMAIL
390   0,                                               /* bmi_run */
391 #endif
392
393   0,                                               /* error */
394   
395   (unsigned int) 
396   ~(1<<ACL_WHERE_RCPT),                            /* caseful_local_part */
397    
398   (unsigned int) 
399   ~(1<<ACL_WHERE_RCPT),                            /* caselower_local_part */
400    
401   (1<<ACL_WHERE_NOTSMTP),                          /* enforce_sync */
402    
403   (1<<ACL_WHERE_NOTSMTP),                          /* no_enforce_sync */
404    
405   (unsigned int) 
406   ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)|       /* freeze */
407     (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
408     (1<<ACL_WHERE_NOTSMTP)),
409      
410   (unsigned int) 
411   ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)|       /* queue_only */
412     (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
413     (1<<ACL_WHERE_NOTSMTP)),
414      
415   (unsigned int) 
416   ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)|       /* submission */
417     (1<<ACL_WHERE_PREDATA)),                       
418
419 #ifdef WITH_CONTENT_SCAN
420   (unsigned int) 
421   ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)|       /* no_mbox_unspool */
422     (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)),
423 #endif
424
425   (unsigned int) 
426   ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)|       /* fakereject */
427     (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)),
428
429   (1<<ACL_WHERE_NOTSMTP)                           /* no_multiline */
430 };
431
432 /* Structure listing various control arguments, with their characteristics. */
433
434 typedef struct control_def {
435   uschar *name;
436   int    value;                  /* CONTROL_xxx value */
437   BOOL   has_option;             /* Has /option(s) following */
438 } control_def;
439
440 static control_def controls_list[] = {
441 #ifdef EXPERIMENTAL_BRIGHTMAIL
442   { US"bmi_run",                CONTROL_BMI_RUN, FALSE},
443 #endif
444   { US"caseful_local_part",     CONTROL_CASEFUL_LOCAL_PART, FALSE},
445   { US"caselower_local_part",   CONTROL_CASELOWER_LOCAL_PART, FALSE},
446   { US"enforce_sync",           CONTROL_ENFORCE_SYNC, FALSE},
447   { US"freeze",                 CONTROL_FREEZE, FALSE},
448   { US"no_enforce_sync",        CONTROL_NO_ENFORCE_SYNC, FALSE},
449   { US"no_multiline_responses", CONTROL_NO_MULTILINE, FALSE},
450   { US"queue_only",             CONTROL_QUEUE_ONLY, FALSE},
451 #ifdef WITH_CONTENT_SCAN
452   { US"no_mbox_unspool",        CONTROL_NO_MBOX_UNSPOOL, FALSE},
453 #endif
454   { US"fakereject",             CONTROL_FAKEREJECT, TRUE},
455   { US"submission",             CONTROL_SUBMISSION, TRUE}
456   };
457
458 /* Enable recursion between acl_check_internal() and acl_check_condition() */
459
460 static int acl_check_internal(int, address_item *, uschar *, int, uschar **,
461          uschar **);
462
463
464 /*************************************************
465 *         Pick out name from list                *
466 *************************************************/
467
468 /* Use a binary chop method
469
470 Arguments:
471   name        name to find
472   list        list of names
473   end         size of list
474
475 Returns:      offset in list, or -1 if not found
476 */
477
478 static int
479 acl_checkname(uschar *name, uschar **list, int end)
480 {
481 int start = 0;
482
483 while (start < end)
484   {
485   int mid = (start + end)/2;
486   int c = Ustrcmp(name, list[mid]);
487   if (c == 0) return mid;
488   if (c < 0) end = mid; else start = mid + 1;
489   }
490
491 return -1;
492 }
493
494
495 /*************************************************
496 *            Read and parse one ACL              *
497 *************************************************/
498
499 /* This function is called both from readconf in order to parse the ACLs in the
500 configuration file, and also when an ACL is encountered dynamically (e.g. as
501 the result of an expansion). It is given a function to call in order to
502 retrieve the lines of the ACL. This function handles skipping comments and
503 blank lines (where relevant).
504
505 Arguments:
506   func        function to get next line of ACL
507   error       where to put an error message
508
509 Returns:      pointer to ACL, or NULL
510               NULL can be legal (empty ACL); in this case error will be NULL
511 */
512
513 acl_block *
514 acl_read(uschar *(*func)(void), uschar **error)
515 {
516 acl_block *yield = NULL;
517 acl_block **lastp = &yield;
518 acl_block *this = NULL;
519 acl_condition_block *cond;
520 acl_condition_block **condp = NULL;
521 uschar *s;
522
523 *error = NULL;
524
525 while ((s = (*func)()) != NULL)
526   {
527   int v, c;
528   BOOL negated = FALSE;
529   uschar *saveline = s;
530   uschar name[64];
531
532   /* Conditions (but not verbs) are allowed to be negated by an initial
533   exclamation mark. */
534
535   while (isspace(*s)) s++;
536   if (*s == '!')
537     {
538     negated = TRUE;
539     s++;
540     }
541
542   /* Read the name of a verb or a condition, or the start of a new ACL */
543
544   s = readconf_readname(name, sizeof(name), s);
545   if (*s == ':')
546     {
547     if (negated || name[0] == 0)
548       {
549       *error = string_sprintf("malformed ACL name in \"%s\"", saveline);
550       return NULL;
551       }
552     break;
553     }
554
555   /* If a verb is unrecognized, it may be another condition or modifier that
556   continues the previous verb. */
557
558   v = acl_checkname(name, verbs, sizeof(verbs)/sizeof(char *));
559   if (v < 0)
560     {
561     if (this == NULL)
562       {
563       *error = string_sprintf("unknown ACL verb in \"%s\"", saveline);
564       return NULL;
565       }
566     }
567
568   /* New verb */
569
570   else
571     {
572     if (negated)
573       {
574       *error = string_sprintf("malformed ACL line \"%s\"", saveline);
575       return NULL;
576       }
577     this = store_get(sizeof(acl_block));
578     *lastp = this;
579     lastp = &(this->next);
580     this->next = NULL;
581     this->verb = v;
582     this->condition = NULL;
583     condp = &(this->condition);
584     if (*s == 0) continue;               /* No condition on this line */
585     if (*s == '!')
586       {
587       negated = TRUE;
588       s++;
589       }
590     s = readconf_readname(name, sizeof(name), s);  /* Condition name */
591     }
592
593   /* Handle a condition or modifier. */
594
595   c = acl_checkname(name, conditions, sizeof(conditions)/sizeof(char *));
596   if (c < 0)
597     {
598     *error = string_sprintf("unknown ACL condition/modifier in \"%s\"",
599       saveline);
600     return NULL;
601     }
602
603   /* The modifiers may not be negated */
604
605   if (negated && cond_modifiers[c])
606     {
607     *error = string_sprintf("ACL error: negation is not allowed with "
608       "\"%s\"", conditions[c]);
609     return NULL;
610     }
611
612   /* ENDPASS may occur only with ACCEPT or DISCARD. */
613
614   if (c == ACLC_ENDPASS &&
615       this->verb != ACL_ACCEPT &&
616       this->verb != ACL_DISCARD)
617     {
618     *error = string_sprintf("ACL error: \"%s\" is not allowed with \"%s\"",
619       conditions[c], verbs[this->verb]);
620     return NULL;
621     }
622
623   cond = store_get(sizeof(acl_condition_block));
624   cond->next = NULL;
625   cond->type = c;
626   cond->u.negated = negated;
627
628   *condp = cond;
629   condp = &(cond->next);
630
631   /* The "set" modifier is different in that its argument is "name=value"
632   rather than just a value, and we can check the validity of the name, which
633   gives us a variable number to insert into the data block. */
634
635   if (c == ACLC_SET)
636     {
637     if (Ustrncmp(s, "acl_", 4) != 0 || (s[4] != 'c' && s[4] != 'm') ||
638         !isdigit(s[5]) || (!isspace(s[6]) && s[6] != '='))
639       {
640       *error = string_sprintf("unrecognized name after \"set\" in ACL "
641         "modifier \"set %s\"", s);
642       return NULL;
643       }
644
645     cond->u.varnumber = s[5] - '0';
646     if (s[4] == 'm') cond->u.varnumber += ACL_C_MAX;
647     s += 6;
648     while (isspace(*s)) s++;
649     }
650
651   /* For "set", we are now positioned for the data. For the others, only
652   "endpass" has no data */
653
654   if (c != ACLC_ENDPASS)
655     {
656     if (*s++ != '=')
657       {
658       *error = string_sprintf("\"=\" missing after ACL \"%s\" %s", name,
659         cond_modifiers[c]? US"modifier" : US"condition");
660       return NULL;
661       }
662     while (isspace(*s)) s++;
663     cond->arg = string_copy(s);
664     }
665   }
666
667 return yield;
668 }
669
670
671
672 /*************************************************
673 *               Handle warnings                  *
674 *************************************************/
675
676 /* This function is called when a WARN verb's conditions are true. It adds to
677 the message's headers, and/or writes information to the log. In each case, this
678 only happens once (per message for headers, per connection for log).
679
680 Arguments:
681   where          ACL_WHERE_xxxx indicating which ACL this is
682   user_message   message for adding to headers
683   log_message    message for logging, if different
684
685 Returns:         nothing
686 */
687
688 static void
689 acl_warn(int where, uschar *user_message, uschar *log_message)
690 {
691 int hlen;
692
693 if (log_message != NULL && log_message != user_message)
694   {
695   uschar *text;
696   string_item *logged;
697
698   text = string_sprintf("%s Warning: %s",  host_and_ident(TRUE),
699     string_printing(log_message));
700
701   /* If a sender verification has failed, and the log message is "sender verify
702   failed", add the failure message. */
703
704   if (sender_verified_failed != NULL &&
705       sender_verified_failed->message != NULL &&
706       strcmpic(log_message, US"sender verify failed") == 0)
707     text = string_sprintf("%s: %s", text, sender_verified_failed->message);
708
709   /* Search previously logged warnings. They are kept in malloc store so they
710   can be freed at the start of a new message. */
711
712   for (logged = acl_warn_logged; logged != NULL; logged = logged->next)
713     if (Ustrcmp(logged->text, text) == 0) break;
714
715   if (logged == NULL)
716     {
717     int length = Ustrlen(text) + 1;
718     log_write(0, LOG_MAIN, "%s", text);
719     logged = store_malloc(sizeof(string_item) + length);
720     logged->text = (uschar *)logged + sizeof(string_item);
721     memcpy(logged->text, text, length);
722     logged->next = acl_warn_logged;
723     acl_warn_logged = logged;
724     }
725   }
726
727 /* If there's no user message, we are done. */
728
729 if (user_message == NULL) return;
730
731 /* If this isn't a message ACL, we can't do anything with a user message.
732 Log an error. */
733
734 if (where > ACL_WHERE_NOTSMTP)
735   {
736   log_write(0, LOG_MAIN|LOG_PANIC, "ACL \"warn\" with \"message\" setting "
737     "found in a non-message (%s) ACL: cannot specify header lines here: "
738     "message ignored", acl_wherenames[where]);
739   return;
740   }
741
742 /* Treat the user message as a sequence of one or more header lines. */
743
744 hlen = Ustrlen(user_message);
745 if (hlen > 0)
746   {
747   uschar *text, *p, *q;
748
749   /* Add a final newline if not present */
750
751   text = ((user_message)[hlen-1] == '\n')? user_message :
752     string_sprintf("%s\n", user_message);
753
754   /* Loop for multiple header lines, taking care about continuations */
755
756   for (p = q = text; *p != 0; )
757     {
758     uschar *s;
759     int newtype = htype_add_bot;
760     header_line **hptr = &acl_warn_headers;
761
762     /* Find next header line within the string */
763
764     for (;;)
765       {
766       q = Ustrchr(q, '\n');
767       if (*(++q) != ' ' && *q != '\t') break;
768       }
769
770     /* If the line starts with a colon, interpret the instruction for where to
771     add it. This temporarily sets up a new type. */
772
773     if (*p == ':')
774       {
775       if (strncmpic(p, US":after_received:", 16) == 0)
776         {
777         newtype = htype_add_rec;
778         p += 16;
779         }
780       else if (strncmpic(p, US":at_start_rfc:", 14) == 0)
781         {
782         newtype = htype_add_rfc;
783         p += 14;
784         }        
785       else if (strncmpic(p, US":at_start:", 10) == 0)
786         {
787         newtype = htype_add_top;
788         p += 10;
789         }
790       else if (strncmpic(p, US":at_end:", 8) == 0)
791         {
792         newtype = htype_add_bot;
793         p += 8;
794         }
795       while (*p == ' ' || *p == '\t') p++;
796       }
797
798     /* See if this line starts with a header name, and if not, add X-ACL-Warn:
799     to the front of it. */
800
801     for (s = p; s < q - 1; s++)
802       {
803       if (*s == ':' || !isgraph(*s)) break;
804       }
805
806     s = string_sprintf("%s%.*s", (*s == ':')? "" : "X-ACL-Warn: ", q - p, p);
807     hlen = Ustrlen(s);
808
809     /* See if this line has already been added */
810
811     while (*hptr != NULL)
812       {
813       if (Ustrncmp((*hptr)->text, s, hlen) == 0) break;
814       hptr = &((*hptr)->next);
815       }
816
817     /* Add if not previously present */
818
819     if (*hptr == NULL)
820       {
821       header_line *h = store_get(sizeof(header_line));
822       h->text = s;
823       h->next = NULL;
824       h->type = newtype;
825       h->slen = hlen;
826       *hptr = h;
827       hptr = &(h->next);
828       }
829
830     /* Advance for next header line within the string */
831
832     p = q;
833     }
834   }
835 }
836
837
838
839 /*************************************************
840 *         Verify and check reverse DNS           *
841 *************************************************/
842
843 /* Called from acl_verify() below. We look up the host name(s) of the client IP
844 address if this has not yet been done. The host_name_lookup() function checks
845 that one of these names resolves to an address list that contains the client IP
846 address, so we don't actually have to do the check here.
847
848 Arguments:
849   user_msgptr  pointer for user message
850   log_msgptr   pointer for log message
851
852 Returns:       OK        verification condition succeeded
853                FAIL      verification failed
854                DEFER     there was a problem verifying
855 */
856
857 static int
858 acl_verify_reverse(uschar **user_msgptr, uschar **log_msgptr)
859 {
860 int rc;
861
862 user_msgptr = user_msgptr;  /* stop compiler warning */
863
864 /* Previous success */
865
866 if (sender_host_name != NULL) return OK;
867
868 /* Previous failure */
869
870 if (host_lookup_failed)
871   {
872   *log_msgptr = string_sprintf("host lookup failed%s", host_lookup_msg);
873   return FAIL;
874   }
875
876 /* Need to do a lookup */
877
878 HDEBUG(D_acl)
879   debug_printf("looking up host name to force name/address consistency check\n");
880
881 if ((rc = host_name_lookup()) != OK)
882   {
883   *log_msgptr = (rc == DEFER)?
884     US"host lookup deferred for reverse lookup check"
885     :
886     string_sprintf("host lookup failed for reverse lookup check%s",
887       host_lookup_msg);
888   return rc;    /* DEFER or FAIL */
889   }
890
891 host_build_sender_fullhost();
892 return OK;
893 }
894
895
896
897 /*************************************************
898 *     Handle verification (address & other)      *
899 *************************************************/
900
901 /* This function implements the "verify" condition. It is called when
902 encountered in any ACL, because some tests are almost always permitted. Some
903 just don't make sense, and always fail (for example, an attempt to test a host
904 lookup for a non-TCP/IP message). Others are restricted to certain ACLs.
905
906 Arguments:
907   where        where called from
908   addr         the recipient address that the ACL is handling, or NULL
909   arg          the argument of "verify"
910   user_msgptr  pointer for user message
911   log_msgptr   pointer for log message
912   basic_errno  where to put verify errno
913
914 Returns:       OK        verification condition succeeded
915                FAIL      verification failed
916                DEFER     there was a problem verifying
917                ERROR     syntax error
918 */
919
920 static int
921 acl_verify(int where, address_item *addr, uschar *arg,
922   uschar **user_msgptr, uschar **log_msgptr, int *basic_errno)
923 {
924 int sep = '/';
925 int callout = -1;
926 int callout_overall = -1;
927 int callout_connect = -1;
928 int verify_options = 0;
929 int rc;
930 BOOL verify_header_sender = FALSE;
931 BOOL defer_ok = FALSE;
932 BOOL callout_defer_ok = FALSE;
933 BOOL no_details = FALSE;
934 address_item *sender_vaddr = NULL;
935 uschar *verify_sender_address = NULL;
936 uschar *pm_mailfrom = NULL;
937 uschar *se_mailfrom = NULL;
938 uschar *list = arg;
939 uschar *ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size);
940
941 if (ss == NULL) goto BAD_VERIFY;
942
943 /* Handle name/address consistency verification in a separate function. */
944
945 if (strcmpic(ss, US"reverse_host_lookup") == 0)
946   {
947   if (sender_host_address == NULL) return OK;
948   return acl_verify_reverse(user_msgptr, log_msgptr);
949   }
950
951 /* TLS certificate verification is done at STARTTLS time; here we just
952 test whether it was successful or not. (This is for optional verification; for
953 mandatory verification, the connection doesn't last this long.) */
954
955 if (strcmpic(ss, US"certificate") == 0)
956   {
957   if (tls_certificate_verified) return OK;
958   *user_msgptr = US"no verified certificate";
959   return FAIL;
960   }
961
962 /* We can test the result of optional HELO verification */
963
964 if (strcmpic(ss, US"helo") == 0) return helo_verified? OK : FAIL;
965
966 /* Handle header verification options - permitted only after DATA or a non-SMTP
967 message. */
968
969 if (strncmpic(ss, US"header_", 7) == 0)
970   {
971   if (where != ACL_WHERE_DATA && where != ACL_WHERE_NOTSMTP)
972     {
973     *log_msgptr = string_sprintf("cannot check header contents in ACL for %s "
974       "(only possible in ACL for DATA)", acl_wherenames[where]);
975     return ERROR;
976     }
977
978   /* Check that all relevant header lines have the correct syntax. If there is
979   a syntax error, we return details of the error to the sender if configured to
980   send out full details. (But a "message" setting on the ACL can override, as
981   always). */
982
983   if (strcmpic(ss+7, US"syntax") == 0)
984     {
985     int rc = verify_check_headers(log_msgptr);
986     if (rc != OK && smtp_return_error_details && *log_msgptr != NULL)
987       *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
988     return rc;
989     }
990
991   /* Check that there is at least one verifiable sender address in the relevant
992   header lines. This can be followed by callout and defer options, just like
993   sender and recipient. */
994
995   else if (strcmpic(ss+7, US"sender") == 0) verify_header_sender = TRUE;
996
997   /* Unknown verify argument starting with "header_" */
998
999   else goto BAD_VERIFY;
1000   }
1001
1002 /* Otherwise, first item in verify argument must be "sender" or "recipient".
1003 In the case of a sender, this can optionally be followed by an address to use
1004 in place of the actual sender (rare special-case requirement). */
1005
1006 else if (strncmpic(ss, US"sender", 6) == 0)
1007   {
1008   uschar *s = ss + 6;
1009   if (where > ACL_WHERE_NOTSMTP)
1010     {
1011     *log_msgptr = string_sprintf("cannot verify sender in ACL for %s "
1012       "(only possible for MAIL, RCPT, PREDATA, or DATA)",
1013       acl_wherenames[where]);
1014     return ERROR;
1015     }
1016   if (*s == 0)
1017     verify_sender_address = sender_address;
1018   else
1019     {
1020     while (isspace(*s)) s++;
1021     if (*s++ != '=') goto BAD_VERIFY;
1022     while (isspace(*s)) s++;
1023     verify_sender_address = string_copy(s);
1024     }
1025   }
1026 else
1027   {
1028   if (strcmpic(ss, US"recipient") != 0) goto BAD_VERIFY;
1029   if (addr == NULL)
1030     {
1031     *log_msgptr = string_sprintf("cannot verify recipient in ACL for %s "
1032       "(only possible for RCPT)", acl_wherenames[where]);
1033     return ERROR;
1034     }
1035   }
1036
1037 /* Remaining items are optional */
1038
1039 while ((ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size))
1040       != NULL)
1041   {
1042   if (strcmpic(ss, US"defer_ok") == 0) defer_ok = TRUE;
1043   else if (strcmpic(ss, US"no_details") == 0) no_details = TRUE;
1044
1045   /* These two old options are left for backwards compatibility */
1046
1047   else if (strcmpic(ss, US"callout_defer_ok") == 0)
1048     {
1049     callout_defer_ok = TRUE;
1050     if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
1051     }
1052
1053   else if (strcmpic(ss, US"check_postmaster") == 0)
1054      {
1055      pm_mailfrom = US"";
1056      if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
1057      }
1058
1059   /* The callout option has a number of sub-options, comma separated */
1060
1061   else if (strncmpic(ss, US"callout", 7) == 0)
1062     {
1063     callout = CALLOUT_TIMEOUT_DEFAULT;
1064     ss += 7;
1065     if (*ss != 0)
1066       {
1067       while (isspace(*ss)) ss++;
1068       if (*ss++ == '=')
1069         {
1070         int optsep = ',';
1071         uschar *opt;
1072         uschar buffer[256];
1073         while (isspace(*ss)) ss++;
1074         
1075         /* This callout option handling code has become a mess as new options 
1076         have been added in an ad hoc manner. It should be tidied up into some 
1077         kind of table-driven thing. */
1078  
1079         while ((opt = string_nextinlist(&ss, &optsep, buffer, sizeof(buffer)))
1080               != NULL)
1081           {
1082           if (strcmpic(opt, US"defer_ok") == 0) callout_defer_ok = TRUE;
1083           else if (strcmpic(opt, US"no_cache") == 0)
1084              verify_options |= vopt_callout_no_cache;
1085           else if (strcmpic(opt, US"random") == 0)
1086              verify_options |= vopt_callout_random;
1087           else if (strcmpic(opt, US"use_sender") == 0)
1088              verify_options |= vopt_callout_recipsender;
1089           else if (strcmpic(opt, US"use_postmaster") == 0)
1090              verify_options |= vopt_callout_recippmaster;
1091           else if (strcmpic(opt, US"postmaster") == 0) pm_mailfrom = US"";
1092
1093           else if (strncmpic(opt, US"mailfrom", 8) == 0)
1094             {
1095             if (!verify_header_sender)
1096               {
1097               *log_msgptr = string_sprintf("\"mailfrom\" is allowed as a "
1098                 "callout option only for verify=header_sender (detected in ACL "
1099                 "condition \"%s\")", arg);
1100               return ERROR;
1101               }
1102             opt += 8;
1103             while (isspace(*opt)) opt++;
1104             if (*opt++ != '=')
1105               {
1106               *log_msgptr = string_sprintf("'=' expected after "
1107                 "\"mailfrom\" in ACL condition \"%s\"", arg);
1108               return ERROR;
1109               }
1110             while (isspace(*opt)) opt++;
1111             se_mailfrom = string_copy(opt);
1112             }
1113
1114           else if (strncmpic(opt, US"postmaster_mailfrom", 19) == 0)
1115             {
1116             opt += 19;
1117             while (isspace(*opt)) opt++;
1118             if (*opt++ != '=')
1119               {
1120               *log_msgptr = string_sprintf("'=' expected after "
1121                 "\"postmaster_mailfrom\" in ACL condition \"%s\"", arg);
1122               return ERROR;
1123               }
1124             while (isspace(*opt)) opt++;
1125             pm_mailfrom = string_copy(opt);
1126             }
1127
1128           else if (strncmpic(opt, US"maxwait", 7) == 0)
1129             {
1130             opt += 7;
1131             while (isspace(*opt)) opt++;
1132             if (*opt++ != '=')
1133               {
1134               *log_msgptr = string_sprintf("'=' expected after \"maxwait\" in "
1135                 "ACL condition \"%s\"", arg);
1136               return ERROR;
1137               }
1138             while (isspace(*opt)) opt++;
1139             callout_overall = readconf_readtime(opt, 0, FALSE);
1140             if (callout_overall < 0)
1141               {
1142               *log_msgptr = string_sprintf("bad time value in ACL condition "
1143                 "\"verify %s\"", arg);
1144               return ERROR;
1145               }
1146             }
1147           else if (strncmpic(opt, US"connect", 7) == 0)
1148             {
1149             opt += 7;
1150             while (isspace(*opt)) opt++;
1151             if (*opt++ != '=')
1152               {
1153               *log_msgptr = string_sprintf("'=' expected after "
1154                 "\"callout_overaall\" in ACL condition \"%s\"", arg);
1155               return ERROR;
1156               }
1157             while (isspace(*opt)) opt++;
1158             callout_connect = readconf_readtime(opt, 0, FALSE);
1159             if (callout_connect < 0)
1160               {
1161               *log_msgptr = string_sprintf("bad time value in ACL condition "
1162                 "\"verify %s\"", arg);
1163               return ERROR;
1164               }
1165             }
1166           else    /* Plain time is callout connect/command timeout */
1167             {
1168             callout = readconf_readtime(opt, 0, FALSE);
1169             if (callout < 0)
1170               {
1171               *log_msgptr = string_sprintf("bad time value in ACL condition "
1172                 "\"verify %s\"", arg);
1173               return ERROR;
1174               }
1175             }
1176           }
1177         }
1178       else
1179         {
1180         *log_msgptr = string_sprintf("'=' expected after \"callout\" in "
1181           "ACL condition \"%s\"", arg);
1182         return ERROR;
1183         }
1184       }
1185     }
1186
1187   /* Option not recognized */
1188
1189   else
1190     {
1191     *log_msgptr = string_sprintf("unknown option \"%s\" in ACL "
1192       "condition \"verify %s\"", ss, arg);
1193     return ERROR;
1194     }
1195   }
1196
1197 if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster)) ==
1198       (vopt_callout_recipsender|vopt_callout_recippmaster))
1199   {
1200   *log_msgptr = US"only one of use_sender and use_postmaster can be set "
1201     "for a recipient callout";
1202   return ERROR;
1203   }
1204
1205 /* Handle sender-in-header verification. Default the user message to the log
1206 message if giving out verification details. */
1207
1208 if (verify_header_sender)
1209   {
1210   rc = verify_check_header_address(user_msgptr, log_msgptr, callout,
1211     callout_overall, callout_connect, se_mailfrom, pm_mailfrom, verify_options);
1212   if (smtp_return_error_details)
1213     {
1214     if (*user_msgptr == NULL && *log_msgptr != NULL)
1215       *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1216     if (rc == DEFER) acl_temp_details = TRUE;
1217     }
1218   }
1219
1220 /* Handle a sender address. The default is to verify *the* sender address, but
1221 optionally a different address can be given, for special requirements. If the
1222 address is empty, we are dealing with a bounce message that has no sender, so
1223 we cannot do any checking. If the real sender address gets rewritten during
1224 verification (e.g. DNS widening), set the flag to stop it being rewritten again
1225 during message reception.
1226
1227 A list of verified "sender" addresses is kept to try to avoid doing to much
1228 work repetitively when there are multiple recipients in a message and they all
1229 require sender verification. However, when callouts are involved, it gets too
1230 complicated because different recipients may require different callout options.
1231 Therefore, we always do a full sender verify when any kind of callout is
1232 specified. Caching elsewhere, for instance in the DNS resolver and in the
1233 callout handling, should ensure that this is not terribly inefficient. */
1234
1235 else if (verify_sender_address != NULL)
1236   {
1237   if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster))
1238        != 0)
1239     {
1240     *log_msgptr = US"use_sender or use_postmaster cannot be used for a "
1241       "sender verify callout";
1242     return ERROR;
1243     }
1244
1245   sender_vaddr = verify_checked_sender(verify_sender_address);
1246   if (sender_vaddr != NULL &&               /* Previously checked */
1247       callout <= 0)                         /* No callout needed this time */
1248     {
1249     /* If the "routed" flag is set, it means that routing worked before, so
1250     this check can give OK (the saved return code value, if set, belongs to a
1251     callout that was done previously). If the "routed" flag is not set, routing
1252     must have failed, so we use the saved return code. */
1253
1254     if (testflag(sender_vaddr, af_verify_routed)) rc = OK; else
1255       {
1256       rc = sender_vaddr->special_action;
1257       *basic_errno = sender_vaddr->basic_errno;
1258       }
1259     HDEBUG(D_acl) debug_printf("using cached sender verify result\n");
1260     }
1261
1262   /* Do a new verification, and cache the result. The cache is used to avoid
1263   verifying the sender multiple times for multiple RCPTs when callouts are not
1264   specified (see comments above).
1265
1266   The cache is also used on failure to give details in response to the first
1267   RCPT that gets bounced for this reason. However, this can be suppressed by
1268   the no_details option, which sets the flag that says "this detail has already
1269   been sent". The cache normally contains just one address, but there may be
1270   more in esoteric circumstances. */
1271
1272   else
1273     {
1274     BOOL routed = TRUE;
1275     uschar *save_address_data = deliver_address_data;
1276       
1277     sender_vaddr = deliver_make_addr(verify_sender_address, TRUE);
1278     if (no_details) setflag(sender_vaddr, af_sverify_told);
1279     if (verify_sender_address[0] != 0)
1280       {
1281       /* If this is the real sender address, save the unrewritten version
1282       for use later in receive. Otherwise, set a flag so that rewriting the
1283       sender in verify_address() does not update sender_address. */
1284
1285       if (verify_sender_address == sender_address)
1286         sender_address_unrewritten = sender_address;
1287       else
1288         verify_options |= vopt_fake_sender;
1289
1290       /* The recipient, qualify, and expn options are never set in
1291       verify_options. */
1292
1293       rc = verify_address(sender_vaddr, NULL, verify_options, callout,
1294         callout_overall, callout_connect, se_mailfrom, pm_mailfrom, &routed);
1295
1296       HDEBUG(D_acl) debug_printf("----------- end verify ------------\n");
1297
1298       if (rc == OK)
1299         {
1300         if (Ustrcmp(sender_vaddr->address, verify_sender_address) != 0)
1301           {
1302           DEBUG(D_acl) debug_printf("sender %s verified ok as %s\n",
1303             verify_sender_address, sender_vaddr->address);
1304           }
1305         else
1306           {
1307           DEBUG(D_acl) debug_printf("sender %s verified ok\n",
1308             verify_sender_address);
1309           }
1310         }
1311       else *basic_errno = sender_vaddr->basic_errno;
1312       }
1313     else rc = OK;  /* Null sender */
1314
1315     /* Cache the result code */
1316
1317     if (routed) setflag(sender_vaddr, af_verify_routed);
1318     if (callout > 0) setflag(sender_vaddr, af_verify_callout);
1319     sender_vaddr->special_action = rc;
1320     sender_vaddr->next = sender_verified_list;
1321     sender_verified_list = sender_vaddr;
1322     
1323     /* Restore the recipient address data, which might have been clobbered by 
1324     the sender verification. */
1325   
1326     deliver_address_data = save_address_data;
1327     }
1328     
1329   /* Put the sender address_data value into $sender_address_data */
1330
1331   sender_address_data = sender_vaddr->p.address_data; 
1332   }
1333
1334 /* A recipient address just gets a straightforward verify; again we must handle
1335 the DEFER overrides. */
1336
1337 else
1338   {
1339   address_item addr2;
1340
1341   /* We must use a copy of the address for verification, because it might
1342   get rewritten. */
1343
1344   addr2 = *addr;
1345   rc = verify_address(&addr2, NULL, verify_options|vopt_is_recipient, callout,
1346     callout_overall, callout_connect, se_mailfrom, pm_mailfrom, NULL);
1347   HDEBUG(D_acl) debug_printf("----------- end verify ------------\n");
1348   *log_msgptr = addr2.message;
1349   *user_msgptr = addr2.user_message;
1350   *basic_errno = addr2.basic_errno;
1351
1352   /* Make $address_data visible */
1353   deliver_address_data = addr2.p.address_data;
1354   }
1355
1356 /* We have a result from the relevant test. Handle defer overrides first. */
1357
1358 if (rc == DEFER && (defer_ok ||
1359    (callout_defer_ok && *basic_errno == ERRNO_CALLOUTDEFER)))
1360   {
1361   HDEBUG(D_acl) debug_printf("verify defer overridden by %s\n",
1362     defer_ok? "defer_ok" : "callout_defer_ok");
1363   rc = OK;
1364   }
1365
1366 /* If we've failed a sender, set up a recipient message, and point
1367 sender_verified_failed to the address item that actually failed. */
1368
1369 if (rc != OK && verify_sender_address != NULL)
1370   {
1371   if (rc != DEFER)
1372     {
1373     *log_msgptr = *user_msgptr = US"Sender verify failed";
1374     }
1375   else if (*basic_errno != ERRNO_CALLOUTDEFER)
1376     {
1377     *log_msgptr = *user_msgptr = US"Could not complete sender verify";
1378     }
1379   else
1380     {
1381     *log_msgptr = US"Could not complete sender verify callout";
1382     *user_msgptr = smtp_return_error_details? sender_vaddr->user_message :
1383       *log_msgptr;
1384     }
1385
1386   sender_verified_failed = sender_vaddr;
1387   }
1388
1389 /* Verifying an address messes up the values of $domain and $local_part,
1390 so reset them before returning if this is a RCPT ACL. */
1391
1392 if (addr != NULL)
1393   {
1394   deliver_domain = addr->domain;
1395   deliver_localpart = addr->local_part;
1396   }
1397 return rc;
1398
1399 /* Syntax errors in the verify argument come here. */
1400
1401 BAD_VERIFY:
1402 *log_msgptr = string_sprintf("expected \"sender[=address]\", \"recipient\", "
1403   "\"header_syntax\" or \"header_sender\" at start of ACL condition "
1404   "\"verify %s\"", arg);
1405 return ERROR;
1406 }
1407
1408
1409
1410
1411 /*************************************************
1412 *        Check argument for control= modifier    *
1413 *************************************************/
1414
1415 /* Called from acl_check_condition() below
1416
1417 Arguments:
1418   arg         the argument string for control=
1419   pptr        set to point to the terminating character
1420   where       which ACL we are in
1421   log_msgptr  for error messages
1422
1423 Returns:      CONTROL_xxx value
1424 */
1425
1426 static int
1427 decode_control(uschar *arg, uschar **pptr, int where, uschar **log_msgptr)
1428 {
1429 int len;
1430 control_def *d;
1431
1432 for (d = controls_list;
1433      d < controls_list + sizeof(controls_list)/sizeof(control_def);
1434      d++)
1435   {
1436   len = Ustrlen(d->name);
1437   if (Ustrncmp(d->name, arg, len) == 0) break;
1438   }
1439
1440 if (d >= controls_list + sizeof(controls_list)/sizeof(control_def) ||
1441    (arg[len] != 0 && (!d->has_option || arg[len] != '/')))
1442   {
1443   *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
1444   return CONTROL_ERROR;
1445   }
1446
1447 *pptr = arg + len;
1448 return d->value;
1449 }
1450
1451
1452
1453 /*************************************************
1454 *   Handle conditions/modifiers on an ACL item   *
1455 *************************************************/
1456
1457 /* Called from acl_check() below.
1458
1459 Arguments:
1460   verb         ACL verb
1461   cb           ACL condition block - if NULL, result is OK
1462   where        where called from
1463   addr         the address being checked for RCPT, or NULL
1464   level        the nesting level
1465   epp          pointer to pass back TRUE if "endpass" encountered
1466                  (applies only to "accept" and "discard")
1467   user_msgptr  user message pointer
1468   log_msgptr   log message pointer
1469   basic_errno  pointer to where to put verify error
1470
1471 Returns:       OK        - all conditions are met
1472                DISCARD   - an "acl" condition returned DISCARD - only allowed
1473                              for "accept" or "discard" verbs
1474                FAIL      - at least one condition fails
1475                FAIL_DROP - an "acl" condition returned FAIL_DROP
1476                DEFER     - can't tell at the moment (typically, lookup defer,
1477                              but can be temporary callout problem)
1478                ERROR     - ERROR from nested ACL or expansion failure or other
1479                              error
1480 */
1481
1482 static int
1483 acl_check_condition(int verb, acl_condition_block *cb, int where,
1484   address_item *addr, int level, BOOL *epp, uschar **user_msgptr,
1485   uschar **log_msgptr, int *basic_errno)
1486 {
1487 uschar *user_message = NULL;
1488 uschar *log_message = NULL;
1489 uschar *p;
1490 int rc = OK;
1491 #ifdef WITH_CONTENT_SCAN
1492 int sep = '/';
1493 #endif
1494
1495 for (; cb != NULL; cb = cb->next)
1496   {
1497   uschar *arg;
1498   int control_type; 
1499
1500   /* The message and log_message items set up messages to be used in
1501   case of rejection. They are expanded later. */
1502
1503   if (cb->type == ACLC_MESSAGE)
1504     {
1505     user_message = cb->arg;
1506     continue;
1507     }
1508
1509   if (cb->type == ACLC_LOG_MESSAGE)
1510     {
1511     log_message = cb->arg;
1512     continue;
1513     }
1514
1515   /* The endpass "condition" just sets a flag to show it occurred. This is
1516   checked at compile time to be on an "accept" or "discard" item. */
1517
1518   if (cb->type == ACLC_ENDPASS)
1519     {
1520     *epp = TRUE;
1521     continue;
1522     }
1523
1524   /* For other conditions and modifiers, the argument is expanded now for some
1525   of them, but not for all, because expansion happens down in some lower level
1526   checking functions in some cases. */
1527
1528   if (cond_expand_at_top[cb->type])
1529     {
1530     arg = expand_string(cb->arg);
1531     if (arg == NULL)
1532       {
1533       if (expand_string_forcedfail) continue;
1534       *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s",
1535         cb->arg, expand_string_message);
1536       return search_find_defer? DEFER : ERROR;
1537       }
1538     }
1539   else arg = cb->arg;
1540
1541   /* Show condition, and expanded condition if it's different */
1542
1543   HDEBUG(D_acl)
1544     {
1545     int lhswidth = 0;
1546     debug_printf("check %s%s %n",
1547       (!cond_modifiers[cb->type] && cb->u.negated)? "!":"",
1548       conditions[cb->type], &lhswidth);
1549
1550     if (cb->type == ACLC_SET)
1551       {
1552       int n = cb->u.varnumber;
1553       int t = (n < ACL_C_MAX)? 'c' : 'm';
1554       if (n >= ACL_C_MAX) n -= ACL_C_MAX;
1555       debug_printf("acl_%c%d ", t, n);
1556       lhswidth += 7;
1557       }
1558
1559     debug_printf("= %s\n", cb->arg);
1560
1561     if (arg != cb->arg)
1562       debug_printf("%.*s= %s\n", lhswidth,
1563       US"                             ", CS arg);
1564     }
1565
1566   /* Check that this condition makes sense at this time */
1567
1568   if ((cond_forbids[cb->type] & (1 << where)) != 0)
1569     {
1570     *log_msgptr = string_sprintf("cannot %s %s condition in %s ACL",
1571       cond_modifiers[cb->type]? "use" : "test",
1572       conditions[cb->type], acl_wherenames[where]);
1573     return ERROR;
1574     }
1575
1576   /* Run the appropriate test for each condition, or take the appropriate
1577   action for the remaining modifiers. */
1578
1579   switch(cb->type)
1580     {
1581     /* A nested ACL that returns "discard" makes sense only for an "accept" or
1582     "discard" verb. */
1583
1584     case ACLC_ACL:
1585     rc = acl_check_internal(where, addr, arg, level+1, user_msgptr, log_msgptr);
1586     if (rc == DISCARD && verb != ACL_ACCEPT && verb != ACL_DISCARD)
1587       {
1588       *log_msgptr = string_sprintf("nested ACL returned \"discard\" for "
1589         "\"%s\" command (only allowed with \"accept\" or \"discard\")",
1590         verbs[verb]);
1591       return ERROR;
1592       }
1593     break;
1594
1595     case ACLC_AUTHENTICATED:
1596     rc = (sender_host_authenticated == NULL)? FAIL :
1597       match_isinlist(sender_host_authenticated, &arg, 0, NULL, NULL, MCL_STRING,
1598         TRUE, NULL);
1599     break;
1600
1601 #ifdef EXPERIMENTAL_BRIGHTMAIL
1602     case ACLC_BMI_OPTIN:
1603       {
1604       int old_pool = store_pool;
1605       store_pool = POOL_PERM;
1606       bmi_current_optin = string_copy(arg);
1607       store_pool = old_pool;
1608       }
1609     break;
1610 #endif
1611
1612     case ACLC_CONDITION:
1613     if (Ustrspn(arg, "0123456789") == Ustrlen(arg))     /* Digits, or empty */
1614       rc = (Uatoi(arg) == 0)? FAIL : OK;
1615     else
1616       rc = (strcmpic(arg, US"no") == 0 ||
1617             strcmpic(arg, US"false") == 0)? FAIL :
1618            (strcmpic(arg, US"yes") == 0 ||
1619             strcmpic(arg, US"true") == 0)? OK : DEFER;
1620     if (rc == DEFER)
1621       *log_msgptr = string_sprintf("invalid \"condition\" value \"%s\"", arg);
1622     break;
1623
1624     case ACLC_CONTROL:
1625     control_type = decode_control(arg, &p, where, log_msgptr);
1626
1627     /* Check if this control makes sense at this time */
1628
1629     if ((control_forbids[control_type] & (1 << where)) != 0)
1630       {
1631       *log_msgptr = string_sprintf("cannot use \"control=%s\" in %s ACL",
1632         controls[control_type], acl_wherenames[where]);
1633       return ERROR;
1634       }                                                     
1635
1636     switch(control_type)
1637       {
1638 #ifdef EXPERIMENTAL_BRIGHTMAIL
1639       case CONTROL_BMI_RUN:
1640       bmi_run = 1;
1641       break;
1642 #endif
1643       
1644       case CONTROL_ERROR:
1645       return ERROR;
1646
1647       case CONTROL_CASEFUL_LOCAL_PART:
1648       deliver_localpart = addr->cc_local_part;
1649       break;
1650
1651       case CONTROL_CASELOWER_LOCAL_PART:
1652       deliver_localpart = addr->lc_local_part;
1653       break;
1654
1655       case CONTROL_ENFORCE_SYNC:
1656       smtp_enforce_sync = TRUE;
1657       break;
1658
1659       case CONTROL_NO_ENFORCE_SYNC:
1660       smtp_enforce_sync = FALSE;
1661       break;
1662
1663 #ifdef WITH_CONTENT_SCAN
1664       case CONTROL_NO_MBOX_UNSPOOL:
1665       no_mbox_unspool = TRUE;
1666       break;
1667 #endif
1668
1669       case CONTROL_NO_MULTILINE:
1670       no_multiline_responses = TRUE;
1671       break;
1672
1673       case CONTROL_FAKEREJECT:
1674       fake_reject = TRUE;
1675       if (*p == '/')
1676         { 
1677         uschar *pp = p + 1;
1678         while (*pp != 0) pp++; 
1679         fake_reject_text = expand_string(string_copyn(p+1, pp-p));
1680         p = pp;
1681         }
1682        else
1683         {
1684         /* Explicitly reset to default string */
1685         fake_reject_text = US"Your message has been rejected but is being kept for evaluation.\nIf it was a legitimate message, it may still be delivered to the target recipient(s).";
1686         }
1687       break;
1688
1689       case CONTROL_FREEZE:
1690       deliver_freeze = TRUE;
1691       deliver_frozen_at = time(NULL);
1692       break;
1693
1694       case CONTROL_QUEUE_ONLY:
1695       queue_only_policy = TRUE;
1696       break;
1697
1698       case CONTROL_SUBMISSION:
1699       submission_mode = TRUE;
1700       while (*p == '/')
1701         { 
1702         if (Ustrncmp(p, "/sender_retain", 14) == 0)
1703           {
1704           p += 14;
1705           active_local_sender_retain = TRUE;
1706           active_local_from_check = FALSE;   
1707           }  
1708         else if (Ustrncmp(p, "/domain=", 8) == 0)
1709           {
1710           uschar *pp = p + 8;
1711           while (*pp != 0 && *pp != '/') pp++; 
1712           submission_domain = string_copyn(p+8, pp-p);
1713           p = pp; 
1714           }
1715         else break;   
1716         }   
1717       if (*p != 0)
1718         {
1719         *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
1720         return ERROR;
1721         }
1722       break;
1723       }
1724     break;
1725
1726 #ifdef WITH_CONTENT_SCAN
1727     case ACLC_DECODE:
1728     rc = mime_decode(&arg);
1729     break;
1730 #endif
1731
1732     case ACLC_DELAY:
1733       {
1734       int delay = readconf_readtime(arg, 0, FALSE);
1735       if (delay < 0)
1736         {
1737         *log_msgptr = string_sprintf("syntax error in argument for \"delay\" "
1738           "modifier: \"%s\" is not a time value", arg);
1739         return ERROR;
1740         }
1741       else
1742         {
1743         HDEBUG(D_acl) debug_printf("delay modifier requests %d-second delay\n",
1744           delay);
1745         if (host_checking)
1746           {
1747           HDEBUG(D_acl)
1748             debug_printf("delay skipped in -bh checking mode\n");
1749           }
1750         else 
1751           {
1752           while (delay > 0) delay = sleep(delay);
1753           } 
1754         }
1755       }
1756     break;
1757
1758 #ifdef WITH_OLD_DEMIME
1759     case ACLC_DEMIME:
1760       rc = demime(&arg);
1761     break;
1762 #endif
1763
1764     case ACLC_DNSLISTS:
1765     rc = verify_check_dnsbl(&arg);
1766     break;
1767
1768     case ACLC_DOMAINS:
1769     rc = match_isinlist(addr->domain, &arg, 0, &domainlist_anchor,
1770       addr->domain_cache, MCL_DOMAIN, TRUE, &deliver_domain_data);
1771     break;
1772
1773     /* The value in tls_cipher is the full cipher name, for example,
1774     TLSv1:DES-CBC3-SHA:168, whereas the values to test for are just the
1775     cipher names such as DES-CBC3-SHA. But program defensively. We don't know
1776     what may in practice come out of the SSL library - which at the time of
1777     writing is poorly documented. */
1778
1779     case ACLC_ENCRYPTED:
1780     if (tls_cipher == NULL) rc = FAIL; else
1781       {
1782       uschar *endcipher = NULL;
1783       uschar *cipher = Ustrchr(tls_cipher, ':');
1784       if (cipher == NULL) cipher = tls_cipher; else
1785         {
1786         endcipher = Ustrchr(++cipher, ':');
1787         if (endcipher != NULL) *endcipher = 0;
1788         }
1789       rc = match_isinlist(cipher, &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL);
1790       if (endcipher != NULL) *endcipher = ':';
1791       }
1792     break;
1793
1794     /* Use verify_check_this_host() instead of verify_check_host() so that
1795     we can pass over &host_data to catch any looked up data. Once it has been
1796     set, it retains its value so that it's still there if another ACL verb
1797     comes through here and uses the cache. However, we must put it into
1798     permanent store in case it is also expected to be used in a subsequent
1799     message in the same SMTP connection. */
1800
1801     case ACLC_HOSTS:
1802     rc = verify_check_this_host(&arg, sender_host_cache, NULL,
1803       (sender_host_address == NULL)? US"" : sender_host_address, &host_data);
1804     if (host_data != NULL) host_data = string_copy_malloc(host_data);
1805     break;
1806
1807     case ACLC_LOCAL_PARTS:
1808     rc = match_isinlist(addr->cc_local_part, &arg, 0,
1809       &localpartlist_anchor, addr->localpart_cache, MCL_LOCALPART, TRUE,
1810       &deliver_localpart_data);
1811     break;
1812
1813     case ACLC_LOGWRITE:
1814       {
1815       int logbits = 0;
1816       uschar *s = arg;
1817       if (*s == ':')
1818         {
1819         s++;
1820         while (*s != ':')
1821           {
1822           if (Ustrncmp(s, "main", 4) == 0)
1823             { logbits |= LOG_MAIN; s += 4; }
1824           else if (Ustrncmp(s, "panic", 5) == 0)
1825             { logbits |= LOG_PANIC; s += 5; }
1826           else if (Ustrncmp(s, "reject", 6) == 0)
1827             { logbits |= LOG_REJECT; s += 6; }
1828           else
1829             {
1830             logbits = LOG_MAIN|LOG_PANIC;
1831             s = string_sprintf(":unknown log name in \"%s\" in "
1832               "\"logwrite\" in %s ACL", arg, acl_wherenames[where]);
1833             }
1834           if (*s == ',') s++;
1835           }
1836         s++;
1837         }
1838       while (isspace(*s)) s++;
1839       if (logbits == 0) logbits = LOG_MAIN;
1840       log_write(0, logbits, "%s", string_printing(s));
1841       }
1842     break;
1843     
1844 #ifdef WITH_CONTENT_SCAN
1845     case ACLC_MALWARE:
1846       {
1847       /* Seperate the regular expression and any optional parameters. */
1848       uschar *ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size);
1849       /* Run the malware backend. */
1850       rc = malware(&ss);
1851       /* Modify return code based upon the existance of options. */
1852       while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
1853             != NULL) {
1854         if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
1855           {
1856           /* FAIL so that the message is passed to the next ACL */
1857           rc = FAIL;
1858           }
1859         }
1860       }
1861     break;
1862
1863     case ACLC_MIME_REGEX:
1864       rc = mime_regex(&arg);
1865     break;
1866 #endif
1867
1868     case ACLC_RECIPIENTS:
1869     rc = match_address_list(addr->address, TRUE, TRUE, &arg, NULL, -1, 0,
1870       &recipient_data);
1871     break;
1872
1873 #ifdef WITH_CONTENT_SCAN
1874    case ACLC_REGEX:
1875       rc = regex(&arg);
1876     break;
1877 #endif
1878
1879     case ACLC_SENDER_DOMAINS:
1880       {
1881       uschar *sdomain;
1882       sdomain = Ustrrchr(sender_address, '@');
1883       sdomain = (sdomain == NULL)? US"" : sdomain + 1;
1884       rc = match_isinlist(sdomain, &arg, 0, &domainlist_anchor,
1885         sender_domain_cache, MCL_DOMAIN, TRUE, NULL);
1886       }
1887     break;
1888
1889     case ACLC_SENDERS:
1890     rc = match_address_list(sender_address, TRUE, TRUE, &arg,
1891       sender_address_cache, -1, 0, &sender_data);
1892     break;
1893
1894     /* Connection variables must persist forever */
1895
1896     case ACLC_SET:
1897       {
1898       int old_pool = store_pool;
1899       if (cb->u.varnumber < ACL_C_MAX) store_pool = POOL_PERM;
1900       acl_var[cb->u.varnumber] = string_copy(arg);
1901       store_pool = old_pool;
1902       }
1903     break;
1904
1905 #ifdef WITH_CONTENT_SCAN
1906     case ACLC_SPAM:
1907       {
1908       /* Seperate the regular expression and any optional parameters. */
1909       uschar *ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size);
1910       /* Run the spam backend. */
1911       rc = spam(&ss);
1912       /* Modify return code based upon the existance of options. */
1913       while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
1914             != NULL) {
1915         if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
1916           {
1917           /* FAIL so that the message is passed to the next ACL */
1918           rc = FAIL;
1919           }
1920         }
1921       }
1922     break;
1923 #endif
1924
1925 #ifdef EXPERIMENTAL_SPF
1926     case ACLC_SPF:
1927       rc = spf_process(&arg, sender_address);
1928     break;
1929 #endif
1930
1931     /* If the verb is WARN, discard any user message from verification, because
1932     such messages are SMTP responses, not header additions. The latter come
1933     only from explicit "message" modifiers. */
1934
1935     case ACLC_VERIFY:
1936     rc = acl_verify(where, addr, arg, user_msgptr, log_msgptr, basic_errno);
1937     if (verb == ACL_WARN) *user_msgptr = NULL;
1938     break;
1939
1940     default:
1941     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown "
1942       "condition %d", cb->type);
1943     break;
1944     }
1945
1946   /* If a condition was negated, invert OK/FAIL. */
1947
1948   if (!cond_modifiers[cb->type] && cb->u.negated)
1949     {
1950     if (rc == OK) rc = FAIL;
1951       else if (rc == FAIL || rc == FAIL_DROP) rc = OK;
1952     }
1953
1954   if (rc != OK) break;   /* Conditions loop */
1955   }
1956
1957
1958 /* If the result is the one for which "message" and/or "log_message" are used,
1959 handle the values of these options. Most verbs have but a single return for
1960 which the messages are relevant, but for "discard", it's useful to have the log
1961 message both when it succeeds and when it fails. Also, for an "accept" that
1962 appears in a QUIT ACL, we want to handle the user message. Since only "accept"
1963 and "warn" are permitted in that ACL, we don't need to test the verb.
1964
1965 These modifiers act in different ways:
1966
1967 "message" is a user message that will be included in an SMTP response. Unless
1968 it is empty, it overrides any previously set user message.
1969
1970 "log_message" is a non-user message, and it adds to any existing non-user
1971 message that is already set.
1972
1973 If there isn't a log message set, we make it the same as the user message. */
1974
1975 if (((rc == FAIL_DROP)? FAIL : rc) == msgcond[verb] ||
1976     (verb == ACL_DISCARD && rc == OK) ||
1977     (where == ACL_WHERE_QUIT))
1978   {
1979   uschar *expmessage;
1980
1981   /* If the verb is "warn", messages generated by conditions (verification or
1982   nested ACLs) are discarded. Only messages specified at this level are used.
1983   However, the value of an existing message is available in $acl_verify_message
1984   during expansions. */
1985
1986   uschar *old_user_msgptr = *user_msgptr;
1987   uschar *old_log_msgptr = (*log_msgptr != NULL)? *log_msgptr : old_user_msgptr;
1988
1989   if (verb == ACL_WARN) *log_msgptr = *user_msgptr = NULL;
1990
1991   if (user_message != NULL)
1992     {
1993     acl_verify_message = old_user_msgptr;
1994     expmessage = expand_string(user_message);
1995     if (expmessage == NULL)
1996       {
1997       if (!expand_string_forcedfail)
1998         log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
1999           user_message, expand_string_message);
2000       }
2001     else if (expmessage[0] != 0) *user_msgptr = expmessage;
2002     }
2003
2004   if (log_message != NULL)
2005     {
2006     acl_verify_message = old_log_msgptr;
2007     expmessage = expand_string(log_message);
2008     if (expmessage == NULL)
2009       {
2010       if (!expand_string_forcedfail)
2011         log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
2012           log_message, expand_string_message);
2013       }
2014     else if (expmessage[0] != 0)
2015       {
2016       *log_msgptr = (*log_msgptr == NULL)? expmessage :
2017         string_sprintf("%s: %s", expmessage, *log_msgptr);
2018       }
2019     }
2020
2021   /* If no log message, default it to the user message */
2022
2023   if (*log_msgptr == NULL) *log_msgptr = *user_msgptr;
2024   }
2025
2026 acl_verify_message = NULL;
2027 return rc;
2028 }
2029
2030
2031
2032
2033
2034 /*************************************************
2035 *        Get line from a literal ACL             *
2036 *************************************************/
2037
2038 /* This function is passed to acl_read() in order to extract individual lines
2039 of a literal ACL, which we access via static pointers. We can destroy the
2040 contents because this is called only once (the compiled ACL is remembered).
2041
2042 This code is intended to treat the data in the same way as lines in the main
2043 Exim configuration file. That is:
2044
2045   . Leading spaces are ignored.
2046
2047   . A \ at the end of a line is a continuation - trailing spaces after the \
2048     are permitted (this is because I don't believe in making invisible things
2049     significant). Leading spaces on the continued part of a line are ignored.
2050
2051   . Physical lines starting (significantly) with # are totally ignored, and
2052     may appear within a sequence of backslash-continued lines.
2053
2054   . Blank lines are ignored, but will end a sequence of continuations.
2055
2056 Arguments: none
2057 Returns:   a pointer to the next line
2058 */
2059
2060
2061 static uschar *acl_text;          /* Current pointer in the text */
2062 static uschar *acl_text_end;      /* Points one past the terminating '0' */
2063
2064
2065 static uschar *
2066 acl_getline(void)
2067 {
2068 uschar *yield;
2069
2070 /* This loop handles leading blank lines and comments. */
2071
2072 for(;;)
2073   {
2074   while (isspace(*acl_text)) acl_text++;   /* Leading spaces/empty lines */
2075   if (*acl_text == 0) return NULL;         /* No more data */
2076   yield = acl_text;                        /* Potential data line */
2077
2078   while (*acl_text != 0 && *acl_text != '\n') acl_text++;
2079
2080   /* If we hit the end before a newline, we have the whole logical line. If
2081   it's a comment, there's no more data to be given. Otherwise, yield it. */
2082
2083   if (*acl_text == 0) return (*yield == '#')? NULL : yield;
2084
2085   /* After reaching a newline, end this loop if the physical line does not
2086   start with '#'. If it does, it's a comment, and the loop continues. */
2087
2088   if (*yield != '#') break;
2089   }
2090
2091 /* This loop handles continuations. We know we have some real data, ending in
2092 newline. See if there is a continuation marker at the end (ignoring trailing
2093 white space). We know that *yield is not white space, so no need to test for
2094 cont > yield in the backwards scanning loop. */
2095
2096 for(;;)
2097   {
2098   uschar *cont;
2099   for (cont = acl_text - 1; isspace(*cont); cont--);
2100
2101   /* If no continuation follows, we are done. Mark the end of the line and
2102   return it. */
2103
2104   if (*cont != '\\')
2105     {
2106     *acl_text++ = 0;
2107     return yield;
2108     }
2109
2110   /* We have encountered a continuation. Skip over whitespace at the start of
2111   the next line, and indeed the whole of the next line or lines if they are
2112   comment lines. */
2113
2114   for (;;)
2115     {
2116     while (*(++acl_text) == ' ' || *acl_text == '\t');
2117     if (*acl_text != '#') break;
2118     while (*(++acl_text) != 0 && *acl_text != '\n');
2119     }
2120
2121   /* We have the start of a continuation line. Move all the rest of the data
2122   to join onto the previous line, and then find its end. If the end is not a
2123   newline, we are done. Otherwise loop to look for another continuation. */
2124
2125   memmove(cont, acl_text, acl_text_end - acl_text);
2126   acl_text_end -= acl_text - cont;
2127   acl_text = cont;
2128   while (*acl_text != 0 && *acl_text != '\n') acl_text++;
2129   if (*acl_text == 0) return yield;
2130   }
2131
2132 /* Control does not reach here */
2133 }
2134
2135
2136
2137
2138
2139 /*************************************************
2140 *        Check access using an ACL               *
2141 *************************************************/
2142
2143 /* This function is called from address_check. It may recurse via
2144 acl_check_condition() - hence the use of a level to stop looping. The ACL is
2145 passed as a string which is expanded. A forced failure implies no access check
2146 is required. If the result is a single word, it is taken as the name of an ACL
2147 which is sought in the global ACL tree. Otherwise, it is taken as literal ACL
2148 text, complete with newlines, and parsed as such. In both cases, the ACL check
2149 is then run. This function uses an auxiliary function for acl_read() to call
2150 for reading individual lines of a literal ACL. This is acl_getline(), which
2151 appears immediately above.
2152
2153 Arguments:
2154   where        where called from
2155   addr         address item when called from RCPT; otherwise NULL
2156   s            the input string; NULL is the same as an empty ACL => DENY
2157   level        the nesting level
2158   user_msgptr  where to put a user error (for SMTP response)
2159   log_msgptr   where to put a logging message (not for SMTP response)
2160
2161 Returns:       OK         access is granted
2162                DISCARD    access is apparently granted...
2163                FAIL       access is denied
2164                FAIL_DROP  access is denied; drop the connection
2165                DEFER      can't tell at the moment
2166                ERROR      disaster
2167 */
2168
2169 static int
2170 acl_check_internal(int where, address_item *addr, uschar *s, int level,
2171   uschar **user_msgptr, uschar **log_msgptr)
2172 {
2173 int fd = -1;
2174 acl_block *acl = NULL;
2175 uschar *acl_name = US"inline ACL";
2176 uschar *ss;
2177
2178 /* Catch configuration loops */
2179
2180 if (level > 20)
2181   {
2182   *log_msgptr = US"ACL nested too deep: possible loop";
2183   return ERROR;
2184   }
2185
2186 if (s == NULL)
2187   {
2188   HDEBUG(D_acl) debug_printf("ACL is NULL: implicit DENY\n");
2189   return FAIL;
2190   }
2191
2192 /* At top level, we expand the incoming string. At lower levels, it has already
2193 been expanded as part of condition processing. */
2194
2195 if (level == 0)
2196   {
2197   ss = expand_string(s);
2198   if (ss == NULL)
2199     {
2200     if (expand_string_forcedfail) return OK;
2201     *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s", s,
2202       expand_string_message);
2203     return ERROR;
2204     }
2205   }
2206 else ss = s;
2207
2208 while (isspace(*ss))ss++;
2209
2210 /* If we can't find a named ACL, the default is to parse it as an inline one.
2211 (Unless it begins with a slash; non-existent files give rise to an error.) */
2212
2213 acl_text = ss;
2214
2215 /* Handle the case of a string that does not contain any spaces. Look for a
2216 named ACL among those read from the configuration, or a previously read file.
2217 It is possible that the pointer to the ACL is NULL if the configuration
2218 contains a name with no data. If not found, and the text begins with '/',
2219 read an ACL from a file, and save it so it can be re-used. */
2220
2221 if (Ustrchr(ss, ' ') == NULL)
2222   {
2223   tree_node *t = tree_search(acl_anchor, ss);
2224   if (t != NULL)
2225     {
2226     acl = (acl_block *)(t->data.ptr);
2227     if (acl == NULL)
2228       {
2229       HDEBUG(D_acl) debug_printf("ACL \"%s\" is empty: implicit DENY\n", ss);
2230       return FAIL;
2231       }
2232     acl_name = string_sprintf("ACL \"%s\"", ss);
2233     HDEBUG(D_acl) debug_printf("using ACL \"%s\"\n", ss);
2234     }
2235
2236   else if (*ss == '/')
2237     {
2238     struct stat statbuf;
2239     fd = Uopen(ss, O_RDONLY, 0);
2240     if (fd < 0)
2241       {
2242       *log_msgptr = string_sprintf("failed to open ACL file \"%s\": %s", ss,
2243         strerror(errno));
2244       return ERROR;
2245       }
2246
2247     if (fstat(fd, &statbuf) != 0)
2248       {
2249       *log_msgptr = string_sprintf("failed to fstat ACL file \"%s\": %s", ss,
2250         strerror(errno));
2251       return ERROR;
2252       }
2253
2254     acl_text = store_get(statbuf.st_size + 1);
2255     acl_text_end = acl_text + statbuf.st_size + 1;
2256
2257     if (read(fd, acl_text, statbuf.st_size) != statbuf.st_size)
2258       {
2259       *log_msgptr = string_sprintf("failed to read ACL file \"%s\": %s",
2260         ss, strerror(errno));
2261       return ERROR;
2262       }
2263     acl_text[statbuf.st_size] = 0;
2264     close(fd);
2265
2266     acl_name = string_sprintf("ACL \"%s\"", ss);
2267     HDEBUG(D_acl) debug_printf("read ACL from file %s\n", ss);
2268     }
2269   }
2270
2271 /* Parse an ACL that is still in text form. If it came from a file, remember it
2272 in the ACL tree, having read it into the POOL_PERM store pool so that it
2273 persists between multiple messages. */
2274
2275 if (acl == NULL)
2276   {
2277   int old_pool = store_pool;
2278   if (fd >= 0) store_pool = POOL_PERM;
2279   acl = acl_read(acl_getline, log_msgptr);
2280   store_pool = old_pool;
2281   if (acl == NULL && *log_msgptr != NULL) return ERROR;
2282   if (fd >= 0)
2283     {
2284     tree_node *t = store_get_perm(sizeof(tree_node) + Ustrlen(ss));
2285     Ustrcpy(t->name, ss);
2286     t->data.ptr = acl;
2287     (void)tree_insertnode(&acl_anchor, t);
2288     }
2289   }
2290
2291 /* Now we have an ACL to use. It's possible it may be NULL. */
2292
2293 while (acl != NULL)
2294   {
2295   int cond;
2296   int basic_errno = 0;
2297   BOOL endpass_seen = FALSE;
2298
2299   *log_msgptr = *user_msgptr = NULL;
2300   acl_temp_details = FALSE;
2301
2302   if (where == ACL_WHERE_QUIT &&
2303       acl->verb != ACL_ACCEPT &&
2304       acl->verb != ACL_WARN)
2305     {
2306     *log_msgptr = string_sprintf("\"%s\" is not allowed in a QUIT ACL",
2307       verbs[acl->verb]);
2308     return ERROR;
2309     }
2310
2311   HDEBUG(D_acl) debug_printf("processing \"%s\"\n", verbs[acl->verb]);
2312
2313   /* Clear out any search error message from a previous check before testing
2314   this condition. */
2315
2316   search_error_message = NULL;
2317   cond = acl_check_condition(acl->verb, acl->condition, where, addr, level,
2318     &endpass_seen, user_msgptr, log_msgptr, &basic_errno);
2319
2320   /* Handle special returns: DEFER causes a return except on a WARN verb;
2321   ERROR always causes a return. */
2322
2323   switch (cond)
2324     {
2325     case DEFER:
2326     HDEBUG(D_acl) debug_printf("%s: condition test deferred\n", verbs[acl->verb]);
2327     if (basic_errno != ERRNO_CALLOUTDEFER)
2328       {
2329       if (search_error_message != NULL && *search_error_message != 0)
2330         *log_msgptr = search_error_message;
2331       if (smtp_return_error_details) acl_temp_details = TRUE;
2332       }
2333     else
2334       {
2335       acl_temp_details = TRUE;
2336       }
2337     if (acl->verb != ACL_WARN) return DEFER;
2338     break;
2339
2340     default:      /* Paranoia */
2341     case ERROR:
2342     HDEBUG(D_acl) debug_printf("%s: condition test error\n", verbs[acl->verb]);
2343     return ERROR;
2344
2345     case OK:
2346     HDEBUG(D_acl) debug_printf("%s: condition test succeeded\n",
2347       verbs[acl->verb]);
2348     break;
2349
2350     case FAIL:
2351     HDEBUG(D_acl) debug_printf("%s: condition test failed\n", verbs[acl->verb]);
2352     break;
2353
2354     /* DISCARD and DROP can happen only from a nested ACL condition, and
2355     DISCARD can happen only for an "accept" or "discard" verb. */
2356
2357     case DISCARD:
2358     HDEBUG(D_acl) debug_printf("%s: condition test yielded \"discard\"\n",
2359       verbs[acl->verb]);
2360     break;
2361
2362     case FAIL_DROP:
2363     HDEBUG(D_acl) debug_printf("%s: condition test yielded \"drop\"\n",
2364       verbs[acl->verb]);
2365     break;
2366     }
2367
2368   /* At this point, cond for most verbs is either OK or FAIL or (as a result of
2369   a nested ACL condition) FAIL_DROP. However, for WARN, cond may be DEFER, and
2370   for ACCEPT and DISCARD, it may be DISCARD after a nested ACL call. */
2371
2372   switch(acl->verb)
2373     {
2374     case ACL_ACCEPT:
2375     if (cond == OK || cond == DISCARD) return cond;
2376     if (endpass_seen)
2377       {
2378       HDEBUG(D_acl) debug_printf("accept: endpass encountered - denying access\n");
2379       return cond;
2380       }
2381     break;
2382
2383     case ACL_DEFER:
2384     if (cond == OK)
2385       {
2386       acl_temp_details = TRUE;
2387       return DEFER;
2388       }
2389     break;
2390
2391     case ACL_DENY:
2392     if (cond == OK) return FAIL;
2393     break;
2394
2395     case ACL_DISCARD:
2396     if (cond == OK || cond == DISCARD) return DISCARD;
2397     if (endpass_seen)
2398       {
2399       HDEBUG(D_acl) debug_printf("discard: endpass encountered - denying access\n");
2400       return cond;
2401       }
2402     break;
2403
2404     case ACL_DROP:
2405     if (cond == OK) return FAIL_DROP;
2406     break;
2407
2408     case ACL_REQUIRE:
2409     if (cond != OK) return cond;
2410     break;
2411
2412     case ACL_WARN:
2413     if (cond == OK)
2414       acl_warn(where, *user_msgptr, *log_msgptr);
2415     else if (cond == DEFER)
2416       acl_warn(where, NULL, string_sprintf("ACL \"warn\" statement skipped: "
2417         "condition test deferred: %s",
2418         (*log_msgptr == NULL)? US"" : *log_msgptr));
2419     *log_msgptr = *user_msgptr = NULL;  /* In case implicit DENY follows */
2420     break;
2421
2422     default:
2423     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown verb %d",
2424       acl->verb);
2425     break;
2426     }
2427
2428   /* Pass to the next ACL item */
2429
2430   acl = acl->next;
2431   }
2432
2433 /* We have reached the end of the ACL. This is an implicit DENY. */
2434
2435 HDEBUG(D_acl) debug_printf("end of %s: implicit DENY\n", acl_name);
2436 return FAIL;
2437 }
2438
2439
2440 /*************************************************
2441 *        Check access using an ACL               *
2442 *************************************************/
2443
2444 /* This is the external interface for ACL checks. It sets up an address and the
2445 expansions for $domain and $local_part when called after RCPT, then calls
2446 acl_check_internal() to do the actual work.
2447
2448 Arguments:
2449   where        ACL_WHERE_xxxx indicating where called from
2450   data_string  RCPT address, or SMTP command argument, or NULL
2451   s            the input string; NULL is the same as an empty ACL => DENY
2452   user_msgptr  where to put a user error (for SMTP response)
2453   log_msgptr   where to put a logging message (not for SMTP response)
2454
2455 Returns:       OK         access is granted by an ACCEPT verb
2456                DISCARD    access is granted by a DISCARD verb
2457                FAIL       access is denied
2458                FAIL_DROP  access is denied; drop the connection
2459                DEFER      can't tell at the moment
2460                ERROR      disaster
2461 */
2462
2463 int
2464 acl_check(int where, uschar *data_string, uschar *s, uschar **user_msgptr,
2465   uschar **log_msgptr)
2466 {
2467 int rc;
2468 address_item adb;
2469 address_item *addr;
2470
2471 *user_msgptr = *log_msgptr = NULL;
2472 sender_verified_failed = NULL;
2473
2474 if (where == ACL_WHERE_RCPT)
2475   {
2476   adb = address_defaults;
2477   addr = &adb;
2478   addr->address = data_string;
2479   if (deliver_split_address(addr) == DEFER)
2480     {
2481     *log_msgptr = US"defer in percent_hack_domains check";
2482     return DEFER;
2483     }
2484   deliver_domain = addr->domain;
2485   deliver_localpart = addr->local_part;
2486   }
2487 else
2488   {
2489   addr = NULL;
2490   smtp_command_argument = data_string;
2491   }
2492
2493 rc = acl_check_internal(where, addr, s, 0, user_msgptr, log_msgptr);
2494
2495 smtp_command_argument = deliver_domain =
2496   deliver_localpart = deliver_address_data = sender_address_data = NULL;
2497
2498 /* A DISCARD response is permitted only for message ACLs, excluding the PREDATA
2499 ACL, which is really in the middle of an SMTP command. */
2500
2501 if (rc == DISCARD)
2502   {
2503   if (where > ACL_WHERE_NOTSMTP || where == ACL_WHERE_PREDATA)
2504     {
2505     log_write(0, LOG_MAIN|LOG_PANIC, "\"discard\" verb not allowed in %s "
2506       "ACL", acl_wherenames[where]);
2507     return ERROR;
2508     }
2509   return DISCARD;
2510   }
2511
2512 /* A DROP response is not permitted from MAILAUTH */
2513
2514 if (rc == FAIL_DROP && where == ACL_WHERE_MAILAUTH)
2515   {
2516   log_write(0, LOG_MAIN|LOG_PANIC, "\"drop\" verb not allowed in %s "
2517     "ACL", acl_wherenames[where]);
2518   return ERROR;
2519   }
2520
2521 /* Before giving an error response, take a look at the length of any user
2522 message, and split it up into multiple lines if possible. */
2523
2524 if (rc != OK && *user_msgptr != NULL && Ustrlen(*user_msgptr) > 75)
2525   {
2526   uschar *s = *user_msgptr = string_copy(*user_msgptr);
2527   uschar *ss = s;
2528
2529   for (;;)
2530     {
2531     int i = 0;
2532     while (i < 75 && *ss != 0 && *ss != '\n') ss++, i++;
2533     if (*ss == 0) break;
2534     if (*ss == '\n')
2535       s = ++ss;
2536     else
2537       {
2538       uschar *t = ss + 1;
2539       uschar *tt = NULL;
2540       while (--t > s + 35)
2541         {
2542         if (*t == ' ')
2543           {
2544           if (t[-1] == ':') { tt = t; break; }
2545           if (tt == NULL) tt = t;
2546           }
2547         }
2548
2549       if (tt == NULL)          /* Can't split behind - try ahead */
2550         {
2551         t = ss + 1;
2552         while (*t != 0)
2553           {
2554           if (*t == ' ' || *t == '\n')
2555             { tt = t; break; }
2556           t++;
2557           }
2558         }
2559
2560       if (tt == NULL) break;   /* Can't find anywhere to split */
2561       *tt = '\n';
2562       s = ss = tt+1;
2563       }
2564     }
2565   }
2566
2567 return rc;
2568 }
2569
2570 /* End of acl.c */