xref: /netbsd-src/external/ibm-public/postfix/dist/src/postqueue/postqueue.c (revision d16b7486a53dcb8072b60ec6fcb4373a2d0c27b7)
1 /*	$NetBSD: postqueue.c,v 1.4 2022/10/08 16:12:48 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 variables 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 /* showq_client - run the appropriate showq protocol client */
347 
348 static void showq_client(int mode, VSTREAM *showq)
349 {
350     if (attr_scan(showq, ATTR_FLAG_STRICT,
351 		  RECV_ATTR_STREQ(MAIL_ATTR_PROTO, MAIL_ATTR_PROTO_SHOWQ),
352 		  ATTR_TYPE_END) != 0)
353 	msg_fatal_status(EX_SOFTWARE, "malformed showq server response");
354     switch (mode) {
355     case PQ_MODE_MAILQ_LIST:
356 	showq_compat(showq);
357 	break;
358     case PQ_MODE_JSON_LIST:
359 	showq_json(showq);
360 	break;
361     default:
362 	msg_panic("show_queue: unknown mode %d", mode);
363     }
364 }
365 
366 /* show_queue - show queue status */
367 
368 static void show_queue(int mode)
369 {
370     const char *errstr;
371     VSTREAM *showq;
372     int     n;
373     uid_t   uid = getuid();
374 
375     if (uid != 0 && uid != var_owner_uid
376 	&& (errstr = check_user_acl_byuid(VAR_SHOWQ_ACL, var_showq_acl,
377 					  uid)) != 0)
378 	msg_fatal_status(EX_NOPERM,
379 		       "User %s(%ld) is not allowed to view the mail queue",
380 			 errstr, (long) uid);
381 
382     /*
383      * Connect to the show queue service.
384      */
385     if ((showq = mail_connect(MAIL_CLASS_PUBLIC, var_showq_service, BLOCKING)) != 0) {
386 	showq_client(mode, showq);
387 	if (vstream_fclose(showq))
388 	    msg_warn("close: %m");
389     }
390 
391     /*
392      * Don't assume that the mail system is down when the user has
393      * insufficient permission to access the showq socket.
394      */
395     else if (errno == EACCES || errno == EPERM) {
396 	msg_fatal_status(EX_SOFTWARE,
397 			 "Connect to the %s %s service: %m",
398 			 var_mail_name, var_showq_service);
399     }
400 
401     /*
402      * When the mail system is down, the superuser can still access the queue
403      * directly. Just run the showq program in stand-alone mode.
404      */
405     else if (geteuid() == 0) {
406 	char   *showq_path;
407 	ARGV   *argv;
408 	int     stat;
409 
410 	msg_warn("Mail system is down -- accessing queue directly"
411 		 " (Connect to the %s %s service: %m)",
412 		 var_mail_name, var_showq_service);
413 	showq_path = concatenate(var_daemon_dir, "/", var_showq_service,
414 				 (char *) 0);
415 	argv = argv_alloc(6);
416 	argv_add(argv, showq_path, "-u", "-S", (char *) 0);
417 	for (n = 0; n < msg_verbose; n++)
418 	    argv_add(argv, "-v", (char *) 0);
419 	argv_terminate(argv);
420 	if ((showq = vstream_popen(O_RDONLY,
421 				   CA_VSTREAM_POPEN_ARGV(argv->argv),
422 				   CA_VSTREAM_POPEN_END)) == 0) {
423 	    stat = -1;
424 	} else {
425 	    showq_client(mode, showq);
426 	    stat = vstream_pclose(showq);
427 	}
428 	argv_free(argv);
429 	myfree(showq_path);
430 	if (stat != 0)
431 	    msg_fatal_status(stat < 0 ? EX_OSERR : EX_SOFTWARE,
432 			     "Error running %s", showq_path);
433     }
434 
435     /*
436      * When the mail system is down, unprivileged users are stuck, because by
437      * design the mail system contains no set_uid programs. The only way for
438      * an unprivileged user to cross protection boundaries is to talk to the
439      * showq daemon.
440      */
441     else {
442 	msg_fatal_status(EX_UNAVAILABLE,
443 			 "Queue report unavailable - mail system is down"
444 			 " (Connect to the %s %s service: %m)",
445 			 var_mail_name, var_showq_service);
446     }
447 }
448 
449 /* flush_queue - force delivery */
450 
451 static void flush_queue(void)
452 {
453     const char *errstr;
454     uid_t   uid = getuid();
455 
456     if (uid != 0 && uid != var_owner_uid
457 	&& (errstr = check_user_acl_byuid(VAR_FLUSH_ACL, var_flush_acl,
458 					  uid)) != 0)
459 	msg_fatal_status(EX_NOPERM,
460 		      "User %s(%ld) is not allowed to flush the mail queue",
461 			 errstr, (long) uid);
462 
463     /*
464      * Trigger the flush queue service.
465      */
466     if (mail_flush_deferred() < 0)
467 	msg_fatal_status(EX_UNAVAILABLE,
468 			 "Cannot flush mail queue - mail system is down");
469     if (mail_flush_maildrop() < 0)
470 	msg_fatal_status(EX_UNAVAILABLE,
471 			 "Cannot flush mail queue - mail system is down");
472     event_drain(2);
473 }
474 
475 /* flush_site - flush mail for site */
476 
477 static void flush_site(const char *site)
478 {
479     int     status;
480     const char *errstr;
481     uid_t   uid = getuid();
482 
483     if (uid != 0 && uid != var_owner_uid
484 	&& (errstr = check_user_acl_byuid(VAR_FLUSH_ACL, var_flush_acl,
485 					  uid)) != 0)
486 	msg_fatal_status(EX_NOPERM,
487 		      "User %s(%ld) is not allowed to flush the mail queue",
488 			 errstr, (long) uid);
489 
490     flush_init();
491 
492     switch (status = flush_send_site(site)) {
493     case FLUSH_STAT_OK:
494 	exit(0);
495     case FLUSH_STAT_BAD:
496 	msg_fatal_status(EX_USAGE, "Invalid request: \"%s\"", site);
497     case FLUSH_STAT_FAIL:
498 	msg_fatal_status(EX_UNAVAILABLE,
499 			 "Cannot flush mail queue - mail system is down");
500     case FLUSH_STAT_DENY:
501 	msg_fatal_status(EX_UNAVAILABLE,
502 		   "Flush service is not configured for destination \"%s\"",
503 			 site);
504     default:
505 	msg_fatal_status(EX_SOFTWARE,
506 			 "Unknown flush server reply status %d", status);
507     }
508 }
509 
510 /* flush_file - flush mail with specific queue ID */
511 
512 static void flush_file(const char *queue_id)
513 {
514     int     status;
515     const char *errstr;
516     uid_t   uid = getuid();
517 
518     if (uid != 0 && uid != var_owner_uid
519 	&& (errstr = check_user_acl_byuid(VAR_FLUSH_ACL, var_flush_acl,
520 					  uid)) != 0)
521 	msg_fatal_status(EX_NOPERM,
522 		      "User %s(%ld) is not allowed to flush the mail queue",
523 			 errstr, (long) uid);
524 
525     switch (status = flush_send_file(queue_id)) {
526     case FLUSH_STAT_OK:
527 	exit(0);
528     case FLUSH_STAT_BAD:
529 	msg_fatal_status(EX_USAGE, "Invalid request: \"%s\"", queue_id);
530     case FLUSH_STAT_FAIL:
531 	msg_fatal_status(EX_UNAVAILABLE,
532 			 "Cannot flush mail queue - mail system is down");
533     default:
534 	msg_fatal_status(EX_SOFTWARE,
535 			 "Unexpected flush server reply status %d", status);
536     }
537 }
538 
539 /* unavailable - sanitize exit status from library run-time errors */
540 
541 static void unavailable(void)
542 {
543     exit(EX_UNAVAILABLE);
544 }
545 
546 /* usage - scream and die */
547 
548 static NORETURN usage(void)
549 {
550     msg_fatal_status(EX_USAGE, "usage: postqueue -f | postqueue -i queueid | postqueue -j | postqueue -p | postqueue -s site");
551 }
552 
553 MAIL_VERSION_STAMP_DECLARE;
554 
555 /* main - the main program */
556 
557 int     main(int argc, char **argv)
558 {
559     struct stat st;
560     int     c;
561     int     fd;
562     int     mode = PQ_MODE_DEFAULT;
563     char   *site_to_flush = 0;
564     char   *id_to_flush = 0;
565     ARGV   *import_env;
566     int     bad_site;
567 
568     /*
569      * Fingerprint executables and core dumps.
570      */
571     MAIL_VERSION_STAMP_ALLOCATE;
572 
573     /*
574      * Be consistent with file permissions.
575      */
576     umask(022);
577 
578     /*
579      * To minimize confusion, make sure that the standard file descriptors
580      * are open before opening anything else. XXX Work around for 44BSD where
581      * fstat can return EBADF on an open file descriptor.
582      */
583     for (fd = 0; fd < 3; fd++)
584 	if (fstat(fd, &st) == -1
585 	    && (close(fd), open("/dev/null", O_RDWR, 0)) != fd)
586 	    msg_fatal_status(EX_UNAVAILABLE, "open /dev/null: %m");
587 
588     /*
589      * Initialize. Set up logging. Read the global configuration file after
590      * parsing command-line arguments. Censor the process name: it is
591      * provided by the user.
592      */
593     argv[0] = "postqueue";
594     msg_vstream_init(argv[0], VSTREAM_ERR);
595     msg_cleanup(unavailable);
596     maillog_client_init(mail_task("postqueue"), MAILLOG_CLIENT_FLAG_NONE);
597     set_mail_conf_str(VAR_PROCNAME, var_procname = mystrdup(argv[0]));
598 
599     /*
600      * Check the Postfix library version as soon as we enable logging.
601      */
602     MAIL_VERSION_CHECK;
603 
604     /*
605      * Parse JCL. This program is set-gid and must sanitize all command-line
606      * parameters. The configuration directory argument is validated by the
607      * mail configuration read routine. Don't do complex things until we have
608      * completed initializations.
609      */
610     while ((c = GETOPT(argc, argv, "c:fi:jps:v")) > 0) {
611 	switch (c) {
612 	case 'c':				/* non-default configuration */
613 	    if (setenv(CONF_ENV_PATH, optarg, 1) < 0)
614 		msg_fatal_status(EX_UNAVAILABLE, "out of memory");
615 	    break;
616 	case 'f':				/* flush queue */
617 	    if (mode != PQ_MODE_DEFAULT)
618 		usage();
619 	    mode = PQ_MODE_FLUSH_QUEUE;
620 	    break;
621 	case 'i':				/* flush queue file */
622 	    if (mode != PQ_MODE_DEFAULT)
623 		usage();
624 	    mode = PQ_MODE_FLUSH_FILE;
625 	    id_to_flush = optarg;
626 	    break;
627 	case 'j':
628 	    if (mode != PQ_MODE_DEFAULT)
629 		usage();
630 	    mode = PQ_MODE_JSON_LIST;
631 	    break;
632 	case 'p':				/* traditional mailq */
633 	    if (mode != PQ_MODE_DEFAULT)
634 		usage();
635 	    mode = PQ_MODE_MAILQ_LIST;
636 	    break;
637 	case 's':				/* flush site */
638 	    if (mode != PQ_MODE_DEFAULT)
639 		usage();
640 	    mode = PQ_MODE_FLUSH_SITE;
641 	    site_to_flush = optarg;
642 	    break;
643 	case 'v':
644 	    if (geteuid() == 0)
645 		msg_verbose++;
646 	    break;
647 	default:
648 	    usage();
649 	}
650     }
651     if (argc > optind)
652 	usage();
653 
654     /*
655      * Further initialization...
656      */
657     mail_conf_read();
658     /* Re-evaluate mail_task() after reading main.cf. */
659     maillog_client_init(mail_task("postqueue"), MAILLOG_CLIENT_FLAG_NONE);
660     mail_dict_init();				/* proxy, sql, ldap */
661     get_mail_conf_str_table(str_table);
662 
663     /*
664      * This program is designed to be set-gid, which makes it a potential
665      * target for attack. Strip and optionally override the process
666      * environment so that we don't have to trust the C library.
667      */
668     import_env = mail_parm_split(VAR_IMPORT_ENVIRON, var_import_environ);
669     clean_env(import_env->argv);
670     argv_free(import_env);
671 
672     if (chdir(var_queue_dir))
673 	msg_fatal_status(EX_UNAVAILABLE, "chdir %s: %m", var_queue_dir);
674 
675     signal(SIGPIPE, SIG_IGN);
676 
677     /* End of initializations. */
678 
679     /*
680      * Further input validation.
681      */
682     if (site_to_flush != 0) {
683 	bad_site = 0;
684 	if (*site_to_flush == '[') {
685 	    bad_site = !valid_mailhost_literal(site_to_flush, DONT_GRIPE);
686 	} else {
687 	    bad_site = !valid_hostname(site_to_flush, DONT_GRIPE);
688 	}
689 	if (bad_site)
690 	    msg_fatal_status(EX_USAGE,
691 	      "Cannot flush mail queue - invalid destination: \"%.100s%s\"",
692 		   site_to_flush, strlen(site_to_flush) > 100 ? "..." : "");
693     }
694     if (id_to_flush != 0) {
695 	if (!mail_queue_id_ok(id_to_flush))
696 	    msg_fatal_status(EX_USAGE,
697 		       "Cannot flush queue ID - invalid name: \"%.100s%s\"",
698 		       id_to_flush, strlen(id_to_flush) > 100 ? "..." : "");
699     }
700 
701     /*
702      * Start processing.
703      */
704     switch (mode) {
705     default:
706 	msg_panic("unknown operation mode: %d", mode);
707 	/* NOTREACHED */
708     case PQ_MODE_MAILQ_LIST:
709     case PQ_MODE_JSON_LIST:
710 	show_queue(mode);
711 	exit(0);
712 	break;
713     case PQ_MODE_FLUSH_SITE:
714 	flush_site(site_to_flush);
715 	exit(0);
716 	break;
717     case PQ_MODE_FLUSH_FILE:
718 	flush_file(id_to_flush);
719 	exit(0);
720 	break;
721     case PQ_MODE_FLUSH_QUEUE:
722 	flush_queue();
723 	exit(0);
724 	break;
725     case PQ_MODE_DEFAULT:
726 	usage();
727 	/* NOTREACHED */
728     }
729 }
730