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