1/*	$NetBSD: smtpd.c,v 1.20 2023/12/23 20:30:45 christos Exp $	*/
2
3/*++
4/* NAME
5/*	smtpd 8
6/* SUMMARY
7/*	Postfix SMTP server
8/* SYNOPSIS
9/*	\fBsmtpd\fR [generic Postfix daemon options]
10/*
11/*	\fBsendmail -bs\fR
12/* DESCRIPTION
13/*	The SMTP server accepts network connection requests
14/*	and performs zero or more SMTP transactions per connection.
15/*	Each received message is piped through the \fBcleanup\fR(8)
16/*	daemon, and is placed into the \fBincoming\fR queue as one
17/*	single queue file.  For this mode of operation, the program
18/*	expects to be run from the \fBmaster\fR(8) process manager.
19/*
20/*	Alternatively, the SMTP server be can run in stand-alone
21/*	mode; this is traditionally obtained with "\fBsendmail
22/*	-bs\fR".  When the SMTP server runs stand-alone with non
23/*	$\fBmail_owner\fR privileges, it receives mail even while
24/*	the mail system is not running, deposits messages directly
25/*	into the \fBmaildrop\fR queue, and disables the SMTP server's
26/*	access policies. As of Postfix version 2.3, the SMTP server
27/*	refuses to receive mail from the network when it runs with
28/*	non $\fBmail_owner\fR privileges.
29/*
30/*	The SMTP server implements a variety of policies for connection
31/*	requests, and for parameters given to \fBHELO, ETRN, MAIL FROM, VRFY\fR
32/*	and \fBRCPT TO\fR commands. They are detailed below and in the
33/*	\fBmain.cf\fR configuration file.
34/* SECURITY
35/* .ad
36/* .fi
37/*	The SMTP server is moderately security-sensitive. It talks to SMTP
38/*	clients and to DNS servers on the network. The SMTP server can be
39/*	run chrooted at fixed low privilege.
40/* STANDARDS
41/*	RFC 821 (SMTP protocol)
42/*	RFC 1123 (Host requirements)
43/*	RFC 1652 (8bit-MIME transport)
44/*	RFC 1869 (SMTP service extensions)
45/*	RFC 1870 (Message size declaration)
46/*	RFC 1985 (ETRN command)
47/*	RFC 2034 (SMTP enhanced status codes)
48/*	RFC 2554 (AUTH command)
49/*	RFC 2821 (SMTP protocol)
50/*	RFC 2920 (SMTP pipelining)
51/*	RFC 3030 (CHUNKING without BINARYMIME)
52/*	RFC 3207 (STARTTLS command)
53/*	RFC 3461 (SMTP DSN extension)
54/*	RFC 3463 (Enhanced status codes)
55/*	RFC 3848 (ESMTP transmission types)
56/*	RFC 4409 (Message submission)
57/*	RFC 4954 (AUTH command)
58/*	RFC 5321 (SMTP protocol)
59/*	RFC 6531 (Internationalized SMTP)
60/*	RFC 6533 (Internationalized Delivery Status Notifications)
61/*	RFC 7505 ("Null MX" No Service Resource Record)
62/* DIAGNOSTICS
63/*	Problems and transactions are logged to \fBsyslogd\fR(8)
64/*	or \fBpostlogd\fR(8).
65/*
66/*	Depending on the setting of the \fBnotify_classes\fR parameter,
67/*	the postmaster is notified of bounces, protocol problems,
68/*	policy violations, and of other trouble.
69/* CONFIGURATION PARAMETERS
70/* .ad
71/* .fi
72/*	Changes to \fBmain.cf\fR are picked up automatically, as \fBsmtpd\fR(8)
73/*	processes run for only a limited amount of time. Use the command
74/*	"\fBpostfix reload\fR" to speed up a change.
75/*
76/*	The text below provides only a parameter summary. See
77/*	\fBpostconf\fR(5) for more details including examples.
78/* COMPATIBILITY CONTROLS
79/* .ad
80/* .fi
81/*	The following parameters work around implementation errors in other
82/*	software, and/or allow you to override standards in order to prevent
83/*	undesirable use.
84/* .ad
85/* .fi
86/* .IP "\fBbroken_sasl_auth_clients (no)\fR"
87/*	Enable interoperability with remote SMTP clients that implement an obsolete
88/*	version of the AUTH command (RFC 4954).
89/* .IP "\fBdisable_vrfy_command (no)\fR"
90/*	Disable the SMTP VRFY command.
91/* .IP "\fBsmtpd_noop_commands (empty)\fR"
92/*	List of commands that the Postfix SMTP server replies to with "250
93/*	Ok", without doing any syntax checks and without changing state.
94/* .IP "\fBstrict_rfc821_envelopes (no)\fR"
95/*	Require that addresses received in SMTP MAIL FROM and RCPT TO
96/*	commands are enclosed with <>, and that those addresses do
97/*	not contain RFC 822 style comments or phrases.
98/* .PP
99/*	Available in Postfix version 2.1 and later:
100/* .IP "\fBsmtpd_reject_unlisted_sender (no)\fR"
101/*	Request that the Postfix SMTP server rejects mail from unknown
102/*	sender addresses, even when no explicit reject_unlisted_sender
103/*	access restriction is specified.
104/* .IP "\fBsmtpd_sasl_exceptions_networks (empty)\fR"
105/*	What remote SMTP clients the Postfix SMTP server will not offer
106/*	AUTH support to.
107/* .PP
108/*	Available in Postfix version 2.2 and later:
109/* .IP "\fBsmtpd_discard_ehlo_keyword_address_maps (empty)\fR"
110/*	Lookup tables, indexed by the remote SMTP client address, with
111/*	case insensitive lists of EHLO keywords (pipelining, starttls, auth,
112/*	etc.) that the Postfix SMTP server will not send in the EHLO response
113/*	to a
114/*	remote SMTP client.
115/* .IP "\fBsmtpd_discard_ehlo_keywords (empty)\fR"
116/*	A case insensitive list of EHLO keywords (pipelining, starttls,
117/*	auth, etc.) that the Postfix SMTP server will not send in the EHLO
118/*	response
119/*	to a remote SMTP client.
120/* .IP "\fBsmtpd_delay_open_until_valid_rcpt (yes)\fR"
121/*	Postpone the start of an SMTP mail transaction until a valid
122/*	RCPT TO command is received.
123/* .PP
124/*	Available in Postfix version 2.3 and later:
125/* .IP "\fBsmtpd_tls_always_issue_session_ids (yes)\fR"
126/*	Force the Postfix SMTP server to issue a TLS session id, even
127/*	when TLS session caching is turned off (smtpd_tls_session_cache_database
128/*	is empty).
129/* .PP
130/*	Available in Postfix version 2.6 and later:
131/* .IP "\fBtcp_windowsize (0)\fR"
132/*	An optional workaround for routers that break TCP window scaling.
133/* .PP
134/*	Available in Postfix version 2.7 and later:
135/* .IP "\fBsmtpd_command_filter (empty)\fR"
136/*	A mechanism to transform commands from remote SMTP clients.
137/* .PP
138/*	Available in Postfix version 2.9 - 3.6:
139/* .IP "\fBsmtpd_per_record_deadline (normal: no, overload: yes)\fR"
140/*	Change the behavior of the smtpd_timeout and smtpd_starttls_timeout
141/*	time limits, from a
142/*	time limit per read or write system call, to a time limit to send
143/*	or receive a complete record (an SMTP command line, SMTP response
144/*	line, SMTP message content line, or TLS protocol message).
145/* .PP
146/*	Available in Postfix version 3.0 and later:
147/* .IP "\fBsmtpd_dns_reply_filter (empty)\fR"
148/*	Optional filter for Postfix SMTP server DNS lookup results.
149/* .PP
150/*	Available in Postfix 3.5 and later:
151/* .IP "\fBinfo_log_address_format (external)\fR"
152/*	The email address form that will be used in non-debug logging
153/*	(info, warning, etc.).
154/* .PP
155/*	Available in Postfix version 3.6 and later:
156/* .IP "\fBsmtpd_relay_before_recipient_restrictions (see 'postconf -d' output)\fR"
157/*	Evaluate smtpd_relay_restrictions before smtpd_recipient_restrictions.
158/* .IP "\fBknown_tcp_ports (lmtp=24, smtp=25, smtps=submissions=465, submission=587)\fR"
159/*	Optional setting that avoids lookups in the \fBservices\fR(5) database.
160/* .PP
161/*	Available in Postfix version 3.7 and later:
162/* .IP "\fBsmtpd_per_request_deadline (normal: no, overload: yes)\fR"
163/*	Change the behavior of the smtpd_timeout and smtpd_starttls_timeout
164/*	time limits, from a time limit per plaintext or TLS read or write
165/*	call, to a combined time limit for receiving a complete SMTP request
166/*	and for sending a complete SMTP response.
167/* .IP "\fBsmtpd_min_data_rate (500)\fR"
168/*	The minimum plaintext data transfer rate in bytes/second for
169/*	DATA and BDAT requests, when deadlines are enabled with
170/*	smtpd_per_request_deadline.
171/* ADDRESS REWRITING CONTROLS
172/* .ad
173/* .fi
174/*	See the ADDRESS_REWRITING_README document for a detailed
175/*	discussion of Postfix address rewriting.
176/* .IP "\fBreceive_override_options (empty)\fR"
177/*	Enable or disable recipient validation, built-in content
178/*	filtering, or address mapping.
179/* .PP
180/*	Available in Postfix version 2.2 and later:
181/* .IP "\fBlocal_header_rewrite_clients (permit_inet_interfaces)\fR"
182/*	Rewrite or add message headers in mail from these clients,
183/*	updating incomplete addresses with the domain name in $myorigin or
184/*	$mydomain, and adding missing headers.
185/* BEFORE-SMTPD PROXY AGENT
186/* .ad
187/* .fi
188/*	Available in Postfix version 2.10 and later:
189/* .IP "\fBsmtpd_upstream_proxy_protocol (empty)\fR"
190/*	The name of the proxy protocol used by an optional before-smtpd
191/*	proxy agent.
192/* .IP "\fBsmtpd_upstream_proxy_timeout (5s)\fR"
193/*	The time limit for the proxy protocol specified with the
194/*	smtpd_upstream_proxy_protocol parameter.
195/* AFTER QUEUE EXTERNAL CONTENT INSPECTION CONTROLS
196/* .ad
197/* .fi
198/*	As of version 1.0, Postfix can be configured to send new mail to
199/*	an external content filter AFTER the mail is queued. This content
200/*	filter is expected to inject mail back into a (Postfix or other)
201/*	MTA for further delivery. See the FILTER_README document for details.
202/* .IP "\fBcontent_filter (empty)\fR"
203/*	After the message is queued, send the entire message to the
204/*	specified \fItransport:destination\fR.
205/* BEFORE QUEUE EXTERNAL CONTENT INSPECTION CONTROLS
206/* .ad
207/* .fi
208/*	As of version 2.1, the Postfix SMTP server can be configured
209/*	to send incoming mail to a real-time SMTP-based content filter
210/*	BEFORE mail is queued.  This content filter is expected to inject
211/*	mail back into Postfix.  See the SMTPD_PROXY_README document for
212/*	details on how to configure and operate this feature.
213/* .IP "\fBsmtpd_proxy_filter (empty)\fR"
214/*	The hostname and TCP port of the mail filtering proxy server.
215/* .IP "\fBsmtpd_proxy_ehlo ($myhostname)\fR"
216/*	How the Postfix SMTP server announces itself to the proxy filter.
217/* .IP "\fBsmtpd_proxy_options (empty)\fR"
218/*	List of options that control how the Postfix SMTP server
219/*	communicates with a before-queue content filter.
220/* .IP "\fBsmtpd_proxy_timeout (100s)\fR"
221/*	The time limit for connecting to a proxy filter and for sending or
222/*	receiving information.
223/* BEFORE QUEUE MILTER CONTROLS
224/* .ad
225/* .fi
226/*	As of version 2.3, Postfix supports the Sendmail version 8
227/*	Milter (mail filter) protocol. These content filters run
228/*	outside Postfix. They can inspect the SMTP command stream
229/*	and the message content, and can request modifications before
230/*	mail is queued. For details see the MILTER_README document.
231/* .IP "\fBsmtpd_milters (empty)\fR"
232/*	A list of Milter (mail filter) applications for new mail that
233/*	arrives via the Postfix \fBsmtpd\fR(8) server.
234/* .IP "\fBmilter_protocol (6)\fR"
235/*	The mail filter protocol version and optional protocol extensions
236/*	for communication with a Milter application; prior to Postfix 2.6
237/*	the default protocol is 2.
238/* .IP "\fBmilter_default_action (tempfail)\fR"
239/*	The default action when a Milter (mail filter) response is
240/*	unavailable (for example, bad Postfix configuration or Milter
241/*	failure).
242/* .IP "\fBmilter_macro_daemon_name ($myhostname)\fR"
243/*	The {daemon_name} macro value for Milter (mail filter) applications.
244/* .IP "\fBmilter_macro_v ($mail_name $mail_version)\fR"
245/*	The {v} macro value for Milter (mail filter) applications.
246/* .IP "\fBmilter_connect_timeout (30s)\fR"
247/*	The time limit for connecting to a Milter (mail filter)
248/*	application, and for negotiating protocol options.
249/* .IP "\fBmilter_command_timeout (30s)\fR"
250/*	The time limit for sending an SMTP command to a Milter (mail
251/*	filter) application, and for receiving the response.
252/* .IP "\fBmilter_content_timeout (300s)\fR"
253/*	The time limit for sending message content to a Milter (mail
254/*	filter) application, and for receiving the response.
255/* .IP "\fBmilter_connect_macros (see 'postconf -d' output)\fR"
256/*	The macros that are sent to Milter (mail filter) applications
257/*	after completion of an SMTP connection.
258/* .IP "\fBmilter_helo_macros (see 'postconf -d' output)\fR"
259/*	The macros that are sent to Milter (mail filter) applications
260/*	after the SMTP HELO or EHLO command.
261/* .IP "\fBmilter_mail_macros (see 'postconf -d' output)\fR"
262/*	The macros that are sent to Milter (mail filter) applications
263/*	after the SMTP MAIL FROM command.
264/* .IP "\fBmilter_rcpt_macros (see 'postconf -d' output)\fR"
265/*	The macros that are sent to Milter (mail filter) applications
266/*	after the SMTP RCPT TO command.
267/* .IP "\fBmilter_data_macros (see 'postconf -d' output)\fR"
268/*	The macros that are sent to version 4 or higher Milter (mail
269/*	filter) applications after the SMTP DATA command.
270/* .IP "\fBmilter_unknown_command_macros (see 'postconf -d' output)\fR"
271/*	The macros that are sent to version 3 or higher Milter (mail
272/*	filter) applications after an unknown SMTP command.
273/* .IP "\fBmilter_end_of_header_macros (see 'postconf -d' output)\fR"
274/*	The macros that are sent to Milter (mail filter) applications
275/*	after the end of the message header.
276/* .IP "\fBmilter_end_of_data_macros (see 'postconf -d' output)\fR"
277/*	The macros that are sent to Milter (mail filter) applications
278/*	after the message end-of-data.
279/* .PP
280/*	Available in Postfix version 3.1 and later:
281/* .IP "\fBmilter_macro_defaults (empty)\fR"
282/*	Optional list of \fIname=value\fR pairs that specify default
283/*	values for arbitrary macros that Postfix may send to Milter
284/*	applications.
285/* .PP
286/*	Available in Postfix version 3.2 and later:
287/* .IP "\fBsmtpd_milter_maps (empty)\fR"
288/*	Lookup tables with Milter settings per remote SMTP client IP
289/*	address.
290/* GENERAL CONTENT INSPECTION CONTROLS
291/* .ad
292/* .fi
293/*	The following parameters are applicable for both built-in
294/*	and external content filters.
295/* .PP
296/*	Available in Postfix version 2.1 and later:
297/* .IP "\fBreceive_override_options (empty)\fR"
298/*	Enable or disable recipient validation, built-in content
299/*	filtering, or address mapping.
300/* EXTERNAL CONTENT INSPECTION CONTROLS
301/* .ad
302/* .fi
303/*	The following parameters are applicable for both before-queue
304/*	and after-queue content filtering.
305/* .PP
306/*	Available in Postfix version 2.1 and later:
307/* .IP "\fBsmtpd_authorized_xforward_hosts (empty)\fR"
308/*	What remote SMTP clients are allowed to use the XFORWARD feature.
309/* SASL AUTHENTICATION CONTROLS
310/* .ad
311/* .fi
312/*	Postfix SASL support (RFC 4954) can be used to authenticate remote
313/*	SMTP clients to the Postfix SMTP server, and to authenticate the
314/*	Postfix SMTP client to a remote SMTP server.
315/*	See the SASL_README document for details.
316/* .IP "\fBbroken_sasl_auth_clients (no)\fR"
317/*	Enable interoperability with remote SMTP clients that implement an obsolete
318/*	version of the AUTH command (RFC 4954).
319/* .IP "\fBsmtpd_sasl_auth_enable (no)\fR"
320/*	Enable SASL authentication in the Postfix SMTP server.
321/* .IP "\fBsmtpd_sasl_local_domain (empty)\fR"
322/*	The name of the Postfix SMTP server's local SASL authentication
323/*	realm.
324/* .IP "\fBsmtpd_sasl_security_options (noanonymous)\fR"
325/*	Postfix SMTP server SASL security options; as of Postfix 2.3
326/*	the list of available
327/*	features depends on the SASL server implementation that is selected
328/*	with \fBsmtpd_sasl_type\fR.
329/* .IP "\fBsmtpd_sender_login_maps (empty)\fR"
330/*	Optional lookup table with the SASL login names that own the sender
331/*	(MAIL FROM) addresses.
332/* .PP
333/*	Available in Postfix version 2.1 and later:
334/* .IP "\fBsmtpd_sasl_exceptions_networks (empty)\fR"
335/*	What remote SMTP clients the Postfix SMTP server will not offer
336/*	AUTH support to.
337/* .PP
338/*	Available in Postfix version 2.1 and 2.2:
339/* .IP "\fBsmtpd_sasl_application_name (smtpd)\fR"
340/*	The application name that the Postfix SMTP server uses for SASL
341/*	server initialization.
342/* .PP
343/*	Available in Postfix version 2.3 and later:
344/* .IP "\fBsmtpd_sasl_authenticated_header (no)\fR"
345/*	Report the SASL authenticated user name in the \fBsmtpd\fR(8) Received
346/*	message header.
347/* .IP "\fBsmtpd_sasl_path (smtpd)\fR"
348/*	Implementation-specific information that the Postfix SMTP server
349/*	passes through to
350/*	the SASL plug-in implementation that is selected with
351/*	\fBsmtpd_sasl_type\fR.
352/* .IP "\fBsmtpd_sasl_type (cyrus)\fR"
353/*	The SASL plug-in type that the Postfix SMTP server should use
354/*	for authentication.
355/* .PP
356/*	Available in Postfix version 2.5 and later:
357/* .IP "\fBcyrus_sasl_config_path (empty)\fR"
358/*	Search path for Cyrus SASL application configuration files,
359/*	currently used only to locate the $smtpd_sasl_path.conf file.
360/* .PP
361/*	Available in Postfix version 2.11 and later:
362/* .IP "\fBsmtpd_sasl_service (smtp)\fR"
363/*	The service name that is passed to the SASL plug-in that is
364/*	selected with \fBsmtpd_sasl_type\fR and \fBsmtpd_sasl_path\fR.
365/* .PP
366/*	Available in Postfix version 3.4 and later:
367/* .IP "\fBsmtpd_sasl_response_limit (12288)\fR"
368/*	The maximum length of a SASL client's response to a server challenge.
369/* .PP
370/*	Available in Postfix 3.6 and later:
371/* .IP "\fBsmtpd_sasl_mechanism_filter (!external, static:rest)\fR"
372/*	If non-empty, a filter for the SASL mechanism names that the
373/*	Postfix SMTP server will announce in the EHLO response.
374/* STARTTLS SUPPORT CONTROLS
375/* .ad
376/* .fi
377/*	Detailed information about STARTTLS configuration may be
378/*	found in the TLS_README document.
379/* .IP "\fBsmtpd_tls_security_level (empty)\fR"
380/*	The SMTP TLS security level for the Postfix SMTP server; when
381/*	a non-empty value is specified, this overrides the obsolete parameters
382/*	smtpd_use_tls and smtpd_enforce_tls.
383/* .IP "\fBsmtpd_sasl_tls_security_options ($smtpd_sasl_security_options)\fR"
384/*	The SASL authentication security options that the Postfix SMTP
385/*	server uses for TLS encrypted SMTP sessions.
386/* .IP "\fBsmtpd_starttls_timeout (see 'postconf -d' output)\fR"
387/*	The time limit for Postfix SMTP server write and read operations
388/*	during TLS startup and shutdown handshake procedures.
389/* .IP "\fBsmtpd_tls_CAfile (empty)\fR"
390/*	A file containing (PEM format) CA certificates of root CAs trusted
391/*	to sign either remote SMTP client certificates or intermediate CA
392/*	certificates.
393/* .IP "\fBsmtpd_tls_CApath (empty)\fR"
394/*	A directory containing (PEM format) CA certificates of root CAs
395/*	trusted to sign either remote SMTP client certificates or intermediate CA
396/*	certificates.
397/* .IP "\fBsmtpd_tls_always_issue_session_ids (yes)\fR"
398/*	Force the Postfix SMTP server to issue a TLS session id, even
399/*	when TLS session caching is turned off (smtpd_tls_session_cache_database
400/*	is empty).
401/* .IP "\fBsmtpd_tls_ask_ccert (no)\fR"
402/*	Ask a remote SMTP client for a client certificate.
403/* .IP "\fBsmtpd_tls_auth_only (no)\fR"
404/*	When TLS encryption is optional in the Postfix SMTP server, do
405/*	not announce or accept SASL authentication over unencrypted
406/*	connections.
407/* .IP "\fBsmtpd_tls_ccert_verifydepth (9)\fR"
408/*	The verification depth for remote SMTP client certificates.
409/* .IP "\fBsmtpd_tls_cert_file (empty)\fR"
410/*	File with the Postfix SMTP server RSA certificate in PEM format.
411/* .IP "\fBsmtpd_tls_exclude_ciphers (empty)\fR"
412/*	List of ciphers or cipher types to exclude from the SMTP server
413/*	cipher list at all TLS security levels.
414/* .IP "\fBsmtpd_tls_dcert_file (empty)\fR"
415/*	File with the Postfix SMTP server DSA certificate in PEM format.
416/* .IP "\fBsmtpd_tls_dh1024_param_file (empty)\fR"
417/*	File with DH parameters that the Postfix SMTP server should
418/*	use with non-export EDH ciphers.
419/* .IP "\fBsmtpd_tls_dh512_param_file (empty)\fR"
420/*	File with DH parameters that the Postfix SMTP server should
421/*	use with export-grade EDH ciphers.
422/* .IP "\fBsmtpd_tls_dkey_file ($smtpd_tls_dcert_file)\fR"
423/*	File with the Postfix SMTP server DSA private key in PEM format.
424/* .IP "\fBsmtpd_tls_key_file ($smtpd_tls_cert_file)\fR"
425/*	File with the Postfix SMTP server RSA private key in PEM format.
426/* .IP "\fBsmtpd_tls_loglevel (0)\fR"
427/*	Enable additional Postfix SMTP server logging of TLS activity.
428/* .IP "\fBsmtpd_tls_mandatory_ciphers (medium)\fR"
429/*	The minimum TLS cipher grade that the Postfix SMTP server will
430/*	use with mandatory TLS encryption.
431/* .IP "\fBsmtpd_tls_mandatory_exclude_ciphers (empty)\fR"
432/*	Additional list of ciphers or cipher types to exclude from the
433/*	Postfix SMTP server cipher list at mandatory TLS security levels.
434/* .IP "\fBsmtpd_tls_mandatory_protocols (see 'postconf -d' output)\fR"
435/*	TLS protocols accepted by the Postfix SMTP server with mandatory TLS
436/*	encryption.
437/* .IP "\fBsmtpd_tls_received_header (no)\fR"
438/*	Request that the Postfix SMTP server produces Received:  message
439/*	headers that include information about the protocol and cipher used,
440/*	as well as the remote SMTP client CommonName and client certificate issuer
441/*	CommonName.
442/* .IP "\fBsmtpd_tls_req_ccert (no)\fR"
443/*	With mandatory TLS encryption, require a trusted remote SMTP client
444/*	certificate in order to allow TLS connections to proceed.
445/* .IP "\fBsmtpd_tls_wrappermode (no)\fR"
446/*	Run the Postfix SMTP server in TLS "wrapper" mode,
447/*	instead of using the STARTTLS command.
448/* .IP "\fBtls_daemon_random_bytes (32)\fR"
449/*	The number of pseudo-random bytes that an \fBsmtp\fR(8) or \fBsmtpd\fR(8)
450/*	process requests from the \fBtlsmgr\fR(8) server in order to seed its
451/*	internal pseudo random number generator (PRNG).
452/* .IP "\fBtls_high_cipherlist (see 'postconf -d' output)\fR"
453/*	The OpenSSL cipherlist for "high" grade ciphers.
454/* .IP "\fBtls_medium_cipherlist (see 'postconf -d' output)\fR"
455/*	The OpenSSL cipherlist for "medium" or higher grade ciphers.
456/* .IP "\fBtls_null_cipherlist (eNULL:!aNULL)\fR"
457/*	The OpenSSL cipherlist for "NULL" grade ciphers that provide
458/*	authentication without encryption.
459/* .PP
460/*	Available in Postfix version 2.3..3.7:
461/* .IP "\fBtls_low_cipherlist (see 'postconf -d' output)\fR"
462/*	The OpenSSL cipherlist for "low" or higher grade ciphers.
463/* .IP "\fBtls_export_cipherlist (see 'postconf -d' output)\fR"
464/*	The OpenSSL cipherlist for "export" or higher grade ciphers.
465/* .PP
466/*	Available in Postfix version 2.5 and later:
467/* .IP "\fBsmtpd_tls_fingerprint_digest (see 'postconf -d' output)\fR"
468/*	The message digest algorithm to construct remote SMTP client-certificate
469/*	fingerprints or public key fingerprints (Postfix 2.9 and later) for
470/*	\fBcheck_ccert_access\fR and \fBpermit_tls_clientcerts\fR.
471/* .PP
472/*	Available in Postfix version 2.6 and later:
473/* .IP "\fBsmtpd_tls_protocols (see postconf -d output)\fR"
474/*	TLS protocols accepted by the Postfix SMTP server with opportunistic
475/*	TLS encryption.
476/* .IP "\fBsmtpd_tls_ciphers (medium)\fR"
477/*	The minimum TLS cipher grade that the Postfix SMTP server
478/*	will use with opportunistic TLS encryption.
479/* .IP "\fBsmtpd_tls_eccert_file (empty)\fR"
480/*	File with the Postfix SMTP server ECDSA certificate in PEM format.
481/* .IP "\fBsmtpd_tls_eckey_file ($smtpd_tls_eccert_file)\fR"
482/*	File with the Postfix SMTP server ECDSA private key in PEM format.
483/* .IP "\fBsmtpd_tls_eecdh_grade (see 'postconf -d' output)\fR"
484/*	The Postfix SMTP server security grade for ephemeral elliptic-curve
485/*	Diffie-Hellman (EECDH) key exchange.
486/* .IP "\fBtls_eecdh_strong_curve (prime256v1)\fR"
487/*	The elliptic curve used by the Postfix SMTP server for sensibly
488/*	strong
489/*	ephemeral ECDH key exchange.
490/* .IP "\fBtls_eecdh_ultra_curve (secp384r1)\fR"
491/*	The elliptic curve used by the Postfix SMTP server for maximally
492/*	strong
493/*	ephemeral ECDH key exchange.
494/* .PP
495/*	Available in Postfix version 2.8 and later:
496/* .IP "\fBtls_preempt_cipherlist (no)\fR"
497/*	With SSLv3 and later, use the Postfix SMTP server's cipher
498/*	preference order instead of the remote client's cipher preference
499/*	order.
500/* .IP "\fBtls_disable_workarounds (see 'postconf -d' output)\fR"
501/*	List or bit-mask of OpenSSL bug work-arounds to disable.
502/* .PP
503/*	Available in Postfix version 2.11 and later:
504/* .IP "\fBtlsmgr_service_name (tlsmgr)\fR"
505/*	The name of the \fBtlsmgr\fR(8) service entry in master.cf.
506/* .PP
507/*	Available in Postfix version 3.0 and later:
508/* .IP "\fBtls_session_ticket_cipher (Postfix >= 3.0: aes-256-cbc, Postfix < 3.0: aes-128-cbc)\fR"
509/*	Algorithm used to encrypt RFC5077 TLS session tickets.
510/* .PP
511/*	Available in Postfix version 3.2 and later:
512/* .IP "\fBtls_eecdh_auto_curves (see 'postconf -d' output)\fR"
513/*	The prioritized list of elliptic curves supported by the Postfix
514/*	SMTP client and server.
515/* .PP
516/*	Available in Postfix version 3.4 and later:
517/* .IP "\fBsmtpd_tls_chain_files (empty)\fR"
518/*	List of one or more PEM files, each holding one or more private keys
519/*	directly followed by a corresponding certificate chain.
520/* .IP "\fBtls_server_sni_maps (empty)\fR"
521/*	Optional lookup tables that map names received from remote SMTP
522/*	clients via the TLS Server Name Indication (SNI) extension to the
523/*	appropriate keys and certificate chains.
524/* .PP
525/*	Available in Postfix 3.5, 3.4.6, 3.3.5, 3.2.10, 3.1.13 and later:
526/* .IP "\fBtls_fast_shutdown_enable (yes)\fR"
527/*	A workaround for implementations that hang Postfix while shutting
528/*	down a TLS session, until Postfix times out.
529/* .PP
530/*	Available in Postfix version 3.8 and later:
531/* .IP "\fBtls_ffdhe_auto_groups (see 'postconf -d' output)\fR"
532/*	The prioritized list of finite-field Diffie-Hellman ephemeral
533/*	(FFDHE) key exchange groups supported by the Postfix SMTP client and
534/*	server.
535/* .PP
536/*	Available in Postfix 3.9, 3.8.1, 3.7.6, 3.6.10, 3.5.20 and later:
537/* .IP "\fBtls_config_file (default)\fR"
538/*	Optional configuration file with baseline OpenSSL settings.
539/* .IP "\fBtls_config_name (empty)\fR"
540/*	The application name passed by Postfix to OpenSSL library
541/*	initialization functions.
542/* OBSOLETE STARTTLS CONTROLS
543/* .ad
544/* .fi
545/*	The following configuration parameters exist for compatibility
546/*	with Postfix versions before 2.3. Support for these will
547/*	be removed in a future release.
548/* .IP "\fBsmtpd_use_tls (no)\fR"
549/*	Opportunistic TLS: announce STARTTLS support to remote SMTP clients,
550/*	but do not require that clients use TLS encryption.
551/* .IP "\fBsmtpd_enforce_tls (no)\fR"
552/*	Mandatory TLS: announce STARTTLS support to remote SMTP clients,
553/*	and require that clients use TLS encryption.
554/* .IP "\fBsmtpd_tls_cipherlist (empty)\fR"
555/*	Obsolete Postfix < 2.3 control for the Postfix SMTP server TLS
556/*	cipher list.
557/* SMTPUTF8 CONTROLS
558/* .ad
559/* .fi
560/*	Preliminary SMTPUTF8 support is introduced with Postfix 3.0.
561/* .IP "\fBsmtputf8_enable (yes)\fR"
562/*	Enable preliminary SMTPUTF8 support for the protocols described
563/*	in RFC 6531, RFC 6532, and RFC 6533.
564/* .IP "\fBstrict_smtputf8 (no)\fR"
565/*	Enable stricter enforcement of the SMTPUTF8 protocol.
566/* .IP "\fBsmtputf8_autodetect_classes (sendmail, verify)\fR"
567/*	Detect that a message requires SMTPUTF8 support for the specified
568/*	mail origin classes.
569/* .PP
570/*	Available in Postfix version 3.2 and later:
571/* .IP "\fBenable_idna2003_compatibility (no)\fR"
572/*	Enable 'transitional' compatibility between IDNA2003 and IDNA2008,
573/*	when converting UTF-8 domain names to/from the ASCII form that is
574/*	used for DNS lookups.
575/* VERP SUPPORT CONTROLS
576/* .ad
577/* .fi
578/*	With VERP style delivery, each recipient of a message receives a
579/*	customized copy of the message with his/her own recipient address
580/*	encoded in the envelope sender address.  The VERP_README file
581/*	describes configuration and operation details of Postfix support
582/*	for variable envelope return path addresses.  VERP style delivery
583/*	is requested with the SMTP XVERP command or with the "sendmail
584/*	-V" command-line option and is available in Postfix version 1.1
585/*	and later.
586/* .IP "\fBdefault_verp_delimiters (+=)\fR"
587/*	The two default VERP delimiter characters.
588/* .IP "\fBverp_delimiter_filter (-=+)\fR"
589/*	The characters Postfix accepts as VERP delimiter characters on the
590/*	Postfix \fBsendmail\fR(1) command line and in SMTP commands.
591/* .PP
592/*	Available in Postfix version 1.1 and 2.0:
593/* .IP "\fBauthorized_verp_clients ($mynetworks)\fR"
594/*	What remote SMTP clients are allowed to specify the XVERP command.
595/* .PP
596/*	Available in Postfix version 2.1 and later:
597/* .IP "\fBsmtpd_authorized_verp_clients ($authorized_verp_clients)\fR"
598/*	What remote SMTP clients are allowed to specify the XVERP command.
599/* TROUBLE SHOOTING CONTROLS
600/* .ad
601/* .fi
602/*	The DEBUG_README document describes how to debug parts of the
603/*	Postfix mail system. The methods vary from making the software log
604/*	a lot of detail, to running some daemon processes under control of
605/*	a call tracer or debugger.
606/* .IP "\fBdebug_peer_level (2)\fR"
607/*	The increment in verbose logging level when a nexthop destination,
608/*	remote client or server name or network address matches a pattern
609/*	given with the debug_peer_list parameter.
610/* .IP "\fBdebug_peer_list (empty)\fR"
611/*	Optional list of nexthop destination, remote client or server
612/*	name or network address patterns that, if matched, cause the verbose
613/*	logging level to increase by the amount specified in $debug_peer_level.
614/* .IP "\fBerror_notice_recipient (postmaster)\fR"
615/*	The recipient of postmaster notifications about mail delivery
616/*	problems that are caused by policy, resource, software or protocol
617/*	errors.
618/* .IP "\fBinternal_mail_filter_classes (empty)\fR"
619/*	What categories of Postfix-generated mail are subject to
620/*	before-queue content inspection by non_smtpd_milters, header_checks
621/*	and body_checks.
622/* .IP "\fBnotify_classes (resource, software)\fR"
623/*	The list of error classes that are reported to the postmaster.
624/* .IP "\fBsmtpd_reject_footer (empty)\fR"
625/*	Optional information that is appended after each Postfix SMTP
626/*	server
627/*	4XX or 5XX response.
628/* .IP "\fBsoft_bounce (no)\fR"
629/*	Safety net to keep mail queued that would otherwise be returned to
630/*	the sender.
631/* .PP
632/*	Available in Postfix version 2.1 and later:
633/* .IP "\fBsmtpd_authorized_xclient_hosts (empty)\fR"
634/*	What remote SMTP clients are allowed to use the XCLIENT feature.
635/* .PP
636/*	Available in Postfix version 2.10 and later:
637/* .IP "\fBsmtpd_log_access_permit_actions (empty)\fR"
638/*	Enable logging of the named "permit" actions in SMTP server
639/*	access lists (by default, the SMTP server logs "reject" actions but
640/*	not "permit" actions).
641/* KNOWN VERSUS UNKNOWN RECIPIENT CONTROLS
642/* .ad
643/* .fi
644/*	As of Postfix version 2.0, the SMTP server rejects mail for
645/*	unknown recipients. This prevents the mail queue from clogging up
646/*	with undeliverable MAILER-DAEMON messages. Additional information
647/*	on this topic is in the LOCAL_RECIPIENT_README and ADDRESS_CLASS_README
648/*	documents.
649/* .IP "\fBshow_user_unknown_table_name (yes)\fR"
650/*	Display the name of the recipient table in the "User unknown"
651/*	responses.
652/* .IP "\fBcanonical_maps (empty)\fR"
653/*	Optional address mapping lookup tables for message headers and
654/*	envelopes.
655/* .IP "\fBrecipient_canonical_maps (empty)\fR"
656/*	Optional address mapping lookup tables for envelope and header
657/*	recipient addresses.
658/* .IP "\fBsender_canonical_maps (empty)\fR"
659/*	Optional address mapping lookup tables for envelope and header
660/*	sender addresses.
661/* .PP
662/*	Parameters concerning known/unknown local recipients:
663/* .IP "\fBmydestination ($myhostname, localhost.$mydomain, localhost)\fR"
664/*	The list of domains that are delivered via the $local_transport
665/*	mail delivery transport.
666/* .IP "\fBinet_interfaces (all)\fR"
667/*	The local network interface addresses that this mail system receives
668/*	mail on.
669/* .IP "\fBproxy_interfaces (empty)\fR"
670/*	The remote network interface addresses that this mail system receives mail
671/*	on by way of a proxy or network address translation unit.
672/* .IP "\fBinet_protocols (see 'postconf -d output')\fR"
673/*	The Internet protocols Postfix will attempt to use when making
674/*	or accepting connections.
675/* .IP "\fBlocal_recipient_maps (proxy:unix:passwd.byname $alias_maps)\fR"
676/*	Lookup tables with all names or addresses of local recipients:
677/*	a recipient address is local when its domain matches $mydestination,
678/*	$inet_interfaces or $proxy_interfaces.
679/* .IP "\fBunknown_local_recipient_reject_code (550)\fR"
680/*	The numerical Postfix SMTP server response code when a recipient
681/*	address is local, and $local_recipient_maps specifies a list of
682/*	lookup tables that does not match the recipient.
683/* .PP
684/*	Parameters concerning known/unknown recipients of relay destinations:
685/* .IP "\fBrelay_domains (Postfix >= 3.0: empty, Postfix < 3.0: $mydestination)\fR"
686/*	What destination domains (and subdomains thereof) this system
687/*	will relay mail to.
688/* .IP "\fBrelay_recipient_maps (empty)\fR"
689/*	Optional lookup tables with all valid addresses in the domains
690/*	that match $relay_domains.
691/* .IP "\fBunknown_relay_recipient_reject_code (550)\fR"
692/*	The numerical Postfix SMTP server reply code when a recipient
693/*	address matches $relay_domains, and relay_recipient_maps specifies
694/*	a list of lookup tables that does not match the recipient address.
695/* .PP
696/*	Parameters concerning known/unknown recipients in virtual alias
697/*	domains:
698/* .IP "\fBvirtual_alias_domains ($virtual_alias_maps)\fR"
699/*	Postfix is the final destination for the specified list of virtual
700/*	alias domains, that is, domains for which all addresses are aliased
701/*	to addresses in other local or remote domains.
702/* .IP "\fBvirtual_alias_maps ($virtual_maps)\fR"
703/*	Optional lookup tables that alias specific mail addresses or domains
704/*	to other local or remote addresses.
705/* .IP "\fBunknown_virtual_alias_reject_code (550)\fR"
706/*	The Postfix SMTP server reply code when a recipient address matches
707/*	$virtual_alias_domains, and $virtual_alias_maps specifies a list
708/*	of lookup tables that does not match the recipient address.
709/* .PP
710/*	Parameters concerning known/unknown recipients in virtual mailbox
711/*	domains:
712/* .IP "\fBvirtual_mailbox_domains ($virtual_mailbox_maps)\fR"
713/*	Postfix is the final destination for the specified list of domains;
714/*	mail is delivered via the $virtual_transport mail delivery transport.
715/* .IP "\fBvirtual_mailbox_maps (empty)\fR"
716/*	Optional lookup tables with all valid addresses in the domains that
717/*	match $virtual_mailbox_domains.
718/* .IP "\fBunknown_virtual_mailbox_reject_code (550)\fR"
719/*	The Postfix SMTP server reply code when a recipient address matches
720/*	$virtual_mailbox_domains, and $virtual_mailbox_maps specifies a list
721/*	of lookup tables that does not match the recipient address.
722/* RESOURCE AND RATE CONTROLS
723/* .ad
724/* .fi
725/*	The following parameters limit resource usage by the SMTP
726/*	server and/or control client request rates.
727/* .IP "\fBline_length_limit (2048)\fR"
728/*	Upon input, long lines are chopped up into pieces of at most
729/*	this length; upon delivery, long lines are reconstructed.
730/* .IP "\fBqueue_minfree (0)\fR"
731/*	The minimal amount of free space in bytes in the queue file system
732/*	that is needed to receive mail.
733/* .IP "\fBmessage_size_limit (10240000)\fR"
734/*	The maximal size in bytes of a message, including envelope information.
735/* .IP "\fBsmtpd_recipient_limit (1000)\fR"
736/*	The maximal number of recipients that the Postfix SMTP server
737/*	accepts per message delivery request.
738/* .IP "\fBsmtpd_timeout (normal: 300s, overload: 10s)\fR"
739/*	When the Postfix SMTP server wants to send an SMTP server
740/*	response, how long the Postfix SMTP server will wait for an underlying
741/*	network write operation to complete; and when the Postfix SMTP
742/*	server Postfix wants to receive an SMTP client request, how long
743/*	the Postfix SMTP server will wait for an underlying network read
744/*	operation to complete.
745/* .IP "\fBsmtpd_history_flush_threshold (100)\fR"
746/*	The maximal number of lines in the Postfix SMTP server command history
747/*	before it is flushed upon receipt of EHLO, RSET, or end of DATA.
748/* .PP
749/*	Available in Postfix version 2.3 and later:
750/* .IP "\fBsmtpd_peername_lookup (yes)\fR"
751/*	Attempt to look up the remote SMTP client hostname, and verify that
752/*	the name matches the client IP address.
753/* .PP
754/*	The per SMTP client connection count and request rate limits are
755/*	implemented in co-operation with the \fBanvil\fR(8) service, and
756/*	are available in Postfix version 2.2 and later.
757/* .IP "\fBsmtpd_client_connection_count_limit (50)\fR"
758/*	How many simultaneous connections any client is allowed to
759/*	make to this service.
760/* .IP "\fBsmtpd_client_connection_rate_limit (0)\fR"
761/*	The maximal number of connection attempts any client is allowed to
762/*	make to this service per time unit.
763/* .IP "\fBsmtpd_client_message_rate_limit (0)\fR"
764/*	The maximal number of message delivery requests that any client is
765/*	allowed to make to this service per time unit, regardless of whether
766/*	or not Postfix actually accepts those messages.
767/* .IP "\fBsmtpd_client_recipient_rate_limit (0)\fR"
768/*	The maximal number of recipient addresses that any client is allowed
769/*	to send to this service per time unit, regardless of whether or not
770/*	Postfix actually accepts those recipients.
771/* .IP "\fBsmtpd_client_event_limit_exceptions ($mynetworks)\fR"
772/*	Clients that are excluded from smtpd_client_*_count/rate_limit
773/*	restrictions.
774/* .PP
775/*	Available in Postfix version 2.3 and later:
776/* .IP "\fBsmtpd_client_new_tls_session_rate_limit (0)\fR"
777/*	The maximal number of new (i.e., uncached) TLS sessions that a
778/*	remote SMTP client is allowed to negotiate with this service per
779/*	time unit.
780/* .PP
781/*	Available in Postfix version 2.9 - 3.6:
782/* .IP "\fBsmtpd_per_record_deadline (normal: no, overload: yes)\fR"
783/*	Change the behavior of the smtpd_timeout and smtpd_starttls_timeout
784/*	time limits, from a
785/*	time limit per read or write system call, to a time limit to send
786/*	or receive a complete record (an SMTP command line, SMTP response
787/*	line, SMTP message content line, or TLS protocol message).
788/* .PP
789/*	Available in Postfix version 3.1 and later:
790/* .IP "\fBsmtpd_client_auth_rate_limit (0)\fR"
791/*	The maximal number of AUTH commands that any client is allowed to
792/*	send to this service per time unit, regardless of whether or not
793/*	Postfix actually accepts those commands.
794/* .PP
795/*	Available in Postfix version 3.7 and later:
796/* .IP "\fBsmtpd_per_request_deadline (normal: no, overload: yes)\fR"
797/*	Change the behavior of the smtpd_timeout and smtpd_starttls_timeout
798/*	time limits, from a time limit per plaintext or TLS read or write
799/*	call, to a combined time limit for receiving a complete SMTP request
800/*	and for sending a complete SMTP response.
801/* .IP "\fBsmtpd_min_data_rate (500)\fR"
802/*	The minimum plaintext data transfer rate in bytes/second for
803/*	DATA and BDAT requests, when deadlines are enabled with
804/*	smtpd_per_request_deadline.
805/* .IP "\fBheader_from_format (standard)\fR"
806/*	The format of the Postfix-generated \fBFrom:\fR header.
807/* .PP
808/*	Available in Postfix version 3.8 and later:
809/* .IP "\fBsmtpd_client_ipv4_prefix_length (32)\fR"
810/*	Aggregate smtpd_client_*_count and smtpd_client_*_rate statistics
811/*	by IPv4 network blocks with the specified network prefix.
812/* .IP "\fBsmtpd_client_ipv6_prefix_length (84)\fR"
813/*	Aggregate smtpd_client_*_count and smtpd_client_*_rate statistics
814/*	by IPv6 network blocks with the specified network prefix.
815/* .PP
816/*	Available in Postfix 3.9, 3.8.1, 3.7.6, 3.6.10, 3.5.20 and later:
817/* .IP "\fBsmtpd_forbid_unauth_pipelining (Postfix >= 3.9: yes)\fR"
818/*	Disconnect remote SMTP clients that violate RFC 2920 (or 5321)
819/*	command pipelining constraints.
820/* .PP
821/*	Available in Postfix 3.9, 3.8.4, 3.7.9, 3.6.13, 3.5.23 and later:
822/* .IP "\fBsmtpd_forbid_bare_newline (Postfix < 3.9: no)\fR"
823/*	Reply with "Error: bare <LF> received" and disconnect
824/*	when a remote SMTP client sends a line ending in <LF>, violating
825/*	the RFC 5321 requirement that lines must end in <CR><LF>.
826/* .IP "\fBsmtpd_forbid_bare_newline_exclusions ($mynetworks)\fR"
827/*	Exclude the specified clients from smtpd_forbid_bare_newline
828/*	enforcement.
829/* TARPIT CONTROLS
830/* .ad
831/* .fi
832/*	When a remote SMTP client makes errors, the Postfix SMTP server
833/*	can insert delays before responding. This can help to slow down
834/*	run-away software.  The behavior is controlled by an error counter
835/*	that counts the number of errors within an SMTP session that a
836/*	client makes without delivering mail.
837/* .IP "\fBsmtpd_error_sleep_time (1s)\fR"
838/*	With Postfix version 2.1 and later: the SMTP server response delay after
839/*	a client has made more than $smtpd_soft_error_limit errors, and
840/*	fewer than $smtpd_hard_error_limit errors, without delivering mail.
841/* .IP "\fBsmtpd_soft_error_limit (10)\fR"
842/*	The number of errors a remote SMTP client is allowed to make without
843/*	delivering mail before the Postfix SMTP server slows down all its
844/*	responses.
845/* .IP "\fBsmtpd_hard_error_limit (normal: 20, overload: 1)\fR"
846/*	The maximal number of errors a remote SMTP client is allowed to
847/*	make without delivering mail.
848/* .IP "\fBsmtpd_junk_command_limit (normal: 100, overload: 1)\fR"
849/*	The number of junk commands (NOOP, VRFY, ETRN or RSET) that a remote
850/*	SMTP client can send before the Postfix SMTP server starts to
851/*	increment the error counter with each junk command.
852/* .PP
853/*	Available in Postfix version 2.1 and later:
854/* .IP "\fBsmtpd_recipient_overshoot_limit (1000)\fR"
855/*	The number of recipients that a remote SMTP client can send in
856/*	excess of the limit specified with $smtpd_recipient_limit, before
857/*	the Postfix SMTP server increments the per-session error count
858/*	for each excess recipient.
859/* ACCESS POLICY DELEGATION CONTROLS
860/* .ad
861/* .fi
862/*	As of version 2.1, Postfix can be configured to delegate access
863/*	policy decisions to an external server that runs outside Postfix.
864/*	See the file SMTPD_POLICY_README for more information.
865/* .IP "\fBsmtpd_policy_service_max_idle (300s)\fR"
866/*	The time after which an idle SMTPD policy service connection is
867/*	closed.
868/* .IP "\fBsmtpd_policy_service_max_ttl (1000s)\fR"
869/*	The time after which an active SMTPD policy service connection is
870/*	closed.
871/* .IP "\fBsmtpd_policy_service_timeout (100s)\fR"
872/*	The time limit for connecting to, writing to, or receiving from a
873/*	delegated SMTPD policy server.
874/* .PP
875/*	Available in Postfix version 3.0 and later:
876/* .IP "\fBsmtpd_policy_service_default_action (451 4.3.5 Server configuration problem)\fR"
877/*	The default action when an SMTPD policy service request fails.
878/* .IP "\fBsmtpd_policy_service_request_limit (0)\fR"
879/*	The maximal number of requests per SMTPD policy service connection,
880/*	or zero (no limit).
881/* .IP "\fBsmtpd_policy_service_try_limit (2)\fR"
882/*	The maximal number of attempts to send an SMTPD policy service
883/*	request before giving up.
884/* .IP "\fBsmtpd_policy_service_retry_delay (1s)\fR"
885/*	The delay between attempts to resend a failed SMTPD policy
886/*	service request.
887/* .PP
888/*	Available in Postfix version 3.1 and later:
889/* .IP "\fBsmtpd_policy_service_policy_context (empty)\fR"
890/*	Optional information that the Postfix SMTP server specifies in
891/*	the "policy_context" attribute of a policy service request (originally,
892/*	to share the same service endpoint among multiple check_policy_service
893/*	clients).
894/* ACCESS CONTROLS
895/* .ad
896/* .fi
897/*	The SMTPD_ACCESS_README document gives an introduction to all the
898/*	SMTP server access control features.
899/* .IP "\fBsmtpd_delay_reject (yes)\fR"
900/*	Wait until the RCPT TO command before evaluating
901/*	$smtpd_client_restrictions, $smtpd_helo_restrictions and
902/*	$smtpd_sender_restrictions, or wait until the ETRN command before
903/*	evaluating $smtpd_client_restrictions and $smtpd_helo_restrictions.
904/* .IP "\fBparent_domain_matches_subdomains (see 'postconf -d' output)\fR"
905/*	A list of Postfix features where the pattern "example.com" also
906/*	matches subdomains of example.com,
907/*	instead of requiring an explicit ".example.com" pattern.
908/* .IP "\fBsmtpd_client_restrictions (empty)\fR"
909/*	Optional restrictions that the Postfix SMTP server applies in the
910/*	context of a client connection request.
911/* .IP "\fBsmtpd_helo_required (no)\fR"
912/*	Require that a remote SMTP client introduces itself with the HELO
913/*	or EHLO command before sending the MAIL command or other commands
914/*	that require EHLO negotiation.
915/* .IP "\fBsmtpd_helo_restrictions (empty)\fR"
916/*	Optional restrictions that the Postfix SMTP server applies in the
917/*	context of a client HELO command.
918/* .IP "\fBsmtpd_sender_restrictions (empty)\fR"
919/*	Optional restrictions that the Postfix SMTP server applies in the
920/*	context of a client MAIL FROM command.
921/* .IP "\fBsmtpd_recipient_restrictions (see 'postconf -d' output)\fR"
922/*	Optional restrictions that the Postfix SMTP server applies in the
923/*	context of a client RCPT TO command, after smtpd_relay_restrictions.
924/* .IP "\fBsmtpd_etrn_restrictions (empty)\fR"
925/*	Optional restrictions that the Postfix SMTP server applies in the
926/*	context of a client ETRN command.
927/* .IP "\fBallow_untrusted_routing (no)\fR"
928/*	Forward mail with sender-specified routing (user[@%!]remote[@%!]site)
929/*	from untrusted clients to destinations matching $relay_domains.
930/* .IP "\fBsmtpd_restriction_classes (empty)\fR"
931/*	User-defined aliases for groups of access restrictions.
932/* .IP "\fBsmtpd_null_access_lookup_key (<>)\fR"
933/*	The lookup key to be used in SMTP \fBaccess\fR(5) tables instead of the
934/*	null sender address.
935/* .IP "\fBpermit_mx_backup_networks (empty)\fR"
936/*	Restrict the use of the permit_mx_backup SMTP access feature to
937/*	only domains whose primary MX hosts match the listed networks.
938/* .PP
939/*	Available in Postfix version 2.0 and later:
940/* .IP "\fBsmtpd_data_restrictions (empty)\fR"
941/*	Optional access restrictions that the Postfix SMTP server applies
942/*	in the context of the SMTP DATA command.
943/* .IP "\fBsmtpd_expansion_filter (see 'postconf -d' output)\fR"
944/*	What characters are allowed in $name expansions of RBL reply
945/*	templates.
946/* .PP
947/*	Available in Postfix version 2.1 and later:
948/* .IP "\fBsmtpd_reject_unlisted_sender (no)\fR"
949/*	Request that the Postfix SMTP server rejects mail from unknown
950/*	sender addresses, even when no explicit reject_unlisted_sender
951/*	access restriction is specified.
952/* .IP "\fBsmtpd_reject_unlisted_recipient (yes)\fR"
953/*	Request that the Postfix SMTP server rejects mail for unknown
954/*	recipient addresses, even when no explicit reject_unlisted_recipient
955/*	access restriction is specified.
956/* .PP
957/*	Available in Postfix version 2.2 and later:
958/* .IP "\fBsmtpd_end_of_data_restrictions (empty)\fR"
959/*	Optional access restrictions that the Postfix SMTP server
960/*	applies in the context of the SMTP END-OF-DATA command.
961/* .PP
962/*	Available in Postfix version 2.10 and later:
963/* .IP "\fBsmtpd_relay_restrictions (permit_mynetworks, permit_sasl_authenticated, defer_unauth_destination)\fR"
964/*	Access restrictions for mail relay control that the Postfix
965/*	SMTP server applies in the context of the RCPT TO command, before
966/*	smtpd_recipient_restrictions.
967/* SENDER AND RECIPIENT ADDRESS VERIFICATION CONTROLS
968/* .ad
969/* .fi
970/*	Postfix version 2.1 introduces sender and recipient address verification.
971/*	This feature is implemented by sending probe email messages that
972/*	are not actually delivered.
973/*	This feature is requested via the reject_unverified_sender and
974/*	reject_unverified_recipient access restrictions.  The status of
975/*	verification probes is maintained by the \fBverify\fR(8) server.
976/*	See the file ADDRESS_VERIFICATION_README for information
977/*	about how to configure and operate the Postfix sender/recipient
978/*	address verification service.
979/* .IP "\fBaddress_verify_poll_count (normal: 3, overload: 1)\fR"
980/*	How many times to query the \fBverify\fR(8) service for the completion
981/*	of an address verification request in progress.
982/* .IP "\fBaddress_verify_poll_delay (3s)\fR"
983/*	The delay between queries for the completion of an address
984/*	verification request in progress.
985/* .IP "\fBaddress_verify_sender ($double_bounce_sender)\fR"
986/*	The sender address to use in address verification probes; prior
987/*	to Postfix 2.5 the default was "postmaster".
988/* .IP "\fBunverified_sender_reject_code (450)\fR"
989/*	The numerical Postfix SMTP server response code when a recipient
990/*	address is rejected by the reject_unverified_sender restriction.
991/* .IP "\fBunverified_recipient_reject_code (450)\fR"
992/*	The numerical Postfix SMTP server response when a recipient address
993/*	is rejected by the reject_unverified_recipient restriction.
994/* .PP
995/*	Available in Postfix version 2.6 and later:
996/* .IP "\fBunverified_sender_defer_code (450)\fR"
997/*	The numerical Postfix SMTP server response code when a sender address
998/*	probe fails due to a temporary error condition.
999/* .IP "\fBunverified_recipient_defer_code (450)\fR"
1000/*	The numerical Postfix SMTP server response when a recipient address
1001/*	probe fails due to a temporary error condition.
1002/* .IP "\fBunverified_sender_reject_reason (empty)\fR"
1003/*	The Postfix SMTP server's reply when rejecting mail with
1004/*	reject_unverified_sender.
1005/* .IP "\fBunverified_recipient_reject_reason (empty)\fR"
1006/*	The Postfix SMTP server's reply when rejecting mail with
1007/*	reject_unverified_recipient.
1008/* .IP "\fBunverified_sender_tempfail_action ($reject_tempfail_action)\fR"
1009/*	The Postfix SMTP server's action when reject_unverified_sender
1010/*	fails due to a temporary error condition.
1011/* .IP "\fBunverified_recipient_tempfail_action ($reject_tempfail_action)\fR"
1012/*	The Postfix SMTP server's action when reject_unverified_recipient
1013/*	fails due to a temporary error condition.
1014/* .PP
1015/*	Available with Postfix 2.9 and later:
1016/* .IP "\fBaddress_verify_sender_ttl (0s)\fR"
1017/*	The time between changes in the time-dependent portion of address
1018/*	verification probe sender addresses.
1019/* ACCESS CONTROL RESPONSES
1020/* .ad
1021/* .fi
1022/*	The following parameters control numerical SMTP reply codes
1023/*	and/or text responses.
1024/* .IP "\fBaccess_map_reject_code (554)\fR"
1025/*	The numerical Postfix SMTP server response code for
1026/*	an \fBaccess\fR(5) map "reject" action.
1027/* .IP "\fBdefer_code (450)\fR"
1028/*	The numerical Postfix SMTP server response code when a remote SMTP
1029/*	client request is rejected by the "defer" restriction.
1030/* .IP "\fBinvalid_hostname_reject_code (501)\fR"
1031/*	The numerical Postfix SMTP server response code when the client
1032/*	HELO or EHLO command parameter is rejected by the reject_invalid_helo_hostname
1033/*	restriction.
1034/* .IP "\fBmaps_rbl_reject_code (554)\fR"
1035/*	The numerical Postfix SMTP server response code when a remote SMTP
1036/*	client request is blocked by the reject_rbl_client, reject_rhsbl_client,
1037/*	reject_rhsbl_reverse_client, reject_rhsbl_sender or
1038/*	reject_rhsbl_recipient restriction.
1039/* .IP "\fBnon_fqdn_reject_code (504)\fR"
1040/*	The numerical Postfix SMTP server reply code when a client request
1041/*	is rejected by the reject_non_fqdn_helo_hostname, reject_non_fqdn_sender
1042/*	or reject_non_fqdn_recipient restriction.
1043/* .IP "\fBplaintext_reject_code (450)\fR"
1044/*	The numerical Postfix SMTP server response code when a request
1045/*	is rejected by the \fBreject_plaintext_session\fR restriction.
1046/* .IP "\fBreject_code (554)\fR"
1047/*	The numerical Postfix SMTP server response code when a remote SMTP
1048/*	client request is rejected by the "reject" restriction.
1049/* .IP "\fBrelay_domains_reject_code (554)\fR"
1050/*	The numerical Postfix SMTP server response code when a client
1051/*	request is rejected by the reject_unauth_destination recipient
1052/*	restriction.
1053/* .IP "\fBunknown_address_reject_code (450)\fR"
1054/*	The numerical response code when the Postfix SMTP server rejects a
1055/*	sender or recipient address because its domain is unknown.
1056/* .IP "\fBunknown_client_reject_code (450)\fR"
1057/*	The numerical Postfix SMTP server response code when a client
1058/*	without valid address <=> name mapping is rejected by the
1059/*	reject_unknown_client_hostname restriction.
1060/* .IP "\fBunknown_hostname_reject_code (450)\fR"
1061/*	The numerical Postfix SMTP server response code when the hostname
1062/*	specified with the HELO or EHLO command is rejected by the
1063/*	reject_unknown_helo_hostname restriction.
1064/* .PP
1065/*	Available in Postfix version 2.0 and later:
1066/* .IP "\fBdefault_rbl_reply (see 'postconf -d' output)\fR"
1067/*	The default Postfix SMTP server response template for a request that is
1068/*	rejected by an RBL-based restriction.
1069/* .IP "\fBmulti_recipient_bounce_reject_code (550)\fR"
1070/*	The numerical Postfix SMTP server response code when a remote SMTP
1071/*	client request is blocked by the reject_multi_recipient_bounce
1072/*	restriction.
1073/* .IP "\fBrbl_reply_maps (empty)\fR"
1074/*	Optional lookup tables with RBL response templates.
1075/* .PP
1076/*	Available in Postfix version 2.6 and later:
1077/* .IP "\fBaccess_map_defer_code (450)\fR"
1078/*	The numerical Postfix SMTP server response code for
1079/*	an \fBaccess\fR(5) map "defer" action, including "defer_if_permit"
1080/*	or "defer_if_reject".
1081/* .IP "\fBreject_tempfail_action (defer_if_permit)\fR"
1082/*	The Postfix SMTP server's action when a reject-type restriction
1083/*	fails due to a temporary error condition.
1084/* .IP "\fBunknown_helo_hostname_tempfail_action ($reject_tempfail_action)\fR"
1085/*	The Postfix SMTP server's action when reject_unknown_helo_hostname
1086/*	fails due to a temporary error condition.
1087/* .IP "\fBunknown_address_tempfail_action ($reject_tempfail_action)\fR"
1088/*	The Postfix SMTP server's action when reject_unknown_sender_domain
1089/*	or reject_unknown_recipient_domain fail due to a temporary error
1090/*	condition.
1091/* MISCELLANEOUS CONTROLS
1092/* .ad
1093/* .fi
1094/* .IP "\fBconfig_directory (see 'postconf -d' output)\fR"
1095/*	The default location of the Postfix main.cf and master.cf
1096/*	configuration files.
1097/* .IP "\fBdaemon_timeout (18000s)\fR"
1098/*	How much time a Postfix daemon process may take to handle a
1099/*	request before it is terminated by a built-in watchdog timer.
1100/* .IP "\fBcommand_directory (see 'postconf -d' output)\fR"
1101/*	The location of all postfix administrative commands.
1102/* .IP "\fBdouble_bounce_sender (double-bounce)\fR"
1103/*	The sender address of postmaster notifications that are generated
1104/*	by the mail system.
1105/* .IP "\fBipc_timeout (3600s)\fR"
1106/*	The time limit for sending or receiving information over an internal
1107/*	communication channel.
1108/* .IP "\fBmail_name (Postfix)\fR"
1109/*	The mail system name that is displayed in Received: headers, in
1110/*	the SMTP greeting banner, and in bounced mail.
1111/* .IP "\fBmail_owner (postfix)\fR"
1112/*	The UNIX system account that owns the Postfix queue and most Postfix
1113/*	daemon processes.
1114/* .IP "\fBmax_idle (100s)\fR"
1115/*	The maximum amount of time that an idle Postfix daemon process waits
1116/*	for an incoming connection before terminating voluntarily.
1117/* .IP "\fBmax_use (100)\fR"
1118/*	The maximal number of incoming connections that a Postfix daemon
1119/*	process will service before terminating voluntarily.
1120/* .IP "\fBmyhostname (see 'postconf -d' output)\fR"
1121/*	The internet hostname of this mail system.
1122/* .IP "\fBmynetworks (see 'postconf -d' output)\fR"
1123/*	The list of "trusted" remote SMTP clients that have more privileges than
1124/*	"strangers".
1125/* .IP "\fBmyorigin ($myhostname)\fR"
1126/*	The domain name that locally-posted mail appears to come
1127/*	from, and that locally posted mail is delivered to.
1128/* .IP "\fBprocess_id (read-only)\fR"
1129/*	The process ID of a Postfix command or daemon process.
1130/* .IP "\fBprocess_name (read-only)\fR"
1131/*	The process name of a Postfix command or daemon process.
1132/* .IP "\fBqueue_directory (see 'postconf -d' output)\fR"
1133/*	The location of the Postfix top-level queue directory.
1134/* .IP "\fBrecipient_delimiter (empty)\fR"
1135/*	The set of characters that can separate an email address
1136/*	localpart, user name, or a .forward file name from its extension.
1137/* .IP "\fBsmtpd_banner ($myhostname ESMTP $mail_name)\fR"
1138/*	The text that follows the 220 status code in the SMTP greeting
1139/*	banner.
1140/* .IP "\fBsyslog_facility (mail)\fR"
1141/*	The syslog facility of Postfix logging.
1142/* .IP "\fBsyslog_name (see 'postconf -d' output)\fR"
1143/*	A prefix that is prepended to the process name in syslog
1144/*	records, so that, for example, "smtpd" becomes "prefix/smtpd".
1145/* .PP
1146/*	Available in Postfix version 2.2 and later:
1147/* .IP "\fBsmtpd_forbidden_commands (CONNECT GET POST regexp:{{/^[^A-Z]/ Bogus}})\fR"
1148/*	List of commands that cause the Postfix SMTP server to immediately
1149/*	terminate the session with a 221 code.
1150/* .PP
1151/*	Available in Postfix version 2.5 and later:
1152/* .IP "\fBsmtpd_client_port_logging (no)\fR"
1153/*	Enable logging of the remote SMTP client port in addition to
1154/*	the hostname and IP address.
1155/* .PP
1156/*	Available in Postfix 3.3 and later:
1157/* .IP "\fBservice_name (read-only)\fR"
1158/*	The master.cf service name of a Postfix daemon process.
1159/* .PP
1160/*	Available in Postfix 3.4 and later:
1161/* .IP "\fBsmtpd_reject_footer_maps (empty)\fR"
1162/*	Lookup tables, indexed by the complete Postfix SMTP server 4xx or
1163/*	5xx response, with reject footer templates.
1164/* SEE ALSO
1165/*	anvil(8), connection/rate limiting
1166/*	cleanup(8), message canonicalization
1167/*	tlsmgr(8), TLS session and PRNG management
1168/*	trivial-rewrite(8), address resolver
1169/*	verify(8), address verification service
1170/*	postconf(5), configuration parameters
1171/*	master(5), generic daemon options
1172/*	master(8), process manager
1173/*	postlogd(8), Postfix logging
1174/*	syslogd(8), system logging
1175/* README FILES
1176/* .ad
1177/* .fi
1178/*	Use "\fBpostconf readme_directory\fR" or
1179/*	"\fBpostconf html_directory\fR" to locate this information.
1180/* .na
1181/* .nf
1182/*	ADDRESS_CLASS_README, blocking unknown hosted or relay recipients
1183/*	ADDRESS_REWRITING_README, Postfix address manipulation
1184/*	BDAT_README, Postfix CHUNKING support
1185/*	FILTER_README, external after-queue content filter
1186/*	LOCAL_RECIPIENT_README, blocking unknown local recipients
1187/*	MILTER_README, before-queue mail filter applications
1188/*	SMTPD_ACCESS_README, built-in access policies
1189/*	SMTPD_POLICY_README, external policy server
1190/*	SMTPD_PROXY_README, external before-queue content filter
1191/*	SASL_README, Postfix SASL howto
1192/*	TLS_README, Postfix STARTTLS howto
1193/*	VERP_README, Postfix XVERP extension
1194/*	XCLIENT_README, Postfix XCLIENT extension
1195/*	XFORWARD_README, Postfix XFORWARD extension
1196/* LICENSE
1197/* .ad
1198/* .fi
1199/*	The Secure Mailer license must be distributed with this software.
1200/* AUTHOR(S)
1201/*	Wietse Venema
1202/*	IBM T.J. Watson Research
1203/*	P.O. Box 704
1204/*	Yorktown Heights, NY 10598, USA
1205/*
1206/*	Wietse Venema
1207/*	Google, Inc.
1208/*	111 8th Avenue
1209/*	New York, NY 10011, USA
1210/*
1211/*	SASL support originally by:
1212/*	Till Franke
1213/*	SuSE Rhein/Main AG
1214/*	65760 Eschborn, Germany
1215/*
1216/*	TLS support originally by:
1217/*	Lutz Jaenicke
1218/*	BTU Cottbus
1219/*	Allgemeine Elektrotechnik
1220/*	Universitaetsplatz 3-4
1221/*	D-03044 Cottbus, Germany
1222/*
1223/*	Revised TLS support by:
1224/*	Victor Duchovni
1225/*	Morgan Stanley
1226/*--*/
1227
1228/* System library. */
1229
1230#include <sys_defs.h>
1231#include <sys/socket.h>
1232#include <sys/stat.h>
1233#include <netinet/in.h>
1234#include <arpa/inet.h>
1235#include <netdb.h>
1236#include <string.h>
1237#include <stdio.h>			/* remove() */
1238#include <unistd.h>
1239#include <stdlib.h>
1240#include <errno.h>
1241#include <ctype.h>
1242#include <signal.h>
1243#include <stddef.h>			/* offsetof() */
1244
1245#ifdef STRCASECMP_IN_STRINGS_H
1246#include <strings.h>
1247#endif
1248
1249/* Utility library. */
1250
1251#include <msg.h>
1252#include <mymalloc.h>
1253#include <vstring.h>
1254#include <vstream.h>
1255#include <vstring_vstream.h>
1256#include <stringops.h>
1257#include <events.h>
1258#include <smtp_stream.h>
1259#include <valid_hostname.h>
1260#include <dict.h>
1261#include <watchdog.h>
1262#include <iostuff.h>
1263#include <split_at.h>
1264#include <name_code.h>
1265#include <inet_proto.h>
1266
1267/* Global library. */
1268
1269#include <mail_params.h>
1270#include <mail_version.h>		/* milter_macro_v */
1271#include <record.h>
1272#include <rec_type.h>
1273#include <mail_proto.h>
1274#include <cleanup_user.h>
1275#include <mail_date.h>
1276#include <mail_conf.h>
1277#include <off_cvt.h>
1278#include <debug_peer.h>
1279#include <mail_error.h>
1280#include <flush_clnt.h>
1281#include <mail_stream.h>
1282#include <mail_queue.h>
1283#include <tok822.h>
1284#include <verp_sender.h>
1285#include <string_list.h>
1286#include <quote_822_local.h>
1287#include <lex_822.h>
1288#include <namadr_list.h>
1289#include <input_transp.h>
1290#include <is_header.h>
1291#include <anvil_clnt.h>
1292#include <flush_clnt.h>
1293#include <ehlo_mask.h>			/* ehlo filter */
1294#include <maps.h>			/* ehlo filter */
1295#include <valid_mailhost_addr.h>
1296#include <dsn_mask.h>
1297#include <xtext.h>
1298#include <uxtext.h>
1299#include <tls_proxy.h>
1300#include <verify_sender_addr.h>
1301#include <smtputf8.h>
1302#include <match_parent_style.h>
1303#include <normalize_mailhost_addr.h>
1304#include <info_log_addr_form.h>
1305#include <hfrom_format.h>
1306
1307/* Single-threaded server skeleton. */
1308
1309#include <mail_server.h>
1310
1311/* Mail filter library. */
1312
1313#include <milter.h>
1314
1315/* DNS library. */
1316
1317#include <dns.h>
1318
1319/* Application-specific */
1320
1321#include <smtpd_token.h>
1322#include <smtpd.h>
1323#include <smtpd_check.h>
1324#include <smtpd_chat.h>
1325#include <smtpd_sasl_proto.h>
1326#include <smtpd_sasl_glue.h>
1327#include <smtpd_proxy.h>
1328#include <smtpd_milter.h>
1329#include <smtpd_expand.h>
1330
1331#include "pfilter.h"
1332
1333 /*
1334  * Tunable parameters. Make sure that there is some bound on the length of
1335  * an SMTP command, so that the mail system stays in control even when a
1336  * malicious client sends commands of unreasonable length (qmail-dos-1).
1337  * Make sure there is some bound on the number of recipients, so that the
1338  * mail system stays in control even when a malicious client sends an
1339  * unreasonable number of recipients (qmail-dos-2).
1340  */
1341int     var_smtpd_rcpt_limit;
1342int     var_smtpd_tmout;
1343int     var_smtpd_soft_erlim;
1344int     var_smtpd_hard_erlim;
1345long    var_queue_minfree;		/* XXX use off_t */
1346char   *var_smtpd_banner;
1347char   *var_notify_classes;
1348char   *var_client_checks;
1349char   *var_helo_checks;
1350char   *var_mail_checks;
1351char   *var_relay_checks;
1352char   *var_rcpt_checks;
1353char   *var_etrn_checks;
1354char   *var_data_checks;
1355char   *var_eod_checks;
1356int     var_unk_client_code;
1357int     var_bad_name_code;
1358int     var_unk_name_code;
1359int     var_unk_addr_code;
1360int     var_relay_code;
1361int     var_maps_rbl_code;
1362int     var_map_reject_code;
1363int     var_map_defer_code;
1364char   *var_maps_rbl_domains;
1365char   *var_rbl_reply_maps;
1366int     var_helo_required;
1367int     var_reject_code;
1368int     var_defer_code;
1369int     var_smtpd_err_sleep;
1370int     var_non_fqdn_code;
1371char   *var_bounce_rcpt;
1372char   *var_error_rcpt;
1373int     var_smtpd_delay_reject;
1374char   *var_rest_classes;
1375int     var_strict_rfc821_env;
1376bool    var_disable_vrfy_cmd;
1377char   *var_canonical_maps;
1378char   *var_send_canon_maps;
1379char   *var_rcpt_canon_maps;
1380char   *var_virt_alias_maps;
1381char   *var_virt_mailbox_maps;
1382char   *var_alias_maps;
1383char   *var_local_rcpt_maps;
1384bool    var_allow_untrust_route;
1385int     var_smtpd_junk_cmd_limit;
1386int     var_smtpd_rcpt_overlim;
1387bool    var_smtpd_sasl_enable;
1388bool    var_smtpd_sasl_auth_hdr;
1389char   *var_smtpd_sasl_opts;
1390char   *var_smtpd_sasl_path;
1391char   *var_smtpd_sasl_service;
1392char   *var_cyrus_conf_path;
1393char   *var_smtpd_sasl_realm;
1394int     var_smtpd_sasl_resp_limit;
1395char   *var_smtpd_sasl_exceptions_networks;
1396char   *var_smtpd_sasl_type;
1397char   *var_smtpd_sasl_mech_filter;
1398char   *var_filter_xport;
1399bool    var_broken_auth_clients;
1400char   *var_perm_mx_networks;
1401char   *var_smtpd_snd_auth_maps;
1402char   *var_smtpd_noop_cmds;
1403char   *var_smtpd_null_key;
1404int     var_smtpd_hist_thrsh;
1405char   *var_smtpd_exp_filter;
1406char   *var_def_rbl_reply;
1407int     var_unv_from_rcode;
1408int     var_unv_rcpt_rcode;
1409int     var_unv_from_dcode;
1410int     var_unv_rcpt_dcode;
1411char   *var_unv_from_why;
1412char   *var_unv_rcpt_why;
1413int     var_mul_rcpt_code;
1414char   *var_relay_rcpt_maps;
1415int     var_local_rcpt_code;
1416int     var_virt_alias_code;
1417int     var_virt_mailbox_code;
1418int     var_relay_rcpt_code;
1419char   *var_verp_clients;
1420int     var_show_unk_rcpt_table;
1421int     var_verify_poll_count;
1422int     var_verify_poll_delay;
1423char   *var_smtpd_proxy_filt;
1424int     var_smtpd_proxy_tmout;
1425char   *var_smtpd_proxy_ehlo;
1426char   *var_smtpd_proxy_opts;
1427char   *var_input_transp;
1428int     var_smtpd_policy_tmout;
1429int     var_smtpd_policy_req_limit;
1430int     var_smtpd_policy_try_limit;
1431int     var_smtpd_policy_try_delay;
1432char   *var_smtpd_policy_def_action;
1433char   *var_smtpd_policy_context;
1434int     var_smtpd_policy_idle;
1435int     var_smtpd_policy_ttl;
1436char   *var_xclient_hosts;
1437char   *var_xforward_hosts;
1438bool    var_smtpd_rej_unl_from;
1439bool    var_smtpd_rej_unl_rcpt;
1440char   *var_smtpd_forbid_cmds;
1441int     var_smtpd_crate_limit;
1442int     var_smtpd_cconn_limit;
1443int     var_smtpd_cmail_limit;
1444int     var_smtpd_crcpt_limit;
1445int     var_smtpd_cntls_limit;
1446int     var_smtpd_cauth_limit;
1447int     var_smtpd_cipv4_prefix;
1448int     var_smtpd_cipv6_prefix;
1449char   *var_smtpd_hoggers;
1450char   *var_local_rwr_clients;
1451char   *var_smtpd_ehlo_dis_words;
1452char   *var_smtpd_ehlo_dis_maps;
1453
1454char   *var_smtpd_tls_level;
1455bool    var_smtpd_use_tls;
1456bool    var_smtpd_enforce_tls;
1457bool    var_smtpd_tls_wrappermode;
1458bool    var_smtpd_tls_auth_only;
1459char   *var_smtpd_cmd_filter;
1460char   *var_smtpd_rej_footer;
1461char   *var_smtpd_rej_ftr_maps;
1462char   *var_smtpd_acl_perm_log;
1463char   *var_smtpd_dns_re_filter;
1464
1465#ifdef USE_TLS
1466char   *var_smtpd_relay_ccerts;
1467char   *var_smtpd_sasl_tls_opts;
1468int     var_smtpd_starttls_tmout;
1469char   *var_smtpd_tls_CAfile;
1470char   *var_smtpd_tls_CApath;
1471bool    var_smtpd_tls_ask_ccert;
1472int     var_smtpd_tls_ccert_vd;
1473char   *var_smtpd_tls_cert_file;
1474char   *var_smtpd_tls_mand_ciph;
1475char   *var_smtpd_tls_excl_ciph;
1476char   *var_smtpd_tls_mand_excl;
1477char   *var_smtpd_tls_dcert_file;
1478char   *var_smtpd_tls_dh1024_param_file;
1479char   *var_smtpd_tls_dh512_param_file;
1480char   *var_smtpd_tls_dkey_file;
1481char   *var_smtpd_tls_key_file;
1482char   *var_smtpd_tls_loglevel;
1483char   *var_smtpd_tls_mand_proto;
1484bool    var_smtpd_tls_received_header;
1485bool    var_smtpd_tls_req_ccert;
1486bool    var_smtpd_tls_set_sessid;
1487char   *var_smtpd_tls_fpt_dgst;
1488char   *var_smtpd_tls_ciph;
1489char   *var_smtpd_tls_proto;
1490char   *var_smtpd_tls_eecdh;
1491char   *var_smtpd_tls_eccert_file;
1492char   *var_smtpd_tls_eckey_file;
1493char   *var_smtpd_tls_chain_files;
1494
1495#endif
1496
1497bool    var_smtpd_peername_lookup;
1498int     var_plaintext_code;
1499bool    var_smtpd_delay_open;
1500char   *var_smtpd_milters;
1501char   *var_smtpd_milter_maps;
1502int     var_milt_conn_time;
1503int     var_milt_cmd_time;
1504int     var_milt_msg_time;
1505char   *var_milt_protocol;
1506char   *var_milt_def_action;
1507char   *var_milt_daemon_name;
1508char   *var_milt_v;
1509char   *var_milt_conn_macros;
1510char   *var_milt_helo_macros;
1511char   *var_milt_mail_macros;
1512char   *var_milt_rcpt_macros;
1513char   *var_milt_data_macros;
1514char   *var_milt_eoh_macros;
1515char   *var_milt_eod_macros;
1516char   *var_milt_unk_macros;
1517char   *var_milt_macro_deflts;
1518bool    var_smtpd_client_port_log;
1519bool    var_smtpd_forbid_unauth_pipe;
1520char   *var_stress;
1521
1522char   *var_reject_tmpf_act;
1523char   *var_unk_name_tf_act;
1524char   *var_unk_addr_tf_act;
1525char   *var_unv_rcpt_tf_act;
1526char   *var_unv_from_tf_act;
1527
1528int     smtpd_proxy_opts;
1529
1530#ifdef USE_TLSPROXY
1531char   *var_tlsproxy_service;
1532
1533#endif
1534
1535char   *var_smtpd_uproxy_proto;
1536int     var_smtpd_uproxy_tmout;
1537bool    var_relay_before_rcpt_checks;
1538bool    var_smtpd_req_deadline;
1539int     var_smtpd_min_data_rate;
1540char   *var_hfrom_format;
1541bool    var_smtpd_forbid_bare_lf;
1542char   *var_smtpd_forbid_bare_lf_excl;
1543static NAMADR_LIST *bare_lf_excl;
1544
1545 /*
1546  * Silly little macros.
1547  */
1548#define STR(x)	vstring_str(x)
1549#define LEN(x)	VSTRING_LEN(x)
1550
1551 /*
1552  * EHLO keyword filter
1553  */
1554static MAPS *ehlo_discard_maps;
1555
1556 /*
1557  * Per-client Milter support.
1558  */
1559static MAPS *smtpd_milter_maps;
1560static void setup_milters(SMTPD_STATE *);
1561static void teardown_milters(SMTPD_STATE *);
1562
1563 /*
1564  * VERP command name.
1565  */
1566#define VERP_CMD	"XVERP"
1567#define VERP_CMD_LEN	5
1568
1569static NAMADR_LIST *verp_clients;
1570
1571 /*
1572  * XCLIENT command. Access control is cached, so that XCLIENT can't override
1573  * its own access control.
1574  */
1575static NAMADR_LIST *xclient_hosts;
1576static int xclient_allowed;		/* XXX should be SMTPD_STATE member */
1577
1578 /*
1579  * XFORWARD command. Access control is cached.
1580  */
1581static NAMADR_LIST *xforward_hosts;
1582static int xforward_allowed;		/* XXX should be SMTPD_STATE member */
1583
1584 /*
1585  * Client connection and rate limiting.
1586  */
1587ANVIL_CLNT *anvil_clnt;
1588static NAMADR_LIST *hogger_list;
1589
1590 /*
1591  * Other application-specific globals.
1592  */
1593int     smtpd_input_transp_mask;
1594
1595 /*
1596  * Forward declarations.
1597  */
1598static void helo_reset(SMTPD_STATE *);
1599static void mail_reset(SMTPD_STATE *);
1600static void rcpt_reset(SMTPD_STATE *);
1601static void chat_reset(SMTPD_STATE *, int);
1602
1603#ifdef USE_TLS
1604static void tls_reset(SMTPD_STATE *);
1605
1606#endif
1607
1608 /*
1609  * This filter is applied after printable().
1610  */
1611#define NEUTER_CHARACTERS " <>()\\\";@"
1612
1613 /*
1614  * Reasons for losing the client.
1615  */
1616#define REASON_TIMEOUT		"timeout"
1617#define REASON_LOST_CONNECTION	"lost connection"
1618#define REASON_ERROR_LIMIT	"too many errors"
1619#define REASON_BARE_LF		"bare <LF> received"
1620
1621#ifdef USE_TLS
1622
1623 /*
1624  * TLS initialization status.
1625  */
1626#ifndef USE_TLSPROXY
1627static TLS_APPL_STATE *smtpd_tls_ctx;
1628static int ask_client_cert;
1629
1630#endif					/* USE_TLSPROXY */
1631#endif
1632
1633 /*
1634  * SMTP command mapping for broken clients.
1635  */
1636static DICT *smtpd_cmd_filter;
1637
1638 /*
1639  * Parsed header_from_format setting.
1640  */
1641int     smtpd_hfrom_format;
1642
1643#ifdef USE_SASL_AUTH
1644
1645 /*
1646  * SASL exceptions.
1647  */
1648static NAMADR_LIST *sasl_exceptions_networks;
1649
1650/* sasl_client_exception - can we offer AUTH for this client */
1651
1652static int sasl_client_exception(SMTPD_STATE *state)
1653{
1654    int     match;
1655
1656    /*
1657     * This is to work around a Netscape mail client bug where it tries to
1658     * use AUTH if available, even if user has not configured it. Returns
1659     * TRUE if AUTH should be offered in the EHLO.
1660     */
1661    if (sasl_exceptions_networks == 0)
1662	return (0);
1663
1664    if ((match = namadr_list_match(sasl_exceptions_networks,
1665				   state->name, state->addr)) == 0)
1666	match = sasl_exceptions_networks->error;
1667
1668    if (msg_verbose)
1669	msg_info("sasl_exceptions: %s, match=%d",
1670		 state->namaddr, match);
1671
1672    return (match);
1673}
1674
1675#endif
1676
1677/* smtpd_whatsup - gather available evidence for logging */
1678
1679static const char *smtpd_whatsup(SMTPD_STATE *state)
1680{
1681    static VSTRING *buf = 0;
1682
1683    if (buf == 0)
1684	buf = vstring_alloc(100);
1685    else
1686	VSTRING_RESET(buf);
1687    if (state->sender)
1688	vstring_sprintf_append(buf, " from=<%s>",
1689			       info_log_addr_form_sender(state->sender));
1690    if (state->recipient)
1691	vstring_sprintf_append(buf, " to=<%s>",
1692			    info_log_addr_form_recipient(state->recipient));
1693    if (state->protocol)
1694	vstring_sprintf_append(buf, " proto=%s", state->protocol);
1695    if (state->helo_name)
1696	vstring_sprintf_append(buf, " helo=<%s>", state->helo_name);
1697#ifdef USE_SASL_AUTH
1698    if (state->sasl_username)
1699	vstring_sprintf_append(buf, " sasl_username=<%s>",
1700			       state->sasl_username);
1701#endif
1702    return (STR(buf));
1703}
1704
1705/* collapse_args - put arguments together again */
1706
1707static void collapse_args(int argc, SMTPD_TOKEN *argv)
1708{
1709    int     i;
1710
1711    for (i = 1; i < argc; i++) {
1712	vstring_strcat(argv[0].vstrval, " ");
1713	vstring_strcat(argv[0].vstrval, argv[i].strval);
1714    }
1715    argv[0].strval = STR(argv[0].vstrval);
1716}
1717
1718/* check_milter_reply - process reply from Milter */
1719
1720static const char *check_milter_reply(SMTPD_STATE *state, const char *reply)
1721{
1722    const char *queue_id = state->queue_id ? state->queue_id : "NOQUEUE";
1723    const char *action;
1724    const char *text;
1725
1726    /*
1727     * The syntax of user-specified SMTP replies is checked by the Milter
1728     * module, because the replies are also used in the cleanup server.
1729     * Automatically disconnect after 421 (shutdown) reply. The Sendmail 8
1730     * Milter quarantine action is not final, so it is not included in
1731     * MILTER_SKIP_FLAGS.
1732     */
1733#define MILTER_SKIP_FLAGS (CLEANUP_FLAG_DISCARD)
1734
1735    switch (reply[0]) {
1736    case 'H':
1737	state->saved_flags |= CLEANUP_FLAG_HOLD;
1738	action = "milter-hold";
1739	reply = 0;
1740	text = "milter triggers HOLD action";
1741	break;
1742    case 'D':
1743	state->saved_flags |= CLEANUP_FLAG_DISCARD;
1744	action = "milter-discard";
1745	reply = 0;
1746	text = "milter triggers DISCARD action";
1747	break;
1748    case 'S':
1749	state->error_mask |= MAIL_ERROR_POLICY;
1750	action = "milter-reject";
1751	reply = "421 4.7.0 Server closing connection";
1752	text = 0;
1753	break;
1754    case '4':
1755    case '5':
1756	state->error_mask |= MAIL_ERROR_POLICY;
1757	action = "milter-reject";
1758	text = 0;
1759	break;
1760    default:
1761	state->error_mask |= MAIL_ERROR_SOFTWARE;
1762	action = "reject";
1763	reply = "421 4.3.5 Server configuration error";
1764	text = 0;
1765	break;
1766    }
1767    msg_info("%s: %s: %s from %s: %s;%s", queue_id, action, state->where,
1768	     state->namaddr, reply ? reply : text, smtpd_whatsup(state));
1769    return (reply);
1770}
1771
1772/* helo_cmd - process HELO command */
1773
1774static int helo_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *argv)
1775{
1776    const char *err;
1777
1778    /*
1779     * RFC 2034: the text part of all 2xx, 4xx, and 5xx SMTP responses other
1780     * than the initial greeting and any response to HELO or EHLO are
1781     * prefaced with a status code as defined in RFC 3463.
1782     */
1783    if (argc < 2) {
1784	state->error_mask |= MAIL_ERROR_PROTOCOL;
1785	smtpd_chat_reply(state, "501 Syntax: HELO hostname");
1786	return (-1);
1787    }
1788    if (argc > 2)
1789	collapse_args(argc - 1, argv + 1);
1790    if (SMTPD_STAND_ALONE(state) == 0
1791	&& var_smtpd_delay_reject == 0
1792	&& (err = smtpd_check_helo(state, argv[1].strval)) != 0) {
1793	smtpd_chat_reply(state, "%s", err);
1794	return (-1);
1795    }
1796
1797    /*
1798     * XXX Sendmail compatibility: if a Milter rejects CONNECT, EHLO, or
1799     * HELO, reply with 250 except in case of 421 (disconnect). The reply
1800     * persists so it will apply to MAIL FROM and to other commands such as
1801     * AUTH, STARTTLS, and VRFY.
1802     */
1803#define PUSH_STRING(old, curr, new)	{ char *old = (curr); (curr) = (new);
1804#define POP_STRING(old, curr)		(curr) = old; }
1805
1806    if (state->milters != 0
1807	&& (state->saved_flags & MILTER_SKIP_FLAGS) == 0
1808     && (err = milter_helo_event(state->milters, argv[1].strval, 0)) != 0) {
1809	/* Log reject etc. with correct HELO information. */
1810	PUSH_STRING(saved_helo, state->helo_name, argv[1].strval);
1811	err = check_milter_reply(state, err);
1812	POP_STRING(saved_helo, state->helo_name);
1813	if (err != 0 && strncmp(err, "421", 3) == 0) {
1814	    smtpd_chat_reply(state, "%s", err);
1815	    return (-1);
1816	}
1817    }
1818    if (state->helo_name != 0)
1819	helo_reset(state);
1820    chat_reset(state, var_smtpd_hist_thrsh);
1821    mail_reset(state);
1822    rcpt_reset(state);
1823    state->helo_name = mystrdup(printable(argv[1].strval, '?'));
1824    neuter(state->helo_name, NEUTER_CHARACTERS, '?');
1825    /* Downgrading the protocol name breaks the unauthorized pipelining test. */
1826    if (strcasecmp(state->protocol, MAIL_PROTO_ESMTP) != 0
1827	&& strcasecmp(state->protocol, MAIL_PROTO_SMTP) != 0) {
1828	myfree(state->protocol);
1829	state->protocol = mystrdup(MAIL_PROTO_SMTP);
1830    }
1831    smtpd_chat_reply(state, "250 %s", var_myhostname);
1832    return (0);
1833}
1834
1835/* cant_announce_feature - explain and terminate this session */
1836
1837static NORETURN cant_announce_feature(SMTPD_STATE *state, const char *feature)
1838{
1839    msg_warn("don't know if EHLO feature %s should be announced to %s",
1840	     feature, state->namaddr);
1841    vstream_longjmp(state->client, SMTP_ERR_DATA);
1842}
1843
1844/* cant_permit_command - explain and terminate this session */
1845
1846static NORETURN cant_permit_command(SMTPD_STATE *state, const char *command)
1847{
1848    msg_warn("don't know if command %s should be allowed from %s",
1849	     command, state->namaddr);
1850    vstream_longjmp(state->client, SMTP_ERR_DATA);
1851}
1852
1853/* ehlo_cmd - process EHLO command */
1854
1855static int ehlo_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *argv)
1856{
1857    const char *err;
1858    int     discard_mask;
1859    char  **cpp;
1860
1861    /*
1862     * XXX 2821 new feature: Section 4.1.4 specifies that a server must clear
1863     * all buffers and reset the state exactly as if a RSET command had been
1864     * issued.
1865     *
1866     * RFC 2034: the text part of all 2xx, 4xx, and 5xx SMTP responses other
1867     * than the initial greeting and any response to HELO or EHLO are
1868     * prefaced with a status code as defined in RFC 3463.
1869     */
1870    if (argc < 2) {
1871	state->error_mask |= MAIL_ERROR_PROTOCOL;
1872	smtpd_chat_reply(state, "501 Syntax: EHLO hostname");
1873	return (-1);
1874    }
1875    if (argc > 2)
1876	collapse_args(argc - 1, argv + 1);
1877    if (SMTPD_STAND_ALONE(state) == 0
1878	&& var_smtpd_delay_reject == 0
1879	&& (err = smtpd_check_helo(state, argv[1].strval)) != 0) {
1880	smtpd_chat_reply(state, "%s", err);
1881	return (-1);
1882    }
1883
1884    /*
1885     * XXX Sendmail compatibility: if a Milter 5xx rejects CONNECT, EHLO, or
1886     * HELO, reply with ENHANCEDSTATUSCODES except in case of immediate
1887     * disconnect. The reply persists so it will apply to MAIL FROM and to
1888     * other commands such as AUTH, STARTTLS, and VRFY.
1889     */
1890    err = 0;
1891    if (state->milters != 0
1892	&& (state->saved_flags & MILTER_SKIP_FLAGS) == 0
1893     && (err = milter_helo_event(state->milters, argv[1].strval, 1)) != 0) {
1894	/* Log reject etc. with correct HELO information. */
1895	PUSH_STRING(saved_helo, state->helo_name, argv[1].strval);
1896	err = check_milter_reply(state, err);
1897	POP_STRING(saved_helo, state->helo_name);
1898	if (err != 0 && strncmp(err, "421", 3) == 0) {
1899	    smtpd_chat_reply(state, "%s", err);
1900	    return (-1);
1901	}
1902    }
1903    if (state->helo_name != 0)
1904	helo_reset(state);
1905    chat_reset(state, var_smtpd_hist_thrsh);
1906    mail_reset(state);
1907    rcpt_reset(state);
1908    state->helo_name = mystrdup(printable(argv[1].strval, '?'));
1909    neuter(state->helo_name, NEUTER_CHARACTERS, '?');
1910
1911    /*
1912     * XXX reject_unauth_pipelining depends on the following. If the user
1913     * sends EHLO then we announce PIPELINING and we can't accuse them of
1914     * using pipelining in places where it is allowed.
1915     *
1916     * XXX The reject_unauth_pipelining test needs to change and also account
1917     * for mechanisms that disable PIPELINING selectively.
1918     */
1919    if (strcasecmp(state->protocol, MAIL_PROTO_ESMTP) != 0) {
1920	myfree(state->protocol);
1921	state->protocol = mystrdup(MAIL_PROTO_ESMTP);
1922    }
1923
1924    /*
1925     * Build the EHLO response, producing no output until we know what to
1926     * send - this simplifies exception handling. The CRLF record boundaries
1927     * don't exist at this level in the code, so we represent multi-line
1928     * output as an array of single-line responses.
1929     */
1930#define EHLO_APPEND(state, cmd) \
1931    do { \
1932	vstring_sprintf((state)->ehlo_buf, (cmd)); \
1933	argv_add((state)->ehlo_argv, STR((state)->ehlo_buf), (char *) 0); \
1934    } while (0)
1935
1936#define EHLO_APPEND1(state, cmd, arg) \
1937    do { \
1938	vstring_sprintf((state)->ehlo_buf, (cmd), (arg)); \
1939	argv_add((state)->ehlo_argv, STR((state)->ehlo_buf), (char *) 0); \
1940    } while (0)
1941
1942    /*
1943     * XXX Sendmail compatibility: if a Milter 5XX rejects CONNECT, EHLO, or
1944     * HELO, reply with ENHANCEDSTATUSCODES only. The reply persists so it
1945     * will apply to MAIL FROM, but we currently don't have a proper
1946     * mechanism to apply Milter rejects to AUTH, STARTTLS, VRFY, and other
1947     * commands while still allowing HELO/EHLO.
1948     */
1949    discard_mask = state->ehlo_discard_mask;
1950    if (err != 0 && err[0] == '5')
1951	discard_mask |= ~EHLO_MASK_ENHANCEDSTATUSCODES;
1952    if ((discard_mask & EHLO_MASK_ENHANCEDSTATUSCODES) == 0)
1953	if (discard_mask && !(discard_mask & EHLO_MASK_SILENT))
1954	    msg_info("discarding EHLO keywords: %s", str_ehlo_mask(discard_mask));
1955    if (ehlo_discard_maps && ehlo_discard_maps->error) {
1956	msg_warn("don't know what EHLO features to announce to %s",
1957		 state->namaddr);
1958	vstream_longjmp(state->client, SMTP_ERR_DATA);
1959    }
1960
1961    /*
1962     * These may still exist after a prior exception.
1963     */
1964    if (state->ehlo_argv == 0) {
1965	state->ehlo_argv = argv_alloc(10);
1966	state->ehlo_buf = vstring_alloc(10);
1967    } else
1968	argv_truncate(state->ehlo_argv, 0);
1969
1970    EHLO_APPEND1(state, "%s", var_myhostname);
1971    if ((discard_mask & EHLO_MASK_PIPELINING) == 0)
1972	EHLO_APPEND(state, "PIPELINING");
1973    if ((discard_mask & EHLO_MASK_SIZE) == 0) {
1974	if (ENFORCING_SIZE_LIMIT(var_message_limit))
1975	    EHLO_APPEND1(state, "SIZE %lu",
1976			 (unsigned long) var_message_limit);	/* XXX */
1977	else
1978	    EHLO_APPEND(state, "SIZE");
1979    }
1980    if ((discard_mask & EHLO_MASK_VRFY) == 0)
1981	if (var_disable_vrfy_cmd == 0)
1982	    EHLO_APPEND(state, SMTPD_CMD_VRFY);
1983    if ((discard_mask & EHLO_MASK_ETRN) == 0)
1984	EHLO_APPEND(state, SMTPD_CMD_ETRN);
1985#ifdef USE_TLS
1986    if ((discard_mask & EHLO_MASK_STARTTLS) == 0)
1987	if (var_smtpd_use_tls && (!state->tls_context))
1988	    EHLO_APPEND(state, SMTPD_CMD_STARTTLS);
1989#endif
1990#ifdef USE_SASL_AUTH
1991#ifndef AUTH_CMD
1992#define AUTH_CMD	"AUTH"
1993#endif
1994    if ((discard_mask & EHLO_MASK_AUTH) == 0) {
1995	if (smtpd_sasl_is_active(state) && !sasl_client_exception(state)) {
1996	    EHLO_APPEND1(state, "AUTH %s", state->sasl_mechanism_list);
1997	    if (var_broken_auth_clients)
1998		EHLO_APPEND1(state, "AUTH=%s", state->sasl_mechanism_list);
1999	} else if (sasl_exceptions_networks && sasl_exceptions_networks->error)
2000	    cant_announce_feature(state, AUTH_CMD);
2001    }
2002#define XCLIENT_LOGIN_KLUDGE	" " XCLIENT_LOGIN
2003#else
2004#define XCLIENT_LOGIN_KLUDGE	""
2005#endif
2006    if ((discard_mask & EHLO_MASK_VERP) == 0) {
2007	if (namadr_list_match(verp_clients, state->name, state->addr))
2008	    EHLO_APPEND(state, VERP_CMD);
2009	else if (verp_clients && verp_clients->error)
2010	    cant_announce_feature(state, VERP_CMD);
2011    }
2012    /* XCLIENT must not override its own access control. */
2013    if ((discard_mask & EHLO_MASK_XCLIENT) == 0) {
2014	if (xclient_allowed)
2015	    EHLO_APPEND(state, XCLIENT_CMD
2016			" " XCLIENT_NAME " " XCLIENT_ADDR
2017			" " XCLIENT_PROTO " " XCLIENT_HELO
2018			" " XCLIENT_REVERSE_NAME " " XCLIENT_PORT
2019			XCLIENT_LOGIN_KLUDGE
2020			" " XCLIENT_DESTADDR
2021			" " XCLIENT_DESTPORT);
2022	else if (xclient_hosts && xclient_hosts->error)
2023	    cant_announce_feature(state, XCLIENT_CMD);
2024    }
2025    if ((discard_mask & EHLO_MASK_XFORWARD) == 0) {
2026	if (xforward_allowed)
2027	    EHLO_APPEND(state, XFORWARD_CMD
2028			" " XFORWARD_NAME " " XFORWARD_ADDR
2029			" " XFORWARD_PROTO " " XFORWARD_HELO
2030			" " XFORWARD_DOMAIN " " XFORWARD_PORT
2031			" " XFORWARD_IDENT);
2032	else if (xforward_hosts && xforward_hosts->error)
2033	    cant_announce_feature(state, XFORWARD_CMD);
2034    }
2035    if ((discard_mask & EHLO_MASK_ENHANCEDSTATUSCODES) == 0)
2036	EHLO_APPEND(state, "ENHANCEDSTATUSCODES");
2037    if ((discard_mask & EHLO_MASK_8BITMIME) == 0)
2038	EHLO_APPEND(state, "8BITMIME");
2039    if ((discard_mask & EHLO_MASK_DSN) == 0)
2040	EHLO_APPEND(state, "DSN");
2041    if (var_smtputf8_enable && (discard_mask & EHLO_MASK_SMTPUTF8) == 0)
2042	EHLO_APPEND(state, "SMTPUTF8");
2043    if ((discard_mask & EHLO_MASK_CHUNKING) == 0)
2044	EHLO_APPEND(state, "CHUNKING");
2045
2046    /*
2047     * Send the reply.
2048     */
2049    for (cpp = state->ehlo_argv->argv; *cpp; cpp++)
2050	smtpd_chat_reply(state, "250%c%s", cpp[1] ? '-' : ' ', *cpp);
2051
2052    /*
2053     * Clean up.
2054     */
2055    argv_free(state->ehlo_argv);
2056    state->ehlo_argv = 0;
2057    vstring_free(state->ehlo_buf);
2058    state->ehlo_buf = 0;
2059
2060    return (0);
2061}
2062
2063/* helo_reset - reset HELO/EHLO command stuff */
2064
2065static void helo_reset(SMTPD_STATE *state)
2066{
2067    if (state->helo_name) {
2068	myfree(state->helo_name);
2069	state->helo_name = 0;
2070	if (state->milters != 0)
2071	    milter_abort(state->milters);
2072    }
2073    if (state->ehlo_argv) {
2074	argv_free(state->ehlo_argv);
2075	state->ehlo_argv = 0;
2076    }
2077    if (state->ehlo_buf) {
2078	vstring_free(state->ehlo_buf);
2079	state->ehlo_buf = 0;
2080    }
2081}
2082
2083#ifdef USE_SASL_AUTH
2084
2085/* smtpd_sasl_auth_cmd_wrapper - smtpd_sasl_auth_cmd front-end */
2086
2087static int smtpd_sasl_auth_cmd_wrapper(SMTPD_STATE *state, int argc,
2088				               SMTPD_TOKEN *argv)
2089{
2090    int     rate;
2091
2092    if (SMTPD_STAND_ALONE(state) == 0
2093	&& !xclient_allowed
2094	&& anvil_clnt
2095	&& var_smtpd_cauth_limit > 0
2096	&& !namadr_list_match(hogger_list, state->name, state->addr)
2097	&& anvil_clnt_auth(anvil_clnt, state->service, state->anvil_range,
2098			   &rate) == ANVIL_STAT_OK
2099	&& rate > var_smtpd_cauth_limit) {
2100	state->error_mask |= MAIL_ERROR_POLICY;
2101	msg_warn("AUTH command rate limit exceeded: %d from %s for service %s",
2102		 rate, state->namaddr, state->service);
2103	smtpd_chat_reply(state,
2104			 "450 4.7.1 Error: too many AUTH commands from %s",
2105			 state->addr);
2106	return (-1);
2107    }
2108    return (smtpd_sasl_auth_cmd(state, argc, argv));
2109}
2110
2111#endif
2112
2113/* mail_open_stream - open mail queue file or IPC stream */
2114
2115static int mail_open_stream(SMTPD_STATE *state)
2116{
2117
2118    /*
2119     * Connect to the before-queue filter when one is configured. The MAIL
2120     * FROM and RCPT TO commands are forwarded as received (including DSN
2121     * attributes), with the exception that the before-filter smtpd process
2122     * handles all authentication, encryption, access control and relay
2123     * control, and that the before-filter smtpd process does not forward
2124     * blocked commands. If the after-filter smtp server does not support
2125     * some of Postfix's ESMTP features, then they must be turned off in the
2126     * before-filter smtpd process with the smtpd_discard_ehlo_keywords
2127     * feature.
2128     */
2129    if (state->proxy_mail) {
2130	if (smtpd_proxy_create(state, smtpd_proxy_opts, var_smtpd_proxy_filt,
2131			       var_smtpd_proxy_tmout, var_smtpd_proxy_ehlo,
2132			       state->proxy_mail) != 0) {
2133	    smtpd_chat_reply(state, "%s", STR(state->proxy->reply));
2134	    smtpd_proxy_free(state);
2135	    return (-1);
2136	}
2137    }
2138
2139    /*
2140     * If running from the master or from inetd, connect to the cleanup
2141     * service.
2142     *
2143     * XXX 2821: An SMTP server is not allowed to "clean up" mail except in the
2144     * case of original submissions.
2145     *
2146     * We implement this by distinguishing between mail that we are willing to
2147     * rewrite (the local rewrite context) and mail from elsewhere.
2148     */
2149    else if (SMTPD_STAND_ALONE(state) == 0) {
2150	int     cleanup_flags;
2151
2152	cleanup_flags = input_transp_cleanup(CLEANUP_FLAG_MASK_EXTERNAL,
2153					     smtpd_input_transp_mask)
2154	    | CLEANUP_FLAG_SMTP_REPLY;
2155	if (state->flags & SMTPD_FLAG_SMTPUTF8)
2156	    cleanup_flags |= CLEANUP_FLAG_SMTPUTF8;
2157	else
2158	    cleanup_flags |= smtputf8_autodetect(MAIL_SRC_MASK_SMTPD);
2159	state->dest = mail_stream_service(MAIL_CLASS_PUBLIC,
2160					  var_cleanup_service);
2161	if (state->dest == 0
2162	    || attr_print(state->dest->stream, ATTR_FLAG_NONE,
2163			  SEND_ATTR_INT(MAIL_ATTR_FLAGS, cleanup_flags),
2164			  ATTR_TYPE_END) != 0)
2165	    msg_fatal("unable to connect to the %s %s service",
2166		      MAIL_CLASS_PUBLIC, var_cleanup_service);
2167    }
2168
2169    /*
2170     * Otherwise, pipe the message through the privileged postdrop helper.
2171     * XXX Make postdrop a manifest constant.
2172     */
2173    else {
2174	char   *postdrop_command;
2175
2176	postdrop_command = concatenate(var_command_dir, "/postdrop",
2177			      msg_verbose ? " -v" : (char *) 0, (char *) 0);
2178	state->dest = mail_stream_command(postdrop_command);
2179	if (state->dest == 0)
2180	    msg_fatal("unable to execute %s", postdrop_command);
2181	myfree(postdrop_command);
2182    }
2183
2184    /*
2185     * Record the time of arrival, the SASL-related stuff if applicable, the
2186     * sender envelope address, some session information, and some additional
2187     * attributes.
2188     *
2189     * XXX Send Milter information first, because this will hang when cleanup
2190     * goes into "throw away" mode. Also, cleanup needs to know early on
2191     * whether or not it has to do its own SMTP event emulation.
2192     *
2193     * XXX At this point we send only dummy information to keep the cleanup
2194     * server from using its non_smtpd_milters settings. We have to send
2195     * up-to-date Milter information after DATA so that the cleanup server
2196     * knows the actual Milter state.
2197     */
2198    if (state->dest) {
2199	state->cleanup = state->dest->stream;
2200	state->queue_id = mystrdup(state->dest->id);
2201	if (SMTPD_STAND_ALONE(state) == 0) {
2202	    if (state->milters != 0
2203		&& (state->saved_flags & MILTER_SKIP_FLAGS) == 0)
2204		/* Send place-holder smtpd_milters list. */
2205		(void) milter_dummy(state->milters, state->cleanup);
2206	    rec_fprintf(state->cleanup, REC_TYPE_TIME, REC_TYPE_TIME_FORMAT,
2207			REC_TYPE_TIME_ARG(state->arrival_time));
2208	    if (*var_filter_xport)
2209		rec_fprintf(state->cleanup, REC_TYPE_FILT, "%s", var_filter_xport);
2210	    if (FORWARD_IDENT(state))
2211		rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2212			    MAIL_ATTR_LOG_IDENT, FORWARD_IDENT(state));
2213	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2214			MAIL_ATTR_RWR_CONTEXT, FORWARD_DOMAIN(state));
2215#ifdef USE_SASL_AUTH
2216	    /* Make external authentication painless (e.g., XCLIENT). */
2217	    if (state->sasl_method)
2218		rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2219			    MAIL_ATTR_SASL_METHOD, state->sasl_method);
2220	    if (state->sasl_username)
2221		rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2222			    MAIL_ATTR_SASL_USERNAME, state->sasl_username);
2223	    if (state->sasl_sender)
2224		rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2225			    MAIL_ATTR_SASL_SENDER, state->sasl_sender);
2226#endif
2227
2228	    /*
2229	     * Record DSN related information that was received with the MAIL
2230	     * FROM command.
2231	     *
2232	     * RFC 3461 Section 5.2.1. If no ENVID parameter was included in the
2233	     * MAIL command when the message was received, the ENVID
2234	     * parameter MUST NOT be supplied when the message is relayed.
2235	     * Ditto for the RET parameter.
2236	     *
2237	     * In other words, we can't simply make up our default ENVID or RET
2238	     * values. We have to remember whether the client sent any.
2239	     *
2240	     * We store DSN information as named attribute records so that we
2241	     * don't have to pollute the queue file with records that are
2242	     * incompatible with past Postfix versions. Preferably, people
2243	     * should be able to back out from an upgrade without losing
2244	     * mail.
2245	     */
2246	    if (state->dsn_envid)
2247		rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2248			    MAIL_ATTR_DSN_ENVID, state->dsn_envid);
2249	    if (state->dsn_ret)
2250		rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%d",
2251			    MAIL_ATTR_DSN_RET, state->dsn_ret);
2252	}
2253	rec_fputs(state->cleanup, REC_TYPE_FROM, state->sender);
2254	if (state->encoding != 0)
2255	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2256			MAIL_ATTR_ENCODING, state->encoding);
2257
2258	/*
2259	 * Store client attributes.
2260	 */
2261	if (SMTPD_STAND_ALONE(state) == 0) {
2262
2263	    /*
2264	     * Attributes for logging, also used for XFORWARD.
2265	     *
2266	     * We store all client attributes, including ones with unknown
2267	     * values. Otherwise, an unknown client hostname would be treated
2268	     * as a non-existent hostname (i.e. local submission).
2269	     */
2270	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2271			MAIL_ATTR_LOG_CLIENT_NAME, FORWARD_NAME(state));
2272	    /* XXX Note: state->rfc_addr, not state->addr. */
2273	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2274			MAIL_ATTR_LOG_CLIENT_ADDR, FORWARD_ADDR(state));
2275	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2276			MAIL_ATTR_LOG_CLIENT_PORT, FORWARD_PORT(state));
2277	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2278			MAIL_ATTR_LOG_ORIGIN, FORWARD_NAMADDR(state));
2279	    if (FORWARD_HELO(state))
2280		rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2281			    MAIL_ATTR_LOG_HELO_NAME, FORWARD_HELO(state));
2282	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2283			MAIL_ATTR_LOG_PROTO_NAME, FORWARD_PROTO(state));
2284
2285	    /*
2286	     * Attributes with actual client information. These are used by
2287	     * the smtpd Milter client for policy decisions. Mail that is
2288	     * requeued with "postsuper -r" is not subject to processing by
2289	     * the cleanup Milter client, because a) it has already been
2290	     * filtered, and b) we don't have sufficient information to
2291	     * reproduce the exact same SMTP events and Sendmail macros that
2292	     * the smtpd Milter client received when the message originally
2293	     * arrived in Postfix.
2294	     */
2295	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2296			MAIL_ATTR_ACT_CLIENT_NAME, state->name);
2297	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2298		    MAIL_ATTR_ACT_REVERSE_CLIENT_NAME, state->reverse_name);
2299	    /* XXX Note: state->addr, not state->rfc_addr. */
2300	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2301			MAIL_ATTR_ACT_CLIENT_ADDR, state->addr);
2302	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2303			MAIL_ATTR_ACT_CLIENT_PORT, state->port);
2304	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2305			MAIL_ATTR_ACT_SERVER_ADDR, state->dest_addr);
2306	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2307			MAIL_ATTR_ACT_SERVER_PORT, state->dest_port);
2308	    if (state->helo_name)
2309		rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2310			    MAIL_ATTR_ACT_HELO_NAME, state->helo_name);
2311	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s",
2312			MAIL_ATTR_ACT_PROTO_NAME, state->protocol);
2313	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%u",
2314			MAIL_ATTR_ACT_CLIENT_AF, state->addr_family);
2315
2316	    /*
2317	     * Don't send client certificate down the pipeline unless it is
2318	     * a) verified or b) just a fingerprint.
2319	     */
2320	}
2321	if (state->verp_delims)
2322	    rec_fputs(state->cleanup, REC_TYPE_VERP, state->verp_delims);
2323    }
2324
2325    /*
2326     * Log the queue ID with the message origin.
2327     */
2328#define PRINT_OR_NULL(cond, str) \
2329	    ((cond) ? (str) : "")
2330#define PRINT2_OR_NULL(cond, name, value) \
2331	    PRINT_OR_NULL((cond), (name)), PRINT_OR_NULL((cond), (value))
2332
2333    msg_info("%s: client=%s%s%s%s%s%s%s%s%s%s%s",
2334	     (state->queue_id ? state->queue_id : "NOQUEUE"),
2335	     state->namaddr,
2336#ifdef USE_SASL_AUTH
2337	     PRINT2_OR_NULL(state->sasl_method,
2338			    ", sasl_method=", state->sasl_method),
2339	     PRINT2_OR_NULL(state->sasl_username,
2340			    ", sasl_username=", state->sasl_username),
2341	     PRINT2_OR_NULL(state->sasl_sender,
2342			    ", sasl_sender=", state->sasl_sender),
2343#else
2344	     "", "", "", "", "", "",
2345#endif
2346    /* Insert transaction TLS status here. */
2347	     PRINT2_OR_NULL(HAVE_FORWARDED_IDENT(state),
2348			    ", orig_queue_id=", FORWARD_IDENT(state)),
2349	     PRINT2_OR_NULL(HAVE_FORWARDED_CLIENT_ATTR(state),
2350			    ", orig_client=", FORWARD_NAMADDR(state)));
2351    return (0);
2352}
2353
2354/* extract_addr - extract address from rubble */
2355
2356static int extract_addr(SMTPD_STATE *state, SMTPD_TOKEN *arg,
2357			        int allow_empty_addr, int strict_rfc821,
2358			        int smtputf8)
2359{
2360    const char *myname = "extract_addr";
2361    TOK822 *tree;
2362    TOK822 *tp;
2363    TOK822 *addr = 0;
2364    int     naddr;
2365    int     non_addr;
2366    int     err = 0;
2367    char   *junk = 0;
2368    char   *text;
2369    char   *colon;
2370
2371    /*
2372     * Special case.
2373     */
2374#define PERMIT_EMPTY_ADDR	1
2375#define REJECT_EMPTY_ADDR	0
2376
2377    /*
2378     * Some mailers send RFC822-style address forms (with comments and such)
2379     * in SMTP envelopes. We cannot blame users for this: the blame is with
2380     * programmers violating the RFC, and with sendmail for being permissive.
2381     *
2382     * XXX The SMTP command tokenizer must leave the address in externalized
2383     * (quoted) form, so that the address parser can correctly extract the
2384     * address from surrounding junk.
2385     *
2386     * XXX We have only one address parser, written according to the rules of
2387     * RFC 822. That standard differs subtly from RFC 821.
2388     */
2389    if (msg_verbose)
2390	msg_info("%s: input: %s", myname, STR(arg->vstrval));
2391    if (STR(arg->vstrval)[0] == '<'
2392	&& STR(arg->vstrval)[LEN(arg->vstrval) - 1] == '>') {
2393	junk = text = mystrndup(STR(arg->vstrval) + 1, LEN(arg->vstrval) - 2);
2394    } else
2395	text = STR(arg->vstrval);
2396
2397    /*
2398     * Truncate deprecated route address form.
2399     */
2400    if (*text == '@' && (colon = strchr(text, ':')) != 0)
2401	text = colon + 1;
2402    tree = tok822_parse(text);
2403
2404    if (junk)
2405	myfree(junk);
2406
2407    /*
2408     * Find trouble.
2409     */
2410    for (naddr = non_addr = 0, tp = tree; tp != 0; tp = tp->next) {
2411	if (tp->type == TOK822_ADDR) {
2412	    addr = tp;
2413	    naddr += 1;				/* count address forms */
2414	} else if (tp->type == '<' || tp->type == '>') {
2415	     /* void */ ;			/* ignore brackets */
2416	} else {
2417	    non_addr += 1;			/* count non-address forms */
2418	}
2419    }
2420
2421    /*
2422     * Report trouble. XXX Should log a warning only if we are going to
2423     * sleep+reject so that attackers can't flood our logfiles.
2424     *
2425     * XXX Unfortunately, the sleep-before-reject feature had to be abandoned
2426     * (at least for small error counts) because servers were DOS-ing
2427     * themselves when flooded by backscatter traffic.
2428     */
2429    if (naddr > 1
2430	|| (strict_rfc821 && (non_addr || *STR(arg->vstrval) != '<'))) {
2431	msg_warn("Illegal address syntax from %s in %s command: %s",
2432		 state->namaddr, state->where,
2433		 printable(STR(arg->vstrval), '?'));
2434	err = 1;
2435    }
2436
2437    /*
2438     * Don't overwrite the input with the extracted address. We need the
2439     * original (external) form in case the client does not send ORCPT
2440     * information; and error messages are more accurate if we log the
2441     * unmodified form. We need the internal form for all other purposes.
2442     */
2443    if (addr)
2444	tok822_internalize(state->addr_buf, addr->head, TOK822_STR_DEFL);
2445    else
2446	vstring_strcpy(state->addr_buf, "");
2447
2448    /*
2449     * Report trouble. XXX Should log a warning only if we are going to
2450     * sleep+reject so that attackers can't flood our logfiles. Log the
2451     * original address.
2452     */
2453    if (err == 0)
2454	if ((STR(state->addr_buf)[0] == 0 && !allow_empty_addr)
2455	    || (strict_rfc821 && STR(state->addr_buf)[0] == '@')
2456	    || (SMTPD_STAND_ALONE(state) == 0
2457	     && smtpd_check_addr(strcmp(state->where, SMTPD_CMD_MAIL) == 0 ?
2458				 state->recipient : state->sender,
2459				 STR(state->addr_buf), smtputf8) != 0)) {
2460	    msg_warn("Illegal address syntax from %s in %s command: %s",
2461		     state->namaddr, state->where,
2462		     printable(STR(arg->vstrval), '?'));
2463	    err = 1;
2464	}
2465
2466    /*
2467     * Cleanup.
2468     */
2469    tok822_free_tree(tree);
2470    if (msg_verbose)
2471	msg_info("%s: in: %s, result: %s",
2472		 myname, STR(arg->vstrval), STR(state->addr_buf));
2473    return (err);
2474}
2475
2476/* milter_argv - impedance adapter */
2477
2478static const char **milter_argv(SMTPD_STATE *state, int argc, SMTPD_TOKEN *argv)
2479{
2480    int     n;
2481    ssize_t len = argc + 1;
2482
2483    if (state->milter_argc < len) {
2484	if (state->milter_argc > 0)
2485	    state->milter_argv = (const char **)
2486		myrealloc((void *) state->milter_argv,
2487			  sizeof(const char *) * len);
2488	else
2489	    state->milter_argv = (const char **)
2490		mymalloc(sizeof(const char *) * len);
2491	state->milter_argc = len;
2492    }
2493    for (n = 0; n < argc; n++)
2494	state->milter_argv[n] = argv[n].strval;
2495    state->milter_argv[n] = 0;
2496    return (state->milter_argv);
2497}
2498
2499/* mail_cmd - process MAIL command */
2500
2501static int mail_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *argv)
2502{
2503    const char *err;
2504    int     narg;
2505    char   *arg;
2506    char   *verp_delims = 0;
2507    int     rate;
2508    int     dsn_envid = 0;
2509
2510    state->flags &= ~SMTPD_FLAG_SMTPUTF8;
2511    state->encoding = 0;
2512    state->dsn_ret = 0;
2513
2514    /*
2515     * Sanity checks.
2516     *
2517     * XXX 2821 pedantism: Section 4.1.2 says that SMTP servers that receive a
2518     * command in which invalid character codes have been employed, and for
2519     * which there are no other reasons for rejection, MUST reject that
2520     * command with a 501 response. Postfix attempts to be 8-bit clean.
2521     */
2522    if (var_helo_required && state->helo_name == 0) {
2523	state->error_mask |= MAIL_ERROR_POLICY;
2524	smtpd_chat_reply(state, "503 5.5.1 Error: send HELO/EHLO first");
2525	return (-1);
2526    }
2527    if (SMTPD_IN_MAIL_TRANSACTION(state)) {
2528	state->error_mask |= MAIL_ERROR_PROTOCOL;
2529	smtpd_chat_reply(state, "503 5.5.1 Error: nested MAIL command");
2530	return (-1);
2531    }
2532    /* Don't accept MAIL after out-of-order BDAT. */
2533    if (SMTPD_PROCESSING_BDAT(state)) {
2534	state->error_mask |= MAIL_ERROR_PROTOCOL;
2535	smtpd_chat_reply(state, "503 5.5.1 Error: MAIL after BDAT");
2536	return (-1);
2537    }
2538    if (argc < 3
2539	|| strcasecmp(argv[1].strval, "from:") != 0) {
2540	state->error_mask |= MAIL_ERROR_PROTOCOL;
2541	smtpd_chat_reply(state, "501 5.5.4 Syntax: MAIL FROM:<address>");
2542	return (-1);
2543    }
2544
2545    /*
2546     * XXX The client event count/rate control must be consistent in its use
2547     * of client address information in connect and disconnect events. For
2548     * now we exclude xclient authorized hosts from event count/rate control.
2549     */
2550    if (SMTPD_STAND_ALONE(state) == 0
2551	&& !xclient_allowed
2552	&& anvil_clnt
2553	&& var_smtpd_cmail_limit > 0
2554	&& !namadr_list_match(hogger_list, state->name, state->addr)
2555	&& anvil_clnt_mail(anvil_clnt, state->service, state->anvil_range,
2556			   &rate) == ANVIL_STAT_OK
2557	&& rate > var_smtpd_cmail_limit) {
2558	state->error_mask |= MAIL_ERROR_POLICY;
2559	smtpd_chat_reply(state, "450 4.7.1 Error: too much mail from %s",
2560			 state->addr);
2561	msg_warn("Message delivery request rate limit exceeded: %d from %s for service %s",
2562		 rate, state->namaddr, state->service);
2563	return (-1);
2564    }
2565    if (argv[2].tokval == SMTPD_TOK_ERROR) {
2566	state->error_mask |= MAIL_ERROR_PROTOCOL;
2567	smtpd_chat_reply(state, "501 5.1.7 Bad sender address syntax");
2568	return (-1);
2569    }
2570
2571    /*
2572     * XXX The sender address comes first, but the optional SMTPUTF8
2573     * parameter determines what address syntax is permitted. We must process
2574     * this parameter early.
2575     */
2576    if (var_smtputf8_enable
2577	&& (state->ehlo_discard_mask & EHLO_MASK_SMTPUTF8) == 0) {
2578	for (narg = 3; narg < argc; narg++) {
2579	    arg = argv[narg].strval;
2580	    if (strcasecmp(arg, "SMTPUTF8") == 0) {	/* RFC 6531 */
2581		/* Fix 20161206: allow UTF8 in smtpd_sender_restrictions. */
2582		state->flags |= SMTPD_FLAG_SMTPUTF8;
2583		break;
2584	    }
2585	}
2586    }
2587    if (extract_addr(state, argv + 2, PERMIT_EMPTY_ADDR,
2588		     var_strict_rfc821_env,
2589		     state->flags & SMTPD_FLAG_SMTPUTF8) != 0) {
2590	state->error_mask |= MAIL_ERROR_PROTOCOL;
2591	smtpd_chat_reply(state, "501 5.1.7 Bad sender address syntax");
2592	return (-1);
2593    }
2594    for (narg = 3; narg < argc; narg++) {
2595	arg = argv[narg].strval;
2596	if (strcasecmp(arg, "BODY=8BITMIME") == 0) {	/* RFC 1652 */
2597	    state->encoding = MAIL_ATTR_ENC_8BIT;
2598	} else if (strcasecmp(arg, "BODY=7BIT") == 0) {	/* RFC 1652 */
2599	    state->encoding = MAIL_ATTR_ENC_7BIT;
2600	} else if (strncasecmp(arg, "SIZE=", 5) == 0) {	/* RFC 1870 */
2601	    /* Reject non-numeric size. */
2602	    if (!alldig(arg + 5)) {
2603		state->error_mask |= MAIL_ERROR_PROTOCOL;
2604		smtpd_chat_reply(state, "501 5.5.4 Bad message size syntax");
2605		return (-1);
2606	    }
2607	    /* Reject size overflow. */
2608	    if ((state->msg_size = off_cvt_string(arg + 5)) < 0) {
2609		state->error_mask |= MAIL_ERROR_POLICY;
2610		smtpd_chat_reply(state, "552 5.3.4 Message size exceeds file system imposed limit");
2611		return (-1);
2612	    }
2613	} else if (var_smtputf8_enable
2614		   && (state->ehlo_discard_mask & EHLO_MASK_SMTPUTF8) == 0
2615		   && strcasecmp(arg, "SMTPUTF8") == 0) {	/* RFC 6531 */
2616	     /* Already processed early. */ ;
2617#ifdef USE_SASL_AUTH
2618	} else if (strncasecmp(arg, "AUTH=", 5) == 0) {
2619	    if ((err = smtpd_sasl_mail_opt(state, arg + 5)) != 0) {
2620		smtpd_chat_reply(state, "%s", err);
2621		return (-1);
2622	    }
2623#endif
2624	} else if (namadr_list_match(verp_clients, state->name, state->addr)
2625		   && strncasecmp(arg, VERP_CMD, VERP_CMD_LEN) == 0
2626		   && (arg[VERP_CMD_LEN] == '=' || arg[VERP_CMD_LEN] == 0)) {
2627	    if (arg[VERP_CMD_LEN] == 0) {
2628		verp_delims = var_verp_delims;
2629	    } else {
2630		verp_delims = arg + VERP_CMD_LEN + 1;
2631		if (verp_delims_verify(verp_delims) != 0) {
2632		    state->error_mask |= MAIL_ERROR_PROTOCOL;
2633		    smtpd_chat_reply(state,
2634			 "501 5.5.4 Error: %s needs two characters from %s",
2635				     VERP_CMD, var_verp_filter);
2636		    return (-1);
2637		}
2638	    }
2639	} else if (strncasecmp(arg, "RET=", 4) == 0) {	/* RFC 3461 */
2640	    /* Sanitized on input. */
2641	    if (state->ehlo_discard_mask & EHLO_MASK_DSN) {
2642		state->error_mask |= MAIL_ERROR_PROTOCOL;
2643		smtpd_chat_reply(state, "501 5.7.1 DSN support is disabled");
2644		return (-1);
2645	    }
2646	    if (state->dsn_ret
2647		|| (state->dsn_ret = dsn_ret_code(arg + 4)) == 0) {
2648		state->error_mask |= MAIL_ERROR_PROTOCOL;
2649		smtpd_chat_reply(state,
2650				 "501 5.5.4 Bad RET parameter syntax");
2651		return (-1);
2652	    }
2653	} else if (strncasecmp(arg, "ENVID=", 6) == 0) {	/* RFC 3461 */
2654	    /* Sanitized by bounce server. */
2655	    if (state->ehlo_discard_mask & EHLO_MASK_DSN) {
2656		state->error_mask |= MAIL_ERROR_PROTOCOL;
2657		smtpd_chat_reply(state, "501 5.7.1 DSN support is disabled");
2658		return (-1);
2659	    }
2660	    if (dsn_envid
2661		|| xtext_unquote(state->dsn_buf, arg + 6) == 0
2662		|| !allprint(STR(state->dsn_buf))) {
2663		state->error_mask |= MAIL_ERROR_PROTOCOL;
2664		smtpd_chat_reply(state, "501 5.5.4 Bad ENVID parameter syntax");
2665		return (-1);
2666	    }
2667	    dsn_envid = 1;
2668	} else {
2669	    state->error_mask |= MAIL_ERROR_PROTOCOL;
2670	    smtpd_chat_reply(state, "555 5.5.4 Unsupported option: %s", arg);
2671	    return (-1);
2672	}
2673    }
2674    /* Fix 20161205: show the envelope sender in reject logging. */
2675    PUSH_STRING(saved_sender, state->sender, STR(state->addr_buf));
2676    err = smtpd_check_size(state, state->msg_size);
2677    POP_STRING(saved_sender, state->sender);
2678    if (err != 0) {
2679	smtpd_chat_reply(state, "%s", err);
2680	return (-1);
2681    }
2682    if (verp_delims && STR(state->addr_buf)[0] == 0) {
2683	smtpd_chat_reply(state, "503 5.5.4 Error: %s requires non-null sender",
2684			 VERP_CMD);
2685	return (-1);
2686    }
2687    if (SMTPD_STAND_ALONE(state) == 0) {
2688	const char *verify_sender;
2689
2690	/*
2691	 * XXX Don't reject the address when we're probed with our own
2692	 * address verification sender address. Otherwise, some timeout or
2693	 * some UCE block may result in mutual negative caching, making it
2694	 * painful to get the mail through. Unfortunately we still have to
2695	 * send the address to the Milters otherwise they may bail out with a
2696	 * "missing recipient" protocol error.
2697	 */
2698	verify_sender = valid_verify_sender_addr(STR(state->addr_buf));
2699	if (verify_sender != 0)
2700	    vstring_strcpy(state->addr_buf, verify_sender);
2701    }
2702    if (SMTPD_STAND_ALONE(state) == 0
2703	&& var_smtpd_delay_reject == 0
2704	&& (err = smtpd_check_mail(state, STR(state->addr_buf))) != 0) {
2705	/* XXX Reset access map side effects. */
2706	mail_reset(state);
2707	smtpd_chat_reply(state, "%s", err);
2708	return (-1);
2709    }
2710    if (state->milters != 0
2711	&& (state->saved_flags & MILTER_SKIP_FLAGS) == 0) {
2712	state->flags |= SMTPD_FLAG_NEED_MILTER_ABORT;
2713	PUSH_STRING(saved_sender, state->sender, STR(state->addr_buf));
2714	err = milter_mail_event(state->milters,
2715				milter_argv(state, argc - 2, argv + 2));
2716	if (err != 0) {
2717	    /* Log reject etc. with correct sender information. */
2718	    err = check_milter_reply(state, err);
2719	}
2720	POP_STRING(saved_sender, state->sender);
2721	if (err != 0) {
2722	    /* XXX Reset access map side effects. */
2723	    mail_reset(state);
2724	    smtpd_chat_reply(state, "%s", err);
2725	    return (-1);
2726	}
2727    }
2728    if (SMTPD_STAND_ALONE(state) == 0) {
2729	err = smtpd_check_rewrite(state);
2730	if (err != 0) {
2731	    /* XXX Reset access map side effects. */
2732	    mail_reset(state);
2733	    smtpd_chat_reply(state, "%s", err);
2734	    return (-1);
2735	}
2736    }
2737
2738    /*
2739     * Historically, Postfix does not forbid 8-bit envelope localparts.
2740     * Changing this would be a compatibility break. That can't happen in the
2741     * foreseeable future.
2742     */
2743    if ((var_strict_smtputf8 || warn_compat_break_smtputf8_enable)
2744	&& (state->flags & SMTPD_FLAG_SMTPUTF8) == 0
2745	&& *STR(state->addr_buf) && !allascii(STR(state->addr_buf))) {
2746	if (var_strict_smtputf8) {
2747	    smtpd_chat_reply(state, "553 5.6.7 Must declare SMTPUTF8 to "
2748			     "send unicode address");
2749	    return (-1);
2750	}
2751
2752	/*
2753	 * Not: #ifndef NO_EAI. They must configure SMTPUTF8_ENABLE=no if a
2754	 * warning message is logged, so that they don't suddenly start to
2755	 * lose mail after Postfix is built with EAI support.
2756	 */
2757	if (warn_compat_break_smtputf8_enable)
2758	    msg_info("using backwards-compatible default setting "
2759		     VAR_SMTPUTF8_ENABLE "=no to accept non-ASCII sender "
2760		     "address \"%s\" from %s", STR(state->addr_buf),
2761		     state->namaddr);
2762    }
2763
2764    /*
2765     * Check the queue file space, if applicable. The optional before-filter
2766     * speed-adjust buffers use disk space. However, we don't know if they
2767     * compete for storage space with the after-filter queue, so we can't
2768     * simply bump up the free space requirement to 2.5 * message_size_limit.
2769     */
2770    if (!USE_SMTPD_PROXY(state)
2771	|| (smtpd_proxy_opts & SMTPD_PROXY_FLAG_SPEED_ADJUST)) {
2772	if (SMTPD_STAND_ALONE(state) == 0
2773	    && (err = smtpd_check_queue(state)) != 0) {
2774	    /* XXX Reset access map side effects. */
2775	    mail_reset(state);
2776	    smtpd_chat_reply(state, "%s", err);
2777	    return (-1);
2778	}
2779    }
2780
2781    /*
2782     * No more early returns. The mail transaction is in progress.
2783     */
2784    GETTIMEOFDAY(&state->arrival_time);
2785    state->sender = mystrdup(STR(state->addr_buf));
2786    vstring_sprintf(state->instance, "%x.%lx.%lx.%x",
2787		    var_pid, (unsigned long) state->arrival_time.tv_sec,
2788	       (unsigned long) state->arrival_time.tv_usec, state->seqno++);
2789    if (verp_delims)
2790	state->verp_delims = mystrdup(verp_delims);
2791    if (dsn_envid)
2792	state->dsn_envid = mystrdup(STR(state->dsn_buf));
2793    if (USE_SMTPD_PROXY(state))
2794	state->proxy_mail = mystrdup(STR(state->buffer));
2795    if (var_smtpd_delay_open == 0 && mail_open_stream(state) < 0) {
2796	/* XXX Reset access map side effects. */
2797	mail_reset(state);
2798	return (-1);
2799    }
2800    smtpd_chat_reply(state, "250 2.1.0 Ok");
2801    return (0);
2802}
2803
2804/* mail_reset - reset MAIL command stuff */
2805
2806static void mail_reset(SMTPD_STATE *state)
2807{
2808    state->msg_size = 0;
2809    state->act_size = 0;
2810    state->flags &= SMTPD_MASK_MAIL_KEEP;
2811
2812    /*
2813     * Unceremoniously close the pipe to the cleanup service. The cleanup
2814     * service will delete the queue file when it detects a premature
2815     * end-of-file condition on input.
2816     */
2817    if (state->cleanup != 0) {
2818	mail_stream_cleanup(state->dest);
2819	state->dest = 0;
2820	state->cleanup = 0;
2821    }
2822    state->err = 0;
2823    if (state->queue_id != 0) {
2824	myfree(state->queue_id);
2825	state->queue_id = 0;
2826    }
2827    if (state->sender) {
2828	myfree(state->sender);
2829	state->sender = 0;
2830    }
2831    /* WeiYu Wu: need to undo milter_mail_event() state change. */
2832    if (state->flags & SMTPD_FLAG_NEED_MILTER_ABORT) {
2833	milter_abort(state->milters);
2834	state->flags &= ~SMTPD_FLAG_NEED_MILTER_ABORT;
2835    }
2836    if (state->verp_delims) {
2837	myfree(state->verp_delims);
2838	state->verp_delims = 0;
2839    }
2840    if (state->proxy_mail) {
2841	myfree(state->proxy_mail);
2842	state->proxy_mail = 0;
2843    }
2844    if (state->saved_filter) {
2845	myfree(state->saved_filter);
2846	state->saved_filter = 0;
2847    }
2848    if (state->saved_redirect) {
2849	myfree(state->saved_redirect);
2850	state->saved_redirect = 0;
2851    }
2852    if (state->saved_bcc) {
2853	argv_free(state->saved_bcc);
2854	state->saved_bcc = 0;
2855    }
2856    state->saved_flags = 0;
2857#ifdef DELAY_ACTION
2858    state->saved_delay = 0;
2859#endif
2860#ifdef USE_SASL_AUTH
2861    if (state->sasl_sender)
2862	smtpd_sasl_mail_reset(state);
2863#endif
2864    state->discard = 0;
2865    VSTRING_RESET(state->instance);
2866    VSTRING_TERMINATE(state->instance);
2867
2868    if (state->proxy)
2869	smtpd_proxy_free(state);
2870    if (state->xforward.flags)
2871	smtpd_xforward_reset(state);
2872    if (state->prepend)
2873	state->prepend = argv_free(state->prepend);
2874    if (state->dsn_envid) {
2875	myfree(state->dsn_envid);
2876	state->dsn_envid = 0;
2877    }
2878    if (state->milter_argv) {
2879	myfree((void *) state->milter_argv);
2880	state->milter_argv = 0;
2881	state->milter_argc = 0;
2882    }
2883
2884    /*
2885     * BDAT.
2886     */
2887    state->bdat_state = SMTPD_BDAT_STAT_NONE;
2888    if (state->bdat_get_stream) {
2889	(void) vstream_fclose(state->bdat_get_stream);
2890	state->bdat_get_stream = 0;
2891    }
2892    if (state->bdat_get_buffer)
2893	VSTRING_RESET(state->bdat_get_buffer);
2894}
2895
2896/* rcpt_cmd - process RCPT TO command */
2897
2898static int rcpt_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *argv)
2899{
2900    SMTPD_PROXY *proxy;
2901    const char *err;
2902    int     narg;
2903    char   *arg;
2904    int     rate;
2905    const char *dsn_orcpt_addr = 0;
2906    ssize_t dsn_orcpt_addr_len = 0;
2907    const char *dsn_orcpt_type = 0;
2908    int     dsn_notify = 0;
2909    const char *coded_addr;
2910    const char *milter_err;
2911
2912    /*
2913     * Sanity checks.
2914     *
2915     * XXX 2821 pedantism: Section 4.1.2 says that SMTP servers that receive a
2916     * command in which invalid character codes have been employed, and for
2917     * which there are no other reasons for rejection, MUST reject that
2918     * command with a 501 response. So much for the principle of "be liberal
2919     * in what you accept, be strict in what you send".
2920     */
2921    if (!SMTPD_IN_MAIL_TRANSACTION(state)) {
2922	state->error_mask |= MAIL_ERROR_PROTOCOL;
2923	smtpd_chat_reply(state, "503 5.5.1 Error: need MAIL command");
2924	return (-1);
2925    }
2926    /* Don't accept RCPT after BDAT. */
2927    if (SMTPD_PROCESSING_BDAT(state)) {
2928	state->error_mask |= MAIL_ERROR_PROTOCOL;
2929	smtpd_chat_reply(state, "503 5.5.1 Error: RCPT after BDAT");
2930	return (-1);
2931    }
2932    if (argc < 3
2933	|| strcasecmp(argv[1].strval, "to:") != 0) {
2934	state->error_mask |= MAIL_ERROR_PROTOCOL;
2935	smtpd_chat_reply(state, "501 5.5.4 Syntax: RCPT TO:<address>");
2936	return (-1);
2937    }
2938
2939    /*
2940     * XXX The client event count/rate control must be consistent in its use
2941     * of client address information in connect and disconnect events. For
2942     * now we exclude xclient authorized hosts from event count/rate control.
2943     */
2944    if (SMTPD_STAND_ALONE(state) == 0
2945	&& !xclient_allowed
2946	&& anvil_clnt
2947	&& var_smtpd_crcpt_limit > 0
2948	&& !namadr_list_match(hogger_list, state->name, state->addr)
2949	&& anvil_clnt_rcpt(anvil_clnt, state->service, state->anvil_range,
2950			   &rate) == ANVIL_STAT_OK
2951	&& rate > var_smtpd_crcpt_limit) {
2952	state->error_mask |= MAIL_ERROR_POLICY;
2953	msg_warn("Recipient address rate limit exceeded: %d from %s for service %s",
2954		 rate, state->namaddr, state->service);
2955	smtpd_chat_reply(state, "450 4.7.1 Error: too many recipients from %s",
2956			 state->addr);
2957	return (-1);
2958    }
2959    if (argv[2].tokval == SMTPD_TOK_ERROR) {
2960	state->error_mask |= MAIL_ERROR_PROTOCOL;
2961	smtpd_chat_reply(state, "501 5.1.3 Bad recipient address syntax");
2962	return (-1);
2963    }
2964    if (extract_addr(state, argv + 2, REJECT_EMPTY_ADDR, var_strict_rfc821_env,
2965		     state->flags & SMTPD_FLAG_SMTPUTF8) != 0) {
2966	state->error_mask |= MAIL_ERROR_PROTOCOL;
2967	smtpd_chat_reply(state, "501 5.1.3 Bad recipient address syntax");
2968	return (-1);
2969    }
2970    for (narg = 3; narg < argc; narg++) {
2971	arg = argv[narg].strval;
2972	if (strncasecmp(arg, "NOTIFY=", 7) == 0) {	/* RFC 3461 */
2973	    /* Sanitized on input. */
2974	    if (state->ehlo_discard_mask & EHLO_MASK_DSN) {
2975		state->error_mask |= MAIL_ERROR_PROTOCOL;
2976		smtpd_chat_reply(state, "501 5.7.1 DSN support is disabled");
2977		return (-1);
2978	    }
2979	    if (dsn_notify || (dsn_notify = dsn_notify_mask(arg + 7)) == 0) {
2980		state->error_mask |= MAIL_ERROR_PROTOCOL;
2981		smtpd_chat_reply(state,
2982			    "501 5.5.4 Error: Bad NOTIFY parameter syntax");
2983		return (-1);
2984	    }
2985	} else if (strncasecmp(arg, "ORCPT=", 6) == 0) {	/* RFC 3461 */
2986	    /* Sanitized by bounce server. */
2987	    if (state->ehlo_discard_mask & EHLO_MASK_DSN) {
2988		state->error_mask |= MAIL_ERROR_PROTOCOL;
2989		smtpd_chat_reply(state, "501 5.7.1 DSN support is disabled");
2990		return (-1);
2991	    }
2992	    vstring_strcpy(state->dsn_orcpt_buf, arg + 6);
2993	    if (dsn_orcpt_addr
2994	     || (coded_addr = split_at(STR(state->dsn_orcpt_buf), ';')) == 0
2995		|| *(dsn_orcpt_type = STR(state->dsn_orcpt_buf)) == 0
2996		|| (strcasecmp(dsn_orcpt_type, "utf-8") == 0 ?
2997		    uxtext_unquote(state->dsn_buf, coded_addr) == 0 :
2998		    xtext_unquote(state->dsn_buf, coded_addr) == 0)) {
2999		state->error_mask |= MAIL_ERROR_PROTOCOL;
3000		smtpd_chat_reply(state,
3001			     "501 5.5.4 Error: Bad ORCPT parameter syntax");
3002		return (-1);
3003	    }
3004	    dsn_orcpt_addr = STR(state->dsn_buf);
3005	    dsn_orcpt_addr_len = LEN(state->dsn_buf);
3006	} else {
3007	    state->error_mask |= MAIL_ERROR_PROTOCOL;
3008	    smtpd_chat_reply(state, "555 5.5.4 Unsupported option: %s", arg);
3009	    return (-1);
3010	}
3011    }
3012    if (var_smtpd_rcpt_limit && state->rcpt_count >= var_smtpd_rcpt_limit) {
3013	smtpd_chat_reply(state, "452 4.5.3 Error: too many recipients");
3014	if (state->rcpt_overshoot++ < var_smtpd_rcpt_overlim)
3015	    return (0);
3016	state->error_mask |= MAIL_ERROR_POLICY;
3017	return (-1);
3018    }
3019
3020    /*
3021     * Historically, Postfix does not forbid 8-bit envelope localparts.
3022     * Changing this would be a compatibility break. That can't happen in the
3023     * foreseeable future.
3024     */
3025    if ((var_strict_smtputf8 || warn_compat_break_smtputf8_enable)
3026	&& (state->flags & SMTPD_FLAG_SMTPUTF8) == 0
3027	&& *STR(state->addr_buf) && !allascii(STR(state->addr_buf))) {
3028	if (var_strict_smtputf8) {
3029	    smtpd_chat_reply(state, "553 5.6.7 Must declare SMTPUTF8 to "
3030			     "send unicode address");
3031	    return (-1);
3032	}
3033
3034	/*
3035	 * Not: #ifndef NO_EAI. They must configure SMTPUTF8_ENABLE=no if a
3036	 * warning message is logged, so that they don't suddenly start to
3037	 * lose mail after Postfix is built with EAI support.
3038	 */
3039	if (warn_compat_break_smtputf8_enable)
3040	    msg_info("using backwards-compatible default setting "
3041		     VAR_SMTPUTF8_ENABLE "=no to accept non-ASCII recipient "
3042		     "address \"%s\" from %s", STR(state->addr_buf),
3043		     state->namaddr);
3044    }
3045    if (SMTPD_STAND_ALONE(state) == 0) {
3046	const char *verify_sender;
3047
3048	/*
3049	 * XXX Don't reject the address when we're probed with our own
3050	 * address verification sender address. Otherwise, some timeout or
3051	 * some UCE block may result in mutual negative caching, making it
3052	 * painful to get the mail through. Unfortunately we still have to
3053	 * send the address to the Milters otherwise they may bail out with a
3054	 * "missing recipient" protocol error.
3055	 */
3056	verify_sender = valid_verify_sender_addr(STR(state->addr_buf));
3057	if (verify_sender != 0) {
3058	    vstring_strcpy(state->addr_buf, verify_sender);
3059	    err = 0;
3060	} else {
3061	    err = smtpd_check_rcpt(state, STR(state->addr_buf));
3062	}
3063	if (state->milters != 0
3064	    && (state->saved_flags & MILTER_SKIP_FLAGS) == 0) {
3065	    PUSH_STRING(saved_rcpt, state->recipient, STR(state->addr_buf));
3066	    state->milter_reject_text = err;
3067	    milter_err = milter_rcpt_event(state->milters,
3068					   err == 0 ? MILTER_FLAG_NONE :
3069					   MILTER_FLAG_WANT_RCPT_REJ,
3070				    milter_argv(state, argc - 2, argv + 2));
3071	    if (err == 0 && milter_err != 0) {
3072		/* Log reject etc. with correct recipient information. */
3073		err = check_milter_reply(state, milter_err);
3074	    }
3075	    POP_STRING(saved_rcpt, state->recipient);
3076	}
3077	if (err != 0) {
3078	    smtpd_chat_reply(state, "%s", err);
3079	    return (-1);
3080	}
3081    }
3082
3083    /*
3084     * Don't access the proxy, queue file, or queue file writer process until
3085     * we have a valid recipient address.
3086     */
3087    if (state->proxy == 0 && state->cleanup == 0 && mail_open_stream(state) < 0)
3088	return (-1);
3089
3090    /*
3091     * Proxy the recipient. OK, so we lied. If the real-time proxy rejects
3092     * the recipient then we can have a proxy connection without having
3093     * accepted a recipient.
3094     */
3095    proxy = state->proxy;
3096    if (proxy != 0 && proxy->cmd(state, SMTPD_PROX_WANT_OK,
3097				 "%s", STR(state->buffer)) != 0) {
3098	smtpd_chat_reply(state, "%s", STR(proxy->reply));
3099	return (-1);
3100    }
3101
3102    /*
3103     * Store the recipient. Remember the first one.
3104     *
3105     * Flush recipients to maintain a stiffer coupling with the next stage and
3106     * to better utilize parallelism.
3107     *
3108     * RFC 3461 Section 5.2.1: If the NOTIFY parameter was not supplied for a
3109     * recipient when the message was received, the NOTIFY parameter MUST NOT
3110     * be supplied for that recipient when the message is relayed.
3111     *
3112     * In other words, we can't simply make up our default NOTIFY value. We have
3113     * to remember whether the client sent any.
3114     *
3115     * RFC 3461 Section 5.2.1: If no ORCPT parameter was present when the
3116     * message was received, an ORCPT parameter MAY be added to the RCPT
3117     * command when the message is relayed.  If an ORCPT parameter is added
3118     * by the relaying MTA, it MUST contain the recipient address from the
3119     * RCPT command used when the message was received by that MTA.
3120     *
3121     * In other words, it is OK to make up our own DSN original recipient when
3122     * the client didn't send one. Although the RFC mentions mail relaying
3123     * only, we also make up our own original recipient for the purpose of
3124     * final delivery. For now, we do this here, rather than on the fly.
3125     *
3126     * XXX We use REC_TYPE_ATTR for DSN-related recipient attributes even though
3127     * 1) REC_TYPE_ATTR is not meant for multiple instances of the same named
3128     * attribute, and 2) mixing REC_TYPE_ATTR with REC_TYPE_(not attr)
3129     * requires that we map attributes with rec_attr_map() in order to
3130     * simplify the recipient record processing loops in the cleanup and qmgr
3131     * servers.
3132     *
3133     * Another possibility, yet to be explored, is to leave the additional
3134     * recipient information in the queue file and just pass queue file
3135     * offsets along with the delivery request. This is a trade off between
3136     * memory allocation versus numeric conversion overhead.
3137     *
3138     * Since we have no record grouping mechanism, all recipient-specific
3139     * parameters must be sent to the cleanup server before the actual
3140     * recipient address.
3141     */
3142    state->rcpt_count++;
3143    if (state->recipient == 0)
3144	state->recipient = mystrdup(STR(state->addr_buf));
3145    if (state->cleanup) {
3146	/* Note: RFC(2)821 externalized address! */
3147	if (dsn_orcpt_addr == 0) {
3148	    dsn_orcpt_type = "rfc822";
3149	    dsn_orcpt_addr = argv[2].strval;
3150	    dsn_orcpt_addr_len = strlen(argv[2].strval);
3151	    if (dsn_orcpt_addr[0] == '<'
3152		&& dsn_orcpt_addr[dsn_orcpt_addr_len - 1] == '>') {
3153		dsn_orcpt_addr += 1;
3154		dsn_orcpt_addr_len -= 2;
3155	    }
3156	}
3157	if (dsn_notify)
3158	    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%d",
3159			MAIL_ATTR_DSN_NOTIFY, dsn_notify);
3160	rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%s;%.*s",
3161		    MAIL_ATTR_DSN_ORCPT, dsn_orcpt_type,
3162		    (int) dsn_orcpt_addr_len, dsn_orcpt_addr);
3163	rec_fputs(state->cleanup, REC_TYPE_RCPT, STR(state->addr_buf));
3164	vstream_fflush(state->cleanup);
3165    }
3166    smtpd_chat_reply(state, "250 2.1.5 Ok");
3167    return (0);
3168}
3169
3170/* rcpt_reset - reset RCPT stuff */
3171
3172static void rcpt_reset(SMTPD_STATE *state)
3173{
3174    if (state->recipient) {
3175	myfree(state->recipient);
3176	state->recipient = 0;
3177    }
3178    state->rcpt_count = 0;
3179    /* XXX Must flush the command history. */
3180    state->rcpt_overshoot = 0;
3181}
3182
3183#if 0
3184
3185/* rfc2047_comment_encode - encode comment string */
3186
3187static VSTRING *rfc2047_comment_encode(const char *str, const char *charset)
3188{
3189    VSTRING *buf = vstring_alloc(30);
3190    const unsigned char *cp;
3191    int     ch;
3192
3193    /*
3194     * XXX This is problematic code.
3195     *
3196     * XXX Most of the RFC 2047 "especials" are not special in RFC*822 comments,
3197     * but we encode them anyway to avoid complaints.
3198     *
3199     * XXX In Received: header comments we enclose peer and issuer common names
3200     * with "" quotes (inherited from the Lutz Jaenicke patch). This is the
3201     * cause of several quirks.
3202     *
3203     * 1) We encode text that contains the " character, even though that
3204     * character is not special for RFC*822 comments.
3205     *
3206     * 2) We ignore the recommended limit of 75 characters per encoded word,
3207     * because long comments look ugly when folded in-between quotes.
3208     *
3209     * 3) We encode the enclosing quotes, to avoid producing invalid encoded
3210     * words. Microsoft abuses RFC 2047 encoding with attachment names, but
3211     * we have no information on what decoders do with malformed encoding in
3212     * comments. This means the comments are Jaenicke-compatible only after
3213     * decoding.
3214     */
3215#define ESPECIALS "()<>@,;:\"/[]?.="		/* Special in RFC 2047 */
3216#define QSPECIALS "_" ESPECIALS			/* Special in RFC 2047 'Q' */
3217#define CSPECIALS "\\\"()"			/* Special in our comments */
3218
3219    /* Don't encode if not needed. */
3220    for (cp = (unsigned char *) str; /* see below */ ; ++cp) {
3221	if ((ch = *cp) == 0) {
3222	    vstring_sprintf(buf, "\"%s\"", str);
3223	    return (buf);
3224	}
3225	if (!ISPRINT(ch) || strchr(CSPECIALS, ch))
3226	    break;
3227    }
3228
3229    /*
3230     * Use quoted-printable (like) encoding with spaces mapped to underscore.
3231     */
3232    vstring_sprintf(buf, "=?%s?Q?=%02X", charset, '"');
3233    for (cp = (unsigned char *) str; (ch = *cp) != 0; ++cp) {
3234	if (!ISPRINT(ch) || strchr(QSPECIALS CSPECIALS, ch)) {
3235	    vstring_sprintf_append(buf, "=%02X", ch);
3236	} else if (ch == ' ') {
3237	    VSTRING_ADDCH(buf, '_');
3238	} else {
3239	    VSTRING_ADDCH(buf, ch);
3240	}
3241    }
3242    vstring_sprintf_append(buf, "=%02X?=", '"');
3243    return (buf);
3244}
3245
3246#endif
3247
3248/* comment_sanitize - clean up comment string */
3249
3250static void comment_sanitize(VSTRING *comment_string)
3251{
3252    unsigned char *cp;
3253    int     ch;
3254    int     pc;
3255
3256    /*
3257     * Postfix Received: headers can be configured to include a comment with
3258     * the CN (CommonName) of the peer and its issuer, or the login name of a
3259     * SASL authenticated user. To avoid problems with RFC 822 etc. syntax,
3260     * we limit this information to printable ASCII text, and neutralize
3261     * characters that affect comment parsing: the backslash and unbalanced
3262     * parentheses.
3263     */
3264    for (pc = 0, cp = (unsigned char *) STR(comment_string); (ch = *cp) != 0; cp++) {
3265	if (!ISASCII(ch) || !ISPRINT(ch) || ch == '\\') {
3266	    *cp = '?';
3267	} else if (ch == '(') {
3268	    pc++;
3269	} else if (ch == ')') {
3270	    if (pc > 0)
3271		pc--;
3272	    else
3273		*cp = '?';
3274	}
3275    }
3276    while (pc-- > 0)
3277	VSTRING_ADDCH(comment_string, ')');
3278    VSTRING_TERMINATE(comment_string);
3279}
3280
3281static void common_pre_message_handling(SMTPD_STATE *state,
3282	          int (*out_record) (VSTREAM *, int, const char *, ssize_t),
3283	              int (*out_fprintf) (VSTREAM *, int, const char *,...),
3284				        VSTREAM *out_stream, int out_error);
3285static void receive_data_message(SMTPD_STATE *state,
3286	          int (*out_record) (VSTREAM *, int, const char *, ssize_t),
3287	              int (*out_fprintf) (VSTREAM *, int, const char *,...),
3288				         VSTREAM *out_stream, int out_error);
3289static int common_post_message_handling(SMTPD_STATE *state);
3290
3291/* data_cmd - process DATA command */
3292
3293static int data_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *unused_argv)
3294{
3295    SMTPD_PROXY *proxy;
3296    const char *err;
3297    int     (*out_record) (VSTREAM *, int, const char *, ssize_t);
3298    int     (*out_fprintf) (VSTREAM *, int, const char *,...);
3299    VSTREAM *out_stream;
3300    int     out_error;
3301
3302    /*
3303     * Sanity checks. With ESMTP command pipelining the client can send DATA
3304     * before all recipients are rejected, so don't report that as a protocol
3305     * error.
3306     */
3307    if (SMTPD_PROCESSING_BDAT(state)) {
3308	state->error_mask |= MAIL_ERROR_PROTOCOL;
3309	smtpd_chat_reply(state, "503 5.5.1 Error: DATA after BDAT");
3310	return (-1);
3311    }
3312    if (state->rcpt_count == 0) {
3313	if (!SMTPD_IN_MAIL_TRANSACTION(state)) {
3314	    state->error_mask |= MAIL_ERROR_PROTOCOL;
3315	    smtpd_chat_reply(state, "503 5.5.1 Error: need RCPT command");
3316	} else {
3317	    smtpd_chat_reply(state, "554 5.5.1 Error: no valid recipients");
3318	}
3319	return (-1);
3320    }
3321    if (argc != 1) {
3322	state->error_mask |= MAIL_ERROR_PROTOCOL;
3323	smtpd_chat_reply(state, "501 5.5.4 Syntax: DATA");
3324	return (-1);
3325    }
3326    if (SMTPD_STAND_ALONE(state) == 0 && (err = smtpd_check_data(state)) != 0) {
3327	smtpd_chat_reply(state, "%s", err);
3328	return (-1);
3329    }
3330    if (state->milters != 0
3331	&& (state->saved_flags & MILTER_SKIP_FLAGS) == 0
3332	&& (err = milter_data_event(state->milters)) != 0
3333	&& (err = check_milter_reply(state, err)) != 0) {
3334	smtpd_chat_reply(state, "%s", err);
3335	return (-1);
3336    }
3337    proxy = state->proxy;
3338    if (proxy != 0 && proxy->cmd(state, SMTPD_PROX_WANT_MORE,
3339				 "%s", STR(state->buffer)) != 0) {
3340	smtpd_chat_reply(state, "%s", STR(proxy->reply));
3341	return (-1);
3342    }
3343
3344    /*
3345     * One level of indirection to choose between normal or proxied
3346     * operation. We want to avoid massive code duplication within tons of
3347     * if-else clauses.
3348     */
3349    if (proxy) {
3350	out_stream = proxy->stream;
3351	out_record = proxy->rec_put;
3352	out_fprintf = proxy->rec_fprintf;
3353	out_error = CLEANUP_STAT_PROXY;
3354    } else {
3355	out_stream = state->cleanup;
3356	out_record = rec_put;
3357	out_fprintf = rec_fprintf;
3358	out_error = CLEANUP_STAT_WRITE;
3359    }
3360    common_pre_message_handling(state, out_record, out_fprintf,
3361				out_stream, out_error);
3362    smtpd_chat_reply(state, "354 End data with <CR><LF>.<CR><LF>");
3363    state->where = SMTPD_AFTER_DATA;
3364    receive_data_message(state, out_record, out_fprintf, out_stream, out_error);
3365    return common_post_message_handling(state);
3366}
3367
3368/* common_pre_message_handling - finish envelope and open message segment */
3369
3370static void common_pre_message_handling(SMTPD_STATE *state,
3371	          int (*out_record) (VSTREAM *, int, const char *, ssize_t),
3372	              int (*out_fprintf) (VSTREAM *, int, const char *,...),
3373					        VSTREAM *out_stream,
3374					        int out_error)
3375{
3376    SMTPD_PROXY *proxy = state->proxy;
3377    char  **cpp;
3378    const char *rfc3848_sess;
3379    const char *rfc3848_auth;
3380    const char *with_protocol = (state->flags & SMTPD_FLAG_SMTPUTF8) ?
3381    "UTF8SMTP" : state->protocol;
3382
3383#ifdef USE_TLS
3384    VSTRING *peer_CN;
3385    VSTRING *issuer_CN;
3386
3387#endif
3388#ifdef USE_SASL_AUTH
3389    VSTRING *username;
3390
3391#endif
3392
3393    /*
3394     * Flush out a first batch of access table actions that are delegated to
3395     * the cleanup server, and that may trigger before we accept the first
3396     * valid recipient. There will be more after end-of-data.
3397     *
3398     * Terminate the message envelope segment. Start the message content
3399     * segment, and prepend our own Received: header. If there is only one
3400     * recipient, list the recipient address.
3401     */
3402    if (state->cleanup) {
3403	if (SMTPD_STAND_ALONE(state) == 0) {
3404	    if (state->milters != 0
3405		&& (state->saved_flags & MILTER_SKIP_FLAGS) == 0)
3406		/* Send actual smtpd_milters list. */
3407		(void) milter_send(state->milters, state->cleanup);
3408	    if (state->saved_flags)
3409		rec_fprintf(state->cleanup, REC_TYPE_FLGS, "%d",
3410			    state->saved_flags);
3411	}
3412	rec_fputs(state->cleanup, REC_TYPE_MESG, "");
3413    }
3414
3415    /*
3416     * PREPEND message headers above our own Received: header.
3417     */
3418    if (state->prepend)
3419	for (cpp = state->prepend->argv; *cpp; cpp++)
3420	    out_fprintf(out_stream, REC_TYPE_NORM, "%s", *cpp);
3421
3422    /*
3423     * Suppress our own Received: header in the unlikely case that we are an
3424     * intermediate proxy.
3425     */
3426    if (!proxy || state->xforward.flags == 0) {
3427	out_fprintf(out_stream, REC_TYPE_NORM,
3428		    "Received: from %s (%s [%s])",
3429		    state->helo_name ? state->helo_name : state->name,
3430		    state->name, state->rfc_addr);
3431
3432#define VSTRING_STRDUP(s) vstring_strcpy(vstring_alloc(strlen(s) + 1), (s))
3433
3434#ifdef USE_TLS
3435	if (var_smtpd_tls_received_header && state->tls_context) {
3436	    int     cont = 0;
3437
3438	    vstring_sprintf(state->buffer,
3439			    "\t(using %s with cipher %s (%d/%d bits)",
3440			    state->tls_context->protocol,
3441			    state->tls_context->cipher_name,
3442			    state->tls_context->cipher_usebits,
3443			    state->tls_context->cipher_algbits);
3444	    if (state->tls_context->kex_name && *state->tls_context->kex_name) {
3445		out_record(out_stream, REC_TYPE_NORM, STR(state->buffer),
3446			   LEN(state->buffer));
3447		vstring_sprintf(state->buffer, "\t key-exchange %s",
3448				state->tls_context->kex_name);
3449		if (state->tls_context->kex_curve
3450		    && *state->tls_context->kex_curve)
3451		    vstring_sprintf_append(state->buffer, " (%s)",
3452					   state->tls_context->kex_curve);
3453		else if (state->tls_context->kex_bits > 0)
3454		    vstring_sprintf_append(state->buffer, " (%d bits)",
3455					   state->tls_context->kex_bits);
3456		cont = 1;
3457	    }
3458	    if (state->tls_context->srvr_sig_name
3459		&& *state->tls_context->srvr_sig_name) {
3460		if (cont) {
3461		    vstring_sprintf_append(state->buffer, " server-signature %s",
3462					 state->tls_context->srvr_sig_name);
3463		} else {
3464		    out_record(out_stream, REC_TYPE_NORM, STR(state->buffer),
3465			       LEN(state->buffer));
3466		    vstring_sprintf(state->buffer, "\t server-signature %s",
3467				    state->tls_context->srvr_sig_name);
3468		}
3469		if (state->tls_context->srvr_sig_curve
3470		    && *state->tls_context->srvr_sig_curve)
3471		    vstring_sprintf_append(state->buffer, " (%s)",
3472					state->tls_context->srvr_sig_curve);
3473		else if (state->tls_context->srvr_sig_bits > 0)
3474		    vstring_sprintf_append(state->buffer, " (%d bits)",
3475					 state->tls_context->srvr_sig_bits);
3476		if (state->tls_context->srvr_sig_dgst
3477		    && *state->tls_context->srvr_sig_dgst)
3478		    vstring_sprintf_append(state->buffer, " server-digest %s",
3479					 state->tls_context->srvr_sig_dgst);
3480	    }
3481	    if (state->tls_context->clnt_sig_name
3482		&& *state->tls_context->clnt_sig_name) {
3483		out_record(out_stream, REC_TYPE_NORM, STR(state->buffer),
3484			   LEN(state->buffer));
3485		vstring_sprintf(state->buffer, "\t client-signature %s",
3486				state->tls_context->clnt_sig_name);
3487		if (state->tls_context->clnt_sig_curve
3488		    && *state->tls_context->clnt_sig_curve)
3489		    vstring_sprintf_append(state->buffer, " (%s)",
3490					state->tls_context->clnt_sig_curve);
3491		else if (state->tls_context->clnt_sig_bits > 0)
3492		    vstring_sprintf_append(state->buffer, " (%d bits)",
3493					 state->tls_context->clnt_sig_bits);
3494		if (state->tls_context->clnt_sig_dgst
3495		    && *state->tls_context->clnt_sig_dgst)
3496		    vstring_sprintf_append(state->buffer, " client-digest %s",
3497					 state->tls_context->clnt_sig_dgst);
3498	    }
3499	    out_fprintf(out_stream, REC_TYPE_NORM, "%s)", STR(state->buffer));
3500	    if (TLS_CERT_IS_PRESENT(state->tls_context)) {
3501		peer_CN = VSTRING_STRDUP(state->tls_context->peer_CN);
3502		comment_sanitize(peer_CN);
3503		issuer_CN = VSTRING_STRDUP(state->tls_context->issuer_CN ?
3504					state->tls_context->issuer_CN : "");
3505		comment_sanitize(issuer_CN);
3506		out_fprintf(out_stream, REC_TYPE_NORM,
3507			    "\t(Client CN \"%s\", Issuer \"%s\" (%s))",
3508			    STR(peer_CN), STR(issuer_CN),
3509			    TLS_CERT_IS_TRUSTED(state->tls_context) ?
3510			    "verified OK" : "not verified");
3511		vstring_free(issuer_CN);
3512		vstring_free(peer_CN);
3513	    } else if (var_smtpd_tls_ask_ccert)
3514		out_fprintf(out_stream, REC_TYPE_NORM,
3515			    "\t(Client did not present a certificate)");
3516	    else
3517		out_fprintf(out_stream, REC_TYPE_NORM,
3518			    "\t(No client certificate requested)");
3519	}
3520	/* RFC 3848 is defined for ESMTP only. */
3521	if (state->tls_context != 0
3522	    && strcmp(state->protocol, MAIL_PROTO_ESMTP) == 0)
3523	    rfc3848_sess = "S";
3524	else
3525#endif
3526	    rfc3848_sess = "";
3527#ifdef USE_SASL_AUTH
3528	if (var_smtpd_sasl_auth_hdr && state->sasl_username) {
3529	    username = VSTRING_STRDUP(state->sasl_username);
3530	    comment_sanitize(username);
3531	    out_fprintf(out_stream, REC_TYPE_NORM,
3532			"\t(Authenticated sender: %s)", STR(username));
3533	    vstring_free(username);
3534	}
3535	/* RFC 3848 is defined for ESMTP only. */
3536	if (state->sasl_username
3537	    && strcmp(state->protocol, MAIL_PROTO_ESMTP) == 0)
3538	    rfc3848_auth = "A";
3539	else
3540#endif
3541	    rfc3848_auth = "";
3542	if (state->rcpt_count == 1 && state->recipient) {
3543	    out_fprintf(out_stream, REC_TYPE_NORM,
3544			state->cleanup ? "\tby %s (%s) with %s%s%s id %s" :
3545			"\tby %s (%s) with %s%s%s",
3546			var_myhostname, var_mail_name,
3547			with_protocol, rfc3848_sess,
3548			rfc3848_auth, state->queue_id);
3549	    quote_822_local(state->buffer, state->recipient);
3550	    out_fprintf(out_stream, REC_TYPE_NORM,
3551			"\tfor <%s>; %s", STR(state->buffer),
3552			mail_date(state->arrival_time.tv_sec));
3553	} else {
3554	    out_fprintf(out_stream, REC_TYPE_NORM,
3555			state->cleanup ? "\tby %s (%s) with %s%s%s id %s;" :
3556			"\tby %s (%s) with %s%s%s;",
3557			var_myhostname, var_mail_name,
3558			with_protocol, rfc3848_sess,
3559			rfc3848_auth, state->queue_id);
3560	    out_fprintf(out_stream, REC_TYPE_NORM,
3561			"\t%s", mail_date(state->arrival_time.tv_sec));
3562	}
3563#ifdef RECEIVED_ENVELOPE_FROM
3564	quote_822_local(state->buffer, state->sender);
3565	out_fprintf(out_stream, REC_TYPE_NORM,
3566		    "\t(envelope-from %s)", STR(state->buffer));
3567#endif
3568    }
3569}
3570
3571/* receive_data_message - finish envelope and open message segment */
3572
3573static void receive_data_message(SMTPD_STATE *state,
3574	          int (*out_record) (VSTREAM *, int, const char *, ssize_t),
3575	              int (*out_fprintf) (VSTREAM *, int, const char *,...),
3576				         VSTREAM *out_stream,
3577				         int out_error)
3578{
3579    SMTPD_PROXY *proxy = state->proxy;
3580    char   *start;
3581    int     len;
3582    int     curr_rec_type;
3583    int     prev_rec_type;
3584    int     first = 1;
3585
3586    /*
3587     * If deadlines are enabled, increase the time budget as message content
3588     * arrives.
3589     */
3590    smtp_stream_setup(state->client, var_smtpd_tmout, var_smtpd_req_deadline,
3591		      var_smtpd_min_data_rate);
3592
3593    /*
3594     * Copy the message content. If the cleanup process has a problem, keep
3595     * reading until the remote stops sending, then complain. Produce typed
3596     * records from the SMTP stream so we can handle data that spans buffers.
3597     *
3598     * XXX Force an empty record when the queue file content begins with
3599     * whitespace, so that it won't be considered as being part of our own
3600     * Received: header. What an ugly Kluge.
3601     *
3602     * XXX Deal with UNIX-style From_ lines at the start of message content
3603     * because sendmail permits it.
3604     */
3605    for (prev_rec_type = 0; /* void */ ; prev_rec_type = curr_rec_type) {
3606	if (smtp_get(state->buffer, state->client, var_line_limit,
3607		     SMTP_GET_FLAG_NONE) == '\n')
3608	    curr_rec_type = REC_TYPE_NORM;
3609	else
3610	    curr_rec_type = REC_TYPE_CONT;
3611	start = vstring_str(state->buffer);
3612	len = VSTRING_LEN(state->buffer);
3613	if (first) {
3614	    if (strncmp(start + strspn(start, ">"), "From ", 5) == 0) {
3615		out_fprintf(out_stream, curr_rec_type,
3616			    "X-Mailbox-Line: %s", start);
3617		continue;
3618	    }
3619	    first = 0;
3620	    if (len > 0 && IS_SPACE_TAB(start[0]))
3621		out_record(out_stream, REC_TYPE_NORM, "", 0);
3622	}
3623	if (prev_rec_type != REC_TYPE_CONT && *start == '.'
3624	    && (proxy == 0 ? (++start, --len) == 0 : len == 1))
3625	    break;
3626	if (state->err == CLEANUP_STAT_OK) {
3627	    if (ENFORCING_SIZE_LIMIT(var_message_limit)
3628		&& var_message_limit - state->act_size < len + 2) {
3629		state->err = CLEANUP_STAT_SIZE;
3630		msg_warn("%s: queue file size limit exceeded",
3631			 state->queue_id ? state->queue_id : "NOQUEUE");
3632	    } else {
3633		state->act_size += len + 2;
3634		if (out_record(out_stream, curr_rec_type, start, len) < 0)
3635		    state->err = out_error;
3636	    }
3637	}
3638    }
3639    state->where = SMTPD_AFTER_EOM;
3640}
3641
3642/* common_post_message_handling - commit message or report error */
3643
3644static int common_post_message_handling(SMTPD_STATE *state)
3645{
3646    SMTPD_PROXY *proxy = state->proxy;
3647    const char *err;
3648    VSTRING *why = 0;
3649    int     saved_err;
3650    const CLEANUP_STAT_DETAIL *detail;
3651
3652#define IS_SMTP_REJECT(s) \
3653	(((s)[0] == '4' || (s)[0] == '5') \
3654	 && ISDIGIT((s)[1]) && ISDIGIT((s)[2]) \
3655	 && ((s)[3] == '\0' || (s)[3] == ' ' || (s)[3] == '-'))
3656
3657    if (state->err == CLEANUP_STAT_OK
3658	&& SMTPD_STAND_ALONE(state) == 0
3659	&& (err = smtpd_check_eod(state)) != 0) {
3660	smtpd_chat_reply(state, "%s", err);
3661	if (proxy) {
3662	    smtpd_proxy_close(state);
3663	} else {
3664	    mail_stream_cleanup(state->dest);
3665	    state->dest = 0;
3666	    state->cleanup = 0;
3667	}
3668	return (-1);
3669    }
3670
3671    /*
3672     * Send the end of DATA and finish the proxy connection. Set the
3673     * CLEANUP_STAT_PROXY error flag in case of trouble.
3674     */
3675    if (proxy) {
3676	if (state->err == CLEANUP_STAT_OK) {
3677	    (void) proxy->cmd(state, SMTPD_PROX_WANT_ANY, ".");
3678	    if (state->err == CLEANUP_STAT_OK &&
3679		*STR(proxy->reply) != '2')
3680		state->err = CLEANUP_STAT_CONT;
3681	}
3682    }
3683
3684    /*
3685     * Flush out access table actions that are delegated to the cleanup
3686     * server. There is similar code at the beginning of the DATA command.
3687     *
3688     * Send the end-of-segment markers and finish the queue file record stream.
3689     */
3690    else {
3691	if (state->err == CLEANUP_STAT_OK) {
3692	    rec_fputs(state->cleanup, REC_TYPE_XTRA, "");
3693	    if (state->saved_filter)
3694		rec_fprintf(state->cleanup, REC_TYPE_FILT, "%s",
3695			    state->saved_filter);
3696	    if (state->saved_redirect)
3697		rec_fprintf(state->cleanup, REC_TYPE_RDR, "%s",
3698			    state->saved_redirect);
3699	    if (state->saved_bcc) {
3700		char  **cpp;
3701
3702		for (cpp = state->saved_bcc->argv; *cpp; cpp++) {
3703		    rec_fprintf(state->cleanup, REC_TYPE_RCPT, "%s",
3704				*cpp);
3705		    rec_fprintf(state->cleanup, REC_TYPE_ATTR, "%s=%d",
3706				MAIL_ATTR_DSN_NOTIFY, DSN_NOTIFY_NEVER);
3707		}
3708	    }
3709	    if (state->saved_flags)
3710		rec_fprintf(state->cleanup, REC_TYPE_FLGS, "%d",
3711			    state->saved_flags);
3712#ifdef DELAY_ACTION
3713	    if (state->saved_delay)
3714		rec_fprintf(state->cleanup, REC_TYPE_DELAY, "%d",
3715			    state->saved_delay);
3716#endif
3717	    if (vstream_ferror(state->cleanup))
3718		state->err = CLEANUP_STAT_WRITE;
3719	}
3720	if (state->err == CLEANUP_STAT_OK)
3721	    if (rec_fputs(state->cleanup, REC_TYPE_END, "") < 0
3722		|| vstream_fflush(state->cleanup))
3723		state->err = CLEANUP_STAT_WRITE;
3724	if (state->err == 0) {
3725	    why = vstring_alloc(10);
3726	    state->err = mail_stream_finish(state->dest, why);
3727	    if (IS_SMTP_REJECT(STR(why)))
3728		printable_except(STR(why), ' ', "\r\n");
3729	    else
3730		printable(STR(why), ' ');
3731	} else
3732	    mail_stream_cleanup(state->dest);
3733	state->dest = 0;
3734	state->cleanup = 0;
3735    }
3736
3737    /*
3738     * XXX If we lose the cleanup server while it is editing a queue file,
3739     * the Postfix SMTP server will be out of sync with Milter applications.
3740     * Sending an ABORT to the Milters is not sufficient to restore
3741     * synchronization, because there may be any number of Milter replies
3742     * already in flight. Destroying and recreating the Milters (and faking
3743     * the connect and ehlo events) is too much trouble for testing and
3744     * maintenance. Workaround: force the Postfix SMTP server to hang up with
3745     * a 421 response in the rare case that the cleanup server breaks AND
3746     * that the remote SMTP client continues the session after end-of-data.
3747     *
3748     * XXX Should use something other than CLEANUP_STAT_WRITE when we lose
3749     * contact with the cleanup server. This requires changes to the
3750     * mail_stream module and its users (smtpd, qmqpd, perhaps sendmail).
3751     *
3752     * XXX See exception below in code that overrides state->access_denied for
3753     * compliance with RFC 2821 Sec 3.1.
3754     */
3755    if (state->milters != 0 && (state->err & CLEANUP_STAT_WRITE) != 0)
3756	state->access_denied = mystrdup("421 4.3.0 Mail system error");
3757
3758    /*
3759     * Handle any errors. One message may suffer from multiple errors, so
3760     * complain only about the most severe error. Forgive any previous client
3761     * errors when a message was received successfully.
3762     *
3763     * See also: qmqpd.c
3764     */
3765    if (state->err == CLEANUP_STAT_OK) {
3766	state->error_count = 0;
3767	state->error_mask = 0;
3768	state->junk_cmds = 0;
3769	if (proxy)
3770	    smtpd_chat_reply(state, "%s", STR(proxy->reply));
3771	else if (SMTPD_PROCESSING_BDAT(state))
3772	    smtpd_chat_reply(state,
3773			     "250 2.0.0 Ok: %ld bytes queued as %s",
3774			     (long) state->act_size, state->queue_id);
3775	else
3776	    smtpd_chat_reply(state,
3777			     "250 2.0.0 Ok: queued as %s", state->queue_id);
3778    } else if (why && IS_SMTP_REJECT(STR(why))) {
3779	state->error_mask |= MAIL_ERROR_POLICY;
3780	smtpd_chat_reply(state, "%s", STR(why));
3781    } else if ((state->err & CLEANUP_STAT_DEFER) != 0) {
3782	state->error_mask |= MAIL_ERROR_POLICY;
3783	detail = cleanup_stat_detail(CLEANUP_STAT_DEFER);
3784	if (why && LEN(why) > 0) {
3785	    /* Allow address-specific DSN status in header/body_checks. */
3786	    smtpd_chat_reply(state, "%d %s", detail->smtp, STR(why));
3787	} else {
3788	    smtpd_chat_reply(state, "%d %s Error: %s",
3789			     detail->smtp, detail->dsn, detail->text);
3790	}
3791    } else if ((state->err & CLEANUP_STAT_BAD) != 0) {
3792	state->error_mask |= MAIL_ERROR_SOFTWARE;
3793	detail = cleanup_stat_detail(CLEANUP_STAT_BAD);
3794	smtpd_chat_reply(state, "%d %s Error: internal error %d",
3795			 detail->smtp, detail->dsn, state->err);
3796    } else if ((state->err & CLEANUP_STAT_SIZE) != 0) {
3797	state->error_mask |= MAIL_ERROR_BOUNCE;
3798	detail = cleanup_stat_detail(CLEANUP_STAT_SIZE);
3799	smtpd_chat_reply(state, "%d %s Error: %s",
3800			 detail->smtp, detail->dsn, detail->text);
3801    } else if ((state->err & CLEANUP_STAT_HOPS) != 0) {
3802	state->error_mask |= MAIL_ERROR_BOUNCE;
3803	detail = cleanup_stat_detail(CLEANUP_STAT_HOPS);
3804	smtpd_chat_reply(state, "%d %s Error: %s",
3805			 detail->smtp, detail->dsn, detail->text);
3806    } else if ((state->err & CLEANUP_STAT_CONT) != 0) {
3807	state->error_mask |= MAIL_ERROR_POLICY;
3808	detail = cleanup_stat_detail(CLEANUP_STAT_CONT);
3809	if (proxy) {
3810	    smtpd_chat_reply(state, "%s", STR(proxy->reply));
3811	} else if (why && LEN(why) > 0) {
3812	    /* Allow address-specific DSN status in header/body_checks. */
3813	    smtpd_chat_reply(state, "%d %s", detail->smtp, STR(why));
3814	} else {
3815	    smtpd_chat_reply(state, "%d %s Error: %s",
3816			     detail->smtp, detail->dsn, detail->text);
3817	}
3818    } else if ((state->err & CLEANUP_STAT_WRITE) != 0) {
3819	state->error_mask |= MAIL_ERROR_RESOURCE;
3820	detail = cleanup_stat_detail(CLEANUP_STAT_WRITE);
3821	smtpd_chat_reply(state, "%d %s Error: %s",
3822			 detail->smtp, detail->dsn, detail->text);
3823    } else if ((state->err & CLEANUP_STAT_PROXY) != 0) {
3824	state->error_mask |= MAIL_ERROR_SOFTWARE;
3825	smtpd_chat_reply(state, "%s", STR(proxy->reply));
3826    } else {
3827	state->error_mask |= MAIL_ERROR_SOFTWARE;
3828	detail = cleanup_stat_detail(CLEANUP_STAT_BAD);
3829	smtpd_chat_reply(state, "%d %s Error: internal error %d",
3830			 detail->smtp, detail->dsn, state->err);
3831    }
3832
3833    /*
3834     * By popular command: the proxy's end-of-data reply.
3835     */
3836    if (proxy)
3837	msg_info("proxy-%s: %s: %s;%s",
3838		 (state->err == CLEANUP_STAT_OK) ? "accept" : "reject",
3839		 state->where, STR(proxy->reply), smtpd_whatsup(state));
3840
3841    /*
3842     * Cleanup. The client may send another MAIL command.
3843     */
3844    saved_err = state->err;
3845    chat_reset(state, var_smtpd_hist_thrsh);
3846    mail_reset(state);
3847    rcpt_reset(state);
3848    if (why)
3849	vstring_free(why);
3850    return (saved_err);
3851}
3852
3853/* skip_bdat - skip content and respond to BDAT error */
3854
3855static int skip_bdat(SMTPD_STATE *state, off_t chunk_size,
3856		             bool final_chunk, const char *format,...)
3857{
3858    va_list ap;
3859    off_t   done;
3860    off_t   len;
3861
3862    /*
3863     * Read and discard content from the remote SMTP client. TODO: drop the
3864     * connection in case of overload.
3865     */
3866    for (done = 0; done < chunk_size; done += len) {
3867	if ((len = chunk_size - done) > VSTREAM_BUFSIZE)
3868	    len = VSTREAM_BUFSIZE;
3869	smtp_fread_buf(state->buffer, len, state->client);
3870    }
3871
3872    /*
3873     * Send the response to the remote SMTP client.
3874     */
3875    va_start(ap, format);
3876    vsmtpd_chat_reply(state, format, ap);
3877    va_end(ap);
3878
3879    /*
3880     * Reset state, or drop subsequent BDAT payloads until BDAT LAST or RSET.
3881     */
3882    if (final_chunk)
3883	mail_reset(state);
3884    else
3885	state->bdat_state = SMTPD_BDAT_STAT_ERROR;
3886    return (-1);
3887}
3888
3889/* bdat_cmd - process BDAT command */
3890
3891static int bdat_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *argv)
3892{
3893    SMTPD_PROXY *proxy;
3894    const char *err;
3895    off_t   chunk_size;
3896    bool    final_chunk;
3897    off_t   done;
3898    off_t   read_len;
3899    char   *start;
3900    int     len;
3901    int     curr_rec_type;
3902    int     (*out_record) (VSTREAM *, int, const char *, ssize_t);
3903    int     (*out_fprintf) (VSTREAM *, int, const char *,...);
3904    VSTREAM *out_stream;
3905    int     out_error;
3906
3907    /*
3908     * Hang up if the BDAT command is disabled. The next input would be raw
3909     * message content and that would trigger lots of command errors.
3910     */
3911    if (state->ehlo_discard_mask & EHLO_MASK_CHUNKING) {
3912	state->error_mask |= MAIL_ERROR_PROTOCOL;
3913	smtpd_chat_reply(state, "521 5.5.1 Error: command not implemented");
3914	return (-1);
3915    }
3916
3917    /*
3918     * Hang up if the BDAT command is malformed. The next input would be raw
3919     * message content and that would trigger lots of command errors.
3920     */
3921    if (argc < 2 || argc > 3 || !alldig(argv[1].strval)
3922	|| (chunk_size = off_cvt_string(argv[1].strval)) < 0
3923	|| ((final_chunk = (argc == 3))
3924	    && strcasecmp(argv[2].strval, "LAST") != 0)) {
3925	state->error_mask |= MAIL_ERROR_PROTOCOL;
3926	msg_warn("%s: malformed BDAT command syntax from %s: %.100s",
3927		 state->queue_id ? state->queue_id : "NOQUEUE",
3928		 state->namaddr, printable(vstring_str(state->buffer), '?'));
3929	smtpd_chat_reply(state, "521 5.5.4 Syntax: BDAT count [LAST]");
3930	return (-1);
3931    }
3932
3933    /*
3934     * If deadlines are enabled, increase the time budget as message content
3935     * arrives.
3936     */
3937    smtp_stream_setup(state->client, var_smtpd_tmout, var_smtpd_req_deadline,
3938		      var_smtpd_min_data_rate);
3939
3940    /*
3941     * Block abuse involving empty chunks (alternatively, we could count
3942     * "BDAT 0" as a "NOOP", but then we would have to refactor the code that
3943     * enforces the junk command limit). Clients that send a message as a
3944     * sequence of "BDAT 1" should not be a problem: the Postfix BDAT
3945     * implementation should be efficient enough to handle that.
3946     */
3947    if (chunk_size == 0 && !final_chunk) {
3948	msg_warn("%s: null BDAT request from %s",
3949		 state->queue_id ? state->queue_id : "NOQUEUE",
3950		 state->namaddr);
3951	return skip_bdat(state, chunk_size, final_chunk,
3952			 "551 5.7.1 Null BDAT request");
3953    }
3954
3955    /*
3956     * BDAT commands may be pipelined within a MAIL transaction. After a BDAT
3957     * request fails, keep accepting BDAT requests and skipping BDAT payloads
3958     * to maintain synchronization with the remote SMTP client, until the
3959     * client sends BDAT LAST or RSET.
3960     */
3961    if (state->bdat_state == SMTPD_BDAT_STAT_ERROR)
3962	return skip_bdat(state, chunk_size, final_chunk,
3963			 "551 5.0.0 Discarded %ld bytes after earlier error",
3964			 (long) chunk_size);
3965
3966    /*
3967     * Special handling for the first BDAT command in a MAIL transaction,
3968     * treating it as a kind of "DATA" command for the purpose of policy
3969     * evaluation.
3970     */
3971    if (!SMTPD_PROCESSING_BDAT(state)) {
3972
3973	/*
3974	 * With ESMTP command pipelining a client may send BDAT before the
3975	 * server has replied to all RCPT commands. For this reason we cannot
3976	 * treat BDAT without valid recipients as a protocol error.  Worse,
3977	 * RFC 3030 does not discuss the role of BDAT commands in RFC 2920
3978	 * command groups (batches of commands that may be sent without
3979	 * waiting for a response to each individual command). Therefore we
3980	 * have to allow for clients that pipeline the entire SMTP session
3981	 * after EHLO, including multiple MAIL transactions.
3982	 */
3983	if (state->rcpt_count == 0) {
3984	    if (!SMTPD_IN_MAIL_TRANSACTION(state)) {
3985		/* TODO: maybe remove this from the DATA and BDAT handlers. */
3986		state->error_mask |= MAIL_ERROR_PROTOCOL;
3987		return skip_bdat(state, chunk_size, final_chunk,
3988				 "503 5.5.1 Error: need RCPT command");
3989	    } else {
3990		return skip_bdat(state, chunk_size, final_chunk,
3991				 "554 5.5.1 Error: no valid recipients");
3992	    }
3993	}
3994	if (SMTPD_STAND_ALONE(state) == 0
3995	    && (err = smtpd_check_data(state)) != 0) {
3996	    return skip_bdat(state, chunk_size, final_chunk, "%s", err);
3997	}
3998	if (state->milters != 0
3999	    && (state->saved_flags & MILTER_SKIP_FLAGS) == 0
4000	    && (err = milter_data_event(state->milters)) != 0
4001	    && (err = check_milter_reply(state, err)) != 0) {
4002	    return skip_bdat(state, chunk_size, final_chunk, "%s", err);
4003	}
4004	proxy = state->proxy;
4005	if (proxy != 0 && proxy->cmd(state, SMTPD_PROX_WANT_MORE,
4006				     SMTPD_CMD_DATA) != 0) {
4007	    return skip_bdat(state, chunk_size, final_chunk,
4008			     "%s", STR(proxy->reply));
4009	}
4010    }
4011    /* Block too large chunks. */
4012    if (ENFORCING_SIZE_LIMIT(var_message_limit)
4013	&& state->act_size > var_message_limit - chunk_size) {
4014	state->error_mask |= MAIL_ERROR_POLICY;
4015	msg_warn("%s: BDAT request from %s exceeds message size limit",
4016		 state->queue_id ? state->queue_id : "NOQUEUE",
4017		 state->namaddr);
4018	return skip_bdat(state, chunk_size, final_chunk,
4019			 "552 5.3.4 Chunk exceeds message size limit");
4020    }
4021
4022    /*
4023     * One level of indirection to choose between normal or proxied
4024     * operation. We want to avoid massive code duplication within tons of
4025     * if-else clauses. TODO: store this in its own data structure, or in
4026     * SMTPD_STATE.
4027     */
4028    proxy = state->proxy;
4029    if (proxy) {
4030	out_stream = proxy->stream;
4031	out_record = proxy->rec_put;
4032	out_fprintf = proxy->rec_fprintf;
4033	out_error = CLEANUP_STAT_PROXY;
4034    } else {
4035	out_stream = state->cleanup;
4036	out_record = rec_put;
4037	out_fprintf = rec_fprintf;
4038	out_error = CLEANUP_STAT_WRITE;
4039    }
4040    if (!SMTPD_PROCESSING_BDAT(state)) {
4041	common_pre_message_handling(state, out_record, out_fprintf,
4042				    out_stream, out_error);
4043	if (state->bdat_get_buffer == 0)
4044	    state->bdat_get_buffer = vstring_alloc(VSTREAM_BUFSIZE);
4045	else
4046	    VSTRING_RESET(state->bdat_get_buffer);
4047	state->bdat_prev_rec_type = 0;
4048    }
4049    state->bdat_state = SMTPD_BDAT_STAT_OK;
4050    state->where = SMTPD_AFTER_BDAT;
4051
4052    /*
4053     * Copy the message content. If the cleanup process has a problem, keep
4054     * reading until the remote stops sending, then complain. Produce typed
4055     * records from the SMTP stream so we can handle data that spans buffers.
4056     */
4057
4058    /*
4059     * Instead of reading the entire BDAT chunk into memory, read the chunk
4060     * one fragment at a time. The loops below always make one iteration, to
4061     * avoid code duplication for the "BDAT 0 LAST" case (empty chunk).
4062     */
4063    done = 0;
4064    do {
4065	int     payload_err;
4066
4067	/*
4068	 * Do not skip the smtp_fread_buf() call if read_len == 0. We still
4069	 * need the side effects which include resetting the buffer write
4070	 * position. Skipping the call would invalidate the buffer state.
4071	 *
4072	 * Caution: smtp_fread_buf() will long jump after EOF or timeout.
4073	 */
4074	if ((read_len = chunk_size - done) > VSTREAM_BUFSIZE)
4075	    read_len = VSTREAM_BUFSIZE;
4076	smtp_fread_buf(state->buffer, read_len, state->client);
4077	state->bdat_get_stream = vstream_memreopen(
4078			   state->bdat_get_stream, state->buffer, O_RDONLY);
4079	vstream_control(state->bdat_get_stream, CA_VSTREAM_CTL_EXCEPT,
4080			CA_VSTREAM_CTL_END);
4081	if ((payload_err = vstream_setjmp(state->bdat_get_stream)) != 0)
4082	    vstream_longjmp(state->client, payload_err);
4083
4084	/*
4085	 * Read lines from the fragment. The last line may continue in the
4086	 * next fragment, or in the next chunk.
4087	 */
4088	do {
4089	    if (smtp_get_noexcept(state->bdat_get_buffer,
4090				  state->bdat_get_stream,
4091				  var_line_limit,
4092				  SMTP_GET_FLAG_APPEND) == '\n') {
4093		/* Stopped at end-of-line. */
4094		curr_rec_type = REC_TYPE_NORM;
4095	    } else if (!vstream_feof(state->bdat_get_stream)) {
4096		/* Stopped at var_line_limit. */
4097		curr_rec_type = REC_TYPE_CONT;
4098	    } else if (VSTRING_LEN(state->bdat_get_buffer) > 0
4099		       && final_chunk && read_len == chunk_size - done) {
4100		/* Stopped at final chunk end; handle missing end-of-line. */
4101		curr_rec_type = REC_TYPE_NORM;
4102	    } else {
4103		/* Stopped at fragment end; empty buffer or not at chunk end. */
4104		/* Skip the out_record() and VSTRING_RESET() calls below. */
4105		break;
4106	    }
4107	    start = vstring_str(state->bdat_get_buffer);
4108	    len = VSTRING_LEN(state->bdat_get_buffer);
4109	    if (state->err == CLEANUP_STAT_OK) {
4110		if (ENFORCING_SIZE_LIMIT(var_message_limit)
4111		    && var_message_limit - state->act_size < len + 2) {
4112		    state->err = CLEANUP_STAT_SIZE;
4113		    msg_warn("%s: queue file size limit exceeded",
4114			     state->queue_id ? state->queue_id : "NOQUEUE");
4115		} else {
4116		    state->act_size += len + 2;
4117		    if (*start == '.' && proxy != 0
4118			&& state->bdat_prev_rec_type != REC_TYPE_CONT)
4119			if (out_record(out_stream, REC_TYPE_CONT, ".", 1) < 0)
4120			    state->err = out_error;
4121		    if (state->err == CLEANUP_STAT_OK
4122			&& out_record(out_stream, curr_rec_type,
4123				      vstring_str(state->bdat_get_buffer),
4124				   VSTRING_LEN(state->bdat_get_buffer)) < 0)
4125			state->err = out_error;
4126		}
4127	    }
4128	    VSTRING_RESET(state->bdat_get_buffer);
4129	    state->bdat_prev_rec_type = curr_rec_type;
4130	} while (!vstream_feof(state->bdat_get_stream));
4131	done += read_len;
4132    } while (done < chunk_size);
4133
4134    /*
4135     * Special handling for BDAT LAST (successful or unsuccessful).
4136     */
4137    if (final_chunk) {
4138	state->where = SMTPD_AFTER_EOM;
4139	return common_post_message_handling(state);
4140    }
4141
4142    /*
4143     * Unsuccessful non-final BDAT command. common_post_message_handling()
4144     * resets all MAIL transaction state including BDAT state. To avoid
4145     * useless error messages due to pipelined BDAT commands, enter the
4146     * SMTPD_BDAT_STAT_ERROR state to accept BDAT commands and skip BDAT
4147     * payloads.
4148     */
4149    else if (state->err != CLEANUP_STAT_OK) {
4150	/* NOT: state->where = SMTPD_AFTER_EOM; */
4151	(void) common_post_message_handling(state);
4152	state->bdat_state = SMTPD_BDAT_STAT_ERROR;
4153	return (-1);
4154    }
4155
4156    /*
4157     * Successful non-final BDAT command.
4158     */
4159    else {
4160	smtpd_chat_reply(state, "250 2.0.0 Ok: %ld bytes", (long) chunk_size);
4161	return (0);
4162    }
4163}
4164
4165/* rset_cmd - process RSET */
4166
4167static int rset_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *unused_argv)
4168{
4169
4170    /*
4171     * Sanity checks.
4172     */
4173    if (argc != 1) {
4174	state->error_mask |= MAIL_ERROR_PROTOCOL;
4175	smtpd_chat_reply(state, "501 5.5.4 Syntax: RSET");
4176	return (-1);
4177    }
4178
4179    /*
4180     * Restore state to right after HELO/EHLO command.
4181     */
4182    chat_reset(state, var_smtpd_hist_thrsh);
4183    mail_reset(state);
4184    rcpt_reset(state);
4185    smtpd_chat_reply(state, "250 2.0.0 Ok");
4186    return (0);
4187}
4188
4189/* noop_cmd - process NOOP */
4190
4191static int noop_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *unused_argv)
4192{
4193
4194    /*
4195     * XXX 2821 incompatibility: Section 4.1.1.9 says that NOOP can have a
4196     * parameter string which is to be ignored. NOOP instructions with
4197     * parameters? Go figure.
4198     *
4199     * RFC 2821 violates RFC 821, which says that NOOP takes no parameters.
4200     */
4201#ifdef RFC821_SYNTAX
4202
4203    /*
4204     * Sanity checks.
4205     */
4206    if (argc != 1) {
4207	state->error_mask |= MAIL_ERROR_PROTOCOL;
4208	smtpd_chat_reply(state, "501 5.5.4 Syntax: NOOP");
4209	return (-1);
4210    }
4211#endif
4212    smtpd_chat_reply(state, "250 2.0.0 Ok");
4213    return (0);
4214}
4215
4216/* vrfy_cmd - process VRFY */
4217
4218static int vrfy_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *argv)
4219{
4220    const char *err = 0;
4221    int     rate;
4222    int     smtputf8 = 0;
4223    int     saved_flags;
4224
4225    /*
4226     * The SMTP standard (RFC 821) disallows unquoted special characters in
4227     * the VRFY argument. Common practice violates the standard, however.
4228     * Postfix accommodates common practice where it violates the standard.
4229     *
4230     * XXX Impedance mismatch! The SMTP command tokenizer preserves quoting,
4231     * whereas the recipient restrictions checks expect unquoted (internal)
4232     * address forms. Therefore we must parse out the address, or we must
4233     * stop doing recipient restriction checks and lose the opportunity to
4234     * say "user unknown" at the SMTP port.
4235     *
4236     * XXX 2821 incompatibility and brain damage: Section 4.5.1 requires that
4237     * VRFY is implemented. RFC 821 specifies that VRFY is optional. It gets
4238     * even worse: section 3.5.3 says that a 502 (command recognized but not
4239     * implemented) reply is not fully compliant.
4240     *
4241     * Thus, an RFC 2821 compliant implementation cannot refuse to supply
4242     * information in reply to VRFY queries. That is simply bogus. The only
4243     * reply we could supply is a generic 252 reply. This causes spammers to
4244     * add tons of bogus addresses to their mailing lists (spam harvesting by
4245     * trying out large lists of potential recipient names with VRFY).
4246     */
4247#define SLOPPY	0
4248
4249    if (var_disable_vrfy_cmd) {
4250	state->error_mask |= MAIL_ERROR_POLICY;
4251	smtpd_chat_reply(state, "502 5.5.1 VRFY command is disabled");
4252	return (-1);
4253    }
4254    /* Fix 20140707: handle missing address. */
4255    if (var_smtputf8_enable
4256	&& (state->ehlo_discard_mask & EHLO_MASK_SMTPUTF8) == 0
4257	&& argc > 1 && strcasecmp(argv[argc - 1].strval, "SMTPUTF8") == 0) {
4258	argc--;					/* RFC 6531 */
4259	smtputf8 = 1;
4260    }
4261    if (argc < 2) {
4262	state->error_mask |= MAIL_ERROR_PROTOCOL;
4263	smtpd_chat_reply(state, "501 5.5.4 Syntax: VRFY address%s",
4264			 var_smtputf8_enable ? " [SMTPUTF8]" : "");
4265	return (-1);
4266    }
4267
4268    /*
4269     * XXX The client event count/rate control must be consistent in its use
4270     * of client address information in connect and disconnect events. For
4271     * now we exclude xclient authorized hosts from event count/rate control.
4272     */
4273    if (SMTPD_STAND_ALONE(state) == 0
4274	&& !xclient_allowed
4275	&& anvil_clnt
4276	&& var_smtpd_crcpt_limit > 0
4277	&& !namadr_list_match(hogger_list, state->name, state->addr)
4278	&& anvil_clnt_rcpt(anvil_clnt, state->service, state->anvil_range,
4279			   &rate) == ANVIL_STAT_OK
4280	&& rate > var_smtpd_crcpt_limit) {
4281	state->error_mask |= MAIL_ERROR_POLICY;
4282	msg_warn("Recipient address rate limit exceeded: %d from %s for service %s",
4283		 rate, state->namaddr, state->service);
4284	smtpd_chat_reply(state, "450 4.7.1 Error: too many recipients from %s",
4285			 state->addr);
4286	return (-1);
4287    }
4288    if (state->milters != 0 && (err = milter_other_event(state->milters)) != 0
4289	&& (err[0] == '5' || err[0] == '4')) {
4290	state->error_mask |= MAIL_ERROR_POLICY;
4291	smtpd_chat_reply(state, "%s", err);
4292	return (-1);
4293    }
4294    if (argc > 2)
4295	collapse_args(argc - 1, argv + 1);
4296    if (extract_addr(state, argv + 1, REJECT_EMPTY_ADDR, SLOPPY, smtputf8) != 0) {
4297	state->error_mask |= MAIL_ERROR_PROTOCOL;
4298	smtpd_chat_reply(state, "501 5.1.3 Bad recipient address syntax");
4299	return (-1);
4300    }
4301    /* Fix 20140707: Check the VRFY command. */
4302    if (smtputf8 == 0 && var_strict_smtputf8) {
4303	if (*STR(state->addr_buf) && !allascii(STR(state->addr_buf))) {
4304	    mail_reset(state);
4305	    smtpd_chat_reply(state, "553 5.6.7 Must declare SMTPUTF8 to send unicode address");
4306	    return (-1);
4307	}
4308    }
4309    /* Use state->addr_buf, with the unquoted result from extract_addr() */
4310    if (SMTPD_STAND_ALONE(state) == 0) {
4311	/* Fix 20161206: allow UTF8 in smtpd_recipient_restrictions. */
4312	saved_flags = state->flags;
4313	if (smtputf8)
4314	    state->flags |= SMTPD_FLAG_SMTPUTF8;
4315	err = smtpd_check_rcpt(state, STR(state->addr_buf));
4316	state->flags = saved_flags;
4317	if (err != 0) {
4318	    smtpd_chat_reply(state, "%s", err);
4319	    return (-1);
4320	}
4321    }
4322
4323    /*
4324     * XXX 2821 new feature: Section 3.5.1 requires that the VRFY response is
4325     * either "full name <user@domain>" or "user@domain". Postfix replies
4326     * with the string that was provided by the client, whether or not it is
4327     * in fully qualified domain form and the address is in <>.
4328     *
4329     * Reply code 250 is reserved for the case where the address is verified;
4330     * reply code 252 should be used when no definitive certainty exists.
4331     */
4332    smtpd_chat_reply(state, "252 2.0.0 %s", argv[1].strval);
4333    return (0);
4334}
4335
4336/* etrn_cmd - process ETRN command */
4337
4338static int etrn_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *argv)
4339{
4340    const char *err;
4341
4342    /*
4343     * Sanity checks.
4344     */
4345    if (var_helo_required && state->helo_name == 0) {
4346	state->error_mask |= MAIL_ERROR_POLICY;
4347	smtpd_chat_reply(state, "503 Error: send HELO/EHLO first");
4348	return (-1);
4349    }
4350    if (state->milters != 0 && (err = milter_other_event(state->milters)) != 0
4351	&& (err[0] == '5' || err[0] == '4')) {
4352	state->error_mask |= MAIL_ERROR_POLICY;
4353	smtpd_chat_reply(state, "%s", err);
4354	return (-1);
4355    }
4356    if (SMTPD_IN_MAIL_TRANSACTION(state)) {
4357	state->error_mask |= MAIL_ERROR_PROTOCOL;
4358	smtpd_chat_reply(state, "503 Error: MAIL transaction in progress");
4359	return (-1);
4360    }
4361    if (argc != 2) {
4362	state->error_mask |= MAIL_ERROR_PROTOCOL;
4363	smtpd_chat_reply(state, "500 Syntax: ETRN domain");
4364	return (-1);
4365    }
4366    if (argv[1].strval[0] == '@' || argv[1].strval[0] == '#')
4367	argv[1].strval++;
4368
4369    /*
4370     * As an extension to RFC 1985 we also allow an RFC 2821 address literal
4371     * enclosed in [].
4372     *
4373     * XXX There does not appear to be an ETRN parameter to indicate that the
4374     * domain name is UTF-8.
4375     */
4376    if (!valid_hostname(argv[1].strval, DONT_GRIPE)
4377	&& !valid_mailhost_literal(argv[1].strval, DONT_GRIPE)) {
4378	state->error_mask |= MAIL_ERROR_PROTOCOL;
4379	smtpd_chat_reply(state, "501 Error: invalid parameter syntax");
4380	return (-1);
4381    }
4382
4383    /*
4384     * XXX The implementation borrows heavily from the code that implements
4385     * UCE restrictions. These typically return 450 or 550 when a request is
4386     * rejected. RFC 1985 requires that 459 be sent when the server refuses
4387     * to perform the request.
4388     */
4389    if (SMTPD_STAND_ALONE(state)) {
4390	msg_warn("do not use ETRN in \"sendmail -bs\" mode");
4391	smtpd_chat_reply(state, "458 Unable to queue messages");
4392	return (-1);
4393    }
4394    if ((err = smtpd_check_etrn(state, argv[1].strval)) != 0) {
4395	smtpd_chat_reply(state, "%s", err);
4396	return (-1);
4397    }
4398    switch (flush_send_site(argv[1].strval)) {
4399    case FLUSH_STAT_OK:
4400	smtpd_chat_reply(state, "250 Queuing started");
4401	return (0);
4402    case FLUSH_STAT_DENY:
4403	msg_warn("reject: ETRN %.100s... from %s",
4404		 argv[1].strval, state->namaddr);
4405	smtpd_chat_reply(state, "459 <%s>: service unavailable",
4406			 argv[1].strval);
4407	return (-1);
4408    case FLUSH_STAT_BAD:
4409	msg_warn("bad ETRN %.100s... from %s", argv[1].strval, state->namaddr);
4410	smtpd_chat_reply(state, "458 Unable to queue messages");
4411	return (-1);
4412    default:
4413	msg_warn("unable to talk to fast flush service");
4414	smtpd_chat_reply(state, "458 Unable to queue messages");
4415	return (-1);
4416    }
4417}
4418
4419/* quit_cmd - process QUIT command */
4420
4421static int quit_cmd(SMTPD_STATE *state, int unused_argc, SMTPD_TOKEN *unused_argv)
4422{
4423    int     out_pending = vstream_bufstat(state->client, VSTREAM_BST_OUT_PEND);
4424
4425    /*
4426     * Don't bother checking the syntax.
4427     */
4428    smtpd_chat_reply(state, "221 2.0.0 Bye");
4429
4430    /*
4431     * When the "." and quit replies are pipelined, make sure they are
4432     * flushed now, to avoid repeated mail deliveries in case of a crash in
4433     * the "clean up before disconnect" code.
4434     *
4435     * XXX When this was added in Postfix 2.1 we used vstream_fflush(). As of
4436     * Postfix 2.3 we use smtp_flush() for better error reporting.
4437     */
4438    if (out_pending > 0)
4439	smtp_flush(state->client);
4440    return (0);
4441}
4442
4443/* xclient_cmd - override SMTP client attributes */
4444
4445static int xclient_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *argv)
4446{
4447    SMTPD_TOKEN *argp;
4448    char   *raw_value;
4449    char   *attr_value;
4450    char   *attr_name;
4451    int     update_namaddr = 0;
4452    int     name_status;
4453    static const NAME_CODE peer_codes[] = {
4454	XCLIENT_UNAVAILABLE, SMTPD_PEER_CODE_PERM,
4455	XCLIENT_TEMPORARY, SMTPD_PEER_CODE_TEMP,
4456	0, SMTPD_PEER_CODE_OK,
4457    };
4458    static const NAME_CODE proto_names[] = {
4459	MAIL_PROTO_SMTP, 1,
4460	MAIL_PROTO_ESMTP, 2,
4461	0, -1,
4462    };
4463    int     got_helo = 0;
4464    int     got_proto = 0;
4465
4466#ifdef USE_SASL_AUTH
4467    int     got_login = 0;
4468    char   *saved_username;
4469
4470#endif
4471
4472    /*
4473     * Sanity checks.
4474     *
4475     * XXX The XCLIENT command will override its own access control, so that
4476     * connection count/rate restrictions can be correctly simulated.
4477     */
4478    if (SMTPD_IN_MAIL_TRANSACTION(state)) {
4479	state->error_mask |= MAIL_ERROR_PROTOCOL;
4480	smtpd_chat_reply(state, "503 5.5.1 Error: MAIL transaction in progress");
4481	return (-1);
4482    }
4483    if (argc < 2) {
4484	state->error_mask |= MAIL_ERROR_PROTOCOL;
4485	smtpd_chat_reply(state, "501 5.5.4 Syntax: %s attribute=value...",
4486			 XCLIENT_CMD);
4487	return (-1);
4488    }
4489    if (xclient_hosts && xclient_hosts->error)
4490	cant_permit_command(state, XCLIENT_CMD);
4491    if (!xclient_allowed) {
4492	state->error_mask |= MAIL_ERROR_POLICY;
4493	smtpd_chat_reply(state, "550 5.7.0 Error: insufficient authorization");
4494	return (-1);
4495    }
4496#define STREQ(x,y)	(strcasecmp((x), (y)) == 0)
4497
4498    /*
4499     * Initialize.
4500     */
4501    if (state->expand_buf == 0)
4502	state->expand_buf = vstring_alloc(100);
4503
4504    /*
4505     * Iterate over all attribute=value elements.
4506     */
4507    for (argp = argv + 1; argp < argv + argc; argp++) {
4508	attr_name = argp->strval;
4509
4510	if ((raw_value = split_at(attr_name, '=')) == 0 || *raw_value == 0) {
4511	    state->error_mask |= MAIL_ERROR_PROTOCOL;
4512	    smtpd_chat_reply(state, "501 5.5.4 Error: attribute=value expected");
4513	    return (-1);
4514	}
4515	if (strlen(raw_value) > 255) {
4516	    state->error_mask |= MAIL_ERROR_PROTOCOL;
4517	    smtpd_chat_reply(state, "501 5.5.4 Error: attribute value too long");
4518	    return (-1);
4519	}
4520
4521	/*
4522	 * Backwards compatibility: Postfix prior to version 2.3 does not
4523	 * xtext encode attribute values.
4524	 */
4525	attr_value = xtext_unquote(state->expand_buf, raw_value) ?
4526	    STR(state->expand_buf) : raw_value;
4527
4528	/*
4529	 * For safety's sake mask non-printable characters. We'll do more
4530	 * specific censoring later.
4531	 */
4532	printable(attr_value, '?');
4533
4534#define UPDATE_STR(s, v) do { \
4535	const char *_v = (v); \
4536	if (s) myfree(s); \
4537	(s) = (_v) ? mystrdup(_v) : 0; \
4538    } while(0)
4539
4540	/*
4541	 * NAME=substitute SMTP client hostname (and reverse/forward name, in
4542	 * case of success). Also updates the client hostname lookup status
4543	 * code.
4544	 */
4545	if (STREQ(attr_name, XCLIENT_NAME)) {
4546	    name_status = name_code(peer_codes, NAME_CODE_FLAG_NONE, attr_value);
4547	    if (name_status != SMTPD_PEER_CODE_OK) {
4548		attr_value = CLIENT_NAME_UNKNOWN;
4549	    } else {
4550		/* XXX EAI */
4551		if (!valid_hostname(attr_value, DONT_GRIPE)) {
4552		    state->error_mask |= MAIL_ERROR_PROTOCOL;
4553		    smtpd_chat_reply(state, "501 5.5.4 Bad %s syntax: %s",
4554				     XCLIENT_NAME, attr_value);
4555		    return (-1);
4556		}
4557	    }
4558	    state->name_status = name_status;
4559	    UPDATE_STR(state->name, attr_value);
4560	    update_namaddr = 1;
4561	    if (name_status == SMTPD_PEER_CODE_OK) {
4562		UPDATE_STR(state->reverse_name, attr_value);
4563		state->reverse_name_status = name_status;
4564	    }
4565	}
4566
4567	/*
4568	 * REVERSE_NAME=substitute SMTP client reverse hostname. Also updates
4569	 * the client reverse hostname lookup status code.
4570	 */
4571	else if (STREQ(attr_name, XCLIENT_REVERSE_NAME)) {
4572	    name_status = name_code(peer_codes, NAME_CODE_FLAG_NONE, attr_value);
4573	    if (name_status != SMTPD_PEER_CODE_OK) {
4574		attr_value = CLIENT_NAME_UNKNOWN;
4575	    } else {
4576		/* XXX EAI */
4577		if (!valid_hostname(attr_value, DONT_GRIPE)) {
4578		    state->error_mask |= MAIL_ERROR_PROTOCOL;
4579		    smtpd_chat_reply(state, "501 5.5.4 Bad %s syntax: %s",
4580				     XCLIENT_REVERSE_NAME, attr_value);
4581		    return (-1);
4582		}
4583	    }
4584	    state->reverse_name_status = name_status;
4585	    UPDATE_STR(state->reverse_name, attr_value);
4586	}
4587
4588	/*
4589	 * ADDR=substitute SMTP client network address.
4590	 */
4591	else if (STREQ(attr_name, XCLIENT_ADDR)) {
4592	    if (STREQ(attr_value, XCLIENT_UNAVAILABLE)) {
4593		attr_value = CLIENT_ADDR_UNKNOWN;
4594		UPDATE_STR(state->addr, attr_value);
4595		UPDATE_STR(state->rfc_addr, attr_value);
4596	    } else {
4597		neuter(attr_value, NEUTER_CHARACTERS, '?');
4598		if (normalize_mailhost_addr(attr_value, &state->rfc_addr,
4599					    &state->addr,
4600					    &state->addr_family) < 0) {
4601		    state->error_mask |= MAIL_ERROR_PROTOCOL;
4602		    smtpd_chat_reply(state, "501 5.5.4 Bad %s syntax: %s",
4603				     XCLIENT_ADDR, attr_value);
4604		    return (-1);
4605		}
4606	    }
4607	    update_namaddr = 1;
4608	}
4609
4610	/*
4611	 * PORT=substitute SMTP client port number.
4612	 */
4613	else if (STREQ(attr_name, XCLIENT_PORT)) {
4614	    if (STREQ(attr_value, XCLIENT_UNAVAILABLE)) {
4615		attr_value = CLIENT_PORT_UNKNOWN;
4616	    } else {
4617		if (!alldig(attr_value)
4618		    || strlen(attr_value) > sizeof("65535") - 1) {
4619		    state->error_mask |= MAIL_ERROR_PROTOCOL;
4620		    smtpd_chat_reply(state, "501 5.5.4 Bad %s syntax: %s",
4621				     XCLIENT_PORT, attr_value);
4622		    return (-1);
4623		}
4624	    }
4625	    UPDATE_STR(state->port, attr_value);
4626	    update_namaddr = 1;
4627	}
4628
4629	/*
4630	 * HELO=substitute SMTP client HELO parameter. Censor special
4631	 * characters that could mess up message headers.
4632	 */
4633	else if (STREQ(attr_name, XCLIENT_HELO)) {
4634	    if (STREQ(attr_value, XCLIENT_UNAVAILABLE)) {
4635		attr_value = CLIENT_HELO_UNKNOWN;
4636	    } else {
4637		if (strlen(attr_value) > VALID_HOSTNAME_LEN) {
4638		    state->error_mask |= MAIL_ERROR_PROTOCOL;
4639		    smtpd_chat_reply(state, "501 5.5.4 Bad %s syntax: %s",
4640				     XCLIENT_HELO, attr_value);
4641		    return (-1);
4642		}
4643		neuter(attr_value, NEUTER_CHARACTERS, '?');
4644	    }
4645	    UPDATE_STR(state->helo_name, attr_value);
4646	    got_helo = 1;
4647	}
4648
4649	/*
4650	 * PROTO=SMTP protocol name.
4651	 */
4652	else if (STREQ(attr_name, XCLIENT_PROTO)) {
4653	    if (name_code(proto_names, NAME_CODE_FLAG_NONE, attr_value) < 0) {
4654		state->error_mask |= MAIL_ERROR_PROTOCOL;
4655		smtpd_chat_reply(state, "501 5.5.4 Bad %s syntax: %s",
4656				 XCLIENT_PROTO, attr_value);
4657		return (-1);
4658	    }
4659	    UPDATE_STR(state->protocol, uppercase(attr_value));
4660	    got_proto = 1;
4661	}
4662
4663	/*
4664	 * LOGIN=sasl_username. Sets the authentication method as XCLIENT.
4665	 * This can be used even if SASL authentication is turned off in
4666	 * main.cf. We can't make it easier than that.
4667	 */
4668#ifdef USE_SASL_AUTH
4669	else if (STREQ(attr_name, XCLIENT_LOGIN)) {
4670	    if (STREQ(attr_value, XCLIENT_UNAVAILABLE) == 0) {
4671		smtpd_sasl_auth_extern(state, attr_value, XCLIENT_CMD);
4672		got_login = 1;
4673	    }
4674	}
4675#endif
4676
4677	/*
4678	 * DESTADDR=substitute SMTP server network address.
4679	 */
4680	else if (STREQ(attr_name, XCLIENT_DESTADDR)) {
4681	    if (STREQ(attr_value, XCLIENT_UNAVAILABLE)) {
4682		attr_value = SERVER_ADDR_UNKNOWN;
4683		UPDATE_STR(state->dest_addr, attr_value);
4684	    } else {
4685#define NO_NORM_RFC_ADDR		((char **) 0)
4686#define NO_NORM_ADDR_FAMILY	((int *) 0)
4687		neuter(attr_value, NEUTER_CHARACTERS, '?');
4688		if (normalize_mailhost_addr(attr_value, NO_NORM_RFC_ADDR,
4689					    &state->dest_addr,
4690					    NO_NORM_ADDR_FAMILY) < 0) {
4691		    state->error_mask |= MAIL_ERROR_PROTOCOL;
4692		    smtpd_chat_reply(state, "501 5.5.4 Bad %s syntax: %s",
4693				     XCLIENT_DESTADDR, attr_value);
4694		    return (-1);
4695		}
4696	    }
4697	    /* XXX Require same address family as client address. */
4698	}
4699
4700	/*
4701	 * DESTPORT=substitute SMTP server port number.
4702	 */
4703	else if (STREQ(attr_name, XCLIENT_DESTPORT)) {
4704	    if (STREQ(attr_value, XCLIENT_UNAVAILABLE)) {
4705		attr_value = SERVER_PORT_UNKNOWN;
4706	    } else {
4707		if (!alldig(attr_value)
4708		    || strlen(attr_value) > sizeof("65535") - 1) {
4709		    state->error_mask |= MAIL_ERROR_PROTOCOL;
4710		    smtpd_chat_reply(state, "501 5.5.4 Bad %s syntax: %s",
4711				     XCLIENT_DESTPORT, attr_value);
4712		    return (-1);
4713		}
4714	    }
4715	    UPDATE_STR(state->dest_port, attr_value);
4716	}
4717
4718	/*
4719	 * Unknown attribute name. Complain.
4720	 */
4721	else {
4722	    state->error_mask |= MAIL_ERROR_PROTOCOL;
4723	    smtpd_chat_reply(state, "501 5.5.4 Bad %s attribute name: %s",
4724			     XCLIENT_CMD, attr_name);
4725	    return (-1);
4726	}
4727    }
4728
4729    /*
4730     * Update the combined name and address when either has changed.
4731     */
4732    if (update_namaddr) {
4733	if (state->namaddr)
4734	    myfree(state->namaddr);
4735	state->namaddr =
4736	    SMTPD_BUILD_NAMADDRPORT(state->name, state->addr, state->port);
4737    }
4738
4739    /*
4740     * XXX Compatibility: when the client issues XCLIENT then we have to go
4741     * back to initial server greeting stage, otherwise we can't correctly
4742     * simulate smtpd_client_restrictions (with smtpd_delay_reject=0) and
4743     * Milter connect restrictions.
4744     *
4745     * XXX Compatibility: for accurate simulation we must also reset the HELO
4746     * information. We keep the information if it was specified in the
4747     * XCLIENT command.
4748     *
4749     * XXX The client connection count/rate control must be consistent in its
4750     * use of client address information in connect and disconnect events. We
4751     * re-evaluate xclient so that we correctly simulate connection
4752     * concurrency and connection rate restrictions.
4753     *
4754     * XXX Duplicated from smtpd_proto().
4755     */
4756    xclient_allowed =
4757	namadr_list_match(xclient_hosts, state->name, state->addr);
4758    smtp_forbid_bare_lf = SMTPD_STAND_ALONE((state)) == 0
4759	&& var_smtpd_forbid_bare_lf
4760	&& !namadr_list_match(bare_lf_excl, state->name, state->addr);
4761    /* NOT: tls_reset() */
4762    if (got_helo == 0)
4763	helo_reset(state);
4764    if (got_proto == 0 && strcasecmp(state->protocol, MAIL_PROTO_SMTP) != 0) {
4765	myfree(state->protocol);
4766	state->protocol = mystrdup(MAIL_PROTO_SMTP);
4767    }
4768#ifdef USE_SASL_AUTH
4769    /* XXX What if they send the parameters via multiple commands? */
4770    if (got_login == 0)
4771	smtpd_sasl_auth_reset(state);
4772    if (smtpd_sasl_is_active(state)) {
4773	if (got_login)
4774	    saved_username = mystrdup(state->sasl_username);
4775	smtpd_sasl_deactivate(state);
4776#ifdef USE_TLS
4777	if (state->tls_context != 0)		/* TLS from XCLIENT proxy? */
4778	    smtpd_sasl_activate(state, VAR_SMTPD_SASL_TLS_OPTS,
4779				var_smtpd_sasl_tls_opts);
4780	else
4781#endif
4782	    smtpd_sasl_activate(state, VAR_SMTPD_SASL_OPTS,
4783				var_smtpd_sasl_opts);
4784	if (got_login) {
4785	    smtpd_sasl_auth_extern(state, saved_username, XCLIENT_CMD);
4786	    myfree(saved_username);
4787	}
4788    }
4789#endif
4790    chat_reset(state, 0);
4791    mail_reset(state);
4792    rcpt_reset(state);
4793    if (state->milters)
4794	milter_disc_event(state->milters);
4795    /* Following duplicates the top-level connect/disconnect handler. */
4796    teardown_milters(state);
4797    setup_milters(state);
4798    vstream_longjmp(state->client, SMTP_ERR_NONE);
4799    return (0);
4800}
4801
4802/* xforward_cmd - forward logging attributes */
4803
4804static int xforward_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *argv)
4805{
4806    SMTPD_TOKEN *argp;
4807    char   *raw_value;
4808    char   *attr_value;
4809    char   *attr_name;
4810    int     updated = 0;
4811    static const NAME_CODE xforward_flags[] = {
4812	XFORWARD_NAME, SMTPD_STATE_XFORWARD_NAME,
4813	XFORWARD_ADDR, SMTPD_STATE_XFORWARD_ADDR,
4814	XFORWARD_PORT, SMTPD_STATE_XFORWARD_PORT,
4815	XFORWARD_PROTO, SMTPD_STATE_XFORWARD_PROTO,
4816	XFORWARD_HELO, SMTPD_STATE_XFORWARD_HELO,
4817	XFORWARD_IDENT, SMTPD_STATE_XFORWARD_IDENT,
4818	XFORWARD_DOMAIN, SMTPD_STATE_XFORWARD_DOMAIN,
4819	0, 0,
4820    };
4821    static const char *context_name[] = {
4822	MAIL_ATTR_RWR_LOCAL,		/* Postfix internal form */
4823	MAIL_ATTR_RWR_REMOTE,		/* Postfix internal form */
4824    };
4825    static const NAME_CODE xforward_to_context[] = {
4826	XFORWARD_DOM_LOCAL, 0,		/* XFORWARD representation */
4827	XFORWARD_DOM_REMOTE, 1,		/* XFORWARD representation */
4828	0, -1,
4829    };
4830    int     flag;
4831    int     context_code;
4832
4833    /*
4834     * Sanity checks.
4835     */
4836    if (SMTPD_IN_MAIL_TRANSACTION(state)) {
4837	state->error_mask |= MAIL_ERROR_PROTOCOL;
4838	smtpd_chat_reply(state, "503 5.5.1 Error: MAIL transaction in progress");
4839	return (-1);
4840    }
4841    if (argc < 2) {
4842	state->error_mask |= MAIL_ERROR_PROTOCOL;
4843	smtpd_chat_reply(state, "501 5.5.4 Syntax: %s attribute=value...",
4844			 XFORWARD_CMD);
4845	return (-1);
4846    }
4847    if (xforward_hosts && xforward_hosts->error)
4848	cant_permit_command(state, XFORWARD_CMD);
4849    if (!xforward_allowed) {
4850	state->error_mask |= MAIL_ERROR_POLICY;
4851	smtpd_chat_reply(state, "550 5.7.0 Error: insufficient authorization");
4852	return (-1);
4853    }
4854
4855    /*
4856     * Initialize.
4857     */
4858    if (state->xforward.flags == 0)
4859	smtpd_xforward_preset(state);
4860    if (state->expand_buf == 0)
4861	state->expand_buf = vstring_alloc(100);
4862
4863    /*
4864     * Iterate over all attribute=value elements.
4865     */
4866    for (argp = argv + 1; argp < argv + argc; argp++) {
4867	attr_name = argp->strval;
4868
4869	if ((raw_value = split_at(attr_name, '=')) == 0 || *raw_value == 0) {
4870	    state->error_mask |= MAIL_ERROR_PROTOCOL;
4871	    smtpd_chat_reply(state, "501 5.5.4 Error: attribute=value expected");
4872	    return (-1);
4873	}
4874	if (strlen(raw_value) > 255) {
4875	    state->error_mask |= MAIL_ERROR_PROTOCOL;
4876	    smtpd_chat_reply(state, "501 5.5.4 Error: attribute value too long");
4877	    return (-1);
4878	}
4879
4880	/*
4881	 * Backwards compatibility: Postfix prior to version 2.3 does not
4882	 * xtext encode attribute values.
4883	 */
4884	attr_value = xtext_unquote(state->expand_buf, raw_value) ?
4885	    STR(state->expand_buf) : raw_value;
4886
4887	/*
4888	 * For safety's sake mask non-printable characters. We'll do more
4889	 * specific censoring later.
4890	 */
4891	printable(attr_value, '?');
4892
4893	flag = name_code(xforward_flags, NAME_CODE_FLAG_NONE, attr_name);
4894	switch (flag) {
4895
4896	    /*
4897	     * NAME=up-stream host name, not necessarily in the DNS. Censor
4898	     * special characters that could mess up message headers.
4899	     */
4900	case SMTPD_STATE_XFORWARD_NAME:
4901	    if (STREQ(attr_value, XFORWARD_UNAVAILABLE)) {
4902		attr_value = CLIENT_NAME_UNKNOWN;
4903	    } else {
4904		/* XXX EAI */
4905		neuter(attr_value, NEUTER_CHARACTERS, '?');
4906		if (!valid_hostname(attr_value, DONT_GRIPE)) {
4907		    state->error_mask |= MAIL_ERROR_PROTOCOL;
4908		    smtpd_chat_reply(state, "501 5.5.4 Bad %s syntax: %s",
4909				     XFORWARD_NAME, attr_value);
4910		    return (-1);
4911		}
4912	    }
4913	    UPDATE_STR(state->xforward.name, attr_value);
4914	    break;
4915
4916	    /*
4917	     * ADDR=up-stream host network address, not necessarily on the
4918	     * Internet. Censor special characters that could mess up message
4919	     * headers.
4920	     */
4921	case SMTPD_STATE_XFORWARD_ADDR:
4922	    if (STREQ(attr_value, XFORWARD_UNAVAILABLE)) {
4923		attr_value = CLIENT_ADDR_UNKNOWN;
4924		UPDATE_STR(state->xforward.addr, attr_value);
4925	    } else {
4926		neuter(attr_value, NEUTER_CHARACTERS, '?');
4927		if (normalize_mailhost_addr(attr_value,
4928					    &state->xforward.rfc_addr,
4929					    &state->xforward.addr,
4930					    NO_NORM_ADDR_FAMILY) < 0) {
4931		    state->error_mask |= MAIL_ERROR_PROTOCOL;
4932		    smtpd_chat_reply(state, "501 5.5.4 Bad %s syntax: %s",
4933				     XFORWARD_ADDR, attr_value);
4934		    return (-1);
4935		}
4936	    }
4937	    break;
4938
4939	    /*
4940	     * PORT=up-stream port number.
4941	     */
4942	case SMTPD_STATE_XFORWARD_PORT:
4943	    if (STREQ(attr_value, XFORWARD_UNAVAILABLE)) {
4944		attr_value = CLIENT_PORT_UNKNOWN;
4945	    } else {
4946		if (!alldig(attr_value)
4947		    || strlen(attr_value) > sizeof("65535") - 1) {
4948		    state->error_mask |= MAIL_ERROR_PROTOCOL;
4949		    smtpd_chat_reply(state, "501 5.5.4 Bad %s syntax: %s",
4950				     XFORWARD_PORT, attr_value);
4951		    return (-1);
4952		}
4953	    }
4954	    UPDATE_STR(state->xforward.port, attr_value);
4955	    break;
4956
4957	    /*
4958	     * HELO=hostname that the up-stream MTA introduced itself with
4959	     * (not necessarily SMTP HELO). Censor special characters that
4960	     * could mess up message headers.
4961	     */
4962	case SMTPD_STATE_XFORWARD_HELO:
4963	    if (STREQ(attr_value, XFORWARD_UNAVAILABLE)) {
4964		attr_value = CLIENT_HELO_UNKNOWN;
4965	    } else {
4966		neuter(attr_value, NEUTER_CHARACTERS, '?');
4967	    }
4968	    UPDATE_STR(state->xforward.helo_name, attr_value);
4969	    break;
4970
4971	    /*
4972	     * PROTO=up-stream protocol, not necessarily SMTP or ESMTP.
4973	     * Censor special characters that could mess up message headers.
4974	     */
4975	case SMTPD_STATE_XFORWARD_PROTO:
4976	    if (STREQ(attr_value, XFORWARD_UNAVAILABLE)) {
4977		attr_value = CLIENT_PROTO_UNKNOWN;
4978	    } else {
4979		if (strlen(attr_value) > 64) {
4980		    state->error_mask |= MAIL_ERROR_PROTOCOL;
4981		    smtpd_chat_reply(state, "501 5.5.4 Bad %s syntax: %s",
4982				     XFORWARD_PROTO, attr_value);
4983		    return (-1);
4984		}
4985		neuter(attr_value, NEUTER_CHARACTERS, '?');
4986	    }
4987	    UPDATE_STR(state->xforward.protocol, attr_value);
4988	    break;
4989
4990	    /*
4991	     * IDENT=local message identifier on the up-stream MTA. Censor
4992	     * special characters that could mess up logging or macro
4993	     * expansions.
4994	     */
4995	case SMTPD_STATE_XFORWARD_IDENT:
4996	    if (STREQ(attr_value, XFORWARD_UNAVAILABLE)) {
4997		attr_value = CLIENT_IDENT_UNKNOWN;
4998	    } else {
4999		neuter(attr_value, NEUTER_CHARACTERS, '?');
5000	    }
5001	    UPDATE_STR(state->xforward.ident, attr_value);
5002	    break;
5003
5004	    /*
5005	     * DOMAIN=local or remote.
5006	     */
5007	case SMTPD_STATE_XFORWARD_DOMAIN:
5008	    if (STREQ(attr_value, XFORWARD_UNAVAILABLE))
5009		attr_value = XFORWARD_DOM_LOCAL;
5010	    if ((context_code = name_code(xforward_to_context,
5011					  NAME_CODE_FLAG_NONE,
5012					  attr_value)) < 0) {
5013		state->error_mask |= MAIL_ERROR_PROTOCOL;
5014		smtpd_chat_reply(state, "501 5.5.4 Bad %s syntax: %s",
5015				 XFORWARD_DOMAIN, attr_value);
5016		return (-1);
5017	    }
5018	    UPDATE_STR(state->xforward.domain, context_name[context_code]);
5019	    break;
5020
5021	    /*
5022	     * Unknown attribute name. Complain.
5023	     */
5024	default:
5025	    state->error_mask |= MAIL_ERROR_PROTOCOL;
5026	    smtpd_chat_reply(state, "501 5.5.4 Bad %s attribute name: %s",
5027			     XFORWARD_CMD, attr_name);
5028	    return (-1);
5029	}
5030	updated |= flag;
5031    }
5032    state->xforward.flags |= updated;
5033
5034    /*
5035     * Update the combined name and address when either has changed. Use only
5036     * the name when no address is available.
5037     */
5038    if (updated & (SMTPD_STATE_XFORWARD_NAME | SMTPD_STATE_XFORWARD_ADDR
5039		   | SMTPD_STATE_XFORWARD_PORT)) {
5040	if (state->xforward.namaddr)
5041	    myfree(state->xforward.namaddr);
5042	state->xforward.namaddr =
5043	    IS_AVAIL_CLIENT_ADDR(state->xforward.addr) ?
5044	    SMTPD_BUILD_NAMADDRPORT(state->xforward.name,
5045				    state->xforward.addr,
5046				    state->xforward.port) :
5047	    mystrdup(state->xforward.name);
5048    }
5049    smtpd_chat_reply(state, "250 2.0.0 Ok");
5050    return (0);
5051}
5052
5053/* chat_reset - notify postmaster and reset conversation log */
5054
5055static void chat_reset(SMTPD_STATE *state, int threshold)
5056{
5057
5058    /*
5059     * Notify the postmaster if there were errors. This usually indicates a
5060     * client configuration problem, or that someone is trying nasty things.
5061     * Either is significant enough to bother the postmaster. XXX Can't
5062     * report problems when running in stand-alone mode: postmaster notices
5063     * require availability of the cleanup service.
5064     */
5065    if (state->history != 0 && state->history->argc > threshold) {
5066	if (SMTPD_STAND_ALONE(state) == 0
5067	    && (state->error_mask & state->notify_mask))
5068	    smtpd_chat_notify(state);
5069	state->error_mask = 0;
5070	smtpd_chat_reset(state);
5071    }
5072}
5073
5074#ifdef USE_TLS
5075
5076/* smtpd_start_tls - turn on TLS or force disconnect */
5077
5078static void smtpd_start_tls(SMTPD_STATE *state)
5079{
5080    int     rate;
5081    int     cert_present;
5082    int     requirecert;
5083
5084#ifdef USE_TLSPROXY
5085
5086    /*
5087     * This is non-production code, for tlsproxy(8) load testing only. It
5088     * implements enough to enable some Postfix features that depend on TLS
5089     * encryption.
5090     *
5091     * To insert tlsproxy(8) between this process and the SMTP client, we swap
5092     * the file descriptors between the state->tlsproxy and state->client
5093     * VSTREAMS, so that we don't lose all the user-configurable
5094     * state->client attributes (such as longjump buffers or timeouts).
5095     *
5096     * As we implement tlsproxy support in the Postfix SMTP client we should
5097     * develop a usable abstraction that encapsulates this stream plumbing in
5098     * a library module.
5099     */
5100    vstream_control(state->tlsproxy, CA_VSTREAM_CTL_DOUBLE, CA_VSTREAM_CTL_END);
5101    vstream_control(state->client, CA_VSTREAM_CTL_SWAP_FD(state->tlsproxy),
5102		    CA_VSTREAM_CTL_END);
5103    (void) vstream_fclose(state->tlsproxy);	/* direct-to-client stream! */
5104    state->tlsproxy = 0;
5105
5106    /*
5107     * After plumbing the plaintext stream, receive the TLS context object.
5108     * For this we must use the same VSTREAM buffer that we also use to
5109     * receive subsequent SMTP commands. The attribute protocol is robust
5110     * enough that an adversary cannot inject their own bogus TLS context
5111     * attributes into the stream.
5112     */
5113    state->tls_context = tls_proxy_context_receive(state->client);
5114
5115    /*
5116     * XXX Maybe it is better to send this information to tlsproxy(8) when
5117     * requesting service, effectively making a remote tls_server_start()
5118     * call.
5119     */
5120    requirecert = (var_smtpd_tls_req_ccert && var_smtpd_enforce_tls);
5121
5122#else						/* USE_TLSPROXY */
5123    TLS_SERVER_START_PROPS props;
5124    static char *cipher_grade;
5125    static VSTRING *cipher_exclusions;
5126
5127    /*
5128     * Wrapper mode uses a dedicated port and always requires TLS.
5129     *
5130     * XXX In non-wrapper mode, it is possible to require client certificate
5131     * verification without requiring TLS. Since certificates can be verified
5132     * only while TLS is turned on, this means that Postfix will happily
5133     * perform SMTP transactions when the client does not use the STARTTLS
5134     * command. For this reason, Postfix does not require client certificate
5135     * verification unless TLS is required.
5136     *
5137     * The cipher grade and exclusions don't change between sessions. Compute
5138     * just once and cache.
5139     */
5140#define ADD_EXCLUDE(vstr, str) \
5141    do { \
5142	if (*(str)) \
5143	    vstring_sprintf_append((vstr), "%s%s", \
5144				   VSTRING_LEN(vstr) ? " " : "", (str)); \
5145    } while (0)
5146
5147    if (cipher_grade == 0) {
5148	cipher_grade = var_smtpd_enforce_tls ?
5149	    var_smtpd_tls_mand_ciph : var_smtpd_tls_ciph;
5150	cipher_exclusions = vstring_alloc(10);
5151	ADD_EXCLUDE(cipher_exclusions, var_smtpd_tls_excl_ciph);
5152	if (var_smtpd_enforce_tls)
5153	    ADD_EXCLUDE(cipher_exclusions, var_smtpd_tls_mand_excl);
5154	if (ask_client_cert)
5155	    ADD_EXCLUDE(cipher_exclusions, "aNULL");
5156    }
5157
5158    /*
5159     * Perform the TLS handshake now. Check the client certificate
5160     * requirements later, if necessary.
5161     */
5162    requirecert = (var_smtpd_tls_req_ccert && var_smtpd_enforce_tls);
5163
5164    state->tls_context =
5165	TLS_SERVER_START(&props,
5166			 ctx = smtpd_tls_ctx,
5167			 stream = state->client,
5168			 fd = -1,
5169			 timeout = var_smtpd_starttls_tmout,
5170			 requirecert = requirecert,
5171			 serverid = state->service,
5172			 namaddr = state->namaddr,
5173			 cipher_grade = cipher_grade,
5174			 cipher_exclusions = STR(cipher_exclusions),
5175			 mdalg = var_smtpd_tls_fpt_dgst);
5176
5177#endif						/* USE_TLSPROXY */
5178
5179    /*
5180     * For new (i.e. not re-used) TLS sessions, increment the client's new
5181     * TLS session rate counter. We enforce the limit here only for human
5182     * factors reasons (reduce the WTF factor), even though it is too late to
5183     * save the CPU that was already burnt on PKI ops. The real safety
5184     * mechanism applies with future STARTTLS commands (or wrappermode
5185     * connections), prior to the SSL handshake.
5186     *
5187     * XXX The client event count/rate control must be consistent in its use of
5188     * client address information in connect and disconnect events. For now
5189     * we exclude xclient authorized hosts from event count/rate control.
5190     */
5191    if (var_smtpd_cntls_limit > 0
5192     && (state->tls_context == 0 || state->tls_context->session_reused == 0)
5193	&& SMTPD_STAND_ALONE(state) == 0
5194	&& !xclient_allowed
5195	&& anvil_clnt
5196	&& !namadr_list_match(hogger_list, state->name, state->addr)
5197	&& anvil_clnt_newtls(anvil_clnt, state->service, state->anvil_range,
5198			     &rate) == ANVIL_STAT_OK
5199	&& rate > var_smtpd_cntls_limit) {
5200	state->error_mask |= MAIL_ERROR_POLICY;
5201	msg_warn("New TLS session rate limit exceeded: %d from %s for service %s",
5202		 rate, state->namaddr, state->service);
5203	if (state->tls_context)
5204	    smtpd_chat_reply(state,
5205		    "421 4.7.0 %s Error: too many new TLS sessions from %s",
5206			     var_myhostname, state->namaddr);
5207	/* XXX Use regular return to signal end of session. */
5208	vstream_longjmp(state->client, SMTP_ERR_QUIET);
5209    }
5210
5211    /*
5212     * When the TLS handshake fails, the conversation is in an unknown state.
5213     * There is nothing we can do except to disconnect from the client.
5214     */
5215    if (state->tls_context == 0)
5216	vstream_longjmp(state->client, SMTP_ERR_EOF);
5217
5218    /*
5219     * If we are requiring verified client certs, enforce the constraint
5220     * here. We have a usable TLS session with the client, so no need to
5221     * disable I/O, ...  we can even be polite and send "421 ...".
5222     */
5223    if (requirecert && TLS_CERT_IS_TRUSTED(state->tls_context) == 0) {
5224
5225	/*
5226	 * In non-wrappermode, fetch the next command (should be EHLO). Reply
5227	 * with 421, then disconnect (as a side-effect of replying with 421).
5228	 */
5229	cert_present = TLS_CERT_IS_PRESENT(state->tls_context);
5230	msg_info("NOQUEUE: abort: TLS from %s: %s",
5231		 state->namaddr, cert_present ?
5232		 "Client certificate not trusted" :
5233		 "No client certificate presented");
5234	if (var_smtpd_tls_wrappermode == 0)
5235	    smtpd_chat_query(state);
5236	smtpd_chat_reply(state, "421 4.7.1 %s Error: %s",
5237			 var_myhostname, cert_present ?
5238			 "Client certificate not trusted" :
5239			 "No client certificate presented");
5240	state->error_mask |= MAIL_ERROR_POLICY;
5241	return;
5242    }
5243
5244    /*
5245     * When TLS is turned on, we may offer AUTH methods that would not be
5246     * offered within a plain-text session.
5247     *
5248     * XXX Always refresh SASL the mechanism list after STARTTLS. Dovecot
5249     * responses may depend on whether the SMTP connection is encrypted.
5250     */
5251#ifdef USE_SASL_AUTH
5252    if (var_smtpd_sasl_enable) {
5253	/* Non-wrappermode, presumably. */
5254	if (smtpd_sasl_is_active(state)) {
5255	    smtpd_sasl_auth_reset(state);
5256	    smtpd_sasl_deactivate(state);
5257	}
5258	/* Wrappermode and non-wrappermode. */
5259	if (smtpd_sasl_is_active(state) == 0)
5260	    smtpd_sasl_activate(state, VAR_SMTPD_SASL_TLS_OPTS,
5261				var_smtpd_sasl_tls_opts);
5262    }
5263#endif
5264}
5265
5266/* starttls_cmd - respond to STARTTLS */
5267
5268static int starttls_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *unused_argv)
5269{
5270    const char *err;
5271    int     rate;
5272
5273    if (argc != 1) {
5274	state->error_mask |= MAIL_ERROR_PROTOCOL;
5275	smtpd_chat_reply(state, "501 5.5.4 Syntax: STARTTLS");
5276	return (-1);
5277    }
5278    if (state->milters != 0 && (err = milter_other_event(state->milters)) != 0) {
5279	if (err[0] == '5') {
5280	    state->error_mask |= MAIL_ERROR_POLICY;
5281	    smtpd_chat_reply(state, "%s", err);
5282	    return (-1);
5283	}
5284	/* Sendmail compatibility: map 4xx into 454. */
5285	else if (err[0] == '4') {
5286	    state->error_mask |= MAIL_ERROR_POLICY;
5287	    smtpd_chat_reply(state, "454 4.3.0 Try again later");
5288	    return (-1);
5289	}
5290    }
5291    if (state->tls_context != 0) {
5292	state->error_mask |= MAIL_ERROR_PROTOCOL;
5293	smtpd_chat_reply(state, "554 5.5.1 Error: TLS already active");
5294	return (-1);
5295    }
5296    if (var_smtpd_use_tls == 0
5297	|| (state->ehlo_discard_mask & EHLO_MASK_STARTTLS)) {
5298	state->error_mask |= MAIL_ERROR_PROTOCOL;
5299	smtpd_chat_reply(state, "502 5.5.1 Error: command not implemented");
5300	return (-1);
5301    }
5302#ifdef USE_TLSPROXY
5303
5304    /*
5305     * Note: state->tlsproxy is left open when smtp_flush() calls longjmp(),
5306     * so we garbage-collect the VSTREAM in smtpd_state_reset().
5307     */
5308#define PROXY_OPEN_FLAGS \
5309	(TLS_PROXY_FLAG_ROLE_SERVER | TLS_PROXY_FLAG_SEND_CONTEXT)
5310
5311    state->tlsproxy =
5312	tls_proxy_legacy_open(var_tlsproxy_service, PROXY_OPEN_FLAGS,
5313			      state->client, state->addr,
5314			      state->port, var_smtpd_tmout,
5315			      state->service);
5316    if (state->tlsproxy == 0) {
5317	state->error_mask |= MAIL_ERROR_SOFTWARE;
5318	/* RFC 3207 Section 4. */
5319	smtpd_chat_reply(state, "454 4.7.0 TLS not available due to local problem");
5320	return (-1);
5321    }
5322#else						/* USE_TLSPROXY */
5323    if (smtpd_tls_ctx == 0) {
5324	state->error_mask |= MAIL_ERROR_SOFTWARE;
5325	/* RFC 3207 Section 4. */
5326	smtpd_chat_reply(state, "454 4.7.0 TLS not available due to local problem");
5327	return (-1);
5328    }
5329#endif						/* USE_TLSPROXY */
5330
5331    /*
5332     * Enforce TLS handshake rate limit when this client negotiated too many
5333     * new TLS sessions in the recent past.
5334     *
5335     * XXX The client event count/rate control must be consistent in its use of
5336     * client address information in connect and disconnect events. For now
5337     * we exclude xclient authorized hosts from event count/rate control.
5338     */
5339    if (var_smtpd_cntls_limit > 0
5340	&& SMTPD_STAND_ALONE(state) == 0
5341	&& !xclient_allowed
5342	&& anvil_clnt
5343	&& !namadr_list_match(hogger_list, state->name, state->addr)
5344	&& anvil_clnt_newtls_stat(anvil_clnt, state->service,
5345				  state->anvil_range, &rate) == ANVIL_STAT_OK
5346	&& rate > var_smtpd_cntls_limit) {
5347	state->error_mask |= MAIL_ERROR_POLICY;
5348	msg_warn("Refusing STARTTLS request from %s for service %s",
5349		 state->namaddr, state->service);
5350	smtpd_chat_reply(state,
5351		       "454 4.7.0 Error: too many new TLS sessions from %s",
5352			 state->namaddr);
5353#ifdef USE_TLSPROXY
5354	(void) vstream_fclose(state->tlsproxy);
5355	state->tlsproxy = 0;
5356#endif
5357	return (-1);
5358    }
5359    smtpd_chat_reply(state, "220 2.0.0 Ready to start TLS");
5360    /* Flush before we switch read/write routines or file descriptors. */
5361    smtp_flush(state->client);
5362    /* At this point there must not be any pending plaintext. */
5363    vstream_fpurge(state->client, VSTREAM_PURGE_BOTH);
5364
5365    /*
5366     * Reset all inputs to the initial state.
5367     *
5368     * XXX RFC 2487 does not forbid the use of STARTTLS while mail transfer is
5369     * in progress, so we have to allow it even when it makes no sense.
5370     */
5371    helo_reset(state);
5372    mail_reset(state);
5373    rcpt_reset(state);
5374
5375    /*
5376     * Turn on TLS, using code that is shared with TLS wrapper mode. This
5377     * code does not return when the handshake fails.
5378     */
5379    smtpd_start_tls(state);
5380    return (0);
5381}
5382
5383/* tls_reset - undo STARTTLS */
5384
5385static void tls_reset(SMTPD_STATE *state)
5386{
5387    int     failure = 0;
5388
5389    /*
5390     * Don't waste time when we lost contact.
5391     */
5392    if (state->tls_context) {
5393	if (vstream_feof(state->client) || vstream_ferror(state->client))
5394	    failure = 1;
5395	vstream_fflush(state->client);		/* NOT: smtp_flush() */
5396#ifdef USE_TLSPROXY
5397	tls_proxy_context_free(state->tls_context);
5398#else
5399	tls_server_stop(smtpd_tls_ctx, state->client, var_smtpd_starttls_tmout,
5400			failure, state->tls_context);
5401#endif
5402	state->tls_context = 0;
5403    }
5404}
5405
5406#endif
5407
5408#if !defined(USE_TLS) || !defined(USE_SASL_AUTH)
5409
5410/* unimpl_cmd - dummy for functionality that is not compiled in */
5411
5412static int unimpl_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *unused_argv)
5413{
5414
5415    /*
5416     * When a connection is closed we want to log the request counts for
5417     * unimplemented STARTTLS or AUTH commands separately, instead of logging
5418     * those commands as "unknown". By handling unimplemented commands with
5419     * this dummy function, we avoid messing up the command processing loop.
5420     */
5421    state->error_mask |= MAIL_ERROR_PROTOCOL;
5422    smtpd_chat_reply(state, "502 5.5.1 Error: command not implemented");
5423    return (-1);
5424}
5425
5426#endif
5427
5428 /*
5429  * The table of all SMTP commands that we know. Set the junk limit flag on
5430  * any command that can be repeated an arbitrary number of times without
5431  * triggering a tarpit delay of some sort.
5432  */
5433typedef struct SMTPD_CMD {
5434    char   *name;
5435    int     (*action) (SMTPD_STATE *, int, SMTPD_TOKEN *);
5436    int     flags;
5437    int     success_count;
5438    int     total_count;
5439} SMTPD_CMD;
5440
5441 /*
5442  * Per RFC 2920: "In particular, the commands RSET, MAIL FROM, SEND FROM,
5443  * SOML FROM, SAML FROM, and RCPT TO can all appear anywhere in a pipelined
5444  * command group. The EHLO, DATA, VRFY, EXPN, TURN, QUIT, and NOOP commands
5445  * can only appear as the last command in a group". RFC 3030 allows BDAT
5446  * commands to be pipelined as well.
5447  */
5448#define SMTPD_CMD_FLAG_LIMIT	(1<<0)	/* limit usage */
5449#define SMTPD_CMD_FLAG_PRE_TLS	(1<<1)	/* allow before STARTTLS */
5450#define SMTPD_CMD_FLAG_LAST	(1<<2)	/* last in PIPELINING command group */
5451
5452static SMTPD_CMD smtpd_cmd_table[] = {
5453    {SMTPD_CMD_HELO, helo_cmd, SMTPD_CMD_FLAG_LIMIT | SMTPD_CMD_FLAG_PRE_TLS | SMTPD_CMD_FLAG_LAST,},
5454    {SMTPD_CMD_EHLO, ehlo_cmd, SMTPD_CMD_FLAG_LIMIT | SMTPD_CMD_FLAG_PRE_TLS | SMTPD_CMD_FLAG_LAST,},
5455    {SMTPD_CMD_XCLIENT, xclient_cmd, SMTPD_CMD_FLAG_PRE_TLS},
5456    {SMTPD_CMD_XFORWARD, xforward_cmd,},
5457#ifdef USE_TLS
5458    {SMTPD_CMD_STARTTLS, starttls_cmd, SMTPD_CMD_FLAG_PRE_TLS,},
5459#else
5460    {SMTPD_CMD_STARTTLS, unimpl_cmd, SMTPD_CMD_FLAG_PRE_TLS,},
5461#endif
5462#ifdef USE_SASL_AUTH
5463    {SMTPD_CMD_AUTH, smtpd_sasl_auth_cmd_wrapper,},
5464#else
5465    {SMTPD_CMD_AUTH, unimpl_cmd,},
5466#endif
5467    {SMTPD_CMD_MAIL, mail_cmd,},
5468    {SMTPD_CMD_RCPT, rcpt_cmd,},
5469    {SMTPD_CMD_DATA, data_cmd, SMTPD_CMD_FLAG_LAST,},
5470    {SMTPD_CMD_BDAT, bdat_cmd,},
5471    {SMTPD_CMD_RSET, rset_cmd, SMTPD_CMD_FLAG_LIMIT,},
5472    {SMTPD_CMD_NOOP, noop_cmd, SMTPD_CMD_FLAG_LIMIT | SMTPD_CMD_FLAG_PRE_TLS | SMTPD_CMD_FLAG_LAST,},
5473    {SMTPD_CMD_VRFY, vrfy_cmd, SMTPD_CMD_FLAG_LIMIT | SMTPD_CMD_FLAG_LAST,},
5474    {SMTPD_CMD_ETRN, etrn_cmd, SMTPD_CMD_FLAG_LIMIT,},
5475    {SMTPD_CMD_QUIT, quit_cmd, SMTPD_CMD_FLAG_PRE_TLS,},
5476    {0,},
5477};
5478
5479static STRING_LIST *smtpd_noop_cmds;
5480static STRING_LIST *smtpd_forbid_cmds;
5481
5482/* smtpd_flag_ill_pipelining - flag pipelining protocol violation */
5483
5484static int smtpd_flag_ill_pipelining(SMTPD_STATE *state)
5485{
5486
5487    /*
5488     * This code will not return after I/O error, timeout, or EOF. VSTREAM
5489     * exceptions must be enabled in advance with smtp_stream_setup().
5490     */
5491    if (vstream_peek(state->client) == 0
5492	&& peekfd(vstream_fileno(state->client)) > 0)
5493	(void) vstream_ungetc(state->client, smtp_fgetc(state->client));
5494    if (vstream_peek(state->client) > 0) {
5495	if (state->expand_buf == 0)
5496	    state->expand_buf = vstring_alloc(100);
5497	escape(state->expand_buf, vstream_peek_data(state->client),
5498	       vstream_peek(state->client) < 100 ?
5499	       vstream_peek(state->client) : 100);
5500	msg_info("improper command pipelining after %s from %s: %s",
5501		 state->where, state->namaddr, STR(state->expand_buf));
5502	state->flags |= SMTPD_FLAG_ILL_PIPELINING;
5503	return (1);
5504    }
5505    return (0);
5506}
5507
5508/* smtpd_proto - talk the SMTP protocol */
5509
5510static void smtpd_proto(SMTPD_STATE *state)
5511{
5512    int     argc;
5513    SMTPD_TOKEN *argv;
5514    SMTPD_CMD *cmdp;
5515    const char *ehlo_words;
5516    const char *err;
5517    int     status;
5518    const char *cp;
5519
5520#ifdef USE_TLS
5521    int     tls_rate;
5522
5523#endif
5524
5525    /*
5526     * Print a greeting banner and run the state machine. Read SMTP commands
5527     * one line at a time. According to the standard, a sender or recipient
5528     * address could contain an escaped newline. I think this is perverse,
5529     * and anyone depending on this is really asking for trouble.
5530     *
5531     * In case of mail protocol trouble, the program jumps back to this place,
5532     * so that it can perform the necessary cleanup before talking to the
5533     * next client. The setjmp/longjmp primitives are like a sharp tool: use
5534     * with care. I would certainly recommend against the use of
5535     * setjmp/longjmp in programs that change privilege levels.
5536     *
5537     * In case of file system trouble the program terminates after logging the
5538     * error and after informing the client. In all other cases (out of
5539     * memory, panic) the error is logged, and the msg_cleanup() exit handler
5540     * cleans up, but no attempt is made to inform the client of the nature
5541     * of the problem.
5542     *
5543     * With deadlines enabled, do not increase the time budget while receiving a
5544     * command, because that would give an attacker too much time.
5545     */
5546    vstream_control(state->client, VSTREAM_CTL_EXCEPT, VSTREAM_CTL_END);
5547    while ((status = vstream_setjmp(state->client)) == SMTP_ERR_NONE)
5548	 /* void */ ;
5549    smtp_stream_setup(state->client, var_smtpd_tmout, var_smtpd_req_deadline, 0);
5550    switch (status) {
5551
5552    default:
5553	msg_panic("smtpd_proto: unknown error reading from %s",
5554		  state->namaddr);
5555	break;
5556
5557    case SMTP_ERR_TIME:
5558	state->reason = REASON_TIMEOUT;
5559	if (vstream_setjmp(state->client) == 0)
5560	    smtpd_chat_reply(state, "421 4.4.2 %s Error: timeout exceeded",
5561			     var_myhostname);
5562	break;
5563
5564    case SMTP_ERR_EOF:
5565	state->reason = REASON_LOST_CONNECTION;
5566	break;
5567
5568    case SMTP_ERR_QUIET:
5569	break;
5570
5571    case SMTP_ERR_DATA:
5572	msg_info("%s: reject: %s from %s: "
5573		 "421 4.3.0 %s Server local data error",
5574		 (state->queue_id ? state->queue_id : "NOQUEUE"),
5575		 state->where, state->namaddr, var_myhostname);
5576	state->error_mask |= MAIL_ERROR_DATA;
5577	if (vstream_setjmp(state->client) == 0)
5578	    smtpd_chat_reply(state, "421 4.3.0 %s Server local data error",
5579			     var_myhostname);
5580	break;
5581
5582    case SMTP_ERR_LF:
5583	state->reason = REASON_BARE_LF;
5584	if (vstream_setjmp(state->client) == 0)
5585	    smtpd_chat_reply(state, "521 5.5.2 %s Error: bare <LF> received",
5586			     var_myhostname);
5587	break;
5588
5589    case 0:
5590
5591	/*
5592	 * Don't bother doing anything if some pre-SMTP handshake (haproxy)
5593	 * did not work out.
5594	 */
5595	if (state->flags & SMTPD_FLAG_HANGUP) {
5596	    smtpd_chat_reply(state, "421 4.3.0 %s Server local error",
5597			     var_myhostname);
5598	    break;
5599	}
5600
5601	/*
5602	 * In TLS wrapper mode, turn on TLS using code that is shared with
5603	 * the STARTTLS command. This code does not return when the handshake
5604	 * fails.
5605	 *
5606	 * Enforce TLS handshake rate limit when this client negotiated too many
5607	 * new TLS sessions in the recent past.
5608	 *
5609	 * XXX This means we don't complete a TLS handshake just to tell the
5610	 * client that we don't provide service. TLS wrapper mode is
5611	 * obsolete, so we don't have to provide perfect support.
5612	 */
5613#ifdef USE_TLS
5614	if (SMTPD_STAND_ALONE(state) == 0 && var_smtpd_tls_wrappermode
5615	    && state->tls_context == 0) {
5616#ifdef USE_TLSPROXY
5617	    /* We garbage-collect the VSTREAM in smtpd_state_reset() */
5618	    state->tlsproxy =
5619		tls_proxy_legacy_open(var_tlsproxy_service,
5620				      PROXY_OPEN_FLAGS,
5621				      state->client, state->addr,
5622				      state->port, var_smtpd_tmout,
5623				      state->service);
5624	    if (state->tlsproxy == 0) {
5625		msg_warn("Wrapper-mode request dropped from %s for service %s."
5626		       " TLS context initialization failed. For details see"
5627			 " earlier warnings in your logs.",
5628			 state->namaddr, state->service);
5629		break;
5630	    }
5631#else						/* USE_TLSPROXY */
5632	    if (smtpd_tls_ctx == 0) {
5633		msg_warn("Wrapper-mode request dropped from %s for service %s."
5634		       " TLS context initialization failed. For details see"
5635			 " earlier warnings in your logs.",
5636			 state->namaddr, state->service);
5637		break;
5638	    }
5639#endif						/* USE_TLSPROXY */
5640	    if (var_smtpd_cntls_limit > 0
5641		&& !xclient_allowed
5642		&& anvil_clnt
5643		&& !namadr_list_match(hogger_list, state->name, state->addr)
5644		&& anvil_clnt_newtls_stat(anvil_clnt, state->service,
5645			     state->anvil_range, &tls_rate) == ANVIL_STAT_OK
5646		&& tls_rate > var_smtpd_cntls_limit) {
5647		state->error_mask |= MAIL_ERROR_POLICY;
5648		msg_warn("Refusing TLS service request from %s for service %s",
5649			 state->namaddr, state->service);
5650		break;
5651	    }
5652	    smtpd_start_tls(state);
5653	}
5654#endif
5655
5656	/*
5657	 * If the client spoke before the server sends the initial greeting,
5658	 * raise a flag and log the content of the protocol violation. This
5659	 * check MUST NOT apply to TLS wrappermode connections.
5660	 */
5661	if (SMTPD_STAND_ALONE(state) == 0
5662	    && vstream_context(state->client) == 0	/* not postscreen */
5663	    && (state->flags & SMTPD_FLAG_ILL_PIPELINING) == 0
5664	    && smtpd_flag_ill_pipelining(state)
5665	    && var_smtpd_forbid_unauth_pipe) {
5666	    smtpd_chat_reply(state,
5667			  "554 5.5.0 Error: SMTP protocol synchronization");
5668	    break;
5669	}
5670
5671	/*
5672	 * XXX The client connection count/rate control must be consistent in
5673	 * its use of client address information in connect and disconnect
5674	 * events. For now we exclude xclient authorized hosts from
5675	 * connection count/rate control.
5676	 *
5677	 * XXX Must send connect/disconnect events to the anvil server even when
5678	 * this service is not connection count or rate limited, otherwise it
5679	 * will discard client message or recipient rate information too
5680	 * early or too late.
5681	 */
5682	if (SMTPD_STAND_ALONE(state) == 0
5683	    && !xclient_allowed
5684	    && anvil_clnt
5685	    && !namadr_list_match(hogger_list, state->name, state->addr)
5686	    && anvil_clnt_connect(anvil_clnt, state->service,
5687				  state->anvil_range, &state->conn_count,
5688				  &state->conn_rate)
5689	    == ANVIL_STAT_OK) {
5690	    if (var_smtpd_cconn_limit > 0
5691		&& state->conn_count > var_smtpd_cconn_limit) {
5692		state->error_mask |= MAIL_ERROR_POLICY;
5693		msg_warn("Connection concurrency limit exceeded: %d from %s for service %s",
5694			 state->conn_count, state->namaddr, state->service);
5695		smtpd_chat_reply(state, "421 4.7.0 %s Error: too many connections from %s",
5696				 var_myhostname, state->addr);
5697		break;
5698	    }
5699	    if (var_smtpd_crate_limit > 0
5700		&& state->conn_rate > var_smtpd_crate_limit) {
5701		msg_warn("Connection rate limit exceeded: %d from %s for service %s",
5702			 state->conn_rate, state->namaddr, state->service);
5703		smtpd_chat_reply(state, "421 4.7.0 %s Error: too many connections from %s",
5704				 var_myhostname, state->addr);
5705		break;
5706	    }
5707	}
5708
5709	/*
5710	 * Determine what server ESMTP features to suppress, typically to
5711	 * avoid inter-operability problems. Moved up so we don't send 421
5712	 * immediately after sending the initial server response.
5713	 */
5714	if (ehlo_discard_maps == 0
5715	|| (ehlo_words = maps_find(ehlo_discard_maps, state->addr, 0)) == 0)
5716	    ehlo_words = var_smtpd_ehlo_dis_words;
5717	state->ehlo_discard_mask = ehlo_mask(ehlo_words);
5718
5719	/* XXX We use the real client for connect access control. */
5720	if (SMTPD_STAND_ALONE(state) == 0
5721	    && var_smtpd_delay_reject == 0
5722	    && (err = smtpd_check_client(state)) != 0) {
5723	    state->error_mask |= MAIL_ERROR_POLICY;
5724	    state->access_denied = mystrdup(err);
5725	    smtpd_chat_reply(state, "%s", state->access_denied);
5726	    state->error_count++;
5727	}
5728
5729	/*
5730	 * RFC 2034: the text part of all 2xx, 4xx, and 5xx SMTP responses
5731	 * other than the initial greeting and any response to HELO or EHLO
5732	 * are prefaced with a status code as defined in RFC 3463.
5733	 */
5734
5735	/*
5736	 * XXX If a Milter rejects CONNECT, reply with 220 except in case of
5737	 * hard reject or 421 (disconnect). The reply persists so it will
5738	 * apply to MAIL FROM and to other commands such as AUTH, STARTTLS,
5739	 * and VRFY. Note: after a Milter CONNECT reject, we must not reject
5740	 * HELO or EHLO, but we do change the feature list that is announced
5741	 * in the EHLO response.
5742	 */
5743	else {
5744	    err = 0;
5745	    if (state->milters != 0) {
5746		milter_macro_callback(state->milters, smtpd_milter_eval,
5747				      (void *) state);
5748		if ((err = milter_conn_event(state->milters, state->name,
5749					     state->addr,
5750				  strcmp(state->port, CLIENT_PORT_UNKNOWN) ?
5751					     state->port : "0",
5752					     state->addr_family)) != 0)
5753		    err = check_milter_reply(state, err);
5754	    }
5755	    if (err && err[0] == '5') {
5756		state->error_mask |= MAIL_ERROR_POLICY;
5757		smtpd_chat_reply(state, "554 %s ESMTP not accepting connections",
5758				 var_myhostname);
5759		state->error_count++;
5760	    } else if (err && strncmp(err, "421", 3) == 0) {
5761		state->error_mask |= MAIL_ERROR_POLICY;
5762		smtpd_chat_reply(state, "421 %s Service unavailable - try again later",
5763				 var_myhostname);
5764		/* Not: state->error_count++; */
5765	    } else {
5766		smtpd_chat_reply(state, "220 %s", var_smtpd_banner);
5767	    }
5768	}
5769
5770	/*
5771	 * SASL initialization for plaintext mode.
5772	 *
5773	 * XXX Backwards compatibility: allow AUTH commands when the AUTH
5774	 * announcement is suppressed via smtpd_sasl_exceptions_networks.
5775	 *
5776	 * XXX Safety: don't enable SASL with "smtpd_tls_auth_only = yes" and
5777	 * non-TLS build.
5778	 */
5779#ifdef USE_SASL_AUTH
5780	if (var_smtpd_sasl_enable && smtpd_sasl_is_active(state) == 0
5781#ifdef USE_TLS
5782	    && state->tls_context == 0 && !var_smtpd_tls_auth_only
5783#else
5784	    && var_smtpd_tls_auth_only == 0
5785#endif
5786	    )
5787	    smtpd_sasl_activate(state, VAR_SMTPD_SASL_OPTS,
5788				var_smtpd_sasl_opts);
5789#endif
5790
5791	/*
5792	 * The command read/execute loop.
5793	 */
5794	for (;;) {
5795	    if (state->flags & SMTPD_FLAG_HANGUP)
5796		break;
5797	    smtp_stream_setup(state->client, var_smtpd_tmout,
5798			      var_smtpd_req_deadline, 0);
5799	    if (state->error_count >= var_smtpd_hard_erlim) {
5800		state->reason = REASON_ERROR_LIMIT;
5801		state->error_mask |= MAIL_ERROR_PROTOCOL;
5802		smtpd_chat_reply(state, "421 4.7.0 %s Error: too many errors",
5803				 var_myhostname);
5804		pfilter_notify(1, vstream_fileno(state->client));
5805		break;
5806	    }
5807	    watchdog_pat();
5808	    smtpd_chat_query(state);
5809	    /* Safety: protect internal interfaces against malformed UTF-8. */
5810	    if (var_smtputf8_enable && valid_utf8_string(STR(state->buffer),
5811						 LEN(state->buffer)) == 0) {
5812		state->error_mask |= MAIL_ERROR_PROTOCOL;
5813		smtpd_chat_reply(state, "500 5.5.2 Error: bad UTF-8 syntax");
5814		state->error_count++;
5815		continue;
5816	    }
5817	    /* Move into smtpd_chat_query() and update session transcript. */
5818	    if (smtpd_cmd_filter != 0) {
5819		for (cp = STR(state->buffer); *cp && IS_SPACE_TAB(*cp); cp++)
5820		     /* void */ ;
5821		if ((cp = dict_get(smtpd_cmd_filter, cp)) != 0) {
5822		    msg_info("%s: replacing command \"%.100s\" with \"%.100s\"",
5823			     state->namaddr, STR(state->buffer), cp);
5824		    vstring_strcpy(state->buffer, cp);
5825		} else if (smtpd_cmd_filter->error != 0) {
5826		    msg_warn("%s:%s lookup error for \"%.100s\"",
5827			     smtpd_cmd_filter->type, smtpd_cmd_filter->name,
5828			     printable(STR(state->buffer), '?'));
5829		    vstream_longjmp(state->client, SMTP_ERR_DATA);
5830		}
5831	    }
5832	    if ((argc = smtpd_token(vstring_str(state->buffer), &argv)) == 0) {
5833		state->error_mask |= MAIL_ERROR_PROTOCOL;
5834		smtpd_chat_reply(state, "500 5.5.2 Error: bad syntax");
5835		state->error_count++;
5836		continue;
5837	    }
5838	    /* Ignore smtpd_noop_cmds lookup errors. Non-critical feature. */
5839	    if (*var_smtpd_noop_cmds
5840		&& string_list_match(smtpd_noop_cmds, argv[0].strval)) {
5841		smtpd_chat_reply(state, "250 2.0.0 Ok");
5842		if (state->junk_cmds++ > var_smtpd_junk_cmd_limit)
5843		    state->error_count++;
5844		continue;
5845	    }
5846	    for (cmdp = smtpd_cmd_table; cmdp->name != 0; cmdp++)
5847		if (strcasecmp(argv[0].strval, cmdp->name) == 0)
5848		    break;
5849	    cmdp->total_count += 1;
5850	    /* Ignore smtpd_forbid_cmds lookup errors. Non-critical feature. */
5851	    if (cmdp->name == 0) {
5852		state->where = SMTPD_CMD_UNKNOWN;
5853		if (is_header(argv[0].strval)
5854		    || (*var_smtpd_forbid_cmds
5855		 && string_list_match(smtpd_forbid_cmds, argv[0].strval))) {
5856		    VSTRING *escape_buf = vstring_alloc(100);
5857
5858		    msg_warn("non-SMTP command from %s: %.100s",
5859			     state->namaddr,
5860			     vstring_str(escape(escape_buf,
5861						vstring_str(state->buffer),
5862					      VSTRING_LEN(state->buffer))));
5863		    smtpd_chat_reply(state, "221 2.7.0 Error: I can break rules, too. Goodbye.");
5864		    vstring_free(escape_buf);
5865		    break;
5866		}
5867	    }
5868	    /* XXX We use the real client for connect access control. */
5869	    if (state->access_denied && cmdp->action != quit_cmd) {
5870		/* XXX Exception for Milter override. */
5871		if (strncmp(state->access_denied + 1, "21", 2) == 0) {
5872		    smtpd_chat_reply(state, "%s", state->access_denied);
5873		    continue;
5874		}
5875		smtpd_chat_reply(state, "503 5.7.0 Error: access denied for %s",
5876				 state->namaddr);	/* RFC 2821 Sec 3.1 */
5877		state->error_count++;
5878		continue;
5879	    }
5880	    /* state->access_denied == 0 || cmdp->action == quit_cmd */
5881	    if (cmdp->name == 0) {
5882		if (state->milters != 0
5883		    && (err = milter_unknown_event(state->milters,
5884						   argv[0].strval)) != 0
5885		    && (err = check_milter_reply(state, err)) != 0) {
5886		    smtpd_chat_reply(state, "%s", err);
5887		} else
5888		    smtpd_chat_reply(state, "500 5.5.2 Error: command not recognized");
5889		state->error_mask |= MAIL_ERROR_PROTOCOL;
5890		state->error_count++;
5891		continue;
5892	    }
5893#ifdef USE_TLS
5894	    if (var_smtpd_enforce_tls &&
5895		!state->tls_context &&
5896		(cmdp->flags & SMTPD_CMD_FLAG_PRE_TLS) == 0) {
5897		smtpd_chat_reply(state,
5898			   "530 5.7.0 Must issue a STARTTLS command first");
5899		state->error_count++;
5900		continue;
5901	    }
5902#endif
5903	    state->where = cmdp->name;
5904	    if (SMTPD_STAND_ALONE(state) == 0
5905		&& (strcasecmp(state->protocol, MAIL_PROTO_ESMTP) != 0
5906		    || (cmdp->flags & SMTPD_CMD_FLAG_LAST))
5907		&& (state->flags & SMTPD_FLAG_ILL_PIPELINING) == 0
5908		&& smtpd_flag_ill_pipelining(state)
5909		&& var_smtpd_forbid_unauth_pipe) {
5910		smtpd_chat_reply(state,
5911			  "554 5.5.0 Error: SMTP protocol synchronization");
5912		break;
5913	    }
5914	    if (cmdp->action(state, argc, argv) != 0)
5915		state->error_count++;
5916	    else
5917		cmdp->success_count += 1;
5918	    if ((cmdp->flags & SMTPD_CMD_FLAG_LIMIT)
5919		&& state->junk_cmds++ > var_smtpd_junk_cmd_limit)
5920		state->error_count++;
5921	    if (cmdp->action == quit_cmd)
5922		break;
5923	}
5924	break;
5925    }
5926
5927    /*
5928     * XXX The client connection count/rate control must be consistent in its
5929     * use of client address information in connect and disconnect events.
5930     * For now we exclude xclient authorized hosts from connection count/rate
5931     * control.
5932     *
5933     * XXX Must send connect/disconnect events to the anvil server even when
5934     * this service is not connection count or rate limited, otherwise it
5935     * will discard client message or recipient rate information too early or
5936     * too late.
5937     */
5938    if (SMTPD_STAND_ALONE(state) == 0
5939	&& !xclient_allowed
5940	&& anvil_clnt
5941	&& !namadr_list_match(hogger_list, state->name, state->addr))
5942	anvil_clnt_disconnect(anvil_clnt, state->service, state->anvil_range);
5943
5944    /*
5945     * Log abnormal session termination, in case postmaster notification has
5946     * been turned off. In the log, indicate the last recognized state before
5947     * things went wrong. Don't complain about clients that go away without
5948     * sending QUIT. Log the byte count after DATA to help diagnose MTU
5949     * troubles.
5950     */
5951    if (state->reason && state->where) {
5952	if (strcmp(state->where, SMTPD_AFTER_DATA) == 0) {
5953	    msg_info("%s after %s (%lu bytes) from %s",	/* 2.5 compat */
5954		     state->reason, SMTPD_CMD_DATA,	/* 2.5 compat */
5955		     (long) (state->act_size + vstream_peek(state->client)),
5956		     state->namaddr);
5957	} else if (strcmp(state->where, SMTPD_AFTER_BDAT) == 0) {
5958	    msg_info("%s after %s (%lu bytes) from %s",
5959		     state->reason, SMTPD_CMD_BDAT,
5960		     (long) (state->act_size + VSTRING_LEN(state->buffer)
5961			     + VSTRING_LEN(state->bdat_get_buffer)),
5962		     state->namaddr);
5963	} else if (strcmp(state->where, SMTPD_AFTER_EOM)
5964		   || strcmp(state->reason, REASON_LOST_CONNECTION)) {
5965	    msg_info("%s after %s from %s",
5966		     state->reason, state->where, state->namaddr);
5967	    if (strcmp(state->where, SMTPD_CMD_AUTH) == 0)
5968		pfilter_notify(1, vstream_fileno(state->client));
5969	}
5970    }
5971
5972    /*
5973     * Cleanup whatever information the client gave us during the SMTP
5974     * dialog.
5975     *
5976     * XXX Duplicated in xclient_cmd().
5977     */
5978#ifdef USE_TLS
5979    tls_reset(state);
5980#endif
5981    helo_reset(state);
5982#ifdef USE_SASL_AUTH
5983    smtpd_sasl_auth_reset(state);
5984    if (smtpd_sasl_is_active(state)) {
5985	smtpd_sasl_deactivate(state);
5986    }
5987#endif
5988    chat_reset(state, 0);
5989    mail_reset(state);
5990    rcpt_reset(state);
5991    if (state->milters)
5992	milter_disc_event(state->milters);
5993}
5994
5995/* smtpd_format_cmd_stats - format per-command statistics */
5996
5997static char *smtpd_format_cmd_stats(VSTRING *buf)
5998{
5999    SMTPD_CMD *cmdp;
6000    int     all_success = 0;
6001    int     all_total = 0;
6002
6003    /*
6004     * Log the statistics. Note that this loop produces no output when no
6005     * command was received. We address that after the loop.
6006     */
6007    VSTRING_RESET(buf);
6008    for (cmdp = smtpd_cmd_table; /* see below */ ; cmdp++) {
6009	if (cmdp->total_count > 0) {
6010	    vstring_sprintf_append(buf, " %s=%d",
6011				   cmdp->name ? cmdp->name : "unknown",
6012				   cmdp->success_count);
6013	    if (cmdp->success_count != cmdp->total_count)
6014		vstring_sprintf_append(buf, "/%d", cmdp->total_count);
6015	    all_success += cmdp->success_count;
6016	    all_total += cmdp->total_count;
6017	}
6018	if (cmdp->name == 0)
6019	    break;
6020    }
6021
6022    /*
6023     * Reset the per-command counters.
6024     *
6025     * Fix 20190621: the command counter resetting code was moved from the SMTP
6026     * protocol handler to this place, because the protocol handler was never
6027     * called after HaProxy handshake error, causing stale numbers to be
6028     * logged.
6029     */
6030    for (cmdp = smtpd_cmd_table; /* see below */ ; cmdp++) {
6031	cmdp->success_count = cmdp->total_count = 0;
6032	if (cmdp->name == 0)
6033	    break;
6034    }
6035
6036    /*
6037     * Log total numbers, so that logfile analyzers will see something even
6038     * if the above loop produced no output. When no commands were received
6039     * log "0/0" to simplify the identification of abnormal sessions: any
6040     * statistics with [0-9]/ indicate that there was a problem.
6041     */
6042    vstring_sprintf_append(buf, " commands=%d", all_success);
6043    if (all_success != all_total || all_total == 0)
6044	vstring_sprintf_append(buf, "/%d", all_total);
6045    return (lowercase(STR(buf)));
6046}
6047
6048/* setup_milters - set up Milters after a connection is established */
6049
6050static void setup_milters(SMTPD_STATE *state)
6051{
6052    const char *milter_string;
6053
6054    /*
6055     * Postcondition: either state->milters is set, or the
6056     * INPUT_TRANSP_MILTER flag is passed down-stream.
6057     */
6058    if (SMTPD_STAND_ALONE(state) == 0
6059	&& (smtpd_input_transp_mask & INPUT_TRANSP_MILTER) == 0
6060	&& ((smtpd_milter_maps
6061	     && (milter_string =
6062		 maps_find(smtpd_milter_maps, state->addr, 0)) != 0)
6063	    || *(milter_string = var_smtpd_milters) != 0)
6064	&& strcasecmp(milter_string, SMTPD_MILTERS_DISABLE) != 0) {
6065	state->milters = milter_create(milter_string,
6066				       var_milt_conn_time,
6067				       var_milt_cmd_time,
6068				       var_milt_msg_time,
6069				       var_milt_protocol,
6070				       var_milt_def_action,
6071				       var_milt_conn_macros,
6072				       var_milt_helo_macros,
6073				       var_milt_mail_macros,
6074				       var_milt_rcpt_macros,
6075				       var_milt_data_macros,
6076				       var_milt_eoh_macros,
6077				       var_milt_eod_macros,
6078				       var_milt_unk_macros,
6079				       var_milt_macro_deflts);
6080    }
6081
6082    /*
6083     * Safety: disable non_smtpd_milters when not sending our own mail filter
6084     * list. Otherwise the next stage could handle this message as a local
6085     * submission.
6086     */
6087    if (state->milters == 0)
6088	smtpd_input_transp_mask |= INPUT_TRANSP_MILTER;
6089}
6090
6091/* teardown_milters - release resources */
6092
6093static void teardown_milters(SMTPD_STATE *state)
6094{
6095    if (state->milters) {
6096	milter_free(state->milters);
6097	state->milters = 0;
6098    }
6099    smtpd_input_transp_mask =
6100	input_transp_mask(VAR_INPUT_TRANSP, var_input_transp);
6101}
6102
6103
6104/* smtpd_service - service one client */
6105
6106static void smtpd_service(VSTREAM *stream, char *service, char **argv)
6107{
6108    SMTPD_STATE state;
6109
6110    /*
6111     * Sanity check. This service takes no command-line arguments.
6112     */
6113    if (argv[0])
6114	msg_fatal("unexpected command-line argument: %s", argv[0]);
6115
6116    /*
6117     * For sanity, require that at least one of INET or INET6 is enabled.
6118     * Otherwise, we can't look up interface information, and we can't
6119     * convert names or addresses.
6120     */
6121    if (SMTPD_STAND_ALONE_STREAM(stream) == 0
6122	&& inet_proto_info()->ai_family_list[0] == 0)
6123	msg_fatal("all network protocols are disabled (%s = %s)",
6124		  VAR_INET_PROTOCOLS, var_inet_protocols);
6125
6126    /*
6127     * This routine runs when a client has connected to our network port, or
6128     * when the smtp server is run in stand-alone mode (input from pipe).
6129     *
6130     * Look up and sanitize the peer name, then initialize some connection-
6131     * specific state. When the name service is hosed, hostname lookup will
6132     * take a while. This is why I always run a local name server on critical
6133     * machines.
6134     */
6135    smtpd_state_init(&state, stream, service);
6136    msg_info("connect from %s", state.namaddr);
6137
6138    /*
6139     * Disable TLS when running in stand-alone mode via "sendmail -bs".
6140     */
6141    if (SMTPD_STAND_ALONE((&state))) {
6142	var_smtpd_use_tls = 0;
6143	var_smtpd_enforce_tls = 0;
6144	var_smtpd_tls_auth_only = 0;
6145    }
6146
6147    /*
6148     * XCLIENT must not override its own access control.
6149     */
6150    xclient_allowed = SMTPD_STAND_ALONE((&state)) == 0 &&
6151	namadr_list_match(xclient_hosts, state.name, state.addr);
6152
6153    /*
6154     * Overriding XFORWARD access control makes no sense, either.
6155     */
6156    xforward_allowed = SMTPD_STAND_ALONE((&state)) == 0 &&
6157	namadr_list_match(xforward_hosts, state.name, state.addr);
6158
6159    /*
6160     * Enforce strict SMTP line endings, with compatibility exclusions.
6161     */
6162    smtp_forbid_bare_lf = SMTPD_STAND_ALONE((&state)) == 0
6163	&& var_smtpd_forbid_bare_lf
6164	&& !namadr_list_match(bare_lf_excl, state.name, state.addr);
6165
6166    /*
6167     * See if we need to turn on verbose logging for this client.
6168     */
6169    debug_peer_check(state.name, state.addr);
6170
6171    /*
6172     * Set up Milters, or disable Milters down-stream.
6173     */
6174    setup_milters(&state);			/* duplicates xclient_cmd */
6175
6176    /*
6177     * Provide the SMTP service.
6178     */
6179    smtpd_proto(&state);
6180
6181    /*
6182     * After the client has gone away, clean up whatever we have set up at
6183     * connection time.
6184     */
6185    msg_info("disconnect from %s%s", state.namaddr,
6186	     smtpd_format_cmd_stats(state.buffer));
6187    teardown_milters(&state);			/* duplicates xclient_cmd */
6188    smtpd_state_reset(&state);
6189    debug_peer_restore();
6190}
6191
6192/* pre_accept - see if tables have changed */
6193
6194static void pre_accept(char *unused_name, char **unused_argv)
6195{
6196    const char *table;
6197
6198    if ((table = dict_changed_name()) != 0) {
6199	msg_info("table %s has changed -- restarting", table);
6200	exit(0);
6201    }
6202}
6203
6204/* pre_jail_init - pre-jail initialization */
6205
6206static void pre_jail_init(char *unused_name, char **unused_argv)
6207{
6208
6209    /*
6210     * Initialize denylist/etc. patterns before entering the chroot jail, in
6211     * case they specify a filename pattern.
6212     */
6213    smtpd_noop_cmds = string_list_init(VAR_SMTPD_NOOP_CMDS, MATCH_FLAG_RETURN,
6214				       var_smtpd_noop_cmds);
6215    smtpd_forbid_cmds = string_list_init(VAR_SMTPD_FORBID_CMDS,
6216					 MATCH_FLAG_RETURN,
6217					 var_smtpd_forbid_cmds);
6218    verp_clients = namadr_list_init(VAR_VERP_CLIENTS, MATCH_FLAG_RETURN,
6219				    var_verp_clients);
6220    xclient_hosts = namadr_list_init(VAR_XCLIENT_HOSTS, MATCH_FLAG_RETURN,
6221				     var_xclient_hosts);
6222    xforward_hosts = namadr_list_init(VAR_XFORWARD_HOSTS, MATCH_FLAG_RETURN,
6223				      var_xforward_hosts);
6224    hogger_list = namadr_list_init(VAR_SMTPD_HOGGERS, MATCH_FLAG_RETURN
6225				   | match_parent_style(VAR_SMTPD_HOGGERS),
6226				   var_smtpd_hoggers);
6227    bare_lf_excl = namadr_list_init(VAR_SMTPD_FORBID_BARE_LF_EXCL,
6228				    MATCH_FLAG_RETURN
6229				    | match_parent_style(VAR_MYNETWORKS),
6230				    var_smtpd_forbid_bare_lf_excl);
6231
6232    /*
6233     * Open maps before dropping privileges so we can read passwords etc.
6234     *
6235     * XXX We should not do this in stand-alone (sendmail -bs) mode, but we
6236     * can't use SMTPD_STAND_ALONE(state) here. This means "sendmail -bs"
6237     * will try to connect to proxymap when invoked by root for mail
6238     * submission. To fix, we would have to pass stand-alone mode information
6239     * via different means. For now we have to tell people not to run mail
6240     * clients as root.
6241     */
6242    if (getuid() == 0 || getuid() == var_owner_uid)
6243	smtpd_check_init();
6244    smtpd_expand_init();
6245    debug_peer_init();
6246
6247    if (var_smtpd_sasl_enable)
6248#ifdef USE_SASL_AUTH
6249	smtpd_sasl_initialize();
6250
6251    if (*var_smtpd_sasl_exceptions_networks)
6252	sasl_exceptions_networks =
6253	    namadr_list_init(VAR_SMTPD_SASL_EXCEPTIONS_NETWORKS,
6254			     MATCH_FLAG_RETURN,
6255			     var_smtpd_sasl_exceptions_networks);
6256#else
6257	msg_warn("%s is true, but SASL support is not compiled in",
6258		 VAR_SMTPD_SASL_ENABLE);
6259#endif
6260
6261    if (*var_smtpd_cmd_filter)
6262	smtpd_cmd_filter = dict_open(var_smtpd_cmd_filter, O_RDONLY,
6263				     DICT_FLAG_LOCK | DICT_FLAG_FOLD_FIX);
6264
6265    /*
6266     * XXX Temporary fix to pretend that we consistently implement TLS
6267     * security levels. We implement only a subset for now. If we implement
6268     * more levels, wrappermode should override only weaker TLS security
6269     * levels.
6270     *
6271     * Note: tls_level_lookup() logs no warning.
6272     */
6273    if (!var_smtpd_tls_wrappermode && *var_smtpd_tls_level) {
6274	switch (tls_level_lookup(var_smtpd_tls_level)) {
6275	default:
6276	    msg_fatal("Invalid TLS level \"%s\"", var_smtpd_tls_level);
6277	    /* NOTREACHED */
6278	    break;
6279	case TLS_LEV_SECURE:
6280	case TLS_LEV_VERIFY:
6281	case TLS_LEV_FPRINT:
6282	    msg_warn("%s: unsupported TLS level \"%s\", using \"encrypt\"",
6283		     VAR_SMTPD_TLS_LEVEL, var_smtpd_tls_level);
6284	    /* FALLTHROUGH */
6285	case TLS_LEV_ENCRYPT:
6286	    var_smtpd_enforce_tls = var_smtpd_use_tls = 1;
6287	    break;
6288	case TLS_LEV_MAY:
6289	    var_smtpd_enforce_tls = 0;
6290	    var_smtpd_use_tls = 1;
6291	    break;
6292	case TLS_LEV_NONE:
6293	    var_smtpd_enforce_tls = var_smtpd_use_tls = 0;
6294	    break;
6295	}
6296    }
6297
6298    /*
6299     * With TLS wrapper mode, we run on a dedicated port and turn on TLS
6300     * before actually speaking the SMTP protocol. This implies TLS enforce
6301     * mode.
6302     *
6303     * With non-wrapper mode, TLS enforce mode implies that we don't advertise
6304     * AUTH before the client issues STARTTLS.
6305     */
6306    var_smtpd_enforce_tls = var_smtpd_tls_wrappermode || var_smtpd_enforce_tls;
6307    var_smtpd_tls_auth_only = var_smtpd_tls_auth_only || var_smtpd_enforce_tls;
6308    var_smtpd_use_tls = var_smtpd_use_tls || var_smtpd_enforce_tls;
6309
6310    /*
6311     * Keys can only be loaded when running with suitable permissions. When
6312     * called from "sendmail -bs" this is not the case, so we must not
6313     * announce STARTTLS support.
6314     */
6315    if (getuid() == 0 || getuid() == var_owner_uid) {
6316	if (var_smtpd_use_tls) {
6317#ifdef USE_TLS
6318#ifndef USE_TLSPROXY
6319	    TLS_SERVER_INIT_PROPS props;
6320	    const char *cert_file;
6321	    int     have_server_cert;
6322	    int     no_server_cert_ok;
6323	    int     require_server_cert;
6324
6325	    /*
6326	     * Can't use anonymous ciphers if we want client certificates.
6327	     * Must use anonymous ciphers if we have no certificates.
6328	     *
6329	     * XXX: Ugh! Too many booleans!
6330	     */
6331	    ask_client_cert = require_server_cert =
6332		(var_smtpd_tls_ask_ccert
6333		 || (var_smtpd_enforce_tls && var_smtpd_tls_req_ccert));
6334	    if (strcasecmp(var_smtpd_tls_cert_file, "none") == 0) {
6335		no_server_cert_ok = 1;
6336		cert_file = "";
6337	    } else {
6338		no_server_cert_ok = 0;
6339		cert_file = var_smtpd_tls_cert_file;
6340	    }
6341
6342	    have_server_cert = *cert_file != 0;
6343	    have_server_cert |= *var_smtpd_tls_eccert_file != 0;
6344	    have_server_cert |= *var_smtpd_tls_dcert_file != 0;
6345
6346	    if (*var_smtpd_tls_chain_files != 0) {
6347		if (!have_server_cert)
6348		    have_server_cert = 1;
6349		else
6350		    msg_warn("Both %s and one or more of the legacy "
6351			     " %s, %s or %s are non-empty; the legacy "
6352			     " parameters will be ignored",
6353			     VAR_SMTPD_TLS_CHAIN_FILES,
6354			     VAR_SMTPD_TLS_CERT_FILE,
6355			     VAR_SMTPD_TLS_ECCERT_FILE,
6356			     VAR_SMTPD_TLS_DCERT_FILE);
6357	    }
6358	    /* Some TLS configuration errors are not show stoppers. */
6359	    if (!have_server_cert && require_server_cert)
6360		msg_warn("Need a server cert to request client certs");
6361	    if (!var_smtpd_enforce_tls && var_smtpd_tls_req_ccert)
6362		msg_warn("Can't require client certs unless TLS is required");
6363	    /* After a show-stopper error, reply with 454 to STARTTLS. */
6364	    if (have_server_cert
6365		|| (no_server_cert_ok && !require_server_cert)) {
6366
6367		tls_pre_jail_init(TLS_ROLE_SERVER);
6368
6369		/*
6370		 * Large parameter lists are error-prone, so we emulate a
6371		 * language feature that C does not have natively: named
6372		 * parameter lists.
6373		 */
6374		smtpd_tls_ctx =
6375		    TLS_SERVER_INIT(&props,
6376				    log_param = VAR_SMTPD_TLS_LOGLEVEL,
6377				    log_level = var_smtpd_tls_loglevel,
6378				    verifydepth = var_smtpd_tls_ccert_vd,
6379				    cache_type = TLS_MGR_SCACHE_SMTPD,
6380				    set_sessid = var_smtpd_tls_set_sessid,
6381				    chain_files = var_smtpd_tls_chain_files,
6382				    cert_file = cert_file,
6383				    key_file = var_smtpd_tls_key_file,
6384				    dcert_file = var_smtpd_tls_dcert_file,
6385				    dkey_file = var_smtpd_tls_dkey_file,
6386				    eccert_file = var_smtpd_tls_eccert_file,
6387				    eckey_file = var_smtpd_tls_eckey_file,
6388				    CAfile = var_smtpd_tls_CAfile,
6389				    CApath = var_smtpd_tls_CApath,
6390				    dh1024_param_file
6391				    = var_smtpd_tls_dh1024_param_file,
6392				    dh512_param_file
6393				    = var_smtpd_tls_dh512_param_file,
6394				    eecdh_grade = var_smtpd_tls_eecdh,
6395				    protocols = var_smtpd_enforce_tls ?
6396				    var_smtpd_tls_mand_proto :
6397				    var_smtpd_tls_proto,
6398				    ask_ccert = ask_client_cert,
6399				    mdalg = var_smtpd_tls_fpt_dgst);
6400	    } else {
6401		msg_warn("No server certs available. TLS won't be enabled");
6402	    }
6403#endif						/* USE_TLSPROXY */
6404#else
6405	    msg_warn("TLS has been selected, but TLS support is not compiled in");
6406#endif
6407	}
6408    }
6409
6410    /*
6411     * flush client.
6412     */
6413    flush_init();
6414
6415    /*
6416     * EHLO keyword filter.
6417     */
6418    if (*var_smtpd_ehlo_dis_maps)
6419	ehlo_discard_maps = maps_create(VAR_SMTPD_EHLO_DIS_MAPS,
6420					var_smtpd_ehlo_dis_maps,
6421					DICT_FLAG_LOCK);
6422
6423    /*
6424     * Per-client Milter support.
6425     */
6426    if (*var_smtpd_milter_maps)
6427	smtpd_milter_maps = maps_create(VAR_SMTPD_MILTER_MAPS,
6428					var_smtpd_milter_maps,
6429					DICT_FLAG_LOCK);
6430
6431    /*
6432     * DNS reply filter.
6433     */
6434    if (*var_smtpd_dns_re_filter)
6435	dns_rr_filter_compile(VAR_SMTPD_DNS_RE_FILTER,
6436			      var_smtpd_dns_re_filter);
6437
6438    /*
6439     * Reject footer.
6440     */
6441    if (*var_smtpd_rej_ftr_maps)
6442	smtpd_chat_pre_jail_init();
6443}
6444
6445/* post_jail_init - post-jail initialization */
6446
6447static void post_jail_init(char *unused_name, char **unused_argv)
6448{
6449
6450    /*
6451     * Initialize the receive transparency options: do we want unknown
6452     * recipient checks, address mapping, header_body_checks?.
6453     */
6454    smtpd_input_transp_mask =
6455    input_transp_mask(VAR_INPUT_TRANSP, var_input_transp);
6456
6457    /*
6458     * Initialize before-queue filter options: do we want speed-matching
6459     * support so that the entire message is received before we contact a
6460     * before-queue content filter?
6461     */
6462    if (*var_smtpd_proxy_filt)
6463	smtpd_proxy_opts =
6464	    smtpd_proxy_parse_opts(VAR_SMTPD_PROXY_OPTS, var_smtpd_proxy_opts);
6465
6466    /*
6467     * Sanity checks. The queue_minfree value should be at least as large as
6468     * (process_limit * message_size_limit) but that is unpractical, so we
6469     * arbitrarily pick a small multiple of the per-message size limit. This
6470     * helps to avoid many unneeded (re)transmissions.
6471     */
6472    if (ENFORCING_SIZE_LIMIT(var_queue_minfree)
6473	&& ENFORCING_SIZE_LIMIT(var_message_limit)
6474	&& var_queue_minfree / 1.5 < var_message_limit)
6475	msg_warn("%s(%lu) should be at least 1.5*%s(%lu)",
6476		 VAR_QUEUE_MINFREE, (unsigned long) var_queue_minfree,
6477		 VAR_MESSAGE_LIMIT, (unsigned long) var_message_limit);
6478
6479    /*
6480     * Connection rate management.
6481     */
6482    if (var_smtpd_crate_limit || var_smtpd_cconn_limit
6483	|| var_smtpd_cmail_limit || var_smtpd_crcpt_limit
6484	|| var_smtpd_cntls_limit || var_smtpd_cauth_limit)
6485	anvil_clnt = anvil_clnt_create();
6486
6487    /*
6488     * header_from_format support, for	postmaster notifications.
6489     */
6490    smtpd_hfrom_format = hfrom_format_parse(VAR_HFROM_FORMAT, var_hfrom_format);
6491}
6492
6493MAIL_VERSION_STAMP_DECLARE;
6494
6495/* main - the main program */
6496
6497int     main(int argc, char **argv)
6498{
6499    static const CONFIG_NINT_TABLE nint_table[] = {
6500	VAR_SMTPD_SOFT_ERLIM, DEF_SMTPD_SOFT_ERLIM, &var_smtpd_soft_erlim, 1, 0,
6501	VAR_SMTPD_HARD_ERLIM, DEF_SMTPD_HARD_ERLIM, &var_smtpd_hard_erlim, 1, 0,
6502	VAR_SMTPD_JUNK_CMD, DEF_SMTPD_JUNK_CMD, &var_smtpd_junk_cmd_limit, 1, 0,
6503	VAR_VERIFY_POLL_COUNT, DEF_VERIFY_POLL_COUNT, &var_verify_poll_count, 1, 0,
6504	0,
6505    };
6506    static const CONFIG_INT_TABLE int_table[] = {
6507	VAR_SMTPD_RCPT_LIMIT, DEF_SMTPD_RCPT_LIMIT, &var_smtpd_rcpt_limit, 1, 0,
6508	VAR_UNK_CLIENT_CODE, DEF_UNK_CLIENT_CODE, &var_unk_client_code, 0, 0,
6509	VAR_BAD_NAME_CODE, DEF_BAD_NAME_CODE, &var_bad_name_code, 0, 0,
6510	VAR_UNK_NAME_CODE, DEF_UNK_NAME_CODE, &var_unk_name_code, 0, 0,
6511	VAR_UNK_ADDR_CODE, DEF_UNK_ADDR_CODE, &var_unk_addr_code, 0, 0,
6512	VAR_RELAY_CODE, DEF_RELAY_CODE, &var_relay_code, 0, 0,
6513	VAR_MAPS_RBL_CODE, DEF_MAPS_RBL_CODE, &var_maps_rbl_code, 0, 0,
6514	VAR_MAP_REJECT_CODE, DEF_MAP_REJECT_CODE, &var_map_reject_code, 0, 0,
6515	VAR_MAP_DEFER_CODE, DEF_MAP_DEFER_CODE, &var_map_defer_code, 0, 0,
6516	VAR_REJECT_CODE, DEF_REJECT_CODE, &var_reject_code, 0, 0,
6517	VAR_DEFER_CODE, DEF_DEFER_CODE, &var_defer_code, 0, 0,
6518	VAR_NON_FQDN_CODE, DEF_NON_FQDN_CODE, &var_non_fqdn_code, 0, 0,
6519	VAR_SMTPD_RCPT_OVERLIM, DEF_SMTPD_RCPT_OVERLIM, &var_smtpd_rcpt_overlim, 1, 0,
6520	VAR_SMTPD_HIST_THRSH, DEF_SMTPD_HIST_THRSH, &var_smtpd_hist_thrsh, 1, 0,
6521	VAR_UNV_FROM_RCODE, DEF_UNV_FROM_RCODE, &var_unv_from_rcode, 200, 599,
6522	VAR_UNV_RCPT_RCODE, DEF_UNV_RCPT_RCODE, &var_unv_rcpt_rcode, 200, 599,
6523	VAR_UNV_FROM_DCODE, DEF_UNV_FROM_DCODE, &var_unv_from_dcode, 200, 499,
6524	VAR_UNV_RCPT_DCODE, DEF_UNV_RCPT_DCODE, &var_unv_rcpt_dcode, 200, 499,
6525	VAR_MUL_RCPT_CODE, DEF_MUL_RCPT_CODE, &var_mul_rcpt_code, 0, 0,
6526	VAR_LOCAL_RCPT_CODE, DEF_LOCAL_RCPT_CODE, &var_local_rcpt_code, 0, 0,
6527	VAR_VIRT_ALIAS_CODE, DEF_VIRT_ALIAS_CODE, &var_virt_alias_code, 0, 0,
6528	VAR_VIRT_MAILBOX_CODE, DEF_VIRT_MAILBOX_CODE, &var_virt_mailbox_code, 0, 0,
6529	VAR_RELAY_RCPT_CODE, DEF_RELAY_RCPT_CODE, &var_relay_rcpt_code, 0, 0,
6530	VAR_PLAINTEXT_CODE, DEF_PLAINTEXT_CODE, &var_plaintext_code, 0, 0,
6531	VAR_SMTPD_CRATE_LIMIT, DEF_SMTPD_CRATE_LIMIT, &var_smtpd_crate_limit, 0, 0,
6532	VAR_SMTPD_CCONN_LIMIT, DEF_SMTPD_CCONN_LIMIT, &var_smtpd_cconn_limit, 0, 0,
6533	VAR_SMTPD_CMAIL_LIMIT, DEF_SMTPD_CMAIL_LIMIT, &var_smtpd_cmail_limit, 0, 0,
6534	VAR_SMTPD_CRCPT_LIMIT, DEF_SMTPD_CRCPT_LIMIT, &var_smtpd_crcpt_limit, 0, 0,
6535	VAR_SMTPD_CNTLS_LIMIT, DEF_SMTPD_CNTLS_LIMIT, &var_smtpd_cntls_limit, 0, 0,
6536	VAR_SMTPD_CAUTH_LIMIT, DEF_SMTPD_CAUTH_LIMIT, &var_smtpd_cauth_limit, 0, 0,
6537	VAR_SMTPD_CIPV4_PREFIX, DEF_SMTPD_CIPV4_PREFIX, &var_smtpd_cipv4_prefix, 0, MAX_SMTPD_CIPV4_PREFIX,
6538	VAR_SMTPD_CIPV6_PREFIX, DEF_SMTPD_CIPV6_PREFIX, &var_smtpd_cipv6_prefix, 0, MAX_SMTPD_CIPV6_PREFIX,
6539#ifdef USE_TLS
6540	VAR_SMTPD_TLS_CCERT_VD, DEF_SMTPD_TLS_CCERT_VD, &var_smtpd_tls_ccert_vd, 0, 0,
6541#endif
6542	VAR_SMTPD_SASL_RESP_LIMIT, DEF_SMTPD_SASL_RESP_LIMIT, &var_smtpd_sasl_resp_limit, DEF_SMTPD_SASL_RESP_LIMIT, 0,
6543	VAR_SMTPD_POLICY_REQ_LIMIT, DEF_SMTPD_POLICY_REQ_LIMIT, &var_smtpd_policy_req_limit, 0, 0,
6544	VAR_SMTPD_POLICY_TRY_LIMIT, DEF_SMTPD_POLICY_TRY_LIMIT, &var_smtpd_policy_try_limit, 1, 0,
6545	VAR_SMTPD_MIN_DATA_RATE, DEF_SMTPD_MIN_DATA_RATE, &var_smtpd_min_data_rate, 1, 0,
6546	0,
6547    };
6548    static const CONFIG_LONG_TABLE long_table[] = {
6549	VAR_QUEUE_MINFREE, DEF_QUEUE_MINFREE, &var_queue_minfree, 0, 0,
6550	0,
6551    };
6552    static const CONFIG_TIME_TABLE time_table[] = {
6553	VAR_SMTPD_TMOUT, DEF_SMTPD_TMOUT, &var_smtpd_tmout, 1, 0,
6554	VAR_SMTPD_ERR_SLEEP, DEF_SMTPD_ERR_SLEEP, &var_smtpd_err_sleep, 0, 0,
6555	VAR_SMTPD_PROXY_TMOUT, DEF_SMTPD_PROXY_TMOUT, &var_smtpd_proxy_tmout, 1, 0,
6556	VAR_VERIFY_POLL_DELAY, DEF_VERIFY_POLL_DELAY, &var_verify_poll_delay, 1, 0,
6557	VAR_SMTPD_POLICY_TMOUT, DEF_SMTPD_POLICY_TMOUT, &var_smtpd_policy_tmout, 1, 0,
6558	VAR_SMTPD_POLICY_IDLE, DEF_SMTPD_POLICY_IDLE, &var_smtpd_policy_idle, 1, 0,
6559	VAR_SMTPD_POLICY_TTL, DEF_SMTPD_POLICY_TTL, &var_smtpd_policy_ttl, 1, 0,
6560#ifdef USE_TLS
6561	VAR_SMTPD_STARTTLS_TMOUT, DEF_SMTPD_STARTTLS_TMOUT, &var_smtpd_starttls_tmout, 1, 0,
6562#endif
6563	VAR_MILT_CONN_TIME, DEF_MILT_CONN_TIME, &var_milt_conn_time, 1, 0,
6564	VAR_MILT_CMD_TIME, DEF_MILT_CMD_TIME, &var_milt_cmd_time, 1, 0,
6565	VAR_MILT_MSG_TIME, DEF_MILT_MSG_TIME, &var_milt_msg_time, 1, 0,
6566	VAR_VERIFY_SENDER_TTL, DEF_VERIFY_SENDER_TTL, &var_verify_sender_ttl, 0, 0,
6567	VAR_SMTPD_UPROXY_TMOUT, DEF_SMTPD_UPROXY_TMOUT, &var_smtpd_uproxy_tmout, 1, 0,
6568	VAR_SMTPD_POLICY_TRY_DELAY, DEF_SMTPD_POLICY_TRY_DELAY, &var_smtpd_policy_try_delay, 1, 0,
6569	0,
6570    };
6571    static const CONFIG_BOOL_TABLE bool_table[] = {
6572	VAR_HELO_REQUIRED, DEF_HELO_REQUIRED, &var_helo_required,
6573	VAR_SMTPD_DELAY_REJECT, DEF_SMTPD_DELAY_REJECT, &var_smtpd_delay_reject,
6574	VAR_STRICT_RFC821_ENV, DEF_STRICT_RFC821_ENV, &var_strict_rfc821_env,
6575	VAR_DISABLE_VRFY_CMD, DEF_DISABLE_VRFY_CMD, &var_disable_vrfy_cmd,
6576	VAR_ALLOW_UNTRUST_ROUTE, DEF_ALLOW_UNTRUST_ROUTE, &var_allow_untrust_route,
6577	VAR_SMTPD_SASL_ENABLE, DEF_SMTPD_SASL_ENABLE, &var_smtpd_sasl_enable,
6578	VAR_SMTPD_SASL_AUTH_HDR, DEF_SMTPD_SASL_AUTH_HDR, &var_smtpd_sasl_auth_hdr,
6579	VAR_BROKEN_AUTH_CLNTS, DEF_BROKEN_AUTH_CLNTS, &var_broken_auth_clients,
6580	VAR_SHOW_UNK_RCPT_TABLE, DEF_SHOW_UNK_RCPT_TABLE, &var_show_unk_rcpt_table,
6581	VAR_SMTPD_REJ_UNL_FROM, DEF_SMTPD_REJ_UNL_FROM, &var_smtpd_rej_unl_from,
6582	VAR_SMTPD_REJ_UNL_RCPT, DEF_SMTPD_REJ_UNL_RCPT, &var_smtpd_rej_unl_rcpt,
6583	VAR_SMTPD_USE_TLS, DEF_SMTPD_USE_TLS, &var_smtpd_use_tls,
6584	VAR_SMTPD_ENFORCE_TLS, DEF_SMTPD_ENFORCE_TLS, &var_smtpd_enforce_tls,
6585	VAR_SMTPD_TLS_WRAPPER, DEF_SMTPD_TLS_WRAPPER, &var_smtpd_tls_wrappermode,
6586	VAR_SMTPD_TLS_AUTH_ONLY, DEF_SMTPD_TLS_AUTH_ONLY, &var_smtpd_tls_auth_only,
6587#ifdef USE_TLS
6588	VAR_SMTPD_TLS_ACERT, DEF_SMTPD_TLS_ACERT, &var_smtpd_tls_ask_ccert,
6589	VAR_SMTPD_TLS_RCERT, DEF_SMTPD_TLS_RCERT, &var_smtpd_tls_req_ccert,
6590	VAR_SMTPD_TLS_RECHEAD, DEF_SMTPD_TLS_RECHEAD, &var_smtpd_tls_received_header,
6591	VAR_SMTPD_TLS_SET_SESSID, DEF_SMTPD_TLS_SET_SESSID, &var_smtpd_tls_set_sessid,
6592#endif
6593	VAR_SMTPD_PEERNAME_LOOKUP, DEF_SMTPD_PEERNAME_LOOKUP, &var_smtpd_peername_lookup,
6594	VAR_SMTPD_DELAY_OPEN, DEF_SMTPD_DELAY_OPEN, &var_smtpd_delay_open,
6595	VAR_SMTPD_CLIENT_PORT_LOG, DEF_SMTPD_CLIENT_PORT_LOG, &var_smtpd_client_port_log,
6596	VAR_SMTPD_FORBID_UNAUTH_PIPE, DEF_SMTPD_FORBID_UNAUTH_PIPE, &var_smtpd_forbid_unauth_pipe,
6597	VAR_SMTPD_FORBID_BARE_LF, DEF_SMTPD_FORBID_BARE_LF, &var_smtpd_forbid_bare_lf,
6598	0,
6599    };
6600    static const CONFIG_NBOOL_TABLE nbool_table[] = {
6601	VAR_RELAY_BEFORE_RCPT_CHECKS, DEF_RELAY_BEFORE_RCPT_CHECKS, &var_relay_before_rcpt_checks,
6602	VAR_SMTPD_REQ_DEADLINE, DEF_SMTPD_REQ_DEADLINE, &var_smtpd_req_deadline,
6603	0,
6604    };
6605    static const CONFIG_STR_TABLE str_table[] = {
6606	VAR_SMTPD_BANNER, DEF_SMTPD_BANNER, &var_smtpd_banner, 1, 0,
6607	VAR_NOTIFY_CLASSES, DEF_NOTIFY_CLASSES, &var_notify_classes, 0, 0,
6608	VAR_CLIENT_CHECKS, DEF_CLIENT_CHECKS, &var_client_checks, 0, 0,
6609	VAR_HELO_CHECKS, DEF_HELO_CHECKS, &var_helo_checks, 0, 0,
6610	VAR_MAIL_CHECKS, DEF_MAIL_CHECKS, &var_mail_checks, 0, 0,
6611	VAR_RELAY_CHECKS, DEF_RELAY_CHECKS, &var_relay_checks, 0, 0,
6612	VAR_RCPT_CHECKS, DEF_RCPT_CHECKS, &var_rcpt_checks, 0, 0,
6613	VAR_ETRN_CHECKS, DEF_ETRN_CHECKS, &var_etrn_checks, 0, 0,
6614	VAR_DATA_CHECKS, DEF_DATA_CHECKS, &var_data_checks, 0, 0,
6615	VAR_EOD_CHECKS, DEF_EOD_CHECKS, &var_eod_checks, 0, 0,
6616	VAR_MAPS_RBL_DOMAINS, DEF_MAPS_RBL_DOMAINS, &var_maps_rbl_domains, 0, 0,
6617	VAR_RBL_REPLY_MAPS, DEF_RBL_REPLY_MAPS, &var_rbl_reply_maps, 0, 0,
6618	VAR_BOUNCE_RCPT, DEF_BOUNCE_RCPT, &var_bounce_rcpt, 1, 0,
6619	VAR_ERROR_RCPT, DEF_ERROR_RCPT, &var_error_rcpt, 1, 0,
6620	VAR_REST_CLASSES, DEF_REST_CLASSES, &var_rest_classes, 0, 0,
6621	VAR_CANONICAL_MAPS, DEF_CANONICAL_MAPS, &var_canonical_maps, 0, 0,
6622	VAR_SEND_CANON_MAPS, DEF_SEND_CANON_MAPS, &var_send_canon_maps, 0, 0,
6623	VAR_RCPT_CANON_MAPS, DEF_RCPT_CANON_MAPS, &var_rcpt_canon_maps, 0, 0,
6624	VAR_VIRT_ALIAS_MAPS, DEF_VIRT_ALIAS_MAPS, &var_virt_alias_maps, 0, 0,
6625	VAR_VIRT_MAILBOX_MAPS, DEF_VIRT_MAILBOX_MAPS, &var_virt_mailbox_maps, 0, 0,
6626	VAR_ALIAS_MAPS, DEF_ALIAS_MAPS, &var_alias_maps, 0, 0,
6627	VAR_LOCAL_RCPT_MAPS, DEF_LOCAL_RCPT_MAPS, &var_local_rcpt_maps, 0, 0,
6628	VAR_SMTPD_SASL_OPTS, DEF_SMTPD_SASL_OPTS, &var_smtpd_sasl_opts, 0, 0,
6629	VAR_SMTPD_SASL_PATH, DEF_SMTPD_SASL_PATH, &var_smtpd_sasl_path, 1, 0,
6630	VAR_SMTPD_SASL_SERVICE, DEF_SMTPD_SASL_SERVICE, &var_smtpd_sasl_service, 1, 0,
6631	VAR_CYRUS_CONF_PATH, DEF_CYRUS_CONF_PATH, &var_cyrus_conf_path, 0, 0,
6632	VAR_SMTPD_SASL_REALM, DEF_SMTPD_SASL_REALM, &var_smtpd_sasl_realm, 0, 0,
6633	VAR_SMTPD_SASL_EXCEPTIONS_NETWORKS, DEF_SMTPD_SASL_EXCEPTIONS_NETWORKS, &var_smtpd_sasl_exceptions_networks, 0, 0,
6634	VAR_FILTER_XPORT, DEF_FILTER_XPORT, &var_filter_xport, 0, 0,
6635	VAR_PERM_MX_NETWORKS, DEF_PERM_MX_NETWORKS, &var_perm_mx_networks, 0, 0,
6636	VAR_SMTPD_SND_AUTH_MAPS, DEF_SMTPD_SND_AUTH_MAPS, &var_smtpd_snd_auth_maps, 0, 0,
6637	VAR_SMTPD_NOOP_CMDS, DEF_SMTPD_NOOP_CMDS, &var_smtpd_noop_cmds, 0, 0,
6638	VAR_SMTPD_FORBID_CMDS, DEF_SMTPD_FORBID_CMDS, &var_smtpd_forbid_cmds, 0, 0,
6639	VAR_SMTPD_NULL_KEY, DEF_SMTPD_NULL_KEY, &var_smtpd_null_key, 0, 0,
6640	VAR_RELAY_RCPT_MAPS, DEF_RELAY_RCPT_MAPS, &var_relay_rcpt_maps, 0, 0,
6641	VAR_VERIFY_SENDER, DEF_VERIFY_SENDER, &var_verify_sender, 0, 0,
6642	VAR_VERP_CLIENTS, DEF_VERP_CLIENTS, &var_verp_clients, 0, 0,
6643	VAR_SMTPD_PROXY_FILT, DEF_SMTPD_PROXY_FILT, &var_smtpd_proxy_filt, 0, 0,
6644	VAR_SMTPD_PROXY_EHLO, DEF_SMTPD_PROXY_EHLO, &var_smtpd_proxy_ehlo, 0, 0,
6645	VAR_SMTPD_PROXY_OPTS, DEF_SMTPD_PROXY_OPTS, &var_smtpd_proxy_opts, 0, 0,
6646	VAR_INPUT_TRANSP, DEF_INPUT_TRANSP, &var_input_transp, 0, 0,
6647	VAR_XCLIENT_HOSTS, DEF_XCLIENT_HOSTS, &var_xclient_hosts, 0, 0,
6648	VAR_XFORWARD_HOSTS, DEF_XFORWARD_HOSTS, &var_xforward_hosts, 0, 0,
6649	VAR_SMTPD_HOGGERS, DEF_SMTPD_HOGGERS, &var_smtpd_hoggers, 0, 0,
6650	VAR_LOC_RWR_CLIENTS, DEF_LOC_RWR_CLIENTS, &var_local_rwr_clients, 0, 0,
6651	VAR_SMTPD_EHLO_DIS_WORDS, DEF_SMTPD_EHLO_DIS_WORDS, &var_smtpd_ehlo_dis_words, 0, 0,
6652	VAR_SMTPD_EHLO_DIS_MAPS, DEF_SMTPD_EHLO_DIS_MAPS, &var_smtpd_ehlo_dis_maps, 0, 0,
6653#ifdef USE_TLS
6654	VAR_RELAY_CCERTS, DEF_RELAY_CCERTS, &var_smtpd_relay_ccerts, 0, 0,
6655	VAR_SMTPD_SASL_TLS_OPTS, DEF_SMTPD_SASL_TLS_OPTS, &var_smtpd_sasl_tls_opts, 0, 0,
6656	VAR_SMTPD_TLS_CHAIN_FILES, DEF_SMTPD_TLS_CHAIN_FILES, &var_smtpd_tls_chain_files, 0, 0,
6657	VAR_SMTPD_TLS_CERT_FILE, DEF_SMTPD_TLS_CERT_FILE, &var_smtpd_tls_cert_file, 0, 0,
6658	VAR_SMTPD_TLS_KEY_FILE, DEF_SMTPD_TLS_KEY_FILE, &var_smtpd_tls_key_file, 0, 0,
6659	VAR_SMTPD_TLS_DCERT_FILE, DEF_SMTPD_TLS_DCERT_FILE, &var_smtpd_tls_dcert_file, 0, 0,
6660	VAR_SMTPD_TLS_DKEY_FILE, DEF_SMTPD_TLS_DKEY_FILE, &var_smtpd_tls_dkey_file, 0, 0,
6661	VAR_SMTPD_TLS_ECCERT_FILE, DEF_SMTPD_TLS_ECCERT_FILE, &var_smtpd_tls_eccert_file, 0, 0,
6662	VAR_SMTPD_TLS_ECKEY_FILE, DEF_SMTPD_TLS_ECKEY_FILE, &var_smtpd_tls_eckey_file, 0, 0,
6663	VAR_SMTPD_TLS_CA_FILE, DEF_SMTPD_TLS_CA_FILE, &var_smtpd_tls_CAfile, 0, 0,
6664	VAR_SMTPD_TLS_CA_PATH, DEF_SMTPD_TLS_CA_PATH, &var_smtpd_tls_CApath, 0, 0,
6665	VAR_SMTPD_TLS_CIPH, DEF_SMTPD_TLS_CIPH, &var_smtpd_tls_ciph, 1, 0,
6666	VAR_SMTPD_TLS_MAND_CIPH, DEF_SMTPD_TLS_MAND_CIPH, &var_smtpd_tls_mand_ciph, 1, 0,
6667	VAR_SMTPD_TLS_EXCL_CIPH, DEF_SMTPD_TLS_EXCL_CIPH, &var_smtpd_tls_excl_ciph, 0, 0,
6668	VAR_SMTPD_TLS_MAND_EXCL, DEF_SMTPD_TLS_MAND_EXCL, &var_smtpd_tls_mand_excl, 0, 0,
6669	VAR_SMTPD_TLS_PROTO, DEF_SMTPD_TLS_PROTO, &var_smtpd_tls_proto, 0, 0,
6670	VAR_SMTPD_TLS_MAND_PROTO, DEF_SMTPD_TLS_MAND_PROTO, &var_smtpd_tls_mand_proto, 0, 0,
6671	VAR_SMTPD_TLS_512_FILE, DEF_SMTPD_TLS_512_FILE, &var_smtpd_tls_dh512_param_file, 0, 0,
6672	VAR_SMTPD_TLS_1024_FILE, DEF_SMTPD_TLS_1024_FILE, &var_smtpd_tls_dh1024_param_file, 0, 0,
6673	VAR_SMTPD_TLS_EECDH, DEF_SMTPD_TLS_EECDH, &var_smtpd_tls_eecdh, 1, 0,
6674	VAR_SMTPD_TLS_FPT_DGST, DEF_SMTPD_TLS_FPT_DGST, &var_smtpd_tls_fpt_dgst, 1, 0,
6675	VAR_SMTPD_TLS_LOGLEVEL, DEF_SMTPD_TLS_LOGLEVEL, &var_smtpd_tls_loglevel, 0, 0,
6676#endif
6677	VAR_SMTPD_TLS_LEVEL, DEF_SMTPD_TLS_LEVEL, &var_smtpd_tls_level, 0, 0,
6678	VAR_SMTPD_SASL_TYPE, DEF_SMTPD_SASL_TYPE, &var_smtpd_sasl_type, 1, 0,
6679	VAR_SMTPD_SASL_MECH_FILTER, DEF_SMTPD_SASL_MECH_FILTER, &var_smtpd_sasl_mech_filter, 0, 0,
6680	VAR_SMTPD_MILTERS, DEF_SMTPD_MILTERS, &var_smtpd_milters, 0, 0,
6681	VAR_MILT_CONN_MACROS, DEF_MILT_CONN_MACROS, &var_milt_conn_macros, 0, 0,
6682	VAR_MILT_HELO_MACROS, DEF_MILT_HELO_MACROS, &var_milt_helo_macros, 0, 0,
6683	VAR_MILT_MAIL_MACROS, DEF_MILT_MAIL_MACROS, &var_milt_mail_macros, 0, 0,
6684	VAR_MILT_RCPT_MACROS, DEF_MILT_RCPT_MACROS, &var_milt_rcpt_macros, 0, 0,
6685	VAR_MILT_DATA_MACROS, DEF_MILT_DATA_MACROS, &var_milt_data_macros, 0, 0,
6686	VAR_MILT_EOH_MACROS, DEF_MILT_EOH_MACROS, &var_milt_eoh_macros, 0, 0,
6687	VAR_MILT_EOD_MACROS, DEF_MILT_EOD_MACROS, &var_milt_eod_macros, 0, 0,
6688	VAR_MILT_UNK_MACROS, DEF_MILT_UNK_MACROS, &var_milt_unk_macros, 0, 0,
6689	VAR_MILT_PROTOCOL, DEF_MILT_PROTOCOL, &var_milt_protocol, 1, 0,
6690	VAR_MILT_DEF_ACTION, DEF_MILT_DEF_ACTION, &var_milt_def_action, 1, 0,
6691	VAR_MILT_DAEMON_NAME, DEF_MILT_DAEMON_NAME, &var_milt_daemon_name, 1, 0,
6692	VAR_MILT_V, DEF_MILT_V, &var_milt_v, 1, 0,
6693	VAR_MILT_MACRO_DEFLTS, DEF_MILT_MACRO_DEFLTS, &var_milt_macro_deflts, 0, 0,
6694	VAR_SMTPD_MILTER_MAPS, DEF_SMTPD_MILTER_MAPS, &var_smtpd_milter_maps, 0, 0,
6695	VAR_STRESS, DEF_STRESS, &var_stress, 0, 0,
6696	VAR_UNV_FROM_WHY, DEF_UNV_FROM_WHY, &var_unv_from_why, 0, 0,
6697	VAR_UNV_RCPT_WHY, DEF_UNV_RCPT_WHY, &var_unv_rcpt_why, 0, 0,
6698	VAR_REJECT_TMPF_ACT, DEF_REJECT_TMPF_ACT, &var_reject_tmpf_act, 1, 0,
6699	VAR_UNK_NAME_TF_ACT, DEF_UNK_NAME_TF_ACT, &var_unk_name_tf_act, 1, 0,
6700	VAR_UNK_ADDR_TF_ACT, DEF_UNK_ADDR_TF_ACT, &var_unk_addr_tf_act, 1, 0,
6701	VAR_UNV_RCPT_TF_ACT, DEF_UNV_RCPT_TF_ACT, &var_unv_rcpt_tf_act, 1, 0,
6702	VAR_UNV_FROM_TF_ACT, DEF_UNV_FROM_TF_ACT, &var_unv_from_tf_act, 1, 0,
6703	VAR_SMTPD_CMD_FILTER, DEF_SMTPD_CMD_FILTER, &var_smtpd_cmd_filter, 0, 0,
6704#ifdef USE_TLSPROXY
6705	VAR_TLSPROXY_SERVICE, DEF_TLSPROXY_SERVICE, &var_tlsproxy_service, 1, 0,
6706#endif
6707	VAR_SMTPD_ACL_PERM_LOG, DEF_SMTPD_ACL_PERM_LOG, &var_smtpd_acl_perm_log, 0, 0,
6708	VAR_SMTPD_UPROXY_PROTO, DEF_SMTPD_UPROXY_PROTO, &var_smtpd_uproxy_proto, 0, 0,
6709	VAR_SMTPD_POLICY_DEF_ACTION, DEF_SMTPD_POLICY_DEF_ACTION, &var_smtpd_policy_def_action, 1, 0,
6710	VAR_SMTPD_POLICY_CONTEXT, DEF_SMTPD_POLICY_CONTEXT, &var_smtpd_policy_context, 0, 0,
6711	VAR_SMTPD_DNS_RE_FILTER, DEF_SMTPD_DNS_RE_FILTER, &var_smtpd_dns_re_filter, 0, 0,
6712	VAR_SMTPD_REJ_FTR_MAPS, DEF_SMTPD_REJ_FTR_MAPS, &var_smtpd_rej_ftr_maps, 0, 0,
6713	VAR_HFROM_FORMAT, DEF_HFROM_FORMAT, &var_hfrom_format, 1, 0,
6714	VAR_SMTPD_FORBID_BARE_LF_EXCL, DEF_SMTPD_FORBID_BARE_LF_EXCL, &var_smtpd_forbid_bare_lf_excl, 0, 0,
6715	0,
6716    };
6717    static const CONFIG_RAW_TABLE raw_table[] = {
6718	VAR_SMTPD_EXP_FILTER, DEF_SMTPD_EXP_FILTER, &var_smtpd_exp_filter, 1, 0,
6719	VAR_DEF_RBL_REPLY, DEF_DEF_RBL_REPLY, &var_def_rbl_reply, 1, 0,
6720	VAR_SMTPD_REJ_FOOTER, DEF_SMTPD_REJ_FOOTER, &var_smtpd_rej_footer, 0, 0,
6721	0,
6722    };
6723
6724    /*
6725     * Fingerprint executables and core dumps.
6726     */
6727    MAIL_VERSION_STAMP_ALLOCATE;
6728
6729    /*
6730     * Pass control to the single-threaded service skeleton.
6731     */
6732    single_server_main(argc, argv, smtpd_service,
6733		       CA_MAIL_SERVER_NINT_TABLE(nint_table),
6734		       CA_MAIL_SERVER_INT_TABLE(int_table),
6735		       CA_MAIL_SERVER_LONG_TABLE(long_table),
6736		       CA_MAIL_SERVER_STR_TABLE(str_table),
6737		       CA_MAIL_SERVER_RAW_TABLE(raw_table),
6738		       CA_MAIL_SERVER_BOOL_TABLE(bool_table),
6739		       CA_MAIL_SERVER_NBOOL_TABLE(nbool_table),
6740		       CA_MAIL_SERVER_TIME_TABLE(time_table),
6741		       CA_MAIL_SERVER_PRE_INIT(pre_jail_init),
6742		       CA_MAIL_SERVER_PRE_ACCEPT(pre_accept),
6743		       CA_MAIL_SERVER_POST_INIT(post_jail_init),
6744		       0);
6745}
6746