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