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