xref: /netbsd-src/external/ibm-public/postfix/dist/src/postqueue/postqueue.c (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
1 /*	$NetBSD: postqueue.c,v 1.3 2020/03/18 19:05:19 christos Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	postqueue 1
6 /* SUMMARY
7 /*	Postfix queue control
8 /* SYNOPSIS
9 /* .ti -4
10 /*	\fBTo flush the mail queue\fR:
11 /*
12 /*	\fBpostqueue\fR [\fB-v\fR] [\fB-c \fIconfig_dir\fR] \fB-f\fR
13 /*
14 /*	\fBpostqueue\fR [\fB-v\fR] [\fB-c \fIconfig_dir\fR] \fB-i \fIqueue_id\fR
15 /*
16 /*	\fBpostqueue\fR [\fB-v\fR] [\fB-c \fIconfig_dir\fR] \fB-s \fIsite\fR
17 /*
18 /* .ti -4
19 /*	\fBTo list the mail queue\fR:
20 /*
21 /*	\fBpostqueue\fR [\fB-v\fR] [\fB-c \fIconfig_dir\fR] \fB-j\fR
22 /*
23 /*	\fBpostqueue\fR [\fB-v\fR] [\fB-c \fIconfig_dir\fR] \fB-p\fR
24 /* DESCRIPTION
25 /*	The \fBpostqueue\fR(1) command implements the Postfix user interface
26 /*	for queue management. It implements operations that are
27 /*	traditionally available via the \fBsendmail\fR(1) command.
28 /*	See the \fBpostsuper\fR(1) command for queue operations
29 /*	that require super-user privileges such as deleting a message
30 /*	from the queue or changing the status of a message.
31 /*
32 /*	The following options are recognized:
33 /* .IP "\fB-c \fIconfig_dir\fR"
34 /*	The \fBmain.cf\fR configuration file is in the named directory
35 /*	instead of the default configuration directory. See also the
36 /*	MAIL_CONFIG environment setting below.
37 /* .IP \fB-f\fR
38 /*	Flush the queue: attempt to deliver all queued mail.
39 /*
40 /*	This option implements the traditional "\fBsendmail -q\fR" command,
41 /*	by contacting the Postfix \fBqmgr\fR(8) daemon.
42 /*
43 /*	Warning: flushing undeliverable mail frequently will result in
44 /*	poor delivery performance of all other mail.
45 /* .IP "\fB-i \fIqueue_id\fR"
46 /*	Schedule immediate delivery of deferred mail with the
47 /*	specified queue ID.
48 /*
49 /*	This option implements the traditional \fBsendmail -qI\fR
50 /*	command, by contacting the \fBflush\fR(8) server.
51 /*
52 /*	This feature is available with Postfix version 2.4 and later.
53 /* .IP "\fB-j\fR"
54 /*	Produce a queue listing in JSON format, based on output
55 /*	from the showq(8) daemon.  The result is a stream of zero
56 /*	or more JSON objects, one per queue file.  Each object is
57 /*	followed by a newline character to support simple streaming
58 /*	parsers. See "\fBJSON OBJECT FORMAT\fR" below for details.
59 /*
60 /*	This feature is available in Postfix 3.1 and later.
61 /* .IP \fB-p\fR
62 /*	Produce a traditional sendmail-style queue listing.
63 /*	This option implements the traditional \fBmailq\fR command,
64 /*	by contacting the Postfix \fBshowq\fR(8) daemon.
65 /*
66 /*	Each queue entry shows the queue file ID, message
67 /*	size, arrival time, sender, and the recipients that still need to
68 /*	be delivered.  If mail could not be delivered upon the last attempt,
69 /*	the reason for failure is shown. The queue ID string
70 /*	is followed by an optional status character:
71 /* .RS
72 /* .IP \fB*\fR
73 /*	The message is in the \fBactive\fR queue, i.e. the message is
74 /*	selected for delivery.
75 /* .IP \fB!\fR
76 /*	The message is in the \fBhold\fR queue, i.e. no further delivery
77 /*	attempt will be made until the mail is taken off hold.
78 /* .IP \fB#\fR
79 /*	The message is forced to expire. See the \fBpostsuper\fR(1)
80 /*	options \fB-e\fR or \fB-f\fR.
81 /* .sp
82 /*	This feature is available in Postfix 3.5 and later.
83 /* .RE
84 /* .IP "\fB-s \fIsite\fR"
85 /*	Schedule immediate delivery of all mail that is queued for the named
86 /*	\fIsite\fR. A numerical site must be specified as a valid RFC 5321
87 /*	address literal enclosed in [], just like in email addresses.
88 /*	The site must be eligible for the "fast flush" service.
89 /*	See \fBflush\fR(8) for more information about the "fast flush"
90 /*	service.
91 /*
92 /*	This option implements the traditional "\fBsendmail -qR\fIsite\fR"
93 /*	command, by contacting the Postfix \fBflush\fR(8) daemon.
94 /* .IP \fB-v\fR
95 /*	Enable verbose logging for debugging purposes. Multiple \fB-v\fR
96 /*	options make the software increasingly verbose. As of Postfix 2.3,
97 /*	this option is available for the super-user only.
98 /* JSON OBJECT FORMAT
99 /* .ad
100 /* .fi
101 /*	Each JSON object represents one queue file; it is emitted
102 /*	as a single text line followed by a newline character.
103 /*
104 /*	Object members have string values unless indicated otherwise.
105 /*	Programs should ignore object members that are not listed
106 /*	here; the list of members is expected to grow over time.
107 /* .IP \fBqueue_name\fR
108 /*	The name of the queue where the message was found.  Note
109 /*	that the contents of the mail queue may change while it is
110 /*	being listed; some messages may appear more than once, and
111 /*	some messages may be missed.
112 /* .IP \fBqueue_id\fR
113 /*	The queue file name. The queue_id may be reused within a
114 /*	Postfix instance unless "enable_long_queue_ids = true" and
115 /*	time is monotonic.  Even then, the queue_id is not expected
116 /*	to be unique between different Postfix instances.  Management
117 /*	tools that require a unique name should combine the queue_id
118 /*	with the myhostname setting of the Postfix instance.
119 /* .IP \fBarrival_time\fR
120 /*	The number of seconds since the start of the UNIX epoch.
121 /* .IP \fBmessage_size\fR
122 /*	The number of bytes in the message header and body. This
123 /*	number does not include message envelope information. It
124 /*	is approximately equal to the number of bytes that would
125 /*	be transmitted via SMTP including the <CR><LF> line endings.
126 /* .IP \fBforced_expire\fR
127 /*	The message is forced to expire (\fBtrue\fR or \fBfalse\fR).
128 /*	See the \fBpostsuper\fR(1) options \fB-e\fR or \fB-f\fR.
129 /* .sp
130 /*	This feature is available in Postfix 3.5 and later.
131 /* .IP \fBsender\fR
132 /*	The envelope sender address.
133 /* .IP \fBrecipients\fR
134 /*	An array containing zero or more objects with members:
135 /* .RS
136 /* .IP \fBaddress\fR
137 /*	One recipient address.
138 /* .IP \fBdelay_reason\fR
139 /*	If present, the reason for delayed delivery.  Delayed
140 /*	recipients may have no delay reason, for example, while
141 /*	delivery is in progress, or after the system was stopped
142 /*	before it could record the reason.
143 /* .RE
144 /* SECURITY
145 /* .ad
146 /* .fi
147 /*	This program is designed to run with set-group ID privileges, so
148 /*	that it can connect to Postfix daemon processes.
149 /* STANDARDS
150 /*	RFC 7159 (JSON notation)
151 /* DIAGNOSTICS
152 /*	Problems are logged to \fBsyslogd\fR(8) or \fBpostlogd\fR(8),
153 /*	and to the standard error stream.
154 /* ENVIRONMENT
155 /* .ad
156 /* .fi
157 /* .IP MAIL_CONFIG
158 /*	Directory with the \fBmain.cf\fR file. In order to avoid exploitation
159 /*	of set-group ID privileges, a non-standard directory is allowed only
160 /*	if:
161 /* .RS
162 /* .IP \(bu
163 /*	The name is listed in the standard \fBmain.cf\fR file with the
164 /*	\fBalternate_config_directories\fR configuration parameter.
165 /* .IP \(bu
166 /*	The command is invoked by the super-user.
167 /* .RE
168 /* CONFIGURATION PARAMETERS
169 /* .ad
170 /* .fi
171 /*	The following \fBmain.cf\fR parameters are especially relevant to
172 /*	this program.
173 /*	The text below provides only a parameter summary. See
174 /*	\fBpostconf\fR(5) for more details including examples.
175 /* .IP "\fBalternate_config_directories (empty)\fR"
176 /*	A list of non-default Postfix configuration directories that may
177 /*	be specified with "-c config_directory" on the command line (in the
178 /*	case of \fBsendmail\fR(1), with the "-C" option), or via the MAIL_CONFIG
179 /*	environment parameter.
180 /* .IP "\fBconfig_directory (see 'postconf -d' output)\fR"
181 /*	The default location of the Postfix main.cf and master.cf
182 /*	configuration files.
183 /* .IP "\fBcommand_directory (see 'postconf -d' output)\fR"
184 /*	The location of all postfix administrative commands.
185 /* .IP "\fBfast_flush_domains ($relay_domains)\fR"
186 /*	Optional list of destinations that are eligible for per-destination
187 /*	logfiles with mail that is queued to those destinations.
188 /* .IP "\fBimport_environment (see 'postconf -d' output)\fR"
189 /*	The list of environment parameters that a privileged Postfix
190 /*	process will import from a non-Postfix parent process, or name=value
191 /*	environment overrides.
192 /* .IP "\fBqueue_directory (see 'postconf -d' output)\fR"
193 /*	The location of the Postfix top-level queue directory.
194 /* .IP "\fBsyslog_facility (mail)\fR"
195 /*	The syslog facility of Postfix logging.
196 /* .IP "\fBsyslog_name (see 'postconf -d' output)\fR"
197 /*	A prefix that is prepended to the process name in syslog
198 /*	records, so that, for example, "smtpd" becomes "prefix/smtpd".
199 /* .IP "\fBtrigger_timeout (10s)\fR"
200 /*	The time limit for sending a trigger to a Postfix daemon (for
201 /*	example, the \fBpickup\fR(8) or \fBqmgr\fR(8) daemon).
202 /* .PP
203 /*	Available in Postfix version 2.2 and later:
204 /* .IP "\fBauthorized_flush_users (static:anyone)\fR"
205 /*	List of users who are authorized to flush the queue.
206 /* .IP "\fBauthorized_mailq_users (static:anyone)\fR"
207 /*	List of users who are authorized to view the queue.
208 /* FILES
209 /*	/var/spool/postfix, mail queue
210 /* SEE ALSO
211 /*	qmgr(8), queue manager
212 /*	showq(8), list mail queue
213 /*	flush(8), fast flush service
214 /*	sendmail(1), Sendmail-compatible user interface
215 /*	postsuper(1), privileged queue operations
216 /*	postlogd(8), Postfix logging
217 /*	syslogd(8), system logging
218 /* README FILES
219 /* .ad
220 /* .fi
221 /*	Use "\fBpostconf readme_directory\fR" or
222 /*	"\fBpostconf html_directory\fR" to locate this information.
223 /* .na
224 /* .nf
225 /*	ETRN_README, Postfix ETRN howto
226 /* LICENSE
227 /* .ad
228 /* .fi
229 /*	The Secure Mailer license must be distributed with this software.
230 /* HISTORY
231 /* .ad
232 /* .fi
233 /*	The postqueue command was introduced with Postfix version 1.1.
234 /* AUTHOR(S)
235 /*	Wietse Venema
236 /*	IBM T.J. Watson Research
237 /*	P.O. Box 704
238 /*	Yorktown Heights, NY 10598, USA
239 /*
240 /*	Wietse Venema
241 /*	Google, Inc.
242 /*	111 8th Avenue
243 /*	New York, NY 10011, USA
244 /*--*/
245 
246 /* System library. */
247 
248 #include <sys_defs.h>
249 #include <sys/stat.h>
250 #include <unistd.h>
251 #include <string.h>
252 #include <stdlib.h>
253 #include <signal.h>
254 #include <sysexits.h>
255 #include <errno.h>
256 
257 /* Utility library. */
258 
259 #include <msg.h>
260 #include <mymalloc.h>
261 #include <clean_env.h>
262 #include <vstream.h>
263 #include <msg_vstream.h>
264 #include <argv.h>
265 #include <safe.h>
266 #include <connect.h>
267 #include <valid_hostname.h>
268 #include <warn_stat.h>
269 #include <events.h>
270 #include <stringops.h>
271 
272 /* Global library. */
273 
274 #include <mail_proto.h>
275 #include <mail_params.h>
276 #include <mail_version.h>
277 #include <mail_conf.h>
278 #include <mail_task.h>
279 #include <mail_run.h>
280 #include <mail_flush.h>
281 #include <mail_queue.h>
282 #include <flush_clnt.h>
283 #include <smtp_stream.h>
284 #include <user_acl.h>
285 #include <valid_mailhost_addr.h>
286 #include <mail_dict.h>
287 #include <mail_parm_split.h>
288 #include <maillog_client.h>
289 
290 /* Application-specific. */
291 
292 #include <postqueue.h>
293 
294  /*
295   * WARNING WARNING WARNING
296   *
297   * This software is designed to run set-gid. In order to avoid exploitation of
298   * privilege, this software should not run any external commands, nor should
299   * it take any information from the user, unless that information can be
300   * properly sanitized. To get an idea of how much information a process can
301   * inherit from a potentially hostile user, examine all the members of the
302   * process structure (typically, in /usr/include/sys/proc.h): the current
303   * directory, open files, timers, signals, environment, command line, umask,
304   * and so on.
305   */
306 
307  /*
308   * Modes of operation.
309   *
310   * XXX To support flush by recipient domain, or for destinations that have no
311   * mapping to logfile, the server has to defend against resource exhaustion
312   * attacks. A malicious user could fork off a postqueue client that starts
313   * an expensive requests and then kills the client immediately; this way she
314   * could create a high Postfix load on the system without ever exceeding her
315   * own per-user process limit. To prevent this, either the server needs to
316   * establish frequent proof of client liveliness with challenge/response, or
317   * the client needs to restrict expensive requests to privileged users only.
318   *
319   * We don't have this problem with queue listings. The showq server detects an
320   * EPIPE error after reporting a few queue entries.
321   */
322 #define PQ_MODE_DEFAULT		0	/* noop */
323 #define PQ_MODE_MAILQ_LIST	1	/* list mail queue */
324 #define PQ_MODE_FLUSH_QUEUE	2	/* flush queue */
325 #define PQ_MODE_FLUSH_SITE	3	/* flush site */
326 #define PQ_MODE_FLUSH_FILE	4	/* flush message */
327 #define PQ_MODE_JSON_LIST	5	/* JSON-format queue listing */
328 
329  /*
330   * Silly little macros (SLMs).
331   */
332 #define STR	vstring_str
333 
334  /*
335   * Queue manipulation access lists.
336   */
337 char   *var_flush_acl;
338 char   *var_showq_acl;
339 
340 static const CONFIG_STR_TABLE str_table[] = {
341     VAR_FLUSH_ACL, DEF_FLUSH_ACL, &var_flush_acl, 0, 0,
342     VAR_SHOWQ_ACL, DEF_SHOWQ_ACL, &var_showq_acl, 0, 0,
343     0,
344 };
345 
346 /* show_queue - show queue status */
347 
348 static void show_queue(int mode)
349 {
350     const char *errstr;
351     VSTREAM *showq;
352     int     n;
353     uid_t   uid = getuid();
354 
355     if (uid != 0 && uid != var_owner_uid
356 	&& (errstr = check_user_acl_byuid(VAR_SHOWQ_ACL, var_showq_acl,
357 					  uid)) != 0)
358 	msg_fatal_status(EX_NOPERM,
359 		       "User %s(%ld) is not allowed to view the mail queue",
360 			 errstr, (long) uid);
361 
362     /*
363      * Connect to the show queue service.
364      */
365     if ((showq = mail_connect(MAIL_CLASS_PUBLIC, var_showq_service, BLOCKING)) != 0) {
366 	switch (mode) {
367 	case PQ_MODE_MAILQ_LIST:
368 	    showq_compat(showq);
369 	    break;
370 	case PQ_MODE_JSON_LIST:
371 	    showq_json(showq);
372 	    break;
373 	default:
374 	    msg_panic("show_queue: unknown mode %d", mode);
375 	}
376 	if (vstream_fclose(showq))
377 	    msg_warn("close: %m");
378     }
379 
380     /*
381      * Don't assume that the mail system is down when the user has
382      * insufficient permission to access the showq socket.
383      */
384     else if (errno == EACCES) {
385 	msg_fatal_status(EX_SOFTWARE,
386 			 "Connect to the %s %s service: %m",
387 			 var_mail_name, var_showq_service);
388     }
389 
390     /*
391      * When the mail system is down, the superuser can still access the queue
392      * directly. Just run the showq program in stand-alone mode.
393      */
394     else if (geteuid() == 0) {
395 	char   *showq_path;
396 	ARGV   *argv;
397 	int     stat;
398 
399 	msg_warn("Mail system is down -- accessing queue directly");
400 	showq_path = concatenate(var_daemon_dir, "/", var_showq_service,
401 				 (char *) 0);
402 	argv = argv_alloc(6);
403 	argv_add(argv, showq_path, "-u", "-S", (char *) 0);
404 	for (n = 0; n < msg_verbose; n++)
405 	    argv_add(argv, "-v", (char *) 0);
406 	argv_terminate(argv);
407 	if ((showq = vstream_popen(O_RDONLY,
408 				   CA_VSTREAM_POPEN_ARGV(argv->argv),
409 				   CA_VSTREAM_POPEN_END)) == 0) {
410 	    stat = -1;
411 	} else {
412 	    switch (mode) {
413 	    case PQ_MODE_MAILQ_LIST:
414 		showq_compat(showq);
415 		break;
416 	    case PQ_MODE_JSON_LIST:
417 		showq_json(showq);
418 		break;
419 	    default:
420 		msg_panic("show_queue: unknown mode %d", mode);
421 	    }
422 	    stat = vstream_pclose(showq);
423 	}
424 	argv_free(argv);
425 	if (stat != 0)
426 	    msg_fatal_status(stat < 0 ? EX_OSERR : EX_SOFTWARE,
427 			     "Error running %s", showq_path);
428 	myfree(showq_path);
429     }
430 
431     /*
432      * When the mail system is down, unprivileged users are stuck, because by
433      * design the mail system contains no set_uid programs. The only way for
434      * an unprivileged user to cross protection boundaries is to talk to the
435      * showq daemon.
436      */
437     else {
438 	msg_fatal_status(EX_UNAVAILABLE,
439 			 "Queue report unavailable - mail system is down");
440     }
441 }
442 
443 /* flush_queue - force delivery */
444 
445 static void flush_queue(void)
446 {
447     const char *errstr;
448     uid_t   uid = getuid();
449 
450     if (uid != 0 && uid != var_owner_uid
451 	&& (errstr = check_user_acl_byuid(VAR_FLUSH_ACL, var_flush_acl,
452 					  uid)) != 0)
453 	msg_fatal_status(EX_NOPERM,
454 		      "User %s(%ld) is not allowed to flush the mail queue",
455 			 errstr, (long) uid);
456 
457     /*
458      * Trigger the flush queue service.
459      */
460     if (mail_flush_deferred() < 0)
461 	msg_fatal_status(EX_UNAVAILABLE,
462 			 "Cannot flush mail queue - mail system is down");
463     if (mail_flush_maildrop() < 0)
464 	msg_fatal_status(EX_UNAVAILABLE,
465 			 "Cannot flush mail queue - mail system is down");
466     event_drain(2);
467 }
468 
469 /* flush_site - flush mail for site */
470 
471 static void flush_site(const char *site)
472 {
473     int     status;
474     const char *errstr;
475     uid_t   uid = getuid();
476 
477     if (uid != 0 && uid != var_owner_uid
478 	&& (errstr = check_user_acl_byuid(VAR_FLUSH_ACL, var_flush_acl,
479 					  uid)) != 0)
480 	msg_fatal_status(EX_NOPERM,
481 		      "User %s(%ld) is not allowed to flush the mail queue",
482 			 errstr, (long) uid);
483 
484     flush_init();
485 
486     switch (status = flush_send_site(site)) {
487     case FLUSH_STAT_OK:
488 	exit(0);
489     case FLUSH_STAT_BAD:
490 	msg_fatal_status(EX_USAGE, "Invalid request: \"%s\"", site);
491     case FLUSH_STAT_FAIL:
492 	msg_fatal_status(EX_UNAVAILABLE,
493 			 "Cannot flush mail queue - mail system is down");
494     case FLUSH_STAT_DENY:
495 	msg_fatal_status(EX_UNAVAILABLE,
496 		   "Flush service is not configured for destination \"%s\"",
497 			 site);
498     default:
499 	msg_fatal_status(EX_SOFTWARE,
500 			 "Unknown flush server reply status %d", status);
501     }
502 }
503 
504 /* flush_file - flush mail with specific queue ID */
505 
506 static void flush_file(const char *queue_id)
507 {
508     int     status;
509     const char *errstr;
510     uid_t   uid = getuid();
511 
512     if (uid != 0 && uid != var_owner_uid
513 	&& (errstr = check_user_acl_byuid(VAR_FLUSH_ACL, var_flush_acl,
514 					  uid)) != 0)
515 	msg_fatal_status(EX_NOPERM,
516 		      "User %s(%ld) is not allowed to flush the mail queue",
517 			 errstr, (long) uid);
518 
519     switch (status = flush_send_file(queue_id)) {
520     case FLUSH_STAT_OK:
521 	exit(0);
522     case FLUSH_STAT_BAD:
523 	msg_fatal_status(EX_USAGE, "Invalid request: \"%s\"", queue_id);
524     case FLUSH_STAT_FAIL:
525 	msg_fatal_status(EX_UNAVAILABLE,
526 			 "Cannot flush mail queue - mail system is down");
527     default:
528 	msg_fatal_status(EX_SOFTWARE,
529 			 "Unexpected flush server reply status %d", status);
530     }
531 }
532 
533 /* unavailable - sanitize exit status from library run-time errors */
534 
535 static void unavailable(void)
536 {
537     exit(EX_UNAVAILABLE);
538 }
539 
540 /* usage - scream and die */
541 
542 static NORETURN usage(void)
543 {
544     msg_fatal_status(EX_USAGE, "usage: postqueue -f | postqueue -i queueid | postqueue -j | postqueue -p | postqueue -s site");
545 }
546 
547 MAIL_VERSION_STAMP_DECLARE;
548 
549 /* main - the main program */
550 
551 int     main(int argc, char **argv)
552 {
553     struct stat st;
554     int     c;
555     int     fd;
556     int     mode = PQ_MODE_DEFAULT;
557     char   *site_to_flush = 0;
558     char   *id_to_flush = 0;
559     ARGV   *import_env;
560     int     bad_site;
561 
562     /*
563      * Fingerprint executables and core dumps.
564      */
565     MAIL_VERSION_STAMP_ALLOCATE;
566 
567     /*
568      * Be consistent with file permissions.
569      */
570     umask(022);
571 
572     /*
573      * To minimize confusion, make sure that the standard file descriptors
574      * are open before opening anything else. XXX Work around for 44BSD where
575      * fstat can return EBADF on an open file descriptor.
576      */
577     for (fd = 0; fd < 3; fd++)
578 	if (fstat(fd, &st) == -1
579 	    && (close(fd), open("/dev/null", O_RDWR, 0)) != fd)
580 	    msg_fatal_status(EX_UNAVAILABLE, "open /dev/null: %m");
581 
582     /*
583      * Initialize. Set up logging. Read the global configuration file after
584      * parsing command-line arguments. Censor the process name: it is
585      * provided by the user.
586      */
587     argv[0] = "postqueue";
588     msg_vstream_init(argv[0], VSTREAM_ERR);
589     msg_cleanup(unavailable);
590     maillog_client_init(mail_task("postqueue"), MAILLOG_CLIENT_FLAG_NONE);
591     set_mail_conf_str(VAR_PROCNAME, var_procname = mystrdup(argv[0]));
592 
593     /*
594      * Check the Postfix library version as soon as we enable logging.
595      */
596     MAIL_VERSION_CHECK;
597 
598     /*
599      * Parse JCL. This program is set-gid and must sanitize all command-line
600      * parameters. The configuration directory argument is validated by the
601      * mail configuration read routine. Don't do complex things until we have
602      * completed initializations.
603      */
604     while ((c = GETOPT(argc, argv, "c:fi:jps:v")) > 0) {
605 	switch (c) {
606 	case 'c':				/* non-default configuration */
607 	    if (setenv(CONF_ENV_PATH, optarg, 1) < 0)
608 		msg_fatal_status(EX_UNAVAILABLE, "out of memory");
609 	    break;
610 	case 'f':				/* flush queue */
611 	    if (mode != PQ_MODE_DEFAULT)
612 		usage();
613 	    mode = PQ_MODE_FLUSH_QUEUE;
614 	    break;
615 	case 'i':				/* flush queue file */
616 	    if (mode != PQ_MODE_DEFAULT)
617 		usage();
618 	    mode = PQ_MODE_FLUSH_FILE;
619 	    id_to_flush = optarg;
620 	    break;
621 	case 'j':
622 	    if (mode != PQ_MODE_DEFAULT)
623 		usage();
624 	    mode = PQ_MODE_JSON_LIST;
625 	    break;
626 	case 'p':				/* traditional mailq */
627 	    if (mode != PQ_MODE_DEFAULT)
628 		usage();
629 	    mode = PQ_MODE_MAILQ_LIST;
630 	    break;
631 	case 's':				/* flush site */
632 	    if (mode != PQ_MODE_DEFAULT)
633 		usage();
634 	    mode = PQ_MODE_FLUSH_SITE;
635 	    site_to_flush = optarg;
636 	    break;
637 	case 'v':
638 	    if (geteuid() == 0)
639 		msg_verbose++;
640 	    break;
641 	default:
642 	    usage();
643 	}
644     }
645     if (argc > optind)
646 	usage();
647 
648     /*
649      * Further initialization...
650      */
651     mail_conf_read();
652     /* Re-evaluate mail_task() after reading main.cf. */
653     maillog_client_init(mail_task("postqueue"), MAILLOG_CLIENT_FLAG_NONE);
654     mail_dict_init();				/* proxy, sql, ldap */
655     get_mail_conf_str_table(str_table);
656 
657     /*
658      * This program is designed to be set-gid, which makes it a potential
659      * target for attack. Strip and optionally override the process
660      * environment so that we don't have to trust the C library.
661      */
662     import_env = mail_parm_split(VAR_IMPORT_ENVIRON, var_import_environ);
663     clean_env(import_env->argv);
664     argv_free(import_env);
665 
666     if (chdir(var_queue_dir))
667 	msg_fatal_status(EX_UNAVAILABLE, "chdir %s: %m", var_queue_dir);
668 
669     signal(SIGPIPE, SIG_IGN);
670 
671     /* End of initializations. */
672 
673     /*
674      * Further input validation.
675      */
676     if (site_to_flush != 0) {
677 	bad_site = 0;
678 	if (*site_to_flush == '[') {
679 	    bad_site = !valid_mailhost_literal(site_to_flush, DONT_GRIPE);
680 	} else {
681 	    bad_site = !valid_hostname(site_to_flush, DONT_GRIPE);
682 	}
683 	if (bad_site)
684 	    msg_fatal_status(EX_USAGE,
685 	      "Cannot flush mail queue - invalid destination: \"%.100s%s\"",
686 		   site_to_flush, strlen(site_to_flush) > 100 ? "..." : "");
687     }
688     if (id_to_flush != 0) {
689 	if (!mail_queue_id_ok(id_to_flush))
690 	    msg_fatal_status(EX_USAGE,
691 		       "Cannot flush queue ID - invalid name: \"%.100s%s\"",
692 		       id_to_flush, strlen(id_to_flush) > 100 ? "..." : "");
693     }
694 
695     /*
696      * Start processing.
697      */
698     switch (mode) {
699     default:
700 	msg_panic("unknown operation mode: %d", mode);
701 	/* NOTREACHED */
702     case PQ_MODE_MAILQ_LIST:
703     case PQ_MODE_JSON_LIST:
704 	show_queue(mode);
705 	exit(0);
706 	break;
707     case PQ_MODE_FLUSH_SITE:
708 	flush_site(site_to_flush);
709 	exit(0);
710 	break;
711     case PQ_MODE_FLUSH_FILE:
712 	flush_file(id_to_flush);
713 	exit(0);
714 	break;
715     case PQ_MODE_FLUSH_QUEUE:
716 	flush_queue();
717 	exit(0);
718 	break;
719     case PQ_MODE_DEFAULT:
720 	usage();
721 	/* NOTREACHED */
722     }
723 }
724