7 /* skeleton triggered mail subsystem
9 /* #include <mail_server.h>
11 /* NORETURN trigger_server_main(argc, argv, service, key, value, ...)
14 /* void (*service)(char *buf, int len, char *service_name, char **argv);
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.
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.
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
42 /* The argv argument specifies command-line arguments left over
43 /* after options processing.
44 /* The \fBserver\fR argument provides the following information:
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
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
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
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
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
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
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.
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.
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".
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.
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.
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.
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.
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.
132 /* Problems and transactions are logged to \fBsyslogd\fR(8).
134 /* Works with FIFO-based services only.
136 /* master(8), master process
137 /* syslogd(8) system logging
141 /* The Secure Mailer license must be distributed with this software.
144 /* IBM T.J. Watson Research
146 /* Yorktown Heights, NY 10598, USA
149 /* System library. */
151 #include <sys_defs.h>
152 #include <sys/socket.h>
162 #ifdef STRCASECMP_IN_STRINGS_H
167 /* Utility library. */
170 #include <msg_syslog.h>
171 #include <msg_vstream.h>
172 #include <chroot_uid.h>
175 #include <msg_vstream.h>
176 #include <mymalloc.h>
179 #include <stringops.h>
180 #include <sane_accept.h>
182 #include <safe_open.h>
184 #include <watchdog.h>
185 #include <split_at.h>
187 /* Global library. */
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>
197 /* Process manager. */
199 #include "master_proto.h"
201 /* Application-specific */
203 #include "mail_server.h"
208 static int use_count
;
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;
221 /* trigger_server_exit - normal termination */
223 static NORETURN
trigger_server_exit(void)
225 if (trigger_server_onexit
)
226 trigger_server_onexit(trigger_server_name
, trigger_server_argv
);
230 /* trigger_server_abort - terminate after abnormal master exit */
232 static void trigger_server_abort(int unused_event
, char *unused_context
)
235 msg_info("master disconnect -- exiting");
236 trigger_server_exit();
239 /* trigger_server_timeout - idle time exceeded */
241 static void trigger_server_timeout(int unused_event
, char *unused_context
)
244 msg_info("idle timeout -- exiting");
245 trigger_server_exit();
248 /* trigger_server_wakeup - wake up application */
250 static void trigger_server_wakeup(int fd
)
252 char buf
[TRIGGER_BUF_SIZE
];
256 * Commit suicide when the master process disconnected from us. Don't
257 * drop the already accepted client request after "postfix reload"; that
260 if (master_notify(var_pid
, trigger_server_generation
, MASTER_STAT_TAKEN
) < 0)
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
);
274 /* trigger_server_accept_fifo - accept fifo client request */
276 static void trigger_server_accept_fifo(int unused_event
, char *context
)
278 const char *myname
= "trigger_server_accept_fifo";
279 int listen_fd
= CAST_CHAR_PTR_TO_INT(context
);
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");
287 msg_info("%s: trigger arrived", myname
);
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.
293 if (trigger_server_pre_accept
)
294 trigger_server_pre_accept(trigger_server_name
, trigger_server_argv
);
295 trigger_server_wakeup(listen_fd
);
298 /* trigger_server_accept_local - accept socket client request */
300 static void trigger_server_accept_local(int unused_event
, char *context
)
302 const char *myname
= "trigger_server_accept_local";
303 int listen_fd
= CAST_CHAR_PTR_TO_INT(context
);
308 msg_info("%s: trigger arrived", myname
);
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.
317 if (var_idle_limit
> 0)
318 time_left
= event_cancel_timer(trigger_server_timeout
, (char *) 0);
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");
329 msg_error("accept connection: %m");
331 event_request_timer(trigger_server_timeout
, (char *) 0, time_left
);
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
);
342 #ifdef MASTER_XPORT_NAME_PASS
344 /* trigger_server_accept_pass - accept descriptor */
346 static void trigger_server_accept_pass(int unused_event
, char *context
)
348 const char *myname
= "trigger_server_accept_pass";
349 int listen_fd
= CAST_CHAR_PTR_TO_INT(context
);
354 msg_info("%s: trigger arrived", myname
);
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.
363 if (var_idle_limit
> 0)
364 time_left
= event_cancel_timer(trigger_server_timeout
, (char *) 0);
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");
375 msg_error("accept connection: %m");
377 event_request_timer(trigger_server_timeout
, (char *) 0, time_left
);
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
);
390 /* trigger_server_main - the real main program */
392 NORETURN
trigger_server_main(int argc
, char **argv
, TRIGGER_SERVER_FN service
,...)
394 const char *myname
= "trigger_server_main";
399 char *service_name
= basename(argv
[0]);
403 int socket_count
= 1;
406 MAIL_SERVER_INIT_FN pre_init
= 0;
407 MAIL_SERVER_INIT_FN post_init
= 0;
408 MAIL_SERVER_LOOP_FN loop
= 0;
410 char buf
[TRIGGER_BUF_SIZE
];
421 int msg_vstream_needed
= 0;
422 int redo_syslog_init
= 0;
425 * Process environment options as early as we can.
427 if (getenv(CONF_ENV_VERB
))
429 if (getenv(CONF_ENV_DEBUG
))
433 * Don't die when a process goes away unexpectedly.
435 signal(SIGPIPE
, SIG_IGN
);
438 * Don't die for frivolous reasons.
441 signal(SIGXFSZ
, SIG_IGN
);
445 * May need this every now and then.
447 var_procname
= mystrdup(basename(argv
[0]));
448 set_mail_conf_str(VAR_PROCNAME
, var_procname
);
451 * Initialize logging and exit handler. Do the syslog first, so that its
452 * initialization completes before we enter the optional chroot jail.
454 msg_syslog_init(mail_task(var_procname
), LOG_PID
, LOG_FACILITY
);
456 msg_info("daemon started");
459 * Initialize from the configuration file. Allow command-line options to
460 * override compiled-in defaults or configured parameter values.
465 * Register dictionaries that use higher-level interfaces and protocols.
470 * Pick up policy settings from master process. Shut up error messages to
471 * stderr, because no-one is going to see them.
474 while ((c
= GETOPT(argc
, argv
, "cdDi:lm:n:o:s:St:uvVz")) > 0) {
486 mail_conf_update(VAR_MAX_IDLE
, optarg
);
492 mail_conf_update(VAR_MAX_USE
, optarg
);
495 service_name
= optarg
;
498 /* XXX Use split_nameval() */
499 oname
= mystrdup(optarg
);
500 if ((oval
= split_at(oname
, '=')) == 0)
502 mail_conf_update(oname
, oval
);
503 if (strcmp(oname
, VAR_SYSLOG_NAME
) == 0)
504 redo_syslog_init
= 1;
507 if ((socket_count
= atoi(optarg
)) <= 0)
508 msg_fatal("invalid socket_count: %s", optarg
);
523 if (++msg_vstream_needed
== 1)
524 msg_vstream_init(mail_task(var_procname
), VSTREAM_ERR
);
530 msg_fatal("invalid option: %c", c
);
536 * Initialize generic parameters.
539 if (redo_syslog_init
)
540 msg_syslog_init(mail_task(var_procname
), LOG_PID
, LOG_FACILITY
);
543 * If not connected to stdin, stdin must not be a terminal.
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");
551 * Application-specific initialization.
553 va_start(ap
, service
);
554 while ((key
= va_arg(ap
, int)) != 0) {
556 case MAIL_SERVER_INT_TABLE
:
557 get_mail_conf_int_table(va_arg(ap
, CONFIG_INT_TABLE
*));
559 case MAIL_SERVER_STR_TABLE
:
560 get_mail_conf_str_table(va_arg(ap
, CONFIG_STR_TABLE
*));
562 case MAIL_SERVER_BOOL_TABLE
:
563 get_mail_conf_bool_table(va_arg(ap
, CONFIG_BOOL_TABLE
*));
565 case MAIL_SERVER_TIME_TABLE
:
566 get_mail_conf_time_table(va_arg(ap
, CONFIG_TIME_TABLE
*));
568 case MAIL_SERVER_RAW_TABLE
:
569 get_mail_conf_raw_table(va_arg(ap
, CONFIG_RAW_TABLE
*));
571 case MAIL_SERVER_NINT_TABLE
:
572 get_mail_conf_nint_table(va_arg(ap
, CONFIG_NINT_TABLE
*));
574 case MAIL_SERVER_PRE_INIT
:
575 pre_init
= va_arg(ap
, MAIL_SERVER_INIT_FN
);
577 case MAIL_SERVER_POST_INIT
:
578 post_init
= va_arg(ap
, MAIL_SERVER_INIT_FN
);
580 case MAIL_SERVER_LOOP
:
581 loop
= va_arg(ap
, MAIL_SERVER_LOOP_FN
);
583 case MAIL_SERVER_EXIT
:
584 trigger_server_onexit
= va_arg(ap
, MAIL_SERVER_EXIT_FN
);
586 case MAIL_SERVER_PRE_ACCEPT
:
587 trigger_server_pre_accept
= va_arg(ap
, MAIL_SERVER_ACCEPT_FN
);
589 case MAIL_SERVER_IN_FLOW_DELAY
:
590 trigger_server_in_flow_delay
= 1;
592 case MAIL_SERVER_SOLITARY
:
593 if (stream
== 0 && !alone
)
594 msg_fatal("service %s requires a process limit of 1",
597 case MAIL_SERVER_UNLIMITED
:
598 if (stream
== 0 && !zerolimit
)
599 msg_fatal("service %s requires a process limit of 0",
602 case MAIL_SERVER_PRIVILEGED
:
604 msg_fatal("service %s requires privileged operation",
607 case MAIL_SERVER_WATCHDOG
:
608 trigger_server_watchdog
= *va_arg(ap
, int *);
611 msg_panic("%s: unknown argument type: %d", myname
, key
);
617 root_dir
= var_queue_dir
;
619 user_name
= var_mail_owner
;
622 * Can options be required?
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.
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.
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.
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
;
650 msg_fatal("unsupported transport type: %s", transport
);
654 * Retrieve process generation from environment.
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
);
661 msg_info("process generation: %s (%o)",
662 generation
, trigger_server_generation
);
666 * Optionally start the debugger on ourself.
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.
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
);
690 * Set up call-back info.
692 trigger_server_service
= service
;
693 trigger_server_name
= service_name
;
694 trigger_server_argv
= argv
+ optind
;
697 * Run pre-jail initialization.
699 if (chdir(var_queue_dir
) < 0)
700 msg_fatal("chdir(\"%s\"): %m", var_queue_dir
);
702 pre_init(trigger_server_name
, trigger_server_argv
);
705 * Optionally, restrict the damage that this process can do.
707 resolve_local_init();
709 chroot_uid(root_dir
, user_name
);
712 * Run post-jail initialization.
715 post_init(trigger_server_name
, trigger_server_argv
);
718 * Are we running as a one-shot server with the client connection on
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();
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.
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
);
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);
749 * The event loop, at last.
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");
758 watchdog_start(watchdog
);
759 delay
= loop
? loop(trigger_server_name
, trigger_server_argv
) : -1;
762 trigger_server_exit();