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