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