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