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