Add owner-* parameter as of RFC 5436.
[exim.git] / src / src / expand.c
CommitLineData
b52bc06e 1/* $Cambridge: exim/src/src/expand.c,v 1.97 2008/12/12 14:51:47 nm4 Exp $ */
059ec3d9
PH
2
3/*************************************************
4* Exim - an Internet mail transport agent *
5*************************************************/
6
184e8823 7/* Copyright (c) University of Cambridge 1995 - 2007 */
059ec3d9
PH
8/* See the file NOTICE for conditions of use and distribution. */
9
10
11/* Functions for handling string expansion. */
12
13
14#include "exim.h"
15
96c065cb
PH
16/* Recursively called function */
17
18static uschar *expand_string_internal(uschar *, BOOL, uschar **, BOOL);
19
059ec3d9
PH
20#ifdef STAND_ALONE
21#ifndef SUPPORT_CRYPTEQ
22#define SUPPORT_CRYPTEQ
23#endif
24#endif
25
96c065cb
PH
26#ifdef LOOKUP_LDAP
27#include "lookups/ldap.h"
28#endif
29
059ec3d9
PH
30#ifdef SUPPORT_CRYPTEQ
31#ifdef CRYPT_H
32#include <crypt.h>
33#endif
34#ifndef HAVE_CRYPT16
35extern char* crypt16(char*, char*);
36#endif
37#endif
38
96c065cb
PH
39/* The handling of crypt16() is a mess. I will record below the analysis of the
40mess that was sent to me. We decided, however, to make changing this very low
41priority, because in practice people are moving away from the crypt()
42algorithms nowadays, so it doesn't seem worth it.
43
44<quote>
45There is an algorithm named "crypt16" in Ultrix and Tru64. It crypts
46the first 8 characters of the password using a 20-round version of crypt
47(standard crypt does 25 rounds). It then crypts the next 8 characters,
48or an empty block if the password is less than 9 characters, using a
4920-round version of crypt and the same salt as was used for the first
50block. Charaters after the first 16 are ignored. It always generates
51a 16-byte hash, which is expressed together with the salt as a string
52of 24 base 64 digits. Here are some links to peruse:
53
54 http://cvs.pld.org.pl/pam/pamcrypt/crypt16.c?rev=1.2
55 http://seclists.org/bugtraq/1999/Mar/0076.html
56
57There's a different algorithm named "bigcrypt" in HP-UX, Digital Unix,
58and OSF/1. This is the same as the standard crypt if given a password
59of 8 characters or less. If given more, it first does the same as crypt
60using the first 8 characters, then crypts the next 8 (the 9th to 16th)
61using as salt the first two base 64 digits from the first hash block.
62If the password is more than 16 characters then it crypts the 17th to 24th
63characters using as salt the first two base 64 digits from the second hash
64block. And so on: I've seen references to it cutting off the password at
6540 characters (5 blocks), 80 (10 blocks), or 128 (16 blocks). Some links:
66
67 http://cvs.pld.org.pl/pam/pamcrypt/bigcrypt.c?rev=1.2
68 http://seclists.org/bugtraq/1999/Mar/0109.html
69 http://h30097.www3.hp.com/docs/base_doc/DOCUMENTATION/HTML/AA-Q0R2D-
70 TET1_html/sec.c222.html#no_id_208
71
72Exim has something it calls "crypt16". It will either use a native
73crypt16 or its own implementation. A native crypt16 will presumably
74be the one that I called "crypt16" above. The internal "crypt16"
75function, however, is a two-block-maximum implementation of what I called
76"bigcrypt". The documentation matches the internal code.
77
78I suspect that whoever did the "crypt16" stuff for Exim didn't realise
79that crypt16 and bigcrypt were different things.
80
81Exim uses the LDAP-style scheme identifier "{crypt16}" to refer
82to whatever it is using under that name. This unfortunately sets a
83precedent for using "{crypt16}" to identify two incompatible algorithms
84whose output can't be distinguished. With "{crypt16}" thus rendered
85ambiguous, I suggest you deprecate it and invent two new identifiers
86for the two algorithms.
87
88Both crypt16 and bigcrypt are very poor algorithms, btw. Hashing parts
89of the password separately means they can be cracked separately, so
90the double-length hash only doubles the cracking effort instead of
91squaring it. I recommend salted SHA-1 ({SSHA}), or the Blowfish-based
92bcrypt ({CRYPT}$2a$).
93</quote>
94*/
059ec3d9
PH
95
96
059ec3d9
PH
97
98
99/*************************************************
100* Local statics and tables *
101*************************************************/
102
103/* Table of item names, and corresponding switch numbers. The names must be in
104alphabetical order. */
105
106static uschar *item_table[] = {
1a46a8c5 107 US"dlfunc",
059ec3d9 108 US"extract",
29f89cad 109 US"filter",
059ec3d9
PH
110 US"hash",
111 US"hmac",
112 US"if",
113 US"length",
114 US"lookup",
29f89cad 115 US"map",
059ec3d9 116 US"nhash",
1a46a8c5 117 US"perl",
fffda43a
TK
118 US"prvs",
119 US"prvscheck",
059ec3d9
PH
120 US"readfile",
121 US"readsocket",
29f89cad 122 US"reduce",
059ec3d9
PH
123 US"run",
124 US"sg",
125 US"substr",
126 US"tr" };
127
128enum {
1a46a8c5 129 EITEM_DLFUNC,
059ec3d9 130 EITEM_EXTRACT,
29f89cad 131 EITEM_FILTER,
059ec3d9
PH
132 EITEM_HASH,
133 EITEM_HMAC,
134 EITEM_IF,
135 EITEM_LENGTH,
136 EITEM_LOOKUP,
29f89cad 137 EITEM_MAP,
059ec3d9 138 EITEM_NHASH,
1a46a8c5 139 EITEM_PERL,
fffda43a
TK
140 EITEM_PRVS,
141 EITEM_PRVSCHECK,
059ec3d9
PH
142 EITEM_READFILE,
143 EITEM_READSOCK,
29f89cad 144 EITEM_REDUCE,
059ec3d9
PH
145 EITEM_RUN,
146 EITEM_SG,
147 EITEM_SUBSTR,
148 EITEM_TR };
149
150/* Tables of operator names, and corresponding switch numbers. The names must be
151in alphabetical order. There are two tables, because underscore is used in some
152cases to introduce arguments, whereas for other it is part of the name. This is
153an historical mis-design. */
154
155static uschar *op_table_underscore[] = {
156 US"from_utf8",
157 US"local_part",
158 US"quote_local_part",
f90d018c 159 US"time_eval",
059ec3d9
PH
160 US"time_interval"};
161
162enum {
163 EOP_FROM_UTF8,
164 EOP_LOCAL_PART,
165 EOP_QUOTE_LOCAL_PART,
f90d018c 166 EOP_TIME_EVAL,
059ec3d9
PH
167 EOP_TIME_INTERVAL };
168
169static uschar *op_table_main[] = {
170 US"address",
29f89cad 171 US"addresses",
059ec3d9
PH
172 US"base62",
173 US"base62d",
174 US"domain",
175 US"escape",
176 US"eval",
177 US"eval10",
178 US"expand",
179 US"h",
180 US"hash",
181 US"hex2b64",
182 US"l",
183 US"lc",
184 US"length",
185 US"mask",
186 US"md5",
187 US"nh",
188 US"nhash",
189 US"quote",
190 US"rfc2047",
9c57cbc0 191 US"rfc2047d",
059ec3d9
PH
192 US"rxquote",
193 US"s",
194 US"sha1",
195 US"stat",
196 US"str2b64",
197 US"strlen",
198 US"substr",
199 US"uc" };
200
201enum {
202 EOP_ADDRESS = sizeof(op_table_underscore)/sizeof(uschar *),
29f89cad 203 EOP_ADDRESSES,
059ec3d9
PH
204 EOP_BASE62,
205 EOP_BASE62D,
206 EOP_DOMAIN,
207 EOP_ESCAPE,
208 EOP_EVAL,
209 EOP_EVAL10,
210 EOP_EXPAND,
211 EOP_H,
212 EOP_HASH,
213 EOP_HEX2B64,
214 EOP_L,
215 EOP_LC,
216 EOP_LENGTH,
217 EOP_MASK,
218 EOP_MD5,
219 EOP_NH,
220 EOP_NHASH,
221 EOP_QUOTE,
222 EOP_RFC2047,
9c57cbc0 223 EOP_RFC2047D,
059ec3d9
PH
224 EOP_RXQUOTE,
225 EOP_S,
226 EOP_SHA1,
227 EOP_STAT,
228 EOP_STR2B64,
229 EOP_STRLEN,
230 EOP_SUBSTR,
231 EOP_UC };
232
233
234/* Table of condition names, and corresponding switch numbers. The names must
235be in alphabetical order. */
236
237static uschar *cond_table[] = {
238 US"<",
239 US"<=",
240 US"=",
241 US"==", /* Backward compatibility */
242 US">",
243 US">=",
244 US"and",
245 US"crypteq",
246 US"def",
247 US"eq",
248 US"eqi",
249 US"exists",
250 US"first_delivery",
0ce9abe6
PH
251 US"forall",
252 US"forany",
059ec3d9
PH
253 US"ge",
254 US"gei",
255 US"gt",
256 US"gti",
257 US"isip",
258 US"isip4",
259 US"isip6",
260 US"ldapauth",
261 US"le",
262 US"lei",
263 US"lt",
264 US"lti",
265 US"match",
266 US"match_address",
267 US"match_domain",
32d668a5 268 US"match_ip",
059ec3d9
PH
269 US"match_local_part",
270 US"or",
271 US"pam",
272 US"pwcheck",
273 US"queue_running",
274 US"radius",
275 US"saslauthd"
276};
277
278enum {
279 ECOND_NUM_L,
280 ECOND_NUM_LE,
281 ECOND_NUM_E,
282 ECOND_NUM_EE,
283 ECOND_NUM_G,
284 ECOND_NUM_GE,
285 ECOND_AND,
286 ECOND_CRYPTEQ,
287 ECOND_DEF,
288 ECOND_STR_EQ,
289 ECOND_STR_EQI,
290 ECOND_EXISTS,
291 ECOND_FIRST_DELIVERY,
0ce9abe6
PH
292 ECOND_FORALL,
293 ECOND_FORANY,
059ec3d9
PH
294 ECOND_STR_GE,
295 ECOND_STR_GEI,
296 ECOND_STR_GT,
297 ECOND_STR_GTI,
298 ECOND_ISIP,
299 ECOND_ISIP4,
300 ECOND_ISIP6,
301 ECOND_LDAPAUTH,
302 ECOND_STR_LE,
303 ECOND_STR_LEI,
304 ECOND_STR_LT,
305 ECOND_STR_LTI,
306 ECOND_MATCH,
307 ECOND_MATCH_ADDRESS,
308 ECOND_MATCH_DOMAIN,
32d668a5 309 ECOND_MATCH_IP,
059ec3d9
PH
310 ECOND_MATCH_LOCAL_PART,
311 ECOND_OR,
312 ECOND_PAM,
313 ECOND_PWCHECK,
314 ECOND_QUEUE_RUNNING,
315 ECOND_RADIUS,
316 ECOND_SASLAUTHD
317};
318
319
320/* Type for main variable table */
321
322typedef struct {
323 char *name;
324 int type;
325 void *value;
326} var_entry;
327
328/* Type for entries pointing to address/length pairs. Not currently
329in use. */
330
331typedef struct {
332 uschar **address;
333 int *length;
334} alblock;
335
336/* Types of table entry */
337
338enum {
339 vtype_int, /* value is address of int */
340 vtype_filter_int, /* ditto, but recognized only when filtering */
341 vtype_ino, /* value is address of ino_t (not always an int) */
342 vtype_uid, /* value is address of uid_t (not always an int) */
343 vtype_gid, /* value is address of gid_t (not always an int) */
344 vtype_stringptr, /* value is address of pointer to string */
345 vtype_msgbody, /* as stringptr, but read when first required */
346 vtype_msgbody_end, /* ditto, the end of the message */
ff75a1f7
PH
347 vtype_msgheaders, /* the message's headers, processed */
348 vtype_msgheaders_raw, /* the message's headers, unprocessed */
059ec3d9
PH
349 vtype_localpart, /* extract local part from string */
350 vtype_domain, /* extract domain from string */
351 vtype_recipients, /* extract recipients from recipients list */
0e20aff9
MH
352 /* (available only in system filters, ACLs, and */
353 /* local_scan()) */
059ec3d9
PH
354 vtype_todbsdin, /* value not used; generate BSD inbox tod */
355 vtype_tode, /* value not used; generate tod in epoch format */
356 vtype_todf, /* value not used; generate full tod */
357 vtype_todl, /* value not used; generate log tod */
358 vtype_todlf, /* value not used; generate log file datestamp tod */
359 vtype_todzone, /* value not used; generate time zone only */
360 vtype_todzulu, /* value not used; generate zulu tod */
361 vtype_reply, /* value not used; get reply from headers */
362 vtype_pid, /* value not used; result is pid */
363 vtype_host_lookup, /* value not used; get host name */
5cb8cbc6
PH
364 vtype_load_avg, /* value not used; result is int from os_getloadavg */
365 vtype_pspace, /* partition space; value is T/F for spool/log */
8e669ac1 366 vtype_pinodes /* partition inodes; value is T/F for spool/log */
fb2274d4
TK
367#ifdef EXPERIMENTAL_DOMAINKEYS
368 ,vtype_dk_verify /* Serve request out of DomainKeys verification structure */
84330b7b 369#endif
059ec3d9
PH
370 };
371
372/* This table must be kept in alphabetical order. */
373
374static var_entry var_table[] = {
38a0a95f
PH
375 /* WARNING: Do not invent variables whose names start acl_c or acl_m because
376 they will be confused with user-creatable ACL variables. */
059ec3d9
PH
377 { "acl_verify_message", vtype_stringptr, &acl_verify_message },
378 { "address_data", vtype_stringptr, &deliver_address_data },
379 { "address_file", vtype_stringptr, &address_file },
380 { "address_pipe", vtype_stringptr, &address_pipe },
381 { "authenticated_id", vtype_stringptr, &authenticated_id },
382 { "authenticated_sender",vtype_stringptr, &authenticated_sender },
383 { "authentication_failed",vtype_int, &authentication_failed },
8523533c
TK
384#ifdef EXPERIMENTAL_BRIGHTMAIL
385 { "bmi_alt_location", vtype_stringptr, &bmi_alt_location },
386 { "bmi_base64_tracker_verdict", vtype_stringptr, &bmi_base64_tracker_verdict },
387 { "bmi_base64_verdict", vtype_stringptr, &bmi_base64_verdict },
388 { "bmi_deliver", vtype_int, &bmi_deliver },
389#endif
059ec3d9
PH
390 { "body_linecount", vtype_int, &body_linecount },
391 { "body_zerocount", vtype_int, &body_zerocount },
392 { "bounce_recipient", vtype_stringptr, &bounce_recipient },
393 { "bounce_return_size_limit", vtype_int, &bounce_return_size_limit },
394 { "caller_gid", vtype_gid, &real_gid },
395 { "caller_uid", vtype_uid, &real_uid },
396 { "compile_date", vtype_stringptr, &version_date },
397 { "compile_number", vtype_stringptr, &version_cnumber },
e5a9dba6 398 { "csa_status", vtype_stringptr, &csa_status },
6a8f9482
TK
399#ifdef EXPERIMENTAL_DCC
400 { "dcc_header", vtype_stringptr, &dcc_header },
401 { "dcc_result", vtype_stringptr, &dcc_result },
402#endif
8523533c
TK
403#ifdef WITH_OLD_DEMIME
404 { "demime_errorlevel", vtype_int, &demime_errorlevel },
405 { "demime_reason", vtype_stringptr, &demime_reason },
fb2274d4
TK
406#endif
407#ifdef EXPERIMENTAL_DOMAINKEYS
408 { "dk_domain", vtype_stringptr, &dk_signing_domain },
409 { "dk_is_signed", vtype_dk_verify, NULL },
410 { "dk_result", vtype_dk_verify, NULL },
411 { "dk_selector", vtype_stringptr, &dk_signing_selector },
412 { "dk_sender", vtype_dk_verify, NULL },
413 { "dk_sender_domain", vtype_dk_verify, NULL },
414 { "dk_sender_local_part",vtype_dk_verify, NULL },
415 { "dk_sender_source", vtype_dk_verify, NULL },
416 { "dk_signsall", vtype_dk_verify, NULL },
417 { "dk_status", vtype_dk_verify, NULL },
418 { "dk_testing", vtype_dk_verify, NULL },
e08d09e5
TK
419#endif
420#ifdef EXPERIMENTAL_DKIM
421 { "dkim_domain", vtype_stringptr, &dkim_signing_domain },
422 { "dkim_selector", vtype_stringptr, &dkim_signing_selector },
8523533c 423#endif
059ec3d9 424 { "dnslist_domain", vtype_stringptr, &dnslist_domain },
93655c46 425 { "dnslist_matched", vtype_stringptr, &dnslist_matched },
059ec3d9
PH
426 { "dnslist_text", vtype_stringptr, &dnslist_text },
427 { "dnslist_value", vtype_stringptr, &dnslist_value },
428 { "domain", vtype_stringptr, &deliver_domain },
429 { "domain_data", vtype_stringptr, &deliver_domain_data },
430 { "exim_gid", vtype_gid, &exim_gid },
431 { "exim_path", vtype_stringptr, &exim_path },
432 { "exim_uid", vtype_uid, &exim_uid },
8523533c
TK
433#ifdef WITH_OLD_DEMIME
434 { "found_extension", vtype_stringptr, &found_extension },
8e669ac1 435#endif
059ec3d9
PH
436 { "home", vtype_stringptr, &deliver_home },
437 { "host", vtype_stringptr, &deliver_host },
438 { "host_address", vtype_stringptr, &deliver_host_address },
439 { "host_data", vtype_stringptr, &host_data },
b08b24c8 440 { "host_lookup_deferred",vtype_int, &host_lookup_deferred },
059ec3d9
PH
441 { "host_lookup_failed", vtype_int, &host_lookup_failed },
442 { "inode", vtype_ino, &deliver_inode },
443 { "interface_address", vtype_stringptr, &interface_address },
444 { "interface_port", vtype_int, &interface_port },
0ce9abe6 445 { "item", vtype_stringptr, &iterate_item },
059ec3d9
PH
446 #ifdef LOOKUP_LDAP
447 { "ldap_dn", vtype_stringptr, &eldap_dn },
448 #endif
449 { "load_average", vtype_load_avg, NULL },
450 { "local_part", vtype_stringptr, &deliver_localpart },
451 { "local_part_data", vtype_stringptr, &deliver_localpart_data },
452 { "local_part_prefix", vtype_stringptr, &deliver_localpart_prefix },
453 { "local_part_suffix", vtype_stringptr, &deliver_localpart_suffix },
454 { "local_scan_data", vtype_stringptr, &local_scan_data },
455 { "local_user_gid", vtype_gid, &local_user_gid },
456 { "local_user_uid", vtype_uid, &local_user_uid },
457 { "localhost_number", vtype_int, &host_number },
5cb8cbc6 458 { "log_inodes", vtype_pinodes, (void *)FALSE },
8e669ac1 459 { "log_space", vtype_pspace, (void *)FALSE },
059ec3d9 460 { "mailstore_basename", vtype_stringptr, &mailstore_basename },
8523533c
TK
461#ifdef WITH_CONTENT_SCAN
462 { "malware_name", vtype_stringptr, &malware_name },
463#endif
d677b2f2 464 { "max_received_linelength", vtype_int, &max_received_linelength },
059ec3d9
PH
465 { "message_age", vtype_int, &message_age },
466 { "message_body", vtype_msgbody, &message_body },
467 { "message_body_end", vtype_msgbody_end, &message_body_end },
468 { "message_body_size", vtype_int, &message_body_size },
1ab52c69 469 { "message_exim_id", vtype_stringptr, &message_id },
059ec3d9 470 { "message_headers", vtype_msgheaders, NULL },
ff75a1f7 471 { "message_headers_raw", vtype_msgheaders_raw, NULL },
059ec3d9 472 { "message_id", vtype_stringptr, &message_id },
2e0c1448 473 { "message_linecount", vtype_int, &message_linecount },
059ec3d9 474 { "message_size", vtype_int, &message_size },
8523533c
TK
475#ifdef WITH_CONTENT_SCAN
476 { "mime_anomaly_level", vtype_int, &mime_anomaly_level },
477 { "mime_anomaly_text", vtype_stringptr, &mime_anomaly_text },
478 { "mime_boundary", vtype_stringptr, &mime_boundary },
479 { "mime_charset", vtype_stringptr, &mime_charset },
480 { "mime_content_description", vtype_stringptr, &mime_content_description },
481 { "mime_content_disposition", vtype_stringptr, &mime_content_disposition },
482 { "mime_content_id", vtype_stringptr, &mime_content_id },
483 { "mime_content_size", vtype_int, &mime_content_size },
484 { "mime_content_transfer_encoding",vtype_stringptr, &mime_content_transfer_encoding },
485 { "mime_content_type", vtype_stringptr, &mime_content_type },
486 { "mime_decoded_filename", vtype_stringptr, &mime_decoded_filename },
487 { "mime_filename", vtype_stringptr, &mime_filename },
488 { "mime_is_coverletter", vtype_int, &mime_is_coverletter },
489 { "mime_is_multipart", vtype_int, &mime_is_multipart },
490 { "mime_is_rfc822", vtype_int, &mime_is_rfc822 },
491 { "mime_part_count", vtype_int, &mime_part_count },
492#endif
059ec3d9
PH
493 { "n0", vtype_filter_int, &filter_n[0] },
494 { "n1", vtype_filter_int, &filter_n[1] },
495 { "n2", vtype_filter_int, &filter_n[2] },
496 { "n3", vtype_filter_int, &filter_n[3] },
497 { "n4", vtype_filter_int, &filter_n[4] },
498 { "n5", vtype_filter_int, &filter_n[5] },
499 { "n6", vtype_filter_int, &filter_n[6] },
500 { "n7", vtype_filter_int, &filter_n[7] },
501 { "n8", vtype_filter_int, &filter_n[8] },
502 { "n9", vtype_filter_int, &filter_n[9] },
503 { "original_domain", vtype_stringptr, &deliver_domain_orig },
504 { "original_local_part", vtype_stringptr, &deliver_localpart_orig },
505 { "originator_gid", vtype_gid, &originator_gid },
506 { "originator_uid", vtype_uid, &originator_uid },
507 { "parent_domain", vtype_stringptr, &deliver_domain_parent },
508 { "parent_local_part", vtype_stringptr, &deliver_localpart_parent },
509 { "pid", vtype_pid, NULL },
510 { "primary_hostname", vtype_stringptr, &primary_hostname },
fffda43a
TK
511 { "prvscheck_address", vtype_stringptr, &prvscheck_address },
512 { "prvscheck_keynum", vtype_stringptr, &prvscheck_keynum },
513 { "prvscheck_result", vtype_stringptr, &prvscheck_result },
059ec3d9
PH
514 { "qualify_domain", vtype_stringptr, &qualify_domain_sender },
515 { "qualify_recipient", vtype_stringptr, &qualify_domain_recipient },
516 { "rcpt_count", vtype_int, &rcpt_count },
517 { "rcpt_defer_count", vtype_int, &rcpt_defer_count },
518 { "rcpt_fail_count", vtype_int, &rcpt_fail_count },
519 { "received_count", vtype_int, &received_count },
520 { "received_for", vtype_stringptr, &received_for },
194cc0e4
PH
521 { "received_ip_address", vtype_stringptr, &interface_address },
522 { "received_port", vtype_int, &interface_port },
059ec3d9 523 { "received_protocol", vtype_stringptr, &received_protocol },
7dbf77c9 524 { "received_time", vtype_int, &received_time },
059ec3d9 525 { "recipient_data", vtype_stringptr, &recipient_data },
8e669ac1 526 { "recipient_verify_failure",vtype_stringptr,&recipient_verify_failure },
059ec3d9
PH
527 { "recipients", vtype_recipients, NULL },
528 { "recipients_count", vtype_int, &recipients_count },
8523533c
TK
529#ifdef WITH_CONTENT_SCAN
530 { "regex_match_string", vtype_stringptr, &regex_match_string },
531#endif
059ec3d9
PH
532 { "reply_address", vtype_reply, NULL },
533 { "return_path", vtype_stringptr, &return_path },
534 { "return_size_limit", vtype_int, &bounce_return_size_limit },
535 { "runrc", vtype_int, &runrc },
536 { "self_hostname", vtype_stringptr, &self_hostname },
537 { "sender_address", vtype_stringptr, &sender_address },
2a3eea10 538 { "sender_address_data", vtype_stringptr, &sender_address_data },
059ec3d9
PH
539 { "sender_address_domain", vtype_domain, &sender_address },
540 { "sender_address_local_part", vtype_localpart, &sender_address },
541 { "sender_data", vtype_stringptr, &sender_data },
542 { "sender_fullhost", vtype_stringptr, &sender_fullhost },
543 { "sender_helo_name", vtype_stringptr, &sender_helo_name },
544 { "sender_host_address", vtype_stringptr, &sender_host_address },
545 { "sender_host_authenticated",vtype_stringptr, &sender_host_authenticated },
546 { "sender_host_name", vtype_host_lookup, NULL },
547 { "sender_host_port", vtype_int, &sender_host_port },
548 { "sender_ident", vtype_stringptr, &sender_ident },
870f6ba8
TF
549 { "sender_rate", vtype_stringptr, &sender_rate },
550 { "sender_rate_limit", vtype_stringptr, &sender_rate_limit },
551 { "sender_rate_period", vtype_stringptr, &sender_rate_period },
059ec3d9 552 { "sender_rcvhost", vtype_stringptr, &sender_rcvhost },
8e669ac1 553 { "sender_verify_failure",vtype_stringptr, &sender_verify_failure },
41c7c167
PH
554 { "sending_ip_address", vtype_stringptr, &sending_ip_address },
555 { "sending_port", vtype_int, &sending_port },
8e669ac1 556 { "smtp_active_hostname", vtype_stringptr, &smtp_active_hostname },
3ee512ff
PH
557 { "smtp_command", vtype_stringptr, &smtp_cmd_buffer },
558 { "smtp_command_argument", vtype_stringptr, &smtp_cmd_argument },
b01dd148 559 { "smtp_count_at_connection_start", vtype_int, &smtp_accept_count },
8f128379 560 { "smtp_notquit_reason", vtype_stringptr, &smtp_notquit_reason },
059ec3d9
PH
561 { "sn0", vtype_filter_int, &filter_sn[0] },
562 { "sn1", vtype_filter_int, &filter_sn[1] },
563 { "sn2", vtype_filter_int, &filter_sn[2] },
564 { "sn3", vtype_filter_int, &filter_sn[3] },
565 { "sn4", vtype_filter_int, &filter_sn[4] },
566 { "sn5", vtype_filter_int, &filter_sn[5] },
567 { "sn6", vtype_filter_int, &filter_sn[6] },
568 { "sn7", vtype_filter_int, &filter_sn[7] },
569 { "sn8", vtype_filter_int, &filter_sn[8] },
570 { "sn9", vtype_filter_int, &filter_sn[9] },
8523533c
TK
571#ifdef WITH_CONTENT_SCAN
572 { "spam_bar", vtype_stringptr, &spam_bar },
573 { "spam_report", vtype_stringptr, &spam_report },
574 { "spam_score", vtype_stringptr, &spam_score },
575 { "spam_score_int", vtype_stringptr, &spam_score_int },
576#endif
577#ifdef EXPERIMENTAL_SPF
65a7d8c3 578 { "spf_guess", vtype_stringptr, &spf_guess },
8523533c
TK
579 { "spf_header_comment", vtype_stringptr, &spf_header_comment },
580 { "spf_received", vtype_stringptr, &spf_received },
581 { "spf_result", vtype_stringptr, &spf_result },
582 { "spf_smtp_comment", vtype_stringptr, &spf_smtp_comment },
583#endif
059ec3d9 584 { "spool_directory", vtype_stringptr, &spool_directory },
5cb8cbc6 585 { "spool_inodes", vtype_pinodes, (void *)TRUE },
8e669ac1 586 { "spool_space", vtype_pspace, (void *)TRUE },
8523533c
TK
587#ifdef EXPERIMENTAL_SRS
588 { "srs_db_address", vtype_stringptr, &srs_db_address },
589 { "srs_db_key", vtype_stringptr, &srs_db_key },
590 { "srs_orig_recipient", vtype_stringptr, &srs_orig_recipient },
591 { "srs_orig_sender", vtype_stringptr, &srs_orig_sender },
592 { "srs_recipient", vtype_stringptr, &srs_recipient },
593 { "srs_status", vtype_stringptr, &srs_status },
594#endif
059ec3d9
PH
595 { "thisaddress", vtype_stringptr, &filter_thisaddress },
596 { "tls_certificate_verified", vtype_int, &tls_certificate_verified },
597 { "tls_cipher", vtype_stringptr, &tls_cipher },
598 { "tls_peerdn", vtype_stringptr, &tls_peerdn },
599 { "tod_bsdinbox", vtype_todbsdin, NULL },
600 { "tod_epoch", vtype_tode, NULL },
601 { "tod_full", vtype_todf, NULL },
602 { "tod_log", vtype_todl, NULL },
603 { "tod_logfile", vtype_todlf, NULL },
604 { "tod_zone", vtype_todzone, NULL },
605 { "tod_zulu", vtype_todzulu, NULL },
606 { "value", vtype_stringptr, &lookup_value },
607 { "version_number", vtype_stringptr, &version_string },
608 { "warn_message_delay", vtype_stringptr, &warnmsg_delay },
609 { "warn_message_recipient",vtype_stringptr, &warnmsg_recipients },
610 { "warn_message_recipients",vtype_stringptr,&warnmsg_recipients },
611 { "warnmsg_delay", vtype_stringptr, &warnmsg_delay },
612 { "warnmsg_recipient", vtype_stringptr, &warnmsg_recipients },
613 { "warnmsg_recipients", vtype_stringptr, &warnmsg_recipients }
614};
615
616static int var_table_size = sizeof(var_table)/sizeof(var_entry);
617static uschar var_buffer[256];
618static BOOL malformed_header;
619
620/* For textual hashes */
621
622static char *hashcodes = "abcdefghijklmnopqrtsuvwxyz"
623 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
624 "0123456789";
625
626enum { HMAC_MD5, HMAC_SHA1 };
627
628/* For numeric hashes */
629
630static unsigned int prime[] = {
631 2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
632 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
633 73, 79, 83, 89, 97, 101, 103, 107, 109, 113};
634
635/* For printing modes in symbolic form */
636
637static uschar *mtable_normal[] =
638 { US"---", US"--x", US"-w-", US"-wx", US"r--", US"r-x", US"rw-", US"rwx" };
639
640static uschar *mtable_setid[] =
641 { US"--S", US"--s", US"-wS", US"-ws", US"r-S", US"r-s", US"rwS", US"rws" };
642
643static uschar *mtable_sticky[] =
644 { US"--T", US"--t", US"-wT", US"-wt", US"r-T", US"r-t", US"rwT", US"rwt" };
645
646
647
648/*************************************************
649* Tables for UTF-8 support *
650*************************************************/
651
652/* Table of the number of extra characters, indexed by the first character
653masked with 0x3f. The highest number for a valid UTF-8 character is in fact
6540x3d. */
655
656static uschar utf8_table1[] = {
657 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
658 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
659 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
660 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 };
661
662/* These are the masks for the data bits in the first byte of a character,
663indexed by the number of additional bytes. */
664
665static int utf8_table2[] = { 0xff, 0x1f, 0x0f, 0x07, 0x03, 0x01};
666
667/* Get the next UTF-8 character, advancing the pointer. */
668
669#define GETUTF8INC(c, ptr) \
670 c = *ptr++; \
671 if ((c & 0xc0) == 0xc0) \
672 { \
673 int a = utf8_table1[c & 0x3f]; /* Number of additional bytes */ \
674 int s = 6*a; \
675 c = (c & utf8_table2[a]) << s; \
676 while (a-- > 0) \
677 { \
678 s -= 6; \
679 c |= (*ptr++ & 0x3f) << s; \
680 } \
681 }
682
683
684/*************************************************
685* Binary chop search on a table *
686*************************************************/
687
688/* This is used for matching expansion items and operators.
689
690Arguments:
691 name the name that is being sought
692 table the table to search
693 table_size the number of items in the table
694
695Returns: the offset in the table, or -1
696*/
697
698static int
699chop_match(uschar *name, uschar **table, int table_size)
700{
701uschar **bot = table;
702uschar **top = table + table_size;
703
704while (top > bot)
705 {
706 uschar **mid = bot + (top - bot)/2;
707 int c = Ustrcmp(name, *mid);
708 if (c == 0) return mid - table;
709 if (c > 0) bot = mid + 1; else top = mid;
710 }
711
712return -1;
713}
714
715
716
717/*************************************************
718* Check a condition string *
719*************************************************/
720
721/* This function is called to expand a string, and test the result for a "true"
722or "false" value. Failure of the expansion yields FALSE; logged unless it was a
723forced fail or lookup defer. All store used by the function can be released on
724exit.
725
726Arguments:
727 condition the condition string
728 m1 text to be incorporated in panic error
729 m2 ditto
730
731Returns: TRUE if condition is met, FALSE if not
732*/
733
734BOOL
735expand_check_condition(uschar *condition, uschar *m1, uschar *m2)
736{
737int rc;
738void *reset_point = store_get(0);
739uschar *ss = expand_string(condition);
740if (ss == NULL)
741 {
742 if (!expand_string_forcedfail && !search_find_defer)
743 log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand condition \"%s\" "
744 "for %s %s: %s", condition, m1, m2, expand_string_message);
745 return FALSE;
746 }
747rc = ss[0] != 0 && Ustrcmp(ss, "0") != 0 && strcmpic(ss, US"no") != 0 &&
748 strcmpic(ss, US"false") != 0;
749store_reset(reset_point);
750return rc;
751}
752
753
754
755/*************************************************
756* Pick out a name from a string *
757*************************************************/
758
759/* If the name is too long, it is silently truncated.
760
761Arguments:
762 name points to a buffer into which to put the name
763 max is the length of the buffer
764 s points to the first alphabetic character of the name
765 extras chars other than alphanumerics to permit
766
767Returns: pointer to the first character after the name
768
769Note: The test for *s != 0 in the while loop is necessary because
770Ustrchr() yields non-NULL if the character is zero (which is not something
771I expected). */
772
773static uschar *
774read_name(uschar *name, int max, uschar *s, uschar *extras)
775{
776int ptr = 0;
777while (*s != 0 && (isalnum(*s) || Ustrchr(extras, *s) != NULL))
778 {
779 if (ptr < max-1) name[ptr++] = *s;
780 s++;
781 }
782name[ptr] = 0;
783return s;
784}
785
786
787
788/*************************************************
789* Pick out the rest of a header name *
790*************************************************/
791
792/* A variable name starting $header_ (or just $h_ for those who like
793abbreviations) might not be the complete header name because headers can
794contain any printing characters in their names, except ':'. This function is
795called to read the rest of the name, chop h[eader]_ off the front, and put ':'
796on the end, if the name was terminated by white space.
797
798Arguments:
799 name points to a buffer in which the name read so far exists
800 max is the length of the buffer
801 s points to the first character after the name so far, i.e. the
802 first non-alphameric character after $header_xxxxx
803
804Returns: a pointer to the first character after the header name
805*/
806
807static uschar *
808read_header_name(uschar *name, int max, uschar *s)
809{
810int prelen = Ustrchr(name, '_') - name + 1;
811int ptr = Ustrlen(name) - prelen;
812if (ptr > 0) memmove(name, name+prelen, ptr);
813while (mac_isgraph(*s) && *s != ':')
814 {
815 if (ptr < max-1) name[ptr++] = *s;
816 s++;
817 }
818if (*s == ':') s++;
819name[ptr++] = ':';
820name[ptr] = 0;
821return s;
822}
823
824
825
826/*************************************************
827* Pick out a number from a string *
828*************************************************/
829
830/* Arguments:
831 n points to an integer into which to put the number
832 s points to the first digit of the number
833
834Returns: a pointer to the character after the last digit
835*/
836
837static uschar *
838read_number(int *n, uschar *s)
839{
840*n = 0;
841while (isdigit(*s)) *n = *n * 10 + (*s++ - '0');
842return s;
843}
844
845
846
847/*************************************************
848* Extract keyed subfield from a string *
849*************************************************/
850
851/* The yield is in dynamic store; NULL means that the key was not found.
852
853Arguments:
854 key points to the name of the key
855 s points to the string from which to extract the subfield
856
857Returns: NULL if the subfield was not found, or
858 a pointer to the subfield's data
859*/
860
861static uschar *
862expand_getkeyed(uschar *key, uschar *s)
863{
864int length = Ustrlen(key);
865while (isspace(*s)) s++;
866
867/* Loop to search for the key */
868
869while (*s != 0)
870 {
871 int dkeylength;
872 uschar *data;
873 uschar *dkey = s;
874
875 while (*s != 0 && *s != '=' && !isspace(*s)) s++;
876 dkeylength = s - dkey;
877 while (isspace(*s)) s++;
878 if (*s == '=') while (isspace((*(++s))));
879
880 data = string_dequote(&s);
881 if (length == dkeylength && strncmpic(key, dkey, length) == 0)
882 return data;
883
884 while (isspace(*s)) s++;
885 }
886
887return NULL;
888}
889
890
891
892
893/*************************************************
894* Extract numbered subfield from string *
895*************************************************/
896
897/* Extracts a numbered field from a string that is divided by tokens - for
898example a line from /etc/passwd is divided by colon characters. First field is
899numbered one. Negative arguments count from the right. Zero returns the whole
900string. Returns NULL if there are insufficient tokens in the string
901
902***WARNING***
903Modifies final argument - this is a dynamically generated string, so that's OK.
904
905Arguments:
906 field number of field to be extracted,
907 first field = 1, whole string = 0, last field = -1
908 separators characters that are used to break string into tokens
909 s points to the string from which to extract the subfield
910
911Returns: NULL if the field was not found,
912 a pointer to the field's data inside s (modified to add 0)
913*/
914
915static uschar *
916expand_gettokened (int field, uschar *separators, uschar *s)
917{
918int sep = 1;
919int count;
920uschar *ss = s;
921uschar *fieldtext = NULL;
922
923if (field == 0) return s;
924
925/* Break the line up into fields in place; for field > 0 we stop when we have
926done the number of fields we want. For field < 0 we continue till the end of
927the string, counting the number of fields. */
928
929count = (field > 0)? field : INT_MAX;
930
931while (count-- > 0)
932 {
933 size_t len;
934
935 /* Previous field was the last one in the string. For a positive field
936 number, this means there are not enough fields. For a negative field number,
937 check that there are enough, and scan back to find the one that is wanted. */
938
939 if (sep == 0)
940 {
941 if (field > 0 || (-field) > (INT_MAX - count - 1)) return NULL;
942 if ((-field) == (INT_MAX - count - 1)) return s;
943 while (field++ < 0)
944 {
945 ss--;
946 while (ss[-1] != 0) ss--;
947 }
948 fieldtext = ss;
949 break;
950 }
951
952 /* Previous field was not last in the string; save its start and put a
953 zero at its end. */
954
955 fieldtext = ss;
956 len = Ustrcspn(ss, separators);
957 sep = ss[len];
958 ss[len] = 0;
959 ss += len + 1;
960 }
961
962return fieldtext;
963}
964
965
966
967/*************************************************
968* Extract a substring from a string *
969*************************************************/
970
971/* Perform the ${substr or ${length expansion operations.
972
973Arguments:
974 subject the input string
975 value1 the offset from the start of the input string to the start of
976 the output string; if negative, count from the right.
977 value2 the length of the output string, or negative (-1) for unset
978 if value1 is positive, unset means "all after"
979 if value1 is negative, unset means "all before"
980 len set to the length of the returned string
981
982Returns: pointer to the output string, or NULL if there is an error
983*/
984
985static uschar *
986extract_substr(uschar *subject, int value1, int value2, int *len)
987{
988int sublen = Ustrlen(subject);
989
990if (value1 < 0) /* count from right */
991 {
992 value1 += sublen;
993
994 /* If the position is before the start, skip to the start, and adjust the
995 length. If the length ends up negative, the substring is null because nothing
996 can precede. This falls out naturally when the length is unset, meaning "all
997 to the left". */
998
999 if (value1 < 0)
1000 {
1001 value2 += value1;
1002 if (value2 < 0) value2 = 0;
1003 value1 = 0;
1004 }
1005
1006 /* Otherwise an unset length => characters before value1 */
1007
1008 else if (value2 < 0)
1009 {
1010 value2 = value1;
1011 value1 = 0;
1012 }
1013 }
1014
1015/* For a non-negative offset, if the starting position is past the end of the
1016string, the result will be the null string. Otherwise, an unset length means
1017"rest"; just set it to the maximum - it will be cut down below if necessary. */
1018
1019else
1020 {
1021 if (value1 > sublen)
1022 {
1023 value1 = sublen;
1024 value2 = 0;
1025 }
1026 else if (value2 < 0) value2 = sublen;
1027 }
1028
1029/* Cut the length down to the maximum possible for the offset value, and get
1030the required characters. */
1031
1032if (value1 + value2 > sublen) value2 = sublen - value1;
1033*len = value2;
1034return subject + value1;
1035}
1036
1037
1038
1039
1040/*************************************************
1041* Old-style hash of a string *
1042*************************************************/
1043
1044/* Perform the ${hash expansion operation.
1045
1046Arguments:
1047 subject the input string (an expanded substring)
1048 value1 the length of the output string; if greater or equal to the
1049 length of the input string, the input string is returned
1050 value2 the number of hash characters to use, or 26 if negative
1051 len set to the length of the returned string
1052
1053Returns: pointer to the output string, or NULL if there is an error
1054*/
1055
1056static uschar *
1057compute_hash(uschar *subject, int value1, int value2, int *len)
1058{
1059int sublen = Ustrlen(subject);
1060
1061if (value2 < 0) value2 = 26;
1062else if (value2 > Ustrlen(hashcodes))
1063 {
1064 expand_string_message =
1065 string_sprintf("hash count \"%d\" too big", value2);
1066 return NULL;
1067 }
1068
1069/* Calculate the hash text. We know it is shorter than the original string, so
1070can safely place it in subject[] (we know that subject is always itself an
1071expanded substring). */
1072
1073if (value1 < sublen)
1074 {
1075 int c;
1076 int i = 0;
1077 int j = value1;
1078 while ((c = (subject[j])) != 0)
1079 {
1080 int shift = (c + j++) & 7;
1081 subject[i] ^= (c << shift) | (c >> (8-shift));
1082 if (++i >= value1) i = 0;
1083 }
1084 for (i = 0; i < value1; i++)
1085 subject[i] = hashcodes[(subject[i]) % value2];
1086 }
1087else value1 = sublen;
1088
1089*len = value1;
1090return subject;
1091}
1092
1093
1094
1095
1096/*************************************************
1097* Numeric hash of a string *
1098*************************************************/
1099
1100/* Perform the ${nhash expansion operation. The first characters of the
1101string are treated as most important, and get the highest prime numbers.
1102
1103Arguments:
1104 subject the input string
1105 value1 the maximum value of the first part of the result
1106 value2 the maximum value of the second part of the result,
1107 or negative to produce only a one-part result
1108 len set to the length of the returned string
1109
1110Returns: pointer to the output string, or NULL if there is an error.
1111*/
1112
1113static uschar *
1114compute_nhash (uschar *subject, int value1, int value2, int *len)
1115{
1116uschar *s = subject;
1117int i = 0;
1118unsigned long int total = 0; /* no overflow */
1119
1120while (*s != 0)
1121 {
1122 if (i == 0) i = sizeof(prime)/sizeof(int) - 1;
1123 total += prime[i--] * (unsigned int)(*s++);
1124 }
1125
1126/* If value2 is unset, just compute one number */
1127
1128if (value2 < 0)
1129 {
1130 s = string_sprintf("%d", total % value1);
1131 }
1132
1133/* Otherwise do a div/mod hash */
1134
1135else
1136 {
1137 total = total % (value1 * value2);
1138 s = string_sprintf("%d/%d", total/value2, total % value2);
1139 }
1140
1141*len = Ustrlen(s);
1142return s;
1143}
1144
1145
1146
1147
1148
1149/*************************************************
1150* Find the value of a header or headers *
1151*************************************************/
1152
1153/* Multiple instances of the same header get concatenated, and this function
1154can also return a concatenation of all the header lines. When concatenating
1155specific headers that contain lists of addresses, a comma is inserted between
1156them. Otherwise we use a straight concatenation. Because some messages can have
1157pathologically large number of lines, there is a limit on the length that is
1158returned. Also, to avoid massive store use which would result from using
1159string_cat() as it copies and extends strings, we do a preliminary pass to find
1160out exactly how much store will be needed. On "normal" messages this will be
1161pretty trivial.
1162
1163Arguments:
1164 name the name of the header, without the leading $header_ or $h_,
1165 or NULL if a concatenation of all headers is required
1166 exists_only TRUE if called from a def: test; don't need to build a string;
1167 just return a string that is not "" and not "0" if the header
1168 exists
1169 newsize return the size of memory block that was obtained; may be NULL
1170 if exists_only is TRUE
1171 want_raw TRUE if called for $rh_ or $rheader_ variables; no processing,
ff75a1f7
PH
1172 other than concatenating, will be done on the header. Also used
1173 for $message_headers_raw.
059ec3d9
PH
1174 charset name of charset to translate MIME words to; used only if
1175 want_raw is false; if NULL, no translation is done (this is
1176 used for $bh_ and $bheader_)
1177
1178Returns: NULL if the header does not exist, else a pointer to a new
1179 store block
1180*/
1181
1182static uschar *
1183find_header(uschar *name, BOOL exists_only, int *newsize, BOOL want_raw,
1184 uschar *charset)
1185{
1186BOOL found = name == NULL;
1187int comma = 0;
1188int len = found? 0 : Ustrlen(name);
1189int i;
1190uschar *yield = NULL;
1191uschar *ptr = NULL;
1192
1193/* Loop for two passes - saves code repetition */
1194
1195for (i = 0; i < 2; i++)
1196 {
1197 int size = 0;
1198 header_line *h;
1199
1200 for (h = header_list; size < header_insert_maxlen && h != NULL; h = h->next)
1201 {
1202 if (h->type != htype_old && h->text != NULL) /* NULL => Received: placeholder */
1203 {
1204 if (name == NULL || (len <= h->slen && strncmpic(name, h->text, len) == 0))
1205 {
1206 int ilen;
1207 uschar *t;
1208
1209 if (exists_only) return US"1"; /* don't need actual string */
1210 found = TRUE;
1211 t = h->text + len; /* text to insert */
1212 if (!want_raw) /* unless wanted raw, */
1213 while (isspace(*t)) t++; /* remove leading white space */
1214 ilen = h->slen - (t - h->text); /* length to insert */
1215
fd700877
PH
1216 /* Unless wanted raw, remove trailing whitespace, including the
1217 newline. */
1218
1219 if (!want_raw)
1220 while (ilen > 0 && isspace(t[ilen-1])) ilen--;
1221
059ec3d9
PH
1222 /* Set comma = 1 if handling a single header and it's one of those
1223 that contains an address list, except when asked for raw headers. Only
1224 need to do this once. */
1225
1226 if (!want_raw && name != NULL && comma == 0 &&
1227 Ustrchr("BCFRST", h->type) != NULL)
1228 comma = 1;
1229
1230 /* First pass - compute total store needed; second pass - compute
1231 total store used, including this header. */
1232
fd700877 1233 size += ilen + comma + 1; /* +1 for the newline */
059ec3d9
PH
1234
1235 /* Second pass - concatentate the data, up to a maximum. Note that
1236 the loop stops when size hits the limit. */
1237
1238 if (i != 0)
1239 {
1240 if (size > header_insert_maxlen)
1241 {
fd700877 1242 ilen -= size - header_insert_maxlen - 1;
059ec3d9
PH
1243 comma = 0;
1244 }
1245 Ustrncpy(ptr, t, ilen);
1246 ptr += ilen;
fd700877
PH
1247
1248 /* For a non-raw header, put in the comma if needed, then add
3168332a
PH
1249 back the newline we removed above, provided there was some text in
1250 the header. */
fd700877 1251
3168332a 1252 if (!want_raw && ilen > 0)
059ec3d9 1253 {
3168332a 1254 if (comma != 0) *ptr++ = ',';
059ec3d9
PH
1255 *ptr++ = '\n';
1256 }
1257 }
1258 }
1259 }
1260 }
1261
fd700877
PH
1262 /* At end of first pass, return NULL if no header found. Then truncate size
1263 if necessary, and get the buffer to hold the data, returning the buffer size.
1264 */
059ec3d9
PH
1265
1266 if (i == 0)
1267 {
1268 if (!found) return NULL;
1269 if (size > header_insert_maxlen) size = header_insert_maxlen;
1270 *newsize = size + 1;
1271 ptr = yield = store_get(*newsize);
1272 }
1273 }
1274
059ec3d9
PH
1275/* That's all we do for raw header expansion. */
1276
1277if (want_raw)
1278 {
1279 *ptr = 0;
1280 }
1281
fd700877
PH
1282/* Otherwise, remove a final newline and a redundant added comma. Then we do
1283RFC 2047 decoding, translating the charset if requested. The rfc2047_decode2()
059ec3d9
PH
1284function can return an error with decoded data if the charset translation
1285fails. If decoding fails, it returns NULL. */
1286
1287else
1288 {
1289 uschar *decoded, *error;
3168332a 1290 if (ptr > yield && ptr[-1] == '\n') ptr--;
fd700877 1291 if (ptr > yield && comma != 0 && ptr[-1] == ',') ptr--;
059ec3d9 1292 *ptr = 0;
a0d6ba8a
PH
1293 decoded = rfc2047_decode2(yield, check_rfc2047_length, charset, '?', NULL,
1294 newsize, &error);
059ec3d9
PH
1295 if (error != NULL)
1296 {
1297 DEBUG(D_any) debug_printf("*** error in RFC 2047 decoding: %s\n"
1298 " input was: %s\n", error, yield);
1299 }
1300 if (decoded != NULL) yield = decoded;
1301 }
1302
1303return yield;
1304}
1305
1306
1307
1308
1309/*************************************************
1310* Find value of a variable *
1311*************************************************/
1312
1313/* The table of variables is kept in alphabetic order, so we can search it
1314using a binary chop. The "choplen" variable is nothing to do with the binary
1315chop.
1316
1317Arguments:
1318 name the name of the variable being sought
1319 exists_only TRUE if this is a def: test; passed on to find_header()
1320 skipping TRUE => skip any processing evaluation; this is not the same as
1321 exists_only because def: may test for values that are first
1322 evaluated here
1323 newsize pointer to an int which is initially zero; if the answer is in
1324 a new memory buffer, *newsize is set to its size
1325
1326Returns: NULL if the variable does not exist, or
1327 a pointer to the variable's contents, or
1328 something non-NULL if exists_only is TRUE
1329*/
1330
1331static uschar *
1332find_variable(uschar *name, BOOL exists_only, BOOL skipping, int *newsize)
1333{
1334int first = 0;
1335int last = var_table_size;
1336
38a0a95f
PH
1337/* Handle ACL variables, whose names are of the form acl_cxxx or acl_mxxx.
1338Originally, xxx had to be a number in the range 0-9 (later 0-19), but from
1339release 4.64 onwards arbitrary names are permitted, as long as the first 5
641cb756
PH
1340characters are acl_c or acl_m and the sixth is either a digit or an underscore
1341(this gave backwards compatibility at the changeover). There may be built-in
1342variables whose names start acl_ but they should never start in this way. This
1343slightly messy specification is a consequence of the history, needless to say.
47ca6d6c 1344
38a0a95f
PH
1345If an ACL variable does not exist, treat it as empty, unless strict_acl_vars is
1346set, in which case give an error. */
47ca6d6c 1347
641cb756
PH
1348if ((Ustrncmp(name, "acl_c", 5) == 0 || Ustrncmp(name, "acl_m", 5) == 0) &&
1349 !isalpha(name[5]))
38a0a95f
PH
1350 {
1351 tree_node *node =
1352 tree_search((name[4] == 'c')? acl_var_c : acl_var_m, name + 4);
1353 return (node == NULL)? (strict_acl_vars? NULL : US"") : node->data.ptr;
47ca6d6c
PH
1354 }
1355
38a0a95f 1356/* Handle $auth<n> variables. */
f78eb7c6
PH
1357
1358if (Ustrncmp(name, "auth", 4) == 0)
1359 {
1360 uschar *endptr;
1361 int n = Ustrtoul(name + 4, &endptr, 10);
1362 if (*endptr == 0 && n != 0 && n <= AUTH_VARS)
1363 return (auth_vars[n-1] == NULL)? US"" : auth_vars[n-1];
1364 }
1365
47ca6d6c
PH
1366/* For all other variables, search the table */
1367
059ec3d9
PH
1368while (last > first)
1369 {
1370 uschar *s, *domain;
1371 uschar **ss;
1372 int middle = (first + last)/2;
1373 int c = Ustrcmp(name, var_table[middle].name);
1374
1375 if (c > 0) { first = middle + 1; continue; }
1376 if (c < 0) { last = middle; continue; }
1377
1378 /* Found an existing variable. If in skipping state, the value isn't needed,
47ca6d6c 1379 and we want to avoid processing (such as looking up the host name). */
059ec3d9
PH
1380
1381 if (skipping) return US"";
1382
1383 switch (var_table[middle].type)
1384 {
fb2274d4
TK
1385#ifdef EXPERIMENTAL_DOMAINKEYS
1386
1387 case vtype_dk_verify:
cacfbf29 1388 if (dk_verify_block == NULL) return US"";
fb2274d4
TK
1389 s = NULL;
1390 if (Ustrcmp(var_table[middle].name, "dk_result") == 0)
1391 s = dk_verify_block->result_string;
1392 if (Ustrcmp(var_table[middle].name, "dk_sender") == 0)
1393 s = dk_verify_block->address;
1394 if (Ustrcmp(var_table[middle].name, "dk_sender_domain") == 0)
1395 s = dk_verify_block->domain;
1396 if (Ustrcmp(var_table[middle].name, "dk_sender_local_part") == 0)
1397 s = dk_verify_block->local_part;
84330b7b 1398
fb2274d4
TK
1399 if (Ustrcmp(var_table[middle].name, "dk_sender_source") == 0)
1400 switch(dk_verify_block->address_source) {
a8d97c8a
PH
1401 case DK_EXIM_ADDRESS_NONE: s = US"0"; break;
1402 case DK_EXIM_ADDRESS_FROM_FROM: s = US"from"; break;
1403 case DK_EXIM_ADDRESS_FROM_SENDER: s = US"sender"; break;
fb2274d4
TK
1404 }
1405
1406 if (Ustrcmp(var_table[middle].name, "dk_status") == 0)
1407 switch(dk_verify_block->result) {
a8d97c8a
PH
1408 case DK_EXIM_RESULT_ERR: s = US"error"; break;
1409 case DK_EXIM_RESULT_BAD_FORMAT: s = US"bad format"; break;
1410 case DK_EXIM_RESULT_NO_KEY: s = US"no key"; break;
1411 case DK_EXIM_RESULT_NO_SIGNATURE: s = US"no signature"; break;
1412 case DK_EXIM_RESULT_REVOKED: s = US"revoked"; break;
1413 case DK_EXIM_RESULT_NON_PARTICIPANT: s = US"non-participant"; break;
1414 case DK_EXIM_RESULT_GOOD: s = US"good"; break;
1415 case DK_EXIM_RESULT_BAD: s = US"bad"; break;
fb2274d4 1416 }
84330b7b 1417
fb2274d4 1418 if (Ustrcmp(var_table[middle].name, "dk_signsall") == 0)
a8d97c8a 1419 s = (dk_verify_block->signsall)? US"1" : US"0";
84330b7b 1420
fb2274d4 1421 if (Ustrcmp(var_table[middle].name, "dk_testing") == 0)
a8d97c8a 1422 s = (dk_verify_block->testing)? US"1" : US"0";
84330b7b 1423
fb2274d4 1424 if (Ustrcmp(var_table[middle].name, "dk_is_signed") == 0)
a8d97c8a 1425 s = (dk_verify_block->is_signed)? US"1" : US"0";
84330b7b 1426
fb2274d4
TK
1427 return (s == NULL)? US"" : s;
1428#endif
1429
9a26b6b2
PH
1430 case vtype_filter_int:
1431 if (!filter_running) return NULL;
1432 /* Fall through */
1433 /* VVVVVVVVVVVV */
059ec3d9
PH
1434 case vtype_int:
1435 sprintf(CS var_buffer, "%d", *(int *)(var_table[middle].value)); /* Integer */
1436 return var_buffer;
1437
1438 case vtype_ino:
1439 sprintf(CS var_buffer, "%ld", (long int)(*(ino_t *)(var_table[middle].value))); /* Inode */
1440 return var_buffer;
1441
1442 case vtype_gid:
1443 sprintf(CS var_buffer, "%ld", (long int)(*(gid_t *)(var_table[middle].value))); /* gid */
1444 return var_buffer;
1445
1446 case vtype_uid:
1447 sprintf(CS var_buffer, "%ld", (long int)(*(uid_t *)(var_table[middle].value))); /* uid */
1448 return var_buffer;
1449
1450 case vtype_stringptr: /* Pointer to string */
1451 s = *((uschar **)(var_table[middle].value));
1452 return (s == NULL)? US"" : s;
1453
1454 case vtype_pid:
1455 sprintf(CS var_buffer, "%d", (int)getpid()); /* pid */
1456 return var_buffer;
1457
1458 case vtype_load_avg:
8669f003 1459 sprintf(CS var_buffer, "%d", OS_GETLOADAVG()); /* load_average */
059ec3d9
PH
1460 return var_buffer;
1461
1462 case vtype_host_lookup: /* Lookup if not done so */
1463 if (sender_host_name == NULL && sender_host_address != NULL &&
1464 !host_lookup_failed && host_name_lookup() == OK)
1465 host_build_sender_fullhost();
1466 return (sender_host_name == NULL)? US"" : sender_host_name;
1467
1468 case vtype_localpart: /* Get local part from address */
1469 s = *((uschar **)(var_table[middle].value));
1470 if (s == NULL) return US"";
1471 domain = Ustrrchr(s, '@');
1472 if (domain == NULL) return s;
1473 if (domain - s > sizeof(var_buffer) - 1)
1474 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "local part longer than %d in "
1475 "string expansion", sizeof(var_buffer));
1476 Ustrncpy(var_buffer, s, domain - s);
1477 var_buffer[domain - s] = 0;
1478 return var_buffer;
1479
1480 case vtype_domain: /* Get domain from address */
1481 s = *((uschar **)(var_table[middle].value));
1482 if (s == NULL) return US"";
1483 domain = Ustrrchr(s, '@');
1484 return (domain == NULL)? US"" : domain + 1;
1485
1486 case vtype_msgheaders:
1487 return find_header(NULL, exists_only, newsize, FALSE, NULL);
1488
ff75a1f7
PH
1489 case vtype_msgheaders_raw:
1490 return find_header(NULL, exists_only, newsize, TRUE, NULL);
1491
059ec3d9
PH
1492 case vtype_msgbody: /* Pointer to msgbody string */
1493 case vtype_msgbody_end: /* Ditto, the end of the msg */
1494 ss = (uschar **)(var_table[middle].value);
1495 if (*ss == NULL && deliver_datafile >= 0) /* Read body when needed */
1496 {
1497 uschar *body;
0d7eb84a 1498 off_t start_offset = SPOOL_DATA_START_OFFSET;
059ec3d9
PH
1499 int len = message_body_visible;
1500 if (len > message_size) len = message_size;
1501 *ss = body = store_malloc(len+1);
1502 body[0] = 0;
1503 if (var_table[middle].type == vtype_msgbody_end)
1504 {
1505 struct stat statbuf;
1506 if (fstat(deliver_datafile, &statbuf) == 0)
1507 {
1508 start_offset = statbuf.st_size - len;
1509 if (start_offset < SPOOL_DATA_START_OFFSET)
1510 start_offset = SPOOL_DATA_START_OFFSET;
1511 }
1512 }
1513 lseek(deliver_datafile, start_offset, SEEK_SET);
1514 len = read(deliver_datafile, body, len);
1515 if (len > 0)
1516 {
1517 body[len] = 0;
ddea74fa 1518 if (message_body_newlines) /* Separate loops for efficiency */
059ec3d9 1519 {
ddea74fa
PH
1520 while (len > 0)
1521 { if (body[--len] == 0) body[len] = ' '; }
1522 }
1523 else
1524 {
1525 while (len > 0)
1526 { if (body[--len] == '\n' || body[len] == 0) body[len] = ' '; }
059ec3d9
PH
1527 }
1528 }
1529 }
1530 return (*ss == NULL)? US"" : *ss;
1531
1532 case vtype_todbsdin: /* BSD inbox time of day */
1533 return tod_stamp(tod_bsdin);
1534
1535 case vtype_tode: /* Unix epoch time of day */
1536 return tod_stamp(tod_epoch);
1537
1538 case vtype_todf: /* Full time of day */
1539 return tod_stamp(tod_full);
1540
1541 case vtype_todl: /* Log format time of day */
1542 return tod_stamp(tod_log_bare); /* (without timezone) */
1543
1544 case vtype_todzone: /* Time zone offset only */
1545 return tod_stamp(tod_zone);
1546
1547 case vtype_todzulu: /* Zulu time */
1548 return tod_stamp(tod_zulu);
1549
1550 case vtype_todlf: /* Log file datestamp tod */
1551 return tod_stamp(tod_log_datestamp);
1552
1553 case vtype_reply: /* Get reply address */
c8ea1597 1554 s = find_header(US"reply-to:", exists_only, newsize, TRUE,
059ec3d9 1555 headers_charset);
6979240a 1556 if (s != NULL) while (isspace(*s)) s++;
059ec3d9 1557 if (s == NULL || *s == 0)
41a13e0a
PH
1558 {
1559 *newsize = 0; /* For the *s==0 case */
c8ea1597
PH
1560 s = find_header(US"from:", exists_only, newsize, TRUE, headers_charset);
1561 }
1562 if (s != NULL)
1563 {
1564 uschar *t;
1565 while (isspace(*s)) s++;
1566 for (t = s; *t != 0; t++) if (*t == '\n') *t = ' ';
6979240a
PH
1567 while (t > s && isspace(t[-1])) t--;
1568 *t = 0;
41a13e0a 1569 }
059ec3d9
PH
1570 return (s == NULL)? US"" : s;
1571
1572 /* A recipients list is available only during system message filtering,
1573 during ACL processing after DATA, and while expanding pipe commands
1574 generated from a system filter, but not elsewhere. */
1575
1576 case vtype_recipients:
1577 if (!enable_dollar_recipients) return NULL; else
1578 {
1579 int size = 128;
1580 int ptr = 0;
1581 int i;
1582 s = store_get(size);
1583 for (i = 0; i < recipients_count; i++)
1584 {
1585 if (i != 0) s = string_cat(s, &size, &ptr, US", ", 2);
1586 s = string_cat(s, &size, &ptr, recipients_list[i].address,
1587 Ustrlen(recipients_list[i].address));
1588 }
1589 s[ptr] = 0; /* string_cat() leaves room */
1590 }
1591 return s;
8e669ac1 1592
5cb8cbc6
PH
1593 case vtype_pspace:
1594 {
1595 int inodes;
8e669ac1
PH
1596 sprintf(CS var_buffer, "%d",
1597 receive_statvfs(var_table[middle].value == (void *)TRUE, &inodes));
5cb8cbc6
PH
1598 }
1599 return var_buffer;
8e669ac1 1600
5cb8cbc6
PH
1601 case vtype_pinodes:
1602 {
1603 int inodes;
8e669ac1 1604 (void) receive_statvfs(var_table[middle].value == (void *)TRUE, &inodes);
5cb8cbc6
PH
1605 sprintf(CS var_buffer, "%d", inodes);
1606 }
1607 return var_buffer;
059ec3d9
PH
1608 }
1609 }
1610
1611return NULL; /* Unknown variable name */
1612}
1613
1614
1615
1616
1617/*************************************************
1618* Read and expand substrings *
1619*************************************************/
1620
1621/* This function is called to read and expand argument substrings for various
1622expansion items. Some have a minimum requirement that is less than the maximum;
1623in these cases, the first non-present one is set to NULL.
1624
1625Arguments:
1626 sub points to vector of pointers to set
1627 n maximum number of substrings
1628 m minimum required
1629 sptr points to current string pointer
1630 skipping the skipping flag
1631 check_end if TRUE, check for final '}'
1632 name name of item, for error message
1633
1634Returns: 0 OK; string pointer updated
1635 1 curly bracketing error (too few arguments)
1636 2 too many arguments (only if check_end is set); message set
1637 3 other error (expansion failure)
1638*/
1639
1640static int
1641read_subs(uschar **sub, int n, int m, uschar **sptr, BOOL skipping,
1642 BOOL check_end, uschar *name)
1643{
1644int i;
1645uschar *s = *sptr;
1646
1647while (isspace(*s)) s++;
1648for (i = 0; i < n; i++)
1649 {
1650 if (*s != '{')
1651 {
1652 if (i < m) return 1;
1653 sub[i] = NULL;
1654 break;
1655 }
1656 sub[i] = expand_string_internal(s+1, TRUE, &s, skipping);
1657 if (sub[i] == NULL) return 3;
1658 if (*s++ != '}') return 1;
1659 while (isspace(*s)) s++;
1660 }
1661if (check_end && *s++ != '}')
1662 {
1663 if (s[-1] == '{')
1664 {
1665 expand_string_message = string_sprintf("Too many arguments for \"%s\" "
1666 "(max is %d)", name, n);
1667 return 2;
1668 }
1669 return 1;
1670 }
1671
1672*sptr = s;
1673return 0;
1674}
1675
1676
1677
1678
641cb756
PH
1679/*************************************************
1680* Elaborate message for bad variable *
1681*************************************************/
1682
1683/* For the "unknown variable" message, take a look at the variable's name, and
1684give additional information about possible ACL variables. The extra information
1685is added on to expand_string_message.
1686
1687Argument: the name of the variable
1688Returns: nothing
1689*/
1690
1691static void
1692check_variable_error_message(uschar *name)
1693{
1694if (Ustrncmp(name, "acl_", 4) == 0)
1695 expand_string_message = string_sprintf("%s (%s)", expand_string_message,
1696 (name[4] == 'c' || name[4] == 'm')?
1697 (isalpha(name[5])?
1698 US"6th character of a user-defined ACL variable must be a digit or underscore" :
1699 US"strict_acl_vars is set" /* Syntax is OK, it has to be this */
1700 ) :
1701 US"user-defined ACL variables must start acl_c or acl_m");
1702}
1703
1704
1705
059ec3d9
PH
1706/*************************************************
1707* Read and evaluate a condition *
1708*************************************************/
1709
1710/*
1711Arguments:
1712 s points to the start of the condition text
1713 yield points to a BOOL to hold the result of the condition test;
1714 if NULL, we are just reading through a condition that is
1715 part of an "or" combination to check syntax, or in a state
1716 where the answer isn't required
1717
1718Returns: a pointer to the first character after the condition, or
1719 NULL after an error
1720*/
1721
1722static uschar *
1723eval_condition(uschar *s, BOOL *yield)
1724{
1725BOOL testfor = TRUE;
1726BOOL tempcond, combined_cond;
1727BOOL *subcondptr;
1728int i, rc, cond_type, roffset;
1729int num[2];
1730struct stat statbuf;
1731uschar name[256];
1732uschar *sub[4];
1733
1734const pcre *re;
1735const uschar *rerror;
1736
1737for (;;)
1738 {
1739 while (isspace(*s)) s++;
1740 if (*s == '!') { testfor = !testfor; s++; } else break;
1741 }
1742
1743/* Numeric comparisons are symbolic */
1744
1745if (*s == '=' || *s == '>' || *s == '<')
1746 {
1747 int p = 0;
1748 name[p++] = *s++;
1749 if (*s == '=')
1750 {
1751 name[p++] = '=';
1752 s++;
1753 }
1754 name[p] = 0;
1755 }
1756
1757/* All other conditions are named */
1758
1759else s = read_name(name, 256, s, US"_");
1760
1761/* If we haven't read a name, it means some non-alpha character is first. */
1762
1763if (name[0] == 0)
1764 {
1765 expand_string_message = string_sprintf("condition name expected, "
1766 "but found \"%.16s\"", s);
1767 return NULL;
1768 }
1769
1770/* Find which condition we are dealing with, and switch on it */
1771
1772cond_type = chop_match(name, cond_table, sizeof(cond_table)/sizeof(uschar *));
1773switch(cond_type)
1774 {
9b4768fa
PH
1775 /* def: tests for a non-empty variable, or for the existence of a header. If
1776 yield == NULL we are in a skipping state, and don't care about the answer. */
059ec3d9
PH
1777
1778 case ECOND_DEF:
1779 if (*s != ':')
1780 {
1781 expand_string_message = US"\":\" expected after \"def\"";
1782 return NULL;
1783 }
1784
1785 s = read_name(name, 256, s+1, US"_");
1786
0d85fa3f
PH
1787 /* Test for a header's existence. If the name contains a closing brace
1788 character, this may be a user error where the terminating colon has been
1789 omitted. Set a flag to adjust a subsequent error message in this case. */
059ec3d9
PH
1790
1791 if (Ustrncmp(name, "h_", 2) == 0 ||
1792 Ustrncmp(name, "rh_", 3) == 0 ||
1793 Ustrncmp(name, "bh_", 3) == 0 ||
1794 Ustrncmp(name, "header_", 7) == 0 ||
1795 Ustrncmp(name, "rheader_", 8) == 0 ||
1796 Ustrncmp(name, "bheader_", 8) == 0)
1797 {
1798 s = read_header_name(name, 256, s);
0d85fa3f 1799 if (Ustrchr(name, '}') != NULL) malformed_header = TRUE;
059ec3d9
PH
1800 if (yield != NULL) *yield =
1801 (find_header(name, TRUE, NULL, FALSE, NULL) != NULL) == testfor;
1802 }
1803
9b4768fa
PH
1804 /* Test for a variable's having a non-empty value. A non-existent variable
1805 causes an expansion failure. */
059ec3d9
PH
1806
1807 else
1808 {
1809 uschar *value = find_variable(name, TRUE, yield == NULL, NULL);
1810 if (value == NULL)
1811 {
1812 expand_string_message = (name[0] == 0)?
1813 string_sprintf("variable name omitted after \"def:\"") :
1814 string_sprintf("unknown variable \"%s\" after \"def:\"", name);
641cb756 1815 check_variable_error_message(name);
059ec3d9
PH
1816 return NULL;
1817 }
9b4768fa 1818 if (yield != NULL) *yield = (value[0] != 0) == testfor;
059ec3d9
PH
1819 }
1820
1821 return s;
1822
1823
1824 /* first_delivery tests for first delivery attempt */
1825
1826 case ECOND_FIRST_DELIVERY:
1827 if (yield != NULL) *yield = deliver_firsttime == testfor;
1828 return s;
1829
1830
1831 /* queue_running tests for any process started by a queue runner */
1832
1833 case ECOND_QUEUE_RUNNING:
1834 if (yield != NULL) *yield = (queue_run_pid != (pid_t)0) == testfor;
1835 return s;
1836
1837
1838 /* exists: tests for file existence
1839 isip: tests for any IP address
1840 isip4: tests for an IPv4 address
1841 isip6: tests for an IPv6 address
1842 pam: does PAM authentication
1843 radius: does RADIUS authentication
1844 ldapauth: does LDAP authentication
1845 pwcheck: does Cyrus SASL pwcheck authentication
1846 */
1847
1848 case ECOND_EXISTS:
1849 case ECOND_ISIP:
1850 case ECOND_ISIP4:
1851 case ECOND_ISIP6:
1852 case ECOND_PAM:
1853 case ECOND_RADIUS:
1854 case ECOND_LDAPAUTH:
1855 case ECOND_PWCHECK:
1856
1857 while (isspace(*s)) s++;
1858 if (*s != '{') goto COND_FAILED_CURLY_START;
1859
1860 sub[0] = expand_string_internal(s+1, TRUE, &s, yield == NULL);
1861 if (sub[0] == NULL) return NULL;
1862 if (*s++ != '}') goto COND_FAILED_CURLY_END;
1863
1864 if (yield == NULL) return s; /* No need to run the test if skipping */
1865
1866 switch(cond_type)
1867 {
1868 case ECOND_EXISTS:
1869 if ((expand_forbid & RDO_EXISTS) != 0)
1870 {
1871 expand_string_message = US"File existence tests are not permitted";
1872 return NULL;
1873 }
1874 *yield = (Ustat(sub[0], &statbuf) == 0) == testfor;
1875 break;
1876
1877 case ECOND_ISIP:
1878 case ECOND_ISIP4:
1879 case ECOND_ISIP6:
1880 rc = string_is_ip_address(sub[0], NULL);
7e66e54d 1881 *yield = ((cond_type == ECOND_ISIP)? (rc != 0) :
059ec3d9
PH
1882 (cond_type == ECOND_ISIP4)? (rc == 4) : (rc == 6)) == testfor;
1883 break;
1884
1885 /* Various authentication tests - all optionally compiled */
1886
1887 case ECOND_PAM:
1888 #ifdef SUPPORT_PAM
1889 rc = auth_call_pam(sub[0], &expand_string_message);
1890 goto END_AUTH;
1891 #else
1892 goto COND_FAILED_NOT_COMPILED;
1893 #endif /* SUPPORT_PAM */
1894
1895 case ECOND_RADIUS:
1896 #ifdef RADIUS_CONFIG_FILE
1897 rc = auth_call_radius(sub[0], &expand_string_message);
1898 goto END_AUTH;
1899 #else
1900 goto COND_FAILED_NOT_COMPILED;
1901 #endif /* RADIUS_CONFIG_FILE */
1902
1903 case ECOND_LDAPAUTH:
1904 #ifdef LOOKUP_LDAP
1905 {
1906 /* Just to keep the interface the same */
1907 BOOL do_cache;
1908 int old_pool = store_pool;
1909 store_pool = POOL_SEARCH;
1910 rc = eldapauth_find((void *)(-1), NULL, sub[0], Ustrlen(sub[0]), NULL,
1911 &expand_string_message, &do_cache);
1912 store_pool = old_pool;
1913 }
1914 goto END_AUTH;
1915 #else
1916 goto COND_FAILED_NOT_COMPILED;
1917 #endif /* LOOKUP_LDAP */
1918
1919 case ECOND_PWCHECK:
1920 #ifdef CYRUS_PWCHECK_SOCKET
1921 rc = auth_call_pwcheck(sub[0], &expand_string_message);
1922 goto END_AUTH;
1923 #else
1924 goto COND_FAILED_NOT_COMPILED;
1925 #endif /* CYRUS_PWCHECK_SOCKET */
1926
1927 #if defined(SUPPORT_PAM) || defined(RADIUS_CONFIG_FILE) || \
1928 defined(LOOKUP_LDAP) || defined(CYRUS_PWCHECK_SOCKET)
1929 END_AUTH:
1930 if (rc == ERROR || rc == DEFER) return NULL;
1931 *yield = (rc == OK) == testfor;
1932 #endif
1933 }
1934 return s;
1935
1936
1937 /* saslauthd: does Cyrus saslauthd authentication. Four parameters are used:
1938
1939 ${if saslauthd {{username}{password}{service}{realm}} {yes}[no}}
1940
1941 However, the last two are optional. That is why the whole set is enclosed
1942 in their own set or braces. */
1943
1944 case ECOND_SASLAUTHD:
1945 #ifndef CYRUS_SASLAUTHD_SOCKET
1946 goto COND_FAILED_NOT_COMPILED;
1947 #else
1948 while (isspace(*s)) s++;
1949 if (*s++ != '{') goto COND_FAILED_CURLY_START;
1950 switch(read_subs(sub, 4, 2, &s, yield == NULL, TRUE, US"saslauthd"))
1951 {
1952 case 1: expand_string_message = US"too few arguments or bracketing "
1953 "error for saslauthd";
1954 case 2:
1955 case 3: return NULL;
1956 }
1957 if (sub[2] == NULL) sub[3] = NULL; /* realm if no service */
1958 if (yield != NULL)
1959 {
1960 int rc;
1961 rc = auth_call_saslauthd(sub[0], sub[1], sub[2], sub[3],
1962 &expand_string_message);
1963 if (rc == ERROR || rc == DEFER) return NULL;
1964 *yield = (rc == OK) == testfor;
1965 }
1966 return s;
1967 #endif /* CYRUS_SASLAUTHD_SOCKET */
1968
1969
1970 /* symbolic operators for numeric and string comparison, and a number of
1971 other operators, all requiring two arguments.
1972
1973 match: does a regular expression match and sets up the numerical
1974 variables if it succeeds
1975 match_address: matches in an address list
1976 match_domain: matches in a domain list
32d668a5 1977 match_ip: matches a host list that is restricted to IP addresses
059ec3d9
PH
1978 match_local_part: matches in a local part list
1979 crypteq: encrypts plaintext and compares against an encrypted text,
1980 using crypt(), crypt16(), MD5 or SHA-1
1981 */
1982
1983 case ECOND_MATCH:
1984 case ECOND_MATCH_ADDRESS:
1985 case ECOND_MATCH_DOMAIN:
32d668a5 1986 case ECOND_MATCH_IP:
059ec3d9
PH
1987 case ECOND_MATCH_LOCAL_PART:
1988 case ECOND_CRYPTEQ:
1989
1990 case ECOND_NUM_L: /* Numerical comparisons */
1991 case ECOND_NUM_LE:
1992 case ECOND_NUM_E:
1993 case ECOND_NUM_EE:
1994 case ECOND_NUM_G:
1995 case ECOND_NUM_GE:
1996
1997 case ECOND_STR_LT: /* String comparisons */
1998 case ECOND_STR_LTI:
1999 case ECOND_STR_LE:
2000 case ECOND_STR_LEI:
2001 case ECOND_STR_EQ:
2002 case ECOND_STR_EQI:
2003 case ECOND_STR_GT:
2004 case ECOND_STR_GTI:
2005 case ECOND_STR_GE:
2006 case ECOND_STR_GEI:
2007
2008 for (i = 0; i < 2; i++)
2009 {
2010 while (isspace(*s)) s++;
2011 if (*s != '{')
2012 {
2013 if (i == 0) goto COND_FAILED_CURLY_START;
2014 expand_string_message = string_sprintf("missing 2nd string in {} "
2015 "after \"%s\"", name);
2016 return NULL;
2017 }
2018 sub[i] = expand_string_internal(s+1, TRUE, &s, yield == NULL);
2019 if (sub[i] == NULL) return NULL;
2020 if (*s++ != '}') goto COND_FAILED_CURLY_END;
2021
2022 /* Convert to numerical if required; we know that the names of all the
2023 conditions that compare numbers do not start with a letter. This just saves
2024 checking for them individually. */
2025
d6066548 2026 if (!isalpha(name[0]) && yield != NULL)
059ec3d9 2027 {
5dd1517f
PH
2028 if (sub[i][0] == 0)
2029 {
2030 num[i] = 0;
2031 DEBUG(D_expand)
2032 debug_printf("empty string cast to zero for numerical comparison\n");
2033 }
2034 else
2035 {
2036 num[i] = expand_string_integer(sub[i], FALSE);
2037 if (expand_string_message != NULL) return NULL;
2038 }
059ec3d9
PH
2039 }
2040 }
2041
2042 /* Result not required */
2043
2044 if (yield == NULL) return s;
2045
2046 /* Do an appropriate comparison */
2047
2048 switch(cond_type)
2049 {
2050 case ECOND_NUM_E:
2051 case ECOND_NUM_EE:
2052 *yield = (num[0] == num[1]) == testfor;
2053 break;
2054
2055 case ECOND_NUM_G:
2056 *yield = (num[0] > num[1]) == testfor;
2057 break;
2058
2059 case ECOND_NUM_GE:
2060 *yield = (num[0] >= num[1]) == testfor;
2061 break;
2062
2063 case ECOND_NUM_L:
2064 *yield = (num[0] < num[1]) == testfor;
2065 break;
2066
2067 case ECOND_NUM_LE:
2068 *yield = (num[0] <= num[1]) == testfor;
2069 break;
2070
2071 case ECOND_STR_LT:
2072 *yield = (Ustrcmp(sub[0], sub[1]) < 0) == testfor;
2073 break;
2074
2075 case ECOND_STR_LTI:
2076 *yield = (strcmpic(sub[0], sub[1]) < 0) == testfor;
2077 break;
2078
2079 case ECOND_STR_LE:
2080 *yield = (Ustrcmp(sub[0], sub[1]) <= 0) == testfor;
2081 break;
2082
2083 case ECOND_STR_LEI:
2084 *yield = (strcmpic(sub[0], sub[1]) <= 0) == testfor;
2085 break;
2086
2087 case ECOND_STR_EQ:
2088 *yield = (Ustrcmp(sub[0], sub[1]) == 0) == testfor;
2089 break;
2090
2091 case ECOND_STR_EQI:
2092 *yield = (strcmpic(sub[0], sub[1]) == 0) == testfor;
2093 break;
2094
2095 case ECOND_STR_GT:
2096 *yield = (Ustrcmp(sub[0], sub[1]) > 0) == testfor;
2097 break;
2098
2099 case ECOND_STR_GTI:
2100 *yield = (strcmpic(sub[0], sub[1]) > 0) == testfor;
2101 break;
2102
2103 case ECOND_STR_GE:
2104 *yield = (Ustrcmp(sub[0], sub[1]) >= 0) == testfor;
2105 break;
2106
2107 case ECOND_STR_GEI:
2108 *yield = (strcmpic(sub[0], sub[1]) >= 0) == testfor;
2109 break;
2110
2111 case ECOND_MATCH: /* Regular expression match */
2112 re = pcre_compile(CS sub[1], PCRE_COPT, (const char **)&rerror, &roffset,
2113 NULL);
2114 if (re == NULL)
2115 {
2116 expand_string_message = string_sprintf("regular expression error in "
2117 "\"%s\": %s at offset %d", sub[1], rerror, roffset);
2118 return NULL;
2119 }
2120 *yield = regex_match_and_setup(re, sub[0], 0, -1) == testfor;
2121 break;
2122
2123 case ECOND_MATCH_ADDRESS: /* Match in an address list */
2124 rc = match_address_list(sub[0], TRUE, FALSE, &(sub[1]), NULL, -1, 0, NULL);
2125 goto MATCHED_SOMETHING;
2126
2127 case ECOND_MATCH_DOMAIN: /* Match in a domain list */
2128 rc = match_isinlist(sub[0], &(sub[1]), 0, &domainlist_anchor, NULL,
2129 MCL_DOMAIN + MCL_NOEXPAND, TRUE, NULL);
2130 goto MATCHED_SOMETHING;
2131
32d668a5 2132 case ECOND_MATCH_IP: /* Match IP address in a host list */
7e66e54d 2133 if (sub[0][0] != 0 && string_is_ip_address(sub[0], NULL) == 0)
32d668a5
PH
2134 {
2135 expand_string_message = string_sprintf("\"%s\" is not an IP address",
2136 sub[0]);
2137 return NULL;
2138 }
2139 else
2140 {
2141 unsigned int *nullcache = NULL;
2142 check_host_block cb;
2143
2144 cb.host_name = US"";
2145 cb.host_address = sub[0];
2146
2147 /* If the host address starts off ::ffff: it is an IPv6 address in
2148 IPv4-compatible mode. Find the IPv4 part for checking against IPv4
2149 addresses. */
2150
2151 cb.host_ipv4 = (Ustrncmp(cb.host_address, "::ffff:", 7) == 0)?
2152 cb.host_address + 7 : cb.host_address;
2153
2154 rc = match_check_list(
2155 &sub[1], /* the list */
2156 0, /* separator character */
2157 &hostlist_anchor, /* anchor pointer */
2158 &nullcache, /* cache pointer */
2159 check_host, /* function for testing */
2160 &cb, /* argument for function */
2161 MCL_HOST, /* type of check */
2162 sub[0], /* text for debugging */
2163 NULL); /* where to pass back data */
2164 }
2165 goto MATCHED_SOMETHING;
2166
059ec3d9
PH
2167 case ECOND_MATCH_LOCAL_PART:
2168 rc = match_isinlist(sub[0], &(sub[1]), 0, &localpartlist_anchor, NULL,
2169 MCL_LOCALPART + MCL_NOEXPAND, TRUE, NULL);
2170 /* Fall through */
9a26b6b2 2171 /* VVVVVVVVVVVV */
059ec3d9
PH
2172 MATCHED_SOMETHING:
2173 switch(rc)
2174 {
2175 case OK:
2176 *yield = testfor;
2177 break;
2178
2179 case FAIL:
2180 *yield = !testfor;
2181 break;
2182
2183 case DEFER:
2184 expand_string_message = string_sprintf("unable to complete match "
2185 "against \"%s\": %s", sub[1], search_error_message);
2186 return NULL;
2187 }
2188
2189 break;
2190
2191 /* Various "encrypted" comparisons. If the second string starts with
2192 "{" then an encryption type is given. Default to crypt() or crypt16()
2193 (build-time choice). */
2194
2195 case ECOND_CRYPTEQ:
2196 #ifndef SUPPORT_CRYPTEQ
2197 goto COND_FAILED_NOT_COMPILED;
2198 #else
2199 if (strncmpic(sub[1], US"{md5}", 5) == 0)
2200 {
2201 int sublen = Ustrlen(sub[1]+5);
2202 md5 base;
2203 uschar digest[16];
2204
2205 md5_start(&base);
2206 md5_end(&base, (uschar *)sub[0], Ustrlen(sub[0]), digest);
2207
2208 /* If the length that we are comparing against is 24, the MD5 digest
2209 is expressed as a base64 string. This is the way LDAP does it. However,
2210 some other software uses a straightforward hex representation. We assume
2211 this if the length is 32. Other lengths fail. */
2212
2213 if (sublen == 24)
2214 {
2215 uschar *coded = auth_b64encode((uschar *)digest, 16);
2216 DEBUG(D_auth) debug_printf("crypteq: using MD5+B64 hashing\n"
2217 " subject=%s\n crypted=%s\n", coded, sub[1]+5);
2218 *yield = (Ustrcmp(coded, sub[1]+5) == 0) == testfor;
2219 }
2220 else if (sublen == 32)
2221 {
2222 int i;
2223 uschar coded[36];
2224 for (i = 0; i < 16; i++) sprintf(CS (coded+2*i), "%02X", digest[i]);
2225 coded[32] = 0;
2226 DEBUG(D_auth) debug_printf("crypteq: using MD5+hex hashing\n"
2227 " subject=%s\n crypted=%s\n", coded, sub[1]+5);
2228 *yield = (strcmpic(coded, sub[1]+5) == 0) == testfor;
2229 }
2230 else
2231 {
2232 DEBUG(D_auth) debug_printf("crypteq: length for MD5 not 24 or 32: "
2233 "fail\n crypted=%s\n", sub[1]+5);
2234 *yield = !testfor;
2235 }
2236 }
2237
2238 else if (strncmpic(sub[1], US"{sha1}", 6) == 0)
2239 {
2240 int sublen = Ustrlen(sub[1]+6);
2241 sha1 base;
2242 uschar digest[20];
2243
2244 sha1_start(&base);
2245 sha1_end(&base, (uschar *)sub[0], Ustrlen(sub[0]), digest);
2246
2247 /* If the length that we are comparing against is 28, assume the SHA1
2248 digest is expressed as a base64 string. If the length is 40, assume a
2249 straightforward hex representation. Other lengths fail. */
2250
2251 if (sublen == 28)
2252 {
2253 uschar *coded = auth_b64encode((uschar *)digest, 20);
2254 DEBUG(D_auth) debug_printf("crypteq: using SHA1+B64 hashing\n"
2255 " subject=%s\n crypted=%s\n", coded, sub[1]+6);
2256 *yield = (Ustrcmp(coded, sub[1]+6) == 0) == testfor;
2257 }
2258 else if (sublen == 40)
2259 {
2260 int i;
2261 uschar coded[44];
2262 for (i = 0; i < 20; i++) sprintf(CS (coded+2*i), "%02X", digest[i]);
2263 coded[40] = 0;
2264 DEBUG(D_auth) debug_printf("crypteq: using SHA1+hex hashing\n"
2265 " subject=%s\n crypted=%s\n", coded, sub[1]+6);
2266 *yield = (strcmpic(coded, sub[1]+6) == 0) == testfor;
2267 }
2268 else
2269 {
2270 DEBUG(D_auth) debug_printf("crypteq: length for SHA-1 not 28 or 40: "
2271 "fail\n crypted=%s\n", sub[1]+6);
2272 *yield = !testfor;
2273 }
2274 }
2275
2276 else /* {crypt} or {crypt16} and non-{ at start */
2277 {
2278 int which = 0;
2279 uschar *coded;
2280
2281 if (strncmpic(sub[1], US"{crypt}", 7) == 0)
2282 {
2283 sub[1] += 7;
2284 which = 1;
2285 }
2286 else if (strncmpic(sub[1], US"{crypt16}", 9) == 0)
2287 {
2288 sub[1] += 9;
2289 which = 2;
2290 }
2291 else if (sub[1][0] == '{')
2292 {
2293 expand_string_message = string_sprintf("unknown encryption mechanism "
2294 "in \"%s\"", sub[1]);
2295 return NULL;
2296 }
2297
2298 switch(which)
2299 {
2300 case 0: coded = US DEFAULT_CRYPT(CS sub[0], CS sub[1]); break;
2301 case 1: coded = US crypt(CS sub[0], CS sub[1]); break;
2302 default: coded = US crypt16(CS sub[0], CS sub[1]); break;
2303 }
2304
2305 #define STR(s) # s
2306 #define XSTR(s) STR(s)
2307 DEBUG(D_auth) debug_printf("crypteq: using %s()\n"
2308 " subject=%s\n crypted=%s\n",
2309 (which == 0)? XSTR(DEFAULT_CRYPT) : (which == 1)? "crypt" : "crypt16",
2310 coded, sub[1]);
2311 #undef STR
2312 #undef XSTR
2313
2314 /* If the encrypted string contains fewer than two characters (for the
2315 salt), force failure. Otherwise we get false positives: with an empty
2316 string the yield of crypt() is an empty string! */
2317
2318 *yield = (Ustrlen(sub[1]) < 2)? !testfor :
2319 (Ustrcmp(coded, sub[1]) == 0) == testfor;
2320 }
2321 break;
2322 #endif /* SUPPORT_CRYPTEQ */
2323 } /* Switch for comparison conditions */
2324
2325 return s; /* End of comparison conditions */
2326
2327
2328 /* and/or: computes logical and/or of several conditions */
2329
2330 case ECOND_AND:
2331 case ECOND_OR:
2332 subcondptr = (yield == NULL)? NULL : &tempcond;
2333 combined_cond = (cond_type == ECOND_AND);
2334
2335 while (isspace(*s)) s++;
2336 if (*s++ != '{') goto COND_FAILED_CURLY_START;
2337
2338 for (;;)
2339 {
2340 while (isspace(*s)) s++;
2341 if (*s == '}') break;
2342 if (*s != '{')
2343 {
2344 expand_string_message = string_sprintf("each subcondition "
2345 "inside an \"%s{...}\" condition must be in its own {}", name);
2346 return NULL;
2347 }
2348
2349 s = eval_condition(s+1, subcondptr);
2350 if (s == NULL)
2351 {
2352 expand_string_message = string_sprintf("%s inside \"%s{...}\" condition",
2353 expand_string_message, name);
2354 return NULL;
2355 }
2356 while (isspace(*s)) s++;
2357
2358 if (*s++ != '}')
2359 {
2360 expand_string_message = string_sprintf("missing } at end of condition "
2361 "inside \"%s\" group", name);
2362 return NULL;
2363 }
2364
2365 if (yield != NULL)
2366 {
2367 if (cond_type == ECOND_AND)
2368 {
2369 combined_cond &= tempcond;
2370 if (!combined_cond) subcondptr = NULL; /* once false, don't */
2371 } /* evaluate any more */
2372 else
2373 {
2374 combined_cond |= tempcond;
2375 if (combined_cond) subcondptr = NULL; /* once true, don't */
2376 } /* evaluate any more */
2377 }
2378 }
2379
2380 if (yield != NULL) *yield = (combined_cond == testfor);
2381 return ++s;
2382
2383
0ce9abe6
PH
2384 /* forall/forany: iterates a condition with different values */
2385
2386 case ECOND_FORALL:
2387 case ECOND_FORANY:
2388 {
2389 int sep = 0;
282b357d 2390 uschar *save_iterate_item = iterate_item;
0ce9abe6
PH
2391
2392 while (isspace(*s)) s++;
2393 if (*s++ != '{') goto COND_FAILED_CURLY_START;
0ce9abe6
PH
2394 sub[0] = expand_string_internal(s, TRUE, &s, (yield == NULL));
2395 if (sub[0] == NULL) return NULL;
2396 if (*s++ != '}') goto COND_FAILED_CURLY_END;
2397
2398 while (isspace(*s)) s++;
2399 if (*s++ != '{') goto COND_FAILED_CURLY_START;
2400
2401 sub[1] = s;
2402
2403 /* Call eval_condition once, with result discarded (as if scanning a
2404 "false" part). This allows us to find the end of the condition, because if
2405 the list it empty, we won't actually evaluate the condition for real. */
2406
2407 s = eval_condition(sub[1], NULL);
2408 if (s == NULL)
2409 {
2410 expand_string_message = string_sprintf("%s inside \"%s\" condition",
2411 expand_string_message, name);
2412 return NULL;
2413 }
2414 while (isspace(*s)) s++;
2415
2416 if (*s++ != '}')
2417 {
2418 expand_string_message = string_sprintf("missing } at end of condition "
2419 "inside \"%s\"", name);
2420 return NULL;
2421 }
2422
2423 if (yield != NULL) *yield = !testfor;
2424 while ((iterate_item = string_nextinlist(&sub[0], &sep, NULL, 0)) != NULL)
2425 {
2426 DEBUG(D_expand) debug_printf("%s: $item = \"%s\"\n", name, iterate_item);
2427 if (eval_condition(sub[1], &tempcond) == NULL)
2428 {
2429 expand_string_message = string_sprintf("%s inside \"%s\" condition",
2430 expand_string_message, name);
e58c13cc 2431 iterate_item = save_iterate_item;
0ce9abe6
PH
2432 return NULL;
2433 }
2434 DEBUG(D_expand) debug_printf("%s: condition evaluated to %s\n", name,
2435 tempcond? "true":"false");
2436
2437 if (yield != NULL) *yield = (tempcond == testfor);
2438 if (tempcond == (cond_type == ECOND_FORANY)) break;
2439 }
2440
282b357d 2441 iterate_item = save_iterate_item;
0ce9abe6
PH
2442 return s;
2443 }
2444
2445
059ec3d9
PH
2446 /* Unknown condition */
2447
2448 default:
2449 expand_string_message = string_sprintf("unknown condition \"%s\"", name);
2450 return NULL;
2451 } /* End switch on condition type */
2452
2453/* Missing braces at start and end of data */
2454
2455COND_FAILED_CURLY_START:
2456expand_string_message = string_sprintf("missing { after \"%s\"", name);
2457return NULL;
2458
2459COND_FAILED_CURLY_END:
2460expand_string_message = string_sprintf("missing } at end of \"%s\" condition",
2461 name);
2462return NULL;
2463
2464/* A condition requires code that is not compiled */
2465
2466#if !defined(SUPPORT_PAM) || !defined(RADIUS_CONFIG_FILE) || \
2467 !defined(LOOKUP_LDAP) || !defined(CYRUS_PWCHECK_SOCKET) || \
2468 !defined(SUPPORT_CRYPTEQ) || !defined(CYRUS_SASLAUTHD_SOCKET)
2469COND_FAILED_NOT_COMPILED:
2470expand_string_message = string_sprintf("support for \"%s\" not compiled",
2471 name);
2472return NULL;
2473#endif
2474}
2475
2476
2477
2478
2479/*************************************************
2480* Save numerical variables *
2481*************************************************/
2482
2483/* This function is called from items such as "if" that want to preserve and
2484restore the numbered variables.
2485
2486Arguments:
2487 save_expand_string points to an array of pointers to set
2488 save_expand_nlength points to an array of ints for the lengths
2489
2490Returns: the value of expand max to save
2491*/
2492
2493static int
2494save_expand_strings(uschar **save_expand_nstring, int *save_expand_nlength)
2495{
2496int i;
2497for (i = 0; i <= expand_nmax; i++)
2498 {
2499 save_expand_nstring[i] = expand_nstring[i];
2500 save_expand_nlength[i] = expand_nlength[i];
2501 }
2502return expand_nmax;
2503}
2504
2505
2506
2507/*************************************************
2508* Restore numerical variables *
2509*************************************************/
2510
2511/* This function restored saved values of numerical strings.
2512
2513Arguments:
2514 save_expand_nmax the number of strings to restore
2515 save_expand_string points to an array of pointers
2516 save_expand_nlength points to an array of ints
2517
2518Returns: nothing
2519*/
2520
2521static void
2522restore_expand_strings(int save_expand_nmax, uschar **save_expand_nstring,
2523 int *save_expand_nlength)
2524{
2525int i;
2526expand_nmax = save_expand_nmax;
2527for (i = 0; i <= expand_nmax; i++)
2528 {
2529 expand_nstring[i] = save_expand_nstring[i];
2530 expand_nlength[i] = save_expand_nlength[i];
2531 }
2532}
2533
2534
2535
2536
2537
2538/*************************************************
2539* Handle yes/no substrings *
2540*************************************************/
2541
2542/* This function is used by ${if}, ${lookup} and ${extract} to handle the
2543alternative substrings that depend on whether or not the condition was true,
2544or the lookup or extraction succeeded. The substrings always have to be
2545expanded, to check their syntax, but "skipping" is set when the result is not
2546needed - this avoids unnecessary nested lookups.
2547
2548Arguments:
2549 skipping TRUE if we were skipping when this item was reached
2550 yes TRUE if the first string is to be used, else use the second
2551 save_lookup a value to put back into lookup_value before the 2nd expansion
2552 sptr points to the input string pointer
2553 yieldptr points to the output string pointer
2554 sizeptr points to the output string size
2555 ptrptr points to the output string pointer
2556 type "lookup" or "if" or "extract" or "run", for error message
2557
2558Returns: 0 OK; lookup_value has been reset to save_lookup
2559 1 expansion failed
2560 2 expansion failed because of bracketing error
2561*/
2562
2563static int
2564process_yesno(BOOL skipping, BOOL yes, uschar *save_lookup, uschar **sptr,
2565 uschar **yieldptr, int *sizeptr, int *ptrptr, uschar *type)
2566{
2567int rc = 0;
2568uschar *s = *sptr; /* Local value */
2569uschar *sub1, *sub2;
2570
2571/* If there are no following strings, we substitute the contents of $value for
063b1e99 2572lookups and for extractions in the success case. For the ${if item, the string
8e669ac1 2573"true" is substituted. In the fail case, nothing is substituted for all three
063b1e99 2574items. */
059ec3d9
PH
2575
2576while (isspace(*s)) s++;
2577if (*s == '}')
2578 {
063b1e99
PH
2579 if (type[0] == 'i')
2580 {
8e669ac1 2581 if (yes) *yieldptr = string_cat(*yieldptr, sizeptr, ptrptr, US"true", 4);
063b1e99
PH
2582 }
2583 else
8e669ac1 2584 {
063b1e99
PH
2585 if (yes && lookup_value != NULL)
2586 *yieldptr = string_cat(*yieldptr, sizeptr, ptrptr, lookup_value,
2587 Ustrlen(lookup_value));
2588 lookup_value = save_lookup;
2589 }
059ec3d9
PH
2590 s++;
2591 goto RETURN;
2592 }
2593
9b4768fa
PH
2594/* The first following string must be braced. */
2595
2596if (*s++ != '{') goto FAILED_CURLY;
2597
059ec3d9
PH
2598/* Expand the first substring. Forced failures are noticed only if we actually
2599want this string. Set skipping in the call in the fail case (this will always
2600be the case if we were already skipping). */
2601
9b4768fa 2602sub1 = expand_string_internal(s, TRUE, &s, !yes);
059ec3d9
PH
2603if (sub1 == NULL && (yes || !expand_string_forcedfail)) goto FAILED;
2604expand_string_forcedfail = FALSE;
2605if (*s++ != '}') goto FAILED_CURLY;
2606
2607/* If we want the first string, add it to the output */
2608
2609if (yes)
2610 *yieldptr = string_cat(*yieldptr, sizeptr, ptrptr, sub1, Ustrlen(sub1));
2611
2612/* If this is called from a lookup or an extract, we want to restore $value to
2613what it was at the start of the item, so that it has this value during the
d20976dc
PH
2614second string expansion. For the call from "if" or "run" to this function,
2615save_lookup is set to lookup_value, so that this statement does nothing. */
059ec3d9
PH
2616
2617lookup_value = save_lookup;
2618
2619/* There now follows either another substring, or "fail", or nothing. This
2620time, forced failures are noticed only if we want the second string. We must
2621set skipping in the nested call if we don't want this string, or if we were
2622already skipping. */
2623
2624while (isspace(*s)) s++;
2625if (*s == '{')
2626 {
2627 sub2 = expand_string_internal(s+1, TRUE, &s, yes || skipping);
2628 if (sub2 == NULL && (!yes || !expand_string_forcedfail)) goto FAILED;
2629 expand_string_forcedfail = FALSE;
2630 if (*s++ != '}') goto FAILED_CURLY;
2631
2632 /* If we want the second string, add it to the output */
2633
2634 if (!yes)
2635 *yieldptr = string_cat(*yieldptr, sizeptr, ptrptr, sub2, Ustrlen(sub2));
2636 }
2637
2638/* If there is no second string, but the word "fail" is present when the use of
2639the second string is wanted, set a flag indicating it was a forced failure
2640rather than a syntactic error. Swallow the terminating } in case this is nested
2641inside another lookup or if or extract. */
2642
2643else if (*s != '}')
2644 {
2645 uschar name[256];
2646 s = read_name(name, sizeof(name), s, US"_");
2647 if (Ustrcmp(name, "fail") == 0)
2648 {
2649 if (!yes && !skipping)
2650 {
2651 while (isspace(*s)) s++;
2652 if (*s++ != '}') goto FAILED_CURLY;
2653 expand_string_message =
2654 string_sprintf("\"%s\" failed and \"fail\" requested", type);
2655 expand_string_forcedfail = TRUE;
2656 goto FAILED;
2657 }
2658 }
2659 else
2660 {
2661 expand_string_message =
2662 string_sprintf("syntax error in \"%s\" item - \"fail\" expected", type);
2663 goto FAILED;
2664 }
2665 }
2666
2667/* All we have to do now is to check on the final closing brace. */
2668
2669while (isspace(*s)) s++;
2670if (*s++ == '}') goto RETURN;
2671
2672/* Get here if there is a bracketing failure */
2673
2674FAILED_CURLY:
2675rc++;
2676
2677/* Get here for other failures */
2678
2679FAILED:
2680rc++;
2681
2682/* Update the input pointer value before returning */
2683
2684RETURN:
2685*sptr = s;
2686return rc;
2687}
2688
2689
2690
2691
059ec3d9
PH
2692/*************************************************
2693* Handle MD5 or SHA-1 computation for HMAC *
2694*************************************************/
2695
2696/* These are some wrapping functions that enable the HMAC code to be a bit
2697cleaner. A good compiler will spot the tail recursion.
2698
2699Arguments:
2700 type HMAC_MD5 or HMAC_SHA1
2701 remaining are as for the cryptographic hash functions
2702
2703Returns: nothing
2704*/
2705
2706static void
2707chash_start(int type, void *base)
2708{
2709if (type == HMAC_MD5)
2710 md5_start((md5 *)base);
2711else
2712 sha1_start((sha1 *)base);
2713}
2714
2715static void
2716chash_mid(int type, void *base, uschar *string)
2717{
2718if (type == HMAC_MD5)
2719 md5_mid((md5 *)base, string);
2720else
2721 sha1_mid((sha1 *)base, string);
2722}
2723
2724static void
2725chash_end(int type, void *base, uschar *string, int length, uschar *digest)
2726{
2727if (type == HMAC_MD5)
2728 md5_end((md5 *)base, string, length, digest);
2729else
2730 sha1_end((sha1 *)base, string, length, digest);
2731}
2732
2733
2734
2735
2736
1549ea3b
PH
2737/********************************************************
2738* prvs: Get last three digits of days since Jan 1, 1970 *
2739********************************************************/
2740
2741/* This is needed to implement the "prvs" BATV reverse
2742 path signing scheme
2743
2744Argument: integer "days" offset to add or substract to
2745 or from the current number of days.
2746
2747Returns: pointer to string containing the last three
2748 digits of the number of days since Jan 1, 1970,
2749 modified by the offset argument, NULL if there
2750 was an error in the conversion.
2751
2752*/
2753
2754static uschar *
2755prvs_daystamp(int day_offset)
2756{
a86229cf
PH
2757uschar *days = store_get(32); /* Need at least 24 for cases */
2758(void)string_format(days, 32, TIME_T_FMT, /* where TIME_T_FMT is %lld */
1549ea3b 2759 (time(NULL) + day_offset*86400)/86400);
e169f567 2760return (Ustrlen(days) >= 3) ? &days[Ustrlen(days)-3] : US"100";
1549ea3b
PH
2761}
2762
2763
2764
2765/********************************************************
2766* prvs: perform HMAC-SHA1 computation of prvs bits *
2767********************************************************/
2768
2769/* This is needed to implement the "prvs" BATV reverse
2770 path signing scheme
2771
2772Arguments:
2773 address RFC2821 Address to use
2774 key The key to use (must be less than 64 characters
2775 in size)
2776 key_num Single-digit key number to use. Defaults to
2777 '0' when NULL.
2778
2779Returns: pointer to string containing the first three
2780 bytes of the final hash in hex format, NULL if
2781 there was an error in the process.
2782*/
2783
2784static uschar *
2785prvs_hmac_sha1(uschar *address, uschar *key, uschar *key_num, uschar *daystamp)
2786{
2787uschar *hash_source, *p;
2788int size = 0,offset = 0,i;
2789sha1 sha1_base;
2790void *use_base = &sha1_base;
2791uschar innerhash[20];
2792uschar finalhash[20];
2793uschar innerkey[64];
2794uschar outerkey[64];
2795uschar *finalhash_hex = store_get(40);
2796
2797if (key_num == NULL)
2798 key_num = US"0";
2799
2800if (Ustrlen(key) > 64)
2801 return NULL;
2802
2803hash_source = string_cat(NULL,&size,&offset,key_num,1);
2804string_cat(hash_source,&size,&offset,daystamp,3);
2805string_cat(hash_source,&size,&offset,address,Ustrlen(address));
2806hash_source[offset] = '\0';
2807
2808DEBUG(D_expand) debug_printf("prvs: hash source is '%s'\n", hash_source);
2809
2810memset(innerkey, 0x36, 64);
2811memset(outerkey, 0x5c, 64);
2812
2813for (i = 0; i < Ustrlen(key); i++)
2814 {
2815 innerkey[i] ^= key[i];
2816 outerkey[i] ^= key[i];
2817 }
2818
2819chash_start(HMAC_SHA1, use_base);
2820chash_mid(HMAC_SHA1, use_base, innerkey);
2821chash_end(HMAC_SHA1, use_base, hash_source, offset, innerhash);
2822
2823chash_start(HMAC_SHA1, use_base);
2824chash_mid(HMAC_SHA1, use_base, outerkey);
2825chash_end(HMAC_SHA1, use_base, innerhash, 20, finalhash);
2826
2827p = finalhash_hex;
2828for (i = 0; i < 3; i++)
2829 {
2830 *p++ = hex_digits[(finalhash[i] & 0xf0) >> 4];
2831 *p++ = hex_digits[finalhash[i] & 0x0f];
2832 }
2833*p = '\0';
2834
2835return finalhash_hex;
2836}
2837
2838
2839
2840
059ec3d9
PH
2841/*************************************************
2842* Join a file onto the output string *
2843*************************************************/
2844
2845/* This is used for readfile and after a run expansion. It joins the contents
2846of a file onto the output string, globally replacing newlines with a given
2847string (optionally). The file is closed at the end.
2848
2849Arguments:
2850 f the FILE
2851 yield pointer to the expandable string
2852 sizep pointer to the current size
2853 ptrp pointer to the current position
2854 eol newline replacement string, or NULL
2855
2856Returns: new value of string pointer
2857*/
2858
2859static uschar *
2860cat_file(FILE *f, uschar *yield, int *sizep, int *ptrp, uschar *eol)
2861{
2862int eollen;
2863uschar buffer[1024];
2864
2865eollen = (eol == NULL)? 0 : Ustrlen(eol);
2866
2867while (Ufgets(buffer, sizeof(buffer), f) != NULL)
2868 {
2869 int len = Ustrlen(buffer);
2870 if (eol != NULL && buffer[len-1] == '\n') len--;
2871 yield = string_cat(yield, sizep, ptrp, buffer, len);
2872 if (buffer[len] != 0)
2873 yield = string_cat(yield, sizep, ptrp, eol, eollen);
2874 }
2875
2876if (yield != NULL) yield[*ptrp] = 0;
2877
2878return yield;
2879}
2880
2881
2882
2883
2884/*************************************************
2885* Evaluate numeric expression *
2886*************************************************/
2887
af561417
PH
2888/* This is a set of mutually recursive functions that evaluate an arithmetic
2889expression involving + - * / % & | ^ ~ << >> and parentheses. The only one of
2890these functions that is called from elsewhere is eval_expr, whose interface is:
059ec3d9
PH
2891
2892Arguments:
af561417
PH
2893 sptr pointer to the pointer to the string - gets updated
2894 decimal TRUE if numbers are to be assumed decimal
2895 error pointer to where to put an error message - must be NULL on input
2896 endket TRUE if ')' must terminate - FALSE for external call
059ec3d9 2897
af561417
PH
2898Returns: on success: the value of the expression, with *error still NULL
2899 on failure: an undefined value, with *error = a message
059ec3d9
PH
2900*/
2901
af561417
PH
2902static int eval_op_or(uschar **, BOOL, uschar **);
2903
059ec3d9
PH
2904
2905static int
2906eval_expr(uschar **sptr, BOOL decimal, uschar **error, BOOL endket)
2907{
2908uschar *s = *sptr;
af561417 2909int x = eval_op_or(&s, decimal, error);
059ec3d9
PH
2910if (*error == NULL)
2911 {
af561417 2912 if (endket)
059ec3d9 2913 {
af561417
PH
2914 if (*s != ')')
2915 *error = US"expecting closing parenthesis";
2916 else
2917 while (isspace(*(++s)));
059ec3d9 2918 }
af561417 2919 else if (*s != 0) *error = US"expecting operator";
059ec3d9 2920 }
059ec3d9
PH
2921*sptr = s;
2922return x;
2923}
2924
af561417 2925
059ec3d9 2926static int
af561417 2927eval_number(uschar **sptr, BOOL decimal, uschar **error)
059ec3d9
PH
2928{
2929register int c;
2930int n;
2931uschar *s = *sptr;
2932while (isspace(*s)) s++;
2933c = *s;
af561417 2934if (isdigit(c))
059ec3d9
PH
2935 {
2936 int count;
2937 (void)sscanf(CS s, (decimal? "%d%n" : "%i%n"), &n, &count);
2938 s += count;
2939 if (tolower(*s) == 'k') { n *= 1024; s++; }
2940 else if (tolower(*s) == 'm') { n *= 1024*1024; s++; }
2941 while (isspace (*s)) s++;
2942 }
2943else if (c == '(')
2944 {
2945 s++;
2946 n = eval_expr(&s, decimal, error, 1);
2947 }
2948else
2949 {
2950 *error = US"expecting number or opening parenthesis";
2951 n = 0;
2952 }
2953*sptr = s;
2954return n;
2955}
2956
af561417
PH
2957
2958static int eval_op_unary(uschar **sptr, BOOL decimal, uschar **error)
2959{
2960uschar *s = *sptr;
2961int x;
2962while (isspace(*s)) s++;
2963if (*s == '+' || *s == '-' || *s == '~')
2964 {
2965 int op = *s++;
2966 x = eval_op_unary(&s, decimal, error);
2967 if (op == '-') x = -x;
2968 else if (op == '~') x = ~x;
2969 }
2970else
2971 {
2972 x = eval_number(&s, decimal, error);
2973 }
2974*sptr = s;
2975return x;
2976}
2977
2978
2979static int eval_op_mult(uschar **sptr, BOOL decimal, uschar **error)
059ec3d9
PH
2980{
2981uschar *s = *sptr;
af561417 2982int x = eval_op_unary(&s, decimal, error);
059ec3d9
PH
2983if (*error == NULL)
2984 {
5591031b 2985 while (*s == '*' || *s == '/' || *s == '%')
059ec3d9
PH
2986 {
2987 int op = *s++;
af561417 2988 int y = eval_op_unary(&s, decimal, error);
059ec3d9 2989 if (*error != NULL) break;
5591031b
PH
2990 if (op == '*') x *= y;
2991 else if (op == '/') x /= y;
2992 else x %= y;
059ec3d9
PH
2993 }
2994 }
2995*sptr = s;
2996return x;
2997}
2998
2999
af561417
PH
3000static int eval_op_sum(uschar **sptr, BOOL decimal, uschar **error)
3001{
3002uschar *s = *sptr;
3003int x = eval_op_mult(&s, decimal, error);
3004if (*error == NULL)
3005 {
3006 while (*s == '+' || *s == '-')
3007 {
3008 int op = *s++;
3009 int y = eval_op_mult(&s, decimal, error);
3010 if (*error != NULL) break;
3011 if (op == '+') x += y; else x -= y;
3012 }
3013 }
3014*sptr = s;
3015return x;
3016}
3017
3018
3019static int eval_op_shift(uschar **sptr, BOOL decimal, uschar **error)
3020{
3021uschar *s = *sptr;
3022int x = eval_op_sum(&s, decimal, error);
3023if (*error == NULL)
3024 {
3025 while ((*s == '<' || *s == '>') && s[1] == s[0])
3026 {
3027 int y;
3028 int op = *s++;
3029 s++;
3030 y = eval_op_sum(&s, decimal, error);
3031 if (*error != NULL) break;
3032 if (op == '<') x <<= y; else x >>= y;
3033 }
3034 }
3035*sptr = s;
3036return x;
3037}
3038
3039
3040static int eval_op_and(uschar **sptr, BOOL decimal, uschar **error)
3041{
3042uschar *s = *sptr;
3043int x = eval_op_shift(&s, decimal, error);
3044if (*error == NULL)
3045 {
3046 while (*s == '&')
3047 {
3048 int y;
3049 s++;
3050 y = eval_op_shift(&s, decimal, error);
3051 if (*error != NULL) break;
3052 x &= y;
3053 }
3054 }
3055*sptr = s;
3056return x;
3057}
3058
3059
3060static int eval_op_xor(uschar **sptr, BOOL decimal, uschar **error)
3061{
3062uschar *s = *sptr;
3063int x = eval_op_and(&s, decimal, error);
3064if (*error == NULL)
3065 {
3066 while (*s == '^')
3067 {
3068 int y;
3069 s++;
3070 y = eval_op_and(&s, decimal, error);
3071 if (*error != NULL) break;
3072 x ^= y;
3073 }
3074 }
3075*sptr = s;
3076return x;
3077}
3078
3079
3080static int eval_op_or(uschar **sptr, BOOL decimal, uschar **error)
3081{
3082uschar *s = *sptr;
3083int x = eval_op_xor(&s, decimal, error);
3084if (*error == NULL)
3085 {
3086 while (*s == '|')
3087 {
3088 int y;
3089 s++;
3090 y = eval_op_xor(&s, decimal, error);
3091 if (*error != NULL) break;
3092 x |= y;
3093 }
3094 }
3095*sptr = s;
3096return x;
3097}
3098
059ec3d9
PH
3099
3100
3101/*************************************************
3102* Expand string *
3103*************************************************/
3104
3105/* Returns either an unchanged string, or the expanded string in stacking pool
3106store. Interpreted sequences are:
3107
3108 \... normal escaping rules
3109 $name substitutes the variable
3110 ${name} ditto
3111 ${op:string} operates on the expanded string value
3112 ${item{arg1}{arg2}...} expands the args and then does the business
3113 some literal args are not enclosed in {}
3114
3115There are now far too many operators and item types to make it worth listing
3116them here in detail any more.
3117
3118We use an internal routine recursively to handle embedded substrings. The
3119external function follows. The yield is NULL if the expansion failed, and there
3120are two cases: if something collapsed syntactically, or if "fail" was given
3121as the action on a lookup failure. These can be distinguised by looking at the
3122variable expand_string_forcedfail, which is TRUE in the latter case.
3123
3124The skipping flag is set true when expanding a substring that isn't actually
3125going to be used (after "if" or "lookup") and it prevents lookups from
3126happening lower down.
3127
3128Store usage: At start, a store block of the length of the input plus 64
3129is obtained. This is expanded as necessary by string_cat(), which might have to
3130get a new block, or might be able to expand the original. At the end of the
3131function we can release any store above that portion of the yield block that
3132was actually used. In many cases this will be optimal.
3133
3134However: if the first item in the expansion is a variable name or header name,
3135we reset the store before processing it; if the result is in fresh store, we
3136use that without copying. This is helpful for expanding strings like
3137$message_headers which can get very long.
3138
d6b4d938
TF
3139There's a problem if a ${dlfunc item has side-effects that cause allocation,
3140since resetting the store at the end of the expansion will free store that was
3141allocated by the plugin code as well as the slop after the expanded string. So
3142we skip any resets if ${dlfunc has been used. This is an unfortunate
3143consequence of string expansion becoming too powerful.
3144
059ec3d9
PH
3145Arguments:
3146 string the string to be expanded
3147 ket_ends true if expansion is to stop at }
3148 left if not NULL, a pointer to the first character after the
3149 expansion is placed here (typically used with ket_ends)
3150 skipping TRUE for recursive calls when the value isn't actually going
3151 to be used (to allow for optimisation)
3152
3153Returns: NULL if expansion fails:
3154 expand_string_forcedfail is set TRUE if failure was forced
3155 expand_string_message contains a textual error message
3156 a pointer to the expanded string on success
3157*/
3158
3159static uschar *
3160expand_string_internal(uschar *string, BOOL ket_ends, uschar **left,
3161 BOOL skipping)
3162{
3163int ptr = 0;
3164int size = Ustrlen(string)+ 64;
3165int item_type;
3166uschar *yield = store_get(size);
3167uschar *s = string;
3168uschar *save_expand_nstring[EXPAND_MAXN+1];
3169int save_expand_nlength[EXPAND_MAXN+1];
d6b4d938 3170BOOL resetok = TRUE;
059ec3d9
PH
3171
3172expand_string_forcedfail = FALSE;
3173expand_string_message = US"";
3174
3175while (*s != 0)
3176 {
3177 uschar *value;
3178 uschar name[256];
3179
3180 /* \ escapes the next character, which must exist, or else
3181 the expansion fails. There's a special escape, \N, which causes
3182 copying of the subject verbatim up to the next \N. Otherwise,
3183 the escapes are the standard set. */
3184
3185 if (*s == '\\')
3186 {
3187 if (s[1] == 0)
3188 {
3189 expand_string_message = US"\\ at end of string";
3190 goto EXPAND_FAILED;
3191 }
3192
3193 if (s[1] == 'N')
3194 {
3195 uschar *t = s + 2;
3196 for (s = t; *s != 0; s++) if (*s == '\\' && s[1] == 'N') break;
3197 yield = string_cat(yield, &size, &ptr, t, s - t);
3198 if (*s != 0) s += 2;
3199 }
3200
3201 else
3202 {
3203 uschar ch[1];
3204 ch[0] = string_interpret_escape(&s);
3205 s++;
3206 yield = string_cat(yield, &size, &ptr, ch, 1);
3207 }
3208
3209 continue;
3210 }
3211
3212 /* Anything other than $ is just copied verbatim, unless we are
3213 looking for a terminating } character. */
3214
3215 if (ket_ends && *s == '}') break;
3216
3217 if (*s != '$')
3218 {
3219 yield = string_cat(yield, &size, &ptr, s++, 1);
3220 continue;
3221 }
3222
3223 /* No { after the $ - must be a plain name or a number for string
3224 match variable. There has to be a fudge for variables that are the
3225 names of header fields preceded by "$header_" because header field
3226 names can contain any printing characters except space and colon.
3227 For those that don't like typing this much, "$h_" is a synonym for
3228 "$header_". A non-existent header yields a NULL value; nothing is
3229 inserted. */
3230
3231 if (isalpha((*(++s))))
3232 {
3233 int len;
3234 int newsize = 0;
3235
3236 s = read_name(name, sizeof(name), s, US"_");
3237
3238 /* If this is the first thing to be expanded, release the pre-allocated
3239 buffer. */
3240
3241 if (ptr == 0 && yield != NULL)
3242 {
d6b4d938 3243 if (resetok) store_reset(yield);
059ec3d9
PH
3244 yield = NULL;
3245 size = 0;
3246 }
3247
3248 /* Header */
3249
3250 if (Ustrncmp(name, "h_", 2) == 0 ||
3251 Ustrncmp(name, "rh_", 3) == 0 ||
3252 Ustrncmp(name, "bh_", 3) == 0 ||
3253 Ustrncmp(name, "header_", 7) == 0 ||
3254 Ustrncmp(name, "rheader_", 8) == 0 ||
3255 Ustrncmp(name, "bheader_", 8) == 0)
3256 {
3257 BOOL want_raw = (name[0] == 'r')? TRUE : FALSE;
3258 uschar *charset = (name[0] == 'b')? NULL : headers_charset;
3259 s = read_header_name(name, sizeof(name), s);
3260 value = find_header(name, FALSE, &newsize, want_raw, charset);
3261
3262 /* If we didn't find the header, and the header contains a closing brace
0d85fa3f 3263 character, this may be a user error where the terminating colon
059ec3d9
PH
3264 has been omitted. Set a flag to adjust the error message in this case.
3265 But there is no error here - nothing gets inserted. */
3266
3267 if (value == NULL)
3268 {
3269 if (Ustrchr(name, '}') != NULL) malformed_header = TRUE;
3270 continue;
3271 }
3272 }
3273
3274 /* Variable */
3275
3276 else
3277 {
3278 value = find_variable(name, FALSE, skipping, &newsize);
3279 if (value == NULL)
3280 {
3281 expand_string_message =
3282 string_sprintf("unknown variable name \"%s\"", name);
641cb756 3283 check_variable_error_message(name);
059ec3d9
PH
3284 goto EXPAND_FAILED;
3285 }
3286 }
3287
3288 /* If the data is known to be in a new buffer, newsize will be set to the
3289 size of that buffer. If this is the first thing in an expansion string,
3290 yield will be NULL; just point it at the new store instead of copying. Many
3291 expansion strings contain just one reference, so this is a useful
3292 optimization, especially for humungous headers. */
3293
3294 len = Ustrlen(value);
3295 if (yield == NULL && newsize != 0)
3296 {
3297 yield = value;
3298 size = newsize;
3299 ptr = len;
3300 }
3301 else yield = string_cat(yield, &size, &ptr, value, len);
3302
3303 continue;
3304 }
3305
3306 if (isdigit(*s))
3307 {
3308 int n;
3309 s = read_number(&n, s);
3310 if (n >= 0 && n <= expand_nmax)
3311 yield = string_cat(yield, &size, &ptr, expand_nstring[n],
3312 expand_nlength[n]);
3313 continue;
3314 }
3315
3316 /* Otherwise, if there's no '{' after $ it's an error. */
3317
3318 if (*s != '{')
3319 {
3320 expand_string_message = US"$ not followed by letter, digit, or {";
3321 goto EXPAND_FAILED;
3322 }
3323
3324 /* After { there can be various things, but they all start with
3325 an initial word, except for a number for a string match variable. */
3326
3327 if (isdigit((*(++s))))
3328 {
3329 int n;
3330 s = read_number(&n, s);
3331 if (*s++ != '}')
3332 {
3333 expand_string_message = US"} expected after number";
3334 goto EXPAND_FAILED;
3335 }
3336 if (n >= 0 && n <= expand_nmax)
3337 yield = string_cat(yield, &size, &ptr, expand_nstring[n],
3338 expand_nlength[n]);
3339 continue;
3340 }
3341
3342 if (!isalpha(*s))
3343 {
3344 expand_string_message = US"letter or digit expected after ${";
3345 goto EXPAND_FAILED;
3346 }
3347
3348 /* Allow "-" in names to cater for substrings with negative
3349 arguments. Since we are checking for known names after { this is
3350 OK. */
3351
3352 s = read_name(name, sizeof(name), s, US"_-");
3353 item_type = chop_match(name, item_table, sizeof(item_table)/sizeof(uschar *));
3354
3355 switch(item_type)
3356 {
3357 /* Handle conditionals - preserve the values of the numerical expansion
3358 variables in case they get changed by a regular expression match in the
3359 condition. If not, they retain their external settings. At the end
3360 of this "if" section, they get restored to their previous values. */
3361
3362 case EITEM_IF:
3363 {
3364 BOOL cond = FALSE;
3365 uschar *next_s;
3366 int save_expand_nmax =
3367 save_expand_strings(save_expand_nstring, save_expand_nlength);
3368
3369 while (isspace(*s)) s++;
3370 next_s = eval_condition(s, skipping? NULL : &cond);
3371 if (next_s == NULL) goto EXPAND_FAILED; /* message already set */
3372
3373 DEBUG(D_expand)
3374 debug_printf("condition: %.*s\n result: %s\n", (int)(next_s - s), s,
3375 cond? "true" : "false");
3376
3377 s = next_s;
3378
3379 /* The handling of "yes" and "no" result strings is now in a separate
3380 function that is also used by ${lookup} and ${extract} and ${run}. */
3381
3382 switch(process_yesno(
3383 skipping, /* were previously skipping */
3384 cond, /* success/failure indicator */
3385 lookup_value, /* value to reset for string2 */
3386 &s, /* input pointer */
3387 &yield, /* output pointer */
3388 &size, /* output size */
3389 &ptr, /* output current point */
3390 US"if")) /* condition type */
3391 {
3392 case 1: goto EXPAND_FAILED; /* when all is well, the */
3393 case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */
3394 }
3395
3396 /* Restore external setting of expansion variables for continuation
3397 at this level. */
3398
3399 restore_expand_strings(save_expand_nmax, save_expand_nstring,
3400 save_expand_nlength);
3401 continue;
3402 }
3403
3404 /* Handle database lookups unless locked out. If "skipping" is TRUE, we are
3405 expanding an internal string that isn't actually going to be used. All we
3406 need to do is check the syntax, so don't do a lookup at all. Preserve the
3407 values of the numerical expansion variables in case they get changed by a
3408 partial lookup. If not, they retain their external settings. At the end
3409 of this "lookup" section, they get restored to their previous values. */
3410
3411 case EITEM_LOOKUP:
3412 {
3413 int stype, partial, affixlen, starflags;
3414 int expand_setup = 0;
3415 int nameptr = 0;
3416 uschar *key, *filename, *affix;
3417 uschar *save_lookup_value = lookup_value;
3418 int save_expand_nmax =
3419 save_expand_strings(save_expand_nstring, save_expand_nlength);
3420
3421 if ((expand_forbid & RDO_LOOKUP) != 0)
3422 {
3423 expand_string_message = US"lookup expansions are not permitted";
3424 goto EXPAND_FAILED;
3425 }
3426
3427 /* Get the key we are to look up for single-key+file style lookups.
3428 Otherwise set the key NULL pro-tem. */
3429
3430 while (isspace(*s)) s++;
3431 if (*s == '{')
3432 {
3433 key = expand_string_internal(s+1, TRUE, &s, skipping);
3434 if (key == NULL) goto EXPAND_FAILED;
3435 if (*s++ != '}') goto EXPAND_FAILED_CURLY;
3436 while (isspace(*s)) s++;
3437 }
3438 else key = NULL;
3439
3440 /* Find out the type of database */
3441
3442 if (!isalpha(*s))
3443 {
3444 expand_string_message = US"missing lookup type";
3445 goto EXPAND_FAILED;
3446 }
3447
3448 /* The type is a string that may contain special characters of various
3449 kinds. Allow everything except space or { to appear; the actual content
3450 is checked by search_findtype_partial. */
3451
3452 while (*s != 0 && *s != '{' && !isspace(*s))
3453 {
3454 if (nameptr < sizeof(name) - 1) name[nameptr++] = *s;
3455 s++;
3456 }
3457 name[nameptr] = 0;
3458 while (isspace(*s)) s++;
3459
3460 /* Now check for the individual search type and any partial or default
3461 options. Only those types that are actually in the binary are valid. */
3462
3463 stype = search_findtype_partial(name, &partial, &affix, &affixlen,
3464 &starflags);
3465 if (stype < 0)
3466 {
3467 expand_string_message = search_error_message;
3468 goto EXPAND_FAILED;
3469 }
3470
3471 /* Check that a key was provided for those lookup types that need it,
3472 and was not supplied for those that use the query style. */
3473
13b685f9 3474 if (!mac_islookup(stype, lookup_querystyle|lookup_absfilequery))
059ec3d9
PH
3475 {
3476 if (key == NULL)
3477 {
3478 expand_string_message = string_sprintf("missing {key} for single-"
3479 "key \"%s\" lookup", name);
3480 goto EXPAND_FAILED;
3481 }
3482 }
3483 else
3484 {
3485 if (key != NULL)
3486 {
3487 expand_string_message = string_sprintf("a single key was given for "
3488 "lookup type \"%s\", which is not a single-key lookup type", name);
3489 goto EXPAND_FAILED;
3490 }
3491 }
3492
3493 /* Get the next string in brackets and expand it. It is the file name for
13b685f9
PH
3494 single-key+file lookups, and the whole query otherwise. In the case of
3495 queries that also require a file name (e.g. sqlite), the file name comes
3496 first. */
059ec3d9
PH
3497
3498 if (*s != '{') goto EXPAND_FAILED_CURLY;
3499 filename = expand_string_internal(s+1, TRUE, &s, skipping);
3500 if (filename == NULL) goto EXPAND_FAILED;
3501 if (*s++ != '}') goto EXPAND_FAILED_CURLY;
3502 while (isspace(*s)) s++;
3503
3504 /* If this isn't a single-key+file lookup, re-arrange the variables
13b685f9
PH
3505 to be appropriate for the search_ functions. For query-style lookups,
3506 there is just a "key", and no file name. For the special query-style +
3507 file types, the query (i.e. "key") starts with a file name. */
059ec3d9
PH
3508
3509 if (key == NULL)
3510 {
13b685f9 3511 while (isspace(*filename)) filename++;
059ec3d9 3512 key = filename;
13b685f9
PH
3513
3514 if (mac_islookup(stype, lookup_querystyle))
3515 {
3516 filename = NULL;
3517 }
3518 else
3519 {
3520 if (*filename != '/')
3521 {
3522 expand_string_message = string_sprintf(
3523 "absolute file name expected for \"%s\" lookup", name);
3524 goto EXPAND_FAILED;
3525 }
3526 while (*key != 0 && !isspace(*key)) key++;
3527 if (*key != 0) *key++ = 0;
3528 }
059ec3d9
PH
3529 }
3530
3531 /* If skipping, don't do the next bit - just lookup_value == NULL, as if
3532 the entry was not found. Note that there is no search_close() function.
3533 Files are left open in case of re-use. At suitable places in higher logic,
3534 search_tidyup() is called to tidy all open files. This can save opening
3535 the same file several times. However, files may also get closed when
3536 others are opened, if too many are open at once. The rule is that a
3537 handle should not be used after a second search_open().
3538
3539 Request that a partial search sets up $1 and maybe $2 by passing
3540 expand_setup containing zero. If its value changes, reset expand_nmax,
3541 since new variables will have been set. Note that at the end of this
3542 "lookup" section, the old numeric variables are restored. */
3543
3544 if (skipping)
3545 lookup_value = NULL;
3546 else
3547 {
3548 void *handle = search_open(filename, stype, 0, NULL, NULL);
3549 if (handle == NULL)
3550 {
3551 expand_string_message = search_error_message;
3552 goto EXPAND_FAILED;
3553 }
3554 lookup_value = search_find(handle, filename, key, partial, affix,
3555 affixlen, starflags, &expand_setup);
3556 if (search_find_defer)
3557 {
3558 expand_string_message =
3559 string_sprintf("lookup of \"%s\" gave DEFER: %s", key,
3560 search_error_message);
3561 goto EXPAND_FAILED;
3562 }
3563 if (expand_setup > 0) expand_nmax = expand_setup;
3564 }
3565
3566 /* The handling of "yes" and "no" result strings is now in a separate
3567 function that is also used by ${if} and ${extract}. */
3568
3569 switch(process_yesno(
3570 skipping, /* were previously skipping */
3571 lookup_value != NULL, /* success/failure indicator */
3572 save_lookup_value, /* value to reset for string2 */
3573 &s, /* input pointer */
3574 &yield, /* output pointer */
3575 &size, /* output size */
3576 &ptr, /* output current point */
3577 US"lookup")) /* condition type */
3578 {
3579 case 1: goto EXPAND_FAILED; /* when all is well, the */
3580 case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */
3581 }
3582
3583 /* Restore external setting of expansion variables for carrying on
3584 at this level, and continue. */
3585
3586 restore_expand_strings(save_expand_nmax, save_expand_nstring,
3587 save_expand_nlength);
3588 continue;
3589 }
3590
3591 /* If Perl support is configured, handle calling embedded perl subroutines,
3592 unless locked out at this time. Syntax is ${perl{sub}} or ${perl{sub}{arg}}
3593 or ${perl{sub}{arg1}{arg2}} or up to a maximum of EXIM_PERL_MAX_ARGS
3594 arguments (defined below). */
3595
059ec3d9
PH
3596 #define EXIM_PERL_MAX_ARGS 8
3597
3598 case EITEM_PERL:
1a46a8c5
PH
3599 #ifndef EXIM_PERL
3600 expand_string_message = US"\"${perl\" encountered, but this facility "
3601 "is not included in this binary";
3602 goto EXPAND_FAILED;
3603
3604 #else /* EXIM_PERL */
059ec3d9
PH
3605 {
3606 uschar *sub_arg[EXIM_PERL_MAX_ARGS + 2];
3607 uschar *new_yield;
3608
3609 if ((expand_forbid & RDO_PERL) != 0)
3610 {
3611 expand_string_message = US"Perl calls are not permitted";
3612 goto EXPAND_FAILED;
3613 }
3614
3615 switch(read_subs(sub_arg, EXIM_PERL_MAX_ARGS + 1, 1, &s, skipping, TRUE,
3616 US"perl"))
3617 {
3618 case 1: goto EXPAND_FAILED_CURLY;
3619 case 2:
3620 case 3: goto EXPAND_FAILED;
3621 }
3622
3623 /* If skipping, we don't actually do anything */
3624
3625 if (skipping) continue;
3626
3627 /* Start the interpreter if necessary */
3628
3629 if (!opt_perl_started)
3630 {
3631 uschar *initerror;
3632 if (opt_perl_startup == NULL)
3633 {
3634 expand_string_message = US"A setting of perl_startup is needed when "
3635 "using the Perl interpreter";
3636 goto EXPAND_FAILED;
3637 }
3638 DEBUG(D_any) debug_printf("Starting Perl interpreter\n");
3639 initerror = init_perl(opt_perl_startup);
3640 if (initerror != NULL)
3641 {
3642 expand_string_message =
3643 string_sprintf("error in perl_startup code: %s\n", initerror);
3644 goto EXPAND_FAILED;
3645 }
3646 opt_perl_started = TRUE;
3647 }
3648
3649 /* Call the function */
3650
3651 sub_arg[EXIM_PERL_MAX_ARGS + 1] = NULL;
3652 new_yield = call_perl_cat(yield, &size, &ptr, &expand_string_message,
3653 sub_arg[0], sub_arg + 1);
3654
3655 /* NULL yield indicates failure; if the message pointer has been set to
3656 NULL, the yield was undef, indicating a forced failure. Otherwise the
3657 message will indicate some kind of Perl error. */
3658
3659 if (new_yield == NULL)
3660 {
3661 if (expand_string_message == NULL)
3662 {
3663 expand_string_message =
3664 string_sprintf("Perl subroutine \"%s\" returned undef to force "
3665 "failure", sub_arg[0]);
3666 expand_string_forcedfail = TRUE;
3667 }
3668 goto EXPAND_FAILED;
3669 }
3670
3671 /* Yield succeeded. Ensure forcedfail is unset, just in case it got
3672 set during a callback from Perl. */
3673
3674 expand_string_forcedfail = FALSE;
3675 yield = new_yield;
3676 continue;
3677 }
3678 #endif /* EXIM_PERL */
3679
fffda43a
TK
3680 /* Transform email address to "prvs" scheme to use
3681 as BATV-signed return path */
3682
3683 case EITEM_PRVS:
3684 {
3685 uschar *sub_arg[3];
3686 uschar *p,*domain;
3687
3688 switch(read_subs(sub_arg, 3, 2, &s, skipping, TRUE, US"prvs"))
3689 {
3690 case 1: goto EXPAND_FAILED_CURLY;
3691 case 2:
3692 case 3: goto EXPAND_FAILED;
3693 }
3694
3695 /* If skipping, we don't actually do anything */
3696 if (skipping) continue;
3697
3698 /* sub_arg[0] is the address */
3699 domain = Ustrrchr(sub_arg[0],'@');
3700 if ( (domain == NULL) || (domain == sub_arg[0]) || (Ustrlen(domain) == 1) )
3701 {
cb9328de
PH
3702 expand_string_message = US"prvs first argument must be a qualified email address";
3703 goto EXPAND_FAILED;
3704 }
3705
3706 /* Calculate the hash. The second argument must be a single-digit
3707 key number, or unset. */
3708
3709 if (sub_arg[2] != NULL &&
3710 (!isdigit(sub_arg[2][0]) || sub_arg[2][1] != 0))
3711 {
3712 expand_string_message = US"prvs second argument must be a single digit";
fffda43a
TK
3713 goto EXPAND_FAILED;
3714 }
3715
fffda43a
TK
3716 p = prvs_hmac_sha1(sub_arg[0],sub_arg[1],sub_arg[2],prvs_daystamp(7));
3717 if (p == NULL)
3718 {
cb9328de 3719 expand_string_message = US"prvs hmac-sha1 conversion failed";
fffda43a
TK
3720 goto EXPAND_FAILED;
3721 }
3722
3723 /* Now separate the domain from the local part */
3724 *domain++ = '\0';
3725
3726 yield = string_cat(yield,&size,&ptr,US"prvs=",5);
fffda43a
TK
3727 string_cat(yield,&size,&ptr,(sub_arg[2] != NULL) ? sub_arg[2] : US"0", 1);
3728 string_cat(yield,&size,&ptr,prvs_daystamp(7),3);
3729 string_cat(yield,&size,&ptr,p,6);
a48ced90
TK
3730 string_cat(yield,&size,&ptr,US"=",1);
3731 string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0]));
fffda43a
TK
3732 string_cat(yield,&size,&ptr,US"@",1);
3733 string_cat(yield,&size,&ptr,domain,Ustrlen(domain));
3734
3735 continue;
3736 }
3737
3738 /* Check a prvs-encoded address for validity */
3739
3740 case EITEM_PRVSCHECK:
3741 {
3742 uschar *sub_arg[3];
3743 int mysize = 0, myptr = 0;
3744 const pcre *re;
3745 uschar *p;
72fdd6ae
PH
3746
3747 /* TF: Ugliness: We want to expand parameter 1 first, then set
fffda43a
TK
3748 up expansion variables that are used in the expansion of
3749 parameter 2. So we clone the string for the first
72fdd6ae
PH
3750 expansion, where we only expand parameter 1.
3751
3752 PH: Actually, that isn't necessary. The read_subs() function is
3753 designed to work this way for the ${if and ${lookup expansions. I've
3754 tidied the code.
3755 */
fffda43a
TK
3756
3757 /* Reset expansion variables */
3758 prvscheck_result = NULL;
3759 prvscheck_address = NULL;
3760 prvscheck_keynum = NULL;
3761
72fdd6ae 3762 switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs"))
fffda43a
TK
3763 {
3764 case 1: goto EXPAND_FAILED_CURLY;
3765 case 2:
3766 case 3: goto EXPAND_FAILED;
3767 }
3768
a48ced90 3769 re = regex_must_compile(US"^prvs\\=([0-9])([0-9]{3})([A-F0-9]{6})\\=(.+)\\@(.+)$",
fffda43a
TK
3770 TRUE,FALSE);
3771
72fdd6ae
PH
3772 if (regex_match_and_setup(re,sub_arg[0],0,-1))
3773 {
a48ced90
TK
3774 uschar *local_part = string_copyn(expand_nstring[4],expand_nlength[4]);
3775 uschar *key_num = string_copyn(expand_nstring[1],expand_nlength[1]);
3776 uschar *daystamp = string_copyn(expand_nstring[2],expand_nlength[2]);
3777 uschar *hash = string_copyn(expand_nstring[3],expand_nlength[3]);
fffda43a
TK
3778 uschar *domain = string_copyn(expand_nstring[5],expand_nlength[5]);
3779
3780 DEBUG(D_expand) debug_printf("prvscheck localpart: %s\n", local_part);
3781 DEBUG(D_expand) debug_printf("prvscheck key number: %s\n", key_num);
3782 DEBUG(D_expand) debug_printf("prvscheck daystamp: %s\n", daystamp);
3783 DEBUG(D_expand) debug_printf("prvscheck hash: %s\n", hash);
3784 DEBUG(D_expand) debug_printf("prvscheck domain: %s\n", domain);
3785
3786 /* Set up expansion variables */
3787 prvscheck_address = string_cat(NULL, &mysize, &myptr, local_part, Ustrlen(local_part));
2740a2ca 3788 string_cat(prvscheck_address,&mysize,&myptr,US"@",1);
fffda43a
TK
3789 string_cat(prvscheck_address,&mysize,&myptr,domain,Ustrlen(domain));
3790 prvscheck_address[myptr] = '\0';
3791 prvscheck_keynum = string_copy(key_num);
3792
72fdd6ae
PH
3793 /* Now expand the second argument */
3794 switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs"))
fffda43a
TK
3795 {
3796 case 1: goto EXPAND_FAILED_CURLY;
3797 case 2:
3798 case 3: goto EXPAND_FAILED;
3799 }
3800
fffda43a 3801 /* Now we have the key and can check the address. */
72fdd6ae
PH
3802
3803 p = prvs_hmac_sha1(prvscheck_address, sub_arg[0], prvscheck_keynum,
3804 daystamp);
3805
fffda43a
TK
3806 if (p == NULL)
3807 {
3808 expand_string_message = US"hmac-sha1 conversion failed";
3809 goto EXPAND_FAILED;
3810 }
3811
3812 DEBUG(D_expand) debug_printf("prvscheck: received hash is %s\n", hash);
3813 DEBUG(D_expand) debug_printf("prvscheck: own hash is %s\n", p);
72fdd6ae 3814
fffda43a
TK
3815 if (Ustrcmp(p,hash) == 0)
3816 {
3817 /* Success, valid BATV address. Now check the expiry date. */
3818 uschar *now = prvs_daystamp(0);
3819 unsigned int inow = 0,iexpire = 1;
3820
ff790e47
PH
3821 (void)sscanf(CS now,"%u",&inow);
3822 (void)sscanf(CS daystamp,"%u",&iexpire);
fffda43a
TK
3823
3824 /* When "iexpire" is < 7, a "flip" has occured.
3825 Adjust "inow" accordingly. */
3826 if ( (iexpire < 7) && (inow >= 993) ) inow = 0;
3827
686c36b7 3828 if (iexpire >= inow)
fffda43a
TK
3829 {
3830 prvscheck_result = US"1";
3831 DEBUG(D_expand) debug_printf("prvscheck: success, $pvrs_result set to 1\n");
3832 }
3833 else
3834 {
3835 prvscheck_result = NULL;
3836 DEBUG(D_expand) debug_printf("prvscheck: signature expired, $pvrs_result unset\n");
3837 }
3838 }
3839 else
3840 {
3841 prvscheck_result = NULL;
3842 DEBUG(D_expand) debug_printf("prvscheck: hash failure, $pvrs_result unset\n");
3843 }
72fdd6ae
PH
3844
3845 /* Now expand the final argument. We leave this till now so that
3846 it can include $prvscheck_result. */
3847
3848 switch(read_subs(sub_arg, 1, 0, &s, skipping, TRUE, US"prvs"))
3849 {
3850 case 1: goto EXPAND_FAILED_CURLY;
3851 case 2:
3852 case 3: goto EXPAND_FAILED;
3853 }
3854
3855 if (sub_arg[0] == NULL || *sub_arg[0] == '\0')
3856 yield = string_cat(yield,&size,&ptr,prvscheck_address,Ustrlen(prvscheck_address));
3857 else
3858 yield = string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0]));
3859
3860 /* Reset the "internal" variables afterwards, because they are in
3861 dynamic store that will be reclaimed if the expansion succeeded. */
3862
3863 prvscheck_address = NULL;
3864 prvscheck_keynum = NULL;
3865 }
fffda43a
TK
3866 else
3867 {
3868 /* Does not look like a prvs encoded address, return the empty string.
72fdd6ae
PH
3869 We need to make sure all subs are expanded first, so as to skip over
3870 the entire item. */
3871
5a03bd24 3872 switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"prvs"))
fffda43a
TK
3873 {
3874 case 1: goto EXPAND_FAILED_CURLY;
3875 case 2:
3876 case 3: goto EXPAND_FAILED;
3877 }
3878 }
3879
3880 continue;
3881 }
3882
059ec3d9
PH
3883 /* Handle "readfile" to insert an entire file */
3884
3885 case EITEM_READFILE:
3886 {
3887 FILE *f;
3888 uschar *sub_arg[2];
3889
3890 if ((expand_forbid & RDO_READFILE) != 0)
3891 {
3892 expand_string_message = US"file insertions are not permitted";
3893 goto EXPAND_FAILED;
3894 }
3895
3896 switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"readfile"))
3897 {
3898 case 1: goto EXPAND_FAILED_CURLY;
3899 case 2:
3900 case 3: goto EXPAND_FAILED;
3901 }
3902
3903 /* If skipping, we don't actually do anything */
3904
3905 if (skipping) continue;
3906
3907 /* Open the file and read it */
3908
3909 f = Ufopen(sub_arg[0], "rb");
3910 if (f == NULL)
3911 {
3912 expand_string_message = string_open_failed(errno, "%s", sub_arg[0]);
3913 goto EXPAND_FAILED;
3914 }
3915
3916 yield = cat_file(f, yield, &size, &ptr, sub_arg[1]);
f1e894f3 3917 (void)fclose(f);
059ec3d9
PH
3918 continue;
3919 }
3920
3921 /* Handle "readsocket" to insert data from a Unix domain socket */
3922
3923 case EITEM_READSOCK:
3924 {
3925 int fd;
3926 int timeout = 5;
3927 int save_ptr = ptr;
3928 FILE *f;
3929 struct sockaddr_un sockun; /* don't call this "sun" ! */
3930 uschar *arg;
3931 uschar *sub_arg[4];
3932
3933 if ((expand_forbid & RDO_READSOCK) != 0)
3934 {
3935 expand_string_message = US"socket insertions are not permitted";
3936 goto EXPAND_FAILED;
3937 }
3938
3939 /* Read up to 4 arguments, but don't do the end of item check afterwards,
3940 because there may be a string for expansion on failure. */
3941
3942 switch(read_subs(sub_arg, 4, 2, &s, skipping, FALSE, US"readsocket"))
3943 {
3944 case 1: goto EXPAND_FAILED_CURLY;
3945 case 2: /* Won't occur: no end check */
3946 case 3: goto EXPAND_FAILED;
3947 }
3948
3949 /* Sort out timeout, if given */
3950
3951 if (sub_arg[2] != NULL)
3952 {
3953 timeout = readconf_readtime(sub_arg[2], 0, FALSE);
3954 if (timeout < 0)
3955 {
3956 expand_string_message = string_sprintf("bad time value %s",
3957 sub_arg[2]);
3958 goto EXPAND_FAILED;
3959 }
3960 }
3961 else sub_arg[3] = NULL; /* No eol if no timeout */
3962
1cce3af8
PH
3963 /* If skipping, we don't actually do anything. Otherwise, arrange to
3964 connect to either an IP or a Unix socket. */
059ec3d9
PH
3965
3966 if (!skipping)
3967 {
1cce3af8 3968 /* Handle an IP (internet) domain */
059ec3d9 3969