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