xref: /netbsd-src/external/ibm-public/postfix/dist/src/master/master.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
1 /*	$NetBSD: master.c,v 1.1.1.1 2009/06/23 10:08:49 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	master 8
6 /* SUMMARY
7 /*	Postfix master process
8 /* SYNOPSIS
9 /*	\fBmaster\fR [\fB-Ddtv\fR] [\fB-c \fIconfig_dir\fR] [\fB-e \fIexit_time\fR]
10 /* DESCRIPTION
11 /*	The \fBmaster\fR(8) daemon is the resident process that runs Postfix
12 /*	daemons on demand: daemons to send or receive messages via the
13 /*	network, daemons to deliver mail locally, etc.  These daemons are
14 /*	created on demand up to a configurable maximum number per service.
15 /*
16 /*	Postfix daemons terminate voluntarily, either after being idle for
17 /*	a configurable amount of time, or after having serviced a
18 /*	configurable number of requests. Exceptions to this rule are the
19 /*	resident queue manager, address verification server, and the TLS
20 /*	session cache and pseudo-random number server.
21 /*
22 /*	The behavior of the \fBmaster\fR(8) daemon is controlled by the
23 /*	\fBmaster.cf\fR configuration file, as described in \fBmaster\fR(5).
24 /*
25 /*	Options:
26 /* .IP "\fB-c \fIconfig_dir\fR"
27 /*	Read the \fBmain.cf\fR and \fBmaster.cf\fR configuration files in
28 /*	the named directory instead of the default configuration directory.
29 /*	This also overrides the configuration files for other Postfix
30 /*	daemon processes.
31 /* .IP \fB-D\fR
32 /*	After initialization, run a debugger on the master process. The
33 /*	debugging command is specified with the \fBdebugger_command\fR in
34 /*	the \fBmain.cf\fR global configuration file.
35 /* .IP \fB-d\fR
36 /*	Do not redirect stdin, stdout or stderr to /dev/null, and
37 /*	do not discard the controlling terminal. This must be used
38 /*	for debugging only.
39 /* .IP "\fB-e \fIexit_time\fR"
40 /*	Terminate the master process after \fIexit_time\fR seconds. Child
41 /*	processes terminate at their convenience.
42 /* .IP \fB-t\fR
43 /*	Test mode. Return a zero exit status when the \fBmaster.pid\fR lock
44 /*	file does not exist or when that file is not locked.  This is evidence
45 /*	that the \fBmaster\fR(8) daemon is not running.
46 /* .IP \fB-v\fR
47 /*	Enable verbose logging for debugging purposes. This option
48 /*	is passed on to child processes. Multiple \fB-v\fR options
49 /*	make the software increasingly verbose.
50 /* .PP
51 /*	Signals:
52 /* .IP \fBSIGHUP\fR
53 /*	Upon receipt of a \fBHUP\fR signal (e.g., after "\fBpostfix reload\fR"),
54 /*	the master process re-reads its configuration files. If a service has
55 /*	been removed from the \fBmaster.cf\fR file, its running processes
56 /*	are terminated immediately.
57 /*	Otherwise, running processes are allowed to terminate as soon
58 /*	as is convenient, so that changes in configuration settings
59 /*	affect only new service requests.
60 /* .IP \fBSIGTERM\fR
61 /*	Upon receipt of a \fBTERM\fR signal (e.g., after "\fBpostfix abort\fR"),
62 /*	the master process passes the signal on to its child processes and
63 /*	terminates.
64 /*	This is useful for an emergency shutdown. Normally one would
65 /*	terminate only the master ("\fBpostfix stop\fR") and allow running
66 /*	processes to finish what they are doing.
67 /* DIAGNOSTICS
68 /*	Problems are reported to \fBsyslogd\fR(8).
69 /* ENVIRONMENT
70 /* .ad
71 /* .fi
72 /* .IP \fBMAIL_DEBUG\fR
73 /*	After initialization, start a debugger as specified with the
74 /*	\fBdebugger_command\fR configuration parameter in the \fBmain.cf\fR
75 /*	configuration file.
76 /* .IP \fBMAIL_CONFIG\fR
77 /*	Directory with Postfix configuration files.
78 /* CONFIGURATION PARAMETERS
79 /* .ad
80 /* .fi
81 /*	Unlike most Postfix daemon processes, the \fBmaster\fR(8) server does
82 /*	not automatically pick up changes to \fBmain.cf\fR. Changes
83 /*	to \fBmaster.cf\fR are never picked up automatically.
84 /*	Use the "\fBpostfix reload\fR" command after a configuration change.
85 /* RESOURCE AND RATE CONTROLS
86 /* .ad
87 /* .fi
88 /* .IP "\fBdefault_process_limit (100)\fR"
89 /*	The default maximal number of Postfix child processes that provide
90 /*	a given service.
91 /* .IP "\fBmax_idle (100s)\fR"
92 /*	The maximum amount of time that an idle Postfix daemon process waits
93 /*	for an incoming connection before terminating voluntarily.
94 /* .IP "\fBmax_use (100)\fR"
95 /*	The maximal number of incoming connections that a Postfix daemon
96 /*	process will service before terminating voluntarily.
97 /* .IP "\fBservice_throttle_time (60s)\fR"
98 /*	How long the Postfix \fBmaster\fR(8) waits before forking a server that
99 /*	appears to be malfunctioning.
100 /* .PP
101 /*	Available in Postfix version 2.6 and later:
102 /* .IP "\fBmaster_service_disable (empty)\fR"
103 /*	Selectively disable \fBmaster\fR(8) listener ports by service type
104 /*	or by service name and type.
105 /* MISCELLANEOUS CONTROLS
106 /* .ad
107 /* .fi
108 /* .IP "\fBconfig_directory (see 'postconf -d' output)\fR"
109 /*	The default location of the Postfix main.cf and master.cf
110 /*	configuration files.
111 /* .IP "\fBdaemon_directory (see 'postconf -d' output)\fR"
112 /*	The directory with Postfix support programs and daemon programs.
113 /* .IP "\fBdebugger_command (empty)\fR"
114 /*	The external command to execute when a Postfix daemon program is
115 /*	invoked with the -D option.
116 /* .IP "\fBinet_interfaces (all)\fR"
117 /*	The network interface addresses that this mail system receives
118 /*	mail on.
119 /* .IP "\fBinet_protocols (ipv4)\fR"
120 /*	The Internet protocols Postfix will attempt to use when making
121 /*	or accepting connections.
122 /* .IP "\fBimport_environment (see 'postconf -d' output)\fR"
123 /*	The list of environment parameters that a Postfix process will
124 /*	import from a non-Postfix parent process.
125 /* .IP "\fBmail_owner (postfix)\fR"
126 /*	The UNIX system account that owns the Postfix queue and most Postfix
127 /*	daemon processes.
128 /* .IP "\fBprocess_id (read-only)\fR"
129 /*	The process ID of a Postfix command or daemon process.
130 /* .IP "\fBprocess_name (read-only)\fR"
131 /*	The process name of a Postfix command or daemon process.
132 /* .IP "\fBqueue_directory (see 'postconf -d' output)\fR"
133 /*	The location of the Postfix top-level queue directory.
134 /* .IP "\fBsyslog_facility (mail)\fR"
135 /*	The syslog facility of Postfix logging.
136 /* .IP "\fBsyslog_name (see 'postconf -d' output)\fR"
137 /*	The mail system name that is prepended to the process name in syslog
138 /*	records, so that "smtpd" becomes, for example, "postfix/smtpd".
139 /* FILES
140 /* .ad
141 /* .fi
142 /*	To expand the directory names below into their actual values,
143 /*	use the command "\fBpostconf config_directory\fR" etc.
144 /* .na
145 /* .nf
146 /*
147 /*	$config_directory/main.cf, global configuration file.
148 /*	$config_directory/master.cf, master server configuration file.
149 /*	$queue_directory/pid/master.pid, master lock file.
150 /*	$data_directory/master.lock, master lock file.
151 /* SEE ALSO
152 /*	qmgr(8), queue manager
153 /*	verify(8), address verification
154 /*	master(5), master.cf configuration file syntax
155 /*	postconf(5), main.cf configuration parameter syntax
156 /*	syslogd(8), system logging
157 /* LICENSE
158 /* .ad
159 /* .fi
160 /*	The Secure Mailer license must be distributed with this software.
161 /* AUTHOR(S)
162 /*	Wietse Venema
163 /*	IBM T.J. Watson Research
164 /*	P.O. Box 704
165 /*	Yorktown Heights, NY 10598, USA
166 /*--*/
167 
168 /* System libraries. */
169 
170 #include <sys_defs.h>
171 #include <sys/stat.h>
172 #include <syslog.h>
173 #include <signal.h>
174 #include <stdlib.h>
175 #include <unistd.h>
176 #include <string.h>
177 #include <fcntl.h>
178 #include <limits.h>
179 
180 /* Utility library. */
181 
182 #include <events.h>
183 #include <msg.h>
184 #include <msg_syslog.h>
185 #include <vstring.h>
186 #include <mymalloc.h>
187 #include <iostuff.h>
188 #include <vstream.h>
189 #include <stringops.h>
190 #include <myflock.h>
191 #include <watchdog.h>
192 #include <clean_env.h>
193 #include <argv.h>
194 #include <safe.h>
195 #include <set_eugid.h>
196 #include <set_ugid.h>
197 
198 /* Global library. */
199 
200 #include <mail_params.h>
201 #include <mail_version.h>
202 #include <debug_process.h>
203 #include <mail_task.h>
204 #include <mail_conf.h>
205 #include <open_lock.h>
206 #include <inet_proto.h>
207 
208 /* Application-specific. */
209 
210 #include "master.h"
211 
212 int     master_detach = 1;
213 
214 /* master_exit_event - exit for memory leak testing purposes */
215 
216 static void master_exit_event(int unused_event, char *unused_context)
217 {
218     msg_info("master exit time has arrived");
219     exit(0);
220 }
221 
222 /* usage - show hint and terminate */
223 
224 static NORETURN usage(const char *me)
225 {
226     msg_fatal("usage: %s [-c config_dir] [-D (debug)] [-d (don't detach from terminal)] [-e exit_time] [-t (test)] [-v]", me);
227 }
228 
229 MAIL_VERSION_STAMP_DECLARE;
230 
231 /* main - main program */
232 
233 int     main(int argc, char **argv)
234 {
235     static VSTREAM *lock_fp;
236     static VSTREAM *data_lock_fp;
237     VSTRING *lock_path;
238     VSTRING *data_lock_path;
239     off_t   inherited_limit;
240     int     debug_me = 0;
241     int     ch;
242     int     fd;
243     int     n;
244     int     test_lock = 0;
245     VSTRING *why;
246     WATCHDOG *watchdog;
247     ARGV   *import_env;
248 
249     /*
250      * Fingerprint executables and core dumps.
251      */
252     MAIL_VERSION_STAMP_ALLOCATE;
253 
254     /*
255      * Initialize.
256      */
257     umask(077);					/* never fails! */
258 
259     /*
260      * Process environment options as early as we can.
261      */
262     if (getenv(CONF_ENV_VERB))
263 	msg_verbose = 1;
264     if (getenv(CONF_ENV_DEBUG))
265 	debug_me = 1;
266 
267     /*
268      * Don't die when a process goes away unexpectedly.
269      */
270     signal(SIGPIPE, SIG_IGN);
271 
272     /*
273      * Strip and save the process name for diagnostics etc.
274      */
275     var_procname = mystrdup(basename(argv[0]));
276 
277     /*
278      * When running a child process, don't leak any open files that were
279      * leaked to us by our own (privileged) parent process. Descriptors 0-2
280      * are taken care of after we have initialized error logging.
281      *
282      * Some systems such as AIX have a huge per-process open file limit. In
283      * those cases, limit the search for potential file descriptor leaks to
284      * just the first couple hundred.
285      *
286      * The Debian post-installation script passes an open file descriptor into
287      * the master process and waits forever for someone to close it. Because
288      * of this we have to close descriptors > 2, and pray that doing so does
289      * not break things.
290      */
291     closefrom(3);
292 
293     /*
294      * Initialize logging and exit handler.
295      */
296     msg_syslog_init(mail_task(var_procname), LOG_PID, LOG_FACILITY);
297 
298     /*
299      * The mail system must be run by the superuser so it can revoke
300      * privileges for selected operations. That's right - it takes privileges
301      * to toss privileges.
302      */
303     if (getuid() != 0)
304 	msg_fatal("the master command is reserved for the superuser");
305     if (unsafe() != 0)
306 	msg_fatal("the master command must not run as a set-uid process");
307 
308     /*
309      * Process JCL.
310      */
311     while ((ch = GETOPT(argc, argv, "c:Dde:tv")) > 0) {
312 	switch (ch) {
313 	case 'c':
314 	    if (setenv(CONF_ENV_PATH, optarg, 1) < 0)
315 		msg_fatal("out of memory");
316 	    break;
317 	case 'd':
318 	    master_detach = 0;
319 	    break;
320 	case 'e':
321 	    event_request_timer(master_exit_event, (char *) 0, atoi(optarg));
322 	    break;
323 	case 'D':
324 	    debug_me = 1;
325 	    break;
326 	case 't':
327 	    test_lock = 1;
328 	    break;
329 	case 'v':
330 	    msg_verbose++;
331 	    break;
332 	default:
333 	    usage(argv[0]);
334 	    /* NOTREACHED */
335 	}
336     }
337 
338     /*
339      * This program takes no other arguments.
340      */
341     if (argc > optind)
342 	usage(argv[0]);
343 
344     /*
345      * If started from a terminal, get rid of any tty association. This also
346      * means that all errors and warnings must go to the syslog daemon.
347      */
348     if (master_detach)
349 	for (fd = 0; fd < 3; fd++) {
350 	    (void) close(fd);
351 	    if (open("/dev/null", O_RDWR, 0) != fd)
352 		msg_fatal("open /dev/null: %m");
353 	}
354 
355     /*
356      * Run in a separate process group, so that "postfix stop" can terminate
357      * all MTA processes cleanly. Give up if we can't separate from our
358      * parent process. We're not supposed to blow away the parent.
359      */
360     if (debug_me == 0 && master_detach != 0 && setsid() == -1 && getsid(0) != getpid())
361 	msg_fatal("unable to set session and process group ID: %m");
362 
363     /*
364      * Make some room for plumbing with file descriptors. XXX This breaks
365      * when a service listens on many ports. In order to do this right we
366      * must change the master-child interface so that descriptors do not need
367      * to have fixed numbers.
368      *
369      * In a child we need two descriptors for the flow control pipe, one for
370      * child->master status updates and at least one for listening.
371      */
372     for (n = 0; n < 5; n++) {
373 	if (close_on_exec(dup(0), CLOSE_ON_EXEC) < 0)
374 	    msg_fatal("dup(0): %m");
375     }
376 
377     /*
378      * Final initializations. Unfortunately, we must read the global Postfix
379      * configuration file after doing command-line processing, so that we get
380      * consistent results when we SIGHUP the server to reload configuration
381      * files.
382      */
383     master_vars_init();
384 
385     /*
386      * In case of multi-protocol support. This needs to be done because
387      * master does not invoke mail_params_init() (it was written before that
388      * code existed).
389      */
390     (void) inet_proto_init(VAR_INET_PROTOCOLS, var_inet_protocols);
391 
392     /*
393      * Environment import filter, to enforce consistent behavior whether
394      * Postfix is started by hand, or at system boot time.
395      */
396     import_env = argv_split(var_import_environ, ", \t\r\n");
397     clean_env(import_env->argv);
398     argv_free(import_env);
399 
400     if ((inherited_limit = get_file_limit()) < 0)
401 	set_file_limit(OFF_T_MAX);
402 
403     if (chdir(var_queue_dir))
404 	msg_fatal("chdir %s: %m", var_queue_dir);
405 
406     /*
407      * Lock down the master.pid file. In test mode, no file means that it
408      * isn't locked.
409      */
410     lock_path = vstring_alloc(10);
411     data_lock_path = vstring_alloc(10);
412     why = vstring_alloc(10);
413 
414     vstring_sprintf(lock_path, "%s/%s.pid", DEF_PID_DIR, var_procname);
415     if (test_lock && access(vstring_str(lock_path), F_OK) < 0)
416 	exit(0);
417     lock_fp = open_lock(vstring_str(lock_path), O_RDWR | O_CREAT, 0644, why);
418     if (test_lock)
419 	exit(lock_fp ? 0 : 1);
420     if (lock_fp == 0)
421 	msg_fatal("open lock file %s: %s",
422 		  vstring_str(lock_path), vstring_str(why));
423     vstream_fprintf(lock_fp, "%*lu\n", (int) sizeof(unsigned long) * 4,
424 		    (unsigned long) var_pid);
425     if (vstream_fflush(lock_fp))
426 	msg_fatal("cannot update lock file %s: %m", vstring_str(lock_path));
427     close_on_exec(vstream_fileno(lock_fp), CLOSE_ON_EXEC);
428 
429     /*
430      * Lock down the Postfix-writable data directory.
431      */
432     vstring_sprintf(data_lock_path, "%s/%s.lock", var_data_dir, var_procname);
433     set_eugid(var_owner_uid, var_owner_gid);
434     data_lock_fp =
435 	open_lock(vstring_str(data_lock_path), O_RDWR | O_CREAT, 0644, why);
436     set_ugid(getuid(), getgid());
437     if (data_lock_fp == 0)
438 	msg_fatal("open lock file %s: %s",
439 		  vstring_str(data_lock_path), vstring_str(why));
440     vstream_fprintf(data_lock_fp, "%*lu\n", (int) sizeof(unsigned long) * 4,
441 		    (unsigned long) var_pid);
442     if (vstream_fflush(data_lock_fp))
443 	msg_fatal("cannot update lock file %s: %m", vstring_str(data_lock_path));
444     close_on_exec(vstream_fileno(data_lock_fp), CLOSE_ON_EXEC);
445 
446     /*
447      * Clean up.
448      */
449     vstring_free(why);
450     vstring_free(lock_path);
451     vstring_free(data_lock_path);
452 
453     /*
454      * Optionally start the debugger on ourself.
455      */
456     if (debug_me)
457 	debug_process();
458 
459     /*
460      * Finish initialization, last part. We must process configuration files
461      * after processing command-line parameters, so that we get consistent
462      * results when we SIGHUP the server to reload configuration files.
463      */
464     master_config();
465     master_sigsetup();
466     master_flow_init();
467     msg_info("daemon started -- version %s, configuration %s",
468 	     var_mail_version, var_config_dir);
469 
470     /*
471      * Process events. The event handler will execute the read/write/timer
472      * action routines. Whenever something has happened, see if we received
473      * any signal in the mean time. Although the master process appears to do
474      * multiple things at the same time, it really is all a single thread, so
475      * that there are no concurrency conflicts within the master process.
476      */
477 #define MASTER_WATCHDOG_TIME	1000
478 
479     watchdog = watchdog_create(MASTER_WATCHDOG_TIME, (WATCHDOG_FN) 0, (char *) 0);
480     for (;;) {
481 #ifdef HAS_VOLATILE_LOCKS
482 	if (myflock(vstream_fileno(lock_fp), INTERNAL_LOCK,
483 		    MYFLOCK_OP_EXCLUSIVE) < 0)
484 	    msg_fatal("refresh exclusive lock: %m");
485 	if (myflock(vstream_fileno(data_lock_fp), INTERNAL_LOCK,
486 		    MYFLOCK_OP_EXCLUSIVE) < 0)
487 	    msg_fatal("refresh exclusive lock: %m");
488 #endif
489 	watchdog_start(watchdog);		/* same as trigger servers */
490 	event_loop(MASTER_WATCHDOG_TIME / 2);
491 	if (master_gotsighup) {
492 	    msg_info("reload -- version %s, configuration %s",
493 		     var_mail_version, var_config_dir);
494 	    master_gotsighup = 0;		/* this first */
495 	    master_vars_init();			/* then this */
496 	    master_refresh();			/* then this */
497 	}
498 	if (master_gotsigchld) {
499 	    if (msg_verbose)
500 		msg_info("got sigchld");
501 	    master_gotsigchld = 0;		/* this first */
502 	    master_reap_child();		/* then this */
503 	}
504     }
505 }
506