xref: /netbsd-src/external/ibm-public/postfix/dist/src/master/trigger_server.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: trigger_server.c,v 1.2 2017/02/14 01:16:45 christos Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	trigger_server 3
6 /* SUMMARY
7 /*	skeleton triggered mail subsystem
8 /* SYNOPSIS
9 /*	#include <mail_server.h>
10 /*
11 /*	NORETURN trigger_server_main(argc, argv, service, key, value, ...)
12 /*	int	argc;
13 /*	char	**argv;
14 /*	void	(*service)(char *buf, int len, char *service_name, char **argv);
15 /*	int	key;
16 /* DESCRIPTION
17 /*	This module implements a skeleton for triggered
18 /*	mail subsystems: mail subsystem programs that wake up on
19 /*	client request and perform some activity without further
20 /*	client interaction.  This module supports local IPC via FIFOs
21 /*	and via UNIX-domain sockets. The resulting program expects to be
22 /*	run from the \fBmaster\fR process.
23 /*
24 /*	trigger_server_main() is the skeleton entry point. It should be
25 /*	called from the application main program.  The skeleton does the
26 /*	generic command-line options processing, initialization of
27 /*	configurable parameters, and connection management.
28 /*	The skeleton never returns.
29 /*
30 /*	Arguments:
31 /* .IP "void (*service)(char *buf, int len, char *service_name, char **argv)"
32 /*	A pointer to a function that is called by the skeleton each time
33 /*	a client connects to the program's service port. The function is
34 /*	run after the program has irrevocably dropped its privileges.
35 /*	The buffer argument specifies the data read from the trigger port;
36 /*	this data corresponds to one or more trigger requests.
37 /*	The len argument specifies how much client data is available.
38 /*	The maximal size of the buffer is specified via the
39 /*	TRIGGER_BUF_SIZE manifest constant.
40 /*	The service name argument corresponds to the service name in the
41 /*	master.cf file.
42 /*	The argv argument specifies command-line arguments left over
43 /*	after options processing.
44 /*	The \fBserver\fR argument provides the following information:
45 /* .PP
46 /*	Optional arguments are specified as a null-terminated list
47 /*	with macros that have zero or more arguments:
48 /* .IP "CA_MAIL_SERVER_INT_TABLE(CONFIG_INT_TABLE *)"
49 /*	A table with configurable parameters, to be loaded from the
50 /*	global Postfix configuration file. Tables are loaded in the
51 /*	order as specified, and multiple instances of the same type
52 /*	are allowed.
53 /* .IP "CA_MAIL_SERVER_LONG_TABLE(CONFIG_LONG_TABLE *)"
54 /*	A table with configurable parameters, to be loaded from the
55 /*	global Postfix configuration file. Tables are loaded in the
56 /*	order as specified, and multiple instances of the same type
57 /*	are allowed.
58 /* .IP "CA_MAIL_SERVER_STR_TABLE(CONFIG_STR_TABLE *)"
59 /*	A table with configurable parameters, to be loaded from the
60 /*	global Postfix configuration file. Tables are loaded in the
61 /*	order as specified, and multiple instances of the same type
62 /*	are allowed.
63 /* .IP "CA_MAIL_SERVER_BOOL_TABLE(CONFIG_BOOL_TABLE *)"
64 /*	A table with configurable parameters, to be loaded from the
65 /*	global Postfix configuration file. Tables are loaded in the
66 /*	order as specified, and multiple instances of the same type
67 /*	are allowed.
68 /* .IP "CA_MAIL_SERVER_TIME_TABLE(CONFIG_TIME_TABLE *)"
69 /*	A table with configurable parameters, to be loaded from the
70 /*	global Postfix configuration file. Tables are loaded in the
71 /*	order as specified, and multiple instances of the same type
72 /*	are allowed.
73 /* .IP "CA_MAIL_SERVER_RAW_TABLE(CONFIG_RAW_TABLE *)"
74 /*	A table with configurable parameters, to be loaded from the
75 /*	global Postfix configuration file. Tables are loaded in the
76 /*	order as specified, and multiple instances of the same type
77 /*	are allowed. Raw parameters are not subjected to $name
78 /*	evaluation.
79 /* .IP "CA_MAIL_SERVER_NINT_TABLE(CONFIG_NINT_TABLE *)"
80 /*	A table with configurable parameters, to be loaded from the
81 /*	global Postfix configuration file. Tables are loaded in the
82 /*	order as specified, and multiple instances of the same type
83 /*	are allowed.
84 /* .IP "CA_MAIL_SERVER_NBOOL_TABLE(CONFIG_NBOOL_TABLE *)"
85 /*	A table with configurable parameters, to be loaded from the
86 /*	global Postfix configuration file. Tables are loaded in the
87 /*	order as specified, and multiple instances of the same type
88 /*	are allowed.
89 /* .IP "CA_MAIL_SERVER_PRE_INIT(void *(char *service_name, char **argv))"
90 /*	A pointer to a function that is called once
91 /*	by the skeleton after it has read the global configuration file
92 /*	and after it has processed command-line arguments, but before
93 /*	the skeleton has optionally relinquished the process privileges.
94 /* .sp
95 /*	Only the last instance of this parameter type is remembered.
96 /* .IP "CA_MAIL_SERVER_POST_INIT(void *(char *service_name, char **argv))"
97 /*	A pointer to a function that is called once
98 /*	by the skeleton after it has optionally relinquished the process
99 /*	privileges, but before servicing client connection requests.
100 /* .sp
101 /*	Only the last instance of this parameter type is remembered.
102 /* .IP "CA_MAIL_SERVER_LOOP(int *(char *service_name, char **argv))"
103 /*	A pointer to function that is executed from
104 /*	within the event loop, whenever an I/O or timer event has happened,
105 /*	or whenever nothing has happened for a specified amount of time.
106 /*	The result value of the function specifies how long to wait until
107 /*	the next event. Specify -1 to wait for "as long as it takes".
108 /* .sp
109 /*	Only the last instance of this parameter type is remembered.
110 /* .IP "CA_MAIL_SERVER_EXIT(void *(char *service_name, char **argv))"
111 /*	A pointer to function that is executed immediately before normal
112 /*	process termination.
113 /* .sp
114 /*	Only the last instance of this parameter type is remembered.
115 /* .IP "CA_MAIL_SERVER_PRE_ACCEPT(void *(char *service_name, char **argv))"
116 /*	Function to be executed prior to accepting a new request.
117 /* .sp
118 /*	Only the last instance of this parameter type is remembered.
119 /* .IP "CA_MAIL_SERVER_IN_FLOW_DELAY(none)"
120 /*	Pause $in_flow_delay seconds when no "mail flow control token"
121 /*	is available. A token is consumed for each connection request.
122 /* .IP CA_MAIL_SERVER_SOLITARY
123 /*	This service must be configured with process limit of 1.
124 /* .IP CA_MAIL_SERVER_UNLIMITED
125 /*	This service must be configured with process limit of 0.
126 /* .IP CA_MAIL_SERVER_PRIVILEGED
127 /*	This service must be configured as privileged.
128 /* .IP "CA_MAIL_SERVER_WATCHDOG(int *)"
129 /*	Override the default 1000s watchdog timeout. The value is
130 /*	used after command-line and main.cf file processing.
131 /* .IP "CA_MAIL_SERVER_BOUNCE_INIT(const char *, const char **)"
132 /*	Initialize the DSN filter for the bounce/defer service
133 /*	clients with the specified map source and map names.
134 /* .PP
135 /*	The var_use_limit variable limits the number of clients that
136 /*	a server can service before it commits suicide.
137 /*	This value is taken from the global \fBmain.cf\fR configuration
138 /*	file. Setting \fBvar_use_limit\fR to zero disables the client limit.
139 /*
140 /*	The var_idle_limit variable limits the time that a service
141 /*	receives no client connection requests before it commits suicide.
142 /*	This value is taken from the global \fBmain.cf\fR configuration
143 /*	file. Setting \fBvar_use_limit\fR to zero disables the idle limit.
144 /* DIAGNOSTICS
145 /*	Problems and transactions are logged to \fBsyslogd\fR(8).
146 /* BUGS
147 /*	Works with FIFO-based services only.
148 /* SEE ALSO
149 /*	master(8), master process
150 /*	syslogd(8) system logging
151 /* LICENSE
152 /* .ad
153 /* .fi
154 /*	The Secure Mailer license must be distributed with this software.
155 /* AUTHOR(S)
156 /*	Wietse Venema
157 /*	IBM T.J. Watson Research
158 /*	P.O. Box 704
159 /*	Yorktown Heights, NY 10598, USA
160 /*--*/
161 
162 /* System library. */
163 
164 #include <sys_defs.h>
165 #include <sys/socket.h>
166 #include <unistd.h>
167 #include <signal.h>
168 #include <syslog.h>
169 #include <stdlib.h>
170 #include <limits.h>
171 #include <string.h>
172 #include <errno.h>
173 #include <fcntl.h>
174 #include <stdarg.h>
175 #ifdef STRCASECMP_IN_STRINGS_H
176 #include <strings.h>
177 #endif
178 #include <time.h>
179 
180 /* Utility library. */
181 
182 #include <msg.h>
183 #include <msg_syslog.h>
184 #include <msg_vstream.h>
185 #include <chroot_uid.h>
186 #include <vstring.h>
187 #include <vstream.h>
188 #include <msg_vstream.h>
189 #include <mymalloc.h>
190 #include <events.h>
191 #include <iostuff.h>
192 #include <stringops.h>
193 #include <sane_accept.h>
194 #include <myflock.h>
195 #include <safe_open.h>
196 #include <listen.h>
197 #include <watchdog.h>
198 #include <split_at.h>
199 
200 /* Global library. */
201 
202 #include <mail_params.h>
203 #include <mail_task.h>
204 #include <debug_process.h>
205 #include <mail_conf.h>
206 #include <mail_dict.h>
207 #include <resolve_local.h>
208 #include <mail_flow.h>
209 #include <mail_version.h>
210 #include <bounce.h>
211 
212 /* Process manager. */
213 
214 #include "master_proto.h"
215 
216 /* Application-specific */
217 
218 #include "mail_server.h"
219 
220  /*
221   * Global state.
222   */
223 static int use_count;
224 
225 static TRIGGER_SERVER_FN trigger_server_service;
226 static char *trigger_server_name;
227 static char **trigger_server_argv;
228 static void (*trigger_server_accept) (int, void *);
229 static void (*trigger_server_onexit) (char *, char **);
230 static void (*trigger_server_pre_accept) (char *, char **);
231 static VSTREAM *trigger_server_lock;
232 static int trigger_server_in_flow_delay;
233 static unsigned trigger_server_generation;
234 static int trigger_server_watchdog = 1000;
235 
236 /* trigger_server_exit - normal termination */
237 
238 static NORETURN trigger_server_exit(void)
239 {
240     if (trigger_server_onexit)
241 	trigger_server_onexit(trigger_server_name, trigger_server_argv);
242     exit(0);
243 }
244 
245 /* trigger_server_abort - terminate after abnormal master exit */
246 
247 static void trigger_server_abort(int unused_event, void *unused_context)
248 {
249     if (msg_verbose)
250 	msg_info("master disconnect -- exiting");
251     trigger_server_exit();
252 }
253 
254 /* trigger_server_timeout - idle time exceeded */
255 
256 static void trigger_server_timeout(int unused_event, void *unused_context)
257 {
258     if (msg_verbose)
259 	msg_info("idle timeout -- exiting");
260     trigger_server_exit();
261 }
262 
263 /* trigger_server_wakeup - wake up application */
264 
265 static void trigger_server_wakeup(int fd)
266 {
267     char    buf[TRIGGER_BUF_SIZE];
268     ssize_t len;
269 
270     /*
271      * Commit suicide when the master process disconnected from us. Don't
272      * drop the already accepted client request after "postfix reload"; that
273      * would be rude.
274      */
275     if (master_notify(var_pid, trigger_server_generation, MASTER_STAT_TAKEN) < 0)
276 	 /* void */ ;
277     if (trigger_server_in_flow_delay && mail_flow_get(1) < 0)
278 	doze(var_in_flow_delay * 1000000);
279     if ((len = read(fd, buf, sizeof(buf))) >= 0)
280 	trigger_server_service(buf, len, trigger_server_name,
281 			       trigger_server_argv);
282     if (master_notify(var_pid, trigger_server_generation, MASTER_STAT_AVAIL) < 0)
283 	trigger_server_abort(EVENT_NULL_TYPE, EVENT_NULL_CONTEXT);
284     if (var_idle_limit > 0)
285 	event_request_timer(trigger_server_timeout, (void *) 0, var_idle_limit);
286     /* Avoid integer wrap-around in a persistent process.  */
287     if (use_count < INT_MAX)
288 	use_count++;
289 }
290 
291 /* trigger_server_accept_fifo - accept fifo client request */
292 
293 static void trigger_server_accept_fifo(int unused_event, void *context)
294 {
295     const char *myname = "trigger_server_accept_fifo";
296     int     listen_fd = CAST_ANY_PTR_TO_INT(context);
297 
298     if (trigger_server_lock != 0
299 	&& myflock(vstream_fileno(trigger_server_lock), INTERNAL_LOCK,
300 		   MYFLOCK_OP_NONE) < 0)
301 	msg_fatal("select unlock: %m");
302 
303     if (msg_verbose)
304 	msg_info("%s: trigger arrived", myname);
305 
306     /*
307      * Read whatever the other side wrote into the FIFO. The FIFO read end is
308      * non-blocking so we won't get stuck when multiple processes wake up.
309      */
310     if (trigger_server_pre_accept)
311 	trigger_server_pre_accept(trigger_server_name, trigger_server_argv);
312     trigger_server_wakeup(listen_fd);
313 }
314 
315 /* trigger_server_accept_local - accept socket client request */
316 
317 static void trigger_server_accept_local(int unused_event, void *context)
318 {
319     const char *myname = "trigger_server_accept_local";
320     int     listen_fd = CAST_ANY_PTR_TO_INT(context);
321     int     time_left = 0;
322     int     fd;
323 
324     if (msg_verbose)
325 	msg_info("%s: trigger arrived", myname);
326 
327     /*
328      * Read a message from a socket. Be prepared for accept() to fail because
329      * some other process already got the connection. The socket is
330      * non-blocking so we won't get stuck when multiple processes wake up.
331      * Don't get stuck when the client connects but sends no data. Restart
332      * the idle timer if this was a false alarm.
333      */
334     if (var_idle_limit > 0)
335 	time_left = event_cancel_timer(trigger_server_timeout, (void *) 0);
336 
337     if (trigger_server_pre_accept)
338 	trigger_server_pre_accept(trigger_server_name, trigger_server_argv);
339     fd = LOCAL_ACCEPT(listen_fd);
340     if (trigger_server_lock != 0
341 	&& myflock(vstream_fileno(trigger_server_lock), INTERNAL_LOCK,
342 		   MYFLOCK_OP_NONE) < 0)
343 	msg_fatal("select unlock: %m");
344     if (fd < 0) {
345 	if (errno != EAGAIN)
346 	    msg_error("accept connection: %m");
347 	if (time_left >= 0)
348 	    event_request_timer(trigger_server_timeout, (void *) 0, time_left);
349 	return;
350     }
351     close_on_exec(fd, CLOSE_ON_EXEC);
352     if (read_wait(fd, 10) == 0)
353 	trigger_server_wakeup(fd);
354     else if (time_left >= 0)
355 	event_request_timer(trigger_server_timeout, (void *) 0, time_left);
356     close(fd);
357 }
358 
359 #ifdef MASTER_XPORT_NAME_PASS
360 
361 /* trigger_server_accept_pass - accept descriptor */
362 
363 static void trigger_server_accept_pass(int unused_event, void *context)
364 {
365     const char *myname = "trigger_server_accept_pass";
366     int     listen_fd = CAST_ANY_PTR_TO_INT(context);
367     int     time_left = 0;
368     int     fd;
369 
370     if (msg_verbose)
371 	msg_info("%s: trigger arrived", myname);
372 
373     /*
374      * Read a message from a socket. Be prepared for accept() to fail because
375      * some other process already got the connection. The socket is
376      * non-blocking so we won't get stuck when multiple processes wake up.
377      * Don't get stuck when the client connects but sends no data. Restart
378      * the idle timer if this was a false alarm.
379      */
380     if (var_idle_limit > 0)
381 	time_left = event_cancel_timer(trigger_server_timeout, (void *) 0);
382 
383     if (trigger_server_pre_accept)
384 	trigger_server_pre_accept(trigger_server_name, trigger_server_argv);
385     fd = pass_accept(listen_fd);
386     if (trigger_server_lock != 0
387 	&& myflock(vstream_fileno(trigger_server_lock), INTERNAL_LOCK,
388 		   MYFLOCK_OP_NONE) < 0)
389 	msg_fatal("select unlock: %m");
390     if (fd < 0) {
391 	if (errno != EAGAIN)
392 	    msg_error("accept connection: %m");
393 	if (time_left >= 0)
394 	    event_request_timer(trigger_server_timeout, (void *) 0, time_left);
395 	return;
396     }
397     close_on_exec(fd, CLOSE_ON_EXEC);
398     if (read_wait(fd, 10) == 0)
399 	trigger_server_wakeup(fd);
400     else if (time_left >= 0)
401 	event_request_timer(trigger_server_timeout, (void *) 0, time_left);
402     close(fd);
403 }
404 
405 #endif
406 
407 /* trigger_server_main - the real main program */
408 
409 NORETURN trigger_server_main(int argc, char **argv, TRIGGER_SERVER_FN service,...)
410 {
411     const char *myname = "trigger_server_main";
412     char   *root_dir = 0;
413     char   *user_name = 0;
414     int     debug_me = 0;
415     int     daemon_mode = 1;
416     char   *service_name = basename(argv[0]);
417     VSTREAM *stream = 0;
418     int     delay;
419     int     c;
420     int     socket_count = 1;
421     int     fd;
422     va_list ap;
423     MAIL_SERVER_INIT_FN pre_init = 0;
424     MAIL_SERVER_INIT_FN post_init = 0;
425     MAIL_SERVER_LOOP_FN loop = 0;
426     int     key;
427     char    buf[TRIGGER_BUF_SIZE];
428     ssize_t len;
429     char   *transport = 0;
430     char   *lock_path;
431     VSTRING *why;
432     int     alone = 0;
433     int     zerolimit = 0;
434     WATCHDOG *watchdog;
435     char   *oname_val;
436     char   *oname;
437     char   *oval;
438     const char *err;
439     char   *generation;
440     int     msg_vstream_needed = 0;
441     int     redo_syslog_init = 0;
442     const char *dsn_filter_title;
443     const char **dsn_filter_maps;
444 
445     /*
446      * Process environment options as early as we can.
447      */
448     if (getenv(CONF_ENV_VERB))
449 	msg_verbose = 1;
450     if (getenv(CONF_ENV_DEBUG))
451 	debug_me = 1;
452 
453     /*
454      * Don't die when a process goes away unexpectedly.
455      */
456     signal(SIGPIPE, SIG_IGN);
457 
458     /*
459      * Don't die for frivolous reasons.
460      */
461 #ifdef SIGXFSZ
462     signal(SIGXFSZ, SIG_IGN);
463 #endif
464 
465     /*
466      * May need this every now and then.
467      */
468     var_procname = mystrdup(basename(argv[0]));
469     set_mail_conf_str(VAR_PROCNAME, var_procname);
470 
471     /*
472      * Initialize logging and exit handler. Do the syslog first, so that its
473      * initialization completes before we enter the optional chroot jail.
474      */
475     msg_syslog_init(mail_task(var_procname), LOG_PID, LOG_FACILITY);
476     if (msg_verbose)
477 	msg_info("daemon started");
478 
479     /*
480      * Check the Postfix library version as soon as we enable logging.
481      */
482     MAIL_VERSION_CHECK;
483 
484     /*
485      * Initialize from the configuration file. Allow command-line options to
486      * override compiled-in defaults or configured parameter values.
487      */
488     mail_conf_suck();
489 
490     /*
491      * After database open error, continue execution with reduced
492      * functionality.
493      */
494     dict_allow_surrogate = 1;
495 
496     /*
497      * Pick up policy settings from master process. Shut up error messages to
498      * stderr, because no-one is going to see them.
499      */
500     opterr = 0;
501     while ((c = GETOPT(argc, argv, "cdDi:lm:n:o:s:St:uvVz")) > 0) {
502 	switch (c) {
503 	case 'c':
504 	    root_dir = "setme";
505 	    break;
506 	case 'd':
507 	    daemon_mode = 0;
508 	    break;
509 	case 'D':
510 	    debug_me = 1;
511 	    break;
512 	case 'i':
513 	    mail_conf_update(VAR_MAX_IDLE, optarg);
514 	    break;
515 	case 'l':
516 	    alone = 1;
517 	    break;
518 	case 'm':
519 	    mail_conf_update(VAR_MAX_USE, optarg);
520 	    break;
521 	case 'n':
522 	    service_name = optarg;
523 	    break;
524 	case 'o':
525 	    oname_val = mystrdup(optarg);
526 	    if ((err = split_nameval(oname_val, &oname, &oval)) != 0)
527 		msg_fatal("invalid \"-o %s\" option value: %s", optarg, err);
528 	    mail_conf_update(oname, oval);
529 	    if (strcmp(oname, VAR_SYSLOG_NAME) == 0)
530 		redo_syslog_init = 1;
531 	    myfree(oname_val);
532 	    break;
533 	case 's':
534 	    if ((socket_count = atoi(optarg)) <= 0)
535 		msg_fatal("invalid socket_count: %s", optarg);
536 	    break;
537 	case 'S':
538 	    stream = VSTREAM_IN;
539 	    break;
540 	case 't':
541 	    transport = optarg;
542 	    break;
543 	case 'u':
544 	    user_name = "setme";
545 	    break;
546 	case 'v':
547 	    msg_verbose++;
548 	    break;
549 	case 'V':
550 	    if (++msg_vstream_needed == 1)
551 		msg_vstream_init(mail_task(var_procname), VSTREAM_ERR);
552 	    break;
553 	case 'z':
554 	    zerolimit = 1;
555 	    break;
556 	default:
557 	    msg_fatal("invalid option: %c", c);
558 	    break;
559 	}
560     }
561 
562     /*
563      * Initialize generic parameters.
564      */
565     mail_params_init();
566     if (redo_syslog_init)
567 	msg_syslog_init(mail_task(var_procname), LOG_PID, LOG_FACILITY);
568 
569     /*
570      * Register higher-level dictionaries and initialize the support for
571      * dynamically-loaded dictionarles.
572      */
573     mail_dict_init();
574 
575     /*
576      * If not connected to stdin, stdin must not be a terminal.
577      */
578     if (daemon_mode && stream == 0 && isatty(STDIN_FILENO)) {
579 	msg_vstream_init(var_procname, VSTREAM_ERR);
580 	msg_fatal("do not run this command by hand");
581     }
582 
583     /*
584      * Application-specific initialization.
585      */
586     va_start(ap, service);
587     while ((key = va_arg(ap, int)) != 0) {
588 	switch (key) {
589 	case MAIL_SERVER_INT_TABLE:
590 	    get_mail_conf_int_table(va_arg(ap, CONFIG_INT_TABLE *));
591 	    break;
592 	case MAIL_SERVER_LONG_TABLE:
593 	    get_mail_conf_long_table(va_arg(ap, CONFIG_LONG_TABLE *));
594 	    break;
595 	case MAIL_SERVER_STR_TABLE:
596 	    get_mail_conf_str_table(va_arg(ap, CONFIG_STR_TABLE *));
597 	    break;
598 	case MAIL_SERVER_BOOL_TABLE:
599 	    get_mail_conf_bool_table(va_arg(ap, CONFIG_BOOL_TABLE *));
600 	    break;
601 	case MAIL_SERVER_TIME_TABLE:
602 	    get_mail_conf_time_table(va_arg(ap, CONFIG_TIME_TABLE *));
603 	    break;
604 	case MAIL_SERVER_RAW_TABLE:
605 	    get_mail_conf_raw_table(va_arg(ap, CONFIG_RAW_TABLE *));
606 	    break;
607 	case MAIL_SERVER_NINT_TABLE:
608 	    get_mail_conf_nint_table(va_arg(ap, CONFIG_NINT_TABLE *));
609 	    break;
610 	case MAIL_SERVER_NBOOL_TABLE:
611 	    get_mail_conf_nbool_table(va_arg(ap, CONFIG_NBOOL_TABLE *));
612 	    break;
613 	case MAIL_SERVER_PRE_INIT:
614 	    pre_init = va_arg(ap, MAIL_SERVER_INIT_FN);
615 	    break;
616 	case MAIL_SERVER_POST_INIT:
617 	    post_init = va_arg(ap, MAIL_SERVER_INIT_FN);
618 	    break;
619 	case MAIL_SERVER_LOOP:
620 	    loop = va_arg(ap, MAIL_SERVER_LOOP_FN);
621 	    break;
622 	case MAIL_SERVER_EXIT:
623 	    trigger_server_onexit = va_arg(ap, MAIL_SERVER_EXIT_FN);
624 	    break;
625 	case MAIL_SERVER_PRE_ACCEPT:
626 	    trigger_server_pre_accept = va_arg(ap, MAIL_SERVER_ACCEPT_FN);
627 	    break;
628 	case MAIL_SERVER_IN_FLOW_DELAY:
629 	    trigger_server_in_flow_delay = 1;
630 	    break;
631 	case MAIL_SERVER_SOLITARY:
632 	    if (stream == 0 && !alone)
633 		msg_fatal("service %s requires a process limit of 1",
634 			  service_name);
635 	    break;
636 	case MAIL_SERVER_UNLIMITED:
637 	    if (stream == 0 && !zerolimit)
638 		msg_fatal("service %s requires a process limit of 0",
639 			  service_name);
640 	    break;
641 	case MAIL_SERVER_PRIVILEGED:
642 	    if (user_name)
643 		msg_fatal("service %s requires privileged operation",
644 			  service_name);
645 	    break;
646 	case MAIL_SERVER_WATCHDOG:
647 	    trigger_server_watchdog = *va_arg(ap, int *);
648 	    break;
649 	case MAIL_SERVER_BOUNCE_INIT:
650 	    dsn_filter_title = va_arg(ap, const char *);
651 	    dsn_filter_maps = va_arg(ap, const char **);
652 	    bounce_client_init(dsn_filter_title, *dsn_filter_maps);
653 	    break;
654 	default:
655 	    msg_panic("%s: unknown argument type: %d", myname, key);
656 	}
657     }
658     va_end(ap);
659 
660     if (root_dir)
661 	root_dir = var_queue_dir;
662     if (user_name)
663 	user_name = var_mail_owner;
664 
665     /*
666      * Can options be required?
667      *
668      * XXX Initially this code was implemented with UNIX-domain sockets, but
669      * Solaris <= 2.5 UNIX-domain sockets misbehave hopelessly when the
670      * client disconnects before the server has accepted the connection.
671      * Symptom: the server accept() fails with EPIPE or EPROTO, but the
672      * socket stays readable, so that the program goes into a wasteful loop.
673      *
674      * The initial fix was to use FIFOs, but those turn out to have their own
675      * problems, witness the workarounds in the fifo_listen() routine.
676      * Therefore we support both FIFOs and UNIX-domain sockets, so that the
677      * user can choose whatever works best.
678      *
679      * Well, I give up. Solaris UNIX-domain sockets still don't work properly,
680      * so it will have to limp along with a streams-specific alternative.
681      */
682     if (stream == 0) {
683 	if (transport == 0)
684 	    msg_fatal("no transport type specified");
685 	if (strcasecmp(transport, MASTER_XPORT_NAME_UNIX) == 0)
686 	    trigger_server_accept = trigger_server_accept_local;
687 	else if (strcasecmp(transport, MASTER_XPORT_NAME_FIFO) == 0)
688 	    trigger_server_accept = trigger_server_accept_fifo;
689 #ifdef MASTER_XPORT_NAME_PASS
690 	else if (strcasecmp(transport, MASTER_XPORT_NAME_PASS) == 0)
691 	    trigger_server_accept = trigger_server_accept_pass;
692 #endif
693 	else
694 	    msg_fatal("unsupported transport type: %s", transport);
695     }
696 
697     /*
698      * Retrieve process generation from environment.
699      */
700     if ((generation = getenv(MASTER_GEN_NAME)) != 0) {
701 	if (!alldig(generation))
702 	    msg_fatal("bad generation: %s", generation);
703 	OCTAL_TO_UNSIGNED(trigger_server_generation, generation);
704 	if (msg_verbose)
705 	    msg_info("process generation: %s (%o)",
706 		     generation, trigger_server_generation);
707     }
708 
709     /*
710      * Optionally start the debugger on ourself.
711      */
712     if (debug_me)
713 	debug_process();
714 
715     /*
716      * Traditionally, BSD select() can't handle multiple processes selecting
717      * on the same socket, and wakes up every process in select(). See TCP/IP
718      * Illustrated volume 2 page 532. We avoid select() collisions with an
719      * external lock file.
720      */
721     if (stream == 0 && !alone) {
722 	lock_path = concatenate(DEF_PID_DIR, "/", transport,
723 				".", service_name, (char *) 0);
724 	why = vstring_alloc(1);
725 	if ((trigger_server_lock = safe_open(lock_path, O_CREAT | O_RDWR, 0600,
726 				      (struct stat *) 0, -1, -1, why)) == 0)
727 	    msg_fatal("open lock file %s: %s", lock_path, vstring_str(why));
728 	close_on_exec(vstream_fileno(trigger_server_lock), CLOSE_ON_EXEC);
729 	myfree(lock_path);
730 	vstring_free(why);
731     }
732 
733     /*
734      * Set up call-back info.
735      */
736     trigger_server_service = service;
737     trigger_server_name = service_name;
738     trigger_server_argv = argv + optind;
739 
740     /*
741      * Run pre-jail initialization.
742      */
743     if (chdir(var_queue_dir) < 0)
744 	msg_fatal("chdir(\"%s\"): %m", var_queue_dir);
745     if (pre_init)
746 	pre_init(trigger_server_name, trigger_server_argv);
747 
748     /*
749      * Optionally, restrict the damage that this process can do.
750      */
751     resolve_local_init();
752     tzset();
753     chroot_uid(root_dir, user_name);
754 
755     /*
756      * Run post-jail initialization.
757      */
758     if (post_init)
759 	post_init(trigger_server_name, trigger_server_argv);
760 
761     /*
762      * Are we running as a one-shot server with the client connection on
763      * standard input?
764      */
765     if (stream != 0) {
766 	if ((len = read(vstream_fileno(stream), buf, sizeof(buf))) <= 0)
767 	    msg_fatal("read: %m");
768 	service(buf, len, trigger_server_name, trigger_server_argv);
769 	vstream_fflush(stream);
770 	trigger_server_exit();
771     }
772 
773     /*
774      * Running as a semi-resident server. Service connection requests.
775      * Terminate when we have serviced a sufficient number of clients, when
776      * no-one has been talking to us for a configurable amount of time, or
777      * when the master process terminated abnormally.
778      */
779     if (var_idle_limit > 0)
780 	event_request_timer(trigger_server_timeout, (void *) 0, var_idle_limit);
781     for (fd = MASTER_LISTEN_FD; fd < MASTER_LISTEN_FD + socket_count; fd++) {
782 	event_enable_read(fd, trigger_server_accept, CAST_INT_TO_VOID_PTR(fd));
783 	close_on_exec(fd, CLOSE_ON_EXEC);
784     }
785     event_enable_read(MASTER_STATUS_FD, trigger_server_abort, (void *) 0);
786     close_on_exec(MASTER_STATUS_FD, CLOSE_ON_EXEC);
787     close_on_exec(MASTER_FLOW_READ, CLOSE_ON_EXEC);
788     close_on_exec(MASTER_FLOW_WRITE, CLOSE_ON_EXEC);
789     watchdog = watchdog_create(trigger_server_watchdog,
790 			       (WATCHDOG_FN) 0, (void *) 0);
791 
792     /*
793      * The event loop, at last.
794      */
795     while (var_use_limit == 0 || use_count < var_use_limit) {
796 	if (trigger_server_lock != 0) {
797 	    watchdog_stop(watchdog);
798 	    if (myflock(vstream_fileno(trigger_server_lock), INTERNAL_LOCK,
799 			MYFLOCK_OP_EXCLUSIVE) < 0)
800 		msg_fatal("select lock: %m");
801 	}
802 	watchdog_start(watchdog);
803 	delay = loop ? loop(trigger_server_name, trigger_server_argv) : -1;
804 	event_loop(delay);
805     }
806     trigger_server_exit();
807 }
808