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