Debian Codegraph @

src/dnsmasq.c

raw
1 /* dnsmasq is Copyright (c) 2000-2026 Simon Kelley
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
5 the Free Software Foundation; version 2 dated June, 1991, or
6 (at your option) version 3 dated 29 June, 2007.
7
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.
12
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/>.
15 */
16
17 /* Declare static char *compiler_opts in config.h */
18 #define DNSMASQ_COMPILE_OPTS
19
20 /* dnsmasq.h has to be included first as it sources config.h */
21 #include "dnsmasq.h"
22
23 #if defined(HAVE_IDN) || defined(HAVE_LIBIDN2) || defined(LOCALEDIR)
24 #include <locale.h>
25 #endif
26
27 struct daemon *daemon;
28
29 static volatile pid_t pid = 0;
30 static volatile int pipewrite;
31
32 static void set_dns_listeners(void);
33 #ifdef HAVE_TFTP
34 static void set_tftp_listeners(void);
35 #endif
36 static void check_dns_listeners(time_t now);
37 static void do_tcp_connection(struct listener *listener, time_t now, int slot);
38 static void sig_handler(int sig);
39 static void async_event(int pipe, time_t now);
40 static void fatal_event(struct event_desc *ev, char *msg);
41 static int read_event(int fd, struct event_desc *evp, char **msg);
42 static void poll_resolv(int force, int do_reload, time_t now);
43
44 int main (int argc, char **argv)
45 {
46 time_t now;
47 struct sigaction sigact;
48 struct iname *if_tmp;
49 int piperead, pipefd[2], err_pipe[2];
50 struct passwd *ent_pw = NULL;
51 #if defined(HAVE_SCRIPT)
52 uid_t script_uid = 0;
53 gid_t script_gid = 0;
54 #endif
55 struct group *gp = NULL;
56 long i, max_fd = sysconf(_SC_OPEN_MAX);
57 char *baduser = NULL;
58 int log_err;
59 int chown_warn = 0;
60 #if defined(HAVE_LINUX_NETWORK)
61 cap_user_header_t hdr = NULL;
62 cap_user_data_t data = NULL;
63 int need_cap_net_admin = 0;
64 int need_cap_net_raw = 0;
65 int need_cap_net_bind_service = 0;
66 int have_cap_chown = 0;
67 # ifdef HAVE_DHCP
68 char *bound_device = NULL;
69 int did_bind = 0;
70 # endif
71 struct server *serv;
72 char *netlink_warn;
73 #else
74 int bind_fallback = 0;
75 #endif
76 #if defined(HAVE_DHCP)
77 struct dhcp_context *context;
78 struct dhcp_relay *relay;
79 #endif
80 #ifdef HAVE_TFTP
81 int tftp_prefix_missing = 0;
82 #endif
83
84 #ifdef HAVE_LINUX_NETWORK
85 (void)netlink_warn;
86 #endif
87
88 #if defined(HAVE_IDN) || defined(HAVE_LIBIDN2) || defined(LOCALEDIR)
89 setlocale(LC_ALL, "");
90 #endif
91 #ifdef LOCALEDIR
92 bindtextdomain("dnsmasq", LOCALEDIR);
93 textdomain("dnsmasq");
94 #endif
95
96 sigact.sa_handler = sig_handler;
97 sigact.sa_flags = 0;
98 sigemptyset(&sigact.sa_mask);
99 sigaction(SIGUSR1, &sigact, NULL);
100 sigaction(SIGUSR2, &sigact, NULL);
101 sigaction(SIGHUP, &sigact, NULL);
102 sigaction(SIGTERM, &sigact, NULL);
103 sigaction(SIGALRM, &sigact, NULL);
104 sigaction(SIGCHLD, &sigact, NULL);
105 sigaction(SIGINT, &sigact, NULL);
106
107 /* ignore SIGPIPE */
108 sigact.sa_handler = SIG_IGN;
109 sigaction(SIGPIPE, &sigact, NULL);
110
111 umask(022); /* known umask, create leases and pid files as 0644 */
112
113 rand_init(); /* Must precede read_opts() */
114
115 read_opts(argc, argv, compile_opts);
116
117 #ifdef HAVE_LINUX_NETWORK
118 daemon->kernel_version = kernel_version();
119 #endif
120
121 if (daemon->edns_pktsz < PACKETSZ)
122 daemon->edns_pktsz = PACKETSZ;
123
124 /* Min buffer size: we check after adding each record, so there must be
125 memory for the largest packet, and the largest record so the
126 min for DNS is PACKETSZ+MAXDNAME+RRFIXEDSZ which is < 1000.
127 This might be increased is EDNS packet size if greater than the minimum. */
128 daemon->packet_buff_sz = daemon->edns_pktsz + MAXDNAME + RRFIXEDSZ;
129 daemon->packet = safe_malloc(daemon->packet_buff_sz);
130 daemon->pipe_to_parent = -1;
131
132 if (option_bool(OPT_EXTRALOG))
133 daemon->addrbuff2 = safe_malloc(ADDRSTRLEN);
134
135 #ifdef HAVE_DNSSEC
136 if (option_bool(OPT_DNSSEC_VALID))
137 {
138 daemon->keyname = safe_malloc(MAXDNAMESTR + 1);
139 daemon->cname = safe_malloc(MAXDNAMESTR + 1);
140 /* one char flag per possible RR in answer section (may get extended). */
141 daemon->rr_status_sz = 64;
142 daemon->rr_status = safe_malloc(sizeof(*daemon->rr_status) * daemon->rr_status_sz);
143 }
144 #endif
145
146 #ifdef HAVE_DHCP
147 if (!daemon->lease_file)
148 {
149 if (daemon->dhcp || daemon->dhcp6)
150 daemon->lease_file = LEASEFILE;
151 }
152 #endif
153
154 /* Ensure that at least stdin, stdout and stderr (fd 0, 1, 2) exist,
155 otherwise file descriptors we create can end up being 0, 1, or 2
156 and then get accidentally closed later when we make 0, 1, and 2
157 open to /dev/null. Normally we'll be started with 0, 1 and 2 open,
158 but it's not guaranteed. By opening /dev/null three times, we
159 ensure that we're not using those fds for real stuff. */
160 for (i = 0; i < 3; i++)
161 open("/dev/null", O_RDWR);
162
163 /* Close any file descriptors we inherited apart from std{in|out|err} */
164 close_fds(max_fd, -1, -1, -1);
165
166 #ifndef HAVE_LINUX_NETWORK
167 # if !(defined(IP_RECVDSTADDR) && defined(IP_RECVIF) && defined(IP_SENDSRCADDR))
168 if (!option_bool(OPT_NOWILD))
169 {
170 bind_fallback = 1;
171 set_option_bool(OPT_NOWILD);
172 }
173 # endif
174
175 /* -- bind-dynamic not supported on !Linux, fall back to --bind-interfaces */
176 if (option_bool(OPT_CLEVERBIND))
177 {
178 bind_fallback = 1;
179 set_option_bool(OPT_NOWILD);
180 reset_option_bool(OPT_CLEVERBIND);
181 }
182 #endif
183
184 #ifndef HAVE_INOTIFY
185 if (daemon->dynamic_dirs)
186 die(_("dhcp-hostsdir, dhcp-optsdir and hostsdir are not supported on this platform"), NULL, EC_BADCONF);
187 #endif
188
189 if (option_bool(OPT_DNSSEC_VALID))
190 {
191 #ifdef HAVE_DNSSEC
192 struct ds_config *ds;
193
194 /* Must have at least a root trust anchor, or the DNSSEC code
195 can loop forever. */
196 for (ds = daemon->ds; ds; ds = ds->next)
197 if (ds->name && ds->name[0] == 0)
198 break;
199
200 if (!ds)
201 die(_("no root trust anchor provided for DNSSEC"), NULL, EC_BADCONF);
202
203 if (daemon->cachesize < CACHESIZ)
204 die(_("cannot reduce cache size from default when DNSSEC enabled"), NULL, EC_BADCONF);
205 #else
206 die(_("DNSSEC not available: set HAVE_DNSSEC in src/config.h"), NULL, EC_BADCONF);
207 #endif
208 }
209
210 #ifndef HAVE_TFTP
211 if (option_bool(OPT_TFTP))
212 die(_("TFTP server not available: set HAVE_TFTP in src/config.h"), NULL, EC_BADCONF);
213 #endif
214
215 #ifdef HAVE_CONNTRACK
216 if (option_bool(OPT_CONNTRACK))
217 {
218 if (daemon->query_port != 0 || daemon->osport)
219 die (_("cannot use --conntrack AND --query-port"), NULL, EC_BADCONF);
220
221 need_cap_net_admin = 1;
222 }
223 #else
224 if (option_bool(OPT_CONNTRACK))
225 die(_("conntrack support not available: set HAVE_CONNTRACK in src/config.h"), NULL, EC_BADCONF);
226 #endif
227
228 #ifdef HAVE_SOLARIS_NETWORK
229 if (daemon->max_logs != 0)
230 die(_("asynchronous logging is not available under Solaris"), NULL, EC_BADCONF);
231 #endif
232
233 #ifdef __ANDROID__
234 if (daemon->max_logs != 0)
235 die(_("asynchronous logging is not available under Android"), NULL, EC_BADCONF);
236 #endif
237
238 #ifndef HAVE_AUTH
239 if (daemon->auth_zones)
240 die(_("authoritative DNS not available: set HAVE_AUTH in src/config.h"), NULL, EC_BADCONF);
241 #endif
242
243 #ifndef HAVE_LOOP
244 if (option_bool(OPT_LOOP_DETECT))
245 die(_("loop detection not available: set HAVE_LOOP in src/config.h"), NULL, EC_BADCONF);
246 #endif
247
248 #ifndef HAVE_UBUS
249 if (option_bool(OPT_UBUS))
250 die(_("Ubus not available: set HAVE_UBUS in src/config.h"), NULL, EC_BADCONF);
251 #endif
252
253 /* Handle only one of min_port/max_port being set. */
254 if (daemon->min_port != 0 && daemon->max_port == 0)
255 daemon->max_port = MAX_PORT;
256
257 if (daemon->max_port != 0 && daemon->min_port == 0)
258 daemon->min_port = MIN_PORT;
259
260 if (daemon->max_port < daemon->min_port)
261 die(_("max_port cannot be smaller than min_port"), NULL, EC_BADCONF);
262
263 if (daemon->max_port != 0 &&
264 daemon->max_port - daemon->min_port + 1 < daemon->randport_limit)
265 die(_("port_limit must not be larger than available port range"), NULL, EC_BADCONF);
266
267 now = dnsmasq_time();
268
269 if (daemon->auth_zones)
270 {
271 if (!daemon->authserver)
272 die(_("--auth-server required when an auth zone is defined."), NULL, EC_BADCONF);
273
274 /* Create a serial at startup if not configured. */
275 #ifdef HAVE_BROKEN_RTC
276 if (daemon->soa_sn == 0)
277 die(_("zone serial must be configured in --auth-soa"), NULL, EC_BADCONF);
278 #else
279 if (daemon->soa_sn == 0)
280 daemon->soa_sn = now;
281 #endif
282 }
283
284 #ifdef HAVE_DHCP6
285 if (daemon->dhcp6)
286 {
287 daemon->doing_ra = option_bool(OPT_RA);
288
289 for (context = daemon->dhcp6; context; context = context->next)
290 {
291 if (context->flags & CONTEXT_DHCP)
292 daemon->doing_dhcp6 = 1;
293 if (context->flags & CONTEXT_RA)
294 daemon->doing_ra = 1;
295 #if !defined(HAVE_LINUX_NETWORK) && !defined(HAVE_BSD_NETWORK)
296 if (context->flags & CONTEXT_TEMPLATE)
297 die (_("dhcp-range constructor not available on this platform"), NULL, EC_BADCONF);
298 #endif
299 }
300 }
301 #endif
302
303 #ifdef HAVE_DHCP
304 /* Note that order matters here, we must call lease_init before
305 creating any file descriptors which shouldn't be leaked
306 to the lease-script init process. We need to call common_init
307 before lease_init to allocate buffers it uses.
308 The script subsystem relies on DHCP buffers, hence the last two
309 conditions below. */
310 if (daemon->dhcp || daemon->doing_dhcp6 || daemon->relay4 ||
311 daemon->relay6 || option_bool(OPT_TFTP) || option_bool(OPT_SCRIPT_ARP))
312 {
313 dhcp_common_init();
314 if (daemon->dhcp || daemon->doing_dhcp6)
315 lease_init(now);
316 }
317
318 if (daemon->dhcp || daemon->relay4)
319 {
320 dhcp_init();
321 # ifdef HAVE_LINUX_NETWORK
322 /* Need NET_RAW to send ping. */
323 if (!option_bool(OPT_NO_PING))
324 need_cap_net_raw = 1;
325 /* Need NET_ADMIN to change ARP cache if not always broadcasting. */
326 if (daemon->force_broadcast == NULL || daemon->force_broadcast->list != NULL)
327 need_cap_net_admin = 1;
328 # endif
329 }
330
331 # ifdef HAVE_DHCP6
332 if (daemon->doing_ra || daemon->doing_dhcp6 || daemon->relay6)
333 {
334 ra_init(now);
335 # ifdef HAVE_LINUX_NETWORK
336 need_cap_net_raw = 1;
337 need_cap_net_admin = 1;
338 # endif
339 }
340
341 if (daemon->doing_dhcp6 || daemon->relay6)
342 dhcp6_init();
343 # endif
344
345 #endif
346
347 #ifdef HAVE_IPSET
348 if (daemon->ipsets)
349 {
350 ipset_init();
351 # ifdef HAVE_LINUX_NETWORK
352 need_cap_net_admin = 1;
353 # endif
354 }
355 #endif
356
357 #ifdef HAVE_NFTSET
358 if (daemon->nftsets)
359 {
360 nftset_init();
361 # ifdef HAVE_LINUX_NETWORK
362 need_cap_net_admin = 1;
363 # endif
364 }
365 #endif
366
367 #if defined(HAVE_LINUX_NETWORK)
368 netlink_warn = netlink_init();
369 #elif defined(HAVE_BSD_NETWORK)
370 route_init();
371 #endif
372
373 if (option_bool(OPT_NOWILD) && option_bool(OPT_CLEVERBIND))
374 die(_("cannot set --bind-interfaces and --bind-dynamic"), NULL, EC_BADCONF);
375
376 if (!enumerate_interfaces(1) || !enumerate_interfaces(0))
377 die(_("failed to find list of interfaces: %s"), NULL, EC_MISC);
378
379 #ifdef HAVE_DHCP
380 /* Determine lease FQDNs after enumerate_interfaces() call, since it needs
381 to call get_domain and that's only valid for some domain configs once we
382 have interface addresses. */
383 lease_calc_fqdns();
384 #endif
385
386 if (option_bool(OPT_NOWILD) || option_bool(OPT_CLEVERBIND))
387 {
388 create_bound_listeners(1);
389
390 if (!option_bool(OPT_CLEVERBIND))
391 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
392 if (if_tmp->name && !(if_tmp->flags & INAME_USED))
393 die(_("unknown interface %s"), if_tmp->name, EC_BADNET);
394
395 #if defined(HAVE_LINUX_NETWORK) && defined(HAVE_DHCP)
396 /* after enumerate_interfaces() */
397 bound_device = whichdevice();
398
399 if ((did_bind = bind_dhcp_devices(bound_device)) & 2)
400 die(_("failed to set SO_BINDTODEVICE on DHCP socket: %s"), NULL, EC_BADNET);
401 #endif
402 }
403 else
404 create_wildcard_listeners();
405
406 #ifdef HAVE_DHCP6
407 /* after enumerate_interfaces() */
408 if (daemon->doing_dhcp6 || daemon->relay6 || daemon->doing_ra)
409 join_multicast(1);
410
411 /* After netlink_init() and before create_helper() */
412 lease_make_duid(now);
413 #endif
414
415 if (daemon->port != 0)
416 {
417 cache_init();
418 blockdata_init();
419
420 /* Scale random socket pool by ftabsize, but
421 limit it based on available fds. */
422 daemon->numrrand = daemon->ftabsize/2;
423 if (daemon->numrrand > max_fd/3)
424 daemon->numrrand = max_fd/3;
425 /* safe_malloc returns zero'd memory */
426 daemon->randomsocks = safe_malloc(daemon->numrrand * sizeof(struct randfd));
427
428 daemon->tcp_pids = safe_malloc(daemon->max_procs*sizeof(pid_t));
429 daemon->tcp_pipes = safe_malloc(daemon->max_procs*sizeof(int));
430
431 for (i = 0; i < daemon->max_procs; i++)
432 daemon->tcp_pipes[i] = -1;
433 }
434
435 if (daemon->dump_file)
436 #ifdef HAVE_DUMPFILE
437 dump_init();
438 else
439 daemon->dumpfd = -1;
440 #else
441 die(_("Packet dumps not available: set HAVE_DUMP in src/config.h"), NULL, EC_BADCONF);
442 #endif
443
444 if (option_bool(OPT_DBUS))
445 #ifdef HAVE_DBUS
446 {
447 char *err;
448 if ((err = dbus_init()))
449 die(_("DBus error: %s"), err, EC_MISC);
450 }
451 #else
452 die(_("DBus not available: set HAVE_DBUS in src/config.h"), NULL, EC_BADCONF);
453 #endif
454
455 if (option_bool(OPT_UBUS))
456 #ifdef HAVE_UBUS
457 {
458 char *err;
459 if ((err = ubus_init()))
460 die(_("UBus error: %s"), err, EC_MISC);
461 }
462 #else
463 die(_("UBus not available: set HAVE_UBUS in src/config.h"), NULL, EC_BADCONF);
464 #endif
465
466 if (daemon->port != 0)
467 pre_allocate_sfds();
468
469 #if defined(HAVE_SCRIPT)
470 /* Note getpwnam returns static storage */
471 if ((daemon->dhcp || daemon->dhcp6) &&
472 daemon->scriptuser &&
473 (daemon->lease_change_command || daemon->luascript))
474 {
475 struct passwd *scr_pw;
476
477 if ((scr_pw = getpwnam(daemon->scriptuser)))
478 {
479 script_uid = scr_pw->pw_uid;
480 script_gid = scr_pw->pw_gid;
481 }
482 else
483 baduser = daemon->scriptuser;
484 }
485 #endif
486
487 if (daemon->username && !(ent_pw = getpwnam(daemon->username)))
488 baduser = daemon->username;
489 else if (daemon->groupname && !(gp = getgrnam(daemon->groupname)))
490 baduser = daemon->groupname;
491
492 if (baduser)
493 die(_("unknown user or group: %s"), baduser, EC_BADCONF);
494
495 /* implement group defaults, "dip" if available, or group associated with uid */
496 if (!daemon->group_set && !gp)
497 {
498 if (!(gp = getgrnam(CHGRP)) && ent_pw)
499 gp = getgrgid(ent_pw->pw_gid);
500
501 /* for error message */
502 if (gp)
503 daemon->groupname = gp->gr_name;
504 }
505
506 #if defined(HAVE_LINUX_NETWORK)
507 /* We keep CAP_NETADMIN (for ARP-injection) and
508 CAP_NET_RAW (for icmp) if we're doing dhcp,
509 if we have yet to bind ports because of DAD,
510 or we're doing it dynamically, we need CAP_NET_BIND_SERVICE. */
511 if ((is_dad_listeners() || option_bool(OPT_CLEVERBIND)) &&
512 (option_bool(OPT_TFTP) || (daemon->port != 0 && daemon->port <= 1024)))
513 need_cap_net_bind_service = 1;
514
515 /* usptream servers which bind to an interface call SO_BINDTODEVICE
516 for each TCP connection, so need CAP_NET_RAW */
517 for (serv = daemon->servers; serv; serv = serv->next)
518 if (serv->interface[0] != 0)
519 need_cap_net_raw = 1;
520
521 /* If we're doing Dbus or UBus, the above can be set dynamically,
522 (as can ports) so always (potentially) needed. */
523 #ifdef HAVE_DBUS
524 if (option_bool(OPT_DBUS))
525 {
526 need_cap_net_bind_service = 1;
527 need_cap_net_raw = 1;
528 }
529 #endif
530
531 #ifdef HAVE_UBUS
532 if (option_bool(OPT_UBUS))
533 {
534 need_cap_net_bind_service = 1;
535 need_cap_net_raw = 1;
536 }
537 #endif
538
539 /* determine capability API version here, while we can still
540 call safe_malloc */
541 int capsize = 1; /* for header version 1 */
542 char *fail = NULL;
543
544 hdr = safe_malloc(sizeof(*hdr));
545
546 /* find version supported by kernel */
547 memset(hdr, 0, sizeof(*hdr));
548 capget(hdr, NULL);
549
550 if (hdr->version != LINUX_CAPABILITY_VERSION_1)
551 {
552 /* if unknown version, use largest supported version (3) */
553 if (hdr->version != LINUX_CAPABILITY_VERSION_2)
554 hdr->version = LINUX_CAPABILITY_VERSION_3;
555 capsize = 2;
556 }
557
558 data = safe_malloc(sizeof(*data) * capsize);
559 capget(hdr, data); /* Get current values, for verification */
560
561 have_cap_chown = data->permitted & (1 << CAP_CHOWN);
562
563 if (need_cap_net_admin && !(data->permitted & (1 << CAP_NET_ADMIN)))
564 fail = "NET_ADMIN";
565 else if (need_cap_net_raw && !(data->permitted & (1 << CAP_NET_RAW)))
566 fail = "NET_RAW";
567 else if (need_cap_net_bind_service && !(data->permitted & (1 << CAP_NET_BIND_SERVICE)))
568 fail = "NET_BIND_SERVICE";
569
570 if (fail)
571 die(_("process is missing required capability %s"), fail, EC_MISC);
572
573 /* Now set bitmaps to set caps after daemonising */
574 memset(data, 0, sizeof(*data) * capsize);
575
576 if (need_cap_net_admin)
577 data->effective |= (1 << CAP_NET_ADMIN);
578 if (need_cap_net_raw)
579 data->effective |= (1 << CAP_NET_RAW);
580 if (need_cap_net_bind_service)
581 data->effective |= (1 << CAP_NET_BIND_SERVICE);
582
583 data->permitted = data->effective;
584 #endif
585
586 /* Use a pipe to carry signals and other events back to the event loop
587 in a race-free manner and another to carry errors to daemon-invoking process */
588 safe_pipe(pipefd, 1);
589
590 piperead = pipefd[0];
591 pipewrite = pipefd[1];
592 /* prime the pipe to load stuff first time. */
593 send_event(pipewrite, EVENT_INIT, 0, NULL);
594
595 err_pipe[1] = -1;
596
597 if (!option_bool(OPT_DEBUG))
598 {
599 /* The following code "daemonizes" the process.
600 See Stevens section 12.4 */
601
602 if (chdir("/") != 0)
603 die(_("cannot chdir to filesystem root: %s"), NULL, EC_MISC);
604
605 if (!option_bool(OPT_NO_FORK))
606 {
607 pid_t pid;
608
609 /* pipe to carry errors back to original process.
610 When startup is complete we close this and the process terminates. */
611 safe_pipe(err_pipe, 0);
612
613 if ((pid = fork()) == -1)
614 /* fd == -1 since we've not forked, never returns. */
615 send_event(-1, EVENT_FORK_ERR, errno, NULL);
616
617 if (pid != 0)
618 {
619 struct event_desc ev;
620 char *msg;
621
622 /* close our copy of write-end */
623 close(err_pipe[1]);
624
625 /* check for errors after the fork */
626 if (read_event(err_pipe[0], &ev, &msg))
627 fatal_event(&ev, msg);
628
629 _exit(EC_GOOD);
630 }
631
632 close(err_pipe[0]);
633
634 /* NO calls to die() from here on. */
635
636 setsid();
637
638 if ((pid = fork()) == -1)
639 send_event(err_pipe[1], EVENT_FORK_ERR, errno, NULL);
640
641 if (pid != 0)
642 _exit(0);
643 }
644
645 /* write pidfile _after_ forking ! */
646 if (daemon->runfile)
647 {
648 int fd, err = 0;
649
650 sprintf(daemon->namebuff, "%d\n", (int) getpid());
651
652 /* Explanation: Some installations of dnsmasq (eg Debian/Ubuntu) locate the pid-file
653 in a directory which is writable by the non-privileged user that dnsmasq runs as. This
654 allows the daemon to delete the file as part of its shutdown. This is a security hole to the
655 extent that an attacker running as the unprivileged user could replace the pidfile with a
656 symlink, and have the target of that symlink overwritten as root next time dnsmasq starts.
657
658 The following code first deletes any existing file, and then opens it with the O_EXCL flag,
659 ensuring that the open() fails should there be any existing file (because the unlink() failed,
660 or an attacker exploited the race between unlink() and open()). This ensures that no symlink
661 attack can succeed.
662
663 Any compromise of the non-privileged user still theoretically allows the pid-file to be
664 replaced whilst dnsmasq is running. The worst that could allow is that the usual
665 "shutdown dnsmasq" shell command could be tricked into stopping any other process.
666
667 Note that if dnsmasq is started as non-root (eg for testing) it silently ignores
668 failure to write the pid-file.
669 */
670
671 unlink(daemon->runfile);
672
673 if ((fd = open(daemon->runfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH)) == -1)
674 {
675 /* only complain if started as root */
676 if (getuid() == 0)
677 err = 1;
678 }
679 else
680 {
681 /* We're still running as root here. Change the ownership of the PID file
682 to the user we will be running as. Note that this is not to allow
683 us to delete the file, since that depends on the permissions
684 of the directory containing the file. That directory will
685 need to by owned by the dnsmasq user, and the ownership of the
686 file has to match, to keep systemd >273 happy. */
687 if (getuid() == 0 && ent_pw && ent_pw->pw_uid != 0 && fchown(fd, ent_pw->pw_uid, ent_pw->pw_gid) == -1)
688 chown_warn = errno;
689
690 if (!read_write(fd, (unsigned char *)daemon->namebuff, strlen(daemon->namebuff), RW_WRITE))
691 err = 1;
692 else
693 {
694 if (close(fd) == -1)
695 err = 1;
696 }
697 }
698
699 if (err)
700 {
701 send_event(err_pipe[1], EVENT_PIDFILE, errno, daemon->runfile);
702 _exit(0);
703 }
704 }
705 }
706
707 log_err = log_start(ent_pw, err_pipe[1]);
708
709 if (!option_bool(OPT_DEBUG))
710 {
711 /* open stdout etc to /dev/null */
712 int nullfd = open("/dev/null", O_RDWR);
713 if (nullfd != -1)
714 {
715 dup2(nullfd, STDOUT_FILENO);
716 dup2(nullfd, STDERR_FILENO);
717 dup2(nullfd, STDIN_FILENO);
718 close(nullfd);
719 }
720 }
721
722 /* if we are to run scripts, we need to fork a helper before dropping root. */
723 daemon->helperfd = -1;
724 #ifdef HAVE_SCRIPT
725 if ((daemon->dhcp ||
726 daemon->dhcp6 ||
727 daemon->relay6 ||
728 option_bool(OPT_TFTP) ||
729 option_bool(OPT_SCRIPT_ARP)) &&
730 (daemon->lease_change_command || daemon->luascript))
731 daemon->helperfd = create_helper(pipewrite, err_pipe[1], script_uid, script_gid, max_fd);
732 #endif
733
734 if (!option_bool(OPT_DEBUG) && getuid() == 0)
735 {
736 int bad_capabilities = 0;
737 gid_t dummy;
738
739 /* remove all supplementary groups */
740 if (gp &&
741 (setgroups(0, &dummy) == -1 ||
742 setgid(gp->gr_gid) == -1))
743 {
744 send_event(err_pipe[1], EVENT_GROUP_ERR, errno, daemon->groupname);
745 _exit(0);
746 }
747
748 if (ent_pw && ent_pw->pw_uid != 0)
749 {
750 #if defined(HAVE_LINUX_NETWORK)
751 /* Need to be able to drop root. */
752 data->effective |= (1 << CAP_SETUID);
753 data->permitted |= (1 << CAP_SETUID);
754 /* Tell kernel to not clear capabilities when dropping root */
755 if (capset(hdr, data) == -1 || prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1)
756 bad_capabilities = errno;
757
758 #elif defined(HAVE_SOLARIS_NETWORK)
759 /* http://developers.sun.com/solaris/articles/program_privileges.html */
760 priv_set_t *priv_set;
761
762 if (!(priv_set = priv_str_to_set("basic", ",", NULL)) ||
763 priv_addset(priv_set, PRIV_NET_ICMPACCESS) == -1 ||
764 priv_addset(priv_set, PRIV_SYS_NET_CONFIG) == -1)
765 bad_capabilities = errno;
766
767 if (priv_set && bad_capabilities == 0)
768 {
769 priv_inverse(priv_set);
770
771 if (setppriv(PRIV_OFF, PRIV_LIMIT, priv_set) == -1)
772 bad_capabilities = errno;
773 }
774
775 if (priv_set)
776 priv_freeset(priv_set);
777
778 #endif
779
780 if (bad_capabilities != 0)
781 {
782 send_event(err_pipe[1], EVENT_CAP_ERR, bad_capabilities, NULL);
783 _exit(0);
784 }
785
786 /* finally drop root */
787 if (setuid(ent_pw->pw_uid) == -1)
788 {
789 send_event(err_pipe[1], EVENT_USER_ERR, errno, daemon->username);
790 _exit(0);
791 }
792
793 #ifdef HAVE_LINUX_NETWORK
794 data->effective &= ~(1 << CAP_SETUID);
795 data->permitted &= ~(1 << CAP_SETUID);
796
797 /* lose the setuid capability */
798 if (capset(hdr, data) == -1)
799 {
800 send_event(err_pipe[1], EVENT_CAP_ERR, errno, NULL);
801 _exit(0);
802 }
803 #endif
804
805 }
806 }
807
808 #ifdef HAVE_LINUX_NETWORK
809 free(hdr);
810 free(data);
811 if (option_bool(OPT_DEBUG))
812 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
813 #endif
814
815 #ifdef HAVE_TFTP
816 if (option_bool(OPT_TFTP))
817 {
818 DIR *dir;
819 struct tftp_prefix *p;
820
821 if (daemon->tftp_prefix)
822 {
823 if (!((dir = opendir(daemon->tftp_prefix))))
824 {
825 tftp_prefix_missing = 1;
826 if (!option_bool(OPT_TFTP_NO_FAIL))
827 {
828 send_event(err_pipe[1], EVENT_TFTP_ERR, errno, daemon->tftp_prefix);
829 _exit(0);
830 }
831 }
832 else
833 closedir(dir);
834 }
835
836 for (p = daemon->if_prefix; p; p = p->next)
837 {
838 p->missing = 0;
839 if (!((dir = opendir(p->prefix))))
840 {
841 p->missing = 1;
842 if (!option_bool(OPT_TFTP_NO_FAIL))
843 {
844 send_event(err_pipe[1], EVENT_TFTP_ERR, errno, p->prefix);
845 _exit(0);
846 }
847 }
848 else
849 closedir(dir);
850 }
851 }
852 #endif
853
854 #ifdef HAVE_INOTIFY
855 if ((daemon->port != 0 && !option_bool(OPT_NO_RESOLV)) ||
856 daemon->dynamic_dirs)
857 inotify_dnsmasq_init(err_pipe[1]);
858 else
859 daemon->inotifyfd = -1;
860 #endif
861
862 /* Don't start logging malloc before logging is set up. */
863 daemon->log_malloc = option_bool(OPT_LOG_MALLOC);
864
865 if (daemon->port == 0)
866 my_syslog(LOG_INFO, _("started, version %s DNS disabled"), VERSION);
867 else
868 {
869 if (daemon->cachesize != 0)
870 {
871 my_syslog(LOG_INFO, _("started, version %s cachesize %d"), VERSION, daemon->cachesize);
872 if (daemon->cachesize > 10000)
873 my_syslog(LOG_WARNING, _("cache size greater than 10000 may cause performance issues, and is unlikely to be useful."));
874 }
875 else
876 my_syslog(LOG_INFO, _("started, version %s cache disabled"), VERSION);
877
878 if (option_bool(OPT_LOCAL_SERVICE))
879 my_syslog(LOG_INFO, _("DNS service limited to local subnets"));
880 else if (option_bool(OPT_LOCALHOST_SERVICE))
881 my_syslog(LOG_INFO, _("DNS service limited to localhost"));
882 }
883
884 my_syslog(LOG_INFO, _("compile time options: %s"), compile_opts);
885
886 if (chown_warn != 0)
887 {
888 #if defined(HAVE_LINUX_NETWORK)
889 if (chown_warn == EPERM && !have_cap_chown)
890 my_syslog(LOG_INFO, "chown of PID file %s failed: please add capability CAP_CHOWN", daemon->runfile);
891 else
892 #endif
893 my_syslog(LOG_WARNING, "chown of PID file %s failed: %s", daemon->runfile, strerror(chown_warn));
894 }
895
896 #ifdef HAVE_DBUS
897 if (option_bool(OPT_DBUS))
898 {
899 if (daemon->dbus)
900 my_syslog(LOG_INFO, _("DBus support enabled: connected to system bus"));
901 else
902 my_syslog(LOG_INFO, _("DBus support enabled: bus connection pending"));
903 }
904 #endif
905
906 #ifdef HAVE_UBUS
907 if (option_bool(OPT_UBUS))
908 {
909 if (daemon->ubus)
910 my_syslog(LOG_INFO, _("UBus support enabled: connected to system bus"));
911 else
912 my_syslog(LOG_INFO, _("UBus support enabled: bus connection pending"));
913 }
914 #endif
915
916 #ifdef HAVE_DNSSEC
917 if (option_bool(OPT_DNSSEC_VALID))
918 {
919 int rc;
920 struct ds_config *ds;
921
922 /* Delay creating the timestamp file until here, after we've changed user, so that
923 it has the correct owner to allow updating the mtime later.
924 This means we have to report fatal errors via the pipe. */
925 if ((rc = setup_timestamp()) == -1)
926 {
927 send_event(err_pipe[1], EVENT_TIME_ERR, errno, daemon->timestamp_file);
928 _exit(0);
929 }
930
931 if (option_bool(OPT_DNSSEC_IGN_NS))
932 my_syslog(LOG_INFO, _("DNSSEC validation enabled but all unsigned answers are trusted"));
933 else
934 my_syslog(LOG_INFO, _("DNSSEC validation enabled"));
935
936 daemon->dnssec_no_time_check = option_bool(OPT_DNSSEC_TIME);
937 if (option_bool(OPT_DNSSEC_TIME) && !daemon->back_to_the_future)
938 my_syslog(LOG_INFO, _("DNSSEC signature timestamps not checked until receipt of SIGINT"));
939
940 if (rc == 1)
941 my_syslog(LOG_INFO, _("DNSSEC signature timestamps not checked until system time valid"));
942
943 for (ds = daemon->ds; ds; ds = ds->next)
944 {
945 struct ds_config *ds1;
946
947 for (ds1 = ds->next; ds1; ds1 = ds1->next)
948 if (strcmp(ds->name, ds1->name) == 0 &&
949 ds->digestlen == ds1->digestlen &&
950 (ds->digestlen == 0 ||
951 (ds->algo == ds1->algo &&
952 ds->keytag == ds1->keytag &&
953 ds->digest_type == ds1->digest_type &&
954 memcmp(ds->digest, ds1->digest, ds->digestlen) == 0)))
955 {
956 ds->name = NULL; /* Mark as duplicate */
957 break;
958 }
959
960 if (ds->name)
961 my_syslog(LOG_INFO,
962 ds->digestlen == 0 ? _("configured with negative trust anchor for %s") : _("configured with trust anchor for %s keytag %u"),
963 ds->name[0] == 0 ? "<root>" : ds->name, ds->keytag);
964 }
965 }
966 #endif
967
968 if (log_err != 0)
969 my_syslog(LOG_WARNING, _("warning: failed to change owner of %s: %s"),
970 daemon->log_file, strerror(log_err));
971
972 #ifndef HAVE_LINUX_NETWORK
973 if (bind_fallback)
974 my_syslog(LOG_WARNING, _("setting --bind-interfaces option because of OS limitations"));
975 #endif
976
977 if (option_bool(OPT_NOWILD))
978 warn_bound_listeners();
979 else if (!option_bool(OPT_CLEVERBIND))
980 warn_wild_labels();
981
982 warn_int_names();
983
984 if (!option_bool(OPT_NOWILD))
985 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
986 if (if_tmp->name && !(if_tmp->flags & INAME_USED))
987 my_syslog(LOG_WARNING, _("warning: interface %s does not currently exist"), if_tmp->name);
988
989 if (daemon->port != 0 && option_bool(OPT_NO_RESOLV))
990 {
991 if (daemon->resolv_files && !daemon->resolv_files->is_default)
992 my_syslog(LOG_WARNING, _("warning: ignoring resolv-file flag because no-resolv is set"));
993 daemon->resolv_files = NULL;
994 if (!daemon->servers)
995 {
996 #ifdef HAVE_DBUS
997 if (option_bool(OPT_DBUS))
998 my_syslog(LOG_INFO, _("no upstream servers configured - please set them from DBus"));
999 else
1000 #endif
1001 my_syslog(LOG_WARNING, _("warning: no upstream servers configured"));
1002 }
1003 }
1004
1005 if (daemon->max_logs != 0)
1006 my_syslog(LOG_INFO, _("asynchronous logging enabled, queue limit is %d messages"), daemon->max_logs);
1007
1008
1009 #ifdef HAVE_DHCP
1010 for (context = daemon->dhcp; context; context = context->next)
1011 log_context(AF_INET, context);
1012
1013 for (relay = daemon->relay4; relay; relay = relay->next)
1014 log_relay(AF_INET, relay);
1015
1016 # ifdef HAVE_DHCP6
1017 for (context = daemon->dhcp6; context; context = context->next)
1018 log_context(AF_INET6, context);
1019
1020 for (relay = daemon->relay6; relay; relay = relay->next)
1021 log_relay(AF_INET6, relay);
1022
1023 if (daemon->doing_dhcp6 || daemon->doing_ra)
1024 dhcp_construct_contexts(now);
1025
1026 if (option_bool(OPT_RA))
1027 my_syslog(MS_DHCP | LOG_INFO, _("IPv6 router advertisement enabled"));
1028 # endif
1029
1030 # ifdef HAVE_LINUX_NETWORK
1031 if (did_bind)
1032 my_syslog(MS_DHCP | LOG_INFO, _("DHCP, sockets bound exclusively to interface %s"), bound_device);
1033
1034 if (netlink_warn)
1035 my_syslog(LOG_WARNING, netlink_warn);
1036 # endif
1037
1038 /* after dhcp_construct_contexts */
1039 if (daemon->dhcp || daemon->doing_dhcp6)
1040 lease_find_interfaces(now);
1041 #endif
1042
1043 #ifdef HAVE_TFTP
1044 if (option_bool(OPT_TFTP))
1045 {
1046 struct tftp_prefix *p;
1047
1048 my_syslog(MS_TFTP | LOG_INFO, "TFTP %s%s %s %s",
1049 daemon->tftp_prefix ? _("root is ") : _("enabled"),
1050 daemon->tftp_prefix ? daemon->tftp_prefix : "",
1051 option_bool(OPT_TFTP_SECURE) ? _("secure mode") : "",
1052 option_bool(OPT_SINGLE_PORT) ? _("single port mode") : "");
1053
1054 if (tftp_prefix_missing)
1055 my_syslog(MS_TFTP | LOG_WARNING, _("warning: %s inaccessible"), daemon->tftp_prefix);
1056
1057 for (p = daemon->if_prefix; p; p = p->next)
1058 if (p->missing)
1059 my_syslog(MS_TFTP | LOG_WARNING, _("warning: TFTP directory %s inaccessible"), p->prefix);
1060
1061 /* This is a guess, it assumes that for small limits,
1062 disjoint files might be served, but for large limits,
1063 a single file will be sent to may clients (the file only needs
1064 one fd). */
1065
1066 max_fd -= 30 + daemon->numrrand; /* use other than TFTP */
1067
1068 if (max_fd < 0)
1069 max_fd = 5;
1070 else if (max_fd < 100 && !option_bool(OPT_SINGLE_PORT))
1071 max_fd = max_fd/2;
1072 else
1073 max_fd = max_fd - 20;
1074
1075 /* if we have to use a limited range of ports,
1076 that will limit the number of transfers */
1077 if (daemon->start_tftp_port != 0 &&
1078 daemon->end_tftp_port - daemon->start_tftp_port + 1 < max_fd)
1079 max_fd = daemon->end_tftp_port - daemon->start_tftp_port + 1;
1080
1081 if (daemon->tftp_max > max_fd)
1082 {
1083 daemon->tftp_max = max_fd;
1084 my_syslog(MS_TFTP | LOG_WARNING,
1085 _("restricting maximum simultaneous TFTP transfers to %d"),
1086 daemon->tftp_max);
1087 }
1088 }
1089 #endif
1090
1091 /* finished start-up - release original process */
1092 if (err_pipe[1] != -1)
1093 close(err_pipe[1]);
1094
1095 if (daemon->port != 0)
1096 check_servers(0);
1097
1098 pid = getpid();
1099
1100 #ifdef HAVE_INOTIFY
1101 /* Using inotify, have to select a resolv file at startup */
1102 poll_resolv(1, 0, now);
1103 #endif
1104
1105 while (1)
1106 {
1107 int timeout = fast_retry(now);
1108
1109 poll_reset();
1110
1111 /* Whilst polling for the dbus, or doing a tftp transfer, wake every quarter second */
1112 if ((daemon->tftp_trans || (option_bool(OPT_DBUS) && !daemon->dbus)) &&
1113 (timeout == -1 || timeout > 250))
1114 timeout = 250;
1115
1116 /* Wake every second whilst waiting for DAD to complete */
1117 else if (is_dad_listeners() &&
1118 (timeout == -1 || timeout > 1000))
1119 timeout = 1000;
1120
1121 if (daemon->port != 0)
1122 set_dns_listeners();
1123
1124 #ifdef HAVE_TFTP
1125 set_tftp_listeners();
1126 #endif
1127
1128 #ifdef HAVE_DBUS
1129 if (option_bool(OPT_DBUS))
1130 set_dbus_listeners();
1131 #endif
1132
1133 #ifdef HAVE_UBUS
1134 if (option_bool(OPT_UBUS))
1135 set_ubus_listeners();
1136 #endif
1137
1138 #ifdef HAVE_DHCP
1139 # if defined(HAVE_LINUX_NETWORK)
1140 if (bind_dhcp_devices(bound_device) & 2)
1141 {
1142 static int warned = 0;
1143 if (!warned)
1144 {
1145 my_syslog(LOG_ERR, _("error binding DHCP socket to device %s"), bound_device);
1146 warned = 1;
1147 }
1148 }
1149 # endif
1150 if (daemon->dhcp || daemon->relay4)
1151 {
1152 poll_listen(daemon->dhcpfd, POLLIN);
1153 if (daemon->pxefd != -1)
1154 poll_listen(daemon->pxefd, POLLIN);
1155 }
1156 #endif
1157
1158 #ifdef HAVE_DHCP6
1159 if (daemon->doing_dhcp6 || daemon->relay6)
1160 poll_listen(daemon->dhcp6fd, POLLIN);
1161
1162 if (daemon->doing_ra)
1163 poll_listen(daemon->icmp6fd, POLLIN);
1164 #endif
1165
1166 #ifdef HAVE_INOTIFY
1167 if (daemon->inotifyfd != -1)
1168 poll_listen(daemon->inotifyfd, POLLIN);
1169 #endif
1170
1171 #if defined(HAVE_LINUX_NETWORK)
1172 poll_listen(daemon->netlinkfd, POLLIN);
1173 #elif defined(HAVE_BSD_NETWORK)
1174 poll_listen(daemon->routefd, POLLIN);
1175 #endif
1176
1177 poll_listen(piperead, POLLIN);
1178
1179 #ifdef HAVE_SCRIPT
1180 # ifdef HAVE_DHCP
1181 while (helper_buf_empty() && do_script_run(now));
1182 # endif
1183
1184 /* Refresh cache */
1185 if (option_bool(OPT_SCRIPT_ARP))
1186 find_mac(NULL, NULL, 0, now);
1187 while (helper_buf_empty() && do_arp_script_run());
1188
1189 # ifdef HAVE_TFTP
1190 while (helper_buf_empty() && do_tftp_script_run());
1191 # endif
1192
1193 # ifdef HAVE_DHCP6
1194 while (helper_buf_empty() && do_snoop_script_run());
1195 # endif
1196
1197 if (!helper_buf_empty())
1198 poll_listen(daemon->helperfd, POLLOUT);
1199 #else
1200 /* need this for other side-effects */
1201 # ifdef HAVE_DHCP
1202 while (do_script_run(now));
1203 # endif
1204
1205 while (do_arp_script_run());
1206
1207 # ifdef HAVE_TFTP
1208 while (do_tftp_script_run());
1209 # endif
1210
1211 #endif
1212
1213
1214 /* must do this just before do_poll(), when we know no
1215 more calls to my_syslog() can occur */
1216 set_log_writer();
1217
1218 if (do_poll(timeout) < 0)
1219 continue;
1220
1221 now = dnsmasq_time();
1222
1223 check_log_writer(0);
1224
1225 /* prime. */
1226 enumerate_interfaces(1);
1227
1228 /* Check the interfaces to see if any have exited DAD state
1229 and if so, bind the address. */
1230 if (is_dad_listeners())
1231 {
1232 enumerate_interfaces(0);
1233 /* NB, is_dad_listeners() == 1 --> we're binding interfaces */
1234 create_bound_listeners(0);
1235 warn_bound_listeners();
1236 }
1237
1238 #if defined(HAVE_LINUX_NETWORK)
1239 if (poll_check(daemon->netlinkfd, POLLIN))
1240 netlink_multicast();
1241 #elif defined(HAVE_BSD_NETWORK)
1242 if (poll_check(daemon->routefd, POLLIN))
1243 route_sock();
1244 #endif
1245
1246 #ifdef HAVE_INOTIFY
1247 if (daemon->inotifyfd != -1 && poll_check(daemon->inotifyfd, POLLIN) && inotify_check(now))
1248 {
1249 if (daemon->port != 0 && !option_bool(OPT_NO_POLL))
1250 poll_resolv(1, 1, now);
1251 }
1252 #else
1253 /* Check for changes to resolv files once per second max. */
1254 /* Don't go silent for long periods if the clock goes backwards. */
1255 if (daemon->last_resolv == 0 ||
1256 difftime(now, daemon->last_resolv) > 1.0 ||
1257 difftime(now, daemon->last_resolv) < -1.0)
1258 {
1259 /* poll_resolv doesn't need to reload first time through, since
1260 that's queued anyway. */
1261
1262 poll_resolv(0, daemon->last_resolv != 0, now);
1263 daemon->last_resolv = now;
1264 }
1265 #endif
1266
1267 if (poll_check(piperead, POLLIN))
1268 async_event(piperead, now);
1269
1270 #ifdef HAVE_DBUS
1271 /* if we didn't create a DBus connection, retry now. */
1272 if (option_bool(OPT_DBUS))
1273 {
1274 if (!daemon->dbus)
1275 {
1276 char *err = dbus_init();
1277
1278 if (daemon->dbus)
1279 my_syslog(LOG_INFO, _("connected to system DBus"));
1280 else if (err)
1281 {
1282 my_syslog(LOG_ERR, _("DBus error: %s"), err);
1283 reset_option_bool(OPT_DBUS); /* fatal error, stop trying. */
1284 }
1285 }
1286
1287 check_dbus_listeners();
1288 }
1289 #endif
1290
1291 #ifdef HAVE_UBUS
1292 /* if we didn't create a UBus connection, retry now. */
1293 if (option_bool(OPT_UBUS))
1294 {
1295 if (!daemon->ubus)
1296 {
1297 char *err = ubus_init();
1298
1299 if (daemon->ubus)
1300 my_syslog(LOG_INFO, _("connected to system UBus"));
1301 else if (err)
1302 {
1303 my_syslog(LOG_ERR, _("UBus error: %s"), err);
1304 reset_option_bool(OPT_UBUS); /* fatal error, stop trying. */
1305 }
1306 }
1307
1308 check_ubus_listeners();
1309 }
1310 #endif
1311
1312 if (daemon->port != 0)
1313 check_dns_listeners(now);
1314
1315 #ifdef HAVE_TFTP
1316 check_tftp_listeners(now);
1317 #endif
1318
1319 #ifdef HAVE_DHCP
1320 if (daemon->dhcp || daemon->relay4)
1321 {
1322 if (poll_check(daemon->dhcpfd, POLLIN))
1323 dhcp_packet(now, 0);
1324 if (daemon->pxefd != -1 && poll_check(daemon->pxefd, POLLIN))
1325 dhcp_packet(now, 1);
1326 }
1327
1328 #ifdef HAVE_DHCP6
1329 if ((daemon->doing_dhcp6 || daemon->relay6) && poll_check(daemon->dhcp6fd, POLLIN))
1330 dhcp6_packet(now);
1331
1332 if (daemon->doing_ra && poll_check(daemon->icmp6fd, POLLIN))
1333 icmp6_packet(now);
1334 #endif
1335
1336 # ifdef HAVE_SCRIPT
1337 if (daemon->helperfd != -1 && poll_check(daemon->helperfd, POLLOUT))
1338 helper_write();
1339 # endif
1340 #endif
1341
1342 }
1343 }
1344
1345 static void sig_handler(int sig)
1346 {
1347 if (pid == 0)
1348 {
1349 /* ignore anything other than TERM during startup
1350 and in helper proc. (helper ignore TERM too) */
1351 if (sig == SIGTERM || sig == SIGINT)
1352 exit(EC_MISC);
1353 }
1354 else if (daemon->pipe_to_parent != -1)
1355 {
1356 /* alarm is used to kill TCP children after a fixed time. */
1357 if (sig == SIGALRM)
1358 {
1359 #ifdef HAVE_DNSSEC
1360 if (!daemon->forward_to_tcp)
1361 #endif
1362 _exit(0); /* Normal TCP child */
1363 #ifdef HAVE_DNSSEC
1364 else
1365 {
1366 /* udp_to_tcp transfer.
1367 If daemon->header_to_tcp is NULL the waiting is over and
1368 we can let things take their course, otherwise, send a failure
1369 return down the pipe to unblock the UDP transaction and kill
1370 the process. */
1371 if (daemon->header_to_tcp)
1372 {
1373 unsigned char op = PIPE_OP_KILLED;
1374 int status = STAT_ABANDONED;
1375
1376 read_write(daemon->pipe_to_parent, &op, sizeof(op), RW_WRITE);
1377 read_write(daemon->pipe_to_parent, (unsigned char *)&status, sizeof(status), RW_WRITE);
1378 read_write(daemon->pipe_to_parent, (unsigned char *)(&daemon->plen_to_tcp), sizeof(daemon->plen_to_tcp), RW_WRITE);
1379 read_write(daemon->pipe_to_parent, (unsigned char *)(daemon->header_to_tcp), daemon->plen_to_tcp, RW_WRITE);
1380 read_write(daemon->pipe_to_parent, (unsigned char *)(&daemon->forward_to_tcp), sizeof(daemon->forward_to_tcp), RW_WRITE);
1381 read_write(daemon->pipe_to_parent, (unsigned char *)(&daemon->forward_to_tcp->uid), sizeof(daemon->forward_to_tcp->uid), RW_WRITE);
1382
1383 _exit(0);
1384 }
1385 }
1386 #endif
1387 }
1388 }
1389 else
1390 {
1391 /* master process */
1392 int event, errsave = errno;
1393
1394 if (sig == SIGHUP)
1395 event = EVENT_RELOAD;
1396 else if (sig == SIGCHLD)
1397 event = EVENT_CHILD;
1398 else if (sig == SIGALRM)
1399 event = EVENT_ALARM;
1400 else if (sig == SIGTERM)
1401 event = EVENT_TERM;
1402 else if (sig == SIGUSR1)
1403 event = EVENT_DUMP;
1404 else if (sig == SIGUSR2)
1405 event = EVENT_REOPEN;
1406 else if (sig == SIGINT)
1407 {
1408 /* Handle SIGINT normally in debug mode, so
1409 ctrl-c continues to operate. */
1410 if (option_bool(OPT_DEBUG))
1411 exit(EC_MISC);
1412 else
1413 event = EVENT_TIME;
1414 }
1415 else
1416 return;
1417
1418 send_event(pipewrite, event, 0, NULL);
1419 errno = errsave;
1420 }
1421 }
1422
1423 /* now == 0 -> queue immediate callback */
1424 void send_alarm(time_t event, time_t now)
1425 {
1426 if (now == 0 || event != 0)
1427 {
1428 /* alarm(0) or alarm(-ve) doesn't do what we want.... */
1429 if ((now == 0 || difftime(event, now) <= 0.0))
1430 send_event(pipewrite, EVENT_ALARM, 0, NULL);
1431 else
1432 alarm((unsigned)difftime(event, now));
1433 }
1434 }
1435
1436 void queue_event(int event)
1437 {
1438 send_event(pipewrite, event, 0, NULL);
1439 }
1440
1441 void send_event(int fd, int event, int data, char *msg)
1442 {
1443 struct event_desc ev;
1444 struct iovec iov[2];
1445
1446 ev.event = event;
1447 ev.data = data;
1448 ev.msg_sz = msg ? strlen(msg) : 0;
1449
1450 iov[0].iov_base = &ev;
1451 iov[0].iov_len = sizeof(ev);
1452 iov[1].iov_base = msg;
1453 iov[1].iov_len = ev.msg_sz;
1454
1455 /* error pipe, debug mode. */
1456 if (fd == -1)
1457 fatal_event(&ev, msg);
1458 else
1459 /* pipe is non-blocking and struct event_desc is smaller than
1460 PIPE_BUF, so this either fails or writes everything */
1461 while (writev(fd, iov, msg ? 2 : 1) == -1 && errno == EINTR);
1462 }
1463
1464 static int read_event(int fd, struct event_desc *evp, char **msg)
1465 {
1466 char *buf;
1467
1468 if (!read_write(fd, (unsigned char *)evp, sizeof(struct event_desc), RW_READ))
1469 return 0;
1470
1471 *msg = NULL;
1472
1473 if (evp->msg_sz != 0)
1474 {
1475 if (!(buf = whine_malloc(evp->msg_sz + 1)))
1476 {
1477 int i;
1478 unsigned char a;
1479
1480 /* Keep the stream synchronised if malloc fails. */
1481 for (i = 0; i < evp->msg_sz; i++)
1482 read_write(fd, &a, 1, RW_READ);
1483 }
1484 else if (read_write(fd, (unsigned char *)buf, evp->msg_sz, RW_READ))
1485 {
1486 buf[evp->msg_sz] = 0;
1487 *msg = buf;
1488 }
1489 }
1490
1491 return 1;
1492 }
1493
1494 static void fatal_event(struct event_desc *ev, char *msg)
1495 {
1496 errno = ev->data;
1497
1498 switch (ev->event)
1499 {
1500 case EVENT_DIE:
1501 exit(0);
1502
1503 case EVENT_FORK_ERR:
1504 die(_("cannot fork into background: %s"), NULL, EC_MISC);
1505
1506 /* fall through */
1507 case EVENT_PIPE_ERR:
1508 die(_("failed to create helper: %s"), NULL, EC_MISC);
1509
1510 /* fall through */
1511 case EVENT_CAP_ERR:
1512 die(_("setting capabilities failed: %s"), NULL, EC_MISC);
1513
1514 /* fall through */
1515 case EVENT_USER_ERR:
1516 die(_("failed to change user-id to %s: %s"), msg, EC_MISC);
1517
1518 /* fall through */
1519 case EVENT_GROUP_ERR:
1520 die(_("failed to change group-id to %s: %s"), msg, EC_MISC);
1521
1522 /* fall through */
1523 case EVENT_PIDFILE:
1524 die(_("failed to open pidfile %s: %s"), msg, EC_FILE);
1525
1526 /* fall through */
1527 case EVENT_LOG_ERR:
1528 die(_("cannot open log %s: %s"), msg, EC_FILE);
1529
1530 /* fall through */
1531 case EVENT_LUA_ERR:
1532 die(_("failed to load Lua script: %s"), msg, EC_MISC);
1533
1534 /* fall through */
1535 case EVENT_TFTP_ERR:
1536 die(_("TFTP directory %s inaccessible: %s"), msg, EC_FILE);
1537
1538 /* fall through */
1539 case EVENT_TIME_ERR:
1540 die(_("cannot create timestamp file %s: %s" ), msg, EC_BADCONF);
1541
1542 /* fall through */
1543 case EVENT_LINK_ERR:
1544 die(_("cannot access path %s: %s" ), msg, EC_MISC);
1545
1546 /* fall through */
1547 case EVENT_INOTFY_ERR:
1548 die(_("failed to create inotify: %s" ), NULL, EC_MISC);
1549
1550 /* fall through */
1551 case EVENT_TMSL_ERR:
1552 die(_("too many symlinks following %s"), msg, EC_MISC);
1553
1554 /* fall through */
1555 case EVENT_RESOLV_ERR:
1556 die(_("directory %s for resolv-file is missing, cannot poll"), msg, EC_MISC);
1557
1558 /* fall through */
1559 case EVENT_IFILE_ERR:
1560 die(_("failed to create inotify for %s: %s"), msg, EC_MISC);
1561 }
1562 }
1563
1564 static void async_event(int pipe, time_t now)
1565 {
1566 pid_t p;
1567 struct event_desc ev;
1568 int wstatus, i, check = 0;
1569 char *msg;
1570
1571 if (read_event(pipe, &ev, &msg))
1572 switch (ev.event)
1573 {
1574 case EVENT_RELOAD:
1575 daemon->soa_sn++; /* Bump zone serial, as it may have changed. */
1576
1577 /* fall through */
1578
1579 case EVENT_INIT:
1580 clear_cache_and_reload(now);
1581
1582 if (daemon->port != 0)
1583 {
1584 if (daemon->resolv_files && option_bool(OPT_NO_POLL))
1585 {
1586 reload_servers(daemon->resolv_files->name);
1587 check = 1;
1588 }
1589
1590 if (daemon->servers_file)
1591 {
1592 read_servers_file();
1593 check = 1;
1594 }
1595
1596 if (check)
1597 check_servers(0);
1598 }
1599
1600 #ifdef HAVE_DHCP
1601 rerun_scripts();
1602 #endif
1603 break;
1604
1605 case EVENT_DUMP:
1606 if (daemon->port != 0)
1607 dump_cache(now);
1608 break;
1609
1610 case EVENT_ALARM:
1611 #ifdef HAVE_DHCP
1612 if (daemon->dhcp || daemon->doing_dhcp6)
1613 {
1614 lease_prune(NULL, now);
1615 lease_update_file(now);
1616 lease_update_dns(0);
1617 }
1618 #ifdef HAVE_DHCP6
1619 else if (daemon->doing_ra)
1620 /* Not doing DHCP, so no lease system, manage alarms for ra only */
1621 send_alarm(periodic_ra(now), now);
1622 #endif
1623 #endif
1624 break;
1625
1626 case EVENT_CHILD:
1627 /* See Stevens 5.10 */
1628 while ((p = waitpid(-1, &wstatus, WNOHANG)) != 0)
1629 if (p == -1)
1630 {
1631 if (errno != EINTR)
1632 break;
1633 }
1634 else if (daemon->port != 0)
1635 for (i = 0 ; i < daemon->max_procs; i++)
1636 if (daemon->tcp_pids[i] == p)
1637 {
1638 daemon->tcp_pids[i] = 0;
1639
1640 if (!WIFEXITED(wstatus))
1641 {
1642 /* If a helper process dies, (eg with SIGSEV)
1643 log that and attempt to patch things up so that the
1644 parent can continue to function. */
1645 my_syslog(LOG_WARNING, _("TCP helper process %u died unexpectedly"), (unsigned int)p);
1646 if (daemon->tcp_pipes[i] != -1)
1647 {
1648 close(daemon->tcp_pipes[i]);
1649 daemon->tcp_pipes[i] = -1;
1650 }
1651 }
1652
1653 /* tcp_pipes == -1 && tcp_pids == 0 required to free slot */
1654 if (daemon->tcp_pipes[i] == -1)
1655 daemon->metrics[METRIC_TCP_CONNECTIONS]--;
1656 }
1657 break;
1658
1659 #if defined(HAVE_SCRIPT)
1660 case EVENT_KILLED:
1661 my_syslog(LOG_WARNING, _("script process killed by signal %d"), ev.data);
1662 break;
1663
1664 case EVENT_EXITED:
1665 my_syslog(LOG_WARNING, _("script process exited with status %d"), ev.data);
1666 break;
1667
1668 case EVENT_EXEC_ERR:
1669 my_syslog(LOG_ERR, _("failed to execute %s: %s"),
1670 daemon->lease_change_command, strerror(ev.data));
1671 break;
1672
1673 case EVENT_SCRIPT_LOG:
1674 my_syslog(MS_SCRIPT | LOG_DEBUG, "%s", msg ? msg : "");
1675 free(msg);
1676 break;
1677
1678 /* necessary for fatal errors in helper */
1679 case EVENT_USER_ERR:
1680 case EVENT_DIE:
1681 case EVENT_LUA_ERR:
1682 fatal_event(&ev, msg);
1683 break;
1684 #endif
1685
1686 case EVENT_REOPEN:
1687 /* Note: this may leave TCP-handling processes with the old file still open.
1688 Since any such process will die in CHILD_LIFETIME or probably much sooner,
1689 we leave them logging to the old file. */
1690 if (daemon->log_file != NULL)
1691 log_reopen(daemon->log_file);
1692 break;
1693
1694 case EVENT_NEWADDR:
1695 newaddress(now);
1696 break;
1697
1698 case EVENT_NEWROUTE:
1699 resend_query();
1700 /* Force re-reading resolv file right now, for luck. */
1701 poll_resolv(0, 1, now);
1702 break;
1703
1704 case EVENT_TIME:
1705 #ifdef HAVE_DNSSEC
1706 if (daemon->dnssec_no_time_check && option_bool(OPT_DNSSEC_VALID) && option_bool(OPT_DNSSEC_TIME))
1707 {
1708 my_syslog(LOG_INFO, _("now checking DNSSEC signature timestamps"));
1709 daemon->dnssec_no_time_check = 0;
1710 clear_cache_and_reload(now);
1711 }
1712 #endif
1713 break;
1714
1715 case EVENT_TERM:
1716 /* Knock all our children on the head. */
1717 if (daemon->port != 0)
1718 for (i = 0; i < daemon->max_procs; i++)
1719 if (daemon->tcp_pids[i] != 0)
1720 kill(daemon->tcp_pids[i], SIGALRM);
1721
1722 #if defined(HAVE_SCRIPT) && defined(HAVE_DHCP)
1723 /* handle pending lease transitions */
1724 if (daemon->helperfd != -1)
1725 {
1726 /* block in writes until all done */
1727 if ((i = fcntl(daemon->helperfd, F_GETFL)) != -1)
1728 while(retry_send(fcntl(daemon->helperfd, F_SETFL, i & ~O_NONBLOCK)));
1729 do {
1730 helper_write();
1731 } while (!helper_buf_empty() || do_script_run(now));
1732 close(daemon->helperfd);
1733 }
1734 #endif
1735
1736 if (daemon->lease_stream)
1737 fclose(daemon->lease_stream);
1738
1739 #ifdef HAVE_DNSSEC
1740 /* update timestamp file on TERM if time is considered valid */
1741 if (daemon->back_to_the_future)
1742 {
1743 if (utimes(daemon->timestamp_file, NULL) == -1)
1744 my_syslog(LOG_ERR, _("failed to update mtime on %s: %s"), daemon->timestamp_file, strerror(errno));
1745 }
1746 #endif
1747
1748 if (daemon->runfile)
1749 unlink(daemon->runfile);
1750
1751 #ifdef HAVE_DUMPFILE
1752 if (daemon->dumpfd != -1)
1753 close(daemon->dumpfd);
1754 #endif
1755
1756 my_syslog(LOG_INFO, _("exiting on receipt of SIGTERM"));
1757 flush_log();
1758 exit(EC_GOOD);
1759 }
1760 }
1761
1762 static void poll_resolv(int force, int do_reload, time_t now)
1763 {
1764 struct resolvc *res, *latest;
1765 struct stat statbuf;
1766 time_t last_change = 0;
1767 /* There may be more than one possible file.
1768 Go through and find the one which changed _last_.
1769 Warn of any which can't be read. */
1770
1771 if (daemon->port == 0 || option_bool(OPT_NO_POLL))
1772 return;
1773
1774 for (latest = NULL, res = daemon->resolv_files; res; res = res->next)
1775 if (stat(res->name, &statbuf) == -1)
1776 {
1777 if (force)
1778 {
1779 res->mtime = 0;
1780 continue;
1781 }
1782
1783 if (!res->logged)
1784 my_syslog(LOG_WARNING, _("failed to access %s: %s"), res->name, strerror(errno));
1785 res->logged = 1;
1786
1787 if (res->mtime != 0)
1788 {
1789 /* existing file evaporated, force selection of the latest
1790 file even if its mtime hasn't changed since we last looked */
1791 poll_resolv(1, do_reload, now);
1792 return;
1793 }
1794 }
1795 else
1796 {
1797 res->logged = 0;
1798 if (force || (statbuf.st_mtime != res->mtime || statbuf.st_ino != res->ino))
1799 {
1800 res->mtime = statbuf.st_mtime;
1801 res->ino = statbuf.st_ino;
1802 if (difftime(statbuf.st_mtime, last_change) > 0.0)
1803 {
1804 last_change = statbuf.st_mtime;
1805 latest = res;
1806 }
1807 }
1808 }
1809
1810 if (latest)
1811 {
1812 static int warned = 0;
1813 if (reload_servers(latest->name))
1814 {
1815 my_syslog(LOG_INFO, _("reading %s"), latest->name);
1816 warned = 0;
1817 check_servers(0);
1818 if (option_bool(OPT_RELOAD) && do_reload)
1819 clear_cache_and_reload(now);
1820 }
1821 else
1822 {
1823 /* If we're delaying things, we don't call check_servers(), but
1824 reload_servers() may have deleted some servers, rendering the server_array
1825 invalid, so just rebuild that here. Once reload_servers() succeeds,
1826 we call check_servers() above, which calls build_server_array itself. */
1827 build_server_array();
1828 latest->mtime = 0;
1829 if (!warned)
1830 {
1831 my_syslog(LOG_WARNING, _("no servers found in %s, will retry"), latest->name);
1832 warned = 1;
1833 }
1834 }
1835 }
1836 }
1837
1838 void clear_cache_and_reload(time_t now)
1839 {
1840 (void)now;
1841
1842 if (daemon->port != 0)
1843 cache_reload();
1844
1845 #ifdef HAVE_DHCP
1846 if (daemon->dhcp || daemon->doing_dhcp6)
1847 {
1848 reread_dhcp();
1849 if (option_bool(OPT_ETHERS))
1850 dhcp_read_ethers();
1851 dhcp_update_configs(daemon->dhcp_conf);
1852 lease_update_from_configs();
1853 lease_update_file(now);
1854 lease_update_dns(1);
1855 }
1856 #ifdef HAVE_DHCP6
1857 else if (daemon->doing_ra)
1858 /* Not doing DHCP, so no lease system, manage
1859 alarms for ra only */
1860 send_alarm(periodic_ra(now), now);
1861 #endif
1862 #endif
1863 }
1864
1865 #ifdef HAVE_TFTP
1866 static void set_tftp_listeners(void)
1867 {
1868 int tftp = 0;
1869 struct tftp_transfer *transfer;
1870 struct listener *listener;
1871
1872 if (!option_bool(OPT_SINGLE_PORT))
1873 for (transfer = daemon->tftp_trans; transfer; transfer = transfer->next)
1874 {
1875 tftp++;
1876 poll_listen(transfer->sockfd, POLLIN);
1877 }
1878
1879 for (listener = daemon->listeners; listener; listener = listener->next)
1880 /* tftp == 0 in single-port mode. */
1881 if (tftp <= daemon->tftp_max && listener->tftpfd != -1)
1882 poll_listen(listener->tftpfd, POLLIN);
1883 }
1884 #endif
1885
1886 static void set_dns_listeners(void)
1887 {
1888 struct serverfd *serverfdp;
1889 struct listener *listener;
1890 struct randfd_list *rfl;
1891 int i;
1892
1893 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1894 poll_listen(serverfdp->fd, POLLIN);
1895
1896 for (i = 0; i < daemon->numrrand; i++)
1897 if (daemon->randomsocks[i].refcount != 0)
1898 poll_listen(daemon->randomsocks[i].fd, POLLIN);
1899
1900 /* Check overflow random sockets too. */
1901 for (rfl = daemon->rfl_poll; rfl; rfl = rfl->next)
1902 poll_listen(rfl->rfd->fd, POLLIN);
1903
1904 /* check to see if we have free tcp process slots. */
1905 for (i = daemon->max_procs - 1; i >= 0; i--)
1906 if (daemon->tcp_pids[i] == 0 && daemon->tcp_pipes[i] == -1)
1907 break;
1908
1909 for (listener = daemon->listeners; listener; listener = listener->next)
1910 {
1911 if (listener->fd != -1)
1912 poll_listen(listener->fd, POLLIN);
1913
1914 /* Only listen for TCP connections when a process slot
1915 is available. Death of a child goes through the select loop, so
1916 we don't need to explicitly arrange to wake up here,
1917 we'll be called again when a slot becomes available. */
1918 if (listener->tcpfd != -1 && i >= 0)
1919 poll_listen(listener->tcpfd, POLLIN);
1920 }
1921
1922 if (!option_bool(OPT_DEBUG))
1923 for (i = 0; i < daemon->max_procs; i++)
1924 if (daemon->tcp_pipes[i] != -1)
1925 poll_listen(daemon->tcp_pipes[i], POLLIN);
1926 }
1927
1928 static void check_dns_listeners(time_t now)
1929 {
1930 struct serverfd *serverfdp;
1931 struct listener *listener;
1932 struct randfd_list *rfl;
1933 int i;
1934
1935 /* Note that handling events here can create or destroy fds and
1936 render the result of the last poll() call invalid. Once
1937 we find an fd that needs service, do it, then return to go around the
1938 poll() loop again. This avoid really, really, wierd bugs. */
1939
1940 if (!option_bool(OPT_DEBUG))
1941 for (i = 0; i < daemon->max_procs; i++)
1942 if (daemon->tcp_pipes[i] != -1 &&
1943 poll_check(daemon->tcp_pipes[i], POLLIN | POLLHUP))
1944 {
1945 /* Races. The child process can die before we read all of the data from the
1946 pipe, or vice versa. Therefore send tcp_pids to zero when we wait() the
1947 process, and tcp_pipes to -1 and close the FD when we read the last
1948 of the data - indicated by cache_recv_insert returning zero.
1949 The order of these events is indeterminate, and both are needed
1950 to free the process slot. Once the child process has gone, poll()
1951 returns POLLHUP, not POLLIN, so have to check for both here. */
1952 if (!cache_recv_insert(now, daemon->tcp_pipes[i]))
1953 {
1954 close(daemon->tcp_pipes[i]);
1955 daemon->tcp_pipes[i] = -1;
1956 /* tcp_pipes == -1 && tcp_pids == 0 required to free slot */
1957 if (daemon->tcp_pids[i] == 0)
1958 daemon->metrics[METRIC_TCP_CONNECTIONS]--;
1959 }
1960 return;
1961 }
1962
1963 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1964 if (poll_check(serverfdp->fd, POLLIN))
1965 {
1966 reply_query(serverfdp->fd, now);
1967 return;
1968 }
1969
1970 for (i = 0; i < daemon->numrrand; i++)
1971 if (daemon->randomsocks[i].refcount != 0 &&
1972 poll_check(daemon->randomsocks[i].fd, POLLIN))
1973 {
1974 reply_query(daemon->randomsocks[i].fd, now);
1975 return;
1976 }
1977
1978 /* Check overflow random sockets too. */
1979 for (rfl = daemon->rfl_poll; rfl; rfl = rfl->next)
1980 if (poll_check(rfl->rfd->fd, POLLIN))
1981 {
1982 reply_query(rfl->rfd->fd, now);
1983 return;
1984 }
1985
1986 for (listener = daemon->listeners; listener; listener = listener->next)
1987 if (listener->fd != -1 && poll_check(listener->fd, POLLIN))
1988 {
1989 receive_query(listener, now);
1990 return;
1991 }
1992
1993 /* check to see if we have a free tcp process slot.
1994 Note that we can't assume that because we had
1995 at least one a poll() time, that we still do.
1996 There may be more waiting connections after
1997 poll() returns then free process slots. */
1998 for (i = daemon->max_procs - 1; i >= 0; i--)
1999 if (daemon->tcp_pids[i] == 0 && daemon->tcp_pipes[i] == -1)
2000 break;
2001
2002 if (i >= 0)
2003 for (listener = daemon->listeners; listener; listener = listener->next)
2004 if (listener->tcpfd != -1 && poll_check(listener->tcpfd, POLLIN))
2005 {
2006 do_tcp_connection(listener, now, i);
2007 return;
2008 }
2009 }
2010
2011 static void do_tcp_connection(struct listener *listener, time_t now, int slot)
2012 {
2013 int confd;
2014 struct irec *iface = NULL;
2015 pid_t p;
2016 union mysockaddr tcp_addr;
2017 socklen_t tcp_len = sizeof(union mysockaddr);
2018 struct server *s;
2019 int flags, auth_dns = 0;
2020 struct in_addr netmask;
2021 int pipefd[2];
2022 struct iovec tcpbuff;
2023 #ifdef HAVE_LINUX_NETWORK
2024 unsigned char a = 0;
2025 #endif
2026 netmask.s_addr = 0;
2027
2028 while ((confd = accept(listener->tcpfd, NULL, NULL)) == -1 && errno == EINTR);
2029
2030 if (confd == -1)
2031 return;
2032
2033 if (getsockname(confd, (struct sockaddr *)&tcp_addr, &tcp_len) == -1)
2034 {
2035 closeconandreturn:
2036 shutdown(confd, SHUT_RDWR);
2037 close(confd);
2038 return;
2039 }
2040
2041 /* Make sure that the interface list is up-to-date.
2042
2043 We do this here as we may need the results below, and
2044 the DNS code needs them for --interface-name stuff.
2045
2046 Multiple calls to enumerate_interfaces() per select loop are
2047 inhibited, so calls to it in the child process (which doesn't select())
2048 have no effect. This avoids two processes reading from the same
2049 netlink fd and screwing the pooch entirely.
2050 */
2051
2052 enumerate_interfaces(0);
2053
2054 if (option_bool(OPT_NOWILD) || option_bool(OPT_CLEVERBIND))
2055 {
2056 if ((iface = listener->iface))
2057 {
2058 netmask = iface->netmask;
2059 auth_dns = iface->dns_auth;
2060 }
2061 }
2062 else
2063 {
2064 int if_index, got_index = 0;
2065 char intr_name[IF_NAMESIZE];
2066
2067 /* if we can find the arrival interface, check it's one that's allowed
2068 tcp_interface() is not implemented on non-Linux platforms */
2069 if ((if_index = tcp_interface(confd, tcp_addr.sa.sa_family)) != 0 &&
2070 indextoname(listener->tcpfd, if_index, intr_name))
2071 {
2072 union all_addr addr;
2073
2074 got_index = 1;
2075
2076 if (tcp_addr.sa.sa_family == AF_INET6)
2077 addr.addr6 = tcp_addr.in6.sin6_addr;
2078 else
2079 addr.addr4 = tcp_addr.in.sin_addr;
2080
2081 if (!iface_check(tcp_addr.sa.sa_family, &addr, intr_name, &auth_dns) &&
2082 !loopback_exception(listener->tcpfd, tcp_addr.sa.sa_family, &addr, intr_name))
2083 goto closeconandreturn;
2084 }
2085
2086 /* When binding the wildcard address, try and get the
2087 netmask of the interface for localisation. */
2088 for (iface = daemon->interfaces; iface; iface = iface->next)
2089 if (sockaddr_isequal(&iface->addr, &tcp_addr))
2090 {
2091 netmask = iface->netmask;
2092 break;
2093 }
2094
2095 /* On platforms where tcp_interface() doesn't work, we rely
2096 of the presence of the local address of the connection in the
2097 interface list to check if we're accepting this connection and
2098 for its auth status. */
2099 if (!got_index)
2100 {
2101 if (!iface)
2102 goto closeconandreturn;
2103
2104 auth_dns = iface->dns_auth;
2105 }
2106 }
2107
2108 if (!option_bool(OPT_DEBUG))
2109 {
2110 /* The code in edns0.c that decorates queries with the source MAC address depends
2111 on the code in arp.c, which populates a cache with the contents of the ARP table
2112 using netlink. Since the child process can't use netlink, we pre-populate
2113 the cache with the ARP table entry for our source here, including a negative entry
2114 if there is nothing for our address in the ARP table.
2115
2116 When the edns0 code calls find_mac() in the child process, it will
2117 get the correct answer from the cache inherited from the parent
2118 without having to use netlink to consult the kernel ARP table.
2119
2120 edns0_needs_mac() simply calls find_mac if any EDNS0 options
2121 which need a MAC address are enabled. */
2122
2123 edns0_needs_mac(&tcp_addr, now);
2124
2125 if (pipe(pipefd) == -1)
2126 goto closeconandreturn; /* pipe failed */
2127
2128 if ((p = fork()) == -1)
2129 {
2130 /* fork failed */
2131 close(pipefd[0]);
2132 close(pipefd[1]);
2133 goto closeconandreturn;
2134 }
2135
2136 if (p != 0)
2137 {
2138 /* fork() done: parent side */
2139 close(pipefd[1]); /* parent needs read pipe end. */
2140
2141 #ifdef HAVE_LINUX_NETWORK
2142 /* The child process inherits the netlink socket,
2143 which it never uses, but when the parent (us)
2144 uses it in the future, the answer may go to the
2145 child, resulting in the parent blocking
2146 forever awaiting the result. To avoid this
2147 the child closes the netlink socket, but there's
2148 a nasty race, since the parent may use netlink
2149 before the child has done the close.
2150
2151 To avoid this, the parent blocks here until a
2152 single byte comes back up the pipe, which
2153 is sent by the child after it has closed the
2154 netlink socket. */
2155
2156 read_write(pipefd[0], &a, 1, RW_READ);
2157 #endif
2158
2159
2160 daemon->tcp_pids[slot] = p;
2161 daemon->tcp_pipes[slot] = pipefd[0];
2162 daemon->metrics[METRIC_TCP_CONNECTIONS]++;
2163 if (daemon->metrics[METRIC_TCP_CONNECTIONS] > daemon->max_procs_used)
2164 daemon->max_procs_used = daemon->metrics[METRIC_TCP_CONNECTIONS];
2165
2166 close(confd);
2167
2168 /* The child can use up to TCP_MAX_QUERIES ids, so skip that many. */
2169 daemon->log_id += TCP_MAX_QUERIES;
2170 #ifdef HAVE_DNSSEC
2171 /* It can do more if making DNSSEC queries too. */
2172 if (option_bool(OPT_DNSSEC_VALID))
2173 daemon->log_id += daemon->limit[LIMIT_WORK];
2174 #endif
2175
2176 return;
2177 }
2178
2179 /* Arrange for SIGALRM after CHILD_LIFETIME seconds to
2180 terminate the process. */
2181 #ifdef HAVE_LINUX_NETWORK
2182 /* See comment above re: netlink socket. */
2183 close(daemon->netlinkfd);
2184 read_write(pipefd[1], &a, 1, RW_WRITE);
2185 #endif
2186 alarm(CHILD_LIFETIME);
2187 close(pipefd[0]); /* close read end in child. */
2188 daemon->pipe_to_parent = pipefd[1];
2189 }
2190
2191 /* The connected socket inherits non-blocking
2192 attribute from the listening socket.
2193 Reset that here. */
2194 if ((flags = fcntl(confd, F_GETFL, 0)) != -1)
2195 while(retry_send(fcntl(confd, F_SETFL, flags & ~O_NONBLOCK)));
2196
2197 tcp_request(confd, now, &tcpbuff, &tcp_addr, netmask, auth_dns);
2198 free(tcpbuff.iov_base);
2199
2200 for (s = daemon->servers; s; s = s->next)
2201 if (s->tcpfd != -1)
2202 {
2203 shutdown(s->tcpfd, SHUT_RDWR);
2204 close(s->tcpfd);
2205 s->tcpfd = -1;
2206 }
2207
2208 if (!option_bool(OPT_DEBUG))
2209 {
2210 #ifdef HAVE_DNSSEC
2211 cache_update_hwm(); /* Sneak out possibly updated crypto HWM values. */
2212 #endif
2213
2214 close(daemon->pipe_to_parent);
2215 flush_log();
2216 _exit(0);
2217 }
2218 }
2219
2220
2221 #ifdef HAVE_DNSSEC
2222 /* If a DNSSEC query over UDP returns a truncated answer,
2223 we swap to the TCP path. This routine is responsible for forking
2224 the required process, the child then calls tcp_key_recurse() and
2225 returns the result of the validation through the pipe to the parent
2226 (which has also primed the cache with the relevant DS and DNSKEY records).
2227 If we're in debug mode, don't fork and return the result directly, otherwise
2228 return STAT_ASYNC. The UDP validation process will restart when
2229 cache_recv_insert() calls pop_and_retry_query() after the result
2230 arrives via the pipe to the parent. */
2231 int swap_to_tcp(struct frec *forward, time_t now, int status, struct dns_header *header,
2232 ssize_t *plen, char *name, int class, struct server *server, int *keycount, int *validatecount)
2233 {
2234 struct server *s;
2235
2236 if (!option_bool(OPT_DEBUG))
2237 {
2238 pid_t p;
2239 int i, pipefd[2];
2240 #ifdef HAVE_LINUX_NETWORK
2241 unsigned char a = 0;
2242 #endif
2243
2244 /* check to see if we have a free tcp process slot. */
2245 for (i = daemon->max_procs - 1; i >= 0; i--)
2246 if (daemon->tcp_pids[i] == 0 && daemon->tcp_pipes[i] == -1)
2247 break;
2248
2249 /* No slots or no pipe */
2250 if (i < 0 || pipe(pipefd) != 0)
2251 return STAT_ABANDONED;
2252
2253 if ((p = fork()) != 0)
2254 {
2255 close(pipefd[1]); /* parent needs read pipe end. */
2256 if (p == -1)
2257 {
2258 /* fork() failed */
2259 close(pipefd[0]);
2260 return STAT_ABANDONED;
2261 }
2262
2263 #ifdef HAVE_LINUX_NETWORK
2264 /* The child process inherits the netlink socket,
2265 which it never uses, but when the parent (us)
2266 uses it in the future, the answer may go to the
2267 child, resulting in the parent blocking
2268 forever awaiting the result. To avoid this
2269 the child closes the netlink socket, but there's
2270 a nasty race, since the parent may use netlink
2271 before the child has done the close.
2272
2273 To avoid this, the parent blocks here until a
2274 single byte comes back up the pipe, which
2275 is sent by the child after it has closed the
2276 netlink socket. */
2277 read_write(pipefd[0], &a, 1, RW_READ);
2278 #endif
2279
2280 /* i holds index of free slot */
2281 daemon->tcp_pids[i] = p;
2282 daemon->tcp_pipes[i] = pipefd[0];
2283 daemon->metrics[METRIC_TCP_CONNECTIONS]++;
2284 if (daemon->metrics[METRIC_TCP_CONNECTIONS] > daemon->max_procs_used)
2285 daemon->max_procs_used = daemon->metrics[METRIC_TCP_CONNECTIONS];
2286
2287 /* child can use a maximum of this many log serials. */
2288 daemon->log_id += daemon->limit[LIMIT_WORK];
2289
2290 /* tell the caller we've forked. */
2291 return STAT_ASYNC;
2292 }
2293 else
2294 {
2295 /* child starts here. */
2296 #ifdef HAVE_LINUX_NETWORK
2297 /* See comment above re: netlink socket. */
2298 close(daemon->netlinkfd);
2299 read_write(pipefd[1], &a, 1, RW_WRITE);
2300 #endif
2301 alarm(CHILD_LIFETIME);
2302 close(pipefd[0]); /* close read end in child. */
2303 daemon->pipe_to_parent = pipefd[1];
2304 daemon->forward_to_tcp = forward;
2305 daemon->header_to_tcp = header;
2306 daemon->plen_to_tcp = *plen;
2307 }
2308 }
2309
2310 status = tcp_from_udp(now, status, header, plen, class, name, server, keycount, validatecount);
2311
2312 /* close upstream connections. */
2313 for (s = daemon->servers; s; s = s->next)
2314 if (s->tcpfd != -1)
2315 {
2316 shutdown(s->tcpfd, SHUT_RDWR);
2317 close(s->tcpfd);
2318 s->tcpfd = -1;
2319 }
2320
2321 if (!option_bool(OPT_DEBUG))
2322 {
2323 unsigned char op = PIPE_OP_RESULT;
2324
2325 /* tell our parent we're done, and what the result was then exit. */
2326 read_write(daemon->pipe_to_parent, &op, sizeof(op), RW_WRITE);
2327 read_write(daemon->pipe_to_parent, (unsigned char *)&status, sizeof(status), RW_WRITE);
2328 read_write(daemon->pipe_to_parent, (unsigned char *)plen, sizeof(*plen), RW_WRITE);
2329 read_write(daemon->pipe_to_parent, (unsigned char *)header, *plen, RW_WRITE);
2330 read_write(daemon->pipe_to_parent, (unsigned char *)&forward, sizeof(forward), RW_WRITE);
2331 read_write(daemon->pipe_to_parent, (unsigned char *)&forward->uid, sizeof(forward->uid), RW_WRITE);
2332 read_write(daemon->pipe_to_parent, (unsigned char *)keycount, sizeof(*keycount), RW_WRITE);
2333 read_write(daemon->pipe_to_parent, (unsigned char *)&keycount, sizeof(keycount), RW_WRITE);
2334 read_write(daemon->pipe_to_parent, (unsigned char *)validatecount, sizeof(*validatecount), RW_WRITE);
2335 read_write(daemon->pipe_to_parent, (unsigned char *)&validatecount, sizeof(validatecount), RW_WRITE);
2336
2337 cache_update_hwm(); /* Sneak out possibly updated crypto HWM values. */
2338
2339 close(daemon->pipe_to_parent);
2340
2341 flush_log();
2342 _exit(0);
2343 }
2344
2345 /* path for debug mode. */
2346 return status;
2347 }
2348 #endif
2349
2350
2351 #ifdef HAVE_DHCP
2352 int make_icmp_sock(void)
2353 {
2354 int fd;
2355 int zeroopt = 0;
2356
2357 if ((fd = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
2358 {
2359 if (!fix_fd(fd) ||
2360 setsockopt(fd, SOL_SOCKET, SO_DONTROUTE, &zeroopt, sizeof(zeroopt)) == -1)
2361 {
2362 close(fd);
2363 fd = -1;
2364 }
2365 }
2366
2367 return fd;
2368 }
2369
2370 int icmp_ping(struct in_addr addr)
2371 {
2372 /* Try and get an ICMP echo from a machine. */
2373
2374 int fd;
2375 struct sockaddr_in saddr;
2376 struct {
2377 struct ip ip;
2378 struct icmp icmp;
2379 } packet;
2380 unsigned short id = rand16();
2381 unsigned int i, j;
2382 int gotreply = 0;
2383
2384 #if defined(HAVE_LINUX_NETWORK) || defined (HAVE_SOLARIS_NETWORK)
2385 if ((fd = make_icmp_sock()) == -1)
2386 return 0;
2387 #else
2388 int opt = 2000;
2389 fd = daemon->dhcp_icmp_fd;
2390 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
2391 #endif
2392
2393 saddr.sin_family = AF_INET;
2394 saddr.sin_port = 0;
2395 saddr.sin_addr = addr;
2396 #ifdef HAVE_SOCKADDR_SA_LEN
2397 saddr.sin_len = sizeof(struct sockaddr_in);
2398 #endif
2399
2400 memset(&packet.icmp, 0, sizeof(packet.icmp));
2401 packet.icmp.icmp_type = ICMP_ECHO;
2402 packet.icmp.icmp_id = id;
2403 for (j = 0, i = 0; i < sizeof(struct icmp) / 2; i++)
2404 j += ((u16 *)&packet.icmp)[i];
2405 while (j>>16)
2406 j = (j & 0xffff) + (j >> 16);
2407 packet.icmp.icmp_cksum = (j == 0xffff) ? j : ~j;
2408
2409 while (retry_send(sendto(fd, (char *)&packet.icmp, sizeof(struct icmp), 0,
2410 (struct sockaddr *)&saddr, sizeof(saddr))));
2411
2412 gotreply = delay_dhcp(dnsmasq_time(), PING_WAIT, fd, addr.s_addr, id);
2413
2414 #if defined(HAVE_LINUX_NETWORK) || defined(HAVE_SOLARIS_NETWORK)
2415 close(fd);
2416 #else
2417 opt = 1;
2418 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
2419 #endif
2420
2421 return gotreply;
2422 }
2423
2424 int delay_dhcp(time_t start, int sec, int fd, uint32_t addr, unsigned short id)
2425 {
2426 /* Delay processing DHCP packets for "sec" seconds counting from "start".
2427 If "fd" is not -1 it will stop waiting if an ICMP echo reply is received
2428 from "addr" with ICMP ID "id" and return 1 */
2429
2430 /* Note that whilst waiting, we check for
2431 (and service) events on the DNS and TFTP sockets, (so doing that
2432 better not use any resources our caller has in use...)
2433 but we remain deaf to signals or further DHCP packets. */
2434
2435 /* There can be a problem using dnsmasq_time() to end the loop, since
2436 it's not monotonic, and can go backwards if the system clock is
2437 tweaked, leading to the code getting stuck in this loop and
2438 ignoring DHCP requests. To fix this, we check to see if select returned
2439 as a result of a timeout rather than a socket becoming available. We
2440 only allow this to happen as many times as it takes to get to the wait time
2441 in quarter-second chunks. This provides a fallback way to end loop. */
2442
2443 int rc, timeout_count;
2444 time_t now;
2445
2446 for (now = dnsmasq_time(), timeout_count = 0;
2447 (difftime(now, start) <= (float)sec) && (timeout_count < sec * 4);)
2448 {
2449 poll_reset();
2450 if (fd != -1)
2451 poll_listen(fd, POLLIN);
2452 if (daemon->port != 0)
2453 set_dns_listeners();
2454 #ifdef HAVE_TFTP
2455 set_tftp_listeners();
2456 #endif
2457 set_log_writer();
2458
2459 #ifdef HAVE_DHCP6
2460 if (daemon->doing_ra)
2461 poll_listen(daemon->icmp6fd, POLLIN);
2462 #endif
2463
2464 rc = do_poll(250);
2465
2466 if (rc < 0)
2467 continue;
2468 else if (rc == 0)
2469 timeout_count++;
2470
2471 now = dnsmasq_time();
2472
2473 check_log_writer(0);
2474 if (daemon->port != 0)
2475 check_dns_listeners(now);
2476
2477 #ifdef HAVE_DHCP6
2478 if (daemon->doing_ra && poll_check(daemon->icmp6fd, POLLIN))
2479 icmp6_packet(now);
2480 #endif
2481
2482 #ifdef HAVE_TFTP
2483 check_tftp_listeners(now);
2484 #endif
2485
2486 if (fd != -1)
2487 {
2488 struct {
2489 struct ip ip;
2490 struct icmp icmp;
2491 } packet;
2492 struct sockaddr_in faddr;
2493 socklen_t len = sizeof(faddr);
2494
2495 if (poll_check(fd, POLLIN) &&
2496 recvfrom(fd, &packet, sizeof(packet), 0, (struct sockaddr *)&faddr, &len) == sizeof(packet) &&
2497 addr == faddr.sin_addr.s_addr &&
2498 packet.icmp.icmp_type == ICMP_ECHOREPLY &&
2499 packet.icmp.icmp_seq == 0 &&
2500 packet.icmp.icmp_id == id)
2501 return 1;
2502 }
2503 }
2504
2505 return 0;
2506 }
2507 #endif /* HAVE_DHCP */
2508
2509