Merge pull request #171

32be6ae added aabramov's gpg key (Riccardo Spagni)
010bfcf minor English wordlist tweaks (Riccardo Spagni)
9ef094b added unbound to external deps (Riccardo Spagni)
732493c split mnemonic printout over 3 lines (Riccardo Spagni)
This commit is contained in:
Riccardo Spagni 2014-10-06 08:51:44 +02:00
commit 3463f0ab52
No known key found for this signature in database
GPG Key ID: 55432DF31CCD4FCD
397 changed files with 199322 additions and 23 deletions

30
external/unbound/LICENSE vendored Normal file
View File

@ -0,0 +1,30 @@
Copyright (c) 2007, NLnet Labs. All rights reserved.
This software is open source.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
Neither the name of the NLNET LABS nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

1208
external/unbound/Makefile.in vendored Normal file

File diff suppressed because it is too large Load Diff

10
external/unbound/README vendored Normal file
View File

@ -0,0 +1,10 @@
Unbound README
* ./configure && make && make install
* You can use libevent if you want. libevent is useful when using
many (10000) outgoing ports. By default max 256 ports are opened at
the same time and the builtin alternative is equally capable and a
little faster.
* More detailed README, README.svn, README.tests in doc directory
* manual pages can be found in doc directory, and are installed, unbound(8).
* example configuration file doc/example.conf

122
external/unbound/ac_pkg_swig.m4 vendored Normal file
View File

@ -0,0 +1,122 @@
# ===========================================================================
# http://autoconf-archive.cryp.to/ac_pkg_swig.html
# ===========================================================================
#
# SYNOPSIS
#
# AC_PROG_SWIG([major.minor.micro])
#
# DESCRIPTION
#
# This macro searches for a SWIG installation on your system. If found you
# should call SWIG via $(SWIG). You can use the optional first argument to
# check if the version of the available SWIG is greater than or equal to
# the value of the argument. It should have the format: N[.N[.N]] (N is a
# number between 0 and 999. Only the first N is mandatory.)
#
# If the version argument is given (e.g. 1.3.17), AC_PROG_SWIG checks that
# the swig package is this version number or higher.
#
# In configure.in, use as:
#
# AC_PROG_SWIG(1.3.17)
# SWIG_ENABLE_CXX
# SWIG_MULTI_MODULE_SUPPORT
# SWIG_PYTHON
#
# LAST MODIFICATION
#
# 2008-04-12
#
# COPYLEFT
#
# Copyright (c) 2008 Sebastian Huber <sebastian-huber@web.de>
# Copyright (c) 2008 Alan W. Irwin <irwin@beluga.phys.uvic.ca>
# Copyright (c) 2008 Rafael Laboissiere <rafael@laboissiere.net>
# Copyright (c) 2008 Andrew Collier <colliera@ukzn.ac.za>
#
# 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, see <http://www.gnu.org/licenses/>.
#
# As a special exception, the respective Autoconf Macro's copyright owner
# gives unlimited permission to copy, distribute and modify the configure
# scripts that are the output of Autoconf when processing the Macro. You
# need not follow the terms of the GNU General Public License when using
# or distributing such scripts, even though portions of the text of the
# Macro appear in them. The GNU General Public License (GPL) does govern
# all other use of the material that constitutes the Autoconf Macro.
#
# This special exception to the GPL applies to versions of the Autoconf
# Macro released by the Autoconf Macro Archive. When you make and
# distribute a modified version of the Autoconf Macro, you may extend this
# special exception to the GPL to apply to your modified version as well.
AC_DEFUN([AC_PROG_SWIG],[
AC_PATH_PROG([SWIG],[swig])
if test -z "$SWIG" ; then
AC_MSG_WARN([cannot find 'swig' program. You should look at http://www.swig.org])
SWIG='echo "Error: SWIG is not installed. You should look at http://www.swig.org" ; false'
elif test -n "$1" ; then
AC_MSG_CHECKING([for SWIG version])
[swig_version=`$SWIG -version 2>&1 | grep 'SWIG Version' | sed 's/.*\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\).*/\1/g'`]
AC_MSG_RESULT([$swig_version])
if test -n "$swig_version" ; then
# Calculate the required version number components
[required=$1]
[required_major=`echo $required | sed 's/[^0-9].*//'`]
if test -z "$required_major" ; then
[required_major=0]
fi
[required=`echo $required | sed 's/[0-9]*[^0-9]//'`]
[required_minor=`echo $required | sed 's/[^0-9].*//'`]
if test -z "$required_minor" ; then
[required_minor=0]
fi
[required=`echo $required | sed 's/[0-9]*[^0-9]//'`]
[required_patch=`echo $required | sed 's/[^0-9].*//'`]
if test -z "$required_patch" ; then
[required_patch=0]
fi
# Calculate the available version number components
[available=$swig_version]
[available_major=`echo $available | sed 's/[^0-9].*//'`]
if test -z "$available_major" ; then
[available_major=0]
fi
[available=`echo $available | sed 's/[0-9]*[^0-9]//'`]
[available_minor=`echo $available | sed 's/[^0-9].*//'`]
if test -z "$available_minor" ; then
[available_minor=0]
fi
[available=`echo $available | sed 's/[0-9]*[^0-9]//'`]
[available_patch=`echo $available | sed 's/[^0-9].*//'`]
if test -z "$available_patch" ; then
[available_patch=0]
fi
if test $available_major -ne $required_major \
-o $available_minor -ne $required_minor \
-o $available_patch -lt $required_patch ; then
AC_MSG_WARN([SWIG version >= $1 is required. You have $swig_version. You should look at http://www.swig.org])
SWIG='echo "Error: SWIG version >= $1 is required. You have '"$swig_version"'. You should look at http://www.swig.org" ; false'
else
AC_MSG_NOTICE([SWIG executable is '$SWIG'])
SWIG_LIB=`$SWIG -swiglib`
AC_MSG_NOTICE([SWIG library directory is '$SWIG_LIB'])
fi
else
AC_MSG_WARN([cannot determine SWIG version])
SWIG='echo "Error: Cannot determine SWIG version. You should look at http://www.swig.org" ; false'
fi
fi
AC_SUBST([SWIG_LIB])
])

8611
external/unbound/aclocal.m4 vendored Normal file

File diff suppressed because it is too large Load Diff

1378
external/unbound/acx_nlnetlabs.m4 vendored Normal file

File diff suppressed because it is too large Load Diff

115
external/unbound/acx_python.m4 vendored Normal file
View File

@ -0,0 +1,115 @@
AC_DEFUN([AC_PYTHON_DEVEL],[
#
# Allow the use of a (user set) custom python version
#
AC_ARG_VAR([PYTHON_VERSION],[The installed Python
version to use, for example '2.3'. This string
will be appended to the Python interpreter
canonical name.])
AC_PATH_PROG([PYTHON],[python[$PYTHON_VERSION]])
if test -z "$PYTHON"; then
AC_MSG_ERROR([Cannot find python$PYTHON_VERSION in your system path])
PYTHON_VERSION=""
fi
if test -z "$PYTHON_VERSION"; then
PYTHON_VERSION=`$PYTHON -c "import sys; \
print(sys.version.split()[[0]])"`
fi
#
# Check if you have distutils, else fail
#
AC_MSG_CHECKING([for the distutils Python package])
ac_distutils_result=`$PYTHON -c "import distutils" 2>&1`
if test -z "$ac_distutils_result"; then
AC_MSG_RESULT([yes])
else
AC_MSG_RESULT([no])
AC_MSG_ERROR([cannot import Python module "distutils".
Please check your Python installation. The error was:
$ac_distutils_result])
PYTHON_VERSION=""
fi
#
# Check for Python include path
#
AC_MSG_CHECKING([for Python include path])
if test -z "$PYTHON_CPPFLAGS"; then
python_path=`$PYTHON -c "import distutils.sysconfig; \
print(distutils.sysconfig.get_python_inc());"`
if test -n "${python_path}"; then
python_path="-I$python_path"
fi
PYTHON_CPPFLAGS=$python_path
fi
AC_MSG_RESULT([$PYTHON_CPPFLAGS])
AC_SUBST([PYTHON_CPPFLAGS])
#
# Check for Python library path
#
AC_MSG_CHECKING([for Python library path])
if test -z "$PYTHON_LDFLAGS"; then
PYTHON_LDFLAGS=`$PYTHON -c "from distutils.sysconfig import *; \
print(get_config_var('BLDLIBRARY'));"`
fi
AC_MSG_RESULT([$PYTHON_LDFLAGS])
AC_SUBST([PYTHON_LDFLAGS])
#
# Check for site packages
#
AC_MSG_CHECKING([for Python site-packages path])
if test -z "$PYTHON_SITE_PKG"; then
PYTHON_SITE_PKG=`$PYTHON -c "import distutils.sysconfig; \
print(distutils.sysconfig.get_python_lib(1,0));"`
fi
AC_MSG_RESULT([$PYTHON_SITE_PKG])
AC_SUBST([PYTHON_SITE_PKG])
#
# final check to see if everything compiles alright
#
AC_MSG_CHECKING([consistency of all components of python development environment])
AC_LANG_PUSH([C])
# save current global flags
ac_save_LIBS="$LIBS"
ac_save_CPPFLAGS="$CPPFLAGS"
LIBS="$LIBS $PYTHON_LDFLAGS"
CPPFLAGS="$CPPFLAGS $PYTHON_CPPFLAGS"
AC_TRY_LINK([
#include <Python.h>
],[
Py_Initialize();
],[pythonexists=yes],[pythonexists=no])
AC_MSG_RESULT([$pythonexists])
if test ! "$pythonexists" = "yes"; then
AC_MSG_ERROR([
Could not link test program to Python. Maybe the main Python library has been
installed in some non-standard library path. If so, pass it to configure,
via the LDFLAGS environment variable.
Example: ./configure LDFLAGS="-L/usr/non-standard-path/python/lib"
============================================================================
ERROR!
You probably have to install the development version of the Python package
for your distribution. The exact name of this package varies among them.
============================================================================
])
PYTHON_VERSION=""
fi
AC_LANG_POP
# turn back to default flags
CPPFLAGS="$ac_save_CPPFLAGS"
LIBS="$ac_save_LIBS"
#
# all done!
#
])

317
external/unbound/ax_pthread.m4 vendored Normal file
View File

@ -0,0 +1,317 @@
# ===========================================================================
# http://www.gnu.org/software/autoconf-archive/ax_pthread.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
#
# DESCRIPTION
#
# This macro figures out how to build C programs using POSIX threads. It
# sets the PTHREAD_LIBS output variable to the threads library and linker
# flags, and the PTHREAD_CFLAGS output variable to any special C compiler
# flags that are needed. (The user can also force certain compiler
# flags/libs to be tested by setting these environment variables.)
#
# Also sets PTHREAD_CC to any special C compiler that is needed for
# multi-threaded programs (defaults to the value of CC otherwise). (This
# is necessary on AIX to use the special cc_r compiler alias.)
#
# NOTE: You are assumed to not only compile your program with these flags,
# but also link it with them as well. e.g. you should link with
# $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS
#
# If you are only building threads programs, you may wish to use these
# variables in your default LIBS, CFLAGS, and CC:
#
# LIBS="$PTHREAD_LIBS $LIBS"
# CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
# CC="$PTHREAD_CC"
#
# In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute constant
# has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to that name
# (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
#
# Also HAVE_PTHREAD_PRIO_INHERIT is defined if pthread is found and the
# PTHREAD_PRIO_INHERIT symbol is defined when compiling with
# PTHREAD_CFLAGS.
#
# ACTION-IF-FOUND is a list of shell commands to run if a threads library
# is found, and ACTION-IF-NOT-FOUND is a list of commands to run it if it
# is not found. If ACTION-IF-FOUND is not specified, the default action
# will define HAVE_PTHREAD.
#
# Please let the authors know if this macro fails on any platform, or if
# you have any other suggestions or comments. This macro was based on work
# by SGJ on autoconf scripts for FFTW (http://www.fftw.org/) (with help
# from M. Frigo), as well as ac_pthread and hb_pthread macros posted by
# Alejandro Forero Cuervo to the autoconf macro repository. We are also
# grateful for the helpful feedback of numerous users.
#
# Updated for Autoconf 2.68 by Daniel Richard G.
#
# LICENSE
#
# Copyright (c) 2008 Steven G. Johnson <stevenj@alum.mit.edu>
# Copyright (c) 2011 Daniel Richard G. <skunk@iSKUNK.ORG>
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
#
# As a special exception, the respective Autoconf Macro's copyright owner
# gives unlimited permission to copy, distribute and modify the configure
# scripts that are the output of Autoconf when processing the Macro. You
# need not follow the terms of the GNU General Public License when using
# or distributing such scripts, even though portions of the text of the
# Macro appear in them. The GNU General Public License (GPL) does govern
# all other use of the material that constitutes the Autoconf Macro.
#
# This special exception to the GPL applies to versions of the Autoconf
# Macro released by the Autoconf Archive. When you make and distribute a
# modified version of the Autoconf Macro, you may extend this special
# exception to the GPL to apply to your modified version as well.
#serial 20
AU_ALIAS([ACX_PTHREAD], [AX_PTHREAD])
AC_DEFUN([AX_PTHREAD], [
AC_REQUIRE([AC_CANONICAL_HOST])
AC_LANG_PUSH([C])
ax_pthread_ok=no
# We used to check for pthread.h first, but this fails if pthread.h
# requires special compiler flags (e.g. on True64 or Sequent).
# It gets checked for in the link test anyway.
# First of all, check if the user has set any of the PTHREAD_LIBS,
# etcetera environment variables, and if threads linking works using
# them:
if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then
save_CFLAGS="$CFLAGS"
CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
save_LIBS="$LIBS"
LIBS="$PTHREAD_LIBS $LIBS"
AC_MSG_CHECKING([for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS])
AC_TRY_LINK_FUNC(pthread_join, ax_pthread_ok=yes)
AC_MSG_RESULT($ax_pthread_ok)
if test x"$ax_pthread_ok" = xno; then
PTHREAD_LIBS=""
PTHREAD_CFLAGS=""
fi
LIBS="$save_LIBS"
CFLAGS="$save_CFLAGS"
fi
# We must check for the threads library under a number of different
# names; the ordering is very important because some systems
# (e.g. DEC) have both -lpthread and -lpthreads, where one of the
# libraries is broken (non-POSIX).
# Create a list of thread flags to try. Items starting with a "-" are
# C compiler flags, and other items are library names, except for "none"
# which indicates that we try without any flags at all, and "pthread-config"
# which is a program returning the flags for the Pth emulation library.
ax_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"
# The ordering *is* (sometimes) important. Some notes on the
# individual items follow:
# pthreads: AIX (must check this before -lpthread)
# none: in case threads are in libc; should be tried before -Kthread and
# other compiler flags to prevent continual compiler warnings
# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads)
# -pthreads: Solaris/gcc
# -mthreads: Mingw32/gcc, Lynx/gcc
# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
# doesn't hurt to check since this sometimes defines pthreads too;
# also defines -D_REENTRANT)
# ... -mt is also the pthreads flag for HP/aCC
# pthread: Linux, etcetera
# --thread-safe: KAI C++
# pthread-config: use pthread-config program (for GNU Pth library)
case ${host_os} in
solaris*)
# On Solaris (at least, for some versions), libc contains stubbed
# (non-functional) versions of the pthreads routines, so link-based
# tests will erroneously succeed. (We need to link with -pthreads/-mt/
# -lpthread.) (The stubs are missing pthread_cleanup_push, or rather
# a function called by this macro, so we could check for that, but
# who knows whether they'll stub that too in a future libc.) So,
# we'll just look for -pthreads and -lpthread first:
ax_pthread_flags="-pthreads pthread -mt -pthread $ax_pthread_flags"
;;
darwin*)
ax_pthread_flags="-pthread $ax_pthread_flags"
;;
esac
if test x"$ax_pthread_ok" = xno; then
for flag in $ax_pthread_flags; do
case $flag in
none)
AC_MSG_CHECKING([whether pthreads work without any flags])
;;
-*)
AC_MSG_CHECKING([whether pthreads work with $flag])
PTHREAD_CFLAGS="$flag"
;;
pthread-config)
AC_CHECK_PROG(ax_pthread_config, pthread-config, yes, no)
if test x"$ax_pthread_config" = xno; then continue; fi
PTHREAD_CFLAGS="`pthread-config --cflags`"
PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
;;
*)
AC_MSG_CHECKING([for the pthreads library -l$flag])
PTHREAD_LIBS="-l$flag"
;;
esac
save_LIBS="$LIBS"
save_CFLAGS="$CFLAGS"
LIBS="$PTHREAD_LIBS $LIBS"
CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
# Check for various functions. We must include pthread.h,
# since some functions may be macros. (On the Sequent, we
# need a special flag -Kthread to make this header compile.)
# We check for pthread_join because it is in -lpthread on IRIX
# while pthread_create is in libc. We check for pthread_attr_init
# due to DEC craziness with -lpthreads. We check for
# pthread_cleanup_push because it is one of the few pthread
# functions on Solaris that doesn't have a non-functional libc stub.
# We try pthread_create on general principles.
AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <pthread.h>
static void routine(void *a) { *((int*)a) = 0; }
static void *start_routine(void *a) { return a; }],
[pthread_t th; pthread_attr_t attr;
pthread_create(&th, 0, start_routine, 0);
pthread_join(th, 0);
pthread_attr_init(&attr);
pthread_cleanup_push(routine, 0);
pthread_cleanup_pop(0) /* ; */])],
[ax_pthread_ok=yes],
[])
LIBS="$save_LIBS"
CFLAGS="$save_CFLAGS"
AC_MSG_RESULT($ax_pthread_ok)
if test "x$ax_pthread_ok" = xyes; then
break;
fi
PTHREAD_LIBS=""
PTHREAD_CFLAGS=""
done
fi
# Various other checks:
if test "x$ax_pthread_ok" = xyes; then
save_LIBS="$LIBS"
LIBS="$PTHREAD_LIBS $LIBS"
save_CFLAGS="$CFLAGS"
CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
# Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
AC_MSG_CHECKING([for joinable pthread attribute])
attr_name=unknown
for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <pthread.h>],
[int attr = $attr; return attr /* ; */])],
[attr_name=$attr; break],
[])
done
AC_MSG_RESULT($attr_name)
if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then
AC_DEFINE_UNQUOTED(PTHREAD_CREATE_JOINABLE, $attr_name,
[Define to necessary symbol if this constant
uses a non-standard name on your system.])
fi
AC_MSG_CHECKING([if more special flags are required for pthreads])
flag=no
case ${host_os} in
aix* | freebsd* | darwin*) flag="-D_THREAD_SAFE";;
osf* | hpux*) flag="-D_REENTRANT";;
solaris*)
if test "$GCC" = "yes"; then
flag="-D_REENTRANT"
else
flag="-mt -D_REENTRANT"
fi
;;
esac
AC_MSG_RESULT(${flag})
if test "x$flag" != xno; then
PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS"
fi
AC_CACHE_CHECK([for PTHREAD_PRIO_INHERIT],
ax_cv_PTHREAD_PRIO_INHERIT, [
AC_LINK_IFELSE([
AC_LANG_PROGRAM([[#include <pthread.h>]], [[int i = PTHREAD_PRIO_INHERIT;]])],
[ax_cv_PTHREAD_PRIO_INHERIT=yes],
[ax_cv_PTHREAD_PRIO_INHERIT=no])
])
AS_IF([test "x$ax_cv_PTHREAD_PRIO_INHERIT" = "xyes"],
AC_DEFINE([HAVE_PTHREAD_PRIO_INHERIT], 1, [Have PTHREAD_PRIO_INHERIT.]))
LIBS="$save_LIBS"
CFLAGS="$save_CFLAGS"
# More AIX lossage: compile with *_r variant
if test "x$GCC" != xyes; then
case $host_os in
aix*)
AS_CASE(["x/$CC"],
[x*/c89|x*/c89_128|x*/c99|x*/c99_128|x*/cc|x*/cc128|x*/xlc|x*/xlc_v6|x*/xlc128|x*/xlc128_v6],
[#handle absolute path differently from PATH based program lookup
AS_CASE(["x$CC"],
[x/*],
[AS_IF([AS_EXECUTABLE_P([${CC}_r])],[PTHREAD_CC="${CC}_r"])],
[AC_CHECK_PROGS([PTHREAD_CC],[${CC}_r],[$CC])])])
;;
esac
fi
fi
test -n "$PTHREAD_CC" || PTHREAD_CC="$CC"
AC_SUBST(PTHREAD_LIBS)
AC_SUBST(PTHREAD_CFLAGS)
AC_SUBST(PTHREAD_CC)
# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
if test x"$ax_pthread_ok" = xyes; then
ifelse([$1],,AC_DEFINE(HAVE_PTHREAD,1,[Define if you have POSIX threads libraries and header files.]),[$1])
:
else
ax_pthread_ok=no
$2
fi
AC_LANG_POP
])dnl AX_PTHREAD

65
external/unbound/compat/arc4_lock.c vendored Normal file
View File

@ -0,0 +1,65 @@
/* arc4_lock.c - global lock for arc4random
*
* Copyright (c) 2014, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#define LOCKRET(func) func
#include "util/locks.h"
void _ARC4_LOCK(void);
void _ARC4_UNLOCK(void);
#ifdef THREADS_DISABLED
void _ARC4_LOCK(void)
{
}
void _ARC4_UNLOCK(void)
{
}
#else /* !THREADS_DISABLED */
static lock_quick_t arc4lock;
static int arc4lockinit = 0;
void _ARC4_LOCK(void)
{
if(!arc4lockinit)
lock_quick_init(&arc4lock);
lock_quick_lock(&arc4lock);
}
void _ARC4_UNLOCK(void)
{
lock_quick_unlock(&arc4lock);
}
#endif /* THREADS_DISABLED */

231
external/unbound/compat/arc4random.c vendored Normal file
View File

@ -0,0 +1,231 @@
/* $OpenBSD: arc4random.c,v 1.41 2014/07/12 13:24:54 deraadt Exp $ */
/*
* Copyright (c) 1996, David Mazieres <dm@uun.org>
* Copyright (c) 2008, Damien Miller <djm@openbsd.org>
* Copyright (c) 2013, Markus Friedl <markus@openbsd.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "config.h"
/*
* ChaCha based random number generator for OpenBSD.
*/
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/time.h>
#ifndef UB_ON_WINDOWS
#include <sys/mman.h>
#endif
#define KEYSTREAM_ONLY
#include "chacha_private.h"
#define arc4_min(a, b) ((a) < (b) ? (a) : (b))
#ifdef __GNUC__
#define inline __inline
#else /* !__GNUC__ */
#define inline
#endif /* !__GNUC__ */
#define KEYSZ 32
#define IVSZ 8
#define BLOCKSZ 64
#define RSBUFSZ (16*BLOCKSZ)
/* Marked MAP_INHERIT_ZERO, so zero'd out in fork children. */
static struct {
size_t rs_have; /* valid bytes at end of rs_buf */
size_t rs_count; /* bytes till reseed */
} *rs;
/* Preserved in fork children. */
static struct {
chacha_ctx rs_chacha; /* chacha context for random keystream */
u_char rs_buf[RSBUFSZ]; /* keystream blocks */
} *rsx;
static inline void _rs_rekey(u_char *dat, size_t datlen);
static inline void
_rs_init(u_char *buf, size_t n)
{
if (n < KEYSZ + IVSZ)
return;
if (rs == NULL) {
#ifndef UB_ON_WINDOWS
if ((rs = mmap(NULL, sizeof(*rs), PROT_READ|PROT_WRITE,
MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED)
abort();
#ifdef MAP_INHERIT_ZERO
if (minherit(rs, sizeof(*rs), MAP_INHERIT_ZERO) == -1)
abort();
#endif
#else /* WINDOWS */
rs = malloc(sizeof(*rs));
if(!rs)
abort();
#endif
}
if (rsx == NULL) {
#ifndef UB_ON_WINDOWS
if ((rsx = mmap(NULL, sizeof(*rsx), PROT_READ|PROT_WRITE,
MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED)
abort();
#else /* WINDOWS */
rsx = malloc(sizeof(*rsx));
if(!rsx)
abort();
#endif
}
chacha_keysetup(&rsx->rs_chacha, buf, KEYSZ * 8, 0);
chacha_ivsetup(&rsx->rs_chacha, buf + KEYSZ);
}
static void
_rs_stir(void)
{
u_char rnd[KEYSZ + IVSZ];
if (getentropy(rnd, sizeof rnd) == -1) {
#ifdef SIGKILL
raise(SIGKILL);
#else
exit(9); /* windows */
#endif
}
if (!rs)
_rs_init(rnd, sizeof(rnd));
else
_rs_rekey(rnd, sizeof(rnd));
explicit_bzero(rnd, sizeof(rnd)); /* discard source seed */
/* invalidate rs_buf */
rs->rs_have = 0;
memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
rs->rs_count = 1600000;
}
static inline void
_rs_stir_if_needed(size_t len)
{
#ifndef MAP_INHERIT_ZERO
static pid_t _rs_pid = 0;
pid_t pid = getpid();
/* If a system lacks MAP_INHERIT_ZERO, resort to getpid() */
if (_rs_pid == 0 || _rs_pid != pid) {
_rs_pid = pid;
if (rs)
rs->rs_count = 0;
}
#endif
if (!rs || rs->rs_count <= len)
_rs_stir();
if (rs->rs_count <= len)
rs->rs_count = 0;
else
rs->rs_count -= len;
}
static inline void
_rs_rekey(u_char *dat, size_t datlen)
{
#ifndef KEYSTREAM_ONLY
memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
#endif
/* fill rs_buf with the keystream */
chacha_encrypt_bytes(&rsx->rs_chacha, rsx->rs_buf,
rsx->rs_buf, sizeof(rsx->rs_buf));
/* mix in optional user provided data */
if (dat) {
size_t i, m;
m = arc4_min(datlen, KEYSZ + IVSZ);
for (i = 0; i < m; i++)
rsx->rs_buf[i] ^= dat[i];
}
/* immediately reinit for backtracking resistance */
_rs_init(rsx->rs_buf, KEYSZ + IVSZ);
memset(rsx->rs_buf, 0, KEYSZ + IVSZ);
rs->rs_have = sizeof(rsx->rs_buf) - KEYSZ - IVSZ;
}
static inline void
_rs_random_buf(void *_buf, size_t n)
{
u_char *buf = (u_char *)_buf;
u_char *keystream;
size_t m;
_rs_stir_if_needed(n);
while (n > 0) {
if (rs->rs_have > 0) {
m = arc4_min(n, rs->rs_have);
keystream = rsx->rs_buf + sizeof(rsx->rs_buf)
- rs->rs_have;
memcpy(buf, keystream, m);
memset(keystream, 0, m);
buf += m;
n -= m;
rs->rs_have -= m;
}
if (rs->rs_have == 0)
_rs_rekey(NULL, 0);
}
}
static inline void
_rs_random_u32(uint32_t *val)
{
u_char *keystream;
_rs_stir_if_needed(sizeof(*val));
if (rs->rs_have < sizeof(*val))
_rs_rekey(NULL, 0);
keystream = rsx->rs_buf + sizeof(rsx->rs_buf) - rs->rs_have;
memcpy(val, keystream, sizeof(*val));
memset(keystream, 0, sizeof(*val));
rs->rs_have -= sizeof(*val);
}
uint32_t
arc4random(void)
{
uint32_t val;
_ARC4_LOCK();
_rs_random_u32(&val);
_ARC4_UNLOCK();
return val;
}
void
arc4random_buf(void *buf, size_t n)
{
_ARC4_LOCK();
_rs_random_buf(buf, n);
_ARC4_UNLOCK();
}

View File

@ -0,0 +1,57 @@
/* $OpenBSD: arc4random_uniform.c,v 1.1 2014/07/12 13:24:54 deraadt Exp $ */
/*
* Copyright (c) 2008, Damien Miller <djm@openbsd.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "config.h"
#include <sys/types.h>
#include <stdlib.h>
/*
* Calculate a uniformly distributed random number less than upper_bound
* avoiding "modulo bias".
*
* Uniformity is achieved by generating new random numbers until the one
* returned is outside the range [0, 2**32 % upper_bound). This
* guarantees the selected random number will be inside
* [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
* after reduction modulo upper_bound.
*/
uint32_t
arc4random_uniform(uint32_t upper_bound)
{
uint32_t r, min;
if (upper_bound < 2)
return 0;
/* 2**32 % x == (2**32 - x) % x */
min = -upper_bound % upper_bound;
/*
* This could theoretically loop forever but each retry has
* p > 0.5 (worst case, usually far better) of selecting a
* number inside the range we need, so it should rarely need
* to re-roll.
*/
for (;;) {
r = arc4random();
if (r >= min)
break;
}
return r % upper_bound;
}

222
external/unbound/compat/chacha_private.h vendored Normal file
View File

@ -0,0 +1,222 @@
/*
chacha-merged.c version 20080118
D. J. Bernstein
Public domain.
*/
/* $OpenBSD: chacha_private.h,v 1.2 2013/10/04 07:02:27 djm Exp $ */
typedef unsigned char u8;
typedef unsigned int u32;
typedef struct
{
u32 input[16]; /* could be compressed */
} chacha_ctx;
#define U8C(v) (v##U)
#define U32C(v) (v##U)
#define U8V(v) ((u8)(v) & U8C(0xFF))
#define U32V(v) ((u32)(v) & U32C(0xFFFFFFFF))
#define ROTL32(v, n) \
(U32V((v) << (n)) | ((v) >> (32 - (n))))
#define U8TO32_LITTLE(p) \
(((u32)((p)[0]) ) | \
((u32)((p)[1]) << 8) | \
((u32)((p)[2]) << 16) | \
((u32)((p)[3]) << 24))
#define U32TO8_LITTLE(p, v) \
do { \
(p)[0] = U8V((v) ); \
(p)[1] = U8V((v) >> 8); \
(p)[2] = U8V((v) >> 16); \
(p)[3] = U8V((v) >> 24); \
} while (0)
#define ROTATE(v,c) (ROTL32(v,c))
#define XOR(v,w) ((v) ^ (w))
#define PLUS(v,w) (U32V((v) + (w)))
#define PLUSONE(v) (PLUS((v),1))
#define QUARTERROUND(a,b,c,d) \
a = PLUS(a,b); d = ROTATE(XOR(d,a),16); \
c = PLUS(c,d); b = ROTATE(XOR(b,c),12); \
a = PLUS(a,b); d = ROTATE(XOR(d,a), 8); \
c = PLUS(c,d); b = ROTATE(XOR(b,c), 7);
static const char sigma[16] = "expand 32-byte k";
static const char tau[16] = "expand 16-byte k";
static void
chacha_keysetup(chacha_ctx *x,const u8 *k,u32 kbits,u32 ATTR_UNUSED(ivbits))
{
const char *constants;
x->input[4] = U8TO32_LITTLE(k + 0);
x->input[5] = U8TO32_LITTLE(k + 4);
x->input[6] = U8TO32_LITTLE(k + 8);
x->input[7] = U8TO32_LITTLE(k + 12);
if (kbits == 256) { /* recommended */
k += 16;
constants = sigma;
} else { /* kbits == 128 */
constants = tau;
}
x->input[8] = U8TO32_LITTLE(k + 0);
x->input[9] = U8TO32_LITTLE(k + 4);
x->input[10] = U8TO32_LITTLE(k + 8);
x->input[11] = U8TO32_LITTLE(k + 12);
x->input[0] = U8TO32_LITTLE(constants + 0);
x->input[1] = U8TO32_LITTLE(constants + 4);
x->input[2] = U8TO32_LITTLE(constants + 8);
x->input[3] = U8TO32_LITTLE(constants + 12);
}
static void
chacha_ivsetup(chacha_ctx *x,const u8 *iv)
{
x->input[12] = 0;
x->input[13] = 0;
x->input[14] = U8TO32_LITTLE(iv + 0);
x->input[15] = U8TO32_LITTLE(iv + 4);
}
static void
chacha_encrypt_bytes(chacha_ctx *x,const u8 *m,u8 *c,u32 bytes)
{
u32 x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15;
u32 j0, j1, j2, j3, j4, j5, j6, j7, j8, j9, j10, j11, j12, j13, j14, j15;
u8 *ctarget = NULL;
u8 tmp[64];
u_int i;
if (!bytes) return;
j0 = x->input[0];
j1 = x->input[1];
j2 = x->input[2];
j3 = x->input[3];
j4 = x->input[4];
j5 = x->input[5];
j6 = x->input[6];
j7 = x->input[7];
j8 = x->input[8];
j9 = x->input[9];
j10 = x->input[10];
j11 = x->input[11];
j12 = x->input[12];
j13 = x->input[13];
j14 = x->input[14];
j15 = x->input[15];
for (;;) {
if (bytes < 64) {
for (i = 0;i < bytes;++i) tmp[i] = m[i];
m = tmp;
ctarget = c;
c = tmp;
}
x0 = j0;
x1 = j1;
x2 = j2;
x3 = j3;
x4 = j4;
x5 = j5;
x6 = j6;
x7 = j7;
x8 = j8;
x9 = j9;
x10 = j10;
x11 = j11;
x12 = j12;
x13 = j13;
x14 = j14;
x15 = j15;
for (i = 20;i > 0;i -= 2) {
QUARTERROUND( x0, x4, x8,x12)
QUARTERROUND( x1, x5, x9,x13)
QUARTERROUND( x2, x6,x10,x14)
QUARTERROUND( x3, x7,x11,x15)
QUARTERROUND( x0, x5,x10,x15)
QUARTERROUND( x1, x6,x11,x12)
QUARTERROUND( x2, x7, x8,x13)
QUARTERROUND( x3, x4, x9,x14)
}
x0 = PLUS(x0,j0);
x1 = PLUS(x1,j1);
x2 = PLUS(x2,j2);
x3 = PLUS(x3,j3);
x4 = PLUS(x4,j4);
x5 = PLUS(x5,j5);
x6 = PLUS(x6,j6);
x7 = PLUS(x7,j7);
x8 = PLUS(x8,j8);
x9 = PLUS(x9,j9);
x10 = PLUS(x10,j10);
x11 = PLUS(x11,j11);
x12 = PLUS(x12,j12);
x13 = PLUS(x13,j13);
x14 = PLUS(x14,j14);
x15 = PLUS(x15,j15);
#ifndef KEYSTREAM_ONLY
x0 = XOR(x0,U8TO32_LITTLE(m + 0));
x1 = XOR(x1,U8TO32_LITTLE(m + 4));
x2 = XOR(x2,U8TO32_LITTLE(m + 8));
x3 = XOR(x3,U8TO32_LITTLE(m + 12));
x4 = XOR(x4,U8TO32_LITTLE(m + 16));
x5 = XOR(x5,U8TO32_LITTLE(m + 20));
x6 = XOR(x6,U8TO32_LITTLE(m + 24));
x7 = XOR(x7,U8TO32_LITTLE(m + 28));
x8 = XOR(x8,U8TO32_LITTLE(m + 32));
x9 = XOR(x9,U8TO32_LITTLE(m + 36));
x10 = XOR(x10,U8TO32_LITTLE(m + 40));
x11 = XOR(x11,U8TO32_LITTLE(m + 44));
x12 = XOR(x12,U8TO32_LITTLE(m + 48));
x13 = XOR(x13,U8TO32_LITTLE(m + 52));
x14 = XOR(x14,U8TO32_LITTLE(m + 56));
x15 = XOR(x15,U8TO32_LITTLE(m + 60));
#endif
j12 = PLUSONE(j12);
if (!j12) {
j13 = PLUSONE(j13);
/* stopping at 2^70 bytes per nonce is user's responsibility */
}
U32TO8_LITTLE(c + 0,x0);
U32TO8_LITTLE(c + 4,x1);
U32TO8_LITTLE(c + 8,x2);
U32TO8_LITTLE(c + 12,x3);
U32TO8_LITTLE(c + 16,x4);
U32TO8_LITTLE(c + 20,x5);
U32TO8_LITTLE(c + 24,x6);
U32TO8_LITTLE(c + 28,x7);
U32TO8_LITTLE(c + 32,x8);
U32TO8_LITTLE(c + 36,x9);
U32TO8_LITTLE(c + 40,x10);
U32TO8_LITTLE(c + 44,x11);
U32TO8_LITTLE(c + 48,x12);
U32TO8_LITTLE(c + 52,x13);
U32TO8_LITTLE(c + 56,x14);
U32TO8_LITTLE(c + 60,x15);
if (bytes <= 64) {
if (bytes < 64) {
for (i = 0;i < bytes;++i) ctarget[i] = c[i];
}
x->input[12] = j12;
x->input[13] = j13;
return;
}
bytes -= 64;
c += 64;
#ifndef KEYSTREAM_ONLY
m += 64;
#endif
}
}

42
external/unbound/compat/ctime_r.c vendored Normal file
View File

@ -0,0 +1,42 @@
/* taken from ldns 1.6.1 */
#include "config.h"
#ifdef HAVE_TIME_H
#include <time.h>
#endif
#include "util/locks.h"
/** the lock for ctime buffer */
static lock_basic_t ctime_lock;
/** has it been inited */
static int ctime_r_init = 0;
/** cleanup ctime_r on exit */
static void
ctime_r_cleanup(void)
{
if(ctime_r_init) {
ctime_r_init = 0;
lock_basic_destroy(&ctime_lock);
}
}
char *ctime_r(const time_t *timep, char *buf)
{
char* result;
if(!ctime_r_init) {
/* still small race where this init can be done twice,
* which is mostly harmless */
ctime_r_init = 1;
lock_basic_init(&ctime_lock);
atexit(&ctime_r_cleanup);
}
lock_basic_lock(&ctime_lock);
result = ctime(timep);
if(buf && result) {
if(strlen(result) > 10 && result[7]==' ' && result[8]=='0')
result[8]=' '; /* fix error in windows ctime */
strcpy(buf, result);
}
lock_basic_unlock(&ctime_lock);
return result;
}

View File

@ -0,0 +1,22 @@
/* $OpenBSD: explicit_bzero.c,v 1.3 2014/06/21 02:34:26 matthew Exp $ */
/*
* Public domain.
* Written by Matthew Dempsky.
*/
#include "config.h"
#include <string.h>
__attribute__((weak)) void
__explicit_bzero_hook(void *ATTR_UNUSED(buf), size_t ATTR_UNUSED(len))
{
}
void
explicit_bzero(void *buf, size_t len)
{
#ifdef UB_ON_WINDOWS
SecureZeroMemory(buf, len);
#endif
memset(buf, 0, len);
__explicit_bzero_hook(buf, len);
}

225
external/unbound/compat/fake-rfc2553.c vendored Normal file
View File

@ -0,0 +1,225 @@
/* From openssh 4.3p2 filename openbsd-compat/fake-rfc2553.h */
/*
* Copyright (C) 2000-2003 Damien Miller. All rights reserved.
* Copyright (C) 1999 WIDE Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Pseudo-implementation of RFC2553 name / address resolution functions
*
* But these functions are not implemented correctly. The minimum subset
* is implemented for ssh use only. For example, this routine assumes
* that ai_family is AF_INET. Don't use it for another purpose.
*/
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "compat/fake-rfc2553.h"
#ifndef HAVE_GETNAMEINFO
int getnameinfo(const struct sockaddr *sa, size_t ATTR_UNUSED(salen), char *host,
size_t hostlen, char *serv, size_t servlen, int flags)
{
struct sockaddr_in *sin = (struct sockaddr_in *)sa;
struct hostent *hp;
char tmpserv[16];
if (serv != NULL) {
snprintf(tmpserv, sizeof(tmpserv), "%d", ntohs(sin->sin_port));
if (strlcpy(serv, tmpserv, servlen) >= servlen)
return (EAI_MEMORY);
}
if (host != NULL) {
if (flags & NI_NUMERICHOST) {
if (strlcpy(host, inet_ntoa(sin->sin_addr),
hostlen) >= hostlen)
return (EAI_MEMORY);
else
return (0);
} else {
hp = gethostbyaddr((char *)&sin->sin_addr,
sizeof(struct in_addr), AF_INET);
if (hp == NULL)
return (EAI_NODATA);
if (strlcpy(host, hp->h_name, hostlen) >= hostlen)
return (EAI_MEMORY);
else
return (0);
}
}
return (0);
}
#endif /* !HAVE_GETNAMEINFO */
#ifndef HAVE_GAI_STRERROR
#ifdef HAVE_CONST_GAI_STRERROR_PROTO
const char *
#else
char *
#endif
gai_strerror(int err)
{
switch (err) {
case EAI_NODATA:
return ("no address associated with name");
case EAI_MEMORY:
return ("memory allocation failure.");
case EAI_NONAME:
return ("nodename nor servname provided, or not known");
default:
return ("unknown/invalid error.");
}
}
#endif /* !HAVE_GAI_STRERROR */
#ifndef HAVE_FREEADDRINFO
void
freeaddrinfo(struct addrinfo *ai)
{
struct addrinfo *next;
for(; ai != NULL;) {
next = ai->ai_next;
free(ai);
ai = next;
}
}
#endif /* !HAVE_FREEADDRINFO */
#ifndef HAVE_GETADDRINFO
static struct
addrinfo *malloc_ai(int port, u_long addr, const struct addrinfo *hints)
{
struct addrinfo *ai;
ai = calloc(1, sizeof(*ai) + sizeof(struct sockaddr_in));
if (ai == NULL)
return (NULL);
ai->ai_addr = (struct sockaddr *)(ai + 1);
/* XXX -- ssh doesn't use sa_len */
ai->ai_addrlen = sizeof(struct sockaddr_in);
ai->ai_addr->sa_family = ai->ai_family = AF_INET;
((struct sockaddr_in *)(ai)->ai_addr)->sin_port = port;
((struct sockaddr_in *)(ai)->ai_addr)->sin_addr.s_addr = addr;
/* XXX: the following is not generally correct, but does what we want */
if (hints->ai_socktype)
ai->ai_socktype = hints->ai_socktype;
else
ai->ai_socktype = SOCK_STREAM;
if (hints->ai_protocol)
ai->ai_protocol = hints->ai_protocol;
return (ai);
}
int
getaddrinfo(const char *hostname, const char *servname,
const struct addrinfo *hints, struct addrinfo **res)
{
struct hostent *hp;
struct servent *sp;
struct in_addr in;
int i;
long int port;
u_long addr;
port = 0;
if (servname != NULL) {
char *cp;
port = strtol(servname, &cp, 10);
if (port > 0 && port <= 65535 && *cp == '\0')
port = htons(port);
else if ((sp = getservbyname(servname, NULL)) != NULL)
port = sp->s_port;
else
port = 0;
}
if (hints && hints->ai_flags & AI_PASSIVE) {
addr = htonl(0x00000000);
if (hostname && inet_aton(hostname, &in) != 0)
addr = in.s_addr;
*res = malloc_ai(port, addr, hints);
if (*res == NULL)
return (EAI_MEMORY);
return (0);
}
if (!hostname) {
*res = malloc_ai(port, htonl(0x7f000001), hints);
if (*res == NULL)
return (EAI_MEMORY);
return (0);
}
if (inet_aton(hostname, &in)) {
*res = malloc_ai(port, in.s_addr, hints);
if (*res == NULL)
return (EAI_MEMORY);
return (0);
}
/* Don't try DNS if AI_NUMERICHOST is set */
if (hints && hints->ai_flags & AI_NUMERICHOST)
return (EAI_NONAME);
hp = gethostbyname(hostname);
if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) {
struct addrinfo *cur, *prev;
cur = prev = *res = NULL;
for (i = 0; hp->h_addr_list[i]; i++) {
struct in_addr *in = (struct in_addr *)hp->h_addr_list[i];
cur = malloc_ai(port, in->s_addr, hints);
if (cur == NULL) {
if (*res != NULL)
freeaddrinfo(*res);
return (EAI_MEMORY);
}
if (prev)
prev->ai_next = cur;
else
*res = cur;
prev = cur;
}
return (0);
}
return (EAI_NODATA);
}
#endif /* !HAVE_GETADDRINFO */

174
external/unbound/compat/fake-rfc2553.h vendored Normal file
View File

@ -0,0 +1,174 @@
/* From openssh 4.3p2 filename openbsd-compat/fake-rfc2553.h */
/*
* Copyright (C) 2000-2003 Damien Miller. All rights reserved.
* Copyright (C) 1999 WIDE Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Pseudo-implementation of RFC2553 name / address resolution functions
*
* But these functions are not implemented correctly. The minimum subset
* is implemented for ssh use only. For example, this routine assumes
* that ai_family is AF_INET. Don't use it for another purpose.
*/
#ifndef _FAKE_RFC2553_H
#define _FAKE_RFC2553_H
#include <config.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <limits.h>
/*
* First, socket and INET6 related definitions
*/
#ifndef HAVE_STRUCT_SOCKADDR_STORAGE
# define _SS_MAXSIZE 128 /* Implementation specific max size */
# define _SS_PADSIZE (_SS_MAXSIZE - sizeof (struct sockaddr))
struct sockaddr_storage {
struct sockaddr ss_sa;
char __ss_pad2[_SS_PADSIZE];
};
# define ss_family ss_sa.sa_family
#endif /* !HAVE_STRUCT_SOCKADDR_STORAGE */
#ifndef IN6_IS_ADDR_LOOPBACK
# define IN6_IS_ADDR_LOOPBACK(a) \
(((uint32_t *)(a))[0] == 0 && ((uint32_t *)(a))[1] == 0 && \
((uint32_t *)(a))[2] == 0 && ((uint32_t *)(a))[3] == htonl(1))
#endif /* !IN6_IS_ADDR_LOOPBACK */
#ifndef HAVE_STRUCT_IN6_ADDR
struct in6_addr {
uint8_t s6_addr[16];
};
#endif /* !HAVE_STRUCT_IN6_ADDR */
#ifndef HAVE_STRUCT_SOCKADDR_IN6
struct sockaddr_in6 {
unsigned short sin6_family;
uint16_t sin6_port;
uint32_t sin6_flowinfo;
struct in6_addr sin6_addr;
};
#endif /* !HAVE_STRUCT_SOCKADDR_IN6 */
#ifndef AF_INET6
/* Define it to something that should never appear */
#define AF_INET6 AF_MAX
#endif
/*
* Next, RFC2553 name / address resolution API
*/
#ifndef NI_NUMERICHOST
# define NI_NUMERICHOST (1)
#endif
#ifndef NI_NAMEREQD
# define NI_NAMEREQD (1<<1)
#endif
#ifndef NI_NUMERICSERV
# define NI_NUMERICSERV (1<<2)
#endif
#ifndef AI_PASSIVE
# define AI_PASSIVE (1)
#endif
#ifndef AI_CANONNAME
# define AI_CANONNAME (1<<1)
#endif
#ifndef AI_NUMERICHOST
# define AI_NUMERICHOST (1<<2)
#endif
#ifndef NI_MAXSERV
# define NI_MAXSERV 32
#endif /* !NI_MAXSERV */
#ifndef NI_MAXHOST
# define NI_MAXHOST 1025
#endif /* !NI_MAXHOST */
#ifndef INT_MAX
#define INT_MAX 0xffffffff
#endif
#ifndef EAI_NODATA
# define EAI_NODATA (INT_MAX - 1)
#endif
#ifndef EAI_MEMORY
# define EAI_MEMORY (INT_MAX - 2)
#endif
#ifndef EAI_NONAME
# define EAI_NONAME (INT_MAX - 3)
#endif
#ifndef EAI_SYSTEM
# define EAI_SYSTEM (INT_MAX - 4)
#endif
#ifndef HAVE_STRUCT_ADDRINFO
struct addrinfo {
int ai_flags; /* AI_PASSIVE, AI_CANONNAME */
int ai_family; /* PF_xxx */
int ai_socktype; /* SOCK_xxx */
int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
size_t ai_addrlen; /* length of ai_addr */
char *ai_canonname; /* canonical name for hostname */
struct sockaddr *ai_addr; /* binary address */
struct addrinfo *ai_next; /* next structure in linked list */
};
#endif /* !HAVE_STRUCT_ADDRINFO */
#ifndef HAVE_GETADDRINFO
#ifdef getaddrinfo
# undef getaddrinfo
#endif
#define getaddrinfo(a,b,c,d) (getaddrinfo_unbound(a,b,c,d))
int getaddrinfo(const char *, const char *,
const struct addrinfo *, struct addrinfo **);
#endif /* !HAVE_GETADDRINFO */
#if !defined(HAVE_GAI_STRERROR) && !defined(HAVE_CONST_GAI_STRERROR_PROTO)
#define gai_strerror(a) (gai_strerror_unbound(a))
char *gai_strerror(int);
#endif /* !HAVE_GAI_STRERROR */
#ifndef HAVE_FREEADDRINFO
#define freeaddrinfo(a) (freeaddrinfo_unbound(a))
void freeaddrinfo(struct addrinfo *);
#endif /* !HAVE_FREEADDRINFO */
#ifndef HAVE_GETNAMEINFO
#define getnameinfo(a,b,c,d,e,f,g) (getnameinfo_unbound(a,b,c,d,e,f,g))
int getnameinfo(const struct sockaddr *, size_t, char *, size_t,
char *, size_t, int);
#endif /* !HAVE_GETNAMEINFO */
#endif /* !_FAKE_RFC2553_H */

View File

@ -0,0 +1,504 @@
/* $OpenBSD: getentropy_linux.c,v 1.20 2014/07/12 15:43:49 beck Exp $ */
/*
* Copyright (c) 2014 Theo de Raadt <deraadt@openbsd.org>
* Copyright (c) 2014 Bob Beck <beck@obtuse.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "config.h"
/*
#define _POSIX_C_SOURCE 199309L
#define _GNU_SOURCE 1
*/
#include <sys/types.h>
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#ifdef HAVE_SYS_SYSCTL_H
#include <sys/sysctl.h>
#endif
#include <sys/statvfs.h>
#include <sys/socket.h>
#include <sys/mount.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <termios.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <openssl/sha.h>
#include <linux/random.h>
#include <linux/sysctl.h>
#ifdef HAVE_GETAUXVAL
#include <sys/auxv.h>
#endif
#include <sys/vfs.h>
#define REPEAT 5
#define min(a, b) (((a) < (b)) ? (a) : (b))
#define HX(a, b) \
do { \
if ((a)) \
HD(errno); \
else \
HD(b); \
} while (0)
#define HR(x, l) (SHA512_Update(&ctx, (char *)(x), (l)))
#define HD(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (x)))
#define HF(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (void*)))
int getentropy(void *buf, size_t len);
#ifdef CAN_REFERENCE_MAIN
extern int main(int, char *argv[]);
#endif
static int gotdata(char *buf, size_t len);
static int getentropy_urandom(void *buf, size_t len);
#ifdef CTL_MAXNAME
static int getentropy_sysctl(void *buf, size_t len);
#endif
static int getentropy_fallback(void *buf, size_t len);
int
getentropy(void *buf, size_t len)
{
int ret = -1;
if (len > 256) {
errno = EIO;
return -1;
}
/*
* Try to get entropy with /dev/urandom
*
* This can fail if the process is inside a chroot or if file
* descriptors are exhausted.
*/
ret = getentropy_urandom(buf, len);
if (ret != -1)
return (ret);
#ifdef CTL_MAXNAME
/*
* Try to use sysctl CTL_KERN, KERN_RANDOM, RANDOM_UUID.
* sysctl is a failsafe API, so it guarantees a result. This
* should work inside a chroot, or when file descriptors are
* exhuasted.
*
* However this can fail if the Linux kernel removes support
* for sysctl. Starting in 2007, there have been efforts to
* deprecate the sysctl API/ABI, and push callers towards use
* of the chroot-unavailable fd-using /proc mechanism --
* essentially the same problems as /dev/urandom.
*
* Numerous setbacks have been encountered in their deprecation
* schedule, so as of June 2014 the kernel ABI still exists on
* most Linux architectures. The sysctl() stub in libc is missing
* on some systems. There are also reports that some kernels
* spew messages to the console.
*/
ret = getentropy_sysctl(buf, len);
if (ret != -1)
return (ret);
#endif /* CTL_MAXNAME */
/*
* Entropy collection via /dev/urandom and sysctl have failed.
*
* No other API exists for collecting entropy. See the large
* comment block above.
*
* We have very few options:
* - Even syslog_r is unsafe to call at this low level, so
* there is no way to alert the user or program.
* - Cannot call abort() because some systems have unsafe
* corefiles.
* - Could raise(SIGKILL) resulting in silent program termination.
* - Return EIO, to hint that arc4random's stir function
* should raise(SIGKILL)
* - Do the best under the circumstances....
*
* This code path exists to bring light to the issue that Linux
* does not provide a failsafe API for entropy collection.
*
* We hope this demonstrates that Linux should either retain their
* sysctl ABI, or consider providing a new failsafe API which
* works in a chroot or when file descriptors are exhausted.
*/
#undef FAIL_INSTEAD_OF_TRYING_FALLBACK
#ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
raise(SIGKILL);
#endif
ret = getentropy_fallback(buf, len);
if (ret != -1)
return (ret);
errno = EIO;
return (ret);
}
/*
* Basic sanity checking; wish we could do better.
*/
static int
gotdata(char *buf, size_t len)
{
char any_set = 0;
size_t i;
for (i = 0; i < len; ++i)
any_set |= buf[i];
if (any_set == 0)
return -1;
return 0;
}
static int
getentropy_urandom(void *buf, size_t len)
{
struct stat st;
size_t i;
int fd, cnt, flags;
int save_errno = errno;
start:
flags = O_RDONLY;
#ifdef O_NOFOLLOW
flags |= O_NOFOLLOW;
#endif
#ifdef O_CLOEXEC
flags |= O_CLOEXEC;
#endif
fd = open("/dev/urandom", flags, 0);
if (fd == -1) {
if (errno == EINTR)
goto start;
goto nodevrandom;
}
#ifndef O_CLOEXEC
fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
#endif
/* Lightly verify that the device node looks sane */
if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode)) {
close(fd);
goto nodevrandom;
}
if (ioctl(fd, RNDGETENTCNT, &cnt) == -1) {
close(fd);
goto nodevrandom;
}
for (i = 0; i < len; ) {
size_t wanted = len - i;
ssize_t ret = read(fd, (char*)buf + i, wanted);
if (ret == -1) {
if (errno == EAGAIN || errno == EINTR)
continue;
close(fd);
goto nodevrandom;
}
i += ret;
}
close(fd);
if (gotdata(buf, len) == 0) {
errno = save_errno;
return 0; /* satisfied */
}
nodevrandom:
errno = EIO;
return -1;
}
#ifdef CTL_MAXNAME
static int
getentropy_sysctl(void *buf, size_t len)
{
static int mib[] = { CTL_KERN, KERN_RANDOM, RANDOM_UUID };
size_t i;
int save_errno = errno;
for (i = 0; i < len; ) {
size_t chunk = min(len - i, 16);
/* SYS__sysctl because some systems already removed sysctl() */
struct __sysctl_args args = {
.name = mib,
.nlen = 3,
.oldval = buf + i,
.oldlenp = &chunk,
};
if (syscall(SYS__sysctl, &args) != 0)
goto sysctlfailed;
i += chunk;
}
if (gotdata(buf, len) == 0) {
errno = save_errno;
return (0); /* satisfied */
}
sysctlfailed:
errno = EIO;
return -1;
}
#endif /* CTL_MAXNAME */
static int cl[] = {
CLOCK_REALTIME,
#ifdef CLOCK_MONOTONIC
CLOCK_MONOTONIC,
#endif
#ifdef CLOCK_MONOTONIC_RAW
CLOCK_MONOTONIC_RAW,
#endif
#ifdef CLOCK_TAI
CLOCK_TAI,
#endif
#ifdef CLOCK_VIRTUAL
CLOCK_VIRTUAL,
#endif
#ifdef CLOCK_UPTIME
CLOCK_UPTIME,
#endif
#ifdef CLOCK_PROCESS_CPUTIME_ID
CLOCK_PROCESS_CPUTIME_ID,
#endif
#ifdef CLOCK_THREAD_CPUTIME_ID
CLOCK_THREAD_CPUTIME_ID,
#endif
};
static int
getentropy_fallback(void *buf, size_t len)
{
uint8_t results[SHA512_DIGEST_LENGTH];
int save_errno = errno, e, pgs = getpagesize(), faster = 0, repeat;
static int cnt;
struct timespec ts;
struct timeval tv;
struct rusage ru;
sigset_t sigset;
struct stat st;
SHA512_CTX ctx;
static pid_t lastpid;
pid_t pid;
size_t i, ii, m;
char *p;
pid = getpid();
if (lastpid == pid) {
faster = 1;
repeat = 2;
} else {
faster = 0;
lastpid = pid;
repeat = REPEAT;
}
for (i = 0; i < len; ) {
int j;
SHA512_Init(&ctx);
for (j = 0; j < repeat; j++) {
HX((e = gettimeofday(&tv, NULL)) == -1, tv);
if (e != -1) {
cnt += (int)tv.tv_sec;
cnt += (int)tv.tv_usec;
}
for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]); ii++)
HX(clock_gettime(cl[ii], &ts) == -1, ts);
HX((pid = getpid()) == -1, pid);
HX((pid = getsid(pid)) == -1, pid);
HX((pid = getppid()) == -1, pid);
HX((pid = getpgid(0)) == -1, pid);
HX((e = getpriority(0, 0)) == -1, e);
if (!faster) {
ts.tv_sec = 0;
ts.tv_nsec = 1;
(void) nanosleep(&ts, NULL);
}
HX(sigpending(&sigset) == -1, sigset);
HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
sigset);
#ifdef CAN_REFERENCE_MAIN
HF(main); /* an addr in program */
#endif
HF(getentropy); /* an addr in this library */
HF(printf); /* an addr in libc */
p = (char *)&p;
HD(p); /* an addr on stack */
p = (char *)&errno;
HD(p); /* the addr of errno */
if (i == 0) {
struct sockaddr_storage ss;
struct statvfs stvfs;
struct termios tios;
struct statfs stfs;
socklen_t ssl;
off_t off;
/*
* Prime-sized mappings encourage fragmentation;
* thus exposing some address entropy.
*/
struct mm {
size_t npg;
void *p;
} mm[] = {
{ 17, MAP_FAILED }, { 3, MAP_FAILED },
{ 11, MAP_FAILED }, { 2, MAP_FAILED },
{ 5, MAP_FAILED }, { 3, MAP_FAILED },
{ 7, MAP_FAILED }, { 1, MAP_FAILED },
{ 57, MAP_FAILED }, { 3, MAP_FAILED },
{ 131, MAP_FAILED }, { 1, MAP_FAILED },
};
for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
HX(mm[m].p = mmap(NULL,
mm[m].npg * pgs,
PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANON, -1,
(off_t)0), mm[m].p);
if (mm[m].p != MAP_FAILED) {
size_t mo;
/* Touch some memory... */
p = mm[m].p;
mo = cnt %
(mm[m].npg * pgs - 1);
p[mo] = 1;
cnt += (int)((long)(mm[m].p)
/ pgs);
}
/* Check cnts and times... */
for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]);
ii++) {
HX((e = clock_gettime(cl[ii],
&ts)) == -1, ts);
if (e != -1)
cnt += (int)ts.tv_nsec;
}
HX((e = getrusage(RUSAGE_SELF,
&ru)) == -1, ru);
if (e != -1) {
cnt += (int)ru.ru_utime.tv_sec;
cnt += (int)ru.ru_utime.tv_usec;
}
}
for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
if (mm[m].p != MAP_FAILED)
munmap(mm[m].p, mm[m].npg * pgs);
mm[m].p = MAP_FAILED;
}
HX(stat(".", &st) == -1, st);
HX(statvfs(".", &stvfs) == -1, stvfs);
HX(statfs(".", &stfs) == -1, stfs);
HX(stat("/", &st) == -1, st);
HX(statvfs("/", &stvfs) == -1, stvfs);
HX(statfs("/", &stfs) == -1, stfs);
HX((e = fstat(0, &st)) == -1, st);
if (e == -1) {
if (S_ISREG(st.st_mode) ||
S_ISFIFO(st.st_mode) ||
S_ISSOCK(st.st_mode)) {
HX(fstatvfs(0, &stvfs) == -1,
stvfs);
HX(fstatfs(0, &stfs) == -1,
stfs);
HX((off = lseek(0, (off_t)0,
SEEK_CUR)) < 0, off);
}
if (S_ISCHR(st.st_mode)) {
HX(tcgetattr(0, &tios) == -1,
tios);
} else if (S_ISSOCK(st.st_mode)) {
memset(&ss, 0, sizeof ss);
ssl = sizeof(ss);
HX(getpeername(0,
(void *)&ss, &ssl) == -1,
ss);
}
}
HX((e = getrusage(RUSAGE_CHILDREN,
&ru)) == -1, ru);
if (e != -1) {
cnt += (int)ru.ru_utime.tv_sec;
cnt += (int)ru.ru_utime.tv_usec;
}
} else {
/* Subsequent hashes absorb previous result */
HD(results);
}
HX((e = gettimeofday(&tv, NULL)) == -1, tv);
if (e != -1) {
cnt += (int)tv.tv_sec;
cnt += (int)tv.tv_usec;
}
HD(cnt);
}
#ifdef AT_RANDOM
/* Not as random as you think but we take what we are given */
p = (char *) getauxval(AT_RANDOM);
if (p)
HR(p, 16);
#endif
#ifdef AT_SYSINFO_EHDR
p = (char *) getauxval(AT_SYSINFO_EHDR);
if (p)
HR(p, pgs);
#endif
#ifdef AT_BASE
p = (char *) getauxval(AT_BASE);
if (p)
HD(p);
#endif
SHA512_Final(results, &ctx);
memcpy((char*)buf + i, results, min(sizeof(results), len - i));
i += min(sizeof(results), len - i);
}
memset(results, 0, sizeof results);
if (gotdata(buf, len) == 0) {
errno = save_errno;
return 0; /* satisfied */
}
errno = EIO;
return -1;
}

432
external/unbound/compat/getentropy_osx.c vendored Normal file
View File

@ -0,0 +1,432 @@
/* $OpenBSD: getentropy_osx.c,v 1.3 2014/07/12 14:48:00 deraadt Exp $ */
/*
* Copyright (c) 2014 Theo de Raadt <deraadt@openbsd.org>
* Copyright (c) 2014 Bob Beck <beck@obtuse.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "config.h"
#include <sys/types.h>
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <sys/sysctl.h>
#include <sys/statvfs.h>
#include <sys/socket.h>
#include <sys/mount.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <termios.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <mach/mach_time.h>
#include <mach/mach_host.h>
#include <mach/host_info.h>
#include <sys/socketvar.h>
#include <sys/vmmeter.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/ip_var.h>
#include <netinet/tcp_var.h>
#include <netinet/udp_var.h>
#include <CommonCrypto/CommonDigest.h>
#define SHA512_Update(a, b, c) (CC_SHA512_Update((a), (b), (c)))
#define SHA512_Init(xxx) (CC_SHA512_Init((xxx)))
#define SHA512_Final(xxx, yyy) (CC_SHA512_Final((xxx), (yyy)))
#define SHA512_CTX CC_SHA512_CTX
#define SHA512_DIGEST_LENGTH CC_SHA512_DIGEST_LENGTH
#define REPEAT 5
#define min(a, b) (((a) < (b)) ? (a) : (b))
#define HX(a, b) \
do { \
if ((a)) \
HD(errno); \
else \
HD(b); \
} while (0)
#define HR(x, l) (SHA512_Update(&ctx, (char *)(x), (l)))
#define HD(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (x)))
#define HF(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (void*)))
int getentropy(void *buf, size_t len);
#ifdef CAN_REFERENCE_MAIN
extern int main(int, char *argv[]);
#endif
static int gotdata(char *buf, size_t len);
static int getentropy_urandom(void *buf, size_t len);
static int getentropy_fallback(void *buf, size_t len);
int
getentropy(void *buf, size_t len)
{
int ret = -1;
if (len > 256) {
errno = EIO;
return -1;
}
/*
* Try to get entropy with /dev/urandom
*
* This can fail if the process is inside a chroot or if file
* descriptors are exhausted.
*/
ret = getentropy_urandom(buf, len);
if (ret != -1)
return (ret);
/*
* Entropy collection via /dev/urandom and sysctl have failed.
*
* No other API exists for collecting entropy, and we have
* no failsafe way to get it on OSX that is not sensitive
* to resource exhaustion.
*
* We have very few options:
* - Even syslog_r is unsafe to call at this low level, so
* there is no way to alert the user or program.
* - Cannot call abort() because some systems have unsafe
* corefiles.
* - Could raise(SIGKILL) resulting in silent program termination.
* - Return EIO, to hint that arc4random's stir function
* should raise(SIGKILL)
* - Do the best under the circumstances....
*
* This code path exists to bring light to the issue that OSX
* does not provide a failsafe API for entropy collection.
*
* We hope this demonstrates that OSX should consider
* providing a new failsafe API which works in a chroot or
* when file descriptors are exhausted.
*/
#undef FAIL_INSTEAD_OF_TRYING_FALLBACK
#ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
raise(SIGKILL);
#endif
ret = getentropy_fallback(buf, len);
if (ret != -1)
return (ret);
errno = EIO;
return (ret);
}
/*
* Basic sanity checking; wish we could do better.
*/
static int
gotdata(char *buf, size_t len)
{
char any_set = 0;
size_t i;
for (i = 0; i < len; ++i)
any_set |= buf[i];
if (any_set == 0)
return -1;
return 0;
}
static int
getentropy_urandom(void *buf, size_t len)
{
struct stat st;
size_t i;
int fd, flags;
int save_errno = errno;
start:
flags = O_RDONLY;
#ifdef O_NOFOLLOW
flags |= O_NOFOLLOW;
#endif
#ifdef O_CLOEXEC
flags |= O_CLOEXEC;
#endif
fd = open("/dev/urandom", flags, 0);
if (fd == -1) {
if (errno == EINTR)
goto start;
goto nodevrandom;
}
#ifndef O_CLOEXEC
fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
#endif
/* Lightly verify that the device node looks sane */
if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode)) {
close(fd);
goto nodevrandom;
}
for (i = 0; i < len; ) {
size_t wanted = len - i;
ssize_t ret = read(fd, (char*)buf + i, wanted);
if (ret == -1) {
if (errno == EAGAIN || errno == EINTR)
continue;
close(fd);
goto nodevrandom;
}
i += ret;
}
close(fd);
if (gotdata(buf, len) == 0) {
errno = save_errno;
return 0; /* satisfied */
}
nodevrandom:
errno = EIO;
return -1;
}
static int tcpmib[] = { CTL_NET, AF_INET, IPPROTO_TCP, TCPCTL_STATS };
static int udpmib[] = { CTL_NET, AF_INET, IPPROTO_UDP, UDPCTL_STATS };
static int ipmib[] = { CTL_NET, AF_INET, IPPROTO_IP, IPCTL_STATS };
static int kmib[] = { CTL_KERN, KERN_USRSTACK };
static int hwmib[] = { CTL_HW, HW_USERMEM };
static int
getentropy_fallback(void *buf, size_t len)
{
uint8_t results[SHA512_DIGEST_LENGTH];
int save_errno = errno, e, pgs = getpagesize(), faster = 0, repeat;
static int cnt;
struct timespec ts;
struct timeval tv;
struct rusage ru;
sigset_t sigset;
struct stat st;
SHA512_CTX ctx;
static pid_t lastpid;
pid_t pid;
size_t i, ii, m;
char *p;
struct tcpstat tcpstat;
struct udpstat udpstat;
struct ipstat ipstat;
u_int64_t mach_time;
unsigned int idata;
void *addr;
pid = getpid();
if (lastpid == pid) {
faster = 1;
repeat = 2;
} else {
faster = 0;
lastpid = pid;
repeat = REPEAT;
}
for (i = 0; i < len; ) {
int j;
SHA512_Init(&ctx);
for (j = 0; j < repeat; j++) {
HX((e = gettimeofday(&tv, NULL)) == -1, tv);
if (e != -1) {
cnt += (int)tv.tv_sec;
cnt += (int)tv.tv_usec;
}
mach_time = mach_absolute_time();
HD(mach_time);
ii = sizeof(addr);
HX(sysctl(kmib, sizeof(kmib) / sizeof(kmib[0]),
&addr, &ii, NULL, 0) == -1, addr);
ii = sizeof(idata);
HX(sysctl(hwmib, sizeof(hwmib) / sizeof(hwmib[0]),
&idata, &ii, NULL, 0) == -1, idata);
ii = sizeof(tcpstat);
HX(sysctl(tcpmib, sizeof(tcpmib) / sizeof(tcpmib[0]),
&tcpstat, &ii, NULL, 0) == -1, tcpstat);
ii = sizeof(udpstat);
HX(sysctl(udpmib, sizeof(udpmib) / sizeof(udpmib[0]),
&udpstat, &ii, NULL, 0) == -1, udpstat);
ii = sizeof(ipstat);
HX(sysctl(ipmib, sizeof(ipmib) / sizeof(ipmib[0]),
&ipstat, &ii, NULL, 0) == -1, ipstat);
HX((pid = getpid()) == -1, pid);
HX((pid = getsid(pid)) == -1, pid);
HX((pid = getppid()) == -1, pid);
HX((pid = getpgid(0)) == -1, pid);
HX((e = getpriority(0, 0)) == -1, e);
if (!faster) {
ts.tv_sec = 0;
ts.tv_nsec = 1;
(void) nanosleep(&ts, NULL);
}
HX(sigpending(&sigset) == -1, sigset);
HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
sigset);
#ifdef CAN_REFERENCE_MAIN
HF(main); /* an addr in program */
#endif
HF(getentropy); /* an addr in this library */
HF(printf); /* an addr in libc */
p = (char *)&p;
HD(p); /* an addr on stack */
p = (char *)&errno;
HD(p); /* the addr of errno */
if (i == 0) {
struct sockaddr_storage ss;
struct statvfs stvfs;
struct termios tios;
struct statfs stfs;
socklen_t ssl;
off_t off;
/*
* Prime-sized mappings encourage fragmentation;
* thus exposing some address entropy.
*/
struct mm {
size_t npg;
void *p;
} mm[] = {
{ 17, MAP_FAILED }, { 3, MAP_FAILED },
{ 11, MAP_FAILED }, { 2, MAP_FAILED },
{ 5, MAP_FAILED }, { 3, MAP_FAILED },
{ 7, MAP_FAILED }, { 1, MAP_FAILED },
{ 57, MAP_FAILED }, { 3, MAP_FAILED },
{ 131, MAP_FAILED }, { 1, MAP_FAILED },
};
for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
HX(mm[m].p = mmap(NULL,
mm[m].npg * pgs,
PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANON, -1,
(off_t)0), mm[m].p);
if (mm[m].p != MAP_FAILED) {
size_t mo;
/* Touch some memory... */
p = mm[m].p;
mo = cnt %
(mm[m].npg * pgs - 1);
p[mo] = 1;
cnt += (int)((long)(mm[m].p)
/ pgs);
}
/* Check cnts and times... */
mach_time = mach_absolute_time();
HD(mach_time);
cnt += (int)mach_time;
HX((e = getrusage(RUSAGE_SELF,
&ru)) == -1, ru);
if (e != -1) {
cnt += (int)ru.ru_utime.tv_sec;
cnt += (int)ru.ru_utime.tv_usec;
}
}
for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
if (mm[m].p != MAP_FAILED)
munmap(mm[m].p, mm[m].npg * pgs);
mm[m].p = MAP_FAILED;
}
HX(stat(".", &st) == -1, st);
HX(statvfs(".", &stvfs) == -1, stvfs);
HX(statfs(".", &stfs) == -1, stfs);
HX(stat("/", &st) == -1, st);
HX(statvfs("/", &stvfs) == -1, stvfs);
HX(statfs("/", &stfs) == -1, stfs);
HX((e = fstat(0, &st)) == -1, st);
if (e == -1) {
if (S_ISREG(st.st_mode) ||
S_ISFIFO(st.st_mode) ||
S_ISSOCK(st.st_mode)) {
HX(fstatvfs(0, &stvfs) == -1,
stvfs);
HX(fstatfs(0, &stfs) == -1,
stfs);
HX((off = lseek(0, (off_t)0,
SEEK_CUR)) < 0, off);
}
if (S_ISCHR(st.st_mode)) {
HX(tcgetattr(0, &tios) == -1,
tios);
} else if (S_ISSOCK(st.st_mode)) {
memset(&ss, 0, sizeof ss);
ssl = sizeof(ss);
HX(getpeername(0,
(void *)&ss, &ssl) == -1,
ss);
}
}
HX((e = getrusage(RUSAGE_CHILDREN,
&ru)) == -1, ru);
if (e != -1) {
cnt += (int)ru.ru_utime.tv_sec;
cnt += (int)ru.ru_utime.tv_usec;
}
} else {
/* Subsequent hashes absorb previous result */
HD(results);
}
HX((e = gettimeofday(&tv, NULL)) == -1, tv);
if (e != -1) {
cnt += (int)tv.tv_sec;
cnt += (int)tv.tv_usec;
}
HD(cnt);
}
SHA512_Final(results, &ctx);
memcpy((char*)buf + i, results, min(sizeof(results), len - i));
i += min(sizeof(results), len - i);
}
memset(results, 0, sizeof results);
if (gotdata(buf, len) == 0) {
errno = save_errno;
return 0; /* satisfied */
}
errno = EIO;
return -1;
}

View File

@ -0,0 +1,435 @@
/* $OpenBSD: getentropy_solaris.c,v 1.3 2014/07/12 14:46:31 deraadt Exp $ */
/*
* Copyright (c) 2014 Theo de Raadt <deraadt@openbsd.org>
* Copyright (c) 2014 Bob Beck <beck@obtuse.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "config.h"
#include <sys/types.h>
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <sys/statvfs.h>
#include <sys/socket.h>
#include <sys/mount.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <termios.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <sys/sha2.h>
#define SHA512_Init SHA512Init
#define SHA512_Update SHA512Update
#define SHA512_Final SHA512Final
#include <sys/vfs.h>
#include <sys/statfs.h>
#include <sys/loadavg.h>
#define REPEAT 5
#define min(a, b) (((a) < (b)) ? (a) : (b))
#define HX(a, b) \
do { \
if ((a)) \
HD(errno); \
else \
HD(b); \
} while (0)
#define HR(x, l) (SHA512_Update(&ctx, (char *)(x), (l)))
#define HD(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (x)))
#define HF(x) (SHA512_Update(&ctx, (char *)&(x), sizeof (void*)))
int getentropy(void *buf, size_t len);
#ifdef CAN_REFERENCE_MAIN
extern int main(int, char *argv[]);
#endif
static int gotdata(char *buf, size_t len);
static int getentropy_urandom(void *buf, size_t len, const char *path,
int devfscheck);
static int getentropy_fallback(void *buf, size_t len);
int
getentropy(void *buf, size_t len)
{
int ret = -1;
if (len > 256) {
errno = EIO;
return -1;
}
/*
* Try to get entropy with /dev/urandom
*
* Solaris provides /dev/urandom as a symbolic link to
* /devices/pseudo/random@0:urandom which is provided by
* a devfs filesystem. Best practice is to use O_NOFOLLOW,
* so we must try the unpublished name directly.
*
* This can fail if the process is inside a chroot which lacks
* the devfs mount, or if file descriptors are exhausted.
*/
ret = getentropy_urandom(buf, len,
"/devices/pseudo/random@0:urandom", 1);
if (ret != -1)
return (ret);
/*
* Unfortunately, chroot spaces on Solaris are sometimes setup
* with direct device node of the well-known /dev/urandom name
* (perhaps to avoid dragging all of devfs into the space).
*
* This can fail if the process is inside a chroot or if file
* descriptors are exhausted.
*/
ret = getentropy_urandom(buf, len, "/dev/urandom", 0);
if (ret != -1)
return (ret);
/*
* Entropy collection via /dev/urandom has failed.
*
* No other API exists for collecting entropy, and we have
* no failsafe way to get it on Solaris that is not sensitive
* to resource exhaustion.
*
* We have very few options:
* - Even syslog_r is unsafe to call at this low level, so
* there is no way to alert the user or program.
* - Cannot call abort() because some systems have unsafe
* corefiles.
* - Could raise(SIGKILL) resulting in silent program termination.
* - Return EIO, to hint that arc4random's stir function
* should raise(SIGKILL)
* - Do the best under the circumstances....
*
* This code path exists to bring light to the issue that Solaris
* does not provide a failsafe API for entropy collection.
*
* We hope this demonstrates that Solaris should consider
* providing a new failsafe API which works in a chroot or
* when file descriptors are exhausted.
*/
#undef FAIL_INSTEAD_OF_TRYING_FALLBACK
#ifdef FAIL_INSTEAD_OF_TRYING_FALLBACK
raise(SIGKILL);
#endif
ret = getentropy_fallback(buf, len);
if (ret != -1)
return (ret);
errno = EIO;
return (ret);
}
/*
* Basic sanity checking; wish we could do better.
*/
static int
gotdata(char *buf, size_t len)
{
char any_set = 0;
size_t i;
for (i = 0; i < len; ++i)
any_set |= buf[i];
if (any_set == 0)
return -1;
return 0;
}
static int
getentropy_urandom(void *buf, size_t len, const char *path, int devfscheck)
{
struct stat st;
size_t i;
int fd, flags;
int save_errno = errno;
start:
flags = O_RDONLY;
#ifdef O_NOFOLLOW
flags |= O_NOFOLLOW;
#endif
#ifdef O_CLOEXEC
flags |= O_CLOEXEC;
#endif
fd = open(path, flags, 0);
if (fd == -1) {
if (errno == EINTR)
goto start;
goto nodevrandom;
}
#ifndef O_CLOEXEC
fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
#endif
/* Lightly verify that the device node looks sane */
if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode) ||
(devfscheck && (strcmp(st.st_fstype, "devfs") != 0))) {
close(fd);
goto nodevrandom;
}
for (i = 0; i < len; ) {
size_t wanted = len - i;
ssize_t ret = read(fd, (char*)buf + i, wanted);
if (ret == -1) {
if (errno == EAGAIN || errno == EINTR)
continue;
close(fd);
goto nodevrandom;
}
i += ret;
}
close(fd);
if (gotdata(buf, len) == 0) {
errno = save_errno;
return 0; /* satisfied */
}
nodevrandom:
errno = EIO;
return -1;
}
static const int cl[] = {
CLOCK_REALTIME,
#ifdef CLOCK_MONOTONIC
CLOCK_MONOTONIC,
#endif
#ifdef CLOCK_MONOTONIC_RAW
CLOCK_MONOTONIC_RAW,
#endif
#ifdef CLOCK_TAI
CLOCK_TAI,
#endif
#ifdef CLOCK_VIRTUAL
CLOCK_VIRTUAL,
#endif
#ifdef CLOCK_UPTIME
CLOCK_UPTIME,
#endif
#ifdef CLOCK_PROCESS_CPUTIME_ID
CLOCK_PROCESS_CPUTIME_ID,
#endif
#ifdef CLOCK_THREAD_CPUTIME_ID
CLOCK_THREAD_CPUTIME_ID,
#endif
};
static int
getentropy_fallback(void *buf, size_t len)
{
uint8_t results[SHA512_DIGEST_LENGTH];
int save_errno = errno, e, pgs = getpagesize(), faster = 0, repeat;
static int cnt;
struct timespec ts;
struct timeval tv;
double loadavg[3];
struct rusage ru;
sigset_t sigset;
struct stat st;
SHA512_CTX ctx;
static pid_t lastpid;
pid_t pid;
size_t i, ii, m;
char *p;
pid = getpid();
if (lastpid == pid) {
faster = 1;
repeat = 2;
} else {
faster = 0;
lastpid = pid;
repeat = REPEAT;
}
for (i = 0; i < len; ) {
int j;
SHA512_Init(&ctx);
for (j = 0; j < repeat; j++) {
HX((e = gettimeofday(&tv, NULL)) == -1, tv);
if (e != -1) {
cnt += (int)tv.tv_sec;
cnt += (int)tv.tv_usec;
}
for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]); ii++)
HX(clock_gettime(cl[ii], &ts) == -1, ts);
HX((pid = getpid()) == -1, pid);
HX((pid = getsid(pid)) == -1, pid);
HX((pid = getppid()) == -1, pid);
HX((pid = getpgid(0)) == -1, pid);
HX((e = getpriority(0, 0)) == -1, e);
HX((getloadavg(loadavg, 3) == -1), loadavg);
if (!faster) {
ts.tv_sec = 0;
ts.tv_nsec = 1;
(void) nanosleep(&ts, NULL);
}
HX(sigpending(&sigset) == -1, sigset);
HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
sigset);
#ifdef CAN_REFERENCE_MAIN
HF(main); /* an addr in program */
#endif
HF(getentropy); /* an addr in this library */
HF(printf); /* an addr in libc */
p = (char *)&p;
HD(p); /* an addr on stack */
p = (char *)&errno;
HD(p); /* the addr of errno */
if (i == 0) {
struct sockaddr_storage ss;
struct statvfs stvfs;
struct termios tios;
socklen_t ssl;
off_t off;
/*
* Prime-sized mappings encourage fragmentation;
* thus exposing some address entropy.
*/
struct mm {
size_t npg;
void *p;
} mm[] = {
{ 17, MAP_FAILED }, { 3, MAP_FAILED },
{ 11, MAP_FAILED }, { 2, MAP_FAILED },
{ 5, MAP_FAILED }, { 3, MAP_FAILED },
{ 7, MAP_FAILED }, { 1, MAP_FAILED },
{ 57, MAP_FAILED }, { 3, MAP_FAILED },
{ 131, MAP_FAILED }, { 1, MAP_FAILED },
};
for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
HX(mm[m].p = mmap(NULL,
mm[m].npg * pgs,
PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANON, -1,
(off_t)0), mm[m].p);
if (mm[m].p != MAP_FAILED) {
size_t mo;
/* Touch some memory... */
p = mm[m].p;
mo = cnt %
(mm[m].npg * pgs - 1);
p[mo] = 1;
cnt += (int)((long)(mm[m].p)
/ pgs);
}
/* Check cnts and times... */
for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]);
ii++) {
HX((e = clock_gettime(cl[ii],
&ts)) == -1, ts);
if (e != -1)
cnt += (int)ts.tv_nsec;
}
HX((e = getrusage(RUSAGE_SELF,
&ru)) == -1, ru);
if (e != -1) {
cnt += (int)ru.ru_utime.tv_sec;
cnt += (int)ru.ru_utime.tv_usec;
}
}
for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
if (mm[m].p != MAP_FAILED)
munmap(mm[m].p, mm[m].npg * pgs);
mm[m].p = MAP_FAILED;
}
HX(stat(".", &st) == -1, st);
HX(statvfs(".", &stvfs) == -1, stvfs);
HX(stat("/", &st) == -1, st);
HX(statvfs("/", &stvfs) == -1, stvfs);
HX((e = fstat(0, &st)) == -1, st);
if (e == -1) {
if (S_ISREG(st.st_mode) ||
S_ISFIFO(st.st_mode) ||
S_ISSOCK(st.st_mode)) {
HX(fstatvfs(0, &stvfs) == -1,
stvfs);
HX((off = lseek(0, (off_t)0,
SEEK_CUR)) < 0, off);
}
if (S_ISCHR(st.st_mode)) {
HX(tcgetattr(0, &tios) == -1,
tios);
} else if (S_ISSOCK(st.st_mode)) {
memset(&ss, 0, sizeof ss);
ssl = sizeof(ss);
HX(getpeername(0,
(void *)&ss, &ssl) == -1,
ss);
}
}
HX((e = getrusage(RUSAGE_CHILDREN,
&ru)) == -1, ru);
if (e != -1) {
cnt += (int)ru.ru_utime.tv_sec;
cnt += (int)ru.ru_utime.tv_usec;
}
} else {
/* Subsequent hashes absorb previous result */
HD(results);
}
HX((e = gettimeofday(&tv, NULL)) == -1, tv);
if (e != -1) {
cnt += (int)tv.tv_sec;
cnt += (int)tv.tv_usec;
}
HD(cnt);
}
SHA512_Final(results, &ctx);
memcpy((char*)buf + i, results, min(sizeof(results), len - i));
i += min(sizeof(results), len - i);
}
memset(results, 0, sizeof results);
if (gotdata(buf, len) == 0) {
errno = save_errno;
return 0; /* satisfied */
}
errno = EIO;
return -1;
}

View File

@ -0,0 +1,56 @@
/* $OpenBSD$ */
/*
* Copyright (c) 2014, Theo de Raadt <deraadt@openbsd.org>
* Copyright (c) 2014, Bob Beck <beck@obtuse.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <windows.h>
#include <errno.h>
#include <stdint.h>
#include <sys/types.h>
#include <wincrypt.h>
#include <process.h>
int getentropy(void *buf, size_t len);
/*
* On Windows, CryptGenRandom is supposed to be a well-seeded
* cryptographically strong random number generator.
*/
int
getentropy(void *buf, size_t len)
{
HCRYPTPROV provider;
if (len > 256) {
errno = EIO;
return -1;
}
if (CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT) != 0)
goto fail;
if (CryptGenRandom(provider, len, buf) != 0) {
CryptReleaseContext(provider, 0);
goto fail;
}
CryptReleaseContext(provider, 0);
return (0);
fail:
errno = EIO;
return (-1);
}

107
external/unbound/compat/gmtime_r.c vendored Normal file
View File

@ -0,0 +1,107 @@
/*
* Taken from FreeBSD src / lib / libc / stdtime / localtime.c 1.43 revision.
* localtime.c 7.78.
* tzfile.h 1.8
* adapted to be replacement gmtime_r.
*/
#include "config.h"
#ifdef HAVE_TIME_H
#include <time.h>
#endif
#define MONSPERYEAR 12
#define DAYSPERNYEAR 365
#define DAYSPERLYEAR 366
#define SECSPERMIN 60
#define SECSPERHOUR (60*60)
#define SECSPERDAY (24*60*60)
#define DAYSPERWEEK 7
#define TM_SUNDAY 0
#define TM_MONDAY 1
#define TM_TUESDAY 2
#define TM_WEDNESDAY 3
#define TM_THURSDAY 4
#define TM_FRIDAY 5
#define TM_SATURDAY 6
#define TM_YEAR_BASE 1900
#define EPOCH_YEAR 1970
#define EPOCH_WDAY TM_THURSDAY
#define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0))
static const int mon_lengths[2][MONSPERYEAR] = {
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
};
static const int year_lengths[2] = {
DAYSPERNYEAR, DAYSPERLYEAR
};
static void
timesub(timep, offset, tmp)
const time_t * const timep;
const long offset;
struct tm * const tmp;
{
long days;
long rem;
long y;
int yleap;
const int * ip;
days = *timep / SECSPERDAY;
rem = *timep % SECSPERDAY;
rem += (offset);
while (rem < 0) {
rem += SECSPERDAY;
--days;
}
while (rem >= SECSPERDAY) {
rem -= SECSPERDAY;
++days;
}
tmp->tm_hour = (int) (rem / SECSPERHOUR);
rem = rem % SECSPERHOUR;
tmp->tm_min = (int) (rem / SECSPERMIN);
/*
** A positive leap second requires a special
** representation. This uses "... ??:59:60" et seq.
*/
tmp->tm_sec = (int) (rem % SECSPERMIN) ;
tmp->tm_wday = (int) ((EPOCH_WDAY + days) % DAYSPERWEEK);
if (tmp->tm_wday < 0)
tmp->tm_wday += DAYSPERWEEK;
y = EPOCH_YEAR;
#define LEAPS_THRU_END_OF(y) ((y) / 4 - (y) / 100 + (y) / 400)
while (days < 0 || days >= (long) year_lengths[yleap = isleap(y)]) {
long newy;
newy = y + days / DAYSPERNYEAR;
if (days < 0)
--newy;
days -= (newy - y) * DAYSPERNYEAR +
LEAPS_THRU_END_OF(newy - 1) -
LEAPS_THRU_END_OF(y - 1);
y = newy;
}
tmp->tm_year = y - TM_YEAR_BASE;
tmp->tm_yday = (int) days;
ip = mon_lengths[yleap];
for (tmp->tm_mon = 0; days >= (long) ip[tmp->tm_mon]; ++(tmp->tm_mon))
days = days - (long) ip[tmp->tm_mon];
tmp->tm_mday = (int) (days + 1);
tmp->tm_isdst = 0;
}
/*
* Re-entrant version of gmtime.
*/
struct tm * gmtime_r(const time_t* timep, struct tm *tm)
{
timesub(timep, 0L, tm);
return tm;
}

182
external/unbound/compat/inet_aton.c vendored Normal file
View File

@ -0,0 +1,182 @@
/* From openssh4.3p2 compat/inet_aton.c */
/*
* Copyright (c) 1983, 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* -
* Portions Copyright (c) 1993 by Digital Equipment Corporation.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies, and that
* the name of Digital Equipment Corporation not be used in advertising or
* publicity pertaining to distribution of the document or software without
* specific, written prior permission.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
* CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
* -
* --Copyright--
*/
/* OPENBSD ORIGINAL: lib/libc/net/inet_addr.c */
#include <config.h>
#if !defined(HAVE_INET_ATON)
#include <sys/types.h>
#include <sys/param.h>
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include <ctype.h>
#if 0
/*
* Ascii internet address interpretation routine.
* The value returned is in network order.
*/
in_addr_t
inet_addr(const char *cp)
{
struct in_addr val;
if (inet_aton(cp, &val))
return (val.s_addr);
return (INADDR_NONE);
}
#endif
/*
* Check whether "cp" is a valid ascii representation
* of an Internet address and convert to a binary address.
* Returns 1 if the address is valid, 0 if not.
* This replaces inet_addr, the return value from which
* cannot distinguish between failure and a local broadcast address.
*/
int
inet_aton(const char *cp, struct in_addr *addr)
{
uint32_t val;
int base, n;
char c;
unsigned int parts[4];
unsigned int *pp = parts;
c = *cp;
for (;;) {
/*
* Collect number up to ``.''.
* Values are specified as for C:
* 0x=hex, 0=octal, isdigit=decimal.
*/
if (!isdigit(c))
return (0);
val = 0; base = 10;
if (c == '0') {
c = *++cp;
if (c == 'x' || c == 'X')
base = 16, c = *++cp;
else
base = 8;
}
for (;;) {
if (isascii(c) && isdigit(c)) {
val = (val * base) + (c - '0');
c = *++cp;
} else if (base == 16 && isascii(c) && isxdigit(c)) {
val = (val << 4) |
(c + 10 - (islower(c) ? 'a' : 'A'));
c = *++cp;
} else
break;
}
if (c == '.') {
/*
* Internet format:
* a.b.c.d
* a.b.c (with c treated as 16 bits)
* a.b (with b treated as 24 bits)
*/
if (pp >= parts + 3)
return (0);
*pp++ = val;
c = *++cp;
} else
break;
}
/*
* Check for trailing characters.
*/
if (c != '\0' && (!isascii(c) || !isspace(c)))
return (0);
/*
* Concoct the address according to
* the number of parts specified.
*/
n = pp - parts + 1;
switch (n) {
case 0:
return (0); /* initial nondigit */
case 1: /* a -- 32 bits */
break;
case 2: /* a.b -- 8.24 bits */
if ((val > 0xffffff) || (parts[0] > 0xff))
return (0);
val |= parts[0] << 24;
break;
case 3: /* a.b.c -- 8.8.16 bits */
if ((val > 0xffff) || (parts[0] > 0xff) || (parts[1] > 0xff))
return (0);
val |= (parts[0] << 24) | (parts[1] << 16);
break;
case 4: /* a.b.c.d -- 8.8.8.8 bits */
if ((val > 0xff) || (parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff))
return (0);
val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
break;
}
if (addr)
addr->s_addr = htonl(val);
return (1);
}
#endif /* !defined(HAVE_INET_ATON) */

218
external/unbound/compat/inet_ntop.c vendored Normal file
View File

@ -0,0 +1,218 @@
/* From openssh 4.3p2 compat/inet_ntop.c */
/* Copyright (c) 1996 by Internet Software Consortium.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
* ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
* CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
*/
/* OPENBSD ORIGINAL: lib/libc/net/inet_ntop.c */
#include <config.h>
#ifndef HAVE_INET_NTOP
#include <sys/param.h>
#include <sys/types.h>
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#include <string.h>
#include <errno.h>
#include <stdio.h>
#ifndef IN6ADDRSZ
#define IN6ADDRSZ 16 /* IPv6 T_AAAA */
#endif
#ifndef INT16SZ
#define INT16SZ 2 /* for systems without 16-bit ints */
#endif
/*
* WARNING: Don't even consider trying to compile this on a system where
* sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX.
*/
static const char *inet_ntop4(const u_char *src, char *dst, size_t size);
static const char *inet_ntop6(const u_char *src, char *dst, size_t size);
/* char *
* inet_ntop(af, src, dst, size)
* convert a network format address to presentation format.
* return:
* pointer to presentation format address (`dst'), or NULL (see errno).
* author:
* Paul Vixie, 1996.
*/
const char *
inet_ntop(int af, const void *src, char *dst, size_t size)
{
switch (af) {
case AF_INET:
return (inet_ntop4(src, dst, size));
case AF_INET6:
return (inet_ntop6(src, dst, size));
default:
#ifdef EAFNOSUPPORT
errno = EAFNOSUPPORT;
#else
errno = ENOSYS;
#endif
return (NULL);
}
/* NOTREACHED */
}
/* const char *
* inet_ntop4(src, dst, size)
* format an IPv4 address, more or less like inet_ntoa()
* return:
* `dst' (as a const)
* notes:
* (1) uses no statics
* (2) takes a u_char* not an in_addr as input
* author:
* Paul Vixie, 1996.
*/
static const char *
inet_ntop4(const u_char *src, char *dst, size_t size)
{
static const char fmt[] = "%u.%u.%u.%u";
char tmp[sizeof "255.255.255.255"];
int l;
l = snprintf(tmp, size, fmt, src[0], src[1], src[2], src[3]);
if (l <= 0 || l >= (int)size) {
errno = ENOSPC;
return (NULL);
}
strlcpy(dst, tmp, size);
return (dst);
}
/* const char *
* inet_ntop6(src, dst, size)
* convert IPv6 binary address into presentation (printable) format
* author:
* Paul Vixie, 1996.
*/
static const char *
inet_ntop6(const u_char *src, char *dst, size_t size)
{
/*
* Note that int32_t and int16_t need only be "at least" large enough
* to contain a value of the specified size. On some systems, like
* Crays, there is no such thing as an integer variable with 16 bits.
* Keep this in mind if you think this function should have been coded
* to use pointer overlays. All the world's not a VAX.
*/
char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"];
char *tp, *ep;
struct { int base, len; } best, cur;
u_int words[IN6ADDRSZ / INT16SZ];
int i;
int advance;
/*
* Preprocess:
* Copy the input (bytewise) array into a wordwise array.
* Find the longest run of 0x00's in src[] for :: shorthanding.
*/
memset(words, '\0', sizeof words);
for (i = 0; i < IN6ADDRSZ; i++)
words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3));
best.base = -1;
best.len = 0;
cur.base = -1;
cur.len = 0;
for (i = 0; i < (IN6ADDRSZ / INT16SZ); i++) {
if (words[i] == 0) {
if (cur.base == -1)
cur.base = i, cur.len = 1;
else
cur.len++;
} else {
if (cur.base != -1) {
if (best.base == -1 || cur.len > best.len)
best = cur;
cur.base = -1;
}
}
}
if (cur.base != -1) {
if (best.base == -1 || cur.len > best.len)
best = cur;
}
if (best.base != -1 && best.len < 2)
best.base = -1;
/*
* Format the result.
*/
tp = tmp;
ep = tmp + sizeof(tmp);
for (i = 0; i < (IN6ADDRSZ / INT16SZ) && tp < ep; i++) {
/* Are we inside the best run of 0x00's? */
if (best.base != -1 && i >= best.base &&
i < (best.base + best.len)) {
if (i == best.base) {
if (tp + 1 >= ep)
return (NULL);
*tp++ = ':';
}
continue;
}
/* Are we following an initial run of 0x00s or any real hex? */
if (i != 0) {
if (tp + 1 >= ep)
return (NULL);
*tp++ = ':';
}
/* Is this address an encapsulated IPv4? */
if (i == 6 && best.base == 0 &&
(best.len == 6 || (best.len == 5 && words[5] == 0xffff))) {
if (!inet_ntop4(src+12, tp, (size_t)(ep - tp)))
return (NULL);
tp += strlen(tp);
break;
}
advance = snprintf(tp, ep - tp, "%x", words[i]);
if (advance <= 0 || advance >= ep - tp)
return (NULL);
tp += advance;
}
/* Was it a trailing run of 0x00's? */
if (best.base != -1 && (best.base + best.len) == (IN6ADDRSZ / INT16SZ)) {
if (tp + 1 >= ep)
return (NULL);
*tp++ = ':';
}
if (tp + 1 >= ep)
return (NULL);
*tp++ = '\0';
/*
* Check for overflow, copy, and we're done.
*/
if ((size_t)(tp - tmp) > size) {
errno = ENOSPC;
return (NULL);
}
strlcpy(dst, tmp, size);
return (dst);
}
#endif /* !HAVE_INET_NTOP */

230
external/unbound/compat/inet_pton.c vendored Normal file
View File

@ -0,0 +1,230 @@
/* $KAME: inet_pton.c,v 1.5 2001/08/20 02:32:40 itojun Exp $ */
/* Copyright (c) 1996 by Internet Software Consortium.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
* ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
* CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
*/
#include <config.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
/*
* WARNING: Don't even consider trying to compile this on a system where
* sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX.
*/
static int inet_pton4 (const char *src, uint8_t *dst);
static int inet_pton6 (const char *src, uint8_t *dst);
/*
*
* The definitions we might miss.
*
*/
#ifndef NS_INT16SZ
#define NS_INT16SZ 2
#endif
#ifndef NS_IN6ADDRSZ
#define NS_IN6ADDRSZ 16
#endif
#ifndef NS_INADDRSZ
#define NS_INADDRSZ 4
#endif
/* int
* inet_pton(af, src, dst)
* convert from presentation format (which usually means ASCII printable)
* to network format (which is usually some kind of binary format).
* return:
* 1 if the address was valid for the specified address family
* 0 if the address wasn't valid (`dst' is untouched in this case)
* -1 if some other error occurred (`dst' is untouched in this case, too)
* author:
* Paul Vixie, 1996.
*/
int
inet_pton(af, src, dst)
int af;
const char *src;
void *dst;
{
switch (af) {
case AF_INET:
return (inet_pton4(src, dst));
case AF_INET6:
return (inet_pton6(src, dst));
default:
#ifdef EAFNOSUPPORT
errno = EAFNOSUPPORT;
#else
errno = ENOSYS;
#endif
return (-1);
}
/* NOTREACHED */
}
/* int
* inet_pton4(src, dst)
* like inet_aton() but without all the hexadecimal and shorthand.
* return:
* 1 if `src' is a valid dotted quad, else 0.
* notice:
* does not touch `dst' unless it's returning 1.
* author:
* Paul Vixie, 1996.
*/
static int
inet_pton4(src, dst)
const char *src;
uint8_t *dst;
{
static const char digits[] = "0123456789";
int saw_digit, octets, ch;
uint8_t tmp[NS_INADDRSZ], *tp;
saw_digit = 0;
octets = 0;
*(tp = tmp) = 0;
while ((ch = *src++) != '\0') {
const char *pch;
if ((pch = strchr(digits, ch)) != NULL) {
uint32_t new = *tp * 10 + (pch - digits);
if (new > 255)
return (0);
*tp = new;
if (! saw_digit) {
if (++octets > 4)
return (0);
saw_digit = 1;
}
} else if (ch == '.' && saw_digit) {
if (octets == 4)
return (0);
*++tp = 0;
saw_digit = 0;
} else
return (0);
}
if (octets < 4)
return (0);
memcpy(dst, tmp, NS_INADDRSZ);
return (1);
}
/* int
* inet_pton6(src, dst)
* convert presentation level address to network order binary form.
* return:
* 1 if `src' is a valid [RFC1884 2.2] address, else 0.
* notice:
* (1) does not touch `dst' unless it's returning 1.
* (2) :: in a full address is silently ignored.
* credit:
* inspired by Mark Andrews.
* author:
* Paul Vixie, 1996.
*/
static int
inet_pton6(src, dst)
const char *src;
uint8_t *dst;
{
static const char xdigits_l[] = "0123456789abcdef",
xdigits_u[] = "0123456789ABCDEF";
uint8_t tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp;
const char *xdigits, *curtok;
int ch, saw_xdigit;
uint32_t val;
memset((tp = tmp), '\0', NS_IN6ADDRSZ);
endp = tp + NS_IN6ADDRSZ;
colonp = NULL;
/* Leading :: requires some special handling. */
if (*src == ':')
if (*++src != ':')
return (0);
curtok = src;
saw_xdigit = 0;
val = 0;
while ((ch = *src++) != '\0') {
const char *pch;
if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL)
pch = strchr((xdigits = xdigits_u), ch);
if (pch != NULL) {
val <<= 4;
val |= (pch - xdigits);
if (val > 0xffff)
return (0);
saw_xdigit = 1;
continue;
}
if (ch == ':') {
curtok = src;
if (!saw_xdigit) {
if (colonp)
return (0);
colonp = tp;
continue;
}
if (tp + NS_INT16SZ > endp)
return (0);
*tp++ = (uint8_t) (val >> 8) & 0xff;
*tp++ = (uint8_t) val & 0xff;
saw_xdigit = 0;
val = 0;
continue;
}
if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) &&
inet_pton4(curtok, tp) > 0) {
tp += NS_INADDRSZ;
saw_xdigit = 0;
break; /* '\0' was seen by inet_pton4(). */
}
return (0);
}
if (saw_xdigit) {
if (tp + NS_INT16SZ > endp)
return (0);
*tp++ = (uint8_t) (val >> 8) & 0xff;
*tp++ = (uint8_t) val & 0xff;
}
if (colonp != NULL) {
/*
* Since some memmove()'s erroneously fail to handle
* overlapping regions, we'll do the shift by hand.
*/
const int n = tp - colonp;
int i;
for (i = 1; i <= n; i++) {
endp[- i] = colonp[n - i];
colonp[n - i] = 0;
}
tp = endp;
}
if (tp != endp)
return (0);
memcpy(dst, tmp, NS_IN6ADDRSZ);
return (1);
}

19
external/unbound/compat/malloc.c vendored Normal file
View File

@ -0,0 +1,19 @@
/* Just a replacement, if the original malloc is not
GNU-compliant. See autoconf documentation. */
#include "config.h"
#undef malloc
#include <sys/types.h>
void *malloc ();
/* Allocate an N-byte block of memory from the heap.
If N is zero, allocate a 1-byte block. */
void *
rpl_malloc_unbound (size_t n)
{
if (n == 0)
n = 1;
return malloc (n);
}

25
external/unbound/compat/memcmp.c vendored Normal file
View File

@ -0,0 +1,25 @@
/*
* memcmp.c: memcmp compat implementation.
*
* Copyright (c) 2010, NLnet Labs. All rights reserved.
*
* See LICENSE for the license.
*/
#include <config.h>
int memcmp(const void *x, const void *y, size_t n);
int memcmp(const void *x, const void *y, size_t n)
{
const uint8_t* x8 = (const uint8_t*)x;
const uint8_t* y8 = (const uint8_t*)y;
size_t i;
for(i=0; i<n; i++) {
if(x8[i] < y8[i])
return -1;
else if(x8[i] > y8[i])
return 1;
}
return 0;
}

16
external/unbound/compat/memcmp.h vendored Normal file
View File

@ -0,0 +1,16 @@
/*
* memcmp.h: undef memcmp for compat.
*
* Copyright (c) 2012, NLnet Labs. All rights reserved.
*
* See LICENSE for the license.
*/
#ifndef COMPAT_MEMCMP_H
#define COMPAT_MEMCMP_H
#ifdef memcmp
/* undef here otherwise autoheader messes it up in config.h */
# undef memcmp
#endif
#endif /* COMPAT_MEMCMP_H */

43
external/unbound/compat/memmove.c vendored Normal file
View File

@ -0,0 +1,43 @@
/*
* memmove.c: memmove compat implementation.
*
* Copyright (c) 2001-2006, NLnet Labs. All rights reserved.
*
* See LICENSE for the license.
*/
#include <config.h>
#include <stdlib.h>
void *memmove(void *dest, const void *src, size_t n);
void *memmove(void *dest, const void *src, size_t n)
{
uint8_t* from = (uint8_t*) src;
uint8_t* to = (uint8_t*) dest;
if (from == to || n == 0)
return dest;
if (to > from && to-from < (int)n) {
/* to overlaps with from */
/* <from......> */
/* <to........> */
/* copy in reverse, to avoid overwriting from */
int i;
for(i=n-1; i>=0; i--)
to[i] = from[i];
return dest;
}
if (from > to && from-to < (int)n) {
/* to overlaps with from */
/* <from......> */
/* <to........> */
/* copy forwards, to avoid overwriting from */
size_t i;
for(i=0; i<n; i++)
to[i] = from[i];
return dest;
}
memcpy(dest, src, n);
return dest;
}

477
external/unbound/compat/sha512.c vendored Normal file
View File

@ -0,0 +1,477 @@
/*
* FILE: sha2.c
* AUTHOR: Aaron D. Gifford - http://www.aarongifford.com/
*
* Copyright (c) 2000-2001, Aaron D. Gifford
* All rights reserved.
*
* Modified by Jelte Jansen to fit in ldns, and not clash with any
* system-defined SHA code.
* Changes:
* - Renamed (external) functions and constants to fit ldns style
* - Removed _End and _Data functions
* - Added ldns_shaX(data, len, digest) convenience functions
* - Removed prototypes of _Transform functions and made those static
* Modified by Wouter, and trimmed, to provide SHA512 for getentropy_fallback.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: sha2.c,v 1.1 2001/11/08 00:01:51 adg Exp adg $
*/
#include "config.h"
#include <string.h> /* memcpy()/memset() or bcopy()/bzero() */
#include <assert.h> /* assert() */
/* do we have sha512 header defs */
#ifndef SHA512_DIGEST_LENGTH
#define SHA512_BLOCK_LENGTH 128
#define SHA512_DIGEST_LENGTH 64
#define SHA512_DIGEST_STRING_LENGTH (SHA512_DIGEST_LENGTH * 2 + 1)
typedef struct _SHA512_CTX {
uint64_t state[8];
uint64_t bitcount[2];
uint8_t buffer[SHA512_BLOCK_LENGTH];
} SHA512_CTX;
#endif /* do we have sha512 header defs */
void SHA512_Init(SHA512_CTX*);
void SHA512_Update(SHA512_CTX*, void*, size_t);
void SHA512_Final(uint8_t[SHA512_DIGEST_LENGTH], SHA512_CTX*);
unsigned char *SHA512(void *data, unsigned int data_len, unsigned char *digest);
/*** SHA-256/384/512 Machine Architecture Definitions *****************/
/*
* BYTE_ORDER NOTE:
*
* Please make sure that your system defines BYTE_ORDER. If your
* architecture is little-endian, make sure it also defines
* LITTLE_ENDIAN and that the two (BYTE_ORDER and LITTLE_ENDIAN) are
* equivilent.
*
* If your system does not define the above, then you can do so by
* hand like this:
*
* #define LITTLE_ENDIAN 1234
* #define BIG_ENDIAN 4321
*
* And for little-endian machines, add:
*
* #define BYTE_ORDER LITTLE_ENDIAN
*
* Or for big-endian machines:
*
* #define BYTE_ORDER BIG_ENDIAN
*
* The FreeBSD machine this was written on defines BYTE_ORDER
* appropriately by including <sys/types.h> (which in turn includes
* <machine/endian.h> where the appropriate definitions are actually
* made).
*/
#if !defined(BYTE_ORDER) || (BYTE_ORDER != LITTLE_ENDIAN && BYTE_ORDER != BIG_ENDIAN)
#error Define BYTE_ORDER to be equal to either LITTLE_ENDIAN or BIG_ENDIAN
#endif
typedef uint8_t sha2_byte; /* Exactly 1 byte */
typedef uint32_t sha2_word32; /* Exactly 4 bytes */
#ifdef S_SPLINT_S
typedef unsigned long long sha2_word64; /* lint 8 bytes */
#else
typedef uint64_t sha2_word64; /* Exactly 8 bytes */
#endif
/*** SHA-256/384/512 Various Length Definitions ***********************/
#define SHA512_SHORT_BLOCK_LENGTH (SHA512_BLOCK_LENGTH - 16)
/*** ENDIAN REVERSAL MACROS *******************************************/
#if BYTE_ORDER == LITTLE_ENDIAN
#define REVERSE32(w,x) { \
sha2_word32 tmp = (w); \
tmp = (tmp >> 16) | (tmp << 16); \
(x) = ((tmp & 0xff00ff00UL) >> 8) | ((tmp & 0x00ff00ffUL) << 8); \
}
#ifndef S_SPLINT_S
#define REVERSE64(w,x) { \
sha2_word64 tmp = (w); \
tmp = (tmp >> 32) | (tmp << 32); \
tmp = ((tmp & 0xff00ff00ff00ff00ULL) >> 8) | \
((tmp & 0x00ff00ff00ff00ffULL) << 8); \
(x) = ((tmp & 0xffff0000ffff0000ULL) >> 16) | \
((tmp & 0x0000ffff0000ffffULL) << 16); \
}
#else /* splint */
#define REVERSE64(w,x) /* splint */
#endif /* splint */
#endif /* BYTE_ORDER == LITTLE_ENDIAN */
/*
* Macro for incrementally adding the unsigned 64-bit integer n to the
* unsigned 128-bit integer (represented using a two-element array of
* 64-bit words):
*/
#define ADDINC128(w,n) { \
(w)[0] += (sha2_word64)(n); \
if ((w)[0] < (n)) { \
(w)[1]++; \
} \
}
#ifdef S_SPLINT_S
#undef ADDINC128
#define ADDINC128(w,n) /* splint */
#endif
/*
* Macros for copying blocks of memory and for zeroing out ranges
* of memory. Using these macros makes it easy to switch from
* using memset()/memcpy() and using bzero()/bcopy().
*
* Please define either SHA2_USE_MEMSET_MEMCPY or define
* SHA2_USE_BZERO_BCOPY depending on which function set you
* choose to use:
*/
#if !defined(SHA2_USE_MEMSET_MEMCPY) && !defined(SHA2_USE_BZERO_BCOPY)
/* Default to memset()/memcpy() if no option is specified */
#define SHA2_USE_MEMSET_MEMCPY 1
#endif
#if defined(SHA2_USE_MEMSET_MEMCPY) && defined(SHA2_USE_BZERO_BCOPY)
/* Abort with an error if BOTH options are defined */
#error Define either SHA2_USE_MEMSET_MEMCPY or SHA2_USE_BZERO_BCOPY, not both!
#endif
#ifdef SHA2_USE_MEMSET_MEMCPY
#define MEMSET_BZERO(p,l) memset((p), 0, (l))
#define MEMCPY_BCOPY(d,s,l) memcpy((d), (s), (l))
#endif
#ifdef SHA2_USE_BZERO_BCOPY
#define MEMSET_BZERO(p,l) bzero((p), (l))
#define MEMCPY_BCOPY(d,s,l) bcopy((s), (d), (l))
#endif
/*** THE SIX LOGICAL FUNCTIONS ****************************************/
/*
* Bit shifting and rotation (used by the six SHA-XYZ logical functions:
*
* NOTE: The naming of R and S appears backwards here (R is a SHIFT and
* S is a ROTATION) because the SHA-256/384/512 description document
* (see http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf) uses this
* same "backwards" definition.
*/
/* Shift-right (used in SHA-256, SHA-384, and SHA-512): */
#define R(b,x) ((x) >> (b))
/* 64-bit Rotate-right (used in SHA-384 and SHA-512): */
#define S64(b,x) (((x) >> (b)) | ((x) << (64 - (b))))
/* Two of six logical functions used in SHA-256, SHA-384, and SHA-512: */
#define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z)))
#define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
/* Four of six logical functions used in SHA-384 and SHA-512: */
#define Sigma0_512(x) (S64(28, (x)) ^ S64(34, (x)) ^ S64(39, (x)))
#define Sigma1_512(x) (S64(14, (x)) ^ S64(18, (x)) ^ S64(41, (x)))
#define sigma0_512(x) (S64( 1, (x)) ^ S64( 8, (x)) ^ R( 7, (x)))
#define sigma1_512(x) (S64(19, (x)) ^ S64(61, (x)) ^ R( 6, (x)))
/*** SHA-XYZ INITIAL HASH VALUES AND CONSTANTS ************************/
/* Hash constant words K for SHA-384 and SHA-512: */
static const sha2_word64 K512[80] = {
0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL
};
/* initial hash value H for SHA-512 */
static const sha2_word64 sha512_initial_hash_value[8] = {
0x6a09e667f3bcc908ULL,
0xbb67ae8584caa73bULL,
0x3c6ef372fe94f82bULL,
0xa54ff53a5f1d36f1ULL,
0x510e527fade682d1ULL,
0x9b05688c2b3e6c1fULL,
0x1f83d9abfb41bd6bULL,
0x5be0cd19137e2179ULL
};
typedef union _ldns_sha2_buffer_union {
uint8_t* theChars;
uint64_t* theLongs;
} ldns_sha2_buffer_union;
/*** SHA-512: *********************************************************/
void SHA512_Init(SHA512_CTX* context) {
if (context == (SHA512_CTX*)0) {
return;
}
MEMCPY_BCOPY(context->state, sha512_initial_hash_value, SHA512_DIGEST_LENGTH);
MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH);
context->bitcount[0] = context->bitcount[1] = 0;
}
static void SHA512_Transform(SHA512_CTX* context,
const sha2_word64* data) {
sha2_word64 a, b, c, d, e, f, g, h, s0, s1;
sha2_word64 T1, T2, *W512 = (sha2_word64*)context->buffer;
int j;
/* initialize registers with the prev. intermediate value */
a = context->state[0];
b = context->state[1];
c = context->state[2];
d = context->state[3];
e = context->state[4];
f = context->state[5];
g = context->state[6];
h = context->state[7];
j = 0;
do {
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert TO host byte order */
REVERSE64(*data++, W512[j]);
/* Apply the SHA-512 compression function to update a..h */
T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j];
#else /* BYTE_ORDER == LITTLE_ENDIAN */
/* Apply the SHA-512 compression function to update a..h with copy */
T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j] = *data++);
#endif /* BYTE_ORDER == LITTLE_ENDIAN */
T2 = Sigma0_512(a) + Maj(a, b, c);
h = g;
g = f;
f = e;
e = d + T1;
d = c;
c = b;
b = a;
a = T1 + T2;
j++;
} while (j < 16);
do {
/* Part of the message block expansion: */
s0 = W512[(j+1)&0x0f];
s0 = sigma0_512(s0);
s1 = W512[(j+14)&0x0f];
s1 = sigma1_512(s1);
/* Apply the SHA-512 compression function to update a..h */
T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] +
(W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0);
T2 = Sigma0_512(a) + Maj(a, b, c);
h = g;
g = f;
f = e;
e = d + T1;
d = c;
c = b;
b = a;
a = T1 + T2;
j++;
} while (j < 80);
/* Compute the current intermediate hash value */
context->state[0] += a;
context->state[1] += b;
context->state[2] += c;
context->state[3] += d;
context->state[4] += e;
context->state[5] += f;
context->state[6] += g;
context->state[7] += h;
/* Clean up */
a = b = c = d = e = f = g = h = T1 = T2 = 0;
}
void SHA512_Update(SHA512_CTX* context, void *datain, size_t len) {
size_t freespace, usedspace;
const sha2_byte* data = (const sha2_byte*)datain;
if (len == 0) {
/* Calling with no data is valid - we do nothing */
return;
}
/* Sanity check: */
assert(context != (SHA512_CTX*)0 && data != (sha2_byte*)0);
usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH;
if (usedspace > 0) {
/* Calculate how much free space is available in the buffer */
freespace = SHA512_BLOCK_LENGTH - usedspace;
if (len >= freespace) {
/* Fill the buffer completely and process it */
MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace);
ADDINC128(context->bitcount, freespace << 3);
len -= freespace;
data += freespace;
SHA512_Transform(context, (sha2_word64*)context->buffer);
} else {
/* The buffer is not yet full */
MEMCPY_BCOPY(&context->buffer[usedspace], data, len);
ADDINC128(context->bitcount, len << 3);
/* Clean up: */
usedspace = freespace = 0;
return;
}
}
while (len >= SHA512_BLOCK_LENGTH) {
/* Process as many complete blocks as we can */
SHA512_Transform(context, (sha2_word64*)data);
ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3);
len -= SHA512_BLOCK_LENGTH;
data += SHA512_BLOCK_LENGTH;
}
if (len > 0) {
/* There's left-overs, so save 'em */
MEMCPY_BCOPY(context->buffer, data, len);
ADDINC128(context->bitcount, len << 3);
}
/* Clean up: */
usedspace = freespace = 0;
}
static void SHA512_Last(SHA512_CTX* context) {
size_t usedspace;
ldns_sha2_buffer_union cast_var;
usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH;
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert FROM host byte order */
REVERSE64(context->bitcount[0],context->bitcount[0]);
REVERSE64(context->bitcount[1],context->bitcount[1]);
#endif
if (usedspace > 0) {
/* Begin padding with a 1 bit: */
context->buffer[usedspace++] = 0x80;
if (usedspace <= SHA512_SHORT_BLOCK_LENGTH) {
/* Set-up for the last transform: */
MEMSET_BZERO(&context->buffer[usedspace], SHA512_SHORT_BLOCK_LENGTH - usedspace);
} else {
if (usedspace < SHA512_BLOCK_LENGTH) {
MEMSET_BZERO(&context->buffer[usedspace], SHA512_BLOCK_LENGTH - usedspace);
}
/* Do second-to-last transform: */
SHA512_Transform(context, (sha2_word64*)context->buffer);
/* And set-up for the last transform: */
MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH - 2);
}
} else {
/* Prepare for final transform: */
MEMSET_BZERO(context->buffer, SHA512_SHORT_BLOCK_LENGTH);
/* Begin padding with a 1 bit: */
*context->buffer = 0x80;
}
/* Store the length of input data (in bits): */
cast_var.theChars = context->buffer;
cast_var.theLongs[SHA512_SHORT_BLOCK_LENGTH / 8] = context->bitcount[1];
cast_var.theLongs[SHA512_SHORT_BLOCK_LENGTH / 8 + 1] = context->bitcount[0];
/* final transform: */
SHA512_Transform(context, (sha2_word64*)context->buffer);
}
void SHA512_Final(sha2_byte digest[], SHA512_CTX* context) {
sha2_word64 *d = (sha2_word64*)digest;
/* Sanity check: */
assert(context != (SHA512_CTX*)0);
/* If no digest buffer is passed, we don't bother doing this: */
if (digest != (sha2_byte*)0) {
SHA512_Last(context);
/* Save the hash data for output: */
#if BYTE_ORDER == LITTLE_ENDIAN
{
/* Convert TO host byte order */
int j;
for (j = 0; j < 8; j++) {
REVERSE64(context->state[j],context->state[j]);
*d++ = context->state[j];
}
}
#else
MEMCPY_BCOPY(d, context->state, SHA512_DIGEST_LENGTH);
#endif
}
/* Zero out state data */
MEMSET_BZERO(context, sizeof(SHA512_CTX));
}
unsigned char *
SHA512(void *data, unsigned int data_len, unsigned char *digest)
{
SHA512_CTX ctx;
SHA512_Init(&ctx);
SHA512_Update(&ctx, data, data_len);
SHA512_Final(digest, &ctx);
return digest;
}

1036
external/unbound/compat/snprintf.c vendored Normal file

File diff suppressed because it is too large Load Diff

73
external/unbound/compat/strlcat.c vendored Normal file
View File

@ -0,0 +1,73 @@
/* compat/strlcat.c */
/*-
* Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* OPENBSD ORIGINAL: lib/libc/string/strlcat.c */
#include "config.h"
#ifndef HAVE_STRLCAT
#include <sys/types.h>
#include <string.h>
/*
* Appends src to string dst of size siz (unlike strncat, siz is the
* full size of dst, not space left). At most siz-1 characters
* will be copied. Always NUL terminates (unless siz <= strlen(dst)).
* Returns strlen(src) + MIN(siz, strlen(initial dst)).
* If retval >= siz, truncation occurred.
*/
size_t
strlcat(char *dst, const char *src, size_t siz)
{
char *d = dst;
const char *s = src;
size_t n = siz;
size_t dlen;
/* Find the end of dst and adjust bytes left but don't go past end */
while (n-- != 0 && *d != '\0')
d++;
dlen = d - dst;
n = siz - dlen;
if (n == 0)
return(dlen + strlen(s));
while (*s != '\0') {
if (n != 1) {
*d++ = *s;
n--;
}
s++;
}
*d = '\0';
return(dlen + (s - src)); /* count does not include NUL */
}
#endif /* !HAVE_STRLCAT */

57
external/unbound/compat/strlcpy.c vendored Normal file
View File

@ -0,0 +1,57 @@
/* from openssh 4.3p2 compat/strlcpy.c */
/*
* Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* OPENBSD ORIGINAL: lib/libc/string/strlcpy.c */
#include <config.h>
#ifndef HAVE_STRLCPY
#include <sys/types.h>
#include <string.h>
/*
* Copy src to string dst of size siz. At most siz-1 characters
* will be copied. Always NUL terminates (unless siz == 0).
* Returns strlen(src); if retval >= siz, truncation occurred.
*/
size_t
strlcpy(char *dst, const char *src, size_t siz)
{
char *d = dst;
const char *s = src;
size_t n = siz;
/* Copy as many bytes as will fit */
if (n != 0 && --n != 0) {
do {
if ((*d++ = *s++) == 0)
break;
} while (--n != 0);
}
/* Not enough room in dst, add NUL and traverse rest of src */
if (n == 0) {
if (siz != 0)
*d = '\0'; /* NUL-terminate dst */
while (*s++)
;
}
return(s - src - 1); /* count does not include NUL */
}
#endif /* !HAVE_STRLCPY */

345
external/unbound/compat/strptime.c vendored Normal file
View File

@ -0,0 +1,345 @@
/** strptime workaround (for oa macos leopard)
* This strptime follows the man strptime (2001-11-12)
* conforming to SUSv2, POSIX.1-2001
*
* This very simple version of strptime has no:
* - E alternatives
* - O alternatives
* - Glibc additions
* - Does not process week numbers
* - Does not properly processes year day
*
* LICENSE
* Copyright (c) 2008, NLnet Labs, Matthijs Mekking
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NLnetLabs nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
**/
#include "config.h"
#ifndef HAVE_CONFIG_H
#include <time.h>
#endif
#ifndef STRPTIME_WORKS
#define TM_YEAR_BASE 1900
#include <ctype.h>
#include <string.h>
static const char *abb_weekdays[] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", NULL
};
static const char *full_weekdays[] = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", NULL
};
static const char *abb_months[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL
};
static const char *full_months[] = {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December", NULL
};
static const char *ampm[] = {
"am", "pm", NULL
};
static int
match_string(const char **buf, const char **strs)
{
int i = 0;
for (i = 0; strs[i] != NULL; i++) {
int len = strlen(strs[i]);
if (strncasecmp (*buf, strs[i], len) == 0) {
*buf += len;
return i;
}
}
return -1;
}
static int
str2int(const char **buf, int max)
{
int ret=0, count=0;
while (*buf[0] != '\0' && isdigit(*buf[0]) && count<max) {
ret = ret*10 + (*buf[0] - '0');
(*buf)++;
count++;
}
if (!count)
return -1;
return ret;
}
/** Converts the character string s to values which are stored in tm
* using the format specified by format
**/
char *
unbound_strptime(const char *s, const char *format, struct tm *tm)
{
int c, ret;
int split_year = 0;
while ((c = *format) != '\0') {
/* whitespace, literal or format */
if (isspace(c)) { /* whitespace */
/** whitespace matches zero or more whitespace characters in the
* input string.
**/
while (isspace(*s))
s++;
}
else if (c == '%') { /* format */
format++;
c = *format;
switch (c) {
case '%': /* %% is converted to % */
if (*s != c) {
return NULL;
}
s++;
break;
case 'a': /* weekday name, abbreviated or full */
case 'A':
ret = match_string(&s, full_weekdays);
if (ret < 0)
ret = match_string(&s, abb_weekdays);
if (ret < 0) {
return NULL;
}
tm->tm_wday = ret;
break;
case 'b': /* month name, abbreviated or full */
case 'B':
case 'h':
ret = match_string(&s, full_months);
if (ret < 0)
ret = match_string(&s, abb_months);
if (ret < 0) {
return NULL;
}
tm->tm_mon = ret;
break;
case 'c': /* date and time representation */
if (!(s = unbound_strptime(s, "%x %X", tm))) {
return NULL;
}
break;
case 'C': /* century number */
ret = str2int(&s, 2);
if (ret < 0 || ret > 99) { /* must be in [00,99] */
return NULL;
}
if (split_year) {
tm->tm_year = ret*100 + (tm->tm_year%100);
}
else {
tm->tm_year = ret*100 - TM_YEAR_BASE;
split_year = 1;
}
break;
case 'd': /* day of month */
case 'e':
ret = str2int(&s, 2);
if (ret < 1 || ret > 31) { /* must be in [01,31] */
return NULL;
}
tm->tm_mday = ret;
break;
case 'D': /* equivalent to %m/%d/%y */
if (!(s = unbound_strptime(s, "%m/%d/%y", tm))) {
return NULL;
}
break;
case 'H': /* hour */
ret = str2int(&s, 2);
if (ret < 0 || ret > 23) { /* must be in [00,23] */
return NULL;
}
tm->tm_hour = ret;
break;
case 'I': /* 12hr clock hour */
ret = str2int(&s, 2);
if (ret < 1 || ret > 12) { /* must be in [01,12] */
return NULL;
}
if (ret == 12) /* actually [0,11] */
ret = 0;
tm->tm_hour = ret;
break;
case 'j': /* day of year */
ret = str2int(&s, 2);
if (ret < 1 || ret > 366) { /* must be in [001,366] */
return NULL;
}
tm->tm_yday = ret;
break;
case 'm': /* month */
ret = str2int(&s, 2);
if (ret < 1 || ret > 12) { /* must be in [01,12] */
return NULL;
}
/* months go from 0-11 */
tm->tm_mon = (ret-1);
break;
case 'M': /* minute */
ret = str2int(&s, 2);
if (ret < 0 || ret > 59) { /* must be in [00,59] */
return NULL;
}
tm->tm_min = ret;
break;
case 'n': /* arbitrary whitespace */
case 't':
while (isspace(*s))
s++;
break;
case 'p': /* am pm */
ret = match_string(&s, ampm);
if (ret < 0) {
return NULL;
}
if (tm->tm_hour < 0 || tm->tm_hour > 11) { /* %I */
return NULL;
}
if (ret == 1) /* pm */
tm->tm_hour += 12;
break;
case 'r': /* equivalent of %I:%M:%S %p */
if (!(s = unbound_strptime(s, "%I:%M:%S %p", tm))) {
return NULL;
}
break;
case 'R': /* equivalent of %H:%M */
if (!(s = unbound_strptime(s, "%H:%M", tm))) {
return NULL;
}
break;
case 'S': /* seconds */
ret = str2int(&s, 2);
/* 60 may occur for leap seconds */
/* earlier 61 was also allowed */
if (ret < 0 || ret > 60) { /* must be in [00,60] */
return NULL;
}
tm->tm_sec = ret;
break;
case 'T': /* equivalent of %H:%M:%S */
if (!(s = unbound_strptime(s, "%H:%M:%S", tm))) {
return NULL;
}
break;
case 'U': /* week number, with the first Sun of Jan being w1 */
ret = str2int(&s, 2);
if (ret < 0 || ret > 53) { /* must be in [00,53] */
return NULL;
}
/** it is hard (and not necessary for nsd) to determine time
* data from week number.
**/
break;
case 'w': /* day of week */
ret = str2int(&s, 1);
if (ret < 0 || ret > 6) { /* must be in [0,6] */
return NULL;
}
tm->tm_wday = ret;
break;
case 'W': /* week number, with the first Mon of Jan being w1 */
ret = str2int(&s, 2);
if (ret < 0 || ret > 53) { /* must be in [00,53] */
return NULL;
}
/** it is hard (and not necessary for nsd) to determine time
* data from week number.
**/
break;
case 'x': /* date format */
if (!(s = unbound_strptime(s, "%m/%d/%y", tm))) {
return NULL;
}
break;
case 'X': /* time format */
if (!(s = unbound_strptime(s, "%H:%M:%S", tm))) {
return NULL;
}
break;
case 'y': /* last two digits of a year */
ret = str2int(&s, 2);
if (ret < 0 || ret > 99) { /* must be in [00,99] */
return NULL;
}
if (split_year) {
tm->tm_year = ((tm->tm_year/100) * 100) + ret;
}
else {
split_year = 1;
/** currently:
* if in [0,68] we are in 21th century,
* if in [69,99] we are in 20th century.
**/
if (ret < 69) /* 2000 */
ret += 100;
tm->tm_year = ret;
}
break;
case 'Y': /* year */
ret = str2int(&s, 4);
if (ret < 0 || ret > 9999) {
return NULL;
}
tm->tm_year = ret - TM_YEAR_BASE;
break;
case '\0':
default: /* unsupported, cannot match format */
return NULL;
break;
}
}
else { /* literal */
/* if input cannot match format, return NULL */
if (*s != c)
return NULL;
s++;
}
format++;
}
/* return pointer to remainder of s */
return (char*) s;
}
#endif /* STRPTIME_WORKS */

1530
external/unbound/config.guess vendored Executable file

File diff suppressed because it is too large Load Diff

1026
external/unbound/config.h.in vendored Normal file

File diff suppressed because it is too large Load Diff

1782
external/unbound/config.sub vendored Executable file

File diff suppressed because it is too large Load Diff

22371
external/unbound/configure vendored Executable file

File diff suppressed because it is too large Load Diff

1370
external/unbound/configure.ac vendored Normal file

File diff suppressed because it is too large Load Diff

28
external/unbound/contrib/README vendored Normal file
View File

@ -0,0 +1,28 @@
These files are contributed to unbound, and are not part of the official
distribution but may be helpful.
* rc_d_unbound: FreeBSD compatible /etc/rc.d script.
* parseunbound.pl: perl script to run from cron that parses statistics from
the log file and stores them.
* unbound.spec and unbound.init: RPM specfile and Linux rc.d initfile.
* update-anchor.sh: shell script that uses unbound-host to update a set
of trust anchor files. Run from cron twice a month.
* unbound_munin_ : plugin for munin statistics report
* unbound_cacti.tar.gz : setup files for cacti statistics report
* selinux: the .fc and .te files for SElinux protection of the unbound daemon
* unbound.plist: launchd configuration file for MacOSX.
* build-unbound-localzone-from-hosts.pl: perl script to turn /etc/hosts into
a local-zone and local-data include file for unbound.conf.
* unbound-host.nagios.patch: makes unbound-host return status that fits right
in with the nagios monitoring framework. Contributed by Migiel de Vos.
* unbound_unixsock.diff: Add Unix socket support for unbound-control.
Contributed by Ilya Bakulin, 2012-08-28.
* patch_rsamd5_enable.diff: this patch enables RSAMD5 validation (otherwise
it is treated as insecure). The RSAMD5 algorithm is deprecated (RFC6725).
* create_unbound_ad_servers.sh: shell script to enter anti-ad server lists.
* create_unbound_ad_servers.cmd: windows script to enter anti-ad server lists.
* unbound_cache.sh: shell script to save and load the cache.
* unbound_cache.cmd: windows script to save and load the cache.
* warmup.sh: shell script to warm up DNS cache by your own MRU domains.
* warmup.cmd: windows script to warm up DNS cache by your own MRU domains.

View File

@ -0,0 +1,67 @@
#!/usr/bin/perl -WT
use strict;
use warnings;
my $hostsfile = '/etc/hosts';
my $localzonefile = '/etc/unbound/localzone.conf.new';
my $localzone = 'example.com';
open( HOSTS,"<${hostsfile}" ) or die( "Could not open ${hostsfile}: $!" );
open( ZONE,">${localzonefile}" ) or die( "Could not open ${localzonefile}: $!" );
print ZONE "server:\n\n";
print ZONE "local-zone: \"${localzone}\" transparent\n\n";
my %ptrhash;
while ( my $hostline = <HOSTS> ) {
# Skip comments
if ( $hostline !~ "^#" and $hostline !~ '^\s+$' ) {
my @entries = split( /\s+/, $hostline );
my $ip;
my $count = 0;
foreach my $entry ( @entries ) {
if ( $count == 0 ) {
$ip = $entry;
} else {
if ( $count == 1) {
# Only return localhost for 127.0.0.1 and ::1
if ( ($ip ne '127.0.0.1' and $ip ne '::1') or $entry =~ 'localhost' ) {
if ( ! defined $ptrhash{$ip} ) {
$ptrhash{$ip} = $entry;
print ZONE "local-data-ptr: \"$ip $entry\"\n";
}
}
}
# Use AAAA for IPv6 addresses
my $a = 'A';
if ( $ip =~ ':' ) {
$a = 'AAAA';
}
print ZONE "local-data: \"$entry ${a} $ip\"\n";
}
$count++;
}
print ZONE "\n";
}
}
__END__

View File

@ -0,0 +1,33 @@
@Echo off
rem Convert the Yoyo.org anti-ad server listing
rem into an unbound dns spoof redirection list.
rem Written by Y.Voinov (c) 2014
rem Note: Wget required!
rem Variables
set prefix="C:\Program Files (x86)"
set dst_dir=%prefix%\Unbound
set work_dir=%TEMP%
set list_addr="http://pgl.yoyo.org/adservers/serverlist.php?hostformat=nohtml&showintro=1&startdate%5Bday%5D=&startdate%5Bmonth%5D=&startdate%5Byear%5D="
rem Check Wget installed
for /f "delims=" %%a in ('where wget') do @set wget=%%a
if /I "%wget%"=="" echo Wget not found. If installed, add path to PATH environment variable. & exit 1
echo Wget found: %wget%
"%wget%" -O %work_dir%\yoyo_ad_servers %list_addr%
del /Q /F /S %dst_dir%\unbound_ad_servers
for /F "eol=; tokens=*" %%a in (%work_dir%\yoyo_ad_servers) do (
echo local-zone: %%a redirect>>%dst_dir%\unbound_ad_servers
echo local-data: "%%a A 127.0.0.1">>%dst_dir%\unbound_ad_servers
)
echo Done.
rem then add an include line to your unbound.conf pointing to the full path of
rem the unbound_ad_servers file:
rem
rem include: $dst_dir/unbound_ad_servers
rem

View File

@ -0,0 +1,39 @@
#!/bin/sh
#
# Convert the Yoyo.org anti-ad server listing
# into an unbound dns spoof redirection list.
# Modified by Y.Voinov (c) 2014
# Note: Wget required!
# Variables
dst_dir="/etc/opt/csw/unbound"
work_dir="/tmp"
list_addr="http://pgl.yoyo.org/adservers/serverlist.php?hostformat=nohtml&showintro=1&startdate%5Bday%5D=&startdate%5Bmonth%5D=&startdate%5Byear%5D="
# OS commands
CAT=`which cat`
ECHO=`which echo`
WGET=`which wget`
# Check Wget installed
if [ ! -f $WGET ]; then
echo "Wget not found. Exiting..."
exit 1
fi
$WGET -O $work_dir/yoyo_ad_servers "$list_addr" && \
$CAT $work_dir/yoyo_ad_servers | \
while read line ; \
do \
$ECHO "local-zone: \"$line\" redirect" ;\
$ECHO "local-data: \"$line A 127.0.0.1\"" ;\
done > \
$dst_dir/unbound_ad_servers
echo "Done."
# then add an include line to your unbound.conf pointing to the full path of
# the unbound_ad_servers file:
#
# include: $dst_dir/unbound_ad_servers
#

140
external/unbound/contrib/parseunbound.pl vendored Normal file
View File

@ -0,0 +1,140 @@
#!/usr/local/bin/perl -w
#
# Script to parse the output from the unbound namedaemon.
# Unbound supports a threading model, and outputs a multiline log-blob for
# every thread.
#
# This script should parse all threads of the once, and store it
# in a local cached file for speedy results when queried lots.
#
use strict;
use POSIX qw(SEEK_END);
use Storable;
use FileHandle;
use Carp qw(croak carp);
use constant UNBOUND_CACHE => "/var/tmp/unbound-cache.stor";
my $run_from_cron = @ARGV && $ARGV[0] eq "--cron" && shift;
my $DEBUG = -t STDERR;
# NB. VERY IMPORTANTES: set this when running this script.
my $numthreads = 4;
### if cache exists, read it in. and is newer than 3 minutes
if ( -r UNBOUND_CACHE ) {
my $result = retrieve(UNBOUND_CACHE);
if (-M _ < 3/24/60 && !$run_from_cron ) {
print STDERR "Cached results:\n" if $DEBUG;
print join("\n", @$result), "\n";
exit;
}
}
my $logfile = shift or die "Usage: parseunbound.pl --cron unboundlogfile";
my $in = new FileHandle $logfile or die "Cannot open $logfile: $!\n";
# there is a special key 'thread' that indicates the thread. its not used, but returned anyway.
my @records = ('thread', 'queries', 'cachehits', 'recursions', 'recursionavg',
'outstandingmax', 'outstandingavg', 'outstandingexc',
'median25', 'median50', 'median75',
'us_0', 'us_1', 'us_2', 'us_4', 'us_8', 'us_16', 'us_32',
'us_64', 'us_128', 'us_256', 'us_512', 'us_1024', 'us_2048',
'us_4096', 'us_8192', 'us_16384', 'us_32768', 'us_65536',
'us_131072', 'us_262144', 'us_524288', 's_1', 's_2', 's_4',
's_8', 's_16', 's_32', 's_64', 's_128', 's_256', 's_512');
# Stats hash containing one or more keys. for every thread, 1 key.
my %allstats = (); # key="$threadid", stats={key => value}
my %startstats = (); # when we got a queries entry for this thread
my %donestats = (); # same, but only when we got a histogram entry for it
# stats hash contains name/value pairs of the actual numbers for that thread.
my $offset = 0;
my $inthread=0;
my $inpid;
# We should continue looping untill we meet these conditions:
# a) more total queries than the previous run (which defaults to 0) AND
# b) parsed all $numthreads threads in the log.
my $numqueries = $previousresult ? $previousresult->[1] : 0;
# Main loop
while ( scalar keys %startstats < $numthreads || scalar keys %donestats < $numthreads) {
$offset += 10000;
if ( $offset > -s $logfile or $offset > 10_000_000 ) {
die "Cannot find stats in $logfile\n";
}
$in->seek(-$offset, SEEK_END) or croak "cannot seek $logfile: $!\n";
for my $line ( <$in> ) {
chomp($line);
#[1208777234] unbound[6705:0]
if ($line =~ m/^\[\d+\] unbound\[\d+:(\d+)\]/) {
$inthread = $1;
if ($inthread + 1 > $numthreads) {
die "Hey. lazy. change \$numthreads in this script to ($inthread)\n";
}
}
# this line doesn't contain a pid:thread. skip.
else {
next;
}
if ( $line =~ m/info: server stats for thread \d+: (\d+) queries, (\d+) answers from cache, (\d+) recursions/ ) {
$startstats{$inthread} = 1;
$allstats{$inthread}->{thread} = $inthread;
$allstats{$inthread}->{queries} = $1;
$allstats{$inthread}->{cachehits} = $2;
$allstats{$inthread}->{recursions} = $3;
}
elsif ( $line =~ m/info: server stats for thread (\d+): requestlist max (\d+) avg ([0-9\.]+) exceeded (\d+)/ ) {
$allstats{$inthread}->{outstandingmax} = $2;
$allstats{$inthread}->{outstandingavg} = int($3); # This is a float; rrdtool only handles ints.
$allstats{$inthread}->{outstandingexc} = $4;
}
elsif ( $line =~ m/info: average recursion processing time ([0-9\.]+) sec/ ) {
$allstats{$inthread}->{recursionavg} = int($1 * 1000); # change sec to milisec.
}
elsif ( $line =~ m/info: histogram of recursion processing times/ ) {
next;
}
elsif ( $line =~ m/info: \[25%\]=([0-9\.]+) median\[50%\]=([0-9\.]+) \[75%\]=([0-9\.]+)/ ) {
$allstats{$inthread}->{median25} = int($1 * 1000000); # change seconds to usec
$allstats{$inthread}->{median50} = int($2 * 1000000);
$allstats{$inthread}->{median75} = int($3 * 1000000);
}
elsif ( $line =~ m/info: lower\(secs\) upper\(secs\) recursions/ ) {
# since after this line we're unsure if we get these numbers
# at all, we sould consider this marker as the end of the
# block. Chances that we're parsing a file halfway written
# at this stage are small. Bold statement.
$donestats{$inthread} = 1;
next;
}
elsif ( $line =~ m/info:\s+(\d+)\.(\d+)\s+(\d+)\.(\d+)\s+(\d+)/ ) {
my ($froms, $fromus, $toms, $tous, $counter) = ($1, $2, $3, $4, $5);
my $prefix = '';
if ($froms > 0) {
$allstats{$inthread}->{'s_' . int($froms)} = $counter;
} else {
$allstats{$inthread}->{'us_' . int($fromus)} = $counter;
}
}
}
}
my @result;
# loop on the records we want to store
for my $key ( @records ) {
my $sum = 0;
# these are the different threads parsed
foreach my $thread ( 0 .. $numthreads - 1 ) {
$sum += ($allstats{$thread}->{$key} || 0);
}
print STDERR "$key = " . $sum . "\n" if $DEBUG;
push @result, $sum;
}
print join("\n", @result), "\n";
store \@result, UNBOUND_CACHE;
if ($DEBUG) {
print STDERR "Threads: " . (scalar keys %allstats) . "\n";
}

View File

@ -0,0 +1,22 @@
Index: validator/val_secalgo.c
===================================================================
--- validator/val_secalgo.c (revision 2759)
+++ validator/val_secalgo.c (working copy)
@@ -153,7 +153,7 @@
switch(id) {
case LDNS_RSAMD5:
/* RFC 6725 deprecates RSAMD5 */
- return 0;
+ return 1;
case LDNS_DSA:
case LDNS_DSA_NSEC3:
case LDNS_RSASHA1:
@@ -617,7 +617,7 @@
switch(id) {
case LDNS_RSAMD5:
/* RFC 6725 deprecates RSAMD5 */
- return 0;
+ return 1;
case LDNS_DSA:
case LDNS_DSA_NSEC3:
case LDNS_RSASHA1:

25
external/unbound/contrib/rc_d_unbound vendored Executable file
View File

@ -0,0 +1,25 @@
#!/bin/sh
#
# unbound freebsd startup rc.d script, modified from the named script.
# uses the default unbound installation path and pidfile location.
# copy this to /etc/rc.d/unbound
# and put unbound_enable="YES" into rc.conf
#
# PROVIDE: unbound
# REQUIRE: SERVERS cleanvar
# KEYWORD: shutdown
. /etc/rc.subr
name="unbound"
rcvar=`set_rcvar`
load_rc_config $name
command="/usr/local/sbin/unbound"
pidfile=${unbound_pidfile:-"/usr/local/etc/unbound/unbound.pid"}
command_args=${unbound_flags:-"-c /usr/local/etc/unbound/unbound.conf"}
extra_commands="reload"
run_rc_command "$1"

View File

@ -0,0 +1,4 @@
/etc/unbound(/.*)? system_u:object_r:unbound_conf_t:s0
/etc/rc\.d/init\.d/unbound -- system_u:object_r:unbound_initrc_exec_t:s0
/usr/sbin/unbound -- system_u:object_r:unbound_exec_t:s0
/var/run/unbound(/.*)? system_u:object_r:unbound_var_run_t:s0

View File

@ -0,0 +1,42 @@
policy_module(unbound, 0.1.0)
type unbound_t;
type unbound_conf_t;
type unbound_exec_t;
type unbound_initrc_exec_t;
type unbound_var_run_t;
init_daemon_domain(unbound_t, unbound_exec_t)
init_script_file(unbound_initrc_exec_t)
role system_r types unbound_t;
# XXX
# unbound-{checkconf,control} are not protected. Do we need protect them?
# Unbound daemon
auth_use_nsswitch(unbound_t)
dev_read_urand(unbound_t)
corenet_all_recvfrom_unlabeled(unbound_t)
corenet_tcp_bind_all_nodes(unbound_t)
corenet_tcp_bind_dns_port(unbound_t)
corenet_tcp_bind_rndc_port(unbound_t)
corenet_udp_bind_all_nodes(unbound_t)
corenet_udp_bind_all_unreserved_ports(unbound_t)
corenet_udp_bind_dns_port(unbound_t)
files_read_etc_files(unbound_t)
files_pid_file(unbound_var_run_t)
files_type(unbound_conf_t)
libs_use_ld_so(unbound_t)
libs_use_shared_libs(unbound_t)
logging_send_syslog_msg(unbound_t)
manage_files_pattern(unbound_t, unbound_var_run_t, unbound_var_run_t)
miscfiles_read_localization(unbound_t)
read_files_pattern(unbound_t, unbound_conf_t, unbound_conf_t)
allow unbound_t self:capability { setuid chown net_bind_service setgid dac_override };
allow unbound_t self:tcp_socket create_stream_socket_perms;
allow unbound_t self:udp_socket create_socket_perms;
###################################################

View File

@ -0,0 +1,134 @@
Index: smallapp/unbound-host.c
===================================================================
--- smallapp/unbound-host.c (revision 2115)
+++ smallapp/unbound-host.c (working copy)
@@ -62,9 +62,18 @@
#include "libunbound/unbound.h"
#include <ldns/ldns.h>
+/** status variable ala nagios */
+#define FINAL_STATUS_OK 0
+#define FINAL_STATUS_WARNING 1
+#define FINAL_STATUS_CRITICAL 2
+#define FINAL_STATUS_UNKNOWN 3
+
/** verbosity for unbound-host app */
static int verb = 0;
+/** variable to determine final output */
+static int final_status = FINAL_STATUS_UNKNOWN;
+
/** Give unbound-host usage, and exit (1). */
static void
usage()
@@ -93,7 +102,7 @@
printf("Version %s\n", PACKAGE_VERSION);
printf("BSD licensed, see LICENSE in source package for details.\n");
printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
- exit(1);
+ exit(FINAL_STATUS_UNKNOWN);
}
/** determine if str is ip4 and put into reverse lookup format */
@@ -138,7 +147,7 @@
*res = strdup(buf);
if(!*res) {
fprintf(stderr, "error: out of memory\n");
- exit(1);
+ exit(FINAL_STATUS_UNKNOWN);
}
return 1;
}
@@ -158,7 +167,7 @@
}
if(!res) {
fprintf(stderr, "error: out of memory\n");
- exit(1);
+ exit(FINAL_STATUS_UNKNOWN);
}
return res;
}
@@ -172,7 +181,7 @@
if(r == 0 && strcasecmp(t, "TYPE0") != 0 &&
strcmp(t, "") != 0) {
fprintf(stderr, "error unknown type %s\n", t);
- exit(1);
+ exit(FINAL_STATUS_UNKNOWN);
}
return r;
}
@@ -191,7 +200,7 @@
if(r == 0 && strcasecmp(c, "CLASS0") != 0 &&
strcmp(c, "") != 0) {
fprintf(stderr, "error unknown class %s\n", c);
- exit(1);
+ exit(FINAL_STATUS_UNKNOWN);
}
return r;
}
@@ -207,6 +216,19 @@
return "(insecure)";
}
+/** update the final status for the exit code */
+void
+update_final_status(struct ub_result* result)
+{
+ if (final_status == FINAL_STATUS_UNKNOWN || final_status == FINAL_STATUS_OK) {
+ if (result->secure) final_status = FINAL_STATUS_OK;
+ else if (result->bogus) final_status = FINAL_STATUS_CRITICAL;
+ else final_status = FINAL_STATUS_WARNING;
+ }
+ else if (final_status == FINAL_STATUS_WARNING && result->bogus)
+ final_status = FINAL_STATUS_CRITICAL;
+}
+
/** nice string for type */
static void
pretty_type(char* s, size_t len, int t)
@@ -353,7 +375,7 @@
} else {
fprintf(stderr, "could not parse "
"reply packet to ANY query\n");
- exit(1);
+ exit(FINAL_STATUS_UNKNOWN);
}
ldns_pkt_free(p);
@@ -388,9 +410,10 @@
ret = ub_resolve(ctx, q, t, c, &result);
if(ret != 0) {
fprintf(stderr, "resolve error: %s\n", ub_strerror(ret));
- exit(1);
+ exit(FINAL_STATUS_UNKNOWN);
}
pretty_output(q, t, c, result, docname);
+ update_final_status(result);
ret = result->nxdomain;
ub_resolve_free(result);
return ret;
@@ -427,7 +450,7 @@
{
if(r != 0) {
fprintf(stderr, "error: %s\n", ub_strerror(r));
- exit(1);
+ exit(FINAL_STATUS_UNKNOWN);
}
}
@@ -448,7 +471,7 @@
ctx = ub_ctx_create();
if(!ctx) {
fprintf(stderr, "error: out of memory\n");
- exit(1);
+ exit(FINAL_STATUS_UNKNOWN);
}
/* parse the options */
@@ -509,5 +532,5 @@
usage();
lookup(ctx, argv[0], qtype, qclass);
- return 0;
+ return final_status;
}

139
external/unbound/contrib/unbound.init vendored Normal file
View File

@ -0,0 +1,139 @@
#!/bin/sh
#
# unbound This shell script takes care of starting and stopping
# unbound (DNS server).
#
# chkconfig: - 14 86
# description: unbound is a Domain Name Server (DNS) \
# that is used to resolve host names to IP addresses.
### BEGIN INIT INFO
# Provides: $named unbound
# Required-Start: $network $local_fs
# Required-Stop: $network $local_fs
# Should-Start: $syslog
# Should-Stop: $syslog
# Short-Description: unbound recursive Domain Name Server.
# Description: unbound is a Domain Name Server (DNS)
# that is used to resolve host names to IP addresses.
### END INIT INFO
# Source function library.
. /etc/rc.d/init.d/functions
exec="/usr/sbin/unbound"
prog="unbound"
config="/var/unbound/unbound.conf"
pidfile="/var/unbound/unbound.pid"
rootdir="/var/unbound"
[ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog
lockfile=/var/lock/subsys/$prog
start() {
[ -x $exec ] || exit 5
[ -f $config ] || exit 6
echo -n $"Starting $prog: "
# setup root jail
if [ -s /etc/localtime ]; then
[ -d ${rootdir}/etc ] || mkdir -p ${rootdir}/etc ;
if [ ! -e ${rootdir}/etc/localtime ] || /usr/bin/cmp -s /etc/localtime ${rootdir}/etc/localtime; then
cp -fp /etc/localtime ${rootdir}/etc/localtime
fi;
fi;
if [ -s /etc/resolv.conf ]; then
[ -d ${rootdir}/etc ] || mkdir -p ${rootdir}/etc ;
if [ ! -e ${rootdir}/etc/resolv.conf ] || /usr/bin/cmp -s /etc/resolv.conf ${rootdir}/etc/resolv.conf; then
cp -fp /etc/resolv.conf ${rootdir}/etc/resolv.conf
fi;
fi;
if ! egrep -q '^/[^[:space:]]+[[:space:]]+'${rootdir}'/dev/log' /proc/mounts; then
[ -d ${rootdir}/dev ] || mkdir -p ${rootdir}/dev ;
[ -e ${rootdir}/dev/log ] || touch ${rootdir}/dev/log
mount --bind -n /dev/log ${rootdir}/dev/log >/dev/null 2>&1;
fi;
if ! egrep -q '^/[^[:space:]]+[[:space:]]+'${rootdir}'/dev/random' /proc/mounts; then
[ -d ${rootdir}/dev ] || mkdir -p ${rootdir}/dev ;
[ -e ${rootdir}/dev/random ] || touch ${rootdir}/dev/random
mount --bind -n /dev/random ${rootdir}/dev/random >/dev/null 2>&1;
fi;
# if not running, start it up here
daemon $exec
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $"Stopping $prog: "
# stop it here, often "killproc $prog"
killproc -p $pidfile $prog
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
if egrep -q '^/[^[:space:]]+[[:space:]]+'${rootdir}'/dev/log' /proc/mounts; then
umount ${rootdir}/dev/log >/dev/null 2>&1
fi;
if egrep -q '^/[^[:space:]]+[[:space:]]+'${rootdir}'/dev/random' /proc/mounts; then
umount ${rootdir}/dev/random >/dev/null 2>&1
fi;
return $retval
}
restart() {
stop
start
}
reload() {
kill -HUP `cat $pidfile`
}
force_reload() {
restart
}
rh_status() {
# run checks to determine if the service is running or use generic status
status -p $pidfile $prog
}
rh_status_q() {
rh_status -p $pidfile >/dev/null 2>&1
}
case "$1" in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart)
$1
;;
reload)
rh_status_q || exit 7
$1
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestart|try-restart)
rh_status_q || exit 0
restart
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
exit 2
esac
exit $?

View File

@ -0,0 +1,119 @@
#!/bin/sh
#
# unbound This shell script takes care of starting and stopping
# unbound (DNS server).
#
# chkconfig: - 14 86
# description: unbound is a Domain Name Server (DNS) \
# that is used to resolve host names to IP addresses.
### BEGIN INIT INFO
# Provides: unbound
# Required-Start: $network $local_fs
# Required-Stop: $network $local_fs
# Should-Start: $syslog
# Should-Stop: $syslog
# Short-Description: unbound recursive Domain Name Server.
# Description: unbound is a Domain Name Server (DNS)
# that is used to resolve host names to IP addresses.
### END INIT INFO
# Source function library.
. /etc/rc.d/init.d/functions
exec="/usr/sbin/unbound"
config="/var/lib/unbound/unbound.conf"
rootdir="/var/lib/unbound"
pidfile="/var/run/unbound/unbound.pid"
[ -e /etc/sysconfig/unbound ] && . /etc/sysconfig/unbound
lockfile=/var/lock/subsys/unbound
start() {
[ -x $exec ] || exit 5
[ -f $config ] || exit 6
echo -n $"Starting unbound: "
if [ ! -e ${rootdir}/etc/resolv.conf ] || /usr/bin/cmp -s /etc/resolv.conf ${rootdir}/etc/resolv.conf; then
cp -fp /etc/resolv.conf ${rootdir}/etc/resolv.conf
fi;
if [ ! -e ${rootdir}/etc/localtime ] || /usr/bin/cmp -s /etc/localtime ${rootdir}/etc/localtime; then
cp -fp /etc/localtime ${rootdir}/etc/localtime
fi;
mount --bind -n /dev/log ${rootdir}/dev/log >/dev/null 2>&1;
mount --bind -n /dev/random ${rootdir}/dev/random >/dev/null 2>&1;
mount --bind -n /var/run/unbound ${rootdir}/var/run/unbound >/dev/null 2>&1;
# if not running, start it up here
daemon $exec
retval=$?
[ $retval -eq 0 ] && touch $lockfile
echo
}
stop() {
echo -n $"Stopping unbound: "
# stop it here, often "killproc unbound"
killproc -p $pidfile unbound
retval=$?
[ $retval -eq 0 ] && rm -f $lockfile
for mountfile in /dev/log /dev/random /etc/localtime /etc/resolv.conf /var/run/unbound
do
if egrep -q '^/[^[:space:]]+[[:space:]]+'${rootdir}''${mountfile}'' /proc/mounts; then
umount ${rootdir}$mountfile >/dev/null 2>&1
fi;
done
echo
}
restart() {
stop
start
}
reload() {
kill -HUP `cat $pidfile`
}
force_reload() {
restart
}
rh_status() {
# run checks to determine if the service is running or use generic status
status -p $pidfile unbound
}
rh_status_q() {
rh_status -p $pidfile >/dev/null 2>&1
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
reload)
reload
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestart|try-restart)
rh_status_q || exit 0
restart
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
exit 2
esac
exit $?

42
external/unbound/contrib/unbound.plist vendored Normal file
View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd >
<plist version="1.0">
<!--
Unbound plist file for use by MacOSX launchd(8) using launchctl(1).
Copy this file to /Library/LaunchDaemons. Launchd keeps unbound running.
Setup your unbound.conf with the following additional settings.
server:
do-daemonize: no
username: ""
chroot: ""
directory: ""
These actions are performed by launchd (for the option values, see below).
-->
<dict>
<key>Label</key>
<string>unbound</string>
<key>ProgramArguments</key>
<array>
<string>unbound</string>
</array>
<key>UserName</key>
<string>unbound</string>
<key>RootDirectory</key>
<string>/usr/local/etc/unbound</string>
<key>WorkingDirectory</key>
<string>/usr/local/etc/unbound</string>
<key>KeepAlive</key>
<true/>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>

112
external/unbound/contrib/unbound.spec vendored Normal file
View File

@ -0,0 +1,112 @@
Summary: Validating, recursive, and caching DNS resolver
Name: unbound
Version: 1.4.18
Release: 1%{?dist}
License: BSD
Url: http://www.nlnetlabs.nl/unbound/
Source: http://www.unbound.net/downloads/%{name}-%{version}.tar.gz
#Source1: unbound.init
Group: System Environment/Daemons
Requires: ldns
BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n)
BuildRequires: flex, openssl-devel, expat-devel, ldns-devel
%description
Unbound is a validating, recursive, and caching DNS resolver.
The C implementation of Unbound is developed and maintained by NLnet
Labs. It is based on ideas and algorithms taken from a java prototype
developed by Verisign labs, Nominet, Kirei and ep.net.
Unbound is designed as a set of modular components, so that also
DNSSEC (secure DNS) validation and stub-resolvers (that do not run
as a server, but are linked into an application) are easily possible.
The source code is under a BSD License.
%prep
%setup -q
# configure with /var/unbound/unbound.conf so that all default chroot,
# pidfile and config file are in /var/unbound, ready for chroot jail set up.
%configure --with-conf-file=%{_localstatedir}/%{name}/unbound.conf --disable-rpath
%build
#%{__make} %{?_smp_mflags}
make
%install
rm -rf %{buildroot}
%{__make} DESTDIR=%{buildroot} install
install -d 0700 %{buildroot}%{_localstatedir}/%{name}
install -d 0755 %{buildroot}%{_initrddir}
install -m 0755 contrib/unbound.init %{buildroot}%{_initrddir}/unbound
# add symbolic link from /etc/unbound.conf -> /var/unbound/unbound.conf
ln -s %{_localstatedir}/unbound/unbound.conf %{buildroot}%{_sysconfdir}/unbound.conf
# remove static library from install (fedora packaging guidelines)
rm -f %{buildroot}%{_libdir}/libunbound.a %{buildroot}%{_libdir}/libunbound.la
%clean
rm -rf ${RPM_BUILD_ROOT}
%files
%defattr(-,root,root,-)
%doc doc/README doc/CREDITS doc/LICENSE doc/FEATURES
%attr(0755,root,root) %{_initrddir}/%{name}
%attr(0700,%{name},%{name}) %dir %{_localstatedir}/%{name}
%attr(0644,%{name},%{name}) %config(noreplace) %{_localstatedir}/%{name}/unbound.conf
%attr(0644,%{name},%{name}) %config(noreplace) %{_sysconfdir}/unbound.conf
%{_sbindir}/*
%{_mandir}/*/*
%{_includedir}/*
%{_libdir}/libunbound*
%pre
getent group unbound >/dev/null || groupadd -r unbound
getent passwd unbound >/dev/null || \
useradd -r -g unbound -d /var/unbound -s /sbin/nologin \
-c "unbound name daemon" unbound
exit 0
%post
# This adds the proper /etc/rc*.d links for the script
/sbin/chkconfig --add %{name}
%preun
if [ $1 -eq 0 ]; then
/sbin/service %{name} stop >/dev/null 2>&1
/sbin/chkconfig --del %{name}
# remove root jail
rm -f /var/unbound/dev/log /var/unbound/dev/random /var/unbound/etc/localtime /var/unbound/etc/resolv.conf >/dev/null 2>&1
rmdir /var/unbound/dev >/dev/null 2>&1 || :
rmdir /var/unbound/etc >/dev/null 2>&1 || :
rmdir /var/unbound >/dev/null 2>&1 || :
fi
%postun
if [ "$1" -ge "1" ]; then
/sbin/service %{name} condrestart >/dev/null 2>&1 || :
fi
%changelog
* Thu Jul 13 2011 Wouter Wijngaards <wouter@nlnetlabs.nl> - 1.4.8
- ldns required and ldns-devel required for build, no more ldns-builtin.
* Thu Mar 17 2011 Wouter Wijngaards <wouter@nlnetlabs.nl> - 1.4.8
- removed --disable-gost, assume recent openssl on the destination platform.
* Wed Mar 16 2011 Harold Jones <hajones@verisign.com> - 1.4.8
- Bump version number to latest
- Add expat-devel to BuildRequires
- Added --disable-gost for building on CentOS 5.x
- Added --with-ldns-builtin for CentOS 5.x
* Thu May 22 2008 Wouter Wijngaards <wouter@nlnetlabs.nl> - 1.0.0
- contrib changes from Patrick Vande Walle.
* Thu Apr 25 2008 Wouter Wijngaards <wouter@nlnetlabs.nl> - 0.12
- Using parts from ports collection entry by Jaap Akkerhuis.
- Using Fedoraproject wiki guidelines.
* Wed Apr 23 2008 Wouter Wijngaards <wouter@nlnetlabs.nl> - 0.11
- Initial version.

View File

@ -0,0 +1,440 @@
# not ready yet
%{?!with_python: %global with_python 1}
%if %{with_python}
%{!?python_sitelib: %global python_sitelib %(%{__python} -c "from distutils.sysconfig import get_python_lib; print get_python_lib()")}
%{!?python_sitearch: %global python_sitearch %(%{__python} -c "from distutils.sysconfig import get_python_lib; print get_python_lib(1)")}
%endif
Summary: Validating, recursive, and caching DNS(SEC) resolver
Name: unbound
Version: 1.4.13
Release: 1%{?dist}
License: BSD
Url: http://www.nlnetlabs.nl/unbound/
Source: http://www.unbound.net/downloads/%{name}-%{version}.tar.gz
Source1: unbound.init
Source2: unbound.conf
Source3: unbound.munin
Source4: unbound_munin_
Source5: root.key
Source6: dlv.isc.org.key
Patch1: unbound-1.2-glob.patch
Group: System Environment/Daemons
BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n)
BuildRequires: flex, openssl-devel , ldns-devel >= 1.5.0,
BuildRequires: libevent-devel expat-devel
%if %{with_python}
BuildRequires: python-devel swig
%endif
# Required for SVN versions
# BuildRequires: bison
Requires(post): chkconfig
Requires(preun): chkconfig
Requires(preun): initscripts
Requires(postun): initscripts
Requires: ldns >= 1.5.0
Requires(pre): shadow-utils
Obsoletes: dnssec-conf < 1.27-2
Provides: dnssec-conf = 1.27-1
%description
Unbound is a validating, recursive, and caching DNS(SEC) resolver.
The C implementation of Unbound is developed and maintained by NLnet
Labs. It is based on ideas and algorithms taken from a java prototype
developed by Verisign labs, Nominet, Kirei and ep.net.
Unbound is designed as a set of modular components, so that also
DNSSEC (secure DNS) validation and stub-resolvers (that do not run
as a server, but are linked into an application) are easily possible.
%package munin
Summary: Plugin for the munin / munin-node monitoring package
Group: System Environment/Daemons
Requires: munin-node
Requires: %{name} = %{version}-%{release}, bc
%description munin
Plugin for the munin / munin-node monitoring package
%package devel
Summary: Development package that includes the unbound header files
Group: Development/Libraries
Requires: %{name}-libs = %{version}-%{release}, openssl-devel, ldns-devel
%description devel
The devel package contains the unbound library and the include files
%package libs
Summary: Libraries used by the unbound server and client applications
Group: Applications/System
Requires(post): /sbin/ldconfig
Requires(postun): /sbin/ldconfig
Requires: openssl
%description libs
Contains libraries used by the unbound server and client applications
%if %{with_python}
%package python
Summary: Python modules and extensions for unbound
Group: Applications/System
Requires: %{name}-libs = %{version}-%{release}
%description python
Python modules and extensions for unbound
%endif
%prep
%setup -q
%patch1 -p1
%build
%configure --with-ldns= --with-libevent --with-pthreads --with-ssl \
--disable-rpath --disable-static \
--with-conf-file=%{_sysconfdir}/%{name}/unbound.conf \
--with-pidfile=%{_localstatedir}/run/%{name}/%{name}.pid \
%if %{with_python}
--with-pythonmodule --with-pyunbound \
%endif
--enable-sha2 --disable-gost
%{__make} %{?_smp_mflags}
%install
rm -rf %{buildroot}
%{__make} DESTDIR=%{buildroot} install
install -d 0755 %{buildroot}%{_initrddir}
install -m 0755 %{SOURCE1} %{buildroot}%{_initrddir}/unbound
install -m 0755 %{SOURCE2} %{buildroot}%{_sysconfdir}/unbound
# Install munin plugin and its softlinks
install -d 0755 %{buildroot}%{_sysconfdir}/munin/plugin-conf.d
install -m 0644 %{SOURCE3} %{buildroot}%{_sysconfdir}/munin/plugin-conf.d/unbound
install -d 0755 %{buildroot}%{_datadir}/munin/plugins/
install -m 0755 %{SOURCE4} %{buildroot}%{_datadir}/munin/plugins/unbound
for plugin in unbound_munin_hits unbound_munin_queue unbound_munin_memory unbound_munin_by_type unbound_munin_by_class unbound_munin_by_opcode unbound_munin_by_rcode unbound_munin_by_flags unbound_munin_histogram; do
ln -s unbound %{buildroot}%{_datadir}/munin/plugins/$plugin
done
# install root and DLV key
install -m 0644 %{SOURCE5} %{SOURCE6} %{buildroot}%{_sysconfdir}/unbound/
# remove static library from install (fedora packaging guidelines)
rm %{buildroot}%{_libdir}/*.la
%if %{with_python}
rm %{buildroot}%{python_sitearch}/*.la
%endif
mkdir -p %{buildroot}%{_localstatedir}/run/unbound
%clean
rm -rf ${RPM_BUILD_ROOT}
%files
%defattr(-,root,root,-)
%doc doc/README doc/CREDITS doc/LICENSE doc/FEATURES
%attr(0755,root,root) %{_initrddir}/%{name}
%attr(0755,root,root) %dir %{_sysconfdir}/%{name}
%ghost %attr(0755,unbound,unbound) %dir %{_localstatedir}/run/%{name}
%attr(0644,root,root) %config(noreplace) %{_sysconfdir}/%{name}/unbound.conf
%attr(0644,root,root) %config(noreplace) %{_sysconfdir}/%{name}/dlv.isc.org.key
%attr(0644,root,root) %config(noreplace) %{_sysconfdir}/%{name}/root.key
%{_sbindir}/*
%{_mandir}/*/*
%if %{with_python}
%files python
%defattr(-,root,root,-)
%{python_sitearch}/*
%doc libunbound/python/examples/*
%doc pythonmod/examples/*
%endif
%files munin
%defattr(-,root,root,-)
%config(noreplace) %{_sysconfdir}/munin/plugin-conf.d/unbound
%{_datadir}/munin/plugins/unbound*
%files devel
%defattr(-,root,root,-)
%{_libdir}/libunbound.so
%{_includedir}/unbound.h
%doc README
%files libs
%defattr(-,root,root,-)
%{_libdir}/libunbound.so.*
%doc doc/README doc/LICENSE
%pre
getent group unbound >/dev/null || groupadd -r unbound
getent passwd unbound >/dev/null || \
useradd -r -g unbound -d %{_sysconfdir}/unbound -s /sbin/nologin \
-c "Unbound DNS resolver" unbound
exit 0
%post
/sbin/chkconfig --add %{name}
# dnssec-conf used to contain our DLV key, but now we include it via unbound
# If unbound had previously been configured with dnssec-configure, we need
# to migrate the location of the DLV key file (to keep DLV enabled, and because
# unbound won't start with a bad location for a DLV key file.
sed -i "s:/etc/pki/dnssec-keys[/]*dlv:/etc/unbound:" %{_sysconfdir}/unbound/unbound.conf
%post libs -p /sbin/ldconfig
%preun
if [ "$1" -eq 0 ]; then
/sbin/service %{name} stop >/dev/null 2>&1
/sbin/chkconfig --del %{name}
fi
%postun
if [ "$1" -ge "1" ]; then
/sbin/service %{name} condrestart >/dev/null 2>&1 || :
fi
%postun libs -p /sbin/ldconfig
%changelog
* Tue Sep 06 2011 Paul Wouters <paul@xelerance.com> - 1.4.13-1
- Updated to 1.4.13
- Fix install location of pythonmod from sitelib to sitearch
- Removed patches merged in by upstream
- Removed versioned openssl dep, it differs per branch
* Mon Aug 08 2011 Paul Wouters <paul@xelerance.com> - 1.4.12-3
- Added pythonmod docs and examples
- Fix for python module load in the server (Tom Hendrikx)
- No longer enable --enable-debug as it causes degraded performance
under load.
* Mon Jul 18 2011 Paul Wouters <paul@xelerance.com> - 1.4.12-1
- Updated to 1.4.12
* Sun Jul 03 2011 Paul Wouters <paul@xelerance.com> - 1.4.11-1
- Updated to 1.4.11
- removed integrated CVE patch
- updated stock unbound.conf for new options introduced
* Mon Jun 06 2011 Paul Wouters <paul@xelerance.com> - 1.4.10-1
- Added ghost for /var/run/unbound (bz#656710)
* Mon Jun 06 2011 Paul Wouters <paul@xelerance.com> - 1.4.9-3
- rebuilt
* Wed May 25 2011 Paul Wouters <paul@xelerance.com> - 1.4.9-2
- Applied patch for CVE-2011-1922 DoS vulnerability
* Sun Mar 27 2011 Paul Wouters <paul@xelerance.com> - 1.4.9-1
- Updated to 1.4.9
* Sat Feb 12 2011 Paul Wouters <paul@xelerance.com> - 1.4.8-2
- rebuilt
* Tue Jan 25 2011 Paul Wouters <paul@xelerance.com> - 1.4.8-1
- Updated to 1.4.8
- Enable root key for DNSSEC
- Fix unbound-munin to use proper file (could cause excessive logging)
- Build unbound-python per default
- Disable gost as Fedora/EPEL does not allow ECC and has mangled openssl
* Tue Oct 26 2010 Paul Wouters <paul@xelerance.com> - 1.4.5-4
- Revert last build - it was on the wrong branch
* Tue Oct 26 2010 Paul Wouters <paul@xelerance.com> - 1.4.5-3
- Disable do-ipv6 per default - causes severe degradation on non-ipv6 machines
(see comments in inbound.conf)
* Tue Jun 15 2010 Paul Wouters <paul@xelerance.com> - 1.4.5-2
- Bump release - forgot to upload the new tar ball.
* Tue Jun 15 2010 Paul Wouters <paul@xelerance.com> - 1.4.5-1
- Upgraded to 1.4.5
* Mon May 31 2010 Paul Wouters <paul@xelerance.com> - 1.4.4-2
- Added accidentally omitted svn patches to cvs
* Mon May 31 2010 Paul Wouters <paul@xelerance.com> - 1.4.4-1
- Upgraded to 1.4.4 with svn patches
- Obsolete dnssec-conf to ensure it is de-installed
* Thu Mar 11 2010 Paul Wouters <paul@xelerance.com> - 1.4.3-1
- Update to 1.4.3 that fixes 64bit crasher
* Tue Mar 09 2010 Paul Wouters <paul@xelerance.com> - 1.4.2-1
- Updated to 1.4.2
- Updated unbound.conf with new options
- Enabled pre-fetching DNSKEY records (DNSSEC speedup)
- Enabled re-fetching popular records before they expire
- Enabled logging of DNSSEC validation errors
* Mon Mar 01 2010 Paul Wouters <paul@xelerance.com> - 1.4.1-5
- Overriding -D_GNU_SOURCE is no longer needed. This fixes DSO issues
with pthreads
* Wed Feb 24 2010 Paul Wouters <paul@xelerance.com> - 1.4.1-3
- Change make/configure lines to attempt to fix -lphtread linking issue
* Thu Feb 18 2010 Paul Wouters <paul@xelerance.com> - 1.4.1-2
- Removed dependancy for dnssec-conf
- Added ISC DLV key (formerly in dnssec-conf)
- Fixup old DLV locations in unbound.conf file via %%post
- Fix parent child disagreement handling and no-ipv6 present [svn r1953]
* Tue Jan 05 2010 Paul Wouters <paul@xelerance.com> - 1.4.1-1
- Updated to 1.4.1
- Changed %%define to %%global
* Thu Oct 08 2009 Paul Wouters <paul@xelerance.com> - 1.3.4-2
- Bump version
* Thu Oct 08 2009 Paul Wouters <paul@xelerance.com> - 1.3.4-1
- Upgraded to 1.3.4. Security fix with validating NSEC3 records
* Fri Aug 21 2009 Tomas Mraz <tmraz@redhat.com> - 1.3.3-2
- rebuilt with new openssl
* Mon Aug 17 2009 Paul Wouters <paul@xelerance.com> - 1.3.3-1
- Updated to 1.3.3
* Sun Jul 26 2009 Fedora Release Engineering <rel-eng@lists.fedoraproject.org> - 1.3.0-3
- Rebuilt for https://fedoraproject.org/wiki/Fedora_12_Mass_Rebuild
* Sat Jun 20 2009 Paul Wouters <paul@xelerance.com> - 1.3.0-2
- Added missing glob patch to cvs
- Place python macros within the %%with_python check
* Sat Jun 20 2009 Paul Wouters <paul@xelerance.com> - 1.3.0-1
- Updated to 1.3.0
- Added unbound-python sub package. disabled for now
- Patch from svn to fix DLV lookups
- Patches from svn to detect wrong truncated response from BIND 9.6.1 with
minimal-responses)
- Added Default-Start and Default-Stop to unbound.init
- Re-enabled --enable-sha2
- Re-enabled glob.patch
* Wed May 20 2009 Paul Wouters <paul@xelerance.com> - 1.2.1-7
- unbound-iterator.patch was not commited
* Wed May 20 2009 Paul Wouters <paul@xelerance.com> - 1.2.1-6
- Fix for https://bugzilla.redhat.com/show_bug.cgi?id=499793
* Tue Mar 17 2009 Paul Wouters <paul@xelerance.com> - 1.2.1-5
- Use --nocheck to avoid giving an error on missing unbound-remote certs/keys
* Tue Mar 10 2009 Adam Tkac <atkac redhat com> - 1.2.1-4
- enable DNSSEC only if it is enabled in sysconfig/dnssec
* Mon Mar 09 2009 Adam Tkac <atkac redhat com> - 1.2.1-3
- add DNSSEC support to initscript and enabled it per default
- add requires dnssec-conf
* Wed Feb 25 2009 Fedora Release Engineering <rel-eng@lists.fedoraproject.org> - 1.2.1-2
- Rebuilt for https://fedoraproject.org/wiki/Fedora_11_Mass_Rebuild
* Tue Feb 10 2009 Paul Wouters <paul@xelerance.com - 1.2.1-1
- updated to 1.2.1
* Sun Jan 18 2009 Tomas Mraz <tmraz@redhat.com> - 1.2.0-2
- rebuild with new openssl
* Wed Jan 14 2009 Paul Wouters <paul@xelerance.com - 1.2.0-1
- Updated to 1.2.0
- Added dependancy on minimum SSL for CVE-2008-5077
- Added dependancy on bc for unbound-munin
- Added minimum requirement of libevent 1.4.5. Crashes with older versions
(note: libevent is stale in EL-4 and not in EL-5, needs fixing there)
- Removed dependancy on selinux-policy (will get used when available)
- Enable options as per draft-wijngaards-dnsext-resolver-side-mitigation-00.txt
- Enable unwanted-reply-threshold to mitigate against a Kaminsky attack
- Enable val-clean-additional to drop addition unsigned data from signed
response.
- Removed patches (got merged into upstream)
* Mon Jan 5 2009 Paul Wouters <paul@xelerance.com> - 1.1.1-7
- Modified scandir patch to silently fail when wildcard matches nothing
- Patch to allow unbound-checkconf to find empty wildcard matches
* Mon Jan 5 2009 Paul Wouters <paul@xelerance.com> - 1.1.1-6
- Added scandir patch for trusted-keys-file: option, which
is used to load multiple dnssec keys in bind file format
* Mon Dec 8 2008 Paul Wouters <paul@xelerance.com> - 1.1.1-4
- Added Requires: for selinux-policy >= 3.5.13-33 for proper SElinux rules.
* Mon Dec 1 2008 Paul Wouters <paul@xelerance.com> - 1.1.1-3
- We did not own the /etc/unbound directory (#474020)
- Fixed cvs anomalies
* Fri Nov 28 2008 Adam Tkac <atkac redhat com> - 1.1.1-2
- removed all obsolete chroot related stuff
- label control certs after generation correctly
* Thu Nov 20 2008 Paul Wouters <paul@xelerance.com> - 1.1.1-1
- Updated to unbound 1.1.1 which fixes a crasher and
addresses nlnetlabs bug #219
* Wed Nov 19 2008 Paul Wouters <paul@xelerance.com> - 1.1.0-3
- Remove the chroot, obsoleted by SElinux
- Add additional munin plugin links supported by unbound plugin
- Move configuration directory from /var/lib/unbound to /etc/unbound
- Modified unbound.init and unbound.conf to account for chroot changes
- Updated unbound.conf with new available options
- Enabled dns-0x20 protection per default
* Wed Nov 19 2008 Adam Tkac <atkac redhat com> - 1.1.0-2
- unbound-1.1.0-log_open.patch
- make sure log is opened before chroot call
- tracked as http://www.nlnetlabs.nl/bugs/show_bug.cgi?id=219
- removed /dev/log and /var/run/unbound and /etc/resolv.conf from
chroot, not needed
- don't mount files in chroot, it causes problems during updates
- fixed typo in default config file
* Fri Nov 14 2008 Paul Wouters <paul@xelerance.com> - 1.1.0-1
- Updated to version 1.1.0
- Updated unbound.conf's statistics options and remote-control
to work properly for munin
- Added unbound-munin package
- Generate unbound remote-control key/certs on first startup
- Required ldns is now 1.4.0
* Wed Oct 22 2008 Paul Wouters <paul@xelerance.com> - 1.0.2-5
- Only call ldconfig in -libs package
- Move configure into build section
- devel subpackage should only depend on libs subpackage
* Tue Oct 21 2008 Paul Wouters <paul@xelerance.com> - 1.0.2-4
- Fix CFLAGS getting lost in build
- Don't enable interface-automatic:yes because that
causes unbound to listen on 0.0.0.0 instead of 127.0.0.1
* Sun Oct 19 2008 Paul Wouters <paul@xelerance.com> - 1.0.2-3
- Split off unbound-libs, make build verbose
* Thu Oct 9 2008 Paul Wouters <paul@xelerance.com> - 1.0.2-2
- FSB compliance, chroot fixes, initscript fixes
* Thu Sep 11 2008 Paul Wouters <paul@xelerance.com> - 1.0.2-1
- Upgraded to 1.0.2
* Wed Jul 16 2008 Paul Wouters <paul@xelerance.com> - 1.0.1-1
- upgraded to new release
* Wed May 21 2008 Paul Wouters <paul@xelerance.com> - 1.0.0-2
- Build against ldns-1.3.0
* Wed May 21 2008 Paul Wouters <paul@xelerance.com> - 1.0.0-1
- Split of -devel package, fixed dependancies, make rpmlint happy
* Thu Apr 25 2008 Wouter Wijngaards <wouter@nlnetlabs.nl> - 0.12
- Using parts from ports collection entry by Jaap Akkerhuis.
- Using Fedoraproject wiki guidelines.
* Wed Apr 23 2008 Wouter Wijngaards <wouter@nlnetlabs.nl> - 0.11
- Initial version.

View File

@ -0,0 +1,65 @@
@echo off
rem --------------------------------------------------------------
rem -- DNS cache save/load script
rem --
rem -- Version 1.0
rem -- By Yuri Voinov (c) 2014
rem --------------------------------------------------------------
rem Variables
set prefix="C:\Program Files (x86)"
set program_path=%prefix%\Unbound
set uc=%program_path%\unbound-control.exe
set fname="unbound_cache.dmp"
rem Check Unbound installed
if exist %uc% goto start
echo Unbound control not found. Exiting...
exit 1
:start
set arg=%1
if /I "%arg%" == "-h" goto help
if "%arg%" == "" (
echo Loading cache from %program_path%\%fname%
type %program_path%\%fname%|%uc% load_cache
goto end
)
if /I "%arg%" == "-s" (
echo Saving cache to %program_path%\%fname%
%uc% dump_cache>%program_path%\%fname%
echo ok
goto end
)
if /I "%arg%" == "-l" (
echo Loading cache from %program_path%\%fname%
type %program_path%\%fname%|%uc% load_cache
goto end
)
if /I "%arg%" == "-r" (
echo Saving cache to %program_path%\%fname%
%uc% dump_cache>%program_path%\%fname%
echo ok
echo Loading cache from %program_path%\%fname%
type %program_path%\%fname%|%uc% load_cache
goto end
)
:help
echo Usage: unbound_cache.cmd [-s] or [-l] or [-r] or [-h]
echo.
echo l - Load - default mode. Warming up Unbound DNS cache from saved file. cache-ttl must be high value.
echo s - Save - save Unbound DNS cache contents to plain file with domain names.
echo r - Reload - reloadind new cache entries and refresh existing cache
echo h - this screen.
echo Note: Run without any arguments will be in default mode.
echo Also, unbound-control must be configured.
exit 1
:end

View File

@ -0,0 +1,135 @@
#!/sbin/sh
#
# --------------------------------------------------------------
# -- DNS cache save/load script
# --
# -- Version 1.0
# -- By Yuri Voinov (c) 2006, 2014
# --------------------------------------------------------------
#
# ident "@(#)unbound_cache.sh 1.1 14/04/26 YV"
#
#############
# Variables #
#############
# Installation base dir
CONF="/etc/opt/csw/unbound"
BASE="/opt/csw"
# Unbound binaries
UC="$BASE/sbin/unbound-control"
FNAME="unbound_cache.dmp"
# OS utilities
BASENAME=`which basename`
CAT=`which cat`
CUT=`which cut`
ECHO=`which echo`
GETOPT=`which getopt`
ID=`which id`
PRINTF=`which printf`
###############
# Subroutines #
###############
usage_note ()
{
# Script usage note
$ECHO "Usage: `$BASENAME $0` [-s] or [-l] or [-r] or [-h]"
$ECHO
$ECHO "l - Load - default mode. Warming up Unbound DNS cache from saved file. cache-ttl must be high value."
$ECHO "s - Save - save Unbound DNS cache contents to plain file with domain names."
$ECHO "r - Reload - reloadind new cache entries and refresh existing cache"
$ECHO "h - this screen."
$ECHO "Note: Run without any arguments will be in default mode."
$ECHO " Also, unbound-control must be configured."
exit 0
}
root_check ()
{
if [ ! `$ID | $CUT -f1 -d" "` = "uid=0(root)" ]; then
$ECHO "ERROR: You must be super-user to run this script."
exit 1
fi
}
check_uc ()
{
if [ ! -f "$UC" ]; then
$ECHO .
$ECHO "ERROR: $UC not found. Exiting..."
exit 1
fi
}
check_saved_file ()
{
if [ ! -f "$CONF/$FNAME" ]; then
$ECHO .
$ECHO "ERROR: File $CONF/$FNAME does not exists. Save it first."
exit 1
fi
}
save_cache ()
{
# Save unbound cache
$PRINTF "Saving cache in $CONF/$FNAME..."
$UC dump_cache>$CONF/$FNAME
$ECHO "ok"
}
load_cache ()
{
# Load saved cache contents and warmup DNS cache
$PRINTF "Loading cache from saved $CONF/$FNAME..."
check_saved_file
$CAT $CONF/$FNAME|$UC load_cache
}
reload_cache ()
{
# Reloading and refresh existing cache and saved dump
save_cache
load_cache
}
##############
# Main block #
##############
# Root check
root_check
# Check unbound-control
check_uc
# Check command-line arguments
if [ "x$1" = "x" ]; then
# If arguments list empty, load cache by default
load_cache
else
arg_list=$1
# Parse command line
set -- `$GETOPT sSlLrRhH: $arg_list` || {
usage_note 1>&2
}
# Read arguments
for i in $arg_list
do
case $i in
-s | -S) save_cache;;
-l | -L) load_cache;;
-r | -R) reload_cache;;
-h | -H | \?) usage_note;;
esac
break
done
fi
exit 0

Binary file not shown.

560
external/unbound/contrib/unbound_munin_ vendored Executable file
View File

@ -0,0 +1,560 @@
#!/bin/sh
#
# plugin for munin to monitor usage of unbound servers.
# To install copy this to /usr/local/share/munin/plugins/unbound_munin_
# and use munin-node-configure (--suggest, --shell).
#
# (C) 2008 W.C.A. Wijngaards. BSD Licensed.
#
# To install; enable statistics and unbound-control in unbound.conf
# server: extended-statistics: yes
# statistics-cumulative: no
# statistics-interval: 0
# remote-control: control-enable: yes
# Run the command unbound-control-setup to generate the key files.
#
# Environment variables for this script
# statefile - where to put temporary statefile.
# unbound_conf - where the unbound.conf file is located.
# unbound_control - where to find unbound-control executable.
# spoof_warn - what level to warn about spoofing
# spoof_crit - what level to crit about spoofing
#
# You can set them in your munin/plugin-conf.d/plugins.conf file
# with:
# [unbound*]
# user root
# env.statefile /usr/local/var/munin/plugin-state/unbound-state
# env.unbound_conf /usr/local/etc/unbound/unbound.conf
# env.unbound_control /usr/local/sbin/unbound-control
# env.spoof_warn 1000
# env.spoof_crit 100000
#
# This plugin can create different graphs depending on what name
# you link it as (with ln -s) into the plugins directory
# You can link it multiple times.
# If you are only a casual user, the _hits and _by_type are most interesting,
# possibly followed by _by_rcode.
#
# unbound_munin_hits - base volume, cache hits, unwanted traffic
# unbound_munin_queue - to monitor the internal requestlist
# unbound_munin_memory - memory usage
# unbound_munin_by_type - incoming queries by type
# unbound_munin_by_class - incoming queries by class
# unbound_munin_by_opcode - incoming queries by opcode
# unbound_munin_by_rcode - answers by rcode, validation status
# unbound_munin_by_flags - incoming queries by flags
# unbound_munin_histogram - histogram of query resolving times
#
# Magic markers - optional - used by installation scripts and
# munin-config: (originally contrib family but munin-node-configure ignores it)
#
#%# family=auto
#%# capabilities=autoconf suggest
# POD documentation
: <<=cut
=head1 NAME
unbound_munin_ - Munin plugin to monitor the Unbound DNS resolver.
=head1 APPLICABLE SYSTEMS
System with unbound daemon.
=head1 CONFIGURATION
[unbound*]
user root
env.statefile /usr/local/var/munin/plugin-state/unbound-state
env.unbound_conf /usr/local/etc/unbound/unbound.conf
env.unbound_control /usr/local/sbin/unbound-control
env.spoof_warn 1000
env.spoof_crit 100000
Use the .env settings to override the defaults.
=head1 USAGE
Can be used to present different graphs. Use ln -s for that name in
the plugins directory to enable the graph.
unbound_munin_hits - base volume, cache hits, unwanted traffic
unbound_munin_queue - to monitor the internal requestlist
unbound_munin_memory - memory usage
unbound_munin_by_type - incoming queries by type
unbound_munin_by_class - incoming queries by class
unbound_munin_by_opcode - incoming queries by opcode
unbound_munin_by_rcode - answers by rcode, validation status
unbound_munin_by_flags - incoming queries by flags
unbound_munin_histogram - histogram of query resolving times
=head1 AUTHOR
Copyright 2008 W.C.A. Wijngaards
=head1 LICENSE
BSD
=cut
state=${statefile:-/usr/local/var/munin/plugin-state/unbound-state}
conf=${unbound_conf:-/usr/local/etc/unbound/unbound.conf}
ctrl=${unbound_control:-/usr/local/sbin/unbound-control}
warn=${spoof_warn:-1000}
crit=${spoof_crit:-100000}
lock=$state.lock
# number of seconds between polling attempts.
# makes the statefile hang around for at least this many seconds,
# so that multiple links of this script can share the results.
lee=55
# to keep things within 19 characters
ABBREV="-e s/total/t/ -e s/thread/t/ -e s/num/n/ -e s/query/q/ -e s/answer/a/ -e s/unwanted/u/ -e s/requestlist/ql/ -e s/type/t/ -e s/class/c/ -e s/opcode/o/ -e s/rcode/r/ -e s/edns/e/ -e s/mem/m/ -e s/cache/c/ -e s/mod/m/"
# get value from $1 into return variable $value
get_value ( ) {
value="`grep '^'$1'=' $state | sed -e 's/^.*=//'`"
if test "$value"x = ""x; then
value="0"
fi
}
# download the state from the unbound server.
get_state ( ) {
# obtain lock for fetching the state
# because there is a race condition in fetching and writing to file
# see if the lock is stale, if so, take it
if test -f $lock ; then
pid="`cat $lock 2>&1`"
kill -0 "$pid" >/dev/null 2>&1
if test $? -ne 0 -a "$pid" != $$ ; then
echo $$ >$lock
fi
fi
i=0
while test ! -f $lock || test "`cat $lock 2>&1`" != $$; do
while test -f $lock; do
# wait
i=`expr $i + 1`
if test $i -gt 1000; then
sleep 1;
fi
if test $i -gt 1500; then
echo "error locking $lock" "=" `cat $lock`
rm -f $lock
exit 1
fi
done
# try to get it
echo $$ >$lock
done
# do not refetch if the file exists and only LEE seconds old
if test -f $state; then
now=`date +%s`
get_value "time.now"
value="`echo $value | sed -e 's/\..*$//'`"
if test $now -lt `expr $value + $lee`; then
rm -f $lock
return
fi
fi
$ctrl -c $conf stats > $state
if test $? -ne 0; then
echo "error retrieving data from unbound server"
rm -f $lock
exit 1
fi
rm -f $lock
}
if test "$1" = "autoconf" ; then
if test ! -f $conf; then
echo no "($conf does not exist)"
exit 1
fi
if test ! -d `dirname $state`; then
echo no "(`dirname $state` directory does not exist)"
exit 1
fi
echo yes
exit 0
fi
if test "$1" = "suggest" ; then
echo "hits"
echo "queue"
echo "memory"
echo "by_type"
echo "by_class"
echo "by_opcode"
echo "by_rcode"
echo "by_flags"
echo "histogram"
exit 0
fi
# determine my type, by name
id=`echo $0 | sed -e 's/^.*unbound_munin_//'`
if test "$id"x = ""x; then
# some default to keep people sane.
id="hits"
fi
# if $1 exists in statefile, config is echoed with label $2
exist_config ( ) {
mn=`echo $1 | sed $ABBREV | tr . _`
if grep '^'$1'=' $state >/dev/null 2>&1; then
echo "$mn.label $2"
echo "$mn.min 0"
fi
}
# print label and min 0 for a name $1 in unbound format
p_config ( ) {
mn=`echo $1 | sed $ABBREV | tr . _`
echo $mn.label "$2"
echo $mn.min 0
}
if test "$1" = "config" ; then
if test ! -f $state; then
get_state
fi
case $id in
hits)
echo "graph_title Unbound DNS traffic and cache hits"
echo "graph_args --base 1000 -l 0"
echo "graph_vlabel queries / second"
echo "graph_category DNS"
for x in `grep "^thread[0-9][0-9]*\.num\.queries=" $state |
sed -e 's/=.*//'`; do
exist_config $x "queries handled by `basename $x .num.queries`"
done
p_config "total.num.queries" "total queries from clients"
p_config "total.num.cachehits" "cache hits"
p_config "total.num.prefetch" "cache prefetch"
p_config "num.query.tcp" "TCP queries"
p_config "num.query.tcpout" "TCP out queries"
p_config "num.query.ipv6" "IPv6 queries"
p_config "unwanted.queries" "queries that failed acl"
p_config "unwanted.replies" "unwanted or unsolicited replies"
echo "u_replies.warning $warn"
echo "u_replies.critical $crit"
echo "graph_info DNS queries to the recursive resolver. The unwanted replies could be innocent duplicate packets, late replies, or spoof threats."
;;
queue)
echo "graph_title Unbound requestlist size"
echo "graph_args --base 1000 -l 0"
echo "graph_vlabel number of queries"
echo "graph_category DNS"
p_config "total.requestlist.avg" "Average size of queue on insert"
p_config "total.requestlist.max" "Max size of queue (in 5 min)"
p_config "total.requestlist.overwritten" "Number of queries replaced by new ones"
p_config "total.requestlist.exceeded" "Number of queries dropped due to lack of space"
echo "graph_info The queries that did not hit the cache and need recursion service take up space in the requestlist. If there are too many queries, first queries get overwritten, and at last resort dropped."
;;
memory)
echo "graph_title Unbound memory usage"
echo "graph_args --base 1024 -l 0"
echo "graph_vlabel memory used in bytes"
echo "graph_category DNS"
p_config "mem.total.sbrk" "Total memory"
p_config "mem.cache.rrset" "RRset cache memory"
p_config "mem.cache.message" "Message cache memory"
p_config "mem.mod.iterator" "Iterator module memory"
p_config "mem.mod.validator" "Validator module and key cache memory"
p_config "msg.cache.count" "msg cache count"
p_config "rrset.cache.count" "rrset cache count"
p_config "infra.cache.count" "infra cache count"
p_config "key.cache.count" "key cache count"
echo "graph_info The memory used by unbound."
;;
by_type)
echo "graph_title Unbound DNS queries by type"
echo "graph_args --base 1000 -l 0"
echo "graph_vlabel queries / second"
echo "graph_category DNS"
for x in `grep "^num.query.type" $state`; do
nm=`echo $x | sed -e 's/=.*$//'`
tp=`echo $nm | sed -e s/num.query.type.//`
p_config "$nm" "$tp"
done
echo "graph_info queries by DNS RR type queried for"
;;
by_class)
echo "graph_title Unbound DNS queries by class"
echo "graph_args --base 1000 -l 0"
echo "graph_vlabel queries / second"
echo "graph_category DNS"
for x in `grep "^num.query.class" $state`; do
nm=`echo $x | sed -e 's/=.*$//'`
tp=`echo $nm | sed -e s/num.query.class.//`
p_config "$nm" "$tp"
done
echo "graph_info queries by DNS RR class queried for."
;;
by_opcode)
echo "graph_title Unbound DNS queries by opcode"
echo "graph_args --base 1000 -l 0"
echo "graph_vlabel queries / second"
echo "graph_category DNS"
for x in `grep "^num.query.opcode" $state`; do
nm=`echo $x | sed -e 's/=.*$//'`
tp=`echo $nm | sed -e s/num.query.opcode.//`
p_config "$nm" "$tp"
done
echo "graph_info queries by opcode in the query packet."
;;
by_rcode)
echo "graph_title Unbound DNS answers by return code"
echo "graph_args --base 1000 -l 0"
echo "graph_vlabel answer packets / second"
echo "graph_category DNS"
for x in `grep "^num.answer.rcode" $state`; do
nm=`echo $x | sed -e 's/=.*$//'`
tp=`echo $nm | sed -e s/num.answer.rcode.//`
p_config "$nm" "$tp"
done
p_config "num.answer.secure" "answer secure"
p_config "num.answer.bogus" "answer bogus"
p_config "num.rrset.bogus" "num rrsets marked bogus"
echo "graph_info answers sorted by return value. rrsets bogus is the number of rrsets marked bogus per second by the validator"
;;
by_flags)
echo "graph_title Unbound DNS incoming queries by flags"
echo "graph_args --base 1000 -l 0"
echo "graph_vlabel queries / second"
echo "graph_category DNS"
p_config "num.query.flags.QR" "QR (query reply) flag"
p_config "num.query.flags.AA" "AA (auth answer) flag"
p_config "num.query.flags.TC" "TC (truncated) flag"
p_config "num.query.flags.RD" "RD (recursion desired) flag"
p_config "num.query.flags.RA" "RA (rec avail) flag"
p_config "num.query.flags.Z" "Z (zero) flag"
p_config "num.query.flags.AD" "AD (auth data) flag"
p_config "num.query.flags.CD" "CD (check disabled) flag"
p_config "num.query.edns.present" "EDNS OPT present"
p_config "num.query.edns.DO" "DO (DNSSEC OK) flag"
echo "graph_info This graphs plots the flags inside incoming queries. For example, if QR, AA, TC, RA, Z flags are set, the query can be rejected. RD, AD, CD and DO are legitimately set by some software."
;;
histogram)
echo "graph_title Unbound DNS histogram of reply time"
echo "graph_args --base 1000 -l 0"
echo "graph_vlabel queries / second"
echo "graph_category DNS"
echo hcache.label "cache hits"
echo hcache.min 0
echo hcache.draw AREA
echo hcache.colour 999999
echo h64ms.label "0 msec - 66 msec"
echo h64ms.min 0
echo h64ms.draw STACK
echo h64ms.colour 0000FF
echo h128ms.label "66 msec - 131 msec"
echo h128ms.min 0
echo h128ms.colour 1F00DF
echo h128ms.draw STACK
echo h256ms.label "131 msec - 262 msec"
echo h256ms.min 0
echo h256ms.draw STACK
echo h256ms.colour 3F00BF
echo h512ms.label "262 msec - 524 msec"
echo h512ms.min 0
echo h512ms.draw STACK
echo h512ms.colour 5F009F
echo h1s.label "524 msec - 1 sec"
echo h1s.min 0
echo h1s.draw STACK
echo h1s.colour 7F007F
echo h2s.label "1 sec - 2 sec"
echo h2s.min 0
echo h2s.draw STACK
echo h2s.colour 9F005F
echo h4s.label "2 sec - 4 sec"
echo h4s.min 0
echo h4s.draw STACK
echo h4s.colour BF003F
echo h8s.label "4 sec - 8 sec"
echo h8s.min 0
echo h8s.draw STACK
echo h8s.colour DF001F
echo h16s.label "8 sec - ..."
echo h16s.min 0
echo h16s.draw STACK
echo h16s.colour FF0000
echo "graph_info Histogram of the reply times for queries."
;;
esac
exit 0
fi
# do the stats itself
get_state
# get the time elapsed
get_value "time.elapsed"
if test $value = 0 || test $value = "0.000000"; then
echo "error: time elapsed 0 or could not retrieve data"
exit 1
fi
elapsed="$value"
# print value for $1 / elapsed
print_qps ( ) {
mn=`echo $1 | sed $ABBREV | tr . _`
get_value $1
echo "$mn.value" `echo scale=6';' $value / $elapsed | bc `
}
# print qps if line already found in $2
print_qps_line ( ) {
mn=`echo $1 | sed $ABBREV | tr . _`
value="`echo $2 | sed -e 's/^.*=//'`"
echo "$mn.value" `echo scale=6';' $value / $elapsed | bc `
}
# print value for $1
print_value ( ) {
mn=`echo $1 | sed $ABBREV | tr . _`
get_value $1
echo "$mn.value" $value
}
case $id in
hits)
for x in `grep "^thread[0-9][0-9]*\.num\.queries=" $state |
sed -e 's/=.*//'` total.num.queries \
total.num.cachehits total.num.prefetch num.query.tcp \
num.query.tcpout num.query.ipv6 unwanted.queries \
unwanted.replies; do
if grep "^"$x"=" $state >/dev/null 2>&1; then
print_qps $x
fi
done
;;
queue)
for x in total.requestlist.avg total.requestlist.max \
total.requestlist.overwritten total.requestlist.exceeded; do
print_value $x
done
;;
memory)
mn=`echo mem.total.sbrk | sed $ABBREV | tr . _`
get_value 'mem.total.sbrk'
if test $value -eq 0; then
chk=`echo $ctrl | sed -e 's/-control$/-checkconf/'`
pidf=`$chk -o pidfile $conf 2>&1`
pid=`cat $pidf 2>&1`
value=`ps -p "$pid" -o rss= 2>&1`
if test "`expr $value + 1 - 1 2>&1`" -eq "$value" 2>&1; then
value=`expr $value \* 1024`
else
value=0
fi
fi
echo "$mn.value" $value
for x in mem.cache.rrset mem.cache.message mem.mod.iterator \
mem.mod.validator msg.cache.count rrset.cache.count \
infra.cache.count key.cache.count; do
print_value $x
done
;;
by_type)
for x in `grep "^num.query.type" $state`; do
nm=`echo $x | sed -e 's/=.*$//'`
print_qps_line $nm $x
done
;;
by_class)
for x in `grep "^num.query.class" $state`; do
nm=`echo $x | sed -e 's/=.*$//'`
print_qps_line $nm $x
done
;;
by_opcode)
for x in `grep "^num.query.opcode" $state`; do
nm=`echo $x | sed -e 's/=.*$//'`
print_qps_line $nm $x
done
;;
by_rcode)
for x in `grep "^num.answer.rcode" $state`; do
nm=`echo $x | sed -e 's/=.*$//'`
print_qps_line $nm $x
done
print_qps "num.answer.secure"
print_qps "num.answer.bogus"
print_qps "num.rrset.bogus"
;;
by_flags)
for x in num.query.flags.QR num.query.flags.AA num.query.flags.TC num.query.flags.RD num.query.flags.RA num.query.flags.Z num.query.flags.AD num.query.flags.CD num.query.edns.present num.query.edns.DO; do
print_qps $x
done
;;
histogram)
get_value total.num.cachehits
echo hcache.value `echo scale=6';' $value / $elapsed | bc `
r=0
for x in histogram.000000.000000.to.000000.000001 \
histogram.000000.000001.to.000000.000002 \
histogram.000000.000002.to.000000.000004 \
histogram.000000.000004.to.000000.000008 \
histogram.000000.000008.to.000000.000016 \
histogram.000000.000016.to.000000.000032 \
histogram.000000.000032.to.000000.000064 \
histogram.000000.000064.to.000000.000128 \
histogram.000000.000128.to.000000.000256 \
histogram.000000.000256.to.000000.000512 \
histogram.000000.000512.to.000000.001024 \
histogram.000000.001024.to.000000.002048 \
histogram.000000.002048.to.000000.004096 \
histogram.000000.004096.to.000000.008192 \
histogram.000000.008192.to.000000.016384 \
histogram.000000.016384.to.000000.032768 \
histogram.000000.032768.to.000000.065536; do
get_value $x
r=`expr $r + $value`
done
echo h64ms.value `echo scale=6';' $r / $elapsed | bc `
get_value histogram.000000.065536.to.000000.131072
echo h128ms.value `echo scale=6';' $value / $elapsed | bc `
get_value histogram.000000.131072.to.000000.262144
echo h256ms.value `echo scale=6';' $value / $elapsed | bc `
get_value histogram.000000.262144.to.000000.524288
echo h512ms.value `echo scale=6';' $value / $elapsed | bc `
get_value histogram.000000.524288.to.000001.000000
echo h1s.value `echo scale=6';' $value / $elapsed | bc `
get_value histogram.000001.000000.to.000002.000000
echo h2s.value `echo scale=6';' $value / $elapsed | bc `
get_value histogram.000002.000000.to.000004.000000
echo h4s.value `echo scale=6';' $value / $elapsed | bc `
get_value histogram.000004.000000.to.000008.000000
echo h8s.value `echo scale=6';' $value / $elapsed | bc `
r=0
for x in histogram.000008.000000.to.000016.000000 \
histogram.000016.000000.to.000032.000000 \
histogram.000032.000000.to.000064.000000 \
histogram.000064.000000.to.000128.000000 \
histogram.000128.000000.to.000256.000000 \
histogram.000256.000000.to.000512.000000 \
histogram.000512.000000.to.001024.000000 \
histogram.001024.000000.to.002048.000000 \
histogram.002048.000000.to.004096.000000 \
histogram.004096.000000.to.008192.000000 \
histogram.008192.000000.to.016384.000000 \
histogram.016384.000000.to.032768.000000 \
histogram.032768.000000.to.065536.000000 \
histogram.065536.000000.to.131072.000000 \
histogram.131072.000000.to.262144.000000 \
histogram.262144.000000.to.524288.000000; do
get_value $x
r=`expr $r + $value`
done
echo h16s.value `echo scale=6';' $r / $elapsed | bc `
;;
esac

View File

@ -0,0 +1,305 @@
diff --git a/daemon/remote.c b/daemon/remote.c
index a2b2204..b6990f3 100644
--- a/daemon/remote.c
+++ b/daemon/remote.c
@@ -81,6 +81,11 @@
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
+#ifdef HAVE_PWD_H
+#include <pwd.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#endif
/* just for portability */
#ifdef SQ
@@ -235,7 +240,8 @@ void daemon_remote_delete(struct daemon_remote* rc)
* @return false on failure.
*/
static int
-add_open(const char* ip, int nr, struct listen_port** list, int noproto_is_err)
+add_open(const char* ip, int nr, struct listen_port** list, int noproto_is_err,
+ struct config_file* cfg)
{
struct addrinfo hints;
struct addrinfo* res;
@@ -246,29 +252,74 @@ add_open(const char* ip, int nr, struct listen_port** list, int noproto_is_err)
snprintf(port, sizeof(port), "%d", nr);
port[sizeof(port)-1]=0;
memset(&hints, 0, sizeof(hints));
- hints.ai_socktype = SOCK_STREAM;
- hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
- if((r = getaddrinfo(ip, port, &hints, &res)) != 0 || !res) {
-#ifdef USE_WINSOCK
- if(!noproto_is_err && r == EAI_NONAME) {
- /* tried to lookup the address as name */
- return 1; /* return success, but do nothing */
+
+ if(ip[0] == '/') {
+ /* This looks like UNIX socket! */
+ fd = create_domain_accept_sock(ip);
+/*
+ * When unbound starts, it first creates a socket and then
+ * drops privs, so the socket is created as root user.
+ * This is fine, but we would like to set _unbound user group
+ * for this socket, and permissions should be 0660 so only
+ * root and _unbound group members can invoke unbound-control.
+ * The username used here is the same as username that unbound
+ * uses for its worker processes.
+ */
+
+/*
+ * Note: this code is an exact copy of code from daemon.c
+ * Normally this should be either wrapped into a function,
+ * or gui/gid values should be retrieved at config parsing time
+ * and then stored in configfile structure.
+ * This requires action from unbound developers!
+*/
+#ifdef HAVE_GETPWNAM
+ struct passwd *pwd = NULL;
+ uid_t uid;
+ gid_t gid;
+ /* initialize, but not to 0 (root) */
+ memset(&uid, 112, sizeof(uid));
+ memset(&gid, 112, sizeof(gid));
+ log_assert(cfg);
+
+ if(cfg->username && cfg->username[0]) {
+ if((pwd = getpwnam(cfg->username)) == NULL)
+ fatal_exit("user '%s' does not exist.",
+ cfg->username);
+ uid = pwd->pw_uid;
+ gid = pwd->pw_gid;
+ endpwent();
}
+
+ chown(ip, 0, gid);
+ chmod(ip, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
+#endif
+ } else {
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
+ if((r = getaddrinfo(ip, port, &hints, &res)) != 0 || !res) {
+#ifdef USE_WINSOCK
+ if(!noproto_is_err && r == EAI_NONAME) {
+ /* tried to lookup the address as name */
+ return 1; /* return success, but do nothing */
+ }
#endif /* USE_WINSOCK */
- log_err("control interface %s:%s getaddrinfo: %s %s",
- ip?ip:"default", port, gai_strerror(r),
+ log_err("control interface %s:%s getaddrinfo: %s %s",
+ ip?ip:"default", port, gai_strerror(r),
#ifdef EAI_SYSTEM
r==EAI_SYSTEM?(char*)strerror(errno):""
#else
""
#endif
);
- return 0;
+ return 0;
+ }
+
+ /* open fd */
+ fd = create_tcp_accept_sock(res, 1, &noproto);
+ freeaddrinfo(res);
}
- /* open fd */
- fd = create_tcp_accept_sock(res, 1, &noproto);
- freeaddrinfo(res);
if(fd == -1 && noproto) {
if(!noproto_is_err)
return 1; /* return success, but do nothing */
@@ -305,7 +356,7 @@ struct listen_port* daemon_remote_open_ports(struct config_file* cfg)
if(cfg->control_ifs) {
struct config_strlist* p;
for(p = cfg->control_ifs; p; p = p->next) {
- if(!add_open(p->str, cfg->control_port, &l, 1)) {
+ if(!add_open(p->str, cfg->control_port, &l, 1, cfg)) {
listening_ports_free(l);
return NULL;
}
@@ -313,12 +364,12 @@ struct listen_port* daemon_remote_open_ports(struct config_file* cfg)
} else {
/* defaults */
if(cfg->do_ip6 &&
- !add_open("::1", cfg->control_port, &l, 0)) {
+ !add_open("::1", cfg->control_port, &l, 0, cfg)) {
listening_ports_free(l);
return NULL;
}
if(cfg->do_ip4 &&
- !add_open("127.0.0.1", cfg->control_port, &l, 1)) {
+ !add_open("127.0.0.1", cfg->control_port, &l, 1, cfg)) {
listening_ports_free(l);
return NULL;
}
diff --git a/services/listen_dnsport.c b/services/listen_dnsport.c
index ea7ec3a..4cb04e2 100644
--- a/services/listen_dnsport.c
+++ b/services/listen_dnsport.c
@@ -55,6 +55,10 @@
#endif
#include <fcntl.h>
+#ifndef USE_WINSOCK
+#include <sys/un.h>
+#endif
+
/** number of queued TCP connections for listen() */
#define TCP_BACKLOG 5
@@ -376,6 +380,53 @@ create_udp_sock(int family, int socktype, struct sockaddr* addr,
}
int
+create_domain_accept_sock(char *path) {
+ int s;
+ struct sockaddr_un unixaddr;
+
+#ifndef USE_WINSOCK
+ unixaddr.sun_len = sizeof(unixaddr);
+ unixaddr.sun_family = AF_UNIX;
+ strlcpy(unixaddr.sun_path, path, 104);
+
+ if((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
+ log_err("Cannot create UNIX socket %s (%s)",
+ path, strerror(errno));
+ return -1;
+ }
+
+ if(unlink(path) && errno != ENOENT) {
+ /* The socket already exists and cannot be removed */
+ log_err("Cannot remove old UNIX socket %s (%s)",
+ path, strerror(errno));
+ return -1;
+ }
+
+ if(bind(s, (struct sockaddr *) &unixaddr,
+ sizeof(struct sockaddr_un)) == -1) {
+ log_err("Cannot bind UNIX socket %s (%s)",
+ path, strerror(errno));
+ return -1;
+ }
+
+ if(!fd_set_nonblock(s)) {
+ log_err("Cannot set non-blocking mode");
+ return -1;
+ }
+
+ if(listen(s, TCP_BACKLOG) == -1) {
+ log_err("can't listen: %s", strerror(errno));
+ return -1;
+ }
+
+ return s;
+#else
+ log_err("UNIX sockets are not supported");
+ return -1;
+#endif
+}
+
+int
create_tcp_accept_sock(struct addrinfo *addr, int v6only, int* noproto)
{
int s;
diff --git a/smallapp/unbound-control.c b/smallapp/unbound-control.c
index a872f92..10631fd 100644
--- a/smallapp/unbound-control.c
+++ b/smallapp/unbound-control.c
@@ -59,6 +59,8 @@
#include "util/locks.h"
#include "util/net_help.h"
+#include <sys/un.h>
+
/** Give unbound-control usage, and exit (1). */
static void
usage()
@@ -158,6 +160,7 @@ contact_server(const char* svr, struct config_file* cfg, int statuscmd)
{
struct sockaddr_storage addr;
socklen_t addrlen;
+ int addrfamily = 0;
int fd;
/* use svr or the first config entry */
if(!svr) {
@@ -176,12 +179,21 @@ contact_server(const char* svr, struct config_file* cfg, int statuscmd)
if(strchr(svr, '@')) {
if(!extstrtoaddr(svr, &addr, &addrlen))
fatal_exit("could not parse IP@port: %s", svr);
+ } else if(svr[0] == '/') {
+ struct sockaddr_un* unixsock = (struct sockaddr_un *) &addr;
+ unixsock->sun_family = AF_UNIX;
+ unixsock->sun_len = sizeof(unixsock);
+ strlcpy(unixsock->sun_path, svr, 104);
+ addrlen = sizeof(struct sockaddr_un);
+ addrfamily = AF_UNIX;
} else {
if(!ipstrtoaddr(svr, cfg->control_port, &addr, &addrlen))
fatal_exit("could not parse IP: %s", svr);
}
- fd = socket(addr_is_ip6(&addr, addrlen)?AF_INET6:AF_INET,
- SOCK_STREAM, 0);
+
+ if(addrfamily != AF_UNIX)
+ addrfamily = addr_is_ip6(&addr, addrlen)?AF_INET6:AF_INET;
+ fd = socket(addrfamily, SOCK_STREAM, 0);
if(fd == -1) {
#ifndef USE_WINSOCK
fatal_exit("socket: %s", strerror(errno));
diff --git a/util/net_help.c b/util/net_help.c
index b3136a3..5b5b4a3 100644
--- a/util/net_help.c
+++ b/util/net_help.c
@@ -45,6 +45,7 @@
#include "util/module.h"
#include "util/regional.h"
#include <fcntl.h>
+#include <sys/un.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
@@ -135,7 +136,7 @@ log_addr(enum verbosity_value v, const char* str,
{
uint16_t port;
const char* family = "unknown";
- char dest[100];
+ char dest[108];
int af = (int)((struct sockaddr_in*)addr)->sin_family;
void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
if(verbosity < v)
@@ -148,15 +149,23 @@ log_addr(enum verbosity_value v, const char* str,
case AF_UNIX: family="unix"; break;
default: break;
}
- if(inet_ntop(af, sinaddr, dest, (socklen_t)sizeof(dest)) == 0) {
- strncpy(dest, "(inet_ntop error)", sizeof(dest));
+
+ if(af != AF_UNIX) {
+ if(inet_ntop(af, sinaddr, dest, (socklen_t)sizeof(dest)) == 0) {
+ strncpy(dest, "(inet_ntop error)", sizeof(dest));
+ }
+ dest[sizeof(dest)-1] = 0;
+ port = ntohs(((struct sockaddr_in*)addr)->sin_port);
+ if(verbosity >= 4)
+ verbose(v, "%s %s %s port %d (len %d)", str, family,
+ dest, (int)port, (int)addrlen);
+ else verbose(v, "%s %s port %d", str, dest, (int)port);
+ } else {
+ struct sockaddr_un* unixsock;
+ unixsock = (struct sockaddr_un *) addr;
+ strlcpy(dest, unixsock->sun_path, sizeof(dest));
+ verbose(v, "%s %s %s", str, family, dest);
}
- dest[sizeof(dest)-1] = 0;
- port = ntohs(((struct sockaddr_in*)addr)->sin_port);
- if(verbosity >= 4)
- verbose(v, "%s %s %s port %d (len %d)", str, family, dest,
- (int)port, (int)addrlen);
- else verbose(v, "%s %s port %d", str, dest, (int)port);
}
int

158
external/unbound/contrib/update-anchor.sh vendored Executable file
View File

@ -0,0 +1,158 @@
#!/bin/sh
# update-anchor.sh, update a trust anchor.
# Copyright 2008, W.C.A. Wijngaards
# This file is BSD licensed, see doc/LICENSE.
# which validating lookup to use.
ubhost=unbound-host
usage ( )
{
echo "usage: update-anchor [-r hs] [-b] <zone name> <trust anchor file>"
echo " performs an update of trust anchor file"
echo " the trust anchor file is overwritten with the latest keys"
echo " the trust anchor file should contain only keys for one zone"
echo " -b causes keyfile to be made in bind format."
echo " without -b the file is made in unbound format."
echo " "
echo "alternate:"
echo " update-anchor [-r hints] [-b] -d directory"
echo " update all <zone>.anchor files in the directory."
echo " "
echo " name the files br.anchor se.anchor ..., and include them in"
echo " the validating resolver config file."
echo " put keys for the root in a file with the name root.anchor."
echo ""
echo "-r root.hints use different root hints. Strict option order."
echo ""
echo "Exit code 0 means anchors updated, 1 no changes, others are errors."
exit 2
}
if test $# -eq 0; then
usage
fi
bindformat="no"
filearg='-f'
roothints=""
if test X"$1" = "X-r"; then
shift
roothints="$1"
shift
fi
if test X"$1" = "X-b"; then
shift
bindformat="yes"
filearg='-F'
fi
if test $# -ne 2; then
echo "arguments wrong."
usage
fi
do_update ( ) {
# arguments: <zonename> <keyfile>
zonename="$1"
keyfile="$2"
tmpfile="/tmp/update-anchor.$$"
tmp2=$tmpfile.2
tmp3=$tmpfile.3
rh=""
if test -n "$roothints"; then
echo "server: root-hints: '$roothints'" > $tmp3
rh="-C $tmp3"
fi
$ubhost -v $rh $filearg "$keyfile" -t DNSKEY "$zonename" >$tmpfile
if test $? -ne 0; then
rm -f $tmpfile
echo "Error: Could not update zone $zonename anchor file $keyfile"
echo "Cause: $ubhost lookup failed"
echo " (Is the domain decommissioned? Is connectivity lost?)"
return 2
fi
# has the lookup been DNSSEC validated?
if grep '(secure)$' $tmpfile >/dev/null 2>&1; then
:
else
rm -f $tmpfile
echo "Error: Could not update zone $zonename anchor file $keyfile"
echo "Cause: result of lookup was not secure"
echo " (keys too far out of date? domain changed ownership? need root hints?)"
return 3
fi
if test $bindformat = "yes"; then
# are there any KSK keys on board?
echo 'trusted-keys {' > "$tmp2"
if grep ' has DNSKEY record 257' $tmpfile >/dev/null 2>&1; then
# store KSK keys in anchor file
grep '(secure)$' $tmpfile | \
grep ' has DNSKEY record 257' | \
sed -e 's/ (secure)$/";/' | \
sed -e 's/ has DNSKEY record \([0-9]*\) \([0-9]*\) \([0-9]*\) /. \1 \2 \3 "/' | \
sed -e 's/^\.\././' | sort >> "$tmp2"
else
# store all keys in the anchor file
grep '(secure)$' $tmpfile | \
sed -e 's/ (secure)$/";/' | \
sed -e 's/ has DNSKEY record \([0-9]*\) \([0-9]*\) \([0-9]*\) /. \1 \2 \3 "/' | \
sed -e 's/^\.\././' | sort >> "$tmp2"
fi
echo '};' >> "$tmp2"
else #not bindformat
# are there any KSK keys on board?
if grep ' has DNSKEY record 257' $tmpfile >/dev/null 2>&1; then
# store KSK keys in anchor file
grep '(secure)$' $tmpfile | \
grep ' has DNSKEY record 257' | \
sed -e 's/ (secure)$//' | \
sed -e 's/ has DNSKEY record /. IN DNSKEY /' | \
sed -e 's/^\.\././' | sort > "$tmp2"
else
# store all keys in the anchor file
grep '(secure)$' $tmpfile | \
sed -e 's/ (secure)$//' | \
sed -e 's/ has DNSKEY record /. IN DNSKEY /' | \
sed -e 's/^\.\././' | sort > "$tmp2"
fi
fi # endif-bindformat
# copy over if changed
diff $tmp2 $keyfile >/dev/null 2>&1
if test $? -eq 1; then # 0 means no change, 2 means trouble.
cat $tmp2 > $keyfile
no_updated=0
echo "$zonename key file $keyfile updated."
else
echo "$zonename key file $keyfile unchanged."
fi
rm -f $tmpfile $tmp2 $tmp3
}
no_updated=1
if test X"$1" = "X-d"; then
tdir="$2"
echo "start updating in $2"
for x in $tdir/*.anchor; do
if test `basename "$x"` = "root.anchor"; then
zname="."
else
zname=`basename "$x" .anchor`
fi
do_update "$zname" "$x"
done
echo "done updating in $2"
else
# regular invocation
if test X"$1" = "X."; then
zname="$1"
else
# strip trailing dot from zone name
zname="`echo $1 | sed -e 's/\.$//'`"
fi
kfile="$2"
do_update $zname $kfile
fi
exit $no_updated

View File

@ -0,0 +1,117 @@
#!/bin/sh
# validation reporter - reports validation failures to a collection server.
# Copyright NLnet Labs, 2010
# BSD license.
###
# Here is the configuration for the validation reporter
# it greps the failure lines out of the log and sends them to a server.
# The pidfile for the reporter daemon.
pidfile="/var/run/validation-reporter.pid"
# The logfile to watch for logged validation failures.
logfile="/var/log/unbound.log"
# how to notify the upstream
# nc is netcat, it sends tcp to given host port. It makes a tcp connection
# and writes one log-line to it (grepped from the logfile).
# the notify command can be: "nc the.server.name.org 1234"
# the listening daemon could be: nc -lk 127.0.0.1 1234 >> outputfile &
notify_cmd="nc localhost 1234"
###
# Below this line is the code for the validation reporter,
# first the daemon itself, then the controller for the daemon.
reporter_daemon() {
trap "rm -f \"$pidfile\"" EXIT
tail -F $logfile | grep --line-buffered "unbound.*info: validation failure" | \
while read x; do
echo "$x" | $notify_cmd
done
}
###
# controller for daemon.
start_daemon() {
echo "starting reporter"
nohup $0 rundaemon </dev/null >/dev/null 2>&1 &
echo $! > "$pidfile"
}
kill_daemon() {
echo "stopping reporter"
if test -s "$pidfile"; then
kill `cat "$pidfile"`
# check it is really dead
if kill -0 `cat "$pidfile"` >/dev/null 2>&1; then
sleep 1
while kill -0 `cat "$pidfile"` >/dev/null 2>&1; do
kill `cat "$pidfile"` >/dev/null 2>&1
echo "waiting for reporter to stop"
sleep 1
done
fi
fi
}
get_status_daemon() {
if test -s "$pidfile"; then
if kill -0 `cat "$pidfile"`; then
return 0;
fi
fi
return 1;
}
restart_daemon() {
kill_daemon
start_daemon
}
condrestart_daemon() {
if get_status_daemon; then
echo "reporter ("`cat "$pidfile"`") is running"
exit 0
fi
start_daemon
exit 0
}
status_daemon() {
if get_status_daemon; then
echo "reporter ("`cat "$pidfile"`") is running"
exit 0
fi
echo "reporter is not running"
exit 1
}
case "$1" in
rundaemon)
reporter_daemon
;;
start)
start_daemon
;;
stop)
kill_daemon
;;
restart)
restart_daemon
;;
condrestart)
condrestart_daemon
;;
status)
status_daemon
;;
*)
echo "Usage: $0 {start|stop|restart|condrestart|status}"
exit 2
;;
esac
exit $?

68
external/unbound/contrib/warmup.cmd vendored Normal file
View File

@ -0,0 +1,68 @@
@echo off
rem --------------------------------------------------------------
rem -- Warm up DNS cache script by your own MRU domains
rem --
rem -- Version 1.0
rem -- By Yuri Voinov (c) 2014
rem --------------------------------------------------------------
rem Check dig installed
for /f "delims=" %%a in ('where dig') do @set dig=%%a
if /I "%dig%"=="" echo Dig not found. If installed, add path to PATH environment variable. & exit 1
echo Dig found: %dig%
echo Warming up cache by MRU domains...
rem dig -f my_domains 1>nul 2>nul
rem echo Done.
for %%a in (
mail.ru
my.mail.ru
mra.mail.ru
agent.mail.ru
news.mail.ru
icq.com
lenta.ru
gazeta.ru
peerbet.ru
www.opennet.ru
snob.ru
artlebedev.ru
mail.google.com
translate.google.com
drive.google.com
google.com
google.kz
drive.google.com
blogspot.com
farmanager.com
forum.farmanager.com
plugring.farmanager.com
symantec.com
symantecliveupdate.com
shalla.de
torstatus.blutmagie.de
torproject.org
dnscrypt.org
unbound.net
getsharex.com
skype.com
vlc.org
aimp.ru
mozilla.org
libreoffice.org
piriform.com
raidcall.com
nvidia.com
intel.com
microsoft.com
windowsupdate.com
ru.wikipedia.org
www.bbc.co.uk
tengrinews.kz
) do "%dig%" %%a 1>nul 2>nul
echo Saving cache...
unbound_cache.cmd -s
echo Done.

65
external/unbound/contrib/warmup.sh vendored Normal file
View File

@ -0,0 +1,65 @@
#!/bin/sh
# --------------------------------------------------------------
# -- Warm up DNS cache script by your own MRU domains
# --
# -- Version 1.0
# -- By Yuri Voinov (c) 2014
# --------------------------------------------------------------
dig=`which dig`
echo "Warming up cache by MRU domains..."
$dig -f - >/dev/null 2>&1 <<EOT
mail.ru
my.mail.ru
mra.mail.ru
agent.mail.ru
news.mail.ru
icq.com
lenta.ru
gazeta.ru
peerbet.ru
www.opennet.ru
snob.ru
artlebedev.ru
mail.google.com
translate.google.com
drive.google.com
google.com
google.kz
drive.google.com
blogspot.com
farmanager.com
forum.farmanager.com
plugring.farmanager.com
symantec.com
symantecliveupdate.com
shalla.de
torstatus.blutmagie.de
torproject.org
dnscrypt.org
unbound.net
getsharex.com
skype.com
vlc.org
aimp.ru
mozilla.org
libreoffice.org
piriform.com
raidcall.com
nvidia.com
intel.com
microsoft.com
windowsupdate.com
ru.wikipedia.org
www.bbc.co.uk
tengrinews.kz
EOT
echo "Done."
echo "Saving cache..."
/usr/local/bin/unbound_cache.sh -s
echo "Done."
exit 0

180
external/unbound/daemon/acl_list.c vendored Normal file
View File

@ -0,0 +1,180 @@
/*
* daemon/acl_list.h - client access control storage for the server.
*
* Copyright (c) 2007, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* This file helps the server keep out queries from outside sources, that
* should not be answered.
*/
#include "config.h"
#include "daemon/acl_list.h"
#include "util/regional.h"
#include "util/log.h"
#include "util/config_file.h"
#include "util/net_help.h"
struct acl_list*
acl_list_create(void)
{
struct acl_list* acl = (struct acl_list*)calloc(1,
sizeof(struct acl_list));
if(!acl)
return NULL;
acl->region = regional_create();
if(!acl->region) {
acl_list_delete(acl);
return NULL;
}
return acl;
}
void
acl_list_delete(struct acl_list* acl)
{
if(!acl)
return;
regional_destroy(acl->region);
free(acl);
}
/** insert new address into acl_list structure */
static int
acl_list_insert(struct acl_list* acl, struct sockaddr_storage* addr,
socklen_t addrlen, int net, enum acl_access control,
int complain_duplicates)
{
struct acl_addr* node = regional_alloc(acl->region,
sizeof(struct acl_addr));
if(!node)
return 0;
node->control = control;
if(!addr_tree_insert(&acl->tree, &node->node, addr, addrlen, net)) {
if(complain_duplicates)
verbose(VERB_QUERY, "duplicate acl address ignored.");
}
return 1;
}
/** apply acl_list string */
static int
acl_list_str_cfg(struct acl_list* acl, const char* str, const char* s2,
int complain_duplicates)
{
struct sockaddr_storage addr;
int net;
socklen_t addrlen;
enum acl_access control;
if(strcmp(s2, "allow") == 0)
control = acl_allow;
else if(strcmp(s2, "deny") == 0)
control = acl_deny;
else if(strcmp(s2, "refuse") == 0)
control = acl_refuse;
else if(strcmp(s2, "deny_non_local") == 0)
control = acl_deny_non_local;
else if(strcmp(s2, "refuse_non_local") == 0)
control = acl_refuse_non_local;
else if(strcmp(s2, "allow_snoop") == 0)
control = acl_allow_snoop;
else {
log_err("access control type %s unknown", str);
return 0;
}
if(!netblockstrtoaddr(str, UNBOUND_DNS_PORT, &addr, &addrlen, &net)) {
log_err("cannot parse access control: %s %s", str, s2);
return 0;
}
if(!acl_list_insert(acl, &addr, addrlen, net, control,
complain_duplicates)) {
log_err("out of memory");
return 0;
}
return 1;
}
/** read acl_list config */
static int
read_acl_list(struct acl_list* acl, struct config_file* cfg)
{
struct config_str2list* p;
for(p = cfg->acls; p; p = p->next) {
log_assert(p->str && p->str2);
if(!acl_list_str_cfg(acl, p->str, p->str2, 1))
return 0;
}
return 1;
}
int
acl_list_apply_cfg(struct acl_list* acl, struct config_file* cfg)
{
regional_free_all(acl->region);
addr_tree_init(&acl->tree);
if(!read_acl_list(acl, cfg))
return 0;
/* insert defaults, with '0' to ignore them if they are duplicates */
if(!acl_list_str_cfg(acl, "0.0.0.0/0", "refuse", 0))
return 0;
if(!acl_list_str_cfg(acl, "127.0.0.0/8", "allow", 0))
return 0;
if(cfg->do_ip6) {
if(!acl_list_str_cfg(acl, "::0/0", "refuse", 0))
return 0;
if(!acl_list_str_cfg(acl, "::1", "allow", 0))
return 0;
if(!acl_list_str_cfg(acl, "::ffff:127.0.0.1", "allow", 0))
return 0;
}
addr_tree_init_parents(&acl->tree);
return 1;
}
enum acl_access
acl_list_lookup(struct acl_list* acl, struct sockaddr_storage* addr,
socklen_t addrlen)
{
struct acl_addr* r = (struct acl_addr*)addr_tree_lookup(&acl->tree,
addr, addrlen);
if(r) return r->control;
return acl_deny;
}
size_t
acl_list_get_mem(struct acl_list* acl)
{
if(!acl) return 0;
return sizeof(*acl) + regional_get_mem(acl->region);
}

129
external/unbound/daemon/acl_list.h vendored Normal file
View File

@ -0,0 +1,129 @@
/*
* daemon/acl_list.h - client access control storage for the server.
*
* Copyright (c) 2007, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* This file keeps track of the list of clients that are allowed to
* access the server.
*/
#ifndef DAEMON_ACL_LIST_H
#define DAEMON_ACL_LIST_H
#include "util/storage/dnstree.h"
struct config_file;
struct regional;
/**
* Enumeration of access control options for an address range.
* Allow or deny access.
*/
enum acl_access {
/** disallow any access whatsoever, drop it */
acl_deny = 0,
/** disallow access, send a polite 'REFUSED' reply */
acl_refuse,
/** disallow any access to zones that aren't local, drop it */
acl_deny_non_local,
/** disallow access to zones that aren't local, 'REFUSED' reply */
acl_refuse_non_local,
/** allow full access for recursion (+RD) queries */
acl_allow,
/** allow full access for all queries, recursion and cache snooping */
acl_allow_snoop
};
/**
* Access control storage structure
*/
struct acl_list {
/** regional for allocation */
struct regional* region;
/**
* Tree of the addresses that are allowed/blocked.
* contents of type acl_addr.
*/
rbtree_t tree;
};
/**
*
* An address span with access control information
*/
struct acl_addr {
/** node in address tree */
struct addr_tree_node node;
/** access control on this netblock */
enum acl_access control;
};
/**
* Create acl structure
* @return new structure or NULL on error.
*/
struct acl_list* acl_list_create(void);
/**
* Delete acl structure.
* @param acl: to delete.
*/
void acl_list_delete(struct acl_list* acl);
/**
* Process access control config.
* @param acl: where to store.
* @param cfg: config options.
* @return 0 on error.
*/
int acl_list_apply_cfg(struct acl_list* acl, struct config_file* cfg);
/**
* Lookup address to see its access control status.
* @param acl: structure for address storage.
* @param addr: address to check
* @param addrlen: length of addr.
* @return: what to do with message from this address.
*/
enum acl_access acl_list_lookup(struct acl_list* acl,
struct sockaddr_storage* addr, socklen_t addrlen);
/**
* Get memory used by acl structure.
* @param acl: structure for address storage.
* @return bytes in use.
*/
size_t acl_list_get_mem(struct acl_list* acl);
#endif /* DAEMON_ACL_LIST_H */

886
external/unbound/daemon/cachedump.c vendored Normal file
View File

@ -0,0 +1,886 @@
/*
* daemon/cachedump.c - dump the cache to text format.
*
* Copyright (c) 2008, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* This file contains functions to read and write the cache(s)
* to text format.
*/
#include "config.h"
#include <openssl/ssl.h>
#include "daemon/cachedump.h"
#include "daemon/remote.h"
#include "daemon/worker.h"
#include "services/cache/rrset.h"
#include "services/cache/dns.h"
#include "services/cache/infra.h"
#include "util/data/msgreply.h"
#include "util/regional.h"
#include "util/net_help.h"
#include "util/data/dname.h"
#include "iterator/iterator.h"
#include "iterator/iter_delegpt.h"
#include "iterator/iter_utils.h"
#include "iterator/iter_fwd.h"
#include "iterator/iter_hints.h"
#include "ldns/sbuffer.h"
#include "ldns/wire2str.h"
#include "ldns/str2wire.h"
/** dump one rrset zonefile line */
static int
dump_rrset_line(SSL* ssl, struct ub_packed_rrset_key* k, time_t now, size_t i)
{
char s[65535];
if(!packed_rr_to_string(k, i, now, s, sizeof(s))) {
return ssl_printf(ssl, "BADRR\n");
}
return ssl_printf(ssl, "%s", s);
}
/** dump rrset key and data info */
static int
dump_rrset(SSL* ssl, struct ub_packed_rrset_key* k,
struct packed_rrset_data* d, time_t now)
{
size_t i;
/* rd lock held by caller */
if(!k || !d) return 1;
if(d->ttl < now) return 1; /* expired */
/* meta line */
if(!ssl_printf(ssl, ";rrset%s " ARG_LL "d %u %u %d %d\n",
(k->rk.flags & PACKED_RRSET_NSEC_AT_APEX)?" nsec_apex":"",
(long long)(d->ttl - now),
(unsigned)d->count, (unsigned)d->rrsig_count,
(int)d->trust, (int)d->security
))
return 0;
for(i=0; i<d->count + d->rrsig_count; i++) {
if(!dump_rrset_line(ssl, k, now, i))
return 0;
}
return 1;
}
/** dump lruhash rrset cache */
static int
dump_rrset_lruhash(SSL* ssl, struct lruhash* h, time_t now)
{
struct lruhash_entry* e;
/* lruhash already locked by caller */
/* walk in order of lru; best first */
for(e=h->lru_start; e; e = e->lru_next) {
lock_rw_rdlock(&e->lock);
if(!dump_rrset(ssl, (struct ub_packed_rrset_key*)e->key,
(struct packed_rrset_data*)e->data, now)) {
lock_rw_unlock(&e->lock);
return 0;
}
lock_rw_unlock(&e->lock);
}
return 1;
}
/** dump rrset cache */
static int
dump_rrset_cache(SSL* ssl, struct worker* worker)
{
struct rrset_cache* r = worker->env.rrset_cache;
size_t slab;
if(!ssl_printf(ssl, "START_RRSET_CACHE\n")) return 0;
for(slab=0; slab<r->table.size; slab++) {
lock_quick_lock(&r->table.array[slab]->lock);
if(!dump_rrset_lruhash(ssl, r->table.array[slab],
*worker->env.now)) {
lock_quick_unlock(&r->table.array[slab]->lock);
return 0;
}
lock_quick_unlock(&r->table.array[slab]->lock);
}
return ssl_printf(ssl, "END_RRSET_CACHE\n");
}
/** dump message to rrset reference */
static int
dump_msg_ref(SSL* ssl, struct ub_packed_rrset_key* k)
{
char* nm, *tp, *cl;
nm = sldns_wire2str_dname(k->rk.dname, k->rk.dname_len);
tp = sldns_wire2str_type(ntohs(k->rk.type));
cl = sldns_wire2str_class(ntohs(k->rk.rrset_class));
if(!nm || !cl || !tp) {
free(nm);
free(tp);
free(cl);
return ssl_printf(ssl, "BADREF\n");
}
if(!ssl_printf(ssl, "%s %s %s %d\n", nm, cl, tp, (int)k->rk.flags)) {
free(nm);
free(tp);
free(cl);
return 0;
}
free(nm);
free(tp);
free(cl);
return 1;
}
/** dump message entry */
static int
dump_msg(SSL* ssl, struct query_info* k, struct reply_info* d,
time_t now)
{
size_t i;
char* nm, *tp, *cl;
if(!k || !d) return 1;
if(d->ttl < now) return 1; /* expired */
nm = sldns_wire2str_dname(k->qname, k->qname_len);
tp = sldns_wire2str_type(k->qtype);
cl = sldns_wire2str_class(k->qclass);
if(!nm || !tp || !cl) {
free(nm);
free(tp);
free(cl);
return 1; /* skip this entry */
}
if(!rrset_array_lock(d->ref, d->rrset_count, now)) {
/* rrsets have timed out or do not exist */
free(nm);
free(tp);
free(cl);
return 1; /* skip this entry */
}
/* meta line */
if(!ssl_printf(ssl, "msg %s %s %s %d %d " ARG_LL "d %d %u %u %u\n",
nm, cl, tp,
(int)d->flags, (int)d->qdcount,
(long long)(d->ttl-now), (int)d->security,
(unsigned)d->an_numrrsets,
(unsigned)d->ns_numrrsets,
(unsigned)d->ar_numrrsets)) {
free(nm);
free(tp);
free(cl);
rrset_array_unlock(d->ref, d->rrset_count);
return 0;
}
free(nm);
free(tp);
free(cl);
for(i=0; i<d->rrset_count; i++) {
if(!dump_msg_ref(ssl, d->rrsets[i])) {
rrset_array_unlock(d->ref, d->rrset_count);
return 0;
}
}
rrset_array_unlock(d->ref, d->rrset_count);
return 1;
}
/** copy msg to worker pad */
static int
copy_msg(struct regional* region, struct lruhash_entry* e,
struct query_info** k, struct reply_info** d)
{
struct reply_info* rep = (struct reply_info*)e->data;
*d = (struct reply_info*)regional_alloc_init(region, e->data,
sizeof(struct reply_info) +
sizeof(struct rrset_ref) * (rep->rrset_count-1) +
sizeof(struct ub_packed_rrset_key*) * rep->rrset_count);
if(!*d)
return 0;
(*d)->rrsets = (struct ub_packed_rrset_key**)(void *)(
(uint8_t*)(&((*d)->ref[0])) +
sizeof(struct rrset_ref) * rep->rrset_count);
*k = (struct query_info*)regional_alloc_init(region,
e->key, sizeof(struct query_info));
if(!*k)
return 0;
(*k)->qname = regional_alloc_init(region,
(*k)->qname, (*k)->qname_len);
return (*k)->qname != NULL;
}
/** dump lruhash msg cache */
static int
dump_msg_lruhash(SSL* ssl, struct worker* worker, struct lruhash* h)
{
struct lruhash_entry* e;
struct query_info* k;
struct reply_info* d;
/* lruhash already locked by caller */
/* walk in order of lru; best first */
for(e=h->lru_start; e; e = e->lru_next) {
regional_free_all(worker->scratchpad);
lock_rw_rdlock(&e->lock);
/* make copy of rrset in worker buffer */
if(!copy_msg(worker->scratchpad, e, &k, &d)) {
lock_rw_unlock(&e->lock);
return 0;
}
lock_rw_unlock(&e->lock);
/* release lock so we can lookup the rrset references
* in the rrset cache */
if(!dump_msg(ssl, k, d, *worker->env.now)) {
return 0;
}
}
return 1;
}
/** dump msg cache */
static int
dump_msg_cache(SSL* ssl, struct worker* worker)
{
struct slabhash* sh = worker->env.msg_cache;
size_t slab;
if(!ssl_printf(ssl, "START_MSG_CACHE\n")) return 0;
for(slab=0; slab<sh->size; slab++) {
lock_quick_lock(&sh->array[slab]->lock);
if(!dump_msg_lruhash(ssl, worker, sh->array[slab])) {
lock_quick_unlock(&sh->array[slab]->lock);
return 0;
}
lock_quick_unlock(&sh->array[slab]->lock);
}
return ssl_printf(ssl, "END_MSG_CACHE\n");
}
int
dump_cache(SSL* ssl, struct worker* worker)
{
if(!dump_rrset_cache(ssl, worker))
return 0;
if(!dump_msg_cache(ssl, worker))
return 0;
return ssl_printf(ssl, "EOF\n");
}
/** read a line from ssl into buffer */
static int
ssl_read_buf(SSL* ssl, sldns_buffer* buf)
{
return ssl_read_line(ssl, (char*)sldns_buffer_begin(buf),
sldns_buffer_capacity(buf));
}
/** check fixed text on line */
static int
read_fixed(SSL* ssl, sldns_buffer* buf, const char* str)
{
if(!ssl_read_buf(ssl, buf)) return 0;
return (strcmp((char*)sldns_buffer_begin(buf), str) == 0);
}
/** load an RR into rrset */
static int
load_rr(SSL* ssl, sldns_buffer* buf, struct regional* region,
struct ub_packed_rrset_key* rk, struct packed_rrset_data* d,
unsigned int i, int is_rrsig, int* go_on, time_t now)
{
uint8_t rr[LDNS_RR_BUF_SIZE];
size_t rr_len = sizeof(rr), dname_len = 0;
int status;
/* read the line */
if(!ssl_read_buf(ssl, buf))
return 0;
if(strncmp((char*)sldns_buffer_begin(buf), "BADRR\n", 6) == 0) {
*go_on = 0;
return 1;
}
status = sldns_str2wire_rr_buf((char*)sldns_buffer_begin(buf), rr,
&rr_len, &dname_len, 3600, NULL, 0, NULL, 0);
if(status != 0) {
log_warn("error cannot parse rr: %s: %s",
sldns_get_errorstr_parse(status),
(char*)sldns_buffer_begin(buf));
return 0;
}
if(is_rrsig && sldns_wirerr_get_type(rr, rr_len, dname_len)
!= LDNS_RR_TYPE_RRSIG) {
log_warn("error expected rrsig but got %s",
(char*)sldns_buffer_begin(buf));
return 0;
}
/* convert ldns rr into packed_rr */
d->rr_ttl[i] = (time_t)sldns_wirerr_get_ttl(rr, rr_len, dname_len) + now;
sldns_buffer_clear(buf);
d->rr_len[i] = sldns_wirerr_get_rdatalen(rr, rr_len, dname_len)+2;
d->rr_data[i] = (uint8_t*)regional_alloc_init(region,
sldns_wirerr_get_rdatawl(rr, rr_len, dname_len), d->rr_len[i]);
if(!d->rr_data[i]) {
log_warn("error out of memory");
return 0;
}
/* if first entry, fill the key structure */
if(i==0) {
rk->rk.type = htons(sldns_wirerr_get_type(rr, rr_len, dname_len));
rk->rk.rrset_class = htons(sldns_wirerr_get_class(rr, rr_len, dname_len));
rk->rk.dname_len = dname_len;
rk->rk.dname = regional_alloc_init(region, rr, dname_len);
if(!rk->rk.dname) {
log_warn("error out of memory");
return 0;
}
}
return 1;
}
/** move entry into cache */
static int
move_into_cache(struct ub_packed_rrset_key* k,
struct packed_rrset_data* d, struct worker* worker)
{
struct ub_packed_rrset_key* ak;
struct packed_rrset_data* ad;
size_t s, i, num = d->count + d->rrsig_count;
struct rrset_ref ref;
uint8_t* p;
ak = alloc_special_obtain(&worker->alloc);
if(!ak) {
log_warn("error out of memory");
return 0;
}
ak->entry.data = NULL;
ak->rk = k->rk;
ak->entry.hash = rrset_key_hash(&k->rk);
ak->rk.dname = (uint8_t*)memdup(k->rk.dname, k->rk.dname_len);
if(!ak->rk.dname) {
log_warn("error out of memory");
ub_packed_rrset_parsedelete(ak, &worker->alloc);
return 0;
}
s = sizeof(*ad) + (sizeof(size_t) + sizeof(uint8_t*) +
sizeof(time_t))* num;
for(i=0; i<num; i++)
s += d->rr_len[i];
ad = (struct packed_rrset_data*)malloc(s);
if(!ad) {
log_warn("error out of memory");
ub_packed_rrset_parsedelete(ak, &worker->alloc);
return 0;
}
p = (uint8_t*)ad;
memmove(p, d, sizeof(*ad));
p += sizeof(*ad);
memmove(p, &d->rr_len[0], sizeof(size_t)*num);
p += sizeof(size_t)*num;
memmove(p, &d->rr_data[0], sizeof(uint8_t*)*num);
p += sizeof(uint8_t*)*num;
memmove(p, &d->rr_ttl[0], sizeof(time_t)*num);
p += sizeof(time_t)*num;
for(i=0; i<num; i++) {
memmove(p, d->rr_data[i], d->rr_len[i]);
p += d->rr_len[i];
}
packed_rrset_ptr_fixup(ad);
ak->entry.data = ad;
ref.key = ak;
ref.id = ak->id;
(void)rrset_cache_update(worker->env.rrset_cache, &ref,
&worker->alloc, *worker->env.now);
return 1;
}
/** load an rrset entry */
static int
load_rrset(SSL* ssl, sldns_buffer* buf, struct worker* worker)
{
char* s = (char*)sldns_buffer_begin(buf);
struct regional* region = worker->scratchpad;
struct ub_packed_rrset_key* rk;
struct packed_rrset_data* d;
unsigned int rr_count, rrsig_count, trust, security;
long long ttl;
unsigned int i;
int go_on = 1;
regional_free_all(region);
rk = (struct ub_packed_rrset_key*)regional_alloc_zero(region,
sizeof(*rk));
d = (struct packed_rrset_data*)regional_alloc_zero(region, sizeof(*d));
if(!rk || !d) {
log_warn("error out of memory");
return 0;
}
if(strncmp(s, ";rrset", 6) != 0) {
log_warn("error expected ';rrset' but got %s", s);
return 0;
}
s += 6;
if(strncmp(s, " nsec_apex", 10) == 0) {
s += 10;
rk->rk.flags |= PACKED_RRSET_NSEC_AT_APEX;
}
if(sscanf(s, " " ARG_LL "d %u %u %u %u", &ttl, &rr_count, &rrsig_count,
&trust, &security) != 5) {
log_warn("error bad rrset spec %s", s);
return 0;
}
if(rr_count == 0 && rrsig_count == 0) {
log_warn("bad rrset without contents");
return 0;
}
d->count = (size_t)rr_count;
d->rrsig_count = (size_t)rrsig_count;
d->security = (enum sec_status)security;
d->trust = (enum rrset_trust)trust;
d->ttl = (time_t)ttl + *worker->env.now;
d->rr_len = regional_alloc_zero(region,
sizeof(size_t)*(d->count+d->rrsig_count));
d->rr_ttl = regional_alloc_zero(region,
sizeof(time_t)*(d->count+d->rrsig_count));
d->rr_data = regional_alloc_zero(region,
sizeof(uint8_t*)*(d->count+d->rrsig_count));
if(!d->rr_len || !d->rr_ttl || !d->rr_data) {
log_warn("error out of memory");
return 0;
}
/* read the rr's themselves */
for(i=0; i<rr_count; i++) {
if(!load_rr(ssl, buf, region, rk, d, i, 0,
&go_on, *worker->env.now)) {
log_warn("could not read rr %u", i);
return 0;
}
}
for(i=0; i<rrsig_count; i++) {
if(!load_rr(ssl, buf, region, rk, d, i+rr_count, 1,
&go_on, *worker->env.now)) {
log_warn("could not read rrsig %u", i);
return 0;
}
}
if(!go_on) {
/* skip this entry */
return 1;
}
return move_into_cache(rk, d, worker);
}
/** load rrset cache */
static int
load_rrset_cache(SSL* ssl, struct worker* worker)
{
sldns_buffer* buf = worker->env.scratch_buffer;
if(!read_fixed(ssl, buf, "START_RRSET_CACHE")) return 0;
while(ssl_read_buf(ssl, buf) &&
strcmp((char*)sldns_buffer_begin(buf), "END_RRSET_CACHE")!=0) {
if(!load_rrset(ssl, buf, worker))
return 0;
}
return 1;
}
/** read qinfo from next three words */
static char*
load_qinfo(char* str, struct query_info* qinfo, struct regional* region)
{
/* s is part of the buf */
char* s = str;
uint8_t rr[LDNS_RR_BUF_SIZE];
size_t rr_len = sizeof(rr), dname_len = 0;
int status;
/* skip three words */
s = strchr(str, ' ');
if(s) s = strchr(s+1, ' ');
if(s) s = strchr(s+1, ' ');
if(!s) {
log_warn("error line too short, %s", str);
return NULL;
}
s[0] = 0;
s++;
/* parse them */
status = sldns_str2wire_rr_question_buf(str, rr, &rr_len, &dname_len,
NULL, 0, NULL, 0);
if(status != 0) {
log_warn("error cannot parse: %s %s",
sldns_get_errorstr_parse(status), str);
return NULL;
}
qinfo->qtype = sldns_wirerr_get_type(rr, rr_len, dname_len);
qinfo->qclass = sldns_wirerr_get_class(rr, rr_len, dname_len);
qinfo->qname_len = dname_len;
qinfo->qname = (uint8_t*)regional_alloc_init(region, rr, dname_len);
if(!qinfo->qname) {
log_warn("error out of memory");
return NULL;
}
return s;
}
/** load a msg rrset reference */
static int
load_ref(SSL* ssl, sldns_buffer* buf, struct worker* worker,
struct regional *region, struct ub_packed_rrset_key** rrset,
int* go_on)
{
char* s = (char*)sldns_buffer_begin(buf);
struct query_info qinfo;
unsigned int flags;
struct ub_packed_rrset_key* k;
/* read line */
if(!ssl_read_buf(ssl, buf))
return 0;
if(strncmp(s, "BADREF", 6) == 0) {
*go_on = 0; /* its bad, skip it and skip message */
return 1;
}
s = load_qinfo(s, &qinfo, region);
if(!s) {
return 0;
}
if(sscanf(s, " %u", &flags) != 1) {
log_warn("error cannot parse flags: %s", s);
return 0;
}
/* lookup in cache */
k = rrset_cache_lookup(worker->env.rrset_cache, qinfo.qname,
qinfo.qname_len, qinfo.qtype, qinfo.qclass,
(uint32_t)flags, *worker->env.now, 0);
if(!k) {
/* not found or expired */
*go_on = 0;
return 1;
}
/* store in result */
*rrset = packed_rrset_copy_region(k, region, *worker->env.now);
lock_rw_unlock(&k->entry.lock);
return (*rrset != NULL);
}
/** load a msg entry */
static int
load_msg(SSL* ssl, sldns_buffer* buf, struct worker* worker)
{
struct regional* region = worker->scratchpad;
struct query_info qinf;
struct reply_info rep;
char* s = (char*)sldns_buffer_begin(buf);
unsigned int flags, qdcount, security, an, ns, ar;
long long ttl;
size_t i;
int go_on = 1;
regional_free_all(region);
if(strncmp(s, "msg ", 4) != 0) {
log_warn("error expected msg but got %s", s);
return 0;
}
s += 4;
s = load_qinfo(s, &qinf, region);
if(!s) {
return 0;
}
/* read remainder of line */
if(sscanf(s, " %u %u " ARG_LL "d %u %u %u %u", &flags, &qdcount, &ttl,
&security, &an, &ns, &ar) != 7) {
log_warn("error cannot parse numbers: %s", s);
return 0;
}
rep.flags = (uint16_t)flags;
rep.qdcount = (uint16_t)qdcount;
rep.ttl = (time_t)ttl;
rep.prefetch_ttl = PREFETCH_TTL_CALC(rep.ttl);
rep.security = (enum sec_status)security;
rep.an_numrrsets = (size_t)an;
rep.ns_numrrsets = (size_t)ns;
rep.ar_numrrsets = (size_t)ar;
rep.rrset_count = (size_t)an+(size_t)ns+(size_t)ar;
rep.rrsets = (struct ub_packed_rrset_key**)regional_alloc_zero(
region, sizeof(struct ub_packed_rrset_key*)*rep.rrset_count);
/* fill repinfo with references */
for(i=0; i<rep.rrset_count; i++) {
if(!load_ref(ssl, buf, worker, region, &rep.rrsets[i],
&go_on)) {
return 0;
}
}
if(!go_on)
return 1; /* skip this one, not all references satisfied */
if(!dns_cache_store(&worker->env, &qinf, &rep, 0, 0, 0, NULL)) {
log_warn("error out of memory");
return 0;
}
return 1;
}
/** load msg cache */
static int
load_msg_cache(SSL* ssl, struct worker* worker)
{
sldns_buffer* buf = worker->env.scratch_buffer;
if(!read_fixed(ssl, buf, "START_MSG_CACHE")) return 0;
while(ssl_read_buf(ssl, buf) &&
strcmp((char*)sldns_buffer_begin(buf), "END_MSG_CACHE")!=0) {
if(!load_msg(ssl, buf, worker))
return 0;
}
return 1;
}
int
load_cache(SSL* ssl, struct worker* worker)
{
if(!load_rrset_cache(ssl, worker))
return 0;
if(!load_msg_cache(ssl, worker))
return 0;
return read_fixed(ssl, worker->env.scratch_buffer, "EOF");
}
/** print details on a delegation point */
static void
print_dp_details(SSL* ssl, struct worker* worker, struct delegpt* dp)
{
char buf[257];
struct delegpt_addr* a;
int lame, dlame, rlame, rto, edns_vs, to, delay,
tA = 0, tAAAA = 0, tother = 0;
long long entry_ttl;
struct rtt_info ri;
uint8_t edns_lame_known;
for(a = dp->target_list; a; a = a->next_target) {
addr_to_str(&a->addr, a->addrlen, buf, sizeof(buf));
if(!ssl_printf(ssl, "%-16s\t", buf))
return;
if(a->bogus) {
if(!ssl_printf(ssl, "Address is BOGUS. "))
return;
}
/* lookup in infra cache */
delay=0;
entry_ttl = infra_get_host_rto(worker->env.infra_cache,
&a->addr, a->addrlen, dp->name, dp->namelen,
&ri, &delay, *worker->env.now, &tA, &tAAAA, &tother);
if(entry_ttl == -2 && ri.rto >= USEFUL_SERVER_TOP_TIMEOUT) {
if(!ssl_printf(ssl, "expired, rto %d msec, tA %d "
"tAAAA %d tother %d.\n", ri.rto, tA, tAAAA,
tother))
return;
continue;
}
if(entry_ttl == -1 || entry_ttl == -2) {
if(!ssl_printf(ssl, "not in infra cache.\n"))
return;
continue; /* skip stuff not in infra cache */
}
/* uses type_A because most often looked up, but other
* lameness won't be reported then */
if(!infra_get_lame_rtt(worker->env.infra_cache,
&a->addr, a->addrlen, dp->name, dp->namelen,
LDNS_RR_TYPE_A, &lame, &dlame, &rlame, &rto,
*worker->env.now)) {
if(!ssl_printf(ssl, "not in infra cache.\n"))
return;
continue; /* skip stuff not in infra cache */
}
if(!ssl_printf(ssl, "%s%s%s%srto %d msec, ttl " ARG_LL "d, "
"ping %d var %d rtt %d, tA %d, tAAAA %d, tother %d",
lame?"LAME ":"", dlame?"NoDNSSEC ":"",
a->lame?"AddrWasParentSide ":"",
rlame?"NoAuthButRecursive ":"", rto, entry_ttl,
ri.srtt, ri.rttvar, rtt_notimeout(&ri),
tA, tAAAA, tother))
return;
if(delay)
if(!ssl_printf(ssl, ", probedelay %d", delay))
return;
if(infra_host(worker->env.infra_cache, &a->addr, a->addrlen,
dp->name, dp->namelen, *worker->env.now, &edns_vs,
&edns_lame_known, &to)) {
if(edns_vs == -1) {
if(!ssl_printf(ssl, ", noEDNS%s.",
edns_lame_known?" probed":" assumed"))
return;
} else {
if(!ssl_printf(ssl, ", EDNS %d%s.", edns_vs,
edns_lame_known?" probed":" assumed"))
return;
}
}
if(!ssl_printf(ssl, "\n"))
return;
}
}
/** print main dp info */
static void
print_dp_main(SSL* ssl, struct delegpt* dp, struct dns_msg* msg)
{
size_t i, n_ns, n_miss, n_addr, n_res, n_avail;
/* print the dp */
if(msg)
for(i=0; i<msg->rep->rrset_count; i++) {
struct ub_packed_rrset_key* k = msg->rep->rrsets[i];
struct packed_rrset_data* d =
(struct packed_rrset_data*)k->entry.data;
if(d->security == sec_status_bogus) {
if(!ssl_printf(ssl, "Address is BOGUS:\n"))
return;
}
if(!dump_rrset(ssl, k, d, 0))
return;
}
delegpt_count_ns(dp, &n_ns, &n_miss);
delegpt_count_addr(dp, &n_addr, &n_res, &n_avail);
/* since dp has not been used by iterator, all are available*/
if(!ssl_printf(ssl, "Delegation with %d names, of which %d "
"can be examined to query further addresses.\n"
"%sIt provides %d IP addresses.\n",
(int)n_ns, (int)n_miss, (dp->bogus?"It is BOGUS. ":""),
(int)n_addr))
return;
}
int print_deleg_lookup(SSL* ssl, struct worker* worker, uint8_t* nm,
size_t nmlen, int ATTR_UNUSED(nmlabs))
{
/* deep links into the iterator module */
struct delegpt* dp;
struct dns_msg* msg;
struct regional* region = worker->scratchpad;
char b[260];
struct query_info qinfo;
struct iter_hints_stub* stub;
regional_free_all(region);
qinfo.qname = nm;
qinfo.qname_len = nmlen;
qinfo.qtype = LDNS_RR_TYPE_A;
qinfo.qclass = LDNS_RR_CLASS_IN;
dname_str(nm, b);
if(!ssl_printf(ssl, "The following name servers are used for lookup "
"of %s\n", b))
return 0;
dp = forwards_lookup(worker->env.fwds, nm, qinfo.qclass);
if(dp) {
if(!ssl_printf(ssl, "forwarding request:\n"))
return 0;
print_dp_main(ssl, dp, NULL);
print_dp_details(ssl, worker, dp);
return 1;
}
while(1) {
dp = dns_cache_find_delegation(&worker->env, nm, nmlen,
qinfo.qtype, qinfo.qclass, region, &msg,
*worker->env.now);
if(!dp) {
return ssl_printf(ssl, "no delegation from "
"cache; goes to configured roots\n");
}
/* go up? */
if(iter_dp_is_useless(&qinfo, BIT_RD, dp)) {
print_dp_main(ssl, dp, msg);
print_dp_details(ssl, worker, dp);
if(!ssl_printf(ssl, "cache delegation was "
"useless (no IP addresses)\n"))
return 0;
if(dname_is_root(nm)) {
/* goes to root config */
return ssl_printf(ssl, "no delegation from "
"cache; goes to configured roots\n");
} else {
/* useless, goes up */
nm = dp->name;
nmlen = dp->namelen;
dname_remove_label(&nm, &nmlen);
dname_str(nm, b);
if(!ssl_printf(ssl, "going up, lookup %s\n", b))
return 0;
continue;
}
}
stub = hints_lookup_stub(worker->env.hints, nm, qinfo.qclass,
dp);
if(stub) {
if(stub->noprime) {
if(!ssl_printf(ssl, "The noprime stub servers "
"are used:\n"))
return 0;
} else {
if(!ssl_printf(ssl, "The stub is primed "
"with servers:\n"))
return 0;
}
print_dp_main(ssl, stub->dp, NULL);
print_dp_details(ssl, worker, stub->dp);
} else {
print_dp_main(ssl, dp, msg);
print_dp_details(ssl, worker, dp);
}
break;
}
return 1;
}

107
external/unbound/daemon/cachedump.h vendored Normal file
View File

@ -0,0 +1,107 @@
/*
* daemon/cachedump.h - dump the cache to text format.
*
* Copyright (c) 2008, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* This file contains functions to read and write the cache(s)
* to text format.
*
* The format of the file is as follows:
* [RRset cache]
* [Message cache]
* EOF -- fixed string "EOF" before end of the file.
*
* The RRset cache is:
* START_RRSET_CACHE
* [rrset]*
* END_RRSET_CACHE
*
* rrset is:
* ;rrset [nsec_apex] TTL rr_count rrsig_count trust security
* resource records, one per line, in zonefile format
* rrsig records, one per line, in zonefile format
* If the text conversion fails, BADRR is printed on the line.
*
* The Message cache is:
* START_MSG_CACHE
* [msg]*
* END_MSG_CACHE
*
* msg is:
* msg name class type flags qdcount ttl security an ns ar
* list of rrset references, one per line. If conversion fails, BADREF
* reference is:
* name class type flags
*
* Expired cache entries are not printed.
*/
#ifndef DAEMON_DUMPCACHE_H
#define DAEMON_DUMPCACHE_H
struct worker;
/**
* Dump cache(s) to text
* @param ssl: to print to
* @param worker: worker that is available (buffers, etc) and has
* ptrs to the caches.
* @return false on ssl print error.
*/
int dump_cache(SSL* ssl, struct worker* worker);
/**
* Load cache(s) from text
* @param ssl: to read from
* @param worker: worker that is available (buffers, etc) and has
* ptrs to the caches.
* @return false on ssl error.
*/
int load_cache(SSL* ssl, struct worker* worker);
/**
* Print the delegation used to lookup for this name.
* @param ssl: to read from
* @param worker: worker that is available (buffers, etc) and has
* ptrs to the caches.
* @param nm: name to lookup
* @param nmlen: length of name.
* @param nmlabs: labels in name.
* @return false on ssl error.
*/
int print_deleg_lookup(SSL* ssl, struct worker* worker, uint8_t* nm,
size_t nmlen, int nmlabs);
#endif /* DAEMON_DUMPCACHE_H */

693
external/unbound/daemon/daemon.c vendored Normal file
View File

@ -0,0 +1,693 @@
/*
* daemon/daemon.c - collection of workers that handles requests.
*
* Copyright (c) 2007, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* The daemon consists of global settings and a number of workers.
*/
#include "config.h"
#ifdef HAVE_OPENSSL_ERR_H
#include <openssl/err.h>
#endif
#ifdef HAVE_OPENSSL_RAND_H
#include <openssl/rand.h>
#endif
#ifdef HAVE_OPENSSL_CONF_H
#include <openssl/conf.h>
#endif
#ifdef HAVE_OPENSSL_ENGINE_H
#include <openssl/engine.h>
#endif
#ifdef HAVE_TIME_H
#include <time.h>
#endif
#include <sys/time.h>
#ifdef HAVE_NSS
/* nss3 */
#include "nss.h"
#endif
#include "daemon/daemon.h"
#include "daemon/worker.h"
#include "daemon/remote.h"
#include "daemon/acl_list.h"
#include "util/log.h"
#include "util/config_file.h"
#include "util/data/msgreply.h"
#include "util/storage/lookup3.h"
#include "util/storage/slabhash.h"
#include "services/listen_dnsport.h"
#include "services/cache/rrset.h"
#include "services/cache/infra.h"
#include "services/localzone.h"
#include "services/modstack.h"
#include "util/module.h"
#include "util/random.h"
#include "util/tube.h"
#include "util/net_help.h"
#include "ldns/keyraw.h"
#include <signal.h>
/** How many quit requests happened. */
static int sig_record_quit = 0;
/** How many reload requests happened. */
static int sig_record_reload = 0;
#if HAVE_DECL_SSL_COMP_GET_COMPRESSION_METHODS
/** cleaner ssl memory freeup */
static void* comp_meth = NULL;
#endif
#ifdef LEX_HAS_YYLEX_DESTROY
/** remove buffers for parsing and init */
int ub_c_lex_destroy(void);
#endif
/** used when no other sighandling happens, so we don't die
* when multiple signals in quick succession are sent to us.
* @param sig: signal number.
* @return signal handler return type (void or int).
*/
static RETSIGTYPE record_sigh(int sig)
{
#ifdef LIBEVENT_SIGNAL_PROBLEM
/* cannot log, verbose here because locks may be held */
/* quit on signal, no cleanup and statistics,
because installed libevent version is not threadsafe */
exit(0);
#endif
switch(sig)
{
case SIGTERM:
#ifdef SIGQUIT
case SIGQUIT:
#endif
#ifdef SIGBREAK
case SIGBREAK:
#endif
case SIGINT:
sig_record_quit++;
break;
#ifdef SIGHUP
case SIGHUP:
sig_record_reload++;
break;
#endif
#ifdef SIGPIPE
case SIGPIPE:
break;
#endif
default:
/* ignoring signal */
break;
}
}
/**
* Signal handling during the time when netevent is disabled.
* Stores signals to replay later.
*/
static void
signal_handling_record(void)
{
if( signal(SIGTERM, record_sigh) == SIG_ERR ||
#ifdef SIGQUIT
signal(SIGQUIT, record_sigh) == SIG_ERR ||
#endif
#ifdef SIGBREAK
signal(SIGBREAK, record_sigh) == SIG_ERR ||
#endif
#ifdef SIGHUP
signal(SIGHUP, record_sigh) == SIG_ERR ||
#endif
#ifdef SIGPIPE
signal(SIGPIPE, SIG_IGN) == SIG_ERR ||
#endif
signal(SIGINT, record_sigh) == SIG_ERR
)
log_err("install sighandler: %s", strerror(errno));
}
/**
* Replay old signals.
* @param wrk: worker that handles signals.
*/
static void
signal_handling_playback(struct worker* wrk)
{
#ifdef SIGHUP
if(sig_record_reload)
worker_sighandler(SIGHUP, wrk);
#endif
if(sig_record_quit)
worker_sighandler(SIGTERM, wrk);
sig_record_quit = 0;
sig_record_reload = 0;
}
struct daemon*
daemon_init(void)
{
struct daemon* daemon = (struct daemon*)calloc(1,
sizeof(struct daemon));
#ifdef USE_WINSOCK
int r;
WSADATA wsa_data;
#endif
if(!daemon)
return NULL;
#ifdef USE_WINSOCK
r = WSAStartup(MAKEWORD(2,2), &wsa_data);
if(r != 0) {
fatal_exit("could not init winsock. WSAStartup: %s",
wsa_strerror(r));
}
#endif /* USE_WINSOCK */
signal_handling_record();
checklock_start();
#ifdef HAVE_SSL
ERR_load_crypto_strings();
ERR_load_SSL_strings();
# ifdef HAVE_OPENSSL_CONFIG
OPENSSL_config("unbound");
# endif
# ifdef USE_GOST
(void)sldns_key_EVP_load_gost_id();
# endif
OpenSSL_add_all_algorithms();
# if HAVE_DECL_SSL_COMP_GET_COMPRESSION_METHODS
/* grab the COMP method ptr because openssl leaks it */
comp_meth = (void*)SSL_COMP_get_compression_methods();
# endif
(void)SSL_library_init();
# if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED)
if(!ub_openssl_lock_init())
fatal_exit("could not init openssl locks");
# endif
#elif defined(HAVE_NSS)
if(NSS_NoDB_Init(NULL) != SECSuccess)
fatal_exit("could not init NSS");
#endif /* HAVE_SSL or HAVE_NSS */
#ifdef HAVE_TZSET
/* init timezone info while we are not chrooted yet */
tzset();
#endif
/* open /dev/random if needed */
ub_systemseed((unsigned)time(NULL)^(unsigned)getpid()^0xe67);
daemon->need_to_exit = 0;
modstack_init(&daemon->mods);
if(!(daemon->env = (struct module_env*)calloc(1,
sizeof(*daemon->env)))) {
free(daemon);
return NULL;
}
alloc_init(&daemon->superalloc, NULL, 0);
daemon->acl = acl_list_create();
if(!daemon->acl) {
free(daemon->env);
free(daemon);
return NULL;
}
if(gettimeofday(&daemon->time_boot, NULL) < 0)
log_err("gettimeofday: %s", strerror(errno));
daemon->time_last_stat = daemon->time_boot;
return daemon;
}
int
daemon_open_shared_ports(struct daemon* daemon)
{
log_assert(daemon);
if(daemon->cfg->port != daemon->listening_port) {
size_t i;
struct listen_port* p0;
daemon->reuseport = 0;
/* free and close old ports */
if(daemon->ports != NULL) {
for(i=0; i<daemon->num_ports; i++)
listening_ports_free(daemon->ports[i]);
free(daemon->ports);
daemon->ports = NULL;
}
/* see if we want to reuseport */
#ifdef SO_REUSEPORT
if(daemon->cfg->so_reuseport && daemon->cfg->num_threads > 0)
daemon->reuseport = 1;
#endif
/* try to use reuseport */
p0 = listening_ports_open(daemon->cfg, &daemon->reuseport);
if(!p0) {
listening_ports_free(p0);
return 0;
}
if(daemon->reuseport) {
/* reuseport was successful, allocate for it */
daemon->num_ports = (size_t)daemon->cfg->num_threads;
} else {
/* do the normal, singleportslist thing,
* reuseport not enabled or did not work */
daemon->num_ports = 1;
}
if(!(daemon->ports = (struct listen_port**)calloc(
daemon->num_ports, sizeof(*daemon->ports)))) {
listening_ports_free(p0);
return 0;
}
daemon->ports[0] = p0;
if(daemon->reuseport) {
/* continue to use reuseport */
for(i=1; i<daemon->num_ports; i++) {
if(!(daemon->ports[i]=
listening_ports_open(daemon->cfg,
&daemon->reuseport))
|| !daemon->reuseport ) {
for(i=0; i<daemon->num_ports; i++)
listening_ports_free(daemon->ports[i]);
free(daemon->ports);
daemon->ports = NULL;
return 0;
}
}
}
daemon->listening_port = daemon->cfg->port;
}
if(!daemon->cfg->remote_control_enable && daemon->rc_port) {
listening_ports_free(daemon->rc_ports);
daemon->rc_ports = NULL;
daemon->rc_port = 0;
}
if(daemon->cfg->remote_control_enable &&
daemon->cfg->control_port != daemon->rc_port) {
listening_ports_free(daemon->rc_ports);
if(!(daemon->rc_ports=daemon_remote_open_ports(daemon->cfg)))
return 0;
daemon->rc_port = daemon->cfg->control_port;
}
return 1;
}
/**
* Setup modules. setup module stack.
* @param daemon: the daemon
*/
static void daemon_setup_modules(struct daemon* daemon)
{
daemon->env->cfg = daemon->cfg;
daemon->env->alloc = &daemon->superalloc;
daemon->env->worker = NULL;
daemon->env->need_to_validate = 0; /* set by module init below */
if(!modstack_setup(&daemon->mods, daemon->cfg->module_conf,
daemon->env)) {
fatal_exit("failed to setup modules");
}
}
/**
* Obtain allowed port numbers, concatenate the list, and shuffle them
* (ready to be handed out to threads).
* @param daemon: the daemon. Uses rand and cfg.
* @param shufport: the portlist output.
* @return number of ports available.
*/
static int daemon_get_shufport(struct daemon* daemon, int* shufport)
{
int i, n, k, temp;
int avail = 0;
for(i=0; i<65536; i++) {
if(daemon->cfg->outgoing_avail_ports[i]) {
shufport[avail++] = daemon->cfg->
outgoing_avail_ports[i];
}
}
if(avail == 0)
fatal_exit("no ports are permitted for UDP, add "
"with outgoing-port-permit");
/* Knuth shuffle */
n = avail;
while(--n > 0) {
k = ub_random_max(daemon->rand, n+1); /* 0<= k<= n */
temp = shufport[k];
shufport[k] = shufport[n];
shufport[n] = temp;
}
return avail;
}
/**
* Allocate empty worker structures. With backptr and thread-number,
* from 0..numthread initialised. Used as user arguments to new threads.
* Creates the daemon random generator if it does not exist yet.
* The random generator stays existing between reloads with a unique state.
* @param daemon: the daemon with (new) config settings.
*/
static void
daemon_create_workers(struct daemon* daemon)
{
int i, numport;
int* shufport;
log_assert(daemon && daemon->cfg);
if(!daemon->rand) {
unsigned int seed = (unsigned int)time(NULL) ^
(unsigned int)getpid() ^ 0x438;
daemon->rand = ub_initstate(seed, NULL);
if(!daemon->rand)
fatal_exit("could not init random generator");
}
hash_set_raninit((uint32_t)ub_random(daemon->rand));
shufport = (int*)calloc(65536, sizeof(int));
if(!shufport)
fatal_exit("out of memory during daemon init");
numport = daemon_get_shufport(daemon, shufport);
verbose(VERB_ALGO, "total of %d outgoing ports available", numport);
daemon->num = (daemon->cfg->num_threads?daemon->cfg->num_threads:1);
daemon->workers = (struct worker**)calloc((size_t)daemon->num,
sizeof(struct worker*));
if(daemon->cfg->dnstap) {
#ifdef USE_DNSTAP
daemon->dtenv = dt_create(daemon->cfg->dnstap_socket_path,
(unsigned int)daemon->num);
if (!daemon->dtenv)
fatal_exit("dt_create failed");
dt_apply_cfg(daemon->dtenv, daemon->cfg);
#else
fatal_exit("dnstap enabled in config but not built with dnstap support");
#endif
}
for(i=0; i<daemon->num; i++) {
if(!(daemon->workers[i] = worker_create(daemon, i,
shufport+numport*i/daemon->num,
numport*(i+1)/daemon->num - numport*i/daemon->num)))
/* the above is not ports/numthr, due to rounding */
fatal_exit("could not create worker");
}
free(shufport);
}
#ifdef THREADS_DISABLED
/**
* Close all pipes except for the numbered thread.
* @param daemon: daemon to close pipes in.
* @param thr: thread number 0..num-1 of thread to skip.
*/
static void close_other_pipes(struct daemon* daemon, int thr)
{
int i;
for(i=0; i<daemon->num; i++)
if(i!=thr) {
if(i==0) {
/* only close read part, need to write stats */
tube_close_read(daemon->workers[i]->cmd);
} else {
/* complete close channel to others */
tube_delete(daemon->workers[i]->cmd);
daemon->workers[i]->cmd = NULL;
}
}
}
#endif /* THREADS_DISABLED */
/**
* Function to start one thread.
* @param arg: user argument.
* @return: void* user return value could be used for thread_join results.
*/
static void*
thread_start(void* arg)
{
struct worker* worker = (struct worker*)arg;
int port_num = 0;
log_thread_set(&worker->thread_num);
ub_thread_blocksigs();
#ifdef THREADS_DISABLED
/* close pipe ends used by main */
tube_close_write(worker->cmd);
close_other_pipes(worker->daemon, worker->thread_num);
#endif
#ifdef SO_REUSEPORT
if(worker->daemon->cfg->so_reuseport)
port_num = worker->thread_num;
else
port_num = 0;
#endif
if(!worker_init(worker, worker->daemon->cfg,
worker->daemon->ports[port_num], 0))
fatal_exit("Could not initialize thread");
worker_work(worker);
return NULL;
}
/**
* Fork and init the other threads. Main thread returns for special handling.
* @param daemon: the daemon with other threads to fork.
*/
static void
daemon_start_others(struct daemon* daemon)
{
int i;
log_assert(daemon);
verbose(VERB_ALGO, "start threads");
/* skip i=0, is this thread */
for(i=1; i<daemon->num; i++) {
ub_thread_create(&daemon->workers[i]->thr_id,
thread_start, daemon->workers[i]);
#ifdef THREADS_DISABLED
/* close pipe end of child */
tube_close_read(daemon->workers[i]->cmd);
#endif /* no threads */
}
}
/**
* Stop the other threads.
* @param daemon: the daemon with other threads.
*/
static void
daemon_stop_others(struct daemon* daemon)
{
int i;
log_assert(daemon);
verbose(VERB_ALGO, "stop threads");
/* skip i=0, is this thread */
/* use i=0 buffer for sending cmds; because we are #0 */
for(i=1; i<daemon->num; i++) {
worker_send_cmd(daemon->workers[i], worker_cmd_quit);
}
/* wait for them to quit */
for(i=1; i<daemon->num; i++) {
/* join it to make sure its dead */
verbose(VERB_ALGO, "join %d", i);
ub_thread_join(daemon->workers[i]->thr_id);
verbose(VERB_ALGO, "join success %d", i);
}
}
void
daemon_fork(struct daemon* daemon)
{
log_assert(daemon);
if(!acl_list_apply_cfg(daemon->acl, daemon->cfg))
fatal_exit("Could not setup access control list");
if(!(daemon->local_zones = local_zones_create()))
fatal_exit("Could not create local zones: out of memory");
if(!local_zones_apply_cfg(daemon->local_zones, daemon->cfg))
fatal_exit("Could not set up local zones");
/* setup modules */
daemon_setup_modules(daemon);
/* first create all the worker structures, so we can pass
* them to the newly created threads.
*/
daemon_create_workers(daemon);
#if defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
/* in libev the first inited base gets signals */
if(!worker_init(daemon->workers[0], daemon->cfg, daemon->ports[0], 1))
fatal_exit("Could not initialize main thread");
#endif
/* Now create the threads and init the workers.
* By the way, this is thread #0 (the main thread).
*/
daemon_start_others(daemon);
/* Special handling for the main thread. This is the thread
* that handles signals and remote control.
*/
#if !(defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP))
/* libevent has the last inited base get signals (or any base) */
if(!worker_init(daemon->workers[0], daemon->cfg, daemon->ports[0], 1))
fatal_exit("Could not initialize main thread");
#endif
signal_handling_playback(daemon->workers[0]);
/* Start resolver service on main thread. */
log_info("start of service (%s).", PACKAGE_STRING);
worker_work(daemon->workers[0]);
log_info("service stopped (%s).", PACKAGE_STRING);
/* we exited! a signal happened! Stop other threads */
daemon_stop_others(daemon);
daemon->need_to_exit = daemon->workers[0]->need_to_exit;
}
void
daemon_cleanup(struct daemon* daemon)
{
int i;
log_assert(daemon);
/* before stopping main worker, handle signals ourselves, so we
don't die on multiple reload signals for example. */
signal_handling_record();
log_thread_set(NULL);
/* clean up caches because
* a) RRset IDs will be recycled after a reload, causing collisions
* b) validation config can change, thus rrset, msg, keycache clear
* The infra cache is kept, the timing and edns info is still valid */
slabhash_clear(&daemon->env->rrset_cache->table);
slabhash_clear(daemon->env->msg_cache);
local_zones_delete(daemon->local_zones);
daemon->local_zones = NULL;
/* key cache is cleared by module desetup during next daemon_init() */
daemon_remote_clear(daemon->rc);
for(i=0; i<daemon->num; i++)
worker_delete(daemon->workers[i]);
free(daemon->workers);
daemon->workers = NULL;
daemon->num = 0;
#ifdef USE_DNSTAP
dt_delete(daemon->dtenv);
#endif
daemon->cfg = NULL;
}
void
daemon_delete(struct daemon* daemon)
{
size_t i;
if(!daemon)
return;
modstack_desetup(&daemon->mods, daemon->env);
daemon_remote_delete(daemon->rc);
for(i = 0; i < daemon->num_ports; i++)
listening_ports_free(daemon->ports[i]);
free(daemon->ports);
listening_ports_free(daemon->rc_ports);
if(daemon->env) {
slabhash_delete(daemon->env->msg_cache);
rrset_cache_delete(daemon->env->rrset_cache);
infra_delete(daemon->env->infra_cache);
}
ub_randfree(daemon->rand);
alloc_clear(&daemon->superalloc);
acl_list_delete(daemon->acl);
free(daemon->chroot);
free(daemon->pidfile);
free(daemon->env);
#ifdef HAVE_SSL
SSL_CTX_free((SSL_CTX*)daemon->listen_sslctx);
SSL_CTX_free((SSL_CTX*)daemon->connect_sslctx);
#endif
free(daemon);
#ifdef LEX_HAS_YYLEX_DESTROY
/* lex cleanup */
ub_c_lex_destroy();
#endif
/* libcrypto cleanup */
#ifdef HAVE_SSL
# if defined(USE_GOST) && defined(HAVE_LDNS_KEY_EVP_UNLOAD_GOST)
sldns_key_EVP_unload_gost();
# endif
# if HAVE_DECL_SSL_COMP_GET_COMPRESSION_METHODS && HAVE_DECL_SK_SSL_COMP_POP_FREE
# ifndef S_SPLINT_S
sk_SSL_COMP_pop_free(comp_meth, (void(*)())CRYPTO_free);
# endif
# endif
# ifdef HAVE_OPENSSL_CONFIG
EVP_cleanup();
ENGINE_cleanup();
CONF_modules_free();
# endif
CRYPTO_cleanup_all_ex_data(); /* safe, no more threads right now */
ERR_remove_state(0);
ERR_free_strings();
RAND_cleanup();
# if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED)
ub_openssl_lock_delete();
# endif
#elif defined(HAVE_NSS)
NSS_Shutdown();
#endif /* HAVE_SSL or HAVE_NSS */
checklock_stop();
#ifdef USE_WINSOCK
if(WSACleanup() != 0) {
log_err("Could not WSACleanup: %s",
wsa_strerror(WSAGetLastError()));
}
#endif
}
void daemon_apply_cfg(struct daemon* daemon, struct config_file* cfg)
{
daemon->cfg = cfg;
config_apply(cfg);
if(!daemon->env->msg_cache ||
cfg->msg_cache_size != slabhash_get_size(daemon->env->msg_cache) ||
cfg->msg_cache_slabs != daemon->env->msg_cache->size) {
slabhash_delete(daemon->env->msg_cache);
daemon->env->msg_cache = slabhash_create(cfg->msg_cache_slabs,
HASH_DEFAULT_STARTARRAY, cfg->msg_cache_size,
msgreply_sizefunc, query_info_compare,
query_entry_delete, reply_info_delete, NULL);
if(!daemon->env->msg_cache) {
fatal_exit("malloc failure updating config settings");
}
}
if((daemon->env->rrset_cache = rrset_cache_adjust(
daemon->env->rrset_cache, cfg, &daemon->superalloc)) == 0)
fatal_exit("malloc failure updating config settings");
if((daemon->env->infra_cache = infra_adjust(daemon->env->infra_cache,
cfg))==0)
fatal_exit("malloc failure updating config settings");
}

164
external/unbound/daemon/daemon.h vendored Normal file
View File

@ -0,0 +1,164 @@
/*
* daemon/daemon.h - collection of workers that handles requests.
*
* Copyright (c) 2007, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* The daemon consists of global settings and a number of workers.
*/
#ifndef DAEMON_H
#define DAEMON_H
#include "util/locks.h"
#include "util/alloc.h"
#include "services/modstack.h"
#ifdef UB_ON_WINDOWS
# include "util/winsock_event.h"
#endif
struct config_file;
struct worker;
struct listen_port;
struct slabhash;
struct module_env;
struct rrset_cache;
struct acl_list;
struct local_zones;
struct ub_randstate;
struct daemon_remote;
#include "dnstap/dnstap_config.h"
#ifdef USE_DNSTAP
struct dt_env;
#endif
/**
* Structure holding worker list.
* Holds globally visible information.
*/
struct daemon {
/** The config settings */
struct config_file* cfg;
/** the chroot dir in use, NULL if none */
char* chroot;
/** pidfile that is used */
char* pidfile;
/** port number that has ports opened. */
int listening_port;
/** array of listening ports, opened. Listening ports per worker,
* or just one element[0] shared by the worker threads. */
struct listen_port** ports;
/** size of ports array */
size_t num_ports;
/** reuseport is enabled if true */
int reuseport;
/** port number for remote that has ports opened. */
int rc_port;
/** listening ports for remote control */
struct listen_port* rc_ports;
/** remote control connections management (for first worker) */
struct daemon_remote* rc;
/** ssl context for listening to dnstcp over ssl, and connecting ssl */
void* listen_sslctx, *connect_sslctx;
/** num threads allocated */
int num;
/** the worker entries */
struct worker** workers;
/** do we need to exit unbound (or is it only a reload?) */
int need_to_exit;
/** master random table ; used for port div between threads on reload*/
struct ub_randstate* rand;
/** master allocation cache */
struct alloc_cache superalloc;
/** the module environment master value, copied and changed by threads*/
struct module_env* env;
/** stack of module callbacks */
struct module_stack mods;
/** access control, which client IPs are allowed to connect */
struct acl_list* acl;
/** local authority zones */
struct local_zones* local_zones;
/** last time of statistics printout */
struct timeval time_last_stat;
/** time when daemon started */
struct timeval time_boot;
#ifdef USE_DNSTAP
/** the dnstap environment master value, copied and changed by threads*/
struct dt_env* dtenv;
#endif
};
/**
* Initialize daemon structure.
* @return: The daemon structure, or NULL on error.
*/
struct daemon* daemon_init(void);
/**
* Open shared listening ports (if needed).
* The cfg member pointer must have been set for the daemon.
* @param daemon: the daemon.
* @return: false on error.
*/
int daemon_open_shared_ports(struct daemon* daemon);
/**
* Fork workers and start service.
* When the routine exits, it is no longer forked.
* @param daemon: the daemon.
*/
void daemon_fork(struct daemon* daemon);
/**
* Close off the worker thread information.
* Bring the daemon back into state ready for daemon_fork again.
* @param daemon: the daemon.
*/
void daemon_cleanup(struct daemon* daemon);
/**
* Delete workers, close listening ports.
* @param daemon: the daemon.
*/
void daemon_delete(struct daemon* daemon);
/**
* Apply config settings.
* @param daemon: the daemon.
* @param cfg: new config settings.
*/
void daemon_apply_cfg(struct daemon* daemon, struct config_file* cfg);
#endif /* DAEMON_H */

2449
external/unbound/daemon/remote.c vendored Normal file

File diff suppressed because it is too large Load Diff

189
external/unbound/daemon/remote.h vendored Normal file
View File

@ -0,0 +1,189 @@
/*
* daemon/remote.h - remote control for the unbound daemon.
*
* Copyright (c) 2008, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* This file contains the remote control functionality for the daemon.
* The remote control can be performed using either the commandline
* unbound-control tool, or a SSLv3/TLS capable web browser.
* The channel is secured using SSLv3 or TLSv1, and certificates.
* Both the server and the client(control tool) have their own keys.
*/
#ifndef DAEMON_REMOTE_H
#define DAEMON_REMOTE_H
#ifdef HAVE_OPENSSL_SSL_H
#include "openssl/ssl.h"
#endif
struct config_file;
struct listen_list;
struct listen_port;
struct worker;
struct comm_reply;
struct comm_point;
struct daemon_remote;
/** number of seconds timeout on incoming remote control handshake */
#define REMOTE_CONTROL_TCP_TIMEOUT 120
/**
* a busy control command connection, SSL state
*/
struct rc_state {
/** the next item in list */
struct rc_state* next;
/** the commpoint */
struct comm_point* c;
/** in the handshake part */
enum { rc_none, rc_hs_read, rc_hs_write } shake_state;
#ifdef HAVE_SSL
/** the ssl state */
SSL* ssl;
#endif
/** the rc this is part of */
struct daemon_remote* rc;
};
/**
* The remote control tool state.
* The state is only created for the first thread, other threads
* are called from this thread. Only the first threads listens to
* the control port. The other threads do not, but are called on the
* command channel(pipe) from the first thread.
*/
struct daemon_remote {
/** the worker for this remote control */
struct worker* worker;
/** commpoints for accepting remote control connections */
struct listen_list* accept_list;
/** number of active commpoints that are handling remote control */
int active;
/** max active commpoints */
int max_active;
/** current commpoints busy; should be a short list, malloced */
struct rc_state* busy_list;
#ifdef HAVE_SSL
/** the SSL context for creating new SSL streams */
SSL_CTX* ctx;
#endif
};
/**
* Create new remote control state for the daemon.
* @param cfg: config file with key file settings.
* @return new state, or NULL on failure.
*/
struct daemon_remote* daemon_remote_create(struct config_file* cfg);
/**
* remote control state to delete.
* @param rc: state to delete.
*/
void daemon_remote_delete(struct daemon_remote* rc);
/**
* remote control state to clear up. Busy and accept points are closed.
* Does not delete the rc itself, or the ssl context (with its keys).
* @param rc: state to clear.
*/
void daemon_remote_clear(struct daemon_remote* rc);
/**
* Open and create listening ports for remote control.
* @param cfg: config options.
* @return list of ports or NULL on failure.
* can be freed with listening_ports_free().
*/
struct listen_port* daemon_remote_open_ports(struct config_file* cfg);
/**
* Setup comm points for accepting remote control connections.
* @param rc: state
* @param ports: already opened ports.
* @param worker: worker with communication base. and links to command channels.
* @return false on error.
*/
int daemon_remote_open_accept(struct daemon_remote* rc,
struct listen_port* ports, struct worker* worker);
/**
* Stop accept handlers for TCP (until enabled again)
* @param rc: state
*/
void daemon_remote_stop_accept(struct daemon_remote* rc);
/**
* Stop accept handlers for TCP (until enabled again)
* @param rc: state
*/
void daemon_remote_start_accept(struct daemon_remote* rc);
/**
* Handle nonthreaded remote cmd execution.
* @param worker: this worker (the remote worker).
*/
void daemon_remote_exec(struct worker* worker);
#ifdef HAVE_SSL
/**
* Print fixed line of text over ssl connection in blocking mode
* @param ssl: print to
* @param text: the text.
* @return false on connection failure.
*/
int ssl_print_text(SSL* ssl, const char* text);
/**
* printf style printing to the ssl connection
* @param ssl: the SSL connection to print to. Blocking.
* @param format: printf style format string.
* @return success or false on a network failure.
*/
int ssl_printf(SSL* ssl, const char* format, ...)
ATTR_FORMAT(printf, 2, 3);
/**
* Read until \n is encountered
* If SSL signals EOF, the string up to then is returned (without \n).
* @param ssl: the SSL connection to read from. blocking.
* @param buf: buffer to read to.
* @param max: size of buffer.
* @return false on connection failure.
*/
int ssl_read_line(SSL* ssl, char* buf, size_t max);
#endif /* HAVE_SSL */
#endif /* DAEMON_REMOTE_H */

321
external/unbound/daemon/stats.c vendored Normal file
View File

@ -0,0 +1,321 @@
/*
* daemon/stats.c - collect runtime performance indicators.
*
* Copyright (c) 2007, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* This file describes the data structure used to collect runtime performance
* numbers. These 'statistics' may be of interest to the operator.
*/
#include "config.h"
#ifdef HAVE_TIME_H
#include <time.h>
#endif
#include <sys/time.h>
#include <sys/types.h>
#include "daemon/stats.h"
#include "daemon/worker.h"
#include "daemon/daemon.h"
#include "services/mesh.h"
#include "services/outside_network.h"
#include "util/config_file.h"
#include "util/tube.h"
#include "util/timehist.h"
#include "util/net_help.h"
#include "validator/validator.h"
#include "ldns/sbuffer.h"
#include "services/cache/rrset.h"
#include "services/cache/infra.h"
#include "validator/val_kcache.h"
/** add timers and the values do not overflow or become negative */
static void
timeval_add(struct timeval* d, const struct timeval* add)
{
#ifndef S_SPLINT_S
d->tv_sec += add->tv_sec;
d->tv_usec += add->tv_usec;
if(d->tv_usec > 1000000) {
d->tv_usec -= 1000000;
d->tv_sec++;
}
#endif
}
void server_stats_init(struct server_stats* stats, struct config_file* cfg)
{
memset(stats, 0, sizeof(*stats));
stats->extended = cfg->stat_extended;
}
void server_stats_querymiss(struct server_stats* stats, struct worker* worker)
{
stats->num_queries_missed_cache++;
stats->sum_query_list_size += worker->env.mesh->all.count;
if(worker->env.mesh->all.count > stats->max_query_list_size)
stats->max_query_list_size = worker->env.mesh->all.count;
}
void server_stats_prefetch(struct server_stats* stats, struct worker* worker)
{
stats->num_queries_prefetch++;
/* changes the query list size so account that, like a querymiss */
stats->sum_query_list_size += worker->env.mesh->all.count;
if(worker->env.mesh->all.count > stats->max_query_list_size)
stats->max_query_list_size = worker->env.mesh->all.count;
}
void server_stats_log(struct server_stats* stats, struct worker* worker,
int threadnum)
{
log_info("server stats for thread %d: %u queries, "
"%u answers from cache, %u recursions, %u prefetch",
threadnum, (unsigned)stats->num_queries,
(unsigned)(stats->num_queries -
stats->num_queries_missed_cache),
(unsigned)stats->num_queries_missed_cache,
(unsigned)stats->num_queries_prefetch);
log_info("server stats for thread %d: requestlist max %u avg %g "
"exceeded %u jostled %u", threadnum,
(unsigned)stats->max_query_list_size,
(stats->num_queries_missed_cache+stats->num_queries_prefetch)?
(double)stats->sum_query_list_size/
(stats->num_queries_missed_cache+
stats->num_queries_prefetch) : 0.0,
(unsigned)worker->env.mesh->stats_dropped,
(unsigned)worker->env.mesh->stats_jostled);
}
/** get rrsets bogus number from validator */
static size_t
get_rrset_bogus(struct worker* worker)
{
int m = modstack_find(&worker->env.mesh->mods, "validator");
struct val_env* ve;
size_t r;
if(m == -1)
return 0;
ve = (struct val_env*)worker->env.modinfo[m];
lock_basic_lock(&ve->bogus_lock);
r = ve->num_rrset_bogus;
if(!worker->env.cfg->stat_cumulative)
ve->num_rrset_bogus = 0;
lock_basic_unlock(&ve->bogus_lock);
return r;
}
void
server_stats_compile(struct worker* worker, struct stats_info* s, int reset)
{
int i;
s->svr = worker->stats;
s->mesh_num_states = worker->env.mesh->all.count;
s->mesh_num_reply_states = worker->env.mesh->num_reply_states;
s->mesh_jostled = worker->env.mesh->stats_jostled;
s->mesh_dropped = worker->env.mesh->stats_dropped;
s->mesh_replies_sent = worker->env.mesh->replies_sent;
s->mesh_replies_sum_wait = worker->env.mesh->replies_sum_wait;
s->mesh_time_median = timehist_quartile(worker->env.mesh->histogram,
0.50);
/* add in the values from the mesh */
s->svr.ans_secure += worker->env.mesh->ans_secure;
s->svr.ans_bogus += worker->env.mesh->ans_bogus;
s->svr.ans_rcode_nodata += worker->env.mesh->ans_nodata;
for(i=0; i<16; i++)
s->svr.ans_rcode[i] += worker->env.mesh->ans_rcode[i];
timehist_export(worker->env.mesh->histogram, s->svr.hist,
NUM_BUCKETS_HIST);
/* values from outside network */
s->svr.unwanted_replies = worker->back->unwanted_replies;
s->svr.qtcp_outgoing = worker->back->num_tcp_outgoing;
/* get and reset validator rrset bogus number */
s->svr.rrset_bogus = get_rrset_bogus(worker);
/* get cache sizes */
s->svr.msg_cache_count = count_slabhash_entries(worker->env.msg_cache);
s->svr.rrset_cache_count = count_slabhash_entries(&worker->env.rrset_cache->table);
s->svr.infra_cache_count = count_slabhash_entries(worker->env.infra_cache->hosts);
if(worker->env.key_cache)
s->svr.key_cache_count = count_slabhash_entries(worker->env.key_cache->slab);
else s->svr.key_cache_count = 0;
if(reset && !worker->env.cfg->stat_cumulative) {
worker_stats_clear(worker);
}
}
void server_stats_obtain(struct worker* worker, struct worker* who,
struct stats_info* s, int reset)
{
uint8_t *reply = NULL;
uint32_t len = 0;
if(worker == who) {
/* just fill it in */
server_stats_compile(worker, s, reset);
return;
}
/* communicate over tube */
verbose(VERB_ALGO, "write stats cmd");
if(reset)
worker_send_cmd(who, worker_cmd_stats);
else worker_send_cmd(who, worker_cmd_stats_noreset);
verbose(VERB_ALGO, "wait for stats reply");
if(!tube_read_msg(worker->cmd, &reply, &len, 0))
fatal_exit("failed to read stats over cmd channel");
if(len != (uint32_t)sizeof(*s))
fatal_exit("stats on cmd channel wrong length %d %d",
(int)len, (int)sizeof(*s));
memcpy(s, reply, (size_t)len);
free(reply);
}
void server_stats_reply(struct worker* worker, int reset)
{
struct stats_info s;
server_stats_compile(worker, &s, reset);
verbose(VERB_ALGO, "write stats replymsg");
if(!tube_write_msg(worker->daemon->workers[0]->cmd,
(uint8_t*)&s, sizeof(s), 0))
fatal_exit("could not write stat values over cmd channel");
}
void server_stats_add(struct stats_info* total, struct stats_info* a)
{
total->svr.num_queries += a->svr.num_queries;
total->svr.num_queries_missed_cache += a->svr.num_queries_missed_cache;
total->svr.num_queries_prefetch += a->svr.num_queries_prefetch;
total->svr.sum_query_list_size += a->svr.sum_query_list_size;
/* the max size reached is upped to higher of both */
if(a->svr.max_query_list_size > total->svr.max_query_list_size)
total->svr.max_query_list_size = a->svr.max_query_list_size;
if(a->svr.extended) {
int i;
total->svr.qtype_big += a->svr.qtype_big;
total->svr.qclass_big += a->svr.qclass_big;
total->svr.qtcp += a->svr.qtcp;
total->svr.qtcp_outgoing += a->svr.qtcp_outgoing;
total->svr.qipv6 += a->svr.qipv6;
total->svr.qbit_QR += a->svr.qbit_QR;
total->svr.qbit_AA += a->svr.qbit_AA;
total->svr.qbit_TC += a->svr.qbit_TC;
total->svr.qbit_RD += a->svr.qbit_RD;
total->svr.qbit_RA += a->svr.qbit_RA;
total->svr.qbit_Z += a->svr.qbit_Z;
total->svr.qbit_AD += a->svr.qbit_AD;
total->svr.qbit_CD += a->svr.qbit_CD;
total->svr.qEDNS += a->svr.qEDNS;
total->svr.qEDNS_DO += a->svr.qEDNS_DO;
total->svr.ans_rcode_nodata += a->svr.ans_rcode_nodata;
total->svr.ans_secure += a->svr.ans_secure;
total->svr.ans_bogus += a->svr.ans_bogus;
total->svr.rrset_bogus += a->svr.rrset_bogus;
total->svr.unwanted_replies += a->svr.unwanted_replies;
total->svr.unwanted_queries += a->svr.unwanted_queries;
for(i=0; i<STATS_QTYPE_NUM; i++)
total->svr.qtype[i] += a->svr.qtype[i];
for(i=0; i<STATS_QCLASS_NUM; i++)
total->svr.qclass[i] += a->svr.qclass[i];
for(i=0; i<STATS_OPCODE_NUM; i++)
total->svr.qopcode[i] += a->svr.qopcode[i];
for(i=0; i<STATS_RCODE_NUM; i++)
total->svr.ans_rcode[i] += a->svr.ans_rcode[i];
for(i=0; i<NUM_BUCKETS_HIST; i++)
total->svr.hist[i] += a->svr.hist[i];
}
total->mesh_num_states += a->mesh_num_states;
total->mesh_num_reply_states += a->mesh_num_reply_states;
total->mesh_jostled += a->mesh_jostled;
total->mesh_dropped += a->mesh_dropped;
total->mesh_replies_sent += a->mesh_replies_sent;
timeval_add(&total->mesh_replies_sum_wait, &a->mesh_replies_sum_wait);
/* the medians are averaged together, this is not as accurate as
* taking the median over all of the data, but is good and fast
* added up here, division later*/
total->mesh_time_median += a->mesh_time_median;
}
void server_stats_insquery(struct server_stats* stats, struct comm_point* c,
uint16_t qtype, uint16_t qclass, struct edns_data* edns,
struct comm_reply* repinfo)
{
uint16_t flags = sldns_buffer_read_u16_at(c->buffer, 2);
if(qtype < STATS_QTYPE_NUM)
stats->qtype[qtype]++;
else stats->qtype_big++;
if(qclass < STATS_QCLASS_NUM)
stats->qclass[qclass]++;
else stats->qclass_big++;
stats->qopcode[ LDNS_OPCODE_WIRE(sldns_buffer_begin(c->buffer)) ]++;
if(c->type != comm_udp)
stats->qtcp++;
if(repinfo && addr_is_ip6(&repinfo->addr, repinfo->addrlen))
stats->qipv6++;
if( (flags&BIT_QR) )
stats->qbit_QR++;
if( (flags&BIT_AA) )
stats->qbit_AA++;
if( (flags&BIT_TC) )
stats->qbit_TC++;
if( (flags&BIT_RD) )
stats->qbit_RD++;
if( (flags&BIT_RA) )
stats->qbit_RA++;
if( (flags&BIT_Z) )
stats->qbit_Z++;
if( (flags&BIT_AD) )
stats->qbit_AD++;
if( (flags&BIT_CD) )
stats->qbit_CD++;
if(edns->edns_present) {
stats->qEDNS++;
if( (edns->bits & EDNS_DO) )
stats->qEDNS_DO++;
}
}
void server_stats_insrcode(struct server_stats* stats, sldns_buffer* buf)
{
if(stats->extended && sldns_buffer_limit(buf) != 0) {
int r = (int)LDNS_RCODE_WIRE( sldns_buffer_begin(buf) );
stats->ans_rcode[r] ++;
if(r == 0 && LDNS_ANCOUNT( sldns_buffer_begin(buf) ) == 0)
stats->ans_rcode_nodata ++;
}
}

246
external/unbound/daemon/stats.h vendored Normal file
View File

@ -0,0 +1,246 @@
/*
* daemon/stats.h - collect runtime performance indicators.
*
* Copyright (c) 2007, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* This file describes the data structure used to collect runtime performance
* numbers. These 'statistics' may be of interest to the operator.
*/
#ifndef DAEMON_STATS_H
#define DAEMON_STATS_H
#include "util/timehist.h"
struct worker;
struct config_file;
struct comm_point;
struct comm_reply;
struct edns_data;
struct sldns_buffer;
/** number of qtype that is stored for in array */
#define STATS_QTYPE_NUM 256
/** number of qclass that is stored for in array */
#define STATS_QCLASS_NUM 256
/** number of rcodes in stats */
#define STATS_RCODE_NUM 16
/** number of opcodes in stats */
#define STATS_OPCODE_NUM 16
/** per worker statistics */
struct server_stats {
/** number of queries from clients received. */
size_t num_queries;
/** number of queries that had a cache-miss. */
size_t num_queries_missed_cache;
/** number of prefetch queries - cachehits with prefetch */
size_t num_queries_prefetch;
/**
* Sum of the querylistsize of the worker for
* every query that missed cache. To calculate average.
*/
size_t sum_query_list_size;
/** max value of query list size reached. */
size_t max_query_list_size;
/** Extended stats below (bool) */
int extended;
/** qtype stats */
size_t qtype[STATS_QTYPE_NUM];
/** bigger qtype values not in array */
size_t qtype_big;
/** qclass stats */
size_t qclass[STATS_QCLASS_NUM];
/** bigger qclass values not in array */
size_t qclass_big;
/** query opcodes */
size_t qopcode[STATS_OPCODE_NUM];
/** number of queries over TCP */
size_t qtcp;
/** number of outgoing queries over TCP */
size_t qtcp_outgoing;
/** number of queries over IPv6 */
size_t qipv6;
/** number of queries with QR bit */
size_t qbit_QR;
/** number of queries with AA bit */
size_t qbit_AA;
/** number of queries with TC bit */
size_t qbit_TC;
/** number of queries with RD bit */
size_t qbit_RD;
/** number of queries with RA bit */
size_t qbit_RA;
/** number of queries with Z bit */
size_t qbit_Z;
/** number of queries with AD bit */
size_t qbit_AD;
/** number of queries with CD bit */
size_t qbit_CD;
/** number of queries with EDNS OPT record */
size_t qEDNS;
/** number of queries with EDNS with DO flag */
size_t qEDNS_DO;
/** answer rcodes */
size_t ans_rcode[STATS_RCODE_NUM];
/** answers with pseudo rcode 'nodata' */
size_t ans_rcode_nodata;
/** answers that were secure (AD) */
size_t ans_secure;
/** answers that were bogus (withheld as SERVFAIL) */
size_t ans_bogus;
/** rrsets marked bogus by validator */
size_t rrset_bogus;
/** unwanted traffic received on server-facing ports */
size_t unwanted_replies;
/** unwanted traffic received on client-facing ports */
size_t unwanted_queries;
/** histogram data exported to array
* if the array is the same size, no data is lost, and
* if all histograms are same size (is so by default) then
* adding up works well. */
size_t hist[NUM_BUCKETS_HIST];
/** number of message cache entries */
size_t msg_cache_count;
/** number of rrset cache entries */
size_t rrset_cache_count;
/** number of infra cache entries */
size_t infra_cache_count;
/** number of key cache entries */
size_t key_cache_count;
};
/**
* Statistics to send over the control pipe when asked
* This struct is made to be memcpied, sent in binary.
*/
struct stats_info {
/** the thread stats */
struct server_stats svr;
/** mesh stats: current number of states */
size_t mesh_num_states;
/** mesh stats: current number of reply (user) states */
size_t mesh_num_reply_states;
/** mesh stats: number of reply states overwritten with a new one */
size_t mesh_jostled;
/** mesh stats: number of incoming queries dropped */
size_t mesh_dropped;
/** mesh stats: replies sent */
size_t mesh_replies_sent;
/** mesh stats: sum of waiting times for the replies */
struct timeval mesh_replies_sum_wait;
/** mesh stats: median of waiting times for replies (in sec) */
double mesh_time_median;
};
/**
* Initialize server stats to 0.
* @param stats: what to init (this is alloced by the caller).
* @param cfg: with extended statistics option.
*/
void server_stats_init(struct server_stats* stats, struct config_file* cfg);
/** add query if it missed the cache */
void server_stats_querymiss(struct server_stats* stats, struct worker* worker);
/** add query if was cached and also resulted in a prefetch */
void server_stats_prefetch(struct server_stats* stats, struct worker* worker);
/** display the stats to the log */
void server_stats_log(struct server_stats* stats, struct worker* worker,
int threadnum);
/**
* Obtain the stats info for a given thread. Uses pipe to communicate.
* @param worker: the worker that is executing (the first worker).
* @param who: on who to get the statistics info.
* @param s: the stats block to fill in.
* @param reset: if stats can be reset.
*/
void server_stats_obtain(struct worker* worker, struct worker* who,
struct stats_info* s, int reset);
/**
* Compile stats into structure for this thread worker.
* Also clears the statistics counters (if that is set by config file).
* @param worker: the worker to compile stats for, also the executing worker.
* @param s: stats block.
* @param reset: if true, depending on config stats are reset.
* if false, statistics are not reset.
*/
void server_stats_compile(struct worker* worker, struct stats_info* s,
int reset);
/**
* Send stats over comm tube in reply to query cmd
* @param worker: this worker.
* @param reset: if true, depending on config stats are reset.
* if false, statistics are not reset.
*/
void server_stats_reply(struct worker* worker, int reset);
/**
* Addup stat blocks.
* @param total: sum of the two entries.
* @param a: to add to it.
*/
void server_stats_add(struct stats_info* total, struct stats_info* a);
/**
* Add stats for this query
* @param stats: the stats
* @param c: commpoint with type and buffer.
* @param qtype: query type
* @param qclass: query class
* @param edns: edns record
* @param repinfo: reply info with remote address
*/
void server_stats_insquery(struct server_stats* stats, struct comm_point* c,
uint16_t qtype, uint16_t qclass, struct edns_data* edns,
struct comm_reply* repinfo);
/**
* Add rcode for this query.
* @param stats: the stats
* @param buf: buffer with rcode. If buffer is length0: not counted.
*/
void server_stats_insrcode(struct server_stats* stats, struct sldns_buffer* buf);
#endif /* DAEMON_STATS_H */

780
external/unbound/daemon/unbound.c vendored Normal file
View File

@ -0,0 +1,780 @@
/*
* daemon/unbound.c - main program for unbound DNS resolver daemon.
*
* Copyright (c) 2007, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* \file
*
* Main program to start the DNS resolver daemon.
*/
#include "config.h"
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
#include <sys/time.h>
#include "util/log.h"
#include "daemon/daemon.h"
#include "daemon/remote.h"
#include "util/config_file.h"
#include "util/storage/slabhash.h"
#include "services/listen_dnsport.h"
#include "services/cache/rrset.h"
#include "services/cache/infra.h"
#include "util/fptr_wlist.h"
#include "util/data/msgreply.h"
#include "util/module.h"
#include "util/net_help.h"
#include <signal.h>
#include <fcntl.h>
#include <openssl/crypto.h>
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif
#ifdef HAVE_GRP_H
#include <grp.h>
#endif
#ifndef S_SPLINT_S
/* splint chokes on this system header file */
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
#endif /* S_SPLINT_S */
#ifdef HAVE_LOGIN_CAP_H
#include <login_cap.h>
#endif
#ifdef USE_MINI_EVENT
# ifdef USE_WINSOCK
# include "util/winsock_event.h"
# else
# include "util/mini_event.h"
# endif
#else
# ifdef HAVE_EVENT_H
# include <event.h>
# else
# include "event2/event.h"
# include "event2/event_struct.h"
# include "event2/event_compat.h"
# endif
#endif
#ifdef UB_ON_WINDOWS
# include "winrc/win_svc.h"
#endif
#ifdef HAVE_NSS
/* nss3 */
# include "nss.h"
#endif
#ifdef HAVE_SBRK
/** global debug value to keep track of heap memory allocation */
void* unbound_start_brk = 0;
#endif
#if !defined(HAVE_EVENT_BASE_GET_METHOD) && (defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP))
static const char* ev_backend2str(int b)
{
switch(b) {
case EVBACKEND_SELECT: return "select";
case EVBACKEND_POLL: return "poll";
case EVBACKEND_EPOLL: return "epoll";
case EVBACKEND_KQUEUE: return "kqueue";
case EVBACKEND_DEVPOLL: return "devpoll";
case EVBACKEND_PORT: return "evport";
}
return "unknown";
}
#endif
/** get the event system in use */
static void get_event_sys(const char** n, const char** s, const char** m)
{
#ifdef USE_WINSOCK
*n = "event";
*s = "winsock";
*m = "WSAWaitForMultipleEvents";
#elif defined(USE_MINI_EVENT)
*n = "mini-event";
*s = "internal";
*m = "select";
#else
struct event_base* b;
*s = event_get_version();
# ifdef HAVE_EVENT_BASE_GET_METHOD
*n = "libevent";
b = event_base_new();
*m = event_base_get_method(b);
# elif defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
*n = "libev";
b = (struct event_base*)ev_default_loop(EVFLAG_AUTO);
*m = ev_backend2str(ev_backend((struct ev_loop*)b));
# else
*n = "unknown";
*m = "not obtainable";
b = NULL;
# endif
# ifdef HAVE_EVENT_BASE_FREE
event_base_free(b);
# endif
#endif
}
/** print usage. */
static void usage()
{
const char** m;
const char *evnm="event", *evsys="", *evmethod="";
printf("usage: unbound [options]\n");
printf(" start unbound daemon DNS resolver.\n");
printf("-h this help\n");
printf("-c file config file to read instead of %s\n", CONFIGFILE);
printf(" file format is described in unbound.conf(5).\n");
printf("-d do not fork into the background.\n");
printf("-v verbose (more times to increase verbosity)\n");
#ifdef UB_ON_WINDOWS
printf("-w opt windows option: \n");
printf(" install, remove - manage the services entry\n");
printf(" service - used to start from services control panel\n");
#endif
printf("Version %s\n", PACKAGE_VERSION);
get_event_sys(&evnm, &evsys, &evmethod);
printf("linked libs: %s %s (it uses %s), %s\n",
evnm, evsys, evmethod,
#ifdef HAVE_SSL
SSLeay_version(SSLEAY_VERSION)
#elif defined(HAVE_NSS)
NSS_GetVersion()
#endif
);
printf("linked modules:");
for(m = module_list_avail(); *m; m++)
printf(" %s", *m);
printf("\n");
printf("BSD licensed, see LICENSE in source package for details.\n");
printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
}
#ifndef unbound_testbound
int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
{
log_assert(0);
return 0;
}
#endif
/** check file descriptor count */
static void
checkrlimits(struct config_file* cfg)
{
#ifndef S_SPLINT_S
#ifdef HAVE_GETRLIMIT
/* list has number of ports to listen to, ifs number addresses */
int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
(int)cfg->incoming_num_tcp:0));
size_t listen_ifs = (size_t)(cfg->num_ifs==0?
((cfg->do_ip4 && !cfg->if_automatic?1:0) +
(cfg->do_ip6?1:0)):cfg->num_ifs);
size_t listen_num = list*listen_ifs;
size_t outudpnum = (size_t)cfg->outgoing_num_ports;
size_t outtcpnum = cfg->outgoing_num_tcp;
size_t misc = 4; /* logfile, pidfile, stdout... */
size_t perthread_noudp = listen_num + outtcpnum +
2/*cmdpipe*/ + 2/*libevent*/ + misc;
size_t perthread = perthread_noudp + outudpnum;
#if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
int numthread = 1; /* it forks */
#else
int numthread = (cfg->num_threads?cfg->num_threads:1);
#endif
size_t total = numthread * perthread + misc;
size_t avail;
struct rlimit rlim;
if(total > 1024 &&
strncmp(event_get_version(), "mini-event", 10) == 0) {
log_warn("too many file descriptors requested. The builtin"
"mini-event cannot handle more than 1024. Config "
"for less fds or compile with libevent");
if(numthread*perthread_noudp+15 > 1024)
fatal_exit("too much tcp. not enough fds.");
cfg->outgoing_num_ports = (int)((1024
- numthread*perthread_noudp
- 10 /* safety margin */) /numthread);
log_warn("continuing with less udp ports: %u",
cfg->outgoing_num_ports);
total = 1024;
}
if(perthread > 64 &&
strncmp(event_get_version(), "winsock-event", 13) == 0) {
log_err("too many file descriptors requested. The winsock"
" event handler cannot handle more than 64 per "
" thread. Config for less fds");
if(perthread_noudp+2 > 64)
fatal_exit("too much tcp. not enough fds.");
cfg->outgoing_num_ports = (int)((64
- perthread_noudp
- 2/* safety margin */));
log_warn("continuing with less udp ports: %u",
cfg->outgoing_num_ports);
total = numthread*(perthread_noudp+
(size_t)cfg->outgoing_num_ports)+misc;
}
if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
log_warn("getrlimit: %s", strerror(errno));
return;
}
if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
return;
if((size_t)rlim.rlim_cur < total) {
avail = (size_t)rlim.rlim_cur;
rlim.rlim_cur = (rlim_t)(total + 10);
rlim.rlim_max = (rlim_t)(total + 10);
#ifdef HAVE_SETRLIMIT
if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
log_warn("setrlimit: %s", strerror(errno));
#endif
log_warn("cannot increase max open fds from %u to %u",
(unsigned)avail, (unsigned)total+10);
/* check that calculation below does not underflow,
* with 15 as margin */
if(numthread*perthread_noudp+15 > avail)
fatal_exit("too much tcp. not enough fds.");
cfg->outgoing_num_ports = (int)((avail
- numthread*perthread_noudp
- 10 /* safety margin */) /numthread);
log_warn("continuing with less udp ports: %u",
cfg->outgoing_num_ports);
log_warn("increase ulimit or decrease threads, "
"ports in config to remove this warning");
return;
#ifdef HAVE_SETRLIMIT
}
#endif
log_warn("increased limit(open files) from %u to %u",
(unsigned)avail, (unsigned)total+10);
}
#else
(void)cfg;
#endif /* HAVE_GETRLIMIT */
#endif /* S_SPLINT_S */
}
/** set verbosity, check rlimits, cache settings */
static void
apply_settings(struct daemon* daemon, struct config_file* cfg,
int cmdline_verbose, int debug_mode)
{
/* apply if they have changed */
verbosity = cmdline_verbose + cfg->verbosity;
if (debug_mode > 1) {
cfg->use_syslog = 0;
cfg->logfile = NULL;
}
daemon_apply_cfg(daemon, cfg);
checkrlimits(cfg);
}
#ifdef HAVE_KILL
/** Read existing pid from pidfile.
* @param file: file name of pid file.
* @return: the pid from the file or -1 if none.
*/
static pid_t
readpid (const char* file)
{
int fd;
pid_t pid;
char pidbuf[32];
char* t;
ssize_t l;
if ((fd = open(file, O_RDONLY)) == -1) {
if(errno != ENOENT)
log_err("Could not read pidfile %s: %s",
file, strerror(errno));
return -1;
}
if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
if(errno != ENOENT)
log_err("Could not read pidfile %s: %s",
file, strerror(errno));
close(fd);
return -1;
}
close(fd);
/* Empty pidfile means no pidfile... */
if (l == 0) {
return -1;
}
pidbuf[sizeof(pidbuf)-1] = 0;
pid = (pid_t)strtol(pidbuf, &t, 10);
if (*t && *t != '\n') {
return -1;
}
return pid;
}
/** write pid to file.
* @param pidfile: file name of pid file.
* @param pid: pid to write to file.
*/
static void
writepid (const char* pidfile, pid_t pid)
{
FILE* f;
if ((f = fopen(pidfile, "w")) == NULL ) {
log_err("cannot open pidfile %s: %s",
pidfile, strerror(errno));
return;
}
if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
log_err("cannot write to pidfile %s: %s",
pidfile, strerror(errno));
}
fclose(f);
}
/**
* check old pid file.
* @param pidfile: the file name of the pid file.
* @param inchroot: if pidfile is inchroot and we can thus expect to
* be able to delete it.
*/
static void
checkoldpid(char* pidfile, int inchroot)
{
pid_t old;
if((old = readpid(pidfile)) != -1) {
/* see if it is still alive */
if(kill(old, 0) == 0 || errno == EPERM)
log_warn("unbound is already running as pid %u.",
(unsigned)old);
else if(inchroot)
log_warn("did not exit gracefully last time (%u)",
(unsigned)old);
}
}
#endif /* HAVE_KILL */
/** detach from command line */
static void
detach(void)
{
#if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
/* use POSIX daemon(3) function */
if(daemon(1, 0) != 0)
fatal_exit("daemon failed: %s", strerror(errno));
#else /* no HAVE_DAEMON */
#ifdef HAVE_FORK
int fd;
/* Take off... */
switch (fork()) {
case 0:
break;
case -1:
fatal_exit("fork failed: %s", strerror(errno));
default:
/* exit interactive session */
exit(0);
}
/* detach */
#ifdef HAVE_SETSID
if(setsid() == -1)
fatal_exit("setsid() failed: %s", strerror(errno));
#endif
if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
(void)dup2(fd, STDIN_FILENO);
(void)dup2(fd, STDOUT_FILENO);
(void)dup2(fd, STDERR_FILENO);
if (fd > 2)
(void)close(fd);
}
#endif /* HAVE_FORK */
#endif /* HAVE_DAEMON */
}
/** daemonize, drop user priviliges and chroot if needed */
static void
perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
const char** cfgfile)
{
#ifdef HAVE_GETPWNAM
struct passwd *pwd = NULL;
uid_t uid;
gid_t gid;
/* initialize, but not to 0 (root) */
memset(&uid, 112, sizeof(uid));
memset(&gid, 112, sizeof(gid));
log_assert(cfg);
if(cfg->username && cfg->username[0]) {
if((pwd = getpwnam(cfg->username)) == NULL)
fatal_exit("user '%s' does not exist.", cfg->username);
uid = pwd->pw_uid;
gid = pwd->pw_gid;
/* endpwent below, in case we need pwd for setusercontext */
}
#endif
/* init syslog (as root) if needed, before daemonize, otherwise
* a fork error could not be printed since daemonize closed stderr.*/
if(cfg->use_syslog) {
log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
}
/* if using a logfile, we cannot open it because the logfile would
* be created with the wrong permissions, we cannot chown it because
* we cannot chown system logfiles, so we do not open at all.
* So, using a logfile, the user does not see errors unless -d is
* given to unbound on the commandline. */
/* read ssl keys while superuser and outside chroot */
#ifdef HAVE_SSL
if(!(daemon->rc = daemon_remote_create(cfg)))
fatal_exit("could not set up remote-control");
if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
if(!(daemon->listen_sslctx = listen_sslctx_create(
cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
fatal_exit("could not set up listen SSL_CTX");
}
if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
fatal_exit("could not set up connect SSL_CTX");
#endif
#ifdef HAVE_KILL
/* check old pid file before forking */
if(cfg->pidfile && cfg->pidfile[0]) {
/* calculate position of pidfile */
if(cfg->pidfile[0] == '/')
daemon->pidfile = strdup(cfg->pidfile);
else daemon->pidfile = fname_after_chroot(cfg->pidfile,
cfg, 1);
if(!daemon->pidfile)
fatal_exit("pidfile alloc: out of memory");
checkoldpid(daemon->pidfile,
/* true if pidfile is inside chrootdir, or nochroot */
!(cfg->chrootdir && cfg->chrootdir[0]) ||
(cfg->chrootdir && cfg->chrootdir[0] &&
strncmp(daemon->pidfile, cfg->chrootdir,
strlen(cfg->chrootdir))==0));
}
#endif
/* daemonize because pid is needed by the writepid func */
if(!debug_mode && cfg->do_daemonize) {
detach();
}
/* write new pidfile (while still root, so can be outside chroot) */
#ifdef HAVE_KILL
if(cfg->pidfile && cfg->pidfile[0]) {
writepid(daemon->pidfile, getpid());
if(!(cfg->chrootdir && cfg->chrootdir[0]) ||
(cfg->chrootdir && cfg->chrootdir[0] &&
strncmp(daemon->pidfile, cfg->chrootdir,
strlen(cfg->chrootdir))==0)) {
/* delete of pidfile could potentially work,
* chown to get permissions */
if(cfg->username && cfg->username[0]) {
if(chown(daemon->pidfile, uid, gid) == -1) {
log_err("cannot chown %u.%u %s: %s",
(unsigned)uid, (unsigned)gid,
daemon->pidfile, strerror(errno));
}
}
}
}
#else
(void)daemon;
#endif
/* Set user context */
#ifdef HAVE_GETPWNAM
if(cfg->username && cfg->username[0]) {
#ifdef HAVE_SETUSERCONTEXT
/* setusercontext does initgroups, setuid, setgid, and
* also resource limits from login config, but we
* still call setresuid, setresgid to be sure to set all uid*/
if(setusercontext(NULL, pwd, uid, (unsigned)
LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
log_warn("unable to setusercontext %s: %s",
cfg->username, strerror(errno));
#endif /* HAVE_SETUSERCONTEXT */
}
#endif /* HAVE_GETPWNAM */
/* box into the chroot */
#ifdef HAVE_CHROOT
if(cfg->chrootdir && cfg->chrootdir[0]) {
if(chdir(cfg->chrootdir)) {
fatal_exit("unable to chdir to chroot %s: %s",
cfg->chrootdir, strerror(errno));
}
verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
if(chroot(cfg->chrootdir))
fatal_exit("unable to chroot to %s: %s",
cfg->chrootdir, strerror(errno));
if(chdir("/"))
fatal_exit("unable to chdir to / in chroot %s: %s",
cfg->chrootdir, strerror(errno));
verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
if(strncmp(*cfgfile, cfg->chrootdir,
strlen(cfg->chrootdir)) == 0)
(*cfgfile) += strlen(cfg->chrootdir);
/* adjust stored pidfile for chroot */
if(daemon->pidfile && daemon->pidfile[0] &&
strncmp(daemon->pidfile, cfg->chrootdir,
strlen(cfg->chrootdir))==0) {
char* old = daemon->pidfile;
daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
free(old);
if(!daemon->pidfile)
log_err("out of memory in pidfile adjust");
}
daemon->chroot = strdup(cfg->chrootdir);
if(!daemon->chroot)
log_err("out of memory in daemon chroot dir storage");
}
#else
(void)cfgfile;
#endif
/* change to working directory inside chroot */
if(cfg->directory && cfg->directory[0]) {
char* dir = cfg->directory;
if(cfg->chrootdir && cfg->chrootdir[0] &&
strncmp(dir, cfg->chrootdir,
strlen(cfg->chrootdir)) == 0)
dir += strlen(cfg->chrootdir);
if(dir[0]) {
if(chdir(dir)) {
fatal_exit("Could not chdir to %s: %s",
dir, strerror(errno));
}
verbose(VERB_QUERY, "chdir to %s", dir);
}
}
/* drop permissions after chroot, getpwnam, pidfile, syslog done*/
#ifdef HAVE_GETPWNAM
if(cfg->username && cfg->username[0]) {
# ifdef HAVE_INITGROUPS
if(initgroups(cfg->username, gid) != 0)
log_warn("unable to initgroups %s: %s",
cfg->username, strerror(errno));
# endif /* HAVE_INITGROUPS */
endpwent();
#ifdef HAVE_SETRESGID
if(setresgid(gid,gid,gid) != 0)
#elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
if(setregid(gid,gid) != 0)
#else /* use setgid */
if(setgid(gid) != 0)
#endif /* HAVE_SETRESGID */
fatal_exit("unable to set group id of %s: %s",
cfg->username, strerror(errno));
#ifdef HAVE_SETRESUID
if(setresuid(uid,uid,uid) != 0)
#elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
if(setreuid(uid,uid) != 0)
#else /* use setuid */
if(setuid(uid) != 0)
#endif /* HAVE_SETRESUID */
fatal_exit("unable to set user id of %s: %s",
cfg->username, strerror(errno));
verbose(VERB_QUERY, "drop user privileges, run as %s",
cfg->username);
}
#endif /* HAVE_GETPWNAM */
/* file logging inited after chroot,chdir,setuid is done so that
* it would succeed on SIGHUP as well */
if(!cfg->use_syslog)
log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
}
/**
* Run the daemon.
* @param cfgfile: the config file name.
* @param cmdline_verbose: verbosity resulting from commandline -v.
* These increase verbosity as specified in the config file.
* @param debug_mode: if set, do not daemonize.
*/
static void
run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode)
{
struct config_file* cfg = NULL;
struct daemon* daemon = NULL;
int done_setup = 0;
if(!(daemon = daemon_init()))
fatal_exit("alloc failure");
while(!daemon->need_to_exit) {
if(done_setup)
verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
/* config stuff */
if(!(cfg = config_create()))
fatal_exit("Could not alloc config defaults");
if(!config_read(cfg, cfgfile, daemon->chroot)) {
if(errno != ENOENT)
fatal_exit("Could not read config file: %s",
cfgfile);
log_warn("Continuing with default config settings");
}
apply_settings(daemon, cfg, cmdline_verbose, debug_mode);
/* prepare */
if(!daemon_open_shared_ports(daemon))
fatal_exit("could not open ports");
if(!done_setup) {
perform_setup(daemon, cfg, debug_mode, &cfgfile);
done_setup = 1;
} else {
/* reopen log after HUP to facilitate log rotation */
if(!cfg->use_syslog)
log_init(cfg->logfile, 0, cfg->chrootdir);
}
/* work */
daemon_fork(daemon);
/* clean up for restart */
verbose(VERB_ALGO, "cleanup.");
daemon_cleanup(daemon);
config_delete(cfg);
}
verbose(VERB_ALGO, "Exit cleanup.");
/* this unlink may not work if the pidfile is located outside
* of the chroot/workdir or we no longer have permissions */
if(daemon->pidfile) {
int fd;
/* truncate pidfile */
fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
if(fd != -1)
close(fd);
/* delete pidfile */
unlink(daemon->pidfile);
}
daemon_delete(daemon);
}
/** getopt global, in case header files fail to declare it. */
extern int optind;
/** getopt global, in case header files fail to declare it. */
extern char* optarg;
/**
* main program. Set options given commandline arguments.
* @param argc: number of commandline arguments.
* @param argv: array of commandline arguments.
* @return: exit status of the program.
*/
int
main(int argc, char* argv[])
{
int c;
const char* cfgfile = CONFIGFILE;
const char* winopt = NULL;
int cmdline_verbose = 0;
int debug_mode = 0;
#ifdef UB_ON_WINDOWS
int cmdline_cfg = 0;
#endif
#ifdef HAVE_SBRK
/* take debug snapshot of heap */
unbound_start_brk = sbrk(0);
#endif
log_init(NULL, 0, NULL);
log_ident_set(strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0]);
/* parse the options */
while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
switch(c) {
case 'c':
cfgfile = optarg;
#ifdef UB_ON_WINDOWS
cmdline_cfg = 1;
#endif
break;
case 'v':
cmdline_verbose ++;
verbosity++;
break;
case 'd':
debug_mode++;
break;
case 'w':
winopt = optarg;
break;
case '?':
case 'h':
default:
usage();
return 1;
}
}
argc -= optind;
argv += optind;
if(winopt) {
#ifdef UB_ON_WINDOWS
wsvc_command_option(winopt, cfgfile, cmdline_verbose,
cmdline_cfg);
#else
fatal_exit("option not supported");
#endif
}
if(argc != 0) {
usage();
return 1;
}
run_daemon(cfgfile, cmdline_verbose, debug_mode);
log_init(NULL, 0, NULL); /* close logfile */
return 0;
}

1452
external/unbound/daemon/worker.c vendored Normal file

File diff suppressed because it is too large Load Diff

173
external/unbound/daemon/worker.h vendored Normal file
View File

@ -0,0 +1,173 @@
/*
* daemon/worker.h - worker that handles a pending list of requests.
*
* Copyright (c) 2007, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* This file describes the worker structure that holds a list of
* pending requests and handles them.
*/
#ifndef DAEMON_WORKER_H
#define DAEMON_WORKER_H
#include "libunbound/worker.h"
#include "util/netevent.h"
#include "util/locks.h"
#include "util/alloc.h"
#include "util/data/msgreply.h"
#include "util/data/msgparse.h"
#include "daemon/stats.h"
#include "util/module.h"
#include "dnstap/dnstap.h"
struct listen_dnsport;
struct outside_network;
struct config_file;
struct daemon;
struct listen_port;
struct ub_randstate;
struct regional;
struct tube;
struct daemon_remote;
/** worker commands */
enum worker_commands {
/** make the worker quit */
worker_cmd_quit,
/** obtain statistics */
worker_cmd_stats,
/** obtain statistics without statsclear */
worker_cmd_stats_noreset,
/** execute remote control command */
worker_cmd_remote
};
/**
* Structure holding working information for unbound.
* Holds globally visible information.
*/
struct worker {
/** the thread number (in daemon array). First in struct for debug. */
int thread_num;
/** global shared daemon structure */
struct daemon* daemon;
/** thread id */
ub_thread_t thr_id;
/** pipe, for commands for this worker */
struct tube* cmd;
/** the event base this worker works with */
struct comm_base* base;
/** the frontside listening interface where request events come in */
struct listen_dnsport* front;
/** the backside outside network interface to the auth servers */
struct outside_network* back;
/** ports to be used by this worker. */
int* ports;
/** number of ports for this worker */
int numports;
/** the signal handler */
struct comm_signal* comsig;
/** commpoint to listen to commands. */
struct comm_point* cmd_com;
/** timer for statistics */
struct comm_timer* stat_timer;
/** random() table for this worker. */
struct ub_randstate* rndstate;
/** do we need to restart or quit (on signal) */
int need_to_exit;
/** allocation cache for this thread */
struct alloc_cache alloc;
/** per thread statistics */
struct server_stats stats;
/** thread scratch regional */
struct regional* scratchpad;
/** module environment passed to modules, changed for this thread */
struct module_env env;
#ifdef USE_DNSTAP
/** dnstap environment, changed for this thread */
struct dt_env dtenv;
#endif
};
/**
* Create the worker structure. Bare bones version, zeroed struct,
* with backpointers only. Use worker_init on it later.
* @param daemon: the daemon that this worker thread is part of.
* @param id: the thread number from 0.. numthreads-1.
* @param ports: the ports it is allowed to use, array.
* @param n: the number of ports.
* @return: the new worker or NULL on alloc failure.
*/
struct worker* worker_create(struct daemon* daemon, int id, int* ports, int n);
/**
* Initialize worker.
* Allocates event base, listens to ports
* @param worker: worker to initialize, created with worker_create.
* @param cfg: configuration settings.
* @param ports: list of shared query ports.
* @param do_sigs: if true, worker installs signal handlers.
* @return: false on error.
*/
int worker_init(struct worker* worker, struct config_file *cfg,
struct listen_port* ports, int do_sigs);
/**
* Make worker work.
*/
void worker_work(struct worker* worker);
/**
* Delete worker.
*/
void worker_delete(struct worker* worker);
/**
* Send a command to a worker. Uses blocking writes.
* @param worker: worker to send command to.
* @param cmd: command to send.
*/
void worker_send_cmd(struct worker* worker, enum worker_commands cmd);
/**
* Init worker stats - includes server_stats_init, outside network and mesh.
* @param worker: the worker to init
*/
void worker_stats_clear(struct worker* worker);
#endif /* DAEMON_WORKER_H */

865
external/unbound/dns64/dns64.c vendored Normal file
View File

@ -0,0 +1,865 @@
/*
* dns64/dns64.c - DNS64 module
*
* Copyright (c) 2009, Viagénie. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Viagénie nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* This file contains a module that performs DNS64 query processing.
*/
#include "config.h"
#include "dns64/dns64.h"
#include "services/cache/dns.h"
#include "services/cache/rrset.h"
#include "util/config_file.h"
#include "util/data/msgreply.h"
#include "util/fptr_wlist.h"
#include "util/net_help.h"
#include "util/regional.h"
/******************************************************************************
* *
* STATIC CONSTANTS *
* *
******************************************************************************/
/**
* This is the default DNS64 prefix that is used whent he dns64 module is listed
* in module-config but when the dns64-prefix variable is not present.
*/
static const char DEFAULT_DNS64_PREFIX[] = "64:ff9b::/96";
/**
* Maximum length of a domain name in a PTR query in the .in-addr.arpa tree.
*/
#define MAX_PTR_QNAME_IPV4 30
/**
* Per-query module-specific state. This is usually a dynamically-allocated
* structure, but in our case we only need to store one variable describing the
* state the query is in. So we repurpose the minfo pointer by storing an
* integer in there.
*/
enum dns64_qstate {
DNS64_INTERNAL_QUERY, /**< Internally-generated query, no DNS64
processing. */
DNS64_NEW_QUERY, /**< Query for which we're the first module in
line. */
DNS64_SUBQUERY_FINISHED /**< Query for which we generated a sub-query, and
for which this sub-query is finished. */
};
/******************************************************************************
* *
* STRUCTURES *
* *
******************************************************************************/
/**
* This structure contains module configuration information. One instance of
* this structure exists per instance of the module. Normally there is only one
* instance of the module.
*/
struct dns64_env {
/**
* DNS64 prefix address. We're using a full sockaddr instead of just an
* in6_addr because we can reuse Unbound's generic string parsing functions.
* It will always contain a sockaddr_in6, and only the sin6_addr member will
* ever be used.
*/
struct sockaddr_storage prefix_addr;
/**
* This is always sizeof(sockaddr_in6).
*/
socklen_t prefix_addrlen;
/**
* This is the CIDR length of the prefix. It needs to be between 0 and 96.
*/
int prefix_net;
};
/******************************************************************************
* *
* UTILITY FUNCTIONS *
* *
******************************************************************************/
/**
* Generic macro for swapping two variables.
*
* \param t Type of the variables. (e.g. int)
* \param a First variable.
* \param b Second variable.
*
* \warning Do not attempt something foolish such as swap(int,a++,b++)!
*/
#define swap(t,a,b) do {t x = a; a = b; b = x;} while(0)
/**
* Reverses a string.
*
* \param begin Points to the first character of the string.
* \param end Points one past the last character of the string.
*/
static void
reverse(char* begin, char* end)
{
while ( begin < --end ) {
swap(char, *begin, *end);
++begin;
}
}
/**
* Convert an unsigned integer to a string. The point of this function is that
* of being faster than sprintf().
*
* \param n The number to be converted.
* \param s The result will be written here. Must be large enough, be careful!
*
* \return The number of characters written.
*/
static int
uitoa(unsigned n, char* s)
{
char* ss = s;
do {
*ss++ = '0' + n % 10;
} while (n /= 10);
reverse(s, ss);
return ss - s;
}
/**
* Extract an IPv4 address embedded in the IPv6 address \a ipv6 at offset \a
* offset (in bits). Note that bits are not necessarily aligned on bytes so we
* need to be careful.
*
* \param ipv6 IPv6 address represented as a 128-bit array in big-endian
* order.
* \param offset Index of the MSB of the IPv4 address embedded in the IPv6
* address.
*/
static uint32_t
extract_ipv4(const uint8_t ipv6[16], const int offset)
{
uint32_t ipv4 = (uint32_t)ipv6[offset/8+0] << (24 + (offset%8))
| (uint32_t)ipv6[offset/8+1] << (16 + (offset%8))
| (uint32_t)ipv6[offset/8+2] << ( 8 + (offset%8))
| (uint32_t)ipv6[offset/8+3] << ( 0 + (offset%8));
if (offset/8+4 < 16)
ipv4 |= (uint32_t)ipv6[offset/8+4] >> (8 - offset%8);
return ipv4;
}
/**
* Builds the PTR query name corresponding to an IPv4 address. For example,
* given the number 3,464,175,361, this will build the string
* "\03206\03123\0231\011\07in-addr\04arpa".
*
* \param ipv4 IPv4 address represented as an unsigned 32-bit number.
* \param ptr The result will be written here. Must be large enough, be
* careful!
*
* \return The number of characters written.
*/
static size_t
ipv4_to_ptr(uint32_t ipv4, char ptr[MAX_PTR_QNAME_IPV4])
{
static const char IPV4_PTR_SUFFIX[] = "\07in-addr\04arpa";
int i;
char* c = ptr;
for (i = 0; i < 4; ++i) {
*c = uitoa((unsigned int)(ipv4 % 256), c + 1);
c += *c + 1;
ipv4 /= 256;
}
memmove(c, IPV4_PTR_SUFFIX, sizeof(IPV4_PTR_SUFFIX));
return c + sizeof(IPV4_PTR_SUFFIX) - ptr;
}
/**
* Converts an IPv6-related domain name string from a PTR query into an IPv6
* address represented as a 128-bit array.
*
* \param ptr The domain name. (e.g. "\011[...]\010\012\016\012\03ip6\04arpa")
* \param ipv6 The result will be written here, in network byte order.
*
* \return 1 on success, 0 on failure.
*/
static int
ptr_to_ipv6(const char* ptr, uint8_t ipv6[16])
{
int i;
for (i = 0; i < 64; i++) {
int x;
if (ptr[i++] != 1)
return 0;
if (ptr[i] >= '0' && ptr[i] <= '9') {
x = ptr[i] - '0';
} else if (ptr[i] >= 'a' && ptr[i] <= 'f') {
x = ptr[i] - 'a' + 10;
} else if (ptr[i] >= 'A' && ptr[i] <= 'F') {
x = ptr[i] - 'A' + 10;
} else {
return 0;
}
ipv6[15-i/4] |= x << (2 * ((i-1) % 4));
}
return 1;
}
/**
* Synthesize an IPv6 address based on an IPv4 address and the DNS64 prefix.
*
* \param prefix_addr DNS64 prefix address.
* \param prefix_net CIDR length of the DNS64 prefix. Must be between 0 and 96.
* \param a IPv4 address.
* \param aaaa IPv6 address. The result will be written here.
*/
static void
synthesize_aaaa(const uint8_t prefix_addr[16], int prefix_net,
const uint8_t a[4], uint8_t aaaa[16])
{
memcpy(aaaa, prefix_addr, 16);
aaaa[prefix_net/8+0] |= a[0] >> (0+prefix_net%8);
aaaa[prefix_net/8+1] |= a[0] << (8-prefix_net%8);
aaaa[prefix_net/8+1] |= a[1] >> (0+prefix_net%8);
aaaa[prefix_net/8+2] |= a[1] << (8-prefix_net%8);
aaaa[prefix_net/8+2] |= a[2] >> (0+prefix_net%8);
aaaa[prefix_net/8+3] |= a[2] << (8-prefix_net%8);
aaaa[prefix_net/8+3] |= a[3] >> (0+prefix_net%8);
if (prefix_net/8+4 < 16) /* <-- my beautiful symmetry is destroyed! */
aaaa[prefix_net/8+4] |= a[3] << (8-prefix_net%8);
}
/******************************************************************************
* *
* DNS64 MODULE FUNCTIONS *
* *
******************************************************************************/
/**
* This function applies the configuration found in the parsed configuration
* file \a cfg to this instance of the dns64 module. Currently only the DNS64
* prefix (a.k.a. Pref64) is configurable.
*
* \param dns64_env Module-specific global parameters.
* \param cfg Parsed configuration file.
*/
static int
dns64_apply_cfg(struct dns64_env* dns64_env, struct config_file* cfg)
{
verbose(VERB_ALGO, "dns64-prefix: %s", cfg->dns64_prefix);
if (!netblockstrtoaddr(cfg->dns64_prefix ? cfg->dns64_prefix :
DEFAULT_DNS64_PREFIX, 0, &dns64_env->prefix_addr,
&dns64_env->prefix_addrlen, &dns64_env->prefix_net)) {
log_err("cannot parse dns64-prefix netblock: %s", cfg->dns64_prefix);
return 0;
}
if (!addr_is_ip6(&dns64_env->prefix_addr, dns64_env->prefix_addrlen)) {
log_err("dns64_prefix is not IPv6: %s", cfg->dns64_prefix);
return 0;
}
if (dns64_env->prefix_net < 0 || dns64_env->prefix_net > 96) {
log_err("dns64-prefix length it not between 0 and 96: %s",
cfg->dns64_prefix);
return 0;
}
return 1;
}
/**
* Initializes this instance of the dns64 module.
*
* \param env Global state of all module instances.
* \param id This instance's ID number.
*/
int
dns64_init(struct module_env* env, int id)
{
struct dns64_env* dns64_env =
(struct dns64_env*)calloc(1, sizeof(struct dns64_env));
if (!dns64_env) {
log_err("malloc failure");
return 0;
}
env->modinfo[id] = (void*)dns64_env;
if (!dns64_apply_cfg(dns64_env, env->cfg)) {
log_err("dns64: could not apply configuration settings.");
return 0;
}
return 1;
}
/**
* Deinitializes this instance of the dns64 module.
*
* \param env Global state of all module instances.
* \param id This instance's ID number.
*/
void
dns64_deinit(struct module_env* env, int id)
{
if (!env)
return;
free(env->modinfo[id]);
env->modinfo[id] = NULL;
}
/**
* Handle PTR queries for IPv6 addresses. If the address belongs to the DNS64
* prefix, we must do a PTR query for the corresponding IPv4 address instead.
*
* \param qstate Query state structure.
* \param id This module instance's ID number.
*
* \return The new state of the query.
*/
static enum module_ext_state
handle_ipv6_ptr(struct module_qstate* qstate, int id)
{
struct dns64_env* dns64_env = (struct dns64_env*)qstate->env->modinfo[id];
struct module_qstate* subq = NULL;
struct query_info qinfo;
struct sockaddr_in6 sin6;
/* Convert the PTR query string to an IPv6 address. */
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
if (!ptr_to_ipv6((char*)qstate->qinfo.qname, sin6.sin6_addr.s6_addr))
return module_wait_module; /* Let other module handle this. */
/*
* If this IPv6 address is not part of our DNS64 prefix, then we don't need
* to do anything. Let another module handle the query.
*/
if (addr_in_common((struct sockaddr_storage*)&sin6, 128,
&dns64_env->prefix_addr, dns64_env->prefix_net,
(socklen_t)sizeof(sin6)) != dns64_env->prefix_net)
return module_wait_module;
verbose(VERB_ALGO, "dns64: rewrite PTR record");
/*
* Create a new PTR query info for the domain name corresponding to the IPv4
* address corresponding to the IPv6 address corresponding to the original
* PTR query domain name.
*/
qinfo = qstate->qinfo;
if (!(qinfo.qname = regional_alloc(qstate->region, MAX_PTR_QNAME_IPV4)))
return module_error;
qinfo.qname_len = ipv4_to_ptr(extract_ipv4(sin6.sin6_addr.s6_addr,
dns64_env->prefix_net), (char*)qinfo.qname);
/* Create the new sub-query. */
fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
if(!(*qstate->env->attach_sub)(qstate, &qinfo, qstate->query_flags, 0,
&subq))
return module_error;
if (subq) {
subq->curmod = id;
subq->ext_state[id] = module_state_initial;
subq->minfo[id] = NULL;
}
return module_wait_subquery;
}
/** allocate (special) rrset keys, return 0 on error */
static int
repinfo_alloc_rrset_keys(struct reply_info* rep,
struct regional* region)
{
size_t i;
for(i=0; i<rep->rrset_count; i++) {
if(region) {
rep->rrsets[i] = (struct ub_packed_rrset_key*)
regional_alloc(region,
sizeof(struct ub_packed_rrset_key));
if(rep->rrsets[i]) {
memset(rep->rrsets[i], 0,
sizeof(struct ub_packed_rrset_key));
rep->rrsets[i]->entry.key = rep->rrsets[i];
}
}
else return 0;/* rep->rrsets[i] = alloc_special_obtain(alloc);*/
if(!rep->rrsets[i])
return 0;
rep->rrsets[i]->entry.data = NULL;
}
return 1;
}
static enum module_ext_state
generate_type_A_query(struct module_qstate* qstate, int id)
{
struct module_qstate* subq = NULL;
struct query_info qinfo;
verbose(VERB_ALGO, "dns64: query A record");
/* Create a new query info. */
qinfo = qstate->qinfo;
qinfo.qtype = LDNS_RR_TYPE_A;
/* Start the sub-query. */
fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
if(!(*qstate->env->attach_sub)(qstate, &qinfo, qstate->query_flags, 0,
&subq))
{
verbose(VERB_ALGO, "dns64: sub-query creation failed");
return module_error;
}
if (subq) {
subq->curmod = id;
subq->ext_state[id] = module_state_initial;
subq->minfo[id] = NULL;
}
return module_wait_subquery;
}
/**
* Handles the "pass" event for a query. This event is received when a new query
* is received by this module. The query may have been generated internally by
* another module, in which case we don't want to do any special processing
* (this is an interesting discussion topic), or it may be brand new, e.g.
* received over a socket, in which case we do want to apply DNS64 processing.
*
* \param qstate A structure representing the state of the query that has just
* received the "pass" event.
* \param id This module's instance ID.
*
* \return The new state of the query.
*/
static enum module_ext_state
handle_event_pass(struct module_qstate* qstate, int id)
{
if ((uintptr_t)qstate->minfo[id] == DNS64_NEW_QUERY
&& qstate->qinfo.qtype == LDNS_RR_TYPE_PTR
&& qstate->qinfo.qname_len == 74
&& !strcmp((char*)&qstate->qinfo.qname[64], "\03ip6\04arpa"))
/* Handle PTR queries for IPv6 addresses. */
return handle_ipv6_ptr(qstate, id);
if (qstate->env->cfg->dns64_synthall &&
(uintptr_t)qstate->minfo[id] == DNS64_NEW_QUERY
&& qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA)
return generate_type_A_query(qstate, id);
/* We are finished when our sub-query is finished. */
if ((uintptr_t)qstate->minfo[id] == DNS64_SUBQUERY_FINISHED)
return module_finished;
/* Otherwise, pass request to next module. */
verbose(VERB_ALGO, "dns64: pass to next module");
return module_wait_module;
}
/**
* Handles the "done" event for a query. We need to analyze the response and
* maybe issue a new sub-query for the A record.
*
* \param qstate A structure representing the state of the query that has just
* received the "pass" event.
* \param id This module's instance ID.
*
* \return The new state of the query.
*/
static enum module_ext_state
handle_event_moddone(struct module_qstate* qstate, int id)
{
/*
* In many cases we have nothing special to do. From most to least common:
*
* - An internal query.
* - A query for a record type other than AAAA.
* - An AAAA query for which an error was returned.
* - A successful AAAA query with an answer.
*/
if ( (enum dns64_qstate)qstate->minfo[id] == DNS64_INTERNAL_QUERY
|| qstate->qinfo.qtype != LDNS_RR_TYPE_AAAA
|| qstate->return_rcode != LDNS_RCODE_NOERROR
|| (qstate->return_msg &&
qstate->return_msg->rep &&
reply_find_answer_rrset(&qstate->qinfo,
qstate->return_msg->rep)))
return module_finished;
/* So, this is a AAAA noerror/nodata answer */
return generate_type_A_query(qstate, id);
}
/**
* This is the module's main() function. It gets called each time a query
* receives an event which we may need to handle. We respond by updating the
* state of the query.
*
* \param qstate Structure containing the state of the query.
* \param event Event that has just been received.
* \param id This module's instance ID.
* \param outbound State of a DNS query on an authoritative server. We never do
* our own queries ourselves (other modules do it for us), so
* this is unused.
*/
void
dns64_operate(struct module_qstate* qstate, enum module_ev event, int id,
struct outbound_entry* outbound)
{
(void)outbound;
verbose(VERB_QUERY, "dns64[module %d] operate: extstate:%s event:%s",
id, strextstate(qstate->ext_state[id]),
strmodulevent(event));
log_query_info(VERB_QUERY, "dns64 operate: query", &qstate->qinfo);
switch(event) {
case module_event_new:
/* Tag this query as being new and fall through. */
qstate->minfo[id] = (void*)DNS64_NEW_QUERY;
case module_event_pass:
qstate->ext_state[id] = handle_event_pass(qstate, id);
break;
case module_event_moddone:
qstate->ext_state[id] = handle_event_moddone(qstate, id);
break;
default:
qstate->ext_state[id] = module_finished;
break;
}
}
static void
dns64_synth_aaaa_data(const struct ub_packed_rrset_key* fk,
const struct packed_rrset_data* fd,
struct ub_packed_rrset_key *dk,
struct packed_rrset_data **dd_out, struct regional *region,
struct dns64_env* dns64_env )
{
struct packed_rrset_data *dd;
size_t i;
/*
* Create synthesized AAAA RR set data. We need to allocated extra memory
* for the RRs themselves. Each RR has a length, TTL, pointer to wireformat
* data, 2 bytes of data length, and 16 bytes of IPv6 address.
*/
if (!(dd = *dd_out = regional_alloc(region,
sizeof(struct packed_rrset_data)
+ fd->count * (sizeof(size_t) + sizeof(time_t) +
sizeof(uint8_t*) + 2 + 16)))) {
log_err("out of memory");
return;
}
/* Copy attributes from A RR set. */
dd->ttl = fd->ttl;
dd->count = fd->count;
dd->rrsig_count = 0;
dd->trust = fd->trust;
dd->security = fd->security;
/*
* Synthesize AAAA records. Adjust pointers in structure.
*/
dd->rr_len =
(size_t*)((uint8_t*)dd + sizeof(struct packed_rrset_data));
dd->rr_data = (uint8_t**)&dd->rr_len[dd->count];
dd->rr_ttl = (time_t*)&dd->rr_data[dd->count];
for(i = 0; i < fd->count; ++i) {
if (fd->rr_len[i] != 6 || fd->rr_data[i][0] != 0
|| fd->rr_data[i][1] != 4)
return;
dd->rr_len[i] = 18;
dd->rr_data[i] =
(uint8_t*)&dd->rr_ttl[dd->count] + 18*i;
dd->rr_data[i][0] = 0;
dd->rr_data[i][1] = 16;
synthesize_aaaa(
((struct sockaddr_in6*)&dns64_env->prefix_addr)->sin6_addr.s6_addr,
dns64_env->prefix_net, &fd->rr_data[i][2],
&dd->rr_data[i][2] );
dd->rr_ttl[i] = fd->rr_ttl[i];
}
/*
* Create synthesized AAAA RR set key. This is mostly just bookkeeping,
* nothing interesting here.
*/
if(!dk) {
log_err("no key");
return;
}
dk->rk.dname = (uint8_t*)regional_alloc_init(region,
fk->rk.dname, fk->rk.dname_len);
if(!dk->rk.dname) {
log_err("out of memory");
return;
}
dk->rk.type = htons(LDNS_RR_TYPE_AAAA);
memset(&dk->entry, 0, sizeof(dk->entry));
dk->entry.key = dk;
dk->entry.hash = rrset_key_hash(&dk->rk);
dk->entry.data = dd;
}
/**
* Synthesize an AAAA RR set from an A sub-query's answer and add it to the
* original empty response.
*
* \param id This module's instance ID.
* \param super Original AAAA query.
* \param qstate A query.
*/
static void
dns64_adjust_a(int id, struct module_qstate* super, struct module_qstate* qstate)
{
struct dns64_env* dns64_env = (struct dns64_env*)super->env->modinfo[id];
struct reply_info *rep, *cp;
size_t i, s;
struct packed_rrset_data* fd, *dd;
struct ub_packed_rrset_key* fk, *dk;
verbose(VERB_ALGO, "converting A answers to AAAA answers");
log_assert(super->region);
log_assert(qstate->return_msg);
log_assert(qstate->return_msg->rep);
/* If dns64-synthall is enabled, return_msg is not initialized */
if(!super->return_msg) {
super->return_msg = (struct dns_msg*)regional_alloc(
super->region, sizeof(struct dns_msg));
if(!super->return_msg)
return;
memset(super->return_msg, 0, sizeof(*super->return_msg));
super->return_msg->qinfo = super->qinfo;
}
rep = qstate->return_msg->rep;
/*
* Build the actual reply.
*/
cp = construct_reply_info_base(super->region, rep->flags, rep->qdcount,
rep->ttl, rep->prefetch_ttl, rep->an_numrrsets, rep->ns_numrrsets,
rep->ar_numrrsets, rep->rrset_count, rep->security);
if(!cp)
return;
/* allocate ub_key structures special or not */
if(!repinfo_alloc_rrset_keys(cp, super->region)) {
return;
}
/* copy everything and replace A by AAAA */
for(i=0; i<cp->rrset_count; i++) {
fk = rep->rrsets[i];
dk = cp->rrsets[i];
fd = (struct packed_rrset_data*)fk->entry.data;
dk->rk = fk->rk;
dk->id = fk->id;
if(i<rep->an_numrrsets && fk->rk.type == htons(LDNS_RR_TYPE_A)) {
/* also sets dk->entry.hash */
dns64_synth_aaaa_data(fk, fd, dk, &dd, super->region, dns64_env);
/* Delete negative AAAA record from cache stored by
* the iterator module */
rrset_cache_remove(super->env->rrset_cache, dk->rk.dname,
dk->rk.dname_len, LDNS_RR_TYPE_AAAA,
LDNS_RR_CLASS_IN, 0);
} else {
dk->entry.hash = fk->entry.hash;
dk->rk.dname = (uint8_t*)regional_alloc_init(super->region,
fk->rk.dname, fk->rk.dname_len);
if(!dk->rk.dname)
return;
s = packed_rrset_sizeof(fd);
dd = (struct packed_rrset_data*)regional_alloc_init(
super->region, fd, s);
if(!dd)
return;
}
packed_rrset_ptr_fixup(dd);
dk->entry.data = (void*)dd;
}
/* Commit changes. */
super->return_msg->rep = cp;
}
/**
* Generate a response for the original IPv6 PTR query based on an IPv4 PTR
* sub-query's response.
*
* \param qstate IPv4 PTR sub-query.
* \param super Original IPv6 PTR query.
*/
static void
dns64_adjust_ptr(struct module_qstate* qstate, struct module_qstate* super)
{
struct ub_packed_rrset_key* answer;
verbose(VERB_ALGO, "adjusting PTR reply");
/* Copy the sub-query's reply to the parent. */
if (!(super->return_msg = (struct dns_msg*)regional_alloc(super->region,
sizeof(struct dns_msg))))
return;
super->return_msg->qinfo = super->qinfo;
super->return_msg->rep = reply_info_copy(qstate->return_msg->rep, NULL,
super->region);
/*
* Adjust the domain name of the answer RR set so that it matches the
* initial query's domain name.
*/
answer = reply_find_answer_rrset(&qstate->qinfo, super->return_msg->rep);
log_assert(answer);
answer->rk.dname = super->qinfo.qname;
answer->rk.dname_len = super->qinfo.qname_len;
}
/**
* This function is called when a sub-query finishes to inform the parent query.
*
* We issue two kinds of sub-queries: PTR and A.
*
* \param qstate State of the sub-query.
* \param id This module's instance ID.
* \param super State of the super-query.
*/
void
dns64_inform_super(struct module_qstate* qstate, int id,
struct module_qstate* super)
{
log_query_info(VERB_ALGO, "dns64: inform_super, sub is",
&qstate->qinfo);
log_query_info(VERB_ALGO, "super is", &super->qinfo);
/*
* Signal that the sub-query is finished, no matter whether we are
* successful or not. This lets the state machine terminate.
*/
super->minfo[id] = (void*)DNS64_SUBQUERY_FINISHED;
/* If there is no successful answer, we're done. */
if (qstate->return_rcode != LDNS_RCODE_NOERROR
|| !qstate->return_msg
|| !qstate->return_msg->rep
|| !reply_find_answer_rrset(&qstate->qinfo,
qstate->return_msg->rep))
return;
/* Generate a response suitable for the original query. */
if (qstate->qinfo.qtype == LDNS_RR_TYPE_A) {
dns64_adjust_a(id, super, qstate);
} else {
log_assert(qstate->qinfo.qtype == LDNS_RR_TYPE_PTR);
dns64_adjust_ptr(qstate, super);
}
/* Store the generated response in cache. */
if (!dns_cache_store(super->env, &super->qinfo, super->return_msg->rep,
0, 0, 0, NULL))
log_err("out of memory");
}
/**
* Clear module-specific data from query state. Since we do not allocate memory,
* it's just a matter of setting a pointer to NULL.
*
* \param qstate Query state.
* \param id This module's instance ID.
*/
void
dns64_clear(struct module_qstate* qstate, int id)
{
qstate->minfo[id] = NULL;
}
/**
* Returns the amount of global memory that this module uses, not including
* per-query data.
*
* \param env Module environment.
* \param id This module's instance ID.
*/
size_t
dns64_get_mem(struct module_env* env, int id)
{
struct dns64_env* dns64_env = (struct dns64_env*)env->modinfo[id];
if (!dns64_env)
return 0;
return sizeof(*dns64_env);
}
/**
* The dns64 function block.
*/
static struct module_func_block dns64_block = {
"dns64",
&dns64_init, &dns64_deinit, &dns64_operate, &dns64_inform_super,
&dns64_clear, &dns64_get_mem
};
/**
* Function for returning the above function block.
*/
struct module_func_block *
dns64_get_funcblock()
{
return &dns64_block;
}

71
external/unbound/dns64/dns64.h vendored Normal file
View File

@ -0,0 +1,71 @@
/*
* dns64/dns64.h - DNS64 module
*
* Copyright (c) 2009, Viagénie. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* This file contains a module that performs DNS64 query processing.
*/
#ifndef DNS64_DNS64_H
#define DNS64_DNS64_H
#include "util/module.h"
/**
* Get the dns64 function block.
* @return: function block with function pointers to dns64 methods.
*/
struct module_func_block *dns64_get_funcblock(void);
/** dns64 init */
int dns64_init(struct module_env* env, int id);
/** dns64 deinit */
void dns64_deinit(struct module_env* env, int id);
/** dns64 operate on a query */
void dns64_operate(struct module_qstate* qstate, enum module_ev event, int id,
struct outbound_entry* outbound);
void dns64_inform_super(struct module_qstate* qstate, int id,
struct module_qstate* super);
/** dns64 cleanup query state */
void dns64_clear(struct module_qstate* qstate, int id);
/** dns64 alloc size routine */
size_t dns64_get_mem(struct module_env* env, int id);
#endif /* DNS64_DNS64_H */

501
external/unbound/dnstap/dnstap.c vendored Normal file
View File

@ -0,0 +1,501 @@
/* dnstap support for Unbound */
/*
* Copyright (c) 2013-2014, Farsight Security, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "dnstap/dnstap_config.h"
#ifdef USE_DNSTAP
#include "config.h"
#include <sys/time.h>
#include "ldns/sbuffer.h"
#include "util/config_file.h"
#include "util/net_help.h"
#include "util/netevent.h"
#include "util/log.h"
#include <fstrm.h>
#include <protobuf-c/protobuf-c.h>
#include "dnstap/dnstap.h"
#include "dnstap/dnstap.pb-c.h"
#define DNSTAP_CONTENT_TYPE "protobuf:dnstap.Dnstap"
#define DNSTAP_INITIAL_BUF_SIZE 256
struct dt_msg {
void *buf;
size_t len_buf;
Dnstap__Dnstap d;
Dnstap__Message m;
};
static int
dt_pack(const Dnstap__Dnstap *d, void **buf, size_t *sz)
{
ProtobufCBufferSimple sbuf;
sbuf.base.append = protobuf_c_buffer_simple_append;
sbuf.len = 0;
sbuf.alloced = DNSTAP_INITIAL_BUF_SIZE;
sbuf.data = malloc(sbuf.alloced);
if (sbuf.data == NULL)
return 0;
sbuf.must_free_data = 1;
*sz = dnstap__dnstap__pack_to_buffer(d, (ProtobufCBuffer *) &sbuf);
if (sbuf.data == NULL)
return 0;
*buf = sbuf.data;
return 1;
}
static void
dt_send(const struct dt_env *env, void *buf, size_t len_buf)
{
fstrm_res res;
if (!buf)
return;
res = fstrm_io_submit(env->fio, env->fq, buf, len_buf,
fstrm_free_wrapper, NULL);
if (res != FSTRM_RES_SUCCESS)
free(buf);
}
static void
dt_msg_init(const struct dt_env *env,
struct dt_msg *dm,
Dnstap__Message__Type mtype)
{
memset(dm, 0, sizeof(*dm));
dm->d.base.descriptor = &dnstap__dnstap__descriptor;
dm->m.base.descriptor = &dnstap__message__descriptor;
dm->d.type = DNSTAP__DNSTAP__TYPE__MESSAGE;
dm->d.message = &dm->m;
dm->m.type = mtype;
if (env->identity != NULL) {
dm->d.identity.data = (uint8_t *) env->identity;
dm->d.identity.len = (size_t) env->len_identity;
dm->d.has_identity = 1;
}
if (env->version != NULL) {
dm->d.version.data = (uint8_t *) env->version;
dm->d.version.len = (size_t) env->len_version;
dm->d.has_version = 1;
}
}
struct dt_env *
dt_create(const char *socket_path, unsigned num_workers)
{
char *fio_err;
struct dt_env *env;
struct fstrm_io_options *fopt;
struct fstrm_unix_writer_options *fuwopt;
verbose(VERB_OPS, "opening dnstap socket %s", socket_path);
log_assert(socket_path != NULL);
log_assert(num_workers > 0);
env = (struct dt_env *) calloc(1, sizeof(struct dt_env));
if (!env)
return NULL;
fuwopt = fstrm_unix_writer_options_init();
fstrm_unix_writer_options_set_socket_path(fuwopt, socket_path);
fopt = fstrm_io_options_init();
fstrm_io_options_set_content_type(fopt,
DNSTAP_CONTENT_TYPE,
sizeof(DNSTAP_CONTENT_TYPE) - 1);
fstrm_io_options_set_num_queues(fopt, num_workers);
fstrm_io_options_set_writer(fopt, fstrm_unix_writer, fuwopt);
env->fio = fstrm_io_init(fopt, &fio_err);
if (env->fio == NULL) {
verbose(VERB_DETAIL, "dt_create: fstrm_io_init() failed: %s",
fio_err);
free(fio_err);
free(env);
env = NULL;
}
fstrm_io_options_destroy(&fopt);
fstrm_unix_writer_options_destroy(&fuwopt);
return env;
}
static void
dt_apply_identity(struct dt_env *env, struct config_file *cfg)
{
char buf[MAXHOSTNAMELEN+1];
if (!cfg->dnstap_send_identity)
return;
free(env->identity);
if (cfg->dnstap_identity == NULL || cfg->dnstap_identity[0] == 0) {
if (gethostname(buf, MAXHOSTNAMELEN) == 0) {
buf[MAXHOSTNAMELEN] = 0;
env->identity = strdup(buf);
} else {
fatal_exit("dt_apply_identity: gethostname() failed");
}
} else {
env->identity = strdup(cfg->dnstap_identity);
}
if (env->identity == NULL)
fatal_exit("dt_apply_identity: strdup() failed");
env->len_identity = (unsigned int)strlen(env->identity);
verbose(VERB_OPS, "dnstap identity field set to \"%s\"",
env->identity);
}
static void
dt_apply_version(struct dt_env *env, struct config_file *cfg)
{
if (!cfg->dnstap_send_version)
return;
free(env->version);
if (cfg->dnstap_version == NULL || cfg->dnstap_version[0] == 0)
env->version = strdup(PACKAGE_STRING);
else
env->version = strdup(cfg->dnstap_version);
if (env->version == NULL)
fatal_exit("dt_apply_version: strdup() failed");
env->len_version = (unsigned int)strlen(env->version);
verbose(VERB_OPS, "dnstap version field set to \"%s\"",
env->version);
}
void
dt_apply_cfg(struct dt_env *env, struct config_file *cfg)
{
if (!cfg->dnstap)
return;
dt_apply_identity(env, cfg);
dt_apply_version(env, cfg);
if ((env->log_resolver_query_messages = (unsigned int)
cfg->dnstap_log_resolver_query_messages))
{
verbose(VERB_OPS, "dnstap Message/RESOLVER_QUERY enabled");
}
if ((env->log_resolver_response_messages = (unsigned int)
cfg->dnstap_log_resolver_response_messages))
{
verbose(VERB_OPS, "dnstap Message/RESOLVER_RESPONSE enabled");
}
if ((env->log_client_query_messages = (unsigned int)
cfg->dnstap_log_client_query_messages))
{
verbose(VERB_OPS, "dnstap Message/CLIENT_QUERY enabled");
}
if ((env->log_client_response_messages = (unsigned int)
cfg->dnstap_log_client_response_messages))
{
verbose(VERB_OPS, "dnstap Message/CLIENT_RESPONSE enabled");
}
if ((env->log_forwarder_query_messages = (unsigned int)
cfg->dnstap_log_forwarder_query_messages))
{
verbose(VERB_OPS, "dnstap Message/FORWARDER_QUERY enabled");
}
if ((env->log_forwarder_response_messages = (unsigned int)
cfg->dnstap_log_forwarder_response_messages))
{
verbose(VERB_OPS, "dnstap Message/FORWARDER_RESPONSE enabled");
}
}
int
dt_init(struct dt_env *env)
{
env->fq = fstrm_io_get_queue(env->fio);
if (env->fq == NULL)
return 0;
return 1;
}
void
dt_delete(struct dt_env *env)
{
if (!env)
return;
verbose(VERB_OPS, "closing dnstap socket");
fstrm_io_destroy(&env->fio);
free(env->identity);
free(env->version);
free(env);
}
static void
dt_fill_timeval(const struct timeval *tv,
uint64_t *time_sec, protobuf_c_boolean *has_time_sec,
uint32_t *time_nsec, protobuf_c_boolean *has_time_nsec)
{
#ifndef S_SPLINT_S
*time_sec = tv->tv_sec;
*time_nsec = tv->tv_usec * 1000;
#endif
*has_time_sec = 1;
*has_time_nsec = 1;
}
static void
dt_fill_buffer(sldns_buffer *b, ProtobufCBinaryData *p, protobuf_c_boolean *has)
{
log_assert(b != NULL);
p->len = sldns_buffer_limit(b);
p->data = sldns_buffer_begin(b);
*has = 1;
}
static void
dt_msg_fill_net(struct dt_msg *dm,
struct sockaddr_storage *ss,
enum comm_point_type cptype,
ProtobufCBinaryData *addr, protobuf_c_boolean *has_addr,
uint32_t *port, protobuf_c_boolean *has_port)
{
log_assert(ss->ss_family == AF_INET6 || ss->ss_family == AF_INET);
if (ss->ss_family == AF_INET6) {
struct sockaddr_in6 *s = (struct sockaddr_in6 *) ss;
/* socket_family */
dm->m.socket_family = DNSTAP__SOCKET_FAMILY__INET6;
dm->m.has_socket_family = 1;
/* addr: query_address or response_address */
addr->data = s->sin6_addr.s6_addr;
addr->len = 16; /* IPv6 */
*has_addr = 1;
/* port: query_port or response_port */
*port = ntohs(s->sin6_port);
*has_port = 1;
} else if (ss->ss_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *) ss;
/* socket_family */
dm->m.socket_family = DNSTAP__SOCKET_FAMILY__INET;
dm->m.has_socket_family = 1;
/* addr: query_address or response_address */
addr->data = (uint8_t *) &s->sin_addr.s_addr;
addr->len = 4; /* IPv4 */
*has_addr = 1;
/* port: query_port or response_port */
*port = ntohs(s->sin_port);
*has_port = 1;
}
log_assert(cptype == comm_udp || cptype == comm_tcp);
if (cptype == comm_udp) {
/* socket_protocol */
dm->m.socket_protocol = DNSTAP__SOCKET_PROTOCOL__UDP;
dm->m.has_socket_protocol = 1;
} else if (cptype == comm_tcp) {
/* socket_protocol */
dm->m.socket_protocol = DNSTAP__SOCKET_PROTOCOL__TCP;
dm->m.has_socket_protocol = 1;
}
}
void
dt_msg_send_client_query(struct dt_env *env,
struct sockaddr_storage *qsock,
enum comm_point_type cptype,
sldns_buffer *qmsg)
{
struct dt_msg dm;
struct timeval qtime;
gettimeofday(&qtime, NULL);
/* type */
dt_msg_init(env, &dm, DNSTAP__MESSAGE__TYPE__CLIENT_QUERY);
/* query_time */
dt_fill_timeval(&qtime,
&dm.m.query_time_sec, &dm.m.has_query_time_sec,
&dm.m.query_time_nsec, &dm.m.has_query_time_nsec);
/* query_message */
dt_fill_buffer(qmsg, &dm.m.query_message, &dm.m.has_query_message);
/* socket_family, socket_protocol, query_address, query_port */
log_assert(cptype == comm_udp || cptype == comm_tcp);
dt_msg_fill_net(&dm, qsock, cptype,
&dm.m.query_address, &dm.m.has_query_address,
&dm.m.query_port, &dm.m.has_query_port);
if (dt_pack(&dm.d, &dm.buf, &dm.len_buf))
dt_send(env, dm.buf, dm.len_buf);
}
void
dt_msg_send_client_response(struct dt_env *env,
struct sockaddr_storage *qsock,
enum comm_point_type cptype,
sldns_buffer *rmsg)
{
struct dt_msg dm;
struct timeval rtime;
gettimeofday(&rtime, NULL);
/* type */
dt_msg_init(env, &dm, DNSTAP__MESSAGE__TYPE__CLIENT_RESPONSE);
/* response_time */
dt_fill_timeval(&rtime,
&dm.m.response_time_sec, &dm.m.has_response_time_sec,
&dm.m.response_time_nsec, &dm.m.has_response_time_nsec);
/* response_message */
dt_fill_buffer(rmsg, &dm.m.response_message, &dm.m.has_response_message);
/* socket_family, socket_protocol, query_address, query_port */
log_assert(cptype == comm_udp || cptype == comm_tcp);
dt_msg_fill_net(&dm, qsock, cptype,
&dm.m.query_address, &dm.m.has_query_address,
&dm.m.query_port, &dm.m.has_query_port);
if (dt_pack(&dm.d, &dm.buf, &dm.len_buf))
dt_send(env, dm.buf, dm.len_buf);
}
void
dt_msg_send_outside_query(struct dt_env *env,
struct sockaddr_storage *rsock,
enum comm_point_type cptype,
uint8_t *zone, size_t zone_len,
sldns_buffer *qmsg)
{
struct dt_msg dm;
struct timeval qtime;
uint16_t qflags;
gettimeofday(&qtime, NULL);
qflags = sldns_buffer_read_u16_at(qmsg, 2);
/* type */
if (qflags & BIT_RD) {
if (!env->log_forwarder_query_messages)
return;
dt_msg_init(env, &dm, DNSTAP__MESSAGE__TYPE__FORWARDER_QUERY);
} else {
if (!env->log_resolver_query_messages)
return;
dt_msg_init(env, &dm, DNSTAP__MESSAGE__TYPE__RESOLVER_QUERY);
}
/* query_zone */
dm.m.query_zone.data = zone;
dm.m.query_zone.len = zone_len;
dm.m.has_query_zone = 1;
/* query_time_sec, query_time_nsec */
dt_fill_timeval(&qtime,
&dm.m.query_time_sec, &dm.m.has_query_time_sec,
&dm.m.query_time_nsec, &dm.m.has_query_time_nsec);
/* query_message */
dt_fill_buffer(qmsg, &dm.m.query_message, &dm.m.has_query_message);
/* socket_family, socket_protocol, response_address, response_port */
log_assert(cptype == comm_udp || cptype == comm_tcp);
dt_msg_fill_net(&dm, rsock, cptype,
&dm.m.response_address, &dm.m.has_response_address,
&dm.m.response_port, &dm.m.has_response_port);
if (dt_pack(&dm.d, &dm.buf, &dm.len_buf))
dt_send(env, dm.buf, dm.len_buf);
}
void
dt_msg_send_outside_response(struct dt_env *env,
struct sockaddr_storage *rsock,
enum comm_point_type cptype,
uint8_t *zone, size_t zone_len,
uint8_t *qbuf, size_t qbuf_len,
const struct timeval *qtime,
const struct timeval *rtime,
sldns_buffer *rmsg)
{
struct dt_msg dm;
uint16_t qflags;
log_assert(qbuf_len >= sizeof(qflags));
memcpy(&qflags, qbuf, sizeof(qflags));
qflags = ntohs(qflags);
/* type */
if (qflags & BIT_RD) {
if (!env->log_forwarder_response_messages)
return;
dt_msg_init(env, &dm, DNSTAP__MESSAGE__TYPE__FORWARDER_RESPONSE);
} else {
if (!env->log_resolver_query_messages)
return;
dt_msg_init(env, &dm, DNSTAP__MESSAGE__TYPE__RESOLVER_RESPONSE);
}
/* query_zone */
dm.m.query_zone.data = zone;
dm.m.query_zone.len = zone_len;
dm.m.has_query_zone = 1;
/* query_time_sec, query_time_nsec */
dt_fill_timeval(qtime,
&dm.m.query_time_sec, &dm.m.has_query_time_sec,
&dm.m.query_time_nsec, &dm.m.has_query_time_nsec);
/* response_time_sec, response_time_nsec */
dt_fill_timeval(rtime,
&dm.m.response_time_sec, &dm.m.has_response_time_sec,
&dm.m.response_time_nsec, &dm.m.has_response_time_nsec);
/* response_message */
dt_fill_buffer(rmsg, &dm.m.response_message, &dm.m.has_response_message);
/* socket_family, socket_protocol, response_address, response_port */
log_assert(cptype == comm_udp || cptype == comm_tcp);
dt_msg_fill_net(&dm, rsock, cptype,
&dm.m.response_address, &dm.m.has_response_address,
&dm.m.response_port, &dm.m.has_response_port);
if (dt_pack(&dm.d, &dm.buf, &dm.len_buf))
dt_send(env, dm.buf, dm.len_buf);
}
#endif /* USE_DNSTAP */

188
external/unbound/dnstap/dnstap.h vendored Normal file
View File

@ -0,0 +1,188 @@
/* dnstap support for Unbound */
/*
* Copyright (c) 2013-2014, Farsight Security, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef UNBOUND_DNSTAP_H
#define UNBOUND_DNSTAP_H
#include "dnstap/dnstap_config.h"
#ifdef USE_DNSTAP
struct config_file;
struct fstrm_io;
struct fstrm_queue;
struct sldns_buffer;
struct dt_env {
/** dnstap I/O socket */
struct fstrm_io *fio;
/** dnstap I/O queue */
struct fstrm_queue *fq;
/** dnstap "identity" field, NULL if disabled */
char *identity;
/** dnstap "version" field, NULL if disabled */
char *version;
/** length of "identity" field */
unsigned len_identity;
/** length of "version" field */
unsigned len_version;
/** whether to log Message/RESOLVER_QUERY */
unsigned log_resolver_query_messages : 1;
/** whether to log Message/RESOLVER_RESPONSE */
unsigned log_resolver_response_messages : 1;
/** whether to log Message/CLIENT_QUERY */
unsigned log_client_query_messages : 1;
/** whether to log Message/CLIENT_RESPONSE */
unsigned log_client_response_messages : 1;
/** whether to log Message/FORWARDER_QUERY */
unsigned log_forwarder_query_messages : 1;
/** whether to log Message/FORWARDER_RESPONSE */
unsigned log_forwarder_response_messages : 1;
};
/**
* Create dnstap environment object. Afterwards, call dt_apply_cfg() to fill in
* the config variables and dt_init() to fill in the per-worker state. Each
* worker needs a copy of this object but with its own I/O queue (the fq field
* of the structure) to ensure lock-free access to its own per-worker circular
* queue. Duplicate the environment object if more than one worker needs to
* share access to the dnstap I/O socket.
* @param socket_path: path to dnstap logging socket, must be non-NULL.
* @param num_workers: number of worker threads, must be > 0.
* @return dt_env object, NULL on failure.
*/
struct dt_env *
dt_create(const char *socket_path, unsigned num_workers);
/**
* Apply config settings.
* @param env: dnstap environment object.
* @param cfg: new config settings.
*/
void
dt_apply_cfg(struct dt_env *env, struct config_file *cfg);
/**
* Initialize per-worker state in dnstap environment object.
* @param env: dnstap environment object to initialize, created with dt_create().
* @return: true on success, false on failure.
*/
int
dt_init(struct dt_env *env);
/**
* Delete dnstap environment object. Closes dnstap I/O socket and deletes all
* per-worker I/O queues.
*/
void
dt_delete(struct dt_env *env);
/**
* Create and send a new dnstap "Message" event of type CLIENT_QUERY.
* @param env: dnstap environment object.
* @param qsock: address/port of client.
* @param cptype: comm_udp or comm_tcp.
* @param qmsg: query message.
*/
void
dt_msg_send_client_query(struct dt_env *env,
struct sockaddr_storage *qsock,
enum comm_point_type cptype,
struct sldns_buffer *qmsg);
/**
* Create and send a new dnstap "Message" event of type CLIENT_RESPONSE.
* @param env: dnstap environment object.
* @param qsock: address/port of client.
* @param cptype: comm_udp or comm_tcp.
* @param rmsg: response message.
*/
void
dt_msg_send_client_response(struct dt_env *env,
struct sockaddr_storage *qsock,
enum comm_point_type cptype,
struct sldns_buffer *rmsg);
/**
* Create and send a new dnstap "Message" event of type RESOLVER_QUERY or
* FORWARDER_QUERY. The type used is dependent on the value of the RD bit
* in the query header.
* @param env: dnstap environment object.
* @param rsock: address/port of server the query is being sent to.
* @param cptype: comm_udp or comm_tcp.
* @param zone: query zone.
* @param zone_len: length of zone.
* @param qmsg: query message.
*/
void
dt_msg_send_outside_query(struct dt_env *env,
struct sockaddr_storage *rsock,
enum comm_point_type cptype,
uint8_t *zone, size_t zone_len,
struct sldns_buffer *qmsg);
/**
* Create and send a new dnstap "Message" event of type RESOLVER_RESPONSE or
* FORWARDER_RESPONSE. The type used is dependent on the value of the RD bit
* in the query header.
* @param env: dnstap environment object.
* @param rsock: address/port of server the response was received from.
* @param cptype: comm_udp or comm_tcp.
* @param zone: query zone.
* @param zone_len: length of zone.
* @param qbuf: outside_network's qbuf key.
* @param qbuf_len: length of outside_network's qbuf key.
* @param qtime: time query message was sent.
* @param rtime: time response message was sent.
* @param rmsg: response message.
*/
void
dt_msg_send_outside_response(struct dt_env *env,
struct sockaddr_storage *rsock,
enum comm_point_type cptype,
uint8_t *zone, size_t zone_len,
uint8_t *qbuf, size_t qbuf_len,
const struct timeval *qtime,
const struct timeval *rtime,
struct sldns_buffer *rmsg);
#endif /* USE_DNSTAP */
#endif /* UNBOUND_DNSTAP_H */

54
external/unbound/dnstap/dnstap.m4 vendored Normal file
View File

@ -0,0 +1,54 @@
# dnstap.m4
# dt_DNSTAP(default_dnstap_socket_path, [action-if-true], [action-if-false])
# --------------------------------------------------------------------------
# Check for required dnstap libraries and add dnstap configure args.
AC_DEFUN([dt_DNSTAP],
[
AC_ARG_ENABLE([dnstap],
AS_HELP_STRING([--enable-dnstap],
[Enable dnstap support (requires fstrm, protobuf-c)]),
[opt_dnstap=$enableval], [opt_dnstap=no])
AC_ARG_WITH([dnstap-socket-path],
AS_HELP_STRING([--with-dnstap-socket-path=pathname],
[set default dnstap socket path]),
[opt_dnstap_socket_path=$withval], [opt_dnstap_socket_path="$1"])
if test "x$opt_dnstap" != "xno"; then
AC_PATH_PROG([PROTOC_C], [protoc-c])
if test -z "$PROTOC_C"; then
AC_MSG_ERROR([The protoc-c program was not found. Please install protobuf-c!])
fi
AC_ARG_WITH([protobuf-c], AC_HELP_STRING([--with-protobuf-c=path],
[Path where protobuf-c is installed, for dnstap]), [
# workaround for protobuf includes at old dir before protobuf-1.0.0
if test -f $withval/include/google/protobuf-c/protobuf-c.h; then
CFLAGS="$CFLAGS -I$withval/include/google"
else
CFLAGS="$CFLAGS -I$withval/include"
fi
LDFLAGS="$LDFLAGS -L$withval/lib"
], [
# workaround for protobuf includes at old dir before protobuf-1.0.0
if test -f /usr/include/google/protobuf-c/protobuf-c.h; then
CFLAGS="$CFLAGS -I/usr/include/google"
else
if test -f /usr/local/include/google/protobuf-c/protobuf-c.h; then
CFLAGS="$CFLAGS -I/usr/local/include/google"
LDFLAGS="$LDFLAGS -L/usr/local/lib"
fi
fi
])
AC_ARG_WITH([libfstrm], AC_HELP_STRING([--with-libfstrm=path],
[Path where libfstrm in installed, for dnstap]), [
CFLAGS="$CFLAGS -I$withval/include"
LDFLAGS="$LDFLAGS -L$withval/lib"
])
AC_SEARCH_LIBS([fstrm_io_init], [fstrm])
AC_SEARCH_LIBS([protobuf_c_message_pack], [protobuf-c])
$2
else
$3
fi
])

518
external/unbound/dnstap/dnstap.pb-c.c vendored Normal file
View File

@ -0,0 +1,518 @@
/* Generated by the protocol buffer compiler. DO NOT EDIT! */
/* Do not generate deprecated warnings for self */
#ifndef PROTOBUF_C_NO_DEPRECATED
#define PROTOBUF_C_NO_DEPRECATED
#endif
#include "dnstap/dnstap.pb-c.h"
void dnstap__dnstap__init
(Dnstap__Dnstap *message)
{
static Dnstap__Dnstap init_value = DNSTAP__DNSTAP__INIT;
*message = init_value;
}
size_t dnstap__dnstap__get_packed_size
(const Dnstap__Dnstap *message)
{
PROTOBUF_C_ASSERT (message->base.descriptor == &dnstap__dnstap__descriptor);
return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message));
}
size_t dnstap__dnstap__pack
(const Dnstap__Dnstap *message,
uint8_t *out)
{
PROTOBUF_C_ASSERT (message->base.descriptor == &dnstap__dnstap__descriptor);
return protobuf_c_message_pack ((const ProtobufCMessage*)message, out);
}
size_t dnstap__dnstap__pack_to_buffer
(const Dnstap__Dnstap *message,
ProtobufCBuffer *buffer)
{
PROTOBUF_C_ASSERT (message->base.descriptor == &dnstap__dnstap__descriptor);
return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer);
}
Dnstap__Dnstap *
dnstap__dnstap__unpack
(ProtobufCAllocator *allocator,
size_t len,
const uint8_t *data)
{
return (Dnstap__Dnstap *)
protobuf_c_message_unpack (&dnstap__dnstap__descriptor,
allocator, len, data);
}
void dnstap__dnstap__free_unpacked
(Dnstap__Dnstap *message,
ProtobufCAllocator *allocator)
{
PROTOBUF_C_ASSERT (message->base.descriptor == &dnstap__dnstap__descriptor);
protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator);
}
void dnstap__message__init
(Dnstap__Message *message)
{
static Dnstap__Message init_value = DNSTAP__MESSAGE__INIT;
*message = init_value;
}
size_t dnstap__message__get_packed_size
(const Dnstap__Message *message)
{
PROTOBUF_C_ASSERT (message->base.descriptor == &dnstap__message__descriptor);
return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message));
}
size_t dnstap__message__pack
(const Dnstap__Message *message,
uint8_t *out)
{
PROTOBUF_C_ASSERT (message->base.descriptor == &dnstap__message__descriptor);
return protobuf_c_message_pack ((const ProtobufCMessage*)message, out);
}
size_t dnstap__message__pack_to_buffer
(const Dnstap__Message *message,
ProtobufCBuffer *buffer)
{
PROTOBUF_C_ASSERT (message->base.descriptor == &dnstap__message__descriptor);
return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer);
}
Dnstap__Message *
dnstap__message__unpack
(ProtobufCAllocator *allocator,
size_t len,
const uint8_t *data)
{
return (Dnstap__Message *)
protobuf_c_message_unpack (&dnstap__message__descriptor,
allocator, len, data);
}
void dnstap__message__free_unpacked
(Dnstap__Message *message,
ProtobufCAllocator *allocator)
{
PROTOBUF_C_ASSERT (message->base.descriptor == &dnstap__message__descriptor);
protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator);
}
const ProtobufCEnumValue dnstap__dnstap__type__enum_values_by_number[1] =
{
{ "MESSAGE", "DNSTAP__DNSTAP__TYPE__MESSAGE", 1 },
};
static const ProtobufCIntRange dnstap__dnstap__type__value_ranges[] = {
{1, 0},{0, 1}
};
const ProtobufCEnumValueIndex dnstap__dnstap__type__enum_values_by_name[1] =
{
{ "MESSAGE", 0 },
};
const ProtobufCEnumDescriptor dnstap__dnstap__type__descriptor =
{
PROTOBUF_C_ENUM_DESCRIPTOR_MAGIC,
"dnstap.Dnstap.Type",
"Type",
"Dnstap__Dnstap__Type",
"dnstap",
1,
dnstap__dnstap__type__enum_values_by_number,
1,
dnstap__dnstap__type__enum_values_by_name,
1,
dnstap__dnstap__type__value_ranges,
NULL,NULL,NULL,NULL /* reserved[1234] */
};
static const ProtobufCFieldDescriptor dnstap__dnstap__field_descriptors[5] =
{
{
"identity",
1,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_BYTES,
PROTOBUF_C_OFFSETOF(Dnstap__Dnstap, has_identity),
PROTOBUF_C_OFFSETOF(Dnstap__Dnstap, identity),
NULL,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"version",
2,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_BYTES,
PROTOBUF_C_OFFSETOF(Dnstap__Dnstap, has_version),
PROTOBUF_C_OFFSETOF(Dnstap__Dnstap, version),
NULL,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"extra",
3,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_BYTES,
PROTOBUF_C_OFFSETOF(Dnstap__Dnstap, has_extra),
PROTOBUF_C_OFFSETOF(Dnstap__Dnstap, extra),
NULL,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"message",
14,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_MESSAGE,
0, /* quantifier_offset */
PROTOBUF_C_OFFSETOF(Dnstap__Dnstap, message),
&dnstap__message__descriptor,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"type",
15,
PROTOBUF_C_LABEL_REQUIRED,
PROTOBUF_C_TYPE_ENUM,
0, /* quantifier_offset */
PROTOBUF_C_OFFSETOF(Dnstap__Dnstap, type),
&dnstap__dnstap__type__descriptor,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
};
static const unsigned dnstap__dnstap__field_indices_by_name[] = {
2, /* field[2] = extra */
0, /* field[0] = identity */
3, /* field[3] = message */
4, /* field[4] = type */
1, /* field[1] = version */
};
static const ProtobufCIntRange dnstap__dnstap__number_ranges[2 + 1] =
{
{ 1, 0 },
{ 14, 3 },
{ 0, 5 }
};
const ProtobufCMessageDescriptor dnstap__dnstap__descriptor =
{
PROTOBUF_C_MESSAGE_DESCRIPTOR_MAGIC,
"dnstap.Dnstap",
"Dnstap",
"Dnstap__Dnstap",
"dnstap",
sizeof(Dnstap__Dnstap),
5,
dnstap__dnstap__field_descriptors,
dnstap__dnstap__field_indices_by_name,
2, dnstap__dnstap__number_ranges,
(ProtobufCMessageInit) dnstap__dnstap__init,
NULL,NULL,NULL /* reserved[123] */
};
const ProtobufCEnumValue dnstap__message__type__enum_values_by_number[10] =
{
{ "AUTH_QUERY", "DNSTAP__MESSAGE__TYPE__AUTH_QUERY", 1 },
{ "AUTH_RESPONSE", "DNSTAP__MESSAGE__TYPE__AUTH_RESPONSE", 2 },
{ "RESOLVER_QUERY", "DNSTAP__MESSAGE__TYPE__RESOLVER_QUERY", 3 },
{ "RESOLVER_RESPONSE", "DNSTAP__MESSAGE__TYPE__RESOLVER_RESPONSE", 4 },
{ "CLIENT_QUERY", "DNSTAP__MESSAGE__TYPE__CLIENT_QUERY", 5 },
{ "CLIENT_RESPONSE", "DNSTAP__MESSAGE__TYPE__CLIENT_RESPONSE", 6 },
{ "FORWARDER_QUERY", "DNSTAP__MESSAGE__TYPE__FORWARDER_QUERY", 7 },
{ "FORWARDER_RESPONSE", "DNSTAP__MESSAGE__TYPE__FORWARDER_RESPONSE", 8 },
{ "STUB_QUERY", "DNSTAP__MESSAGE__TYPE__STUB_QUERY", 9 },
{ "STUB_RESPONSE", "DNSTAP__MESSAGE__TYPE__STUB_RESPONSE", 10 },
};
static const ProtobufCIntRange dnstap__message__type__value_ranges[] = {
{1, 0},{0, 10}
};
const ProtobufCEnumValueIndex dnstap__message__type__enum_values_by_name[10] =
{
{ "AUTH_QUERY", 0 },
{ "AUTH_RESPONSE", 1 },
{ "CLIENT_QUERY", 4 },
{ "CLIENT_RESPONSE", 5 },
{ "FORWARDER_QUERY", 6 },
{ "FORWARDER_RESPONSE", 7 },
{ "RESOLVER_QUERY", 2 },
{ "RESOLVER_RESPONSE", 3 },
{ "STUB_QUERY", 8 },
{ "STUB_RESPONSE", 9 },
};
const ProtobufCEnumDescriptor dnstap__message__type__descriptor =
{
PROTOBUF_C_ENUM_DESCRIPTOR_MAGIC,
"dnstap.Message.Type",
"Type",
"Dnstap__Message__Type",
"dnstap",
10,
dnstap__message__type__enum_values_by_number,
10,
dnstap__message__type__enum_values_by_name,
1,
dnstap__message__type__value_ranges,
NULL,NULL,NULL,NULL /* reserved[1234] */
};
static const ProtobufCFieldDescriptor dnstap__message__field_descriptors[14] =
{
{
"type",
1,
PROTOBUF_C_LABEL_REQUIRED,
PROTOBUF_C_TYPE_ENUM,
0, /* quantifier_offset */
PROTOBUF_C_OFFSETOF(Dnstap__Message, type),
&dnstap__message__type__descriptor,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"socket_family",
2,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_ENUM,
PROTOBUF_C_OFFSETOF(Dnstap__Message, has_socket_family),
PROTOBUF_C_OFFSETOF(Dnstap__Message, socket_family),
&dnstap__socket_family__descriptor,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"socket_protocol",
3,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_ENUM,
PROTOBUF_C_OFFSETOF(Dnstap__Message, has_socket_protocol),
PROTOBUF_C_OFFSETOF(Dnstap__Message, socket_protocol),
&dnstap__socket_protocol__descriptor,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"query_address",
4,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_BYTES,
PROTOBUF_C_OFFSETOF(Dnstap__Message, has_query_address),
PROTOBUF_C_OFFSETOF(Dnstap__Message, query_address),
NULL,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"response_address",
5,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_BYTES,
PROTOBUF_C_OFFSETOF(Dnstap__Message, has_response_address),
PROTOBUF_C_OFFSETOF(Dnstap__Message, response_address),
NULL,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"query_port",
6,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_UINT32,
PROTOBUF_C_OFFSETOF(Dnstap__Message, has_query_port),
PROTOBUF_C_OFFSETOF(Dnstap__Message, query_port),
NULL,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"response_port",
7,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_UINT32,
PROTOBUF_C_OFFSETOF(Dnstap__Message, has_response_port),
PROTOBUF_C_OFFSETOF(Dnstap__Message, response_port),
NULL,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"query_time_sec",
8,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_UINT64,
PROTOBUF_C_OFFSETOF(Dnstap__Message, has_query_time_sec),
PROTOBUF_C_OFFSETOF(Dnstap__Message, query_time_sec),
NULL,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"query_time_nsec",
9,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_FIXED32,
PROTOBUF_C_OFFSETOF(Dnstap__Message, has_query_time_nsec),
PROTOBUF_C_OFFSETOF(Dnstap__Message, query_time_nsec),
NULL,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"query_message",
10,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_BYTES,
PROTOBUF_C_OFFSETOF(Dnstap__Message, has_query_message),
PROTOBUF_C_OFFSETOF(Dnstap__Message, query_message),
NULL,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"query_zone",
11,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_BYTES,
PROTOBUF_C_OFFSETOF(Dnstap__Message, has_query_zone),
PROTOBUF_C_OFFSETOF(Dnstap__Message, query_zone),
NULL,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"response_time_sec",
12,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_UINT64,
PROTOBUF_C_OFFSETOF(Dnstap__Message, has_response_time_sec),
PROTOBUF_C_OFFSETOF(Dnstap__Message, response_time_sec),
NULL,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"response_time_nsec",
13,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_FIXED32,
PROTOBUF_C_OFFSETOF(Dnstap__Message, has_response_time_nsec),
PROTOBUF_C_OFFSETOF(Dnstap__Message, response_time_nsec),
NULL,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
{
"response_message",
14,
PROTOBUF_C_LABEL_OPTIONAL,
PROTOBUF_C_TYPE_BYTES,
PROTOBUF_C_OFFSETOF(Dnstap__Message, has_response_message),
PROTOBUF_C_OFFSETOF(Dnstap__Message, response_message),
NULL,
NULL,
0, /* packed */
0,NULL,NULL /* reserved1,reserved2, etc */
},
};
static const unsigned dnstap__message__field_indices_by_name[] = {
3, /* field[3] = query_address */
9, /* field[9] = query_message */
5, /* field[5] = query_port */
8, /* field[8] = query_time_nsec */
7, /* field[7] = query_time_sec */
10, /* field[10] = query_zone */
4, /* field[4] = response_address */
13, /* field[13] = response_message */
6, /* field[6] = response_port */
12, /* field[12] = response_time_nsec */
11, /* field[11] = response_time_sec */
1, /* field[1] = socket_family */
2, /* field[2] = socket_protocol */
0, /* field[0] = type */
};
static const ProtobufCIntRange dnstap__message__number_ranges[1 + 1] =
{
{ 1, 0 },
{ 0, 14 }
};
const ProtobufCMessageDescriptor dnstap__message__descriptor =
{
PROTOBUF_C_MESSAGE_DESCRIPTOR_MAGIC,
"dnstap.Message",
"Message",
"Dnstap__Message",
"dnstap",
sizeof(Dnstap__Message),
14,
dnstap__message__field_descriptors,
dnstap__message__field_indices_by_name,
1, dnstap__message__number_ranges,
(ProtobufCMessageInit) dnstap__message__init,
NULL,NULL,NULL /* reserved[123] */
};
const ProtobufCEnumValue dnstap__socket_family__enum_values_by_number[2] =
{
{ "INET", "DNSTAP__SOCKET_FAMILY__INET", 1 },
{ "INET6", "DNSTAP__SOCKET_FAMILY__INET6", 2 },
};
static const ProtobufCIntRange dnstap__socket_family__value_ranges[] = {
{1, 0},{0, 2}
};
const ProtobufCEnumValueIndex dnstap__socket_family__enum_values_by_name[2] =
{
{ "INET", 0 },
{ "INET6", 1 },
};
const ProtobufCEnumDescriptor dnstap__socket_family__descriptor =
{
PROTOBUF_C_ENUM_DESCRIPTOR_MAGIC,
"dnstap.SocketFamily",
"SocketFamily",
"Dnstap__SocketFamily",
"dnstap",
2,
dnstap__socket_family__enum_values_by_number,
2,
dnstap__socket_family__enum_values_by_name,
1,
dnstap__socket_family__value_ranges,
NULL,NULL,NULL,NULL /* reserved[1234] */
};
const ProtobufCEnumValue dnstap__socket_protocol__enum_values_by_number[2] =
{
{ "UDP", "DNSTAP__SOCKET_PROTOCOL__UDP", 1 },
{ "TCP", "DNSTAP__SOCKET_PROTOCOL__TCP", 2 },
};
static const ProtobufCIntRange dnstap__socket_protocol__value_ranges[] = {
{1, 0},{0, 2}
};
const ProtobufCEnumValueIndex dnstap__socket_protocol__enum_values_by_name[2] =
{
{ "TCP", 1 },
{ "UDP", 0 },
};
const ProtobufCEnumDescriptor dnstap__socket_protocol__descriptor =
{
PROTOBUF_C_ENUM_DESCRIPTOR_MAGIC,
"dnstap.SocketProtocol",
"SocketProtocol",
"Dnstap__SocketProtocol",
"dnstap",
2,
dnstap__socket_protocol__enum_values_by_number,
2,
dnstap__socket_protocol__enum_values_by_name,
1,
dnstap__socket_protocol__value_ranges,
NULL,NULL,NULL,NULL /* reserved[1234] */
};

158
external/unbound/dnstap/dnstap.pb-c.h vendored Normal file
View File

@ -0,0 +1,158 @@
/* Generated by the protocol buffer compiler. DO NOT EDIT! */
#ifndef PROTOBUF_C_dnstap_2fdnstap_2eproto__INCLUDED
#define PROTOBUF_C_dnstap_2fdnstap_2eproto__INCLUDED
#include <google/protobuf-c/protobuf-c.h>
PROTOBUF_C_BEGIN_DECLS
typedef struct _Dnstap__Dnstap Dnstap__Dnstap;
typedef struct _Dnstap__Message Dnstap__Message;
/* --- enums --- */
typedef enum _Dnstap__Dnstap__Type {
DNSTAP__DNSTAP__TYPE__MESSAGE = 1
} Dnstap__Dnstap__Type;
typedef enum _Dnstap__Message__Type {
DNSTAP__MESSAGE__TYPE__AUTH_QUERY = 1,
DNSTAP__MESSAGE__TYPE__AUTH_RESPONSE = 2,
DNSTAP__MESSAGE__TYPE__RESOLVER_QUERY = 3,
DNSTAP__MESSAGE__TYPE__RESOLVER_RESPONSE = 4,
DNSTAP__MESSAGE__TYPE__CLIENT_QUERY = 5,
DNSTAP__MESSAGE__TYPE__CLIENT_RESPONSE = 6,
DNSTAP__MESSAGE__TYPE__FORWARDER_QUERY = 7,
DNSTAP__MESSAGE__TYPE__FORWARDER_RESPONSE = 8,
DNSTAP__MESSAGE__TYPE__STUB_QUERY = 9,
DNSTAP__MESSAGE__TYPE__STUB_RESPONSE = 10
} Dnstap__Message__Type;
typedef enum _Dnstap__SocketFamily {
DNSTAP__SOCKET_FAMILY__INET = 1,
DNSTAP__SOCKET_FAMILY__INET6 = 2
} Dnstap__SocketFamily;
typedef enum _Dnstap__SocketProtocol {
DNSTAP__SOCKET_PROTOCOL__UDP = 1,
DNSTAP__SOCKET_PROTOCOL__TCP = 2
} Dnstap__SocketProtocol;
/* --- messages --- */
struct _Dnstap__Dnstap
{
ProtobufCMessage base;
protobuf_c_boolean has_identity;
ProtobufCBinaryData identity;
protobuf_c_boolean has_version;
ProtobufCBinaryData version;
protobuf_c_boolean has_extra;
ProtobufCBinaryData extra;
Dnstap__Dnstap__Type type;
Dnstap__Message *message;
};
#define DNSTAP__DNSTAP__INIT \
{ PROTOBUF_C_MESSAGE_INIT (&dnstap__dnstap__descriptor) \
, 0,{0,NULL}, 0,{0,NULL}, 0,{0,NULL}, 0, NULL }
struct _Dnstap__Message
{
ProtobufCMessage base;
Dnstap__Message__Type type;
protobuf_c_boolean has_socket_family;
Dnstap__SocketFamily socket_family;
protobuf_c_boolean has_socket_protocol;
Dnstap__SocketProtocol socket_protocol;
protobuf_c_boolean has_query_address;
ProtobufCBinaryData query_address;
protobuf_c_boolean has_response_address;
ProtobufCBinaryData response_address;
protobuf_c_boolean has_query_port;
uint32_t query_port;
protobuf_c_boolean has_response_port;
uint32_t response_port;
protobuf_c_boolean has_query_time_sec;
uint64_t query_time_sec;
protobuf_c_boolean has_query_time_nsec;
uint32_t query_time_nsec;
protobuf_c_boolean has_query_message;
ProtobufCBinaryData query_message;
protobuf_c_boolean has_query_zone;
ProtobufCBinaryData query_zone;
protobuf_c_boolean has_response_time_sec;
uint64_t response_time_sec;
protobuf_c_boolean has_response_time_nsec;
uint32_t response_time_nsec;
protobuf_c_boolean has_response_message;
ProtobufCBinaryData response_message;
};
#define DNSTAP__MESSAGE__INIT \
{ PROTOBUF_C_MESSAGE_INIT (&dnstap__message__descriptor) \
, 0, 0,0, 0,0, 0,{0,NULL}, 0,{0,NULL}, 0,0, 0,0, 0,0, 0,0, 0,{0,NULL}, 0,{0,NULL}, 0,0, 0,0, 0,{0,NULL} }
/* Dnstap__Dnstap methods */
void dnstap__dnstap__init
(Dnstap__Dnstap *message);
size_t dnstap__dnstap__get_packed_size
(const Dnstap__Dnstap *message);
size_t dnstap__dnstap__pack
(const Dnstap__Dnstap *message,
uint8_t *out);
size_t dnstap__dnstap__pack_to_buffer
(const Dnstap__Dnstap *message,
ProtobufCBuffer *buffer);
Dnstap__Dnstap *
dnstap__dnstap__unpack
(ProtobufCAllocator *allocator,
size_t len,
const uint8_t *data);
void dnstap__dnstap__free_unpacked
(Dnstap__Dnstap *message,
ProtobufCAllocator *allocator);
/* Dnstap__Message methods */
void dnstap__message__init
(Dnstap__Message *message);
size_t dnstap__message__get_packed_size
(const Dnstap__Message *message);
size_t dnstap__message__pack
(const Dnstap__Message *message,
uint8_t *out);
size_t dnstap__message__pack_to_buffer
(const Dnstap__Message *message,
ProtobufCBuffer *buffer);
Dnstap__Message *
dnstap__message__unpack
(ProtobufCAllocator *allocator,
size_t len,
const uint8_t *data);
void dnstap__message__free_unpacked
(Dnstap__Message *message,
ProtobufCAllocator *allocator);
/* --- per-message closures --- */
typedef void (*Dnstap__Dnstap_Closure)
(const Dnstap__Dnstap *message,
void *closure_data);
typedef void (*Dnstap__Message_Closure)
(const Dnstap__Message *message,
void *closure_data);
/* --- services --- */
/* --- descriptors --- */
extern const ProtobufCEnumDescriptor dnstap__socket_family__descriptor;
extern const ProtobufCEnumDescriptor dnstap__socket_protocol__descriptor;
extern const ProtobufCMessageDescriptor dnstap__dnstap__descriptor;
extern const ProtobufCEnumDescriptor dnstap__dnstap__type__descriptor;
extern const ProtobufCMessageDescriptor dnstap__message__descriptor;
extern const ProtobufCEnumDescriptor dnstap__message__type__descriptor;
PROTOBUF_C_END_DECLS
#endif /* PROTOBUF_dnstap_2fdnstap_2eproto__INCLUDED */

262
external/unbound/dnstap/dnstap.proto vendored Normal file
View File

@ -0,0 +1,262 @@
// dnstap: flexible, structured event replication format for DNS software
//
// This file contains the protobuf schemas for the "dnstap" structured event
// replication format for DNS software.
// Written in 2013-2014 by Farsight Security, Inc.
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this file to the public
// domain worldwide. This file is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along
// with this file. If not, see:
//
// <http://creativecommons.org/publicdomain/zero/1.0/>.
package dnstap;
// "Dnstap": this is the top-level dnstap type, which is a "union" type that
// contains other kinds of dnstap payloads, although currently only one type
// of dnstap payload is defined.
// See: https://developers.google.com/protocol-buffers/docs/techniques#union
message Dnstap {
// DNS server identity.
// If enabled, this is the identity string of the DNS server which generated
// this message. Typically this would be the same string as returned by an
// "NSID" (RFC 5001) query.
optional bytes identity = 1;
// DNS server version.
// If enabled, this is the version string of the DNS server which generated
// this message. Typically this would be the same string as returned by a
// "version.bind" query.
optional bytes version = 2;
// Extra data for this payload.
// This field can be used for adding an arbitrary byte-string annotation to
// the payload. No encoding or interpretation is applied or enforced.
optional bytes extra = 3;
// Identifies which field below is filled in.
enum Type {
MESSAGE = 1;
}
required Type type = 15;
// One of the following will be filled in.
optional Message message = 14;
}
// SocketFamily: the network protocol family of a socket. This specifies how
// to interpret "network address" fields.
enum SocketFamily {
INET = 1; // IPv4 (RFC 791)
INET6 = 2; // IPv6 (RFC 2460)
}
// SocketProtocol: the transport protocol of a socket. This specifies how to
// interpret "transport port" fields.
enum SocketProtocol {
UDP = 1; // User Datagram Protocol (RFC 768)
TCP = 2; // Transmission Control Protocol (RFC 793)
}
// Message: a wire-format (RFC 1035 section 4) DNS message and associated
// metadata. Applications generating "Message" payloads should follow
// certain requirements based on the MessageType, see below.
message Message {
// There are eight types of "Message" defined that correspond to the
// four arrows in the following diagram, slightly modified from RFC 1035
// section 2:
// +---------+ +----------+ +--------+
// | | query | | query | |
// | Stub |-SQ--------CQ->| Recursive|-RQ----AQ->| Auth. |
// | Resolver| | Server | | Name |
// | |<-SR--------CR-| |<-RR----AR-| Server |
// +---------+ response | | response | |
// +----------+ +--------+
// Each arrow has two Type values each, one for each "end" of each arrow,
// because these are considered to be distinct events. Each end of each
// arrow on the diagram above has been marked with a two-letter Type
// mnemonic. Clockwise from upper left, these mnemonic values are:
//
// SQ: STUB_QUERY
// CQ: CLIENT_QUERY
// RQ: RESOLVER_QUERY
// AQ: AUTH_QUERY
// AR: AUTH_RESPONSE
// RR: RESOLVER_RESPONSE
// CR: CLIENT_RESPONSE
// SR: STUB_RESPONSE
// Two additional types of "Message" have been defined for the
// "forwarding" case where an upstream DNS server is responsible for
// further recursion. These are not shown on the diagram above, but have
// the following mnemonic values:
// FQ: FORWARDER_QUERY
// FR: FORWARDER_RESPONSE
// The "Message" Type values are defined below.
enum Type {
// AUTH_QUERY is a DNS query message received from a resolver by an
// authoritative name server, from the perspective of the authorative
// name server.
AUTH_QUERY = 1;
// AUTH_RESPONSE is a DNS response message sent from an authoritative
// name server to a resolver, from the perspective of the authoritative
// name server.
AUTH_RESPONSE = 2;
// RESOLVER_QUERY is a DNS query message sent from a resolver to an
// authoritative name server, from the perspective of the resolver.
// Resolvers typically clear the RD (recursion desired) bit when
// sending queries.
RESOLVER_QUERY = 3;
// RESOLVER_RESPONSE is a DNS response message received from an
// authoritative name server by a resolver, from the perspective of
// the resolver.
RESOLVER_RESPONSE = 4;
// CLIENT_QUERY is a DNS query message sent from a client to a DNS
// server which is expected to perform further recursion, from the
// perspective of the DNS server. The client may be a stub resolver or
// forwarder or some other type of software which typically sets the RD
// (recursion desired) bit when querying the DNS server. The DNS server
// may be a simple forwarding proxy or it may be a full recursive
// resolver.
CLIENT_QUERY = 5;
// CLIENT_RESPONSE is a DNS response message sent from a DNS server to
// a client, from the perspective of the DNS server. The DNS server
// typically sets the RA (recursion available) bit when responding.
CLIENT_RESPONSE = 6;
// FORWARDER_QUERY is a DNS query message sent from a downstream DNS
// server to an upstream DNS server which is expected to perform
// further recursion, from the perspective of the downstream DNS
// server.
FORWARDER_QUERY = 7;
// FORWARDER_RESPONSE is a DNS response message sent from an upstream
// DNS server performing recursion to a downstream DNS server, from the
// perspective of the downstream DNS server.
FORWARDER_RESPONSE = 8;
// STUB_QUERY is a DNS query message sent from a stub resolver to a DNS
// server, from the perspective of the stub resolver.
STUB_QUERY = 9;
// STUB_RESPONSE is a DNS response message sent from a DNS server to a
// stub resolver, from the perspective of the stub resolver.
STUB_RESPONSE = 10;
}
// One of the Type values described above.
required Type type = 1;
// One of the SocketFamily values described above.
optional SocketFamily socket_family = 2;
// One of the SocketProtocol values described above.
optional SocketProtocol socket_protocol = 3;
// The network address of the message initiator.
// For SocketFamily INET, this field is 4 octets (IPv4 address).
// For SocketFamily INET6, this field is 16 octets (IPv6 address).
optional bytes query_address = 4;
// The network address of the message responder.
// For SocketFamily INET, this field is 4 octets (IPv4 address).
// For SocketFamily INET6, this field is 16 octets (IPv6 address).
optional bytes response_address = 5;
// The transport port of the message initiator.
// This is a 16-bit UDP or TCP port number, depending on SocketProtocol.
optional uint32 query_port = 6;
// The transport port of the message responder.
// This is a 16-bit UDP or TCP port number, depending on SocketProtocol.
optional uint32 response_port = 7;
// The time at which the DNS query message was sent or received, depending
// on whether this is an AUTH_QUERY, RESOLVER_QUERY, or CLIENT_QUERY.
// This is the number of seconds since the UNIX epoch.
optional uint64 query_time_sec = 8;
// The time at which the DNS query message was sent or received.
// This is the seconds fraction, expressed as a count of nanoseconds.
optional fixed32 query_time_nsec = 9;
// The initiator's original wire-format DNS query message, verbatim.
optional bytes query_message = 10;
// The "zone" or "bailiwick" pertaining to the DNS query message.
// This is a wire-format DNS domain name.
optional bytes query_zone = 11;
// The time at which the DNS response message was sent or received,
// depending on whether this is an AUTH_RESPONSE, RESOLVER_RESPONSE, or
// CLIENT_RESPONSE.
// This is the number of seconds since the UNIX epoch.
optional uint64 response_time_sec = 12;
// The time at which the DNS response message was sent or received.
// This is the seconds fraction, expressed as a count of nanoseconds.
optional fixed32 response_time_nsec = 13;
// The responder's original wire-format DNS response message, verbatim.
optional bytes response_message = 14;
}
// All fields except for 'type' in the Message schema are optional.
// It is recommended that at least the following fields be filled in for
// particular types of Messages.
// AUTH_QUERY:
// socket_family, socket_protocol
// query_address, query_port
// query_message
// query_time_sec, query_time_nsec
// AUTH_RESPONSE:
// socket_family, socket_protocol
// query_address, query_port
// query_time_sec, query_time_nsec
// response_message
// response_time_sec, response_time_nsec
// RESOLVER_QUERY:
// socket_family, socket_protocol
// query_name, query_type, query_class
// query_message
// query_time_sec, query_time_nsec
// query_zone
// response_address, response_port
// RESOLVER_RESPONSE:
// socket_family, socket_protocol
// query_name, query_type, query_class
// query_time_sec, query_time_nsec
// query_zone
// response_address, response_port
// response_message
// response_time_sec, response_time_nsec
// CLIENT_QUERY:
// socket_family, socket_protocol
// query_message
// query_time_sec, query_time_nsec
// CLIENT_RESPONSE:
// socket_family, socket_protocol
// query_time_sec, query_time_nsec
// response_message
// response_time_sec, response_time_nsec

View File

@ -0,0 +1,17 @@
#ifndef UNBOUND_DNSTAP_CONFIG_H
#define UNBOUND_DNSTAP_CONFIG_H
/*
* Process this file (dnstap_config.h.in) with AC_CONFIG_FILES to generate
* dnstap_config.h.
*
* This file exists so that USE_DNSTAP can be used without including config.h.
*/
#if @ENABLE_DNSTAP@ /* ENABLE_DNSTAP */
# ifndef USE_DNSTAP
# define USE_DNSTAP 1
# endif
#endif
#endif /* UNBOUND_DNSTAP_CONFIG_H */

23
external/unbound/doc/CREDITS vendored Normal file
View File

@ -0,0 +1,23 @@
Unbound was developed at NLnet Labs by Wouter Wijngaards.
Unbound was architected in January of 2004 by Jakob Schlyter of Kirei
and Roy Arends of Nominet. VeriSign and EP.Net funded development of
the prototype, which was built by David Blacka and Matt Larson of VeriSign.
Late in 2006, NLnet Labs joined the effort, writing an implementation in C
based on the existing prototype and using experience NLnet Labs gained
during the development of NSD, an authoritative DNS server.
At NLnet Labs, Jelte Jansen, Mark Santcroos and Matthijs Mekking
reviewed the unbound C sources.
Jakob Schlyter - for advice on secure settings, random numbers and blacklists.
Ondřej Surý - running coverity analysis tool on 0.9 dev version.
Alexander Gall - multihomed, anycast testing of unbound resolver server.
Zdenek Vasicek and Marek Vavrusa - python module.
cz.nic - sponsoring 'summer of code' development by Zdenek and Marek.
Brett Carr - windows beta testing.
Luca Bruno - patch for windows support in libunbound hosts and resolvconf().
Tom Hendrikx - contributed split-itar.sh a useful script to 5011-track ITAR.
Daisuke HIGASHI - patch for rrset-roundrobin and minimal-responses.
Simon Perrault - DNS64 module.
Robert Edmonds - dnstap code.

5618
external/unbound/doc/Changelog vendored Normal file

File diff suppressed because it is too large Load Diff

103
external/unbound/doc/FEATURES vendored Normal file
View File

@ -0,0 +1,103 @@
Unbound Features
(C) Copyright 2008, Wouter Wijngaards, NLnet Labs.
This document describes the features and RFCs that unbound
adheres to, and which ones are decided to be out of scope.
Big Features
------------
Recursive service.
Caching service.
Forwarding and stub zones.
Very limited authoritative service.
DNSSEC Validation options.
EDNS0, NSEC3, IPv6, DNAME, Unknown-RR-types.
RSASHA256, GOST, ECDSA, SHA384 DNSSEC algorithms.
Details
-------
Processing support
RFC 1034-1035: as a recursive, caching server. Not authoritative.
including CNAMEs, referrals, wildcards, classes, ...
AAAA type, and IP6 dual stack support.
type ANY queries are supported, class ANY queries are supported.
RFC 1123, 6.1 Requirements for DNS of internet hosts.
RFC 4033-4035: as a validating caching server (unbound daemon).
as a validating stub (libunbound).
RFC 1918.
RFC 1995, 1996, 2136: not authoritative, so no AXFR, IXFR, NOTIFY or
dynamic update services are appropriate.
RFC 2181: completely, including the trust model, keeping rrsets together.
RFC 2308: TTL directive, and the rest of the RFC too.
RFC 2671: EDNS0 support, default advertisement 4Kb size.
RFC 2672: DNAME support.
RFC 3597: Unknown RR type support.
RFC 4343: case insensitive handling of domain names.
RFC 4509: SHA256 DS hash.
RFC 4592: wildcards.
RFC 4697: No DNS Resolution Misbehavior.
RFC 5011: update of trust anchors with timers.
RFC 5155: NSEC3, NSEC3PARAM types
RFC 5358: reflectors-are-evil: access control list for recursive
service. In fact for all DNS service so cache snooping is halted.
RFC 5452: forgery resilience. all recommendations followed.
RFC 5702: RSASHA256 signature algorithm.
RFC 5933: GOST signature algorithm.
RFC 6303: default local zones.
It is possible to block zones or return an address for localhost.
This is a very limited authoritative service. Defaults as in draft.
RFC 6604: xNAME RCODE and status bits.
RFC 6605: ECDSA signature algorithm, SHA384 DS hash.
chroot and drop-root-privileges support, default enabled in config file.
AD bit in query can be used to request AD bit in response (w/o using DO bit).
CD bit in query can be used to request bogus data.
UDP and TCP service is provided downstream.
UDP and TCP are used to request from upstream servers.
SSL wrapped TCP service can be used upstream and provided downstream.
Multiple queries can be made over a TCP stream.
No TSIG support at this time.
No SIG0 support at this time.
No dTLS support at this time.
This is not a DNS statistics package, but some operationally useful
values are provided via unbound-control stats.
TXT RRs from the Chaos class (id.server, hostname.bind, ...) are supported.
draft-0x20: implemented, use caps-for-id option to enable use.
Also implements bitwise echo of the query to support downstream 0x20.
draft-ietf-dnsop-resolver-priming(-00): can prime and can fallback to
a safety belt list.
draft-ietf-dnsop-dnssec-trust-anchor(-01): DS records can be configured
as trust anchors. Also DNSKEYs are allowed, by the way.
draft-ietf-dnsext-dnssec-bis-updates: supported.
Record type syntax support, extensive, from lib ldns.
For these types only syntax and parsing support is needed.
RFC 1034-1035: basic RR types.
RFC 1183: RP, AFSDB, X25, ISDN, RT
RFC 1706: NSAP
RFC 2535: KEY, SIG, NXT: treated as unknown data, syntax is parsed (obsolete).
2163: PX
AAAA type
1876: LOC type
2782: SRV type
2915: NAPTR type.
2230: KX type.
2538: CERT type.
2672: DNAME type.
OPT type
3123: APL
3596: AAAA
SSHFP type
4025: IPSECKEY
4033-4035: DS, RRSIG, NSEC, DNSKEY
4701: DHCID
5155: NSEC3, NSEC3PARAM
4408: SPF
6944: DNSKEY algorithm status

30
external/unbound/doc/LICENSE vendored Normal file
View File

@ -0,0 +1,30 @@
Copyright (c) 2007, NLnet Labs. All rights reserved.
This software is open source.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
Neither the name of the NLNET LABS nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

149
external/unbound/doc/README vendored Normal file
View File

@ -0,0 +1,149 @@
README for Unbound @version@
Copyright 2007 NLnet Labs
http://unbound.net
This software is under BSD license, see LICENSE for details.
The DNS64 module has BSD license in dns64/dns64.c.
The DNSTAP code has BSD license in dnstap/dnstap.c.
* Download the latest release version of this software from
http://unbound.net
or get a beta version from the svn repository at
http://unbound.net/svn/
* Uses the following libraries;
* libevent http://www.monkey.org/~provos/libevent/ (BSD license)
(optional) can use builtin alternative instead.
* libexpat (for the unbound-anchor helper program) (MIT license)
* Make and install: ./configure; make; make install
* --with-libevent=/path/to/libevent
Can be set to either the system install or the build directory.
--with-libevent=no (default) gives a builtin alternative
implementation. libevent is useful when having many (thousands)
of outgoing ports. This improves randomization and spoof
resistance. For the default of 16 ports the builtin alternative
works well and is a little faster.
* --with-libexpat=/path/to/libexpat
Can be set to the install directory of libexpat.
* --without-pthreads
This disables pthreads. Without this option the pthreads library
is detected automatically. Use this option to disable threading
altogether, or, on Solaris, also use --with(out)-solaris-threads.
* --enable-checking
This enables assertions in the code that guard against a variety of
programming errors, among which buffer overflows. The program exits
with an error if an assertion fails (but the buffer did not overflow).
* --enable-static-exe
This enables a debug option to statically link against the
libevent library.
* --enable-lock-checks
This enables a debug option to check lock and unlock calls. It needs
a recent pthreads library to work.
* --enable-alloc-checks
This enables a debug option to check malloc (calloc, realloc, free).
The server periodically checks if the amount of memory used fits with
the amount of memory it thinks it should be using, and reports
memory usage in detail.
* --with-conf-file=filename
Set default location of config file,
the default is /usr/local/etc/unbound/unbound.conf.
* --with-pidfile=filename
Set default location of pidfile,
the default is /usr/local/etc/unbound/unbound.pid.
* --with-run-dir=path
Set default working directory,
the default is /usr/local/etc/unbound.
* --with-chroot-dir=path
Set default chroot directory,
the default is /usr/local/etc/unbound.
* --with-rootkey-file=path
Set the default root.key path. This file is read and written.
the default is /usr/local/etc/unbound/root.key
* --with-rootcert-file=path
Set the default root update certificate path. A builtin certificate
is used if this file is empty or does not exist.
the default is /usr/local/etc/unbound/icannbundle.pem
* --with-username=user
Set default user name to change to,
the default is the "unbound" user.
* --with-pyunbound
Create libunbound wrapper usable from python.
Needs python-devel and swig development tools.
* --with-pythonmodule
Compile the python module that processes responses in the server.
* --disable-sha2
Disable support for RSASHA256 and RSASHA512 crypto.
* --disable-gost
Disable support for GOST crypto, RFC 5933.
* 'make test' runs a series of self checks.
Known issues
------------
o If there are no replies for a forward or stub zone, for a reverse zone,
you may need to add a local-zone: name transparent or nodefault to the
server: section of the config file to unblock the reverse zone.
Only happens for (sub)zones that are blocked by default; e.g. 10.in-addr.arpa
o If libevent is older (before 1.3c), unbound will exit instead of reload
on sighup. On a restart 'did not exit gracefully last time' warning is
printed. Perform ./configure --with-libevent=no or update libevent, rerun
configure and recompile unbound to make sighup work correctly.
It is strongly suggested to use a recent version of libevent.
o If you are not receiving the correct source IP address on replies (e.g.
you are running a multihomed, anycast server), the interface-automatic
option can be enabled to set socket options to achieve the correct
source IP address on UDP replies. Listing all IP addresses explicitly in
the config file is an alternative. The interface-automatic option uses
non portable socket options, Linux and FreeBSD should work fine.
o The warning 'openssl has no entropy, seeding with time', with chroot
enabled, may be solved with a symbolic link to /dev/random from <chrootdir>.
o On Solaris 5.10 some libtool packages from repositories do not work with
gcc, showing errors gcc: unrecognized option `-KPIC'
To solve this do ./configure libtool=./libtool [your options...].
On Solaris you may pass CFLAGS="-xO4 -xtarget=generic" if you use sun-cc.
o If unbound-control (or munin graphs) do not work, this can often be because
the unbound-control-setup script creates the keys with restricted
permissions, and the files need to be made readable or ownered by both the
unbound daemon and unbound-control.
o Crosscompile seems to hang. You tried to install unbound under wine.
wine regedit and remove all the unbound entries from the registry or
delete .wine/drive_c.
Acknowledgements
----------------
o Unbound was written in portable C by Wouter Wijngaards (NLnet Labs).
o Thanks to David Blacka and Matt Larson (Verisign) for the unbound-java
prototype. Design and code from that prototype has been used to create
this program. Such as the iterator state machine and the cache design.
o Other code origins are from the NSD (NLnet Labs) and LDNS (NLnet Labs)
projects. Such as buffer, region-allocator and red-black tree code.
o See Credits file for contributors.
Your Support
------------
NLnet Labs offers all of its software products as open source, most are
published under a BSD license. You can download them, not only from the
NLnet Labs website but also through the various OS distributions for
which NSD, ldns, and Unbound are packaged. We therefore have little idea
who uses our software in production environments and have no direct ties
with 'our customers'.
Therefore, we ask you to contact us at users@NLnetLabs.nl and tell us
whether you use one of our products in your production environment,
what that environment looks like, and maybe even share some praise.
We would like to refer to the fact that your organization is using our
products. We will only do that if you explicitly allow us. In all other
cases we will keep the information you share with us to ourselves.
In addition to the moral support you can also support us
financially. NLnet Labs is a recognized not-for-profit charity foundation
that is chartered to develop open-source software and open-standards
for the Internet. If you use our software to satisfaction please express
that by giving us a donation. For small donations PayPal can be used. For
larger and regular donations please contact us at users@NLnetLabs.nl. Also
see http://www.nlnetlabs.nl/labs/contributors/.
* mailto:unbound-bugs@nlnetlabs.nl

30
external/unbound/doc/README.DNS64 vendored Normal file
View File

@ -0,0 +1,30 @@
The DNS64 code was written by Viagenie, 2009, by Simon Perrault as part
of the Ecdysis project. The code is copyright by them, and has the BSD
license (see the dns64/dns64.c file).
To enable DNS64 functionality in Unbound, two directives in unbound.conf must
be edited:
1. The "module-config" directive must start with "dns64". For example:
module-config: "dns64 validator iterator"
If you're not using DNSSEC then you may remove "validator".
2. The "dns64-prefix" directive indicates your DNS64 prefix. For example:
dns64-prefix: 64:FF9B::/96
The prefix must be a /96 or shorter.
To test that things are working right, perform a query against Unbound for a
domain name for which no AAAA record exists. You should see a AAAA record in
the answer section. The corresponding IPv6 address will be inside the DNS64
prefix. For example:
$ unbound -c unbound.conf
$ dig @localhost jazz-v4.viagenie.ca aaaa
[...]
;; ANSWER SECTION:
jazz-v4.viagenie.ca. 86400 IN AAAA 64:ff9b::ce7b:1f02

17
external/unbound/doc/README.svn vendored Normal file
View File

@ -0,0 +1,17 @@
README.svn
For a svn checkout:
* configure script, aclocal.m4, as well as yacc/lex output files are
committed to the repository.
* use --enable-debug flag for configure to enable dependency tracking and
assertions, otherwise, use make clean; make after svn update.
* Note changes in the Changelog.
* Every check-in a postcommit hook is run
(the postcommit hook is in the svn/unbound/hooks directory).
* generates commit email with your changes and comment.
* compiles and runs the tests (with testcode/do-tests.sh).
* If build errors or test errors happen
* Please fix your errors and commit again.
* Use gnu make to compile, make or 'gmake'.

24
external/unbound/doc/README.tests vendored Normal file
View File

@ -0,0 +1,24 @@
README unbound tests
For a quick test that runs unit tests and state machine tests, use
make test
There is a long test setup for unbound that needs tools installed. Use
make longtest
To make and run the long tests. The results are summarized at the end.
You need to have the following programs installed and in your PATH.
* dig - from the bind-tools package. Used to send DNS queries.
* splint (optional) - for lint test
* doxygen (optional) - for doc completeness test
* ldns-testns - from ldns examples. Used as DNS auth server.
* xxd and nc (optional) - for (malformed) packet transmission.
The optional programs are detected and can be omitted.
testdata/ contains the data for tests.
testcode/ contains scripts and c code for the tests.
do-tests.sh : runs all the tests in the testdata directory.
testbed.sh : compiles on a set of (user specific) hosts and runs do-tests.
Tests are run using testcode/mini_tpkg.sh.

76
external/unbound/doc/TODO vendored Normal file
View File

@ -0,0 +1,76 @@
TODO items. These are interesting todo items.
o understand synthesized DNAMEs, so those TTL=0 packets are cached properly.
o NSEC/NSEC3 aggressive negative caching, so that updates to NSEC/NSEC3
will result in proper negative responses.
o (option) where port 53 is used for send and receive, no other ports are used.
o (option) to not send replies to clients after a timeout of (say 5 secs) has
passed, but keep task active for later retries by client.
o (option) private TTL feature (always report TTL x in answers).
o (option) pretend-dnssec-unaware, and pretend-edns-unaware modes for workshops.
o delegpt use rbtree for ns-list, to avoid slowdown for very large NS sets.
o (option) reprime and refresh oft used data before timeout.
o (option) retain prime results in a overlaid roothints file.
o (option) store primed key data in a overlaid keyhints file (sort of like drafttimers).
o windows version, auto update feature, a query to check for the version.
o command the server with TSIG inband. get-config, clearcache,
get stats, get memstats, get ..., reload, clear one zone from cache
o NSID rfc 5001 support.
o timers rfc 5011 support.
o Treat YXDOMAIN from a DNAME properly, in iterator (not throwaway), validator.
o make timeout backoffs randomized (a couple percent random) to spread traffic.
o inspect date on executable, then warn user in log if its more than 1 year.
o (option) proactively prime root, stubs and trust anchors, feature.
early failure, faster on first query, but more traffic.
o library add convenience functions for A, AAAA, PTR, getaddrinfo, libresolve.
o library add function to validate input from app that is signed.
o add dynamic-update requests (making a dynupd request) to libunbound api.
o SIG(0) and TSIG.
o support OPT record placement on recv anywhere in the additional section.
o add local-file: config with authority features.
o (option) to make local-data answers be secure for libunbound (default=no)
o (option) to make chroot: copy all needed files into jail (or make jail)
perhaps also print reminder to link /dev/random and sysloghack.
o overhaul outside-network servicedquery to merge with udpwait and tcpwait,
to make timers in servicedquery independent of udpwait queues.
o check into rebinding ports for efficiency, configure time test.
o EVP hardware crypto support.
o option to ignore all inception and expiration dates for rrsigs.
o cleaner code; return and func statements on newline.
o memcached module that sits before validator module; checks for memcached
data (on local lan), stores recursion lookup. Provides one cache for multiple resolver machines, coherent reply content in anycast setup.
o no openssl_add_all_algorithms, but only the ones necessary, less space.
o listen to NOTIFY messages for zones and flush the cache for that zone
if received. Useful when also having a stub to that auth server.
Needs proper protection, TSIG, in place.
o winevent - do not go more than 64 fds (by polling with select one by
one), win95/98 have 100fd limit in the kernel, so this ruins w9x portability.
*** Features features, for later
* dTLS, TLS, look to need special port numbers, cert storage, recent libssl.
* aggressive negative caching for NSEC, NSEC3.
* multiple queries per question, server exploration, server selection.
* support TSIG on queries, for validating resolver deployment.
* retry-mode, where a bogus result triggers a retry-mode query, where a list
of responses over a time interval is collected, and each is validated.
or try in TCP mode. Do not 'try all servers several times', since we must
not create packet storms with operator errors.
o on windows version, implement that OS ancillary data capabilities for
interface-automatic. IPPKTINFO, IP6PKTINFO for WSARecvMsg, WSASendMsg.
o local-zone directive with authority service, full authority server
is a non-goal.
o infra and lame cache: easier size config (in Mb), show usage in graphs.
- store time of dump in cachedumps, so that on a load the ttls can be
compared to the absolute time, and now-expired items can be dealt with.
later
- selective verbosity; ubcontrol trace example.com
- cache fork-dump, pre-load
- for fwds, send queries to N servers in fwd-list, use first reply.
document high scalable, high available unbound setup onepager.
- prefetch DNSKEY when DS in delegation seen (nonCD, underTA).
- use libevent if available on system by default(?), default outgoing 256to1024
[1] BIND-like query logging to see who's looking up what and when
[2] more logging about stuff like SERVFAIL and REFUSED responses
[3] a Makefile that works without gnumake

View File

@ -0,0 +1,70 @@
Specification for the unbound-control protocol.
Server listens on 8953 TCP (localhost by default). Client connects,
SSLv3 or TLSv1 connection setup (server selfsigned certificate,
client has cert signed by server certificate).
Port 8953 is registered with IANA as:
ub-dns-control 8953/tcp unbound dns nameserver control
# Wouter Wijngaards <wouter&nlnetlabs.nl> 10 May 2011
On may 11 2011, ticket [IANA #442315].
Query and Response
------------------
Client sends
UBCT[version] [commandline] \n
fixed string UBCT1 (for version 1), then an ascii text line,
with a command, some whitespace allowed. Line ends with '\n'.
Server executes command. And sends reply in ascii text over channel,
closes the channel when done.
in case of error the first line of the response is:
error <descriptive text possible> \n
or the remainder is data of the response, for many commands the
response is 'ok\n'.
Queries and responses
---------------------
stop
stops the server.
reload
reloads the config file, and flushes the cache.
verbosity <new value>
Change logging verbosity to new value.
stats
output is a list of [name]=[value] lines.
clears the counters.
dump_cache
output is a text representation of the cache contents.
data ends with a line 'EOF' before connection close.
load_cache
client sends cache contents (like from dump_cache), which is stored
in the cache. end of data indicated with a line with 'EOF' on it.
The data is sent after the query line.
flush <name>
flushes some information regarding the name from the cache.
removes the A, AAAA, NS, SOA, CNAME, DNAME, MX, PTR, SRV, NAPTR types.
Does not remove other types.
flush_type <name> <RR type>
removes rrtype entry from the cache.
flush_zone <name>
removes name and everything below that name from the cache.
has to search through the cache item by item, so this is slow.
lookup <name>
see what servers would be queried for a lookup of the given name.
local_zone_remove <name of local-zone entry>
the local-zone entry is removed.
All data from the local zone is also deleted.
If it did not exist, nothing happens.
local_zone <name of local zone> <type>
As the config file entry. Adds new local zone or updates
existing zone type.
local_data_remove <name>
Removes local-data (all types) name.
local_data <resource record string>
Add new local data record (on the rest of the line).
local_data_add www.example.com. IN A 192.0.2.2
if no local_zone exists for it; a transparent zone with the same
name as the data is created.
Other commands in the unbound-control manual page.

603
external/unbound/doc/example.conf.in vendored Normal file
View File

@ -0,0 +1,603 @@
#
# Example configuration file.
#
# See unbound.conf(5) man page, version @version@.
#
# this is a comment.
#Use this to include other text into the file.
#include: "otherfile.conf"
# The server clause sets the main parameters.
server:
# whitespace is not necessary, but looks cleaner.
# verbosity number, 0 is least verbose. 1 is default.
verbosity: 1
# print statistics to the log (for every thread) every N seconds.
# Set to "" or 0 to disable. Default is disabled.
# statistics-interval: 0
# enable cumulative statistics, without clearing them after printing.
# statistics-cumulative: no
# enable extended statistics (query types, answer codes, status)
# printed from unbound-control. default off, because of speed.
# extended-statistics: no
# number of threads to create. 1 disables threading.
# num-threads: 1
# specify the interfaces to answer queries from by ip-address.
# The default is to listen to localhost (127.0.0.1 and ::1).
# specify 0.0.0.0 and ::0 to bind to all available interfaces.
# specify every interface[@port] on a new 'interface:' labelled line.
# The listen interfaces are not changed on reload, only on restart.
# interface: 192.0.2.153
# interface: 192.0.2.154
# interface: 192.0.2.154@5003
# interface: 2001:DB8::5
# enable this feature to copy the source address of queries to reply.
# Socket options are not supported on all platforms. experimental.
# interface-automatic: no
# port to answer queries from
# port: 53
# specify the interfaces to send outgoing queries to authoritative
# server from by ip-address. If none, the default (all) interface
# is used. Specify every interface on a 'outgoing-interface:' line.
# outgoing-interface: 192.0.2.153
# outgoing-interface: 2001:DB8::5
# outgoing-interface: 2001:DB8::6
# number of ports to allocate per thread, determines the size of the
# port range that can be open simultaneously. About double the
# num-queries-per-thread, or, use as many as the OS will allow you.
# outgoing-range: 4096
# permit unbound to use this port number or port range for
# making outgoing queries, using an outgoing interface.
# outgoing-port-permit: 32768
# deny unbound the use this of port number or port range for
# making outgoing queries, using an outgoing interface.
# Use this to make sure unbound does not grab a UDP port that some
# other server on this computer needs. The default is to avoid
# IANA-assigned port numbers.
# If multiple outgoing-port-permit and outgoing-port-avoid options
# are present, they are processed in order.
# outgoing-port-avoid: "3200-3208"
# number of outgoing simultaneous tcp buffers to hold per thread.
# outgoing-num-tcp: 10
# number of incoming simultaneous tcp buffers to hold per thread.
# incoming-num-tcp: 10
# buffer size for UDP port 53 incoming (SO_RCVBUF socket option).
# 0 is system default. Use 4m to catch query spikes for busy servers.
# so-rcvbuf: 0
# buffer size for UDP port 53 outgoing (SO_SNDBUF socket option).
# 0 is system default. Use 4m to handle spikes on very busy servers.
# so-sndbuf: 0
# use SO_REUSEPORT to distribute queries over threads.
# so-reuseport: no
# EDNS reassembly buffer to advertise to UDP peers (the actual buffer
# is set with msg-buffer-size). 1480 can solve fragmentation (timeouts).
# edns-buffer-size: 4096
# Maximum UDP response size (not applied to TCP response).
# Suggested values are 512 to 4096. Default is 4096. 65536 disables it.
# max-udp-size: 4096
# buffer size for handling DNS data. No messages larger than this
# size can be sent or received, by UDP or TCP. In bytes.
# msg-buffer-size: 65552
# the amount of memory to use for the message cache.
# plain value in bytes or you can append k, m or G. default is "4Mb".
# msg-cache-size: 4m
# the number of slabs to use for the message cache.
# the number of slabs must be a power of 2.
# more slabs reduce lock contention, but fragment memory usage.
# msg-cache-slabs: 4
# the number of queries that a thread gets to service.
# num-queries-per-thread: 1024
# if very busy, 50% queries run to completion, 50% get timeout in msec
# jostle-timeout: 200
# msec to wait before close of port on timeout UDP. 0 disables.
# delay-close: 0
# the amount of memory to use for the RRset cache.
# plain value in bytes or you can append k, m or G. default is "4Mb".
# rrset-cache-size: 4m
# the number of slabs to use for the RRset cache.
# the number of slabs must be a power of 2.
# more slabs reduce lock contention, but fragment memory usage.
# rrset-cache-slabs: 4
# the time to live (TTL) value lower bound, in seconds. Default 0.
# If more than an hour could easily give trouble due to stale data.
# cache-min-ttl: 0
# the time to live (TTL) value cap for RRsets and messages in the
# cache. Items are not cached for longer. In seconds.
# cache-max-ttl: 86400
# the time to live (TTL) value for cached roundtrip times, lameness and
# EDNS version information for hosts. In seconds.
# infra-host-ttl: 900
# the number of slabs to use for the Infrastructure cache.
# the number of slabs must be a power of 2.
# more slabs reduce lock contention, but fragment memory usage.
# infra-cache-slabs: 4
# the maximum number of hosts that are cached (roundtrip, EDNS, lame).
# infra-cache-numhosts: 10000
# Enable IPv4, "yes" or "no".
# do-ip4: yes
# Enable IPv6, "yes" or "no".
# do-ip6: yes
# Enable UDP, "yes" or "no".
# do-udp: yes
# Enable TCP, "yes" or "no".
# do-tcp: yes
# upstream connections use TCP only (and no UDP), "yes" or "no"
# useful for tunneling scenarios, default no.
# tcp-upstream: no
# Detach from the terminal, run in background, "yes" or "no".
# do-daemonize: yes
# control which clients are allowed to make (recursive) queries
# to this server. Specify classless netblocks with /size and action.
# By default everything is refused, except for localhost.
# Choose deny (drop message), refuse (polite error reply),
# allow (recursive ok), allow_snoop (recursive and nonrecursive ok)
# deny_non_local (drop queries unless can be answered from local-data)
# refuse_non_local (like deny_non_local but polite error reply).
# access-control: 0.0.0.0/0 refuse
# access-control: 127.0.0.0/8 allow
# access-control: ::0/0 refuse
# access-control: ::1 allow
# access-control: ::ffff:127.0.0.1 allow
# if given, a chroot(2) is done to the given directory.
# i.e. you can chroot to the working directory, for example,
# for extra security, but make sure all files are in that directory.
#
# If chroot is enabled, you should pass the configfile (from the
# commandline) as a full path from the original root. After the
# chroot has been performed the now defunct portion of the config
# file path is removed to be able to reread the config after a reload.
#
# All other file paths (working dir, logfile, roothints, and
# key files) can be specified in several ways:
# o as an absolute path relative to the new root.
# o as a relative path to the working directory.
# o as an absolute path relative to the original root.
# In the last case the path is adjusted to remove the unused portion.
#
# The pid file can be absolute and outside of the chroot, it is
# written just prior to performing the chroot and dropping permissions.
#
# Additionally, unbound may need to access /dev/random (for entropy).
# How to do this is specific to your OS.
#
# If you give "" no chroot is performed. The path must not end in a /.
# chroot: "@UNBOUND_CHROOT_DIR@"
# if given, user privileges are dropped (after binding port),
# and the given username is assumed. Default is user "unbound".
# If you give "" no privileges are dropped.
# username: "@UNBOUND_USERNAME@"
# the working directory. The relative files in this config are
# relative to this directory. If you give "" the working directory
# is not changed.
# directory: "@UNBOUND_RUN_DIR@"
# the log file, "" means log to stderr.
# Use of this option sets use-syslog to "no".
# logfile: ""
# Log to syslog(3) if yes. The log facility LOG_DAEMON is used to
# log to, with identity "unbound". If yes, it overrides the logfile.
# use-syslog: yes
# print UTC timestamp in ascii to logfile, default is epoch in seconds.
# log-time-ascii: no
# print one line with time, IP, name, type, class for every query.
# log-queries: no
# the pid file. Can be an absolute path outside of chroot/work dir.
# pidfile: "@UNBOUND_PIDFILE@"
# file to read root hints from.
# get one from ftp://FTP.INTERNIC.NET/domain/named.cache
# root-hints: ""
# enable to not answer id.server and hostname.bind queries.
# hide-identity: no
# enable to not answer version.server and version.bind queries.
# hide-version: no
# the identity to report. Leave "" or default to return hostname.
# identity: ""
# the version to report. Leave "" or default to return package version.
# version: ""
# the target fetch policy.
# series of integers describing the policy per dependency depth.
# The number of values in the list determines the maximum dependency
# depth the recursor will pursue before giving up. Each integer means:
# -1 : fetch all targets opportunistically,
# 0: fetch on demand,
# positive value: fetch that many targets opportunistically.
# Enclose the list of numbers between quotes ("").
# target-fetch-policy: "3 2 1 0 0"
# Harden against very small EDNS buffer sizes.
# harden-short-bufsize: no
# Harden against unseemly large queries.
# harden-large-queries: no
# Harden against out of zone rrsets, to avoid spoofing attempts.
# harden-glue: yes
# Harden against receiving dnssec-stripped data. If you turn it
# off, failing to validate dnskey data for a trustanchor will
# trigger insecure mode for that zone (like without a trustanchor).
# Default on, which insists on dnssec data for trust-anchored zones.
# harden-dnssec-stripped: yes
# Harden against queries that fall under dnssec-signed nxdomain names.
# harden-below-nxdomain: no
# Harden the referral path by performing additional queries for
# infrastructure data. Validates the replies (if possible).
# Default off, because the lookups burden the server. Experimental
# implementation of draft-wijngaards-dnsext-resolver-side-mitigation.
# harden-referral-path: no
# Use 0x20-encoded random bits in the query to foil spoof attempts.
# This feature is an experimental implementation of draft dns-0x20.
# use-caps-for-id: no
# Enforce privacy of these addresses. Strips them away from answers.
# It may cause DNSSEC validation to additionally mark it as bogus.
# Protects against 'DNS Rebinding' (uses browser as network proxy).
# Only 'private-domain' and 'local-data' names are allowed to have
# these private addresses. No default.
# private-address: 10.0.0.0/8
# private-address: 172.16.0.0/12
# private-address: 192.168.0.0/16
# private-address: 169.254.0.0/16
# private-address: fd00::/8
# private-address: fe80::/10
# Allow the domain (and its subdomains) to contain private addresses.
# local-data statements are allowed to contain private addresses too.
# private-domain: "example.com"
# If nonzero, unwanted replies are not only reported in statistics,
# but also a running total is kept per thread. If it reaches the
# threshold, a warning is printed and a defensive action is taken,
# the cache is cleared to flush potential poison out of it.
# A suggested value is 10000000, the default is 0 (turned off).
# unwanted-reply-threshold: 0
# Do not query the following addresses. No DNS queries are sent there.
# List one address per entry. List classless netblocks with /size,
# do-not-query-address: 127.0.0.1/8
# do-not-query-address: ::1
# if yes, the above default do-not-query-address entries are present.
# if no, localhost can be queried (for testing and debugging).
# do-not-query-localhost: yes
# if yes, perform prefetching of almost expired message cache entries.
# prefetch: no
# if yes, perform key lookups adjacent to normal lookups.
# prefetch-key: no
# if yes, Unbound rotates RRSet order in response.
# rrset-roundrobin: no
# if yes, Unbound doesn't insert authority/additional sections
# into response messages when those sections are not required.
# minimal-responses: no
# module configuration of the server. A string with identifiers
# separated by spaces. Syntax: "[dns64] [validator] iterator"
# module-config: "validator iterator"
# File with trusted keys, kept uptodate using RFC5011 probes,
# initial file like trust-anchor-file, then it stores metadata.
# Use several entries, one per domain name, to track multiple zones.
#
# If you want to perform DNSSEC validation, run unbound-anchor before
# you start unbound (i.e. in the system boot scripts). And enable:
# Please note usage of unbound-anchor root anchor is at your own risk
# and under the terms of our LICENSE (see that file in the source).
# auto-trust-anchor-file: "@UNBOUND_ROOTKEY_FILE@"
# File with DLV trusted keys. Same format as trust-anchor-file.
# There can be only one DLV configured, it is trusted from root down.
# Download http://ftp.isc.org/www/dlv/dlv.isc.org.key
# dlv-anchor-file: "dlv.isc.org.key"
# File with trusted keys for validation. Specify more than one file
# with several entries, one file per entry.
# Zone file format, with DS and DNSKEY entries.
# Note this gets out of date, use auto-trust-anchor-file please.
# trust-anchor-file: ""
# Trusted key for validation. DS or DNSKEY. specify the RR on a
# single line, surrounded by "". TTL is ignored. class is IN default.
# Note this gets out of date, use auto-trust-anchor-file please.
# (These examples are from August 2007 and may not be valid anymore).
# trust-anchor: "nlnetlabs.nl. DNSKEY 257 3 5 AQPzzTWMz8qSWIQlfRnPckx2BiVmkVN6LPupO3mbz7FhLSnm26n6iG9N Lby97Ji453aWZY3M5/xJBSOS2vWtco2t8C0+xeO1bc/d6ZTy32DHchpW 6rDH1vp86Ll+ha0tmwyy9QP7y2bVw5zSbFCrefk8qCUBgfHm9bHzMG1U BYtEIQ=="
# trust-anchor: "jelte.nlnetlabs.nl. DS 42860 5 1 14D739EB566D2B1A5E216A0BA4D17FA9B038BE4A"
# File with trusted keys for validation. Specify more than one file
# with several entries, one file per entry. Like trust-anchor-file
# but has a different file format. Format is BIND-9 style format,
# the trusted-keys { name flag proto algo "key"; }; clauses are read.
# you need external update procedures to track changes in keys.
# trusted-keys-file: ""
# Ignore chain of trust. Domain is treated as insecure.
# domain-insecure: "example.com"
# Override the date for validation with a specific fixed date.
# Do not set this unless you are debugging signature inception
# and expiration. "" or "0" turns the feature off. -1 ignores date.
# val-override-date: ""
# The time to live for bogus data, rrsets and messages. This avoids
# some of the revalidation, until the time interval expires. in secs.
# val-bogus-ttl: 60
# The signature inception and expiration dates are allowed to be off
# by 10% of the signature lifetime (expir-incep) from our local clock.
# This leeway is capped with a minimum and a maximum. In seconds.
# val-sig-skew-min: 3600
# val-sig-skew-max: 86400
# Should additional section of secure message also be kept clean of
# unsecure data. Useful to shield the users of this validator from
# potential bogus data in the additional section. All unsigned data
# in the additional section is removed from secure messages.
# val-clean-additional: yes
# Turn permissive mode on to permit bogus messages. Thus, messages
# for which security checks failed will be returned to clients,
# instead of SERVFAIL. It still performs the security checks, which
# result in interesting log files and possibly the AD bit in
# replies if the message is found secure. The default is off.
# val-permissive-mode: no
# Ignore the CD flag in incoming queries and refuse them bogus data.
# Enable it if the only clients of unbound are legacy servers (w2008)
# that set CD but cannot validate themselves.
# ignore-cd-flag: no
# Have the validator log failed validations for your diagnosis.
# 0: off. 1: A line per failed user query. 2: With reason and bad IP.
# val-log-level: 0
# It is possible to configure NSEC3 maximum iteration counts per
# keysize. Keep this table very short, as linear search is done.
# A message with an NSEC3 with larger count is marked insecure.
# List in ascending order the keysize and count values.
# val-nsec3-keysize-iterations: "1024 150 2048 500 4096 2500"
# instruct the auto-trust-anchor-file probing to add anchors after ttl.
# add-holddown: 2592000 # 30 days
# instruct the auto-trust-anchor-file probing to del anchors after ttl.
# del-holddown: 2592000 # 30 days
# auto-trust-anchor-file probing removes missing anchors after ttl.
# If the value 0 is given, missing anchors are not removed.
# keep-missing: 31622400 # 366 days
# the amount of memory to use for the key cache.
# plain value in bytes or you can append k, m or G. default is "4Mb".
# key-cache-size: 4m
# the number of slabs to use for the key cache.
# the number of slabs must be a power of 2.
# more slabs reduce lock contention, but fragment memory usage.
# key-cache-slabs: 4
# the amount of memory to use for the negative cache (used for DLV).
# plain value in bytes or you can append k, m or G. default is "1Mb".
# neg-cache-size: 1m
# By default, for a number of zones a small default 'nothing here'
# reply is built-in. Query traffic is thus blocked. If you
# wish to serve such zone you can unblock them by uncommenting one
# of the nodefault statements below.
# You may also have to use domain-insecure: zone to make DNSSEC work,
# unless you have your own trust anchors for this zone.
# local-zone: "localhost." nodefault
# local-zone: "127.in-addr.arpa." nodefault
# local-zone: "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa." nodefault
# local-zone: "10.in-addr.arpa." nodefault
# local-zone: "16.172.in-addr.arpa." nodefault
# local-zone: "17.172.in-addr.arpa." nodefault
# local-zone: "18.172.in-addr.arpa." nodefault
# local-zone: "19.172.in-addr.arpa." nodefault
# local-zone: "20.172.in-addr.arpa." nodefault
# local-zone: "21.172.in-addr.arpa." nodefault
# local-zone: "22.172.in-addr.arpa." nodefault
# local-zone: "23.172.in-addr.arpa." nodefault
# local-zone: "24.172.in-addr.arpa." nodefault
# local-zone: "25.172.in-addr.arpa." nodefault
# local-zone: "26.172.in-addr.arpa." nodefault
# local-zone: "27.172.in-addr.arpa." nodefault
# local-zone: "28.172.in-addr.arpa." nodefault
# local-zone: "29.172.in-addr.arpa." nodefault
# local-zone: "30.172.in-addr.arpa." nodefault
# local-zone: "31.172.in-addr.arpa." nodefault
# local-zone: "168.192.in-addr.arpa." nodefault
# local-zone: "0.in-addr.arpa." nodefault
# local-zone: "254.169.in-addr.arpa." nodefault
# local-zone: "2.0.192.in-addr.arpa." nodefault
# local-zone: "100.51.198.in-addr.arpa." nodefault
# local-zone: "113.0.203.in-addr.arpa." nodefault
# local-zone: "255.255.255.255.in-addr.arpa." nodefault
# local-zone: "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa." nodefault
# local-zone: "d.f.ip6.arpa." nodefault
# local-zone: "8.e.f.ip6.arpa." nodefault
# local-zone: "9.e.f.ip6.arpa." nodefault
# local-zone: "a.e.f.ip6.arpa." nodefault
# local-zone: "b.e.f.ip6.arpa." nodefault
# local-zone: "8.b.d.0.1.0.0.2.ip6.arpa." nodefault
# And for 64.100.in-addr.arpa. to 127.100.in-addr.arpa.
# if unbound is running service for the local host then it is useful
# to perform lan-wide lookups to the upstream, and unblock the
# long list of local-zones above. If this unbound is a dns server
# for a network of computers, disabled is better and stops information
# leakage of local lan information.
# unblock-lan-zones: no
# a number of locally served zones can be configured.
# local-zone: <zone> <type>
# local-data: "<resource record string>"
# o deny serves local data (if any), else, drops queries.
# o refuse serves local data (if any), else, replies with error.
# o static serves local data, else, nxdomain or nodata answer.
# o transparent gives local data, but resolves normally for other names
# o redirect serves the zone data for any subdomain in the zone.
# o nodefault can be used to normally resolve AS112 zones.
# o typetransparent resolves normally for other types and other names
#
# defaults are localhost address, reverse for 127.0.0.1 and ::1
# and nxdomain for AS112 zones. If you configure one of these zones
# the default content is omitted, or you can omit it with 'nodefault'.
#
# If you configure local-data without specifying local-zone, by
# default a transparent local-zone is created for the data.
#
# You can add locally served data with
# local-zone: "local." static
# local-data: "mycomputer.local. IN A 192.0.2.51"
# local-data: 'mytext.local TXT "content of text record"'
#
# You can override certain queries with
# local-data: "adserver.example.com A 127.0.0.1"
#
# You can redirect a domain to a fixed address with
# (this makes example.com, www.example.com, etc, all go to 192.0.2.3)
# local-zone: "example.com" redirect
# local-data: "example.com A 192.0.2.3"
#
# Shorthand to make PTR records, "IPv4 name" or "IPv6 name".
# You can also add PTR records using local-data directly, but then
# you need to do the reverse notation yourself.
# local-data-ptr: "192.0.2.3 www.example.com"
# service clients over SSL (on the TCP sockets), with plain DNS inside
# the SSL stream. Give the certificate to use and private key.
# default is "" (disabled). requires restart to take effect.
# ssl-service-key: "path/to/privatekeyfile.key"
# ssl-service-pem: "path/to/publiccertfile.pem"
# ssl-port: 443
# request upstream over SSL (with plain DNS inside the SSL stream).
# Default is no. Can be turned on and off with unbound-control.
# ssl-upstream: no
# DNS64 prefix. Must be specified when DNS64 is use.
# Enable dns64 in module-config. Used to synthesize IPv6 from IPv4.
# dns64-prefix: 64:ff9b::0/96
# Python config section. To enable:
# o use --with-pythonmodule to configure before compiling.
# o list python in the module-config string (above) to enable.
# o and give a python-script to run.
python:
# Script file to load
# python-script: "@UNBOUND_SHARE_DIR@/ubmodule-tst.py"
# Remote control config section.
remote-control:
# Enable remote control with unbound-control(8) here.
# set up the keys and certificates with unbound-control-setup.
# control-enable: no
# what interfaces are listened to for remote control.
# give 0.0.0.0 and ::0 to listen to all interfaces.
# control-interface: 127.0.0.1
# control-interface: ::1
# port number for remote control operations.
# control-port: 8953
# unbound server key file.
# server-key-file: "@UNBOUND_RUN_DIR@/unbound_server.key"
# unbound server certificate file.
# server-cert-file: "@UNBOUND_RUN_DIR@/unbound_server.pem"
# unbound-control key file.
# control-key-file: "@UNBOUND_RUN_DIR@/unbound_control.key"
# unbound-control certificate file.
# control-cert-file: "@UNBOUND_RUN_DIR@/unbound_control.pem"
# Stub zones.
# Create entries like below, to make all queries for 'example.com' and
# 'example.org' go to the given list of nameservers. list zero or more
# nameservers by hostname or by ipaddress. If you set stub-prime to yes,
# the list is treated as priming hints (default is no).
# With stub-first yes, it attempts without the stub if it fails.
# stub-zone:
# name: "example.com"
# stub-addr: 192.0.2.68
# stub-prime: no
# stub-first: no
# stub-zone:
# name: "example.org"
# stub-host: ns.example.com.
# Forward zones
# Create entries like below, to make all queries for 'example.com' and
# 'example.org' go to the given list of servers. These servers have to handle
# recursion to other nameservers. List zero or more nameservers by hostname
# or by ipaddress. Use an entry with name "." to forward all queries.
# If you enable forward-first, it attempts without the forward if it fails.
# forward-zone:
# name: "example.com"
# forward-addr: 192.0.2.68
# forward-addr: 192.0.2.73@5355 # forward to port 5355.
# forward-first: no
# forward-zone:
# name: "example.org"
# forward-host: fwd.example.com

Binary file not shown.

Binary file not shown.

385
external/unbound/doc/libunbound.3.in vendored Normal file
View File

@ -0,0 +1,385 @@
.TH "libunbound" "3" "@date@" "NLnet Labs" "unbound @version@"
.\"
.\" libunbound.3 -- unbound library functions manual
.\"
.\" Copyright (c) 2007, NLnet Labs. All rights reserved.
.\"
.\" See LICENSE for the license.
.\"
.\"
.SH "NAME"
.B libunbound,
.B unbound.h,
.B ub_ctx,
.B ub_result,
.B ub_callback_t,
.B ub_ctx_create,
.B ub_ctx_delete,
.B ub_ctx_set_option,
.B ub_ctx_get_option,
.B ub_ctx_config,
.B ub_ctx_set_fwd,
.B ub_ctx_resolvconf,
.B ub_ctx_hosts,
.B ub_ctx_add_ta,
.B ub_ctx_add_ta_file,
.B ub_ctx_trustedkeys,
.B ub_ctx_debugout,
.B ub_ctx_debuglevel,
.B ub_ctx_async,
.B ub_poll,
.B ub_wait,
.B ub_fd,
.B ub_process,
.B ub_resolve,
.B ub_resolve_async,
.B ub_cancel,
.B ub_resolve_free,
.B ub_strerror,
.B ub_ctx_print_local_zones,
.B ub_ctx_zone_add,
.B ub_ctx_zone_remove,
.B ub_ctx_data_add,
.B ub_ctx_data_remove
\- Unbound DNS validating resolver @version@ functions.
.SH "SYNOPSIS"
.B #include <unbound.h>
.LP
\fIstruct ub_ctx *\fR
\fBub_ctx_create\fR(\fIvoid\fR);
.LP
\fIvoid\fR
\fBub_ctx_delete\fR(\fIstruct ub_ctx*\fR ctx);
.LP
\fIint\fR
\fBub_ctx_set_option\fR(\fIstruct ub_ctx*\fR ctx, \fIchar*\fR opt, \fIchar*\fR val);
.LP
\fIint\fR
\fBub_ctx_get_option\fR(\fIstruct ub_ctx*\fR ctx, \fIchar*\fR opt, \fIchar**\fR val);
.LP
\fIint\fR
\fBub_ctx_config\fR(\fIstruct ub_ctx*\fR ctx, \fIchar*\fR fname);
.LP
\fIint\fR
\fBub_ctx_set_fwd\fR(\fIstruct ub_ctx*\fR ctx, \fIchar*\fR addr);
.LP
\fIint\fR
\fBub_ctx_resolvconf\fR(\fIstruct ub_ctx*\fR ctx, \fIchar*\fR fname);
.LP
\fIint\fR
\fBub_ctx_hosts\fR(\fIstruct ub_ctx*\fR ctx, \fIchar*\fR fname);
.LP
\fIint\fR
\fBub_ctx_add_ta\fR(\fIstruct ub_ctx*\fR ctx, \fIchar*\fR ta);
.LP
\fIint\fR
\fBub_ctx_add_ta_file\fR(\fIstruct ub_ctx*\fR ctx, \fIchar*\fR fname);
.LP
\fIint\fR
\fBub_ctx_trustedkeys\fR(\fIstruct ub_ctx*\fR ctx, \fIchar*\fR fname);
.LP
\fIint\fR
\fBub_ctx_debugout\fR(\fIstruct ub_ctx*\fR ctx, \fIFILE*\fR out);
.LP
\fIint\fR
\fBub_ctx_debuglevel\fR(\fIstruct ub_ctx*\fR ctx, \fIint\fR d);
.LP
\fIint\fR
\fBub_ctx_async\fR(\fIstruct ub_ctx*\fR ctx, \fIint\fR dothread);
.LP
\fIint\fR
\fBub_poll\fR(\fIstruct ub_ctx*\fR ctx);
.LP
\fIint\fR
\fBub_wait\fR(\fIstruct ub_ctx*\fR ctx);
.LP
\fIint\fR
\fBub_fd\fR(\fIstruct ub_ctx*\fR ctx);
.LP
\fIint\fR
\fBub_process\fR(\fIstruct ub_ctx*\fR ctx);
.LP
\fIint\fR
\fBub_resolve\fR(\fIstruct ub_ctx*\fR ctx, \fIchar*\fR name,
.br
\fIint\fR rrtype, \fIint\fR rrclass, \fIstruct ub_result**\fR result);
.LP
\fIint\fR
\fBub_resolve_async\fR(\fIstruct ub_ctx*\fR ctx, \fIchar*\fR name,
.br
\fIint\fR rrtype, \fIint\fR rrclass, \fIvoid*\fR mydata,
.br
\fIub_callback_t\fR callback, \fIint*\fR async_id);
.LP
\fIint\fR
\fBub_cancel\fR(\fIstruct ub_ctx*\fR ctx, \fIint\fR async_id);
.LP
\fIvoid\fR
\fBub_resolve_free\fR(\fIstruct ub_result*\fR result);
.LP
\fIconst char *\fR
\fBub_strerror\fR(\fIint\fR err);
.LP
\fIint\fR
\fBub_ctx_print_local_zones\fR(\fIstruct ub_ctx*\fR ctx);
.LP
\fIint\fR
\fBub_ctx_zone_add\fR(\fIstruct ub_ctx*\fR ctx, \fIchar*\fR zone_name, \fIchar*\fR zone_type);
.LP
\fIint\fR
\fBub_ctx_zone_remove\fR(\fIstruct ub_ctx*\fR ctx, \fIchar*\fR zone_name);
.LP
\fIint\fR
\fBub_ctx_data_add\fR(\fIstruct ub_ctx*\fR ctx, \fIchar*\fR data);
.LP
\fIint\fR
\fBub_ctx_data_remove\fR(\fIstruct ub_ctx*\fR ctx, \fIchar*\fR data);
.SH "DESCRIPTION"
.B Unbound
is an implementation of a DNS resolver, that does caching and
DNSSEC validation. This is the library API, for using the \-lunbound library.
The server daemon is described in \fIunbound\fR(8).
The library can be used to convert hostnames to ip addresses, and back,
and obtain other information from the DNS. The library performs public\-key
validation of results with DNSSEC.
.P
The library uses a variable of type \fIstruct ub_ctx\fR to keep context
between calls. The user must maintain it, creating it with
.B ub_ctx_create
and deleting it with
.B ub_ctx_delete\fR.
It can be created and deleted at any time. Creating it anew removes any
previous configuration (such as trusted keys) and clears any cached results.
.P
The functions are thread\-safe, and a context an be used in a threaded (as
well as in a non\-threaded) environment. Also resolution (and validation)
can be performed blocking and non\-blocking (also called asynchronous).
The async method returns from the call immediately, so that processing
can go on, while the results become available later.
.P
The functions are discussed in turn below.
.SH "FUNCTIONS"
.TP
.B ub_ctx_create
Create a new context, initialised with defaults.
The information from /etc/resolv.conf and /etc/hosts is not utilised
by default. Use
.B ub_ctx_resolvconf
and
.B ub_ctx_hosts
to read them.
Before you call this, use the openssl functions CRYPTO_set_id_callback and
CRYPTO_set_locking_callback to set up asyncronous operation if you use
lib openssl (the application calls these functions once for initialisation).
.TP
.B ub_ctx_delete
Delete validation context and free associated resources.
Outstanding async queries are killed and callbacks are not called for them.
.TP
.B ub_ctx_set_option
A power\-user interface that lets you specify one of the options from the
config file format, see \fIunbound.conf\fR(5). Not all options are
relevant. For some specific options, such as adding trust anchors, special
routines exist. Pass the option name with the trailing ':'.
.TP
.B ub_ctx_get_option
A power\-user interface that gets an option value. Some options cannot be
gotten, and others return a newline separated list. Pass the option name
without trailing ':'. The returned value must be free(2)d by the caller.
.TP
.B ub_ctx_config
A power\-user interface that lets you specify an unbound config file, see
\fIunbound.conf\fR(5), which is read for configuration. Not all options are
relevant. For some specific options, such as adding trust anchors, special
routines exist.
.TP
.B ub_ctx_set_fwd
Set machine to forward DNS queries to, the caching resolver to use.
IP4 or IP6 address. Forwards all DNS requests to that machine, which
is expected to run a recursive resolver. If the proxy is not
DNSSEC capable, validation may fail. Can be called several times, in
that case the addresses are used as backup servers.
At this time it is only possible to set configuration before the
first resolve is done.
.TP
.B ub_ctx_resolvconf
By default the root servers are queried and full resolver mode is used, but
you can use this call to read the list of nameservers to use from the
filename given.
Usually "/etc/resolv.conf". Uses those nameservers as caching proxies.
If they do not support DNSSEC, validation may fail.
Only nameservers are picked up, the searchdomain, ndots and other
settings from \fIresolv.conf\fR(5) are ignored.
If fname NULL is passed, "/etc/resolv.conf" is used (if on Windows,
the system\-wide configured nameserver is picked instead).
At this time it is only possible to set configuration before the
first resolve is done.
.TP
.B ub_ctx_hosts
Read list of hosts from the filename given.
Usually "/etc/hosts". When queried for, these addresses are not marked
DNSSEC secure. If fname NULL is passed, "/etc/hosts" is used
(if on Windows, etc/hosts from WINDIR is picked instead).
At this time it is only possible to set configuration before the
first resolve is done.
.TP
.B
ub_ctx_add_ta
Add a trust anchor to the given context.
At this time it is only possible to add trusted keys before the
first resolve is done.
The format is a string, similar to the zone\-file format,
[domainname] [type] [rdata contents]. Both DS and DNSKEY records are accepted.
.TP
.B ub_ctx_add_ta_file
Add trust anchors to the given context.
Pass name of a file with DS and DNSKEY records in zone file format.
At this time it is only possible to add trusted keys before the
first resolve is done.
.TP
.B ub_ctx_trustedkeys
Add trust anchors to the given context.
Pass the name of a bind\-style config file with trusted\-keys{}.
At this time it is only possible to add trusted keys before the
first resolve is done.
.TP
.B ub_ctx_debugout
Set debug and error log output to the given stream. Pass NULL to disable
output. Default is stderr. File\-names or using syslog can be enabled
using config options, this routine is for using your own stream.
.TP
.B ub_ctx_debuglevel
Set debug verbosity for the context. Output is directed to stderr.
Higher debug level gives more output.
.TP
.B ub_ctx_async
Set a context behaviour for asynchronous action.
if set to true, enables threading and a call to
.B ub_resolve_async
creates a thread to handle work in the background.
If false, a process is forked to handle work in the background.
Changes to this setting after
.B ub_resolve_async
calls have been made have no effect (delete and re\-create the context
to change).
.TP
.B ub_poll
Poll a context to see if it has any new results.
Do not poll in a loop, instead extract the fd below to poll for readiness,
and then check, or wait using the wait routine.
Returns 0 if nothing to read, or nonzero if a result is available.
If nonzero, call
.B ub_process
to do callbacks.
.TP
.B ub_wait
Wait for a context to finish with results. Calls
.B ub_process
after the wait for you. After the wait, there are no more outstanding
asynchronous queries.
.TP
.B ub_fd
Get file descriptor. Wait for it to become readable, at this point
answers are returned from the asynchronous validating resolver.
Then call the \fBub_process\fR to continue processing.
.TP
.B ub_process
Call this routine to continue processing results from the validating
resolver (when the fd becomes readable).
Will perform necessary callbacks.
.TP
.B ub_resolve
Perform resolution and validation of the target name.
The name is a domain name in a zero terminated text string.
The rrtype and rrclass are DNS type and class codes.
The result structure is newly allocated with the resulting data.
.TP
.B ub_resolve_async
Perform asynchronous resolution and validation of the target name.
Arguments mean the same as for \fBub_resolve\fR except no
data is returned immediately, instead a callback is called later.
The callback receives a copy of the mydata pointer, that you can use to pass
information to the callback. The callback type is a function pointer to
a function declared as
.IP
void my_callback_function(void* my_arg, int err,
.br
struct ub_result* result);
.IP
The async_id is returned so you can (at your option) decide to track it
and cancel the request if needed. If you pass a NULL pointer the async_id
is not returned.
.TP
.B ub_cancel
Cancel an async query in progress. This may return an error if the query
does not exist, or the query is already being delivered, in that case you
may still get a callback for the query.
.TP
.B ub_resolve_free
Free struct ub_result contents after use.
.TP
.B ub_strerror
Convert error value from one of the unbound library functions
to a human readable string.
.TP
.B ub_ctx_print_local_zones
Debug printout the local authority information to debug output.
.TP
.B ub_ctx_zone_add
Add new zone to local authority info, like local\-zone \fIunbound.conf\fR(5)
statement.
.TP
.B ub_ctx_zone_remove
Delete zone from local authority info.
.TP
.B ub_ctx_data_add
Add resource record data to local authority info, like local\-data
\fIunbound.conf\fR(5) statement.
.TP
.B ub_ctx_data_remove
Delete local authority data from the name given.
.SH "RESULT DATA STRUCTURE"
The result of the DNS resolution and validation is returned as
\fIstruct ub_result\fR. The result structure contains the following entries.
.P
.nf
struct ub_result {
char* qname; /* text string, original question */
int qtype; /* type code asked for */
int qclass; /* class code asked for */
char** data; /* array of rdata items, NULL terminated*/
int* len; /* array with lengths of rdata items */
char* canonname; /* canonical name of result */
int rcode; /* additional error code in case of no data */
void* answer_packet; /* full network format answer packet */
int answer_len; /* length of packet in octets */
int havedata; /* true if there is data */
int nxdomain; /* true if nodata because name does not exist */
int secure; /* true if result is secure */
int bogus; /* true if a security failure happened */
char* why_bogus; /* string with error if bogus */
int ttl; /* number of seconds the result is valid */
};
.fi
.P
If both secure and bogus are false, security was not enabled for the
domain of the query. Else, they are not both true, one of them is true.
.SH "RETURN VALUES"
Many routines return an error code. The value 0 (zero) denotes no error
happened. Other values can be passed to
.B ub_strerror
to obtain a readable error string.
.B ub_strerror
returns a zero terminated string.
.B ub_ctx_create
returns NULL on an error (a malloc failure).
.B ub_poll
returns true if some information may be available, false otherwise.
.B ub_fd
returns a file descriptor or \-1 on error.
.SH "SEE ALSO"
\fIunbound.conf\fR(5),
\fIunbound\fR(8).
.SH "AUTHORS"
.B Unbound
developers are mentioned in the CREDITS file in the distribution.

294
external/unbound/doc/requirements.txt vendored Normal file
View File

@ -0,0 +1,294 @@
Requirements for Recursive Caching Resolver
(a.k.a. Treeshrew, Unbound-C)
By W.C.A. Wijngaards, NLnet Labs, October 2006.
Contents
1. Introduction
2. History
3. Goals
4. Non-Goals
1. Introduction
---------------
This is the requirements document for a DNS name server and aims to
document the goals and non-goals of the project. The DNS (the Domain
Name System) is a global, replicated database that uses a hierarchical
structure for queries.
Data in the DNS is stored in Resource Record sets (RR sets), and has a
time to live (TTL). During this time the data can be cached. It is
thus useful to cache data to speed up future lookups. A server that
looks up data in the DNS for clients and caches previous answers to
speed up processing is called a caching, recursive nameserver.
This project aims to develop such a nameserver in modular components, so
that also DNSSEC (secure DNS) validation and stub-resolvers (that do not
run as a server, but a linked into an application) are easily possible.
The main components are the Validator that validates the security
fingerprints on data sets, the Iterator that sends queries to the
hierarchical DNS servers that own the data and the Cache that stores
data from previous queries. The networking and query management code
then interface with the modules to perform the necessary processing.
In Section 2 the origins of the Unbound project are documented. Section
3 lists the goals, while Section 4 lists the explicit non-goals of the
project. Section 5 discusses choices made during development.
2. History
----------
The unbound resolver project started by Bill Manning, David Blacka, and
Matt Larson (from the University of California and from Verisign), that
created a Java based prototype resolver called Unbound. The basic
design decisions of clean modules was executed.
The Java prototype worked very well, with contributions from Geoff
Sisson and Roy Arends from Nominet. Around 2006 the idea came to create
a full-fledged C implementation ready for deployed use. NLnet Labs
volunteered to write this implementation.
3. Goals
--------
o A validating recursive DNS resolver.
o Code diversity in the DNS resolver monoculture.
o Drop-in replacement for BIND apart from config.
o DNSSEC support.
o Fully RFC compliant.
o High performance
* even with validation.
o Used as
* stub resolver.
* full caching name server.
* resolver library.
o Elegant design of validator, resolver, cache modules.
* provide the ability to pick and choose modules.
o Robust.
o In C, open source: The BSD license.
o Highly portable, targets include modern Unix systems, such as *BSD,
solaris, linux, and maybe also the windows platform.
o Smallest as possible component that does the job.
o Stub-zones can be configured (local data or AS112 zones).
4. Non-Goals
------------
o An authoritative name server.
o Too many Features.
5. Choices
----------
o rfc2181 decourages duplicates RRs in RRsets. unbound does not create
duplicates, but when presented with duplicates on the wire from the
authoritative servers, does not perform duplicate removal.
It does do some rrsig duplicate removal, in the msgparser, for dnssec qtype
rrsig and any, because of special rrsig processing in the msgparser.
o The harden-glue feature, when yes all out of zone glue is deleted, when
no out of zone glue is used for further resolving, is more complicated
than that, see below.
Main points:
* rfc2182 trust handling is used.
* data is let through only in very specific cases
* spoofability remains possible.
Not all glue is let through (despite the name of the option). Only glue
which is present in a delegation, of type A and AAAA, where the name is
present in the NS record in the authority section is let through.
The glue that is let through is stored in the cache (marked as 'from the
additional section'). And will then be used for sending queries to. It
will not be present in the reply to the client (if RD is off).
A direct query for that name will attempt to get a msg into the message
cache. Since A and AAAA queries are not synthesized by the unbound cache,
this query will be (eventually) sent to the authoritative server and its
answer will be put in the cache, marked as 'from the answer section' and
thus remove the 'from the additional section' data, and this record is
returned to the client.
The message has a TTL smaller or equal to the TTL of the answer RR.
If the cache memory is low; the answer RR may be dropped, and a glue
RR may be inserted, within the message TTL time, and thus return the
spoofed glue to a client. When the message expires, it is refetched and
the cached RR is updated with the correct content.
The server can be spoofed by getting it to visit a especially prepared
domain. This domain then inserts an address for another authoritative
server into the cache, when visiting that other domain, this address may
then be used to send queries to. And fake answers may be returned.
If the other domain is signed by DNSSEC, the fakes will be detected.
In summary, the harden glue feature presents a security risk if
disabled. Disabling the feature leads to possible better performance
as more glue is present for the recursive service to use. The feature
is implemented so as to minimise the security risk, while trying to
keep this performance gain.
o The method by which dnssec-lameness is detected is not secure. DNSSEC lame
is when a server has the zone in question, but lacks dnssec data, such as
signatures. The method to detect dnssec lameness looks at nonvalidated
data from the parent of a zone. This can be used, by spoofing the parent,
to create a false sense of dnssec-lameness in the child, or a false sense
or dnssec-non-lameness in the child. The first results in the server marked
lame, and not used for 900 seconds, and the second will result in a
validator failure (SERVFAIL again), when the query is validated later on.
Concluding, a spoof of the parent delegation can be used for many cases
of denial of service. I.e. a completely different NS set could be returned,
or the information withheld. All of these alterations can be caught by
the validator if the parent is signed, and result in 900 seconds bogus.
The dnssec-lameness detection is used to detect operator failures,
before the validator will properly verify the messages.
Also for zones for which no chain of trust exists, but a DS is given by the
parent, dnssec-lameness detection enables. This delivers dnssec to our
clients when possible (for client validators).
The following issue needs to be resolved:
a server that serves both a parent and child zone, where
parent is signed, but child is not. The server must not be marked
lame for the parent zone, because the child answer is not signed.
Instead of a false positive, we want false negatives; failure to
detect dnssec-lameness is less of a problem than marking honest
servers lame. dnssec-lameness is a config error and deserves the trouble.
So, only messages that identify the zone are used to mark the zone
lame. The zone is identified by SOA or NS RRsets in the answer/auth.
That includes almost all negative responses and also A, AAAA qtypes.
That would be most responses from servers.
For referrals, delegations that add a single label can be checked to be
from their zone, this covers most delegation-centric zones.
So possibly, for complicated setups, with multiple (parent-child) zones
on a server, dnssec-lameness detection does not work - no dnssec-lameness
is detected. Instead the zone that is dnssec-lame becomes bogus.
o authority features.
This is a recursive server, and authority features are out of scope.
However, some authority features are expected in a recursor. Things like
localhost, reverse lookup for 127.0.0.1, or blocking AS112 traffic.
Also redirection of domain names with fixed data is needed by service
providers. Limited support is added specifically to address this.
Adding full authority support, requires much more code, and more complex
maintenance.
The limited support allows adding some static data (for localhost and so),
and to respond with a fixed rcode (NXDOMAIN) for domains (such as AS112).
You can put authority data on a separate server, and set the server in
unbound.conf as stub for those zones, this allows clients to access data
from the server without making unbound authoritative for the zones.
o the access control denies queries before any other processing.
This denies queries that are not authoritative, or version.bind, or any.
And thus prevents cache-snooping (denied hosts cannot make non-recursive
queries and get answers from the cache).
o If a client makes a query without RD bit, in the case of a returned
message from cache which is:
answer section: empty
auth section: NS record present, no SOA record, no DS record,
maybe NSEC or NSEC3 records present.
additional: A records or other relevant records.
A SOA record would indicate that this was a NODATA answer.
A DS records would indicate a referral.
Absence of NS record would indicate a NODATA answer as well.
Then the receiver does not know whether this was a referral
with attempt at no-DS proof) or a nodata answer with attempt
at no-data proof. It could be determined by attempting to prove
either condition; and looking if only one is valid, but both
proofs could be valid, or neither could be valid, which creates
doubt. This case is validated by unbound as a 'referral' which
ascertains that RRSIGs are OK (and not omitted), but does not
check NSEC/NSEC3.
o Case preservation
Unbound preserves the casing received from authority servers as best
as possible. It compresses without case, so case can get lost there.
The casing from the query name is used in preference to the casing
of the authority server. This is the same as BIND. RFC4343 allows either
behaviour.
o Denial of service protection
If many queries are made, and they are made to names for which the
authority servers do not respond, then the requestlist for unbound
fills up fast. This results in denial of service for new queries.
To combat this the first 50% of the requestlist can run to completion.
The last 50% of the requestlist get (200 msec) at least and are replaced
by newer queries when older (LIFO).
When a new query comes in, and a place in the first 50% is available, this
is preferred. Otherwise, it can replace older queries out of the last 50%.
Thus, even long queries get a 50% chance to be resolved. And many 'short'
one or two round-trip resolves can be done in the last 50% of the list.
The timeout can be configured.
o EDNS fallback. Is done according to the EDNS RFC (and update draft-00).
Unbound assumes EDNS 0 support for the first query. Then it can detect
support (if the servers replies) or non-support (on a NOTIMPL or FORMERR).
Some middleboxes drop EDNS 0 queries, mainly when forwarding, not when
routing packets. To detect this, when timeouts keep happening, as the
timeout approached 5-10 seconds, and EDNS status has not been detected yet,
a single probe query is sent. This probe has a sub-second timeout, and
if the server responds (quickly) without EDNS, this is cached for 15 min.
This works very well when detecting an address that you use much - like
a forwarder address - which is where the middleboxes need to be detected.
Otherwise, it results in a 5 second wait time before EDNS timeout is
detected, which is slow but it works at least.
It minimizes the chances of a dropped query making a (DNSSEC) EDNS server
falsely EDNS-nonsupporting, and thus DNSSEC-bogus, works well with
middleboxes, and can detect the occasional authority that drops EDNS.
For some boxes it is necessary to probe for every failing query, a
reassurance that the DNS server does EDNS does not mean that path can
take large DNS answers.
o 0x20 backoff.
The draft describes to back off to the next server, and go through all
servers several times. Unbound goes on get the full list of nameserver
addresses, and then makes 3 * number of addresses queries.
They are sent to a random server, but no one address more than 4 times.
It succeeds if one has 0x20 intact, or else all are equal.
Otherwise, servfail is returned to the client.
o NXDOMAIN and SOA serial numbers.
Unbound keeps TTL values for message formats, and thus rcodes, such
as NXDOMAIN. Also it keeps the latest rrsets in the rrset cache.
So it will faithfully negative cache for the exact TTL as originally
specified for an NXDOMAIN message, but send a newer SOA record if
this has been found in the mean time. In point, this could lead to a
negative cached NXDOMAIN reply with a SOA RR where the serial number
indicates a zone version where this domain is not any longer NXDOMAIN.
These situations become consistent once the original TTL expires.
If the domain is DNSSEC signed, by the way, then NSEC records are
updated more carefully. If one of the NSEC records in an NXDOMAIN is
updated from another query, the NXDOMAIN is dropped from the cache,
and queried for again, so that its proof can be checked again.
o SOA records in negative cached answers for DS queries.
The current unbound code uses a negative cache for queries for type DS.
This speeds up building chains of trust, and uses NSEC and NSEC3
(optout) information to speed up lookups. When used internally,
the bare NSEC(3) information is sufficient, probably picked up from
a referral. When answering to clients, a SOA record is needed for
the correct message format, a SOA record is picked from the cache
(and may not actually match the serial number of the SOA for which the
NSEC and NSEC3 records were obtained) if available otherwise network
queries are performed to get the data.
o Parent and child with different nameserver information.
A misconfiguration that sometimes happens is where the parent and child
have different NS, glue information. The child is authoritative, and
unbound will not trust information from the parent nameservers as the
final answer. To help lookups, unbound will however use the parent-side
version of the glue as a last resort lookup. This resolves lookups for
those misconfigured domains where the servers reported by the parent
are the only ones working, and servers reported by the child do not.
o Failure of validation and probing.
Retries on a validation failure are now 5x to a different nameserver IP
(if possible), and then it gives up, for one name, type, class entry in
the message cache. If a DNSKEY or DS fails in the chain of trust in the
key cache additionally, after the probing, a bad key entry is created that
makes the entire zone bogus for 900 seconds. This is a fixed value at
this time and is conservative in sending probes. It makes the compound
effect of many resolvers less and easier to handle, but penalizes
individual resolvers by having less probes and a longer time before fixes
are picked up.

175
external/unbound/doc/unbound-anchor.8.in vendored Normal file
View File

@ -0,0 +1,175 @@
.TH "unbound-anchor" "8" "@date@" "NLnet Labs" "unbound @version@"
.\"
.\" unbound-anchor.8 -- unbound anchor maintenance utility manual
.\"
.\" Copyright (c) 2008, NLnet Labs. All rights reserved.
.\"
.\" See LICENSE for the license.
.\"
.\"
.SH "NAME"
.B unbound\-anchor
\- Unbound anchor utility.
.SH "SYNOPSIS"
.B unbound\-anchor
.RB [ opts ]
.SH "DESCRIPTION"
.B Unbound\-anchor
performs setup or update of the root trust anchor for DNSSEC validation.
It can be run (as root) from the commandline, or run as part of startup
scripts. Before you start the \fIunbound\fR(8) DNS server.
.P
Suggested usage:
.P
.nf
# in the init scripts.
# provide or update the root anchor (if necessary)
unbound-anchor -a "@UNBOUND_ROOTKEY_FILE@"
# Please note usage of this root anchor is at your own risk
# and under the terms of our LICENSE (see source).
#
# start validating resolver
# the unbound.conf contains:
# auto-trust-anchor-file: "@UNBOUND_ROOTKEY_FILE@"
unbound -c unbound.conf
.fi
.P
This tool provides builtin default contents for the root anchor and root
update certificate files.
.P
It tests if the root anchor file works, and if not, and an update is possible,
attempts to update the root anchor using the root update certificate.
It performs a https fetch of root-anchors.xml and checks the results, if
all checks are successful, it updates the root anchor file. Otherwise
the root anchor file is unchanged. It performs RFC5011 tracking if the
DNSSEC information available via the DNS makes that possible.
.P
It does not perform an update if the certificate is expired, if the network
is down or other errors occur.
.P
The available options are:
.TP
.B \-a \fIfile
The root anchor key file, that is read in and written out.
Default is @UNBOUND_ROOTKEY_FILE@.
If the file does not exist, or is empty, a builtin root key is written to it.
.TP
.B \-c \fIfile
The root update certificate file, that is read in.
Default is @UNBOUND_ROOTCERT_FILE@.
If the file does not exist, or is empty, a builtin certificate is used.
.TP
.B \-l
List the builtin root key and builtin root update certificate on stdout.
.TP
.B \-u \fIname
The server name, it connects to https://name. Specify without https:// prefix.
The default is "data.iana.org". It connects to the port specified with \-P.
You can pass an IPv4 addres or IPv6 address (no brackets) if you want.
.TP
.B \-x \fIpath
The pathname to the root\-anchors.xml file on the server. (forms URL with \-u).
The default is /root\-anchors/root\-anchors.xml.
.TP
.B \-s \fIpath
The pathname to the root\-anchors.p7s file on the server. (forms URL with \-u).
The default is /root\-anchors/root\-anchors.p7s. This file has to be a PKCS7
signature over the xml file, using the pem file (\-c) as trust anchor.
.TP
.B \-n \fIname
The emailAddress for the Subject of the signer's certificate from the p7s
signature file. Only signatures from this name are allowed. default is
dnssec@iana.org. If you pass "" then the emailAddress is not checked.
.TP
.B \-4
Use IPv4 for domain resolution and contacting the server on https. Default is
to use IPv4 and IPv6 where appropriate.
.TP
.B \-6
Use IPv6 for domain resolution and contacting the server on https. Default is
to use IPv4 and IPv6 where appropriate.
.TP
.B \-f \fIresolv.conf
Use the given resolv.conf file. Not enabled by default, but you could try to
pass /etc/resolv.conf on some systems. It contains the IP addresses of the
recursive nameservers to use. However, since this tool could be used to
bootstrap that very recursive nameserver, it would not be useful (since
that server is not up yet, since we are bootstrapping it). It could be
useful in a situation where you know an upstream cache is deployed (and
running) and in captive portal situations.
.TP
.B \-r \fIroot.hints
Use the given root.hints file (same syntax as the BIND and Unbound root hints
file) to bootstrap domain resolution. By default a list of builtin root
hints is used. Unbound\-anchor goes to the network itself for these roots,
to resolve the server (\-u option) and to check the root DNSKEY records.
It does so, because the tool when used for bootstrapping the recursive
resolver, cannot use that recursive resolver itself because it is bootstrapping
that server.
.TP
.B \-v
More verbose. Once prints informational messages, multiple times may enable
large debug amounts (such as full certificates or byte\-dumps of downloaded
files). By default it prints almost nothing. It also prints nothing on
errors by default; in that case the original root anchor file is simply
left undisturbed, so that a recursive server can start right after it.
.TP
.B \-C \fIunbound.conf
Debug option to read unbound.conf into the resolver process used.
.TP
.B \-P \fIport
Set the port number to use for the https connection. The default is 443.
.TP
.B \-F
Debug option to force update of the root anchor through downloading the xml
file and verifying it with the certificate. By default it first tries to
update by contacting the DNS, which uses much less bandwidth, is much
faster (200 msec not 2 sec), and is nicer to the deployed infrastructure.
With this option, it still attempts to do so (and may verbosely tell you),
but then ignores the result and goes on to use the xml fallback method.
.TP
.B \-h
Show the version and commandline option help.
.SH "EXIT CODE"
This tool exits with value 1 if the root anchor was updated using the
certificate or if the builtin root-anchor was used. It exits with code
0 if no update was necessary, if the update was possible with RFC5011
tracking, or if an error occurred.
.P
You can check the exit value in this manner:
.nf
unbound-anchor -a "root.key" || logger "Please check root.key"
.fi
Or something more suitable for your operational environment.
.SH "TRUST"
The root keys and update certificate included in this tool
are provided for convenience and under the terms of our
license (see the LICENSE file in the source distribution or
http://unbound.nlnetlabs.nl/svn/trunk/LICENSE) and might be stale or
not suitable to your purpose.
.P
By running "unbound\-anchor \-l" the keys and certificate that are
configured in the code are printed for your convenience.
.P
The build\-in configuration can be overridden by providing a root\-cert
file and a rootkey file.
.SH "FILES"
.TP
.I @UNBOUND_ROOTKEY_FILE@
The root anchor file, updated with 5011 tracking, and read and written to.
The file is created if it does not exist.
.TP
.I @UNBOUND_ROOTCERT_FILE@
The trusted self\-signed certificate that is used to verify the downloaded
DNSSEC root trust anchor. You can update it by fetching it from
https://data.iana.org/root\-anchors/icannbundle.pem (and validate it).
If the file does not exist or is empty, a builtin version is used.
.TP
.I https://data.iana.org/root\-anchors/root\-anchors.xml
Source for the root key information.
.TP
.I https://data.iana.org/root\-anchors/root\-anchors.p7s
Signature on the root key information.
.SH "SEE ALSO"
\fIunbound.conf\fR(5),
\fIunbound\fR(8).

Some files were not shown because too many files have changed in this diff Show More