1/*	$NetBSD$	*/
2
3/*++
4/* NAME
5/*	qmgr 8
6/* SUMMARY
7/*	Postfix queue manager
8/* SYNOPSIS
9/*	\fBqmgr\fR [generic Postfix daemon options]
10/* DESCRIPTION
11/*	The \fBqmgr\fR(8) daemon awaits the arrival of incoming mail
12/*	and arranges for its delivery via Postfix delivery processes.
13/*	The actual mail routing strategy is delegated to the
14/*	\fBtrivial-rewrite\fR(8) daemon.
15/*	This program expects to be run from the \fBmaster\fR(8) process
16/*	manager.
17/*
18/*	Mail addressed to the local \fBdouble-bounce\fR address is
19/*	logged and discarded.  This stops potential loops caused by
20/*	undeliverable bounce notifications.
21/* MAIL QUEUES
22/* .ad
23/* .fi
24/*	The \fBqmgr\fR(8) daemon maintains the following queues:
25/* .IP \fBincoming\fR
26/*	Inbound mail from the network, or mail picked up by the
27/*	local \fBpickup\fR(8) daemon from the \fBmaildrop\fR directory.
28/* .IP \fBactive\fR
29/*	Messages that the queue manager has opened for delivery. Only
30/*	a limited number of messages is allowed to enter the \fBactive\fR
31/*	queue (leaky bucket strategy, for a fixed delivery rate).
32/* .IP \fBdeferred\fR
33/*	Mail that could not be delivered upon the first attempt. The queue
34/*	manager implements exponential backoff by doubling the time between
35/*	delivery attempts.
36/* .IP \fBcorrupt\fR
37/*	Unreadable or damaged queue files are moved here for inspection.
38/* .IP \fBhold\fR
39/*	Messages that are kept "on hold" are kept here until someone
40/*	sets them free.
41/* DELIVERY STATUS REPORTS
42/* .ad
43/* .fi
44/*	The \fBqmgr\fR(8) daemon keeps an eye on per-message delivery status
45/*	reports in the following directories. Each status report file has
46/*	the same name as the corresponding message file:
47/* .IP \fBbounce\fR
48/*	Per-recipient status information about why mail is bounced.
49/*	These files are maintained by the \fBbounce\fR(8) daemon.
50/* .IP \fBdefer\fR
51/*	Per-recipient status information about why mail is delayed.
52/*	These files are maintained by the \fBdefer\fR(8) daemon.
53/* .IP \fBtrace\fR
54/*	Per-recipient status information as requested with the
55/*	Postfix "\fBsendmail -v\fR" or "\fBsendmail -bv\fR" command.
56/*	These files are maintained by the \fBtrace\fR(8) daemon.
57/* .PP
58/*	The \fBqmgr\fR(8) daemon is responsible for asking the
59/*	\fBbounce\fR(8), \fBdefer\fR(8) or \fBtrace\fR(8) daemons to
60/*	send delivery reports.
61/* STRATEGIES
62/* .ad
63/* .fi
64/*	The queue manager implements a variety of strategies for
65/*	either opening queue files (input) or for message delivery (output).
66/* .IP "\fBleaky bucket\fR"
67/*	This strategy limits the number of messages in the \fBactive\fR queue
68/*	and prevents the queue manager from running out of memory under
69/*	heavy load.
70/* .IP \fBfairness\fR
71/*	When the \fBactive\fR queue has room, the queue manager takes one
72/*	message from the \fBincoming\fR queue and one from the \fBdeferred\fR
73/*	queue. This prevents a large mail backlog from blocking the delivery
74/*	of new mail.
75/* .IP "\fBslow start\fR"
76/*	This strategy eliminates "thundering herd" problems by slowly
77/*	adjusting the number of parallel deliveries to the same destination.
78/* .IP "\fBround robin\fR
79/*	The queue manager sorts delivery requests by destination.
80/*	Round-robin selection prevents one destination from dominating
81/*	deliveries to other destinations.
82/* .IP "\fBexponential backoff\fR"
83/*	Mail that cannot be delivered upon the first attempt is deferred.
84/*	The time interval between delivery attempts is doubled after each
85/*	attempt.
86/* .IP "\fBdestination status cache\fR"
87/*	The queue manager avoids unnecessary delivery attempts by
88/*	maintaining a short-term, in-memory list of unreachable destinations.
89/* .IP "\fBpreemptive message scheduling\fR"
90/*	The queue manager attempts to minimize the average per-recipient delay
91/*	while still preserving the correct per-message delays, using
92/*	a sophisticated preemptive message scheduling.
93/* TRIGGERS
94/* .ad
95/* .fi
96/*	On an idle system, the queue manager waits for the arrival of
97/*	trigger events, or it waits for a timer to go off. A trigger
98/*	is a one-byte message.
99/*	Depending on the message received, the queue manager performs
100/*	one of the following actions (the message is followed by the
101/*	symbolic constant used internally by the software):
102/* .IP "\fBD (QMGR_REQ_SCAN_DEFERRED)\fR"
103/*	Start a deferred queue scan.  If a deferred queue scan is already
104/*	in progress, that scan will be restarted as soon as it finishes.
105/* .IP "\fBI (QMGR_REQ_SCAN_INCOMING)\fR"
106/*	Start an incoming queue scan. If an incoming queue scan is already
107/*	in progress, that scan will be restarted as soon as it finishes.
108/* .IP "\fBA (QMGR_REQ_SCAN_ALL)\fR"
109/*	Ignore deferred queue file time stamps. The request affects
110/*	the next deferred queue scan.
111/* .IP "\fBF (QMGR_REQ_FLUSH_DEAD)\fR"
112/*	Purge all information about dead transports and destinations.
113/* .IP "\fBW (TRIGGER_REQ_WAKEUP)\fR"
114/*	Wakeup call, This is used by the master server to instantiate
115/*	servers that should not go away forever. The action is to start
116/*	an incoming queue scan.
117/* .PP
118/*	The \fBqmgr\fR(8) daemon reads an entire buffer worth of triggers.
119/*	Multiple identical trigger requests are collapsed into one, and
120/*	trigger requests are sorted so that \fBA\fR and \fBF\fR precede
121/*	\fBD\fR and \fBI\fR. Thus, in order to force a deferred queue run,
122/*	one would request \fBA F D\fR; in order to notify the queue manager
123/*	of the arrival of new mail one would request \fBI\fR.
124/* STANDARDS
125/*	RFC 3463 (Enhanced status codes)
126/*	RFC 3464 (Delivery status notifications)
127/* SECURITY
128/* .ad
129/* .fi
130/*	The \fBqmgr\fR(8) daemon is not security sensitive. It reads
131/*	single-character messages from untrusted local users, and thus may
132/*	be susceptible to denial of service attacks. The \fBqmgr\fR(8) daemon
133/*	does not talk to the outside world, and it can be run at fixed low
134/*	privilege in a chrooted environment.
135/* DIAGNOSTICS
136/*	Problems and transactions are logged to the syslog daemon.
137/*	Corrupted message files are saved to the \fBcorrupt\fR queue
138/*	for further inspection.
139/*
140/*	Depending on the setting of the \fBnotify_classes\fR parameter,
141/*	the postmaster is notified of bounces and of other trouble.
142/* BUGS
143/*	A single queue manager process has to compete for disk access with
144/*	multiple front-end processes such as \fBcleanup\fR(8). A sudden burst of
145/*	inbound mail can negatively impact outbound delivery rates.
146/* CONFIGURATION PARAMETERS
147/* .ad
148/* .fi
149/*	Changes to \fBmain.cf\fR are not picked up automatically
150/*	as \fBqmgr\fR(8)
151/*	is a persistent process. Use the "\fBpostfix reload\fR" command after
152/*	a configuration change.
153/*
154/*	The text below provides only a parameter summary. See
155/*	\fBpostconf\fR(5) for more details including examples.
156/*
157/*	In the text below, \fItransport\fR is the first field in a
158/*	\fBmaster.cf\fR entry.
159/* COMPATIBILITY CONTROLS
160/* .ad
161/* .fi
162/*	Available before Postfix version 2.5:
163/* .IP "\fBallow_min_user (no)\fR"
164/*	Allow a sender or recipient address to have `-' as the first
165/*	character.
166/* .PP
167/*	Available with Postfix version 2.7 and later:
168/* .IP "\fBdefault_filter_nexthop (empty)\fR"
169/*	When a content_filter or FILTER request specifies no explicit
170/*	next-hop destination, use $default_filter_nexthop instead; when
171/*	that value is empty, use the domain in the recipient address.
172/* ACTIVE QUEUE CONTROLS
173/* .ad
174/* .fi
175/* .IP "\fBqmgr_clog_warn_time (300s)\fR"
176/*	The minimal delay between warnings that a specific destination is
177/*	clogging up the Postfix active queue.
178/* .IP "\fBqmgr_message_active_limit (20000)\fR"
179/*	The maximal number of messages in the active queue.
180/* .IP "\fBqmgr_message_recipient_limit (20000)\fR"
181/*	The maximal number of recipients held in memory by the Postfix
182/*	queue manager, and the maximal size of the size of the short-term,
183/*	in-memory "dead" destination status cache.
184/* .IP "\fBqmgr_message_recipient_minimum (10)\fR"
185/*	The minimal number of in-memory recipients for any message.
186/* .IP "\fBdefault_recipient_limit (20000)\fR"
187/*	The default per-transport upper limit on the number of in-memory
188/*	recipients.
189/* .IP "\fItransport\fB_recipient_limit ($default_recipient_limit)\fR"
190/*	Idem, for delivery via the named message \fItransport\fR.
191/* .IP "\fBdefault_extra_recipient_limit (1000)\fR"
192/*	The default value for the extra per-transport limit imposed on the
193/*	number of in-memory recipients.
194/* .IP "\fItransport\fB_extra_recipient_limit ($default_extra_recipient_limit)\fR"
195/*	Idem, for delivery via the named message \fItransport\fR.
196/* .PP
197/*	Available in Postfix version 2.4 and later:
198/* .IP "\fBdefault_recipient_refill_limit (100)\fR"
199/*	The default per-transport limit on the number of recipients refilled at
200/*	once.
201/* .IP "\fItransport\fB_recipient_refill_limit ($default_recipient_refill_limit)\fR"
202/*	Idem, for delivery via the named message \fItransport\fR.
203/* .IP "\fBdefault_recipient_refill_delay (5s)\fR"
204/*	The default per-transport maximum delay between recipients refills.
205/* .IP "\fItransport\fB_recipient_refill_delay ($default_recipient_refill_delay)\fR"
206/*	Idem, for delivery via the named message \fItransport\fR.
207/* DELIVERY CONCURRENCY CONTROLS
208/* .ad
209/* .fi
210/* .IP "\fBinitial_destination_concurrency (5)\fR"
211/*	The initial per-destination concurrency level for parallel delivery
212/*	to the same destination.
213/* .IP "\fBdefault_destination_concurrency_limit (20)\fR"
214/*	The default maximal number of parallel deliveries to the same
215/*	destination.
216/* .IP "\fItransport\fB_destination_concurrency_limit ($default_destination_concurrency_limit)\fR"
217/*	Idem, for delivery via the named message \fItransport\fR.
218/* .PP
219/*	Available in Postfix version 2.5 and later:
220/* .IP "\fItransport\fB_initial_destination_concurrency ($initial_destination_concurrency)\fR"
221/*	Initial concurrency for delivery via the named message
222/*	\fItransport\fR.
223/* .IP "\fBdefault_destination_concurrency_failed_cohort_limit (1)\fR"
224/*	How many pseudo-cohorts must suffer connection or handshake
225/*	failure before a specific destination is considered unavailable
226/*	(and further delivery is suspended).
227/* .IP "\fItransport\fB_destination_concurrency_failed_cohort_limit ($default_destination_concurrency_failed_cohort_limit)\fR"
228/*	Idem, for delivery via the named message \fItransport\fR.
229/* .IP "\fBdefault_destination_concurrency_negative_feedback (1)\fR"
230/*	The per-destination amount of delivery concurrency negative
231/*	feedback, after a delivery completes with a connection or handshake
232/*	failure.
233/* .IP "\fItransport\fB_destination_concurrency_negative_feedback ($default_destination_concurrency_negative_feedback)\fR"
234/*	Idem, for delivery via the named message \fItransport\fR.
235/* .IP "\fBdefault_destination_concurrency_positive_feedback (1)\fR"
236/*	The per-destination amount of delivery concurrency positive
237/*	feedback, after a delivery completes without connection or handshake
238/*	failure.
239/* .IP "\fItransport\fB_destination_concurrency_positive_feedback ($default_destination_concurrency_positive_feedback)\fR"
240/*	Idem, for delivery via the named message \fItransport\fR.
241/* .IP "\fBdestination_concurrency_feedback_debug (no)\fR"
242/*	Make the queue manager's feedback algorithm verbose for performance
243/*	analysis purposes.
244/* RECIPIENT SCHEDULING CONTROLS
245/* .ad
246/* .fi
247/* .IP "\fBdefault_destination_recipient_limit (50)\fR"
248/*	The default maximal number of recipients per message delivery.
249/* .IP "\fItransport\fB_destination_recipient_limit ($default_destination_recipient_limit)\fR"
250/*	Idem, for delivery via the named message \fItransport\fR.
251/* MESSAGE SCHEDULING CONTROLS
252/* .ad
253/* .fi
254/* .IP "\fBdefault_delivery_slot_cost (5)\fR"
255/*	How often the Postfix queue manager's scheduler is allowed to
256/*	preempt delivery of one message with another.
257/* .IP "\fItransport\fB_delivery_slot_cost ($default_delivery_slot_cost)\fR"
258/*	Idem, for delivery via the named message \fItransport\fR.
259/* .IP "\fBdefault_minimum_delivery_slots (3)\fR"
260/*	How many recipients a message must have in order to invoke the
261/*	Postfix queue manager's scheduling algorithm at all.
262/* .IP "\fItransport\fB_minimum_delivery_slots ($default_minimum_delivery_slots)\fR"
263/*	Idem, for delivery via the named message \fItransport\fR.
264/* .IP "\fBdefault_delivery_slot_discount (50)\fR"
265/*	The default value for transport-specific _delivery_slot_discount
266/*	settings.
267/* .IP "\fItransport\fB_delivery_slot_discount ($default_delivery_slot_discount)\fR"
268/*	Idem, for delivery via the named message \fItransport\fR.
269/* .IP "\fBdefault_delivery_slot_loan (3)\fR"
270/*	The default value for transport-specific _delivery_slot_loan
271/*	settings.
272/* .IP "\fItransport\fB_delivery_slot_loan ($default_delivery_slot_loan)\fR"
273/*	Idem, for delivery via the named message \fItransport\fR.
274/* OTHER RESOURCE AND RATE CONTROLS
275/* .ad
276/* .fi
277/* .IP "\fBminimal_backoff_time (300s)\fR"
278/*	The minimal time between attempts to deliver a deferred message;
279/*	prior to Postfix 2.4 the default value was 1000s.
280/* .IP "\fBmaximal_backoff_time (4000s)\fR"
281/*	The maximal time between attempts to deliver a deferred message.
282/* .IP "\fBmaximal_queue_lifetime (5d)\fR"
283/*	The maximal time a message is queued before it is sent back as
284/*	undeliverable.
285/* .IP "\fBqueue_run_delay (300s)\fR"
286/*	The time between deferred queue scans by the queue manager;
287/*	prior to Postfix 2.4 the default value was 1000s.
288/* .IP "\fBtransport_retry_time (60s)\fR"
289/*	The time between attempts by the Postfix queue manager to contact
290/*	a malfunctioning message delivery transport.
291/* .PP
292/*	Available in Postfix version 2.1 and later:
293/* .IP "\fBbounce_queue_lifetime (5d)\fR"
294/*	The maximal time a bounce message is queued before it is considered
295/*	undeliverable.
296/* .PP
297/*	Available in Postfix version 2.5 and later:
298/* .IP "\fBdefault_destination_rate_delay (0s)\fR"
299/*	The default amount of delay that is inserted between individual
300/*	deliveries to the same destination; with per-destination recipient
301/*	limit > 1, a destination is a domain, otherwise it is a recipient.
302/* .IP "\fItransport\fB_destination_rate_delay $default_destination_rate_delay
303/*	Idem, for delivery via the named message \fItransport\fR.
304/* SAFETY CONTROLS
305/* .ad
306/* .fi
307/* .IP "\fBqmgr_daemon_timeout (1000s)\fR"
308/*	How much time a Postfix queue manager process may take to handle
309/*	a request before it is terminated by a built-in watchdog timer.
310/* .IP "\fBqmgr_ipc_timeout (60s)\fR"
311/*	The time limit for the queue manager to send or receive information
312/*	over an internal communication channel.
313/* MISCELLANEOUS CONTROLS
314/* .ad
315/* .fi
316/* .IP "\fBconfig_directory (see 'postconf -d' output)\fR"
317/*	The default location of the Postfix main.cf and master.cf
318/*	configuration files.
319/* .IP "\fBdefer_transports (empty)\fR"
320/*	The names of message delivery transports that should not deliver mail
321/*	unless someone issues "\fBsendmail -q\fR" or equivalent.
322/* .IP "\fBdelay_logging_resolution_limit (2)\fR"
323/*	The maximal number of digits after the decimal point when logging
324/*	sub-second delay values.
325/* .IP "\fBhelpful_warnings (yes)\fR"
326/*	Log warnings about problematic configuration settings, and provide
327/*	helpful suggestions.
328/* .IP "\fBprocess_id (read-only)\fR"
329/*	The process ID of a Postfix command or daemon process.
330/* .IP "\fBprocess_name (read-only)\fR"
331/*	The process name of a Postfix command or daemon process.
332/* .IP "\fBqueue_directory (see 'postconf -d' output)\fR"
333/*	The location of the Postfix top-level queue directory.
334/* .IP "\fBsyslog_facility (mail)\fR"
335/*	The syslog facility of Postfix logging.
336/* .IP "\fBsyslog_name (see 'postconf -d' output)\fR"
337/*	The mail system name that is prepended to the process name in syslog
338/*	records, so that "smtpd" becomes, for example, "postfix/smtpd".
339/* FILES
340/*	/var/spool/postfix/incoming, incoming queue
341/*	/var/spool/postfix/active, active queue
342/*	/var/spool/postfix/deferred, deferred queue
343/*	/var/spool/postfix/bounce, non-delivery status
344/*	/var/spool/postfix/defer, non-delivery status
345/*	/var/spool/postfix/trace, delivery status
346/* SEE ALSO
347/*	trivial-rewrite(8), address routing
348/*	bounce(8), delivery status reports
349/*	postconf(5), configuration parameters
350/*	master(5), generic daemon options
351/*	master(8), process manager
352/*	syslogd(8), system logging
353/* README FILES
354/* .ad
355/* .fi
356/*	Use "\fBpostconf readme_directory\fR" or
357/*	"\fBpostconf html_directory\fR" to locate this information.
358/* .na
359/* .nf
360/*	SCHEDULER_README, scheduling algorithm
361/*	QSHAPE_README, Postfix queue analysis
362/* LICENSE
363/* .ad
364/* .fi
365/*	The Secure Mailer license must be distributed with this software.
366/* AUTHOR(S)
367/*	Wietse Venema
368/*	IBM T.J. Watson Research
369/*	P.O. Box 704
370/*	Yorktown Heights, NY 10598, USA
371/*
372/*	Preemptive scheduler enhancements:
373/*	Patrik Rak
374/*	Modra 6
375/*	155 00, Prague, Czech Republic
376/*--*/
377
378/* System library. */
379
380#include <sys_defs.h>
381#include <stdlib.h>
382#include <unistd.h>
383#include <ctype.h>
384
385/* Utility library. */
386
387#include <msg.h>
388#include <events.h>
389#include <vstream.h>
390#include <dict.h>
391
392/* Global library. */
393
394#include <mail_queue.h>
395#include <recipient_list.h>
396#include <mail_conf.h>
397#include <mail_params.h>
398#include <mail_version.h>
399#include <mail_proto.h>			/* QMGR_SCAN constants */
400#include <mail_flow.h>
401#include <flush_clnt.h>
402
403/* Master process interface */
404
405#include <master_proto.h>
406#include <mail_server.h>
407
408/* Application-specific. */
409
410#include "qmgr.h"
411
412 /*
413  * Tunables.
414  */
415int     var_queue_run_delay;
416int     var_min_backoff_time;
417int     var_max_backoff_time;
418int     var_max_queue_time;
419int     var_dsn_queue_time;
420int     var_qmgr_active_limit;
421int     var_qmgr_rcpt_limit;
422int     var_qmgr_msg_rcpt_limit;
423int     var_xport_rcpt_limit;
424int     var_stack_rcpt_limit;
425int     var_xport_refill_limit;
426int     var_xport_refill_delay;
427int     var_delivery_slot_cost;
428int     var_delivery_slot_loan;
429int     var_delivery_slot_discount;
430int     var_min_delivery_slots;
431int     var_init_dest_concurrency;
432int     var_transport_retry_time;
433int     var_dest_con_limit;
434int     var_dest_rcpt_limit;
435char   *var_defer_xports;
436int     var_local_con_lim;
437int     var_local_rcpt_lim;
438int     var_proc_limit;
439bool    var_verp_bounce_off;
440int     var_qmgr_clog_warn_time;
441char   *var_conc_pos_feedback;
442char   *var_conc_neg_feedback;
443int     var_conc_cohort_limit;
444int     var_conc_feedback_debug;
445int     var_dest_rate_delay;
446char   *var_def_filter_nexthop;
447int     var_qmgr_daemon_timeout;
448int     var_qmgr_ipc_timeout;
449
450static QMGR_SCAN *qmgr_scans[2];
451
452#define QMGR_SCAN_IDX_INCOMING 0
453#define QMGR_SCAN_IDX_DEFERRED 1
454#define QMGR_SCAN_IDX_COUNT (sizeof(qmgr_scans) / sizeof(qmgr_scans[0]))
455
456/* qmgr_deferred_run_event - queue manager heartbeat */
457
458static void qmgr_deferred_run_event(int unused_event, char *dummy)
459{
460
461    /*
462     * This routine runs when it is time for another deferred queue scan.
463     * Make sure this routine gets called again in the future.
464     */
465    qmgr_scan_request(qmgr_scans[QMGR_SCAN_IDX_DEFERRED], QMGR_SCAN_START);
466    event_request_timer(qmgr_deferred_run_event, dummy, var_queue_run_delay);
467}
468
469/* qmgr_trigger_event - respond to external trigger(s) */
470
471static void qmgr_trigger_event(char *buf, int len,
472			               char *unused_service, char **argv)
473{
474    int     incoming_flag = 0;
475    int     deferred_flag = 0;
476    int     i;
477
478    /*
479     * Sanity check. This service takes no command-line arguments.
480     */
481    if (argv[0])
482	msg_fatal("unexpected command-line argument: %s", argv[0]);
483
484    /*
485     * Collapse identical requests that have arrived since we looked last
486     * time. There is no client feedback so there is no need to process each
487     * request in order. And as long as we don't have conflicting requests we
488     * are free to sort them into the most suitable order.
489     */
490#define QMGR_FLUSH_BEFORE	(QMGR_FLUSH_ONCE | QMGR_FLUSH_DFXP)
491
492    for (i = 0; i < len; i++) {
493	if (msg_verbose)
494	    msg_info("request: %d (%c)",
495		     buf[i], ISALNUM(buf[i]) ? buf[i] : '?');
496	switch (buf[i]) {
497	case TRIGGER_REQ_WAKEUP:
498	case QMGR_REQ_SCAN_INCOMING:
499	    incoming_flag |= QMGR_SCAN_START;
500	    break;
501	case QMGR_REQ_SCAN_DEFERRED:
502	    deferred_flag |= QMGR_SCAN_START;
503	    break;
504	case QMGR_REQ_FLUSH_DEAD:
505	    deferred_flag |= QMGR_FLUSH_BEFORE;
506	    incoming_flag |= QMGR_FLUSH_BEFORE;
507	    break;
508	case QMGR_REQ_SCAN_ALL:
509	    deferred_flag |= QMGR_SCAN_ALL;
510	    incoming_flag |= QMGR_SCAN_ALL;
511	    break;
512	default:
513	    if (msg_verbose)
514		msg_info("request ignored");
515	    break;
516	}
517    }
518
519    /*
520     * Process each request type at most once. Modifiers take effect upon the
521     * next queue run. If no queue run is in progress, and a queue scan is
522     * requested, the request takes effect immediately.
523     */
524    if (incoming_flag != 0)
525	qmgr_scan_request(qmgr_scans[QMGR_SCAN_IDX_INCOMING], incoming_flag);
526    if (deferred_flag != 0)
527	qmgr_scan_request(qmgr_scans[QMGR_SCAN_IDX_DEFERRED], deferred_flag);
528}
529
530/* qmgr_loop - queue manager main loop */
531
532static int qmgr_loop(char *unused_name, char **unused_argv)
533{
534    char   *path;
535    int     token_count;
536    int     feed = 0;
537    int     scan_idx;			/* Priority order scan index */
538    static int first_scan_idx = QMGR_SCAN_IDX_INCOMING;
539    int     last_scan_idx = QMGR_SCAN_IDX_COUNT - 1;
540    int     delay;
541
542    /*
543     * This routine runs as part of the event handling loop, after the event
544     * manager has delivered a timer or I/O event (including the completion
545     * of a connection to a delivery process), or after it has waited for a
546     * specified amount of time. The result value of qmgr_loop() specifies
547     * how long the event manager should wait for the next event.
548     */
549#define DONT_WAIT	0
550#define WAIT_FOR_EVENT	(-1)
551
552    /*
553     * Attempt to drain the active queue by allocating a suitable delivery
554     * process and by delivering mail via it. Delivery process allocation and
555     * mail delivery are asynchronous.
556     */
557    qmgr_active_drain();
558
559    /*
560     * Let some new blood into the active queue when the queue size is
561     * smaller than some configurable limit.
562     *
563     * We import one message per interrupt, to optimally tune the input count
564     * for the number of delivery agent protocol wait states, as explained in
565     * qmgr_transport.c.
566     */
567    delay = WAIT_FOR_EVENT;
568    for (scan_idx = 0; qmgr_message_count < var_qmgr_active_limit
569	 && scan_idx < QMGR_SCAN_IDX_COUNT; ++scan_idx) {
570	last_scan_idx = (scan_idx + first_scan_idx) % QMGR_SCAN_IDX_COUNT;
571	if ((path = qmgr_scan_next(qmgr_scans[last_scan_idx])) != 0) {
572	    delay = DONT_WAIT;
573	    if ((feed = qmgr_active_feed(qmgr_scans[last_scan_idx], path)) != 0)
574		break;
575	}
576    }
577
578    /*
579     * Round-robin the queue scans. When the active queue becomes full,
580     * prefer new mail over deferred mail.
581     */
582    if (qmgr_message_count < var_qmgr_active_limit) {
583	first_scan_idx = (last_scan_idx + 1) % QMGR_SCAN_IDX_COUNT;
584    } else if (first_scan_idx != QMGR_SCAN_IDX_INCOMING) {
585	first_scan_idx = QMGR_SCAN_IDX_INCOMING;
586    }
587
588    /*
589     * Global flow control. If enabled, slow down receiving processes that
590     * get ahead of the queue manager, but don't block them completely.
591     */
592    if (var_in_flow_delay > 0) {
593	token_count = mail_flow_count();
594	if (token_count < var_proc_limit) {
595	    if (feed != 0 && last_scan_idx == QMGR_SCAN_IDX_INCOMING)
596		mail_flow_put(1);
597	    else if (qmgr_scans[QMGR_SCAN_IDX_INCOMING]->handle == 0)
598		mail_flow_put(var_proc_limit - token_count);
599	} else if (token_count > var_proc_limit) {
600	    mail_flow_get(token_count - var_proc_limit);
601	}
602    }
603    return (delay);
604}
605
606/* pre_accept - see if tables have changed */
607
608static void pre_accept(char *unused_name, char **unused_argv)
609{
610    const char *table;
611
612    if ((table = dict_changed_name()) != 0) {
613	msg_info("table %s has changed -- restarting", table);
614	exit(0);
615    }
616}
617
618/* qmgr_pre_init - pre-jail initialization */
619
620static void qmgr_pre_init(char *unused_name, char **unused_argv)
621{
622    flush_init();
623}
624
625/* qmgr_post_init - post-jail initialization */
626
627static void qmgr_post_init(char *name, char **unused_argv)
628{
629
630    /*
631     * Backwards compatibility.
632     */
633    if (strcmp(var_procname, "nqmgr") == 0) {
634	msg_warn("please update the %s/%s file; the new queue manager",
635		 var_config_dir, MASTER_CONF_FILE);
636	msg_warn("(old name: nqmgr) has become the standard queue manager (new name: qmgr)");
637	msg_warn("support for the name old name (nqmgr) will be removed from Postfix");
638    }
639
640    /*
641     * Sanity check.
642     */
643    if (var_qmgr_rcpt_limit < var_qmgr_active_limit) {
644	msg_warn("%s is smaller than %s - adjusting %s",
645	      VAR_QMGR_RCPT_LIMIT, VAR_QMGR_ACT_LIMIT, VAR_QMGR_RCPT_LIMIT);
646	var_qmgr_rcpt_limit = var_qmgr_active_limit;
647    }
648    if (var_dsn_queue_time > var_max_queue_time) {
649	msg_warn("%s is larger than %s - adjusting %s",
650		 VAR_DSN_QUEUE_TIME, VAR_MAX_QUEUE_TIME, VAR_DSN_QUEUE_TIME);
651	var_dsn_queue_time = var_max_queue_time;
652    }
653
654    /*
655     * This routine runs after the skeleton code has entered the chroot jail.
656     * Prevent automatic process suicide after a limited number of client
657     * requests or after a limited amount of idle time. Move any left-over
658     * entries from the active queue to the incoming queue, and give them a
659     * time stamp into the future, in order to allow ongoing deliveries to
660     * finish first. Start scanning the incoming and deferred queues.
661     * Left-over active queue entries are moved to the incoming queue because
662     * the incoming queue has priority; moving left-overs to the deferred
663     * queue could cause anomalous delays when "postfix reload/start" are
664     * issued often. Override the IPC timeout (default 3600s) so that the
665     * queue manager can reset a broken IPC channel before the watchdog timer
666     * goes off.
667     */
668    var_ipc_timeout = var_qmgr_ipc_timeout;
669    var_use_limit = 0;
670    var_idle_limit = 0;
671    qmgr_move(MAIL_QUEUE_ACTIVE, MAIL_QUEUE_INCOMING, event_time());
672    qmgr_scans[QMGR_SCAN_IDX_INCOMING] = qmgr_scan_create(MAIL_QUEUE_INCOMING);
673    qmgr_scans[QMGR_SCAN_IDX_DEFERRED] = qmgr_scan_create(MAIL_QUEUE_DEFERRED);
674    qmgr_scan_request(qmgr_scans[QMGR_SCAN_IDX_INCOMING], QMGR_SCAN_START);
675    qmgr_deferred_run_event(0, (char *) 0);
676}
677
678MAIL_VERSION_STAMP_DECLARE;
679
680/* main - the main program */
681
682int     main(int argc, char **argv)
683{
684    static const CONFIG_STR_TABLE str_table[] = {
685	VAR_DEFER_XPORTS, DEF_DEFER_XPORTS, &var_defer_xports, 0, 0,
686	VAR_CONC_POS_FDBACK, DEF_CONC_POS_FDBACK, &var_conc_pos_feedback, 1, 0,
687	VAR_CONC_NEG_FDBACK, DEF_CONC_NEG_FDBACK, &var_conc_neg_feedback, 1, 0,
688	VAR_DEF_FILTER_NEXTHOP, DEF_DEF_FILTER_NEXTHOP, &var_def_filter_nexthop, 0, 0,
689	0,
690    };
691    static const CONFIG_TIME_TABLE time_table[] = {
692	VAR_QUEUE_RUN_DELAY, DEF_QUEUE_RUN_DELAY, &var_queue_run_delay, 1, 0,
693	VAR_MIN_BACKOFF_TIME, DEF_MIN_BACKOFF_TIME, &var_min_backoff_time, 1, 0,
694	VAR_MAX_BACKOFF_TIME, DEF_MAX_BACKOFF_TIME, &var_max_backoff_time, 1, 0,
695	VAR_MAX_QUEUE_TIME, DEF_MAX_QUEUE_TIME, &var_max_queue_time, 0, 8640000,
696	VAR_DSN_QUEUE_TIME, DEF_DSN_QUEUE_TIME, &var_dsn_queue_time, 0, 8640000,
697	VAR_XPORT_RETRY_TIME, DEF_XPORT_RETRY_TIME, &var_transport_retry_time, 1, 0,
698	VAR_QMGR_CLOG_WARN_TIME, DEF_QMGR_CLOG_WARN_TIME, &var_qmgr_clog_warn_time, 0, 0,
699	VAR_XPORT_REFILL_DELAY, DEF_XPORT_REFILL_DELAY, &var_xport_refill_delay, 1, 0,
700	VAR_DEST_RATE_DELAY, DEF_DEST_RATE_DELAY, &var_dest_rate_delay, 0, 0,
701	VAR_QMGR_DAEMON_TIMEOUT, DEF_QMGR_DAEMON_TIMEOUT, &var_qmgr_daemon_timeout, 1, 0,
702	VAR_QMGR_IPC_TIMEOUT, DEF_QMGR_IPC_TIMEOUT, &var_qmgr_ipc_timeout, 1, 0,
703	0,
704    };
705    static const CONFIG_INT_TABLE int_table[] = {
706	VAR_QMGR_ACT_LIMIT, DEF_QMGR_ACT_LIMIT, &var_qmgr_active_limit, 1, 0,
707	VAR_QMGR_RCPT_LIMIT, DEF_QMGR_RCPT_LIMIT, &var_qmgr_rcpt_limit, 1, 0,
708	VAR_QMGR_MSG_RCPT_LIMIT, DEF_QMGR_MSG_RCPT_LIMIT, &var_qmgr_msg_rcpt_limit, 1, 0,
709	VAR_XPORT_RCPT_LIMIT, DEF_XPORT_RCPT_LIMIT, &var_xport_rcpt_limit, 0, 0,
710	VAR_STACK_RCPT_LIMIT, DEF_STACK_RCPT_LIMIT, &var_stack_rcpt_limit, 0, 0,
711	VAR_XPORT_REFILL_LIMIT, DEF_XPORT_REFILL_LIMIT, &var_xport_refill_limit, 1, 0,
712	VAR_DELIVERY_SLOT_COST, DEF_DELIVERY_SLOT_COST, &var_delivery_slot_cost, 0, 0,
713	VAR_DELIVERY_SLOT_LOAN, DEF_DELIVERY_SLOT_LOAN, &var_delivery_slot_loan, 0, 0,
714	VAR_DELIVERY_SLOT_DISCOUNT, DEF_DELIVERY_SLOT_DISCOUNT, &var_delivery_slot_discount, 0, 100,
715	VAR_MIN_DELIVERY_SLOTS, DEF_MIN_DELIVERY_SLOTS, &var_min_delivery_slots, 0, 0,
716	VAR_INIT_DEST_CON, DEF_INIT_DEST_CON, &var_init_dest_concurrency, 1, 0,
717	VAR_DEST_CON_LIMIT, DEF_DEST_CON_LIMIT, &var_dest_con_limit, 0, 0,
718	VAR_DEST_RCPT_LIMIT, DEF_DEST_RCPT_LIMIT, &var_dest_rcpt_limit, 0, 0,
719	VAR_LOCAL_RCPT_LIMIT, DEF_LOCAL_RCPT_LIMIT, &var_local_rcpt_lim, 0, 0,
720	VAR_LOCAL_CON_LIMIT, DEF_LOCAL_CON_LIMIT, &var_local_con_lim, 0, 0,
721	VAR_PROC_LIMIT, DEF_PROC_LIMIT, &var_proc_limit, 1, 0,
722	VAR_CONC_COHORT_LIM, DEF_CONC_COHORT_LIM, &var_conc_cohort_limit, 0, 0,
723	0,
724    };
725    static const CONFIG_BOOL_TABLE bool_table[] = {
726	VAR_VERP_BOUNCE_OFF, DEF_VERP_BOUNCE_OFF, &var_verp_bounce_off,
727	VAR_CONC_FDBACK_DEBUG, DEF_CONC_FDBACK_DEBUG, &var_conc_feedback_debug,
728	0,
729    };
730
731    /*
732     * Fingerprint executables and core dumps.
733     */
734    MAIL_VERSION_STAMP_ALLOCATE;
735
736    /*
737     * Use the trigger service skeleton, because no-one else should be
738     * monitoring our service port while this process runs, and because we do
739     * not talk back to the client.
740     */
741    trigger_server_main(argc, argv, qmgr_trigger_event,
742			MAIL_SERVER_INT_TABLE, int_table,
743			MAIL_SERVER_STR_TABLE, str_table,
744			MAIL_SERVER_BOOL_TABLE, bool_table,
745			MAIL_SERVER_TIME_TABLE, time_table,
746			MAIL_SERVER_PRE_INIT, qmgr_pre_init,
747			MAIL_SERVER_POST_INIT, qmgr_post_init,
748			MAIL_SERVER_LOOP, qmgr_loop,
749			MAIL_SERVER_PRE_ACCEPT, pre_accept,
750			MAIL_SERVER_SOLITARY,
751			MAIL_SERVER_WATCHDOG, &var_qmgr_daemon_timeout,
752			0);
753}
754