Args count reduction in expansions coding
[exim.git] / src / src / expand.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) The Exim Maintainers 2020 - 2022 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
8
9
10 /* Functions for handling string expansion. */
11
12
13 #include "exim.h"
14
15 typedef unsigned esi_flags;
16 #define ESI_NOFLAGS             0
17 #define ESI_BRACE_ENDS          BIT(0)  /* expansion should stop at } */
18 #define ESI_HONOR_DOLLAR        BIT(1)  /* $ is meaningfull */
19 #define ESI_SKIPPING            BIT(2)  /* value will not be needed */
20
21 /* Recursively called function */
22
23 static uschar *expand_string_internal(const uschar *, esi_flags, const uschar **, BOOL *, BOOL *);
24 static int_eximarith_t expanded_string_integer(const uschar *, BOOL);
25
26 #ifdef STAND_ALONE
27 # ifndef SUPPORT_CRYPTEQ
28 #  define SUPPORT_CRYPTEQ
29 # endif
30 #endif
31
32 #ifdef LOOKUP_LDAP
33 # include "lookups/ldap.h"
34 #endif
35
36 #ifdef SUPPORT_CRYPTEQ
37 # ifdef CRYPT_H
38 #  include <crypt.h>
39 # endif
40 # ifndef HAVE_CRYPT16
41 extern char* crypt16(char*, char*);
42 # endif
43 #endif
44
45 /* The handling of crypt16() is a mess. I will record below the analysis of the
46 mess that was sent to me. We decided, however, to make changing this very low
47 priority, because in practice people are moving away from the crypt()
48 algorithms nowadays, so it doesn't seem worth it.
49
50 <quote>
51 There is an algorithm named "crypt16" in Ultrix and Tru64.  It crypts
52 the first 8 characters of the password using a 20-round version of crypt
53 (standard crypt does 25 rounds).  It then crypts the next 8 characters,
54 or an empty block if the password is less than 9 characters, using a
55 20-round version of crypt and the same salt as was used for the first
56 block.  Characters after the first 16 are ignored.  It always generates
57 a 16-byte hash, which is expressed together with the salt as a string
58 of 24 base 64 digits.  Here are some links to peruse:
59
60         http://cvs.pld.org.pl/pam/pamcrypt/crypt16.c?rev=1.2
61         http://seclists.org/bugtraq/1999/Mar/0076.html
62
63 There's a different algorithm named "bigcrypt" in HP-UX, Digital Unix,
64 and OSF/1.  This is the same as the standard crypt if given a password
65 of 8 characters or less.  If given more, it first does the same as crypt
66 using the first 8 characters, then crypts the next 8 (the 9th to 16th)
67 using as salt the first two base 64 digits from the first hash block.
68 If the password is more than 16 characters then it crypts the 17th to 24th
69 characters using as salt the first two base 64 digits from the second hash
70 block.  And so on: I've seen references to it cutting off the password at
71 40 characters (5 blocks), 80 (10 blocks), or 128 (16 blocks).  Some links:
72
73         http://cvs.pld.org.pl/pam/pamcrypt/bigcrypt.c?rev=1.2
74         http://seclists.org/bugtraq/1999/Mar/0109.html
75         http://h30097.www3.hp.com/docs/base_doc/DOCUMENTATION/HTML/AA-Q0R2D-
76              TET1_html/sec.c222.html#no_id_208
77
78 Exim has something it calls "crypt16".  It will either use a native
79 crypt16 or its own implementation.  A native crypt16 will presumably
80 be the one that I called "crypt16" above.  The internal "crypt16"
81 function, however, is a two-block-maximum implementation of what I called
82 "bigcrypt".  The documentation matches the internal code.
83
84 I suspect that whoever did the "crypt16" stuff for Exim didn't realise
85 that crypt16 and bigcrypt were different things.
86
87 Exim uses the LDAP-style scheme identifier "{crypt16}" to refer
88 to whatever it is using under that name.  This unfortunately sets a
89 precedent for using "{crypt16}" to identify two incompatible algorithms
90 whose output can't be distinguished.  With "{crypt16}" thus rendered
91 ambiguous, I suggest you deprecate it and invent two new identifiers
92 for the two algorithms.
93
94 Both crypt16 and bigcrypt are very poor algorithms, btw.  Hashing parts
95 of the password separately means they can be cracked separately, so
96 the double-length hash only doubles the cracking effort instead of
97 squaring it.  I recommend salted SHA-1 ({SSHA}), or the Blowfish-based
98 bcrypt ({CRYPT}$2a$).
99 </quote>
100 */
101
102
103
104 /*************************************************
105 *            Local statics and tables            *
106 *************************************************/
107
108 /* Table of item names, and corresponding switch numbers. The names must be in
109 alphabetical order. */
110
111 static uschar *item_table[] = {
112   US"acl",
113   US"authresults",
114   US"certextract",
115   US"dlfunc",
116   US"env",
117   US"extract",
118   US"filter",
119   US"hash",
120   US"hmac",
121   US"if",
122 #ifdef SUPPORT_I18N
123   US"imapfolder",
124 #endif
125   US"length",
126   US"listextract",
127   US"listquote",
128   US"lookup",
129   US"map",
130   US"nhash",
131   US"perl",
132   US"prvs",
133   US"prvscheck",
134   US"readfile",
135   US"readsocket",
136   US"reduce",
137   US"run",
138   US"sg",
139   US"sort",
140 #ifdef SUPPORT_SRS
141   US"srs_encode",
142 #endif
143   US"substr",
144   US"tr" };
145
146 enum {
147   EITEM_ACL,
148   EITEM_AUTHRESULTS,
149   EITEM_CERTEXTRACT,
150   EITEM_DLFUNC,
151   EITEM_ENV,
152   EITEM_EXTRACT,
153   EITEM_FILTER,
154   EITEM_HASH,
155   EITEM_HMAC,
156   EITEM_IF,
157 #ifdef SUPPORT_I18N
158   EITEM_IMAPFOLDER,
159 #endif
160   EITEM_LENGTH,
161   EITEM_LISTEXTRACT,
162   EITEM_LISTQUOTE,
163   EITEM_LOOKUP,
164   EITEM_MAP,
165   EITEM_NHASH,
166   EITEM_PERL,
167   EITEM_PRVS,
168   EITEM_PRVSCHECK,
169   EITEM_READFILE,
170   EITEM_READSOCK,
171   EITEM_REDUCE,
172   EITEM_RUN,
173   EITEM_SG,
174   EITEM_SORT,
175 #ifdef SUPPORT_SRS
176   EITEM_SRS_ENCODE,
177 #endif
178   EITEM_SUBSTR,
179   EITEM_TR };
180
181 /* Tables of operator names, and corresponding switch numbers. The names must be
182 in alphabetical order. There are two tables, because underscore is used in some
183 cases to introduce arguments, whereas for other it is part of the name. This is
184 an historical mis-design. */
185
186 static uschar * op_table_underscore[] = {
187   US"from_utf8",
188   US"local_part",
189   US"quote_local_part",
190   US"reverse_ip",
191   US"time_eval",
192   US"time_interval"
193 #ifdef SUPPORT_I18N
194  ,US"utf8_domain_from_alabel",
195   US"utf8_domain_to_alabel",
196   US"utf8_localpart_from_alabel",
197   US"utf8_localpart_to_alabel"
198 #endif
199   };
200
201 enum {
202   EOP_FROM_UTF8,
203   EOP_LOCAL_PART,
204   EOP_QUOTE_LOCAL_PART,
205   EOP_REVERSE_IP,
206   EOP_TIME_EVAL,
207   EOP_TIME_INTERVAL
208 #ifdef SUPPORT_I18N
209  ,EOP_UTF8_DOMAIN_FROM_ALABEL,
210   EOP_UTF8_DOMAIN_TO_ALABEL,
211   EOP_UTF8_LOCALPART_FROM_ALABEL,
212   EOP_UTF8_LOCALPART_TO_ALABEL
213 #endif
214   };
215
216 static uschar *op_table_main[] = {
217   US"address",
218   US"addresses",
219   US"base32",
220   US"base32d",
221   US"base62",
222   US"base62d",
223   US"base64",
224   US"base64d",
225   US"domain",
226   US"escape",
227   US"escape8bit",
228   US"eval",
229   US"eval10",
230   US"expand",
231   US"h",
232   US"hash",
233   US"hex2b64",
234   US"hexquote",
235   US"ipv6denorm",
236   US"ipv6norm",
237   US"l",
238   US"lc",
239   US"length",
240   US"listcount",
241   US"listnamed",
242   US"mask",
243   US"md5",
244   US"nh",
245   US"nhash",
246   US"quote",
247   US"randint",
248   US"rfc2047",
249   US"rfc2047d",
250   US"rxquote",
251   US"s",
252   US"sha1",
253   US"sha2",
254   US"sha256",
255   US"sha3",
256   US"stat",
257   US"str2b64",
258   US"strlen",
259   US"substr",
260   US"uc",
261   US"utf8clean" };
262
263 enum {
264   EOP_ADDRESS =  nelem(op_table_underscore),
265   EOP_ADDRESSES,
266   EOP_BASE32,
267   EOP_BASE32D,
268   EOP_BASE62,
269   EOP_BASE62D,
270   EOP_BASE64,
271   EOP_BASE64D,
272   EOP_DOMAIN,
273   EOP_ESCAPE,
274   EOP_ESCAPE8BIT,
275   EOP_EVAL,
276   EOP_EVAL10,
277   EOP_EXPAND,
278   EOP_H,
279   EOP_HASH,
280   EOP_HEX2B64,
281   EOP_HEXQUOTE,
282   EOP_IPV6DENORM,
283   EOP_IPV6NORM,
284   EOP_L,
285   EOP_LC,
286   EOP_LENGTH,
287   EOP_LISTCOUNT,
288   EOP_LISTNAMED,
289   EOP_MASK,
290   EOP_MD5,
291   EOP_NH,
292   EOP_NHASH,
293   EOP_QUOTE,
294   EOP_RANDINT,
295   EOP_RFC2047,
296   EOP_RFC2047D,
297   EOP_RXQUOTE,
298   EOP_S,
299   EOP_SHA1,
300   EOP_SHA2,
301   EOP_SHA256,
302   EOP_SHA3,
303   EOP_STAT,
304   EOP_STR2B64,
305   EOP_STRLEN,
306   EOP_SUBSTR,
307   EOP_UC,
308   EOP_UTF8CLEAN };
309
310
311 /* Table of condition names, and corresponding switch numbers. The names must
312 be in alphabetical order. */
313
314 static uschar *cond_table[] = {
315   US"<",
316   US"<=",
317   US"=",
318   US"==",     /* Backward compatibility */
319   US">",
320   US">=",
321   US"acl",
322   US"and",
323   US"bool",
324   US"bool_lax",
325   US"crypteq",
326   US"def",
327   US"eq",
328   US"eqi",
329   US"exists",
330   US"first_delivery",
331   US"forall",
332   US"forall_json",
333   US"forall_jsons",
334   US"forany",
335   US"forany_json",
336   US"forany_jsons",
337   US"ge",
338   US"gei",
339   US"gt",
340   US"gti",
341 #ifdef SUPPORT_SRS
342   US"inbound_srs",
343 #endif
344   US"inlist",
345   US"inlisti",
346   US"isip",
347   US"isip4",
348   US"isip6",
349   US"ldapauth",
350   US"le",
351   US"lei",
352   US"lt",
353   US"lti",
354   US"match",
355   US"match_address",
356   US"match_domain",
357   US"match_ip",
358   US"match_local_part",
359   US"or",
360   US"pam",
361   US"pwcheck",
362   US"queue_running",
363   US"radius",
364   US"saslauthd"
365 };
366
367 enum {
368   ECOND_NUM_L,
369   ECOND_NUM_LE,
370   ECOND_NUM_E,
371   ECOND_NUM_EE,
372   ECOND_NUM_G,
373   ECOND_NUM_GE,
374   ECOND_ACL,
375   ECOND_AND,
376   ECOND_BOOL,
377   ECOND_BOOL_LAX,
378   ECOND_CRYPTEQ,
379   ECOND_DEF,
380   ECOND_STR_EQ,
381   ECOND_STR_EQI,
382   ECOND_EXISTS,
383   ECOND_FIRST_DELIVERY,
384   ECOND_FORALL,
385   ECOND_FORALL_JSON,
386   ECOND_FORALL_JSONS,
387   ECOND_FORANY,
388   ECOND_FORANY_JSON,
389   ECOND_FORANY_JSONS,
390   ECOND_STR_GE,
391   ECOND_STR_GEI,
392   ECOND_STR_GT,
393   ECOND_STR_GTI,
394 #ifdef SUPPORT_SRS
395   ECOND_INBOUND_SRS,
396 #endif
397   ECOND_INLIST,
398   ECOND_INLISTI,
399   ECOND_ISIP,
400   ECOND_ISIP4,
401   ECOND_ISIP6,
402   ECOND_LDAPAUTH,
403   ECOND_STR_LE,
404   ECOND_STR_LEI,
405   ECOND_STR_LT,
406   ECOND_STR_LTI,
407   ECOND_MATCH,
408   ECOND_MATCH_ADDRESS,
409   ECOND_MATCH_DOMAIN,
410   ECOND_MATCH_IP,
411   ECOND_MATCH_LOCAL_PART,
412   ECOND_OR,
413   ECOND_PAM,
414   ECOND_PWCHECK,
415   ECOND_QUEUE_RUNNING,
416   ECOND_RADIUS,
417   ECOND_SASLAUTHD
418 };
419
420
421 /* Types of table entry */
422
423 enum vtypes {
424   vtype_int,            /* value is address of int */
425   vtype_filter_int,     /* ditto, but recognized only when filtering */
426   vtype_ino,            /* value is address of ino_t (not always an int) */
427   vtype_uid,            /* value is address of uid_t (not always an int) */
428   vtype_gid,            /* value is address of gid_t (not always an int) */
429   vtype_bool,           /* value is address of bool */
430   vtype_stringptr,      /* value is address of pointer to string */
431   vtype_msgbody,        /* as stringptr, but read when first required */
432   vtype_msgbody_end,    /* ditto, the end of the message */
433   vtype_msgheaders,     /* the message's headers, processed */
434   vtype_msgheaders_raw, /* the message's headers, unprocessed */
435   vtype_localpart,      /* extract local part from string */
436   vtype_domain,         /* extract domain from string */
437   vtype_string_func,    /* value is string returned by given function */
438   vtype_todbsdin,       /* value not used; generate BSD inbox tod */
439   vtype_tode,           /* value not used; generate tod in epoch format */
440   vtype_todel,          /* value not used; generate tod in epoch/usec format */
441   vtype_todf,           /* value not used; generate full tod */
442   vtype_todl,           /* value not used; generate log tod */
443   vtype_todlf,          /* value not used; generate log file datestamp tod */
444   vtype_todzone,        /* value not used; generate time zone only */
445   vtype_todzulu,        /* value not used; generate zulu tod */
446   vtype_reply,          /* value not used; get reply from headers */
447   vtype_pid,            /* value not used; result is pid */
448   vtype_host_lookup,    /* value not used; get host name */
449   vtype_load_avg,       /* value not used; result is int from os_getloadavg */
450   vtype_pspace,         /* partition space; value is T/F for spool/log */
451   vtype_pinodes,        /* partition inodes; value is T/F for spool/log */
452   vtype_cert            /* SSL certificate */
453 #ifndef DISABLE_DKIM
454   ,vtype_dkim           /* Lookup of value in DKIM signature */
455 #endif
456 };
457
458 /* Type for main variable table */
459
460 typedef struct {
461   const char *name;
462   enum vtypes type;
463   void       *value;
464 } var_entry;
465
466 /* Type for entries pointing to address/length pairs. Not currently
467 in use. */
468
469 typedef struct {
470   uschar **address;
471   int  *length;
472 } alblock;
473
474 static uschar * fn_recipients(void);
475 typedef uschar * stringptr_fn_t(void);
476 static uschar * fn_queue_size(void);
477
478 /* This table must be kept in alphabetical order. */
479
480 static var_entry var_table[] = {
481   /* WARNING: Do not invent variables whose names start acl_c or acl_m because
482      they will be confused with user-creatable ACL variables. */
483   { "acl_arg1",            vtype_stringptr,   &acl_arg[0] },
484   { "acl_arg2",            vtype_stringptr,   &acl_arg[1] },
485   { "acl_arg3",            vtype_stringptr,   &acl_arg[2] },
486   { "acl_arg4",            vtype_stringptr,   &acl_arg[3] },
487   { "acl_arg5",            vtype_stringptr,   &acl_arg[4] },
488   { "acl_arg6",            vtype_stringptr,   &acl_arg[5] },
489   { "acl_arg7",            vtype_stringptr,   &acl_arg[6] },
490   { "acl_arg8",            vtype_stringptr,   &acl_arg[7] },
491   { "acl_arg9",            vtype_stringptr,   &acl_arg[8] },
492   { "acl_narg",            vtype_int,         &acl_narg },
493   { "acl_verify_message",  vtype_stringptr,   &acl_verify_message },
494   { "address_data",        vtype_stringptr,   &deliver_address_data },
495   { "address_file",        vtype_stringptr,   &address_file },
496   { "address_pipe",        vtype_stringptr,   &address_pipe },
497 #ifdef EXPERIMENTAL_ARC
498   { "arc_domains",         vtype_string_func, (void *) &fn_arc_domains },
499   { "arc_oldest_pass",     vtype_int,         &arc_oldest_pass },
500   { "arc_state",           vtype_stringptr,   &arc_state },
501   { "arc_state_reason",    vtype_stringptr,   &arc_state_reason },
502 #endif
503   { "authenticated_fail_id",vtype_stringptr,  &authenticated_fail_id },
504   { "authenticated_id",    vtype_stringptr,   &authenticated_id },
505   { "authenticated_sender",vtype_stringptr,   &authenticated_sender },
506   { "authentication_failed",vtype_int,        &authentication_failed },
507 #ifdef WITH_CONTENT_SCAN
508   { "av_failed",           vtype_int,         &av_failed },
509 #endif
510 #ifdef EXPERIMENTAL_BRIGHTMAIL
511   { "bmi_alt_location",    vtype_stringptr,   &bmi_alt_location },
512   { "bmi_base64_tracker_verdict", vtype_stringptr, &bmi_base64_tracker_verdict },
513   { "bmi_base64_verdict",  vtype_stringptr,   &bmi_base64_verdict },
514   { "bmi_deliver",         vtype_int,         &bmi_deliver },
515 #endif
516   { "body_linecount",      vtype_int,         &body_linecount },
517   { "body_zerocount",      vtype_int,         &body_zerocount },
518   { "bounce_recipient",    vtype_stringptr,   &bounce_recipient },
519   { "bounce_return_size_limit", vtype_int,    &bounce_return_size_limit },
520   { "caller_gid",          vtype_gid,         &real_gid },
521   { "caller_uid",          vtype_uid,         &real_uid },
522   { "callout_address",     vtype_stringptr,   &callout_address },
523   { "compile_date",        vtype_stringptr,   &version_date },
524   { "compile_number",      vtype_stringptr,   &version_cnumber },
525   { "config_dir",          vtype_stringptr,   &config_main_directory },
526   { "config_file",         vtype_stringptr,   &config_main_filename },
527   { "csa_status",          vtype_stringptr,   &csa_status },
528 #ifdef EXPERIMENTAL_DCC
529   { "dcc_header",          vtype_stringptr,   &dcc_header },
530   { "dcc_result",          vtype_stringptr,   &dcc_result },
531 #endif
532 #ifndef DISABLE_DKIM
533   { "dkim_algo",           vtype_dkim,        (void *)DKIM_ALGO },
534   { "dkim_bodylength",     vtype_dkim,        (void *)DKIM_BODYLENGTH },
535   { "dkim_canon_body",     vtype_dkim,        (void *)DKIM_CANON_BODY },
536   { "dkim_canon_headers",  vtype_dkim,        (void *)DKIM_CANON_HEADERS },
537   { "dkim_copiedheaders",  vtype_dkim,        (void *)DKIM_COPIEDHEADERS },
538   { "dkim_created",        vtype_dkim,        (void *)DKIM_CREATED },
539   { "dkim_cur_signer",     vtype_stringptr,   &dkim_cur_signer },
540   { "dkim_domain",         vtype_stringptr,   &dkim_signing_domain },
541   { "dkim_expires",        vtype_dkim,        (void *)DKIM_EXPIRES },
542   { "dkim_headernames",    vtype_dkim,        (void *)DKIM_HEADERNAMES },
543   { "dkim_identity",       vtype_dkim,        (void *)DKIM_IDENTITY },
544   { "dkim_key_granularity",vtype_dkim,        (void *)DKIM_KEY_GRANULARITY },
545   { "dkim_key_length",     vtype_int,         &dkim_key_length },
546   { "dkim_key_nosubdomains",vtype_dkim,       (void *)DKIM_NOSUBDOMAINS },
547   { "dkim_key_notes",      vtype_dkim,        (void *)DKIM_KEY_NOTES },
548   { "dkim_key_srvtype",    vtype_dkim,        (void *)DKIM_KEY_SRVTYPE },
549   { "dkim_key_testing",    vtype_dkim,        (void *)DKIM_KEY_TESTING },
550   { "dkim_selector",       vtype_stringptr,   &dkim_signing_selector },
551   { "dkim_signers",        vtype_stringptr,   &dkim_signers },
552   { "dkim_verify_reason",  vtype_stringptr,   &dkim_verify_reason },
553   { "dkim_verify_status",  vtype_stringptr,   &dkim_verify_status },
554 #endif
555 #ifdef SUPPORT_DMARC
556   { "dmarc_domain_policy", vtype_stringptr,   &dmarc_domain_policy },
557   { "dmarc_status",        vtype_stringptr,   &dmarc_status },
558   { "dmarc_status_text",   vtype_stringptr,   &dmarc_status_text },
559   { "dmarc_used_domain",   vtype_stringptr,   &dmarc_used_domain },
560 #endif
561   { "dnslist_domain",      vtype_stringptr,   &dnslist_domain },
562   { "dnslist_matched",     vtype_stringptr,   &dnslist_matched },
563   { "dnslist_text",        vtype_stringptr,   &dnslist_text },
564   { "dnslist_value",       vtype_stringptr,   &dnslist_value },
565   { "domain",              vtype_stringptr,   &deliver_domain },
566   { "domain_data",         vtype_stringptr,   &deliver_domain_data },
567 #ifndef DISABLE_EVENT
568   { "event_data",          vtype_stringptr,   &event_data },
569
570   /*XXX want to use generic vars for as many of these as possible*/
571   { "event_defer_errno",   vtype_int,         &event_defer_errno },
572
573   { "event_name",          vtype_stringptr,   &event_name },
574 #endif
575   { "exim_gid",            vtype_gid,         &exim_gid },
576   { "exim_path",           vtype_stringptr,   &exim_path },
577   { "exim_uid",            vtype_uid,         &exim_uid },
578   { "exim_version",        vtype_stringptr,   &version_string },
579   { "headers_added",       vtype_string_func, (void *) &fn_hdrs_added },
580   { "home",                vtype_stringptr,   &deliver_home },
581   { "host",                vtype_stringptr,   &deliver_host },
582   { "host_address",        vtype_stringptr,   &deliver_host_address },
583   { "host_data",           vtype_stringptr,   &host_data },
584   { "host_lookup_deferred",vtype_int,         &host_lookup_deferred },
585   { "host_lookup_failed",  vtype_int,         &host_lookup_failed },
586   { "host_port",           vtype_int,         &deliver_host_port },
587   { "initial_cwd",         vtype_stringptr,   &initial_cwd },
588   { "inode",               vtype_ino,         &deliver_inode },
589   { "interface_address",   vtype_stringptr,   &interface_address },
590   { "interface_port",      vtype_int,         &interface_port },
591   { "item",                vtype_stringptr,   &iterate_item },
592 #ifdef LOOKUP_LDAP
593   { "ldap_dn",             vtype_stringptr,   &eldap_dn },
594 #endif
595   { "load_average",        vtype_load_avg,    NULL },
596   { "local_part",          vtype_stringptr,   &deliver_localpart },
597   { "local_part_data",     vtype_stringptr,   &deliver_localpart_data },
598   { "local_part_prefix",   vtype_stringptr,   &deliver_localpart_prefix },
599   { "local_part_prefix_v", vtype_stringptr,   &deliver_localpart_prefix_v },
600   { "local_part_suffix",   vtype_stringptr,   &deliver_localpart_suffix },
601   { "local_part_suffix_v", vtype_stringptr,   &deliver_localpart_suffix_v },
602 #ifdef HAVE_LOCAL_SCAN
603   { "local_scan_data",     vtype_stringptr,   &local_scan_data },
604 #endif
605   { "local_user_gid",      vtype_gid,         &local_user_gid },
606   { "local_user_uid",      vtype_uid,         &local_user_uid },
607   { "localhost_number",    vtype_int,         &host_number },
608   { "log_inodes",          vtype_pinodes,     (void *)FALSE },
609   { "log_space",           vtype_pspace,      (void *)FALSE },
610   { "lookup_dnssec_authenticated",vtype_stringptr,&lookup_dnssec_authenticated},
611   { "mailstore_basename",  vtype_stringptr,   &mailstore_basename },
612 #ifdef WITH_CONTENT_SCAN
613   { "malware_name",        vtype_stringptr,   &malware_name },
614 #endif
615   { "max_received_linelength", vtype_int,     &max_received_linelength },
616   { "message_age",         vtype_int,         &message_age },
617   { "message_body",        vtype_msgbody,     &message_body },
618   { "message_body_end",    vtype_msgbody_end, &message_body_end },
619   { "message_body_size",   vtype_int,         &message_body_size },
620   { "message_exim_id",     vtype_stringptr,   &message_id },
621   { "message_headers",     vtype_msgheaders,  NULL },
622   { "message_headers_raw", vtype_msgheaders_raw, NULL },
623   { "message_id",          vtype_stringptr,   &message_id },
624   { "message_linecount",   vtype_int,         &message_linecount },
625   { "message_size",        vtype_int,         &message_size },
626 #ifdef SUPPORT_I18N
627   { "message_smtputf8",    vtype_bool,        &message_smtputf8 },
628 #endif
629 #ifdef WITH_CONTENT_SCAN
630   { "mime_anomaly_level",  vtype_int,         &mime_anomaly_level },
631   { "mime_anomaly_text",   vtype_stringptr,   &mime_anomaly_text },
632   { "mime_boundary",       vtype_stringptr,   &mime_boundary },
633   { "mime_charset",        vtype_stringptr,   &mime_charset },
634   { "mime_content_description", vtype_stringptr, &mime_content_description },
635   { "mime_content_disposition", vtype_stringptr, &mime_content_disposition },
636   { "mime_content_id",     vtype_stringptr,   &mime_content_id },
637   { "mime_content_size",   vtype_int,         &mime_content_size },
638   { "mime_content_transfer_encoding",vtype_stringptr, &mime_content_transfer_encoding },
639   { "mime_content_type",   vtype_stringptr,   &mime_content_type },
640   { "mime_decoded_filename", vtype_stringptr, &mime_decoded_filename },
641   { "mime_filename",       vtype_stringptr,   &mime_filename },
642   { "mime_is_coverletter", vtype_int,         &mime_is_coverletter },
643   { "mime_is_multipart",   vtype_int,         &mime_is_multipart },
644   { "mime_is_rfc822",      vtype_int,         &mime_is_rfc822 },
645   { "mime_part_count",     vtype_int,         &mime_part_count },
646 #endif
647   { "n0",                  vtype_filter_int,  &filter_n[0] },
648   { "n1",                  vtype_filter_int,  &filter_n[1] },
649   { "n2",                  vtype_filter_int,  &filter_n[2] },
650   { "n3",                  vtype_filter_int,  &filter_n[3] },
651   { "n4",                  vtype_filter_int,  &filter_n[4] },
652   { "n5",                  vtype_filter_int,  &filter_n[5] },
653   { "n6",                  vtype_filter_int,  &filter_n[6] },
654   { "n7",                  vtype_filter_int,  &filter_n[7] },
655   { "n8",                  vtype_filter_int,  &filter_n[8] },
656   { "n9",                  vtype_filter_int,  &filter_n[9] },
657   { "original_domain",     vtype_stringptr,   &deliver_domain_orig },
658   { "original_local_part", vtype_stringptr,   &deliver_localpart_orig },
659   { "originator_gid",      vtype_gid,         &originator_gid },
660   { "originator_uid",      vtype_uid,         &originator_uid },
661   { "parent_domain",       vtype_stringptr,   &deliver_domain_parent },
662   { "parent_local_part",   vtype_stringptr,   &deliver_localpart_parent },
663   { "pid",                 vtype_pid,         NULL },
664 #ifndef DISABLE_PRDR
665   { "prdr_requested",      vtype_bool,        &prdr_requested },
666 #endif
667   { "primary_hostname",    vtype_stringptr,   &primary_hostname },
668 #if defined(SUPPORT_PROXY) || defined(SUPPORT_SOCKS)
669   { "proxy_external_address",vtype_stringptr, &proxy_external_address },
670   { "proxy_external_port", vtype_int,         &proxy_external_port },
671   { "proxy_local_address", vtype_stringptr,   &proxy_local_address },
672   { "proxy_local_port",    vtype_int,         &proxy_local_port },
673   { "proxy_session",       vtype_bool,        &proxy_session },
674 #endif
675   { "prvscheck_address",   vtype_stringptr,   &prvscheck_address },
676   { "prvscheck_keynum",    vtype_stringptr,   &prvscheck_keynum },
677   { "prvscheck_result",    vtype_stringptr,   &prvscheck_result },
678   { "qualify_domain",      vtype_stringptr,   &qualify_domain_sender },
679   { "qualify_recipient",   vtype_stringptr,   &qualify_domain_recipient },
680   { "queue_name",          vtype_stringptr,   &queue_name },
681   { "queue_size",          vtype_string_func, &fn_queue_size },
682   { "rcpt_count",          vtype_int,         &rcpt_count },
683   { "rcpt_defer_count",    vtype_int,         &rcpt_defer_count },
684   { "rcpt_fail_count",     vtype_int,         &rcpt_fail_count },
685   { "received_count",      vtype_int,         &received_count },
686   { "received_for",        vtype_stringptr,   &received_for },
687   { "received_ip_address", vtype_stringptr,   &interface_address },
688   { "received_port",       vtype_int,         &interface_port },
689   { "received_protocol",   vtype_stringptr,   &received_protocol },
690   { "received_time",       vtype_int,         &received_time.tv_sec },
691   { "recipient_data",      vtype_stringptr,   &recipient_data },
692   { "recipient_verify_failure",vtype_stringptr,&recipient_verify_failure },
693   { "recipients",          vtype_string_func, (void *) &fn_recipients },
694   { "recipients_count",    vtype_int,         &recipients_count },
695 #ifdef WITH_CONTENT_SCAN
696   { "regex_match_string",  vtype_stringptr,   &regex_match_string },
697 #endif
698   { "reply_address",       vtype_reply,       NULL },
699   { "return_path",         vtype_stringptr,   &return_path },
700   { "return_size_limit",   vtype_int,         &bounce_return_size_limit },
701   { "router_name",         vtype_stringptr,   &router_name },
702   { "runrc",               vtype_int,         &runrc },
703   { "self_hostname",       vtype_stringptr,   &self_hostname },
704   { "sender_address",      vtype_stringptr,   &sender_address },
705   { "sender_address_data", vtype_stringptr,   &sender_address_data },
706   { "sender_address_domain", vtype_domain,    &sender_address },
707   { "sender_address_local_part", vtype_localpart, &sender_address },
708   { "sender_data",         vtype_stringptr,   &sender_data },
709   { "sender_fullhost",     vtype_stringptr,   &sender_fullhost },
710   { "sender_helo_dnssec",  vtype_bool,        &sender_helo_dnssec },
711   { "sender_helo_name",    vtype_stringptr,   &sender_helo_name },
712   { "sender_host_address", vtype_stringptr,   &sender_host_address },
713   { "sender_host_authenticated",vtype_stringptr, &sender_host_authenticated },
714   { "sender_host_dnssec",  vtype_bool,        &sender_host_dnssec },
715   { "sender_host_name",    vtype_host_lookup, NULL },
716   { "sender_host_port",    vtype_int,         &sender_host_port },
717   { "sender_ident",        vtype_stringptr,   &sender_ident },
718   { "sender_rate",         vtype_stringptr,   &sender_rate },
719   { "sender_rate_limit",   vtype_stringptr,   &sender_rate_limit },
720   { "sender_rate_period",  vtype_stringptr,   &sender_rate_period },
721   { "sender_rcvhost",      vtype_stringptr,   &sender_rcvhost },
722   { "sender_verify_failure",vtype_stringptr,  &sender_verify_failure },
723   { "sending_ip_address",  vtype_stringptr,   &sending_ip_address },
724   { "sending_port",        vtype_int,         &sending_port },
725   { "smtp_active_hostname", vtype_stringptr,  &smtp_active_hostname },
726   { "smtp_command",        vtype_stringptr,   &smtp_cmd_buffer },
727   { "smtp_command_argument", vtype_stringptr, &smtp_cmd_argument },
728   { "smtp_command_history", vtype_string_func, (void *) &smtp_cmd_hist },
729   { "smtp_count_at_connection_start", vtype_int, &smtp_accept_count },
730   { "smtp_notquit_reason", vtype_stringptr,   &smtp_notquit_reason },
731   { "sn0",                 vtype_filter_int,  &filter_sn[0] },
732   { "sn1",                 vtype_filter_int,  &filter_sn[1] },
733   { "sn2",                 vtype_filter_int,  &filter_sn[2] },
734   { "sn3",                 vtype_filter_int,  &filter_sn[3] },
735   { "sn4",                 vtype_filter_int,  &filter_sn[4] },
736   { "sn5",                 vtype_filter_int,  &filter_sn[5] },
737   { "sn6",                 vtype_filter_int,  &filter_sn[6] },
738   { "sn7",                 vtype_filter_int,  &filter_sn[7] },
739   { "sn8",                 vtype_filter_int,  &filter_sn[8] },
740   { "sn9",                 vtype_filter_int,  &filter_sn[9] },
741 #ifdef WITH_CONTENT_SCAN
742   { "spam_action",         vtype_stringptr,   &spam_action },
743   { "spam_bar",            vtype_stringptr,   &spam_bar },
744   { "spam_report",         vtype_stringptr,   &spam_report },
745   { "spam_score",          vtype_stringptr,   &spam_score },
746   { "spam_score_int",      vtype_stringptr,   &spam_score_int },
747 #endif
748 #ifdef SUPPORT_SPF
749   { "spf_guess",           vtype_stringptr,   &spf_guess },
750   { "spf_header_comment",  vtype_stringptr,   &spf_header_comment },
751   { "spf_received",        vtype_stringptr,   &spf_received },
752   { "spf_result",          vtype_stringptr,   &spf_result },
753   { "spf_result_guessed",  vtype_bool,        &spf_result_guessed },
754   { "spf_smtp_comment",    vtype_stringptr,   &spf_smtp_comment },
755 #endif
756   { "spool_directory",     vtype_stringptr,   &spool_directory },
757   { "spool_inodes",        vtype_pinodes,     (void *)TRUE },
758   { "spool_space",         vtype_pspace,      (void *)TRUE },
759 #ifdef SUPPORT_SRS
760   { "srs_recipient",       vtype_stringptr,   &srs_recipient },
761 #endif
762   { "thisaddress",         vtype_stringptr,   &filter_thisaddress },
763
764   /* The non-(in,out) variables are now deprecated */
765   { "tls_bits",            vtype_int,         &tls_in.bits },
766   { "tls_certificate_verified", vtype_int,    &tls_in.certificate_verified },
767   { "tls_cipher",          vtype_stringptr,   &tls_in.cipher },
768
769   { "tls_in_bits",         vtype_int,         &tls_in.bits },
770   { "tls_in_certificate_verified", vtype_int, &tls_in.certificate_verified },
771   { "tls_in_cipher",       vtype_stringptr,   &tls_in.cipher },
772   { "tls_in_cipher_std",   vtype_stringptr,   &tls_in.cipher_stdname },
773   { "tls_in_ocsp",         vtype_int,         &tls_in.ocsp },
774   { "tls_in_ourcert",      vtype_cert,        &tls_in.ourcert },
775   { "tls_in_peercert",     vtype_cert,        &tls_in.peercert },
776   { "tls_in_peerdn",       vtype_stringptr,   &tls_in.peerdn },
777 #ifndef DISABLE_TLS_RESUME
778   { "tls_in_resumption",   vtype_int,         &tls_in.resumption },
779 #endif
780 #ifndef DISABLE_TLS
781   { "tls_in_sni",          vtype_stringptr,   &tls_in.sni },
782 #endif
783   { "tls_in_ver",          vtype_stringptr,   &tls_in.ver },
784   { "tls_out_bits",        vtype_int,         &tls_out.bits },
785   { "tls_out_certificate_verified", vtype_int,&tls_out.certificate_verified },
786   { "tls_out_cipher",      vtype_stringptr,   &tls_out.cipher },
787   { "tls_out_cipher_std",  vtype_stringptr,   &tls_out.cipher_stdname },
788 #ifdef SUPPORT_DANE
789   { "tls_out_dane",        vtype_bool,        &tls_out.dane_verified },
790 #endif
791   { "tls_out_ocsp",        vtype_int,         &tls_out.ocsp },
792   { "tls_out_ourcert",     vtype_cert,        &tls_out.ourcert },
793   { "tls_out_peercert",    vtype_cert,        &tls_out.peercert },
794   { "tls_out_peerdn",      vtype_stringptr,   &tls_out.peerdn },
795 #ifndef DISABLE_TLS_RESUME
796   { "tls_out_resumption",  vtype_int,         &tls_out.resumption },
797 #endif
798 #ifndef DISABLE_TLS
799   { "tls_out_sni",         vtype_stringptr,   &tls_out.sni },
800 #endif
801 #ifdef SUPPORT_DANE
802   { "tls_out_tlsa_usage",  vtype_int,         &tls_out.tlsa_usage },
803 #endif
804   { "tls_out_ver",         vtype_stringptr,   &tls_out.ver },
805
806   { "tls_peerdn",          vtype_stringptr,   &tls_in.peerdn }, /* mind the alphabetical order! */
807 #ifndef DISABLE_TLS
808   { "tls_sni",             vtype_stringptr,   &tls_in.sni },    /* mind the alphabetical order! */
809 #endif
810
811   { "tod_bsdinbox",        vtype_todbsdin,    NULL },
812   { "tod_epoch",           vtype_tode,        NULL },
813   { "tod_epoch_l",         vtype_todel,       NULL },
814   { "tod_full",            vtype_todf,        NULL },
815   { "tod_log",             vtype_todl,        NULL },
816   { "tod_logfile",         vtype_todlf,       NULL },
817   { "tod_zone",            vtype_todzone,     NULL },
818   { "tod_zulu",            vtype_todzulu,     NULL },
819   { "transport_name",      vtype_stringptr,   &transport_name },
820   { "value",               vtype_stringptr,   &lookup_value },
821   { "verify_mode",         vtype_stringptr,   &verify_mode },
822   { "version_number",      vtype_stringptr,   &version_string },
823   { "warn_message_delay",  vtype_stringptr,   &warnmsg_delay },
824   { "warn_message_recipient",vtype_stringptr, &warnmsg_recipients },
825   { "warn_message_recipients",vtype_stringptr,&warnmsg_recipients },
826   { "warnmsg_delay",       vtype_stringptr,   &warnmsg_delay },
827   { "warnmsg_recipient",   vtype_stringptr,   &warnmsg_recipients },
828   { "warnmsg_recipients",  vtype_stringptr,   &warnmsg_recipients }
829 };
830
831 static int var_table_size = nelem(var_table);
832 static uschar var_buffer[256];
833 static BOOL malformed_header;
834
835 /* For textual hashes */
836
837 static const char *hashcodes = "abcdefghijklmnopqrtsuvwxyz"
838                                "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
839                                "0123456789";
840
841 enum { HMAC_MD5, HMAC_SHA1 };
842
843 /* For numeric hashes */
844
845 static unsigned int prime[] = {
846   2,   3,   5,   7,  11,  13,  17,  19,  23,  29,
847  31,  37,  41,  43,  47,  53,  59,  61,  67,  71,
848  73,  79,  83,  89,  97, 101, 103, 107, 109, 113};
849
850 /* For printing modes in symbolic form */
851
852 static uschar *mtable_normal[] =
853   { US"---", US"--x", US"-w-", US"-wx", US"r--", US"r-x", US"rw-", US"rwx" };
854
855 static uschar *mtable_setid[] =
856   { US"--S", US"--s", US"-wS", US"-ws", US"r-S", US"r-s", US"rwS", US"rws" };
857
858 static uschar *mtable_sticky[] =
859   { US"--T", US"--t", US"-wT", US"-wt", US"r-T", US"r-t", US"rwT", US"rwt" };
860
861 /* flags for find_header() */
862 #define FH_EXISTS_ONLY  BIT(0)
863 #define FH_WANT_RAW     BIT(1)
864 #define FH_WANT_LIST    BIT(2)
865
866
867 /*************************************************
868 *           Tables for UTF-8 support             *
869 *************************************************/
870
871 /* Table of the number of extra characters, indexed by the first character
872 masked with 0x3f. The highest number for a valid UTF-8 character is in fact
873 0x3d. */
874
875 static uschar utf8_table1[] = {
876   1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
877   1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
878   2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
879   3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 };
880
881 /* These are the masks for the data bits in the first byte of a character,
882 indexed by the number of additional bytes. */
883
884 static int utf8_table2[] = { 0xff, 0x1f, 0x0f, 0x07, 0x03, 0x01};
885
886 /* Get the next UTF-8 character, advancing the pointer. */
887
888 #define GETUTF8INC(c, ptr) \
889   c = *ptr++; \
890   if ((c & 0xc0) == 0xc0) \
891     { \
892     int a = utf8_table1[c & 0x3f];  /* Number of additional bytes */ \
893     int s = 6*a; \
894     c = (c & utf8_table2[a]) << s; \
895     while (a-- > 0) \
896       { \
897       s -= 6; \
898       c |= (*ptr++ & 0x3f) << s; \
899       } \
900     }
901
902
903
904 static uschar * base32_chars = US"abcdefghijklmnopqrstuvwxyz234567";
905
906 /*************************************************
907 *           Binary chop search on a table        *
908 *************************************************/
909
910 /* This is used for matching expansion items and operators.
911
912 Arguments:
913   name        the name that is being sought
914   table       the table to search
915   table_size  the number of items in the table
916
917 Returns:      the offset in the table, or -1
918 */
919
920 static int
921 chop_match(uschar *name, uschar **table, int table_size)
922 {
923 uschar **bot = table;
924 uschar **top = table + table_size;
925
926 while (top > bot)
927   {
928   uschar **mid = bot + (top - bot)/2;
929   int c = Ustrcmp(name, *mid);
930   if (c == 0) return mid - table;
931   if (c > 0) bot = mid + 1; else top = mid;
932   }
933
934 return -1;
935 }
936
937
938
939 /*************************************************
940 *          Check a condition string              *
941 *************************************************/
942
943 /* This function is called to expand a string, and test the result for a "true"
944 or "false" value. Failure of the expansion yields FALSE; logged unless it was a
945 forced fail or lookup defer.
946
947 We used to release all store used, but this is not not safe due
948 to ${dlfunc } and ${acl }.  In any case expand_string_internal()
949 is reasonably careful to release what it can.
950
951 The actual false-value tests should be replicated for ECOND_BOOL_LAX.
952
953 Arguments:
954   condition     the condition string
955   m1            text to be incorporated in panic error
956   m2            ditto
957
958 Returns:        TRUE if condition is met, FALSE if not
959 */
960
961 BOOL
962 expand_check_condition(uschar *condition, uschar *m1, uschar *m2)
963 {
964 uschar * ss = expand_string(condition);
965 if (!ss)
966   {
967   if (!f.expand_string_forcedfail && !f.search_find_defer)
968     log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand condition \"%s\" "
969       "for %s %s: %s", condition, m1, m2, expand_string_message);
970   return FALSE;
971   }
972 return *ss && Ustrcmp(ss, "0") != 0 && strcmpic(ss, US"no") != 0 &&
973   strcmpic(ss, US"false") != 0;
974 }
975
976
977
978
979 /*************************************************
980 *        Pseudo-random number generation         *
981 *************************************************/
982
983 /* Pseudo-random number generation.  The result is not "expected" to be
984 cryptographically strong but not so weak that someone will shoot themselves
985 in the foot using it as a nonce in some email header scheme or whatever
986 weirdness they'll twist this into.  The result should ideally handle fork().
987
988 However, if we're stuck unable to provide this, then we'll fall back to
989 appallingly bad randomness.
990
991 If DISABLE_TLS is not defined then this will not be used except as an emergency
992 fallback.
993
994 Arguments:
995   max       range maximum
996 Returns     a random number in range [0, max-1]
997 */
998
999 #ifndef DISABLE_TLS
1000 # define vaguely_random_number vaguely_random_number_fallback
1001 #endif
1002 int
1003 vaguely_random_number(int max)
1004 {
1005 #ifndef DISABLE_TLS
1006 # undef vaguely_random_number
1007 #endif
1008 static pid_t pid = 0;
1009 pid_t p2;
1010
1011 if ((p2 = getpid()) != pid)
1012   {
1013   if (pid != 0)
1014     {
1015
1016 #ifdef HAVE_ARC4RANDOM
1017     /* cryptographically strong randomness, common on *BSD platforms, not
1018     so much elsewhere.  Alas. */
1019 # ifndef NOT_HAVE_ARC4RANDOM_STIR
1020     arc4random_stir();
1021 # endif
1022 #elif defined(HAVE_SRANDOM) || defined(HAVE_SRANDOMDEV)
1023 # ifdef HAVE_SRANDOMDEV
1024     /* uses random(4) for seeding */
1025     srandomdev();
1026 # else
1027     {
1028     struct timeval tv;
1029     gettimeofday(&tv, NULL);
1030     srandom(tv.tv_sec | tv.tv_usec | getpid());
1031     }
1032 # endif
1033 #else
1034     /* Poor randomness and no seeding here */
1035 #endif
1036
1037     }
1038   pid = p2;
1039   }
1040
1041 #ifdef HAVE_ARC4RANDOM
1042 return arc4random() % max;
1043 #elif defined(HAVE_SRANDOM) || defined(HAVE_SRANDOMDEV)
1044 return random() % max;
1045 #else
1046 /* This one returns a 16-bit number, definitely not crypto-strong */
1047 return random_number(max);
1048 #endif
1049 }
1050
1051
1052
1053
1054 /*************************************************
1055 *             Pick out a name from a string      *
1056 *************************************************/
1057
1058 /* If the name is too long, it is silently truncated.
1059
1060 Arguments:
1061   name      points to a buffer into which to put the name
1062   max       is the length of the buffer
1063   s         points to the first alphabetic character of the name
1064   extras    chars other than alphanumerics to permit
1065
1066 Returns:    pointer to the first character after the name
1067
1068 Note: The test for *s != 0 in the while loop is necessary because
1069 Ustrchr() yields non-NULL if the character is zero (which is not something
1070 I expected). */
1071
1072 static const uschar *
1073 read_name(uschar *name, int max, const uschar *s, uschar *extras)
1074 {
1075 int ptr = 0;
1076 while (*s && (isalnum(*s) || Ustrchr(extras, *s) != NULL))
1077   {
1078   if (ptr < max-1) name[ptr++] = *s;
1079   s++;
1080   }
1081 name[ptr] = 0;
1082 return s;
1083 }
1084
1085
1086
1087 /*************************************************
1088 *     Pick out the rest of a header name         *
1089 *************************************************/
1090
1091 /* A variable name starting $header_ (or just $h_ for those who like
1092 abbreviations) might not be the complete header name because headers can
1093 contain any printing characters in their names, except ':'. This function is
1094 called to read the rest of the name, chop h[eader]_ off the front, and put ':'
1095 on the end, if the name was terminated by white space.
1096
1097 Arguments:
1098   name      points to a buffer in which the name read so far exists
1099   max       is the length of the buffer
1100   s         points to the first character after the name so far, i.e. the
1101             first non-alphameric character after $header_xxxxx
1102
1103 Returns:    a pointer to the first character after the header name
1104 */
1105
1106 static const uschar *
1107 read_header_name(uschar *name, int max, const uschar *s)
1108 {
1109 int prelen = Ustrchr(name, '_') - name + 1;
1110 int ptr = Ustrlen(name) - prelen;
1111 if (ptr > 0) memmove(name, name+prelen, ptr);
1112 while (mac_isgraph(*s) && *s != ':')
1113   {
1114   if (ptr < max-1) name[ptr++] = *s;
1115   s++;
1116   }
1117 if (*s == ':') s++;
1118 name[ptr++] = ':';
1119 name[ptr] = 0;
1120 return s;
1121 }
1122
1123
1124
1125 /*************************************************
1126 *           Pick out a number from a string      *
1127 *************************************************/
1128
1129 /* Arguments:
1130   n     points to an integer into which to put the number
1131   s     points to the first digit of the number
1132
1133 Returns:  a pointer to the character after the last digit
1134 */
1135 /*XXX consider expanding to int_eximarith_t.  But the test for
1136 "overbig numbers" in 0002 still needs to overflow it. */
1137
1138 static uschar *
1139 read_number(int *n, uschar *s)
1140 {
1141 *n = 0;
1142 while (isdigit(*s)) *n = *n * 10 + (*s++ - '0');
1143 return s;
1144 }
1145
1146 static const uschar *
1147 read_cnumber(int *n, const uschar *s)
1148 {
1149 *n = 0;
1150 while (isdigit(*s)) *n = *n * 10 + (*s++ - '0');
1151 return s;
1152 }
1153
1154
1155
1156 /*************************************************
1157 *        Extract keyed subfield from a string    *
1158 *************************************************/
1159
1160 /* The yield is in dynamic store; NULL means that the key was not found.
1161
1162 Arguments:
1163   key       points to the name of the key
1164   s         points to the string from which to extract the subfield
1165
1166 Returns:    NULL if the subfield was not found, or
1167             a pointer to the subfield's data
1168 */
1169
1170 uschar *
1171 expand_getkeyed(const uschar * key, const uschar * s)
1172 {
1173 int length = Ustrlen(key);
1174 Uskip_whitespace(&s);
1175
1176 /* Loop to search for the key */
1177
1178 while (*s)
1179   {
1180   int dkeylength;
1181   uschar * data;
1182   const uschar * dkey = s;
1183
1184   while (*s && *s != '=' && !isspace(*s)) s++;
1185   dkeylength = s - dkey;
1186   if (Uskip_whitespace(&s) == '=') while (isspace(*++s));
1187
1188   data = string_dequote(&s);
1189   if (length == dkeylength && strncmpic(key, dkey, length) == 0)
1190     return data;
1191
1192   Uskip_whitespace(&s);
1193   }
1194
1195 return NULL;
1196 }
1197
1198
1199
1200 static var_entry *
1201 find_var_ent(uschar * name)
1202 {
1203 int first = 0;
1204 int last = var_table_size;
1205
1206 while (last > first)
1207   {
1208   int middle = (first + last)/2;
1209   int c = Ustrcmp(name, var_table[middle].name);
1210
1211   if (c > 0) { first = middle + 1; continue; }
1212   if (c < 0) { last = middle; continue; }
1213   return &var_table[middle];
1214   }
1215 return NULL;
1216 }
1217
1218 /*************************************************
1219 *   Extract numbered subfield from string        *
1220 *************************************************/
1221
1222 /* Extracts a numbered field from a string that is divided by tokens - for
1223 example a line from /etc/passwd is divided by colon characters.  First field is
1224 numbered one.  Negative arguments count from the right. Zero returns the whole
1225 string. Returns NULL if there are insufficient tokens in the string
1226
1227 ***WARNING***
1228 Modifies final argument - this is a dynamically generated string, so that's OK.
1229
1230 Arguments:
1231   field       number of field to be extracted,
1232                 first field = 1, whole string = 0, last field = -1
1233   separators  characters that are used to break string into tokens
1234   s           points to the string from which to extract the subfield
1235
1236 Returns:      NULL if the field was not found,
1237               a pointer to the field's data inside s (modified to add 0)
1238 */
1239
1240 static uschar *
1241 expand_gettokened (int field, uschar *separators, uschar *s)
1242 {
1243 int sep = 1;
1244 int count;
1245 uschar *ss = s;
1246 uschar *fieldtext = NULL;
1247
1248 if (field == 0) return s;
1249
1250 /* Break the line up into fields in place; for field > 0 we stop when we have
1251 done the number of fields we want. For field < 0 we continue till the end of
1252 the string, counting the number of fields. */
1253
1254 count = (field > 0)? field : INT_MAX;
1255
1256 while (count-- > 0)
1257   {
1258   size_t len;
1259
1260   /* Previous field was the last one in the string. For a positive field
1261   number, this means there are not enough fields. For a negative field number,
1262   check that there are enough, and scan back to find the one that is wanted. */
1263
1264   if (sep == 0)
1265     {
1266     if (field > 0 || (-field) > (INT_MAX - count - 1)) return NULL;
1267     if ((-field) == (INT_MAX - count - 1)) return s;
1268     while (field++ < 0)
1269       {
1270       ss--;
1271       while (ss[-1] != 0) ss--;
1272       }
1273     fieldtext = ss;
1274     break;
1275     }
1276
1277   /* Previous field was not last in the string; save its start and put a
1278   zero at its end. */
1279
1280   fieldtext = ss;
1281   len = Ustrcspn(ss, separators);
1282   sep = ss[len];
1283   ss[len] = 0;
1284   ss += len + 1;
1285   }
1286
1287 return fieldtext;
1288 }
1289
1290
1291 static uschar *
1292 expand_getlistele(int field, const uschar * list)
1293 {
1294 const uschar * tlist = list;
1295 int sep = 0;
1296 /* Tainted mem for the throwaway element copies */
1297 uschar * dummy = store_get(2, GET_TAINTED);
1298
1299 if (field < 0)
1300   {
1301   for (field++; string_nextinlist(&tlist, &sep, dummy, 1); ) field++;
1302   sep = 0;
1303   }
1304 if (field == 0) return NULL;
1305 while (--field > 0 && (string_nextinlist(&list, &sep, dummy, 1))) ;
1306 return string_nextinlist(&list, &sep, NULL, 0);
1307 }
1308
1309
1310 /* Certificate fields, by name.  Worry about by-OID later */
1311 /* Names are chosen to not have common prefixes */
1312
1313 #ifndef DISABLE_TLS
1314 typedef struct
1315 {
1316 uschar * name;
1317 int      namelen;
1318 uschar * (*getfn)(void * cert, uschar * mod);
1319 } certfield;
1320 static certfield certfields[] =
1321 {                       /* linear search; no special order */
1322   { US"version",         7,  &tls_cert_version },
1323   { US"serial_number",   13, &tls_cert_serial_number },
1324   { US"subject",         7,  &tls_cert_subject },
1325   { US"notbefore",       9,  &tls_cert_not_before },
1326   { US"notafter",        8,  &tls_cert_not_after },
1327   { US"issuer",          6,  &tls_cert_issuer },
1328   { US"signature",       9,  &tls_cert_signature },
1329   { US"sig_algorithm",   13, &tls_cert_signature_algorithm },
1330   { US"subj_altname",    12, &tls_cert_subject_altname },
1331   { US"ocsp_uri",        8,  &tls_cert_ocsp_uri },
1332   { US"crl_uri",         7,  &tls_cert_crl_uri },
1333 };
1334
1335 static uschar *
1336 expand_getcertele(uschar * field, uschar * certvar)
1337 {
1338 var_entry * vp;
1339
1340 if (!(vp = find_var_ent(certvar)))
1341   {
1342   expand_string_message =
1343     string_sprintf("no variable named \"%s\"", certvar);
1344   return NULL;          /* Unknown variable name */
1345   }
1346 /* NB this stops us passing certs around in variable.  Might
1347 want to do that in future */
1348 if (vp->type != vtype_cert)
1349   {
1350   expand_string_message =
1351     string_sprintf("\"%s\" is not a certificate", certvar);
1352   return NULL;          /* Unknown variable name */
1353   }
1354 if (!*(void **)vp->value)
1355   return NULL;
1356
1357 if (*field >= '0' && *field <= '9')
1358   return tls_cert_ext_by_oid(*(void **)vp->value, field, 0);
1359
1360 for (certfield * cp = certfields;
1361      cp < certfields + nelem(certfields);
1362      cp++)
1363   if (Ustrncmp(cp->name, field, cp->namelen) == 0)
1364     {
1365     uschar * modifier = *(field += cp->namelen) == ','
1366       ? ++field : NULL;
1367     return (*cp->getfn)( *(void **)vp->value, modifier );
1368     }
1369
1370 expand_string_message =
1371   string_sprintf("bad field selector \"%s\" for certextract", field);
1372 return NULL;
1373 }
1374 #endif  /*DISABLE_TLS*/
1375
1376 /*************************************************
1377 *        Extract a substring from a string       *
1378 *************************************************/
1379
1380 /* Perform the ${substr or ${length expansion operations.
1381
1382 Arguments:
1383   subject     the input string
1384   value1      the offset from the start of the input string to the start of
1385                 the output string; if negative, count from the right.
1386   value2      the length of the output string, or negative (-1) for unset
1387                 if value1 is positive, unset means "all after"
1388                 if value1 is negative, unset means "all before"
1389   len         set to the length of the returned string
1390
1391 Returns:      pointer to the output string, or NULL if there is an error
1392 */
1393
1394 static uschar *
1395 extract_substr(uschar *subject, int value1, int value2, int *len)
1396 {
1397 int sublen = Ustrlen(subject);
1398
1399 if (value1 < 0)    /* count from right */
1400   {
1401   value1 += sublen;
1402
1403   /* If the position is before the start, skip to the start, and adjust the
1404   length. If the length ends up negative, the substring is null because nothing
1405   can precede. This falls out naturally when the length is unset, meaning "all
1406   to the left". */
1407
1408   if (value1 < 0)
1409     {
1410     value2 += value1;
1411     if (value2 < 0) value2 = 0;
1412     value1 = 0;
1413     }
1414
1415   /* Otherwise an unset length => characters before value1 */
1416
1417   else if (value2 < 0)
1418     {
1419     value2 = value1;
1420     value1 = 0;
1421     }
1422   }
1423
1424 /* For a non-negative offset, if the starting position is past the end of the
1425 string, the result will be the null string. Otherwise, an unset length means
1426 "rest"; just set it to the maximum - it will be cut down below if necessary. */
1427
1428 else
1429   {
1430   if (value1 > sublen)
1431     {
1432     value1 = sublen;
1433     value2 = 0;
1434     }
1435   else if (value2 < 0) value2 = sublen;
1436   }
1437
1438 /* Cut the length down to the maximum possible for the offset value, and get
1439 the required characters. */
1440
1441 if (value1 + value2 > sublen) value2 = sublen - value1;
1442 *len = value2;
1443 return subject + value1;
1444 }
1445
1446
1447
1448
1449 /*************************************************
1450 *            Old-style hash of a string          *
1451 *************************************************/
1452
1453 /* Perform the ${hash expansion operation.
1454
1455 Arguments:
1456   subject     the input string (an expanded substring)
1457   value1      the length of the output string; if greater or equal to the
1458                 length of the input string, the input string is returned
1459   value2      the number of hash characters to use, or 26 if negative
1460   len         set to the length of the returned string
1461
1462 Returns:      pointer to the output string, or NULL if there is an error
1463 */
1464
1465 static uschar *
1466 compute_hash(uschar *subject, int value1, int value2, int *len)
1467 {
1468 int sublen = Ustrlen(subject);
1469
1470 if (value2 < 0) value2 = 26;
1471 else if (value2 > Ustrlen(hashcodes))
1472   {
1473   expand_string_message =
1474     string_sprintf("hash count \"%d\" too big", value2);
1475   return NULL;
1476   }
1477
1478 /* Calculate the hash text. We know it is shorter than the original string, so
1479 can safely place it in subject[] (we know that subject is always itself an
1480 expanded substring). */
1481
1482 if (value1 < sublen)
1483   {
1484   int c;
1485   int i = 0;
1486   int j = value1;
1487   while ((c = (subject[j])) != 0)
1488     {
1489     int shift = (c + j++) & 7;
1490     subject[i] ^= (c << shift) | (c >> (8-shift));
1491     if (++i >= value1) i = 0;
1492     }
1493   for (i = 0; i < value1; i++)
1494     subject[i] = hashcodes[(subject[i]) % value2];
1495   }
1496 else value1 = sublen;
1497
1498 *len = value1;
1499 return subject;
1500 }
1501
1502
1503
1504
1505 /*************************************************
1506 *             Numeric hash of a string           *
1507 *************************************************/
1508
1509 /* Perform the ${nhash expansion operation. The first characters of the
1510 string are treated as most important, and get the highest prime numbers.
1511
1512 Arguments:
1513   subject     the input string
1514   value1      the maximum value of the first part of the result
1515   value2      the maximum value of the second part of the result,
1516                 or negative to produce only a one-part result
1517   len         set to the length of the returned string
1518
1519 Returns:  pointer to the output string, or NULL if there is an error.
1520 */
1521
1522 static uschar *
1523 compute_nhash (uschar *subject, int value1, int value2, int *len)
1524 {
1525 uschar *s = subject;
1526 int i = 0;
1527 unsigned long int total = 0; /* no overflow */
1528
1529 while (*s != 0)
1530   {
1531   if (i == 0) i = nelem(prime) - 1;
1532   total += prime[i--] * (unsigned int)(*s++);
1533   }
1534
1535 /* If value2 is unset, just compute one number */
1536
1537 if (value2 < 0)
1538   s = string_sprintf("%lu", total % value1);
1539
1540 /* Otherwise do a div/mod hash */
1541
1542 else
1543   {
1544   total = total % (value1 * value2);
1545   s = string_sprintf("%lu/%lu", total/value2, total % value2);
1546   }
1547
1548 *len = Ustrlen(s);
1549 return s;
1550 }
1551
1552
1553
1554
1555
1556 /*************************************************
1557 *     Find the value of a header or headers      *
1558 *************************************************/
1559
1560 /* Multiple instances of the same header get concatenated, and this function
1561 can also return a concatenation of all the header lines. When concatenating
1562 specific headers that contain lists of addresses, a comma is inserted between
1563 them. Otherwise we use a straight concatenation. Because some messages can have
1564 pathologically large number of lines, there is a limit on the length that is
1565 returned.
1566
1567 Arguments:
1568   name          the name of the header, without the leading $header_ or $h_,
1569                 or NULL if a concatenation of all headers is required
1570   newsize       return the size of memory block that was obtained; may be NULL
1571                 if exists_only is TRUE
1572   flags         FH_EXISTS_ONLY
1573                   set if called from a def: test; don't need to build a string;
1574                   just return a string that is not "" and not "0" if the header
1575                   exists
1576                 FH_WANT_RAW
1577                   set if called for $rh_ or $rheader_ items; no processing,
1578                   other than concatenating, will be done on the header. Also used
1579                   for $message_headers_raw.
1580                 FH_WANT_LIST
1581                   Double colon chars in the content, and replace newline with
1582                   colon between each element when concatenating; returning a
1583                   colon-sep list (elements might contain newlines)
1584   charset       name of charset to translate MIME words to; used only if
1585                 want_raw is false; if NULL, no translation is done (this is
1586                 used for $bh_ and $bheader_)
1587
1588 Returns:        NULL if the header does not exist, else a pointer to a new
1589                 store block
1590 */
1591
1592 static uschar *
1593 find_header(uschar *name, int *newsize, unsigned flags, const uschar *charset)
1594 {
1595 BOOL found = !name;
1596 int len = name ? Ustrlen(name) : 0;
1597 BOOL comma = FALSE;
1598 gstring * g = NULL;
1599
1600 for (header_line * h = header_list; h; h = h->next)
1601   if (h->type != htype_old && h->text)  /* NULL => Received: placeholder */
1602     if (!name || (len <= h->slen && strncmpic(name, h->text, len) == 0))
1603       {
1604       uschar * s, * t;
1605       size_t inc;
1606
1607       if (flags & FH_EXISTS_ONLY)
1608         return US"1";  /* don't need actual string */
1609
1610       found = TRUE;
1611       s = h->text + len;                /* text to insert */
1612       if (!(flags & FH_WANT_RAW))       /* unless wanted raw, */
1613         Uskip_whitespace(&s);           /* remove leading white space */
1614       t = h->text + h->slen;            /* end-point */
1615
1616       /* Unless wanted raw, remove trailing whitespace, including the
1617       newline. */
1618
1619       if (flags & FH_WANT_LIST)
1620         while (t > s && t[-1] == '\n') t--;
1621       else if (!(flags & FH_WANT_RAW))
1622         {
1623         while (t > s && isspace(t[-1])) t--;
1624
1625         /* Set comma if handling a single header and it's one of those
1626         that contains an address list, except when asked for raw headers. Only
1627         need to do this once. */
1628
1629         if (name && !comma && Ustrchr("BCFRST", h->type)) comma = TRUE;
1630         }
1631
1632       /* Trim the header roughly if we're approaching limits */
1633       inc = t - s;
1634       if (gstring_length(g) + inc > header_insert_maxlen)
1635         inc = header_insert_maxlen - gstring_length(g);
1636
1637       /* For raw just copy the data; for a list, add the data as a colon-sep
1638       list-element; for comma-list add as an unchecked comma,newline sep
1639       list-elemment; for other nonraw add as an unchecked newline-sep list (we
1640       stripped trailing WS above including the newline). We ignore the potential
1641       expansion due to colon-doubling, just leaving the loop if the limit is met
1642       or exceeded. */
1643
1644       if (flags & FH_WANT_LIST)
1645         g = string_append_listele_n(g, ':', s, (unsigned)inc);
1646       else if (flags & FH_WANT_RAW)
1647         g = string_catn(g, s, (unsigned)inc);
1648       else if (inc > 0)
1649         g = string_append2_listele_n(g, comma ? US",\n" : US"\n",
1650           s, (unsigned)inc);
1651
1652       if (gstring_length(g) >= header_insert_maxlen) break;
1653       }
1654
1655 if (!found) return NULL;        /* No header found */
1656 if (!g) return US"";
1657
1658 /* That's all we do for raw header expansion. */
1659
1660 *newsize = g->size;
1661 if (flags & FH_WANT_RAW)
1662   return string_from_gstring(g);
1663
1664 /* Otherwise do RFC 2047 decoding, translating the charset if requested.
1665 The rfc2047_decode2() function can return an error with decoded data if the
1666 charset translation fails. If decoding fails, it returns NULL. */
1667
1668 else
1669   {
1670   uschar * error, * decoded = rfc2047_decode2(string_from_gstring(g),
1671     check_rfc2047_length, charset, '?', NULL, newsize, &error);
1672   if (error)
1673     DEBUG(D_any) debug_printf("*** error in RFC 2047 decoding: %s\n"
1674       "    input was: %s\n", error, g->s);
1675   return decoded ? decoded : string_from_gstring(g);
1676   }
1677 }
1678
1679
1680
1681
1682 /* Append a "local" element to an Authentication-Results: header
1683 if this was a non-smtp message.
1684 */
1685
1686 static gstring *
1687 authres_local(gstring * g, const uschar * sysname)
1688 {
1689 if (!f.authentication_local)
1690   return g;
1691 g = string_append(g, 3, US";\n\tlocal=pass (non-smtp, ", sysname, US")");
1692 if (authenticated_id) g = string_append(g, 2, " u=", authenticated_id);
1693 return g;
1694 }
1695
1696
1697 /* Append an "iprev" element to an Authentication-Results: header
1698 if we have attempted to get the calling host's name.
1699 */
1700
1701 static gstring *
1702 authres_iprev(gstring * g)
1703 {
1704 if (sender_host_name)
1705   g = string_append(g, 3, US";\n\tiprev=pass (", sender_host_name, US")");
1706 else if (host_lookup_deferred)
1707   g = string_cat(g, US";\n\tiprev=temperror");
1708 else if (host_lookup_failed)
1709   g = string_cat(g, US";\n\tiprev=fail");
1710 else
1711   return g;
1712
1713 if (sender_host_address)
1714   g = string_append(g, 2, US" smtp.remote-ip=", sender_host_address);
1715 return g;
1716 }
1717
1718
1719
1720 /*************************************************
1721 *               Return list of recipients        *
1722 *************************************************/
1723 /* A recipients list is available only during system message filtering,
1724 during ACL processing after DATA, and while expanding pipe commands
1725 generated from a system filter, but not elsewhere. */
1726
1727 static uschar *
1728 fn_recipients(void)
1729 {
1730 uschar * s;
1731 gstring * g = NULL;
1732
1733 if (!f.enable_dollar_recipients) return NULL;
1734
1735 for (int i = 0; i < recipients_count; i++)
1736   {
1737   s = recipients_list[i].address;
1738   g = string_append2_listele_n(g, US", ", s, Ustrlen(s));
1739   }
1740 return g ? g->s : NULL;
1741 }
1742
1743
1744 /*************************************************
1745 *               Return size of queue             *
1746 *************************************************/
1747 /* Ask the daemon for the queue size */
1748
1749 static uschar *
1750 fn_queue_size(void)
1751 {
1752 struct sockaddr_un sa_un = {.sun_family = AF_UNIX};
1753 uschar buf[16];
1754 int fd;
1755 ssize_t len;
1756 const uschar * where;
1757 uschar * sname;
1758
1759 if ((fd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0)
1760   {
1761   DEBUG(D_expand) debug_printf(" socket: %s\n", strerror(errno));
1762   return NULL;
1763   }
1764
1765 len = daemon_client_sockname(&sa_un, &sname);
1766
1767 if (bind(fd, (const struct sockaddr *)&sa_un, (socklen_t)len) < 0)
1768   { where = US"bind"; goto bad; }
1769
1770 #ifdef notdef
1771 debug_printf("local addr '%s%s'\n",
1772   *sa_un.sun_path ? "" : "@",
1773   sa_un.sun_path + (*sa_un.sun_path ? 0 : 1));
1774 #endif
1775
1776 len = daemon_notifier_sockname(&sa_un);
1777 if (connect(fd, (const struct sockaddr *)&sa_un, len) < 0)
1778   { where = US"connect"; goto bad2; }
1779
1780 buf[0] = NOTIFY_QUEUE_SIZE_REQ;
1781 if (send(fd, buf, 1, 0) < 0) { where = US"send"; goto bad; }
1782
1783 if (poll_one_fd(fd, POLLIN, 2 * 1000) != 1)
1784   {
1785   DEBUG(D_expand) debug_printf("no daemon response; using local evaluation\n");
1786   len = snprintf(CS buf, sizeof(buf), "%u", queue_count_cached());
1787   }
1788 else if ((len = recv(fd, buf, sizeof(buf), 0)) < 0)
1789   { where = US"recv"; goto bad2; }
1790
1791 close(fd);
1792 #ifndef EXIM_HAVE_ABSTRACT_UNIX_SOCKETS
1793 Uunlink(sname);
1794 #endif
1795 return string_copyn(buf, len);
1796
1797 bad2:
1798 #ifndef EXIM_HAVE_ABSTRACT_UNIX_SOCKETS
1799   Uunlink(sname);
1800 #endif
1801 bad:
1802   close(fd);
1803   DEBUG(D_expand) debug_printf(" %s: %s\n", where, strerror(errno));
1804   return NULL;
1805 }
1806
1807
1808 /*************************************************
1809 *               Find value of a variable         *
1810 *************************************************/
1811
1812 /* The table of variables is kept in alphabetic order, so we can search it
1813 using a binary chop. The "choplen" variable is nothing to do with the binary
1814 chop.
1815
1816 Arguments:
1817   name          the name of the variable being sought
1818   exists_only   TRUE if this is a def: test; passed on to find_header()
1819   skipping      TRUE => skip any processing evaluation; this is not the same as
1820                   exists_only because def: may test for values that are first
1821                   evaluated here
1822   newsize       pointer to an int which is initially zero; if the answer is in
1823                 a new memory buffer, *newsize is set to its size
1824
1825 Returns:        NULL if the variable does not exist, or
1826                 a pointer to the variable's contents, or
1827                 something non-NULL if exists_only is TRUE
1828 */
1829
1830 static const uschar *
1831 find_variable(uschar *name, BOOL exists_only, BOOL skipping, int *newsize)
1832 {
1833 var_entry * vp;
1834 uschar *s, *domain;
1835 uschar **ss;
1836 void * val;
1837
1838 /* Handle ACL variables, whose names are of the form acl_cxxx or acl_mxxx.
1839 Originally, xxx had to be a number in the range 0-9 (later 0-19), but from
1840 release 4.64 onwards arbitrary names are permitted, as long as the first 5
1841 characters are acl_c or acl_m and the sixth is either a digit or an underscore
1842 (this gave backwards compatibility at the changeover). There may be built-in
1843 variables whose names start acl_ but they should never start in this way. This
1844 slightly messy specification is a consequence of the history, needless to say.
1845
1846 If an ACL variable does not exist, treat it as empty, unless strict_acl_vars is
1847 set, in which case give an error. */
1848
1849 if ((Ustrncmp(name, "acl_c", 5) == 0 || Ustrncmp(name, "acl_m", 5) == 0) &&
1850      !isalpha(name[5]))
1851   {
1852   tree_node * node =
1853     tree_search(name[4] == 'c' ? acl_var_c : acl_var_m, name + 4);
1854   return node ? node->data.ptr : strict_acl_vars ? NULL : US"";
1855   }
1856 else if (Ustrncmp(name, "r_", 2) == 0)
1857   {
1858   tree_node * node = tree_search(router_var, name + 2);
1859   return node ? node->data.ptr : strict_acl_vars ? NULL : US"";
1860   }
1861
1862 /* Handle $auth<n> variables. */
1863
1864 if (Ustrncmp(name, "auth", 4) == 0)
1865   {
1866   uschar *endptr;
1867   int n = Ustrtoul(name + 4, &endptr, 10);
1868   if (!*endptr && n != 0 && n <= AUTH_VARS)
1869     return auth_vars[n-1] ? auth_vars[n-1] : US"";
1870   }
1871 else if (Ustrncmp(name, "regex", 5) == 0)
1872   {
1873   uschar *endptr;
1874   int n = Ustrtoul(name + 5, &endptr, 10);
1875   if (!*endptr && n != 0 && n <= REGEX_VARS)
1876     return regex_vars[n-1] ? regex_vars[n-1] : US"";
1877   }
1878
1879 /* For all other variables, search the table */
1880
1881 if (!(vp = find_var_ent(name)))
1882   return NULL;          /* Unknown variable name */
1883
1884 /* Found an existing variable. If in skipping state, the value isn't needed,
1885 and we want to avoid processing (such as looking up the host name). */
1886
1887 if (skipping)
1888   return US"";
1889
1890 val = vp->value;
1891 switch (vp->type)
1892   {
1893   case vtype_filter_int:
1894     if (!f.filter_running) return NULL;
1895     /* Fall through */
1896     /* VVVVVVVVVVVV */
1897   case vtype_int:
1898     sprintf(CS var_buffer, "%d", *(int *)(val)); /* Integer */
1899     return var_buffer;
1900
1901   case vtype_ino:
1902     sprintf(CS var_buffer, "%ld", (long int)(*(ino_t *)(val))); /* Inode */
1903     return var_buffer;
1904
1905   case vtype_gid:
1906     sprintf(CS var_buffer, "%ld", (long int)(*(gid_t *)(val))); /* gid */
1907     return var_buffer;
1908
1909   case vtype_uid:
1910     sprintf(CS var_buffer, "%ld", (long int)(*(uid_t *)(val))); /* uid */
1911     return var_buffer;
1912
1913   case vtype_bool:
1914     sprintf(CS var_buffer, "%s", *(BOOL *)(val) ? "yes" : "no"); /* bool */
1915     return var_buffer;
1916
1917   case vtype_stringptr:                      /* Pointer to string */
1918     return (s = *((uschar **)(val))) ? s : US"";
1919
1920   case vtype_pid:
1921     sprintf(CS var_buffer, "%d", (int)getpid()); /* pid */
1922     return var_buffer;
1923
1924   case vtype_load_avg:
1925     sprintf(CS var_buffer, "%d", OS_GETLOADAVG()); /* load_average */
1926     return var_buffer;
1927
1928   case vtype_host_lookup:                    /* Lookup if not done so */
1929     if (  !sender_host_name && sender_host_address
1930        && !host_lookup_failed && host_name_lookup() == OK)
1931       host_build_sender_fullhost();
1932     return sender_host_name ? sender_host_name : US"";
1933
1934   case vtype_localpart:                      /* Get local part from address */
1935     if (!(s = *((uschar **)(val)))) return US"";
1936     if (!(domain = Ustrrchr(s, '@'))) return s;
1937     if (domain - s > sizeof(var_buffer) - 1)
1938       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "local part longer than " SIZE_T_FMT
1939           " in string expansion", sizeof(var_buffer));
1940     return string_copyn(s, domain - s);
1941
1942   case vtype_domain:                         /* Get domain from address */
1943     if (!(s = *((uschar **)(val)))) return US"";
1944     domain = Ustrrchr(s, '@');
1945     return domain ? domain + 1 : US"";
1946
1947   case vtype_msgheaders:
1948     return find_header(NULL, newsize, exists_only ? FH_EXISTS_ONLY : 0, NULL);
1949
1950   case vtype_msgheaders_raw:
1951     return find_header(NULL, newsize,
1952                 exists_only ? FH_EXISTS_ONLY|FH_WANT_RAW : FH_WANT_RAW, NULL);
1953
1954   case vtype_msgbody:                        /* Pointer to msgbody string */
1955   case vtype_msgbody_end:                    /* Ditto, the end of the msg */
1956     ss = (uschar **)(val);
1957     if (!*ss && deliver_datafile >= 0)  /* Read body when needed */
1958       {
1959       uschar * body;
1960       off_t start_offset = SPOOL_DATA_START_OFFSET;
1961       int len = message_body_visible;
1962
1963       if (len > message_size) len = message_size;
1964       *ss = body = store_get(len+1, GET_TAINTED);
1965       body[0] = 0;
1966       if (vp->type == vtype_msgbody_end)
1967         {
1968         struct stat statbuf;
1969         if (fstat(deliver_datafile, &statbuf) == 0)
1970           {
1971           start_offset = statbuf.st_size - len;
1972           if (start_offset < SPOOL_DATA_START_OFFSET)
1973             start_offset = SPOOL_DATA_START_OFFSET;
1974           }
1975         }
1976       if (lseek(deliver_datafile, start_offset, SEEK_SET) < 0)
1977         log_write(0, LOG_MAIN|LOG_PANIC_DIE, "deliver_datafile lseek: %s",
1978           strerror(errno));
1979       if ((len = read(deliver_datafile, body, len)) > 0)
1980         {
1981         body[len] = 0;
1982         if (message_body_newlines)   /* Separate loops for efficiency */
1983           while (len > 0)
1984             { if (body[--len] == 0) body[len] = ' '; }
1985         else
1986           while (len > 0)
1987             { if (body[--len] == '\n' || body[len] == 0) body[len] = ' '; }
1988         }
1989       }
1990     return *ss ? *ss : US"";
1991
1992   case vtype_todbsdin:                       /* BSD inbox time of day */
1993     return tod_stamp(tod_bsdin);
1994
1995   case vtype_tode:                           /* Unix epoch time of day */
1996     return tod_stamp(tod_epoch);
1997
1998   case vtype_todel:                          /* Unix epoch/usec time of day */
1999     return tod_stamp(tod_epoch_l);
2000
2001   case vtype_todf:                           /* Full time of day */
2002     return tod_stamp(tod_full);
2003
2004   case vtype_todl:                           /* Log format time of day */
2005     return tod_stamp(tod_log_bare);            /* (without timezone) */
2006
2007   case vtype_todzone:                        /* Time zone offset only */
2008     return tod_stamp(tod_zone);
2009
2010   case vtype_todzulu:                        /* Zulu time */
2011     return tod_stamp(tod_zulu);
2012
2013   case vtype_todlf:                          /* Log file datestamp tod */
2014     return tod_stamp(tod_log_datestamp_daily);
2015
2016   case vtype_reply:                          /* Get reply address */
2017     s = find_header(US"reply-to:", newsize,
2018                 exists_only ? FH_EXISTS_ONLY|FH_WANT_RAW : FH_WANT_RAW,
2019                 headers_charset);
2020     if (s) Uskip_whitespace(&s);
2021     if (!s || !*s)
2022       {
2023       *newsize = 0;                            /* For the *s==0 case */
2024       s = find_header(US"from:", newsize,
2025                 exists_only ? FH_EXISTS_ONLY|FH_WANT_RAW : FH_WANT_RAW,
2026                 headers_charset);
2027       }
2028     if (s)
2029       {
2030       uschar *t;
2031       Uskip_whitespace(&s);
2032       for (t = s; *t; t++) if (*t == '\n') *t = ' ';
2033       while (t > s && isspace(t[-1])) t--;
2034       *t = 0;
2035       }
2036     return s ? s : US"";
2037
2038   case vtype_string_func:
2039     {
2040     stringptr_fn_t * fn = (stringptr_fn_t *) val;
2041     uschar* s = fn();
2042     return s ? s : US"";
2043     }
2044
2045   case vtype_pspace:
2046     {
2047     int inodes;
2048     sprintf(CS var_buffer, PR_EXIM_ARITH,
2049       receive_statvfs(val == (void *)TRUE, &inodes));
2050     }
2051   return var_buffer;
2052
2053   case vtype_pinodes:
2054     {
2055     int inodes;
2056     (void) receive_statvfs(val == (void *)TRUE, &inodes);
2057     sprintf(CS var_buffer, "%d", inodes);
2058     }
2059   return var_buffer;
2060
2061   case vtype_cert:
2062     return *(void **)val ? US"<cert>" : US"";
2063
2064 #ifndef DISABLE_DKIM
2065   case vtype_dkim:
2066     return dkim_exim_expand_query((int)(long)val);
2067 #endif
2068
2069   }
2070
2071 return NULL;  /* Unknown variable. Silences static checkers. */
2072 }
2073
2074
2075
2076
2077 void
2078 modify_variable(uschar *name, void * value)
2079 {
2080 var_entry * vp;
2081 if ((vp = find_var_ent(name))) vp->value = value;
2082 return;          /* Unknown variable name, fail silently */
2083 }
2084
2085
2086
2087
2088
2089
2090 /*************************************************
2091 *           Read and expand substrings           *
2092 *************************************************/
2093
2094 /* This function is called to read and expand argument substrings for various
2095 expansion items. Some have a minimum requirement that is less than the maximum;
2096 in these cases, the first non-present one is set to NULL.
2097
2098 Arguments:
2099   sub        points to vector of pointers to set
2100   n          maximum number of substrings
2101   m          minimum required
2102   sptr       points to current string pointer
2103   flags
2104    skipping   the skipping flag
2105   check_end  if TRUE, check for final '}'
2106   name       name of item, for error message
2107   resetok    if not NULL, pointer to flag - write FALSE if unsafe to reset
2108              the store
2109   textonly_p if not NULL, pointer to bitmask of which subs were text-only
2110              (did not change when expended)
2111
2112 Returns:     -1 OK; string pointer updated, but in "skipping" mode
2113              0 OK; string pointer updated
2114              1 curly bracketing error (too few arguments)
2115              2 too many arguments (only if check_end is set); message set
2116              3 other error (expansion failure)
2117 */
2118
2119 static int
2120 read_subs(uschar ** sub, int n, int m, const uschar ** sptr, esi_flags flags,
2121   BOOL check_end, uschar * name, BOOL * resetok, unsigned * textonly_p)
2122 {
2123 const uschar * s = *sptr;
2124 unsigned textonly_l = 0;
2125
2126 Uskip_whitespace(&s);
2127 for (int i = 0; i < n; i++)
2128   {
2129   BOOL textonly;
2130   if (*s != '{')
2131     {
2132     if (i < m)
2133       {
2134       expand_string_message = string_sprintf("Not enough arguments for '%s' "
2135         "(min is %d)", name, m);
2136       return 1;
2137       }
2138     sub[i] = NULL;
2139     break;
2140     }
2141   if (!(sub[i] = expand_string_internal(s+1,
2142           ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | flags & ESI_SKIPPING, &s, resetok,
2143           textonly_p ? &textonly : NULL)))
2144     return 3;
2145   if (*s++ != '}') return 1;
2146   if (textonly_p && textonly) textonly_l |= BIT(i);
2147   Uskip_whitespace(&s);
2148   }                                             /*{*/
2149 if (check_end && *s++ != '}')
2150   {
2151   if (s[-1] == '{')
2152     {
2153     expand_string_message = string_sprintf("Too many arguments for '%s' "
2154       "(max is %d)", name, n);
2155     return 2;
2156     }
2157   expand_string_message = string_sprintf("missing '}' after '%s'", name);
2158   return 1;
2159   }
2160
2161 if (textonly_p) *textonly_p = textonly_l;
2162 *sptr = s;
2163 return flags & ESI_SKIPPING ? -1 : 0;
2164 }
2165
2166
2167
2168
2169 /*************************************************
2170 *     Elaborate message for bad variable         *
2171 *************************************************/
2172
2173 /* For the "unknown variable" message, take a look at the variable's name, and
2174 give additional information about possible ACL variables. The extra information
2175 is added on to expand_string_message.
2176
2177 Argument:   the name of the variable
2178 Returns:    nothing
2179 */
2180
2181 static void
2182 check_variable_error_message(uschar *name)
2183 {
2184 if (Ustrncmp(name, "acl_", 4) == 0)
2185   expand_string_message = string_sprintf("%s (%s)", expand_string_message,
2186     (name[4] == 'c' || name[4] == 'm')?
2187       (isalpha(name[5])?
2188         US"6th character of a user-defined ACL variable must be a digit or underscore" :
2189         US"strict_acl_vars is set"    /* Syntax is OK, it has to be this */
2190       ) :
2191       US"user-defined ACL variables must start acl_c or acl_m");
2192 }
2193
2194
2195
2196 /*
2197 Load args from sub array to globals, and call acl_check().
2198 Sub array will be corrupted on return.
2199
2200 Returns:       OK         access is granted by an ACCEPT verb
2201                DISCARD    access is (apparently) granted by a DISCARD verb
2202                FAIL       access is denied
2203                FAIL_DROP  access is denied; drop the connection
2204                DEFER      can't tell at the moment
2205                ERROR      disaster
2206 */
2207 static int
2208 eval_acl(uschar ** sub, int nsub, uschar ** user_msgp)
2209 {
2210 int i;
2211 int sav_narg = acl_narg;
2212 int ret;
2213 uschar * dummy_logmsg;
2214 extern int acl_where;
2215
2216 if(--nsub > nelem(acl_arg)) nsub = nelem(acl_arg);
2217 for (i = 0; i < nsub && sub[i+1]; i++)
2218   {
2219   uschar * tmp = acl_arg[i];
2220   acl_arg[i] = sub[i+1];        /* place callers args in the globals */
2221   sub[i+1] = tmp;               /* stash the old args using our caller's storage */
2222   }
2223 acl_narg = i;
2224 while (i < nsub)
2225   {
2226   sub[i+1] = acl_arg[i];
2227   acl_arg[i++] = NULL;
2228   }
2229
2230 DEBUG(D_expand)
2231   debug_printf_indent("expanding: acl: %s  arg: %s%s\n",
2232     sub[0],
2233     acl_narg>0 ? acl_arg[0] : US"<none>",
2234     acl_narg>1 ? " +more"   : "");
2235
2236 ret = acl_eval(acl_where, sub[0], user_msgp, &dummy_logmsg);
2237
2238 for (i = 0; i < nsub; i++)
2239   acl_arg[i] = sub[i+1];        /* restore old args */
2240 acl_narg = sav_narg;
2241
2242 return ret;
2243 }
2244
2245
2246
2247
2248 /* Return pointer to dewrapped string, with enclosing specified chars removed.
2249 The given string is modified on return.  Leading whitespace is skipped while
2250 looking for the opening wrap character, then the rest is scanned for the trailing
2251 (non-escaped) wrap character.  A backslash in the string will act as an escape.
2252
2253 A nul is written over the trailing wrap, and a pointer to the char after the
2254 leading wrap is returned.
2255
2256 Arguments:
2257   s     String for de-wrapping
2258   wrap  Two-char string, the first being the opener, second the closer wrapping
2259         character
2260 Return:
2261   Pointer to de-wrapped string, or NULL on error (with expand_string_message set).
2262 */
2263
2264 static uschar *
2265 dewrap(uschar * s, const uschar * wrap)
2266 {
2267 uschar * p = s;
2268 unsigned depth = 0;
2269 BOOL quotesmode = wrap[0] == wrap[1];
2270
2271 if (Uskip_whitespace(&p) == *wrap)
2272   {
2273   s = ++p;
2274   wrap++;
2275   while (*p)
2276     {
2277     if (*p == '\\') p++;
2278     else if (!quotesmode && *p == wrap[-1]) depth++;
2279     else if (*p == *wrap)
2280       if (depth == 0)
2281         {
2282         *p = '\0';
2283         return s;
2284         }
2285       else
2286         depth--;
2287     p++;
2288     }
2289   }
2290 expand_string_message = string_sprintf("missing '%c'", *wrap);
2291 return NULL;
2292 }
2293
2294
2295 /* Pull off the leading array or object element, returning
2296 a copy in an allocated string.  Update the list pointer.
2297
2298 The element may itself be an abject or array.
2299 Return NULL when the list is empty.
2300 */
2301
2302 static uschar *
2303 json_nextinlist(const uschar ** list)
2304 {
2305 unsigned array_depth = 0, object_depth = 0;
2306 const uschar * s = *list, * item;
2307
2308 skip_whitespace(&s);
2309
2310 for (item = s;
2311      *s && (*s != ',' || array_depth != 0 || object_depth != 0);
2312      s++)
2313   switch (*s)
2314     {
2315     case '[': array_depth++; break;
2316     case ']': array_depth--; break;
2317     case '{': object_depth++; break;
2318     case '}': object_depth--; break;
2319     }
2320 *list = *s ? s+1 : s;
2321 if (item == s) return NULL;
2322 item = string_copyn(item, s - item);
2323 DEBUG(D_expand) debug_printf_indent("  json ele: '%s'\n", item);
2324 return US item;
2325 }
2326
2327
2328
2329 /************************************************/
2330 /*  Return offset in ops table, or -1 if not found.
2331 Repoint to just after the operator in the string.
2332
2333 Argument:
2334  ss     string representation of operator
2335  opname split-out operator name
2336 */
2337
2338 static int
2339 identify_operator(const uschar ** ss, uschar ** opname)
2340 {
2341 const uschar * s = *ss;
2342 uschar name[256];
2343
2344 /* Numeric comparisons are symbolic */
2345
2346 if (*s == '=' || *s == '>' || *s == '<')
2347   {
2348   int p = 0;
2349   name[p++] = *s++;
2350   if (*s == '=')
2351     {
2352     name[p++] = '=';
2353     s++;
2354     }
2355   name[p] = 0;
2356   }
2357
2358 /* All other conditions are named */
2359
2360 else
2361   s = read_name(name, sizeof(name), s, US"_");
2362 *ss = s;
2363
2364 /* If we haven't read a name, it means some non-alpha character is first. */
2365
2366 if (!name[0])
2367   {
2368   expand_string_message = string_sprintf("condition name expected, "
2369     "but found \"%.16s\"", s);
2370   return -1;
2371   }
2372 if (opname)
2373   *opname = string_copy(name);
2374
2375 return chop_match(name, cond_table, nelem(cond_table));
2376 }
2377
2378
2379 /*************************************************
2380 *    Handle MD5 or SHA-1 computation for HMAC    *
2381 *************************************************/
2382
2383 /* These are some wrapping functions that enable the HMAC code to be a bit
2384 cleaner. A good compiler will spot the tail recursion.
2385
2386 Arguments:
2387   type         HMAC_MD5 or HMAC_SHA1
2388   remaining    are as for the cryptographic hash functions
2389
2390 Returns:       nothing
2391 */
2392
2393 static void
2394 chash_start(int type, void * base)
2395 {
2396 if (type == HMAC_MD5)
2397   md5_start((md5 *)base);
2398 else
2399   sha1_start((hctx *)base);
2400 }
2401
2402 static void
2403 chash_mid(int type, void * base, const uschar * string)
2404 {
2405 if (type == HMAC_MD5)
2406   md5_mid((md5 *)base, string);
2407 else
2408   sha1_mid((hctx *)base, string);
2409 }
2410
2411 static void
2412 chash_end(int type, void * base, const uschar * string, int length,
2413   uschar * digest)
2414 {
2415 if (type == HMAC_MD5)
2416   md5_end((md5 *)base, string, length, digest);
2417 else
2418   sha1_end((hctx *)base, string, length, digest);
2419 }
2420
2421
2422
2423
2424 #ifdef SUPPORT_SRS
2425 /* Do an hmac_md5.  The result is _not_ nul-terminated, and is sized as
2426 the smaller of a full hmac_md5 result (16 bytes) or the supplied output buffer.
2427
2428 Arguments:
2429         key     encoding key, nul-terminated
2430         src     data to be hashed, nul-terminated
2431         buf     output buffer
2432         len     size of output buffer
2433 */
2434
2435 static void
2436 hmac_md5(const uschar * key, const uschar * src, uschar * buf, unsigned len)
2437 {
2438 md5 md5_base;
2439 const uschar * keyptr;
2440 uschar * p;
2441 unsigned int keylen;
2442
2443 #define MD5_HASHLEN      16
2444 #define MD5_HASHBLOCKLEN 64
2445
2446 uschar keyhash[MD5_HASHLEN];
2447 uschar innerhash[MD5_HASHLEN];
2448 uschar finalhash[MD5_HASHLEN];
2449 uschar innerkey[MD5_HASHBLOCKLEN];
2450 uschar outerkey[MD5_HASHBLOCKLEN];
2451
2452 keyptr = key;
2453 keylen = Ustrlen(keyptr);
2454
2455 /* If the key is longer than the hash block length, then hash the key
2456 first */
2457
2458 if (keylen > MD5_HASHBLOCKLEN)
2459   {
2460   chash_start(HMAC_MD5, &md5_base);
2461   chash_end(HMAC_MD5, &md5_base, keyptr, keylen, keyhash);
2462   keyptr = keyhash;
2463   keylen = MD5_HASHLEN;
2464   }
2465
2466 /* Now make the inner and outer key values */
2467
2468 memset(innerkey, 0x36, MD5_HASHBLOCKLEN);
2469 memset(outerkey, 0x5c, MD5_HASHBLOCKLEN);
2470
2471 for (int i = 0; i < keylen; i++)
2472   {
2473   innerkey[i] ^= keyptr[i];
2474   outerkey[i] ^= keyptr[i];
2475   }
2476
2477 /* Now do the hashes */
2478
2479 chash_start(HMAC_MD5, &md5_base);
2480 chash_mid(HMAC_MD5, &md5_base, innerkey);
2481 chash_end(HMAC_MD5, &md5_base, src, Ustrlen(src), innerhash);
2482
2483 chash_start(HMAC_MD5, &md5_base);
2484 chash_mid(HMAC_MD5, &md5_base, outerkey);
2485 chash_end(HMAC_MD5, &md5_base, innerhash, MD5_HASHLEN, finalhash);
2486
2487 /* Encode the final hash as a hex string, limited by output buffer size */
2488
2489 p = buf;
2490 for (int i = 0, j = len; i < MD5_HASHLEN; i++)
2491   {
2492   if (j-- <= 0) break;
2493   *p++ = hex_digits[(finalhash[i] & 0xf0) >> 4];
2494   if (j-- <= 0) break;
2495   *p++ = hex_digits[finalhash[i] & 0x0f];
2496   }
2497 return;
2498 }
2499 #endif /*SUPPORT_SRS*/
2500
2501
2502 /*************************************************
2503 *        Read and evaluate a condition           *
2504 *************************************************/
2505
2506 /*
2507 Arguments:
2508   s        points to the start of the condition text
2509   resetok  points to a BOOL which is written false if it is unsafe to
2510            free memory. Certain condition types (acl) may have side-effect
2511            allocation which must be preserved.
2512   yield    points to a BOOL to hold the result of the condition test;
2513            if NULL, we are just reading through a condition that is
2514            part of an "or" combination to check syntax, or in a state
2515            where the answer isn't required
2516
2517 Returns:   a pointer to the first character after the condition, or
2518            NULL after an error
2519 */
2520
2521 static const uschar *
2522 eval_condition(const uschar * s, BOOL * resetok, BOOL * yield)
2523 {
2524 BOOL testfor = TRUE;
2525 BOOL tempcond, combined_cond;
2526 BOOL * subcondptr;
2527 BOOL sub2_honour_dollar = TRUE;
2528 BOOL is_forany, is_json, is_jsons;
2529 int rc, cond_type;
2530 int_eximarith_t num[2];
2531 struct stat statbuf;
2532 uschar * opname;
2533 uschar name[256];
2534 const uschar * sub[10];
2535 unsigned sub_textonly = 0;
2536
2537 for (;;)
2538   if (Uskip_whitespace(&s) == '!') { testfor = !testfor; s++; } else break;
2539
2540 switch(cond_type = identify_operator(&s, &opname))
2541   {
2542   /* def: tests for a non-empty variable, or for the existence of a header. If
2543   yield == NULL we are in a skipping state, and don't care about the answer. */
2544
2545   case ECOND_DEF:
2546     {
2547     const uschar * t;
2548
2549     if (*s != ':')
2550       {
2551       expand_string_message = US"\":\" expected after \"def\"";
2552       return NULL;
2553       }
2554
2555     s = read_name(name, sizeof(name), s+1, US"_");
2556
2557     /* Test for a header's existence. If the name contains a closing brace
2558     character, this may be a user error where the terminating colon has been
2559     omitted. Set a flag to adjust a subsequent error message in this case. */
2560
2561     if (  ( *(t = name) == 'h'
2562           || (*t == 'r' || *t == 'l' || *t == 'b') && *++t == 'h'
2563           )
2564        && (*++t == '_' || Ustrncmp(t, "eader_", 6) == 0)
2565        )
2566       {
2567       s = read_header_name(name, sizeof(name), s);
2568       /* {-for-text-editors */
2569       if (Ustrchr(name, '}') != NULL) malformed_header = TRUE;
2570       if (yield) *yield =
2571         (find_header(name, NULL, FH_EXISTS_ONLY, NULL) != NULL) == testfor;
2572       }
2573
2574     /* Test for a variable's having a non-empty value. A non-existent variable
2575     causes an expansion failure. */
2576
2577     else
2578       {
2579       if (!(t = find_variable(name, TRUE, yield == NULL, NULL)))
2580         {
2581         expand_string_message = name[0]
2582           ? string_sprintf("unknown variable \"%s\" after \"def:\"", name)
2583           : US"variable name omitted after \"def:\"";
2584         check_variable_error_message(name);
2585         return NULL;
2586         }
2587       if (yield) *yield = (t[0] != 0) == testfor;
2588       }
2589
2590     return s;
2591     }
2592
2593
2594   /* first_delivery tests for first delivery attempt */
2595
2596   case ECOND_FIRST_DELIVERY:
2597   if (yield) *yield = f.deliver_firsttime == testfor;
2598   return s;
2599
2600
2601   /* queue_running tests for any process started by a queue runner */
2602
2603   case ECOND_QUEUE_RUNNING:
2604   if (yield) *yield = (queue_run_pid != (pid_t)0) == testfor;
2605   return s;
2606
2607
2608   /* exists:  tests for file existence
2609        isip:  tests for any IP address
2610       isip4:  tests for an IPv4 address
2611       isip6:  tests for an IPv6 address
2612         pam:  does PAM authentication
2613      radius:  does RADIUS authentication
2614    ldapauth:  does LDAP authentication
2615     pwcheck:  does Cyrus SASL pwcheck authentication
2616   */
2617
2618   case ECOND_EXISTS:
2619   case ECOND_ISIP:
2620   case ECOND_ISIP4:
2621   case ECOND_ISIP6:
2622   case ECOND_PAM:
2623   case ECOND_RADIUS:
2624   case ECOND_LDAPAUTH:
2625   case ECOND_PWCHECK:
2626
2627   if (Uskip_whitespace(&s) != '{') goto COND_FAILED_CURLY_START; /* }-for-text-editors */
2628
2629    {
2630     BOOL textonly;
2631     sub[0] = expand_string_internal(s+1,
2632       ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | (yield ? ESI_NOFLAGS : ESI_SKIPPING),
2633       &s, resetok, &textonly);
2634     if (!sub[0]) return NULL;
2635     if (textonly) sub_textonly |= BIT(0);
2636    }
2637   /* {-for-text-editors */
2638   if (*s++ != '}') goto COND_FAILED_CURLY_END;
2639
2640   if (!yield) return s;   /* No need to run the test if skipping */
2641
2642   switch(cond_type)
2643     {
2644     case ECOND_EXISTS:
2645     if ((expand_forbid & RDO_EXISTS) != 0)
2646       {
2647       expand_string_message = US"File existence tests are not permitted";
2648       return NULL;
2649       }
2650     *yield = (Ustat(sub[0], &statbuf) == 0) == testfor;
2651     break;
2652
2653     case ECOND_ISIP:
2654     case ECOND_ISIP4:
2655     case ECOND_ISIP6:
2656     rc = string_is_ip_address(sub[0], NULL);
2657     *yield = ((cond_type == ECOND_ISIP)? (rc != 0) :
2658              (cond_type == ECOND_ISIP4)? (rc == 4) : (rc == 6)) == testfor;
2659     break;
2660
2661     /* Various authentication tests - all optionally compiled */
2662
2663     case ECOND_PAM:
2664     #ifdef SUPPORT_PAM
2665     rc = auth_call_pam(sub[0], &expand_string_message);
2666     goto END_AUTH;
2667     #else
2668     goto COND_FAILED_NOT_COMPILED;
2669     #endif  /* SUPPORT_PAM */
2670
2671     case ECOND_RADIUS:
2672     #ifdef RADIUS_CONFIG_FILE
2673     rc = auth_call_radius(sub[0], &expand_string_message);
2674     goto END_AUTH;
2675     #else
2676     goto COND_FAILED_NOT_COMPILED;
2677     #endif  /* RADIUS_CONFIG_FILE */
2678
2679     case ECOND_LDAPAUTH:
2680     #ifdef LOOKUP_LDAP
2681       {
2682       /* Just to keep the interface the same */
2683       BOOL do_cache;
2684       int old_pool = store_pool;
2685       store_pool = POOL_SEARCH;
2686       rc = eldapauth_find((void *)(-1), NULL, sub[0], Ustrlen(sub[0]), NULL,
2687         &expand_string_message, &do_cache);
2688       store_pool = old_pool;
2689       }
2690     goto END_AUTH;
2691     #else
2692     goto COND_FAILED_NOT_COMPILED;
2693     #endif  /* LOOKUP_LDAP */
2694
2695     case ECOND_PWCHECK:
2696     #ifdef CYRUS_PWCHECK_SOCKET
2697     rc = auth_call_pwcheck(sub[0], &expand_string_message);
2698     goto END_AUTH;
2699     #else
2700     goto COND_FAILED_NOT_COMPILED;
2701     #endif  /* CYRUS_PWCHECK_SOCKET */
2702
2703     #if defined(SUPPORT_PAM) || defined(RADIUS_CONFIG_FILE) || \
2704         defined(LOOKUP_LDAP) || defined(CYRUS_PWCHECK_SOCKET)
2705     END_AUTH:
2706     if (rc == ERROR || rc == DEFER) return NULL;
2707     *yield = (rc == OK) == testfor;
2708     #endif
2709     }
2710   return s;
2711
2712
2713   /* call ACL (in a conditional context).  Accept true, deny false.
2714   Defer is a forced-fail.  Anything set by message= goes to $value.
2715   Up to ten parameters are used; we use the braces round the name+args
2716   like the saslauthd condition does, to permit a variable number of args.
2717   See also the expansion-item version EITEM_ACL and the traditional
2718   acl modifier ACLC_ACL.
2719   Since the ACL may allocate new global variables, tell our caller to not
2720   reclaim memory.
2721   */
2722
2723   case ECOND_ACL:
2724     /* ${if acl {{name}{arg1}{arg2}...}  {yes}{no}} */
2725     {
2726     uschar *sub[10];
2727     uschar *user_msg;
2728     BOOL cond = FALSE;
2729
2730     Uskip_whitespace(&s);
2731     if (*s++ != '{') goto COND_FAILED_CURLY_START;      /*}*/
2732
2733     switch(read_subs(sub, nelem(sub), 1, &s,
2734         yield ? ESI_NOFLAGS : ESI_SKIPPING, TRUE, name, resetok, NULL))
2735       {
2736       case 1: expand_string_message = US"too few arguments or bracketing "
2737         "error for acl";
2738       case 2:
2739       case 3: return NULL;
2740       }
2741
2742     if (yield)
2743       {
2744       int rc;
2745       *resetok = FALSE; /* eval_acl() might allocate; do not reclaim */
2746       switch(rc = eval_acl(sub, nelem(sub), &user_msg))
2747         {
2748         case OK:
2749           cond = TRUE;
2750         case FAIL:
2751           lookup_value = NULL;
2752           if (user_msg)
2753             lookup_value = string_copy(user_msg);
2754           *yield = cond == testfor;
2755           break;
2756
2757         case DEFER:
2758           f.expand_string_forcedfail = TRUE;
2759           /*FALLTHROUGH*/
2760         default:
2761           expand_string_message = string_sprintf("%s from acl \"%s\"",
2762             rc_names[rc], sub[0]);
2763           return NULL;
2764         }
2765       }
2766     return s;
2767     }
2768
2769
2770   /* saslauthd: does Cyrus saslauthd authentication. Four parameters are used:
2771
2772      ${if saslauthd {{username}{password}{service}{realm}}  {yes}{no}}
2773
2774   However, the last two are optional. That is why the whole set is enclosed
2775   in their own set of braces. */
2776
2777   case ECOND_SASLAUTHD:
2778 #ifndef CYRUS_SASLAUTHD_SOCKET
2779     goto COND_FAILED_NOT_COMPILED;
2780 #else
2781     {
2782     uschar *sub[4];
2783     Uskip_whitespace(&s);
2784     if (*s++ != '{') goto COND_FAILED_CURLY_START;      /* }-for-text-editors */
2785     switch(read_subs(sub, nelem(sub), 2, &s,
2786         yield ? ESI_NOFLAGS : ESI_SKIPPING, TRUE, name, resetok, NULL))
2787       {
2788       case 1: expand_string_message = US"too few arguments or bracketing "
2789         "error for saslauthd";
2790       case 2:
2791       case 3: return NULL;
2792       }
2793     if (!sub[2]) sub[3] = NULL;  /* realm if no service */
2794     if (yield)
2795       {
2796       int rc = auth_call_saslauthd(sub[0], sub[1], sub[2], sub[3],
2797         &expand_string_message);
2798       if (rc == ERROR || rc == DEFER) return NULL;
2799       *yield = (rc == OK) == testfor;
2800       }
2801     return s;
2802     }
2803 #endif /* CYRUS_SASLAUTHD_SOCKET */
2804
2805
2806   /* symbolic operators for numeric and string comparison, and a number of
2807   other operators, all requiring two arguments.
2808
2809   crypteq:           encrypts plaintext and compares against an encrypted text,
2810                        using crypt(), crypt16(), MD5 or SHA-1
2811   inlist/inlisti:    checks if first argument is in the list of the second
2812   match:             does a regular expression match and sets up the numerical
2813                        variables if it succeeds
2814   match_address:     matches in an address list
2815   match_domain:      matches in a domain list
2816   match_ip:          matches a host list that is restricted to IP addresses
2817   match_local_part:  matches in a local part list
2818   */
2819
2820   case ECOND_MATCH_ADDRESS:
2821   case ECOND_MATCH_DOMAIN:
2822   case ECOND_MATCH_IP:
2823   case ECOND_MATCH_LOCAL_PART:
2824 #ifndef EXPAND_LISTMATCH_RHS
2825     sub2_honour_dollar = FALSE;
2826 #endif
2827     /* FALLTHROUGH */
2828
2829   case ECOND_CRYPTEQ:
2830   case ECOND_INLIST:
2831   case ECOND_INLISTI:
2832   case ECOND_MATCH:
2833
2834   case ECOND_NUM_L:     /* Numerical comparisons */
2835   case ECOND_NUM_LE:
2836   case ECOND_NUM_E:
2837   case ECOND_NUM_EE:
2838   case ECOND_NUM_G:
2839   case ECOND_NUM_GE:
2840
2841   case ECOND_STR_LT:    /* String comparisons */
2842   case ECOND_STR_LTI:
2843   case ECOND_STR_LE:
2844   case ECOND_STR_LEI:
2845   case ECOND_STR_EQ:
2846   case ECOND_STR_EQI:
2847   case ECOND_STR_GT:
2848   case ECOND_STR_GTI:
2849   case ECOND_STR_GE:
2850   case ECOND_STR_GEI:
2851
2852   for (int i = 0; i < 2; i++)
2853     {
2854     BOOL textonly;
2855     /* Sometimes, we don't expand substrings; too many insecure configurations
2856     created using match_address{}{} and friends, where the second param
2857     includes information from untrustworthy sources. */
2858     /*XXX is this moot given taint-tracking? */
2859
2860     esi_flags flags = ESI_BRACE_ENDS;
2861
2862     if (!(i > 0 && !sub2_honour_dollar)) flags |= ESI_HONOR_DOLLAR;
2863     if (!yield) flags |= ESI_SKIPPING;
2864
2865     if (Uskip_whitespace(&s) != '{')
2866       {
2867       if (i == 0) goto COND_FAILED_CURLY_START;
2868       expand_string_message = string_sprintf("missing 2nd string in {} "
2869         "after \"%s\"", opname);
2870       return NULL;
2871       }
2872     if (!(sub[i] = expand_string_internal(s+1, flags, &s, resetok, &textonly)))
2873       return NULL;
2874     if (textonly) sub_textonly |= BIT(i);
2875     DEBUG(D_expand) if (i == 1 && !sub2_honour_dollar && Ustrchr(sub[1], '$'))
2876       debug_printf_indent("WARNING: the second arg is NOT expanded,"
2877                         " for security reasons\n");
2878     if (*s++ != '}') goto COND_FAILED_CURLY_END;
2879
2880     /* Convert to numerical if required; we know that the names of all the
2881     conditions that compare numbers do not start with a letter. This just saves
2882     checking for them individually. */
2883
2884     if (!isalpha(opname[0]) && yield)
2885       if (sub[i][0] == 0)
2886         {
2887         num[i] = 0;
2888         DEBUG(D_expand)
2889           debug_printf_indent("empty string cast to zero for numerical comparison\n");
2890         }
2891       else
2892         {
2893         num[i] = expanded_string_integer(sub[i], FALSE);
2894         if (expand_string_message) return NULL;
2895         }
2896     }
2897
2898   /* Result not required */
2899
2900   if (!yield) return s;
2901
2902   /* Do an appropriate comparison */
2903
2904   switch(cond_type)
2905     {
2906     case ECOND_NUM_E:
2907     case ECOND_NUM_EE:
2908       tempcond = (num[0] == num[1]); break;
2909
2910     case ECOND_NUM_G:
2911       tempcond = (num[0] > num[1]); break;
2912
2913     case ECOND_NUM_GE:
2914       tempcond = (num[0] >= num[1]); break;
2915
2916     case ECOND_NUM_L:
2917       tempcond = (num[0] < num[1]); break;
2918
2919     case ECOND_NUM_LE:
2920       tempcond = (num[0] <= num[1]); break;
2921
2922     case ECOND_STR_LT:
2923       tempcond = (Ustrcmp(sub[0], sub[1]) < 0); break;
2924
2925     case ECOND_STR_LTI:
2926       tempcond = (strcmpic(sub[0], sub[1]) < 0); break;
2927
2928     case ECOND_STR_LE:
2929       tempcond = (Ustrcmp(sub[0], sub[1]) <= 0); break;
2930
2931     case ECOND_STR_LEI:
2932       tempcond = (strcmpic(sub[0], sub[1]) <= 0); break;
2933
2934     case ECOND_STR_EQ:
2935       tempcond = (Ustrcmp(sub[0], sub[1]) == 0); break;
2936
2937     case ECOND_STR_EQI:
2938       tempcond = (strcmpic(sub[0], sub[1]) == 0); break;
2939
2940     case ECOND_STR_GT:
2941       tempcond = (Ustrcmp(sub[0], sub[1]) > 0); break;
2942
2943     case ECOND_STR_GTI:
2944       tempcond = (strcmpic(sub[0], sub[1]) > 0); break;
2945
2946     case ECOND_STR_GE:
2947       tempcond = (Ustrcmp(sub[0], sub[1]) >= 0); break;
2948
2949     case ECOND_STR_GEI:
2950       tempcond = (strcmpic(sub[0], sub[1]) >= 0); break;
2951
2952     case ECOND_MATCH:   /* Regular expression match */
2953       {
2954       const pcre2_code * re = regex_compile(sub[1],
2955                   sub_textonly & BIT(1) ? MCS_CACHEABLE : MCS_NOFLAGS,
2956                   &expand_string_message, pcre_gen_cmp_ctx);
2957       if (!re)
2958         return NULL;
2959
2960       tempcond = regex_match_and_setup(re, sub[0], 0, -1);
2961       break;
2962       }
2963
2964     case ECOND_MATCH_ADDRESS:  /* Match in an address list */
2965       rc = match_address_list(sub[0], TRUE, FALSE, &(sub[1]), NULL, -1, 0,
2966                               CUSS &lookup_value);
2967       goto MATCHED_SOMETHING;
2968
2969     case ECOND_MATCH_DOMAIN:   /* Match in a domain list */
2970       rc = match_isinlist(sub[0], &(sub[1]), 0, &domainlist_anchor, NULL,
2971         MCL_DOMAIN + MCL_NOEXPAND, TRUE, CUSS &lookup_value);
2972       goto MATCHED_SOMETHING;
2973
2974     case ECOND_MATCH_IP:       /* Match IP address in a host list */
2975       if (sub[0][0] != 0 && string_is_ip_address(sub[0], NULL) == 0)
2976         {
2977         expand_string_message = string_sprintf("\"%s\" is not an IP address",
2978           sub[0]);
2979         return NULL;
2980         }
2981       else
2982         {
2983         unsigned int *nullcache = NULL;
2984         check_host_block cb;
2985
2986         cb.host_name = US"";
2987         cb.host_address = sub[0];
2988
2989         /* If the host address starts off ::ffff: it is an IPv6 address in
2990         IPv4-compatible mode. Find the IPv4 part for checking against IPv4
2991         addresses. */
2992
2993         cb.host_ipv4 = (Ustrncmp(cb.host_address, "::ffff:", 7) == 0)?
2994           cb.host_address + 7 : cb.host_address;
2995
2996         rc = match_check_list(
2997                &sub[1],                   /* the list */
2998                0,                         /* separator character */
2999                &hostlist_anchor,          /* anchor pointer */
3000                &nullcache,                /* cache pointer */
3001                check_host,                /* function for testing */
3002                &cb,                       /* argument for function */
3003                MCL_HOST,                  /* type of check */
3004                sub[0],                    /* text for debugging */
3005                CUSS &lookup_value);       /* where to pass back data */
3006         }
3007       goto MATCHED_SOMETHING;
3008
3009     case ECOND_MATCH_LOCAL_PART:
3010       rc = match_isinlist(sub[0], &(sub[1]), 0, &localpartlist_anchor, NULL,
3011         MCL_LOCALPART + MCL_NOEXPAND, TRUE, CUSS &lookup_value);
3012       /* Fall through */
3013       /* VVVVVVVVVVVV */
3014       MATCHED_SOMETHING:
3015       switch(rc)
3016         {
3017         case OK:   tempcond = TRUE;  break;
3018         case FAIL: tempcond = FALSE; break;
3019
3020         case DEFER:
3021           expand_string_message = string_sprintf("unable to complete match "
3022             "against \"%s\": %s", sub[1], search_error_message);
3023           return NULL;
3024         }
3025
3026       break;
3027
3028     /* Various "encrypted" comparisons. If the second string starts with
3029     "{" then an encryption type is given. Default to crypt() or crypt16()
3030     (build-time choice). */
3031     /* }-for-text-editors */
3032
3033     case ECOND_CRYPTEQ:
3034     #ifndef SUPPORT_CRYPTEQ
3035       goto COND_FAILED_NOT_COMPILED;
3036     #else
3037       if (strncmpic(sub[1], US"{md5}", 5) == 0)
3038         {
3039         int sublen = Ustrlen(sub[1]+5);
3040         md5 base;
3041         uschar digest[16];
3042
3043         md5_start(&base);
3044         md5_end(&base, sub[0], Ustrlen(sub[0]), digest);
3045
3046         /* If the length that we are comparing against is 24, the MD5 digest
3047         is expressed as a base64 string. This is the way LDAP does it. However,
3048         some other software uses a straightforward hex representation. We assume
3049         this if the length is 32. Other lengths fail. */
3050
3051         if (sublen == 24)
3052           {
3053           uschar *coded = b64encode(CUS digest, 16);
3054           DEBUG(D_auth) debug_printf("crypteq: using MD5+B64 hashing\n"
3055             "  subject=%s\n  crypted=%s\n", coded, sub[1]+5);
3056           tempcond = (Ustrcmp(coded, sub[1]+5) == 0);
3057           }
3058         else if (sublen == 32)
3059           {
3060           uschar coded[36];
3061           for (int i = 0; i < 16; i++) sprintf(CS (coded+2*i), "%02X", digest[i]);
3062           coded[32] = 0;
3063           DEBUG(D_auth) debug_printf("crypteq: using MD5+hex hashing\n"
3064             "  subject=%s\n  crypted=%s\n", coded, sub[1]+5);
3065           tempcond = (strcmpic(coded, sub[1]+5) == 0);
3066           }
3067         else
3068           {
3069           DEBUG(D_auth) debug_printf("crypteq: length for MD5 not 24 or 32: "
3070             "fail\n  crypted=%s\n", sub[1]+5);
3071           tempcond = FALSE;
3072           }
3073         }
3074
3075       else if (strncmpic(sub[1], US"{sha1}", 6) == 0)
3076         {
3077         int sublen = Ustrlen(sub[1]+6);
3078         hctx h;
3079         uschar digest[20];
3080
3081         sha1_start(&h);
3082         sha1_end(&h, sub[0], Ustrlen(sub[0]), digest);
3083
3084         /* If the length that we are comparing against is 28, assume the SHA1
3085         digest is expressed as a base64 string. If the length is 40, assume a
3086         straightforward hex representation. Other lengths fail. */
3087
3088         if (sublen == 28)
3089           {
3090           uschar *coded = b64encode(CUS digest, 20);
3091           DEBUG(D_auth) debug_printf("crypteq: using SHA1+B64 hashing\n"
3092             "  subject=%s\n  crypted=%s\n", coded, sub[1]+6);
3093           tempcond = (Ustrcmp(coded, sub[1]+6) == 0);
3094           }
3095         else if (sublen == 40)
3096           {
3097           uschar coded[44];
3098           for (int i = 0; i < 20; i++) sprintf(CS (coded+2*i), "%02X", digest[i]);
3099           coded[40] = 0;
3100           DEBUG(D_auth) debug_printf("crypteq: using SHA1+hex hashing\n"
3101             "  subject=%s\n  crypted=%s\n", coded, sub[1]+6);
3102           tempcond = (strcmpic(coded, sub[1]+6) == 0);
3103           }
3104         else
3105           {
3106           DEBUG(D_auth) debug_printf("crypteq: length for SHA-1 not 28 or 40: "
3107             "fail\n  crypted=%s\n", sub[1]+6);
3108           tempcond = FALSE;
3109           }
3110         }
3111
3112       else   /* {crypt} or {crypt16} and non-{ at start */
3113              /* }-for-text-editors */
3114         {
3115         int which = 0;
3116         uschar *coded;
3117
3118         if (strncmpic(sub[1], US"{crypt}", 7) == 0)
3119           {
3120           sub[1] += 7;
3121           which = 1;
3122           }
3123         else if (strncmpic(sub[1], US"{crypt16}", 9) == 0)
3124           {
3125           sub[1] += 9;
3126           which = 2;
3127           }
3128         else if (sub[1][0] == '{')              /* }-for-text-editors */
3129           {
3130           expand_string_message = string_sprintf("unknown encryption mechanism "
3131             "in \"%s\"", sub[1]);
3132           return NULL;
3133           }
3134
3135         switch(which)
3136           {
3137           case 0:  coded = US DEFAULT_CRYPT(CS sub[0], CS sub[1]); break;
3138           case 1:  coded = US crypt(CS sub[0], CS sub[1]); break;
3139           default: coded = US crypt16(CS sub[0], CS sub[1]); break;
3140           }
3141
3142         #define STR(s) # s
3143         #define XSTR(s) STR(s)
3144         DEBUG(D_auth) debug_printf("crypteq: using %s()\n"
3145           "  subject=%s\n  crypted=%s\n",
3146           which == 0 ? XSTR(DEFAULT_CRYPT) : which == 1 ? "crypt" : "crypt16",
3147           coded, sub[1]);
3148         #undef STR
3149         #undef XSTR
3150
3151         /* If the encrypted string contains fewer than two characters (for the
3152         salt), force failure. Otherwise we get false positives: with an empty
3153         string the yield of crypt() is an empty string! */
3154
3155         if (coded)
3156           tempcond = Ustrlen(sub[1]) < 2 ? FALSE : Ustrcmp(coded, sub[1]) == 0;
3157         else if (errno == EINVAL)
3158           tempcond = FALSE;
3159         else
3160           {
3161           expand_string_message = string_sprintf("crypt error: %s\n",
3162             US strerror(errno));
3163           return NULL;
3164           }
3165         }
3166       break;
3167     #endif  /* SUPPORT_CRYPTEQ */
3168
3169     case ECOND_INLIST:
3170     case ECOND_INLISTI:
3171       {
3172       const uschar * list = sub[1];
3173       int sep = 0;
3174       uschar *save_iterate_item = iterate_item;
3175       int (*compare)(const uschar *, const uschar *);
3176
3177       DEBUG(D_expand) debug_printf_indent("condition: %s  item: %s\n", opname, sub[0]);
3178
3179       tempcond = FALSE;
3180       compare = cond_type == ECOND_INLISTI
3181         ? strcmpic : (int (*)(const uschar *, const uschar *)) strcmp;
3182
3183       while ((iterate_item = string_nextinlist(&list, &sep, NULL, 0)))
3184         {
3185         DEBUG(D_expand) debug_printf_indent(" compare %s\n", iterate_item);
3186         if (compare(sub[0], iterate_item) == 0)
3187           {
3188           tempcond = TRUE;
3189           lookup_value = iterate_item;
3190           break;
3191           }
3192         }
3193       iterate_item = save_iterate_item;
3194       }
3195
3196     }   /* Switch for comparison conditions */
3197
3198   *yield = tempcond == testfor;
3199   return s;    /* End of comparison conditions */
3200
3201
3202   /* and/or: computes logical and/or of several conditions */
3203
3204   case ECOND_AND:
3205   case ECOND_OR:
3206   subcondptr = (yield == NULL) ? NULL : &tempcond;
3207   combined_cond = (cond_type == ECOND_AND);
3208
3209   Uskip_whitespace(&s);
3210   if (*s++ != '{') goto COND_FAILED_CURLY_START;        /* }-for-text-editors */
3211
3212   for (;;)
3213     {
3214     /* {-for-text-editors */
3215     if (Uskip_whitespace(&s) == '}') break;
3216     if (*s != '{')                                      /* }-for-text-editors */
3217       {
3218       expand_string_message = string_sprintf("each subcondition "
3219         "inside an \"%s{...}\" condition must be in its own {}", opname);
3220       return NULL;
3221       }
3222
3223     if (!(s = eval_condition(s+1, resetok, subcondptr)))
3224       {
3225       expand_string_message = string_sprintf("%s inside \"%s{...}\" condition",
3226         expand_string_message, opname);
3227       return NULL;
3228       }
3229     Uskip_whitespace(&s);
3230
3231     /* {-for-text-editors */
3232     if (*s++ != '}')
3233       {
3234       /* {-for-text-editors */
3235       expand_string_message = string_sprintf("missing } at end of condition "
3236         "inside \"%s\" group", opname);
3237       return NULL;
3238       }
3239
3240     if (yield)
3241       if (cond_type == ECOND_AND)
3242         {
3243         combined_cond &= tempcond;
3244         if (!combined_cond) subcondptr = NULL;  /* once false, don't */
3245         }                                       /* evaluate any more */
3246       else
3247         {
3248         combined_cond |= tempcond;
3249         if (combined_cond) subcondptr = NULL;   /* once true, don't */
3250         }                                       /* evaluate any more */
3251     }
3252
3253   if (yield) *yield = (combined_cond == testfor);
3254   return ++s;
3255
3256
3257   /* forall/forany: iterates a condition with different values */
3258
3259   case ECOND_FORALL:      is_forany = FALSE;  is_json = FALSE; is_jsons = FALSE; goto FORMANY;
3260   case ECOND_FORANY:      is_forany = TRUE;   is_json = FALSE; is_jsons = FALSE; goto FORMANY;
3261   case ECOND_FORALL_JSON: is_forany = FALSE;  is_json = TRUE;  is_jsons = FALSE; goto FORMANY;
3262   case ECOND_FORANY_JSON: is_forany = TRUE;   is_json = TRUE;  is_jsons = FALSE; goto FORMANY;
3263   case ECOND_FORALL_JSONS: is_forany = FALSE; is_json = TRUE;  is_jsons = TRUE;  goto FORMANY;
3264   case ECOND_FORANY_JSONS: is_forany = TRUE;  is_json = TRUE;  is_jsons = TRUE;  goto FORMANY;
3265
3266   FORMANY:
3267     {
3268     const uschar * list;
3269     int sep = 0;
3270     uschar *save_iterate_item = iterate_item;
3271
3272     DEBUG(D_expand) debug_printf_indent("condition: %s\n", opname);
3273
3274     Uskip_whitespace(&s);
3275     if (*s++ != '{') goto COND_FAILED_CURLY_START;      /* }-for-text-editors */
3276     if (!(sub[0] = expand_string_internal(s,
3277       ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | (yield ? ESI_NOFLAGS : ESI_SKIPPING),
3278       &s, resetok, NULL)))
3279       return NULL;
3280     /* {-for-text-editors */
3281     if (*s++ != '}') goto COND_FAILED_CURLY_END;
3282
3283     Uskip_whitespace(&s);
3284     if (*s++ != '{') goto COND_FAILED_CURLY_START;      /* }-for-text-editors */
3285
3286     sub[1] = s;
3287
3288     /* Call eval_condition once, with result discarded (as if scanning a
3289     "false" part). This allows us to find the end of the condition, because if
3290     the list it empty, we won't actually evaluate the condition for real. */
3291
3292     if (!(s = eval_condition(sub[1], resetok, NULL)))
3293       {
3294       expand_string_message = string_sprintf("%s inside \"%s\" condition",
3295         expand_string_message, opname);
3296       return NULL;
3297       }
3298     Uskip_whitespace(&s);
3299
3300     /* {-for-text-editors */
3301     if (*s++ != '}')
3302       {
3303       /* {-for-text-editors */
3304       expand_string_message = string_sprintf("missing } at end of condition "
3305         "inside \"%s\"", opname);
3306       return NULL;
3307       }
3308
3309     if (yield) *yield = !testfor;
3310     list = sub[0];
3311     if (is_json) list = dewrap(string_copy(list), US"[]");
3312     while ((iterate_item = is_json
3313       ? json_nextinlist(&list) : string_nextinlist(&list, &sep, NULL, 0)))
3314       {
3315       if (is_jsons)
3316         if (!(iterate_item = dewrap(iterate_item, US"\"\"")))
3317           {
3318           expand_string_message =
3319             string_sprintf("%s wrapping string result for extract jsons",
3320               expand_string_message);
3321           iterate_item = save_iterate_item;
3322           return NULL;
3323           }
3324
3325       DEBUG(D_expand) debug_printf_indent("%s: $item = \"%s\"\n", opname, iterate_item);
3326       if (!eval_condition(sub[1], resetok, &tempcond))
3327         {
3328         expand_string_message = string_sprintf("%s inside \"%s\" condition",
3329           expand_string_message, opname);
3330         iterate_item = save_iterate_item;
3331         return NULL;
3332         }
3333       DEBUG(D_expand) debug_printf_indent("%s: condition evaluated to %s\n", opname,
3334         tempcond? "true":"false");
3335
3336       if (yield) *yield = (tempcond == testfor);
3337       if (tempcond == is_forany) break;
3338       }
3339
3340     iterate_item = save_iterate_item;
3341     return s;
3342     }
3343
3344
3345   /* The bool{} expansion condition maps a string to boolean.
3346   The values supported should match those supported by the ACL condition
3347   (acl.c, ACLC_CONDITION) so that we keep to a minimum the different ideas
3348   of true/false.  Note that Router "condition" rules have a different
3349   interpretation, where general data can be used and only a few values
3350   map to FALSE.
3351   Note that readconf.c boolean matching, for boolean configuration options,
3352   only matches true/yes/false/no.
3353   The bool_lax{} condition matches the Router logic, which is much more
3354   liberal. */
3355   case ECOND_BOOL:
3356   case ECOND_BOOL_LAX:
3357     {
3358     uschar *sub_arg[1];
3359     uschar *t, *t2;
3360     uschar *ourname;
3361     size_t len;
3362     BOOL boolvalue = FALSE;
3363
3364     if (Uskip_whitespace(&s) != '{') goto COND_FAILED_CURLY_START;      /* }-for-text-editors */
3365     ourname = cond_type == ECOND_BOOL_LAX ? US"bool_lax" : US"bool";
3366     switch(read_subs(sub_arg, 1, 1, &s,
3367             yield ? ESI_NOFLAGS : ESI_SKIPPING, FALSE, ourname, resetok, NULL))
3368       {
3369       case 1: expand_string_message = string_sprintf(
3370                   "too few arguments or bracketing error for %s",
3371                   ourname);
3372       /*FALLTHROUGH*/
3373       case 2:
3374       case 3: return NULL;
3375       }
3376     t = sub_arg[0];
3377     Uskip_whitespace(&t);
3378     if ((len = Ustrlen(t)))
3379       {
3380       /* trailing whitespace: seems like a good idea to ignore it too */
3381       t2 = t + len - 1;
3382       while (isspace(*t2)) t2--;
3383       if (t2 != (t + len))
3384         {
3385         *++t2 = '\0';
3386         len = t2 - t;
3387         }
3388       }
3389     DEBUG(D_expand)
3390       debug_printf_indent("considering %s: %s\n", ourname, len ? t : US"<empty>");
3391     /* logic for the lax case from expand_check_condition(), which also does
3392     expands, and the logic is both short and stable enough that there should
3393     be no maintenance burden from replicating it. */
3394     if (len == 0)
3395       boolvalue = FALSE;
3396     else if (*t == '-'
3397              ? Ustrspn(t+1, "0123456789") == len-1
3398              : Ustrspn(t,   "0123456789") == len)
3399       {
3400       boolvalue = (Uatoi(t) == 0) ? FALSE : TRUE;
3401       /* expand_check_condition only does a literal string "0" check */
3402       if ((cond_type == ECOND_BOOL_LAX) && (len > 1))
3403         boolvalue = TRUE;
3404       }
3405     else if (strcmpic(t, US"true") == 0 || strcmpic(t, US"yes") == 0)
3406       boolvalue = TRUE;
3407     else if (strcmpic(t, US"false") == 0 || strcmpic(t, US"no") == 0)
3408       boolvalue = FALSE;
3409     else if (cond_type == ECOND_BOOL_LAX)
3410       boolvalue = TRUE;
3411     else
3412       {
3413       expand_string_message = string_sprintf("unrecognised boolean "
3414        "value \"%s\"", t);
3415       return NULL;
3416       }
3417     DEBUG(D_expand) debug_printf_indent("%s: condition evaluated to %s\n", ourname,
3418         boolvalue? "true":"false");
3419     if (yield) *yield = (boolvalue == testfor);
3420     return s;
3421     }
3422
3423 #ifdef SUPPORT_SRS
3424   case ECOND_INBOUND_SRS:
3425     /* ${if inbound_srs {local_part}{secret}  {yes}{no}} */
3426     {
3427     uschar * sub[2];
3428     const pcre2_code * re;
3429     pcre2_match_data * md;
3430     PCRE2_SIZE * ovec;
3431     int quoting = 0;
3432     uschar cksum[4];
3433     BOOL boolvalue = FALSE;
3434
3435     switch(read_subs(sub, 2, 2, CUSS &s,
3436             yield ? ESI_NOFLAGS : ESI_SKIPPING, FALSE, name, resetok, NULL))
3437       {
3438       case 1: expand_string_message = US"too few arguments or bracketing "
3439         "error for inbound_srs";
3440       case 2:
3441       case 3: return NULL;
3442       }
3443
3444     /* Match the given local_part against the SRS-encoded pattern */
3445
3446     re = regex_must_compile(US"^(?i)SRS0=([^=]+)=([A-Z2-7]+)=([^=]*)=(.*)$",
3447                             MCS_CASELESS | MCS_CACHEABLE, FALSE);
3448     md = pcre2_match_data_create(4+1, pcre_gen_ctx);
3449     if (pcre2_match(re, sub[0], PCRE2_ZERO_TERMINATED, 0, PCRE_EOPT,
3450                     md, pcre_gen_mtc_ctx) < 0)
3451       {
3452       DEBUG(D_expand) debug_printf("no match for SRS'd local-part pattern\n");
3453       goto srs_result;
3454       }
3455     ovec = pcre2_get_ovector_pointer(md);
3456
3457     if (sub[0][0] == '"')
3458       quoting = 1;
3459     else for (uschar * s = sub[0]; *s; s++)
3460       if (!isalnum(*s) && Ustrchr(".!#$%&'*+-/=?^_`{|}~", *s) == NULL)
3461         { quoting = 1; break; }
3462     if (quoting)
3463       DEBUG(D_expand) debug_printf_indent("auto-quoting local part\n");
3464
3465     /* Record the (quoted, if needed) decoded recipient as $srs_recipient */
3466
3467     srs_recipient = string_sprintf("%.*s%.*S%.*s@%.*S",         /* lowercased */
3468                       quoting, "\"",
3469                       (int) (ovec[9]-ovec[8]), sub[0] + ovec[8],  /* substr 4 */
3470                       quoting, "\"",
3471                       (int) (ovec[7]-ovec[6]), sub[0] + ovec[6]); /* substr 3 */
3472
3473     /* If a zero-length secret was given, we're done.  Otherwise carry on
3474     and validate the given SRS local_part againt our secret. */
3475
3476     if (!*sub[1])
3477       {
3478       boolvalue = TRUE;
3479       goto srs_result;
3480       }
3481
3482     /* check the timestamp */
3483       {
3484       struct timeval now;
3485       uschar * ss = sub[0] + ovec[4];   /* substring 2, the timestamp */
3486       long d;
3487       int n;
3488
3489       gettimeofday(&now, NULL);
3490       now.tv_sec /= 86400;              /* days since epoch */
3491
3492       /* Decode substring 2 from base32 to a number */
3493
3494       for (d = 0, n = ovec[5]-ovec[4]; n; n--)
3495         {
3496         uschar * t = Ustrchr(base32_chars, *ss++);
3497         d = d * 32 + (t - base32_chars);
3498         }
3499
3500       if (((now.tv_sec - d) & 0x3ff) > 10)      /* days since SRS generated */
3501         {
3502         DEBUG(D_expand) debug_printf("SRS too old\n");
3503         goto srs_result;
3504         }
3505       }
3506
3507     /* check length of substring 1, the offered checksum */
3508
3509     if (ovec[3]-ovec[2] != 4)
3510       {
3511       DEBUG(D_expand) debug_printf("SRS checksum wrong size\n");
3512       goto srs_result;
3513       }
3514
3515     /* Hash the address with our secret, and compare that computed checksum
3516     with the one extracted from the arg */
3517
3518     hmac_md5(sub[1], srs_recipient, cksum, sizeof(cksum));
3519     if (Ustrncmp(cksum, sub[0] + ovec[2], 4) != 0)
3520       {
3521       DEBUG(D_expand) debug_printf("SRS checksum mismatch\n");
3522       goto srs_result;
3523       }
3524     boolvalue = TRUE;
3525
3526 srs_result:
3527     /* pcre2_match_data_free(md);       gen ctx needs no free */
3528     if (yield) *yield = (boolvalue == testfor);
3529     return s;
3530     }
3531 #endif /*SUPPORT_SRS*/
3532
3533   /* Unknown condition */
3534
3535   default:
3536     if (!expand_string_message || !*expand_string_message)
3537       expand_string_message = string_sprintf("unknown condition \"%s\"", opname);
3538     return NULL;
3539   }   /* End switch on condition type */
3540
3541 /* Missing braces at start and end of data */
3542
3543 COND_FAILED_CURLY_START:
3544 expand_string_message = string_sprintf("missing { after \"%s\"", opname);
3545 return NULL;
3546
3547 COND_FAILED_CURLY_END:
3548 expand_string_message = string_sprintf("missing } at end of \"%s\" condition",
3549   opname);
3550 return NULL;
3551
3552 /* A condition requires code that is not compiled */
3553
3554 #if !defined(SUPPORT_PAM) || !defined(RADIUS_CONFIG_FILE) || \
3555     !defined(LOOKUP_LDAP) || !defined(CYRUS_PWCHECK_SOCKET) || \
3556     !defined(SUPPORT_CRYPTEQ) || !defined(CYRUS_SASLAUTHD_SOCKET)
3557 COND_FAILED_NOT_COMPILED:
3558 expand_string_message = string_sprintf("support for \"%s\" not compiled",
3559   opname);
3560 return NULL;
3561 #endif
3562 }
3563
3564
3565
3566
3567 /*************************************************
3568 *          Save numerical variables              *
3569 *************************************************/
3570
3571 /* This function is called from items such as "if" that want to preserve and
3572 restore the numbered variables.
3573
3574 Arguments:
3575   save_expand_string    points to an array of pointers to set
3576   save_expand_nlength   points to an array of ints for the lengths
3577
3578 Returns:                the value of expand max to save
3579 */
3580
3581 static int
3582 save_expand_strings(const uschar **save_expand_nstring, int *save_expand_nlength)
3583 {
3584 for (int i = 0; i <= expand_nmax; i++)
3585   {
3586   save_expand_nstring[i] = expand_nstring[i];
3587   save_expand_nlength[i] = expand_nlength[i];
3588   }
3589 return expand_nmax;
3590 }
3591
3592
3593
3594 /*************************************************
3595 *           Restore numerical variables          *
3596 *************************************************/
3597
3598 /* This function restored saved values of numerical strings.
3599
3600 Arguments:
3601   save_expand_nmax      the number of strings to restore
3602   save_expand_string    points to an array of pointers
3603   save_expand_nlength   points to an array of ints
3604
3605 Returns:                nothing
3606 */
3607
3608 static void
3609 restore_expand_strings(int save_expand_nmax, const uschar **save_expand_nstring,
3610   int *save_expand_nlength)
3611 {
3612 expand_nmax = save_expand_nmax;
3613 for (int i = 0; i <= expand_nmax; i++)
3614   {
3615   expand_nstring[i] = save_expand_nstring[i];
3616   expand_nlength[i] = save_expand_nlength[i];
3617   }
3618 }
3619
3620
3621
3622
3623
3624 /*************************************************
3625 *            Handle yes/no substrings            *
3626 *************************************************/
3627
3628 /* This function is used by ${if}, ${lookup} and ${extract} to handle the
3629 alternative substrings that depend on whether or not the condition was true,
3630 or the lookup or extraction succeeded. The substrings always have to be
3631 expanded, to check their syntax, but "skipping" is set when the result is not
3632 needed - this avoids unnecessary nested lookups.
3633
3634 Arguments:
3635   flags
3636    skipping       TRUE if we were skipping when this item was reached
3637   yes            TRUE if the first string is to be used, else use the second
3638   save_lookup    a value to put back into lookup_value before the 2nd expansion
3639   sptr           points to the input string pointer
3640   yieldptr       points to the output growable-string pointer
3641   type           "lookup", "if", "extract", "run", "env", "listextract" or
3642                  "certextract" for error message
3643   resetok        if not NULL, pointer to flag - write FALSE if unsafe to reset
3644                 the store.
3645
3646 Returns:         0 OK; lookup_value has been reset to save_lookup
3647                  1 expansion failed
3648                  2 expansion failed because of bracketing error
3649 */
3650
3651 static int
3652 process_yesno(esi_flags flags, BOOL yes, uschar *save_lookup, const uschar **sptr,
3653   gstring ** yieldptr, uschar *type, BOOL *resetok)
3654 {
3655 int rc = 0;
3656 const uschar *s = *sptr;    /* Local value */
3657 uschar *sub1, *sub2;
3658 const uschar * errwhere;
3659
3660 flags &= ESI_SKIPPING;          /* Ignore all buf the skipping flag */
3661
3662 /* If there are no following strings, we substitute the contents of $value for
3663 lookups and for extractions in the success case. For the ${if item, the string
3664 "true" is substituted. In the fail case, nothing is substituted for all three
3665 items. */
3666
3667 if (skip_whitespace(&s) == '}')
3668   {
3669   if (type[0] == 'i')
3670     {
3671     if (yes && !(flags & ESI_SKIPPING))
3672       *yieldptr = string_catn(*yieldptr, US"true", 4);
3673     }
3674   else
3675     {
3676     if (yes && lookup_value && !(flags & ESI_SKIPPING))
3677       *yieldptr = string_cat(*yieldptr, lookup_value);
3678     lookup_value = save_lookup;
3679     }
3680   s++;
3681   goto RETURN;
3682   }
3683
3684 /* The first following string must be braced. */
3685
3686 if (*s++ != '{')
3687   {
3688   errwhere = US"'yes' part did not start with '{'";             /*}}*/
3689   goto FAILED_CURLY;
3690   }
3691
3692 /* Expand the first substring. Forced failures are noticed only if we actually
3693 want this string. Set skipping in the call in the fail case (this will always
3694 be the case if we were already skipping). */
3695
3696 sub1 = expand_string_internal(s,
3697   ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | (yes ? ESI_NOFLAGS : ESI_SKIPPING),
3698   &s, resetok, NULL);
3699 if (sub1 == NULL && (yes || !f.expand_string_forcedfail)) goto FAILED;
3700 f.expand_string_forcedfail = FALSE;
3701                                                                 /*{{*/
3702 if (*s++ != '}')
3703   {
3704   errwhere = US"'yes' part did not end with '}'";
3705   goto FAILED_CURLY;
3706   }
3707
3708 /* If we want the first string, add it to the output */
3709
3710 if (yes)
3711   *yieldptr = string_cat(*yieldptr, sub1);
3712
3713 /* If this is called from a lookup/env or a (cert)extract, we want to restore
3714 $value to what it was at the start of the item, so that it has this value
3715 during the second string expansion. For the call from "if" or "run" to this
3716 function, save_lookup is set to lookup_value, so that this statement does
3717 nothing. */
3718
3719 lookup_value = save_lookup;
3720
3721 /* There now follows either another substring, or "fail", or nothing. This
3722 time, forced failures are noticed only if we want the second string. We must
3723 set skipping in the nested call if we don't want this string, or if we were
3724 already skipping. */
3725
3726 if (skip_whitespace(&s) == '{')                                 /*}*/
3727   {
3728   esi_flags s_flags = ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | flags;
3729   if (yes) s_flags |= ESI_SKIPPING;
3730   sub2 = expand_string_internal(s+1, s_flags, &s, resetok, NULL);
3731   if (!sub2 && (!yes || !f.expand_string_forcedfail)) goto FAILED;
3732   f.expand_string_forcedfail = FALSE;                           /*{*/
3733   if (*s++ != '}')
3734     {
3735     errwhere = US"'no' part did not start with '{'";            /*}*/
3736     goto FAILED_CURLY;
3737     }
3738
3739   /* If we want the second string, add it to the output */
3740
3741   if (!yes)
3742     *yieldptr = string_cat(*yieldptr, sub2);
3743   }
3744                                                                 /*{{*/
3745 /* If there is no second string, but the word "fail" is present when the use of
3746 the second string is wanted, set a flag indicating it was a forced failure
3747 rather than a syntactic error. Swallow the terminating } in case this is nested
3748 inside another lookup or if or extract. */
3749
3750 else if (*s != '}')
3751   {
3752   uschar name[256];
3753   /* deconst cast ok here as source is s anyway */
3754   s = US read_name(name, sizeof(name), s, US"_");
3755   if (Ustrcmp(name, "fail") == 0)
3756     {
3757     if (!yes && !(flags & ESI_SKIPPING))
3758       {
3759       Uskip_whitespace(&s);                                     /*{{*/
3760       if (*s++ != '}')
3761         {
3762         errwhere = US"did not close with '}' after forcedfail";
3763         goto FAILED_CURLY;
3764         }
3765       expand_string_message =
3766         string_sprintf("\"%s\" failed and \"fail\" requested", type);
3767       f.expand_string_forcedfail = TRUE;
3768       goto FAILED;
3769       }
3770     }
3771   else
3772     {
3773     expand_string_message =
3774       string_sprintf("syntax error in \"%s\" item - \"fail\" expected", type);
3775     goto FAILED;
3776     }
3777   }
3778
3779 /* All we have to do now is to check on the final closing brace. */
3780
3781 skip_whitespace(&s);                                            /*{{*/
3782 if (*s++ != '}')
3783   {
3784   errwhere = US"did not close with '}'";
3785   goto FAILED_CURLY;
3786   }
3787
3788
3789 RETURN:
3790 /* Update the input pointer value before returning */
3791 *sptr = s;
3792 return rc;
3793
3794 FAILED_CURLY:
3795   /* Get here if there is a bracketing failure */
3796   expand_string_message = string_sprintf(
3797     "curly-bracket problem in conditional yes/no parsing: %s\n"
3798     " remaining string is '%s'", errwhere, --s);
3799   rc = 2;
3800   goto RETURN;
3801
3802 FAILED:
3803   /* Get here for other failures */
3804   rc = 1;
3805   goto RETURN;
3806 }
3807
3808
3809
3810
3811 /********************************************************
3812 * prvs: Get last three digits of days since Jan 1, 1970 *
3813 ********************************************************/
3814
3815 /* This is needed to implement the "prvs" BATV reverse
3816    path signing scheme
3817
3818 Argument: integer "days" offset to add or substract to
3819           or from the current number of days.
3820
3821 Returns:  pointer to string containing the last three
3822           digits of the number of days since Jan 1, 1970,
3823           modified by the offset argument, NULL if there
3824           was an error in the conversion.
3825
3826 */
3827
3828 static uschar *
3829 prvs_daystamp(int day_offset)
3830 {
3831 uschar * days = store_get(32, GET_UNTAINTED);      /* Need at least 24 for cases */
3832 (void)string_format(days, 32, TIME_T_FMT,          /* where TIME_T_FMT is %lld */
3833   (time(NULL) + day_offset*86400)/86400);
3834 return (Ustrlen(days) >= 3) ? &days[Ustrlen(days)-3] : US"100";
3835 }
3836
3837
3838
3839 /********************************************************
3840 *   prvs: perform HMAC-SHA1 computation of prvs bits    *
3841 ********************************************************/
3842
3843 /* This is needed to implement the "prvs" BATV reverse
3844    path signing scheme
3845
3846 Arguments:
3847   address RFC2821 Address to use
3848       key The key to use (must be less than 64 characters
3849           in size)
3850   key_num Single-digit key number to use. Defaults to
3851           '0' when NULL.
3852
3853 Returns:  pointer to string containing the first three
3854           bytes of the final hash in hex format, NULL if
3855           there was an error in the process.
3856 */
3857
3858 static uschar *
3859 prvs_hmac_sha1(uschar *address, uschar *key, uschar *key_num, uschar *daystamp)
3860 {
3861 gstring * hash_source;
3862 uschar * p;
3863 hctx h;
3864 uschar innerhash[20];
3865 uschar finalhash[20];
3866 uschar innerkey[64];
3867 uschar outerkey[64];
3868 uschar *finalhash_hex;
3869
3870 if (!key_num)
3871   key_num = US"0";
3872
3873 if (Ustrlen(key) > 64)
3874   return NULL;
3875
3876 hash_source = string_catn(NULL, key_num, 1);
3877 hash_source = string_catn(hash_source, daystamp, 3);
3878 hash_source = string_cat(hash_source, address);
3879 (void) string_from_gstring(hash_source);
3880
3881 DEBUG(D_expand)
3882   debug_printf_indent("prvs: hash source is '%s'\n", hash_source->s);
3883
3884 memset(innerkey, 0x36, 64);
3885 memset(outerkey, 0x5c, 64);
3886
3887 for (int i = 0; i < Ustrlen(key); i++)
3888   {
3889   innerkey[i] ^= key[i];
3890   outerkey[i] ^= key[i];
3891   }
3892
3893 chash_start(HMAC_SHA1, &h);
3894 chash_mid(HMAC_SHA1, &h, innerkey);
3895 chash_end(HMAC_SHA1, &h, hash_source->s, hash_source->ptr, innerhash);
3896
3897 chash_start(HMAC_SHA1, &h);
3898 chash_mid(HMAC_SHA1, &h, outerkey);
3899 chash_end(HMAC_SHA1, &h, innerhash, 20, finalhash);
3900
3901 /* Hashing is deemed sufficient to de-taint any input data */
3902
3903 p = finalhash_hex = store_get(40, GET_UNTAINTED);
3904 for (int i = 0; i < 3; i++)
3905   {
3906   *p++ = hex_digits[(finalhash[i] & 0xf0) >> 4];
3907   *p++ = hex_digits[finalhash[i] & 0x0f];
3908   }
3909 *p = '\0';
3910
3911 return finalhash_hex;
3912 }
3913
3914
3915
3916
3917 /*************************************************
3918 *        Join a file onto the output string      *
3919 *************************************************/
3920
3921 /* This is used for readfile/readsock and after a run expansion.
3922 It joins the contents of a file onto the output string, globally replacing
3923 newlines with a given string (optionally).
3924
3925 Arguments:
3926   f            the FILE
3927   yield        pointer to the expandable string struct
3928   eol          newline replacement string, or NULL
3929
3930 Returns:       new pointer for expandable string, terminated if non-null
3931 */
3932
3933 gstring *
3934 cat_file(FILE * f, gstring * yield, uschar * eol)
3935 {
3936 uschar buffer[1024];
3937
3938 while (Ufgets(buffer, sizeof(buffer), f))
3939   {
3940   int len = Ustrlen(buffer);
3941   if (eol && buffer[len-1] == '\n') len--;
3942   yield = string_catn(yield, buffer, len);
3943   if (eol && buffer[len])
3944     yield = string_cat(yield, eol);
3945   }
3946 return yield;
3947 }
3948
3949
3950 #ifndef DISABLE_TLS
3951 gstring *
3952 cat_file_tls(void * tls_ctx, gstring * yield, uschar * eol)
3953 {
3954 int rc;
3955 uschar buffer[1024];
3956
3957 /*XXX could we read direct into a pre-grown string? */
3958
3959 while ((rc = tls_read(tls_ctx, buffer, sizeof(buffer))) > 0)
3960   for (uschar * s = buffer; rc--; s++)
3961     yield = eol && *s == '\n'
3962       ? string_cat(yield, eol) : string_catn(yield, s, 1);
3963
3964 /* We assume that all errors, and any returns of zero bytes,
3965 are actually EOF. */
3966
3967 return yield;
3968 }
3969 #endif
3970
3971
3972 /*************************************************
3973 *          Evaluate numeric expression           *
3974 *************************************************/
3975
3976 /* This is a set of mutually recursive functions that evaluate an arithmetic
3977 expression involving + - * / % & | ^ ~ << >> and parentheses. The only one of
3978 these functions that is called from elsewhere is eval_expr, whose interface is:
3979
3980 Arguments:
3981   sptr        pointer to the pointer to the string - gets updated
3982   decimal     TRUE if numbers are to be assumed decimal
3983   error       pointer to where to put an error message - must be NULL on input
3984   endket      TRUE if ')' must terminate - FALSE for external call
3985
3986 Returns:      on success: the value of the expression, with *error still NULL
3987               on failure: an undefined value, with *error = a message
3988 */
3989
3990 static int_eximarith_t eval_op_or(uschar **, BOOL, uschar **);
3991
3992
3993 static int_eximarith_t
3994 eval_expr(uschar **sptr, BOOL decimal, uschar **error, BOOL endket)
3995 {
3996 uschar *s = *sptr;
3997 int_eximarith_t x = eval_op_or(&s, decimal, error);
3998
3999 if (!*error)
4000   if (endket)
4001     if (*s != ')')
4002       *error = US"expecting closing parenthesis";
4003     else
4004       while (isspace(*++s));
4005   else if (*s)
4006     *error = US"expecting operator";
4007 *sptr = s;
4008 return x;
4009 }
4010
4011
4012 static int_eximarith_t
4013 eval_number(uschar **sptr, BOOL decimal, uschar **error)
4014 {
4015 int c;
4016 int_eximarith_t n;
4017 uschar *s = *sptr;
4018
4019 if (isdigit((c = Uskip_whitespace(&s))))
4020   {
4021   int count;
4022   (void)sscanf(CS s, (decimal? SC_EXIM_DEC "%n" : SC_EXIM_ARITH "%n"), &n, &count);
4023   s += count;
4024   switch (tolower(*s))
4025     {
4026     default: break;
4027     case 'k': n *= 1024; s++; break;
4028     case 'm': n *= 1024*1024; s++; break;
4029     case 'g': n *= 1024*1024*1024; s++; break;
4030     }
4031   Uskip_whitespace(&s);
4032   }
4033 else if (c == '(')
4034   {
4035   s++;
4036   n = eval_expr(&s, decimal, error, 1);
4037   }
4038 else
4039   {
4040   *error = US"expecting number or opening parenthesis";
4041   n = 0;
4042   }
4043 *sptr = s;
4044 return n;
4045 }
4046
4047
4048 static int_eximarith_t
4049 eval_op_unary(uschar **sptr, BOOL decimal, uschar **error)
4050 {
4051 uschar *s = *sptr;
4052 int_eximarith_t x;
4053 Uskip_whitespace(&s);
4054 if (*s == '+' || *s == '-' || *s == '~')
4055   {
4056   int op = *s++;
4057   x = eval_op_unary(&s, decimal, error);
4058   if (op == '-') x = -x;
4059     else if (op == '~') x = ~x;
4060   }
4061 else
4062   x = eval_number(&s, decimal, error);
4063
4064 *sptr = s;
4065 return x;
4066 }
4067
4068
4069 static int_eximarith_t
4070 eval_op_mult(uschar **sptr, BOOL decimal, uschar **error)
4071 {
4072 uschar *s = *sptr;
4073 int_eximarith_t x = eval_op_unary(&s, decimal, error);
4074 if (!*error)
4075   {
4076   while (*s == '*' || *s == '/' || *s == '%')
4077     {
4078     int op = *s++;
4079     int_eximarith_t y = eval_op_unary(&s, decimal, error);
4080     if (*error) break;
4081     /* SIGFPE both on div/mod by zero and on INT_MIN / -1, which would give
4082      * a value of INT_MAX+1. Note that INT_MIN * -1 gives INT_MIN for me, which
4083      * is a bug somewhere in [gcc 4.2.1, FreeBSD, amd64].  In fact, -N*-M where
4084      * -N*M is INT_MIN will yield INT_MIN.
4085      * Since we don't support floating point, this is somewhat simpler.
4086      * Ideally, we'd return an error, but since we overflow for all other
4087      * arithmetic, consistency suggests otherwise, but what's the correct value
4088      * to use?  There is none.
4089      * The C standard guarantees overflow for unsigned arithmetic but signed
4090      * overflow invokes undefined behaviour; in practice, this is overflow
4091      * except for converting INT_MIN to INT_MAX+1.  We also can't guarantee
4092      * that long/longlong larger than int are available, or we could just work
4093      * with larger types.  We should consider whether to guarantee 32bit eval
4094      * and 64-bit working variables, with errors returned.  For now ...
4095      * So, the only SIGFPEs occur with a non-shrinking div/mod, thus -1; we
4096      * can just let the other invalid results occur otherwise, as they have
4097      * until now.  For this one case, we can coerce.
4098      */
4099     if (y == -1 && x == EXIM_ARITH_MIN && op != '*')
4100       {
4101       DEBUG(D_expand)
4102         debug_printf("Integer exception dodging: " PR_EXIM_ARITH "%c-1 coerced to " PR_EXIM_ARITH "\n",
4103             EXIM_ARITH_MIN, op, EXIM_ARITH_MAX);
4104       x = EXIM_ARITH_MAX;
4105       continue;
4106       }
4107     if (op == '*')
4108       x *= y;
4109     else
4110       {
4111       if (y == 0)
4112         {
4113         *error = (op == '/') ? US"divide by zero" : US"modulo by zero";
4114         x = 0;
4115         break;
4116         }
4117       if (op == '/')
4118         x /= y;
4119       else
4120         x %= y;
4121       }
4122     }
4123   }
4124 *sptr = s;
4125 return x;
4126 }
4127
4128
4129 static int_eximarith_t
4130 eval_op_sum(uschar **sptr, BOOL decimal, uschar **error)
4131 {
4132 uschar *s = *sptr;
4133 int_eximarith_t x = eval_op_mult(&s, decimal, error);
4134 if (!*error)
4135   {
4136   while (*s == '+' || *s == '-')
4137     {
4138     int op = *s++;
4139     int_eximarith_t y = eval_op_mult(&s, decimal, error);
4140     if (*error) break;
4141     if (  (x >=   EXIM_ARITH_MAX/2  && x >=   EXIM_ARITH_MAX/2)
4142        || (x <= -(EXIM_ARITH_MAX/2) && y <= -(EXIM_ARITH_MAX/2)))
4143       {                 /* over-conservative check */
4144       *error = op == '+'
4145         ? US"overflow in sum" : US"overflow in difference";
4146       break;
4147       }
4148     if (op == '+') x += y; else x -= y;
4149     }
4150   }
4151 *sptr = s;
4152 return x;
4153 }
4154
4155
4156 static int_eximarith_t
4157 eval_op_shift(uschar **sptr, BOOL decimal, uschar **error)
4158 {
4159 uschar *s = *sptr;
4160 int_eximarith_t x = eval_op_sum(&s, decimal, error);
4161 if (!*error)
4162   {
4163   while ((*s == '<' || *s == '>') && s[1] == s[0])
4164     {
4165     int_eximarith_t y;
4166     int op = *s++;
4167     s++;
4168     y = eval_op_sum(&s, decimal, error);
4169     if (*error) break;
4170     if (op == '<') x <<= y; else x >>= y;
4171     }
4172   }
4173 *sptr = s;
4174 return x;
4175 }
4176
4177
4178 static int_eximarith_t
4179 eval_op_and(uschar **sptr, BOOL decimal, uschar **error)
4180 {
4181 uschar *s = *sptr;
4182 int_eximarith_t x = eval_op_shift(&s, decimal, error);
4183 if (!*error)
4184   {
4185   while (*s == '&')
4186     {
4187     int_eximarith_t y;
4188     s++;
4189     y = eval_op_shift(&s, decimal, error);
4190     if (*error) break;
4191     x &= y;
4192     }
4193   }
4194 *sptr = s;
4195 return x;
4196 }
4197
4198
4199 static int_eximarith_t
4200 eval_op_xor(uschar **sptr, BOOL decimal, uschar **error)
4201 {
4202 uschar *s = *sptr;
4203 int_eximarith_t x = eval_op_and(&s, decimal, error);
4204 if (!*error)
4205   {
4206   while (*s == '^')
4207     {
4208     int_eximarith_t y;
4209     s++;
4210     y = eval_op_and(&s, decimal, error);
4211     if (*error) break;
4212     x ^= y;
4213     }
4214   }
4215 *sptr = s;
4216 return x;
4217 }
4218
4219
4220 static int_eximarith_t
4221 eval_op_or(uschar **sptr, BOOL decimal, uschar **error)
4222 {
4223 uschar *s = *sptr;
4224 int_eximarith_t x = eval_op_xor(&s, decimal, error);
4225 if (!*error)
4226   {
4227   while (*s == '|')
4228     {
4229     int_eximarith_t y;
4230     s++;
4231     y = eval_op_xor(&s, decimal, error);
4232     if (*error) break;
4233     x |= y;
4234     }
4235   }
4236 *sptr = s;
4237 return x;
4238 }
4239
4240
4241
4242 /************************************************/
4243 /* Comparison operation for sort expansion.  We need to avoid
4244 re-expanding the fields being compared, so need a custom routine.
4245
4246 Arguments:
4247  cond_type              Comparison operator code
4248  leftarg, rightarg      Arguments for comparison
4249
4250 Return true iff (leftarg compare rightarg)
4251 */
4252
4253 static BOOL
4254 sortsbefore(int cond_type, BOOL alpha_cond,
4255   const uschar * leftarg, const uschar * rightarg)
4256 {
4257 int_eximarith_t l_num, r_num;
4258
4259 if (!alpha_cond)
4260   {
4261   l_num = expanded_string_integer(leftarg, FALSE);
4262   if (expand_string_message) return FALSE;
4263   r_num = expanded_string_integer(rightarg, FALSE);
4264   if (expand_string_message) return FALSE;
4265
4266   switch (cond_type)
4267     {
4268     case ECOND_NUM_G:   return l_num >  r_num;
4269     case ECOND_NUM_GE:  return l_num >= r_num;
4270     case ECOND_NUM_L:   return l_num <  r_num;
4271     case ECOND_NUM_LE:  return l_num <= r_num;
4272     default: break;
4273     }
4274   }
4275 else
4276   switch (cond_type)
4277     {
4278     case ECOND_STR_LT:  return Ustrcmp (leftarg, rightarg) <  0;
4279     case ECOND_STR_LTI: return strcmpic(leftarg, rightarg) <  0;
4280     case ECOND_STR_LE:  return Ustrcmp (leftarg, rightarg) <= 0;
4281     case ECOND_STR_LEI: return strcmpic(leftarg, rightarg) <= 0;
4282     case ECOND_STR_GT:  return Ustrcmp (leftarg, rightarg) >  0;
4283     case ECOND_STR_GTI: return strcmpic(leftarg, rightarg) >  0;
4284     case ECOND_STR_GE:  return Ustrcmp (leftarg, rightarg) >= 0;
4285     case ECOND_STR_GEI: return strcmpic(leftarg, rightarg) >= 0;
4286     default: break;
4287     }
4288 return FALSE;   /* should not happen */
4289 }
4290
4291
4292 /* Expand a named list.  Return false on failure. */
4293 static gstring *
4294 expand_listnamed(gstring * yield, const uschar * name, const uschar * listtype)
4295 {
4296 tree_node *t = NULL;
4297 const uschar * list;
4298 int sep = 0;
4299 uschar * item;
4300 BOOL needsep = FALSE;
4301 #define LISTNAMED_BUF_SIZE 256
4302 uschar b[LISTNAMED_BUF_SIZE];
4303 uschar * buffer = b;
4304
4305 if (*name == '+') name++;
4306 if (!listtype)          /* no-argument version */
4307   {
4308   if (  !(t = tree_search(addresslist_anchor, name))
4309      && !(t = tree_search(domainlist_anchor,  name))
4310      && !(t = tree_search(hostlist_anchor,    name)))
4311     t = tree_search(localpartlist_anchor, name);
4312   }
4313 else switch(*listtype)  /* specific list-type version */
4314   {
4315   case 'a': t = tree_search(addresslist_anchor,   name); break;
4316   case 'd': t = tree_search(domainlist_anchor,    name); break;
4317   case 'h': t = tree_search(hostlist_anchor,      name); break;
4318   case 'l': t = tree_search(localpartlist_anchor, name); break;
4319   default:
4320     expand_string_message = US"bad suffix on \"list\" operator";
4321     return yield;
4322   }
4323
4324 if(!t)
4325   {
4326   expand_string_message = string_sprintf("\"%s\" is not a %snamed list",
4327     name, !listtype?""
4328       : *listtype=='a'?"address "
4329       : *listtype=='d'?"domain "
4330       : *listtype=='h'?"host "
4331       : *listtype=='l'?"localpart "
4332       : 0);
4333   return yield;
4334   }
4335
4336 list = ((namedlist_block *)(t->data.ptr))->string;
4337
4338 /* The list could be quite long so we (re)use a buffer for each element
4339 rather than getting each in new memory */
4340
4341 if (is_tainted(list)) buffer = store_get(LISTNAMED_BUF_SIZE, GET_TAINTED);
4342 while ((item = string_nextinlist(&list, &sep, buffer, LISTNAMED_BUF_SIZE)))
4343   {
4344   uschar * buf = US" : ";
4345   if (needsep)
4346     yield = string_catn(yield, buf, 3);
4347   else
4348     needsep = TRUE;
4349
4350   if (*item == '+')     /* list item is itself a named list */
4351     {
4352     yield = expand_listnamed(yield, item, listtype);
4353     if (expand_string_message)
4354       return yield;
4355     }
4356
4357   else if (sep != ':')  /* item from non-colon-sep list, re-quote for colon list-separator */
4358     {
4359     char tok[3];
4360     tok[0] = sep; tok[1] = ':'; tok[2] = 0;
4361
4362     for(char * cp; cp = strpbrk(CCS item, tok); item = US cp)
4363       {
4364       yield = string_catn(yield, item, cp - CS item);
4365       if (*cp++ == ':') /* colon in a non-colon-sep list item, needs doubling */
4366         yield = string_catn(yield, US"::", 2);
4367       else              /* sep in item; should already be doubled; emit once */
4368         {
4369         yield = string_catn(yield, US tok, 1);
4370         if (*cp == sep) cp++;
4371         }
4372       }
4373     yield = string_cat(yield, item);
4374     }
4375   else
4376     yield = string_cat(yield, item);
4377   }
4378 return yield;
4379 }
4380
4381
4382
4383 /************************************************/
4384 static void
4385 debug_expansion_interim(const uschar * what, const uschar * value, int nchar,
4386   BOOL skipping)
4387 {
4388 DEBUG(D_noutf8)
4389   debug_printf_indent("|");
4390 else
4391   debug_printf_indent(UTF8_VERT_RIGHT);
4392
4393 for (int fill = 11 - Ustrlen(what); fill > 0; fill--)
4394   DEBUG(D_noutf8)
4395     debug_printf("-");
4396   else
4397     debug_printf(UTF8_HORIZ);
4398
4399 debug_printf("%s: %.*s\n", what, nchar, value);
4400 if (is_tainted(value))
4401   {
4402   DEBUG(D_noutf8)
4403     debug_printf_indent("%s     \\__", skipping ? "|     " : "      ");
4404   else
4405     debug_printf_indent("%s",
4406       skipping
4407       ? UTF8_VERT "             " : "           " UTF8_UP_RIGHT UTF8_HORIZ UTF8_HORIZ);
4408   debug_printf("(tainted)\n");
4409   }
4410 }
4411
4412
4413 /*************************************************
4414 *                 Expand string                  *
4415 *************************************************/
4416
4417 /* Returns either an unchanged string, or the expanded string in stacking pool
4418 store. Interpreted sequences are:
4419
4420    \...                    normal escaping rules
4421    $name                   substitutes the variable
4422    ${name}                 ditto
4423    ${op:string}            operates on the expanded string value
4424    ${item{arg1}{arg2}...}  expands the args and then does the business
4425                              some literal args are not enclosed in {}
4426
4427 There are now far too many operators and item types to make it worth listing
4428 them here in detail any more.
4429
4430 We use an internal routine recursively to handle embedded substrings. The
4431 external function follows. The yield is NULL if the expansion failed, and there
4432 are two cases: if something collapsed syntactically, or if "fail" was given
4433 as the action on a lookup failure. These can be distinguished by looking at the
4434 variable expand_string_forcedfail, which is TRUE in the latter case.
4435
4436 The skipping flag is set true when expanding a substring that isn't actually
4437 going to be used (after "if" or "lookup") and it prevents lookups from
4438 happening lower down.
4439
4440 Store usage: At start, a store block of the length of the input plus 64
4441 is obtained. This is expanded as necessary by string_cat(), which might have to
4442 get a new block, or might be able to expand the original. At the end of the
4443 function we can release any store above that portion of the yield block that
4444 was actually used. In many cases this will be optimal.
4445
4446 However: if the first item in the expansion is a variable name or header name,
4447 we reset the store before processing it; if the result is in fresh store, we
4448 use that without copying. This is helpful for expanding strings like
4449 $message_headers which can get very long.
4450
4451 There's a problem if a ${dlfunc item has side-effects that cause allocation,
4452 since resetting the store at the end of the expansion will free store that was
4453 allocated by the plugin code as well as the slop after the expanded string. So
4454 we skip any resets if ${dlfunc } has been used. The same applies for ${acl }
4455 and, given the acl condition, ${if }. This is an unfortunate consequence of
4456 string expansion becoming too powerful.
4457
4458 Arguments:
4459   string         the string to be expanded
4460   flags
4461    brace_ends     expansion is to stop at }
4462    honour_dollar  TRUE if $ is to be expanded,
4463                   FALSE if it's just another character
4464    skipping       TRUE for recursive calls when the value isn't actually going
4465                   to be used (to allow for optimisation)
4466   left           if not NULL, a pointer to the first character after the
4467                  expansion is placed here (typically used with brace_ends)
4468   resetok_p      if not NULL, pointer to flag - write FALSE if unsafe to reset
4469                  the store.
4470   textonly_p     if not NULL, pointer to flag - write bool for only-met-text
4471
4472 Returns:         NULL if expansion fails:
4473                    expand_string_forcedfail is set TRUE if failure was forced
4474                    expand_string_message contains a textual error message
4475                  a pointer to the expanded string on success
4476 */
4477
4478 static uschar *
4479 expand_string_internal(const uschar * string, esi_flags flags, const uschar ** left,
4480   BOOL *resetok_p, BOOL * textonly_p)
4481 {
4482 rmark reset_point = store_mark();
4483 gstring * yield = string_get(Ustrlen(string) + 64);
4484 int item_type;
4485 const uschar * s = string;
4486 const uschar * save_expand_nstring[EXPAND_MAXN+1];
4487 int save_expand_nlength[EXPAND_MAXN+1];
4488 BOOL resetok = TRUE, first = TRUE, textonly = TRUE;
4489
4490 expand_level++;
4491 f.expand_string_forcedfail = FALSE;
4492 expand_string_message = US"";
4493
4494 if (is_tainted(string))
4495   {
4496   expand_string_message =
4497     string_sprintf("attempt to expand tainted string '%s'", s);
4498   log_write(0, LOG_MAIN|LOG_PANIC, "%s", expand_string_message);
4499   goto EXPAND_FAILED;
4500   }
4501
4502 while (*s)
4503   {
4504   uschar name[256];
4505
4506   DEBUG(D_expand)
4507     {
4508     DEBUG(D_noutf8)
4509       debug_printf_indent("%c%s: %s\n",
4510         first ? '/' : '|',
4511         flags & ESI_SKIPPING ? "---scanning" : "considering", s);
4512     else
4513       debug_printf_indent("%s%s: %s\n",
4514         first ? UTF8_DOWN_RIGHT : UTF8_VERT_RIGHT,
4515         flags & ESI_SKIPPING
4516         ? UTF8_HORIZ UTF8_HORIZ UTF8_HORIZ "scanning"
4517         : "considering",
4518         s);
4519     first = FALSE;
4520     }
4521
4522   /* \ escapes the next character, which must exist, or else
4523   the expansion fails. There's a special escape, \N, which causes
4524   copying of the subject verbatim up to the next \N. Otherwise,
4525   the escapes are the standard set. */
4526
4527   if (*s == '\\')
4528     {
4529     if (s[1] == 0)
4530       {
4531       expand_string_message = US"\\ at end of string";
4532       goto EXPAND_FAILED;
4533       }
4534
4535     if (s[1] == 'N')
4536       {
4537       const uschar * t = s + 2;
4538       for (s = t; *s ; s++) if (*s == '\\' && s[1] == 'N') break;
4539
4540       DEBUG(D_expand)
4541         debug_expansion_interim(US"protected", t, (int)(s - t), !!(flags & ESI_SKIPPING));
4542       yield = string_catn(yield, t, s - t);
4543       if (*s) s += 2;
4544       }
4545     else
4546       {
4547       uschar ch[1];
4548       DEBUG(D_expand)
4549         DEBUG(D_noutf8)
4550           debug_printf_indent("|backslashed: '\\%c'\n", s[1]);
4551         else
4552           debug_printf_indent(UTF8_VERT_RIGHT "backslashed: '\\%c'\n", s[1]);
4553       ch[0] = string_interpret_escape(&s);
4554       s++;
4555       yield = string_catn(yield, ch, 1);
4556       }
4557     continue;
4558     }
4559
4560                                                                         /*{{*/
4561   /* Anything other than $ is just copied verbatim, unless we are
4562   looking for a terminating } character. */
4563
4564   if (flags & ESI_BRACE_ENDS && *s == '}') break;
4565
4566   if (*s != '$' || !(flags & ESI_HONOR_DOLLAR))
4567     {
4568     int i = 1;                                                          /*{*/
4569     for (const uschar * t = s+1;
4570         *t && *t != '$' && *t != '}' && *t != '\\'; t++) i++;
4571
4572     DEBUG(D_expand) debug_expansion_interim(US"text", s, i, !!(flags & ESI_SKIPPING));
4573
4574     yield = string_catn(yield, s, i);
4575     s += i;
4576     continue;
4577     }
4578   textonly = FALSE;
4579
4580   /* No { after the $ - must be a plain name or a number for string
4581   match variable. There has to be a fudge for variables that are the
4582   names of header fields preceded by "$header_" because header field
4583   names can contain any printing characters except space and colon.
4584   For those that don't like typing this much, "$h_" is a synonym for
4585   "$header_". A non-existent header yields a NULL value; nothing is
4586   inserted. */  /*}*/
4587
4588   if (isalpha(*++s))
4589     {
4590     const uschar * value;
4591     int newsize = 0, len;
4592     gstring * g = NULL;
4593     uschar * t;
4594
4595     s = read_name(name, sizeof(name), s, US"_");
4596
4597     /* If this is the first thing to be expanded, release the pre-allocated
4598     buffer. */
4599
4600     if (!yield)
4601       g = store_get(sizeof(gstring), GET_UNTAINTED);
4602     else if (yield->ptr == 0)
4603       {
4604       if (resetok) reset_point = store_reset(reset_point);
4605       yield = NULL;
4606       reset_point = store_mark();
4607       g = store_get(sizeof(gstring), GET_UNTAINTED);    /* alloc _before_ calling find_variable() */
4608       }
4609
4610     /* Header */
4611
4612     if (  ( *(t = name) == 'h'
4613           || (*t == 'r' || *t == 'l' || *t == 'b') && *++t == 'h'
4614           )
4615        && (*++t == '_' || Ustrncmp(t, "eader_", 6) == 0)
4616        )
4617       {
4618       unsigned flags = *name == 'r' ? FH_WANT_RAW
4619                       : *name == 'l' ? FH_WANT_RAW|FH_WANT_LIST
4620                       : 0;
4621       const uschar * charset = *name == 'b' ? NULL : headers_charset;
4622
4623       s = read_header_name(name, sizeof(name), s);
4624       value = find_header(name, &newsize, flags, charset);
4625
4626       /* If we didn't find the header, and the header contains a closing brace
4627       character, this may be a user error where the terminating colon
4628       has been omitted. Set a flag to adjust the error message in this case.
4629       But there is no error here - nothing gets inserted. */
4630
4631       if (!value)
4632         {                                                               /*{*/
4633         if (Ustrchr(name, '}')) malformed_header = TRUE;
4634         continue;
4635         }
4636       }
4637
4638     /* Variable */
4639
4640     else if (!(value = find_variable(name, FALSE, !!(flags & ESI_SKIPPING), &newsize)))
4641       {
4642       expand_string_message =
4643         string_sprintf("unknown variable name \"%s\"", name);
4644         check_variable_error_message(name);
4645       goto EXPAND_FAILED;
4646       }
4647
4648     /* If the data is known to be in a new buffer, newsize will be set to the
4649     size of that buffer. If this is the first thing in an expansion string,
4650     yield will be NULL; just point it at the new store instead of copying. Many
4651     expansion strings contain just one reference, so this is a useful
4652     optimization, especially for humungous headers.  We need to use a gstring
4653     structure that is not allocated after that new-buffer, else a later store
4654     reset in the middle of the buffer will make it inaccessible. */
4655
4656     len = Ustrlen(value);
4657     if (!yield && newsize != 0)
4658       {
4659       yield = g;
4660       yield->size = newsize;
4661       yield->ptr = len;
4662       yield->s = US value; /* known to be in new store i.e. a copy, so deconst safe */
4663       }
4664     else
4665       yield = string_catn(yield, value, len);
4666
4667     continue;
4668     }
4669
4670   if (isdigit(*s))
4671     {
4672     int n;
4673     s = read_cnumber(&n, s);
4674     if (n >= 0 && n <= expand_nmax)
4675       yield = string_catn(yield, expand_nstring[n], expand_nlength[n]);
4676     continue;
4677     }
4678
4679   /* Otherwise, if there's no '{' after $ it's an error. */             /*}*/
4680
4681   if (*s != '{')                                                        /*}*/
4682     {
4683     expand_string_message = US"$ not followed by letter, digit, or {";  /*}*/
4684     goto EXPAND_FAILED;
4685     }
4686
4687   /* After { there can be various things, but they all start with
4688   an initial word, except for a number for a string match variable. */  /*}*/
4689
4690   if (isdigit(*++s))
4691     {
4692     int n;
4693     s = read_cnumber(&n, s);                                            /*{{*/
4694     if (*s++ != '}')
4695       {
4696       expand_string_message = US"} expected after number";
4697       goto EXPAND_FAILED;
4698       }
4699     if (n >= 0 && n <= expand_nmax)
4700       yield = string_catn(yield, expand_nstring[n], expand_nlength[n]);
4701     continue;
4702     }
4703
4704   if (!isalpha(*s))
4705     {
4706     expand_string_message = US"letter or digit expected after ${";      /*}*/
4707     goto EXPAND_FAILED;
4708     }
4709
4710   /* Allow "-" in names to cater for substrings with negative
4711   arguments. Since we are checking for known names after { this is
4712   OK. */                                                                /*}*/
4713
4714   s = read_name(name, sizeof(name), s, US"_-");
4715   item_type = chop_match(name, item_table, nelem(item_table));
4716
4717   /* Switch on item type.  All nondefault choices should "continue* when
4718   skipping, but "break" otherwise so we get debug output for the item
4719   expansion. */
4720   {
4721   int start = gstring_length(yield);
4722   switch(item_type)
4723     {
4724     /* Call an ACL from an expansion.  We feed data in via $acl_arg1 - $acl_arg9.
4725     If the ACL returns accept or reject we return content set by "message ="
4726     There is currently no limit on recursion; this would have us call
4727     acl_check_internal() directly and get a current level from somewhere.
4728     See also the acl expansion condition ECOND_ACL and the traditional
4729     acl modifier ACLC_ACL.
4730     Assume that the function has side-effects on the store that must be preserved.
4731     */
4732
4733     case EITEM_ACL:
4734       /* ${acl {name} {arg1}{arg2}...} */
4735       {
4736       uschar * sub[10]; /* name + arg1-arg9 (which must match number of acl_arg[]) */
4737       uschar * user_msg;
4738       int rc;
4739
4740       switch(read_subs(sub, nelem(sub), 1, &s, flags, TRUE, name, &resetok, NULL))
4741         {
4742         case -1: continue;              /* skipping */
4743         case 1: goto EXPAND_FAILED_CURLY;
4744         case 2:
4745         case 3: goto EXPAND_FAILED;
4746         }
4747
4748       resetok = FALSE;
4749       switch(rc = eval_acl(sub, nelem(sub), &user_msg))
4750         {
4751         case OK:
4752         case FAIL:
4753           DEBUG(D_expand)
4754             debug_printf_indent("acl expansion yield: %s\n", user_msg);
4755           if (user_msg)
4756             yield = string_cat(yield, user_msg);
4757           break;
4758
4759         case DEFER:
4760           f.expand_string_forcedfail = TRUE;
4761           /*FALLTHROUGH*/
4762         default:
4763           expand_string_message = string_sprintf("%s from acl \"%s\"",
4764             rc_names[rc], sub[0]);
4765           goto EXPAND_FAILED;
4766         }
4767       break;
4768       }
4769
4770     case EITEM_AUTHRESULTS:
4771       /* ${authresults {mysystemname}} */
4772       {
4773       uschar * sub_arg[1];
4774
4775       switch(read_subs(sub_arg, nelem(sub_arg), 1, &s, flags, TRUE, name, &resetok, NULL))
4776         {
4777         case 1: goto EXPAND_FAILED_CURLY;
4778         case 2:
4779         case 3: goto EXPAND_FAILED;
4780         }
4781       /*XXX no skipping-optimisation? */
4782
4783       yield = string_append(yield, 3,
4784                         US"Authentication-Results: ", sub_arg[0], US"; none");
4785       yield->ptr -= 6;
4786
4787       yield = authres_local(yield, sub_arg[0]);
4788       yield = authres_iprev(yield);
4789       yield = authres_smtpauth(yield);
4790 #ifdef SUPPORT_SPF
4791       yield = authres_spf(yield);
4792 #endif
4793 #ifndef DISABLE_DKIM
4794       yield = authres_dkim(yield);
4795 #endif
4796 #ifdef SUPPORT_DMARC
4797       yield = authres_dmarc(yield);
4798 #endif
4799 #ifdef EXPERIMENTAL_ARC
4800       yield = authres_arc(yield);
4801 #endif
4802       break;
4803       }
4804
4805     /* Handle conditionals - preserve the values of the numerical expansion
4806     variables in case they get changed by a regular expression match in the
4807     condition. If not, they retain their external settings. At the end
4808     of this "if" section, they get restored to their previous values. */
4809
4810     case EITEM_IF:
4811       {
4812       BOOL cond = FALSE;
4813       const uschar *next_s;
4814       int save_expand_nmax =
4815         save_expand_strings(save_expand_nstring, save_expand_nlength);
4816       uschar * save_lookup_value = lookup_value;
4817
4818       Uskip_whitespace(&s);
4819       if (!(next_s = eval_condition(s, &resetok, flags & ESI_SKIPPING ? NULL : &cond)))
4820         goto EXPAND_FAILED;  /* message already set */
4821
4822       DEBUG(D_expand)
4823         {
4824         debug_expansion_interim(US"condition", s, (int)(next_s - s), !!(flags & ESI_SKIPPING));
4825         debug_expansion_interim(US"result",
4826           cond ? US"true" : US"false", cond ? 4 : 5, !!(flags & ESI_SKIPPING));
4827         }
4828
4829       s = next_s;
4830
4831       /* The handling of "yes" and "no" result strings is now in a separate
4832       function that is also used by ${lookup} and ${extract} and ${run}. */
4833
4834       switch(process_yesno(
4835                flags,                   /* were previously skipping */
4836                cond,                    /* success/failure indicator */
4837                lookup_value,                    /* value to reset for string2 */
4838                &s,                      /* input pointer */
4839                &yield,                  /* output pointer */
4840                US"if",                  /* condition type */
4841                &resetok))
4842         {
4843         case 1: goto EXPAND_FAILED;          /* when all is well, the */
4844         case 2: goto EXPAND_FAILED_CURLY;    /* returned value is 0 */
4845         }
4846
4847       /* Restore external setting of expansion variables for continuation
4848       at this level. */
4849
4850       lookup_value = save_lookup_value;
4851       restore_expand_strings(save_expand_nmax, save_expand_nstring,
4852         save_expand_nlength);
4853       break;
4854       }
4855
4856 #ifdef SUPPORT_I18N
4857     case EITEM_IMAPFOLDER:
4858       {                         /* ${imapfolder {name}{sep}{specials}} */
4859       uschar *sub_arg[3];
4860       uschar *encoded;
4861
4862       switch(read_subs(sub_arg, nelem(sub_arg), 1, &s, flags, TRUE, name, &resetok, NULL))
4863         {
4864         case 1: goto EXPAND_FAILED_CURLY;
4865         case 2:
4866         case 3: goto EXPAND_FAILED;
4867         }
4868       /*XXX no skipping-optimisation? */
4869
4870       if (!sub_arg[1])                  /* One argument */
4871         {
4872         sub_arg[1] = US"/";             /* default separator */
4873         sub_arg[2] = NULL;
4874         }
4875       else if (Ustrlen(sub_arg[1]) != 1)
4876         {
4877         expand_string_message =
4878           string_sprintf(
4879                 "IMAP folder separator must be one character, found \"%s\"",
4880                 sub_arg[1]);
4881         goto EXPAND_FAILED;
4882         }
4883
4884       if (flags & ESI_SKIPPING) continue;
4885
4886       if (!(encoded = imap_utf7_encode(sub_arg[0], headers_charset,
4887                           sub_arg[1][0], sub_arg[2], &expand_string_message)))
4888         goto EXPAND_FAILED;
4889       yield = string_cat(yield, encoded);
4890       break;
4891       }
4892 #endif
4893
4894     /* Handle database lookups unless locked out. If "skipping" is TRUE, we are
4895     expanding an internal string that isn't actually going to be used. All we
4896     need to do is check the syntax, so don't do a lookup at all. Preserve the
4897     values of the numerical expansion variables in case they get changed by a
4898     partial lookup. If not, they retain their external settings. At the end
4899     of this "lookup" section, they get restored to their previous values. */
4900
4901     case EITEM_LOOKUP:
4902       {
4903       int stype, partial, affixlen, starflags;
4904       int expand_setup = 0;
4905       int nameptr = 0;
4906       uschar * key, * filename;
4907       const uschar * affix, * opts;
4908       uschar * save_lookup_value = lookup_value;
4909       int save_expand_nmax =
4910         save_expand_strings(save_expand_nstring, save_expand_nlength);
4911
4912       if (expand_forbid & RDO_LOOKUP)
4913         {
4914         expand_string_message = US"lookup expansions are not permitted";
4915         goto EXPAND_FAILED;
4916         }
4917
4918       /* Get the key we are to look up for single-key+file style lookups.
4919       Otherwise set the key NULL pro-tem. */
4920
4921       if (Uskip_whitespace(&s) == '{')                                  /*}*/
4922         {
4923         key = expand_string_internal(s+1,
4924                 ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | flags, &s, &resetok, NULL);
4925         if (!key) goto EXPAND_FAILED;                   /*{{*/
4926         if (*s++ != '}')
4927           {
4928           expand_string_message = US"missing '}' after lookup key";
4929           goto EXPAND_FAILED_CURLY;
4930           }
4931         Uskip_whitespace(&s);
4932         }
4933       else key = NULL;
4934
4935       /* Find out the type of database */
4936
4937       if (!isalpha(*s))
4938         {
4939         expand_string_message = US"missing lookup type";
4940         goto EXPAND_FAILED;
4941         }
4942
4943       /* The type is a string that may contain special characters of various
4944       kinds. Allow everything except space or { to appear; the actual content
4945       is checked by search_findtype_partial. */         /*}*/
4946
4947       while (*s && *s != '{' && !isspace(*s))           /*}*/
4948         {
4949         if (nameptr < sizeof(name) - 1) name[nameptr++] = *s;
4950         s++;
4951         }
4952       name[nameptr] = '\0';
4953       Uskip_whitespace(&s);
4954
4955       /* Now check for the individual search type and any partial or default
4956       options. Only those types that are actually in the binary are valid. */
4957
4958       if ((stype = search_findtype_partial(name, &partial, &affix, &affixlen,
4959           &starflags, &opts)) < 0)
4960         {
4961         expand_string_message = search_error_message;
4962         goto EXPAND_FAILED;
4963         }
4964
4965       /* Check that a key was provided for those lookup types that need it,
4966       and was not supplied for those that use the query style. */
4967
4968       if (!mac_islookup(stype, lookup_querystyle|lookup_absfilequery))
4969         {
4970         if (!key)
4971           {
4972           expand_string_message = string_sprintf("missing {key} for single-"
4973             "key \"%s\" lookup", name);
4974           goto EXPAND_FAILED;
4975           }
4976         }
4977       else if (key)
4978         {
4979         expand_string_message = string_sprintf("a single key was given for "
4980           "lookup type \"%s\", which is not a single-key lookup type", name);
4981         goto EXPAND_FAILED;
4982         }
4983
4984       /* Get the next string in brackets and expand it. It is the file name for
4985       single-key+file lookups, and the whole query otherwise. In the case of
4986       queries that also require a file name (e.g. sqlite), the file name comes
4987       first. */
4988
4989       if (*s != '{')
4990         {
4991         expand_string_message = US"missing '{' for lookup file-or-query arg";
4992         goto EXPAND_FAILED_CURLY;                                               /*}}*/
4993         }
4994       if (!(filename = expand_string_internal(s+1,
4995                 ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | flags, &s, &resetok, NULL)))
4996         goto EXPAND_FAILED;
4997                                                                                 /*{{*/
4998       if (*s++ != '}')
4999         {
5000         expand_string_message = US"missing '}' closing lookup file-or-query arg";
5001         goto EXPAND_FAILED_CURLY;
5002         }
5003       Uskip_whitespace(&s);
5004
5005       /* If this isn't a single-key+file lookup, re-arrange the variables
5006       to be appropriate for the search_ functions. For query-style lookups,
5007       there is just a "key", and no file name. For the special query-style +
5008       file types, the query (i.e. "key") starts with a file name. */
5009
5010       if (!key)
5011         key = search_args(stype, name, filename, &filename, opts);
5012
5013       /* If skipping, don't do the next bit - just lookup_value == NULL, as if
5014       the entry was not found. Note that there is no search_close() function.
5015       Files are left open in case of re-use. At suitable places in higher logic,
5016       search_tidyup() is called to tidy all open files. This can save opening
5017       the same file several times. However, files may also get closed when
5018       others are opened, if too many are open at once. The rule is that a
5019       handle should not be used after a second search_open().
5020
5021       Request that a partial search sets up $1 and maybe $2 by passing
5022       expand_setup containing zero. If its value changes, reset expand_nmax,
5023       since new variables will have been set. Note that at the end of this
5024       "lookup" section, the old numeric variables are restored. */
5025
5026       if (flags & ESI_SKIPPING)
5027         lookup_value = NULL;
5028       else
5029         {
5030         void * handle = search_open(filename, stype, 0, NULL, NULL);
5031         if (!handle)
5032           {
5033           expand_string_message = search_error_message;
5034           goto EXPAND_FAILED;
5035           }
5036         lookup_value = search_find(handle, filename, key, partial, affix,
5037           affixlen, starflags, &expand_setup, opts);
5038         if (f.search_find_defer)
5039           {
5040           expand_string_message =
5041             string_sprintf("lookup of \"%s\" gave DEFER: %s",
5042               string_printing2(key, SP_TAB), search_error_message);
5043           goto EXPAND_FAILED;
5044           }
5045         if (expand_setup > 0) expand_nmax = expand_setup;
5046         }
5047
5048       /* The handling of "yes" and "no" result strings is now in a separate
5049       function that is also used by ${if} and ${extract}. */
5050
5051       switch(process_yesno(
5052                flags,                   /* were previously skipping */
5053                lookup_value != NULL,    /* success/failure indicator */
5054                save_lookup_value,       /* value to reset for string2 */
5055                &s,                      /* input pointer */
5056                &yield,                  /* output pointer */
5057                US"lookup",              /* condition type */
5058                &resetok))
5059         {
5060         case 1: goto EXPAND_FAILED;          /* when all is well, the */
5061         case 2: goto EXPAND_FAILED_CURLY;    /* returned value is 0 */
5062         }
5063
5064       /* Restore external setting of expansion variables for carrying on
5065       at this level, and continue. */
5066
5067       restore_expand_strings(save_expand_nmax, save_expand_nstring,
5068         save_expand_nlength);
5069
5070       if (flags & ESI_SKIPPING) continue;
5071       break;
5072       }
5073
5074     /* If Perl support is configured, handle calling embedded perl subroutines,
5075     unless locked out at this time. Syntax is ${perl{sub}} or ${perl{sub}{arg}}
5076     or ${perl{sub}{arg1}{arg2}} or up to a maximum of EXIM_PERL_MAX_ARGS
5077     arguments (defined below). */
5078
5079 #define EXIM_PERL_MAX_ARGS 8
5080
5081     case EITEM_PERL:
5082 #ifndef EXIM_PERL
5083       expand_string_message = US"\"${perl\" encountered, but this facility "    /*}*/
5084         "is not included in this binary";
5085       goto EXPAND_FAILED;
5086
5087 #else   /* EXIM_PERL */
5088       {
5089       uschar * sub_arg[EXIM_PERL_MAX_ARGS + 2];
5090       gstring * new_yield;
5091
5092       if (expand_forbid & RDO_PERL)
5093         {
5094         expand_string_message = US"Perl calls are not permitted";
5095         goto EXPAND_FAILED;
5096         }
5097
5098       switch(read_subs(sub_arg, EXIM_PERL_MAX_ARGS + 1, 1, &s, flags, TRUE,
5099            name, &resetok, NULL))
5100         {
5101         case -1: continue;      /* If skipping, we don't actually do anything */
5102         case 1: goto EXPAND_FAILED_CURLY;
5103         case 2:
5104         case 3: goto EXPAND_FAILED;
5105         }
5106
5107       /* Start the interpreter if necessary */
5108
5109       if (!opt_perl_started)
5110         {
5111         uschar * initerror;
5112         if (!opt_perl_startup)
5113           {
5114           expand_string_message = US"A setting of perl_startup is needed when "
5115             "using the Perl interpreter";
5116           goto EXPAND_FAILED;
5117           }
5118         DEBUG(D_any) debug_printf("Starting Perl interpreter\n");
5119         if ((initerror = init_perl(opt_perl_startup)))
5120           {
5121           expand_string_message =
5122             string_sprintf("error in perl_startup code: %s\n", initerror);
5123           goto EXPAND_FAILED;
5124           }
5125         opt_perl_started = TRUE;
5126         }
5127
5128       /* Call the function */
5129
5130       sub_arg[EXIM_PERL_MAX_ARGS + 1] = NULL;
5131       new_yield = call_perl_cat(yield, &expand_string_message,
5132         sub_arg[0], sub_arg + 1);
5133
5134       /* NULL yield indicates failure; if the message pointer has been set to
5135       NULL, the yield was undef, indicating a forced failure. Otherwise the
5136       message will indicate some kind of Perl error. */
5137
5138       if (!new_yield)
5139         {
5140         if (!expand_string_message)
5141           {
5142           expand_string_message =
5143             string_sprintf("Perl subroutine \"%s\" returned undef to force "
5144               "failure", sub_arg[0]);
5145           f.expand_string_forcedfail = TRUE;
5146           }
5147         goto EXPAND_FAILED;
5148         }
5149
5150       /* Yield succeeded. Ensure forcedfail is unset, just in case it got
5151       set during a callback from Perl. */
5152
5153       f.expand_string_forcedfail = FALSE;
5154       yield = new_yield;
5155       break;
5156       }
5157 #endif /* EXIM_PERL */
5158
5159     /* Transform email address to "prvs" scheme to use
5160        as BATV-signed return path */
5161
5162     case EITEM_PRVS:
5163       {
5164       uschar * sub_arg[3], * p, * domain;
5165
5166       switch(read_subs(sub_arg, 3, 2, &s, flags, TRUE, name, &resetok, NULL))
5167         {
5168         case -1: continue;      /* If skipping, we don't actually do anything */
5169         case 1: goto EXPAND_FAILED_CURLY;
5170         case 2:
5171         case 3: goto EXPAND_FAILED;
5172         }
5173
5174       /* sub_arg[0] is the address */
5175       if (  !(domain = Ustrrchr(sub_arg[0],'@'))
5176          || domain == sub_arg[0] || Ustrlen(domain) == 1)
5177         {
5178         expand_string_message = US"prvs first argument must be a qualified email address";
5179         goto EXPAND_FAILED;
5180         }
5181
5182       /* Calculate the hash. The third argument must be a single-digit
5183       key number, or unset. */
5184
5185       if (  sub_arg[2]
5186          && (!isdigit(sub_arg[2][0]) || sub_arg[2][1] != 0))
5187         {
5188         expand_string_message = US"prvs third argument must be a single digit";
5189         goto EXPAND_FAILED;
5190         }
5191
5192       p = prvs_hmac_sha1(sub_arg[0], sub_arg[1], sub_arg[2], prvs_daystamp(7));
5193       if (!p)
5194         {
5195         expand_string_message = US"prvs hmac-sha1 conversion failed";
5196         goto EXPAND_FAILED;
5197         }
5198
5199       /* Now separate the domain from the local part */
5200       *domain++ = '\0';
5201
5202       yield = string_catn(yield, US"prvs=", 5);
5203       yield = string_catn(yield, sub_arg[2] ? sub_arg[2] : US"0", 1);
5204       yield = string_catn(yield, prvs_daystamp(7), 3);
5205       yield = string_catn(yield, p, 6);
5206       yield = string_catn(yield, US"=", 1);
5207       yield = string_cat (yield, sub_arg[0]);
5208       yield = string_catn(yield, US"@", 1);
5209       yield = string_cat (yield, domain);
5210
5211       break;
5212       }
5213
5214     /* Check a prvs-encoded address for validity */
5215
5216     case EITEM_PRVSCHECK:
5217       {
5218       uschar * sub_arg[3], * p;
5219       gstring * g;
5220       const pcre2_code * re;
5221
5222       /* Reset expansion variables */
5223       prvscheck_result = NULL;
5224       prvscheck_address = NULL;
5225       prvscheck_keynum = NULL;
5226
5227       switch(read_subs(sub_arg, 1, 1, &s, flags, FALSE, name, &resetok, NULL))
5228         {
5229         case 1: goto EXPAND_FAILED_CURLY;
5230         case 2:
5231         case 3: goto EXPAND_FAILED;
5232         }
5233
5234       re = regex_must_compile(
5235         US"^prvs\\=([0-9])([0-9]{3})([A-F0-9]{6})\\=(.+)\\@(.+)$",
5236         MCS_CASELESS | MCS_CACHEABLE, FALSE);
5237
5238       if (regex_match_and_setup(re,sub_arg[0],0,-1))
5239         {
5240         uschar * local_part = string_copyn(expand_nstring[4],expand_nlength[4]);
5241         uschar * key_num = string_copyn(expand_nstring[1],expand_nlength[1]);
5242         uschar * daystamp = string_copyn(expand_nstring[2],expand_nlength[2]);
5243         uschar * hash = string_copyn(expand_nstring[3],expand_nlength[3]);
5244         uschar * domain = string_copyn(expand_nstring[5],expand_nlength[5]);
5245
5246         DEBUG(D_expand)
5247           {
5248           debug_printf_indent("prvscheck localpart: %s\n", local_part);
5249           debug_printf_indent("prvscheck key number: %s\n", key_num);
5250           debug_printf_indent("prvscheck daystamp: %s\n", daystamp);
5251           debug_printf_indent("prvscheck hash: %s\n", hash);
5252           debug_printf_indent("prvscheck domain: %s\n", domain);
5253           }
5254
5255         /* Set up expansion variables */
5256         g = string_cat (NULL, local_part);
5257         g = string_catn(g, US"@", 1);
5258         g = string_cat (g, domain);
5259         prvscheck_address = string_from_gstring(g);
5260         prvscheck_keynum = string_copy(key_num);
5261
5262         /* Now expand the second argument */
5263         switch(read_subs(sub_arg, 1, 1, &s, flags, FALSE, name, &resetok, NULL))
5264           {
5265           case 1: goto EXPAND_FAILED_CURLY;
5266           case 2:
5267           case 3: goto EXPAND_FAILED;
5268           }
5269
5270         /* Now we have the key and can check the address. */
5271
5272         p = prvs_hmac_sha1(prvscheck_address, sub_arg[0], prvscheck_keynum,
5273           daystamp);
5274         if (!p)
5275           {
5276           expand_string_message = US"hmac-sha1 conversion failed";
5277           goto EXPAND_FAILED;
5278           }
5279
5280         DEBUG(D_expand) debug_printf_indent("prvscheck: received hash is %s\n", hash);
5281         DEBUG(D_expand) debug_printf_indent("prvscheck:      own hash is %s\n", p);
5282
5283         if (Ustrcmp(p,hash) == 0)
5284           {
5285           /* Success, valid BATV address. Now check the expiry date. */
5286           uschar *now = prvs_daystamp(0);
5287           unsigned int inow = 0,iexpire = 1;
5288
5289           (void)sscanf(CS now,"%u",&inow);
5290           (void)sscanf(CS daystamp,"%u",&iexpire);
5291
5292           /* When "iexpire" is < 7, a "flip" has occurred.
5293              Adjust "inow" accordingly. */
5294           if ( (iexpire < 7) && (inow >= 993) ) inow = 0;
5295
5296           if (iexpire >= inow)
5297             {
5298             prvscheck_result = US"1";
5299             DEBUG(D_expand) debug_printf_indent("prvscheck: success, $pvrs_result set to 1\n");
5300             }
5301           else
5302             {
5303             prvscheck_result = NULL;
5304             DEBUG(D_expand) debug_printf_indent("prvscheck: signature expired, $pvrs_result unset\n");
5305             }
5306           }
5307         else
5308           {
5309           prvscheck_result = NULL;
5310           DEBUG(D_expand) debug_printf_indent("prvscheck: hash failure, $pvrs_result unset\n");
5311           }
5312
5313         /* Now expand the final argument. We leave this till now so that
5314         it can include $prvscheck_result. */
5315
5316         switch(read_subs(sub_arg, 1, 0, &s, flags, TRUE, name, &resetok, NULL))
5317           {
5318           case 1: goto EXPAND_FAILED_CURLY;
5319           case 2:
5320           case 3: goto EXPAND_FAILED;
5321           }
5322
5323         yield = string_cat(yield,
5324           !sub_arg[0] || !*sub_arg[0] ? prvscheck_address : sub_arg[0]);
5325
5326         /* Reset the "internal" variables afterwards, because they are in
5327         dynamic store that will be reclaimed if the expansion succeeded. */
5328
5329         prvscheck_address = NULL;
5330         prvscheck_keynum = NULL;
5331         }
5332       else
5333         /* Does not look like a prvs encoded address, return the empty string.
5334            We need to make sure all subs are expanded first, so as to skip over
5335            the entire item. */
5336
5337         switch(read_subs(sub_arg, 2, 1, &s, flags, TRUE, name, &resetok, NULL))
5338           {
5339           case 1: goto EXPAND_FAILED_CURLY;
5340           case 2:
5341           case 3: goto EXPAND_FAILED;
5342           }
5343
5344       if (flags & ESI_SKIPPING) continue;
5345       break;
5346       }
5347
5348     /* Handle "readfile" to insert an entire file */
5349
5350     case EITEM_READFILE:
5351       {
5352       FILE * f;
5353       uschar * sub_arg[2];
5354
5355       if ((expand_forbid & RDO_READFILE) != 0)
5356         {
5357         expand_string_message = US"file insertions are not permitted";
5358         goto EXPAND_FAILED;
5359         }
5360
5361       switch(read_subs(sub_arg, 2, 1, &s, flags, TRUE, name, &resetok, NULL))
5362         {
5363         case 1: goto EXPAND_FAILED_CURLY;
5364         case 2:
5365         case 3: goto EXPAND_FAILED;
5366         }
5367
5368       /* If skipping, we don't actually do anything */
5369
5370       if (flags & ESI_SKIPPING) continue;
5371
5372       /* Open the file and read it */
5373
5374       if (!(f = Ufopen(sub_arg[0], "rb")))
5375         {
5376         expand_string_message = string_open_failed("%s", sub_arg[0]);
5377         goto EXPAND_FAILED;
5378         }
5379
5380       yield = cat_file(f, yield, sub_arg[1]);
5381       (void)fclose(f);
5382       break;
5383       }
5384
5385     /* Handle "readsocket" to insert data from a socket, either
5386     Inet or Unix domain */
5387
5388     case EITEM_READSOCK:
5389       {
5390       uschar * arg;
5391       uschar * sub_arg[4];
5392
5393       if (expand_forbid & RDO_READSOCK)
5394         {
5395         expand_string_message = US"socket insertions are not permitted";
5396         goto EXPAND_FAILED;
5397         }
5398
5399       /* Read up to 4 arguments, but don't do the end of item check afterwards,
5400       because there may be a string for expansion on failure. */
5401
5402       switch(read_subs(sub_arg, 4, 2, &s, flags, FALSE, name, &resetok, NULL))
5403         {
5404         case 1: goto EXPAND_FAILED_CURLY;
5405         case 2:                             /* Won't occur: no end check */
5406         case 3: goto EXPAND_FAILED;
5407         }
5408
5409       /* If skipping, we don't actually do anything. Otherwise, arrange to
5410       connect to either an IP or a Unix socket. */
5411
5412       if (!(flags & ESI_SKIPPING))
5413         {
5414         int stype = search_findtype(US"readsock", 8);
5415         gstring * g = NULL;
5416         void * handle;
5417         int expand_setup = -1;
5418         uschar * s;
5419
5420         /* If the reqstr is empty, flag that and set a dummy */
5421
5422         if (!sub_arg[1][0])
5423           {
5424           g = string_append_listele(g, ',', US"send=no");
5425           sub_arg[1] = US"DUMMY";
5426           }
5427
5428         /* Re-marshall the options */
5429
5430         if (sub_arg[2])
5431           {
5432           const uschar * list = sub_arg[2];
5433           uschar * item;
5434           int sep = 0;
5435
5436           /* First option has no tag and is timeout */
5437           if ((item = string_nextinlist(&list, &sep, NULL, 0)))
5438             g = string_append_listele(g, ',',
5439                   string_sprintf("timeout=%s", item));
5440
5441           /* The rest of the options from the expansion */
5442           while ((item = string_nextinlist(&list, &sep, NULL, 0)))
5443             g = string_append_listele(g, ',', item);
5444
5445           /* possibly plus an EOL string.  Process with escapes, to protect
5446           from list-processing.  The only current user of eol= in search
5447           options is the readsock expansion. */
5448
5449           if (sub_arg[3] && *sub_arg[3])
5450             g = string_append_listele(g, ',',
5451                   string_sprintf("eol=%s",
5452                     string_printing2(sub_arg[3], SP_TAB|SP_SPACE)));
5453           }
5454
5455         /* Gat a (possibly cached) handle for the connection */
5456
5457         if (!(handle = search_open(sub_arg[0], stype, 0, NULL, NULL)))
5458           {
5459           if (*expand_string_message) goto EXPAND_FAILED;
5460           expand_string_message = search_error_message;
5461           search_error_message = NULL;
5462           goto SOCK_FAIL;
5463           }
5464
5465         /* Get (possibly cached) results for the lookup */
5466         /* sspec: sub_arg[0]  req: sub_arg[1]  opts: g */
5467
5468         if ((s = search_find(handle, sub_arg[0], sub_arg[1], -1, NULL, 0, 0,
5469                                     &expand_setup, string_from_gstring(g))))
5470           yield = string_cat(yield, s);
5471         else if (f.search_find_defer)
5472           {
5473           expand_string_message = search_error_message;
5474           search_error_message = NULL;
5475           goto SOCK_FAIL;
5476           }
5477         else
5478           {     /* should not happen, at present */
5479           expand_string_message = search_error_message;
5480           search_error_message = NULL;
5481           goto SOCK_FAIL;
5482           }
5483         }
5484
5485       /* The whole thing has worked (or we were skipping). If there is a
5486       failure string following, we need to skip it. */
5487
5488       if (*s == '{')                                                    /*}*/
5489         {
5490         if (!expand_string_internal(s+1,
5491           ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | ESI_SKIPPING, &s, &resetok, NULL))
5492           goto EXPAND_FAILED;                                           /*{*/
5493         if (*s++ != '}')
5494           {                                                             /*{*/
5495           expand_string_message = US"missing '}' closing failstring for readsocket";
5496           goto EXPAND_FAILED_CURLY;
5497           }
5498         Uskip_whitespace(&s);
5499         }
5500
5501     READSOCK_DONE:                                                      /*{*/
5502       if (*s++ != '}')
5503         {                                                               /*{*/
5504         expand_string_message = US"missing '}' closing readsocket";
5505         goto EXPAND_FAILED_CURLY;
5506         }
5507       if (flags & ESI_SKIPPING) continue;
5508       break;
5509
5510       /* Come here on failure to create socket, connect socket, write to the
5511       socket, or timeout on reading. If another substring follows, expand and
5512       use it. Otherwise, those conditions give expand errors. */
5513
5514     SOCK_FAIL:
5515       if (*s != '{') goto EXPAND_FAILED;                                /*}*/
5516       DEBUG(D_any) debug_printf("%s\n", expand_string_message);
5517       if (!(arg = expand_string_internal(s+1,
5518                     ESI_BRACE_ENDS | ESI_HONOR_DOLLAR, &s, &resetok, NULL)))
5519         goto EXPAND_FAILED;
5520       yield = string_cat(yield, arg);                                   /*{*/
5521       if (*s++ != '}')
5522         {                                                               /*{*/
5523         expand_string_message = US"missing '}' closing failstring for readsocket";
5524         goto EXPAND_FAILED_CURLY;
5525         }
5526       Uskip_whitespace(&s);
5527       goto READSOCK_DONE;
5528       }
5529
5530     /* Handle "run" to execute a program. */
5531
5532     case EITEM_RUN:
5533       {
5534       FILE * f;
5535       const uschar * arg, ** argv;
5536       BOOL late_expand = TRUE;
5537
5538       if ((expand_forbid & RDO_RUN) != 0)
5539         {
5540         expand_string_message = US"running a command is not permitted";
5541         goto EXPAND_FAILED;
5542         }
5543
5544       /* Handle options to the "run" */
5545
5546       while (*s == ',')
5547         {
5548         if (Ustrncmp(++s, "preexpand", 9) == 0)
5549           { late_expand = FALSE; s += 9; }
5550         else
5551           {
5552           const uschar * t = s;
5553           while (isalpha(*++t)) ;
5554           expand_string_message = string_sprintf("bad option '%.*s' for run",
5555                                                   (int)(t-s), s);
5556           goto EXPAND_FAILED;
5557           }
5558         }
5559       Uskip_whitespace(&s);
5560
5561       if (*s != '{')                                    /*}*/
5562         {
5563         expand_string_message = US"missing '{' for command arg of run";
5564         goto EXPAND_FAILED_CURLY;                       /*"}*/
5565         }
5566       s++;
5567
5568       if (late_expand)          /* this is the default case */
5569         {                                               /*{*/
5570         int n = Ustrcspn(s, "}");
5571         arg = flags & ESI_SKIPPING ? NULL : string_copyn(s, n);
5572         s += n;
5573         }
5574       else
5575         {
5576         if (!(arg = expand_string_internal(s,
5577                 ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | flags, &s, &resetok, NULL)))
5578           goto EXPAND_FAILED;
5579         Uskip_whitespace(&s);
5580         }
5581                                                         /*{*/
5582       if (*s++ != '}')
5583         {                                               /*{*/
5584         expand_string_message = US"missing '}' closing command arg of run";
5585         goto EXPAND_FAILED_CURLY;
5586         }
5587
5588       if (flags & ESI_SKIPPING)   /* Just pretend it worked when we're skipping */
5589         {
5590         runrc = 0;
5591         lookup_value = NULL;
5592         }
5593       else
5594         {
5595         int fd_in, fd_out;
5596         pid_t pid;
5597
5598         if (!transport_set_up_command(&argv,    /* anchor for arg list */
5599             arg,                                /* raw command */
5600             late_expand,                /* expand args if not already done */
5601             0,                          /* not relevant when... */
5602             NULL,                       /* no transporting address */
5603             late_expand,                /* allow tainted args, when expand-after-split */
5604             US"${run} expansion",       /* for error messages */
5605             &expand_string_message))    /* where to put error message */
5606           goto EXPAND_FAILED;
5607
5608         /* Create the child process, making it a group leader. */
5609
5610         if ((pid = child_open(USS argv, NULL, 0077, &fd_in, &fd_out, TRUE,
5611                               US"expand-run")) < 0)
5612           {
5613           expand_string_message =
5614             string_sprintf("couldn't create child process: %s", strerror(errno));
5615           goto EXPAND_FAILED;
5616           }
5617
5618         /* Nothing is written to the standard input. */
5619
5620         (void)close(fd_in);
5621
5622         /* Read the pipe to get the command's output into $value (which is kept
5623         in lookup_value). Read during execution, so that if the output exceeds
5624         the OS pipe buffer limit, we don't block forever. Remember to not release
5625         memory just allocated for $value. */
5626
5627         resetok = FALSE;
5628         f = fdopen(fd_out, "rb");
5629         sigalrm_seen = FALSE;
5630         ALARM(60);
5631         lookup_value = string_from_gstring(cat_file(f, NULL, NULL));
5632         ALARM_CLR(0);
5633         (void)fclose(f);
5634
5635         /* Wait for the process to finish, applying the timeout, and inspect its
5636         return code for serious disasters. Simple non-zero returns are passed on.
5637         */
5638
5639         if (sigalrm_seen || (runrc = child_close(pid, 30)) < 0)
5640           {
5641           if (sigalrm_seen || runrc == -256)
5642             {
5643             expand_string_message = US"command timed out";
5644             killpg(pid, SIGKILL);       /* Kill the whole process group */
5645             }
5646
5647           else if (runrc == -257)
5648             expand_string_message = string_sprintf("wait() failed: %s",
5649               strerror(errno));
5650
5651           else
5652             expand_string_message = string_sprintf("command killed by signal %d",
5653               -runrc);
5654
5655           goto EXPAND_FAILED;
5656           }
5657         }
5658
5659       /* Process the yes/no strings; $value may be useful in both cases */
5660
5661       switch(process_yesno(
5662                flags,                   /* were previously skipping */
5663                runrc == 0,              /* success/failure indicator */
5664                lookup_value,            /* value to reset for string2 */
5665                &s,                      /* input pointer */
5666                &yield,                  /* output pointer */
5667                US"run",                 /* condition type */
5668                &resetok))
5669         {
5670         case 1: goto EXPAND_FAILED;          /* when all is well, the */
5671         case 2: goto EXPAND_FAILED_CURLY;    /* returned value is 0 */
5672         }
5673
5674       if (flags & ESI_SKIPPING) continue;
5675       break;
5676       }
5677
5678     /* Handle character translation for "tr" */
5679
5680     case EITEM_TR:
5681       {
5682       int oldptr = gstring_length(yield);
5683       int o2m;
5684       uschar * sub[3];
5685
5686       switch(read_subs(sub, 3, 3, &s, flags, TRUE, name, &resetok, NULL))
5687         {
5688         case -1: continue;      /* skipping */
5689         case 1: goto EXPAND_FAILED_CURLY;
5690         case 2:
5691         case 3: goto EXPAND_FAILED;
5692         }
5693
5694       yield = string_cat(yield, sub[0]);
5695       o2m = Ustrlen(sub[2]) - 1;
5696
5697       if (o2m >= 0) for (; oldptr < yield->ptr; oldptr++)
5698         {
5699         uschar *m = Ustrrchr(sub[1], yield->s[oldptr]);
5700         if (m)
5701           {
5702           int o = m - sub[1];
5703           yield->s[oldptr] = sub[2][(o < o2m)? o : o2m];
5704           }
5705         }
5706
5707       break;
5708       }
5709
5710     /* Handle "hash", "length", "nhash", and "substr" when they are given with
5711     expanded arguments. */
5712
5713     case EITEM_HASH:
5714     case EITEM_LENGTH:
5715     case EITEM_NHASH:
5716     case EITEM_SUBSTR:
5717       {
5718       int len;
5719       uschar *ret;
5720       int val[2] = { 0, -1 };
5721       uschar * sub[3];
5722
5723       /* "length" takes only 2 arguments whereas the others take 2 or 3.
5724       Ensure that sub[2] is set in the ${length } case. */
5725
5726       sub[2] = NULL;
5727       switch(read_subs(sub, item_type == EITEM_LENGTH ? 2:3, 2, &s, flags,
5728              TRUE, name, &resetok, NULL))
5729         {
5730         case -1: continue;      /* skipping */
5731         case 1: goto EXPAND_FAILED_CURLY;
5732         case 2:
5733         case 3: goto EXPAND_FAILED;
5734         }
5735
5736       /* Juggle the arguments if there are only two of them: always move the
5737       string to the last position and make ${length{n}{str}} equivalent to
5738       ${substr{0}{n}{str}}. See the defaults for val[] above. */
5739
5740       if (!sub[2])
5741         {
5742         sub[2] = sub[1];
5743         sub[1] = NULL;
5744         if (item_type == EITEM_LENGTH)
5745           {
5746           sub[1] = sub[0];
5747           sub[0] = NULL;
5748           }
5749         }
5750
5751       for (int i = 0; i < 2; i++) if (sub[i])
5752         {
5753         val[i] = (int)Ustrtol(sub[i], &ret, 10);
5754         if (*ret != 0 || (i != 0 && val[i] < 0))
5755           {
5756           expand_string_message = string_sprintf("\"%s\" is not a%s number "
5757             "(in \"%s\" expansion)", sub[i], (i != 0)? " positive" : "", name);
5758           goto EXPAND_FAILED;
5759           }
5760         }
5761
5762       ret =
5763         item_type == EITEM_HASH
5764         ?  compute_hash(sub[2], val[0], val[1], &len)
5765         : item_type == EITEM_NHASH
5766         ? compute_nhash(sub[2], val[0], val[1], &len)
5767         : extract_substr(sub[2], val[0], val[1], &len);
5768       if (!ret)
5769         goto EXPAND_FAILED;
5770       yield = string_catn(yield, ret, len);
5771       break;
5772       }
5773
5774     /* Handle HMAC computation: ${hmac{<algorithm>}{<secret>}{<text>}}
5775     This code originally contributed by Steve Haslam. It currently supports
5776     the use of MD5 and SHA-1 hashes.
5777
5778     We need some workspace that is large enough to handle all the supported
5779     hash types. Use macros to set the sizes rather than be too elaborate. */
5780
5781     #define MAX_HASHLEN      20
5782     #define MAX_HASHBLOCKLEN 64
5783
5784     case EITEM_HMAC:
5785       {
5786       uschar * sub[3];
5787       md5 md5_base;
5788       hctx sha1_ctx;
5789       void * use_base;
5790       int type;
5791       int hashlen;      /* Number of octets for the hash algorithm's output */
5792       int hashblocklen; /* Number of octets the hash algorithm processes */
5793       uschar * keyptr, * p;
5794       unsigned int keylen;
5795
5796       uschar keyhash[MAX_HASHLEN];
5797       uschar innerhash[MAX_HASHLEN];
5798       uschar finalhash[MAX_HASHLEN];
5799       uschar finalhash_hex[2*MAX_HASHLEN];
5800       uschar innerkey[MAX_HASHBLOCKLEN];
5801       uschar outerkey[MAX_HASHBLOCKLEN];
5802
5803       switch (read_subs(sub, 3, 3, &s, flags, TRUE, name, &resetok, NULL))
5804         {
5805         case -1: continue;      /* skipping */
5806         case 1: goto EXPAND_FAILED_CURLY;
5807         case 2:
5808         case 3: goto EXPAND_FAILED;
5809         }
5810
5811       if (Ustrcmp(sub[0], "md5") == 0)
5812         {
5813         type = HMAC_MD5;
5814         use_base = &md5_base;
5815         hashlen = 16;
5816         hashblocklen = 64;
5817         }
5818       else if (Ustrcmp(sub[0], "sha1") == 0)
5819         {
5820         type = HMAC_SHA1;
5821         use_base = &sha1_ctx;
5822         hashlen = 20;
5823         hashblocklen = 64;
5824         }
5825       else
5826         {
5827         expand_string_message =
5828           string_sprintf("hmac algorithm \"%s\" is not recognised", sub[0]);
5829         goto EXPAND_FAILED;
5830         }
5831
5832       keyptr = sub[1];
5833       keylen = Ustrlen(keyptr);
5834
5835       /* If the key is longer than the hash block length, then hash the key
5836       first */
5837
5838       if (keylen > hashblocklen)
5839         {
5840         chash_start(type, use_base);
5841         chash_end(type, use_base, keyptr, keylen, keyhash);
5842         keyptr = keyhash;
5843         keylen = hashlen;
5844         }
5845
5846       /* Now make the inner and outer key values */
5847
5848       memset(innerkey, 0x36, hashblocklen);
5849       memset(outerkey, 0x5c, hashblocklen);
5850
5851       for (int i = 0; i < keylen; i++)
5852         {
5853         innerkey[i] ^= keyptr[i];
5854         outerkey[i] ^= keyptr[i];
5855         }
5856
5857       /* Now do the hashes */
5858
5859       chash_start(type, use_base);
5860       chash_mid(type, use_base, innerkey);
5861       chash_end(type, use_base, sub[2], Ustrlen(sub[2]), innerhash);
5862
5863       chash_start(type, use_base);
5864       chash_mid(type, use_base, outerkey);
5865       chash_end(type, use_base, innerhash, hashlen, finalhash);
5866
5867       /* Encode the final hash as a hex string */
5868
5869       p = finalhash_hex;
5870       for (int i = 0; i < hashlen; i++)
5871         {
5872         *p++ = hex_digits[(finalhash[i] & 0xf0) >> 4];
5873         *p++ = hex_digits[finalhash[i] & 0x0f];
5874         }
5875
5876       DEBUG(D_any) debug_printf("HMAC[%s](%.*s,%s)=%.*s\n",
5877         sub[0], (int)keylen, keyptr, sub[2], hashlen*2, finalhash_hex);
5878
5879       yield = string_catn(yield, finalhash_hex, hashlen*2);
5880       break;
5881       }
5882
5883     /* Handle global substitution for "sg" - like Perl's s/xxx/yyy/g operator.
5884     We have to save the numerical variables and restore them afterwards. */
5885
5886     case EITEM_SG:
5887       {
5888       const pcre2_code * re;
5889       int moffset, moffsetextra, slen;
5890       pcre2_match_data * md;
5891       int emptyopt;
5892       uschar * subject, * sub[3];
5893       int save_expand_nmax =
5894         save_expand_strings(save_expand_nstring, save_expand_nlength);
5895       unsigned sub_textonly = 0;
5896
5897       switch(read_subs(sub, 3, 3, &s, flags, TRUE, name, &resetok, &sub_textonly))
5898         {
5899         case -1: continue;      /* skipping */
5900         case 1: goto EXPAND_FAILED_CURLY;
5901         case 2:
5902         case 3: goto EXPAND_FAILED;
5903         }
5904
5905       /* Compile the regular expression */
5906
5907       re = regex_compile(sub[1],
5908               sub_textonly & BIT(1) ? MCS_CACHEABLE : MCS_NOFLAGS,
5909               &expand_string_message, pcre_gen_cmp_ctx);
5910       if (!re)
5911         goto EXPAND_FAILED;
5912
5913       md = pcre2_match_data_create(EXPAND_MAXN + 1, pcre_gen_ctx);
5914
5915       /* Now run a loop to do the substitutions as often as necessary. It ends
5916       when there are no more matches. Take care over matches of the null string;
5917       do the same thing as Perl does. */
5918
5919       subject = sub[0];
5920       slen = Ustrlen(sub[0]);
5921       moffset = moffsetextra = 0;
5922       emptyopt = 0;
5923
5924       for (;;)
5925         {
5926         PCRE2_SIZE * ovec = pcre2_get_ovector_pointer(md);
5927         int n = pcre2_match(re, (PCRE2_SPTR)subject, slen, moffset + moffsetextra,
5928           PCRE_EOPT | emptyopt, md, pcre_gen_mtc_ctx);
5929         uschar * insert;
5930
5931         /* No match - if we previously set PCRE_NOTEMPTY after a null match, this
5932         is not necessarily the end. We want to repeat the match from one
5933         character further along, but leaving the basic offset the same (for
5934         copying below). We can't be at the end of the string - that was checked
5935         before setting PCRE_NOTEMPTY. If PCRE_NOTEMPTY is not set, we are
5936         finished; copy the remaining string and end the loop. */
5937
5938         if (n < 0)
5939           {
5940           if (emptyopt != 0)
5941             {
5942             moffsetextra = 1;
5943             emptyopt = 0;
5944             continue;
5945             }
5946           yield = string_catn(yield, subject+moffset, slen-moffset);
5947           break;
5948           }
5949
5950         /* Match - set up for expanding the replacement. */
5951         DEBUG(D_expand) debug_printf_indent("%s: match\n", name);
5952
5953         if (n == 0) n = EXPAND_MAXN + 1;
5954         expand_nmax = 0;
5955         for (int nn = 0; nn < n*2; nn += 2)
5956           {
5957           expand_nstring[expand_nmax] = subject + ovec[nn];
5958           expand_nlength[expand_nmax++] = ovec[nn+1] - ovec[nn];
5959           }
5960         expand_nmax--;
5961
5962         /* Copy the characters before the match, plus the expanded insertion. */
5963
5964         yield = string_catn(yield, subject + moffset, ovec[0] - moffset);
5965
5966         if (!(insert = expand_string(sub[2])))
5967           goto EXPAND_FAILED;
5968         yield = string_cat(yield, insert);
5969
5970         moffset = ovec[1];
5971         moffsetextra = 0;
5972         emptyopt = 0;
5973
5974         /* If we have matched an empty string, first check to see if we are at
5975         the end of the subject. If so, the loop is over. Otherwise, mimic
5976         what Perl's /g options does. This turns out to be rather cunning. First
5977         we set PCRE_NOTEMPTY and PCRE_ANCHORED and try the match a non-empty
5978         string at the same point. If this fails (picked up above) we advance to
5979         the next character. */
5980
5981         if (ovec[0] == ovec[1])
5982           {
5983           if (ovec[0] == slen) break;
5984           emptyopt = PCRE2_NOTEMPTY | PCRE2_ANCHORED;
5985           }
5986         }
5987
5988       /* All done - restore numerical variables. */
5989
5990       /* pcre2_match_data_free(md);     gen ctx needs no free */
5991       restore_expand_strings(save_expand_nmax, save_expand_nstring,
5992         save_expand_nlength);
5993       break;
5994       }
5995
5996     /* Handle keyed and numbered substring extraction. If the first argument
5997     consists entirely of digits, then a numerical extraction is assumed. */
5998
5999     case EITEM_EXTRACT:
6000       {
6001       int field_number = 1;
6002       BOOL field_number_set = FALSE;
6003       uschar * save_lookup_value = lookup_value, * sub[3];
6004       int save_expand_nmax =
6005         save_expand_strings(save_expand_nstring, save_expand_nlength);
6006
6007       /* On reflection the original behaviour of extract-json for a string
6008       result, leaving it quoted, was a mistake.  But it was already published,
6009       hence the addition of jsons.  In a future major version, make json
6010       work like josons, and withdraw jsons. */
6011
6012       enum {extract_basic, extract_json, extract_jsons} fmt = extract_basic;
6013
6014       /* Check for a format-variant specifier */
6015
6016       if (Uskip_whitespace(&s) != '{')                                  /*}*/
6017         if (Ustrncmp(s, "json", 4) == 0)
6018           if (*(s += 4) == 's')
6019             {fmt = extract_jsons; s++;}
6020           else
6021             fmt = extract_json;
6022
6023       /* While skipping we cannot rely on the data for expansions being
6024       available (eg. $item) hence cannot decide on numeric vs. keyed.
6025       Read a maximum of 5 arguments (including the yes/no) */
6026
6027       if (flags & ESI_SKIPPING)
6028         {
6029         for (int j = 5; j > 0 && *s == '{'; j--)                        /*'}'*/
6030           {
6031           if (!expand_string_internal(s+1,
6032                 ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | flags, &s, &resetok, NULL))
6033             goto EXPAND_FAILED;                                 /*'{'*/
6034           if (*s++ != '}')
6035             {
6036             expand_string_message = US"missing '{' for arg of extract";
6037             goto EXPAND_FAILED_CURLY;
6038             }
6039           Uskip_whitespace(&s);
6040           }
6041         if (  Ustrncmp(s, "fail", 4) == 0                               /*'{'*/
6042            && (s[4] == '}' || s[4] == ' ' || s[4] == '\t' || !s[4])
6043            )
6044           {
6045           s += 4;
6046           Uskip_whitespace(&s);
6047           }                                                             /*'{'*/
6048         if (*s != '}')
6049           {
6050           expand_string_message = US"missing '}' closing extract";
6051           goto EXPAND_FAILED_CURLY;
6052           }
6053         }
6054
6055       else for (int i = 0, j = 2; i < j; i++) /* Read the proper number of arguments */
6056         {
6057         if (Uskip_whitespace(&s) == '{')                                /*'}'*/
6058           {
6059           if (!(sub[i] = expand_string_internal(s+1,
6060                 ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | flags, &s, &resetok, NULL)))
6061             goto EXPAND_FAILED;                                         /*'{'*/
6062           if (*s++ != '}')
6063             {
6064             expand_string_message = string_sprintf(
6065               "missing '}' closing arg %d of extract", i+1);
6066             goto EXPAND_FAILED_CURLY;
6067             }
6068
6069           /* After removal of leading and trailing white space, the first
6070           argument must not be empty; if it consists entirely of digits
6071           (optionally preceded by a minus sign), this is a numerical
6072           extraction, and we expect 3 arguments (normal) or 2 (json). */
6073
6074           if (i == 0)
6075             {
6076             int len;
6077             int x = 0;
6078             uschar * p = sub[0];
6079
6080             Uskip_whitespace(&p);
6081             sub[0] = p;
6082
6083             len = Ustrlen(p);
6084             while (len > 0 && isspace(p[len-1])) len--;
6085             p[len] = 0;
6086
6087             if (!*p)
6088               {
6089               expand_string_message = US"first argument of \"extract\" must "
6090                 "not be empty";
6091               goto EXPAND_FAILED;
6092               }
6093
6094             if (*p == '-')
6095               {
6096               field_number = -1;
6097               p++;
6098               }
6099             while (*p && isdigit(*p)) x = x * 10 + *p++ - '0';
6100             if (!*p)
6101               {
6102               field_number *= x;
6103               if (fmt == extract_basic) j = 3;               /* Need 3 args */
6104               field_number_set = TRUE;
6105               }
6106             }
6107           }
6108         else
6109           {
6110           expand_string_message = string_sprintf(
6111             "missing '{' for arg %d of extract", i+1);
6112           goto EXPAND_FAILED_CURLY;
6113           }
6114         }
6115
6116       /* Extract either the numbered or the keyed substring into $value. If
6117       skipping, just pretend the extraction failed. */
6118
6119       if (flags & ESI_SKIPPING)
6120         lookup_value = NULL;
6121       else switch (fmt)
6122         {
6123         case extract_basic:
6124           lookup_value = field_number_set
6125             ? expand_gettokened(field_number, sub[1], sub[2])
6126             : expand_getkeyed(sub[0], sub[1]);
6127           break;
6128
6129         case extract_json:
6130         case extract_jsons:
6131           {
6132           uschar * s, * item;
6133           const uschar * list;
6134
6135           /* Array: Bracket-enclosed and comma-separated.
6136           Object: Brace-enclosed, comma-sep list of name:value pairs */
6137
6138           if (!(s = dewrap(sub[1], field_number_set ? US"[]" : US"{}")))
6139             {
6140             expand_string_message =
6141               string_sprintf("%s wrapping %s for extract json",
6142                 expand_string_message,
6143                 field_number_set ? "array" : "object");
6144             goto EXPAND_FAILED_CURLY;
6145             }
6146
6147           list = s;
6148           if (field_number_set)
6149             {
6150             if (field_number <= 0)
6151               {
6152               expand_string_message = US"first argument of \"extract\" must "
6153                 "be greater than zero";
6154               goto EXPAND_FAILED;
6155               }
6156             while (field_number > 0 && (item = json_nextinlist(&list)))
6157               field_number--;
6158             if ((lookup_value = s = item))
6159               {
6160               while (*s) s++;
6161               while (--s >= lookup_value && isspace(*s)) *s = '\0';
6162               }
6163             }
6164           else
6165             {
6166             lookup_value = NULL;
6167             while ((item = json_nextinlist(&list)))
6168               {
6169               /* Item is:  string name-sep value.  string is quoted.
6170               Dequote the string and compare with the search key. */
6171
6172               if (!(item = dewrap(item, US"\"\"")))
6173                 {
6174                 expand_string_message =
6175                   string_sprintf("%s wrapping string key for extract json",
6176                     expand_string_message);
6177                 goto EXPAND_FAILED_CURLY;
6178                 }
6179               if (Ustrcmp(item, sub[0]) == 0)   /*XXX should be a UTF8-compare */
6180                 {
6181                 s = item + Ustrlen(item) + 1;
6182                 if (Uskip_whitespace(&s) != ':')
6183                   {
6184                   expand_string_message =
6185                     US"missing object value-separator for extract json";
6186                   goto EXPAND_FAILED_CURLY;
6187                   }
6188                 s++;
6189                 Uskip_whitespace(&s);
6190                 lookup_value = s;
6191                 break;
6192                 }
6193               }
6194             }
6195           }
6196
6197           if (  fmt == extract_jsons
6198              && lookup_value
6199              && !(lookup_value = dewrap(lookup_value, US"\"\"")))
6200             {
6201             expand_string_message =
6202               string_sprintf("%s wrapping string result for extract jsons",
6203                 expand_string_message);
6204             goto EXPAND_FAILED_CURLY;
6205             }
6206           break;        /* json/s */
6207         }
6208
6209       /* If no string follows, $value gets substituted; otherwise there can
6210       be yes/no strings, as for lookup or if. */
6211
6212       switch(process_yesno(
6213                flags,                   /* were previously skipping */
6214                lookup_value != NULL,    /* success/failure indicator */
6215                save_lookup_value,       /* value to reset for string2 */
6216                &s,                      /* input pointer */
6217                &yield,                  /* output pointer */
6218                US"extract",             /* condition type */
6219                &resetok))
6220         {
6221         case 1: goto EXPAND_FAILED;          /* when all is well, the */
6222         case 2: goto EXPAND_FAILED_CURLY;    /* returned value is 0 */
6223         }
6224
6225       /* All done - restore numerical variables. */
6226
6227       restore_expand_strings(save_expand_nmax, save_expand_nstring,
6228         save_expand_nlength);
6229
6230       if (flags & ESI_SKIPPING) continue;
6231       break;
6232       }
6233
6234     /* return the Nth item from a list */
6235
6236     case EITEM_LISTEXTRACT:
6237       {
6238       int field_number = 1;
6239       uschar * save_lookup_value = lookup_value, * sub[2];
6240       int save_expand_nmax =
6241         save_expand_strings(save_expand_nstring, save_expand_nlength);
6242
6243       /* Read the field & list arguments */
6244
6245       for (int i = 0; i < 2; i++)
6246         {
6247         if (Uskip_whitespace(&s) != '{')                                /*}*/
6248           {
6249           expand_string_message = string_sprintf(
6250             "missing '{' for arg %d of listextract", i+1);              /*}*/
6251           goto EXPAND_FAILED_CURLY;
6252           }
6253
6254         sub[i] = expand_string_internal(s+1,
6255               ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | flags, &s, &resetok, NULL);
6256         if (!sub[i])     goto EXPAND_FAILED;                            /*{{*/
6257         if (*s++ != '}')
6258           {
6259           expand_string_message = string_sprintf(
6260             "missing '}' closing arg %d of listextract", i+1);
6261           goto EXPAND_FAILED_CURLY;
6262           }
6263
6264         /* After removal of leading and trailing white space, the first
6265         argument must be numeric and nonempty. */
6266
6267         if (i == 0)
6268           {
6269           int len;
6270           int x = 0;
6271           uschar *p = sub[0];
6272
6273           Uskip_whitespace(&p);
6274           sub[0] = p;
6275
6276           len = Ustrlen(p);
6277           while (len > 0 && isspace(p[len-1])) len--;
6278           p[len] = 0;
6279
6280           if (!*p && !(flags & ESI_SKIPPING))
6281             {
6282             expand_string_message = US"first argument of \"listextract\" must "
6283               "not be empty";
6284             goto EXPAND_FAILED;
6285             }
6286
6287           if (*p == '-')
6288             {
6289             field_number = -1;
6290             p++;
6291             }
6292           while (*p && isdigit(*p)) x = x * 10 + *p++ - '0';
6293           if (*p)
6294             {
6295             expand_string_message = US"first argument of \"listextract\" must "
6296               "be numeric";
6297             goto EXPAND_FAILED;
6298             }
6299           field_number *= x;
6300           }
6301         }
6302
6303       /* Extract the numbered element into $value. If
6304       skipping, just pretend the extraction failed. */
6305
6306       lookup_value = flags & ESI_SKIPPING ? NULL : expand_getlistele(field_number, sub[1]);
6307
6308       /* If no string follows, $value gets substituted; otherwise there can
6309       be yes/no strings, as for lookup or if. */
6310
6311       switch(process_yesno(
6312                flags,                           /* were previously skipping */
6313                lookup_value != NULL,            /* success/failure indicator */
6314                save_lookup_value,               /* value to reset for string2 */
6315                &s,                              /* input pointer */
6316                &yield,                          /* output pointer */
6317                US"listextract",                 /* condition type */
6318                &resetok))
6319         {
6320         case 1: goto EXPAND_FAILED;          /* when all is well, the */
6321         case 2: goto EXPAND_FAILED_CURLY;    /* returned value is 0 */
6322         }
6323
6324       /* All done - restore numerical variables. */
6325
6326       restore_expand_strings(save_expand_nmax, save_expand_nstring,
6327         save_expand_nlength);
6328
6329       if (flags & ESI_SKIPPING) continue;
6330       break;
6331       }
6332
6333     case EITEM_LISTQUOTE:
6334       {
6335       uschar * sub[2];
6336       switch(read_subs(sub, 2, 2, &s, flags, TRUE, name, &resetok, NULL))
6337         {
6338         case -1: continue;      /* skipping */
6339         case 1: goto EXPAND_FAILED_CURLY;
6340         case 2:
6341         case 3: goto EXPAND_FAILED;
6342         }
6343       if (*sub[1]) for (uschar sep = *sub[0], c; c = *sub[1]; sub[1]++)
6344         {
6345         if (c == sep) yield = string_catn(yield, sub[1], 1);
6346         yield = string_catn(yield, sub[1], 1);
6347         }
6348       else yield = string_catn(yield, US" ", 1);
6349       break;
6350       }
6351
6352 #ifndef DISABLE_TLS
6353     case EITEM_CERTEXTRACT:
6354       {
6355       uschar * save_lookup_value = lookup_value, * sub[2];
6356       int save_expand_nmax =
6357         save_expand_strings(save_expand_nstring, save_expand_nlength);
6358
6359       /* Read the field argument */
6360       if (Uskip_whitespace(&s) != '{')                                  /*}*/
6361         {
6362         expand_string_message = US"missing '{' for field arg of certextract";
6363         goto EXPAND_FAILED_CURLY;                                       /*}*/
6364         }
6365       sub[0] = expand_string_internal(s+1,
6366                 ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | flags, &s, &resetok, NULL);
6367       if (!sub[0])     goto EXPAND_FAILED;                              /*{{*/
6368       if (*s++ != '}')
6369         {
6370         expand_string_message = US"missing '}' closing field arg of certextract";
6371         goto EXPAND_FAILED_CURLY;
6372         }
6373       /* strip spaces fore & aft */
6374       {
6375       int len;
6376       uschar *p = sub[0];
6377
6378       Uskip_whitespace(&p);
6379       sub[0] = p;
6380
6381       len = Ustrlen(p);
6382       while (len > 0 && isspace(p[len-1])) len--;
6383       p[len] = 0;
6384       }
6385
6386       /* inspect the cert argument */
6387       if (Uskip_whitespace(&s) != '{')                                  /*}*/
6388         {
6389         expand_string_message = US"missing '{' for cert variable arg of certextract";
6390         goto EXPAND_FAILED_CURLY;                                       /*}*/
6391         }
6392       if (*++s != '$')
6393         {
6394         expand_string_message = US"second argument of \"certextract\" must "
6395           "be a certificate variable";
6396         goto EXPAND_FAILED;
6397         }
6398       sub[1] = expand_string_internal(s+1,
6399                 ESI_BRACE_ENDS | flags & ESI_SKIPPING, &s, &resetok, NULL);
6400       if (!sub[1])     goto EXPAND_FAILED;                              /*{{*/
6401       if (*s++ != '}')
6402         {
6403         expand_string_message = US"missing '}' closing cert variable arg of certextract";
6404         goto EXPAND_FAILED_CURLY;
6405         }
6406
6407       if (flags & ESI_SKIPPING)
6408         lookup_value = NULL;
6409       else
6410         {
6411         lookup_value = expand_getcertele(sub[0], sub[1]);
6412         if (*expand_string_message) goto EXPAND_FAILED;
6413         }
6414       switch(process_yesno(
6415                flags,                           /* were previously skipping */
6416                lookup_value != NULL,            /* success/failure indicator */
6417                save_lookup_value,               /* value to reset for string2 */
6418                &s,                              /* input pointer */
6419                &yield,                          /* output pointer */
6420                US"certextract",                 /* condition type */
6421                &resetok))
6422         {
6423         case 1: goto EXPAND_FAILED;          /* when all is well, the */
6424         case 2: goto EXPAND_FAILED_CURLY;    /* returned value is 0 */
6425         }
6426
6427       restore_expand_strings(save_expand_nmax, save_expand_nstring,
6428         save_expand_nlength);
6429       if (flags & ESI_SKIPPING) continue;
6430       break;
6431       }
6432 #endif  /*DISABLE_TLS*/
6433
6434     /* Handle list operations */
6435
6436     case EITEM_FILTER:
6437     case EITEM_MAP:
6438     case EITEM_REDUCE:
6439       {
6440       int sep = 0, save_ptr = gstring_length(yield);
6441       uschar outsep[2] = { '\0', '\0' };
6442       const uschar *list, *expr, *temp;
6443       uschar * save_iterate_item = iterate_item;
6444       uschar * save_lookup_value = lookup_value;
6445
6446       Uskip_whitespace(&s);
6447       if (*s++ != '{')                                                  /*}*/
6448         {
6449         expand_string_message =
6450           string_sprintf("missing '{' for first arg of %s", name);
6451         goto EXPAND_FAILED_CURLY;                                       /*}*/
6452         }
6453
6454       if (!(list = expand_string_internal(s,
6455               ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | flags, &s, &resetok, NULL)))
6456         goto EXPAND_FAILED;                                             /*{{*/
6457       if (*s++ != '}')
6458         {
6459         expand_string_message =
6460           string_sprintf("missing '}' closing first arg of %s", name);
6461         goto EXPAND_FAILED_CURLY;
6462         }
6463
6464       if (item_type == EITEM_REDUCE)
6465         {
6466         uschar * t;
6467         Uskip_whitespace(&s);
6468         if (*s++ != '{')                                                /*}*/
6469           {
6470           expand_string_message = US"missing '{' for second arg of reduce";
6471           goto EXPAND_FAILED_CURLY;                                     /*}*/
6472           }
6473         t = expand_string_internal(s,
6474               ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | flags, &s, &resetok, NULL);
6475         if (!t) goto EXPAND_FAILED;
6476         lookup_value = t;                                               /*{{*/
6477         if (*s++ != '}')
6478           {
6479           expand_string_message = US"missing '}' closing second arg of reduce";
6480           goto EXPAND_FAILED_CURLY;
6481           }
6482         }
6483
6484       Uskip_whitespace(&s);
6485       if (*s++ != '{')                                                  /*}*/
6486         {
6487         expand_string_message =
6488           string_sprintf("missing '{' for last arg of %s", name);       /*}*/
6489         goto EXPAND_FAILED_CURLY;
6490         }
6491
6492       expr = s;
6493
6494       /* For EITEM_FILTER, call eval_condition once, with result discarded (as
6495       if scanning a "false" part). This allows us to find the end of the
6496       condition, because if the list is empty, we won't actually evaluate the
6497       condition for real. For EITEM_MAP and EITEM_REDUCE, do the same, using
6498       the normal internal expansion function. */
6499
6500       if (item_type != EITEM_FILTER)
6501         temp = expand_string_internal(s,
6502           ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | ESI_SKIPPING, &s, &resetok, NULL);
6503       else
6504         if ((temp = eval_condition(expr, &resetok, NULL))) s = temp;
6505
6506       if (!temp)
6507         {
6508         expand_string_message = string_sprintf("%s inside \"%s\" item",
6509           expand_string_message, name);
6510         goto EXPAND_FAILED;
6511         }
6512
6513       Uskip_whitespace(&s);                                             /*{{{*/
6514       if (*s++ != '}')
6515         {
6516         expand_string_message = string_sprintf("missing } at end of condition "
6517           "or expression inside \"%s\"; could be an unquoted } in the content",
6518           name);
6519         goto EXPAND_FAILED;
6520         }
6521
6522       Uskip_whitespace(&s);                                             /*{{*/
6523       if (*s++ != '}')
6524         {
6525         expand_string_message = string_sprintf("missing } at end of \"%s\"",
6526           name);
6527         goto EXPAND_FAILED;
6528         }
6529
6530       /* If we are skipping, we can now just move on to the next item. When
6531       processing for real, we perform the iteration. */
6532
6533       if (flags & ESI_SKIPPING) continue;
6534       while ((iterate_item = string_nextinlist(&list, &sep, NULL, 0)))
6535         {
6536         *outsep = (uschar)sep;      /* Separator as a string */
6537
6538         DEBUG(D_expand) debug_printf_indent("%s: $item = '%s'  $value = '%s'\n",
6539                           name, iterate_item, lookup_value);
6540
6541         if (item_type == EITEM_FILTER)
6542           {
6543           BOOL condresult;
6544           if (!eval_condition(expr, &resetok, &condresult))
6545             {
6546             iterate_item = save_iterate_item;
6547             lookup_value = save_lookup_value;
6548             expand_string_message = string_sprintf("%s inside \"%s\" condition",
6549               expand_string_message, name);
6550             goto EXPAND_FAILED;
6551             }
6552           DEBUG(D_expand) debug_printf_indent("%s: condition is %s\n", name,
6553             condresult? "true":"false");
6554           if (condresult)
6555             temp = iterate_item;    /* TRUE => include this item */
6556           else
6557             continue;               /* FALSE => skip this item */
6558           }
6559
6560         /* EITEM_MAP and EITEM_REDUCE */
6561
6562         else
6563           {
6564           uschar * t = expand_string_internal(expr,
6565             ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | flags, NULL, &resetok, NULL);
6566           temp = t;
6567           if (!temp)
6568             {
6569             iterate_item = save_iterate_item;
6570             expand_string_message = string_sprintf("%s inside \"%s\" item",
6571               expand_string_message, name);
6572             goto EXPAND_FAILED;
6573             }
6574           if (item_type == EITEM_REDUCE)
6575             {
6576             lookup_value = t;         /* Update the value of $value */
6577             continue;                 /* and continue the iteration */
6578             }
6579           }
6580
6581         /* We reach here for FILTER if the condition is true, always for MAP,
6582         and never for REDUCE. The value in "temp" is to be added to the output
6583         list that is being created, ensuring that any occurrences of the
6584         separator character are doubled. Unless we are dealing with the first
6585         item of the output list, add in a space if the new item begins with the
6586         separator character, or is an empty string. */
6587
6588 /*XXX is there not a standard support function for this, appending to a list? */
6589 /* yes, string_append_listele(), but it depends on lack of text before the list */
6590
6591         if (  yield && yield->ptr != save_ptr
6592            && (temp[0] == *outsep || temp[0] == 0))
6593           yield = string_catn(yield, US" ", 1);
6594
6595         /* Add the string in "temp" to the output list that we are building,
6596         This is done in chunks by searching for the separator character. */
6597
6598         for (;;)
6599           {
6600           size_t seglen = Ustrcspn(temp, outsep);
6601
6602           yield = string_catn(yield, temp, seglen + 1);
6603
6604           /* If we got to the end of the string we output one character
6605           too many; backup and end the loop. Otherwise arrange to double the
6606           separator. */
6607
6608           if (!temp[seglen]) { yield->ptr--; break; }
6609           yield = string_catn(yield, outsep, 1);
6610           temp += seglen + 1;
6611           }
6612
6613         /* Output a separator after the string: we will remove the redundant
6614         final one at the end. */
6615
6616         yield = string_catn(yield, outsep, 1);
6617         }   /* End of iteration over the list loop */
6618
6619       /* REDUCE has generated no output above: output the final value of
6620       $value. */
6621
6622       if (item_type == EITEM_REDUCE)
6623         {
6624         yield = string_cat(yield, lookup_value);
6625         lookup_value = save_lookup_value;  /* Restore $value */
6626         }
6627
6628       /* FILTER and MAP generate lists: if they have generated anything, remove
6629       the redundant final separator. Even though an empty item at the end of a
6630       list does not count, this is tidier. */
6631
6632       else if (yield && yield->ptr != save_ptr) yield->ptr--;
6633
6634       /* Restore preserved $item */
6635
6636       iterate_item = save_iterate_item;
6637       if (flags & ESI_SKIPPING) continue;
6638       break;
6639       }
6640
6641     case EITEM_SORT:
6642       {
6643       int sep = 0, cond_type;
6644       const uschar * srclist, * cmp, * xtract;
6645       uschar * opname, * srcitem;
6646       const uschar * dstlist = NULL, * dstkeylist = NULL;
6647       uschar * tmp, * save_iterate_item = iterate_item;
6648
6649       Uskip_whitespace(&s);
6650       if (*s++ != '{')                                                  /*}*/
6651         {
6652         expand_string_message = US"missing '{' for list arg of sort";
6653         goto EXPAND_FAILED_CURLY;                                       /*}*/
6654         }
6655
6656       srclist = expand_string_internal(s,
6657               ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | flags, &s, &resetok, NULL);
6658       if (!srclist) goto EXPAND_FAILED;                                 /*{{*/
6659       if (*s++ != '}')
6660         {
6661         expand_string_message = US"missing '}' closing list arg of sort";
6662         goto EXPAND_FAILED_CURLY;
6663         }
6664
6665       Uskip_whitespace(&s);
6666       if (*s++ != '{')                                                  /*}*/
6667         {
6668         expand_string_message = US"missing '{' for comparator arg of sort";
6669         goto EXPAND_FAILED_CURLY;                                       /*}*/
6670         }
6671
6672       cmp = expand_string_internal(s,
6673               ESI_BRACE_ENDS | flags & ESI_SKIPPING, &s, &resetok, NULL);
6674       if (!cmp) goto EXPAND_FAILED;                                     /*{{*/
6675       if (*s++ != '}')
6676         {
6677         expand_string_message = US"missing '}' closing comparator arg of sort";
6678         goto EXPAND_FAILED_CURLY;
6679         }
6680
6681       if ((cond_type = identify_operator(&cmp, &opname)) == -1)
6682         {
6683         if (!expand_string_message)
6684           expand_string_message = string_sprintf("unknown condition \"%s\"", s);
6685         goto EXPAND_FAILED;
6686         }
6687       switch(cond_type)
6688         {
6689         case ECOND_NUM_L: case ECOND_NUM_LE:
6690         case ECOND_NUM_G: case ECOND_NUM_GE:
6691         case ECOND_STR_GE: case ECOND_STR_GEI: case ECOND_STR_GT: case ECOND_STR_GTI:
6692         case ECOND_STR_LE: case ECOND_STR_LEI: case ECOND_STR_LT: case ECOND_STR_LTI:
6693           break;
6694
6695         default:
6696           expand_string_message = US"comparator not handled for sort";
6697           goto EXPAND_FAILED;
6698         }
6699
6700       Uskip_whitespace(&s);
6701       if (*s++ != '{')                                                  /*}*/
6702         {
6703         expand_string_message = US"missing '{' for extractor arg of sort";
6704         goto EXPAND_FAILED_CURLY;                                       /*}*/
6705         }
6706
6707       xtract = s;
6708       if (!(tmp = expand_string_internal(s,
6709         ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | ESI_SKIPPING, &s, &resetok, NULL)))
6710         goto EXPAND_FAILED;
6711       xtract = string_copyn(xtract, s - xtract);
6712                                                                         /*{{*/
6713       if (*s++ != '}')
6714         {
6715         expand_string_message = US"missing '}' closing extractor arg of sort";
6716         goto EXPAND_FAILED_CURLY;
6717         }
6718                                                                         /*{{*/
6719       if (*s++ != '}')
6720         {
6721         expand_string_message = US"missing } at end of \"sort\"";
6722         goto EXPAND_FAILED;
6723         }
6724
6725       if (flags & ESI_SKIPPING) continue;
6726
6727       while ((srcitem = string_nextinlist(&srclist, &sep, NULL, 0)))
6728         {
6729         uschar * srcfield, * dstitem;
6730         gstring * newlist = NULL, * newkeylist = NULL;
6731
6732         DEBUG(D_expand) debug_printf_indent("%s: $item = \"%s\"\n", name, srcitem);
6733
6734         /* extract field for comparisons */
6735         iterate_item = srcitem;
6736         if (  !(srcfield = expand_string_internal(xtract,
6737                                   ESI_HONOR_DOLLAR, NULL, &resetok, NULL))
6738            || !*srcfield)
6739           {
6740           expand_string_message = string_sprintf(
6741               "field-extract in sort: \"%s\"", xtract);
6742           goto EXPAND_FAILED;
6743           }
6744
6745         /* Insertion sort */
6746
6747         /* copy output list until new-item < list-item */
6748         while ((dstitem = string_nextinlist(&dstlist, &sep, NULL, 0)))
6749           {
6750           uschar * dstfield;
6751
6752           /* field for comparison */
6753           if (!(dstfield = string_nextinlist(&dstkeylist, &sep, NULL, 0)))
6754             goto SORT_MISMATCH;
6755
6756           /* String-comparator names start with a letter; numeric names do not */
6757
6758           if (sortsbefore(cond_type, isalpha(opname[0]),
6759               srcfield, dstfield))
6760             {
6761             /* New-item sorts before this dst-item.  Append new-item,
6762             then dst-item, then remainder of dst list. */
6763
6764             newlist = string_append_listele(newlist, sep, srcitem);
6765             newkeylist = string_append_listele(newkeylist, sep, srcfield);
6766             srcitem = NULL;
6767
6768             newlist = string_append_listele(newlist, sep, dstitem);
6769             newkeylist = string_append_listele(newkeylist, sep, dstfield);
6770
6771 /*XXX why field-at-a-time copy?  Why not just dup the rest of the list? */
6772             while ((dstitem = string_nextinlist(&dstlist, &sep, NULL, 0)))
6773               {
6774               if (!(dstfield = string_nextinlist(&dstkeylist, &sep, NULL, 0)))
6775                 goto SORT_MISMATCH;
6776               newlist = string_append_listele(newlist, sep, dstitem);
6777               newkeylist = string_append_listele(newkeylist, sep, dstfield);
6778               }
6779
6780             break;
6781             }
6782
6783           newlist = string_append_listele(newlist, sep, dstitem);
6784           newkeylist = string_append_listele(newkeylist, sep, dstfield);
6785           }
6786
6787         /* If we ran out of dstlist without consuming srcitem, append it */
6788         if (srcitem)
6789           {
6790           newlist = string_append_listele(newlist, sep, srcitem);
6791           newkeylist = string_append_listele(newkeylist, sep, srcfield);
6792           }
6793
6794         dstlist = newlist->s;
6795         dstkeylist = newkeylist->s;
6796
6797         DEBUG(D_expand) debug_printf_indent("%s: dstlist = \"%s\"\n", name, dstlist);
6798         DEBUG(D_expand) debug_printf_indent("%s: dstkeylist = \"%s\"\n", name, dstkeylist);
6799         }
6800
6801       if (dstlist)
6802         yield = string_cat(yield, dstlist);
6803
6804       /* Restore preserved $item */
6805       iterate_item = save_iterate_item;
6806       break;
6807
6808       SORT_MISMATCH:
6809         expand_string_message = US"Internal error in sort (list mismatch)";
6810         goto EXPAND_FAILED;
6811       }
6812
6813
6814     /* If ${dlfunc } support is configured, handle calling dynamically-loaded
6815     functions, unless locked out at this time. Syntax is ${dlfunc{file}{func}}
6816     or ${dlfunc{file}{func}{arg}} or ${dlfunc{file}{func}{arg1}{arg2}} or up to
6817     a maximum of EXPAND_DLFUNC_MAX_ARGS arguments (defined below). */
6818
6819     #define EXPAND_DLFUNC_MAX_ARGS 8
6820
6821     case EITEM_DLFUNC:
6822 #ifndef EXPAND_DLFUNC
6823       expand_string_message = US"\"${dlfunc\" encountered, but this facility "  /*}*/
6824         "is not included in this binary";
6825       goto EXPAND_FAILED;
6826
6827 #else   /* EXPAND_DLFUNC */
6828       {
6829       tree_node * t;
6830       exim_dlfunc_t * func;
6831       uschar * result;
6832       int status, argc;
6833       uschar * argv[EXPAND_DLFUNC_MAX_ARGS + 3];
6834
6835       if (expand_forbid & RDO_DLFUNC)
6836         {
6837         expand_string_message =
6838           US"dynamically-loaded functions are not permitted";
6839         goto EXPAND_FAILED;
6840         }
6841
6842       switch(read_subs(argv, EXPAND_DLFUNC_MAX_ARGS + 2, 2, &s, flags,
6843            TRUE, name, &resetok, NULL))
6844         {
6845         case -1: continue;      /* skipping */
6846         case 1: goto EXPAND_FAILED_CURLY;
6847         case 2:
6848         case 3: goto EXPAND_FAILED;
6849         }
6850
6851       /* Look up the dynamically loaded object handle in the tree. If it isn't
6852       found, dlopen() the file and put the handle in the tree for next time. */
6853
6854       if (!(t = tree_search(dlobj_anchor, argv[0])))
6855         {
6856         void * handle = dlopen(CS argv[0], RTLD_LAZY);
6857         if (!handle)
6858           {
6859           expand_string_message = string_sprintf("dlopen \"%s\" failed: %s",
6860             argv[0], dlerror());
6861           log_write(0, LOG_MAIN|LOG_PANIC, "%s", expand_string_message);
6862           goto EXPAND_FAILED;
6863           }
6864         t = store_get_perm(sizeof(tree_node) + Ustrlen(argv[0]), argv[0]);
6865         Ustrcpy(t->name, argv[0]);
6866         t->data.ptr = handle;
6867         (void)tree_insertnode(&dlobj_anchor, t);
6868         }
6869
6870       /* Having obtained the dynamically loaded object handle, look up the
6871       function pointer. */
6872
6873       if (!(func = (exim_dlfunc_t *)dlsym(t->data.ptr, CS argv[1])))
6874         {
6875         expand_string_message = string_sprintf("dlsym \"%s\" in \"%s\" failed: "
6876           "%s", argv[1], argv[0], dlerror());
6877         log_write(0, LOG_MAIN|LOG_PANIC, "%s", expand_string_message);
6878         goto EXPAND_FAILED;
6879         }
6880
6881       /* Call the function and work out what to do with the result. If it
6882       returns OK, we have a replacement string; if it returns DEFER then
6883       expansion has failed in a non-forced manner; if it returns FAIL then
6884       failure was forced; if it returns ERROR or any other value there's a
6885       problem, so panic slightly. In any case, assume that the function has
6886       side-effects on the store that must be preserved. */
6887
6888       resetok = FALSE;
6889       result = NULL;
6890       for (argc = 0; argv[argc]; argc++) ;
6891
6892       if ((status = func(&result, argc - 2, &argv[2])) != OK)
6893         {
6894         expand_string_message = result ? result : US"(no message)";
6895         if (status == FAIL_FORCED)
6896           f.expand_string_forcedfail = TRUE;
6897         else if (status != FAIL)
6898           log_write(0, LOG_MAIN|LOG_PANIC, "dlfunc{%s}{%s} failed (%d): %s",
6899               argv[0], argv[1], status, expand_string_message);
6900         goto EXPAND_FAILED;
6901         }
6902
6903       if (result) yield = string_cat(yield, result);
6904       break;
6905       }
6906 #endif /* EXPAND_DLFUNC */
6907
6908     case EITEM_ENV:     /* ${env {name} {val_if_found} {val_if_unfound}} */
6909       {
6910       uschar * key;
6911       uschar *save_lookup_value = lookup_value;
6912
6913       if (Uskip_whitespace(&s) != '{')                                  /*}*/
6914         goto EXPAND_FAILED;
6915
6916       key = expand_string_internal(s+1,
6917               ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | flags, &s, &resetok, NULL);
6918       if (!key) goto EXPAND_FAILED;                                     /*{{*/
6919       if (*s++ != '}')
6920         {
6921         expand_string_message = US"missing '}' for name arg of env";
6922         goto EXPAND_FAILED_CURLY;
6923         }
6924
6925       lookup_value = US getenv(CS key);
6926
6927       switch(process_yesno(
6928                flags,                           /* were previously skipping */
6929                lookup_value != NULL,            /* success/failure indicator */
6930                save_lookup_value,               /* value to reset for string2 */
6931                &s,                              /* input pointer */
6932                &yield,                          /* output pointer */
6933                US"env",                         /* condition type */
6934                &resetok))
6935         {
6936         case 1: goto EXPAND_FAILED;          /* when all is well, the */
6937         case 2: goto EXPAND_FAILED_CURLY;    /* returned value is 0 */
6938         }
6939       if (flags & ESI_SKIPPING) continue;
6940       break;
6941       }
6942
6943 #ifdef SUPPORT_SRS
6944     case EITEM_SRS_ENCODE:
6945       /* ${srs_encode {secret} {return_path} {orig_domain}} */
6946       {
6947       uschar * sub[3];
6948       uschar cksum[4];
6949       gstring * g = NULL;
6950       BOOL quoted = FALSE;
6951
6952       switch (read_subs(sub, 3, 3, CUSS &s, flags, TRUE, name, &resetok, NULL))
6953         {
6954         case -1: continue;      /* skipping */
6955         case 1: goto EXPAND_FAILED_CURLY;
6956         case 2:
6957         case 3: goto EXPAND_FAILED;
6958         }
6959
6960       g = string_catn(g, US"SRS0=", 5);
6961
6962       /* ${l_4:${hmac{md5}{SRS_SECRET}{${lc:$return_path}}}}= */
6963       hmac_md5(sub[0], string_copylc(sub[1]), cksum, sizeof(cksum));
6964       g = string_catn(g, cksum, sizeof(cksum));
6965       g = string_catn(g, US"=", 1);
6966
6967       /* ${base32:${eval:$tod_epoch/86400&0x3ff}}= */
6968         {
6969         struct timeval now;
6970         unsigned long i;
6971         gstring * h = NULL;
6972
6973         gettimeofday(&now, NULL);
6974         for (unsigned long i = (now.tv_sec / 86400) & 0x3ff; i; i >>= 5)
6975           h = string_catn(h, &base32_chars[i & 0x1f], 1);
6976         if (h) while (h->ptr > 0)
6977           g = string_catn(g, &h->s[--h->ptr], 1);
6978         }
6979       g = string_catn(g, US"=", 1);
6980
6981       /* ${domain:$return_path}=${local_part:$return_path} */
6982         {
6983         int start, end, domain;
6984         uschar * t = parse_extract_address(sub[1], &expand_string_message,
6985                                           &start, &end, &domain, FALSE);
6986         uschar * s;
6987
6988         if (!t)
6989           goto EXPAND_FAILED;
6990
6991         if (domain > 0) g = string_cat(g, t + domain);
6992         g = string_catn(g, US"=", 1);
6993
6994         s = domain > 0 ? string_copyn(t, domain - 1) : t;
6995         if ((quoted = Ustrchr(s, '"') != NULL))
6996           {
6997           gstring * h = NULL;
6998           DEBUG(D_expand) debug_printf_indent("auto-quoting local part\n");
6999           while (*s)            /* de-quote */
7000             {
7001             while (*s && *s != '"') h = string_catn(h, s++, 1);
7002             if (*s) s++;
7003             while (*s && *s != '"') h = string_catn(h, s++, 1);
7004             if (*s) s++;
7005             }
7006           gstring_release_unused(h);
7007           s = string_from_gstring(h);
7008           }
7009         g = string_cat(g, s);
7010         }
7011
7012       /* Assume that if the original local_part had quotes
7013       it was for good reason */
7014
7015       if (quoted) yield = string_catn(yield, US"\"", 1);
7016       yield = string_catn(yield, g->s, g->ptr);
7017       if (quoted) yield = string_catn(yield, US"\"", 1);
7018
7019       /* @$original_domain */
7020       yield = string_catn(yield, US"@", 1);
7021       yield = string_cat(yield, sub[2]);
7022
7023       break;
7024       }
7025 #endif /*SUPPORT_SRS*/
7026
7027     default:
7028       goto NOT_ITEM;
7029     }   /* EITEM_* switch */
7030     /*NOTREACHED*/
7031
7032   DEBUG(D_expand)
7033     if (yield && (start > 0 || *s))     /* only if not the sole expansion of the line */
7034       debug_expansion_interim(US"item-res",
7035                               yield->s + start, yield->ptr - start, !!(flags & ESI_SKIPPING));
7036   continue;
7037
7038 NOT_ITEM: ;
7039   }
7040
7041   /* Control reaches here if the name is not recognized as one of the more
7042   complicated expansion items. Check for the "operator" syntax (name terminated
7043   by a colon). Some of the operators have arguments, separated by _ from the
7044   name. */
7045
7046   if (*s == ':')
7047     {
7048     int c;
7049     uschar * arg = NULL, * sub;
7050 #ifndef DISABLE_TLS
7051     var_entry * vp = NULL;
7052 #endif
7053
7054     /* Owing to an historical mis-design, an underscore may be part of the
7055     operator name, or it may introduce arguments.  We therefore first scan the
7056     table of names that contain underscores. If there is no match, we cut off
7057     the arguments and then scan the main table. */
7058
7059     if ((c = chop_match(name, op_table_underscore,
7060                         nelem(op_table_underscore))) < 0)
7061       {
7062       if ((arg = Ustrchr(name, '_')))
7063         *arg = 0;
7064       if ((c = chop_match(name, op_table_main, nelem(op_table_main))) >= 0)
7065         c += nelem(op_table_underscore);
7066       if (arg) *arg++ = '_';            /* Put back for error messages */
7067       }
7068
7069     /* Deal specially with operators that might take a certificate variable
7070     as we do not want to do the usual expansion. For most, expand the string.*/
7071     switch(c)
7072       {
7073 #ifndef DISABLE_TLS
7074       case EOP_MD5:
7075       case EOP_SHA1:
7076       case EOP_SHA256:
7077       case EOP_BASE64:
7078         if (s[1] == '$')
7079           {
7080           const uschar * s1 = s;
7081           sub = expand_string_internal(s+2,
7082               ESI_BRACE_ENDS | flags & ESI_SKIPPING, &s1, &resetok, NULL);
7083           if (!sub)       goto EXPAND_FAILED;           /*{*/
7084           if (*s1 != '}')
7085             {                                           /*{*/
7086             expand_string_message =
7087               string_sprintf("missing '}' closing cert arg of %s", name);
7088             goto EXPAND_FAILED_CURLY;
7089             }
7090           if ((vp = find_var_ent(sub)) && vp->type == vtype_cert)
7091             {
7092             s = s1+1;
7093             break;
7094             }
7095           vp = NULL;
7096           }
7097         /*FALLTHROUGH*/
7098 #endif
7099       default:
7100         sub = expand_string_internal(s+1,
7101                 ESI_BRACE_ENDS | ESI_HONOR_DOLLAR | flags, &s, &resetok, NULL);
7102         if (!sub) goto EXPAND_FAILED;
7103         s++;
7104         break;
7105       }
7106
7107     /* If we are skipping, we don't need to perform the operation at all.
7108     This matters for operations like "mask", because the data may not be
7109     in the correct format when skipping. For example, the expression may test
7110     for the existence of $sender_host_address before trying to mask it. For
7111     other operations, doing them may not fail, but it is a waste of time. */
7112
7113     if (flags & ESI_SKIPPING && c >= 0) continue;
7114
7115     /* Otherwise, switch on the operator type.  After handling go back
7116     to the main loop top. */
7117
7118      {
7119      int start = yield->ptr;
7120      switch(c)
7121       {
7122       case EOP_BASE32:
7123         {
7124         uschar *t;
7125         unsigned long int n = Ustrtoul(sub, &t, 10);
7126         gstring * g = NULL;
7127
7128         if (*t != 0)
7129           {
7130           expand_string_message = string_sprintf("argument for base32 "
7131             "operator is \"%s\", which is not a decimal number", sub);
7132           goto EXPAND_FAILED;
7133           }
7134         for ( ; n; n >>= 5)
7135           g = string_catn(g, &base32_chars[n & 0x1f], 1);
7136
7137         if (g) while (g->ptr > 0) yield = string_catn(yield, &g->s[--g->ptr], 1);
7138         break;
7139         }
7140
7141       case EOP_BASE32D:
7142         {
7143         uschar *tt = sub;
7144         unsigned long int n = 0;
7145         while (*tt)
7146           {
7147           uschar * t = Ustrchr(base32_chars, *tt++);
7148           if (!t)
7149             {
7150             expand_string_message = string_sprintf("argument for base32d "
7151               "operator is \"%s\", which is not a base 32 number", sub);
7152             goto EXPAND_FAILED;
7153             }
7154           n = n * 32 + (t - base32_chars);
7155           }
7156         yield = string_fmt_append(yield, "%ld", n);
7157         break;
7158         }
7159
7160       case EOP_BASE62:
7161         {
7162         uschar *t;
7163         unsigned long int n = Ustrtoul(sub, &t, 10);
7164         if (*t != 0)
7165           {
7166           expand_string_message = string_sprintf("argument for base62 "
7167             "operator is \"%s\", which is not a decimal number", sub);
7168           goto EXPAND_FAILED;
7169           }
7170         yield = string_cat(yield, string_base62(n));
7171         break;
7172         }
7173
7174       /* Note that for Darwin and Cygwin, BASE_62 actually has the value 36 */
7175
7176       case EOP_BASE62D:
7177         {
7178         uschar *tt = sub;
7179         unsigned long int n = 0;
7180         while (*tt != 0)
7181           {
7182           uschar *t = Ustrchr(base62_chars, *tt++);
7183           if (!t)
7184             {
7185             expand_string_message = string_sprintf("argument for base62d "
7186               "operator is \"%s\", which is not a base %d number", sub,
7187               BASE_62);
7188             goto EXPAND_FAILED;
7189             }
7190           n = n * BASE_62 + (t - base62_chars);
7191           }
7192         yield = string_fmt_append(yield, "%ld", n);
7193         break;
7194         }
7195
7196       case EOP_EXPAND:
7197         {
7198         uschar *expanded = expand_string_internal(sub,
7199                 ESI_HONOR_DOLLAR | flags & ESI_SKIPPING, NULL, &resetok, NULL);
7200         if (!expanded)
7201           {
7202           expand_string_message =
7203             string_sprintf("internal expansion of \"%s\" failed: %s", sub,
7204               expand_string_message);
7205           goto EXPAND_FAILED;
7206           }
7207         yield = string_cat(yield, expanded);
7208         break;
7209         }
7210
7211       case EOP_LC:
7212         {
7213         int count = 0;
7214         uschar *t = sub - 1;
7215         while (*(++t) != 0) { *t = tolower(*t); count++; }
7216         yield = string_catn(yield, sub, count);
7217         break;
7218         }
7219
7220       case EOP_UC:
7221         {
7222         int count = 0;
7223         uschar *t = sub - 1;
7224         while (*(++t) != 0) { *t = toupper(*t); count++; }
7225         yield = string_catn(yield, sub, count);
7226         break;
7227         }
7228
7229       case EOP_MD5:
7230 #ifndef DISABLE_TLS
7231         if (vp && *(void **)vp->value)
7232           {
7233           uschar * cp = tls_cert_fprt_md5(*(void **)vp->value);
7234           yield = string_cat(yield, cp);
7235           }
7236         else
7237 #endif
7238           {
7239           md5 base;
7240           uschar digest[16];
7241           md5_start(&base);
7242           md5_end(&base, sub, Ustrlen(sub), digest);
7243           for (int j = 0; j < 16; j++)
7244             yield = string_fmt_append(yield, "%02x", digest[j]);
7245           }
7246         break;
7247
7248       case EOP_SHA1:
7249 #ifndef DISABLE_TLS
7250         if (vp && *(void **)vp->value)
7251           {
7252           uschar * cp = tls_cert_fprt_sha1(*(void **)vp->value);
7253           yield = string_cat(yield, cp);
7254           }
7255         else
7256 #endif
7257           {
7258           hctx h;
7259           uschar digest[20];
7260           sha1_start(&h);
7261           sha1_end(&h, sub, Ustrlen(sub), digest);
7262           for (int j = 0; j < 20; j++)
7263             yield = string_fmt_append(yield, "%02X", digest[j]);
7264           }
7265         break;
7266
7267       case EOP_SHA2:
7268       case EOP_SHA256:
7269 #ifdef EXIM_HAVE_SHA2
7270         if (vp && *(void **)vp->value)
7271           if (c == EOP_SHA256)
7272             yield = string_cat(yield, tls_cert_fprt_sha256(*(void **)vp->value));
7273           else
7274             expand_string_message = US"sha2_N not supported with certificates";
7275         else
7276           {
7277           hctx h;
7278           blob b;
7279           hashmethod m = !arg ? HASH_SHA2_256
7280             : Ustrcmp(arg, "256") == 0 ? HASH_SHA2_256
7281             : Ustrcmp(arg, "384") == 0 ? HASH_SHA2_384
7282             : Ustrcmp(arg, "512") == 0 ? HASH_SHA2_512
7283             : HASH_BADTYPE;
7284
7285           if (m == HASH_BADTYPE || !exim_sha_init(&h, m))
7286             {
7287             expand_string_message = US"unrecognised sha2 variant";
7288             goto EXPAND_FAILED;
7289             }
7290
7291           exim_sha_update_string(&h, sub);
7292           exim_sha_finish(&h, &b);
7293           while (b.len-- > 0)
7294             yield = string_fmt_append(yield, "%02X", *b.data++);
7295           }
7296 #else
7297           expand_string_message = US"sha256 only supported with TLS";
7298 #endif
7299         break;
7300
7301       case EOP_SHA3:
7302 #ifdef EXIM_HAVE_SHA3
7303         {
7304         hctx h;
7305         blob b;
7306         hashmethod m = !arg ? HASH_SHA3_256
7307           : Ustrcmp(arg, "224") == 0 ? HASH_SHA3_224
7308           : Ustrcmp(arg, "256") == 0 ? HASH_SHA3_256
7309           : Ustrcmp(arg, "384") == 0 ? HASH_SHA3_384
7310           : Ustrcmp(arg, "512") == 0 ? HASH_SHA3_512
7311           : HASH_BADTYPE;
7312
7313         if (m == HASH_BADTYPE || !exim_sha_init(&h, m))
7314           {
7315           expand_string_message = US"unrecognised sha3 variant";
7316           goto EXPAND_FAILED;
7317           }
7318
7319         exim_sha_update_string(&h, sub);
7320         exim_sha_finish(&h, &b);
7321         while (b.len-- > 0)
7322           yield = string_fmt_append(yield, "%02X", *b.data++);
7323         }
7324         break;
7325 #else
7326         expand_string_message = US"sha3 only supported with GnuTLS 3.5.0 + or OpenSSL 1.1.1 +";
7327         goto EXPAND_FAILED;
7328 #endif
7329
7330       /* Convert hex encoding to base64 encoding */
7331
7332       case EOP_HEX2B64:
7333         {
7334         int c = 0;
7335         int b = -1;
7336         uschar *in = sub;
7337         uschar *out = sub;
7338         uschar *enc;
7339
7340         for (enc = sub; *enc; enc++)
7341           {
7342           if (!isxdigit(*enc))
7343             {
7344             expand_string_message = string_sprintf("\"%s\" is not a hex "
7345               "string", sub);
7346             goto EXPAND_FAILED;
7347             }
7348           c++;
7349           }
7350
7351         if ((c & 1) != 0)
7352           {
7353           expand_string_message = string_sprintf("\"%s\" contains an odd "
7354             "number of characters", sub);
7355           goto EXPAND_FAILED;
7356           }
7357
7358         while ((c = *in++) != 0)
7359           {
7360           if (isdigit(c)) c -= '0';
7361           else c = toupper(c) - 'A' + 10;
7362           if (b == -1)
7363             b = c << 4;
7364           else
7365             {
7366             *out++ = b | c;
7367             b = -1;
7368             }
7369           }
7370
7371         enc = b64encode(CUS sub, out - sub);
7372         yield = string_cat(yield, enc);
7373         break;
7374         }
7375
7376       /* Convert octets outside 0x21..0x7E to \xXX form */
7377
7378       case EOP_HEXQUOTE:
7379         {
7380         uschar *t = sub - 1;
7381         while (*(++t) != 0)
7382           {
7383           if (*t < 0x21 || 0x7E < *t)
7384             yield = string_fmt_append(yield, "\\x%02x", *t);
7385           else
7386             yield = string_catn(yield, t, 1);
7387           }
7388         break;
7389         }
7390
7391       /* count the number of list elements */
7392
7393       case EOP_LISTCOUNT:
7394         {
7395         int cnt = 0, sep = 0;
7396         uschar * buf = store_get(2, sub);
7397
7398         while (string_nextinlist(CUSS &sub, &sep, buf, 1)) cnt++;
7399         yield = string_fmt_append(yield, "%d", cnt);
7400         break;
7401         }
7402
7403       /* expand a named list given the name */
7404       /* handles nested named lists; requotes as colon-sep list */
7405
7406       case EOP_LISTNAMED:
7407         expand_string_message = NULL;
7408         yield = expand_listnamed(yield, sub, arg);
7409         if (expand_string_message)
7410           goto EXPAND_FAILED;
7411         break;
7412
7413       /* quote a list-item for the given list-separator */
7414
7415       /* mask applies a mask to an IP address; for example the result of
7416       ${mask:131.111.10.206/28} is 131.111.10.192/28. */
7417
7418       case EOP_MASK:
7419         {
7420         int count;
7421         uschar *endptr;
7422         int binary[4];
7423         int type, mask, maskoffset;
7424         BOOL normalised;
7425         uschar buffer[64];
7426
7427         if ((type = string_is_ip_address(sub, &maskoffset)) == 0)
7428           {
7429           expand_string_message = string_sprintf("\"%s\" is not an IP address",
7430            sub);
7431           goto EXPAND_FAILED;
7432           }
7433
7434         if (maskoffset == 0)
7435           {
7436           expand_string_message = string_sprintf("missing mask value in \"%s\"",
7437             sub);
7438           goto EXPAND_FAILED;
7439           }
7440
7441         mask = Ustrtol(sub + maskoffset + 1, &endptr, 10);
7442
7443         if (*endptr || mask < 0 || mask > (type == 4 ? 32 : 128))
7444           {
7445           expand_string_message = string_sprintf("mask value too big in \"%s\"",
7446             sub);
7447           goto EXPAND_FAILED;
7448           }
7449
7450         /* If an optional 'n' was given, ipv6 gets normalised output:
7451         colons rather than dots, and zero-compressed. */
7452
7453         normalised = arg && *arg == 'n';
7454
7455         /* Convert the address to binary integer(s) and apply the mask */
7456
7457         sub[maskoffset] = 0;
7458         count = host_aton(sub, binary);
7459         host_mask(count, binary, mask);
7460
7461         /* Convert to masked textual format and add to output. */
7462
7463         if (type == 4 || !normalised)
7464           yield = string_catn(yield, buffer,
7465             host_nmtoa(count, binary, mask, buffer, '.'));
7466         else
7467           {
7468           ipv6_nmtoa(binary, buffer);
7469           yield = string_fmt_append(yield, "%s/%d", buffer, mask);
7470           }
7471         break;
7472         }
7473
7474       case EOP_IPV6NORM:
7475       case EOP_IPV6DENORM:
7476         {
7477         int type = string_is_ip_address(sub, NULL);
7478         int binary[4];
7479         uschar buffer[44];
7480
7481         switch (type)
7482           {
7483           case 6:
7484             (void) host_aton(sub, binary);
7485             break;
7486
7487           case 4:       /* convert to IPv4-mapped IPv6 */
7488             binary[0] = binary[1] = 0;
7489             binary[2] = 0x0000ffff;
7490             (void) host_aton(sub, binary+3);
7491             break;
7492
7493           case 0:
7494             expand_string_message =
7495               string_sprintf("\"%s\" is not an IP address", sub);
7496             goto EXPAND_FAILED;
7497           }
7498
7499         yield = string_catn(yield, buffer, c == EOP_IPV6NORM
7500                     ? ipv6_nmtoa(binary, buffer)
7501                     : host_nmtoa(4, binary, -1, buffer, ':')
7502                   );
7503         break;
7504         }
7505
7506       case EOP_ADDRESS:
7507       case EOP_LOCAL_PART:
7508       case EOP_DOMAIN:
7509         {
7510         uschar * error;
7511         int start, end, domain;
7512         uschar * t = parse_extract_address(sub, &error, &start, &end, &domain,
7513           FALSE);
7514         if (t)
7515           if (c != EOP_DOMAIN)
7516             yield = c == EOP_LOCAL_PART && domain > 0
7517               ? string_catn(yield, t, domain - 1)
7518               : string_cat(yield, t);
7519           else if (domain > 0)
7520             yield = string_cat(yield, t + domain);
7521         break;
7522         }
7523
7524       case EOP_ADDRESSES:
7525         {
7526         uschar outsep[2] = { ':', '\0' };
7527         uschar *address, *error;
7528         int save_ptr = gstring_length(yield);
7529         int start, end, domain;  /* Not really used */
7530
7531         if (Uskip_whitespace(&sub) == '>')
7532           if (*outsep = *++sub) ++sub;
7533           else
7534             {
7535             expand_string_message = string_sprintf("output separator "
7536               "missing in expanding ${addresses:%s}", --sub);
7537             goto EXPAND_FAILED;
7538             }
7539         f.parse_allow_group = TRUE;
7540
7541         for (;;)
7542           {
7543           uschar * p = parse_find_address_end(sub, FALSE);
7544           uschar saveend = *p;
7545           *p = '\0';
7546           address = parse_extract_address(sub, &error, &start, &end, &domain,
7547             FALSE);
7548           *p = saveend;
7549
7550           /* Add the address to the output list that we are building. This is
7551           done in chunks by searching for the separator character. At the
7552           start, unless we are dealing with the first address of the output
7553           list, add in a space if the new address begins with the separator
7554           character, or is an empty string. */
7555
7556           if (address)
7557             {
7558             if (yield && yield->ptr != save_ptr && address[0] == *outsep)
7559               yield = string_catn(yield, US" ", 1);
7560
7561             for (;;)
7562               {
7563               size_t seglen = Ustrcspn(address, outsep);
7564               yield = string_catn(yield, address, seglen + 1);
7565
7566               /* If we got to the end of the string we output one character
7567               too many. */
7568
7569               if (address[seglen] == '\0') { yield->ptr--; break; }
7570               yield = string_catn(yield, outsep, 1);
7571               address += seglen + 1;
7572               }
7573
7574             /* Output a separator after the string: we will remove the
7575             redundant final one at the end. */
7576
7577             yield = string_catn(yield, outsep, 1);
7578             }
7579
7580           if (saveend == '\0') break;
7581           sub = p + 1;
7582           }
7583
7584         /* If we have generated anything, remove the redundant final
7585         separator. */
7586
7587         if (yield && yield->ptr != save_ptr) yield->ptr--;
7588         f.parse_allow_group = FALSE;
7589         break;
7590         }
7591
7592
7593       /* quote puts a string in quotes if it is empty or contains anything
7594       other than alphamerics, underscore, dot, or hyphen.
7595
7596       quote_local_part puts a string in quotes if RFC 2821/2822 requires it to
7597       be quoted in order to be a valid local part.
7598
7599       In both cases, newlines and carriage returns are converted into \n and \r
7600       respectively */
7601
7602       case EOP_QUOTE:
7603       case EOP_QUOTE_LOCAL_PART:
7604         if (!arg)
7605           {
7606           BOOL needs_quote = (!*sub);      /* TRUE for empty string */
7607           uschar *t = sub - 1;
7608
7609           if (c == EOP_QUOTE)
7610             while (!needs_quote && *++t)
7611               needs_quote = !isalnum(*t) && !strchr("_-.", *t);
7612
7613           else  /* EOP_QUOTE_LOCAL_PART */
7614             while (!needs_quote && *++t)
7615               needs_quote = !isalnum(*t)
7616                 && strchr("!#$%&'*+-/=?^_`{|}~", *t) == NULL
7617                 && (*t != '.' || t == sub || !t[1]);
7618
7619           if (needs_quote)
7620             {
7621             yield = string_catn(yield, US"\"", 1);
7622             t = sub - 1;
7623             while (*++t)
7624               if (*t == '\n')
7625                 yield = string_catn(yield, US"\\n", 2);
7626               else if (*t == '\r')
7627                 yield = string_catn(yield, US"\\r", 2);
7628               else
7629                 {
7630                 if (*t == '\\' || *t == '"')
7631                   yield = string_catn(yield, US"\\", 1);
7632                 yield = string_catn(yield, t, 1);
7633                 }
7634             yield = string_catn(yield, US"\"", 1);
7635             }
7636           else
7637             yield = string_cat(yield, sub);
7638           break;
7639           }
7640
7641         /* quote_lookuptype does lookup-specific quoting */
7642
7643         else
7644           {
7645           int n;
7646           uschar * opt = Ustrchr(arg, '_');
7647
7648           if (opt) *opt++ = 0;
7649
7650           if ((n = search_findtype(arg, Ustrlen(arg))) < 0)
7651             {
7652             expand_string_message = search_error_message;
7653             goto EXPAND_FAILED;
7654             }
7655
7656           if (lookup_list[n]->quote)
7657             sub = (lookup_list[n]->quote)(sub, opt, (unsigned)n);
7658           else if (opt)
7659             sub = NULL;
7660
7661           if (!sub)
7662             {
7663             expand_string_message = string_sprintf(
7664               "\"%s\" unrecognized after \"${quote_%s\"",       /*}*/
7665               opt, arg);
7666             goto EXPAND_FAILED;
7667             }
7668
7669           yield = string_cat(yield, sub);
7670           break;
7671           }
7672
7673         /* rx quote sticks in \ before any non-alphameric character so that
7674         the insertion works in a regular expression. */
7675
7676         case EOP_RXQUOTE:
7677           {
7678           uschar *t = sub - 1;
7679           while (*(++t) != 0)
7680             {
7681             if (!isalnum(*t))
7682               yield = string_catn(yield, US"\\", 1);
7683             yield = string_catn(yield, t, 1);
7684             }
7685           break;
7686           }
7687
7688         /* RFC 2047 encodes, assuming headers_charset (default ISO 8859-1) as
7689         prescribed by the RFC, if there are characters that need to be encoded */
7690
7691         case EOP_RFC2047:
7692           yield = string_cat(yield,
7693                               parse_quote_2047(sub, Ustrlen(sub), headers_charset,
7694                                 FALSE));
7695           break;
7696
7697         /* RFC 2047 decode */
7698
7699         case EOP_RFC2047D:
7700           {
7701           int len;
7702           uschar *error;
7703           uschar *decoded = rfc2047_decode(sub, check_rfc2047_length,
7704             headers_charset, '?', &len, &error);
7705           if (error)
7706             {
7707             expand_string_message = error;
7708             goto EXPAND_FAILED;
7709             }
7710           yield = string_catn(yield, decoded, len);
7711           break;
7712           }
7713
7714         /* from_utf8 converts UTF-8 to 8859-1, turning non-existent chars into
7715         underscores */
7716
7717         case EOP_FROM_UTF8:
7718           {
7719           uschar * buff = store_get(4, sub);
7720           while (*sub)
7721             {
7722             int c;
7723             GETUTF8INC(c, sub);
7724             if (c > 255) c = '_';
7725             buff[0] = c;
7726             yield = string_catn(yield, buff, 1);
7727             }
7728           break;
7729           }
7730
7731         /* replace illegal UTF-8 sequences by replacement character  */
7732
7733         #define UTF8_REPLACEMENT_CHAR US"?"
7734
7735         case EOP_UTF8CLEAN:
7736           {
7737           int seq_len = 0, index = 0;
7738           int bytes_left = 0;
7739           long codepoint = -1;
7740           int complete;
7741           uschar seq_buff[4];                   /* accumulate utf-8 here */
7742
7743           /* Manually track tainting, as we deal in individual chars below */
7744
7745           if (!yield->s || !yield->ptr)
7746             yield->s = store_get(yield->size = Ustrlen(sub), sub);
7747           else if (is_incompatible(yield->s, sub))
7748             gstring_rebuffer(yield, sub);
7749
7750           /* Check the UTF-8, byte-by-byte */
7751
7752           while (*sub)
7753             {
7754             complete = 0;
7755             uschar c = *sub++;
7756
7757             if (bytes_left)
7758               {
7759               if ((c & 0xc0) != 0x80)
7760                       /* wrong continuation byte; invalidate all bytes */
7761                 complete = 1; /* error */
7762               else
7763                 {
7764                 codepoint = (codepoint << 6) | (c & 0x3f);
7765                 seq_buff[index++] = c;
7766                 if (--bytes_left == 0)          /* codepoint complete */
7767                   if(codepoint > 0x10FFFF)      /* is it too large? */
7768                     complete = -1;      /* error (RFC3629 limit) */
7769                   else
7770                     {           /* finished; output utf-8 sequence */
7771                     yield = string_catn(yield, seq_buff, seq_len);
7772                     index = 0;
7773                     }
7774                 }
7775               }
7776             else        /* no bytes left: new sequence */
7777               {
7778               if(!(c & 0x80))   /* 1-byte sequence, US-ASCII, keep it */
7779                 {
7780                 yield = string_catn(yield, &c, 1);
7781                 continue;
7782                 }
7783               if((c & 0xe0) == 0xc0)            /* 2-byte sequence */
7784                 {
7785                 if(c == 0xc0 || c == 0xc1)      /* 0xc0 and 0xc1 are illegal */
7786                   complete = -1;
7787                 else
7788                   {
7789                     bytes_left = 1;
7790                     codepoint = c & 0x1f;
7791                   }
7792                 }
7793               else if((c & 0xf0) == 0xe0)               /* 3-byte sequence */
7794                 {
7795                 bytes_left = 2;
7796                 codepoint = c & 0x0f;
7797                 }
7798               else if((c & 0xf8) == 0xf0)               /* 4-byte sequence */
7799                 {
7800                 bytes_left = 3;
7801                 codepoint = c & 0x07;
7802                 }
7803               else      /* invalid or too long (RFC3629 allows only 4 bytes) */
7804                 complete = -1;
7805
7806               seq_buff[index++] = c;
7807               seq_len = bytes_left + 1;
7808               }         /* if(bytes_left) */
7809
7810             if (complete != 0)
7811               {
7812               bytes_left = index = 0;
7813               yield = string_catn(yield, UTF8_REPLACEMENT_CHAR, 1);
7814               }
7815             if ((complete == 1) && ((c & 0x80) == 0))
7816                           /* ASCII character follows incomplete sequence */
7817                 yield = string_catn(yield, &c, 1);
7818             }
7819           /* If given a sequence truncated mid-character, we also want to report ?
7820           Eg, ${length_1:フィル} is one byte, not one character, so we expect
7821           ${utf8clean:${length_1:フィル}} to yield '?' */
7822
7823           if (bytes_left != 0)
7824             yield = string_catn(yield, UTF8_REPLACEMENT_CHAR, 1);
7825
7826           break;
7827           }
7828
7829 #ifdef SUPPORT_I18N
7830         case EOP_UTF8_DOMAIN_TO_ALABEL:
7831           {
7832           uschar * error = NULL;
7833           uschar * s = string_domain_utf8_to_alabel(sub, &error);
7834           if (error)
7835             {
7836             expand_string_message = string_sprintf(
7837               "error converting utf8 (%s) to alabel: %s",
7838               string_printing(sub), error);
7839             goto EXPAND_FAILED;
7840             }
7841           yield = string_cat(yield, s);
7842           break;
7843           }
7844
7845         case EOP_UTF8_DOMAIN_FROM_ALABEL:
7846           {
7847           uschar * error = NULL;
7848           uschar * s = string_domain_alabel_to_utf8(sub, &error);
7849           if (error)
7850             {
7851             expand_string_message = string_sprintf(
7852               "error converting alabel (%s) to utf8: %s",
7853               string_printing(sub), error);
7854             goto EXPAND_FAILED;
7855             }
7856           yield = string_cat(yield, s);
7857           break;
7858           }
7859
7860         case EOP_UTF8_LOCALPART_TO_ALABEL:
7861           {
7862           uschar * error = NULL;
7863           uschar * s = string_localpart_utf8_to_alabel(sub, &error);
7864           if (error)
7865             {
7866             expand_string_message = string_sprintf(
7867               "error converting utf8 (%s) to alabel: %s",
7868               string_printing(sub), error);
7869             goto EXPAND_FAILED;
7870             }
7871           yield = string_cat(yield, s);
7872           DEBUG(D_expand) debug_printf_indent("yield: '%s'\n", yield->s);
7873           break;
7874           }
7875
7876         case EOP_UTF8_LOCALPART_FROM_ALABEL:
7877           {
7878           uschar * error = NULL;
7879           uschar * s = string_localpart_alabel_to_utf8(sub, &error);
7880           if (error)
7881             {
7882             expand_string_message = string_sprintf(
7883               "error converting alabel (%s) to utf8: %s",
7884               string_printing(sub), error);
7885             goto EXPAND_FAILED;
7886             }
7887           yield = string_cat(yield, s);
7888           break;
7889           }
7890 #endif  /* EXPERIMENTAL_INTERNATIONAL */
7891
7892         /* escape turns all non-printing characters into escape sequences. */
7893
7894         case EOP_ESCAPE:
7895           {
7896           const uschar * t = string_printing(sub);
7897           yield = string_cat(yield, t);
7898           break;
7899           }
7900
7901         case EOP_ESCAPE8BIT:
7902           {
7903           uschar c;
7904
7905           for (const uschar * s = sub; (c = *s); s++)
7906             yield = c < 127 && c != '\\'
7907               ? string_catn(yield, s, 1)
7908               : string_fmt_append(yield, "\\%03o", c);
7909           break;
7910           }
7911
7912         /* Handle numeric expression evaluation */
7913
7914         case EOP_EVAL:
7915         case EOP_EVAL10:
7916           {
7917           uschar *save_sub = sub;
7918           uschar *error = NULL;
7919           int_eximarith_t n = eval_expr(&sub, (c == EOP_EVAL10), &error, FALSE);
7920           if (error)
7921             {
7922             expand_string_message = string_sprintf("error in expression "
7923               "evaluation: %s (after processing \"%.*s\")", error,
7924               (int)(sub-save_sub), save_sub);
7925             goto EXPAND_FAILED;
7926             }
7927           yield = string_fmt_append(yield, PR_EXIM_ARITH, n);
7928           break;
7929           }
7930
7931         /* Handle time period formatting */
7932
7933         case EOP_TIME_EVAL:
7934           {
7935           int n = readconf_readtime(sub, 0, FALSE);
7936           if (n < 0)
7937             {
7938             expand_string_message = string_sprintf("string \"%s\" is not an "
7939               "Exim time interval in \"%s\" operator", sub, name);
7940             goto EXPAND_FAILED;
7941             }
7942           yield = string_fmt_append(yield, "%d", n);
7943           break;
7944           }
7945
7946         case EOP_TIME_INTERVAL:
7947           {
7948           int n;
7949           uschar *t = read_number(&n, sub);
7950           if (*t != 0) /* Not A Number*/
7951             {
7952             expand_string_message = string_sprintf("string \"%s\" is not a "
7953               "positive number in \"%s\" operator", sub, name);
7954             goto EXPAND_FAILED;
7955             }
7956           t = readconf_printtime(n);
7957           yield = string_cat(yield, t);
7958           break;
7959           }
7960
7961         /* Convert string to base64 encoding */
7962
7963         case EOP_STR2B64:
7964         case EOP_BASE64:
7965           {
7966 #ifndef DISABLE_TLS
7967           uschar * s = vp && *(void **)vp->value
7968             ? tls_cert_der_b64(*(void **)vp->value)
7969             : b64encode(CUS sub, Ustrlen(sub));
7970 #else
7971           uschar * s = b64encode(CUS sub, Ustrlen(sub));
7972 #endif
7973           yield = string_cat(yield, s);
7974           break;
7975           }
7976
7977         case EOP_BASE64D:
7978           {
7979           uschar * s;
7980           int len = b64decode(sub, &s);
7981           if (len < 0)
7982             {
7983             expand_string_message = string_sprintf("string \"%s\" is not "
7984               "well-formed for \"%s\" operator", sub, name);
7985             goto EXPAND_FAILED;
7986             }
7987           yield = string_cat(yield, s);
7988           break;
7989           }
7990
7991         /* strlen returns the length of the string */
7992
7993         case EOP_STRLEN:
7994           yield = string_fmt_append(yield, "%d", Ustrlen(sub));
7995           break;
7996
7997         /* length_n or l_n takes just the first n characters or the whole string,
7998         whichever is the shorter;
7999
8000         substr_m_n, and s_m_n take n characters from offset m; negative m take
8001         from the end; l_n is synonymous with s_0_n. If n is omitted in substr it
8002         takes the rest, either to the right or to the left.
8003
8004         hash_n or h_n makes a hash of length n from the string, yielding n
8005         characters from the set a-z; hash_n_m makes a hash of length n, but
8006         uses m characters from the set a-zA-Z0-9.
8007
8008         nhash_n returns a single number between 0 and n-1 (in text form), while
8009         nhash_n_m returns a div/mod hash as two numbers "a/b". The first lies
8010         between 0 and n-1 and the second between 0 and m-1. */
8011
8012         case EOP_LENGTH:
8013         case EOP_L:
8014         case EOP_SUBSTR:
8015         case EOP_S:
8016         case EOP_HASH:
8017         case EOP_H:
8018         case EOP_NHASH:
8019         case EOP_NH:
8020           {
8021           int sign = 1;
8022           int value1 = 0;
8023           int value2 = -1;
8024           int *pn;
8025           int len;
8026           uschar *ret;
8027
8028           if (!arg)
8029             {
8030             expand_string_message = string_sprintf("missing values after %s",
8031               name);
8032             goto EXPAND_FAILED;
8033             }
8034
8035           /* "length" has only one argument, effectively being synonymous with
8036           substr_0_n. */
8037
8038           if (c == EOP_LENGTH || c == EOP_L)
8039             {
8040             pn = &value2;
8041             value2 = 0;
8042             }
8043
8044           /* The others have one or two arguments; for "substr" the first may be
8045           negative. The second being negative means "not supplied". */
8046
8047           else
8048             {
8049             pn = &value1;
8050             if (name[0] == 's' && *arg == '-') { sign = -1; arg++; }
8051             }
8052
8053           /* Read up to two numbers, separated by underscores */
8054
8055           ret = arg;
8056           while (*arg != 0)
8057             {
8058             if (arg != ret && *arg == '_' && pn == &value1)
8059               {
8060               pn = &value2;
8061               value2 = 0;
8062               if (arg[1] != 0) arg++;
8063               }
8064             else if (!isdigit(*arg))
8065               {
8066               expand_string_message =
8067                 string_sprintf("non-digit after underscore in \"%s\"", name);
8068               goto EXPAND_FAILED;
8069               }
8070             else *pn = (*pn)*10 + *arg++ - '0';
8071             }
8072           value1 *= sign;
8073
8074           /* Perform the required operation */
8075
8076           ret = c == EOP_HASH || c == EOP_H
8077             ? compute_hash(sub, value1, value2, &len)
8078             : c == EOP_NHASH || c == EOP_NH
8079             ? compute_nhash(sub, value1, value2, &len)
8080             : extract_substr(sub, value1, value2, &len);
8081           if (!ret) goto EXPAND_FAILED;
8082
8083           yield = string_catn(yield, ret, len);
8084           break;
8085           }
8086
8087         /* Stat a path */
8088
8089         case EOP_STAT:
8090           {
8091           uschar smode[12];
8092           uschar **modetable[3];
8093           mode_t mode;
8094           struct stat st;
8095
8096           if (expand_forbid & RDO_EXISTS)
8097             {
8098             expand_string_message = US"Use of the stat() expansion is not permitted";
8099             goto EXPAND_FAILED;
8100             }
8101
8102           if (stat(CS sub, &st) < 0)
8103             {
8104             expand_string_message = string_sprintf("stat(%s) failed: %s",
8105               sub, strerror(errno));
8106             goto EXPAND_FAILED;
8107             }
8108           mode = st.st_mode;
8109           switch (mode & S_IFMT)
8110             {
8111             case S_IFIFO: smode[0] = 'p'; break;
8112             case S_IFCHR: smode[0] = 'c'; break;
8113             case S_IFDIR: smode[0] = 'd'; break;
8114             case S_IFBLK: smode[0] = 'b'; break;
8115             case S_IFREG: smode[0] = '-'; break;
8116             default: smode[0] = '?'; break;
8117             }
8118
8119           modetable[0] = ((mode & 01000) == 0)? mtable_normal : mtable_sticky;
8120           modetable[1] = ((mode & 02000) == 0)? mtable_normal : mtable_setid;
8121           modetable[2] = ((mode & 04000) == 0)? mtable_normal : mtable_setid;
8122
8123           for (int i = 0; i < 3; i++)
8124             {
8125             memcpy(CS(smode + 7 - i*3), CS(modetable[i][mode & 7]), 3);
8126             mode >>= 3;
8127             }
8128
8129           smode[10] = 0;
8130           yield = string_fmt_append(yield,
8131             "mode=%04lo smode=%s inode=%ld device=%ld links=%ld "
8132             "uid=%ld gid=%ld size=" OFF_T_FMT " atime=%ld mtime=%ld ctime=%ld",
8133             (long)(st.st_mode & 077777), smode, (long)st.st_ino,
8134             (long)st.st_dev, (long)st.st_nlink, (long)st.st_uid,
8135             (long)st.st_gid, st.st_size, (long)st.st_atime,
8136             (long)st.st_mtime, (long)st.st_ctime);
8137           break;
8138           }
8139
8140         /* vaguely random number less than N */
8141
8142         case EOP_RANDINT:
8143           {
8144           int_eximarith_t max = expanded_string_integer(sub, TRUE);
8145
8146           if (expand_string_message)
8147             goto EXPAND_FAILED;
8148           yield = string_fmt_append(yield, "%d", vaguely_random_number((int)max));
8149           break;
8150           }
8151
8152         /* Reverse IP, including IPv6 to dotted-nibble */
8153
8154         case EOP_REVERSE_IP:
8155           {
8156           int family, maskptr;
8157           uschar reversed[128];
8158
8159           family = string_is_ip_address(sub, &maskptr);
8160           if (family == 0)
8161             {
8162             expand_string_message = string_sprintf(
8163                 "reverse_ip() not given an IP address [%s]", sub);
8164             goto EXPAND_FAILED;
8165             }
8166           invert_address(reversed, sub);
8167           yield = string_cat(yield, reversed);
8168           break;
8169           }
8170
8171         /* Unknown operator */
8172
8173         default:
8174           expand_string_message =
8175             string_sprintf("unknown expansion operator \"%s\"", name);
8176           goto EXPAND_FAILED;
8177         }       /* EOP_* switch */
8178
8179        DEBUG(D_expand)
8180         {
8181         const uschar * s = yield->s + start;
8182         int i = yield->ptr - start;
8183         BOOL tainted = is_tainted(s);
8184
8185         DEBUG(D_noutf8)
8186           {
8187           debug_printf_indent("|-----op-res: %.*s\n", i, s);
8188           if (tainted)
8189             {
8190             debug_printf_indent("%s     \\__", flags & ESI_SKIPPING ? "|     " : "      ");
8191             debug_print_taint(yield->s);
8192             }
8193           }
8194         else
8195           {
8196           debug_printf_indent(UTF8_VERT_RIGHT
8197             UTF8_HORIZ UTF8_HORIZ UTF8_HORIZ UTF8_HORIZ UTF8_HORIZ
8198             "op-res: %.*s\n", i, s);
8199           if (tainted)
8200             {
8201             debug_printf_indent("%s",
8202               flags & ESI_SKIPPING
8203               ? UTF8_VERT "             " : "           " UTF8_UP_RIGHT UTF8_HORIZ UTF8_HORIZ);
8204             debug_print_taint(yield->s);
8205             }
8206           }
8207         }
8208        continue;
8209        }
8210     }
8211
8212   /* Not an item or an operator */
8213   /* Handle a plain name. If this is the first thing in the expansion, release
8214   the pre-allocated buffer. If the result data is known to be in a new buffer,
8215   newsize will be set to the size of that buffer, and we can just point at that
8216   store instead of copying. Many expansion strings contain just one reference,
8217   so this is a useful optimization, especially for humungous headers
8218   ($message_headers). */
8219                                                 /*{*/
8220   if (*s++ == '}')
8221     {
8222     const uschar * value;
8223     int len;
8224     int newsize = 0;
8225     gstring * g = NULL;
8226
8227     if (!yield)
8228       g = store_get(sizeof(gstring), GET_UNTAINTED);
8229     else if (yield->ptr == 0)
8230       {
8231       if (resetok) reset_point = store_reset(reset_point);
8232       yield = NULL;
8233       reset_point = store_mark();
8234       g = store_get(sizeof(gstring), GET_UNTAINTED);    /* alloc _before_ calling find_variable() */
8235       }
8236     if (!(value = find_variable(name, FALSE, !!(flags & ESI_SKIPPING), &newsize)))
8237       {
8238       expand_string_message =
8239         string_sprintf("unknown variable in \"${%s}\"", name);
8240       check_variable_error_message(name);
8241       goto EXPAND_FAILED;
8242       }
8243     len = Ustrlen(value);
8244     if (!yield && newsize)
8245       {
8246       yield = g;
8247       yield->size = newsize;
8248       yield->ptr = len;
8249       yield->s = US value; /* known to be in new store i.e. a copy, so deconst safe */
8250       }
8251     else
8252       yield = string_catn(yield, value, len);
8253     continue;
8254     }
8255
8256   /* Else there's something wrong */
8257
8258   expand_string_message =
8259     string_sprintf("\"${%s\" is not a known operator (or a } is missing "
8260     "in a variable reference)", name);
8261   goto EXPAND_FAILED;
8262   }
8263
8264 /* If we hit the end of the string when brace_ends is set, there is a missing
8265 terminating brace. */
8266
8267 if (flags & ESI_BRACE_ENDS && !*s)
8268   {                                                     /*{{*/
8269   expand_string_message = malformed_header
8270     ? US"missing } at end of string - could be header name not terminated by colon"
8271     : US"missing } at end of string";
8272   goto EXPAND_FAILED;
8273   }
8274
8275 /* Expansion succeeded; yield may still be NULL here if nothing was actually
8276 added to the string. If so, set up an empty string. Add a terminating zero. If
8277 left != NULL, return a pointer to the terminator. */
8278
8279 if (!yield)
8280   yield = string_get(1);
8281 (void) string_from_gstring(yield);
8282 if (left) *left = s;
8283
8284 /* Any stacking store that was used above the final string is no longer needed.
8285 In many cases the final string will be the first one that was got and so there
8286 will be optimal store usage. */
8287
8288 if (resetok) gstring_release_unused(yield);
8289 else if (resetok_p) *resetok_p = FALSE;
8290
8291 DEBUG(D_expand)
8292   {
8293   BOOL tainted = is_tainted(yield->s);
8294   DEBUG(D_noutf8)
8295     {
8296     debug_printf_indent("|--expanding: %.*s\n", (int)(s - string), string);
8297     debug_printf_indent("%sresult: %s\n",
8298       flags & ESI_SKIPPING ? "|-----" : "\\_____", yield->s);
8299     if (tainted)
8300       {
8301       debug_printf_indent("%s     \\__", flags & ESI_SKIPPING ? "|     " : "      ");
8302       debug_print_taint(yield->s);
8303       }
8304     if (flags & ESI_SKIPPING)
8305       debug_printf_indent("\\___skipping: result is not used\n");
8306     }
8307   else
8308     {
8309     debug_printf_indent(UTF8_VERT_RIGHT UTF8_HORIZ UTF8_HORIZ
8310       "expanding: %.*s\n",
8311       (int)(s - string), string);
8312     debug_printf_indent("%s" UTF8_HORIZ UTF8_HORIZ UTF8_HORIZ UTF8_HORIZ UTF8_HORIZ
8313       "result: %s\n",
8314       flags & ESI_SKIPPING ? UTF8_VERT_RIGHT : UTF8_UP_RIGHT,
8315       yield->s);
8316     if (tainted)
8317       {
8318       debug_printf_indent("%s",
8319         flags & ESI_SKIPPING
8320         ? UTF8_VERT "             " : "           " UTF8_UP_RIGHT UTF8_HORIZ UTF8_HORIZ);
8321       debug_print_taint(yield->s);
8322       }
8323     if (flags & ESI_SKIPPING)
8324       debug_printf_indent(UTF8_UP_RIGHT UTF8_HORIZ UTF8_HORIZ UTF8_HORIZ
8325         "skipping: result is not used\n");
8326     }
8327   }
8328 if (textonly_p) *textonly_p = textonly;
8329 expand_level--;
8330 return yield->s;
8331
8332 /* This is the failure exit: easiest to program with a goto. We still need
8333 to update the pointer to the terminator, for cases of nested calls with "fail".
8334 */
8335
8336 EXPAND_FAILED_CURLY:
8337 if (malformed_header)
8338   expand_string_message =
8339     US"missing or misplaced { or } - could be header name not terminated by colon";
8340
8341 else if (!expand_string_message || !*expand_string_message)
8342   expand_string_message = US"missing or misplaced { or }";
8343
8344 /* At one point, Exim reset the store to yield (if yield was not NULL), but
8345 that is a bad idea, because expand_string_message is in dynamic store. */
8346
8347 EXPAND_FAILED:
8348 if (left) *left = s;
8349 DEBUG(D_expand)
8350   {
8351   DEBUG(D_noutf8)
8352     {
8353     debug_printf_indent("|failed to expand: %s\n", string);
8354     debug_printf_indent("%serror message: %s\n",
8355       f.expand_string_forcedfail ? "|---" : "\\___", expand_string_message);
8356     if (f.expand_string_forcedfail)
8357       debug_printf_indent("\\failure was forced\n");
8358     }
8359   else
8360     {
8361     debug_printf_indent(UTF8_VERT_RIGHT "failed to expand: %s\n",
8362       string);
8363     debug_printf_indent("%s" UTF8_HORIZ UTF8_HORIZ UTF8_HORIZ
8364       "error message: %s\n",
8365       f.expand_string_forcedfail ? UTF8_VERT_RIGHT : UTF8_UP_RIGHT,
8366       expand_string_message);
8367     if (f.expand_string_forcedfail)
8368       debug_printf_indent(UTF8_UP_RIGHT "failure was forced\n");
8369     }
8370   }
8371 if (resetok_p && !resetok) *resetok_p = FALSE;
8372 expand_level--;
8373 return NULL;
8374 }
8375
8376
8377
8378 /* This is the external function call. Do a quick check for any expansion
8379 metacharacters, and if there are none, just return the input string.
8380
8381 Arguments
8382         the string to be expanded
8383         optional pointer for return boolean indicating no-dynamic-expansions
8384
8385 Returns:  the expanded string, or NULL if expansion failed; if failure was
8386           due to a lookup deferring, search_find_defer will be TRUE
8387 */
8388
8389 const uschar *
8390 expand_string_2(const uschar * string, BOOL * textonly_p)
8391 {
8392 if (Ustrpbrk(string, "$\\") != NULL)
8393   {
8394   int old_pool = store_pool;
8395   uschar * s;
8396
8397   f.search_find_defer = FALSE;
8398   malformed_header = FALSE;
8399   store_pool = POOL_MAIN;
8400     s = expand_string_internal(string, ESI_HONOR_DOLLAR, NULL, NULL, textonly_p);
8401   store_pool = old_pool;
8402   return s;
8403   }
8404 if (textonly_p) *textonly_p = TRUE;
8405 return string;
8406 }
8407
8408 const uschar *
8409 expand_cstring(const uschar * string)
8410 { return expand_string_2(string, NULL); }
8411
8412 uschar *
8413 expand_string(uschar * string)
8414 { return US expand_string_2(CUS string, NULL); }
8415
8416
8417
8418
8419
8420
8421 /*************************************************
8422 *              Expand and copy                   *
8423 *************************************************/
8424
8425 /* Now and again we want to expand a string and be sure that the result is in a
8426 new bit of store. This function does that.
8427 Since we know it has been copied, the de-const cast is safe.
8428
8429 Argument: the string to be expanded
8430 Returns:  the expanded string, always in a new bit of store, or NULL
8431 */
8432
8433 uschar *
8434 expand_string_copy(const uschar *string)
8435 {
8436 const uschar *yield = expand_cstring(string);
8437 if (yield == string) yield = string_copy(string);
8438 return US yield;
8439 }
8440
8441
8442
8443 /*************************************************
8444 *        Expand and interpret as an integer      *
8445 *************************************************/
8446
8447 /* Expand a string, and convert the result into an integer.
8448
8449 Arguments:
8450   string  the string to be expanded
8451   isplus  TRUE if a non-negative number is expected
8452
8453 Returns:  the integer value, or
8454           -1 for an expansion error               ) in both cases, message in
8455           -2 for an integer interpretation error  ) expand_string_message
8456           expand_string_message is set NULL for an OK integer
8457 */
8458
8459 int_eximarith_t
8460 expand_string_integer(uschar *string, BOOL isplus)
8461 {
8462 return expanded_string_integer(expand_string(string), isplus);
8463 }
8464
8465
8466 /*************************************************
8467  *         Interpret string as an integer        *
8468  *************************************************/
8469
8470 /* Convert a string (that has already been expanded) into an integer.
8471
8472 This function is used inside the expansion code.
8473
8474 Arguments:
8475   s       the string to be expanded
8476   isplus  TRUE if a non-negative number is expected
8477
8478 Returns:  the integer value, or
8479           -1 if string is NULL (which implies an expansion error)
8480           -2 for an integer interpretation error
8481           expand_string_message is set NULL for an OK integer
8482 */
8483
8484 static int_eximarith_t
8485 expanded_string_integer(const uschar *s, BOOL isplus)
8486 {
8487 int_eximarith_t value;
8488 uschar *msg = US"invalid integer \"%s\"";
8489 uschar *endptr;
8490
8491 /* If expansion failed, expand_string_message will be set. */
8492
8493 if (!s) return -1;
8494
8495 /* On an overflow, strtol() returns LONG_MAX or LONG_MIN, and sets errno
8496 to ERANGE. When there isn't an overflow, errno is not changed, at least on some
8497 systems, so we set it zero ourselves. */
8498
8499 errno = 0;
8500 expand_string_message = NULL;               /* Indicates no error */
8501
8502 /* Before Exim 4.64, strings consisting entirely of whitespace compared
8503 equal to 0.  Unfortunately, people actually relied upon that, so preserve
8504 the behaviour explicitly.  Stripping leading whitespace is a harmless
8505 noop change since strtol skips it anyway (provided that there is a number
8506 to find at all). */
8507 if (isspace(*s))
8508   if (Uskip_whitespace(&s) == '\0')
8509     {
8510       DEBUG(D_expand)
8511        debug_printf_indent("treating blank string as number 0\n");
8512       return 0;
8513     }
8514
8515 value = strtoll(CS s, CSS &endptr, 10);
8516
8517 if (endptr == s)
8518   msg = US"integer expected but \"%s\" found";
8519 else if (value < 0 && isplus)
8520   msg = US"non-negative integer expected but \"%s\" found";
8521 else
8522   {
8523   switch (tolower(*endptr))
8524     {
8525     default:
8526       break;
8527     case 'k':
8528       if (value > EXIM_ARITH_MAX/1024 || value < EXIM_ARITH_MIN/1024) errno = ERANGE;
8529       else value *= 1024;
8530       endptr++;
8531       break;
8532     case 'm':
8533       if (value > EXIM_ARITH_MAX/(1024*1024) || value < EXIM_ARITH_MIN/(1024*1024)) errno = ERANGE;
8534       else value *= 1024*1024;
8535       endptr++;
8536       break;
8537     case 'g':
8538       if (value > EXIM_ARITH_MAX/(1024*1024*1024) || value < EXIM_ARITH_MIN/(1024*1024*1024)) errno = ERANGE;
8539       else value *= 1024*1024*1024;
8540       endptr++;
8541       break;
8542     }
8543   if (errno == ERANGE)
8544     msg = US"absolute value of integer \"%s\" is too large (overflow)";
8545   else
8546     if (Uskip_whitespace(&endptr) == 0) return value;
8547   }
8548
8549 expand_string_message = string_sprintf(CS msg, s);
8550 return -2;
8551 }
8552
8553
8554 /* These values are usually fixed boolean values, but they are permitted to be
8555 expanded strings.
8556
8557 Arguments:
8558   addr       address being routed
8559   mtype      the module type
8560   mname      the module name
8561   dbg_opt    debug selectors
8562   oname      the option name
8563   bvalue     the router's boolean value
8564   svalue     the router's string value
8565   rvalue     where to put the returned value
8566
8567 Returns:     OK     value placed in rvalue
8568              DEFER  expansion failed
8569 */
8570
8571 int
8572 exp_bool(address_item *addr,
8573   uschar *mtype, uschar *mname, unsigned dbg_opt,
8574   uschar *oname, BOOL bvalue,
8575   uschar *svalue, BOOL *rvalue)
8576 {
8577 uschar *expanded;
8578 if (!svalue) { *rvalue = bvalue; return OK; }
8579
8580 if (!(expanded = expand_string(svalue)))
8581   {
8582   if (f.expand_string_forcedfail)
8583     {
8584     DEBUG(dbg_opt) debug_printf("expansion of \"%s\" forced failure\n", oname);
8585     *rvalue = bvalue;
8586     return OK;
8587     }
8588   addr->message = string_sprintf("failed to expand \"%s\" in %s %s: %s",
8589       oname, mname, mtype, expand_string_message);
8590   DEBUG(dbg_opt) debug_printf("%s\n", addr->message);
8591   return DEFER;
8592   }
8593
8594 DEBUG(dbg_opt) debug_printf("expansion of \"%s\" yields \"%s\"\n", oname,
8595   expanded);
8596
8597 if (strcmpic(expanded, US"true") == 0 || strcmpic(expanded, US"yes") == 0)
8598   *rvalue = TRUE;
8599 else if (strcmpic(expanded, US"false") == 0 || strcmpic(expanded, US"no") == 0)
8600   *rvalue = FALSE;
8601 else
8602   {
8603   addr->message = string_sprintf("\"%s\" is not a valid value for the "
8604     "\"%s\" option in the %s %s", expanded, oname, mname, mtype);
8605   return DEFER;
8606   }
8607
8608 return OK;
8609 }
8610
8611
8612
8613 /* Avoid potentially exposing a password in a string about to be logged */
8614
8615 uschar *
8616 expand_hide_passwords(uschar * s)
8617 {
8618 return (  (  Ustrstr(s, "failed to expand") != NULL
8619           || Ustrstr(s, "expansion of ")    != NULL
8620           )
8621        && (  Ustrstr(s, "mysql")   != NULL
8622           || Ustrstr(s, "pgsql")   != NULL
8623           || Ustrstr(s, "redis")   != NULL
8624           || Ustrstr(s, "sqlite")  != NULL
8625           || Ustrstr(s, "ldap:")   != NULL
8626           || Ustrstr(s, "ldaps:")  != NULL
8627           || Ustrstr(s, "ldapi:")  != NULL
8628           || Ustrstr(s, "ldapdn:") != NULL
8629           || Ustrstr(s, "ldapm:")  != NULL
8630        )  )
8631   ? US"Temporary internal error" : s;
8632 }
8633
8634
8635 /* Read given named file into big_buffer.  Use for keying material etc.
8636 The content will have an ascii NUL appended.
8637
8638 Arguments:
8639  filename       as it says
8640
8641 Return:  pointer to buffer, or NULL on error.
8642 */
8643
8644 uschar *
8645 expand_file_big_buffer(const uschar * filename)
8646 {
8647 int fd, off = 0, len;
8648
8649 if ((fd = exim_open2(CS filename, O_RDONLY)) < 0)
8650   {
8651   log_write(0, LOG_MAIN | LOG_PANIC, "unable to open file for reading: %s",
8652              filename);
8653   return NULL;
8654   }
8655
8656 do
8657   {
8658   if ((len = read(fd, big_buffer + off, big_buffer_size - 2 - off)) < 0)
8659     {
8660     (void) close(fd);
8661     log_write(0, LOG_MAIN|LOG_PANIC, "unable to read file: %s", filename);
8662     return NULL;
8663     }
8664   off += len;
8665   }
8666 while (len > 0);
8667
8668 (void) close(fd);
8669 big_buffer[off] = '\0';
8670 return big_buffer;
8671 }
8672
8673
8674
8675 /*************************************************
8676 * Error-checking for testsuite                   *
8677 *************************************************/
8678 typedef struct {
8679   uschar *      region_start;
8680   uschar *      region_end;
8681   const uschar *var_name;
8682   const uschar *var_data;
8683 } err_ctx;
8684
8685 /* Called via tree_walk, which allows nonconst name/data.  Our usage is const. */
8686 static void
8687 assert_variable_notin(uschar * var_name, uschar * var_data, void * ctx)
8688 {
8689 err_ctx * e = ctx;
8690 if (var_data >= e->region_start  &&  var_data < e->region_end)
8691   {
8692   e->var_name = CUS var_name;
8693   e->var_data = CUS var_data;
8694   }
8695 }
8696
8697 void
8698 assert_no_variables(void * ptr, int len, const char * filename, int linenumber)
8699 {
8700 err_ctx e = { .region_start = ptr, .region_end = US ptr + len,
8701               .var_name = NULL, .var_data = NULL };
8702
8703 /* check acl_ variables */
8704 tree_walk(acl_var_c, assert_variable_notin, &e);
8705 tree_walk(acl_var_m, assert_variable_notin, &e);
8706
8707 /* check auth<n> variables.
8708 assert_variable_notin() treats as const, so deconst is safe. */
8709 for (int i = 0; i < AUTH_VARS; i++) if (auth_vars[i])
8710   assert_variable_notin(US"auth<n>", US auth_vars[i], &e);
8711
8712 /* check regex<n> variables. assert_variable_notin() treats as const. */
8713 for (int i = 0; i < REGEX_VARS; i++) if (regex_vars[i])
8714   assert_variable_notin(US"regex<n>", US regex_vars[i], &e);
8715
8716 /* check known-name variables */
8717 for (var_entry * v = var_table; v < var_table + var_table_size; v++)
8718   if (v->type == vtype_stringptr)
8719     assert_variable_notin(US v->name, *(USS v->value), &e);
8720
8721 /* check dns and address trees */
8722 tree_walk(tree_dns_fails,     assert_variable_notin, &e);
8723 tree_walk(tree_duplicates,    assert_variable_notin, &e);
8724 tree_walk(tree_nonrecipients, assert_variable_notin, &e);
8725 tree_walk(tree_unusable,      assert_variable_notin, &e);
8726
8727 if (e.var_name)
8728   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
8729     "live variable '%s' destroyed by reset_store at %s:%d\n- value '%.64s'",
8730     e.var_name, filename, linenumber, e.var_data);
8731 }
8732
8733
8734
8735 /*************************************************
8736 **************************************************
8737 *             Stand-alone test program           *
8738 **************************************************
8739 *************************************************/
8740
8741 #ifdef STAND_ALONE
8742
8743
8744 BOOL
8745 regex_match_and_setup(const pcre2_code *re, uschar *subject, int options, int setup)
8746 {
8747 int ovec[3*(EXPAND_MAXN+1)];
8748 int n = pcre_exec(re, NULL, subject, Ustrlen(subject), 0, PCRE_EOPT|options,
8749   ovec, nelem(ovec));
8750 BOOL yield = n >= 0;
8751 if (n == 0) n = EXPAND_MAXN + 1;
8752 if (yield)
8753   {
8754   expand_nmax = setup < 0 ? 0 : setup + 1;
8755   for (int nn = setup < 0 ? 0 : 2; nn < n*2; nn += 2)
8756     {
8757     expand_nstring[expand_nmax] = subject + ovec[nn];
8758     expand_nlength[expand_nmax++] = ovec[nn+1] - ovec[nn];
8759     }
8760   expand_nmax--;
8761   }
8762 return yield;
8763 }
8764
8765
8766 int main(int argc, uschar **argv)
8767 {
8768 uschar buffer[1024];
8769
8770 debug_selector = D_v;
8771 debug_file = stderr;
8772 debug_fd = fileno(debug_file);
8773 big_buffer = malloc(big_buffer_size);
8774 store_init();
8775
8776 for (int i = 1; i < argc; i++)
8777   {
8778   if (argv[i][0] == '+')
8779     {
8780     debug_trace_memory = 2;
8781     argv[i]++;
8782     }
8783   if (isdigit(argv[i][0]))
8784     debug_selector = Ustrtol(argv[i], NULL, 0);
8785   else
8786     if (Ustrspn(argv[i], "abcdefghijklmnopqrtsuvwxyz0123456789-.:/") ==
8787         Ustrlen(argv[i]))
8788       {
8789 #ifdef LOOKUP_LDAP
8790       eldap_default_servers = argv[i];
8791 #endif
8792 #ifdef LOOKUP_MYSQL
8793       mysql_servers = argv[i];
8794 #endif
8795 #ifdef LOOKUP_PGSQL
8796       pgsql_servers = argv[i];
8797 #endif
8798 #ifdef LOOKUP_REDIS
8799       redis_servers = argv[i];
8800 #endif
8801       }
8802 #ifdef EXIM_PERL
8803   else opt_perl_startup = argv[i];
8804 #endif
8805   }
8806
8807 printf("Testing string expansion: debug_level = %d\n\n", debug_level);
8808
8809 expand_nstring[1] = US"string 1....";
8810 expand_nlength[1] = 8;
8811 expand_nmax = 1;
8812
8813 #ifdef EXIM_PERL
8814 if (opt_perl_startup != NULL)
8815   {
8816   uschar *errstr;
8817   printf("Starting Perl interpreter\n");
8818   errstr = init_perl(opt_perl_startup);
8819   if (errstr != NULL)
8820     {
8821     printf("** error in perl_startup code: %s\n", errstr);
8822     return EXIT_FAILURE;
8823     }
8824   }
8825 #endif /* EXIM_PERL */
8826
8827 /* Thie deliberately regards the input as untainted, so that it can be
8828 expanded; only reasonable since this is a test for string-expansions. */
8829
8830 while (fgets(buffer, sizeof(buffer), stdin) != NULL)
8831   {
8832   rmark reset_point = store_mark();
8833   uschar *yield = expand_string(buffer);
8834   if (yield)
8835     printf("%s\n", yield);
8836   else
8837     {
8838     if (f.search_find_defer) printf("search_find deferred\n");
8839     printf("Failed: %s\n", expand_string_message);
8840     if (f.expand_string_forcedfail) printf("Forced failure\n");
8841     printf("\n");
8842     }
8843   store_reset(reset_point);
8844   }
8845
8846 search_tidyup();
8847
8848 return 0;
8849 }
8850
8851 #endif
8852
8853 /* vi: aw ai sw=2
8854 */
8855 /* End of expand.c */