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