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