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