tidying
[exim.git] / src / src / daemon.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8 /* Functions concerned with running Exim as a daemon */
9
10
11 #include "exim.h"
12
13
14 /* Structure for holding data for each SMTP connection */
15
16 typedef struct smtp_slot {
17   pid_t pid;                       /* pid of the spawned reception process */
18   uschar *host_address;            /* address of the client host */
19 } smtp_slot;
20
21 /* An empty slot for initializing (Standard C does not allow constructor
22 expressions in assignments except as initializers in declarations). */
23
24 static smtp_slot empty_smtp_slot = { .pid = 0, .host_address = NULL };
25
26
27
28 /*************************************************
29 *               Local static variables           *
30 *************************************************/
31
32 static SIGNAL_BOOL sigchld_seen;
33 static SIGNAL_BOOL sighup_seen;
34 static SIGNAL_BOOL sigterm_seen;
35
36 static int   accept_retry_count = 0;
37 static int   accept_retry_errno;
38 static BOOL  accept_retry_select_failed;
39
40 static int   queue_run_count = 0;
41 static pid_t *queue_pid_slots = NULL;
42 static smtp_slot *smtp_slots = NULL;
43
44 static BOOL  write_pid = TRUE;
45
46
47
48 /*************************************************
49 *             SIGHUP Handler                     *
50 *************************************************/
51
52 /* All this handler does is to set a flag and re-enable the signal.
53
54 Argument: the signal number
55 Returns:  nothing
56 */
57
58 static void
59 sighup_handler(int sig)
60 {
61 sig = sig;    /* Keep picky compilers happy */
62 sighup_seen = TRUE;
63 signal(SIGHUP, sighup_handler);
64 }
65
66
67
68 /*************************************************
69 *     SIGCHLD handler for main daemon process    *
70 *************************************************/
71
72 /* Don't re-enable the handler here, since we aren't doing the
73 waiting here. If the signal is re-enabled, there will just be an
74 infinite sequence of calls to this handler. The SIGCHLD signal is
75 used just as a means of waking up the daemon so that it notices
76 terminated subprocesses as soon as possible.
77
78 Argument: the signal number
79 Returns:  nothing
80 */
81
82 static void
83 main_sigchld_handler(int sig)
84 {
85 sig = sig;    /* Keep picky compilers happy */
86 os_non_restarting_signal(SIGCHLD, SIG_DFL);
87 sigchld_seen = TRUE;
88 }
89
90
91 /* SIGTERM handler.  Try to get the damon pif file removed
92 before exiting. */
93
94 static void
95 main_sigterm_handler(int sig)
96 {
97 sigterm_seen = TRUE;
98 }
99
100
101
102
103 /*************************************************
104 *          Unexpected errors in SMTP calls       *
105 *************************************************/
106
107 /* This function just saves a bit of repetitious coding.
108
109 Arguments:
110   log_msg        Text of message to be logged
111   smtp_msg       Text of SMTP error message
112   was_errno      The failing errno
113
114 Returns:         nothing
115 */
116
117 static void
118 never_error(uschar *log_msg, uschar *smtp_msg, int was_errno)
119 {
120 uschar *emsg = was_errno <= 0
121   ? US"" : string_sprintf(": %s", strerror(was_errno));
122 log_write(0, LOG_MAIN|LOG_PANIC, "%s%s", log_msg, emsg);
123 if (smtp_out) smtp_printf("421 %s\r\n", FALSE, smtp_msg);
124 }
125
126
127
128
129 /*************************************************
130 *************************************************/
131
132 static void
133 close_daemon_sockets(int daemon_notifier_fd,
134   int * listen_sockets, int listen_socket_count)
135 {
136 if (daemon_notifier_fd >= 0) (void) close(daemon_notifier_fd);
137 for (int i = 0; i < listen_socket_count; i++) (void) close(listen_sockets[i]);
138 }
139
140
141 /*************************************************
142 *            Handle a connected SMTP call        *
143 *************************************************/
144
145 /* This function is called when an SMTP connection has been accepted.
146 If there are too many, give an error message and close down. Otherwise
147 spin off a sub-process to handle the call. The list of listening sockets
148 is required so that they can be closed in the sub-process. Take care not to
149 leak store in this process - reset the stacking pool at the end.
150
151 Arguments:
152   listen_sockets        sockets which are listening for incoming calls
153   listen_socket_count   count of listening sockets
154   accept_socket         socket of the current accepted call
155   accepted              socket information about the current call
156
157 Returns:            nothing
158 */
159
160 static void
161 handle_smtp_call(int *listen_sockets, int listen_socket_count,
162   int accept_socket, struct sockaddr *accepted)
163 {
164 pid_t pid;
165 union sockaddr_46 interface_sockaddr;
166 EXIM_SOCKLEN_T ifsize = sizeof(interface_sockaddr);
167 int dup_accept_socket = -1;
168 int max_for_this_host = 0;
169 int save_log_selector = *log_selector;
170 gstring * whofrom;
171
172 rmark reset_point = store_mark();
173
174 /* Make the address available in ASCII representation, and also fish out
175 the remote port. */
176
177 sender_host_address = host_ntoa(-1, accepted, NULL, &sender_host_port);
178 DEBUG(D_any) debug_printf("Connection request from %s port %d\n",
179   sender_host_address, sender_host_port);
180
181 /* Set up the output stream, check the socket has duplicated, and set up the
182 input stream. These operations fail only the exceptional circumstances. Note
183 that never_error() won't use smtp_out if it is NULL. */
184
185 if (!(smtp_out = fdopen(accept_socket, "wb")))
186   {
187   never_error(US"daemon: fdopen() for smtp_out failed", US"", errno);
188   goto ERROR_RETURN;
189   }
190
191 if ((dup_accept_socket = dup(accept_socket)) < 0)
192   {
193   never_error(US"daemon: couldn't dup socket descriptor",
194     US"Connection setup failed", errno);
195   goto ERROR_RETURN;
196   }
197
198 if (!(smtp_in = fdopen(dup_accept_socket, "rb")))
199   {
200   never_error(US"daemon: fdopen() for smtp_in failed",
201     US"Connection setup failed", errno);
202   goto ERROR_RETURN;
203   }
204
205 /* Get the data for the local interface address. Panic for most errors, but
206 "connection reset by peer" just means the connection went away. */
207
208 if (getsockname(accept_socket, (struct sockaddr *)(&interface_sockaddr),
209      &ifsize) < 0)
210   {
211   log_write(0, LOG_MAIN | ((errno == ECONNRESET)? 0 : LOG_PANIC),
212     "getsockname() failed: %s", strerror(errno));
213   smtp_printf("421 Local problem: getsockname() failed; please try again later\r\n", FALSE);
214   goto ERROR_RETURN;
215   }
216
217 interface_address = host_ntoa(-1, &interface_sockaddr, NULL, &interface_port);
218 DEBUG(D_interface) debug_printf("interface address=%s port=%d\n",
219   interface_address, interface_port);
220
221 /* Build a string identifying the remote host and, if requested, the port and
222 the local interface data. This is for logging; at the end of this function the
223 memory is reclaimed. */
224
225 whofrom = string_append(NULL, 3, "[", sender_host_address, "]");
226
227 if (LOGGING(incoming_port))
228   whofrom = string_fmt_append(whofrom, ":%d", sender_host_port);
229
230 if (LOGGING(incoming_interface))
231   whofrom = string_fmt_append(whofrom, " I=[%s]:%d",
232     interface_address, interface_port);
233
234 (void) string_from_gstring(whofrom);    /* Terminate the newly-built string */
235
236 /* Check maximum number of connections. We do not check for reserved
237 connections or unacceptable hosts here. That is done in the subprocess because
238 it might take some time. */
239
240 if (smtp_accept_max > 0 && smtp_accept_count >= smtp_accept_max)
241   {
242   DEBUG(D_any) debug_printf("rejecting SMTP connection: count=%d max=%d\n",
243     smtp_accept_count, smtp_accept_max);
244   smtp_printf("421 Too many concurrent SMTP connections; "
245     "please try again later.\r\n", FALSE);
246   log_write(L_connection_reject,
247             LOG_MAIN, "Connection from %s refused: too many connections",
248     whofrom->s);
249   goto ERROR_RETURN;
250   }
251
252 /* If a load limit above which only reserved hosts are acceptable is defined,
253 get the load average here, and if there are in fact no reserved hosts, do
254 the test right away (saves a fork). If there are hosts, do the check in the
255 subprocess because it might take time. */
256
257 if (smtp_load_reserve >= 0)
258   {
259   load_average = OS_GETLOADAVG();
260   if (smtp_reserve_hosts == NULL && load_average > smtp_load_reserve)
261     {
262     DEBUG(D_any) debug_printf("rejecting SMTP connection: load average = %.2f\n",
263       (double)load_average/1000.0);
264     smtp_printf("421 Too much load; please try again later.\r\n", FALSE);
265     log_write(L_connection_reject,
266               LOG_MAIN, "Connection from %s refused: load average = %.2f",
267       whofrom->s, (double)load_average/1000.0);
268     goto ERROR_RETURN;
269     }
270   }
271
272 /* Check that one specific host (strictly, IP address) is not hogging
273 resources. This is done here to prevent a denial of service attack by someone
274 forcing you to fork lots of times before denying service. The value of
275 smtp_accept_max_per_host is a string which is expanded. This makes it possible
276 to provide host-specific limits according to $sender_host address, but because
277 this is in the daemon mainline, only fast expansions (such as inline address
278 checks) should be used. The documentation is full of warnings. */
279
280 if (smtp_accept_max_per_host != NULL)
281   {
282   uschar *expanded = expand_string(smtp_accept_max_per_host);
283   if (expanded == NULL)
284     {
285     if (!f.expand_string_forcedfail)
286       log_write(0, LOG_MAIN|LOG_PANIC, "expansion of smtp_accept_max_per_host "
287         "failed for %s: %s", whofrom->s, expand_string_message);
288     }
289   /* For speed, interpret a decimal number inline here */
290   else
291     {
292     uschar *s = expanded;
293     while (isdigit(*s))
294       max_for_this_host = max_for_this_host * 10 + *s++ - '0';
295     if (*s != 0)
296       log_write(0, LOG_MAIN|LOG_PANIC, "expansion of smtp_accept_max_per_host "
297         "for %s contains non-digit: %s", whofrom->s, expanded);
298     }
299   }
300
301 /* If we have fewer connections than max_for_this_host, we can skip the tedious
302 per host_address checks. Note that at this stage smtp_accept_count contains the
303 count of *other* connections, not including this one. */
304
305 if ((max_for_this_host > 0) &&
306     (smtp_accept_count >= max_for_this_host))
307   {
308   int host_accept_count = 0;
309   int other_host_count = 0;    /* keep a count of non matches to optimise */
310
311   for (int i = 0; i < smtp_accept_max; ++i)
312     if (smtp_slots[i].host_address)
313       {
314       if (Ustrcmp(sender_host_address, smtp_slots[i].host_address) == 0)
315        host_accept_count++;
316       else
317        other_host_count++;
318
319       /* Testing all these strings is expensive - see if we can drop out
320       early, either by hitting the target, or finding there are not enough
321       connections left to make the target. */
322
323       if ((host_accept_count >= max_for_this_host) ||
324          ((smtp_accept_count - other_host_count) < max_for_this_host))
325        break;
326       }
327
328   if (host_accept_count >= max_for_this_host)
329     {
330     DEBUG(D_any) debug_printf("rejecting SMTP connection: too many from this "
331       "IP address: count=%d max=%d\n",
332       host_accept_count, max_for_this_host);
333     smtp_printf("421 Too many concurrent SMTP connections "
334       "from this IP address; please try again later.\r\n", FALSE);
335     log_write(L_connection_reject,
336               LOG_MAIN, "Connection from %s refused: too many connections "
337       "from that IP address", whofrom->s);
338     goto ERROR_RETURN;
339     }
340   }
341
342 /* OK, the connection count checks have been passed. Before we can fork the
343 accepting process, we must first log the connection if requested. This logging
344 used to happen in the subprocess, but doing that means that the value of
345 smtp_accept_count can be out of step by the time it is logged. So we have to do
346 the logging here and accept the performance cost. Note that smtp_accept_count
347 hasn't yet been incremented to take account of this connection.
348
349 In order to minimize the cost (because this is going to happen for every
350 connection), do a preliminary selector test here. This saves ploughing through
351 the generalized logging code each time when the selector is false. If the
352 selector is set, check whether the host is on the list for logging. If not,
353 arrange to unset the selector in the subprocess. */
354
355 if (LOGGING(smtp_connection))
356   {
357   uschar *list = hosts_connection_nolog;
358   memset(sender_host_cache, 0, sizeof(sender_host_cache));
359   if (list != NULL && verify_check_host(&list) == OK)
360     save_log_selector &= ~L_smtp_connection;
361   else
362     log_write(L_smtp_connection, LOG_MAIN, "SMTP connection from %s "
363       "(TCP/IP connection count = %d)", whofrom->s, smtp_accept_count + 1);
364   }
365
366 /* Now we can fork the accepting process; do a lookup tidy, just in case any
367 expansion above did a lookup. */
368
369 search_tidyup();
370 pid = exim_fork(US"daemon-accept");
371
372 /* Handle the child process */
373
374 if (pid == 0)
375   {
376   int queue_only_reason = 0;
377   int old_pool = store_pool;
378   int save_debug_selector = debug_selector;
379   BOOL local_queue_only;
380   BOOL session_local_queue_only;
381   #ifdef SA_NOCLDWAIT
382   struct sigaction act;
383   #endif
384
385   smtp_accept_count++;    /* So that it includes this process */
386
387   /* May have been modified for the subprocess */
388
389   *log_selector = save_log_selector;
390
391   /* Get the local interface address into permanent store */
392
393   store_pool = POOL_PERM;
394   interface_address = string_copy(interface_address);
395   store_pool = old_pool;
396
397   /* Check for a tls-on-connect port */
398
399   if (host_is_tls_on_connect_port(interface_port)) tls_in.on_connect = TRUE;
400
401   /* Expand smtp_active_hostname if required. We do not do this any earlier,
402   because it may depend on the local interface address (indeed, that is most
403   likely what it depends on.) */
404
405   smtp_active_hostname = primary_hostname;
406   if (raw_active_hostname)
407     {
408     uschar * nah = expand_string(raw_active_hostname);
409     if (!nah)
410       {
411       if (!f.expand_string_forcedfail)
412         {
413         log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand \"%s\" "
414           "(smtp_active_hostname): %s", raw_active_hostname,
415           expand_string_message);
416         smtp_printf("421 Local configuration error; "
417           "please try again later.\r\n", FALSE);
418         mac_smtp_fflush();
419         search_tidyup();
420         exim_underbar_exit(EXIT_FAILURE);
421         }
422       }
423     else if (*nah) smtp_active_hostname = nah;
424     }
425
426   /* Initialize the queueing flags */
427
428   queue_check_only();
429   session_local_queue_only = queue_only;
430
431   /* Close the listening sockets, and set the SIGCHLD handler to SIG_IGN.
432   We also attempt to set things up so that children are automatically reaped,
433   but just in case this isn't available, there's a paranoid waitpid() in the
434   loop too (except for systems where we are sure it isn't needed). See the more
435   extensive comment before the reception loop in exim.c for a fuller
436   explanation of this logic. */
437
438   close_daemon_sockets(daemon_notifier_fd, listen_sockets, listen_socket_count);
439
440   /* Set FD_CLOEXEC on the SMTP socket. We don't want any rogue child processes
441   to be able to communicate with them, under any circumstances. */
442   (void)fcntl(accept_socket, F_SETFD,
443               fcntl(accept_socket, F_GETFD) | FD_CLOEXEC);
444   (void)fcntl(dup_accept_socket, F_SETFD,
445               fcntl(dup_accept_socket, F_GETFD) | FD_CLOEXEC);
446
447   #ifdef SA_NOCLDWAIT
448   act.sa_handler = SIG_IGN;
449   sigemptyset(&(act.sa_mask));
450   act.sa_flags = SA_NOCLDWAIT;
451   sigaction(SIGCHLD, &act, NULL);
452   #else
453   signal(SIGCHLD, SIG_IGN);
454   #endif
455   signal(SIGTERM, SIG_DFL);
456
457   /* Attempt to get an id from the sending machine via the RFC 1413
458   protocol. We do this in the sub-process in order not to hold up the
459   main process if there is any delay. Then set up the fullhost information
460   in case there is no HELO/EHLO.
461
462   If debugging is enabled only for the daemon, we must turn if off while
463   finding the id, but turn it on again afterwards so that information about the
464   incoming connection is output. */
465
466   if (f.debug_daemon) debug_selector = 0;
467   verify_get_ident(IDENT_PORT);
468   host_build_sender_fullhost();
469   debug_selector = save_debug_selector;
470
471   DEBUG(D_any)
472     debug_printf("Process %d is handling incoming connection from %s\n",
473       (int)getpid(), sender_fullhost);
474
475   /* Now disable debugging permanently if it's required only for the daemon
476   process. */
477
478   if (f.debug_daemon) debug_selector = 0;
479
480   /* If there are too many child processes for immediate delivery,
481   set the session_local_queue_only flag, which is initialized from the
482   configured value and may therefore already be TRUE. Leave logging
483   till later so it will have a message id attached. Note that there is no
484   possibility of re-calculating this per-message, because the value of
485   smtp_accept_count does not change in this subprocess. */
486
487   if (smtp_accept_queue > 0 && smtp_accept_count > smtp_accept_queue)
488     {
489     session_local_queue_only = TRUE;
490     queue_only_reason = 1;
491     }
492
493   /* Handle the start of the SMTP session, then loop, accepting incoming
494   messages from the SMTP connection. The end will come at the QUIT command,
495   when smtp_setup_msg() returns 0. A break in the connection causes the
496   process to die (see accept.c).
497
498   NOTE: We do *not* call smtp_log_no_mail() if smtp_start_session() fails,
499   because a log line has already been written for all its failure exists
500   (usually "connection refused: <reason>") and writing another one is
501   unnecessary clutter. */
502
503   if (!smtp_start_session())
504     {
505     mac_smtp_fflush();
506     search_tidyup();
507     exim_underbar_exit(EXIT_SUCCESS);
508     }
509
510   for (;;)
511     {
512     int rc;
513     message_id[0] = 0;            /* Clear out any previous message_id */
514     reset_point = store_mark();   /* Save current store high water point */
515
516     DEBUG(D_any)
517       debug_printf("Process %d is ready for new message\n", (int)getpid());
518
519     /* Smtp_setup_msg() returns 0 on QUIT or if the call is from an
520     unacceptable host or if an ACL "drop" command was triggered, -1 on
521     connection lost, and +1 on validly reaching DATA. Receive_msg() almost
522     always returns TRUE when smtp_input is true; just retry if no message was
523     accepted (can happen for invalid message parameters). However, it can yield
524     FALSE if the connection was forcibly dropped by the DATA ACL. */
525
526     if ((rc = smtp_setup_msg()) > 0)
527       {
528       BOOL ok = receive_msg(FALSE);
529       search_tidyup();                    /* Close cached databases */
530       if (!ok)                            /* Connection was dropped */
531         {
532         cancel_cutthrough_connection(TRUE, US"receive dropped");
533         mac_smtp_fflush();
534         smtp_log_no_mail();               /* Log no mail if configured */
535         exim_underbar_exit(EXIT_SUCCESS);
536         }
537       if (message_id[0] == 0) continue;   /* No message was accepted */
538       }
539     else
540       {
541       if (smtp_out)
542         {
543         int fd = fileno(smtp_in);
544         uschar buf[128];
545
546         mac_smtp_fflush();
547         /* drain socket, for clean TCP FINs */
548         if (fcntl(fd, F_SETFL, O_NONBLOCK) == 0)
549           for(int i = 16; read(fd, buf, sizeof(buf)) > 0 && i > 0; ) i--;
550         }
551       cancel_cutthrough_connection(TRUE, US"message setup dropped");
552       search_tidyup();
553       smtp_log_no_mail();                 /* Log no mail if configured */
554
555       /*XXX should we pause briefly, hoping that the client will be the
556       active TCP closer hence get the TCP_WAIT endpoint? */
557       DEBUG(D_receive) debug_printf("SMTP>>(close on process exit)\n");
558       exim_underbar_exit(rc ? EXIT_FAILURE : EXIT_SUCCESS);
559       }
560
561     /* Show the recipients when debugging */
562
563     DEBUG(D_receive)
564       {
565       if (sender_address)
566         debug_printf("Sender: %s\n", sender_address);
567       if (recipients_list)
568         {
569         debug_printf("Recipients:\n");
570         for (int i = 0; i < recipients_count; i++)
571           debug_printf("  %s\n", recipients_list[i].address);
572         }
573       }
574
575     /* A message has been accepted. Clean up any previous delivery processes
576     that have completed and are defunct, on systems where they don't go away
577     by themselves (see comments when setting SIG_IGN above). On such systems
578     (if any) these delivery processes hang around after termination until
579     the next message is received. */
580
581     #ifndef SIG_IGN_WORKS
582     while (waitpid(-1, NULL, WNOHANG) > 0);
583     #endif
584
585     /* Reclaim up the store used in accepting this message */
586
587       {
588       int r = receive_messagecount;
589       BOOL q = f.queue_only_policy;
590       smtp_reset(reset_point);
591       reset_point = NULL;
592       f.queue_only_policy = q;
593       receive_messagecount = r;
594       }
595
596     /* If queue_only is set or if there are too many incoming connections in
597     existence, session_local_queue_only will be TRUE. If it is not, check
598     whether we have received too many messages in this session for immediate
599     delivery. */
600
601     if (!session_local_queue_only &&
602         smtp_accept_queue_per_connection > 0 &&
603         receive_messagecount > smtp_accept_queue_per_connection)
604       {
605       session_local_queue_only = TRUE;
606       queue_only_reason = 2;
607       }
608
609     /* Initialize local_queue_only from session_local_queue_only. If it is not
610     true, and queue_only_load is set, check that the load average is below it.
611     If local_queue_only is set by this means, we also set if for the session if
612     queue_only_load_latch is true (the default). This means that, once set,
613     local_queue_only remains set for any subsequent messages on the same SMTP
614     connection. This is a deliberate choice; even though the load average may
615     fall, it doesn't seem right to deliver later messages on the same call when
616     not delivering earlier ones. However, the are special circumstances such as
617     very long-lived connections from scanning appliances where this is not the
618     best strategy. In such cases, queue_only_load_latch should be set false. */
619
620     if (  !(local_queue_only = session_local_queue_only)
621        && queue_only_load >= 0
622        && (local_queue_only = (load_average = OS_GETLOADAVG()) > queue_only_load)
623        )
624       {
625       queue_only_reason = 3;
626       if (queue_only_load_latch) session_local_queue_only = TRUE;
627       }
628
629     /* Log the queueing here, when it will get a message id attached, but
630     not if queue_only is set (case 0). */
631
632     if (local_queue_only) switch(queue_only_reason)
633       {
634       case 1: log_write(L_delay_delivery,
635                 LOG_MAIN, "no immediate delivery: too many connections "
636                 "(%d, max %d)", smtp_accept_count, smtp_accept_queue);
637               break;
638
639       case 2: log_write(L_delay_delivery,
640                 LOG_MAIN, "no immediate delivery: more than %d messages "
641                 "received in one connection", smtp_accept_queue_per_connection);
642               break;
643
644       case 3: log_write(L_delay_delivery,
645                 LOG_MAIN, "no immediate delivery: load average %.2f",
646                 (double)load_average/1000.0);
647               break;
648       }
649
650     /* If a delivery attempt is required, spin off a new process to handle it.
651     If we are not root, we have to re-exec exim unless deliveries are being
652     done unprivileged. */
653
654     else if (  (!f.queue_only_policy || f.queue_smtp)
655             && !f.deliver_freeze)
656       {
657       pid_t dpid;
658
659       /* Before forking, ensure that the C output buffer is flushed. Otherwise
660       anything that it in it will get duplicated, leading to duplicate copies
661       of the pending output. */
662
663       mac_smtp_fflush();
664
665       if ((dpid = exim_fork(US"daemon-accept-delivery")) == 0)
666         {
667         (void)fclose(smtp_in);
668         (void)fclose(smtp_out);
669
670         /* Don't ever molest the parent's SSL connection, but do clean up
671         the data structures if necessary. */
672
673 #ifndef DISABLE_TLS
674         tls_close(NULL, TLS_NO_SHUTDOWN);
675 #endif
676
677         /* Reset SIGHUP and SIGCHLD in the child in both cases. */
678
679         signal(SIGHUP,  SIG_DFL);
680         signal(SIGCHLD, SIG_DFL);
681         signal(SIGTERM, SIG_DFL);
682
683         if (geteuid() != root_uid && !deliver_drop_privilege)
684           {
685           signal(SIGALRM, SIG_DFL);
686           delivery_re_exec(CEE_EXEC_PANIC);
687           /* Control does not return here. */
688           }
689
690         /* No need to re-exec; SIGALRM remains set to the default handler */
691
692         (void) deliver_message(message_id, FALSE, FALSE);
693         search_tidyup();
694         exim_underbar_exit(EXIT_SUCCESS);
695         }
696
697       if (dpid > 0)
698         {
699         release_cutthrough_connection(US"passed for delivery");
700         DEBUG(D_any) debug_printf("forked delivery process %d\n", (int)dpid);
701         }
702       else
703         {
704         cancel_cutthrough_connection(TRUE, US"delivery fork failed");
705         log_write(0, LOG_MAIN|LOG_PANIC, "daemon: delivery process fork "
706           "failed: %s", strerror(errno));
707         }
708       }
709     }
710   }
711
712
713 /* Carrying on in the parent daemon process... Can't do much if the fork
714 failed. Otherwise, keep count of the number of accepting processes and
715 remember the pid for ticking off when the child completes. */
716
717 if (pid < 0)
718   never_error(US"daemon: accept process fork failed", US"Fork failed", errno);
719 else
720   {
721   for (int i = 0; i < smtp_accept_max; ++i)
722     if (smtp_slots[i].pid <= 0)
723       {
724       smtp_slots[i].pid = pid;
725       /* Connection closes come asyncronously, so we cannot stack this store */
726       if (smtp_accept_max_per_host)
727         smtp_slots[i].host_address = string_copy_malloc(sender_host_address);
728       smtp_accept_count++;
729       break;
730       }
731   DEBUG(D_any) debug_printf("%d SMTP accept process%s running\n",
732     smtp_accept_count, smtp_accept_count == 1 ? "" : "es");
733   }
734
735 /* Get here via goto in error cases */
736
737 ERROR_RETURN:
738
739 /* Close the streams associated with the socket which will also close the
740 socket fds in this process. We can't do anything if fclose() fails, but
741 logging brings it to someone's attention. However, "connection reset by peer"
742 isn't really a problem, so skip that one. On Solaris, a dropped connection can
743 manifest itself as a broken pipe, so drop that one too. If the streams don't
744 exist, something went wrong while setting things up. Make sure the socket
745 descriptors are closed, in order to drop the connection. */
746
747 if (smtp_out)
748   {
749   if (fclose(smtp_out) != 0 && errno != ECONNRESET && errno != EPIPE)
750     log_write(0, LOG_MAIN|LOG_PANIC, "daemon: fclose(smtp_out) failed: %s",
751       strerror(errno));
752   smtp_out = NULL;
753   }
754 else (void)close(accept_socket);
755
756 if (smtp_in)
757   {
758   if (fclose(smtp_in) != 0 && errno != ECONNRESET && errno != EPIPE)
759     log_write(0, LOG_MAIN|LOG_PANIC, "daemon: fclose(smtp_in) failed: %s",
760       strerror(errno));
761   smtp_in = NULL;
762   }
763 else (void)close(dup_accept_socket);
764
765 /* Release any store used in this process, including the store used for holding
766 the incoming host address and an expanded active_hostname. */
767
768 log_close_all();
769 interface_address =
770 sender_host_address = NULL;
771 store_reset(reset_point);
772 sender_host_address = NULL;
773 }
774
775
776
777
778 /*************************************************
779 *       Check wildcard listen special cases      *
780 *************************************************/
781
782 /* This function is used when binding and listening on lists of addresses and
783 ports. It tests for special cases of wildcard listening, when IPv4 and IPv6
784 sockets may interact in different ways in different operating systems. It is
785 passed an error number, the list of listening addresses, and the current
786 address. Two checks are available: for a previous wildcard IPv6 address, or for
787 a following wildcard IPv4 address, in both cases on the same port.
788
789 In practice, pairs of wildcard addresses should be adjacent in the address list
790 because they are sorted that way below.
791
792 Arguments:
793   eno            the error number
794   addresses      the list of addresses
795   ipa            the current IP address
796   back           if TRUE, check for previous wildcard IPv6 address
797                  if FALSE, check for a following wildcard IPv4 address
798
799 Returns:         TRUE or FALSE
800 */
801
802 static BOOL
803 check_special_case(int eno, ip_address_item *addresses, ip_address_item *ipa,
804   BOOL back)
805 {
806 ip_address_item *ipa2;
807
808 /* For the "back" case, if the failure was "address in use" for a wildcard IPv4
809 address, seek a previous IPv6 wildcard address on the same port. As it is
810 previous, it must have been successfully bound and be listening. Flag it as a
811 "6 including 4" listener. */
812
813 if (back)
814   {
815   if (eno != EADDRINUSE || ipa->address[0] != 0) return FALSE;
816   for (ipa2 = addresses; ipa2 != ipa; ipa2 = ipa2->next)
817     {
818     if (ipa2->address[1] == 0 && ipa2->port == ipa->port)
819       {
820       ipa2->v6_include_v4 = TRUE;
821       return TRUE;
822       }
823     }
824   }
825
826 /* For the "forward" case, if the current address is a wildcard IPv6 address,
827 we seek a following wildcard IPv4 address on the same port. */
828
829 else
830   {
831   if (ipa->address[0] != ':' || ipa->address[1] != 0) return FALSE;
832   for (ipa2 = ipa->next; ipa2 != NULL; ipa2 = ipa2->next)
833     if (ipa2->address[0] == 0 && ipa->port == ipa2->port) return TRUE;
834   }
835
836 return FALSE;
837 }
838
839
840
841
842 /*************************************************
843 *         Handle terminating subprocesses        *
844 *************************************************/
845
846 /* Handle the termination of child processes. Theoretically, this need be done
847 only when sigchld_seen is TRUE, but rumour has it that some systems lose
848 SIGCHLD signals at busy times, so to be on the safe side, this function is
849 called each time round. It shouldn't be too expensive.
850
851 Arguments:  none
852 Returns:    nothing
853 */
854
855 static void
856 handle_ending_processes(void)
857 {
858 int status;
859 pid_t pid;
860
861 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
862   {
863   DEBUG(D_any)
864     {
865     debug_printf("child %d ended: status=0x%x\n", (int)pid, status);
866 #ifdef WCOREDUMP
867     if (WIFEXITED(status))
868       debug_printf("  normal exit, %d\n", WEXITSTATUS(status));
869     else if (WIFSIGNALED(status))
870       debug_printf("  signal exit, signal %d%s\n", WTERMSIG(status),
871           WCOREDUMP(status) ? " (core dumped)" : "");
872 #endif
873     }
874
875   /* If it's a listening daemon for which we are keeping track of individual
876   subprocesses, deal with an accepting process that has terminated. */
877
878   if (smtp_slots)
879     {
880     int i;
881     for (i = 0; i < smtp_accept_max; i++)
882       if (smtp_slots[i].pid == pid)
883         {
884         if (smtp_slots[i].host_address)
885           store_free(smtp_slots[i].host_address);
886         smtp_slots[i] = empty_smtp_slot;
887         if (--smtp_accept_count < 0) smtp_accept_count = 0;
888         DEBUG(D_any) debug_printf("%d SMTP accept process%s now running\n",
889           smtp_accept_count, (smtp_accept_count == 1)? "" : "es");
890         break;
891         }
892     if (i < smtp_accept_max) continue;  /* Found an accepting process */
893     }
894
895   /* If it wasn't an accepting process, see if it was a queue-runner
896   process that we are tracking. */
897
898   if (queue_pid_slots)
899     {
900     int max = atoi(CS expand_string(queue_run_max));
901     for (int i = 0; i < max; i++)
902       if (queue_pid_slots[i] == pid)
903         {
904         queue_pid_slots[i] = 0;
905         if (--queue_run_count < 0) queue_run_count = 0;
906         DEBUG(D_any) debug_printf("%d queue-runner process%s now running\n",
907           queue_run_count, (queue_run_count == 1)? "" : "es");
908         break;
909         }
910     }
911   }
912 }
913
914
915
916 static void
917 set_pid_file_path(void)
918 {
919 if (override_pid_file_path)
920   pid_file_path = override_pid_file_path;
921
922 if (!*pid_file_path)
923   pid_file_path = string_sprintf("%s/exim-daemon.pid", spool_directory);
924 }
925
926
927 /* Remove the daemon's pidfile.  Note: runs with root privilege,
928 as a direct child of the daemon.  Does not return. */
929
930 void
931 delete_pid_file(void)
932 {
933 uschar * daemon_pid = string_sprintf("%d\n", (int)getppid());
934 FILE * f;
935
936 set_pid_file_path();
937 if ((f = Ufopen(pid_file_path, "rb")))
938   {
939   if (  fgets(CS big_buffer, big_buffer_size, f)
940         && Ustrcmp(daemon_pid, big_buffer) == 0
941      )
942     if (Uunlink(pid_file_path) == 0)
943       {
944       DEBUG(D_any)
945         debug_printf("%s unlink: %s\n", pid_file_path, strerror(errno));
946       }
947     else
948       DEBUG(D_any)
949         debug_printf("unlinked %s\n", pid_file_path);
950   fclose(f);
951   }
952 else
953   DEBUG(D_any)
954     debug_printf("%s\n", string_open_failed(errno, "pid file %s",
955       pid_file_path));
956 exim_exit(EXIT_SUCCESS);
957 }
958
959
960 /* Called by the daemon; exec a child to get the pid file deleted
961 since we may require privs for the containing directory */
962
963 static void
964 daemon_die(void)
965 {
966 int pid;
967
968 if (daemon_notifier_fd >= 0)
969   {
970   close(daemon_notifier_fd);
971   daemon_notifier_fd = -1;
972 #ifndef EXIM_HAVE_ABSTRACT_UNIX_SOCKETS
973     {
974     uschar * s = expand_string(notifier_socket);
975     DEBUG(D_any) debug_printf("unlinking notifier socket %s\n", s);
976     Uunlink(s);
977     }
978 #endif
979   }
980
981 if (f.running_in_test_harness || write_pid)
982   {
983   if ((pid = exim_fork(US"daemon-del-pidfile")) == 0)
984     {
985     if (override_pid_file_path)
986       (void)child_exec_exim(CEE_EXEC_PANIC, FALSE, NULL, FALSE, 3,
987         "-oP", override_pid_file_path, "-oPX");
988     else
989       (void)child_exec_exim(CEE_EXEC_PANIC, FALSE, NULL, FALSE, 1, "-oPX");
990
991     /* Control never returns here. */
992     }
993   if (pid > 0)
994     child_close(pid, 1);
995   }
996 exim_exit(EXIT_SUCCESS);
997 }
998
999
1000 /*************************************************
1001 *       Listener socket for local work prompts   *
1002 *************************************************/
1003
1004 static void
1005 daemon_notifier_socket(void)
1006 {
1007 int fd;
1008 const uschar * where;
1009 struct sockaddr_un sa_un = {.sun_family = AF_UNIX};
1010 int len;
1011
1012 if (override_local_interfaces && !override_pid_file_path)
1013   {
1014   DEBUG(D_any)
1015     debug_printf("-oX used without -oP so not creating notifier socket\n");
1016   return;
1017   }
1018
1019 DEBUG(D_any) debug_printf("creating notifier socket\n");
1020
1021 #ifdef SOCK_CLOEXEC
1022 if ((fd = socket(PF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
1023   { where = US"socket"; goto bad; }
1024 #else
1025 if ((fd = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0)
1026   { where = US"socket"; goto bad; }
1027 (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
1028 #endif
1029
1030 #ifdef EXIM_HAVE_ABSTRACT_UNIX_SOCKETS
1031 sa_un.sun_path[0] = 0;  /* Abstract local socket addr - Linux-specific? */
1032 len = offsetof(struct sockaddr_un, sun_path) + 1
1033   + snprintf(sa_un.sun_path+1, sizeof(sa_un.sun_path)-1, "%s",
1034               expand_string(notifier_socket));
1035 DEBUG(D_any) debug_printf(" @%s\n", sa_un.sun_path+1);
1036 #else                   /* filesystem-visible and persistent; will neeed removal */
1037 len = offsetof(struct sockaddr_un, sun_path)
1038   + snprintf(sa_un.sun_path, sizeof(sa_un.sun_path), "%s", 
1039               expand_string(notifier_socket));
1040 DEBUG(D_any) debug_printf(" %s\n", sa_un.sun_path);
1041 #endif
1042
1043 if (bind(fd, (const struct sockaddr *)&sa_un, len) < 0)
1044   { where = US"bind"; goto bad; }
1045
1046 #ifdef SO_PASSCRED              /* Linux */
1047 if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on)) < 0)
1048   { where = US"SO_PASSCRED"; goto bad2; }
1049 #elif defined(LOCAL_CREDS)      /* FreeBSD-ish */
1050 if (setsockopt(fd, 0, LOCAL_CREDS, &on, sizeof(on)) < 0)
1051   { where = US"LOCAL_CREDS"; goto bad2; }
1052 #endif
1053
1054 /* debug_printf("%s: fd %d\n", __FUNCTION__, fd); */
1055 daemon_notifier_fd = fd;
1056 return;
1057
1058 bad2:
1059 #ifndef EXIM_HAVE_ABSTRACT_UNIX_SOCKETS
1060   Uunlink(sa_un.sun_path);
1061 #endif
1062 bad:
1063   log_write(0, LOG_MAIN|LOG_PANIC, "%s %s: %s",
1064     __FUNCTION__, where, strerror(errno));
1065   close(fd);
1066   return;
1067 }
1068
1069
1070 static uschar queuerun_msgid[MESSAGE_ID_LENGTH+1];
1071
1072 /* Return TRUE if a sigalrm should be emulated */
1073 static BOOL
1074 daemon_notification(void)
1075 {
1076 uschar buf[256], cbuf[256];
1077 struct sockaddr_un sa_un;
1078 struct iovec iov = {.iov_base = buf, .iov_len = sizeof(buf)-1};
1079 struct msghdr msg = { .msg_name = &sa_un,
1080                       .msg_namelen = sizeof(sa_un),
1081                       .msg_iov = &iov,
1082                       .msg_iovlen = 1,
1083                       .msg_control = cbuf,
1084                       .msg_controllen = sizeof(cbuf)
1085                     };
1086 ssize_t sz;
1087
1088 buf[sizeof(buf)-1] = 0;
1089 if ((sz = recvmsg(daemon_notifier_fd, &msg, 0)) <= 0) return FALSE;
1090 if (sz >= sizeof(buf)) return FALSE;
1091
1092 #ifdef notdef
1093 debug_printf("addrlen %d\n", msg.msg_namelen);
1094 #endif
1095 DEBUG(D_queue_run) debug_printf("%s from addr '%s%.*s'\n", __FUNCTION__,
1096   *sa_un.sun_path ? "" : "@",
1097   (int)msg.msg_namelen - (*sa_un.sun_path ? 0 : 1),
1098   sa_un.sun_path + (*sa_un.sun_path ? 0 : 1));
1099
1100 /* Refuse to handle the item unless the peer has good credentials */
1101 #ifdef SCM_CREDENTIALS
1102 # define EXIM_SCM_CR_TYPE SCM_CREDENTIALS
1103 #elif defined(LOCAL_CREDS) && defined(SCM_CREDS)
1104 # define EXIM_SCM_CR_TYPE SCM_CREDS
1105 #else
1106         /* The OS has no way to get the creds of the caller (for a unix/datagram socket.
1107         Punt; don't try to check. */
1108 #endif
1109
1110 #ifdef EXIM_SCM_CR_TYPE
1111 for (struct cmsghdr * cp = CMSG_FIRSTHDR(&msg);
1112      cp;
1113      cp = CMSG_NXTHDR(&msg, cp))
1114   if (cp->cmsg_level == SOL_SOCKET && cp->cmsg_type == EXIM_SCM_CR_TYPE)
1115   {
1116 # ifdef SCM_CREDENTIALS                                 /* Linux */
1117   struct ucred * cr = (struct ucred *) CMSG_DATA(cp);
1118   if (cr->uid && cr->uid != exim_uid)
1119     {
1120     DEBUG(D_queue_run) debug_printf("%s: sender creds pid %d uid %d gid %d\n",
1121       __FUNCTION__, (int)cr->pid, (int)cr->uid, (int)cr->gid);
1122     return FALSE;
1123     }
1124 # elif defined(LOCAL_CREDS)                             /* BSD-ish */
1125   struct sockcred * cr = (struct sockcred *) CMSG_DATA(cp);
1126   if (cr->sc_uid && cr->sc_uid != exim_uid)
1127     {
1128     DEBUG(D_queue_run) debug_printf("%s: sender creds pid ??? uid %d gid %d\n",
1129       __FUNCTION__, (int)cr->sc_uid, (int)cr->sc_gid);
1130     return FALSE;
1131     }
1132 # endif
1133   break;
1134   }
1135 #endif
1136
1137 buf[sz] = 0;
1138 switch (buf[0])
1139   {
1140 #ifdef EXPERIMENTAL_QUEUE_RAMP
1141   case NOTIFY_MSG_QRUN:
1142     /* this should be a message_id */
1143     DEBUG(D_queue_run)
1144       debug_printf("%s: qrunner trigger: %s\n", __FUNCTION__, buf+1);
1145     memcpy(queuerun_msgid, buf+1, MESSAGE_ID_LENGTH+1);
1146     return TRUE;
1147 #endif  /*EXPERIMENTAL_QUEUE_RAMP*/
1148
1149   case NOTIFY_QUEUE_SIZE_REQ:
1150     {
1151     uschar buf[16];
1152     int len = snprintf(CS buf, sizeof(buf), "%u", queue_count_cached());
1153
1154     DEBUG(D_queue_run)
1155       debug_printf("%s: queue size request: %s\n", __FUNCTION__, buf);
1156
1157     if (sendto(daemon_notifier_fd, buf, len, 0,
1158                 (const struct sockaddr *)&sa_un, msg.msg_namelen) < 0)
1159       log_write(0, LOG_MAIN|LOG_PANIC,
1160         "%s: sendto: %s\n", __FUNCTION__, strerror(errno));
1161     return FALSE;
1162     }
1163   }
1164 return FALSE;
1165 }
1166
1167
1168 /*************************************************
1169 *              Exim Daemon Mainline              *
1170 *************************************************/
1171
1172 /* The daemon can do two jobs, either of which is optional:
1173
1174 (1) Listens for incoming SMTP calls and spawns off a sub-process to handle
1175 each one. This is requested by the -bd option, with -oX specifying the SMTP
1176 port on which to listen (for testing).
1177
1178 (2) Spawns a queue-running process every so often. This is controlled by the
1179 -q option with a an interval time. (If no time is given, a single queue run
1180 is done from the main function, and control doesn't get here.)
1181
1182 Root privilege is required in order to attach to port 25. Some systems require
1183 it when calling socket() rather than bind(). To cope with all cases, we run as
1184 root for both socket() and bind(). Some systems also require root in order to
1185 write to the pid file directory. This function must therefore be called as root
1186 if it is to work properly in all circumstances. Once the socket is bound and
1187 the pid file written, root privilege is given up if there is an exim uid.
1188
1189 There are no arguments to this function, and it never returns. */
1190
1191 void
1192 daemon_go(void)
1193 {
1194 struct passwd *pw;
1195 int *listen_sockets = NULL;
1196 int listen_socket_count = 0;
1197 ip_address_item *addresses = NULL;
1198 time_t last_connection_time = (time_t)0;
1199 int local_queue_run_max = atoi(CS expand_string(queue_run_max));
1200
1201 process_purpose = US"daemon";
1202
1203 /* If any debugging options are set, turn on the D_pid bit so that all
1204 debugging lines get the pid added. */
1205
1206 DEBUG(D_any|D_v) debug_selector |= D_pid;
1207
1208 if (f.inetd_wait_mode)
1209   {
1210   listen_socket_count = 1;
1211   listen_sockets = store_get(sizeof(int), FALSE);
1212   (void) close(3);
1213   if (dup2(0, 3) == -1)
1214     log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1215         "failed to dup inetd socket safely away: %s", strerror(errno));
1216
1217   listen_sockets[0] = 3;
1218   (void) close(0);
1219   (void) close(1);
1220   (void) close(2);
1221   exim_nullstd();
1222
1223   if (debug_file == stderr)
1224     {
1225     /* need a call to log_write before call to open debug_file, so that
1226     log.c:file_path has been initialised.  This is unfortunate. */
1227     log_write(0, LOG_MAIN, "debugging Exim in inetd wait mode starting");
1228
1229     fclose(debug_file);
1230     debug_file = NULL;
1231     exim_nullstd(); /* re-open fd2 after we just closed it again */
1232     debug_logging_activate(US"-wait", NULL);
1233     }
1234
1235   DEBUG(D_any) debug_printf("running in inetd wait mode\n");
1236
1237   /* As per below, when creating sockets ourselves, we handle tcp_nodelay for
1238   our own buffering; we assume though that inetd set the socket REUSEADDR. */
1239
1240   if (tcp_nodelay)
1241     if (setsockopt(3, IPPROTO_TCP, TCP_NODELAY, US &on, sizeof(on)))
1242       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to set socket NODELAY: %s",
1243         strerror(errno));
1244   }
1245
1246
1247 if (f.inetd_wait_mode || f.daemon_listen)
1248   {
1249   /* If any option requiring a load average to be available during the
1250   reception of a message is set, call os_getloadavg() while we are root
1251   for those OS for which this is necessary the first time it is called (in
1252   order to perform an "open" on the kernel memory file). */
1253
1254   #ifdef LOAD_AVG_NEEDS_ROOT
1255   if (queue_only_load >= 0 || smtp_load_reserve >= 0 ||
1256        (deliver_queue_load_max >= 0 && deliver_drop_privilege))
1257     (void)os_getloadavg();
1258   #endif
1259   }
1260
1261
1262 /* Do the preparation for setting up a listener on one or more interfaces, and
1263 possible on various ports. This is controlled by the combination of
1264 local_interfaces (which can set IP addresses and ports) and daemon_smtp_port
1265 (which is a list of default ports to use for those items in local_interfaces
1266 that do not specify a port). The -oX command line option can be used to
1267 override one or both of these options.
1268
1269 If local_interfaces is not set, the default is to listen on all interfaces.
1270 When it is set, it can include "all IPvx interfaces" as an item. This is useful
1271 when different ports are in use.
1272
1273 It turns out that listening on all interfaces is messy in an IPv6 world,
1274 because several different implementation approaches have been taken. This code
1275 is now supposed to work with all of them. The point of difference is whether an
1276 IPv6 socket that is listening on all interfaces will receive incoming IPv4
1277 calls or not. We also have to cope with the case when IPv6 libraries exist, but
1278 there is no IPv6 support in the kernel.
1279
1280 . On Solaris, an IPv6 socket will accept IPv4 calls, and give them as mapped
1281   addresses. However, if an IPv4 socket is also listening on all interfaces,
1282   calls are directed to the appropriate socket.
1283
1284 . On (some versions of) Linux, an IPv6 socket will accept IPv4 calls, and
1285   give them as mapped addresses, but an attempt also to listen on an IPv4
1286   socket on all interfaces causes an error.
1287
1288 . On OpenBSD, an IPv6 socket will not accept IPv4 calls. You have to set up
1289   two sockets if you want to accept both kinds of call.
1290
1291 . FreeBSD is like OpenBSD, but it has the IPV6_V6ONLY socket option, which
1292   can be turned off, to make it behave like the versions of Linux described
1293   above.
1294
1295 . I heard a report that the USAGI IPv6 stack for Linux has implemented
1296   IPV6_V6ONLY.
1297
1298 So, what we do when IPv6 is supported is as follows:
1299
1300  (1) After it is set up, the list of interfaces is scanned for wildcard
1301      addresses. If an IPv6 and an IPv4 wildcard are both found for the same
1302      port, the list is re-arranged so that they are together, with the IPv6
1303      wildcard first.
1304
1305  (2) If the creation of a wildcard IPv6 socket fails, we just log the error and
1306      carry on if an IPv4 wildcard socket for the same port follows later in the
1307      list. This allows Exim to carry on in the case when the kernel has no IPv6
1308      support.
1309
1310  (3) Having created an IPv6 wildcard socket, we try to set IPV6_V6ONLY if that
1311      option is defined. However, if setting fails, carry on regardless (but log
1312      the incident).
1313
1314  (4) If binding or listening on an IPv6 wildcard socket fails, it is a serious
1315      error.
1316
1317  (5) If binding or listening on an IPv4 wildcard socket fails with the error
1318      EADDRINUSE, and a previous interface was an IPv6 wildcard for the same
1319      port (which must have succeeded or we wouldn't have got this far), we
1320      assume we are in the situation where just a single socket is permitted,
1321      and ignore the error.
1322
1323 Phew!
1324
1325 The preparation code decodes options and sets up the relevant data. We do this
1326 first, so that we can return non-zero if there are any syntax errors, and also
1327 write to stderr. */
1328
1329 if (f.daemon_listen && !f.inetd_wait_mode)
1330   {
1331   int *default_smtp_port;
1332   int sep;
1333   int pct = 0;
1334   uschar *s;
1335   const uschar * list;
1336   uschar *local_iface_source = US"local_interfaces";
1337   ip_address_item *ipa;
1338   ip_address_item **pipa;
1339
1340   /* If -oX was used, disable the writing of a pid file unless -oP was
1341   explicitly used to force it. Then scan the string given to -oX. Any items
1342   that contain neither a dot nor a colon are used to override daemon_smtp_port.
1343   Any other items are used to override local_interfaces. */
1344
1345   if (override_local_interfaces)
1346     {
1347     gstring * new_smtp_port = NULL;
1348     gstring * new_local_interfaces = NULL;
1349
1350     if (!override_pid_file_path) write_pid = FALSE;
1351
1352     list = override_local_interfaces;
1353     sep = 0;
1354     while ((s = string_nextinlist(&list, &sep, NULL, 0)))
1355       {
1356       uschar joinstr[4];
1357       gstring ** gp = Ustrpbrk(s, ".:") ? &new_local_interfaces : &new_smtp_port;
1358
1359       if (!*gp)
1360         {
1361         joinstr[0] = sep;
1362         joinstr[1] = ' ';
1363         *gp = string_catn(*gp, US"<", 1);
1364         }
1365
1366       *gp = string_catn(*gp, joinstr, 2);
1367       *gp = string_cat (*gp, s);
1368       }
1369
1370     if (new_smtp_port)
1371       {
1372       daemon_smtp_port = string_from_gstring(new_smtp_port);
1373       DEBUG(D_any) debug_printf("daemon_smtp_port overridden by -oX:\n  %s\n",
1374         daemon_smtp_port);
1375       }
1376
1377     if (new_local_interfaces)
1378       {
1379       local_interfaces = string_from_gstring(new_local_interfaces);
1380       local_iface_source = US"-oX data";
1381       DEBUG(D_any) debug_printf("local_interfaces overridden by -oX:\n  %s\n",
1382         local_interfaces);
1383       }
1384     }
1385
1386   /* Create a list of default SMTP ports, to be used if local_interfaces
1387   contains entries without explicit ports. First count the number of ports, then
1388   build a translated list in a vector. */
1389
1390   list = daemon_smtp_port;
1391   sep = 0;
1392   while ((s = string_nextinlist(&list, &sep, NULL, 0)))
1393     pct++;
1394   default_smtp_port = store_get((pct+1) * sizeof(int), FALSE);
1395   list = daemon_smtp_port;
1396   sep = 0;
1397   for (pct = 0;
1398        (s = string_nextinlist(&list, &sep, NULL, 0));
1399        pct++)
1400     {
1401     if (isdigit(*s))
1402       {
1403       uschar *end;
1404       default_smtp_port[pct] = Ustrtol(s, &end, 0);
1405       if (end != s + Ustrlen(s))
1406         log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "invalid SMTP port: %s", s);
1407       }
1408     else
1409       {
1410       struct servent *smtp_service = getservbyname(CS s, "tcp");
1411       if (!smtp_service)
1412         log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "TCP port \"%s\" not found", s);
1413       default_smtp_port[pct] = ntohs(smtp_service->s_port);
1414       }
1415     }
1416   default_smtp_port[pct] = 0;
1417
1418   /* Check the list of TLS-on-connect ports and do name lookups if needed */
1419
1420   list = tls_in.on_connect_ports;
1421   sep = 0;
1422   while ((s = string_nextinlist(&list, &sep, big_buffer, big_buffer_size)))
1423     if (!isdigit(*s))
1424       {
1425       gstring * g = NULL;
1426
1427       list = tls_in.on_connect_ports;
1428       tls_in.on_connect_ports = NULL;
1429       sep = 0;
1430       while ((s = string_nextinlist(&list, &sep, big_buffer, big_buffer_size)))
1431         {
1432         if (!isdigit(*s))
1433           {
1434           struct servent * smtp_service = getservbyname(CS s, "tcp");
1435           if (!smtp_service)
1436             log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "TCP port \"%s\" not found", s);
1437           s = string_sprintf("%d", (int)ntohs(smtp_service->s_port));
1438           }
1439         g = string_append_listele(g, ':', s);
1440         }
1441       if (g)
1442         tls_in.on_connect_ports = g->s;
1443       break;
1444       }
1445
1446   /* Create the list of local interfaces, possibly with ports included. This
1447   list may contain references to 0.0.0.0 and ::0 as wildcards. These special
1448   values are converted below. */
1449
1450   addresses = host_build_ifacelist(local_interfaces, local_iface_source);
1451
1452   /* In the list of IP addresses, convert 0.0.0.0 into an empty string, and ::0
1453   into the string ":". We use these to recognize wildcards in IPv4 and IPv6. In
1454   fact, many IP stacks recognize 0.0.0.0 and ::0 and handle them as wildcards
1455   anyway, but we need to know which are the wildcard addresses, and the shorter
1456   strings are neater.
1457
1458   In the same scan, fill in missing port numbers from the default list. When
1459   there is more than one item in the list, extra items are created. */
1460
1461   for (ipa = addresses; ipa; ipa = ipa->next)
1462     {
1463     if (Ustrcmp(ipa->address, "0.0.0.0") == 0)
1464       ipa->address[0] = 0;
1465     else if (Ustrcmp(ipa->address, "::0") == 0)
1466       {
1467       ipa->address[0] = ':';
1468       ipa->address[1] = 0;
1469       }
1470
1471     if (ipa->port > 0) continue;
1472
1473     if (daemon_smtp_port[0] <= 0)
1474       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "no port specified for interface "
1475         "%s and daemon_smtp_port is unset; cannot start daemon",
1476         ipa->address[0] == 0 ? US"\"all IPv4\"" :
1477         ipa->address[1] == 0 ? US"\"all IPv6\"" : ipa->address);
1478
1479     ipa->port = default_smtp_port[0];
1480     for (int i = 1; default_smtp_port[i] > 0; i++)
1481       {
1482       ip_address_item *new = store_get(sizeof(ip_address_item), FALSE);
1483
1484       memcpy(new->address, ipa->address, Ustrlen(ipa->address) + 1);
1485       new->port = default_smtp_port[i];
1486       new->next = ipa->next;
1487       ipa->next = new;
1488       ipa = new;
1489       }
1490     }
1491
1492   /* Scan the list of addresses for wildcards. If we find an IPv4 and an IPv6
1493   wildcard for the same port, ensure that (a) they are together and (b) the
1494   IPv6 address comes first. This makes handling the messy features easier, and
1495   also simplifies the construction of the "daemon started" log line. */
1496
1497   pipa = &addresses;
1498   for (ipa = addresses; ipa; pipa = &ipa->next, ipa = ipa->next)
1499     {
1500     ip_address_item *ipa2;
1501
1502     /* Handle an IPv4 wildcard */
1503
1504     if (ipa->address[0] == 0)
1505       for (ipa2 = ipa; ipa2->next; ipa2 = ipa2->next)
1506         {
1507         ip_address_item *ipa3 = ipa2->next;
1508         if (ipa3->address[0] == ':' &&
1509             ipa3->address[1] == 0 &&
1510             ipa3->port == ipa->port)
1511           {
1512           ipa2->next = ipa3->next;
1513           ipa3->next = ipa;
1514           *pipa = ipa3;
1515           break;
1516           }
1517         }
1518
1519     /* Handle an IPv6 wildcard. */
1520
1521     else if (ipa->address[0] == ':' && ipa->address[1] == 0)
1522       for (ipa2 = ipa; ipa2->next; ipa2 = ipa2->next)
1523         {
1524         ip_address_item *ipa3 = ipa2->next;
1525         if (ipa3->address[0] == 0 && ipa3->port == ipa->port)
1526           {
1527           ipa2->next = ipa3->next;
1528           ipa3->next = ipa->next;
1529           ipa->next = ipa3;
1530           ipa = ipa3;
1531           break;
1532           }
1533         }
1534     }
1535
1536   /* Get a vector to remember all the sockets in */
1537
1538   for (ipa = addresses; ipa; ipa = ipa->next)
1539     listen_socket_count++;
1540   listen_sockets = store_get(sizeof(int) * listen_socket_count, FALSE);
1541
1542   } /* daemon_listen but not inetd_wait_mode */
1543
1544 if (f.daemon_listen)
1545   {
1546
1547   /* Do a sanity check on the max connects value just to save us from getting
1548   a huge amount of store. */
1549
1550   if (smtp_accept_max > 4095) smtp_accept_max = 4096;
1551
1552   /* There's no point setting smtp_accept_queue unless it is less than the max
1553   connects limit. The configuration reader ensures that the max is set if the
1554   queue-only option is set. */
1555
1556   if (smtp_accept_queue > smtp_accept_max) smtp_accept_queue = 0;
1557
1558   /* Get somewhere to keep the list of SMTP accepting pids if we are keeping
1559   track of them for total number and queue/host limits. */
1560
1561   if (smtp_accept_max > 0)
1562     {
1563     smtp_slots = store_get(smtp_accept_max * sizeof(smtp_slot), FALSE);
1564     for (int i = 0; i < smtp_accept_max; i++) smtp_slots[i] = empty_smtp_slot;
1565     }
1566   }
1567
1568 /* The variable background_daemon is always false when debugging, but
1569 can also be forced false in order to keep a non-debugging daemon in the
1570 foreground. If background_daemon is true, close all open file descriptors that
1571 we know about, but then re-open stdin, stdout, and stderr to /dev/null.  Also
1572 do this for inetd_wait mode.
1573
1574 This is protection against any called functions (in libraries, or in
1575 Perl, or whatever) that think they can write to stderr (or stdout). Before this
1576 was added, it was quite likely that an SMTP connection would use one of these
1577 file descriptors, in which case writing random stuff to it caused chaos.
1578
1579 Then disconnect from the controlling terminal, Most modern Unixes seem to have
1580 setsid() for getting rid of the controlling terminal. For any OS that doesn't,
1581 setsid() can be #defined as a no-op, or as something else. */
1582
1583 if (f.background_daemon || f.inetd_wait_mode)
1584   {
1585   log_close_all();    /* Just in case anything was logged earlier */
1586   search_tidyup();    /* Just in case any were used in reading the config. */
1587   (void)close(0);           /* Get rid of stdin/stdout/stderr */
1588   (void)close(1);
1589   (void)close(2);
1590   exim_nullstd();     /* Connect stdin/stdout/stderr to /dev/null */
1591   log_stderr = NULL;  /* So no attempt to copy paniclog output */
1592   }
1593
1594 if (f.background_daemon)
1595   {
1596   /* If the parent process of this one has pid == 1, we are re-initializing the
1597   daemon as the result of a SIGHUP. In this case, there is no need to do
1598   anything, because the controlling terminal has long gone. Otherwise, fork, in
1599   case current process is a process group leader (see 'man setsid' for an
1600   explanation) before calling setsid(). */
1601
1602   if (getppid() != 1)
1603     {
1604     pid_t pid = exim_fork(US"daemon");
1605     if (pid < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1606       "fork() failed when starting daemon: %s", strerror(errno));
1607     if (pid > 0) exit(EXIT_SUCCESS);      /* in parent process, just exit */
1608     (void)setsid();                       /* release controlling terminal */
1609     }
1610   }
1611
1612 /* We are now in the disconnected, daemon process (unless debugging). Set up
1613 the listening sockets if required. */
1614
1615 daemon_notifier_socket();
1616
1617 if (f.daemon_listen && !f.inetd_wait_mode)
1618   {
1619   int sk;
1620   ip_address_item *ipa;
1621
1622   /* For each IP address, create a socket, bind it to the appropriate port, and
1623   start listening. See comments above about IPv6 sockets that may or may not
1624   accept IPv4 calls when listening on all interfaces. We also have to cope with
1625   the case of a system with IPv6 libraries, but no IPv6 support in the kernel.
1626   listening, provided a wildcard IPv4 socket for the same port follows. */
1627
1628   for (ipa = addresses, sk = 0; sk < listen_socket_count; ipa = ipa->next, sk++)
1629     {
1630     BOOL wildcard;
1631     ip_address_item *ipa2;
1632     int af;
1633
1634     if (Ustrchr(ipa->address, ':') != NULL)
1635       {
1636       af = AF_INET6;
1637       wildcard = ipa->address[1] == 0;
1638       }
1639     else
1640       {
1641       af = AF_INET;
1642       wildcard = ipa->address[0] == 0;
1643       }
1644
1645     if ((listen_sockets[sk] = ip_socket(SOCK_STREAM, af)) < 0)
1646       {
1647       if (check_special_case(0, addresses, ipa, FALSE))
1648         {
1649         log_write(0, LOG_MAIN, "Failed to create IPv6 socket for wildcard "
1650           "listening (%s): will use IPv4", strerror(errno));
1651         goto SKIP_SOCKET;
1652         }
1653       log_write(0, LOG_PANIC_DIE, "IPv%c socket creation failed: %s",
1654         (af == AF_INET6)? '6' : '4', strerror(errno));
1655       }
1656
1657     /* If this is an IPv6 wildcard socket, set IPV6_V6ONLY if that option is
1658     available. Just log failure (can get protocol not available, just like
1659     socket creation can). */
1660
1661 #ifdef IPV6_V6ONLY
1662     if (af == AF_INET6 && wildcard &&
1663         setsockopt(listen_sockets[sk], IPPROTO_IPV6, IPV6_V6ONLY, CS (&on),
1664           sizeof(on)) < 0)
1665       log_write(0, LOG_MAIN, "Setting IPV6_V6ONLY on daemon's IPv6 wildcard "
1666         "socket failed (%s): carrying on without it", strerror(errno));
1667 #endif  /* IPV6_V6ONLY */
1668
1669     /* Set SO_REUSEADDR so that the daemon can be restarted while a connection
1670     is being handled.  Without this, a connection will prevent reuse of the
1671     smtp port for listening. */
1672
1673     if (setsockopt(listen_sockets[sk], SOL_SOCKET, SO_REUSEADDR,
1674                    US (&on), sizeof(on)) < 0)
1675       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "setting SO_REUSEADDR on socket "
1676         "failed when starting daemon: %s", strerror(errno));
1677
1678     /* Set TCP_NODELAY; Exim does its own buffering. There is a switch to
1679     disable this because it breaks some broken clients. */
1680
1681     if (tcp_nodelay) setsockopt(listen_sockets[sk], IPPROTO_TCP, TCP_NODELAY,
1682       US (&on), sizeof(on));
1683
1684     /* Now bind the socket to the required port; if Exim is being restarted
1685     it may not always be possible to bind immediately, even with SO_REUSEADDR
1686     set, so try 10 times, waiting between each try. After 10 failures, we give
1687     up. In an IPv6 environment, if bind () fails with the error EADDRINUSE and
1688     we are doing wildcard IPv4 listening and there was a previous IPv6 wildcard
1689     address for the same port, ignore the error on the grounds that we must be
1690     in a system where the IPv6 socket accepts both kinds of call. This is
1691     necessary for (some release of) USAGI Linux; other IP stacks fail at the
1692     listen() stage instead. */
1693
1694 #ifdef TCP_FASTOPEN
1695     f.tcp_fastopen_ok = TRUE;
1696 #endif
1697     for(;;)
1698       {
1699       uschar *msg, *addr;
1700       if (ip_bind(listen_sockets[sk], af, ipa->address, ipa->port) >= 0) break;
1701       if (check_special_case(errno, addresses, ipa, TRUE))
1702         {
1703         DEBUG(D_any) debug_printf("wildcard IPv4 bind() failed after IPv6 "
1704           "listen() success; EADDRINUSE ignored\n");
1705         (void)close(listen_sockets[sk]);
1706         goto SKIP_SOCKET;
1707         }
1708       msg = US strerror(errno);
1709       addr = wildcard
1710         ? af == AF_INET6
1711         ? US"(any IPv6)"
1712         : US"(any IPv4)"
1713         : ipa->address;
1714       if (daemon_startup_retries <= 0)
1715         log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1716           "socket bind() to port %d for address %s failed: %s: "
1717           "daemon abandoned", ipa->port, addr, msg);
1718       log_write(0, LOG_MAIN, "socket bind() to port %d for address %s "
1719         "failed: %s: waiting %s before trying again (%d more %s)",
1720         ipa->port, addr, msg, readconf_printtime(daemon_startup_sleep),
1721         daemon_startup_retries, (daemon_startup_retries > 1)? "tries" : "try");
1722       daemon_startup_retries--;
1723       sleep(daemon_startup_sleep);
1724       }
1725
1726     DEBUG(D_any)
1727       if (wildcard)
1728         debug_printf("listening on all interfaces (IPv%c) port %d\n",
1729           af == AF_INET6 ? '6' : '4', ipa->port);
1730       else
1731         debug_printf("listening on %s port %d\n", ipa->address, ipa->port);
1732
1733 #if defined(TCP_FASTOPEN) && !defined(__APPLE__)
1734     if (  f.tcp_fastopen_ok
1735        && setsockopt(listen_sockets[sk], IPPROTO_TCP, TCP_FASTOPEN,
1736                     &smtp_connect_backlog, sizeof(smtp_connect_backlog)))
1737       {
1738       DEBUG(D_any) debug_printf("setsockopt FASTOPEN: %s\n", strerror(errno));
1739       f.tcp_fastopen_ok = FALSE;
1740       }
1741 #endif
1742
1743     /* Start listening on the bound socket, establishing the maximum backlog of
1744     connections that is allowed. On success, continue to the next address. */
1745
1746     if (listen(listen_sockets[sk], smtp_connect_backlog) >= 0)
1747       {
1748 #if defined(TCP_FASTOPEN) && defined(__APPLE__)
1749       if (  f.tcp_fastopen_ok
1750          && setsockopt(listen_sockets[sk], IPPROTO_TCP, TCP_FASTOPEN,
1751                       &on, sizeof(on)))
1752         {
1753         DEBUG(D_any) debug_printf("setsockopt FASTOPEN: %s\n", strerror(errno));
1754         f.tcp_fastopen_ok = FALSE;
1755         }
1756 #endif
1757       continue;
1758       }
1759
1760     /* Listening has failed. In an IPv6 environment, as for bind(), if listen()
1761     fails with the error EADDRINUSE and we are doing IPv4 wildcard listening
1762     and there was a previous successful IPv6 wildcard listen on the same port,
1763     we want to ignore the error on the grounds that we must be in a system
1764     where the IPv6 socket accepts both kinds of call. */
1765
1766     if (!check_special_case(errno, addresses, ipa, TRUE))
1767       log_write(0, LOG_PANIC_DIE, "listen() failed on interface %s: %s",
1768         wildcard
1769         ? af == AF_INET6 ? US"(any IPv6)" : US"(any IPv4)" : ipa->address,
1770         strerror(errno));
1771
1772     DEBUG(D_any) debug_printf("wildcard IPv4 listen() failed after IPv6 "
1773       "listen() success; EADDRINUSE ignored\n");
1774     (void)close(listen_sockets[sk]);
1775
1776     /* Come here if there has been a problem with the socket which we
1777     are going to ignore. We remove the address from the chain, and back up the
1778     counts. */
1779
1780   SKIP_SOCKET:
1781     sk--;                          /* Back up the count */
1782     listen_socket_count--;         /* Reduce the total */
1783     if (ipa == addresses) addresses = ipa->next; else
1784       {
1785       for (ipa2 = addresses; ipa2->next != ipa; ipa2 = ipa2->next);
1786       ipa2->next = ipa->next;
1787       ipa = ipa2;
1788       }
1789     }          /* End of bind/listen loop for each address */
1790   }            /* End of setup for listening */
1791
1792
1793 /* If we are not listening, we want to write a pid file only if -oP was
1794 explicitly given. */
1795
1796 else if (!override_pid_file_path)
1797   write_pid = FALSE;
1798
1799 /* Write the pid to a known file for assistance in identification, if required.
1800 We do this before giving up root privilege, because on some systems it is
1801 necessary to be root in order to write into the pid file directory. There's
1802 nothing to stop multiple daemons running, as long as no more than one listens
1803 on a given TCP/IP port on the same interface(s). However, in these
1804 circumstances it gets far too complicated to mess with pid file names
1805 automatically. Consequently, Exim 4 writes a pid file only
1806
1807   (a) When running in the test harness, or
1808   (b) When -bd is used and -oX is not used, or
1809   (c) When -oP is used to supply a path.
1810
1811 The variable daemon_write_pid is used to control this. */
1812
1813 if (f.running_in_test_harness || write_pid)
1814   {
1815   FILE *f;
1816
1817   set_pid_file_path();
1818   if ((f = modefopen(pid_file_path, "wb", 0644)))
1819     {
1820     (void)fprintf(f, "%d\n", (int)getpid());
1821     (void)fclose(f);
1822     DEBUG(D_any) debug_printf("pid written to %s\n", pid_file_path);
1823     }
1824   else
1825     DEBUG(D_any)
1826       debug_printf("%s\n", string_open_failed(errno, "pid file %s",
1827         pid_file_path));
1828   }
1829
1830 /* Set up the handler for SIGHUP, which causes a restart of the daemon. */
1831
1832 sighup_seen = FALSE;
1833 signal(SIGHUP, sighup_handler);
1834
1835 /* Give up root privilege at this point (assuming that exim_uid and exim_gid
1836 are not root). The third argument controls the running of initgroups().
1837 Normally we do this, in order to set up the groups for the Exim user. However,
1838 if we are not root at this time - some odd installations run that way - we
1839 cannot do this. */
1840
1841 exim_setugid(exim_uid, exim_gid, geteuid()==root_uid, US"running as a daemon");
1842
1843 /* Update the originator_xxx fields so that received messages as listed as
1844 coming from Exim, not whoever started the daemon. */
1845
1846 originator_uid = exim_uid;
1847 originator_gid = exim_gid;
1848 originator_login = (pw = getpwuid(exim_uid))
1849   ? string_copy_perm(US pw->pw_name, FALSE) : US"exim";
1850
1851 /* Get somewhere to keep the list of queue-runner pids if we are keeping track
1852 of them (and also if we are doing queue runs). */
1853
1854 if (queue_interval > 0 && local_queue_run_max > 0)
1855   {
1856   queue_pid_slots = store_get(local_queue_run_max * sizeof(pid_t), FALSE);
1857   for (int i = 0; i < local_queue_run_max; i++) queue_pid_slots[i] = 0;
1858   }
1859
1860 /* Set up the handler for termination of child processes, and the one
1861 telling us to die. */
1862
1863 sigchld_seen = FALSE;
1864 os_non_restarting_signal(SIGCHLD, main_sigchld_handler);
1865
1866 sigterm_seen = FALSE;
1867 os_non_restarting_signal(SIGTERM, main_sigterm_handler);
1868
1869 /* If we are to run the queue periodically, pretend the alarm has just gone
1870 off. This will cause the first queue-runner to get kicked off straight away. */
1871
1872 sigalrm_seen = (queue_interval > 0);
1873
1874 /* Log the start up of a daemon - at least one of listening or queue running
1875 must be set up. */
1876
1877 if (f.inetd_wait_mode)
1878   {
1879   uschar *p = big_buffer;
1880
1881   if (inetd_wait_timeout >= 0)
1882     sprintf(CS p, "terminating after %d seconds", inetd_wait_timeout);
1883   else
1884     sprintf(CS p, "with no wait timeout");
1885
1886   log_write(0, LOG_MAIN,
1887     "exim %s daemon started: pid=%d, launched with listening socket, %s",
1888     version_string, getpid(), big_buffer);
1889   set_process_info("daemon(%s): pre-listening socket", version_string);
1890
1891   /* set up the timeout logic */
1892   sigalrm_seen = TRUE;
1893   }
1894
1895 else if (f.daemon_listen)
1896   {
1897   int smtp_ports = 0;
1898   int smtps_ports = 0;
1899   ip_address_item * ipa;
1900   uschar * p;
1901   uschar * qinfo = queue_interval > 0
1902     ? string_sprintf("-q%s%s",
1903         f.queue_2stage ? "q" : "", readconf_printtime(queue_interval))
1904     : US"no queue runs";
1905
1906   /* Build a list of listening addresses in big_buffer, but limit it to 10
1907   items. The style is for backwards compatibility.
1908
1909   It is now possible to have some ports listening for SMTPS (the old,
1910   deprecated protocol that starts TLS without using STARTTLS), and others
1911   listening for standard SMTP. Keep their listings separate. */
1912
1913   for (int j = 0, i; j < 2; j++)
1914     {
1915     for (i = 0, ipa = addresses; i < 10 && ipa; i++, ipa = ipa->next)
1916       {
1917       /* First time round, look for SMTP ports; second time round, look for
1918       SMTPS ports. Build IP+port strings. */
1919
1920       if (host_is_tls_on_connect_port(ipa->port) == (j > 0))
1921         {
1922         if (j == 0)
1923           smtp_ports++;
1924         else
1925           smtps_ports++;
1926
1927         /* Now the information about the port (and sometimes interface) */
1928
1929         if (ipa->address[0] == ':' && ipa->address[1] == 0)
1930           {                                             /* v6 wildcard */
1931           if (ipa->next && ipa->next->address[0] == 0 &&
1932               ipa->next->port == ipa->port)
1933             {
1934             ipa->log = string_sprintf(" port %d (IPv6 and IPv4)", ipa->port);
1935             (ipa = ipa->next)->log = NULL;
1936             }
1937           else if (ipa->v6_include_v4)
1938             ipa->log = string_sprintf(" port %d (IPv6 with IPv4)", ipa->port);
1939           else
1940             ipa->log = string_sprintf(" port %d (IPv6)", ipa->port);
1941           }
1942         else if (ipa->address[0] == 0)                  /* v4 wildcard */
1943           ipa->log = string_sprintf(" port %d (IPv4)", ipa->port);
1944         else                            /* check for previously-seen IP */
1945           {
1946           ip_address_item * i2;
1947           for (i2 = addresses; i2 != ipa; i2 = i2->next)
1948             if (  host_is_tls_on_connect_port(i2->port) == (j > 0)
1949                && Ustrcmp(ipa->address, i2->address) == 0
1950                )
1951               {                         /* found; append port to list */
1952               for (p = i2->log; *p; ) p++;      /* end of existing string */
1953               if (*--p == '}') *p = '\0';       /* drop EOL */
1954               while (isdigit(*--p)) ;           /* char before port */
1955
1956               i2->log = *p == ':'               /* no list yet? */
1957                 ? string_sprintf("%.*s{%s,%d}",
1958                   (int)(p - i2->log + 1), i2->log, p+1, ipa->port)
1959                 : string_sprintf("%s,%d}", i2->log, ipa->port);
1960               ipa->log = NULL;
1961               break;
1962               }
1963           if (i2 == ipa)                /* first-time IP */
1964             ipa->log = string_sprintf(" [%s]:%d", ipa->address, ipa->port);
1965           }
1966         }
1967       }
1968     }
1969
1970   p = big_buffer;
1971   for (int j = 0, i; j < 2; j++)
1972     {
1973     /* First time round, look for SMTP ports; second time round, look for
1974     SMTPS ports. For the first one of each, insert leading text. */
1975
1976     if (j == 0)
1977       {
1978       if (smtp_ports > 0)
1979         p += sprintf(CS p, "SMTP on");
1980       }
1981     else
1982       if (smtps_ports > 0)
1983         p += sprintf(CS p, "%sSMTPS on",
1984           smtp_ports == 0 ? "" : " and for ");
1985
1986     /* Now the information about the port (and sometimes interface) */
1987
1988     for (i = 0, ipa = addresses; i < 10 && ipa; i++, ipa = ipa->next)
1989       if (host_is_tls_on_connect_port(ipa->port) == (j > 0))
1990         if (ipa->log)
1991           p += sprintf(CS p, "%s",  ipa->log);
1992
1993     if (ipa)
1994       p += sprintf(CS p, " ...");
1995     }
1996
1997   log_write(0, LOG_MAIN,
1998     "exim %s daemon started: pid=%d, %s, listening for %s",
1999     version_string, getpid(), qinfo, big_buffer);
2000   set_process_info("daemon(%s): %s, listening for %s",
2001     version_string, qinfo, big_buffer);
2002   }
2003
2004 else
2005   {
2006   uschar * s = *queue_name
2007     ? string_sprintf("-qG%s/%s", queue_name, readconf_printtime(queue_interval))
2008     : string_sprintf("-q%s", readconf_printtime(queue_interval));
2009   log_write(0, LOG_MAIN,
2010     "exim %s daemon started: pid=%d, %s, not listening for SMTP",
2011     version_string, getpid(), s);
2012   set_process_info("daemon(%s): %s, not listening", version_string, s);
2013   }
2014
2015 /* Do any work it might be useful to amortize over our children
2016 (eg: compile regex) */
2017
2018 dns_pattern_init();
2019 smtp_deliver_init();    /* Used for callouts */
2020
2021 #ifndef DISABLE_DKIM
2022   {
2023 # ifdef MEASURE_TIMING
2024   struct timeval t0;
2025   gettimeofday(&t0, NULL);
2026 # endif
2027   dkim_exim_init();
2028 # ifdef MEASURE_TIMING
2029   report_time_since(&t0, US"dkim_exim_init (delta)");
2030 # endif
2031   }
2032 #endif
2033
2034 #ifdef WITH_CONTENT_SCAN
2035 malware_init();
2036 #endif
2037 #ifdef SUPPORT_SPF
2038 spf_init();
2039 #endif
2040
2041 /* Close the log so it can be renamed and moved. In the few cases below where
2042 this long-running process writes to the log (always exceptional conditions), it
2043 closes the log afterwards, for the same reason. */
2044
2045 log_close_all();
2046
2047 DEBUG(D_any) debug_print_ids(US"daemon running with");
2048
2049 /* Any messages accepted via this route are going to be SMTP. */
2050
2051 smtp_input = TRUE;
2052
2053 #ifdef MEASURE_TIMING
2054 report_time_since(&timestamp_startup, US"daemon loop start");   /* testcase 0022 */
2055 #endif
2056
2057 /* Enter the never-ending loop... */
2058
2059 for (;;)
2060   {
2061   #if HAVE_IPV6
2062   struct sockaddr_in6 accepted;
2063   #else
2064   struct sockaddr_in accepted;
2065   #endif
2066
2067   EXIM_SOCKLEN_T len;
2068   pid_t pid;
2069
2070   if (sigterm_seen)
2071     daemon_die();       /* Does not return */
2072
2073   /* This code is placed first in the loop, so that it gets obeyed at the
2074   start, before the first wait, for the queue-runner case, so that the first
2075   one can be started immediately.
2076
2077   The other option is that we have an inetd wait timeout specified to -bw. */
2078
2079   if (sigalrm_seen)
2080     {
2081     if (inetd_wait_timeout > 0)
2082       {
2083       time_t resignal_interval = inetd_wait_timeout;
2084
2085       if (last_connection_time == (time_t)0)
2086         {
2087         DEBUG(D_any)
2088           debug_printf("inetd wait timeout expired, but still not seen first message, ignoring\n");
2089         }
2090       else
2091         {
2092         time_t now = time(NULL);
2093         if (now == (time_t)-1)
2094           {
2095           DEBUG(D_any) debug_printf("failed to get time: %s\n", strerror(errno));
2096           }
2097         else
2098           {
2099           if ((now - last_connection_time) >= inetd_wait_timeout)
2100             {
2101             DEBUG(D_any)
2102               debug_printf("inetd wait timeout %d expired, ending daemon\n",
2103                   inetd_wait_timeout);
2104             log_write(0, LOG_MAIN, "exim %s daemon terminating, inetd wait timeout reached.\n",
2105                 version_string);
2106             exit(EXIT_SUCCESS);
2107             }
2108           else
2109             {
2110             resignal_interval -= (now - last_connection_time);
2111             }
2112           }
2113         }
2114
2115       sigalrm_seen = FALSE;
2116       ALARM(resignal_interval);
2117       }
2118
2119     else
2120       {
2121       DEBUG(D_any) debug_printf("%s received\n",
2122 #ifdef EXPERIMENTAL_QUEUE_RAMP
2123         *queuerun_msgid ? "qrun notification" :
2124 #endif
2125         "SIGALRM");
2126
2127       /* Do a full queue run in a child process, if required, unless we already
2128       have enough queue runners on the go. If we are not running as root, a
2129       re-exec is required. */
2130
2131       if (  queue_interval > 0
2132          && (local_queue_run_max <= 0 || queue_run_count < local_queue_run_max))
2133         {
2134         if ((pid = exim_fork(US"queue-runner")) == 0)
2135           {
2136           /* Disable debugging if it's required only for the daemon process. We
2137           leave the above message, because it ties up with the "child ended"
2138           debugging messages. */
2139
2140           if (f.debug_daemon) debug_selector = 0;
2141
2142           /* Close any open listening sockets in the child */
2143
2144           close_daemon_sockets(daemon_notifier_fd,
2145             listen_sockets, listen_socket_count);
2146
2147           /* Reset SIGHUP and SIGCHLD in the child in both cases. */
2148
2149           signal(SIGHUP,  SIG_DFL);
2150           signal(SIGCHLD, SIG_DFL);
2151           signal(SIGTERM, SIG_DFL);
2152
2153           /* Re-exec if privilege has been given up, unless deliver_drop_
2154           privilege is set. Reset SIGALRM before exec(). */
2155
2156           if (geteuid() != root_uid && !deliver_drop_privilege)
2157             {
2158             uschar opt[8];
2159             uschar *p = opt;
2160             uschar *extra[7];
2161             int extracount = 1;
2162
2163             signal(SIGALRM, SIG_DFL);
2164             *p++ = '-';
2165             *p++ = 'q';
2166             if (  f.queue_2stage
2167 #ifdef EXPERIMENTAL_QUEUE_RAMP
2168                && !*queuerun_msgid
2169 #endif
2170                ) *p++ = 'q';
2171             if (f.queue_run_first_delivery) *p++ = 'i';
2172             if (f.queue_run_force) *p++ = 'f';
2173             if (f.deliver_force_thaw) *p++ = 'f';
2174             if (f.queue_run_local) *p++ = 'l';
2175             *p = 0;
2176             extra[0] = *queue_name
2177               ? string_sprintf("%sG%s", opt, queue_name) : opt;
2178
2179 #ifdef EXPERIMENTAL_QUEUE_RAMP
2180             if (*queuerun_msgid)
2181               {
2182               log_write(0, LOG_MAIN, "notify triggered queue run");
2183               extra[extracount++] = queuerun_msgid;     /* Trigger only the */
2184               extra[extracount++] = queuerun_msgid;     /* one message      */
2185               }
2186 #endif
2187
2188             /* If -R or -S were on the original command line, ensure they get
2189             passed on. */
2190
2191             if (deliver_selectstring)
2192               {
2193               extra[extracount++] = f.deliver_selectstring_regex ? US"-Rr" : US"-R";
2194               extra[extracount++] = deliver_selectstring;
2195               }
2196
2197             if (deliver_selectstring_sender)
2198               {
2199               extra[extracount++] = f.deliver_selectstring_sender_regex
2200                 ? US"-Sr" : US"-S";
2201               extra[extracount++] = deliver_selectstring_sender;
2202               }
2203
2204             /* Overlay this process with a new execution. */
2205
2206             (void)child_exec_exim(CEE_EXEC_PANIC, FALSE, NULL, FALSE, extracount,
2207               extra[0], extra[1], extra[2], extra[3], extra[4], extra[5], extra[6]);
2208
2209             /* Control never returns here. */
2210             }
2211
2212           /* No need to re-exec; SIGALRM remains set to the default handler */
2213
2214 #ifdef EXPERIMENTAL_QUEUE_RAMP
2215           if (*queuerun_msgid)
2216             {
2217             log_write(0, LOG_MAIN, "notify triggered queue run");
2218             f.queue_2stage = FALSE;
2219             queue_run(queuerun_msgid, queuerun_msgid, FALSE);
2220             }
2221           else
2222 #endif
2223             queue_run(NULL, NULL, FALSE);
2224           exim_underbar_exit(EXIT_SUCCESS);
2225           }
2226
2227         if (pid < 0)
2228           {
2229           log_write(0, LOG_MAIN|LOG_PANIC, "daemon: fork of queue-runner "
2230             "process failed: %s", strerror(errno));
2231           log_close_all();
2232           }
2233         else
2234           {
2235           for (int i = 0; i < local_queue_run_max; ++i)
2236             if (queue_pid_slots[i] <= 0)
2237               {
2238               queue_pid_slots[i] = pid;
2239               queue_run_count++;
2240               break;
2241               }
2242           DEBUG(D_any) debug_printf("%d queue-runner process%s running\n",
2243             queue_run_count, queue_run_count == 1 ? "" : "es");
2244           }
2245         }
2246
2247       /* Reset the alarm clock */
2248
2249       sigalrm_seen = FALSE;
2250 #ifdef EXPERIMENTAL_QUEUE_RAMP
2251       if (*queuerun_msgid)
2252         *queuerun_msgid = 0;
2253       else
2254 #endif
2255         ALARM(queue_interval);
2256       }
2257
2258     } /* sigalrm_seen */
2259
2260
2261   /* Sleep till a connection happens if listening, and handle the connection if
2262   that is why we woke up. The FreeBSD operating system requires the use of
2263   select() before accept() because the latter function is not interrupted by
2264   a signal, and we want to wake up for SIGCHLD and SIGALRM signals. Some other
2265   OS do notice signals in accept() but it does no harm to have the select()
2266   in for all of them - and it won't then be a lurking problem for ports to
2267   new OS. In fact, the later addition of listening on specific interfaces only
2268   requires this way of working anyway. */
2269
2270   if (f.daemon_listen)
2271     {
2272     int lcount, select_errno;
2273     int max_socket = 0;
2274     BOOL select_failed = FALSE;
2275     fd_set select_listen;
2276
2277     FD_ZERO(&select_listen);
2278     if (daemon_notifier_fd >= 0)
2279       FD_SET(daemon_notifier_fd, &select_listen);
2280     for (int sk = 0; sk < listen_socket_count; sk++)
2281       {
2282       FD_SET(listen_sockets[sk], &select_listen);
2283       if (listen_sockets[sk] > max_socket) max_socket = listen_sockets[sk];
2284       }
2285
2286     DEBUG(D_any) debug_printf("Listening...\n");
2287
2288     /* In rare cases we may have had a SIGCHLD signal in the time between
2289     setting the handler (below) and getting back here. If so, pretend that the
2290     select() was interrupted so that we reap the child. This might still leave
2291     a small window when a SIGCHLD could get lost. However, since we use SIGCHLD
2292     only to do the reaping more quickly, it shouldn't result in anything other
2293     than a delay until something else causes a wake-up. */
2294
2295     if (sigchld_seen)
2296       {
2297       lcount = -1;
2298       errno = EINTR;
2299       }
2300     else
2301       lcount = select(max_socket + 1, (SELECT_ARG2_TYPE *)&select_listen,
2302         NULL, NULL, NULL);
2303
2304     if (lcount < 0)
2305       {
2306       select_failed = TRUE;
2307       lcount = 1;
2308       }
2309
2310     /* Clean up any subprocesses that may have terminated. We need to do this
2311     here so that smtp_accept_max_per_host works when a connection to that host
2312     has completed, and we are about to accept a new one. When this code was
2313     later in the sequence, a new connection could be rejected, even though an
2314     old one had just finished. Preserve the errno from any select() failure for
2315     the use of the common select/accept error processing below. */
2316
2317     select_errno = errno;
2318     handle_ending_processes();
2319     errno = select_errno;
2320
2321 #ifndef DISABLE_TLS
2322     /* Create or rotate any required keys */
2323     tls_daemon_init();
2324 #endif
2325
2326     /* Loop for all the sockets that are currently ready to go. If select
2327     actually failed, we have set the count to 1 and select_failed=TRUE, so as
2328     to use the common error code for select/accept below. */
2329
2330     while (lcount-- > 0)
2331       {
2332       int accept_socket = -1;
2333
2334       if (!select_failed)
2335         {
2336         if (  daemon_notifier_fd >= 0
2337            && FD_ISSET(daemon_notifier_fd, &select_listen))
2338           {
2339           FD_CLR(daemon_notifier_fd, &select_listen);
2340           sigalrm_seen = daemon_notification();
2341           break;        /* to top of daemon loop */
2342           }
2343         for (int sk = 0; sk < listen_socket_count; sk++)
2344           if (FD_ISSET(listen_sockets[sk], &select_listen))
2345             {
2346             len = sizeof(accepted);
2347             accept_socket = accept(listen_sockets[sk],
2348               (struct sockaddr *)&accepted, &len);
2349             FD_CLR(listen_sockets[sk], &select_listen);
2350             break;
2351             }
2352         }
2353
2354       /* If select or accept has failed and this was not caused by an
2355       interruption, log the incident and try again. With asymmetric TCP/IP
2356       routing errors such as "No route to network" have been seen here. Also
2357       "connection reset by peer" has been seen. These cannot be classed as
2358       disastrous errors, but they could fill up a lot of log. The code in smail
2359       crashes the daemon after 10 successive failures of accept, on the grounds
2360       that some OS fail continuously. Exim originally followed suit, but this
2361       appears to have caused problems. Now it just keeps going, but instead of
2362       logging each error, it batches them up when they are continuous. */
2363
2364       if (accept_socket < 0 && errno != EINTR)
2365         {
2366         if (accept_retry_count == 0)
2367           {
2368           accept_retry_errno = errno;
2369           accept_retry_select_failed = select_failed;
2370           }
2371         else
2372           {
2373           if (errno != accept_retry_errno ||
2374               select_failed != accept_retry_select_failed ||
2375               accept_retry_count >= 50)
2376             {
2377             log_write(0, LOG_MAIN | ((accept_retry_count >= 50)? LOG_PANIC : 0),
2378               "%d %s() failure%s: %s",
2379               accept_retry_count,
2380               accept_retry_select_failed? "select" : "accept",
2381               (accept_retry_count == 1)? "" : "s",
2382               strerror(accept_retry_errno));
2383             log_close_all();
2384             accept_retry_count = 0;
2385             accept_retry_errno = errno;
2386             accept_retry_select_failed = select_failed;
2387             }
2388           }
2389         accept_retry_count++;
2390         }
2391
2392       else
2393         {
2394         if (accept_retry_count > 0)
2395           {
2396           log_write(0, LOG_MAIN, "%d %s() failure%s: %s",
2397             accept_retry_count,
2398             accept_retry_select_failed? "select" : "accept",
2399             (accept_retry_count == 1)? "" : "s",
2400             strerror(accept_retry_errno));
2401           log_close_all();
2402           accept_retry_count = 0;
2403           }
2404         }
2405
2406       /* If select/accept succeeded, deal with the connection. */
2407
2408       if (accept_socket >= 0)
2409         {
2410         if (inetd_wait_timeout)
2411           last_connection_time = time(NULL);
2412         handle_smtp_call(listen_sockets, listen_socket_count, accept_socket,
2413           (struct sockaddr *)&accepted);
2414         }
2415       }
2416     }
2417
2418   /* If not listening, then just sleep for the queue interval. If we woke
2419   up early the last time for some other signal, it won't matter because
2420   the alarm signal will wake at the right time. This code originally used
2421   sleep() but it turns out that on the FreeBSD system, sleep() is not inter-
2422   rupted by signals, so it wasn't waking up for SIGALRM or SIGCHLD. Luckily
2423   select() can be used as an interruptible sleep() on all versions of Unix. */
2424
2425   else
2426     {
2427     struct timeval tv;
2428     tv.tv_sec = queue_interval;
2429     tv.tv_usec = 0;
2430     select(0, NULL, NULL, NULL, &tv);
2431     handle_ending_processes();
2432     }
2433
2434   /* Re-enable the SIGCHLD handler if it has been run. It can't do it
2435   for itself, because it isn't doing the waiting itself. */
2436
2437   if (sigchld_seen)
2438     {
2439     sigchld_seen = FALSE;
2440     os_non_restarting_signal(SIGCHLD, main_sigchld_handler);
2441     }
2442
2443   /* Handle being woken by SIGHUP. We know at this point that the result
2444   of accept() has been dealt with, so we can re-exec exim safely, first
2445   closing the listening sockets so that they can be reused. Cancel any pending
2446   alarm in case it is just about to go off, and set SIGHUP to be ignored so
2447   that another HUP in quick succession doesn't clobber the new daemon before it
2448   gets going. All log files get closed by the close-on-exec flag; however, if
2449   the exec fails, we need to close the logs. */
2450
2451   if (sighup_seen)
2452     {
2453     log_write(0, LOG_MAIN, "pid %d: SIGHUP received: re-exec daemon",
2454       getpid());
2455     close_daemon_sockets(daemon_notifier_fd,
2456       listen_sockets, listen_socket_count);
2457     ALARM_CLR(0);
2458     signal(SIGHUP, SIG_IGN);
2459     sighup_argv[0] = exim_path;
2460     exim_nullstd();
2461     execv(CS exim_path, (char *const *)sighup_argv);
2462     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "pid %d: exec of %s failed: %s",
2463       getpid(), exim_path, strerror(errno));
2464     log_close_all();
2465     }
2466
2467   }   /* End of main loop */
2468
2469 /* Control never reaches here */
2470 }
2471
2472 /* vi: aw ai sw=2
2473 */
2474 /* End of exim_daemon.c */