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