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