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