xref: /netbsd-src/external/ibm-public/postfix/dist/src/master/master.c (revision 7788a0781fe6ff2cce37368b4578a7ade0850cb1)
1 /*	$NetBSD: master.c,v 1.1.1.2 2013/01/02 18:59:01 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 (all)\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 file 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      * Check the Postfix library version as soon as we enable logging.
300      */
301     MAIL_VERSION_CHECK;
302 
303     /*
304      * The mail system must be run by the superuser so it can revoke
305      * privileges for selected operations. That's right - it takes privileges
306      * to toss privileges.
307      */
308     if (getuid() != 0)
309 	msg_fatal("the master command is reserved for the superuser");
310     if (unsafe() != 0)
311 	msg_fatal("the master command must not run as a set-uid process");
312 
313     /*
314      * Process JCL.
315      */
316     while ((ch = GETOPT(argc, argv, "c:Dde:tv")) > 0) {
317 	switch (ch) {
318 	case 'c':
319 	    if (setenv(CONF_ENV_PATH, optarg, 1) < 0)
320 		msg_fatal("out of memory");
321 	    break;
322 	case 'd':
323 	    master_detach = 0;
324 	    break;
325 	case 'e':
326 	    event_request_timer(master_exit_event, (char *) 0, atoi(optarg));
327 	    break;
328 	case 'D':
329 	    debug_me = 1;
330 	    break;
331 	case 't':
332 	    test_lock = 1;
333 	    break;
334 	case 'v':
335 	    msg_verbose++;
336 	    break;
337 	default:
338 	    usage(argv[0]);
339 	    /* NOTREACHED */
340 	}
341     }
342 
343     /*
344      * This program takes no other arguments.
345      */
346     if (argc > optind)
347 	usage(argv[0]);
348 
349     /*
350      * If started from a terminal, get rid of any tty association. This also
351      * means that all errors and warnings must go to the syslog daemon.
352      */
353     if (master_detach)
354 	for (fd = 0; fd < 3; fd++) {
355 	    (void) close(fd);
356 	    if (open("/dev/null", O_RDWR, 0) != fd)
357 		msg_fatal("open /dev/null: %m");
358 	}
359 
360     /*
361      * Run in a separate process group, so that "postfix stop" can terminate
362      * all MTA processes cleanly. Give up if we can't separate from our
363      * parent process. We're not supposed to blow away the parent.
364      */
365     if (debug_me == 0 && master_detach != 0 && setsid() == -1 && getsid(0) != getpid())
366 	msg_fatal("unable to set session and process group ID: %m");
367 
368     /*
369      * Make some room for plumbing with file descriptors. XXX This breaks
370      * when a service listens on many ports. In order to do this right we
371      * must change the master-child interface so that descriptors do not need
372      * to have fixed numbers.
373      *
374      * In a child we need two descriptors for the flow control pipe, one for
375      * child->master status updates and at least one for listening.
376      */
377     for (n = 0; n < 5; n++) {
378 	if (close_on_exec(dup(0), CLOSE_ON_EXEC) < 0)
379 	    msg_fatal("dup(0): %m");
380     }
381 
382     /*
383      * Final initializations. Unfortunately, we must read the global Postfix
384      * configuration file after doing command-line processing, so that we get
385      * consistent results when we SIGHUP the server to reload configuration
386      * files.
387      */
388     master_vars_init();
389 
390     /*
391      * In case of multi-protocol support. This needs to be done because
392      * master does not invoke mail_params_init() (it was written before that
393      * code existed).
394      */
395     (void) inet_proto_init(VAR_INET_PROTOCOLS, var_inet_protocols);
396 
397     /*
398      * Environment import filter, to enforce consistent behavior whether
399      * Postfix is started by hand, or at system boot time.
400      */
401     import_env = argv_split(var_import_environ, ", \t\r\n");
402     clean_env(import_env->argv);
403     argv_free(import_env);
404 
405     if ((inherited_limit = get_file_limit()) < 0)
406 	set_file_limit(OFF_T_MAX);
407 
408     if (chdir(var_queue_dir))
409 	msg_fatal("chdir %s: %m", var_queue_dir);
410 
411     /*
412      * Lock down the master.pid file. In test mode, no file means that it
413      * isn't locked.
414      */
415     lock_path = vstring_alloc(10);
416     data_lock_path = vstring_alloc(10);
417     why = vstring_alloc(10);
418 
419     vstring_sprintf(lock_path, "%s/%s.pid", DEF_PID_DIR, var_procname);
420     if (test_lock && access(vstring_str(lock_path), F_OK) < 0)
421 	exit(0);
422     lock_fp = open_lock(vstring_str(lock_path), O_RDWR | O_CREAT, 0644, why);
423     if (test_lock)
424 	exit(lock_fp ? 0 : 1);
425     if (lock_fp == 0)
426 	msg_fatal("open lock file %s: %s",
427 		  vstring_str(lock_path), vstring_str(why));
428     vstream_fprintf(lock_fp, "%*lu\n", (int) sizeof(unsigned long) * 4,
429 		    (unsigned long) var_pid);
430     if (vstream_fflush(lock_fp))
431 	msg_fatal("cannot update lock file %s: %m", vstring_str(lock_path));
432     close_on_exec(vstream_fileno(lock_fp), CLOSE_ON_EXEC);
433 
434     /*
435      * Lock down the Postfix-writable data directory.
436      */
437     vstring_sprintf(data_lock_path, "%s/%s.lock", var_data_dir, var_procname);
438     set_eugid(var_owner_uid, var_owner_gid);
439     data_lock_fp =
440 	open_lock(vstring_str(data_lock_path), O_RDWR | O_CREAT, 0644, why);
441     set_ugid(getuid(), getgid());
442     if (data_lock_fp == 0)
443 	msg_fatal("open lock file %s: %s",
444 		  vstring_str(data_lock_path), vstring_str(why));
445     vstream_fprintf(data_lock_fp, "%*lu\n", (int) sizeof(unsigned long) * 4,
446 		    (unsigned long) var_pid);
447     if (vstream_fflush(data_lock_fp))
448 	msg_fatal("cannot update lock file %s: %m", vstring_str(data_lock_path));
449     close_on_exec(vstream_fileno(data_lock_fp), CLOSE_ON_EXEC);
450 
451     /*
452      * Clean up.
453      */
454     vstring_free(why);
455     vstring_free(lock_path);
456     vstring_free(data_lock_path);
457 
458     /*
459      * Optionally start the debugger on ourself.
460      */
461     if (debug_me)
462 	debug_process();
463 
464     /*
465      * Finish initialization, last part. We must process configuration files
466      * after processing command-line parameters, so that we get consistent
467      * results when we SIGHUP the server to reload configuration files.
468      */
469     master_config();
470     master_sigsetup();
471     master_flow_init();
472     msg_info("daemon started -- version %s, configuration %s",
473 	     var_mail_version, var_config_dir);
474 
475     /*
476      * Process events. The event handler will execute the read/write/timer
477      * action routines. Whenever something has happened, see if we received
478      * any signal in the mean time. Although the master process appears to do
479      * multiple things at the same time, it really is all a single thread, so
480      * that there are no concurrency conflicts within the master process.
481      */
482 #define MASTER_WATCHDOG_TIME	1000
483 
484     watchdog = watchdog_create(MASTER_WATCHDOG_TIME, (WATCHDOG_FN) 0, (char *) 0);
485     for (;;) {
486 #ifdef HAS_VOLATILE_LOCKS
487 	if (myflock(vstream_fileno(lock_fp), INTERNAL_LOCK,
488 		    MYFLOCK_OP_EXCLUSIVE) < 0)
489 	    msg_fatal("refresh exclusive lock: %m");
490 	if (myflock(vstream_fileno(data_lock_fp), INTERNAL_LOCK,
491 		    MYFLOCK_OP_EXCLUSIVE) < 0)
492 	    msg_fatal("refresh exclusive lock: %m");
493 #endif
494 	watchdog_start(watchdog);		/* same as trigger servers */
495 	event_loop(MASTER_WATCHDOG_TIME / 2);
496 	if (master_gotsighup) {
497 	    msg_info("reload -- version %s, configuration %s",
498 		     var_mail_version, var_config_dir);
499 	    master_gotsighup = 0;		/* this first */
500 	    master_vars_init();			/* then this */
501 	    master_refresh();			/* then this */
502 	}
503 	if (master_gotsigchld) {
504 	    if (msg_verbose)
505 		msg_info("got sigchld");
506 	    master_gotsigchld = 0;		/* this first */
507 	    master_reap_child();		/* then this */
508 	}
509     }
510 }
511