Compare commits

...

5 Commits
v2.9 ... v2.14

Author SHA1 Message Date
Simon Kelley
3be34541c2 import of dnsmasq-2.14.tar.gz 2012-01-05 17:31:10 +00:00
Simon Kelley
9c74ec03ca import of dnsmasq-2.13.tar.gz 2012-01-05 17:31:10 +00:00
Simon Kelley
c1bb85048b import of dnsmasq-2.12.tar.gz 2012-01-05 17:31:10 +00:00
Simon Kelley
dfa666f24b import of dnsmasq-2.11.tar.gz 2012-01-05 17:31:10 +00:00
Simon Kelley
feba5c1d25 import of dnsmasq-2.10.tar.gz 2012-01-05 17:31:10 +00:00
24 changed files with 3102 additions and 1354 deletions

134
CHANGELOG
View File

@@ -1056,3 +1056,137 @@ release 2.9
Allow # as the argument to --domain, meaning "read the
domain from the first search directive in
/etc.resolv.conf". Feature suggested by Evan Jones.
release 2.10
Allow --query-port to be set to a low port by creating and
binding the socket before dropping root. (Suggestion from
Jamie Lokier)
Support TCP queries. It turned out to be possible to do
this with a couple of hundred lines of code, once I knew
how. The executable size went up by a few K on i386.
There are a few limitations: data obtained via TCP is not
cached, and dynamically-created interfaces may break under
certain circumstances. Source-address or query-port
specifications are ignored for TCP.
NAK attempts to renew a DHCP lease where the DHCP range
has changed and the lease is no longer in the allowed
range. Jamie Lokier pointed out this bug.
NAK attempts to renew a pool DHCP lease when a statically
allocated address has become available, forcing a host to
move to it's allocated address. Lots of people have
suggested this change and been rebuffed (they know who
they are) the straws that broke the camel's back were Tim
Cutts and Jamie Lokier.
Remove any nameserver records from answers which are
modified by --alias flags. If the answer is modified, it
cannot any longer be authoritative.
Change behaviour of "bogus-priv" option to return NXDOMAIN
rather than a PTR record with the dotted-quad address as
name. The new behaviour doesn't provoke tcpwrappers like
the old behavior did.
Added a patch for the Suse rpm. That changes the default
group to one suitable for Suse and disables inclusion of
the ISC lease-file reader code. Thanks to Andy Cambeis for
his ongoing work on Suse packaging.
Support forwarding of EDNS.0 The maximum UDP packet size
defaults to 1280, but may be changed with the
--edns-packet-max option. Detect queries with the do bit
set and always forward them, since DNSSEC records are
not cached. This behaviour is required to make
DNSSECbis work properly though dnsmasq. Thanks to Simon
Josefsson for help with this.
Move default config file location under OpenBSD from
/usr/local/etc/dnsmasq.conf to /etc/dnsmasq.conf. Bug
report from Jonathan Weiss.
Use a lease with matching MAC address for a host which
doesn't present a client-id, even if there was a client ID
at some point in the past. This reduces surprises when
changing DHCP clients, adding id:* to a host, and from the
semantics change of /etc/ethers in 2.9. Thanks to Bernard
Sammer for finding that.
Added a "contrib" directory and in it the dnslist utility,
from Thomas Tuttle.
Fixed "fail to start up" problems under Linux with IPv6
enabled. It's not clear that these were an issue in
released versions, but they manifested themselves when TCP
support was added. Thanks to Michael Hamilton for
assistance with this.
version 2.11
Fixed DHCP problem which could result in two leases in the
database with the same address. This looked much more
alarming then it was, since it could only happen when a
machine changes MAC address but kept the same name. The
old lease would persist until it timed out but things
would still work OK.
Check that IP addresses in all dhcp-host directives are
unique and die horribly if they are not, since otherwise
endless protocol loops can occur.
Use IPV6_RECVPKTINFO as socket option rather than
IPV6_PKTINFO where available. This keeps late-model FreeBSD
happy.
Set source interface when replying to IPv6 UDP
queries. This is needed to cope with link-local addresses.
version 2.12
Added extra checks to ensure that DHCP created DNS entries
cannot generate multiple DNS address->name entries. Thanks to
Stefan Monnier for finding the exact set of configuration
options which could create this.
Don't set the the filterwin2k option in the example config
file and add warnings that is breaks Kerberos. Thanks to
Simon Josefsson and Timothy Folks for pointing that out.
Log types of incoming queries as well as source and domain.
Log NODATA replies generated as a result of the
filterwin2k option.
version 2.13
Fixed crash with un-named DHCP hosts introduced in 2.12.
Thanks to Nicolo Wojewoda and Gregory Gathy for bug reports.
version 2.14
Fix DHCP network detection for hosts which talk via a
relay. This makes lease renewal for such hosts work
correctly.
Support RFC3011 subnet selectors in the DHCP server.
Fix DHCP code to generate RFC-compliant responses
to hosts in the INIT-REBOOT state.
In the DHCP server, set the receive buffer size on
the transmit-only packet socket to zero, to avoid
waste of kernel buffers.
Fix DHCP address allocation code to use the whole of
the DHCP range, including the start and end addresses.
Attempt an ICMP "ping" on new addresses before allocating
them to leases, to avoid allocating addresses which are in use.
Handle rfc951 BOOTP as well as DHCP for hosts which have
MAC address to IP address mapping defined.
Fix compilation under MacOS X. Thanks to Chris Tomlinson.
Fix compilation under NetBSD. Thanks to Felix Deichmann.
Added "keep-in-foreground" option. Thanks to Sean
MacLennan for the patch.

32
FAQ
View File

@@ -20,12 +20,10 @@ A: The high ports that dnsmasq opens is for replies from the upstream
Q: Why doesn't dnsmasq support DNS queries over TCP? Don't the RFC's specify
that?
A: Yes, they do, so technically dnsmasq is not RFC-compliant. In practice, the
sorts of queries which dnsmasq is used for are always sent via UDP. Adding
TCP support would make dnsmasq much more heavyweight for no practical
benefit. If you really want to do zone transfers, forward port 53 TCP
using in-kernel port-forwarding or a port-fowarder like rinetd.
A: Update: from version 2.10, it does. There are a few limitations:
data obtained via TCP is not cached, and dynamically-created
interfaces may break under certain circumstances. Source-address
or query-port specifications are ignored for TCP.
Q: When I send SIGUSR1 to dump the contents of the cache, some entries have
no IP address and are for names like mymachine.mydomain.com.mydomain.com.
@@ -74,6 +72,8 @@ A: Use the standard DNS convention of <reversed address>.in-addr.arpa.
For instance to send reverse queries on the range 192.168.0.0 to
192.168.0.255 to a nameserver at 10.0.0.1 do
server=/0.168.192.in-addr.arpa/10.0.0.1
Note that the "bogus-priv" option take priority over this option,
so the above will not work when the bogus-priv option is set.
Q: Dnsmasq fails to start with an error like this: "dnsmasq: bind
failed: Cannot assign requested address". What's the problem?
@@ -190,7 +190,8 @@ A: By default, none of the DHCP clients send the host-name when asking
send with the "hostname" keyword in /etc/network/interfaces. (See
"man interfaces" for details.) That doesn't work for dhclient, were
you have to add something like "send host-name daisy" to
/etc/dhclient.conf
/etc/dhclient.conf [Update: the lastest dhcpcd packages _do_ send
the hostname by default.
Q: I'm network booting my machines, and trying to give them static
DHCP-assigned addresses. The machine gets its correct address
@@ -268,4 +269,21 @@ A: The DNS spec says that the reply to a DNS query must come from the
(address,port) pair when dnsmasq has bound (wildcard,port), hence
the ability to explicitly turn off wildcard binding.
Q: Why doesn't Kerberos work/why can't I get sensible answers to
queries for SRV records.
A: Probably because you have the "filterwin2k" option set. Note that
it was on by default in example configuration files included in
versions before 2.12, so you might have it set on without
realising.
Q: Can I get email notification when a new version of dnsmasq is
released?
A: Yes, new releases of dnsmasq are always announced through
freshmeat.net, and they allow you to subcribe to email alerts when
new versions of particular projects are released.

View File

@@ -10,7 +10,7 @@ all :
@cd $(SRC); $(MAKE) dnsmasq
clean :
rm -f *~ */*~ $(SRC)/*.o $(SRC)/dnsmasq core build
rm -f *~ contrib/*/*~ */*~ $(SRC)/*.o $(SRC)/dnsmasq core build
install : all
install -d $(DESTDIR)$(BINDIR) -d $(DESTDIR)$(MANDIR)/man8

57
contrib/dnslist/dhcp.css Normal file
View File

@@ -0,0 +1,57 @@
body
{
font-family: sans-serif;
color: #000;
}
h1
{
font-size: medium;
font-weight: bold;
}
h1 .updated
{
color: #999;
}
table
{
border-collapse: collapse;
border-bottom: 2px solid #000;
}
th
{
background: #DDD;
border-top: 2px solid #000;
text-align: left;
font-weight: bold;
}
/* Any row */
tr
{
border-top: 2px solid #000;
}
/* Any row but the first or second (overrides above rule) */
tr + tr + tr
{
border-top: 2px solid #999;
}
tr.offline td.hostname
{
color: #999;
}
.hostname { width: 10em; }
.ip_addr { width: 10em; background: #DDD; }
.ether_addr { width: 15em; }
.client_id { width: 15em; background: #DDD; }
.status { width: 5em; }
.since { width: 10em; background: #DDD; }
.lease { width: 10em; }

608
contrib/dnslist/dnslist.pl Executable file
View File

@@ -0,0 +1,608 @@
#!/usr/bin/perl
# dnslist - Read state file from dnsmasq and create a nice web page to display
# a list of DHCP clients.
#
# Copyright (C) 2004 Thomas Tuttle
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTIBILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program*; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# * The license is in fact included at the end of this file, and can
# either be viewed by reading everything after "__DATA__" or by
# running dnslist with the '-l' option.
#
# Version: 0.2
# Author: Thomas Tuttle
# Email: dnslist.20.thinkinginbinary@spamgourmet.org
# License: GNU General Public License, version 2.0
#
# v. 0.0: Too ugly to publish, thrown out.
#
# v. 0.1: First rewrite.
# Added master host list so offline hosts can still be displayed.
# Fixed modification detection (a newer modification time is lower.)
#
# v. 0.2: Fixed Client ID = "*" => "None"
# Fixed HTML entities (a client ID of ????<? screwed it up)
# Fixed command-line argument processing (apparently, "shift @ARGV" !=
# "$_ = shift @ARGV"...)
# Added license information.
use Template;
# Location of state file. (This is the dnsmasq default.)
# Change with -s <file>
my $dnsmasq_state_file = '/var/lib/misc/dnsmasq.leases';
# Location of template. (Assumed to be in current directory.)
# Change with -t <file>
my $html_template_file = 'dnslist.tt2';
# File to write HTML page to. (This is where Slackware puts WWW pages. It may
# be different on other systems. Make sure the permissions are set correctly
# for it.)
my $html_output_file = '/var/www/htdocs/dhcp.html';
# Time to wait after each page update. (The state file is checked for changes
# before each update but is not read in each time, in case it is very big. The
# page is rewritten just so the "(updated __/__ __:__:__)" text changes ;-)
my $wait_time = 2;
# Read command-line arguments.
while ($_ = shift @ARGV) {
if (/-s/) { $dnsmasq_state_file = shift; next; }
if (/-t/) { $html_template_file = shift; next; }
if (/-o/) { $html_output_file = shift; next; }
if (/-d/) { $wait_time = shift; next; }
if (/-l/) { show_license(); exit; }
die "usage: dnslist [-s state_file] [-t template_file] [-o output_file] [-d delay_time]\n";
}
# Master list of clients, offline and online.
my $list = {};
# Sorted host list. (It's actually sorted by IP--the sub &byip() compares two
# IP addresses, octet by octet, and figures out which is higher.)
my @hosts = ();
# Last time the state file was changed.
my $last_state_change;
# Check for a change to the state file.
sub check_state {
if (defined $last_state_change) {
if (-M $dnsmasq_state_file < $last_state_change) {
print "check_state: state file has been changed.\n";
$last_state_change = -M $dnsmasq_state_file;
return 1;
} else {
return 0;
}
} else {
# Last change undefined, so we are running for the first time.
print "check_state: reading state file at startup.\n";
read_state();
$last_state_change = -M $dnsmasq_state_file;
return 1;
}
}
# Read data in state file.
sub read_state {
my $old;
my $new;
# Open file.
unless (open STATE, $dnsmasq_state_file) {
warn "read_state: can't open $dnsmasq_state_file!\n";
return 0;
}
# Mark all hosts as offline, saving old state.
foreach $ether (keys %{$list}) {
$list->{$ether}->{'old_online'} = $list->{$ether}->{'online'};
$list->{$ether}->{'online'} = 0;
}
# Read hosts.
while (<STATE>) {
chomp;
@host{qw/raw_lease ether_addr ip_addr hostname raw_client_id/} = split /\s+/;
$ether = $host{ether_addr};
# Mark each online host as online.
$list->{$ether}->{'online'} = 1;
# Copy data to master list.
foreach $key (keys %host) {
$list->{$ether}->{$key} = $host{$key};
}
}
close STATE;
# Handle changes in offline/online state. (The sub &do_host() handles
# all of the extra stuff to do with a host's data once it is read.
foreach $ether (keys %{$list}) {
$old = $list->{$ether}->{'old_online'};
$new = $list->{$ether}->{'online'};
if (not $old) {
if (not $new) {
do_host($ether, 'offline');
} else {
do_host($ether, 'join');
}
} else {
if (not $new) {
do_host($ether, 'leave');
} else {
do_host($ether, 'online');
}
}
}
# Sort hosts by IP ;-)
@hosts = sort byip values %{$list};
# Copy sorted list to template data store.
$data->{'hosts'} = [ @hosts ];
}
# Do stuff per host.
sub do_host {
my ($ether, $status) = @_;
# Find textual representation of DHCP client ID.
if ($list->{$ether}->{'raw_client_id'} eq '*') {
$list->{$ether}->{'text_client_id'} = 'None';
} else {
my $text = "";
foreach $char (split /:/, $list->{$ether}->{'raw_client_id'}) {
$char = pack('H2', $char);
if (ord($char) >= 32 and ord($char) <= 127) {
$text .= $char;
} else {
$text .= "?";
}
}
$list->{$ether}->{'text_client_id'} = $text;
}
# Convert lease expiration date/time to text.
if ($list->{$ether}->{'raw_lease'} == 0) {
$list->{$ether}->{'text_lease'} = 'Never';
} else {
$list->{$ether}->{'text_lease'} = nice_time($list->{$ether}->{'raw_lease'});
}
if ($status eq 'offline') {
# Nothing to do.
} elsif ($status eq 'online') {
# Nothing to do.
} elsif ($status eq 'join') {
# Update times for joining host.
print "do_host: $ether joined the network.\n";
$list->{$ether}->{'join_time'} = time;
$list->{$ether}->{'since'} = nice_time(time);
} elsif ($status eq 'leave') {
# Update times for leaving host.
print "do_host: $ether left the network.\n";
$list->{$ether}->{'leave_time'} = time;
$list->{$ether}->{'since'} = nice_time(time);
}
}
# Convert time to a string representation.
sub nice_time {
my $time = shift;
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $dst) = localtime($time);
$sec = pad($sec, '0', 2);
$min = pad($min, '0', 2);
$hour = pad($hour, '0', 2);
$mon = pad($mon, '0', 2);
$mday = pad($mday, '0', 2);
return "$mon/$mday $hour:$min:$sec";
}
# Pad string to a certain length by repeatedly prepending another string.
sub pad {
my ($text, $pad, $length) = @_;
while (length($text) < $length) {
$text = "$pad$text";
}
return $text;
}
# Compare two IP addresses. (Uses $a and $b from sort.)
sub byip {
# Split into octets.
my @a = split /\./, $a->{ip_addr};
my @b = split /\./, $b->{ip_addr};
# Compare octets.
foreach $n (0..3) {
return $a[$n] <=> $b[$n] if ($a[$n] != $b[$n]);
}
# If we get here there is no difference.
return 0;
}
# Output HTML file.
sub write_output {
# Create new template object.
my $template = Template->new(
{
ABSOLUTE => 1, # /var/www/... is an absolute path
OUTPUT => $html_output_file # put it here, not STDOUT
}
);
$data->{'updated'} = nice_time(time); # add "(updated ...)" to file
unless ($template->process($html_template_file, $data)) { # do it
warn "write_output: Template Toolkit error: " . $template->error() . "\n";
return 0;
}
print "write_output: page updated.\n";
return 1;
}
sub show_license {
while (<DATA>) {
print;
$line++;
if ($line == 24) { <>; $line = 1; }
}
}
# Main loop.
while (1) {
# Check for state change.
if (check_state()) {
read_state();
sleep 1; # Sleep for a second just so we don't wear anything
# out. (By not sleeping the whole time after a change
# we can detect rapid changes more easily--like if 300
# hosts all come back online, they show up quicker.)
} else {
sleep $wait_time; # Take a nap.
}
write_output(); # Write the file anyway.
}
__DATA__
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.

View File

@@ -0,0 +1,32 @@
<html>
<head>
<title>DHCP Clients</title>
<link rel="stylesheet" href="dhcp.css"/>
<meta http-equiv="Refresh" content="2"/>
</head>
<body>
<h1>DHCP Clients <span class="updated">(updated [% updated %])</span></h1>
<table cols="7">
<tr>
<th class="hostname">Hostname</th>
<th class="ip_addr">IP Address</th>
<th class="ether_addr">Ethernet Address</th>
<th class="client_id">DHCP Client ID</th>
<th class="status">Status</th>
<th class="since">Since</th>
<th class="lease">Lease Expires</th>
</tr>
[% FOREACH host IN hosts %]
<tr class="[% IF host.online %]online[% ELSE %]offline[% END %]">
<td class="hostname">[% host.hostname %]</td>
<td class="ip_addr">[% host.ip_addr %]</td>
<td class="ether_addr">[% host.ether_addr %]</td>
<td class="client_id">[% host.text_client_id %] ([% host.raw_client_id %])</td>
<td class="status">[% IF host.online %]Online[% ELSE %]Offline[% END %]</td>
<td class="since">[% host.since %]</td>
<td class="lease">[% host.text_lease %]</td>
</tr>
[% END %]
</table>
</body>
</html>

View File

@@ -5,7 +5,7 @@
###############################################################################
Name: dnsmasq
Version: 2.9
Version: 2.14
Release: 1
Copyright: GPL
Group: System Environment/Daemons

View File

@@ -5,7 +5,7 @@
###############################################################################
Name: dnsmasq
Version: 2.9
Version: 2.14
Release: 1
Copyright: GPL
Group: Productivity/Networking/DNS/Servers
@@ -16,7 +16,7 @@ Provides: dns_daemon
Conflicts: bind bind8 bind9
PreReq: %fillup_prereq %insserv_prereq
Autoreqprov: on
Source0: %{name}-%{version}.tar.gz
Source0: %{name}-%{version}.tar.bz2
BuildRoot: /var/tmp/%{name}-%{version}
Summary: A lightweight caching nameserver
@@ -39,6 +39,8 @@ leases and BOOTP for network booting of diskless machines.
%prep
%setup -q
patch -p0 <rpm/%{name}-SuSE.patch
%build
%{?suse_update_config:%{suse_update_config -f}}
make
@@ -101,6 +103,7 @@ rm -rf $RPM_BUILD_ROOT
%files
%defattr(-,root,root)
%doc CHANGELOG COPYING FAQ doc.html setup.html UPGRADING_to_2.0 rpm/README.susefirewall
%doc contrib
%config /etc/init.d/dnsmasq
%config /etc/dnsmasq.conf
/usr/sbin/rcdnsmasq

135
dnsmasq.8
View File

@@ -15,12 +15,13 @@ contents of /etc/hosts so that local hostnames
which do not appear in the global DNS can be resolved and also answers
DNS queries for DHCP configured hosts.
.PP
.BR dnsmasq
supports IPv6.
The dnsmasq DHCP server supports static address assignments, multiple
networks, DHCP-relay and RFC3011 subnet specifiers. It automatically
sends a sensible default set of DHCP options, and can be configured to
send any desired set of DHCP options. It also supports BOOTP.
.PP
.BR dnsmasq
is lightweight and easy to configure. It is intended as be run on
small router/firewalls and provide a DNS (and optionally, DHCP) service to a LAN.
Dnsmasq
supports IPv6.
.SH OPTIONS
Note that in general missing parameters are allowed and switch off
functions, for instance "--pid-file=" disables writing a PID file. On
@@ -45,10 +46,15 @@ time-to-live (in seconds) to be given for these replies. This will
reduce the load on the server at the expense of clients using stale
data under some circumstances.
.TP
.B \-k, --keep-in-foreground
Do not go into the background at startup but otherwise run as
normal. This is intended for use when dnsmasq is run under daemontools.
.TP
.B \-d, --no-daemon
Debug mode: don't fork to the background, don't write a pid file,
don't change user id, generate a complete cache dump on receipt on
SIGUSR1, log to stderr as well as syslog.
SIGUSR1, log to stderr as well as syslog, don't fork new processes
to handle TCP queries.
.TP
.B \-q, --log-queries
Log the results of DNS queries handled by dnsmasq. Enable a full cache dump on receipt of SIGUSR1.
@@ -73,19 +79,29 @@ Print the version number.
Listen on <port> instead of the standard DNS port (53). Useful mainly for
debugging.
.TP
.B \-P, --edns-packet-max=<size>
Specify the largest EDNS.0 UDP packet which is supported by the DNS
forwarder. Defaults to 1280, which is the RFC2671-recommended maximum
for ethernet.
.TP
.B \-Q, --query-port=<query_port>
Send outbound DNS queries from, and listen for their replies on, the specific UDP port <query_port> instead of using one chosen at runtime. Useful to simplify your
firewall rules; without this, your firewall would have to allow connections from outside DNS servers to a range of UDP ports, or dynamically adapt to the
port being used by the current dnsmasq instance.
.TP
.B \-i, --interface=<interface name>
Listen only on the specified interface. More than one interface may be specified. Dnsmasq always listens on the loopback (local) interface. If no
.B \-i
flags are given, dnsmasq listens on all available interfaces unless overridden by
.B \-a
Listen only on the specified interface(s). Dnsmasq automatically adds
the loopback (local) interface to the list of interfaces to use when
the
.B \--interface
option is used. If no
.B \--interface
or
.B \-I
flags. If IP alias interfaces (eg "eth1:0") are used with
.B \--listen-address
options are given dnsmasq listens on all available interfaces except any
given in
.B \--except-interface
options. If IP alias interfaces (eg "eth1:0") are used with
.B --interface
or
.B --except-interface
@@ -95,21 +111,30 @@ option will be automatically set. This is required for deeply boring
sockets-API reasons.
.TP
.B \-I, --except-interface=<interface name>
Do not listen on the specified interface.
Do not listen on the specified interface. Note that the order of
.B \--listen-address
.B --interface
and
.B --except-interface
options does not matter and that
.B --except-interface
options always override the others.
.TP
.B \-a, --listen-address=<ipaddr>
Listen only on the given IP address. As with
.B \-i
more than one address may be specified. Unlike
.B \-i
the loopback interface is not special: if dnsmasq is to listen on the loopback interface,
it's IP, 127.0.0.1, must be explicitly given. If no
.B \-a
flags are given, dnsmasq listens on all available interfaces unless overridden by
.B \-i
or
.B \-I
flags.
Listen on the given IP address(es). Both
.B \--interface
and
.B \--listen-address
options may be given, in which case the set of both interfaces and
addresses is used. Note that if no
.B \--interface
option is given, but
.B \--listen-address
is, dnsmasq will not automatically listen on the loopback
interface. To achieve this, its IP address, 127.0.0.1, must be
explicitly given as a
.B \--listen-address
option.
.TP
.B \-z, --bind-interfaces
On systems which support it, dnsmasq binds the wildcard address,
@@ -126,7 +151,8 @@ broadcast packets.
.TP
.B \-b, --bogus-priv
Bogus private reverse lookups. All reverse lookups for private IP ranges (ie 192.168.x.x, etc)
which are not found in /etc/hosts or the DHCP leases file are resolved to the IP address in dotted-quad form.
which are not found in /etc/hosts or the DHCP leases file are answered
with "no such domain" rather than being forwarded upstream.
.TP
.B \-V, --alias=<old-ip>,<new-ip>[,<mask>]
Modify IPv4 addresses returned from upstream nameservers; old-ip is
@@ -421,8 +447,12 @@ in /etc/resolv.conf (or equivalent).
Add the domain-suffix to simple names (without a period) in /etc/hosts
in the same way as for DHCP-derived names.
.SH CONFIG FILE
At startup, dnsmasq reads /etc/dnsmasq.conf, if it exists. (On
FreeBSD and OpenBSD, the file is /usr/local/etc/dnsmasq.conf) The format of this
At startup, dnsmasq reads
.I /etc/dnsmasq.conf,
if it exists. (On
FreeBSD, the file is
.I /usr/local/etc/dnsmasq.conf
) The format of this
file consists of one option per line, exactly as the long options detailed
in the OPTIONS section but without the leading "--". Lines starting with # are comments and ignored. For
options which may only be specified once, the configuration file overrides
@@ -433,10 +463,14 @@ level of nesting is allowed.
.SH NOTES
When it receives a SIGHUP,
.B dnsmasq
clears its cache and then re-loads /etc/hosts. If
clears its cache and then re-loads
.I /etc/hosts.
If
.B
--no-poll
is set SIGHUP also re-reads /etc/resolv.conf. SIGHUP
is set SIGHUP also re-reads
.I /etc/resolv.conf.
SIGHUP
does NOT re-read the configuration file.
.PP
When it receives a SIGUSR1,
@@ -452,25 +486,34 @@ Dnsmasq is a DNS query forwarder: it it not capable of recursively
answering arbitrary queries starting from the root servers but
forwards such queries to a fully recursive upstream DNS server which is
typically provided by an ISP. By default, dnsmasq reads
/etc/resolv.conf to discover the IP
.I /etc/resolv.conf
to discover the IP
addresses of the upstream nameservers it should use, since the
information is typically stored there. Unless
.B --no-poll
is used,
.B dnsmasq
checks the modification time of /etc/resolv.conf (or
equivalent if
checks the modification time of
.I /etc/resolv.conf
(or equivalent if
.B \--resolv-file
is used) and re-reads it if it changes. This allows the DNS servers to
be set dynamically by PPP or DHCP since both protocols provide the
information.
Absence of /etc/resolv.conf is not an error
Absence of
.I /etc/resolv.conf
is not an error
since it may not have been created before a PPP connection exists. Dnsmasq
simply keeps checking in case /etc/resolv.conf is created at any
simply keeps checking in case
.I /etc/resolv.conf
is created at any
time. Dnsmasq can be told to parse more than one resolv.conf
file. This is useful on a laptop, where both PPP and DHCP may be used:
dnsmasq can be set to poll both /etc/ppp/resolv.conf and
/etc/dhcpc/resolv.conf and will use the contents of whichever changed
dnsmasq can be set to poll both
.I /etc/ppp/resolv.conf
and
.I /etc/dhcpc/resolv.conf
and will use the contents of whichever changed
last, giving automatic switching between DNS servers.
.PP
Upstream servers may also be specified on the command line or in
@@ -490,6 +533,22 @@ and run dnsmasq with the
.B \-r /etc/resolv.dnsmasq
option. This second technique allows for dynamic update of the server
addresses by PPP or DHCP.
.PP
The DHCP server in dnsmasq will function as a BOOTP server also,
provided that the MAC address and IP address for clients are given,
either using
.B dhcp-host
configurations or in
.I /etc/ethers
, and a
.B dhcp-range
configuration option is present to activate the DHCP server
on a particular network. The filename
parameter in a BOOTP request is matched against netids in
.B dhcp-option
configurations, allowing some control over the options returned to
different classes of hosts.
.SH FILES
.IR /etc/dnsmasq.conf
@@ -499,6 +558,8 @@ addresses by PPP or DHCP.
.IR /etc/hosts
.IR /etc/ethers
.IR /var/lib/misc/dnsmasq.leases
.IR /var/db/dnsmasq.leases

View File

@@ -12,7 +12,7 @@
#selfmx
#localmx
# The following three options make you a better netizen, since they
# The following two options make you a better netizen, since they
# tell dnsmasq to filter out queries which the public DNS cannot
# answer, and which load the servers (especially the root servers)
# uneccessarily. If you have a dial-on-demand link they also stop
@@ -20,13 +20,16 @@
# Never forward plain names (with a dot or domain part)
domain-needed
# Reply to reverse queries for addresses in the non-routed address
# space with the dotted.quad address
# Never forward addresses in the non-routed address spaces.
bogus-priv
# Filter useless windows-originated DNS requests
filterwin2k
# Uncomment this to filter useless windows-originated DNS requests
# which can trigger dial-on-demand links needlessly.
# Note that (amongst other things) this blocks all SRV requests,
# so don't use it if you use eg Kerberos.
#filterwin2k
# Change this line if you want dns to get its upstream servers from
# somewhere other that /etc/resolv.conf
#resolv-file=

View File

@@ -18,9 +18,11 @@ connected to the internet via a modem, cable-modem or ADSL
connection but would be a good choice for any small network where low
resource use and ease of configuration are important.
<P>
Supported platforms include Linux (with glibc and uclibc), *BSD and
Mac OS X.
Dnsmasq is included in at least the following Linux distributions:
Gentoo, Debian, Slackware, Suse,
Smoothwall, IP-Cop, floppyfw, Firebox, Freesco, CoyoteLinux and
Smoothwall, IP-Cop, floppyfw, Firebox, LEAF, Freesco, CoyoteLinux and
Clarkconnect. It is also available as a FreeBSD port and is used in Linksys wireless routers.
<P>
Dnsmasq provides the following features:
@@ -110,7 +112,9 @@ bzip2 dnsmasq-zzz.tar
</PRE>
<H2>Links.</H2>
Ulrich Ivens has a nice HOWTO in German on installing dnsmasq at <A HREF="http://howto.linux-hardware-shop.de/dnsmasq.html">http://howto.linux-hardware-shop.de/dnsmasq.html</A>
Ulrich Ivens has a nice HOWTO in German on installing dnsmasq at <A
HREF="http://howto.linux-hardware-shop.de/dnsmasq.html">http://howto.linux-hardware-shop.de/dnsmasq.html</A>
and Damien Raude-Morvan has one in French at <A HREF="http://www.drazzib.com/docs-dnsmasq.html">http://www.drazzib.com/docs-dnsmasq.html</A>
<H2>License.</H2>
Dnsmasq is distributed under the GPL. See the file COPYING in the distribution

42
rpm/dnsmasq-SuSE.patch Normal file
View File

@@ -0,0 +1,42 @@
--- dnsmasq.8 2004-08-08 20:57:56.000000000 +0200
+++ dnsmasq.8 2004-08-12 00:40:01.000000000 +0200
@@ -63,7 +63,7 @@
.TP
.B \-g, --group=<groupname>
Specify the group which dnsmasq will run
-as. The defaults to "dip", if available, to facilitate access to
+as. The defaults to "dialout", if available, to facilitate access to
/etc/ppp/resolv.conf which is not normally world readable.
.TP
.B \-v, --version
--- dnsmasq.conf.example 2004-08-08 21:18:26.000000000 +0200
+++ dnsmasq.conf.example 2004-08-12 00:40:01.000000000 +0200
@@ -65,7 +65,7 @@
# You no longer (as of version 1.7) need to set these to enable
# dnsmasq to read /etc/ppp/resolv.conf since dnsmasq now uses the
-# "dip" group to achieve this.
+# "dialout" group to achieve this.
#user=
#group=
--- src/config.h 2004-08-11 11:39:18.000000000 +0200
+++ src/config.h 2004-08-12 00:40:01.000000000 +0200
@@ -44,7 +44,7 @@
#endif
#define DEFLEASE 3600 /* default lease time, 1 hour */
#define CHUSER "nobody"
-#define CHGRP "dip"
+#define CHGRP "dialout"
#define IP6INTERFACES "/proc/net/if_inet6"
#define UPTIME "/proc/uptime"
#define DHCP_SERVER_PORT 67
@@ -176,7 +176,7 @@
/* platform independent options. */
#undef HAVE_BROKEN_RTC
-#define HAVE_ISC_READER
+#undef HAVE_ISC_READER
#if defined(HAVE_BROKEN_RTC) && defined(HAVE_ISC_READER)
# error HAVE_ISC_READER is not compatible with HAVE_BROKEN_RTC

View File

@@ -226,7 +226,7 @@ void cache_insert(char *name, struct all_addr *addr,
union bigname *big_name = NULL;
int freed_all = flags & F_REVERSE;
log_query(flags | F_UPSTREAM, name, addr);
log_query(flags | F_UPSTREAM, name, addr, 0);
/* name is needed as workspace by log_query in this case */
if ((flags & F_NEG) && (flags & F_REVERSE))
@@ -633,36 +633,45 @@ void cache_unhash_dhcp(void)
dhcp_inuse = NULL;
}
void cache_add_dhcp_entry(char *host_name, struct in_addr *host_address, time_t ttd, unsigned short flags)
void cache_add_dhcp_entry(char *host_name, struct in_addr *host_address, time_t ttd)
{
struct crec *crec;
unsigned short flags = F_DHCP | F_FORWARD | F_IPV4 | F_REVERSE;
if (!host_name)
return;
if ((crec = cache_find_by_name(NULL, host_name, 0, F_IPV4)))
{
if (crec->flags & F_HOSTS)
{
if (crec->addr.addr.addr4.s_addr != host_address->s_addr)
syslog(LOG_WARNING, "not naming DHCP lease for %s because it clashes with an /etc/hosts entry.", host_name);
return;
}
else if (!(crec->flags & F_DHCP))
{
if (crec->flags & F_NEG)
if (!(crec->flags & F_NEG))
{
/* name may have been searched for before being allocated to DHCP and
therefore got a negative cache entry. If so delete it and continue. */
cache_scan_free(host_name, NULL, 0, F_IPV4 | F_FORWARD);
goto newrec;
syslog(LOG_WARNING, "not naming DHCP lease for %s because it clashes with a cached name.", host_name);
return;
}
else
syslog(LOG_WARNING, "not naming DHCP lease for %s because it clashes with a cached name.", cache_get_name(crec));
/* name may have been searched for before being allocated to DHCP and
therefore got a negative cache entry. If so delete it and continue. */
cache_scan_free(host_name, NULL, 0, F_IPV4 | F_FORWARD);
}
return;
}
if ((crec = cache_find_by_addr(NULL, (struct all_addr *)host_address, 0, F_IPV4)) && (crec->flags & F_NEG))
cache_scan_free(NULL, (struct all_addr *)host_address, 0, F_IPV4 | F_REVERSE);
newrec:
if ((crec = cache_find_by_addr(NULL, (struct all_addr *)host_address, 0, F_IPV4)))
{
if (crec->flags & F_NEG)
cache_scan_free(NULL, (struct all_addr *)host_address, 0, F_IPV4 | F_REVERSE);
else
/* avoid multiple reverse mappings */
flags &= ~F_REVERSE;
}
if ((crec = dhcp_spare))
dhcp_spare = dhcp_spare->prev;
else /* need new one */
@@ -670,7 +679,7 @@ void cache_add_dhcp_entry(char *host_name, struct in_addr *host_address, time_t
if (crec) /* malloc may fail */
{
crec->flags = F_DHCP | F_FORWARD | F_IPV4 | flags;
crec->flags = flags;
if (ttd == 0)
crec->flags |= F_IMMORTAL;
else
@@ -734,20 +743,23 @@ void dump_cache(int debug, int cache_size)
cache->flags & F_IMMORTAL ? "\n" : ctime(&(cache->ttd))) ;
#endif
}
}
}
}
void log_query(unsigned short flags, char *name, struct all_addr *addr)
void log_query(unsigned short flags, char *name, struct all_addr *addr, unsigned short type)
{
char *source;
char *verb = "is";
char types[20];
char addrbuff[ADDRSTRLEN];
if (!log_queries)
return;
strcpy(types, " ");
if (flags & F_NEG)
{
if (flags & F_REVERSE)
@@ -796,6 +808,47 @@ void log_query(unsigned short flags, char *name, struct all_addr *addr)
}
else if (flags & F_QUERY)
{
unsigned int i;
static struct {
unsigned int type;
char *name;
} typestr[] = {
{ 1, "A" },
{ 2, "NS" },
{ 5, "CNAME" },
{ 6, "SOA" },
{ 10, "NULL" },
{ 11, "WKS" },
{ 12, "PTR" },
{ 13, "HINFO" },
{ 15, "MX" },
{ 16, "TXT" },
{ 22, "NSAP" },
{ 23, "NSAP_PTR" },
{ 24, "SIG" },
{ 25, "KEY" },
{ 28, "AAAA" },
{ 33, "SRV" },
{ 36, "KX" },
{ 37, "CERT" },
{ 38, "A6" },
{ 39, "DNAME" },
{ 41, "OPT" },
{ 250, "TSIG" },
{ 251, "IXFR" },
{ 252, "AXFR" },
{ 253, "MAILB" },
{ 254, "MAILA" },
{ 255, "ANY" }
};
if (type != 0)
{
sprintf(types, "[type=%d] ", type);
for (i = 0; i < (sizeof(typestr)/sizeof(typestr[0])); i++)
if (typestr[i].type == type)
sprintf(types,"[%s] ", typestr[i].name);
}
source = "query";
verb = "from";
}
@@ -803,7 +856,7 @@ void log_query(unsigned short flags, char *name, struct all_addr *addr)
source = "cached";
if ((flags & F_FORWARD) | (flags & F_NEG))
syslog(LOG_DEBUG, "%s %s %s %s", source, name, verb, addrbuff);
syslog(LOG_DEBUG, "%s %s%s%s %s", source, name, types, verb, addrbuff);
else if (flags & F_REVERSE)
syslog(LOG_DEBUG, "%s %s is %s", source, addrbuff, name);
}

View File

@@ -12,10 +12,13 @@
/* Author's email: simon@thekelleys.org.uk */
#define VERSION "2.9"
#define VERSION "2.14"
#define FTABSIZ 150 /* max number of outstanding requests */
#define TIMEOUT 20 /* drop queries after TIMEOUT seconds */
#define MAX_PROCS 20 /* max no children for TCP requests */
#define CHILD_LIFETIME 150 /* secs 'till terminated (RFC1035 suggests > 120s) */
#define EDNS_PKTSZ 1280 /* default max EDNS.0 UDP packet from RFC2671 */
#define TIMEOUT 20 /* drop UDP queries after TIMEOUT seconds */
#define LOGRATE 120 /* log table overflows every LOGRATE seconds */
#define CACHESIZ 150 /* default cache size */
#define MAXTOK 50 /* token in DHCP leases */
@@ -31,9 +34,12 @@
#define RUNFILE "/var/run/dnsmasq.pid"
#if defined(__FreeBSD__) || defined (__OpenBSD__)
# define LEASEFILE "/var/db/dnsmasq.leases"
# define CONFFILE "/usr/local/etc/dnsmasq.conf"
#else
# define LEASEFILE "/var/lib/misc/dnsmasq.leases"
#endif
#if defined(__FreeBSD__)
# define CONFFILE "/usr/local/etc/dnsmasq.conf"
#else
# define CONFFILE "/etc/dnsmasq.conf"
#endif
#define DEFLEASE 3600 /* default lease time, 1 hour */
@@ -58,12 +64,21 @@
# define DNSMASQ_LOG_FAC(debug) LOG_DAEMON
#endif
/* A small collection of RR-types which are missing on some platforms */
#ifndef T_SRV
# define T_SRV 33
#endif
#ifndef T_OPT
# define T_OPT 41
#endif
/* Decide if we're going to support IPv6 */
/* We assume that systems which don't have IPv6
headers don't have ntop and pton either */
#if defined(INET6_ADDRSTRLEN) && !defined(NO_IPV6)
#if defined(INET6_ADDRSTRLEN) && defined(IPV6_V6ONLY) && !defined(NO_IPV6)
# define HAVE_IPV6
# define ADDRSTRLEN INET6_ADDRSTRLEN
# if defined(SOL_IPV6)
@@ -89,7 +104,6 @@
new system, you may want to edit these.
May replace this with Autoconf one day.
HAVE_LINUX_IPV6_PROC
define this to do IPv6 interface discovery using
proc/net/if_inet6 ala LINUX.
@@ -213,7 +227,6 @@ NOTES:
#undef HAVE_SOCKADDR_SA_LEN
#undef HAVE_PSELECT
/* Fix various misfeatures of libc5 headers */
#define T_SRV 33
typedef unsigned long in_addr_t;
typedef size_t socklen_t;
@@ -262,9 +275,8 @@ typedef unsigned long in_addr_t;
#define BIND_8_COMPAT
/* Define before sys/socket.h is included so we get socklen_t */
#define _BSD_SOCKLEN_T_
/* The two below are not defined in Mac OS X arpa/nameserv.h */
/* The three below are not defined in Mac OS X arpa/nameserv.h */
#define IN6ADDRSZ 16
#define T_SRV 33
#elif defined(__NetBSD__)
#undef HAVE_LINUX_IPV6_PROC

View File

@@ -14,61 +14,91 @@
#include "dnsmasq.h"
void dhcp_init(int *fdp, int* rfdp)
void dhcp_init(struct daemon *daemon)
{
int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
struct sockaddr_in saddr;
int opt = 1;
int oneopt = 1, zeroopt = 0;
struct dhcp_config *configs, *cp;
if (fd == -1)
die ("cannot create DHCP socket : %s", NULL);
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
if (
#if defined(IP_PKTINFO)
setsockopt(fd, SOL_IP, IP_PKTINFO, &opt, sizeof(opt)) == -1 ||
setsockopt(fd, SOL_IP, IP_PKTINFO, &oneopt, sizeof(oneopt)) == -1 ||
#elif defined(IP_RECVIF)
setsockopt(fd, IPPROTO_IP, IP_RECVIF, &opt, sizeof(opt)) == -1 ||
setsockopt(fd, IPPROTO_IP, IP_RECVIF, &oneopt, sizeof(oneopt)) == -1 ||
#endif
setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &opt, sizeof(opt)) == -1)
setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &oneopt, sizeof(oneopt)) == -1)
die("failed to set options on DHCP socket: %s", NULL);
saddr.sin_family = AF_INET;
saddr.sin_port = htons(DHCP_SERVER_PORT);
saddr.sin_addr.s_addr = INADDR_ANY;
#ifdef HAVE_SOCKADDR_SA_LEN
saddr.sin_len = sizeof(struct sockaddr_in);
#endif
if (bind(fd, (struct sockaddr *)&saddr, sizeof(struct sockaddr_in)))
die("failed to bind DHCP server socket: %s", NULL);
*fdp = fd;
daemon->dhcpfd = fd;
if ((fd = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP)) == -1 ||
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &oneopt, sizeof(oneopt)) ||
setsockopt(fd, SOL_SOCKET, SO_DONTROUTE, &zeroopt, sizeof(zeroopt)) == -1)
die("cannot create ICMP raw socket: %s.", NULL);
daemon->dhcp_icmp_fd = fd;
#ifdef HAVE_BPF
opt = 0;
while (1)
{
char filename[50];
sprintf(filename, "/dev/bpf%d", opt++);
if ((fd = open(filename, O_RDWR, 0)) != -1)
break;
if (errno != EBUSY)
die("cannot create DHCP BPF socket: %s", NULL);
}
{
int i = 0;
while (1)
{
char filename[50];
sprintf(filename, "/dev/bpf%d", i++);
if ((fd = open(filename, O_RDWR, 0)) != -1)
break;
if (errno != EBUSY)
die("cannot create DHCP BPF socket: %s", NULL);
}
}
#else
if ((fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETHERTYPE_IP))) == -1)
die("cannot create DHCP packet socket: %s", NULL);
/* since we don't ever use the packet socket for reception,
and it receives copies of _all_ IP packets, then that data
will build up in kernel buffers, wasting memory. Set the
socket receive buffer size to one to avoid that. (zero is
rejected as non-sensical by some BSD kernels) */
if ((fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETHERTYPE_IP))) == -1 ||
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &oneopt, sizeof(oneopt)) == -1)
die("cannot create DHCP packet socket: %s. "
"Is CONFIG_PACKET enabled in your kernel?", NULL);
#endif
*rfdp = fd;
daemon->dhcp_raw_fd = fd;
/* If the same IP appears in more than one host config, then DISCOVER
for one of the hosts will get the address, but REQUEST will be NAKed,
since the address is reserved by the other one -> protocol loop. */
for (configs = daemon->dhcp_conf; configs; configs = configs->next)
for (cp = configs->next; cp; cp = cp->next)
if ((configs->flags & cp->flags & CONFIG_ADDR) && configs->addr.s_addr == cp->addr.s_addr)
die("duplicate IP address %s in dhcp-config directive.", inet_ntoa(cp->addr));
daemon->dhcp_packet = safe_malloc(sizeof(struct udp_dhcp_packet));
/* These two each hold a DHCP option max size 256
and get a terminating zero added */
daemon->dhcp_buff = safe_malloc(257);
daemon->dhcp_buff2 = safe_malloc(257);
}
void dhcp_packet(struct dhcp_context *contexts, char *packet,
struct dhcp_opt *dhcp_opts, struct dhcp_config *dhcp_configs,
struct dhcp_vendor *vendors,
time_t now, char *namebuff, char *domain_suffix,
char *dhcp_file, char *dhcp_sname,
struct in_addr dhcp_next_server, int dhcp_fd, int raw_fd,
struct iname *names, struct iname *addrs, struct iname *except)
void dhcp_packet(struct daemon *daemon, time_t now)
{
struct udp_dhcp_packet *rawpacket = (struct udp_dhcp_packet *)packet;
struct dhcp_packet *mess = (struct dhcp_packet *)&rawpacket->data;
struct udp_dhcp_packet *rawpacket = daemon->dhcp_packet;
struct dhcp_packet *mess = &rawpacket->data;
struct dhcp_context *context;
struct iname *tmp;
struct ifreq ifr;
@@ -76,8 +106,7 @@ void dhcp_packet(struct dhcp_context *contexts, char *packet,
struct iovec iov[2];
struct cmsghdr *cmptr;
int sz, newlen, iface_index = 0;
struct in_addr source, iface_netmask, iface_addr, iface_broadcast;
struct in_addr netmask_save, broadcast_save, router;
struct in_addr iface_netmask, iface_addr, iface_broadcast;
#ifdef HAVE_BPF
unsigned char iface_hwaddr[ETHER_ADDR_LEN];
#endif
@@ -91,8 +120,8 @@ void dhcp_packet(struct dhcp_context *contexts, char *packet,
#endif
} control_u;
iov[0].iov_base = (char *)&rawpacket->data;
iov[0].iov_len = DNSMASQ_PACKETSZ - (sizeof(struct ip) + sizeof(struct udphdr));
iov[0].iov_base = (char *)mess;
iov[0].iov_len = sizeof(struct dhcp_packet);
msg.msg_control = control_u.control;
msg.msg_controllen = sizeof(control_u);
@@ -102,7 +131,7 @@ void dhcp_packet(struct dhcp_context *contexts, char *packet,
msg.msg_iov = iov;
msg.msg_iovlen = 1;
sz = recvmsg(dhcp_fd, &msg, 0);
sz = recvmsg(daemon->dhcpfd, &msg, 0);
if (sz < (int)(sizeof(*mess) - sizeof(mess->options)))
return;
@@ -115,7 +144,7 @@ void dhcp_packet(struct dhcp_context *contexts, char *packet,
iface_index = ((struct in_pktinfo *)CMSG_DATA(cmptr))->ipi_ifindex;
if (!(ifr.ifr_ifindex = iface_index) ||
ioctl(dhcp_fd, SIOCGIFNAME, &ifr) == -1)
ioctl(daemon->dhcpfd, SIOCGIFNAME, &ifr) == -1)
return;
#elif defined(IP_RECVIF)
@@ -129,35 +158,37 @@ void dhcp_packet(struct dhcp_context *contexts, char *packet,
return;
#else
while (names->isloop)
names = names->next;
strcpy(ifr.ifr_name, names->name);
{
struct iname *name;
for (name = daemon->if_names; names->isloop; names = names->next);
strcpy(ifr.ifr_name, name->name);
}
#endif
#ifdef HAVE_BPF
ifr.ifr_addr.sa_family = AF_LINK;
if (ioctl(dhcp_fd, SIOCGIFADDR, &ifr) < 0)
if (ioctl(daemon->dhcpfd, SIOCGIFADDR, &ifr) < 0)
return;
memcpy(iface_hwaddr, LLADDR((struct sockaddr_dl *)&ifr.ifr_addr), ETHER_ADDR_LEN);
#endif
ifr.ifr_addr.sa_family = AF_INET;
if (ioctl(dhcp_fd, SIOCGIFADDR, &ifr) < 0 )
if (ioctl(daemon->dhcpfd, SIOCGIFADDR, &ifr) < 0 )
return;
iface_addr = ((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr;
/* enforce available interface configuration */
for (tmp = except; tmp; tmp = tmp->next)
for (tmp = daemon->if_except; tmp; tmp = tmp->next)
if (tmp->name && (strcmp(tmp->name, ifr.ifr_name) == 0))
return;
if (names || addrs)
if (daemon->if_names || daemon->if_addrs)
{
for (tmp = names; tmp; tmp = tmp->next)
for (tmp = daemon->if_names; tmp; tmp = tmp->next)
if (tmp->name && (strcmp(tmp->name, ifr.ifr_name) == 0))
break;
if (!tmp)
for (tmp = addrs; tmp; tmp = tmp->next)
for (tmp = daemon->if_addrs; tmp; tmp = tmp->next)
if (tmp->addr.sa.sa_family == AF_INET &&
tmp->addr.in.sin_addr.s_addr == iface_addr.s_addr)
break;
@@ -165,90 +196,71 @@ void dhcp_packet(struct dhcp_context *contexts, char *packet,
return;
}
/* If the packet came via a relay, use that address to look up the context,
else use the address of the interface is arrived on. */
source = mess->giaddr.s_addr ? mess->giaddr : iface_addr;
iface_netmask.s_addr = 0;
iface_broadcast.s_addr = 0;
if (ioctl(dhcp_fd, SIOCGIFNETMASK, &ifr) != -1)
{
iface_netmask = ((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr;
/* we can use the interface netmask if either the packet came direct,
or it came via a relay listening on the same network. This sounds unlikely,
but it happens with win4lin. */
if (!is_same_net(source, iface_addr, iface_netmask))
iface_netmask.s_addr = 0;
else if (ioctl(dhcp_fd, SIOCGIFBRDADDR, &ifr) != -1)
iface_broadcast = ((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr;
}
for (context = contexts; context; context = context->next)
iface_netmask.s_addr = 0;
iface_broadcast.s_addr = 0;
for (context = daemon->dhcp; context; context = context->next)
{
struct in_addr netmask = context->netmask.s_addr ? context->netmask : iface_netmask;
if (netmask.s_addr &&
is_same_net(source, context->start, netmask) &&
is_same_net(source, context->end, netmask))
break;
/* Fill in missing netmask and broadcast address values for any approriate
dhcp-ranges which match this interface and don't have them. */
if (!context->netmask.s_addr)
{
if (!iface_netmask.s_addr && ioctl(daemon->dhcpfd, SIOCGIFNETMASK, &ifr) != -1)
iface_netmask = ((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr;
if (iface_netmask.s_addr &&
is_same_net(iface_addr, context->start, iface_netmask) &&
is_same_net(iface_addr, context->end, iface_netmask))
context->netmask = iface_netmask;
}
/* Determine "default" default routes. These are to this server or the relay agent.
Also broadcast addresses, if not specified */
if (context->netmask.s_addr)
{
if (is_same_net(iface_addr, context->start, context->netmask))
{
if (!context->router.s_addr)
context->router = iface_addr;
if (!context->broadcast.s_addr)
{
if (!iface_broadcast.s_addr && ioctl(daemon->dhcpfd, SIOCGIFBRDADDR, &ifr) != -1)
iface_broadcast = ((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr;
if (iface_broadcast.s_addr)
context->broadcast = iface_broadcast;
else
context->broadcast.s_addr = context->start.s_addr | ~context->netmask.s_addr;
}
}
else if (mess->giaddr.s_addr && is_same_net(mess->giaddr, context->start, context->netmask))
{
if (!context->router.s_addr)
context->router = mess->giaddr;
/* fill in missing broadcast addresses for relayed ranges */
if (!context->broadcast.s_addr)
context->broadcast.s_addr = context->start.s_addr | ~context->netmask.s_addr;
}
}
}
if (!context)
{
syslog(LOG_WARNING, "no address range available for DHCP request via %s", inet_ntoa(source));
return;
}
netmask_save = context->netmask;
broadcast_save = context->broadcast;
if (!context->netmask.s_addr)
context->netmask = iface_netmask;
if (!context->broadcast.s_addr)
{
if (iface_broadcast.s_addr)
context->broadcast = iface_broadcast;
else
context->broadcast.s_addr = (source.s_addr & context->netmask.s_addr) | ~context->netmask.s_addr;
}
if (ioctl(dhcp_fd, SIOCGIFMTU, &ifr) == -1)
ifr.ifr_mtu = ETHERMTU;
/* Normally, we set the default route to point to the machine which is getting the
DHCP broadcast, either this machine or a relay. In the special case that the relay
is on the same network as us, we set the default route to us, not the relay.
This is the win4lin scenario again. */
if (is_same_net(source, iface_addr, context->netmask))
router = iface_addr;
else
router = source;
lease_prune(NULL, now); /* lose any expired leases */
newlen = dhcp_reply(context, iface_addr, ifr.ifr_name, ifr.ifr_mtu,
rawpacket, sz, now, namebuff,
dhcp_opts, dhcp_configs, vendors, domain_suffix,
dhcp_file, dhcp_sname, dhcp_next_server, router);
newlen = dhcp_reply(daemon, iface_addr, ifr.ifr_name, sz, now);
lease_update_file(0, now);
lease_update_dns();
context->netmask = netmask_save;
context->broadcast = broadcast_save;
if (newlen == 0)
return;
if (mess->giaddr.s_addr || mess->ciaddr.s_addr)
{
/* To send to BOOTP relay or configured client, use
the IP packet */
/* To send to BOOTP relay or configured client, use the IP packet */
struct sockaddr_in dest;
dest.sin_family = AF_INET;
#ifdef HAVE_SOCKADDR_SA_LEN
dest.sin_len = sizeof(struct sockaddr_in);
#endif
if (mess->giaddr.s_addr)
{
dest.sin_port = htons(DHCP_SERVER_PORT);
@@ -260,7 +272,7 @@ void dhcp_packet(struct dhcp_context *contexts, char *packet,
dest.sin_addr = mess->ciaddr;
}
sendto(dhcp_fd, mess, newlen, 0, (struct sockaddr *)&dest, sizeof(dest));
sendto(daemon->dhcpfd, mess, newlen, 0, (struct sockaddr *)&dest, sizeof(dest));
}
else
{
@@ -324,13 +336,13 @@ void dhcp_packet(struct dhcp_context *contexts, char *packet,
memcpy(header.ether_shost, iface_hwaddr, ETHER_ADDR_LEN);
memcpy(header.ether_dhost, hwdest, ETHER_ADDR_LEN);
ioctl(raw_fd, BIOCSETIF, &ifr);
ioctl(daemon->dhcp_raw_fd, BIOCSETIF, &ifr);
iov[0].iov_base = (char *)&header;
iov[0].iov_len = sizeof(struct ether_header);
iov[1].iov_base = (char *)rawpacket;
iov[1].iov_len = ntohs(rawpacket->ip.ip_len);
writev(raw_fd, iov, 2);
writev(daemon->dhcp_raw_fd, iov, 2);
#else
struct sockaddr_ll dest;
@@ -339,7 +351,7 @@ void dhcp_packet(struct dhcp_context *contexts, char *packet,
dest.sll_ifindex = iface_index;
dest.sll_protocol = htons(ETHERTYPE_IP);
memcpy(dest.sll_addr, hwdest, ETHER_ADDR_LEN);
sendto(raw_fd, rawpacket, ntohs(rawpacket->ip.ip_len),
sendto(daemon->dhcp_raw_fd, rawpacket, ntohs(rawpacket->ip.ip_len),
0, (struct sockaddr *)&dest, sizeof(dest));
#endif
@@ -354,67 +366,75 @@ int address_available(struct dhcp_context *context, struct in_addr taddr)
unsigned int addr, start, end;
/* static leases only. */
if (context->static_only)
return 0;
addr = ntohl(taddr.s_addr);
start = ntohl(context->start.s_addr);
end = ntohl(context->end.s_addr);
/* static leases only. */
if (start == end)
return 0;
if (addr < start)
return 0;
if (addr > end)
return 0;
if (lease_find_by_addr(taddr))
return 0;
return 1;
}
struct dhcp_config *config_find_by_address(struct dhcp_config *configs, struct in_addr addr)
{
struct dhcp_config *config;
for (config = configs; config; config = config->next)
if ((config->flags & CONFIG_ADDR) && config->addr.s_addr == addr.s_addr)
return config;
int address_allocate(struct dhcp_context *context, struct dhcp_config *configs,
return NULL;
}
int address_allocate(struct dhcp_context *context, struct daemon *daemon,
struct in_addr *addrp, unsigned char *hwaddr)
{
/* Find a free address: exlude anything in use and anything allocated to
/* Find a free address: exclude anything in use and anything allocated to
a particular hwaddr/clientid/hostname in our configuration */
struct dhcp_config *config;
struct in_addr start, addr ;
int i, j;
unsigned int i, j;
/* start == end means no dynamic leases. */
if (context->end.s_addr == context->start.s_addr)
/* check if no dynamic leases. */
if (context->static_only)
return 0;
/* pick a seed based on hwaddr then iterate until we find a free address. */
for (j = 0, i = 0; i < ETHER_ADDR_LEN; i++)
for (j = context->addr_epoch, i = 0; i < ETHER_ADDR_LEN; i++)
j += hwaddr[i] + (hwaddr[i] << 8) + (hwaddr[i] << 16);
start.s_addr = addr.s_addr =
htonl(ntohl(context->start.s_addr) +
(j % (ntohl(context->end.s_addr) - ntohl(context->start.s_addr))));
do {
if (addr.s_addr == context->end.s_addr)
addr = context->start;
else
addr.s_addr = htonl(ntohl(addr.s_addr) + 1);
(j % (1 + ntohl(context->end.s_addr) - ntohl(context->start.s_addr))));
if (!lease_find_by_addr(addr))
do {
if (!lease_find_by_addr(addr) &&
!config_find_by_address(daemon->dhcp_conf, addr))
{
for (config = configs; config; config = config->next)
if ((config->flags & CONFIG_ADDR) && config->addr.s_addr == addr.s_addr)
break;
if (!config)
if (icmp_ping(daemon, addr))
/* perturb address selection so that we are
less likely to try this address again. */
context->addr_epoch++;
else
{
*addrp = addr;
return 1;
}
}
addr.s_addr = htonl(ntohl(addr.s_addr) + 1);
if (addr.s_addr == htonl(ntohl(context->end.s_addr) + 1))
addr = context->start;
} while (addr.s_addr != start.s_addr);
return 0;
@@ -472,20 +492,21 @@ struct dhcp_config *find_config(struct dhcp_config *configs,
return NULL;
}
struct dhcp_config *dhcp_read_ethers(struct dhcp_config *configs, char *buff)
void dhcp_read_ethers(struct daemon *daemon)
{
FILE *f = fopen(ETHERSFILE, "r");
unsigned int flags, e0, e1, e2, e3, e4, e5;
char *buff = daemon->namebuff;
char *ip, *cp;
struct in_addr addr;
unsigned char hwaddr[ETHER_ADDR_LEN];
struct dhcp_config *config;
struct dhcp_config *config, *configs = daemon->dhcp_conf;
int count = 0;
if (!f)
{
syslog(LOG_ERR, "failed to read " ETHERSFILE ":%m");
return configs;
return;
}
while (fgets(buff, MAXDNAME, f))
@@ -577,7 +598,8 @@ struct dhcp_config *dhcp_read_ethers(struct dhcp_config *configs, char *buff)
fclose(f);
syslog(LOG_INFO, "read " ETHERSFILE " - %d addresses", count);
return configs;
daemon->dhcp_conf = configs;
}
void dhcp_update_configs(struct dhcp_config *configs)

View File

@@ -1,4 +1,4 @@
/* dnsmasq is Copyright (c) 2000-2003 Simon Kelley
/* dnsmasq is Copyright (c) 2000-2004 Simon Kelley
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -10,67 +10,24 @@
GNU General Public License for more details.
*/
/* See RFC1035 for details of the protocol this code talks. */
/* Author's email: simon@thekelleys.org.uk */
#include "dnsmasq.h"
static int sigterm, sighup, sigusr1, sigalarm;
static int sigterm, sighup, sigusr1, sigalarm, num_kids, in_child;
static void sig_handler(int sig)
{
if (sig == SIGTERM)
sigterm = 1;
else if (sig == SIGHUP)
sighup = 1;
else if (sig == SIGUSR1)
sigusr1 = 1;
else if (sig == SIGALRM)
sigalarm = 1;
}
static int set_dns_listeners(struct daemon *daemon, fd_set *set, int maxfd);
static void check_dns_listeners(struct daemon *daemon, fd_set *set, time_t now);
static void sig_handler(int sig);
int main (int argc, char **argv)
{
int cachesize = CACHESIZ;
int port = NAMESERVER_PORT;
int maxleases = MAXLEASES;
int query_port = 0;
struct daemon *daemon;
int first_loop = 1;
int bind_fallback = 0;
unsigned long local_ttl = 0;
unsigned int options, min_leasetime;
char *runfile = RUNFILE;
time_t resolv_changed = 0;
time_t now, last = 0;
struct irec *interfaces = NULL;
struct listener *listener, *listeners = NULL;
struct doctor *doctors = NULL;
struct mx_record *mxnames = NULL;
char *mxtarget = NULL;
char *lease_file = NULL;
char *addn_hosts = NULL;
char *domain_suffix = NULL;
char *username = CHUSER;
char *groupname = CHGRP;
struct iname *if_names = NULL;
struct iname *if_addrs = NULL;
struct iname *if_except = NULL;
struct server *serv_addrs = NULL;
char *dnamebuff, *packet;
int uptime_fd = -1;
struct server *servers, *last_server;
struct resolvc default_resolv = { NULL, 1, 0, RESOLVFILE };
struct resolvc *resolv = &default_resolv;
struct bogus_addr *bogus_addr = NULL;
struct serverfd *serverfdp, *sfds = NULL;
struct dhcp_context *dhcp_tmp, *dhcp = NULL;
struct dhcp_config *dhcp_configs = NULL;
struct dhcp_opt *dhcp_options = NULL;
struct dhcp_vendor *dhcp_vendors = NULL;
char *dhcp_file = NULL, *dhcp_sname = NULL;
struct in_addr dhcp_next_server;
int leasefd = -1, dhcpfd = -1, dhcp_raw_fd = -1;
struct irec *interfaces;
struct sigaction sigact;
sigset_t sigmask;
@@ -82,6 +39,8 @@ int main (int argc, char **argv)
#else
sigalarm = 0; /* or not */
#endif
num_kids = 0;
in_child = 0;
sigact.sa_handler = sig_handler;
sigact.sa_flags = 0;
@@ -90,6 +49,11 @@ int main (int argc, char **argv)
sigaction(SIGHUP, &sigact, NULL);
sigaction(SIGTERM, &sigact, NULL);
sigaction(SIGALRM, &sigact, NULL);
sigaction(SIGCHLD, &sigact, NULL);
/* ignore SIGPIPE */
sigact.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &sigact, NULL);
/* now block all the signals, they stay that way except
during the call to pselect */
@@ -97,55 +61,48 @@ int main (int argc, char **argv)
sigaddset(&sigact.sa_mask, SIGTERM);
sigaddset(&sigact.sa_mask, SIGHUP);
sigaddset(&sigact.sa_mask, SIGALRM);
sigaddset(&sigact.sa_mask, SIGCHLD);
sigprocmask(SIG_BLOCK, &sigact.sa_mask, &sigmask);
/* These get allocated here to avoid overflowing the small stack
on embedded systems. dnamebuff is big enough to hold one
maximal sixed domain name and gets passed into all the processing
code. We manage to get away with one buffer. */
dnamebuff = safe_malloc(MAXDNAME);
packet = safe_malloc(DNSMASQ_PACKETSZ);
daemon = read_opts(argc, argv);
dhcp_next_server.s_addr = 0;
options = read_opts(argc, argv, dnamebuff, &resolv, &mxnames, &mxtarget, &lease_file,
&username, &groupname, &domain_suffix, &runfile,
&if_names, &if_addrs, &if_except, &bogus_addr,
&serv_addrs, &cachesize, &port, &query_port, &local_ttl, &addn_hosts,
&dhcp, &dhcp_configs, &dhcp_options, &dhcp_vendors,
&dhcp_file, &dhcp_sname, &dhcp_next_server, &maxleases, &min_leasetime,
&doctors);
if (!lease_file)
if (daemon->edns_pktsz < PACKETSZ)
daemon->edns_pktsz = PACKETSZ;
daemon->packet = safe_malloc(daemon->edns_pktsz > DNSMASQ_PACKETSZ ?
daemon->edns_pktsz : DNSMASQ_PACKETSZ);
if (!daemon->lease_file)
{
if (dhcp)
lease_file = LEASEFILE;
if (daemon->dhcp)
daemon->lease_file = LEASEFILE;
}
#ifndef HAVE_ISC_READER
else if (!dhcp)
else if (!daemon->dhcp)
die("ISC dhcpd integration not available: set HAVE_ISC_READER in src/config.h", NULL);
#endif
interfaces = enumerate_interfaces(&if_names, &if_addrs, if_except, port);
if (!(options & OPT_NOWILD) && !(listeners = create_wildcard_listeners(port)))
interfaces = enumerate_interfaces(daemon);
if (!(daemon->options & OPT_NOWILD) &&
!(daemon->listeners = create_wildcard_listeners(daemon->port)))
{
bind_fallback = 1;
options |= OPT_NOWILD;
daemon->options |= OPT_NOWILD;
}
if (options & OPT_NOWILD)
if (daemon->options & OPT_NOWILD)
{
struct iname *if_tmp;
listeners = create_bound_listeners(interfaces);
daemon->listeners = create_bound_listeners(interfaces, daemon->port);
for (if_tmp = if_names; if_tmp; if_tmp = if_tmp->next)
for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next)
if (if_tmp->name && !if_tmp->used)
die("unknown interface %s", if_tmp->name);
for (if_tmp = if_addrs; if_tmp; if_tmp = if_tmp->next)
for (if_tmp = daemon->if_addrs; if_tmp; if_tmp = if_tmp->next)
if (!if_tmp->used)
{
char addrbuff[ADDRSTRLEN];
char *addrbuff = daemon->namebuff;
#ifdef HAVE_IPV6
if (if_tmp->addr.sa.sa_family == AF_INET)
inet_ntop(AF_INET, &if_tmp->addr.in.sin_addr,
@@ -161,35 +118,62 @@ int main (int argc, char **argv)
}
forward_init(1);
cache_init(cachesize, options & OPT_LOG);
cache_init(daemon->cachesize, daemon->options & OPT_LOG);
#ifdef HAVE_BROKEN_RTC
if ((uptime_fd = open(UPTIME, O_RDONLY)) == -1)
if ((daemon->uptime_fd = open(UPTIME, O_RDONLY)) == -1)
die("cannot open " UPTIME ":%s", NULL);
#endif
now = dnsmasq_time(uptime_fd);
now = dnsmasq_time(daemon->uptime_fd);
if (dhcp)
if (daemon->dhcp)
{
#if !defined(IP_PKTINFO) && !defined(IP_RECVIF)
int c;
struct iname *tmp;
for (c = 0, tmp = if_names; tmp; tmp = tmp->next)
for (c = 0, tmp = daemon->if_names; tmp; tmp = tmp->next)
if (!tmp->isloop)
c++;
if (c != 1)
die("must set exactly one interface on broken systems without IP_RECVIF", NULL);
#endif
dhcp_init(&dhcpfd, &dhcp_raw_fd);
leasefd = lease_init(lease_file, domain_suffix, dnamebuff, packet, now, maxleases);
dhcp_init(daemon);
lease_init(daemon, now);
}
/* If query_port is set then create a socket now, before dumping root
for use to access nameservers without more specific source addresses.
This allows query_port to be a low port */
if (daemon->query_port)
{
union mysockaddr addr;
addr.in.sin_family = AF_INET;
addr.in.sin_addr.s_addr = INADDR_ANY;
addr.in.sin_port = htons(daemon->query_port);
#ifdef HAVE_SOCKADDR_SA_LEN
addr.in.sin_len = sizeof(struct sockaddr_in);
#endif
allocate_sfd(&addr, &daemon->sfds);
#ifdef HAVE_IPV6
addr.in6.sin6_family = AF_INET6;
addr.in6.sin6_addr = in6addr_any;
addr.in6.sin6_port = htons(daemon->query_port);
addr.in6.sin6_flowinfo = htonl(0);
#ifdef HAVE_SOCKADDR_SA_LEN
addr.in6.sin6_len = sizeof(struct sockaddr_in6);
#endif
allocate_sfd(&addr, &daemon->sfds);
#endif
}
setbuf(stdout, NULL);
if (!(options & OPT_DEBUG))
if (!(daemon->options & OPT_DEBUG))
{
FILE *pidfile;
struct serverfd *serverfdp;
struct listener *listener;
struct passwd *ent_pw;
int i;
@@ -197,20 +181,23 @@ int main (int argc, char **argv)
See Stevens section 12.4 */
#ifndef NO_FORK
if (fork() != 0 )
exit(0);
setsid();
if (fork() != 0)
exit(0);
if (!(daemon->options & OPT_NO_FORK))
{
if (fork() != 0 )
exit(0);
setsid();
if (fork() != 0)
exit(0);
}
#endif
chdir("/");
umask(022); /* make pidfile 0644 */
/* write pidfile _after_ forking ! */
if (runfile && (pidfile = fopen(runfile, "w")))
if (daemon->runfile && (pidfile = fopen(daemon->runfile, "w")))
{
fprintf(pidfile, "%d\n", (int) getpid());
fclose(pidfile);
@@ -220,23 +207,35 @@ int main (int argc, char **argv)
for (i=0; i<64; i++)
{
for (listener = listeners; listener; listener = listener->next)
if (listener->fd == i)
for (listener = daemon->listeners; listener; listener = listener->next)
if (listener->fd == i || listener->tcpfd == i)
break;
if (listener)
continue;
if (i == leasefd ||
i == uptime_fd ||
i == dhcpfd ||
i == dhcp_raw_fd)
#ifdef HAVE_BROKEN_RTC
if (i == daemon->uptime_fd)
continue;
#endif
if (daemon->dhcp &&
(i == daemon->lease_fd ||
i == daemon->dhcpfd ||
i == daemon->dhcp_raw_fd ||
i == daemon->dhcp_icmp_fd))
continue;
for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
if (serverfdp->fd == i)
break;
if (serverfdp)
continue;
close(i);
}
/* Change uid and gid for security */
if (username && (ent_pw = getpwnam(username)))
if (daemon->username && (ent_pw = getpwnam(daemon->username)))
{
gid_t dummy;
struct group *gp;
@@ -244,7 +243,7 @@ int main (int argc, char **argv)
setgroups(0, &dummy);
/* change group for /etc/ppp/resolv.conf
otherwise get the group for "nobody" */
if ((groupname && (gp = getgrnam(groupname))) ||
if ((daemon->groupname && (gp = getgrnam(daemon->groupname))) ||
(gp = getgrgid(ent_pw->pw_gid)))
setgid(gp->gr_gid);
/* finally drop root */
@@ -253,80 +252,91 @@ int main (int argc, char **argv)
}
openlog("dnsmasq",
DNSMASQ_LOG_OPT(options & OPT_DEBUG),
DNSMASQ_LOG_FAC(options & OPT_DEBUG));
DNSMASQ_LOG_OPT(daemon->options & OPT_DEBUG),
DNSMASQ_LOG_FAC(daemon->options & OPT_DEBUG));
if (cachesize)
syslog(LOG_INFO, "started, version %s cachesize %d", VERSION, cachesize);
if (daemon->cachesize != 0)
syslog(LOG_INFO, "started, version %s cachesize %d", VERSION, daemon->cachesize);
else
syslog(LOG_INFO, "started, version %s cache disabled", VERSION);
if (bind_fallback)
syslog(LOG_WARNING, "setting --bind-interfaces option because if OS limitations");
syslog(LOG_WARNING, "setting --bind-interfaces option because of OS limitations");
for (dhcp_tmp = dhcp; dhcp_tmp; dhcp_tmp = dhcp_tmp->next)
if (daemon->dhcp)
{
strcpy(dnamebuff, inet_ntoa(dhcp_tmp->start));
if (dhcp_tmp->lease_time == 0)
sprintf(packet, "infinite");
else
sprintf(packet, "%ds", (int)dhcp_tmp->lease_time);
syslog(LOG_INFO,
dhcp_tmp->start.s_addr == dhcp_tmp->end.s_addr ?
"DHCP, static leases only on %.0s%s, lease time %s" :
"DHCP, IP range %s -- %s, lease time %s",
dnamebuff, inet_ntoa(dhcp_tmp->end), packet);
struct dhcp_context *dhcp_tmp;
for (dhcp_tmp = daemon->dhcp; dhcp_tmp; dhcp_tmp = dhcp_tmp->next)
{
char *time = daemon->dhcp_buff2;
strcpy(daemon->dhcp_buff, inet_ntoa(dhcp_tmp->start));
if (dhcp_tmp->lease_time == 0)
sprintf(time, "infinite");
else
{
unsigned int x, p = 0, t = (unsigned int)dhcp_tmp->lease_time;
if ((x = t/3600))
p += sprintf(&time[p], "%dh", x);
if ((x = (t/60)%60))
p += sprintf(&time[p], "%dm", x);
if ((x = t%60))
p += sprintf(&time[p], "%ds", x);
}
syslog(LOG_INFO,
dhcp_tmp->static_only ?
"DHCP, static leases only on %.0s%s, lease time %s" :
"DHCP, IP range %s -- %s, lease time %s",
daemon->dhcp_buff, inet_ntoa(dhcp_tmp->end), time);
}
}
#ifdef HAVE_BROKEN_RTC
if (dhcp)
syslog(LOG_INFO, "DHCP, %s will be written every %ds", lease_file, min_leasetime/3);
if (daemon->dhcp)
syslog(LOG_INFO, "DHCP, %s will be written every %ds", daemon->lease_file, daemon->min_leasetime/3);
#endif
if (getuid() == 0 || geteuid() == 0)
syslog(LOG_WARNING, "failed to drop root privs");
servers = check_servers(serv_addrs, interfaces, &sfds);
last_server = NULL;
if (!(daemon->options & OPT_DEBUG) && (getuid() == 0 || geteuid() == 0))
syslog(LOG_WARNING, "running as root");
check_servers(daemon, interfaces);
while (sigterm == 0)
{
fd_set rset;
if (sighup)
{
cache_reload(options, dnamebuff, domain_suffix, addn_hosts);
if (dhcp)
cache_reload(daemon->options, daemon->namebuff, daemon->domain_suffix, daemon->addn_hosts);
if (daemon->dhcp)
{
if (options & OPT_ETHERS)
dhcp_configs = dhcp_read_ethers(dhcp_configs, dnamebuff);
dhcp_update_configs(dhcp_configs);
lease_update_from_configs(dhcp_configs, domain_suffix);
if (daemon->options & OPT_ETHERS)
dhcp_read_ethers(daemon);
dhcp_update_configs(daemon->dhcp_conf);
lease_update_from_configs(daemon->dhcp_conf, daemon->domain_suffix);
lease_update_file(0, now);
lease_update_dns();
}
if (resolv && (options & OPT_NO_POLL))
if (daemon->resolv_files && (daemon->options & OPT_NO_POLL))
{
servers = check_servers(reload_servers(resolv->name, dnamebuff, servers, query_port),
interfaces, &sfds);
last_server = NULL;
reload_servers(daemon->resolv_files->name, daemon);
check_servers(daemon, interfaces);
}
sighup = 0;
}
if (sigusr1)
{
dump_cache(options & (OPT_DEBUG | OPT_LOG), cachesize);
dump_cache(daemon->options & (OPT_DEBUG | OPT_LOG), daemon->cachesize);
sigusr1 = 0;
}
if (sigalarm)
{
if (dhcp)
if (daemon->dhcp)
{
lease_update_file(1, now);
#ifdef HAVE_BROKEN_RTC
alarm(min_leasetime/3);
alarm(daemon->min_leasetime/3);
#endif
}
sigalarm = 0;
@@ -336,27 +346,13 @@ int main (int argc, char **argv)
if (!first_loop)
{
int maxfd = 0;
for (serverfdp = sfds; serverfdp; serverfdp = serverfdp->next)
int maxfd = set_dns_listeners(daemon, &rset, 0);
if (daemon->dhcp)
{
FD_SET(serverfdp->fd, &rset);
if (serverfdp->fd > maxfd)
maxfd = serverfdp->fd;
}
for (listener = listeners; listener; listener = listener->next)
{
FD_SET(listener->fd, &rset);
if (listener->fd > maxfd)
maxfd = listener->fd;
}
if (dhcp)
{
FD_SET(dhcpfd, &rset);
if (dhcpfd > maxfd)
maxfd = dhcpfd;
FD_SET(daemon->dhcpfd, &rset);
if (daemon->dhcpfd > maxfd)
maxfd = daemon->dhcpfd;
}
#ifdef HAVE_PSELECT
@@ -371,11 +367,10 @@ int main (int argc, char **argv)
sigprocmask(SIG_SETMASK, &save_mask, NULL);
}
#endif
}
first_loop = 0;
now = dnsmasq_time(uptime_fd);
now = dnsmasq_time(daemon->uptime_fd);
/* Check for changes to resolv files once per second max. */
if (last == 0 || difftime(now, last) > 1.0)
@@ -383,13 +378,13 @@ int main (int argc, char **argv)
last = now;
#ifdef HAVE_ISC_READER
if (lease_file && !dhcp)
load_dhcp(lease_file, domain_suffix, now, dnamebuff);
if (daemon->lease_file && !daemon->dhcp)
load_dhcp(daemon->lease_file, daemon->domain_suffix, now, daemon->namebuff);
#endif
if (!(options & OPT_NO_POLL))
if (!(daemon->options & OPT_NO_POLL))
{
struct resolvc *res = resolv, *latest = NULL;
struct resolvc *res = daemon->resolv_files, *latest = NULL;
struct stat statbuf;
time_t last_change = 0;
/* There may be more than one possible file.
@@ -418,45 +413,268 @@ int main (int argc, char **argv)
if (latest && difftime(last_change, resolv_changed) > 0.0)
{
resolv_changed = last_change;
servers = check_servers(reload_servers(latest->name, dnamebuff, servers, query_port),
interfaces, &sfds);
last_server = NULL;
reload_servers(latest->name, daemon);
check_servers(daemon, interfaces);
}
}
}
for (serverfdp = sfds; serverfdp; serverfdp = serverfdp->next)
if (FD_ISSET(serverfdp->fd, &rset))
last_server = reply_query(serverfdp, options, packet, now,
dnamebuff, servers, last_server, bogus_addr, doctors);
if (dhcp && FD_ISSET(dhcpfd, &rset))
dhcp_packet(dhcp, packet, dhcp_options, dhcp_configs, dhcp_vendors,
now, dnamebuff, domain_suffix, dhcp_file,
dhcp_sname, dhcp_next_server, dhcpfd, dhcp_raw_fd,
if_names, if_addrs, if_except);
check_dns_listeners(daemon, &rset, now);
for (listener = listeners; listener; listener = listener->next)
if (FD_ISSET(listener->fd, &rset))
last_server = receive_query(listener, packet,
mxnames, mxtarget, options, now, local_ttl, dnamebuff,
if_names, if_addrs, if_except, last_server, servers);
if (daemon->dhcp && FD_ISSET(daemon->dhcpfd, &rset))
dhcp_packet(daemon, now);
}
syslog(LOG_INFO, "exiting on receipt of SIGTERM");
if (daemon->dhcp)
{
#ifdef HAVE_BROKEN_RTC
if (dhcp)
lease_update_file(1, now);
lease_update_file(1, now);
#endif
if (leasefd != -1)
close(leasefd);
close(daemon->lease_fd);
}
return 0;
}
static void sig_handler(int sig)
{
if (sig == SIGTERM)
sigterm = 1;
else if (sig == SIGHUP)
sighup = 1;
else if (sig == SIGUSR1)
sigusr1 = 1;
else if (sig == SIGALRM)
{
/* alarm is used to kill children after a fixed time. */
if (in_child)
exit(0);
else
sigalarm = 1;
}
else if (sig == SIGCHLD)
{
/* See Stevens 5.10 */
while (waitpid(-1, NULL, WNOHANG) > 0)
num_kids--;
}
}
static int set_dns_listeners(struct daemon *daemon, fd_set *set, int maxfd)
{
struct serverfd *serverfdp;
struct listener *listener;
for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
{
FD_SET(serverfdp->fd, set);
if (serverfdp->fd > maxfd)
maxfd = serverfdp->fd;
}
for (listener = daemon->listeners; listener; listener = listener->next)
{
FD_SET(listener->fd, set);
if (listener->fd > maxfd)
maxfd = listener->fd;
FD_SET(listener->tcpfd, set);
if (listener->tcpfd > maxfd)
maxfd = listener->tcpfd;
}
return maxfd;
}
static void check_dns_listeners(struct daemon *daemon, fd_set *set, time_t now)
{
struct serverfd *serverfdp;
struct listener *listener;
for (serverfdp = daemon->sfds; serverfdp; serverfdp = serverfdp->next)
if (FD_ISSET(serverfdp->fd, set))
reply_query(serverfdp, daemon, now);
for (listener = daemon->listeners; listener; listener = listener->next)
{
if (FD_ISSET(listener->fd, set))
receive_query(listener, daemon, now);
if (FD_ISSET(listener->tcpfd, set))
{
int confd;
while((confd = accept(listener->tcpfd, NULL, NULL)) == -1 && errno == EINTR);
if (confd != -1)
{
int match = 1;
if (!(daemon->options & OPT_NOWILD))
{
/* Check for allowed interfaces when binding the wildcard address */
/* Don't know how to get interface of a connection, so we have to
check by address. This will break when interfaces change address */
union mysockaddr tcp_addr;
socklen_t tcp_len = sizeof(union mysockaddr);
struct iname *tmp;
if (getsockname(confd, (struct sockaddr *)&tcp_addr, &tcp_len) != -1)
{
#ifdef HAVE_IPV6
if (tcp_addr.sa.sa_family == AF_INET6)
tcp_addr.in6.sin6_flowinfo = htonl(0);
#endif
for (match = 1, tmp = daemon->if_except; tmp; tmp = tmp->next)
if (sockaddr_isequal(&tmp->addr, &tcp_addr))
match = 0;
if (match && (daemon->if_names || daemon->if_addrs))
{
match = 0;
for (tmp = daemon->if_names; tmp; tmp = tmp->next)
if (sockaddr_isequal(&tmp->addr, &tcp_addr))
match = 1;
for (tmp = daemon->if_addrs; tmp; tmp = tmp->next)
if (sockaddr_isequal(&tmp->addr, &tcp_addr))
match = 1;
}
}
}
if (!match || (num_kids >= MAX_PROCS))
close(confd);
else if (!(daemon->options & OPT_DEBUG) && fork())
{
num_kids++;
close(confd);
}
else
{
char *buff;
struct server *s;
int flags;
/* Arrange for SIGALARM after CHILD_LIFETIME seconds to
terminate the process. */
if (!(daemon->options & OPT_DEBUG))
{
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGALRM);
sigprocmask(SIG_UNBLOCK, &mask, NULL);
alarm(CHILD_LIFETIME);
in_child = 1;
}
/* start with no upstream connections. */
for (s = daemon->servers; s; s = s->next)
s->tcpfd = -1;
/* The connected socket inherits non-blocking
attribute from the listening socket.
Reset that here. */
if ((flags = fcntl(confd, F_GETFL, 0)) != -1)
fcntl(confd, F_SETFL, flags & ~O_NONBLOCK);
buff = tcp_request(daemon, confd, now);
if (!(daemon->options & OPT_DEBUG))
exit(0);
close(confd);
if (buff)
free(buff);
for (s = daemon->servers; s; s = s->next)
if (s->tcpfd != -1)
close(s->tcpfd);
}
}
}
}
}
int icmp_ping(struct daemon *daemon, struct in_addr addr)
{
/* Try and get an ICMP echo from a machine.
Note that we can't create the raw socket each time
we do this, since that needs root. Therefore the socket has to hang
around all the time. Since most of the time we won't read the
socket, it will accumulate buffers full of ICMP messages,
wasting memory. To avoid that we set the receive buffer
length to zero except when we're actively pinging. */
/* Note that whilst in the three second wait, we check for
(and service) events on the DNS sockets, (so doing that
better not use any resources our caller has in use...)
but we remain deaf to signals or further DHCP packets. */
struct sockaddr_in saddr;
struct {
struct ip ip;
struct icmp icmp;
} packet;
unsigned short id = rand16();
unsigned int i, j;
int opt = 2000, gotreply = 0;
time_t start, now;
saddr.sin_family = AF_INET;
saddr.sin_port = 0;
saddr.sin_addr = addr;
#ifdef HAVE_SOCKADDR_SA_LEN
saddr.sin_len = sizeof(struct sockaddr_in);
#endif
memset(&packet.icmp, 0, sizeof(packet.icmp));
packet.icmp.icmp_type = ICMP_ECHO;
packet.icmp.icmp_id = id;
for (j = 0, i = 0; i < sizeof(struct icmp) / 2; i++)
j += ((u16 *)&packet.icmp)[i];
while (j>>16)
j = (j & 0xffff) + (j >> 16);
packet.icmp.icmp_cksum = (j == 0xffff) ? j : ~j;
setsockopt(daemon->dhcp_icmp_fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
if (sendto(daemon->dhcp_icmp_fd, (char *)&packet.icmp, sizeof(struct icmp), 0,
(struct sockaddr *)&saddr, sizeof(saddr)) == sizeof(struct icmp))
for (now = start = dnsmasq_time(daemon->uptime_fd); difftime(now, start) < 3.0;)
{
struct timeval tv;
fd_set rset;
struct sockaddr_in faddr;
int maxfd, len = sizeof(faddr);
tv.tv_usec = 250000;
tv.tv_sec = 0;
FD_ZERO(&rset);
FD_SET(daemon->dhcp_icmp_fd, &rset);
maxfd = set_dns_listeners(daemon, &rset, daemon->dhcp_icmp_fd);
if (select(maxfd+1, &rset, NULL, NULL, &tv) < 0)
FD_ZERO(&rset);
now = dnsmasq_time(daemon->uptime_fd);
check_dns_listeners(daemon, &rset, now);
if (FD_ISSET(daemon->dhcp_icmp_fd, &rset) &&
recvfrom(daemon->dhcp_icmp_fd, &packet, sizeof(packet), 0,
(struct sockaddr *)&faddr, &len) == sizeof(packet) &&
saddr.sin_addr.s_addr == faddr.sin_addr.s_addr &&
packet.icmp.icmp_type == ICMP_ECHOREPLY &&
packet.icmp.icmp_seq == 0 &&
packet.icmp.icmp_id == id)
{
gotreply = 1;
break;
}
}
opt = 1;
setsockopt(daemon->dhcp_icmp_fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt));
return gotreply;
}

View File

@@ -11,7 +11,8 @@
*/
/* Author's email: simon@thekelleys.org.uk */
#define COPYRIGHT "Copyright (C) 2000-2004 Simon Kelley"
#ifdef __linux__
/* for pselect.... */
@@ -26,16 +27,16 @@
/* get this before config.h too. */
#include <syslog.h>
#include <arpa/nameser.h>
#include "config.h"
#include <arpa/nameser.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/wait.h>
#if defined(__sun) || defined(__sun__)
# include <sys/sockio.h>
#endif
@@ -64,6 +65,7 @@
#include <net/if_arp.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#ifdef HAVE_BPF
# include <net/bpf.h>
# include <net/if_dl.h>
@@ -92,6 +94,7 @@
#define OPT_NOWILD 8192
#define OPT_ETHERS 16384
#define OPT_RESOLV_DOMAIN 32768
#define OPT_NO_FORK 65536
struct all_addr {
union {
@@ -194,7 +197,7 @@ struct server {
struct serverfd *sfd; /* non-NULL if this server has its own fd bound to
a source port */
char *domain; /* set if this server only handles a domain. */
int flags;
int flags, tcpfd;
struct server *next;
};
@@ -204,7 +207,7 @@ struct irec {
};
struct listener {
int fd, family;
int fd, tcpfd, family;
struct listener *next;
};
@@ -228,6 +231,7 @@ struct frec {
union mysockaddr source;
struct all_addr dest;
struct server *sentto;
unsigned int iface;
unsigned short orig_id, new_id;
int fd;
time_t time;
@@ -285,9 +289,10 @@ struct dhcp_vendor {
};
struct dhcp_context {
unsigned int lease_time;
struct in_addr netmask, broadcast;
unsigned int lease_time, addr_epoch;
struct in_addr netmask, broadcast, router;
struct in_addr start, end; /* range of available addresses */
int static_only;
struct dhcp_netid netid;
struct dhcp_context *next;
};
@@ -311,15 +316,60 @@ struct udp_dhcp_packet {
u16 secs, flags;
struct in_addr ciaddr, yiaddr, siaddr, giaddr;
u8 chaddr[16], sname[64], file[128];
u32 cookie;
u8 options[308];
u8 options[312];
} data;
};
struct daemon {
/* datastuctures representing the command-line and
config file arguments. All set (including defaults)
in option.c */
unsigned int options;
struct resolvc default_resolv, *resolv_files;
struct mx_record *mxnames;
char *mxtarget;
char *lease_file;
char *username, *groupname;
char *domain_suffix;
char *runfile;
struct iname *if_names, *if_addrs, *if_except;
struct bogus_addr *bogus_addr;
struct server *servers;
int cachesize;
int port, query_port;
unsigned long local_ttl;
char *addn_hosts;
struct dhcp_context *dhcp;
struct dhcp_config *dhcp_conf;
struct dhcp_opt *dhcp_opts;
struct dhcp_vendor *dhcp_vendors;
char *dhcp_file;
char *dhcp_sname;
struct in_addr dhcp_next_server;
int dhcp_max;
unsigned int min_leasetime;
struct doctor *doctors;
unsigned short edns_pktsz;
/* globally used stuff for DNS */
char *packet; /* packet buffer */
char *namebuff; /* MAXDNAME size buffer */
struct serverfd *sfds;
struct listener *listeners;
struct server *last_server;
int uptime_fd;
/* DHCP state */
int dhcpfd, dhcp_raw_fd, dhcp_icmp_fd, lease_fd;
struct udp_dhcp_packet *dhcp_packet;
char *dhcp_buff, *dhcp_buff2;
};
/* cache.c */
void cache_init(int cachesize, int log);
void log_query(unsigned short flags, char *name, struct all_addr *addr);
void log_query(unsigned short flags, char *name, struct all_addr *addr, unsigned short type);
struct crec *cache_find_by_addr(struct crec *crecp,
struct all_addr *addr, time_t now,
unsigned short prot);
@@ -330,25 +380,24 @@ void cache_start_insert(void);
void cache_insert(char *name, struct all_addr *addr,
time_t now, unsigned long ttl, unsigned short flags);
void cache_reload(int opts, char *buff, char *domain_suffix, char *addn_hosts);
void cache_add_dhcp_entry(char *host_name, struct in_addr *host_address,
time_t ttd, unsigned short flags);
void cache_add_dhcp_entry(char *host_name, struct in_addr *host_address, time_t ttd);
void cache_unhash_dhcp(void);
void dump_cache(int debug, int size);
char *cache_get_name(struct crec *crecp);
/* rfc1035.c */
unsigned short extract_request(HEADER *header, unsigned int qlen, char *name);
unsigned short extract_request(HEADER *header, unsigned int qlen,
char *name, unsigned short *typep);
int setup_reply(HEADER *header, unsigned int qlen,
struct all_addr *addrp, unsigned short flags,
unsigned long local_ttl);
void extract_addresses(HEADER *header, unsigned int qlen, char *namebuff,
time_t now, struct doctor *doctors);
void extract_neg_addrs(HEADER *header, unsigned int qlen, char *namebuff, time_t now);
int answer_request(HEADER *header, char *limit, unsigned int qlen, struct mx_record *mxnames,
char *mxtarget, unsigned int options, time_t now, unsigned long local_ttl,
char *namebuff);
int answer_request(HEADER *header, char *limit, unsigned int qlen, struct daemon *daemon, time_t now);
int check_for_bogus_wildcard(HEADER *header, unsigned int qlen, char *name,
struct bogus_addr *addr, time_t now);
unsigned char *find_pseudoheader(HEADER *header, unsigned int plen);
/* util.c */
unsigned short rand16(void);
@@ -366,63 +415,41 @@ time_t dnsmasq_time(int fd);
int is_same_net(struct in_addr a, struct in_addr b, struct in_addr mask);
/* option.c */
unsigned int read_opts(int argc, char **argv, char *buff, struct resolvc **resolv_file,
struct mx_record **mxnames, char **mxtarget, char **lease_file,
char **username, char **groupname,
char **domain_suffix, char **runfile,
struct iname **if_names, struct iname **if_addrs, struct iname **if_except,
struct bogus_addr **bogus_addr, struct server **serv_addrs, int *cachesize,
int *port, int *query_port, unsigned long *local_ttl, char **addn_hosts,
struct dhcp_context **dhcp, struct dhcp_config **dhcp_conf,
struct dhcp_opt **opts, struct dhcp_vendor **dhcp_vendors,
char **dhcp_file, char **dhcp_sname, struct in_addr *dhcp_next_server,
int *maxleases, unsigned int *min_leasetime, struct doctor **doctors);
struct daemon *read_opts (int argc, char **argv);
/* forward.c */
void forward_init(int first);
struct server *reply_query(struct serverfd *sfd, int options, char *packet, time_t now,
char *dnamebuff, struct server *servers, struct server *last_server,
struct bogus_addr *bogus_nxdomain, struct doctor *doctors);
void reply_query(struct serverfd *sfd, struct daemon *daemon, time_t now);
void receive_query(struct listener *listen, struct daemon *daemon, time_t now);
char *tcp_request(struct daemon *daemon, int confd, time_t now);
struct server *receive_query(struct listener *listen, char *packet, struct mx_record *mxnames,
char *mxtarget, unsigned int options, time_t now,
unsigned long local_ttl, char *namebuff,
struct iname *names, struct iname *addrs, struct iname *except,
struct server *last_server, struct server *servers);
/* network.c */
struct server *reload_servers(char *fname, char *buff, struct server *servers, int query_port);
struct server *check_servers(struct server *new, struct irec *interfaces, struct serverfd **sfds);
struct irec *enumerate_interfaces(struct iname **names,
struct iname **addrs,
struct iname *except,
int port);
struct serverfd *allocate_sfd(union mysockaddr *addr, struct serverfd **sfds);
void reload_servers(char *fname, struct daemon *daemon);
void check_servers(struct daemon *daemon, struct irec *interfaces);
struct irec *enumerate_interfaces(struct daemon *daemon);
struct listener *create_wildcard_listeners(int port);
struct listener *create_bound_listeners(struct irec *interfaces);
struct listener *create_bound_listeners(struct irec *interfaces, int port);
/* dhcp.c */
void dhcp_init(int *fdp, int* rfdp);
void dhcp_packet(struct dhcp_context *contexts, char *packet,
struct dhcp_opt *dhcp_opts, struct dhcp_config *dhcp_configs,
struct dhcp_vendor *vendors,
time_t now, char *namebuff, char *domain_suffix,
char *dhcp_file, char *dhcp_sname,
struct in_addr dhcp_next_server, int dhcp_fd, int raw_fd,
struct iname *names, struct iname *addrs, struct iname *except);
void dhcp_init(struct daemon *daemon);
void dhcp_packet(struct daemon *daemon, time_t now);
int address_available(struct dhcp_context *context, struct in_addr addr);
int address_allocate(struct dhcp_context *context, struct dhcp_config *configs,
int address_allocate(struct dhcp_context *context, struct daemon *daemon,
struct in_addr *addrp, unsigned char *hwaddr);
struct dhcp_config *find_config(struct dhcp_config *configs,
struct dhcp_context *context,
unsigned char *clid, int clid_len,
unsigned char *hwaddr, char *hostname);
struct dhcp_config *read_ethers(struct dhcp_config *configs, char *buff);
void dhcp_update_configs(struct dhcp_config *configs);
struct dhcp_config *dhcp_read_ethers(struct dhcp_config *configs, char *buff);
void dhcp_read_ethers(struct daemon *daemon);
struct dhcp_config *config_find_by_address(struct dhcp_config *configs, struct in_addr addr);
/* lease.c */
void lease_update_file(int force, time_t now);
void lease_update_dns(void);
int lease_init(char *lease_file, char *domain, char *buff,
char *buff2, time_t now, int maxleases);
void lease_init(struct daemon *daemon, time_t now);
struct dhcp_lease *lease_allocate(unsigned char *clid, int clid_len, struct in_addr addr);
void lease_set_hwaddr(struct dhcp_lease *lease, unsigned char *hwaddr);
void lease_set_hostname(struct dhcp_lease *lease, char *name, char *suffix);
@@ -433,18 +460,13 @@ void lease_prune(struct dhcp_lease *target, time_t now);
void lease_update_from_configs(struct dhcp_config *dhcp_configs, char *domain);
/* rfc2131.c */
int dhcp_reply(struct dhcp_context *context,
struct in_addr iface_addr,
char *iface_name,
int iface_mtu,
struct udp_dhcp_packet *rawpacket,
unsigned int sz, time_t now, char *namebuff,
struct dhcp_opt *dhcp_opts, struct dhcp_config *dhcp_configs,
struct dhcp_vendor *vendors,
char *domain_suffix, char *dhcp_file, char *dhcp_sname,
struct in_addr dhcp_next_server, struct in_addr router);
int dhcp_reply(struct daemon *daemon, struct in_addr iface_addr, char *iface_name, unsigned int sz, time_t now);
/* dnsmasq.c */
int icmp_ping(struct daemon *daemon, struct in_addr addr);
/* isc.c */
#ifdef HAVE_ISC_READER
void load_dhcp(char *file, char *suffix, time_t now, char *hostname);
#endif

View File

@@ -26,7 +26,7 @@ static unsigned short get_id(void);
void forward_init(int first)
{
struct frec *f;
if (first)
frec_list = NULL;
for (f = frec_list; f; f = f->next)
@@ -36,11 +36,11 @@ void forward_init(int first)
/* Send a UDP packet with it's source address set as "source"
unless nowild is true, when we just send it with the kernel default */
static void send_from(int fd, int nowild, char *packet, int len,
union mysockaddr *to, struct all_addr *source)
union mysockaddr *to, struct all_addr *source,
unsigned int iface)
{
struct msghdr msg;
struct iovec iov[1];
struct cmsghdr *cmptr;
union {
struct cmsghdr align; /* this ensures alignment */
#if defined(IP_PKTINFO)
@@ -52,169 +52,182 @@ static void send_from(int fd, int nowild, char *packet, int len,
char control6[CMSG_SPACE(sizeof(struct in6_pktinfo))];
#endif
} control_u;
iov[0].iov_base = packet;
iov[0].iov_len = len;
if (nowild)
{
msg.msg_control = NULL;
msg.msg_controllen = 0;
}
else
{
msg.msg_control = &control_u;
msg.msg_controllen = sizeof(control_u);
}
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_flags = 0;
msg.msg_name = to;
msg.msg_namelen = sa_len(to);
msg.msg_iov = iov;
msg.msg_iovlen = 1;
cmptr = CMSG_FIRSTHDR(&msg);
if (!nowild && to->sa.sa_family == AF_INET)
{
msg.msg_control = &control_u;
msg.msg_controllen = sizeof(control_u);
{
struct cmsghdr *cmptr = CMSG_FIRSTHDR(&msg);
#if defined(IP_PKTINFO)
if (!nowild && to->sa.sa_family == AF_INET)
{
struct in_pktinfo *pkt = (struct in_pktinfo *)CMSG_DATA(cmptr);
pkt->ipi_ifindex = 0;
pkt->ipi_spec_dst = source->addr.addr4;
msg.msg_controllen = cmptr->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
cmptr->cmsg_level = SOL_IP;
cmptr->cmsg_type = IP_PKTINFO;
}
struct in_pktinfo *pkt = (struct in_pktinfo *)CMSG_DATA(cmptr);
pkt->ipi_ifindex = 0;
pkt->ipi_spec_dst = source->addr.addr4;
msg.msg_controllen = cmptr->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
cmptr->cmsg_level = SOL_IP;
cmptr->cmsg_type = IP_PKTINFO;
#elif defined(IP_SENDSRCADDR)
if (!nowild && to->sa.sa_family == AF_INET)
{
struct in_addr *a = (struct in_addr *)CMSG_DATA(cmptr);
*a = source->addr.addr4;
msg.msg_controllen = cmptr->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
cmptr->cmsg_level = IPPROTO_IP;
cmptr->cmsg_type = IP_SENDSRCADDR;
}
struct in_addr *a = (struct in_addr *)CMSG_DATA(cmptr);
*a = source->addr.addr4;
msg.msg_controllen = cmptr->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
cmptr->cmsg_level = IPPROTO_IP;
cmptr->cmsg_type = IP_SENDSRCADDR;
#endif
}
}
#ifdef HAVE_IPV6
if (!nowild && to->sa.sa_family == AF_INET6)
if (to->sa.sa_family == AF_INET6)
{
struct in6_pktinfo *pkt = (struct in6_pktinfo *)CMSG_DATA(cmptr);
pkt->ipi6_ifindex = 0;
pkt->ipi6_addr = source->addr.addr6;
msg.msg_controllen = cmptr->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
cmptr->cmsg_type = IPV6_PKTINFO;
cmptr->cmsg_level = IPV6_LEVEL;
msg.msg_control = &control_u;
msg.msg_controllen = sizeof(control_u);
{
struct cmsghdr *cmptr = CMSG_FIRSTHDR(&msg);
struct in6_pktinfo *pkt = (struct in6_pktinfo *)CMSG_DATA(cmptr);
pkt->ipi6_ifindex = iface; /* Need iface for IPv6 to handle link-local addrs */
pkt->ipi6_addr = source->addr.addr6;
msg.msg_controllen = cmptr->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
cmptr->cmsg_type = IPV6_PKTINFO;
cmptr->cmsg_level = IPV6_LEVEL;
}
}
#endif
sendmsg(fd, &msg, 0);
/* certain Linux kernels seem to object to setting the source address in the IPv6 stack
by returning EINVAL from sendmsg. In that case, try again without setting the
source address, since it will nearly alway be correct anyway. IPv6 stinks. */
if (sendmsg(fd, &msg, 0) == -1 && errno == EINVAL)
{
msg.msg_controllen = 0;
sendmsg(fd, &msg, 0);
}
}
unsigned short search_servers(struct daemon *daemon, struct all_addr **addrpp,
unsigned short qtype, char *qdomain, int *type, char **domain)
{
/* If the query ends in the domain in one of our servers, set
domain to point to that name. We find the largest match to allow both
domain.org and sub.domain.org to exist. */
unsigned int namelen = strlen(qdomain);
unsigned int matchlen = 0;
struct server *serv;
unsigned short flags = 0;
for (serv = daemon->servers; serv; serv=serv->next)
/* domain matches take priority over NODOTS matches */
if ((serv->flags & SERV_FOR_NODOTS) && *type != SERV_HAS_DOMAIN && !strchr(qdomain, '.'))
{
unsigned short sflag = serv->addr.sa.sa_family == AF_INET ? F_IPV4 : F_IPV6;
*type = SERV_FOR_NODOTS;
flags = 0;
if (serv->flags & SERV_NO_ADDR)
flags = F_NXDOMAIN;
else if ((serv->flags & SERV_LITERAL_ADDRESS) && (sflag & qtype))
{
flags = sflag;
if (serv->addr.sa.sa_family == AF_INET)
*addrpp = (struct all_addr *)&serv->addr.in.sin_addr;
#ifdef HAVE_IPV6
else
*addrpp = (struct all_addr *)&serv->addr.in6.sin6_addr;
#endif
}
}
else if (serv->flags & SERV_HAS_DOMAIN)
{
unsigned int domainlen = strlen(serv->domain);
if (namelen >= domainlen &&
hostname_isequal(qdomain + namelen - domainlen, serv->domain) &&
domainlen >= matchlen)
{
unsigned short sflag = serv->addr.sa.sa_family == AF_INET ? F_IPV4 : F_IPV6;
*type = SERV_HAS_DOMAIN;
*domain = serv->domain;
matchlen = domainlen;
flags = 0;
if (serv->flags & SERV_NO_ADDR)
flags = F_NXDOMAIN;
else if ((serv->flags & SERV_LITERAL_ADDRESS) && ((sflag | F_QUERY ) & qtype))
{
flags = qtype;
if (serv->addr.sa.sa_family == AF_INET)
*addrpp = (struct all_addr *)&serv->addr.in.sin_addr;
#ifdef HAVE_IPV6
else
*addrpp = (struct all_addr *)&serv->addr.in6.sin6_addr;
#endif
}
}
}
if (flags & ~F_NXDOMAIN) /* flags set here means a literal found */
{
if (flags & F_QUERY)
log_query(F_CONFIG | F_FORWARD | F_NEG, qdomain, NULL, 0);
else
log_query(F_CONFIG | F_FORWARD | flags, qdomain, *addrpp, 0);
}
else if (qtype && (daemon->options & OPT_NODOTS_LOCAL) && !strchr(qdomain, '.'))
flags = F_NOERR;
if (flags & (F_NOERR | F_NXDOMAIN))
log_query(F_CONFIG | F_FORWARD | F_NEG | qtype | (flags & F_NXDOMAIN), qdomain, NULL, 0);
return flags;
}
/* returns new last_server */
static struct server *forward_query(int udpfd, union mysockaddr *udpaddr,
struct all_addr *dst_addr, HEADER *header,
int plen, unsigned int options, char *dnamebuff,
struct server *servers, struct server *last_server,
time_t now, unsigned long local_ttl)
static void forward_query(struct daemon *daemon, int udpfd, union mysockaddr *udpaddr,
struct all_addr *dst_addr, unsigned int dst_iface,
HEADER *header, int plen, time_t now)
{
struct frec *forward;
char *domain = NULL;
int forwardall = 0, type = 0;
struct all_addr *addrp = NULL;
unsigned short flags = 0;
unsigned short gotname = extract_request(header, (unsigned int)plen, dnamebuff);
unsigned short gotname = extract_request(header, (unsigned int)plen, daemon->namebuff, NULL);
struct server *start = NULL;
/* may be recursion not speced or no servers available. */
if (!header->rd || !servers)
if (!header->rd || !daemon->servers)
forward = NULL;
else if ((forward = lookup_frec_by_sender(ntohs(header->id), udpaddr)))
{
/* retry on existing query, send to all available servers */
domain = forward->sentto->domain;
if (!(options & OPT_ORDER))
if (!(daemon->options & OPT_ORDER))
{
forwardall = 1;
last_server = NULL;
daemon->last_server = NULL;
}
type = forward->sentto->flags & SERV_TYPE;
if (!(start = forward->sentto->next))
start = servers; /* at end of list, recycle */
start = daemon->servers; /* at end of list, recycle */
header->id = htons(forward->new_id);
}
else
{
if (gotname)
{
/* If the query ends in the domain in one of our servers, set
domain to point to that name. We find the largest match to allow both
domain.org and sub.domain.org to exist. */
unsigned int namelen = strlen(dnamebuff);
unsigned int matchlen = 0;
struct server *serv;
for (serv=servers; serv; serv=serv->next)
/* domain matches take priority over NODOTS matches */
if ((serv->flags & SERV_FOR_NODOTS) && type != SERV_HAS_DOMAIN && !strchr(dnamebuff, '.'))
{
unsigned short sflag = serv->addr.sa.sa_family == AF_INET ? F_IPV4 : F_IPV6;
type = SERV_FOR_NODOTS;
flags = 0;
if ((serv->flags & SERV_LITERAL_ADDRESS) && (sflag & gotname))
{
flags = sflag;
if (serv->addr.sa.sa_family == AF_INET)
addrp = (struct all_addr *)&serv->addr.in.sin_addr;
#ifdef HAVE_IPV6
else
addrp = (struct all_addr *)&serv->addr.in6.sin6_addr;
#endif
}
}
else if (serv->flags & SERV_HAS_DOMAIN)
{
unsigned int domainlen = strlen(serv->domain);
if (namelen >= domainlen &&
hostname_isequal(dnamebuff + namelen - domainlen, serv->domain) &&
domainlen >= matchlen)
{
unsigned short sflag = serv->addr.sa.sa_family == AF_INET ? F_IPV4 : F_IPV6;
type = SERV_HAS_DOMAIN;
domain = serv->domain;
matchlen = domainlen;
flags = 0;
if ((serv->flags & SERV_LITERAL_ADDRESS) && ((sflag | F_QUERY ) & gotname))
{
flags = gotname;
if (serv->addr.sa.sa_family == AF_INET)
addrp = (struct all_addr *)&serv->addr.in.sin_addr;
#ifdef HAVE_IPV6
else
addrp = (struct all_addr *)&serv->addr.in6.sin6_addr;
#endif
}
}
}
}
flags = search_servers(daemon, &addrp, gotname, daemon->namebuff, &type, &domain);
if (flags) /* flags set here means a literal found */
{
if (flags & F_QUERY)
log_query(F_CONFIG | F_FORWARD | F_NEG, dnamebuff, NULL);
else
log_query(F_CONFIG | F_FORWARD | flags, dnamebuff, addrp);
}
else
{
/* we may by policy not forward names without a domain part */
if (gotname && (options & OPT_NODOTS_LOCAL) && !strchr(dnamebuff, '.'))
flags = F_NXDOMAIN;
else if (!(forward = get_new_frec(now)))
/* table full - server failure. */
flags = F_NEG;
}
if (!flags && !(forward = get_new_frec(now)))
/* table full - server failure. */
flags = F_NEG;
if (forward)
{
@@ -222,23 +235,24 @@ static struct server *forward_query(int udpfd, union mysockaddr *udpaddr,
always try servers in the order specified in resolv.conf,
otherwise, use the one last known to work. */
if (type != 0 || (options & OPT_ORDER))
start = servers;
else if (!(start = last_server))
if (type != 0 || (daemon->options & OPT_ORDER))
start = daemon->servers;
else if (!(start = daemon->last_server))
{
start = servers;
start = daemon->servers;
forwardall = 1;
}
forward->source = *udpaddr;
forward->dest = *dst_addr;
forward->iface = dst_iface;
forward->new_id = get_id();
forward->fd = udpfd;
forward->orig_id = ntohs(header->id);
header->id = htons(forward->new_id);
}
}
/* check for send errors here (no route to host)
if we fail to send to all nameservers, send back an error
packet straight away (helps modem users when offline) */
@@ -257,22 +271,20 @@ static struct server *forward_query(int udpfd, union mysockaddr *udpaddr,
if (type == (start->flags & SERV_TYPE) &&
(type != SERV_HAS_DOMAIN || hostname_isequal(domain, start->domain)))
{
if (start->flags & SERV_NO_ADDR)
flags = F_NOERR; /* NULL servers are OK. */
else if (!(start->flags & SERV_LITERAL_ADDRESS) &&
sendto(start->sfd->fd, (char *)header, plen, 0,
&start->addr.sa,
sa_len(&start->addr)) != -1)
if (!(start->flags & SERV_LITERAL_ADDRESS) &&
sendto(start->sfd->fd, (char *)header, plen, 0,
&start->addr.sa,
sa_len(&start->addr)) != -1)
{
if (!gotname)
strcpy(dnamebuff, "query");
strcpy(daemon->namebuff, "query");
if (start->addr.sa.sa_family == AF_INET)
log_query(F_SERVER | F_IPV4 | F_FORWARD, dnamebuff,
(struct all_addr *)&start->addr.in.sin_addr);
log_query(F_SERVER | F_IPV4 | F_FORWARD, daemon->namebuff,
(struct all_addr *)&start->addr.in.sin_addr, 0);
#ifdef HAVE_IPV6
else
log_query(F_SERVER | F_IPV6 | F_FORWARD, dnamebuff,
(struct all_addr *)&start->addr.in6.sin6_addr);
log_query(F_SERVER | F_IPV6 | F_FORWARD, daemon->namebuff,
(struct all_addr *)&start->addr.in6.sin6_addr, 0);
#endif
forwarded = 1;
forward->sentto = start;
@@ -282,14 +294,14 @@ static struct server *forward_query(int udpfd, union mysockaddr *udpaddr,
}
if (!(start = start->next))
start = servers;
start = daemon->servers;
if (start == firstsentto)
break;
}
if (forwarded)
return last_server;
return;
/* could not send on, prepare to return */
header->id = htons(forward->orig_id);
@@ -297,19 +309,65 @@ static struct server *forward_query(int udpfd, union mysockaddr *udpaddr,
}
/* could not send on, return empty answer or address if known for whole domain */
plen = setup_reply(header, (unsigned int)plen, addrp, flags, local_ttl);
send_from(udpfd, options & OPT_NOWILD, (char *)header, plen, udpaddr, dst_addr);
plen = setup_reply(header, (unsigned int)plen, addrp, flags, daemon->local_ttl);
send_from(udpfd, daemon->options & OPT_NOWILD, (char *)header, plen, udpaddr, dst_addr, dst_iface);
if (flags & (F_NOERR | F_NXDOMAIN))
log_query(F_CONFIG | F_FORWARD | F_NEG | gotname | (flags & F_NXDOMAIN), dnamebuff, NULL);
return last_server;
return;
}
/* returns new last_server */
struct server *reply_query(struct serverfd *sfd, int options, char *packet, time_t now,
char *dnamebuff, struct server *servers, struct server *last_server,
struct bogus_addr *bogus_nxdomain, struct doctor *doctors)
static int process_reply(struct daemon *daemon, HEADER *header, time_t now,
union mysockaddr *serveraddr, int n)
{
unsigned char *pheader;
/* If upstream is advertising a larger UDP packet size
than we allow, trim it so that we don't get overlarge
requests for the client. */
if ((pheader = find_pseudoheader(header, n)))
{
unsigned short udpsz;
unsigned char *psave = pheader;
GETSHORT(udpsz, pheader);
if (udpsz > daemon->edns_pktsz)
PUTSHORT(daemon->edns_pktsz, psave);
}
/* Complain loudly if the upstream server is non-recursive. */
if (!header->ra && header->rcode == NOERROR && ntohs(header->ancount) == 0)
{
char addrbuff[ADDRSTRLEN];
#ifdef HAVE_IPV6
if (serveraddr->sa.sa_family == AF_INET)
inet_ntop(AF_INET, &serveraddr->in.sin_addr, addrbuff, ADDRSTRLEN);
else if (serveraddr->sa.sa_family == AF_INET6)
inet_ntop(AF_INET6, &serveraddr->in6.sin6_addr, addrbuff, ADDRSTRLEN);
#else
strcpy(addrbuff, inet_ntoa(serveraddr->in.sin_addr));
#endif
syslog(LOG_WARNING, "nameserver %s refused to do a recursive query", addrbuff);
return 0;
}
if ((header->rcode == NOERROR || header->rcode == NXDOMAIN) && header->opcode == QUERY)
{
if (!(daemon->bogus_addr &&
header->rcode == NOERROR &&
check_for_bogus_wildcard(header, (unsigned int)n, daemon->namebuff, daemon->bogus_addr, now)))
{
if (header->rcode == NOERROR && ntohs(header->ancount) != 0)
extract_addresses(header, (unsigned int)n, daemon->namebuff, now, daemon->doctors);
else if (!(daemon->options & OPT_NO_NEG))
extract_neg_addrs(header, (unsigned int)n, daemon->namebuff, now);
}
}
return 1;
}
/* sets new last_server */
void reply_query(struct serverfd *sfd, struct daemon *daemon, time_t now)
{
/* packet from peer server, extract data for cache, and send to
original requester */
@@ -317,7 +375,7 @@ struct server *reply_query(struct serverfd *sfd, int options, char *packet, time
HEADER *header;
union mysockaddr serveraddr;
socklen_t addrlen = sizeof(serveraddr);
int n = recvfrom(sfd->fd, packet, PACKETSZ, 0, &serveraddr.sa, &addrlen);
int n = recvfrom(sfd->fd, daemon->packet, daemon->edns_pktsz, 0, &serveraddr.sa, &addrlen);
/* Determine the address of the server replying so that we can mark that as good */
serveraddr.sa.sa_family = sfd->source_addr.sa.sa_family;
@@ -326,71 +384,41 @@ struct server *reply_query(struct serverfd *sfd, int options, char *packet, time
serveraddr.in6.sin6_flowinfo = htonl(0);
#endif
header = (HEADER *)packet;
header = (HEADER *)daemon->packet;
if (n >= (int)sizeof(HEADER) && header->qr && (forward = lookup_frec(ntohs(header->id))))
{
/* find good server by address if possible, otherwise assume the last one we sent to */
if ((forward->sentto->flags & SERV_TYPE) == 0)
{
for (last_server = servers; last_server; last_server = last_server->next)
struct server *last_server;
daemon->last_server = forward->sentto;
for (last_server = daemon->servers; last_server; last_server = last_server->next)
if (!(last_server->flags & (SERV_LITERAL_ADDRESS | SERV_HAS_DOMAIN | SERV_FOR_NODOTS | SERV_NO_ADDR)) &&
sockaddr_isequal(&last_server->addr, &serveraddr))
break;
if (!last_server)
last_server = forward->sentto;
}
/* Complain loudly if the upstream server is non-recursive. */
if (!header->ra && header->rcode == NOERROR && ntohs(header->ancount) == 0)
{
char addrbuff[ADDRSTRLEN];
#ifdef HAVE_IPV6
if (serveraddr.sa.sa_family == AF_INET)
inet_ntop(AF_INET, &serveraddr.in.sin_addr, addrbuff, ADDRSTRLEN);
else if (serveraddr.sa.sa_family == AF_INET6)
inet_ntop(AF_INET6, &serveraddr.in6.sin6_addr, addrbuff, ADDRSTRLEN);
#else
strcpy(addrbuff, inet_ntoa(serveraddr.in.sin_addr));
#endif
syslog(LOG_WARNING, "nameserver %s refused to do a recursive query", addrbuff);
return NULL;
{
daemon->last_server = last_server;
break;
}
}
if ((header->rcode == NOERROR || header->rcode == NXDOMAIN) && header->opcode == QUERY)
if (process_reply(daemon, header, now, &serveraddr, n))
{
if (!(bogus_nxdomain &&
header->rcode == NOERROR &&
check_for_bogus_wildcard(header, (unsigned int)n, dnamebuff, bogus_nxdomain, now)))
{
if (header->rcode == NOERROR && ntohs(header->ancount) != 0)
extract_addresses(header, (unsigned int)n, dnamebuff, now, doctors);
else if (!(options & OPT_NO_NEG))
extract_neg_addrs(header, (unsigned int)n, dnamebuff, now);
}
header->id = htons(forward->orig_id);
send_from(forward->fd, daemon->options & OPT_NOWILD, daemon->packet, n,
&forward->source, &forward->dest, forward->iface);
forward->new_id = 0; /* cancel */
}
header->id = htons(forward->orig_id);
/* There's no point returning an upstream reply marked as truncated,
since that will prod the resolver into moving to TCP - which we
don't support. */
header->tc = 0; /* goodbye truncate */
send_from(forward->fd, options & OPT_NOWILD, packet, n, &forward->source, &forward->dest);
forward->new_id = 0; /* cancel */
}
return last_server;
}
struct server *receive_query(struct listener *listen, char *packet, struct mx_record *mxnames,
char *mxtarget, unsigned int options, time_t now,
unsigned long local_ttl, char *namebuff,
struct iname *names, struct iname *addrs, struct iname *except,
struct server *last_server, struct server *servers)
void receive_query(struct listener *listen, struct daemon *daemon, time_t now)
{
HEADER *header = (HEADER *)packet;
HEADER *header = (HEADER *)daemon->packet;
union mysockaddr source_addr;
unsigned short type;
struct iname *tmp;
struct all_addr dst_addr;
int check_dst = !(daemon->options & OPT_NOWILD);
int m, n, if_index = 0;
struct iovec iov[1];
struct msghdr msg;
@@ -408,8 +436,8 @@ struct server *receive_query(struct listener *listen, char *packet, struct mx_re
#endif
} control_u;
iov[0].iov_base = packet;
iov[0].iov_len = PACKETSZ;
iov[0].iov_base = daemon->packet;
iov[0].iov_len = daemon->edns_pktsz;
msg.msg_control = control_u.control;
msg.msg_controllen = sizeof(control_u);
@@ -420,19 +448,22 @@ struct server *receive_query(struct listener *listen, char *packet, struct mx_re
msg.msg_iovlen = 1;
if ((n = recvmsg(listen->fd, &msg, 0)) == -1)
return last_server;
return;
source_addr.sa.sa_family = listen->family;
#ifdef HAVE_IPV6
if (listen->family == AF_INET6)
source_addr.in6.sin6_flowinfo = htonl(0);
{
check_dst = 1;
source_addr.in6.sin6_flowinfo = htonl(0);
}
#endif
if (!(options & OPT_NOWILD) && msg.msg_controllen < sizeof(struct cmsghdr))
return last_server;
if (check_dst && msg.msg_controllen < sizeof(struct cmsghdr))
return;
#if defined(IP_PKTINFO)
if (!(options & OPT_NOWILD) && listen->family == AF_INET)
if (check_dst && listen->family == AF_INET)
for (cmptr = CMSG_FIRSTHDR(&msg); cmptr; cmptr = CMSG_NXTHDR(&msg, cmptr))
if (cmptr->cmsg_level == SOL_IP && cmptr->cmsg_type == IP_PKTINFO)
{
@@ -440,7 +471,7 @@ struct server *receive_query(struct listener *listen, char *packet, struct mx_re
if_index = ((struct in_pktinfo *)CMSG_DATA(cmptr))->ipi_ifindex;
}
#elif defined(IP_RECVDSTADDR) && defined(IP_RECVIF)
if (!(options & OPT_NOWILD) && listen->family == AF_INET)
if (check_dst && listen->family == AF_INET)
{
for (cmptr = CMSG_FIRSTHDR(&msg); cmptr; cmptr = CMSG_NXTHDR(&msg, cmptr))
if (cmptr->cmsg_level == IPPROTO_IP && cmptr->cmsg_type == IP_RECVDSTADDR)
@@ -451,7 +482,7 @@ struct server *receive_query(struct listener *listen, char *packet, struct mx_re
#endif
#ifdef HAVE_IPV6
if (!(options & OPT_NOWILD) && listen->family == AF_INET6)
if (listen->family == AF_INET6)
{
for (cmptr = CMSG_FIRSTHDR(&msg); cmptr; cmptr = CMSG_NXTHDR(&msg, cmptr))
if (cmptr->cmsg_level == IPV6_LEVEL && cmptr->cmsg_type == IPV6_PKTINFO)
@@ -463,39 +494,39 @@ struct server *receive_query(struct listener *listen, char *packet, struct mx_re
#endif
if (n < (int)sizeof(HEADER) || header->qr)
return last_server;
return;
/* enforce available interface configuration */
if (!(options & OPT_NOWILD))
if (check_dst)
{
struct ifreq ifr;
if (if_index == 0)
return last_server;
return;
if (except || names)
if (daemon->if_except || daemon->if_names)
{
#ifdef SIOCGIFNAME
ifr.ifr_ifindex = if_index;
if (ioctl(listen->fd, SIOCGIFNAME, &ifr) == -1)
return last_server;
return;
#else
if (!if_indextoname(if_index, ifr.ifr_name))
return last_server;
return;
#endif
}
for (tmp = except; tmp; tmp = tmp->next)
for (tmp = daemon->if_except; tmp; tmp = tmp->next)
if (tmp->name && (strcmp(tmp->name, ifr.ifr_name) == 0))
return last_server;
return;
if (names || addrs)
if (daemon->if_names || daemon->if_addrs)
{
for (tmp = names; tmp; tmp = tmp->next)
for (tmp = daemon->if_names; tmp; tmp = tmp->next)
if (tmp->name && (strcmp(tmp->name, ifr.ifr_name) == 0))
break;
if (!tmp)
for (tmp = addrs; tmp; tmp = tmp->next)
for (tmp = daemon->if_addrs; tmp; tmp = tmp->next)
if (tmp->addr.sa.sa_family == listen->family)
{
if (tmp->addr.sa.sa_family == AF_INET &&
@@ -510,31 +541,212 @@ struct server *receive_query(struct listener *listen, char *packet, struct mx_re
#endif
}
if (!tmp)
return last_server;
return;
}
}
if (extract_request(header, (unsigned int)n, namebuff))
if (extract_request(header, (unsigned int)n, daemon->namebuff, &type))
{
if (listen->family == AF_INET)
log_query(F_QUERY | F_IPV4 | F_FORWARD, namebuff,
(struct all_addr *)&source_addr.in.sin_addr);
log_query(F_QUERY | F_IPV4 | F_FORWARD, daemon->namebuff,
(struct all_addr *)&source_addr.in.sin_addr, type);
#ifdef HAVE_IPV6
else
log_query(F_QUERY | F_IPV6 | F_FORWARD, namebuff,
(struct all_addr *)&source_addr.in6.sin6_addr);
log_query(F_QUERY | F_IPV6 | F_FORWARD, daemon->namebuff,
(struct all_addr *)&source_addr.in6.sin6_addr, type);
#endif
}
m = answer_request (header, ((char *) header) + PACKETSZ, (unsigned int)n,
mxnames, mxtarget, options, now, local_ttl, namebuff);
m = answer_request (header, ((char *) header) + PACKETSZ, (unsigned int)n, daemon, now);
if (m >= 1)
send_from(listen->fd, options & OPT_NOWILD, (char *)header, m, &source_addr, &dst_addr);
send_from(listen->fd, daemon->options & OPT_NOWILD, (char *)header, m, &source_addr, &dst_addr, if_index);
else
last_server = forward_query(listen->fd, &source_addr, &dst_addr,
header, n, options, namebuff, servers,
last_server, now, local_ttl);
return last_server;
forward_query(daemon, listen->fd, &source_addr, &dst_addr, if_index,
header, n, now);
}
static int read_write(int fd, char *packet, int size, int rw)
{
int n, done;
for (done = 0; done < size; done += n)
{
retry:
if (rw)
n = read(fd, &packet[done], (size_t)(size - done));
else
n = write(fd, &packet[done], (size_t)(size - done));
if (n == 0)
return 0;
else if (n == -1)
{
if (errno == EINTR)
goto retry;
else if (errno == EAGAIN)
{
struct timespec waiter;
waiter.tv_sec = 0;
waiter.tv_nsec = 10000;
nanosleep(&waiter, NULL);
goto retry;
}
else
return 0;
}
}
return 1;
}
/* The daemon forks before calling this: it should deal with one connection,
blocking as neccessary, and then return. Note, need to be a bit careful
about resources for debug mode, when the fork is suppressed: that's
done by the caller. */
char *tcp_request(struct daemon *daemon, int confd, time_t now)
{
int size = 0, m;
unsigned short qtype, gotname;
unsigned char c1, c2;
/* Max TCP packet + slop */
char *packet = malloc(65536 + MAXDNAME + RRFIXEDSZ);
HEADER *header;
struct server *last_server;
while (1)
{
if (!packet ||
!read_write(confd, &c1, 1, 1) || !read_write(confd, &c2, 1, 1) ||
!(size = c1 << 8 | c2) ||
!read_write(confd, packet, size, 1))
return packet;
if (size < (int)sizeof(HEADER))
continue;
header = (HEADER *)packet;
if ((gotname = extract_request(header, (unsigned int)size, daemon->namebuff, &qtype)))
{
union mysockaddr peer_addr;
socklen_t peer_len = sizeof(union mysockaddr);
if (getpeername(confd, (struct sockaddr *)&peer_addr, &peer_len) != -1)
{
if (peer_addr.sa.sa_family == AF_INET)
log_query(F_QUERY | F_IPV4 | F_FORWARD, daemon->namebuff,
(struct all_addr *)&peer_addr.in.sin_addr, qtype);
#ifdef HAVE_IPV6
else
log_query(F_QUERY | F_IPV6 | F_FORWARD, daemon->namebuff,
(struct all_addr *)&peer_addr.in6.sin6_addr, qtype);
#endif
}
}
/* m > 0 if answered from cache */
m = answer_request(header, ((char *) header) + 65536, (unsigned int)size, daemon, now);
if (m == 0)
{
unsigned short flags = 0;
struct all_addr *addrp = NULL;
int type = 0;
char *domain = NULL;
if (gotname)
flags = search_servers(daemon, &addrp, gotname, daemon->namebuff, &type, &domain);
if (type != 0 || (daemon->options & OPT_ORDER) || !daemon->last_server)
last_server = daemon->servers;
else
last_server = daemon->last_server;
if (!flags && last_server)
{
struct server *firstsendto = NULL;
/* Loop round available servers until we succeed in connecting to one.
Note that this code subtley ensures that consecutive queries on this connection
which can go to the same server, do so. */
while (1)
{
if (!firstsendto)
firstsendto = last_server;
else
{
if (!(last_server = last_server->next))
last_server = daemon->servers;
if (last_server == firstsendto)
break;
}
/* server for wrong domain */
if (type != (last_server->flags & SERV_TYPE) ||
(type == SERV_HAS_DOMAIN && !hostname_isequal(domain, last_server->domain)))
continue;
if ((last_server->tcpfd == -1) &&
(last_server->tcpfd = socket(last_server->addr.sa.sa_family, SOCK_STREAM, 0)) != -1 &&
connect(last_server->tcpfd, &last_server->addr.sa, sa_len(&last_server->addr)) == -1)
{
close(last_server->tcpfd);
last_server->tcpfd = -1;
}
if (last_server->tcpfd == -1)
continue;
c1 = size >> 8;
c2 = size;
if (!read_write(last_server->tcpfd, &c1, 1, 0) ||
!read_write(last_server->tcpfd, &c2, 1, 0) ||
!read_write(last_server->tcpfd, packet, size, 0) ||
!read_write(last_server->tcpfd, &c1, 1, 1) ||
!read_write(last_server->tcpfd, &c2, 1, 1))
{
close(last_server->tcpfd);
last_server->tcpfd = -1;
continue;
}
m = (c1 << 8) | c2;
if (!read_write(last_server->tcpfd, packet, m, 1))
return packet;
if (!gotname)
strcpy(daemon->namebuff, "query");
if (last_server->addr.sa.sa_family == AF_INET)
log_query(F_SERVER | F_IPV4 | F_FORWARD, daemon->namebuff,
(struct all_addr *)&last_server->addr.in.sin_addr, 0);
#ifdef HAVE_IPV6
else
log_query(F_SERVER | F_IPV6 | F_FORWARD, daemon->namebuff,
(struct all_addr *)&last_server->addr.in6.sin6_addr, 0);
#endif
/* There's no point in updating the cache, since this process will exit and
lose the information after one query. We make this call for the alias and
bogus-nxdomain side-effects. */
process_reply(daemon, header, now, &last_server->addr, m);
break;
}
}
/* In case of local answer or no connections made. */
if (m == 0)
m = setup_reply(header, (unsigned int)size, addrp, flags, daemon->local_ttl);
}
c1 = m>>8;
c2 = m;
if (!read_write(confd, &c1, 1, 0) ||
!read_write(confd, &c2, 1, 0) ||
!read_write(confd, packet, m, 0))
return packet;
}
}
static struct frec *get_new_frec(time_t now)
@@ -603,8 +815,8 @@ static struct frec *lookup_frec(unsigned short id)
static struct frec *lookup_frec_by_sender(unsigned short id,
union mysockaddr *addr)
{
struct frec *f;
struct frec *f;
for(f = frec_list; f; f = f->next)
if (f->new_id &&
f->orig_id == id &&

View File

@@ -235,13 +235,8 @@ void load_dhcp(char *file, char *suffix, time_t now, char *hostname)
for (lease = leases; lease; lease = lease->next)
{
if (lease->fqdn)
{
cache_add_dhcp_entry(lease->fqdn, &lease->addr, lease->expires, F_REVERSE);
cache_add_dhcp_entry(lease->name, &lease->addr, lease->expires, 0);
}
else
cache_add_dhcp_entry(lease->name, &lease->addr, lease->expires, F_REVERSE);
cache_add_dhcp_entry(lease->fqdn, &lease->addr, lease->expires);
cache_add_dhcp_entry(lease->name, &lease->addr, lease->expires);
}
}

View File

@@ -15,12 +15,11 @@
#include "dnsmasq.h"
static struct dhcp_lease *leases;
FILE *lease_file;
int dns_dirty, file_dirty, new_lease;
int leases_left;
static FILE *lease_file;
static int dns_dirty, file_dirty, new_lease;
static int leases_left;
int lease_init(char *filename, char *domain, char *buff,
char *buff2, time_t now, int maxleases)
void lease_init(struct daemon *daemon, time_t now)
{
unsigned int e0, e1, e2, e3, e4, e5, a0, a1, a2, a3;
unsigned long ei;
@@ -30,19 +29,22 @@ int lease_init(char *filename, char *domain, char *buff,
struct dhcp_lease *lease;
int clid_len = 0;
int has_old = 0;
char *buff = daemon->dhcp_buff;
char *buff2 = daemon->dhcp_buff2;
leases = NULL;
leases_left = maxleases;
leases_left = daemon->dhcp_max;
/* NOTE: need a+ mode to create file if it doesn't exist */
if (!(lease_file = fopen(filename, "a+")))
if (!(lease_file = fopen(daemon->lease_file, "a+")))
die("cannot open or create leases file: %s", NULL);
/* a+ mode lease pointer at end. */
rewind(lease_file);
while (fscanf(lease_file, "%lu %x:%x:%x:%x:%x:%x %d.%d.%d.%d %256s %500s",
&ei, &e0, &e1, &e2, &e3, &e4, &e5, &a0, &a1, &a2, &a3, buff, buff2) == 13)
while (fscanf(lease_file, "%lu %x:%x:%x:%x:%x:%x %d.%d.%d.%d %257s %257s",
&ei, &e0, &e1, &e2, &e3, &e4, &e5, &a0, &a1, &a2, &a3,
buff, buff2) == 13)
{
#ifdef HAVE_BROKEN_RTC
if (ei)
@@ -90,14 +92,14 @@ int lease_init(char *filename, char *domain, char *buff,
memcpy(lease->hwaddr, hwaddr, ETHER_ADDR_LEN);
if (strcmp(buff, "*") != 0)
lease_set_hostname(lease, buff, domain);
lease_set_hostname(lease, buff, daemon->domain_suffix);
}
dns_dirty = 1;
file_dirty = has_old;
new_lease = 0;
return fileno(lease_file);
daemon->lease_fd = fileno(lease_file);
}
void lease_update_from_configs(struct dhcp_config *dhcp_configs, char *domain)
@@ -175,13 +177,8 @@ void lease_update_dns(void)
for (lease = leases; lease; lease = lease->next)
{
if (lease->fqdn)
{
cache_add_dhcp_entry(lease->fqdn, &lease->addr, lease->expires, F_REVERSE);
cache_add_dhcp_entry(lease->hostname, &lease->addr, lease->expires, 0);
}
else if (lease->hostname)
cache_add_dhcp_entry(lease->hostname, &lease->addr, lease->expires, F_REVERSE);
cache_add_dhcp_entry(lease->fqdn, &lease->addr, lease->expires);
cache_add_dhcp_entry(lease->hostname, &lease->addr, lease->expires);
}
dns_dirty = 0;
@@ -220,9 +217,6 @@ void lease_prune(struct dhcp_lease *target, time_t now)
struct dhcp_lease *lease_find_by_client(unsigned char *clid, int clid_len)
{
/* zero length means clid from hwaddr: never match am option clid to
a hardware-address derived clid */
struct dhcp_lease *lease;
if (clid_len)
@@ -235,8 +229,7 @@ struct dhcp_lease *lease_find_by_client(unsigned char *clid, int clid_len)
else
{
for (lease = leases; lease; lease = lease->next)
if (!lease->clid &&
memcmp(clid, lease->hwaddr, ETHER_ADDR_LEN) == 0)
if (memcmp(clid, lease->hwaddr, ETHER_ADDR_LEN) == 0)
return lease;
}

View File

@@ -14,29 +14,34 @@
#include "dnsmasq.h"
static struct irec *add_iface(struct irec *list, char *name, union mysockaddr *addr,
struct iname *names, struct iname *addrs,
struct iname *except)
static struct irec *add_iface(struct daemon *daemon, struct irec *list, char *name, union mysockaddr *addr)
{
struct irec *iface;
struct iname *tmp;
/* check blacklist */
if (except)
for (tmp = except; tmp; tmp = tmp->next)
if (daemon->if_except)
for (tmp = daemon->if_except; tmp; tmp = tmp->next)
if (tmp->name && strcmp(tmp->name, name) == 0)
return list;
{
/* record address of named interfaces, for TCP access control */
tmp->addr = *addr;
return list;
}
/* we may need to check the whitelist */
if (names || addrs)
if (daemon->if_names || daemon->if_addrs)
{
int found = 0;
for (tmp = names; tmp; tmp = tmp->next)
for (tmp = daemon->if_names; tmp; tmp = tmp->next)
if (tmp->name && (strcmp(tmp->name, name) == 0))
found = tmp->used = 1;
for (tmp = addrs; tmp; tmp = tmp->next)
{
tmp->addr = *addr;
found = tmp->used = 1;
}
for (tmp = daemon->if_addrs; tmp; tmp = tmp->next)
if (sockaddr_isequal(&tmp->addr, addr))
found = tmp->used = 1;
@@ -60,10 +65,7 @@ static struct irec *add_iface(struct irec *list, char *name, union mysockaddr *a
}
struct irec *enumerate_interfaces(struct iname **names,
struct iname **addrs,
struct iname *except,
int port)
struct irec *enumerate_interfaces(struct daemon *daemon)
{
struct irec *iface = NULL;
char *buf, *ptr;
@@ -119,7 +121,7 @@ struct irec *enumerate_interfaces(struct iname **names,
if (ifr->ifr_addr.sa_family == AF_INET)
{
addr.in = *((struct sockaddr_in *) &ifr->ifr_addr);
addr.in.sin_port = htons(port);
addr.in.sin_port = htons(daemon->port);
}
#ifdef HAVE_IPV6
else if (ifr->ifr_addr.sa_family == AF_INET6)
@@ -129,7 +131,7 @@ struct irec *enumerate_interfaces(struct iname **names,
#else
addr.in6 = *((struct sockaddr_in6 *) &ifr->ifr_addr);
#endif
addr.in6.sin6_port = htons(port);
addr.in6.sin6_port = htons(daemon->port);
addr.in6.sin6_flowinfo = htonl(0);
}
#endif
@@ -141,10 +143,10 @@ struct irec *enumerate_interfaces(struct iname **names,
/* If we are restricting the set of interfaces to use, make
sure that loopback interfaces are in that set. */
if (*names && (ifr->ifr_flags & IFF_LOOPBACK))
if (daemon->if_names && (ifr->ifr_flags & IFF_LOOPBACK))
{
struct iname *lo;
for (lo = *names; lo; lo = lo->next)
for (lo = daemon->if_names; lo; lo = lo->next)
if (lo->name && strcmp(lo->name, ifr->ifr_name) == 0)
{
lo->isloop = 1;
@@ -155,12 +157,12 @@ struct irec *enumerate_interfaces(struct iname **names,
lo = safe_malloc(sizeof(struct iname));
lo->name = safe_string_alloc(ifr->ifr_name);
lo->isloop = lo->used = 1;
lo->next = *names;
*names = lo;
lo->next = daemon->if_names;
daemon->if_names = lo;
}
}
iface = add_iface(iface, ifr->ifr_name, &addr, *names, *addrs, except);
iface = add_iface(daemon, iface, ifr->ifr_name, &addr);
#if defined(HAVE_LINUX_IPV6_PROC) && defined(HAVE_IPV6)
/* IPv6 addresses don't seem to work with SIOCGIFCONF. Barf */
@@ -191,7 +193,7 @@ struct irec *enumerate_interfaces(struct iname **names,
sscanf(addrstring+i+i, "%02x", &byte);
addr6p[i] = byte;
}
addr6.in6.sin6_port = htons(port);
addr6.in6.sin6_port = htons(daemon->port);
addr6.in6.sin6_flowinfo = htonl(0);
addr6.in6.sin6_scope_id = htonl(scope);
@@ -204,7 +206,7 @@ struct irec *enumerate_interfaces(struct iname **names,
}
if (found)
iface = add_iface(iface, ifr->ifr_name, &addr6, *names, *addrs, except);
iface = add_iface(daemon, iface, ifr->ifr_name, &addr6);
}
#endif /* LINUX */
}
@@ -220,46 +222,14 @@ struct irec *enumerate_interfaces(struct iname **names,
return iface;
}
struct listener *create_wildcard_listeners(int port)
#ifdef HAVE_IPV6
static int create_ipv6_listener(struct listener **link, int port)
{
#if !(defined(IP_PKTINFO) || (defined(IP_RECVDSTADDR) && defined(IP_RECVIF) && defined(IP_SENDSRCADDR)))
return NULL;
#else
union mysockaddr addr;
int tcpfd, fd, flags, save;
struct listener *l;
int opt = 1;
struct listener *listen;
#ifdef HAVE_IPV6
int fd;
#endif
addr.in.sin_family = AF_INET;
addr.in.sin_addr.s_addr = INADDR_ANY;
addr.in.sin_port = htons(port);
#ifdef HAVE_SOCKADDR_SA_LEN
addr.in.sin_len = sizeof(struct sockaddr_in);
#endif
listen = safe_malloc(sizeof(struct listener));
if ((listen->fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
free(listen);
return NULL;
}
if (setsockopt(listen->fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
#if defined(IP_PKTINFO)
setsockopt(listen->fd, SOL_IP, IP_PKTINFO, &opt, sizeof(opt)) == -1 ||
#elif defined(IP_RECVDSTADDR) && defined(IP_RECVIF)
setsockopt(listen->fd, IPPROTO_IP, IP_RECVDSTADDR, &opt, sizeof(opt)) == -1 ||
setsockopt(listen->fd, IPPROTO_IP, IP_RECVIF, &opt, sizeof(opt)) == -1 ||
#endif
bind(listen->fd, (struct sockaddr *)&addr, sa_len(&addr)) == -1)
{
close(listen->fd);
free(listen);
return NULL;
}
listen->next = NULL;
listen->family = AF_INET;
#ifdef HAVE_IPV6
addr.in6.sin6_family = AF_INET6;
addr.in6.sin6_addr = in6addr_any;
addr.in6.sin6_port = htons(port);
@@ -267,65 +237,152 @@ struct listener *create_wildcard_listeners(int port)
#ifdef HAVE_SOCKADDR_SA_LEN
addr.in6.sin6_len = sizeof(struct sockaddr_in6);
#endif
/* No error of the kernel doesn't support IPv6 */
if ((fd = socket(AF_INET6, SOCK_DGRAM, 0)) == -1)
return (errno == EPROTONOSUPPORT ||
errno == EAFNOSUPPORT ||
errno == EINVAL);
if ((tcpfd = socket(AF_INET6, SOCK_STREAM, 0)) == -1)
{
if (errno != EPROTONOSUPPORT &&
errno != EAFNOSUPPORT &&
errno != EINVAL)
{
close(listen->fd);
free(listen);
return NULL;
}
}
else
{
listen->next = safe_malloc(sizeof(struct listener));
listen->next->fd = fd;
listen->next->family = AF_INET6;
listen->next->next = NULL;
if (setsockopt(listen->next->fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
setsockopt(listen->next->fd, IPV6_LEVEL, IPV6_PKTINFO, &opt, sizeof(opt)) == -1 ||
bind(listen->next->fd, (struct sockaddr *)&addr, sa_len(&addr)) == -1)
{
close(listen->next->fd);
free(listen->next);
close(listen->fd);
free(listen);
return NULL;
}
save = errno;
close(fd);
errno = save;
return 0;
}
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
setsockopt(tcpfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
setsockopt(fd, IPV6_LEVEL, IPV6_V6ONLY, &opt, sizeof(opt)) == -1 ||
setsockopt(tcpfd, IPV6_LEVEL, IPV6_V6ONLY, &opt, sizeof(opt)) == -1 ||
(flags = fcntl(tcpfd, F_GETFL, 0)) == -1 ||
fcntl(tcpfd, F_SETFL, flags | O_NONBLOCK) == -1 ||
#ifdef IPV6_RECVPKTINFO
setsockopt(fd, IPV6_LEVEL, IPV6_RECVPKTINFO, &opt, sizeof(opt)) == -1 ||
#else
setsockopt(fd, IPV6_LEVEL, IPV6_PKTINFO, &opt, sizeof(opt)) == -1 ||
#endif
bind(tcpfd, (struct sockaddr *)&addr, sa_len(&addr)) == -1 ||
listen(tcpfd, 5) == -1 ||
bind(fd, (struct sockaddr *)&addr, sa_len(&addr)) == -1)
{
save = errno;
close(fd);
close(tcpfd);
errno = save;
return 0;
}
return listen;
l = safe_malloc(sizeof(struct listener));
l->fd = fd;
l->tcpfd = tcpfd;
l->family = AF_INET6;
l->next = NULL;
*link = l;
return 1;
}
#endif
struct listener *create_wildcard_listeners(int port)
{
#if !(defined(IP_PKTINFO) || (defined(IP_RECVDSTADDR) && defined(IP_RECVIF) && defined(IP_SENDSRCADDR)))
return NULL;
#else
union mysockaddr addr;
int opt = 1;
struct listener *l, *l6 = NULL;
int flags;
int tcpfd, fd;
addr.in.sin_family = AF_INET;
addr.in.sin_addr.s_addr = INADDR_ANY;
addr.in.sin_port = htons(port);
#ifdef HAVE_SOCKADDR_SA_LEN
addr.in.sin_len = sizeof(struct sockaddr_in);
#endif
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
return NULL;
if ((tcpfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
close (fd);
return NULL;
}
if (setsockopt(tcpfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
bind(tcpfd, (struct sockaddr *)&addr, sa_len(&addr)) == -1 ||
listen(tcpfd, 5) == -1 ||
(flags = fcntl(tcpfd, F_GETFL, 0)) == -1 ||
fcntl(tcpfd, F_SETFL, flags | O_NONBLOCK) == -1 ||
#ifdef HAVE_IPV6
!create_ipv6_listener(&l6, port) ||
#endif
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
#if defined(IP_PKTINFO)
setsockopt(fd, SOL_IP, IP_PKTINFO, &opt, sizeof(opt)) == -1 ||
#elif defined(IP_RECVDSTADDR) && defined(IP_RECVIF)
setsockopt(fd, IPPROTO_IP, IP_RECVDSTADDR, &opt, sizeof(opt)) == -1 ||
setsockopt(fd, IPPROTO_IP, IP_RECVIF, &opt, sizeof(opt)) == -1 ||
#endif
bind(fd, (struct sockaddr *)&addr, sa_len(&addr)) == -1)
{
close(fd);
close(tcpfd);
return NULL;
}
l = safe_malloc(sizeof(struct listener));
l->family = AF_INET;
l->fd = fd;
l->tcpfd = tcpfd;
l->next = l6;
return l;
#endif
}
struct listener *create_bound_listeners(struct irec *interfaces)
struct listener *create_bound_listeners(struct irec *interfaces, int port)
{
struct listener *listeners = NULL;
struct irec *iface;
int opt = 1;
int flags = port, opt = 1;
/* Create bound listeners only for IPv4, IPv6 always binds the wildcard */
#ifdef HAVE_IPV6
if (!create_ipv6_listener(&listeners, port))
die("failed to to create listening socket: %s", NULL);
#endif
for (iface = interfaces ;iface; iface = iface->next)
{
struct listener *new = safe_malloc(sizeof(struct listener));
new->family = iface->addr.sa.sa_family;
new->next = listeners;
listeners = new;
if ((new->fd = socket(iface->addr.sa.sa_family, SOCK_DGRAM, 0)) == -1)
die("failed to create socket: %s", NULL);
if (setsockopt(new->fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
bind(new->fd, &iface->addr.sa, sa_len(&iface->addr)) == -1)
die("failed to bind socket: %s", NULL);
}
if (iface->addr.sa.sa_family == AF_INET)
{
struct listener *new = safe_malloc(sizeof(struct listener));
new->family = iface->addr.sa.sa_family;
new->next = listeners;
listeners = new;
if ((new->tcpfd = socket(iface->addr.sa.sa_family, SOCK_STREAM, 0)) == -1 ||
(new->fd = socket(iface->addr.sa.sa_family, SOCK_DGRAM, 0)) == -1 ||
setsockopt(new->fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
setsockopt(new->tcpfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
/* See Stevens 16.6 */
(flags = fcntl(new->tcpfd, F_GETFL, 0)) == -1 ||
fcntl(new->tcpfd, F_SETFL, flags | O_NONBLOCK) == -1 ||
bind(new->tcpfd, &iface->addr.sa, sa_len(&iface->addr)) == -1 ||
bind(new->fd, &iface->addr.sa, sa_len(&iface->addr)) == -1 ||
listen(new->tcpfd, 5) == -1)
die("failed to to create listening socket: %s", NULL);
}
return listeners;
}
static struct serverfd *allocate_sfd(union mysockaddr *addr, struct serverfd **sfds)
struct serverfd *allocate_sfd(union mysockaddr *addr, struct serverfd **sfds)
{
struct serverfd *sfd;
@@ -361,17 +418,19 @@ static struct serverfd *allocate_sfd(union mysockaddr *addr, struct serverfd **s
return sfd;
}
struct server *check_servers(struct server *new, struct irec *interfaces, struct serverfd **sfds)
void check_servers(struct daemon *daemon, struct irec *interfaces)
{
char addrbuff[ADDRSTRLEN];
struct irec *iface;
struct server *tmp, *ret = NULL;
struct server *new, *tmp, *ret = NULL;
int port = 0;
/* forward table rules reference servers, so have to blow them away */
forward_init(0);
for (;new; new = tmp)
daemon->last_server = NULL;
for (new = daemon->servers; new; new = tmp)
{
tmp = new->next;
@@ -403,7 +462,7 @@ struct server *check_servers(struct server *new, struct irec *interfaces, struct
}
/* Do we need a socket set? */
if (!new->sfd && !(new->sfd = allocate_sfd(&new->source_addr, sfds)))
if (!new->sfd && !(new->sfd = allocate_sfd(&new->source_addr, &daemon->sfds)))
{
syslog(LOG_WARNING,
"ignoring nameserver %s - cannot make/bind socket: %m", addrbuff);
@@ -433,15 +492,16 @@ struct server *check_servers(struct server *new, struct irec *interfaces, struct
syslog(LOG_INFO, "using nameserver %s#%d", addrbuff, port);
}
return ret;
daemon->servers = ret;
}
struct server *reload_servers(char *fname, char *buff, struct server *serv, int query_port)
void reload_servers(char *fname, struct daemon *daemon)
{
FILE *f;
char *line;
struct server *old_servers = NULL;
struct server *new_servers = NULL;
struct server *serv = daemon->servers;
/* move old servers to free list - we can reuse the memory
and not risk malloc if there are the same or fewer new servers.
@@ -471,7 +531,7 @@ struct server *reload_servers(char *fname, char *buff, struct server *serv, int
else
{
syslog(LOG_INFO, "reading %s", fname);
while ((line = fgets(buff, MAXDNAME, f)))
while ((line = fgets(daemon->namebuff, MAXDNAME, f)))
{
union mysockaddr addr, source_addr;
char *token = strtok(line, " \t\n\r");
@@ -494,7 +554,7 @@ struct server *reload_servers(char *fname, char *buff, struct server *serv, int
source_addr.in.sin_family = addr.in.sin_family = AF_INET;
addr.in.sin_port = htons(NAMESERVER_PORT);
source_addr.in.sin_addr.s_addr = INADDR_ANY;
source_addr.in.sin_port = htons(query_port);
source_addr.in.sin_port = htons(daemon->query_port);
}
#ifdef HAVE_IPV6
else if (inet_pton(AF_INET6, token, &addr.in6.sin6_addr))
@@ -506,7 +566,7 @@ struct server *reload_servers(char *fname, char *buff, struct server *serv, int
addr.in6.sin6_port = htons(NAMESERVER_PORT);
source_addr.in6.sin6_flowinfo = addr.in6.sin6_flowinfo = htonl(0);
source_addr.in6.sin6_addr = in6addr_any;
source_addr.in6.sin6_port = htons(query_port);
source_addr.in6.sin6_port = htons(daemon->query_port);
}
#endif /* IPV6 */
else
@@ -542,7 +602,7 @@ struct server *reload_servers(char *fname, char *buff, struct server *serv, int
old_servers = tmp;
}
return new_servers;
daemon->servers = new_servers;
}

View File

@@ -21,7 +21,7 @@ struct myoption {
int val;
};
#define OPTSTRING "ZDNLERzowefnbvhdqr:m:p:c:l:s:i:t:u:g:a:x:S:C:A:T:H:Q:I:B:F:G:O:M:X:V:U:j:"
#define OPTSTRING "ZDNLERzowefnbvhdkqr:m:p:c:l:s:i:t:u:g:a:x:S:C:A:T:H:Q:I:B:F:G:O:M:X:V:U:j:P:"
static struct myoption opts[] = {
{"version", 0, 0, 'v'},
@@ -72,6 +72,8 @@ static struct myoption opts[] = {
{"alias", 1, 0, 'V' },
{"dhcp-vendorclass", 1, 0, 'U'},
{"dhcp-userclass", 1, 0, 'j'},
{"edns-packet-max", 1, 0, 'P'},
{"keep-in-foreground", 0, 0, 'k'},
{0, 0, 0, 0}
};
@@ -88,6 +90,7 @@ static struct optflags optmap[] = {
{ 'h', OPT_NO_HOSTS },
{ 'n', OPT_NO_POLL },
{ 'd', OPT_DEBUG },
{ 'k', OPT_NO_FORK },
{ 'o', OPT_ORDER },
{ 'R', OPT_NO_RESOLV },
{ 'E', OPT_EXPAND },
@@ -123,6 +126,7 @@ static char *usage =
"-i, --interface=interface Specify interface(s) to listen on.\n"
"-I, --except-interface=int Specify interface(s) NOT to listen on.\n"
"-j, --dhcp-userclass=<id>,<class> Map DHCP user class to option set.\n"
"-k, --keep-in-foreground Do NOT fork into the background, do NOT run in debug mode.\n"
"-l, --dhcp-leasefile=path Specify where to store DHCP leases (defaults to " LEASEFILE ").\n"
"-L, --localmx Return MX records for local hosts.\n"
"-m, --mx-host=host_name Specify the MX name to reply to.\n"
@@ -132,6 +136,7 @@ static char *usage =
"-o, --strict-order Use nameservers strictly in the order given in " RESOLVFILE ".\n"
"-O, --dhcp-option=<optspec> Set extra options to be set to DHCP clients.\n"
"-p, --port=number Specify port to listen for DNS requests on (defaults to 53).\n"
"-P, --edns-packet-max=<size> Maximum supported UDP packet size for EDNS.0 (defaults to %d).\n"
"-q, --log-queries Log queries.\n"
"-Q, --query-port=number Force the originating port for upstream queries.\n"
"-R, --no-resolv Do NOT read resolv.conf.\n"
@@ -143,7 +148,7 @@ static char *usage =
"-T, --local-ttl=time Specify time-to-live in seconds for replies from /etc/hosts.\n"
"-u, --user=username Change to this user after startup. (defaults to " CHUSER ").\n"
"-U, --dhcp-vendorclass=<id>,<class> Map DHCP vendor class to option set.\n"
"-v, --version Display dnsmasq version.\n"
"-v, --version Display dnsmasq version and copyright information.\n"
"-V, --alias=addr,addr,mask Translate IPv4 addresses from upstream servers.\n"
"-w, --help Display this message.\n"
"-x, --pid-file=path Specify path of PID file. (defaults to " RUNFILE ").\n"
@@ -153,26 +158,33 @@ static char *usage =
"\n";
unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **resolv_files,
struct mx_record **mxnames, char **mxtarget, char **lease_file,
char **username, char **groupname, char **domain_suffix, char **runfile,
struct iname **if_names, struct iname **if_addrs, struct iname **if_except,
struct bogus_addr **bogus_addr, struct server **serv_addrs, int *cachesize, int *port,
int *query_port, unsigned long *local_ttl, char **addn_hosts, struct dhcp_context **dhcp,
struct dhcp_config **dhcp_conf, struct dhcp_opt **dhcp_opts, struct dhcp_vendor **dhcp_vendors, char **dhcp_file,
char **dhcp_sname, struct in_addr *dhcp_next_server, int *dhcp_max,
unsigned int *min_leasetime, struct doctor **doctors)
struct daemon *read_opts (int argc, char **argv)
{
struct daemon *daemon = safe_malloc(sizeof(struct daemon));
char *buff = safe_malloc(MAXDNAME);
int option = 0, i;
unsigned int flags = 0;
FILE *file_save = NULL, *f = NULL;
char *file_name_save = NULL, *conffile = CONFFILE;
int conffile_set = 0;
int line_save = 0, lineno = 0;
opterr = 0;
*min_leasetime = UINT_MAX;
memset(daemon, 0, sizeof(struct daemon));
daemon->namebuff = buff;
/* Set defaults - everything else is zero or NULL */
daemon->min_leasetime = UINT_MAX;
daemon->cachesize = CACHESIZ;
daemon->port = NAMESERVER_PORT;
daemon->default_resolv.is_default = 1;
daemon->default_resolv.name = RESOLVFILE;
daemon->resolv_files = &daemon->default_resolv;
daemon->username = CHUSER;
daemon->groupname = CHGRP;
daemon->runfile = RUNFILE;
daemon->dhcp_max = MAXLEASES;
daemon->edns_pktsz = EDNS_PKTSZ;
while (1)
{
if (!f)
@@ -256,20 +268,23 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
if (!f && option == 'w')
{
fprintf (stderr, usage, CACHESIZ, MAXLEASES);
fprintf (stderr, usage, CACHESIZ, EDNS_PKTSZ, MAXLEASES);
exit(0);
}
if (!f && option == 'v')
{
fprintf(stderr, "dnsmasq version %s\n", VERSION);
fprintf(stderr, "Dnsmasq version %s %s\n\n", VERSION, COPYRIGHT);
fprintf(stderr, "This software comes with ABSOLUTELY NO WARRANTY.\n");
fprintf(stderr, "Dnsmasq is free software, and you are welcome to redistribute it\n");
fprintf(stderr, "under the terms of the GNU General Public License, version 2.\n");
exit(0);
}
for (i=0; optmap[i].c; i++)
if (option == optmap[i].c)
{
flags |= optmap[i].flag;
daemon->options |= optmap[i].flag;
option = 0;
if (f && optarg)
{
@@ -314,13 +329,13 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
goto fileopen;
case 'x':
*runfile = safe_string_alloc(optarg);
daemon->runfile = safe_string_alloc(optarg);
break;
case 'r':
{
char *name = safe_string_alloc(optarg);
struct resolvc *new, *list = *resolv_files;
struct resolvc *new, *list = daemon->resolv_files;
if (list && list->is_default)
{
/* replace default resolv file - possibly with nothing */
@@ -341,7 +356,7 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
new->logged = 0;
list = new;
}
*resolv_files = list;
daemon->resolv_files = list;
break;
}
@@ -355,8 +370,8 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
else
{
struct mx_record *new = safe_malloc(sizeof(struct mx_record));
new->next = *mxnames;
*mxnames = new;
new->next = daemon->mxnames;
daemon->mxnames = new;
new->mxname = safe_string_alloc(optarg);
new->mxtarget = safe_string_alloc(comma); /* may be NULL */
}
@@ -367,59 +382,59 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
if (!canonicalise(optarg))
option = '?';
else
*mxtarget = safe_string_alloc(optarg);
daemon->mxtarget = safe_string_alloc(optarg);
break;
case 'l':
*lease_file = safe_string_alloc(optarg);
daemon->lease_file = safe_string_alloc(optarg);
break;
case 'H':
if (*addn_hosts)
if (daemon->addn_hosts)
option = '?';
else
*addn_hosts = safe_string_alloc(optarg);
daemon->addn_hosts = safe_string_alloc(optarg);
break;
case 's':
if (strcmp (optarg, "#") == 0)
flags |= OPT_RESOLV_DOMAIN;
daemon->options |= OPT_RESOLV_DOMAIN;
else if (!canonicalise(optarg))
option = '?';
else
*domain_suffix = safe_string_alloc(optarg);
daemon->domain_suffix = safe_string_alloc(optarg);
break;
case 'u':
*username = safe_string_alloc(optarg);
daemon->username = safe_string_alloc(optarg);
break;
case 'g':
*groupname = safe_string_alloc(optarg);
daemon->groupname = safe_string_alloc(optarg);
break;
case 'i':
{
struct iname *new = safe_malloc(sizeof(struct iname));
new->next = *if_names;
*if_names = new;
new->next = daemon->if_names;
daemon->if_names = new;
/* new->name may be NULL if someone does
"interface=" to disable all interfaces except loop. */
new->name = safe_string_alloc(optarg);
new->isloop = new->used = 0;
if (strchr(optarg, ':'))
flags |= OPT_NOWILD;
daemon->options |= OPT_NOWILD;
break;
}
case 'I':
{
struct iname *new = safe_malloc(sizeof(struct iname));
new->next = *if_except;
*if_except = new;
new->next = daemon->if_except;
daemon->if_except = new;
new->name = safe_string_alloc(optarg);
if (strchr(optarg, ':'))
flags |= OPT_NOWILD;
daemon->options |= OPT_NOWILD;
break;
}
@@ -429,8 +444,8 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
if ((addr.s_addr = inet_addr(optarg)) != (in_addr_t)-1)
{
struct bogus_addr *baddr = safe_malloc(sizeof(struct bogus_addr));
baddr->next = *bogus_addr;
*bogus_addr = baddr;
baddr->next = daemon->bogus_addr;
daemon->bogus_addr = baddr;
baddr->addr = addr;
}
else
@@ -441,7 +456,7 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
case 'a':
{
struct iname *new = safe_malloc(sizeof(struct iname));
new->next = *if_addrs;
new->next = daemon->if_addrs;
#ifdef HAVE_IPV6
if (inet_pton(AF_INET, optarg, &new->addr.in.sin_addr))
{
@@ -475,7 +490,7 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
}
if (new)
*if_addrs = new;
daemon->if_addrs = new;
break;
}
@@ -628,8 +643,8 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
serv->next->source_addr = serv->source_addr;
serv = serv->next;
}
serv->next = *serv_addrs;
*serv_addrs = newlist;
serv->next = daemon->servers;
daemon->servers = newlist;
}
break;
}
@@ -648,18 +663,27 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
else if (size > 10000)
size = 10000;
*cachesize = size;
daemon->cachesize = size;
}
break;
}
case 'p':
if (!atoi_check(optarg, port))
if (!atoi_check(optarg, &daemon->port))
option = '?';
break;
case 'P':
{
int i;
if (!atoi_check(optarg, &i))
option = '?';
daemon->edns_pktsz = (unsigned short)i;
break;
}
case 'Q':
if (!atoi_check(optarg, query_port))
if (!atoi_check(optarg, &daemon->query_port))
option = '?';
break;
@@ -669,12 +693,12 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
if (!atoi_check(optarg, &ttl))
option = '?';
else
*local_ttl = (unsigned long)ttl;
daemon->local_ttl = (unsigned long)ttl;
break;
}
case 'X':
if (!atoi_check(optarg, dhcp_max))
if (!atoi_check(optarg, &daemon->dhcp_max))
option = '?';
break;
@@ -684,12 +708,14 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
char *cp, *comma, *a[5] = { NULL, NULL, NULL, NULL, NULL };
struct dhcp_context *new = safe_malloc(sizeof(struct dhcp_context));
new->next = *dhcp;
new->lease_time = DEFLEASE;
new->next = daemon->dhcp;
new->lease_time = DEFLEASE;
new->addr_epoch = 0;
new->netmask.s_addr = 0;
new->broadcast.s_addr = 0;
new->router.s_addr = 0;
new->netid.net = NULL;
new->static_only = 0;
for (cp = optarg; *cp; cp++)
if (!(*cp == ' ' || *cp == '.' || (*cp >='0' && *cp <= '9')))
@@ -715,17 +741,27 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
if ((k < 2) || ((new->start.s_addr = inet_addr(a[0])) == (in_addr_t)-1))
option = '?';
else if (strcmp(a[1], "static") == 0)
new->end = new->start;
{
new->end = new->start;
new->static_only = 1;
}
else if ((new->end.s_addr = inet_addr(a[1])) == (in_addr_t)-1)
option = '?';
if (ntohl(new->start.s_addr) > ntohl(new->end.s_addr))
{
struct in_addr tmp = new->start;
new->start = new->end;
new->end = tmp;
}
if (option == '?')
{
free(new);
break;
}
else
*dhcp = new;
daemon->dhcp = new;
if (k >= 3 && strchr(a[2], '.') &&
((new->netmask.s_addr = inet_addr(a[2])) != (in_addr_t)-1))
@@ -764,8 +800,8 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
}
}
if (new->lease_time < *min_leasetime)
*min_leasetime = new->lease_time;
if (new->lease_time < daemon->min_leasetime)
daemon->min_leasetime = new->lease_time;
break;
}
@@ -777,7 +813,7 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
struct dhcp_config *new = safe_malloc(sizeof(struct dhcp_config));
struct in_addr in;
new->next = *dhcp_conf;
new->next = daemon->dhcp_conf;
new->flags = 0;
@@ -929,9 +965,9 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
}
else
{
if ((new->flags & CONFIG_TIME) && new->lease_time < *min_leasetime)
*min_leasetime = new->lease_time;
*dhcp_conf = new;
if ((new->flags & CONFIG_TIME) && new->lease_time < daemon->min_leasetime)
daemon->min_leasetime = new->lease_time;
daemon->dhcp_conf = new;
}
break;
}
@@ -942,7 +978,7 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
char *cp, *comma;
int addrs, digs, is_addr, is_hex, is_dec;
new->next = *dhcp_opts;
new->next = daemon->dhcp_opts;
new->len = 0;
new->is_addr = 0;
new->netid = NULL;
@@ -973,7 +1009,7 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
break;
}
*dhcp_opts = new;
daemon->dhcp_opts = new;
if (!comma)
break;
@@ -1030,7 +1066,7 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
else if (is_dec)
{
/* Given that we don't know the length,
this applaing hack is the best available */
this appaling hack is the best available */
unsigned int val = atoi(comma+1);
if (val < 256)
{
@@ -1088,14 +1124,14 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
if ((comma = strchr(optarg, ',')))
*comma = 0;
*dhcp_file = safe_string_alloc(optarg);
daemon->dhcp_file = safe_string_alloc(optarg);
if (comma)
{
optarg = comma+1;
if ((comma = strchr(optarg, ',')))
*comma = 0;
*dhcp_sname = safe_string_alloc(optarg);
if (comma && (dhcp_next_server->s_addr = inet_addr(comma+1)) == (in_addr_t)-1)
daemon->dhcp_sname = safe_string_alloc(optarg);
if (comma && (daemon->dhcp_next_server.s_addr = inet_addr(comma+1)) == (in_addr_t)-1)
option = '?';
}
break;
@@ -1117,8 +1153,8 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
new->data = safe_malloc(new->len);
memcpy(new->data, comma+1, new->len);
new->is_vendor = (option == 'U');
new->next = *dhcp_vendors;
*dhcp_vendors = new;
new->next = daemon->dhcp_vendors;
daemon->dhcp_vendors = new;
}
break;
}
@@ -1155,8 +1191,8 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
new->in = in;
new->out = out;
new->mask = mask;
new->next = *doctors;
*doctors = new;
new->next = daemon->doctors;
daemon->doctors = new;
break;
}
@@ -1176,66 +1212,66 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
}
/* port might no be known when the address is parsed - fill in here */
if (*serv_addrs)
if (daemon->servers)
{
struct server *tmp;
for (tmp = *serv_addrs; tmp; tmp = tmp->next)
for (tmp = daemon->servers; tmp; tmp = tmp->next)
if (!(tmp->flags & SERV_HAS_SOURCE))
{
if (tmp->source_addr.sa.sa_family == AF_INET)
tmp->source_addr.in.sin_port = htons(*query_port);
tmp->source_addr.in.sin_port = htons(daemon->query_port);
#ifdef HAVE_IPV6
else if (tmp->source_addr.sa.sa_family == AF_INET6)
tmp->source_addr.in6.sin6_port = htons(*query_port);
tmp->source_addr.in6.sin6_port = htons(daemon->query_port);
#endif
}
}
if (*if_addrs)
if (daemon->if_addrs)
{
struct iname *tmp;
for(tmp = *if_addrs; tmp; tmp = tmp->next)
for(tmp = daemon->if_addrs; tmp; tmp = tmp->next)
if (tmp->addr.sa.sa_family == AF_INET)
tmp->addr.in.sin_port = htons(*port);
tmp->addr.in.sin_port = htons(daemon->port);
#ifdef HAVE_IPV6
else if (tmp->addr.sa.sa_family == AF_INET6)
tmp->addr.in6.sin6_port = htons(*port);
tmp->addr.in6.sin6_port = htons(daemon->port);
#endif /* IPv6 */
}
/* only one of these need be specified: the other defaults to the
host-name */
if ((flags & OPT_LOCALMX) || *mxnames || *mxtarget)
if ((daemon->options & OPT_LOCALMX) || daemon->mxnames || daemon->mxtarget)
{
if (gethostname(buff, MAXDNAME) == -1)
die("cannot get host-name: %s", NULL);
if (!*mxnames)
if (!daemon->mxnames)
{
*mxnames = safe_malloc(sizeof(struct mx_record));
(*mxnames)->next = NULL;
(*mxnames)->mxtarget = NULL;
(*mxnames)->mxname = safe_string_alloc(buff);
}
daemon->mxnames = safe_malloc(sizeof(struct mx_record));
daemon->mxnames->next = NULL;
daemon->mxnames->mxtarget = NULL;
daemon->mxnames->mxname = safe_string_alloc(buff);
}
if (!*mxtarget)
*mxtarget = safe_string_alloc(buff);
if (!daemon->mxtarget)
daemon->mxtarget = safe_string_alloc(buff);
}
if (flags & OPT_NO_RESOLV)
*resolv_files = 0;
else if (*resolv_files && (*resolv_files)->next && (flags & OPT_NO_POLL))
if (daemon->options & OPT_NO_RESOLV)
daemon->resolv_files = 0;
else if (daemon->resolv_files && (daemon->resolv_files)->next && (daemon->options & OPT_NO_POLL))
die("only one resolv.conf file allowed in no-poll mode.", NULL);
if (flags & OPT_RESOLV_DOMAIN)
if (daemon->options & OPT_RESOLV_DOMAIN)
{
char *line;
if (!*resolv_files || (*resolv_files)->next)
if (!daemon->resolv_files || (daemon->resolv_files)->next)
die("must have exactly one resolv.conf to read domain from.", NULL);
if (!(f = fopen((*resolv_files)->name, "r")))
die("failed to read %s: %m", (*resolv_files)->name);
if (!(f = fopen((daemon->resolv_files)->name, "r")))
die("failed to read %s: %m", (daemon->resolv_files)->name);
while ((line = fgets(buff, MAXDNAME, f)))
{
@@ -1246,17 +1282,17 @@ unsigned int read_opts (int argc, char **argv, char *buff, struct resolvc **reso
if ((token = strtok(NULL, " \t\n\r")) &&
canonicalise(token) &&
(*domain_suffix = safe_string_alloc(token)))
(daemon->domain_suffix = safe_string_alloc(token)))
break;
}
fclose(f);
if (!*domain_suffix)
die("no search directive found in %s", (*resolv_files)->name);
if (!daemon->domain_suffix)
die("no search directive found in %s", (daemon->resolv_files)->name);
}
return flags;
return daemon;
}

View File

@@ -244,52 +244,60 @@ static int in_arpa_name_2_addr(char *namein, struct all_addr *addrp)
return 0;
}
static unsigned char *skip_name(unsigned char *ansp, HEADER *header, unsigned int plen)
{
while(1)
{
unsigned int label_type = (*ansp) & 0xc0;
if ((unsigned int)(ansp - (unsigned char *)header) >= plen)
return NULL;
if (label_type == 0xc0)
{
/* pointer for compression. */
ansp += 2;
break;
}
else if (label_type == 0x80)
return NULL; /* reserved */
else if (label_type == 0x40)
{
/* Extended label type */
unsigned int count;
if (((*ansp++) & 0x3f) != 1)
return NULL; /* we only understand bitstrings */
count = *(ansp++); /* Bits in bitstring */
if (count == 0) /* count == 0 means 256 bits */
ansp += 32;
else
ansp += ((count-1)>>3)+1;
}
else
{ /* label type == 0 Bottom six bits is length */
unsigned int len = (*ansp++) & 0x3f;
if (len == 0)
break; /* zero length label marks the end. */
ansp += len;
}
}
return ansp;
}
static unsigned char *skip_questions(HEADER *header, unsigned int plen)
{
int q, qdcount = ntohs(header->qdcount);
unsigned char *ansp = (unsigned char *)(header+1);
for (q=0; q<qdcount; q++)
for (q = 0; q<qdcount; q++)
{
while (1)
{
unsigned int label_type = (*ansp) & 0xc0;
if ((unsigned int)(ansp - (unsigned char *)header) >= plen)
return NULL;
if (label_type == 0xc0)
{
/* pointer for compression. */
ansp += 2;
break;
}
else if (label_type == 0x80)
return NULL; /* reserved */
else if (label_type == 0x40)
{
/* Extended label type */
unsigned int count;
if (((*ansp++) & 0x3f) != 1)
return NULL; /* we only understand bitstrings */
count = *(ansp++); /* Bits in bitstring */
if (count == 0) /* count == 0 means 256 bits */
ansp += 32;
else
ansp += ((count-1)>>3)+1;
}
else
{ /* label type == 0 Bottom six bits is length */
unsigned int len = (*ansp++) & 0x3f;
if (len == 0)
break; /* zero length label marks the end. */
ansp += len;
}
}
if (!(ansp = skip_name(ansp, header, plen)))
return NULL;
ansp += 4; /* class and type */
}
if ((unsigned int)(ansp - (unsigned char *)header) > plen)
@@ -298,6 +306,49 @@ static unsigned char *skip_questions(HEADER *header, unsigned int plen)
return ansp;
}
unsigned char *find_pseudoheader(HEADER *header, unsigned int plen)
{
/* See if packet has an RFC2671 pseudoheader, and if so return a pointer to it. */
int i, arcount = ntohs(header->arcount);
unsigned char *ansp;
unsigned short rdlen, type;
if (arcount == 0 || !(ansp = skip_questions(header, plen)))
return NULL;
for (i = 0; i < (ntohs(header->ancount) + ntohs(header->nscount)); i++)
{
if (!(ansp = skip_name(ansp, header, plen)))
return NULL;
ansp += 8; /* type, class, TTL */
GETSHORT(rdlen, ansp);
if ((unsigned int)(ansp + rdlen - (unsigned char *)header) > plen)
return NULL;
ansp += rdlen;
}
for (i = 0; i < arcount; i++)
{
unsigned char *save;
if (!(ansp = skip_name(ansp, header, plen)))
return NULL;
GETSHORT(type, ansp);
save = ansp;
ansp += 6; /* class, TTL */
GETSHORT(rdlen, ansp);
if ((unsigned int)(ansp + rdlen - (unsigned char *)header) > plen)
return NULL;
if (type == T_OPT)
return save;
ansp += rdlen;
}
return NULL;
}
/* is addr in the non-globally-routed IP space? */
static int private_net(struct all_addr *addrp)
{
@@ -440,13 +491,16 @@ void extract_neg_addrs(HEADER *header, unsigned int qlen, char *name, time_t now
cache_end_insert();
}
static void dns_doctor(struct doctor *doctor, struct in_addr *addr)
static void dns_doctor(HEADER *header, struct doctor *doctor, struct in_addr *addr)
{
for (; doctor; doctor = doctor->next)
if (is_same_net(doctor->in, *addr, doctor->mask))
{
addr->s_addr &= ~doctor->mask.s_addr;
addr->s_addr |= (doctor->out.s_addr & doctor->mask.s_addr);
/* Since we munged the data, the server it came from is no longer authoritative */
header->nscount = htons(0);
header->arcount = htons(0);
break;
}
}
@@ -490,7 +544,7 @@ void extract_addresses(HEADER *header, unsigned int qlen, char *name,
if (qtype == T_A) /* A record. */
{
dns_doctor(doctors, (struct in_addr *)p);
dns_doctor(header, doctors, (struct in_addr *)p);
cache_insert(name, (struct all_addr *)p, now,
ttl, F_IPV4 | F_FORWARD);
}
@@ -562,7 +616,7 @@ void extract_addresses(HEADER *header, unsigned int qlen, char *name,
if (qtype == T_A) /* A record. */
{
dns_doctor(doctors, (struct in_addr *)p);
dns_doctor(header, doctors, (struct in_addr *)p);
cache_insert(name, (struct all_addr *)p, now,
cttl, F_IPV4 | F_FORWARD);
}
@@ -596,11 +650,14 @@ void extract_addresses(HEADER *header, unsigned int qlen, char *name,
/* If the packet holds exactly one query
return 1 and leave the name from the query in name. */
unsigned short extract_request(HEADER *header,unsigned int qlen, char *name)
unsigned short extract_request(HEADER *header,unsigned int qlen, char *name, unsigned short *typep)
{
unsigned char *p = (unsigned char *)(header+1);
int qtype, qclass;
if (typep)
*typep = 0;
if (ntohs(header->qdcount) != 1 || header->opcode != QUERY)
return 0; /* must be exactly one query. */
@@ -612,6 +669,9 @@ unsigned short extract_request(HEADER *header,unsigned int qlen, char *name)
if (qclass == C_IN)
{
if (typep)
*typep = qtype;
if (qtype == T_A)
return F_IPV4;
if (qtype == T_AAAA)
@@ -635,7 +695,7 @@ int setup_reply(HEADER *header, unsigned int qlen,
header->tc = 0; /* not truncated */
header->nscount = htons(0);
header->arcount = htons(0);
header->ancount = htons(0); /* no answers unless changed below*/
header->ancount = htons(0); /* no answers unless changed below */
if (flags == F_NEG)
header->rcode = SERVFAIL; /* couldn't get memory */
else if (flags == F_NOERR || flags == F_QUERY)
@@ -728,29 +788,59 @@ int check_for_bogus_wildcard(HEADER *header, unsigned int qlen, char *name,
}
/* return zero if we can't answer from cache, or packet size if we can */
int answer_request(HEADER *header, char *limit, unsigned int qlen, struct mx_record *mxnames,
char *mxtarget, unsigned int options, time_t now,
unsigned long local_ttl, char *name)
int answer_request(HEADER *header, char *limit, unsigned int qlen, struct daemon *daemon, time_t now)
{
unsigned char *p, *ansp;
char *name = daemon->namebuff;
unsigned char *p, *ansp, *pheader;
int qtype, qclass, is_arpa;
struct all_addr addr;
unsigned int nameoffset;
int q, qdcount = ntohs(header->qdcount);
int ans, anscount = 0;
unsigned short flag;
int qdcount = ntohs(header->qdcount);
int q, ans, anscount;
int dryrun = 0, sec_reqd = 0;
struct crec *crecp;
int nxdomain = 0, auth = 1;
int nxdomain, auth;
if (!qdcount || header->opcode != QUERY )
return 0;
/* If there is an RFC2671 pseudoheader then it will be overwritten by
partial replies, so we have to do a dry run to see if we can answer
the query. We check to see if the do bit is set, if so we always
forward rather than answering from the cache, which doesn't include
security information. */
if ((pheader = find_pseudoheader(header, qlen)))
{
unsigned short udpsz, ext_rcode, flags;
unsigned char *psave = pheader;
GETSHORT(udpsz, pheader);
GETSHORT(ext_rcode, pheader);
GETSHORT(flags, pheader);
sec_reqd = flags & 0x8000; /* do bit */
/* If our client is advertising a larger UDP packet size
than we allow, trim it so that we don't get an overlarge
response from upstream */
if (udpsz > daemon->edns_pktsz)
PUTSHORT(daemon->edns_pktsz, psave);
dryrun = 1;
}
rerun:
/* determine end of question section (we put answers there) */
if (!(ansp = skip_questions(header, qlen)))
return 0; /* bad packet */
/* now process each question, answers go in RRs after the question */
p = (unsigned char *)(header+1);
nxdomain = 0, auth = 1, anscount = 0;
for (q=0; q<qdcount; q++)
{
/* save pointer to name for copying into answers */
@@ -769,16 +859,19 @@ int answer_request(HEADER *header, char *limit, unsigned int qlen, struct mx_rec
ans = 0; /* have we answered this question */
if (qclass == C_CHAOS)
if (qclass == C_CHAOS && qtype == T_TXT)
/* special query to get version. */
{
if (qtype == T_TXT)
ans = 1;
if (!dryrun)
{
int len;
if (hostname_isequal(name, "version.bind"))
sprintf(name, "dnsmasq-%s", VERSION);
else if (hostname_isequal(name, "authors.bind"))
sprintf(name, "Simon Kelley");
else if (hostname_isequal(name, "copyright.bind"))
sprintf(name, COPYRIGHT);
else
*name = 0;
len = strlen(name);
@@ -790,235 +883,195 @@ int answer_request(HEADER *header, char *limit, unsigned int qlen, struct mx_rec
*ansp++ = len;
memcpy(ansp, name, len);
ansp += len;
ans = 1;
anscount++;
if (((unsigned char *)limit - ansp) < 0)
return 0;
}
else
return 0;
}
else if (qclass != C_IN)
return 0; /* we can't answer non-inet queries */
else
}
else if (qclass == C_IN)
{
if ((options & OPT_FILTER) && (qtype == T_SOA || qtype == T_SRV))
ans = 1;
if (qtype == T_PTR || qtype == T_ANY)
if ((daemon->options & OPT_FILTER) &&
(qtype == T_SOA || qtype == T_SRV || (qtype == T_ANY && strchr(name, '_'))))
{
crecp = NULL;
while ((crecp = cache_find_by_addr(crecp, &addr, now, is_arpa)))
{
unsigned long ttl;
/* Return 0 ttl for DHCP entries, which might change
before the lease expires. */
if (crecp->flags & (F_IMMORTAL | F_DHCP))
ttl = local_ttl;
else
ttl = crecp->ttd - now;
ans = 1;
log_query(F_CONFIG | F_NEG, name, &addr, 0);
}
else
{
if (qtype == T_PTR || qtype == T_ANY)
{
if (!(crecp = cache_find_by_addr(NULL, &addr, now, is_arpa)))
{
if (is_arpa == F_IPV4 && (daemon->options & OPT_BOGUSPRIV) && private_net(&addr))
{
/* if not in cache, enabled and private IPV4 address, return NXDOMAIN */
ans = 1;
if (!dryrun)
{
log_query(F_CONFIG | F_REVERSE | F_IPV4 | F_NEG | F_NXDOMAIN, name, &addr, 0);
nxdomain = 1;
}
}
}
else do
{
/* don't answer wildcard queries with data not from /etc/hosts or dhcp leases */
if (qtype == T_ANY && !(crecp->flags & (F_HOSTS | F_DHCP)))
continue;
if (crecp->flags & F_NEG)
{
ans = 1;
if (!dryrun)
{
log_query(crecp->flags & ~F_FORWARD, name, &addr, 0);
auth = 0;
if (crecp->flags & F_NXDOMAIN)
nxdomain = 1;
}
}
else if ((crecp->flags & (F_HOSTS | F_DHCP)) || !sec_reqd)
{
ans = 1;
if (!dryrun)
{
unsigned long ttl;
/* Return 0 ttl for DHCP entries, which might change
before the lease expires. */
if (crecp->flags & (F_IMMORTAL | F_DHCP))
ttl = daemon->local_ttl;
else
ttl = crecp->ttd - now;
if (!(crecp->flags & (F_HOSTS | F_DHCP)))
auth = 0;
ansp = add_text_record(nameoffset, ansp, ttl, 0, T_PTR,
cache_get_name(crecp));
log_query(crecp->flags & ~F_FORWARD, cache_get_name(crecp), &addr, 0);
anscount++;
/* if last answer exceeded packet size, give up */
if (((unsigned char *)limit - ansp) < 0)
return 0;
}
}
} while ((crecp = cache_find_by_addr(crecp, &addr, now, is_arpa)));
}
for (flag = F_IPV4; flag; flag = (flag == F_IPV4) ? F_IPV6 : 0)
{
unsigned short type = T_A;
int addrsz = INADDRSZ;
/* don't answer wildcard queries with data not from /etc/hosts
or dhcp leases */
if (qtype == T_ANY && !(crecp->flags & (F_HOSTS | F_DHCP)))
return 0;
ans = 1;
if (crecp->flags & F_NEG)
if (flag == F_IPV6)
{
log_query(crecp->flags & ~F_FORWARD, name, &addr);
auth = 0;
if (crecp->flags & F_NXDOMAIN)
nxdomain = 1;
}
else
{
if (!(crecp->flags & (F_HOSTS | F_DHCP)))
auth = 0;
ansp = add_text_record(nameoffset, ansp, ttl, 0, T_PTR,
cache_get_name(crecp));
log_query(crecp->flags & ~F_FORWARD, cache_get_name(crecp), &addr);
anscount++;
/* if last answer exceeded packet size, give up */
if (((unsigned char *)limit - ansp) < 0)
return 0;
}
}
/* if not in cache, enabled and private IPV4 address, fake up answer */
if (ans == 0 && is_arpa == F_IPV4 &&
(options & OPT_BOGUSPRIV) &&
private_net(&addr))
{
struct in_addr addr4 = *((struct in_addr *)&addr);
ansp = add_text_record(nameoffset, ansp, local_ttl, 0, T_PTR, inet_ntoa(addr4));
log_query(F_CONFIG | F_REVERSE | F_IPV4, inet_ntoa(addr4), &addr);
anscount++;
ans = 1;
if (((unsigned char *)limit - ansp) < 0)
return 0;
}
}
if (qtype == T_A || qtype == T_ANY)
{
/* T_ANY queries for hostnames with underscores are spam
from win2k - don't forward them. */
if ((options & OPT_FILTER) &&
qtype == T_ANY &&
(strchr(name, '_') != NULL))
ans = 1;
else
{
crecp = NULL;
while ((crecp = cache_find_by_name(crecp, name, now, F_IPV4)))
{
unsigned long ttl;
if (crecp->flags & (F_IMMORTAL | F_DHCP))
ttl = local_ttl;
else
ttl = crecp->ttd - now;
/* don't answer wildcard queries with data not from /etc/hosts
or DHCP leases */
if (qtype == T_ANY && !(crecp->flags & (F_HOSTS | F_DHCP)))
return 0;
/* If we have negative cache entry, it's OK
to return no answer. */
ans = 1;
if (crecp->flags & F_NEG)
{
log_query(crecp->flags, name, NULL);
auth = 0;
if (crecp->flags & F_NXDOMAIN)
nxdomain = 1;
}
else
{
if (!(crecp->flags & (F_HOSTS | F_DHCP)))
auth = 0;
log_query(crecp->flags & ~F_REVERSE, name, &crecp->addr);
/* copy question as first part of answer (use compression) */
PUTSHORT(nameoffset | 0xc000, ansp);
PUTSHORT(T_A, ansp);
PUTSHORT(C_IN, ansp);
PUTLONG(ttl, ansp); /* TTL */
PUTSHORT(INADDRSZ, ansp);
memcpy(ansp, &crecp->addr, INADDRSZ);
ansp += INADDRSZ;
anscount++;
if (((unsigned char *)limit - ansp) < 0)
return 0;
}
}
}
}
#ifdef HAVE_IPV6
if (qtype == T_AAAA || qtype == T_ANY)
{
/* T_ANY queries for hostnames with underscores are spam
from win2k - don't forward them. */
if ((options & OPT_FILTER) &&
qtype == T_ANY
&& (strchr(name, '_') != NULL))
ans = 1;
else
{
type = T_AAAA;
addrsz = IN6ADDRSZ;
#else
break;
#endif
}
if (qtype != type && qtype != T_ANY)
continue;
crecp = NULL;
while ((crecp = cache_find_by_name(crecp, name, now, F_IPV6)))
while ((crecp = cache_find_by_name(crecp, name, now, flag)))
{
unsigned long ttl;
if (crecp->flags & (F_IMMORTAL | F_DHCP))
ttl = local_ttl;
else
ttl = crecp->ttd - now;
/* don't answer wildcard queries with data not from /etc/hosts
or DHCP leases */
if (qtype == T_ANY && !(crecp->flags & (F_HOSTS | F_DHCP)))
return 0;
/* If we have negative cache entry, it's OK
to return no answer. */
ans = 1;
continue;
if (crecp->flags & F_NEG)
{
log_query(crecp->flags, name, NULL);
auth = 0;
if (crecp->flags & F_NXDOMAIN)
nxdomain = 1;
ans = 1;
if (!dryrun)
{
log_query(crecp->flags, name, NULL, 0);
auth = 0;
if (crecp->flags & F_NXDOMAIN)
nxdomain = 1;
}
}
else
else if ((crecp->flags & (F_HOSTS | F_DHCP)) || !sec_reqd)
{
if (!(crecp->flags & (F_HOSTS | F_DHCP)))
auth = 0;
log_query(crecp->flags & ~F_REVERSE, name, &crecp->addr);
/* copy question as first part of answer (use compression) */
PUTSHORT(nameoffset | 0xc000, ansp);
PUTSHORT(T_AAAA, ansp);
PUTSHORT(C_IN, ansp);
PUTLONG(ttl, ansp); /* TTL */
PUTSHORT(IN6ADDRSZ, ansp);
memcpy(ansp, &crecp->addr, IN6ADDRSZ);
ansp += IN6ADDRSZ;
anscount++;
if (((unsigned char *)limit - ansp) < 0)
return 0;
ans = 1;
if (!dryrun)
{
unsigned long ttl;
if (crecp->flags & (F_IMMORTAL | F_DHCP))
ttl = daemon->local_ttl;
else
ttl = crecp->ttd - now;
if (!(crecp->flags & (F_HOSTS | F_DHCP)))
auth = 0;
log_query(crecp->flags & ~F_REVERSE, name, &crecp->addr, 0);
/* copy question as first part of answer (use compression) */
PUTSHORT(nameoffset | 0xc000, ansp);
PUTSHORT(type, ansp);
PUTSHORT(C_IN, ansp);
PUTLONG(ttl, ansp); /* TTL */
PUTSHORT(addrsz, ansp);
memcpy(ansp, &crecp->addr, addrsz);
ansp += addrsz;
anscount++;
if (((unsigned char *)limit - ansp) < 0)
return 0;
}
}
}
}
}
#endif
if (qtype == T_MX || qtype == T_ANY)
{
struct mx_record *mx;
for (mx = mxnames; mx; mx = mx->next)
if (hostname_isequal(name, mx->mxname))
break;
if (mx)
{
ansp = add_text_record(nameoffset, ansp, local_ttl, 1, T_MX,
mx->mxtarget ? mx->mxtarget : mxtarget);
anscount++;
ans = 1;
}
else if ((options & (OPT_SELFMX | OPT_LOCALMX)) &&
cache_find_by_name(NULL, name, now, F_HOSTS | F_DHCP))
{
ansp = add_text_record(nameoffset, ansp, local_ttl, 1, T_MX,
(options & OPT_SELFMX) ? name : mxtarget);
anscount++;
ans = 1;
}
if (((unsigned char *)limit - ansp) < 0)
return 0;
}
if (qtype == T_MAILB)
ans = 1, nxdomain = 1;
if (qtype == T_MX || qtype == T_ANY)
{
struct mx_record *mx;
for (mx = daemon->mxnames; mx; mx = mx->next)
if (hostname_isequal(name, mx->mxname))
break;
if (mx)
{
ans = 1;
if (!dryrun)
{
ansp = add_text_record(nameoffset, ansp, daemon->local_ttl, 1, T_MX,
mx->mxtarget ? mx->mxtarget : daemon->mxtarget);
anscount++;
}
}
else if ((daemon->options & (OPT_SELFMX | OPT_LOCALMX)) &&
cache_find_by_name(NULL, name, now, F_HOSTS | F_DHCP))
{
ans = 1;
if (!dryrun)
{
ansp = add_text_record(nameoffset, ansp, daemon->local_ttl, 1, T_MX,
(daemon->options & OPT_SELFMX) ? name : daemon->mxtarget);
anscount++;
}
}
}
if (qtype == T_MAILB)
ans = 1, nxdomain = 1;
}
}
if (!ans)
if (!ans || ((unsigned char *)limit - ansp) < 0)
return 0; /* failed to answer a question */
}
if (dryrun)
{
dryrun = 0;
goto rerun;
}
/* done all questions, set up header and return length of result */

View File

@@ -42,6 +42,7 @@
#define OPTION_VENDOR_ID 60
#define OPTION_CLIENT_ID 61
#define OPTION_USER_CLASS 77
#define OPTION_SUBNET_SELECT 118
#define OPTION_END 255
#define DHCPDISCOVER 1
@@ -66,77 +67,151 @@ static unsigned char *option_find(struct dhcp_packet *mess, int size, int opt_ty
static unsigned char *do_req_options(struct dhcp_context *context,
unsigned char *p, unsigned char *end,
unsigned char *req_options,
struct dhcp_opt *config_opts,
char *domainname, char *hostname,
struct in_addr router,
struct daemon *daemon,
char *hostname,
struct in_addr iface_addr,
int iface_mtu, struct dhcp_netid *netid);
struct dhcp_netid *netid,
struct in_addr subnet_addr);
static int have_config(struct dhcp_config *config, unsigned int mask)
{
return config && (config->flags & mask);
}
int dhcp_reply(struct dhcp_context *context,
struct in_addr iface_addr,
char *iface_name,
int iface_mtu,
struct udp_dhcp_packet *rawpacket,
unsigned int sz, time_t now, char *namebuff,
struct dhcp_opt *dhcp_opts, struct dhcp_config *dhcp_configs,
struct dhcp_vendor *vendors,
char *domain_suffix, char *dhcp_file, char *dhcp_sname,
struct in_addr dhcp_next_server, struct in_addr router)
int dhcp_reply(struct daemon *daemon, struct in_addr iface_addr, char *iface_name, unsigned int sz, time_t now)
{
struct dhcp_context *context;
unsigned char *opt, *clid;
struct dhcp_lease *lease;
struct dhcp_lease *lease, *ltmp;
struct dhcp_vendor *vendor;
int clid_len;
struct dhcp_packet *mess = &rawpacket->data;
unsigned char *p = mess->options;
/* default max reply packet length, max be overridden */
unsigned char *end = (unsigned char *)(rawpacket + 1);
struct dhcp_packet *mess = &daemon->dhcp_packet->data;
unsigned char *p = mess->options + sizeof(u32); /* skip cookie */
unsigned char *end = (unsigned char *)(daemon->dhcp_packet + 1);
char *hostname = NULL;
char *req_options = NULL;
char *message = NULL;
unsigned int renewal_time, expires_time, def_time;
struct dhcp_config *config;
struct dhcp_netid *netid = NULL;
struct in_addr addr;
struct in_addr addr, subnet_addr;
unsigned short fuzz = 0;
unsigned int mess_type = 0;
if (mess->op != BOOTREQUEST ||
mess->hlen != ETHER_ADDR_LEN ||
mess->cookie != htonl(DHCP_COOKIE))
subnet_addr.s_addr = 0;
if (mess->op != BOOTREQUEST)
return 0;
/* Token ring is supported when we have packet sockets
to make the HW headers for us. We don't have the code to build
token ring headers when using BPF. We rely on the fact that
token ring hwaddrs are the same size as ethernet hwaddrs. */
#ifdef HAVE_BPF
if (mess->htype != ARPHRD_ETHER)
return 0;
if (mess->htype != ARPHRD_ETHER)
#else
if (mess->htype != ARPHRD_ETHER &&
mess->htype != ARPHRD_IEEE802)
return 0;
if (mess->htype != ARPHRD_ETHER && mess->htype != ARPHRD_IEEE802)
#endif
mess->op = BOOTREPLY;
if ((opt = option_find(mess, sz, OPTION_MAXMESSAGE)))
{
int maxsize = (int)option_uint(opt, 2);
if (maxsize > DNSMASQ_PACKETSZ)
maxsize = DNSMASQ_PACKETSZ;
if (maxsize > iface_mtu)
maxsize = iface_mtu;
syslog(LOG_WARNING, "DHCP request for unsupported hardware type (%d) recieved on %s",
mess->htype, iface_name);
return 0;
}
if (mess->hlen != ETHER_ADDR_LEN)
return 0;
/* check for DHCP rather than BOOTP */
if ((opt = option_find(mess, sz, OPTION_MESSAGE_TYPE)))
{
mess_type = option_uint(opt, 1);
end = ((unsigned char *)rawpacket) + maxsize;
/* only insist on a cookie for DHCP. */
if (*((u32 *)&mess->options) != htonl(DHCP_COOKIE))
return 0;
/* Some buggy clients set ciaddr when they shouldn't, so clear that here since
it can affect the context-determination code. */
if ((option_find(mess, sz, OPTION_REQUESTED_IP) || mess_type == DHCPDISCOVER))
mess->ciaddr.s_addr = 0;
/* Check for RFC3011 subnet selector */
if ((opt = option_find(mess, sz, OPTION_SUBNET_SELECT)))
subnet_addr = option_addr(opt);
}
/* Determine network for this packet. If the machine has an address already, and we don't have
have a giaddr or explicit subnet selector, use the ciaddr. This is necessary because a
machine which got a lease via a relay won't use the relay to renew. */
addr =
subnet_addr.s_addr ? subnet_addr :
(mess->giaddr.s_addr ? mess->giaddr :
(mess->ciaddr.s_addr ? mess->ciaddr : iface_addr));
for (context = daemon->dhcp; context; context = context->next)
if (context->netmask.s_addr &&
is_same_net(addr, context->start, context->netmask) &&
is_same_net(addr, context->end, context->netmask))
break;
if (!context)
{
syslog(LOG_WARNING, "no address range available for DHCP request %s %s",
subnet_addr.s_addr ? "with subnet selector" : "via",
subnet_addr.s_addr ? inet_ntoa(subnet_addr) : (mess->giaddr.s_addr ? inet_ntoa(mess->giaddr) : iface_name));
return 0;
}
mess->op = BOOTREPLY;
/* start to build netid chain */
if (context->netid.net)
{
context->netid.next = netid;
netid = &context->netid;
}
if (mess_type == 0)
{
/* BOOTP request */
config = find_config(daemon->dhcp_conf, context, NULL, 0, mess->chaddr, NULL);
if (have_config(config, CONFIG_ADDR) &&
!have_config(config, CONFIG_DISABLE) &&
!lease_find_by_addr(config->addr))
{
struct dhcp_netid id;
char save = mess->file[128];
end = mess->options + 64; /* BOOTP vend area is only 64 bytes */
mess->yiaddr = config->addr;
mess->siaddr = daemon->dhcp_next_server.s_addr ? daemon->dhcp_next_server : iface_addr;
if (have_config(config, CONFIG_NAME))
hostname = config->hostname;
if (have_config(config, CONFIG_NETID))
{
config->netid.next = netid;
netid = &config->netid;
}
/* Match incoming filename field as a netid. */
if (mess->file[0])
{
mess->file[128] = 0; /* ensure zero term. */
id.net = mess->file;
id.next = netid;
netid = &id;
}
p = do_req_options(context, p, end, NULL, daemon,
hostname, iface_addr, netid, subnet_addr);
/* must do this after do_req_options since it overwrites filename field. */
bootp_option_put(mess, daemon->dhcp_file, daemon->dhcp_sname);
p = option_end(p, end, mess);
log_packet(NULL, &config->addr, mess->chaddr, iface_name, NULL);
mess->file[128] = save;
return p - (unsigned char *)mess;
}
return 0;
}
/* If there is no client identifier option, use the hardware address */
if ((opt = option_find(mess, sz, OPTION_CLIENT_ID)))
{
@@ -149,15 +224,14 @@ int dhcp_reply(struct dhcp_context *context,
clid_len = 0;
}
if ((config = find_config(dhcp_configs, context, clid, clid_len, mess->chaddr, NULL)) &&
have_config(config, CONFIG_NAME))
config = find_config(daemon->dhcp_conf, context, clid, clid_len, mess->chaddr, NULL);
if (have_config(config, CONFIG_NAME))
hostname = config->hostname;
else if ((opt = option_find(mess, sz, OPTION_HOSTNAME)))
{
int len = option_len(opt);
/* namebuff is 1K long, use half for requested options and half for hostname */
/* len < 256 by definition */
hostname = namebuff + 500;
hostname = daemon->dhcp_buff;
memcpy(hostname, option_ptr(opt), len);
/* May not be zero terminated */
hostname[len] = 0;
@@ -169,7 +243,7 @@ int dhcp_reply(struct dhcp_context *context,
char *dot = strchr(hostname, '.');
if (dot)
{
if (!domain_suffix || !hostname_isequal(dot+1, domain_suffix))
if (!daemon->domain_suffix || !hostname_isequal(dot+1, daemon->domain_suffix))
{
syslog(LOG_WARNING, "Ignoring DHCP host name %s because it has an illegal domain part", hostname);
hostname = NULL;
@@ -181,19 +255,21 @@ int dhcp_reply(struct dhcp_context *context,
hostname = NULL; /* nothing left */
}
}
/* search again now we have a hostname */
config = find_config(dhcp_configs, context, clid, clid_len, mess->chaddr, hostname);
/* Search again now we have a hostname.
Only accept configs without CLID and HWADDR here, (they won't match)
to avoid impersonation by name. */
if (!config)
{
struct dhcp_config *new = find_config(daemon->dhcp_conf, context, NULL, 0, mess->chaddr, hostname);
if (!have_config(new, CONFIG_CLID) && !have_config(new, CONFIG_HWADDR))
config = new;
}
}
}
def_time = have_config(config, CONFIG_TIME) ? config->lease_time : context->lease_time;
if (context->netid.net)
{
context->netid.next = netid;
netid = &context->netid;
}
if (have_config(config, CONFIG_NETID))
{
config->netid.next = netid;
@@ -202,11 +278,11 @@ int dhcp_reply(struct dhcp_context *context,
/* Theres a chance that carefully chosen data could match the same
vendor/user option twice and make a loop in the netid chain. */
for (vendor = vendors; vendor; vendor = vendor->next)
for (vendor = daemon->dhcp_vendors; vendor; vendor = vendor->next)
vendor->used = 0;
if ((opt = option_find(mess, sz, OPTION_VENDOR_ID)))
for (vendor = vendors; vendor; vendor = vendor->next)
for (vendor = daemon->dhcp_vendors; vendor; vendor = vendor->next)
if (vendor->is_vendor && !vendor->used)
{
int i;
@@ -225,7 +301,7 @@ int dhcp_reply(struct dhcp_context *context,
unsigned char *ucp = option_ptr(opt);
int j;
for (j = 0; j < option_len(opt); j += ucp[j] + 1)
for (vendor = vendors; vendor; vendor = vendor->next)
for (vendor = daemon->dhcp_vendors; vendor; vendor = vendor->next)
if (!vendor->is_vendor && !vendor->used)
{
int i;
@@ -272,15 +348,12 @@ int dhcp_reply(struct dhcp_context *context,
if ((opt = option_find(mess, sz, OPTION_REQUESTED_OPTIONS)))
{
int len = option_len(opt);
req_options = namebuff;
req_options = daemon->dhcp_buff2;
memcpy(req_options, option_ptr(opt), len);
req_options[len] = OPTION_END;
}
if (!(opt = option_find(mess, sz, OPTION_MESSAGE_TYPE)))
return 0;
switch (option_uint(opt, 1))
switch (mess_type)
{
case DHCPDECLINE:
if (!(opt = option_find(mess, sz, OPTION_SERVER_IDENTIFIER)) ||
@@ -290,7 +363,7 @@ int dhcp_reply(struct dhcp_context *context,
/* sanitise any message. Paranoid? Moi? */
if ((opt = option_find(mess, sz, OPTION_MESSAGE)))
{
char *p = option_ptr(opt), *q = namebuff;
char *p = option_ptr(opt), *q = daemon->dhcp_buff;
int i;
for (i = option_len(opt); i > 0; i--)
@@ -300,7 +373,7 @@ int dhcp_reply(struct dhcp_context *context,
*q++ = c;
}
*q++ = 0; /* add terminator */
message = namebuff;
message = daemon->dhcp_buff;
}
if (!(opt = option_find(mess, sz, OPTION_REQUESTED_IP)))
@@ -317,6 +390,9 @@ int dhcp_reply(struct dhcp_context *context,
syslog(LOG_WARNING, "disabling DHCP static address %s", inet_ntoa(config->addr));
config->flags &= ~CONFIG_ADDR ;
}
else
/* make sure this host gets a different address next time. */
context->addr_epoch++;
return 0;
@@ -335,27 +411,25 @@ int dhcp_reply(struct dhcp_context *context,
case DHCPDISCOVER:
if ((opt = option_find(mess, sz, OPTION_REQUESTED_IP)))
addr = option_addr(opt);
if (have_config(config, CONFIG_DISABLE))
message = "ignored";
else if (have_config(config, CONFIG_ADDR) && !lease_find_by_addr(config->addr))
else if (have_config(config, CONFIG_ADDR) &&
(!(ltmp = lease_find_by_addr(config->addr)) || ltmp == lease))
mess->yiaddr = config->addr;
else if (lease && is_same_net(lease->addr, context->start, context->netmask))
else if (lease && address_available(context, lease->addr))
mess->yiaddr = lease->addr;
else if (opt && address_available(context, addr))
else if (opt && address_available(context, addr) && !lease_find_by_addr(addr) &&
!config_find_by_address(daemon->dhcp_conf, addr))
mess->yiaddr = addr;
else if (!address_allocate(context, dhcp_configs, &mess->yiaddr, mess->chaddr))
message = "no address available";
else if (!address_allocate(context, daemon, &mess->yiaddr, mess->chaddr))
message = "no address available";
log_packet("DISCOVER", opt ? &addr : NULL, mess->chaddr, iface_name, message);
if (message)
return 0;
/* ensure that we send the reply by steam even if a buggy client sets this. */
mess->ciaddr.s_addr = 0;
bootp_option_put(mess, dhcp_file, dhcp_sname);
mess->siaddr = dhcp_next_server.s_addr ? dhcp_next_server : iface_addr;
bootp_option_put(mess, daemon->dhcp_file, daemon->dhcp_sname);
mess->siaddr = daemon->dhcp_next_server.s_addr ? daemon->dhcp_next_server : iface_addr;
p = option_put(p, end, OPTION_MESSAGE_TYPE, 1, DHCPOFFER);
p = option_put(p, end, OPTION_SERVER_IDENTIFIER, INADDRSZ, ntohl(iface_addr.s_addr));
p = option_put(p, end, OPTION_LEASE_TIME, 4, expires_time);
@@ -365,8 +439,8 @@ int dhcp_reply(struct dhcp_context *context,
p = option_put(p, end, OPTION_T1, 4, (expires_time/2));
p = option_put(p, end, OPTION_T2, 4, ((expires_time * 7)/8));
}
p = do_req_options(context, p, end, req_options, dhcp_opts, domain_suffix,
NULL, router, iface_addr, iface_mtu, netid);
p = do_req_options(context, p, end, req_options, daemon,
NULL, iface_addr, netid, subnet_addr);
p = option_end(p, end, mess);
log_packet("OFFER" , &mess->yiaddr, mess->chaddr, iface_name, NULL);
@@ -379,53 +453,77 @@ int dhcp_reply(struct dhcp_context *context,
{
/* SELECTING or INIT_REBOOT */
mess->yiaddr = option_addr(opt);
/* The RFC says that this is already zero, but there exist
real-world counter examples. */
mess->ciaddr.s_addr = 0;
if ((opt = option_find(mess, sz, OPTION_SERVER_IDENTIFIER)) &&
(iface_addr.s_addr != option_addr(opt).s_addr))
return 0;
/* If a lease exists for this host and another address, squash it. */
if (lease && lease->addr.s_addr != mess->yiaddr.s_addr)
if ((opt = option_find(mess, sz, OPTION_SERVER_IDENTIFIER)))
{
lease_prune(lease, now);
lease = NULL;
/* SELECTING */
if (iface_addr.s_addr != option_addr(opt).s_addr)
return 0;
/* If a lease exists for this host and another address, squash it. */
if (lease && lease->addr.s_addr != mess->yiaddr.s_addr)
{
lease_prune(lease, now);
lease = NULL;
}
if (!lease)
{
if (lease_find_by_addr(mess->yiaddr))
message = "address in use";
else if (!(lease = lease_allocate(clid, clid_len, mess->yiaddr)))
message = "no leases left";
}
}
/* accept addresses in the dynamic range or ones allocated statically to
particular hosts or an address which the host already has. */
if (!lease)
{
if (!address_available(context, mess->yiaddr) &&
(!have_config(config, CONFIG_ADDR) || config->addr.s_addr != mess->yiaddr.s_addr))
message = "address unavailable";
else if (!(lease = lease_allocate(clid, clid_len, mess->yiaddr)))
message = "no leases left";
else
{
/* INIT-REBOOT */
if (!lease)
return 0;
if (lease->addr.s_addr != mess->yiaddr.s_addr)
message = "wrong address";
}
}
else
{
/* RENEWING or REBINDING */
/* Must exist a lease for this address */
if (!mess->ciaddr.s_addr)
return 0;
mess->yiaddr = mess->ciaddr;
if (!lease || mess->ciaddr.s_addr != lease->addr.s_addr)
message = "lease not found";
/* desynchronise renewals */
fuzz = rand16();
while (fuzz > (renewal_time/16))
fuzz = fuzz/2;
fuzz = fuzz/2;
mess->yiaddr = mess->ciaddr;
}
/* If a machine moves networks whilst it has a lease, we catch that here. */
if (!message && !is_same_net(mess->yiaddr, context->start, context->netmask))
message = "wrong network";
if (!message)
{
struct dhcp_config *addr_config;
/* If a machine moves networks whilst it has a lease, we catch that here. */
if (!is_same_net(mess->yiaddr, context->start, context->netmask))
message = "wrong network";
/* Check for renewal of a lease which is now outside the allowed range. */
else if (!address_available(context, mess->yiaddr) &&
(!have_config(config, CONFIG_ADDR) || config->addr.s_addr != mess->yiaddr.s_addr))
message = "address no longer available";
/* Check if a new static address has been configured. Be very sure that
when the client does DISCOVER, it will get the static address, otherwise
an endless protocol loop will ensue. */
else if (have_config(config, CONFIG_ADDR) && !lease_find_by_addr(config->addr))
message = "static lease available";
/* Check to see if the address is reserved as a static address for another host */
else if ((addr_config = config_find_by_address(daemon->dhcp_conf, mess->yiaddr)) && addr_config != config)
message ="address reserved";
}
log_packet("REQUEST", &mess->yiaddr, mess->chaddr, iface_name, NULL);
if (message)
@@ -445,11 +543,11 @@ int dhcp_reply(struct dhcp_context *context,
lease_set_hwaddr(lease, mess->chaddr);
if (hostname)
lease_set_hostname(lease, hostname, domain_suffix);
lease_set_hostname(lease, hostname, daemon->domain_suffix);
lease_set_expires(lease, renewal_time == 0xffffffff ? 0 : now + (time_t)renewal_time);
bootp_option_put(mess, dhcp_file, dhcp_sname);
mess->siaddr = dhcp_next_server.s_addr ? dhcp_next_server : iface_addr;
bootp_option_put(mess, daemon->dhcp_file, daemon->dhcp_sname);
mess->siaddr = daemon->dhcp_next_server.s_addr ? daemon->dhcp_next_server : iface_addr;
p = option_put(p, end, OPTION_MESSAGE_TYPE, 1, DHCPACK);
p = option_put(p, end, OPTION_SERVER_IDENTIFIER, INADDRSZ, ntohl(iface_addr.s_addr));
p = option_put(p, end, OPTION_LEASE_TIME, 4, renewal_time);
@@ -458,8 +556,8 @@ int dhcp_reply(struct dhcp_context *context,
p = option_put(p, end, OPTION_T1, 4, (renewal_time/2) - fuzz);
p = option_put(p, end, OPTION_T2, 4, ((renewal_time * 7)/8) - fuzz);
}
p = do_req_options(context, p, end, req_options, dhcp_opts, domain_suffix,
hostname, router, iface_addr, iface_mtu, netid);
p = do_req_options(context, p, end, req_options, daemon,
hostname, iface_addr, netid, subnet_addr);
p = option_end(p, end, mess);
return p - (unsigned char *)mess;
@@ -474,8 +572,8 @@ int dhcp_reply(struct dhcp_context *context,
p = option_put(p, end, OPTION_MESSAGE_TYPE, 1, DHCPACK);
p = option_put(p, end, OPTION_SERVER_IDENTIFIER, INADDRSZ, ntohl(iface_addr.s_addr));
p = do_req_options(context, p, end, req_options, dhcp_opts, domain_suffix,
hostname, router, iface_addr, iface_mtu, netid);
p = do_req_options(context, p, end, req_options, daemon,
hostname, iface_addr, netid, subnet_addr);
p = option_end(p, end, mess);
log_packet("ACK", &mess->ciaddr, mess->chaddr, iface_name, hostname);
@@ -487,8 +585,9 @@ int dhcp_reply(struct dhcp_context *context,
static void log_packet(char *type, struct in_addr *addr, unsigned char *hwaddr, char *interface, char *string)
{
syslog(LOG_INFO, "DHCP%s(%s)%s%s %.2x:%.2x:%.2x:%.2x:%.2x:%.2x%s%s",
type,
syslog(LOG_INFO, "%s%s(%s)%s%s %.2x:%.2x:%.2x:%.2x:%.2x:%.2x%s%s",
type ? "DHCP" : "BOOTP",
type ? type : "",
interface,
addr ? " " : "",
addr ? inet_ntoa(*addr) : "",
@@ -568,13 +667,16 @@ static unsigned char *option_end(unsigned char *p, unsigned char *end, struct dh
static unsigned char *option_put_string(unsigned char *p, unsigned char *end, int opt, char *string)
{
if (p + strlen(string) + 3 < end)
int len = strlen(string);
if (p + len + 3 < end)
{
*(p++) = opt;
*(p++) = strlen(string);
memcpy(p, string, strlen(string));
p += strlen(string);
*(p++) = len;
memcpy(p, string, len);
p += len;
}
return p;
}
@@ -619,7 +721,8 @@ static unsigned char *option_find(struct dhcp_packet *mess, int size, int opt_ty
int overload = 0;
unsigned char *ret;
ret = option_find1(&mess->options[0], ((unsigned char *)mess) + size, opt_type, &overload);
/* skip over DHCP cookie; */
ret = option_find1(&mess->options[0] + sizeof(u32), ((unsigned char *)mess) + size, opt_type, &overload);
if (!ret && (overload & 1))
ret = option_find1(&mess->file[0], &mess->file[128], opt_type, &overload);
@@ -670,39 +773,46 @@ static struct dhcp_opt *option_find2(struct dhcp_netid *netid, struct dhcp_opt *
static unsigned char *do_req_options(struct dhcp_context *context,
unsigned char *p, unsigned char *end,
unsigned char *req_options,
struct dhcp_opt *config_opts,
char *domainname, char *hostname,
struct in_addr router,
struct daemon *daemon,
char *hostname,
struct in_addr iface_addr,
int iface_mtu, struct dhcp_netid *netid)
struct dhcp_netid *netid,
struct in_addr subnet_addr)
{
struct dhcp_opt *opt;
struct dhcp_opt *opt, *config_opts = daemon->dhcp_opts;
if (in_list(req_options, OPTION_MAXMESSAGE))
p = option_put(p, end, OPTION_MAXMESSAGE, 2,
DNSMASQ_PACKETSZ > iface_mtu ?
iface_mtu : DNSMASQ_PACKETSZ);
p = option_put(p, end, OPTION_MAXMESSAGE, 2, end - (unsigned char *)daemon->dhcp_packet);
/* rfc3011 says this doesn't need to be in the requested options list. */
if (subnet_addr.s_addr)
p = option_put(p, end, OPTION_SUBNET_SELECT, INADDRSZ, ntohl(subnet_addr.s_addr));
if (in_list(req_options, OPTION_NETMASK) &&
!option_find2(netid, config_opts, OPTION_NETMASK))
p = option_put(p, end, OPTION_NETMASK, INADDRSZ, ntohl(context->netmask.s_addr));
if (in_list(req_options, OPTION_BROADCAST) &&
/* May not have a "guessed" broadcast address if we got no packets via a relay
from this net yet (ie just unicast renewals after a restart */
if (context->broadcast.s_addr &&
in_list(req_options, OPTION_BROADCAST) &&
!option_find2(netid, config_opts, OPTION_BROADCAST))
p = option_put(p, end, OPTION_BROADCAST, INADDRSZ, ntohl(context->broadcast.s_addr));
if (in_list(req_options, OPTION_ROUTER) &&
/* Same comments as broadcast apply, and also may not be able to get a sensible
default when using subnet select. User must configure by steam in that case. */
if (context->router.s_addr &&
in_list(req_options, OPTION_ROUTER) &&
!option_find2(netid, config_opts, OPTION_ROUTER))
p = option_put(p, end, OPTION_ROUTER, INADDRSZ,
ntohl(router.s_addr));
p = option_put(p, end, OPTION_ROUTER, INADDRSZ, ntohl(context->router.s_addr));
if (in_list(req_options, OPTION_DNSSERVER) &&
!option_find2(netid, config_opts, OPTION_DNSSERVER))
p = option_put(p, end, OPTION_DNSSERVER, INADDRSZ, ntohl(iface_addr.s_addr));
if (domainname && in_list(req_options, OPTION_DOMAINNAME) &&
if (daemon->domain_suffix && in_list(req_options, OPTION_DOMAINNAME) &&
!option_find2(netid, config_opts, OPTION_DOMAINNAME))
p = option_put_string(p, end, OPTION_DOMAINNAME, domainname);
p = option_put_string(p, end, OPTION_DOMAINNAME, daemon->domain_suffix);
/* Note that we ignore attempts to set the hostname using
--dhcp-option=12,<name> */