1bdcd3760c0d061055d258985232d1ef53a4337c
[exim.git] / src / src / expand.c
1 /* $Cambridge: exim/src/src/expand.c,v 1.7 2004/11/18 11:17:33 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
11 /* Functions for handling string expansion. */
12
13
14 #include "exim.h"
15
16 #ifdef STAND_ALONE
17 #ifndef SUPPORT_CRYPTEQ
18 #define SUPPORT_CRYPTEQ
19 #endif
20 #endif
21
22 #ifdef SUPPORT_CRYPTEQ
23 #ifdef CRYPT_H
24 #include <crypt.h>
25 #endif
26 #ifndef HAVE_CRYPT16
27 extern char* crypt16(char*, char*);
28 #endif
29 #endif
30
31 #ifdef LOOKUP_LDAP
32 #include "lookups/ldap.h"
33 #endif
34
35
36
37 /* Recursively called function */
38
39 static uschar *expand_string_internal(uschar *, BOOL, uschar **, BOOL);
40
41
42
43 /*************************************************
44 *            Local statics and tables            *
45 *************************************************/
46
47 /* Table of item names, and corresponding switch numbers. The names must be in
48 alphabetical order. */
49
50 static uschar *item_table[] = {
51   US"extract",
52   US"hash",
53   US"hmac",
54   US"if",
55   US"length",
56   US"lookup",
57   US"nhash",
58   #ifdef EXIM_PERL
59     US"perl",
60   #endif
61   US"readfile",
62   US"readsocket",
63   US"run",
64   US"sg",
65   US"substr",
66   US"tr" };
67
68 enum {
69   EITEM_EXTRACT,
70   EITEM_HASH,
71   EITEM_HMAC,
72   EITEM_IF,
73   EITEM_LENGTH,
74   EITEM_LOOKUP,
75   EITEM_NHASH,
76   #ifdef EXIM_PERL
77     EITEM_PERL,
78   #endif
79   EITEM_READFILE,
80   EITEM_READSOCK,
81   EITEM_RUN,
82   EITEM_SG,
83   EITEM_SUBSTR,
84   EITEM_TR };
85
86 /* Tables of operator names, and corresponding switch numbers. The names must be
87 in alphabetical order. There are two tables, because underscore is used in some
88 cases to introduce arguments, whereas for other it is part of the name. This is
89 an historical mis-design. */
90
91 static uschar *op_table_underscore[] = {
92   US"from_utf8",
93   US"local_part",
94   US"quote_local_part",
95   US"time_interval"};
96
97 enum {
98   EOP_FROM_UTF8,
99   EOP_LOCAL_PART,
100   EOP_QUOTE_LOCAL_PART,
101   EOP_TIME_INTERVAL };
102
103 static uschar *op_table_main[] = {
104   US"address",
105   US"base62",
106   US"base62d",
107   US"domain",
108   US"escape",
109   US"eval",
110   US"eval10",
111   US"expand",
112   US"h",
113   US"hash",
114   US"hex2b64",
115   US"l",
116   US"lc",
117   US"length",
118   US"mask",
119   US"md5",
120   US"nh",
121   US"nhash",
122   US"quote",
123   US"rfc2047",
124   US"rxquote",
125   US"s",
126   US"sha1",
127   US"stat",
128   US"str2b64",
129   US"strlen",
130   US"substr",
131   US"uc" };
132
133 enum {
134   EOP_ADDRESS =  sizeof(op_table_underscore)/sizeof(uschar *),
135   EOP_BASE62,
136   EOP_BASE62D,
137   EOP_DOMAIN,
138   EOP_ESCAPE,
139   EOP_EVAL,
140   EOP_EVAL10,
141   EOP_EXPAND,
142   EOP_H,
143   EOP_HASH,
144   EOP_HEX2B64,
145   EOP_L,
146   EOP_LC,
147   EOP_LENGTH,
148   EOP_MASK,
149   EOP_MD5,
150   EOP_NH,
151   EOP_NHASH,
152   EOP_QUOTE,
153   EOP_RFC2047,
154   EOP_RXQUOTE,
155   EOP_S,
156   EOP_SHA1,
157   EOP_STAT,
158   EOP_STR2B64,
159   EOP_STRLEN,
160   EOP_SUBSTR,
161   EOP_UC };
162
163
164 /* Table of condition names, and corresponding switch numbers. The names must
165 be in alphabetical order. */
166
167 static uschar *cond_table[] = {
168   US"<",
169   US"<=",
170   US"=",
171   US"==",     /* Backward compatibility */
172   US">",
173   US">=",
174   US"and",
175   US"crypteq",
176   US"def",
177   US"eq",
178   US"eqi",
179   US"exists",
180   US"first_delivery",
181   US"ge",
182   US"gei",
183   US"gt",
184   US"gti",
185   US"isip",
186   US"isip4",
187   US"isip6",
188   US"ldapauth",
189   US"le",
190   US"lei",
191   US"lt",
192   US"lti",
193   US"match",
194   US"match_address",
195   US"match_domain",
196   US"match_local_part",
197   US"or",
198   US"pam",
199   US"pwcheck",
200   US"queue_running",
201   US"radius",
202   US"saslauthd"
203 };
204
205 enum {
206   ECOND_NUM_L,
207   ECOND_NUM_LE,
208   ECOND_NUM_E,
209   ECOND_NUM_EE,
210   ECOND_NUM_G,
211   ECOND_NUM_GE,
212   ECOND_AND,
213   ECOND_CRYPTEQ,
214   ECOND_DEF,
215   ECOND_STR_EQ,
216   ECOND_STR_EQI,
217   ECOND_EXISTS,
218   ECOND_FIRST_DELIVERY,
219   ECOND_STR_GE,
220   ECOND_STR_GEI,
221   ECOND_STR_GT,
222   ECOND_STR_GTI,
223   ECOND_ISIP,
224   ECOND_ISIP4,
225   ECOND_ISIP6,
226   ECOND_LDAPAUTH,
227   ECOND_STR_LE,
228   ECOND_STR_LEI,
229   ECOND_STR_LT,
230   ECOND_STR_LTI,
231   ECOND_MATCH,
232   ECOND_MATCH_ADDRESS,
233   ECOND_MATCH_DOMAIN,
234   ECOND_MATCH_LOCAL_PART,
235   ECOND_OR,
236   ECOND_PAM,
237   ECOND_PWCHECK,
238   ECOND_QUEUE_RUNNING,
239   ECOND_RADIUS,
240   ECOND_SASLAUTHD
241 };
242
243
244 /* Type for main variable table */
245
246 typedef struct {
247   char *name;
248   int   type;
249   void *value;
250 } var_entry;
251
252 /* Type for entries pointing to address/length pairs. Not currently
253 in use. */
254
255 typedef struct {
256   uschar **address;
257   int  *length;
258 } alblock;
259
260 /* Types of table entry */
261
262 enum {
263   vtype_int,            /* value is address of int */
264   vtype_filter_int,     /* ditto, but recognized only when filtering */
265   vtype_ino,            /* value is address of ino_t (not always an int) */
266   vtype_uid,            /* value is address of uid_t (not always an int) */
267   vtype_gid,            /* value is address of gid_t (not always an int) */
268   vtype_stringptr,      /* value is address of pointer to string */
269   vtype_msgbody,        /* as stringptr, but read when first required */
270   vtype_msgbody_end,    /* ditto, the end of the message */
271   vtype_msgheaders,     /* the message's headers */
272   vtype_localpart,      /* extract local part from string */
273   vtype_domain,         /* extract domain from string */
274   vtype_recipients,     /* extract recipients from recipients list */
275                         /* (enabled only during system filtering */
276   vtype_todbsdin,       /* value not used; generate BSD inbox tod */
277   vtype_tode,           /* value not used; generate tod in epoch format */
278   vtype_todf,           /* value not used; generate full tod */
279   vtype_todl,           /* value not used; generate log tod */
280   vtype_todlf,          /* value not used; generate log file datestamp tod */
281   vtype_todzone,        /* value not used; generate time zone only */
282   vtype_todzulu,        /* value not used; generate zulu tod */
283   vtype_reply,          /* value not used; get reply from headers */
284   vtype_pid,            /* value not used; result is pid */
285   vtype_host_lookup,    /* value not used; get host name */
286   vtype_load_avg,       /* value not used; result is int from os_getloadavg */
287   vtype_pspace,         /* partition space; value is T/F for spool/log */
288   vtype_pinodes         /* partition inodes; value is T/F for spool/log */  
289   };
290
291 /* This table must be kept in alphabetical order. */
292
293 static var_entry var_table[] = {
294   { "acl_c0",              vtype_stringptr,   &acl_var[0] },
295   { "acl_c1",              vtype_stringptr,   &acl_var[1] },
296   { "acl_c2",              vtype_stringptr,   &acl_var[2] },
297   { "acl_c3",              vtype_stringptr,   &acl_var[3] },
298   { "acl_c4",              vtype_stringptr,   &acl_var[4] },
299   { "acl_c5",              vtype_stringptr,   &acl_var[5] },
300   { "acl_c6",              vtype_stringptr,   &acl_var[6] },
301   { "acl_c7",              vtype_stringptr,   &acl_var[7] },
302   { "acl_c8",              vtype_stringptr,   &acl_var[8] },
303   { "acl_c9",              vtype_stringptr,   &acl_var[9] },
304   { "acl_m0",              vtype_stringptr,   &acl_var[10] },
305   { "acl_m1",              vtype_stringptr,   &acl_var[11] },
306   { "acl_m2",              vtype_stringptr,   &acl_var[12] },
307   { "acl_m3",              vtype_stringptr,   &acl_var[13] },
308   { "acl_m4",              vtype_stringptr,   &acl_var[14] },
309   { "acl_m5",              vtype_stringptr,   &acl_var[15] },
310   { "acl_m6",              vtype_stringptr,   &acl_var[16] },
311   { "acl_m7",              vtype_stringptr,   &acl_var[17] },
312   { "acl_m8",              vtype_stringptr,   &acl_var[18] },
313   { "acl_m9",              vtype_stringptr,   &acl_var[19] },
314   { "acl_verify_message",  vtype_stringptr,   &acl_verify_message },
315   { "address_data",        vtype_stringptr,   &deliver_address_data },
316   { "address_file",        vtype_stringptr,   &address_file },
317   { "address_pipe",        vtype_stringptr,   &address_pipe },
318   { "authenticated_id",    vtype_stringptr,   &authenticated_id },
319   { "authenticated_sender",vtype_stringptr,   &authenticated_sender },
320   { "authentication_failed",vtype_int,        &authentication_failed },
321   { "body_linecount",      vtype_int,         &body_linecount },
322   { "body_zerocount",      vtype_int,         &body_zerocount },
323   { "bounce_recipient",    vtype_stringptr,   &bounce_recipient },
324   { "bounce_return_size_limit", vtype_int,    &bounce_return_size_limit },
325   { "caller_gid",          vtype_gid,         &real_gid },
326   { "caller_uid",          vtype_uid,         &real_uid },
327   { "compile_date",        vtype_stringptr,   &version_date },
328   { "compile_number",      vtype_stringptr,   &version_cnumber },
329   { "dnslist_domain",      vtype_stringptr,   &dnslist_domain },
330   { "dnslist_text",        vtype_stringptr,   &dnslist_text },
331   { "dnslist_value",       vtype_stringptr,   &dnslist_value },
332   { "domain",              vtype_stringptr,   &deliver_domain },
333   { "domain_data",         vtype_stringptr,   &deliver_domain_data },
334   { "exim_gid",            vtype_gid,         &exim_gid },
335   { "exim_path",           vtype_stringptr,   &exim_path },
336   { "exim_uid",            vtype_uid,         &exim_uid },
337   { "home",                vtype_stringptr,   &deliver_home },
338   { "host",                vtype_stringptr,   &deliver_host },
339   { "host_address",        vtype_stringptr,   &deliver_host_address },
340   { "host_data",           vtype_stringptr,   &host_data },
341   { "host_lookup_failed",  vtype_int,         &host_lookup_failed },
342   { "inode",               vtype_ino,         &deliver_inode },
343   { "interface_address",   vtype_stringptr,   &interface_address },
344   { "interface_port",      vtype_int,         &interface_port },
345   #ifdef LOOKUP_LDAP
346   { "ldap_dn",             vtype_stringptr,   &eldap_dn },
347   #endif
348   { "load_average",        vtype_load_avg,    NULL },
349   { "local_part",          vtype_stringptr,   &deliver_localpart },
350   { "local_part_data",     vtype_stringptr,   &deliver_localpart_data },
351   { "local_part_prefix",   vtype_stringptr,   &deliver_localpart_prefix },
352   { "local_part_suffix",   vtype_stringptr,   &deliver_localpart_suffix },
353   { "local_scan_data",     vtype_stringptr,   &local_scan_data },
354   { "local_user_gid",      vtype_gid,         &local_user_gid },
355   { "local_user_uid",      vtype_uid,         &local_user_uid },
356   { "localhost_number",    vtype_int,         &host_number },
357   { "log_inodes",          vtype_pinodes,     (void *)FALSE },
358   { "log_space",           vtype_pspace,      (void *)FALSE },  
359   { "mailstore_basename",  vtype_stringptr,   &mailstore_basename },
360   { "message_age",         vtype_int,         &message_age },
361   { "message_body",        vtype_msgbody,     &message_body },
362   { "message_body_end",    vtype_msgbody_end, &message_body_end },
363   { "message_body_size",   vtype_int,         &message_body_size },
364   { "message_headers",     vtype_msgheaders,  NULL },
365   { "message_id",          vtype_stringptr,   &message_id },
366   { "message_size",        vtype_int,         &message_size },
367   { "n0",                  vtype_filter_int,  &filter_n[0] },
368   { "n1",                  vtype_filter_int,  &filter_n[1] },
369   { "n2",                  vtype_filter_int,  &filter_n[2] },
370   { "n3",                  vtype_filter_int,  &filter_n[3] },
371   { "n4",                  vtype_filter_int,  &filter_n[4] },
372   { "n5",                  vtype_filter_int,  &filter_n[5] },
373   { "n6",                  vtype_filter_int,  &filter_n[6] },
374   { "n7",                  vtype_filter_int,  &filter_n[7] },
375   { "n8",                  vtype_filter_int,  &filter_n[8] },
376   { "n9",                  vtype_filter_int,  &filter_n[9] },
377   { "original_domain",     vtype_stringptr,   &deliver_domain_orig },
378   { "original_local_part", vtype_stringptr,   &deliver_localpart_orig },
379   { "originator_gid",      vtype_gid,         &originator_gid },
380   { "originator_uid",      vtype_uid,         &originator_uid },
381   { "parent_domain",       vtype_stringptr,   &deliver_domain_parent },
382   { "parent_local_part",   vtype_stringptr,   &deliver_localpart_parent },
383   { "pid",                 vtype_pid,         NULL },
384   { "primary_hostname",    vtype_stringptr,   &primary_hostname },
385   { "qualify_domain",      vtype_stringptr,   &qualify_domain_sender },
386   { "qualify_recipient",   vtype_stringptr,   &qualify_domain_recipient },
387   { "rcpt_count",          vtype_int,         &rcpt_count },
388   { "rcpt_defer_count",    vtype_int,         &rcpt_defer_count },
389   { "rcpt_fail_count",     vtype_int,         &rcpt_fail_count },
390   { "received_count",      vtype_int,         &received_count },
391   { "received_for",        vtype_stringptr,   &received_for },
392   { "received_protocol",   vtype_stringptr,   &received_protocol },
393   { "recipient_data",      vtype_stringptr,   &recipient_data },
394   { "recipient_verify_failure",vtype_stringptr,&recipient_verify_failure }, 
395   { "recipients",          vtype_recipients,  NULL },
396   { "recipients_count",    vtype_int,         &recipients_count },
397   { "reply_address",       vtype_reply,       NULL },
398   { "return_path",         vtype_stringptr,   &return_path },
399   { "return_size_limit",   vtype_int,         &bounce_return_size_limit },
400   { "runrc",               vtype_int,         &runrc },
401   { "self_hostname",       vtype_stringptr,   &self_hostname },
402   { "sender_address",      vtype_stringptr,   &sender_address },
403   { "sender_address_data", vtype_stringptr,   &sender_address_data },
404   { "sender_address_domain", vtype_domain,    &sender_address },
405   { "sender_address_local_part", vtype_localpart, &sender_address },
406   { "sender_data",         vtype_stringptr,   &sender_data },
407   { "sender_fullhost",     vtype_stringptr,   &sender_fullhost },
408   { "sender_helo_name",    vtype_stringptr,   &sender_helo_name },
409   { "sender_host_address", vtype_stringptr,   &sender_host_address },
410   { "sender_host_authenticated",vtype_stringptr, &sender_host_authenticated },
411   { "sender_host_name",    vtype_host_lookup, NULL },
412   { "sender_host_port",    vtype_int,         &sender_host_port },
413   { "sender_ident",        vtype_stringptr,   &sender_ident },
414   { "sender_rcvhost",      vtype_stringptr,   &sender_rcvhost },
415   { "sender_verify_failure",vtype_stringptr,  &sender_verify_failure }, 
416   { "smtp_command_argument", vtype_stringptr, &smtp_command_argument },
417   { "sn0",                 vtype_filter_int,  &filter_sn[0] },
418   { "sn1",                 vtype_filter_int,  &filter_sn[1] },
419   { "sn2",                 vtype_filter_int,  &filter_sn[2] },
420   { "sn3",                 vtype_filter_int,  &filter_sn[3] },
421   { "sn4",                 vtype_filter_int,  &filter_sn[4] },
422   { "sn5",                 vtype_filter_int,  &filter_sn[5] },
423   { "sn6",                 vtype_filter_int,  &filter_sn[6] },
424   { "sn7",                 vtype_filter_int,  &filter_sn[7] },
425   { "sn8",                 vtype_filter_int,  &filter_sn[8] },
426   { "sn9",                 vtype_filter_int,  &filter_sn[9] },
427   { "spool_directory",     vtype_stringptr,   &spool_directory },
428   { "spool_inodes",        vtype_pinodes,     (void *)TRUE },
429   { "spool_space",         vtype_pspace,      (void *)TRUE },  
430   { "thisaddress",         vtype_stringptr,   &filter_thisaddress },
431   { "tls_certificate_verified", vtype_int,    &tls_certificate_verified },
432   { "tls_cipher",          vtype_stringptr,   &tls_cipher },
433   { "tls_peerdn",          vtype_stringptr,   &tls_peerdn },
434   { "tod_bsdinbox",        vtype_todbsdin,    NULL },
435   { "tod_epoch",           vtype_tode,        NULL },
436   { "tod_full",            vtype_todf,        NULL },
437   { "tod_log",             vtype_todl,        NULL },
438   { "tod_logfile",         vtype_todlf,       NULL },
439   { "tod_zone",            vtype_todzone,     NULL },
440   { "tod_zulu",            vtype_todzulu,     NULL },
441   { "value",               vtype_stringptr,   &lookup_value },
442   { "version_number",      vtype_stringptr,   &version_string },
443   { "warn_message_delay",  vtype_stringptr,   &warnmsg_delay },
444   { "warn_message_recipient",vtype_stringptr, &warnmsg_recipients },
445   { "warn_message_recipients",vtype_stringptr,&warnmsg_recipients },
446   { "warnmsg_delay",       vtype_stringptr,   &warnmsg_delay },
447   { "warnmsg_recipient",   vtype_stringptr,   &warnmsg_recipients },
448   { "warnmsg_recipients",  vtype_stringptr,   &warnmsg_recipients }
449 };
450
451 static int var_table_size = sizeof(var_table)/sizeof(var_entry);
452 static uschar var_buffer[256];
453 static BOOL malformed_header;
454
455 /* For textual hashes */
456
457 static char *hashcodes = "abcdefghijklmnopqrtsuvwxyz"
458                          "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
459                          "0123456789";
460
461 enum { HMAC_MD5, HMAC_SHA1 };
462
463 /* For numeric hashes */
464
465 static unsigned int prime[] = {
466   2,   3,   5,   7,  11,  13,  17,  19,  23,  29,
467  31,  37,  41,  43,  47,  53,  59,  61,  67,  71,
468  73,  79,  83,  89,  97, 101, 103, 107, 109, 113};
469
470 /* For printing modes in symbolic form */
471
472 static uschar *mtable_normal[] =
473   { US"---", US"--x", US"-w-", US"-wx", US"r--", US"r-x", US"rw-", US"rwx" };
474
475 static uschar *mtable_setid[] =
476   { US"--S", US"--s", US"-wS", US"-ws", US"r-S", US"r-s", US"rwS", US"rws" };
477
478 static uschar *mtable_sticky[] =
479   { US"--T", US"--t", US"-wT", US"-wt", US"r-T", US"r-t", US"rwT", US"rwt" };
480
481
482
483 /*************************************************
484 *           Tables for UTF-8 support             *
485 *************************************************/
486
487 /* Table of the number of extra characters, indexed by the first character
488 masked with 0x3f. The highest number for a valid UTF-8 character is in fact
489 0x3d. */
490
491 static uschar utf8_table1[] = {
492   1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
493   1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
494   2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
495   3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 };
496
497 /* These are the masks for the data bits in the first byte of a character,
498 indexed by the number of additional bytes. */
499
500 static int utf8_table2[] = { 0xff, 0x1f, 0x0f, 0x07, 0x03, 0x01};
501
502 /* Get the next UTF-8 character, advancing the pointer. */
503
504 #define GETUTF8INC(c, ptr) \
505   c = *ptr++; \
506   if ((c & 0xc0) == 0xc0) \
507     { \
508     int a = utf8_table1[c & 0x3f];  /* Number of additional bytes */ \
509     int s = 6*a; \
510     c = (c & utf8_table2[a]) << s; \
511     while (a-- > 0) \
512       { \
513       s -= 6; \
514       c |= (*ptr++ & 0x3f) << s; \
515       } \
516     }
517
518
519 /*************************************************
520 *           Binary chop search on a table        *
521 *************************************************/
522
523 /* This is used for matching expansion items and operators.
524
525 Arguments:
526   name        the name that is being sought
527   table       the table to search
528   table_size  the number of items in the table
529
530 Returns:      the offset in the table, or -1
531 */
532
533 static int
534 chop_match(uschar *name, uschar **table, int table_size)
535 {
536 uschar **bot = table;
537 uschar **top = table + table_size;
538
539 while (top > bot)
540   {
541   uschar **mid = bot + (top - bot)/2;
542   int c = Ustrcmp(name, *mid);
543   if (c == 0) return mid - table;
544   if (c > 0) bot = mid + 1; else top = mid;
545   }
546
547 return -1;
548 }
549
550
551
552 /*************************************************
553 *          Check a condition string              *
554 *************************************************/
555
556 /* This function is called to expand a string, and test the result for a "true"
557 or "false" value. Failure of the expansion yields FALSE; logged unless it was a
558 forced fail or lookup defer. All store used by the function can be released on
559 exit.
560
561 Arguments:
562   condition     the condition string
563   m1            text to be incorporated in panic error
564   m2            ditto
565
566 Returns:        TRUE if condition is met, FALSE if not
567 */
568
569 BOOL
570 expand_check_condition(uschar *condition, uschar *m1, uschar *m2)
571 {
572 int rc;
573 void *reset_point = store_get(0);
574 uschar *ss = expand_string(condition);
575 if (ss == NULL)
576   {
577   if (!expand_string_forcedfail && !search_find_defer)
578     log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand condition \"%s\" "
579       "for %s %s: %s", condition, m1, m2, expand_string_message);
580   return FALSE;
581   }
582 rc = ss[0] != 0 && Ustrcmp(ss, "0") != 0 && strcmpic(ss, US"no") != 0 &&
583   strcmpic(ss, US"false") != 0;
584 store_reset(reset_point);
585 return rc;
586 }
587
588
589
590 /*************************************************
591 *             Pick out a name from a string      *
592 *************************************************/
593
594 /* If the name is too long, it is silently truncated.
595
596 Arguments:
597   name      points to a buffer into which to put the name
598   max       is the length of the buffer
599   s         points to the first alphabetic character of the name
600   extras    chars other than alphanumerics to permit
601
602 Returns:    pointer to the first character after the name
603
604 Note: The test for *s != 0 in the while loop is necessary because
605 Ustrchr() yields non-NULL if the character is zero (which is not something
606 I expected). */
607
608 static uschar *
609 read_name(uschar *name, int max, uschar *s, uschar *extras)
610 {
611 int ptr = 0;
612 while (*s != 0 && (isalnum(*s) || Ustrchr(extras, *s) != NULL))
613   {
614   if (ptr < max-1) name[ptr++] = *s;
615   s++;
616   }
617 name[ptr] = 0;
618 return s;
619 }
620
621
622
623 /*************************************************
624 *     Pick out the rest of a header name         *
625 *************************************************/
626
627 /* A variable name starting $header_ (or just $h_ for those who like
628 abbreviations) might not be the complete header name because headers can
629 contain any printing characters in their names, except ':'. This function is
630 called to read the rest of the name, chop h[eader]_ off the front, and put ':'
631 on the end, if the name was terminated by white space.
632
633 Arguments:
634   name      points to a buffer in which the name read so far exists
635   max       is the length of the buffer
636   s         points to the first character after the name so far, i.e. the
637             first non-alphameric character after $header_xxxxx
638
639 Returns:    a pointer to the first character after the header name
640 */
641
642 static uschar *
643 read_header_name(uschar *name, int max, uschar *s)
644 {
645 int prelen = Ustrchr(name, '_') - name + 1;
646 int ptr = Ustrlen(name) - prelen;
647 if (ptr > 0) memmove(name, name+prelen, ptr);
648 while (mac_isgraph(*s) && *s != ':')
649   {
650   if (ptr < max-1) name[ptr++] = *s;
651   s++;
652   }
653 if (*s == ':') s++;
654 name[ptr++] = ':';
655 name[ptr] = 0;
656 return s;
657 }
658
659
660
661 /*************************************************
662 *           Pick out a number from a string      *
663 *************************************************/
664
665 /* Arguments:
666   n     points to an integer into which to put the number
667   s     points to the first digit of the number
668
669 Returns:  a pointer to the character after the last digit
670 */
671
672 static uschar *
673 read_number(int *n, uschar *s)
674 {
675 *n = 0;
676 while (isdigit(*s)) *n = *n * 10 + (*s++ - '0');
677 return s;
678 }
679
680
681
682 /*************************************************
683 *        Extract keyed subfield from a string    *
684 *************************************************/
685
686 /* The yield is in dynamic store; NULL means that the key was not found.
687
688 Arguments:
689   key       points to the name of the key
690   s         points to the string from which to extract the subfield
691
692 Returns:    NULL if the subfield was not found, or
693             a pointer to the subfield's data
694 */
695
696 static uschar *
697 expand_getkeyed(uschar *key, uschar *s)
698 {
699 int length = Ustrlen(key);
700 while (isspace(*s)) s++;
701
702 /* Loop to search for the key */
703
704 while (*s != 0)
705   {
706   int dkeylength;
707   uschar *data;
708   uschar *dkey = s;
709
710   while (*s != 0 && *s != '=' && !isspace(*s)) s++;
711   dkeylength = s - dkey;
712   while (isspace(*s)) s++;
713   if (*s == '=') while (isspace((*(++s))));
714
715   data = string_dequote(&s);
716   if (length == dkeylength && strncmpic(key, dkey, length) == 0)
717     return data;
718
719   while (isspace(*s)) s++;
720   }
721
722 return NULL;
723 }
724
725
726
727
728 /*************************************************
729 *   Extract numbered subfield from string        *
730 *************************************************/
731
732 /* Extracts a numbered field from a string that is divided by tokens - for
733 example a line from /etc/passwd is divided by colon characters.  First field is
734 numbered one.  Negative arguments count from the right. Zero returns the whole
735 string. Returns NULL if there are insufficient tokens in the string
736
737 ***WARNING***
738 Modifies final argument - this is a dynamically generated string, so that's OK.
739
740 Arguments:
741   field       number of field to be extracted,
742                 first field = 1, whole string = 0, last field = -1
743   separators  characters that are used to break string into tokens
744   s           points to the string from which to extract the subfield
745
746 Returns:      NULL if the field was not found,
747               a pointer to the field's data inside s (modified to add 0)
748 */
749
750 static uschar *
751 expand_gettokened (int field, uschar *separators, uschar *s)
752 {
753 int sep = 1;
754 int count;
755 uschar *ss = s;
756 uschar *fieldtext = NULL;
757
758 if (field == 0) return s;
759
760 /* Break the line up into fields in place; for field > 0 we stop when we have
761 done the number of fields we want. For field < 0 we continue till the end of
762 the string, counting the number of fields. */
763
764 count = (field > 0)? field : INT_MAX;
765
766 while (count-- > 0)
767   {
768   size_t len;
769
770   /* Previous field was the last one in the string. For a positive field
771   number, this means there are not enough fields. For a negative field number,
772   check that there are enough, and scan back to find the one that is wanted. */
773
774   if (sep == 0)
775     {
776     if (field > 0 || (-field) > (INT_MAX - count - 1)) return NULL;
777     if ((-field) == (INT_MAX - count - 1)) return s;
778     while (field++ < 0)
779       {
780       ss--;
781       while (ss[-1] != 0) ss--;
782       }
783     fieldtext = ss;
784     break;
785     }
786
787   /* Previous field was not last in the string; save its start and put a
788   zero at its end. */
789
790   fieldtext = ss;
791   len = Ustrcspn(ss, separators);
792   sep = ss[len];
793   ss[len] = 0;
794   ss += len + 1;
795   }
796
797 return fieldtext;
798 }
799
800
801
802 /*************************************************
803 *        Extract a substring from a string       *
804 *************************************************/
805
806 /* Perform the ${substr or ${length expansion operations.
807
808 Arguments:
809   subject     the input string
810   value1      the offset from the start of the input string to the start of
811                 the output string; if negative, count from the right.
812   value2      the length of the output string, or negative (-1) for unset
813                 if value1 is positive, unset means "all after"
814                 if value1 is negative, unset means "all before"
815   len         set to the length of the returned string
816
817 Returns:      pointer to the output string, or NULL if there is an error
818 */
819
820 static uschar *
821 extract_substr(uschar *subject, int value1, int value2, int *len)
822 {
823 int sublen = Ustrlen(subject);
824
825 if (value1 < 0)    /* count from right */
826   {
827   value1 += sublen;
828
829   /* If the position is before the start, skip to the start, and adjust the
830   length. If the length ends up negative, the substring is null because nothing
831   can precede. This falls out naturally when the length is unset, meaning "all
832   to the left". */
833
834   if (value1 < 0)
835     {
836     value2 += value1;
837     if (value2 < 0) value2 = 0;
838     value1 = 0;
839     }
840
841   /* Otherwise an unset length => characters before value1 */
842
843   else if (value2 < 0)
844     {
845     value2 = value1;
846     value1 = 0;
847     }
848   }
849
850 /* For a non-negative offset, if the starting position is past the end of the
851 string, the result will be the null string. Otherwise, an unset length means
852 "rest"; just set it to the maximum - it will be cut down below if necessary. */
853
854 else
855   {
856   if (value1 > sublen)
857     {
858     value1 = sublen;
859     value2 = 0;
860     }
861   else if (value2 < 0) value2 = sublen;
862   }
863
864 /* Cut the length down to the maximum possible for the offset value, and get
865 the required characters. */
866
867 if (value1 + value2 > sublen) value2 = sublen - value1;
868 *len = value2;
869 return subject + value1;
870 }
871
872
873
874
875 /*************************************************
876 *            Old-style hash of a string          *
877 *************************************************/
878
879 /* Perform the ${hash expansion operation.
880
881 Arguments:
882   subject     the input string (an expanded substring)
883   value1      the length of the output string; if greater or equal to the
884                 length of the input string, the input string is returned
885   value2      the number of hash characters to use, or 26 if negative
886   len         set to the length of the returned string
887
888 Returns:      pointer to the output string, or NULL if there is an error
889 */
890
891 static uschar *
892 compute_hash(uschar *subject, int value1, int value2, int *len)
893 {
894 int sublen = Ustrlen(subject);
895
896 if (value2 < 0) value2 = 26;
897 else if (value2 > Ustrlen(hashcodes))
898   {
899   expand_string_message =
900     string_sprintf("hash count \"%d\" too big", value2);
901   return NULL;
902   }
903
904 /* Calculate the hash text. We know it is shorter than the original string, so
905 can safely place it in subject[] (we know that subject is always itself an
906 expanded substring). */
907
908 if (value1 < sublen)
909   {
910   int c;
911   int i = 0;
912   int j = value1;
913   while ((c = (subject[j])) != 0)
914     {
915     int shift = (c + j++) & 7;
916     subject[i] ^= (c << shift) | (c >> (8-shift));
917     if (++i >= value1) i = 0;
918     }
919   for (i = 0; i < value1; i++)
920     subject[i] = hashcodes[(subject[i]) % value2];
921   }
922 else value1 = sublen;
923
924 *len = value1;
925 return subject;
926 }
927
928
929
930
931 /*************************************************
932 *             Numeric hash of a string           *
933 *************************************************/
934
935 /* Perform the ${nhash expansion operation. The first characters of the
936 string are treated as most important, and get the highest prime numbers.
937
938 Arguments:
939   subject     the input string
940   value1      the maximum value of the first part of the result
941   value2      the maximum value of the second part of the result,
942                 or negative to produce only a one-part result
943   len         set to the length of the returned string
944
945 Returns:  pointer to the output string, or NULL if there is an error.
946 */
947
948 static uschar *
949 compute_nhash (uschar *subject, int value1, int value2, int *len)
950 {
951 uschar *s = subject;
952 int i = 0;
953 unsigned long int total = 0; /* no overflow */
954
955 while (*s != 0)
956   {
957   if (i == 0) i = sizeof(prime)/sizeof(int) - 1;
958   total += prime[i--] * (unsigned int)(*s++);
959   }
960
961 /* If value2 is unset, just compute one number */
962
963 if (value2 < 0)
964   {
965   s = string_sprintf("%d", total % value1);
966   }
967
968 /* Otherwise do a div/mod hash */
969
970 else
971   {
972   total = total % (value1 * value2);
973   s = string_sprintf("%d/%d", total/value2, total % value2);
974   }
975
976 *len = Ustrlen(s);
977 return s;
978 }
979
980
981
982
983
984 /*************************************************
985 *     Find the value of a header or headers      *
986 *************************************************/
987
988 /* Multiple instances of the same header get concatenated, and this function
989 can also return a concatenation of all the header lines. When concatenating
990 specific headers that contain lists of addresses, a comma is inserted between
991 them. Otherwise we use a straight concatenation. Because some messages can have
992 pathologically large number of lines, there is a limit on the length that is
993 returned. Also, to avoid massive store use which would result from using
994 string_cat() as it copies and extends strings, we do a preliminary pass to find
995 out exactly how much store will be needed. On "normal" messages this will be
996 pretty trivial.
997
998 Arguments:
999   name          the name of the header, without the leading $header_ or $h_,
1000                 or NULL if a concatenation of all headers is required
1001   exists_only   TRUE if called from a def: test; don't need to build a string;
1002                 just return a string that is not "" and not "0" if the header
1003                 exists
1004   newsize       return the size of memory block that was obtained; may be NULL
1005                 if exists_only is TRUE
1006   want_raw      TRUE if called for $rh_ or $rheader_ variables; no processing,
1007                 other than concatenating, will be done on the header
1008   charset       name of charset to translate MIME words to; used only if
1009                 want_raw is false; if NULL, no translation is done (this is
1010                 used for $bh_ and $bheader_)
1011
1012 Returns:        NULL if the header does not exist, else a pointer to a new
1013                 store block
1014 */
1015
1016 static uschar *
1017 find_header(uschar *name, BOOL exists_only, int *newsize, BOOL want_raw,
1018   uschar *charset)
1019 {
1020 BOOL found = name == NULL;
1021 int comma = 0;
1022 int len = found? 0 : Ustrlen(name);
1023 int i;
1024 uschar *yield = NULL;
1025 uschar *ptr = NULL;
1026
1027 /* Loop for two passes - saves code repetition */
1028
1029 for (i = 0; i < 2; i++)
1030   {
1031   int size = 0;
1032   header_line *h;
1033
1034   for (h = header_list; size < header_insert_maxlen && h != NULL; h = h->next)
1035     {
1036     if (h->type != htype_old && h->text != NULL)  /* NULL => Received: placeholder */
1037       {
1038       if (name == NULL || (len <= h->slen && strncmpic(name, h->text, len) == 0))
1039         {
1040         int ilen;
1041         uschar *t;
1042
1043         if (exists_only) return US"1";      /* don't need actual string */
1044         found = TRUE;
1045         t = h->text + len;                  /* text to insert */
1046         if (!want_raw)                      /* unless wanted raw, */
1047           while (isspace(*t)) t++;          /* remove leading white space */
1048         ilen = h->slen - (t - h->text);     /* length to insert */
1049
1050         /* Set comma = 1 if handling a single header and it's one of those
1051         that contains an address list, except when asked for raw headers. Only
1052         need to do this once. */
1053
1054         if (!want_raw && name != NULL && comma == 0 &&
1055             Ustrchr("BCFRST", h->type) != NULL)
1056           comma = 1;
1057
1058         /* First pass - compute total store needed; second pass - compute
1059         total store used, including this header. */
1060
1061         size += ilen + comma;
1062
1063         /* Second pass - concatentate the data, up to a maximum. Note that
1064         the loop stops when size hits the limit. */
1065
1066         if (i != 0)
1067           {
1068           if (size > header_insert_maxlen)
1069             {
1070             ilen -= size - header_insert_maxlen;
1071             comma = 0;
1072             }
1073           Ustrncpy(ptr, t, ilen);
1074           ptr += ilen;
1075           if (comma != 0 && ilen > 0)
1076             {
1077             ptr[-1] = ',';
1078             *ptr++ = '\n';
1079             }
1080           }
1081         }
1082       }
1083     }
1084
1085   /* At end of first pass, truncate size if necessary, and get the buffer
1086   to hold the data, returning the buffer size. */
1087
1088   if (i == 0)
1089     {
1090     if (!found) return NULL;
1091     if (size > header_insert_maxlen) size = header_insert_maxlen;
1092     *newsize = size + 1;
1093     ptr = yield = store_get(*newsize);
1094     }
1095   }
1096
1097 /* Remove a redundant added comma if present */
1098
1099 if (comma != 0 && ptr > yield) ptr -= 2;
1100
1101 /* That's all we do for raw header expansion. */
1102
1103 if (want_raw)
1104   {
1105   *ptr = 0;
1106   }
1107
1108 /* Otherwise, we remove trailing whitespace, including newlines. Then we do RFC
1109 2047 decoding, translating the charset if requested. The rfc2047_decode2()
1110 function can return an error with decoded data if the charset translation
1111 fails. If decoding fails, it returns NULL. */
1112
1113 else
1114   {
1115   uschar *decoded, *error;
1116   while (ptr > yield && isspace(ptr[-1])) ptr--;
1117   *ptr = 0;
1118   decoded = rfc2047_decode2(yield, TRUE, charset, '?', NULL, newsize, &error);
1119   if (error != NULL)
1120     {
1121     DEBUG(D_any) debug_printf("*** error in RFC 2047 decoding: %s\n"
1122       "    input was: %s\n", error, yield);
1123     }
1124   if (decoded != NULL) yield = decoded;
1125   }
1126
1127 return yield;
1128 }
1129
1130
1131
1132
1133 /*************************************************
1134 *               Find value of a variable         *
1135 *************************************************/
1136
1137 /* The table of variables is kept in alphabetic order, so we can search it
1138 using a binary chop. The "choplen" variable is nothing to do with the binary
1139 chop.
1140
1141 Arguments:
1142   name          the name of the variable being sought
1143   exists_only   TRUE if this is a def: test; passed on to find_header()
1144   skipping      TRUE => skip any processing evaluation; this is not the same as
1145                   exists_only because def: may test for values that are first
1146                   evaluated here
1147   newsize       pointer to an int which is initially zero; if the answer is in
1148                 a new memory buffer, *newsize is set to its size
1149
1150 Returns:        NULL if the variable does not exist, or
1151                 a pointer to the variable's contents, or
1152                 something non-NULL if exists_only is TRUE
1153 */
1154
1155 static uschar *
1156 find_variable(uschar *name, BOOL exists_only, BOOL skipping, int *newsize)
1157 {
1158 int first = 0;
1159 int last = var_table_size;
1160
1161 while (last > first)
1162   {
1163   uschar *s, *domain;
1164   uschar **ss;
1165   int middle = (first + last)/2;
1166   int c = Ustrcmp(name, var_table[middle].name);
1167
1168   if (c > 0) { first = middle + 1; continue; }
1169   if (c < 0) { last = middle; continue; }
1170
1171   /* Found an existing variable. If in skipping state, the value isn't needed,
1172   and we want to avoid processing (such as looking up up the host name). */
1173
1174   if (skipping) return US"";
1175
1176   switch (var_table[middle].type)
1177     {
1178     case vtype_filter_int:
1179     if (!filter_running) return NULL;
1180     /* Fall through */
1181
1182     case vtype_int:
1183     sprintf(CS var_buffer, "%d", *(int *)(var_table[middle].value)); /* Integer */
1184     return var_buffer;
1185
1186     case vtype_ino:
1187     sprintf(CS var_buffer, "%ld", (long int)(*(ino_t *)(var_table[middle].value))); /* Inode */
1188     return var_buffer;
1189
1190     case vtype_gid:
1191     sprintf(CS var_buffer, "%ld", (long int)(*(gid_t *)(var_table[middle].value))); /* gid */
1192     return var_buffer;
1193
1194     case vtype_uid:
1195     sprintf(CS var_buffer, "%ld", (long int)(*(uid_t *)(var_table[middle].value))); /* uid */
1196     return var_buffer;
1197
1198     case vtype_stringptr:                      /* Pointer to string */
1199     s = *((uschar **)(var_table[middle].value));
1200     return (s == NULL)? US"" : s;
1201
1202     case vtype_pid:
1203     sprintf(CS var_buffer, "%d", (int)getpid()); /* pid */
1204     return var_buffer;
1205
1206     case vtype_load_avg:
1207     sprintf(CS var_buffer, "%d", os_getloadavg()); /* load_average */
1208     return var_buffer;
1209
1210     case vtype_host_lookup:                    /* Lookup if not done so */
1211     if (sender_host_name == NULL && sender_host_address != NULL &&
1212         !host_lookup_failed && host_name_lookup() == OK)
1213       host_build_sender_fullhost();
1214     return (sender_host_name == NULL)? US"" : sender_host_name;
1215
1216     case vtype_localpart:                      /* Get local part from address */
1217     s = *((uschar **)(var_table[middle].value));
1218     if (s == NULL) return US"";
1219     domain = Ustrrchr(s, '@');
1220     if (domain == NULL) return s;
1221     if (domain - s > sizeof(var_buffer) - 1)
1222       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "local part longer than %d in "
1223         "string expansion", sizeof(var_buffer));
1224     Ustrncpy(var_buffer, s, domain - s);
1225     var_buffer[domain - s] = 0;
1226     return var_buffer;
1227
1228     case vtype_domain:                         /* Get domain from address */
1229     s = *((uschar **)(var_table[middle].value));
1230     if (s == NULL) return US"";
1231     domain = Ustrrchr(s, '@');
1232     return (domain == NULL)? US"" : domain + 1;
1233
1234     case vtype_msgheaders:
1235     return find_header(NULL, exists_only, newsize, FALSE, NULL);
1236
1237     case vtype_msgbody:                        /* Pointer to msgbody string */
1238     case vtype_msgbody_end:                    /* Ditto, the end of the msg */
1239     ss = (uschar **)(var_table[middle].value);
1240     if (*ss == NULL && deliver_datafile >= 0)  /* Read body when needed */
1241       {
1242       uschar *body;
1243       int start_offset = SPOOL_DATA_START_OFFSET;
1244       int len = message_body_visible;
1245       if (len > message_size) len = message_size;
1246       *ss = body = store_malloc(len+1);
1247       body[0] = 0;
1248       if (var_table[middle].type == vtype_msgbody_end)
1249         {
1250         struct stat statbuf;
1251         if (fstat(deliver_datafile, &statbuf) == 0)
1252           {
1253           start_offset = statbuf.st_size - len;
1254           if (start_offset < SPOOL_DATA_START_OFFSET)
1255             start_offset = SPOOL_DATA_START_OFFSET;
1256           }
1257         }
1258       lseek(deliver_datafile, start_offset, SEEK_SET);
1259       len = read(deliver_datafile, body, len);
1260       if (len > 0)
1261         {
1262         body[len] = 0;
1263         while (len > 0)
1264           {
1265           if (body[--len] == '\n' || body[len] == 0) body[len] = ' ';
1266           }
1267         }
1268       }
1269     return (*ss == NULL)? US"" : *ss;
1270
1271     case vtype_todbsdin:                       /* BSD inbox time of day */
1272     return tod_stamp(tod_bsdin);
1273
1274     case vtype_tode:                           /* Unix epoch time of day */
1275     return tod_stamp(tod_epoch);
1276
1277     case vtype_todf:                           /* Full time of day */
1278     return tod_stamp(tod_full);
1279
1280     case vtype_todl:                           /* Log format time of day */
1281     return tod_stamp(tod_log_bare);            /* (without timezone) */
1282
1283     case vtype_todzone:                        /* Time zone offset only */
1284     return tod_stamp(tod_zone);
1285
1286     case vtype_todzulu:                        /* Zulu time */
1287     return tod_stamp(tod_zulu);
1288
1289     case vtype_todlf:                          /* Log file datestamp tod */
1290     return tod_stamp(tod_log_datestamp);
1291
1292     case vtype_reply:                          /* Get reply address */
1293     s = find_header(US"reply-to:", exists_only, newsize, FALSE,
1294       headers_charset);
1295     if (s == NULL || *s == 0)
1296       s = find_header(US"from:", exists_only, newsize, FALSE, headers_charset);
1297     return (s == NULL)? US"" : s;
1298
1299     /* A recipients list is available only during system message filtering,
1300     during ACL processing after DATA, and while expanding pipe commands
1301     generated from a system filter, but not elsewhere. */
1302
1303     case vtype_recipients:
1304     if (!enable_dollar_recipients) return NULL; else
1305       {
1306       int size = 128;
1307       int ptr = 0;
1308       int i;
1309       s = store_get(size);
1310       for (i = 0; i < recipients_count; i++)
1311         {
1312         if (i != 0) s = string_cat(s, &size, &ptr, US", ", 2);
1313         s = string_cat(s, &size, &ptr, recipients_list[i].address,
1314           Ustrlen(recipients_list[i].address));
1315         }
1316       s[ptr] = 0;     /* string_cat() leaves room */
1317       }
1318     return s;
1319     
1320     case vtype_pspace:
1321       {
1322       int inodes;
1323       sprintf(CS var_buffer, "%d", 
1324         receive_statvfs((BOOL)(var_table[middle].value), &inodes));  
1325       }
1326     return var_buffer;
1327     
1328     case vtype_pinodes:
1329       {
1330       int inodes;
1331       (void) receive_statvfs((BOOL)(var_table[middle].value), &inodes);  
1332       sprintf(CS var_buffer, "%d", inodes);
1333       }
1334     return var_buffer;
1335     }
1336   }
1337
1338 return NULL;          /* Unknown variable name */
1339 }
1340
1341
1342
1343
1344 /*************************************************
1345 *           Read and expand substrings           *
1346 *************************************************/
1347
1348 /* This function is called to read and expand argument substrings for various
1349 expansion items. Some have a minimum requirement that is less than the maximum;
1350 in these cases, the first non-present one is set to NULL.
1351
1352 Arguments:
1353   sub        points to vector of pointers to set
1354   n          maximum number of substrings
1355   m          minimum required
1356   sptr       points to current string pointer
1357   skipping   the skipping flag
1358   check_end  if TRUE, check for final '}'
1359   name       name of item, for error message
1360
1361 Returns:     0 OK; string pointer updated
1362              1 curly bracketing error (too few arguments)
1363              2 too many arguments (only if check_end is set); message set
1364              3 other error (expansion failure)
1365 */
1366
1367 static int
1368 read_subs(uschar **sub, int n, int m, uschar **sptr, BOOL skipping,
1369   BOOL check_end, uschar *name)
1370 {
1371 int i;
1372 uschar *s = *sptr;
1373
1374 while (isspace(*s)) s++;
1375 for (i = 0; i < n; i++)
1376   {
1377   if (*s != '{')
1378     {
1379     if (i < m) return 1;
1380     sub[i] = NULL;
1381     break;
1382     }
1383   sub[i] = expand_string_internal(s+1, TRUE, &s, skipping);
1384   if (sub[i] == NULL) return 3;
1385   if (*s++ != '}') return 1;
1386   while (isspace(*s)) s++;
1387   }
1388 if (check_end && *s++ != '}')
1389   {
1390   if (s[-1] == '{')
1391     {
1392     expand_string_message = string_sprintf("Too many arguments for \"%s\" "
1393       "(max is %d)", name, n);
1394     return 2;
1395     }
1396   return 1;
1397   }
1398
1399 *sptr = s;
1400 return 0;
1401 }
1402
1403
1404
1405
1406 /*************************************************
1407 *        Read and evaluate a condition           *
1408 *************************************************/
1409
1410 /*
1411 Arguments:
1412   s        points to the start of the condition text
1413   yield    points to a BOOL to hold the result of the condition test;
1414            if NULL, we are just reading through a condition that is
1415            part of an "or" combination to check syntax, or in a state
1416            where the answer isn't required
1417
1418 Returns:   a pointer to the first character after the condition, or
1419            NULL after an error
1420 */
1421
1422 static uschar *
1423 eval_condition(uschar *s, BOOL *yield)
1424 {
1425 BOOL testfor = TRUE;
1426 BOOL tempcond, combined_cond;
1427 BOOL *subcondptr;
1428 int i, rc, cond_type, roffset;
1429 int num[2];
1430 struct stat statbuf;
1431 uschar name[256];
1432 uschar *sub[4];
1433
1434 const pcre *re;
1435 const uschar *rerror;
1436
1437 for (;;)
1438   {
1439   while (isspace(*s)) s++;
1440   if (*s == '!') { testfor = !testfor; s++; } else break;
1441   }
1442
1443 /* Numeric comparisons are symbolic */
1444
1445 if (*s == '=' || *s == '>' || *s == '<')
1446   {
1447   int p = 0;
1448   name[p++] = *s++;
1449   if (*s == '=')
1450     {
1451     name[p++] = '=';
1452     s++;
1453     }
1454   name[p] = 0;
1455   }
1456
1457 /* All other conditions are named */
1458
1459 else s = read_name(name, 256, s, US"_");
1460
1461 /* If we haven't read a name, it means some non-alpha character is first. */
1462
1463 if (name[0] == 0)
1464   {
1465   expand_string_message = string_sprintf("condition name expected, "
1466     "but found \"%.16s\"", s);
1467   return NULL;
1468   }
1469
1470 /* Find which condition we are dealing with, and switch on it */
1471
1472 cond_type = chop_match(name, cond_table, sizeof(cond_table)/sizeof(uschar *));
1473 switch(cond_type)
1474   {
1475   /* def: tests for a non-zero or non-NULL variable, or for an existing
1476   header */
1477
1478   case ECOND_DEF:
1479   if (*s != ':')
1480     {
1481     expand_string_message = US"\":\" expected after \"def\"";
1482     return NULL;
1483     }
1484
1485   s = read_name(name, 256, s+1, US"_");
1486
1487   /* Test for a header's existence */
1488
1489   if (Ustrncmp(name, "h_", 2) == 0 ||
1490       Ustrncmp(name, "rh_", 3) == 0 ||
1491       Ustrncmp(name, "bh_", 3) == 0 ||
1492       Ustrncmp(name, "header_", 7) == 0 ||
1493       Ustrncmp(name, "rheader_", 8) == 0 ||
1494       Ustrncmp(name, "bheader_", 8) == 0)
1495     {
1496     s = read_header_name(name, 256, s);
1497     if (yield != NULL) *yield =
1498       (find_header(name, TRUE, NULL, FALSE, NULL) != NULL) == testfor;
1499     }
1500
1501   /* Test for a variable's having a non-empty value. If yield == NULL we
1502   are in a skipping state, and don't care about the answer. */
1503
1504   else
1505     {
1506     uschar *value = find_variable(name, TRUE, yield == NULL, NULL);
1507     if (value == NULL)
1508       {
1509       expand_string_message = (name[0] == 0)?
1510         string_sprintf("variable name omitted after \"def:\"") :
1511         string_sprintf("unknown variable \"%s\" after \"def:\"", name);
1512       return NULL;
1513       }
1514     if (yield != NULL)
1515       *yield = (value[0] != 0 && Ustrcmp(value, "0") != 0) == testfor;
1516     }
1517
1518   return s;
1519
1520
1521   /* first_delivery tests for first delivery attempt */
1522
1523   case ECOND_FIRST_DELIVERY:
1524   if (yield != NULL) *yield = deliver_firsttime == testfor;
1525   return s;
1526
1527
1528   /* queue_running tests for any process started by a queue runner */
1529
1530   case ECOND_QUEUE_RUNNING:
1531   if (yield != NULL) *yield = (queue_run_pid != (pid_t)0) == testfor;
1532   return s;
1533
1534
1535   /* exists:  tests for file existence
1536        isip:  tests for any IP address
1537       isip4:  tests for an IPv4 address
1538       isip6:  tests for an IPv6 address
1539         pam:  does PAM authentication
1540      radius:  does RADIUS authentication
1541    ldapauth:  does LDAP authentication
1542     pwcheck:  does Cyrus SASL pwcheck authentication
1543   */
1544
1545   case ECOND_EXISTS:
1546   case ECOND_ISIP:
1547   case ECOND_ISIP4:
1548   case ECOND_ISIP6:
1549   case ECOND_PAM:
1550   case ECOND_RADIUS:
1551   case ECOND_LDAPAUTH:
1552   case ECOND_PWCHECK:
1553
1554   while (isspace(*s)) s++;
1555   if (*s != '{') goto COND_FAILED_CURLY_START;
1556
1557   sub[0] = expand_string_internal(s+1, TRUE, &s, yield == NULL);
1558   if (sub[0] == NULL) return NULL;
1559   if (*s++ != '}') goto COND_FAILED_CURLY_END;
1560
1561   if (yield == NULL) return s;   /* No need to run the test if skipping */
1562
1563   switch(cond_type)
1564     {
1565     case ECOND_EXISTS:
1566     if ((expand_forbid & RDO_EXISTS) != 0)
1567       {
1568       expand_string_message = US"File existence tests are not permitted";
1569       return NULL;
1570       }
1571     *yield = (Ustat(sub[0], &statbuf) == 0) == testfor;
1572     break;
1573
1574     case ECOND_ISIP:
1575     case ECOND_ISIP4:
1576     case ECOND_ISIP6:
1577     rc = string_is_ip_address(sub[0], NULL);
1578     *yield = ((cond_type == ECOND_ISIP)? (rc > 0) :
1579              (cond_type == ECOND_ISIP4)? (rc == 4) : (rc == 6)) == testfor;
1580     break;
1581
1582     /* Various authentication tests - all optionally compiled */
1583
1584     case ECOND_PAM:
1585     #ifdef SUPPORT_PAM
1586     rc = auth_call_pam(sub[0], &expand_string_message);
1587     goto END_AUTH;
1588     #else
1589     goto COND_FAILED_NOT_COMPILED;
1590     #endif  /* SUPPORT_PAM */
1591
1592     case ECOND_RADIUS:
1593     #ifdef RADIUS_CONFIG_FILE
1594     rc = auth_call_radius(sub[0], &expand_string_message);
1595     goto END_AUTH;
1596     #else
1597     goto COND_FAILED_NOT_COMPILED;
1598     #endif  /* RADIUS_CONFIG_FILE */
1599
1600     case ECOND_LDAPAUTH:
1601     #ifdef LOOKUP_LDAP
1602       {
1603       /* Just to keep the interface the same */
1604       BOOL do_cache;
1605       int old_pool = store_pool;
1606       store_pool = POOL_SEARCH;
1607       rc = eldapauth_find((void *)(-1), NULL, sub[0], Ustrlen(sub[0]), NULL,
1608         &expand_string_message, &do_cache);
1609       store_pool = old_pool;
1610       }
1611     goto END_AUTH;
1612     #else
1613     goto COND_FAILED_NOT_COMPILED;
1614     #endif  /* LOOKUP_LDAP */
1615
1616     case ECOND_PWCHECK:
1617     #ifdef CYRUS_PWCHECK_SOCKET
1618     rc = auth_call_pwcheck(sub[0], &expand_string_message);
1619     goto END_AUTH;
1620     #else
1621     goto COND_FAILED_NOT_COMPILED;
1622     #endif  /* CYRUS_PWCHECK_SOCKET */
1623
1624     #if defined(SUPPORT_PAM) || defined(RADIUS_CONFIG_FILE) || \
1625         defined(LOOKUP_LDAP) || defined(CYRUS_PWCHECK_SOCKET)
1626     END_AUTH:
1627     if (rc == ERROR || rc == DEFER) return NULL;
1628     *yield = (rc == OK) == testfor;
1629     #endif
1630     }
1631   return s;
1632
1633
1634   /* saslauthd: does Cyrus saslauthd authentication. Four parameters are used:
1635
1636      ${if saslauthd {{username}{password}{service}{realm}}  {yes}[no}}
1637
1638   However, the last two are optional. That is why the whole set is enclosed
1639   in their own set or braces. */
1640
1641   case ECOND_SASLAUTHD:
1642   #ifndef CYRUS_SASLAUTHD_SOCKET
1643   goto COND_FAILED_NOT_COMPILED;
1644   #else
1645   while (isspace(*s)) s++;
1646   if (*s++ != '{') goto COND_FAILED_CURLY_START;
1647   switch(read_subs(sub, 4, 2, &s, yield == NULL, TRUE, US"saslauthd"))
1648     {
1649     case 1: expand_string_message = US"too few arguments or bracketing "
1650       "error for saslauthd";
1651     case 2:
1652     case 3: return NULL;
1653     }
1654   if (sub[2] == NULL) sub[3] = NULL;  /* realm if no service */
1655   if (yield != NULL)
1656     {
1657     int rc;
1658     rc = auth_call_saslauthd(sub[0], sub[1], sub[2], sub[3],
1659       &expand_string_message);
1660     if (rc == ERROR || rc == DEFER) return NULL;
1661     *yield = (rc == OK) == testfor;
1662     }
1663   return s;
1664   #endif /* CYRUS_SASLAUTHD_SOCKET */
1665
1666
1667   /* symbolic operators for numeric and string comparison, and a number of
1668   other operators, all requiring two arguments.
1669
1670   match:             does a regular expression match and sets up the numerical
1671                        variables if it succeeds
1672   match_address:     matches in an address list
1673   match_domain:      matches in a domain list
1674   match_local_part:  matches in a local part list
1675   crypteq:           encrypts plaintext and compares against an encrypted text,
1676                        using crypt(), crypt16(), MD5 or SHA-1
1677   */
1678
1679   case ECOND_MATCH:
1680   case ECOND_MATCH_ADDRESS:
1681   case ECOND_MATCH_DOMAIN:
1682   case ECOND_MATCH_LOCAL_PART:
1683   case ECOND_CRYPTEQ:
1684
1685   case ECOND_NUM_L:     /* Numerical comparisons */
1686   case ECOND_NUM_LE:
1687   case ECOND_NUM_E:
1688   case ECOND_NUM_EE:
1689   case ECOND_NUM_G:
1690   case ECOND_NUM_GE:
1691
1692   case ECOND_STR_LT:    /* String comparisons */
1693   case ECOND_STR_LTI:
1694   case ECOND_STR_LE:
1695   case ECOND_STR_LEI:
1696   case ECOND_STR_EQ:
1697   case ECOND_STR_EQI:
1698   case ECOND_STR_GT:
1699   case ECOND_STR_GTI:
1700   case ECOND_STR_GE:
1701   case ECOND_STR_GEI:
1702
1703   for (i = 0; i < 2; i++)
1704     {
1705     while (isspace(*s)) s++;
1706     if (*s != '{')
1707       {
1708       if (i == 0) goto COND_FAILED_CURLY_START;
1709       expand_string_message = string_sprintf("missing 2nd string in {} "
1710         "after \"%s\"", name);
1711       return NULL;
1712       }
1713     sub[i] = expand_string_internal(s+1, TRUE, &s, yield == NULL);
1714     if (sub[i] == NULL) return NULL;
1715     if (*s++ != '}') goto COND_FAILED_CURLY_END;
1716
1717     /* Convert to numerical if required; we know that the names of all the
1718     conditions that compare numbers do not start with a letter. This just saves
1719     checking for them individually. */
1720
1721     if (!isalpha(name[0]))
1722       {
1723       uschar *endptr;
1724       num[i] = (int)Ustrtol((const uschar *)sub[i], &endptr, 10);
1725       if (tolower(*endptr) == 'k')
1726         {
1727         num[i] *= 1024;
1728         endptr++;
1729         }
1730       else if (tolower(*endptr) == 'm')
1731         {
1732         num[i] *= 1024*1024;
1733         endptr++;
1734         }
1735       while (isspace(*endptr)) endptr++;
1736       if (*endptr != 0)
1737         {
1738         expand_string_message = string_sprintf("\"%s\" is not a number",
1739           sub[i]);
1740         return NULL;
1741         }
1742       }
1743     }
1744
1745   /* Result not required */
1746
1747   if (yield == NULL) return s;
1748
1749   /* Do an appropriate comparison */
1750
1751   switch(cond_type)
1752     {
1753     case ECOND_NUM_E:
1754     case ECOND_NUM_EE:
1755     *yield = (num[0] == num[1]) == testfor;
1756     break;
1757
1758     case ECOND_NUM_G:
1759     *yield = (num[0] > num[1]) == testfor;
1760     break;
1761
1762     case ECOND_NUM_GE:
1763     *yield = (num[0] >= num[1]) == testfor;
1764     break;
1765
1766     case ECOND_NUM_L:
1767     *yield = (num[0] < num[1]) == testfor;
1768     break;
1769
1770     case ECOND_NUM_LE:
1771     *yield = (num[0] <= num[1]) == testfor;
1772     break;
1773
1774     case ECOND_STR_LT:
1775     *yield = (Ustrcmp(sub[0], sub[1]) < 0) == testfor;
1776     break;
1777
1778     case ECOND_STR_LTI:
1779     *yield = (strcmpic(sub[0], sub[1]) < 0) == testfor;
1780     break;
1781
1782     case ECOND_STR_LE:
1783     *yield = (Ustrcmp(sub[0], sub[1]) <= 0) == testfor;
1784     break;
1785
1786     case ECOND_STR_LEI:
1787     *yield = (strcmpic(sub[0], sub[1]) <= 0) == testfor;
1788     break;
1789
1790     case ECOND_STR_EQ:
1791     *yield = (Ustrcmp(sub[0], sub[1]) == 0) == testfor;
1792     break;
1793
1794     case ECOND_STR_EQI:
1795     *yield = (strcmpic(sub[0], sub[1]) == 0) == testfor;
1796     break;
1797
1798     case ECOND_STR_GT:
1799     *yield = (Ustrcmp(sub[0], sub[1]) > 0) == testfor;
1800     break;
1801
1802     case ECOND_STR_GTI:
1803     *yield = (strcmpic(sub[0], sub[1]) > 0) == testfor;
1804     break;
1805
1806     case ECOND_STR_GE:
1807     *yield = (Ustrcmp(sub[0], sub[1]) >= 0) == testfor;
1808     break;
1809
1810     case ECOND_STR_GEI:
1811     *yield = (strcmpic(sub[0], sub[1]) >= 0) == testfor;
1812     break;
1813
1814     case ECOND_MATCH:   /* Regular expression match */
1815     re = pcre_compile(CS sub[1], PCRE_COPT, (const char **)&rerror, &roffset,
1816       NULL);
1817     if (re == NULL)
1818       {
1819       expand_string_message = string_sprintf("regular expression error in "
1820         "\"%s\": %s at offset %d", sub[1], rerror, roffset);
1821       return NULL;
1822       }
1823     *yield = regex_match_and_setup(re, sub[0], 0, -1) == testfor;
1824     break;
1825
1826     case ECOND_MATCH_ADDRESS:  /* Match in an address list */
1827     rc = match_address_list(sub[0], TRUE, FALSE, &(sub[1]), NULL, -1, 0, NULL);
1828     goto MATCHED_SOMETHING;
1829
1830     case ECOND_MATCH_DOMAIN:   /* Match in a domain list */
1831     rc = match_isinlist(sub[0], &(sub[1]), 0, &domainlist_anchor, NULL,
1832       MCL_DOMAIN + MCL_NOEXPAND, TRUE, NULL);
1833     goto MATCHED_SOMETHING;
1834
1835     case ECOND_MATCH_LOCAL_PART:
1836     rc = match_isinlist(sub[0], &(sub[1]), 0, &localpartlist_anchor, NULL,
1837       MCL_LOCALPART + MCL_NOEXPAND, TRUE, NULL);
1838     /* Fall through */
1839
1840     MATCHED_SOMETHING:
1841     switch(rc)
1842       {
1843       case OK:
1844       *yield = testfor;
1845       break;
1846
1847       case FAIL:
1848       *yield = !testfor;
1849       break;
1850
1851       case DEFER:
1852       expand_string_message = string_sprintf("unable to complete match "
1853         "against \"%s\": %s", sub[1], search_error_message);
1854       return NULL;
1855       }
1856
1857     break;
1858
1859     /* Various "encrypted" comparisons. If the second string starts with
1860     "{" then an encryption type is given. Default to crypt() or crypt16()
1861     (build-time choice). */
1862
1863     case ECOND_CRYPTEQ:
1864     #ifndef SUPPORT_CRYPTEQ
1865     goto COND_FAILED_NOT_COMPILED;
1866     #else
1867     if (strncmpic(sub[1], US"{md5}", 5) == 0)
1868       {
1869       int sublen = Ustrlen(sub[1]+5);
1870       md5 base;
1871       uschar digest[16];
1872
1873       md5_start(&base);
1874       md5_end(&base, (uschar *)sub[0], Ustrlen(sub[0]), digest);
1875
1876       /* If the length that we are comparing against is 24, the MD5 digest
1877       is expressed as a base64 string. This is the way LDAP does it. However,
1878       some other software uses a straightforward hex representation. We assume
1879       this if the length is 32. Other lengths fail. */
1880
1881       if (sublen == 24)
1882         {
1883         uschar *coded = auth_b64encode((uschar *)digest, 16);
1884         DEBUG(D_auth) debug_printf("crypteq: using MD5+B64 hashing\n"
1885           "  subject=%s\n  crypted=%s\n", coded, sub[1]+5);
1886         *yield = (Ustrcmp(coded, sub[1]+5) == 0) == testfor;
1887         }
1888       else if (sublen == 32)
1889         {
1890         int i;
1891         uschar coded[36];
1892         for (i = 0; i < 16; i++) sprintf(CS (coded+2*i), "%02X", digest[i]);
1893         coded[32] = 0;
1894         DEBUG(D_auth) debug_printf("crypteq: using MD5+hex hashing\n"
1895           "  subject=%s\n  crypted=%s\n", coded, sub[1]+5);
1896         *yield = (strcmpic(coded, sub[1]+5) == 0) == testfor;
1897         }
1898       else
1899         {
1900         DEBUG(D_auth) debug_printf("crypteq: length for MD5 not 24 or 32: "
1901           "fail\n  crypted=%s\n", sub[1]+5);
1902         *yield = !testfor;
1903         }
1904       }
1905
1906     else if (strncmpic(sub[1], US"{sha1}", 6) == 0)
1907       {
1908       int sublen = Ustrlen(sub[1]+6);
1909       sha1 base;
1910       uschar digest[20];
1911
1912       sha1_start(&base);
1913       sha1_end(&base, (uschar *)sub[0], Ustrlen(sub[0]), digest);
1914
1915       /* If the length that we are comparing against is 28, assume the SHA1
1916       digest is expressed as a base64 string. If the length is 40, assume a
1917       straightforward hex representation. Other lengths fail. */
1918
1919       if (sublen == 28)
1920         {
1921         uschar *coded = auth_b64encode((uschar *)digest, 20);
1922         DEBUG(D_auth) debug_printf("crypteq: using SHA1+B64 hashing\n"
1923           "  subject=%s\n  crypted=%s\n", coded, sub[1]+6);
1924         *yield = (Ustrcmp(coded, sub[1]+6) == 0) == testfor;
1925         }
1926       else if (sublen == 40)
1927         {
1928         int i;
1929         uschar coded[44];
1930         for (i = 0; i < 20; i++) sprintf(CS (coded+2*i), "%02X", digest[i]);
1931         coded[40] = 0;
1932         DEBUG(D_auth) debug_printf("crypteq: using SHA1+hex hashing\n"
1933           "  subject=%s\n  crypted=%s\n", coded, sub[1]+6);
1934         *yield = (strcmpic(coded, sub[1]+6) == 0) == testfor;
1935         }
1936       else
1937         {
1938         DEBUG(D_auth) debug_printf("crypteq: length for SHA-1 not 28 or 40: "
1939           "fail\n  crypted=%s\n", sub[1]+6);
1940         *yield = !testfor;
1941         }
1942       }
1943
1944     else   /* {crypt} or {crypt16} and non-{ at start */
1945       {
1946       int which = 0;
1947       uschar *coded;
1948
1949       if (strncmpic(sub[1], US"{crypt}", 7) == 0)
1950         {
1951         sub[1] += 7;
1952         which = 1;
1953         }
1954       else if (strncmpic(sub[1], US"{crypt16}", 9) == 0)
1955         {
1956         sub[1] += 9;
1957         which = 2;
1958         }
1959       else if (sub[1][0] == '{')
1960         {
1961         expand_string_message = string_sprintf("unknown encryption mechanism "
1962           "in \"%s\"", sub[1]);
1963         return NULL;
1964         }
1965
1966       switch(which)
1967         {
1968         case 0:  coded = US DEFAULT_CRYPT(CS sub[0], CS sub[1]); break;
1969         case 1:  coded = US crypt(CS sub[0], CS sub[1]); break;
1970         default: coded = US crypt16(CS sub[0], CS sub[1]); break;
1971         }
1972
1973       #define STR(s) # s
1974       #define XSTR(s) STR(s)
1975       DEBUG(D_auth) debug_printf("crypteq: using %s()\n"
1976         "  subject=%s\n  crypted=%s\n",
1977         (which == 0)? XSTR(DEFAULT_CRYPT) : (which == 1)? "crypt" : "crypt16",
1978         coded, sub[1]);
1979       #undef STR
1980       #undef XSTR
1981
1982       /* If the encrypted string contains fewer than two characters (for the
1983       salt), force failure. Otherwise we get false positives: with an empty
1984       string the yield of crypt() is an empty string! */
1985
1986       *yield = (Ustrlen(sub[1]) < 2)? !testfor :
1987         (Ustrcmp(coded, sub[1]) == 0) == testfor;
1988       }
1989     break;
1990     #endif  /* SUPPORT_CRYPTEQ */
1991     }   /* Switch for comparison conditions */
1992
1993   return s;    /* End of comparison conditions */
1994
1995
1996   /* and/or: computes logical and/or of several conditions */
1997
1998   case ECOND_AND:
1999   case ECOND_OR:
2000   subcondptr = (yield == NULL)? NULL : &tempcond;
2001   combined_cond = (cond_type == ECOND_AND);
2002
2003   while (isspace(*s)) s++;
2004   if (*s++ != '{') goto COND_FAILED_CURLY_START;
2005
2006   for (;;)
2007     {
2008     while (isspace(*s)) s++;
2009     if (*s == '}') break;
2010     if (*s != '{')
2011       {
2012       expand_string_message = string_sprintf("each subcondition "
2013         "inside an \"%s{...}\" condition must be in its own {}", name);
2014       return NULL;
2015       }
2016
2017     s = eval_condition(s+1, subcondptr);
2018     if (s == NULL)
2019       {
2020       expand_string_message = string_sprintf("%s inside \"%s{...}\" condition",
2021         expand_string_message, name);
2022       return NULL;
2023       }
2024     while (isspace(*s)) s++;
2025
2026     if (*s++ != '}')
2027       {
2028       expand_string_message = string_sprintf("missing } at end of condition "
2029         "inside \"%s\" group", name);
2030       return NULL;
2031       }
2032
2033     if (yield != NULL)
2034       {
2035       if (cond_type == ECOND_AND)
2036         {
2037         combined_cond &= tempcond;
2038         if (!combined_cond) subcondptr = NULL;  /* once false, don't */
2039         }                                       /* evaluate any more */
2040       else
2041         {
2042         combined_cond |= tempcond;
2043         if (combined_cond) subcondptr = NULL;   /* once true, don't */
2044         }                                       /* evaluate any more */
2045       }
2046     }
2047
2048   if (yield != NULL) *yield = (combined_cond == testfor);
2049   return ++s;
2050
2051
2052   /* Unknown condition */
2053
2054   default:
2055   expand_string_message = string_sprintf("unknown condition \"%s\"", name);
2056   return NULL;
2057   }   /* End switch on condition type */
2058
2059 /* Missing braces at start and end of data */
2060
2061 COND_FAILED_CURLY_START:
2062 expand_string_message = string_sprintf("missing { after \"%s\"", name);
2063 return NULL;
2064
2065 COND_FAILED_CURLY_END:
2066 expand_string_message = string_sprintf("missing } at end of \"%s\" condition",
2067   name);
2068 return NULL;
2069
2070 /* A condition requires code that is not compiled */
2071
2072 #if !defined(SUPPORT_PAM) || !defined(RADIUS_CONFIG_FILE) || \
2073     !defined(LOOKUP_LDAP) || !defined(CYRUS_PWCHECK_SOCKET) || \
2074     !defined(SUPPORT_CRYPTEQ) || !defined(CYRUS_SASLAUTHD_SOCKET)
2075 COND_FAILED_NOT_COMPILED:
2076 expand_string_message = string_sprintf("support for \"%s\" not compiled",
2077   name);
2078 return NULL;
2079 #endif
2080 }
2081
2082
2083
2084
2085 /*************************************************
2086 *          Save numerical variables              *
2087 *************************************************/
2088
2089 /* This function is called from items such as "if" that want to preserve and
2090 restore the numbered variables.
2091
2092 Arguments:
2093   save_expand_string    points to an array of pointers to set
2094   save_expand_nlength   points to an array of ints for the lengths
2095
2096 Returns:                the value of expand max to save
2097 */
2098
2099 static int
2100 save_expand_strings(uschar **save_expand_nstring, int *save_expand_nlength)
2101 {
2102 int i;
2103 for (i = 0; i <= expand_nmax; i++)
2104   {
2105   save_expand_nstring[i] = expand_nstring[i];
2106   save_expand_nlength[i] = expand_nlength[i];
2107   }
2108 return expand_nmax;
2109 }
2110
2111
2112
2113 /*************************************************
2114 *           Restore numerical variables          *
2115 *************************************************/
2116
2117 /* This function restored saved values of numerical strings.
2118
2119 Arguments:
2120   save_expand_nmax      the number of strings to restore
2121   save_expand_string    points to an array of pointers
2122   save_expand_nlength   points to an array of ints
2123
2124 Returns:                nothing
2125 */
2126
2127 static void
2128 restore_expand_strings(int save_expand_nmax, uschar **save_expand_nstring,
2129   int *save_expand_nlength)
2130 {
2131 int i;
2132 expand_nmax = save_expand_nmax;
2133 for (i = 0; i <= expand_nmax; i++)
2134   {
2135   expand_nstring[i] = save_expand_nstring[i];
2136   expand_nlength[i] = save_expand_nlength[i];
2137   }
2138 }
2139
2140
2141
2142
2143
2144 /*************************************************
2145 *            Handle yes/no substrings            *
2146 *************************************************/
2147
2148 /* This function is used by ${if}, ${lookup} and ${extract} to handle the
2149 alternative substrings that depend on whether or not the condition was true,
2150 or the lookup or extraction succeeded. The substrings always have to be
2151 expanded, to check their syntax, but "skipping" is set when the result is not
2152 needed - this avoids unnecessary nested lookups.
2153
2154 Arguments:
2155   skipping       TRUE if we were skipping when this item was reached
2156   yes            TRUE if the first string is to be used, else use the second
2157   save_lookup    a value to put back into lookup_value before the 2nd expansion
2158   sptr           points to the input string pointer
2159   yieldptr       points to the output string pointer
2160   sizeptr        points to the output string size
2161   ptrptr         points to the output string pointer
2162   type           "lookup" or "if" or "extract" or "run", for error message
2163
2164 Returns:         0 OK; lookup_value has been reset to save_lookup
2165                  1 expansion failed
2166                  2 expansion failed because of bracketing error
2167 */
2168
2169 static int
2170 process_yesno(BOOL skipping, BOOL yes, uschar *save_lookup, uschar **sptr,
2171   uschar **yieldptr, int *sizeptr, int *ptrptr, uschar *type)
2172 {
2173 int rc = 0;
2174 uschar *s = *sptr;    /* Local value */
2175 uschar *sub1, *sub2;
2176
2177 /* If there are no following strings, we substitute the contents of $value for
2178 lookups and for extractions in the success case. For the ${if item, the string
2179 "true" is substituted. In the fail case, nothing is substituted for all three 
2180 items. */
2181
2182 while (isspace(*s)) s++;
2183 if (*s == '}')
2184   {
2185   if (type[0] == 'i')
2186     {
2187     if (yes) *yieldptr = string_cat(*yieldptr, sizeptr, ptrptr, US"true", 4); 
2188     }
2189   else
2190     {      
2191     if (yes && lookup_value != NULL)
2192       *yieldptr = string_cat(*yieldptr, sizeptr, ptrptr, lookup_value,
2193         Ustrlen(lookup_value));
2194     lookup_value = save_lookup;
2195     }
2196   s++;
2197   goto RETURN;
2198   }
2199
2200 /* Expand the first substring. Forced failures are noticed only if we actually
2201 want this string. Set skipping in the call in the fail case (this will always
2202 be the case if we were already skipping). */
2203
2204 sub1 = expand_string_internal(s+1, TRUE, &s, !yes);
2205 if (sub1 == NULL && (yes || !expand_string_forcedfail)) goto FAILED;
2206 expand_string_forcedfail = FALSE;
2207 if (*s++ != '}') goto FAILED_CURLY;
2208
2209 /* If we want the first string, add it to the output */
2210
2211 if (yes)
2212   *yieldptr = string_cat(*yieldptr, sizeptr, ptrptr, sub1, Ustrlen(sub1));
2213
2214 /* If this is called from a lookup or an extract, we want to restore $value to
2215 what it was at the start of the item, so that it has this value during the
2216 second string expansion. For the call from "if" to this function, save_lookup
2217 is set to lookup_value, so that this statement does nothing. */
2218
2219 lookup_value = save_lookup;
2220
2221 /* There now follows either another substring, or "fail", or nothing. This
2222 time, forced failures are noticed only if we want the second string. We must
2223 set skipping in the nested call if we don't want this string, or if we were
2224 already skipping. */
2225
2226 while (isspace(*s)) s++;
2227 if (*s == '{')
2228   {
2229   sub2 = expand_string_internal(s+1, TRUE, &s, yes || skipping);
2230   if (sub2 == NULL && (!yes || !expand_string_forcedfail)) goto FAILED;
2231   expand_string_forcedfail = FALSE;
2232   if (*s++ != '}') goto FAILED_CURLY;
2233
2234   /* If we want the second string, add it to the output */
2235
2236   if (!yes)
2237     *yieldptr = string_cat(*yieldptr, sizeptr, ptrptr, sub2, Ustrlen(sub2));
2238   }
2239
2240 /* If there is no second string, but the word "fail" is present when the use of
2241 the second string is wanted, set a flag indicating it was a forced failure
2242 rather than a syntactic error. Swallow the terminating } in case this is nested
2243 inside another lookup or if or extract. */
2244
2245 else if (*s != '}')
2246   {
2247   uschar name[256];
2248   s = read_name(name, sizeof(name), s, US"_");
2249   if (Ustrcmp(name, "fail") == 0)
2250     {
2251     if (!yes && !skipping)
2252       {
2253       while (isspace(*s)) s++;
2254       if (*s++ != '}') goto FAILED_CURLY;
2255       expand_string_message =
2256         string_sprintf("\"%s\" failed and \"fail\" requested", type);
2257       expand_string_forcedfail = TRUE;
2258       goto FAILED;
2259       }
2260     }
2261   else
2262     {
2263     expand_string_message =
2264       string_sprintf("syntax error in \"%s\" item - \"fail\" expected", type);
2265     goto FAILED;
2266     }
2267   }
2268
2269 /* All we have to do now is to check on the final closing brace. */
2270
2271 while (isspace(*s)) s++;
2272 if (*s++ == '}') goto RETURN;
2273
2274 /* Get here if there is a bracketing failure */
2275
2276 FAILED_CURLY:
2277 rc++;
2278
2279 /* Get here for other failures */
2280
2281 FAILED:
2282 rc++;
2283
2284 /* Update the input pointer value before returning */
2285
2286 RETURN:
2287 *sptr = s;
2288 return rc;
2289 }
2290
2291
2292
2293
2294
2295
2296 /*************************************************
2297 *    Handle MD5 or SHA-1 computation for HMAC    *
2298 *************************************************/
2299
2300 /* These are some wrapping functions that enable the HMAC code to be a bit
2301 cleaner. A good compiler will spot the tail recursion.
2302
2303 Arguments:
2304   type         HMAC_MD5 or HMAC_SHA1
2305   remaining    are as for the cryptographic hash functions
2306
2307 Returns:       nothing
2308 */
2309
2310 static void
2311 chash_start(int type, void *base)
2312 {
2313 if (type == HMAC_MD5)
2314   md5_start((md5 *)base);
2315 else
2316   sha1_start((sha1 *)base);
2317 }
2318
2319 static void
2320 chash_mid(int type, void *base, uschar *string)
2321 {
2322 if (type == HMAC_MD5)
2323   md5_mid((md5 *)base, string);
2324 else
2325   sha1_mid((sha1 *)base, string);
2326 }
2327
2328 static void
2329 chash_end(int type, void *base, uschar *string, int length, uschar *digest)
2330 {
2331 if (type == HMAC_MD5)
2332   md5_end((md5 *)base, string, length, digest);
2333 else
2334   sha1_end((sha1 *)base, string, length, digest);
2335 }
2336
2337
2338
2339
2340
2341 /*************************************************
2342 *        Join a file onto the output string      *
2343 *************************************************/
2344
2345 /* This is used for readfile and after a run expansion. It joins the contents
2346 of a file onto the output string, globally replacing newlines with a given
2347 string (optionally). The file is closed at the end.
2348
2349 Arguments:
2350   f            the FILE
2351   yield        pointer to the expandable string
2352   sizep        pointer to the current size
2353   ptrp         pointer to the current position
2354   eol          newline replacement string, or NULL
2355
2356 Returns:       new value of string pointer
2357 */
2358
2359 static uschar *
2360 cat_file(FILE *f, uschar *yield, int *sizep, int *ptrp, uschar *eol)
2361 {
2362 int eollen;
2363 uschar buffer[1024];
2364
2365 eollen = (eol == NULL)? 0 : Ustrlen(eol);
2366
2367 while (Ufgets(buffer, sizeof(buffer), f) != NULL)
2368   {
2369   int len = Ustrlen(buffer);
2370   if (eol != NULL && buffer[len-1] == '\n') len--;
2371   yield = string_cat(yield, sizep, ptrp, buffer, len);
2372   if (buffer[len] != 0)
2373     yield = string_cat(yield, sizep, ptrp, eol, eollen);
2374   }
2375
2376 if (yield != NULL) yield[*ptrp] = 0;
2377
2378 return yield;
2379 }
2380
2381
2382
2383
2384 /*************************************************
2385 *          Evaluate numeric expression           *
2386 *************************************************/
2387
2388 /* This is a set of mutually recursive functions that evaluate a simple
2389 arithmetic expression involving only + - * / and parentheses. The only one that
2390 is called from elsewhere is eval_expr, whose interface is:
2391
2392 Arguments:
2393   sptr          pointer to the pointer to the string - gets updated
2394   decimal       TRUE if numbers are to be assumed decimal
2395   error         pointer to where to put an error message - must be NULL on input
2396   endket        TRUE if ')' must terminate - FALSE for external call
2397
2398
2399 Returns:        on success: the value of the expression, with *error still NULL
2400                 on failure: an undefined value, with *error = a message
2401 */
2402
2403 static int eval_sumterm(uschar **, BOOL, uschar **);
2404
2405 static int
2406 eval_expr(uschar **sptr, BOOL decimal, uschar **error, BOOL endket)
2407 {
2408 uschar *s = *sptr;
2409 int x = eval_sumterm(&s, decimal, error);
2410 if (*error == NULL)
2411   {
2412   while (*s == '+' || *s == '-')
2413     {
2414     int op = *s++;
2415     int y = eval_sumterm(&s, decimal, error);
2416     if (*error != NULL) break;
2417     if (op == '+') x += y; else x -= y;
2418     }
2419   if (*error == NULL)
2420     {
2421     if (endket)
2422       {
2423       if (*s != ')')
2424         *error = US"expecting closing parenthesis";
2425       else
2426         while (isspace(*(++s)));
2427       }
2428     else if (*s != 0) *error = US"expecting + or -";
2429     }
2430   }
2431
2432 *sptr = s;
2433 return x;
2434 }
2435
2436 static int
2437 eval_term(uschar **sptr, BOOL decimal, uschar **error)
2438 {
2439 register int c;
2440 int n;
2441 uschar *s = *sptr;
2442 while (isspace(*s)) s++;
2443 c = *s;
2444 if (isdigit(c) || ((c == '-' || c == '+') && isdigit(s[1])))
2445   {
2446   int count;
2447   (void)sscanf(CS s, (decimal? "%d%n" : "%i%n"), &n, &count);
2448   s += count;
2449   if (tolower(*s) == 'k') { n *= 1024; s++; }
2450     else if (tolower(*s) == 'm') { n *= 1024*1024; s++; }
2451   while (isspace (*s)) s++;
2452   }
2453 else if (c == '(')
2454   {
2455   s++;
2456   n = eval_expr(&s, decimal, error, 1);
2457   }
2458 else
2459   {
2460   *error = US"expecting number or opening parenthesis";
2461   n = 0;
2462   }
2463 *sptr = s;
2464 return n;
2465 }
2466
2467 static int eval_sumterm(uschar **sptr, BOOL decimal, uschar **error)
2468 {
2469 uschar *s = *sptr;
2470 int x = eval_term(&s, decimal, error);
2471 if (*error == NULL)
2472   {
2473   while (*s == '*' || *s == '/')
2474     {
2475     int op = *s++;
2476     int y = eval_term(&s, decimal, error);
2477     if (*error != NULL) break;
2478     if (op == '*') x *= y; else x /= y;
2479     }
2480   }
2481 *sptr = s;
2482 return x;
2483 }
2484
2485
2486
2487
2488 /*************************************************
2489 *                 Expand string                  *
2490 *************************************************/
2491
2492 /* Returns either an unchanged string, or the expanded string in stacking pool
2493 store. Interpreted sequences are:
2494
2495    \...                    normal escaping rules
2496    $name                   substitutes the variable
2497    ${name}                 ditto
2498    ${op:string}            operates on the expanded string value
2499    ${item{arg1}{arg2}...}  expands the args and then does the business
2500                              some literal args are not enclosed in {}
2501
2502 There are now far too many operators and item types to make it worth listing
2503 them here in detail any more.
2504
2505 We use an internal routine recursively to handle embedded substrings. The
2506 external function follows. The yield is NULL if the expansion failed, and there
2507 are two cases: if something collapsed syntactically, or if "fail" was given
2508 as the action on a lookup failure. These can be distinguised by looking at the
2509 variable expand_string_forcedfail, which is TRUE in the latter case.
2510
2511 The skipping flag is set true when expanding a substring that isn't actually
2512 going to be used (after "if" or "lookup") and it prevents lookups from
2513 happening lower down.
2514
2515 Store usage: At start, a store block of the length of the input plus 64
2516 is obtained. This is expanded as necessary by string_cat(), which might have to
2517 get a new block, or might be able to expand the original. At the end of the
2518 function we can release any store above that portion of the yield block that
2519 was actually used. In many cases this will be optimal.
2520
2521 However: if the first item in the expansion is a variable name or header name,
2522 we reset the store before processing it; if the result is in fresh store, we
2523 use that without copying. This is helpful for expanding strings like
2524 $message_headers which can get very long.
2525
2526 Arguments:
2527   string         the string to be expanded
2528   ket_ends       true if expansion is to stop at }
2529   left           if not NULL, a pointer to the first character after the
2530                  expansion is placed here (typically used with ket_ends)
2531   skipping       TRUE for recursive calls when the value isn't actually going
2532                  to be used (to allow for optimisation)
2533
2534 Returns:         NULL if expansion fails:
2535                    expand_string_forcedfail is set TRUE if failure was forced
2536                    expand_string_message contains a textual error message
2537                  a pointer to the expanded string on success
2538 */
2539
2540 static uschar *
2541 expand_string_internal(uschar *string, BOOL ket_ends, uschar **left,
2542   BOOL skipping)
2543 {
2544 int ptr = 0;
2545 int size = Ustrlen(string)+ 64;
2546 int item_type;
2547 uschar *yield = store_get(size);
2548 uschar *s = string;
2549 uschar *save_expand_nstring[EXPAND_MAXN+1];
2550 int save_expand_nlength[EXPAND_MAXN+1];
2551
2552 expand_string_forcedfail = FALSE;
2553 expand_string_message = US"";
2554
2555 while (*s != 0)
2556   {
2557   uschar *value;
2558   uschar name[256];
2559
2560   /* \ escapes the next character, which must exist, or else
2561   the expansion fails. There's a special escape, \N, which causes
2562   copying of the subject verbatim up to the next \N. Otherwise,
2563   the escapes are the standard set. */
2564
2565   if (*s == '\\')
2566     {
2567     if (s[1] == 0)
2568       {
2569       expand_string_message = US"\\ at end of string";
2570       goto EXPAND_FAILED;
2571       }
2572
2573     if (s[1] == 'N')
2574       {
2575       uschar *t = s + 2;
2576       for (s = t; *s != 0; s++) if (*s == '\\' && s[1] == 'N') break;
2577       yield = string_cat(yield, &size, &ptr, t, s - t);
2578       if (*s != 0) s += 2;
2579       }
2580
2581     else
2582       {
2583       uschar ch[1];
2584       ch[0] = string_interpret_escape(&s);
2585       s++;
2586       yield = string_cat(yield, &size, &ptr, ch, 1);
2587       }
2588
2589     continue;
2590     }
2591
2592   /* Anything other than $ is just copied verbatim, unless we are
2593   looking for a terminating } character. */
2594
2595   if (ket_ends && *s == '}') break;
2596
2597   if (*s != '$')
2598     {
2599     yield = string_cat(yield, &size, &ptr, s++, 1);
2600     continue;
2601     }
2602
2603   /* No { after the $ - must be a plain name or a number for string
2604   match variable. There has to be a fudge for variables that are the
2605   names of header fields preceded by "$header_" because header field
2606   names can contain any printing characters except space and colon.
2607   For those that don't like typing this much, "$h_" is a synonym for
2608   "$header_". A non-existent header yields a NULL value; nothing is
2609   inserted. */
2610
2611   if (isalpha((*(++s))))
2612     {
2613     int len;
2614     int newsize = 0;
2615
2616     s = read_name(name, sizeof(name), s, US"_");
2617
2618     /* If this is the first thing to be expanded, release the pre-allocated
2619     buffer. */
2620
2621     if (ptr == 0 && yield != NULL)
2622       {
2623       store_reset(yield);
2624       yield = NULL;
2625       size = 0;
2626       }
2627
2628     /* Header */
2629
2630     if (Ustrncmp(name, "h_", 2) == 0 ||
2631         Ustrncmp(name, "rh_", 3) == 0 ||
2632         Ustrncmp(name, "bh_", 3) == 0 ||
2633         Ustrncmp(name, "header_", 7) == 0 ||
2634         Ustrncmp(name, "rheader_", 8) == 0 ||
2635         Ustrncmp(name, "bheader_", 8) == 0)
2636       {
2637       BOOL want_raw = (name[0] == 'r')? TRUE : FALSE;
2638       uschar *charset = (name[0] == 'b')? NULL : headers_charset;
2639       s = read_header_name(name, sizeof(name), s);
2640       value = find_header(name, FALSE, &newsize, want_raw, charset);
2641
2642       /* If we didn't find the header, and the header contains a closing brace
2643       characters, this may be a user error where the terminating colon
2644       has been omitted. Set a flag to adjust the error message in this case.
2645       But there is no error here - nothing gets inserted. */
2646
2647       if (value == NULL)
2648         {
2649         if (Ustrchr(name, '}') != NULL) malformed_header = TRUE;
2650         continue;
2651         }
2652       }
2653
2654     /* Variable */
2655
2656     else
2657       {
2658       value = find_variable(name, FALSE, skipping, &newsize);
2659       if (value == NULL)
2660         {
2661         expand_string_message =
2662           string_sprintf("unknown variable name \"%s\"", name);
2663         goto EXPAND_FAILED;
2664         }
2665       }
2666
2667     /* If the data is known to be in a new buffer, newsize will be set to the
2668     size of that buffer. If this is the first thing in an expansion string,
2669     yield will be NULL; just point it at the new store instead of copying. Many
2670     expansion strings contain just one reference, so this is a useful
2671     optimization, especially for humungous headers. */
2672
2673     len = Ustrlen(value);
2674     if (yield == NULL && newsize != 0)
2675       {
2676       yield = value;
2677       size = newsize;
2678       ptr = len;
2679       }
2680     else yield = string_cat(yield, &size, &ptr, value, len);
2681
2682     continue;
2683     }
2684
2685   if (isdigit(*s))
2686     {
2687     int n;
2688     s = read_number(&n, s);
2689     if (n >= 0 && n <= expand_nmax)
2690       yield = string_cat(yield, &size, &ptr, expand_nstring[n],
2691         expand_nlength[n]);
2692     continue;
2693     }
2694
2695   /* Otherwise, if there's no '{' after $ it's an error. */
2696
2697   if (*s != '{')
2698     {
2699     expand_string_message = US"$ not followed by letter, digit, or {";
2700     goto EXPAND_FAILED;
2701     }
2702
2703   /* After { there can be various things, but they all start with
2704   an initial word, except for a number for a string match variable. */
2705
2706   if (isdigit((*(++s))))
2707     {
2708     int n;
2709     s = read_number(&n, s);
2710     if (*s++ != '}')
2711       {
2712       expand_string_message = US"} expected after number";
2713       goto EXPAND_FAILED;
2714       }
2715     if (n >= 0 && n <= expand_nmax)
2716       yield = string_cat(yield, &size, &ptr, expand_nstring[n],
2717         expand_nlength[n]);
2718     continue;
2719     }
2720
2721   if (!isalpha(*s))
2722     {
2723     expand_string_message = US"letter or digit expected after ${";
2724     goto EXPAND_FAILED;
2725     }
2726
2727   /* Allow "-" in names to cater for substrings with negative
2728   arguments. Since we are checking for known names after { this is
2729   OK. */
2730
2731   s = read_name(name, sizeof(name), s, US"_-");
2732   item_type = chop_match(name, item_table, sizeof(item_table)/sizeof(uschar *));
2733
2734   switch(item_type)
2735     {
2736     /* Handle conditionals - preserve the values of the numerical expansion
2737     variables in case they get changed by a regular expression match in the
2738     condition. If not, they retain their external settings. At the end
2739     of this "if" section, they get restored to their previous values. */
2740
2741     case EITEM_IF:
2742       {
2743       BOOL cond = FALSE;
2744       uschar *next_s;
2745       int save_expand_nmax =
2746         save_expand_strings(save_expand_nstring, save_expand_nlength);
2747
2748       while (isspace(*s)) s++;
2749       next_s = eval_condition(s, skipping? NULL : &cond);
2750       if (next_s == NULL) goto EXPAND_FAILED;  /* message already set */
2751
2752       DEBUG(D_expand)
2753         debug_printf("condition: %.*s\n   result: %s\n", (int)(next_s - s), s,
2754           cond? "true" : "false");
2755
2756       s = next_s;
2757
2758       /* The handling of "yes" and "no" result strings is now in a separate
2759       function that is also used by ${lookup} and ${extract} and ${run}. */
2760
2761       switch(process_yesno(
2762                skipping,                     /* were previously skipping */
2763                cond,                         /* success/failure indicator */
2764                lookup_value,                 /* value to reset for string2 */
2765                &s,                           /* input pointer */
2766                &yield,                       /* output pointer */
2767                &size,                        /* output size */
2768                &ptr,                         /* output current point */
2769                US"if"))                      /* condition type */
2770         {
2771         case 1: goto EXPAND_FAILED;          /* when all is well, the */
2772         case 2: goto EXPAND_FAILED_CURLY;    /* returned value is 0 */
2773         }
2774
2775       /* Restore external setting of expansion variables for continuation
2776       at this level. */
2777
2778       restore_expand_strings(save_expand_nmax, save_expand_nstring,
2779         save_expand_nlength);
2780       continue;
2781       }
2782
2783     /* Handle database lookups unless locked out. If "skipping" is TRUE, we are
2784     expanding an internal string that isn't actually going to be used. All we
2785     need to do is check the syntax, so don't do a lookup at all. Preserve the
2786     values of the numerical expansion variables in case they get changed by a
2787     partial lookup. If not, they retain their external settings. At the end
2788     of this "lookup" section, they get restored to their previous values. */
2789
2790     case EITEM_LOOKUP:
2791       {
2792       int stype, partial, affixlen, starflags;
2793       int expand_setup = 0;
2794       int nameptr = 0;
2795       uschar *key, *filename, *affix;
2796       uschar *save_lookup_value = lookup_value;
2797       int save_expand_nmax =
2798         save_expand_strings(save_expand_nstring, save_expand_nlength);
2799
2800       if ((expand_forbid & RDO_LOOKUP) != 0)
2801         {
2802         expand_string_message = US"lookup expansions are not permitted";
2803         goto EXPAND_FAILED;
2804         }
2805
2806       /* Get the key we are to look up for single-key+file style lookups.
2807       Otherwise set the key NULL pro-tem. */
2808
2809       while (isspace(*s)) s++;
2810       if (*s == '{')
2811         {
2812         key = expand_string_internal(s+1, TRUE, &s, skipping);
2813         if (key == NULL) goto EXPAND_FAILED;
2814         if (*s++ != '}') goto EXPAND_FAILED_CURLY;
2815         while (isspace(*s)) s++;
2816         }
2817       else key = NULL;
2818
2819       /* Find out the type of database */
2820
2821       if (!isalpha(*s))
2822         {
2823         expand_string_message = US"missing lookup type";
2824         goto EXPAND_FAILED;
2825         }
2826
2827       /* The type is a string that may contain special characters of various
2828       kinds. Allow everything except space or { to appear; the actual content
2829       is checked by search_findtype_partial. */
2830
2831       while (*s != 0 && *s != '{' && !isspace(*s))
2832         {
2833         if (nameptr < sizeof(name) - 1) name[nameptr++] = *s;
2834         s++;
2835         }
2836       name[nameptr] = 0;
2837       while (isspace(*s)) s++;
2838
2839       /* Now check for the individual search type and any partial or default
2840       options. Only those types that are actually in the binary are valid. */
2841
2842       stype = search_findtype_partial(name, &partial, &affix, &affixlen,
2843         &starflags);
2844       if (stype < 0)
2845         {
2846         expand_string_message = search_error_message;
2847         goto EXPAND_FAILED;
2848         }
2849
2850       /* Check that a key was provided for those lookup types that need it,
2851       and was not supplied for those that use the query style. */
2852
2853       if (!mac_islookup(stype, lookup_querystyle))
2854         {
2855         if (key == NULL)
2856           {
2857           expand_string_message = string_sprintf("missing {key} for single-"
2858             "key \"%s\" lookup", name);
2859           goto EXPAND_FAILED;
2860           }
2861         }
2862       else
2863         {
2864         if (key != NULL)
2865           {
2866           expand_string_message = string_sprintf("a single key was given for "
2867             "lookup type \"%s\", which is not a single-key lookup type", name);
2868           goto EXPAND_FAILED;
2869           }
2870         }
2871
2872       /* Get the next string in brackets and expand it. It is the file name for
2873       single-key+file lookups, and the whole query otherwise. */
2874
2875       if (*s != '{') goto EXPAND_FAILED_CURLY;
2876       filename = expand_string_internal(s+1, TRUE, &s, skipping);
2877       if (filename == NULL) goto EXPAND_FAILED;
2878       if (*s++ != '}') goto EXPAND_FAILED_CURLY;
2879       while (isspace(*s)) s++;
2880
2881       /* If this isn't a single-key+file lookup, re-arrange the variables
2882       to be appropriate for the search_ functions. */
2883
2884       if (key == NULL)
2885         {
2886         key = filename;
2887         filename = NULL;
2888         }
2889
2890       /* If skipping, don't do the next bit - just lookup_value == NULL, as if
2891       the entry was not found. Note that there is no search_close() function.
2892       Files are left open in case of re-use. At suitable places in higher logic,
2893       search_tidyup() is called to tidy all open files. This can save opening
2894       the same file several times. However, files may also get closed when
2895       others are opened, if too many are open at once. The rule is that a
2896       handle should not be used after a second search_open().
2897
2898       Request that a partial search sets up $1 and maybe $2 by passing
2899       expand_setup containing zero. If its value changes, reset expand_nmax,
2900       since new variables will have been set. Note that at the end of this
2901       "lookup" section, the old numeric variables are restored. */
2902
2903       if (skipping)
2904         lookup_value = NULL;
2905       else
2906         {
2907         void *handle = search_open(filename, stype, 0, NULL, NULL);
2908         if (handle == NULL)
2909           {
2910           expand_string_message = search_error_message;
2911           goto EXPAND_FAILED;
2912           }
2913         lookup_value = search_find(handle, filename, key, partial, affix,
2914           affixlen, starflags, &expand_setup);
2915         if (search_find_defer)
2916           {
2917           expand_string_message =
2918             string_sprintf("lookup of \"%s\" gave DEFER: %s", key,
2919               search_error_message);
2920           goto EXPAND_FAILED;
2921           }
2922         if (expand_setup > 0) expand_nmax = expand_setup;
2923         }
2924
2925       /* The handling of "yes" and "no" result strings is now in a separate
2926       function that is also used by ${if} and ${extract}. */
2927
2928       switch(process_yesno(
2929                skipping,                     /* were previously skipping */
2930                lookup_value != NULL,         /* success/failure indicator */
2931                save_lookup_value,            /* value to reset for string2 */
2932                &s,                           /* input pointer */
2933                &yield,                       /* output pointer */
2934                &size,                        /* output size */
2935                &ptr,                         /* output current point */
2936                US"lookup"))                  /* condition type */
2937         {
2938         case 1: goto EXPAND_FAILED;          /* when all is well, the */
2939         case 2: goto EXPAND_FAILED_CURLY;    /* returned value is 0 */
2940         }
2941
2942       /* Restore external setting of expansion variables for carrying on
2943       at this level, and continue. */
2944
2945       restore_expand_strings(save_expand_nmax, save_expand_nstring,
2946         save_expand_nlength);
2947       continue;
2948       }
2949
2950     /* If Perl support is configured, handle calling embedded perl subroutines,
2951     unless locked out at this time. Syntax is ${perl{sub}} or ${perl{sub}{arg}}
2952     or ${perl{sub}{arg1}{arg2}} or up to a maximum of EXIM_PERL_MAX_ARGS
2953     arguments (defined below). */
2954
2955     #ifdef EXIM_PERL
2956     #define EXIM_PERL_MAX_ARGS 8
2957
2958     case EITEM_PERL:
2959       {
2960       uschar *sub_arg[EXIM_PERL_MAX_ARGS + 2];
2961       uschar *new_yield;
2962
2963       if ((expand_forbid & RDO_PERL) != 0)
2964         {
2965         expand_string_message = US"Perl calls are not permitted";
2966         goto EXPAND_FAILED;
2967         }
2968
2969       switch(read_subs(sub_arg, EXIM_PERL_MAX_ARGS + 1, 1, &s, skipping, TRUE,
2970            US"perl"))
2971         {
2972         case 1: goto EXPAND_FAILED_CURLY;
2973         case 2:
2974         case 3: goto EXPAND_FAILED;
2975         }
2976
2977       /* If skipping, we don't actually do anything */
2978
2979       if (skipping) continue;
2980
2981       /* Start the interpreter if necessary */
2982
2983       if (!opt_perl_started)
2984         {
2985         uschar *initerror;
2986         if (opt_perl_startup == NULL)
2987           {
2988           expand_string_message = US"A setting of perl_startup is needed when "
2989             "using the Perl interpreter";
2990           goto EXPAND_FAILED;
2991           }
2992         DEBUG(D_any) debug_printf("Starting Perl interpreter\n");
2993         initerror = init_perl(opt_perl_startup);
2994         if (initerror != NULL)
2995           {
2996           expand_string_message =
2997             string_sprintf("error in perl_startup code: %s\n", initerror);
2998           goto EXPAND_FAILED;
2999           }
3000         opt_perl_started = TRUE;
3001         }
3002
3003       /* Call the function */
3004
3005       sub_arg[EXIM_PERL_MAX_ARGS + 1] = NULL;
3006       new_yield = call_perl_cat(yield, &size, &ptr, &expand_string_message,
3007         sub_arg[0], sub_arg + 1);
3008
3009       /* NULL yield indicates failure; if the message pointer has been set to
3010       NULL, the yield was undef, indicating a forced failure. Otherwise the
3011       message will indicate some kind of Perl error. */
3012
3013       if (new_yield == NULL)
3014         {
3015         if (expand_string_message == NULL)
3016           {
3017           expand_string_message =
3018             string_sprintf("Perl subroutine \"%s\" returned undef to force "
3019               "failure", sub_arg[0]);
3020           expand_string_forcedfail = TRUE;
3021           }
3022         goto EXPAND_FAILED;
3023         }
3024
3025       /* Yield succeeded. Ensure forcedfail is unset, just in case it got
3026       set during a callback from Perl. */
3027
3028       expand_string_forcedfail = FALSE;
3029       yield = new_yield;
3030       continue;
3031       }
3032     #endif /* EXIM_PERL */
3033
3034     /* Handle "readfile" to insert an entire file */
3035
3036     case EITEM_READFILE:
3037       {
3038       FILE *f;
3039       uschar *sub_arg[2];
3040
3041       if ((expand_forbid & RDO_READFILE) != 0)
3042         {
3043         expand_string_message = US"file insertions are not permitted";
3044         goto EXPAND_FAILED;
3045         }
3046
3047       switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"readfile"))
3048         {
3049         case 1: goto EXPAND_FAILED_CURLY;
3050         case 2:
3051         case 3: goto EXPAND_FAILED;
3052         }
3053
3054       /* If skipping, we don't actually do anything */
3055
3056       if (skipping) continue;
3057
3058       /* Open the file and read it */
3059
3060       f = Ufopen(sub_arg[0], "rb");
3061       if (f == NULL)
3062         {
3063         expand_string_message = string_open_failed(errno, "%s", sub_arg[0]);
3064         goto EXPAND_FAILED;
3065         }
3066
3067       yield = cat_file(f, yield, &size, &ptr, sub_arg[1]);
3068       fclose(f);
3069       continue;
3070       }
3071
3072     /* Handle "readsocket" to insert data from a Unix domain socket */
3073
3074     case EITEM_READSOCK:
3075       {
3076       int fd;
3077       int timeout = 5;
3078       int save_ptr = ptr;
3079       FILE *f;
3080       struct sockaddr_un sockun;         /* don't call this "sun" ! */
3081       uschar *arg;
3082       uschar *sub_arg[4];
3083
3084       if ((expand_forbid & RDO_READSOCK) != 0)
3085         {
3086         expand_string_message = US"socket insertions are not permitted";
3087         goto EXPAND_FAILED;
3088         }
3089
3090       /* Read up to 4 arguments, but don't do the end of item check afterwards,
3091       because there may be a string for expansion on failure. */
3092
3093       switch(read_subs(sub_arg, 4, 2, &s, skipping, FALSE, US"readsocket"))
3094         {
3095         case 1: goto EXPAND_FAILED_CURLY;
3096         case 2:                             /* Won't occur: no end check */
3097         case 3: goto EXPAND_FAILED;
3098         }
3099
3100       /* Sort out timeout, if given */
3101
3102       if (sub_arg[2] != NULL)
3103         {
3104         timeout = readconf_readtime(sub_arg[2], 0, FALSE);
3105         if (timeout < 0)
3106           {
3107           expand_string_message = string_sprintf("bad time value %s",
3108             sub_arg[2]);
3109           goto EXPAND_FAILED;
3110           }
3111         }
3112       else sub_arg[3] = NULL;                     /* No eol if no timeout */
3113
3114       /* If skipping, we don't actually do anything */
3115
3116       if (!skipping)
3117         {
3118         /* Make a connection to the socket */
3119
3120         if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
3121           {
3122           expand_string_message = string_sprintf("failed to create socket: %s",
3123             strerror(errno));
3124           goto SOCK_FAIL;
3125           }
3126
3127         sockun.sun_family = AF_UNIX;
3128         sprintf(sockun.sun_path, "%.*s", (int)(sizeof(sockun.sun_path)-1),
3129           sub_arg[0]);
3130         if(connect(fd, (struct sockaddr *)(&sockun), sizeof(sockun)) == -1)
3131           {
3132           expand_string_message = string_sprintf("failed to connect to socket "
3133             "%s: %s", sub_arg[0], strerror(errno));
3134           goto SOCK_FAIL;
3135           }
3136         DEBUG(D_expand) debug_printf("connected to socket %s\n", sub_arg[0]);
3137
3138         /* Write the request string, if not empty */
3139
3140         if (sub_arg[1][0] != 0)
3141           {
3142           int len = Ustrlen(sub_arg[1]);
3143           DEBUG(D_expand) debug_printf("writing \"%s\" to socket\n",
3144             sub_arg[1]);
3145           if (write(fd, sub_arg[1], len) != len)
3146             {
3147             expand_string_message = string_sprintf("request write to socket "
3148               "failed: %s", strerror(errno));
3149             goto SOCK_FAIL;
3150             }
3151           }
3152
3153         /* Now we need to read from the socket, under a timeout. The function
3154         that reads a file can be used. */
3155
3156         f = fdopen(fd, "rb");
3157         sigalrm_seen = FALSE;
3158         alarm(timeout);
3159         yield = cat_file(f, yield, &size, &ptr, sub_arg[3]);
3160         alarm(0);
3161         fclose(f);
3162
3163         /* After a timeout, we restore the pointer in the result, that is,
3164         make sure we add nothing from the socket. */
3165
3166         if (sigalrm_seen)
3167           {
3168           ptr = save_ptr;
3169           expand_string_message = US"socket read timed out";
3170           goto SOCK_FAIL;
3171           }
3172         }
3173
3174       /* The whole thing has worked (or we were skipping). If there is a
3175       failure string following, we need to skip it. */
3176
3177       if (*s == '{')
3178         {
3179         if (expand_string_internal(s+1, TRUE, &s, TRUE) == NULL)
3180           goto EXPAND_FAILED;
3181         if (*s++ != '}') goto EXPAND_FAILED_CURLY;
3182         while (isspace(*s)) s++;
3183         }
3184       if (*s++ != '}') goto EXPAND_FAILED_CURLY;
3185       continue;
3186
3187       /* Come here on failure to create socket, connect socket, write to the
3188       socket, or timeout on reading. If another substring follows, expand and
3189       use it. Otherwise, those conditions give expand errors. */
3190
3191       SOCK_FAIL:
3192       if (*s != '{') goto EXPAND_FAILED;
3193       DEBUG(D_any) debug_printf("%s\n", expand_string_message);
3194       arg = expand_string_internal(s+1, TRUE, &s, FALSE);
3195       if (arg == NULL) goto EXPAND_FAILED;
3196       yield = string_cat(yield, &size, &ptr, arg, Ustrlen(arg));
3197       if (*s++ != '}') goto EXPAND_FAILED_CURLY;
3198       while (isspace(*s)) s++;
3199       if (*s++ != '}') goto EXPAND_FAILED_CURLY;
3200       continue;
3201       }
3202
3203     /* Handle "run" to execute a program. */
3204
3205     case EITEM_RUN:
3206       {
3207       FILE *f;
3208       uschar *old_lookup_value = NULL;
3209       uschar *arg;
3210       uschar **argv;
3211       pid_t pid;
3212       int fd_in, fd_out;
3213       int lsize = 0;
3214       int lptr = 0;
3215
3216       if ((expand_forbid & RDO_RUN) != 0)
3217         {
3218         expand_string_message = US"running a command is not permitted";
3219         goto EXPAND_FAILED;
3220         }
3221
3222       while (isspace(*s)) s++;
3223       if (*s != '{') goto EXPAND_FAILED_CURLY;
3224       arg = expand_string_internal(s+1, TRUE, &s, skipping);
3225       if (arg == NULL) goto EXPAND_FAILED;
3226       while (isspace(*s)) s++;
3227       if (*s++ != '}') goto EXPAND_FAILED_CURLY;
3228
3229       if (skipping)   /* Just pretend it worked when we're skipping */
3230         {
3231         runrc = 0;
3232         }
3233       else
3234         {
3235         if (!transport_set_up_command(&argv,    /* anchor for arg list */
3236             arg,                                /* raw command */
3237             FALSE,                              /* don't expand the arguments */
3238             0,                                  /* not relevant when... */
3239             NULL,                               /* no transporting address */
3240             US"${run} expansion",               /* for error messages */
3241             &expand_string_message))            /* where to put error message */
3242           {
3243           goto EXPAND_FAILED;
3244           }
3245
3246         /* Create the child process, making it a group leader. */
3247
3248         pid = child_open(argv, NULL, 0077, &fd_in, &fd_out, TRUE);
3249
3250         if (pid < 0)
3251           {
3252           expand_string_message =
3253             string_sprintf("couldn't create child process: %s", strerror(errno));
3254           goto EXPAND_FAILED;
3255           }
3256
3257         /* Nothing is written to the standard input. */
3258
3259         close(fd_in);
3260
3261         /* Wait for the process to finish, applying the timeout, and inspect its
3262         return code for serious disasters. Simple non-zero returns are passed on.
3263         */
3264
3265         if ((runrc = child_close(pid, 60)) < 0)
3266           {
3267           if (runrc == -256)
3268             {
3269             expand_string_message = string_sprintf("command timed out");
3270             killpg(pid, SIGKILL);       /* Kill the whole process group */
3271             }
3272
3273           else if (runrc == -257)
3274             expand_string_message = string_sprintf("wait() failed: %s",
3275               strerror(errno));
3276
3277           else
3278             expand_string_message = string_sprintf("command killed by signal %d",
3279               -runrc);
3280
3281           goto EXPAND_FAILED;
3282           }
3283
3284         /* Read the pipe to get the command's output into $value (which is kept
3285         in lookup_value). */
3286
3287         f = fdopen(fd_out, "rb");
3288         old_lookup_value = lookup_value;
3289         lookup_value = NULL;
3290         lookup_value = cat_file(f, lookup_value, &lsize, &lptr, NULL);
3291         fclose(f);
3292         }
3293
3294       /* Process the yes/no strings */
3295
3296       switch(process_yesno(
3297                skipping,                     /* were previously skipping */
3298                runrc == 0,                   /* success/failure indicator */
3299                old_lookup_value,             /* value to reset for string2 */
3300                &s,                           /* input pointer */
3301                &yield,                       /* output pointer */
3302                &size,                        /* output size */
3303                &ptr,                         /* output current point */
3304                US"run"))                     /* condition type */
3305         {
3306         case 1: goto EXPAND_FAILED;          /* when all is well, the */
3307         case 2: goto EXPAND_FAILED_CURLY;    /* returned value is 0 */
3308         }
3309
3310       continue;
3311       }
3312
3313     /* Handle character translation for "tr" */
3314
3315     case EITEM_TR:
3316       {
3317       int oldptr = ptr;
3318       int o2m;
3319       uschar *sub[3];
3320
3321       switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"tr"))
3322         {
3323         case 1: goto EXPAND_FAILED_CURLY;
3324         case 2:
3325         case 3: goto EXPAND_FAILED;
3326         }
3327
3328       yield = string_cat(yield, &size, &ptr, sub[0], Ustrlen(sub[0]));
3329       o2m = Ustrlen(sub[2]) - 1;
3330
3331       if (o2m >= 0) for (; oldptr < ptr; oldptr++)
3332         {
3333         uschar *m = Ustrrchr(sub[1], yield[oldptr]);
3334         if (m != NULL)
3335           {
3336           int o = m - sub[1];
3337           yield[oldptr] = sub[2][(o < o2m)? o : o2m];
3338           }
3339         }
3340
3341       continue;
3342       }
3343
3344     /* Handle "hash", "length", "nhash", and "substr" when they are given with
3345     expanded arguments. */
3346
3347     case EITEM_HASH:
3348     case EITEM_LENGTH:
3349     case EITEM_NHASH:
3350     case EITEM_SUBSTR:
3351       {
3352       int i;
3353       int len;
3354       uschar *ret;
3355       int val[2] = { 0, -1 };
3356       uschar *sub[3];
3357
3358       /* "length" takes only 2 arguments whereas the others take 2 or 3.
3359       Ensure that sub[2] is set in the ${length case. */
3360
3361       sub[2] = NULL;
3362       switch(read_subs(sub, (item_type == EITEM_LENGTH)? 2:3, 2, &s, skipping,
3363              TRUE, name))
3364         {
3365         case 1: goto EXPAND_FAILED_CURLY;
3366         case 2:
3367         case 3: goto EXPAND_FAILED;
3368         }
3369
3370       /* Juggle the arguments if there are only two of them: always move the
3371       string to the last position and make ${length{n}{str}} equivalent to
3372       ${substr{0}{n}{str}}. See the defaults for val[] above. */
3373
3374       if (sub[2] == NULL)
3375         {
3376         sub[2] = sub[1];
3377         sub[1] = NULL;
3378         if (item_type == EITEM_LENGTH)
3379           {
3380           sub[1] = sub[0];
3381           sub[0] = NULL;
3382           }
3383         }
3384
3385       for (i = 0; i < 2; i++)
3386         {
3387         if (sub[i] == NULL) continue;
3388         val[i] = (int)Ustrtol(sub[i], &ret, 10);
3389         if (*ret != 0 || (i != 0 && val[i] < 0))
3390           {
3391           expand_string_message = string_sprintf("\"%s\" is not a%s number "
3392             "(in \"%s\" expansion)", sub[i], (i != 0)? " positive" : "", name);
3393           goto EXPAND_FAILED;
3394           }
3395         }
3396
3397       ret =
3398         (item_type == EITEM_HASH)?
3399           compute_hash(sub[2], val[0], val[1], &len) :
3400         (item_type == EITEM_NHASH)?
3401           compute_nhash(sub[2], val[0], val[1], &len) :
3402           extract_substr(sub[2], val[0], val[1], &len);
3403
3404       if (ret == NULL) goto EXPAND_FAILED;
3405       yield = string_cat(yield, &size, &ptr, ret, len);
3406       continue;
3407       }
3408
3409     /* Handle HMAC computation: ${hmac{<algorithm>}{<secret>}{<text>}}
3410     This code originally contributed by Steve Haslam. It currently supports
3411     the use of MD5 and SHA-1 hashes.
3412
3413     We need some workspace that is large enough to handle all the supported
3414     hash types. Use macros to set the sizes rather than be too elaborate. */
3415
3416     #define MAX_HASHLEN      20
3417     #define MAX_HASHBLOCKLEN 64
3418
3419     case EITEM_HMAC:
3420       {
3421       uschar *sub[3];
3422       md5 md5_base;
3423       sha1 sha1_base;
3424       void *use_base;
3425       int type, i;
3426       int hashlen;      /* Number of octets for the hash algorithm's output */
3427       int hashblocklen; /* Number of octets the hash algorithm processes */
3428       uschar *keyptr, *p;
3429       unsigned int keylen;
3430
3431       uschar keyhash[MAX_HASHLEN];
3432       uschar innerhash[MAX_HASHLEN];
3433       uschar finalhash[MAX_HASHLEN];
3434       uschar finalhash_hex[2*MAX_HASHLEN];
3435       uschar innerkey[MAX_HASHBLOCKLEN];
3436       uschar outerkey[MAX_HASHBLOCKLEN];
3437
3438       switch (read_subs(sub, 3, 3, &s, skipping, TRUE, name))
3439         {
3440         case 1: goto EXPAND_FAILED_CURLY;
3441         case 2:
3442         case 3: goto EXPAND_FAILED;
3443         }
3444
3445       if (Ustrcmp(sub[0], "md5") == 0)
3446         {
3447         type = HMAC_MD5;
3448         use_base = &md5_base;
3449         hashlen = 16;
3450         hashblocklen = 64;
3451         }
3452       else if (Ustrcmp(sub[0], "sha1") == 0)
3453         {
3454         type = HMAC_SHA1;
3455         use_base = &sha1_base;
3456         hashlen = 20;
3457         hashblocklen = 64;
3458         }
3459       else
3460         {
3461         expand_string_message =
3462           string_sprintf("hmac algorithm \"%s\" is not recognised", sub[0]);
3463         goto EXPAND_FAILED;
3464         }
3465
3466       keyptr = sub[1];
3467       keylen = Ustrlen(keyptr);
3468
3469       /* If the key is longer than the hash block length, then hash the key
3470       first */
3471
3472       if (keylen > hashblocklen)
3473         {
3474         chash_start(type, use_base);
3475         chash_end(type, use_base, keyptr, keylen, keyhash);
3476         keyptr = keyhash;
3477         keylen = hashlen;
3478         }
3479
3480       /* Now make the inner and outer key values */
3481
3482       memset(innerkey, 0x36, hashblocklen);
3483       memset(outerkey, 0x5c, hashblocklen);
3484
3485       for (i = 0; i < keylen; i++)
3486         {
3487         innerkey[i] ^= keyptr[i];
3488         outerkey[i] ^= keyptr[i];
3489         }
3490
3491       /* Now do the hashes */
3492
3493       chash_start(type, use_base);
3494       chash_mid(type, use_base, innerkey);
3495       chash_end(type, use_base, sub[2], Ustrlen(sub[2]), innerhash);
3496
3497       chash_start(type, use_base);
3498       chash_mid(type, use_base, outerkey);
3499       chash_end(type, use_base, innerhash, hashlen, finalhash);
3500
3501       /* Encode the final hash as a hex string */
3502
3503       p = finalhash_hex;
3504       for (i = 0; i < hashlen; i++)
3505         {
3506         *p++ = hex_digits[(finalhash[i] & 0xf0) >> 4];
3507         *p++ = hex_digits[finalhash[i] & 0x0f];
3508         }
3509
3510       DEBUG(D_any) debug_printf("HMAC[%s](%.*s,%.*s)=%.*s\n", sub[0],
3511         (int)keylen, keyptr, Ustrlen(sub[2]), sub[2], hashlen*2, finalhash_hex);
3512
3513       yield = string_cat(yield, &size, &ptr, finalhash_hex, hashlen*2);
3514       }
3515
3516     continue;
3517
3518     /* Handle global substitution for "sg" - like Perl's s/xxx/yyy/g operator.
3519     We have to save the numerical variables and restore them afterwards. */
3520
3521     case EITEM_SG:
3522       {
3523       const pcre *re;
3524       int moffset, moffsetextra, slen;
3525       int roffset;
3526       int emptyopt;
3527       const uschar *rerror;
3528       uschar *subject;
3529       uschar *sub[3];
3530       int save_expand_nmax =
3531         save_expand_strings(save_expand_nstring, save_expand_nlength);
3532
3533       switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"sg"))
3534         {
3535         case 1: goto EXPAND_FAILED_CURLY;
3536         case 2:
3537         case 3: goto EXPAND_FAILED;
3538         }
3539
3540       /* Compile the regular expression */
3541
3542       re = pcre_compile(CS sub[1], PCRE_COPT, (const char **)&rerror, &roffset,
3543         NULL);
3544
3545       if (re == NULL)
3546         {
3547         expand_string_message = string_sprintf("regular expression error in "
3548           "\"%s\": %s at offset %d", sub[1], rerror, roffset);
3549         goto EXPAND_FAILED;
3550         }
3551
3552       /* Now run a loop to do the substitutions as often as necessary. It ends
3553       when there are no more matches. Take care over matches of the null string;
3554       do the same thing as Perl does. */
3555
3556       subject = sub[0];
3557       slen = Ustrlen(sub[0]);
3558       moffset = moffsetextra = 0;
3559       emptyopt = 0;
3560
3561       for (;;)
3562         {
3563         int ovector[3*(EXPAND_MAXN+1)];
3564         int n = pcre_exec(re, NULL, CS subject, slen, moffset + moffsetextra,
3565           PCRE_EOPT | emptyopt, ovector, sizeof(ovector)/sizeof(int));
3566         int nn;
3567         uschar *insert;
3568
3569         /* No match - if we previously set PCRE_NOTEMPTY after a null match, this
3570         is not necessarily the end. We want to repeat the match from one
3571         character further along, but leaving the basic offset the same (for
3572         copying below). We can't be at the end of the string - that was checked
3573         before setting PCRE_NOTEMPTY. If PCRE_NOTEMPTY is not set, we are
3574         finished; copy the remaining string and end the loop. */
3575
3576         if (n < 0)
3577           {
3578           if (emptyopt != 0)
3579             {
3580             moffsetextra = 1;
3581             emptyopt = 0;
3582             continue;
3583             }
3584           yield = string_cat(yield, &size, &ptr, subject+moffset, slen-moffset);
3585           break;
3586           }
3587
3588         /* Match - set up for expanding the replacement. */
3589
3590         if (n == 0) n = EXPAND_MAXN + 1;
3591         expand_nmax = 0;
3592         for (nn = 0; nn < n*2; nn += 2)
3593           {
3594           expand_nstring[expand_nmax] = subject + ovector[nn];
3595           expand_nlength[expand_nmax++] = ovector[nn+1] - ovector[nn];
3596           }
3597         expand_nmax--;
3598
3599         /* Copy the characters before the match, plus the expanded insertion. */
3600
3601         yield = string_cat(yield, &size, &ptr, subject + moffset,
3602           ovector[0] - moffset);
3603         insert = expand_string(sub[2]);
3604         if (insert == NULL) goto EXPAND_FAILED;
3605         yield = string_cat(yield, &size, &ptr, insert, Ustrlen(insert));
3606
3607         moffset = ovector[1];
3608         moffsetextra = 0;
3609         emptyopt = 0;
3610
3611         /* If we have matched an empty string, first check to see if we are at
3612         the end of the subject. If so, the loop is over. Otherwise, mimic
3613         what Perl's /g options does. This turns out to be rather cunning. First
3614         we set PCRE_NOTEMPTY and PCRE_ANCHORED and try the match a non-empty
3615         string at the same point. If this fails (picked up above) we advance to
3616         the next character. */
3617
3618         if (ovector[0] == ovector[1])
3619           {
3620           if (ovector[0] == slen) break;
3621           emptyopt = PCRE_NOTEMPTY | PCRE_ANCHORED;
3622           }
3623         }
3624
3625       /* All done - restore numerical variables. */
3626
3627       restore_expand_strings(save_expand_nmax, save_expand_nstring,
3628         save_expand_nlength);
3629       continue;
3630       }
3631
3632     /* Handle keyed and numbered substring extraction. If the first argument
3633     consists entirely of digits, then a numerical extraction is assumed. */
3634
3635     case EITEM_EXTRACT:
3636       {
3637       int i;
3638       int j = 2;
3639       int field_number = 1;
3640       BOOL field_number_set = FALSE;
3641       uschar *save_lookup_value = lookup_value;
3642       uschar *sub[3];
3643       int save_expand_nmax =
3644         save_expand_strings(save_expand_nstring, save_expand_nlength);
3645
3646       /* Read the arguments */
3647
3648       for (i = 0; i < j; i++)
3649         {
3650         while (isspace(*s)) s++;
3651         if (*s == '{')
3652           {
3653           sub[i] = expand_string_internal(s+1, TRUE, &s, skipping);
3654           if (sub[i] == NULL) goto EXPAND_FAILED;
3655           if (*s++ != '}') goto EXPAND_FAILED_CURLY;
3656
3657           /* After removal of leading and trailing white space, the first
3658           argument must not be empty; if it consists entirely of digits
3659           (optionally preceded by a minus sign), this is a numerical
3660           extraction, and we expect 3 arguments. */
3661
3662           if (i == 0)
3663             {
3664             int len;
3665             int x = 0;
3666             uschar *p = sub[0];
3667
3668             while (isspace(*p)) p++;
3669             sub[0] = p;
3670
3671             len = Ustrlen(p);
3672             while (len > 0 && isspace(p[len-1])) len--;
3673             p[len] = 0;
3674
3675             if (*p == 0)
3676               {
3677               expand_string_message = US"first argument of \"expand\" must not "
3678                 "be empty";
3679               goto EXPAND_FAILED;
3680               }
3681
3682             if (*p == '-')
3683               {
3684               field_number = -1;
3685               p++;
3686               }
3687             while (*p != 0 && isdigit(*p)) x = x * 10 + *p++ - '0';
3688             if (*p == 0)
3689               {
3690               field_number *= x;
3691               j = 3;               /* Need 3 args */
3692               field_number_set = TRUE;
3693               }
3694             }
3695           }
3696         else goto EXPAND_FAILED_CURLY;
3697         }
3698
3699       /* Extract either the numbered or the keyed substring into $value. If
3700       skipping, just pretend the extraction failed. */
3701
3702       lookup_value = skipping? NULL : field_number_set?
3703         expand_gettokened(field_number, sub[1], sub[2]) :
3704         expand_getkeyed(sub[0], sub[1]);
3705
3706       /* If no string follows, $value gets substituted; otherwise there can
3707       be yes/no strings, as for lookup or if. */
3708
3709       switch(process_yesno(
3710                skipping,                     /* were previously skipping */
3711                lookup_value != NULL,         /* success/failure indicator */
3712                save_lookup_value,            /* value to reset for string2 */
3713                &s,                           /* input pointer */
3714                &yield,                       /* output pointer */
3715                &size,                        /* output size */
3716                &ptr,                         /* output current point */
3717                US"extract"))                 /* condition type */
3718         {
3719         case 1: goto EXPAND_FAILED;          /* when all is well, the */
3720         case 2: goto EXPAND_FAILED_CURLY;    /* returned value is 0 */
3721         }
3722
3723       /* All done - restore numerical variables. */
3724
3725       restore_expand_strings(save_expand_nmax, save_expand_nstring,
3726         save_expand_nlength);
3727
3728       continue;
3729       }
3730     }
3731
3732   /* Control reaches here if the name is not recognized as one of the more
3733   complicated expansion items. Check for the "operator" syntax (name terminated
3734   by a colon). Some of the operators have arguments, separated by _ from the
3735   name. */
3736
3737   if (*s == ':')
3738     {
3739     int c;
3740     uschar *arg = NULL;
3741     uschar *sub = expand_string_internal(s+1, TRUE, &s, skipping);
3742     if (sub == NULL) goto EXPAND_FAILED;
3743     s++;
3744
3745     /* Owing to an historical mis-design, an underscore may be part of the
3746     operator name, or it may introduce arguments.  We therefore first scan the
3747     table of names that contain underscores. If there is no match, we cut off
3748     the arguments and then scan the main table. */
3749
3750     c = chop_match(name, op_table_underscore,
3751       sizeof(op_table_underscore)/sizeof(uschar *));
3752
3753     if (c < 0)
3754       {
3755       arg = Ustrchr(name, '_');
3756       if (arg != NULL) *arg = 0;
3757       c = chop_match(name, op_table_main,
3758         sizeof(op_table_main)/sizeof(uschar *));
3759       if (c >= 0) c += sizeof(op_table_underscore)/sizeof(uschar *);
3760       if (arg != NULL) *arg++ = '_';   /* Put back for error messages */
3761       }
3762
3763     /* If we are skipping, we don't need to perform the operation at all.
3764     This matters for operations like "mask", because the data may not be
3765     in the correct format when skipping. For example, the expression may test
3766     for the existence of $sender_host_address before trying to mask it. For
3767     other operations, doing them may not fail, but it is a waste of time. */
3768
3769     if (skipping && c >= 0) continue;
3770
3771     /* Otherwise, switch on the operator type */
3772
3773     switch(c)
3774       {
3775       case EOP_BASE62:
3776         {
3777         uschar *t;
3778         unsigned long int n = Ustrtoul(sub, &t, 10);
3779         if (*t != 0)
3780           {
3781           expand_string_message = string_sprintf("argument for base62 "
3782             "operator is \"%s\", which is not a decimal number", sub);
3783           goto EXPAND_FAILED;
3784           }
3785         t = string_base62(n);
3786         yield = string_cat(yield, &size, &ptr, t, Ustrlen(t));
3787         continue;
3788         }
3789
3790       case EOP_BASE62D:
3791         {
3792         uschar buf[16];
3793         uschar *tt = sub;
3794         unsigned long int n = 0;
3795         while (*tt != 0)
3796           {
3797           uschar *t = Ustrchr(base62_chars, *tt++);
3798           if (t == NULL)
3799             {
3800             expand_string_message = string_sprintf("argument for base62d "
3801               "operator is \"%s\", which is not a base 62 number", sub);
3802             goto EXPAND_FAILED;
3803             }
3804           n = n * 62 + (t - base62_chars);
3805           }
3806         (void)sprintf(CS buf, "%ld", n);
3807         yield = string_cat(yield, &size, &ptr, buf, Ustrlen(buf));
3808         continue;
3809         }
3810
3811       case EOP_EXPAND:
3812         {
3813         uschar *expanded = expand_string_internal(sub, FALSE, NULL, skipping);
3814         if (expanded == NULL)
3815           {
3816           expand_string_message =
3817             string_sprintf("internal expansion of \"%s\" failed: %s", sub,
3818               expand_string_message);
3819           goto EXPAND_FAILED;
3820           }
3821         yield = string_cat(yield, &size, &ptr, expanded, Ustrlen(expanded));
3822         continue;
3823         }
3824
3825       case EOP_LC:
3826         {
3827         int count = 0;
3828         uschar *t = sub - 1;
3829         while (*(++t) != 0) { *t = tolower(*t); count++; }
3830         yield = string_cat(yield, &size, &ptr, sub, count);
3831         continue;
3832         }
3833
3834       case EOP_UC:
3835         {
3836         int count = 0;
3837         uschar *t = sub - 1;
3838         while (*(++t) != 0) { *t = toupper(*t); count++; }
3839         yield = string_cat(yield, &size, &ptr, sub, count);
3840         continue;
3841         }
3842
3843       case EOP_MD5:
3844         {
3845         md5 base;
3846         uschar digest[16];
3847         int j;
3848         char st[33];
3849         md5_start(&base);
3850         md5_end(&base, sub, Ustrlen(sub), digest);
3851         for(j = 0; j < 16; j++) sprintf(st+2*j, "%02x", digest[j]);
3852         yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st));
3853         continue;
3854         }
3855
3856       case EOP_SHA1:
3857         {
3858         sha1 base;
3859         uschar digest[20];
3860         int j;
3861         char st[41];
3862         sha1_start(&base);
3863         sha1_end(&base, sub, Ustrlen(sub), digest);
3864         for(j = 0; j < 20; j++) sprintf(st+2*j, "%02X", digest[j]);
3865         yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st));
3866         continue;
3867         }
3868
3869       /* Convert hex encoding to base64 encoding */
3870
3871       case EOP_HEX2B64:
3872         {
3873         int c = 0;
3874         int b = -1;
3875         uschar *in = sub;
3876         uschar *out = sub;
3877         uschar *enc;
3878
3879         for (enc = sub; *enc != 0; enc++)
3880           {
3881           if (!isxdigit(*enc))
3882             {
3883             expand_string_message = string_sprintf("\"%s\" is not a hex "
3884               "string", sub);
3885             goto EXPAND_FAILED;
3886             }
3887           c++;
3888           }
3889
3890         if ((c & 1) != 0)
3891           {
3892           expand_string_message = string_sprintf("\"%s\" contains an odd "
3893             "number of characters", sub);
3894           goto EXPAND_FAILED;
3895           }
3896
3897         while ((c = *in++) != 0)
3898           {
3899           if (isdigit(c)) c -= '0';
3900           else c = toupper(c) - 'A' + 10;
3901           if (b == -1)
3902             {
3903             b = c << 4;
3904             }
3905           else
3906             {
3907             *out++ = b | c;
3908             b = -1;
3909             }
3910           }
3911
3912         enc = auth_b64encode(sub, out - sub);
3913         yield = string_cat(yield, &size, &ptr, enc, Ustrlen(enc));
3914         continue;
3915         }
3916
3917       /* mask applies a mask to an IP address; for example the result of
3918       ${mask:131.111.10.206/28} is 131.111.10.192/28. */
3919
3920       case EOP_MASK:
3921         {
3922         int count;
3923         uschar *endptr;
3924         int binary[4];
3925         int mask, maskoffset;
3926         int type = string_is_ip_address(sub, &maskoffset);
3927         uschar buffer[64];
3928
3929         if (type == 0)
3930           {
3931           expand_string_message = string_sprintf("\"%s\" is not an IP address",
3932            sub);
3933           goto EXPAND_FAILED;
3934           }
3935
3936         if (maskoffset == 0)
3937           {
3938           expand_string_message = string_sprintf("missing mask value in \"%s\"",
3939             sub);
3940           goto EXPAND_FAILED;
3941           }
3942
3943         mask = Ustrtol(sub + maskoffset + 1, &endptr, 10);
3944
3945         if (*endptr != 0 || mask < 0 || mask > ((type == 4)? 32 : 128))
3946           {
3947           expand_string_message = string_sprintf("mask value too big in \"%s\"",
3948             sub);
3949           goto EXPAND_FAILED;
3950           }
3951
3952         /* Convert the address to binary integer(s) and apply the mask */
3953
3954         sub[maskoffset] = 0;
3955         count = host_aton(sub, binary);
3956         host_mask(count, binary, mask);
3957
3958         /* Convert to masked textual format and add to output. */
3959
3960         yield = string_cat(yield, &size, &ptr, buffer,
3961           host_nmtoa(count, binary, mask, buffer, '.'));
3962         continue;
3963         }
3964
3965       case EOP_ADDRESS:
3966       case EOP_LOCAL_PART:
3967       case EOP_DOMAIN:
3968         {
3969         uschar *error;
3970         int start, end, domain;
3971         uschar *t = parse_extract_address(sub, &error, &start, &end, &domain,
3972           FALSE);
3973         if (t != NULL)
3974           {
3975           if (c != EOP_DOMAIN)
3976             {
3977             if (c == EOP_LOCAL_PART && domain != 0) end = start + domain - 1;
3978             yield = string_cat(yield, &size, &ptr, sub+start, end-start);
3979             }
3980           else if (domain != 0)
3981             {
3982             domain += start;
3983             yield = string_cat(yield, &size, &ptr, sub+domain, end-domain);
3984             }
3985           }
3986         continue;
3987         }
3988
3989       /* quote puts a string in quotes if it is empty or contains anything
3990       other than alphamerics, underscore, dot, or hyphen.
3991
3992       quote_local_part puts a string in quotes if RFC 2821/2822 requires it to
3993       be quoted in order to be a valid local part.
3994
3995       In both cases, newlines and carriage returns are converted into \n and \r
3996       respectively */
3997
3998       case EOP_QUOTE:
3999       case EOP_QUOTE_LOCAL_PART:
4000       if (arg == NULL)
4001         {
4002         BOOL needs_quote = (*sub == 0);      /* TRUE for empty string */
4003         uschar *t = sub - 1;
4004
4005         if (c == EOP_QUOTE)
4006           {
4007           while (!needs_quote && *(++t) != 0)
4008             needs_quote = !isalnum(*t) && !strchr("_-.", *t);
4009           }
4010         else  /* EOP_QUOTE_LOCAL_PART */
4011           {
4012           while (!needs_quote && *(++t) != 0)
4013             needs_quote = !isalnum(*t) &&
4014               strchr("!#$%&'*+-/=?^_`{|}~", *t) == NULL &&
4015               (*t != '.' || t == sub || t[1] == 0);
4016           }
4017
4018         if (needs_quote)
4019           {
4020           yield = string_cat(yield, &size, &ptr, US"\"", 1);
4021           t = sub - 1;
4022           while (*(++t) != 0)
4023             {
4024             if (*t == '\n')
4025               yield = string_cat(yield, &size, &ptr, US"\\n", 2);
4026             else if (*t == '\r')
4027               yield = string_cat(yield, &size, &ptr, US"\\r", 2);
4028             else
4029               {
4030               if (*t == '\\' || *t == '"')
4031                 yield = string_cat(yield, &size, &ptr, US"\\", 1);
4032               yield = string_cat(yield, &size, &ptr, t, 1);
4033               }
4034             }
4035           yield = string_cat(yield, &size, &ptr, US"\"", 1);
4036           }
4037         else yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub));
4038         continue;
4039         }
4040
4041       /* quote_lookuptype does lookup-specific quoting */
4042
4043       else
4044         {
4045         int n;
4046         uschar *opt = Ustrchr(arg, '_');
4047
4048         if (opt != NULL) *opt++ = 0;
4049
4050         n = search_findtype(arg, Ustrlen(arg));
4051         if (n < 0)
4052           {
4053           expand_string_message = search_error_message;
4054           goto EXPAND_FAILED;
4055           }
4056
4057         if (lookup_list[n].quote != NULL)
4058           sub = (lookup_list[n].quote)(sub, opt);
4059         else if (opt != NULL) sub = NULL;
4060
4061         if (sub == NULL)
4062           {
4063           expand_string_message = string_sprintf(
4064             "\"%s\" unrecognized after \"${quote_%s\"",
4065             opt, arg);
4066           goto EXPAND_FAILED;
4067           }
4068
4069         yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub));
4070         continue;
4071         }
4072
4073       /* rx quote sticks in \ before any non-alphameric character so that
4074       the insertion works in a regular expression. */
4075
4076       case EOP_RXQUOTE:
4077         {
4078         uschar *t = sub - 1;
4079         while (*(++t) != 0)
4080           {
4081           if (!isalnum(*t))
4082             yield = string_cat(yield, &size, &ptr, US"\\", 1);
4083           yield = string_cat(yield, &size, &ptr, t, 1);
4084           }
4085         continue;
4086         }
4087
4088       /* RFC 2047 encodes, assuming headers_charset (default ISO 8859-1) as
4089       prescribed by the RFC, if there are characters that need to be encoded */
4090
4091       case EOP_RFC2047:
4092         {
4093         uschar buffer[2048];
4094         uschar *string = parse_quote_2047(sub, Ustrlen(sub), headers_charset,
4095           buffer, sizeof(buffer));
4096         yield = string_cat(yield, &size, &ptr, string, Ustrlen(string));
4097         continue;
4098         }
4099
4100       /* from_utf8 converts UTF-8 to 8859-1, turning non-existent chars into
4101       underscores */
4102
4103       case EOP_FROM_UTF8:
4104         {
4105         while (*sub != 0)
4106           {
4107           int c;
4108           uschar buff[4];
4109           GETUTF8INC(c, sub);
4110           if (c > 255) c = '_';
4111           buff[0] = c;
4112           yield = string_cat(yield, &size, &ptr, buff, 1);
4113           }
4114         continue;
4115         }
4116
4117       /* escape turns all non-printing characters into escape sequences. */
4118
4119       case EOP_ESCAPE:
4120         {
4121         uschar *t = string_printing(sub);
4122         yield = string_cat(yield, &size, &ptr, t, Ustrlen(t));
4123         continue;
4124         }
4125
4126       /* Handle numeric expression evaluation */
4127
4128       case EOP_EVAL:
4129       case EOP_EVAL10:
4130         {
4131         uschar *save_sub = sub;
4132         uschar *error = NULL;
4133         int n = eval_expr(&sub, (c == EOP_EVAL10), &error, FALSE);
4134         if (error != NULL)
4135           {
4136           expand_string_message = string_sprintf("error in expression "
4137             "evaluation: %s (after processing \"%.*s\")", error, sub-save_sub,
4138               save_sub);
4139           goto EXPAND_FAILED;
4140           }
4141         sprintf(CS var_buffer, "%d", n);
4142         yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer));
4143         continue;
4144         }
4145
4146       /* Handle time period formating */
4147
4148       case EOP_TIME_INTERVAL:
4149         {
4150         int n;
4151         uschar *t = read_number(&n, sub);
4152         if (*t != 0) /* Not A Number*/
4153           {
4154           expand_string_message = string_sprintf("string \"%s\" is not a "
4155             "positive number in \"%s\" operator", sub, name);
4156           goto EXPAND_FAILED;
4157           }
4158         t = readconf_printtime(n);
4159         yield = string_cat(yield, &size, &ptr, t, Ustrlen(t));
4160         continue;
4161         }
4162
4163       /* Convert string to base64 encoding */
4164
4165       case EOP_STR2B64:
4166         {
4167         uschar *encstr = auth_b64encode(sub, Ustrlen(sub));
4168         yield = string_cat(yield, &size, &ptr, encstr, Ustrlen(encstr));
4169         continue;
4170         }
4171
4172       /* strlen returns the length of the string */
4173
4174       case EOP_STRLEN:
4175         {
4176         uschar buff[24];
4177         (void)sprintf(CS buff, "%d", Ustrlen(sub));
4178         yield = string_cat(yield, &size, &ptr, buff, Ustrlen(buff));
4179         continue;
4180         }
4181
4182       /* length_n or l_n takes just the first n characters or the whole string,
4183       whichever is the shorter;
4184
4185       substr_m_n, and s_m_n take n characters from offset m; negative m take
4186       from the end; l_n is synonymous with s_0_n. If n is omitted in substr it
4187       takes the rest, either to the right or to the left.
4188
4189       hash_n or h_n makes a hash of length n from the string, yielding n
4190       characters from the set a-z; hash_n_m makes a hash of length n, but
4191       uses m characters from the set a-zA-Z0-9.
4192
4193       nhash_n returns a single number between 0 and n-1 (in text form), while
4194       nhash_n_m returns a div/mod hash as two numbers "a/b". The first lies
4195       between 0 and n-1 and the second between 0 and m-1. */
4196
4197       case EOP_LENGTH:
4198       case EOP_L:
4199       case EOP_SUBSTR:
4200       case EOP_S:
4201       case EOP_HASH:
4202       case EOP_H:
4203       case EOP_NHASH:
4204       case EOP_NH:
4205         {
4206         int sign = 1;
4207         int value1 = 0;
4208         int value2 = -1;
4209         int *pn;
4210         int len;
4211         uschar *ret;
4212
4213         if (arg == NULL)
4214           {
4215           expand_string_message = string_sprintf("missing values after %s",
4216             name);
4217           goto EXPAND_FAILED;
4218           }
4219
4220         /* "length" has only one argument, effectively being synonymous with
4221         substr_0_n. */
4222
4223         if (c == EOP_LENGTH || c == EOP_L)
4224           {
4225           pn = &value2;
4226           value2 = 0;
4227           }
4228
4229         /* The others have one or two arguments; for "substr" the first may be
4230         negative. The second being negative means "not supplied". */
4231
4232         else
4233           {
4234           pn = &value1;
4235           if (name[0] == 's' && *arg == '-') { sign = -1; arg++; }
4236           }
4237
4238         /* Read up to two numbers, separated by underscores */
4239
4240         ret = arg;
4241         while (*arg != 0)
4242           {
4243           if (arg != ret && *arg == '_' && pn == &value1)
4244             {
4245             pn = &value2;
4246             value2 = 0;
4247             if (arg[1] != 0) arg++;
4248             }
4249           else if (!isdigit(*arg))
4250             {
4251             expand_string_message =
4252               string_sprintf("non-digit after underscore in \"%s\"", name);
4253             goto EXPAND_FAILED;
4254             }
4255           else *pn = (*pn)*10 + *arg++ - '0';
4256           }
4257         value1 *= sign;
4258
4259         /* Perform the required operation */
4260
4261         ret =
4262           (c == EOP_HASH || c == EOP_H)?
4263              compute_hash(sub, value1, value2, &len) :
4264           (c == EOP_NHASH || c == EOP_NH)?
4265              compute_nhash(sub, value1, value2, &len) :
4266              extract_substr(sub, value1, value2, &len);
4267
4268         if (ret == NULL) goto EXPAND_FAILED;
4269         yield = string_cat(yield, &size, &ptr, ret, len);
4270         continue;
4271         }
4272
4273       /* Stat a path */
4274
4275       case EOP_STAT:
4276         {
4277         uschar *s;
4278         uschar smode[12];
4279         uschar **modetable[3];
4280         int i;
4281         mode_t mode;
4282         struct stat st;
4283
4284         if (stat(CS sub, &st) < 0)
4285           {
4286           expand_string_message = string_sprintf("stat(%s) failed: %s",
4287             sub, strerror(errno));
4288           goto EXPAND_FAILED;
4289           }
4290         mode = st.st_mode;
4291         switch (mode & S_IFMT)
4292           {
4293           case S_IFIFO: smode[0] = 'p'; break;
4294           case S_IFCHR: smode[0] = 'c'; break;
4295           case S_IFDIR: smode[0] = 'd'; break;
4296           case S_IFBLK: smode[0] = 'b'; break;
4297           case S_IFREG: smode[0] = '-'; break;
4298           default: smode[0] = '?'; break;
4299           }
4300
4301         modetable[0] = ((mode & 01000) == 0)? mtable_normal : mtable_sticky;
4302         modetable[1] = ((mode & 02000) == 0)? mtable_normal : mtable_setid;
4303         modetable[2] = ((mode & 04000) == 0)? mtable_normal : mtable_setid;
4304
4305         for (i = 0; i < 3; i++)
4306           {
4307           memcpy(CS(smode + 7 - i*3), CS(modetable[i][mode & 7]), 3);
4308           mode >>= 3;
4309           }
4310
4311         smode[10] = 0;
4312         s = string_sprintf("mode=%04lo smode=%s inode=%ld device=%ld links=%ld "
4313           "uid=%ld gid=%ld size=%ld atime=%ld mtime=%ld ctime=%ld",
4314           (long)(st.st_mode & 077777), smode, (long)st.st_ino,
4315           (long)st.st_dev, (long)st.st_nlink, (long)st.st_uid,
4316           (long)st.st_gid, (long)st.st_size, (long)st.st_atime,
4317           (long)st.st_mtime, (long)st.st_ctime);
4318         yield = string_cat(yield, &size, &ptr, s, Ustrlen(s));
4319         continue;
4320         }
4321
4322       /* Unknown operator */
4323
4324       default:
4325       expand_string_message =
4326         string_sprintf("unknown expansion operator \"%s\"", name);
4327       goto EXPAND_FAILED;
4328       }
4329     }
4330
4331   /* Handle a plain name. If this is the first thing in the expansion, release
4332   the pre-allocated buffer. If the result data is known to be in a new buffer,
4333   newsize will be set to the size of that buffer, and we can just point at that
4334   store instead of copying. Many expansion strings contain just one reference,
4335   so this is a useful optimization, especially for humungous headers
4336   ($message_headers). */
4337
4338   if (*s++ == '}')
4339     {
4340     int len;
4341     int newsize = 0;
4342     if (ptr == 0)
4343       {
4344       store_reset(yield);
4345       yield = NULL;
4346       size = 0;
4347       }
4348     value = find_variable(name, FALSE, skipping, &newsize);
4349     if (value == NULL)
4350       {
4351       expand_string_message =
4352         string_sprintf("unknown variable in \"${%s}\"", name);
4353       goto EXPAND_FAILED;
4354       }
4355     len = Ustrlen(value);
4356     if (yield == NULL && newsize != 0)
4357       {
4358       yield = value;
4359       size = newsize;
4360       ptr = len;
4361       }
4362     else yield = string_cat(yield, &size, &ptr, value, len);
4363     continue;
4364     }
4365
4366   /* Else there's something wrong */
4367
4368   expand_string_message =
4369     string_sprintf("\"${%s\" is not a known operator (or a } is missing "
4370     "in a variable reference)", name);
4371   goto EXPAND_FAILED;
4372   }
4373
4374 /* If we hit the end of the string when ket_ends is set, there is a missing
4375 terminating brace. */
4376
4377 if (ket_ends && *s == 0)
4378   {
4379   expand_string_message = malformed_header?
4380     US"missing } at end of string - could be header name not terminated by colon"
4381     :
4382     US"missing } at end of string";
4383   goto EXPAND_FAILED;
4384   }
4385
4386 /* Expansion succeeded; yield may still be NULL here if nothing was actually
4387 added to the string. If so, set up an empty string. Add a terminating zero. If
4388 left != NULL, return a pointer to the terminator. */
4389
4390 if (yield == NULL) yield = store_get(1);
4391 yield[ptr] = 0;
4392 if (left != NULL) *left = s;
4393
4394 /* Any stacking store that was used above the final string is no longer needed.
4395 In many cases the final string will be the first one that was got and so there
4396 will be optimal store usage. */
4397
4398 store_reset(yield + ptr + 1);
4399 DEBUG(D_expand)
4400   {
4401   debug_printf("expanding: %.*s\n   result: %s\n", (int)(s - string), string,
4402     yield);
4403   if (skipping) debug_printf("skipping: result is not used\n");
4404   }
4405 return yield;
4406
4407 /* This is the failure exit: easiest to program with a goto. We still need
4408 to update the pointer to the terminator, for cases of nested calls with "fail".
4409 */
4410
4411 EXPAND_FAILED_CURLY:
4412 expand_string_message = malformed_header?
4413   US"missing or misplaced { or } - could be header name not terminated by colon"
4414   :
4415   US"missing or misplaced { or }";
4416
4417 /* At one point, Exim reset the store to yield (if yield was not NULL), but
4418 that is a bad idea, because expand_string_message is in dynamic store. */
4419
4420 EXPAND_FAILED:
4421 if (left != NULL) *left = s;
4422 DEBUG(D_expand)
4423   {
4424   debug_printf("failed to expand: %s\n", string);
4425   debug_printf("   error message: %s\n", expand_string_message);
4426   if (expand_string_forcedfail) debug_printf("failure was forced\n");
4427   }
4428 return NULL;
4429 }
4430
4431
4432 /* This is the external function call. Do a quick check for any expansion
4433 metacharacters, and if there are none, just return the input string.
4434
4435 Argument: the string to be expanded
4436 Returns:  the expanded string, or NULL if expansion failed; if failure was
4437           due to a lookup deferring, search_find_defer will be TRUE
4438 */
4439
4440 uschar *
4441 expand_string(uschar *string)
4442 {
4443 search_find_defer = FALSE;
4444 malformed_header = FALSE;
4445 return (Ustrpbrk(string, "$\\") == NULL)? string :
4446   expand_string_internal(string, FALSE, NULL, FALSE);
4447 }
4448
4449
4450
4451 /*************************************************
4452 *              Expand and copy                   *
4453 *************************************************/
4454
4455 /* Now and again we want to expand a string and be sure that the result is in a
4456 new bit of store. This function does that.
4457
4458 Argument: the string to be expanded
4459 Returns:  the expanded string, always in a new bit of store, or NULL
4460 */
4461
4462 uschar *
4463 expand_string_copy(uschar *string)
4464 {
4465 uschar *yield = expand_string(string);
4466 if (yield == string) yield = string_copy(string);
4467 return yield;
4468 }
4469
4470
4471
4472 /*************************************************
4473 *        Expand and interpret as an integer      *
4474 *************************************************/
4475
4476 /* Expand a string, and convert the result into an integer.
4477
4478 Argument: the string to be expanded
4479
4480 Returns:  the integer value, or
4481           -1 for an expansion error               ) in both cases, message in
4482           -2 for an integer interpretation error  ) expand_string_message
4483
4484 */
4485
4486 int
4487 expand_string_integer(uschar *string)
4488 {
4489 long int value;
4490 uschar *s = expand_string(string);
4491 uschar *msg = US"invalid integer \"%s\"";
4492 uschar *endptr;
4493
4494 if (s == NULL) return -1;
4495
4496 /* On an overflow, strtol() returns LONG_MAX or LONG_MIN, and sets errno
4497 to ERANGE. When there isn't an overflow, errno is not changed, at least on some
4498 systems, so we set it zero ourselves. */
4499
4500 errno = 0;
4501 value = strtol(CS s, CSS &endptr, 0);
4502
4503 if (endptr == s)
4504   {
4505   msg = US"integer expected but \"%s\" found";
4506   }
4507 else
4508   {
4509   /* Ensure we can cast this down to an int */
4510   if (value > INT_MAX  || value < INT_MIN) errno = ERANGE;
4511
4512   if (errno != ERANGE)
4513     {
4514     if (tolower(*endptr) == 'k')
4515       {
4516       if (value > INT_MAX/1024 || value < INT_MIN/1024) errno = ERANGE;
4517         else value *= 1024;
4518       endptr++;
4519       }
4520     else if (tolower(*endptr) == 'm')
4521       {
4522       if (value > INT_MAX/(1024*1024) || value < INT_MIN/(1024*1024))
4523         errno = ERANGE;
4524       else value *= 1024*1024;
4525       endptr++;
4526       }
4527     }
4528   if (errno == ERANGE)
4529     msg = US"absolute value of integer \"%s\" is too large (overflow)";
4530   else
4531     {
4532     while (isspace(*endptr)) endptr++;
4533     if (*endptr == 0) return (int)value;
4534     }
4535   }
4536
4537 expand_string_message = string_sprintf(CS msg, s);
4538 return -2;
4539 }
4540
4541
4542
4543 /*************************************************
4544 **************************************************
4545 *             Stand-alone test program           *
4546 **************************************************
4547 *************************************************/
4548
4549 #ifdef STAND_ALONE
4550
4551
4552 BOOL
4553 regex_match_and_setup(const pcre *re, uschar *subject, int options, int setup)
4554 {
4555 int ovector[3*(EXPAND_MAXN+1)];
4556 int n = pcre_exec(re, NULL, subject, Ustrlen(subject), 0, PCRE_EOPT|options,
4557   ovector, sizeof(ovector)/sizeof(int));
4558 BOOL yield = n >= 0;
4559 if (n == 0) n = EXPAND_MAXN + 1;
4560 if (yield)
4561   {
4562   int nn;
4563   expand_nmax = (setup < 0)? 0 : setup + 1;
4564   for (nn = (setup < 0)? 0 : 2; nn < n*2; nn += 2)
4565     {
4566     expand_nstring[expand_nmax] = subject + ovector[nn];
4567     expand_nlength[expand_nmax++] = ovector[nn+1] - ovector[nn];
4568     }
4569   expand_nmax--;
4570   }
4571 return yield;
4572 }
4573
4574
4575 int main(int argc, uschar **argv)
4576 {
4577 int i;
4578 uschar buffer[1024];
4579
4580 debug_selector = D_v;
4581 debug_file = stderr;
4582 debug_fd = fileno(debug_file);
4583 big_buffer = malloc(big_buffer_size);
4584
4585 for (i = 1; i < argc; i++)
4586   {
4587   if (argv[i][0] == '+')
4588     {
4589     debug_trace_memory = 2;
4590     argv[i]++;
4591     }
4592   if (isdigit(argv[i][0]))
4593     debug_selector = Ustrtol(argv[i], NULL, 0);
4594   else
4595     if (Ustrspn(argv[i], "abcdefghijklmnopqrtsuvwxyz0123456789-.:/") ==
4596         Ustrlen(argv[i]))
4597       {
4598       #ifdef LOOKUP_LDAP
4599       eldap_default_servers = argv[i];
4600       #endif
4601       #ifdef LOOKUP_MYSQL
4602       mysql_servers = argv[i];
4603       #endif
4604       #ifdef LOOKUP_PGSQL
4605       pgsql_servers = argv[i];
4606       #endif
4607       }
4608   #ifdef EXIM_PERL
4609   else opt_perl_startup = argv[i];
4610   #endif
4611   }
4612
4613 printf("Testing string expansion: debug_level = %d\n\n", debug_level);
4614
4615 expand_nstring[1] = US"string 1....";
4616 expand_nlength[1] = 8;
4617 expand_nmax = 1;
4618
4619 #ifdef EXIM_PERL
4620 if (opt_perl_startup != NULL)
4621   {
4622   uschar *errstr;
4623   printf("Starting Perl interpreter\n");
4624   errstr = init_perl(opt_perl_startup);
4625   if (errstr != NULL)
4626     {
4627     printf("** error in perl_startup code: %s\n", errstr);
4628     return EXIT_FAILURE;
4629     }
4630   }
4631 #endif /* EXIM_PERL */
4632
4633 while (fgets(buffer, sizeof(buffer), stdin) != NULL)
4634   {
4635   void *reset_point = store_get(0);
4636   uschar *yield = expand_string(buffer);
4637   if (yield != NULL)
4638     {
4639     printf("%s\n", yield);
4640     store_reset(reset_point);
4641     }
4642   else
4643     {
4644     if (search_find_defer) printf("search_find deferred\n");
4645     printf("Failed: %s\n", expand_string_message);
4646     if (expand_string_forcedfail) printf("Forced failure\n");
4647     printf("\n");
4648     }
4649   }
4650
4651 search_tidyup();
4652
4653 return 0;
4654 }
4655
4656 #endif
4657
4658 /* End of expand.c */