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