dnsmasq 2.72+ up to December 9 2014
[tomato.git] / release / src / router / dnsmasq / src / dnsmasq.c
blob4c909d6458389ac0ff7641871e03bedf73fcc07e
1 /* dnsmasq is Copyright (c) 2000-2014 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
100 #ifdef LOCALEDIR
101 setlocale(LC_ALL, "");
102 bindtextdomain("dnsmasq", LOCALEDIR);
103 textdomain("dnsmasq");
104 #endif
106 sigact.sa_handler = sig_handler;
107 sigact.sa_flags = 0;
108 sigemptyset(&sigact.sa_mask);
109 sigaction(SIGUSR1, &sigact, NULL);
110 sigaction(SIGUSR2, &sigact, NULL);
111 sigaction(SIGHUP, &sigact, NULL);
112 sigaction(SIGTERM, &sigact, NULL);
113 sigaction(SIGALRM, &sigact, NULL);
114 sigaction(SIGCHLD, &sigact, NULL);
116 /* ignore SIGPIPE */
117 sigact.sa_handler = SIG_IGN;
118 sigaction(SIGPIPE, &sigact, NULL);
120 umask(022); /* known umask, create leases and pid files as 0644 */
122 rand_init(); /* Must precede read_opts() */
124 read_opts(argc, argv, compile_opts);
126 if (daemon->edns_pktsz < PACKETSZ)
127 daemon->edns_pktsz = PACKETSZ;
128 #ifdef HAVE_DNSSEC
129 /* Enforce min packet big enough for DNSSEC */
130 if (option_bool(OPT_DNSSEC_VALID) && daemon->edns_pktsz < EDNS_PKTSZ)
131 daemon->edns_pktsz = EDNS_PKTSZ;
132 #endif
134 daemon->packet_buff_sz = daemon->edns_pktsz > DNSMASQ_PACKETSZ ?
135 daemon->edns_pktsz : DNSMASQ_PACKETSZ;
136 daemon->packet = safe_malloc(daemon->packet_buff_sz);
138 daemon->addrbuff = safe_malloc(ADDRSTRLEN);
140 #ifdef HAVE_DNSSEC
141 if (option_bool(OPT_DNSSEC_VALID))
143 daemon->keyname = safe_malloc(MAXDNAME);
144 daemon->workspacename = safe_malloc(MAXDNAME);
146 #endif
148 #ifdef HAVE_DHCP
149 if (!daemon->lease_file)
151 if (daemon->dhcp || daemon->dhcp6)
152 daemon->lease_file = LEASEFILE;
154 #endif
156 /* Close any file descriptors we inherited apart from std{in|out|err}
158 Ensure that at least stdin, stdout and stderr (fd 0, 1, 2) exist,
159 otherwise file descriptors we create can end up being 0, 1, or 2
160 and then get accidentally closed later when we make 0, 1, and 2
161 open to /dev/null. Normally we'll be started with 0, 1 and 2 open,
162 but it's not guaranteed. By opening /dev/null three times, we
163 ensure that we're not using those fds for real stuff. */
164 for (i = 0; i < max_fd; i++)
165 if (i != STDOUT_FILENO && i != STDERR_FILENO && i != STDIN_FILENO)
166 close(i);
167 else
168 open("/dev/null", O_RDWR);
170 #ifndef HAVE_LINUX_NETWORK
171 # if !(defined(IP_RECVDSTADDR) && defined(IP_RECVIF) && defined(IP_SENDSRCADDR))
172 if (!option_bool(OPT_NOWILD))
174 bind_fallback = 1;
175 set_option_bool(OPT_NOWILD);
177 # endif
179 /* -- bind-dynamic not supported on !Linux, fall back to --bind-interfaces */
180 if (option_bool(OPT_CLEVERBIND))
182 bind_fallback = 1;
183 set_option_bool(OPT_NOWILD);
184 reset_option_bool(OPT_CLEVERBIND);
186 #endif
188 if (option_bool(OPT_DNSSEC_VALID))
190 #ifdef HAVE_DNSSEC
191 if (!daemon->ds)
192 die(_("No trust anchors provided for DNSSEC"), NULL, EC_BADCONF);
194 if (daemon->cachesize < CACHESIZ)
195 die(_("Cannot reduce cache size from default when DNSSEC enabled"), NULL, EC_BADCONF);
196 #else
197 die(_("DNSSEC not available: set HAVE_DNSSEC in src/config.h"), NULL, EC_BADCONF);
198 #endif
201 #ifndef HAVE_TFTP
202 if (option_bool(OPT_TFTP))
203 die(_("TFTP server not available: set HAVE_TFTP in src/config.h"), NULL, EC_BADCONF);
204 #endif
206 #ifdef HAVE_CONNTRACK
207 if (option_bool(OPT_CONNTRACK) && (daemon->query_port != 0 || daemon->osport))
208 die (_("Cannot use --conntrack AND --query-port"), NULL, EC_BADCONF);
209 #else
210 if (option_bool(OPT_CONNTRACK))
211 die(_("Conntrack support not available: set HAVE_CONNTRACK in src/config.h"), NULL, EC_BADCONF);
212 #endif
214 #ifdef HAVE_SOLARIS_NETWORK
215 if (daemon->max_logs != 0)
216 die(_("asychronous logging is not available under Solaris"), NULL, EC_BADCONF);
217 #endif
219 #ifdef __ANDROID__
220 if (daemon->max_logs != 0)
221 die(_("asychronous logging is not available under Android"), NULL, EC_BADCONF);
222 #endif
224 #ifndef HAVE_AUTH
225 if (daemon->authserver)
226 die(_("authoritative DNS not available: set HAVE_AUTH in src/config.h"), NULL, EC_BADCONF);
227 #endif
229 #ifndef HAVE_LOOP
230 if (option_bool(OPT_LOOP_DETECT))
231 die(_("Loop detection not available: set HAVE_LOOP in src/config.h"), NULL, EC_BADCONF);
232 #endif
234 now = dnsmasq_time();
236 /* Create a serial at startup if not configured. */
237 if (daemon->authinterface && daemon->soa_sn == 0)
238 #ifdef HAVE_BROKEN_RTC
239 die(_("zone serial must be configured in --auth-soa"), NULL, EC_BADCONF);
240 #else
241 daemon->soa_sn = now;
242 #endif
244 #ifdef HAVE_DHCP6
245 if (daemon->dhcp6)
247 daemon->doing_ra = option_bool(OPT_RA);
249 for (context = daemon->dhcp6; context; context = context->next)
251 if (context->flags & CONTEXT_DHCP)
252 daemon->doing_dhcp6 = 1;
253 if (context->flags & CONTEXT_RA)
254 daemon->doing_ra = 1;
255 #if !defined(HAVE_LINUX_NETWORK) && !defined(HAVE_BSD_NETWORK)
256 if (context->flags & CONTEXT_TEMPLATE)
257 die (_("dhcp-range constructor not available on this platform"), NULL, EC_BADCONF);
258 #endif
261 #endif
263 #ifdef HAVE_DHCP
264 /* Note that order matters here, we must call lease_init before
265 creating any file descriptors which shouldn't be leaked
266 to the lease-script init process. We need to call common_init
267 before lease_init to allocate buffers it uses.*/
268 if (daemon->dhcp || daemon->doing_dhcp6 || daemon->relay4 || daemon->relay6)
270 dhcp_common_init();
271 if (daemon->dhcp || daemon->doing_dhcp6)
272 lease_init(now);
275 if (daemon->dhcp || daemon->relay4)
276 dhcp_init();
278 # ifdef HAVE_DHCP6
279 if (daemon->doing_ra || daemon->doing_dhcp6 || daemon->relay6)
280 ra_init(now);
282 if (daemon->doing_dhcp6 || daemon->relay6)
283 dhcp6_init();
284 # endif
286 #endif
288 #ifdef HAVE_IPSET
289 if (daemon->ipsets)
290 ipset_init();
291 #endif
293 #if defined(HAVE_LINUX_NETWORK)
294 netlink_init();
295 #elif defined(HAVE_BSD_NETWORK)
296 route_init();
297 #endif
299 if (option_bool(OPT_NOWILD) && option_bool(OPT_CLEVERBIND))
300 die(_("cannot set --bind-interfaces and --bind-dynamic"), NULL, EC_BADCONF);
302 if (!enumerate_interfaces(1) || !enumerate_interfaces(0))
303 die(_("failed to find list of interfaces: %s"), NULL, EC_MISC);
305 if (option_bool(OPT_NOWILD) || option_bool(OPT_CLEVERBIND))
307 create_bound_listeners(1);
309 if (!option_bool(OPT_CLEVERBIND))
310 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
311 if (if_tmp->name && !if_tmp->used)
312 die(_("unknown interface %s"), if_tmp->name, EC_BADNET);
314 #if defined(HAVE_LINUX_NETWORK) && defined(HAVE_DHCP)
315 /* after enumerate_interfaces() */
316 bound_device = whichdevice();
318 if (daemon->dhcp)
320 if (!daemon->relay4 && bound_device)
322 bindtodevice(bound_device, daemon->dhcpfd);
323 did_bind = 1;
325 if (daemon->enable_pxe && bound_device)
327 bindtodevice(bound_device, daemon->pxefd);
328 did_bind = 1;
331 #endif
333 #if defined(HAVE_LINUX_NETWORK) && defined(HAVE_DHCP6)
334 if (daemon->doing_dhcp6 && !daemon->relay6 && bound_device)
336 bindtodevice(bound_device, daemon->dhcp6fd);
337 did_bind = 1;
339 #endif
341 else
342 create_wildcard_listeners();
344 #ifdef HAVE_DHCP6
345 /* after enumerate_interfaces() */
346 if (daemon->doing_dhcp6 || daemon->relay6 || daemon->doing_ra)
347 join_multicast(1);
349 /* After netlink_init() and before create_helper() */
350 lease_make_duid(now);
351 #endif
353 if (daemon->port != 0)
355 cache_init();
356 #ifdef HAVE_DNSSEC
357 blockdata_init();
358 #endif
361 if (option_bool(OPT_DBUS))
362 #ifdef HAVE_DBUS
364 char *err;
365 daemon->dbus = NULL;
366 daemon->watches = NULL;
367 if ((err = dbus_init()))
368 die(_("DBus error: %s"), err, EC_MISC);
370 #else
371 die(_("DBus not available: set HAVE_DBUS in src/config.h"), NULL, EC_BADCONF);
372 #endif
374 if (daemon->port != 0)
375 pre_allocate_sfds();
377 #if defined(HAVE_SCRIPT)
378 /* Note getpwnam returns static storage */
379 if ((daemon->dhcp || daemon->dhcp6) &&
380 daemon->scriptuser &&
381 (daemon->lease_change_command || daemon->luascript))
383 if ((ent_pw = getpwnam(daemon->scriptuser)))
385 script_uid = ent_pw->pw_uid;
386 script_gid = ent_pw->pw_gid;
388 else
389 baduser = daemon->scriptuser;
391 #endif
393 if (daemon->username && !(ent_pw = getpwnam(daemon->username)))
394 baduser = daemon->username;
395 else if (daemon->groupname && !(gp = getgrnam(daemon->groupname)))
396 baduser = daemon->groupname;
398 if (baduser)
399 die(_("unknown user or group: %s"), baduser, EC_BADCONF);
401 /* implement group defaults, "dip" if available, or group associated with uid */
402 if (!daemon->group_set && !gp)
404 if (!(gp = getgrnam(CHGRP)) && ent_pw)
405 gp = getgrgid(ent_pw->pw_gid);
407 /* for error message */
408 if (gp)
409 daemon->groupname = gp->gr_name;
412 #if defined(HAVE_LINUX_NETWORK)
413 /* determine capability API version here, while we can still
414 call safe_malloc */
415 if (ent_pw && ent_pw->pw_uid != 0)
417 int capsize = 1; /* for header version 1 */
418 hdr = safe_malloc(sizeof(*hdr));
420 /* find version supported by kernel */
421 memset(hdr, 0, sizeof(*hdr));
422 capget(hdr, NULL);
424 if (hdr->version != LINUX_CAPABILITY_VERSION_1)
426 /* if unknown version, use largest supported version (3) */
427 if (hdr->version != LINUX_CAPABILITY_VERSION_2)
428 hdr->version = LINUX_CAPABILITY_VERSION_3;
429 capsize = 2;
432 data = safe_malloc(sizeof(*data) * capsize);
433 memset(data, 0, sizeof(*data) * capsize);
435 #endif
437 /* Use a pipe to carry signals and other events back to the event loop
438 in a race-free manner and another to carry errors to daemon-invoking process */
439 safe_pipe(pipefd, 1);
441 piperead = pipefd[0];
442 pipewrite = pipefd[1];
443 /* prime the pipe to load stuff first time. */
444 send_event(pipewrite, EVENT_INIT, 0, NULL);
446 err_pipe[1] = -1;
448 if (!option_bool(OPT_DEBUG))
450 /* The following code "daemonizes" the process.
451 See Stevens section 12.4 */
453 if (chdir("/") != 0)
454 die(_("cannot chdir to filesystem root: %s"), NULL, EC_MISC);
456 #ifndef NO_FORK
457 if (!option_bool(OPT_NO_FORK))
459 pid_t pid;
461 /* pipe to carry errors back to original process.
462 When startup is complete we close this and the process terminates. */
463 safe_pipe(err_pipe, 0);
465 if ((pid = fork()) == -1)
466 /* fd == -1 since we've not forked, never returns. */
467 send_event(-1, EVENT_FORK_ERR, errno, NULL);
469 if (pid != 0)
471 struct event_desc ev;
472 char *msg;
474 /* close our copy of write-end */
475 close(err_pipe[1]);
477 /* check for errors after the fork */
478 if (read_event(err_pipe[0], &ev, &msg))
479 fatal_event(&ev, msg);
481 _exit(EC_GOOD);
484 close(err_pipe[0]);
486 /* NO calls to die() from here on. */
488 setsid();
490 if ((pid = fork()) == -1)
491 send_event(err_pipe[1], EVENT_FORK_ERR, errno, NULL);
493 if (pid != 0)
494 _exit(0);
496 #endif
498 /* write pidfile _after_ forking ! */
499 if (daemon->runfile)
501 int fd, err = 0;
503 sprintf(daemon->namebuff, "%d\n", (int) getpid());
505 /* Explanation: Some installations of dnsmasq (eg Debian/Ubuntu) locate the pid-file
506 in a directory which is writable by the non-privileged user that dnsmasq runs as. This
507 allows the daemon to delete the file as part of its shutdown. This is a security hole to the
508 extent that an attacker running as the unprivileged user could replace the pidfile with a
509 symlink, and have the target of that symlink overwritten as root next time dnsmasq starts.
511 The folowing code first deletes any existing file, and then opens it with the O_EXCL flag,
512 ensuring that the open() fails should there be any existing file (because the unlink() failed,
513 or an attacker exploited the race between unlink() and open()). This ensures that no symlink
514 attack can succeed.
516 Any compromise of the non-privileged user still theoretically allows the pid-file to be
517 replaced whilst dnsmasq is running. The worst that could allow is that the usual
518 "shutdown dnsmasq" shell command could be tricked into stopping any other process.
520 Note that if dnsmasq is started as non-root (eg for testing) it silently ignores
521 failure to write the pid-file.
524 unlink(daemon->runfile);
526 if ((fd = open(daemon->runfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH)) == -1)
528 /* only complain if started as root */
529 if (getuid() == 0)
530 err = 1;
532 else
534 if (!read_write(fd, (unsigned char *)daemon->namebuff, strlen(daemon->namebuff), 0))
535 err = 1;
537 while (!err && close(fd) == -1)
538 if (!retry_send())
539 err = 1;
542 if (err)
544 send_event(err_pipe[1], EVENT_PIDFILE, errno, daemon->runfile);
545 _exit(0);
550 log_err = log_start(ent_pw, err_pipe[1]);
552 if (!option_bool(OPT_DEBUG))
554 /* open stdout etc to /dev/null */
555 int nullfd = open("/dev/null", O_RDWR);
556 dup2(nullfd, STDOUT_FILENO);
557 dup2(nullfd, STDERR_FILENO);
558 dup2(nullfd, STDIN_FILENO);
559 close(nullfd);
562 /* if we are to run scripts, we need to fork a helper before dropping root. */
563 daemon->helperfd = -1;
564 #ifdef HAVE_SCRIPT
565 if ((daemon->dhcp || daemon->dhcp6) && (daemon->lease_change_command || daemon->luascript))
566 daemon->helperfd = create_helper(pipewrite, err_pipe[1], script_uid, script_gid, max_fd);
567 #endif
569 if (!option_bool(OPT_DEBUG) && getuid() == 0)
571 int bad_capabilities = 0;
572 gid_t dummy;
574 /* remove all supplimentary groups */
575 if (gp &&
576 (setgroups(0, &dummy) == -1 ||
577 setgid(gp->gr_gid) == -1))
579 send_event(err_pipe[1], EVENT_GROUP_ERR, errno, daemon->groupname);
580 _exit(0);
583 if (ent_pw && ent_pw->pw_uid != 0)
585 #if defined(HAVE_LINUX_NETWORK)
586 /* On linux, we keep CAP_NETADMIN (for ARP-injection) and
587 CAP_NET_RAW (for icmp) if we're doing dhcp. If we have yet to bind
588 ports because of DAD, or we're doing it dynamically,
589 we need CAP_NET_BIND_SERVICE too. */
590 if (is_dad_listeners() || option_bool(OPT_CLEVERBIND))
591 data->effective = data->permitted = data->inheritable =
592 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) |
593 (1 << CAP_SETUID) | (1 << CAP_NET_BIND_SERVICE);
594 else
595 data->effective = data->permitted = data->inheritable =
596 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID);
598 /* Tell kernel to not clear capabilities when dropping root */
599 if (capset(hdr, data) == -1 || prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1)
600 bad_capabilities = errno;
602 #elif defined(HAVE_SOLARIS_NETWORK)
603 /* http://developers.sun.com/solaris/articles/program_privileges.html */
604 priv_set_t *priv_set;
606 if (!(priv_set = priv_str_to_set("basic", ",", NULL)) ||
607 priv_addset(priv_set, PRIV_NET_ICMPACCESS) == -1 ||
608 priv_addset(priv_set, PRIV_SYS_NET_CONFIG) == -1)
609 bad_capabilities = errno;
611 if (priv_set && bad_capabilities == 0)
613 priv_inverse(priv_set);
615 if (setppriv(PRIV_OFF, PRIV_LIMIT, priv_set) == -1)
616 bad_capabilities = errno;
619 if (priv_set)
620 priv_freeset(priv_set);
622 #endif
624 if (bad_capabilities != 0)
626 send_event(err_pipe[1], EVENT_CAP_ERR, bad_capabilities, NULL);
627 _exit(0);
630 /* finally drop root */
631 if (setuid(ent_pw->pw_uid) == -1)
633 send_event(err_pipe[1], EVENT_USER_ERR, errno, daemon->username);
634 _exit(0);
637 #ifdef HAVE_LINUX_NETWORK
638 if (is_dad_listeners() || option_bool(OPT_CLEVERBIND))
639 data->effective = data->permitted =
640 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_NET_BIND_SERVICE);
641 else
642 data->effective = data->permitted =
643 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW);
644 data->inheritable = 0;
646 /* lose the setuid and setgid capbilities */
647 if (capset(hdr, data) == -1)
649 send_event(err_pipe[1], EVENT_CAP_ERR, errno, NULL);
650 _exit(0);
652 #endif
657 #ifdef HAVE_LINUX_NETWORK
658 if (option_bool(OPT_DEBUG))
659 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
660 #endif
662 #ifdef HAVE_TFTP
663 if (option_bool(OPT_TFTP))
665 DIR *dir;
666 struct tftp_prefix *p;
668 if (daemon->tftp_prefix)
670 if (!((dir = opendir(daemon->tftp_prefix))))
672 send_event(err_pipe[1], EVENT_TFTP_ERR, errno, daemon->tftp_prefix);
673 _exit(0);
675 closedir(dir);
678 for (p = daemon->if_prefix; p; p = p->next)
680 if (!((dir = opendir(p->prefix))))
682 send_event(err_pipe[1], EVENT_TFTP_ERR, errno, p->prefix);
683 _exit(0);
685 closedir(dir);
688 #endif
690 if (daemon->port == 0)
691 my_syslog(LOG_INFO, _("started, version %s DNS disabled"), VERSION);
692 else if (daemon->cachesize != 0)
693 my_syslog(LOG_INFO, _("started, version %s cachesize %d"), VERSION, daemon->cachesize);
694 else
695 my_syslog(LOG_INFO, _("started, version %s cache disabled"), VERSION);
697 my_syslog(LOG_INFO, _("compile time options: %s"), compile_opts);
699 #ifdef HAVE_DBUS
700 if (option_bool(OPT_DBUS))
702 if (daemon->dbus)
703 my_syslog(LOG_INFO, _("DBus support enabled: connected to system bus"));
704 else
705 my_syslog(LOG_INFO, _("DBus support enabled: bus connection pending"));
707 #endif
709 if (option_bool(OPT_LOCAL_SERVICE))
710 my_syslog(LOG_INFO, _("DNS service limited to local subnets"));
712 #ifdef HAVE_DNSSEC
713 if (option_bool(OPT_DNSSEC_VALID))
715 my_syslog(LOG_INFO, _("DNSSEC validation enabled"));
716 if (option_bool(OPT_DNSSEC_TIME))
717 my_syslog(LOG_INFO, _("DNSSEC signature timestamps not checked until first cache reload"));
719 #endif
721 if (log_err != 0)
722 my_syslog(LOG_WARNING, _("warning: failed to change owner of %s: %s"),
723 daemon->log_file, strerror(log_err));
725 if (bind_fallback)
726 my_syslog(LOG_WARNING, _("setting --bind-interfaces option because of OS limitations"));
728 if (option_bool(OPT_NOWILD))
729 warn_bound_listeners();
731 warn_int_names();
733 if (!option_bool(OPT_NOWILD))
734 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
735 if (if_tmp->name && !if_tmp->used)
736 my_syslog(LOG_WARNING, _("warning: interface %s does not currently exist"), if_tmp->name);
738 if (daemon->port != 0 && option_bool(OPT_NO_RESOLV))
740 if (daemon->resolv_files && !daemon->resolv_files->is_default)
741 my_syslog(LOG_WARNING, _("warning: ignoring resolv-file flag because no-resolv is set"));
742 daemon->resolv_files = NULL;
743 if (!daemon->servers)
744 my_syslog(LOG_WARNING, _("warning: no upstream servers configured"));
747 if (daemon->max_logs != 0)
748 my_syslog(LOG_INFO, _("asynchronous logging enabled, queue limit is %d messages"), daemon->max_logs);
751 #ifdef HAVE_DHCP
752 for (context = daemon->dhcp; context; context = context->next)
753 log_context(AF_INET, context);
755 for (relay = daemon->relay4; relay; relay = relay->next)
756 log_relay(AF_INET, relay);
758 # ifdef HAVE_DHCP6
759 for (context = daemon->dhcp6; context; context = context->next)
760 log_context(AF_INET6, context);
762 for (relay = daemon->relay6; relay; relay = relay->next)
763 log_relay(AF_INET6, relay);
765 if (daemon->doing_dhcp6 || daemon->doing_ra)
766 dhcp_construct_contexts(now);
768 if (option_bool(OPT_RA))
769 my_syslog(MS_DHCP | LOG_INFO, _("IPv6 router advertisement enabled"));
770 # endif
772 # ifdef HAVE_LINUX_NETWORK
773 if (did_bind)
774 my_syslog(MS_DHCP | LOG_INFO, _("DHCP, sockets bound exclusively to interface %s"), bound_device);
775 # endif
777 /* after dhcp_contruct_contexts */
778 if (daemon->dhcp || daemon->doing_dhcp6)
779 lease_find_interfaces(now);
780 #endif
782 #ifdef HAVE_TFTP
783 if (option_bool(OPT_TFTP))
785 #ifdef FD_SETSIZE
786 if (FD_SETSIZE < (unsigned)max_fd)
787 max_fd = FD_SETSIZE;
788 #endif
790 my_syslog(MS_TFTP | LOG_INFO, "TFTP %s%s %s",
791 daemon->tftp_prefix ? _("root is ") : _("enabled"),
792 daemon->tftp_prefix ? daemon->tftp_prefix: "",
793 option_bool(OPT_TFTP_SECURE) ? _("secure mode") : "");
795 /* This is a guess, it assumes that for small limits,
796 disjoint files might be served, but for large limits,
797 a single file will be sent to may clients (the file only needs
798 one fd). */
800 max_fd -= 30; /* use other than TFTP */
802 if (max_fd < 0)
803 max_fd = 5;
804 else if (max_fd < 100)
805 max_fd = max_fd/2;
806 else
807 max_fd = max_fd - 20;
809 /* if we have to use a limited range of ports,
810 that will limit the number of transfers */
811 if (daemon->start_tftp_port != 0 &&
812 daemon->end_tftp_port - daemon->start_tftp_port + 1 < max_fd)
813 max_fd = daemon->end_tftp_port - daemon->start_tftp_port + 1;
815 if (daemon->tftp_max > max_fd)
817 daemon->tftp_max = max_fd;
818 my_syslog(MS_TFTP | LOG_WARNING,
819 _("restricting maximum simultaneous TFTP transfers to %d"),
820 daemon->tftp_max);
823 #endif
825 /* finished start-up - release original process */
826 if (err_pipe[1] != -1)
827 close(err_pipe[1]);
829 if (daemon->port != 0)
830 check_servers();
832 pid = getpid();
834 while (1)
836 int maxfd = -1;
837 struct timeval t, *tp = NULL;
838 fd_set rset, wset, eset;
840 FD_ZERO(&rset);
841 FD_ZERO(&wset);
842 FD_ZERO(&eset);
844 /* if we are out of resources, find how long we have to wait
845 for some to come free, we'll loop around then and restart
846 listening for queries */
847 if ((t.tv_sec = set_dns_listeners(now, &rset, &maxfd)) != 0)
849 t.tv_usec = 0;
850 tp = &t;
853 /* Whilst polling for the dbus, or doing a tftp transfer, wake every quarter second */
854 if (daemon->tftp_trans ||
855 (option_bool(OPT_DBUS) && !daemon->dbus))
857 t.tv_sec = 0;
858 t.tv_usec = 250000;
859 tp = &t;
861 /* Wake every second whilst waiting for DAD to complete */
862 else if (is_dad_listeners())
864 t.tv_sec = 1;
865 t.tv_usec = 0;
866 tp = &t;
869 #ifdef HAVE_DBUS
870 set_dbus_listeners(&maxfd, &rset, &wset, &eset);
871 #endif
873 #ifdef HAVE_DHCP
874 if (daemon->dhcp || daemon->relay4)
876 FD_SET(daemon->dhcpfd, &rset);
877 bump_maxfd(daemon->dhcpfd, &maxfd);
878 if (daemon->pxefd != -1)
880 FD_SET(daemon->pxefd, &rset);
881 bump_maxfd(daemon->pxefd, &maxfd);
884 #endif
886 #ifdef HAVE_DHCP6
887 if (daemon->doing_dhcp6 || daemon->relay6)
889 FD_SET(daemon->dhcp6fd, &rset);
890 bump_maxfd(daemon->dhcp6fd, &maxfd);
893 if (daemon->doing_ra)
895 FD_SET(daemon->icmp6fd, &rset);
896 bump_maxfd(daemon->icmp6fd, &maxfd);
898 #endif
900 #if defined(HAVE_LINUX_NETWORK)
901 FD_SET(daemon->netlinkfd, &rset);
902 bump_maxfd(daemon->netlinkfd, &maxfd);
903 #elif defined(HAVE_BSD_NETWORK)
904 FD_SET(daemon->routefd, &rset);
905 bump_maxfd(daemon->routefd, &maxfd);
906 #endif
908 FD_SET(piperead, &rset);
909 bump_maxfd(piperead, &maxfd);
911 #ifdef HAVE_DHCP
912 # ifdef HAVE_SCRIPT
913 while (helper_buf_empty() && do_script_run(now));
915 # ifdef HAVE_TFTP
916 while (helper_buf_empty() && do_tftp_script_run());
917 # endif
919 if (!helper_buf_empty())
921 FD_SET(daemon->helperfd, &wset);
922 bump_maxfd(daemon->helperfd, &maxfd);
924 # else
925 /* need this for other side-effects */
926 while (do_script_run(now));
928 # ifdef HAVE_TFTP
929 while (do_tftp_script_run());
930 # endif
932 # endif
933 #endif
935 /* must do this just before select(), when we know no
936 more calls to my_syslog() can occur */
937 set_log_writer(&wset, &maxfd);
939 if (select(maxfd+1, &rset, &wset, &eset, tp) < 0)
941 /* otherwise undefined after error */
942 FD_ZERO(&rset); FD_ZERO(&wset); FD_ZERO(&eset);
945 now = dnsmasq_time();
947 check_log_writer(&wset);
949 /* prime. */
950 enumerate_interfaces(1);
952 /* Check the interfaces to see if any have exited DAD state
953 and if so, bind the address. */
954 if (is_dad_listeners())
956 enumerate_interfaces(0);
957 /* NB, is_dad_listeners() == 1 --> we're binding interfaces */
958 create_bound_listeners(0);
959 warn_bound_listeners();
962 #if defined(HAVE_LINUX_NETWORK)
963 if (FD_ISSET(daemon->netlinkfd, &rset))
964 netlink_multicast();
965 #elif defined(HAVE_BSD_NETWORK)
966 if (FD_ISSET(daemon->routefd, &rset))
967 route_sock();
968 #endif
970 /* Check for changes to resolv files once per second max. */
971 /* Don't go silent for long periods if the clock goes backwards. */
972 if (daemon->last_resolv == 0 ||
973 difftime(now, daemon->last_resolv) > 1.0 ||
974 difftime(now, daemon->last_resolv) < -1.0)
976 /* poll_resolv doesn't need to reload first time through, since
977 that's queued anyway. */
979 poll_resolv(0, daemon->last_resolv != 0, now);
980 daemon->last_resolv = now;
983 if (FD_ISSET(piperead, &rset))
984 async_event(piperead, now);
986 #ifdef HAVE_DBUS
987 /* if we didn't create a DBus connection, retry now. */
988 if (option_bool(OPT_DBUS) && !daemon->dbus)
990 char *err;
991 if ((err = dbus_init()))
992 my_syslog(LOG_WARNING, _("DBus error: %s"), err);
993 if (daemon->dbus)
994 my_syslog(LOG_INFO, _("connected to system DBus"));
996 check_dbus_listeners(&rset, &wset, &eset);
997 #endif
999 check_dns_listeners(&rset, now);
1001 #ifdef HAVE_TFTP
1002 check_tftp_listeners(&rset, now);
1003 #endif
1005 #ifdef HAVE_DHCP
1006 if (daemon->dhcp || daemon->relay4)
1008 if (FD_ISSET(daemon->dhcpfd, &rset))
1009 dhcp_packet(now, 0);
1010 if (daemon->pxefd != -1 && FD_ISSET(daemon->pxefd, &rset))
1011 dhcp_packet(now, 1);
1014 #ifdef HAVE_DHCP6
1015 if ((daemon->doing_dhcp6 || daemon->relay6) && FD_ISSET(daemon->dhcp6fd, &rset))
1016 dhcp6_packet(now);
1018 if (daemon->doing_ra && FD_ISSET(daemon->icmp6fd, &rset))
1019 icmp6_packet(now);
1020 #endif
1022 # ifdef HAVE_SCRIPT
1023 if (daemon->helperfd != -1 && FD_ISSET(daemon->helperfd, &wset))
1024 helper_write();
1025 # endif
1026 #endif
1031 static void sig_handler(int sig)
1033 if (pid == 0)
1035 /* ignore anything other than TERM during startup
1036 and in helper proc. (helper ignore TERM too) */
1037 if (sig == SIGTERM)
1038 exit(EC_MISC);
1040 else if (pid != getpid())
1042 /* alarm is used to kill TCP children after a fixed time. */
1043 if (sig == SIGALRM)
1044 _exit(0);
1046 else
1048 /* master process */
1049 int event, errsave = errno;
1051 if (sig == SIGHUP)
1052 event = EVENT_RELOAD;
1053 else if (sig == SIGCHLD)
1054 event = EVENT_CHILD;
1055 else if (sig == SIGALRM)
1056 event = EVENT_ALARM;
1057 else if (sig == SIGTERM)
1058 event = EVENT_TERM;
1059 else if (sig == SIGUSR1)
1060 event = EVENT_DUMP;
1061 else if (sig == SIGUSR2)
1062 event = EVENT_REOPEN;
1063 else
1064 return;
1066 send_event(pipewrite, event, 0, NULL);
1067 errno = errsave;
1071 /* now == 0 -> queue immediate callback */
1072 void send_alarm(time_t event, time_t now)
1074 if (now == 0 || event != 0)
1076 /* alarm(0) or alarm(-ve) doesn't do what we want.... */
1077 if ((now == 0 || difftime(event, now) <= 0.0))
1078 send_event(pipewrite, EVENT_ALARM, 0, NULL);
1079 else
1080 alarm((unsigned)difftime(event, now));
1084 void queue_event(int event)
1086 send_event(pipewrite, event, 0, NULL);
1089 void send_event(int fd, int event, int data, char *msg)
1091 struct event_desc ev;
1092 struct iovec iov[2];
1094 ev.event = event;
1095 ev.data = data;
1096 ev.msg_sz = msg ? strlen(msg) : 0;
1098 iov[0].iov_base = &ev;
1099 iov[0].iov_len = sizeof(ev);
1100 iov[1].iov_base = msg;
1101 iov[1].iov_len = ev.msg_sz;
1103 /* error pipe, debug mode. */
1104 if (fd == -1)
1105 fatal_event(&ev, msg);
1106 else
1107 /* pipe is non-blocking and struct event_desc is smaller than
1108 PIPE_BUF, so this either fails or writes everything */
1109 while (writev(fd, iov, msg ? 2 : 1) == -1 && errno == EINTR);
1112 /* NOTE: the memory used to return msg is leaked: use msgs in events only
1113 to describe fatal errors. */
1114 static int read_event(int fd, struct event_desc *evp, char **msg)
1116 char *buf;
1118 if (!read_write(fd, (unsigned char *)evp, sizeof(struct event_desc), 1))
1119 return 0;
1121 *msg = NULL;
1123 if (evp->msg_sz != 0 &&
1124 (buf = malloc(evp->msg_sz + 1)) &&
1125 read_write(fd, (unsigned char *)buf, evp->msg_sz, 1))
1127 buf[evp->msg_sz] = 0;
1128 *msg = buf;
1131 return 1;
1134 static void fatal_event(struct event_desc *ev, char *msg)
1136 errno = ev->data;
1138 switch (ev->event)
1140 case EVENT_DIE:
1141 exit(0);
1143 case EVENT_FORK_ERR:
1144 die(_("cannot fork into background: %s"), NULL, EC_MISC);
1146 case EVENT_PIPE_ERR:
1147 die(_("failed to create helper: %s"), NULL, EC_MISC);
1149 case EVENT_CAP_ERR:
1150 die(_("setting capabilities failed: %s"), NULL, EC_MISC);
1152 case EVENT_USER_ERR:
1153 die(_("failed to change user-id to %s: %s"), msg, EC_MISC);
1155 case EVENT_GROUP_ERR:
1156 die(_("failed to change group-id to %s: %s"), msg, EC_MISC);
1158 case EVENT_PIDFILE:
1159 die(_("failed to open pidfile %s: %s"), msg, EC_FILE);
1161 case EVENT_LOG_ERR:
1162 die(_("cannot open log %s: %s"), msg, EC_FILE);
1164 case EVENT_LUA_ERR:
1165 die(_("failed to load Lua script: %s"), msg, EC_MISC);
1167 case EVENT_TFTP_ERR:
1168 die(_("TFTP directory %s inaccessible: %s"), msg, EC_FILE);
1172 static void async_event(int pipe, time_t now)
1174 pid_t p;
1175 struct event_desc ev;
1176 int i, check = 0;
1177 char *msg;
1179 /* NOTE: the memory used to return msg is leaked: use msgs in events only
1180 to describe fatal errors. */
1182 if (read_event(pipe, &ev, &msg))
1183 switch (ev.event)
1185 case EVENT_RELOAD:
1186 #ifdef HAVE_DNSSEC
1187 if (option_bool(OPT_DNSSEC_VALID) && option_bool(OPT_DNSSEC_TIME))
1189 my_syslog(LOG_INFO, _("now checking DNSSEC signature timestamps"));
1190 reset_option_bool(OPT_DNSSEC_TIME);
1192 #endif
1193 /* fall through */
1195 case EVENT_INIT:
1196 clear_cache_and_reload(now);
1198 if (daemon->port != 0)
1200 if (daemon->resolv_files && option_bool(OPT_NO_POLL))
1202 reload_servers(daemon->resolv_files->name);
1203 check = 1;
1206 if (daemon->servers_file)
1208 read_servers_file();
1209 check = 1;
1212 if (check)
1213 check_servers();
1216 #ifdef HAVE_DHCP
1217 rerun_scripts();
1218 #endif
1219 break;
1221 case EVENT_DUMP:
1222 if (daemon->port != 0)
1223 dump_cache(now);
1224 break;
1226 case EVENT_ALARM:
1227 #ifdef HAVE_DHCP
1228 if (daemon->dhcp || daemon->doing_dhcp6)
1230 lease_prune(NULL, now);
1231 lease_update_file(now);
1233 #ifdef HAVE_DHCP6
1234 else if (daemon->doing_ra)
1235 /* Not doing DHCP, so no lease system, manage alarms for ra only */
1236 send_alarm(periodic_ra(now), now);
1237 #endif
1238 #endif
1239 break;
1241 case EVENT_CHILD:
1242 /* See Stevens 5.10 */
1243 while ((p = waitpid(-1, NULL, WNOHANG)) != 0)
1244 if (p == -1)
1246 if (errno != EINTR)
1247 break;
1249 else
1250 for (i = 0 ; i < MAX_PROCS; i++)
1251 if (daemon->tcp_pids[i] == p)
1252 daemon->tcp_pids[i] = 0;
1253 break;
1255 case EVENT_KILLED:
1256 my_syslog(LOG_WARNING, _("script process killed by signal %d"), ev.data);
1257 break;
1259 case EVENT_EXITED:
1260 my_syslog(LOG_WARNING, _("script process exited with status %d"), ev.data);
1261 break;
1263 case EVENT_EXEC_ERR:
1264 my_syslog(LOG_ERR, _("failed to execute %s: %s"),
1265 daemon->lease_change_command, strerror(ev.data));
1266 break;
1268 /* necessary for fatal errors in helper */
1269 case EVENT_USER_ERR:
1270 case EVENT_DIE:
1271 case EVENT_LUA_ERR:
1272 fatal_event(&ev, msg);
1273 break;
1275 case EVENT_REOPEN:
1276 /* Note: this may leave TCP-handling processes with the old file still open.
1277 Since any such process will die in CHILD_LIFETIME or probably much sooner,
1278 we leave them logging to the old file. */
1280 if (daemon->log_file != NULL)
1281 log_reopen(daemon->log_file);
1283 #ifdef HAVE_TOMATO
1284 tomato_helper(now); //possibly delete & write out leases for tomato
1285 #endif //TOMATO
1286 /* following is Asus tweak. Interestingly Asus read the dnsmasq leases db
1287 directly. They signal dnsmasq to update via SIGUSR2 and wait 1 second
1288 assuming the file will be complete by the time they come to parse it.
1289 Race conditions anyone? What if dnsmasq happens to be updating the
1290 file anyway? */
1291 #if defined(HAVE_DHCP) && defined(HAVE_LEASEFILE_EXPIRE) && !defined(HAVE_TOMATO)
1292 if (daemon->dhcp || daemon->dhcp6)
1293 flush_lease_file(now);
1294 #endif
1295 break;
1297 case EVENT_NEWADDR:
1298 newaddress(now);
1299 break;
1301 case EVENT_NEWROUTE:
1302 resend_query();
1303 /* Force re-reading resolv file right now, for luck. */
1304 poll_resolv(0, 1, now);
1305 break;
1307 case EVENT_TERM:
1308 /* Knock all our children on the head. */
1309 for (i = 0; i < MAX_PROCS; i++)
1310 if (daemon->tcp_pids[i] != 0)
1311 kill(daemon->tcp_pids[i], SIGALRM);
1313 #if defined(HAVE_SCRIPT)
1314 /* handle pending lease transitions */
1315 if (daemon->helperfd != -1)
1317 /* block in writes until all done */
1318 if ((i = fcntl(daemon->helperfd, F_GETFL)) != -1)
1319 fcntl(daemon->helperfd, F_SETFL, i & ~O_NONBLOCK);
1320 do {
1321 helper_write();
1322 } while (!helper_buf_empty() || do_script_run(now));
1323 close(daemon->helperfd);
1325 #endif
1327 //Originally TOMATO tweak
1328 #if defined(HAVE_DHCP) && defined(HAVE_LEASEFILE_EXPIRE)
1329 if (daemon->dhcp || daemon->dhcp6)
1330 flush_lease_file(now);
1331 #endif
1333 if (daemon->lease_stream)
1334 fclose(daemon->lease_stream);
1336 if (daemon->runfile)
1337 unlink(daemon->runfile);
1339 my_syslog(LOG_INFO, _("exiting on receipt of SIGTERM"));
1340 flush_log();
1341 exit(EC_GOOD);
1345 static void poll_resolv(int force, int do_reload, time_t now)
1347 struct resolvc *res, *latest;
1348 struct stat statbuf;
1349 time_t last_change = 0;
1350 /* There may be more than one possible file.
1351 Go through and find the one which changed _last_.
1352 Warn of any which can't be read. */
1354 if (daemon->port == 0 || option_bool(OPT_NO_POLL))
1355 return;
1357 for (latest = NULL, res = daemon->resolv_files; res; res = res->next)
1358 if (stat(res->name, &statbuf) == -1)
1360 if (force)
1362 res->mtime = 0;
1363 continue;
1366 if (!res->logged)
1367 my_syslog(LOG_WARNING, _("failed to access %s: %s"), res->name, strerror(errno));
1368 res->logged = 1;
1370 if (res->mtime != 0)
1372 /* existing file evaporated, force selection of the latest
1373 file even if its mtime hasn't changed since we last looked */
1374 poll_resolv(1, do_reload, now);
1375 return;
1378 else
1380 res->logged = 0;
1381 if (force || (statbuf.st_mtime != res->mtime))
1383 res->mtime = statbuf.st_mtime;
1384 if (difftime(statbuf.st_mtime, last_change) > 0.0)
1386 last_change = statbuf.st_mtime;
1387 latest = res;
1392 if (latest)
1394 static int warned = 0;
1395 if (reload_servers(latest->name))
1397 my_syslog(LOG_INFO, _("reading %s"), latest->name);
1398 warned = 0;
1399 check_servers();
1400 if (option_bool(OPT_RELOAD) && do_reload)
1401 clear_cache_and_reload(now);
1403 else
1405 latest->mtime = 0;
1406 if (!warned)
1408 my_syslog(LOG_WARNING, _("no servers found in %s, will retry"), latest->name);
1409 warned = 1;
1415 void clear_cache_and_reload(time_t now)
1417 (void)now;
1419 if (daemon->port != 0)
1420 cache_reload();
1422 #ifdef HAVE_DHCP
1423 if (daemon->dhcp || daemon->doing_dhcp6)
1425 if (option_bool(OPT_ETHERS))
1426 dhcp_read_ethers();
1427 reread_dhcp();
1428 dhcp_update_configs(daemon->dhcp_conf);
1429 lease_update_from_configs();
1430 lease_update_file(now);
1431 lease_update_dns(1);
1433 #ifdef HAVE_DHCP6
1434 else if (daemon->doing_ra)
1435 /* Not doing DHCP, so no lease system, manage
1436 alarms for ra only */
1437 send_alarm(periodic_ra(now), now);
1438 #endif
1439 #endif
1442 static int set_dns_listeners(time_t now, fd_set *set, int *maxfdp)
1444 struct serverfd *serverfdp;
1445 struct listener *listener;
1446 int wait = 0, i;
1448 #ifdef HAVE_TFTP
1449 int tftp = 0;
1450 struct tftp_transfer *transfer;
1451 for (transfer = daemon->tftp_trans; transfer; transfer = transfer->next)
1453 tftp++;
1454 FD_SET(transfer->sockfd, set);
1455 bump_maxfd(transfer->sockfd, maxfdp);
1457 #endif
1459 /* will we be able to get memory? */
1460 if (daemon->port != 0)
1461 get_new_frec(now, &wait, 0);
1463 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1465 FD_SET(serverfdp->fd, set);
1466 bump_maxfd(serverfdp->fd, maxfdp);
1469 if (daemon->port != 0 && !daemon->osport)
1470 for (i = 0; i < RANDOM_SOCKS; i++)
1471 if (daemon->randomsocks[i].refcount != 0)
1473 FD_SET(daemon->randomsocks[i].fd, set);
1474 bump_maxfd(daemon->randomsocks[i].fd, maxfdp);
1477 for (listener = daemon->listeners; listener; listener = listener->next)
1479 /* only listen for queries if we have resources */
1480 if (listener->fd != -1 && wait == 0)
1482 FD_SET(listener->fd, set);
1483 bump_maxfd(listener->fd, maxfdp);
1486 /* death of a child goes through the select loop, so
1487 we don't need to explicitly arrange to wake up here */
1488 if (listener->tcpfd != -1)
1489 for (i = 0; i < MAX_PROCS; i++)
1490 if (daemon->tcp_pids[i] == 0)
1492 FD_SET(listener->tcpfd, set);
1493 bump_maxfd(listener->tcpfd, maxfdp);
1494 break;
1497 #ifdef HAVE_TFTP
1498 if (tftp <= daemon->tftp_max && listener->tftpfd != -1)
1500 FD_SET(listener->tftpfd, set);
1501 bump_maxfd(listener->tftpfd, maxfdp);
1503 #endif
1507 return wait;
1510 static void check_dns_listeners(fd_set *set, time_t now)
1512 struct serverfd *serverfdp;
1513 struct listener *listener;
1514 int i;
1516 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1517 if (FD_ISSET(serverfdp->fd, set))
1518 reply_query(serverfdp->fd, serverfdp->source_addr.sa.sa_family, now);
1520 if (daemon->port != 0 && !daemon->osport)
1521 for (i = 0; i < RANDOM_SOCKS; i++)
1522 if (daemon->randomsocks[i].refcount != 0 &&
1523 FD_ISSET(daemon->randomsocks[i].fd, set))
1524 reply_query(daemon->randomsocks[i].fd, daemon->randomsocks[i].family, now);
1526 for (listener = daemon->listeners; listener; listener = listener->next)
1528 if (listener->fd != -1 && FD_ISSET(listener->fd, set))
1529 receive_query(listener, now);
1531 #ifdef HAVE_TFTP
1532 if (listener->tftpfd != -1 && FD_ISSET(listener->tftpfd, set))
1533 tftp_request(listener, now);
1534 #endif
1536 if (listener->tcpfd != -1 && FD_ISSET(listener->tcpfd, set))
1538 int confd, client_ok = 1;
1539 struct irec *iface = NULL;
1540 pid_t p;
1541 union mysockaddr tcp_addr;
1542 socklen_t tcp_len = sizeof(union mysockaddr);
1544 while ((confd = accept(listener->tcpfd, NULL, NULL)) == -1 && errno == EINTR);
1546 if (confd == -1)
1547 continue;
1549 if (getsockname(confd, (struct sockaddr *)&tcp_addr, &tcp_len) == -1)
1551 close(confd);
1552 continue;
1555 /* Make sure that the interface list is up-to-date.
1557 We do this here as we may need the results below, and
1558 the DNS code needs them for --interface-name stuff.
1560 Multiple calls to enumerate_interfaces() per select loop are
1561 inhibited, so calls to it in the child process (which doesn't select())
1562 have no effect. This avoids two processes reading from the same
1563 netlink fd and screwing the pooch entirely.
1566 enumerate_interfaces(0);
1568 if (option_bool(OPT_NOWILD))
1569 iface = listener->iface; /* May be NULL */
1570 else
1572 int if_index;
1573 char intr_name[IF_NAMESIZE];
1575 /* if we can find the arrival interface, check it's one that's allowed */
1576 if ((if_index = tcp_interface(confd, tcp_addr.sa.sa_family)) != 0 &&
1577 indextoname(listener->tcpfd, if_index, intr_name))
1579 struct all_addr addr;
1580 addr.addr.addr4 = tcp_addr.in.sin_addr;
1581 #ifdef HAVE_IPV6
1582 if (tcp_addr.sa.sa_family == AF_INET6)
1583 addr.addr.addr6 = tcp_addr.in6.sin6_addr;
1584 #endif
1586 for (iface = daemon->interfaces; iface; iface = iface->next)
1587 if (iface->index == if_index)
1588 break;
1590 if (!iface && !loopback_exception(listener->tcpfd, tcp_addr.sa.sa_family, &addr, intr_name))
1591 client_ok = 0;
1594 if (option_bool(OPT_CLEVERBIND))
1595 iface = listener->iface; /* May be NULL */
1596 else
1598 /* Check for allowed interfaces when binding the wildcard address:
1599 we do this by looking for an interface with the same address as
1600 the local address of the TCP connection, then looking to see if that's
1601 an allowed interface. As a side effect, we get the netmask of the
1602 interface too, for localisation. */
1604 for (iface = daemon->interfaces; iface; iface = iface->next)
1605 if (sockaddr_isequal(&iface->addr, &tcp_addr))
1606 break;
1608 if (!iface)
1609 client_ok = 0;
1613 if (!client_ok)
1615 shutdown(confd, SHUT_RDWR);
1616 close(confd);
1618 #ifndef NO_FORK
1619 else if (!option_bool(OPT_DEBUG) && (p = fork()) != 0)
1621 if (p != -1)
1623 int i;
1624 for (i = 0; i < MAX_PROCS; i++)
1625 if (daemon->tcp_pids[i] == 0)
1627 daemon->tcp_pids[i] = p;
1628 break;
1631 close(confd);
1633 #endif
1634 else
1636 unsigned char *buff;
1637 struct server *s;
1638 int flags;
1639 struct in_addr netmask;
1640 int auth_dns;
1642 if (iface)
1644 netmask = iface->netmask;
1645 auth_dns = iface->dns_auth;
1647 else
1649 netmask.s_addr = 0;
1650 auth_dns = 0;
1653 #ifndef NO_FORK
1654 /* Arrange for SIGALARM after CHILD_LIFETIME seconds to
1655 terminate the process. */
1656 if (!option_bool(OPT_DEBUG))
1657 alarm(CHILD_LIFETIME);
1658 #endif
1660 /* start with no upstream connections. */
1661 for (s = daemon->servers; s; s = s->next)
1662 s->tcpfd = -1;
1664 /* The connected socket inherits non-blocking
1665 attribute from the listening socket.
1666 Reset that here. */
1667 if ((flags = fcntl(confd, F_GETFL, 0)) != -1)
1668 fcntl(confd, F_SETFL, flags & ~O_NONBLOCK);
1670 buff = tcp_request(confd, now, &tcp_addr, netmask, auth_dns);
1672 shutdown(confd, SHUT_RDWR);
1673 close(confd);
1675 if (buff)
1676 free(buff);
1678 for (s = daemon->servers; s; s = s->next)
1679 if (s->tcpfd != -1)
1681 shutdown(s->tcpfd, SHUT_RDWR);
1682 close(s->tcpfd);
1684 #ifndef NO_FORK
1685 if (!option_bool(OPT_DEBUG))
1687 flush_log();
1688 _exit(0);
1690 #endif
1696 #ifdef HAVE_DHCP
1697 int make_icmp_sock(void)
1699 int fd;
1700 int zeroopt = 0;
1702 if ((fd = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
1704 if (!fix_fd(fd) ||
1705 setsockopt(fd, SOL_SOCKET, SO_DONTROUTE, &zeroopt, sizeof(zeroopt)) == -1)
1707 close(fd);
1708 fd = -1;
1712 return fd;
1715 int icmp_ping(struct in_addr addr)
1717 /* Try and get an ICMP echo from a machine. */
1719 /* Note that whilst in the three second wait, we check for
1720 (and service) events on the DNS and TFTP sockets, (so doing that
1721 better not use any resources our caller has in use...)
1722 but we remain deaf to signals or further DHCP packets. */
1724 int fd;
1725 struct sockaddr_in saddr;
1726 struct {
1727 struct ip ip;
1728 struct icmp icmp;
1729 } packet;
1730 unsigned short id = rand16();
1731 unsigned int i, j;
1732 int gotreply = 0;
1733 time_t start, now;
1735 #if defined(HAVE_LINUX_NETWORK) || defined (HAVE_SOLARIS_NETWORK)
1736 if ((fd = make_icmp_sock()) == -1)
1737 return 0;
1738 #else
1739 int opt = 2000;
1740 fd = daemon->dhcp_icmp_fd;
1741 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1742 #endif
1744 saddr.sin_family = AF_INET;
1745 saddr.sin_port = 0;
1746 saddr.sin_addr = addr;
1747 #ifdef HAVE_SOCKADDR_SA_LEN
1748 saddr.sin_len = sizeof(struct sockaddr_in);
1749 #endif
1751 memset(&packet.icmp, 0, sizeof(packet.icmp));
1752 packet.icmp.icmp_type = ICMP_ECHO;
1753 packet.icmp.icmp_id = id;
1754 for (j = 0, i = 0; i < sizeof(struct icmp) / 2; i++)
1755 j += ((u16 *)&packet.icmp)[i];
1756 while (j>>16)
1757 j = (j & 0xffff) + (j >> 16);
1758 packet.icmp.icmp_cksum = (j == 0xffff) ? j : ~j;
1760 while (sendto(fd, (char *)&packet.icmp, sizeof(struct icmp), 0,
1761 (struct sockaddr *)&saddr, sizeof(saddr)) == -1 &&
1762 retry_send());
1764 for (now = start = dnsmasq_time();
1765 difftime(now, start) < (float)PING_WAIT;)
1767 struct timeval tv;
1768 fd_set rset, wset;
1769 struct sockaddr_in faddr;
1770 int maxfd = fd;
1771 socklen_t len = sizeof(faddr);
1773 tv.tv_usec = 250000;
1774 tv.tv_sec = 0;
1776 FD_ZERO(&rset);
1777 FD_ZERO(&wset);
1778 FD_SET(fd, &rset);
1779 set_dns_listeners(now, &rset, &maxfd);
1780 set_log_writer(&wset, &maxfd);
1782 #ifdef HAVE_DHCP6
1783 if (daemon->doing_ra)
1785 FD_SET(daemon->icmp6fd, &rset);
1786 bump_maxfd(daemon->icmp6fd, &maxfd);
1788 #endif
1790 if (select(maxfd+1, &rset, &wset, NULL, &tv) < 0)
1792 FD_ZERO(&rset);
1793 FD_ZERO(&wset);
1796 now = dnsmasq_time();
1798 check_log_writer(&wset);
1799 check_dns_listeners(&rset, now);
1801 #ifdef HAVE_DHCP6
1802 if (daemon->doing_ra && FD_ISSET(daemon->icmp6fd, &rset))
1803 icmp6_packet(now);
1804 #endif
1806 #ifdef HAVE_TFTP
1807 check_tftp_listeners(&rset, now);
1808 #endif
1810 if (FD_ISSET(fd, &rset) &&
1811 recvfrom(fd, &packet, sizeof(packet), 0,
1812 (struct sockaddr *)&faddr, &len) == sizeof(packet) &&
1813 saddr.sin_addr.s_addr == faddr.sin_addr.s_addr &&
1814 packet.icmp.icmp_type == ICMP_ECHOREPLY &&
1815 packet.icmp.icmp_seq == 0 &&
1816 packet.icmp.icmp_id == id)
1818 gotreply = 1;
1819 break;
1823 #if defined(HAVE_LINUX_NETWORK) || defined(HAVE_SOLARIS_NETWORK)
1824 close(fd);
1825 #else
1826 opt = 1;
1827 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1828 #endif
1830 return gotreply;
1832 #endif