ACL: "seen" condition
[exim.git] / src / src / acl.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* Copyright (c) The Exim Maintainers 2020 */
7 /* See the file NOTICE for conditions of use and distribution. */
8
9 /* Code for handling Access Control Lists (ACLs) */
10
11 #include "exim.h"
12
13
14 /* Default callout timeout */
15
16 #define CALLOUT_TIMEOUT_DEFAULT 30
17
18 /* Default quota cache TTLs */
19
20 #define QUOTA_POS_DEFAULT (5*60)
21 #define QUOTA_NEG_DEFAULT (60*60)
22
23
24 /* ACL verb codes - keep in step with the table of verbs that follows */
25
26 enum { ACL_ACCEPT, ACL_DEFER, ACL_DENY, ACL_DISCARD, ACL_DROP, ACL_REQUIRE,
27        ACL_WARN };
28
29 /* ACL verbs */
30
31 static uschar *verbs[] = {
32     [ACL_ACCEPT] =      US"accept",
33     [ACL_DEFER] =       US"defer",
34     [ACL_DENY] =        US"deny",
35     [ACL_DISCARD] =     US"discard",
36     [ACL_DROP] =        US"drop",
37     [ACL_REQUIRE] =     US"require",
38     [ACL_WARN] =        US"warn"
39 };
40
41 /* For each verb, the conditions for which "message" or "log_message" are used
42 are held as a bitmap. This is to avoid expanding the strings unnecessarily. For
43 "accept", the FAIL case is used only after "endpass", but that is selected in
44 the code. */
45
46 static int msgcond[] = {
47   [ACL_ACCEPT] =        BIT(OK) | BIT(FAIL) | BIT(FAIL_DROP),
48   [ACL_DEFER] =         BIT(OK),
49   [ACL_DENY] =          BIT(OK),
50   [ACL_DISCARD] =       BIT(OK) | BIT(FAIL) | BIT(FAIL_DROP),
51   [ACL_DROP] =          BIT(OK),
52   [ACL_REQUIRE] =       BIT(FAIL) | BIT(FAIL_DROP),
53   [ACL_WARN] =          BIT(OK)
54   };
55
56 /* ACL condition and modifier codes - keep in step with the table that
57 follows.
58 down. */
59
60 enum { ACLC_ACL,
61        ACLC_ADD_HEADER,
62        ACLC_AUTHENTICATED,
63 #ifdef EXPERIMENTAL_BRIGHTMAIL
64        ACLC_BMI_OPTIN,
65 #endif
66        ACLC_CONDITION,
67        ACLC_CONTINUE,
68        ACLC_CONTROL,
69 #ifdef EXPERIMENTAL_DCC
70        ACLC_DCC,
71 #endif
72 #ifdef WITH_CONTENT_SCAN
73        ACLC_DECODE,
74 #endif
75        ACLC_DELAY,
76 #ifndef DISABLE_DKIM
77        ACLC_DKIM_SIGNER,
78        ACLC_DKIM_STATUS,
79 #endif
80 #ifdef SUPPORT_DMARC
81        ACLC_DMARC_STATUS,
82 #endif
83        ACLC_DNSLISTS,
84        ACLC_DOMAINS,
85        ACLC_ENCRYPTED,
86        ACLC_ENDPASS,
87        ACLC_HOSTS,
88        ACLC_LOCAL_PARTS,
89        ACLC_LOG_MESSAGE,
90        ACLC_LOG_REJECT_TARGET,
91        ACLC_LOGWRITE,
92 #ifdef WITH_CONTENT_SCAN
93        ACLC_MALWARE,
94 #endif
95        ACLC_MESSAGE,
96 #ifdef WITH_CONTENT_SCAN
97        ACLC_MIME_REGEX,
98 #endif
99        ACLC_QUEUE,
100        ACLC_RATELIMIT,
101        ACLC_RECIPIENTS,
102 #ifdef WITH_CONTENT_SCAN
103        ACLC_REGEX,
104 #endif
105        ACLC_REMOVE_HEADER,
106        ACLC_SEEN,
107        ACLC_SENDER_DOMAINS,
108        ACLC_SENDERS,
109        ACLC_SET,
110 #ifdef WITH_CONTENT_SCAN
111        ACLC_SPAM,
112 #endif
113 #ifdef SUPPORT_SPF
114        ACLC_SPF,
115        ACLC_SPF_GUESS,
116 #endif
117        ACLC_UDPSEND,
118        ACLC_VERIFY };
119
120 /* ACL conditions/modifiers: "delay", "control", "continue", "endpass",
121 "message", "log_message", "log_reject_target", "logwrite", "queue" and "set" are
122 modifiers that look like conditions but always return TRUE. They are used for
123 their side effects.  Do not invent new modifier names that result in one name
124 being the prefix of another; the binary-search in the list will go wrong. */
125
126 typedef struct condition_def {
127   uschar        *name;
128
129 /* Flag to indicate the condition/modifier has a string expansion done
130 at the outer level. In the other cases, expansion already occurs in the
131 checking functions. */
132   BOOL          expand_at_top:1;
133
134   BOOL          is_modifier:1;
135
136 /* Bit map vector of which conditions and modifiers are not allowed at certain
137 times. For each condition and modifier, there's a bitmap of dis-allowed times.
138 For some, it is easier to specify the negation of a small number of allowed
139 times. */
140   unsigned      forbids;
141
142 } condition_def;
143
144 static condition_def conditions[] = {
145   [ACLC_ACL] =                  { US"acl",              FALSE, FALSE,   0 },
146
147   [ACLC_ADD_HEADER] =           { US"add_header",       TRUE, TRUE,
148                                   (unsigned int)
149                                   ~(ACL_BIT_MAIL | ACL_BIT_RCPT |
150                                     ACL_BIT_PREDATA | ACL_BIT_DATA |
151 #ifndef DISABLE_PRDR
152                                     ACL_BIT_PRDR |
153 #endif
154                                     ACL_BIT_MIME | ACL_BIT_NOTSMTP |
155                                     ACL_BIT_DKIM |
156                                     ACL_BIT_NOTSMTP_START),
157   },
158
159   [ACLC_AUTHENTICATED] =        { US"authenticated",    FALSE, FALSE,
160                                   ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START |
161                                     ACL_BIT_CONNECT | ACL_BIT_HELO,
162   },
163 #ifdef EXPERIMENTAL_BRIGHTMAIL
164   [ACLC_BMI_OPTIN] =            { US"bmi_optin",        TRUE, TRUE,
165                                   ACL_BIT_AUTH |
166                                     ACL_BIT_CONNECT | ACL_BIT_HELO |
167                                     ACL_BIT_DATA | ACL_BIT_MIME |
168 # ifndef DISABLE_PRDR
169                                     ACL_BIT_PRDR |
170 # endif
171                                     ACL_BIT_ETRN | ACL_BIT_EXPN |
172                                     ACL_BIT_MAILAUTH |
173                                     ACL_BIT_MAIL | ACL_BIT_STARTTLS |
174                                     ACL_BIT_VRFY | ACL_BIT_PREDATA |
175                                     ACL_BIT_NOTSMTP_START,
176   },
177 #endif
178   [ACLC_CONDITION] =            { US"condition",        TRUE, FALSE,    0 },
179   [ACLC_CONTINUE] =             { US"continue", TRUE, TRUE,     0 },
180
181   /* Certain types of control are always allowed, so we let it through
182   always and check in the control processing itself. */
183   [ACLC_CONTROL] =              { US"control",  TRUE, TRUE,     0 },
184
185 #ifdef EXPERIMENTAL_DCC
186   [ACLC_DCC] =                  { US"dcc",              TRUE, FALSE,
187                                   (unsigned int)
188                                   ~(ACL_BIT_DATA |
189 # ifndef DISABLE_PRDR
190                                   ACL_BIT_PRDR |
191 # endif
192                                   ACL_BIT_NOTSMTP),
193   },
194 #endif
195 #ifdef WITH_CONTENT_SCAN
196   [ACLC_DECODE] =               { US"decode",           TRUE, FALSE, (unsigned int) ~ACL_BIT_MIME },
197
198 #endif
199   [ACLC_DELAY] =                { US"delay",            TRUE, TRUE, ACL_BIT_NOTQUIT },
200 #ifndef DISABLE_DKIM
201   [ACLC_DKIM_SIGNER] =          { US"dkim_signers",     TRUE, FALSE, (unsigned int) ~ACL_BIT_DKIM },
202   [ACLC_DKIM_STATUS] =          { US"dkim_status",      TRUE, FALSE, (unsigned int) ~ACL_BIT_DKIM },
203 #endif
204 #ifdef SUPPORT_DMARC
205   [ACLC_DMARC_STATUS] =         { US"dmarc_status",     TRUE, FALSE, (unsigned int) ~ACL_BIT_DATA },
206 #endif
207
208   /* Explicit key lookups can be made in non-smtp ACLs so pass
209   always and check in the verify processing itself. */
210   [ACLC_DNSLISTS] =             { US"dnslists", TRUE, FALSE,    0 },
211
212   [ACLC_DOMAINS] =              { US"domains",  FALSE, FALSE,
213                                   (unsigned int)
214                                   ~(ACL_BIT_RCPT | ACL_BIT_VRFY
215 #ifndef DISABLE_PRDR
216                                   |ACL_BIT_PRDR
217 #endif
218       ),
219   },
220   [ACLC_ENCRYPTED] =            { US"encrypted",        FALSE, FALSE,
221                                   ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START |
222                                     ACL_BIT_HELO,
223   },
224
225   [ACLC_ENDPASS] =              { US"endpass",  TRUE, TRUE,     0 },
226
227   [ACLC_HOSTS] =                { US"hosts",            FALSE, FALSE,
228                                   ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START,
229   },
230   [ACLC_LOCAL_PARTS] =          { US"local_parts",      FALSE, FALSE,
231                                   (unsigned int)
232                                   ~(ACL_BIT_RCPT | ACL_BIT_VRFY
233 #ifndef DISABLE_PRDR
234                                   | ACL_BIT_PRDR
235 #endif
236       ),
237   },
238
239   [ACLC_LOG_MESSAGE] =          { US"log_message",      TRUE, TRUE,     0 },
240   [ACLC_LOG_REJECT_TARGET] =    { US"log_reject_target", TRUE, TRUE,    0 },
241   [ACLC_LOGWRITE] =             { US"logwrite", TRUE, TRUE,     0 },
242
243 #ifdef WITH_CONTENT_SCAN
244   [ACLC_MALWARE] =              { US"malware",  TRUE, FALSE,
245                                   (unsigned int)
246                                     ~(ACL_BIT_DATA |
247 # ifndef DISABLE_PRDR
248                                     ACL_BIT_PRDR |
249 # endif
250                                     ACL_BIT_NOTSMTP),
251   },
252 #endif
253
254   [ACLC_MESSAGE] =              { US"message",  TRUE, TRUE,     0 },
255 #ifdef WITH_CONTENT_SCAN
256   [ACLC_MIME_REGEX] =           { US"mime_regex",       TRUE, FALSE, (unsigned int) ~ACL_BIT_MIME },
257 #endif
258
259   [ACLC_QUEUE] =                { US"queue",            TRUE, TRUE,
260                                   ACL_BIT_NOTSMTP |
261 #ifndef DISABLE_PRDR
262                                   ACL_BIT_PRDR |
263 #endif
264                                   ACL_BIT_DATA,
265   },
266
267   [ACLC_RATELIMIT] =            { US"ratelimit",        TRUE, FALSE,    0 },
268   [ACLC_RECIPIENTS] =           { US"recipients",       FALSE, FALSE, (unsigned int) ~ACL_BIT_RCPT },
269
270 #ifdef WITH_CONTENT_SCAN
271   [ACLC_REGEX] =                { US"regex",            TRUE, FALSE,
272                                   (unsigned int)
273                                   ~(ACL_BIT_DATA |
274 # ifndef DISABLE_PRDR
275                                     ACL_BIT_PRDR |
276 # endif
277                                     ACL_BIT_NOTSMTP |
278                                     ACL_BIT_MIME),
279   },
280
281 #endif
282   [ACLC_REMOVE_HEADER] =        { US"remove_header",    TRUE, TRUE,
283                                   (unsigned int)
284                                   ~(ACL_BIT_MAIL|ACL_BIT_RCPT |
285                                     ACL_BIT_PREDATA | ACL_BIT_DATA |
286 #ifndef DISABLE_PRDR
287                                     ACL_BIT_PRDR |
288 #endif
289                                     ACL_BIT_MIME | ACL_BIT_NOTSMTP |
290                                     ACL_BIT_NOTSMTP_START),
291   },
292   [ACLC_SEEN] =                 { US"seen",             TRUE, FALSE,    0 },
293   [ACLC_SENDER_DOMAINS] =       { US"sender_domains",   FALSE, FALSE,
294                                   ACL_BIT_AUTH | ACL_BIT_CONNECT |
295                                     ACL_BIT_HELO |
296                                     ACL_BIT_MAILAUTH | ACL_BIT_QUIT |
297                                     ACL_BIT_ETRN | ACL_BIT_EXPN |
298                                     ACL_BIT_STARTTLS | ACL_BIT_VRFY,
299   },
300   [ACLC_SENDERS] =              { US"senders",  FALSE, FALSE,
301                                   ACL_BIT_AUTH | ACL_BIT_CONNECT |
302                                     ACL_BIT_HELO |
303                                     ACL_BIT_MAILAUTH | ACL_BIT_QUIT |
304                                     ACL_BIT_ETRN | ACL_BIT_EXPN |
305                                     ACL_BIT_STARTTLS | ACL_BIT_VRFY,
306   },
307
308   [ACLC_SET] =                  { US"set",              TRUE, TRUE,     0 },
309
310 #ifdef WITH_CONTENT_SCAN
311   [ACLC_SPAM] =                 { US"spam",             TRUE, FALSE,
312                                   (unsigned int) ~(ACL_BIT_DATA |
313 # ifndef DISABLE_PRDR
314                                   ACL_BIT_PRDR |
315 # endif
316                                   ACL_BIT_NOTSMTP),
317   },
318 #endif
319 #ifdef SUPPORT_SPF
320   [ACLC_SPF] =                  { US"spf",              TRUE, FALSE,
321                                   ACL_BIT_AUTH | ACL_BIT_CONNECT |
322                                     ACL_BIT_HELO | ACL_BIT_MAILAUTH |
323                                     ACL_BIT_ETRN | ACL_BIT_EXPN |
324                                     ACL_BIT_STARTTLS | ACL_BIT_VRFY |
325                                     ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START,
326   },
327   [ACLC_SPF_GUESS] =            { US"spf_guess",        TRUE, FALSE,
328                                   ACL_BIT_AUTH | ACL_BIT_CONNECT |
329                                     ACL_BIT_HELO | ACL_BIT_MAILAUTH |
330                                     ACL_BIT_ETRN | ACL_BIT_EXPN |
331                                     ACL_BIT_STARTTLS | ACL_BIT_VRFY |
332                                     ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START,
333   },
334 #endif
335   [ACLC_UDPSEND] =              { US"udpsend",          TRUE, TRUE,     0 },
336
337   /* Certain types of verify are always allowed, so we let it through
338   always and check in the verify function itself */
339   [ACLC_VERIFY] =               { US"verify",           TRUE, FALSE, 0 },
340 };
341
342
343
344 /* Return values from decode_control(); used as index so keep in step
345 with the controls_list table that follows! */
346
347 enum {
348   CONTROL_AUTH_UNADVERTISED,
349 #ifdef EXPERIMENTAL_BRIGHTMAIL
350   CONTROL_BMI_RUN,
351 #endif
352   CONTROL_CASEFUL_LOCAL_PART,
353   CONTROL_CASELOWER_LOCAL_PART,
354   CONTROL_CUTTHROUGH_DELIVERY,
355   CONTROL_DEBUG,
356 #ifndef DISABLE_DKIM
357   CONTROL_DKIM_VERIFY,
358 #endif
359 #ifdef SUPPORT_DMARC
360   CONTROL_DMARC_VERIFY,
361   CONTROL_DMARC_FORENSIC,
362 #endif
363   CONTROL_DSCP,
364   CONTROL_ENFORCE_SYNC,
365   CONTROL_ERROR,                /* pseudo-value for decode errors */
366   CONTROL_FAKEDEFER,
367   CONTROL_FAKEREJECT,
368   CONTROL_FREEZE,
369
370   CONTROL_NO_CALLOUT_FLUSH,
371   CONTROL_NO_DELAY_FLUSH,
372   CONTROL_NO_ENFORCE_SYNC,
373 #ifdef WITH_CONTENT_SCAN
374   CONTROL_NO_MBOX_UNSPOOL,
375 #endif
376   CONTROL_NO_MULTILINE,
377   CONTROL_NO_PIPELINING,
378
379   CONTROL_QUEUE,
380   CONTROL_SUBMISSION,
381   CONTROL_SUPPRESS_LOCAL_FIXUPS,
382 #ifdef SUPPORT_I18N
383   CONTROL_UTF8_DOWNCONVERT,
384 #endif
385 };
386
387
388
389 /* Structure listing various control arguments, with their characteristics.
390 For each control, there's a bitmap of dis-allowed times. For some, it is easier
391 to specify the negation of a small number of allowed times. */
392
393 typedef struct control_def {
394   uschar        *name;
395   BOOL          has_option;     /* Has /option(s) following */
396   unsigned      forbids;        /* bitmap of dis-allowed times */
397 } control_def;
398
399 static control_def controls_list[] = {
400   /*    name                    has_option      forbids */
401 [CONTROL_AUTH_UNADVERTISED] =
402   { US"allow_auth_unadvertised", FALSE,
403                                   (unsigned)
404                                   ~(ACL_BIT_CONNECT | ACL_BIT_HELO)
405   },
406 #ifdef EXPERIMENTAL_BRIGHTMAIL
407 [CONTROL_BMI_RUN] =
408   { US"bmi_run",                 FALSE,         0 },
409 #endif
410 [CONTROL_CASEFUL_LOCAL_PART] =
411   { US"caseful_local_part",      FALSE, (unsigned) ~ACL_BIT_RCPT },
412 [CONTROL_CASELOWER_LOCAL_PART] =
413   { US"caselower_local_part",    FALSE, (unsigned) ~ACL_BIT_RCPT },
414 [CONTROL_CUTTHROUGH_DELIVERY] =
415   { US"cutthrough_delivery",     TRUE,          0 },
416 [CONTROL_DEBUG] =
417   { US"debug",                   TRUE,          0 },
418
419 #ifndef DISABLE_DKIM
420 [CONTROL_DKIM_VERIFY] =
421   { US"dkim_disable_verify",     FALSE,
422                                   ACL_BIT_DATA | ACL_BIT_NOTSMTP |
423 # ifndef DISABLE_PRDR
424                                   ACL_BIT_PRDR |
425 # endif
426                                   ACL_BIT_NOTSMTP_START
427   },
428 #endif
429
430 #ifdef SUPPORT_DMARC
431 [CONTROL_DMARC_VERIFY] =
432   { US"dmarc_disable_verify",    FALSE,
433           ACL_BIT_DATA | ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
434   },
435 [CONTROL_DMARC_FORENSIC] =
436   { US"dmarc_enable_forensic",   FALSE,
437           ACL_BIT_DATA | ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
438   },
439 #endif
440
441 [CONTROL_DSCP] =
442   { US"dscp",                    TRUE,
443           ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START | ACL_BIT_NOTQUIT
444   },
445 [CONTROL_ENFORCE_SYNC] =
446   { US"enforce_sync",            FALSE,
447           ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
448   },
449
450   /* Pseudo-value for decode errors */
451 [CONTROL_ERROR] =
452   { US"error",                   FALSE, 0 },
453
454 [CONTROL_FAKEDEFER] =
455   { US"fakedefer",               TRUE,
456           (unsigned)
457           ~(ACL_BIT_MAIL | ACL_BIT_RCPT |
458             ACL_BIT_PREDATA | ACL_BIT_DATA |
459 #ifndef DISABLE_PRDR
460             ACL_BIT_PRDR |
461 #endif
462             ACL_BIT_MIME)
463   },
464 [CONTROL_FAKEREJECT] =
465   { US"fakereject",              TRUE,
466           (unsigned)
467           ~(ACL_BIT_MAIL | ACL_BIT_RCPT |
468             ACL_BIT_PREDATA | ACL_BIT_DATA |
469 #ifndef DISABLE_PRDR
470           ACL_BIT_PRDR |
471 #endif
472           ACL_BIT_MIME)
473   },
474 [CONTROL_FREEZE] =
475   { US"freeze",                  TRUE,
476           (unsigned)
477           ~(ACL_BIT_MAIL | ACL_BIT_RCPT |
478             ACL_BIT_PREDATA | ACL_BIT_DATA |
479             // ACL_BIT_PRDR|    /* Not allow one user to freeze for all */
480             ACL_BIT_NOTSMTP | ACL_BIT_MIME)
481   },
482
483 [CONTROL_NO_CALLOUT_FLUSH] =
484   { US"no_callout_flush",        FALSE,
485           ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
486   },
487 [CONTROL_NO_DELAY_FLUSH] =
488   { US"no_delay_flush",          FALSE,
489           ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
490   },
491
492 [CONTROL_NO_ENFORCE_SYNC] =
493   { US"no_enforce_sync",         FALSE,
494           ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
495   },
496 #ifdef WITH_CONTENT_SCAN
497 [CONTROL_NO_MBOX_UNSPOOL] =
498   { US"no_mbox_unspool",         FALSE,
499         (unsigned)
500         ~(ACL_BIT_MAIL | ACL_BIT_RCPT |
501           ACL_BIT_PREDATA | ACL_BIT_DATA |
502           // ACL_BIT_PRDR|    /* Not allow one user to freeze for all */
503           ACL_BIT_MIME)
504   },
505 #endif
506 [CONTROL_NO_MULTILINE] =
507   { US"no_multiline_responses",  FALSE,
508           ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
509   },
510 [CONTROL_NO_PIPELINING] =
511   { US"no_pipelining",           FALSE,
512           ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
513   },
514
515 [CONTROL_QUEUE] =
516   { US"queue",                  TRUE,
517           (unsigned)
518           ~(ACL_BIT_MAIL | ACL_BIT_RCPT |
519             ACL_BIT_PREDATA | ACL_BIT_DATA |
520             // ACL_BIT_PRDR|    /* Not allow one user to freeze for all */
521             ACL_BIT_NOTSMTP | ACL_BIT_MIME)
522   },
523
524 [CONTROL_SUBMISSION] =
525   { US"submission",              TRUE,
526           (unsigned)
527           ~(ACL_BIT_MAIL | ACL_BIT_RCPT | ACL_BIT_PREDATA)
528   },
529 [CONTROL_SUPPRESS_LOCAL_FIXUPS] =
530   { US"suppress_local_fixups",   FALSE,
531     (unsigned)
532     ~(ACL_BIT_MAIL | ACL_BIT_RCPT | ACL_BIT_PREDATA |
533       ACL_BIT_NOTSMTP_START)
534   },
535 #ifdef SUPPORT_I18N
536 [CONTROL_UTF8_DOWNCONVERT] =
537   { US"utf8_downconvert",        TRUE, (unsigned) ~(ACL_BIT_RCPT | ACL_BIT_VRFY)
538   }
539 #endif
540 };
541
542 /* Support data structures for Client SMTP Authorization. acl_verify_csa()
543 caches its result in a tree to avoid repeated DNS queries. The result is an
544 integer code which is used as an index into the following tables of
545 explanatory strings and verification return codes. */
546
547 static tree_node *csa_cache = NULL;
548
549 enum { CSA_UNKNOWN, CSA_OK, CSA_DEFER_SRV, CSA_DEFER_ADDR,
550  CSA_FAIL_EXPLICIT, CSA_FAIL_DOMAIN, CSA_FAIL_NOADDR, CSA_FAIL_MISMATCH };
551
552 /* The acl_verify_csa() return code is translated into an acl_verify() return
553 code using the following table. It is OK unless the client is definitely not
554 authorized. This is because CSA is supposed to be optional for sending sites,
555 so recipients should not be too strict about checking it - especially because
556 DNS problems are quite likely to occur. It's possible to use $csa_status in
557 further ACL conditions to distinguish ok, unknown, and defer if required, but
558 the aim is to make the usual configuration simple. */
559
560 static int csa_return_code[] = {
561   [CSA_UNKNOWN] =       OK,
562   [CSA_OK] =            OK,
563   [CSA_DEFER_SRV] =     OK,
564   [CSA_DEFER_ADDR] =    OK,
565   [CSA_FAIL_EXPLICIT] = FAIL,
566   [CSA_FAIL_DOMAIN] =   FAIL,
567   [CSA_FAIL_NOADDR] =   FAIL,
568   [CSA_FAIL_MISMATCH] = FAIL
569 };
570
571 static uschar *csa_status_string[] = {
572   [CSA_UNKNOWN] =       US"unknown",
573   [CSA_OK] =            US"ok",
574   [CSA_DEFER_SRV] =     US"defer",
575   [CSA_DEFER_ADDR] =    US"defer",
576   [CSA_FAIL_EXPLICIT] = US"fail",
577   [CSA_FAIL_DOMAIN] =   US"fail",
578   [CSA_FAIL_NOADDR] =   US"fail",
579   [CSA_FAIL_MISMATCH] = US"fail"
580 };
581
582 static uschar *csa_reason_string[] = {
583   [CSA_UNKNOWN] =       US"unknown",
584   [CSA_OK] =            US"ok",
585   [CSA_DEFER_SRV] =     US"deferred (SRV lookup failed)",
586   [CSA_DEFER_ADDR] =    US"deferred (target address lookup failed)",
587   [CSA_FAIL_EXPLICIT] = US"failed (explicit authorization required)",
588   [CSA_FAIL_DOMAIN] =   US"failed (host name not authorized)",
589   [CSA_FAIL_NOADDR] =   US"failed (no authorized addresses)",
590   [CSA_FAIL_MISMATCH] = US"failed (client address mismatch)"
591 };
592
593 /* Options for the ratelimit condition. Note that there are two variants of
594 the per_rcpt option, depending on the ACL that is used to measure the rate.
595 However any ACL must be able to look up per_rcpt rates in /noupdate mode,
596 so the two variants must have the same internal representation as well as
597 the same configuration string. */
598
599 enum {
600   RATE_PER_WHAT, RATE_PER_CLASH, RATE_PER_ADDR, RATE_PER_BYTE, RATE_PER_CMD,
601   RATE_PER_CONN, RATE_PER_MAIL, RATE_PER_RCPT, RATE_PER_ALLRCPTS
602 };
603
604 #define RATE_SET(var,new) \
605   (((var) == RATE_PER_WHAT) ? ((var) = RATE_##new) : ((var) = RATE_PER_CLASH))
606
607 static uschar *ratelimit_option_string[] = {
608   [RATE_PER_WHAT] =     US"?",
609   [RATE_PER_CLASH] =    US"!",
610   [RATE_PER_ADDR] =     US"per_addr",
611   [RATE_PER_BYTE] =     US"per_byte",
612   [RATE_PER_CMD] =      US"per_cmd",
613   [RATE_PER_CONN] =     US"per_conn",
614   [RATE_PER_MAIL] =     US"per_mail",
615   [RATE_PER_RCPT] =     US"per_rcpt",
616   [RATE_PER_ALLRCPTS] = US"per_rcpt"
617 };
618
619 /* Enable recursion between acl_check_internal() and acl_check_condition() */
620
621 static int acl_check_wargs(int, address_item *, const uschar *, uschar **,
622     uschar **);
623
624
625 /*************************************************
626 *            Find control in list                *
627 *************************************************/
628
629 /* The lists are always in order, so binary chop can be used.
630
631 Arguments:
632   name      the control name to search for
633   ol        the first entry in the control list
634   last      one more than the offset of the last entry in the control list
635
636 Returns:    index of a control entry, or -1 if not found
637 */
638
639 static int
640 find_control(const uschar * name, control_def * ol, int last)
641 {
642 for (int first = 0; last > first; )
643   {
644   int middle = (first + last)/2;
645   uschar * s =  ol[middle].name;
646   int c = Ustrncmp(name, s, Ustrlen(s));
647   if (c == 0) return middle;
648   else if (c > 0) first = middle + 1;
649   else last = middle;
650   }
651 return -1;
652 }
653
654
655
656 /*************************************************
657 *         Pick out condition from list           *
658 *************************************************/
659
660 /* Use a binary chop method
661
662 Arguments:
663   name        name to find
664   list        list of conditions
665   end         size of list
666
667 Returns:      offset in list, or -1 if not found
668 */
669
670 static int
671 acl_checkcondition(uschar * name, condition_def * list, int end)
672 {
673 for (int start = 0; start < end; )
674   {
675   int mid = (start + end)/2;
676   int c = Ustrcmp(name, list[mid].name);
677   if (c == 0) return mid;
678   if (c < 0) end = mid;
679   else start = mid + 1;
680   }
681 return -1;
682 }
683
684
685 /*************************************************
686 *         Pick out name from list                *
687 *************************************************/
688
689 /* Use a binary chop method
690
691 Arguments:
692   name        name to find
693   list        list of names
694   end         size of list
695
696 Returns:      offset in list, or -1 if not found
697 */
698
699 static int
700 acl_checkname(uschar *name, uschar **list, int end)
701 {
702 for (int start = 0; start < end; )
703   {
704   int mid = (start + end)/2;
705   int c = Ustrcmp(name, list[mid]);
706   if (c == 0) return mid;
707   if (c < 0) end = mid; else start = mid + 1;
708   }
709
710 return -1;
711 }
712
713
714 /*************************************************
715 *            Read and parse one ACL              *
716 *************************************************/
717
718 /* This function is called both from readconf in order to parse the ACLs in the
719 configuration file, and also when an ACL is encountered dynamically (e.g. as
720 the result of an expansion). It is given a function to call in order to
721 retrieve the lines of the ACL. This function handles skipping comments and
722 blank lines (where relevant).
723
724 Arguments:
725   func        function to get next line of ACL
726   error       where to put an error message
727
728 Returns:      pointer to ACL, or NULL
729               NULL can be legal (empty ACL); in this case error will be NULL
730 */
731
732 acl_block *
733 acl_read(uschar *(*func)(void), uschar **error)
734 {
735 acl_block *yield = NULL;
736 acl_block **lastp = &yield;
737 acl_block *this = NULL;
738 acl_condition_block *cond;
739 acl_condition_block **condp = NULL;
740 uschar * s;
741
742 *error = NULL;
743
744 while ((s = (*func)()))
745   {
746   int v, c;
747   BOOL negated = FALSE;
748   uschar *saveline = s;
749   uschar name[EXIM_DRIVERNAME_MAX];
750
751   /* Conditions (but not verbs) are allowed to be negated by an initial
752   exclamation mark. */
753
754   if (Uskip_whitespace(&s) == '!')
755     {
756     negated = TRUE;
757     s++;
758     }
759
760   /* Read the name of a verb or a condition, or the start of a new ACL, which
761   can be started by a name, or by a macro definition. */
762
763   s = readconf_readname(name, sizeof(name), s);
764   if (*s == ':' || (isupper(name[0]) && *s == '=')) return yield;
765
766   /* If a verb is unrecognized, it may be another condition or modifier that
767   continues the previous verb. */
768
769   if ((v = acl_checkname(name, verbs, nelem(verbs))) < 0)
770     {
771     if (!this)
772       {
773       *error = string_sprintf("unknown ACL verb \"%s\" in \"%s\"", name,
774         saveline);
775       return NULL;
776       }
777     }
778
779   /* New verb */
780
781   else
782     {
783     if (negated)
784       {
785       *error = string_sprintf("malformed ACL line \"%s\"", saveline);
786       return NULL;
787       }
788     this = store_get(sizeof(acl_block), FALSE);
789     *lastp = this;
790     lastp = &(this->next);
791     this->next = NULL;
792     this->condition = NULL;
793     this->verb = v;
794     this->srcline = config_lineno;      /* for debug output */
795     this->srcfile = config_filename;    /**/
796     condp = &(this->condition);
797     if (*s == 0) continue;               /* No condition on this line */
798     if (*s == '!')
799       {
800       negated = TRUE;
801       s++;
802       }
803     s = readconf_readname(name, sizeof(name), s);  /* Condition name */
804     }
805
806   /* Handle a condition or modifier. */
807
808   if ((c = acl_checkcondition(name, conditions, nelem(conditions))) < 0)
809     {
810     *error = string_sprintf("unknown ACL condition/modifier in \"%s\"",
811       saveline);
812     return NULL;
813     }
814
815   /* The modifiers may not be negated */
816
817   if (negated && conditions[c].is_modifier)
818     {
819     *error = string_sprintf("ACL error: negation is not allowed with "
820       "\"%s\"", conditions[c].name);
821     return NULL;
822     }
823
824   /* ENDPASS may occur only with ACCEPT or DISCARD. */
825
826   if (c == ACLC_ENDPASS &&
827       this->verb != ACL_ACCEPT &&
828       this->verb != ACL_DISCARD)
829     {
830     *error = string_sprintf("ACL error: \"%s\" is not allowed with \"%s\"",
831       conditions[c].name, verbs[this->verb]);
832     return NULL;
833     }
834
835   cond = store_get(sizeof(acl_condition_block), FALSE);
836   cond->next = NULL;
837   cond->type = c;
838   cond->u.negated = negated;
839
840   *condp = cond;
841   condp = &(cond->next);
842
843   /* The "set" modifier is different in that its argument is "name=value"
844   rather than just a value, and we can check the validity of the name, which
845   gives us a variable name to insert into the data block. The original ACL
846   variable names were acl_c0 ... acl_c9 and acl_m0 ... acl_m9. This was
847   extended to 20 of each type, but after that people successfully argued for
848   arbitrary names. In the new scheme, the names must start with acl_c or acl_m.
849   After that, we allow alphanumerics and underscores, but the first character
850   after c or m must be a digit or an underscore. This retains backwards
851   compatibility. */
852
853   if (c == ACLC_SET)
854 #ifndef DISABLE_DKIM
855     if (  Ustrncmp(s, "dkim_verify_status", 18) == 0
856        || Ustrncmp(s, "dkim_verify_reason", 18) == 0)
857       {
858       uschar * endptr = s+18;
859
860       if (isalnum(*endptr))
861         {
862         *error = string_sprintf("invalid variable name after \"set\" in ACL "
863           "modifier \"set %s\" "
864           "(only \"dkim_verify_status\" or \"dkim_verify_reason\" permitted)",
865           s);
866         return NULL;
867         }
868       cond->u.varname = string_copyn(s, 18);
869       s = endptr;
870       Uskip_whitespace(&s);
871       }
872     else
873 #endif
874     {
875     uschar *endptr;
876
877     if (Ustrncmp(s, "acl_c", 5) != 0 && Ustrncmp(s, "acl_m", 5) != 0)
878       {
879       *error = string_sprintf("invalid variable name after \"set\" in ACL "
880         "modifier \"set %s\" (must start \"acl_c\" or \"acl_m\")", s);
881       return NULL;
882       }
883
884     endptr = s + 5;
885     if (!isdigit(*endptr) && *endptr != '_')
886       {
887       *error = string_sprintf("invalid variable name after \"set\" in ACL "
888         "modifier \"set %s\" (digit or underscore must follow acl_c or acl_m)",
889         s);
890       return NULL;
891       }
892
893     while (*endptr && *endptr != '=' && !isspace(*endptr))
894       {
895       if (!isalnum(*endptr) && *endptr != '_')
896         {
897         *error = string_sprintf("invalid character \"%c\" in variable name "
898           "in ACL modifier \"set %s\"", *endptr, s);
899         return NULL;
900         }
901       endptr++;
902       }
903
904     cond->u.varname = string_copyn(s + 4, endptr - s - 4);
905     s = endptr;
906     Uskip_whitespace(&s);
907     }
908
909   /* For "set", we are now positioned for the data. For the others, only
910   "endpass" has no data */
911
912   if (c != ACLC_ENDPASS)
913     {
914     if (*s++ != '=')
915       {
916       *error = string_sprintf("\"=\" missing after ACL \"%s\" %s", name,
917         conditions[c].is_modifier ? US"modifier" : US"condition");
918       return NULL;
919       }
920     Uskip_whitespace(&s);
921     cond->arg = string_copy(s);
922     }
923   }
924
925 return yield;
926 }
927
928
929
930 /*************************************************
931 *         Set up added header line(s)            *
932 *************************************************/
933
934 /* This function is called by the add_header modifier, and also from acl_warn()
935 to implement the now-deprecated way of adding header lines using "message" on a
936 "warn" verb. The argument is treated as a sequence of header lines which are
937 added to a chain, provided there isn't an identical one already there.
938
939 Argument:   string of header lines
940 Returns:    nothing
941 */
942
943 static void
944 setup_header(const uschar *hstring)
945 {
946 const uschar *p, *q;
947 int hlen = Ustrlen(hstring);
948
949 /* Ignore any leading newlines */
950 while (*hstring == '\n') hstring++, hlen--;
951
952 /* An empty string does nothing; ensure exactly one final newline. */
953 if (hlen <= 0) return;
954 if (hstring[--hlen] != '\n')            /* no newline */
955   q = string_sprintf("%s\n", hstring);
956 else if (hstring[hlen-1] == '\n')       /* double newline */
957   {
958   uschar * s = string_copy(hstring);
959   while(s[--hlen] == '\n')
960     s[hlen+1] = '\0';
961   q = s;
962   }
963 else
964   q = hstring;
965
966 /* Loop for multiple header lines, taking care about continuations */
967
968 for (p = q; *p; p = q)
969   {
970   const uschar *s;
971   uschar * hdr;
972   int newtype = htype_add_bot;
973   header_line **hptr = &acl_added_headers;
974
975   /* Find next header line within the string */
976
977   for (;;)
978     {
979     q = Ustrchr(q, '\n');               /* we know there was a newline */
980     if (*++q != ' ' && *q != '\t') break;
981     }
982
983   /* If the line starts with a colon, interpret the instruction for where to
984   add it. This temporarily sets up a new type. */
985
986   if (*p == ':')
987     {
988     if (strncmpic(p, US":after_received:", 16) == 0)
989       {
990       newtype = htype_add_rec;
991       p += 16;
992       }
993     else if (strncmpic(p, US":at_start_rfc:", 14) == 0)
994       {
995       newtype = htype_add_rfc;
996       p += 14;
997       }
998     else if (strncmpic(p, US":at_start:", 10) == 0)
999       {
1000       newtype = htype_add_top;
1001       p += 10;
1002       }
1003     else if (strncmpic(p, US":at_end:", 8) == 0)
1004       {
1005       newtype = htype_add_bot;
1006       p += 8;
1007       }
1008     while (*p == ' ' || *p == '\t') p++;
1009     }
1010
1011   /* See if this line starts with a header name, and if not, add X-ACL-Warn:
1012   to the front of it. */
1013
1014   for (s = p; s < q - 1; s++)
1015     if (*s == ':' || !isgraph(*s)) break;
1016
1017   hdr = string_sprintf("%s%.*s", *s == ':' ? "" : "X-ACL-Warn: ", (int) (q - p), p);
1018   hlen = Ustrlen(hdr);
1019
1020   /* See if this line has already been added */
1021
1022   while (*hptr)
1023     {
1024     if (Ustrncmp((*hptr)->text, hdr, hlen) == 0) break;
1025     hptr = &(*hptr)->next;
1026     }
1027
1028   /* Add if not previously present */
1029
1030   if (!*hptr)
1031     {
1032     /* The header_line struct itself is not tainted, though it points to
1033     possibly tainted data. */
1034     header_line * h = store_get(sizeof(header_line), FALSE);
1035     h->text = hdr;
1036     h->next = NULL;
1037     h->type = newtype;
1038     h->slen = hlen;
1039     *hptr = h;
1040     hptr = &h->next;
1041     }
1042   }
1043 }
1044
1045
1046
1047 /*************************************************
1048 *        List the added header lines             *
1049 *************************************************/
1050 uschar *
1051 fn_hdrs_added(void)
1052 {
1053 gstring * g = NULL;
1054
1055 for (header_line * h = acl_added_headers; h; h = h->next)
1056   {
1057   int i = h->slen;
1058   if (h->text[i-1] == '\n') i--;
1059   g = string_append_listele_n(g, '\n', h->text, i);
1060   }
1061
1062 return g ? g->s : NULL;
1063 }
1064
1065
1066 /*************************************************
1067 *        Set up removed header line(s)           *
1068 *************************************************/
1069
1070 /* This function is called by the remove_header modifier.  The argument is
1071 treated as a sequence of header names which are added to a colon separated
1072 list, provided there isn't an identical one already there.
1073
1074 Argument:   string of header names
1075 Returns:    nothing
1076 */
1077
1078 static void
1079 setup_remove_header(const uschar *hnames)
1080 {
1081 if (*hnames)
1082   acl_removed_headers = acl_removed_headers
1083     ? string_sprintf("%s : %s", acl_removed_headers, hnames)
1084     : string_copy(hnames);
1085 }
1086
1087
1088
1089 /*************************************************
1090 *               Handle warnings                  *
1091 *************************************************/
1092
1093 /* This function is called when a WARN verb's conditions are true. It adds to
1094 the message's headers, and/or writes information to the log. In each case, this
1095 only happens once (per message for headers, per connection for log).
1096
1097 ** NOTE: The header adding action using the "message" setting is historic, and
1098 its use is now deprecated. The new add_header modifier should be used instead.
1099
1100 Arguments:
1101   where          ACL_WHERE_xxxx indicating which ACL this is
1102   user_message   message for adding to headers
1103   log_message    message for logging, if different
1104
1105 Returns:         nothing
1106 */
1107
1108 static void
1109 acl_warn(int where, uschar *user_message, uschar *log_message)
1110 {
1111 if (log_message != NULL && log_message != user_message)
1112   {
1113   uschar *text;
1114   string_item *logged;
1115
1116   text = string_sprintf("%s Warning: %s",  host_and_ident(TRUE),
1117     string_printing(log_message));
1118
1119   /* If a sender verification has failed, and the log message is "sender verify
1120   failed", add the failure message. */
1121
1122   if (sender_verified_failed != NULL &&
1123       sender_verified_failed->message != NULL &&
1124       strcmpic(log_message, US"sender verify failed") == 0)
1125     text = string_sprintf("%s: %s", text, sender_verified_failed->message);
1126
1127   /* Search previously logged warnings. They are kept in malloc
1128   store so they can be freed at the start of a new message. */
1129
1130   for (logged = acl_warn_logged; logged; logged = logged->next)
1131     if (Ustrcmp(logged->text, text) == 0) break;
1132
1133   if (!logged)
1134     {
1135     int length = Ustrlen(text) + 1;
1136     log_write(0, LOG_MAIN, "%s", text);
1137     logged = store_malloc(sizeof(string_item) + length);
1138     logged->text = US logged + sizeof(string_item);
1139     memcpy(logged->text, text, length);
1140     logged->next = acl_warn_logged;
1141     acl_warn_logged = logged;
1142     }
1143   }
1144
1145 /* If there's no user message, we are done. */
1146
1147 if (!user_message) return;
1148
1149 /* If this isn't a message ACL, we can't do anything with a user message.
1150 Log an error. */
1151
1152 if (where > ACL_WHERE_NOTSMTP)
1153   {
1154   log_write(0, LOG_MAIN|LOG_PANIC, "ACL \"warn\" with \"message\" setting "
1155     "found in a non-message (%s) ACL: cannot specify header lines here: "
1156     "message ignored", acl_wherenames[where]);
1157   return;
1158   }
1159
1160 /* The code for setting up header lines is now abstracted into a separate
1161 function so that it can be used for the add_header modifier as well. */
1162
1163 setup_header(user_message);
1164 }
1165
1166
1167
1168 /*************************************************
1169 *         Verify and check reverse DNS           *
1170 *************************************************/
1171
1172 /* Called from acl_verify() below. We look up the host name(s) of the client IP
1173 address if this has not yet been done. The host_name_lookup() function checks
1174 that one of these names resolves to an address list that contains the client IP
1175 address, so we don't actually have to do the check here.
1176
1177 Arguments:
1178   user_msgptr  pointer for user message
1179   log_msgptr   pointer for log message
1180
1181 Returns:       OK        verification condition succeeded
1182                FAIL      verification failed
1183                DEFER     there was a problem verifying
1184 */
1185
1186 static int
1187 acl_verify_reverse(uschar **user_msgptr, uschar **log_msgptr)
1188 {
1189 int rc;
1190
1191 /* Previous success */
1192
1193 if (sender_host_name != NULL) return OK;
1194
1195 /* Previous failure */
1196
1197 if (host_lookup_failed)
1198   {
1199   *log_msgptr = string_sprintf("host lookup failed%s", host_lookup_msg);
1200   return FAIL;
1201   }
1202
1203 /* Need to do a lookup */
1204
1205 HDEBUG(D_acl)
1206   debug_printf_indent("looking up host name to force name/address consistency check\n");
1207
1208 if ((rc = host_name_lookup()) != OK)
1209   {
1210   *log_msgptr = rc == DEFER
1211     ? US"host lookup deferred for reverse lookup check"
1212     : string_sprintf("host lookup failed for reverse lookup check%s",
1213         host_lookup_msg);
1214   return rc;    /* DEFER or FAIL */
1215   }
1216
1217 host_build_sender_fullhost();
1218 return OK;
1219 }
1220
1221
1222
1223 /*************************************************
1224 *   Check client IP address matches CSA target   *
1225 *************************************************/
1226
1227 /* Called from acl_verify_csa() below. This routine scans a section of a DNS
1228 response for address records belonging to the CSA target hostname. The section
1229 is specified by the reset argument, either RESET_ADDITIONAL or RESET_ANSWERS.
1230 If one of the addresses matches the client's IP address, then the client is
1231 authorized by CSA. If there are target IP addresses but none of them match
1232 then the client is using an unauthorized IP address. If there are no target IP
1233 addresses then the client cannot be using an authorized IP address. (This is
1234 an odd configuration - why didn't the SRV record have a weight of 1 instead?)
1235
1236 Arguments:
1237   dnsa       the DNS answer block
1238   dnss       a DNS scan block for us to use
1239   reset      option specifying what portion to scan, as described above
1240   target     the target hostname to use for matching RR names
1241
1242 Returns:     CSA_OK             successfully authorized
1243              CSA_FAIL_MISMATCH  addresses found but none matched
1244              CSA_FAIL_NOADDR    no target addresses found
1245 */
1246
1247 static int
1248 acl_verify_csa_address(dns_answer *dnsa, dns_scan *dnss, int reset,
1249                        uschar *target)
1250 {
1251 int rc = CSA_FAIL_NOADDR;
1252
1253 for (dns_record * rr = dns_next_rr(dnsa, dnss, reset);
1254      rr;
1255      rr = dns_next_rr(dnsa, dnss, RESET_NEXT))
1256   {
1257   /* Check this is an address RR for the target hostname. */
1258
1259   if (rr->type != T_A
1260     #if HAVE_IPV6
1261       && rr->type != T_AAAA
1262     #endif
1263   ) continue;
1264
1265   if (strcmpic(target, rr->name) != 0) continue;
1266
1267   rc = CSA_FAIL_MISMATCH;
1268
1269   /* Turn the target address RR into a list of textual IP addresses and scan
1270   the list. There may be more than one if it is an A6 RR. */
1271
1272   for (dns_address * da = dns_address_from_rr(dnsa, rr); da; da = da->next)
1273     {
1274     /* If the client IP address matches the target IP address, it's good! */
1275
1276     DEBUG(D_acl) debug_printf_indent("CSA target address is %s\n", da->address);
1277
1278     if (strcmpic(sender_host_address, da->address) == 0) return CSA_OK;
1279     }
1280   }
1281
1282 /* If we found some target addresses but none of them matched, the client is
1283 using an unauthorized IP address, otherwise the target has no authorized IP
1284 addresses. */
1285
1286 return rc;
1287 }
1288
1289
1290
1291 /*************************************************
1292 *       Verify Client SMTP Authorization         *
1293 *************************************************/
1294
1295 /* Called from acl_verify() below. This routine calls dns_lookup_special()
1296 to find the CSA SRV record corresponding to the domain argument, or
1297 $sender_helo_name if no argument is provided. It then checks that the
1298 client is authorized, and that its IP address corresponds to the SRV
1299 target's address by calling acl_verify_csa_address() above. The address
1300 should have been returned in the DNS response's ADDITIONAL section, but if
1301 not we perform another DNS lookup to get it.
1302
1303 Arguments:
1304   domain    pointer to optional parameter following verify = csa
1305
1306 Returns:    CSA_UNKNOWN    no valid CSA record found
1307             CSA_OK         successfully authorized
1308             CSA_FAIL_*     client is definitely not authorized
1309             CSA_DEFER_*    there was a DNS problem
1310 */
1311
1312 static int
1313 acl_verify_csa(const uschar *domain)
1314 {
1315 tree_node *t;
1316 const uschar *found;
1317 int priority, weight, port;
1318 dns_answer * dnsa;
1319 dns_scan dnss;
1320 dns_record *rr;
1321 int rc, type, yield;
1322 #define TARGET_SIZE 256
1323 uschar * target = store_get(TARGET_SIZE, TRUE);
1324
1325 /* Work out the domain we are using for the CSA lookup. The default is the
1326 client's HELO domain. If the client has not said HELO, use its IP address
1327 instead. If it's a local client (exim -bs), CSA isn't applicable. */
1328
1329 while (isspace(*domain) && *domain != '\0') ++domain;
1330 if (*domain == '\0') domain = sender_helo_name;
1331 if (!domain) domain = sender_host_address;
1332 if (!sender_host_address) return CSA_UNKNOWN;
1333
1334 /* If we have an address literal, strip off the framing ready for turning it
1335 into a domain. The framing consists of matched square brackets possibly
1336 containing a keyword and a colon before the actual IP address. */
1337
1338 if (domain[0] == '[')
1339   {
1340   const uschar *start = Ustrchr(domain, ':');
1341   if (start == NULL) start = domain;
1342   domain = string_copyn(start + 1, Ustrlen(start) - 2);
1343   }
1344
1345 /* Turn domains that look like bare IP addresses into domains in the reverse
1346 DNS. This code also deals with address literals and $sender_host_address. It's
1347 not quite kosher to treat bare domains such as EHLO 192.0.2.57 the same as
1348 address literals, but it's probably the most friendly thing to do. This is an
1349 extension to CSA, so we allow it to be turned off for proper conformance. */
1350
1351 if (string_is_ip_address(domain, NULL) != 0)
1352   {
1353   if (!dns_csa_use_reverse) return CSA_UNKNOWN;
1354   domain = dns_build_reverse(domain);
1355   }
1356
1357 /* Find out if we've already done the CSA check for this domain. If we have,
1358 return the same result again. Otherwise build a new cached result structure
1359 for this domain. The name is filled in now, and the value is filled in when
1360 we return from this function. */
1361
1362 if ((t = tree_search(csa_cache, domain)))
1363   return t->data.val;
1364
1365 t = store_get_perm(sizeof(tree_node) + Ustrlen(domain), is_tainted(domain));
1366 Ustrcpy(t->name, domain);
1367 (void)tree_insertnode(&csa_cache, t);
1368
1369 /* Now we are ready to do the actual DNS lookup(s). */
1370
1371 found = domain;
1372 dnsa = store_get_dns_answer();
1373 switch (dns_special_lookup(dnsa, domain, T_CSA, &found))
1374   {
1375   /* If something bad happened (most commonly DNS_AGAIN), defer. */
1376
1377   default:
1378     yield = CSA_DEFER_SRV;
1379     goto out;
1380
1381   /* If we found nothing, the client's authorization is unknown. */
1382
1383   case DNS_NOMATCH:
1384   case DNS_NODATA:
1385     yield = CSA_UNKNOWN;
1386     goto out;
1387
1388   /* We got something! Go on to look at the reply in more detail. */
1389
1390   case DNS_SUCCEED:
1391     break;
1392   }
1393
1394 /* Scan the reply for well-formed CSA SRV records. */
1395
1396 for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS);
1397      rr;
1398      rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)) if (rr->type == T_SRV)
1399   {
1400   const uschar * p = rr->data;
1401
1402   /* Extract the numerical SRV fields (p is incremented) */
1403
1404   GETSHORT(priority, p);
1405   GETSHORT(weight, p);
1406   GETSHORT(port, p);
1407
1408   DEBUG(D_acl)
1409     debug_printf_indent("CSA priority=%d weight=%d port=%d\n", priority, weight, port);
1410
1411   /* Check the CSA version number */
1412
1413   if (priority != 1) continue;
1414
1415   /* If the domain does not have a CSA SRV record of its own (i.e. the domain
1416   found by dns_special_lookup() is a parent of the one we asked for), we check
1417   the subdomain assertions in the port field. At the moment there's only one
1418   assertion: legitimate SMTP clients are all explicitly authorized with CSA
1419   SRV records of their own. */
1420
1421   if (Ustrcmp(found, domain) != 0)
1422     {
1423     yield = port & 1 ? CSA_FAIL_EXPLICIT : CSA_UNKNOWN;
1424     goto out;
1425     }
1426
1427   /* This CSA SRV record refers directly to our domain, so we check the value
1428   in the weight field to work out the domain's authorization. 0 and 1 are
1429   unauthorized; 3 means the client is authorized but we can't check the IP
1430   address in order to authenticate it, so we treat it as unknown; values
1431   greater than 3 are undefined. */
1432
1433   if (weight < 2)
1434     {
1435     yield = CSA_FAIL_DOMAIN;
1436     goto out;
1437     }
1438
1439   if (weight > 2) continue;
1440
1441   /* Weight == 2, which means the domain is authorized. We must check that the
1442   client's IP address is listed as one of the SRV target addresses. Save the
1443   target hostname then break to scan the additional data for its addresses. */
1444
1445   (void)dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen, p,
1446     (DN_EXPAND_ARG4_TYPE)target, TARGET_SIZE);
1447
1448   DEBUG(D_acl) debug_printf_indent("CSA target is %s\n", target);
1449
1450   break;
1451   }
1452
1453 /* If we didn't break the loop then no appropriate records were found. */
1454
1455 if (!rr)
1456   {
1457   yield = CSA_UNKNOWN;
1458   goto out;
1459   }
1460
1461 /* Do not check addresses if the target is ".", in accordance with RFC 2782.
1462 A target of "." indicates there are no valid addresses, so the client cannot
1463 be authorized. (This is an odd configuration because weight=2 target=. is
1464 equivalent to weight=1, but we check for it in order to keep load off the
1465 root name servers.) Note that dn_expand() turns "." into "". */
1466
1467 if (Ustrcmp(target, "") == 0)
1468   {
1469   yield = CSA_FAIL_NOADDR;
1470   goto out;
1471   }
1472
1473 /* Scan the additional section of the CSA SRV reply for addresses belonging
1474 to the target. If the name server didn't return any additional data (e.g.
1475 because it does not fully support SRV records), we need to do another lookup
1476 to obtain the target addresses; otherwise we have a definitive result. */
1477
1478 rc = acl_verify_csa_address(dnsa, &dnss, RESET_ADDITIONAL, target);
1479 if (rc != CSA_FAIL_NOADDR)
1480   {
1481   yield = rc;
1482   goto out;
1483   }
1484
1485 /* The DNS lookup type corresponds to the IP version used by the client. */
1486
1487 #if HAVE_IPV6
1488 if (Ustrchr(sender_host_address, ':') != NULL)
1489   type = T_AAAA;
1490 else
1491 #endif /* HAVE_IPV6 */
1492   type = T_A;
1493
1494
1495 lookup_dnssec_authenticated = NULL;
1496 switch (dns_lookup(dnsa, target, type, NULL))
1497   {
1498   /* If something bad happened (most commonly DNS_AGAIN), defer. */
1499
1500   default:
1501     yield = CSA_DEFER_ADDR;
1502     break;
1503
1504   /* If the query succeeded, scan the addresses and return the result. */
1505
1506   case DNS_SUCCEED:
1507     rc = acl_verify_csa_address(dnsa, &dnss, RESET_ANSWERS, target);
1508     if (rc != CSA_FAIL_NOADDR)
1509       {
1510       yield = rc;
1511       break;
1512       }
1513     /* else fall through */
1514
1515   /* If the target has no IP addresses, the client cannot have an authorized
1516   IP address. However, if the target site uses A6 records (not AAAA records)
1517   we have to do yet another lookup in order to check them. */
1518
1519   case DNS_NOMATCH:
1520   case DNS_NODATA:
1521     yield = CSA_FAIL_NOADDR;
1522     break;
1523   }
1524
1525 out:
1526
1527 store_free_dns_answer(dnsa);
1528 return t->data.val = yield;
1529 }
1530
1531
1532
1533 /*************************************************
1534 *     Handle verification (address & other)      *
1535 *************************************************/
1536
1537 enum { VERIFY_REV_HOST_LKUP, VERIFY_CERT, VERIFY_HELO, VERIFY_CSA, VERIFY_HDR_SYNTAX,
1538        VERIFY_NOT_BLIND, VERIFY_HDR_SNDR, VERIFY_SNDR, VERIFY_RCPT,
1539        VERIFY_HDR_NAMES_ASCII, VERIFY_ARC
1540   };
1541 typedef struct {
1542   uschar * name;
1543   int      value;
1544   unsigned where_allowed;       /* bitmap */
1545   BOOL     no_options;          /* Never has /option(s) following */
1546   unsigned alt_opt_sep;         /* >0 Non-/ option separator (custom parser) */
1547   } verify_type_t;
1548 static verify_type_t verify_type_list[] = {
1549     /*  name                    value                   where           no-opt opt-sep */
1550     { US"reverse_host_lookup",  VERIFY_REV_HOST_LKUP,   (unsigned)~0,   FALSE, 0 },
1551     { US"certificate",          VERIFY_CERT,            (unsigned)~0,   TRUE,  0 },
1552     { US"helo",                 VERIFY_HELO,            (unsigned)~0,   TRUE,  0 },
1553     { US"csa",                  VERIFY_CSA,             (unsigned)~0,   FALSE, 0 },
1554     { US"header_syntax",        VERIFY_HDR_SYNTAX,      ACL_BITS_HAVEDATA, TRUE, 0 },
1555     { US"not_blind",            VERIFY_NOT_BLIND,       ACL_BITS_HAVEDATA, FALSE, 0 },
1556     { US"header_sender",        VERIFY_HDR_SNDR,        ACL_BITS_HAVEDATA, FALSE, 0 },
1557     { US"sender",               VERIFY_SNDR,            ACL_BIT_MAIL | ACL_BIT_RCPT
1558                         | ACL_BIT_PREDATA | ACL_BIT_DATA | ACL_BIT_NOTSMTP,
1559                                                                                 FALSE, 6 },
1560     { US"recipient",            VERIFY_RCPT,            ACL_BIT_RCPT,   FALSE, 0 },
1561     { US"header_names_ascii",   VERIFY_HDR_NAMES_ASCII, ACL_BITS_HAVEDATA, TRUE, 0 },
1562 #ifdef EXPERIMENTAL_ARC
1563     { US"arc",                  VERIFY_ARC,             ACL_BIT_DATA,   FALSE , 0 },
1564 #endif
1565   };
1566
1567
1568 enum { CALLOUT_DEFER_OK, CALLOUT_NOCACHE, CALLOUT_RANDOM, CALLOUT_USE_SENDER,
1569   CALLOUT_USE_POSTMASTER, CALLOUT_POSTMASTER, CALLOUT_FULLPOSTMASTER,
1570   CALLOUT_MAILFROM, CALLOUT_POSTMASTER_MAILFROM, CALLOUT_MAXWAIT, CALLOUT_CONNECT,
1571   CALLOUT_HOLD, CALLOUT_TIME    /* TIME must be last */
1572   };
1573 typedef struct {
1574   uschar * name;
1575   int      value;
1576   int      flag;
1577   BOOL     has_option;  /* Has =option(s) following */
1578   BOOL     timeval;     /* Has a time value */
1579   } callout_opt_t;
1580 static callout_opt_t callout_opt_list[] = {
1581     /*  name                    value                   flag            has-opt         has-time */
1582     { US"defer_ok",       CALLOUT_DEFER_OK,      0,                             FALSE, FALSE },
1583     { US"no_cache",       CALLOUT_NOCACHE,       vopt_callout_no_cache,         FALSE, FALSE },
1584     { US"random",         CALLOUT_RANDOM,        vopt_callout_random,           FALSE, FALSE },
1585     { US"use_sender",     CALLOUT_USE_SENDER,    vopt_callout_recipsender,      FALSE, FALSE },
1586     { US"use_postmaster", CALLOUT_USE_POSTMASTER,vopt_callout_recippmaster,     FALSE, FALSE },
1587     { US"postmaster_mailfrom",CALLOUT_POSTMASTER_MAILFROM,0,                    TRUE,  FALSE },
1588     { US"postmaster",     CALLOUT_POSTMASTER,    0,                             FALSE, FALSE },
1589     { US"fullpostmaster", CALLOUT_FULLPOSTMASTER,vopt_callout_fullpm,           FALSE, FALSE },
1590     { US"mailfrom",       CALLOUT_MAILFROM,      0,                             TRUE,  FALSE },
1591     { US"maxwait",        CALLOUT_MAXWAIT,       0,                             TRUE,  TRUE },
1592     { US"connect",        CALLOUT_CONNECT,       0,                             TRUE,  TRUE },
1593     { US"hold",           CALLOUT_HOLD,          vopt_callout_hold,             FALSE, FALSE },
1594     { NULL,               CALLOUT_TIME,          0,                             FALSE, TRUE }
1595   };
1596
1597
1598
1599 static int
1600 v_period(const uschar * s, const uschar * arg, uschar ** log_msgptr)
1601 {
1602 int period;
1603 if ((period = readconf_readtime(s, 0, FALSE)) < 0)
1604   {
1605   *log_msgptr = string_sprintf("bad time value in ACL condition "
1606     "\"verify %s\"", arg);
1607   }
1608 return period;
1609 }
1610
1611
1612
1613 /* This function implements the "verify" condition. It is called when
1614 encountered in any ACL, because some tests are almost always permitted. Some
1615 just don't make sense, and always fail (for example, an attempt to test a host
1616 lookup for a non-TCP/IP message). Others are restricted to certain ACLs.
1617
1618 Arguments:
1619   where        where called from
1620   addr         the recipient address that the ACL is handling, or NULL
1621   arg          the argument of "verify"
1622   user_msgptr  pointer for user message
1623   log_msgptr   pointer for log message
1624   basic_errno  where to put verify errno
1625
1626 Returns:       OK        verification condition succeeded
1627                FAIL      verification failed
1628                DEFER     there was a problem verifying
1629                ERROR     syntax error
1630 */
1631
1632 static int
1633 acl_verify(int where, address_item *addr, const uschar *arg,
1634   uschar **user_msgptr, uschar **log_msgptr, int *basic_errno)
1635 {
1636 int sep = '/';
1637 int callout = -1;
1638 int callout_overall = -1;
1639 int callout_connect = -1;
1640 int verify_options = 0;
1641 int rc;
1642 BOOL verify_header_sender = FALSE;
1643 BOOL defer_ok = FALSE;
1644 BOOL callout_defer_ok = FALSE;
1645 BOOL no_details = FALSE;
1646 BOOL success_on_redirect = FALSE;
1647 BOOL quota = FALSE;
1648 int quota_pos_cache = QUOTA_POS_DEFAULT, quota_neg_cache = QUOTA_NEG_DEFAULT;
1649 address_item *sender_vaddr = NULL;
1650 uschar *verify_sender_address = NULL;
1651 uschar *pm_mailfrom = NULL;
1652 uschar *se_mailfrom = NULL;
1653
1654 /* Some of the verify items have slash-separated options; some do not. Diagnose
1655 an error if options are given for items that don't expect them.
1656 */
1657
1658 uschar *slash = Ustrchr(arg, '/');
1659 const uschar *list = arg;
1660 uschar *ss = string_nextinlist(&list, &sep, NULL, 0);
1661 verify_type_t * vp;
1662
1663 if (!ss) goto BAD_VERIFY;
1664
1665 /* Handle name/address consistency verification in a separate function. */
1666
1667 for (vp = verify_type_list;
1668      CS vp < CS verify_type_list + sizeof(verify_type_list);
1669      vp++
1670     )
1671   if (vp->alt_opt_sep ? strncmpic(ss, vp->name, vp->alt_opt_sep) == 0
1672                       : strcmpic (ss, vp->name) == 0)
1673    break;
1674 if (CS vp >= CS verify_type_list + sizeof(verify_type_list))
1675   goto BAD_VERIFY;
1676
1677 if (vp->no_options && slash)
1678   {
1679   *log_msgptr = string_sprintf("unexpected '/' found in \"%s\" "
1680     "(this verify item has no options)", arg);
1681   return ERROR;
1682   }
1683 if (!(vp->where_allowed & BIT(where)))
1684   {
1685   *log_msgptr = string_sprintf("cannot verify %s in ACL for %s",
1686                   vp->name, acl_wherenames[where]);
1687   return ERROR;
1688   }
1689 switch(vp->value)
1690   {
1691   case VERIFY_REV_HOST_LKUP:
1692     if (!sender_host_address) return OK;
1693     if ((rc = acl_verify_reverse(user_msgptr, log_msgptr)) == DEFER)
1694       while ((ss = string_nextinlist(&list, &sep, NULL, 0)))
1695         if (strcmpic(ss, US"defer_ok") == 0)
1696           return OK;
1697     return rc;
1698
1699   case VERIFY_CERT:
1700     /* TLS certificate verification is done at STARTTLS time; here we just
1701     test whether it was successful or not. (This is for optional verification; for
1702     mandatory verification, the connection doesn't last this long.) */
1703
1704     if (tls_in.certificate_verified) return OK;
1705     *user_msgptr = US"no verified certificate";
1706     return FAIL;
1707
1708   case VERIFY_HELO:
1709     /* We can test the result of optional HELO verification that might have
1710     occurred earlier. If not, we can attempt the verification now. */
1711
1712     if (!f.helo_verified && !f.helo_verify_failed) smtp_verify_helo();
1713     return f.helo_verified ? OK : FAIL;
1714
1715   case VERIFY_CSA:
1716     /* Do Client SMTP Authorization checks in a separate function, and turn the
1717     result code into user-friendly strings. */
1718
1719     rc = acl_verify_csa(list);
1720     *log_msgptr = *user_msgptr = string_sprintf("client SMTP authorization %s",
1721                                               csa_reason_string[rc]);
1722     csa_status = csa_status_string[rc];
1723     DEBUG(D_acl) debug_printf_indent("CSA result %s\n", csa_status);
1724     return csa_return_code[rc];
1725
1726 #ifdef EXPERIMENTAL_ARC
1727   case VERIFY_ARC:
1728     {   /* Do Authenticated Received Chain checks in a separate function. */
1729     const uschar * condlist = CUS string_nextinlist(&list, &sep, NULL, 0);
1730     int csep = 0;
1731     uschar * cond;
1732
1733     if (!(arc_state = acl_verify_arc())) return DEFER;
1734     DEBUG(D_acl) debug_printf_indent("ARC verify result %s %s%s%s\n", arc_state,
1735       arc_state_reason ? "(":"", arc_state_reason, arc_state_reason ? ")":"");
1736
1737     if (!condlist) condlist = US"none:pass";
1738     while ((cond = string_nextinlist(&condlist, &csep, NULL, 0)))
1739       if (Ustrcmp(arc_state, cond) == 0) return OK;
1740     return FAIL;
1741     }
1742 #endif
1743
1744   case VERIFY_HDR_SYNTAX:
1745     /* Check that all relevant header lines have the correct 5322-syntax. If there is
1746     a syntax error, we return details of the error to the sender if configured to
1747     send out full details. (But a "message" setting on the ACL can override, as
1748     always). */
1749
1750     rc = verify_check_headers(log_msgptr);
1751     if (rc != OK && *log_msgptr)
1752       if (smtp_return_error_details)
1753         *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1754       else
1755         acl_verify_message = *log_msgptr;
1756     return rc;
1757
1758   case VERIFY_HDR_NAMES_ASCII:
1759     /* Check that all header names are true 7 bit strings
1760     See RFC 5322, 2.2. and RFC 6532, 3. */
1761
1762     rc = verify_check_header_names_ascii(log_msgptr);
1763     if (rc != OK && smtp_return_error_details && *log_msgptr)
1764       *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1765     return rc;
1766
1767   case VERIFY_NOT_BLIND:
1768     /* Check that no recipient of this message is "blind", that is, every envelope
1769     recipient must be mentioned in either To: or Cc:. */
1770     {
1771     BOOL case_sensitive = TRUE;
1772
1773     while ((ss = string_nextinlist(&list, &sep, NULL, 0)))
1774       if (strcmpic(ss, US"case_insensitive") == 0)
1775         case_sensitive = FALSE;
1776       else
1777         {
1778         *log_msgptr = string_sprintf("unknown option \"%s\" in ACL "
1779            "condition \"verify %s\"", ss, arg);
1780         return ERROR;
1781         }
1782
1783     if ((rc = verify_check_notblind(case_sensitive)) != OK)
1784       {
1785       *log_msgptr = US"bcc recipient detected";
1786       if (smtp_return_error_details)
1787         *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1788       }
1789     return rc;
1790     }
1791
1792   /* The remaining verification tests check recipient and sender addresses,
1793   either from the envelope or from the header. There are a number of
1794   slash-separated options that are common to all of them. */
1795
1796   case VERIFY_HDR_SNDR:
1797     verify_header_sender = TRUE;
1798     break;
1799
1800   case VERIFY_SNDR:
1801     /* In the case of a sender, this can optionally be followed by an address to use
1802     in place of the actual sender (rare special-case requirement). */
1803     {
1804     uschar *s = ss + 6;
1805     if (!*s)
1806       verify_sender_address = sender_address;
1807     else
1808       {
1809       while (isspace(*s)) s++;
1810       if (*s++ != '=') goto BAD_VERIFY;
1811       while (isspace(*s)) s++;
1812       verify_sender_address = string_copy(s);
1813       }
1814     }
1815     break;
1816
1817   case VERIFY_RCPT:
1818     break;
1819   }
1820
1821
1822
1823 /* Remaining items are optional; they apply to sender and recipient
1824 verification, including "header sender" verification. */
1825
1826 while ((ss = string_nextinlist(&list, &sep, NULL, 0)))
1827   {
1828   if (strcmpic(ss, US"defer_ok") == 0) defer_ok = TRUE;
1829   else if (strcmpic(ss, US"no_details") == 0) no_details = TRUE;
1830   else if (strcmpic(ss, US"success_on_redirect") == 0) success_on_redirect = TRUE;
1831
1832   /* These two old options are left for backwards compatibility */
1833
1834   else if (strcmpic(ss, US"callout_defer_ok") == 0)
1835     {
1836     callout_defer_ok = TRUE;
1837     if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
1838     }
1839
1840   else if (strcmpic(ss, US"check_postmaster") == 0)
1841      {
1842      pm_mailfrom = US"";
1843      if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
1844      }
1845
1846   /* The callout option has a number of sub-options, comma separated */
1847
1848   else if (strncmpic(ss, US"callout", 7) == 0)
1849     {
1850     callout = CALLOUT_TIMEOUT_DEFAULT;
1851     if (*(ss += 7))
1852       {
1853       while (isspace(*ss)) ss++;
1854       if (*ss++ == '=')
1855         {
1856         const uschar * sublist = ss;
1857         int optsep = ',';
1858
1859         while (isspace(*sublist)) sublist++;
1860         for (uschar * opt; opt = string_nextinlist(&sublist, &optsep, NULL, 0); )
1861           {
1862           callout_opt_t * op;
1863           double period = 1.0F;
1864
1865           for (op= callout_opt_list; op->name; op++)
1866             if (strncmpic(opt, op->name, Ustrlen(op->name)) == 0)
1867               break;
1868
1869           verify_options |= op->flag;
1870           if (op->has_option)
1871             {
1872             opt += Ustrlen(op->name);
1873             while (isspace(*opt)) opt++;
1874             if (*opt++ != '=')
1875               {
1876               *log_msgptr = string_sprintf("'=' expected after "
1877                 "\"%s\" in ACL verify condition \"%s\"", op->name, arg);
1878               return ERROR;
1879               }
1880             while (isspace(*opt)) opt++;
1881             }
1882           if (op->timeval && (period = v_period(opt, arg, log_msgptr)) < 0)
1883             return ERROR;
1884
1885           switch(op->value)
1886             {
1887             case CALLOUT_DEFER_OK:              callout_defer_ok = TRUE; break;
1888             case CALLOUT_POSTMASTER:            pm_mailfrom = US"";     break;
1889             case CALLOUT_FULLPOSTMASTER:        pm_mailfrom = US"";     break;
1890             case CALLOUT_MAILFROM:
1891               if (!verify_header_sender)
1892                 {
1893                 *log_msgptr = string_sprintf("\"mailfrom\" is allowed as a "
1894                   "callout option only for verify=header_sender (detected in ACL "
1895                   "condition \"%s\")", arg);
1896                 return ERROR;
1897                 }
1898               se_mailfrom = string_copy(opt);
1899               break;
1900             case CALLOUT_POSTMASTER_MAILFROM:   pm_mailfrom = string_copy(opt); break;
1901             case CALLOUT_MAXWAIT:               callout_overall = period;       break;
1902             case CALLOUT_CONNECT:               callout_connect = period;       break;
1903             case CALLOUT_TIME:                  callout = period;               break;
1904             }
1905           }
1906         }
1907       else
1908         {
1909         *log_msgptr = string_sprintf("'=' expected after \"callout\" in "
1910           "ACL condition \"%s\"", arg);
1911         return ERROR;
1912         }
1913       }
1914     }
1915
1916   /* The quota option has sub-options, comma-separated */
1917
1918   else if (strncmpic(ss, US"quota", 5) == 0)
1919     {
1920     quota = TRUE;
1921     if (*(ss += 5))
1922       {
1923       while (isspace(*ss)) ss++;
1924       if (*ss++ == '=')
1925         {
1926         const uschar * sublist = ss;
1927         int optsep = ',';
1928         int period;
1929
1930         while (isspace(*sublist)) sublist++;
1931         for (uschar * opt; opt = string_nextinlist(&sublist, &optsep, NULL, 0); )
1932           if (Ustrncmp(opt, "cachepos=", 9) == 0)
1933             if ((period = v_period(opt += 9, arg, log_msgptr)) < 0)
1934               return ERROR;
1935             else
1936               quota_pos_cache = period;
1937           else if (Ustrncmp(opt, "cacheneg=", 9) == 0)
1938             if ((period = v_period(opt += 9, arg, log_msgptr)) < 0)
1939               return ERROR;
1940             else
1941               quota_neg_cache = period;
1942           else if (Ustrcmp(opt, "no_cache") == 0)
1943             quota_pos_cache = quota_neg_cache = 0;
1944         }
1945       }
1946     }
1947
1948   /* Option not recognized */
1949
1950   else
1951     {
1952     *log_msgptr = string_sprintf("unknown option \"%s\" in ACL "
1953       "condition \"verify %s\"", ss, arg);
1954     return ERROR;
1955     }
1956   }
1957
1958 if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster)) ==
1959       (vopt_callout_recipsender|vopt_callout_recippmaster))
1960   {
1961   *log_msgptr = US"only one of use_sender and use_postmaster can be set "
1962     "for a recipient callout";
1963   return ERROR;
1964   }
1965
1966 /* Handle quota verification */
1967 if (quota)
1968   {
1969   if (vp->value != VERIFY_RCPT)
1970     {
1971     *log_msgptr = US"can only verify quota of recipient";
1972     return ERROR;
1973     }
1974
1975   if ((rc = verify_quota_call(addr->address,
1976               quota_pos_cache, quota_neg_cache, log_msgptr)) != OK)
1977     {
1978     *basic_errno = errno;
1979     if (smtp_return_error_details)
1980       {
1981       if (!*user_msgptr && *log_msgptr)
1982         *user_msgptr = string_sprintf("Rejected after %s: %s",
1983             smtp_names[smtp_connection_had[SMTP_HBUFF_PREV(smtp_ch_index)]],
1984             *log_msgptr);
1985       if (rc == DEFER) f.acl_temp_details = TRUE;
1986       }
1987     }
1988
1989   return rc;
1990   }
1991
1992 /* Handle sender-in-header verification. Default the user message to the log
1993 message if giving out verification details. */
1994
1995 if (verify_header_sender)
1996   {
1997   int verrno;
1998
1999   if ((rc = verify_check_header_address(user_msgptr, log_msgptr, callout,
2000     callout_overall, callout_connect, se_mailfrom, pm_mailfrom, verify_options,
2001     &verrno)) != OK)
2002     {
2003     *basic_errno = verrno;
2004     if (smtp_return_error_details)
2005       {
2006       if (!*user_msgptr && *log_msgptr)
2007         *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
2008       if (rc == DEFER) f.acl_temp_details = TRUE;
2009       }
2010     }
2011   }
2012
2013 /* Handle a sender address. The default is to verify *the* sender address, but
2014 optionally a different address can be given, for special requirements. If the
2015 address is empty, we are dealing with a bounce message that has no sender, so
2016 we cannot do any checking. If the real sender address gets rewritten during
2017 verification (e.g. DNS widening), set the flag to stop it being rewritten again
2018 during message reception.
2019
2020 A list of verified "sender" addresses is kept to try to avoid doing to much
2021 work repetitively when there are multiple recipients in a message and they all
2022 require sender verification. However, when callouts are involved, it gets too
2023 complicated because different recipients may require different callout options.
2024 Therefore, we always do a full sender verify when any kind of callout is
2025 specified. Caching elsewhere, for instance in the DNS resolver and in the
2026 callout handling, should ensure that this is not terribly inefficient. */
2027
2028 else if (verify_sender_address)
2029   {
2030   if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster)))
2031     {
2032     *log_msgptr = US"use_sender or use_postmaster cannot be used for a "
2033       "sender verify callout";
2034     return ERROR;
2035     }
2036
2037   sender_vaddr = verify_checked_sender(verify_sender_address);
2038   if (   sender_vaddr                           /* Previously checked */
2039       && callout <= 0)                          /* No callout needed this time */
2040     {
2041     /* If the "routed" flag is set, it means that routing worked before, so
2042     this check can give OK (the saved return code value, if set, belongs to a
2043     callout that was done previously). If the "routed" flag is not set, routing
2044     must have failed, so we use the saved return code. */
2045
2046     if (testflag(sender_vaddr, af_verify_routed))
2047       rc = OK;
2048     else
2049       {
2050       rc = sender_vaddr->special_action;
2051       *basic_errno = sender_vaddr->basic_errno;
2052       }
2053     HDEBUG(D_acl) debug_printf_indent("using cached sender verify result\n");
2054     }
2055
2056   /* Do a new verification, and cache the result. The cache is used to avoid
2057   verifying the sender multiple times for multiple RCPTs when callouts are not
2058   specified (see comments above).
2059
2060   The cache is also used on failure to give details in response to the first
2061   RCPT that gets bounced for this reason. However, this can be suppressed by
2062   the no_details option, which sets the flag that says "this detail has already
2063   been sent". The cache normally contains just one address, but there may be
2064   more in esoteric circumstances. */
2065
2066   else
2067     {
2068     BOOL routed = TRUE;
2069     uschar *save_address_data = deliver_address_data;
2070
2071     sender_vaddr = deliver_make_addr(verify_sender_address, TRUE);
2072 #ifdef SUPPORT_I18N
2073     if ((sender_vaddr->prop.utf8_msg = message_smtputf8))
2074       {
2075       sender_vaddr->prop.utf8_downcvt =       message_utf8_downconvert == 1;
2076       sender_vaddr->prop.utf8_downcvt_maybe = message_utf8_downconvert == -1;
2077       }
2078 #endif
2079     if (no_details) setflag(sender_vaddr, af_sverify_told);
2080     if (verify_sender_address[0] != 0)
2081       {
2082       /* If this is the real sender address, save the unrewritten version
2083       for use later in receive. Otherwise, set a flag so that rewriting the
2084       sender in verify_address() does not update sender_address. */
2085
2086       if (verify_sender_address == sender_address)
2087         sender_address_unrewritten = sender_address;
2088       else
2089         verify_options |= vopt_fake_sender;
2090
2091       if (success_on_redirect)
2092         verify_options |= vopt_success_on_redirect;
2093
2094       /* The recipient, qualify, and expn options are never set in
2095       verify_options. */
2096
2097       rc = verify_address(sender_vaddr, NULL, verify_options, callout,
2098         callout_overall, callout_connect, se_mailfrom, pm_mailfrom, &routed);
2099
2100       HDEBUG(D_acl) debug_printf_indent("----------- end verify ------------\n");
2101
2102       if (rc != OK)
2103         *basic_errno = sender_vaddr->basic_errno;
2104       else
2105         DEBUG(D_acl)
2106           if (Ustrcmp(sender_vaddr->address, verify_sender_address) != 0)
2107             debug_printf_indent("sender %s verified ok as %s\n",
2108               verify_sender_address, sender_vaddr->address);
2109           else
2110             debug_printf_indent("sender %s verified ok\n",
2111               verify_sender_address);
2112       }
2113     else
2114       rc = OK;  /* Null sender */
2115
2116     /* Cache the result code */
2117
2118     if (routed) setflag(sender_vaddr, af_verify_routed);
2119     if (callout > 0) setflag(sender_vaddr, af_verify_callout);
2120     sender_vaddr->special_action = rc;
2121     sender_vaddr->next = sender_verified_list;
2122     sender_verified_list = sender_vaddr;
2123
2124     /* Restore the recipient address data, which might have been clobbered by
2125     the sender verification. */
2126
2127     deliver_address_data = save_address_data;
2128     }
2129
2130   /* Put the sender address_data value into $sender_address_data */
2131
2132   sender_address_data = sender_vaddr->prop.address_data;
2133   }
2134
2135 /* A recipient address just gets a straightforward verify; again we must handle
2136 the DEFER overrides. */
2137
2138 else
2139   {
2140   address_item addr2;
2141
2142   if (success_on_redirect)
2143     verify_options |= vopt_success_on_redirect;
2144
2145   /* We must use a copy of the address for verification, because it might
2146   get rewritten. */
2147
2148   addr2 = *addr;
2149   rc = verify_address(&addr2, NULL, verify_options|vopt_is_recipient, callout,
2150     callout_overall, callout_connect, se_mailfrom, pm_mailfrom, NULL);
2151   HDEBUG(D_acl) debug_printf_indent("----------- end verify ------------\n");
2152
2153   *basic_errno = addr2.basic_errno;
2154   *log_msgptr = addr2.message;
2155   *user_msgptr = addr2.user_message ? addr2.user_message : addr2.message;
2156
2157   /* Allow details for temporary error if the address is so flagged. */
2158   if (testflag((&addr2), af_pass_message)) f.acl_temp_details = TRUE;
2159
2160   /* Make $address_data visible */
2161   deliver_address_data = addr2.prop.address_data;
2162   }
2163
2164 /* We have a result from the relevant test. Handle defer overrides first. */
2165
2166 if (  rc == DEFER
2167    && (  defer_ok
2168       || callout_defer_ok && *basic_errno == ERRNO_CALLOUTDEFER
2169    )  )
2170   {
2171   HDEBUG(D_acl) debug_printf_indent("verify defer overridden by %s\n",
2172     defer_ok? "defer_ok" : "callout_defer_ok");
2173   rc = OK;
2174   }
2175
2176 /* If we've failed a sender, set up a recipient message, and point
2177 sender_verified_failed to the address item that actually failed. */
2178
2179 if (rc != OK && verify_sender_address)
2180   {
2181   if (rc != DEFER)
2182     *log_msgptr = *user_msgptr = US"Sender verify failed";
2183   else if (*basic_errno != ERRNO_CALLOUTDEFER)
2184     *log_msgptr = *user_msgptr = US"Could not complete sender verify";
2185   else
2186     {
2187     *log_msgptr = US"Could not complete sender verify callout";
2188     *user_msgptr = smtp_return_error_details? sender_vaddr->user_message :
2189       *log_msgptr;
2190     }
2191
2192   sender_verified_failed = sender_vaddr;
2193   }
2194
2195 /* Verifying an address messes up the values of $domain and $local_part,
2196 so reset them before returning if this is a RCPT ACL. */
2197
2198 if (addr)
2199   {
2200   deliver_domain = addr->domain;
2201   deliver_localpart = addr->local_part;
2202   }
2203 return rc;
2204
2205 /* Syntax errors in the verify argument come here. */
2206
2207 BAD_VERIFY:
2208 *log_msgptr = string_sprintf("expected \"sender[=address]\", \"recipient\", "
2209   "\"helo\", \"header_syntax\", \"header_sender\", \"header_names_ascii\" "
2210   "or \"reverse_host_lookup\" at start of ACL condition "
2211   "\"verify %s\"", arg);
2212 return ERROR;
2213 }
2214
2215
2216
2217
2218 /*************************************************
2219 *        Check argument for control= modifier    *
2220 *************************************************/
2221
2222 /* Called from acl_check_condition() below.
2223 To handle the case "queue_only" we accept an _ in the
2224 initial / option-switch position.
2225
2226 Arguments:
2227   arg         the argument string for control=
2228   pptr        set to point to the terminating character
2229   where       which ACL we are in
2230   log_msgptr  for error messages
2231
2232 Returns:      CONTROL_xxx value
2233 */
2234
2235 static int
2236 decode_control(const uschar *arg, const uschar **pptr, int where, uschar **log_msgptr)
2237 {
2238 int idx, len;
2239 control_def * d;
2240 uschar c;
2241
2242 if (  (idx = find_control(arg, controls_list, nelem(controls_list))) < 0
2243    || (  (c = arg[len = Ustrlen((d = controls_list+idx)->name)]) != 0
2244       && (!d->has_option || c != '/' && c != '_')
2245    )  )
2246   {
2247   *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
2248   return CONTROL_ERROR;
2249   }
2250
2251 *pptr = arg + len;
2252 return idx;
2253 }
2254
2255
2256
2257
2258 /*************************************************
2259 *        Return a ratelimit error                *
2260 *************************************************/
2261
2262 /* Called from acl_ratelimit() below
2263
2264 Arguments:
2265   log_msgptr  for error messages
2266   format      format string
2267   ...         supplementary arguments
2268
2269 Returns:      ERROR
2270 */
2271
2272 static int
2273 ratelimit_error(uschar **log_msgptr, const char *format, ...)
2274 {
2275 va_list ap;
2276 gstring * g =
2277   string_cat(NULL, US"error in arguments to \"ratelimit\" condition: ");
2278
2279 va_start(ap, format);
2280 g = string_vformat(g, SVFMT_EXTEND|SVFMT_REBUFFER, format, ap);
2281 va_end(ap);
2282
2283 gstring_release_unused(g);
2284 *log_msgptr = string_from_gstring(g);
2285 return ERROR;
2286 }
2287
2288
2289
2290
2291 /*************************************************
2292 *            Handle rate limiting                *
2293 *************************************************/
2294
2295 /* Called by acl_check_condition() below to calculate the result
2296 of the ACL ratelimit condition.
2297
2298 Note that the return value might be slightly unexpected: if the
2299 sender's rate is above the limit then the result is OK. This is
2300 similar to the dnslists condition, and is so that you can write
2301 ACL clauses like: defer ratelimit = 15 / 1h
2302
2303 Arguments:
2304   arg         the option string for ratelimit=
2305   where       ACL_WHERE_xxxx indicating which ACL this is
2306   log_msgptr  for error messages
2307
2308 Returns:       OK        - Sender's rate is above limit
2309                FAIL      - Sender's rate is below limit
2310                DEFER     - Problem opening ratelimit database
2311                ERROR     - Syntax error in options.
2312 */
2313
2314 static int
2315 acl_ratelimit(const uschar *arg, int where, uschar **log_msgptr)
2316 {
2317 double limit, period, count;
2318 uschar *ss;
2319 uschar *key = NULL;
2320 uschar *unique = NULL;
2321 int sep = '/';
2322 BOOL leaky = FALSE, strict = FALSE, readonly = FALSE;
2323 BOOL noupdate = FALSE, badacl = FALSE;
2324 int mode = RATE_PER_WHAT;
2325 int old_pool, rc;
2326 tree_node **anchor, *t;
2327 open_db dbblock, *dbm;
2328 int dbdb_size;
2329 dbdata_ratelimit *dbd;
2330 dbdata_ratelimit_unique *dbdb;
2331 struct timeval tv;
2332
2333 /* Parse the first two options and record their values in expansion
2334 variables. These variables allow the configuration to have informative
2335 error messages based on rate limits obtained from a table lookup. */
2336
2337 /* First is the maximum number of messages per period / maximum burst
2338 size, which must be greater than or equal to zero. Zero is useful for
2339 rate measurement as opposed to rate limiting. */
2340
2341 if (!(sender_rate_limit = string_nextinlist(&arg, &sep, NULL, 0)))
2342   return ratelimit_error(log_msgptr, "sender rate limit not set");
2343
2344 limit = Ustrtod(sender_rate_limit, &ss);
2345 if      (tolower(*ss) == 'k') { limit *= 1024.0; ss++; }
2346 else if (tolower(*ss) == 'm') { limit *= 1024.0*1024.0; ss++; }
2347 else if (tolower(*ss) == 'g') { limit *= 1024.0*1024.0*1024.0; ss++; }
2348
2349 if (limit < 0.0 || *ss != '\0')
2350   return ratelimit_error(log_msgptr,
2351     "\"%s\" is not a positive number", sender_rate_limit);
2352
2353 /* Second is the rate measurement period / exponential smoothing time
2354 constant. This must be strictly greater than zero, because zero leads to
2355 run-time division errors. */
2356
2357 period = !(sender_rate_period = string_nextinlist(&arg, &sep, NULL, 0))
2358   ? -1.0 : readconf_readtime(sender_rate_period, 0, FALSE);
2359 if (period <= 0.0)
2360   return ratelimit_error(log_msgptr,
2361     "\"%s\" is not a time value", sender_rate_period);
2362
2363 /* By default we are counting one of something, but the per_rcpt,
2364 per_byte, and count options can change this. */
2365
2366 count = 1.0;
2367
2368 /* Parse the other options. */
2369
2370 while ((ss = string_nextinlist(&arg, &sep, NULL, 0)))
2371   {
2372   if (strcmpic(ss, US"leaky") == 0) leaky = TRUE;
2373   else if (strcmpic(ss, US"strict") == 0) strict = TRUE;
2374   else if (strcmpic(ss, US"noupdate") == 0) noupdate = TRUE;
2375   else if (strcmpic(ss, US"readonly") == 0) readonly = TRUE;
2376   else if (strcmpic(ss, US"per_cmd") == 0) RATE_SET(mode, PER_CMD);
2377   else if (strcmpic(ss, US"per_conn") == 0)
2378     {
2379     RATE_SET(mode, PER_CONN);
2380     if (where == ACL_WHERE_NOTSMTP || where == ACL_WHERE_NOTSMTP_START)
2381       badacl = TRUE;
2382     }
2383   else if (strcmpic(ss, US"per_mail") == 0)
2384     {
2385     RATE_SET(mode, PER_MAIL);
2386     if (where > ACL_WHERE_NOTSMTP) badacl = TRUE;
2387     }
2388   else if (strcmpic(ss, US"per_rcpt") == 0)
2389     {
2390     /* If we are running in the RCPT ACL, then we'll count the recipients
2391     one by one, but if we are running when we have accumulated the whole
2392     list then we'll add them all in one batch. */
2393     if (where == ACL_WHERE_RCPT)
2394       RATE_SET(mode, PER_RCPT);
2395     else if (where >= ACL_WHERE_PREDATA && where <= ACL_WHERE_NOTSMTP)
2396       RATE_SET(mode, PER_ALLRCPTS), count = (double)recipients_count;
2397     else if (where == ACL_WHERE_MAIL || where > ACL_WHERE_NOTSMTP)
2398       RATE_SET(mode, PER_RCPT), badacl = TRUE;
2399     }
2400   else if (strcmpic(ss, US"per_byte") == 0)
2401     {
2402     /* If we have not yet received the message data and there was no SIZE
2403     declaration on the MAIL command, then it's safe to just use a value of
2404     zero and let the recorded rate decay as if nothing happened. */
2405     RATE_SET(mode, PER_MAIL);
2406     if (where > ACL_WHERE_NOTSMTP) badacl = TRUE;
2407     else count = message_size < 0 ? 0.0 : (double)message_size;
2408     }
2409   else if (strcmpic(ss, US"per_addr") == 0)
2410     {
2411     RATE_SET(mode, PER_RCPT);
2412     if (where != ACL_WHERE_RCPT) badacl = TRUE, unique = US"*";
2413     else unique = string_sprintf("%s@%s", deliver_localpart, deliver_domain);
2414     }
2415   else if (strncmpic(ss, US"count=", 6) == 0)
2416     {
2417     uschar *e;
2418     count = Ustrtod(ss+6, &e);
2419     if (count < 0.0 || *e != '\0')
2420       return ratelimit_error(log_msgptr, "\"%s\" is not a positive number", ss);
2421     }
2422   else if (strncmpic(ss, US"unique=", 7) == 0)
2423     unique = string_copy(ss + 7);
2424   else if (!key)
2425     key = string_copy(ss);
2426   else
2427     key = string_sprintf("%s/%s", key, ss);
2428   }
2429
2430 /* Sanity check. When the badacl flag is set the update mode must either
2431 be readonly (which is the default if it is omitted) or, for backwards
2432 compatibility, a combination of noupdate and strict or leaky. */
2433
2434 if (mode == RATE_PER_CLASH)
2435   return ratelimit_error(log_msgptr, "conflicting per_* options");
2436 if (leaky + strict + readonly > 1)
2437   return ratelimit_error(log_msgptr, "conflicting update modes");
2438 if (badacl && (leaky || strict) && !noupdate)
2439   return ratelimit_error(log_msgptr,
2440     "\"%s\" must not have /leaky or /strict option, or cannot be used in %s ACL",
2441     ratelimit_option_string[mode], acl_wherenames[where]);
2442
2443 /* Set the default values of any unset options. In readonly mode we
2444 perform the rate computation without any increment so that its value
2445 decays to eventually allow over-limit senders through. */
2446
2447 if (noupdate) readonly = TRUE, leaky = strict = FALSE;
2448 if (badacl) readonly = TRUE;
2449 if (readonly) count = 0.0;
2450 if (!strict && !readonly) leaky = TRUE;
2451 if (mode == RATE_PER_WHAT) mode = RATE_PER_MAIL;
2452
2453 /* Create the lookup key. If there is no explicit key, use sender_host_address.
2454 If there is no sender_host_address (e.g. -bs or acl_not_smtp) then we simply
2455 omit it. The smoothing constant (sender_rate_period) and the per_xxx options
2456 are added to the key because they alter the meaning of the stored data. */
2457
2458 if (!key)
2459   key = !sender_host_address ? US"" : sender_host_address;
2460
2461 key = string_sprintf("%s/%s/%s%s",
2462   sender_rate_period,
2463   ratelimit_option_string[mode],
2464   unique == NULL ? "" : "unique/",
2465   key);
2466
2467 HDEBUG(D_acl)
2468   debug_printf_indent("ratelimit condition count=%.0f %.1f/%s\n", count, limit, key);
2469
2470 /* See if we have already computed the rate by looking in the relevant tree.
2471 For per-connection rate limiting, store tree nodes and dbdata in the permanent
2472 pool so that they survive across resets. In readonly mode we only remember the
2473 result for the rest of this command in case a later command changes it. After
2474 this bit of logic the code is independent of the per_* mode. */
2475
2476 old_pool = store_pool;
2477
2478 if (readonly)
2479   anchor = &ratelimiters_cmd;
2480 else switch(mode)
2481   {
2482   case RATE_PER_CONN:
2483     anchor = &ratelimiters_conn;
2484     store_pool = POOL_PERM;
2485     break;
2486   case RATE_PER_BYTE:
2487   case RATE_PER_MAIL:
2488   case RATE_PER_ALLRCPTS:
2489     anchor = &ratelimiters_mail;
2490     break;
2491   case RATE_PER_ADDR:
2492   case RATE_PER_CMD:
2493   case RATE_PER_RCPT:
2494     anchor = &ratelimiters_cmd;
2495     break;
2496   default:
2497     anchor = NULL; /* silence an "unused" complaint */
2498     log_write(0, LOG_MAIN|LOG_PANIC_DIE,
2499       "internal ACL error: unknown ratelimit mode %d", mode);
2500     break;
2501   }
2502
2503 if ((t = tree_search(*anchor, key)))
2504   {
2505   dbd = t->data.ptr;
2506   /* The following few lines duplicate some of the code below. */
2507   rc = (dbd->rate < limit)? FAIL : OK;
2508   store_pool = old_pool;
2509   sender_rate = string_sprintf("%.1f", dbd->rate);
2510   HDEBUG(D_acl)
2511     debug_printf_indent("ratelimit found pre-computed rate %s\n", sender_rate);
2512   return rc;
2513   }
2514
2515 /* We aren't using a pre-computed rate, so get a previously recorded rate
2516 from the database, which will be updated and written back if required. */
2517
2518 if (!(dbm = dbfn_open(US"ratelimit", O_RDWR, &dbblock, TRUE, TRUE)))
2519   {
2520   store_pool = old_pool;
2521   sender_rate = NULL;
2522   HDEBUG(D_acl) debug_printf_indent("ratelimit database not available\n");
2523   *log_msgptr = US"ratelimit database not available";
2524   return DEFER;
2525   }
2526 dbdb = dbfn_read_with_length(dbm, key, &dbdb_size);
2527 dbd = NULL;
2528
2529 gettimeofday(&tv, NULL);
2530
2531 if (dbdb)
2532   {
2533   /* Locate the basic ratelimit block inside the DB data. */
2534   HDEBUG(D_acl) debug_printf_indent("ratelimit found key in database\n");
2535   dbd = &dbdb->dbd;
2536
2537   /* Forget the old Bloom filter if it is too old, so that we count each
2538   repeating event once per period. We don't simply clear and re-use the old
2539   filter because we want its size to change if the limit changes. Note that
2540   we keep the dbd pointer for copying the rate into the new data block. */
2541
2542   if(unique && tv.tv_sec > dbdb->bloom_epoch + period)
2543     {
2544     HDEBUG(D_acl) debug_printf_indent("ratelimit discarding old Bloom filter\n");
2545     dbdb = NULL;
2546     }
2547
2548   /* Sanity check. */
2549
2550   if(unique && dbdb_size < sizeof(*dbdb))
2551     {
2552     HDEBUG(D_acl) debug_printf_indent("ratelimit discarding undersize Bloom filter\n");
2553     dbdb = NULL;
2554     }
2555   }
2556
2557 /* Allocate a new data block if the database lookup failed
2558 or the Bloom filter passed its age limit. */
2559
2560 if (!dbdb)
2561   {
2562   if (!unique)
2563     {
2564     /* No Bloom filter. This basic ratelimit block is initialized below. */
2565     HDEBUG(D_acl) debug_printf_indent("ratelimit creating new rate data block\n");
2566     dbdb_size = sizeof(*dbd);
2567     dbdb = store_get(dbdb_size, FALSE);         /* not tainted */
2568     }
2569   else
2570     {
2571     int extra;
2572     HDEBUG(D_acl) debug_printf_indent("ratelimit creating new Bloom filter\n");
2573
2574     /* See the long comment below for an explanation of the magic number 2.
2575     The filter has a minimum size in case the rate limit is very small;
2576     this is determined by the definition of dbdata_ratelimit_unique. */
2577
2578     extra = (int)limit * 2 - sizeof(dbdb->bloom);
2579     if (extra < 0) extra = 0;
2580     dbdb_size = sizeof(*dbdb) + extra;
2581     dbdb = store_get(dbdb_size, FALSE);         /* not tainted */
2582     dbdb->bloom_epoch = tv.tv_sec;
2583     dbdb->bloom_size = sizeof(dbdb->bloom) + extra;
2584     memset(dbdb->bloom, 0, dbdb->bloom_size);
2585
2586     /* Preserve any basic ratelimit data (which is our longer-term memory)
2587     by copying it from the discarded block. */
2588
2589     if (dbd)
2590       {
2591       dbdb->dbd = *dbd;
2592       dbd = &dbdb->dbd;
2593       }
2594     }
2595   }
2596
2597 /* If we are counting unique events, find out if this event is new or not.
2598 If the client repeats the event during the current period then it should be
2599 counted. We skip this code in readonly mode for efficiency, because any
2600 changes to the filter will be discarded and because count is already set to
2601 zero. */
2602
2603 if (unique && !readonly)
2604   {
2605   /* We identify unique events using a Bloom filter. (You can find my
2606   notes on Bloom filters at http://fanf.livejournal.com/81696.html)
2607   With the per_addr option, an "event" is a recipient address, though the
2608   user can use the unique option to define their own events. We only count
2609   an event if we have not seen it before.
2610
2611   We size the filter according to the rate limit, which (in leaky mode)
2612   is the limit on the population of the filter. We allow 16 bits of space
2613   per entry (see the construction code above) and we set (up to) 8 of them
2614   when inserting an element (see the loop below). The probability of a false
2615   positive (an event we have not seen before but which we fail to count) is
2616
2617     size    = limit * 16
2618     numhash = 8
2619     allzero = exp(-numhash * pop / size)
2620             = exp(-0.5 * pop / limit)
2621     fpr     = pow(1 - allzero, numhash)
2622
2623   For senders at the limit the fpr is      0.06%    or  1 in 1700
2624   and for senders at half the limit it is  0.0006%  or  1 in 170000
2625
2626   In strict mode the Bloom filter can fill up beyond the normal limit, in
2627   which case the false positive rate will rise. This means that the
2628   measured rate for very fast senders can bogusly drop off after a while.
2629
2630   At twice the limit, the fpr is  2.5%  or  1 in 40
2631   At four times the limit, it is  31%   or  1 in 3.2
2632
2633   It takes ln(pop/limit) periods for an over-limit burst of pop events to
2634   decay below the limit, and if this is more than one then the Bloom filter
2635   will be discarded before the decay gets that far. The false positive rate
2636   at this threshold is 9.3% or 1 in 10.7. */
2637
2638   BOOL seen;
2639   unsigned n, hash, hinc;
2640   uschar md5sum[16];
2641   md5 md5info;
2642
2643   /* Instead of using eight independent hash values, we combine two values
2644   using the formula h1 + n * h2. This does not harm the Bloom filter's
2645   performance, and means the amount of hash we need is independent of the
2646   number of bits we set in the filter. */
2647
2648   md5_start(&md5info);
2649   md5_end(&md5info, unique, Ustrlen(unique), md5sum);
2650   hash = md5sum[0] | md5sum[1] << 8 | md5sum[2] << 16 | md5sum[3] << 24;
2651   hinc = md5sum[4] | md5sum[5] << 8 | md5sum[6] << 16 | md5sum[7] << 24;
2652
2653   /* Scan the bits corresponding to this event. A zero bit means we have
2654   not seen it before. Ensure all bits are set to record this event. */
2655
2656   HDEBUG(D_acl) debug_printf_indent("ratelimit checking uniqueness of %s\n", unique);
2657
2658   seen = TRUE;
2659   for (n = 0; n < 8; n++, hash += hinc)
2660     {
2661     int bit = 1 << (hash % 8);
2662     int byte = (hash / 8) % dbdb->bloom_size;
2663     if ((dbdb->bloom[byte] & bit) == 0)
2664       {
2665       dbdb->bloom[byte] |= bit;
2666       seen = FALSE;
2667       }
2668     }
2669
2670   /* If this event has occurred before, do not count it. */
2671
2672   if (seen)
2673     {
2674     HDEBUG(D_acl) debug_printf_indent("ratelimit event found in Bloom filter\n");
2675     count = 0.0;
2676     }
2677   else
2678     HDEBUG(D_acl) debug_printf_indent("ratelimit event added to Bloom filter\n");
2679   }
2680
2681 /* If there was no previous ratelimit data block for this key, initialize
2682 the new one, otherwise update the block from the database. The initial rate
2683 is what would be computed by the code below for an infinite interval. */
2684
2685 if (!dbd)
2686   {
2687   HDEBUG(D_acl) debug_printf_indent("ratelimit initializing new key's rate data\n");
2688   dbd = &dbdb->dbd;
2689   dbd->time_stamp = tv.tv_sec;
2690   dbd->time_usec = tv.tv_usec;
2691   dbd->rate = count;
2692   }
2693 else
2694   {
2695   /* The smoothed rate is computed using an exponentially weighted moving
2696   average adjusted for variable sampling intervals. The standard EWMA for
2697   a fixed sampling interval is:  f'(t) = (1 - a) * f(t) + a * f'(t - 1)
2698   where f() is the measured value and f'() is the smoothed value.
2699
2700   Old data decays out of the smoothed value exponentially, such that data n
2701   samples old is multiplied by a^n. The exponential decay time constant p
2702   is defined such that data p samples old is multiplied by 1/e, which means
2703   that a = exp(-1/p). We can maintain the same time constant for a variable
2704   sampling interval i by using a = exp(-i/p).
2705
2706   The rate we are measuring is messages per period, suitable for directly
2707   comparing with the limit. The average rate between now and the previous
2708   message is period / interval, which we feed into the EWMA as the sample.
2709
2710   It turns out that the number of messages required for the smoothed rate
2711   to reach the limit when they are sent in a burst is equal to the limit.
2712   This can be seen by analysing the value of the smoothed rate after N
2713   messages sent at even intervals. Let k = (1 - a) * p/i
2714
2715     rate_1 = (1 - a) * p/i + a * rate_0
2716            = k + a * rate_0
2717     rate_2 = k + a * rate_1
2718            = k + a * k + a^2 * rate_0
2719     rate_3 = k + a * k + a^2 * k + a^3 * rate_0
2720     rate_N = rate_0 * a^N + k * SUM(x=0..N-1)(a^x)
2721            = rate_0 * a^N + k * (1 - a^N) / (1 - a)
2722            = rate_0 * a^N + p/i * (1 - a^N)
2723
2724   When N is large, a^N -> 0 so rate_N -> p/i as desired.
2725
2726     rate_N = p/i + (rate_0 - p/i) * a^N
2727     a^N = (rate_N - p/i) / (rate_0 - p/i)
2728     N * -i/p = log((rate_N - p/i) / (rate_0 - p/i))
2729     N = p/i * log((rate_0 - p/i) / (rate_N - p/i))
2730
2731   Numerical analysis of the above equation, setting the computed rate to
2732   increase from rate_0 = 0 to rate_N = limit, shows that for large sending
2733   rates, p/i, the number of messages N = limit. So limit serves as both the
2734   maximum rate measured in messages per period, and the maximum number of
2735   messages that can be sent in a fast burst. */
2736
2737   double this_time = (double)tv.tv_sec
2738                    + (double)tv.tv_usec / 1000000.0;
2739   double prev_time = (double)dbd->time_stamp
2740                    + (double)dbd->time_usec / 1000000.0;
2741
2742   /* We must avoid division by zero, and deal gracefully with the clock going
2743   backwards. If we blunder ahead when time is in reverse then the computed
2744   rate will be bogus. To be safe we clamp interval to a very small number. */
2745
2746   double interval = this_time - prev_time <= 0.0 ? 1e-9
2747                   : this_time - prev_time;
2748
2749   double i_over_p = interval / period;
2750   double a = exp(-i_over_p);
2751
2752   /* Combine the instantaneous rate (period / interval) with the previous rate
2753   using the smoothing factor a. In order to measure sized events, multiply the
2754   instantaneous rate by the count of bytes or recipients etc. */
2755
2756   dbd->time_stamp = tv.tv_sec;
2757   dbd->time_usec = tv.tv_usec;
2758   dbd->rate = (1 - a) * count / i_over_p + a * dbd->rate;
2759
2760   /* When events are very widely spaced the computed rate tends towards zero.
2761   Although this is accurate it turns out not to be useful for our purposes,
2762   especially when the first event after a long silence is the start of a spam
2763   run. A more useful model is that the rate for an isolated event should be the
2764   size of the event per the period size, ignoring the lack of events outside
2765   the current period and regardless of where the event falls in the period. So,
2766   if the interval was so long that the calculated rate is unhelpfully small, we
2767   re-initialize the rate. In the absence of higher-rate bursts, the condition
2768   below is true if the interval is greater than the period. */
2769
2770   if (dbd->rate < count) dbd->rate = count;
2771   }
2772
2773 /* Clients sending at the limit are considered to be over the limit.
2774 This matters for edge cases such as a limit of zero, when the client
2775 should be completely blocked. */
2776
2777 rc = dbd->rate < limit ? FAIL : OK;
2778
2779 /* Update the state if the rate is low or if we are being strict. If we
2780 are in leaky mode and the sender's rate is too high, we do not update
2781 the recorded rate in order to avoid an over-aggressive sender's retry
2782 rate preventing them from getting any email through. If readonly is set,
2783 neither leaky nor strict are set, so we do not do any updates. */
2784
2785 if ((rc == FAIL && leaky) || strict)
2786   {
2787   dbfn_write(dbm, key, dbdb, dbdb_size);
2788   HDEBUG(D_acl) debug_printf_indent("ratelimit db updated\n");
2789   }
2790 else
2791   {
2792   HDEBUG(D_acl) debug_printf_indent("ratelimit db not updated: %s\n",
2793     readonly? "readonly mode" : "over the limit, but leaky");
2794   }
2795
2796 dbfn_close(dbm);
2797
2798 /* Store the result in the tree for future reference.  Take the taint status
2799 from the key for consistency even though it's unlikely we'll ever expand this. */
2800
2801 t = store_get(sizeof(tree_node) + Ustrlen(key), is_tainted(key));
2802 t->data.ptr = dbd;
2803 Ustrcpy(t->name, key);
2804 (void)tree_insertnode(anchor, t);
2805
2806 /* We create the formatted version of the sender's rate very late in
2807 order to ensure that it is done using the correct storage pool. */
2808
2809 store_pool = old_pool;
2810 sender_rate = string_sprintf("%.1f", dbd->rate);
2811
2812 HDEBUG(D_acl)
2813   debug_printf_indent("ratelimit computed rate %s\n", sender_rate);
2814
2815 return rc;
2816 }
2817
2818
2819
2820 /*************************************************
2821 *      Handle a check for previously-seen        *
2822 *************************************************/
2823
2824 /*
2825 ACL clauses like:   seen = -5m / key=$foo / readonly
2826
2827 Return is true for condition-true - but the semantics
2828 depend heavily on the actual use-case.
2829
2830 Negative times test for seen-before, positive for seen-more-recently-than
2831 (the given interval before current time).
2832
2833 All are subject to history not having been cleaned from the DB.
2834
2835 Default for seen-before is to create if not present, and to
2836 update if older than 10d (with the seen-test time).
2837 Default for seen-since is to always create or update.
2838
2839 Options:
2840   key=value.  Default key is $sender_host_address
2841   readonly
2842   write
2843   refresh=<interval>:  update an existing DB entry older than given
2844                         amount.  Default refresh lacking this option is 10d.
2845                         The update sets the record timestamp to the seen-test time.
2846
2847 XXX do we need separate nocreate, noupdate controls?
2848
2849 Arguments:
2850   arg         the option string for seen=
2851   where       ACL_WHERE_xxxx indicating which ACL this is
2852   log_msgptr  for error messages
2853
2854 Returns:       OK        - Condition is true
2855                FAIL      - Condition is false
2856                DEFER     - Problem opening history database
2857                ERROR     - Syntax error in options
2858 */
2859
2860 static int
2861 acl_seen(const uschar * arg, int where, uschar ** log_msgptr)
2862 {
2863 enum { SEEN_DEFAULT, SEEN_READONLY, SEEN_WRITE };
2864
2865 const uschar * list = arg;
2866 int slash = '/', equal = '=', interval, mode = SEEN_DEFAULT, yield = FAIL;
2867 BOOL before;
2868 int refresh = 10 * 24 * 60 * 60;        /* 10 days */
2869 const uschar * ele, * key = sender_host_address;
2870 open_db dbblock, * dbm;
2871 dbdata_seen * dbd;
2872 time_t now;
2873
2874 /* Parse the first element, the time-relation. */
2875
2876 if (!(ele = string_nextinlist(&list, &slash, NULL, 0)))
2877   goto badparse;
2878 if ((before = *ele == '-'))
2879   ele++;
2880 if ((interval = readconf_readtime(ele, 0, FALSE)) < 0)
2881   goto badparse;
2882
2883 /* Remaining elements are options */
2884
2885 while ((ele = string_nextinlist(&list, &slash, NULL, 0)))
2886   if (Ustrncmp(ele, "key=", 4) == 0)
2887     key = ele + 4;
2888   else if (Ustrcmp(ele, "readonly") == 0)
2889     mode = SEEN_READONLY;
2890   else if (Ustrcmp(ele, "write") == 0)
2891     mode = SEEN_WRITE;
2892   else if (Ustrncmp(ele, "refresh=", 8) == 0)
2893     {
2894     if ((refresh = readconf_readtime(ele + 8, 0, FALSE)) < 0)
2895       goto badparse;
2896     }
2897   else
2898     goto badopt;
2899
2900 if (!(dbm = dbfn_open(US"seen", O_RDWR, &dbblock, TRUE, TRUE)))
2901   {
2902   HDEBUG(D_acl) debug_printf_indent("database for 'seen' not available\n");
2903   *log_msgptr = US"database for 'seen' not available";
2904   return DEFER;
2905   }
2906
2907 dbd = dbfn_read_with_length(dbm, key, NULL);
2908 now = time(NULL);
2909 if (dbd)                /* an existing record */
2910   {
2911   time_t diff = now - dbd->time_stamp;  /* time since the record was written */
2912
2913   if (before ? diff >= interval : diff < interval)
2914     yield = OK;
2915
2916   if (mode == SEEN_READONLY)
2917     { HDEBUG(D_acl) debug_printf_indent("seen db not written (readonly)\n"); }
2918   else if (mode == SEEN_WRITE || !before)
2919     {
2920     dbd->time_stamp = now;
2921     dbfn_write(dbm, key, dbd, sizeof(*dbd));
2922     HDEBUG(D_acl) debug_printf_indent("seen db written (update)\n");
2923     }
2924   else if (diff >= refresh)
2925     {
2926     dbd->time_stamp = now - interval;
2927     dbfn_write(dbm, key, dbd, sizeof(*dbd));
2928     HDEBUG(D_acl) debug_printf_indent("seen db written (refresh)\n");
2929     }
2930   }
2931 else
2932   {                     /* No record found, yield always FAIL */
2933   if (mode != SEEN_READONLY)
2934     {
2935     dbdata_seen d = {.time_stamp = now};
2936     dbfn_write(dbm, key, &d, sizeof(*dbd));
2937     HDEBUG(D_acl) debug_printf_indent("seen db written (create)\n");
2938     }
2939   else
2940     HDEBUG(D_acl) debug_printf_indent("seen db not written (readonly)\n");
2941   }
2942
2943 dbfn_close(dbm);
2944 return yield;
2945
2946
2947 badparse:
2948   *log_msgptr = string_sprintf("failed to parse '%s'", arg);
2949   return ERROR;
2950 badopt:
2951   *log_msgptr = string_sprintf("unrecognised option '%s' in '%s'", ele, arg);
2952   return ERROR;
2953 }
2954
2955
2956
2957 /*************************************************
2958 *            The udpsend ACL modifier            *
2959 *************************************************/
2960
2961 /* Called by acl_check_condition() below.
2962
2963 Arguments:
2964   arg          the option string for udpsend=
2965   log_msgptr   for error messages
2966
2967 Returns:       OK        - Completed.
2968                DEFER     - Problem with DNS lookup.
2969                ERROR     - Syntax error in options.
2970 */
2971
2972 static int
2973 acl_udpsend(const uschar *arg, uschar **log_msgptr)
2974 {
2975 int sep = 0;
2976 uschar *hostname;
2977 uschar *portstr;
2978 uschar *portend;
2979 host_item *h;
2980 int portnum;
2981 int len;
2982 int r, s;
2983 uschar * errstr;
2984
2985 hostname = string_nextinlist(&arg, &sep, NULL, 0);
2986 portstr = string_nextinlist(&arg, &sep, NULL, 0);
2987
2988 if (!hostname)
2989   {
2990   *log_msgptr = US"missing destination host in \"udpsend\" modifier";
2991   return ERROR;
2992   }
2993 if (!portstr)
2994   {
2995   *log_msgptr = US"missing destination port in \"udpsend\" modifier";
2996   return ERROR;
2997   }
2998 if (!arg)
2999   {
3000   *log_msgptr = US"missing datagram payload in \"udpsend\" modifier";
3001   return ERROR;
3002   }
3003 portnum = Ustrtol(portstr, &portend, 10);
3004 if (*portend != '\0')
3005   {
3006   *log_msgptr = US"bad destination port in \"udpsend\" modifier";
3007   return ERROR;
3008   }
3009
3010 /* Make a single-item host list. */
3011 h = store_get(sizeof(host_item), FALSE);
3012 memset(h, 0, sizeof(host_item));
3013 h->name = hostname;
3014 h->port = portnum;
3015 h->mx = MX_NONE;
3016
3017 if (string_is_ip_address(hostname, NULL))
3018   h->address = hostname, r = HOST_FOUND;
3019 else
3020   r = host_find_byname(h, NULL, 0, NULL, FALSE);
3021 if (r == HOST_FIND_FAILED || r == HOST_FIND_AGAIN)
3022   {
3023   *log_msgptr = US"DNS lookup failed in \"udpsend\" modifier";
3024   return DEFER;
3025   }
3026
3027 HDEBUG(D_acl)
3028   debug_printf_indent("udpsend [%s]:%d %s\n", h->address, portnum, arg);
3029
3030 /*XXX this could better use sendto */
3031 r = s = ip_connectedsocket(SOCK_DGRAM, h->address, portnum, portnum,
3032                 1, NULL, &errstr, NULL);
3033 if (r < 0) goto defer;
3034 len = Ustrlen(arg);
3035 r = send(s, arg, len, 0);
3036 if (r < 0)
3037   {
3038   errstr = US strerror(errno);
3039   close(s);
3040   goto defer;
3041   }
3042 close(s);
3043 if (r < len)
3044   {
3045   *log_msgptr =
3046     string_sprintf("\"udpsend\" truncated from %d to %d octets", len, r);
3047   return DEFER;
3048   }
3049
3050 HDEBUG(D_acl)
3051   debug_printf_indent("udpsend %d bytes\n", r);
3052
3053 return OK;
3054
3055 defer:
3056 *log_msgptr = string_sprintf("\"udpsend\" failed: %s", errstr);
3057 return DEFER;
3058 }
3059
3060
3061
3062 /*************************************************
3063 *   Handle conditions/modifiers on an ACL item   *
3064 *************************************************/
3065
3066 /* Called from acl_check() below.
3067
3068 Arguments:
3069   verb         ACL verb
3070   cb           ACL condition block - if NULL, result is OK
3071   where        where called from
3072   addr         the address being checked for RCPT, or NULL
3073   level        the nesting level
3074   epp          pointer to pass back TRUE if "endpass" encountered
3075                  (applies only to "accept" and "discard")
3076   user_msgptr  user message pointer
3077   log_msgptr   log message pointer
3078   basic_errno  pointer to where to put verify error
3079
3080 Returns:       OK        - all conditions are met
3081                DISCARD   - an "acl" condition returned DISCARD - only allowed
3082                              for "accept" or "discard" verbs
3083                FAIL      - at least one condition fails
3084                FAIL_DROP - an "acl" condition returned FAIL_DROP
3085                DEFER     - can't tell at the moment (typically, lookup defer,
3086                              but can be temporary callout problem)
3087                ERROR     - ERROR from nested ACL or expansion failure or other
3088                              error
3089 */
3090
3091 static int
3092 acl_check_condition(int verb, acl_condition_block *cb, int where,
3093   address_item *addr, int level, BOOL *epp, uschar **user_msgptr,
3094   uschar **log_msgptr, int *basic_errno)
3095 {
3096 uschar *user_message = NULL;
3097 uschar *log_message = NULL;
3098 int rc = OK;
3099 #ifdef WITH_CONTENT_SCAN
3100 int sep = -'/';
3101 #endif
3102
3103 for (; cb; cb = cb->next)
3104   {
3105   const uschar *arg;
3106   int control_type;
3107
3108   /* The message and log_message items set up messages to be used in
3109   case of rejection. They are expanded later. */
3110
3111   if (cb->type == ACLC_MESSAGE)
3112     {
3113     HDEBUG(D_acl) debug_printf_indent("  message: %s\n", cb->arg);
3114     user_message = cb->arg;
3115     continue;
3116     }
3117
3118   if (cb->type == ACLC_LOG_MESSAGE)
3119     {
3120     HDEBUG(D_acl) debug_printf_indent("l_message: %s\n", cb->arg);
3121     log_message = cb->arg;
3122     continue;
3123     }
3124
3125   /* The endpass "condition" just sets a flag to show it occurred. This is
3126   checked at compile time to be on an "accept" or "discard" item. */
3127
3128   if (cb->type == ACLC_ENDPASS)
3129     {
3130     *epp = TRUE;
3131     continue;
3132     }
3133
3134   /* For other conditions and modifiers, the argument is expanded now for some
3135   of them, but not for all, because expansion happens down in some lower level
3136   checking functions in some cases. */
3137
3138   if (!conditions[cb->type].expand_at_top)
3139     arg = cb->arg;
3140   else if (!(arg = expand_string(cb->arg)))
3141     {
3142     if (f.expand_string_forcedfail) continue;
3143     *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s",
3144       cb->arg, expand_string_message);
3145     return f.search_find_defer ? DEFER : ERROR;
3146     }
3147
3148   /* Show condition, and expanded condition if it's different */
3149
3150   HDEBUG(D_acl)
3151     {
3152     int lhswidth = 0;
3153     debug_printf_indent("check %s%s %n",
3154       (!conditions[cb->type].is_modifier && cb->u.negated)? "!":"",
3155       conditions[cb->type].name, &lhswidth);
3156
3157     if (cb->type == ACLC_SET)
3158       {
3159 #ifndef DISABLE_DKIM
3160       if (  Ustrcmp(cb->u.varname, "dkim_verify_status") == 0
3161          || Ustrcmp(cb->u.varname, "dkim_verify_reason") == 0)
3162         {
3163         debug_printf("%s ", cb->u.varname);
3164         lhswidth += 19;
3165         }
3166       else
3167 #endif
3168         {
3169         debug_printf("acl_%s ", cb->u.varname);
3170         lhswidth += 5 + Ustrlen(cb->u.varname);
3171         }
3172       }
3173
3174     debug_printf("= %s\n", cb->arg);
3175
3176     if (arg != cb->arg)
3177       debug_printf("%.*s= %s\n", lhswidth,
3178       US"                             ", CS arg);
3179     }
3180
3181   /* Check that this condition makes sense at this time */
3182
3183   if ((conditions[cb->type].forbids & (1 << where)) != 0)
3184     {
3185     *log_msgptr = string_sprintf("cannot %s %s condition in %s ACL",
3186       conditions[cb->type].is_modifier ? "use" : "test",
3187       conditions[cb->type].name, acl_wherenames[where]);
3188     return ERROR;
3189     }
3190
3191   /* Run the appropriate test for each condition, or take the appropriate
3192   action for the remaining modifiers. */
3193
3194   switch(cb->type)
3195     {
3196     case ACLC_ADD_HEADER:
3197     setup_header(arg);
3198     break;
3199
3200     /* A nested ACL that returns "discard" makes sense only for an "accept" or
3201     "discard" verb. */
3202
3203     case ACLC_ACL:
3204       rc = acl_check_wargs(where, addr, arg, user_msgptr, log_msgptr);
3205       if (rc == DISCARD && verb != ACL_ACCEPT && verb != ACL_DISCARD)
3206         {
3207         *log_msgptr = string_sprintf("nested ACL returned \"discard\" for "
3208           "\"%s\" command (only allowed with \"accept\" or \"discard\")",
3209           verbs[verb]);
3210         return ERROR;
3211         }
3212     break;
3213
3214     case ACLC_AUTHENTICATED:
3215       rc = sender_host_authenticated ? match_isinlist(sender_host_authenticated,
3216               &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL) : FAIL;
3217     break;
3218
3219     #ifdef EXPERIMENTAL_BRIGHTMAIL
3220     case ACLC_BMI_OPTIN:
3221       {
3222       int old_pool = store_pool;
3223       store_pool = POOL_PERM;
3224       bmi_current_optin = string_copy(arg);
3225       store_pool = old_pool;
3226       }
3227     break;
3228     #endif
3229
3230     case ACLC_CONDITION:
3231     /* The true/false parsing here should be kept in sync with that used in
3232     expand.c when dealing with ECOND_BOOL so that we don't have too many
3233     different definitions of what can be a boolean. */
3234     if (*arg == '-'
3235         ? Ustrspn(arg+1, "0123456789") == Ustrlen(arg+1)    /* Negative number */
3236         : Ustrspn(arg,   "0123456789") == Ustrlen(arg))     /* Digits, or empty */
3237       rc = (Uatoi(arg) == 0)? FAIL : OK;
3238     else
3239       rc = (strcmpic(arg, US"no") == 0 ||
3240             strcmpic(arg, US"false") == 0)? FAIL :
3241            (strcmpic(arg, US"yes") == 0 ||
3242             strcmpic(arg, US"true") == 0)? OK : DEFER;
3243     if (rc == DEFER)
3244       *log_msgptr = string_sprintf("invalid \"condition\" value \"%s\"", arg);
3245     break;
3246
3247     case ACLC_CONTINUE:    /* Always succeeds */
3248     break;
3249
3250     case ACLC_CONTROL:
3251       {
3252       const uschar *p = NULL;
3253       control_type = decode_control(arg, &p, where, log_msgptr);
3254
3255       /* Check if this control makes sense at this time */
3256
3257       if (controls_list[control_type].forbids & (1 << where))
3258         {
3259         *log_msgptr = string_sprintf("cannot use \"control=%s\" in %s ACL",
3260           controls_list[control_type].name, acl_wherenames[where]);
3261         return ERROR;
3262         }
3263
3264       switch(control_type)
3265         {
3266         case CONTROL_AUTH_UNADVERTISED:
3267           f.allow_auth_unadvertised = TRUE;
3268           break;
3269
3270 #ifdef EXPERIMENTAL_BRIGHTMAIL
3271         case CONTROL_BMI_RUN:
3272           bmi_run = 1;
3273           break;
3274 #endif
3275
3276 #ifndef DISABLE_DKIM
3277         case CONTROL_DKIM_VERIFY:
3278           f.dkim_disable_verify = TRUE;
3279 # ifdef SUPPORT_DMARC
3280           /* Since DKIM was blocked, skip DMARC too */
3281           f.dmarc_disable_verify = TRUE;
3282           f.dmarc_enable_forensic = FALSE;
3283 # endif
3284         break;
3285 #endif
3286
3287 #ifdef SUPPORT_DMARC
3288         case CONTROL_DMARC_VERIFY:
3289           f.dmarc_disable_verify = TRUE;
3290           break;
3291
3292         case CONTROL_DMARC_FORENSIC:
3293           f.dmarc_enable_forensic = TRUE;
3294           break;
3295 #endif
3296
3297         case CONTROL_DSCP:
3298           if (*p == '/')
3299             {
3300             int fd, af, level, optname, value;
3301             /* If we are acting on stdin, the setsockopt may fail if stdin is not
3302             a socket; we can accept that, we'll just debug-log failures anyway. */
3303             fd = fileno(smtp_in);
3304             if ((af = ip_get_address_family(fd)) < 0)
3305               {
3306               HDEBUG(D_acl)
3307                 debug_printf_indent("smtp input is probably not a socket [%s], not setting DSCP\n",
3308                     strerror(errno));
3309               break;
3310               }
3311             if (dscp_lookup(p+1, af, &level, &optname, &value))
3312               if (setsockopt(fd, level, optname, &value, sizeof(value)) < 0)
3313                 {
3314                 HDEBUG(D_acl) debug_printf_indent("failed to set input DSCP[%s]: %s\n",
3315                     p+1, strerror(errno));
3316                 }
3317               else
3318                 {
3319                 HDEBUG(D_acl) debug_printf_indent("set input DSCP to \"%s\"\n", p+1);
3320                 }
3321             else
3322               {
3323               *log_msgptr = string_sprintf("unrecognised DSCP value in \"control=%s\"", arg);
3324               return ERROR;
3325               }
3326             }
3327           else
3328             {
3329             *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
3330             return ERROR;
3331             }
3332           break;
3333
3334         case CONTROL_ERROR:
3335           return ERROR;
3336
3337         case CONTROL_CASEFUL_LOCAL_PART:
3338           deliver_localpart = addr->cc_local_part;
3339           break;
3340
3341         case CONTROL_CASELOWER_LOCAL_PART:
3342           deliver_localpart = addr->lc_local_part;
3343           break;
3344
3345         case CONTROL_ENFORCE_SYNC:
3346           smtp_enforce_sync = TRUE;
3347           break;
3348
3349         case CONTROL_NO_ENFORCE_SYNC:
3350           smtp_enforce_sync = FALSE;
3351           break;
3352
3353 #ifdef WITH_CONTENT_SCAN
3354         case CONTROL_NO_MBOX_UNSPOOL:
3355           f.no_mbox_unspool = TRUE;
3356           break;
3357 #endif
3358
3359         case CONTROL_NO_MULTILINE:
3360           f.no_multiline_responses = TRUE;
3361           break;
3362
3363         case CONTROL_NO_PIPELINING:
3364           f.pipelining_enable = FALSE;
3365           break;
3366
3367         case CONTROL_NO_DELAY_FLUSH:
3368           f.disable_delay_flush = TRUE;
3369           break;
3370
3371         case CONTROL_NO_CALLOUT_FLUSH:
3372           f.disable_callout_flush = TRUE;
3373           break;
3374
3375         case CONTROL_FAKEREJECT:
3376           cancel_cutthrough_connection(TRUE, US"fakereject");
3377         case CONTROL_FAKEDEFER:
3378           fake_response = (control_type == CONTROL_FAKEDEFER) ? DEFER : FAIL;
3379           if (*p == '/')
3380             {
3381             const uschar *pp = p + 1;
3382             while (*pp) pp++;
3383             /* The entire control= line was expanded at top so no need to expand
3384             the part after the / */
3385             fake_response_text = string_copyn(p+1, pp-p-1);
3386             p = pp;
3387             }
3388            else /* Explicitly reset to default string */
3389             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).";
3390           break;
3391
3392         case CONTROL_FREEZE:
3393           f.deliver_freeze = TRUE;
3394           deliver_frozen_at = time(NULL);
3395           freeze_tell = freeze_tell_config;       /* Reset to configured value */
3396           if (Ustrncmp(p, "/no_tell", 8) == 0)
3397             {
3398             p += 8;
3399             freeze_tell = NULL;
3400             }
3401           if (*p)
3402             {
3403             *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
3404             return ERROR;
3405             }
3406           cancel_cutthrough_connection(TRUE, US"item frozen");
3407           break;
3408
3409         case CONTROL_QUEUE:
3410           f.queue_only_policy = TRUE;
3411           if (Ustrcmp(p, "_only") == 0)
3412             p += 5;
3413           else while (*p == '/')
3414             if (Ustrncmp(p, "/only", 5) == 0)
3415               { p += 5; f.queue_smtp = FALSE; }
3416             else if (Ustrncmp(p, "/first_pass_route", 17) == 0)
3417               { p += 17; f.queue_smtp = TRUE; }
3418             else
3419               break;
3420           cancel_cutthrough_connection(TRUE, US"queueing forced");
3421           break;
3422
3423         case CONTROL_SUBMISSION:
3424           originator_name = US"";
3425           f.submission_mode = TRUE;
3426           while (*p == '/')
3427             {
3428             if (Ustrncmp(p, "/sender_retain", 14) == 0)
3429               {
3430               p += 14;
3431               f.active_local_sender_retain = TRUE;
3432               f.active_local_from_check = FALSE;
3433               }
3434             else if (Ustrncmp(p, "/domain=", 8) == 0)
3435               {
3436               const uschar *pp = p + 8;
3437               while (*pp && *pp != '/') pp++;
3438               submission_domain = string_copyn(p+8, pp-p-8);
3439               p = pp;
3440               }
3441             /* The name= option must be last, because it swallows the rest of
3442             the string. */
3443             else if (Ustrncmp(p, "/name=", 6) == 0)
3444               {
3445               const uschar *pp = p + 6;
3446               while (*pp) pp++;
3447               submission_name = parse_fix_phrase(p+6, pp-p-6);
3448               p = pp;
3449               }
3450             else break;
3451             }
3452           if (*p)
3453             {
3454             *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
3455             return ERROR;
3456             }
3457           break;
3458
3459         case CONTROL_DEBUG:
3460           {
3461           uschar * debug_tag = NULL;
3462           uschar * debug_opts = NULL;
3463           BOOL kill = FALSE;
3464
3465           while (*p == '/')
3466             {
3467             const uschar * pp = p+1;
3468             if (Ustrncmp(pp, "tag=", 4) == 0)
3469               {
3470               for (pp += 4; *pp && *pp != '/';) pp++;
3471               debug_tag = string_copyn(p+5, pp-p-5);
3472               }
3473             else if (Ustrncmp(pp, "opts=", 5) == 0)
3474               {
3475               for (pp += 5; *pp && *pp != '/';) pp++;
3476               debug_opts = string_copyn(p+6, pp-p-6);
3477               }
3478             else if (Ustrncmp(pp, "kill", 4) == 0)
3479               {
3480               for (pp += 4; *pp && *pp != '/';) pp++;
3481               kill = TRUE;
3482               }
3483             else
3484               while (*pp && *pp != '/') pp++;
3485             p = pp;
3486             }
3487
3488             if (kill)
3489               debug_logging_stop();
3490             else
3491               debug_logging_activate(debug_tag, debug_opts);
3492           break;
3493           }
3494
3495         case CONTROL_SUPPRESS_LOCAL_FIXUPS:
3496           f.suppress_local_fixups = TRUE;
3497           break;
3498
3499         case CONTROL_CUTTHROUGH_DELIVERY:
3500           {
3501           uschar * ignored = NULL;
3502 #ifndef DISABLE_PRDR
3503           if (prdr_requested)
3504 #else
3505           if (0)
3506 #endif
3507             /* Too hard to think about for now.  We might in future cutthrough
3508             the case where both sides handle prdr and this-node prdr acl
3509             is "accept" */
3510             ignored = US"PRDR active";
3511           else if (f.deliver_freeze)
3512             ignored = US"frozen";
3513           else if (f.queue_only_policy)
3514             ignored = US"queue-only";
3515           else if (fake_response == FAIL)
3516             ignored = US"fakereject";
3517           else if (rcpt_count != 1)
3518             ignored = US"nonfirst rcpt";
3519           else if (cutthrough.delivery)
3520             ignored = US"repeated";
3521           else if (cutthrough.callout_hold_only)
3522             {
3523             DEBUG(D_acl)
3524               debug_printf_indent(" cutthrough request upgrades callout hold\n");
3525             cutthrough.callout_hold_only = FALSE;
3526             cutthrough.delivery = TRUE; /* control accepted */
3527             }
3528           else
3529             {
3530             cutthrough.delivery = TRUE; /* control accepted */
3531             while (*p == '/')
3532               {
3533               const uschar * pp = p+1;
3534               if (Ustrncmp(pp, "defer=", 6) == 0)
3535                 {
3536                 pp += 6;
3537                 if (Ustrncmp(pp, "pass", 4) == 0) cutthrough.defer_pass = TRUE;
3538                 /* else if (Ustrncmp(pp, "spool") == 0) ;       default */
3539                 }
3540               else
3541                 while (*pp && *pp != '/') pp++;
3542               p = pp;
3543               }
3544             }
3545
3546           DEBUG(D_acl) if (ignored)
3547             debug_printf(" cutthrough request ignored on %s item\n", ignored);
3548           }
3549         break;
3550
3551 #ifdef SUPPORT_I18N
3552         case CONTROL_UTF8_DOWNCONVERT:
3553           if (*p == '/')
3554             {
3555             if (p[1] == '1')
3556               {
3557               message_utf8_downconvert = 1;
3558               addr->prop.utf8_downcvt = TRUE;
3559               addr->prop.utf8_downcvt_maybe = FALSE;
3560               p += 2;
3561               break;
3562               }
3563             if (p[1] == '0')
3564               {
3565               message_utf8_downconvert = 0;
3566               addr->prop.utf8_downcvt = FALSE;
3567               addr->prop.utf8_downcvt_maybe = FALSE;
3568               p += 2;
3569               break;
3570               }
3571             if (p[1] == '-' && p[2] == '1')
3572               {
3573               message_utf8_downconvert = -1;
3574               addr->prop.utf8_downcvt = FALSE;
3575               addr->prop.utf8_downcvt_maybe = TRUE;
3576               p += 3;
3577               break;
3578               }
3579             *log_msgptr = US"bad option value for control=utf8_downconvert";
3580             }
3581           else
3582             {
3583             message_utf8_downconvert = 1;
3584             addr->prop.utf8_downcvt = TRUE;
3585             addr->prop.utf8_downcvt_maybe = FALSE;
3586             break;
3587             }
3588           return ERROR;
3589 #endif
3590
3591         }
3592       break;
3593       }
3594
3595     #ifdef EXPERIMENTAL_DCC
3596     case ACLC_DCC:
3597       {
3598       /* Separate the regular expression and any optional parameters. */
3599       const uschar * list = arg;
3600       uschar *ss = string_nextinlist(&list, &sep, NULL, 0);
3601       /* Run the dcc backend. */
3602       rc = dcc_process(&ss);
3603       /* Modify return code based upon the existence of options. */
3604       while ((ss = string_nextinlist(&list, &sep, NULL, 0)))
3605         if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
3606           rc = FAIL;   /* FAIL so that the message is passed to the next ACL */
3607       }
3608     break;
3609     #endif
3610
3611     #ifdef WITH_CONTENT_SCAN
3612     case ACLC_DECODE:
3613     rc = mime_decode(&arg);
3614     break;
3615     #endif
3616
3617     case ACLC_DELAY:
3618       {
3619       int delay = readconf_readtime(arg, 0, FALSE);
3620       if (delay < 0)
3621         {
3622         *log_msgptr = string_sprintf("syntax error in argument for \"delay\" "
3623           "modifier: \"%s\" is not a time value", arg);
3624         return ERROR;
3625         }
3626       else
3627         {
3628         HDEBUG(D_acl) debug_printf_indent("delay modifier requests %d-second delay\n",
3629           delay);
3630         if (host_checking)
3631           {
3632           HDEBUG(D_acl)
3633             debug_printf_indent("delay skipped in -bh checking mode\n");
3634           }
3635
3636         /* NOTE 1: Remember that we may be
3637         dealing with stdin/stdout here, in addition to TCP/IP connections.
3638         Also, delays may be specified for non-SMTP input, where smtp_out and
3639         smtp_in will be NULL. Whatever is done must work in all cases.
3640
3641         NOTE 2: The added feature of flushing the output before a delay must
3642         apply only to SMTP input. Hence the test for smtp_out being non-NULL.
3643         */
3644
3645         else
3646           {
3647           if (smtp_out && !f.disable_delay_flush)
3648             mac_smtp_fflush();
3649
3650 #if !defined(NO_POLL_H) && defined (POLLRDHUP)
3651             {
3652             struct pollfd p;
3653             nfds_t n = 0;
3654             if (smtp_out)
3655               {
3656               p.fd = fileno(smtp_out);
3657               p.events = POLLRDHUP;
3658               n = 1;
3659               }
3660             if (poll(&p, n, delay*1000) > 0)
3661               HDEBUG(D_acl) debug_printf_indent("delay cancelled by peer close\n");
3662             }
3663 #else
3664           /* Lacking POLLRDHUP it appears to be impossible to detect that a
3665           TCP/IP connection has gone away without reading from it. This means
3666           that we cannot shorten the delay below if the client goes away,
3667           because we cannot discover that the client has closed its end of the
3668           connection. (The connection is actually in a half-closed state,
3669           waiting for the server to close its end.) It would be nice to be able
3670           to detect this state, so that the Exim process is not held up
3671           unnecessarily. However, it seems that we can't. The poll() function
3672           does not do the right thing, and in any case it is not always
3673           available.  */
3674
3675           while (delay > 0) delay = sleep(delay);
3676 #endif
3677           }
3678         }
3679       }
3680     break;
3681
3682 #ifndef DISABLE_DKIM
3683     case ACLC_DKIM_SIGNER:
3684     if (dkim_cur_signer)
3685       rc = match_isinlist(dkim_cur_signer,
3686                           &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL);
3687     else
3688       rc = FAIL;
3689     break;
3690
3691     case ACLC_DKIM_STATUS:
3692     rc = match_isinlist(dkim_verify_status,
3693                         &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL);
3694     break;
3695 #endif
3696
3697 #ifdef SUPPORT_DMARC
3698     case ACLC_DMARC_STATUS:
3699     if (!f.dmarc_has_been_checked)
3700       dmarc_process();
3701     f.dmarc_has_been_checked = TRUE;
3702     /* used long way of dmarc_exim_expand_query() in case we need more
3703      * view into the process in the future. */
3704     rc = match_isinlist(dmarc_exim_expand_query(DMARC_VERIFY_STATUS),
3705                         &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL);
3706     break;
3707 #endif
3708
3709     case ACLC_DNSLISTS:
3710     rc = verify_check_dnsbl(where, &arg, log_msgptr);
3711     break;
3712
3713     case ACLC_DOMAINS:
3714     rc = match_isinlist(addr->domain, &arg, 0, &domainlist_anchor,
3715       addr->domain_cache, MCL_DOMAIN, TRUE, CUSS &deliver_domain_data);
3716     break;
3717
3718     /* The value in tls_cipher is the full cipher name, for example,
3719     TLSv1:DES-CBC3-SHA:168, whereas the values to test for are just the
3720     cipher names such as DES-CBC3-SHA. But program defensively. We don't know
3721     what may in practice come out of the SSL library - which at the time of
3722     writing is poorly documented. */
3723
3724     case ACLC_ENCRYPTED:
3725     if (tls_in.cipher == NULL) rc = FAIL; else
3726       {
3727       uschar *endcipher = NULL;
3728       uschar *cipher = Ustrchr(tls_in.cipher, ':');
3729       if (!cipher) cipher = tls_in.cipher; else
3730         {
3731         endcipher = Ustrchr(++cipher, ':');
3732         if (endcipher) *endcipher = 0;
3733         }
3734       rc = match_isinlist(cipher, &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL);
3735       if (endcipher) *endcipher = ':';
3736       }
3737     break;
3738
3739     /* Use verify_check_this_host() instead of verify_check_host() so that
3740     we can pass over &host_data to catch any looked up data. Once it has been
3741     set, it retains its value so that it's still there if another ACL verb
3742     comes through here and uses the cache. However, we must put it into
3743     permanent store in case it is also expected to be used in a subsequent
3744     message in the same SMTP connection. */
3745
3746     case ACLC_HOSTS:
3747     rc = verify_check_this_host(&arg, sender_host_cache, NULL,
3748       sender_host_address ? sender_host_address : US"", CUSS &host_data);
3749     if (rc == DEFER) *log_msgptr = search_error_message;
3750     if (host_data) host_data = string_copy_perm(host_data, TRUE);
3751     break;
3752
3753     case ACLC_LOCAL_PARTS:
3754     rc = match_isinlist(addr->cc_local_part, &arg, 0,
3755       &localpartlist_anchor, addr->localpart_cache, MCL_LOCALPART, TRUE,
3756       CUSS &deliver_localpart_data);
3757     break;
3758
3759     case ACLC_LOG_REJECT_TARGET:
3760       {
3761       int logbits = 0;
3762       int sep = 0;
3763       const uschar *s = arg;
3764       uschar * ss;
3765       while ((ss = string_nextinlist(&s, &sep, NULL, 0)))
3766         {
3767         if (Ustrcmp(ss, "main") == 0) logbits |= LOG_MAIN;
3768         else if (Ustrcmp(ss, "panic") == 0) logbits |= LOG_PANIC;
3769         else if (Ustrcmp(ss, "reject") == 0) logbits |= LOG_REJECT;
3770         else
3771           {
3772           logbits |= LOG_MAIN|LOG_REJECT;
3773           log_write(0, LOG_MAIN|LOG_PANIC, "unknown log name \"%s\" in "
3774             "\"log_reject_target\" in %s ACL", ss, acl_wherenames[where]);
3775           }
3776         }
3777       log_reject_target = logbits;
3778       }
3779     break;
3780
3781     case ACLC_LOGWRITE:
3782       {
3783       int logbits = 0;
3784       const uschar *s = arg;
3785       if (*s == ':')
3786         {
3787         s++;
3788         while (*s != ':')
3789           {
3790           if (Ustrncmp(s, "main", 4) == 0)
3791             { logbits |= LOG_MAIN; s += 4; }
3792           else if (Ustrncmp(s, "panic", 5) == 0)
3793             { logbits |= LOG_PANIC; s += 5; }
3794           else if (Ustrncmp(s, "reject", 6) == 0)
3795             { logbits |= LOG_REJECT; s += 6; }
3796           else
3797             {
3798             logbits = LOG_MAIN|LOG_PANIC;
3799             s = string_sprintf(":unknown log name in \"%s\" in "
3800               "\"logwrite\" in %s ACL", arg, acl_wherenames[where]);
3801             }
3802           if (*s == ',') s++;
3803           }
3804         s++;
3805         }
3806       while (isspace(*s)) s++;
3807
3808       if (logbits == 0) logbits = LOG_MAIN;
3809       log_write(0, logbits, "%s", string_printing(s));
3810       }
3811     break;
3812
3813     #ifdef WITH_CONTENT_SCAN
3814     case ACLC_MALWARE:                  /* Run the malware backend. */
3815       {
3816       /* Separate the regular expression and any optional parameters. */
3817       const uschar * list = arg;
3818       uschar * ss = string_nextinlist(&list, &sep, NULL, 0);
3819       uschar * opt;
3820       BOOL defer_ok = FALSE;
3821       int timeout = 0;
3822
3823       while ((opt = string_nextinlist(&list, &sep, NULL, 0)))
3824         if (strcmpic(opt, US"defer_ok") == 0)
3825           defer_ok = TRUE;
3826         else if (  strncmpic(opt, US"tmo=", 4) == 0
3827                 && (timeout = readconf_readtime(opt+4, '\0', FALSE)) < 0
3828                 )
3829           {
3830           *log_msgptr = string_sprintf("bad timeout value in '%s'", opt);
3831           return ERROR;
3832           }
3833
3834       rc = malware(ss, timeout);
3835       if (rc == DEFER && defer_ok)
3836         rc = FAIL;      /* FAIL so that the message is passed to the next ACL */
3837       }
3838     break;
3839
3840     case ACLC_MIME_REGEX:
3841     rc = mime_regex(&arg);
3842     break;
3843     #endif
3844
3845     case ACLC_QUEUE:
3846       {
3847       uschar *m;
3848       if ((m = is_tainted2(arg, 0, "Tainted name '%s' for queue not permitted", arg)))
3849         {
3850         *log_msgptr = m;
3851         return ERROR;
3852         }
3853       if (Ustrchr(arg, '/'))
3854         {
3855         *log_msgptr = string_sprintf(
3856                 "Directory separator not permitted in queue name: '%s'", arg);
3857         return ERROR;
3858         }
3859       queue_name = string_copy_perm(arg, FALSE);
3860       break;
3861       }
3862
3863     case ACLC_RATELIMIT:
3864     rc = acl_ratelimit(arg, where, log_msgptr);
3865     break;
3866
3867     case ACLC_RECIPIENTS:
3868     rc = match_address_list(CUS addr->address, TRUE, TRUE, &arg, NULL, -1, 0,
3869       CUSS &recipient_data);
3870     break;
3871
3872     #ifdef WITH_CONTENT_SCAN
3873     case ACLC_REGEX:
3874     rc = regex(&arg);
3875     break;
3876     #endif
3877
3878     case ACLC_REMOVE_HEADER:
3879     setup_remove_header(arg);
3880     break;
3881
3882     case ACLC_SEEN:
3883     rc = acl_seen(arg, where, log_msgptr);
3884     break;
3885
3886     case ACLC_SENDER_DOMAINS:
3887       {
3888       uschar *sdomain;
3889       sdomain = Ustrrchr(sender_address, '@');
3890       sdomain = sdomain ? sdomain + 1 : US"";
3891       rc = match_isinlist(sdomain, &arg, 0, &domainlist_anchor,
3892         sender_domain_cache, MCL_DOMAIN, TRUE, NULL);
3893       }
3894     break;
3895
3896     case ACLC_SENDERS:
3897     rc = match_address_list(CUS sender_address, TRUE, TRUE, &arg,
3898       sender_address_cache, -1, 0, CUSS &sender_data);
3899     break;
3900
3901     /* Connection variables must persist forever; message variables not */
3902
3903     case ACLC_SET:
3904       {
3905       int old_pool = store_pool;
3906       if (  cb->u.varname[0] != 'm'
3907 #ifndef DISABLE_EVENT
3908          || event_name          /* An event is being delivered */
3909 #endif
3910          )
3911         store_pool = POOL_PERM;
3912 #ifndef DISABLE_DKIM    /* Overwriteable dkim result variables */
3913       if (Ustrcmp(cb->u.varname, "dkim_verify_status") == 0)
3914         dkim_verify_status = string_copy(arg);
3915       else if (Ustrcmp(cb->u.varname, "dkim_verify_reason") == 0)
3916         dkim_verify_reason = string_copy(arg);
3917       else
3918 #endif
3919         acl_var_create(cb->u.varname)->data.ptr = string_copy(arg);
3920       store_pool = old_pool;
3921       }
3922     break;
3923
3924 #ifdef WITH_CONTENT_SCAN
3925     case ACLC_SPAM:
3926       {
3927       /* Separate the regular expression and any optional parameters. */
3928       const uschar * list = arg;
3929       uschar *ss = string_nextinlist(&list, &sep, NULL, 0);
3930
3931       rc = spam(CUSS &ss);
3932       /* Modify return code based upon the existence of options. */
3933       while ((ss = string_nextinlist(&list, &sep, NULL, 0)))
3934         if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
3935           rc = FAIL;    /* FAIL so that the message is passed to the next ACL */
3936       }
3937     break;
3938 #endif
3939
3940 #ifdef SUPPORT_SPF
3941     case ACLC_SPF:
3942       rc = spf_process(&arg, sender_address, SPF_PROCESS_NORMAL);
3943     break;
3944     case ACLC_SPF_GUESS:
3945       rc = spf_process(&arg, sender_address, SPF_PROCESS_GUESS);
3946     break;
3947 #endif
3948
3949     case ACLC_UDPSEND:
3950     rc = acl_udpsend(arg, log_msgptr);
3951     break;
3952
3953     /* If the verb is WARN, discard any user message from verification, because
3954     such messages are SMTP responses, not header additions. The latter come
3955     only from explicit "message" modifiers. However, put the user message into
3956     $acl_verify_message so it can be used in subsequent conditions or modifiers
3957     (until something changes it). */
3958
3959     case ACLC_VERIFY:
3960     rc = acl_verify(where, addr, arg, user_msgptr, log_msgptr, basic_errno);
3961     if (*user_msgptr)
3962       acl_verify_message = *user_msgptr;
3963     if (verb == ACL_WARN) *user_msgptr = NULL;
3964     break;
3965
3966     default:
3967     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown "
3968       "condition %d", cb->type);
3969     break;
3970     }
3971
3972   /* If a condition was negated, invert OK/FAIL. */
3973
3974   if (!conditions[cb->type].is_modifier && cb->u.negated)
3975     if (rc == OK) rc = FAIL;
3976     else if (rc == FAIL || rc == FAIL_DROP) rc = OK;
3977
3978   if (rc != OK) break;   /* Conditions loop */
3979   }
3980
3981
3982 /* If the result is the one for which "message" and/or "log_message" are used,
3983 handle the values of these modifiers. If there isn't a log message set, we make
3984 it the same as the user message.
3985
3986 "message" is a user message that will be included in an SMTP response. Unless
3987 it is empty, it overrides any previously set user message.
3988
3989 "log_message" is a non-user message, and it adds to any existing non-user
3990 message that is already set.
3991
3992 Most verbs have but a single return for which the messages are relevant, but
3993 for "discard", it's useful to have the log message both when it succeeds and
3994 when it fails. For "accept", the message is used in the OK case if there is no
3995 "endpass", but (for backwards compatibility) in the FAIL case if "endpass" is
3996 present. */
3997
3998 if (*epp && rc == OK) user_message = NULL;
3999
4000 if ((BIT(rc) & msgcond[verb]) != 0)
4001   {
4002   uschar *expmessage;
4003   uschar *old_user_msgptr = *user_msgptr;
4004   uschar *old_log_msgptr = (*log_msgptr != NULL)? *log_msgptr : old_user_msgptr;
4005
4006   /* If the verb is "warn", messages generated by conditions (verification or
4007   nested ACLs) are always discarded. This also happens for acceptance verbs
4008   when they actually do accept. Only messages specified at this level are used.
4009   However, the value of an existing message is available in $acl_verify_message
4010   during expansions. */
4011
4012   if (verb == ACL_WARN ||
4013       (rc == OK && (verb == ACL_ACCEPT || verb == ACL_DISCARD)))
4014     *log_msgptr = *user_msgptr = NULL;
4015
4016   if (user_message)
4017     {
4018     acl_verify_message = old_user_msgptr;
4019     expmessage = expand_string(user_message);
4020     if (!expmessage)
4021       {
4022       if (!f.expand_string_forcedfail)
4023         log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
4024           user_message, expand_string_message);
4025       }
4026     else if (expmessage[0] != 0) *user_msgptr = expmessage;
4027     }
4028
4029   if (log_message)
4030     {
4031     acl_verify_message = old_log_msgptr;
4032     expmessage = expand_string(log_message);
4033     if (!expmessage)
4034       {
4035       if (!f.expand_string_forcedfail)
4036         log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
4037           log_message, expand_string_message);
4038       }
4039     else if (expmessage[0] != 0)
4040       {
4041       *log_msgptr = (*log_msgptr == NULL)? expmessage :
4042         string_sprintf("%s: %s", expmessage, *log_msgptr);
4043       }
4044     }
4045
4046   /* If no log message, default it to the user message */
4047
4048   if (!*log_msgptr) *log_msgptr = *user_msgptr;
4049   }
4050
4051 acl_verify_message = NULL;
4052 return rc;
4053 }
4054
4055
4056
4057
4058
4059 /*************************************************
4060 *        Get line from a literal ACL             *
4061 *************************************************/
4062
4063 /* This function is passed to acl_read() in order to extract individual lines
4064 of a literal ACL, which we access via static pointers. We can destroy the
4065 contents because this is called only once (the compiled ACL is remembered).
4066
4067 This code is intended to treat the data in the same way as lines in the main
4068 Exim configuration file. That is:
4069
4070   . Leading spaces are ignored.
4071
4072   . A \ at the end of a line is a continuation - trailing spaces after the \
4073     are permitted (this is because I don't believe in making invisible things
4074     significant). Leading spaces on the continued part of a line are ignored.
4075
4076   . Physical lines starting (significantly) with # are totally ignored, and
4077     may appear within a sequence of backslash-continued lines.
4078
4079   . Blank lines are ignored, but will end a sequence of continuations.
4080
4081 Arguments: none
4082 Returns:   a pointer to the next line
4083 */
4084
4085
4086 static uschar *acl_text;          /* Current pointer in the text */
4087 static uschar *acl_text_end;      /* Points one past the terminating '0' */
4088
4089
4090 static uschar *
4091 acl_getline(void)
4092 {
4093 uschar *yield;
4094
4095 /* This loop handles leading blank lines and comments. */
4096
4097 for(;;)
4098   {
4099   Uskip_whitespace(&acl_text);          /* Leading spaces/empty lines */
4100   if (!*acl_text) return NULL;          /* No more data */
4101   yield = acl_text;                     /* Potential data line */
4102
4103   while (*acl_text && *acl_text != '\n') acl_text++;
4104
4105   /* If we hit the end before a newline, we have the whole logical line. If
4106   it's a comment, there's no more data to be given. Otherwise, yield it. */
4107
4108   if (!*acl_text) return *yield == '#' ? NULL : yield;
4109
4110   /* After reaching a newline, end this loop if the physical line does not
4111   start with '#'. If it does, it's a comment, and the loop continues. */
4112
4113   if (*yield != '#') break;
4114   }
4115
4116 /* This loop handles continuations. We know we have some real data, ending in
4117 newline. See if there is a continuation marker at the end (ignoring trailing
4118 white space). We know that *yield is not white space, so no need to test for
4119 cont > yield in the backwards scanning loop. */
4120
4121 for(;;)
4122   {
4123   uschar *cont;
4124   for (cont = acl_text - 1; isspace(*cont); cont--);
4125
4126   /* If no continuation follows, we are done. Mark the end of the line and
4127   return it. */
4128
4129   if (*cont != '\\')
4130     {
4131     *acl_text++ = 0;
4132     return yield;
4133     }
4134
4135   /* We have encountered a continuation. Skip over whitespace at the start of
4136   the next line, and indeed the whole of the next line or lines if they are
4137   comment lines. */
4138
4139   for (;;)
4140     {
4141     while (*(++acl_text) == ' ' || *acl_text == '\t');
4142     if (*acl_text != '#') break;
4143     while (*(++acl_text) != 0 && *acl_text != '\n');
4144     }
4145
4146   /* We have the start of a continuation line. Move all the rest of the data
4147   to join onto the previous line, and then find its end. If the end is not a
4148   newline, we are done. Otherwise loop to look for another continuation. */
4149
4150   memmove(cont, acl_text, acl_text_end - acl_text);
4151   acl_text_end -= acl_text - cont;
4152   acl_text = cont;
4153   while (*acl_text != 0 && *acl_text != '\n') acl_text++;
4154   if (*acl_text == 0) return yield;
4155   }
4156
4157 /* Control does not reach here */
4158 }
4159
4160
4161
4162
4163
4164 /*************************************************
4165 *        Check access using an ACL               *
4166 *************************************************/
4167
4168 /* This function is called from address_check. It may recurse via
4169 acl_check_condition() - hence the use of a level to stop looping. The ACL is
4170 passed as a string which is expanded. A forced failure implies no access check
4171 is required. If the result is a single word, it is taken as the name of an ACL
4172 which is sought in the global ACL tree. Otherwise, it is taken as literal ACL
4173 text, complete with newlines, and parsed as such. In both cases, the ACL check
4174 is then run. This function uses an auxiliary function for acl_read() to call
4175 for reading individual lines of a literal ACL. This is acl_getline(), which
4176 appears immediately above.
4177
4178 Arguments:
4179   where        where called from
4180   addr         address item when called from RCPT; otherwise NULL
4181   s            the input string; NULL is the same as an empty ACL => DENY
4182   user_msgptr  where to put a user error (for SMTP response)
4183   log_msgptr   where to put a logging message (not for SMTP response)
4184
4185 Returns:       OK         access is granted
4186                DISCARD    access is apparently granted...
4187                FAIL       access is denied
4188                FAIL_DROP  access is denied; drop the connection
4189                DEFER      can't tell at the moment
4190                ERROR      disaster
4191 */
4192
4193 static int
4194 acl_check_internal(int where, address_item *addr, uschar *s,
4195   uschar **user_msgptr, uschar **log_msgptr)
4196 {
4197 int fd = -1;
4198 acl_block *acl = NULL;
4199 uschar *acl_name = US"inline ACL";
4200 uschar *ss;
4201
4202 /* Catch configuration loops */
4203
4204 if (acl_level > 20)
4205   {
4206   *log_msgptr = US"ACL nested too deep: possible loop";
4207   return ERROR;
4208   }
4209
4210 if (!s)
4211   {
4212   HDEBUG(D_acl) debug_printf_indent("ACL is NULL: implicit DENY\n");
4213   return FAIL;
4214   }
4215
4216 /* At top level, we expand the incoming string. At lower levels, it has already
4217 been expanded as part of condition processing. */
4218
4219 if (acl_level == 0)
4220   {
4221   if (!(ss = expand_string(s)))
4222     {
4223     if (f.expand_string_forcedfail) return OK;
4224     *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s", s,
4225       expand_string_message);
4226     return ERROR;
4227     }
4228   }
4229 else ss = s;
4230
4231 while (isspace(*ss)) ss++;
4232
4233 /* If we can't find a named ACL, the default is to parse it as an inline one.
4234 (Unless it begins with a slash; non-existent files give rise to an error.) */
4235
4236 acl_text = ss;
4237
4238 if (  !f.running_in_test_harness
4239    &&  is_tainted2(acl_text, LOG_MAIN|LOG_PANIC,
4240                           "Tainted ACL text \"%s\"", acl_text))
4241   {
4242   /* Avoid leaking info to an attacker */
4243   *log_msgptr = US"internal configuration error";
4244   return ERROR;
4245   }
4246
4247 /* Handle the case of a string that does not contain any spaces. Look for a
4248 named ACL among those read from the configuration, or a previously read file.
4249 It is possible that the pointer to the ACL is NULL if the configuration
4250 contains a name with no data. If not found, and the text begins with '/',
4251 read an ACL from a file, and save it so it can be re-used. */
4252
4253 if (Ustrchr(ss, ' ') == NULL)
4254   {
4255   tree_node * t = tree_search(acl_anchor, ss);
4256   if (t)
4257     {
4258     if (!(acl = (acl_block *)(t->data.ptr)))
4259       {
4260       HDEBUG(D_acl) debug_printf_indent("ACL \"%s\" is empty: implicit DENY\n", ss);
4261       return FAIL;
4262       }
4263     acl_name = string_sprintf("ACL \"%s\"", ss);
4264     HDEBUG(D_acl) debug_printf_indent("using ACL \"%s\"\n", ss);
4265     }
4266
4267   else if (*ss == '/')
4268     {
4269     struct stat statbuf;
4270     if (is_tainted2(ss, LOG_MAIN|LOG_PANIC, "Tainted ACL file name '%s'", ss))
4271       {
4272       /* Avoid leaking info to an attacker */
4273       *log_msgptr = US"internal configuration error";
4274       return ERROR;
4275       }
4276     if ((fd = Uopen(ss, O_RDONLY, 0)) < 0)
4277       {
4278       *log_msgptr = string_sprintf("failed to open ACL file \"%s\": %s", ss,
4279         strerror(errno));
4280       return ERROR;
4281       }
4282     if (fstat(fd, &statbuf) != 0)
4283       {
4284       *log_msgptr = string_sprintf("failed to fstat ACL file \"%s\": %s", ss,
4285         strerror(errno));
4286       return ERROR;
4287       }
4288
4289     /* If the string being used as a filename is tainted, so is the file content */
4290     acl_text = store_get(statbuf.st_size + 1, is_tainted(ss));
4291     acl_text_end = acl_text + statbuf.st_size + 1;
4292
4293     if (read(fd, acl_text, statbuf.st_size) != statbuf.st_size)
4294       {
4295       *log_msgptr = string_sprintf("failed to read ACL file \"%s\": %s",
4296         ss, strerror(errno));
4297       return ERROR;
4298       }
4299     acl_text[statbuf.st_size] = 0;
4300     (void)close(fd);
4301
4302     acl_name = string_sprintf("ACL \"%s\"", ss);
4303     HDEBUG(D_acl) debug_printf_indent("read ACL from file %s\n", ss);
4304     }
4305   }
4306
4307 /* Parse an ACL that is still in text form. If it came from a file, remember it
4308 in the ACL tree, having read it into the POOL_PERM store pool so that it
4309 persists between multiple messages. */
4310
4311 if (!acl)
4312   {
4313   int old_pool = store_pool;
4314   if (fd >= 0) store_pool = POOL_PERM;
4315   acl = acl_read(acl_getline, log_msgptr);
4316   store_pool = old_pool;
4317   if (!acl && *log_msgptr) return ERROR;
4318   if (fd >= 0)
4319     {
4320     tree_node *t = store_get_perm(sizeof(tree_node) + Ustrlen(ss), is_tainted(ss));
4321     Ustrcpy(t->name, ss);
4322     t->data.ptr = acl;
4323     (void)tree_insertnode(&acl_anchor, t);
4324     }
4325   }
4326
4327 /* Now we have an ACL to use. It's possible it may be NULL. */
4328
4329 while (acl)
4330   {
4331   int cond;
4332   int basic_errno = 0;
4333   BOOL endpass_seen = FALSE;
4334   BOOL acl_quit_check = acl_level == 0
4335     && (where == ACL_WHERE_QUIT || where == ACL_WHERE_NOTQUIT);
4336
4337   *log_msgptr = *user_msgptr = NULL;
4338   f.acl_temp_details = FALSE;
4339
4340   HDEBUG(D_acl) debug_printf_indent("processing \"%s\" (%s %d)\n",
4341     verbs[acl->verb], acl->srcfile, acl->srcline);
4342
4343   /* Clear out any search error message from a previous check before testing
4344   this condition. */
4345
4346   search_error_message = NULL;
4347   cond = acl_check_condition(acl->verb, acl->condition, where, addr, acl_level,
4348     &endpass_seen, user_msgptr, log_msgptr, &basic_errno);
4349
4350   /* Handle special returns: DEFER causes a return except on a WARN verb;
4351   ERROR always causes a return. */
4352
4353   switch (cond)
4354     {
4355     case DEFER:
4356       HDEBUG(D_acl) debug_printf_indent("%s: condition test deferred in %s\n",
4357         verbs[acl->verb], acl_name);
4358       if (basic_errno != ERRNO_CALLOUTDEFER)
4359         {
4360         if (search_error_message != NULL && *search_error_message != 0)
4361           *log_msgptr = search_error_message;
4362         if (smtp_return_error_details) f.acl_temp_details = TRUE;
4363         }
4364       else
4365         f.acl_temp_details = TRUE;
4366       if (acl->verb != ACL_WARN) return DEFER;
4367       break;
4368
4369     default:      /* Paranoia */
4370     case ERROR:
4371       HDEBUG(D_acl) debug_printf_indent("%s: condition test error in %s\n",
4372         verbs[acl->verb], acl_name);
4373       return ERROR;
4374
4375     case OK:
4376       HDEBUG(D_acl) debug_printf_indent("%s: condition test succeeded in %s\n",
4377         verbs[acl->verb], acl_name);
4378       break;
4379
4380     case FAIL:
4381       HDEBUG(D_acl) debug_printf_indent("%s: condition test failed in %s\n",
4382         verbs[acl->verb], acl_name);
4383       break;
4384
4385     /* DISCARD and DROP can happen only from a nested ACL condition, and
4386     DISCARD can happen only for an "accept" or "discard" verb. */
4387
4388     case DISCARD:
4389       HDEBUG(D_acl) debug_printf_indent("%s: condition test yielded \"discard\" in %s\n",
4390         verbs[acl->verb], acl_name);
4391       break;
4392
4393     case FAIL_DROP:
4394       HDEBUG(D_acl) debug_printf_indent("%s: condition test yielded \"drop\" in %s\n",
4395         verbs[acl->verb], acl_name);
4396       break;
4397     }
4398
4399   /* At this point, cond for most verbs is either OK or FAIL or (as a result of
4400   a nested ACL condition) FAIL_DROP. However, for WARN, cond may be DEFER, and
4401   for ACCEPT and DISCARD, it may be DISCARD after a nested ACL call. */
4402
4403   switch(acl->verb)
4404     {
4405     case ACL_ACCEPT:
4406       if (cond == OK || cond == DISCARD)
4407         {
4408         HDEBUG(D_acl) debug_printf_indent("end of %s: ACCEPT\n", acl_name);
4409         return cond;
4410         }
4411       if (endpass_seen)
4412         {
4413         HDEBUG(D_acl) debug_printf_indent("accept: endpass encountered - denying access\n");
4414         return cond;
4415         }
4416       break;
4417
4418     case ACL_DEFER:
4419       if (cond == OK)
4420         {
4421         HDEBUG(D_acl) debug_printf_indent("end of %s: DEFER\n", acl_name);
4422         if (acl_quit_check) goto badquit;
4423         f.acl_temp_details = TRUE;
4424         return DEFER;
4425         }
4426       break;
4427
4428     case ACL_DENY:
4429       if (cond == OK)
4430         {
4431         HDEBUG(D_acl) debug_printf_indent("end of %s: DENY\n", acl_name);
4432         if (acl_quit_check) goto badquit;
4433         return FAIL;
4434         }
4435       break;
4436
4437     case ACL_DISCARD:
4438       if (cond == OK || cond == DISCARD)
4439         {
4440         HDEBUG(D_acl) debug_printf_indent("end of %s: DISCARD\n", acl_name);
4441         if (acl_quit_check) goto badquit;
4442         return DISCARD;
4443         }
4444       if (endpass_seen)
4445         {
4446         HDEBUG(D_acl)
4447           debug_printf_indent("discard: endpass encountered - denying access\n");
4448         return cond;
4449         }
4450       break;
4451
4452     case ACL_DROP:
4453       if (cond == OK)
4454         {
4455         HDEBUG(D_acl) debug_printf_indent("end of %s: DROP\n", acl_name);
4456         if (acl_quit_check) goto badquit;
4457         return FAIL_DROP;
4458         }
4459       break;
4460
4461     case ACL_REQUIRE:
4462       if (cond != OK)
4463         {
4464         HDEBUG(D_acl) debug_printf_indent("end of %s: not OK\n", acl_name);
4465         if (acl_quit_check) goto badquit;
4466         return cond;
4467         }
4468       break;
4469
4470     case ACL_WARN:
4471       if (cond == OK)
4472         acl_warn(where, *user_msgptr, *log_msgptr);
4473       else if (cond == DEFER && LOGGING(acl_warn_skipped))
4474         log_write(0, LOG_MAIN, "%s Warning: ACL \"warn\" statement skipped: "
4475           "condition test deferred%s%s", host_and_ident(TRUE),
4476           (*log_msgptr == NULL)? US"" : US": ",
4477           (*log_msgptr == NULL)? US"" : *log_msgptr);
4478       *log_msgptr = *user_msgptr = NULL;  /* In case implicit DENY follows */
4479       break;
4480
4481     default:
4482       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown verb %d",
4483         acl->verb);
4484       break;
4485     }
4486
4487   /* Pass to the next ACL item */
4488
4489   acl = acl->next;
4490   }
4491
4492 /* We have reached the end of the ACL. This is an implicit DENY. */
4493
4494 HDEBUG(D_acl) debug_printf_indent("end of %s: implicit DENY\n", acl_name);
4495 return FAIL;
4496
4497 badquit:
4498   *log_msgptr = string_sprintf("QUIT or not-QUIT toplevel ACL may not fail "
4499     "('%s' verb used incorrectly)", verbs[acl->verb]);
4500   return ERROR;
4501 }
4502
4503
4504
4505
4506 /* Same args as acl_check_internal() above, but the string s is
4507 the name of an ACL followed optionally by up to 9 space-separated arguments.
4508 The name and args are separately expanded.  Args go into $acl_arg globals. */
4509 static int
4510 acl_check_wargs(int where, address_item *addr, const uschar *s,
4511   uschar **user_msgptr, uschar **log_msgptr)
4512 {
4513 uschar * tmp;
4514 uschar * tmp_arg[9];    /* must match acl_arg[] */
4515 uschar * sav_arg[9];    /* must match acl_arg[] */
4516 int sav_narg;
4517 uschar * name;
4518 int i;
4519 int ret;
4520
4521 if (!(tmp = string_dequote(&s)) || !(name = expand_string(tmp)))
4522   goto bad;
4523
4524 for (i = 0; i < 9; i++)
4525   {
4526   while (*s && isspace(*s)) s++;
4527   if (!*s) break;
4528   if (!(tmp = string_dequote(&s)) || !(tmp_arg[i] = expand_string(tmp)))
4529     {
4530     tmp = name;
4531     goto bad;
4532     }
4533   }
4534
4535 sav_narg = acl_narg;
4536 acl_narg = i;
4537 for (i = 0; i < acl_narg; i++)
4538   {
4539   sav_arg[i] = acl_arg[i];
4540   acl_arg[i] = tmp_arg[i];
4541   }
4542 while (i < 9)
4543   {
4544   sav_arg[i] = acl_arg[i];
4545   acl_arg[i++] = NULL;
4546   }
4547
4548 acl_level++;
4549 ret = acl_check_internal(where, addr, name, user_msgptr, log_msgptr);
4550 acl_level--;
4551
4552 acl_narg = sav_narg;
4553 for (i = 0; i < 9; i++) acl_arg[i] = sav_arg[i];
4554 return ret;
4555
4556 bad:
4557 if (f.expand_string_forcedfail) return ERROR;
4558 *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s",
4559   tmp, expand_string_message);
4560 return f.search_find_defer ? DEFER : ERROR;
4561 }
4562
4563
4564
4565 /*************************************************
4566 *        Check access using an ACL               *
4567 *************************************************/
4568
4569 /* Alternate interface for ACL, used by expansions */
4570 int
4571 acl_eval(int where, uschar *s, uschar **user_msgptr, uschar **log_msgptr)
4572 {
4573 address_item adb;
4574 address_item *addr = NULL;
4575 int rc;
4576
4577 *user_msgptr = *log_msgptr = NULL;
4578 sender_verified_failed = NULL;
4579 ratelimiters_cmd = NULL;
4580 log_reject_target = LOG_MAIN|LOG_REJECT;
4581
4582 if (where == ACL_WHERE_RCPT)
4583   {
4584   adb = address_defaults;
4585   addr = &adb;
4586   addr->address = expand_string(US"$local_part@$domain");
4587   addr->domain = deliver_domain;
4588   addr->local_part = deliver_localpart;
4589   addr->cc_local_part = deliver_localpart;
4590   addr->lc_local_part = deliver_localpart;
4591   }
4592
4593 acl_level++;
4594 rc = acl_check_internal(where, addr, s, user_msgptr, log_msgptr);
4595 acl_level--;
4596 return rc;
4597 }
4598
4599
4600
4601 /* This is the external interface for ACL checks. It sets up an address and the
4602 expansions for $domain and $local_part when called after RCPT, then calls
4603 acl_check_internal() to do the actual work.
4604
4605 Arguments:
4606   where        ACL_WHERE_xxxx indicating where called from
4607   recipient    RCPT address for RCPT check, else NULL
4608   s            the input string; NULL is the same as an empty ACL => DENY
4609   user_msgptr  where to put a user error (for SMTP response)
4610   log_msgptr   where to put a logging message (not for SMTP response)
4611
4612 Returns:       OK         access is granted by an ACCEPT verb
4613                DISCARD    access is granted by a DISCARD verb
4614                FAIL       access is denied
4615                FAIL_DROP  access is denied; drop the connection
4616                DEFER      can't tell at the moment
4617                ERROR      disaster
4618 */
4619 int acl_where = ACL_WHERE_UNKNOWN;
4620
4621 int
4622 acl_check(int where, uschar *recipient, uschar *s, uschar **user_msgptr,
4623   uschar **log_msgptr)
4624 {
4625 int rc;
4626 address_item adb;
4627 address_item *addr = NULL;
4628
4629 *user_msgptr = *log_msgptr = NULL;
4630 sender_verified_failed = NULL;
4631 ratelimiters_cmd = NULL;
4632 log_reject_target = LOG_MAIN|LOG_REJECT;
4633
4634 #ifndef DISABLE_PRDR
4635 if (where==ACL_WHERE_RCPT || where==ACL_WHERE_VRFY || where==ACL_WHERE_PRDR)
4636 #else
4637 if (where==ACL_WHERE_RCPT || where==ACL_WHERE_VRFY)
4638 #endif
4639   {
4640   adb = address_defaults;
4641   addr = &adb;
4642   addr->address = recipient;
4643   if (deliver_split_address(addr) == DEFER)
4644     {
4645     *log_msgptr = US"defer in percent_hack_domains check";
4646     return DEFER;
4647     }
4648 #ifdef SUPPORT_I18N
4649   if ((addr->prop.utf8_msg = message_smtputf8))
4650     {
4651     addr->prop.utf8_downcvt =       message_utf8_downconvert == 1;
4652     addr->prop.utf8_downcvt_maybe = message_utf8_downconvert == -1;
4653     }
4654 #endif
4655   deliver_domain = addr->domain;
4656   deliver_localpart = addr->local_part;
4657   }
4658
4659 acl_where = where;
4660 acl_level = 0;
4661 rc = acl_check_internal(where, addr, s, user_msgptr, log_msgptr);
4662 acl_level = 0;
4663 acl_where = ACL_WHERE_UNKNOWN;
4664
4665 /* Cutthrough - if requested,
4666 and WHERE_RCPT and not yet opened conn as result of recipient-verify,
4667 and rcpt acl returned accept,
4668 and first recipient (cancel on any subsequents)
4669 open one now and run it up to RCPT acceptance.
4670 A failed verify should cancel cutthrough request,
4671 and will pass the fail to the originator.
4672 Initial implementation:  dual-write to spool.
4673 Assume the rxd datastream is now being copied byte-for-byte to an open cutthrough connection.
4674
4675 Cease cutthrough copy on rxd final dot; do not send one.
4676
4677 On a data acl, if not accept and a cutthrough conn is open, hard-close it (no SMTP niceness).
4678
4679 On data acl accept, terminate the dataphase on an open cutthrough conn.  If accepted or
4680 perm-rejected, reflect that to the original sender - and dump the spooled copy.
4681 If temp-reject, close the conn (and keep the spooled copy).
4682 If conn-failure, no action (and keep the spooled copy).
4683 */
4684 switch (where)
4685   {
4686   case ACL_WHERE_RCPT:
4687 #ifndef DISABLE_PRDR
4688   case ACL_WHERE_PRDR:
4689 #endif
4690
4691     if (f.host_checking_callout)        /* -bhc mode */
4692       cancel_cutthrough_connection(TRUE, US"host-checking mode");
4693
4694     else if (  rc == OK
4695             && cutthrough.delivery
4696             && rcpt_count > cutthrough.nrcpt
4697             )
4698       {
4699       if ((rc = open_cutthrough_connection(addr)) == DEFER)
4700         if (cutthrough.defer_pass)
4701           {
4702           uschar * s = addr->message;
4703           /* Horrid kludge to recover target's SMTP message */
4704           while (*s) s++;
4705           do --s; while (!isdigit(*s));
4706           if (*--s && isdigit(*s) && *--s && isdigit(*s)) *user_msgptr = s;
4707           f.acl_temp_details = TRUE;
4708           }
4709         else
4710           {
4711           HDEBUG(D_acl) debug_printf_indent("cutthrough defer; will spool\n");
4712           rc = OK;
4713           }
4714       }
4715     else HDEBUG(D_acl) if (cutthrough.delivery)
4716       if (rcpt_count <= cutthrough.nrcpt)
4717         debug_printf_indent("ignore cutthrough request; nonfirst message\n");
4718       else if (rc != OK)
4719         debug_printf_indent("ignore cutthrough request; ACL did not accept\n");
4720     break;
4721
4722   case ACL_WHERE_PREDATA:
4723     if (rc == OK)
4724       cutthrough_predata();
4725     else
4726       cancel_cutthrough_connection(TRUE, US"predata acl not ok");
4727     break;
4728
4729   case ACL_WHERE_QUIT:
4730   case ACL_WHERE_NOTQUIT:
4731     /* Drop cutthrough conns, and drop heldopen verify conns if
4732     the previous was not DATA */
4733     {
4734     uschar prev =
4735       smtp_connection_had[SMTP_HBUFF_PREV(SMTP_HBUFF_PREV(smtp_ch_index))];
4736     BOOL dropverify = !(prev == SCH_DATA || prev == SCH_BDAT);
4737
4738     cancel_cutthrough_connection(dropverify, US"quit or conndrop");
4739     break;
4740     }
4741
4742   default:
4743     break;
4744   }
4745
4746 deliver_domain = deliver_localpart = deliver_address_data =
4747   deliver_domain_data = sender_address_data = NULL;
4748
4749 /* A DISCARD response is permitted only for message ACLs, excluding the PREDATA
4750 ACL, which is really in the middle of an SMTP command. */
4751
4752 if (rc == DISCARD)
4753   {
4754   if (where > ACL_WHERE_NOTSMTP || where == ACL_WHERE_PREDATA)
4755     {
4756     log_write(0, LOG_MAIN|LOG_PANIC, "\"discard\" verb not allowed in %s "
4757       "ACL", acl_wherenames[where]);
4758     return ERROR;
4759     }
4760   return DISCARD;
4761   }
4762
4763 /* A DROP response is not permitted from MAILAUTH */
4764
4765 if (rc == FAIL_DROP && where == ACL_WHERE_MAILAUTH)
4766   {
4767   log_write(0, LOG_MAIN|LOG_PANIC, "\"drop\" verb not allowed in %s "
4768     "ACL", acl_wherenames[where]);
4769   return ERROR;
4770   }
4771
4772 /* Before giving a response, take a look at the length of any user message, and
4773 split it up into multiple lines if possible. */
4774
4775 *user_msgptr = string_split_message(*user_msgptr);
4776 if (fake_response != OK)
4777   fake_response_text = string_split_message(fake_response_text);
4778
4779 return rc;
4780 }
4781
4782
4783 /*************************************************
4784 *             Create ACL variable                *
4785 *************************************************/
4786
4787 /* Create an ACL variable or reuse an existing one. ACL variables are in a
4788 binary tree (see tree.c) with acl_var_c and acl_var_m as root nodes.
4789
4790 Argument:
4791   name    pointer to the variable's name, starting with c or m
4792
4793 Returns   the pointer to variable's tree node
4794 */
4795
4796 tree_node *
4797 acl_var_create(uschar * name)
4798 {
4799 tree_node * node, ** root = name[0] == 'c' ? &acl_var_c : &acl_var_m;
4800 if (!(node = tree_search(*root, name)))
4801   {
4802   node = store_get(sizeof(tree_node) + Ustrlen(name), is_tainted(name));
4803   Ustrcpy(node->name, name);
4804   (void)tree_insertnode(root, node);
4805   }
4806 node->data.ptr = NULL;
4807 return node;
4808 }
4809
4810
4811
4812 /*************************************************
4813 *       Write an ACL variable in spool format    *
4814 *************************************************/
4815
4816 /* This function is used as a callback for tree_walk when writing variables to
4817 the spool file. To retain spool file compatibility, what is written is -aclc or
4818 -aclm followed by the rest of the name and the data length, space separated,
4819 then the value itself, starting on a new line, and terminated by an additional
4820 newline. When we had only numbered ACL variables, the first line might look
4821 like this: "-aclc 5 20". Now it might be "-aclc foo 20" for the variable called
4822 acl_cfoo.
4823
4824 Arguments:
4825   name    of the variable
4826   value   of the variable
4827   ctx     FILE pointer (as a void pointer)
4828
4829 Returns:  nothing
4830 */
4831
4832 void
4833 acl_var_write(uschar *name, uschar *value, void *ctx)
4834 {
4835 FILE *f = (FILE *)ctx;
4836 if (is_tainted(value)) putc('-', f);
4837 fprintf(f, "-acl%c %s %d\n%s\n", name[0], name+1, Ustrlen(value), value);
4838 }
4839
4840 /* vi: aw ai sw=2
4841 */
4842 /* End of acl.c */