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