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