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