1 /*        $NetBSD: sendmail.c,v 1.5 2025/02/25 19:15:49 christos Exp $          */
2 
3 /*++
4 /* NAME
5 /*        sendmail 1
6 /* SUMMARY
7 /*        Postfix to Sendmail compatibility interface
8 /* SYNOPSIS
9 /*        \fBsendmail\fR [\fIoption ...\fR] [\fIrecipient ...\fR]
10 /*
11 /*        \fBmailq\fR
12 /*        \fBsendmail -bp\fR
13 /*
14 /*        \fBnewaliases\fR
15 /*        \fBsendmail -I\fR
16 /* DESCRIPTION
17 /*        The Postfix \fBsendmail\fR(1) command implements the Postfix
18 /*        to Sendmail compatibility interface.
19 /*        For the sake of compatibility with existing applications, some
20 /*        Sendmail command-line options are recognized but silently ignored.
21 /*
22 /*        By default, Postfix \fBsendmail\fR(1) reads a message from
23 /*        standard input
24 /*        until EOF or until it reads a line with only a \fB.\fR character,
25 /*        and arranges for delivery.  Postfix \fBsendmail\fR(1) relies on the
26 /*        \fBpostdrop\fR(1) command to create a queue file in the \fBmaildrop\fR
27 /*        directory.
28 /*
29 /*        Specific command aliases are provided for other common modes of
30 /*        operation:
31 /* .IP \fBmailq\fR
32 /*        List the mail queue. Each entry shows the queue file ID, message
33 /*        size, arrival time, sender, and the recipients that still need to
34 /*        be delivered.  If mail could not be delivered upon the last attempt,
35 /*        the reason for failure is shown. The queue ID string is
36 /*        followed by an optional status character:
37 /* .RS
38 /* .IP \fB*\fR
39 /*        The message is in the \fBactive\fR queue, i.e. the message is
40 /*        selected for delivery.
41 /* .IP \fB!\fR
42 /*        The message is in the \fBhold\fR queue, i.e. no further delivery
43 /*        attempt will be made until the mail is taken off hold.
44 /* .IP \fB#\fR
45 /*        The message is forced to expire. See the \fBpostsuper\fR(1)
46 /*        options \fB-e\fR or \fB-f\fR.
47 /* .RE
48 /* .IP
49 /*        This mode of operation is implemented by executing the
50 /*        \fBpostqueue\fR(1) command.
51 /* .IP \fBnewaliases\fR
52 /*        Initialize the alias database.  If no input file is specified (with
53 /*        the \fB-oA\fR option, see below), the program processes the file(s)
54 /*        specified with the \fBalias_database\fR configuration parameter.
55 /*        If no alias database type is specified, the program uses the type
56 /*        specified with the \fBdefault_database_type\fR configuration parameter.
57 /*        This mode of operation is implemented by running the \fBpostalias\fR(1)
58 /*        command.
59 /* .sp
60 /*        Note: it may take a minute or so before an alias database update
61 /*        becomes visible. Use the "\fBpostfix reload\fR" command to eliminate
62 /*        this delay.
63 /* .PP
64 /*        These and other features can be selected by specifying the
65 /*        appropriate combination of command-line options. Some features are
66 /*        controlled by parameters in the \fBmain.cf\fR configuration file.
67 /*
68 /*        The following options are recognized:
69 /* .IP "\fB-Am\fR (ignored)"
70 /* .IP "\fB-Ac\fR (ignored)"
71 /*        Postfix sendmail uses the same configuration file regardless of
72 /*        whether or not a message is an initial submission.
73 /* .IP "\fB-B \fIbody_type\fR"
74 /*        The message body MIME type: \fB7BIT\fR or \fB8BITMIME\fR.
75 /* .IP \fB-bd\fR
76 /*        Go into daemon mode. This mode of operation is implemented by
77 /*        executing the "\fBpostfix start\fR" command.
78 /* .IP "\fB-bh\fR (ignored)"
79 /* .IP "\fB-bH\fR (ignored)"
80 /*        Postfix has no persistent host status database.
81 /* .IP \fB-bi\fR
82 /*        Initialize alias database. See the \fBnewaliases\fR
83 /*        command above.
84 /* .IP \fB-bl\fR
85 /*        Go into daemon mode. To accept only local connections as
86 /*        with Sendmail's \fB-bl\fR option, specify "\fBinet_interfaces
87 /*        = loopback\fR" in the Postfix \fBmain.cf\fR configuration
88 /*        file.
89 /* .IP \fB-bm\fR
90 /*        Read mail from standard input and arrange for delivery.
91 /*        This is the default mode of operation.
92 /* .IP \fB-bp\fR
93 /*        List the mail queue. See the \fBmailq\fR command above.
94 /* .IP \fB-bs\fR
95 /*        Stand-alone SMTP server mode. Read SMTP commands from
96 /*        standard input, and write responses to standard output.
97 /*        In stand-alone SMTP server mode, mail relaying and other
98 /*        access controls are disabled by default. To enable them,
99 /*        run the process as the \fBmail_owner\fR user.
100 /* .sp
101 /*        This mode of operation is implemented by running the
102 /*        \fBsmtpd\fR(8) daemon.
103 /* .IP \fB-bv\fR
104 /*        Do not collect or deliver a message. Instead, send an email
105 /*        report after verifying each recipient address.  This is useful
106 /*        for testing address rewriting and routing configurations.
107 /* .sp
108 /*        This feature is available in Postfix version 2.1 and later.
109 /* .IP "\fB-C \fIconfig_file\fR"
110 /* .IP "\fB-C \fIconfig_dir\fR"
111 /*        The path name of the Postfix \fBmain.cf\fR file, or of its
112 /*        parent directory. This information is ignored with Postfix
113 /*        versions before 2.3.
114 /*
115 /*        With Postfix version 3.2 and later, a non-default directory
116 /*        must be authorized in the default \fBmain.cf\fR file, through
117 /*        the alternate_config_directories or multi_instance_directories
118 /*        parameters.
119 /*
120 /*        With all Postfix versions, you can specify a directory pathname
121 /*        with the MAIL_CONFIG environment variable to override the
122 /*        location of configuration files.
123 /* .IP "\fB-F \fIfull_name\fR"
124 /*        Set the sender full name. This overrides the NAME environment
125 /*        variable, and is used only with messages that
126 /*        have no \fBFrom:\fR message header.
127 /* .IP "\fB-f \fIsender\fR"
128 /*        Set the envelope sender address. This is the address where
129 /*        delivery problems are sent to. With Postfix versions before 2.1, the
130 /*        \fBErrors-To:\fR message header overrides the error return address.
131 /* .IP \fB-G\fR
132 /*        Gateway (relay) submission, as opposed to initial user
133 /*        submission.  Either do not rewrite addresses at all, or
134 /*        update incomplete addresses with the domain information
135 /*        specified with \fBremote_header_rewrite_domain\fR.
136 /*
137 /*        This option is ignored before Postfix version 2.3.
138 /* .IP "\fB-h \fIhop_count\fR (ignored)"
139 /*        Hop count limit. Use the \fBhopcount_limit\fR configuration
140 /*        parameter instead.
141 /* .IP \fB-I\fR
142 /*        Initialize alias database. See the \fBnewaliases\fR
143 /*        command above.
144 /* .IP "\fB-i\fR"
145 /*        When reading a message from standard input, don't treat a line
146 /*        with only a \fB.\fR character as the end of input.
147 /* .IP "\fB-L \fIlabel\fR (ignored)"
148 /*        The logging label. Use the \fBsyslog_name\fR configuration
149 /*        parameter instead.
150 /* .IP "\fB-m\fR (ignored)"
151 /*        Backwards compatibility.
152 /* .IP "\fB-N \fIdsn\fR (default: 'delay, failure')"
153 /*        Delivery status notification control. Specify either a
154 /*        comma-separated list with one or more of \fBfailure\fR (send
155 /*        notification when delivery fails), \fBdelay\fR (send
156 /*        notification when delivery is delayed), or \fBsuccess\fR
157 /*        (send notification when the message is delivered); or specify
158 /*        \fBnever\fR (don't send any notifications at all).
159 /*
160 /*        This feature is available in Postfix 2.3 and later.
161 /* .IP "\fB-n\fR (ignored)"
162 /*        Backwards compatibility.
163 /* .IP "\fB-oA\fIalias_database\fR"
164 /*        Non-default alias database. Specify \fIpathname\fR or
165 /*        \fItype\fR:\fIpathname\fR. See \fBpostalias\fR(1) for
166 /*        details.
167 /* .IP "\fB-O \fIoption=value\fR (ignored)"
168 /*        Set the named \fIoption\fR to \fIvalue\fR. Use the equivalent
169 /*        configuration parameter in \fBmain.cf\fR instead.
170 /* .IP "\fB-o7\fR (ignored)"
171 /* .IP "\fB-o8\fR (ignored)"
172 /*        To send 8-bit or binary content, use an appropriate MIME encapsulation
173 /*        and specify the appropriate \fB-B\fR command-line option.
174 /* .IP "\fB-oi\fR"
175 /*        When reading a message from standard input, don't treat a line
176 /*        with only a \fB.\fR character as the end of input.
177 /* .IP "\fB-om\fR (ignored)"
178 /*        The sender is never eliminated from alias etc. expansions.
179 /* .IP "\fB-o \fIx value\fR (ignored)"
180 /*        Set option \fIx\fR to \fIvalue\fR. Use the equivalent
181 /*        configuration parameter in \fBmain.cf\fR instead.
182 /* .IP "\fB-r \fIsender\fR"
183 /*        Set the envelope sender address. This is the address where
184 /*        delivery problems are sent to. With Postfix versions before 2.1, the
185 /*        \fBErrors-To:\fR message header overrides the error return address.
186 /* .IP "\fB-R \fIreturn\fR"
187 /*        Delivery status notification control.  Specify "hdrs" to
188 /*        return only the header when a message bounces, "full" to
189 /*        return a full copy (the default behavior).
190 /*
191 /*        The \fB-R\fR option specifies an upper bound; Postfix will
192 /*        return only the header, when a full copy would exceed the
193 /*        bounce_size_limit setting.
194 /*
195 /*        This option is ignored before Postfix version 2.10.
196 /* .IP \fB-q\fR
197 /*        Attempt to deliver all queued mail. This is implemented by
198 /*        executing the \fBpostqueue\fR(1) command.
199 /*
200 /*        Warning: flushing undeliverable mail frequently will result in
201 /*        poor delivery performance of all other mail.
202 /* .IP "\fB-q\fIinterval\fR (ignored)"
203 /*        The interval between queue runs. Use the \fBqueue_run_delay\fR
204 /*        configuration parameter instead.
205 /* .IP \fB-qI\fIqueueid\fR
206 /*        Schedule immediate delivery of mail with the specified queue
207 /*        ID.  This option is implemented by executing the
208 /*        \fBpostqueue\fR(1) command, and is available with Postfix
209 /*        version 2.4 and later.
210 /* .IP \fB-qR\fIsite\fR
211 /*        Schedule immediate delivery of all mail that is queued for the named
212 /*        \fIsite\fR. This option accepts only \fIsite\fR names that are
213 /*        eligible for the "fast flush" service, and is implemented by
214 /*        executing the \fBpostqueue\fR(1) command.
215 /*        See \fBflush\fR(8) for more information about the "fast flush"
216 /*        service.
217 /* .IP \fB-qS\fIsite\fR
218 /*        This command is not implemented. Use the slower "\fBsendmail -q\fR"
219 /*        command instead.
220 /* .IP \fB-t\fR
221 /*        Extract recipients from message headers. These are added to any
222 /*        recipients specified on the command line.
223 /*
224 /*        With Postfix versions prior to 2.1, this option requires that
225 /*        no recipient addresses are specified on the command line.
226 /* .IP "\fB-U\fR (ignored)"
227 /*        Initial user submission.
228 /* .IP "\fB-V \fIenvid\fR"
229 /*        Specify the envelope ID for notification by servers that
230 /*        support DSN.
231 /*
232 /*        This feature is available in Postfix 2.3 and later.
233 /* .IP "\fB-XV\fR (Postfix 2.2 and earlier: \fB-V\fR)"
234 /*        Variable Envelope Return Path. Given an envelope sender address
235 /*        of the form \fIowner-listname\fR@\fIorigin\fR, each recipient
236 /*        \fIuser\fR@\fIdomain\fR receives mail with a personalized envelope
237 /*        sender address.
238 /* .sp
239 /*        By default, the personalized envelope sender address is
240 /*        \fIowner-listname\fB+\fIuser\fB=\fIdomain\fR@\fIorigin\fR. The default
241 /*        \fB+\fR and \fB=\fR characters are configurable with the
242 /*        \fBdefault_verp_delimiters\fR configuration parameter.
243 /* .IP "\fB-XV\fIxy\fR (Postfix 2.2 and earlier: \fB-V\fIxy\fR)"
244 /*        As \fB-XV\fR, but uses \fIx\fR and \fIy\fR as the VERP delimiter
245 /*        characters, instead of the characters specified with the
246 /*        \fBdefault_verp_delimiters\fR configuration parameter.
247 /* .IP \fB-v\fR
248 /*        Send an email report of the first delivery attempt (Postfix
249 /*        versions 2.1 and later). Mail delivery
250 /*        always happens in the background. When multiple \fB-v\fR
251 /*        options are given, enable verbose logging for debugging purposes.
252 /* .IP "\fB-X \fIlog_file\fR (ignored)"
253 /*        Log mailer traffic. Use the \fBdebug_peer_list\fR and
254 /*        \fBdebug_peer_level\fR configuration parameters instead.
255 /* SECURITY
256 /* .ad
257 /* .fi
258 /*        By design, this program is not set-user (or group) id.
259 /*        It is prepared to handle message content from untrusted,
260 /*        possibly remote, users.
261 /*
262 /*        However, like most Postfix programs, this program does not
263 /*        enforce a security policy on its command-line arguments.
264 /*        Instead, it relies on the UNIX system to enforce access
265 /*        policies based on the effective user and group IDs of the
266 /*        process. Concretely, this means that running Postfix commands
267 /*        as root (from sudo or equivalent) on behalf of a non-root
268 /*        user is likely to create privilege escalation opportunities.
269 /*
270 /*        If an application runs any Postfix programs on behalf of
271 /*        users that do not have normal shell access to Postfix
272 /*        commands, then that application MUST restrict user-specified
273 /*        command-line arguments to avoid privilege escalation.
274 /* .IP \(bu
275 /*        Filter all command-line arguments, for example arguments
276 /*        that contain a pathname or that specify a database access
277 /*        method. These pathname checks must reject user-controlled
278 /*        symlinks or hardlinks to sensitive files, and must not be
279 /*        vulnerable to TOCTOU race attacks.
280 /* .IP \(bu
281 /*        Disable command options processing for all command arguments
282 /*        that contain user-specified data. For example, the Postfix
283 /*        \fBsendmail\fR(1) command line MUST be structured as follows:
284 /*
285 /* .nf
286 /*            \fB/path/to/sendmail\fR \fIsystem-arguments\fR \fB--\fR \fIuser-arguments\fR
287 /* .fi
288 /*
289 /*        Here, the "\fB--\fR" disables command option processing for
290 /*        all \fIuser-arguments\fR that follow.
291 /* .IP
292 /*        Without the "\fB--\fR", a malicious user could enable Postfix
293 /*        \fBsendmail\fR(1) command options, by specifying an email
294 /*        address that starts with "\fB-\fR".
295 /* DIAGNOSTICS
296 /*        Problems are logged to \fBsyslogd\fR(8) or \fBpostlogd\fR(8),
297 /*        and to the standard error stream.
298 /* ENVIRONMENT
299 /* .ad
300 /* .fi
301 /* .IP \fBMAIL_CONFIG\fR
302 /*        Directory with Postfix configuration files.
303 /* .IP "\fBMAIL_VERBOSE\fR (value does not matter)"
304 /*        Enable verbose logging for debugging purposes.
305 /* .IP "\fBMAIL_DEBUG\fR (value does not matter)"
306 /*        Enable debugging with an external command, as specified with the
307 /*        \fBdebugger_command\fR configuration parameter.
308 /* .IP \fBNAME\fR
309 /*        The sender full name. This is used only with messages that
310 /*        have no \fBFrom:\fR message header. See also the \fB-F\fR
311 /*        option above.
312 /* CONFIGURATION PARAMETERS
313 /* .ad
314 /* .fi
315 /*        The following \fBmain.cf\fR parameters are especially relevant to
316 /*        this program.
317 /*        The text below provides only a parameter summary. See
318 /*        \fBpostconf\fR(5) for more details including examples.
319 /* COMPATIBILITY CONTROLS
320 /* .ad
321 /* .fi
322 /*        Available with Postfix 2.9 and later:
323 /* .IP "\fBsendmail_fix_line_endings (always)\fR"
324 /*        Controls how the Postfix sendmail command converts email message
325 /*        line endings from <CR><LF> into UNIX format (<LF>).
326 /* TROUBLE SHOOTING CONTROLS
327 /* .ad
328 /* .fi
329 /*        The DEBUG_README file gives examples of how to troubleshoot a
330 /*        Postfix system.
331 /* .IP "\fBdebugger_command (empty)\fR"
332 /*        The external command to execute when a Postfix daemon program is
333 /*        invoked with the -D option.
334 /* .IP "\fBdebug_peer_level (2)\fR"
335 /*        The increment in verbose logging level when a nexthop destination,
336 /*        remote client or server name or network address matches a pattern
337 /*        given with the debug_peer_list parameter.
338 /* .IP "\fBdebug_peer_list (empty)\fR"
339 /*        Optional list of nexthop destination, remote client or server
340 /*        name or network address patterns that, if matched, cause the verbose
341 /*        logging level to increase by the amount specified in $debug_peer_level.
342 /* ACCESS CONTROLS
343 /* .ad
344 /* .fi
345 /*        Available in Postfix version 2.2 and later:
346 /* .IP "\fBauthorized_flush_users (static:anyone)\fR"
347 /*        List of users who are authorized to flush the queue.
348 /* .IP "\fBauthorized_mailq_users (static:anyone)\fR"
349 /*        List of users who are authorized to view the queue.
350 /* .IP "\fBauthorized_submit_users (static:anyone)\fR"
351 /*        List of users who are authorized to submit mail with the \fBsendmail\fR(1)
352 /*        command (and with the privileged \fBpostdrop\fR(1) helper command).
353 /* RESOURCE AND RATE CONTROLS
354 /* .ad
355 /* .fi
356 /* .IP "\fBbounce_size_limit (50000)\fR"
357 /*        The maximal amount of original message text that is sent in a
358 /*        non-delivery notification.
359 /* .IP "\fBfork_attempts (5)\fR"
360 /*        The maximal number of attempts to fork() a child process.
361 /* .IP "\fBfork_delay (1s)\fR"
362 /*        The delay between attempts to fork() a child process.
363 /* .IP "\fBhopcount_limit (50)\fR"
364 /*        The maximal number of Received:  message headers that is allowed
365 /*        in the primary message headers.
366 /* .IP "\fBqueue_run_delay (300s)\fR"
367 /*        The time between deferred queue scans by the queue manager;
368 /*        prior to Postfix 2.4 the default value was 1000s.
369 /* FAST FLUSH CONTROLS
370 /* .ad
371 /* .fi
372 /*        The ETRN_README file describes configuration and operation
373 /*        details for the Postfix "fast flush" service.
374 /* .IP "\fBfast_flush_domains ($relay_domains)\fR"
375 /*        Optional list of destinations that are eligible for per-destination
376 /*        logfiles with mail that is queued to those destinations.
377 /* VERP CONTROLS
378 /* .ad
379 /* .fi
380 /*        The VERP_README file describes configuration and operation
381 /*        details of Postfix support for variable envelope return
382 /*        path addresses.
383 /* .IP "\fBdefault_verp_delimiters (+=)\fR"
384 /*        The two default VERP delimiter characters.
385 /* .IP "\fBverp_delimiter_filter (-=+)\fR"
386 /*        The characters Postfix accepts as VERP delimiter characters on the
387 /*        Postfix \fBsendmail\fR(1) command line and in SMTP commands.
388 /* MISCELLANEOUS CONTROLS
389 /* .ad
390 /* .fi
391 /* .IP "\fBalias_database (see 'postconf -d' output)\fR"
392 /*        The alias databases for \fBlocal\fR(8) delivery that are updated with
393 /*        "\fBnewaliases\fR" or with "\fBsendmail -bi\fR".
394 /* .IP "\fBcommand_directory (see 'postconf -d' output)\fR"
395 /*        The location of all postfix administrative commands.
396 /* .IP "\fBconfig_directory (see 'postconf -d' output)\fR"
397 /*        The default location of the Postfix main.cf and master.cf
398 /*        configuration files.
399 /* .IP "\fBdaemon_directory (see 'postconf -d' output)\fR"
400 /*        The directory with Postfix support programs and daemon programs.
401 /* .IP "\fBdefault_database_type (see 'postconf -d' output)\fR"
402 /*        The default database type for use in \fBnewaliases\fR(1), \fBpostalias\fR(1)
403 /*        and \fBpostmap\fR(1) commands.
404 /* .IP "\fBdelay_warning_time (0h)\fR"
405 /*        The time after which the sender receives a copy of the message
406 /*        headers of mail that is still queued.
407 /* .IP "\fBimport_environment (see 'postconf -d' output)\fR"
408 /*        The list of environment variables that a privileged Postfix
409 /*        process will import from a non-Postfix parent process, or name=value
410 /*        environment overrides.
411 /* .IP "\fBmail_owner (postfix)\fR"
412 /*        The UNIX system account that owns the Postfix queue and most Postfix
413 /*        daemon processes.
414 /* .IP "\fBqueue_directory (see 'postconf -d' output)\fR"
415 /*        The location of the Postfix top-level queue directory.
416 /* .IP "\fBremote_header_rewrite_domain (empty)\fR"
417 /*        Rewrite or add message headers in mail from remote clients if
418 /*        the remote_header_rewrite_domain parameter value is non-empty,
419 /*        updating incomplete addresses with the domain specified in the
420 /*        remote_header_rewrite_domain parameter, and adding missing headers.
421 /* .IP "\fBsyslog_facility (mail)\fR"
422 /*        The syslog facility of Postfix logging.
423 /* .IP "\fBsyslog_name (see 'postconf -d' output)\fR"
424 /*        A prefix that is prepended to the process name in syslog
425 /*        records, so that, for example, "smtpd" becomes "prefix/smtpd".
426 /* .PP
427 /*        Postfix 3.2 and later:
428 /* .IP "\fBalternate_config_directories (empty)\fR"
429 /*        A list of non-default Postfix configuration directories that may
430 /*        be specified with "-c config_directory" on the command line (in the
431 /*        case of \fBsendmail\fR(1), with the "-C" option), or via the MAIL_CONFIG
432 /*        environment parameter.
433 /* .IP "\fBmulti_instance_directories (empty)\fR"
434 /*        An optional list of non-default Postfix configuration directories;
435 /*        these directories belong to additional Postfix instances that share
436 /*        the Postfix executable files and documentation with the default
437 /*        Postfix instance, and that are started, stopped, etc., together
438 /*        with the default Postfix instance.
439 /* FILES
440 /*        /var/spool/postfix, mail queue
441 /*        /etc/postfix, configuration files
442 /* SEE ALSO
443 /*        pickup(8), mail pickup daemon
444 /*        qmgr(8), queue manager
445 /*        smtpd(8), SMTP server
446 /*        flush(8), fast flush service
447 /*        postsuper(1), queue maintenance
448 /*        postalias(1), create/update/query alias database
449 /*        postdrop(1), mail posting utility
450 /*        postfix(1), mail system control
451 /*        postqueue(1), mail queue control
452 /*        postlogd(8), Postfix logging
453 /*        syslogd(8), system logging
454 /* README_FILES
455 /* .ad
456 /* .fi
457 /*        Use "\fBpostconf readme_directory\fR" or
458 /*        "\fBpostconf html_directory\fR" to locate this information.
459 /* .na
460 /* .nf
461 /*        DEBUG_README, Postfix debugging howto
462 /*        ETRN_README, Postfix ETRN howto
463 /*        VERP_README, Postfix VERP howto
464 /* LICENSE
465 /* .ad
466 /* .fi
467 /*        The Secure Mailer license must be distributed with this software.
468 /* AUTHOR(S)
469 /*        Wietse Venema
470 /*        IBM T.J. Watson Research
471 /*        P.O. Box 704
472 /*        Yorktown Heights, NY 10598, USA
473 /*
474 /*        Wietse Venema
475 /*        Google, Inc.
476 /*        111 8th Avenue
477 /*        New York, NY 10011, USA
478 /*--*/
479 
480 /* System library. */
481 
482 #include <sys_defs.h>
483 #include <sys/stat.h>
484 #include <unistd.h>
485 #include <string.h>
486 #include <stdio.h>                      /* remove() */
487 #include <stdlib.h>
488 #include <signal.h>
489 #include <fcntl.h>
490 #include <time.h>
491 #include <errno.h>
492 #include <ctype.h>
493 #include <stdarg.h>
494 #include <sysexits.h>
495 
496 /* Utility library. */
497 
498 #include <msg.h>
499 #include <mymalloc.h>
500 #include <vstream.h>
501 #include <msg_vstream.h>
502 #include <vstring_vstream.h>
503 #include <username.h>
504 #include <fullname.h>
505 #include <argv.h>
506 #include <safe.h>
507 #include <iostuff.h>
508 #include <stringops.h>
509 #include <set_ugid.h>
510 #include <connect.h>
511 #include <split_at.h>
512 #include <name_code.h>
513 #include <warn_stat.h>
514 #include <clean_env.h>
515 #include <maillog_client.h>
516 
517 /* Global library. */
518 
519 #include <mail_queue.h>
520 #include <mail_proto.h>
521 #include <mail_params.h>
522 #include <mail_version.h>
523 #include <record.h>
524 #include <rec_type.h>
525 #include <rec_streamlf.h>
526 #include <mail_conf.h>
527 #include <cleanup_user.h>
528 #include <mail_task.h>
529 #include <mail_run.h>
530 #include <debug_process.h>
531 #include <tok822.h>
532 #include <mail_flush.h>
533 #include <mail_stream.h>
534 #include <verp_sender.h>
535 #include <deliver_request.h>
536 #include <mime_state.h>
537 #include <header_opts.h>
538 #include <mail_dict.h>
539 #include <user_acl.h>
540 #include <dsn_mask.h>
541 #include <mail_parm_split.h>
542 
543 /* Application-specific. */
544 
545  /*
546   * Modes of operation.
547   */
548 #define SM_MODE_ENQUEUE                 1         /* delivery mode */
549 #define SM_MODE_NEWALIAS      2         /* initialize alias database */
550 #define SM_MODE_MAILQ                   3         /* list mail queue */
551 #define SM_MODE_DAEMON                  4         /* daemon mode */
552 #define SM_MODE_USER                    5         /* user (stand-alone) mode */
553 #define SM_MODE_FLUSHQ                  6         /* user (stand-alone) mode */
554 #define SM_MODE_IGNORE                  7         /* ignore this mode */
555 
556  /*
557   * Flag parade. Flags 8-15 are reserved for delivery request trace flags.
558   */
559 #define SM_FLAG_AEOF          (1<<0)              /* archaic EOF */
560 #define SM_FLAG_XRCPT         (1<<1)              /* extract recipients from headers */
561 
562 #define SM_FLAG_DEFAULT       (SM_FLAG_AEOF)
563 
564  /*
565   * VERP support.
566   */
567 static char *verp_delims;
568 
569  /*
570   * Callback context for extracting recipients.
571   */
572 typedef struct SM_STATE {
573     VSTREAM *dst;                       /* output stream */
574     ARGV   *recipients;                           /* recipients from regular headers */
575     ARGV   *resent_recip;               /* recipients from resent headers */
576     int     resent;                     /* resent flag */
577     const char *saved_sender;           /* for error messages */
578     uid_t   uid;                        /* for error messages */
579     VSTRING *temp;                      /* scratch buffer */
580 } SM_STATE;
581 
582  /*
583   * Mail submission ACL, line-end fixing.
584   */
585 char   *var_submit_acl;
586 char   *var_sm_fix_eol;
587 
588 static const CONFIG_STR_TABLE str_table[] = {
589     VAR_SUBMIT_ACL, DEF_SUBMIT_ACL, &var_submit_acl, 0, 0,
590     VAR_SM_FIX_EOL, DEF_SM_FIX_EOL, &var_sm_fix_eol, 1, 0,
591     0,
592 };
593 
594  /*
595   * Silly little macros (SLMs).
596   */
597 #define STR         vstring_str
598 
599 /* output_text - output partial or complete text line */
600 
output_text(void * context,int rec_type,const char * buf,ssize_t len,off_t unused_offset)601 static void output_text(void *context, int rec_type, const char *buf, ssize_t len,
602                                       off_t unused_offset)
603 {
604     SM_STATE *state = (SM_STATE *) context;
605 
606     if (rec_put(state->dst, rec_type, buf, len) < 0)
607           msg_fatal_status(EX_TEMPFAIL,
608                                "%s(%ld): error writing queue file: %m",
609                                state->saved_sender, (long) state->uid);
610 }
611 
612 /* output_header - output one message header */
613 
output_header(void * context,int header_class,const HEADER_OPTS * header_info,VSTRING * buf,off_t offset)614 static void output_header(void *context, int header_class,
615                                         const HEADER_OPTS *header_info,
616                                         VSTRING *buf, off_t offset)
617 {
618     SM_STATE *state = (SM_STATE *) context;
619     TOK822 *tree;
620     TOK822 **addr_list;
621     TOK822 **tpp;
622     ARGV   *rcpt;
623     char   *start;
624     char   *line;
625     char   *next_line;
626     ssize_t len;
627 
628     /*
629      * Parse the header line, and save copies of recipient addresses in the
630      * appropriate place.
631      */
632     if (header_class == MIME_HDR_PRIMARY
633           && header_info
634           && (header_info->flags & HDR_OPT_RECIP)
635           && (header_info->flags & HDR_OPT_EXTRACT)
636           && (state->resent == 0 || (header_info->flags & HDR_OPT_RR))) {
637           if (header_info->flags & HDR_OPT_RR) {
638               rcpt = state->resent_recip;
639               if (state->resent == 0)
640                     state->resent = 1;
641           } else
642               rcpt = state->recipients;
643           tree = tok822_parse(STR(buf) + strlen(header_info->name) + 1);
644           addr_list = tok822_grep(tree, TOK822_ADDR);
645           for (tpp = addr_list; *tpp; tpp++) {
646               tok822_internalize(state->temp, tpp[0]->head, TOK822_STR_DEFL);
647               argv_add(rcpt, STR(state->temp), (char *) 0);
648           }
649           myfree((void *) addr_list);
650           tok822_free_tree(tree);
651     }
652 
653     /*
654      * Pipe the unmodified message header through the header line folding
655      * routine, and ensure that long lines are chopped appropriately.
656      */
657     for (line = start = STR(buf); line; line = next_line) {
658           next_line = split_at(line, '\n');
659           len = next_line ? next_line - line - 1 : strlen(line);
660           do {
661               if (len > var_line_limit) {
662                     output_text(context, REC_TYPE_CONT, line, var_line_limit, offset);
663                     line += var_line_limit;
664                     len -= var_line_limit;
665                     offset += var_line_limit;
666               } else {
667                     output_text(context, REC_TYPE_NORM, line, len, offset);
668                     offset += len;
669                     break;
670               }
671           } while (len > 0);
672           offset += 1;
673     }
674 }
675 
676 /* enqueue - post one message */
677 
enqueue(const int flags,const char * encoding,const char * dsn_envid,int dsn_ret,int dsn_notify,const char * rewrite_context,const char * sender,const char * full_name,char ** recipients)678 static void enqueue(const int flags, const char *encoding,
679                              const char *dsn_envid, int dsn_ret, int dsn_notify,
680                                 const char *rewrite_context, const char *sender,
681                                 const char *full_name, char **recipients)
682 {
683     VSTRING *buf;
684     VSTREAM *dst;
685     char   *saved_sender;
686     char  **cpp;
687     int     type;
688     char   *start;
689     int     skip_from_;
690     TOK822 *tree;
691     TOK822 *tp;
692     int     rcpt_count = 0;
693     enum {
694           STRIP_CR_DUNNO, STRIP_CR_DO, STRIP_CR_DONT, STRIP_CR_ERROR
695     }       strip_cr;
696     MAIL_STREAM *handle;
697     VSTRING *postdrop_command;
698     uid_t   uid = getuid();
699     int     status;
700     VSTRING *why;                       /* postdrop status message */
701     int     naddr;
702     int     prev_type;
703     MIME_STATE *mime_state = 0;
704     SM_STATE state;
705     int     mime_errs;
706     const char *errstr;
707     int     addr_count;
708     int     level;
709     static NAME_CODE sm_fix_eol_table[] = {
710           SM_FIX_EOL_ALWAYS, STRIP_CR_DO,
711           SM_FIX_EOL_STRICT, STRIP_CR_DUNNO,
712           SM_FIX_EOL_NEVER, STRIP_CR_DONT,
713           0, STRIP_CR_ERROR,
714     };
715 
716     /*
717      * Access control is enforced in the postdrop command. The code here
718      * merely produces a more user-friendly interface.
719      */
720     if ((errstr = check_user_acl_byuid(VAR_SUBMIT_ACL,
721                                                var_submit_acl, uid)) != 0)
722           msg_fatal_status(EX_NOPERM,
723             "User %s(%ld) is not allowed to submit mail", errstr, (long) uid);
724 
725     /*
726      * Initialize.
727      */
728     buf = vstring_alloc(100);
729 
730     /*
731      * Stop run-away process accidents by limiting the queue file size. This
732      * is not a defense against DOS attack.
733      */
734     if (ENFORCING_SIZE_LIMIT(var_message_limit)
735           && get_file_limit() > var_message_limit)
736           set_file_limit((off_t) var_message_limit);
737 
738     /*
739      * The sender name is provided by the user. In principle, the mail pickup
740      * service could deduce the sender name from queue file ownership, but:
741      * pickup would not be able to run chrooted, and it may not be desirable
742      * to use login names at all.
743      */
744     if (sender != 0) {
745           VSTRING_RESET(buf);
746           VSTRING_TERMINATE(buf);
747           tree = tok822_parse(sender);
748           for (naddr = 0, tp = tree; tp != 0; tp = tp->next)
749               if (tp->type == TOK822_ADDR && naddr++ == 0)
750                     tok822_internalize(buf, tp->head, TOK822_STR_DEFL);
751           tok822_free_tree(tree);
752           saved_sender = mystrdup(STR(buf));
753           if (naddr > 1)
754               msg_warn("-f option specified malformed sender: %s", sender);
755     } else {
756           if ((sender = username()) == 0)
757               msg_fatal_status(EX_OSERR, "no login name found for user ID %lu",
758                                    (unsigned long) uid);
759           saved_sender = mystrdup(sender);
760     }
761 
762     /*
763      * Let the postdrop command open the queue file for us, and sanity check
764      * the content. XXX Make postdrop a manifest constant.
765      */
766     errno = 0;
767     postdrop_command = vstring_alloc(1000);
768     vstring_sprintf(postdrop_command, "%s/postdrop -r", var_command_dir);
769     for (level = 0; level < msg_verbose; level++)
770           vstring_strcat(postdrop_command, " -v");
771     if ((handle = mail_stream_command(STR(postdrop_command))) == 0)
772           msg_fatal_status(EX_UNAVAILABLE, "%s(%ld): unable to execute %s: %m",
773                                saved_sender, (long) uid, STR(postdrop_command));
774     vstring_free(postdrop_command);
775     dst = handle->stream;
776 
777     /*
778      * First, write envelope information to the output stream.
779      *
780      * For sendmail compatibility, parse each command-line recipient as if it
781      * were an RFC 822 message header; some MUAs specify comma-separated
782      * recipient lists; and some MUAs even specify "word word <address>".
783      *
784      * Sort-uniq-ing the recipient list is done after address canonicalization,
785      * before recipients are written to queue file. That's cleaner than
786      * having the queue manager nuke duplicate recipient status records.
787      *
788      * XXX Should limit the size of envelope records.
789      *
790      * With "sendmail -N", instead of a per-message NOTIFY record we store one
791      * per recipient so that we can simplify the implementation somewhat.
792      */
793     if (dsn_envid)
794           rec_fprintf(dst, REC_TYPE_ATTR, "%s=%s",
795                         MAIL_ATTR_DSN_ENVID, dsn_envid);
796     if (dsn_ret)
797           rec_fprintf(dst, REC_TYPE_ATTR, "%s=%d",
798                         MAIL_ATTR_DSN_RET, dsn_ret);
799     rec_fprintf(dst, REC_TYPE_ATTR, "%s=%s",
800                     MAIL_ATTR_RWR_CONTEXT, rewrite_context);
801     if (full_name || (full_name = fullname()) != 0)
802           rec_fputs(dst, REC_TYPE_FULL, full_name);
803     rec_fputs(dst, REC_TYPE_FROM, saved_sender);
804     if (verp_delims && *saved_sender == 0)
805           msg_fatal_status(EX_USAGE,
806                           "%s(%ld): -V option requires non-null sender address",
807                                saved_sender, (long) uid);
808     if (encoding)
809           rec_fprintf(dst, REC_TYPE_ATTR, "%s=%s", MAIL_ATTR_ENCODING, encoding);
810     if (DEL_REQ_TRACE_FLAGS(flags))
811           rec_fprintf(dst, REC_TYPE_ATTR, "%s=%d", MAIL_ATTR_TRACE_FLAGS,
812                         DEL_REQ_TRACE_FLAGS(flags));
813     if (verp_delims)
814           rec_fputs(dst, REC_TYPE_VERP, verp_delims);
815     if (recipients) {
816           for (cpp = recipients; *cpp != 0; cpp++) {
817               tree = tok822_parse(*cpp);
818               for (addr_count = 0, tp = tree; tp != 0; tp = tp->next) {
819                     if (tp->type == TOK822_ADDR) {
820                         tok822_internalize(buf, tp->head, TOK822_STR_DEFL);
821                         if (dsn_notify)
822                               rec_fprintf(dst, REC_TYPE_ATTR, "%s=%d",
823                                             MAIL_ATTR_DSN_NOTIFY, dsn_notify);
824                         if (REC_PUT_BUF(dst, REC_TYPE_RCPT, buf) < 0)
825                               msg_fatal_status(EX_TEMPFAIL,
826                                             "%s(%ld): error writing queue file: %m",
827                                                    saved_sender, (long) uid);
828                         ++rcpt_count;
829                         ++addr_count;
830                     }
831               }
832               tok822_free_tree(tree);
833               if (addr_count == 0) {
834                     if (rec_put(dst, REC_TYPE_RCPT, "", 0) < 0)
835                         msg_fatal_status(EX_TEMPFAIL,
836                                              "%s(%ld): error writing queue file: %m",
837                                              saved_sender, (long) uid);
838                     ++rcpt_count;
839               }
840           }
841     }
842 
843     /*
844      * Append the message contents to the queue file. Write chunks of at most
845      * 1kbyte. Internally, we use different record types for data ending in
846      * LF and for data that doesn't, so we can actually be binary transparent
847      * for local mail. Unfortunately, SMTP has no record continuation
848      * convention, so there is no guarantee that arbitrary data will be
849      * delivered intact via SMTP. Strip leading From_ lines. For the benefit
850      * of UUCP environments, also get rid of leading >>>From_ lines.
851      */
852     rec_fputs(dst, REC_TYPE_MESG, "");
853     if (DEL_REQ_TRACE_ONLY(flags) != 0) {
854           if (flags & SM_FLAG_XRCPT)
855               msg_fatal_status(EX_USAGE, "%s(%ld): -t option cannot be used with -bv",
856                                    saved_sender, (long) uid);
857           if (*saved_sender)
858               rec_fprintf(dst, REC_TYPE_NORM, "From: %s", saved_sender);
859           rec_fprintf(dst, REC_TYPE_NORM, "Subject: probe");
860           if (recipients) {
861               rec_fprintf(dst, REC_TYPE_CONT, "To:");
862               for (cpp = recipients; *cpp != 0; cpp++) {
863                     rec_fprintf(dst, REC_TYPE_NORM, "       %s%s",
864                                   *cpp, cpp[1] ? "," : "");
865               }
866           }
867     } else {
868 
869           /*
870            * Initialize the MIME processor and set up the callback context.
871            */
872           if (flags & SM_FLAG_XRCPT) {
873               state.dst = dst;
874               state.recipients = argv_alloc(2);
875               state.resent_recip = argv_alloc(2);
876               state.resent = 0;
877               state.saved_sender = saved_sender;
878               state.uid = uid;
879               state.temp = vstring_alloc(10);
880               mime_state = mime_state_alloc(MIME_OPT_DISABLE_MIME
881                                                     | MIME_OPT_REPORT_TRUNC_HEADER,
882                                                     output_header,
883                                                     (MIME_STATE_ANY_END) 0,
884                                                     output_text,
885                                                     (MIME_STATE_ANY_END) 0,
886                                                     (MIME_STATE_ERR_PRINT) 0,
887                                                     (void *) &state);
888           }
889 
890           /*
891            * Process header/body lines.
892            */
893           skip_from_ = 1;
894           strip_cr = name_code(sm_fix_eol_table, NAME_CODE_FLAG_STRICT_CASE,
895                                    var_sm_fix_eol);
896           if (strip_cr == STRIP_CR_ERROR)
897               msg_fatal_status(EX_USAGE,
898                         "invalid %s value: %s", VAR_SM_FIX_EOL, var_sm_fix_eol);
899           for (prev_type = 0; (type = rec_streamlf_get(VSTREAM_IN, buf, var_line_limit))
900                != REC_TYPE_EOF; prev_type = type) {
901               if (strip_cr == STRIP_CR_DUNNO && type == REC_TYPE_NORM) {
902                     if (VSTRING_LEN(buf) > 0 && vstring_end(buf)[-1] == '\r')
903                         strip_cr = STRIP_CR_DO;
904                     else
905                         strip_cr = STRIP_CR_DONT;
906               }
907               if (skip_from_) {
908                     if (type == REC_TYPE_NORM) {
909                         start = STR(buf);
910                         if (strncmp(start + strspn(start, ">"), "From ", 5) == 0)
911                               continue;
912                     }
913                     skip_from_ = 0;
914               }
915               if (strip_cr == STRIP_CR_DO && type == REC_TYPE_NORM)
916                     while (VSTRING_LEN(buf) > 0 && vstring_end(buf)[-1] == '\r')
917                         vstring_truncate(buf, VSTRING_LEN(buf) - 1);
918               if ((flags & SM_FLAG_AEOF) && prev_type != REC_TYPE_CONT
919                     && VSTRING_LEN(buf) == 1 && *STR(buf) == '.')
920                     break;
921               if (mime_state) {
922                     mime_errs = mime_state_update(mime_state, type, STR(buf),
923                                                         VSTRING_LEN(buf));
924                     if (mime_errs)
925                         msg_fatal_status(EX_DATAERR,
926                                         "%s(%ld): unable to extract recipients: %s",
927                                              saved_sender, (long) uid,
928                                              mime_state_error(mime_errs));
929               } else {
930                     if (REC_PUT_BUF(dst, type, buf) < 0)
931                         msg_fatal_status(EX_TEMPFAIL,
932                                              "%s(%ld): error writing queue file: %m",
933                                              saved_sender, (long) uid);
934               }
935           }
936     }
937 
938     /*
939      * Finish MIME processing. We need a final mime_state_update() call in
940      * order to flush text that is still buffered. That can happen when the
941      * last line did not end in newline.
942      */
943     if (mime_state) {
944           mime_errs = mime_state_update(mime_state, REC_TYPE_EOF, "", 0);
945           if (mime_errs)
946               msg_fatal_status(EX_DATAERR,
947                                    "%s(%ld): unable to extract recipients: %s",
948                                    saved_sender, (long) uid,
949                                    mime_state_error(mime_errs));
950           mime_state = mime_state_free(mime_state);
951     }
952 
953     /*
954      * Append recipient addresses that were extracted from message headers.
955      */
956     rec_fputs(dst, REC_TYPE_XTRA, "");
957     if (flags & SM_FLAG_XRCPT) {
958           for (cpp = state.resent ? state.resent_recip->argv :
959                state.recipients->argv; *cpp; cpp++) {
960               if (dsn_notify)
961                     rec_fprintf(dst, REC_TYPE_ATTR, "%s=%d",
962                                   MAIL_ATTR_DSN_NOTIFY, dsn_notify);
963               if (rec_put(dst, REC_TYPE_RCPT, *cpp, strlen(*cpp)) < 0)
964                     msg_fatal_status(EX_TEMPFAIL,
965                                          "%s(%ld): error writing queue file: %m",
966                                          saved_sender, (long) uid);
967               ++rcpt_count;
968           }
969           argv_free(state.recipients);
970           argv_free(state.resent_recip);
971           vstring_free(state.temp);
972     }
973     if (rcpt_count == 0)
974           msg_fatal_status(EX_USAGE, (flags & SM_FLAG_XRCPT) ?
975                      "%s(%ld): No recipient addresses found in message header" :
976                                "%s(%ld): Recipient addresses must be specified on"
977                                " the command line or via the -t option",
978                                saved_sender, (long) uid);
979 
980     /*
981      * Identify the end of the queue file.
982      */
983     rec_fputs(dst, REC_TYPE_END, "");
984 
985     /*
986      * Make sure that the message makes it to the file system. Once we have
987      * terminated with successful exit status we cannot lose the message due
988      * to "frivolous reasons". If all goes well, prevent the run-time error
989      * handler from removing the file.
990      */
991     if (vstream_ferror(VSTREAM_IN))
992           msg_fatal_status(EX_DATAERR, "%s(%ld): error reading input: %m",
993                                saved_sender, (long) uid);
994     why = vstring_alloc(100);
995     if ((status = mail_stream_finish(handle, why)) != CLEANUP_STAT_OK)
996           msg_fatal_status((status & CLEANUP_STAT_BAD) ? EX_SOFTWARE :
997                                (status & CLEANUP_STAT_WRITE) ? EX_TEMPFAIL :
998                                (status & CLEANUP_STAT_NOPERM) ? EX_NOPERM :
999                                EX_UNAVAILABLE, "%s(%ld): %s", saved_sender,
1000                                (long) uid, VSTRING_LEN(why) ?
1001                                STR(why) : cleanup_strerror(status));
1002     vstring_free(why);
1003 
1004     /*
1005      * Don't leave them in the dark.
1006      */
1007     if (DEL_REQ_TRACE_FLAGS(flags)) {
1008           vstream_printf("Mail Delivery Status Report will be mailed to <%s>.\n",
1009                            saved_sender);
1010           vstream_fflush(VSTREAM_OUT);
1011     }
1012 
1013     /*
1014      * Cleanup. Not really necessary as we're about to exit, but good for
1015      * debugging purposes.
1016      */
1017     vstring_free(buf);
1018     myfree(saved_sender);
1019 }
1020 
1021 /* tempfail - sanitize exit status after library run-time error */
1022 
tempfail(void)1023 static void tempfail(void)
1024 {
1025     exit(EX_TEMPFAIL);
1026 }
1027 
1028 MAIL_VERSION_STAMP_DECLARE;
1029 
1030 /* main - the main program */
1031 
main(int argc,char ** argv)1032 int     main(int argc, char **argv)
1033 {
1034     static char *full_name = 0;                   /* sendmail -F */
1035     struct stat st;
1036     char   *slash;
1037     char   *sender = 0;                           /* sendmail -f */
1038     int     c;
1039     int     fd;
1040     int     mode;
1041     ARGV   *ext_argv;
1042     int     debug_me = 0;
1043     int     err;
1044     int     n;
1045     int     flags = SM_FLAG_DEFAULT;
1046     char   *site_to_flush = 0;
1047     char   *id_to_flush = 0;
1048     char   *encoding = 0;
1049     char   *qtime = 0;
1050     const char *errstr;
1051     uid_t   uid;
1052     const char *rewrite_context = MAIL_ATTR_RWR_LOCAL;
1053     int     dsn_notify = 0;
1054     int     dsn_ret = 0;
1055     const char *dsn_envid = 0;
1056     int     saved_optind;
1057     ARGV   *import_env;
1058     char   *alias_map_from_args = 0;
1059 
1060     /*
1061      * Fingerprint executables and core dumps.
1062      */
1063     MAIL_VERSION_STAMP_ALLOCATE;
1064 
1065     /*
1066      * Be consistent with file permissions.
1067      */
1068     umask(022);
1069 
1070     /*
1071      * To minimize confusion, make sure that the standard file descriptors
1072      * are open before opening anything else. XXX Work around for 44BSD where
1073      * fstat can return EBADF on an open file descriptor.
1074      */
1075     for (fd = 0; fd < 3; fd++)
1076           if (fstat(fd, &st) == -1
1077               && (close(fd), open("/dev/null", O_RDWR, 0)) != fd)
1078               msg_fatal_status(EX_OSERR, "open /dev/null: %m");
1079 
1080     /*
1081      * The CDE desktop calendar manager leaks a parent file descriptor into
1082      * the child process. For the sake of sendmail compatibility we have to
1083      * close the file descriptor otherwise mail notification will hang.
1084      */
1085     for ( /* void */ ; fd < 100; fd++)
1086           (void) close(fd);
1087 
1088     /*
1089      * Process environment options as early as we can. We might be called
1090      * from a set-uid (set-gid) program, so be careful with importing
1091      * environment variables.
1092      */
1093     if (safe_getenv(CONF_ENV_VERB))
1094           msg_verbose = 1;
1095     if (safe_getenv(CONF_ENV_DEBUG))
1096           debug_me = 1;
1097 
1098     /*
1099      * Initialize. Set up logging. Read the global configuration file after
1100      * command-line processing. Set up signal handlers so that we can clean
1101      * up incomplete output.
1102      */
1103     if ((slash = strrchr(argv[0], '/')) != 0 && slash[1])
1104           argv[0] = slash + 1;
1105     msg_vstream_init(argv[0], VSTREAM_ERR);
1106     msg_cleanup(tempfail);
1107     maillog_client_init(mail_task("sendmail"), MAILLOG_CLIENT_FLAG_NONE);
1108     set_mail_conf_str(VAR_PROCNAME, var_procname = mystrdup(argv[0]));
1109 
1110     /*
1111      * Check the Postfix library version as soon as we enable logging.
1112      */
1113     MAIL_VERSION_CHECK;
1114 
1115     /*
1116      * Some sites mistakenly install Postfix sendmail as set-uid root. Drop
1117      * set-uid privileges only when root, otherwise some systems will not
1118      * reset the saved set-userid, which would be a security vulnerability.
1119      */
1120     if (geteuid() == 0 && getuid() != 0) {
1121           msg_warn("the Postfix sendmail command has set-uid root file permissions");
1122           msg_warn("or the command is run from a set-uid root process");
1123           msg_warn("the Postfix sendmail command must be installed without set-uid root file permissions");
1124           set_ugid(getuid(), getgid());
1125     }
1126 
1127     /*
1128      * Further initialization. Load main.cf first, so that command-line
1129      * options can override main.cf settings. Pre-scan the argument list so
1130      * that we load the right main.cf file.
1131      */
1132 #define GETOPT_LIST "A:B:C:F:GIL:N:O:R:UV:X:b:ce:f:h:imno:p:r:q:tvx"
1133 
1134     saved_optind = optind;
1135     while (argv[OPTIND] != 0) {
1136           if (strcmp(argv[OPTIND], "-q") == 0) {  /* not getopt compatible */
1137               optind++;
1138               continue;
1139           }
1140           if ((c = GETOPT(argc, argv, GETOPT_LIST)) <= 0)
1141               break;
1142           if (c == 'C') {
1143               VSTRING *buf = vstring_alloc(1);
1144               char   *dir;
1145 
1146               dir = strcmp(sane_basename(buf, optarg), MAIN_CONF_FILE) == 0 ?
1147                     sane_dirname(buf, optarg) : optarg;
1148               if (strcmp(dir, DEF_CONFIG_DIR) != 0 && geteuid() != 0)
1149                     mail_conf_checkdir(dir);
1150               if (setenv(CONF_ENV_PATH, dir, 1) < 0)
1151                     msg_fatal_status(EX_UNAVAILABLE, "out of memory");
1152               vstring_free(buf);
1153           }
1154     }
1155     optind = saved_optind;
1156     mail_conf_read();
1157     /* Enforce consistent operation of different Postfix parts.        */
1158     import_env = mail_parm_split(VAR_IMPORT_ENVIRON, var_import_environ);
1159     update_env(import_env->argv);
1160     argv_free(import_env);
1161     /* Re-evaluate mail_task() after reading main.cf. */
1162     maillog_client_init(mail_task("sendmail"), MAILLOG_CLIENT_FLAG_NONE);
1163     get_mail_conf_str_table(str_table);
1164 
1165     mail_dict_init();
1166 
1167     if (chdir(var_queue_dir))
1168           msg_fatal_status(EX_UNAVAILABLE, "chdir %s: %m", var_queue_dir);
1169 
1170     signal(SIGPIPE, SIG_IGN);
1171 
1172     /*
1173      * Optionally start the debugger on ourself. This must be done after
1174      * reading the global configuration file, because that file specifies
1175      * what debugger command to execute.
1176      */
1177     if (debug_me)
1178           debug_process();
1179 
1180     /*
1181      * The default mode of operation is determined by the process name. It
1182      * can, however, be changed via command-line options (for example,
1183      * "newaliases -bp" will show the mail queue).
1184      */
1185     if (strcmp(argv[0], "mailq") == 0) {
1186           mode = SM_MODE_MAILQ;
1187     } else if (strcmp(argv[0], "newaliases") == 0) {
1188           mode = SM_MODE_NEWALIAS;
1189     } else if (strcmp(argv[0], "smtpd") == 0) {
1190           mode = SM_MODE_DAEMON;
1191     } else {
1192           mode = SM_MODE_ENQUEUE;
1193     }
1194 
1195     /*
1196      * Parse JCL. Sendmail has been around for a long time, and has acquired
1197      * a large number of options in the course of time. Some options such as
1198      * -q are not parsable with GETOPT() and get special treatment.
1199      */
1200 #define OPTIND  (optind > 0 ? optind : 1)
1201 
1202     while (argv[OPTIND] != 0) {
1203           if (strcmp(argv[OPTIND], "-q") == 0) {
1204               if (mode == SM_MODE_DAEMON)
1205                     msg_warn("ignoring -q option in daemon mode");
1206               else
1207                     mode = SM_MODE_FLUSHQ;
1208               optind++;
1209               continue;
1210           }
1211           if (strcmp(argv[OPTIND], "-V") == 0
1212               && argv[OPTIND + 1] != 0 && strlen(argv[OPTIND + 1]) == 2) {
1213               msg_warn("option -V is deprecated with Postfix 2.3; "
1214                          "specify -XV instead");
1215               argv[OPTIND] = "-XV";
1216           }
1217           if (strncmp(argv[OPTIND], "-V", 2) == 0 && strlen(argv[OPTIND]) == 4) {
1218               msg_warn("option %s is deprecated with Postfix 2.3; "
1219                          "specify -X%s instead",
1220                          argv[OPTIND], argv[OPTIND] + 1);
1221               argv[OPTIND] = concatenate("-X", argv[OPTIND] + 1, (char *) 0);
1222           }
1223           if (strcmp(argv[OPTIND], "-XV") == 0) {
1224               verp_delims = var_verp_delims;
1225               optind++;
1226               continue;
1227           }
1228           if ((c = GETOPT(argc, argv, GETOPT_LIST)) <= 0)
1229               break;
1230           switch (c) {
1231           default:
1232               if (msg_verbose)
1233                     msg_info("-%c option ignored", c);
1234               break;
1235           case 'n':
1236               msg_fatal_status(EX_USAGE, "-%c option not supported", c);
1237           case 'B':
1238               if (strcmp(optarg, "8BITMIME") == 0)/* RFC 1652 */
1239                     encoding = MAIL_ATTR_ENC_8BIT;
1240               else if (strcmp(optarg, "7BIT") == 0)         /* RFC 1652 */
1241                     encoding = MAIL_ATTR_ENC_7BIT;
1242               else
1243                     msg_fatal_status(EX_USAGE, "-B option needs 8BITMIME or 7BIT");
1244               break;
1245           case 'F':                               /* full name */
1246               full_name = optarg;
1247               break;
1248           case 'G':                               /* gateway submission */
1249               rewrite_context = MAIL_ATTR_RWR_REMOTE;
1250               break;
1251           case 'I':                               /* newaliases */
1252               mode = SM_MODE_NEWALIAS;
1253               break;
1254           case 'N':
1255               if ((dsn_notify = dsn_notify_mask(optarg)) == 0)
1256                     msg_warn("bad -N option value -- ignored");
1257               break;
1258           case 'R':
1259               if ((dsn_ret = dsn_ret_code(optarg)) == 0)
1260                     msg_warn("bad -R option value -- ignored");
1261               break;
1262           case 'V':                               /* DSN, was: VERP */
1263               if (strlen(optarg) > 100)
1264                     msg_warn("too long -V option value -- ignored");
1265               else if (!allprint(optarg))
1266                     msg_warn("bad syntax in -V option value -- ignored");
1267               else
1268                     dsn_envid = optarg;
1269               break;
1270           case 'X':
1271               switch (*optarg) {
1272               default:
1273                     msg_fatal_status(EX_USAGE, "unsupported: -%c%c", c, *optarg);
1274               case 'V':                                     /* VERP */
1275                     if (verp_delims_verify(optarg + 1) != 0)
1276                         msg_fatal_status(EX_USAGE, "-V requires two characters from %s",
1277                                              var_verp_filter);
1278                     verp_delims = optarg + 1;
1279                     break;
1280               }
1281               break;
1282           case 'b':
1283               switch (*optarg) {
1284               default:
1285                     msg_fatal_status(EX_USAGE, "unsupported: -%c%c", c, *optarg);
1286               case 'd':                                     /* daemon mode */
1287               case 'l':                                     /* daemon mode */
1288                     if (mode == SM_MODE_FLUSHQ)
1289                         msg_warn("ignoring -q option in daemon mode");
1290                     mode = SM_MODE_DAEMON;
1291                     break;
1292               case 'h':                                     /* print host status */
1293               case 'H':                                     /* flush host status */
1294                     mode = SM_MODE_IGNORE;
1295                     break;
1296               case 'i':                                     /* newaliases */
1297                     mode = SM_MODE_NEWALIAS;
1298                     break;
1299               case 'm':                                     /* deliver mail */
1300                     mode = SM_MODE_ENQUEUE;
1301                     break;
1302               case 'p':                                     /* mailq */
1303                     mode = SM_MODE_MAILQ;
1304                     break;
1305               case 's':                                     /* stand-alone mode */
1306                     mode = SM_MODE_USER;
1307                     break;
1308               case 'v':                                     /* expand recipients */
1309                     flags |= DEL_REQ_FLAG_USR_VRFY;
1310                     break;
1311               }
1312               break;
1313           case 'f':
1314               sender = optarg;
1315               break;
1316           case 'i':
1317               flags &= ~SM_FLAG_AEOF;
1318               break;
1319           case 'o':
1320               switch (*optarg) {
1321               default:
1322                     if (msg_verbose)
1323                         msg_info("-%c%c option ignored", c, *optarg);
1324                     break;
1325               case 'A':
1326                     if (optarg[1] == 0)
1327                         msg_fatal_status(EX_USAGE, "-oA requires pathname");
1328                     alias_map_from_args = optarg + 1;
1329                     break;
1330               case '7':
1331               case '8':
1332                     break;
1333               case 'i':
1334                     flags &= ~SM_FLAG_AEOF;
1335                     break;
1336               case 'm':
1337                     break;
1338               }
1339               break;
1340           case 'r':                               /* obsoleted by -f */
1341               sender = optarg;
1342               break;
1343           case 'q':
1344               if (ISDIGIT(optarg[0])) {
1345                     qtime = optarg;
1346               } else if (optarg[0] == 'R') {
1347                     site_to_flush = optarg + 1;
1348                     if (*site_to_flush == 0)
1349                         msg_fatal_status(EX_USAGE, "specify: -qRsitename");
1350               } else if (optarg[0] == 'I') {
1351                     id_to_flush = optarg + 1;
1352                     if (*id_to_flush == 0)
1353                         msg_fatal_status(EX_USAGE, "specify: -qIqueueid");
1354               } else {
1355                     msg_fatal_status(EX_USAGE, "-q%c is not implemented",
1356                                          optarg[0]);
1357               }
1358               break;
1359           case 't':
1360               flags |= SM_FLAG_XRCPT;
1361               break;
1362           case 'v':
1363               msg_verbose++;
1364               break;
1365           case '?':
1366               msg_fatal_status(EX_USAGE, "usage: %s [options]", argv[0]);
1367           }
1368     }
1369 
1370     /*
1371      * Look for conflicting options and arguments.
1372      */
1373     if ((flags & SM_FLAG_XRCPT) && mode != SM_MODE_ENQUEUE)
1374           msg_fatal_status(EX_USAGE, "-t can be used only in delivery mode");
1375 
1376     if (site_to_flush && mode != SM_MODE_ENQUEUE)
1377           msg_fatal_status(EX_USAGE, "-qR can be used only in delivery mode");
1378 
1379     if (id_to_flush && mode != SM_MODE_ENQUEUE)
1380           msg_fatal_status(EX_USAGE, "-qI can be used only in delivery mode");
1381 
1382     if (flags & DEL_REQ_FLAG_USR_VRFY) {
1383           if (flags & SM_FLAG_XRCPT)
1384               msg_fatal_status(EX_USAGE, "-t option cannot be used with -bv");
1385           if (dsn_notify)
1386               msg_fatal_status(EX_USAGE, "-N option cannot be used with -bv");
1387           if (dsn_ret)
1388               msg_fatal_status(EX_USAGE, "-R option cannot be used with -bv");
1389           if (msg_verbose == 1)
1390               msg_fatal_status(EX_USAGE, "-v option cannot be used with -bv");
1391     }
1392 
1393     /*
1394      * The -v option plays double duty. One requests verbose delivery, more
1395      * than one requests verbose logging.
1396      */
1397     if (msg_verbose == 1 && mode == SM_MODE_ENQUEUE) {
1398           msg_verbose = 0;
1399           flags |= DEL_REQ_FLAG_RECORD;
1400     }
1401 
1402     /*
1403      * Start processing. Everything is delegated to external commands.
1404      */
1405     if (qtime && mode != SM_MODE_DAEMON)
1406           exit(0);
1407     switch (mode) {
1408     default:
1409           msg_panic("unknown operation mode: %d", mode);
1410           /* NOTREACHED */
1411     case SM_MODE_ENQUEUE:
1412           if (site_to_flush) {
1413               if (argv[OPTIND])
1414                     msg_fatal_status(EX_USAGE, "flush site requires no recipient");
1415               ext_argv = argv_alloc(2);
1416               argv_add(ext_argv, "postqueue", "-s", site_to_flush, (char *) 0);
1417               for (n = 0; n < msg_verbose; n++)
1418                     argv_add(ext_argv, "-v", (char *) 0);
1419               argv_terminate(ext_argv);
1420               mail_run_replace(var_command_dir, ext_argv->argv);
1421               /* NOTREACHED */
1422           } else if (id_to_flush) {
1423               if (argv[OPTIND])
1424                     msg_fatal_status(EX_USAGE, "flush queue_id requires no recipient");
1425               ext_argv = argv_alloc(2);
1426               argv_add(ext_argv, "postqueue", "-i", id_to_flush, (char *) 0);
1427               for (n = 0; n < msg_verbose; n++)
1428                     argv_add(ext_argv, "-v", (char *) 0);
1429               argv_terminate(ext_argv);
1430               mail_run_replace(var_command_dir, ext_argv->argv);
1431               /* NOTREACHED */
1432           } else {
1433               enqueue(flags, encoding, dsn_envid, dsn_ret, dsn_notify,
1434                         rewrite_context, sender, full_name, argv + OPTIND);
1435               exit(0);
1436               /* NOTREACHED */
1437           }
1438           break;
1439     case SM_MODE_MAILQ:
1440           if (argv[OPTIND])
1441               msg_fatal_status(EX_USAGE,
1442                                    "display queue mode requires no recipient");
1443           ext_argv = argv_alloc(2);
1444           argv_add(ext_argv, "postqueue", "-p", (char *) 0);
1445           for (n = 0; n < msg_verbose; n++)
1446               argv_add(ext_argv, "-v", (char *) 0);
1447           argv_terminate(ext_argv);
1448           mail_run_replace(var_command_dir, ext_argv->argv);
1449           /* NOTREACHED */
1450     case SM_MODE_FLUSHQ:
1451           if (argv[OPTIND])
1452               msg_fatal_status(EX_USAGE,
1453                                    "flush queue mode requires no recipient");
1454           ext_argv = argv_alloc(2);
1455           argv_add(ext_argv, "postqueue", "-f", (char *) 0);
1456           for (n = 0; n < msg_verbose; n++)
1457               argv_add(ext_argv, "-v", (char *) 0);
1458           argv_terminate(ext_argv);
1459           mail_run_replace(var_command_dir, ext_argv->argv);
1460           /* NOTREACHED */
1461     case SM_MODE_DAEMON:
1462           if (argv[OPTIND])
1463               msg_fatal_status(EX_USAGE, "daemon mode requires no recipient");
1464           ext_argv = argv_alloc(2);
1465           argv_add(ext_argv, "postfix", (char *) 0);
1466           for (n = 0; n < msg_verbose; n++)
1467               argv_add(ext_argv, "-v", (char *) 0);
1468           argv_add(ext_argv, "start", (char *) 0);
1469           argv_terminate(ext_argv);
1470           err = (mail_run_background(var_command_dir, ext_argv->argv) < 0);
1471           argv_free(ext_argv);
1472           exit(err);
1473           break;
1474     case SM_MODE_NEWALIAS:
1475           if (argv[OPTIND])
1476               msg_fatal_status(EX_USAGE,
1477                                "alias initialization mode requires no recipient");
1478           if (alias_map_from_args == 0 && *var_alias_db_map == 0)
1479               return (0);
1480           ext_argv = argv_alloc(3);
1481           argv_add(ext_argv, "postalias", (char *) 0);
1482           for (n = 0; n < msg_verbose; n++)
1483               argv_add(ext_argv, "-v", (char *) 0);
1484           argv_add(ext_argv, "--", (char *) 0);
1485           if (alias_map_from_args != 0)
1486               argv_add(ext_argv, alias_map_from_args, (char *) 0);
1487           else
1488               argv_split_append(ext_argv, var_alias_db_map, CHARS_COMMA_SP);
1489           argv_terminate(ext_argv);
1490           mail_run_replace(var_command_dir, ext_argv->argv);
1491           /* NOTREACHED */
1492     case SM_MODE_USER:
1493           if (argv[OPTIND])
1494               msg_fatal_status(EX_USAGE,
1495                                    "stand-alone mode requires no recipient");
1496           /* The actual enforcement happens in the postdrop command. */
1497           if ((errstr = check_user_acl_byuid(VAR_SUBMIT_ACL, var_submit_acl,
1498                                                      uid = getuid())) != 0)
1499               msg_fatal_status(EX_NOPERM,
1500                                    "User %s(%ld) is not allowed to submit mail",
1501                                    errstr, (long) uid);
1502           ext_argv = argv_alloc(2);
1503           argv_add(ext_argv, "smtpd", "-S", (char *) 0);
1504           for (n = 0; n < msg_verbose; n++)
1505               argv_add(ext_argv, "-v", (char *) 0);
1506           argv_terminate(ext_argv);
1507           mail_run_replace(var_daemon_dir, ext_argv->argv);
1508           /* NOTREACHED */
1509     case SM_MODE_IGNORE:
1510           exit(0);
1511           /* NOTREACHED */
1512     }
1513 }
1514