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