1 /* $NetBSD: master.c,v 1.4 2022/10/08 16:12:46 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 (see 'postconf -d output')\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 /* .PP 168 /* Available in Postfix 3.6 and later: 169 /* .IP "\fBknown_tcp_ports (lmtp=24, smtp=25, smtps=submissions=465, submission=587)\fR" 170 /* Optional setting that avoids lookups in the \fBservices\fR(5) database. 171 /* FILES 172 /* .ad 173 /* .fi 174 /* To expand the directory names below into their actual values, 175 /* use the command "\fBpostconf config_directory\fR" etc. 176 /* .na 177 /* .nf 178 /* 179 /* $config_directory/main.cf, global configuration file. 180 /* $config_directory/master.cf, master server configuration file. 181 /* $queue_directory/pid/master.pid, master lock file. 182 /* $data_directory/master.lock, master lock file. 183 /* SEE ALSO 184 /* qmgr(8), queue manager 185 /* verify(8), address verification 186 /* master(5), master.cf configuration file syntax 187 /* postconf(5), main.cf configuration file syntax 188 /* postlogd(8), Postfix logging 189 /* syslogd(8), system logging 190 /* LICENSE 191 /* .ad 192 /* .fi 193 /* The Secure Mailer license must be distributed with this software. 194 /* AUTHOR(S) 195 /* Wietse Venema 196 /* IBM T.J. Watson Research 197 /* P.O. Box 704 198 /* Yorktown Heights, NY 10598, USA 199 /* 200 /* Wietse Venema 201 /* Google, Inc. 202 /* 111 8th Avenue 203 /* New York, NY 10011, USA 204 /*--*/ 205 206 /* System libraries. */ 207 208 #include <sys_defs.h> 209 #include <sys/stat.h> 210 #include <signal.h> 211 #include <stdlib.h> 212 #include <unistd.h> 213 #include <string.h> 214 #include <fcntl.h> 215 #include <limits.h> 216 217 /* Utility library. */ 218 219 #include <events.h> 220 #include <msg.h> 221 #include <vstring.h> 222 #include <mymalloc.h> 223 #include <iostuff.h> 224 #include <vstream.h> 225 #include <stringops.h> 226 #include <myflock.h> 227 #include <watchdog.h> 228 #include <clean_env.h> 229 #include <argv.h> 230 #include <safe.h> 231 #include <set_eugid.h> 232 #include <set_ugid.h> 233 234 /* Global library. */ 235 236 #include <mail_params.h> 237 #include <mail_version.h> 238 #include <debug_process.h> 239 #include <mail_task.h> 240 #include <mail_conf.h> 241 #include <open_lock.h> 242 #include <inet_proto.h> 243 #include <mail_parm_split.h> 244 #include <maillog_client.h> 245 246 /* Application-specific. */ 247 248 #include "master.h" 249 250 int master_detach = 1; 251 int init_mode = 0; 252 253 /* master_exit_event - exit for memory leak testing purposes */ 254 255 static void master_exit_event(int unused_event, void *unused_context) 256 { 257 msg_info("master exit time has arrived"); 258 exit(0); 259 } 260 261 /* usage - show hint and terminate */ 262 263 static NORETURN usage(const char *me) 264 { 265 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); 266 } 267 268 MAIL_VERSION_STAMP_DECLARE; 269 270 /* main - main program */ 271 272 int main(int argc, char **argv) 273 { 274 static VSTREAM *lock_fp; 275 static VSTREAM *data_lock_fp; 276 VSTRING *lock_path; 277 VSTRING *data_lock_path; 278 off_t inherited_limit; 279 int debug_me = 0; 280 int keep_stdout = 0; 281 int ch; 282 int fd; 283 int n; 284 int test_lock = 0; 285 VSTRING *why; 286 WATCHDOG *watchdog; 287 ARGV *import_env; 288 int wait_flag = 0; 289 int monitor_fd = -1; 290 291 /* 292 * Fingerprint executables and core dumps. 293 */ 294 MAIL_VERSION_STAMP_ALLOCATE; 295 296 /* 297 * Initialize. 298 */ 299 umask(077); /* never fails! */ 300 301 /* 302 * Process environment options as early as we can. 303 */ 304 if (getenv(CONF_ENV_VERB)) 305 msg_verbose = 1; 306 if (getenv(CONF_ENV_DEBUG)) 307 debug_me = 1; 308 309 /* 310 * Don't die when a process goes away unexpectedly. 311 */ 312 signal(SIGPIPE, SIG_IGN); 313 314 /* 315 * Strip and save the process name for diagnostics etc. 316 */ 317 var_procname = mystrdup(basename(argv[0])); 318 319 /* 320 * When running a child process, don't leak any open files that were 321 * leaked to us by our own (privileged) parent process. Descriptors 0-2 322 * are taken care of after we have initialized error logging. 323 * 324 * Some systems such as AIX have a huge per-process open file limit. In 325 * those cases, limit the search for potential file descriptor leaks to 326 * just the first couple hundred. 327 * 328 * The Debian post-installation script passes an open file descriptor into 329 * the master process and waits forever for someone to close it. Because 330 * of this we have to close descriptors > 2, and pray that doing so does 331 * not break things. 332 */ 333 closefrom(3); 334 335 /* 336 * Initialize logging and exit handler. 337 */ 338 maillog_client_init(mail_task(var_procname), 339 MAILLOG_CLIENT_FLAG_LOGWRITER_FALLBACK); 340 341 /* 342 * Check the Postfix library version as soon as we enable logging. 343 */ 344 MAIL_VERSION_CHECK; 345 346 /* 347 * The mail system must be run by the superuser so it can revoke 348 * privileges for selected operations. That's right - it takes privileges 349 * to toss privileges. 350 */ 351 if (getuid() != 0) 352 msg_fatal("the master command is reserved for the superuser"); 353 if (unsafe() != 0) 354 msg_fatal("the master command must not run as a set-uid process"); 355 356 /* 357 * Process JCL. 358 */ 359 while ((ch = GETOPT(argc, argv, "c:Dde:istvw")) > 0) { 360 switch (ch) { 361 case 'c': 362 if (setenv(CONF_ENV_PATH, optarg, 1) < 0) 363 msg_fatal("out of memory"); 364 break; 365 case 'd': 366 master_detach = 0; 367 break; 368 case 'e': 369 event_request_timer(master_exit_event, (void *) 0, atoi(optarg)); 370 break; 371 case 'i': 372 if (getpid() != 1) 373 msg_fatal("-i is allowed only for PID 1 process"); 374 init_mode = 1; 375 keep_stdout = 1; 376 break; 377 case 'D': 378 debug_me = 1; 379 break; 380 case 's': 381 keep_stdout = 1; 382 break; 383 case 't': 384 test_lock = 1; 385 break; 386 case 'v': 387 msg_verbose++; 388 break; 389 case 'w': 390 wait_flag = 1; 391 break; 392 default: 393 usage(argv[0]); 394 /* NOTREACHED */ 395 } 396 } 397 398 /* 399 * This program takes no other arguments. 400 */ 401 if (argc > optind) 402 usage(argv[0]); 403 404 /* 405 * Sanity check. 406 */ 407 if (test_lock && wait_flag) 408 msg_fatal("the -t and -w options cannot be used together"); 409 if (init_mode && (debug_me || !master_detach || wait_flag)) 410 msg_fatal("the -i option cannot be used with -D, -d, or -w"); 411 412 /* 413 * Run a foreground monitor process that returns an exit status of 0 when 414 * the child background process reports successful initialization as a 415 * daemon process. We use a generous limit in case main/master.cf specify 416 * symbolic hosts/ports and the naming service is slow. 417 */ 418 #define MASTER_INIT_TIMEOUT 100 /* keep this limit generous */ 419 420 if (wait_flag) 421 monitor_fd = master_monitor(MASTER_INIT_TIMEOUT); 422 423 /* 424 * If started from a terminal, get rid of any tty association. This also 425 * means that all errors and warnings must go to the syslog daemon. 426 * Some new world has no terminals and prefers logging to stdout. 427 */ 428 if (master_detach) 429 for (fd = 0; fd < 3; fd++) { 430 if (fd == STDOUT_FILENO && keep_stdout) 431 continue; 432 (void) close(fd); 433 if (open("/dev/null", O_RDWR, 0) != fd) 434 msg_fatal("open /dev/null: %m"); 435 } 436 437 /* 438 * Run in a separate process group, so that "postfix stop" can terminate 439 * all MTA processes cleanly. Give up if we can't separate from our 440 * parent process. We're not supposed to blow away the parent. 441 */ 442 if (init_mode == 0 && debug_me == 0 && master_detach != 0 443 && setsid() == -1 && getsid(0) != getpid()) 444 msg_fatal("unable to set session and process group ID: %m"); 445 446 /* 447 * Make some room for plumbing with file descriptors. XXX This breaks 448 * when a service listens on many ports. In order to do this right we 449 * must change the master-child interface so that descriptors do not need 450 * to have fixed numbers. 451 * 452 * In a child we need two descriptors for the flow control pipe, one for 453 * child->master status updates and at least one for listening. 454 */ 455 for (n = 0; n < 5; n++) { 456 if (close_on_exec(dup(0), CLOSE_ON_EXEC) < 0) 457 msg_fatal("dup(0): %m"); 458 } 459 460 /* 461 * Final initializations. Unfortunately, we must read the global Postfix 462 * configuration file after doing command-line processing, so that we get 463 * consistent results when we SIGHUP the server to reload configuration 464 * files. 465 */ 466 master_vars_init(); 467 468 /* 469 * In case of multi-protocol support. This needs to be done because 470 * master does not invoke mail_params_init() (it was written before that 471 * code existed). 472 */ 473 (void) inet_proto_init(VAR_INET_PROTOCOLS, var_inet_protocols); 474 475 /* 476 * Environment import filter, to enforce consistent behavior whether 477 * Postfix is started by hand, or at system boot time. 478 */ 479 import_env = mail_parm_split(VAR_IMPORT_ENVIRON, var_import_environ); 480 clean_env(import_env->argv); 481 argv_free(import_env); 482 483 if ((inherited_limit = get_file_limit()) < 0) 484 set_file_limit(OFF_T_MAX); 485 486 if (chdir(var_queue_dir)) 487 msg_fatal("chdir %s: %m", var_queue_dir); 488 489 /* 490 * Lock down the master.pid file. In test mode, no file means that it 491 * isn't locked. 492 */ 493 lock_path = vstring_alloc(10); 494 data_lock_path = vstring_alloc(10); 495 why = vstring_alloc(10); 496 497 vstring_sprintf(lock_path, "%s/%s.pid", DEF_PID_DIR, var_procname); 498 if (test_lock && access(vstring_str(lock_path), F_OK) < 0) 499 exit(0); 500 lock_fp = open_lock(vstring_str(lock_path), O_RDWR | O_CREAT, 0644, why); 501 if (test_lock) 502 exit(lock_fp ? 0 : 1); 503 if (lock_fp == 0) 504 msg_fatal("open lock file %s: %s", 505 vstring_str(lock_path), vstring_str(why)); 506 vstream_fprintf(lock_fp, "%*lu\n", (int) sizeof(unsigned long) * 4, 507 (unsigned long) var_pid); 508 if (vstream_fflush(lock_fp)) 509 msg_fatal("cannot update lock file %s: %m", vstring_str(lock_path)); 510 close_on_exec(vstream_fileno(lock_fp), CLOSE_ON_EXEC); 511 512 /* 513 * Lock down the Postfix-writable data directory. 514 */ 515 vstring_sprintf(data_lock_path, "%s/%s.lock", var_data_dir, var_procname); 516 set_eugid(var_owner_uid, var_owner_gid); 517 data_lock_fp = 518 open_lock(vstring_str(data_lock_path), O_RDWR | O_CREAT, 0644, why); 519 set_ugid(getuid(), getgid()); 520 if (data_lock_fp == 0) 521 msg_fatal("open lock file %s: %s", 522 vstring_str(data_lock_path), vstring_str(why)); 523 vstream_fprintf(data_lock_fp, "%*lu\n", (int) sizeof(unsigned long) * 4, 524 (unsigned long) var_pid); 525 if (vstream_fflush(data_lock_fp)) 526 msg_fatal("cannot update lock file %s: %m", vstring_str(data_lock_path)); 527 close_on_exec(vstream_fileno(data_lock_fp), CLOSE_ON_EXEC); 528 529 /* 530 * Clean up. 531 */ 532 vstring_free(why); 533 vstring_free(lock_path); 534 vstring_free(data_lock_path); 535 536 /* 537 * Optionally start the debugger on ourself. 538 */ 539 if (debug_me) 540 debug_process(); 541 542 /* 543 * Finish initialization, last part. We must process configuration files 544 * after processing command-line parameters, so that we get consistent 545 * results when we SIGHUP the server to reload configuration files. 546 */ 547 master_config(); 548 master_sigsetup(); 549 master_flow_init(); 550 maillog_client_init(mail_task(var_procname), 551 MAILLOG_CLIENT_FLAG_LOGWRITER_FALLBACK); 552 msg_info("daemon started -- version %s, configuration %s", 553 var_mail_version, var_config_dir); 554 555 /* 556 * Report successful initialization to the foreground monitor process. 557 */ 558 if (monitor_fd >= 0) { 559 write(monitor_fd, "", 1); 560 (void) close(monitor_fd); 561 } 562 563 /* 564 * Process events. The event handler will execute the read/write/timer 565 * action routines. Whenever something has happened, see if we received 566 * any signal in the mean time. Although the master process appears to do 567 * multiple things at the same time, it really is all a single thread, so 568 * that there are no concurrency conflicts within the master process. 569 */ 570 #define MASTER_WATCHDOG_TIME 1000 571 572 watchdog = watchdog_create(MASTER_WATCHDOG_TIME, (WATCHDOG_FN) 0, (void *) 0); 573 for (;;) { 574 #ifdef HAS_VOLATILE_LOCKS 575 if (myflock(vstream_fileno(lock_fp), INTERNAL_LOCK, 576 MYFLOCK_OP_EXCLUSIVE) < 0) 577 msg_fatal("refresh exclusive lock: %m"); 578 if (myflock(vstream_fileno(data_lock_fp), INTERNAL_LOCK, 579 MYFLOCK_OP_EXCLUSIVE) < 0) 580 msg_fatal("refresh exclusive lock: %m"); 581 #endif 582 watchdog_start(watchdog); /* same as trigger servers */ 583 event_loop(MASTER_WATCHDOG_TIME / 2); 584 if (master_gotsighup) { 585 msg_info("reload -- version %s, configuration %s", 586 var_mail_version, var_config_dir); 587 master_gotsighup = 0; /* this first */ 588 master_vars_init(); /* then this */ 589 master_refresh(); /* then this */ 590 maillog_client_init(mail_task(var_procname), 591 MAILLOG_CLIENT_FLAG_LOGWRITER_FALLBACK); 592 } 593 if (master_gotsigchld) { 594 if (msg_verbose) 595 msg_info("got sigchld"); 596 master_gotsigchld = 0; /* this first */ 597 master_reap_child(); /* then this */ 598 } 599 } 600 } 601