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