dnsmasq: update to 2.73 (23.06.2015)
[tomato.git] / release / src / router / dnsmasq / src / dnsmasq.c
blobf087226979a966d1503f741b84e851a148295bd0
1 /* dnsmasq is Copyright (c) 2000-2015 Simon Kelley
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.
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.
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/>.
16 /* Jon Zarate AFAIK wrote the original Tomato specific code, primarily to
17 support extra info in the GUI. Following is a vague clue as to how it
18 hangs together.
20 device list status is handled by www/devlist.c - this sends a SIGUSR2
21 to dnsmasq which causes the 'tomato_helper' function to execute in
22 addition to the normal dnsmasq SIGUSR2 code (Switch logfile, but since
23 Tomato not using that it doesn't matter) devlist.c waits up to 5 secs
24 for file '/var/tmp/dhcp/leases.!' to disappear before continuing
25 (Must be a better way to do this IPC stuff)
27 tomato_helper(lease.c) does a couple of things:
29 It looks for /var/tmp/dhcp/delete and deletes any known leases by IP
30 address found therein. It deletes /var/tmp/dhcp/delete when done.
31 This implements the 'delete lease' from GUI functionality.
33 It dumps the current dhcp leases into /var/tmp/dhcp/lease.! (tmp file)
34 subtracting the current time from the lease expiry time, thus producing
35 a 'lease remaining' time for the GUI.
36 The temp file is renamed to /var/tmp/dhcp/leases thus signalling devlist.c
37 that it may proceed. Finally when devlist.c is finished
38 /var/tmp/dhcp/leases is removed.
40 dnsmasq.c also intercepts SIGHUP so that it may flush the lease file.
41 This is so lease expiry times survive a process restart since dnsmasq
42 reads the lease file at start-up.
44 Finally(?) lease_update_file (lease.c) writes out the remaining lease
45 duration for each dhcp lease rather than lease expiry time (with RTC) or
46 lease length (no RTC) for dnsmasq's internal lease database.
48 dhcp lease file is /var/lib/misc/dnsmasq.leases
50 Above description K Darbyshire-Bryant 04/12/13
55 /* Declare static char *compiler_opts in config.h */
56 #define DNSMASQ_COMPILE_OPTS
58 #include "dnsmasq.h"
60 struct daemon *daemon;
62 static volatile pid_t pid = 0;
63 static volatile int pipewrite;
65 static int set_dns_listeners(time_t now, fd_set *set, int *maxfdp);
66 static void check_dns_listeners(fd_set *set, time_t now);
67 static void sig_handler(int sig);
68 static void async_event(int pipe, time_t now);
69 static void fatal_event(struct event_desc *ev, char *msg);
70 static int read_event(int fd, struct event_desc *evp, char **msg);
71 static void poll_resolv(int force, int do_reload, time_t now);
73 int main (int argc, char **argv)
75 int bind_fallback = 0;
76 time_t now;
77 struct sigaction sigact;
78 struct iname *if_tmp;
79 int piperead, pipefd[2], err_pipe[2];
80 struct passwd *ent_pw = NULL;
81 #if defined(HAVE_SCRIPT)
82 uid_t script_uid = 0;
83 gid_t script_gid = 0;
84 #endif
85 struct group *gp = NULL;
86 long i, max_fd = sysconf(_SC_OPEN_MAX);
87 char *baduser = NULL;
88 int log_err;
89 #if defined(HAVE_LINUX_NETWORK)
90 cap_user_header_t hdr = NULL;
91 cap_user_data_t data = NULL;
92 char *bound_device = NULL;
93 int did_bind = 0;
94 #endif
95 #if defined(HAVE_DHCP) || defined(HAVE_DHCP6)
96 struct dhcp_context *context;
97 struct dhcp_relay *relay;
98 #endif
99 #ifdef HAVE_TFTP
100 int tftp_prefix_missing = 0;
101 #endif
103 #ifdef LOCALEDIR
104 setlocale(LC_ALL, "");
105 bindtextdomain("dnsmasq", LOCALEDIR);
106 textdomain("dnsmasq");
107 #endif
109 sigact.sa_handler = sig_handler;
110 sigact.sa_flags = 0;
111 sigemptyset(&sigact.sa_mask);
112 sigaction(SIGUSR1, &sigact, NULL);
113 sigaction(SIGUSR2, &sigact, NULL);
114 sigaction(SIGHUP, &sigact, NULL);
115 sigaction(SIGTERM, &sigact, NULL);
116 sigaction(SIGALRM, &sigact, NULL);
117 sigaction(SIGCHLD, &sigact, NULL);
119 /* ignore SIGPIPE */
120 sigact.sa_handler = SIG_IGN;
121 sigaction(SIGPIPE, &sigact, NULL);
123 umask(022); /* known umask, create leases and pid files as 0644 */
125 rand_init(); /* Must precede read_opts() */
127 read_opts(argc, argv, compile_opts);
129 if (daemon->edns_pktsz < PACKETSZ)
130 daemon->edns_pktsz = PACKETSZ;
132 daemon->packet_buff_sz = daemon->edns_pktsz > DNSMASQ_PACKETSZ ?
133 daemon->edns_pktsz : DNSMASQ_PACKETSZ;
134 daemon->packet = safe_malloc(daemon->packet_buff_sz);
136 daemon->addrbuff = safe_malloc(ADDRSTRLEN);
137 if (option_bool(OPT_EXTRALOG))
138 daemon->addrbuff2 = safe_malloc(ADDRSTRLEN);
140 #ifdef HAVE_DNSSEC
141 if (option_bool(OPT_DNSSEC_VALID))
143 /* Note that both /000 and '.' are allowed within labels. These get
144 represented in presentation format using NAME_ESCAPE as an escape
145 character when in DNSSEC mode.
146 In theory, if all the characters in a name were /000 or
147 '.' or NAME_ESCAPE then all would have to be escaped, so the
148 presentation format would be twice as long as the spec.
150 daemon->namebuff was previously allocated by the option-reading
151 code before we knew if we're in DNSSEC mode, so reallocate here. */
152 free(daemon->namebuff);
153 daemon->namebuff = safe_malloc(MAXDNAME * 2);
154 daemon->keyname = safe_malloc(MAXDNAME * 2);
155 daemon->workspacename = safe_malloc(MAXDNAME * 2);
157 #endif
159 #ifdef HAVE_DHCP
160 if (!daemon->lease_file)
162 if (daemon->dhcp || daemon->dhcp6)
163 daemon->lease_file = LEASEFILE;
165 #endif
167 /* Close any file descriptors we inherited apart from std{in|out|err}
169 Ensure that at least stdin, stdout and stderr (fd 0, 1, 2) exist,
170 otherwise file descriptors we create can end up being 0, 1, or 2
171 and then get accidentally closed later when we make 0, 1, and 2
172 open to /dev/null. Normally we'll be started with 0, 1 and 2 open,
173 but it's not guaranteed. By opening /dev/null three times, we
174 ensure that we're not using those fds for real stuff. */
175 for (i = 0; i < max_fd; i++)
176 if (i != STDOUT_FILENO && i != STDERR_FILENO && i != STDIN_FILENO)
177 close(i);
178 else
179 open("/dev/null", O_RDWR);
181 #ifndef HAVE_LINUX_NETWORK
182 # if !(defined(IP_RECVDSTADDR) && defined(IP_RECVIF) && defined(IP_SENDSRCADDR))
183 if (!option_bool(OPT_NOWILD))
185 bind_fallback = 1;
186 set_option_bool(OPT_NOWILD);
188 # endif
190 /* -- bind-dynamic not supported on !Linux, fall back to --bind-interfaces */
191 if (option_bool(OPT_CLEVERBIND))
193 bind_fallback = 1;
194 set_option_bool(OPT_NOWILD);
195 reset_option_bool(OPT_CLEVERBIND);
197 #endif
199 #ifndef HAVE_INOTIFY
200 if (daemon->dynamic_dirs)
201 die(_("dhcp-hostsdir, dhcp-optsdir and hostsdir are not supported on this platform"), NULL, EC_BADCONF);
202 #endif
204 if (option_bool(OPT_DNSSEC_VALID))
206 #ifdef HAVE_DNSSEC
207 if (!daemon->ds)
208 die(_("no trust anchors provided for DNSSEC"), NULL, EC_BADCONF);
210 if (daemon->cachesize < CACHESIZ)
211 die(_("cannot reduce cache size from default when DNSSEC enabled"), NULL, EC_BADCONF);
212 #else
213 die(_("DNSSEC not available: set HAVE_DNSSEC in src/config.h"), NULL, EC_BADCONF);
214 #endif
217 #ifndef HAVE_TFTP
218 if (option_bool(OPT_TFTP))
219 die(_("TFTP server not available: set HAVE_TFTP in src/config.h"), NULL, EC_BADCONF);
220 #endif
222 #ifdef HAVE_CONNTRACK
223 if (option_bool(OPT_CONNTRACK) && (daemon->query_port != 0 || daemon->osport))
224 die (_("cannot use --conntrack AND --query-port"), NULL, EC_BADCONF);
225 #else
226 if (option_bool(OPT_CONNTRACK))
227 die(_("conntrack support not available: set HAVE_CONNTRACK in src/config.h"), NULL, EC_BADCONF);
228 #endif
230 #ifdef HAVE_SOLARIS_NETWORK
231 if (daemon->max_logs != 0)
232 die(_("asychronous logging is not available under Solaris"), NULL, EC_BADCONF);
233 #endif
235 #ifdef __ANDROID__
236 if (daemon->max_logs != 0)
237 die(_("asychronous logging is not available under Android"), NULL, EC_BADCONF);
238 #endif
240 #ifndef HAVE_AUTH
241 if (daemon->authserver)
242 die(_("authoritative DNS not available: set HAVE_AUTH in src/config.h"), NULL, EC_BADCONF);
243 #endif
245 #ifndef HAVE_LOOP
246 if (option_bool(OPT_LOOP_DETECT))
247 die(_("loop detection not available: set HAVE_LOOP in src/config.h"), NULL, EC_BADCONF);
248 #endif
250 now = dnsmasq_time();
252 /* Create a serial at startup if not configured. */
253 if (daemon->authinterface && daemon->soa_sn == 0)
254 #ifdef HAVE_BROKEN_RTC
255 die(_("zone serial must be configured in --auth-soa"), NULL, EC_BADCONF);
256 #else
257 daemon->soa_sn = now;
258 #endif
260 #ifdef HAVE_DHCP6
261 if (daemon->dhcp6)
263 daemon->doing_ra = option_bool(OPT_RA);
265 for (context = daemon->dhcp6; context; context = context->next)
267 if (context->flags & CONTEXT_DHCP)
268 daemon->doing_dhcp6 = 1;
269 if (context->flags & CONTEXT_RA)
270 daemon->doing_ra = 1;
271 #if !defined(HAVE_LINUX_NETWORK) && !defined(HAVE_BSD_NETWORK)
272 if (context->flags & CONTEXT_TEMPLATE)
273 die (_("dhcp-range constructor not available on this platform"), NULL, EC_BADCONF);
274 #endif
277 #endif
279 #ifdef HAVE_DHCP
280 /* Note that order matters here, we must call lease_init before
281 creating any file descriptors which shouldn't be leaked
282 to the lease-script init process. We need to call common_init
283 before lease_init to allocate buffers it uses.*/
284 if (daemon->dhcp || daemon->doing_dhcp6 || daemon->relay4 || daemon->relay6)
286 dhcp_common_init();
287 if (daemon->dhcp || daemon->doing_dhcp6)
288 lease_init(now);
291 if (daemon->dhcp || daemon->relay4)
292 dhcp_init();
294 # ifdef HAVE_DHCP6
295 if (daemon->doing_ra || daemon->doing_dhcp6 || daemon->relay6)
296 ra_init(now);
298 if (daemon->doing_dhcp6 || daemon->relay6)
299 dhcp6_init();
300 # endif
302 #endif
304 #ifdef HAVE_IPSET
305 if (daemon->ipsets)
306 ipset_init();
307 #endif
309 #if defined(HAVE_LINUX_NETWORK)
310 netlink_init();
311 #elif defined(HAVE_BSD_NETWORK)
312 route_init();
313 #endif
315 if (option_bool(OPT_NOWILD) && option_bool(OPT_CLEVERBIND))
316 die(_("cannot set --bind-interfaces and --bind-dynamic"), NULL, EC_BADCONF);
318 if (!enumerate_interfaces(1) || !enumerate_interfaces(0))
319 die(_("failed to find list of interfaces: %s"), NULL, EC_MISC);
321 if (option_bool(OPT_NOWILD) || option_bool(OPT_CLEVERBIND))
323 create_bound_listeners(1);
325 if (!option_bool(OPT_CLEVERBIND))
326 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
327 if (if_tmp->name && !if_tmp->used)
328 die(_("unknown interface %s"), if_tmp->name, EC_BADNET);
330 #if defined(HAVE_LINUX_NETWORK) && defined(HAVE_DHCP)
331 /* after enumerate_interfaces() */
332 bound_device = whichdevice();
334 if (daemon->dhcp)
336 if (!daemon->relay4 && bound_device)
338 bindtodevice(bound_device, daemon->dhcpfd);
339 did_bind = 1;
341 if (daemon->enable_pxe && bound_device)
343 bindtodevice(bound_device, daemon->pxefd);
344 did_bind = 1;
347 #endif
349 #if defined(HAVE_LINUX_NETWORK) && defined(HAVE_DHCP6)
350 if (daemon->doing_dhcp6 && !daemon->relay6 && bound_device)
352 bindtodevice(bound_device, daemon->dhcp6fd);
353 did_bind = 1;
355 #endif
357 else
358 create_wildcard_listeners();
360 #ifdef HAVE_DHCP6
361 /* after enumerate_interfaces() */
362 if (daemon->doing_dhcp6 || daemon->relay6 || daemon->doing_ra)
363 join_multicast(1);
365 /* After netlink_init() and before create_helper() */
366 lease_make_duid(now);
367 #endif
369 if (daemon->port != 0)
371 cache_init();
373 #ifdef HAVE_DNSSEC
374 blockdata_init();
375 #endif
378 #ifdef HAVE_INOTIFY
379 if (daemon->port != 0 || daemon->dhcp || daemon->doing_dhcp6)
380 inotify_dnsmasq_init();
381 else
382 daemon->inotifyfd = -1;
383 #endif
385 if (option_bool(OPT_DBUS))
386 #ifdef HAVE_DBUS
388 char *err;
389 daemon->dbus = NULL;
390 daemon->watches = NULL;
391 if ((err = dbus_init()))
392 die(_("DBus error: %s"), err, EC_MISC);
394 #else
395 die(_("DBus not available: set HAVE_DBUS in src/config.h"), NULL, EC_BADCONF);
396 #endif
398 if (daemon->port != 0)
399 pre_allocate_sfds();
401 #if defined(HAVE_SCRIPT)
402 /* Note getpwnam returns static storage */
403 if ((daemon->dhcp || daemon->dhcp6) &&
404 daemon->scriptuser &&
405 (daemon->lease_change_command || daemon->luascript))
407 if ((ent_pw = getpwnam(daemon->scriptuser)))
409 script_uid = ent_pw->pw_uid;
410 script_gid = ent_pw->pw_gid;
412 else
413 baduser = daemon->scriptuser;
415 #endif
417 if (daemon->username && !(ent_pw = getpwnam(daemon->username)))
418 baduser = daemon->username;
419 else if (daemon->groupname && !(gp = getgrnam(daemon->groupname)))
420 baduser = daemon->groupname;
422 if (baduser)
423 die(_("unknown user or group: %s"), baduser, EC_BADCONF);
425 /* implement group defaults, "dip" if available, or group associated with uid */
426 if (!daemon->group_set && !gp)
428 if (!(gp = getgrnam(CHGRP)) && ent_pw)
429 gp = getgrgid(ent_pw->pw_gid);
431 /* for error message */
432 if (gp)
433 daemon->groupname = gp->gr_name;
436 #if defined(HAVE_LINUX_NETWORK)
437 /* determine capability API version here, while we can still
438 call safe_malloc */
439 if (ent_pw && ent_pw->pw_uid != 0)
441 int capsize = 1; /* for header version 1 */
442 hdr = safe_malloc(sizeof(*hdr));
444 /* find version supported by kernel */
445 memset(hdr, 0, sizeof(*hdr));
446 capget(hdr, NULL);
448 if (hdr->version != LINUX_CAPABILITY_VERSION_1)
450 /* if unknown version, use largest supported version (3) */
451 if (hdr->version != LINUX_CAPABILITY_VERSION_2)
452 hdr->version = LINUX_CAPABILITY_VERSION_3;
453 capsize = 2;
456 data = safe_malloc(sizeof(*data) * capsize);
457 memset(data, 0, sizeof(*data) * capsize);
459 #endif
461 /* Use a pipe to carry signals and other events back to the event loop
462 in a race-free manner and another to carry errors to daemon-invoking process */
463 safe_pipe(pipefd, 1);
465 piperead = pipefd[0];
466 pipewrite = pipefd[1];
467 /* prime the pipe to load stuff first time. */
468 send_event(pipewrite, EVENT_INIT, 0, NULL);
470 err_pipe[1] = -1;
472 if (!option_bool(OPT_DEBUG))
474 /* The following code "daemonizes" the process.
475 See Stevens section 12.4 */
477 if (chdir("/") != 0)
478 die(_("cannot chdir to filesystem root: %s"), NULL, EC_MISC);
480 #ifndef NO_FORK
481 if (!option_bool(OPT_NO_FORK))
483 pid_t pid;
485 /* pipe to carry errors back to original process.
486 When startup is complete we close this and the process terminates. */
487 safe_pipe(err_pipe, 0);
489 if ((pid = fork()) == -1)
490 /* fd == -1 since we've not forked, never returns. */
491 send_event(-1, EVENT_FORK_ERR, errno, NULL);
493 if (pid != 0)
495 struct event_desc ev;
496 char *msg;
498 /* close our copy of write-end */
499 while (retry_send(close(err_pipe[1])));
501 /* check for errors after the fork */
502 if (read_event(err_pipe[0], &ev, &msg))
503 fatal_event(&ev, msg);
505 _exit(EC_GOOD);
508 while (retry_send(close(err_pipe[0])));
510 /* NO calls to die() from here on. */
512 setsid();
514 if ((pid = fork()) == -1)
515 send_event(err_pipe[1], EVENT_FORK_ERR, errno, NULL);
517 if (pid != 0)
518 _exit(0);
520 #endif
522 /* write pidfile _after_ forking ! */
523 if (daemon->runfile)
525 int fd, err = 0;
527 sprintf(daemon->namebuff, "%d\n", (int) getpid());
529 /* Explanation: Some installations of dnsmasq (eg Debian/Ubuntu) locate the pid-file
530 in a directory which is writable by the non-privileged user that dnsmasq runs as. This
531 allows the daemon to delete the file as part of its shutdown. This is a security hole to the
532 extent that an attacker running as the unprivileged user could replace the pidfile with a
533 symlink, and have the target of that symlink overwritten as root next time dnsmasq starts.
535 The folowing code first deletes any existing file, and then opens it with the O_EXCL flag,
536 ensuring that the open() fails should there be any existing file (because the unlink() failed,
537 or an attacker exploited the race between unlink() and open()). This ensures that no symlink
538 attack can succeed.
540 Any compromise of the non-privileged user still theoretically allows the pid-file to be
541 replaced whilst dnsmasq is running. The worst that could allow is that the usual
542 "shutdown dnsmasq" shell command could be tricked into stopping any other process.
544 Note that if dnsmasq is started as non-root (eg for testing) it silently ignores
545 failure to write the pid-file.
548 unlink(daemon->runfile);
550 if ((fd = open(daemon->runfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH)) == -1)
552 /* only complain if started as root */
553 if (getuid() == 0)
554 err = 1;
556 else
558 if (!read_write(fd, (unsigned char *)daemon->namebuff, strlen(daemon->namebuff), 0))
559 err = 1;
560 else
562 while (retry_send(close(fd)));
563 if (errno != 0)
564 err = 1;
568 if (err)
570 send_event(err_pipe[1], EVENT_PIDFILE, errno, daemon->runfile);
571 _exit(0);
576 log_err = log_start(ent_pw, err_pipe[1]);
578 if (!option_bool(OPT_DEBUG))
580 /* open stdout etc to /dev/null */
581 int nullfd = open("/dev/null", O_RDWR);
582 dup2(nullfd, STDOUT_FILENO);
583 dup2(nullfd, STDERR_FILENO);
584 dup2(nullfd, STDIN_FILENO);
585 close(nullfd);
588 /* if we are to run scripts, we need to fork a helper before dropping root. */
589 daemon->helperfd = -1;
590 #ifdef HAVE_SCRIPT
591 if ((daemon->dhcp || daemon->dhcp6) && (daemon->lease_change_command || daemon->luascript))
592 daemon->helperfd = create_helper(pipewrite, err_pipe[1], script_uid, script_gid, max_fd);
593 #endif
595 if (!option_bool(OPT_DEBUG) && getuid() == 0)
597 int bad_capabilities = 0;
598 gid_t dummy;
600 /* remove all supplimentary groups */
601 if (gp &&
602 (setgroups(0, &dummy) == -1 ||
603 setgid(gp->gr_gid) == -1))
605 send_event(err_pipe[1], EVENT_GROUP_ERR, errno, daemon->groupname);
606 _exit(0);
609 if (ent_pw && ent_pw->pw_uid != 0)
611 #if defined(HAVE_LINUX_NETWORK)
612 /* On linux, we keep CAP_NETADMIN (for ARP-injection) and
613 CAP_NET_RAW (for icmp) if we're doing dhcp. If we have yet to bind
614 ports because of DAD, or we're doing it dynamically,
615 we need CAP_NET_BIND_SERVICE too. */
616 if (is_dad_listeners() || option_bool(OPT_CLEVERBIND))
617 data->effective = data->permitted = data->inheritable =
618 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) |
619 (1 << CAP_SETUID) | (1 << CAP_NET_BIND_SERVICE);
620 else
621 data->effective = data->permitted = data->inheritable =
622 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID);
624 /* Tell kernel to not clear capabilities when dropping root */
625 if (capset(hdr, data) == -1 || prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1)
626 bad_capabilities = errno;
628 #elif defined(HAVE_SOLARIS_NETWORK)
629 /* http://developers.sun.com/solaris/articles/program_privileges.html */
630 priv_set_t *priv_set;
632 if (!(priv_set = priv_str_to_set("basic", ",", NULL)) ||
633 priv_addset(priv_set, PRIV_NET_ICMPACCESS) == -1 ||
634 priv_addset(priv_set, PRIV_SYS_NET_CONFIG) == -1)
635 bad_capabilities = errno;
637 if (priv_set && bad_capabilities == 0)
639 priv_inverse(priv_set);
641 if (setppriv(PRIV_OFF, PRIV_LIMIT, priv_set) == -1)
642 bad_capabilities = errno;
645 if (priv_set)
646 priv_freeset(priv_set);
648 #endif
650 if (bad_capabilities != 0)
652 send_event(err_pipe[1], EVENT_CAP_ERR, bad_capabilities, NULL);
653 _exit(0);
656 /* finally drop root */
657 if (setuid(ent_pw->pw_uid) == -1)
659 send_event(err_pipe[1], EVENT_USER_ERR, errno, daemon->username);
660 _exit(0);
663 #ifdef HAVE_LINUX_NETWORK
664 if (is_dad_listeners() || option_bool(OPT_CLEVERBIND))
665 data->effective = data->permitted =
666 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_NET_BIND_SERVICE);
667 else
668 data->effective = data->permitted =
669 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW);
670 data->inheritable = 0;
672 /* lose the setuid and setgid capbilities */
673 if (capset(hdr, data) == -1)
675 send_event(err_pipe[1], EVENT_CAP_ERR, errno, NULL);
676 _exit(0);
678 #endif
683 #ifdef HAVE_LINUX_NETWORK
684 free(hdr);
685 free(data);
686 if (option_bool(OPT_DEBUG))
687 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
688 #endif
690 #ifdef HAVE_TFTP
691 if (option_bool(OPT_TFTP))
693 DIR *dir;
694 struct tftp_prefix *p;
696 if (daemon->tftp_prefix)
698 if (!((dir = opendir(daemon->tftp_prefix))))
700 tftp_prefix_missing = 1;
701 if (!option_bool(OPT_TFTP_NO_FAIL))
703 send_event(err_pipe[1], EVENT_TFTP_ERR, errno, daemon->tftp_prefix);
704 _exit(0);
707 else
708 closedir(dir);
711 for (p = daemon->if_prefix; p; p = p->next)
713 p->missing = 0;
714 if (!((dir = opendir(p->prefix))))
716 p->missing = 1;
717 if (!option_bool(OPT_TFTP_NO_FAIL))
719 send_event(err_pipe[1], EVENT_TFTP_ERR, errno, p->prefix);
720 _exit(0);
723 else
724 closedir(dir);
727 #endif
729 if (daemon->port == 0)
730 my_syslog(LOG_INFO, _("started, version %s DNS disabled"), VERSION);
731 else if (daemon->cachesize != 0)
732 my_syslog(LOG_INFO, _("started, version %s cachesize %d"), VERSION, daemon->cachesize);
733 else
734 my_syslog(LOG_INFO, _("started, version %s cache disabled"), VERSION);
736 my_syslog(LOG_INFO, _("compile time options: %s"), compile_opts);
738 #ifdef HAVE_DBUS
739 if (option_bool(OPT_DBUS))
741 if (daemon->dbus)
742 my_syslog(LOG_INFO, _("DBus support enabled: connected to system bus"));
743 else
744 my_syslog(LOG_INFO, _("DBus support enabled: bus connection pending"));
746 #endif
748 if (option_bool(OPT_LOCAL_SERVICE))
749 my_syslog(LOG_INFO, _("DNS service limited to local subnets"));
751 #ifdef HAVE_DNSSEC
752 if (option_bool(OPT_DNSSEC_VALID))
754 int rc;
756 /* Delay creating the timestamp file until here, after we've changed user, so that
757 it has the correct owner to allow updating the mtime later.
758 This means we have to report fatal errors via the pipe. */
759 if ((rc = setup_timestamp()) == -1)
761 send_event(err_pipe[1], EVENT_TIME_ERR, errno, daemon->timestamp_file);
762 _exit(0);
765 my_syslog(LOG_INFO, _("DNSSEC validation enabled"));
767 if (option_bool(OPT_DNSSEC_TIME))
768 my_syslog(LOG_INFO, _("DNSSEC signature timestamps not checked until first cache reload"));
770 if (rc == 1)
771 my_syslog(LOG_INFO, _("DNSSEC signature timestamps not checked until system time valid"));
773 #endif
775 if (log_err != 0)
776 my_syslog(LOG_WARNING, _("warning: failed to change owner of %s: %s"),
777 daemon->log_file, strerror(log_err));
779 if (bind_fallback)
780 my_syslog(LOG_WARNING, _("setting --bind-interfaces option because of OS limitations"));
782 if (option_bool(OPT_NOWILD))
783 warn_bound_listeners();
785 warn_int_names();
787 if (!option_bool(OPT_NOWILD))
788 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
789 if (if_tmp->name && !if_tmp->used)
790 my_syslog(LOG_WARNING, _("warning: interface %s does not currently exist"), if_tmp->name);
792 if (daemon->port != 0 && option_bool(OPT_NO_RESOLV))
794 if (daemon->resolv_files && !daemon->resolv_files->is_default)
795 my_syslog(LOG_WARNING, _("warning: ignoring resolv-file flag because no-resolv is set"));
796 daemon->resolv_files = NULL;
797 if (!daemon->servers)
798 my_syslog(LOG_WARNING, _("warning: no upstream servers configured"));
801 if (daemon->max_logs != 0)
802 my_syslog(LOG_INFO, _("asynchronous logging enabled, queue limit is %d messages"), daemon->max_logs);
805 #ifdef HAVE_DHCP
806 for (context = daemon->dhcp; context; context = context->next)
807 log_context(AF_INET, context);
809 for (relay = daemon->relay4; relay; relay = relay->next)
810 log_relay(AF_INET, relay);
812 # ifdef HAVE_DHCP6
813 for (context = daemon->dhcp6; context; context = context->next)
814 log_context(AF_INET6, context);
816 for (relay = daemon->relay6; relay; relay = relay->next)
817 log_relay(AF_INET6, relay);
819 if (daemon->doing_dhcp6 || daemon->doing_ra)
820 dhcp_construct_contexts(now);
822 if (option_bool(OPT_RA))
823 my_syslog(MS_DHCP | LOG_INFO, _("IPv6 router advertisement enabled"));
824 # endif
826 # ifdef HAVE_LINUX_NETWORK
827 if (did_bind)
828 my_syslog(MS_DHCP | LOG_INFO, _("DHCP, sockets bound exclusively to interface %s"), bound_device);
829 # endif
831 /* after dhcp_contruct_contexts */
832 if (daemon->dhcp || daemon->doing_dhcp6)
833 lease_find_interfaces(now);
834 #endif
836 #ifdef HAVE_TFTP
837 if (option_bool(OPT_TFTP))
839 struct tftp_prefix *p;
840 #ifdef FD_SETSIZE
841 if (FD_SETSIZE < (unsigned)max_fd)
842 max_fd = FD_SETSIZE;
843 #endif
845 my_syslog(MS_TFTP | LOG_INFO, "TFTP %s%s %s",
846 daemon->tftp_prefix ? _("root is ") : _("enabled"),
847 daemon->tftp_prefix ? daemon->tftp_prefix: "",
848 option_bool(OPT_TFTP_SECURE) ? _("secure mode") : "");
850 if (tftp_prefix_missing)
851 my_syslog(MS_TFTP | LOG_WARNING, _("warning: %s inaccessible"), daemon->tftp_prefix);
853 for (p = daemon->if_prefix; p; p = p->next)
854 if (p->missing)
855 my_syslog(MS_TFTP | LOG_WARNING, _("warning: TFTP directory %s inaccessible"), p->prefix);
857 /* This is a guess, it assumes that for small limits,
858 disjoint files might be served, but for large limits,
859 a single file will be sent to may clients (the file only needs
860 one fd). */
862 max_fd -= 30; /* use other than TFTP */
864 if (max_fd < 0)
865 max_fd = 5;
866 else if (max_fd < 100)
867 max_fd = max_fd/2;
868 else
869 max_fd = max_fd - 20;
871 /* if we have to use a limited range of ports,
872 that will limit the number of transfers */
873 if (daemon->start_tftp_port != 0 &&
874 daemon->end_tftp_port - daemon->start_tftp_port + 1 < max_fd)
875 max_fd = daemon->end_tftp_port - daemon->start_tftp_port + 1;
877 if (daemon->tftp_max > max_fd)
879 daemon->tftp_max = max_fd;
880 my_syslog(MS_TFTP | LOG_WARNING,
881 _("restricting maximum simultaneous TFTP transfers to %d"),
882 daemon->tftp_max);
885 #endif
887 /* finished start-up - release original process */
888 if (err_pipe[1] != -1)
889 while (retry_send(close(err_pipe[1])));
891 if (daemon->port != 0)
892 check_servers();
894 pid = getpid();
896 #ifdef HAVE_INOTIFY
897 /* Using inotify, have to select a resolv file at startup */
898 poll_resolv(1, 0, now);
899 #endif
901 while (1)
903 int maxfd = -1;
904 struct timeval t, *tp = NULL;
905 fd_set rset, wset, eset;
907 FD_ZERO(&rset);
908 FD_ZERO(&wset);
909 FD_ZERO(&eset);
911 /* if we are out of resources, find how long we have to wait
912 for some to come free, we'll loop around then and restart
913 listening for queries */
914 if ((t.tv_sec = set_dns_listeners(now, &rset, &maxfd)) != 0)
916 t.tv_usec = 0;
917 tp = &t;
920 /* Whilst polling for the dbus, or doing a tftp transfer, wake every quarter second */
921 if (daemon->tftp_trans ||
922 (option_bool(OPT_DBUS) && !daemon->dbus))
924 t.tv_sec = 0;
925 t.tv_usec = 250000;
926 tp = &t;
928 /* Wake every second whilst waiting for DAD to complete */
929 else if (is_dad_listeners())
931 t.tv_sec = 1;
932 t.tv_usec = 0;
933 tp = &t;
936 #ifdef HAVE_DBUS
937 set_dbus_listeners(&maxfd, &rset, &wset, &eset);
938 #endif
940 #ifdef HAVE_DHCP
941 if (daemon->dhcp || daemon->relay4)
943 FD_SET(daemon->dhcpfd, &rset);
944 bump_maxfd(daemon->dhcpfd, &maxfd);
945 if (daemon->pxefd != -1)
947 FD_SET(daemon->pxefd, &rset);
948 bump_maxfd(daemon->pxefd, &maxfd);
951 #endif
953 #ifdef HAVE_DHCP6
954 if (daemon->doing_dhcp6 || daemon->relay6)
956 FD_SET(daemon->dhcp6fd, &rset);
957 bump_maxfd(daemon->dhcp6fd, &maxfd);
960 if (daemon->doing_ra)
962 FD_SET(daemon->icmp6fd, &rset);
963 bump_maxfd(daemon->icmp6fd, &maxfd);
965 #endif
967 #ifdef HAVE_INOTIFY
968 if (daemon->inotifyfd != -1)
970 FD_SET(daemon->inotifyfd, &rset);
971 bump_maxfd(daemon->inotifyfd, &maxfd);
973 #endif
975 #if defined(HAVE_LINUX_NETWORK)
976 FD_SET(daemon->netlinkfd, &rset);
977 bump_maxfd(daemon->netlinkfd, &maxfd);
978 #elif defined(HAVE_BSD_NETWORK)
979 FD_SET(daemon->routefd, &rset);
980 bump_maxfd(daemon->routefd, &maxfd);
981 #endif
983 FD_SET(piperead, &rset);
984 bump_maxfd(piperead, &maxfd);
986 #ifdef HAVE_DHCP
987 # ifdef HAVE_SCRIPT
988 while (helper_buf_empty() && do_script_run(now));
990 # ifdef HAVE_TFTP
991 while (helper_buf_empty() && do_tftp_script_run());
992 # endif
994 if (!helper_buf_empty())
996 FD_SET(daemon->helperfd, &wset);
997 bump_maxfd(daemon->helperfd, &maxfd);
999 # else
1000 /* need this for other side-effects */
1001 while (do_script_run(now));
1003 # ifdef HAVE_TFTP
1004 while (do_tftp_script_run());
1005 # endif
1007 # endif
1008 #endif
1010 /* must do this just before select(), when we know no
1011 more calls to my_syslog() can occur */
1012 set_log_writer(&wset, &maxfd);
1014 if (select(maxfd+1, &rset, &wset, &eset, tp) < 0)
1016 /* otherwise undefined after error */
1017 FD_ZERO(&rset); FD_ZERO(&wset); FD_ZERO(&eset);
1020 now = dnsmasq_time();
1022 check_log_writer(&wset);
1024 /* prime. */
1025 enumerate_interfaces(1);
1027 /* Check the interfaces to see if any have exited DAD state
1028 and if so, bind the address. */
1029 if (is_dad_listeners())
1031 enumerate_interfaces(0);
1032 /* NB, is_dad_listeners() == 1 --> we're binding interfaces */
1033 create_bound_listeners(0);
1034 warn_bound_listeners();
1037 #if defined(HAVE_LINUX_NETWORK)
1038 if (FD_ISSET(daemon->netlinkfd, &rset))
1039 netlink_multicast();
1040 #elif defined(HAVE_BSD_NETWORK)
1041 if (FD_ISSET(daemon->routefd, &rset))
1042 route_sock();
1043 #endif
1045 #ifdef HAVE_INOTIFY
1046 if (daemon->inotifyfd != -1 && FD_ISSET(daemon->inotifyfd, &rset) && inotify_check(now))
1048 if (daemon->port != 0 && !option_bool(OPT_NO_POLL))
1049 poll_resolv(1, 1, now);
1051 #else
1052 /* Check for changes to resolv files once per second max. */
1053 /* Don't go silent for long periods if the clock goes backwards. */
1054 if (daemon->last_resolv == 0 ||
1055 difftime(now, daemon->last_resolv) > 1.0 ||
1056 difftime(now, daemon->last_resolv) < -1.0)
1058 /* poll_resolv doesn't need to reload first time through, since
1059 that's queued anyway. */
1061 poll_resolv(0, daemon->last_resolv != 0, now);
1062 daemon->last_resolv = now;
1064 #endif
1066 if (FD_ISSET(piperead, &rset))
1067 async_event(piperead, now);
1069 #ifdef HAVE_DBUS
1070 /* if we didn't create a DBus connection, retry now. */
1071 if (option_bool(OPT_DBUS) && !daemon->dbus)
1073 char *err;
1074 if ((err = dbus_init()))
1075 my_syslog(LOG_WARNING, _("DBus error: %s"), err);
1076 if (daemon->dbus)
1077 my_syslog(LOG_INFO, _("connected to system DBus"));
1079 check_dbus_listeners(&rset, &wset, &eset);
1080 #endif
1082 check_dns_listeners(&rset, now);
1084 #ifdef HAVE_TFTP
1085 check_tftp_listeners(&rset, now);
1086 #endif
1088 #ifdef HAVE_DHCP
1089 if (daemon->dhcp || daemon->relay4)
1091 if (FD_ISSET(daemon->dhcpfd, &rset))
1092 dhcp_packet(now, 0);
1093 if (daemon->pxefd != -1 && FD_ISSET(daemon->pxefd, &rset))
1094 dhcp_packet(now, 1);
1097 #ifdef HAVE_DHCP6
1098 if ((daemon->doing_dhcp6 || daemon->relay6) && FD_ISSET(daemon->dhcp6fd, &rset))
1099 dhcp6_packet(now);
1101 if (daemon->doing_ra && FD_ISSET(daemon->icmp6fd, &rset))
1102 icmp6_packet(now);
1103 #endif
1105 # ifdef HAVE_SCRIPT
1106 if (daemon->helperfd != -1 && FD_ISSET(daemon->helperfd, &wset))
1107 helper_write();
1108 # endif
1109 #endif
1114 static void sig_handler(int sig)
1116 if (pid == 0)
1118 /* ignore anything other than TERM during startup
1119 and in helper proc. (helper ignore TERM too) */
1120 if (sig == SIGTERM)
1121 exit(EC_MISC);
1123 else if (pid != getpid())
1125 /* alarm is used to kill TCP children after a fixed time. */
1126 if (sig == SIGALRM)
1127 _exit(0);
1129 else
1131 /* master process */
1132 int event, errsave = errno;
1134 if (sig == SIGHUP)
1135 event = EVENT_RELOAD;
1136 else if (sig == SIGCHLD)
1137 event = EVENT_CHILD;
1138 else if (sig == SIGALRM)
1139 event = EVENT_ALARM;
1140 else if (sig == SIGTERM)
1141 event = EVENT_TERM;
1142 else if (sig == SIGUSR1)
1143 event = EVENT_DUMP;
1144 else if (sig == SIGUSR2)
1145 event = EVENT_REOPEN;
1146 else
1147 return;
1149 send_event(pipewrite, event, 0, NULL);
1150 errno = errsave;
1154 /* now == 0 -> queue immediate callback */
1155 void send_alarm(time_t event, time_t now)
1157 if (now == 0 || event != 0)
1159 /* alarm(0) or alarm(-ve) doesn't do what we want.... */
1160 if ((now == 0 || difftime(event, now) <= 0.0))
1161 send_event(pipewrite, EVENT_ALARM, 0, NULL);
1162 else
1163 alarm((unsigned)difftime(event, now));
1167 void queue_event(int event)
1169 send_event(pipewrite, event, 0, NULL);
1172 void send_event(int fd, int event, int data, char *msg)
1174 struct event_desc ev;
1175 struct iovec iov[2];
1177 ev.event = event;
1178 ev.data = data;
1179 ev.msg_sz = msg ? strlen(msg) : 0;
1181 iov[0].iov_base = &ev;
1182 iov[0].iov_len = sizeof(ev);
1183 iov[1].iov_base = msg;
1184 iov[1].iov_len = ev.msg_sz;
1186 /* error pipe, debug mode. */
1187 if (fd == -1)
1188 fatal_event(&ev, msg);
1189 else
1190 /* pipe is non-blocking and struct event_desc is smaller than
1191 PIPE_BUF, so this either fails or writes everything */
1192 while (writev(fd, iov, msg ? 2 : 1) == -1 && errno == EINTR);
1195 /* NOTE: the memory used to return msg is leaked: use msgs in events only
1196 to describe fatal errors. */
1197 static int read_event(int fd, struct event_desc *evp, char **msg)
1199 char *buf;
1201 if (!read_write(fd, (unsigned char *)evp, sizeof(struct event_desc), 1))
1202 return 0;
1204 *msg = NULL;
1206 if (evp->msg_sz != 0 &&
1207 (buf = malloc(evp->msg_sz + 1)) &&
1208 read_write(fd, (unsigned char *)buf, evp->msg_sz, 1))
1210 buf[evp->msg_sz] = 0;
1211 *msg = buf;
1214 return 1;
1217 static void fatal_event(struct event_desc *ev, char *msg)
1219 errno = ev->data;
1221 switch (ev->event)
1223 case EVENT_DIE:
1224 exit(0);
1226 case EVENT_FORK_ERR:
1227 die(_("cannot fork into background: %s"), NULL, EC_MISC);
1229 case EVENT_PIPE_ERR:
1230 die(_("failed to create helper: %s"), NULL, EC_MISC);
1232 case EVENT_CAP_ERR:
1233 die(_("setting capabilities failed: %s"), NULL, EC_MISC);
1235 case EVENT_USER_ERR:
1236 die(_("failed to change user-id to %s: %s"), msg, EC_MISC);
1238 case EVENT_GROUP_ERR:
1239 die(_("failed to change group-id to %s: %s"), msg, EC_MISC);
1241 case EVENT_PIDFILE:
1242 die(_("failed to open pidfile %s: %s"), msg, EC_FILE);
1244 case EVENT_LOG_ERR:
1245 die(_("cannot open log %s: %s"), msg, EC_FILE);
1247 case EVENT_LUA_ERR:
1248 die(_("failed to load Lua script: %s"), msg, EC_MISC);
1250 case EVENT_TFTP_ERR:
1251 die(_("TFTP directory %s inaccessible: %s"), msg, EC_FILE);
1253 case EVENT_TIME_ERR:
1254 die(_("cannot create timestamp file %s: %s" ), msg, EC_BADCONF);
1258 static void async_event(int pipe, time_t now)
1260 pid_t p;
1261 struct event_desc ev;
1262 int i, check = 0;
1263 char *msg;
1265 /* NOTE: the memory used to return msg is leaked: use msgs in events only
1266 to describe fatal errors. */
1268 if (read_event(pipe, &ev, &msg))
1269 switch (ev.event)
1271 case EVENT_RELOAD:
1272 #ifdef HAVE_DNSSEC
1273 if (option_bool(OPT_DNSSEC_VALID) && option_bool(OPT_DNSSEC_TIME))
1275 my_syslog(LOG_INFO, _("now checking DNSSEC signature timestamps"));
1276 reset_option_bool(OPT_DNSSEC_TIME);
1278 #endif
1279 /* fall through */
1281 case EVENT_INIT:
1282 clear_cache_and_reload(now);
1284 if (daemon->port != 0)
1286 if (daemon->resolv_files && option_bool(OPT_NO_POLL))
1288 reload_servers(daemon->resolv_files->name);
1289 check = 1;
1292 if (daemon->servers_file)
1294 read_servers_file();
1295 check = 1;
1298 if (check)
1299 check_servers();
1302 #ifdef HAVE_DHCP
1303 rerun_scripts();
1304 #endif
1305 break;
1307 case EVENT_DUMP:
1308 if (daemon->port != 0)
1309 dump_cache(now);
1310 break;
1312 case EVENT_ALARM:
1313 #ifdef HAVE_DHCP
1314 if (daemon->dhcp || daemon->doing_dhcp6)
1316 lease_prune(NULL, now);
1317 lease_update_file(now);
1319 #ifdef HAVE_DHCP6
1320 else if (daemon->doing_ra)
1321 /* Not doing DHCP, so no lease system, manage alarms for ra only */
1322 send_alarm(periodic_ra(now), now);
1323 #endif
1324 #endif
1325 break;
1327 case EVENT_CHILD:
1328 /* See Stevens 5.10 */
1329 while ((p = waitpid(-1, NULL, WNOHANG)) != 0)
1330 if (p == -1)
1332 if (errno != EINTR)
1333 break;
1335 else
1336 for (i = 0 ; i < MAX_PROCS; i++)
1337 if (daemon->tcp_pids[i] == p)
1338 daemon->tcp_pids[i] = 0;
1339 break;
1341 case EVENT_KILLED:
1342 my_syslog(LOG_WARNING, _("script process killed by signal %d"), ev.data);
1343 break;
1345 case EVENT_EXITED:
1346 my_syslog(LOG_WARNING, _("script process exited with status %d"), ev.data);
1347 break;
1349 case EVENT_EXEC_ERR:
1350 my_syslog(LOG_ERR, _("failed to execute %s: %s"),
1351 daemon->lease_change_command, strerror(ev.data));
1352 break;
1354 /* necessary for fatal errors in helper */
1355 case EVENT_USER_ERR:
1356 case EVENT_DIE:
1357 case EVENT_LUA_ERR:
1358 fatal_event(&ev, msg);
1359 break;
1361 case EVENT_REOPEN:
1362 /* Note: this may leave TCP-handling processes with the old file still open.
1363 Since any such process will die in CHILD_LIFETIME or probably much sooner,
1364 we leave them logging to the old file. */
1366 if (daemon->log_file != NULL)
1367 log_reopen(daemon->log_file);
1369 #ifdef HAVE_TOMATO
1370 tomato_helper(now); //possibly delete & write out leases for tomato
1371 #endif //TOMATO
1372 /* following is Asus tweak. Interestingly Asus read the dnsmasq leases db
1373 directly. They signal dnsmasq to update via SIGUSR2 and wait 1 second
1374 assuming the file will be complete by the time they come to parse it.
1375 Race conditions anyone? What if dnsmasq happens to be updating the
1376 file anyway? */
1377 #if defined(HAVE_DHCP) && defined(HAVE_LEASEFILE_EXPIRE) && !defined(HAVE_TOMATO)
1378 if (daemon->dhcp || daemon->dhcp6)
1379 flush_lease_file(now);
1380 #endif
1381 break;
1383 case EVENT_NEWADDR:
1384 newaddress(now);
1385 break;
1387 case EVENT_NEWROUTE:
1388 resend_query();
1389 /* Force re-reading resolv file right now, for luck. */
1390 poll_resolv(0, 1, now);
1391 break;
1393 case EVENT_TERM:
1394 /* Knock all our children on the head. */
1395 for (i = 0; i < MAX_PROCS; i++)
1396 if (daemon->tcp_pids[i] != 0)
1397 kill(daemon->tcp_pids[i], SIGALRM);
1399 #if defined(HAVE_SCRIPT)
1400 /* handle pending lease transitions */
1401 if (daemon->helperfd != -1)
1403 /* block in writes until all done */
1404 if ((i = fcntl(daemon->helperfd, F_GETFL)) != -1)
1405 fcntl(daemon->helperfd, F_SETFL, i & ~O_NONBLOCK);
1406 do {
1407 helper_write();
1408 } while (!helper_buf_empty() || do_script_run(now));
1409 while (retry_send(close(daemon->helperfd)));
1411 #endif
1413 //Originally TOMATO tweak
1414 #if defined(HAVE_DHCP) && defined(HAVE_LEASEFILE_EXPIRE)
1415 if (daemon->dhcp || daemon->dhcp6)
1416 flush_lease_file(now);
1417 #endif
1419 if (daemon->lease_stream)
1420 fclose(daemon->lease_stream);
1422 if (daemon->runfile)
1423 unlink(daemon->runfile);
1425 my_syslog(LOG_INFO, _("exiting on receipt of SIGTERM"));
1426 flush_log();
1427 exit(EC_GOOD);
1431 static void poll_resolv(int force, int do_reload, time_t now)
1433 struct resolvc *res, *latest;
1434 struct stat statbuf;
1435 time_t last_change = 0;
1436 /* There may be more than one possible file.
1437 Go through and find the one which changed _last_.
1438 Warn of any which can't be read. */
1440 if (daemon->port == 0 || option_bool(OPT_NO_POLL))
1441 return;
1443 for (latest = NULL, res = daemon->resolv_files; res; res = res->next)
1444 if (stat(res->name, &statbuf) == -1)
1446 if (force)
1448 res->mtime = 0;
1449 continue;
1452 if (!res->logged)
1453 my_syslog(LOG_WARNING, _("failed to access %s: %s"), res->name, strerror(errno));
1454 res->logged = 1;
1456 if (res->mtime != 0)
1458 /* existing file evaporated, force selection of the latest
1459 file even if its mtime hasn't changed since we last looked */
1460 poll_resolv(1, do_reload, now);
1461 return;
1464 else
1466 res->logged = 0;
1467 if (force || (statbuf.st_mtime != res->mtime))
1469 res->mtime = statbuf.st_mtime;
1470 if (difftime(statbuf.st_mtime, last_change) > 0.0)
1472 last_change = statbuf.st_mtime;
1473 latest = res;
1478 if (latest)
1480 static int warned = 0;
1481 if (reload_servers(latest->name))
1483 my_syslog(LOG_INFO, _("reading %s"), latest->name);
1484 warned = 0;
1485 check_servers();
1486 if (option_bool(OPT_RELOAD) && do_reload)
1487 clear_cache_and_reload(now);
1489 else
1491 latest->mtime = 0;
1492 if (!warned)
1494 my_syslog(LOG_WARNING, _("no servers found in %s, will retry"), latest->name);
1495 warned = 1;
1501 void clear_cache_and_reload(time_t now)
1503 (void)now;
1505 if (daemon->port != 0)
1506 cache_reload();
1508 #ifdef HAVE_DHCP
1509 if (daemon->dhcp || daemon->doing_dhcp6)
1511 if (option_bool(OPT_ETHERS))
1512 dhcp_read_ethers();
1513 reread_dhcp();
1514 #ifdef HAVE_INOTIFY
1515 set_dynamic_inotify(AH_DHCP_HST | AH_DHCP_OPT, 0, NULL, 0);
1516 #endif
1517 dhcp_update_configs(daemon->dhcp_conf);
1518 lease_update_from_configs();
1519 lease_update_file(now);
1520 lease_update_dns(1);
1522 #ifdef HAVE_DHCP6
1523 else if (daemon->doing_ra)
1524 /* Not doing DHCP, so no lease system, manage
1525 alarms for ra only */
1526 send_alarm(periodic_ra(now), now);
1527 #endif
1528 #endif
1531 static int set_dns_listeners(time_t now, fd_set *set, int *maxfdp)
1533 struct serverfd *serverfdp;
1534 struct listener *listener;
1535 int wait = 0, i;
1537 #ifdef HAVE_TFTP
1538 int tftp = 0;
1539 struct tftp_transfer *transfer;
1540 for (transfer = daemon->tftp_trans; transfer; transfer = transfer->next)
1542 tftp++;
1543 FD_SET(transfer->sockfd, set);
1544 bump_maxfd(transfer->sockfd, maxfdp);
1546 #endif
1548 /* will we be able to get memory? */
1549 if (daemon->port != 0)
1550 get_new_frec(now, &wait, 0);
1552 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1554 FD_SET(serverfdp->fd, set);
1555 bump_maxfd(serverfdp->fd, maxfdp);
1558 if (daemon->port != 0 && !daemon->osport)
1559 for (i = 0; i < RANDOM_SOCKS; i++)
1560 if (daemon->randomsocks[i].refcount != 0)
1562 FD_SET(daemon->randomsocks[i].fd, set);
1563 bump_maxfd(daemon->randomsocks[i].fd, maxfdp);
1566 for (listener = daemon->listeners; listener; listener = listener->next)
1568 /* only listen for queries if we have resources */
1569 if (listener->fd != -1 && wait == 0)
1571 FD_SET(listener->fd, set);
1572 bump_maxfd(listener->fd, maxfdp);
1575 /* death of a child goes through the select loop, so
1576 we don't need to explicitly arrange to wake up here */
1577 if (listener->tcpfd != -1)
1578 for (i = 0; i < MAX_PROCS; i++)
1579 if (daemon->tcp_pids[i] == 0)
1581 FD_SET(listener->tcpfd, set);
1582 bump_maxfd(listener->tcpfd, maxfdp);
1583 break;
1586 #ifdef HAVE_TFTP
1587 if (tftp <= daemon->tftp_max && listener->tftpfd != -1)
1589 FD_SET(listener->tftpfd, set);
1590 bump_maxfd(listener->tftpfd, maxfdp);
1592 #endif
1596 return wait;
1599 static void check_dns_listeners(fd_set *set, time_t now)
1601 struct serverfd *serverfdp;
1602 struct listener *listener;
1603 int i;
1605 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1606 if (FD_ISSET(serverfdp->fd, set))
1607 reply_query(serverfdp->fd, serverfdp->source_addr.sa.sa_family, now);
1609 if (daemon->port != 0 && !daemon->osport)
1610 for (i = 0; i < RANDOM_SOCKS; i++)
1611 if (daemon->randomsocks[i].refcount != 0 &&
1612 FD_ISSET(daemon->randomsocks[i].fd, set))
1613 reply_query(daemon->randomsocks[i].fd, daemon->randomsocks[i].family, now);
1615 for (listener = daemon->listeners; listener; listener = listener->next)
1617 if (listener->fd != -1 && FD_ISSET(listener->fd, set))
1618 receive_query(listener, now);
1620 #ifdef HAVE_TFTP
1621 if (listener->tftpfd != -1 && FD_ISSET(listener->tftpfd, set))
1622 tftp_request(listener, now);
1623 #endif
1625 if (listener->tcpfd != -1 && FD_ISSET(listener->tcpfd, set))
1627 int confd, client_ok = 1;
1628 struct irec *iface = NULL;
1629 pid_t p;
1630 union mysockaddr tcp_addr;
1631 socklen_t tcp_len = sizeof(union mysockaddr);
1633 while ((confd = accept(listener->tcpfd, NULL, NULL)) == -1 && errno == EINTR);
1635 if (confd == -1)
1636 continue;
1638 if (getsockname(confd, (struct sockaddr *)&tcp_addr, &tcp_len) == -1)
1640 while (retry_send(close(confd)));
1641 continue;
1644 /* Make sure that the interface list is up-to-date.
1646 We do this here as we may need the results below, and
1647 the DNS code needs them for --interface-name stuff.
1649 Multiple calls to enumerate_interfaces() per select loop are
1650 inhibited, so calls to it in the child process (which doesn't select())
1651 have no effect. This avoids two processes reading from the same
1652 netlink fd and screwing the pooch entirely.
1655 enumerate_interfaces(0);
1657 if (option_bool(OPT_NOWILD))
1658 iface = listener->iface; /* May be NULL */
1659 else
1661 int if_index;
1662 char intr_name[IF_NAMESIZE];
1664 /* if we can find the arrival interface, check it's one that's allowed */
1665 if ((if_index = tcp_interface(confd, tcp_addr.sa.sa_family)) != 0 &&
1666 indextoname(listener->tcpfd, if_index, intr_name))
1668 struct all_addr addr;
1669 addr.addr.addr4 = tcp_addr.in.sin_addr;
1670 #ifdef HAVE_IPV6
1671 if (tcp_addr.sa.sa_family == AF_INET6)
1672 addr.addr.addr6 = tcp_addr.in6.sin6_addr;
1673 #endif
1675 for (iface = daemon->interfaces; iface; iface = iface->next)
1676 if (iface->index == if_index)
1677 break;
1679 if (!iface && !loopback_exception(listener->tcpfd, tcp_addr.sa.sa_family, &addr, intr_name))
1680 client_ok = 0;
1683 if (option_bool(OPT_CLEVERBIND))
1684 iface = listener->iface; /* May be NULL */
1685 else
1687 /* Check for allowed interfaces when binding the wildcard address:
1688 we do this by looking for an interface with the same address as
1689 the local address of the TCP connection, then looking to see if that's
1690 an allowed interface. As a side effect, we get the netmask of the
1691 interface too, for localisation. */
1693 for (iface = daemon->interfaces; iface; iface = iface->next)
1694 if (sockaddr_isequal(&iface->addr, &tcp_addr))
1695 break;
1697 if (!iface)
1698 client_ok = 0;
1702 if (!client_ok)
1704 shutdown(confd, SHUT_RDWR);
1705 while (retry_send(close(confd)));
1707 #ifndef NO_FORK
1708 else if (!option_bool(OPT_DEBUG) && (p = fork()) != 0)
1710 if (p != -1)
1712 int i;
1713 for (i = 0; i < MAX_PROCS; i++)
1714 if (daemon->tcp_pids[i] == 0)
1716 daemon->tcp_pids[i] = p;
1717 break;
1720 while (retry_send(close(confd)));
1722 /* The child can use up to TCP_MAX_QUERIES ids, so skip that many. */
1723 daemon->log_id += TCP_MAX_QUERIES;
1725 #endif
1726 else
1728 unsigned char *buff;
1729 struct server *s;
1730 int flags;
1731 struct in_addr netmask;
1732 int auth_dns;
1734 if (iface)
1736 netmask = iface->netmask;
1737 auth_dns = iface->dns_auth;
1739 else
1741 netmask.s_addr = 0;
1742 auth_dns = 0;
1745 #ifndef NO_FORK
1746 /* Arrange for SIGALARM after CHILD_LIFETIME seconds to
1747 terminate the process. */
1748 if (!option_bool(OPT_DEBUG))
1749 alarm(CHILD_LIFETIME);
1750 #endif
1752 /* start with no upstream connections. */
1753 for (s = daemon->servers; s; s = s->next)
1754 s->tcpfd = -1;
1756 /* The connected socket inherits non-blocking
1757 attribute from the listening socket.
1758 Reset that here. */
1759 if ((flags = fcntl(confd, F_GETFL, 0)) != -1)
1760 fcntl(confd, F_SETFL, flags & ~O_NONBLOCK);
1762 buff = tcp_request(confd, now, &tcp_addr, netmask, auth_dns);
1764 shutdown(confd, SHUT_RDWR);
1765 while (retry_send(close(confd)));
1767 if (buff)
1768 free(buff);
1770 for (s = daemon->servers; s; s = s->next)
1771 if (s->tcpfd != -1)
1773 shutdown(s->tcpfd, SHUT_RDWR);
1774 while (retry_send(close(s->tcpfd)));
1776 #ifndef NO_FORK
1777 if (!option_bool(OPT_DEBUG))
1779 flush_log();
1780 _exit(0);
1782 #endif
1788 #ifdef HAVE_DHCP
1789 int make_icmp_sock(void)
1791 int fd;
1792 int zeroopt = 0;
1794 if ((fd = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
1796 if (!fix_fd(fd) ||
1797 setsockopt(fd, SOL_SOCKET, SO_DONTROUTE, &zeroopt, sizeof(zeroopt)) == -1)
1799 close(fd);
1800 fd = -1;
1804 return fd;
1807 int icmp_ping(struct in_addr addr)
1809 /* Try and get an ICMP echo from a machine. */
1811 /* Note that whilst in the three second wait, we check for
1812 (and service) events on the DNS and TFTP sockets, (so doing that
1813 better not use any resources our caller has in use...)
1814 but we remain deaf to signals or further DHCP packets. */
1816 int fd;
1817 struct sockaddr_in saddr;
1818 struct {
1819 struct ip ip;
1820 struct icmp icmp;
1821 } packet;
1822 unsigned short id = rand16();
1823 unsigned int i, j;
1824 int gotreply = 0;
1825 time_t start, now;
1827 #if defined(HAVE_LINUX_NETWORK) || defined (HAVE_SOLARIS_NETWORK)
1828 if ((fd = make_icmp_sock()) == -1)
1829 return 0;
1830 #else
1831 int opt = 2000;
1832 fd = daemon->dhcp_icmp_fd;
1833 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1834 #endif
1836 saddr.sin_family = AF_INET;
1837 saddr.sin_port = 0;
1838 saddr.sin_addr = addr;
1839 #ifdef HAVE_SOCKADDR_SA_LEN
1840 saddr.sin_len = sizeof(struct sockaddr_in);
1841 #endif
1843 memset(&packet.icmp, 0, sizeof(packet.icmp));
1844 packet.icmp.icmp_type = ICMP_ECHO;
1845 packet.icmp.icmp_id = id;
1846 for (j = 0, i = 0; i < sizeof(struct icmp) / 2; i++)
1847 j += ((u16 *)&packet.icmp)[i];
1848 while (j>>16)
1849 j = (j & 0xffff) + (j >> 16);
1850 packet.icmp.icmp_cksum = (j == 0xffff) ? j : ~j;
1852 while (retry_send(sendto(fd, (char *)&packet.icmp, sizeof(struct icmp), 0,
1853 (struct sockaddr *)&saddr, sizeof(saddr))));
1855 for (now = start = dnsmasq_time();
1856 difftime(now, start) < (float)PING_WAIT;)
1858 struct timeval tv;
1859 fd_set rset, wset;
1860 struct sockaddr_in faddr;
1861 int maxfd = fd;
1862 socklen_t len = sizeof(faddr);
1864 tv.tv_usec = 250000;
1865 tv.tv_sec = 0;
1867 FD_ZERO(&rset);
1868 FD_ZERO(&wset);
1869 FD_SET(fd, &rset);
1870 set_dns_listeners(now, &rset, &maxfd);
1871 set_log_writer(&wset, &maxfd);
1873 #ifdef HAVE_DHCP6
1874 if (daemon->doing_ra)
1876 FD_SET(daemon->icmp6fd, &rset);
1877 bump_maxfd(daemon->icmp6fd, &maxfd);
1879 #endif
1881 if (select(maxfd+1, &rset, &wset, NULL, &tv) < 0)
1883 FD_ZERO(&rset);
1884 FD_ZERO(&wset);
1887 now = dnsmasq_time();
1889 check_log_writer(&wset);
1890 check_dns_listeners(&rset, now);
1892 #ifdef HAVE_DHCP6
1893 if (daemon->doing_ra && FD_ISSET(daemon->icmp6fd, &rset))
1894 icmp6_packet(now);
1895 #endif
1897 #ifdef HAVE_TFTP
1898 check_tftp_listeners(&rset, now);
1899 #endif
1901 if (FD_ISSET(fd, &rset) &&
1902 recvfrom(fd, &packet, sizeof(packet), 0,
1903 (struct sockaddr *)&faddr, &len) == sizeof(packet) &&
1904 saddr.sin_addr.s_addr == faddr.sin_addr.s_addr &&
1905 packet.icmp.icmp_type == ICMP_ECHOREPLY &&
1906 packet.icmp.icmp_seq == 0 &&
1907 packet.icmp.icmp_id == id)
1909 gotreply = 1;
1910 break;
1914 #if defined(HAVE_LINUX_NETWORK) || defined(HAVE_SOLARIS_NETWORK)
1915 while (retry_send(close(fd)));
1916 #else
1917 opt = 1;
1918 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1919 #endif
1921 return gotreply;
1923 #endif