7 /* skeleton single-threaded mail subsystem
9 /* #include <mail_server.h>
11 /* NORETURN single_server_main(argc, argv, service, key, value, ...)
14 /* void (*service)(VSTREAM *stream, char *service_name, char **argv);
17 /* This module implements a skeleton for single-threaded
18 /* mail subsystems: mail subsystem programs that service one
19 /* client at a time. The resulting program expects to be run
20 /* from the \fBmaster\fR process.
22 /* single_server_main() is the skeleton entry point. It should be
23 /* called from the application main program. The skeleton does the
24 /* generic command-line options processing, initialization of
25 /* configurable parameters, and connection management.
26 /* The skeleton never returns.
29 /* .IP "void (*service)(VSTREAM *fp, char *service_name, char **argv)"
30 /* A pointer to a function that is called by the skeleton each time
31 /* a client connects to the program's service port. The function is
32 /* run after the program has irrevocably dropped its privileges.
33 /* The stream initial state is non-blocking mode.
34 /* The service name argument corresponds to the service name in the
36 /* The argv argument specifies command-line arguments left over
37 /* after options processing.
39 /* Optional arguments are specified as a null-terminated (key, value)
40 /* list. Keys and expected values are:
41 /* .IP "MAIL_SERVER_INT_TABLE (CONFIG_INT_TABLE *)"
42 /* A table with configurable parameters, to be loaded from the
43 /* global Postfix configuration file. Tables are loaded in the
44 /* order as specified, and multiple instances of the same type
46 /* .IP "MAIL_SERVER_STR_TABLE (CONFIG_STR_TABLE *)"
47 /* A table with configurable parameters, to be loaded from the
48 /* global Postfix configuration file. Tables are loaded in the
49 /* order as specified, and multiple instances of the same type
51 /* .IP "MAIL_SERVER_BOOL_TABLE (CONFIG_BOOL_TABLE *)"
52 /* A table with configurable parameters, to be loaded from the
53 /* global Postfix configuration file. Tables are loaded in the
54 /* order as specified, and multiple instances of the same type
56 /* .IP "MAIL_SERVER_TIME_TABLE (CONFIG_TIME_TABLE *)"
57 /* A table with configurable parameters, to be loaded from the
58 /* global Postfix configuration file. Tables are loaded in the
59 /* order as specified, and multiple instances of the same type
61 /* .IP "MAIL_SERVER_RAW_TABLE (CONFIG_RAW_TABLE *)"
62 /* A table with configurable parameters, to be loaded from the
63 /* global Postfix configuration file. Tables are loaded in the
64 /* order as specified, and multiple instances of the same type
65 /* are allowed. Raw parameters are not subjected to $name
67 /* .IP "MAIL_SERVER_NINT_TABLE (CONFIG_NINT_TABLE *)"
68 /* A table with configurable parameters, to be loaded from the
69 /* global Postfix configuration file. Tables are loaded in the
70 /* order as specified, and multiple instances of the same type
72 /* .IP "MAIL_SERVER_PRE_INIT (void *(char *service_name, char **argv))"
73 /* A pointer to a function that is called once
74 /* by the skeleton after it has read the global configuration file
75 /* and after it has processed command-line arguments, but before
76 /* the skeleton has optionally relinquished the process privileges.
78 /* Only the last instance of this parameter type is remembered.
79 /* .IP "MAIL_SERVER_POST_INIT (void *(char *service_name, char **argv))"
80 /* A pointer to a function that is called once
81 /* by the skeleton after it has optionally relinquished the process
82 /* privileges, but before servicing client connection requests.
84 /* Only the last instance of this parameter type is remembered.
85 /* .IP "MAIL_SERVER_LOOP (int *(char *service_name, char **argv))"
86 /* A pointer to function that is executed from
87 /* within the event loop, whenever an I/O or timer event has happened,
88 /* or whenever nothing has happened for a specified amount of time.
89 /* The result value of the function specifies how long to wait until
90 /* the next event. Specify -1 to wait for "as long as it takes".
92 /* Only the last instance of this parameter type is remembered.
93 /* .IP "MAIL_SERVER_EXIT (void *(void))"
94 /* A pointer to function that is executed immediately before normal
95 /* process termination.
97 /* Only the last instance of this parameter type is remembered.
98 /* .IP "MAIL_SERVER_PRE_ACCEPT (void *(char *service_name, char **argv))"
99 /* Function to be executed prior to accepting a new connection.
101 /* Only the last instance of this parameter type is remembered.
102 /* .IP "MAIL_SERVER_IN_FLOW_DELAY (none)"
103 /* Pause $in_flow_delay seconds when no "mail flow control token"
104 /* is available. A token is consumed for each connection request.
105 /* .IP MAIL_SERVER_SOLITARY
106 /* This service must be configured with process limit of 1.
107 /* .IP MAIL_SERVER_UNLIMITED
108 /* This service must be configured with process limit of 0.
109 /* .IP MAIL_SERVER_PRIVILEGED
110 /* This service must be configured as privileged.
112 /* The var_use_limit variable limits the number of clients that
113 /* a server can service before it commits suicide.
114 /* This value is taken from the global \fBmain.cf\fR configuration
115 /* file. Setting \fBvar_idle_limit\fR to zero disables the client limit.
117 /* The var_idle_limit variable limits the time that a service
118 /* receives no client connection requests before it commits suicide.
119 /* This value is taken from the global \fBmain.cf\fR configuration
120 /* file. Setting \fBvar_use_limit\fR to zero disables the idle limit.
122 /* Problems and transactions are logged to \fBsyslogd\fR(8).
125 /* master(8), master process
126 /* syslogd(8) system logging
130 /* The Secure Mailer license must be distributed with this software.
133 /* IBM T.J. Watson Research
135 /* Yorktown Heights, NY 10598, USA
138 /* System library. */
140 #include <sys_defs.h>
141 #include <sys/socket.h>
151 #ifdef STRCASECMP_IN_STRINGS_H
156 /* Utility library. */
159 #include <msg_syslog.h>
160 #include <msg_vstream.h>
161 #include <chroot_uid.h>
164 #include <msg_vstream.h>
165 #include <mymalloc.h>
168 #include <stringops.h>
169 #include <sane_accept.h>
171 #include <safe_open.h>
173 #include <watchdog.h>
174 #include <split_at.h>
176 /* Global library. */
178 #include <mail_params.h>
179 #include <mail_task.h>
180 #include <debug_process.h>
181 #include <mail_conf.h>
182 #include <mail_dict.h>
183 #include <timed_ipc.h>
184 #include <resolve_local.h>
185 #include <mail_flow.h>
187 /* Process manager. */
189 #include "master_proto.h"
191 /* Application-specific */
193 #include "mail_server.h"
198 static int use_count
;
200 static void (*single_server_service
) (VSTREAM
*, char *, char **);
201 static char *single_server_name
;
202 static char **single_server_argv
;
203 static void (*single_server_accept
) (int, char *);
204 static void (*single_server_onexit
) (char *, char **);
205 static void (*single_server_pre_accept
) (char *, char **);
206 static VSTREAM
*single_server_lock
;
207 static int single_server_in_flow_delay
;
208 static unsigned single_server_generation
;
210 /* single_server_exit - normal termination */
212 static NORETURN
single_server_exit(void)
214 if (single_server_onexit
)
215 single_server_onexit(single_server_name
, single_server_argv
);
219 /* single_server_abort - terminate after abnormal master exit */
221 static void single_server_abort(int unused_event
, char *unused_context
)
224 msg_info("master disconnect -- exiting");
225 single_server_exit();
228 /* single_server_timeout - idle time exceeded */
230 static void single_server_timeout(int unused_event
, char *unused_context
)
233 msg_info("idle timeout -- exiting");
234 single_server_exit();
237 /* single_server_wakeup - wake up application */
239 static void single_server_wakeup(int fd
)
245 * If the accept() succeeds, be sure to disable non-blocking I/O, because
246 * the application is supposed to be single-threaded. Notice the master
247 * of our (un)availability to service connection requests. Commit suicide
248 * when the master process disconnected from us. Don't drop the already
249 * accepted client request after "postfix reload"; that would be rude.
252 msg_info("connection established");
253 non_blocking(fd
, BLOCKING
);
254 close_on_exec(fd
, CLOSE_ON_EXEC
);
255 stream
= vstream_fdopen(fd
, O_RDWR
);
256 tmp
= concatenate(single_server_name
, " socket", (char *) 0);
257 vstream_control(stream
, VSTREAM_CTL_PATH
, tmp
, VSTREAM_CTL_END
);
259 timed_ipc_setup(stream
);
260 if (master_notify(var_pid
, single_server_generation
, MASTER_STAT_TAKEN
) < 0)
262 if (single_server_in_flow_delay
&& mail_flow_get(1) < 0)
263 doze(var_in_flow_delay
* 1000000);
264 single_server_service(stream
, single_server_name
, single_server_argv
);
265 (void) vstream_fclose(stream
);
266 if (master_notify(var_pid
, single_server_generation
, MASTER_STAT_AVAIL
) < 0)
267 single_server_abort(EVENT_NULL_TYPE
, EVENT_NULL_CONTEXT
);
269 msg_info("connection closed");
271 if (var_idle_limit
> 0)
272 event_request_timer(single_server_timeout
, (char *) 0, var_idle_limit
);
275 /* single_server_accept_local - accept client connection request */
277 static void single_server_accept_local(int unused_event
, char *context
)
279 int listen_fd
= CAST_CHAR_PTR_TO_INT(context
);
284 * Be prepared for accept() to fail because some other process already
285 * got the connection. We use select() + accept(), instead of simply
286 * blocking in accept(), because we must be able to detect that the
287 * master process has gone away unexpectedly.
289 if (var_idle_limit
> 0)
290 time_left
= event_cancel_timer(single_server_timeout
, (char *) 0);
292 if (single_server_pre_accept
)
293 single_server_pre_accept(single_server_name
, single_server_argv
);
294 fd
= LOCAL_ACCEPT(listen_fd
);
295 if (single_server_lock
!= 0
296 && myflock(vstream_fileno(single_server_lock
), INTERNAL_LOCK
,
297 MYFLOCK_OP_NONE
) < 0)
298 msg_fatal("select unlock: %m");
301 msg_error("accept connection: %m");
303 event_request_timer(single_server_timeout
, (char *) 0, time_left
);
306 single_server_wakeup(fd
);
309 #ifdef MASTER_XPORT_NAME_PASS
311 /* single_server_accept_pass - accept descriptor */
313 static void single_server_accept_pass(int unused_event
, char *context
)
315 int listen_fd
= CAST_CHAR_PTR_TO_INT(context
);
320 * Be prepared for accept() to fail because some other process already
321 * got the connection. We use select() + accept(), instead of simply
322 * blocking in accept(), because we must be able to detect that the
323 * master process has gone away unexpectedly.
325 if (var_idle_limit
> 0)
326 time_left
= event_cancel_timer(single_server_timeout
, (char *) 0);
328 if (single_server_pre_accept
)
329 single_server_pre_accept(single_server_name
, single_server_argv
);
330 fd
= PASS_ACCEPT(listen_fd
);
331 if (single_server_lock
!= 0
332 && myflock(vstream_fileno(single_server_lock
), INTERNAL_LOCK
,
333 MYFLOCK_OP_NONE
) < 0)
334 msg_fatal("select unlock: %m");
337 msg_error("accept connection: %m");
339 event_request_timer(single_server_timeout
, (char *) 0, time_left
);
342 single_server_wakeup(fd
);
347 /* single_server_accept_inet - accept client connection request */
349 static void single_server_accept_inet(int unused_event
, char *context
)
351 int listen_fd
= CAST_CHAR_PTR_TO_INT(context
);
356 * Be prepared for accept() to fail because some other process already
357 * got the connection. We use select() + accept(), instead of simply
358 * blocking in accept(), because we must be able to detect that the
359 * master process has gone away unexpectedly.
361 if (var_idle_limit
> 0)
362 time_left
= event_cancel_timer(single_server_timeout
, (char *) 0);
364 if (single_server_pre_accept
)
365 single_server_pre_accept(single_server_name
, single_server_argv
);
366 fd
= inet_accept(listen_fd
);
367 if (single_server_lock
!= 0
368 && myflock(vstream_fileno(single_server_lock
), INTERNAL_LOCK
,
369 MYFLOCK_OP_NONE
) < 0)
370 msg_fatal("select unlock: %m");
373 msg_error("accept connection: %m");
375 event_request_timer(single_server_timeout
, (char *) 0, time_left
);
378 single_server_wakeup(fd
);
381 /* single_server_main - the real main program */
383 NORETURN
single_server_main(int argc
, char **argv
, SINGLE_SERVER_FN service
,...)
385 const char *myname
= "single_server_main";
391 char *service_name
= basename(argv
[0]);
394 int socket_count
= 1;
397 MAIL_SERVER_INIT_FN pre_init
= 0;
398 MAIL_SERVER_INIT_FN post_init
= 0;
399 MAIL_SERVER_LOOP_FN loop
= 0;
410 int msg_vstream_needed
= 0;
411 int redo_syslog_init
= 0;
414 * Process environment options as early as we can.
416 if (getenv(CONF_ENV_VERB
))
418 if (getenv(CONF_ENV_DEBUG
))
422 * Don't die when a process goes away unexpectedly.
424 signal(SIGPIPE
, SIG_IGN
);
427 * Don't die for frivolous reasons.
430 signal(SIGXFSZ
, SIG_IGN
);
434 * May need this every now and then.
436 var_procname
= mystrdup(basename(argv
[0]));
437 set_mail_conf_str(VAR_PROCNAME
, var_procname
);
440 * Initialize logging and exit handler. Do the syslog first, so that its
441 * initialization completes before we enter the optional chroot jail.
443 msg_syslog_init(mail_task(var_procname
), LOG_PID
, LOG_FACILITY
);
445 msg_info("daemon started");
448 * Initialize from the configuration file. Allow command-line options to
449 * override compiled-in defaults or configured parameter values.
454 * Register dictionaries that use higher-level interfaces and protocols.
459 * Pick up policy settings from master process. Shut up error messages to
460 * stderr, because no-one is going to see them.
463 while ((c
= GETOPT(argc
, argv
, "cdDi:lm:n:o:s:St:uvVz")) > 0) {
475 mail_conf_update(VAR_MAX_IDLE
, optarg
);
481 mail_conf_update(VAR_MAX_USE
, optarg
);
484 service_name
= optarg
;
487 /* XXX Use split_nameval() */
488 oname
= mystrdup(optarg
);
489 if ((oval
= split_at(oname
, '=')) == 0)
491 mail_conf_update(oname
, oval
);
492 if (strcmp(oname
, VAR_SYSLOG_NAME
) == 0)
493 redo_syslog_init
= 1;
496 if ((socket_count
= atoi(optarg
)) <= 0)
497 msg_fatal("invalid socket_count: %s", optarg
);
512 if (++msg_vstream_needed
== 1)
513 msg_vstream_init(mail_task(var_procname
), VSTREAM_ERR
);
519 msg_fatal("invalid option: %c", c
);
525 * Initialize generic parameters.
528 if (redo_syslog_init
)
529 msg_syslog_init(mail_task(var_procname
), LOG_PID
, LOG_FACILITY
);
532 * If not connected to stdin, stdin must not be a terminal.
534 if (daemon_mode
&& stream
== 0 && isatty(STDIN_FILENO
)) {
535 msg_vstream_init(var_procname
, VSTREAM_ERR
);
536 msg_fatal("do not run this command by hand");
540 * Application-specific initialization.
542 va_start(ap
, service
);
543 while ((key
= va_arg(ap
, int)) != 0) {
545 case MAIL_SERVER_INT_TABLE
:
546 get_mail_conf_int_table(va_arg(ap
, CONFIG_INT_TABLE
*));
548 case MAIL_SERVER_STR_TABLE
:
549 get_mail_conf_str_table(va_arg(ap
, CONFIG_STR_TABLE
*));
551 case MAIL_SERVER_BOOL_TABLE
:
552 get_mail_conf_bool_table(va_arg(ap
, CONFIG_BOOL_TABLE
*));
554 case MAIL_SERVER_TIME_TABLE
:
555 get_mail_conf_time_table(va_arg(ap
, CONFIG_TIME_TABLE
*));
557 case MAIL_SERVER_RAW_TABLE
:
558 get_mail_conf_raw_table(va_arg(ap
, CONFIG_RAW_TABLE
*));
560 case MAIL_SERVER_NINT_TABLE
:
561 get_mail_conf_nint_table(va_arg(ap
, CONFIG_NINT_TABLE
*));
563 case MAIL_SERVER_PRE_INIT
:
564 pre_init
= va_arg(ap
, MAIL_SERVER_INIT_FN
);
566 case MAIL_SERVER_POST_INIT
:
567 post_init
= va_arg(ap
, MAIL_SERVER_INIT_FN
);
569 case MAIL_SERVER_LOOP
:
570 loop
= va_arg(ap
, MAIL_SERVER_LOOP_FN
);
572 case MAIL_SERVER_EXIT
:
573 single_server_onexit
= va_arg(ap
, MAIL_SERVER_EXIT_FN
);
575 case MAIL_SERVER_PRE_ACCEPT
:
576 single_server_pre_accept
= va_arg(ap
, MAIL_SERVER_ACCEPT_FN
);
578 case MAIL_SERVER_IN_FLOW_DELAY
:
579 single_server_in_flow_delay
= 1;
581 case MAIL_SERVER_SOLITARY
:
582 if (stream
== 0 && !alone
)
583 msg_fatal("service %s requires a process limit of 1",
586 case MAIL_SERVER_UNLIMITED
:
587 if (stream
== 0 && !zerolimit
)
588 msg_fatal("service %s requires a process limit of 0",
591 case MAIL_SERVER_PRIVILEGED
:
593 msg_fatal("service %s requires privileged operation",
597 msg_panic("%s: unknown argument type: %d", myname
, key
);
603 root_dir
= var_queue_dir
;
605 user_name
= var_mail_owner
;
608 * Can options be required?
612 msg_fatal("no transport type specified");
613 if (strcasecmp(transport
, MASTER_XPORT_NAME_INET
) == 0)
614 single_server_accept
= single_server_accept_inet
;
615 else if (strcasecmp(transport
, MASTER_XPORT_NAME_UNIX
) == 0)
616 single_server_accept
= single_server_accept_local
;
617 #ifdef MASTER_XPORT_NAME_PASS
618 else if (strcasecmp(transport
, MASTER_XPORT_NAME_PASS
) == 0)
619 single_server_accept
= single_server_accept_pass
;
622 msg_fatal("unsupported transport type: %s", transport
);
626 * Retrieve process generation from environment.
628 if ((generation
= getenv(MASTER_GEN_NAME
)) != 0) {
629 if (!alldig(generation
))
630 msg_fatal("bad generation: %s", generation
);
631 OCTAL_TO_UNSIGNED(single_server_generation
, generation
);
633 msg_info("process generation: %s (%o)",
634 generation
, single_server_generation
);
638 * Optionally start the debugger on ourself.
644 * Traditionally, BSD select() can't handle multiple processes selecting
645 * on the same socket, and wakes up every process in select(). See TCP/IP
646 * Illustrated volume 2 page 532. We avoid select() collisions with an
647 * external lock file.
649 if (stream
== 0 && !alone
) {
650 lock_path
= concatenate(DEF_PID_DIR
, "/", transport
,
651 ".", service_name
, (char *) 0);
652 why
= vstring_alloc(1);
653 if ((single_server_lock
= safe_open(lock_path
, O_CREAT
| O_RDWR
, 0600,
654 (struct stat
*) 0, -1, -1, why
)) == 0)
655 msg_fatal("open lock file %s: %s", lock_path
, vstring_str(why
));
656 close_on_exec(vstream_fileno(single_server_lock
), CLOSE_ON_EXEC
);
662 * Set up call-back info.
664 single_server_service
= service
;
665 single_server_name
= service_name
;
666 single_server_argv
= argv
+ optind
;
669 * Run pre-jail initialization.
671 if (chdir(var_queue_dir
) < 0)
672 msg_fatal("chdir(\"%s\"): %m", var_queue_dir
);
674 pre_init(single_server_name
, single_server_argv
);
677 * Optionally, restrict the damage that this process can do.
679 resolve_local_init();
681 chroot_uid(root_dir
, user_name
);
684 * Run post-jail initialization.
687 post_init(single_server_name
, single_server_argv
);
690 * Are we running as a one-shot server with the client connection on
691 * standard input? If so, make sure the output is written to stdout so as
692 * to satisfy common expectation.
695 vstream_control(stream
,
697 VSTREAM_CTL_WRITE_FD
, STDOUT_FILENO
,
699 service(stream
, single_server_name
, single_server_argv
);
700 vstream_fflush(stream
);
701 single_server_exit();
705 * Running as a semi-resident server. Service connection requests.
706 * Terminate when we have serviced a sufficient number of clients, when
707 * no-one has been talking to us for a configurable amount of time, or
708 * when the master process terminated abnormally.
710 if (var_idle_limit
> 0)
711 event_request_timer(single_server_timeout
, (char *) 0, var_idle_limit
);
712 for (fd
= MASTER_LISTEN_FD
; fd
< MASTER_LISTEN_FD
+ socket_count
; fd
++) {
713 event_enable_read(fd
, single_server_accept
, CAST_INT_TO_CHAR_PTR(fd
));
714 close_on_exec(fd
, CLOSE_ON_EXEC
);
716 event_enable_read(MASTER_STATUS_FD
, single_server_abort
, (char *) 0);
717 close_on_exec(MASTER_STATUS_FD
, CLOSE_ON_EXEC
);
718 close_on_exec(MASTER_FLOW_READ
, CLOSE_ON_EXEC
);
719 close_on_exec(MASTER_FLOW_WRITE
, CLOSE_ON_EXEC
);
720 watchdog
= watchdog_create(var_daemon_timeout
, (WATCHDOG_FN
) 0, (char *) 0);
723 * The event loop, at last.
725 while (var_use_limit
== 0 || use_count
< var_use_limit
) {
726 if (single_server_lock
!= 0) {
727 watchdog_stop(watchdog
);
728 if (myflock(vstream_fileno(single_server_lock
), INTERNAL_LOCK
,
729 MYFLOCK_OP_EXCLUSIVE
) < 0)
730 msg_fatal("select lock: %m");
732 watchdog_start(watchdog
);
733 delay
= loop
? loop(single_server_name
, single_server_argv
) : -1;
736 single_server_exit();