Tomato 1.28
[tomato.git] / release / src / router / dnsmasq / src / dnsmasq.c
blob84c9a00df4017605cbc6a884cd775fb9dc3af45f
1 /* dnsmasq is Copyright (c) 2000-2010 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 #if defined(HAVE_DHCP) && !defined(HAVE_SCRIPT)
53 "no-scripts "
54 #endif
55 #ifndef HAVE_TFTP
56 "no-"
57 #endif
58 "TFTP";
62 static volatile pid_t pid = 0;
63 static volatile int pipewrite;
65 static int set_dns_listeners(time_t now, fd_set *set, int *maxfdp);
66 static void check_dns_listeners(fd_set *set, time_t now);
67 static void sig_handler(int sig);
68 static void async_event(int pipe, time_t now);
69 static void fatal_event(struct event_desc *ev);
71 void tomato_helper(time_t now); // zzz
72 void flush_lease_file(time_t now); // zzz
74 int main (int argc, char **argv)
76 int bind_fallback = 0;
77 time_t now;
78 struct sigaction sigact;
79 struct iname *if_tmp;
80 int piperead, pipefd[2], err_pipe[2];
81 struct passwd *ent_pw = NULL;
82 #if defined(HAVE_DHCP) && defined(HAVE_SCRIPT)
83 uid_t script_uid = 0;
84 gid_t script_gid = 0;
85 #endif
86 struct group *gp = NULL;
87 long i, max_fd = sysconf(_SC_OPEN_MAX);
88 char *baduser = NULL;
89 int log_err;
90 #if defined(HAVE_LINUX_NETWORK)
91 cap_user_header_t hdr = NULL;
92 cap_user_data_t data = NULL;
93 #endif
95 #ifdef LOCALEDIR
96 setlocale(LC_ALL, "");
97 bindtextdomain("dnsmasq", LOCALEDIR);
98 textdomain("dnsmasq");
99 #endif
101 sigact.sa_handler = sig_handler;
102 sigact.sa_flags = 0;
103 sigemptyset(&sigact.sa_mask);
104 sigaction(SIGUSR1, &sigact, NULL);
105 sigaction(SIGUSR2, &sigact, NULL);
106 sigaction(SIGHUP, &sigact, NULL);
107 sigaction(SIGTERM, &sigact, NULL);
108 sigaction(SIGALRM, &sigact, NULL);
109 sigaction(SIGCHLD, &sigact, NULL);
111 /* ignore SIGPIPE */
112 sigact.sa_handler = SIG_IGN;
113 sigaction(SIGPIPE, &sigact, NULL);
115 umask(022); /* known umask, create leases and pid files as 0644 */
117 read_opts(argc, argv, compile_opts);
119 if (daemon->edns_pktsz < PACKETSZ)
120 daemon->edns_pktsz = PACKETSZ;
121 daemon->packet_buff_sz = daemon->edns_pktsz > DNSMASQ_PACKETSZ ?
122 daemon->edns_pktsz : DNSMASQ_PACKETSZ;
123 daemon->packet = safe_malloc(daemon->packet_buff_sz);
125 #ifdef HAVE_DHCP
126 if (!daemon->lease_file)
128 if (daemon->dhcp)
129 daemon->lease_file = LEASEFILE;
131 #endif
133 /* Close any file descriptors we inherited apart from std{in|out|err} */
134 for (i = 0; i < max_fd; i++)
135 if (i != STDOUT_FILENO && i != STDERR_FILENO && i != STDIN_FILENO)
136 close(i);
138 #ifdef HAVE_LINUX_NETWORK
139 netlink_init();
140 #elif !(defined(IP_RECVDSTADDR) && \
141 defined(IP_RECVIF) && \
142 defined(IP_SENDSRCADDR))
143 if (!(daemon->options & OPT_NOWILD))
145 bind_fallback = 1;
146 daemon->options |= OPT_NOWILD;
148 #endif
150 #ifndef HAVE_TFTP
151 if (daemon->tftp_unlimited || daemon->tftp_interfaces)
152 die(_("TFTP server not available: set HAVE_TFTP in src/config.h"), NULL, EC_BADCONF);
153 #endif
155 #ifdef HAVE_SOLARIS_NETWORK
156 if (daemon->max_logs != 0)
157 die(_("asychronous logging is not available under Solaris"), NULL, EC_BADCONF);
158 #endif
160 rand_init();
162 now = dnsmasq_time();
164 #ifdef HAVE_DHCP
165 if (daemon->dhcp)
167 /* Note that order matters here, we must call lease_init before
168 creating any file descriptors which shouldn't be leaked
169 to the lease-script init process. */
170 lease_init(now);
171 dhcp_init();
173 #endif
175 if (!enumerate_interfaces())
176 die(_("failed to find list of interfaces: %s"), NULL, EC_MISC);
178 if (daemon->options & OPT_NOWILD)
180 daemon->listeners = create_bound_listeners();
182 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
183 if (if_tmp->name && !if_tmp->used)
184 die(_("unknown interface %s"), if_tmp->name, EC_BADNET);
186 for (if_tmp = daemon->if_addrs; if_tmp; if_tmp = if_tmp->next)
187 if (!if_tmp->used)
189 prettyprint_addr(&if_tmp->addr, daemon->namebuff);
190 die(_("no interface with address %s"), daemon->namebuff, EC_BADNET);
193 else if ((daemon->port != 0 || daemon->tftp_interfaces || daemon->tftp_unlimited) &&
194 !(daemon->listeners = create_wildcard_listeners()))
195 die(_("failed to create listening socket: %s"), NULL, EC_BADNET);
197 if (daemon->port != 0)
198 cache_init();
200 if (daemon->options & OPT_DBUS)
201 #ifdef HAVE_DBUS
203 char *err;
204 daemon->dbus = NULL;
205 daemon->watches = NULL;
206 if ((err = dbus_init()))
207 die(_("DBus error: %s"), err, EC_MISC);
209 #else
210 die(_("DBus not available: set HAVE_DBUS in src/config.h"), NULL, EC_BADCONF);
211 #endif
213 if (daemon->port != 0)
214 pre_allocate_sfds();
216 #if defined(HAVE_DHCP) && defined(HAVE_SCRIPT)
217 /* Note getpwnam returns static storage */
218 if (daemon->dhcp && daemon->lease_change_command && daemon->scriptuser)
220 if ((ent_pw = getpwnam(daemon->scriptuser)))
222 script_uid = ent_pw->pw_uid;
223 script_gid = ent_pw->pw_gid;
225 else
226 baduser = daemon->scriptuser;
228 #endif
230 if (daemon->username && !(ent_pw = getpwnam(daemon->username)))
231 baduser = daemon->username;
232 else if (daemon->groupname && !(gp = getgrnam(daemon->groupname)))
233 baduser = daemon->groupname;
235 if (baduser)
236 die(_("unknown user or group: %s"), baduser, EC_BADCONF);
238 /* implement group defaults, "dip" if available, or group associated with uid */
239 if (!daemon->group_set && !gp)
241 if (!(gp = getgrnam(CHGRP)) && ent_pw)
242 gp = getgrgid(ent_pw->pw_gid);
244 /* for error message */
245 if (gp)
246 daemon->groupname = gp->gr_name;
249 #if defined(HAVE_LINUX_NETWORK)
250 /* determine capability API version here, while we can still
251 call safe_malloc */
252 if (ent_pw && ent_pw->pw_uid != 0)
254 int capsize = 1; /* for header version 1 */
255 hdr = safe_malloc(sizeof(*hdr));
257 /* find version supported by kernel */
258 memset(hdr, 0, sizeof(*hdr));
259 capget(hdr, NULL);
261 if (hdr->version != LINUX_CAPABILITY_VERSION_1)
263 /* if unknown version, use largest supported version (3) */
264 if (hdr->version != LINUX_CAPABILITY_VERSION_2)
265 hdr->version = LINUX_CAPABILITY_VERSION_3;
266 capsize = 2;
269 data = safe_malloc(sizeof(*data) * capsize);
270 memset(data, 0, sizeof(*data) * capsize);
272 #endif
274 /* Use a pipe to carry signals and other events back to the event loop
275 in a race-free manner and another to carry errors to daemon-invoking process */
276 safe_pipe(pipefd, 1);
278 piperead = pipefd[0];
279 pipewrite = pipefd[1];
280 /* prime the pipe to load stuff first time. */
281 send_event(pipewrite, EVENT_RELOAD, 0);
283 err_pipe[1] = -1;
285 if (!(daemon->options & OPT_DEBUG))
287 /* The following code "daemonizes" the process.
288 See Stevens section 12.4 */
290 if (chdir("/") != 0)
291 die(_("cannot chdir to filesystem root: %s"), NULL, EC_MISC);
293 #ifndef NO_FORK
294 if (!(daemon->options & OPT_NO_FORK))
296 pid_t pid;
298 /* pipe to carry errors back to original process.
299 When startup is complete we close this and the process terminates. */
300 safe_pipe(err_pipe, 0);
302 if ((pid = fork()) == -1)
303 /* fd == -1 since we've not forked, never returns. */
304 send_event(-1, EVENT_FORK_ERR, errno);
306 if (pid != 0)
308 struct event_desc ev;
310 /* close our copy of write-end */
311 close(err_pipe[1]);
313 /* check for errors after the fork */
314 if (read_write(err_pipe[0], (unsigned char *)&ev, sizeof(ev), 1))
315 fatal_event(&ev);
317 _exit(EC_GOOD);
320 close(err_pipe[0]);
322 /* NO calls to die() from here on. */
324 setsid();
326 if ((pid = fork()) == -1)
327 send_event(err_pipe[1], EVENT_FORK_ERR, errno);
329 if (pid != 0)
330 _exit(0);
332 #endif
334 /* write pidfile _after_ forking ! */
335 if (daemon->runfile)
337 FILE *pidfile;
339 /* only complain if started as root */
340 if ((pidfile = fopen(daemon->runfile, "w")))
342 fprintf(pidfile, "%d\n", (int) getpid());
343 fclose(pidfile);
345 else if (getuid() == 0)
347 send_event(err_pipe[1], EVENT_PIDFILE, errno);
348 _exit(0);
353 log_err = log_start(ent_pw, err_pipe[1]);
355 if (!(daemon->options & OPT_DEBUG))
357 /* open stdout etc to /dev/null */
358 int nullfd = open("/dev/null", O_RDWR);
359 dup2(nullfd, STDOUT_FILENO);
360 dup2(nullfd, STDERR_FILENO);
361 dup2(nullfd, STDIN_FILENO);
362 close(nullfd);
365 /* if we are to run scripts, we need to fork a helper before dropping root. */
366 daemon->helperfd = -1;
367 #if defined(HAVE_DHCP) && defined(HAVE_SCRIPT)
368 if (daemon->dhcp && daemon->lease_change_command)
369 daemon->helperfd = create_helper(pipewrite, err_pipe[1], script_uid, script_gid, max_fd);
370 #endif
372 if (!(daemon->options & OPT_DEBUG) && getuid() == 0)
374 int bad_capabilities = 0;
375 gid_t dummy;
377 /* remove all supplimentary groups */
378 if (gp &&
379 (setgroups(0, &dummy) == -1 ||
380 setgid(gp->gr_gid) == -1))
382 send_event(err_pipe[1], EVENT_GROUP_ERR, errno);
383 _exit(0);
386 if (ent_pw && ent_pw->pw_uid != 0)
388 #if defined(HAVE_LINUX_NETWORK)
389 /* On linux, we keep CAP_NETADMIN (for ARP-injection) and
390 CAP_NET_RAW (for icmp) if we're doing dhcp */
391 data->effective = data->permitted = data->inheritable =
392 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID);
394 /* Tell kernel to not clear capabilities when dropping root */
395 if (capset(hdr, data) == -1 || prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1)
396 bad_capabilities = errno;
398 #elif defined(HAVE_SOLARIS_NETWORK)
399 /* http://developers.sun.com/solaris/articles/program_privileges.html */
400 priv_set_t *priv_set;
402 if (!(priv_set = priv_str_to_set("basic", ",", NULL)) ||
403 priv_addset(priv_set, PRIV_NET_ICMPACCESS) == -1 ||
404 priv_addset(priv_set, PRIV_SYS_NET_CONFIG) == -1)
405 bad_capabilities = errno;
407 if (priv_set && bad_capabilities == 0)
409 priv_inverse(priv_set);
411 if (setppriv(PRIV_OFF, PRIV_LIMIT, priv_set) == -1)
412 bad_capabilities = errno;
415 if (priv_set)
416 priv_freeset(priv_set);
418 #endif
420 if (bad_capabilities != 0)
422 send_event(err_pipe[1], EVENT_CAP_ERR, bad_capabilities);
423 _exit(0);
426 /* finally drop root */
427 if (setuid(ent_pw->pw_uid) == -1)
429 send_event(err_pipe[1], EVENT_USER_ERR, errno);
430 _exit(0);
433 #ifdef HAVE_LINUX_NETWORK
434 data->effective = data->permitted =
435 (1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW);
436 data->inheritable = 0;
438 /* lose the setuid and setgid capbilities */
439 if (capset(hdr, data) == -1)
441 send_event(err_pipe[1], EVENT_CAP_ERR, errno);
442 _exit(0);
444 #endif
449 #ifdef HAVE_LINUX_NETWORK
450 if (daemon->options & OPT_DEBUG)
451 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
452 #endif
454 if (daemon->port == 0)
455 my_syslog(LOG_INFO, _("started, version %s DNS disabled"), VERSION);
456 else if (daemon->cachesize != 0)
457 my_syslog(LOG_INFO, _("started, version %s cachesize %d"), VERSION, daemon->cachesize);
458 else
459 my_syslog(LOG_INFO, _("started, version %s cache disabled"), VERSION);
461 my_syslog(LOG_INFO, _("compile time options: %s"), compile_opts);
463 #ifdef HAVE_DBUS
464 if (daemon->options & OPT_DBUS)
466 if (daemon->dbus)
467 my_syslog(LOG_INFO, _("DBus support enabled: connected to system bus"));
468 else
469 my_syslog(LOG_INFO, _("DBus support enabled: bus connection pending"));
471 #endif
473 if (log_err != 0)
474 my_syslog(LOG_WARNING, _("warning: failed to change owner of %s: %s"),
475 daemon->log_file, strerror(log_err));
477 if (bind_fallback)
478 my_syslog(LOG_WARNING, _("setting --bind-interfaces option because of OS limitations"));
480 if (!(daemon->options & OPT_NOWILD))
481 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
482 if (if_tmp->name && !if_tmp->used)
483 my_syslog(LOG_WARNING, _("warning: interface %s does not currently exist"), if_tmp->name);
485 if (daemon->port != 0 && (daemon->options & OPT_NO_RESOLV))
487 if (daemon->resolv_files && !daemon->resolv_files->is_default)
488 my_syslog(LOG_WARNING, _("warning: ignoring resolv-file flag because no-resolv is set"));
489 daemon->resolv_files = NULL;
490 if (!daemon->servers)
491 my_syslog(LOG_WARNING, _("warning: no upstream servers configured"));
494 if (daemon->max_logs != 0)
495 my_syslog(LOG_INFO, _("asynchronous logging enabled, queue limit is %d messages"), daemon->max_logs);
497 #ifdef HAVE_DHCP
498 if (daemon->dhcp)
500 struct dhcp_context *dhcp_tmp;
502 for (dhcp_tmp = daemon->dhcp; dhcp_tmp; dhcp_tmp = dhcp_tmp->next)
504 prettyprint_time(daemon->dhcp_buff2, dhcp_tmp->lease_time);
505 strcpy(daemon->dhcp_buff, inet_ntoa(dhcp_tmp->start));
506 my_syslog(MS_DHCP | LOG_INFO,
507 (dhcp_tmp->flags & CONTEXT_STATIC) ?
508 _("DHCP, static leases only on %.0s%s, lease time %s") :
509 (dhcp_tmp->flags & CONTEXT_PROXY) ?
510 _("DHCP, proxy on subnet %.0s%s%.0s") :
511 _("DHCP, IP range %s -- %s, lease time %s"),
512 daemon->dhcp_buff, inet_ntoa(dhcp_tmp->end), daemon->dhcp_buff2);
515 #endif
517 #ifdef HAVE_TFTP
518 if (daemon->tftp_unlimited || daemon->tftp_interfaces)
520 #ifdef FD_SETSIZE
521 if (FD_SETSIZE < (unsigned)max_fd)
522 max_fd = FD_SETSIZE;
523 #endif
525 my_syslog(MS_TFTP | LOG_INFO, "TFTP %s%s %s",
526 daemon->tftp_prefix ? _("root is ") : _("enabled"),
527 daemon->tftp_prefix ? daemon->tftp_prefix: "",
528 daemon->options & OPT_TFTP_SECURE ? _("secure mode") : "");
530 /* This is a guess, it assumes that for small limits,
531 disjoint files might be served, but for large limits,
532 a single file will be sent to may clients (the file only needs
533 one fd). */
535 max_fd -= 30; /* use other than TFTP */
537 if (max_fd < 0)
538 max_fd = 5;
539 else if (max_fd < 100)
540 max_fd = max_fd/2;
541 else
542 max_fd = max_fd - 20;
544 /* if we have to use a limited range of ports,
545 that will limit the number of transfers */
546 if (daemon->start_tftp_port != 0 &&
547 daemon->end_tftp_port - daemon->start_tftp_port + 1 < max_fd)
548 max_fd = daemon->end_tftp_port - daemon->start_tftp_port + 1;
550 if (daemon->tftp_max > max_fd)
552 daemon->tftp_max = max_fd;
553 my_syslog(MS_TFTP | LOG_WARNING,
554 _("restricting maximum simultaneous TFTP transfers to %d"),
555 daemon->tftp_max);
558 #endif
560 /* finished start-up - release original process */
561 if (err_pipe[1] != -1)
562 close(err_pipe[1]);
564 if (daemon->port != 0)
565 check_servers();
567 pid = getpid();
569 while (1)
571 int maxfd = -1;
572 struct timeval t, *tp = NULL;
573 fd_set rset, wset, eset;
575 FD_ZERO(&rset);
576 FD_ZERO(&wset);
577 FD_ZERO(&eset);
579 /* if we are out of resources, find how long we have to wait
580 for some to come free, we'll loop around then and restart
581 listening for queries */
582 if ((t.tv_sec = set_dns_listeners(now, &rset, &maxfd)) != 0)
584 t.tv_usec = 0;
585 tp = &t;
588 /* Whilst polling for the dbus, or doing a tftp transfer, wake every quarter second */
589 if (daemon->tftp_trans ||
590 ((daemon->options & OPT_DBUS) && !daemon->dbus))
592 t.tv_sec = 0;
593 t.tv_usec = 250000;
594 tp = &t;
597 #ifdef HAVE_DBUS
598 set_dbus_listeners(&maxfd, &rset, &wset, &eset);
599 #endif
601 #ifdef HAVE_DHCP
602 if (daemon->dhcp)
604 FD_SET(daemon->dhcpfd, &rset);
605 bump_maxfd(daemon->dhcpfd, &maxfd);
606 if (daemon->pxefd != -1)
608 FD_SET(daemon->pxefd, &rset);
609 bump_maxfd(daemon->pxefd, &maxfd);
612 #endif
614 #ifdef HAVE_LINUX_NETWORK
615 FD_SET(daemon->netlinkfd, &rset);
616 bump_maxfd(daemon->netlinkfd, &maxfd);
617 #endif
619 FD_SET(piperead, &rset);
620 bump_maxfd(piperead, &maxfd);
622 #ifdef HAVE_DHCP
623 # ifdef HAVE_SCRIPT
624 while (helper_buf_empty() && do_script_run(now));
626 if (!helper_buf_empty())
628 FD_SET(daemon->helperfd, &wset);
629 bump_maxfd(daemon->helperfd, &maxfd);
631 # else
632 /* need this for other side-effects */
633 while (do_script_run(now));
634 # endif
635 #endif
637 /* must do this just before select(), when we know no
638 more calls to my_syslog() can occur */
639 set_log_writer(&wset, &maxfd);
641 if (select(maxfd+1, &rset, &wset, &eset, tp) < 0)
643 /* otherwise undefined after error */
644 FD_ZERO(&rset); FD_ZERO(&wset); FD_ZERO(&eset);
647 now = dnsmasq_time();
649 check_log_writer(&wset);
651 #ifdef HAVE_LINUX_NETWORK
652 if (FD_ISSET(daemon->netlinkfd, &rset))
653 netlink_multicast();
654 #endif
656 /* Check for changes to resolv files once per second max. */
657 /* Don't go silent for long periods if the clock goes backwards. */
658 if (daemon->last_resolv == 0 ||
659 difftime(now, daemon->last_resolv) > 1.0 ||
660 difftime(now, daemon->last_resolv) < -1.0)
662 /* poll_resolv doesn't need to reload first time through, since
663 that's queued anyway. */
665 poll_resolv(0, daemon->last_resolv != 0, now);
666 daemon->last_resolv = now;
669 if (FD_ISSET(piperead, &rset))
670 async_event(piperead, now);
672 #ifdef HAVE_DBUS
673 /* if we didn't create a DBus connection, retry now. */
674 if ((daemon->options & OPT_DBUS) && !daemon->dbus)
676 char *err;
677 if ((err = dbus_init()))
678 my_syslog(LOG_WARNING, _("DBus error: %s"), err);
679 if (daemon->dbus)
680 my_syslog(LOG_INFO, _("connected to system DBus"));
682 check_dbus_listeners(&rset, &wset, &eset);
683 #endif
685 check_dns_listeners(&rset, now);
687 #ifdef HAVE_TFTP
688 check_tftp_listeners(&rset, now);
689 #endif
691 #ifdef HAVE_DHCP
692 if (daemon->dhcp)
694 if (FD_ISSET(daemon->dhcpfd, &rset))
695 dhcp_packet(now, 0);
696 if (daemon->pxefd != -1 && FD_ISSET(daemon->pxefd, &rset))
697 dhcp_packet(now, 1);
700 # ifdef HAVE_SCRIPT
701 if (daemon->helperfd != -1 && FD_ISSET(daemon->helperfd, &wset))
702 helper_write();
703 # endif
704 #endif
709 static void sig_handler(int sig)
711 if (pid == 0)
713 /* ignore anything other than TERM during startup
714 and in helper proc. (helper ignore TERM too) */
715 if (sig == SIGTERM)
716 exit(EC_MISC);
718 else if (pid != getpid())
720 /* alarm is used to kill TCP children after a fixed time. */
721 if (sig == SIGALRM)
722 _exit(0);
724 else
726 /* master process */
727 int event, errsave = errno;
729 if (sig == SIGHUP)
730 event = EVENT_RELOAD;
731 else if (sig == SIGCHLD)
732 event = EVENT_CHILD;
733 else if (sig == SIGALRM)
734 event = EVENT_ALARM;
735 else if (sig == SIGTERM)
736 event = EVENT_TERM;
737 else if (sig == SIGUSR1)
738 event = EVENT_DUMP;
739 else if (sig == SIGUSR2)
740 event = EVENT_REOPEN;
741 else
742 return;
744 send_event(pipewrite, event, 0);
745 errno = errsave;
749 void send_event(int fd, int event, int data)
751 struct event_desc ev;
753 ev.event = event;
754 ev.data = data;
756 /* error pipe, debug mode. */
757 if (fd == -1)
758 fatal_event(&ev);
759 else
760 /* pipe is non-blocking and struct event_desc is smaller than
761 PIPE_BUF, so this either fails or writes everything */
762 while (write(fd, &ev, sizeof(ev)) == -1 && errno == EINTR);
765 static void fatal_event(struct event_desc *ev)
767 errno = ev->data;
769 switch (ev->event)
771 case EVENT_DIE:
772 exit(0);
774 case EVENT_FORK_ERR:
775 die(_("cannot fork into background: %s"), NULL, EC_MISC);
777 case EVENT_PIPE_ERR:
778 die(_("failed to create helper: %s"), NULL, EC_MISC);
780 case EVENT_CAP_ERR:
781 die(_("setting capabilities failed: %s"), NULL, EC_MISC);
783 case EVENT_USER_ERR:
784 case EVENT_HUSER_ERR:
785 die(_("failed to change user-id to %s: %s"),
786 ev->event == EVENT_USER_ERR ? daemon->username : daemon->scriptuser,
787 EC_MISC);
789 case EVENT_GROUP_ERR:
790 die(_("failed to change group-id to %s: %s"), daemon->groupname, EC_MISC);
792 case EVENT_PIDFILE:
793 die(_("failed to open pidfile %s: %s"), daemon->runfile, EC_FILE);
795 case EVENT_LOG_ERR:
796 die(_("cannot open %s: %s"), daemon->log_file ? daemon->log_file : "log", EC_FILE);
800 static void async_event(int pipe, time_t now)
802 pid_t p;
803 struct event_desc ev;
804 int i;
806 if (read_write(pipe, (unsigned char *)&ev, sizeof(ev), 1))
807 switch (ev.event)
809 case EVENT_RELOAD:
810 clear_cache_and_reload(now);
811 if (daemon->port != 0 && daemon->resolv_files && (daemon->options & OPT_NO_POLL))
813 reload_servers(daemon->resolv_files->name);
814 check_servers();
816 #ifdef HAVE_DHCP
817 rerun_scripts();
818 #endif
819 break;
821 case EVENT_DUMP:
822 if (daemon->port != 0)
823 dump_cache(now);
824 break;
826 case EVENT_ALARM:
827 #ifdef HAVE_DHCP
828 if (daemon->dhcp)
830 lease_prune(NULL, now);
831 lease_update_file(now);
833 #endif
834 break;
836 case EVENT_CHILD:
837 /* See Stevens 5.10 */
838 while ((p = waitpid(-1, NULL, WNOHANG)) != 0)
839 if (p == -1)
841 if (errno != EINTR)
842 break;
844 else
845 for (i = 0 ; i < MAX_PROCS; i++)
846 if (daemon->tcp_pids[i] == p)
847 daemon->tcp_pids[i] = 0;
848 break;
850 case EVENT_KILLED:
851 my_syslog(LOG_WARNING, _("child process killed by signal %d"), ev.data);
852 break;
854 case EVENT_EXITED:
855 my_syslog(LOG_WARNING, _("child process exited with status %d"), ev.data);
856 break;
858 case EVENT_EXEC_ERR:
859 my_syslog(LOG_ERR, _("failed to execute %s: %s"),
860 daemon->lease_change_command, strerror(ev.data));
861 break;
863 /* necessary for fatal errors in helper */
864 case EVENT_HUSER_ERR:
865 case EVENT_DIE:
866 fatal_event(&ev);
867 break;
869 case EVENT_REOPEN:
870 tomato_helper(now); // zzz
872 /* Note: this may leave TCP-handling processes with the old file still open.
873 Since any such process will die in CHILD_LIFETIME or probably much sooner,
874 we leave them logging to the old file. */
875 if (daemon->log_file != NULL)
876 log_reopen(daemon->log_file);
877 break;
879 case EVENT_TERM:
880 /* Knock all our children on the head. */
881 for (i = 0; i < MAX_PROCS; i++)
882 if (daemon->tcp_pids[i] != 0)
883 kill(daemon->tcp_pids[i], SIGALRM);
885 #if defined(HAVE_DHCP) && defined(HAVE_SCRIPT)
886 /* handle pending lease transitions */
887 if (daemon->helperfd != -1)
889 /* block in writes until all done */
890 if ((i = fcntl(daemon->helperfd, F_GETFL)) != -1)
891 fcntl(daemon->helperfd, F_SETFL, i & ~O_NONBLOCK);
892 do {
893 helper_write();
894 } while (!helper_buf_empty() || do_script_run(now));
895 close(daemon->helperfd);
897 #endif
899 flush_lease_file(now); // zzz
901 if (daemon->lease_stream)
902 fclose(daemon->lease_stream);
904 if (daemon->runfile)
905 unlink(daemon->runfile);
907 my_syslog(LOG_INFO, _("exiting on receipt of SIGTERM"));
908 flush_log();
909 exit(EC_GOOD);
913 void poll_resolv(int force, int do_reload, time_t now)
915 struct resolvc *res, *latest;
916 struct stat statbuf;
917 time_t last_change = 0;
918 /* There may be more than one possible file.
919 Go through and find the one which changed _last_.
920 Warn of any which can't be read. */
922 if (daemon->port == 0 || (daemon->options & OPT_NO_POLL))
923 return;
925 for (latest = NULL, res = daemon->resolv_files; res; res = res->next)
926 if (stat(res->name, &statbuf) == -1)
928 if (force)
930 res->mtime = 0;
931 continue;
934 if (!res->logged)
935 my_syslog(LOG_WARNING, _("failed to access %s: %s"), res->name, strerror(errno));
936 res->logged = 1;
938 if (res->mtime != 0)
940 /* existing file evaporated, force selection of the latest
941 file even if its mtime hasn't changed since we last looked */
942 poll_resolv(1, do_reload, now);
943 return;
946 else
948 res->logged = 0;
949 if (force || (statbuf.st_mtime != res->mtime))
951 res->mtime = statbuf.st_mtime;
952 if (difftime(statbuf.st_mtime, last_change) > 0.0)
954 last_change = statbuf.st_mtime;
955 latest = res;
956 break; // zzz - (~0 time?)
961 if (latest)
963 static int warned = 0;
964 if (reload_servers(latest->name))
966 my_syslog(LOG_INFO, _("reading %s"), latest->name);
967 warned = 0;
968 check_servers();
969 if ((daemon->options & OPT_RELOAD) && do_reload)
970 clear_cache_and_reload(now);
972 else
974 latest->mtime = 0;
975 if (!warned)
977 my_syslog(LOG_WARNING, _("no servers found in %s, will retry"), latest->name);
978 warned = 1;
984 void clear_cache_and_reload(time_t now)
986 if (daemon->port != 0)
987 cache_reload();
989 #ifdef HAVE_DHCP
990 if (daemon->dhcp)
992 if (daemon->options & OPT_ETHERS)
993 dhcp_read_ethers();
994 reread_dhcp();
995 dhcp_update_configs(daemon->dhcp_conf);
996 check_dhcp_hosts(0);
997 lease_update_from_configs();
998 lease_update_file(now);
999 lease_update_dns();
1001 #endif
1004 static int set_dns_listeners(time_t now, fd_set *set, int *maxfdp)
1006 struct serverfd *serverfdp;
1007 struct listener *listener;
1008 int wait = 0, i;
1010 #ifdef HAVE_TFTP
1011 int tftp = 0;
1012 struct tftp_transfer *transfer;
1013 for (transfer = daemon->tftp_trans; transfer; transfer = transfer->next)
1015 tftp++;
1016 FD_SET(transfer->sockfd, set);
1017 bump_maxfd(transfer->sockfd, maxfdp);
1019 #endif
1021 /* will we be able to get memory? */
1022 if (daemon->port != 0)
1023 get_new_frec(now, &wait);
1025 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1027 FD_SET(serverfdp->fd, set);
1028 bump_maxfd(serverfdp->fd, maxfdp);
1031 if (daemon->port != 0 && !daemon->osport)
1032 for (i = 0; i < RANDOM_SOCKS; i++)
1033 if (daemon->randomsocks[i].refcount != 0)
1035 FD_SET(daemon->randomsocks[i].fd, set);
1036 bump_maxfd(daemon->randomsocks[i].fd, maxfdp);
1039 for (listener = daemon->listeners; listener; listener = listener->next)
1041 /* only listen for queries if we have resources */
1042 if (listener->fd != -1 && wait == 0)
1044 FD_SET(listener->fd, set);
1045 bump_maxfd(listener->fd, maxfdp);
1048 /* death of a child goes through the select loop, so
1049 we don't need to explicitly arrange to wake up here */
1050 if (listener->tcpfd != -1)
1051 for (i = 0; i < MAX_PROCS; i++)
1052 if (daemon->tcp_pids[i] == 0)
1054 FD_SET(listener->tcpfd, set);
1055 bump_maxfd(listener->tcpfd, maxfdp);
1056 break;
1059 #ifdef HAVE_TFTP
1060 if (tftp <= daemon->tftp_max && listener->tftpfd != -1)
1062 FD_SET(listener->tftpfd, set);
1063 bump_maxfd(listener->tftpfd, maxfdp);
1065 #endif
1069 return wait;
1072 static void check_dns_listeners(fd_set *set, time_t now)
1074 struct serverfd *serverfdp;
1075 struct listener *listener;
1076 int i;
1078 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1079 if (FD_ISSET(serverfdp->fd, set))
1080 reply_query(serverfdp->fd, serverfdp->source_addr.sa.sa_family, now);
1082 if (daemon->port != 0 && !daemon->osport)
1083 for (i = 0; i < RANDOM_SOCKS; i++)
1084 if (daemon->randomsocks[i].refcount != 0 &&
1085 FD_ISSET(daemon->randomsocks[i].fd, set))
1086 reply_query(daemon->randomsocks[i].fd, daemon->randomsocks[i].family, now);
1088 for (listener = daemon->listeners; listener; listener = listener->next)
1090 if (listener->fd != -1 && FD_ISSET(listener->fd, set))
1091 receive_query(listener, now);
1093 #ifdef HAVE_TFTP
1094 if (listener->tftpfd != -1 && FD_ISSET(listener->tftpfd, set))
1095 tftp_request(listener, now);
1096 #endif
1098 if (listener->tcpfd != -1 && FD_ISSET(listener->tcpfd, set))
1100 int confd;
1101 struct irec *iface = NULL;
1102 pid_t p;
1104 while((confd = accept(listener->tcpfd, NULL, NULL)) == -1 && errno == EINTR);
1106 if (confd == -1)
1107 continue;
1109 if (daemon->options & OPT_NOWILD)
1110 iface = listener->iface;
1111 else
1113 union mysockaddr tcp_addr;
1114 socklen_t tcp_len = sizeof(union mysockaddr);
1115 /* Check for allowed interfaces when binding the wildcard address:
1116 we do this by looking for an interface with the same address as
1117 the local address of the TCP connection, then looking to see if that's
1118 an allowed interface. As a side effect, we get the netmask of the
1119 interface too, for localisation. */
1121 /* interface may be new since startup */
1122 if (enumerate_interfaces() &&
1123 getsockname(confd, (struct sockaddr *)&tcp_addr, &tcp_len) != -1)
1124 for (iface = daemon->interfaces; iface; iface = iface->next)
1125 if (sockaddr_isequal(&iface->addr, &tcp_addr))
1126 break;
1129 if (!iface)
1131 shutdown(confd, SHUT_RDWR);
1132 close(confd);
1134 #ifndef NO_FORK
1135 else if (!(daemon->options & OPT_DEBUG) && (p = fork()) != 0)
1137 if (p != -1)
1139 int i;
1140 for (i = 0; i < MAX_PROCS; i++)
1141 if (daemon->tcp_pids[i] == 0)
1143 daemon->tcp_pids[i] = p;
1144 break;
1147 close(confd);
1149 #endif
1150 else
1152 unsigned char *buff;
1153 struct server *s;
1154 int flags;
1155 struct in_addr dst_addr_4;
1157 dst_addr_4.s_addr = 0;
1159 #ifndef NO_FORK
1160 /* Arrange for SIGALARM after CHILD_LIFETIME seconds to
1161 terminate the process. */
1162 if (!(daemon->options & OPT_DEBUG))
1163 alarm(CHILD_LIFETIME);
1164 #endif
1166 /* start with no upstream connections. */
1167 for (s = daemon->servers; s; s = s->next)
1168 s->tcpfd = -1;
1170 /* The connected socket inherits non-blocking
1171 attribute from the listening socket.
1172 Reset that here. */
1173 if ((flags = fcntl(confd, F_GETFL, 0)) != -1)
1174 fcntl(confd, F_SETFL, flags & ~O_NONBLOCK);
1176 if (listener->family == AF_INET)
1177 dst_addr_4 = iface->addr.in.sin_addr;
1179 buff = tcp_request(confd, now, dst_addr_4, iface->netmask);
1181 shutdown(confd, SHUT_RDWR);
1182 close(confd);
1184 if (buff)
1185 free(buff);
1187 for (s = daemon->servers; s; s = s->next)
1188 if (s->tcpfd != -1)
1190 shutdown(s->tcpfd, SHUT_RDWR);
1191 close(s->tcpfd);
1193 #ifndef NO_FORK
1194 if (!(daemon->options & OPT_DEBUG))
1196 flush_log();
1197 _exit(0);
1199 #endif
1205 #ifdef HAVE_DHCP
1206 int make_icmp_sock(void)
1208 int fd;
1209 int zeroopt = 0;
1211 if ((fd = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
1213 if (!fix_fd(fd) ||
1214 setsockopt(fd, SOL_SOCKET, SO_DONTROUTE, &zeroopt, sizeof(zeroopt)) == -1)
1216 close(fd);
1217 fd = -1;
1221 return fd;
1224 int icmp_ping(struct in_addr addr)
1226 /* Try and get an ICMP echo from a machine. */
1228 /* Note that whilst in the three second wait, we check for
1229 (and service) events on the DNS and TFTP sockets, (so doing that
1230 better not use any resources our caller has in use...)
1231 but we remain deaf to signals or further DHCP packets. */
1233 int fd;
1234 struct sockaddr_in saddr;
1235 struct {
1236 struct ip ip;
1237 struct icmp icmp;
1238 } packet;
1239 unsigned short id = rand16();
1240 unsigned int i, j;
1241 int gotreply = 0;
1242 time_t start, now;
1244 #if defined(HAVE_LINUX_NETWORK) || defined (HAVE_SOLARIS_NETWORK)
1245 if ((fd = make_icmp_sock()) == -1)
1246 return 0;
1247 #else
1248 int opt = 2000;
1249 fd = daemon->dhcp_icmp_fd;
1250 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1251 #endif
1253 saddr.sin_family = AF_INET;
1254 saddr.sin_port = 0;
1255 saddr.sin_addr = addr;
1256 #ifdef HAVE_SOCKADDR_SA_LEN
1257 saddr.sin_len = sizeof(struct sockaddr_in);
1258 #endif
1260 memset(&packet.icmp, 0, sizeof(packet.icmp));
1261 packet.icmp.icmp_type = ICMP_ECHO;
1262 packet.icmp.icmp_id = id;
1263 for (j = 0, i = 0; i < sizeof(struct icmp) / 2; i++)
1264 j += ((u16 *)&packet.icmp)[i];
1265 while (j>>16)
1266 j = (j & 0xffff) + (j >> 16);
1267 packet.icmp.icmp_cksum = (j == 0xffff) ? j : ~j;
1269 while (sendto(fd, (char *)&packet.icmp, sizeof(struct icmp), 0,
1270 (struct sockaddr *)&saddr, sizeof(saddr)) == -1 &&
1271 retry_send());
1273 for (now = start = dnsmasq_time();
1274 difftime(now, start) < (float)PING_WAIT;)
1276 struct timeval tv;
1277 fd_set rset, wset;
1278 struct sockaddr_in faddr;
1279 int maxfd = fd;
1280 socklen_t len = sizeof(faddr);
1282 tv.tv_usec = 250000;
1283 tv.tv_sec = 0;
1285 FD_ZERO(&rset);
1286 FD_ZERO(&wset);
1287 FD_SET(fd, &rset);
1288 set_dns_listeners(now, &rset, &maxfd);
1289 set_log_writer(&wset, &maxfd);
1291 if (select(maxfd+1, &rset, &wset, NULL, &tv) < 0)
1293 FD_ZERO(&rset);
1294 FD_ZERO(&wset);
1297 now = dnsmasq_time();
1299 check_log_writer(&wset);
1300 check_dns_listeners(&rset, now);
1302 #ifdef HAVE_TFTP
1303 check_tftp_listeners(&rset, now);
1304 #endif
1306 if (FD_ISSET(fd, &rset) &&
1307 recvfrom(fd, &packet, sizeof(packet), 0,
1308 (struct sockaddr *)&faddr, &len) == sizeof(packet) &&
1309 saddr.sin_addr.s_addr == faddr.sin_addr.s_addr &&
1310 packet.icmp.icmp_type == ICMP_ECHOREPLY &&
1311 packet.icmp.icmp_seq == 0 &&
1312 packet.icmp.icmp_id == id)
1314 gotreply = 1;
1315 break;
1319 #if defined(HAVE_LINUX_NETWORK) || defined(HAVE_SOLARIS_NETWORK)
1320 close(fd);
1321 #else
1322 opt = 1;
1323 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1324 #endif
1326 return gotreply;
1328 #endif