Fix bug in readconf in diagnosing overflowing ints in 64-bit systems.
[exim.git] / src / src / readconf.c
1 /* $Cambridge: exim/src/src/readconf.c,v 1.31 2007/07/04 11:03:46 ph10 Exp $ */
2
3 /*************************************************
4 *     Exim - an Internet mail transport agent    *
5 *************************************************/
6
7 /* Copyright (c) University of Cambridge 1995 - 2007 */
8 /* See the file NOTICE for conditions of use and distribution. */
9
10 /* Functions for reading the configuration file, and for displaying
11 overall configuration values. Thanks to Brian Candler for the original
12 implementation of the conditional .ifdef etc. */
13
14 #include "exim.h"
15
16 #define CSTATE_STACK_SIZE 10
17
18
19 /* Structure for chain (stack) of .included files */
20
21 typedef struct config_file_item {
22   struct config_file_item *next;
23   uschar *filename;
24   FILE *file;
25   int lineno;
26 } config_file_item;
27
28 /* Structure of table of conditional words and their state transitions */
29
30 typedef struct cond_item {
31   uschar *name;
32   int    namelen;
33   int    action1;
34   int    action2;
35   int    pushpop;
36 } cond_item;
37
38 /* Structure of table of syslog facility names and values */
39
40 typedef struct syslog_fac_item {
41   uschar *name;
42   int    value;
43 } syslog_fac_item;
44
45
46 /* Static variables */
47
48 static config_file_item *config_file_stack = NULL;  /* For includes */
49
50 static uschar *syslog_facility_str  = NULL;
51 static uschar next_section[24];
52 static uschar time_buffer[24];
53
54 /* State variables for conditional loading (.ifdef / .else / .endif) */
55
56 static int cstate = 0;
57 static int cstate_stack_ptr = -1;
58 static int cstate_stack[CSTATE_STACK_SIZE];
59
60 /* Table of state transitions for handling conditional inclusions. There are
61 four possible state transitions:
62
63   .ifdef true
64   .ifdef false
65   .elifdef true  (or .else)
66   .elifdef false
67
68 .endif just causes the previous cstate to be popped off the stack */
69
70 static int next_cstate[3][4] =
71   {
72   /* State 0: reading from file, or reading until next .else or .endif */
73   { 0, 1, 2, 2 },
74   /* State 1: condition failed, skipping until next .else or .endif */
75   { 2, 2, 0, 1 },
76   /* State 2: skipping until .endif */
77   { 2, 2, 2, 2 },
78   };
79
80 /* Table of conditionals and the states to set. For each name, there are four
81 values: the length of the name (to save computing it each time), the state to
82 set if a macro was found in the line, the state to set if a macro was not found
83 in the line, and a stack manipulation setting which is:
84
85   -1   pull state value off the stack
86    0   don't alter the stack
87   +1   push value onto stack, before setting new state
88 */
89
90 static cond_item cond_list[] = {
91   { US"ifdef",    5, 0, 1,  1 },
92   { US"ifndef",   6, 1, 0,  1 },
93   { US"elifdef",  7, 2, 3,  0 },
94   { US"elifndef", 8, 3, 2,  0 },
95   { US"else",     4, 2, 2,  0 },
96   { US"endif",    5, 0, 0, -1 }
97 };
98
99 static int cond_list_size = sizeof(cond_list)/sizeof(cond_item);
100
101 /* Table of syslog facility names and their values */
102
103 static syslog_fac_item syslog_list[] = {
104   { US"mail",   LOG_MAIL },
105   { US"user",   LOG_USER },
106   { US"news",   LOG_NEWS },
107   { US"uucp",   LOG_UUCP },
108   { US"local0", LOG_LOCAL0 },
109   { US"local1", LOG_LOCAL1 },
110   { US"local2", LOG_LOCAL2 },
111   { US"local3", LOG_LOCAL3 },
112   { US"local4", LOG_LOCAL4 },
113   { US"local5", LOG_LOCAL5 },
114   { US"local6", LOG_LOCAL6 },
115   { US"local7", LOG_LOCAL7 },
116   { US"daemon", LOG_DAEMON }
117 };
118
119 static int syslog_list_size = sizeof(syslog_list)/sizeof(syslog_fac_item);
120
121
122
123
124 /*************************************************
125 *           Main configuration options           *
126 *************************************************/
127
128 /* The list of options that can be set in the main configuration file. This
129 must be in alphabetic order because it is searched by binary chop. */
130
131 static optionlist optionlist_config[] = {
132   { "*set_exim_group",          opt_bool|opt_hidden, &exim_gid_set },
133   { "*set_exim_user",           opt_bool|opt_hidden, &exim_uid_set },
134   { "*set_system_filter_group", opt_bool|opt_hidden, &system_filter_gid_set },
135   { "*set_system_filter_user",  opt_bool|opt_hidden, &system_filter_uid_set },
136   { "accept_8bitmime",          opt_bool,        &accept_8bitmime },
137   { "acl_not_smtp",             opt_stringptr,   &acl_not_smtp },
138 #ifdef WITH_CONTENT_SCAN
139   { "acl_not_smtp_mime",        opt_stringptr,   &acl_not_smtp_mime },
140 #endif
141   { "acl_not_smtp_start",       opt_stringptr,   &acl_not_smtp_start },
142   { "acl_smtp_auth",            opt_stringptr,   &acl_smtp_auth },
143   { "acl_smtp_connect",         opt_stringptr,   &acl_smtp_connect },
144   { "acl_smtp_data",            opt_stringptr,   &acl_smtp_data },
145   { "acl_smtp_etrn",            opt_stringptr,   &acl_smtp_etrn },
146   { "acl_smtp_expn",            opt_stringptr,   &acl_smtp_expn },
147   { "acl_smtp_helo",            opt_stringptr,   &acl_smtp_helo },
148   { "acl_smtp_mail",            opt_stringptr,   &acl_smtp_mail },
149   { "acl_smtp_mailauth",        opt_stringptr,   &acl_smtp_mailauth },
150 #ifdef WITH_CONTENT_SCAN
151   { "acl_smtp_mime",            opt_stringptr,   &acl_smtp_mime },
152 #endif
153   { "acl_smtp_predata",         opt_stringptr,   &acl_smtp_predata },
154   { "acl_smtp_quit",            opt_stringptr,   &acl_smtp_quit },
155   { "acl_smtp_rcpt",            opt_stringptr,   &acl_smtp_rcpt },
156 #ifdef SUPPORT_TLS
157   { "acl_smtp_starttls",        opt_stringptr,   &acl_smtp_starttls },
158 #endif
159   { "acl_smtp_vrfy",            opt_stringptr,   &acl_smtp_vrfy },
160   { "admin_groups",             opt_gidlist,     &admin_groups },
161   { "allow_domain_literals",    opt_bool,        &allow_domain_literals },
162   { "allow_mx_to_ip",           opt_bool,        &allow_mx_to_ip },
163   { "allow_utf8_domains",       opt_bool,        &allow_utf8_domains },
164   { "auth_advertise_hosts",     opt_stringptr,   &auth_advertise_hosts },
165   { "auto_thaw",                opt_time,        &auto_thaw },
166 #ifdef WITH_CONTENT_SCAN
167   { "av_scanner",               opt_stringptr,   &av_scanner },
168 #endif
169   { "bi_command",               opt_stringptr,   &bi_command },
170 #ifdef EXPERIMENTAL_BRIGHTMAIL
171   { "bmi_config_file",          opt_stringptr,   &bmi_config_file },
172 #endif
173   { "bounce_message_file",      opt_stringptr,   &bounce_message_file },
174   { "bounce_message_text",      opt_stringptr,   &bounce_message_text },
175   { "bounce_return_body",       opt_bool,        &bounce_return_body },
176   { "bounce_return_message",    opt_bool,        &bounce_return_message },
177   { "bounce_return_size_limit", opt_mkint,       &bounce_return_size_limit },
178   { "bounce_sender_authentication",opt_stringptr,&bounce_sender_authentication },
179   { "callout_domain_negative_expire", opt_time,  &callout_cache_domain_negative_expire },
180   { "callout_domain_positive_expire", opt_time,  &callout_cache_domain_positive_expire },
181   { "callout_negative_expire",  opt_time,        &callout_cache_negative_expire },
182   { "callout_positive_expire",  opt_time,        &callout_cache_positive_expire },
183   { "callout_random_local_part",opt_stringptr,   &callout_random_local_part },
184   { "check_log_inodes",         opt_int,         &check_log_inodes },
185   { "check_log_space",          opt_Kint,        &check_log_space },
186   { "check_rfc2047_length",     opt_bool,        &check_rfc2047_length },
187   { "check_spool_inodes",       opt_int,         &check_spool_inodes },
188   { "check_spool_space",        opt_Kint,        &check_spool_space },
189   { "daemon_smtp_port",         opt_stringptr|opt_hidden, &daemon_smtp_port },
190   { "daemon_smtp_ports",        opt_stringptr,   &daemon_smtp_port },
191   { "daemon_startup_retries",   opt_int,         &daemon_startup_retries },
192   { "daemon_startup_sleep",     opt_time,        &daemon_startup_sleep },
193   { "delay_warning",            opt_timelist,    &delay_warning },
194   { "delay_warning_condition",  opt_stringptr,   &delay_warning_condition },
195   { "deliver_drop_privilege",   opt_bool,        &deliver_drop_privilege },
196   { "deliver_queue_load_max",   opt_fixed,       &deliver_queue_load_max },
197   { "delivery_date_remove",     opt_bool,        &delivery_date_remove },
198 #ifdef ENABLE_DISABLE_FSYNC
199   { "disable_fsync",            opt_bool,        &disable_fsync },
200 #endif
201   { "disable_ipv6",             opt_bool,        &disable_ipv6 },
202   { "dns_again_means_nonexist", opt_stringptr,   &dns_again_means_nonexist },
203   { "dns_check_names_pattern",  opt_stringptr,   &check_dns_names_pattern },
204   { "dns_csa_search_limit",     opt_int,         &dns_csa_search_limit },
205   { "dns_csa_use_reverse",      opt_bool,        &dns_csa_use_reverse },
206   { "dns_ipv4_lookup",          opt_stringptr,   &dns_ipv4_lookup },
207   { "dns_retrans",              opt_time,        &dns_retrans },
208   { "dns_retry",                opt_int,         &dns_retry },
209  /* This option is now a no-op, retained for compability */
210   { "drop_cr",                  opt_bool,        &drop_cr },
211 /*********************************************************/
212   { "dsn_from",                 opt_stringptr,   &dsn_from },
213   { "envelope_to_remove",       opt_bool,        &envelope_to_remove },
214   { "errors_copy",              opt_stringptr,   &errors_copy },
215   { "errors_reply_to",          opt_stringptr,   &errors_reply_to },
216   { "exim_group",               opt_gid,         &exim_gid },
217   { "exim_path",                opt_stringptr,   &exim_path },
218   { "exim_user",                opt_uid,         &exim_uid },
219   { "extra_local_interfaces",   opt_stringptr,   &extra_local_interfaces },
220   { "extract_addresses_remove_arguments", opt_bool, &extract_addresses_remove_arguments },
221   { "finduser_retries",         opt_int,         &finduser_retries },
222   { "freeze_tell",              opt_stringptr,   &freeze_tell },
223   { "gecos_name",               opt_stringptr,   &gecos_name },
224   { "gecos_pattern",            opt_stringptr,   &gecos_pattern },
225 #ifdef SUPPORT_TLS
226   { "gnutls_require_kx",        opt_stringptr,   &gnutls_require_kx },
227   { "gnutls_require_mac",       opt_stringptr,   &gnutls_require_mac },
228   { "gnutls_require_protocols", opt_stringptr,   &gnutls_require_proto },
229 #endif
230   { "header_line_maxsize",      opt_int,         &header_line_maxsize },
231   { "header_maxsize",           opt_int,         &header_maxsize },
232   { "headers_charset",          opt_stringptr,   &headers_charset },
233   { "helo_accept_junk_hosts",   opt_stringptr,   &helo_accept_junk_hosts },
234   { "helo_allow_chars",         opt_stringptr,   &helo_allow_chars },
235   { "helo_lookup_domains",      opt_stringptr,   &helo_lookup_domains },
236   { "helo_try_verify_hosts",    opt_stringptr,   &helo_try_verify_hosts },
237   { "helo_verify_hosts",        opt_stringptr,   &helo_verify_hosts },
238   { "hold_domains",             opt_stringptr,   &hold_domains },
239   { "host_lookup",              opt_stringptr,   &host_lookup },
240   { "host_lookup_order",        opt_stringptr,   &host_lookup_order },
241   { "host_reject_connection",   opt_stringptr,   &host_reject_connection },
242   { "hosts_connection_nolog",   opt_stringptr,   &hosts_connection_nolog },
243   { "hosts_treat_as_local",     opt_stringptr,   &hosts_treat_as_local },
244 #ifdef LOOKUP_IBASE
245   { "ibase_servers",            opt_stringptr,   &ibase_servers },
246 #endif
247   { "ignore_bounce_errors_after", opt_time,      &ignore_bounce_errors_after },
248   { "ignore_fromline_hosts",    opt_stringptr,   &ignore_fromline_hosts },
249   { "ignore_fromline_local",    opt_bool,        &ignore_fromline_local },
250   { "keep_malformed",           opt_time,        &keep_malformed },
251 #ifdef LOOKUP_LDAP
252   { "ldap_default_servers",     opt_stringptr,   &eldap_default_servers },
253   { "ldap_version",             opt_int,         &eldap_version },
254 #endif
255   { "local_from_check",         opt_bool,        &local_from_check },
256   { "local_from_prefix",        opt_stringptr,   &local_from_prefix },
257   { "local_from_suffix",        opt_stringptr,   &local_from_suffix },
258   { "local_interfaces",         opt_stringptr,   &local_interfaces },
259   { "local_scan_timeout",       opt_time,        &local_scan_timeout },
260   { "local_sender_retain",      opt_bool,        &local_sender_retain },
261   { "localhost_number",         opt_stringptr,   &host_number_string },
262   { "log_file_path",            opt_stringptr,   &log_file_path },
263   { "log_selector",             opt_stringptr,   &log_selector_string },
264   { "log_timezone",             opt_bool,        &log_timezone },
265   { "lookup_open_max",          opt_int,         &lookup_open_max },
266   { "max_username_length",      opt_int,         &max_username_length },
267   { "message_body_visible",     opt_mkint,       &message_body_visible },
268   { "message_id_header_domain", opt_stringptr,   &message_id_domain },
269   { "message_id_header_text",   opt_stringptr,   &message_id_text },
270   { "message_logs",             opt_bool,        &message_logs },
271   { "message_size_limit",       opt_stringptr,   &message_size_limit },
272 #ifdef SUPPORT_MOVE_FROZEN_MESSAGES
273   { "move_frozen_messages",     opt_bool,        &move_frozen_messages },
274 #endif
275   { "mua_wrapper",              opt_bool,        &mua_wrapper },
276 #ifdef LOOKUP_MYSQL
277   { "mysql_servers",            opt_stringptr,   &mysql_servers },
278 #endif
279   { "never_users",              opt_uidlist,     &never_users },
280 #ifdef LOOKUP_ORACLE
281   { "oracle_servers",           opt_stringptr,   &oracle_servers },
282 #endif
283   { "percent_hack_domains",     opt_stringptr,   &percent_hack_domains },
284 #ifdef EXIM_PERL
285   { "perl_at_start",            opt_bool,        &opt_perl_at_start },
286   { "perl_startup",             opt_stringptr,   &opt_perl_startup },
287 #endif
288 #ifdef LOOKUP_PGSQL
289   { "pgsql_servers",            opt_stringptr,   &pgsql_servers },
290 #endif
291   { "pid_file_path",            opt_stringptr,   &pid_file_path },
292   { "pipelining_advertise_hosts", opt_stringptr, &pipelining_advertise_hosts },
293   { "preserve_message_logs",    opt_bool,        &preserve_message_logs },
294   { "primary_hostname",         opt_stringptr,   &primary_hostname },
295   { "print_topbitchars",        opt_bool,        &print_topbitchars },
296   { "process_log_path",         opt_stringptr,   &process_log_path },
297   { "prod_requires_admin",      opt_bool,        &prod_requires_admin },
298   { "qualify_domain",           opt_stringptr,   &qualify_domain_sender },
299   { "qualify_recipient",        opt_stringptr,   &qualify_domain_recipient },
300   { "queue_domains",            opt_stringptr,   &queue_domains },
301   { "queue_list_requires_admin",opt_bool,        &queue_list_requires_admin },
302   { "queue_only",               opt_bool,        &queue_only },
303   { "queue_only_file",          opt_stringptr,   &queue_only_file },
304   { "queue_only_load",          opt_fixed,       &queue_only_load },
305   { "queue_only_load_latch",    opt_bool,        &queue_only_load_latch },
306   { "queue_only_override",      opt_bool,        &queue_only_override },
307   { "queue_run_in_order",       opt_bool,        &queue_run_in_order },
308   { "queue_run_max",            opt_int,         &queue_run_max },
309   { "queue_smtp_domains",       opt_stringptr,   &queue_smtp_domains },
310   { "receive_timeout",          opt_time,        &receive_timeout },
311   { "received_header_text",     opt_stringptr,   &received_header_text },
312   { "received_headers_max",     opt_int,         &received_headers_max },
313   { "recipient_unqualified_hosts", opt_stringptr, &recipient_unqualified_hosts },
314   { "recipients_max",           opt_int,         &recipients_max },
315   { "recipients_max_reject",    opt_bool,        &recipients_max_reject },
316   { "remote_max_parallel",      opt_int,         &remote_max_parallel },
317   { "remote_sort_domains",      opt_stringptr,   &remote_sort_domains },
318   { "retry_data_expire",        opt_time,        &retry_data_expire },
319   { "retry_interval_max",       opt_time,        &retry_interval_max },
320   { "return_path_remove",       opt_bool,        &return_path_remove },
321   { "return_size_limit",        opt_mkint|opt_hidden, &bounce_return_size_limit },
322   { "rfc1413_hosts",            opt_stringptr,   &rfc1413_hosts },
323   { "rfc1413_query_timeout",    opt_time,        &rfc1413_query_timeout },
324   { "sender_unqualified_hosts", opt_stringptr,   &sender_unqualified_hosts },
325   { "smtp_accept_keepalive",    opt_bool,        &smtp_accept_keepalive },
326   { "smtp_accept_max",          opt_int,         &smtp_accept_max },
327   { "smtp_accept_max_nonmail",  opt_int,         &smtp_accept_max_nonmail },
328   { "smtp_accept_max_nonmail_hosts", opt_stringptr, &smtp_accept_max_nonmail_hosts },
329   { "smtp_accept_max_per_connection", opt_int,   &smtp_accept_max_per_connection },
330   { "smtp_accept_max_per_host", opt_stringptr,   &smtp_accept_max_per_host },
331   { "smtp_accept_queue",        opt_int,         &smtp_accept_queue },
332   { "smtp_accept_queue_per_connection", opt_int, &smtp_accept_queue_per_connection },
333   { "smtp_accept_reserve",      opt_int,         &smtp_accept_reserve },
334   { "smtp_active_hostname",     opt_stringptr,   &raw_active_hostname },
335   { "smtp_banner",              opt_stringptr,   &smtp_banner },
336   { "smtp_check_spool_space",   opt_bool,        &smtp_check_spool_space },
337   { "smtp_connect_backlog",     opt_int,         &smtp_connect_backlog },
338   { "smtp_enforce_sync",        opt_bool,        &smtp_enforce_sync },
339   { "smtp_etrn_command",        opt_stringptr,   &smtp_etrn_command },
340   { "smtp_etrn_serialize",      opt_bool,        &smtp_etrn_serialize },
341   { "smtp_load_reserve",        opt_fixed,       &smtp_load_reserve },
342   { "smtp_max_synprot_errors",  opt_int,         &smtp_max_synprot_errors },
343   { "smtp_max_unknown_commands",opt_int,         &smtp_max_unknown_commands },
344   { "smtp_ratelimit_hosts",     opt_stringptr,   &smtp_ratelimit_hosts },
345   { "smtp_ratelimit_mail",      opt_stringptr,   &smtp_ratelimit_mail },
346   { "smtp_ratelimit_rcpt",      opt_stringptr,   &smtp_ratelimit_rcpt },
347   { "smtp_receive_timeout",     opt_time,        &smtp_receive_timeout },
348   { "smtp_reserve_hosts",       opt_stringptr,   &smtp_reserve_hosts },
349   { "smtp_return_error_details",opt_bool,        &smtp_return_error_details },
350 #ifdef WITH_CONTENT_SCAN
351   { "spamd_address",            opt_stringptr,   &spamd_address },
352 #endif
353   { "split_spool_directory",    opt_bool,        &split_spool_directory },
354   { "spool_directory",          opt_stringptr,   &spool_directory },
355 #ifdef LOOKUP_SQLITE
356   { "sqlite_lock_timeout",      opt_int,         &sqlite_lock_timeout },
357 #endif
358 #ifdef EXPERIMENTAL_SRS
359   { "srs_config",               opt_stringptr,   &srs_config },
360   { "srs_hashlength",           opt_int,         &srs_hashlength },
361   { "srs_hashmin",              opt_int,         &srs_hashmin },
362   { "srs_maxage",               opt_int,         &srs_maxage },
363   { "srs_secrets",              opt_stringptr,   &srs_secrets },
364   { "srs_usehash",              opt_bool,        &srs_usehash },
365   { "srs_usetimestamp",         opt_bool,        &srs_usetimestamp },
366 #endif
367   { "strict_acl_vars",          opt_bool,        &strict_acl_vars },
368   { "strip_excess_angle_brackets", opt_bool,     &strip_excess_angle_brackets },
369   { "strip_trailing_dot",       opt_bool,        &strip_trailing_dot },
370   { "syslog_duplication",       opt_bool,        &syslog_duplication },
371   { "syslog_facility",          opt_stringptr,   &syslog_facility_str },
372   { "syslog_processname",       opt_stringptr,   &syslog_processname },
373   { "syslog_timestamp",         opt_bool,        &syslog_timestamp },
374   { "system_filter",            opt_stringptr,   &system_filter },
375   { "system_filter_directory_transport", opt_stringptr,&system_filter_directory_transport },
376   { "system_filter_file_transport",opt_stringptr,&system_filter_file_transport },
377   { "system_filter_group",      opt_gid,         &system_filter_gid },
378   { "system_filter_pipe_transport",opt_stringptr,&system_filter_pipe_transport },
379   { "system_filter_reply_transport",opt_stringptr,&system_filter_reply_transport },
380   { "system_filter_user",       opt_uid,         &system_filter_uid },
381   { "tcp_nodelay",              opt_bool,        &tcp_nodelay },
382   { "timeout_frozen_after",     opt_time,        &timeout_frozen_after },
383   { "timezone",                 opt_stringptr,   &timezone_string },
384 #ifdef SUPPORT_TLS
385   { "tls_advertise_hosts",      opt_stringptr,   &tls_advertise_hosts },
386   { "tls_certificate",          opt_stringptr,   &tls_certificate },
387   { "tls_crl",                  opt_stringptr,   &tls_crl },
388   { "tls_dhparam",              opt_stringptr,   &tls_dhparam },
389   { "tls_on_connect_ports",     opt_stringptr,   &tls_on_connect_ports },
390   { "tls_privatekey",           opt_stringptr,   &tls_privatekey },
391   { "tls_remember_esmtp",       opt_bool,        &tls_remember_esmtp },
392   { "tls_require_ciphers",      opt_stringptr,   &tls_require_ciphers },
393   { "tls_try_verify_hosts",     opt_stringptr,   &tls_try_verify_hosts },
394   { "tls_verify_certificates",  opt_stringptr,   &tls_verify_certificates },
395   { "tls_verify_hosts",         opt_stringptr,   &tls_verify_hosts },
396 #endif
397   { "trusted_groups",           opt_gidlist,     &trusted_groups },
398   { "trusted_users",            opt_uidlist,     &trusted_users },
399   { "unknown_login",            opt_stringptr,   &unknown_login },
400   { "unknown_username",         opt_stringptr,   &unknown_username },
401   { "untrusted_set_sender",     opt_stringptr,   &untrusted_set_sender },
402   { "uucp_from_pattern",        opt_stringptr,   &uucp_from_pattern },
403   { "uucp_from_sender",         opt_stringptr,   &uucp_from_sender },
404   { "warn_message_file",        opt_stringptr,   &warn_message_file },
405   { "write_rejectlog",          opt_bool,        &write_rejectlog }
406 };
407
408 static int optionlist_config_size =
409   sizeof(optionlist_config)/sizeof(optionlist);
410
411
412
413 /*************************************************
414 *         Find the name of an option             *
415 *************************************************/
416
417 /* This function is to aid debugging. Various functions take arguments that are
418 pointer variables in the options table or in option tables for various drivers.
419 For debugging output, it is useful to be able to find the name of the option
420 which is currently being processed. This function finds it, if it exists, by
421 searching the table(s).
422
423 Arguments:   a value that is presumed to be in the table above
424 Returns:     the option name, or an empty string
425 */
426
427 uschar *
428 readconf_find_option(void *p)
429 {
430 int i;
431 router_instance *r;
432 transport_instance *t;
433
434 for (i = 0; i < optionlist_config_size; i++)
435   if (p == optionlist_config[i].value) return US optionlist_config[i].name;
436
437 for (r = routers; r != NULL; r = r->next)
438   {
439   router_info *ri = r->info;
440   for (i = 0; i < ri->options_count[0]; i++)
441     {
442     if ((ri->options[i].type & opt_mask) != opt_stringptr) continue;
443     if (p == (char *)(r->options_block) + (long int)(ri->options[i].value))
444       return US ri->options[i].name;
445     }
446   }
447
448 for (t = transports; t != NULL; t = t->next)
449   {
450   transport_info *ti = t->info;
451   for (i = 0; i < ti->options_count[0]; i++)
452     {
453     if ((ti->options[i].type & opt_mask) != opt_stringptr) continue;
454     if (p == (char *)(t->options_block) + (long int)(ti->options[i].value))
455       return US ti->options[i].name;
456     }
457   }
458
459 return US"";
460 }
461
462
463
464
465 /*************************************************
466 *       Deal with an assignment to a macro       *
467 *************************************************/
468
469 /* This function is called when a line that starts with an upper case letter is
470 encountered. The argument "line" should contain a complete logical line, and
471 start with the first letter of the macro name. The macro name and the
472 replacement text are extracted and stored. Redefinition of existing,
473 non-command line, macros is permitted using '==' instead of '='.
474
475 Arguments:
476   s            points to the start of the logical line
477
478 Returns:       nothing
479 */
480
481 static void
482 read_macro_assignment(uschar *s)
483 {
484 uschar name[64];
485 int namelen = 0;
486 BOOL redef = FALSE;
487 macro_item *m;
488 macro_item *mlast = NULL;
489
490 while (isalnum(*s) || *s == '_')
491   {
492   if (namelen >= sizeof(name) - 1)
493     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
494       "macro name too long (maximum is %d characters)", sizeof(name) - 1);
495   name[namelen++] = *s++;
496   }
497 name[namelen] = 0;
498
499 while (isspace(*s)) s++;
500 if (*s++ != '=')
501   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "malformed macro definition");
502
503 if (*s == '=')
504   {
505   redef = TRUE;
506   s++;
507   }
508 while (isspace(*s)) s++;
509
510 /* If an existing macro of the same name was defined on the command line, we
511 just skip this definition. It's an error to attempt to redefine a macro without
512 redef set to TRUE, or to redefine a macro when it hasn't been defined earlier.
513 It is also an error to define a macro whose name begins with the name of a
514 previously defined macro. Note: it is documented that the other way round
515 works. */
516
517 for (m = macros; m != NULL; m = m->next)
518   {
519   int len = Ustrlen(m->name);
520
521   if (Ustrcmp(m->name, name) == 0)
522     {
523     if (!m->command_line && !redef)
524       log_write(0, LOG_CONFIG|LOG_PANIC_DIE, "macro \"%s\" is already "
525        "defined (use \"==\" if you want to redefine it", name);
526     break;
527     }
528
529   if (len < namelen && Ustrstr(name, m->name) != NULL)
530     log_write(0, LOG_CONFIG|LOG_PANIC_DIE, "\"%s\" cannot be defined as "
531       "a macro because previously defined macro \"%s\" is a substring",
532       name, m->name);
533
534   /* We cannot have this test, because it is documented that a substring
535   macro is permitted (there is even an example).
536   *
537   * if (len > namelen && Ustrstr(m->name, name) != NULL)
538   *   log_write(0, LOG_CONFIG|LOG_PANIC_DIE, "\"%s\" cannot be defined as "
539   *     "a macro because it is a substring of previously defined macro \"%s\"",
540   *     name, m->name);
541   */
542
543   mlast = m;
544   }
545
546 /* Check for an overriding command-line definition. */
547
548 if (m != NULL && m->command_line) return;
549
550 /* Redefinition must refer to an existing macro. */
551
552 if (redef)
553   {
554   if (m == NULL)
555     log_write(0, LOG_CONFIG|LOG_PANIC_DIE, "can't redefine an undefined macro "
556       "\"%s\"", name);
557   }
558
559 /* We have a new definition. The macro_item structure includes a final vector
560 called "name" which is one byte long. Thus, adding "namelen" gives us enough
561 room to store the "name" string. */
562
563 else
564   {
565   m = store_get(sizeof(macro_item) + namelen);
566   if (macros == NULL) macros = m; else mlast->next = m;
567   Ustrncpy(m->name, name, namelen);
568   m->name[namelen] = 0;
569   m->next = NULL;
570   m->command_line = FALSE;
571   }
572
573 /* Set the value of the new or redefined macro */
574
575 m->replacement = string_copy(s);
576 }
577
578
579
580
581
582 /*************************************************
583 *            Read configuration line             *
584 *************************************************/
585
586 /* A logical line of text is read from the configuration file into the big
587 buffer, taking account of macros, .includes, and continuations. The size of
588 big_buffer is increased if necessary. The count of configuration lines is
589 maintained. Physical input lines starting with # (ignoring leading white space,
590 and after macro replacement) and empty logical lines are always ignored.
591 Leading and trailing spaces are removed.
592
593 If we hit a line of the form "begin xxxx", the xxxx is placed in the
594 next_section vector, and the function returns NULL, indicating the end of a
595 configuration section. On end-of-file, NULL is returned with next_section
596 empty.
597
598 Arguments:      none
599
600 Returns:        a pointer to the first non-blank in the line,
601                 or NULL if eof or end of section is reached
602 */
603
604 static uschar *
605 get_config_line(void)
606 {
607 int startoffset = 0;         /* To first non-blank char in logical line */
608 int len = 0;                 /* Of logical line so far */
609 int newlen;
610 uschar *s, *ss;
611 macro_item *m;
612 BOOL macro_found;
613
614 /* Loop for handling continuation lines, skipping comments, and dealing with
615 .include files. */
616
617 for (;;)
618   {
619   if (Ufgets(big_buffer+len, big_buffer_size-len, config_file) == NULL)
620     {
621     if (config_file_stack != NULL)    /* EOF inside .include */
622       {
623       (void)fclose(config_file);
624       config_file = config_file_stack->file;
625       config_filename = config_file_stack->filename;
626       config_lineno = config_file_stack->lineno;
627       config_file_stack = config_file_stack->next;
628       continue;
629       }
630
631     /* EOF at top level */
632
633     if (cstate_stack_ptr >= 0)
634       log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
635         "Unexpected end of configuration file: .endif missing");
636
637     if (len != 0) break;        /* EOF after continuation */
638     next_section[0] = 0;        /* EOF at start of logical line */
639     return NULL;
640     }
641
642   config_lineno++;
643   newlen = len + Ustrlen(big_buffer + len);
644
645   /* Handle pathologically long physical lines - yes, it did happen - by
646   extending big_buffer at this point. The code also copes with very long
647   logical lines. */
648
649   while (newlen == big_buffer_size - 1 && big_buffer[newlen - 1] != '\n')
650     {
651     uschar *newbuffer;
652     big_buffer_size += BIG_BUFFER_SIZE;
653     newbuffer = store_malloc(big_buffer_size);
654
655     /* This use of strcpy is OK because we know that the string in the old
656     buffer is shorter than the new buffer. */
657
658     Ustrcpy(newbuffer, big_buffer);
659     store_free(big_buffer);
660     big_buffer = newbuffer;
661     if (Ufgets(big_buffer+newlen, big_buffer_size-newlen, config_file) == NULL)
662       break;
663     newlen += Ustrlen(big_buffer + newlen);
664     }
665
666   /* Find the true start of the physical line - leading spaces are always
667   ignored. */
668
669   ss = big_buffer + len;
670   while (isspace(*ss)) ss++;
671
672   /* Process the physical line for macros. If this is the start of the logical
673   line, skip over initial text at the start of the line if it starts with an
674   upper case character followed by a sequence of name characters and an equals
675   sign, because that is the definition of a new macro, and we don't do
676   replacement therein. */
677
678   s = ss;
679   if (len == 0 && isupper(*s))
680     {
681     while (isalnum(*s) || *s == '_') s++;
682     while (isspace(*s)) s++;
683     if (*s != '=') s = ss;          /* Not a macro definition */
684     }
685
686   /* For each defined macro, scan the line (from after XXX= if present),
687   replacing all occurrences of the macro. */
688
689   macro_found = FALSE;
690   for (m = macros; m != NULL; m = m->next)
691     {
692     uschar *p, *pp;
693     uschar *t = s;
694
695     while ((p = Ustrstr(t, m->name)) != NULL)
696       {
697       int moveby;
698       int namelen = Ustrlen(m->name);
699       int replen = Ustrlen(m->replacement);
700
701       /* Expand the buffer if necessary */
702
703       while (newlen - namelen + replen + 1 > big_buffer_size)
704         {
705         int newsize = big_buffer_size + BIG_BUFFER_SIZE;
706         uschar *newbuffer = store_malloc(newsize);
707         memcpy(newbuffer, big_buffer, newlen + 1);
708         p = newbuffer  + (p - big_buffer);
709         s = newbuffer  + (s - big_buffer);
710         ss = newbuffer + (ss - big_buffer);
711         t = newbuffer  + (t - big_buffer);
712         big_buffer_size = newsize;
713         store_free(big_buffer);
714         big_buffer = newbuffer;
715         }
716
717       /* Shuffle the remaining characters up or down in the buffer before
718       copying in the replacement text. Don't rescan the replacement for this
719       same macro. */
720
721       pp = p + namelen;
722       moveby = replen - namelen;
723       if (moveby != 0)
724         {
725         memmove(p + replen, pp, (big_buffer + newlen) - pp + 1);
726         newlen += moveby;
727         }
728       Ustrncpy(p, m->replacement, replen);
729       t = p + replen;
730       macro_found = TRUE;
731       }
732     }
733
734   /* An empty macro replacement at the start of a line could mean that ss no
735   longer points to the first non-blank character. */
736
737   while (isspace(*ss)) ss++;
738
739   /* Check for comment lines - these are physical lines. */
740
741   if (*ss == '#') continue;
742
743   /* Handle conditionals, which are also applied to physical lines. Conditions
744   are of the form ".ifdef ANYTEXT" and are treated as true if any macro
745   expansion occured on the rest of the line. A preliminary test for the leading
746   '.' saves effort on most lines. */
747
748   if (*ss == '.')
749     {
750     int i;
751
752     /* Search the list of conditional directives */
753
754     for (i = 0; i < cond_list_size; i++)
755       {
756       int n;
757       cond_item *c = cond_list+i;
758       if (Ustrncmp(ss+1, c->name, c->namelen) != 0) continue;
759
760       /* The following character must be white space or end of string */
761
762       n = ss[1 + c->namelen];
763       if (n != ' ' && n != 't' && n != '\n' && n != 0) break;
764
765       /* .ifdef and .ifndef push the current state onto the stack, then set
766       a new one from the table. Stack overflow is an error */
767
768       if (c->pushpop > 0)
769         {
770         if (cstate_stack_ptr >= CSTATE_STACK_SIZE - 1)
771           log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
772             ".%s nested too deeply", c->name);
773         cstate_stack[++cstate_stack_ptr] = cstate;
774         cstate = next_cstate[cstate][macro_found? c->action1 : c->action2];
775         }
776
777       /* For any of the others, stack underflow is an error. The next state
778       comes either from the stack (.endif) or from the table. */
779
780       else
781         {
782         if (cstate_stack_ptr < 0)
783           log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
784             ".%s without matching .ifdef", c->name);
785         cstate = (c->pushpop < 0)? cstate_stack[cstate_stack_ptr--] :
786           next_cstate[cstate][macro_found? c->action1 : c->action2];
787         }
788
789       /* Having dealt with a directive, break the loop */
790
791       break;
792       }
793
794     /* If we have handled a conditional directive, continue with the next
795     physical line. Otherwise, fall through. */
796
797     if (i < cond_list_size) continue;
798     }
799
800   /* If the conditional state is not 0 (actively using these lines), ignore
801   this input line. */
802
803   if (cstate != 0) continue;  /* Conditional skip */
804
805   /* Handle .include lines - these are also physical lines. */
806
807   if (Ustrncmp(ss, ".include", 8) == 0 &&
808        (isspace(ss[8]) ||
809          (Ustrncmp(ss+8, "_if_exists", 10) == 0 && isspace(ss[18]))))
810     {
811     uschar *t;
812     int include_if_exists = isspace(ss[8])? 0 : 10;
813     config_file_item *save;
814     struct stat statbuf;
815
816     ss += 9 + include_if_exists;
817     while (isspace(*ss)) ss++;
818     t = ss + Ustrlen(ss);
819     while (t > ss && isspace(t[-1])) t--;
820     if (*ss == '\"' && t[-1] == '\"')
821       {
822       ss++;
823       t--;
824       }
825     *t = 0;
826
827     if (*ss != '/')
828       log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, ".include specifies a non-"
829         "absolute path \"%s\"", ss);
830
831     if (include_if_exists != 0 && (Ustat(ss, &statbuf) != 0)) continue;
832
833     save = store_get(sizeof(config_file_item));
834     save->next = config_file_stack;
835     config_file_stack = save;
836     save->file = config_file;
837     save->filename = config_filename;
838     save->lineno = config_lineno;
839
840     config_file = Ufopen(ss, "rb");
841     if (config_file == NULL)
842       log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "failed to open included "
843         "configuration file %s", ss);
844     config_filename = string_copy(ss);
845     config_lineno = 0;
846     continue;
847     }
848
849   /* If this is the start of the logical line, remember where the non-blank
850   data starts. Otherwise shuffle down continuation lines to remove leading
851   white space. */
852
853   if (len == 0)
854     startoffset = ss - big_buffer;
855   else
856     {
857     s = big_buffer + len;
858     if (ss > s)
859       {
860       memmove(s, ss, (newlen - len) -  (ss - s) + 1);
861       newlen -= ss - s;
862       }
863     }
864
865   /* Accept the new addition to the line. Remove trailing white space. */
866
867   len = newlen;
868   while (len > 0 && isspace(big_buffer[len-1])) len--;
869   big_buffer[len] = 0;
870
871   /* We are done if the line does not end in backslash and contains some data.
872   Empty logical lines are ignored. For continuations, remove the backslash and
873   go round the loop to read the continuation line. */
874
875   if (len > 0)
876     {
877     if (big_buffer[len-1] != '\\') break;   /* End of logical line */
878     big_buffer[--len] = 0;                  /* Remove backslash */
879     }
880   }     /* Loop for reading multiple physical lines */
881
882 /* We now have a logical line. Test for the end of a configuration section (or,
883 more accurately, for the start of the next section). Place the name of the next
884 section in next_section, and return NULL. If the name given is longer than
885 next_section, truncate it. It will be unrecognized later, because all the known
886 section names do fit. Leave space for pluralizing. */
887
888 s = big_buffer + startoffset;            /* First non-space character */
889 if (strncmpic(s, US"begin ", 6) == 0)
890   {
891   s += 6;
892   while (isspace(*s)) s++;
893   if (big_buffer + len - s > sizeof(next_section) - 2)
894     s[sizeof(next_section) - 2] = 0;
895   Ustrcpy(next_section, s);
896   return NULL;
897   }
898
899 /* Return the first non-blank character. */
900
901 return s;
902 }
903
904
905
906 /*************************************************
907 *             Read a name                        *
908 *************************************************/
909
910 /* The yield is the pointer to the next uschar. Names longer than the
911 output space are silently truncated. This function is also used from acl.c when
912 parsing ACLs.
913
914 Arguments:
915   name      where to put the name
916   len       length of name
917   s         input pointer
918
919 Returns:    new input pointer
920 */
921
922 uschar *
923 readconf_readname(uschar *name, int len, uschar *s)
924 {
925 int p = 0;
926 while (isspace(*s)) s++;
927 if (isalpha(*s))
928   {
929   while (isalnum(*s) || *s == '_')
930     {
931     if (p < len-1) name[p++] = *s;
932     s++;
933     }
934   }
935 name[p] = 0;
936 while (isspace(*s)) s++;
937 return s;
938 }
939
940
941
942
943 /*************************************************
944 *          Read a time value                     *
945 *************************************************/
946
947 /* This function is also called from outside, to read argument
948 time values. The format of a time value is:
949
950   [<n>w][<n>d][<n>h][<n>m][<n>s]
951
952 as long as at least one is present. If a format error is encountered,
953 return a negative value. The value must be terminated by the given
954 terminator.
955
956 Arguments:
957   s             input pointer
958   terminator    required terminating character
959   return_msec   if TRUE, allow fractional seconds and return milliseconds
960
961 Returns:        the time value, or -1 on syntax error
962                 value is seconds if return_msec is FALSE
963                 value is milliseconds if return_msec is TRUE
964 */
965
966 int
967 readconf_readtime(uschar *s, int terminator, BOOL return_msec)
968 {
969 int yield = 0;
970 for (;;)
971   {
972   int value, count;
973   double fraction;
974
975   if (!isdigit(*s)) return -1;
976   (void)sscanf(CS s, "%d%n", &value, &count);
977   s += count;
978
979   switch (*s)
980     {
981     case 'w': value *= 7;
982     case 'd': value *= 24;
983     case 'h': value *= 60;
984     case 'm': value *= 60;
985     case 's': s++;
986     break;
987
988     case '.':
989     if (!return_msec) return -1;
990     (void)sscanf(CS s, "%lf%n", &fraction, &count);
991     s += count;
992     if (*s++ != 's') return -1;
993     yield += (int)(fraction * 1000.0);
994     break;
995
996     default: return -1;
997     }
998
999   if (return_msec) value *= 1000;
1000   yield += value;
1001   if (*s == terminator) return yield;
1002   }
1003 /* Control never reaches here. */
1004 }
1005
1006
1007
1008 /*************************************************
1009 *          Read a fixed point value              *
1010 *************************************************/
1011
1012 /* The value is returned *1000
1013
1014 Arguments:
1015   s           input pointer
1016   terminator  required terminator
1017
1018 Returns:      the value, or -1 on error
1019 */
1020
1021 static int
1022 readconf_readfixed(uschar *s, int terminator)
1023 {
1024 int yield = 0;
1025 int value, count;
1026 if (!isdigit(*s)) return -1;
1027 (void)sscanf(CS  s, "%d%n", &value, &count);
1028 s += count;
1029 yield = value * 1000;
1030 if (*s == '.')
1031   {
1032   int m = 100;
1033   while (isdigit((*(++s))))
1034     {
1035     yield += (*s - '0') * m;
1036     m /= 10;
1037     }
1038   }
1039
1040 return (*s == terminator)? yield : (-1);
1041 }
1042
1043
1044
1045 /*************************************************
1046 *            Find option in list                 *
1047 *************************************************/
1048
1049 /* The lists are always in order, so binary chop can be used.
1050
1051 Arguments:
1052   name      the option name to search for
1053   ol        the first entry in the option list
1054   last      one more than the offset of the last entry in the option list
1055
1056 Returns:    pointer to an option entry, or NULL if not found
1057 */
1058
1059 static optionlist *
1060 find_option(uschar *name, optionlist *ol, int last)
1061 {
1062 int first = 0;
1063 while (last > first)
1064   {
1065   int middle = (first + last)/2;
1066   int c = Ustrcmp(name, ol[middle].name);
1067   if (c == 0) return ol + middle;
1068     else if (c > 0) first = middle + 1;
1069       else last = middle;
1070   }
1071 return NULL;
1072 }
1073
1074
1075
1076 /*************************************************
1077 *      Find a set flag in option list            *
1078 *************************************************/
1079
1080 /* Because some versions of Unix make no restrictions on the values of uids and
1081 gids (even negative ones), we cannot represent "unset" by a special value.
1082 There is therefore a separate boolean variable for each one indicating whether
1083 a value is set or not. This function returns a pointer to the boolean, given
1084 the original option name. It is a major disaster if the flag cannot be found.
1085
1086 Arguments:
1087   name          the name of the uid or gid option
1088   oltop         points to the start of the relevant option list
1089   last          one more than the offset of the last item in the option list
1090   data_block    NULL when reading main options => data values in the option
1091                   list are absolute addresses; otherwise they are byte offsets
1092                   in data_block (used for driver options)
1093
1094 Returns:        a pointer to the boolean flag.
1095 */
1096
1097 static BOOL *
1098 get_set_flag(uschar *name, optionlist *oltop, int last, void *data_block)
1099 {
1100 optionlist *ol;
1101 uschar name2[64];
1102 sprintf(CS name2, "*set_%.50s", name);
1103 ol = find_option(name2, oltop, last);
1104 if (ol == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1105   "Exim internal error: missing set flag for %s", name);
1106 return (data_block == NULL)? (BOOL *)(ol->value) :
1107   (BOOL *)((uschar *)data_block + (long int)(ol->value));
1108 }
1109
1110
1111
1112
1113 /*************************************************
1114 *    Output extra characters message and die     *
1115 *************************************************/
1116
1117 /* Called when an option line has junk on the end. Sometimes this is because
1118 the sysadmin thinks comments are permitted.
1119
1120 Arguments:
1121   s          points to the extra characters
1122   t1..t3     strings to insert in the log message
1123
1124 Returns:     doesn't return; dies
1125 */
1126
1127 static void
1128 extra_chars_error(uschar *s, uschar *t1, uschar *t2, uschar *t3)
1129 {
1130 uschar *comment = US"";
1131 if (*s == '#') comment = US" (# is comment only at line start)";
1132 log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1133   "extra characters follow %s%s%s%s", t1, t2, t3, comment);
1134 }
1135
1136
1137
1138 /*************************************************
1139 *              Read rewrite information          *
1140 *************************************************/
1141
1142 /* Each line of rewrite information contains:
1143
1144 .  A complete address in the form user@domain, possibly with
1145    leading * for each part; or alternatively, a regex.
1146
1147 .  A replacement string (which will be expanded).
1148
1149 .  An optional sequence of one-letter flags, indicating which
1150    headers etc. to apply this rule to.
1151
1152 All this is decoded and placed into a control block. The OR of the flags is
1153 maintained in a common word.
1154
1155 Arguments:
1156   p           points to the string that makes up the rule
1157   existflags  points to the overall flag word
1158   isglobal    TRUE if reading global rewrite rules
1159
1160 Returns:      the control block for the parsed rule.
1161 */
1162
1163 static rewrite_rule *
1164 readconf_one_rewrite(uschar *p, int *existflags, BOOL isglobal)
1165 {
1166 rewrite_rule *next = store_get(sizeof(rewrite_rule));
1167
1168 next->next = NULL;
1169 next->key = string_dequote(&p);
1170
1171 while (isspace(*p)) p++;
1172 if (*p == 0)
1173   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1174     "missing rewrite replacement string");
1175
1176 next->flags = 0;
1177 next->replacement = string_dequote(&p);
1178
1179 while (*p != 0) switch (*p++)
1180   {
1181   case ' ': case '\t': break;
1182
1183   case 'q': next->flags |= rewrite_quit; break;
1184   case 'w': next->flags |= rewrite_whole; break;
1185
1186   case 'h': next->flags |= rewrite_all_headers; break;
1187   case 's': next->flags |= rewrite_sender; break;
1188   case 'f': next->flags |= rewrite_from; break;
1189   case 't': next->flags |= rewrite_to;   break;
1190   case 'c': next->flags |= rewrite_cc;   break;
1191   case 'b': next->flags |= rewrite_bcc;  break;
1192   case 'r': next->flags |= rewrite_replyto; break;
1193
1194   case 'E': next->flags |= rewrite_all_envelope; break;
1195   case 'F': next->flags |= rewrite_envfrom; break;
1196   case 'T': next->flags |= rewrite_envto; break;
1197
1198   case 'Q': next->flags |= rewrite_qualify; break;
1199   case 'R': next->flags |= rewrite_repeat; break;
1200
1201   case 'S':
1202   next->flags |= rewrite_smtp;
1203   if (next->key[0] != '^' && Ustrncmp(next->key, "\\N^", 3) != 0)
1204     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1205       "rewrite rule has the S flag but is not a regular expression");
1206   break;
1207
1208   default:
1209   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1210     "unknown rewrite flag character '%c' "
1211     "(could be missing quotes round replacement item)", p[-1]);
1212   break;
1213   }
1214
1215 /* If no action flags are set, set all the "normal" rewrites. */
1216
1217 if ((next->flags & (rewrite_all | rewrite_smtp)) == 0)
1218   next->flags |= isglobal? rewrite_all : rewrite_all_headers;
1219
1220 /* Remember which exist, for optimization, and return the rule */
1221
1222 *existflags |= next->flags;
1223 return next;
1224 }
1225
1226
1227
1228
1229 /*************************************************
1230 *          Read global rewrite information       *
1231 *************************************************/
1232
1233 /* Each line is a single rewrite rule; it is parsed into a control block
1234 by readconf_one_rewrite(), and its flags are ORed into the global flag
1235 word rewrite_existflags. */
1236
1237 void
1238 readconf_rewrites(void)
1239 {
1240 rewrite_rule **chain = &global_rewrite_rules;
1241 uschar *p;
1242
1243 while ((p = get_config_line()) != NULL)
1244   {
1245   rewrite_rule *next = readconf_one_rewrite(p, &rewrite_existflags, TRUE);
1246   *chain = next;
1247   chain = &(next->next);
1248   }
1249 }
1250
1251
1252
1253 /*************************************************
1254 *               Read a string                    *
1255 *************************************************/
1256
1257 /* Strings are read into the normal store pool. As long we aren't too
1258 near the end of the current block, the string will just use what is necessary
1259 on the top of the stacking pool, because string_cat() uses the extension
1260 mechanism.
1261
1262 Argument:
1263   s         the rest of the input line
1264   name      the option name (for errors)
1265
1266 Returns:    pointer to the string
1267 */
1268
1269 static uschar *
1270 read_string(uschar *s, uschar *name)
1271 {
1272 uschar *yield;
1273 uschar *ss;
1274
1275 if (*s != '\"') return string_copy(s);
1276
1277 ss = s;
1278 yield = string_dequote(&s);
1279
1280 if (s == ss+1 || s[-1] != '\"')
1281   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1282     "missing quote at end of string value for %s", name);
1283
1284 if (*s != 0) extra_chars_error(s, US"string value for ", name, US"");
1285
1286 return yield;
1287 }
1288
1289
1290 /*************************************************
1291 *            Handle option line                  *
1292 *************************************************/
1293
1294 /* This function is called from several places to process a line containing the
1295 setting of an option. The first argument is the line to be decoded; it has been
1296 checked not to be empty and not to start with '#'. Trailing newlines and white
1297 space have been removed. The second argument is a pointer to the list of
1298 variable names that are to be recognized, together with their types and
1299 locations, and the third argument gives the number of entries in the list.
1300
1301 The fourth argument is a pointer to a data block. If it is NULL, then the data
1302 values in the options list are absolute addresses. Otherwise, they are byte
1303 offsets in the data block.
1304
1305 String option data may continue onto several lines; this function reads further
1306 data from config_file if necessary.
1307
1308 The yield of this function is normally zero. If a string continues onto
1309 multiple lines, then the data value is permitted to be followed by a comma
1310 or a semicolon (for use in drivers) and the yield is that character.
1311
1312 Arguments:
1313   buffer        contains the configuration line to be handled
1314   oltop         points to the start of the relevant option list
1315   last          one more than the offset of the last item in the option list
1316   data_block    NULL when reading main options => data values in the option
1317                   list are absolute addresses; otherwise they are byte offsets
1318                   in data_block when they have opt_public set; otherwise
1319                   they are byte offsets in data_block->options_block.
1320   unknown_txt   format string to use in panic message for unknown option;
1321                   must contain %s for option name
1322                 if given as NULL, don't panic on unknown option
1323
1324 Returns:        TRUE if an option was read successfully,
1325                 FALSE false for an unknown option if unknown_txt == NULL,
1326                   otherwise panic and die on an unknown option
1327 */
1328
1329 static BOOL
1330 readconf_handle_option(uschar *buffer, optionlist *oltop, int last,
1331   void *data_block, uschar *unknown_txt)
1332 {
1333 int ptr = 0;
1334 int offset = 0;
1335 int n, count, type, value;
1336 int issecure = 0;
1337 uid_t uid;
1338 gid_t gid;
1339 BOOL boolvalue = TRUE;
1340 BOOL freesptr = TRUE;
1341 optionlist *ol, *ol2;
1342 struct passwd *pw;
1343 void *reset_point;
1344 int intbase = 0;
1345 uschar *inttype = US"";
1346 uschar *sptr;
1347 uschar *s = buffer;
1348 uschar name[64];
1349 uschar name2[64];
1350
1351 /* There may be leading spaces; thereafter, we expect an option name starting
1352 with a letter. */
1353
1354 while (isspace(*s)) s++;
1355 if (!isalpha(*s))
1356   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "option setting expected: %s", s);
1357
1358 /* Read the name of the option, and skip any subsequent white space. If
1359 it turns out that what we read was "hide", set the flag indicating that
1360 this is a secure option, and loop to read the next word. */
1361
1362 for (n = 0; n < 2; n++)
1363   {
1364   while (isalnum(*s) || *s == '_')
1365     {
1366     if (ptr < sizeof(name)-1) name[ptr++] = *s;
1367     s++;
1368     }
1369   name[ptr] = 0;
1370   while (isspace(*s)) s++;
1371   if (Ustrcmp(name, "hide") != 0) break;
1372   issecure = opt_secure;
1373   ptr = 0;
1374   }
1375
1376 /* Deal with "no_" or "not_" here for booleans */
1377
1378 if (Ustrncmp(name, "no_", 3) == 0)
1379   {
1380   boolvalue = FALSE;
1381   offset = 3;
1382   }
1383
1384 if (Ustrncmp(name, "not_", 4) == 0)
1385   {
1386   boolvalue = FALSE;
1387   offset = 4;
1388   }
1389
1390 /* Search the list for the given name. A non-existent name, or an option that
1391 is set twice, is a disaster. */
1392
1393 ol = find_option(name + offset, oltop, last);
1394
1395 if (ol == NULL)
1396   {
1397   if (unknown_txt == NULL) return FALSE;
1398   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, CS unknown_txt, name);
1399   }
1400
1401 if ((ol->type & opt_set) != 0)
1402   {
1403   uschar *mname = name;
1404   if (Ustrncmp(mname, "no_", 3) == 0) mname += 3;
1405   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1406     "\"%s\" option set for the second time", mname);
1407   }
1408
1409 ol->type |= opt_set | issecure;
1410 type = ol->type & opt_mask;
1411
1412 /* Types with data values must be followed by '='; the "no[t]_" prefix
1413 applies only to boolean values. */
1414
1415 if (type < opt_bool || type > opt_bool_last)
1416   {
1417   if (offset != 0)
1418     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1419       "negation prefix applied to a non-boolean option");
1420   if (*s == 0)
1421     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1422       "unexpected end of line (data missing) after %s", name);
1423   if (*s != '=')
1424     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "missing \"=\" after %s", name);
1425   }
1426
1427 /* If a boolean wasn't preceded by "no[t]_" it can be followed by = and
1428 true/false/yes/no, or, in the case of opt_expanded_bool, a general string that
1429 ultimately expands to one of those values. */
1430
1431 else if (*s != 0 && (offset != 0 || *s != '='))
1432   extra_chars_error(s, US"boolean option ", name, US"");
1433
1434 /* Skip white space after = */
1435
1436 if (*s == '=') while (isspace((*(++s))));
1437
1438 /* If there is a data block and the opt_public flag is not set, change
1439 the data block pointer to the private options block. */
1440
1441 if (data_block != NULL && (ol->type & opt_public) == 0)
1442   data_block = (void *)(((driver_instance *)data_block)->options_block);
1443
1444 /* Now get the data according to the type. */
1445
1446 switch (type)
1447   {
1448   /* If a string value is not enclosed in quotes, it consists of
1449   the rest of the current line, verbatim. Otherwise, string escapes
1450   are processed.
1451
1452   A transport is specified as a string, which is then looked up in the
1453   list of transports. A search type is specified as one of a number of
1454   known strings.
1455
1456   A set or rewrite rules for a driver is specified as a string, which is
1457   then parsed into a suitable chain of control blocks.
1458
1459   Uids and gids are specified as strings which are then looked up in the
1460   passwd file. Lists of uids and gids are similarly specified as colon-
1461   separated strings. */
1462
1463   case opt_stringptr:
1464   case opt_uid:
1465   case opt_gid:
1466   case opt_expand_uid:
1467   case opt_expand_gid:
1468   case opt_uidlist:
1469   case opt_gidlist:
1470   case opt_rewrite:
1471
1472   reset_point = sptr = read_string(s, name);
1473
1474   /* Having read a string, we now have several different ways of using it,
1475   depending on the data type, so do another switch. If keeping the actual
1476   string is not required (because it is interpreted), freesptr is set TRUE,
1477   and at the end we reset the pool. */
1478
1479   switch (type)
1480     {
1481     /* If this was a string, set the variable to point to the new string,
1482     and set the flag so its store isn't reclaimed. If it was a list of rewrite
1483     rules, we still keep the string (for printing), and parse the rules into a
1484     control block and flags word. */
1485
1486     case opt_stringptr:
1487     case opt_rewrite:
1488     if (data_block == NULL)
1489       *((uschar **)(ol->value)) = sptr;
1490     else
1491       *((uschar **)((uschar *)data_block + (long int)(ol->value))) = sptr;
1492     freesptr = FALSE;
1493     if (type == opt_rewrite)
1494       {
1495       int sep = 0;
1496       int *flagptr;
1497       uschar *p = sptr;
1498       rewrite_rule **chain;
1499       optionlist *ol3;
1500
1501       sprintf(CS name2, "*%.50s_rules", name);
1502       ol2 = find_option(name2, oltop, last);
1503       sprintf(CS name2, "*%.50s_flags", name);
1504       ol3 = find_option(name2, oltop, last);
1505
1506       if (ol2 == NULL || ol3 == NULL)
1507         log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1508           "rewrite rules not available for driver");
1509
1510       if (data_block == NULL)
1511         {
1512         chain = (rewrite_rule **)(ol2->value);
1513         flagptr = (int *)(ol3->value);
1514         }
1515       else
1516         {
1517         chain = (rewrite_rule **)((uschar *)data_block + (long int)(ol2->value));
1518         flagptr = (int *)((uschar *)data_block + (long int)(ol3->value));
1519         }
1520
1521       while ((p = string_nextinlist(&sptr, &sep, big_buffer, BIG_BUFFER_SIZE))
1522               != NULL)
1523         {
1524         rewrite_rule *next = readconf_one_rewrite(p, flagptr, FALSE);
1525         *chain = next;
1526         chain = &(next->next);
1527         }
1528
1529       if ((*flagptr & (rewrite_all_envelope | rewrite_smtp)) != 0)
1530         log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "rewrite rule specifies a "
1531           "non-header rewrite - not allowed at transport time -");
1532       }
1533     break;
1534
1535     /* If it was an expanded uid, see if there is any expansion to be
1536     done by checking for the presence of a $ character. If there is, save it
1537     in the corresponding *expand_user option field. Otherwise, fall through
1538     to treat it as a fixed uid. Ensure mutual exclusivity of the two kinds
1539     of data. */
1540
1541     case opt_expand_uid:
1542     sprintf(CS name2, "*expand_%.50s", name);
1543     ol2 = find_option(name2, oltop, last);
1544     if (ol2 != NULL)
1545       {
1546       uschar *ss = (Ustrchr(sptr, '$') != NULL)? sptr : NULL;
1547
1548       if (data_block == NULL)
1549         *((uschar **)(ol2->value)) = ss;
1550       else
1551         *((uschar **)((uschar *)data_block + (long int)(ol2->value))) = ss;
1552
1553       if (ss != NULL)
1554         {
1555         *(get_set_flag(name, oltop, last, data_block)) = FALSE;
1556         freesptr = FALSE;
1557         break;
1558         }
1559       }
1560
1561     /* Look up a fixed uid, and also make use of the corresponding gid
1562     if a passwd entry is returned and the gid has not been set. */
1563
1564     case opt_uid:
1565     if (!route_finduser(sptr, &pw, &uid))
1566       log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "user %s was not found", sptr);
1567     if (data_block == NULL)
1568       *((uid_t *)(ol->value)) = uid;
1569     else
1570       *((uid_t *)((uschar *)data_block + (long int)(ol->value))) = uid;
1571
1572     /* Set the flag indicating a fixed value is set */
1573
1574     *(get_set_flag(name, oltop, last, data_block)) = TRUE;
1575
1576     /* Handle matching gid if we have a passwd entry: done by finding the
1577     same name with terminating "user" changed to "group"; if not found,
1578     ignore. Also ignore if the value is already set. */
1579
1580     if (pw == NULL) break;
1581     Ustrcpy(name+Ustrlen(name)-4, "group");
1582     ol2 = find_option(name, oltop, last);
1583     if (ol2 != NULL && ((ol2->type & opt_mask) == opt_gid ||
1584         (ol2->type & opt_mask) == opt_expand_gid))
1585       {
1586       BOOL *set_flag = get_set_flag(name, oltop, last, data_block);
1587       if (! *set_flag)
1588         {
1589         if (data_block == NULL)
1590           *((gid_t *)(ol2->value)) = pw->pw_gid;
1591         else
1592           *((gid_t *)((uschar *)data_block + (long int)(ol2->value))) = pw->pw_gid;
1593         *set_flag = TRUE;
1594         }
1595       }
1596     break;
1597
1598     /* If it was an expanded gid, see if there is any expansion to be
1599     done by checking for the presence of a $ character. If there is, save it
1600     in the corresponding *expand_user option field. Otherwise, fall through
1601     to treat it as a fixed gid. Ensure mutual exclusivity of the two kinds
1602     of data. */
1603
1604     case opt_expand_gid:
1605     sprintf(CS name2, "*expand_%.50s", name);
1606     ol2 = find_option(name2, oltop, last);
1607     if (ol2 != NULL)
1608       {
1609       uschar *ss = (Ustrchr(sptr, '$') != NULL)? sptr : NULL;
1610
1611       if (data_block == NULL)
1612         *((uschar **)(ol2->value)) = ss;
1613       else
1614         *((uschar **)((uschar *)data_block + (long int)(ol2->value))) = ss;
1615
1616       if (ss != NULL)
1617         {
1618         *(get_set_flag(name, oltop, last, data_block)) = FALSE;
1619         freesptr = FALSE;
1620         break;
1621         }
1622       }
1623
1624     /* Handle freestanding gid */
1625
1626     case opt_gid:
1627     if (!route_findgroup(sptr, &gid))
1628       log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "group %s was not found", sptr);
1629     if (data_block == NULL)
1630       *((gid_t *)(ol->value)) = gid;
1631     else
1632       *((gid_t *)((uschar *)data_block + (long int)(ol->value))) = gid;
1633     *(get_set_flag(name, oltop, last, data_block)) = TRUE;
1634     break;
1635
1636     /* If it was a uid list, look up each individual entry, and build
1637     a vector of uids, with a count in the first element. Put the vector
1638     in malloc store so we can free the string. (We are reading into
1639     permanent store already.) */
1640
1641     case opt_uidlist:
1642       {
1643       int count = 1;
1644       uid_t *list;
1645       int ptr = 0;
1646       uschar *p;
1647       uschar *op = expand_string (sptr);
1648
1649       if (op == NULL)
1650         log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "failed to expand %s: %s",
1651           name, expand_string_message);
1652
1653       p = op;
1654       if (*p != 0) count++;
1655       while (*p != 0) if (*p++ == ':' && *p != 0) count++;
1656       list = store_malloc(count*sizeof(uid_t));
1657       list[ptr++] = (uid_t)(count - 1);
1658
1659       if (data_block == NULL)
1660         *((uid_t **)(ol->value)) = list;
1661       else
1662         *((uid_t **)((uschar *)data_block + (long int)(ol->value))) = list;
1663
1664       p = op;
1665       while (count-- > 1)
1666         {
1667         int sep = 0;
1668         (void)string_nextinlist(&p, &sep, big_buffer, BIG_BUFFER_SIZE);
1669         if (!route_finduser(big_buffer, NULL, &uid))
1670           log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "user %s was not found",
1671             big_buffer);
1672         list[ptr++] = uid;
1673         }
1674       }
1675     break;
1676
1677     /* If it was a gid list, look up each individual entry, and build
1678     a vector of gids, with a count in the first element. Put the vector
1679     in malloc store so we can free the string. (We are reading into permanent
1680     store already.) */
1681
1682     case opt_gidlist:
1683       {
1684       int count = 1;
1685       gid_t *list;
1686       int ptr = 0;
1687       uschar *p;
1688       uschar *op = expand_string (sptr);
1689
1690       if (op == NULL)
1691         log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "failed to expand %s: %s",
1692           name, expand_string_message);
1693
1694       p = op;
1695       if (*p != 0) count++;
1696       while (*p != 0) if (*p++ == ':' && *p != 0) count++;
1697       list = store_malloc(count*sizeof(gid_t));
1698       list[ptr++] = (gid_t)(count - 1);
1699
1700       if (data_block == NULL)
1701         *((gid_t **)(ol->value)) = list;
1702       else
1703         *((gid_t **)((uschar *)data_block + (long int)(ol->value))) = list;
1704
1705       p = op;
1706       while (count-- > 1)
1707         {
1708         int sep = 0;
1709         (void)string_nextinlist(&p, &sep, big_buffer, BIG_BUFFER_SIZE);
1710         if (!route_findgroup(big_buffer, &gid))
1711           log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "group %s was not found",
1712             big_buffer);
1713         list[ptr++] = gid;
1714         }
1715       }
1716     break;
1717     }
1718
1719   /* Release store if the value of the string doesn't need to be kept. */
1720
1721   if (freesptr) store_reset(reset_point);
1722   break;
1723
1724   /* Expanded boolean: if no characters follow, or if there are no dollar
1725   characters, this is a fixed-valued boolean, and we fall through. Otherwise,
1726   save the string for later expansion in the alternate place. */
1727
1728   case opt_expand_bool:
1729   if (*s != 0 && Ustrchr(s, '$') != 0)
1730     {
1731     sprintf(CS name2, "*expand_%.50s", name);
1732     ol2 = find_option(name2, oltop, last);
1733     if (ol2 != NULL)
1734       {
1735       reset_point = sptr = read_string(s, name);
1736       if (data_block == NULL)
1737         *((uschar **)(ol2->value)) = sptr;
1738       else
1739         *((uschar **)((uschar *)data_block + (long int)(ol2->value))) = sptr;
1740       freesptr = FALSE;
1741       break;
1742       }
1743     }
1744   /* Fall through */
1745
1746   /* Boolean: if no characters follow, the value is boolvalue. Otherwise
1747   look for yes/not/true/false. Some booleans are stored in a single bit in
1748   a single int. There's a special fudge for verify settings; without a suffix
1749   they set both xx_sender and xx_recipient. The table points to the sender
1750   value; search subsequently for the recipient. There's another special case:
1751   opt_bool_set also notes when a boolean has been set. */
1752
1753   case opt_bool:
1754   case opt_bit:
1755   case opt_bool_verify:
1756   case opt_bool_set:
1757   if (*s != 0)
1758     {
1759     s = readconf_readname(name2, 64, s);
1760     if (strcmpic(name2, US"true") == 0 || strcmpic(name2, US"yes") == 0)
1761       boolvalue = TRUE;
1762     else if (strcmpic(name2, US"false") == 0 || strcmpic(name2, US"no") == 0)
1763       boolvalue = FALSE;
1764     else log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1765       "\"%s\" is not a valid value for the \"%s\" option", name2, name);
1766     if (*s != 0) extra_chars_error(s, string_sprintf("\"%s\" ", name2),
1767       US"for boolean option ", name);
1768     }
1769
1770   /* Handle single-bit type. */
1771
1772   if (type == opt_bit)
1773     {
1774     int bit = 1 << ((ol->type >> 16) & 31);
1775     int *ptr = (data_block == NULL)?
1776       (int *)(ol->value) :
1777       (int *)((uschar *)data_block + (long int)ol->value);
1778     if (boolvalue) *ptr |= bit; else *ptr &= ~bit;
1779     break;
1780     }
1781
1782   /* Handle full BOOL types */
1783
1784   if (data_block == NULL)
1785     *((BOOL *)(ol->value)) = boolvalue;
1786   else
1787     *((BOOL *)((uschar *)data_block + (long int)(ol->value))) = boolvalue;
1788
1789   /* Verify fudge */
1790
1791   if (type == opt_bool_verify)
1792     {
1793     sprintf(CS name2, "%.50s_recipient", name + offset);
1794     ol2 = find_option(name2, oltop, last);
1795     if (ol2 != NULL)
1796       {
1797       if (data_block == NULL)
1798         *((BOOL *)(ol2->value)) = boolvalue;
1799       else
1800         *((BOOL *)((uschar *)data_block + (long int)(ol2->value))) = boolvalue;
1801       }
1802     }
1803
1804   /* Note that opt_bool_set type is set, if there is somewhere to do so */
1805
1806   else if (type == opt_bool_set)
1807     {
1808     sprintf(CS name2, "*set_%.50s", name + offset);
1809     ol2 = find_option(name2, oltop, last);
1810     if (ol2 != NULL)
1811       {
1812       if (data_block == NULL)
1813         *((BOOL *)(ol2->value)) = TRUE;
1814       else
1815         *((BOOL *)((uschar *)data_block + (long int)(ol2->value))) = TRUE;
1816       }
1817     }
1818   break;
1819
1820   /* Octal integer */
1821
1822   case opt_octint:
1823   intbase = 8;
1824   inttype = US"octal ";
1825
1826   /*  Integer: a simple(ish) case; allow octal and hex formats, and
1827   suffixes K and M. The different types affect output, not input. */
1828
1829   case opt_mkint:
1830   case opt_int:
1831     {
1832     uschar *endptr;
1833     long int lvalue;
1834
1835     errno = 0;
1836     lvalue = strtol(CS s, CSS &endptr, intbase);
1837
1838     if (endptr == s)
1839       log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "%sinteger expected for %s",
1840         inttype, name);
1841
1842     if (errno != ERANGE)
1843       {
1844       if (tolower(*endptr) == 'k')
1845         {
1846         if (lvalue > INT_MAX/1024 || lvalue < INT_MIN/1024) errno = ERANGE;
1847           else lvalue *= 1024;
1848         endptr++;
1849         }
1850       else if (tolower(*endptr) == 'm')
1851         {
1852         if (lvalue > INT_MAX/(1024*1024) || lvalue < INT_MIN/(1024*1024))
1853           errno = ERANGE;
1854         else lvalue *= 1024*1024;
1855         endptr++;
1856         }
1857       }
1858
1859     if (errno == ERANGE || lvalue > INT_MAX || lvalue < INT_MIN)
1860       log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1861         "absolute value of integer \"%s\" is too large (overflow)", s);
1862
1863     while (isspace(*endptr)) endptr++;
1864     if (*endptr != 0)
1865       extra_chars_error(endptr, inttype, US"integer value for ", name);
1866
1867     value = (int)lvalue;
1868     }
1869
1870   if (data_block == NULL)
1871     *((int *)(ol->value)) = value;
1872   else
1873     *((int *)((uschar *)data_block + (long int)(ol->value))) = value;
1874   break;
1875
1876   /*  Integer held in K: again, allow octal and hex formats, and suffixes K and
1877   M. */
1878
1879   case opt_Kint:
1880     {
1881     uschar *endptr;
1882     errno = 0;
1883     value = strtol(CS s, CSS &endptr, intbase);
1884
1885     if (endptr == s)
1886       log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "%sinteger expected for %s",
1887         inttype, name);
1888
1889     if (errno != ERANGE)
1890       {
1891       if (tolower(*endptr) == 'm')
1892         {
1893         if (value > INT_MAX/1024 || value < INT_MIN/1024) errno = ERANGE;
1894           else value *= 1024;
1895         endptr++;
1896         }
1897       else if (tolower(*endptr) == 'k')
1898         {
1899         endptr++;
1900         }
1901       else
1902         {
1903         value = (value + 512)/1024;
1904         }
1905       }
1906
1907     if (errno == ERANGE) log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1908       "absolute value of integer \"%s\" is too large (overflow)", s);
1909
1910     while (isspace(*endptr)) endptr++;
1911     if (*endptr != 0)
1912       extra_chars_error(endptr, inttype, US"integer value for ", name);
1913     }
1914
1915   if (data_block == NULL)
1916     *((int *)(ol->value)) = value;
1917   else
1918     *((int *)((uschar *)data_block + (long int)(ol->value))) = value;
1919   break;
1920
1921   /*  Fixed-point number: held to 3 decimal places. */
1922
1923   case opt_fixed:
1924   if (sscanf(CS s, "%d%n", &value, &count) != 1)
1925     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1926       "fixed-point number expected for %s", name);
1927
1928   if (value < 0) log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1929     "integer \"%s\" is too large (overflow)", s);
1930
1931   value *= 1000;
1932
1933   if (value < 0) log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1934     "integer \"%s\" is too large (overflow)", s);
1935
1936   if (s[count] == '.')
1937     {
1938     int d = 100;
1939     while (isdigit(s[++count]))
1940       {
1941       value += (s[count] - '0') * d;
1942       d /= 10;
1943       }
1944     }
1945
1946   while (isspace(s[count])) count++;
1947
1948   if (s[count] != 0)
1949     extra_chars_error(s+count, US"fixed-point value for ", name, US"");
1950
1951   if (data_block == NULL)
1952     *((int *)(ol->value)) = value;
1953   else
1954     *((int *)((uschar *)data_block + (long int)(ol->value))) = value;
1955   break;
1956
1957   /* There's a special routine to read time values. */
1958
1959   case opt_time:
1960   value = readconf_readtime(s, 0, FALSE);
1961   if (value < 0)
1962     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "invalid time value for %s",
1963       name);
1964   if (data_block == NULL)
1965     *((int *)(ol->value)) = value;
1966   else
1967     *((int *)((uschar *)data_block + (long int)(ol->value))) = value;
1968   break;
1969
1970   /* A time list is a list of colon-separated times, with the first
1971   element holding the size of the list and the second the number of
1972   entries used. */
1973
1974   case opt_timelist:
1975     {
1976     int count = 0;
1977     int *list = (data_block == NULL)?
1978       (int *)(ol->value) :
1979       (int *)((uschar *)data_block + (long int)(ol->value));
1980
1981     if (*s != 0) for (count = 1; count <= list[0] - 2; count++)
1982       {
1983       int terminator = 0;
1984       uschar *snext = Ustrchr(s, ':');
1985       if (snext != NULL)
1986         {
1987         uschar *ss = snext;
1988         while (ss > s && isspace(ss[-1])) ss--;
1989         terminator = *ss;
1990         }
1991       value = readconf_readtime(s, terminator, FALSE);
1992       if (value < 0)
1993         log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "invalid time value for %s",
1994           name);
1995       if (count > 1 && value <= list[count])
1996         log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
1997           "time value out of order for %s", name);
1998       list[count+1] = value;
1999       if (snext == NULL) break;
2000       s = snext + 1;
2001       while (isspace(*s)) s++;
2002       }
2003
2004     if (count > list[0] - 2)
2005       log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "too many time values for %s",
2006         name);
2007     if (count > 0 && list[2] == 0) count = 0;
2008     list[1] = count;
2009     }
2010
2011   break;
2012   }
2013
2014 return TRUE;
2015 }
2016
2017
2018
2019 /*************************************************
2020 *               Print a time value               *
2021 *************************************************/
2022
2023 /*
2024 Argument:  a time value in seconds
2025 Returns:   pointer to a fixed buffer containing the time as a string,
2026            in readconf_readtime() format
2027 */
2028
2029 uschar *
2030 readconf_printtime(int t)
2031 {
2032 int s, m, h, d, w;
2033 uschar *p = time_buffer;
2034
2035 if (t < 0)
2036   {
2037   *p++ = '-';
2038   t = -t;
2039   }
2040
2041 s = t % 60;
2042 t /= 60;
2043 m = t % 60;
2044 t /= 60;
2045 h = t % 24;
2046 t /= 24;
2047 d = t % 7;
2048 w = t/7;
2049
2050 if (w > 0) { sprintf(CS p, "%dw", w); while (*p) p++; }
2051 if (d > 0) { sprintf(CS p, "%dd", d); while (*p) p++; }
2052 if (h > 0) { sprintf(CS p, "%dh", h); while (*p) p++; }
2053 if (m > 0) { sprintf(CS p, "%dm", m); while (*p) p++; }
2054 if (s > 0 || p == time_buffer) sprintf(CS p, "%ds", s);
2055
2056 return time_buffer;
2057 }
2058
2059
2060
2061 /*************************************************
2062 *      Print an individual option value          *
2063 *************************************************/
2064
2065 /* This is used by the -bP option, so prints to the standard output.
2066 The entire options list is passed in as an argument, because some options come
2067 in pairs - typically uid/gid settings, which can either be explicit numerical
2068 values, or strings to be expanded later. If the numerical value is unset,
2069 search for "*expand_<name>" to see if there is a string equivalent.
2070
2071 Arguments:
2072   ol             option entry, or NULL for an unknown option
2073   name           option name
2074   options_block  NULL for main configuration options; otherwise points to
2075                    a driver block; if the option doesn't have opt_public
2076                    set, then options_block->options_block is where the item
2077                    resides.
2078   oltop          points to the option list in which ol exists
2079   last           one more than the offset of the last entry in optop
2080
2081 Returns:         nothing
2082 */
2083
2084 static void
2085 print_ol(optionlist *ol, uschar *name, void *options_block,
2086   optionlist *oltop, int last)
2087 {
2088 struct passwd *pw;
2089 struct group *gr;
2090 optionlist *ol2;
2091 void *value;
2092 uid_t *uidlist;
2093 gid_t *gidlist;
2094 uschar *s;
2095 uschar name2[64];
2096
2097 if (ol == NULL)
2098   {
2099   printf("%s is not a known option\n", name);
2100   return;
2101   }
2102
2103 /* Non-admin callers cannot see options that have been flagged secure by the
2104 "hide" prefix. */
2105
2106 if (!admin_user && (ol->type & opt_secure) != 0)
2107   {
2108   printf("%s = <value not displayable>\n", name);
2109   return;
2110   }
2111
2112 /* Else show the value of the option */
2113
2114 value = ol->value;
2115 if (options_block != NULL)
2116   {
2117   if ((ol->type & opt_public) == 0)
2118     options_block = (void *)(((driver_instance *)options_block)->options_block);
2119   value = (void *)((uschar *)options_block + (long int)value);
2120   }
2121
2122 switch(ol->type & opt_mask)
2123   {
2124   case opt_stringptr:
2125   case opt_rewrite:        /* Show the text value */
2126   s = *((uschar **)value);
2127   printf("%s = %s\n", name, (s == NULL)? US"" : string_printing2(s, FALSE));
2128   break;
2129
2130   case opt_int:
2131   printf("%s = %d\n", name, *((int *)value));
2132   break;
2133
2134   case opt_mkint:
2135     {
2136     int x = *((int *)value);
2137     if (x != 0 && (x & 1023) == 0)
2138       {
2139       int c = 'K';
2140       x >>= 10;
2141       if ((x & 1023) == 0)
2142         {
2143         c = 'M';
2144         x >>= 10;
2145         }
2146       printf("%s = %d%c\n", name, x, c);
2147       }
2148     else printf("%s = %d\n", name, x);
2149     }
2150   break;
2151
2152   case opt_Kint:
2153     {
2154     int x = *((int *)value);
2155     if (x == 0) printf("%s = 0\n", name);
2156       else if ((x & 1023) == 0) printf("%s = %dM\n", name, x >> 10);
2157         else printf("%s = %dK\n", name, x);
2158     }
2159   break;
2160
2161   case opt_octint:
2162   printf("%s = %#o\n", name, *((int *)value));
2163   break;
2164
2165   /* Can be negative only when "unset", in which case integer */
2166
2167   case opt_fixed:
2168     {
2169     int x = *((int *)value);
2170     int f = x % 1000;
2171     int d = 100;
2172     if (x < 0) printf("%s =\n", name); else
2173       {
2174       printf("%s = %d.", name, x/1000);
2175       do
2176         {
2177         printf("%d", f/d);
2178         f %= d;
2179         d /= 10;
2180         }
2181       while (f != 0);
2182       printf("\n");
2183       }
2184     }
2185   break;
2186
2187   /* If the numerical value is unset, try for the string value */
2188
2189   case opt_expand_uid:
2190   if (! *get_set_flag(name, oltop, last, options_block))
2191     {
2192     sprintf(CS name2, "*expand_%.50s", name);
2193     ol2 = find_option(name2, oltop, last);
2194     if (ol2 != NULL)
2195       {
2196       void *value2 = ol2->value;
2197       if (options_block != NULL)
2198         value2 = (void *)((uschar *)options_block + (long int)value2);
2199       s = *((uschar **)value2);
2200       printf("%s = %s\n", name, (s == NULL)? US"" : string_printing(s));
2201       break;
2202       }
2203     }
2204
2205   /* Else fall through */
2206
2207   case opt_uid:
2208   if (! *get_set_flag(name, oltop, last, options_block))
2209     printf("%s =\n", name);
2210   else
2211     {
2212     pw = getpwuid(*((uid_t *)value));
2213     if (pw == NULL)
2214       printf("%s = %ld\n", name, (long int)(*((uid_t *)value)));
2215     else printf("%s = %s\n", name, pw->pw_name);
2216     }
2217   break;
2218
2219   /* If the numerical value is unset, try for the string value */
2220
2221   case opt_expand_gid:
2222   if (! *get_set_flag(name, oltop, last, options_block))
2223     {
2224     sprintf(CS name2, "*expand_%.50s", name);
2225     ol2 = find_option(name2, oltop, last);
2226     if (ol2 != NULL && (ol2->type & opt_mask) == opt_stringptr)
2227       {
2228       void *value2 = ol2->value;
2229       if (options_block != NULL)
2230         value2 = (void *)((uschar *)options_block + (long int)value2);
2231       s = *((uschar **)value2);
2232       printf("%s = %s\n", name, (s == NULL)? US"" : string_printing(s));
2233       break;
2234       }
2235     }
2236
2237   /* Else fall through */
2238
2239   case opt_gid:
2240   if (! *get_set_flag(name, oltop, last, options_block))
2241     printf("%s =\n", name);
2242   else
2243     {
2244     gr = getgrgid(*((int *)value));
2245     if (gr == NULL)
2246        printf("%s = %ld\n", name, (long int)(*((int *)value)));
2247     else printf("%s = %s\n", name, gr->gr_name);
2248     }
2249   break;
2250
2251   case opt_uidlist:
2252   uidlist = *((uid_t **)value);
2253   printf("%s =", name);
2254   if (uidlist != NULL)
2255     {
2256     int i;
2257     uschar sep = ' ';
2258     for (i = 1; i <= (int)(uidlist[0]); i++)
2259       {
2260       uschar *name = NULL;
2261       pw = getpwuid(uidlist[i]);
2262       if (pw != NULL) name = US pw->pw_name;
2263       if (name != NULL) printf("%c%s", sep, name);
2264         else printf("%c%ld", sep, (long int)(uidlist[i]));
2265       sep = ':';
2266       }
2267     }
2268   printf("\n");
2269   break;
2270
2271   case opt_gidlist:
2272   gidlist = *((gid_t **)value);
2273   printf("%s =", name);
2274   if (gidlist != NULL)
2275     {
2276     int i;
2277     uschar sep = ' ';
2278     for (i = 1; i <= (int)(gidlist[0]); i++)
2279       {
2280       uschar *name = NULL;
2281       gr = getgrgid(gidlist[i]);
2282       if (gr != NULL) name = US gr->gr_name;
2283       if (name != NULL) printf("%c%s", sep, name);
2284         else printf("%c%ld", sep, (long int)(gidlist[i]));
2285       sep = ':';
2286       }
2287     }
2288   printf("\n");
2289   break;
2290
2291   case opt_time:
2292   printf("%s = %s\n", name, readconf_printtime(*((int *)value)));
2293   break;
2294
2295   case opt_timelist:
2296     {
2297     int i;
2298     int *list = (int *)value;
2299     printf("%s = ", name);
2300     for (i = 0; i < list[1]; i++)
2301       printf("%s%s", (i == 0)? "" : ":", readconf_printtime(list[i+2]));
2302     printf("\n");
2303     }
2304   break;
2305
2306   case opt_bit:
2307   printf("%s%s\n", ((*((int *)value)) & (1 << ((ol->type >> 16) & 31)))?
2308     "" : "no_", name);
2309   break;
2310
2311   case opt_expand_bool:
2312   sprintf(CS name2, "*expand_%.50s", name);
2313   ol2 = find_option(name2, oltop, last);
2314   if (ol2 != NULL && ol2->value != NULL)
2315     {
2316     void *value2 = ol2->value;
2317     if (options_block != NULL)
2318       value2 = (void *)((uschar *)options_block + (long int)value2);
2319     s = *((uschar **)value2);
2320     if (s != NULL)
2321       {
2322       printf("%s = %s\n", name, string_printing(s));
2323       break;
2324       }
2325     /* s == NULL => string not set; fall through */
2326     }
2327
2328   /* Fall through */
2329
2330   case opt_bool:
2331   case opt_bool_verify:
2332   case opt_bool_set:
2333   printf("%s%s\n", (*((BOOL *)value))? "" : "no_", name);
2334   break;
2335   }
2336 }
2337
2338
2339
2340 /*************************************************
2341 *        Print value from main configuration     *
2342 *************************************************/
2343
2344 /* This function, called as a result of encountering the -bP option,
2345 causes the value of any main configuration variable to be output if the
2346 second argument is NULL. There are some special values:
2347
2348   all                print all main configuration options
2349   configure_file     print the name of the configuration file
2350   routers            print the routers' configurations
2351   transports         print the transports' configuration
2352   authenticators     print the authenticators' configuration
2353   router_list        print a list of router names
2354   transport_list     print a list of transport names
2355   authenticator_list print a list of authentication mechanism names
2356   +name              print a named list item
2357   local_scan         print the local_scan options
2358
2359 If the second argument is not NULL, it must be one of "router", "transport", or
2360 "authenticator" in which case the first argument identifies the driver whose
2361 options are to be printed.
2362
2363 Arguments:
2364   name        option name if type == NULL; else driver name
2365   type        NULL or driver type name, as described above
2366
2367 Returns:      nothing
2368 */
2369
2370 void
2371 readconf_print(uschar *name, uschar *type)
2372 {
2373 BOOL names_only = FALSE;
2374 optionlist *ol;
2375 optionlist *ol2 = NULL;
2376 driver_instance *d = NULL;
2377 int size = 0;
2378
2379 if (type == NULL)
2380   {
2381   if (*name == '+')
2382     {
2383     int i;
2384     tree_node *t;
2385     BOOL found = FALSE;
2386     static uschar *types[] = { US"address", US"domain", US"host",
2387       US"localpart" };
2388     static tree_node **anchors[] = { &addresslist_anchor, &domainlist_anchor,
2389       &hostlist_anchor, &localpartlist_anchor };
2390
2391     for (i = 0; i < 4; i++)
2392       {
2393       t = tree_search(*(anchors[i]), name+1);
2394       if (t != NULL)
2395         {
2396         found = TRUE;
2397         printf("%slist %s = %s\n", types[i], name+1,
2398           ((namedlist_block *)(t->data.ptr))->string);
2399         }
2400       }
2401
2402     if (!found)
2403       printf("no address, domain, host, or local part list called \"%s\" "
2404         "exists\n", name+1);
2405
2406     return;
2407     }
2408
2409   if (Ustrcmp(name, "configure_file") == 0)
2410     {
2411     printf("%s\n", CS config_main_filename);
2412     return;
2413     }
2414
2415   if (Ustrcmp(name, "all") == 0)
2416     {
2417     for (ol = optionlist_config;
2418          ol < optionlist_config + optionlist_config_size; ol++)
2419       {
2420       if ((ol->type & opt_hidden) == 0)
2421         print_ol(ol, US ol->name, NULL, optionlist_config, optionlist_config_size);
2422       }
2423     return;
2424     }
2425
2426   if (Ustrcmp(name, "local_scan") == 0)
2427     {
2428     #ifndef LOCAL_SCAN_HAS_OPTIONS
2429     printf("local_scan() options are not supported\n");
2430     #else
2431     for (ol = local_scan_options;
2432          ol < local_scan_options + local_scan_options_count; ol++)
2433       {
2434       print_ol(ol, US ol->name, NULL, local_scan_options,
2435         local_scan_options_count);
2436       }
2437     #endif
2438     return;
2439     }
2440
2441   if (Ustrcmp(name, "routers") == 0)
2442     {
2443     type = US"router";
2444     name = NULL;
2445     }
2446   else if (Ustrcmp(name, "transports") == 0)
2447     {
2448     type = US"transport";
2449     name = NULL;
2450     }
2451
2452   else if (Ustrcmp(name, "authenticators") == 0)
2453     {
2454     type = US"authenticator";
2455     name = NULL;
2456     }
2457
2458   else if (Ustrcmp(name, "authenticator_list") == 0)
2459     {
2460     type = US"authenticator";
2461     name = NULL;
2462     names_only = TRUE;
2463     }
2464
2465   else if (Ustrcmp(name, "router_list") == 0)
2466     {
2467     type = US"router";
2468     name = NULL;
2469     names_only = TRUE;
2470     }
2471   else if (Ustrcmp(name, "transport_list") == 0)
2472     {
2473     type = US"transport";
2474     name = NULL;
2475     names_only = TRUE;
2476     }
2477   else
2478     {
2479     print_ol(find_option(name, optionlist_config, optionlist_config_size),
2480       name, NULL, optionlist_config, optionlist_config_size);
2481     return;
2482     }
2483   }
2484
2485 /* Handle the options for a router or transport. Skip options that are flagged
2486 as hidden. Some of these are options with names starting with '*', used for
2487 internal alternative representations of other options (which the printing
2488 function will sort out). Others are synonyms kept for backward compatibility.
2489 */
2490
2491 if (Ustrcmp(type, "router") == 0)
2492   {
2493   d = (driver_instance *)routers;
2494   ol2 = optionlist_routers;
2495   size = optionlist_routers_size;
2496   }
2497 else if (Ustrcmp(type, "transport") == 0)
2498   {
2499   d = (driver_instance *)transports;
2500   ol2 = optionlist_transports;
2501   size = optionlist_transports_size;
2502   }
2503 else if (Ustrcmp(type, "authenticator") == 0)
2504   {
2505   d = (driver_instance *)auths;
2506   ol2 = optionlist_auths;
2507   size = optionlist_auths_size;
2508   }
2509
2510 if (names_only)
2511   {
2512   for (; d != NULL; d = d->next) printf("%s\n", CS d->name);
2513   return;
2514   }
2515
2516 /* Either search for a given driver, or print all of them */
2517
2518 for (; d != NULL; d = d->next)
2519   {
2520   if (name == NULL)
2521     printf("\n%s %s:\n", d->name, type);
2522   else if (Ustrcmp(d->name, name) != 0) continue;
2523
2524   for (ol = ol2; ol < ol2 + size; ol++)
2525     {
2526     if ((ol->type & opt_hidden) == 0)
2527       print_ol(ol, US ol->name, d, ol2, size);
2528     }
2529
2530   for (ol = d->info->options;
2531        ol < d->info->options + *(d->info->options_count); ol++)
2532     {
2533     if ((ol->type & opt_hidden) == 0)
2534       print_ol(ol, US ol->name, d, d->info->options, *(d->info->options_count));
2535     }
2536   if (name != NULL) return;
2537   }
2538 if (name != NULL) printf("%s %s not found\n", type, name);
2539 }
2540
2541
2542
2543 /*************************************************
2544 *          Read a named list item                *
2545 *************************************************/
2546
2547 /* This function reads a name and a list (i.e. string). The name is used to
2548 save the list in a tree, sorted by its name. Each entry also has a number,
2549 which can be used for caching tests, but if the string contains any expansion
2550 items other than $key, the number is set negative to inhibit caching. This
2551 mechanism is used for domain, host, and address lists that are referenced by
2552 the "+name" syntax.
2553
2554 Arguments:
2555   anchorp     points to the tree anchor
2556   numberp     points to the current number for this tree
2557   max         the maximum number permitted
2558   s           the text of the option line, starting immediately after the name
2559                 of the list type
2560   tname       the name of the list type, for messages
2561
2562 Returns:      nothing
2563 */
2564
2565 static void
2566 read_named_list(tree_node **anchorp, int *numberp, int max, uschar *s,
2567   uschar *tname)
2568 {
2569 BOOL forcecache = FALSE;
2570 uschar *ss;
2571 tree_node *t;
2572 namedlist_block *nb = store_get(sizeof(namedlist_block));
2573
2574 if (Ustrncmp(s, "_cache", 6) == 0)
2575   {
2576   forcecache = TRUE;
2577   s += 6;
2578   }
2579
2580 if (!isspace(*s))
2581   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "unrecognized configuration line");
2582
2583 if (*numberp >= max)
2584  log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "too many named %ss (max is %d)\n",
2585    tname, max);
2586
2587 while (isspace(*s)) s++;
2588 ss = s;
2589 while (isalnum(*s) || *s == '_') s++;
2590 t = store_get(sizeof(tree_node) + s-ss);
2591 Ustrncpy(t->name, ss, s-ss);
2592 t->name[s-ss] = 0;
2593 while (isspace(*s)) s++;
2594
2595 if (!tree_insertnode(anchorp, t))
2596   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
2597     "duplicate name \"%s\" for a named %s", t->name, tname);
2598
2599 t->data.ptr = nb;
2600 nb->number = *numberp;
2601 *numberp += 1;
2602
2603 if (*s++ != '=') log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
2604   "missing '=' after \"%s\"", t->name);
2605 while (isspace(*s)) s++;
2606 nb->string = read_string(s, t->name);
2607 nb->cache_data = NULL;
2608
2609 /* Check the string for any expansions; if any are found, mark this list
2610 uncacheable unless the user has explicited forced caching. */
2611
2612 if (!forcecache && Ustrchr(nb->string, '$') != NULL) nb->number = -1;
2613 }
2614
2615
2616
2617
2618 /*************************************************
2619 *        Unpick data for a rate limit            *
2620 *************************************************/
2621
2622 /* This function is called to unpick smtp_ratelimit_{mail,rcpt} into four
2623 separate values.
2624
2625 Arguments:
2626   s            string, in the form t,b,f,l
2627                where t is the threshold (integer)
2628                b is the initial delay (time)
2629                f is the multiplicative factor (fixed point)
2630                k is the maximum time (time)
2631   threshold    where to store threshold
2632   base         where to store base in milliseconds
2633   factor       where to store factor in milliseconds
2634   limit        where to store limit
2635
2636 Returns:       nothing (panics on error)
2637 */
2638
2639 static void
2640 unpick_ratelimit(uschar *s, int *threshold, int *base, double *factor,
2641   int *limit)
2642 {
2643 uschar bstring[16], lstring[16];
2644
2645 if (sscanf(CS s, "%d, %15[0123456789smhdw.], %lf, %15s", threshold, bstring,
2646     factor, lstring) == 4)
2647   {
2648   *base = readconf_readtime(bstring, 0, TRUE);
2649   *limit = readconf_readtime(lstring, 0, TRUE);
2650   if (*base >= 0 && *limit >= 0) return;
2651   }
2652 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "malformed ratelimit data: %s", s);
2653 }
2654
2655
2656
2657
2658 /*************************************************
2659 *         Read main configuration options        *
2660 *************************************************/
2661
2662 /* This function is the first to be called for configuration reading. It
2663 opens the configuration file and reads general configuration settings until
2664 it reaches the end of the configuration section. The file is then left open so
2665 that the remaining configuration data can subsequently be read if needed for
2666 this run of Exim.
2667
2668 The configuration file must be owned either by root or exim, and be writeable
2669 only by root or uid/gid exim. The values for Exim's uid and gid can be changed
2670 in the config file, so the test is done on the compiled in values. A slight
2671 anomaly, to be carefully documented.
2672
2673 The name of the configuration file is taken from a list that is included in the
2674 binary of Exim. It can be altered from the command line, but if that is done,
2675 root privilege is immediately withdrawn unless the caller is root or exim.
2676 The first file on the list that exists is used.
2677
2678 For use on multiple systems that share file systems, first look for a
2679 configuration file whose name has the current node name on the end. If that is
2680 not found, try the generic name. For really contorted configurations, that run
2681 multiple Exims with different uid settings, first try adding the effective uid
2682 before the node name. These complications are going to waste resources on most
2683 systems. Therefore they are available only when requested by compile-time
2684 options. */
2685
2686 void
2687 readconf_main(void)
2688 {
2689 int sep = 0;
2690 struct stat statbuf;
2691 uschar *s, *filename;
2692 uschar *list = config_main_filelist;
2693
2694 /* Loop through the possible file names */
2695
2696 while((filename = string_nextinlist(&list, &sep, big_buffer, big_buffer_size))
2697        != NULL)
2698   {
2699   /* Cut out all the fancy processing unless specifically wanted */
2700
2701   #if defined(CONFIGURE_FILE_USE_NODE) || defined(CONFIGURE_FILE_USE_EUID)
2702   uschar *suffix = filename + Ustrlen(filename);
2703
2704   /* Try for the node-specific file if a node name exists */
2705
2706   #ifdef CONFIGURE_FILE_USE_NODE
2707   struct utsname uts;
2708   if (uname(&uts) >= 0)
2709     {
2710     #ifdef CONFIGURE_FILE_USE_EUID
2711     sprintf(CS suffix, ".%ld.%.256s", (long int)original_euid, uts.nodename);
2712     config_file = Ufopen(filename, "rb");
2713     if (config_file == NULL)
2714     #endif  /* CONFIGURE_FILE_USE_EUID */
2715       {
2716       sprintf(CS suffix, ".%.256s", uts.nodename);
2717       config_file = Ufopen(filename, "rb");
2718       }
2719     }
2720   #endif  /* CONFIGURE_FILE_USE_NODE */
2721
2722   /* Otherwise, try the generic name, possibly with the euid added */
2723
2724   #ifdef CONFIGURE_FILE_USE_EUID
2725   if (config_file == NULL)
2726     {
2727     sprintf(CS suffix, ".%ld", (long int)original_euid);
2728     config_file = Ufopen(filename, "rb");
2729     }
2730   #endif  /* CONFIGURE_FILE_USE_EUID */
2731
2732   /* Finally, try the unadorned name */
2733
2734   if (config_file == NULL)
2735     {
2736     *suffix = 0;
2737     config_file = Ufopen(filename, "rb");
2738     }
2739   #else  /* if neither defined */
2740
2741   /* This is the common case when the fancy processing is not included. */
2742
2743   config_file = Ufopen(filename, "rb");
2744   #endif
2745
2746   /* If the file does not exist, continue to try any others. For any other
2747   error, break out (and die). */
2748
2749   if (config_file != NULL || errno != ENOENT) break;
2750   }
2751
2752 /* On success, save the name for verification; config_filename is used when
2753 logging configuration errors (it changes for .included files) whereas
2754 config_main_filename is the name shown by -bP. Failure to open a configuration
2755 file is a serious disaster. */
2756
2757 if (config_file != NULL)
2758   {
2759   config_filename = config_main_filename = string_copy(filename);
2760   }
2761 else
2762   {
2763   if (filename == NULL)
2764     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "non-existent configuration file(s): "
2765       "%s", config_main_filelist);
2766   else
2767     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s", string_open_failed(errno,
2768       "configuration file %s", filename));
2769   }
2770
2771 /* Check the status of the file we have opened, unless it was specified on
2772 the command line, in which case privilege was given away at the start. */
2773
2774 if (!config_changed)
2775   {
2776   if (fstat(fileno(config_file), &statbuf) != 0)
2777     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to stat configuration file %s",
2778       big_buffer);
2779
2780   if ((statbuf.st_uid != root_uid &&             /* owner not root */
2781        statbuf.st_uid != exim_uid                /* owner not exim */
2782        #ifdef CONFIGURE_OWNER
2783        && statbuf.st_uid != config_uid           /* owner not the special one */
2784        #endif
2785          ) ||                                    /* or */
2786       (statbuf.st_gid != exim_gid                /* group not exim & */
2787        #ifdef CONFIGURE_GROUP
2788        && statbuf.st_gid != config_gid           /* group not the special one */
2789        #endif
2790        && (statbuf.st_mode & 020) != 0) ||       /* group writeable  */
2791                                                  /* or */
2792       ((statbuf.st_mode & 2) != 0))              /* world writeable  */
2793
2794     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Exim configuration file %s has the "
2795       "wrong owner, group, or mode", big_buffer);
2796   }
2797
2798 /* Process the main configuration settings. They all begin with a lower case
2799 letter. If we see something starting with an upper case letter, it is taken as
2800 a macro definition. */
2801
2802 while ((s = get_config_line()) != NULL)
2803   {
2804   if (isupper(s[0])) read_macro_assignment(s);
2805
2806   else if (Ustrncmp(s, "domainlist", 10) == 0)
2807     read_named_list(&domainlist_anchor, &domainlist_count,
2808       MAX_NAMED_LIST, s+10, US"domain list");
2809
2810   else if (Ustrncmp(s, "hostlist", 8) == 0)
2811     read_named_list(&hostlist_anchor, &hostlist_count,
2812       MAX_NAMED_LIST, s+8, US"host list");
2813
2814   else if (Ustrncmp(s, US"addresslist", 11) == 0)
2815     read_named_list(&addresslist_anchor, &addresslist_count,
2816       MAX_NAMED_LIST, s+11, US"address list");
2817
2818   else if (Ustrncmp(s, US"localpartlist", 13) == 0)
2819     read_named_list(&localpartlist_anchor, &localpartlist_count,
2820       MAX_NAMED_LIST, s+13, US"local part list");
2821
2822   else
2823     (void) readconf_handle_option(s, optionlist_config, optionlist_config_size,
2824       NULL, US"main option \"%s\" unknown");
2825   }
2826
2827
2828 /* If local_sender_retain is set, local_from_check must be unset. */
2829
2830 if (local_sender_retain && local_from_check)
2831   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "both local_from_check and "
2832     "local_sender_retain are set; this combination is not allowed");
2833
2834 /* If the timezone string is empty, set it to NULL, implying no TZ variable
2835 wanted. */
2836
2837 if (timezone_string != NULL && *timezone_string == 0) timezone_string = NULL;
2838
2839 /* The max retry interval must not be greater than 24 hours. */
2840
2841 if (retry_interval_max > 24*60*60) retry_interval_max = 24*60*60;
2842
2843 /* remote_max_parallel must be > 0 */
2844
2845 if (remote_max_parallel <= 0) remote_max_parallel = 1;
2846
2847 /* Save the configured setting of freeze_tell, so we can re-instate it at the
2848 start of a new SMTP message. */
2849
2850 freeze_tell_config = freeze_tell;
2851
2852 /* The primary host name may be required for expansion of spool_directory
2853 and log_file_path, so make sure it is set asap. It is obtained from uname(),
2854 but if that yields an unqualified value, make a FQDN by using gethostbyname to
2855 canonize it. Some people like upper case letters in their host names, so we
2856 don't force the case. */
2857
2858 if (primary_hostname == NULL)
2859   {
2860   uschar *hostname;
2861   struct utsname uts;
2862   if (uname(&uts) < 0)
2863     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "uname() failed to yield host name");
2864   hostname = US uts.nodename;
2865
2866   if (Ustrchr(hostname, '.') == NULL)
2867     {
2868     int af = AF_INET;
2869     struct hostent *hostdata;
2870
2871     #if HAVE_IPV6
2872     if (!disable_ipv6 && (dns_ipv4_lookup == NULL ||
2873          match_isinlist(hostname, &dns_ipv4_lookup, 0, NULL, NULL, MCL_DOMAIN,
2874            TRUE, NULL) != OK))
2875       af = AF_INET6;
2876     #else
2877     af = AF_INET;
2878     #endif
2879
2880     for (;;)
2881       {
2882       #if HAVE_IPV6
2883         #if HAVE_GETIPNODEBYNAME
2884         int error_num;
2885         hostdata = getipnodebyname(CS hostname, af, 0, &error_num);
2886         #else
2887         hostdata = gethostbyname2(CS hostname, af);
2888         #endif
2889       #else
2890       hostdata = gethostbyname(CS hostname);
2891       #endif
2892
2893       if (hostdata != NULL)
2894         {
2895         hostname = US hostdata->h_name;
2896         break;
2897         }
2898
2899       if (af == AF_INET) break;
2900       af = AF_INET;
2901       }
2902     }
2903
2904   primary_hostname = string_copy(hostname);
2905   }
2906
2907 /* Set up default value for smtp_active_hostname */
2908
2909 smtp_active_hostname = primary_hostname;
2910
2911 /* If spool_directory wasn't set in the build-time configuration, it must have
2912 got set above. Of course, writing to the log may not work if log_file_path is
2913 not set, but it will at least get to syslog or somewhere, with any luck. */
2914
2915 if (*spool_directory == 0)
2916   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "spool_directory undefined: cannot "
2917     "proceed");
2918
2919 /* Expand the spool directory name; it may, for example, contain the primary
2920 host name. Same comment about failure. */
2921
2922 s = expand_string(spool_directory);
2923 if (s == NULL)
2924   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand spool_directory "
2925     "\"%s\": %s", spool_directory, expand_string_message);
2926 spool_directory = s;
2927
2928 /* Expand log_file_path, which must contain "%s" in any component that isn't
2929 the null string or "syslog". It is also allowed to contain one instance of %D.
2930 However, it must NOT contain % followed by anything else. */
2931
2932 if (*log_file_path != 0)
2933   {
2934   uschar *ss, *sss;
2935   int sep = ':';                       /* Fixed for log file path */
2936   s = expand_string(log_file_path);
2937   if (s == NULL)
2938     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand log_file_path "
2939       "\"%s\": %s", log_file_path, expand_string_message);
2940
2941   ss = s;
2942   while ((sss = string_nextinlist(&ss,&sep,big_buffer,big_buffer_size)) != NULL)
2943     {
2944     uschar *t;
2945     if (sss[0] == 0 || Ustrcmp(sss, "syslog") == 0) continue;
2946     t = Ustrstr(sss, "%s");
2947     if (t == NULL)
2948       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "log_file_path \"%s\" does not "
2949         "contain \"%%s\"", sss);
2950     *t = 'X';
2951     t = Ustrchr(sss, '%');
2952     if (t != NULL)
2953       {
2954       if (t[1] != 'D' || Ustrchr(t+2, '%') != NULL)
2955         log_write(0, LOG_MAIN|LOG_PANIC_DIE, "log_file_path \"%s\" contains "
2956           "unexpected \"%%\" character", s);
2957       }
2958     }
2959
2960   log_file_path = s;
2961   }
2962
2963 /* Interpret syslog_facility into an integer argument for 'ident' param to
2964 openlog(). Default is LOG_MAIL set in globals.c. Allow the user to omit the
2965 leading "log_". */
2966
2967 if (syslog_facility_str != NULL)
2968   {
2969   int i;
2970   uschar *s = syslog_facility_str;
2971
2972   if ((Ustrlen(syslog_facility_str) >= 4) &&
2973         (strncmpic(syslog_facility_str, US"log_", 4) == 0))
2974     s += 4;
2975
2976   for (i = 0; i < syslog_list_size; i++)
2977     {
2978     if (strcmpic(s, syslog_list[i].name) == 0)
2979       {
2980       syslog_facility = syslog_list[i].value;
2981       break;
2982       }
2983     }
2984
2985   if (i >= syslog_list_size)
2986     {
2987     log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
2988       "failed to interpret syslog_facility \"%s\"", syslog_facility_str);
2989     }
2990   }
2991
2992 /* Expand pid_file_path */
2993
2994 if (*pid_file_path != 0)
2995   {
2996   s = expand_string(pid_file_path);
2997   if (s == NULL)
2998     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand pid_file_path "
2999       "\"%s\": %s", pid_file_path, expand_string_message);
3000   pid_file_path = s;
3001   }
3002
3003 /* Compile the regex for matching a UUCP-style "From_" line in an incoming
3004 message. */
3005
3006 regex_From = regex_must_compile(uucp_from_pattern, FALSE, TRUE);
3007
3008 /* Unpick the SMTP rate limiting options, if set */
3009
3010 if (smtp_ratelimit_mail != NULL)
3011   {
3012   unpick_ratelimit(smtp_ratelimit_mail, &smtp_rlm_threshold,
3013     &smtp_rlm_base, &smtp_rlm_factor, &smtp_rlm_limit);
3014   }
3015
3016 if (smtp_ratelimit_rcpt != NULL)
3017   {
3018   unpick_ratelimit(smtp_ratelimit_rcpt, &smtp_rlr_threshold,
3019     &smtp_rlr_base, &smtp_rlr_factor, &smtp_rlr_limit);
3020   }
3021
3022 /* The qualify domains default to the primary host name */
3023
3024 if (qualify_domain_sender == NULL)
3025   qualify_domain_sender = primary_hostname;
3026 if (qualify_domain_recipient == NULL)
3027   qualify_domain_recipient = qualify_domain_sender;
3028
3029 /* Setting system_filter_user in the configuration sets the gid as well if a
3030 name is given, but a numerical value does not. */
3031
3032 if (system_filter_uid_set && !system_filter_gid_set)
3033   {
3034   struct passwd *pw = getpwuid(system_filter_uid);
3035   if (pw == NULL)
3036     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Failed to look up uid %ld",
3037       (long int)system_filter_uid);
3038   system_filter_gid = pw->pw_gid;
3039   system_filter_gid_set = TRUE;
3040   }
3041
3042 /* If the errors_reply_to field is set, check that it is syntactically valid
3043 and ensure it contains a domain. */
3044
3045 if (errors_reply_to != NULL)
3046   {
3047   uschar *errmess;
3048   int start, end, domain;
3049   uschar *recipient = parse_extract_address(errors_reply_to, &errmess,
3050     &start, &end, &domain, FALSE);
3051
3052   if (recipient == NULL)
3053     log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
3054       "error in errors_reply_to (%s): %s", errors_reply_to, errmess);
3055
3056   if (domain == 0)
3057     log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
3058       "errors_reply_to (%s) does not contain a domain", errors_reply_to);
3059   }
3060
3061 /* If smtp_accept_queue or smtp_accept_max_per_host is set, then
3062 smtp_accept_max must also be set. */
3063
3064 if (smtp_accept_max == 0 &&
3065     (smtp_accept_queue > 0 || smtp_accept_max_per_host != NULL))
3066   log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
3067     "smtp_accept_max must be set if smtp_accept_queue or "
3068     "smtp_accept_max_per_host is set");
3069
3070 /* Set up the host number if anything is specified. It is an expanded string
3071 so that it can be computed from the host name, for example. We do this last
3072 so as to ensure that everything else is set up before the expansion. */
3073
3074 if (host_number_string != NULL)
3075   {
3076   uschar *end;
3077   uschar *s = expand_string(host_number_string);
3078   long int n = Ustrtol(s, &end, 0);
3079   while (isspace(*end)) end++;
3080   if (*end != 0)
3081     log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
3082       "localhost_number value is not a number: %s", s);
3083   if (n > LOCALHOST_MAX)
3084     log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
3085       "localhost_number is greater than the maximum allowed value (%d)",
3086         LOCALHOST_MAX);
3087   host_number = n;
3088   }
3089
3090 #ifdef SUPPORT_TLS
3091 /* If tls_verify_hosts is set, tls_verify_certificates must also be set */
3092
3093 if ((tls_verify_hosts != NULL || tls_try_verify_hosts != NULL) &&
3094      tls_verify_certificates == NULL)
3095   log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
3096     "tls_%sverify_hosts is set, but tls_verify_certificates is not set",
3097     (tls_verify_hosts != NULL)? "" : "try_");
3098 #endif
3099 }
3100
3101
3102
3103 /*************************************************
3104 *          Initialize one driver                 *
3105 *************************************************/
3106
3107 /* This is called once the driver's generic options, if any, have been read.
3108 We can now find the driver, set up defaults for the private options, and
3109 unset any "set" bits in the private options table (which might have been
3110 set by another incarnation of the same driver).
3111
3112 Arguments:
3113   d                   pointer to driver instance block, with generic
3114                         options filled in
3115   drivers_available   vector of available drivers
3116   size_of_info        size of each block in drivers_available
3117   class               class of driver, for error message
3118
3119 Returns:              pointer to the driver info block
3120 */
3121
3122 static driver_info *
3123 init_driver(driver_instance *d, driver_info *drivers_available,
3124   int size_of_info, uschar *class)
3125 {
3126 driver_info *dd;
3127
3128 for (dd = drivers_available; dd->driver_name[0] != 0;
3129      dd = (driver_info *)(((uschar *)dd) + size_of_info))
3130   {
3131   if (Ustrcmp(d->driver_name, dd->driver_name) == 0)
3132     {
3133     int i;
3134     int len = dd->options_len;
3135     d->info = dd;
3136     d->options_block = store_get(len);
3137     memcpy(d->options_block, dd->options_block, len);
3138     for (i = 0; i < *(dd->options_count); i++)
3139       dd->options[i].type &= ~opt_set;
3140     return dd;
3141     }
3142   }
3143
3144 log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
3145   "%s %s: cannot find %s driver \"%s\"", class, d->name, class, d->driver_name);
3146
3147 return NULL;   /* never obeyed */
3148 }
3149
3150
3151
3152
3153 /*************************************************
3154 *             Initialize driver list             *
3155 *************************************************/
3156
3157 /* This function is called for routers, transports, and authentication
3158 mechanisms. It reads the data from the current point in the configuration file
3159 up to the end of the section, and sets up a chain of instance blocks according
3160 to the file's contents. The file will already have been opened by a call to
3161 readconf_main, and must be left open for subsequent reading of further data.
3162
3163 Any errors cause a panic crash. Note that the blocks with names driver_info and
3164 driver_instance must map the first portions of all the _info and _instance
3165 blocks for this shared code to work.
3166
3167 Arguments:
3168   class                      "router", "transport", or "authenticator"
3169   anchor                     &routers, &transports, &auths
3170   drivers_available          available drivers
3171   size_of_info               size of each info block
3172   instance_default           points to default data for an instance
3173   instance_size              size of instance block
3174   driver_optionlist          generic option list
3175   driver_optionlist_count    count of generic option list
3176
3177 Returns:                     nothing
3178 */
3179
3180 void
3181 readconf_driver_init(
3182   uschar *class,
3183   driver_instance **anchor,
3184   driver_info *drivers_available,
3185   int size_of_info,
3186   void *instance_default,
3187   int  instance_size,
3188   optionlist *driver_optionlist,
3189   int  driver_optionlist_count)
3190 {
3191 driver_instance **p = anchor;
3192 driver_instance *d = NULL;
3193 uschar *buffer;
3194
3195 while ((buffer = get_config_line()) != NULL)
3196   {
3197   uschar name[64];
3198   uschar *s;
3199
3200   /* Read the first name on the line and test for the start of a new driver. A
3201   macro definition indicates the end of the previous driver. If this isn't the
3202   start of a new driver, the line will be re-read. */
3203
3204   s = readconf_readname(name, sizeof(name), buffer);
3205
3206   /* Handle macro definition, first finishing off the initialization of the
3207   previous driver, if any. */
3208
3209   if (isupper(*name) && *s == '=')
3210     {
3211     if (d != NULL)
3212       {
3213       if (d->driver_name == NULL)
3214         log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
3215           "no driver defined for %s \"%s\"", class, d->name);
3216       (d->info->init)(d);
3217       d = NULL;
3218       }
3219     read_macro_assignment(buffer);
3220     continue;
3221     }
3222
3223   /* If the line starts with a name terminated by a colon, we are at the
3224   start of the definition of a new driver. The rest of the line must be
3225   blank. */
3226
3227   if (*s++ == ':')
3228     {
3229     int i;
3230
3231     /* Finish off initializing the previous driver. */
3232
3233     if (d != NULL)
3234       {
3235       if (d->driver_name == NULL)
3236         log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
3237           "no driver defined for %s \"%s\"", class, d->name);
3238       (d->info->init)(d);
3239       }
3240
3241     /* Check that we haven't already got a driver of this name */
3242
3243     for (d = *anchor; d != NULL; d = d->next)
3244       if (Ustrcmp(name, d->name) == 0)
3245         log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
3246           "there are two %ss called \"%s\"", class, name);
3247
3248     /* Set up a new driver instance data block on the chain, with
3249     its default values installed. */
3250
3251     d = store_get(instance_size);
3252     memcpy(d, instance_default, instance_size);
3253     *p = d;
3254     p = &(d->next);
3255     d->name = string_copy(name);
3256
3257     /* Clear out the "set" bits in the generic options */
3258
3259     for (i = 0; i < driver_optionlist_count; i++)
3260       driver_optionlist[i].type &= ~opt_set;
3261
3262     /* Check nothing more on this line, then do the next loop iteration. */
3263
3264     while (isspace(*s)) s++;
3265     if (*s != 0) extra_chars_error(s, US"driver name ", name, US"");
3266     continue;
3267     }
3268
3269   /* Not the start of a new driver. Give an error if we have not set up a
3270   current driver yet. */
3271
3272   if (d == NULL) log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
3273     "%s name missing", class);
3274
3275   /* First look to see if this is a generic option; if it is "driver",
3276   initialize the driver. If is it not a generic option, we can look for a
3277   private option provided that the driver has been previously set up. */
3278
3279   if (readconf_handle_option(buffer, driver_optionlist,
3280         driver_optionlist_count, d, NULL))
3281     {
3282     if (d->info == NULL && d->driver_name != NULL)
3283       init_driver(d, drivers_available, size_of_info, class);
3284     }
3285
3286   /* Handle private options - pass the generic block because some may
3287   live therein. A flag with each option indicates if it is in the public
3288   block. */
3289
3290   else if (d->info != NULL)
3291     {
3292     readconf_handle_option(buffer, d->info->options,
3293       *(d->info->options_count), d, US"option \"%s\" unknown");
3294     }
3295
3296   /* The option is not generic and the driver name has not yet been given. */
3297
3298   else log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "option \"%s\" unknown "
3299     "(\"driver\" must be specified before any private options)", name);
3300   }
3301
3302 /* Run the initialization function for the final driver. */
3303
3304 if (d != NULL)
3305   {
3306   if (d->driver_name == NULL)
3307     log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
3308       "no driver defined for %s \"%s\"", class, d->name);
3309   (d->info->init)(d);
3310   }
3311 }
3312
3313
3314
3315 /*************************************************
3316 *            Check driver dependency             *
3317 *************************************************/
3318
3319 /* This function is passed a driver instance and a string. It checks whether
3320 any of the string options for the driver contains the given string as an
3321 expansion variable.
3322
3323 Arguments:
3324   d        points to a driver instance block
3325   s        the string to search for
3326
3327 Returns:   TRUE if a dependency is found
3328 */
3329
3330 BOOL
3331 readconf_depends(driver_instance *d, uschar *s)
3332 {
3333 int count = *(d->info->options_count);
3334 optionlist *ol;
3335 uschar *ss;
3336
3337 for (ol = d->info->options; ol < d->info->options + count; ol++)
3338   {
3339   void *options_block;
3340   uschar *value;
3341   int type = ol->type & opt_mask;
3342   if (type != opt_stringptr) continue;
3343   options_block = ((ol->type & opt_public) == 0)? d->options_block : (void *)d;
3344   value = *(uschar **)((uschar *)options_block + (long int)(ol->value));
3345   if (value != NULL && (ss = Ustrstr(value, s)) != NULL)
3346     {
3347     if (ss <= value || (ss[-1] != '$' && ss[-1] != '{') ||
3348       isalnum(ss[Ustrlen(s)])) continue;
3349     DEBUG(D_transport) debug_printf("driver %s: \"%s\" option depends on %s\n",
3350       d->name, ol->name, s);
3351     return TRUE;
3352     }
3353   }
3354
3355 DEBUG(D_transport) debug_printf("driver %s does not depend on %s\n", d->name, s);
3356 return FALSE;
3357 }
3358
3359
3360
3361
3362 /*************************************************
3363 *      Decode an error type for retries          *
3364 *************************************************/
3365
3366 /* This function is global because it is also called from the main
3367 program when testing retry information. It decodes strings such as "quota_7d"
3368 into numerical error codes.
3369
3370 Arguments:
3371   pp           points to start of text
3372   p            points past end of text
3373   basic_errno  points to an int to receive the main error number
3374   more_errno   points to an int to receive the secondary error data
3375
3376 Returns:       NULL if decoded correctly; else points to error text
3377 */
3378
3379 uschar *
3380 readconf_retry_error(uschar *pp, uschar *p, int *basic_errno, int *more_errno)
3381 {
3382 int len;
3383 uschar *q = pp;
3384 while (q < p && *q != '_') q++;
3385 len = q - pp;
3386
3387 if (len == 5 && strncmpic(pp, US"quota", len) == 0)
3388   {
3389   *basic_errno = ERRNO_EXIMQUOTA;
3390   if (q != p && (*more_errno = readconf_readtime(q+1, *p, FALSE)) < 0)
3391       return US"bad time value";
3392   }
3393
3394 else if (len == 7 && strncmpic(pp, US"refused", len) == 0)
3395   {
3396   *basic_errno = ECONNREFUSED;
3397   if (q != p)
3398     {
3399     if (strncmpic(q+1, US"MX", p-q-1) == 0) *more_errno = 'M';
3400     else if (strncmpic(q+1, US"A", p-q-1) == 0) *more_errno = 'A';
3401     else return US"A or MX expected after \"refused\"";
3402     }
3403   }
3404
3405 else if (len == 7 && strncmpic(pp, US"timeout", len) == 0)
3406   {
3407   *basic_errno = ETIMEDOUT;
3408   if (q != p)
3409     {
3410     int i;
3411     int xlen = p - q - 1;
3412     uschar *x = q + 1;
3413
3414     static uschar *extras[] =
3415       { US"A", US"MX", US"connect", US"connect_A",  US"connect_MX" };
3416     static int values[] =
3417       { 'A',   'M',    RTEF_CTOUT,  RTEF_CTOUT|'A', RTEF_CTOUT|'M' };
3418
3419     for (i = 0; i < sizeof(extras)/sizeof(uschar *); i++)
3420       {
3421       if (strncmpic(x, extras[i], xlen) == 0)
3422         {
3423         *more_errno = values[i];
3424         break;
3425         }
3426       }
3427
3428     if (i >= sizeof(extras)/sizeof(uschar *))
3429       {
3430       if (strncmpic(x, US"DNS", xlen) == 0)
3431         {
3432         log_write(0, LOG_MAIN|LOG_PANIC, "\"timeout_dns\" is no longer "
3433           "available in retry rules (it has never worked) - treated as "
3434           "\"timeout\"");
3435         }
3436       else return US"\"A\", \"MX\", or \"connect\" expected after \"timeout\"";
3437       }
3438     }
3439   }
3440
3441 else if (strncmpic(pp, US"mail_4", 6) == 0 ||
3442          strncmpic(pp, US"rcpt_4", 6) == 0 ||
3443          strncmpic(pp, US"data_4", 6) == 0)
3444   {
3445   BOOL bad = FALSE;
3446   int x = 255;                           /* means "any 4xx code" */
3447   if (p != pp + 8) bad = TRUE; else
3448     {
3449     int a = pp[6], b = pp[7];
3450     if (isdigit(a))
3451       {
3452       x = (a - '0') * 10;
3453       if (isdigit(b)) x += b - '0';
3454       else if (b == 'x') x += 100;
3455       else bad = TRUE;
3456       }
3457     else if (a != 'x' || b != 'x') bad = TRUE;
3458     }
3459
3460   if (bad)
3461     return string_sprintf("%.4s_4 must be followed by xx, dx, or dd, where "
3462       "x is literal and d is any digit", pp);
3463
3464   *basic_errno = (*pp == 'm')? ERRNO_MAIL4XX :
3465                  (*pp == 'r')? ERRNO_RCPT4XX : ERRNO_DATA4XX;
3466   *more_errno = x << 8;
3467   }
3468
3469 else if (len == 4 && strncmpic(pp, US"auth", len) == 0 &&
3470          strncmpic(q+1, US"failed", p-q-1) == 0)
3471   *basic_errno = ERRNO_AUTHFAIL;
3472
3473 else if (strncmpic(pp, US"lost_connection", p - pp) == 0)
3474   *basic_errno = ERRNO_SMTPCLOSED;
3475
3476 else if (strncmpic(pp, US"tls_required", p - pp) == 0)
3477   *basic_errno = ERRNO_TLSREQUIRED;
3478
3479 else if (len != 1 || Ustrncmp(pp, "*", 1) != 0)
3480   return string_sprintf("unknown or malformed retry error \"%.*s\"", p-pp, pp);
3481
3482 return NULL;
3483 }
3484
3485
3486
3487
3488 /*************************************************
3489 *                Read retry information          *
3490 *************************************************/
3491
3492 /* Each line of retry information contains:
3493
3494 .  A domain name pattern or an address pattern;
3495
3496 .  An error name, possibly with additional data, or *;
3497
3498 .  An optional sequence of retry items, each consisting of an identifying
3499    letter, a cutoff time, and optional parameters.
3500
3501 All this is decoded and placed into a control block. */
3502
3503
3504 /* Subroutine to read an argument, preceded by a comma and terminated
3505 by comma, semicolon, whitespace, or newline. The types are: 0 = time value,
3506 1 = fixed point number (returned *1000).
3507
3508 Arguments:
3509   paddr     pointer to pointer to current character; updated
3510   type      0 => read a time; 1 => read a fixed point number
3511
3512 Returns:    time in seconds or fixed point number * 1000
3513 */
3514
3515 static int
3516 retry_arg(uschar **paddr, int type)
3517 {
3518 uschar *p = *paddr;
3519 uschar *pp;
3520
3521 if (*p++ != ',') log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "comma expected");
3522
3523 while (isspace(*p)) p++;
3524 pp = p;
3525 while (isalnum(*p) || (type == 1 && *p == '.')) p++;
3526
3527 if (*p != 0 && !isspace(*p) && *p != ',' && *p != ';')
3528   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "comma or semicolon expected");
3529
3530 *paddr = p;
3531 switch (type)
3532   {
3533   case 0:
3534   return readconf_readtime(pp, *p, FALSE);
3535   case 1:
3536   return readconf_readfixed(pp, *p);
3537   }
3538 return 0;    /* Keep picky compilers happy */
3539 }
3540
3541 /* The function proper */
3542
3543 void
3544 readconf_retries(void)
3545 {
3546 retry_config **chain = &retries;
3547 retry_config *next;
3548 uschar *p;
3549
3550 while ((p = get_config_line()) != NULL)
3551   {
3552   retry_rule **rchain;
3553   uschar *pp, *error;
3554
3555   next = store_get(sizeof(retry_config));
3556   next->next = NULL;
3557   *chain = next;
3558   chain = &(next->next);
3559   next->basic_errno = next->more_errno = 0;
3560   next->senders = NULL;
3561   next->rules = NULL;
3562   rchain = &(next->rules);
3563
3564   next->pattern = string_dequote(&p);
3565   while (isspace(*p)) p++;
3566   pp = p;
3567   while (mac_isgraph(*p)) p++;
3568   if (p - pp <= 0) log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
3569     "missing error type");
3570
3571   /* Test error names for things we understand. */
3572
3573   if ((error = readconf_retry_error(pp, p, &(next->basic_errno),
3574        &(next->more_errno))) != NULL)
3575     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "%s", error);
3576
3577   /* There may be an optional address list of senders to be used as another
3578   constraint on the rule. This was added later, so the syntax is a bit of a
3579   fudge. Anything that is not a retry rule starting "F," or "G," is treated as
3580   an address list. */
3581
3582   while (isspace(*p)) p++;
3583   if (Ustrncmp(p, "senders", 7) == 0)
3584     {
3585     p += 7;
3586     while (isspace(*p)) p++;
3587     if (*p++ != '=') log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
3588       "\"=\" expected after \"senders\" in retry rule");
3589     while (isspace(*p)) p++;
3590     next->senders = string_dequote(&p);
3591     }
3592
3593   /* Now the retry rules. Keep the maximum timeout encountered. */
3594
3595   while (isspace(*p)) p++;
3596
3597   while (*p != 0)
3598     {
3599     retry_rule *rule = store_get(sizeof(retry_rule));
3600     *rchain = rule;
3601     rchain = &(rule->next);
3602     rule->next = NULL;
3603     rule->rule = toupper(*p++);
3604     rule->timeout = retry_arg(&p, 0);
3605     if (rule->timeout > retry_maximum_timeout)
3606       retry_maximum_timeout = rule->timeout;
3607
3608     switch (rule->rule)
3609       {
3610       case 'F':   /* Fixed interval */
3611       rule->p1 = retry_arg(&p, 0);
3612       break;
3613
3614       case 'G':   /* Geometrically increasing intervals */
3615       case 'H':   /* Ditto, but with randomness */
3616       rule->p1 = retry_arg(&p, 0);
3617       rule->p2 = retry_arg(&p, 1);
3618       break;
3619
3620       default:
3621       log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "unknown retry rule letter");
3622       break;
3623       }
3624
3625     if (rule->timeout <= 0 || rule->p1 <= 0 ||
3626           (rule->rule != 'F' && rule->p2 < 1000))
3627       log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
3628         "bad parameters for retry rule");
3629
3630     while (isspace(*p)) p++;
3631     if (*p == ';')
3632       {
3633       p++;
3634       while (isspace(*p)) p++;
3635       }
3636     else if (*p != 0)
3637       log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "semicolon expected");
3638     }
3639   }
3640 }
3641
3642
3643
3644 /*************************************************
3645 *         Initialize authenticators              *
3646 *************************************************/
3647
3648 /* Read the authenticators section of the configuration file.
3649
3650 Arguments:   none
3651 Returns:     nothing
3652 */
3653
3654 static void
3655 auths_init(void)
3656 {
3657 auth_instance *au, *bu;
3658 readconf_driver_init(US"authenticator",
3659   (driver_instance **)(&auths),      /* chain anchor */
3660   (driver_info *)auths_available,    /* available drivers */
3661   sizeof(auth_info),                 /* size of info block */
3662   &auth_defaults,                    /* default values for generic options */
3663   sizeof(auth_instance),             /* size of instance block */
3664   optionlist_auths,                  /* generic options */
3665   optionlist_auths_size);
3666
3667 for (au = auths; au != NULL; au = au->next)
3668   {
3669   if (au->public_name == NULL)
3670     log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "no public name specified for "
3671       "the %s authenticator", au->name);
3672   for (bu = au->next; bu != NULL; bu = bu->next)
3673     {
3674     if (strcmpic(au->public_name, bu->public_name) == 0)
3675       {
3676       if ((au->client && bu->client) || (au->server && bu->server))
3677         log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "two %s authenticators "
3678           "(%s and %s) have the same public name (%s)",
3679           (au->client)? US"client" : US"server", au->name, bu->name,
3680           au->public_name);
3681       }
3682     }
3683   }
3684 }
3685
3686
3687
3688
3689 /*************************************************
3690 *             Read ACL information               *
3691 *************************************************/
3692
3693 /* If this run of Exim is not doing something that involves receiving a
3694 message, we can just skip over the ACL information. No need to parse it.
3695
3696 First, we have a function for acl_read() to call back to get the next line. We
3697 need to remember the line we passed, because at the end it will contain the
3698 name of the next ACL. */
3699
3700 static uschar *acl_line;
3701
3702 static uschar *
3703 acl_callback(void)
3704 {
3705 acl_line = get_config_line();
3706 return acl_line;
3707 }
3708
3709
3710 /* Now the main function:
3711
3712 Arguments:
3713   skip        TRUE when this Exim process is doing something that will
3714               not need the ACL data
3715
3716 Returns:      nothing
3717 */
3718
3719 static void
3720 readconf_acl(BOOL skip)
3721 {
3722 uschar *p;
3723
3724 /* Not receiving messages, don't need to parse the ACL data */
3725
3726 if (skip)
3727   {
3728   DEBUG(D_acl) debug_printf("skipping ACL configuration - not needed\n");
3729   while ((p = get_config_line()) != NULL);
3730   return;
3731   }
3732
3733 /* Read each ACL and add it into the tree. Macro (re)definitions are allowed
3734 between ACLs. */
3735
3736 acl_line = get_config_line();
3737
3738 while(acl_line != NULL)
3739   {
3740   uschar name[64];
3741   tree_node *node;
3742   uschar *error;
3743
3744   p = readconf_readname(name, sizeof(name), acl_line);
3745   if (isupper(*name) && *p == '=')
3746     {
3747     read_macro_assignment(acl_line);
3748     acl_line = get_config_line();
3749     continue;
3750     }
3751
3752   if (*p != ':' || name[0] == 0)
3753     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "missing or malformed ACL name");
3754
3755   node = store_get(sizeof(tree_node) + Ustrlen(name));
3756   Ustrcpy(node->name, name);
3757   if (!tree_insertnode(&acl_anchor, node))
3758     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
3759       "there are two ACLs called \"%s\"", name);
3760
3761   node->data.ptr = acl_read(acl_callback, &error);
3762
3763   if (node->data.ptr == NULL && error != NULL)
3764     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "error in ACL: %s", error);
3765   }
3766 }
3767
3768
3769
3770 /*************************************************
3771 *     Read configuration for local_scan()        *
3772 *************************************************/
3773
3774 /* This function is called after "begin local_scan" is encountered in the
3775 configuration file. If the local_scan() function allows for configuration
3776 options, we can process them. Otherwise, we expire in a panic.
3777
3778 Arguments:  none
3779 Returns:    nothing
3780 */
3781
3782 static void
3783 local_scan_init(void)
3784 {
3785 #ifndef LOCAL_SCAN_HAS_OPTIONS
3786 log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN, "local_scan() options not supported: "
3787   "(LOCAL_SCAN_HAS_OPTIONS not defined in Local/Makefile)");
3788 #else
3789
3790 uschar *p;
3791 while ((p = get_config_line()) != NULL)
3792   {
3793   (void) readconf_handle_option(p, local_scan_options, local_scan_options_count,
3794     NULL, US"local_scan option \"%s\" unknown");
3795   }
3796 #endif
3797 }
3798
3799
3800
3801 /*************************************************
3802 *     Read rest of configuration (after main)    *
3803 *************************************************/
3804
3805 /* This function reads the rest of the runtime configuration, after the main
3806 configuration. It is called only when actually needed. Each subsequent section
3807 of the configuration starts with a line of the form
3808
3809   begin name
3810
3811 where the name is "routers", "transports", etc. A section is terminated by
3812 hitting the next "begin" line, and the next name is left in next_section.
3813 Because it may confuse people as to whether the names are singular or plural,
3814 we add "s" if it's missing. There is always enough room in next_section for
3815 this. This function is basically just a switch.
3816
3817 Arguments:
3818   skip_acl   TRUE if ACL information is not needed
3819
3820 Returns:     nothing
3821 */
3822
3823 static uschar *section_list[] = {
3824   US"acls",
3825   US"authenticators",
3826   US"local_scans",
3827   US"retrys",
3828   US"rewrites",
3829   US"routers",
3830   US"transports"};
3831
3832 void
3833 readconf_rest(BOOL skip_acl)
3834 {
3835 int had = 0;
3836
3837 while(next_section[0] != 0)
3838   {
3839   int bit;
3840   int first = 0;
3841   int last = sizeof(section_list) / sizeof(uschar *);
3842   int mid = last/2;
3843   int n = Ustrlen(next_section);
3844
3845   if (tolower(next_section[n-1]) != 's') Ustrcpy(next_section+n, "s");
3846
3847   for (;;)
3848     {
3849     int c = strcmpic(next_section, section_list[mid]);
3850     if (c == 0) break;
3851     if (c > 0) first = mid + 1; else last = mid;
3852     if (first >= last)
3853       log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
3854         "\"%.*s\" is not a known configuration section name", n, next_section);
3855     mid = (last + first)/2;
3856     }
3857
3858   bit = 1 << mid;
3859   if (((had ^= bit) & bit) == 0)
3860     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_IN,
3861       "\"%.*s\" section is repeated in the configuration file", n,
3862         next_section);
3863
3864   switch(mid)
3865     {
3866     case 0: readconf_acl(skip_acl); break;
3867     case 1: auths_init(); break;
3868     case 2: local_scan_init(); break;
3869     case 3: readconf_retries(); break;
3870     case 4: readconf_rewrites(); break;
3871     case 5: route_init(); break;
3872     case 6: transport_init(); break;
3873     }
3874   }
3875
3876 (void)fclose(config_file);
3877 }
3878
3879 /* End of readconf.c */