xref: /netbsd-src/external/ibm-public/postfix/dist/src/master/trigger_server.c (revision 3816d47b2c42fcd6e549e3407f842a5b1a1d23ad)
1 /*	$NetBSD: trigger_server.c,v 1.1.1.1 2009/06/23 10:08:49 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	trigger_server 3
6 /* SUMMARY
7 /*	skeleton triggered mail subsystem
8 /* SYNOPSIS
9 /*	#include <mail_server.h>
10 /*
11 /*	NORETURN trigger_server_main(argc, argv, service, key, value, ...)
12 /*	int	argc;
13 /*	char	**argv;
14 /*	void	(*service)(char *buf, int len, char *service_name, char **argv);
15 /*	int	key;
16 /* DESCRIPTION
17 /*	This module implements a skeleton for triggered
18 /*	mail subsystems: mail subsystem programs that wake up on
19 /*	client request and perform some activity without further
20 /*	client interaction.  This module supports local IPC via FIFOs
21 /*	and via UNIX-domain sockets. The resulting program expects to be
22 /*	run from the \fBmaster\fR process.
23 /*
24 /*	trigger_server_main() is the skeleton entry point. It should be
25 /*	called from the application main program.  The skeleton does the
26 /*	generic command-line options processing, initialization of
27 /*	configurable parameters, and connection management.
28 /*	The skeleton never returns.
29 /*
30 /*	Arguments:
31 /* .IP "void (*service)(char *buf, int len, char *service_name, char **argv)"
32 /*	A pointer to a function that is called by the skeleton each time
33 /*	a client connects to the program's service port. The function is
34 /*	run after the program has irrevocably dropped its privileges.
35 /*	The buffer argument specifies the data read from the trigger port;
36 /*	this data corresponds to one or more trigger requests.
37 /*	The len argument specifies how much client data is available.
38 /*	The maximal size of the buffer is specified via the
39 /*	TRIGGER_BUF_SIZE manifest constant.
40 /*	The service name argument corresponds to the service name in the
41 /*	master.cf file.
42 /*	The argv argument specifies command-line arguments left over
43 /*	after options processing.
44 /*	The \fBserver\fR argument provides the following information:
45 /* .PP
46 /*	Optional arguments are specified as a null-terminated (key, value)
47 /*	list. Keys and expected values are:
48 /* .IP "MAIL_SERVER_INT_TABLE (CONFIG_INT_TABLE *)"
49 /*	A table with configurable parameters, to be loaded from the
50 /*	global Postfix configuration file. Tables are loaded in the
51 /*	order as specified, and multiple instances of the same type
52 /*	are allowed.
53 /* .IP "MAIL_SERVER_STR_TABLE (CONFIG_STR_TABLE *)"
54 /*	A table with configurable parameters, to be loaded from the
55 /*	global Postfix configuration file. Tables are loaded in the
56 /*	order as specified, and multiple instances of the same type
57 /*	are allowed.
58 /* .IP "MAIL_SERVER_BOOL_TABLE (CONFIG_BOOL_TABLE *)"
59 /*	A table with configurable parameters, to be loaded from the
60 /*	global Postfix configuration file. Tables are loaded in the
61 /*	order as specified, and multiple instances of the same type
62 /*	are allowed.
63 /* .IP "MAIL_SERVER_TIME_TABLE (CONFIG_TIME_TABLE *)"
64 /*	A table with configurable parameters, to be loaded from the
65 /*	global Postfix configuration file. Tables are loaded in the
66 /*	order as specified, and multiple instances of the same type
67 /*	are allowed.
68 /* .IP "MAIL_SERVER_RAW_TABLE (CONFIG_RAW_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. Raw parameters are not subjected to $name
73 /*	evaluation.
74 /* .IP "MAIL_SERVER_NINT_TABLE (CONFIG_NINT_TABLE *)"
75 /*	A table with configurable parameters, to be loaded from the
76 /*	global Postfix configuration file. Tables are loaded in the
77 /*	order as specified, and multiple instances of the same type
78 /*	are allowed.
79 /* .IP "MAIL_SERVER_PRE_INIT (void *(char *service_name, char **argv))"
80 /*	A pointer to a function that is called once
81 /*	by the skeleton after it has read the global configuration file
82 /*	and after it has processed command-line arguments, but before
83 /*	the skeleton has optionally relinquished the process privileges.
84 /* .sp
85 /*	Only the last instance of this parameter type is remembered.
86 /* .IP "MAIL_SERVER_POST_INIT (void *(char *service_name, char **argv))"
87 /*	A pointer to a function that is called once
88 /*	by the skeleton after it has optionally relinquished the process
89 /*	privileges, but before servicing client connection requests.
90 /* .sp
91 /*	Only the last instance of this parameter type is remembered.
92 /* .IP "MAIL_SERVER_LOOP (int *(char *service_name, char **argv))"
93 /*	A pointer to function that is executed from
94 /*	within the event loop, whenever an I/O or timer event has happened,
95 /*	or whenever nothing has happened for a specified amount of time.
96 /*	The result value of the function specifies how long to wait until
97 /*	the next event. Specify -1 to wait for "as long as it takes".
98 /* .sp
99 /*	Only the last instance of this parameter type is remembered.
100 /* .IP "MAIL_SERVER_EXIT (void *(char *service_name, char **argv))"
101 /*	A pointer to function that is executed immediately before normal
102 /*	process termination.
103 /* .sp
104 /*	Only the last instance of this parameter type is remembered.
105 /* .IP "MAIL_SERVER_PRE_ACCEPT (void *(char *service_name, char **argv))"
106 /*	Function to be executed prior to accepting a new request.
107 /* .sp
108 /*	Only the last instance of this parameter type is remembered.
109 /* .IP "MAIL_SERVER_IN_FLOW_DELAY (none)"
110 /*	Pause $in_flow_delay seconds when no "mail flow control token"
111 /*	is available. A token is consumed for each connection request.
112 /* .IP MAIL_SERVER_SOLITARY
113 /*	This service must be configured with process limit of 1.
114 /* .IP MAIL_SERVER_UNLIMITED
115 /*	This service must be configured with process limit of 0.
116 /* .IP MAIL_SERVER_PRIVILEGED
117 /*	This service must be configured as privileged.
118 /* .IP "MAIL_SERVER_WATCHDOG (int *)"
119 /*	Override the default 1000s watchdog timeout. The value is
120 /*	used after command-line and main.cf file processing.
121 /* .PP
122 /*	The var_use_limit variable limits the number of clients that
123 /*	a server can service before it commits suicide.
124 /*	This value is taken from the global \fBmain.cf\fR configuration
125 /*	file. Setting \fBvar_use_limit\fR to zero disables the client limit.
126 /*
127 /*	The var_idle_limit variable limits the time that a service
128 /*	receives no client connection requests before it commits suicide.
129 /*	This value is taken from the global \fBmain.cf\fR configuration
130 /*	file. Setting \fBvar_use_limit\fR to zero disables the idle limit.
131 /* DIAGNOSTICS
132 /*	Problems and transactions are logged to \fBsyslogd\fR(8).
133 /* BUGS
134 /*	Works with FIFO-based services only.
135 /* SEE ALSO
136 /*	master(8), master process
137 /*	syslogd(8) system logging
138 /* LICENSE
139 /* .ad
140 /* .fi
141 /*	The Secure Mailer license must be distributed with this software.
142 /* AUTHOR(S)
143 /*	Wietse Venema
144 /*	IBM T.J. Watson Research
145 /*	P.O. Box 704
146 /*	Yorktown Heights, NY 10598, USA
147 /*--*/
148 
149 /* System library. */
150 
151 #include <sys_defs.h>
152 #include <sys/socket.h>
153 #include <unistd.h>
154 #include <signal.h>
155 #include <syslog.h>
156 #include <stdlib.h>
157 #include <limits.h>
158 #include <string.h>
159 #include <errno.h>
160 #include <fcntl.h>
161 #include <stdarg.h>
162 #ifdef STRCASECMP_IN_STRINGS_H
163 #include <strings.h>
164 #endif
165 #include <time.h>
166 
167 /* Utility library. */
168 
169 #include <msg.h>
170 #include <msg_syslog.h>
171 #include <msg_vstream.h>
172 #include <chroot_uid.h>
173 #include <vstring.h>
174 #include <vstream.h>
175 #include <msg_vstream.h>
176 #include <mymalloc.h>
177 #include <events.h>
178 #include <iostuff.h>
179 #include <stringops.h>
180 #include <sane_accept.h>
181 #include <myflock.h>
182 #include <safe_open.h>
183 #include <listen.h>
184 #include <watchdog.h>
185 #include <split_at.h>
186 
187 /* Global library. */
188 
189 #include <mail_params.h>
190 #include <mail_task.h>
191 #include <debug_process.h>
192 #include <mail_conf.h>
193 #include <mail_dict.h>
194 #include <resolve_local.h>
195 #include <mail_flow.h>
196 
197 /* Process manager. */
198 
199 #include "master_proto.h"
200 
201 /* Application-specific */
202 
203 #include "mail_server.h"
204 
205  /*
206   * Global state.
207   */
208 static int use_count;
209 
210 static TRIGGER_SERVER_FN trigger_server_service;
211 static char *trigger_server_name;
212 static char **trigger_server_argv;
213 static void (*trigger_server_accept) (int, char *);
214 static void (*trigger_server_onexit) (char *, char **);
215 static void (*trigger_server_pre_accept) (char *, char **);
216 static VSTREAM *trigger_server_lock;
217 static int trigger_server_in_flow_delay;
218 static unsigned trigger_server_generation;
219 static int trigger_server_watchdog = 1000;
220 
221 /* trigger_server_exit - normal termination */
222 
223 static NORETURN trigger_server_exit(void)
224 {
225     if (trigger_server_onexit)
226 	trigger_server_onexit(trigger_server_name, trigger_server_argv);
227     exit(0);
228 }
229 
230 /* trigger_server_abort - terminate after abnormal master exit */
231 
232 static void trigger_server_abort(int unused_event, char *unused_context)
233 {
234     if (msg_verbose)
235 	msg_info("master disconnect -- exiting");
236     trigger_server_exit();
237 }
238 
239 /* trigger_server_timeout - idle time exceeded */
240 
241 static void trigger_server_timeout(int unused_event, char *unused_context)
242 {
243     if (msg_verbose)
244 	msg_info("idle timeout -- exiting");
245     trigger_server_exit();
246 }
247 
248 /* trigger_server_wakeup - wake up application */
249 
250 static void trigger_server_wakeup(int fd)
251 {
252     char    buf[TRIGGER_BUF_SIZE];
253     int     len;
254 
255     /*
256      * Commit suicide when the master process disconnected from us. Don't
257      * drop the already accepted client request after "postfix reload"; that
258      * would be rude.
259      */
260     if (master_notify(var_pid, trigger_server_generation, MASTER_STAT_TAKEN) < 0)
261 	 /* void */ ;
262     if (trigger_server_in_flow_delay && mail_flow_get(1) < 0)
263 	doze(var_in_flow_delay * 1000000);
264     if ((len = read(fd, buf, sizeof(buf))) >= 0)
265 	trigger_server_service(buf, len, trigger_server_name,
266 			       trigger_server_argv);
267     if (master_notify(var_pid, trigger_server_generation, MASTER_STAT_AVAIL) < 0)
268 	trigger_server_abort(EVENT_NULL_TYPE, EVENT_NULL_CONTEXT);
269     if (var_idle_limit > 0)
270 	event_request_timer(trigger_server_timeout, (char *) 0, var_idle_limit);
271     use_count++;
272 }
273 
274 /* trigger_server_accept_fifo - accept fifo client request */
275 
276 static void trigger_server_accept_fifo(int unused_event, char *context)
277 {
278     const char *myname = "trigger_server_accept_fifo";
279     int     listen_fd = CAST_CHAR_PTR_TO_INT(context);
280 
281     if (trigger_server_lock != 0
282 	&& myflock(vstream_fileno(trigger_server_lock), INTERNAL_LOCK,
283 		   MYFLOCK_OP_NONE) < 0)
284 	msg_fatal("select unlock: %m");
285 
286     if (msg_verbose)
287 	msg_info("%s: trigger arrived", myname);
288 
289     /*
290      * Read whatever the other side wrote into the FIFO. The FIFO read end is
291      * non-blocking so we won't get stuck when multiple processes wake up.
292      */
293     if (trigger_server_pre_accept)
294 	trigger_server_pre_accept(trigger_server_name, trigger_server_argv);
295     trigger_server_wakeup(listen_fd);
296 }
297 
298 /* trigger_server_accept_local - accept socket client request */
299 
300 static void trigger_server_accept_local(int unused_event, char *context)
301 {
302     const char *myname = "trigger_server_accept_local";
303     int     listen_fd = CAST_CHAR_PTR_TO_INT(context);
304     int     time_left = 0;
305     int     fd;
306 
307     if (msg_verbose)
308 	msg_info("%s: trigger arrived", myname);
309 
310     /*
311      * Read a message from a socket. Be prepared for accept() to fail because
312      * some other process already got the connection. The socket is
313      * non-blocking so we won't get stuck when multiple processes wake up.
314      * Don't get stuck when the client connects but sends no data. Restart
315      * the idle timer if this was a false alarm.
316      */
317     if (var_idle_limit > 0)
318 	time_left = event_cancel_timer(trigger_server_timeout, (char *) 0);
319 
320     if (trigger_server_pre_accept)
321 	trigger_server_pre_accept(trigger_server_name, trigger_server_argv);
322     fd = LOCAL_ACCEPT(listen_fd);
323     if (trigger_server_lock != 0
324 	&& myflock(vstream_fileno(trigger_server_lock), INTERNAL_LOCK,
325 		   MYFLOCK_OP_NONE) < 0)
326 	msg_fatal("select unlock: %m");
327     if (fd < 0) {
328 	if (errno != EAGAIN)
329 	    msg_error("accept connection: %m");
330 	if (time_left >= 0)
331 	    event_request_timer(trigger_server_timeout, (char *) 0, time_left);
332 	return;
333     }
334     close_on_exec(fd, CLOSE_ON_EXEC);
335     if (read_wait(fd, 10) == 0)
336 	trigger_server_wakeup(fd);
337     else if (time_left >= 0)
338 	event_request_timer(trigger_server_timeout, (char *) 0, time_left);
339     close(fd);
340 }
341 
342 #ifdef MASTER_XPORT_NAME_PASS
343 
344 /* trigger_server_accept_pass - accept descriptor */
345 
346 static void trigger_server_accept_pass(int unused_event, char *context)
347 {
348     const char *myname = "trigger_server_accept_pass";
349     int     listen_fd = CAST_CHAR_PTR_TO_INT(context);
350     int     time_left = 0;
351     int     fd;
352 
353     if (msg_verbose)
354 	msg_info("%s: trigger arrived", myname);
355 
356     /*
357      * Read a message from a socket. Be prepared for accept() to fail because
358      * some other process already got the connection. The socket is
359      * non-blocking so we won't get stuck when multiple processes wake up.
360      * Don't get stuck when the client connects but sends no data. Restart
361      * the idle timer if this was a false alarm.
362      */
363     if (var_idle_limit > 0)
364 	time_left = event_cancel_timer(trigger_server_timeout, (char *) 0);
365 
366     if (trigger_server_pre_accept)
367 	trigger_server_pre_accept(trigger_server_name, trigger_server_argv);
368     fd = PASS_ACCEPT(listen_fd);
369     if (trigger_server_lock != 0
370 	&& myflock(vstream_fileno(trigger_server_lock), INTERNAL_LOCK,
371 		   MYFLOCK_OP_NONE) < 0)
372 	msg_fatal("select unlock: %m");
373     if (fd < 0) {
374 	if (errno != EAGAIN)
375 	    msg_error("accept connection: %m");
376 	if (time_left >= 0)
377 	    event_request_timer(trigger_server_timeout, (char *) 0, time_left);
378 	return;
379     }
380     close_on_exec(fd, CLOSE_ON_EXEC);
381     if (read_wait(fd, 10) == 0)
382 	trigger_server_wakeup(fd);
383     else if (time_left >= 0)
384 	event_request_timer(trigger_server_timeout, (char *) 0, time_left);
385     close(fd);
386 }
387 
388 #endif
389 
390 /* trigger_server_main - the real main program */
391 
392 NORETURN trigger_server_main(int argc, char **argv, TRIGGER_SERVER_FN service,...)
393 {
394     const char *myname = "trigger_server_main";
395     char   *root_dir = 0;
396     char   *user_name = 0;
397     int     debug_me = 0;
398     int     daemon_mode = 1;
399     char   *service_name = basename(argv[0]);
400     VSTREAM *stream = 0;
401     int     delay;
402     int     c;
403     int     socket_count = 1;
404     int     fd;
405     va_list ap;
406     MAIL_SERVER_INIT_FN pre_init = 0;
407     MAIL_SERVER_INIT_FN post_init = 0;
408     MAIL_SERVER_LOOP_FN loop = 0;
409     int     key;
410     char    buf[TRIGGER_BUF_SIZE];
411     int     len;
412     char   *transport = 0;
413     char   *lock_path;
414     VSTRING *why;
415     int     alone = 0;
416     int     zerolimit = 0;
417     WATCHDOG *watchdog;
418     char   *oname;
419     char   *oval;
420     char   *generation;
421     int     msg_vstream_needed = 0;
422     int     redo_syslog_init = 0;
423 
424     /*
425      * Process environment options as early as we can.
426      */
427     if (getenv(CONF_ENV_VERB))
428 	msg_verbose = 1;
429     if (getenv(CONF_ENV_DEBUG))
430 	debug_me = 1;
431 
432     /*
433      * Don't die when a process goes away unexpectedly.
434      */
435     signal(SIGPIPE, SIG_IGN);
436 
437     /*
438      * Don't die for frivolous reasons.
439      */
440 #ifdef SIGXFSZ
441     signal(SIGXFSZ, SIG_IGN);
442 #endif
443 
444     /*
445      * May need this every now and then.
446      */
447     var_procname = mystrdup(basename(argv[0]));
448     set_mail_conf_str(VAR_PROCNAME, var_procname);
449 
450     /*
451      * Initialize logging and exit handler. Do the syslog first, so that its
452      * initialization completes before we enter the optional chroot jail.
453      */
454     msg_syslog_init(mail_task(var_procname), LOG_PID, LOG_FACILITY);
455     if (msg_verbose)
456 	msg_info("daemon started");
457 
458     /*
459      * Initialize from the configuration file. Allow command-line options to
460      * override compiled-in defaults or configured parameter values.
461      */
462     mail_conf_suck();
463 
464     /*
465      * Register dictionaries that use higher-level interfaces and protocols.
466      */
467     mail_dict_init();
468 
469     /*
470      * Pick up policy settings from master process. Shut up error messages to
471      * stderr, because no-one is going to see them.
472      */
473     opterr = 0;
474     while ((c = GETOPT(argc, argv, "cdDi:lm:n:o:s:St:uvVz")) > 0) {
475 	switch (c) {
476 	case 'c':
477 	    root_dir = "setme";
478 	    break;
479 	case 'd':
480 	    daemon_mode = 0;
481 	    break;
482 	case 'D':
483 	    debug_me = 1;
484 	    break;
485 	case 'i':
486 	    mail_conf_update(VAR_MAX_IDLE, optarg);
487 	    break;
488 	case 'l':
489 	    alone = 1;
490 	    break;
491 	case 'm':
492 	    mail_conf_update(VAR_MAX_USE, optarg);
493 	    break;
494 	case 'n':
495 	    service_name = optarg;
496 	    break;
497 	case 'o':
498 	    /* XXX Use split_nameval() */
499 	    oname = mystrdup(optarg);
500 	    if ((oval = split_at(oname, '=')) == 0)
501 		oval = "";
502 	    mail_conf_update(oname, oval);
503 	    if (strcmp(oname, VAR_SYSLOG_NAME) == 0)
504 		redo_syslog_init = 1;
505 	    break;
506 	case 's':
507 	    if ((socket_count = atoi(optarg)) <= 0)
508 		msg_fatal("invalid socket_count: %s", optarg);
509 	    break;
510 	case 'S':
511 	    stream = VSTREAM_IN;
512 	    break;
513 	case 't':
514 	    transport = optarg;
515 	    break;
516 	case 'u':
517 	    user_name = "setme";
518 	    break;
519 	case 'v':
520 	    msg_verbose++;
521 	    break;
522 	case 'V':
523 	    if (++msg_vstream_needed == 1)
524 		msg_vstream_init(mail_task(var_procname), VSTREAM_ERR);
525 	    break;
526 	case 'z':
527 	    zerolimit = 1;
528 	    break;
529 	default:
530 	    msg_fatal("invalid option: %c", c);
531 	    break;
532 	}
533     }
534 
535     /*
536      * Initialize generic parameters.
537      */
538     mail_params_init();
539     if (redo_syslog_init)
540 	msg_syslog_init(mail_task(var_procname), LOG_PID, LOG_FACILITY);
541 
542     /*
543      * If not connected to stdin, stdin must not be a terminal.
544      */
545     if (daemon_mode && stream == 0 && isatty(STDIN_FILENO)) {
546 	msg_vstream_init(var_procname, VSTREAM_ERR);
547 	msg_fatal("do not run this command by hand");
548     }
549 
550     /*
551      * Application-specific initialization.
552      */
553     va_start(ap, service);
554     while ((key = va_arg(ap, int)) != 0) {
555 	switch (key) {
556 	case MAIL_SERVER_INT_TABLE:
557 	    get_mail_conf_int_table(va_arg(ap, CONFIG_INT_TABLE *));
558 	    break;
559 	case MAIL_SERVER_STR_TABLE:
560 	    get_mail_conf_str_table(va_arg(ap, CONFIG_STR_TABLE *));
561 	    break;
562 	case MAIL_SERVER_BOOL_TABLE:
563 	    get_mail_conf_bool_table(va_arg(ap, CONFIG_BOOL_TABLE *));
564 	    break;
565 	case MAIL_SERVER_TIME_TABLE:
566 	    get_mail_conf_time_table(va_arg(ap, CONFIG_TIME_TABLE *));
567 	    break;
568 	case MAIL_SERVER_RAW_TABLE:
569 	    get_mail_conf_raw_table(va_arg(ap, CONFIG_RAW_TABLE *));
570 	    break;
571 	case MAIL_SERVER_NINT_TABLE:
572 	    get_mail_conf_nint_table(va_arg(ap, CONFIG_NINT_TABLE *));
573 	    break;
574 	case MAIL_SERVER_PRE_INIT:
575 	    pre_init = va_arg(ap, MAIL_SERVER_INIT_FN);
576 	    break;
577 	case MAIL_SERVER_POST_INIT:
578 	    post_init = va_arg(ap, MAIL_SERVER_INIT_FN);
579 	    break;
580 	case MAIL_SERVER_LOOP:
581 	    loop = va_arg(ap, MAIL_SERVER_LOOP_FN);
582 	    break;
583 	case MAIL_SERVER_EXIT:
584 	    trigger_server_onexit = va_arg(ap, MAIL_SERVER_EXIT_FN);
585 	    break;
586 	case MAIL_SERVER_PRE_ACCEPT:
587 	    trigger_server_pre_accept = va_arg(ap, MAIL_SERVER_ACCEPT_FN);
588 	    break;
589 	case MAIL_SERVER_IN_FLOW_DELAY:
590 	    trigger_server_in_flow_delay = 1;
591 	    break;
592 	case MAIL_SERVER_SOLITARY:
593 	    if (stream == 0 && !alone)
594 		msg_fatal("service %s requires a process limit of 1",
595 			  service_name);
596 	    break;
597 	case MAIL_SERVER_UNLIMITED:
598 	    if (stream == 0 && !zerolimit)
599 		msg_fatal("service %s requires a process limit of 0",
600 			  service_name);
601 	    break;
602 	case MAIL_SERVER_PRIVILEGED:
603 	    if (user_name)
604 		msg_fatal("service %s requires privileged operation",
605 			  service_name);
606 	    break;
607 	case MAIL_SERVER_WATCHDOG:
608 	    trigger_server_watchdog = *va_arg(ap, int *);
609 	    break;
610 	default:
611 	    msg_panic("%s: unknown argument type: %d", myname, key);
612 	}
613     }
614     va_end(ap);
615 
616     if (root_dir)
617 	root_dir = var_queue_dir;
618     if (user_name)
619 	user_name = var_mail_owner;
620 
621     /*
622      * Can options be required?
623      *
624      * XXX Initially this code was implemented with UNIX-domain sockets, but
625      * Solaris <= 2.5 UNIX-domain sockets misbehave hopelessly when the
626      * client disconnects before the server has accepted the connection.
627      * Symptom: the server accept() fails with EPIPE or EPROTO, but the
628      * socket stays readable, so that the program goes into a wasteful loop.
629      *
630      * The initial fix was to use FIFOs, but those turn out to have their own
631      * problems, witness the workarounds in the fifo_listen() routine.
632      * Therefore we support both FIFOs and UNIX-domain sockets, so that the
633      * user can choose whatever works best.
634      *
635      * Well, I give up. Solaris UNIX-domain sockets still don't work properly,
636      * so it will have to limp along with a streams-specific alternative.
637      */
638     if (stream == 0) {
639 	if (transport == 0)
640 	    msg_fatal("no transport type specified");
641 	if (strcasecmp(transport, MASTER_XPORT_NAME_UNIX) == 0)
642 	    trigger_server_accept = trigger_server_accept_local;
643 	else if (strcasecmp(transport, MASTER_XPORT_NAME_FIFO) == 0)
644 	    trigger_server_accept = trigger_server_accept_fifo;
645 #ifdef MASTER_XPORT_NAME_PASS
646 	else if (strcasecmp(transport, MASTER_XPORT_NAME_PASS) == 0)
647 	    trigger_server_accept = trigger_server_accept_pass;
648 #endif
649 	else
650 	    msg_fatal("unsupported transport type: %s", transport);
651     }
652 
653     /*
654      * Retrieve process generation from environment.
655      */
656     if ((generation = getenv(MASTER_GEN_NAME)) != 0) {
657 	if (!alldig(generation))
658 	    msg_fatal("bad generation: %s", generation);
659 	OCTAL_TO_UNSIGNED(trigger_server_generation, generation);
660 	if (msg_verbose)
661 	    msg_info("process generation: %s (%o)",
662 		     generation, trigger_server_generation);
663     }
664 
665     /*
666      * Optionally start the debugger on ourself.
667      */
668     if (debug_me)
669 	debug_process();
670 
671     /*
672      * Traditionally, BSD select() can't handle multiple processes selecting
673      * on the same socket, and wakes up every process in select(). See TCP/IP
674      * Illustrated volume 2 page 532. We avoid select() collisions with an
675      * external lock file.
676      */
677     if (stream == 0 && !alone) {
678 	lock_path = concatenate(DEF_PID_DIR, "/", transport,
679 				".", service_name, (char *) 0);
680 	why = vstring_alloc(1);
681 	if ((trigger_server_lock = safe_open(lock_path, O_CREAT | O_RDWR, 0600,
682 				      (struct stat *) 0, -1, -1, why)) == 0)
683 	    msg_fatal("open lock file %s: %s", lock_path, vstring_str(why));
684 	close_on_exec(vstream_fileno(trigger_server_lock), CLOSE_ON_EXEC);
685 	myfree(lock_path);
686 	vstring_free(why);
687     }
688 
689     /*
690      * Set up call-back info.
691      */
692     trigger_server_service = service;
693     trigger_server_name = service_name;
694     trigger_server_argv = argv + optind;
695 
696     /*
697      * Run pre-jail initialization.
698      */
699     if (chdir(var_queue_dir) < 0)
700 	msg_fatal("chdir(\"%s\"): %m", var_queue_dir);
701     if (pre_init)
702 	pre_init(trigger_server_name, trigger_server_argv);
703 
704     /*
705      * Optionally, restrict the damage that this process can do.
706      */
707     resolve_local_init();
708     tzset();
709     chroot_uid(root_dir, user_name);
710 
711     /*
712      * Run post-jail initialization.
713      */
714     if (post_init)
715 	post_init(trigger_server_name, trigger_server_argv);
716 
717     /*
718      * Are we running as a one-shot server with the client connection on
719      * standard input?
720      */
721     if (stream != 0) {
722 	if ((len = read(vstream_fileno(stream), buf, sizeof(buf))) <= 0)
723 	    msg_fatal("read: %m");
724 	service(buf, len, trigger_server_name, trigger_server_argv);
725 	vstream_fflush(stream);
726 	trigger_server_exit();
727     }
728 
729     /*
730      * Running as a semi-resident server. Service connection requests.
731      * Terminate when we have serviced a sufficient number of clients, when
732      * no-one has been talking to us for a configurable amount of time, or
733      * when the master process terminated abnormally.
734      */
735     if (var_idle_limit > 0)
736 	event_request_timer(trigger_server_timeout, (char *) 0, var_idle_limit);
737     for (fd = MASTER_LISTEN_FD; fd < MASTER_LISTEN_FD + socket_count; fd++) {
738 	event_enable_read(fd, trigger_server_accept, CAST_INT_TO_CHAR_PTR(fd));
739 	close_on_exec(fd, CLOSE_ON_EXEC);
740     }
741     event_enable_read(MASTER_STATUS_FD, trigger_server_abort, (char *) 0);
742     close_on_exec(MASTER_STATUS_FD, CLOSE_ON_EXEC);
743     close_on_exec(MASTER_FLOW_READ, CLOSE_ON_EXEC);
744     close_on_exec(MASTER_FLOW_WRITE, CLOSE_ON_EXEC);
745     watchdog = watchdog_create(trigger_server_watchdog,
746 			       (WATCHDOG_FN) 0, (char *) 0);
747 
748     /*
749      * The event loop, at last.
750      */
751     while (var_use_limit == 0 || use_count < var_use_limit) {
752 	if (trigger_server_lock != 0) {
753 	    watchdog_stop(watchdog);
754 	    if (myflock(vstream_fileno(trigger_server_lock), INTERNAL_LOCK,
755 			MYFLOCK_OP_EXCLUSIVE) < 0)
756 		msg_fatal("select lock: %m");
757 	}
758 	watchdog_start(watchdog);
759 	delay = loop ? loop(trigger_server_name, trigger_server_argv) : -1;
760 	event_loop(delay);
761     }
762     trigger_server_exit();
763 }
764