Tomato 1.26 beta(1766)
[tomato.git] / release / src / router / dnsmasq / src / dnsmasq.c
blob5bf19013cf8819ba1e0eba75fd3198b1197f88ae
1 /* dnsmasq is Copyright (c) 2000-2009 Simon Kelley
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; version 2 dated June, 1991, or
6 (at your option) version 3 dated 29 June, 2007.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 #include "dnsmasq.h"
19 // zzz
20 #include <asm/unistd.h>
21 _syscall5(int, prctl, int, a, int, b, int, c, int, d, int, e);
23 struct daemon *daemon;
25 static char *compile_opts =
26 #ifndef HAVE_IPV6
27 "no-"
28 #endif
29 "IPv6 "
30 #ifndef HAVE_GETOPT_LONG
31 "no-"
32 #endif
33 "GNU-getopt "
34 #ifdef HAVE_BROKEN_RTC
35 "no-RTC "
36 #endif
37 #ifdef NO_FORK
38 "no-MMU "
39 #endif
40 #ifndef HAVE_DBUS
41 "no-"
42 #endif
43 "DBus "
44 #ifndef LOCALEDIR
45 "no-"
46 #endif
47 "I18N "
48 #ifndef HAVE_DHCP
49 "no-"
50 #endif
51 "DHCP "
52 #ifndef HAVE_TFTP
53 "no-"
54 #endif
55 "TFTP";
57 static volatile pid_t pid = 0;
58 static volatile int pipewrite;
60 static int set_dns_listeners(time_t now, fd_set *set, int *maxfdp);
61 static void check_dns_listeners(fd_set *set, time_t now);
62 static void sig_handler(int sig);
63 static void async_event(int pipe, time_t now);
64 static void fatal_event(struct event_desc *ev);
65 static void poll_resolv(void);
67 void tomato_helper(time_t now); // zzz
68 void flush_lease_file(time_t now); // zzz
70 int main (int argc, char **argv)
72 int bind_fallback = 0;
73 time_t now;
74 struct sigaction sigact;
75 struct iname *if_tmp;
76 int piperead, pipefd[2], err_pipe[2];
77 struct passwd *ent_pw = NULL;
78 #ifdef HAVE_DHCP
79 uid_t script_uid = 0;
80 gid_t script_gid = 0;
81 #endif
82 struct group *gp = NULL;
83 long i, max_fd = sysconf(_SC_OPEN_MAX);
84 char *baduser = NULL;
85 int log_err;
86 #if defined(HAVE_LINUX_NETWORK)
87 cap_user_header_t hdr = NULL;
88 cap_user_data_t data = NULL;
89 #endif
91 #ifdef LOCALEDIR
92 setlocale(LC_ALL, "");
93 bindtextdomain("dnsmasq", LOCALEDIR);
94 textdomain("dnsmasq");
95 #endif
97 sigact.sa_handler = sig_handler;
98 sigact.sa_flags = 0;
99 sigemptyset(&sigact.sa_mask);
100 sigaction(SIGUSR1, &sigact, NULL);
101 sigaction(SIGUSR2, &sigact, NULL);
102 sigaction(SIGHUP, &sigact, NULL);
103 sigaction(SIGTERM, &sigact, NULL);
104 sigaction(SIGALRM, &sigact, NULL);
105 sigaction(SIGCHLD, &sigact, NULL);
107 /* ignore SIGPIPE */
108 sigact.sa_handler = SIG_IGN;
109 sigaction(SIGPIPE, &sigact, NULL);
111 umask(022); /* known umask, create leases and pid files as 0644 */
113 read_opts(argc, argv, compile_opts);
115 if (daemon->edns_pktsz < PACKETSZ)
116 daemon->edns_pktsz = PACKETSZ;
117 daemon->packet_buff_sz = daemon->edns_pktsz > DNSMASQ_PACKETSZ ?
118 daemon->edns_pktsz : DNSMASQ_PACKETSZ;
119 daemon->packet = safe_malloc(daemon->packet_buff_sz);
121 #ifdef HAVE_DHCP
122 if (!daemon->lease_file)
124 if (daemon->dhcp)
125 daemon->lease_file = LEASEFILE;
127 #endif
129 /* Close any file descriptors we inherited apart from std{in|out|err} */
130 for (i = 0; i < max_fd; i++)
131 if (i != STDOUT_FILENO && i != STDERR_FILENO && i != STDIN_FILENO)
132 close(i);
134 #ifdef HAVE_LINUX_NETWORK
135 netlink_init();
136 #elif !(defined(IP_RECVDSTADDR) && \
137 defined(IP_RECVIF) && \
138 defined(IP_SENDSRCADDR))
139 if (!(daemon->options & OPT_NOWILD))
141 bind_fallback = 1;
142 daemon->options |= OPT_NOWILD;
144 #endif
146 #ifndef HAVE_TFTP
147 if (daemon->options & OPT_TFTP)
148 die(_("TFTP server not available: set HAVE_TFTP in src/config.h"), NULL, EC_BADCONF);
149 #endif
151 #ifdef HAVE_SOLARIS_NETWORK
152 if (daemon->max_logs != 0)
153 die(_("asychronous logging is not available under Solaris"), NULL, EC_BADCONF);
154 #endif
156 rand_init();
158 now = dnsmasq_time();
160 #ifdef HAVE_DHCP
161 if (daemon->dhcp)
163 /* Note that order matters here, we must call lease_init before
164 creating any file descriptors which shouldn't be leaked
165 to the lease-script init process. */
166 lease_init(now);
167 dhcp_init();
169 #endif
171 if (!enumerate_interfaces())
172 die(_("failed to find list of interfaces: %s"), NULL, EC_MISC);
174 if (daemon->options & OPT_NOWILD)
176 daemon->listeners = create_bound_listeners();
178 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
179 if (if_tmp->name && !if_tmp->used)
180 die(_("unknown interface %s"), if_tmp->name, EC_BADNET);
182 for (if_tmp = daemon->if_addrs; if_tmp; if_tmp = if_tmp->next)
183 if (!if_tmp->used)
185 prettyprint_addr(&if_tmp->addr, daemon->namebuff);
186 die(_("no interface with address %s"), daemon->namebuff, EC_BADNET);
189 else if ((daemon->port != 0 || (daemon->options & OPT_TFTP)) &&
190 !(daemon->listeners = create_wildcard_listeners()))
191 die(_("failed to create listening socket: %s"), NULL, EC_BADNET);
193 if (daemon->port != 0)
194 cache_init();
196 if (daemon->options & OPT_DBUS)
197 #ifdef HAVE_DBUS
199 char *err;
200 daemon->dbus = NULL;
201 daemon->watches = NULL;
202 if ((err = dbus_init()))
203 die(_("DBus error: %s"), err, EC_MISC);
205 #else
206 die(_("DBus not available: set HAVE_DBUS in src/config.h"), NULL, EC_BADCONF);
207 #endif
209 if (daemon->port != 0)
210 pre_allocate_sfds();
212 #ifdef HAVE_DHCP
213 /* Note getpwnam returns static storage */
214 if (daemon->dhcp && daemon->lease_change_command && daemon->scriptuser)
216 if ((ent_pw = getpwnam(daemon->scriptuser)))
218 script_uid = ent_pw->pw_uid;
219 script_gid = ent_pw->pw_gid;
221 else
222 baduser = daemon->scriptuser;
224 #endif
226 if (daemon->username && !(ent_pw = getpwnam(daemon->username)))
227 baduser = daemon->username;
228 else if (daemon->groupname && !(gp = getgrnam(daemon->groupname)))
229 baduser = daemon->groupname;
231 if (baduser)
232 die(_("unknown user or group: %s"), baduser, EC_BADCONF);
234 /* implement group defaults, "dip" if available, or group associated with uid */
235 if (!daemon->group_set && !gp)
237 if (!(gp = getgrnam(CHGRP)) && ent_pw)
238 gp = getgrgid(ent_pw->pw_gid);
240 /* for error message */
241 if (gp)
242 daemon->groupname = gp->gr_name;
245 #if defined(HAVE_LINUX_NETWORK)
246 /* determine capability API version here, while we can still
247 call safe_malloc */
248 if (ent_pw && ent_pw->pw_uid != 0)
250 int capsize = 1; /* for header version 1 */
251 hdr = safe_malloc(sizeof(*hdr));
253 /* find version supported by kernel */
254 memset(hdr, 0, sizeof(*hdr));
255 capget(hdr, NULL);
257 if (hdr->version != LINUX_CAPABILITY_VERSION_1)
259 /* if unknown version, use largest supported version (3) */
260 if (hdr->version != LINUX_CAPABILITY_VERSION_2)
261 hdr->version = LINUX_CAPABILITY_VERSION_3;
262 capsize = 2;
265 data = safe_malloc(sizeof(*data) * capsize);
266 memset(data, 0, sizeof(*data) * capsize);
268 #endif
270 /* Use a pipe to carry signals and other events back to the event loop
271 in a race-free manner and another to carry errors to daemon-invoking process */
272 safe_pipe(pipefd, 1);
274 piperead = pipefd[0];
275 pipewrite = pipefd[1];
276 /* prime the pipe to load stuff first time. */
277 send_event(pipewrite, EVENT_RELOAD, 0);
279 err_pipe[1] = -1;
281 if (!(daemon->options & OPT_DEBUG))
283 int nullfd;
285 /* The following code "daemonizes" the process.
286 See Stevens section 12.4 */
288 if (chdir("/") != 0)
289 die(_("cannot chdir to filesystem root: %s"), NULL, EC_MISC);
291 #ifndef NO_FORK
292 if (!(daemon->options & OPT_NO_FORK))
294 pid_t pid;
296 /* pipe to carry errors back to original process.
297 When startup is complete we close this and the process terminates. */
298 safe_pipe(err_pipe, 0);
300 if ((pid = fork()) == -1)
301 /* fd == -1 since we've not forked, never returns. */
302 send_event(-1, EVENT_FORK_ERR, errno);
304 if (pid != 0)
306 struct event_desc ev;
308 /* close our copy of write-end */
309 close(err_pipe[1]);
311 /* check for errors after the fork */
312 if (read_write(err_pipe[0], (unsigned char *)&ev, sizeof(ev), 1))
313 fatal_event(&ev);
315 _exit(EC_GOOD);
318 close(err_pipe[0]);
320 /* NO calls to die() from here on. */
322 setsid();
324 if ((pid = fork()) == -1)
325 send_event(err_pipe[1], EVENT_FORK_ERR, errno);
327 if (pid != 0)
328 _exit(0);
330 #endif
332 /* write pidfile _after_ forking ! */
333 if (daemon->runfile)
335 FILE *pidfile;
337 /* only complain if started as root */
338 if ((pidfile = fopen(daemon->runfile, "w")))
340 fprintf(pidfile, "%d\n", (int) getpid());
341 fclose(pidfile);
343 else if (getuid() == 0)
345 send_event(err_pipe[1], EVENT_PIDFILE, errno);
346 _exit(0);
350 /* open stdout etc to /dev/null */
351 nullfd = open("/dev/null", O_RDWR);
352 dup2(nullfd, STDOUT_FILENO);
353 dup2(nullfd, STDERR_FILENO);
354 dup2(nullfd, STDIN_FILENO);
355 close(nullfd);
358 log_err = log_start(ent_pw, err_pipe[1]);
360 /* if we are to run scripts, we need to fork a helper before dropping root. */
361 daemon->helperfd = -1;
362 #if defined(HAVE_DHCP) && !defined(NO_FORK)
363 if (daemon->dhcp && daemon->lease_change_command)
364 daemon->helperfd = create_helper(pipewrite, err_pipe[1], script_uid, script_gid, max_fd);
365 #endif
367 if (!(daemon->options & OPT_DEBUG) && getuid() == 0)
369 int bad_capabilities = 0;
370 gid_t dummy;
372 /* remove all supplimentary groups */
373 if (gp &&
374 (setgroups(0, &dummy) == -1 ||
375 setgid(gp->gr_gid) == -1))
377 send_event(err_pipe[1], EVENT_GROUP_ERR, errno);
378 _exit(0);
381 if (ent_pw && ent_pw->pw_uid != 0)
383 #if defined(HAVE_LINUX_NETWORK)
384 /* On linux, we keep CAP_NETADMIN (for ARP-injection) and
385 CAP_NET_RAW (for icmp) if we're doing dhcp */
386 data->effective = data->permitted = data->inheritable =
387 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID);
389 /* Tell kernel to not clear capabilities when dropping root */
390 if (capset(hdr, data) == -1 || prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1)
391 bad_capabilities = errno;
393 #elif defined(HAVE_SOLARIS_NETWORK)
394 /* http://developers.sun.com/solaris/articles/program_privileges.html */
395 priv_set_t *priv_set;
397 if (!(priv_set = priv_str_to_set("basic", ",", NULL)) ||
398 priv_addset(priv_set, PRIV_NET_ICMPACCESS) == -1 ||
399 priv_addset(priv_set, PRIV_SYS_NET_CONFIG) == -1)
400 bad_capabilities = errno;
402 if (priv_set && bad_capabilities == 0)
404 priv_inverse(priv_set);
406 if (setppriv(PRIV_OFF, PRIV_LIMIT, priv_set) == -1)
407 bad_capabilities = errno;
410 if (priv_set)
411 priv_freeset(priv_set);
413 #endif
415 if (bad_capabilities != 0)
417 send_event(err_pipe[1], EVENT_CAP_ERR, bad_capabilities);
418 _exit(0);
421 /* finally drop root */
422 if (setuid(ent_pw->pw_uid) == -1)
424 send_event(err_pipe[1], EVENT_USER_ERR, errno);
425 _exit(0);
428 #ifdef HAVE_LINUX_NETWORK
429 data->effective = data->permitted =
430 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW);
431 data->inheritable = 0;
433 /* lose the setuid and setgid capbilities */
434 if (capset(hdr, data) == -1)
436 send_event(err_pipe[1], EVENT_CAP_ERR, errno);
437 _exit(0);
439 #endif
444 #ifdef HAVE_LINUX_NETWORK
445 if (daemon->options & OPT_DEBUG)
446 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
447 #endif
449 if (daemon->port == 0)
450 my_syslog(LOG_INFO, _("started, version %s DNS disabled"), VERSION);
451 else if (daemon->cachesize != 0)
452 my_syslog(LOG_INFO, _("started, version %s cachesize %d"), VERSION, daemon->cachesize);
453 else
454 my_syslog(LOG_INFO, _("started, version %s cache disabled"), VERSION);
456 my_syslog(LOG_INFO, _("compile time options: %s"), compile_opts);
458 #ifdef HAVE_DBUS
459 if (daemon->options & OPT_DBUS)
461 if (daemon->dbus)
462 my_syslog(LOG_INFO, _("DBus support enabled: connected to system bus"));
463 else
464 my_syslog(LOG_INFO, _("DBus support enabled: bus connection pending"));
466 #endif
468 if (log_err != 0)
469 my_syslog(LOG_WARNING, _("warning: failed to change owner of %s: %s"),
470 daemon->log_file, strerror(log_err));
472 if (bind_fallback)
473 my_syslog(LOG_WARNING, _("setting --bind-interfaces option because of OS limitations"));
475 if (!(daemon->options & OPT_NOWILD))
476 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
477 if (if_tmp->name && !if_tmp->used)
478 my_syslog(LOG_WARNING, _("warning: interface %s does not currently exist"), if_tmp->name);
480 if (daemon->port != 0 && (daemon->options & OPT_NO_RESOLV))
482 if (daemon->resolv_files && !daemon->resolv_files->is_default)
483 my_syslog(LOG_WARNING, _("warning: ignoring resolv-file flag because no-resolv is set"));
484 daemon->resolv_files = NULL;
485 if (!daemon->servers)
486 my_syslog(LOG_WARNING, _("warning: no upstream servers configured"));
489 if (daemon->max_logs != 0)
490 my_syslog(LOG_INFO, _("asynchronous logging enabled, queue limit is %d messages"), daemon->max_logs);
492 #ifdef HAVE_DHCP
493 if (daemon->dhcp)
495 struct dhcp_context *dhcp_tmp;
497 for (dhcp_tmp = daemon->dhcp; dhcp_tmp; dhcp_tmp = dhcp_tmp->next)
499 prettyprint_time(daemon->dhcp_buff2, dhcp_tmp->lease_time);
500 strcpy(daemon->dhcp_buff, inet_ntoa(dhcp_tmp->start));
501 my_syslog(MS_DHCP | LOG_INFO,
502 (dhcp_tmp->flags & CONTEXT_STATIC) ?
503 _("DHCP, static leases only on %.0s%s, lease time %s") :
504 (dhcp_tmp->flags & CONTEXT_PROXY) ?
505 _("DHCP, proxy on subnet %.0s%s%.0s") :
506 _("DHCP, IP range %s -- %s, lease time %s"),
507 daemon->dhcp_buff, inet_ntoa(dhcp_tmp->end), daemon->dhcp_buff2);
510 #endif
512 #ifdef HAVE_TFTP
513 if (daemon->options & OPT_TFTP)
515 #ifdef FD_SETSIZE
516 if (FD_SETSIZE < (unsigned)max_fd)
517 max_fd = FD_SETSIZE;
518 #endif
520 my_syslog(MS_TFTP | LOG_INFO, "TFTP %s%s %s",
521 daemon->tftp_prefix ? _("root is ") : _("enabled"),
522 daemon->tftp_prefix ? daemon->tftp_prefix: "",
523 daemon->options & OPT_TFTP_SECURE ? _("secure mode") : "");
525 /* This is a guess, it assumes that for small limits,
526 disjoint files might be served, but for large limits,
527 a single file will be sent to may clients (the file only needs
528 one fd). */
530 max_fd -= 30; /* use other than TFTP */
532 if (max_fd < 0)
533 max_fd = 5;
534 else if (max_fd < 100)
535 max_fd = max_fd/2;
536 else
537 max_fd = max_fd - 20;
539 /* if we have to use a limited range of ports,
540 that will limit the number of transfers */
541 if (daemon->start_tftp_port != 0 &&
542 daemon->end_tftp_port - daemon->start_tftp_port + 1 < max_fd)
543 max_fd = daemon->end_tftp_port - daemon->start_tftp_port + 1;
545 if (daemon->tftp_max > max_fd)
547 daemon->tftp_max = max_fd;
548 my_syslog(MS_TFTP | LOG_WARNING,
549 _("restricting maximum simultaneous TFTP transfers to %d"),
550 daemon->tftp_max);
553 #endif
555 /* finished start-up - release original process */
556 if (err_pipe[1] != -1)
557 close(err_pipe[1]);
559 if (daemon->port != 0)
560 check_servers();
562 pid = getpid();
564 while (1)
566 int maxfd = -1;
567 struct timeval t, *tp = NULL;
568 fd_set rset, wset, eset;
570 FD_ZERO(&rset);
571 FD_ZERO(&wset);
572 FD_ZERO(&eset);
574 /* if we are out of resources, find how long we have to wait
575 for some to come free, we'll loop around then and restart
576 listening for queries */
577 if ((t.tv_sec = set_dns_listeners(now, &rset, &maxfd)) != 0)
579 t.tv_usec = 0;
580 tp = &t;
583 /* Whilst polling for the dbus, or doing a tftp transfer, wake every quarter second */
584 if (daemon->tftp_trans ||
585 ((daemon->options & OPT_DBUS) && !daemon->dbus))
587 t.tv_sec = 0;
588 t.tv_usec = 250000;
589 tp = &t;
592 #ifdef HAVE_DBUS
593 set_dbus_listeners(&maxfd, &rset, &wset, &eset);
594 #endif
596 #ifdef HAVE_DHCP
597 if (daemon->dhcp)
599 FD_SET(daemon->dhcpfd, &rset);
600 bump_maxfd(daemon->dhcpfd, &maxfd);
602 #endif
604 #ifdef HAVE_LINUX_NETWORK
605 FD_SET(daemon->netlinkfd, &rset);
606 bump_maxfd(daemon->netlinkfd, &maxfd);
607 #endif
609 FD_SET(piperead, &rset);
610 bump_maxfd(piperead, &maxfd);
612 #ifdef HAVE_DHCP
613 # ifndef NO_FORK
614 while (helper_buf_empty() && do_script_run(now));
616 if (!helper_buf_empty())
618 FD_SET(daemon->helperfd, &wset);
619 bump_maxfd(daemon->helperfd, &maxfd);
621 # else
622 /* need this for other side-effects */
623 while (do_script_run(now));
624 # endif
625 #endif
627 /* must do this just before select(), when we know no
628 more calls to my_syslog() can occur */
629 set_log_writer(&wset, &maxfd);
631 if (select(maxfd+1, &rset, &wset, &eset, tp) < 0)
633 /* otherwise undefined after error */
634 FD_ZERO(&rset); FD_ZERO(&wset); FD_ZERO(&eset);
637 now = dnsmasq_time();
639 check_log_writer(&wset);
641 /* Check for changes to resolv files once per second max. */
642 /* Don't go silent for long periods if the clock goes backwards. */
643 if (daemon->last_resolv == 0 ||
644 difftime(now, daemon->last_resolv) > 1.0 ||
645 difftime(now, daemon->last_resolv) < -1.0)
647 daemon->last_resolv = now;
649 if (daemon->port != 0 && !(daemon->options & OPT_NO_POLL))
650 poll_resolv();
653 if (FD_ISSET(piperead, &rset))
654 async_event(piperead, now);
656 #ifdef HAVE_LINUX_NETWORK
657 if (FD_ISSET(daemon->netlinkfd, &rset))
658 netlink_multicast();
659 #endif
661 #ifdef HAVE_DBUS
662 /* if we didn't create a DBus connection, retry now. */
663 if ((daemon->options & OPT_DBUS) && !daemon->dbus)
665 char *err;
666 if ((err = dbus_init()))
667 my_syslog(LOG_WARNING, _("DBus error: %s"), err);
668 if (daemon->dbus)
669 my_syslog(LOG_INFO, _("connected to system DBus"));
671 check_dbus_listeners(&rset, &wset, &eset);
672 #endif
674 check_dns_listeners(&rset, now);
676 #ifdef HAVE_TFTP
677 check_tftp_listeners(&rset, now);
678 #endif
680 #ifdef HAVE_DHCP
681 if (daemon->dhcp && FD_ISSET(daemon->dhcpfd, &rset))
682 dhcp_packet(now);
684 # ifndef NO_FORK
685 if (daemon->helperfd != -1 && FD_ISSET(daemon->helperfd, &wset))
686 helper_write();
687 # endif
688 #endif
693 static void sig_handler(int sig)
695 if (pid == 0)
697 /* ignore anything other than TERM during startup
698 and in helper proc. (helper ignore TERM too) */
699 if (sig == SIGTERM)
700 exit(EC_MISC);
702 else if (pid != getpid())
704 /* alarm is used to kill TCP children after a fixed time. */
705 if (sig == SIGALRM)
706 _exit(0);
708 else
710 /* master process */
711 int event, errsave = errno;
713 if (sig == SIGHUP)
714 event = EVENT_RELOAD;
715 else if (sig == SIGCHLD)
716 event = EVENT_CHILD;
717 else if (sig == SIGALRM)
718 event = EVENT_ALARM;
719 else if (sig == SIGTERM)
720 event = EVENT_TERM;
721 else if (sig == SIGUSR1)
722 event = EVENT_DUMP;
723 else if (sig == SIGUSR2)
724 event = EVENT_REOPEN;
725 else
726 return;
728 send_event(pipewrite, event, 0);
729 errno = errsave;
733 void send_event(int fd, int event, int data)
735 struct event_desc ev;
737 ev.event = event;
738 ev.data = data;
740 /* error pipe, debug mode. */
741 if (fd == -1)
742 fatal_event(&ev);
743 else
744 /* pipe is non-blocking and struct event_desc is smaller than
745 PIPE_BUF, so this either fails or writes everything */
746 while (write(fd, &ev, sizeof(ev)) == -1 && errno == EINTR);
749 static void fatal_event(struct event_desc *ev)
751 errno = ev->data;
753 switch (ev->event)
755 case EVENT_DIE:
756 exit(0);
758 case EVENT_FORK_ERR:
759 die(_("cannot fork into background: %s"), NULL, EC_MISC);
761 case EVENT_PIPE_ERR:
762 die(_("failed to create helper: %s"), NULL, EC_MISC);
764 case EVENT_CAP_ERR:
765 die(_("setting capabilities failed: %s"), NULL, EC_MISC);
767 case EVENT_USER_ERR:
768 case EVENT_HUSER_ERR:
769 die(_("failed to change user-id to %s: %s"),
770 ev->event == EVENT_USER_ERR ? daemon->username : daemon->scriptuser,
771 EC_MISC);
773 case EVENT_GROUP_ERR:
774 die(_("failed to change group-id to %s: %s"), daemon->groupname, EC_MISC);
776 case EVENT_PIDFILE:
777 die(_("failed to open pidfile %s: %s"), daemon->runfile, EC_FILE);
779 case EVENT_LOG_ERR:
780 die(_("cannot open %s: %s"), daemon->log_file ? daemon->log_file : "log", EC_FILE);
784 static void async_event(int pipe, time_t now)
786 pid_t p;
787 struct event_desc ev;
788 int i;
790 if (read_write(pipe, (unsigned char *)&ev, sizeof(ev), 1))
791 switch (ev.event)
793 case EVENT_RELOAD:
794 clear_cache_and_reload(now);
795 if (daemon->port != 0 && daemon->resolv_files && (daemon->options & OPT_NO_POLL))
797 reload_servers(daemon->resolv_files->name);
798 check_servers();
800 #ifdef HAVE_DHCP
801 rerun_scripts();
802 #endif
803 break;
805 case EVENT_DUMP:
806 if (daemon->port != 0)
807 dump_cache(now);
808 break;
810 case EVENT_ALARM:
811 #ifdef HAVE_DHCP
812 if (daemon->dhcp)
814 lease_prune(NULL, now);
815 lease_update_file(now);
817 #endif
818 break;
820 case EVENT_CHILD:
821 /* See Stevens 5.10 */
822 while ((p = waitpid(-1, NULL, WNOHANG)) != 0)
823 if (p == -1)
825 if (errno != EINTR)
826 break;
828 else
829 for (i = 0 ; i < MAX_PROCS; i++)
830 if (daemon->tcp_pids[i] == p)
831 daemon->tcp_pids[i] = 0;
832 break;
834 case EVENT_KILLED:
835 my_syslog(LOG_WARNING, _("child process killed by signal %d"), ev.data);
836 break;
838 case EVENT_EXITED:
839 my_syslog(LOG_WARNING, _("child process exited with status %d"), ev.data);
840 break;
842 case EVENT_EXEC_ERR:
843 my_syslog(LOG_ERR, _("failed to execute %s: %s"),
844 daemon->lease_change_command, strerror(ev.data));
845 break;
847 /* necessary for fatal errors in helper */
848 case EVENT_HUSER_ERR:
849 case EVENT_DIE:
850 fatal_event(&ev);
851 break;
853 case EVENT_REOPEN:
854 tomato_helper(now); // zzz
856 /* Note: this may leave TCP-handling processes with the old file still open.
857 Since any such process will die in CHILD_LIFETIME or probably much sooner,
858 we leave them logging to the old file. */
859 if (daemon->log_file != NULL)
860 log_reopen(daemon->log_file);
861 break;
863 case EVENT_TERM:
864 /* Knock all our children on the head. */
865 for (i = 0; i < MAX_PROCS; i++)
866 if (daemon->tcp_pids[i] != 0)
867 kill(daemon->tcp_pids[i], SIGALRM);
869 #if defined(HAVE_DHCP) && !defined(NO_FORK)
870 /* handle pending lease transitions */
871 if (daemon->helperfd != -1)
873 /* block in writes until all done */
874 if ((i = fcntl(daemon->helperfd, F_GETFL)) != -1)
875 fcntl(daemon->helperfd, F_SETFL, i & ~O_NONBLOCK);
876 do {
877 helper_write();
878 } while (!helper_buf_empty() || do_script_run(now));
879 close(daemon->helperfd);
881 #endif
883 flush_lease_file(now); // zzz
885 if (daemon->lease_stream)
886 fclose(daemon->lease_stream);
888 if (daemon->runfile)
889 unlink(daemon->runfile);
891 my_syslog(LOG_INFO, _("exiting on receipt of SIGTERM"));
892 flush_log();
893 exit(EC_GOOD);
897 static void poll_resolv()
899 struct resolvc *res, *latest;
900 struct stat statbuf;
901 time_t last_change = 0;
902 /* There may be more than one possible file.
903 Go through and find the one which changed _last_.
904 Warn of any which can't be read. */
905 for (latest = NULL, res = daemon->resolv_files; res; res = res->next)
906 if (stat(res->name, &statbuf) == -1)
908 if (!res->logged)
909 my_syslog(LOG_WARNING, _("failed to access %s: %s"), res->name, strerror(errno));
910 res->logged = 1;
912 else
914 res->logged = 0;
915 if (statbuf.st_mtime != res->mtime)
917 res->mtime = statbuf.st_mtime;
918 if (difftime(statbuf.st_mtime, last_change) > 0.0)
920 last_change = statbuf.st_mtime;
921 latest = res;
922 break; // zzz - (~0 time?)
927 if (latest)
929 static int warned = 0;
930 if (reload_servers(latest->name))
932 my_syslog(LOG_INFO, _("reading %s"), latest->name);
933 warned = 0;
934 check_servers();
935 if (daemon->options & OPT_RELOAD)
936 cache_reload();
938 else
940 latest->mtime = 0;
941 if (!warned)
943 my_syslog(LOG_WARNING, _("no servers found in %s, will retry"), latest->name);
944 warned = 1;
950 void clear_cache_and_reload(time_t now)
952 if (daemon->port != 0)
953 cache_reload();
955 #ifdef HAVE_DHCP
956 if (daemon->dhcp)
958 if (daemon->options & OPT_ETHERS)
959 dhcp_read_ethers();
960 reread_dhcp();
961 dhcp_update_configs(daemon->dhcp_conf);
962 check_dhcp_hosts(0);
963 lease_update_from_configs();
964 lease_update_file(now);
965 lease_update_dns();
967 #endif
970 static int set_dns_listeners(time_t now, fd_set *set, int *maxfdp)
972 struct serverfd *serverfdp;
973 struct listener *listener;
974 int wait = 0, i;
976 #ifdef HAVE_TFTP
977 int tftp = 0;
978 struct tftp_transfer *transfer;
979 for (transfer = daemon->tftp_trans; transfer; transfer = transfer->next)
981 tftp++;
982 FD_SET(transfer->sockfd, set);
983 bump_maxfd(transfer->sockfd, maxfdp);
985 #endif
987 /* will we be able to get memory? */
988 if (daemon->port != 0)
989 get_new_frec(now, &wait);
991 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
993 FD_SET(serverfdp->fd, set);
994 bump_maxfd(serverfdp->fd, maxfdp);
997 if (daemon->port != 0 && !daemon->osport)
998 for (i = 0; i < RANDOM_SOCKS; i++)
999 if (daemon->randomsocks[i].refcount != 0)
1001 FD_SET(daemon->randomsocks[i].fd, set);
1002 bump_maxfd(daemon->randomsocks[i].fd, maxfdp);
1005 for (listener = daemon->listeners; listener; listener = listener->next)
1007 /* only listen for queries if we have resources */
1008 if (listener->fd != -1 && wait == 0)
1010 FD_SET(listener->fd, set);
1011 bump_maxfd(listener->fd, maxfdp);
1014 /* death of a child goes through the select loop, so
1015 we don't need to explicitly arrange to wake up here */
1016 if (listener->tcpfd != -1)
1017 for (i = 0; i < MAX_PROCS; i++)
1018 if (daemon->tcp_pids[i] == 0)
1020 FD_SET(listener->tcpfd, set);
1021 bump_maxfd(listener->tcpfd, maxfdp);
1022 break;
1025 #ifdef HAVE_TFTP
1026 if (tftp <= daemon->tftp_max && listener->tftpfd != -1)
1028 FD_SET(listener->tftpfd, set);
1029 bump_maxfd(listener->tftpfd, maxfdp);
1031 #endif
1035 return wait;
1038 static void check_dns_listeners(fd_set *set, time_t now)
1040 struct serverfd *serverfdp;
1041 struct listener *listener;
1042 int i;
1044 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1045 if (FD_ISSET(serverfdp->fd, set))
1046 reply_query(serverfdp->fd, serverfdp->source_addr.sa.sa_family, now);
1048 if (daemon->port != 0 && !daemon->osport)
1049 for (i = 0; i < RANDOM_SOCKS; i++)
1050 if (daemon->randomsocks[i].refcount != 0 &&
1051 FD_ISSET(daemon->randomsocks[i].fd, set))
1052 reply_query(daemon->randomsocks[i].fd, daemon->randomsocks[i].family, now);
1054 for (listener = daemon->listeners; listener; listener = listener->next)
1056 if (listener->fd != -1 && FD_ISSET(listener->fd, set))
1057 receive_query(listener, now);
1059 #ifdef HAVE_TFTP
1060 if (listener->tftpfd != -1 && FD_ISSET(listener->tftpfd, set))
1061 tftp_request(listener, now);
1062 #endif
1064 if (listener->tcpfd != -1 && FD_ISSET(listener->tcpfd, set))
1066 int confd;
1067 struct irec *iface = NULL;
1068 pid_t p;
1070 while((confd = accept(listener->tcpfd, NULL, NULL)) == -1 && errno == EINTR);
1072 if (confd == -1)
1073 continue;
1075 if (daemon->options & OPT_NOWILD)
1076 iface = listener->iface;
1077 else
1079 union mysockaddr tcp_addr;
1080 socklen_t tcp_len = sizeof(union mysockaddr);
1081 /* Check for allowed interfaces when binding the wildcard address:
1082 we do this by looking for an interface with the same address as
1083 the local address of the TCP connection, then looking to see if that's
1084 an allowed interface. As a side effect, we get the netmask of the
1085 interface too, for localisation. */
1087 /* interface may be new since startup */
1088 if (enumerate_interfaces() &&
1089 getsockname(confd, (struct sockaddr *)&tcp_addr, &tcp_len) != -1)
1090 for (iface = daemon->interfaces; iface; iface = iface->next)
1091 if (sockaddr_isequal(&iface->addr, &tcp_addr))
1092 break;
1095 if (!iface)
1097 shutdown(confd, SHUT_RDWR);
1098 close(confd);
1100 #ifndef NO_FORK
1101 else if (!(daemon->options & OPT_DEBUG) && (p = fork()) != 0)
1103 if (p != -1)
1105 int i;
1106 for (i = 0; i < MAX_PROCS; i++)
1107 if (daemon->tcp_pids[i] == 0)
1109 daemon->tcp_pids[i] = p;
1110 break;
1113 close(confd);
1115 #endif
1116 else
1118 unsigned char *buff;
1119 struct server *s;
1120 int flags;
1121 struct in_addr dst_addr_4;
1123 dst_addr_4.s_addr = 0;
1125 /* Arrange for SIGALARM after CHILD_LIFETIME seconds to
1126 terminate the process. */
1127 if (!(daemon->options & OPT_DEBUG))
1128 alarm(CHILD_LIFETIME);
1130 /* start with no upstream connections. */
1131 for (s = daemon->servers; s; s = s->next)
1132 s->tcpfd = -1;
1134 /* The connected socket inherits non-blocking
1135 attribute from the listening socket.
1136 Reset that here. */
1137 if ((flags = fcntl(confd, F_GETFL, 0)) != -1)
1138 fcntl(confd, F_SETFL, flags & ~O_NONBLOCK);
1140 if (listener->family == AF_INET)
1141 dst_addr_4 = iface->addr.in.sin_addr;
1143 buff = tcp_request(confd, now, dst_addr_4, iface->netmask);
1145 shutdown(confd, SHUT_RDWR);
1146 close(confd);
1148 if (buff)
1149 free(buff);
1151 for (s = daemon->servers; s; s = s->next)
1152 if (s->tcpfd != -1)
1154 shutdown(s->tcpfd, SHUT_RDWR);
1155 close(s->tcpfd);
1157 #ifndef NO_FORK
1158 if (!(daemon->options & OPT_DEBUG))
1160 flush_log();
1161 _exit(0);
1163 #endif
1169 #ifdef HAVE_DHCP
1170 int make_icmp_sock(void)
1172 int fd;
1173 int zeroopt = 0;
1175 if ((fd = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
1177 if (!fix_fd(fd) ||
1178 setsockopt(fd, SOL_SOCKET, SO_DONTROUTE, &zeroopt, sizeof(zeroopt)) == -1)
1180 close(fd);
1181 fd = -1;
1185 return fd;
1188 int icmp_ping(struct in_addr addr)
1190 /* Try and get an ICMP echo from a machine. */
1192 /* Note that whilst in the three second wait, we check for
1193 (and service) events on the DNS and TFTP sockets, (so doing that
1194 better not use any resources our caller has in use...)
1195 but we remain deaf to signals or further DHCP packets. */
1197 int fd;
1198 struct sockaddr_in saddr;
1199 struct {
1200 struct ip ip;
1201 struct icmp icmp;
1202 } packet;
1203 unsigned short id = rand16();
1204 unsigned int i, j;
1205 int gotreply = 0;
1206 time_t start, now;
1208 #if defined(HAVE_LINUX_NETWORK) || defined (HAVE_SOLARIS_NETWORK)
1209 if ((fd = make_icmp_sock()) == -1)
1210 return 0;
1211 #else
1212 int opt = 2000;
1213 fd = daemon->dhcp_icmp_fd;
1214 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1215 #endif
1217 saddr.sin_family = AF_INET;
1218 saddr.sin_port = 0;
1219 saddr.sin_addr = addr;
1220 #ifdef HAVE_SOCKADDR_SA_LEN
1221 saddr.sin_len = sizeof(struct sockaddr_in);
1222 #endif
1224 memset(&packet.icmp, 0, sizeof(packet.icmp));
1225 packet.icmp.icmp_type = ICMP_ECHO;
1226 packet.icmp.icmp_id = id;
1227 for (j = 0, i = 0; i < sizeof(struct icmp) / 2; i++)
1228 j += ((u16 *)&packet.icmp)[i];
1229 while (j>>16)
1230 j = (j & 0xffff) + (j >> 16);
1231 packet.icmp.icmp_cksum = (j == 0xffff) ? j : ~j;
1233 while (sendto(fd, (char *)&packet.icmp, sizeof(struct icmp), 0,
1234 (struct sockaddr *)&saddr, sizeof(saddr)) == -1 &&
1235 retry_send());
1237 for (now = start = dnsmasq_time();
1238 difftime(now, start) < (float)PING_WAIT;)
1240 struct timeval tv;
1241 fd_set rset, wset;
1242 struct sockaddr_in faddr;
1243 int maxfd = fd;
1244 socklen_t len = sizeof(faddr);
1246 tv.tv_usec = 250000;
1247 tv.tv_sec = 0;
1249 FD_ZERO(&rset);
1250 FD_ZERO(&wset);
1251 FD_SET(fd, &rset);
1252 set_dns_listeners(now, &rset, &maxfd);
1253 set_log_writer(&wset, &maxfd);
1255 if (select(maxfd+1, &rset, &wset, NULL, &tv) < 0)
1257 FD_ZERO(&rset);
1258 FD_ZERO(&wset);
1261 now = dnsmasq_time();
1263 check_log_writer(&wset);
1264 check_dns_listeners(&rset, now);
1266 #ifdef HAVE_TFTP
1267 check_tftp_listeners(&rset, now);
1268 #endif
1270 if (FD_ISSET(fd, &rset) &&
1271 recvfrom(fd, &packet, sizeof(packet), 0,
1272 (struct sockaddr *)&faddr, &len) == sizeof(packet) &&
1273 saddr.sin_addr.s_addr == faddr.sin_addr.s_addr &&
1274 packet.icmp.icmp_type == ICMP_ECHOREPLY &&
1275 packet.icmp.icmp_seq == 0 &&
1276 packet.icmp.icmp_id == id)
1278 gotreply = 1;
1279 break;
1283 #if defined(HAVE_LINUX_NETWORK) || defined(HAVE_SOLARIS_NETWORK)
1284 close(fd);
1285 #else
1286 opt = 1;
1287 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1288 #endif
1290 return gotreply;
1292 #endif