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