dnsmasq: re-apply original Tomato specific code
[tomato.git] / release / src / router / dnsmasq / src / dnsmasq.c
blobc11df7ba2c50a77333d239ed18f36f58c6149666
1 /* dnsmasq is Copyright (c) 2000-2016 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);
66 static void check_dns_listeners(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 /* Min buffer size: we check after adding each record, so there must be
133 memory for the largest packet, and the largest record so the
134 min for DNS is PACKETSZ+MAXDNAME+RRFIXEDSZ which is < 1000.
135 This might be increased is EDNS packet size if greater than the minimum. */
136 daemon->packet_buff_sz = daemon->edns_pktsz + MAXDNAME + RRFIXEDSZ;
137 daemon->packet = safe_malloc(daemon->packet_buff_sz);
139 daemon->addrbuff = safe_malloc(ADDRSTRLEN);
140 if (option_bool(OPT_EXTRALOG))
141 daemon->addrbuff2 = safe_malloc(ADDRSTRLEN);
143 #ifdef HAVE_DNSSEC
144 if (option_bool(OPT_DNSSEC_VALID))
146 /* Note that both /000 and '.' are allowed within labels. These get
147 represented in presentation format using NAME_ESCAPE as an escape
148 character when in DNSSEC mode.
149 In theory, if all the characters in a name were /000 or
150 '.' or NAME_ESCAPE then all would have to be escaped, so the
151 presentation format would be twice as long as the spec.
153 daemon->namebuff was previously allocated by the option-reading
154 code before we knew if we're in DNSSEC mode, so reallocate here. */
155 free(daemon->namebuff);
156 daemon->namebuff = safe_malloc(MAXDNAME * 2);
157 daemon->keyname = safe_malloc(MAXDNAME * 2);
158 daemon->workspacename = safe_malloc(MAXDNAME * 2);
160 #endif
162 #ifdef HAVE_DHCP
163 if (!daemon->lease_file)
165 if (daemon->dhcp || daemon->dhcp6)
166 daemon->lease_file = LEASEFILE;
168 #endif
170 /* Close any file descriptors we inherited apart from std{in|out|err}
172 Ensure that at least stdin, stdout and stderr (fd 0, 1, 2) exist,
173 otherwise file descriptors we create can end up being 0, 1, or 2
174 and then get accidentally closed later when we make 0, 1, and 2
175 open to /dev/null. Normally we'll be started with 0, 1 and 2 open,
176 but it's not guaranteed. By opening /dev/null three times, we
177 ensure that we're not using those fds for real stuff. */
178 for (i = 0; i < max_fd; i++)
179 if (i != STDOUT_FILENO && i != STDERR_FILENO && i != STDIN_FILENO)
180 close(i);
181 else
182 open("/dev/null", O_RDWR);
184 #ifndef HAVE_LINUX_NETWORK
185 # if !(defined(IP_RECVDSTADDR) && defined(IP_RECVIF) && defined(IP_SENDSRCADDR))
186 if (!option_bool(OPT_NOWILD))
188 bind_fallback = 1;
189 set_option_bool(OPT_NOWILD);
191 # endif
193 /* -- bind-dynamic not supported on !Linux, fall back to --bind-interfaces */
194 if (option_bool(OPT_CLEVERBIND))
196 bind_fallback = 1;
197 set_option_bool(OPT_NOWILD);
198 reset_option_bool(OPT_CLEVERBIND);
200 #endif
202 #ifndef HAVE_INOTIFY
203 if (daemon->dynamic_dirs)
204 die(_("dhcp-hostsdir, dhcp-optsdir and hostsdir are not supported on this platform"), NULL, EC_BADCONF);
205 #endif
207 if (option_bool(OPT_DNSSEC_VALID))
209 #ifdef HAVE_DNSSEC
210 struct ds_config *ds;
212 /* Must have at least a root trust anchor, or the DNSSEC code
213 can loop forever. */
214 for (ds = daemon->ds; ds; ds = ds->next)
215 if (ds->name[0] == 0)
216 break;
218 if (!ds)
219 die(_("no root trust anchor provided for DNSSEC"), NULL, EC_BADCONF);
221 if (daemon->cachesize < CACHESIZ)
222 die(_("cannot reduce cache size from default when DNSSEC enabled"), NULL, EC_BADCONF);
223 #else
224 die(_("DNSSEC not available: set HAVE_DNSSEC in src/config.h"), NULL, EC_BADCONF);
225 #endif
228 #ifndef HAVE_TFTP
229 if (option_bool(OPT_TFTP))
230 die(_("TFTP server not available: set HAVE_TFTP in src/config.h"), NULL, EC_BADCONF);
231 #endif
233 #ifdef HAVE_CONNTRACK
234 if (option_bool(OPT_CONNTRACK) && (daemon->query_port != 0 || daemon->osport))
235 die (_("cannot use --conntrack AND --query-port"), NULL, EC_BADCONF);
236 #else
237 if (option_bool(OPT_CONNTRACK))
238 die(_("conntrack support not available: set HAVE_CONNTRACK in src/config.h"), NULL, EC_BADCONF);
239 #endif
241 #ifdef HAVE_SOLARIS_NETWORK
242 if (daemon->max_logs != 0)
243 die(_("asychronous logging is not available under Solaris"), NULL, EC_BADCONF);
244 #endif
246 #ifdef __ANDROID__
247 if (daemon->max_logs != 0)
248 die(_("asychronous logging is not available under Android"), NULL, EC_BADCONF);
249 #endif
251 #ifndef HAVE_AUTH
252 if (daemon->authserver)
253 die(_("authoritative DNS not available: set HAVE_AUTH in src/config.h"), NULL, EC_BADCONF);
254 #endif
256 #ifndef HAVE_LOOP
257 if (option_bool(OPT_LOOP_DETECT))
258 die(_("loop detection not available: set HAVE_LOOP in src/config.h"), NULL, EC_BADCONF);
259 #endif
261 if (daemon->max_port != MAX_PORT && daemon->min_port == 0)
262 daemon->min_port = 1024u;
264 if (daemon->max_port < daemon->min_port)
265 die(_("max_port cannot be smaller than min_port"), NULL, EC_BADCONF);
267 now = dnsmasq_time();
269 /* Create a serial at startup if not configured. */
270 if (daemon->authinterface && daemon->soa_sn == 0)
271 #ifdef HAVE_BROKEN_RTC
272 die(_("zone serial must be configured in --auth-soa"), NULL, EC_BADCONF);
273 #else
274 daemon->soa_sn = now;
275 #endif
277 #ifdef HAVE_DHCP6
278 if (daemon->dhcp6)
280 daemon->doing_ra = option_bool(OPT_RA);
282 for (context = daemon->dhcp6; context; context = context->next)
284 if (context->flags & CONTEXT_DHCP)
285 daemon->doing_dhcp6 = 1;
286 if (context->flags & CONTEXT_RA)
287 daemon->doing_ra = 1;
288 #if !defined(HAVE_LINUX_NETWORK) && !defined(HAVE_BSD_NETWORK)
289 if (context->flags & CONTEXT_TEMPLATE)
290 die (_("dhcp-range constructor not available on this platform"), NULL, EC_BADCONF);
291 #endif
294 #endif
296 #ifdef HAVE_DHCP
297 /* Note that order matters here, we must call lease_init before
298 creating any file descriptors which shouldn't be leaked
299 to the lease-script init process. We need to call common_init
300 before lease_init to allocate buffers it uses.
301 The script subsystem relies on DHCP buffers, hence the last two
302 conditions below. */
303 if (daemon->dhcp || daemon->doing_dhcp6 || daemon->relay4 ||
304 daemon->relay6 || option_bool(OPT_TFTP) || option_bool(OPT_SCRIPT_ARP))
306 dhcp_common_init();
307 if (daemon->dhcp || daemon->doing_dhcp6)
308 lease_init(now);
311 if (daemon->dhcp || daemon->relay4)
312 dhcp_init();
314 # ifdef HAVE_DHCP6
315 if (daemon->doing_ra || daemon->doing_dhcp6 || daemon->relay6)
316 ra_init(now);
318 if (daemon->doing_dhcp6 || daemon->relay6)
319 dhcp6_init();
320 # endif
322 #endif
324 #ifdef HAVE_IPSET
325 if (daemon->ipsets)
326 ipset_init();
327 #endif
329 #if defined(HAVE_LINUX_NETWORK)
330 netlink_init();
331 #elif defined(HAVE_BSD_NETWORK)
332 route_init();
333 #endif
335 if (option_bool(OPT_NOWILD) && option_bool(OPT_CLEVERBIND))
336 die(_("cannot set --bind-interfaces and --bind-dynamic"), NULL, EC_BADCONF);
338 if (!enumerate_interfaces(1) || !enumerate_interfaces(0))
339 die(_("failed to find list of interfaces: %s"), NULL, EC_MISC);
341 if (option_bool(OPT_NOWILD) || option_bool(OPT_CLEVERBIND))
343 create_bound_listeners(1);
345 if (!option_bool(OPT_CLEVERBIND))
346 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
347 if (if_tmp->name && !if_tmp->used)
348 die(_("unknown interface %s"), if_tmp->name, EC_BADNET);
350 #if defined(HAVE_LINUX_NETWORK) && defined(HAVE_DHCP)
351 /* after enumerate_interfaces() */
352 bound_device = whichdevice();
354 if (daemon->dhcp)
356 if (!daemon->relay4 && bound_device)
358 bindtodevice(bound_device, daemon->dhcpfd);
359 did_bind = 1;
361 if (daemon->enable_pxe && bound_device)
363 bindtodevice(bound_device, daemon->pxefd);
364 did_bind = 1;
367 #endif
369 #if defined(HAVE_LINUX_NETWORK) && defined(HAVE_DHCP6)
370 if (daemon->doing_dhcp6 && !daemon->relay6 && bound_device)
372 bindtodevice(bound_device, daemon->dhcp6fd);
373 did_bind = 1;
375 #endif
377 else
378 create_wildcard_listeners();
380 #ifdef HAVE_DHCP6
381 /* after enumerate_interfaces() */
382 if (daemon->doing_dhcp6 || daemon->relay6 || daemon->doing_ra)
383 join_multicast(1);
385 /* After netlink_init() and before create_helper() */
386 lease_make_duid(now);
387 #endif
389 if (daemon->port != 0)
391 cache_init();
393 #ifdef HAVE_DNSSEC
394 blockdata_init();
395 #endif
398 #ifdef HAVE_INOTIFY
399 if (daemon->port != 0 || daemon->dhcp || daemon->doing_dhcp6)
400 inotify_dnsmasq_init();
401 else
402 daemon->inotifyfd = -1;
403 #endif
405 if (option_bool(OPT_DBUS))
406 #ifdef HAVE_DBUS
408 char *err;
409 daemon->dbus = NULL;
410 daemon->watches = NULL;
411 if ((err = dbus_init()))
412 die(_("DBus error: %s"), err, EC_MISC);
414 #else
415 die(_("DBus not available: set HAVE_DBUS in src/config.h"), NULL, EC_BADCONF);
416 #endif
418 if (daemon->port != 0)
419 pre_allocate_sfds();
421 #if defined(HAVE_SCRIPT)
422 /* Note getpwnam returns static storage */
423 if ((daemon->dhcp || daemon->dhcp6) &&
424 daemon->scriptuser &&
425 (daemon->lease_change_command || daemon->luascript))
427 if ((ent_pw = getpwnam(daemon->scriptuser)))
429 script_uid = ent_pw->pw_uid;
430 script_gid = ent_pw->pw_gid;
432 else
433 baduser = daemon->scriptuser;
435 #endif
437 if (daemon->username && !(ent_pw = getpwnam(daemon->username)))
438 baduser = daemon->username;
439 else if (daemon->groupname && !(gp = getgrnam(daemon->groupname)))
440 baduser = daemon->groupname;
442 if (baduser)
443 die(_("unknown user or group: %s"), baduser, EC_BADCONF);
445 /* implement group defaults, "dip" if available, or group associated with uid */
446 if (!daemon->group_set && !gp)
448 if (!(gp = getgrnam(CHGRP)) && ent_pw)
449 gp = getgrgid(ent_pw->pw_gid);
451 /* for error message */
452 if (gp)
453 daemon->groupname = gp->gr_name;
456 #if defined(HAVE_LINUX_NETWORK)
457 /* determine capability API version here, while we can still
458 call safe_malloc */
459 if (ent_pw && ent_pw->pw_uid != 0)
461 int capsize = 1; /* for header version 1 */
462 hdr = safe_malloc(sizeof(*hdr));
464 /* find version supported by kernel */
465 memset(hdr, 0, sizeof(*hdr));
466 capget(hdr, NULL);
468 if (hdr->version != LINUX_CAPABILITY_VERSION_1)
470 /* if unknown version, use largest supported version (3) */
471 if (hdr->version != LINUX_CAPABILITY_VERSION_2)
472 hdr->version = LINUX_CAPABILITY_VERSION_3;
473 capsize = 2;
476 data = safe_malloc(sizeof(*data) * capsize);
477 memset(data, 0, sizeof(*data) * capsize);
479 #endif
481 /* Use a pipe to carry signals and other events back to the event loop
482 in a race-free manner and another to carry errors to daemon-invoking process */
483 safe_pipe(pipefd, 1);
485 piperead = pipefd[0];
486 pipewrite = pipefd[1];
487 /* prime the pipe to load stuff first time. */
488 send_event(pipewrite, EVENT_INIT, 0, NULL);
490 err_pipe[1] = -1;
492 if (!option_bool(OPT_DEBUG))
494 /* The following code "daemonizes" the process.
495 See Stevens section 12.4 */
497 if (chdir("/") != 0)
498 die(_("cannot chdir to filesystem root: %s"), NULL, EC_MISC);
500 #ifndef NO_FORK
501 if (!option_bool(OPT_NO_FORK))
503 pid_t pid;
505 /* pipe to carry errors back to original process.
506 When startup is complete we close this and the process terminates. */
507 safe_pipe(err_pipe, 0);
509 if ((pid = fork()) == -1)
510 /* fd == -1 since we've not forked, never returns. */
511 send_event(-1, EVENT_FORK_ERR, errno, NULL);
513 if (pid != 0)
515 struct event_desc ev;
516 char *msg;
518 /* close our copy of write-end */
519 while (retry_send(close(err_pipe[1])));
521 /* check for errors after the fork */
522 if (read_event(err_pipe[0], &ev, &msg))
523 fatal_event(&ev, msg);
525 _exit(EC_GOOD);
528 while (retry_send(close(err_pipe[0])));
530 /* NO calls to die() from here on. */
532 setsid();
534 if ((pid = fork()) == -1)
535 send_event(err_pipe[1], EVENT_FORK_ERR, errno, NULL);
537 if (pid != 0)
538 _exit(0);
540 #endif
542 /* write pidfile _after_ forking ! */
543 if (daemon->runfile)
545 int fd, err = 0;
547 sprintf(daemon->namebuff, "%d\n", (int) getpid());
549 /* Explanation: Some installations of dnsmasq (eg Debian/Ubuntu) locate the pid-file
550 in a directory which is writable by the non-privileged user that dnsmasq runs as. This
551 allows the daemon to delete the file as part of its shutdown. This is a security hole to the
552 extent that an attacker running as the unprivileged user could replace the pidfile with a
553 symlink, and have the target of that symlink overwritten as root next time dnsmasq starts.
555 The folowing code first deletes any existing file, and then opens it with the O_EXCL flag,
556 ensuring that the open() fails should there be any existing file (because the unlink() failed,
557 or an attacker exploited the race between unlink() and open()). This ensures that no symlink
558 attack can succeed.
560 Any compromise of the non-privileged user still theoretically allows the pid-file to be
561 replaced whilst dnsmasq is running. The worst that could allow is that the usual
562 "shutdown dnsmasq" shell command could be tricked into stopping any other process.
564 Note that if dnsmasq is started as non-root (eg for testing) it silently ignores
565 failure to write the pid-file.
568 unlink(daemon->runfile);
570 if ((fd = open(daemon->runfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH)) == -1)
572 /* only complain if started as root */
573 if (getuid() == 0)
574 err = 1;
576 else
578 if (!read_write(fd, (unsigned char *)daemon->namebuff, strlen(daemon->namebuff), 0))
579 err = 1;
580 else
582 while (retry_send(close(fd)));
583 if (errno != 0)
584 err = 1;
588 if (err)
590 send_event(err_pipe[1], EVENT_PIDFILE, errno, daemon->runfile);
591 _exit(0);
596 log_err = log_start(ent_pw, err_pipe[1]);
598 if (!option_bool(OPT_DEBUG))
600 /* open stdout etc to /dev/null */
601 int nullfd = open("/dev/null", O_RDWR);
602 if (nullfd != -1)
604 dup2(nullfd, STDOUT_FILENO);
605 dup2(nullfd, STDERR_FILENO);
606 dup2(nullfd, STDIN_FILENO);
607 close(nullfd);
611 /* if we are to run scripts, we need to fork a helper before dropping root. */
612 daemon->helperfd = -1;
613 #ifdef HAVE_SCRIPT
614 if ((daemon->dhcp || daemon->dhcp6 || option_bool(OPT_TFTP) || option_bool(OPT_SCRIPT_ARP)) &&
615 (daemon->lease_change_command || daemon->luascript))
616 daemon->helperfd = create_helper(pipewrite, err_pipe[1], script_uid, script_gid, max_fd);
617 #endif
619 if (!option_bool(OPT_DEBUG) && getuid() == 0)
621 int bad_capabilities = 0;
622 gid_t dummy;
624 /* remove all supplimentary groups */
625 if (gp &&
626 (setgroups(0, &dummy) == -1 ||
627 setgid(gp->gr_gid) == -1))
629 send_event(err_pipe[1], EVENT_GROUP_ERR, errno, daemon->groupname);
630 _exit(0);
633 if (ent_pw && ent_pw->pw_uid != 0)
635 #if defined(HAVE_LINUX_NETWORK)
636 /* On linux, we keep CAP_NETADMIN (for ARP-injection) and
637 CAP_NET_RAW (for icmp) if we're doing dhcp. If we have yet to bind
638 ports because of DAD, or we're doing it dynamically,
639 we need CAP_NET_BIND_SERVICE too. */
640 if (is_dad_listeners() || option_bool(OPT_CLEVERBIND))
641 data->effective = data->permitted = data->inheritable =
642 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) |
643 (1 << CAP_SETUID) | (1 << CAP_NET_BIND_SERVICE);
644 else
645 data->effective = data->permitted = data->inheritable =
646 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID);
648 /* Tell kernel to not clear capabilities when dropping root */
649 if (capset(hdr, data) == -1 || prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1)
650 bad_capabilities = errno;
652 #elif defined(HAVE_SOLARIS_NETWORK)
653 /* http://developers.sun.com/solaris/articles/program_privileges.html */
654 priv_set_t *priv_set;
656 if (!(priv_set = priv_str_to_set("basic", ",", NULL)) ||
657 priv_addset(priv_set, PRIV_NET_ICMPACCESS) == -1 ||
658 priv_addset(priv_set, PRIV_SYS_NET_CONFIG) == -1)
659 bad_capabilities = errno;
661 if (priv_set && bad_capabilities == 0)
663 priv_inverse(priv_set);
665 if (setppriv(PRIV_OFF, PRIV_LIMIT, priv_set) == -1)
666 bad_capabilities = errno;
669 if (priv_set)
670 priv_freeset(priv_set);
672 #endif
674 if (bad_capabilities != 0)
676 send_event(err_pipe[1], EVENT_CAP_ERR, bad_capabilities, NULL);
677 _exit(0);
680 /* finally drop root */
681 if (setuid(ent_pw->pw_uid) == -1)
683 send_event(err_pipe[1], EVENT_USER_ERR, errno, daemon->username);
684 _exit(0);
687 #ifdef HAVE_LINUX_NETWORK
688 if (is_dad_listeners() || option_bool(OPT_CLEVERBIND))
689 data->effective = data->permitted =
690 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_NET_BIND_SERVICE);
691 else
692 data->effective = data->permitted =
693 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW);
694 data->inheritable = 0;
696 /* lose the setuid and setgid capbilities */
697 if (capset(hdr, data) == -1)
699 send_event(err_pipe[1], EVENT_CAP_ERR, errno, NULL);
700 _exit(0);
702 #endif
707 #ifdef HAVE_LINUX_NETWORK
708 free(hdr);
709 free(data);
710 if (option_bool(OPT_DEBUG))
711 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
712 #endif
714 #ifdef HAVE_TFTP
715 if (option_bool(OPT_TFTP))
717 DIR *dir;
718 struct tftp_prefix *p;
720 if (daemon->tftp_prefix)
722 if (!((dir = opendir(daemon->tftp_prefix))))
724 tftp_prefix_missing = 1;
725 if (!option_bool(OPT_TFTP_NO_FAIL))
727 send_event(err_pipe[1], EVENT_TFTP_ERR, errno, daemon->tftp_prefix);
728 _exit(0);
731 else
732 closedir(dir);
735 for (p = daemon->if_prefix; p; p = p->next)
737 p->missing = 0;
738 if (!((dir = opendir(p->prefix))))
740 p->missing = 1;
741 if (!option_bool(OPT_TFTP_NO_FAIL))
743 send_event(err_pipe[1], EVENT_TFTP_ERR, errno, p->prefix);
744 _exit(0);
747 else
748 closedir(dir);
751 #endif
753 if (daemon->port == 0)
754 my_syslog(LOG_INFO, _("started, version %s DNS disabled"), VERSION);
755 else if (daemon->cachesize != 0)
756 my_syslog(LOG_INFO, _("started, version %s cachesize %d"), VERSION, daemon->cachesize);
757 else
758 my_syslog(LOG_INFO, _("started, version %s cache disabled"), VERSION);
760 my_syslog(LOG_INFO, _("compile time options: %s"), compile_opts);
762 #ifdef HAVE_DBUS
763 if (option_bool(OPT_DBUS))
765 if (daemon->dbus)
766 my_syslog(LOG_INFO, _("DBus support enabled: connected to system bus"));
767 else
768 my_syslog(LOG_INFO, _("DBus support enabled: bus connection pending"));
770 #endif
772 if (option_bool(OPT_LOCAL_SERVICE))
773 my_syslog(LOG_INFO, _("DNS service limited to local subnets"));
775 #ifdef HAVE_DNSSEC
776 if (option_bool(OPT_DNSSEC_VALID))
778 int rc;
780 /* Delay creating the timestamp file until here, after we've changed user, so that
781 it has the correct owner to allow updating the mtime later.
782 This means we have to report fatal errors via the pipe. */
783 if ((rc = setup_timestamp()) == -1)
785 send_event(err_pipe[1], EVENT_TIME_ERR, errno, daemon->timestamp_file);
786 _exit(0);
789 my_syslog(LOG_INFO, _("DNSSEC validation enabled"));
791 if (option_bool(OPT_DNSSEC_TIME))
792 my_syslog(LOG_INFO, _("DNSSEC signature timestamps not checked until first cache reload"));
794 if (rc == 1)
795 my_syslog(LOG_INFO, _("DNSSEC signature timestamps not checked until system time valid"));
797 #endif
799 if (log_err != 0)
800 my_syslog(LOG_WARNING, _("warning: failed to change owner of %s: %s"),
801 daemon->log_file, strerror(log_err));
803 if (bind_fallback)
804 my_syslog(LOG_WARNING, _("setting --bind-interfaces option because of OS limitations"));
806 if (option_bool(OPT_NOWILD))
807 warn_bound_listeners();
809 warn_int_names();
811 if (!option_bool(OPT_NOWILD))
812 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
813 if (if_tmp->name && !if_tmp->used)
814 my_syslog(LOG_WARNING, _("warning: interface %s does not currently exist"), if_tmp->name);
816 if (daemon->port != 0 && option_bool(OPT_NO_RESOLV))
818 if (daemon->resolv_files && !daemon->resolv_files->is_default)
819 my_syslog(LOG_WARNING, _("warning: ignoring resolv-file flag because no-resolv is set"));
820 daemon->resolv_files = NULL;
821 if (!daemon->servers)
822 my_syslog(LOG_WARNING, _("warning: no upstream servers configured"));
825 if (daemon->max_logs != 0)
826 my_syslog(LOG_INFO, _("asynchronous logging enabled, queue limit is %d messages"), daemon->max_logs);
829 #ifdef HAVE_DHCP
830 for (context = daemon->dhcp; context; context = context->next)
831 log_context(AF_INET, context);
833 for (relay = daemon->relay4; relay; relay = relay->next)
834 log_relay(AF_INET, relay);
836 # ifdef HAVE_DHCP6
837 for (context = daemon->dhcp6; context; context = context->next)
838 log_context(AF_INET6, context);
840 for (relay = daemon->relay6; relay; relay = relay->next)
841 log_relay(AF_INET6, relay);
843 if (daemon->doing_dhcp6 || daemon->doing_ra)
844 dhcp_construct_contexts(now);
846 if (option_bool(OPT_RA))
847 my_syslog(MS_DHCP | LOG_INFO, _("IPv6 router advertisement enabled"));
848 # endif
850 # ifdef HAVE_LINUX_NETWORK
851 if (did_bind)
852 my_syslog(MS_DHCP | LOG_INFO, _("DHCP, sockets bound exclusively to interface %s"), bound_device);
853 # endif
855 /* after dhcp_contruct_contexts */
856 if (daemon->dhcp || daemon->doing_dhcp6)
857 lease_find_interfaces(now);
858 #endif
860 #ifdef HAVE_TFTP
861 if (option_bool(OPT_TFTP))
863 struct tftp_prefix *p;
865 my_syslog(MS_TFTP | LOG_INFO, "TFTP %s%s %s",
866 daemon->tftp_prefix ? _("root is ") : _("enabled"),
867 daemon->tftp_prefix ? daemon->tftp_prefix: "",
868 option_bool(OPT_TFTP_SECURE) ? _("secure mode") : "");
870 if (tftp_prefix_missing)
871 my_syslog(MS_TFTP | LOG_WARNING, _("warning: %s inaccessible"), daemon->tftp_prefix);
873 for (p = daemon->if_prefix; p; p = p->next)
874 if (p->missing)
875 my_syslog(MS_TFTP | LOG_WARNING, _("warning: TFTP directory %s inaccessible"), p->prefix);
877 /* This is a guess, it assumes that for small limits,
878 disjoint files might be served, but for large limits,
879 a single file will be sent to may clients (the file only needs
880 one fd). */
882 max_fd -= 30; /* use other than TFTP */
884 if (max_fd < 0)
885 max_fd = 5;
886 else if (max_fd < 100)
887 max_fd = max_fd/2;
888 else
889 max_fd = max_fd - 20;
891 /* if we have to use a limited range of ports,
892 that will limit the number of transfers */
893 if (daemon->start_tftp_port != 0 &&
894 daemon->end_tftp_port - daemon->start_tftp_port + 1 < max_fd)
895 max_fd = daemon->end_tftp_port - daemon->start_tftp_port + 1;
897 if (daemon->tftp_max > max_fd)
899 daemon->tftp_max = max_fd;
900 my_syslog(MS_TFTP | LOG_WARNING,
901 _("restricting maximum simultaneous TFTP transfers to %d"),
902 daemon->tftp_max);
905 #endif
907 /* finished start-up - release original process */
908 if (err_pipe[1] != -1)
909 while (retry_send(close(err_pipe[1])));
911 if (daemon->port != 0)
912 check_servers();
914 pid = getpid();
916 #ifdef HAVE_INOTIFY
917 /* Using inotify, have to select a resolv file at startup */
918 poll_resolv(1, 0, now);
919 #endif
921 while (1)
923 int t, timeout = -1;
925 poll_reset();
927 /* if we are out of resources, find how long we have to wait
928 for some to come free, we'll loop around then and restart
929 listening for queries */
930 if ((t = set_dns_listeners(now)) != 0)
931 timeout = t * 1000;
933 /* Whilst polling for the dbus, or doing a tftp transfer, wake every quarter second */
934 if (daemon->tftp_trans ||
935 (option_bool(OPT_DBUS) && !daemon->dbus))
936 timeout = 250;
938 /* Wake every second whilst waiting for DAD to complete */
939 else if (is_dad_listeners())
940 timeout = 1000;
942 #ifdef HAVE_DBUS
943 set_dbus_listeners();
944 #endif
946 #ifdef HAVE_DHCP
947 if (daemon->dhcp || daemon->relay4)
949 poll_listen(daemon->dhcpfd, POLLIN);
950 if (daemon->pxefd != -1)
951 poll_listen(daemon->pxefd, POLLIN);
953 #endif
955 #ifdef HAVE_DHCP6
956 if (daemon->doing_dhcp6 || daemon->relay6)
957 poll_listen(daemon->dhcp6fd, POLLIN);
959 if (daemon->doing_ra)
960 poll_listen(daemon->icmp6fd, POLLIN);
961 #endif
963 #ifdef HAVE_INOTIFY
964 if (daemon->inotifyfd != -1)
965 poll_listen(daemon->inotifyfd, POLLIN);
966 #endif
968 #if defined(HAVE_LINUX_NETWORK)
969 poll_listen(daemon->netlinkfd, POLLIN);
970 #elif defined(HAVE_BSD_NETWORK)
971 poll_listen(daemon->routefd, POLLIN);
972 #endif
974 poll_listen(piperead, POLLIN);
976 #ifdef HAVE_SCRIPT
977 # ifdef HAVE_DHCP
978 while (helper_buf_empty() && do_script_run(now));
979 # endif
981 /* Refresh cache */
982 if (option_bool(OPT_SCRIPT_ARP))
983 find_mac(NULL, NULL, 0, now);
984 while (helper_buf_empty() && do_arp_script_run());
986 # ifdef HAVE_TFTP
987 while (helper_buf_empty() && do_tftp_script_run());
988 # endif
990 if (!helper_buf_empty())
991 poll_listen(daemon->helperfd, POLLOUT);
992 #else
993 /* need this for other side-effects */
994 # ifdef HAVE_DHCP
995 while (do_script_run(now));
996 # endif
998 while (do_arp_script_run());
1000 # ifdef HAVE_TFTP
1001 while (do_tftp_script_run());
1002 # endif
1004 #endif
1007 /* must do this just before select(), when we know no
1008 more calls to my_syslog() can occur */
1009 set_log_writer();
1011 if (do_poll(timeout) < 0)
1012 continue;
1014 now = dnsmasq_time();
1016 check_log_writer(0);
1018 /* prime. */
1019 enumerate_interfaces(1);
1021 /* Check the interfaces to see if any have exited DAD state
1022 and if so, bind the address. */
1023 if (is_dad_listeners())
1025 enumerate_interfaces(0);
1026 /* NB, is_dad_listeners() == 1 --> we're binding interfaces */
1027 create_bound_listeners(0);
1028 warn_bound_listeners();
1031 #if defined(HAVE_LINUX_NETWORK)
1032 if (poll_check(daemon->netlinkfd, POLLIN))
1033 netlink_multicast();
1034 #elif defined(HAVE_BSD_NETWORK)
1035 if (poll_check(daemon->routefd, POLLIN))
1036 route_sock();
1037 #endif
1039 #ifdef HAVE_INOTIFY
1040 if (daemon->inotifyfd != -1 && poll_check(daemon->inotifyfd, POLLIN) && inotify_check(now))
1042 if (daemon->port != 0 && !option_bool(OPT_NO_POLL))
1043 poll_resolv(1, 1, now);
1045 #else
1046 /* Check for changes to resolv files once per second max. */
1047 /* Don't go silent for long periods if the clock goes backwards. */
1048 if (daemon->last_resolv == 0 ||
1049 difftime(now, daemon->last_resolv) > 1.0 ||
1050 difftime(now, daemon->last_resolv) < -1.0)
1052 /* poll_resolv doesn't need to reload first time through, since
1053 that's queued anyway. */
1055 poll_resolv(0, daemon->last_resolv != 0, now);
1056 daemon->last_resolv = now;
1058 #endif
1060 if (poll_check(piperead, POLLIN))
1061 async_event(piperead, now);
1063 #ifdef HAVE_DBUS
1064 /* if we didn't create a DBus connection, retry now. */
1065 if (option_bool(OPT_DBUS) && !daemon->dbus)
1067 char *err;
1068 if ((err = dbus_init()))
1069 my_syslog(LOG_WARNING, _("DBus error: %s"), err);
1070 if (daemon->dbus)
1071 my_syslog(LOG_INFO, _("connected to system DBus"));
1073 check_dbus_listeners();
1074 #endif
1076 check_dns_listeners(now);
1078 #ifdef HAVE_TFTP
1079 check_tftp_listeners(now);
1080 #endif
1082 #ifdef HAVE_DHCP
1083 if (daemon->dhcp || daemon->relay4)
1085 if (poll_check(daemon->dhcpfd, POLLIN))
1086 dhcp_packet(now, 0);
1087 if (daemon->pxefd != -1 && poll_check(daemon->pxefd, POLLIN))
1088 dhcp_packet(now, 1);
1091 #ifdef HAVE_DHCP6
1092 if ((daemon->doing_dhcp6 || daemon->relay6) && poll_check(daemon->dhcp6fd, POLLIN))
1093 dhcp6_packet(now);
1095 if (daemon->doing_ra && poll_check(daemon->icmp6fd, POLLIN))
1096 icmp6_packet(now);
1097 #endif
1099 # ifdef HAVE_SCRIPT
1100 if (daemon->helperfd != -1 && poll_check(daemon->helperfd, POLLOUT))
1101 helper_write();
1102 # endif
1103 #endif
1108 static void sig_handler(int sig)
1110 if (pid == 0)
1112 /* ignore anything other than TERM during startup
1113 and in helper proc. (helper ignore TERM too) */
1114 if (sig == SIGTERM)
1115 exit(EC_MISC);
1117 else if (pid != getpid())
1119 /* alarm is used to kill TCP children after a fixed time. */
1120 if (sig == SIGALRM)
1121 _exit(0);
1123 else
1125 /* master process */
1126 int event, errsave = errno;
1128 if (sig == SIGHUP)
1129 event = EVENT_RELOAD;
1130 else if (sig == SIGCHLD)
1131 event = EVENT_CHILD;
1132 else if (sig == SIGALRM)
1133 event = EVENT_ALARM;
1134 else if (sig == SIGTERM)
1135 event = EVENT_TERM;
1136 else if (sig == SIGUSR1)
1137 event = EVENT_DUMP;
1138 else if (sig == SIGUSR2)
1139 event = EVENT_REOPEN;
1140 else
1141 return;
1143 send_event(pipewrite, event, 0, NULL);
1144 errno = errsave;
1148 /* now == 0 -> queue immediate callback */
1149 void send_alarm(time_t event, time_t now)
1151 if (now == 0 || event != 0)
1153 /* alarm(0) or alarm(-ve) doesn't do what we want.... */
1154 if ((now == 0 || difftime(event, now) <= 0.0))
1155 send_event(pipewrite, EVENT_ALARM, 0, NULL);
1156 else
1157 alarm((unsigned)difftime(event, now));
1161 void queue_event(int event)
1163 send_event(pipewrite, event, 0, NULL);
1166 void send_event(int fd, int event, int data, char *msg)
1168 struct event_desc ev;
1169 struct iovec iov[2];
1171 ev.event = event;
1172 ev.data = data;
1173 ev.msg_sz = msg ? strlen(msg) : 0;
1175 iov[0].iov_base = &ev;
1176 iov[0].iov_len = sizeof(ev);
1177 iov[1].iov_base = msg;
1178 iov[1].iov_len = ev.msg_sz;
1180 /* error pipe, debug mode. */
1181 if (fd == -1)
1182 fatal_event(&ev, msg);
1183 else
1184 /* pipe is non-blocking and struct event_desc is smaller than
1185 PIPE_BUF, so this either fails or writes everything */
1186 while (writev(fd, iov, msg ? 2 : 1) == -1 && errno == EINTR);
1189 /* NOTE: the memory used to return msg is leaked: use msgs in events only
1190 to describe fatal errors. */
1191 static int read_event(int fd, struct event_desc *evp, char **msg)
1193 char *buf;
1195 if (!read_write(fd, (unsigned char *)evp, sizeof(struct event_desc), 1))
1196 return 0;
1198 *msg = NULL;
1200 if (evp->msg_sz != 0 &&
1201 (buf = malloc(evp->msg_sz + 1)) &&
1202 read_write(fd, (unsigned char *)buf, evp->msg_sz, 1))
1204 buf[evp->msg_sz] = 0;
1205 *msg = buf;
1208 return 1;
1211 static void fatal_event(struct event_desc *ev, char *msg)
1213 errno = ev->data;
1215 switch (ev->event)
1217 case EVENT_DIE:
1218 exit(0);
1220 case EVENT_FORK_ERR:
1221 die(_("cannot fork into background: %s"), NULL, EC_MISC);
1223 case EVENT_PIPE_ERR:
1224 die(_("failed to create helper: %s"), NULL, EC_MISC);
1226 case EVENT_CAP_ERR:
1227 die(_("setting capabilities failed: %s"), NULL, EC_MISC);
1229 case EVENT_USER_ERR:
1230 die(_("failed to change user-id to %s: %s"), msg, EC_MISC);
1232 case EVENT_GROUP_ERR:
1233 die(_("failed to change group-id to %s: %s"), msg, EC_MISC);
1235 case EVENT_PIDFILE:
1236 die(_("failed to open pidfile %s: %s"), msg, EC_FILE);
1238 case EVENT_LOG_ERR:
1239 die(_("cannot open log %s: %s"), msg, EC_FILE);
1241 case EVENT_LUA_ERR:
1242 die(_("failed to load Lua script: %s"), msg, EC_MISC);
1244 case EVENT_TFTP_ERR:
1245 die(_("TFTP directory %s inaccessible: %s"), msg, EC_FILE);
1247 case EVENT_TIME_ERR:
1248 die(_("cannot create timestamp file %s: %s" ), msg, EC_BADCONF);
1252 static void async_event(int pipe, time_t now)
1254 pid_t p;
1255 struct event_desc ev;
1256 int i, check = 0;
1257 char *msg;
1259 /* NOTE: the memory used to return msg is leaked: use msgs in events only
1260 to describe fatal errors. */
1262 if (read_event(pipe, &ev, &msg))
1263 switch (ev.event)
1265 case EVENT_RELOAD:
1266 #ifdef HAVE_DNSSEC
1267 if (option_bool(OPT_DNSSEC_VALID) && option_bool(OPT_DNSSEC_TIME))
1269 my_syslog(LOG_INFO, _("now checking DNSSEC signature timestamps"));
1270 reset_option_bool(OPT_DNSSEC_TIME);
1272 #endif
1273 /* fall through */
1275 case EVENT_INIT:
1276 clear_cache_and_reload(now);
1278 if (daemon->port != 0)
1280 if (daemon->resolv_files && option_bool(OPT_NO_POLL))
1282 reload_servers(daemon->resolv_files->name);
1283 check = 1;
1286 if (daemon->servers_file)
1288 read_servers_file();
1289 check = 1;
1292 if (check)
1293 check_servers();
1296 #ifdef HAVE_DHCP
1297 rerun_scripts();
1298 #endif
1299 break;
1301 case EVENT_DUMP:
1302 if (daemon->port != 0)
1303 dump_cache(now);
1304 break;
1306 case EVENT_ALARM:
1307 #ifdef HAVE_DHCP
1308 if (daemon->dhcp || daemon->doing_dhcp6)
1310 lease_prune(NULL, now);
1311 lease_update_file(now);
1313 #ifdef HAVE_DHCP6
1314 else if (daemon->doing_ra)
1315 /* Not doing DHCP, so no lease system, manage alarms for ra only */
1316 send_alarm(periodic_ra(now), now);
1317 #endif
1318 #endif
1319 break;
1321 case EVENT_CHILD:
1322 /* See Stevens 5.10 */
1323 while ((p = waitpid(-1, NULL, WNOHANG)) != 0)
1324 if (p == -1)
1326 if (errno != EINTR)
1327 break;
1329 else
1330 for (i = 0 ; i < MAX_PROCS; i++)
1331 if (daemon->tcp_pids[i] == p)
1332 daemon->tcp_pids[i] = 0;
1333 break;
1335 case EVENT_KILLED:
1336 my_syslog(LOG_WARNING, _("script process killed by signal %d"), ev.data);
1337 break;
1339 case EVENT_EXITED:
1340 my_syslog(LOG_WARNING, _("script process exited with status %d"), ev.data);
1341 break;
1343 case EVENT_EXEC_ERR:
1344 my_syslog(LOG_ERR, _("failed to execute %s: %s"),
1345 daemon->lease_change_command, strerror(ev.data));
1346 break;
1348 /* necessary for fatal errors in helper */
1349 case EVENT_USER_ERR:
1350 case EVENT_DIE:
1351 case EVENT_LUA_ERR:
1352 fatal_event(&ev, msg);
1353 break;
1355 case EVENT_REOPEN:
1356 /* Note: this may leave TCP-handling processes with the old file still open.
1357 Since any such process will die in CHILD_LIFETIME or probably much sooner,
1358 we leave them logging to the old file. */
1360 if (daemon->log_file != NULL)
1361 log_reopen(daemon->log_file);
1363 #ifdef HAVE_TOMATO
1364 tomato_helper(now); //possibly delete & write out leases for tomato
1365 #endif //TOMATO
1366 /* following is Asus tweak. Interestingly Asus read the dnsmasq leases db
1367 directly. They signal dnsmasq to update via SIGUSR2 and wait 1 second
1368 assuming the file will be complete by the time they come to parse it.
1369 Race conditions anyone? What if dnsmasq happens to be updating the
1370 file anyway? */
1371 #if defined(HAVE_DHCP) && defined(HAVE_LEASEFILE_EXPIRE) && !defined(HAVE_TOMATO)
1372 if (daemon->dhcp || daemon->dhcp6)
1373 flush_lease_file(now);
1374 #endif
1375 break;
1377 case EVENT_NEWADDR:
1378 newaddress(now);
1379 break;
1381 case EVENT_NEWROUTE:
1382 resend_query();
1383 /* Force re-reading resolv file right now, for luck. */
1384 poll_resolv(0, 1, now);
1385 break;
1387 case EVENT_TERM:
1388 /* Knock all our children on the head. */
1389 for (i = 0; i < MAX_PROCS; i++)
1390 if (daemon->tcp_pids[i] != 0)
1391 kill(daemon->tcp_pids[i], SIGALRM);
1393 #if defined(HAVE_SCRIPT) && defined(HAVE_DHCP)
1394 /* handle pending lease transitions */
1395 if (daemon->helperfd != -1)
1397 /* block in writes until all done */
1398 if ((i = fcntl(daemon->helperfd, F_GETFL)) != -1)
1399 fcntl(daemon->helperfd, F_SETFL, i & ~O_NONBLOCK);
1400 do {
1401 helper_write();
1402 } while (!helper_buf_empty() || do_script_run(now));
1403 while (retry_send(close(daemon->helperfd)));
1405 #endif
1407 //Originally TOMATO tweak
1408 #if defined(HAVE_DHCP) && defined(HAVE_LEASEFILE_EXPIRE)
1409 if (daemon->dhcp || daemon->dhcp6)
1410 flush_lease_file(now);
1411 #endif
1413 if (daemon->lease_stream)
1414 fclose(daemon->lease_stream);
1416 #ifdef HAVE_DNSSEC
1417 /* update timestamp file on TERM if time is considered valid */
1418 if (daemon->back_to_the_future)
1420 if (utime(daemon->timestamp_file, NULL) == -1)
1421 my_syslog(LOG_ERR, _("failed to update mtime on %s: %s"), daemon->timestamp_file, strerror(errno));
1423 #endif
1425 if (daemon->runfile)
1426 unlink(daemon->runfile);
1428 my_syslog(LOG_INFO, _("exiting on receipt of SIGTERM"));
1429 flush_log();
1430 exit(EC_GOOD);
1434 static void poll_resolv(int force, int do_reload, time_t now)
1436 struct resolvc *res, *latest;
1437 struct stat statbuf;
1438 time_t last_change = 0;
1439 /* There may be more than one possible file.
1440 Go through and find the one which changed _last_.
1441 Warn of any which can't be read. */
1443 if (daemon->port == 0 || option_bool(OPT_NO_POLL))
1444 return;
1446 for (latest = NULL, res = daemon->resolv_files; res; res = res->next)
1447 if (stat(res->name, &statbuf) == -1)
1449 if (force)
1451 res->mtime = 0;
1452 continue;
1455 if (!res->logged)
1456 my_syslog(LOG_WARNING, _("failed to access %s: %s"), res->name, strerror(errno));
1457 res->logged = 1;
1459 if (res->mtime != 0)
1461 /* existing file evaporated, force selection of the latest
1462 file even if its mtime hasn't changed since we last looked */
1463 poll_resolv(1, do_reload, now);
1464 return;
1467 else
1469 res->logged = 0;
1470 if (force || (statbuf.st_mtime != res->mtime))
1472 res->mtime = statbuf.st_mtime;
1473 if (difftime(statbuf.st_mtime, last_change) > 0.0)
1475 last_change = statbuf.st_mtime;
1476 latest = res;
1481 if (latest)
1483 static int warned = 0;
1484 if (reload_servers(latest->name))
1486 my_syslog(LOG_INFO, _("reading %s"), latest->name);
1487 warned = 0;
1488 check_servers();
1489 if (option_bool(OPT_RELOAD) && do_reload)
1490 clear_cache_and_reload(now);
1492 else
1494 latest->mtime = 0;
1495 if (!warned)
1497 my_syslog(LOG_WARNING, _("no servers found in %s, will retry"), latest->name);
1498 warned = 1;
1504 void clear_cache_and_reload(time_t now)
1506 (void)now;
1508 if (daemon->port != 0)
1509 cache_reload();
1511 #ifdef HAVE_DHCP
1512 if (daemon->dhcp || daemon->doing_dhcp6)
1514 if (option_bool(OPT_ETHERS))
1515 dhcp_read_ethers();
1516 reread_dhcp();
1517 #ifdef HAVE_INOTIFY
1518 set_dynamic_inotify(AH_DHCP_HST | AH_DHCP_OPT, 0, NULL, 0);
1519 #endif
1520 dhcp_update_configs(daemon->dhcp_conf);
1521 lease_update_from_configs();
1522 lease_update_file(now);
1523 lease_update_dns(1);
1525 #ifdef HAVE_DHCP6
1526 else if (daemon->doing_ra)
1527 /* Not doing DHCP, so no lease system, manage
1528 alarms for ra only */
1529 send_alarm(periodic_ra(now), now);
1530 #endif
1531 #endif
1534 static int set_dns_listeners(time_t now)
1536 struct serverfd *serverfdp;
1537 struct listener *listener;
1538 int wait = 0, i;
1540 #ifdef HAVE_TFTP
1541 int tftp = 0;
1542 struct tftp_transfer *transfer;
1543 for (transfer = daemon->tftp_trans; transfer; transfer = transfer->next)
1545 tftp++;
1546 poll_listen(transfer->sockfd, POLLIN);
1548 #endif
1550 /* will we be able to get memory? */
1551 if (daemon->port != 0)
1552 get_new_frec(now, &wait, 0);
1554 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1555 poll_listen(serverfdp->fd, POLLIN);
1557 if (daemon->port != 0 && !daemon->osport)
1558 for (i = 0; i < RANDOM_SOCKS; i++)
1559 if (daemon->randomsocks[i].refcount != 0)
1560 poll_listen(daemon->randomsocks[i].fd, POLLIN);
1562 for (listener = daemon->listeners; listener; listener = listener->next)
1564 /* only listen for queries if we have resources */
1565 if (listener->fd != -1 && wait == 0)
1566 poll_listen(listener->fd, POLLIN);
1568 /* death of a child goes through the select loop, so
1569 we don't need to explicitly arrange to wake up here */
1570 if (listener->tcpfd != -1)
1571 for (i = 0; i < MAX_PROCS; i++)
1572 if (daemon->tcp_pids[i] == 0)
1574 poll_listen(listener->tcpfd, POLLIN);
1575 break;
1578 #ifdef HAVE_TFTP
1579 if (tftp <= daemon->tftp_max && listener->tftpfd != -1)
1580 poll_listen(listener->tftpfd, POLLIN);
1581 #endif
1585 return wait;
1588 static void check_dns_listeners(time_t now)
1590 struct serverfd *serverfdp;
1591 struct listener *listener;
1592 int i;
1594 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1595 if (poll_check(serverfdp->fd, POLLIN))
1596 reply_query(serverfdp->fd, serverfdp->source_addr.sa.sa_family, now);
1598 if (daemon->port != 0 && !daemon->osport)
1599 for (i = 0; i < RANDOM_SOCKS; i++)
1600 if (daemon->randomsocks[i].refcount != 0 &&
1601 poll_check(daemon->randomsocks[i].fd, POLLIN))
1602 reply_query(daemon->randomsocks[i].fd, daemon->randomsocks[i].family, now);
1604 for (listener = daemon->listeners; listener; listener = listener->next)
1606 if (listener->fd != -1 && poll_check(listener->fd, POLLIN))
1607 receive_query(listener, now);
1609 #ifdef HAVE_TFTP
1610 if (listener->tftpfd != -1 && poll_check(listener->tftpfd, POLLIN))
1611 tftp_request(listener, now);
1612 #endif
1614 if (listener->tcpfd != -1 && poll_check(listener->tcpfd, POLLIN))
1616 int confd, client_ok = 1;
1617 struct irec *iface = NULL;
1618 pid_t p;
1619 union mysockaddr tcp_addr;
1620 socklen_t tcp_len = sizeof(union mysockaddr);
1622 while ((confd = accept(listener->tcpfd, NULL, NULL)) == -1 && errno == EINTR);
1624 if (confd == -1)
1625 continue;
1627 if (getsockname(confd, (struct sockaddr *)&tcp_addr, &tcp_len) == -1)
1629 while (retry_send(close(confd)));
1630 continue;
1633 /* Make sure that the interface list is up-to-date.
1635 We do this here as we may need the results below, and
1636 the DNS code needs them for --interface-name stuff.
1638 Multiple calls to enumerate_interfaces() per select loop are
1639 inhibited, so calls to it in the child process (which doesn't select())
1640 have no effect. This avoids two processes reading from the same
1641 netlink fd and screwing the pooch entirely.
1644 enumerate_interfaces(0);
1646 if (option_bool(OPT_NOWILD))
1647 iface = listener->iface; /* May be NULL */
1648 else
1650 int if_index;
1651 char intr_name[IF_NAMESIZE];
1653 /* if we can find the arrival interface, check it's one that's allowed */
1654 if ((if_index = tcp_interface(confd, tcp_addr.sa.sa_family)) != 0 &&
1655 indextoname(listener->tcpfd, if_index, intr_name))
1657 struct all_addr addr;
1658 addr.addr.addr4 = tcp_addr.in.sin_addr;
1659 #ifdef HAVE_IPV6
1660 if (tcp_addr.sa.sa_family == AF_INET6)
1661 addr.addr.addr6 = tcp_addr.in6.sin6_addr;
1662 #endif
1664 for (iface = daemon->interfaces; iface; iface = iface->next)
1665 if (iface->index == if_index)
1666 break;
1668 if (!iface && !loopback_exception(listener->tcpfd, tcp_addr.sa.sa_family, &addr, intr_name))
1669 client_ok = 0;
1672 if (option_bool(OPT_CLEVERBIND))
1673 iface = listener->iface; /* May be NULL */
1674 else
1676 /* Check for allowed interfaces when binding the wildcard address:
1677 we do this by looking for an interface with the same address as
1678 the local address of the TCP connection, then looking to see if that's
1679 an allowed interface. As a side effect, we get the netmask of the
1680 interface too, for localisation. */
1682 for (iface = daemon->interfaces; iface; iface = iface->next)
1683 if (sockaddr_isequal(&iface->addr, &tcp_addr))
1684 break;
1686 if (!iface)
1687 client_ok = 0;
1691 if (!client_ok)
1693 shutdown(confd, SHUT_RDWR);
1694 while (retry_send(close(confd)));
1696 #ifndef NO_FORK
1697 else if (!option_bool(OPT_DEBUG) && (p = fork()) != 0)
1699 if (p != -1)
1701 int i;
1702 for (i = 0; i < MAX_PROCS; i++)
1703 if (daemon->tcp_pids[i] == 0)
1705 daemon->tcp_pids[i] = p;
1706 break;
1709 while (retry_send(close(confd)));
1711 /* The child can use up to TCP_MAX_QUERIES ids, so skip that many. */
1712 daemon->log_id += TCP_MAX_QUERIES;
1714 #endif
1715 else
1717 unsigned char *buff;
1718 struct server *s;
1719 int flags;
1720 struct in_addr netmask;
1721 int auth_dns;
1723 if (iface)
1725 netmask = iface->netmask;
1726 auth_dns = iface->dns_auth;
1728 else
1730 netmask.s_addr = 0;
1731 auth_dns = 0;
1734 #ifndef NO_FORK
1735 /* Arrange for SIGALARM after CHILD_LIFETIME seconds to
1736 terminate the process. */
1737 if (!option_bool(OPT_DEBUG))
1738 alarm(CHILD_LIFETIME);
1739 #endif
1741 /* start with no upstream connections. */
1742 for (s = daemon->servers; s; s = s->next)
1743 s->tcpfd = -1;
1745 /* The connected socket inherits non-blocking
1746 attribute from the listening socket.
1747 Reset that here. */
1748 if ((flags = fcntl(confd, F_GETFL, 0)) != -1)
1749 fcntl(confd, F_SETFL, flags & ~O_NONBLOCK);
1751 buff = tcp_request(confd, now, &tcp_addr, netmask, auth_dns);
1753 shutdown(confd, SHUT_RDWR);
1754 while (retry_send(close(confd)));
1756 if (buff)
1757 free(buff);
1759 for (s = daemon->servers; s; s = s->next)
1760 if (s->tcpfd != -1)
1762 shutdown(s->tcpfd, SHUT_RDWR);
1763 while (retry_send(close(s->tcpfd)));
1765 #ifndef NO_FORK
1766 if (!option_bool(OPT_DEBUG))
1768 flush_log();
1769 _exit(0);
1771 #endif
1777 #ifdef HAVE_DHCP
1778 int make_icmp_sock(void)
1780 int fd;
1781 int zeroopt = 0;
1783 if ((fd = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
1785 if (!fix_fd(fd) ||
1786 setsockopt(fd, SOL_SOCKET, SO_DONTROUTE, &zeroopt, sizeof(zeroopt)) == -1)
1788 close(fd);
1789 fd = -1;
1793 return fd;
1796 int icmp_ping(struct in_addr addr)
1798 /* Try and get an ICMP echo from a machine. */
1800 /* Note that whilst in the three second wait, we check for
1801 (and service) events on the DNS and TFTP sockets, (so doing that
1802 better not use any resources our caller has in use...)
1803 but we remain deaf to signals or further DHCP packets. */
1805 /* There can be a problem using dnsmasq_time() to end the loop, since
1806 it's not monotonic, and can go backwards if the system clock is
1807 tweaked, leading to the code getting stuck in this loop and
1808 ignoring DHCP requests. To fix this, we check to see if select returned
1809 as a result of a timeout rather than a socket becoming available. We
1810 only allow this to happen as many times as it takes to get to the wait time
1811 in quarter-second chunks. This provides a fallback way to end loop. */
1813 int fd, rc;
1814 struct sockaddr_in saddr;
1815 struct {
1816 struct ip ip;
1817 struct icmp icmp;
1818 } packet;
1819 unsigned short id = rand16();
1820 unsigned int i, j, timeout_count;
1821 int gotreply = 0;
1822 time_t start, now;
1824 #if defined(HAVE_LINUX_NETWORK) || defined (HAVE_SOLARIS_NETWORK)
1825 if ((fd = make_icmp_sock()) == -1)
1826 return 0;
1827 #else
1828 int opt = 2000;
1829 fd = daemon->dhcp_icmp_fd;
1830 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1831 #endif
1833 saddr.sin_family = AF_INET;
1834 saddr.sin_port = 0;
1835 saddr.sin_addr = addr;
1836 #ifdef HAVE_SOCKADDR_SA_LEN
1837 saddr.sin_len = sizeof(struct sockaddr_in);
1838 #endif
1840 memset(&packet.icmp, 0, sizeof(packet.icmp));
1841 packet.icmp.icmp_type = ICMP_ECHO;
1842 packet.icmp.icmp_id = id;
1843 for (j = 0, i = 0; i < sizeof(struct icmp) / 2; i++)
1844 j += ((u16 *)&packet.icmp)[i];
1845 while (j>>16)
1846 j = (j & 0xffff) + (j >> 16);
1847 packet.icmp.icmp_cksum = (j == 0xffff) ? j : ~j;
1849 while (retry_send(sendto(fd, (char *)&packet.icmp, sizeof(struct icmp), 0,
1850 (struct sockaddr *)&saddr, sizeof(saddr))));
1852 for (now = start = dnsmasq_time(), timeout_count = 0;
1853 (difftime(now, start) < (float)PING_WAIT) && (timeout_count < PING_WAIT * 4);)
1855 struct sockaddr_in faddr;
1856 socklen_t len = sizeof(faddr);
1858 poll_reset();
1859 poll_listen(fd, POLLIN);
1860 set_dns_listeners(now);
1861 set_log_writer();
1863 #ifdef HAVE_DHCP6
1864 if (daemon->doing_ra)
1865 poll_listen(daemon->icmp6fd, POLLIN);
1866 #endif
1868 rc = do_poll(250);
1870 if (rc < 0)
1871 continue;
1872 else if (rc == 0)
1873 timeout_count++;
1875 now = dnsmasq_time();
1877 check_log_writer(0);
1878 check_dns_listeners(now);
1880 #ifdef HAVE_DHCP6
1881 if (daemon->doing_ra && poll_check(daemon->icmp6fd, POLLIN))
1882 icmp6_packet(now);
1883 #endif
1885 #ifdef HAVE_TFTP
1886 check_tftp_listeners(now);
1887 #endif
1889 if (poll_check(fd, POLLIN) &&
1890 recvfrom(fd, &packet, sizeof(packet), 0,
1891 (struct sockaddr *)&faddr, &len) == sizeof(packet) &&
1892 saddr.sin_addr.s_addr == faddr.sin_addr.s_addr &&
1893 packet.icmp.icmp_type == ICMP_ECHOREPLY &&
1894 packet.icmp.icmp_seq == 0 &&
1895 packet.icmp.icmp_id == id)
1897 gotreply = 1;
1898 break;
1902 #if defined(HAVE_LINUX_NETWORK) || defined(HAVE_SOLARIS_NETWORK)
1903 while (retry_send(close(fd)));
1904 #else
1905 opt = 1;
1906 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1907 #endif
1909 return gotreply;
1911 #endif