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