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