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