]> git.ipfire.org Git - people/ms/dnsmasq.git/blame - src/dnsmasq.c
dhcp-host selection fix for v4/v6
[people/ms/dnsmasq.git] / src / dnsmasq.c
CommitLineData
61744359 1/* dnsmasq is Copyright (c) 2000-2013 Simon Kelley
9e4abcb5
SK
2
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
824af85b
SK
5 the Free Software Foundation; version 2 dated June, 1991, or
6 (at your option) version 3 dated 29 June, 2007.
7
9e4abcb5
SK
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.
824af85b 12
73a08a24
SK
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/>.
9e4abcb5
SK
15*/
16
c72daea8
SK
17/* Declare static char *compiler_opts in config.h */
18#define DNSMASQ_COMPILE_OPTS
19
9e4abcb5
SK
20#include "dnsmasq.h"
21
5aabfc78
SK
22struct daemon *daemon;
23
5aabfc78
SK
24static volatile pid_t pid = 0;
25static volatile int pipewrite;
9e4abcb5 26
5aabfc78
SK
27static int set_dns_listeners(time_t now, fd_set *set, int *maxfdp);
28static void check_dns_listeners(fd_set *set, time_t now);
3be34541 29static void sig_handler(int sig);
5aabfc78 30static void async_event(int pipe, time_t now);
c72daea8
SK
31static void fatal_event(struct event_desc *ev, char *msg);
32static int read_event(int fd, struct event_desc *evp, char **msg);
9e4abcb5
SK
33
34int main (int argc, char **argv)
35{
de37951c 36 int bind_fallback = 0;
9009d746 37 time_t now;
9e4abcb5 38 struct sigaction sigact;
26128d27 39 struct iname *if_tmp;
1a6bca81
SK
40 int piperead, pipefd[2], err_pipe[2];
41 struct passwd *ent_pw = NULL;
c72daea8 42#if defined(HAVE_SCRIPT)
1a6bca81
SK
43 uid_t script_uid = 0;
44 gid_t script_gid = 0;
7622fc06
SK
45#endif
46 struct group *gp = NULL;
5aabfc78 47 long i, max_fd = sysconf(_SC_OPEN_MAX);
1a6bca81
SK
48 char *baduser = NULL;
49 int log_err;
50#if defined(HAVE_LINUX_NETWORK)
51 cap_user_header_t hdr = NULL;
52 cap_user_data_t data = NULL;
53#endif
408c368f 54#if defined(HAVE_DHCP) || defined(HAVE_DHCP6)
1f776932 55 struct dhcp_context *context;
ff7eea27 56 struct dhcp_relay *relay;
408c368f 57#endif
5aabfc78 58
824af85b 59#ifdef LOCALEDIR
b8187c80
SK
60 setlocale(LC_ALL, "");
61 bindtextdomain("dnsmasq", LOCALEDIR);
62 textdomain("dnsmasq");
63#endif
64
9e4abcb5
SK
65 sigact.sa_handler = sig_handler;
66 sigact.sa_flags = 0;
67 sigemptyset(&sigact.sa_mask);
68 sigaction(SIGUSR1, &sigact, NULL);
5aabfc78 69 sigaction(SIGUSR2, &sigact, NULL);
9e4abcb5
SK
70 sigaction(SIGHUP, &sigact, NULL);
71 sigaction(SIGTERM, &sigact, NULL);
44a2a316 72 sigaction(SIGALRM, &sigact, NULL);
feba5c1d
SK
73 sigaction(SIGCHLD, &sigact, NULL);
74
75 /* ignore SIGPIPE */
76 sigact.sa_handler = SIG_IGN;
77 sigaction(SIGPIPE, &sigact, NULL);
9e4abcb5 78
5aabfc78
SK
79 umask(022); /* known umask, create leases and pid files as 0644 */
80
81 read_opts(argc, argv, compile_opts);
82
3be34541
SK
83 if (daemon->edns_pktsz < PACKETSZ)
84 daemon->edns_pktsz = PACKETSZ;
0a852541
SK
85 daemon->packet_buff_sz = daemon->edns_pktsz > DNSMASQ_PACKETSZ ?
86 daemon->edns_pktsz : DNSMASQ_PACKETSZ;
87 daemon->packet = safe_malloc(daemon->packet_buff_sz);
1a6bca81 88
c72daea8
SK
89 daemon->addrbuff = safe_malloc(ADDRSTRLEN);
90
4f7b304f 91
7622fc06 92#ifdef HAVE_DHCP
3be34541 93 if (!daemon->lease_file)
9e4abcb5 94 {
52b92f4d 95 if (daemon->dhcp || daemon->dhcp6)
3be34541 96 daemon->lease_file = LEASEFILE;
9e4abcb5 97 }
7622fc06 98#endif
9e4abcb5 99
a2761754
SK
100 /* Close any file descriptors we inherited apart from std{in|out|err}
101
102 Ensure that at least stdin, stdout and stderr (fd 0, 1, 2) exist,
103 otherwise file descriptors we create can end up being 0, 1, or 2
104 and then get accidentally closed later when we make 0, 1, and 2
105 open to /dev/null. Normally we'll be started with 0, 1 and 2 open,
106 but it's not guaranteed. By opening /dev/null three times, we
107 ensure that we're not using those fds for real stuff. */
5aabfc78
SK
108 for (i = 0; i < max_fd; i++)
109 if (i != STDOUT_FILENO && i != STDERR_FILENO && i != STDIN_FILENO)
110 close(i);
a2761754
SK
111 else
112 open("/dev/null", O_RDWR);
5aabfc78 113
801ca9a7
SK
114#ifndef HAVE_LINUX_NETWORK
115# if !(defined(IP_RECVDSTADDR) && defined(IP_RECVIF) && defined(IP_SENDSRCADDR))
28866e95 116 if (!option_bool(OPT_NOWILD))
de37951c
SK
117 {
118 bind_fallback = 1;
28866e95 119 set_option_bool(OPT_NOWILD);
de37951c 120 }
801ca9a7 121# endif
2b5bae9a
SK
122
123 /* -- bind-dynamic not supported on !Linux, fall back to --bind-interfaces */
54dd393f 124 if (option_bool(OPT_CLEVERBIND))
2b5bae9a
SK
125 {
126 bind_fallback = 1;
127 set_option_bool(OPT_NOWILD);
236e072c 128 reset_option_bool(OPT_CLEVERBIND);
2b5bae9a 129 }
309331f5 130#endif
2b5bae9a 131
832af0ba 132#ifndef HAVE_TFTP
9b40cbf5 133 if (option_bool(OPT_TFTP))
5aabfc78 134 die(_("TFTP server not available: set HAVE_TFTP in src/config.h"), NULL, EC_BADCONF);
832af0ba
SK
135#endif
136
7de060b0
SK
137#ifdef HAVE_CONNTRACK
138 if (option_bool(OPT_CONNTRACK) && (daemon->query_port != 0 || daemon->osport))
139 die (_("Cannot use --conntrack AND --query-port"), NULL, EC_BADCONF);
140#else
141 if (option_bool(OPT_CONNTRACK))
142 die(_("Conntrack support not available: set HAVE_CONNTRACK in src/config.h"), NULL, EC_BADCONF);
143#endif
144
824af85b
SK
145#ifdef HAVE_SOLARIS_NETWORK
146 if (daemon->max_logs != 0)
147 die(_("asychronous logging is not available under Solaris"), NULL, EC_BADCONF);
148#endif
149
572b41eb
SK
150#ifdef __ANDROID__
151 if (daemon->max_logs != 0)
152 die(_("asychronous logging is not available under Android"), NULL, EC_BADCONF);
153#endif
154
4820dce9
SK
155#ifndef HAVE_AUTH
156 if (daemon->authserver)
157 die(_("authoritative DNS not available: set HAVE_AUTH in src/config.h"), NULL, EC_BADCONF);
158#endif
159
1a6bca81
SK
160 rand_init();
161
5aabfc78 162 now = dnsmasq_time();
4f7b304f 163
b0ff858e 164 /* Create a serial at startup if not configured. */
4f7b304f
SK
165 if (daemon->authinterface && daemon->soa_sn == 0)
166#ifdef HAVE_BROKEN_RTC
b0ff858e 167 die(_("zone serial must be configured in --auth-soa"), NULL, EC_BADCONF);
4f7b304f
SK
168#else
169 daemon->soa_sn = now;
170#endif
5aabfc78 171
ff7eea27
SK
172#ifdef HAVE_DHCP6
173 if (daemon->dhcp6)
174 {
175 daemon->doing_ra = option_bool(OPT_RA);
1f776932 176
ff7eea27 177 for (context = daemon->dhcp6; context; context = context->next)
1f776932 178 {
ff7eea27
SK
179 if (context->flags & CONTEXT_DHCP)
180 daemon->doing_dhcp6 = 1;
181 if (context->flags & CONTEXT_RA)
182 daemon->doing_ra = 1;
bb86e858 183#ifndef HAVE_LINUX_NETWORK
ff7eea27
SK
184 if (context->flags & CONTEXT_TEMPLATE)
185 die (_("dhcp-range constructor not available on this platform"), NULL, EC_BADCONF);
bb86e858 186#endif
1f776932 187 }
ff7eea27
SK
188 }
189#endif
190
191#ifdef HAVE_DHCP
192 /* Note that order matters here, we must call lease_init before
193 creating any file descriptors which shouldn't be leaked
194 to the lease-script init process. We need to call common_init
195 before lease_init to allocate buffers it uses.*/
196 if (daemon->dhcp || daemon->doing_dhcp6 || daemon->relay4 || daemon->relay6)
197 {
198 dhcp_common_init();
1f776932 199 if (daemon->dhcp || daemon->doing_dhcp6)
ff7eea27
SK
200 lease_init(now);
201 }
202
203 if (daemon->dhcp || daemon->relay4)
204 dhcp_init();
205
843c96b4 206# ifdef HAVE_DHCP6
89500e31 207 if (daemon->doing_ra || daemon->doing_dhcp6 || daemon->relay6)
ff7eea27
SK
208 ra_init(now);
209
210 if (daemon->doing_dhcp6 || daemon->relay6)
211 dhcp6_init();
801ca9a7
SK
212# endif
213
214#endif
215
13d86c73
JD
216#ifdef HAVE_IPSET
217 if (daemon->ipsets)
218 ipset_init();
219#endif
220
801ca9a7 221#ifdef HAVE_LINUX_NETWORK
801ca9a7 222 netlink_init();
8445f5d2 223
54dd393f
SK
224 if (option_bool(OPT_NOWILD) && option_bool(OPT_CLEVERBIND))
225 die(_("cannot set --bind-interfaces and --bind-dynamic"), NULL, EC_BADCONF);
801ca9a7
SK
226#endif
227
115ac3e4 228 if (!enumerate_interfaces(1) || !enumerate_interfaces(0))
5aabfc78 229 die(_("failed to find list of interfaces: %s"), NULL, EC_MISC);
843c96b4 230
54dd393f 231 if (option_bool(OPT_NOWILD) || option_bool(OPT_CLEVERBIND))
de37951c 232 {
74c95c25 233 create_bound_listeners(1);
54dd393f
SK
234
235 if (!option_bool(OPT_CLEVERBIND))
236 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
237 if (if_tmp->name && !if_tmp->used)
238 die(_("unknown interface %s"), if_tmp->name, EC_BADNET);
9380ba70
SK
239
240#if defined(HAVE_LINUX_NETWORK) && defined(HAVE_DHCP)
241 /* after enumerate_interfaces() */
10ae7b50 242 if (daemon->dhcp)
9380ba70 243 {
10ae7b50
SK
244 if (!daemon->relay4)
245 bindtodevice(daemon->dhcpfd);
9380ba70
SK
246 if (daemon->enable_pxe)
247 bindtodevice(daemon->pxefd);
248 }
249#endif
250
251#if defined(HAVE_LINUX_NETWORK) && defined(HAVE_DHCP6)
10ae7b50 252 if (daemon->doing_dhcp6 && !daemon->relay6)
9380ba70
SK
253 bindtodevice(daemon->dhcp6fd);
254#endif
de37951c 255 }
28866e95 256 else
74c95c25 257 create_wildcard_listeners();
5d162f20
SK
258
259#ifdef HAVE_DHCP6
260 /* after enumerate_interfaces() */
ff7eea27 261 if (daemon->doing_dhcp6 || daemon->relay6 || daemon->doing_ra)
5d162f20
SK
262 join_multicast(1);
263#endif
de37951c 264
824af85b
SK
265 if (daemon->port != 0)
266 cache_init();
1a6bca81 267
28866e95 268 if (option_bool(OPT_DBUS))
3d8df260
SK
269#ifdef HAVE_DBUS
270 {
271 char *err;
272 daemon->dbus = NULL;
273 daemon->watches = NULL;
5aabfc78
SK
274 if ((err = dbus_init()))
275 die(_("DBus error: %s"), err, EC_MISC);
3d8df260
SK
276 }
277#else
5aabfc78 278 die(_("DBus not available: set HAVE_DBUS in src/config.h"), NULL, EC_BADCONF);
3d8df260
SK
279#endif
280
824af85b
SK
281 if (daemon->port != 0)
282 pre_allocate_sfds();
1a6bca81 283
c72daea8 284#if defined(HAVE_SCRIPT)
1a6bca81 285 /* Note getpwnam returns static storage */
843c96b4
SK
286 if ((daemon->dhcp || daemon->dhcp6) &&
287 daemon->scriptuser &&
c72daea8 288 (daemon->lease_change_command || daemon->luascript))
1a6bca81
SK
289 {
290 if ((ent_pw = getpwnam(daemon->scriptuser)))
291 {
292 script_uid = ent_pw->pw_uid;
293 script_gid = ent_pw->pw_gid;
294 }
295 else
296 baduser = daemon->scriptuser;
297 }
7622fc06 298#endif
9e4abcb5 299
1a6bca81
SK
300 if (daemon->username && !(ent_pw = getpwnam(daemon->username)))
301 baduser = daemon->username;
302 else if (daemon->groupname && !(gp = getgrnam(daemon->groupname)))
303 baduser = daemon->groupname;
304
305 if (baduser)
306 die(_("unknown user or group: %s"), baduser, EC_BADCONF);
307
308 /* implement group defaults, "dip" if available, or group associated with uid */
309 if (!daemon->group_set && !gp)
310 {
311 if (!(gp = getgrnam(CHGRP)) && ent_pw)
312 gp = getgrgid(ent_pw->pw_gid);
313
314 /* for error message */
315 if (gp)
316 daemon->groupname = gp->gr_name;
317 }
318
319#if defined(HAVE_LINUX_NETWORK)
320 /* determine capability API version here, while we can still
321 call safe_malloc */
322 if (ent_pw && ent_pw->pw_uid != 0)
323 {
1a6bca81 324 int capsize = 1; /* for header version 1 */
3927da46
SK
325 hdr = safe_malloc(sizeof(*hdr));
326
1a6bca81
SK
327 /* find version supported by kernel */
328 memset(hdr, 0, sizeof(*hdr));
329 capget(hdr, NULL);
330
331 if (hdr->version != LINUX_CAPABILITY_VERSION_1)
332 {
333 /* if unknown version, use largest supported version (3) */
334 if (hdr->version != LINUX_CAPABILITY_VERSION_2)
335 hdr->version = LINUX_CAPABILITY_VERSION_3;
336 capsize = 2;
337 }
338
339 data = safe_malloc(sizeof(*data) * capsize);
340 memset(data, 0, sizeof(*data) * capsize);
341 }
342#endif
343
5aabfc78 344 /* Use a pipe to carry signals and other events back to the event loop
1a6bca81
SK
345 in a race-free manner and another to carry errors to daemon-invoking process */
346 safe_pipe(pipefd, 1);
5e9e0efb
SK
347
348 piperead = pipefd[0];
349 pipewrite = pipefd[1];
350 /* prime the pipe to load stuff first time. */
c72daea8 351 send_event(pipewrite, EVENT_RELOAD, 0, NULL);
1a6bca81
SK
352
353 err_pipe[1] = -1;
1697269c 354
28866e95 355 if (!option_bool(OPT_DEBUG))
9e4abcb5 356 {
9e4abcb5
SK
357 /* The following code "daemonizes" the process.
358 See Stevens section 12.4 */
1a6bca81 359
9e038946
SK
360 if (chdir("/") != 0)
361 die(_("cannot chdir to filesystem root: %s"), NULL, EC_MISC);
362
1697269c 363#ifndef NO_FORK
28866e95 364 if (!option_bool(OPT_NO_FORK))
3be34541 365 {
5aabfc78 366 pid_t pid;
3be34541 367
1a6bca81
SK
368 /* pipe to carry errors back to original process.
369 When startup is complete we close this and the process terminates. */
370 safe_pipe(err_pipe, 0);
371
7622fc06
SK
372 if ((pid = fork()) == -1)
373 /* fd == -1 since we've not forked, never returns. */
c72daea8 374 send_event(-1, EVENT_FORK_ERR, errno, NULL);
9e038946 375
5aabfc78 376 if (pid != 0)
1a6bca81
SK
377 {
378 struct event_desc ev;
c72daea8
SK
379 char *msg;
380
1a6bca81
SK
381 /* close our copy of write-end */
382 close(err_pipe[1]);
383
384 /* check for errors after the fork */
c72daea8
SK
385 if (read_event(err_pipe[0], &ev, &msg))
386 fatal_event(&ev, msg);
1a6bca81
SK
387
388 _exit(EC_GOOD);
389 }
390
391 close(err_pipe[0]);
392
393 /* NO calls to die() from here on. */
3be34541 394
5aabfc78 395 setsid();
7622fc06
SK
396
397 if ((pid = fork()) == -1)
c72daea8 398 send_event(err_pipe[1], EVENT_FORK_ERR, errno, NULL);
7622fc06
SK
399
400 if (pid != 0)
7cebd20f 401 _exit(0);
3be34541 402 }
9e4abcb5 403#endif
9e038946 404
9e4abcb5 405 /* write pidfile _after_ forking ! */
1a6bca81
SK
406 if (daemon->runfile)
407 {
79cfefd8
SK
408 int fd, err = 0;
409
410 sprintf(daemon->namebuff, "%d\n", (int) getpid());
411
412 /* Explanation: Some installations of dnsmasq (eg Debian/Ubuntu) locate the pid-file
413 in a directory which is writable by the non-privileged user that dnsmasq runs as. This
414 allows the daemon to delete the file as part of its shutdown. This is a security hole to the
415 extent that an attacker running as the unprivileged user could replace the pidfile with a
416 symlink, and have the target of that symlink overwritten as root next time dnsmasq starts.
417
418 The folowing code first deletes any existing file, and then opens it with the O_EXCL flag,
419 ensuring that the open() fails should there be any existing file (because the unlink() failed,
420 or an attacker exploited the race between unlink() and open()). This ensures that no symlink
421 attack can succeed.
422
423 Any compromise of the non-privileged user still theoretically allows the pid-file to be
424 replaced whilst dnsmasq is running. The worst that could allow is that the usual
425 "shutdown dnsmasq" shell command could be tricked into stopping any other process.
426
427 Note that if dnsmasq is started as non-root (eg for testing) it silently ignores
428 failure to write the pid-file.
429 */
430
431 unlink(daemon->runfile);
1a6bca81 432
79cfefd8 433 if ((fd = open(daemon->runfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH)) == -1)
1a6bca81 434 {
79cfefd8
SK
435 /* only complain if started as root */
436 if (getuid() == 0)
437 err = 1;
1a6bca81 438 }
79cfefd8
SK
439 else
440 {
441 if (!read_write(fd, (unsigned char *)daemon->namebuff, strlen(daemon->namebuff), 0))
442 err = 1;
443
444 while (!err && close(fd) == -1)
445 if (!retry_send())
446 err = 1;
447 }
448
449 if (err)
1a6bca81 450 {
c72daea8 451 send_event(err_pipe[1], EVENT_PIDFILE, errno, daemon->runfile);
1a6bca81
SK
452 _exit(0);
453 }
9e4abcb5 454 }
1697269c
SK
455 }
456
8ef5ada2
SK
457 log_err = log_start(ent_pw, err_pipe[1]);
458
28866e95 459 if (!option_bool(OPT_DEBUG))
8ef5ada2
SK
460 {
461 /* open stdout etc to /dev/null */
462 int nullfd = open("/dev/null", O_RDWR);
463 dup2(nullfd, STDOUT_FILENO);
464 dup2(nullfd, STDERR_FILENO);
465 dup2(nullfd, STDIN_FILENO);
466 close(nullfd);
467 }
1a6bca81
SK
468
469 /* if we are to run scripts, we need to fork a helper before dropping root. */
470 daemon->helperfd = -1;
c72daea8 471#ifdef HAVE_SCRIPT
52b92f4d 472 if ((daemon->dhcp || daemon->dhcp6) && (daemon->lease_change_command || daemon->luascript))
1a6bca81 473 daemon->helperfd = create_helper(pipewrite, err_pipe[1], script_uid, script_gid, max_fd);
5aabfc78 474#endif
5aabfc78 475
28866e95 476 if (!option_bool(OPT_DEBUG) && getuid() == 0)
1697269c 477 {
1a6bca81
SK
478 int bad_capabilities = 0;
479 gid_t dummy;
480
481 /* remove all supplimentary groups */
482 if (gp &&
483 (setgroups(0, &dummy) == -1 ||
484 setgid(gp->gr_gid) == -1))
9e4abcb5 485 {
c72daea8 486 send_event(err_pipe[1], EVENT_GROUP_ERR, errno, daemon->groupname);
1a6bca81 487 _exit(0);
7cebd20f 488 }
1a6bca81 489
7cebd20f 490 if (ent_pw && ent_pw->pw_uid != 0)
1697269c 491 {
74c95c25 492#if defined(HAVE_LINUX_NETWORK)
1697269c 493 /* On linux, we keep CAP_NETADMIN (for ARP-injection) and
74c95c25 494 CAP_NET_RAW (for icmp) if we're doing dhcp. If we have yet to bind
54dd393f
SK
495 ports because of DAD, or we're doing it dynamically,
496 we need CAP_NET_BIND_SERVICE too. */
497 if (is_dad_listeners() || option_bool(OPT_CLEVERBIND))
74c95c25
SK
498 data->effective = data->permitted = data->inheritable =
499 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) |
500 (1 << CAP_SETUID) | (1 << CAP_NET_BIND_SERVICE);
501 else
502 data->effective = data->permitted = data->inheritable =
503 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID);
5e9e0efb 504
1697269c 505 /* Tell kernel to not clear capabilities when dropping root */
572b41eb 506 if (capset(hdr, data) == -1 || prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1)
1697269c 507 bad_capabilities = errno;
1a6bca81 508
7622fc06 509#elif defined(HAVE_SOLARIS_NETWORK)
824af85b
SK
510 /* http://developers.sun.com/solaris/articles/program_privileges.html */
511 priv_set_t *priv_set;
512
513 if (!(priv_set = priv_str_to_set("basic", ",", NULL)) ||
514 priv_addset(priv_set, PRIV_NET_ICMPACCESS) == -1 ||
515 priv_addset(priv_set, PRIV_SYS_NET_CONFIG) == -1)
516 bad_capabilities = errno;
517
518 if (priv_set && bad_capabilities == 0)
519 {
520 priv_inverse(priv_set);
521
522 if (setppriv(PRIV_OFF, PRIV_LIMIT, priv_set) == -1)
523 bad_capabilities = errno;
524 }
525
526 if (priv_set)
527 priv_freeset(priv_set);
528
824af85b
SK
529#endif
530
1a6bca81 531 if (bad_capabilities != 0)
1697269c 532 {
c72daea8 533 send_event(err_pipe[1], EVENT_CAP_ERR, bad_capabilities, NULL);
1a6bca81
SK
534 _exit(0);
535 }
536
537 /* finally drop root */
538 if (setuid(ent_pw->pw_uid) == -1)
539 {
c72daea8 540 send_event(err_pipe[1], EVENT_USER_ERR, errno, daemon->username);
1a6bca81
SK
541 _exit(0);
542 }
543
1697269c 544#ifdef HAVE_LINUX_NETWORK
54dd393f 545 if (is_dad_listeners() || option_bool(OPT_CLEVERBIND))
74c95c25
SK
546 data->effective = data->permitted =
547 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_NET_BIND_SERVICE);
548 else
549 data->effective = data->permitted =
550 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW);
1a6bca81
SK
551 data->inheritable = 0;
552
553 /* lose the setuid and setgid capbilities */
554 if (capset(hdr, data) == -1)
555 {
c72daea8 556 send_event(err_pipe[1], EVENT_CAP_ERR, errno, NULL);
1a6bca81 557 _exit(0);
1697269c 558 }
1a6bca81
SK
559#endif
560
9e4abcb5
SK
561 }
562 }
1697269c 563
1697269c 564#ifdef HAVE_LINUX_NETWORK
28866e95 565 if (option_bool(OPT_DEBUG))
572b41eb 566 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
1697269c 567#endif
9e4abcb5 568
8b3ae2fd 569#ifdef HAVE_TFTP
8bc4cece 570 if (option_bool(OPT_TFTP))
8b3ae2fd
SK
571 {
572 DIR *dir;
573 struct tftp_prefix *p;
574
575 if (daemon->tftp_prefix)
576 {
577 if (!((dir = opendir(daemon->tftp_prefix))))
578 {
579 send_event(err_pipe[1], EVENT_TFTP_ERR, errno, daemon->tftp_prefix);
580 _exit(0);
581 }
582 closedir(dir);
583 }
584
585 for (p = daemon->if_prefix; p; p = p->next)
586 {
587 if (!((dir = opendir(p->prefix))))
588 {
589 send_event(err_pipe[1], EVENT_TFTP_ERR, errno, p->prefix);
590 _exit(0);
591 }
592 closedir(dir);
593 }
594 }
595#endif
596
824af85b
SK
597 if (daemon->port == 0)
598 my_syslog(LOG_INFO, _("started, version %s DNS disabled"), VERSION);
599 else if (daemon->cachesize != 0)
f2621c7f 600 my_syslog(LOG_INFO, _("started, version %s cachesize %d"), VERSION, daemon->cachesize);
9e4abcb5 601 else
f2621c7f 602 my_syslog(LOG_INFO, _("started, version %s cache disabled"), VERSION);
1697269c 603
f2621c7f 604 my_syslog(LOG_INFO, _("compile time options: %s"), compile_opts);
1697269c 605
3d8df260 606#ifdef HAVE_DBUS
28866e95 607 if (option_bool(OPT_DBUS))
3d8df260
SK
608 {
609 if (daemon->dbus)
f2621c7f 610 my_syslog(LOG_INFO, _("DBus support enabled: connected to system bus"));
3d8df260 611 else
f2621c7f 612 my_syslog(LOG_INFO, _("DBus support enabled: bus connection pending"));
3d8df260
SK
613 }
614#endif
615
1a6bca81
SK
616 if (log_err != 0)
617 my_syslog(LOG_WARNING, _("warning: failed to change owner of %s: %s"),
618 daemon->log_file, strerror(log_err));
619
de37951c 620 if (bind_fallback)
f2621c7f 621 my_syslog(LOG_WARNING, _("setting --bind-interfaces option because of OS limitations"));
de37951c 622
28866e95 623 if (!option_bool(OPT_NOWILD))
26128d27
SK
624 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
625 if (if_tmp->name && !if_tmp->used)
f2621c7f 626 my_syslog(LOG_WARNING, _("warning: interface %s does not currently exist"), if_tmp->name);
5e9e0efb 627
28866e95 628 if (daemon->port != 0 && option_bool(OPT_NO_RESOLV))
208b65c5
SK
629 {
630 if (daemon->resolv_files && !daemon->resolv_files->is_default)
f2621c7f 631 my_syslog(LOG_WARNING, _("warning: ignoring resolv-file flag because no-resolv is set"));
208b65c5 632 daemon->resolv_files = NULL;
1b7ecd11 633 if (!daemon->servers)
f2621c7f 634 my_syslog(LOG_WARNING, _("warning: no upstream servers configured"));
208b65c5
SK
635 }
636
f2621c7f
SK
637 if (daemon->max_logs != 0)
638 my_syslog(LOG_INFO, _("asynchronous logging enabled, queue limit is %d messages"), daemon->max_logs);
1f776932 639
f2621c7f 640
7622fc06 641#ifdef HAVE_DHCP
1f776932
SK
642 for (context = daemon->dhcp; context; context = context->next)
643 log_context(AF_INET, context);
52b92f4d 644
ff7eea27
SK
645 for (relay = daemon->relay4; relay; relay = relay->next)
646 log_relay(AF_INET, relay);
647
1f776932
SK
648# ifdef HAVE_DHCP6
649 for (context = daemon->dhcp6; context; context = context->next)
650 log_context(AF_INET6, context);
651
ff7eea27
SK
652 for (relay = daemon->relay6; relay; relay = relay->next)
653 log_relay(AF_INET6, relay);
654
1f776932
SK
655 if (daemon->doing_dhcp6 || daemon->doing_ra)
656 dhcp_construct_contexts(now);
657
658 if (option_bool(OPT_RA))
659 my_syslog(MS_DHCP | LOG_INFO, _("IPv6 router advertisement enabled"));
660# endif
26128d27 661
8445f5d2
SK
662 /* after dhcp_contruct_contexts */
663 if (daemon->dhcp || daemon->doing_dhcp6)
664 lease_find_interfaces(now);
1f776932 665#endif
52b92f4d 666
832af0ba 667#ifdef HAVE_TFTP
8bc4cece 668 if (option_bool(OPT_TFTP))
832af0ba 669 {
832af0ba 670#ifdef FD_SETSIZE
5aabfc78 671 if (FD_SETSIZE < (unsigned)max_fd)
832af0ba
SK
672 max_fd = FD_SETSIZE;
673#endif
674
7622fc06 675 my_syslog(MS_TFTP | LOG_INFO, "TFTP %s%s %s",
f2621c7f
SK
676 daemon->tftp_prefix ? _("root is ") : _("enabled"),
677 daemon->tftp_prefix ? daemon->tftp_prefix: "",
28866e95 678 option_bool(OPT_TFTP_SECURE) ? _("secure mode") : "");
f2621c7f 679
832af0ba 680 /* This is a guess, it assumes that for small limits,
f2621c7f 681 disjoint files might be served, but for large limits,
832af0ba
SK
682 a single file will be sent to may clients (the file only needs
683 one fd). */
684
685 max_fd -= 30; /* use other than TFTP */
686
687 if (max_fd < 0)
688 max_fd = 5;
689 else if (max_fd < 100)
690 max_fd = max_fd/2;
691 else
692 max_fd = max_fd - 20;
824af85b
SK
693
694 /* if we have to use a limited range of ports,
695 that will limit the number of transfers */
696 if (daemon->start_tftp_port != 0 &&
697 daemon->end_tftp_port - daemon->start_tftp_port + 1 < max_fd)
698 max_fd = daemon->end_tftp_port - daemon->start_tftp_port + 1;
832af0ba
SK
699
700 if (daemon->tftp_max > max_fd)
701 {
702 daemon->tftp_max = max_fd;
7622fc06 703 my_syslog(MS_TFTP | LOG_WARNING,
f2621c7f
SK
704 _("restricting maximum simultaneous TFTP transfers to %d"),
705 daemon->tftp_max);
832af0ba
SK
706 }
707 }
708#endif
709
1a6bca81
SK
710 /* finished start-up - release original process */
711 if (err_pipe[1] != -1)
712 close(err_pipe[1]);
9e4abcb5 713
824af85b
SK
714 if (daemon->port != 0)
715 check_servers();
716
7cebd20f
SK
717 pid = getpid();
718
5e9e0efb 719 while (1)
9e4abcb5 720 {
1697269c 721 int maxfd = -1;
5e9e0efb 722 struct timeval t, *tp = NULL;
3d8df260 723 fd_set rset, wset, eset;
9e4abcb5
SK
724
725 FD_ZERO(&rset);
3d8df260
SK
726 FD_ZERO(&wset);
727 FD_ZERO(&eset);
9e4abcb5 728
1697269c
SK
729 /* if we are out of resources, find how long we have to wait
730 for some to come free, we'll loop around then and restart
731 listening for queries */
5aabfc78 732 if ((t.tv_sec = set_dns_listeners(now, &rset, &maxfd)) != 0)
1697269c
SK
733 {
734 t.tv_usec = 0;
735 tp = &t;
736 }
737
832af0ba
SK
738 /* Whilst polling for the dbus, or doing a tftp transfer, wake every quarter second */
739 if (daemon->tftp_trans ||
28866e95 740 (option_bool(OPT_DBUS) && !daemon->dbus))
5e9e0efb 741 {
1697269c
SK
742 t.tv_sec = 0;
743 t.tv_usec = 250000;
5e9e0efb 744 tp = &t;
5e9e0efb 745 }
74c95c25
SK
746 /* Wake every second whilst waiting for DAD to complete */
747 else if (is_dad_listeners())
748 {
749 t.tv_sec = 1;
750 t.tv_usec = 0;
751 tp = &t;
752 }
44a2a316 753
832af0ba 754#ifdef HAVE_DBUS
5aabfc78 755 set_dbus_listeners(&maxfd, &rset, &wset, &eset);
5e9e0efb
SK
756#endif
757
7622fc06 758#ifdef HAVE_DHCP
ff7eea27 759 if (daemon->dhcp || daemon->relay4)
5e9e0efb
SK
760 {
761 FD_SET(daemon->dhcpfd, &rset);
1697269c 762 bump_maxfd(daemon->dhcpfd, &maxfd);
316e2730
SK
763 if (daemon->pxefd != -1)
764 {
765 FD_SET(daemon->pxefd, &rset);
766 bump_maxfd(daemon->pxefd, &maxfd);
767 }
5e9e0efb 768 }
7622fc06 769#endif
cdeda28f 770
52b92f4d 771#ifdef HAVE_DHCP6
ff7eea27 772 if (daemon->doing_dhcp6 || daemon->relay6)
52b92f4d
SK
773 {
774 FD_SET(daemon->dhcp6fd, &rset);
c5ad4e79 775 bump_maxfd(daemon->dhcp6fd, &maxfd);
5d71d834
SK
776 }
777
1f776932 778 if (daemon->doing_ra)
5d71d834
SK
779 {
780 FD_SET(daemon->icmp6fd, &rset);
781 bump_maxfd(daemon->icmp6fd, &maxfd);
52b92f4d
SK
782 }
783#endif
784
5e9e0efb
SK
785#ifdef HAVE_LINUX_NETWORK
786 FD_SET(daemon->netlinkfd, &rset);
1697269c 787 bump_maxfd(daemon->netlinkfd, &maxfd);
3d8df260 788#endif
3d8df260 789
5e9e0efb 790 FD_SET(piperead, &rset);
1697269c
SK
791 bump_maxfd(piperead, &maxfd);
792
7622fc06 793#ifdef HAVE_DHCP
1f15b81d 794# ifdef HAVE_SCRIPT
5aabfc78 795 while (helper_buf_empty() && do_script_run(now));
1697269c 796
a9530964
SK
797# ifdef HAVE_TFTP
798 while (helper_buf_empty() && do_tftp_script_run());
799# endif
800
1697269c
SK
801 if (!helper_buf_empty())
802 {
803 FD_SET(daemon->helperfd, &wset);
804 bump_maxfd(daemon->helperfd, &maxfd);
805 }
7622fc06 806# else
5aabfc78
SK
807 /* need this for other side-effects */
808 while (do_script_run(now));
a9530964
SK
809
810# ifdef HAVE_TFTP
811 while (do_tftp_script_run());
812# endif
813
7622fc06 814# endif
5aabfc78 815#endif
7622fc06 816
f2621c7f
SK
817 /* must do this just before select(), when we know no
818 more calls to my_syslog() can occur */
819 set_log_writer(&wset, &maxfd);
820
5e9e0efb
SK
821 if (select(maxfd+1, &rset, &wset, &eset, tp) < 0)
822 {
823 /* otherwise undefined after error */
824 FD_ZERO(&rset); FD_ZERO(&wset); FD_ZERO(&eset);
825 }
826
827 now = dnsmasq_time();
9e4abcb5 828
f2621c7f 829 check_log_writer(&wset);
115ac3e4
SK
830
831 /* prime. */
832 enumerate_interfaces(1);
833
74c95c25
SK
834 /* Check the interfaces to see if any have exited DAD state
835 and if so, bind the address. */
836 if (is_dad_listeners())
837 {
115ac3e4 838 enumerate_interfaces(0);
74c95c25
SK
839 /* NB, is_dad_listeners() == 1 --> we're binding interfaces */
840 create_bound_listeners(0);
841 }
f2621c7f 842
c52e1897
SK
843#ifdef HAVE_LINUX_NETWORK
844 if (FD_ISSET(daemon->netlinkfd, &rset))
1f776932 845 netlink_multicast(now);
c52e1897
SK
846#endif
847
9e4abcb5 848 /* Check for changes to resolv files once per second max. */
3d8df260 849 /* Don't go silent for long periods if the clock goes backwards. */
9009d746
SK
850 if (daemon->last_resolv == 0 ||
851 difftime(now, daemon->last_resolv) > 1.0 ||
852 difftime(now, daemon->last_resolv) < -1.0)
9e4abcb5 853 {
8ef5ada2
SK
854 /* poll_resolv doesn't need to reload first time through, since
855 that's queued anyway. */
33820b7e 856
8ef5ada2
SK
857 poll_resolv(0, daemon->last_resolv != 0, now);
858 daemon->last_resolv = now;
9e4abcb5 859 }
5aabfc78 860
5e9e0efb 861 if (FD_ISSET(piperead, &rset))
5aabfc78 862 async_event(piperead, now);
7cebd20f 863
3d8df260
SK
864#ifdef HAVE_DBUS
865 /* if we didn't create a DBus connection, retry now. */
28866e95 866 if (option_bool(OPT_DBUS) && !daemon->dbus)
3d8df260
SK
867 {
868 char *err;
5aabfc78 869 if ((err = dbus_init()))
f2621c7f 870 my_syslog(LOG_WARNING, _("DBus error: %s"), err);
3d8df260 871 if (daemon->dbus)
f2621c7f 872 my_syslog(LOG_INFO, _("connected to system DBus"));
3d8df260 873 }
5aabfc78 874 check_dbus_listeners(&rset, &wset, &eset);
3d8df260 875#endif
824af85b 876
5aabfc78 877 check_dns_listeners(&rset, now);
832af0ba
SK
878
879#ifdef HAVE_TFTP
5aabfc78 880 check_tftp_listeners(&rset, now);
832af0ba
SK
881#endif
882
7622fc06 883#ifdef HAVE_DHCP
ff7eea27 884 if (daemon->dhcp || daemon->relay4)
316e2730
SK
885 {
886 if (FD_ISSET(daemon->dhcpfd, &rset))
887 dhcp_packet(now, 0);
888 if (daemon->pxefd != -1 && FD_ISSET(daemon->pxefd, &rset))
889 dhcp_packet(now, 1);
890 }
1697269c 891
52b92f4d 892#ifdef HAVE_DHCP6
ff7eea27 893 if ((daemon->doing_dhcp6 || daemon->relay6) && FD_ISSET(daemon->dhcp6fd, &rset))
18c63eff 894 dhcp6_packet(now);
c5ad4e79 895
1f776932
SK
896 if (daemon->doing_ra && FD_ISSET(daemon->icmp6fd, &rset))
897 icmp6_packet(now);
52b92f4d
SK
898#endif
899
1f15b81d 900# ifdef HAVE_SCRIPT
1697269c 901 if (daemon->helperfd != -1 && FD_ISSET(daemon->helperfd, &wset))
5aabfc78 902 helper_write();
7622fc06 903# endif
5aabfc78
SK
904#endif
905
9e4abcb5 906 }
9e4abcb5
SK
907}
908
3be34541
SK
909static void sig_handler(int sig)
910{
5e9e0efb 911 if (pid == 0)
3be34541 912 {
1697269c
SK
913 /* ignore anything other than TERM during startup
914 and in helper proc. (helper ignore TERM too) */
5e9e0efb 915 if (sig == SIGTERM)
5aabfc78 916 exit(EC_MISC);
3be34541 917 }
5aabfc78 918 else if (pid != getpid())
5e9e0efb 919 {
1697269c 920 /* alarm is used to kill TCP children after a fixed time. */
5e9e0efb 921 if (sig == SIGALRM)
7cebd20f 922 _exit(0);
3be34541 923 }
5aabfc78
SK
924 else
925 {
926 /* master process */
927 int event, errsave = errno;
928
929 if (sig == SIGHUP)
930 event = EVENT_RELOAD;
931 else if (sig == SIGCHLD)
932 event = EVENT_CHILD;
933 else if (sig == SIGALRM)
934 event = EVENT_ALARM;
935 else if (sig == SIGTERM)
936 event = EVENT_TERM;
937 else if (sig == SIGUSR1)
938 event = EVENT_DUMP;
939 else if (sig == SIGUSR2)
940 event = EVENT_REOPEN;
941 else
942 return;
943
c72daea8 944 send_event(pipewrite, event, 0, NULL);
5aabfc78
SK
945 errno = errsave;
946 }
947}
948
353ae4d2
SK
949/* now == 0 -> queue immediate callback */
950void send_alarm(time_t event, time_t now)
741c2952 951{
884a6dfe 952 if (now == 0 || event != 0)
353ae4d2 953 {
884a6dfe
SK
954 /* alarm(0) or alarm(-ve) doesn't do what we want.... */
955 if ((now == 0 || difftime(event, now) <= 0.0))
956 send_event(pipewrite, EVENT_ALARM, 0, NULL);
957 else
958 alarm((unsigned)difftime(event, now));
353ae4d2 959 }
741c2952
SK
960}
961
c72daea8 962void send_event(int fd, int event, int data, char *msg)
5aabfc78
SK
963{
964 struct event_desc ev;
c72daea8
SK
965 struct iovec iov[2];
966
5aabfc78
SK
967 ev.event = event;
968 ev.data = data;
c72daea8
SK
969 ev.msg_sz = msg ? strlen(msg) : 0;
970
971 iov[0].iov_base = &ev;
972 iov[0].iov_len = sizeof(ev);
973 iov[1].iov_base = msg;
974 iov[1].iov_len = ev.msg_sz;
1a6bca81
SK
975
976 /* error pipe, debug mode. */
977 if (fd == -1)
c72daea8 978 fatal_event(&ev, msg);
1a6bca81
SK
979 else
980 /* pipe is non-blocking and struct event_desc is smaller than
981 PIPE_BUF, so this either fails or writes everything */
c72daea8 982 while (writev(fd, iov, msg ? 2 : 1) == -1 && errno == EINTR);
5aabfc78
SK
983}
984
c72daea8
SK
985/* NOTE: the memory used to return msg is leaked: use msgs in events only
986 to describe fatal errors. */
987static int read_event(int fd, struct event_desc *evp, char **msg)
988{
989 char *buf;
990
991 if (!read_write(fd, (unsigned char *)evp, sizeof(struct event_desc), 1))
992 return 0;
993
994 *msg = NULL;
995
996 if (evp->msg_sz != 0 &&
997 (buf = malloc(evp->msg_sz + 1)) &&
998 read_write(fd, (unsigned char *)buf, evp->msg_sz, 1))
999 {
1000 buf[evp->msg_sz] = 0;
1001 *msg = buf;
1002 }
1003
1004 return 1;
1005}
1006
1007static void fatal_event(struct event_desc *ev, char *msg)
1a6bca81
SK
1008{
1009 errno = ev->data;
1010
1011 switch (ev->event)
1012 {
1013 case EVENT_DIE:
1014 exit(0);
7622fc06
SK
1015
1016 case EVENT_FORK_ERR:
1017 die(_("cannot fork into background: %s"), NULL, EC_MISC);
1a6bca81
SK
1018
1019 case EVENT_PIPE_ERR:
1020 die(_("failed to create helper: %s"), NULL, EC_MISC);
1021
1022 case EVENT_CAP_ERR:
1023 die(_("setting capabilities failed: %s"), NULL, EC_MISC);
1024
1025 case EVENT_USER_ERR:
c72daea8 1026 die(_("failed to change user-id to %s: %s"), msg, EC_MISC);
1a6bca81
SK
1027
1028 case EVENT_GROUP_ERR:
c72daea8 1029 die(_("failed to change group-id to %s: %s"), msg, EC_MISC);
1a6bca81
SK
1030
1031 case EVENT_PIDFILE:
c72daea8 1032 die(_("failed to open pidfile %s: %s"), msg, EC_FILE);
1a6bca81
SK
1033
1034 case EVENT_LOG_ERR:
c72daea8
SK
1035 die(_("cannot open log %s: %s"), msg, EC_FILE);
1036
1037 case EVENT_LUA_ERR:
1038 die(_("failed to load Lua script: %s"), msg, EC_MISC);
8b3ae2fd
SK
1039
1040 case EVENT_TFTP_ERR:
1041 die(_("TFTP directory %s inaccessible: %s"), msg, EC_FILE);
1a6bca81
SK
1042 }
1043}
1044
5aabfc78
SK
1045static void async_event(int pipe, time_t now)
1046{
1047 pid_t p;
1048 struct event_desc ev;
1049 int i;
c72daea8
SK
1050 char *msg;
1051
1052 /* NOTE: the memory used to return msg is leaked: use msgs in events only
1053 to describe fatal errors. */
1054
1055 if (read_event(pipe, &ev, &msg))
5aabfc78
SK
1056 switch (ev.event)
1057 {
1058 case EVENT_RELOAD:
1059 clear_cache_and_reload(now);
28866e95 1060 if (daemon->port != 0 && daemon->resolv_files && option_bool(OPT_NO_POLL))
5aabfc78
SK
1061 {
1062 reload_servers(daemon->resolv_files->name);
1063 check_servers();
1064 }
7622fc06 1065#ifdef HAVE_DHCP
5aabfc78 1066 rerun_scripts();
7622fc06 1067#endif
5aabfc78
SK
1068 break;
1069
1070 case EVENT_DUMP:
824af85b
SK
1071 if (daemon->port != 0)
1072 dump_cache(now);
5aabfc78
SK
1073 break;
1074
1075 case EVENT_ALARM:
7622fc06 1076#ifdef HAVE_DHCP
1f776932 1077 if (daemon->dhcp || daemon->doing_dhcp6)
5aabfc78
SK
1078 {
1079 lease_prune(NULL, now);
1080 lease_update_file(now);
1081 }
843c96b4 1082#ifdef HAVE_DHCP6
1f776932 1083 else if (daemon->doing_ra)
353ae4d2
SK
1084 /* Not doing DHCP, so no lease system, manage alarms for ra only */
1085 send_alarm(periodic_ra(now), now);
843c96b4 1086#endif
7622fc06 1087#endif
5aabfc78
SK
1088 break;
1089
1090 case EVENT_CHILD:
1091 /* See Stevens 5.10 */
1092 while ((p = waitpid(-1, NULL, WNOHANG)) != 0)
1093 if (p == -1)
1094 {
1095 if (errno != EINTR)
1096 break;
1097 }
1098 else
1099 for (i = 0 ; i < MAX_PROCS; i++)
1100 if (daemon->tcp_pids[i] == p)
1101 daemon->tcp_pids[i] = 0;
1102 break;
1103
1104 case EVENT_KILLED:
c72daea8 1105 my_syslog(LOG_WARNING, _("script process killed by signal %d"), ev.data);
5aabfc78
SK
1106 break;
1107
1108 case EVENT_EXITED:
c72daea8 1109 my_syslog(LOG_WARNING, _("script process exited with status %d"), ev.data);
5aabfc78
SK
1110 break;
1111
1112 case EVENT_EXEC_ERR:
9e038946
SK
1113 my_syslog(LOG_ERR, _("failed to execute %s: %s"),
1114 daemon->lease_change_command, strerror(ev.data));
5aabfc78
SK
1115 break;
1116
1a6bca81 1117 /* necessary for fatal errors in helper */
c72daea8 1118 case EVENT_USER_ERR:
1a6bca81 1119 case EVENT_DIE:
c72daea8
SK
1120 case EVENT_LUA_ERR:
1121 fatal_event(&ev, msg);
9e038946
SK
1122 break;
1123
5aabfc78
SK
1124 case EVENT_REOPEN:
1125 /* Note: this may leave TCP-handling processes with the old file still open.
1126 Since any such process will die in CHILD_LIFETIME or probably much sooner,
1127 we leave them logging to the old file. */
1128 if (daemon->log_file != NULL)
1129 log_reopen(daemon->log_file);
1130 break;
1131
1132 case EVENT_TERM:
1133 /* Knock all our children on the head. */
1134 for (i = 0; i < MAX_PROCS; i++)
1135 if (daemon->tcp_pids[i] != 0)
1136 kill(daemon->tcp_pids[i], SIGALRM);
1137
c72daea8 1138#if defined(HAVE_SCRIPT)
5aabfc78
SK
1139 /* handle pending lease transitions */
1140 if (daemon->helperfd != -1)
1141 {
1142 /* block in writes until all done */
1143 if ((i = fcntl(daemon->helperfd, F_GETFL)) != -1)
1144 fcntl(daemon->helperfd, F_SETFL, i & ~O_NONBLOCK);
1145 do {
1146 helper_write();
1147 } while (!helper_buf_empty() || do_script_run(now));
1148 close(daemon->helperfd);
1149 }
1150#endif
1151
1152 if (daemon->lease_stream)
1153 fclose(daemon->lease_stream);
73a08a24
SK
1154
1155 if (daemon->runfile)
1156 unlink(daemon->runfile);
5aabfc78
SK
1157
1158 my_syslog(LOG_INFO, _("exiting on receipt of SIGTERM"));
1159 flush_log();
1160 exit(EC_GOOD);
1161 }
3be34541
SK
1162}
1163
8ef5ada2 1164void poll_resolv(int force, int do_reload, time_t now)
5aabfc78
SK
1165{
1166 struct resolvc *res, *latest;
1167 struct stat statbuf;
1168 time_t last_change = 0;
1169 /* There may be more than one possible file.
1170 Go through and find the one which changed _last_.
1171 Warn of any which can't be read. */
8ef5ada2 1172
28866e95 1173 if (daemon->port == 0 || option_bool(OPT_NO_POLL))
8ef5ada2
SK
1174 return;
1175
5aabfc78
SK
1176 for (latest = NULL, res = daemon->resolv_files; res; res = res->next)
1177 if (stat(res->name, &statbuf) == -1)
1178 {
8ef5ada2
SK
1179 if (force)
1180 {
1181 res->mtime = 0;
1182 continue;
1183 }
1184
5aabfc78
SK
1185 if (!res->logged)
1186 my_syslog(LOG_WARNING, _("failed to access %s: %s"), res->name, strerror(errno));
1187 res->logged = 1;
8ef5ada2
SK
1188
1189 if (res->mtime != 0)
1190 {
1191 /* existing file evaporated, force selection of the latest
1192 file even if its mtime hasn't changed since we last looked */
1193 poll_resolv(1, do_reload, now);
1194 return;
1195 }
5aabfc78
SK
1196 }
1197 else
1198 {
1199 res->logged = 0;
8ef5ada2
SK
1200 if (force || (statbuf.st_mtime != res->mtime))
1201 {
1202 res->mtime = statbuf.st_mtime;
5aabfc78
SK
1203 if (difftime(statbuf.st_mtime, last_change) > 0.0)
1204 {
1205 last_change = statbuf.st_mtime;
1206 latest = res;
1207 }
1208 }
1209 }
1210
1211 if (latest)
1212 {
1213 static int warned = 0;
1214 if (reload_servers(latest->name))
1215 {
1216 my_syslog(LOG_INFO, _("reading %s"), latest->name);
1217 warned = 0;
1218 check_servers();
28866e95 1219 if (option_bool(OPT_RELOAD) && do_reload)
8ef5ada2 1220 clear_cache_and_reload(now);
5aabfc78
SK
1221 }
1222 else
1223 {
1224 latest->mtime = 0;
1225 if (!warned)
1226 {
1227 my_syslog(LOG_WARNING, _("no servers found in %s, will retry"), latest->name);
1228 warned = 1;
1229 }
1230 }
1231 }
1232}
3d8df260 1233
5aabfc78 1234void clear_cache_and_reload(time_t now)
3d8df260 1235{
408c368f
VG
1236 (void)now;
1237
824af85b 1238 if (daemon->port != 0)
7622fc06 1239 cache_reload();
824af85b 1240
7622fc06 1241#ifdef HAVE_DHCP
1f776932 1242 if (daemon->dhcp || daemon->doing_dhcp6)
3d8df260 1243 {
28866e95 1244 if (option_bool(OPT_ETHERS))
5aabfc78 1245 dhcp_read_ethers();
824af85b 1246 reread_dhcp();
3d8df260 1247 dhcp_update_configs(daemon->dhcp_conf);
5aabfc78
SK
1248 lease_update_from_configs();
1249 lease_update_file(now);
353ae4d2 1250 lease_update_dns(1);
3d8df260 1251 }
843c96b4 1252#ifdef HAVE_DHCP6
1f776932 1253 else if (daemon->doing_ra)
2021c662
SK
1254 /* Not doing DHCP, so no lease system, manage
1255 alarms for ra only */
1256 send_alarm(periodic_ra(now), now);
843c96b4 1257#endif
7622fc06 1258#endif
3d8df260
SK
1259}
1260
5aabfc78 1261static int set_dns_listeners(time_t now, fd_set *set, int *maxfdp)
3be34541
SK
1262{
1263 struct serverfd *serverfdp;
1264 struct listener *listener;
824af85b 1265 int wait = 0, i;
832af0ba
SK
1266
1267#ifdef HAVE_TFTP
1268 int tftp = 0;
1269 struct tftp_transfer *transfer;
1270 for (transfer = daemon->tftp_trans; transfer; transfer = transfer->next)
1271 {
1272 tftp++;
1273 FD_SET(transfer->sockfd, set);
1274 bump_maxfd(transfer->sockfd, maxfdp);
1275 }
1276#endif
1277
1697269c 1278 /* will we be able to get memory? */
824af85b
SK
1279 if (daemon->port != 0)
1280 get_new_frec(now, &wait);
1697269c 1281
3be34541
SK
1282 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1283 {
1284 FD_SET(serverfdp->fd, set);
1697269c 1285 bump_maxfd(serverfdp->fd, maxfdp);
3be34541 1286 }
1a6bca81
SK
1287
1288 if (daemon->port != 0 && !daemon->osport)
1289 for (i = 0; i < RANDOM_SOCKS; i++)
1290 if (daemon->randomsocks[i].refcount != 0)
1291 {
1292 FD_SET(daemon->randomsocks[i].fd, set);
1293 bump_maxfd(daemon->randomsocks[i].fd, maxfdp);
1294 }
1295
3be34541
SK
1296 for (listener = daemon->listeners; listener; listener = listener->next)
1297 {
1697269c 1298 /* only listen for queries if we have resources */
824af85b 1299 if (listener->fd != -1 && wait == 0)
1697269c
SK
1300 {
1301 FD_SET(listener->fd, set);
1302 bump_maxfd(listener->fd, maxfdp);
1303 }
1304
1305 /* death of a child goes through the select loop, so
1306 we don't need to explicitly arrange to wake up here */
824af85b
SK
1307 if (listener->tcpfd != -1)
1308 for (i = 0; i < MAX_PROCS; i++)
1309 if (daemon->tcp_pids[i] == 0)
1310 {
1311 FD_SET(listener->tcpfd, set);
1312 bump_maxfd(listener->tcpfd, maxfdp);
1313 break;
1314 }
9e4abcb5 1315
832af0ba
SK
1316#ifdef HAVE_TFTP
1317 if (tftp <= daemon->tftp_max && listener->tftpfd != -1)
1318 {
1319 FD_SET(listener->tftpfd, set);
1320 bump_maxfd(listener->tftpfd, maxfdp);
1321 }
1322#endif
1323
1324 }
1325
1697269c 1326 return wait;
3be34541 1327}
9e4abcb5 1328
5aabfc78 1329static void check_dns_listeners(fd_set *set, time_t now)
3be34541
SK
1330{
1331 struct serverfd *serverfdp;
1a6bca81
SK
1332 struct listener *listener;
1333 int i;
1334
832af0ba
SK
1335 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1336 if (FD_ISSET(serverfdp->fd, set))
1a6bca81
SK
1337 reply_query(serverfdp->fd, serverfdp->source_addr.sa.sa_family, now);
1338
1339 if (daemon->port != 0 && !daemon->osport)
1340 for (i = 0; i < RANDOM_SOCKS; i++)
1341 if (daemon->randomsocks[i].refcount != 0 &&
1342 FD_ISSET(daemon->randomsocks[i].fd, set))
1343 reply_query(daemon->randomsocks[i].fd, daemon->randomsocks[i].family, now);
832af0ba
SK
1344
1345 for (listener = daemon->listeners; listener; listener = listener->next)
1346 {
824af85b 1347 if (listener->fd != -1 && FD_ISSET(listener->fd, set))
5aabfc78 1348 receive_query(listener, now);
1a6bca81 1349
832af0ba
SK
1350#ifdef HAVE_TFTP
1351 if (listener->tftpfd != -1 && FD_ISSET(listener->tftpfd, set))
5aabfc78 1352 tftp_request(listener, now);
832af0ba 1353#endif
3be34541 1354
824af85b 1355 if (listener->tcpfd != -1 && FD_ISSET(listener->tcpfd, set))
832af0ba 1356 {
22ce550e 1357 int confd, client_ok = 1;
832af0ba
SK
1358 struct irec *iface = NULL;
1359 pid_t p;
52d4abf2
SK
1360 union mysockaddr tcp_addr;
1361 socklen_t tcp_len = sizeof(union mysockaddr);
1362
1363 while ((confd = accept(listener->tcpfd, NULL, NULL)) == -1 && errno == EINTR);
832af0ba 1364
46b06656 1365 if (confd == -1)
832af0ba 1366 continue;
76dd75de 1367
46b06656
SK
1368 if (getsockname(confd, (struct sockaddr *)&tcp_addr, &tcp_len) == -1)
1369 {
1370 close(confd);
1371 continue;
1372 }
76dd75de
SK
1373
1374 /* Make sure that the interface list is up-to-date.
1375
1376 We do this here as we may need the results below, and
1377 the DNS code needs them for --interface-name stuff.
1378
1379 Multiple calls to enumerate_interfaces() per select loop are
1380 inhibited, so calls to it in the child process (which doesn't select())
1381 have no effect. This avoids two processes reading from the same
1382 netlink fd and screwing the pooch entirely.
1383 */
e25db1f2 1384
76dd75de
SK
1385 enumerate_interfaces(0);
1386
1387 if (option_bool(OPT_NOWILD))
1388 iface = listener->iface; /* May be NULL */
1389 else
1390 {
1391 int if_index;
1392 char intr_name[IF_NAMESIZE];
1393
1394 /* if we can find the arrival interface, check it's one that's allowed */
1395 if ((if_index = tcp_interface(confd, tcp_addr.sa.sa_family)) != 0 &&
1396 indextoname(listener->tcpfd, if_index, intr_name))
1397 {
1398 struct all_addr addr;
1399 addr.addr.addr4 = tcp_addr.in.sin_addr;
e25db1f2 1400#ifdef HAVE_IPV6
76dd75de
SK
1401 if (tcp_addr.sa.sa_family == AF_INET6)
1402 addr.addr.addr6 = tcp_addr.in6.sin6_addr;
e25db1f2 1403#endif
76dd75de
SK
1404
1405 for (iface = daemon->interfaces; iface; iface = iface->next)
1406 if (iface->index == if_index)
1407 break;
1408
1409 if (!iface && !loopback_exception(listener->tcpfd, tcp_addr.sa.sa_family, &addr, intr_name))
1410 client_ok = 0;
1411 }
1412
1413 if (option_bool(OPT_CLEVERBIND))
1414 iface = listener->iface; /* May be NULL */
1415 else
1416 {
1417 /* Check for allowed interfaces when binding the wildcard address:
1418 we do this by looking for an interface with the same address as
1419 the local address of the TCP connection, then looking to see if that's
1420 an allowed interface. As a side effect, we get the netmask of the
1421 interface too, for localisation. */
1422
1423 for (iface = daemon->interfaces; iface; iface = iface->next)
1424 if (sockaddr_isequal(&iface->addr, &tcp_addr))
1425 break;
1426
1427 if (!iface)
1428 client_ok = 0;
1429 }
1430 }
1431
22ce550e 1432 if (!client_ok)
832af0ba
SK
1433 {
1434 shutdown(confd, SHUT_RDWR);
1435 close(confd);
1436 }
59353a6b 1437#ifndef NO_FORK
28866e95 1438 else if (!option_bool(OPT_DEBUG) && (p = fork()) != 0)
832af0ba
SK
1439 {
1440 if (p != -1)
1441 {
1442 int i;
1443 for (i = 0; i < MAX_PROCS; i++)
1444 if (daemon->tcp_pids[i] == 0)
1445 {
1446 daemon->tcp_pids[i] = p;
1447 break;
1448 }
1449 }
1450 close(confd);
1451 }
1452#endif
1453 else
1454 {
1455 unsigned char *buff;
1456 struct server *s;
1457 int flags;
52d4abf2 1458 struct in_addr netmask;
4f7b304f 1459 int auth_dns;
52d4abf2
SK
1460
1461 if (iface)
4f7b304f
SK
1462 {
1463 netmask = iface->netmask;
1464 auth_dns = iface->dns_auth;
1465 }
52d4abf2 1466 else
4f7b304f
SK
1467 {
1468 netmask.s_addr = 0;
1469 auth_dns = 0;
1470 }
52d4abf2 1471
8ef5ada2
SK
1472#ifndef NO_FORK
1473 /* Arrange for SIGALARM after CHILD_LIFETIME seconds to
1474 terminate the process. */
28866e95 1475 if (!option_bool(OPT_DEBUG))
832af0ba 1476 alarm(CHILD_LIFETIME);
8ef5ada2
SK
1477#endif
1478
832af0ba
SK
1479 /* start with no upstream connections. */
1480 for (s = daemon->servers; s; s = s->next)
7cebd20f 1481 s->tcpfd = -1;
832af0ba
SK
1482
1483 /* The connected socket inherits non-blocking
1484 attribute from the listening socket.
1485 Reset that here. */
1486 if ((flags = fcntl(confd, F_GETFL, 0)) != -1)
1487 fcntl(confd, F_SETFL, flags & ~O_NONBLOCK);
1488
4f7b304f 1489 buff = tcp_request(confd, now, &tcp_addr, netmask, auth_dns);
7cebd20f 1490
832af0ba
SK
1491 shutdown(confd, SHUT_RDWR);
1492 close(confd);
1493
1494 if (buff)
1495 free(buff);
1496
1497 for (s = daemon->servers; s; s = s->next)
1498 if (s->tcpfd != -1)
1499 {
1500 shutdown(s->tcpfd, SHUT_RDWR);
1501 close(s->tcpfd);
1502 }
7cebd20f 1503#ifndef NO_FORK
28866e95 1504 if (!option_bool(OPT_DEBUG))
5aabfc78
SK
1505 {
1506 flush_log();
1507 _exit(0);
1508 }
59353a6b 1509#endif
832af0ba
SK
1510 }
1511 }
1512 }
3be34541
SK
1513}
1514
7622fc06 1515#ifdef HAVE_DHCP
5e9e0efb
SK
1516int make_icmp_sock(void)
1517{
7cebd20f 1518 int fd;
5e9e0efb
SK
1519 int zeroopt = 0;
1520
1521 if ((fd = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
1522 {
7cebd20f 1523 if (!fix_fd(fd) ||
5e9e0efb
SK
1524 setsockopt(fd, SOL_SOCKET, SO_DONTROUTE, &zeroopt, sizeof(zeroopt)) == -1)
1525 {
1526 close(fd);
1527 fd = -1;
1528 }
1529 }
1530
1531 return fd;
1532}
1533
5aabfc78 1534int icmp_ping(struct in_addr addr)
3be34541 1535{
5e9e0efb 1536 /* Try and get an ICMP echo from a machine. */
3be34541
SK
1537
1538 /* Note that whilst in the three second wait, we check for
832af0ba 1539 (and service) events on the DNS and TFTP sockets, (so doing that
3be34541
SK
1540 better not use any resources our caller has in use...)
1541 but we remain deaf to signals or further DHCP packets. */
1542
5e9e0efb 1543 int fd;
3be34541
SK
1544 struct sockaddr_in saddr;
1545 struct {
1546 struct ip ip;
1547 struct icmp icmp;
1548 } packet;
1549 unsigned short id = rand16();
1550 unsigned int i, j;
5e9e0efb 1551 int gotreply = 0;
3be34541 1552 time_t start, now;
5e9e0efb 1553
824af85b 1554#if defined(HAVE_LINUX_NETWORK) || defined (HAVE_SOLARIS_NETWORK)
5e9e0efb
SK
1555 if ((fd = make_icmp_sock()) == -1)
1556 return 0;
1557#else
1558 int opt = 2000;
1559 fd = daemon->dhcp_icmp_fd;
1560 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1561#endif
1562
3be34541
SK
1563 saddr.sin_family = AF_INET;
1564 saddr.sin_port = 0;
1565 saddr.sin_addr = addr;
1566#ifdef HAVE_SOCKADDR_SA_LEN
1567 saddr.sin_len = sizeof(struct sockaddr_in);
1568#endif
1569
1570 memset(&packet.icmp, 0, sizeof(packet.icmp));
1571 packet.icmp.icmp_type = ICMP_ECHO;
1572 packet.icmp.icmp_id = id;
1573 for (j = 0, i = 0; i < sizeof(struct icmp) / 2; i++)
1574 j += ((u16 *)&packet.icmp)[i];
1575 while (j>>16)
1576 j = (j & 0xffff) + (j >> 16);
1577 packet.icmp.icmp_cksum = (j == 0xffff) ? j : ~j;
1578
5e9e0efb 1579 while (sendto(fd, (char *)&packet.icmp, sizeof(struct icmp), 0,
fd9fa481
SK
1580 (struct sockaddr *)&saddr, sizeof(saddr)) == -1 &&
1581 retry_send());
1582
5e9e0efb
SK
1583 for (now = start = dnsmasq_time();
1584 difftime(now, start) < (float)PING_WAIT;)
fd9fa481
SK
1585 {
1586 struct timeval tv;
f2621c7f 1587 fd_set rset, wset;
fd9fa481 1588 struct sockaddr_in faddr;
1697269c 1589 int maxfd = fd;
3d8df260 1590 socklen_t len = sizeof(faddr);
fd9fa481
SK
1591
1592 tv.tv_usec = 250000;
1593 tv.tv_sec = 0;
1594
1595 FD_ZERO(&rset);
f2621c7f 1596 FD_ZERO(&wset);
5e9e0efb 1597 FD_SET(fd, &rset);
5aabfc78 1598 set_dns_listeners(now, &rset, &maxfd);
f2621c7f 1599 set_log_writer(&wset, &maxfd);
c5ad4e79
SK
1600
1601#ifdef HAVE_DHCP6
1f776932 1602 if (daemon->doing_ra)
c5ad4e79
SK
1603 {
1604 FD_SET(daemon->icmp6fd, &rset);
1605 bump_maxfd(daemon->icmp6fd, &maxfd);
1606 }
1607#endif
1608
f2621c7f
SK
1609 if (select(maxfd+1, &rset, &wset, NULL, &tv) < 0)
1610 {
1611 FD_ZERO(&rset);
1612 FD_ZERO(&wset);
1613 }
1614
5e9e0efb 1615 now = dnsmasq_time();
f2621c7f
SK
1616
1617 check_log_writer(&wset);
5aabfc78 1618 check_dns_listeners(&rset, now);
832af0ba 1619
c5ad4e79 1620#ifdef HAVE_DHCP6
1f776932
SK
1621 if (daemon->doing_ra && FD_ISSET(daemon->icmp6fd, &rset))
1622 icmp6_packet(now);
c5ad4e79
SK
1623#endif
1624
832af0ba 1625#ifdef HAVE_TFTP
5aabfc78 1626 check_tftp_listeners(&rset, now);
832af0ba
SK
1627#endif
1628
5e9e0efb
SK
1629 if (FD_ISSET(fd, &rset) &&
1630 recvfrom(fd, &packet, sizeof(packet), 0,
fd9fa481
SK
1631 (struct sockaddr *)&faddr, &len) == sizeof(packet) &&
1632 saddr.sin_addr.s_addr == faddr.sin_addr.s_addr &&
1633 packet.icmp.icmp_type == ICMP_ECHOREPLY &&
1634 packet.icmp.icmp_seq == 0 &&
1635 packet.icmp.icmp_id == id)
1636 {
1637 gotreply = 1;
1638 break;
1639 }
1640 }
1641
824af85b 1642#if defined(HAVE_LINUX_NETWORK) || defined(HAVE_SOLARIS_NETWORK)
5e9e0efb
SK
1643 close(fd);
1644#else
3be34541 1645 opt = 1;
5e9e0efb
SK
1646 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1647#endif
1648
3be34541
SK
1649 return gotreply;
1650}
7622fc06 1651#endif
0a852541
SK
1652
1653