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