1 /* dnsmasq is Copyright (c) 2000-2022 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/>.
17 /* Declare static char *compiler_opts in config.h */
18 #define DNSMASQ_COMPILE_OPTS
20 /* dnsmasq.h has to be included first as it sources config.h */
23 #if defined(HAVE_IDN) || defined(HAVE_LIBIDN2) || defined(LOCALEDIR)
27 struct daemon *daemon;
29 static volatile pid_t pid = 0;
30 static volatile int pipewrite;
32 static void set_dns_listeners(void);
33 static void check_dns_listeners(time_t now);
34 static void sig_handler(int sig);
35 static void async_event(int pipe, time_t now);
36 static void fatal_event(struct event_desc *ev, char *msg);
37 static int read_event(int fd, struct event_desc *evp, char **msg);
38 static void poll_resolv(int force, int do_reload, time_t now);
40 int main (int argc, char **argv)
43 struct sigaction sigact;
45 int piperead, pipefd[2], err_pipe[2];
46 struct passwd *ent_pw = NULL;
47 #if defined(HAVE_SCRIPT)
51 struct group *gp = NULL;
52 long i, max_fd = sysconf(_SC_OPEN_MAX);
56 #if defined(HAVE_LINUX_NETWORK)
57 cap_user_header_t hdr = NULL;
58 cap_user_data_t data = NULL;
59 int need_cap_net_admin = 0;
60 int need_cap_net_raw = 0;
61 int need_cap_net_bind_service = 0;
62 char *bound_device = NULL;
67 int bind_fallback = 0;
69 #if defined(HAVE_DHCP) || defined(HAVE_DHCP6)
70 struct dhcp_context *context;
71 struct dhcp_relay *relay;
74 int tftp_prefix_missing = 0;
77 #if defined(HAVE_IDN) || defined(HAVE_LIBIDN2) || defined(LOCALEDIR)
78 setlocale(LC_ALL, "");
81 bindtextdomain("dnsmasq", LOCALEDIR);
82 textdomain("dnsmasq");
85 sigact.sa_handler = sig_handler;
87 sigemptyset(&sigact.sa_mask);
88 sigaction(SIGUSR1, &sigact, NULL);
89 sigaction(SIGUSR2, &sigact, NULL);
90 sigaction(SIGHUP, &sigact, NULL);
91 sigaction(SIGTERM, &sigact, NULL);
92 sigaction(SIGALRM, &sigact, NULL);
93 sigaction(SIGCHLD, &sigact, NULL);
94 sigaction(SIGINT, &sigact, NULL);
97 sigact.sa_handler = SIG_IGN;
98 sigaction(SIGPIPE, &sigact, NULL);
100 umask(022); /* known umask, create leases and pid files as 0644 */
102 rand_init(); /* Must precede read_opts() */
104 read_opts(argc, argv, compile_opts);
106 #ifdef HAVE_LINUX_NETWORK
107 daemon->kernel_version = kernel_version();
110 if (daemon->edns_pktsz < PACKETSZ)
111 daemon->edns_pktsz = PACKETSZ;
113 /* Min buffer size: we check after adding each record, so there must be
114 memory for the largest packet, and the largest record so the
115 min for DNS is PACKETSZ+MAXDNAME+RRFIXEDSZ which is < 1000.
116 This might be increased is EDNS packet size if greater than the minimum. */
117 daemon->packet_buff_sz = daemon->edns_pktsz + MAXDNAME + RRFIXEDSZ;
118 daemon->packet = safe_malloc(daemon->packet_buff_sz);
120 if (option_bool(OPT_EXTRALOG))
121 daemon->addrbuff2 = safe_malloc(ADDRSTRLEN);
124 if (option_bool(OPT_DNSSEC_VALID))
126 /* Note that both /000 and '.' are allowed within labels. These get
127 represented in presentation format using NAME_ESCAPE as an escape
128 character when in DNSSEC mode.
129 In theory, if all the characters in a name were /000 or
130 '.' or NAME_ESCAPE then all would have to be escaped, so the
131 presentation format would be twice as long as the spec.
133 daemon->namebuff was previously allocated by the option-reading
134 code before we knew if we're in DNSSEC mode, so reallocate here. */
135 free(daemon->namebuff);
136 daemon->namebuff = safe_malloc(MAXDNAME * 2);
137 daemon->keyname = safe_malloc(MAXDNAME * 2);
138 daemon->workspacename = safe_malloc(MAXDNAME * 2);
139 /* one char flag per possible RR in answer section (may get extended). */
140 daemon->rr_status_sz = 64;
141 daemon->rr_status = safe_malloc(sizeof(*daemon->rr_status) * daemon->rr_status_sz);
145 #if defined(HAVE_CONNTRACK) && defined(HAVE_UBUS)
146 /* CONNTRACK UBUS code uses this buffer, so if not allocated above,
147 we need to allocate it here. */
148 if (option_bool(OPT_CMARK_ALST_EN) && !daemon->workspacename)
149 daemon->workspacename = safe_malloc(MAXDNAME);
153 if (!daemon->lease_file)
155 if (daemon->dhcp || daemon->dhcp6)
156 daemon->lease_file = LEASEFILE;
160 /* Ensure that at least stdin, stdout and stderr (fd 0, 1, 2) exist,
161 otherwise file descriptors we create can end up being 0, 1, or 2
162 and then get accidentally closed later when we make 0, 1, and 2
163 open to /dev/null. Normally we'll be started with 0, 1 and 2 open,
164 but it's not guaranteed. By opening /dev/null three times, we
165 ensure that we're not using those fds for real stuff. */
166 for (i = 0; i < 3; i++)
167 open("/dev/null", O_RDWR);
169 /* Close any file descriptors we inherited apart from std{in|out|err} */
170 close_fds(max_fd, -1, -1, -1);
172 #ifndef HAVE_LINUX_NETWORK
173 # if !(defined(IP_RECVDSTADDR) && defined(IP_RECVIF) && defined(IP_SENDSRCADDR))
174 if (!option_bool(OPT_NOWILD))
177 set_option_bool(OPT_NOWILD);
181 /* -- bind-dynamic not supported on !Linux, fall back to --bind-interfaces */
182 if (option_bool(OPT_CLEVERBIND))
185 set_option_bool(OPT_NOWILD);
186 reset_option_bool(OPT_CLEVERBIND);
191 if (daemon->dynamic_dirs)
192 die(_("dhcp-hostsdir, dhcp-optsdir and hostsdir are not supported on this platform"), NULL, EC_BADCONF);
195 if (option_bool(OPT_DNSSEC_VALID))
198 struct ds_config *ds;
200 /* Must have at least a root trust anchor, or the DNSSEC code
202 for (ds = daemon->ds; ds; ds = ds->next)
203 if (ds->name[0] == 0)
207 die(_("no root trust anchor provided for DNSSEC"), NULL, EC_BADCONF);
209 if (daemon->cachesize < CACHESIZ)
210 die(_("cannot reduce cache size from default when DNSSEC enabled"), NULL, EC_BADCONF);
212 die(_("DNSSEC not available: set HAVE_DNSSEC in src/config.h"), NULL, EC_BADCONF);
217 if (option_bool(OPT_TFTP))
218 die(_("TFTP server not available: set HAVE_TFTP in src/config.h"), NULL, EC_BADCONF);
221 #ifdef HAVE_CONNTRACK
222 if (option_bool(OPT_CONNTRACK))
224 if (daemon->query_port != 0 || daemon->osport)
225 die (_("cannot use --conntrack AND --query-port"), NULL, EC_BADCONF);
227 need_cap_net_admin = 1;
230 if (option_bool(OPT_CONNTRACK))
231 die(_("conntrack support not available: set HAVE_CONNTRACK in src/config.h"), NULL, EC_BADCONF);
234 #ifdef HAVE_SOLARIS_NETWORK
235 if (daemon->max_logs != 0)
236 die(_("asynchronous logging is not available under Solaris"), NULL, EC_BADCONF);
240 if (daemon->max_logs != 0)
241 die(_("asynchronous logging is not available under Android"), NULL, EC_BADCONF);
245 if (daemon->auth_zones)
246 die(_("authoritative DNS not available: set HAVE_AUTH in src/config.h"), NULL, EC_BADCONF);
250 if (option_bool(OPT_LOOP_DETECT))
251 die(_("loop detection not available: set HAVE_LOOP in src/config.h"), NULL, EC_BADCONF);
255 if (option_bool(OPT_UBUS))
256 die(_("Ubus not available: set HAVE_UBUS in src/config.h"), NULL, EC_BADCONF);
259 /* Handle only one of min_port/max_port being set. */
260 if (daemon->min_port != 0 && daemon->max_port == 0)
261 daemon->max_port = MAX_PORT;
263 if (daemon->max_port != 0 && daemon->min_port == 0)
264 daemon->min_port = MIN_PORT;
266 if (daemon->max_port < daemon->min_port)
267 die(_("max_port cannot be smaller than min_port"), NULL, EC_BADCONF);
269 if (daemon->max_port != 0 &&
270 daemon->max_port - daemon->min_port + 1 < daemon->randport_limit)
271 die(_("port_limit must not be larger than available port range"), NULL, EC_BADCONF);
273 now = dnsmasq_time();
275 if (daemon->auth_zones)
277 if (!daemon->authserver)
278 die(_("--auth-server required when an auth zone is defined."), NULL, EC_BADCONF);
280 /* Create a serial at startup if not configured. */
281 #ifdef HAVE_BROKEN_RTC
282 if (daemon->soa_sn == 0)
283 die(_("zone serial must be configured in --auth-soa"), NULL, EC_BADCONF);
285 if (daemon->soa_sn == 0)
286 daemon->soa_sn = now;
293 daemon->doing_ra = option_bool(OPT_RA);
295 for (context = daemon->dhcp6; context; context = context->next)
297 if (context->flags & CONTEXT_DHCP)
298 daemon->doing_dhcp6 = 1;
299 if (context->flags & CONTEXT_RA)
300 daemon->doing_ra = 1;
301 #if !defined(HAVE_LINUX_NETWORK) && !defined(HAVE_BSD_NETWORK)
302 if (context->flags & CONTEXT_TEMPLATE)
303 die (_("dhcp-range constructor not available on this platform"), NULL, EC_BADCONF);
310 /* Note that order matters here, we must call lease_init before
311 creating any file descriptors which shouldn't be leaked
312 to the lease-script init process. We need to call common_init
313 before lease_init to allocate buffers it uses.
314 The script subsystem relies on DHCP buffers, hence the last two
316 if (daemon->dhcp || daemon->doing_dhcp6 || daemon->relay4 ||
317 daemon->relay6 || option_bool(OPT_TFTP) || option_bool(OPT_SCRIPT_ARP))
320 if (daemon->dhcp || daemon->doing_dhcp6)
324 if (daemon->dhcp || daemon->relay4)
327 # ifdef HAVE_LINUX_NETWORK
328 if (!option_bool(OPT_NO_PING))
329 need_cap_net_raw = 1;
330 need_cap_net_admin = 1;
335 if (daemon->doing_ra || daemon->doing_dhcp6 || daemon->relay6)
338 # ifdef HAVE_LINUX_NETWORK
339 need_cap_net_raw = 1;
340 need_cap_net_admin = 1;
344 if (daemon->doing_dhcp6 || daemon->relay6)
354 # ifdef HAVE_LINUX_NETWORK
355 need_cap_net_admin = 1;
364 # ifdef HAVE_LINUX_NETWORK
365 need_cap_net_admin = 1;
370 #if defined(HAVE_LINUX_NETWORK)
371 netlink_warn = netlink_init();
372 #elif defined(HAVE_BSD_NETWORK)
376 if (option_bool(OPT_NOWILD) && option_bool(OPT_CLEVERBIND))
377 die(_("cannot set --bind-interfaces and --bind-dynamic"), NULL, EC_BADCONF);
379 if (!enumerate_interfaces(1) || !enumerate_interfaces(0))
380 die(_("failed to find list of interfaces: %s"), NULL, EC_MISC);
382 if (option_bool(OPT_NOWILD) || option_bool(OPT_CLEVERBIND))
384 create_bound_listeners(1);
386 if (!option_bool(OPT_CLEVERBIND))
387 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
388 if (if_tmp->name && !if_tmp->used)
389 die(_("unknown interface %s"), if_tmp->name, EC_BADNET);
391 #if defined(HAVE_LINUX_NETWORK) && defined(HAVE_DHCP)
392 /* after enumerate_interfaces() */
393 bound_device = whichdevice();
395 if ((did_bind = bind_dhcp_devices(bound_device)) & 2)
396 die(_("failed to set SO_BINDTODEVICE on DHCP socket: %s"), NULL, EC_BADNET);
400 create_wildcard_listeners();
403 /* after enumerate_interfaces() */
404 if (daemon->doing_dhcp6 || daemon->relay6 || daemon->doing_ra)
407 /* After netlink_init() and before create_helper() */
408 lease_make_duid(now);
411 if (daemon->port != 0)
415 hash_questions_init();
417 /* Scale random socket pool by ftabsize, but
418 limit it based on available fds. */
419 daemon->numrrand = daemon->ftabsize/2;
420 if (daemon->numrrand > max_fd/3)
421 daemon->numrrand = max_fd/3;
422 /* safe_malloc returns zero'd memory */
423 daemon->randomsocks = safe_malloc(daemon->numrrand * sizeof(struct randfd));
427 if ((daemon->port != 0 || daemon->dhcp || daemon->doing_dhcp6)
428 && (!option_bool(OPT_NO_RESOLV) || daemon->dynamic_dirs))
429 inotify_dnsmasq_init();
431 daemon->inotifyfd = -1;
434 if (daemon->dump_file)
440 die(_("Packet dumps not available: set HAVE_DUMP in src/config.h"), NULL, EC_BADCONF);
443 if (option_bool(OPT_DBUS))
447 if ((err = dbus_init()))
448 die(_("DBus error: %s"), err, EC_MISC);
451 die(_("DBus not available: set HAVE_DBUS in src/config.h"), NULL, EC_BADCONF);
454 if (option_bool(OPT_UBUS))
458 if ((err = ubus_init()))
459 die(_("UBus error: %s"), err, EC_MISC);
462 die(_("UBus not available: set HAVE_UBUS in src/config.h"), NULL, EC_BADCONF);
465 if (daemon->port != 0)
468 #if defined(HAVE_SCRIPT)
469 /* Note getpwnam returns static storage */
470 if ((daemon->dhcp || daemon->dhcp6) &&
471 daemon->scriptuser &&
472 (daemon->lease_change_command || daemon->luascript))
474 struct passwd *scr_pw;
476 if ((scr_pw = getpwnam(daemon->scriptuser)))
478 script_uid = scr_pw->pw_uid;
479 script_gid = scr_pw->pw_gid;
482 baduser = daemon->scriptuser;
486 if (daemon->username && !(ent_pw = getpwnam(daemon->username)))
487 baduser = daemon->username;
488 else if (daemon->groupname && !(gp = getgrnam(daemon->groupname)))
489 baduser = daemon->groupname;
492 die(_("unknown user or group: %s"), baduser, EC_BADCONF);
494 /* implement group defaults, "dip" if available, or group associated with uid */
495 if (!daemon->group_set && !gp)
497 if (!(gp = getgrnam(CHGRP)) && ent_pw)
498 gp = getgrgid(ent_pw->pw_gid);
500 /* for error message */
502 daemon->groupname = gp->gr_name;
505 #if defined(HAVE_LINUX_NETWORK)
506 /* We keep CAP_NETADMIN (for ARP-injection) and
507 CAP_NET_RAW (for icmp) if we're doing dhcp,
508 if we have yet to bind ports because of DAD,
509 or we're doing it dynamically, we need CAP_NET_BIND_SERVICE. */
510 if ((is_dad_listeners() || option_bool(OPT_CLEVERBIND)) &&
511 (option_bool(OPT_TFTP) || (daemon->port != 0 && daemon->port <= 1024)))
512 need_cap_net_bind_service = 1;
514 /* usptream servers which bind to an interface call SO_BINDTODEVICE
515 for each TCP connection, so need CAP_NET_RAW */
516 for (serv = daemon->servers; serv; serv = serv->next)
517 if (serv->interface[0] != 0)
518 need_cap_net_raw = 1;
520 /* If we're doing Dbus or UBus, the above can be set dynamically,
521 (as can ports) so always (potentially) needed. */
523 if (option_bool(OPT_DBUS))
525 need_cap_net_bind_service = 1;
526 need_cap_net_raw = 1;
531 if (option_bool(OPT_UBUS))
533 need_cap_net_bind_service = 1;
534 need_cap_net_raw = 1;
538 /* determine capability API version here, while we can still
540 int capsize = 1; /* for header version 1 */
543 hdr = safe_malloc(sizeof(*hdr));
545 /* find version supported by kernel */
546 memset(hdr, 0, sizeof(*hdr));
549 if (hdr->version != LINUX_CAPABILITY_VERSION_1)
551 /* if unknown version, use largest supported version (3) */
552 if (hdr->version != LINUX_CAPABILITY_VERSION_2)
553 hdr->version = LINUX_CAPABILITY_VERSION_3;
557 data = safe_malloc(sizeof(*data) * capsize);
558 capget(hdr, data); /* Get current values, for verification */
560 if (need_cap_net_admin && !(data->permitted & (1 << CAP_NET_ADMIN)))
562 else if (need_cap_net_raw && !(data->permitted & (1 << CAP_NET_RAW)))
564 else if (need_cap_net_bind_service && !(data->permitted & (1 << CAP_NET_BIND_SERVICE)))
565 fail = "NET_BIND_SERVICE";
568 die(_("process is missing required capability %s"), fail, EC_MISC);
570 /* Now set bitmaps to set caps after daemonising */
571 memset(data, 0, sizeof(*data) * capsize);
573 if (need_cap_net_admin)
574 data->effective |= (1 << CAP_NET_ADMIN);
575 if (need_cap_net_raw)
576 data->effective |= (1 << CAP_NET_RAW);
577 if (need_cap_net_bind_service)
578 data->effective |= (1 << CAP_NET_BIND_SERVICE);
580 data->permitted = data->effective;
583 /* Use a pipe to carry signals and other events back to the event loop
584 in a race-free manner and another to carry errors to daemon-invoking process */
585 safe_pipe(pipefd, 1);
587 piperead = pipefd[0];
588 pipewrite = pipefd[1];
589 /* prime the pipe to load stuff first time. */
590 send_event(pipewrite, EVENT_INIT, 0, NULL);
594 if (!option_bool(OPT_DEBUG))
596 /* The following code "daemonizes" the process.
597 See Stevens section 12.4 */
600 die(_("cannot chdir to filesystem root: %s"), NULL, EC_MISC);
602 if (!option_bool(OPT_NO_FORK))
606 /* pipe to carry errors back to original process.
607 When startup is complete we close this and the process terminates. */
608 safe_pipe(err_pipe, 0);
610 if ((pid = fork()) == -1)
611 /* fd == -1 since we've not forked, never returns. */
612 send_event(-1, EVENT_FORK_ERR, errno, NULL);
616 struct event_desc ev;
619 /* close our copy of write-end */
622 /* check for errors after the fork */
623 if (read_event(err_pipe[0], &ev, &msg))
624 fatal_event(&ev, msg);
631 /* NO calls to die() from here on. */
635 if ((pid = fork()) == -1)
636 send_event(err_pipe[1], EVENT_FORK_ERR, errno, NULL);
642 /* write pidfile _after_ forking ! */
647 sprintf(daemon->namebuff, "%d\n", (int) getpid());
649 /* Explanation: Some installations of dnsmasq (eg Debian/Ubuntu) locate the pid-file
650 in a directory which is writable by the non-privileged user that dnsmasq runs as. This
651 allows the daemon to delete the file as part of its shutdown. This is a security hole to the
652 extent that an attacker running as the unprivileged user could replace the pidfile with a
653 symlink, and have the target of that symlink overwritten as root next time dnsmasq starts.
655 The following code first deletes any existing file, and then opens it with the O_EXCL flag,
656 ensuring that the open() fails should there be any existing file (because the unlink() failed,
657 or an attacker exploited the race between unlink() and open()). This ensures that no symlink
660 Any compromise of the non-privileged user still theoretically allows the pid-file to be
661 replaced whilst dnsmasq is running. The worst that could allow is that the usual
662 "shutdown dnsmasq" shell command could be tricked into stopping any other process.
664 Note that if dnsmasq is started as non-root (eg for testing) it silently ignores
665 failure to write the pid-file.
668 unlink(daemon->runfile);
670 if ((fd = open(daemon->runfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH)) == -1)
672 /* only complain if started as root */
678 /* We're still running as root here. Change the ownership of the PID file
679 to the user we will be running as. Note that this is not to allow
680 us to delete the file, since that depends on the permissions
681 of the directory containing the file. That directory will
682 need to by owned by the dnsmasq user, and the ownership of the
683 file has to match, to keep systemd >273 happy. */
684 if (getuid() == 0 && ent_pw && ent_pw->pw_uid != 0 && fchown(fd, ent_pw->pw_uid, ent_pw->pw_gid) == -1)
687 if (!read_write(fd, (unsigned char *)daemon->namebuff, strlen(daemon->namebuff), 0))
698 send_event(err_pipe[1], EVENT_PIDFILE, errno, daemon->runfile);
704 log_err = log_start(ent_pw, err_pipe[1]);
706 if (!option_bool(OPT_DEBUG))
708 /* open stdout etc to /dev/null */
709 int nullfd = open("/dev/null", O_RDWR);
712 dup2(nullfd, STDOUT_FILENO);
713 dup2(nullfd, STDERR_FILENO);
714 dup2(nullfd, STDIN_FILENO);
719 /* if we are to run scripts, we need to fork a helper before dropping root. */
720 daemon->helperfd = -1;
725 option_bool(OPT_TFTP) ||
726 option_bool(OPT_SCRIPT_ARP)) &&
727 (daemon->lease_change_command || daemon->luascript))
728 daemon->helperfd = create_helper(pipewrite, err_pipe[1], script_uid, script_gid, max_fd);
731 if (!option_bool(OPT_DEBUG) && getuid() == 0)
733 int bad_capabilities = 0;
736 /* remove all supplementary groups */
738 (setgroups(0, &dummy) == -1 ||
739 setgid(gp->gr_gid) == -1))
741 send_event(err_pipe[1], EVENT_GROUP_ERR, errno, daemon->groupname);
745 if (ent_pw && ent_pw->pw_uid != 0)
747 #if defined(HAVE_LINUX_NETWORK)
748 /* Need to be able to drop root. */
749 data->effective |= (1 << CAP_SETUID);
750 data->permitted |= (1 << CAP_SETUID);
751 /* Tell kernel to not clear capabilities when dropping root */
752 if (capset(hdr, data) == -1 || prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1)
753 bad_capabilities = errno;
755 #elif defined(HAVE_SOLARIS_NETWORK)
756 /* http://developers.sun.com/solaris/articles/program_privileges.html */
757 priv_set_t *priv_set;
759 if (!(priv_set = priv_str_to_set("basic", ",", NULL)) ||
760 priv_addset(priv_set, PRIV_NET_ICMPACCESS) == -1 ||
761 priv_addset(priv_set, PRIV_SYS_NET_CONFIG) == -1)
762 bad_capabilities = errno;
764 if (priv_set && bad_capabilities == 0)
766 priv_inverse(priv_set);
768 if (setppriv(PRIV_OFF, PRIV_LIMIT, priv_set) == -1)
769 bad_capabilities = errno;
773 priv_freeset(priv_set);
777 if (bad_capabilities != 0)
779 send_event(err_pipe[1], EVENT_CAP_ERR, bad_capabilities, NULL);
783 /* finally drop root */
784 if (setuid(ent_pw->pw_uid) == -1)
786 send_event(err_pipe[1], EVENT_USER_ERR, errno, daemon->username);
790 #ifdef HAVE_LINUX_NETWORK
791 data->effective &= ~(1 << CAP_SETUID);
792 data->permitted &= ~(1 << CAP_SETUID);
794 /* lose the setuid capability */
795 if (capset(hdr, data) == -1)
797 send_event(err_pipe[1], EVENT_CAP_ERR, errno, NULL);
805 #ifdef HAVE_LINUX_NETWORK
808 if (option_bool(OPT_DEBUG))
809 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
813 if (option_bool(OPT_TFTP))
816 struct tftp_prefix *p;
818 if (daemon->tftp_prefix)
820 if (!((dir = opendir(daemon->tftp_prefix))))
822 tftp_prefix_missing = 1;
823 if (!option_bool(OPT_TFTP_NO_FAIL))
825 send_event(err_pipe[1], EVENT_TFTP_ERR, errno, daemon->tftp_prefix);
833 for (p = daemon->if_prefix; p; p = p->next)
836 if (!((dir = opendir(p->prefix))))
839 if (!option_bool(OPT_TFTP_NO_FAIL))
841 send_event(err_pipe[1], EVENT_TFTP_ERR, errno, p->prefix);
851 if (daemon->port == 0)
852 my_syslog(LOG_INFO, _("started, version %s DNS disabled"), VERSION);
855 if (daemon->cachesize != 0)
857 my_syslog(LOG_INFO, _("started, version %s cachesize %d"), VERSION, daemon->cachesize);
858 if (daemon->cachesize > 10000)
859 my_syslog(LOG_WARNING, _("cache size greater than 10000 may cause performance issues, and is unlikely to be useful."));
862 my_syslog(LOG_INFO, _("started, version %s cache disabled"), VERSION);
864 if (option_bool(OPT_LOCAL_SERVICE))
865 my_syslog(LOG_INFO, _("DNS service limited to local subnets"));
868 my_syslog(LOG_INFO, _("compile time options: %s"), compile_opts);
871 my_syslog(LOG_WARNING, "chown of PID file %s failed: %s", daemon->runfile, strerror(chown_warn));
874 if (option_bool(OPT_DBUS))
877 my_syslog(LOG_INFO, _("DBus support enabled: connected to system bus"));
879 my_syslog(LOG_INFO, _("DBus support enabled: bus connection pending"));
884 if (option_bool(OPT_UBUS))
887 my_syslog(LOG_INFO, _("UBus support enabled: connected to system bus"));
889 my_syslog(LOG_INFO, _("UBus support enabled: bus connection pending"));
894 if (option_bool(OPT_DNSSEC_VALID))
897 struct ds_config *ds;
899 /* Delay creating the timestamp file until here, after we've changed user, so that
900 it has the correct owner to allow updating the mtime later.
901 This means we have to report fatal errors via the pipe. */
902 if ((rc = setup_timestamp()) == -1)
904 send_event(err_pipe[1], EVENT_TIME_ERR, errno, daemon->timestamp_file);
908 if (option_bool(OPT_DNSSEC_IGN_NS))
909 my_syslog(LOG_INFO, _("DNSSEC validation enabled but all unsigned answers are trusted"));
911 my_syslog(LOG_INFO, _("DNSSEC validation enabled"));
913 daemon->dnssec_no_time_check = option_bool(OPT_DNSSEC_TIME);
914 if (option_bool(OPT_DNSSEC_TIME) && !daemon->back_to_the_future)
915 my_syslog(LOG_INFO, _("DNSSEC signature timestamps not checked until receipt of SIGINT"));
918 my_syslog(LOG_INFO, _("DNSSEC signature timestamps not checked until system time valid"));
920 for (ds = daemon->ds; ds; ds = ds->next)
921 my_syslog(LOG_INFO, _("configured with trust anchor for %s keytag %u"),
922 ds->name[0] == 0 ? "<root>" : ds->name, ds->keytag);
927 my_syslog(LOG_WARNING, _("warning: failed to change owner of %s: %s"),
928 daemon->log_file, strerror(log_err));
930 #ifndef HAVE_LINUX_NETWORK
932 my_syslog(LOG_WARNING, _("setting --bind-interfaces option because of OS limitations"));
935 if (option_bool(OPT_NOWILD))
936 warn_bound_listeners();
937 else if (!option_bool(OPT_CLEVERBIND))
942 if (!option_bool(OPT_NOWILD))
943 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
944 if (if_tmp->name && !if_tmp->used)
945 my_syslog(LOG_WARNING, _("warning: interface %s does not currently exist"), if_tmp->name);
947 if (daemon->port != 0 && option_bool(OPT_NO_RESOLV))
949 if (daemon->resolv_files && !daemon->resolv_files->is_default)
950 my_syslog(LOG_WARNING, _("warning: ignoring resolv-file flag because no-resolv is set"));
951 daemon->resolv_files = NULL;
952 if (!daemon->servers)
953 my_syslog(LOG_WARNING, _("warning: no upstream servers configured"));
956 if (daemon->max_logs != 0)
957 my_syslog(LOG_INFO, _("asynchronous logging enabled, queue limit is %d messages"), daemon->max_logs);
961 for (context = daemon->dhcp; context; context = context->next)
962 log_context(AF_INET, context);
964 for (relay = daemon->relay4; relay; relay = relay->next)
965 log_relay(AF_INET, relay);
968 for (context = daemon->dhcp6; context; context = context->next)
969 log_context(AF_INET6, context);
971 for (relay = daemon->relay6; relay; relay = relay->next)
972 log_relay(AF_INET6, relay);
974 if (daemon->doing_dhcp6 || daemon->doing_ra)
975 dhcp_construct_contexts(now);
977 if (option_bool(OPT_RA))
978 my_syslog(MS_DHCP | LOG_INFO, _("IPv6 router advertisement enabled"));
981 # ifdef HAVE_LINUX_NETWORK
983 my_syslog(MS_DHCP | LOG_INFO, _("DHCP, sockets bound exclusively to interface %s"), bound_device);
986 my_syslog(LOG_WARNING, netlink_warn);
989 /* after dhcp_construct_contexts */
990 if (daemon->dhcp || daemon->doing_dhcp6)
991 lease_find_interfaces(now);
995 if (option_bool(OPT_TFTP))
997 struct tftp_prefix *p;
999 my_syslog(MS_TFTP | LOG_INFO, "TFTP %s%s %s %s",
1000 daemon->tftp_prefix ? _("root is ") : _("enabled"),
1001 daemon->tftp_prefix ? daemon->tftp_prefix : "",
1002 option_bool(OPT_TFTP_SECURE) ? _("secure mode") : "",
1003 option_bool(OPT_SINGLE_PORT) ? _("single port mode") : "");
1005 if (tftp_prefix_missing)
1006 my_syslog(MS_TFTP | LOG_WARNING, _("warning: %s inaccessible"), daemon->tftp_prefix);
1008 for (p = daemon->if_prefix; p; p = p->next)
1010 my_syslog(MS_TFTP | LOG_WARNING, _("warning: TFTP directory %s inaccessible"), p->prefix);
1012 /* This is a guess, it assumes that for small limits,
1013 disjoint files might be served, but for large limits,
1014 a single file will be sent to may clients (the file only needs
1017 max_fd -= 30 + daemon->numrrand; /* use other than TFTP */
1021 else if (max_fd < 100 && !option_bool(OPT_SINGLE_PORT))
1024 max_fd = max_fd - 20;
1026 /* if we have to use a limited range of ports,
1027 that will limit the number of transfers */
1028 if (daemon->start_tftp_port != 0 &&
1029 daemon->end_tftp_port - daemon->start_tftp_port + 1 < max_fd)
1030 max_fd = daemon->end_tftp_port - daemon->start_tftp_port + 1;
1032 if (daemon->tftp_max > max_fd)
1034 daemon->tftp_max = max_fd;
1035 my_syslog(MS_TFTP | LOG_WARNING,
1036 _("restricting maximum simultaneous TFTP transfers to %d"),
1042 /* finished start-up - release original process */
1043 if (err_pipe[1] != -1)
1046 if (daemon->port != 0)
1051 daemon->pipe_to_parent = -1;
1052 for (i = 0; i < MAX_PROCS; i++)
1053 daemon->tcp_pipes[i] = -1;
1056 /* Using inotify, have to select a resolv file at startup */
1057 poll_resolv(1, 0, now);
1062 int timeout = fast_retry(now);
1066 /* Whilst polling for the dbus, or doing a tftp transfer, wake every quarter second */
1067 if ((daemon->tftp_trans || (option_bool(OPT_DBUS) && !daemon->dbus)) &&
1068 (timeout == -1 || timeout > 250))
1071 /* Wake every second whilst waiting for DAD to complete */
1072 else if (is_dad_listeners() &&
1073 (timeout == -1 || timeout > 1000))
1076 set_dns_listeners();
1079 if (option_bool(OPT_DBUS))
1080 set_dbus_listeners();
1084 if (option_bool(OPT_UBUS))
1085 set_ubus_listeners();
1089 # if defined(HAVE_LINUX_NETWORK)
1090 if (bind_dhcp_devices(bound_device) & 2)
1092 static int warned = 0;
1095 my_syslog(LOG_ERR, _("error binding DHCP socket to device %s"), bound_device);
1100 if (daemon->dhcp || daemon->relay4)
1102 poll_listen(daemon->dhcpfd, POLLIN);
1103 if (daemon->pxefd != -1)
1104 poll_listen(daemon->pxefd, POLLIN);
1109 if (daemon->doing_dhcp6 || daemon->relay6)
1110 poll_listen(daemon->dhcp6fd, POLLIN);
1112 if (daemon->doing_ra)
1113 poll_listen(daemon->icmp6fd, POLLIN);
1117 if (daemon->inotifyfd != -1)
1118 poll_listen(daemon->inotifyfd, POLLIN);
1121 #if defined(HAVE_LINUX_NETWORK)
1122 poll_listen(daemon->netlinkfd, POLLIN);
1123 #elif defined(HAVE_BSD_NETWORK)
1124 poll_listen(daemon->routefd, POLLIN);
1127 poll_listen(piperead, POLLIN);
1131 while (helper_buf_empty() && do_script_run(now));
1135 if (option_bool(OPT_SCRIPT_ARP))
1136 find_mac(NULL, NULL, 0, now);
1137 while (helper_buf_empty() && do_arp_script_run());
1140 while (helper_buf_empty() && do_tftp_script_run());
1144 while (helper_buf_empty() && do_snoop_script_run());
1147 if (!helper_buf_empty())
1148 poll_listen(daemon->helperfd, POLLOUT);
1150 /* need this for other side-effects */
1152 while (do_script_run(now));
1155 while (do_arp_script_run());
1158 while (do_tftp_script_run());
1164 /* must do this just before do_poll(), when we know no
1165 more calls to my_syslog() can occur */
1168 if (do_poll(timeout) < 0)
1171 now = dnsmasq_time();
1173 check_log_writer(0);
1176 enumerate_interfaces(1);
1178 /* Check the interfaces to see if any have exited DAD state
1179 and if so, bind the address. */
1180 if (is_dad_listeners())
1182 enumerate_interfaces(0);
1183 /* NB, is_dad_listeners() == 1 --> we're binding interfaces */
1184 create_bound_listeners(0);
1185 warn_bound_listeners();
1188 #if defined(HAVE_LINUX_NETWORK)
1189 if (poll_check(daemon->netlinkfd, POLLIN))
1190 netlink_multicast();
1191 #elif defined(HAVE_BSD_NETWORK)
1192 if (poll_check(daemon->routefd, POLLIN))
1197 if (daemon->inotifyfd != -1 && poll_check(daemon->inotifyfd, POLLIN) && inotify_check(now))
1199 if (daemon->port != 0 && !option_bool(OPT_NO_POLL))
1200 poll_resolv(1, 1, now);
1203 /* Check for changes to resolv files once per second max. */
1204 /* Don't go silent for long periods if the clock goes backwards. */
1205 if (daemon->last_resolv == 0 ||
1206 difftime(now, daemon->last_resolv) > 1.0 ||
1207 difftime(now, daemon->last_resolv) < -1.0)
1209 /* poll_resolv doesn't need to reload first time through, since
1210 that's queued anyway. */
1212 poll_resolv(0, daemon->last_resolv != 0, now);
1213 daemon->last_resolv = now;
1217 if (poll_check(piperead, POLLIN))
1218 async_event(piperead, now);
1221 /* if we didn't create a DBus connection, retry now. */
1222 if (option_bool(OPT_DBUS))
1226 char *err = dbus_init();
1229 my_syslog(LOG_INFO, _("connected to system DBus"));
1232 my_syslog(LOG_ERR, _("DBus error: %s"), err);
1233 reset_option_bool(OPT_DBUS); /* fatal error, stop trying. */
1237 check_dbus_listeners();
1242 /* if we didn't create a UBus connection, retry now. */
1243 if (option_bool(OPT_UBUS))
1247 char *err = ubus_init();
1250 my_syslog(LOG_INFO, _("connected to system UBus"));
1253 my_syslog(LOG_ERR, _("UBus error: %s"), err);
1254 reset_option_bool(OPT_UBUS); /* fatal error, stop trying. */
1258 check_ubus_listeners();
1262 check_dns_listeners(now);
1265 check_tftp_listeners(now);
1269 if (daemon->dhcp || daemon->relay4)
1271 if (poll_check(daemon->dhcpfd, POLLIN))
1272 dhcp_packet(now, 0);
1273 if (daemon->pxefd != -1 && poll_check(daemon->pxefd, POLLIN))
1274 dhcp_packet(now, 1);
1278 if ((daemon->doing_dhcp6 || daemon->relay6) && poll_check(daemon->dhcp6fd, POLLIN))
1281 if (daemon->doing_ra && poll_check(daemon->icmp6fd, POLLIN))
1286 if (daemon->helperfd != -1 && poll_check(daemon->helperfd, POLLOUT))
1294 static void sig_handler(int sig)
1298 /* ignore anything other than TERM during startup
1299 and in helper proc. (helper ignore TERM too) */
1300 if (sig == SIGTERM || sig == SIGINT)
1303 else if (pid != getpid())
1305 /* alarm is used to kill TCP children after a fixed time. */
1311 /* master process */
1312 int event, errsave = errno;
1315 event = EVENT_RELOAD;
1316 else if (sig == SIGCHLD)
1317 event = EVENT_CHILD;
1318 else if (sig == SIGALRM)
1319 event = EVENT_ALARM;
1320 else if (sig == SIGTERM)
1322 else if (sig == SIGUSR1)
1324 else if (sig == SIGUSR2)
1325 event = EVENT_REOPEN;
1326 else if (sig == SIGINT)
1328 /* Handle SIGINT normally in debug mode, so
1329 ctrl-c continues to operate. */
1330 if (option_bool(OPT_DEBUG))
1338 send_event(pipewrite, event, 0, NULL);
1343 /* now == 0 -> queue immediate callback */
1344 void send_alarm(time_t event, time_t now)
1346 if (now == 0 || event != 0)
1348 /* alarm(0) or alarm(-ve) doesn't do what we want.... */
1349 if ((now == 0 || difftime(event, now) <= 0.0))
1350 send_event(pipewrite, EVENT_ALARM, 0, NULL);
1352 alarm((unsigned)difftime(event, now));
1356 void queue_event(int event)
1358 send_event(pipewrite, event, 0, NULL);
1361 void send_event(int fd, int event, int data, char *msg)
1363 struct event_desc ev;
1364 struct iovec iov[2];
1368 ev.msg_sz = msg ? strlen(msg) : 0;
1370 iov[0].iov_base = &ev;
1371 iov[0].iov_len = sizeof(ev);
1372 iov[1].iov_base = msg;
1373 iov[1].iov_len = ev.msg_sz;
1375 /* error pipe, debug mode. */
1377 fatal_event(&ev, msg);
1379 /* pipe is non-blocking and struct event_desc is smaller than
1380 PIPE_BUF, so this either fails or writes everything */
1381 while (writev(fd, iov, msg ? 2 : 1) == -1 && errno == EINTR);
1384 /* NOTE: the memory used to return msg is leaked: use msgs in events only
1385 to describe fatal errors. */
1386 static int read_event(int fd, struct event_desc *evp, char **msg)
1390 if (!read_write(fd, (unsigned char *)evp, sizeof(struct event_desc), 1))
1395 if (evp->msg_sz != 0 &&
1396 (buf = malloc(evp->msg_sz + 1)) &&
1397 read_write(fd, (unsigned char *)buf, evp->msg_sz, 1))
1399 buf[evp->msg_sz] = 0;
1406 static void fatal_event(struct event_desc *ev, char *msg)
1415 case EVENT_FORK_ERR:
1416 die(_("cannot fork into background: %s"), NULL, EC_MISC);
1419 case EVENT_PIPE_ERR:
1420 die(_("failed to create helper: %s"), NULL, EC_MISC);
1424 die(_("setting capabilities failed: %s"), NULL, EC_MISC);
1427 case EVENT_USER_ERR:
1428 die(_("failed to change user-id to %s: %s"), msg, EC_MISC);
1431 case EVENT_GROUP_ERR:
1432 die(_("failed to change group-id to %s: %s"), msg, EC_MISC);
1436 die(_("failed to open pidfile %s: %s"), msg, EC_FILE);
1440 die(_("cannot open log %s: %s"), msg, EC_FILE);
1444 die(_("failed to load Lua script: %s"), msg, EC_MISC);
1447 case EVENT_TFTP_ERR:
1448 die(_("TFTP directory %s inaccessible: %s"), msg, EC_FILE);
1451 case EVENT_TIME_ERR:
1452 die(_("cannot create timestamp file %s: %s" ), msg, EC_BADCONF);
1456 static void async_event(int pipe, time_t now)
1459 struct event_desc ev;
1463 /* NOTE: the memory used to return msg is leaked: use msgs in events only
1464 to describe fatal errors. */
1466 if (read_event(pipe, &ev, &msg))
1470 daemon->soa_sn++; /* Bump zone serial, as it may have changed. */
1475 clear_cache_and_reload(now);
1477 if (daemon->port != 0)
1479 if (daemon->resolv_files && option_bool(OPT_NO_POLL))
1481 reload_servers(daemon->resolv_files->name);
1485 if (daemon->servers_file)
1487 read_servers_file();
1501 if (daemon->port != 0)
1507 if (daemon->dhcp || daemon->doing_dhcp6)
1509 lease_prune(NULL, now);
1510 lease_update_file(now);
1513 else if (daemon->doing_ra)
1514 /* Not doing DHCP, so no lease system, manage alarms for ra only */
1515 send_alarm(periodic_ra(now), now);
1521 /* See Stevens 5.10 */
1522 while ((p = waitpid(-1, NULL, WNOHANG)) != 0)
1529 for (i = 0 ; i < MAX_PROCS; i++)
1530 if (daemon->tcp_pids[i] == p)
1531 daemon->tcp_pids[i] = 0;
1534 #if defined(HAVE_SCRIPT)
1536 my_syslog(LOG_WARNING, _("script process killed by signal %d"), ev.data);
1540 my_syslog(LOG_WARNING, _("script process exited with status %d"), ev.data);
1543 case EVENT_EXEC_ERR:
1544 my_syslog(LOG_ERR, _("failed to execute %s: %s"),
1545 daemon->lease_change_command, strerror(ev.data));
1548 case EVENT_SCRIPT_LOG:
1549 my_syslog(MS_SCRIPT | LOG_DEBUG, "%s", msg ? msg : "");
1554 /* necessary for fatal errors in helper */
1555 case EVENT_USER_ERR:
1558 fatal_event(&ev, msg);
1563 /* Note: this may leave TCP-handling processes with the old file still open.
1564 Since any such process will die in CHILD_LIFETIME or probably much sooner,
1565 we leave them logging to the old file. */
1566 if (daemon->log_file != NULL)
1567 log_reopen(daemon->log_file);
1574 case EVENT_NEWROUTE:
1576 /* Force re-reading resolv file right now, for luck. */
1577 poll_resolv(0, 1, now);
1582 if (daemon->dnssec_no_time_check && option_bool(OPT_DNSSEC_VALID) && option_bool(OPT_DNSSEC_TIME))
1584 my_syslog(LOG_INFO, _("now checking DNSSEC signature timestamps"));
1585 daemon->dnssec_no_time_check = 0;
1586 clear_cache_and_reload(now);
1592 /* Knock all our children on the head. */
1593 for (i = 0; i < MAX_PROCS; i++)
1594 if (daemon->tcp_pids[i] != 0)
1595 kill(daemon->tcp_pids[i], SIGALRM);
1597 #if defined(HAVE_SCRIPT) && defined(HAVE_DHCP)
1598 /* handle pending lease transitions */
1599 if (daemon->helperfd != -1)
1601 /* block in writes until all done */
1602 if ((i = fcntl(daemon->helperfd, F_GETFL)) != -1)
1603 while(retry_send(fcntl(daemon->helperfd, F_SETFL, i & ~O_NONBLOCK)));
1606 } while (!helper_buf_empty() || do_script_run(now));
1607 close(daemon->helperfd);
1611 if (daemon->lease_stream)
1612 fclose(daemon->lease_stream);
1615 /* update timestamp file on TERM if time is considered valid */
1616 if (daemon->back_to_the_future)
1618 if (utimes(daemon->timestamp_file, NULL) == -1)
1619 my_syslog(LOG_ERR, _("failed to update mtime on %s: %s"), daemon->timestamp_file, strerror(errno));
1623 if (daemon->runfile)
1624 unlink(daemon->runfile);
1626 #ifdef HAVE_DUMPFILE
1627 if (daemon->dumpfd != -1)
1628 close(daemon->dumpfd);
1631 my_syslog(LOG_INFO, _("exiting on receipt of SIGTERM"));
1637 static void poll_resolv(int force, int do_reload, time_t now)
1639 struct resolvc *res, *latest;
1640 struct stat statbuf;
1641 time_t last_change = 0;
1642 /* There may be more than one possible file.
1643 Go through and find the one which changed _last_.
1644 Warn of any which can't be read. */
1646 if (daemon->port == 0 || option_bool(OPT_NO_POLL))
1649 for (latest = NULL, res = daemon->resolv_files; res; res = res->next)
1650 if (stat(res->name, &statbuf) == -1)
1659 my_syslog(LOG_WARNING, _("failed to access %s: %s"), res->name, strerror(errno));
1662 if (res->mtime != 0)
1664 /* existing file evaporated, force selection of the latest
1665 file even if its mtime hasn't changed since we last looked */
1666 poll_resolv(1, do_reload, now);
1673 if (force || (statbuf.st_mtime != res->mtime || statbuf.st_ino != res->ino))
1675 res->mtime = statbuf.st_mtime;
1676 res->ino = statbuf.st_ino;
1677 if (difftime(statbuf.st_mtime, last_change) > 0.0)
1679 last_change = statbuf.st_mtime;
1687 static int warned = 0;
1688 if (reload_servers(latest->name))
1690 my_syslog(LOG_INFO, _("reading %s"), latest->name);
1693 if (option_bool(OPT_RELOAD) && do_reload)
1694 clear_cache_and_reload(now);
1698 /* If we're delaying things, we don't call check_servers(), but
1699 reload_servers() may have deleted some servers, rendering the server_array
1700 invalid, so just rebuild that here. Once reload_servers() succeeds,
1701 we call check_servers() above, which calls build_server_array itself. */
1702 build_server_array();
1706 my_syslog(LOG_WARNING, _("no servers found in %s, will retry"), latest->name);
1713 void clear_cache_and_reload(time_t now)
1717 if (daemon->port != 0)
1721 if (daemon->dhcp || daemon->doing_dhcp6)
1723 if (option_bool(OPT_ETHERS))
1726 dhcp_update_configs(daemon->dhcp_conf);
1727 lease_update_from_configs();
1728 lease_update_file(now);
1729 lease_update_dns(1);
1732 else if (daemon->doing_ra)
1733 /* Not doing DHCP, so no lease system, manage
1734 alarms for ra only */
1735 send_alarm(periodic_ra(now), now);
1740 static void set_dns_listeners(void)
1742 struct serverfd *serverfdp;
1743 struct listener *listener;
1744 struct randfd_list *rfl;
1749 struct tftp_transfer *transfer;
1750 if (!option_bool(OPT_SINGLE_PORT))
1751 for (transfer = daemon->tftp_trans; transfer; transfer = transfer->next)
1754 poll_listen(transfer->sockfd, POLLIN);
1758 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1759 poll_listen(serverfdp->fd, POLLIN);
1761 for (i = 0; i < daemon->numrrand; i++)
1762 if (daemon->randomsocks[i].refcount != 0)
1763 poll_listen(daemon->randomsocks[i].fd, POLLIN);
1765 /* Check overflow random sockets too. */
1766 for (rfl = daemon->rfl_poll; rfl; rfl = rfl->next)
1767 poll_listen(rfl->rfd->fd, POLLIN);
1769 /* check to see if we have free tcp process slots. */
1770 for (i = MAX_PROCS - 1; i >= 0; i--)
1771 if (daemon->tcp_pids[i] == 0 && daemon->tcp_pipes[i] == -1)
1774 for (listener = daemon->listeners; listener; listener = listener->next)
1776 if (listener->fd != -1)
1777 poll_listen(listener->fd, POLLIN);
1779 /* Only listen for TCP connections when a process slot
1780 is available. Death of a child goes through the select loop, so
1781 we don't need to explicitly arrange to wake up here,
1782 we'll be called again when a slot becomes available. */
1783 if (listener->tcpfd != -1 && i >= 0)
1784 poll_listen(listener->tcpfd, POLLIN);
1787 /* tftp == 0 in single-port mode. */
1788 if (tftp <= daemon->tftp_max && listener->tftpfd != -1)
1789 poll_listen(listener->tftpfd, POLLIN);
1793 if (!option_bool(OPT_DEBUG))
1794 for (i = 0; i < MAX_PROCS; i++)
1795 if (daemon->tcp_pipes[i] != -1)
1796 poll_listen(daemon->tcp_pipes[i], POLLIN);
1799 static void check_dns_listeners(time_t now)
1801 struct serverfd *serverfdp;
1802 struct listener *listener;
1803 struct randfd_list *rfl;
1807 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1808 if (poll_check(serverfdp->fd, POLLIN))
1809 reply_query(serverfdp->fd, now);
1811 for (i = 0; i < daemon->numrrand; i++)
1812 if (daemon->randomsocks[i].refcount != 0 &&
1813 poll_check(daemon->randomsocks[i].fd, POLLIN))
1814 reply_query(daemon->randomsocks[i].fd, now);
1816 /* Check overflow random sockets too. */
1817 for (rfl = daemon->rfl_poll; rfl; rfl = rfl->next)
1818 if (poll_check(rfl->rfd->fd, POLLIN))
1819 reply_query(rfl->rfd->fd, now);
1821 /* Races. The child process can die before we read all of the data from the
1822 pipe, or vice versa. Therefore send tcp_pids to zero when we wait() the
1823 process, and tcp_pipes to -1 and close the FD when we read the last
1824 of the data - indicated by cache_recv_insert returning zero.
1825 The order of these events is indeterminate, and both are needed
1826 to free the process slot. Once the child process has gone, poll()
1827 returns POLLHUP, not POLLIN, so have to check for both here. */
1828 if (!option_bool(OPT_DEBUG))
1829 for (i = 0; i < MAX_PROCS; i++)
1830 if (daemon->tcp_pipes[i] != -1 &&
1831 poll_check(daemon->tcp_pipes[i], POLLIN | POLLHUP) &&
1832 !cache_recv_insert(now, daemon->tcp_pipes[i]))
1834 close(daemon->tcp_pipes[i]);
1835 daemon->tcp_pipes[i] = -1;
1838 for (listener = daemon->listeners; listener; listener = listener->next)
1840 if (listener->fd != -1 && poll_check(listener->fd, POLLIN))
1841 receive_query(listener, now);
1844 if (listener->tftpfd != -1 && poll_check(listener->tftpfd, POLLIN))
1845 tftp_request(listener, now);
1848 /* check to see if we have a free tcp process slot.
1849 Note that we can't assume that because we had
1850 at least one a poll() time, that we still do.
1851 There may be more waiting connections after
1852 poll() returns then free process slots. */
1853 for (i = MAX_PROCS - 1; i >= 0; i--)
1854 if (daemon->tcp_pids[i] == 0 && daemon->tcp_pipes[i] == -1)
1857 if (listener->tcpfd != -1 && i >= 0 && poll_check(listener->tcpfd, POLLIN))
1859 int confd, client_ok = 1;
1860 struct irec *iface = NULL;
1862 union mysockaddr tcp_addr;
1863 socklen_t tcp_len = sizeof(union mysockaddr);
1865 while ((confd = accept(listener->tcpfd, NULL, NULL)) == -1 && errno == EINTR);
1870 if (getsockname(confd, (struct sockaddr *)&tcp_addr, &tcp_len) == -1)
1876 /* Make sure that the interface list is up-to-date.
1878 We do this here as we may need the results below, and
1879 the DNS code needs them for --interface-name stuff.
1881 Multiple calls to enumerate_interfaces() per select loop are
1882 inhibited, so calls to it in the child process (which doesn't select())
1883 have no effect. This avoids two processes reading from the same
1884 netlink fd and screwing the pooch entirely.
1887 enumerate_interfaces(0);
1889 if (option_bool(OPT_NOWILD))
1890 iface = listener->iface; /* May be NULL */
1894 char intr_name[IF_NAMESIZE];
1896 /* if we can find the arrival interface, check it's one that's allowed */
1897 if ((if_index = tcp_interface(confd, tcp_addr.sa.sa_family)) != 0 &&
1898 indextoname(listener->tcpfd, if_index, intr_name))
1900 union all_addr addr;
1902 if (tcp_addr.sa.sa_family == AF_INET6)
1903 addr.addr6 = tcp_addr.in6.sin6_addr;
1905 addr.addr4 = tcp_addr.in.sin_addr;
1907 for (iface = daemon->interfaces; iface; iface = iface->next)
1908 if (iface->index == if_index &&
1909 iface->addr.sa.sa_family == tcp_addr.sa.sa_family)
1912 if (!iface && !loopback_exception(listener->tcpfd, tcp_addr.sa.sa_family, &addr, intr_name))
1916 if (option_bool(OPT_CLEVERBIND))
1917 iface = listener->iface; /* May be NULL */
1920 /* Check for allowed interfaces when binding the wildcard address:
1921 we do this by looking for an interface with the same address as
1922 the local address of the TCP connection, then looking to see if that's
1923 an allowed interface. As a side effect, we get the netmask of the
1924 interface too, for localisation. */
1926 for (iface = daemon->interfaces; iface; iface = iface->next)
1927 if (sockaddr_isequal(&iface->addr, &tcp_addr))
1937 shutdown(confd, SHUT_RDWR);
1940 else if (!option_bool(OPT_DEBUG) && pipe(pipefd) == 0 && (p = fork()) != 0)
1942 close(pipefd[1]); /* parent needs read pipe end. */
1947 #ifdef HAVE_LINUX_NETWORK
1948 /* The child process inherits the netlink socket,
1949 which it never uses, but when the parent (us)
1950 uses it in the future, the answer may go to the
1951 child, resulting in the parent blocking
1952 forever awaiting the result. To avoid this
1953 the child closes the netlink socket, but there's
1954 a nasty race, since the parent may use netlink
1955 before the child has done the close.
1957 To avoid this, the parent blocks here until a
1958 single byte comes back up the pipe, which
1959 is sent by the child after it has closed the
1963 read_write(pipefd[0], &a, 1, 1);
1966 /* i holds index of free slot */
1967 daemon->tcp_pids[i] = p;
1968 daemon->tcp_pipes[i] = pipefd[0];
1972 /* The child can use up to TCP_MAX_QUERIES ids, so skip that many. */
1973 daemon->log_id += TCP_MAX_QUERIES;
1977 unsigned char *buff;
1980 struct in_addr netmask;
1985 netmask = iface->netmask;
1986 auth_dns = iface->dns_auth;
1994 /* Arrange for SIGALRM after CHILD_LIFETIME seconds to
1995 terminate the process. */
1996 if (!option_bool(OPT_DEBUG))
1998 #ifdef HAVE_LINUX_NETWORK
1999 /* See comment above re: netlink socket. */
2000 unsigned char a = 0;
2002 close(daemon->netlinkfd);
2003 read_write(pipefd[1], &a, 1, 0);
2005 alarm(CHILD_LIFETIME);
2006 close(pipefd[0]); /* close read end in child. */
2007 daemon->pipe_to_parent = pipefd[1];
2010 /* start with no upstream connections. */
2011 for (s = daemon->servers; s; s = s->next)
2014 /* The connected socket inherits non-blocking
2015 attribute from the listening socket.
2017 if ((flags = fcntl(confd, F_GETFL, 0)) != -1)
2018 while(retry_send(fcntl(confd, F_SETFL, flags & ~O_NONBLOCK)));
2020 buff = tcp_request(confd, now, &tcp_addr, netmask, auth_dns);
2025 for (s = daemon->servers; s; s = s->next)
2028 shutdown(s->tcpfd, SHUT_RDWR);
2032 if (!option_bool(OPT_DEBUG))
2034 close(daemon->pipe_to_parent);
2044 int make_icmp_sock(void)
2049 if ((fd = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
2052 setsockopt(fd, SOL_SOCKET, SO_DONTROUTE, &zeroopt, sizeof(zeroopt)) == -1)
2062 int icmp_ping(struct in_addr addr)
2064 /* Try and get an ICMP echo from a machine. */
2067 struct sockaddr_in saddr;
2072 unsigned short id = rand16();
2076 #if defined(HAVE_LINUX_NETWORK) || defined (HAVE_SOLARIS_NETWORK)
2077 if ((fd = make_icmp_sock()) == -1)
2081 fd = daemon->dhcp_icmp_fd;
2082 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
2085 saddr.sin_family = AF_INET;
2087 saddr.sin_addr = addr;
2088 #ifdef HAVE_SOCKADDR_SA_LEN
2089 saddr.sin_len = sizeof(struct sockaddr_in);
2092 memset(&packet.icmp, 0, sizeof(packet.icmp));
2093 packet.icmp.icmp_type = ICMP_ECHO;
2094 packet.icmp.icmp_id = id;
2095 for (j = 0, i = 0; i < sizeof(struct icmp) / 2; i++)
2096 j += ((u16 *)&packet.icmp)[i];
2098 j = (j & 0xffff) + (j >> 16);
2099 packet.icmp.icmp_cksum = (j == 0xffff) ? j : ~j;
2101 while (retry_send(sendto(fd, (char *)&packet.icmp, sizeof(struct icmp), 0,
2102 (struct sockaddr *)&saddr, sizeof(saddr))));
2104 gotreply = delay_dhcp(dnsmasq_time(), PING_WAIT, fd, addr.s_addr, id);
2106 #if defined(HAVE_LINUX_NETWORK) || defined(HAVE_SOLARIS_NETWORK)
2110 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
2116 int delay_dhcp(time_t start, int sec, int fd, uint32_t addr, unsigned short id)
2118 /* Delay processing DHCP packets for "sec" seconds counting from "start".
2119 If "fd" is not -1 it will stop waiting if an ICMP echo reply is received
2120 from "addr" with ICMP ID "id" and return 1 */
2122 /* Note that whilst waiting, we check for
2123 (and service) events on the DNS and TFTP sockets, (so doing that
2124 better not use any resources our caller has in use...)
2125 but we remain deaf to signals or further DHCP packets. */
2127 /* There can be a problem using dnsmasq_time() to end the loop, since
2128 it's not monotonic, and can go backwards if the system clock is
2129 tweaked, leading to the code getting stuck in this loop and
2130 ignoring DHCP requests. To fix this, we check to see if select returned
2131 as a result of a timeout rather than a socket becoming available. We
2132 only allow this to happen as many times as it takes to get to the wait time
2133 in quarter-second chunks. This provides a fallback way to end loop. */
2135 int rc, timeout_count;
2138 for (now = dnsmasq_time(), timeout_count = 0;
2139 (difftime(now, start) <= (float)sec) && (timeout_count < sec * 4);)
2143 poll_listen(fd, POLLIN);
2144 set_dns_listeners();
2148 if (daemon->doing_ra)
2149 poll_listen(daemon->icmp6fd, POLLIN);
2159 now = dnsmasq_time();
2161 check_log_writer(0);
2162 check_dns_listeners(now);
2165 if (daemon->doing_ra && poll_check(daemon->icmp6fd, POLLIN))
2170 check_tftp_listeners(now);
2179 struct sockaddr_in faddr;
2180 socklen_t len = sizeof(faddr);
2182 if (poll_check(fd, POLLIN) &&
2183 recvfrom(fd, &packet, sizeof(packet), 0, (struct sockaddr *)&faddr, &len) == sizeof(packet) &&
2184 addr == faddr.sin_addr.s_addr &&
2185 packet.icmp.icmp_type == ICMP_ECHOREPLY &&
2186 packet.icmp.icmp_seq == 0 &&
2187 packet.icmp.icmp_id == id)
2194 #endif /* HAVE_DHCP */