1/* dnsmasq is Copyright (c) 2000-2009 Simon Kelley
2
3   This program is free software; you can redistribute it and/or modify
4   it under the terms of the GNU General Public License as published by
5   the Free Software Foundation; version 2 dated June, 1991, or
6   (at your option) version 3 dated 29 June, 2007.
7
8   This program is distributed in the hope that it will be useful,
9   but WITHOUT ANY WARRANTY; without even the implied warranty of
10   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11   GNU General Public License for more details.
12
13   You should have received a copy of the GNU General Public License
14   along with this program.  If not, see <http://www.gnu.org/licenses/>.
15*/
16
17#include "dnsmasq.h"
18
19struct daemon *daemon;
20
21static char *compile_opts =
22#ifndef HAVE_IPV6
23"no-"
24#endif
25"IPv6 "
26#ifndef HAVE_GETOPT_LONG
27"no-"
28#endif
29"GNU-getopt "
30#ifdef HAVE_BROKEN_RTC
31"no-RTC "
32#endif
33#ifdef NO_FORK
34"no-MMU "
35#endif
36#ifndef LOCALEDIR
37"no-"
38#endif
39"I18N "
40#ifndef HAVE_DHCP
41"no-"
42#endif
43"DHCP "
44#if defined(HAVE_DHCP) && !defined(HAVE_SCRIPT)
45"no-scripts"
46#endif
47"";
48
49
50
51static volatile pid_t pid = 0;
52static volatile int pipewrite;
53
54static int set_dns_listeners(time_t now, fd_set *set, int *maxfdp);
55static void check_dns_listeners(fd_set *set, time_t now);
56static void sig_handler(int sig);
57static void async_event(int pipe, time_t now);
58static void fatal_event(struct event_desc *ev);
59static void poll_resolv(void);
60#if defined(__ANDROID__) && !defined(__BRILLO__)
61static int set_android_listeners(fd_set *set, int *maxfdp);
62static int check_android_listeners(fd_set *set);
63#endif
64
65int main (int argc, char **argv)
66{
67  int bind_fallback = 0;
68  time_t now;
69  struct sigaction sigact;
70  struct iname *if_tmp;
71  int piperead, pipefd[2], err_pipe[2];
72  struct passwd *ent_pw = NULL;
73#if defined(HAVE_DHCP) && defined(HAVE_SCRIPT)
74  uid_t script_uid = 0;
75  gid_t script_gid = 0;
76#endif
77  struct group *gp = NULL;
78  long i, max_fd = sysconf(_SC_OPEN_MAX);
79  char *baduser = NULL;
80  int log_err;
81#if defined(HAVE_LINUX_NETWORK)
82  cap_user_header_t hdr = NULL;
83  cap_user_data_t data = NULL;
84#endif
85
86#ifdef LOCALEDIR
87  setlocale(LC_ALL, "");
88  bindtextdomain("dnsmasq", LOCALEDIR);
89  textdomain("dnsmasq");
90#endif
91
92  sigact.sa_handler = sig_handler;
93  sigact.sa_flags = 0;
94  sigemptyset(&sigact.sa_mask);
95  sigaction(SIGUSR1, &sigact, NULL);
96  sigaction(SIGUSR2, &sigact, NULL);
97  sigaction(SIGHUP, &sigact, NULL);
98  sigaction(SIGTERM, &sigact, NULL);
99  sigaction(SIGALRM, &sigact, NULL);
100  sigaction(SIGCHLD, &sigact, NULL);
101
102  /* ignore SIGPIPE */
103  sigact.sa_handler = SIG_IGN;
104  sigaction(SIGPIPE, &sigact, NULL);
105
106  umask(022); /* known umask, create leases and pid files as 0644 */
107
108  read_opts(argc, argv, compile_opts);
109
110  if (daemon->edns_pktsz < PACKETSZ)
111    daemon->edns_pktsz = PACKETSZ;
112  daemon->packet_buff_sz = daemon->edns_pktsz > DNSMASQ_PACKETSZ ?
113    daemon->edns_pktsz : DNSMASQ_PACKETSZ;
114  daemon->packet = safe_malloc(daemon->packet_buff_sz);
115
116#ifdef HAVE_DHCP
117  if (!daemon->lease_file)
118    {
119      if (daemon->dhcp)
120	daemon->lease_file = LEASEFILE;
121    }
122#endif
123
124  /* Close any file descriptors we inherited apart from std{in|out|err} */
125  for (i = 0; i < max_fd; i++)
126    if (i != STDOUT_FILENO && i != STDERR_FILENO && i != STDIN_FILENO)
127      close(i);
128
129#ifdef HAVE_LINUX_NETWORK
130  netlink_init();
131#elif !(defined(IP_RECVDSTADDR) && \
132	defined(IP_RECVIF) && \
133	defined(IP_SENDSRCADDR))
134  if (!(daemon->options & OPT_NOWILD))
135    {
136      bind_fallback = 1;
137      daemon->options |= OPT_NOWILD;
138    }
139#endif
140
141#ifdef HAVE_SOLARIS_NETWORK
142  if (daemon->max_logs != 0)
143    die(_("asychronous logging is not available under Solaris"), NULL, EC_BADCONF);
144#endif
145
146  rand_init();
147
148  now = dnsmasq_time();
149
150#ifdef HAVE_DHCP
151  if (daemon->dhcp)
152    {
153      /* Note that order matters here, we must call lease_init before
154	 creating any file descriptors which shouldn't be leaked
155	 to the lease-script init process. */
156      lease_init(now);
157      dhcp_init();
158    }
159#endif
160
161  if (!enumerate_interfaces())
162    die(_("failed to find list of interfaces: %s"), NULL, EC_MISC);
163
164  if (daemon->options & OPT_NOWILD)
165    {
166      daemon->listeners = create_bound_listeners();
167
168      for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
169	if (if_tmp->name && !if_tmp->used)
170	  die(_("unknown interface %s"), if_tmp->name, EC_BADNET);
171
172      for (if_tmp = daemon->if_addrs; if_tmp; if_tmp = if_tmp->next)
173	if (!if_tmp->used)
174	  {
175	    prettyprint_addr(&if_tmp->addr, daemon->namebuff);
176	    die(_("no interface with address %s"), daemon->namebuff, EC_BADNET);
177	  }
178    }
179  else if ((daemon->port != 0 || (daemon->options & OPT_TFTP)) &&
180	   !(daemon->listeners = create_wildcard_listeners()))
181    die(_("failed to create listening socket: %s"), NULL, EC_BADNET);
182
183  if (daemon->port != 0)
184    cache_init();
185
186  if (daemon->port != 0)
187    pre_allocate_sfds();
188
189#if defined(HAVE_DHCP) && defined(HAVE_SCRIPT)
190  /* Note getpwnam returns static storage */
191  if (daemon->dhcp && daemon->lease_change_command && daemon->scriptuser)
192    {
193      if ((ent_pw = getpwnam(daemon->scriptuser)))
194	{
195	  script_uid = ent_pw->pw_uid;
196	  script_gid = ent_pw->pw_gid;
197	 }
198      else
199	baduser = daemon->scriptuser;
200    }
201#endif
202
203  if (daemon->username && !(ent_pw = getpwnam(daemon->username)))
204    baduser = daemon->username;
205  else if (daemon->groupname && !(gp = getgrnam(daemon->groupname)))
206    baduser = daemon->groupname;
207
208  if (baduser)
209    die(_("unknown user or group: %s"), baduser, EC_BADCONF);
210
211  /* implement group defaults, "dip" if available, or group associated with uid */
212  if (!daemon->group_set && !gp)
213    {
214      if (!(gp = getgrnam(CHGRP)) && ent_pw)
215	gp = getgrgid(ent_pw->pw_gid);
216
217      /* for error message */
218      if (gp)
219	daemon->groupname = gp->gr_name;
220    }
221
222#if defined(HAVE_LINUX_NETWORK)
223  /* determine capability API version here, while we can still
224     call safe_malloc */
225  if (ent_pw && ent_pw->pw_uid != 0)
226    {
227      int capsize = 1; /* for header version 1 */
228      hdr = safe_malloc(sizeof(*hdr));
229
230      /* find version supported by kernel */
231      memset(hdr, 0, sizeof(*hdr));
232      capget(hdr, NULL);
233
234      if (hdr->version != LINUX_CAPABILITY_VERSION_1)
235	{
236	  /* if unknown version, use largest supported version (3) */
237	  if (hdr->version != LINUX_CAPABILITY_VERSION_2)
238	    hdr->version = LINUX_CAPABILITY_VERSION_3;
239	  capsize = 2;
240	}
241
242      data = safe_malloc(sizeof(*data) * capsize);
243      memset(data, 0, sizeof(*data) * capsize);
244    }
245#endif
246
247  /* Use a pipe to carry signals and other events back to the event loop
248     in a race-free manner and another to carry errors to daemon-invoking process */
249  safe_pipe(pipefd, 1);
250
251  piperead = pipefd[0];
252  pipewrite = pipefd[1];
253  /* prime the pipe to load stuff first time. */
254  send_event(pipewrite, EVENT_RELOAD, 0);
255
256  err_pipe[1] = -1;
257
258  if (!(daemon->options & OPT_DEBUG))
259    {
260#if !defined(__ANDROID__) || defined(__BRILLO__)
261      int nullfd;
262#endif
263
264      /* The following code "daemonizes" the process.
265	 See Stevens section 12.4 */
266
267      if (chdir("/") != 0)
268	die(_("cannot chdir to filesystem root: %s"), NULL, EC_MISC);
269
270#ifndef NO_FORK
271      if (!(daemon->options & OPT_NO_FORK))
272	{
273	  pid_t pid;
274
275	  /* pipe to carry errors back to original process.
276	     When startup is complete we close this and the process terminates. */
277	  safe_pipe(err_pipe, 0);
278
279	  if ((pid = fork()) == -1)
280	    /* fd == -1 since we've not forked, never returns. */
281	    send_event(-1, EVENT_FORK_ERR, errno);
282
283	  if (pid != 0)
284	    {
285	      struct event_desc ev;
286
287	      /* close our copy of write-end */
288	      close(err_pipe[1]);
289
290	      /* check for errors after the fork */
291	      if (read_write(err_pipe[0], (unsigned char *)&ev, sizeof(ev), 1))
292		fatal_event(&ev);
293
294	      _exit(EC_GOOD);
295	    }
296
297	  close(err_pipe[0]);
298
299	  /* NO calls to die() from here on. */
300
301	  setsid();
302
303	  if ((pid = fork()) == -1)
304	    send_event(err_pipe[1], EVENT_FORK_ERR, errno);
305
306	  if (pid != 0)
307	    _exit(0);
308	}
309#endif
310
311      /* write pidfile _after_ forking ! */
312      if (daemon->runfile)
313	{
314	  FILE *pidfile;
315
316	  /* only complain if started as root */
317	  if ((pidfile = fopen(daemon->runfile, "w")))
318	    {
319	      fprintf(pidfile, "%d\n", (int) getpid());
320	      fclose(pidfile);
321	    }
322	  else if (getuid() == 0)
323	    {
324	      send_event(err_pipe[1], EVENT_PIDFILE, errno);
325	      _exit(0);
326	    }
327	}
328
329#if !defined(__ANDROID__) || defined(__BRILLO__)
330      /* open  stdout etc to /dev/null */
331      nullfd = open("/dev/null", O_RDWR);
332      dup2(nullfd, STDOUT_FILENO);
333      dup2(nullfd, STDERR_FILENO);
334      dup2(nullfd, STDIN_FILENO);
335      close(nullfd);
336#endif
337    }
338
339   log_err = log_start(ent_pw, err_pipe[1]);
340
341   /* if we are to run scripts, we need to fork a helper before dropping root. */
342  daemon->helperfd = -1;
343#if defined(HAVE_DHCP) && defined(HAVE_SCRIPT)
344  if (daemon->dhcp && daemon->lease_change_command)
345    daemon->helperfd = create_helper(pipewrite, err_pipe[1], script_uid, script_gid, max_fd);
346#endif
347
348  if (!(daemon->options & OPT_DEBUG) && getuid() == 0)
349    {
350      int bad_capabilities = 0;
351      gid_t dummy;
352
353      /* remove all supplimentary groups */
354      if (gp &&
355	  (setgroups(0, &dummy) == -1 ||
356	   setgid(gp->gr_gid) == -1))
357	{
358	  send_event(err_pipe[1], EVENT_GROUP_ERR, errno);
359	  _exit(0);
360	}
361
362      if (ent_pw && ent_pw->pw_uid != 0)
363	{
364#if defined(HAVE_LINUX_NETWORK)
365	  /* On linux, we keep CAP_NETADMIN (for ARP-injection) and
366	     CAP_NET_RAW (for icmp) if we're doing dhcp */
367	  data->effective = data->permitted = data->inheritable =
368#ifdef __ANDROID__
369	    (1 << CAP_NET_BIND_SERVICE) |
370#endif
371	    (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID);
372
373	  /* Tell kernel to not clear capabilities when dropping root */
374	  if (capset(hdr, data) == -1 || prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1)
375	    bad_capabilities = errno;
376
377#elif defined(HAVE_SOLARIS_NETWORK)
378	  /* http://developers.sun.com/solaris/articles/program_privileges.html */
379	  priv_set_t *priv_set;
380
381	  if (!(priv_set = priv_str_to_set("basic", ",", NULL)) ||
382	      priv_addset(priv_set, PRIV_NET_ICMPACCESS) == -1 ||
383	      priv_addset(priv_set, PRIV_SYS_NET_CONFIG) == -1)
384	    bad_capabilities = errno;
385
386	  if (priv_set && bad_capabilities == 0)
387	    {
388	      priv_inverse(priv_set);
389
390	      if (setppriv(PRIV_OFF, PRIV_LIMIT, priv_set) == -1)
391		bad_capabilities = errno;
392	    }
393
394	  if (priv_set)
395	    priv_freeset(priv_set);
396
397#endif
398
399	  if (bad_capabilities != 0)
400	    {
401	      send_event(err_pipe[1], EVENT_CAP_ERR, bad_capabilities);
402	      _exit(0);
403	    }
404
405	  /* finally drop root */
406	  if (setuid(ent_pw->pw_uid) == -1)
407	    {
408	      send_event(err_pipe[1], EVENT_USER_ERR, errno);
409	      _exit(0);
410	    }
411
412#ifdef HAVE_LINUX_NETWORK
413	  data->effective = data->permitted =
414#ifdef __ANDROID__
415	    (1 << CAP_NET_BIND_SERVICE) |
416#endif
417	    (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW);
418	  data->inheritable = 0;
419
420	  /* lose the setuid and setgid capbilities */
421	  if (capset(hdr, data) == -1)
422	    {
423	      send_event(err_pipe[1], EVENT_CAP_ERR, errno);
424	      _exit(0);
425	    }
426#endif
427
428	}
429    }
430
431#ifdef HAVE_LINUX_NETWORK
432  if (daemon->options & OPT_DEBUG)
433    prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
434#endif
435
436  if (daemon->port == 0)
437    my_syslog(LOG_INFO, _("started, version %s DNS disabled"), VERSION);
438  else if (daemon->cachesize != 0)
439    my_syslog(LOG_INFO, _("started, version %s cachesize %d"), VERSION, daemon->cachesize);
440  else
441    my_syslog(LOG_INFO, _("started, version %s cache disabled"), VERSION);
442
443  my_syslog(LOG_INFO, _("compile time options: %s"), compile_opts);
444
445  if (log_err != 0)
446    my_syslog(LOG_WARNING, _("warning: failed to change owner of %s: %s"),
447	      daemon->log_file, strerror(log_err));
448
449  if (bind_fallback)
450    my_syslog(LOG_WARNING, _("setting --bind-interfaces option because of OS limitations"));
451
452  if (!(daemon->options & OPT_NOWILD))
453    for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
454      if (if_tmp->name && !if_tmp->used)
455	my_syslog(LOG_WARNING, _("warning: interface %s does not currently exist"), if_tmp->name);
456
457  if (daemon->port != 0 && (daemon->options & OPT_NO_RESOLV))
458    {
459      if (daemon->resolv_files && !daemon->resolv_files->is_default)
460	my_syslog(LOG_WARNING, _("warning: ignoring resolv-file flag because no-resolv is set"));
461      daemon->resolv_files = NULL;
462      if (!daemon->servers)
463	my_syslog(LOG_WARNING, _("warning: no upstream servers configured"));
464    }
465
466  if (daemon->max_logs != 0)
467    my_syslog(LOG_INFO, _("asynchronous logging enabled, queue limit is %d messages"), daemon->max_logs);
468
469#ifdef HAVE_DHCP
470  if (daemon->dhcp)
471    {
472      struct dhcp_context *dhcp_tmp;
473
474      for (dhcp_tmp = daemon->dhcp; dhcp_tmp; dhcp_tmp = dhcp_tmp->next)
475	{
476	  prettyprint_time(daemon->dhcp_buff2, dhcp_tmp->lease_time);
477	  strcpy(daemon->dhcp_buff, inet_ntoa(dhcp_tmp->start));
478	  my_syslog(MS_DHCP | LOG_INFO,
479		    (dhcp_tmp->flags & CONTEXT_STATIC) ?
480		    _("DHCP, static leases only on %.0s%s, lease time %s") :
481		    (dhcp_tmp->flags & CONTEXT_PROXY) ?
482		    _("DHCP, proxy on subnet %.0s%s%.0s") :
483		    _("DHCP, IP range %s -- %s, lease time %s"),
484		    daemon->dhcp_buff, inet_ntoa(dhcp_tmp->end), daemon->dhcp_buff2);
485	}
486    }
487#endif
488
489  /* finished start-up - release original process */
490  if (err_pipe[1] != -1)
491    close(err_pipe[1]);
492
493  if (daemon->port != 0)
494    check_servers();
495
496  pid = getpid();
497
498  while (1)
499    {
500      int maxfd = -1;
501      struct timeval t, *tp = NULL;
502      fd_set rset, wset, eset;
503
504      FD_ZERO(&rset);
505      FD_ZERO(&wset);
506      FD_ZERO(&eset);
507
508      /* if we are out of resources, find how long we have to wait
509	 for some to come free, we'll loop around then and restart
510	 listening for queries */
511      if ((t.tv_sec = set_dns_listeners(now, &rset, &maxfd)) != 0)
512	{
513	  t.tv_usec = 0;
514	  tp = &t;
515	}
516#if defined(__ANDROID__) && !defined(__BRILLO__)
517      set_android_listeners(&rset, &maxfd);
518#endif
519
520#ifdef HAVE_DHCP
521      if (daemon->dhcp)
522	{
523	  FD_SET(daemon->dhcpfd, &rset);
524	  bump_maxfd(daemon->dhcpfd, &maxfd);
525	}
526#endif
527
528#ifdef HAVE_LINUX_NETWORK
529      FD_SET(daemon->netlinkfd, &rset);
530      bump_maxfd(daemon->netlinkfd, &maxfd);
531#endif
532
533      FD_SET(piperead, &rset);
534      bump_maxfd(piperead, &maxfd);
535
536#ifdef HAVE_DHCP
537#  ifdef HAVE_SCRIPT
538      while (helper_buf_empty() && do_script_run(now));
539
540      if (!helper_buf_empty())
541	{
542	  FD_SET(daemon->helperfd, &wset);
543	  bump_maxfd(daemon->helperfd, &maxfd);
544	}
545#  else
546      /* need this for other side-effects */
547      while (do_script_run(now));
548#  endif
549#endif
550
551      /* must do this just before select(), when we know no
552	 more calls to my_syslog() can occur */
553      set_log_writer(&wset, &maxfd);
554
555      if (select(maxfd+1, &rset, &wset, &eset, tp) < 0)
556	{
557	  /* otherwise undefined after error */
558	  FD_ZERO(&rset); FD_ZERO(&wset); FD_ZERO(&eset);
559	}
560
561      now = dnsmasq_time();
562
563      check_log_writer(&wset);
564
565      /* Check for changes to resolv files once per second max. */
566      /* Don't go silent for long periods if the clock goes backwards. */
567      if (daemon->last_resolv == 0 ||
568	  difftime(now, daemon->last_resolv) > 1.0 ||
569	  difftime(now, daemon->last_resolv) < -1.0)
570	{
571	  daemon->last_resolv = now;
572
573	  if (daemon->port != 0 && !(daemon->options & OPT_NO_POLL))
574	    poll_resolv();
575	}
576
577      if (FD_ISSET(piperead, &rset))
578	async_event(piperead, now);
579
580#ifdef HAVE_LINUX_NETWORK
581      if (FD_ISSET(daemon->netlinkfd, &rset))
582	netlink_multicast();
583#endif
584
585#if defined(__ANDROID__) && !defined(__BRILLO__)
586      check_android_listeners(&rset);
587#endif
588
589      check_dns_listeners(&rset, now);
590
591#ifdef HAVE_DHCP
592      if (daemon->dhcp && FD_ISSET(daemon->dhcpfd, &rset))
593	dhcp_packet(now);
594
595#  ifdef HAVE_SCRIPT
596      if (daemon->helperfd != -1 && FD_ISSET(daemon->helperfd, &wset))
597	helper_write();
598#  endif
599#endif
600
601    }
602}
603
604static void sig_handler(int sig)
605{
606  if (pid == 0)
607    {
608      /* ignore anything other than TERM during startup
609	 and in helper proc. (helper ignore TERM too) */
610      if (sig == SIGTERM)
611	exit(EC_MISC);
612    }
613  else if (pid != getpid())
614    {
615      /* alarm is used to kill TCP children after a fixed time. */
616      if (sig == SIGALRM)
617	_exit(0);
618    }
619  else
620    {
621      /* master process */
622      int event, errsave = errno;
623
624      if (sig == SIGHUP)
625	event = EVENT_RELOAD;
626      else if (sig == SIGCHLD)
627	event = EVENT_CHILD;
628      else if (sig == SIGALRM)
629	event = EVENT_ALARM;
630      else if (sig == SIGTERM)
631	event = EVENT_TERM;
632      else if (sig == SIGUSR1)
633	event = EVENT_DUMP;
634      else if (sig == SIGUSR2)
635	event = EVENT_REOPEN;
636      else
637	return;
638
639      send_event(pipewrite, event, 0);
640      errno = errsave;
641    }
642}
643
644void send_event(int fd, int event, int data)
645{
646  struct event_desc ev;
647
648  ev.event = event;
649  ev.data = data;
650
651  /* error pipe, debug mode. */
652  if (fd == -1)
653    fatal_event(&ev);
654  else
655    /* pipe is non-blocking and struct event_desc is smaller than
656       PIPE_BUF, so this either fails or writes everything */
657    while (write(fd, &ev, sizeof(ev)) == -1 && errno == EINTR);
658}
659
660static void fatal_event(struct event_desc *ev)
661{
662  errno = ev->data;
663
664  switch (ev->event)
665    {
666    case EVENT_DIE:
667      exit(0);
668
669    case EVENT_FORK_ERR:
670      die(_("cannot fork into background: %s"), NULL, EC_MISC);
671
672    case EVENT_PIPE_ERR:
673      die(_("failed to create helper: %s"), NULL, EC_MISC);
674
675    case EVENT_CAP_ERR:
676      die(_("setting capabilities failed: %s"), NULL, EC_MISC);
677
678    case EVENT_USER_ERR:
679    case EVENT_HUSER_ERR:
680      die(_("failed to change user-id to %s: %s"),
681	  ev->event == EVENT_USER_ERR ? daemon->username : daemon->scriptuser,
682	  EC_MISC);
683
684    case EVENT_GROUP_ERR:
685      die(_("failed to change group-id to %s: %s"), daemon->groupname, EC_MISC);
686
687    case EVENT_PIDFILE:
688      die(_("failed to open pidfile %s: %s"), daemon->runfile, EC_FILE);
689
690    case EVENT_LOG_ERR:
691      die(_("cannot open %s: %s"), daemon->log_file ? daemon->log_file : "log", EC_FILE);
692    }
693}
694
695static void async_event(int pipe, time_t now)
696{
697  pid_t p;
698  struct event_desc ev;
699  int i;
700
701  if (read_write(pipe, (unsigned char *)&ev, sizeof(ev), 1))
702    switch (ev.event)
703      {
704      case EVENT_RELOAD:
705	clear_cache_and_reload(now);
706	if (daemon->port != 0 && daemon->resolv_files && (daemon->options & OPT_NO_POLL))
707	  {
708	    reload_servers(daemon->resolv_files->name);
709	    check_servers();
710	  }
711#ifdef HAVE_DHCP
712	rerun_scripts();
713#endif
714	break;
715
716      case EVENT_DUMP:
717	if (daemon->port != 0)
718	  dump_cache(now);
719	break;
720
721      case EVENT_ALARM:
722#ifdef HAVE_DHCP
723	if (daemon->dhcp)
724	  {
725	    lease_prune(NULL, now);
726	    lease_update_file(now);
727	  }
728#endif
729	break;
730
731      case EVENT_CHILD:
732	/* See Stevens 5.10 */
733	while ((p = waitpid(-1, NULL, WNOHANG)) != 0)
734	  if (p == -1)
735	    {
736	      if (errno != EINTR)
737		break;
738	    }
739	  else
740	    for (i = 0 ; i < MAX_PROCS; i++)
741	      if (daemon->tcp_pids[i] == p)
742		daemon->tcp_pids[i] = 0;
743	break;
744
745      case EVENT_KILLED:
746	my_syslog(LOG_WARNING, _("child process killed by signal %d"), ev.data);
747	break;
748
749      case EVENT_EXITED:
750	my_syslog(LOG_WARNING, _("child process exited with status %d"), ev.data);
751	break;
752
753      case EVENT_EXEC_ERR:
754	my_syslog(LOG_ERR, _("failed to execute %s: %s"),
755		  daemon->lease_change_command, strerror(ev.data));
756	break;
757
758	/* necessary for fatal errors in helper */
759      case EVENT_HUSER_ERR:
760      case EVENT_DIE:
761	fatal_event(&ev);
762	break;
763
764      case EVENT_REOPEN:
765	/* Note: this may leave TCP-handling processes with the old file still open.
766	   Since any such process will die in CHILD_LIFETIME or probably much sooner,
767	   we leave them logging to the old file. */
768	if (daemon->log_file != NULL)
769	  log_reopen(daemon->log_file);
770	break;
771
772      case EVENT_TERM:
773	/* Knock all our children on the head. */
774	for (i = 0; i < MAX_PROCS; i++)
775	  if (daemon->tcp_pids[i] != 0)
776	    kill(daemon->tcp_pids[i], SIGALRM);
777
778#if defined(HAVE_DHCP) && defined(HAVE_SCRIPT)
779	/* handle pending lease transitions */
780	if (daemon->helperfd != -1)
781	  {
782	    /* block in writes until all done */
783	    if ((i = fcntl(daemon->helperfd, F_GETFL)) != -1)
784	      fcntl(daemon->helperfd, F_SETFL, i & ~O_NONBLOCK);
785	    do {
786	      helper_write();
787	    } while (!helper_buf_empty() || do_script_run(now));
788	    close(daemon->helperfd);
789	  }
790#endif
791
792	if (daemon->lease_stream)
793	  fclose(daemon->lease_stream);
794
795	if (daemon->runfile)
796	  unlink(daemon->runfile);
797
798	my_syslog(LOG_INFO, _("exiting on receipt of SIGTERM"));
799	flush_log();
800	exit(EC_GOOD);
801      }
802}
803
804static void poll_resolv()
805{
806  struct resolvc *res, *latest;
807  struct stat statbuf;
808  time_t last_change = 0;
809  /* There may be more than one possible file.
810     Go through and find the one which changed _last_.
811     Warn of any which can't be read. */
812  for (latest = NULL, res = daemon->resolv_files; res; res = res->next)
813    if (stat(res->name, &statbuf) == -1)
814      {
815	if (!res->logged)
816	  my_syslog(LOG_WARNING, _("failed to access %s: %s"), res->name, strerror(errno));
817	res->logged = 1;
818      }
819    else
820      {
821	res->logged = 0;
822	if (statbuf.st_mtime != res->mtime)
823	  {
824	    res->mtime = statbuf.st_mtime;
825	    if (difftime(statbuf.st_mtime, last_change) > 0.0)
826	      {
827		last_change = statbuf.st_mtime;
828		latest = res;
829	      }
830	  }
831      }
832
833  if (latest)
834    {
835      static int warned = 0;
836      if (reload_servers(latest->name))
837	{
838	  my_syslog(LOG_INFO, _("reading %s"), latest->name);
839	  warned = 0;
840	  check_servers();
841	  if (daemon->options & OPT_RELOAD)
842	    cache_reload();
843	}
844      else
845	{
846	  latest->mtime = 0;
847	  if (!warned)
848	    {
849	      my_syslog(LOG_WARNING, _("no servers found in %s, will retry"), latest->name);
850	      warned = 1;
851	    }
852	}
853    }
854}
855
856void clear_cache_and_reload(time_t now)
857{
858  if (daemon->port != 0)
859    cache_reload();
860
861#ifdef HAVE_DHCP
862  if (daemon->dhcp)
863    {
864      if (daemon->options & OPT_ETHERS)
865	dhcp_read_ethers();
866      reread_dhcp();
867      dhcp_update_configs(daemon->dhcp_conf);
868      check_dhcp_hosts(0);
869      lease_update_from_configs();
870      lease_update_file(now);
871      lease_update_dns();
872    }
873#endif
874}
875
876#if defined(__ANDROID__) && !defined(__BRILLO__)
877
878static int set_android_listeners(fd_set *set, int *maxfdp) {
879    FD_SET(STDIN_FILENO, set);
880    bump_maxfd(STDIN_FILENO, maxfdp);
881    return 0;
882}
883
884static int check_android_listeners(fd_set *set) {
885    int retcode = 0;
886    if (FD_ISSET(STDIN_FILENO, set)) {
887        char buffer[1024];
888        int rc;
889        int consumed = 0;
890
891        if ((rc = read(STDIN_FILENO, buffer, sizeof(buffer) -1)) < 0) {
892            my_syslog(LOG_ERR, _("Error reading from stdin (%s)"), strerror(errno));
893            return -1;
894        }
895        buffer[rc] = '\0';
896        while(consumed < rc) {
897            char *cmd;
898            char *current_cmd = &buffer[consumed];
899            char *params = current_cmd;
900            int len = strlen(current_cmd);
901
902            cmd = strsep(&params, "|");
903            if (!strcmp(cmd, "update_dns")) {
904                if (params != NULL) {
905                    set_servers(params);
906                    check_servers();
907                } else {
908                    my_syslog(LOG_ERR, _("Misformatted msg '%s'"), current_cmd);
909                    retcode = -1;
910                }
911            } else if (!strcmp(cmd, "update_ifaces")) {
912                if (params != NULL) {
913                    set_interfaces(params);
914                } else {
915                    my_syslog(LOG_ERR, _("Misformatted msg '%s'"), current_cmd);
916                    retcode = -1;
917                }
918            } else {
919                 my_syslog(LOG_ERR, _("Unknown cmd '%s'"), cmd);
920                 retcode = -1;
921            }
922            consumed += len + 1;
923        }
924    }
925    return retcode;
926}
927#endif
928
929static int set_dns_listeners(time_t now, fd_set *set, int *maxfdp)
930{
931  struct serverfd *serverfdp;
932  struct listener *listener;
933  int wait = 0, i;
934
935  /* will we be able to get memory? */
936  if (daemon->port != 0)
937    get_new_frec(now, &wait);
938
939  for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
940    {
941      FD_SET(serverfdp->fd, set);
942      bump_maxfd(serverfdp->fd, maxfdp);
943    }
944
945  if (daemon->port != 0 && !daemon->osport)
946    for (i = 0; i < RANDOM_SOCKS; i++)
947      if (daemon->randomsocks[i].refcount != 0)
948	{
949	  FD_SET(daemon->randomsocks[i].fd, set);
950	  bump_maxfd(daemon->randomsocks[i].fd, maxfdp);
951	}
952
953  for (listener = daemon->listeners; listener; listener = listener->next)
954    {
955      /* only listen for queries if we have resources */
956      if (listener->fd != -1 && wait == 0)
957	{
958	  FD_SET(listener->fd, set);
959	  bump_maxfd(listener->fd, maxfdp);
960	}
961
962      /* death of a child goes through the select loop, so
963	 we don't need to explicitly arrange to wake up here */
964      if  (listener->tcpfd != -1)
965	for (i = 0; i < MAX_PROCS; i++)
966	  if (daemon->tcp_pids[i] == 0)
967	    {
968	      FD_SET(listener->tcpfd, set);
969	      bump_maxfd(listener->tcpfd, maxfdp);
970	      break;
971	    }
972    }
973
974  return wait;
975}
976
977static void check_dns_listeners(fd_set *set, time_t now)
978{
979  struct serverfd *serverfdp;
980  struct listener *listener;
981  int i;
982
983  for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
984    if (FD_ISSET(serverfdp->fd, set))
985      reply_query(serverfdp->fd, serverfdp->source_addr.sa.sa_family, now);
986
987  if (daemon->port != 0 && !daemon->osport)
988    for (i = 0; i < RANDOM_SOCKS; i++)
989      if (daemon->randomsocks[i].refcount != 0 &&
990	  FD_ISSET(daemon->randomsocks[i].fd, set))
991	reply_query(daemon->randomsocks[i].fd, daemon->randomsocks[i].family, now);
992
993  for (listener = daemon->listeners; listener; listener = listener->next)
994    {
995      if (listener->fd != -1 && FD_ISSET(listener->fd, set))
996	receive_query(listener, now);
997
998      if (listener->tcpfd != -1 && FD_ISSET(listener->tcpfd, set))
999	{
1000	  int confd;
1001	  struct irec *iface = NULL;
1002	  pid_t p;
1003
1004	  while((confd = accept(listener->tcpfd, NULL, NULL)) == -1 && errno == EINTR);
1005
1006	  if (confd == -1)
1007	    continue;
1008
1009	  if (daemon->options & OPT_NOWILD)
1010	    iface = listener->iface;
1011	  else
1012	    {
1013	      union mysockaddr tcp_addr;
1014	      socklen_t tcp_len = sizeof(union mysockaddr);
1015	      /* Check for allowed interfaces when binding the wildcard address:
1016		 we do this by looking for an interface with the same address as
1017		 the local address of the TCP connection, then looking to see if that's
1018		 an allowed interface. As a side effect, we get the netmask of the
1019		 interface too, for localisation. */
1020
1021	      /* interface may be new since startup */
1022	      if (enumerate_interfaces() &&
1023		  getsockname(confd, (struct sockaddr *)&tcp_addr, &tcp_len) != -1)
1024		for (iface = daemon->interfaces; iface; iface = iface->next)
1025		  if (sockaddr_isequal(&iface->addr, &tcp_addr))
1026		    break;
1027	    }
1028
1029	  if (!iface)
1030	    {
1031	      shutdown(confd, SHUT_RDWR);
1032	      close(confd);
1033	    }
1034#ifndef NO_FORK
1035	  else if (!(daemon->options & OPT_DEBUG) && (p = fork()) != 0)
1036	    {
1037	      if (p != -1)
1038		{
1039		  int i;
1040		  for (i = 0; i < MAX_PROCS; i++)
1041		    if (daemon->tcp_pids[i] == 0)
1042		      {
1043			daemon->tcp_pids[i] = p;
1044			break;
1045		      }
1046		}
1047	      close(confd);
1048	    }
1049#endif
1050	  else
1051	    {
1052	      unsigned char *buff;
1053	      struct server *s;
1054	      int flags;
1055	      struct in_addr dst_addr_4;
1056
1057	      dst_addr_4.s_addr = 0;
1058
1059	       /* Arrange for SIGALARM after CHILD_LIFETIME seconds to
1060		  terminate the process. */
1061	      if (!(daemon->options & OPT_DEBUG))
1062		alarm(CHILD_LIFETIME);
1063
1064	      /* start with no upstream connections. */
1065	      for (s = daemon->servers; s; s = s->next)
1066		 s->tcpfd = -1;
1067
1068	      /* The connected socket inherits non-blocking
1069		 attribute from the listening socket.
1070		 Reset that here. */
1071	      if ((flags = fcntl(confd, F_GETFL, 0)) != -1)
1072		fcntl(confd, F_SETFL, flags & ~O_NONBLOCK);
1073
1074	      if (listener->family == AF_INET)
1075		dst_addr_4 = iface->addr.in.sin_addr;
1076
1077	      buff = tcp_request(confd, now, dst_addr_4, iface->netmask);
1078
1079	      shutdown(confd, SHUT_RDWR);
1080	      close(confd);
1081
1082	      if (buff)
1083		free(buff);
1084
1085	      for (s = daemon->servers; s; s = s->next)
1086		if (s->tcpfd != -1)
1087		  {
1088		    shutdown(s->tcpfd, SHUT_RDWR);
1089		    close(s->tcpfd);
1090		  }
1091#ifndef NO_FORK
1092	      if (!(daemon->options & OPT_DEBUG))
1093		{
1094		  flush_log();
1095		  _exit(0);
1096		}
1097#endif
1098	    }
1099	}
1100    }
1101}
1102
1103#ifdef HAVE_DHCP
1104int make_icmp_sock(void)
1105{
1106  int fd;
1107  int zeroopt = 0;
1108
1109  if ((fd = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
1110    {
1111      if (!fix_fd(fd) ||
1112	  setsockopt(fd, SOL_SOCKET, SO_DONTROUTE, &zeroopt, sizeof(zeroopt)) == -1)
1113	{
1114	  close(fd);
1115	  fd = -1;
1116	}
1117    }
1118
1119  return fd;
1120}
1121
1122int icmp_ping(struct in_addr addr)
1123{
1124  /* Try and get an ICMP echo from a machine. */
1125
1126  /* Note that whilst in the three second wait, we check for
1127     (and service) events on the DNS sockets, (so doing that
1128     better not use any resources our caller has in use...)
1129     but we remain deaf to signals or further DHCP packets. */
1130
1131  int fd;
1132  struct sockaddr_in saddr;
1133  struct {
1134    struct ip ip;
1135    struct icmp icmp;
1136  } packet;
1137  unsigned short id = rand16();
1138  unsigned int i, j;
1139  int gotreply = 0;
1140  time_t start, now;
1141
1142#if defined(HAVE_LINUX_NETWORK) || defined (HAVE_SOLARIS_NETWORK)
1143  if ((fd = make_icmp_sock()) == -1)
1144    return 0;
1145#else
1146  int opt = 2000;
1147  fd = daemon->dhcp_icmp_fd;
1148  setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1149#endif
1150
1151  saddr.sin_family = AF_INET;
1152  saddr.sin_port = 0;
1153  saddr.sin_addr = addr;
1154#ifdef HAVE_SOCKADDR_SA_LEN
1155  saddr.sin_len = sizeof(struct sockaddr_in);
1156#endif
1157
1158  memset(&packet.icmp, 0, sizeof(packet.icmp));
1159  packet.icmp.icmp_type = ICMP_ECHO;
1160  packet.icmp.icmp_id = id;
1161  for (j = 0, i = 0; i < sizeof(struct icmp) / 2; i++)
1162    j += ((u16 *)&packet.icmp)[i];
1163  while (j>>16)
1164    j = (j & 0xffff) + (j >> 16);
1165  packet.icmp.icmp_cksum = (j == 0xffff) ? j : ~j;
1166
1167  while (sendto(fd, (char *)&packet.icmp, sizeof(struct icmp), 0,
1168		(struct sockaddr *)&saddr, sizeof(saddr)) == -1 &&
1169	 retry_send());
1170
1171  for (now = start = dnsmasq_time();
1172       difftime(now, start) < (float)PING_WAIT;)
1173    {
1174      struct timeval tv;
1175      fd_set rset, wset;
1176      struct sockaddr_in faddr;
1177      int maxfd = fd;
1178      socklen_t len = sizeof(faddr);
1179
1180      tv.tv_usec = 250000;
1181      tv.tv_sec = 0;
1182
1183      FD_ZERO(&rset);
1184      FD_ZERO(&wset);
1185      FD_SET(fd, &rset);
1186      set_dns_listeners(now, &rset, &maxfd);
1187      set_log_writer(&wset, &maxfd);
1188
1189      if (select(maxfd+1, &rset, &wset, NULL, &tv) < 0)
1190	{
1191	  FD_ZERO(&rset);
1192	  FD_ZERO(&wset);
1193	}
1194
1195      now = dnsmasq_time();
1196
1197      check_log_writer(&wset);
1198      check_dns_listeners(&rset, now);
1199
1200      if (FD_ISSET(fd, &rset) &&
1201	  recvfrom(fd, &packet, sizeof(packet), 0,
1202		   (struct sockaddr *)&faddr, &len) == sizeof(packet) &&
1203	  saddr.sin_addr.s_addr == faddr.sin_addr.s_addr &&
1204	  packet.icmp.icmp_type == ICMP_ECHOREPLY &&
1205	  packet.icmp.icmp_seq == 0 &&
1206	  packet.icmp.icmp_id == id)
1207	{
1208	  gotreply = 1;
1209	  break;
1210	}
1211    }
1212
1213#if defined(HAVE_LINUX_NETWORK) || defined(HAVE_SOLARIS_NETWORK)
1214  close(fd);
1215#else
1216  opt = 1;
1217  setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1218#endif
1219
1220  return gotreply;
1221}
1222#endif
1223