xref: /netbsd-src/external/ibm-public/postfix/dist/src/master/multi_server.c (revision a4ddc2c8fb9af816efe3b1c375a5530aef0e89e9)
1 /*	$NetBSD: multi_server.c,v 1.1.1.4 2013/01/02 18:59:01 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	multi_server 3
6 /* SUMMARY
7 /*	skeleton multi-threaded mail subsystem
8 /* SYNOPSIS
9 /*	#include <mail_server.h>
10 /*
11 /*	NORETURN multi_server_main(argc, argv, service, key, value, ...)
12 /*	int	argc;
13 /*	char	**argv;
14 /*	void	(*service)(VSTREAM *stream, char *service_name, char **argv);
15 /*	int	key;
16 /*
17 /*	void	multi_server_disconnect(stream)
18 /*	VSTREAM *stream;
19 /*
20 /*	void	multi_server_drain()
21 /* DESCRIPTION
22 /*	This module implements a skeleton for multi-threaded
23 /*	mail subsystems: mail subsystem programs that service multiple
24 /*	clients at the same time. The resulting program expects to be run
25 /*	from the \fBmaster\fR process.
26 /*
27 /*	multi_server_main() is the skeleton entry point. It should be
28 /*	called from the application main program.  The skeleton does all
29 /*	the generic command-line processing, initialization of
30 /*	configurable parameters, and connection management.
31 /*	The skeleton never returns.
32 /*
33 /*	Arguments:
34 /* .IP "void (*service)(VSTREAM *stream, char *service_name, char **argv)"
35 /*	A pointer to a function that is called by the skeleton each
36 /*	time a client sends data to the program's service port. The
37 /*	function is run after the program has optionally dropped its
38 /*	privileges. This function should not attempt to preserve state
39 /*	across calls. The stream initial state is non-blocking mode.
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 /* .PP
45 /*	Optional arguments are specified as a null-terminated (key, value)
46 /*	list. Keys and expected values are:
47 /* .IP "MAIL_SERVER_INT_TABLE (CONFIG_INT_TABLE *)"
48 /*	A table with configurable parameters, to be loaded from the
49 /*	global Postfix configuration file. Tables are loaded in the
50 /*	order as specified, and multiple instances of the same type
51 /*	are allowed.
52 /* .IP "MAIL_SERVER_LONG_TABLE (CONFIG_LONG_TABLE *)"
53 /*	A table with configurable parameters, to be loaded from the
54 /*	global Postfix configuration file. Tables are loaded in the
55 /*	order as specified, and multiple instances of the same type
56 /*	are allowed.
57 /* .IP "MAIL_SERVER_STR_TABLE (CONFIG_STR_TABLE *)"
58 /*	A table with configurable parameters, to be loaded from the
59 /*	global Postfix configuration file. Tables are loaded in the
60 /*	order as specified, and multiple instances of the same type
61 /*	are allowed.
62 /* .IP "MAIL_SERVER_BOOL_TABLE (CONFIG_BOOL_TABLE *)"
63 /*	A table with configurable parameters, to be loaded from the
64 /*	global Postfix configuration file. Tables are loaded in the
65 /*	order as specified, and multiple instances of the same type
66 /*	are allowed.
67 /* .IP "MAIL_SERVER_TIME_TABLE (CONFIG_TIME_TABLE *)"
68 /*	A table with configurable parameters, to be loaded from the
69 /*	global Postfix configuration file. Tables are loaded in the
70 /*	order as specified, and multiple instances of the same type
71 /*	are allowed.
72 /* .IP "MAIL_SERVER_RAW_TABLE (CONFIG_RAW_TABLE *)"
73 /*	A table with configurable parameters, to be loaded from the
74 /*	global Postfix configuration file. Tables are loaded in the
75 /*	order as specified, and multiple instances of the same type
76 /*	are allowed. Raw parameters are not subjected to $name
77 /*	evaluation.
78 /* .IP "MAIL_SERVER_NINT_TABLE (CONFIG_NINT_TABLE *)"
79 /*	A table with configurable parameters, to be loaded from the
80 /*	global Postfix configuration file. Tables are loaded in the
81 /*	order as specified, and multiple instances of the same type
82 /*	are allowed.
83 /* .IP "MAIL_SERVER_NBOOL_TABLE (CONFIG_NBOOL_TABLE *)"
84 /*	A table with configurable parameters, to be loaded from the
85 /*	global Postfix configuration file. Tables are loaded in the
86 /*	order as specified, and multiple instances of the same type
87 /*	are allowed.
88 /* .IP "MAIL_SERVER_PRE_INIT (void *(char *service_name, char **argv))"
89 /*	A pointer to a function that is called once
90 /*	by the skeleton after it has read the global configuration file
91 /*	and after it has processed command-line arguments, but before
92 /*	the skeleton has optionally relinquished the process privileges.
93 /* .sp
94 /*	Only the last instance of this parameter type is remembered.
95 /* .IP "MAIL_SERVER_POST_INIT (void *(char *service_name, char **argv))"
96 /*	A pointer to a function that is called once
97 /*	by the skeleton after it has optionally relinquished the process
98 /*	privileges, but before servicing client connection requests.
99 /* .sp
100 /*	Only the last instance of this parameter type is remembered.
101 /* .IP "MAIL_SERVER_LOOP (int *(char *service_name, char **argv))"
102 /*	A pointer to function that is executed from
103 /*	within the event loop, whenever an I/O or timer event has happened,
104 /*	or whenever nothing has happened for a specified amount of time.
105 /*	The result value of the function specifies how long to wait until
106 /*	the next event. Specify -1 to wait for "as long as it takes".
107 /* .sp
108 /*	Only the last instance of this parameter type is remembered.
109 /* .IP "MAIL_SERVER_EXIT (void *(char *service_name, char **argv))"
110 /*	A pointer to function that is executed immediately before normal
111 /*	process termination.
112 /* .IP "MAIL_SERVER_PRE_ACCEPT (void *(char *service_name, char **argv))"
113 /*	Function to be executed prior to accepting a new connection.
114 /* .sp
115 /*	Only the last instance of this parameter type is remembered.
116 /* .IP "MAIL_SERVER_PRE_DISCONN (VSTREAM *, char *service_name, char **argv)"
117 /*	A pointer to a function that is called
118 /*	by the multi_server_disconnect() function (see below).
119 /* .sp
120 /*	Only the last instance of this parameter type is remembered.
121 /* .IP "MAIL_SERVER_IN_FLOW_DELAY (none)"
122 /*	Pause $in_flow_delay seconds when no "mail flow control token"
123 /*	is available. A token is consumed for each connection request.
124 /* .IP MAIL_SERVER_SOLITARY
125 /*	This service must be configured with process limit of 1.
126 /* .IP MAIL_SERVER_UNLIMITED
127 /*	This service must be configured with process limit of 0.
128 /* .IP MAIL_SERVER_PRIVILEGED
129 /*	This service must be configured as privileged.
130 /* .PP
131 /*	multi_server_disconnect() should be called by the application
132 /*	to close a client connection.
133 /*
134 /*	multi_server_drain() should be called when the application
135 /*	no longer wishes to accept new client connections. Existing
136 /*	clients are handled in a background process, and the process
137 /*	terminates when the last client is disconnected. A non-zero
138 /*	result means this call should be tried again later.
139 /*
140 /*	The var_use_limit variable limits the number of clients that
141 /*	a server can service 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 client limit.
144 /*
145 /*	The var_idle_limit variable limits the time that a service
146 /*	receives no client connection requests before it commits suicide.
147 /*	This value is taken from the global \fBmain.cf\fR configuration
148 /*	file. Setting \fBvar_idle_limit\fR to zero disables the idle limit.
149 /* DIAGNOSTICS
150 /*	Problems and transactions are logged to \fBsyslogd\fR(8).
151 /* SEE ALSO
152 /*	master(8), master process
153 /*	syslogd(8) system logging
154 /* LICENSE
155 /* .ad
156 /* .fi
157 /*	The Secure Mailer license must be distributed with this software.
158 /* AUTHOR(S)
159 /*	Wietse Venema
160 /*	IBM T.J. Watson Research
161 /*	P.O. Box 704
162 /*	Yorktown Heights, NY 10598, USA
163 /*--*/
164 
165 /* System library. */
166 
167 #include <sys_defs.h>
168 #include <sys/socket.h>
169 #include <sys/time.h>			/* select() */
170 #include <unistd.h>
171 #include <signal.h>
172 #include <syslog.h>
173 #include <stdlib.h>
174 #include <limits.h>
175 #include <string.h>
176 #include <errno.h>
177 #include <fcntl.h>
178 #include <stdarg.h>
179 #ifdef STRCASECMP_IN_STRINGS_H
180 #include <strings.h>
181 #endif
182 #include <time.h>
183 
184 #ifdef USE_SYS_SELECT_H
185 #include <sys/select.h>			/* select() */
186 #endif
187 
188 /* Utility library. */
189 
190 #include <msg.h>
191 #include <msg_syslog.h>
192 #include <msg_vstream.h>
193 #include <chroot_uid.h>
194 #include <listen.h>
195 #include <events.h>
196 #include <vstring.h>
197 #include <vstream.h>
198 #include <msg_vstream.h>
199 #include <mymalloc.h>
200 #include <iostuff.h>
201 #include <stringops.h>
202 #include <sane_accept.h>
203 #include <myflock.h>
204 #include <safe_open.h>
205 #include <listen.h>
206 #include <watchdog.h>
207 #include <split_at.h>
208 
209 /* Global library. */
210 
211 #include <mail_task.h>
212 #include <debug_process.h>
213 #include <mail_params.h>
214 #include <mail_conf.h>
215 #include <mail_dict.h>
216 #include <timed_ipc.h>
217 #include <resolve_local.h>
218 #include <mail_flow.h>
219 #include <mail_version.h>
220 
221 /* Process manager. */
222 
223 #include "master_proto.h"
224 
225 /* Application-specific */
226 
227 #include "mail_server.h"
228 
229  /*
230   * Global state.
231   */
232 static int client_count;
233 static int use_count;
234 static int socket_count = 1;
235 
236 static void (*multi_server_service) (VSTREAM *, char *, char **);
237 static char *multi_server_name;
238 static char **multi_server_argv;
239 static void (*multi_server_accept) (int, char *);
240 static void (*multi_server_onexit) (char *, char **);
241 static void (*multi_server_pre_accept) (char *, char **);
242 static VSTREAM *multi_server_lock;
243 static int multi_server_in_flow_delay;
244 static unsigned multi_server_generation;
245 static void (*multi_server_pre_disconn) (VSTREAM *, char *, char **);
246 
247 /* multi_server_exit - normal termination */
248 
249 static NORETURN multi_server_exit(void)
250 {
251     if (multi_server_onexit)
252 	multi_server_onexit(multi_server_name, multi_server_argv);
253     exit(0);
254 }
255 
256 /* multi_server_abort - terminate after abnormal master exit */
257 
258 static void multi_server_abort(int unused_event, char *unused_context)
259 {
260     if (msg_verbose)
261 	msg_info("master disconnect -- exiting");
262     multi_server_exit();
263 }
264 
265 /* multi_server_timeout - idle time exceeded */
266 
267 static void multi_server_timeout(int unused_event, char *unused_context)
268 {
269     if (msg_verbose)
270 	msg_info("idle timeout -- exiting");
271     multi_server_exit();
272 }
273 
274 /*  multi_server_drain - stop accepting new clients */
275 
276 int     multi_server_drain(void)
277 {
278     const char *myname = "multi_server_drain";
279     int     fd;
280 
281     switch (fork()) {
282 	/* Try again later. */
283     case -1:
284 	return (-1);
285 	/* Finish existing clients in the background, then terminate. */
286     case 0:
287 	(void) msg_cleanup((MSG_CLEANUP_FN) 0);
288 	event_fork();
289 	for (fd = MASTER_LISTEN_FD; fd < MASTER_LISTEN_FD + socket_count; fd++) {
290 	    event_disable_readwrite(fd);
291 	    (void) close(fd);
292 	    /* Play safe - don't reuse this file number. */
293 	    if (DUP2(STDIN_FILENO, fd) < 0)
294 		msg_warn("%s: dup2(%d, %d): %m", myname, STDIN_FILENO, fd);
295 	}
296 	var_use_limit = 1;
297 	return (0);
298 	/* Let the master start a new process. */
299     default:
300 	exit(0);
301     }
302 }
303 
304 /* multi_server_disconnect - terminate client session */
305 
306 void    multi_server_disconnect(VSTREAM *stream)
307 {
308     if (msg_verbose)
309 	msg_info("connection closed fd %d", vstream_fileno(stream));
310     if (multi_server_pre_disconn)
311 	multi_server_pre_disconn(stream, multi_server_name, multi_server_argv);
312     event_disable_readwrite(vstream_fileno(stream));
313     (void) vstream_fclose(stream);
314     client_count--;
315     /* Avoid integer wrap-around in a persistent process.  */
316     if (use_count < INT_MAX)
317 	use_count++;
318     if (client_count == 0 && var_idle_limit > 0)
319 	event_request_timer(multi_server_timeout, (char *) 0, var_idle_limit);
320 }
321 
322 /* multi_server_execute - in case (char *) != (struct *) */
323 
324 static void multi_server_execute(int unused_event, char *context)
325 {
326     VSTREAM *stream = (VSTREAM *) context;
327 
328     if (multi_server_lock != 0
329 	&& myflock(vstream_fileno(multi_server_lock), INTERNAL_LOCK,
330 		   MYFLOCK_OP_NONE) < 0)
331 	msg_fatal("select unlock: %m");
332 
333     /*
334      * Do not bother the application when the client disconnected. Don't drop
335      * the already accepted client request after "postfix reload"; that would
336      * be rude.
337      */
338     if (peekfd(vstream_fileno(stream)) > 0) {
339 	if (master_notify(var_pid, multi_server_generation, MASTER_STAT_TAKEN) < 0)
340 	     /* void */ ;
341 	multi_server_service(stream, multi_server_name, multi_server_argv);
342 	if (master_notify(var_pid, multi_server_generation, MASTER_STAT_AVAIL) < 0)
343 	    multi_server_abort(EVENT_NULL_TYPE, EVENT_NULL_CONTEXT);
344     } else {
345 	multi_server_disconnect(stream);
346     }
347 }
348 
349 /* multi_server_enable_read - enable read events */
350 
351 static void multi_server_enable_read(int unused_event, char *context)
352 {
353     VSTREAM *stream = (VSTREAM *) context;
354 
355     event_enable_read(vstream_fileno(stream), multi_server_execute, (char *) stream);
356 }
357 
358 /* multi_server_wakeup - wake up application */
359 
360 static void multi_server_wakeup(int fd)
361 {
362     VSTREAM *stream;
363     char   *tmp;
364 
365 #if defined(F_DUPFD) && (EVENTS_STYLE != EVENTS_STYLE_SELECT)
366 #ifndef THRESHOLD_FD_WORKAROUND
367 #define THRESHOLD_FD_WORKAROUND 128
368 #endif
369     int     new_fd;
370 
371     /*
372      * Leave some handles < FD_SETSIZE for DBMS libraries, in the unlikely
373      * case of a multi-server with a thousand clients.
374      */
375     if (fd < THRESHOLD_FD_WORKAROUND) {
376 	if ((new_fd = fcntl(fd, F_DUPFD, THRESHOLD_FD_WORKAROUND)) < 0)
377 	    msg_fatal("fcntl F_DUPFD: %m");
378 	(void) close(fd);
379 	fd = new_fd;
380     }
381 #endif
382     if (msg_verbose)
383 	msg_info("connection established fd %d", fd);
384     non_blocking(fd, BLOCKING);
385     close_on_exec(fd, CLOSE_ON_EXEC);
386     client_count++;
387     stream = vstream_fdopen(fd, O_RDWR);
388     tmp = concatenate(multi_server_name, " socket", (char *) 0);
389     vstream_control(stream, VSTREAM_CTL_PATH, tmp, VSTREAM_CTL_END);
390     myfree(tmp);
391     timed_ipc_setup(stream);
392     if (multi_server_in_flow_delay && mail_flow_get(1) < 0)
393 	event_request_timer(multi_server_enable_read, (char *) stream,
394 			    var_in_flow_delay);
395     else
396 	multi_server_enable_read(0, (char *) stream);
397 }
398 
399 /* multi_server_accept_local - accept client connection request */
400 
401 static void multi_server_accept_local(int unused_event, char *context)
402 {
403     int     listen_fd = CAST_CHAR_PTR_TO_INT(context);
404     int     time_left = -1;
405     int     fd;
406 
407     /*
408      * Be prepared for accept() to fail because some other process already
409      * got the connection (the number of processes competing for clients is
410      * kept small, so this is not a "thundering herd" problem). If the
411      * accept() succeeds, be sure to disable non-blocking I/O, in order to
412      * minimize confusion.
413      */
414     if (client_count == 0 && var_idle_limit > 0)
415 	time_left = event_cancel_timer(multi_server_timeout, (char *) 0);
416 
417     if (multi_server_pre_accept)
418 	multi_server_pre_accept(multi_server_name, multi_server_argv);
419     fd = LOCAL_ACCEPT(listen_fd);
420     if (multi_server_lock != 0
421 	&& myflock(vstream_fileno(multi_server_lock), INTERNAL_LOCK,
422 		   MYFLOCK_OP_NONE) < 0)
423 	msg_fatal("select unlock: %m");
424     if (fd < 0) {
425 	if (errno != EAGAIN)
426 	    msg_error("accept connection: %m");
427 	if (time_left >= 0)
428 	    event_request_timer(multi_server_timeout, (char *) 0, time_left);
429 	return;
430     }
431     multi_server_wakeup(fd);
432 }
433 
434 #ifdef MASTER_XPORT_NAME_PASS
435 
436 /* multi_server_accept_pass - accept descriptor */
437 
438 static void multi_server_accept_pass(int unused_event, char *context)
439 {
440     int     listen_fd = CAST_CHAR_PTR_TO_INT(context);
441     int     time_left = -1;
442     int     fd;
443 
444     /*
445      * Be prepared for accept() to fail because some other process already
446      * got the connection (the number of processes competing for clients is
447      * kept small, so this is not a "thundering herd" problem). If the
448      * accept() succeeds, be sure to disable non-blocking I/O, in order to
449      * minimize confusion.
450      */
451     if (client_count == 0 && var_idle_limit > 0)
452 	time_left = event_cancel_timer(multi_server_timeout, (char *) 0);
453 
454     if (multi_server_pre_accept)
455 	multi_server_pre_accept(multi_server_name, multi_server_argv);
456     fd = PASS_ACCEPT(listen_fd);
457     if (multi_server_lock != 0
458 	&& myflock(vstream_fileno(multi_server_lock), INTERNAL_LOCK,
459 		   MYFLOCK_OP_NONE) < 0)
460 	msg_fatal("select unlock: %m");
461     if (fd < 0) {
462 	if (errno != EAGAIN)
463 	    msg_error("accept connection: %m");
464 	if (time_left >= 0)
465 	    event_request_timer(multi_server_timeout, (char *) 0, time_left);
466 	return;
467     }
468     multi_server_wakeup(fd);
469 }
470 
471 #endif
472 
473 /* multi_server_accept_inet - accept client connection request */
474 
475 static void multi_server_accept_inet(int unused_event, char *context)
476 {
477     int     listen_fd = CAST_CHAR_PTR_TO_INT(context);
478     int     time_left = -1;
479     int     fd;
480 
481     /*
482      * Be prepared for accept() to fail because some other process already
483      * got the connection (the number of processes competing for clients is
484      * kept small, so this is not a "thundering herd" problem). If the
485      * accept() succeeds, be sure to disable non-blocking I/O, in order to
486      * minimize confusion.
487      */
488     if (client_count == 0 && var_idle_limit > 0)
489 	time_left = event_cancel_timer(multi_server_timeout, (char *) 0);
490 
491     if (multi_server_pre_accept)
492 	multi_server_pre_accept(multi_server_name, multi_server_argv);
493     fd = inet_accept(listen_fd);
494     if (multi_server_lock != 0
495 	&& myflock(vstream_fileno(multi_server_lock), INTERNAL_LOCK,
496 		   MYFLOCK_OP_NONE) < 0)
497 	msg_fatal("select unlock: %m");
498     if (fd < 0) {
499 	if (errno != EAGAIN)
500 	    msg_error("accept connection: %m");
501 	if (time_left >= 0)
502 	    event_request_timer(multi_server_timeout, (char *) 0, time_left);
503 	return;
504     }
505     multi_server_wakeup(fd);
506 }
507 
508 /* multi_server_main - the real main program */
509 
510 NORETURN multi_server_main(int argc, char **argv, MULTI_SERVER_FN service,...)
511 {
512     const char *myname = "multi_server_main";
513     VSTREAM *stream = 0;
514     char   *root_dir = 0;
515     char   *user_name = 0;
516     int     debug_me = 0;
517     int     daemon_mode = 1;
518     char   *service_name = basename(argv[0]);
519     int     delay;
520     int     c;
521     int     fd;
522     va_list ap;
523     MAIL_SERVER_INIT_FN pre_init = 0;
524     MAIL_SERVER_INIT_FN post_init = 0;
525     MAIL_SERVER_LOOP_FN loop = 0;
526     int     key;
527     char   *transport = 0;
528 
529 #if 0
530     char   *lock_path;
531     VSTRING *why;
532 
533 #endif
534     int     alone = 0;
535     int     zerolimit = 0;
536     WATCHDOG *watchdog;
537     char   *oname_val;
538     char   *oname;
539     char   *oval;
540     const char *err;
541     char   *generation;
542     int     msg_vstream_needed = 0;
543     int     redo_syslog_init = 0;
544 
545     /*
546      * Process environment options as early as we can.
547      */
548     if (getenv(CONF_ENV_VERB))
549 	msg_verbose = 1;
550     if (getenv(CONF_ENV_DEBUG))
551 	debug_me = 1;
552 
553     /*
554      * Don't die when a process goes away unexpectedly.
555      */
556     signal(SIGPIPE, SIG_IGN);
557 
558     /*
559      * Don't die for frivolous reasons.
560      */
561 #ifdef SIGXFSZ
562     signal(SIGXFSZ, SIG_IGN);
563 #endif
564 
565     /*
566      * May need this every now and then.
567      */
568     var_procname = mystrdup(basename(argv[0]));
569     set_mail_conf_str(VAR_PROCNAME, var_procname);
570 
571     /*
572      * Initialize logging and exit handler. Do the syslog first, so that its
573      * initialization completes before we enter the optional chroot jail.
574      */
575     msg_syslog_init(mail_task(var_procname), LOG_PID, LOG_FACILITY);
576     if (msg_verbose)
577 	msg_info("daemon started");
578 
579     /*
580      * Check the Postfix library version as soon as we enable logging.
581      */
582     MAIL_VERSION_CHECK;
583 
584     /*
585      * Initialize from the configuration file. Allow command-line options to
586      * override compiled-in defaults or configured parameter values.
587      */
588     mail_conf_suck();
589 
590     /*
591      * Register dictionaries that use higher-level interfaces and protocols.
592      */
593     mail_dict_init();
594 
595     /*
596      * After database open error, continue execution with reduced
597      * functionality.
598      */
599     dict_allow_surrogate = 1;
600 
601     /*
602      * Pick up policy settings from master process. Shut up error messages to
603      * stderr, because no-one is going to see them.
604      */
605     opterr = 0;
606     while ((c = GETOPT(argc, argv, "cdDi:lm:n:o:s:St:uvVz")) > 0) {
607 	switch (c) {
608 	case 'c':
609 	    root_dir = "setme";
610 	    break;
611 	case 'd':
612 	    daemon_mode = 0;
613 	    break;
614 	case 'D':
615 	    debug_me = 1;
616 	    break;
617 	case 'i':
618 	    mail_conf_update(VAR_MAX_IDLE, optarg);
619 	    break;
620 	case 'l':
621 	    alone = 1;
622 	    break;
623 	case 'm':
624 	    mail_conf_update(VAR_MAX_USE, optarg);
625 	    break;
626 	case 'n':
627 	    service_name = optarg;
628 	    break;
629 	case 'o':
630 	    oname_val = mystrdup(optarg);
631 	    if ((err = split_nameval(oname_val, &oname, &oval)) != 0)
632 		msg_fatal("invalid \"-o %s\" option value: %s", optarg, err);
633 	    mail_conf_update(oname, oval);
634 	    if (strcmp(oname, VAR_SYSLOG_NAME) == 0)
635 		redo_syslog_init = 1;
636 	    myfree(oname_val);
637 	    break;
638 	case 's':
639 	    if ((socket_count = atoi(optarg)) <= 0)
640 		msg_fatal("invalid socket_count: %s", optarg);
641 	    break;
642 	case 'S':
643 	    stream = VSTREAM_IN;
644 	    break;
645 	case 'u':
646 	    user_name = "setme";
647 	    break;
648 	case 't':
649 	    transport = optarg;
650 	    break;
651 	case 'v':
652 	    msg_verbose++;
653 	    break;
654 	case 'V':
655 	    if (++msg_vstream_needed == 1)
656 		msg_vstream_init(mail_task(var_procname), VSTREAM_ERR);
657 	    break;
658 	case 'z':
659 	    zerolimit = 1;
660 	    break;
661 	default:
662 	    msg_fatal("invalid option: %c", c);
663 	    break;
664 	}
665     }
666 
667     /*
668      * Initialize generic parameters.
669      */
670     mail_params_init();
671     if (redo_syslog_init)
672 	msg_syslog_init(mail_task(var_procname), LOG_PID, LOG_FACILITY);
673 
674     /*
675      * If not connected to stdin, stdin must not be a terminal.
676      */
677     if (daemon_mode && stream == 0 && isatty(STDIN_FILENO)) {
678 	msg_vstream_init(var_procname, VSTREAM_ERR);
679 	msg_fatal("do not run this command by hand");
680     }
681 
682     /*
683      * Application-specific initialization.
684      */
685     va_start(ap, service);
686     while ((key = va_arg(ap, int)) != 0) {
687 	switch (key) {
688 	case MAIL_SERVER_INT_TABLE:
689 	    get_mail_conf_int_table(va_arg(ap, CONFIG_INT_TABLE *));
690 	    break;
691 	case MAIL_SERVER_LONG_TABLE:
692 	    get_mail_conf_long_table(va_arg(ap, CONFIG_LONG_TABLE *));
693 	    break;
694 	case MAIL_SERVER_STR_TABLE:
695 	    get_mail_conf_str_table(va_arg(ap, CONFIG_STR_TABLE *));
696 	    break;
697 	case MAIL_SERVER_BOOL_TABLE:
698 	    get_mail_conf_bool_table(va_arg(ap, CONFIG_BOOL_TABLE *));
699 	    break;
700 	case MAIL_SERVER_TIME_TABLE:
701 	    get_mail_conf_time_table(va_arg(ap, CONFIG_TIME_TABLE *));
702 	    break;
703 	case MAIL_SERVER_RAW_TABLE:
704 	    get_mail_conf_raw_table(va_arg(ap, CONFIG_RAW_TABLE *));
705 	    break;
706 	case MAIL_SERVER_NINT_TABLE:
707 	    get_mail_conf_nint_table(va_arg(ap, CONFIG_NINT_TABLE *));
708 	    break;
709 	case MAIL_SERVER_NBOOL_TABLE:
710 	    get_mail_conf_nbool_table(va_arg(ap, CONFIG_NBOOL_TABLE *));
711 	    break;
712 	case MAIL_SERVER_PRE_INIT:
713 	    pre_init = va_arg(ap, MAIL_SERVER_INIT_FN);
714 	    break;
715 	case MAIL_SERVER_POST_INIT:
716 	    post_init = va_arg(ap, MAIL_SERVER_INIT_FN);
717 	    break;
718 	case MAIL_SERVER_LOOP:
719 	    loop = va_arg(ap, MAIL_SERVER_LOOP_FN);
720 	    break;
721 	case MAIL_SERVER_EXIT:
722 	    multi_server_onexit = va_arg(ap, MAIL_SERVER_EXIT_FN);
723 	    break;
724 	case MAIL_SERVER_PRE_ACCEPT:
725 	    multi_server_pre_accept = va_arg(ap, MAIL_SERVER_ACCEPT_FN);
726 	    break;
727 	case MAIL_SERVER_PRE_DISCONN:
728 	    multi_server_pre_disconn = va_arg(ap, MAIL_SERVER_DISCONN_FN);
729 	    break;
730 	case MAIL_SERVER_IN_FLOW_DELAY:
731 	    multi_server_in_flow_delay = 1;
732 	    break;
733 	case MAIL_SERVER_SOLITARY:
734 	    if (stream == 0 && !alone)
735 		msg_fatal("service %s requires a process limit of 1",
736 			  service_name);
737 	    break;
738 	case MAIL_SERVER_UNLIMITED:
739 	    if (stream == 0 && !zerolimit)
740 		msg_fatal("service %s requires a process limit of 0",
741 			  service_name);
742 	    break;
743 	case MAIL_SERVER_PRIVILEGED:
744 	    if (user_name)
745 		msg_fatal("service %s requires privileged operation",
746 			  service_name);
747 	    break;
748 	default:
749 	    msg_panic("%s: unknown argument type: %d", myname, key);
750 	}
751     }
752     va_end(ap);
753 
754     if (root_dir)
755 	root_dir = var_queue_dir;
756     if (user_name)
757 	user_name = var_mail_owner;
758 
759     /*
760      * Can options be required?
761      */
762     if (stream == 0) {
763 	if (transport == 0)
764 	    msg_fatal("no transport type specified");
765 	if (strcasecmp(transport, MASTER_XPORT_NAME_INET) == 0)
766 	    multi_server_accept = multi_server_accept_inet;
767 	else if (strcasecmp(transport, MASTER_XPORT_NAME_UNIX) == 0)
768 	    multi_server_accept = multi_server_accept_local;
769 #ifdef MASTER_XPORT_NAME_PASS
770 	else if (strcasecmp(transport, MASTER_XPORT_NAME_PASS) == 0)
771 	    multi_server_accept = multi_server_accept_pass;
772 #endif
773 	else
774 	    msg_fatal("unsupported transport type: %s", transport);
775     }
776 
777     /*
778      * Retrieve process generation from environment.
779      */
780     if ((generation = getenv(MASTER_GEN_NAME)) != 0) {
781 	if (!alldig(generation))
782 	    msg_fatal("bad generation: %s", generation);
783 	OCTAL_TO_UNSIGNED(multi_server_generation, generation);
784 	if (msg_verbose)
785 	    msg_info("process generation: %s (%o)",
786 		     generation, multi_server_generation);
787     }
788 
789     /*
790      * Optionally start the debugger on ourself.
791      */
792     if (debug_me)
793 	debug_process();
794 
795     /*
796      * Traditionally, BSD select() can't handle multiple processes selecting
797      * on the same socket, and wakes up every process in select(). See TCP/IP
798      * Illustrated volume 2 page 532. We avoid select() collisions with an
799      * external lock file.
800      */
801 
802     /*
803      * XXX Can't compete for exclusive access to the listen socket because we
804      * also have to monitor existing client connections for service requests.
805      */
806 #if 0
807     if (stream == 0 && !alone) {
808 	lock_path = concatenate(DEF_PID_DIR, "/", transport,
809 				".", service_name, (char *) 0);
810 	why = vstring_alloc(1);
811 	if ((multi_server_lock = safe_open(lock_path, O_CREAT | O_RDWR, 0600,
812 				      (struct stat *) 0, -1, -1, why)) == 0)
813 	    msg_fatal("open lock file %s: %s", lock_path, vstring_str(why));
814 	close_on_exec(vstream_fileno(multi_server_lock), CLOSE_ON_EXEC);
815 	myfree(lock_path);
816 	vstring_free(why);
817     }
818 #endif
819 
820     /*
821      * Set up call-back info.
822      */
823     multi_server_service = service;
824     multi_server_name = service_name;
825     multi_server_argv = argv + optind;
826 
827     /*
828      * Run pre-jail initialization.
829      */
830     if (chdir(var_queue_dir) < 0)
831 	msg_fatal("chdir(\"%s\"): %m", var_queue_dir);
832     if (pre_init)
833 	pre_init(multi_server_name, multi_server_argv);
834 
835     /*
836      * Optionally, restrict the damage that this process can do.
837      */
838     resolve_local_init();
839     tzset();
840     chroot_uid(root_dir, user_name);
841 
842     /*
843      * Run post-jail initialization.
844      */
845     if (post_init)
846 	post_init(multi_server_name, multi_server_argv);
847 
848     /*
849      * Are we running as a one-shot server with the client connection on
850      * standard input? If so, make sure the output is written to stdout so as
851      * to satisfy common expectation.
852      */
853     if (stream != 0) {
854 	vstream_control(stream,
855 			VSTREAM_CTL_DOUBLE,
856 			VSTREAM_CTL_WRITE_FD, STDOUT_FILENO,
857 			VSTREAM_CTL_END);
858 	service(stream, multi_server_name, multi_server_argv);
859 	vstream_fflush(stream);
860 	multi_server_exit();
861     }
862 
863     /*
864      * Running as a semi-resident server. Service connection requests.
865      * Terminate when we have serviced a sufficient number of clients, when
866      * no-one has been talking to us for a configurable amount of time, or
867      * when the master process terminated abnormally.
868      */
869     if (var_idle_limit > 0)
870 	event_request_timer(multi_server_timeout, (char *) 0, var_idle_limit);
871     for (fd = MASTER_LISTEN_FD; fd < MASTER_LISTEN_FD + socket_count; fd++) {
872 	event_enable_read(fd, multi_server_accept, CAST_INT_TO_CHAR_PTR(fd));
873 	close_on_exec(fd, CLOSE_ON_EXEC);
874     }
875     event_enable_read(MASTER_STATUS_FD, multi_server_abort, (char *) 0);
876     close_on_exec(MASTER_STATUS_FD, CLOSE_ON_EXEC);
877     close_on_exec(MASTER_FLOW_READ, CLOSE_ON_EXEC);
878     close_on_exec(MASTER_FLOW_WRITE, CLOSE_ON_EXEC);
879     watchdog = watchdog_create(var_daemon_timeout, (WATCHDOG_FN) 0, (char *) 0);
880 
881     /*
882      * The event loop, at last.
883      */
884     while (var_use_limit == 0 || use_count < var_use_limit || client_count > 0) {
885 	if (multi_server_lock != 0) {
886 	    watchdog_stop(watchdog);
887 	    if (myflock(vstream_fileno(multi_server_lock), INTERNAL_LOCK,
888 			MYFLOCK_OP_EXCLUSIVE) < 0)
889 		msg_fatal("select lock: %m");
890 	}
891 	watchdog_start(watchdog);
892 	delay = loop ? loop(multi_server_name, multi_server_argv) : -1;
893 	event_loop(delay);
894     }
895     multi_server_exit();
896 }
897