PageRenderTime 63ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/src/src/daemon.c

https://gitlab.com/Exim/exim
C | 2103 lines | 1217 code | 340 blank | 546 comment | 371 complexity | b398103b1da8ca58db117951ee4541cd MD5 | raw file
Possible License(s): GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. /*************************************************
  2. * Exim - an Internet mail transport agent *
  3. *************************************************/
  4. /* Copyright (c) University of Cambridge 1995 - 2014 */
  5. /* See the file NOTICE for conditions of use and distribution. */
  6. /* Functions concerned with running Exim as a daemon */
  7. #include "exim.h"
  8. /* Structure for holding data for each SMTP connection */
  9. typedef struct smtp_slot {
  10. pid_t pid; /* pid of the spawned reception process */
  11. uschar *host_address; /* address of the client host */
  12. } smtp_slot;
  13. /* An empty slot for initializing (Standard C does not allow constructor
  14. expressions in assigments except as initializers in declarations). */
  15. static smtp_slot empty_smtp_slot = { 0, NULL };
  16. /*************************************************
  17. * Local static variables *
  18. *************************************************/
  19. static SIGNAL_BOOL sigchld_seen;
  20. static SIGNAL_BOOL sighup_seen;
  21. static int accept_retry_count = 0;
  22. static int accept_retry_errno;
  23. static BOOL accept_retry_select_failed;
  24. static int queue_run_count = 0;
  25. static pid_t *queue_pid_slots = NULL;
  26. static smtp_slot *smtp_slots = NULL;
  27. static BOOL write_pid = TRUE;
  28. /*************************************************
  29. * SIGHUP Handler *
  30. *************************************************/
  31. /* All this handler does is to set a flag and re-enable the signal.
  32. Argument: the signal number
  33. Returns: nothing
  34. */
  35. static void
  36. sighup_handler(int sig)
  37. {
  38. sig = sig; /* Keep picky compilers happy */
  39. sighup_seen = TRUE;
  40. signal(SIGHUP, sighup_handler);
  41. }
  42. /*************************************************
  43. * SIGCHLD handler for main daemon process *
  44. *************************************************/
  45. /* Don't re-enable the handler here, since we aren't doing the
  46. waiting here. If the signal is re-enabled, there will just be an
  47. infinite sequence of calls to this handler. The SIGCHLD signal is
  48. used just as a means of waking up the daemon so that it notices
  49. terminated subprocesses as soon as possible.
  50. Argument: the signal number
  51. Returns: nothing
  52. */
  53. static void
  54. main_sigchld_handler(int sig)
  55. {
  56. sig = sig; /* Keep picky compilers happy */
  57. os_non_restarting_signal(SIGCHLD, SIG_DFL);
  58. sigchld_seen = TRUE;
  59. }
  60. /*************************************************
  61. * Unexpected errors in SMTP calls *
  62. *************************************************/
  63. /* This function just saves a bit of repetitious coding.
  64. Arguments:
  65. log_msg Text of message to be logged
  66. smtp_msg Text of SMTP error message
  67. was_errno The failing errno
  68. Returns: nothing
  69. */
  70. static void
  71. never_error(uschar *log_msg, uschar *smtp_msg, int was_errno)
  72. {
  73. uschar *emsg = (was_errno <= 0)? US"" :
  74. string_sprintf(": %s", strerror(was_errno));
  75. log_write(0, LOG_MAIN|LOG_PANIC, "%s%s", log_msg, emsg);
  76. if (smtp_out != NULL) smtp_printf("421 %s\r\n", smtp_msg);
  77. }
  78. /*************************************************
  79. * Handle a connected SMTP call *
  80. *************************************************/
  81. /* This function is called when an SMTP connection has been accepted.
  82. If there are too many, give an error message and close down. Otherwise
  83. spin off a sub-process to handle the call. The list of listening sockets
  84. is required so that they can be closed in the sub-process. Take care not to
  85. leak store in this process - reset the stacking pool at the end.
  86. Arguments:
  87. listen_sockets sockets which are listening for incoming calls
  88. listen_socket_count count of listening sockets
  89. accept_socket socket of the current accepted call
  90. accepted socket information about the current call
  91. Returns: nothing
  92. */
  93. static void
  94. handle_smtp_call(int *listen_sockets, int listen_socket_count,
  95. int accept_socket, struct sockaddr *accepted)
  96. {
  97. pid_t pid;
  98. union sockaddr_46 interface_sockaddr;
  99. EXIM_SOCKLEN_T ifsize = sizeof(interface_sockaddr);
  100. int dup_accept_socket = -1;
  101. int max_for_this_host = 0;
  102. int wfsize = 0;
  103. int wfptr = 0;
  104. int use_log_write_selector = log_write_selector;
  105. uschar *whofrom = NULL;
  106. void *reset_point = store_get(0);
  107. /* Make the address available in ASCII representation, and also fish out
  108. the remote port. */
  109. sender_host_address = host_ntoa(-1, accepted, NULL, &sender_host_port);
  110. DEBUG(D_any) debug_printf("Connection request from %s port %d\n",
  111. sender_host_address, sender_host_port);
  112. /* Set up the output stream, check the socket has duplicated, and set up the
  113. input stream. These operations fail only the exceptional circumstances. Note
  114. that never_error() won't use smtp_out if it is NULL. */
  115. smtp_out = fdopen(accept_socket, "wb");
  116. if (smtp_out == NULL)
  117. {
  118. never_error(US"daemon: fdopen() for smtp_out failed", US"", errno);
  119. goto ERROR_RETURN;
  120. }
  121. dup_accept_socket = dup(accept_socket);
  122. if (dup_accept_socket < 0)
  123. {
  124. never_error(US"daemon: couldn't dup socket descriptor",
  125. US"Connection setup failed", errno);
  126. goto ERROR_RETURN;
  127. }
  128. smtp_in = fdopen(dup_accept_socket, "rb");
  129. if (smtp_in == NULL)
  130. {
  131. never_error(US"daemon: fdopen() for smtp_in failed",
  132. US"Connection setup failed", errno);
  133. goto ERROR_RETURN;
  134. }
  135. /* Get the data for the local interface address. Panic for most errors, but
  136. "connection reset by peer" just means the connection went away. */
  137. if (getsockname(accept_socket, (struct sockaddr *)(&interface_sockaddr),
  138. &ifsize) < 0)
  139. {
  140. log_write(0, LOG_MAIN | ((errno == ECONNRESET)? 0 : LOG_PANIC),
  141. "getsockname() failed: %s", strerror(errno));
  142. smtp_printf("421 Local problem: getsockname() failed; please try again later\r\n");
  143. goto ERROR_RETURN;
  144. }
  145. interface_address = host_ntoa(-1, &interface_sockaddr, NULL, &interface_port);
  146. DEBUG(D_interface) debug_printf("interface address=%s port=%d\n",
  147. interface_address, interface_port);
  148. /* Build a string identifying the remote host and, if requested, the port and
  149. the local interface data. This is for logging; at the end of this function the
  150. memory is reclaimed. */
  151. whofrom = string_append(whofrom, &wfsize, &wfptr, 3, "[", sender_host_address, "]");
  152. if ((log_extra_selector & LX_incoming_port) != 0)
  153. whofrom = string_append(whofrom, &wfsize, &wfptr, 2, ":", string_sprintf("%d",
  154. sender_host_port));
  155. if ((log_extra_selector & LX_incoming_interface) != 0)
  156. whofrom = string_append(whofrom, &wfsize, &wfptr, 4, " I=[",
  157. interface_address, "]:", string_sprintf("%d", interface_port));
  158. whofrom[wfptr] = 0; /* Terminate the newly-built string */
  159. /* Check maximum number of connections. We do not check for reserved
  160. connections or unacceptable hosts here. That is done in the subprocess because
  161. it might take some time. */
  162. if (smtp_accept_max > 0 && smtp_accept_count >= smtp_accept_max)
  163. {
  164. DEBUG(D_any) debug_printf("rejecting SMTP connection: count=%d max=%d\n",
  165. smtp_accept_count, smtp_accept_max);
  166. smtp_printf("421 Too many concurrent SMTP connections; "
  167. "please try again later.\r\n");
  168. log_write(L_connection_reject,
  169. LOG_MAIN, "Connection from %s refused: too many connections",
  170. whofrom);
  171. goto ERROR_RETURN;
  172. }
  173. /* If a load limit above which only reserved hosts are acceptable is defined,
  174. get the load average here, and if there are in fact no reserved hosts, do
  175. the test right away (saves a fork). If there are hosts, do the check in the
  176. subprocess because it might take time. */
  177. if (smtp_load_reserve >= 0)
  178. {
  179. load_average = OS_GETLOADAVG();
  180. if (smtp_reserve_hosts == NULL && load_average > smtp_load_reserve)
  181. {
  182. DEBUG(D_any) debug_printf("rejecting SMTP connection: load average = %.2f\n",
  183. (double)load_average/1000.0);
  184. smtp_printf("421 Too much load; please try again later.\r\n");
  185. log_write(L_connection_reject,
  186. LOG_MAIN, "Connection from %s refused: load average = %.2f",
  187. whofrom, (double)load_average/1000.0);
  188. goto ERROR_RETURN;
  189. }
  190. }
  191. /* Check that one specific host (strictly, IP address) is not hogging
  192. resources. This is done here to prevent a denial of service attack by someone
  193. forcing you to fork lots of times before denying service. The value of
  194. smtp_accept_max_per_host is a string which is expanded. This makes it possible
  195. to provide host-specific limits according to $sender_host address, but because
  196. this is in the daemon mainline, only fast expansions (such as inline address
  197. checks) should be used. The documentation is full of warnings. */
  198. if (smtp_accept_max_per_host != NULL)
  199. {
  200. uschar *expanded = expand_string(smtp_accept_max_per_host);
  201. if (expanded == NULL)
  202. {
  203. if (!expand_string_forcedfail)
  204. log_write(0, LOG_MAIN|LOG_PANIC, "expansion of smtp_accept_max_per_host "
  205. "failed for %s: %s", whofrom, expand_string_message);
  206. }
  207. /* For speed, interpret a decimal number inline here */
  208. else
  209. {
  210. uschar *s = expanded;
  211. while (isdigit(*s))
  212. max_for_this_host = max_for_this_host * 10 + *s++ - '0';
  213. if (*s != 0)
  214. log_write(0, LOG_MAIN|LOG_PANIC, "expansion of smtp_accept_max_per_host "
  215. "for %s contains non-digit: %s", whofrom, expanded);
  216. }
  217. }
  218. /* If we have fewer connections than max_for_this_host, we can skip the tedious
  219. per host_address checks. Note that at this stage smtp_accept_count contains the
  220. count of *other* connections, not including this one. */
  221. if ((max_for_this_host > 0) &&
  222. (smtp_accept_count >= max_for_this_host))
  223. {
  224. int i;
  225. int host_accept_count = 0;
  226. int other_host_count = 0; /* keep a count of non matches to optimise */
  227. for (i = 0; i < smtp_accept_max; ++i)
  228. {
  229. if (smtp_slots[i].host_address != NULL)
  230. {
  231. if (Ustrcmp(sender_host_address, smtp_slots[i].host_address) == 0)
  232. host_accept_count++;
  233. else
  234. other_host_count++;
  235. /* Testing all these strings is expensive - see if we can drop out
  236. early, either by hitting the target, or finding there are not enough
  237. connections left to make the target. */
  238. if ((host_accept_count >= max_for_this_host) ||
  239. ((smtp_accept_count - other_host_count) < max_for_this_host))
  240. break;
  241. }
  242. }
  243. if (host_accept_count >= max_for_this_host)
  244. {
  245. DEBUG(D_any) debug_printf("rejecting SMTP connection: too many from this "
  246. "IP address: count=%d max=%d\n",
  247. host_accept_count, max_for_this_host);
  248. smtp_printf("421 Too many concurrent SMTP connections "
  249. "from this IP address; please try again later.\r\n");
  250. log_write(L_connection_reject,
  251. LOG_MAIN, "Connection from %s refused: too many connections "
  252. "from that IP address", whofrom);
  253. goto ERROR_RETURN;
  254. }
  255. }
  256. /* OK, the connection count checks have been passed. Before we can fork the
  257. accepting process, we must first log the connection if requested. This logging
  258. used to happen in the subprocess, but doing that means that the value of
  259. smtp_accept_count can be out of step by the time it is logged. So we have to do
  260. the logging here and accept the performance cost. Note that smtp_accept_count
  261. hasn't yet been incremented to take account of this connection.
  262. In order to minimize the cost (because this is going to happen for every
  263. connection), do a preliminary selector test here. This saves ploughing through
  264. the generalized logging code each time when the selector is false. If the
  265. selector is set, check whether the host is on the list for logging. If not,
  266. arrange to unset the selector in the subprocess. */
  267. if ((log_write_selector & L_smtp_connection) != 0)
  268. {
  269. uschar *list = hosts_connection_nolog;
  270. if (list != NULL && verify_check_host(&list) == OK)
  271. use_log_write_selector &= ~L_smtp_connection;
  272. else
  273. log_write(L_smtp_connection, LOG_MAIN, "SMTP connection from %s "
  274. "(TCP/IP connection count = %d)", whofrom, smtp_accept_count + 1);
  275. }
  276. /* Now we can fork the accepting process; do a lookup tidy, just in case any
  277. expansion above did a lookup. */
  278. search_tidyup();
  279. pid = fork();
  280. /* Handle the child process */
  281. if (pid == 0)
  282. {
  283. int i;
  284. int queue_only_reason = 0;
  285. int old_pool = store_pool;
  286. int save_debug_selector = debug_selector;
  287. BOOL local_queue_only;
  288. BOOL session_local_queue_only;
  289. #ifdef SA_NOCLDWAIT
  290. struct sigaction act;
  291. #endif
  292. smtp_accept_count++; /* So that it includes this process */
  293. /* May have been modified for the subprocess */
  294. log_write_selector = use_log_write_selector;
  295. /* Get the local interface address into permanent store */
  296. store_pool = POOL_PERM;
  297. interface_address = string_copy(interface_address);
  298. store_pool = old_pool;
  299. /* Check for a tls-on-connect port */
  300. if (host_is_tls_on_connect_port(interface_port)) tls_in.on_connect = TRUE;
  301. /* Expand smtp_active_hostname if required. We do not do this any earlier,
  302. because it may depend on the local interface address (indeed, that is most
  303. likely what it depends on.) */
  304. smtp_active_hostname = primary_hostname;
  305. if (raw_active_hostname != NULL)
  306. {
  307. uschar *nah = expand_string(raw_active_hostname);
  308. if (nah == NULL)
  309. {
  310. if (!expand_string_forcedfail)
  311. {
  312. log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand \"%s\" "
  313. "(smtp_active_hostname): %s", raw_active_hostname,
  314. expand_string_message);
  315. smtp_printf("421 Local configuration error; "
  316. "please try again later.\r\n");
  317. mac_smtp_fflush();
  318. search_tidyup();
  319. _exit(EXIT_FAILURE);
  320. }
  321. }
  322. else if (nah[0] != 0) smtp_active_hostname = nah;
  323. }
  324. /* Initialize the queueing flags */
  325. queue_check_only();
  326. session_local_queue_only = queue_only;
  327. /* Close the listening sockets, and set the SIGCHLD handler to SIG_IGN.
  328. We also attempt to set things up so that children are automatically reaped,
  329. but just in case this isn't available, there's a paranoid waitpid() in the
  330. loop too (except for systems where we are sure it isn't needed). See the more
  331. extensive comment before the reception loop in exim.c for a fuller
  332. explanation of this logic. */
  333. for (i = 0; i < listen_socket_count; i++) (void)close(listen_sockets[i]);
  334. /* Set FD_CLOEXEC on the SMTP socket. We don't want any rogue child processes
  335. to be able to communicate with them, under any circumstances. */
  336. (void)fcntl(accept_socket, F_SETFD,
  337. fcntl(accept_socket, F_GETFD) | FD_CLOEXEC);
  338. (void)fcntl(dup_accept_socket, F_SETFD,
  339. fcntl(dup_accept_socket, F_GETFD) | FD_CLOEXEC);
  340. #ifdef SA_NOCLDWAIT
  341. act.sa_handler = SIG_IGN;
  342. sigemptyset(&(act.sa_mask));
  343. act.sa_flags = SA_NOCLDWAIT;
  344. sigaction(SIGCHLD, &act, NULL);
  345. #else
  346. signal(SIGCHLD, SIG_IGN);
  347. #endif
  348. /* Attempt to get an id from the sending machine via the RFC 1413
  349. protocol. We do this in the sub-process in order not to hold up the
  350. main process if there is any delay. Then set up the fullhost information
  351. in case there is no HELO/EHLO.
  352. If debugging is enabled only for the daemon, we must turn if off while
  353. finding the id, but turn it on again afterwards so that information about the
  354. incoming connection is output. */
  355. if (debug_daemon) debug_selector = 0;
  356. verify_get_ident(IDENT_PORT);
  357. host_build_sender_fullhost();
  358. debug_selector = save_debug_selector;
  359. DEBUG(D_any)
  360. debug_printf("Process %d is handling incoming connection from %s\n",
  361. (int)getpid(), sender_fullhost);
  362. /* Now disable debugging permanently if it's required only for the daemon
  363. process. */
  364. if (debug_daemon) debug_selector = 0;
  365. /* If there are too many child processes for immediate delivery,
  366. set the session_local_queue_only flag, which is initialized from the
  367. configured value and may therefore already be TRUE. Leave logging
  368. till later so it will have a message id attached. Note that there is no
  369. possibility of re-calculating this per-message, because the value of
  370. smtp_accept_count does not change in this subprocess. */
  371. if (smtp_accept_queue > 0 && smtp_accept_count > smtp_accept_queue)
  372. {
  373. session_local_queue_only = TRUE;
  374. queue_only_reason = 1;
  375. }
  376. /* Handle the start of the SMTP session, then loop, accepting incoming
  377. messages from the SMTP connection. The end will come at the QUIT command,
  378. when smtp_setup_msg() returns 0. A break in the connection causes the
  379. process to die (see accept.c).
  380. NOTE: We do *not* call smtp_log_no_mail() if smtp_start_session() fails,
  381. because a log line has already been written for all its failure exists
  382. (usually "connection refused: <reason>") and writing another one is
  383. unnecessary clutter. */
  384. if (!smtp_start_session())
  385. {
  386. mac_smtp_fflush();
  387. search_tidyup();
  388. _exit(EXIT_SUCCESS);
  389. }
  390. for (;;)
  391. {
  392. int rc;
  393. message_id[0] = 0; /* Clear out any previous message_id */
  394. reset_point = store_get(0); /* Save current store high water point */
  395. DEBUG(D_any)
  396. debug_printf("Process %d is ready for new message\n", (int)getpid());
  397. /* Smtp_setup_msg() returns 0 on QUIT or if the call is from an
  398. unacceptable host or if an ACL "drop" command was triggered, -1 on
  399. connection lost, and +1 on validly reaching DATA. Receive_msg() almost
  400. always returns TRUE when smtp_input is true; just retry if no message was
  401. accepted (can happen for invalid message parameters). However, it can yield
  402. FALSE if the connection was forcibly dropped by the DATA ACL. */
  403. if ((rc = smtp_setup_msg()) > 0)
  404. {
  405. BOOL ok = receive_msg(FALSE);
  406. search_tidyup(); /* Close cached databases */
  407. if (!ok) /* Connection was dropped */
  408. {
  409. mac_smtp_fflush();
  410. smtp_log_no_mail(); /* Log no mail if configured */
  411. _exit(EXIT_SUCCESS);
  412. }
  413. if (message_id[0] == 0) continue; /* No message was accepted */
  414. }
  415. else
  416. {
  417. mac_smtp_fflush();
  418. search_tidyup();
  419. smtp_log_no_mail(); /* Log no mail if configured */
  420. _exit((rc == 0)? EXIT_SUCCESS : EXIT_FAILURE);
  421. }
  422. /* Show the recipients when debugging */
  423. DEBUG(D_receive)
  424. {
  425. int i;
  426. if (sender_address != NULL)
  427. debug_printf("Sender: %s\n", sender_address);
  428. if (recipients_list != NULL)
  429. {
  430. debug_printf("Recipients:\n");
  431. for (i = 0; i < recipients_count; i++)
  432. debug_printf(" %s\n", recipients_list[i].address);
  433. }
  434. }
  435. /* A message has been accepted. Clean up any previous delivery processes
  436. that have completed and are defunct, on systems where they don't go away
  437. by themselves (see comments when setting SIG_IGN above). On such systems
  438. (if any) these delivery processes hang around after termination until
  439. the next message is received. */
  440. #ifndef SIG_IGN_WORKS
  441. while (waitpid(-1, NULL, WNOHANG) > 0);
  442. #endif
  443. /* Reclaim up the store used in accepting this message */
  444. store_reset(reset_point);
  445. /* If queue_only is set or if there are too many incoming connections in
  446. existence, session_local_queue_only will be TRUE. If it is not, check
  447. whether we have received too many messages in this session for immediate
  448. delivery. */
  449. if (!session_local_queue_only &&
  450. smtp_accept_queue_per_connection > 0 &&
  451. receive_messagecount > smtp_accept_queue_per_connection)
  452. {
  453. session_local_queue_only = TRUE;
  454. queue_only_reason = 2;
  455. }
  456. /* Initialize local_queue_only from session_local_queue_only. If it is not
  457. true, and queue_only_load is set, check that the load average is below it.
  458. If local_queue_only is set by this means, we also set if for the session if
  459. queue_only_load_latch is true (the default). This means that, once set,
  460. local_queue_only remains set for any subsequent messages on the same SMTP
  461. connection. This is a deliberate choice; even though the load average may
  462. fall, it doesn't seem right to deliver later messages on the same call when
  463. not delivering earlier ones. However, the are special circumstances such as
  464. very long-lived connections from scanning appliances where this is not the
  465. best strategy. In such cases, queue_only_load_latch should be set false. */
  466. local_queue_only = session_local_queue_only;
  467. if (!local_queue_only && queue_only_load >= 0)
  468. {
  469. local_queue_only = (load_average = OS_GETLOADAVG()) > queue_only_load;
  470. if (local_queue_only)
  471. {
  472. queue_only_reason = 3;
  473. if (queue_only_load_latch) session_local_queue_only = TRUE;
  474. }
  475. }
  476. /* Log the queueing here, when it will get a message id attached, but
  477. not if queue_only is set (case 0). */
  478. if (local_queue_only) switch(queue_only_reason)
  479. {
  480. case 1:
  481. log_write(L_delay_delivery,
  482. LOG_MAIN, "no immediate delivery: too many connections "
  483. "(%d, max %d)", smtp_accept_count, smtp_accept_queue);
  484. break;
  485. case 2:
  486. log_write(L_delay_delivery,
  487. LOG_MAIN, "no immediate delivery: more than %d messages "
  488. "received in one connection", smtp_accept_queue_per_connection);
  489. break;
  490. case 3:
  491. log_write(L_delay_delivery,
  492. LOG_MAIN, "no immediate delivery: load average %.2f",
  493. (double)load_average/1000.0);
  494. break;
  495. }
  496. /* If a delivery attempt is required, spin off a new process to handle it.
  497. If we are not root, we have to re-exec exim unless deliveries are being
  498. done unprivileged. */
  499. else if (!queue_only_policy && !deliver_freeze)
  500. {
  501. pid_t dpid;
  502. /* Before forking, ensure that the C output buffer is flushed. Otherwise
  503. anything that it in it will get duplicated, leading to duplicate copies
  504. of the pending output. */
  505. mac_smtp_fflush();
  506. if ((dpid = fork()) == 0)
  507. {
  508. (void)fclose(smtp_in);
  509. (void)fclose(smtp_out);
  510. /* Don't ever molest the parent's SSL connection, but do clean up
  511. the data structures if necessary. */
  512. #ifdef SUPPORT_TLS
  513. tls_close(TRUE, FALSE);
  514. #endif
  515. /* Reset SIGHUP and SIGCHLD in the child in both cases. */
  516. signal(SIGHUP, SIG_DFL);
  517. signal(SIGCHLD, SIG_DFL);
  518. if (geteuid() != root_uid && !deliver_drop_privilege)
  519. {
  520. signal(SIGALRM, SIG_DFL);
  521. (void)child_exec_exim(CEE_EXEC_PANIC, FALSE, NULL, FALSE, 2, US"-Mc",
  522. message_id);
  523. /* Control does not return here. */
  524. }
  525. /* No need to re-exec; SIGALRM remains set to the default handler */
  526. (void)deliver_message(message_id, FALSE, FALSE);
  527. search_tidyup();
  528. _exit(EXIT_SUCCESS);
  529. }
  530. if (dpid > 0)
  531. {
  532. DEBUG(D_any) debug_printf("forked delivery process %d\n", (int)dpid);
  533. }
  534. else
  535. {
  536. log_write(0, LOG_MAIN|LOG_PANIC, "daemon: delivery process fork "
  537. "failed: %s", strerror(errno));
  538. }
  539. }
  540. }
  541. }
  542. /* Carrying on in the parent daemon process... Can't do much if the fork
  543. failed. Otherwise, keep count of the number of accepting processes and
  544. remember the pid for ticking off when the child completes. */
  545. if (pid < 0)
  546. {
  547. never_error(US"daemon: accept process fork failed", US"Fork failed", errno);
  548. }
  549. else
  550. {
  551. int i;
  552. for (i = 0; i < smtp_accept_max; ++i)
  553. {
  554. if (smtp_slots[i].pid <= 0)
  555. {
  556. smtp_slots[i].pid = pid;
  557. if (smtp_accept_max_per_host != NULL)
  558. smtp_slots[i].host_address = string_copy_malloc(sender_host_address);
  559. smtp_accept_count++;
  560. break;
  561. }
  562. }
  563. DEBUG(D_any) debug_printf("%d SMTP accept process%s running\n",
  564. smtp_accept_count, (smtp_accept_count == 1)? "" : "es");
  565. }
  566. /* Get here via goto in error cases */
  567. ERROR_RETURN:
  568. /* Close the streams associated with the socket which will also close the
  569. socket fds in this process. We can't do anything if fclose() fails, but
  570. logging brings it to someone's attention. However, "connection reset by peer"
  571. isn't really a problem, so skip that one. On Solaris, a dropped connection can
  572. manifest itself as a broken pipe, so drop that one too. If the streams don't
  573. exist, something went wrong while setting things up. Make sure the socket
  574. descriptors are closed, in order to drop the connection. */
  575. if (smtp_out != NULL)
  576. {
  577. if (fclose(smtp_out) != 0 && errno != ECONNRESET && errno != EPIPE)
  578. log_write(0, LOG_MAIN|LOG_PANIC, "daemon: fclose(smtp_out) failed: %s",
  579. strerror(errno));
  580. smtp_out = NULL;
  581. }
  582. else (void)close(accept_socket);
  583. if (smtp_in != NULL)
  584. {
  585. if (fclose(smtp_in) != 0 && errno != ECONNRESET && errno != EPIPE)
  586. log_write(0, LOG_MAIN|LOG_PANIC, "daemon: fclose(smtp_in) failed: %s",
  587. strerror(errno));
  588. smtp_in = NULL;
  589. }
  590. else (void)close(dup_accept_socket);
  591. /* Release any store used in this process, including the store used for holding
  592. the incoming host address and an expanded active_hostname. */
  593. store_reset(reset_point);
  594. sender_host_address = NULL;
  595. }
  596. /*************************************************
  597. * Check wildcard listen special cases *
  598. *************************************************/
  599. /* This function is used when binding and listening on lists of addresses and
  600. ports. It tests for special cases of wildcard listening, when IPv4 and IPv6
  601. sockets may interact in different ways in different operating systems. It is
  602. passed an error number, the list of listening addresses, and the current
  603. address. Two checks are available: for a previous wildcard IPv6 address, or for
  604. a following wildcard IPv4 address, in both cases on the same port.
  605. In practice, pairs of wildcard addresses should be adjacent in the address list
  606. because they are sorted that way below.
  607. Arguments:
  608. eno the error number
  609. addresses the list of addresses
  610. ipa the current IP address
  611. back if TRUE, check for previous wildcard IPv6 address
  612. if FALSE, check for a following wildcard IPv4 address
  613. Returns: TRUE or FALSE
  614. */
  615. static BOOL
  616. check_special_case(int eno, ip_address_item *addresses, ip_address_item *ipa,
  617. BOOL back)
  618. {
  619. ip_address_item *ipa2;
  620. /* For the "back" case, if the failure was "address in use" for a wildcard IPv4
  621. address, seek a previous IPv6 wildcard address on the same port. As it is
  622. previous, it must have been successfully bound and be listening. Flag it as a
  623. "6 including 4" listener. */
  624. if (back)
  625. {
  626. if (eno != EADDRINUSE || ipa->address[0] != 0) return FALSE;
  627. for (ipa2 = addresses; ipa2 != ipa; ipa2 = ipa2->next)
  628. {
  629. if (ipa2->address[1] == 0 && ipa2->port == ipa->port)
  630. {
  631. ipa2->v6_include_v4 = TRUE;
  632. return TRUE;
  633. }
  634. }
  635. }
  636. /* For the "forward" case, if the current address is a wildcard IPv6 address,
  637. we seek a following wildcard IPv4 address on the same port. */
  638. else
  639. {
  640. if (ipa->address[0] != ':' || ipa->address[1] != 0) return FALSE;
  641. for (ipa2 = ipa->next; ipa2 != NULL; ipa2 = ipa2->next)
  642. if (ipa2->address[0] == 0 && ipa->port == ipa2->port) return TRUE;
  643. }
  644. return FALSE;
  645. }
  646. /*************************************************
  647. * Handle terminating subprocesses *
  648. *************************************************/
  649. /* Handle the termination of child processes. Theoretically, this need be done
  650. only when sigchld_seen is TRUE, but rumour has it that some systems lose
  651. SIGCHLD signals at busy times, so to be on the safe side, this function is
  652. called each time round. It shouldn't be too expensive.
  653. Arguments: none
  654. Returns: nothing
  655. */
  656. static void
  657. handle_ending_processes(void)
  658. {
  659. int status;
  660. pid_t pid;
  661. while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
  662. {
  663. int i;
  664. DEBUG(D_any)
  665. {
  666. debug_printf("child %d ended: status=0x%x\n", (int)pid, status);
  667. #ifdef WCOREDUMP
  668. if (WIFEXITED(status))
  669. debug_printf(" normal exit, %d\n", WEXITSTATUS(status));
  670. else if (WIFSIGNALED(status))
  671. debug_printf(" signal exit, signal %d%s\n", WTERMSIG(status),
  672. WCOREDUMP(status) ? " (core dumped)" : "");
  673. #endif
  674. }
  675. /* If it's a listening daemon for which we are keeping track of individual
  676. subprocesses, deal with an accepting process that has terminated. */
  677. if (smtp_slots != NULL)
  678. {
  679. for (i = 0; i < smtp_accept_max; i++)
  680. {
  681. if (smtp_slots[i].pid == pid)
  682. {
  683. if (smtp_slots[i].host_address != NULL)
  684. store_free(smtp_slots[i].host_address);
  685. smtp_slots[i] = empty_smtp_slot;
  686. if (--smtp_accept_count < 0) smtp_accept_count = 0;
  687. DEBUG(D_any) debug_printf("%d SMTP accept process%s now running\n",
  688. smtp_accept_count, (smtp_accept_count == 1)? "" : "es");
  689. break;
  690. }
  691. }
  692. if (i < smtp_accept_max) continue; /* Found an accepting process */
  693. }
  694. /* If it wasn't an accepting process, see if it was a queue-runner
  695. process that we are tracking. */
  696. if (queue_pid_slots != NULL)
  697. {
  698. for (i = 0; i < queue_run_max; i++)
  699. {
  700. if (queue_pid_slots[i] == pid)
  701. {
  702. queue_pid_slots[i] = 0;
  703. if (--queue_run_count < 0) queue_run_count = 0;
  704. DEBUG(D_any) debug_printf("%d queue-runner process%s now running\n",
  705. queue_run_count, (queue_run_count == 1)? "" : "es");
  706. break;
  707. }
  708. }
  709. }
  710. }
  711. }
  712. /*************************************************
  713. * Exim Daemon Mainline *
  714. *************************************************/
  715. /* The daemon can do two jobs, either of which is optional:
  716. (1) Listens for incoming SMTP calls and spawns off a sub-process to handle
  717. each one. This is requested by the -bd option, with -oX specifying the SMTP
  718. port on which to listen (for testing).
  719. (2) Spawns a queue-running process every so often. This is controlled by the
  720. -q option with a an interval time. (If no time is given, a single queue run
  721. is done from the main function, and control doesn't get here.)
  722. Root privilege is required in order to attach to port 25. Some systems require
  723. it when calling socket() rather than bind(). To cope with all cases, we run as
  724. root for both socket() and bind(). Some systems also require root in order to
  725. write to the pid file directory. This function must therefore be called as root
  726. if it is to work properly in all circumstances. Once the socket is bound and
  727. the pid file written, root privilege is given up if there is an exim uid.
  728. There are no arguments to this function, and it never returns. */
  729. void
  730. daemon_go(void)
  731. {
  732. struct passwd *pw;
  733. int *listen_sockets = NULL;
  734. int listen_socket_count = 0;
  735. ip_address_item *addresses = NULL;
  736. time_t last_connection_time = (time_t)0;
  737. /* If any debugging options are set, turn on the D_pid bit so that all
  738. debugging lines get the pid added. */
  739. DEBUG(D_any|D_v) debug_selector |= D_pid;
  740. if (inetd_wait_mode)
  741. {
  742. int on = 1;
  743. listen_socket_count = 1;
  744. listen_sockets = store_get(sizeof(int *));
  745. (void) close(3);
  746. if (dup2(0, 3) == -1)
  747. {
  748. log_write(0, LOG_MAIN|LOG_PANIC_DIE,
  749. "failed to dup inetd socket safely away: %s", strerror(errno));
  750. }
  751. listen_sockets[0] = 3;
  752. (void) close(0);
  753. (void) close(1);
  754. (void) close(2);
  755. exim_nullstd();
  756. if (debug_file == stderr)
  757. {
  758. /* need a call to log_write before call to open debug_file, so that
  759. log.c:file_path has been initialised. This is unfortunate. */
  760. log_write(0, LOG_MAIN, "debugging Exim in inetd wait mode starting");
  761. fclose(debug_file);
  762. debug_file = NULL;
  763. exim_nullstd(); /* re-open fd2 after we just closed it again */
  764. debug_logging_activate(US"-wait", NULL);
  765. }
  766. DEBUG(D_any) debug_printf("running in inetd wait mode\n");
  767. /* As per below, when creating sockets ourselves, we handle tcp_nodelay for
  768. our own buffering; we assume though that inetd set the socket REUSEADDR. */
  769. if (tcp_nodelay) setsockopt(3, IPPROTO_TCP, TCP_NODELAY,
  770. (uschar *)(&on), sizeof(on));
  771. }
  772. if (inetd_wait_mode || daemon_listen)
  773. {
  774. /* If any option requiring a load average to be available during the
  775. reception of a message is set, call os_getloadavg() while we are root
  776. for those OS for which this is necessary the first time it is called (in
  777. order to perform an "open" on the kernel memory file). */
  778. #ifdef LOAD_AVG_NEEDS_ROOT
  779. if (queue_only_load >= 0 || smtp_load_reserve >= 0 ||
  780. (deliver_queue_load_max >= 0 && deliver_drop_privilege))
  781. (void)os_getloadavg();
  782. #endif
  783. }
  784. /* Do the preparation for setting up a listener on one or more interfaces, and
  785. possible on various ports. This is controlled by the combination of
  786. local_interfaces (which can set IP addresses and ports) and daemon_smtp_port
  787. (which is a list of default ports to use for those items in local_interfaces
  788. that do not specify a port). The -oX command line option can be used to
  789. override one or both of these options.
  790. If local_interfaces is not set, the default is to listen on all interfaces.
  791. When it is set, it can include "all IPvx interfaces" as an item. This is useful
  792. when different ports are in use.
  793. It turns out that listening on all interfaces is messy in an IPv6 world,
  794. because several different implementation approaches have been taken. This code
  795. is now supposed to work with all of them. The point of difference is whether an
  796. IPv6 socket that is listening on all interfaces will receive incoming IPv4
  797. calls or not. We also have to cope with the case when IPv6 libraries exist, but
  798. there is no IPv6 support in the kernel.
  799. . On Solaris, an IPv6 socket will accept IPv4 calls, and give them as mapped
  800. addresses. However, if an IPv4 socket is also listening on all interfaces,
  801. calls are directed to the appropriate socket.
  802. . On (some versions of) Linux, an IPv6 socket will accept IPv4 calls, and
  803. give them as mapped addresses, but an attempt also to listen on an IPv4
  804. socket on all interfaces causes an error.
  805. . On OpenBSD, an IPv6 socket will not accept IPv4 calls. You have to set up
  806. two sockets if you want to accept both kinds of call.
  807. . FreeBSD is like OpenBSD, but it has the IPV6_V6ONLY socket option, which
  808. can be turned off, to make it behave like the versions of Linux described
  809. above.
  810. . I heard a report that the USAGI IPv6 stack for Linux has implemented
  811. IPV6_V6ONLY.
  812. So, what we do when IPv6 is supported is as follows:
  813. (1) After it is set up, the list of interfaces is scanned for wildcard
  814. addresses. If an IPv6 and an IPv4 wildcard are both found for the same
  815. port, the list is re-arranged so that they are together, with the IPv6
  816. wildcard first.
  817. (2) If the creation of a wildcard IPv6 socket fails, we just log the error and
  818. carry on if an IPv4 wildcard socket for the same port follows later in the
  819. list. This allows Exim to carry on in the case when the kernel has no IPv6
  820. support.
  821. (3) Having created an IPv6 wildcard socket, we try to set IPV6_V6ONLY if that
  822. option is defined. However, if setting fails, carry on regardless (but log
  823. the incident).
  824. (4) If binding or listening on an IPv6 wildcard socket fails, it is a serious
  825. error.
  826. (5) If binding or listening on an IPv4 wildcard socket fails with the error
  827. EADDRINUSE, and a previous interface was an IPv6 wildcard for the same
  828. port (which must have succeeded or we wouldn't have got this far), we
  829. assume we are in the situation where just a single socket is permitted,
  830. and ignore the error.
  831. Phew!
  832. The preparation code decodes options and sets up the relevant data. We do this
  833. first, so that we can return non-zero if there are any syntax errors, and also
  834. write to stderr. */
  835. if (daemon_listen && !inetd_wait_mode)
  836. {
  837. int *default_smtp_port;
  838. int sep;
  839. int pct = 0;
  840. uschar *s;
  841. const uschar * list;
  842. uschar *local_iface_source = US"local_interfaces";
  843. ip_address_item *ipa;
  844. ip_address_item **pipa;
  845. /* If -oX was used, disable the writing of a pid file unless -oP was
  846. explicitly used to force it. Then scan the string given to -oX. Any items
  847. that contain neither a dot nor a colon are used to override daemon_smtp_port.
  848. Any other items are used to override local_interfaces. */
  849. if (override_local_interfaces != NULL)
  850. {
  851. uschar *new_smtp_port = NULL;
  852. uschar *new_local_interfaces = NULL;
  853. int portsize = 0;
  854. int portptr = 0;
  855. int ifacesize = 0;
  856. int ifaceptr = 0;
  857. if (override_pid_file_path == NULL) write_pid = FALSE;
  858. list = override_local_interfaces;
  859. sep = 0;
  860. while ((s = string_nextinlist(&list, &sep, big_buffer, big_buffer_size)))
  861. {
  862. uschar joinstr[4];
  863. uschar **ptr;
  864. int *sizeptr;
  865. int *ptrptr;
  866. if (Ustrpbrk(s, ".:") == NULL)
  867. {
  868. ptr = &new_smtp_port;
  869. sizeptr = &portsize;
  870. ptrptr = &portptr;
  871. }
  872. else
  873. {
  874. ptr = &new_local_interfaces;
  875. sizeptr = &ifacesize;
  876. ptrptr = &ifaceptr;
  877. }
  878. if (*ptr == NULL)
  879. {
  880. joinstr[0] = sep;
  881. joinstr[1] = ' ';
  882. *ptr = string_cat(*ptr, sizeptr, ptrptr, US"<", 1);
  883. }
  884. *ptr = string_cat(*ptr, sizeptr, ptrptr, joinstr, 2);
  885. *ptr = string_cat(*ptr, sizeptr, ptrptr, s, Ustrlen(s));
  886. }
  887. if (new_smtp_port != NULL)
  888. {
  889. new_smtp_port[portptr] = 0;
  890. daemon_smtp_port = new_smtp_port;
  891. DEBUG(D_any) debug_printf("daemon_smtp_port overridden by -oX:\n %s\n",
  892. daemon_smtp_port);
  893. }
  894. if (new_local_interfaces != NULL)
  895. {
  896. new_local_interfaces[ifaceptr] = 0;
  897. local_interfaces = new_local_interfaces;
  898. local_iface_source = US"-oX data";
  899. DEBUG(D_any) debug_printf("local_interfaces overridden by -oX:\n %s\n",
  900. local_interfaces);
  901. }
  902. }
  903. /* Create a list of default SMTP ports, to be used if local_interfaces
  904. contains entries without explict ports. First count the number of ports, then
  905. build a translated list in a vector. */
  906. list = daemon_smtp_port;
  907. sep = 0;
  908. while ((s = string_nextinlist(&list, &sep, big_buffer, big_buffer_size)))
  909. pct++;
  910. default_smtp_port = store_get((pct+1) * sizeof(int));
  911. list = daemon_smtp_port;
  912. sep = 0;
  913. for (pct = 0;
  914. (s = string_nextinlist(&list, &sep, big_buffer, big_buffer_size));
  915. pct++)
  916. {
  917. if (isdigit(*s))
  918. {
  919. uschar *end;
  920. default_smtp_port[pct] = Ustrtol(s, &end, 0);
  921. if (end != s + Ustrlen(s))
  922. log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "invalid SMTP port: %s", s);
  923. }
  924. else
  925. {
  926. struct servent *smtp_service = getservbyname(CS s, "tcp");
  927. if (!smtp_service)
  928. log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "TCP port \"%s\" not found", s);
  929. default_smtp_port[pct] = ntohs(smtp_service->s_port);
  930. }
  931. }
  932. default_smtp_port[pct] = 0;
  933. /* Check the list of TLS-on-connect ports and do name lookups if needed */
  934. list = tls_in.on_connect_ports;
  935. sep = 0;
  936. while ((s = string_nextinlist(&list, &sep, big_buffer, big_buffer_size)))
  937. if (!isdigit(*s))
  938. {
  939. list = tls_in.on_connect_ports;
  940. tls_in.on_connect_ports = NULL;
  941. sep = 0;
  942. while ((s = string_nextinlist(&list, &sep, big_buffer, big_buffer_size)))
  943. {
  944. if (!isdigit(*s))
  945. {
  946. struct servent *smtp_service = getservbyname(CS s, "tcp");
  947. if (!smtp_service)
  948. log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "TCP port \"%s\" not found", s);
  949. s= string_sprintf("%d", (int)ntohs(smtp_service->s_port));
  950. }
  951. tls_in.on_connect_ports = string_append_listele(tls_in.on_connect_ports,
  952. ':', s);
  953. }
  954. break;
  955. }
  956. /* Create the list of local interfaces, possibly with ports included. This
  957. list may contain references to 0.0.0.0 and ::0 as wildcards. These special
  958. values are converted below. */
  959. addresses = host_build_ifacelist(local_interfaces, local_iface_source);
  960. /* In the list of IP addresses, convert 0.0.0.0 into an empty string, and ::0
  961. into the string ":". We use these to recognize wildcards in IPv4 and IPv6. In
  962. fact, many IP stacks recognize 0.0.0.0 and ::0 and handle them as wildcards
  963. anyway, but we need to know which are the wildcard addresses, and the shorter
  964. strings are neater.
  965. In the same scan, fill in missing port numbers from the default list. When
  966. there is more than one item in the list, extra items are created. */
  967. for (ipa = addresses; ipa != NULL; ipa = ipa->next)
  968. {
  969. int i;
  970. if (Ustrcmp(ipa->address, "0.0.0.0") == 0) ipa->address[0] = 0;
  971. else if (Ustrcmp(ipa->address, "::0") == 0)
  972. {
  973. ipa->address[0] = ':';
  974. ipa->address[1] = 0;
  975. }
  976. if (ipa->port > 0) continue;
  977. if (daemon_smtp_port[0] <= 0)
  978. log_write(0, LOG_MAIN|LOG_PANIC_DIE, "no port specified for interface "
  979. "%s and daemon_smtp_port is unset; cannot start daemon",
  980. (ipa->address[0] == 0)? US"\"all IPv4\"" :
  981. (ipa->address[1] == 0)? US"\"all IPv6\"" : ipa->address);
  982. ipa->port = default_smtp_port[0];
  983. for (i = 1; default_smtp_port[i] > 0; i++)
  984. {
  985. ip_address_item *new = store_get(sizeof(ip_address_item));
  986. memcpy(new->address, ipa->address, Ustrlen(ipa->address) + 1);
  987. new->port = default_smtp_port[i];
  988. new->next = ipa->next;
  989. ipa->next = new;
  990. ipa = new;
  991. }
  992. }
  993. /* Scan the list of addresses for wildcards. If we find an IPv4 and an IPv6
  994. wildcard for the same port, ensure that (a) they are together and (b) the
  995. IPv6 address comes first. This makes handling the messy features easier, and
  996. also simplifies the construction of the "daemon started" log line. */
  997. pipa = &addresses;
  998. for (ipa = addresses; ipa != NULL; pipa = &(ipa->next), ipa = ipa->next)
  999. {
  1000. ip_address_item *ipa2;
  1001. /* Handle an IPv4 wildcard */
  1002. if (ipa->address[0] == 0)
  1003. {
  1004. for (ipa2 = ipa; ipa2->next != NULL; ipa2 = ipa2->next)
  1005. {
  1006. ip_address_item *ipa3 = ipa2->next;
  1007. if (ipa3->address[0] == ':' &&
  1008. ipa3->address[1] == 0 &&
  1009. ipa3->port == ipa->port)
  1010. {
  1011. ipa2->next = ipa3->next;
  1012. ipa3->next = ipa;
  1013. *pipa = ipa3;
  1014. break;
  1015. }
  1016. }
  1017. }
  1018. /* Handle an IPv6 wildcard. */
  1019. else if (ipa->address[0] == ':' && ipa->address[1] == 0)
  1020. {
  1021. for (ipa2 = ipa; ipa2->next != NULL; ipa2 = ipa2->next)
  1022. {
  1023. ip_address_item *ipa3 = ipa2->next;
  1024. if (ipa3->address[0] == 0 && ipa3->port == ipa->port)
  1025. {
  1026. ipa2->next = ipa3->next;
  1027. ipa3->next = ipa->next;
  1028. ipa->next = ipa3;
  1029. ipa = ipa3;
  1030. break;
  1031. }
  1032. }
  1033. }
  1034. }
  1035. /* Get a vector to remember all the sockets in */
  1036. for (ipa = addresses; ipa != NULL; ipa = ipa->next)
  1037. listen_socket_count++;
  1038. listen_sockets = store_get(sizeof(int *) * listen_socket_count);
  1039. } /* daemon_listen but not inetd_wait_mode */
  1040. if (daemon_listen)
  1041. {
  1042. /* Do a sanity check on the max connects value just to save us from getting
  1043. a huge amount of store. */
  1044. if (smtp_accept_max > 4095) smtp_accept_max = 4096;
  1045. /* There's no point setting smtp_accept_queue unless it is less than the max
  1046. connects limit. The configuration reader ensures that the max is set if the
  1047. queue-only option is set. */
  1048. if (smtp_accept_queue > smtp_accept_max) smtp_accept_queue = 0;
  1049. /* Get somewhere to keep the list of SMTP accepting pids if we are keeping
  1050. track of them for total number and queue/host limits. */
  1051. if (smtp_accept_max > 0)
  1052. {
  1053. int i;
  1054. smtp_slots = store_get(smtp_accept_max * sizeof(smtp_slot));
  1055. for (i = 0; i < smtp_accept_max; i++) smtp_slots[i] = empty_smtp_slot;
  1056. }
  1057. }
  1058. /* The variable background_daemon is always false when debugging, but
  1059. can also be forced false in order to keep a non-debugging daemon in the
  1060. foreground. If background_daemon is true, close all open file descriptors that
  1061. we know about, but then re-open stdin, stdout, and stderr to /dev/null. Also
  1062. do this for inetd_wait mode.
  1063. This is protection against any called functions (in libraries, or in
  1064. Perl, or whatever) that think they can write to stderr (or stdout). Before this
  1065. was added, it was quite likely that an SMTP connection would use one of these
  1066. file descriptors, in which case writing random stuff to it caused chaos.
  1067. Then disconnect from the controlling terminal, Most modern Unixes seem to have
  1068. setsid() for getting rid of the controlling terminal. For any OS that doesn't,
  1069. setsid() can be #defined as a no-op, or as something else. */
  1070. if (background_daemon || inetd_wait_mode)
  1071. {
  1072. log_close_all(); /* Just in case anything was logged earlier */
  1073. search_tidyup(); /* Just in case any were used in reading the config. */
  1074. (void)close(0); /* Get rid of stdin/stdout/stderr */
  1075. (void)close(1);
  1076. (void)close(2);
  1077. exim_nullstd(); /* Connect stdin/stdout/stderr to /dev/null */
  1078. log_stderr = NULL; /* So no attempt to copy paniclog output */
  1079. }
  1080. if (background_daemon)
  1081. {
  1082. /* If the parent process of this one has pid == 1, we are re-initializing the
  1083. daemon as the result of a SIGHUP. In this case, there is no need to do
  1084. anything, because the controlling terminal has long gone. Otherwise, fork, in
  1085. case current process is a process group leader (see 'man setsid' for an
  1086. explanation) before calling setsid(). */
  1087. if (getppid() != 1)
  1088. {
  1089. pid_t pid = fork();
  1090. if (pid < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE,
  1091. "fork() failed when starting daemon: %s", strerror(errno));
  1092. if (pid > 0) exit(EXIT_SUCCESS); /* in parent process, just exit */
  1093. (void)setsid(); /* release controlling terminal */
  1094. }
  1095. }
  1096. /* We are now in the disconnected, daemon process (unless debugging). Set up
  1097. the listening sockets if required. */
  1098. if (daemon_listen && !inetd_wait_mode)
  1099. {
  1100. int sk;
  1101. int on = 1;
  1102. ip_address_item *ipa;
  1103. /* For each IP address, create a socket, bind it to the appropriate port, and
  1104. start listening. See comments above about IPv6 sockets that may or may not
  1105. accept IPv4 calls when listening on all interfaces. We also have to cope with
  1106. the case of a system with IPv6 libraries, but no IPv6 support in the kernel.
  1107. listening, provided a wildcard IPv4 socket for the same port follows. */
  1108. for (ipa = addresses, sk = 0; sk < listen_socket_count; ipa = ipa->next, sk++)
  1109. {
  1110. BOOL wildcard;
  1111. ip_address_item *ipa2;
  1112. int af;
  1113. if (Ustrchr(ipa->address, ':') != NULL)
  1114. {
  1115. af = AF_INET6;
  1116. wildcard = ipa->address[1] == 0;
  1117. }
  1118. else
  1119. {
  1120. af = AF_INET;
  1121. wildcard = ipa->address[0] == 0;
  1122. }
  1123. listen_sockets[sk] = ip_socket(SOCK_STREAM, af);
  1124. if (listen_sockets[sk] < 0)
  1125. {
  1126. if (check_special_case(0, addresses, ipa, FALSE))
  1127. {
  1128. log_write(0, LOG_MAIN, "Failed to create IPv6 socket for wildcard "
  1129. "listening (%s): will use IPv4", strerror(errno));
  1130. goto SKIP_SOCKET;
  1131. }
  1132. log_write(0, LOG_PANIC_DIE, "IPv%c socket creation failed: %s",
  1133. (af == AF_INET6)? '6' : '4', strerror(errno));
  1134. }
  1135. /* If this is an IPv6 wildcard socket, set IPV6_V6ONLY if that option is
  1136. available. Just log failure (can get protocol not available, just like
  1137. socket creation can). */
  1138. #ifdef IPV6_V6ONLY
  1139. if (af == AF_INET6 && wildcard &&
  1140. setsockopt(listen_sockets[sk], IPPROTO_IPV6, IPV6_V6ONLY, (char *)(&on),
  1141. sizeof(on)) < 0)
  1142. log_write(0, LOG_MAIN, "Setting IPV6_V6ONLY on daemon's IPv6 wildcard "
  1143. "socket failed (%s): carrying on without it", strerror(errno));
  1144. #endif /* IPV6_V6ONLY */
  1145. /* Set SO_REUSEADDR so that the daemon can be restarted while a connection
  1146. is being handled. Without this, a connection will prevent reuse of the
  1147. smtp port for listening. */
  1148. if (setsockopt(listen_sockets[sk], SOL_SOCKET, SO_REUSEADDR,
  1149. (uschar *)(&on), sizeof(on)) < 0)
  1150. log_write(0, LOG_MAIN|LOG_PANIC_DIE, "setting SO_REUSEADDR on socket "
  1151. "failed when starting daemon: %s", strerror(errno));
  1152. /* Set TCP_NODELAY; Exim does its own buffering. There is a switch to
  1153. disable this because it breaks some broken clients. */
  1154. if (tcp_nodelay) setsockopt(listen_sockets[sk], IPPROTO_TCP, TCP_NODELAY,
  1155. (uschar *)(&on), sizeof(on));
  1156. /* Now bind the socket to the required port; if Exim is being restarted
  1157. it may not always be possible to bind immediately, even with SO_REUSEADDR
  1158. set, so try 10 times, waiting between each try. After 10 failures, we give
  1159. up. In an IPv6 environment, if bind () fails with the error EADDRINUSE and
  1160. we are doing wildcard IPv4 listening and there was a previous IPv6 wildcard
  1161. address for the same port, ignore the error on the grounds that we must be
  1162. in a system where the IPv6 socket accepts both kinds of call. This is
  1163. necessary for (some release of) USAGI Linux; other IP stacks fail at the
  1164. listen() stage instead. */
  1165. for(;;)
  1166. {
  1167. uschar *msg, *addr;
  1168. if (ip_bind(listen_sockets[sk], af, ipa->address, ipa->port) >= 0) break;
  1169. if (check_special_case(errno, addresses, ipa, TRUE))
  1170. {
  1171. DEBUG(D_any) debug_printf("wildcard IPv4 bind() failed after IPv6 "
  1172. "listen() success; EADDRINUSE ignored\n");
  1173. (void)close(listen_sockets[sk]);
  1174. goto SKIP_SOCKET;
  1175. }
  1176. msg = US strerror(errno);
  1177. addr = wildcard? ((af == AF_INET6)? US"(any IPv6)" : US"(any IPv4)") :
  1178. ipa->address;
  1179. if (daemon_startup_retries <= 0)
  1180. log_write(0, LOG_MAIN|LOG_PANIC_DIE,
  1181. "socket bind() to port %d for address %s failed: %s: "
  1182. "daemon abandoned", ipa->port, addr, msg);
  1183. log_write(0, LOG_MAIN, "socket bind() to port %d for address %s "
  1184. "failed: %s: waiting %s before trying again (%d more %s)",
  1185. ipa->port, addr, msg, readconf_printtime(daemon_startup_sleep),
  1186. daemon_startup_retries, (daemon_startup_retries > 1)? "tries" : "try");
  1187. daemon_startup_retries--;
  1188. sleep(daemon_startup

Large files files are truncated, but you can click here to view the full file