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