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