xref: /netbsd-src/external/ibm-public/postfix/dist/src/flush/flush.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: flush.c,v 1.2 2017/02/14 01:16:45 christos Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	flush 8
6 /* SUMMARY
7 /*	Postfix fast flush server
8 /* SYNOPSIS
9 /*	\fBflush\fR [generic Postfix daemon options]
10 /* DESCRIPTION
11 /*	The \fBflush\fR(8) server maintains a record of deferred
12 /*	mail by destination.
13 /*	This information is used to improve the performance of the SMTP
14 /*	\fBETRN\fR request, and of its command-line equivalent,
15 /*	"\fBsendmail -qR\fR" or "\fBpostqueue -f\fR".
16 /*	This program expects to be run from the \fBmaster\fR(8) process
17 /*	manager.
18 /*
19 /*	The record is implemented as a per-destination logfile with
20 /*	as contents the queue IDs of deferred mail. A logfile is
21 /*	append-only, and is truncated when delivery is requested
22 /*	for the corresponding destination. A destination is the
23 /*	part on the right-hand side of the right-most \fB@\fR in
24 /*	an email address.
25 /*
26 /*	Per-destination logfiles of deferred mail are maintained only for
27 /*	eligible destinations. The list of eligible destinations is
28 /*	specified with the \fBfast_flush_domains\fR configuration parameter,
29 /*	which defaults to \fB$relay_domains\fR.
30 /*
31 /*	This server implements the following requests:
32 /* .IP "\fBadd\fI sitename queueid\fR"
33 /*	Inform the \fBflush\fR(8) server that the message with the specified
34 /*	queue ID is queued for the specified destination.
35 /* .IP "\fBsend_site\fI sitename\fR"
36 /*	Request delivery of mail that is queued for the specified
37 /*	destination.
38 /* .IP "\fBsend_file\fI queueid\fR"
39 /*	Request delivery of the specified deferred message.
40 /* .IP \fBrefresh\fR
41 /*	Refresh non-empty per-destination logfiles that were not read in
42 /*	\fB$fast_flush_refresh_time\fR hours, by simulating
43 /*	send requests (see above) for the corresponding destinations.
44 /* .sp
45 /*	Delete empty per-destination logfiles that were not updated in
46 /*	\fB$fast_flush_purge_time\fR days.
47 /* .sp
48 /*	This request completes in the background.
49 /* .IP \fBpurge\fR
50 /*	Do a \fBrefresh\fR for all per-destination logfiles.
51 /* SECURITY
52 /* .ad
53 /* .fi
54 /*	The \fBflush\fR(8) server is not security-sensitive. It does not
55 /*	talk to the network, and it does not talk to local users.
56 /*	The fast flush server can run chrooted at fixed low privilege.
57 /* DIAGNOSTICS
58 /*	Problems and transactions are logged to \fBsyslogd\fR(8).
59 /* BUGS
60 /*	Fast flush logfiles are truncated only after a "send"
61 /*	request, not when mail is actually delivered, and therefore can
62 /*	accumulate outdated or redundant data. In order to maintain sanity,
63 /*	"refresh" must be executed periodically. This can
64 /*	be automated with a suitable wakeup timer setting in the
65 /*	\fBmaster.cf\fR configuration file.
66 /*
67 /*	Upon receipt of a request to deliver mail for an eligible
68 /*	destination, the \fBflush\fR(8) server requests delivery of all messages
69 /*	that are listed in that destination's logfile, regardless of the
70 /*	recipients of those messages. This is not an issue for mail
71 /*	that is sent to a \fBrelay_domains\fR destination because
72 /*	such mail typically only has recipients in one domain.
73 /* CONFIGURATION PARAMETERS
74 /* .ad
75 /* .fi
76 /*	Changes to \fBmain.cf\fR are picked up automatically as \fBflush\fR(8)
77 /*	processes run for only a limited amount of time. Use the command
78 /*	"\fBpostfix reload\fR" to speed up a change.
79 /*
80 /*	The text below provides only a parameter summary. See
81 /*	\fBpostconf\fR(5) for more details including examples.
82 /* .IP "\fBconfig_directory (see 'postconf -d' output)\fR"
83 /*	The default location of the Postfix main.cf and master.cf
84 /*	configuration files.
85 /* .IP "\fBdaemon_timeout (18000s)\fR"
86 /*	How much time a Postfix daemon process may take to handle a
87 /*	request before it is terminated by a built-in watchdog timer.
88 /* .IP "\fBfast_flush_domains ($relay_domains)\fR"
89 /*	Optional list of destinations that are eligible for per-destination
90 /*	logfiles with mail that is queued to those destinations.
91 /* .IP "\fBfast_flush_refresh_time (12h)\fR"
92 /*	The time after which a non-empty but unread per-destination "fast
93 /*	flush" logfile needs to be refreshed.
94 /* .IP "\fBfast_flush_purge_time (7d)\fR"
95 /*	The time after which an empty per-destination "fast flush" logfile
96 /*	is deleted.
97 /* .IP "\fBipc_timeout (3600s)\fR"
98 /*	The time limit for sending or receiving information over an internal
99 /*	communication channel.
100 /* .IP "\fBmax_idle (100s)\fR"
101 /*	The maximum amount of time that an idle Postfix daemon process waits
102 /*	for an incoming connection before terminating voluntarily.
103 /* .IP "\fBmax_use (100)\fR"
104 /*	The maximal number of incoming connections that a Postfix daemon
105 /*	process will service before terminating voluntarily.
106 /* .IP "\fBparent_domain_matches_subdomains (see 'postconf -d' output)\fR"
107 /*	A list of Postfix features where the pattern "example.com" also
108 /*	matches subdomains of example.com,
109 /*	instead of requiring an explicit ".example.com" pattern.
110 /* .IP "\fBprocess_id (read-only)\fR"
111 /*	The process ID of a Postfix command or daemon process.
112 /* .IP "\fBprocess_name (read-only)\fR"
113 /*	The process name of a Postfix command or daemon process.
114 /* .IP "\fBqueue_directory (see 'postconf -d' output)\fR"
115 /*	The location of the Postfix top-level queue directory.
116 /* .IP "\fBsyslog_facility (mail)\fR"
117 /*	The syslog facility of Postfix logging.
118 /* .IP "\fBsyslog_name (see 'postconf -d' output)\fR"
119 /*	The mail system name that is prepended to the process name in syslog
120 /*	records, so that "smtpd" becomes, for example, "postfix/smtpd".
121 /* FILES
122 /*	/var/spool/postfix/flush, "fast flush" logfiles.
123 /* SEE ALSO
124 /*	smtpd(8), SMTP server
125 /*	qmgr(8), queue manager
126 /*	postconf(5), configuration parameters
127 /*	master(5), generic daemon options
128 /*	master(8), process manager
129 /*	syslogd(8), system logging
130 /* README FILES
131 /* .ad
132 /* .fi
133 /*	Use "\fBpostconf readme_directory\fR" or
134 /*	"\fBpostconf html_directory\fR" to locate this information.
135 /* .na
136 /* .nf
137 /*	ETRN_README, Postfix ETRN howto
138 /* LICENSE
139 /* .ad
140 /* .fi
141 /*	The Secure Mailer license must be distributed with this software.
142 /* HISTORY
143 /*	This service was introduced with Postfix version 1.0.
144 /* AUTHOR(S)
145 /*	Wietse Venema
146 /*	IBM T.J. Watson Research
147 /*	P.O. Box 704
148 /*	Yorktown Heights, NY 10598, USA
149 /*
150 /*	Wietse Venema
151 /*	Google, Inc.
152 /*	111 8th Avenue
153 /*	New York, NY 10011, USA
154 /*--*/
155 
156 /* System library. */
157 
158 #include <sys_defs.h>
159 #include <sys/stat.h>
160 #include <sys/time.h>
161 #include <unistd.h>
162 #include <stdlib.h>
163 #include <utime.h>
164 #include <errno.h>
165 #include <ctype.h>
166 #include <string.h>
167 
168 /* Utility library. */
169 
170 #include <msg.h>
171 #include <events.h>
172 #include <vstream.h>
173 #include <vstring.h>
174 #include <vstring_vstream.h>
175 #include <myflock.h>
176 #include <htable.h>
177 #include <dict.h>
178 #include <scan_dir.h>
179 #include <stringops.h>
180 #include <safe_open.h>
181 #include <warn_stat.h>
182 #include <midna_domain.h>
183 
184 /* Global library. */
185 
186 #include <mail_params.h>
187 #include <mail_version.h>
188 #include <mail_queue.h>
189 #include <mail_proto.h>
190 #include <mail_flush.h>
191 #include <flush_clnt.h>
192 #include <mail_conf.h>
193 #include <mail_scan_dir.h>
194 #include <maps.h>
195 #include <domain_list.h>
196 #include <match_parent_style.h>
197 
198 /* Single server skeleton. */
199 
200 #include <mail_server.h>
201 
202 /* Application-specific. */
203 
204  /*
205   * Tunable parameters. The fast_flush_domains parameter is not defined here,
206   * because it is also used by the global library, and therefore is owned by
207   * the library.
208   */
209 int     var_fflush_refresh;
210 int     var_fflush_purge;
211 
212  /*
213   * Flush policy stuff.
214   */
215 static DOMAIN_LIST *flush_domains;
216 
217  /*
218   * Some hard-wired policy: how many queue IDs we remember while we're
219   * flushing a logfile (duplicate elimination). Sites with 1000+ emails
220   * queued should arrange for permanent connectivity.
221   */
222 #define FLUSH_DUP_FILTER_SIZE	10000	/* graceful degradation */
223 
224  /*
225   * Silly little macros.
226   */
227 #define STR(x)			vstring_str(x)
228 #define STREQ(x,y)		((x) == (y) || strcmp(x,y) == 0)
229 
230  /*
231   * Forward declarations resulting from breaking up routines according to
232   * name space: domain names versus safe-to-use pathnames.
233   */
234 static int flush_add_path(const char *, const char *);
235 static int flush_send_path(const char *, int);
236 
237  /*
238   * Do we only refresh the per-destination logfile, or do we really request
239   * mail delivery as if someone sent ETRN? If the latter, we must override
240   * information about unavailable hosts or unavailable transports.
241   *
242   * When selectively flushing deferred mail, we need to override the queue
243   * manager's "dead destination" information and unthrottle transports and
244   * queues. There are two options:
245   *
246   * - Unthrottle all transports and queues before we move mail to the incoming
247   * queue. This is less accurate, but has the advantage when flushing lots of
248   * mail, because Postfix can skip delivery of flushed messages after it
249   * discovers that a destination is (still) unavailable.
250   *
251   * - Unthrottle some transports and queues after the queue manager moves mail
252   * to the active queue. This is more accurate, but has the disadvantage when
253   * flushing lots of mail, because Postfix cannot skip delivery of flushed
254   * messages after it discovers that a destination is (still) unavailable.
255   */
256 #define REFRESH_ONLY		0
257 #define UNTHROTTLE_BEFORE	(1<<0)
258 #define UNTHROTTLE_AFTER	(1<<1)
259 
260 /* flush_site_to_path - convert domain or [addr] to harmless string */
261 
262 static VSTRING *flush_site_to_path(VSTRING *path, const char *site)
263 {
264     const char *ptr;
265     int     ch;
266 
267     /*
268      * Convert the name to ASCII, so that we don't to end up with non-ASCII
269      * names in the file system. The IDNA library functions fold case.
270      */
271 #ifndef NO_EAI
272     if ((site = midna_domain_to_ascii(site)) == 0)
273 	return (0);
274 #endif
275 
276     /*
277      * Allocate buffer on the fly; caller still needs to clean up.
278      */
279     if (path == 0)
280 	path = vstring_alloc(10);
281 
282     /*
283      * Mask characters that could upset the name-to-queue-file mapping code.
284      */
285     for (ptr = site; (ch = *(unsigned const char *) ptr) != 0; ptr++)
286 	if (ISALNUM(ch))
287 	    VSTRING_ADDCH(path, tolower(ch));
288 	else
289 	    VSTRING_ADDCH(path, '_');
290     VSTRING_TERMINATE(path);
291 
292     if (msg_verbose)
293 	msg_info("site %s to path %s", site, STR(path));
294 
295     return (path);
296 }
297 
298 /* flush_add_service - append queue ID to per-site fast flush logfile */
299 
300 static int flush_add_service(const char *site, const char *queue_id)
301 {
302     const char *myname = "flush_add_service";
303     VSTRING *site_path;
304     int     status;
305 
306     if (msg_verbose)
307 	msg_info("%s: site %s queue_id %s", myname, site, queue_id);
308 
309     /*
310      * If this site is not eligible for logging, deny the request.
311      */
312     if (domain_list_match(flush_domains, site) == 0)
313 	return (flush_domains->error ? FLUSH_STAT_FAIL : FLUSH_STAT_DENY);
314 
315     /*
316      * Map site to path and update log.
317      */
318     if ((site_path = flush_site_to_path((VSTRING *) 0, site)) == 0)
319 	return (FLUSH_STAT_DENY);
320     status = flush_add_path(STR(site_path), queue_id);
321     vstring_free(site_path);
322 
323     return (status);
324 }
325 
326 /* flush_add_path - add record to log */
327 
328 static int flush_add_path(const char *path, const char *queue_id)
329 {
330     const char *myname = "flush_add_path";
331     VSTREAM *log;
332 
333     /*
334      * Sanity check.
335      */
336     if (!mail_queue_id_ok(path))
337 	return (FLUSH_STAT_BAD);
338 
339     /*
340      * Open the logfile or bust.
341      */
342     if ((log = mail_queue_open(MAIL_QUEUE_FLUSH, path,
343 			       O_CREAT | O_APPEND | O_WRONLY, 0600)) == 0)
344 	msg_fatal("%s: open fast flush logfile %s: %m", myname, path);
345 
346     /*
347      * We must lock the logfile, so that we don't lose information due to
348      * concurrent access. If the lock takes too long, the Postfix watchdog
349      * will eventually take care of the problem, but it will take a while.
350      */
351     if (myflock(vstream_fileno(log), INTERNAL_LOCK, MYFLOCK_OP_EXCLUSIVE) < 0)
352 	msg_fatal("%s: lock fast flush logfile %s: %m", myname, path);
353 
354     /*
355      * Append the queue ID. With 15 bits of microsecond time, a queue ID is
356      * not recycled often enough for false hits to be a problem. If it does,
357      * then we could add other signature information, such as the file size
358      * in bytes.
359      */
360     vstream_fprintf(log, "%s\n", queue_id);
361     if (vstream_fflush(log))
362 	msg_warn("write fast flush logfile %s: %m", path);
363 
364     /*
365      * Clean up.
366      */
367     if (myflock(vstream_fileno(log), INTERNAL_LOCK, MYFLOCK_OP_NONE) < 0)
368 	msg_fatal("%s: unlock fast flush logfile %s: %m", myname, path);
369     if (vstream_fclose(log) != 0)
370 	msg_warn("write fast flush logfile %s: %m", path);
371 
372     return (FLUSH_STAT_OK);
373 }
374 
375 /* flush_send_service - flush mail queued for site */
376 
377 static int flush_send_service(const char *site, int how)
378 {
379     const char *myname = "flush_send_service";
380     VSTRING *site_path;
381     int     status;
382 
383     if (msg_verbose)
384 	msg_info("%s: site %s", myname, site);
385 
386     /*
387      * If this site is not eligible for logging, deny the request.
388      */
389     if (domain_list_match(flush_domains, site) == 0)
390 	return (flush_domains->error ? FLUSH_STAT_FAIL : FLUSH_STAT_DENY);
391 
392     /*
393      * Map site name to path name and flush the log.
394      */
395     if ((site_path = flush_site_to_path((VSTRING *) 0, site)) == 0)
396 	return (FLUSH_STAT_DENY);
397     status = flush_send_path(STR(site_path), how);
398     vstring_free(site_path);
399 
400     return (status);
401 }
402 
403 /* flush_one_file - move one queue file to incoming queue */
404 
405 static int flush_one_file(const char *queue_id, VSTRING *queue_file,
406 			          struct utimbuf * tbuf, int how)
407 {
408     const char *myname = "flush_one_file";
409     const char *queue_name;
410     const char *path;
411 
412     /*
413      * Some other instance of this program may flush some logfile and may
414      * just have moved this queue file to the incoming queue.
415      */
416     for (queue_name = MAIL_QUEUE_DEFERRED; /* see below */ ;
417 	 queue_name = MAIL_QUEUE_INCOMING) {
418 	path = mail_queue_path(queue_file, queue_name, queue_id);
419 	if (utime(path, tbuf) == 0)
420 	    break;
421 	if (errno != ENOENT)
422 	    msg_warn("%s: update %s time stamps: %m", myname, path);
423 	if (STREQ(queue_name, MAIL_QUEUE_INCOMING))
424 	    return (0);
425     }
426 
427     /*
428      * With the UNTHROTTLE_AFTER strategy, we leave it up to the queue
429      * manager to unthrottle transports and queues as it reads recipients
430      * from a queue file. We request this unthrottle operation by setting the
431      * group read permission bit.
432      *
433      * Note: we must avoid using chmod(). It is not only slower than fchmod()
434      * but it is also less secure. With chmod(), an attacker could repeatedly
435      * send requests to the flush server and trick it into changing
436      * permissions of non-queue files, by exploiting a race condition.
437      *
438      * We use safe_open() because we don't validate the file content before
439      * modifying the file status.
440      */
441     if (how & UNTHROTTLE_AFTER) {
442 	VSTRING *why;
443 	struct stat st;
444 	VSTREAM *fp;
445 
446 	for (why = vstring_alloc(1); /* see below */ ;
447 	     queue_name = MAIL_QUEUE_INCOMING,
448 	     path = mail_queue_path(queue_file, queue_name, queue_id)) {
449 	    if ((fp = safe_open(path, O_RDWR, 0, &st, -1, -1, why)) != 0)
450 		break;
451 	    if (errno != ENOENT)
452 		msg_warn("%s: open %s: %s", myname, path, STR(why));
453 	    if (errno != ENOENT || STREQ(queue_name, MAIL_QUEUE_INCOMING)) {
454 		vstring_free(why);
455 		return (0);
456 	    }
457 	}
458 	vstring_free(why);
459 	if ((st.st_mode & MAIL_QUEUE_STAT_READY) != MAIL_QUEUE_STAT_READY) {
460 	    (void) vstream_fclose(fp);
461 	    return (0);
462 	}
463 	if (fchmod(vstream_fileno(fp), st.st_mode | MAIL_QUEUE_STAT_UNTHROTTLE) < 0)
464 	    msg_warn("%s: fchmod %s: %m", myname, path);
465 	(void) vstream_fclose(fp);
466     }
467 
468     /*
469      * Move the file to the incoming queue, if it isn't already there.
470      */
471     if (STREQ(queue_name, MAIL_QUEUE_INCOMING) == 0
472 	&& mail_queue_rename(queue_id, queue_name, MAIL_QUEUE_INCOMING) < 0
473 	&& errno != ENOENT)
474 	msg_warn("%s: rename from %s to %s: %m",
475 		 path, queue_name, MAIL_QUEUE_INCOMING);
476 
477     /*
478      * If we got here, we achieved something, so let's claim succes.
479      */
480     return (1);
481 }
482 
483 /* flush_send_path - flush logfile file */
484 
485 static int flush_send_path(const char *path, int how)
486 {
487     const char *myname = "flush_send_path";
488     VSTRING *queue_id;
489     VSTRING *queue_file;
490     VSTREAM *log;
491     struct utimbuf tbuf;
492     static char qmgr_flush_trigger[] = {
493 	QMGR_REQ_FLUSH_DEAD,		/* flush dead site/transport cache */
494     };
495     static char qmgr_scan_trigger[] = {
496 	QMGR_REQ_SCAN_INCOMING,		/* scan incoming queue */
497     };
498     HTABLE *dup_filter;
499     int     count;
500 
501     /*
502      * Sanity check.
503      */
504     if (!mail_queue_id_ok(path))
505 	return (FLUSH_STAT_BAD);
506 
507     /*
508      * Open the logfile. If the file does not exist, then there is no queued
509      * mail for this destination.
510      */
511     if ((log = mail_queue_open(MAIL_QUEUE_FLUSH, path, O_RDWR, 0600)) == 0) {
512 	if (errno != ENOENT)
513 	    msg_fatal("%s: open fast flush logfile %s: %m", myname, path);
514 	return (FLUSH_STAT_OK);
515     }
516 
517     /*
518      * We must lock the logfile, so that we don't lose information when it is
519      * truncated. Unfortunately, this means that the file can be locked for a
520      * significant amount of time. If things really get stuck the Postfix
521      * watchdog will take care of it.
522      */
523     if (myflock(vstream_fileno(log), INTERNAL_LOCK, MYFLOCK_OP_EXCLUSIVE) < 0)
524 	msg_fatal("%s: lock fast flush logfile %s: %m", myname, path);
525 
526     /*
527      * With the UNTHROTTLE_BEFORE strategy, we ask the queue manager to
528      * unthrottle all transports and queues before we move a deferred queue
529      * file to the incoming queue. This minimizes a race condition where the
530      * queue manager seizes a queue file before it knows that we want to
531      * flush that message.
532      *
533      * This reduces the race condition time window to a very small amount (the
534      * flush server does not really know when the queue manager reads its
535      * command fifo). But there is a worse race, where the queue manager
536      * moves a deferred queue file to the active queue before we have a
537      * chance to expedite its delivery.
538      */
539     if (how & UNTHROTTLE_BEFORE)
540 	mail_trigger(MAIL_CLASS_PUBLIC, var_queue_service,
541 		     qmgr_flush_trigger, sizeof(qmgr_flush_trigger));
542 
543     /*
544      * This is the part that dominates running time: schedule the listed
545      * queue files for delivery by updating their file time stamps and by
546      * moving them from the deferred queue to the incoming queue. This should
547      * take no more than a couple seconds under normal conditions. Filter out
548      * duplicate queue file names to avoid hammering the file system, with
549      * some finite limit on the amount of memory that we are willing to
550      * sacrifice for duplicate filtering. Graceful degradation.
551      *
552      * By moving selected queue files from the deferred queue to the incoming
553      * queue we optimize for the case where most deferred mail is for other
554      * sites. If that assumption does not hold, i.e. all deferred mail is for
555      * the same site, then doing a "fast flush" will cost more disk I/O than
556      * a "slow flush" that delivers the entire deferred queue. This penalty
557      * is only temporary - it will go away after we unite the active queue
558      * and the incoming queue.
559      */
560     queue_id = vstring_alloc(10);
561     queue_file = vstring_alloc(10);
562     dup_filter = htable_create(10);
563     tbuf.actime = tbuf.modtime = event_time();
564     for (count = 0; vstring_get_nonl(queue_id, log) != VSTREAM_EOF; count++) {
565 	if (!mail_queue_id_ok(STR(queue_id))) {
566 	    msg_warn("bad queue id \"%.30s...\" in fast flush logfile %s",
567 		     STR(queue_id), path);
568 	    continue;
569 	}
570 	if (dup_filter->used >= FLUSH_DUP_FILTER_SIZE
571 	    || htable_find(dup_filter, STR(queue_id)) == 0) {
572 	    if (msg_verbose)
573 		msg_info("%s: logfile %s: update queue file %s time stamps",
574 			 myname, path, STR(queue_id));
575 	    if (dup_filter->used <= FLUSH_DUP_FILTER_SIZE)
576 		htable_enter(dup_filter, STR(queue_id), 0);
577 	    count += flush_one_file(STR(queue_id), queue_file, &tbuf, how);
578 	} else {
579 	    if (msg_verbose)
580 		msg_info("%s: logfile %s: skip queue file %s as duplicate",
581 			 myname, path, STR(queue_file));
582 	}
583     }
584     htable_free(dup_filter, (void (*) (void *)) 0);
585     vstring_free(queue_file);
586     vstring_free(queue_id);
587 
588     /*
589      * Truncate the fast flush log.
590      */
591     if (count > 0 && ftruncate(vstream_fileno(log), (off_t) 0) < 0)
592 	msg_fatal("%s: truncate fast flush logfile %s: %m", myname, path);
593 
594     /*
595      * Workaround for noatime mounts. Use futimes() if available.
596      */
597     (void) utimes(VSTREAM_PATH(log), (struct timeval *) 0);
598 
599     /*
600      * Request delivery and clean up.
601      */
602     if (myflock(vstream_fileno(log), INTERNAL_LOCK, MYFLOCK_OP_NONE) < 0)
603 	msg_fatal("%s: unlock fast flush logfile %s: %m", myname, path);
604     if (vstream_fclose(log) != 0)
605 	msg_warn("%s: read fast flush logfile %s: %m", myname, path);
606     if (count > 0) {
607 	if (msg_verbose)
608 	    msg_info("%s: requesting delivery for logfile %s", myname, path);
609 	mail_trigger(MAIL_CLASS_PUBLIC, var_queue_service,
610 		     qmgr_scan_trigger, sizeof(qmgr_scan_trigger));
611     }
612     return (FLUSH_STAT_OK);
613 }
614 
615 /* flush_send_file_service - flush one queue file */
616 
617 static int flush_send_file_service(const char *queue_id)
618 {
619     const char *myname = "flush_send_file_service";
620     VSTRING *queue_file;
621     struct utimbuf tbuf;
622     static char qmgr_scan_trigger[] = {
623 	QMGR_REQ_SCAN_INCOMING,		/* scan incoming queue */
624     };
625 
626     /*
627      * Sanity check.
628      */
629     if (!mail_queue_id_ok(queue_id))
630 	return (FLUSH_STAT_BAD);
631 
632     if (msg_verbose)
633 	msg_info("%s: requesting delivery for queue_id %s", myname, queue_id);
634 
635     queue_file = vstring_alloc(30);
636     tbuf.actime = tbuf.modtime = event_time();
637     if (flush_one_file(queue_id, queue_file, &tbuf, UNTHROTTLE_AFTER) > 0)
638 	mail_trigger(MAIL_CLASS_PUBLIC, var_queue_service,
639 		     qmgr_scan_trigger, sizeof(qmgr_scan_trigger));
640     vstring_free(queue_file);
641 
642     return (FLUSH_STAT_OK);
643 }
644 
645 /* flush_refresh_service - refresh logfiles beyond some age */
646 
647 static int flush_refresh_service(int max_age)
648 {
649     const char *myname = "flush_refresh_service";
650     SCAN_DIR *scan;
651     char   *site_path;
652     struct stat st;
653     VSTRING *path = vstring_alloc(10);
654 
655     scan = scan_dir_open(MAIL_QUEUE_FLUSH);
656     while ((site_path = mail_scan_dir_next(scan)) != 0) {
657 	if (!mail_queue_id_ok(site_path))
658 	    continue;				/* XXX grumble. */
659 	mail_queue_path(path, MAIL_QUEUE_FLUSH, site_path);
660 	if (stat(STR(path), &st) < 0) {
661 	    if (errno != ENOENT)
662 		msg_warn("%s: stat %s: %m", myname, STR(path));
663 	    else if (msg_verbose)
664 		msg_info("%s: %s: %m", myname, STR(path));
665 	    continue;
666 	}
667 	if (st.st_size == 0) {
668 	    if (st.st_mtime + var_fflush_purge < event_time()) {
669 		if (unlink(STR(path)) < 0)
670 		    msg_warn("remove logfile %s: %m", STR(path));
671 		else if (msg_verbose)
672 		    msg_info("%s: unlink %s, empty and unchanged for %d days",
673 			     myname, STR(path), var_fflush_purge / 86400);
674 	    } else if (msg_verbose)
675 		msg_info("%s: skip logfile %s - empty log", myname, site_path);
676 	} else if (st.st_atime + max_age < event_time()) {
677 	    if (msg_verbose)
678 		msg_info("%s: flush logfile %s", myname, site_path);
679 	    flush_send_path(site_path, REFRESH_ONLY);
680 	} else {
681 	    if (msg_verbose)
682 		msg_info("%s: skip logfile %s, unread for <%d hours(s) ",
683 			 myname, site_path, max_age / 3600);
684 	}
685     }
686     scan_dir_close(scan);
687     vstring_free(path);
688 
689     return (FLUSH_STAT_OK);
690 }
691 
692 /* flush_request_receive - receive request */
693 
694 static int flush_request_receive(VSTREAM *client_stream, VSTRING *request)
695 {
696     int     count;
697 
698     /*
699      * Kluge: choose the protocol depending on the request size.
700      */
701     if (read_wait(vstream_fileno(client_stream), var_ipc_timeout) < 0) {
702 	msg_warn("timeout while waiting for data from %s",
703 		 VSTREAM_PATH(client_stream));
704 	return (-1);
705     }
706     if ((count = peekfd(vstream_fileno(client_stream))) < 0) {
707 	msg_warn("cannot examine read buffer of %s: %m",
708 		 VSTREAM_PATH(client_stream));
709 	return (-1);
710     }
711 
712     /*
713      * Short request: master trigger. Use the string+null protocol.
714      */
715     if (count <= 2) {
716 	if (vstring_get_null(request, client_stream) == VSTREAM_EOF) {
717 	    msg_warn("end-of-input while reading request from %s: %m",
718 		     VSTREAM_PATH(client_stream));
719 	    return (-1);
720 	}
721     }
722 
723     /*
724      * Long request: real flush client. Use the attribute list protocol.
725      */
726     else {
727 	if (attr_scan(client_stream,
728 		      ATTR_FLAG_MORE | ATTR_FLAG_STRICT,
729 		      RECV_ATTR_STR(MAIL_ATTR_REQ, request),
730 		      ATTR_TYPE_END) != 1) {
731 	    return (-1);
732 	}
733     }
734     return (0);
735 }
736 
737 /* flush_service - perform service for client */
738 
739 static void flush_service(VSTREAM *client_stream, char *unused_service,
740 			          char **argv)
741 {
742     VSTRING *request = vstring_alloc(10);
743     VSTRING *site = 0;
744     VSTRING *queue_id = 0;
745     static char wakeup[] = {		/* master wakeup request */
746 	TRIGGER_REQ_WAKEUP,
747 	0,
748     };
749     int     status = FLUSH_STAT_BAD;
750 
751     /*
752      * Sanity check. This service takes no command-line arguments.
753      */
754     if (argv[0])
755 	msg_fatal("unexpected command-line argument: %s", argv[0]);
756 
757     /*
758      * This routine runs whenever a client connects to the UNIX-domain socket
759      * dedicated to the fast flush service. What we see below is a little
760      * protocol to (1) read a request from the client (the name of the site)
761      * and (2) acknowledge that we have received the request.
762      *
763      * All connection-management stuff is handled by the common code in
764      * single_server.c.
765      */
766     if (flush_request_receive(client_stream, request) == 0) {
767 	if (STREQ(STR(request), FLUSH_REQ_ADD)) {
768 	    site = vstring_alloc(10);
769 	    queue_id = vstring_alloc(10);
770 	    if (attr_scan(client_stream, ATTR_FLAG_STRICT,
771 			  RECV_ATTR_STR(MAIL_ATTR_SITE, site),
772 			  RECV_ATTR_STR(MAIL_ATTR_QUEUEID, queue_id),
773 			  ATTR_TYPE_END) == 2
774 		&& mail_queue_id_ok(STR(queue_id)))
775 		status = flush_add_service(STR(site), STR(queue_id));
776 	    attr_print(client_stream, ATTR_FLAG_NONE,
777 		       SEND_ATTR_INT(MAIL_ATTR_STATUS, status),
778 		       ATTR_TYPE_END);
779 	} else if (STREQ(STR(request), FLUSH_REQ_SEND_SITE)) {
780 	    site = vstring_alloc(10);
781 	    if (attr_scan(client_stream, ATTR_FLAG_STRICT,
782 			  RECV_ATTR_STR(MAIL_ATTR_SITE, site),
783 			  ATTR_TYPE_END) == 1)
784 		status = flush_send_service(STR(site), UNTHROTTLE_BEFORE);
785 	    attr_print(client_stream, ATTR_FLAG_NONE,
786 		       SEND_ATTR_INT(MAIL_ATTR_STATUS, status),
787 		       ATTR_TYPE_END);
788 	} else if (STREQ(STR(request), FLUSH_REQ_SEND_FILE)) {
789 	    queue_id = vstring_alloc(10);
790 	    if (attr_scan(client_stream, ATTR_FLAG_STRICT,
791 			  RECV_ATTR_STR(MAIL_ATTR_QUEUEID, queue_id),
792 			  ATTR_TYPE_END) == 1)
793 		status = flush_send_file_service(STR(queue_id));
794 	    attr_print(client_stream, ATTR_FLAG_NONE,
795 		       SEND_ATTR_INT(MAIL_ATTR_STATUS, status),
796 		       ATTR_TYPE_END);
797 	} else if (STREQ(STR(request), FLUSH_REQ_REFRESH)
798 		   || STREQ(STR(request), wakeup)) {
799 	    attr_print(client_stream, ATTR_FLAG_NONE,
800 		       SEND_ATTR_INT(MAIL_ATTR_STATUS, FLUSH_STAT_OK),
801 		       ATTR_TYPE_END);
802 	    vstream_fflush(client_stream);
803 	    (void) flush_refresh_service(var_fflush_refresh);
804 	} else if (STREQ(STR(request), FLUSH_REQ_PURGE)) {
805 	    attr_print(client_stream, ATTR_FLAG_NONE,
806 		       SEND_ATTR_INT(MAIL_ATTR_STATUS, FLUSH_STAT_OK),
807 		       ATTR_TYPE_END);
808 	    vstream_fflush(client_stream);
809 	    (void) flush_refresh_service(0);
810 	}
811     } else
812 	attr_print(client_stream, ATTR_FLAG_NONE,
813 		   SEND_ATTR_INT(MAIL_ATTR_STATUS, status),
814 		   ATTR_TYPE_END);
815     vstring_free(request);
816     if (site)
817 	vstring_free(site);
818     if (queue_id)
819 	vstring_free(queue_id);
820 }
821 
822 /* pre_jail_init - pre-jail initialization */
823 
824 static void pre_jail_init(char *unused_name, char **unused_argv)
825 {
826     flush_domains = domain_list_init(VAR_FFLUSH_DOMAINS, MATCH_FLAG_RETURN
827 				   | match_parent_style(VAR_FFLUSH_DOMAINS),
828 				     var_fflush_domains);
829 }
830 
831 MAIL_VERSION_STAMP_DECLARE;
832 
833 /* main - pass control to the single-threaded skeleton */
834 
835 int     main(int argc, char **argv)
836 {
837     static const CONFIG_TIME_TABLE time_table[] = {
838 	VAR_FFLUSH_REFRESH, DEF_FFLUSH_REFRESH, &var_fflush_refresh, 1, 0,
839 	VAR_FFLUSH_PURGE, DEF_FFLUSH_PURGE, &var_fflush_purge, 1, 0,
840 	0,
841     };
842 
843     /*
844      * Fingerprint executables and core dumps.
845      */
846     MAIL_VERSION_STAMP_ALLOCATE;
847 
848     single_server_main(argc, argv, flush_service,
849 		       CA_MAIL_SERVER_TIME_TABLE(time_table),
850 		       CA_MAIL_SERVER_PRE_INIT(pre_jail_init),
851 		       CA_MAIL_SERVER_UNLIMITED,
852 		       0);
853 }
854