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