Tomato 1.26 beta (1786)
[tomato.git] / release / src / router / dnsmasq / src / dnsmasq.c
blobf2c9d175f574e346107cd0c56f0a800e4e51aa6c
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 #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);
70 static void poll_resolv(void);
72 void tomato_helper(time_t now); // zzz
73 void flush_lease_file(time_t now); // zzz
75 int main (int argc, char **argv)
77 int bind_fallback = 0;
78 time_t now;
79 struct sigaction sigact;
80 struct iname *if_tmp;
81 int piperead, pipefd[2], err_pipe[2];
82 struct passwd *ent_pw = NULL;
83 #if defined(HAVE_DHCP) && defined(HAVE_SCRIPT)
84 uid_t script_uid = 0;
85 gid_t script_gid = 0;
86 #endif
87 struct group *gp = NULL;
88 long i, max_fd = sysconf(_SC_OPEN_MAX);
89 char *baduser = NULL;
90 int log_err;
91 #if defined(HAVE_LINUX_NETWORK)
92 cap_user_header_t hdr = NULL;
93 cap_user_data_t data = NULL;
94 #endif
96 #ifdef LOCALEDIR
97 setlocale(LC_ALL, "");
98 bindtextdomain("dnsmasq", LOCALEDIR);
99 textdomain("dnsmasq");
100 #endif
102 sigact.sa_handler = sig_handler;
103 sigact.sa_flags = 0;
104 sigemptyset(&sigact.sa_mask);
105 sigaction(SIGUSR1, &sigact, NULL);
106 sigaction(SIGUSR2, &sigact, NULL);
107 sigaction(SIGHUP, &sigact, NULL);
108 sigaction(SIGTERM, &sigact, NULL);
109 sigaction(SIGALRM, &sigact, NULL);
110 sigaction(SIGCHLD, &sigact, NULL);
112 /* ignore SIGPIPE */
113 sigact.sa_handler = SIG_IGN;
114 sigaction(SIGPIPE, &sigact, NULL);
116 umask(022); /* known umask, create leases and pid files as 0644 */
118 read_opts(argc, argv, compile_opts);
120 if (daemon->edns_pktsz < PACKETSZ)
121 daemon->edns_pktsz = PACKETSZ;
122 daemon->packet_buff_sz = daemon->edns_pktsz > DNSMASQ_PACKETSZ ?
123 daemon->edns_pktsz : DNSMASQ_PACKETSZ;
124 daemon->packet = safe_malloc(daemon->packet_buff_sz);
126 #ifdef HAVE_DHCP
127 if (!daemon->lease_file)
129 if (daemon->dhcp)
130 daemon->lease_file = LEASEFILE;
132 #endif
134 /* Close any file descriptors we inherited apart from std{in|out|err} */
135 for (i = 0; i < max_fd; i++)
136 if (i != STDOUT_FILENO && i != STDERR_FILENO && i != STDIN_FILENO)
137 close(i);
139 #ifdef HAVE_LINUX_NETWORK
140 netlink_init();
141 #elif !(defined(IP_RECVDSTADDR) && \
142 defined(IP_RECVIF) && \
143 defined(IP_SENDSRCADDR))
144 if (!(daemon->options & OPT_NOWILD))
146 bind_fallback = 1;
147 daemon->options |= OPT_NOWILD;
149 #endif
151 #ifndef HAVE_TFTP
152 if (daemon->options & OPT_TFTP)
153 die(_("TFTP server not available: set HAVE_TFTP in src/config.h"), NULL, EC_BADCONF);
154 #endif
156 #ifdef HAVE_SOLARIS_NETWORK
157 if (daemon->max_logs != 0)
158 die(_("asychronous logging is not available under Solaris"), NULL, EC_BADCONF);
159 #endif
161 rand_init();
163 now = dnsmasq_time();
165 #ifdef HAVE_DHCP
166 if (daemon->dhcp)
168 /* Note that order matters here, we must call lease_init before
169 creating any file descriptors which shouldn't be leaked
170 to the lease-script init process. */
171 lease_init(now);
172 dhcp_init();
174 #endif
176 if (!enumerate_interfaces())
177 die(_("failed to find list of interfaces: %s"), NULL, EC_MISC);
179 if (daemon->options & OPT_NOWILD)
181 daemon->listeners = create_bound_listeners();
183 for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
184 if (if_tmp->name && !if_tmp->used)
185 die(_("unknown interface %s"), if_tmp->name, EC_BADNET);
187 for (if_tmp = daemon->if_addrs; if_tmp; if_tmp = if_tmp->next)
188 if (!if_tmp->used)
190 prettyprint_addr(&if_tmp->addr, daemon->namebuff);
191 die(_("no interface with address %s"), daemon->namebuff, EC_BADNET);
194 else if ((daemon->port != 0 || (daemon->options & OPT_TFTP)) &&
195 !(daemon->listeners = create_wildcard_listeners()))
196 die(_("failed to create listening socket: %s"), NULL, EC_BADNET);
198 if (daemon->port != 0)
199 cache_init();
201 if (daemon->options & OPT_DBUS)
202 #ifdef HAVE_DBUS
204 char *err;
205 daemon->dbus = NULL;
206 daemon->watches = NULL;
207 if ((err = dbus_init()))
208 die(_("DBus error: %s"), err, EC_MISC);
210 #else
211 die(_("DBus not available: set HAVE_DBUS in src/config.h"), NULL, EC_BADCONF);
212 #endif
214 if (daemon->port != 0)
215 pre_allocate_sfds();
217 #if defined(HAVE_DHCP) && defined(HAVE_SCRIPT)
218 /* Note getpwnam returns static storage */
219 if (daemon->dhcp && daemon->lease_change_command && daemon->scriptuser)
221 if ((ent_pw = getpwnam(daemon->scriptuser)))
223 script_uid = ent_pw->pw_uid;
224 script_gid = ent_pw->pw_gid;
226 else
227 baduser = daemon->scriptuser;
229 #endif
231 if (daemon->username && !(ent_pw = getpwnam(daemon->username)))
232 baduser = daemon->username;
233 else if (daemon->groupname && !(gp = getgrnam(daemon->groupname)))
234 baduser = daemon->groupname;
236 if (baduser)
237 die(_("unknown user or group: %s"), baduser, EC_BADCONF);
239 /* implement group defaults, "dip" if available, or group associated with uid */
240 if (!daemon->group_set && !gp)
242 if (!(gp = getgrnam(CHGRP)) && ent_pw)
243 gp = getgrgid(ent_pw->pw_gid);
245 /* for error message */
246 if (gp)
247 daemon->groupname = gp->gr_name;
250 #if defined(HAVE_LINUX_NETWORK)
251 /* determine capability API version here, while we can still
252 call safe_malloc */
253 if (ent_pw && ent_pw->pw_uid != 0)
255 int capsize = 1; /* for header version 1 */
256 hdr = safe_malloc(sizeof(*hdr));
258 /* find version supported by kernel */
259 memset(hdr, 0, sizeof(*hdr));
260 capget(hdr, NULL);
262 if (hdr->version != LINUX_CAPABILITY_VERSION_1)
264 /* if unknown version, use largest supported version (3) */
265 if (hdr->version != LINUX_CAPABILITY_VERSION_2)
266 hdr->version = LINUX_CAPABILITY_VERSION_3;
267 capsize = 2;
270 data = safe_malloc(sizeof(*data) * capsize);
271 memset(data, 0, sizeof(*data) * capsize);
273 #endif
275 /* Use a pipe to carry signals and other events back to the event loop
276 in a race-free manner and another to carry errors to daemon-invoking process */
277 safe_pipe(pipefd, 1);
279 piperead = pipefd[0];
280 pipewrite = pipefd[1];
281 /* prime the pipe to load stuff first time. */
282 send_event(pipewrite, EVENT_RELOAD, 0);
284 err_pipe[1] = -1;
286 if (!(daemon->options & OPT_DEBUG))
288 int nullfd;
290 /* The following code "daemonizes" the process.
291 See Stevens section 12.4 */
293 if (chdir("/") != 0)
294 die(_("cannot chdir to filesystem root: %s"), NULL, EC_MISC);
296 #ifndef NO_FORK
297 if (!(daemon->options & OPT_NO_FORK))
299 pid_t pid;
301 /* pipe to carry errors back to original process.
302 When startup is complete we close this and the process terminates. */
303 safe_pipe(err_pipe, 0);
305 if ((pid = fork()) == -1)
306 /* fd == -1 since we've not forked, never returns. */
307 send_event(-1, EVENT_FORK_ERR, errno);
309 if (pid != 0)
311 struct event_desc ev;
313 /* close our copy of write-end */
314 close(err_pipe[1]);
316 /* check for errors after the fork */
317 if (read_write(err_pipe[0], (unsigned char *)&ev, sizeof(ev), 1))
318 fatal_event(&ev);
320 _exit(EC_GOOD);
323 close(err_pipe[0]);
325 /* NO calls to die() from here on. */
327 setsid();
329 if ((pid = fork()) == -1)
330 send_event(err_pipe[1], EVENT_FORK_ERR, errno);
332 if (pid != 0)
333 _exit(0);
335 #endif
337 /* write pidfile _after_ forking ! */
338 if (daemon->runfile)
340 FILE *pidfile;
342 /* only complain if started as root */
343 if ((pidfile = fopen(daemon->runfile, "w")))
345 fprintf(pidfile, "%d\n", (int) getpid());
346 fclose(pidfile);
348 else if (getuid() == 0)
350 send_event(err_pipe[1], EVENT_PIDFILE, errno);
351 _exit(0);
355 /* open stdout etc to /dev/null */
356 nullfd = open("/dev/null", O_RDWR);
357 dup2(nullfd, STDOUT_FILENO);
358 dup2(nullfd, STDERR_FILENO);
359 dup2(nullfd, STDIN_FILENO);
360 close(nullfd);
363 log_err = log_start(ent_pw, err_pipe[1]);
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->options & OPT_TFTP)
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);
607 #endif
609 #ifdef HAVE_LINUX_NETWORK
610 FD_SET(daemon->netlinkfd, &rset);
611 bump_maxfd(daemon->netlinkfd, &maxfd);
612 #endif
614 FD_SET(piperead, &rset);
615 bump_maxfd(piperead, &maxfd);
617 #ifdef HAVE_DHCP
618 # ifdef HAVE_SCRIPT
619 while (helper_buf_empty() && do_script_run(now));
621 if (!helper_buf_empty())
623 FD_SET(daemon->helperfd, &wset);
624 bump_maxfd(daemon->helperfd, &maxfd);
626 # else
627 /* need this for other side-effects */
628 while (do_script_run(now));
629 # endif
630 #endif
632 /* must do this just before select(), when we know no
633 more calls to my_syslog() can occur */
634 set_log_writer(&wset, &maxfd);
636 if (select(maxfd+1, &rset, &wset, &eset, tp) < 0)
638 /* otherwise undefined after error */
639 FD_ZERO(&rset); FD_ZERO(&wset); FD_ZERO(&eset);
642 now = dnsmasq_time();
644 check_log_writer(&wset);
646 /* Check for changes to resolv files once per second max. */
647 /* Don't go silent for long periods if the clock goes backwards. */
648 if (daemon->last_resolv == 0 ||
649 difftime(now, daemon->last_resolv) > 1.0 ||
650 difftime(now, daemon->last_resolv) < -1.0)
652 daemon->last_resolv = now;
654 if (daemon->port != 0 && !(daemon->options & OPT_NO_POLL))
655 poll_resolv();
658 if (FD_ISSET(piperead, &rset))
659 async_event(piperead, now);
661 #ifdef HAVE_LINUX_NETWORK
662 if (FD_ISSET(daemon->netlinkfd, &rset))
663 netlink_multicast();
664 #endif
666 #ifdef HAVE_DBUS
667 /* if we didn't create a DBus connection, retry now. */
668 if ((daemon->options & OPT_DBUS) && !daemon->dbus)
670 char *err;
671 if ((err = dbus_init()))
672 my_syslog(LOG_WARNING, _("DBus error: %s"), err);
673 if (daemon->dbus)
674 my_syslog(LOG_INFO, _("connected to system DBus"));
676 check_dbus_listeners(&rset, &wset, &eset);
677 #endif
679 check_dns_listeners(&rset, now);
681 #ifdef HAVE_TFTP
682 check_tftp_listeners(&rset, now);
683 #endif
685 #ifdef HAVE_DHCP
686 if (daemon->dhcp && FD_ISSET(daemon->dhcpfd, &rset))
687 dhcp_packet(now);
689 # ifdef HAVE_SCRIPT
690 if (daemon->helperfd != -1 && FD_ISSET(daemon->helperfd, &wset))
691 helper_write();
692 # endif
693 #endif
698 static void sig_handler(int sig)
700 if (pid == 0)
702 /* ignore anything other than TERM during startup
703 and in helper proc. (helper ignore TERM too) */
704 if (sig == SIGTERM)
705 exit(EC_MISC);
707 else if (pid != getpid())
709 /* alarm is used to kill TCP children after a fixed time. */
710 if (sig == SIGALRM)
711 _exit(0);
713 else
715 /* master process */
716 int event, errsave = errno;
718 if (sig == SIGHUP)
719 event = EVENT_RELOAD;
720 else if (sig == SIGCHLD)
721 event = EVENT_CHILD;
722 else if (sig == SIGALRM)
723 event = EVENT_ALARM;
724 else if (sig == SIGTERM)
725 event = EVENT_TERM;
726 else if (sig == SIGUSR1)
727 event = EVENT_DUMP;
728 else if (sig == SIGUSR2)
729 event = EVENT_REOPEN;
730 else
731 return;
733 send_event(pipewrite, event, 0);
734 errno = errsave;
738 void send_event(int fd, int event, int data)
740 struct event_desc ev;
742 ev.event = event;
743 ev.data = data;
745 /* error pipe, debug mode. */
746 if (fd == -1)
747 fatal_event(&ev);
748 else
749 /* pipe is non-blocking and struct event_desc is smaller than
750 PIPE_BUF, so this either fails or writes everything */
751 while (write(fd, &ev, sizeof(ev)) == -1 && errno == EINTR);
754 static void fatal_event(struct event_desc *ev)
756 errno = ev->data;
758 switch (ev->event)
760 case EVENT_DIE:
761 exit(0);
763 case EVENT_FORK_ERR:
764 die(_("cannot fork into background: %s"), NULL, EC_MISC);
766 case EVENT_PIPE_ERR:
767 die(_("failed to create helper: %s"), NULL, EC_MISC);
769 case EVENT_CAP_ERR:
770 die(_("setting capabilities failed: %s"), NULL, EC_MISC);
772 case EVENT_USER_ERR:
773 case EVENT_HUSER_ERR:
774 die(_("failed to change user-id to %s: %s"),
775 ev->event == EVENT_USER_ERR ? daemon->username : daemon->scriptuser,
776 EC_MISC);
778 case EVENT_GROUP_ERR:
779 die(_("failed to change group-id to %s: %s"), daemon->groupname, EC_MISC);
781 case EVENT_PIDFILE:
782 die(_("failed to open pidfile %s: %s"), daemon->runfile, EC_FILE);
784 case EVENT_LOG_ERR:
785 die(_("cannot open %s: %s"), daemon->log_file ? daemon->log_file : "log", EC_FILE);
789 static void async_event(int pipe, time_t now)
791 pid_t p;
792 struct event_desc ev;
793 int i;
795 if (read_write(pipe, (unsigned char *)&ev, sizeof(ev), 1))
796 switch (ev.event)
798 case EVENT_RELOAD:
799 clear_cache_and_reload(now);
800 if (daemon->port != 0 && daemon->resolv_files && (daemon->options & OPT_NO_POLL))
802 reload_servers(daemon->resolv_files->name);
803 check_servers();
805 #ifdef HAVE_DHCP
806 rerun_scripts();
807 #endif
808 break;
810 case EVENT_DUMP:
811 if (daemon->port != 0)
812 dump_cache(now);
813 break;
815 case EVENT_ALARM:
816 #ifdef HAVE_DHCP
817 if (daemon->dhcp)
819 lease_prune(NULL, now);
820 lease_update_file(now);
822 #endif
823 break;
825 case EVENT_CHILD:
826 /* See Stevens 5.10 */
827 while ((p = waitpid(-1, NULL, WNOHANG)) != 0)
828 if (p == -1)
830 if (errno != EINTR)
831 break;
833 else
834 for (i = 0 ; i < MAX_PROCS; i++)
835 if (daemon->tcp_pids[i] == p)
836 daemon->tcp_pids[i] = 0;
837 break;
839 case EVENT_KILLED:
840 my_syslog(LOG_WARNING, _("child process killed by signal %d"), ev.data);
841 break;
843 case EVENT_EXITED:
844 my_syslog(LOG_WARNING, _("child process exited with status %d"), ev.data);
845 break;
847 case EVENT_EXEC_ERR:
848 my_syslog(LOG_ERR, _("failed to execute %s: %s"),
849 daemon->lease_change_command, strerror(ev.data));
850 break;
852 /* necessary for fatal errors in helper */
853 case EVENT_HUSER_ERR:
854 case EVENT_DIE:
855 fatal_event(&ev);
856 break;
858 case EVENT_REOPEN:
859 tomato_helper(now); // zzz
861 /* Note: this may leave TCP-handling processes with the old file still open.
862 Since any such process will die in CHILD_LIFETIME or probably much sooner,
863 we leave them logging to the old file. */
864 if (daemon->log_file != NULL)
865 log_reopen(daemon->log_file);
866 break;
868 case EVENT_TERM:
869 /* Knock all our children on the head. */
870 for (i = 0; i < MAX_PROCS; i++)
871 if (daemon->tcp_pids[i] != 0)
872 kill(daemon->tcp_pids[i], SIGALRM);
874 #if defined(HAVE_DHCP) && defined(HAVE_SCRIPT)
875 /* handle pending lease transitions */
876 if (daemon->helperfd != -1)
878 /* block in writes until all done */
879 if ((i = fcntl(daemon->helperfd, F_GETFL)) != -1)
880 fcntl(daemon->helperfd, F_SETFL, i & ~O_NONBLOCK);
881 do {
882 helper_write();
883 } while (!helper_buf_empty() || do_script_run(now));
884 close(daemon->helperfd);
886 #endif
888 flush_lease_file(now); // zzz
890 if (daemon->lease_stream)
891 fclose(daemon->lease_stream);
893 if (daemon->runfile)
894 unlink(daemon->runfile);
896 my_syslog(LOG_INFO, _("exiting on receipt of SIGTERM"));
897 flush_log();
898 exit(EC_GOOD);
902 static void poll_resolv()
904 struct resolvc *res, *latest;
905 struct stat statbuf;
906 time_t last_change = 0;
907 /* There may be more than one possible file.
908 Go through and find the one which changed _last_.
909 Warn of any which can't be read. */
910 for (latest = NULL, res = daemon->resolv_files; res; res = res->next)
911 if (stat(res->name, &statbuf) == -1)
913 if (!res->logged)
914 my_syslog(LOG_WARNING, _("failed to access %s: %s"), res->name, strerror(errno));
915 res->logged = 1;
917 else
919 res->logged = 0;
920 if (statbuf.st_mtime != res->mtime)
922 res->mtime = statbuf.st_mtime;
923 if (difftime(statbuf.st_mtime, last_change) > 0.0)
925 last_change = statbuf.st_mtime;
926 latest = res;
927 break; // zzz - (~0 time?)
932 if (latest)
934 static int warned = 0;
935 if (reload_servers(latest->name))
937 my_syslog(LOG_INFO, _("reading %s"), latest->name);
938 warned = 0;
939 check_servers();
940 if (daemon->options & OPT_RELOAD)
941 cache_reload();
943 else
945 latest->mtime = 0;
946 if (!warned)
948 my_syslog(LOG_WARNING, _("no servers found in %s, will retry"), latest->name);
949 warned = 1;
955 void clear_cache_and_reload(time_t now)
957 if (daemon->port != 0)
958 cache_reload();
960 #ifdef HAVE_DHCP
961 if (daemon->dhcp)
963 if (daemon->options & OPT_ETHERS)
964 dhcp_read_ethers();
965 reread_dhcp();
966 dhcp_update_configs(daemon->dhcp_conf);
967 check_dhcp_hosts(0);
968 lease_update_from_configs();
969 lease_update_file(now);
970 lease_update_dns();
972 #endif
975 static int set_dns_listeners(time_t now, fd_set *set, int *maxfdp)
977 struct serverfd *serverfdp;
978 struct listener *listener;
979 int wait = 0, i;
981 #ifdef HAVE_TFTP
982 int tftp = 0;
983 struct tftp_transfer *transfer;
984 for (transfer = daemon->tftp_trans; transfer; transfer = transfer->next)
986 tftp++;
987 FD_SET(transfer->sockfd, set);
988 bump_maxfd(transfer->sockfd, maxfdp);
990 #endif
992 /* will we be able to get memory? */
993 if (daemon->port != 0)
994 get_new_frec(now, &wait);
996 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
998 FD_SET(serverfdp->fd, set);
999 bump_maxfd(serverfdp->fd, maxfdp);
1002 if (daemon->port != 0 && !daemon->osport)
1003 for (i = 0; i < RANDOM_SOCKS; i++)
1004 if (daemon->randomsocks[i].refcount != 0)
1006 FD_SET(daemon->randomsocks[i].fd, set);
1007 bump_maxfd(daemon->randomsocks[i].fd, maxfdp);
1010 for (listener = daemon->listeners; listener; listener = listener->next)
1012 /* only listen for queries if we have resources */
1013 if (listener->fd != -1 && wait == 0)
1015 FD_SET(listener->fd, set);
1016 bump_maxfd(listener->fd, maxfdp);
1019 /* death of a child goes through the select loop, so
1020 we don't need to explicitly arrange to wake up here */
1021 if (listener->tcpfd != -1)
1022 for (i = 0; i < MAX_PROCS; i++)
1023 if (daemon->tcp_pids[i] == 0)
1025 FD_SET(listener->tcpfd, set);
1026 bump_maxfd(listener->tcpfd, maxfdp);
1027 break;
1030 #ifdef HAVE_TFTP
1031 if (tftp <= daemon->tftp_max && listener->tftpfd != -1)
1033 FD_SET(listener->tftpfd, set);
1034 bump_maxfd(listener->tftpfd, maxfdp);
1036 #endif
1040 return wait;
1043 static void check_dns_listeners(fd_set *set, time_t now)
1045 struct serverfd *serverfdp;
1046 struct listener *listener;
1047 int i;
1049 for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
1050 if (FD_ISSET(serverfdp->fd, set))
1051 reply_query(serverfdp->fd, serverfdp->source_addr.sa.sa_family, now);
1053 if (daemon->port != 0 && !daemon->osport)
1054 for (i = 0; i < RANDOM_SOCKS; i++)
1055 if (daemon->randomsocks[i].refcount != 0 &&
1056 FD_ISSET(daemon->randomsocks[i].fd, set))
1057 reply_query(daemon->randomsocks[i].fd, daemon->randomsocks[i].family, now);
1059 for (listener = daemon->listeners; listener; listener = listener->next)
1061 if (listener->fd != -1 && FD_ISSET(listener->fd, set))
1062 receive_query(listener, now);
1064 #ifdef HAVE_TFTP
1065 if (listener->tftpfd != -1 && FD_ISSET(listener->tftpfd, set))
1066 tftp_request(listener, now);
1067 #endif
1069 if (listener->tcpfd != -1 && FD_ISSET(listener->tcpfd, set))
1071 int confd;
1072 struct irec *iface = NULL;
1073 pid_t p;
1075 while((confd = accept(listener->tcpfd, NULL, NULL)) == -1 && errno == EINTR);
1077 if (confd == -1)
1078 continue;
1080 if (daemon->options & OPT_NOWILD)
1081 iface = listener->iface;
1082 else
1084 union mysockaddr tcp_addr;
1085 socklen_t tcp_len = sizeof(union mysockaddr);
1086 /* Check for allowed interfaces when binding the wildcard address:
1087 we do this by looking for an interface with the same address as
1088 the local address of the TCP connection, then looking to see if that's
1089 an allowed interface. As a side effect, we get the netmask of the
1090 interface too, for localisation. */
1092 /* interface may be new since startup */
1093 if (enumerate_interfaces() &&
1094 getsockname(confd, (struct sockaddr *)&tcp_addr, &tcp_len) != -1)
1095 for (iface = daemon->interfaces; iface; iface = iface->next)
1096 if (sockaddr_isequal(&iface->addr, &tcp_addr))
1097 break;
1100 if (!iface)
1102 shutdown(confd, SHUT_RDWR);
1103 close(confd);
1105 #ifndef NO_FORK
1106 else if (!(daemon->options & OPT_DEBUG) && (p = fork()) != 0)
1108 if (p != -1)
1110 int i;
1111 for (i = 0; i < MAX_PROCS; i++)
1112 if (daemon->tcp_pids[i] == 0)
1114 daemon->tcp_pids[i] = p;
1115 break;
1118 close(confd);
1120 #endif
1121 else
1123 unsigned char *buff;
1124 struct server *s;
1125 int flags;
1126 struct in_addr dst_addr_4;
1128 dst_addr_4.s_addr = 0;
1130 /* Arrange for SIGALARM after CHILD_LIFETIME seconds to
1131 terminate the process. */
1132 if (!(daemon->options & OPT_DEBUG))
1133 alarm(CHILD_LIFETIME);
1135 /* start with no upstream connections. */
1136 for (s = daemon->servers; s; s = s->next)
1137 s->tcpfd = -1;
1139 /* The connected socket inherits non-blocking
1140 attribute from the listening socket.
1141 Reset that here. */
1142 if ((flags = fcntl(confd, F_GETFL, 0)) != -1)
1143 fcntl(confd, F_SETFL, flags & ~O_NONBLOCK);
1145 if (listener->family == AF_INET)
1146 dst_addr_4 = iface->addr.in.sin_addr;
1148 buff = tcp_request(confd, now, dst_addr_4, iface->netmask);
1150 shutdown(confd, SHUT_RDWR);
1151 close(confd);
1153 if (buff)
1154 free(buff);
1156 for (s = daemon->servers; s; s = s->next)
1157 if (s->tcpfd != -1)
1159 shutdown(s->tcpfd, SHUT_RDWR);
1160 close(s->tcpfd);
1162 #ifndef NO_FORK
1163 if (!(daemon->options & OPT_DEBUG))
1165 flush_log();
1166 _exit(0);
1168 #endif
1174 #ifdef HAVE_DHCP
1175 int make_icmp_sock(void)
1177 int fd;
1178 int zeroopt = 0;
1180 if ((fd = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
1182 if (!fix_fd(fd) ||
1183 setsockopt(fd, SOL_SOCKET, SO_DONTROUTE, &zeroopt, sizeof(zeroopt)) == -1)
1185 close(fd);
1186 fd = -1;
1190 return fd;
1193 int icmp_ping(struct in_addr addr)
1195 /* Try and get an ICMP echo from a machine. */
1197 /* Note that whilst in the three second wait, we check for
1198 (and service) events on the DNS and TFTP sockets, (so doing that
1199 better not use any resources our caller has in use...)
1200 but we remain deaf to signals or further DHCP packets. */
1202 int fd;
1203 struct sockaddr_in saddr;
1204 struct {
1205 struct ip ip;
1206 struct icmp icmp;
1207 } packet;
1208 unsigned short id = rand16();
1209 unsigned int i, j;
1210 int gotreply = 0;
1211 time_t start, now;
1213 #if defined(HAVE_LINUX_NETWORK) || defined (HAVE_SOLARIS_NETWORK)
1214 if ((fd = make_icmp_sock()) == -1)
1215 return 0;
1216 #else
1217 int opt = 2000;
1218 fd = daemon->dhcp_icmp_fd;
1219 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1220 #endif
1222 saddr.sin_family = AF_INET;
1223 saddr.sin_port = 0;
1224 saddr.sin_addr = addr;
1225 #ifdef HAVE_SOCKADDR_SA_LEN
1226 saddr.sin_len = sizeof(struct sockaddr_in);
1227 #endif
1229 memset(&packet.icmp, 0, sizeof(packet.icmp));
1230 packet.icmp.icmp_type = ICMP_ECHO;
1231 packet.icmp.icmp_id = id;
1232 for (j = 0, i = 0; i < sizeof(struct icmp) / 2; i++)
1233 j += ((u16 *)&packet.icmp)[i];
1234 while (j>>16)
1235 j = (j & 0xffff) + (j >> 16);
1236 packet.icmp.icmp_cksum = (j == 0xffff) ? j : ~j;
1238 while (sendto(fd, (char *)&packet.icmp, sizeof(struct icmp), 0,
1239 (struct sockaddr *)&saddr, sizeof(saddr)) == -1 &&
1240 retry_send());
1242 for (now = start = dnsmasq_time();
1243 difftime(now, start) < (float)PING_WAIT;)
1245 struct timeval tv;
1246 fd_set rset, wset;
1247 struct sockaddr_in faddr;
1248 int maxfd = fd;
1249 socklen_t len = sizeof(faddr);
1251 tv.tv_usec = 250000;
1252 tv.tv_sec = 0;
1254 FD_ZERO(&rset);
1255 FD_ZERO(&wset);
1256 FD_SET(fd, &rset);
1257 set_dns_listeners(now, &rset, &maxfd);
1258 set_log_writer(&wset, &maxfd);
1260 if (select(maxfd+1, &rset, &wset, NULL, &tv) < 0)
1262 FD_ZERO(&rset);
1263 FD_ZERO(&wset);
1266 now = dnsmasq_time();
1268 check_log_writer(&wset);
1269 check_dns_listeners(&rset, now);
1271 #ifdef HAVE_TFTP
1272 check_tftp_listeners(&rset, now);
1273 #endif
1275 if (FD_ISSET(fd, &rset) &&
1276 recvfrom(fd, &packet, sizeof(packet), 0,
1277 (struct sockaddr *)&faddr, &len) == sizeof(packet) &&
1278 saddr.sin_addr.s_addr == faddr.sin_addr.s_addr &&
1279 packet.icmp.icmp_type == ICMP_ECHOREPLY &&
1280 packet.icmp.icmp_seq == 0 &&
1281 packet.icmp.icmp_id == id)
1283 gotreply = 1;
1284 break;
1288 #if defined(HAVE_LINUX_NETWORK) || defined(HAVE_SOLARIS_NETWORK)
1289 close(fd);
1290 #else
1291 opt = 1;
1292 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
1293 #endif
1295 return gotreply;
1297 #endif