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