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