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