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