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