1 /* dnsmasq is Copyright (c) 2000-2012 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
22 struct daemon
*daemon
;
24 static volatile pid_t pid
= 0;
25 static volatile int pipewrite
;
27 static int set_dns_listeners(time_t now
, fd_set
*set
, int *maxfdp
);
28 static void check_dns_listeners(fd_set
*set
, time_t now
);
29 static void sig_handler(int sig
);
30 static void async_event(int pipe
, time_t now
);
31 static void fatal_event(struct event_desc
*ev
, char *msg
);
32 static int read_event(int fd
, struct event_desc
*evp
, char **msg
);
34 int main (int argc
, char **argv
)
36 int bind_fallback
= 0;
38 struct sigaction sigact
;
40 int piperead
, pipefd
[2], err_pipe
[2];
41 struct passwd
*ent_pw
= NULL
;
42 #if defined(HAVE_SCRIPT)
46 struct group
*gp
= NULL
;
47 long i
, max_fd
= sysconf(_SC_OPEN_MAX
);
50 #if defined(HAVE_LINUX_NETWORK)
51 cap_user_header_t hdr
= NULL
;
52 cap_user_data_t data
= NULL
;
56 setlocale(LC_ALL
, "");
57 bindtextdomain("dnsmasq", LOCALEDIR
);
58 textdomain("dnsmasq");
61 sigact
.sa_handler
= sig_handler
;
63 sigemptyset(&sigact
.sa_mask
);
64 sigaction(SIGUSR1
, &sigact
, NULL
);
65 sigaction(SIGUSR2
, &sigact
, NULL
);
66 sigaction(SIGHUP
, &sigact
, NULL
);
67 sigaction(SIGTERM
, &sigact
, NULL
);
68 sigaction(SIGALRM
, &sigact
, NULL
);
69 sigaction(SIGCHLD
, &sigact
, NULL
);
72 sigact
.sa_handler
= SIG_IGN
;
73 sigaction(SIGPIPE
, &sigact
, NULL
);
75 umask(022); /* known umask, create leases and pid files as 0644 */
77 read_opts(argc
, argv
, compile_opts
);
79 if (daemon
->edns_pktsz
< PACKETSZ
)
80 daemon
->edns_pktsz
= PACKETSZ
;
81 daemon
->packet_buff_sz
= daemon
->edns_pktsz
> DNSMASQ_PACKETSZ
?
82 daemon
->edns_pktsz
: DNSMASQ_PACKETSZ
;
83 daemon
->packet
= safe_malloc(daemon
->packet_buff_sz
);
85 daemon
->addrbuff
= safe_malloc(ADDRSTRLEN
);
88 if (!daemon
->lease_file
)
90 if (daemon
->dhcp
|| daemon
->dhcp6
)
91 daemon
->lease_file
= LEASEFILE
;
95 /* Close any file descriptors we inherited apart from std{in|out|err}
97 Ensure that at least stdin, stdout and stderr (fd 0, 1, 2) exist,
98 otherwise file descriptors we create can end up being 0, 1, or 2
99 and then get accidentally closed later when we make 0, 1, and 2
100 open to /dev/null. Normally we'll be started with 0, 1 and 2 open,
101 but it's not guaranteed. By opening /dev/null three times, we
102 ensure that we're not using those fds for real stuff. */
103 for (i
= 0; i
< max_fd
; i
++)
104 if (i
!= STDOUT_FILENO
&& i
!= STDERR_FILENO
&& i
!= STDIN_FILENO
)
107 open("/dev/null", O_RDWR
);
109 #ifndef HAVE_LINUX_NETWORK
110 # if !(defined(IP_RECVDSTADDR) && defined(IP_RECVIF) && defined(IP_SENDSRCADDR))
111 if (!option_bool(OPT_NOWILD
))
114 set_option_bool(OPT_NOWILD
);
118 /* -- bind-dynamic not supported on !Linux, fall back to --bind-interfaces */
119 if (option_bool(OPT_CLEVERBIND
))
122 set_option_bool(OPT_NOWILD
);
123 reset_option_bool(OPT_CLEVERBIND
);
128 if (option_bool(OPT_TFTP
))
129 die(_("TFTP server not available: set HAVE_TFTP in src/config.h"), NULL
, EC_BADCONF
);
132 #ifdef HAVE_CONNTRACK
133 if (option_bool(OPT_CONNTRACK
) && (daemon
->query_port
!= 0 || daemon
->osport
))
134 die (_("Cannot use --conntrack AND --query-port"), NULL
, EC_BADCONF
);
136 if (option_bool(OPT_CONNTRACK
))
137 die(_("Conntrack support not available: set HAVE_CONNTRACK in src/config.h"), NULL
, EC_BADCONF
);
140 #ifdef HAVE_SOLARIS_NETWORK
141 if (daemon
->max_logs
!= 0)
142 die(_("asychronous logging is not available under Solaris"), NULL
, EC_BADCONF
);
146 if (daemon
->max_logs
!= 0)
147 die(_("asychronous logging is not available under Android"), NULL
, EC_BADCONF
);
152 now
= dnsmasq_time();
155 if (daemon
->dhcp
|| daemon
->dhcp6
)
157 /* Note that order matters here, we must call lease_init before
158 creating any file descriptors which shouldn't be leaked
159 to the lease-script init process. We need to call common_init
160 before lease_init to allocate buffers it uses.*/
169 /* Start RA subsystem if --enable-ra OR dhcp-range=<subnet>, ra-only */
170 if (daemon
->ra_contexts
|| option_bool(OPT_RA
))
172 /* link the DHCP6 contexts to the ra-only ones so we can traverse them all
173 from ->ra_contexts, but only the non-ra-onlies from ->dhcp6 */
174 struct dhcp_context
*context
;
176 if (!daemon
->ra_contexts
)
177 daemon
->ra_contexts
= daemon
->dhcp6
;
180 for (context
= daemon
->ra_contexts
; context
->next
; context
= context
->next
);
181 context
->next
= daemon
->dhcp6
;
193 #ifdef HAVE_LINUX_NETWORK
194 /* After lease_init */
197 if (option_bool(OPT_NOWILD
) && option_bool(OPT_CLEVERBIND
))
198 die(_("cannot set --bind-interfaces and --bind-dynamic"), NULL
, EC_BADCONF
);
202 /* after netlink_init */
203 if (daemon
->ra_contexts
|| daemon
->dhcp6
)
208 /* after netlink_init */
209 if (daemon
->dhcp
|| daemon
->dhcp6
)
210 lease_find_interfaces(now
);
213 if (!enumerate_interfaces())
214 die(_("failed to find list of interfaces: %s"), NULL
, EC_MISC
);
216 if (option_bool(OPT_NOWILD
) || option_bool(OPT_CLEVERBIND
))
218 create_bound_listeners(1);
220 if (!option_bool(OPT_CLEVERBIND
))
221 for (if_tmp
= daemon
->if_names
; if_tmp
; if_tmp
= if_tmp
->next
)
222 if (if_tmp
->name
&& !if_tmp
->used
)
223 die(_("unknown interface %s"), if_tmp
->name
, EC_BADNET
);
225 #if defined(HAVE_LINUX_NETWORK) && defined(HAVE_DHCP)
226 /* after enumerate_interfaces() */
229 bindtodevice(daemon
->dhcpfd
);
230 if (daemon
->enable_pxe
)
231 bindtodevice(daemon
->pxefd
);
235 #if defined(HAVE_LINUX_NETWORK) && defined(HAVE_DHCP6)
237 bindtodevice(daemon
->dhcp6fd
);
241 create_wildcard_listeners();
243 if (daemon
->port
!= 0)
246 if (option_bool(OPT_DBUS
))
251 daemon
->watches
= NULL
;
252 if ((err
= dbus_init()))
253 die(_("DBus error: %s"), err
, EC_MISC
);
256 die(_("DBus not available: set HAVE_DBUS in src/config.h"), NULL
, EC_BADCONF
);
259 if (daemon
->port
!= 0)
262 #if defined(HAVE_SCRIPT)
263 /* Note getpwnam returns static storage */
264 if ((daemon
->dhcp
|| daemon
->dhcp6
) &&
265 daemon
->scriptuser
&&
266 (daemon
->lease_change_command
|| daemon
->luascript
))
268 if ((ent_pw
= getpwnam(daemon
->scriptuser
)))
270 script_uid
= ent_pw
->pw_uid
;
271 script_gid
= ent_pw
->pw_gid
;
274 baduser
= daemon
->scriptuser
;
278 if (daemon
->username
&& !(ent_pw
= getpwnam(daemon
->username
)))
279 baduser
= daemon
->username
;
280 else if (daemon
->groupname
&& !(gp
= getgrnam(daemon
->groupname
)))
281 baduser
= daemon
->groupname
;
284 die(_("unknown user or group: %s"), baduser
, EC_BADCONF
);
286 /* implement group defaults, "dip" if available, or group associated with uid */
287 if (!daemon
->group_set
&& !gp
)
289 if (!(gp
= getgrnam(CHGRP
)) && ent_pw
)
290 gp
= getgrgid(ent_pw
->pw_gid
);
292 /* for error message */
294 daemon
->groupname
= gp
->gr_name
;
297 #if defined(HAVE_LINUX_NETWORK)
298 /* determine capability API version here, while we can still
300 if (ent_pw
&& ent_pw
->pw_uid
!= 0)
302 int capsize
= 1; /* for header version 1 */
303 hdr
= safe_malloc(sizeof(*hdr
));
305 /* find version supported by kernel */
306 memset(hdr
, 0, sizeof(*hdr
));
309 if (hdr
->version
!= LINUX_CAPABILITY_VERSION_1
)
311 /* if unknown version, use largest supported version (3) */
312 if (hdr
->version
!= LINUX_CAPABILITY_VERSION_2
)
313 hdr
->version
= LINUX_CAPABILITY_VERSION_3
;
317 data
= safe_malloc(sizeof(*data
) * capsize
);
318 memset(data
, 0, sizeof(*data
) * capsize
);
322 /* Use a pipe to carry signals and other events back to the event loop
323 in a race-free manner and another to carry errors to daemon-invoking process */
324 safe_pipe(pipefd
, 1);
326 piperead
= pipefd
[0];
327 pipewrite
= pipefd
[1];
328 /* prime the pipe to load stuff first time. */
329 send_event(pipewrite
, EVENT_RELOAD
, 0, NULL
);
333 if (!option_bool(OPT_DEBUG
))
335 /* The following code "daemonizes" the process.
336 See Stevens section 12.4 */
339 die(_("cannot chdir to filesystem root: %s"), NULL
, EC_MISC
);
342 if (!option_bool(OPT_NO_FORK
))
346 /* pipe to carry errors back to original process.
347 When startup is complete we close this and the process terminates. */
348 safe_pipe(err_pipe
, 0);
350 if ((pid
= fork()) == -1)
351 /* fd == -1 since we've not forked, never returns. */
352 send_event(-1, EVENT_FORK_ERR
, errno
, NULL
);
356 struct event_desc ev
;
359 /* close our copy of write-end */
362 /* check for errors after the fork */
363 if (read_event(err_pipe
[0], &ev
, &msg
))
364 fatal_event(&ev
, msg
);
371 /* NO calls to die() from here on. */
375 if ((pid
= fork()) == -1)
376 send_event(err_pipe
[1], EVENT_FORK_ERR
, errno
, NULL
);
383 /* write pidfile _after_ forking ! */
388 sprintf(daemon
->namebuff
, "%d\n", (int) getpid());
390 /* Explanation: Some installations of dnsmasq (eg Debian/Ubuntu) locate the pid-file
391 in a directory which is writable by the non-privileged user that dnsmasq runs as. This
392 allows the daemon to delete the file as part of its shutdown. This is a security hole to the
393 extent that an attacker running as the unprivileged user could replace the pidfile with a
394 symlink, and have the target of that symlink overwritten as root next time dnsmasq starts.
396 The folowing code first deletes any existing file, and then opens it with the O_EXCL flag,
397 ensuring that the open() fails should there be any existing file (because the unlink() failed,
398 or an attacker exploited the race between unlink() and open()). This ensures that no symlink
401 Any compromise of the non-privileged user still theoretically allows the pid-file to be
402 replaced whilst dnsmasq is running. The worst that could allow is that the usual
403 "shutdown dnsmasq" shell command could be tricked into stopping any other process.
405 Note that if dnsmasq is started as non-root (eg for testing) it silently ignores
406 failure to write the pid-file.
409 unlink(daemon
->runfile
);
411 if ((fd
= open(daemon
->runfile
, O_WRONLY
|O_CREAT
|O_TRUNC
|O_EXCL
, S_IWUSR
|S_IRUSR
|S_IRGRP
|S_IROTH
)) == -1)
413 /* only complain if started as root */
419 if (!read_write(fd
, (unsigned char *)daemon
->namebuff
, strlen(daemon
->namebuff
), 0))
422 while (!err
&& close(fd
) == -1)
429 send_event(err_pipe
[1], EVENT_PIDFILE
, errno
, daemon
->runfile
);
435 log_err
= log_start(ent_pw
, err_pipe
[1]);
437 if (!option_bool(OPT_DEBUG
))
439 /* open stdout etc to /dev/null */
440 int nullfd
= open("/dev/null", O_RDWR
);
441 dup2(nullfd
, STDOUT_FILENO
);
442 dup2(nullfd
, STDERR_FILENO
);
443 dup2(nullfd
, STDIN_FILENO
);
447 /* if we are to run scripts, we need to fork a helper before dropping root. */
448 daemon
->helperfd
= -1;
450 if ((daemon
->dhcp
|| daemon
->dhcp6
) && (daemon
->lease_change_command
|| daemon
->luascript
))
451 daemon
->helperfd
= create_helper(pipewrite
, err_pipe
[1], script_uid
, script_gid
, max_fd
);
454 if (!option_bool(OPT_DEBUG
) && getuid() == 0)
456 int bad_capabilities
= 0;
459 /* remove all supplimentary groups */
461 (setgroups(0, &dummy
) == -1 ||
462 setgid(gp
->gr_gid
) == -1))
464 send_event(err_pipe
[1], EVENT_GROUP_ERR
, errno
, daemon
->groupname
);
468 if (ent_pw
&& ent_pw
->pw_uid
!= 0)
470 #if defined(HAVE_LINUX_NETWORK)
471 /* On linux, we keep CAP_NETADMIN (for ARP-injection) and
472 CAP_NET_RAW (for icmp) if we're doing dhcp. If we have yet to bind
473 ports because of DAD, or we're doing it dynamically,
474 we need CAP_NET_BIND_SERVICE too. */
475 if (is_dad_listeners() || option_bool(OPT_CLEVERBIND
))
476 data
->effective
= data
->permitted
= data
->inheritable
=
477 (1 << CAP_NET_ADMIN
) | (1 << CAP_NET_RAW
) |
478 (1 << CAP_SETUID
) | (1 << CAP_NET_BIND_SERVICE
);
480 data
->effective
= data
->permitted
= data
->inheritable
=
481 (1 << CAP_NET_ADMIN
) | (1 << CAP_NET_RAW
) | (1 << CAP_SETUID
);
483 /* Tell kernel to not clear capabilities when dropping root */
484 if (capset(hdr
, data
) == -1 || prctl(PR_SET_KEEPCAPS
, 1, 0, 0, 0) == -1)
485 bad_capabilities
= errno
;
487 #elif defined(HAVE_SOLARIS_NETWORK)
488 /* http://developers.sun.com/solaris/articles/program_privileges.html */
489 priv_set_t
*priv_set
;
491 if (!(priv_set
= priv_str_to_set("basic", ",", NULL
)) ||
492 priv_addset(priv_set
, PRIV_NET_ICMPACCESS
) == -1 ||
493 priv_addset(priv_set
, PRIV_SYS_NET_CONFIG
) == -1)
494 bad_capabilities
= errno
;
496 if (priv_set
&& bad_capabilities
== 0)
498 priv_inverse(priv_set
);
500 if (setppriv(PRIV_OFF
, PRIV_LIMIT
, priv_set
) == -1)
501 bad_capabilities
= errno
;
505 priv_freeset(priv_set
);
509 if (bad_capabilities
!= 0)
511 send_event(err_pipe
[1], EVENT_CAP_ERR
, bad_capabilities
, NULL
);
515 /* finally drop root */
516 if (setuid(ent_pw
->pw_uid
) == -1)
518 send_event(err_pipe
[1], EVENT_USER_ERR
, errno
, daemon
->username
);
522 #ifdef HAVE_LINUX_NETWORK
523 if (is_dad_listeners() || option_bool(OPT_CLEVERBIND
))
524 data
->effective
= data
->permitted
=
525 (1 << CAP_NET_ADMIN
) | (1 << CAP_NET_RAW
) | (1 << CAP_NET_BIND_SERVICE
);
527 data
->effective
= data
->permitted
=
528 (1 << CAP_NET_ADMIN
) | (1 << CAP_NET_RAW
);
529 data
->inheritable
= 0;
531 /* lose the setuid and setgid capbilities */
532 if (capset(hdr
, data
) == -1)
534 send_event(err_pipe
[1], EVENT_CAP_ERR
, errno
, NULL
);
542 #ifdef HAVE_LINUX_NETWORK
543 if (option_bool(OPT_DEBUG
))
544 prctl(PR_SET_DUMPABLE
, 1, 0, 0, 0);
548 if (option_bool(OPT_TFTP
))
551 struct tftp_prefix
*p
;
553 if (daemon
->tftp_prefix
)
555 if (!((dir
= opendir(daemon
->tftp_prefix
))))
557 send_event(err_pipe
[1], EVENT_TFTP_ERR
, errno
, daemon
->tftp_prefix
);
563 for (p
= daemon
->if_prefix
; p
; p
= p
->next
)
565 if (!((dir
= opendir(p
->prefix
))))
567 send_event(err_pipe
[1], EVENT_TFTP_ERR
, errno
, p
->prefix
);
575 if (daemon
->port
== 0)
576 my_syslog(LOG_INFO
, _("started, version %s DNS disabled"), VERSION
);
577 else if (daemon
->cachesize
!= 0)
578 my_syslog(LOG_INFO
, _("started, version %s cachesize %d"), VERSION
, daemon
->cachesize
);
580 my_syslog(LOG_INFO
, _("started, version %s cache disabled"), VERSION
);
582 my_syslog(LOG_INFO
, _("compile time options: %s"), compile_opts
);
585 if (option_bool(OPT_DBUS
))
588 my_syslog(LOG_INFO
, _("DBus support enabled: connected to system bus"));
590 my_syslog(LOG_INFO
, _("DBus support enabled: bus connection pending"));
595 my_syslog(LOG_WARNING
, _("warning: failed to change owner of %s: %s"),
596 daemon
->log_file
, strerror(log_err
));
599 my_syslog(LOG_WARNING
, _("setting --bind-interfaces option because of OS limitations"));
601 if (!option_bool(OPT_NOWILD
))
602 for (if_tmp
= daemon
->if_names
; if_tmp
; if_tmp
= if_tmp
->next
)
603 if (if_tmp
->name
&& !if_tmp
->used
)
604 my_syslog(LOG_WARNING
, _("warning: interface %s does not currently exist"), if_tmp
->name
);
606 if (daemon
->port
!= 0 && option_bool(OPT_NO_RESOLV
))
608 if (daemon
->resolv_files
&& !daemon
->resolv_files
->is_default
)
609 my_syslog(LOG_WARNING
, _("warning: ignoring resolv-file flag because no-resolv is set"));
610 daemon
->resolv_files
= NULL
;
611 if (!daemon
->servers
)
612 my_syslog(LOG_WARNING
, _("warning: no upstream servers configured"));
615 if (daemon
->max_logs
!= 0)
616 my_syslog(LOG_INFO
, _("asynchronous logging enabled, queue limit is %d messages"), daemon
->max_logs
);
618 if (daemon
->ra_contexts
)
619 my_syslog(MS_DHCP
| LOG_INFO
, _("IPv6 router advertisement enabled"));
622 if (daemon
->dhcp
|| daemon
->dhcp6
|| daemon
->ra_contexts
)
624 struct dhcp_context
*dhcp_tmp
;
625 int family
= AF_INET
;
626 dhcp_tmp
= daemon
->dhcp
;
631 for (; dhcp_tmp
; dhcp_tmp
= dhcp_tmp
->next
)
633 void *start
= &dhcp_tmp
->start
;
634 void *end
= &dhcp_tmp
->end
;
637 if (family
== AF_INET6
)
639 start
= &dhcp_tmp
->start6
;
640 end
= &dhcp_tmp
->end6
;
641 struct in6_addr subnet
= dhcp_tmp
->start6
;
642 setaddr6part(&subnet
, 0);
643 inet_ntop(AF_INET6
, &subnet
, daemon
->dhcp_buff2
, 256);
647 if (family
!= AF_INET
&& (dhcp_tmp
->flags
& CONTEXT_DEPRECATE
))
648 strcpy(daemon
->namebuff
, _("prefix deprecated"));
651 char *p
= daemon
->namebuff
;
652 p
+= sprintf(p
, _("lease time "));
653 prettyprint_time(p
, dhcp_tmp
->lease_time
);
656 inet_ntop(family
, start
, daemon
->dhcp_buff
, 256);
657 inet_ntop(family
, end
, daemon
->dhcp_buff3
, 256);
658 if ((dhcp_tmp
->flags
& CONTEXT_DHCP
) || family
== AF_INET
)
659 my_syslog(MS_DHCP
| LOG_INFO
,
660 (dhcp_tmp
->flags
& CONTEXT_RA_STATELESS
) ?
661 _("%s stateless on %s%.0s%.0s") :
662 (dhcp_tmp
->flags
& CONTEXT_STATIC
) ?
663 _("%s, static leases only on %.0s%s, %s") :
664 (dhcp_tmp
->flags
& CONTEXT_PROXY
) ?
665 _("%s, proxy on subnet %.0s%s%.0s") :
666 _("%s, IP range %s -- %s, %s"),
667 (family
!= AF_INET
) ? "DHCPv6" : "DHCP",
668 daemon
->dhcp_buff
, daemon
->dhcp_buff3
, daemon
->namebuff
);
670 if (dhcp_tmp
->flags
& CONTEXT_RA_NAME
)
671 my_syslog(MS_DHCP
| LOG_INFO
, _("DHCPv4-derived IPv6 names on %s"),
673 if (dhcp_tmp
->flags
& (CONTEXT_RA_ONLY
| CONTEXT_RA_NAME
| CONTEXT_RA_STATELESS
))
675 if (!(dhcp_tmp
->flags
& CONTEXT_DEPRECATE
))
677 char *p
= daemon
->namebuff
;
678 p
+= sprintf(p
, _("prefix valid "));
679 prettyprint_time(p
, dhcp_tmp
->lease_time
> 7200 ? dhcp_tmp
->lease_time
: 7200);
681 my_syslog(MS_DHCP
| LOG_INFO
, _("SLAAC on %s %s"),
682 daemon
->dhcp_buff2
, daemon
->namebuff
);
687 if (family
== AF_INET
)
690 if (daemon
->ra_contexts
)
691 dhcp_tmp
= daemon
->ra_contexts
;
693 dhcp_tmp
= daemon
->dhcp6
;
703 if (option_bool(OPT_TFTP
))
706 if (FD_SETSIZE
< (unsigned)max_fd
)
710 my_syslog(MS_TFTP
| LOG_INFO
, "TFTP %s%s %s",
711 daemon
->tftp_prefix
? _("root is ") : _("enabled"),
712 daemon
->tftp_prefix
? daemon
->tftp_prefix
: "",
713 option_bool(OPT_TFTP_SECURE
) ? _("secure mode") : "");
715 /* This is a guess, it assumes that for small limits,
716 disjoint files might be served, but for large limits,
717 a single file will be sent to may clients (the file only needs
720 max_fd
-= 30; /* use other than TFTP */
724 else if (max_fd
< 100)
727 max_fd
= max_fd
- 20;
729 /* if we have to use a limited range of ports,
730 that will limit the number of transfers */
731 if (daemon
->start_tftp_port
!= 0 &&
732 daemon
->end_tftp_port
- daemon
->start_tftp_port
+ 1 < max_fd
)
733 max_fd
= daemon
->end_tftp_port
- daemon
->start_tftp_port
+ 1;
735 if (daemon
->tftp_max
> max_fd
)
737 daemon
->tftp_max
= max_fd
;
738 my_syslog(MS_TFTP
| LOG_WARNING
,
739 _("restricting maximum simultaneous TFTP transfers to %d"),
745 /* finished start-up - release original process */
746 if (err_pipe
[1] != -1)
749 if (daemon
->port
!= 0)
757 struct timeval t
, *tp
= NULL
;
758 fd_set rset
, wset
, eset
;
764 /* if we are out of resources, find how long we have to wait
765 for some to come free, we'll loop around then and restart
766 listening for queries */
767 if ((t
.tv_sec
= set_dns_listeners(now
, &rset
, &maxfd
)) != 0)
773 /* Whilst polling for the dbus, or doing a tftp transfer, wake every quarter second */
774 if (daemon
->tftp_trans
||
775 (option_bool(OPT_DBUS
) && !daemon
->dbus
))
781 /* Wake every second whilst waiting for DAD to complete */
782 else if (is_dad_listeners())
790 set_dbus_listeners(&maxfd
, &rset
, &wset
, &eset
);
796 FD_SET(daemon
->dhcpfd
, &rset
);
797 bump_maxfd(daemon
->dhcpfd
, &maxfd
);
798 if (daemon
->pxefd
!= -1)
800 FD_SET(daemon
->pxefd
, &rset
);
801 bump_maxfd(daemon
->pxefd
, &maxfd
);
809 FD_SET(daemon
->dhcp6fd
, &rset
);
810 bump_maxfd(daemon
->dhcp6fd
, &maxfd
);
813 if (daemon
->ra_contexts
)
815 FD_SET(daemon
->icmp6fd
, &rset
);
816 bump_maxfd(daemon
->icmp6fd
, &maxfd
);
820 #ifdef HAVE_LINUX_NETWORK
821 FD_SET(daemon
->netlinkfd
, &rset
);
822 bump_maxfd(daemon
->netlinkfd
, &maxfd
);
825 FD_SET(piperead
, &rset
);
826 bump_maxfd(piperead
, &maxfd
);
830 while (helper_buf_empty() && do_script_run(now
));
833 while (helper_buf_empty() && do_tftp_script_run());
836 if (!helper_buf_empty())
838 FD_SET(daemon
->helperfd
, &wset
);
839 bump_maxfd(daemon
->helperfd
, &maxfd
);
842 /* need this for other side-effects */
843 while (do_script_run(now
));
846 while (do_tftp_script_run());
852 /* must do this just before select(), when we know no
853 more calls to my_syslog() can occur */
854 set_log_writer(&wset
, &maxfd
);
856 if (select(maxfd
+1, &rset
, &wset
, &eset
, tp
) < 0)
858 /* otherwise undefined after error */
859 FD_ZERO(&rset
); FD_ZERO(&wset
); FD_ZERO(&eset
);
862 now
= dnsmasq_time();
864 check_log_writer(&wset
);
866 /* Check the interfaces to see if any have exited DAD state
867 and if so, bind the address. */
868 if (is_dad_listeners())
870 enumerate_interfaces();
871 /* NB, is_dad_listeners() == 1 --> we're binding interfaces */
872 create_bound_listeners(0);
875 #ifdef HAVE_LINUX_NETWORK
876 if (FD_ISSET(daemon
->netlinkfd
, &rset
))
880 /* Check for changes to resolv files once per second max. */
881 /* Don't go silent for long periods if the clock goes backwards. */
882 if (daemon
->last_resolv
== 0 ||
883 difftime(now
, daemon
->last_resolv
) > 1.0 ||
884 difftime(now
, daemon
->last_resolv
) < -1.0)
886 /* poll_resolv doesn't need to reload first time through, since
887 that's queued anyway. */
889 poll_resolv(0, daemon
->last_resolv
!= 0, now
);
890 daemon
->last_resolv
= now
;
893 if (FD_ISSET(piperead
, &rset
))
894 async_event(piperead
, now
);
897 /* if we didn't create a DBus connection, retry now. */
898 if (option_bool(OPT_DBUS
) && !daemon
->dbus
)
901 if ((err
= dbus_init()))
902 my_syslog(LOG_WARNING
, _("DBus error: %s"), err
);
904 my_syslog(LOG_INFO
, _("connected to system DBus"));
906 check_dbus_listeners(&rset
, &wset
, &eset
);
909 check_dns_listeners(&rset
, now
);
912 check_tftp_listeners(&rset
, now
);
918 if (FD_ISSET(daemon
->dhcpfd
, &rset
))
920 if (daemon
->pxefd
!= -1 && FD_ISSET(daemon
->pxefd
, &rset
))
925 if (daemon
->dhcp6
&& FD_ISSET(daemon
->dhcp6fd
, &rset
))
928 if (daemon
->ra_contexts
&& FD_ISSET(daemon
->icmp6fd
, &rset
))
933 if (daemon
->helperfd
!= -1 && FD_ISSET(daemon
->helperfd
, &wset
))
941 static void sig_handler(int sig
)
945 /* ignore anything other than TERM during startup
946 and in helper proc. (helper ignore TERM too) */
950 else if (pid
!= getpid())
952 /* alarm is used to kill TCP children after a fixed time. */
959 int event
, errsave
= errno
;
962 event
= EVENT_RELOAD
;
963 else if (sig
== SIGCHLD
)
965 else if (sig
== SIGALRM
)
967 else if (sig
== SIGTERM
)
969 else if (sig
== SIGUSR1
)
971 else if (sig
== SIGUSR2
)
972 event
= EVENT_REOPEN
;
976 send_event(pipewrite
, event
, 0, NULL
);
981 /* now == 0 -> queue immediate callback */
982 void send_alarm(time_t event
, time_t now
)
984 if (now
== 0 || event
!= 0)
986 /* alarm(0) or alarm(-ve) doesn't do what we want.... */
987 if ((now
== 0 || difftime(event
, now
) <= 0.0))
988 send_event(pipewrite
, EVENT_ALARM
, 0, NULL
);
990 alarm((unsigned)difftime(event
, now
));
994 void send_event(int fd
, int event
, int data
, char *msg
)
996 struct event_desc ev
;
1001 ev
.msg_sz
= msg
? strlen(msg
) : 0;
1003 iov
[0].iov_base
= &ev
;
1004 iov
[0].iov_len
= sizeof(ev
);
1005 iov
[1].iov_base
= msg
;
1006 iov
[1].iov_len
= ev
.msg_sz
;
1008 /* error pipe, debug mode. */
1010 fatal_event(&ev
, msg
);
1012 /* pipe is non-blocking and struct event_desc is smaller than
1013 PIPE_BUF, so this either fails or writes everything */
1014 while (writev(fd
, iov
, msg
? 2 : 1) == -1 && errno
== EINTR
);
1017 /* NOTE: the memory used to return msg is leaked: use msgs in events only
1018 to describe fatal errors. */
1019 static int read_event(int fd
, struct event_desc
*evp
, char **msg
)
1023 if (!read_write(fd
, (unsigned char *)evp
, sizeof(struct event_desc
), 1))
1028 if (evp
->msg_sz
!= 0 &&
1029 (buf
= malloc(evp
->msg_sz
+ 1)) &&
1030 read_write(fd
, (unsigned char *)buf
, evp
->msg_sz
, 1))
1032 buf
[evp
->msg_sz
] = 0;
1039 static void fatal_event(struct event_desc
*ev
, char *msg
)
1048 case EVENT_FORK_ERR
:
1049 die(_("cannot fork into background: %s"), NULL
, EC_MISC
);
1051 case EVENT_PIPE_ERR
:
1052 die(_("failed to create helper: %s"), NULL
, EC_MISC
);
1055 die(_("setting capabilities failed: %s"), NULL
, EC_MISC
);
1057 case EVENT_USER_ERR
:
1058 die(_("failed to change user-id to %s: %s"), msg
, EC_MISC
);
1060 case EVENT_GROUP_ERR
:
1061 die(_("failed to change group-id to %s: %s"), msg
, EC_MISC
);
1064 die(_("failed to open pidfile %s: %s"), msg
, EC_FILE
);
1067 die(_("cannot open log %s: %s"), msg
, EC_FILE
);
1070 die(_("failed to load Lua script: %s"), msg
, EC_MISC
);
1072 case EVENT_TFTP_ERR
:
1073 die(_("TFTP directory %s inaccessible: %s"), msg
, EC_FILE
);
1077 static void async_event(int pipe
, time_t now
)
1080 struct event_desc ev
;
1084 /* NOTE: the memory used to return msg is leaked: use msgs in events only
1085 to describe fatal errors. */
1087 if (read_event(pipe
, &ev
, &msg
))
1091 clear_cache_and_reload(now
);
1092 if (daemon
->port
!= 0 && daemon
->resolv_files
&& option_bool(OPT_NO_POLL
))
1094 reload_servers(daemon
->resolv_files
->name
);
1103 if (daemon
->port
!= 0)
1109 if (daemon
->dhcp
|| daemon
->dhcp6
)
1111 lease_prune(NULL
, now
);
1112 lease_update_file(now
);
1115 else if (daemon
->ra_contexts
)
1116 /* Not doing DHCP, so no lease system, manage alarms for ra only */
1117 send_alarm(periodic_ra(now
), now
);
1123 /* See Stevens 5.10 */
1124 while ((p
= waitpid(-1, NULL
, WNOHANG
)) != 0)
1131 for (i
= 0 ; i
< MAX_PROCS
; i
++)
1132 if (daemon
->tcp_pids
[i
] == p
)
1133 daemon
->tcp_pids
[i
] = 0;
1137 my_syslog(LOG_WARNING
, _("script process killed by signal %d"), ev
.data
);
1141 my_syslog(LOG_WARNING
, _("script process exited with status %d"), ev
.data
);
1144 case EVENT_EXEC_ERR
:
1145 my_syslog(LOG_ERR
, _("failed to execute %s: %s"),
1146 daemon
->lease_change_command
, strerror(ev
.data
));
1149 /* necessary for fatal errors in helper */
1150 case EVENT_USER_ERR
:
1153 fatal_event(&ev
, msg
);
1157 /* Note: this may leave TCP-handling processes with the old file still open.
1158 Since any such process will die in CHILD_LIFETIME or probably much sooner,
1159 we leave them logging to the old file. */
1160 if (daemon
->log_file
!= NULL
)
1161 log_reopen(daemon
->log_file
);
1165 /* Knock all our children on the head. */
1166 for (i
= 0; i
< MAX_PROCS
; i
++)
1167 if (daemon
->tcp_pids
[i
] != 0)
1168 kill(daemon
->tcp_pids
[i
], SIGALRM
);
1170 #if defined(HAVE_SCRIPT)
1171 /* handle pending lease transitions */
1172 if (daemon
->helperfd
!= -1)
1174 /* block in writes until all done */
1175 if ((i
= fcntl(daemon
->helperfd
, F_GETFL
)) != -1)
1176 fcntl(daemon
->helperfd
, F_SETFL
, i
& ~O_NONBLOCK
);
1179 } while (!helper_buf_empty() || do_script_run(now
));
1180 close(daemon
->helperfd
);
1184 if (daemon
->lease_stream
)
1185 fclose(daemon
->lease_stream
);
1187 if (daemon
->runfile
)
1188 unlink(daemon
->runfile
);
1190 my_syslog(LOG_INFO
, _("exiting on receipt of SIGTERM"));
1196 void poll_resolv(int force
, int do_reload
, time_t now
)
1198 struct resolvc
*res
, *latest
;
1199 struct stat statbuf
;
1200 time_t last_change
= 0;
1201 /* There may be more than one possible file.
1202 Go through and find the one which changed _last_.
1203 Warn of any which can't be read. */
1205 if (daemon
->port
== 0 || option_bool(OPT_NO_POLL
))
1208 for (latest
= NULL
, res
= daemon
->resolv_files
; res
; res
= res
->next
)
1209 if (stat(res
->name
, &statbuf
) == -1)
1218 my_syslog(LOG_WARNING
, _("failed to access %s: %s"), res
->name
, strerror(errno
));
1221 if (res
->mtime
!= 0)
1223 /* existing file evaporated, force selection of the latest
1224 file even if its mtime hasn't changed since we last looked */
1225 poll_resolv(1, do_reload
, now
);
1232 if (force
|| (statbuf
.st_mtime
!= res
->mtime
))
1234 res
->mtime
= statbuf
.st_mtime
;
1235 if (difftime(statbuf
.st_mtime
, last_change
) > 0.0)
1237 last_change
= statbuf
.st_mtime
;
1245 static int warned
= 0;
1246 if (reload_servers(latest
->name
))
1248 my_syslog(LOG_INFO
, _("reading %s"), latest
->name
);
1251 if (option_bool(OPT_RELOAD
) && do_reload
)
1252 clear_cache_and_reload(now
);
1259 my_syslog(LOG_WARNING
, _("no servers found in %s, will retry"), latest
->name
);
1266 void clear_cache_and_reload(time_t now
)
1268 if (daemon
->port
!= 0)
1272 if (daemon
->dhcp
|| daemon
->dhcp6
)
1274 if (option_bool(OPT_ETHERS
))
1277 dhcp_update_configs(daemon
->dhcp_conf
);
1278 lease_update_from_configs();
1279 lease_update_file(now
);
1280 lease_update_dns(1);
1283 else if (daemon
->ra_contexts
)
1284 /* Not doing DHCP, so no lease system, manage
1285 alarms for ra only */
1286 send_alarm(periodic_ra(now
), now
);
1291 static int set_dns_listeners(time_t now
, fd_set
*set
, int *maxfdp
)
1293 struct serverfd
*serverfdp
;
1294 struct listener
*listener
;
1299 struct tftp_transfer
*transfer
;
1300 for (transfer
= daemon
->tftp_trans
; transfer
; transfer
= transfer
->next
)
1303 FD_SET(transfer
->sockfd
, set
);
1304 bump_maxfd(transfer
->sockfd
, maxfdp
);
1308 /* will we be able to get memory? */
1309 if (daemon
->port
!= 0)
1310 get_new_frec(now
, &wait
);
1312 for (serverfdp
= daemon
->sfds
; serverfdp
; serverfdp
= serverfdp
->next
)
1314 FD_SET(serverfdp
->fd
, set
);
1315 bump_maxfd(serverfdp
->fd
, maxfdp
);
1318 if (daemon
->port
!= 0 && !daemon
->osport
)
1319 for (i
= 0; i
< RANDOM_SOCKS
; i
++)
1320 if (daemon
->randomsocks
[i
].refcount
!= 0)
1322 FD_SET(daemon
->randomsocks
[i
].fd
, set
);
1323 bump_maxfd(daemon
->randomsocks
[i
].fd
, maxfdp
);
1326 for (listener
= daemon
->listeners
; listener
; listener
= listener
->next
)
1328 /* only listen for queries if we have resources */
1329 if (listener
->fd
!= -1 && wait
== 0)
1331 FD_SET(listener
->fd
, set
);
1332 bump_maxfd(listener
->fd
, maxfdp
);
1335 /* death of a child goes through the select loop, so
1336 we don't need to explicitly arrange to wake up here */
1337 if (listener
->tcpfd
!= -1)
1338 for (i
= 0; i
< MAX_PROCS
; i
++)
1339 if (daemon
->tcp_pids
[i
] == 0)
1341 FD_SET(listener
->tcpfd
, set
);
1342 bump_maxfd(listener
->tcpfd
, maxfdp
);
1347 if (tftp
<= daemon
->tftp_max
&& listener
->tftpfd
!= -1)
1349 FD_SET(listener
->tftpfd
, set
);
1350 bump_maxfd(listener
->tftpfd
, maxfdp
);
1359 static void check_dns_listeners(fd_set
*set
, time_t now
)
1361 struct serverfd
*serverfdp
;
1362 struct listener
*listener
;
1365 for (serverfdp
= daemon
->sfds
; serverfdp
; serverfdp
= serverfdp
->next
)
1366 if (FD_ISSET(serverfdp
->fd
, set
))
1367 reply_query(serverfdp
->fd
, serverfdp
->source_addr
.sa
.sa_family
, now
);
1369 if (daemon
->port
!= 0 && !daemon
->osport
)
1370 for (i
= 0; i
< RANDOM_SOCKS
; i
++)
1371 if (daemon
->randomsocks
[i
].refcount
!= 0 &&
1372 FD_ISSET(daemon
->randomsocks
[i
].fd
, set
))
1373 reply_query(daemon
->randomsocks
[i
].fd
, daemon
->randomsocks
[i
].family
, now
);
1375 for (listener
= daemon
->listeners
; listener
; listener
= listener
->next
)
1377 if (listener
->fd
!= -1 && FD_ISSET(listener
->fd
, set
))
1378 receive_query(listener
, now
);
1381 if (listener
->tftpfd
!= -1 && FD_ISSET(listener
->tftpfd
, set
))
1382 tftp_request(listener
, now
);
1385 if (listener
->tcpfd
!= -1 && FD_ISSET(listener
->tcpfd
, set
))
1388 struct irec
*iface
= NULL
;
1390 union mysockaddr tcp_addr
;
1391 socklen_t tcp_len
= sizeof(union mysockaddr
);
1393 while ((confd
= accept(listener
->tcpfd
, NULL
, NULL
)) == -1 && errno
== EINTR
);
1396 getsockname(confd
, (struct sockaddr
*)&tcp_addr
, &tcp_len
) == -1)
1399 if (option_bool(OPT_NOWILD
) || option_bool(OPT_CLEVERBIND
))
1400 iface
= listener
->iface
; /* May be NULL */
1403 /* Check for allowed interfaces when binding the wildcard address:
1404 we do this by looking for an interface with the same address as
1405 the local address of the TCP connection, then looking to see if that's
1406 an allowed interface. As a side effect, we get the netmask of the
1407 interface too, for localisation. */
1409 /* interface may be new since startup */
1410 if (enumerate_interfaces())
1411 for (iface
= daemon
->interfaces
; iface
; iface
= iface
->next
)
1412 if (sockaddr_isequal(&iface
->addr
, &tcp_addr
))
1416 if (!iface
&& !(option_bool(OPT_NOWILD
) || option_bool(OPT_CLEVERBIND
)))
1418 shutdown(confd
, SHUT_RDWR
);
1422 else if (!option_bool(OPT_DEBUG
) && (p
= fork()) != 0)
1427 for (i
= 0; i
< MAX_PROCS
; i
++)
1428 if (daemon
->tcp_pids
[i
] == 0)
1430 daemon
->tcp_pids
[i
] = p
;
1439 unsigned char *buff
;
1442 struct in_addr netmask
;
1445 netmask
= iface
->netmask
;
1450 /* Arrange for SIGALARM after CHILD_LIFETIME seconds to
1451 terminate the process. */
1452 if (!option_bool(OPT_DEBUG
))
1453 alarm(CHILD_LIFETIME
);
1456 /* start with no upstream connections. */
1457 for (s
= daemon
->servers
; s
; s
= s
->next
)
1460 /* The connected socket inherits non-blocking
1461 attribute from the listening socket.
1463 if ((flags
= fcntl(confd
, F_GETFL
, 0)) != -1)
1464 fcntl(confd
, F_SETFL
, flags
& ~O_NONBLOCK
);
1466 buff
= tcp_request(confd
, now
, &tcp_addr
, netmask
);
1468 shutdown(confd
, SHUT_RDWR
);
1474 for (s
= daemon
->servers
; s
; s
= s
->next
)
1477 shutdown(s
->tcpfd
, SHUT_RDWR
);
1481 if (!option_bool(OPT_DEBUG
))
1493 int make_icmp_sock(void)
1498 if ((fd
= socket (AF_INET
, SOCK_RAW
, IPPROTO_ICMP
)) != -1)
1501 setsockopt(fd
, SOL_SOCKET
, SO_DONTROUTE
, &zeroopt
, sizeof(zeroopt
)) == -1)
1511 int icmp_ping(struct in_addr addr
)
1513 /* Try and get an ICMP echo from a machine. */
1515 /* Note that whilst in the three second wait, we check for
1516 (and service) events on the DNS and TFTP sockets, (so doing that
1517 better not use any resources our caller has in use...)
1518 but we remain deaf to signals or further DHCP packets. */
1521 struct sockaddr_in saddr
;
1526 unsigned short id
= rand16();
1531 #if defined(HAVE_LINUX_NETWORK) || defined (HAVE_SOLARIS_NETWORK)
1532 if ((fd
= make_icmp_sock()) == -1)
1536 fd
= daemon
->dhcp_icmp_fd
;
1537 setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &opt
, sizeof(opt
));
1540 saddr
.sin_family
= AF_INET
;
1542 saddr
.sin_addr
= addr
;
1543 #ifdef HAVE_SOCKADDR_SA_LEN
1544 saddr
.sin_len
= sizeof(struct sockaddr_in
);
1547 memset(&packet
.icmp
, 0, sizeof(packet
.icmp
));
1548 packet
.icmp
.icmp_type
= ICMP_ECHO
;
1549 packet
.icmp
.icmp_id
= id
;
1550 for (j
= 0, i
= 0; i
< sizeof(struct icmp
) / 2; i
++)
1551 j
+= ((u16
*)&packet
.icmp
)[i
];
1553 j
= (j
& 0xffff) + (j
>> 16);
1554 packet
.icmp
.icmp_cksum
= (j
== 0xffff) ? j
: ~j
;
1556 while (sendto(fd
, (char *)&packet
.icmp
, sizeof(struct icmp
), 0,
1557 (struct sockaddr
*)&saddr
, sizeof(saddr
)) == -1 &&
1560 for (now
= start
= dnsmasq_time();
1561 difftime(now
, start
) < (float)PING_WAIT
;)
1565 struct sockaddr_in faddr
;
1567 socklen_t len
= sizeof(faddr
);
1569 tv
.tv_usec
= 250000;
1575 set_dns_listeners(now
, &rset
, &maxfd
);
1576 set_log_writer(&wset
, &maxfd
);
1579 if (daemon
->ra_contexts
)
1581 FD_SET(daemon
->icmp6fd
, &rset
);
1582 bump_maxfd(daemon
->icmp6fd
, &maxfd
);
1586 if (select(maxfd
+1, &rset
, &wset
, NULL
, &tv
) < 0)
1592 now
= dnsmasq_time();
1594 check_log_writer(&wset
);
1595 check_dns_listeners(&rset
, now
);
1598 if (daemon
->ra_contexts
&& FD_ISSET(daemon
->icmp6fd
, &rset
))
1603 check_tftp_listeners(&rset
, now
);
1606 if (FD_ISSET(fd
, &rset
) &&
1607 recvfrom(fd
, &packet
, sizeof(packet
), 0,
1608 (struct sockaddr
*)&faddr
, &len
) == sizeof(packet
) &&
1609 saddr
.sin_addr
.s_addr
== faddr
.sin_addr
.s_addr
&&
1610 packet
.icmp
.icmp_type
== ICMP_ECHOREPLY
&&
1611 packet
.icmp
.icmp_seq
== 0 &&
1612 packet
.icmp
.icmp_id
== id
)
1619 #if defined(HAVE_LINUX_NETWORK) || defined(HAVE_SOLARIS_NETWORK)
1623 setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &opt
, sizeof(opt
));