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