1 /* dnsmasq is Copyright (c) 2000-2015 Simon Kelley
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; version 2 dated June, 1991, or
6 (at your option) version 3 dated 29 June, 2007.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 /* Jon Zarate AFAIK wrote the original Tomato specific code, primarily to
17 support extra info in the GUI. Following is a vague clue as to how it
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
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;
77 struct sigaction sigact
;
79 int piperead
, pipefd
[2], err_pipe
[2];
80 struct passwd
*ent_pw
= NULL
;
81 #if defined(HAVE_SCRIPT)
85 struct group
*gp
= NULL
;
86 long i
, max_fd
= sysconf(_SC_OPEN_MAX
);
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
;
95 #if defined(HAVE_DHCP) || defined(HAVE_DHCP6)
96 struct dhcp_context
*context
;
97 struct dhcp_relay
*relay
;
100 int tftp_prefix_missing
= 0;
104 setlocale(LC_ALL
, "");
105 bindtextdomain("dnsmasq", LOCALEDIR
);
106 textdomain("dnsmasq");
109 sigact
.sa_handler
= sig_handler
;
111 sigemptyset(&sigact
.sa_mask
);
112 sigaction(SIGUSR1
, &sigact
, NULL
);
113 sigaction(SIGUSR2
, &sigact
, NULL
);
114 sigaction(SIGHUP
, &sigact
, NULL
);
115 sigaction(SIGTERM
, &sigact
, NULL
);
116 sigaction(SIGALRM
, &sigact
, NULL
);
117 sigaction(SIGCHLD
, &sigact
, NULL
);
120 sigact
.sa_handler
= SIG_IGN
;
121 sigaction(SIGPIPE
, &sigact
, NULL
);
123 umask(022); /* known umask, create leases and pid files as 0644 */
125 rand_init(); /* Must precede read_opts() */
127 read_opts(argc
, argv
, compile_opts
);
129 if (daemon
->edns_pktsz
< PACKETSZ
)
130 daemon
->edns_pktsz
= PACKETSZ
;
132 daemon
->packet_buff_sz
= daemon
->edns_pktsz
> DNSMASQ_PACKETSZ
?
133 daemon
->edns_pktsz
: DNSMASQ_PACKETSZ
;
134 daemon
->packet
= safe_malloc(daemon
->packet_buff_sz
);
136 daemon
->addrbuff
= safe_malloc(ADDRSTRLEN
);
137 if (option_bool(OPT_EXTRALOG
))
138 daemon
->addrbuff2
= safe_malloc(ADDRSTRLEN
);
141 if (option_bool(OPT_DNSSEC_VALID
))
143 /* Note that both /000 and '.' are allowed within labels. These get
144 represented in presentation format using NAME_ESCAPE as an escape
145 character when in DNSSEC mode.
146 In theory, if all the characters in a name were /000 or
147 '.' or NAME_ESCAPE then all would have to be escaped, so the
148 presentation format would be twice as long as the spec.
150 daemon->namebuff was previously allocated by the option-reading
151 code before we knew if we're in DNSSEC mode, so reallocate here. */
152 free(daemon
->namebuff
);
153 daemon
->namebuff
= safe_malloc(MAXDNAME
* 2);
154 daemon
->keyname
= safe_malloc(MAXDNAME
* 2);
155 daemon
->workspacename
= safe_malloc(MAXDNAME
* 2);
160 if (!daemon
->lease_file
)
162 if (daemon
->dhcp
|| daemon
->dhcp6
)
163 daemon
->lease_file
= LEASEFILE
;
167 /* Close any file descriptors we inherited apart from std{in|out|err}
169 Ensure that at least stdin, stdout and stderr (fd 0, 1, 2) exist,
170 otherwise file descriptors we create can end up being 0, 1, or 2
171 and then get accidentally closed later when we make 0, 1, and 2
172 open to /dev/null. Normally we'll be started with 0, 1 and 2 open,
173 but it's not guaranteed. By opening /dev/null three times, we
174 ensure that we're not using those fds for real stuff. */
175 for (i
= 0; i
< max_fd
; i
++)
176 if (i
!= STDOUT_FILENO
&& i
!= STDERR_FILENO
&& i
!= STDIN_FILENO
)
179 open("/dev/null", O_RDWR
);
181 #ifndef HAVE_LINUX_NETWORK
182 # if !(defined(IP_RECVDSTADDR) && defined(IP_RECVIF) && defined(IP_SENDSRCADDR))
183 if (!option_bool(OPT_NOWILD
))
186 set_option_bool(OPT_NOWILD
);
190 /* -- bind-dynamic not supported on !Linux, fall back to --bind-interfaces */
191 if (option_bool(OPT_CLEVERBIND
))
194 set_option_bool(OPT_NOWILD
);
195 reset_option_bool(OPT_CLEVERBIND
);
200 if (daemon
->dynamic_dirs
)
201 die(_("dhcp-hostsdir, dhcp-optsdir and hostsdir are not supported on this platform"), NULL
, EC_BADCONF
);
204 if (option_bool(OPT_DNSSEC_VALID
))
208 die(_("no trust anchors provided for DNSSEC"), NULL
, EC_BADCONF
);
210 if (daemon
->cachesize
< CACHESIZ
)
211 die(_("cannot reduce cache size from default when DNSSEC enabled"), NULL
, EC_BADCONF
);
213 die(_("DNSSEC not available: set HAVE_DNSSEC in src/config.h"), NULL
, EC_BADCONF
);
218 if (option_bool(OPT_TFTP
))
219 die(_("TFTP server not available: set HAVE_TFTP in src/config.h"), NULL
, EC_BADCONF
);
222 #ifdef HAVE_CONNTRACK
223 if (option_bool(OPT_CONNTRACK
) && (daemon
->query_port
!= 0 || daemon
->osport
))
224 die (_("cannot use --conntrack AND --query-port"), NULL
, EC_BADCONF
);
226 if (option_bool(OPT_CONNTRACK
))
227 die(_("conntrack support not available: set HAVE_CONNTRACK in src/config.h"), NULL
, EC_BADCONF
);
230 #ifdef HAVE_SOLARIS_NETWORK
231 if (daemon
->max_logs
!= 0)
232 die(_("asychronous logging is not available under Solaris"), NULL
, EC_BADCONF
);
236 if (daemon
->max_logs
!= 0)
237 die(_("asychronous logging is not available under Android"), NULL
, EC_BADCONF
);
241 if (daemon
->authserver
)
242 die(_("authoritative DNS not available: set HAVE_AUTH in src/config.h"), NULL
, EC_BADCONF
);
246 if (option_bool(OPT_LOOP_DETECT
))
247 die(_("loop detection not available: set HAVE_LOOP in src/config.h"), NULL
, EC_BADCONF
);
250 now
= dnsmasq_time();
252 /* Create a serial at startup if not configured. */
253 if (daemon
->authinterface
&& daemon
->soa_sn
== 0)
254 #ifdef HAVE_BROKEN_RTC
255 die(_("zone serial must be configured in --auth-soa"), NULL
, EC_BADCONF
);
257 daemon
->soa_sn
= now
;
263 daemon
->doing_ra
= option_bool(OPT_RA
);
265 for (context
= daemon
->dhcp6
; context
; context
= context
->next
)
267 if (context
->flags
& CONTEXT_DHCP
)
268 daemon
->doing_dhcp6
= 1;
269 if (context
->flags
& CONTEXT_RA
)
270 daemon
->doing_ra
= 1;
271 #if !defined(HAVE_LINUX_NETWORK) && !defined(HAVE_BSD_NETWORK)
272 if (context
->flags
& CONTEXT_TEMPLATE
)
273 die (_("dhcp-range constructor not available on this platform"), NULL
, EC_BADCONF
);
280 /* Note that order matters here, we must call lease_init before
281 creating any file descriptors which shouldn't be leaked
282 to the lease-script init process. We need to call common_init
283 before lease_init to allocate buffers it uses.*/
284 if (daemon
->dhcp
|| daemon
->doing_dhcp6
|| daemon
->relay4
|| daemon
->relay6
)
287 if (daemon
->dhcp
|| daemon
->doing_dhcp6
)
291 if (daemon
->dhcp
|| daemon
->relay4
)
295 if (daemon
->doing_ra
|| daemon
->doing_dhcp6
|| daemon
->relay6
)
298 if (daemon
->doing_dhcp6
|| daemon
->relay6
)
309 #if defined(HAVE_LINUX_NETWORK)
311 #elif defined(HAVE_BSD_NETWORK)
315 if (option_bool(OPT_NOWILD
) && option_bool(OPT_CLEVERBIND
))
316 die(_("cannot set --bind-interfaces and --bind-dynamic"), NULL
, EC_BADCONF
);
318 if (!enumerate_interfaces(1) || !enumerate_interfaces(0))
319 die(_("failed to find list of interfaces: %s"), NULL
, EC_MISC
);
321 if (option_bool(OPT_NOWILD
) || option_bool(OPT_CLEVERBIND
))
323 create_bound_listeners(1);
325 if (!option_bool(OPT_CLEVERBIND
))
326 for (if_tmp
= daemon
->if_names
; if_tmp
; if_tmp
= if_tmp
->next
)
327 if (if_tmp
->name
&& !if_tmp
->used
)
328 die(_("unknown interface %s"), if_tmp
->name
, EC_BADNET
);
330 #if defined(HAVE_LINUX_NETWORK) && defined(HAVE_DHCP)
331 /* after enumerate_interfaces() */
332 bound_device
= whichdevice();
336 if (!daemon
->relay4
&& bound_device
)
338 bindtodevice(bound_device
, daemon
->dhcpfd
);
341 if (daemon
->enable_pxe
&& bound_device
)
343 bindtodevice(bound_device
, daemon
->pxefd
);
349 #if defined(HAVE_LINUX_NETWORK) && defined(HAVE_DHCP6)
350 if (daemon
->doing_dhcp6
&& !daemon
->relay6
&& bound_device
)
352 bindtodevice(bound_device
, daemon
->dhcp6fd
);
358 create_wildcard_listeners();
361 /* after enumerate_interfaces() */
362 if (daemon
->doing_dhcp6
|| daemon
->relay6
|| daemon
->doing_ra
)
365 /* After netlink_init() and before create_helper() */
366 lease_make_duid(now
);
369 if (daemon
->port
!= 0)
379 if (daemon
->port
!= 0 || daemon
->dhcp
|| daemon
->doing_dhcp6
)
380 inotify_dnsmasq_init();
382 daemon
->inotifyfd
= -1;
385 if (option_bool(OPT_DBUS
))
390 daemon
->watches
= NULL
;
391 if ((err
= dbus_init()))
392 die(_("DBus error: %s"), err
, EC_MISC
);
395 die(_("DBus not available: set HAVE_DBUS in src/config.h"), NULL
, EC_BADCONF
);
398 if (daemon
->port
!= 0)
401 #if defined(HAVE_SCRIPT)
402 /* Note getpwnam returns static storage */
403 if ((daemon
->dhcp
|| daemon
->dhcp6
) &&
404 daemon
->scriptuser
&&
405 (daemon
->lease_change_command
|| daemon
->luascript
))
407 if ((ent_pw
= getpwnam(daemon
->scriptuser
)))
409 script_uid
= ent_pw
->pw_uid
;
410 script_gid
= ent_pw
->pw_gid
;
413 baduser
= daemon
->scriptuser
;
417 if (daemon
->username
&& !(ent_pw
= getpwnam(daemon
->username
)))
418 baduser
= daemon
->username
;
419 else if (daemon
->groupname
&& !(gp
= getgrnam(daemon
->groupname
)))
420 baduser
= daemon
->groupname
;
423 die(_("unknown user or group: %s"), baduser
, EC_BADCONF
);
425 /* implement group defaults, "dip" if available, or group associated with uid */
426 if (!daemon
->group_set
&& !gp
)
428 if (!(gp
= getgrnam(CHGRP
)) && ent_pw
)
429 gp
= getgrgid(ent_pw
->pw_gid
);
431 /* for error message */
433 daemon
->groupname
= gp
->gr_name
;
436 #if defined(HAVE_LINUX_NETWORK)
437 /* determine capability API version here, while we can still
439 if (ent_pw
&& ent_pw
->pw_uid
!= 0)
441 int capsize
= 1; /* for header version 1 */
442 hdr
= safe_malloc(sizeof(*hdr
));
444 /* find version supported by kernel */
445 memset(hdr
, 0, sizeof(*hdr
));
448 if (hdr
->version
!= LINUX_CAPABILITY_VERSION_1
)
450 /* if unknown version, use largest supported version (3) */
451 if (hdr
->version
!= LINUX_CAPABILITY_VERSION_2
)
452 hdr
->version
= LINUX_CAPABILITY_VERSION_3
;
456 data
= safe_malloc(sizeof(*data
) * capsize
);
457 memset(data
, 0, sizeof(*data
) * capsize
);
461 /* Use a pipe to carry signals and other events back to the event loop
462 in a race-free manner and another to carry errors to daemon-invoking process */
463 safe_pipe(pipefd
, 1);
465 piperead
= pipefd
[0];
466 pipewrite
= pipefd
[1];
467 /* prime the pipe to load stuff first time. */
468 send_event(pipewrite
, EVENT_INIT
, 0, NULL
);
472 if (!option_bool(OPT_DEBUG
))
474 /* The following code "daemonizes" the process.
475 See Stevens section 12.4 */
478 die(_("cannot chdir to filesystem root: %s"), NULL
, EC_MISC
);
481 if (!option_bool(OPT_NO_FORK
))
485 /* pipe to carry errors back to original process.
486 When startup is complete we close this and the process terminates. */
487 safe_pipe(err_pipe
, 0);
489 if ((pid
= fork()) == -1)
490 /* fd == -1 since we've not forked, never returns. */
491 send_event(-1, EVENT_FORK_ERR
, errno
, NULL
);
495 struct event_desc ev
;
498 /* close our copy of write-end */
499 while (retry_send(close(err_pipe
[1])));
501 /* check for errors after the fork */
502 if (read_event(err_pipe
[0], &ev
, &msg
))
503 fatal_event(&ev
, msg
);
508 while (retry_send(close(err_pipe
[0])));
510 /* NO calls to die() from here on. */
514 if ((pid
= fork()) == -1)
515 send_event(err_pipe
[1], EVENT_FORK_ERR
, errno
, NULL
);
522 /* write pidfile _after_ forking ! */
527 sprintf(daemon
->namebuff
, "%d\n", (int) getpid());
529 /* Explanation: Some installations of dnsmasq (eg Debian/Ubuntu) locate the pid-file
530 in a directory which is writable by the non-privileged user that dnsmasq runs as. This
531 allows the daemon to delete the file as part of its shutdown. This is a security hole to the
532 extent that an attacker running as the unprivileged user could replace the pidfile with a
533 symlink, and have the target of that symlink overwritten as root next time dnsmasq starts.
535 The folowing code first deletes any existing file, and then opens it with the O_EXCL flag,
536 ensuring that the open() fails should there be any existing file (because the unlink() failed,
537 or an attacker exploited the race between unlink() and open()). This ensures that no symlink
540 Any compromise of the non-privileged user still theoretically allows the pid-file to be
541 replaced whilst dnsmasq is running. The worst that could allow is that the usual
542 "shutdown dnsmasq" shell command could be tricked into stopping any other process.
544 Note that if dnsmasq is started as non-root (eg for testing) it silently ignores
545 failure to write the pid-file.
548 unlink(daemon
->runfile
);
550 if ((fd
= open(daemon
->runfile
, O_WRONLY
|O_CREAT
|O_TRUNC
|O_EXCL
, S_IWUSR
|S_IRUSR
|S_IRGRP
|S_IROTH
)) == -1)
552 /* only complain if started as root */
558 if (!read_write(fd
, (unsigned char *)daemon
->namebuff
, strlen(daemon
->namebuff
), 0))
562 while (retry_send(close(fd
)));
570 send_event(err_pipe
[1], EVENT_PIDFILE
, errno
, daemon
->runfile
);
576 log_err
= log_start(ent_pw
, err_pipe
[1]);
578 if (!option_bool(OPT_DEBUG
))
580 /* open stdout etc to /dev/null */
581 int nullfd
= open("/dev/null", O_RDWR
);
582 dup2(nullfd
, STDOUT_FILENO
);
583 dup2(nullfd
, STDERR_FILENO
);
584 dup2(nullfd
, STDIN_FILENO
);
588 /* if we are to run scripts, we need to fork a helper before dropping root. */
589 daemon
->helperfd
= -1;
591 if ((daemon
->dhcp
|| daemon
->dhcp6
) && (daemon
->lease_change_command
|| daemon
->luascript
))
592 daemon
->helperfd
= create_helper(pipewrite
, err_pipe
[1], script_uid
, script_gid
, max_fd
);
595 if (!option_bool(OPT_DEBUG
) && getuid() == 0)
597 int bad_capabilities
= 0;
600 /* remove all supplimentary groups */
602 (setgroups(0, &dummy
) == -1 ||
603 setgid(gp
->gr_gid
) == -1))
605 send_event(err_pipe
[1], EVENT_GROUP_ERR
, errno
, daemon
->groupname
);
609 if (ent_pw
&& ent_pw
->pw_uid
!= 0)
611 #if defined(HAVE_LINUX_NETWORK)
612 /* On linux, we keep CAP_NETADMIN (for ARP-injection) and
613 CAP_NET_RAW (for icmp) if we're doing dhcp. If we have yet to bind
614 ports because of DAD, or we're doing it dynamically,
615 we need CAP_NET_BIND_SERVICE too. */
616 if (is_dad_listeners() || option_bool(OPT_CLEVERBIND
))
617 data
->effective
= data
->permitted
= data
->inheritable
=
618 (1 << CAP_NET_ADMIN
) | (1 << CAP_NET_RAW
) |
619 (1 << CAP_SETUID
) | (1 << CAP_NET_BIND_SERVICE
);
621 data
->effective
= data
->permitted
= data
->inheritable
=
622 (1 << CAP_NET_ADMIN
) | (1 << CAP_NET_RAW
) | (1 << CAP_SETUID
);
624 /* Tell kernel to not clear capabilities when dropping root */
625 if (capset(hdr
, data
) == -1 || prctl(PR_SET_KEEPCAPS
, 1, 0, 0, 0) == -1)
626 bad_capabilities
= errno
;
628 #elif defined(HAVE_SOLARIS_NETWORK)
629 /* http://developers.sun.com/solaris/articles/program_privileges.html */
630 priv_set_t
*priv_set
;
632 if (!(priv_set
= priv_str_to_set("basic", ",", NULL
)) ||
633 priv_addset(priv_set
, PRIV_NET_ICMPACCESS
) == -1 ||
634 priv_addset(priv_set
, PRIV_SYS_NET_CONFIG
) == -1)
635 bad_capabilities
= errno
;
637 if (priv_set
&& bad_capabilities
== 0)
639 priv_inverse(priv_set
);
641 if (setppriv(PRIV_OFF
, PRIV_LIMIT
, priv_set
) == -1)
642 bad_capabilities
= errno
;
646 priv_freeset(priv_set
);
650 if (bad_capabilities
!= 0)
652 send_event(err_pipe
[1], EVENT_CAP_ERR
, bad_capabilities
, NULL
);
656 /* finally drop root */
657 if (setuid(ent_pw
->pw_uid
) == -1)
659 send_event(err_pipe
[1], EVENT_USER_ERR
, errno
, daemon
->username
);
663 #ifdef HAVE_LINUX_NETWORK
664 if (is_dad_listeners() || option_bool(OPT_CLEVERBIND
))
665 data
->effective
= data
->permitted
=
666 (1 << CAP_NET_ADMIN
) | (1 << CAP_NET_RAW
) | (1 << CAP_NET_BIND_SERVICE
);
668 data
->effective
= data
->permitted
=
669 (1 << CAP_NET_ADMIN
) | (1 << CAP_NET_RAW
);
670 data
->inheritable
= 0;
672 /* lose the setuid and setgid capbilities */
673 if (capset(hdr
, data
) == -1)
675 send_event(err_pipe
[1], EVENT_CAP_ERR
, errno
, NULL
);
683 #ifdef HAVE_LINUX_NETWORK
686 if (option_bool(OPT_DEBUG
))
687 prctl(PR_SET_DUMPABLE
, 1, 0, 0, 0);
691 if (option_bool(OPT_TFTP
))
694 struct tftp_prefix
*p
;
696 if (daemon
->tftp_prefix
)
698 if (!((dir
= opendir(daemon
->tftp_prefix
))))
700 tftp_prefix_missing
= 1;
701 if (!option_bool(OPT_TFTP_NO_FAIL
))
703 send_event(err_pipe
[1], EVENT_TFTP_ERR
, errno
, daemon
->tftp_prefix
);
711 for (p
= daemon
->if_prefix
; p
; p
= p
->next
)
714 if (!((dir
= opendir(p
->prefix
))))
717 if (!option_bool(OPT_TFTP_NO_FAIL
))
719 send_event(err_pipe
[1], EVENT_TFTP_ERR
, errno
, p
->prefix
);
729 if (daemon
->port
== 0)
730 my_syslog(LOG_INFO
, _("started, version %s DNS disabled"), VERSION
);
731 else if (daemon
->cachesize
!= 0)
732 my_syslog(LOG_INFO
, _("started, version %s cachesize %d"), VERSION
, daemon
->cachesize
);
734 my_syslog(LOG_INFO
, _("started, version %s cache disabled"), VERSION
);
736 my_syslog(LOG_INFO
, _("compile time options: %s"), compile_opts
);
739 if (option_bool(OPT_DBUS
))
742 my_syslog(LOG_INFO
, _("DBus support enabled: connected to system bus"));
744 my_syslog(LOG_INFO
, _("DBus support enabled: bus connection pending"));
748 if (option_bool(OPT_LOCAL_SERVICE
))
749 my_syslog(LOG_INFO
, _("DNS service limited to local subnets"));
752 if (option_bool(OPT_DNSSEC_VALID
))
756 /* Delay creating the timestamp file until here, after we've changed user, so that
757 it has the correct owner to allow updating the mtime later.
758 This means we have to report fatal errors via the pipe. */
759 if ((rc
= setup_timestamp()) == -1)
761 send_event(err_pipe
[1], EVENT_TIME_ERR
, errno
, daemon
->timestamp_file
);
765 my_syslog(LOG_INFO
, _("DNSSEC validation enabled"));
767 if (option_bool(OPT_DNSSEC_TIME
))
768 my_syslog(LOG_INFO
, _("DNSSEC signature timestamps not checked until first cache reload"));
771 my_syslog(LOG_INFO
, _("DNSSEC signature timestamps not checked until system time valid"));
776 my_syslog(LOG_WARNING
, _("warning: failed to change owner of %s: %s"),
777 daemon
->log_file
, strerror(log_err
));
780 my_syslog(LOG_WARNING
, _("setting --bind-interfaces option because of OS limitations"));
782 if (option_bool(OPT_NOWILD
))
783 warn_bound_listeners();
787 if (!option_bool(OPT_NOWILD
))
788 for (if_tmp
= daemon
->if_names
; if_tmp
; if_tmp
= if_tmp
->next
)
789 if (if_tmp
->name
&& !if_tmp
->used
)
790 my_syslog(LOG_WARNING
, _("warning: interface %s does not currently exist"), if_tmp
->name
);
792 if (daemon
->port
!= 0 && option_bool(OPT_NO_RESOLV
))
794 if (daemon
->resolv_files
&& !daemon
->resolv_files
->is_default
)
795 my_syslog(LOG_WARNING
, _("warning: ignoring resolv-file flag because no-resolv is set"));
796 daemon
->resolv_files
= NULL
;
797 if (!daemon
->servers
)
798 my_syslog(LOG_WARNING
, _("warning: no upstream servers configured"));
801 if (daemon
->max_logs
!= 0)
802 my_syslog(LOG_INFO
, _("asynchronous logging enabled, queue limit is %d messages"), daemon
->max_logs
);
806 for (context
= daemon
->dhcp
; context
; context
= context
->next
)
807 log_context(AF_INET
, context
);
809 for (relay
= daemon
->relay4
; relay
; relay
= relay
->next
)
810 log_relay(AF_INET
, relay
);
813 for (context
= daemon
->dhcp6
; context
; context
= context
->next
)
814 log_context(AF_INET6
, context
);
816 for (relay
= daemon
->relay6
; relay
; relay
= relay
->next
)
817 log_relay(AF_INET6
, relay
);
819 if (daemon
->doing_dhcp6
|| daemon
->doing_ra
)
820 dhcp_construct_contexts(now
);
822 if (option_bool(OPT_RA
))
823 my_syslog(MS_DHCP
| LOG_INFO
, _("IPv6 router advertisement enabled"));
826 # ifdef HAVE_LINUX_NETWORK
828 my_syslog(MS_DHCP
| LOG_INFO
, _("DHCP, sockets bound exclusively to interface %s"), bound_device
);
831 /* after dhcp_contruct_contexts */
832 if (daemon
->dhcp
|| daemon
->doing_dhcp6
)
833 lease_find_interfaces(now
);
837 if (option_bool(OPT_TFTP
))
839 struct tftp_prefix
*p
;
841 if (FD_SETSIZE
< (unsigned)max_fd
)
845 my_syslog(MS_TFTP
| LOG_INFO
, "TFTP %s%s %s",
846 daemon
->tftp_prefix
? _("root is ") : _("enabled"),
847 daemon
->tftp_prefix
? daemon
->tftp_prefix
: "",
848 option_bool(OPT_TFTP_SECURE
) ? _("secure mode") : "");
850 if (tftp_prefix_missing
)
851 my_syslog(MS_TFTP
| LOG_WARNING
, _("warning: %s inaccessible"), daemon
->tftp_prefix
);
853 for (p
= daemon
->if_prefix
; p
; p
= p
->next
)
855 my_syslog(MS_TFTP
| LOG_WARNING
, _("warning: TFTP directory %s inaccessible"), p
->prefix
);
857 /* This is a guess, it assumes that for small limits,
858 disjoint files might be served, but for large limits,
859 a single file will be sent to may clients (the file only needs
862 max_fd
-= 30; /* use other than TFTP */
866 else if (max_fd
< 100)
869 max_fd
= max_fd
- 20;
871 /* if we have to use a limited range of ports,
872 that will limit the number of transfers */
873 if (daemon
->start_tftp_port
!= 0 &&
874 daemon
->end_tftp_port
- daemon
->start_tftp_port
+ 1 < max_fd
)
875 max_fd
= daemon
->end_tftp_port
- daemon
->start_tftp_port
+ 1;
877 if (daemon
->tftp_max
> max_fd
)
879 daemon
->tftp_max
= max_fd
;
880 my_syslog(MS_TFTP
| LOG_WARNING
,
881 _("restricting maximum simultaneous TFTP transfers to %d"),
887 /* finished start-up - release original process */
888 if (err_pipe
[1] != -1)
889 while (retry_send(close(err_pipe
[1])));
891 if (daemon
->port
!= 0)
897 /* Using inotify, have to select a resolv file at startup */
898 poll_resolv(1, 0, now
);
904 struct timeval t
, *tp
= NULL
;
905 fd_set rset
, wset
, eset
;
911 /* if we are out of resources, find how long we have to wait
912 for some to come free, we'll loop around then and restart
913 listening for queries */
914 if ((t
.tv_sec
= set_dns_listeners(now
, &rset
, &maxfd
)) != 0)
920 /* Whilst polling for the dbus, or doing a tftp transfer, wake every quarter second */
921 if (daemon
->tftp_trans
||
922 (option_bool(OPT_DBUS
) && !daemon
->dbus
))
928 /* Wake every second whilst waiting for DAD to complete */
929 else if (is_dad_listeners())
937 set_dbus_listeners(&maxfd
, &rset
, &wset
, &eset
);
941 if (daemon
->dhcp
|| daemon
->relay4
)
943 FD_SET(daemon
->dhcpfd
, &rset
);
944 bump_maxfd(daemon
->dhcpfd
, &maxfd
);
945 if (daemon
->pxefd
!= -1)
947 FD_SET(daemon
->pxefd
, &rset
);
948 bump_maxfd(daemon
->pxefd
, &maxfd
);
954 if (daemon
->doing_dhcp6
|| daemon
->relay6
)
956 FD_SET(daemon
->dhcp6fd
, &rset
);
957 bump_maxfd(daemon
->dhcp6fd
, &maxfd
);
960 if (daemon
->doing_ra
)
962 FD_SET(daemon
->icmp6fd
, &rset
);
963 bump_maxfd(daemon
->icmp6fd
, &maxfd
);
968 if (daemon
->inotifyfd
!= -1)
970 FD_SET(daemon
->inotifyfd
, &rset
);
971 bump_maxfd(daemon
->inotifyfd
, &maxfd
);
975 #if defined(HAVE_LINUX_NETWORK)
976 FD_SET(daemon
->netlinkfd
, &rset
);
977 bump_maxfd(daemon
->netlinkfd
, &maxfd
);
978 #elif defined(HAVE_BSD_NETWORK)
979 FD_SET(daemon
->routefd
, &rset
);
980 bump_maxfd(daemon
->routefd
, &maxfd
);
983 FD_SET(piperead
, &rset
);
984 bump_maxfd(piperead
, &maxfd
);
988 while (helper_buf_empty() && do_script_run(now
));
991 while (helper_buf_empty() && do_tftp_script_run());
994 if (!helper_buf_empty())
996 FD_SET(daemon
->helperfd
, &wset
);
997 bump_maxfd(daemon
->helperfd
, &maxfd
);
1000 /* need this for other side-effects */
1001 while (do_script_run(now
));
1004 while (do_tftp_script_run());
1010 /* must do this just before select(), when we know no
1011 more calls to my_syslog() can occur */
1012 set_log_writer(&wset
, &maxfd
);
1014 if (select(maxfd
+1, &rset
, &wset
, &eset
, tp
) < 0)
1016 /* otherwise undefined after error */
1017 FD_ZERO(&rset
); FD_ZERO(&wset
); FD_ZERO(&eset
);
1020 now
= dnsmasq_time();
1022 check_log_writer(&wset
);
1025 enumerate_interfaces(1);
1027 /* Check the interfaces to see if any have exited DAD state
1028 and if so, bind the address. */
1029 if (is_dad_listeners())
1031 enumerate_interfaces(0);
1032 /* NB, is_dad_listeners() == 1 --> we're binding interfaces */
1033 create_bound_listeners(0);
1034 warn_bound_listeners();
1037 #if defined(HAVE_LINUX_NETWORK)
1038 if (FD_ISSET(daemon
->netlinkfd
, &rset
))
1039 netlink_multicast();
1040 #elif defined(HAVE_BSD_NETWORK)
1041 if (FD_ISSET(daemon
->routefd
, &rset
))
1046 if (daemon
->inotifyfd
!= -1 && FD_ISSET(daemon
->inotifyfd
, &rset
) && inotify_check(now
))
1048 if (daemon
->port
!= 0 && !option_bool(OPT_NO_POLL
))
1049 poll_resolv(1, 1, now
);
1052 /* Check for changes to resolv files once per second max. */
1053 /* Don't go silent for long periods if the clock goes backwards. */
1054 if (daemon
->last_resolv
== 0 ||
1055 difftime(now
, daemon
->last_resolv
) > 1.0 ||
1056 difftime(now
, daemon
->last_resolv
) < -1.0)
1058 /* poll_resolv doesn't need to reload first time through, since
1059 that's queued anyway. */
1061 poll_resolv(0, daemon
->last_resolv
!= 0, now
);
1062 daemon
->last_resolv
= now
;
1066 if (FD_ISSET(piperead
, &rset
))
1067 async_event(piperead
, now
);
1070 /* if we didn't create a DBus connection, retry now. */
1071 if (option_bool(OPT_DBUS
) && !daemon
->dbus
)
1074 if ((err
= dbus_init()))
1075 my_syslog(LOG_WARNING
, _("DBus error: %s"), err
);
1077 my_syslog(LOG_INFO
, _("connected to system DBus"));
1079 check_dbus_listeners(&rset
, &wset
, &eset
);
1082 check_dns_listeners(&rset
, now
);
1085 check_tftp_listeners(&rset
, now
);
1089 if (daemon
->dhcp
|| daemon
->relay4
)
1091 if (FD_ISSET(daemon
->dhcpfd
, &rset
))
1092 dhcp_packet(now
, 0);
1093 if (daemon
->pxefd
!= -1 && FD_ISSET(daemon
->pxefd
, &rset
))
1094 dhcp_packet(now
, 1);
1098 if ((daemon
->doing_dhcp6
|| daemon
->relay6
) && FD_ISSET(daemon
->dhcp6fd
, &rset
))
1101 if (daemon
->doing_ra
&& FD_ISSET(daemon
->icmp6fd
, &rset
))
1106 if (daemon
->helperfd
!= -1 && FD_ISSET(daemon
->helperfd
, &wset
))
1114 static void sig_handler(int sig
)
1118 /* ignore anything other than TERM during startup
1119 and in helper proc. (helper ignore TERM too) */
1123 else if (pid
!= getpid())
1125 /* alarm is used to kill TCP children after a fixed time. */
1131 /* master process */
1132 int event
, errsave
= errno
;
1135 event
= EVENT_RELOAD
;
1136 else if (sig
== SIGCHLD
)
1137 event
= EVENT_CHILD
;
1138 else if (sig
== SIGALRM
)
1139 event
= EVENT_ALARM
;
1140 else if (sig
== SIGTERM
)
1142 else if (sig
== SIGUSR1
)
1144 else if (sig
== SIGUSR2
)
1145 event
= EVENT_REOPEN
;
1149 send_event(pipewrite
, event
, 0, NULL
);
1154 /* now == 0 -> queue immediate callback */
1155 void send_alarm(time_t event
, time_t now
)
1157 if (now
== 0 || event
!= 0)
1159 /* alarm(0) or alarm(-ve) doesn't do what we want.... */
1160 if ((now
== 0 || difftime(event
, now
) <= 0.0))
1161 send_event(pipewrite
, EVENT_ALARM
, 0, NULL
);
1163 alarm((unsigned)difftime(event
, now
));
1167 void queue_event(int event
)
1169 send_event(pipewrite
, event
, 0, NULL
);
1172 void send_event(int fd
, int event
, int data
, char *msg
)
1174 struct event_desc ev
;
1175 struct iovec iov
[2];
1179 ev
.msg_sz
= msg
? strlen(msg
) : 0;
1181 iov
[0].iov_base
= &ev
;
1182 iov
[0].iov_len
= sizeof(ev
);
1183 iov
[1].iov_base
= msg
;
1184 iov
[1].iov_len
= ev
.msg_sz
;
1186 /* error pipe, debug mode. */
1188 fatal_event(&ev
, msg
);
1190 /* pipe is non-blocking and struct event_desc is smaller than
1191 PIPE_BUF, so this either fails or writes everything */
1192 while (writev(fd
, iov
, msg
? 2 : 1) == -1 && errno
== EINTR
);
1195 /* NOTE: the memory used to return msg is leaked: use msgs in events only
1196 to describe fatal errors. */
1197 static int read_event(int fd
, struct event_desc
*evp
, char **msg
)
1201 if (!read_write(fd
, (unsigned char *)evp
, sizeof(struct event_desc
), 1))
1206 if (evp
->msg_sz
!= 0 &&
1207 (buf
= malloc(evp
->msg_sz
+ 1)) &&
1208 read_write(fd
, (unsigned char *)buf
, evp
->msg_sz
, 1))
1210 buf
[evp
->msg_sz
] = 0;
1217 static void fatal_event(struct event_desc
*ev
, char *msg
)
1226 case EVENT_FORK_ERR
:
1227 die(_("cannot fork into background: %s"), NULL
, EC_MISC
);
1229 case EVENT_PIPE_ERR
:
1230 die(_("failed to create helper: %s"), NULL
, EC_MISC
);
1233 die(_("setting capabilities failed: %s"), NULL
, EC_MISC
);
1235 case EVENT_USER_ERR
:
1236 die(_("failed to change user-id to %s: %s"), msg
, EC_MISC
);
1238 case EVENT_GROUP_ERR
:
1239 die(_("failed to change group-id to %s: %s"), msg
, EC_MISC
);
1242 die(_("failed to open pidfile %s: %s"), msg
, EC_FILE
);
1245 die(_("cannot open log %s: %s"), msg
, EC_FILE
);
1248 die(_("failed to load Lua script: %s"), msg
, EC_MISC
);
1250 case EVENT_TFTP_ERR
:
1251 die(_("TFTP directory %s inaccessible: %s"), msg
, EC_FILE
);
1253 case EVENT_TIME_ERR
:
1254 die(_("cannot create timestamp file %s: %s" ), msg
, EC_BADCONF
);
1258 static void async_event(int pipe
, time_t now
)
1261 struct event_desc ev
;
1265 /* NOTE: the memory used to return msg is leaked: use msgs in events only
1266 to describe fatal errors. */
1268 if (read_event(pipe
, &ev
, &msg
))
1273 if (option_bool(OPT_DNSSEC_VALID
) && option_bool(OPT_DNSSEC_TIME
))
1275 my_syslog(LOG_INFO
, _("now checking DNSSEC signature timestamps"));
1276 reset_option_bool(OPT_DNSSEC_TIME
);
1282 clear_cache_and_reload(now
);
1284 if (daemon
->port
!= 0)
1286 if (daemon
->resolv_files
&& option_bool(OPT_NO_POLL
))
1288 reload_servers(daemon
->resolv_files
->name
);
1292 if (daemon
->servers_file
)
1294 read_servers_file();
1308 if (daemon
->port
!= 0)
1314 if (daemon
->dhcp
|| daemon
->doing_dhcp6
)
1316 lease_prune(NULL
, now
);
1317 lease_update_file(now
);
1320 else if (daemon
->doing_ra
)
1321 /* Not doing DHCP, so no lease system, manage alarms for ra only */
1322 send_alarm(periodic_ra(now
), now
);
1328 /* See Stevens 5.10 */
1329 while ((p
= waitpid(-1, NULL
, WNOHANG
)) != 0)
1336 for (i
= 0 ; i
< MAX_PROCS
; i
++)
1337 if (daemon
->tcp_pids
[i
] == p
)
1338 daemon
->tcp_pids
[i
] = 0;
1342 my_syslog(LOG_WARNING
, _("script process killed by signal %d"), ev
.data
);
1346 my_syslog(LOG_WARNING
, _("script process exited with status %d"), ev
.data
);
1349 case EVENT_EXEC_ERR
:
1350 my_syslog(LOG_ERR
, _("failed to execute %s: %s"),
1351 daemon
->lease_change_command
, strerror(ev
.data
));
1354 /* necessary for fatal errors in helper */
1355 case EVENT_USER_ERR
:
1358 fatal_event(&ev
, msg
);
1362 /* Note: this may leave TCP-handling processes with the old file still open.
1363 Since any such process will die in CHILD_LIFETIME or probably much sooner,
1364 we leave them logging to the old file. */
1366 if (daemon
->log_file
!= NULL
)
1367 log_reopen(daemon
->log_file
);
1370 tomato_helper(now
); //possibly delete & write out leases for tomato
1372 /* following is Asus tweak. Interestingly Asus read the dnsmasq leases db
1373 directly. They signal dnsmasq to update via SIGUSR2 and wait 1 second
1374 assuming the file will be complete by the time they come to parse it.
1375 Race conditions anyone? What if dnsmasq happens to be updating the
1377 #if defined(HAVE_DHCP) && defined(HAVE_LEASEFILE_EXPIRE) && !defined(HAVE_TOMATO)
1378 if (daemon
->dhcp
|| daemon
->dhcp6
)
1379 flush_lease_file(now
);
1387 case EVENT_NEWROUTE
:
1389 /* Force re-reading resolv file right now, for luck. */
1390 poll_resolv(0, 1, now
);
1394 /* Knock all our children on the head. */
1395 for (i
= 0; i
< MAX_PROCS
; i
++)
1396 if (daemon
->tcp_pids
[i
] != 0)
1397 kill(daemon
->tcp_pids
[i
], SIGALRM
);
1399 #if defined(HAVE_SCRIPT)
1400 /* handle pending lease transitions */
1401 if (daemon
->helperfd
!= -1)
1403 /* block in writes until all done */
1404 if ((i
= fcntl(daemon
->helperfd
, F_GETFL
)) != -1)
1405 fcntl(daemon
->helperfd
, F_SETFL
, i
& ~O_NONBLOCK
);
1408 } while (!helper_buf_empty() || do_script_run(now
));
1409 while (retry_send(close(daemon
->helperfd
)));
1413 //Originally TOMATO tweak
1414 #if defined(HAVE_DHCP) && defined(HAVE_LEASEFILE_EXPIRE)
1415 if (daemon
->dhcp
|| daemon
->dhcp6
)
1416 flush_lease_file(now
);
1419 if (daemon
->lease_stream
)
1420 fclose(daemon
->lease_stream
);
1422 if (daemon
->runfile
)
1423 unlink(daemon
->runfile
);
1425 my_syslog(LOG_INFO
, _("exiting on receipt of SIGTERM"));
1431 static void poll_resolv(int force
, int do_reload
, time_t now
)
1433 struct resolvc
*res
, *latest
;
1434 struct stat statbuf
;
1435 time_t last_change
= 0;
1436 /* There may be more than one possible file.
1437 Go through and find the one which changed _last_.
1438 Warn of any which can't be read. */
1440 if (daemon
->port
== 0 || option_bool(OPT_NO_POLL
))
1443 for (latest
= NULL
, res
= daemon
->resolv_files
; res
; res
= res
->next
)
1444 if (stat(res
->name
, &statbuf
) == -1)
1453 my_syslog(LOG_WARNING
, _("failed to access %s: %s"), res
->name
, strerror(errno
));
1456 if (res
->mtime
!= 0)
1458 /* existing file evaporated, force selection of the latest
1459 file even if its mtime hasn't changed since we last looked */
1460 poll_resolv(1, do_reload
, now
);
1467 if (force
|| (statbuf
.st_mtime
!= res
->mtime
))
1469 res
->mtime
= statbuf
.st_mtime
;
1470 if (difftime(statbuf
.st_mtime
, last_change
) > 0.0)
1472 last_change
= statbuf
.st_mtime
;
1480 static int warned
= 0;
1481 if (reload_servers(latest
->name
))
1483 my_syslog(LOG_INFO
, _("reading %s"), latest
->name
);
1486 if (option_bool(OPT_RELOAD
) && do_reload
)
1487 clear_cache_and_reload(now
);
1494 my_syslog(LOG_WARNING
, _("no servers found in %s, will retry"), latest
->name
);
1501 void clear_cache_and_reload(time_t now
)
1505 if (daemon
->port
!= 0)
1509 if (daemon
->dhcp
|| daemon
->doing_dhcp6
)
1511 if (option_bool(OPT_ETHERS
))
1515 set_dynamic_inotify(AH_DHCP_HST
| AH_DHCP_OPT
, 0, NULL
, 0);
1517 dhcp_update_configs(daemon
->dhcp_conf
);
1518 lease_update_from_configs();
1519 lease_update_file(now
);
1520 lease_update_dns(1);
1523 else if (daemon
->doing_ra
)
1524 /* Not doing DHCP, so no lease system, manage
1525 alarms for ra only */
1526 send_alarm(periodic_ra(now
), now
);
1531 static int set_dns_listeners(time_t now
, fd_set
*set
, int *maxfdp
)
1533 struct serverfd
*serverfdp
;
1534 struct listener
*listener
;
1539 struct tftp_transfer
*transfer
;
1540 for (transfer
= daemon
->tftp_trans
; transfer
; transfer
= transfer
->next
)
1543 FD_SET(transfer
->sockfd
, set
);
1544 bump_maxfd(transfer
->sockfd
, maxfdp
);
1548 /* will we be able to get memory? */
1549 if (daemon
->port
!= 0)
1550 get_new_frec(now
, &wait
, 0);
1552 for (serverfdp
= daemon
->sfds
; serverfdp
; serverfdp
= serverfdp
->next
)
1554 FD_SET(serverfdp
->fd
, set
);
1555 bump_maxfd(serverfdp
->fd
, maxfdp
);
1558 if (daemon
->port
!= 0 && !daemon
->osport
)
1559 for (i
= 0; i
< RANDOM_SOCKS
; i
++)
1560 if (daemon
->randomsocks
[i
].refcount
!= 0)
1562 FD_SET(daemon
->randomsocks
[i
].fd
, set
);
1563 bump_maxfd(daemon
->randomsocks
[i
].fd
, maxfdp
);
1566 for (listener
= daemon
->listeners
; listener
; listener
= listener
->next
)
1568 /* only listen for queries if we have resources */
1569 if (listener
->fd
!= -1 && wait
== 0)
1571 FD_SET(listener
->fd
, set
);
1572 bump_maxfd(listener
->fd
, maxfdp
);
1575 /* death of a child goes through the select loop, so
1576 we don't need to explicitly arrange to wake up here */
1577 if (listener
->tcpfd
!= -1)
1578 for (i
= 0; i
< MAX_PROCS
; i
++)
1579 if (daemon
->tcp_pids
[i
] == 0)
1581 FD_SET(listener
->tcpfd
, set
);
1582 bump_maxfd(listener
->tcpfd
, maxfdp
);
1587 if (tftp
<= daemon
->tftp_max
&& listener
->tftpfd
!= -1)
1589 FD_SET(listener
->tftpfd
, set
);
1590 bump_maxfd(listener
->tftpfd
, maxfdp
);
1599 static void check_dns_listeners(fd_set
*set
, time_t now
)
1601 struct serverfd
*serverfdp
;
1602 struct listener
*listener
;
1605 for (serverfdp
= daemon
->sfds
; serverfdp
; serverfdp
= serverfdp
->next
)
1606 if (FD_ISSET(serverfdp
->fd
, set
))
1607 reply_query(serverfdp
->fd
, serverfdp
->source_addr
.sa
.sa_family
, now
);
1609 if (daemon
->port
!= 0 && !daemon
->osport
)
1610 for (i
= 0; i
< RANDOM_SOCKS
; i
++)
1611 if (daemon
->randomsocks
[i
].refcount
!= 0 &&
1612 FD_ISSET(daemon
->randomsocks
[i
].fd
, set
))
1613 reply_query(daemon
->randomsocks
[i
].fd
, daemon
->randomsocks
[i
].family
, now
);
1615 for (listener
= daemon
->listeners
; listener
; listener
= listener
->next
)
1617 if (listener
->fd
!= -1 && FD_ISSET(listener
->fd
, set
))
1618 receive_query(listener
, now
);
1621 if (listener
->tftpfd
!= -1 && FD_ISSET(listener
->tftpfd
, set
))
1622 tftp_request(listener
, now
);
1625 if (listener
->tcpfd
!= -1 && FD_ISSET(listener
->tcpfd
, set
))
1627 int confd
, client_ok
= 1;
1628 struct irec
*iface
= NULL
;
1630 union mysockaddr tcp_addr
;
1631 socklen_t tcp_len
= sizeof(union mysockaddr
);
1633 while ((confd
= accept(listener
->tcpfd
, NULL
, NULL
)) == -1 && errno
== EINTR
);
1638 if (getsockname(confd
, (struct sockaddr
*)&tcp_addr
, &tcp_len
) == -1)
1640 while (retry_send(close(confd
)));
1644 /* Make sure that the interface list is up-to-date.
1646 We do this here as we may need the results below, and
1647 the DNS code needs them for --interface-name stuff.
1649 Multiple calls to enumerate_interfaces() per select loop are
1650 inhibited, so calls to it in the child process (which doesn't select())
1651 have no effect. This avoids two processes reading from the same
1652 netlink fd and screwing the pooch entirely.
1655 enumerate_interfaces(0);
1657 if (option_bool(OPT_NOWILD
))
1658 iface
= listener
->iface
; /* May be NULL */
1662 char intr_name
[IF_NAMESIZE
];
1664 /* if we can find the arrival interface, check it's one that's allowed */
1665 if ((if_index
= tcp_interface(confd
, tcp_addr
.sa
.sa_family
)) != 0 &&
1666 indextoname(listener
->tcpfd
, if_index
, intr_name
))
1668 struct all_addr addr
;
1669 addr
.addr
.addr4
= tcp_addr
.in
.sin_addr
;
1671 if (tcp_addr
.sa
.sa_family
== AF_INET6
)
1672 addr
.addr
.addr6
= tcp_addr
.in6
.sin6_addr
;
1675 for (iface
= daemon
->interfaces
; iface
; iface
= iface
->next
)
1676 if (iface
->index
== if_index
)
1679 if (!iface
&& !loopback_exception(listener
->tcpfd
, tcp_addr
.sa
.sa_family
, &addr
, intr_name
))
1683 if (option_bool(OPT_CLEVERBIND
))
1684 iface
= listener
->iface
; /* May be NULL */
1687 /* Check for allowed interfaces when binding the wildcard address:
1688 we do this by looking for an interface with the same address as
1689 the local address of the TCP connection, then looking to see if that's
1690 an allowed interface. As a side effect, we get the netmask of the
1691 interface too, for localisation. */
1693 for (iface
= daemon
->interfaces
; iface
; iface
= iface
->next
)
1694 if (sockaddr_isequal(&iface
->addr
, &tcp_addr
))
1704 shutdown(confd
, SHUT_RDWR
);
1705 while (retry_send(close(confd
)));
1708 else if (!option_bool(OPT_DEBUG
) && (p
= fork()) != 0)
1713 for (i
= 0; i
< MAX_PROCS
; i
++)
1714 if (daemon
->tcp_pids
[i
] == 0)
1716 daemon
->tcp_pids
[i
] = p
;
1720 while (retry_send(close(confd
)));
1722 /* The child can use up to TCP_MAX_QUERIES ids, so skip that many. */
1723 daemon
->log_id
+= TCP_MAX_QUERIES
;
1728 unsigned char *buff
;
1731 struct in_addr netmask
;
1736 netmask
= iface
->netmask
;
1737 auth_dns
= iface
->dns_auth
;
1746 /* Arrange for SIGALARM after CHILD_LIFETIME seconds to
1747 terminate the process. */
1748 if (!option_bool(OPT_DEBUG
))
1749 alarm(CHILD_LIFETIME
);
1752 /* start with no upstream connections. */
1753 for (s
= daemon
->servers
; s
; s
= s
->next
)
1756 /* The connected socket inherits non-blocking
1757 attribute from the listening socket.
1759 if ((flags
= fcntl(confd
, F_GETFL
, 0)) != -1)
1760 fcntl(confd
, F_SETFL
, flags
& ~O_NONBLOCK
);
1762 buff
= tcp_request(confd
, now
, &tcp_addr
, netmask
, auth_dns
);
1764 shutdown(confd
, SHUT_RDWR
);
1765 while (retry_send(close(confd
)));
1770 for (s
= daemon
->servers
; s
; s
= s
->next
)
1773 shutdown(s
->tcpfd
, SHUT_RDWR
);
1774 while (retry_send(close(s
->tcpfd
)));
1777 if (!option_bool(OPT_DEBUG
))
1789 int make_icmp_sock(void)
1794 if ((fd
= socket (AF_INET
, SOCK_RAW
, IPPROTO_ICMP
)) != -1)
1797 setsockopt(fd
, SOL_SOCKET
, SO_DONTROUTE
, &zeroopt
, sizeof(zeroopt
)) == -1)
1807 int icmp_ping(struct in_addr addr
)
1809 /* Try and get an ICMP echo from a machine. */
1811 /* Note that whilst in the three second wait, we check for
1812 (and service) events on the DNS and TFTP sockets, (so doing that
1813 better not use any resources our caller has in use...)
1814 but we remain deaf to signals or further DHCP packets. */
1817 struct sockaddr_in saddr
;
1822 unsigned short id
= rand16();
1827 #if defined(HAVE_LINUX_NETWORK) || defined (HAVE_SOLARIS_NETWORK)
1828 if ((fd
= make_icmp_sock()) == -1)
1832 fd
= daemon
->dhcp_icmp_fd
;
1833 setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &opt
, sizeof(opt
));
1836 saddr
.sin_family
= AF_INET
;
1838 saddr
.sin_addr
= addr
;
1839 #ifdef HAVE_SOCKADDR_SA_LEN
1840 saddr
.sin_len
= sizeof(struct sockaddr_in
);
1843 memset(&packet
.icmp
, 0, sizeof(packet
.icmp
));
1844 packet
.icmp
.icmp_type
= ICMP_ECHO
;
1845 packet
.icmp
.icmp_id
= id
;
1846 for (j
= 0, i
= 0; i
< sizeof(struct icmp
) / 2; i
++)
1847 j
+= ((u16
*)&packet
.icmp
)[i
];
1849 j
= (j
& 0xffff) + (j
>> 16);
1850 packet
.icmp
.icmp_cksum
= (j
== 0xffff) ? j
: ~j
;
1852 while (retry_send(sendto(fd
, (char *)&packet
.icmp
, sizeof(struct icmp
), 0,
1853 (struct sockaddr
*)&saddr
, sizeof(saddr
))));
1855 for (now
= start
= dnsmasq_time();
1856 difftime(now
, start
) < (float)PING_WAIT
;)
1860 struct sockaddr_in faddr
;
1862 socklen_t len
= sizeof(faddr
);
1864 tv
.tv_usec
= 250000;
1870 set_dns_listeners(now
, &rset
, &maxfd
);
1871 set_log_writer(&wset
, &maxfd
);
1874 if (daemon
->doing_ra
)
1876 FD_SET(daemon
->icmp6fd
, &rset
);
1877 bump_maxfd(daemon
->icmp6fd
, &maxfd
);
1881 if (select(maxfd
+1, &rset
, &wset
, NULL
, &tv
) < 0)
1887 now
= dnsmasq_time();
1889 check_log_writer(&wset
);
1890 check_dns_listeners(&rset
, now
);
1893 if (daemon
->doing_ra
&& FD_ISSET(daemon
->icmp6fd
, &rset
))
1898 check_tftp_listeners(&rset
, now
);
1901 if (FD_ISSET(fd
, &rset
) &&
1902 recvfrom(fd
, &packet
, sizeof(packet
), 0,
1903 (struct sockaddr
*)&faddr
, &len
) == sizeof(packet
) &&
1904 saddr
.sin_addr
.s_addr
== faddr
.sin_addr
.s_addr
&&
1905 packet
.icmp
.icmp_type
== ICMP_ECHOREPLY
&&
1906 packet
.icmp
.icmp_seq
== 0 &&
1907 packet
.icmp
.icmp_id
== id
)
1914 #if defined(HAVE_LINUX_NETWORK) || defined(HAVE_SOLARIS_NETWORK)
1915 while (retry_send(close(fd
)));
1918 setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &opt
, sizeof(opt
));