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